content
stringlengths 5
1.05M
|
---|
-- Plugins and modifications to the core text editing
-- experience, and isn't that really why we're here in
-- the first place?
local function setup()
vim.cmd([[
packadd nvim-autopairs
packadd nvim-comment
]])
require('nvim_comment').setup {
marker_padding = true,
comment_empty = true,
}
vim.opt.completeopt = 'menuone,noinsert,noselect'
require('nvim-autopairs').setup {
disable_filetype = { 'TelescopePrompt' },
}
local ap = require('nvim-autopairs.completion.cmp')
local cmp = require('cmp')
cmp.event:on('confirm_done', ap.on_confirm_done({ map_char = { tex = '' }}))
end
return { setup = setup }
|
-- version
set_xmakever("2.2.5")
-- set warning all as error
set_warnings("all", "error")
-- set language: c99, c++11
set_languages("c99", "cxx11")
-- disable some compiler errors
add_cxflags("-Wno-error=deprecated-declarations", "-fno-strict-aliasing")
add_mxflags("-Wno-error=deprecated-declarations", "-fno-strict-aliasing")
-- the debug mode
if is_mode("debug") then
-- enable the debug symbols
set_symbols("debug")
-- disable optimization
set_optimize("none")
-- add defines for debug
add_defines("__tb_debug__")
end
-- the release mode
if is_mode("release") then
-- set the symbols visibility: hidden
set_symbols("hidden")
-- strip all symbols
set_strip("all")
-- enable fastest optimization
set_optimize("fastest")
end
-- for the windows platform (msvc)
if is_plat("windows") then
-- the release mode
if is_mode("release") then
-- link libcmt.lib
add_cxflags("-MT")
-- the debug mode
elseif is_mode("debug") then
-- link libcmtd.lib
add_cxflags("-MTd")
end
-- no msvcrt.lib
add_ldflags("-nodefaultlib:msvcrt.lib")
end
-- add syslinks
if is_plat("windows") then add_syslinks("ws2_32")
elseif is_plat("android") then add_syslinks("m", "c")
else add_syslinks("pthread", "dl", "m", "c") end
-- add requires
add_requires("tbox", {debug = is_mode("debug")})
-- include project sources
includes("src/${TARGETNAME}", "src/${TARGETNAME}_demo")
${FAQ}
|
-- Lua Library inline imports
function __TS__ObjectKeys(obj)
local result = {}
for key in pairs(obj) do
result[#result + 1] = key
end
return result
end
function __TS__ArrayForEach(arr, callbackFn)
do
local i = 0
while i < #arr do
callbackFn(_G, arr[i + 1], i, arr)
i = i + 1
end
end
end
function PassiveRegenOnTimer()
PassiveRegen:onTimer()
end
PassiveRegen = {
timerInterval = 2500,
fatigueMin = 0.9,
healthRate = 0.25,
healthBucket = 0,
healthRegenMax = 0.5,
magickaRate = 0.1,
magickaBucket = 0,
magickaRegenMax = 0.5,
regenTimerId = nil,
onTimer = function()
__TS__ArrayForEach(
__TS__ObjectKeys(Players),
function(____, pid)
local player = Players[pid]
if (player == nil) or (not player:IsLoggedIn()) then
return
end
local healthBase = player.data.stats.healthBase
local magickaBase = player.data.stats.magickaBase
local fatigueBase = player.data.stats.fatigueBase
local healthCurrent = tes3mp.GetHealthCurrent(pid)
local magickaCurrent = tes3mp.GetMagickaCurrent(pid)
local fatigueCurrent = tes3mp.GetFatigueCurrent(pid)
PassiveRegen.healthBucket = PassiveRegen.healthBucket + ((PassiveRegen.healthRate * PassiveRegen.timerInterval) * 0.001)
PassiveRegen.magickaBucket = PassiveRegen.magickaBucket + ((PassiveRegen.magickaRate * PassiveRegen.timerInterval) * 0.001)
local changed = false
if healthBase > 1 then
if fatigueCurrent > (fatigueBase * PassiveRegen.fatigueMin) then
if ((healthBase * PassiveRegen.healthRegenMax) > healthCurrent) and (PassiveRegen.healthBucket >= 1) then
player.data.stats.healthCurrent = healthCurrent + math.floor(PassiveRegen.healthBucket)
tes3mp.SetHealthCurrent(pid, player.data.stats.healthCurrent)
end
if ((magickaBase * PassiveRegen.magickaRegenMax) > magickaCurrent) and (PassiveRegen.magickaBucket >= 1) then
player.data.stats.magickaCurrent = magickaCurrent + math.floor(PassiveRegen.magickaBucket)
tes3mp.SetMagickaCurrent(pid, player.data.stats.magickaCurrent)
end
tes3mp.SendStatsDynamic(pid)
end
end
end
)
if PassiveRegen.healthBucket >= 1 then
PassiveRegen.healthBucket = PassiveRegen.healthBucket - math.floor(PassiveRegen.healthBucket)
end
if PassiveRegen.magickaBucket >= 1 then
PassiveRegen.magickaBucket = PassiveRegen.magickaBucket - math.floor(PassiveRegen.magickaBucket)
end
tes3mp.RestartTimer(PassiveRegen.regenTimerId, PassiveRegen.timerInterval)
end,
init = function()
PassiveRegen.regenTimerId = tes3mp.CreateTimer("PassiveRegenOnTimer", PassiveRegen.timerInterval)
tes3mp.StartTimer(PassiveRegen.regenTimerId)
end
}
PassiveRegen:init()
|
Socket,Address,Interface,Buffer =
require('t.Net.Socket'),require('t.Net.Address'),require('t.Net.Interface'),require('t.Buffer')
ipAddr = arg[1] and arg[1] or Interface.default( ).address.ip
port = arg[2] and arg[2] or 8888
udpsock = Socket( 'UDP' ) --implicit ip4
adr = Address( ipAddr, port )
udpsock:send( Buffer("This is my message to you\n"), adr, 15 ) -- send 15 bytes of Buffer to adr
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:28' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
ZO_SceneFragmentBar = ZO_Object:Subclass()
function ZO_SceneFragmentBar:New(...)
local object = ZO_Object.New(self)
object:Initialize(...)
return object
end
function ZO_SceneFragmentBar:Initialize(menuBar)
self.menuBar = menuBar
self.label = menuBar:GetNamedChild("Label")
self.buttonData = {}
end
function ZO_SceneFragmentBar:SelectFragment(name)
local SKIP_ANIMATIONS = true
ZO_MenuBar_SelectDescriptor(self.menuBar, name, SKIP_ANIMATIONS)
end
function ZO_SceneFragmentBar:SetStartingFragment(name)
self.lastFragmentName = name
end
function ZO_SceneFragmentBar:ShowLastFragment()
self:SelectFragment(self.lastFragmentName)
end
function ZO_SceneFragmentBar:GetLastFragment()
return self.lastFragmentName
end
function ZO_SceneFragmentBar:RemoveActiveKeybind()
local keybindButton = self.currentKeybindButton
self.currentKeybindButton = nil
if keybindButton then
if keybindButton.keybind then
KEYBIND_STRIP:RemoveKeybindButton(keybindButton)
else
KEYBIND_STRIP:RemoveKeybindButtonGroup(keybindButton)
end
end
end
function ZO_SceneFragmentBar:UpdateActiveKeybind()
if self.currentKeybindButton then
if self.currentKeybindButton.keybind then
KEYBIND_STRIP:UpdateKeybindButton(self.currentKeybindButton)
else
KEYBIND_STRIP:UpdateKeybindButtonGroup(self.currentKeybindButton)
end
end
end
function ZO_SceneFragmentBar:GetActiveKeybind()
return self.currentKeybindButton
end
function ZO_SceneFragmentBar:Clear()
ZO_MenuBar_ClearSelection(self.menuBar)
self:RemoveActiveKeybind()
--Removing the fragment bar fragments from the scene makes it so the scene does not care about when those fragments finish hiding for computing its own hidden state. Since this function is only called when the scene
--that owns this bar is hiding we can rely on the behavior where a hidden scene dumps all of its temporary fragments to handle this. If you call Clear at any other time it will not remove the temporary fragments
--added by the fragment bar.
end
function ZO_SceneFragmentBar:RemoveAll()
self:Clear()
ZO_MenuBar_ClearButtons(self.menuBar)
for _, buttonData in ipairs(self.buttonData) do
buttonData.callback = buttonData.existingCallback
end
self.buttonData = {}
end
function ZO_SceneFragmentBar:Add(name, fragmentGroup, buttonData, keybindButton)
buttonData.descriptor = name
buttonData.categoryName = name
buttonData.existingCallback = buttonData.callback
local existingCallback = buttonData.callback
buttonData.callback = function()
self:RemoveActiveKeybind()
if self.currentFragmentGroup then
SCENE_MANAGER:RemoveFragmentGroup(self.currentFragmentGroup)
end
self.currentFragmentGroup = fragmentGroup
self.currentKeybindButton = keybindButton
SCENE_MANAGER:AddFragmentGroup(fragmentGroup)
if keybindButton then
if keybindButton.keybind then
KEYBIND_STRIP:AddKeybindButton(keybindButton)
else
KEYBIND_STRIP:AddKeybindButtonGroup(keybindButton)
end
end
if self.label then
self.label:SetText(zo_strformat(SI_SCENE_FRAGMENT_BAR_TITLE, GetString(name)))
end
self.lastFragmentName = name
if existingCallback then
existingCallback()
end
end
ZO_MenuBar_AddButton(self.menuBar, buttonData)
table.insert(self.buttonData, buttonData)
end
function ZO_SceneFragmentBar:UpdateButtons(forceSelection)
ZO_MenuBar_UpdateButtons(self.menuBar, forceSelection)
end
|
Importer{version=1.00, format="Bancolombia 'Excel'", fileExtension="xls"}
local function strToDate (str)
-- Helper function for converting localized date strings to timestamps.
local y, m, d = string.match(str, "(%d%d%d%d)/(%d%d)/(%d%d)")
return os.time{year=y, month=m, day=d}
end
function ReadTransactions (account)
-- Read transactions from a file with the format "date<TAB>amount<TAB>purpose".
local transactions = {}
local linecount = 0
for line in assert(io.lines()) do
print(linecount)
if linecount ~= 0 then --ignore description
local values = {}
for value in string.gmatch(line, "[^\t]+") do
table.insert(values, value)
end
if #values >= 4 then
print(values[1], "-", values[2], "-", values[#values-1])
-- the description might have tabs, just grab the last value as amount
local amountString = values[#values-1]:gsub(",", "")
local transaction = {
bookingDate = strToDate(values[1]),
-- values[2] is empty
name = values[3],
purpose = values[4],
amount = tonumber(amountString),--tonumber gets confused by commas
currency = "COP"
}
print(tonumber(values[5]))
table.insert(transactions, transaction)
end
end
linecount = linecount + 1
end
return transactions
end
|
local strAllowedNumericCharacters = "1234567890.-"
DEFINE_BASECLASS("Panel")
--local baseEntry = baseclass.Get( "DTextEntry" )
local PANEL = {}
AccessorFunc(PANEL, "bDeleteSelf", "DeleteSelf", FORCE_BOOL)
AccessorFunc(PANEL, "m_characters", "Characters", FORCE_STRING)
PANEL.outlineRect = Color(204, 204, 204, 100)
function PANEL:Init()
surface.SetFont("ixMenuButtonFont")
local width, height = surface.GetTextSize("999999")
self.m_bIsMenuComponent = true
self.bDeleteSelf = true
self.realHeight = 200
self.height = 200
self:SetSize(width + 50, height)
self:DockPadding(4, 4, 4, 4)
self:SetCharacters(strAllowedNumericCharacters)
self.textEntry = self:Add("ixTextEntry")
self.textEntry:SetNumeric(true)
self.textEntry:SetAllowNonAsciiCharacters(false)
self.textEntry:SetFont("ixMenuButtonFont")
self.textEntry:SetCursorColor(color_white)
self.textEntry:Dock(FILL)
self.textEntry:RequestFocus()
self.textEntry.OnEnter = function()
self:Remove(true)
end
self.textEntry.Paint = function(t, w, h)
surface.SetDrawColor(90, 90, 90, 255)
surface.DrawRect(0, 0, w, h)
t:DrawTextEntryText(color_white, ix.config.Get("color"), color_white)
end
self.textEntry.CheckNumeric = function(t, strValue)
if ( !t:GetNumeric() ) then return false end
if ( !string.find( self.m_characters, strValue, 1, true ) ) then
return true
end
return false
end
self.textButton = self:Add("DButton")
self.textButton:SetFont("ixMenuButtonFont")
self.textButton:SetText("OK")
self.textButton:Dock(RIGHT)
self.textButton:SizeToContents()
self.textButton.Paint = function(t, w, h)
surface.SetDrawColor(color_black)
surface.DrawRect(0, 0, w, h)
surface.SetDrawColor(self.outlineRect)
surface.DrawOutlinedRect(0, 0, w, h, 1)
end
self.textButton.DoClick = function()
self:Remove(true)
end
self:MakePopup()
RegisterDermaMenuForClose(self)
end
function PANEL:SetValue(value, bInitial)
value = tostring(value)
self.textEntry:SetValue(value)
if (bInitial) then
self.textEntry:SetCaretPos(value:utf8len())
end
end
function PANEL:GetValue()
return tonumber(self.textEntry:GetValue()) or 0
end
function PANEL:Attach(panel)
self.attached = panel
end
function PANEL:Think()
local panel = self.attached
if (IsValid(panel)) then
local width, height = self:GetSize()
local x, y = panel:LocalToScreen(0, 0)
self:SetPos(
math.Clamp(x + panel:GetWide() - width, 0, ScrW() - width),
math.Clamp(y + panel:GetTall(), 0, ScrH() - height)
)
end
end
function PANEL:Paint(width, height)
surface.SetDrawColor(derma.GetColor("DarkerBackground", self))
surface.DrawRect(0, 0, width, height)
end
function PANEL:OnValueChanged()
end
function PANEL:Remove(valueChanged)
if (self.bClosing) then
return
end
if (valueChanged) then self:OnValueChanged() end
-- @todo open/close animations
self.bClosing = true
self:SetMouseInputEnabled(false)
self:SetKeyboardInputEnabled(false)
BaseClass.Remove(self)
end
vgui.Register("ixRowNumberEntry", PANEL, "EditablePanel")
-- Багфикс
PANEL = vgui.GetControlTable("DMenu")
function PANEL:SetFont(font)
for _, v in pairs(self:GetCanvas():GetChildren()) do
if (!v.SetFont) then continue end
v:SetFont(font or "DermaDefault")
v:SizeToContents()
end
-- reposition for the new font
self:InvalidateLayout(true)
self:Open(self.ixX, self.ixY, false, self.ixOwnerPanel)
end |
local E, L, V, P, G = unpack(select(2, ...)); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
local S = E:GetModule('Skins')
--Lua functions
local _G = _G
local unpack = unpack
--WoW API / Variables
local hooksecurefunc = hooksecurefunc
local function SkinOjectiveTrackerHeaders()
local frame = _G.ObjectiveTrackerFrame.MODULES
if frame then
for i = 1, #frame do
local modules = frame[i]
if modules then
modules.Header.Background:SetAtlas(nil)
local text = modules.Header.Text
text:FontTemplate()
text:SetParent(modules.Header)
end
end
end
end
local function ColorProgressBars(self, value)
if not (self.Bar and self.isSkinned and value) then return end
S:StatusBarColorGradient(self.Bar, value, 100)
end
local function SkinItemButton(_, block)
local item = block.itemButton
if item and not item.skinned then
item:Size(25, 25)
item:SetTemplate("Transparent")
item:StyleButton()
item:SetNormalTexture(nil)
item.icon:SetTexCoord(unpack(E.TexCoords))
item.icon:SetInside()
item.Cooldown:SetInside()
item.Count:ClearAllPoints()
item.Count:Point("TOPLEFT", 1, -1)
item.Count:FontTemplate(E.media.normFont, 14, "OUTLINE")
item.Count:SetShadowOffset(5, -5)
E:RegisterCooldown(item.Cooldown)
item.skinned = true
end
end
local function SkinProgressBars(_, _, line)
local progressBar = line and line.ProgressBar
local bar = progressBar and progressBar.Bar
if not bar then return end
local icon = bar.Icon
local label = bar.Label
if not progressBar.isSkinned then
if bar.BarFrame then bar.BarFrame:Hide() end
if bar.BarFrame2 then bar.BarFrame2:Hide() end
if bar.BarFrame3 then bar.BarFrame3:Hide() end
if bar.BarGlow then bar.BarGlow:Hide() end
if bar.Sheen then bar.Sheen:Hide() end
if bar.IconBG then bar.IconBG:SetAlpha(0) end
if bar.BorderLeft then bar.BorderLeft:SetAlpha(0) end
if bar.BorderRight then bar.BorderRight:SetAlpha(0) end
if bar.BorderMid then bar.BorderMid:SetAlpha(0) end
bar:Height(18)
bar:StripTextures()
bar:CreateBackdrop("Transparent")
bar:SetStatusBarTexture(E.media.normTex)
E:RegisterStatusBar(bar)
if label then
label:ClearAllPoints()
label:Point("CENTER", bar, 0, 1)
label:FontTemplate(E.media.normFont, 14, "OUTLINE")
end
if icon then
icon:ClearAllPoints()
icon:Point("LEFT", bar, "RIGHT", E.PixelMode and 3 or 7, 0)
icon:SetMask("")
icon:SetTexCoord(unpack(E.TexCoords))
if not progressBar.backdrop then
progressBar:CreateBackdrop()
progressBar.backdrop:SetOutside(icon)
progressBar.backdrop:SetShown(icon:IsShown())
end
end
_G.BonusObjectiveTrackerProgressBar_PlayFlareAnim = E.noop
progressBar.isSkinned = true
ColorProgressBars(progressBar, bar:GetValue())
elseif icon and progressBar.backdrop then
progressBar.backdrop:SetShown(icon:IsShown())
end
end
local function SkinTimerBars(_, _, line)
local timerBar = line and line.TimerBar
local bar = timerBar and timerBar.Bar
if not timerBar.isSkinned then
bar:Height(18)
bar:StripTextures()
bar:CreateBackdrop("Transparent")
bar:SetStatusBarTexture(E.media.normTex)
E:RegisterStatusBar(bar)
timerBar.isSkinned = true
end
end
local function PositionFindGroupButton(block, button)
if button and button.GetPoint then
local a, b, c, d, e = button:GetPoint()
if block.groupFinderButton and b == block.groupFinderButton and block.itemButton and button == block.itemButton then
-- this fires when there is a group button and a item button to the left of it
-- we push the item button away from the group button (to the left)
button:Point(a, b, c, d-(E.PixelMode and -1 or 1), e);
elseif b == block and block.groupFinderButton and button == block.groupFinderButton then
-- this fires when there is a group finder button
-- we push the group finder button down slightly
button:Point(a, b, c, d, e-(E.PixelMode and 2 or -1));
end
end
end
local function SkinFindGroupButton(block)
if block.hasGroupFinderButton and block.groupFinderButton then
if block.groupFinderButton and not block.groupFinderButton.skinned then
S:HandleButton(block.groupFinderButton)
block.groupFinderButton:Size(20)
block.groupFinderButton.skinned = true
end
end
end
local function LoadSkin()
if E.private.skins.blizzard.enable ~= true or E.private.skins.blizzard.objectiveTracker ~= true then return end
local ObjectiveTrackerFrame = _G.ObjectiveTrackerFrame
local minimizeButton = ObjectiveTrackerFrame.HeaderMenu.MinimizeButton
minimizeButton:StripTextures()
minimizeButton:Size(16, 16)
minimizeButton.tex = minimizeButton:CreateTexture(nil, "OVERLAY")
minimizeButton.tex:SetTexture(E.Media.Textures.MinusButton)
minimizeButton.tex:SetInside()
minimizeButton:SetHighlightTexture("Interface\\Buttons\\UI-PlusButton-Hilight", "ADD")
minimizeButton:HookScript("OnClick", function()
if ObjectiveTrackerFrame.collapsed then
minimizeButton.tex:SetTexture(E.Media.Textures.PlusButton)
else
minimizeButton.tex:SetTexture(E.Media.Textures.MinusButton)
end
end)
hooksecurefunc("ObjectiveTracker_Collapse", function()
if EuiAutoQuestButton then EuiAutoQuestButton:Hide(); end
end)
hooksecurefunc("ObjectiveTracker_Expand", function()
if EuiAutoQuestButton then EuiAutoQuestButton:Show(); end
end)
hooksecurefunc("BonusObjectiveTrackerProgressBar_SetValue",ColorProgressBars) --[Color]: Bonus Objective Progress Bar
hooksecurefunc("ObjectiveTrackerProgressBar_SetValue",ColorProgressBars) --[Color]: Quest Progress Bar
hooksecurefunc("ScenarioTrackerProgressBar_SetValue",ColorProgressBars) --[Color]: Scenario Progress Bar
hooksecurefunc("QuestObjectiveSetupBlockButton_AddRightButton",PositionFindGroupButton) --[Move]: The eye & quest item to the left of the eye
hooksecurefunc("ObjectiveTracker_Update",SkinOjectiveTrackerHeaders) --[Skin]: Module Headers
hooksecurefunc("QuestObjectiveSetupBlockButton_FindGroup",SkinFindGroupButton) --[Skin]: The eye
hooksecurefunc(_G.BONUS_OBJECTIVE_TRACKER_MODULE,"AddProgressBar",SkinProgressBars) --[Skin]: Bonus Objective Progress Bar
hooksecurefunc(_G.WORLD_QUEST_TRACKER_MODULE,"AddProgressBar",SkinProgressBars) --[Skin]: World Quest Progress Bar
hooksecurefunc(_G.DEFAULT_OBJECTIVE_TRACKER_MODULE,"AddProgressBar",SkinProgressBars) --[Skin]: Quest Progress Bar
hooksecurefunc(_G.SCENARIO_TRACKER_MODULE,"AddProgressBar",SkinProgressBars) --[Skin]: Scenario Progress Bar
hooksecurefunc(_G.QUEST_TRACKER_MODULE,"AddTimerBar",SkinTimerBars) --[Skin]: Quest Timer Bar
hooksecurefunc(_G.SCENARIO_TRACKER_MODULE,"AddTimerBar",SkinTimerBars) --[Skin]: Scenario Timer Bar
hooksecurefunc(_G.ACHIEVEMENT_TRACKER_MODULE,"AddTimerBar",SkinTimerBars) --[Skin]: Achievement Timer Bar
hooksecurefunc(_G.QUEST_TRACKER_MODULE,"SetBlockHeader",SkinItemButton) --[Skin]: Quest Item Buttons
hooksecurefunc(_G.WORLD_QUEST_TRACKER_MODULE,"AddObjective",SkinItemButton) --[Skin]: World Quest Item Buttons
end
S:AddCallback("ObjectiveTracker", LoadSkin)
|
-- This is a ROS enabled Hokuyo_04LX_UG01 model (although it can be used as a generic
-- ROS enabled laser scanner), based on the existing Hokuyo model. It performs instantaneous
-- scans and publishes ROS Laserscan msgs, along with the sensor's tf.
function sysCall_init()
laserHandle=sim.getObjectHandle("Hokuyo_URG_04LX_UG01_ROS_laser")
jointHandle=sim.getObjectHandle("Hokuyo_URG_04LX_UG01_ROS_joint")
modelRef=sim.getObjectHandle("Hokuyo_URG_04LX_UG01_ROS_ref")
modelHandle=sim.getObjectAssociatedWithScript(sim.handle_self)
objName=sim.getObjectName(modelHandle)
communicationTube=sim.tubeOpen(0,objName..'_HOKUYO',1)
scanRange=110*math.pi/180 --You can change the scan range. Angle_min=-scanRange/2, Angle_max=scanRange/2-stepSize
stepSize= 0.36*math.pi/180 --0.0063 --2*math.pi/1024
pts=math.floor(scanRange/stepSize)
dists={}
points={}
segments={}
for i=1,pts*3,1 do
table.insert(points,0)
end
for i=1,pts*7,1 do
table.insert(segments,0)
end
black={0,0,0}
red={1,0,0}
lines100=sim.addDrawingObject(sim.drawing_lines,1,0,-1,1000,black,black,black,red)
points100=sim.addDrawingObject(sim.drawing_points,4,0,-1,1000,black,black,black,red)
-- Check if the required plugin is there (libv_repExtRos.so or libv_repExtRos.dylib):
local moduleName=0
local moduleVersion=0
local index=0
local pluginNotFound=true
while moduleName do
moduleName,moduleVersion=sim.getModuleName(index)
if (moduleName=='RosInterface') then
pluginNotFound=false
end
index=index+1
end
if (pluginNotFound) then
-- Display an error message if the plugin was not found:
sim.displayDialog('Hokuyo_URG_04LX_UG01_ROS error','ROS plugin was not found.&&nSimulation will not run properly',sim.dlgstyle_ok,false,nil,{0.8,0,0,0,0,0},{0.5,0,0,1,1,1})
end
scanPub=simROS.advertise('/scan', 'sensor_msgs/LaserScan')
simROS.publisherTreatUInt8ArrayAsString(scanPub) -- treat uint8 arrays as strings (much faster, tables/arrays are kind of slow in Lua)
--topicName=simExtROS_enablePublisher('front_scan',1,simros_strmcmd_get_laser_scanner_data ,modelHandle,-1,'rangeDat'..objName)
--parentTf=sim.getObjectHandle("parentTf#") --get handle to parent object in tf tree. Change this to your needs
--tfPub=simROS.advertise('/laser_tf', 'tf2_msgs/TFMessage')
--tfname=simExtROS_enablePublisher('tf',1,simros_strmcmd_get_transform ,modelHandle,parentTf,'') --publish the tf
end
function sysCall_cleanup()
sim.removeDrawingObject(lines100)
sim.removeDrawingObject(points100)
end
function sysCall_sensing()
showLaserPoints=sim.getScriptSimulationParameter(sim.handle_self,'showLaserPoints')
showLaserSegments=sim.getScriptSimulationParameter(sim.handle_self,'showLaserSegments')
dists={}
angle=-scanRange*0.5
sim.setJointPosition(jointHandle,angle)
jointPos=angle
laserOrigin=sim.getObjectPosition(jointHandle,-1)
modelInverseMatrix=simGetInvertedMatrix(sim.getObjectMatrix(modelRef,-1))
data={}
for ind=0,pts-1,1 do
r,dist,pt=sim.handleProximitySensor(laserHandle) -- pt is relative to the laser ray! (rotating!)
-- m=sim.getObjectMatrix(laserHandle,-1)
table.insert(data,dist)
-- if r>0 then
-- dists[ind]=dist
-- -- We put the RELATIVE coordinate of that point into the table that we will return:
-- ptAbsolute=sim.multiplyVector(m,pt)
-- ptRelative=sim.multiplyVector(modelInverseMatrix,ptAbsolute)
-- points[3*ind+1]=ptRelative[1]
-- points[3*ind+2]=ptRelative[2]
-- points[3*ind+3]=ptRelative[3]
-- segments[7*ind+7]=1 -- indicates a valid point
-- else
-- dists[ind]=0
-- -- If we didn't detect anything, we specify (0,0,0) for the coordinates:
-- ptAbsolute=sim.multiplyVector(m,{0,0,6})
-- points[3*ind+1]=0
-- points[3*ind+2]=0
-- points[3*ind+3]=0
-- segments[7*ind+7]=0 -- indicates an invalid point
-- end
-- segments[7*ind+1]=laserOrigin[1]
-- segments[7*ind+2]=laserOrigin[2]
-- segments[7*ind+3]=laserOrigin[3]
-- segments[7*ind+4]=ptAbsolute[1]
-- segments[7*ind+5]=ptAbsolute[2]
-- segments[7*ind+6]=ptAbsolute[3]
ind=ind+1
angle=angle+stepSize
jointPos=jointPos+stepSize
sim.setJointPosition(jointHandle,jointPos)
end
-- sim.addDrawingObjectItem(lines100,nil)
-- sim.addDrawingObjectItem(points100,nil)
--
-- if (showLaserPoints or showLaserSegments) then
-- t={0,0,0,0,0,0}
-- for i=0,pts-1,1 do
-- t[1]=segments[7*i+4]
-- t[2]=segments[7*i+5]
-- t[3]=segments[7*i+6]
-- t[4]=segments[7*i+1]
-- t[5]=segments[7*i+2]
-- t[6]=segments[7*i+3]
-- if showLaserSegments then
-- sim.addDrawingObjectItem(lines100,t)
-- end
-- if (showLaserPoints and segments[7*i+7]~=0)then
-- sim.addDrawingObjectItem(points100,t)
-- end
-- end
-- end
-- Now send the data:
if #points>0 then
d={}
d['header']={
stamp=simGetSimulationTime(),
frame_id='/base_laser'
}
d['angle_min']=-scanRange*0.5
d['angle_max']=scanRange*0.5-stepSize
d['angle_increment']=stepSize
d['time_increment']=0 -- Unsure
d['scan_time']=0 -- Unsure
d['range_min']=0.0
d['range_max']=6.0
d['ranges']=data
d['intensities']={}
-- print(d)
simROS.publish(scanPub,d)
-- table.insert(dists,-scanRange*0.5) --append angle_min to [ranges]
-- table.insert(dists,scanRange*0.5-stepSize) --append angle_max to [ranges]
-- table.insert(dists,stepSize) --append stepsize to [ranges]
-- -- The publisher defined further up uses the data stored in signal 'rangeDat'..objName
-- sim.setStringSignal('rangeDat'..objName,sim.packFloatTable(dists))
end
end
|
local conditionalProperty = require(script.Parent.Parent.Utility.conditionalProperty)
local evaluateColorSequence = require(script.Parent.Parent.Utility.Sequences.evaluateColorSequence)
local evaluateNumberSequence = require(script.Parent.Parent.Utility.Sequences.evaluateNumberSequence)
local Types = require(script.Parent.Parent.Utility.Types)
type GooeyParticle = Types.GooeyParticle
type GooeyParticleProps = Types.GooeyParticleProps
local function updateParticle(particle: GooeyParticle, props: GooeyParticleProps, dt: number): ()
local currentTime = os.clock()
local alpha = (currentTime - particle.spawnedAt) / particle.lifetime
if alpha > 1 then
particle.remove()
particle.obj:Destroy()
return
end
local acceleration = props.Acceleration * dt * 5
particle.velocity += acceleration
particle.position += particle.velocity * dt
particle.obj.Position = UDim2.fromOffset(particle.position.X, particle.position.Y)
particle.obj.Rotation += particle.rotation * dt
if typeof(props.Transparency) ~= "number" then
particle.obj.ImageTransparency = evaluateNumberSequence(props.Transparency, alpha)
end
if typeof(props.Color) ~= "Color3" then
particle.obj.ImageColor3 = evaluateColorSequence(props.Color, alpha)
end
if typeof(props.Size) ~= "number" then
local size = evaluateNumberSequence(props.Size, alpha)
particle.obj.Size = UDim2.fromOffset(size, size)
end
end
return updateParticle
|
bot_token = "323116787:AAEgT0pkF9I3_Ja2p7wBN_l9nWxDKn-9YLU"
send_api = "https://api.telegram.org/bot"..bot_token
bot_version = "6.0"
sudo_name = "ALIREZA ABEDZADEH"
sudo_id = 119707014
admingp = -185089971
sudo_num = "989226773671"
sudo_user = "alireza_abedzadeh"
sudo_ch = "botantispam1"
|
local ffi = require("ffi")
-- OpenFlow: protocol between controller and datapath.
local common = require("openflow_common")
local OFP_ASSERT = common.OFP_ASSERT;
ffi.cdef[[
/* Group commands */
enum ofp15_group_mod_command {
/* Present since OpenFlow 1.1 - 1.4 */
OFPGC15_ADD = 0, /* New group. */
OFPGC15_MODIFY = 1, /* Modify all matching groups. */
OFPGC15_DELETE = 2, /* Delete all matching groups. */
/* New in OpenFlow 1.5 */
OFPGC15_INSERT_BUCKET = 3,/* Insert action buckets to the already available
list of action buckets in a matching group */
/* OFPGCXX_YYY = 4, */ /* Reserved for future use. */
OFPGC15_REMOVE_BUCKET = 5,/* Remove all action buckets or any specific
action bucket from matching group */
};
/* Group bucket property types. */
enum ofp15_group_bucket_prop_type {
OFPGBPT15_WEIGHT = 0, /* Select groups only. */
OFPGBPT15_WATCH_PORT = 1, /* Fast failover groups only. */
OFPGBPT15_WATCH_GROUP = 2, /* Fast failover groups only. */
OFPGBPT15_EXPERIMENTER = 0xFFFF, /* Experimenter defined. */
};
]]
ffi.cdef[[
/* Group bucket weight property, for select groups only. */
struct ofp15_group_bucket_prop_weight {
ovs_be16 type; /* OFPGBPT15_WEIGHT. */
ovs_be16 length; /* 8. */
ovs_be16 weight; /* Relative weight of bucket. */
uint8_t pad[2]; /* Pad to 64 bits. */
};
]]
OFP_ASSERT(ffi.sizeof("struct ofp15_group_bucket_prop_weight") == 8);
ffi.cdef[[
/* Group bucket watch port or watch group property, for fast failover groups
* only. */
struct ofp15_group_bucket_prop_watch {
ovs_be16 type; /* OFPGBPT15_WATCH_PORT or OFPGBPT15_WATCH_GROUP. */
ovs_be16 length; /* 8. */
ovs_be32 watch; /* The port or the group. */
};
]]
OFP_ASSERT(ffi.sizeof("struct ofp15_group_bucket_prop_watch") == 8);
ffi.cdef[[
/* Bucket for use in groups. */
struct ofp15_bucket {
ovs_be16 len; /* Length the bucket in bytes, including
this header and any padding to make it
64-bit aligned. */
ovs_be16 action_array_len; /* Length of all actions in bytes. */
ovs_be32 bucket_id; /* Bucket Id used to identify bucket*/
/* Followed by exactly len - 8 bytes of group bucket properties. */
/* Followed by:
* - Exactly 'action_array_len' bytes containing an array of
* struct ofp_action_*.
* - Zero or more bytes of group bucket properties to fill out the
* overall length in header.length. */
};
]]
OFP_ASSERT(ffi.sizeof("struct ofp15_bucket") == 8);
ffi.cdef[[
/* Bucket Id can be any value between 0 and OFPG_BUCKET_MAX */
enum ofp15_group_bucket {
OFPG15_BUCKET_MAX = 0xffffff00, /* Last usable bucket ID */
OFPG15_BUCKET_FIRST = 0xfffffffd, /* First bucket ID in the list of action
buckets of a group. This is applicable
for OFPGC15_INSERT_BUCKET and
OFPGC15_REMOVE_BUCKET commands */
OFPG15_BUCKET_LAST = 0xfffffffe, /* Last bucket ID in the list of action
buckets of a group. This is applicable
for OFPGC15_INSERT_BUCKET and
OFPGC15_REMOVE_BUCKET commands */
OFPG15_BUCKET_ALL = 0xffffffff /* All action buckets in a group,
This is applicable for
only OFPGC15_REMOVE_BUCKET command */
};
/* Group property types. */
enum ofp_group_prop_type {
OFPGPT15_EXPERIMENTER = 0xFFFF, /* Experimenter defined. */
};
]]
ffi.cdef[[
/* Group setup and teardown (controller -> datapath). */
struct ofp15_group_mod {
ovs_be16 command; /* One of OFPGC15_*. */
uint8_t type; /* One of OFPGT11_*. */
uint8_t pad; /* Pad to 64 bits. */
ovs_be32 group_id; /* Group identifier. */
ovs_be16 bucket_array_len; /* Length of action buckets data. */
uint8_t pad1[2]; /* Pad to 64 bits. */
ovs_be32 command_bucket_id; /* Bucket Id used as part of
* OFPGC15_INSERT_BUCKET and
* OFPGC15_REMOVE_BUCKET commands
* execution.*/
/* Followed by:
* - Exactly 'bucket_array_len' bytes containing an array of
* struct ofp15_bucket.
* - Zero or more bytes of group properties to fill out the overall
* length in header.length. */
};
]]
OFP_ASSERT(ffi.sizeof("struct ofp15_group_mod") == 16);
ffi.cdef[[
/* Body of reply to OFPMP_GROUP_DESC request. */
struct ofp15_group_desc_stats {
ovs_be16 length; /* Length of this entry. */
uint8_t type; /* One of OFPGT11_*. */
uint8_t pad; /* Pad to 64 bits. */
ovs_be32 group_id; /* Group identifier. */
ovs_be16 bucket_list_len; /* Length of action buckets data. */
uint8_t pad2[6]; /* Pad to 64 bits. */
/* Followed by:
* - Exactly 'bucket_list_len' bytes containing an array of
* struct ofp_bucket.
* - Zero or more bytes of group properties to fill out the overall
* length in header.length. */
};
]]
OFP_ASSERT(ffi.sizeof("struct ofp15_group_desc_stats") == 16);
|
id = 'V-38547'
severity = 'low'
weight = 10.0
title = 'The audit system must be configured to audit all discretionary access control permission modifications using fchmod.'
description = 'The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.'
fixtext = [==[At a minimum, the audit system should collect file permission changes for all users and root. Add the following to "/etc/audit/audit.rules":
-a always,exit -F arch=b32 -S fchmod -F auid>=500 -F auid!=4294967295 \
-k perm_mod
-a always,exit -F arch=b32 -S fchmod -F auid=0 -k perm_mod
If the system is 64-bit, then also add the following:
-a always,exit -F arch=b64 -S fchmod -F auid>=500 -F auid!=4294967295 \
-k perm_mod
-a always,exit -F arch=b64 -S fchmod -F auid=0 -k perm_mod]==]
checktext = [=[To determine if the system is configured to audit calls to the "fchmod" system call, run the following command:
$ sudo grep -w "fchmod" /etc/audit/audit.rules
If the system is configured to audit this activity, it will return several lines.
If no line is returned, this is a finding.]=]
function test()
end
function fix()
end
|
--[[
Localization.lua
Translations for Dominos
English: Default language
--]]
local AddonName = ...
local L = LibStub('AceLocale-3.0'):NewLocale(AddonName, 'enUS', true)
L.ActionBarDisplayName = "Action Bar %d"
L.ActionButtonDisplayName = "Action Button %d"
L.AlertsBarDisplayName = "Alerts"
L.AvailableProfiles = 'Available Profiles'
L.BagBarDisplayName = "Bags"
L.BarDisplayName = "%s Bar"
L.BindingEnterTip = 'Shift-Left Click to enter binding mode'
L.BindingExitTip = 'Shift-Left Click to exit binding mode'
L.CantDeleteCurrentProfile = 'Cannot delete the current profile'
L.ClassBarDisplayName = "Class Bar"
L.ConfigDesc = 'Toggles configuration mode'
L.ConfigEnterTip = 'Left Click to enter configuration mode'
L.ConfigExitTip = 'Left Click to exit configuration mode'
L.ConfigMode = 'Configuration Mode'
L.ConfigModeExit = 'Exit Config Mode'
L.ConfigModeHelp = 'Drag any bar to move it. Right Click to configure. Middle Click or Shift-Right Click to toggle visibility.'
L.CopyDesc = 'Copies settings from <profile>'
L.DeleteDesc = 'Deletes <profile>'
L.ExtraBarDescription = "Displays zone and encounter specific abilities"
L.ExtraBarDisplayName = "Extra Bar"
L.GridDensity = "Density"
L.Hidden = "Hidden"
L.HideBar = 'Middle Click or Shift-Right Click to hide'
L.HideFramesDesc = 'Hides the given <frameList>'
L.InvalidProfile = 'Invalid profile "%s"'
L.KeyboardMovementTip = "Use movement keys to adjust position."
L.ListDesc = 'Lists all profiles'
L.MenuBarDisplayName = "Menu"
L.MouseMovementTip = 'Drag with the Left Button to move.'
L.NewPlayer = 'Created new profile for %s'
L.PossessBarDisplayName = 'Possess Bar'
L.PetBarDisplayName = "Pet Action Bar"
L.PrintVersionDesc = 'Prints the current version'
L.ProfileCopied = 'Copied settings from "%s"'
L.ProfileCreated = 'Created new profile "%s"'
L.ProfileDeleted = 'Deleted profile "%s"'
L.ProfileLoaded = 'Set profile to "%s"'
L.ProfileReset = 'Reset profile "%s"'
L.ResetDesc = 'Returns to default settings'
L.RollBarDisplayName = "Rolls"
L.SaveDesc = 'Saves current settings and switches to <profile>'
L.SetAlpha = 'Mousewheel to set opacity (|cffffffff%d|r)'
L.SetAlphaDesc = 'Sets the opacity of <frameList>'
L.SetColsDesc = 'Sets the number of columns for <frameList>'
L.SetDesc = 'Switches settings to <profile>'
L.SetFadeDesc = 'Sets the faded opacity of <frameList>'
L.SetPadDesc = 'Sets the padding level for <frameList>'
L.SetScaleDesc = 'Sets the scale of <frameList>'
L.SetSpacingDesc = 'Sets the spacing level for <frameList>'
L.ShowAlignmentGrid = "Show Grid"
L.ShowBar = 'Middle Click or Shift-Right Click to show'
L.ShowConfig = 'Right Click to configure'
L.ShowFramesDesc = 'Shows the given <frameList>'
L.Shown = "Shown"
L.ShowOptionsDesc = 'Shows the options menu'
L.ShowOptionsTip = 'Right Click to show the options menu'
L.TipRollBar = 'Displays frames for rolling on items when in a group.'
L.TipVehicleBar = [[Displays controls to aim and exit a vehicle.\nAll other vehicle actions are displayed on the possess bar.]]
L.ToggleFramesDesc = 'Toggles the given <frameList>'
L.Updated = 'Updated to v%s'
L.WrongBuildWarning = "You're running a %s version for %s on a %s server. Things may not work"
|
_side = "enemy"
local _states = {
["player"] = {color = {0, 0, 0.545098}, state = 1},
["enemy"] = {color = {0.517647, 0, 0.098039}, bright = {0.94902, 0.184314, 0.32549}, state = 2},
["ally"] = {color = {0.039216, 0.368627, 0.211765}, bright = {0.352941, 0.823529, 0.603922}, state = 3},
["neutral"] = {color = {0.764706, 0.560784, 0}, bright = {0.933333, 0.741176, 0.219608}, state = 4}
}
local _extraParams = {
epic = false,
lair = false,
epicBoons = nil,
done = false
}
local names = {
"Kyle",
"Preston",
"Pedro",
"Jean",
"Willis",
"Eric",
"Alan",
"Jeremiah",
"Troy",
"Warner",
"Guadalupe",
"Emanuel",
"Parker",
"Willie",
"Mauricio",
"Tommie",
"Buck",
"Marlon",
"Deshawn",
"Fritz",
"Sam",
"Chung",
"Chungus",
"Jim",
"Whitney",
"Barton",
"Alec",
"Antione",
"Micah",
"Rhett",
"Clint",
"Raphael",
"Sammy",
"Dale",
"Pat",
"Lazarus",
"Milton",
"Vaughn",
"Walton",
"Lorenzo",
"Robby",
"Stanley",
"Marvin",
"Arnold",
"Chester",
"Wilmer",
"Zane",
"Cornelius",
"Ivan",
"Javier",
"Jesse",
"Rhea",
"Karla",
"Maybelle",
"Salley",
"Temple",
"Ronna",
"Lilli",
"Stella",
"Lorine",
"Denna",
"Bernice",
"Lorina",
"Rhona",
"Kasie",
"Earline",
"Felisha",
"Jeni",
"Stormy",
"Akiko",
"Beverlee",
"Chia",
"Ethelene",
"Lakisha",
"Hsiu",
"Dawna",
"Demetra",
"Junita",
"June",
"Lyndia",
"Otelia",
"Joanie",
"Jenell",
"Johana",
"Corina",
"Hannelore",
"Deandra",
"Florida",
"Matilde",
"Maragret",
"Luana",
"Neva",
"Rachal",
"Rona",
"Shirl",
"Maudie",
"Rosalyn",
"Rosaura",
"Jesusita",
"Adela",
"Lashon"
}
debug = false
function onload()
debug = shouldIDebug()
local inputs = {
{
-- name input [0]
input_function = "none",
function_owner = self,
label = " ",
position = {-2.94, 0.4, -0.27},
scale = {0.5, 0.5, 0.5},
width = 2900,
height = 424,
font_size = 350,
tooltip = "Name",
value = debug and "/" or "",
alignment = 2,
tab = 2
},
{
-- initiative input [1]
input_function = "none",
function_owner = self,
label = " ",
position = {-4.18, 0.4, 0.55},
scale = {0.5, 0.5, 0.5},
width = 550,
height = 385,
font_size = 350,
tooltip = "Initiative Modifier",
value = debug and "5" or "",
alignment = 3,
validation = 2,
tab = 2
},
{
-- hp input [2]
input_function = "none",
function_owner = self,
label = " ",
position = {-3, 0.4, 0.55},
scale = {0.5, 0.5, 0.5},
width = 1540,
height = 385,
font_size = 350,
tooltip = "Hit Points\nIf you want random hp start with r followed by the lower value and the upper value.\n" ..
"[i][AAAAAA]Example:[-] [0074D9]r[-][2ECC40]25[-]-[2ECC40]182[-][/i]",
value = debug and "r25-182" or "",
alignment = 3,
tab = 2
},
{
--ac input [3]
input_function = "none",
function_owner = self,
label = " ",
position = {-1.76, 0.4, 0.55},
scale = {0.5, 0.5, 0.5},
width = 650,
height = 385,
font_size = 350,
tooltip = " ",
alignment = 3,
validation = 2,
tab = 2,
value = debug and "15" or ""
},
{
-- movement input [4]
input_function = "none",
function_owner = self,
label = " ",
position = {-2.94, 0.4, 1.35},
scale = {0.5, 0.5, 0.5},
width = 2900,
height = 424,
font_size = 350,
tooltip = " ",
alignment = 3,
tab = 2,
value = debug and "30ft" or ""
},
{
-- numberToCreate input [5]
input_function = "none",
function_owner = self,
label = "NMB",
position = {0.03, 0.4, 0.73},
scale = {0.5, 0.5, 0.5},
width = 870,
height = 495,
font_size = 320,
color = {0.4941, 0.4941, 0.4941, 1},
tooltip = "Number to Create",
alignment = 3,
validation = 2,
tab = 2
},
{
-- jsonImport input [6]
input_function = "none",
function_owner = self,
label = "JSON IMPORT",
position = {2.48, 0.4, 1.12},
scale = {0.5, 0.5, 0.5},
color = {0.4941, 0.4941, 0.4941, 1},
width = 2730,
height = 425,
font_size = 320,
tooltip = "Import JSON stuff",
alignment = 2
},
{
-- boss token size bossSize [7]
input_function = "none",
function_owner = self,
label = "Boss Size",
position = {3.48, 0.4, -1.08},
scale = {0.5, 0.5, 0.5},
width = 1830,
height = 425,
font_size = 300,
color = {0.4941, 0.4941, 0.4941, 1},
tooltip = "Boss Size",
alignment = 3,
value = "Boss token size",
validation = 3
}
}
local buttons = {
{
-- size button [0]
click_function = "switch_size",
function_owner = self,
label = "Medium",
tooltip = "Size",
position = {3.64, 0.4, 0.62},
scale = {0.5, 0.5, 0.5},
width = 1630,
height = 425,
font_size = 320,
color = {0.1921, 0.4431, 0.1921, 1},
alignment = 2
},
{
-- note button [1]
click_function = "create_json_note",
function_owner = self,
label = "Make Note",
position = {1.95, 0.4, -0.24},
scale = {0.5, 0.5, 0.5},
width = 1730,
height = 425,
font_size = 320,
color = {0.1921, 0.4431, 0.1921, 1},
font_color = {0.6353, 0.8902, 0.6353, 1},
alignment = 2
},
{
-- create button [2]
click_function = "create_npc",
function_owner = self,
label = "CREATE",
position = {0.03, 0.4, 0.23},
scale = {0.5, 0.5, 0.5},
width = 1620,
height = 495,
font_size = 320,
color = {0.2823, 0.4039, 0.7686, 1},
font_color = {0.8, 0.8196, 0.8862, 1},
alignment = 2
},
{
-- isBoss button [3]
click_function = "boss_checkbox",
function_owner = self,
label = "",
position = {3.19, 0.4, -0.24},
scale = {0.5, 0.5, 0.5},
width = 425,
height = 425,
font_size = 320,
color = {0.6196, 0.2431, 0.2431, 1},
font_color = {0.6353, 0.8902, 0.6353, 1},
tooltip = "false",
alignment = 2
},
{
-- allegiance button [4]
click_function = "switch_sides",
function_owner = self,
label = "Enemy",
position = {1.88, 0.4, 0.62},
scale = {0.5, 0.5, 0.5},
width = 1630,
height = 425,
font_size = 320,
color = _states["enemy"].color,
alignment = 2
},
{
-- name question button [5]
click_function = "none",
function_owner = self,
label = "?",
tooltip = "The names of monsters can be variegated, remember of these escape characters:" ..
"\n- [FF4136]/[-] is for [b][FF4136]r[-][FF851B]a[-][FFDC00]n[-][2ECC40]d[-][0074D9]o[-][B10DC9]m[-] names[/b]" ..
"\n- [FF4136]%[-] is for [b]numbered creatures[/b] (only works for a set of monsters)\n\n" ..
"[AAAAAA]You may put things in parenthesis [FF4136]()[-] and they will be removed and put in a black only visible label, useful for " ..
"reminders that you may need from time to time in combat![-]",
position = {-3.42, 0.4, -0.63},
scale = {0.5, 0.5, 0.5},
width = 290,
height = 290,
font_size = 270,
color = {0.8972, 0.8915, 0.3673, 1},
alignment = 2
},
{
-- boss question button [6]
click_function = "none",
function_owner = self,
label = "?",
tooltip = "A boss is defined by its image, if it has one then it needs to be a boss." ..
"To have a creature with image simply put the link to the image (hosted wherever, I suggest imgur)" ..
"in the [b][FF4136]description of the commander[-][/b] and click the button button to the immediate left" ..
"of this tutorial: \n[2ECC40]green[-] = boss\n[FF4136]red[-] = not boss",
position = {4.25, 0.400000005960464, -0.12},
scale = {0.5, 0.5, 0.5},
width = 290,
height = 290,
font_size = 270,
color = {0.8972, 0.8915, 0.3673, 1},
alignment = 2
},
{
-- clear button [7]
click_function = "clear",
function_owner = self,
label = "↺",
position = {-4, 0.400000005960464, -1.13},
scale = {0.5, 0.5, 0.5},
width = 490,
height = 490,
font_size = 470,
color = {0.2823, 0.4039, 0.7686, 1},
tooltip = "Clear",
alignment = 2
},
{
-- randomize button [8]
click_function = "randomize",
function_owner = self,
label = "↝",
position = {-3.5, 0.400000005960464, -1.13},
scale = {0.5, 0.5, 0.5},
width = 490,
height = 490,
font_size = 470,
color = {0.2823, 0.4039, 0.7686, 1},
tooltip = "Randomize\nPlease don't use this as an encounter builder",
alignment = 2
},
{
click_function = "parseJson",
function_owner = self,
label = "P",
tooltip = "Parse JSON",
position = {4.13, 0.400000005960464, 1.12},
scale = {0.5, 0.5, 0.5},
width = 640,
height = 460,
font_size = 270,
color = {0.3764, 0.3764, 0.3764, 1},
alignment = 2
}
}
for i = 1, #inputs do
self.createInput(inputs[i])
end
for i = 1, #buttons do
self.createButton(buttons[i])
end
end
function none()
end
function clear()
for i = 1, #self.getInputs() do
self.editInput({index = i - 1, value = ""})
end
end
function randomize()
-- name input [0]
-- initiative input [1]
-- hp input [2]
-- ac input [3]
-- movement input [4]
-- numberToCreate input [5]
self.editInput({index = 0, value = "/"})
self.editInput({index = 1, value = math.random(-2, 5)})
self.editInput({index = 2, value = "r" .. math.random(1, 50) .. "-" .. math.random(51, 175)})
self.editInput({index = 3, value = math.random(8, 17)})
self.editInput({index = 4, value = math.random(1, 5) .. "0 ft"})
self.editInput({index = 5, value = math.random(1, 9)})
end
function shouldIDebug()
local notes = self.getGMNotes()
local vars = JSON.decode(notes)
return vars.debug
end
------------------------------------------------------
-- Get Baggies
------------------------------------------------------
function getBag(name)
-- vars ------------
-- token
-- boss
-- notes
-- initiative
--------------------
local notes = self.getGMNotes()
local vars = JSON.decode(notes)
return vars[name]
end
function getNewPos(id)
local obj = getObjectFromGUID(id)
local notes = obj.getGMNotes()
local pos = obj.getPosition()
if notes ~= nil then
local var = JSON.decode(notes)
if var then
local varianceX = var.varx and var.varx or 0
local varianceY = var.vary and var.vary or 0
local varianceZ = var.varz and var.varz or 0
if var.diffx then
pos.x = pos.x + var.diffx + math.random(-varianceX, varianceX)
end
if var.diffy then
pos.y = pos.y + var.diffy + math.random(-varianceY, varianceY)
end
if var.diffz then
pos.z = pos.z + var.diffz + math.random(-varianceZ, varianceZ)
end
return pos
end
end
pos.x = pos.x + 3
pos.y = pos.y + 3
return pos
end
function getNewRot(id)
local obj = getObjectFromGUID(id)
local notes = obj.getGMNotes()
local rot = {x = 0, y = 0, z = 0}
if notes ~= nil then
local var = JSON.decode(notes)
if var then
if var.rotx then
rot.x = var.rotx
end
if var.roty then
rot.y = var.roty
end
if var.rotz then
rot.z = var.rotz
end
return rot
end
end
return rot
end
function getDestination()
-- calculates wether an item should go to the hand or not
local notes = self.getGMNotes()
local masterPos = self.getPosition()
local masterBounds = self.getBounds()
local variance = 3
local pos = {
x = masterPos.x + math.random(-variance, variance),
y = masterPos.y + 3,
z = masterPos.z - 3 - (masterBounds.size.z / 2)
}
if notes ~= nil then
local var = JSON.decode(notes)
if var then
if var.hand ~= nil then
pos = {x = var.hand.x, y = var.hand.y, z = var.hand.z}
end
end
end
return pos
end
------------------------------------------------------
-- Get/Set Input Functions
------------------------------------------------------
-- name ----------------------------------------------
function getName(number, literal)
local inputs = self.getInputs()[1]
local name = inputs.value
if literal then
return name
end
name = name:gsub("/", names[math.random(1, #names)])
if number then
name = name:gsub("%%", number)
end
--if string.sub(returner, 1, 1) == "/" then
-- if #returner > 1 then
-- returner = string.sub(returner, 2) .. names[math.random(1, #names)]
-- else
-- returner = names[math.random(1, #names)]
-- end
--else if number ~= nil then
--
--end
return name
end
function setName(params)
self.editInput({index = 0, value = params.input})
end
function findBlackName(name)
if debug then
log(name, "Finding black name")
end
local pattern = ".+%((.+)%)"
local _,
_,
found = string.find(name, pattern)
if found ~= nil then
return {name = name:gsub("%(" .. found .. "%)", ""), black = found}
end
return nil
end
------------------------------------------------------
-- initiative ----------------------------------------
function getInitiative()
local input = self.getInputs()[2].value
return input
end
function setInitiative(params)
self.editInput({index = 1, value = params.input})
end
-- deprecated method
function setINI(params)
setInitiative(params)
end
------------------------------------------------------
-- hp ------------------------------------------------
function getHP(literal)
local hp = self.getInputs()[3].value
if literal then
return hp
end
if string.sub(hp, 1, 1) == "r" then
hp = string.gsub(hp, "r", "")
local range = mysplit(hp, "-")
hp = math.random(range[1], range[2])
end
return tonumber(hp)
end
function setHP(params)
self.editInput({index = 2, value = params.input})
end
------------------------------------------------------
-- ac ------------------------------------------------
function getAC()
local input = self.getInputs()[4].value
return input
end
function setAC(params)
self.editInput({index = 3, value = params.input})
end
------------------------------------------------------
-- movement ------------------------------------------
function getMovement()
local input = self.getInputs()[5].value
return input
end
function setMovement(params)
self.editInput({index = 4, value = params.input})
end
------------------------------------------------------
-- size ----------------------------------------------
function getSize(getData)
local buttons = self.getButtons()[1]
if not getData then
return buttons.label
else
if not getBossCheckbox() then
local scale = {}
scale["Small"] = 0.17
scale["Medium"] = 0.30
scale["Large"] = 0.55
scale["Huge"] = 0.90
scale["Gargantuan"] = 1.20
return scale[buttons.label]
else
local scale = {}
scale["Small"] = 0.53
scale["Medium"] = 0.78
scale["Large"] = 1.45
scale["Huge"] = 2.40
scale["Gargantuan"] = 3.30
return scale[buttons.label]
end
end
end
function setSize(params)
self.editButton({index = 0, label = params.input})
end
------------------------------------------------------
-- boss checkbox -------------------------------------
function boss_checkbox()
local btn = self.getButtons()[4]
local isBoss = btn.tooltip == "true"
local color = {
red = {0.6196, 0.2431, 0.2431, 1},
green = {0.1921, 0.4431, 0.1921, 1}
}
if not isBoss then
self.editButton({index = 3, color = color.green})
self.editButton({index = 3, tooltip = "true"})
else
self.editButton({index = 3, color = color.red})
self.editButton({index = 3, tooltip = "false"})
end
end
function getBossCheckbox()
local btn = self.getButtons()[4]
return btn.tooltip == "true"
end
function toggleIsBoss(params)
local btn = self.getButtons()[4]
local color = {
red = {0.6196, 0.2431, 0.2431, 1},
green = {0.1921, 0.4431, 0.1921, 1}
}
if params.input then
self.editButton({index = 3, color = color.green})
self.editButton({index = 3, tooltip = "true"})
else
self.editButton({index = 3, color = color.red})
self.editButton({index = 3, tooltip = "false"})
end
end
-- numberToCreate -------------------------------------
function setNumberToCreate(params)
self.editInput({index = 5, value = params.input})
end
function getNumberToCreate()
local input = self.getInputs()[6]
if input.value == "" then
return 1
else
return tonumber(input.value)
end
end
------------------------------------------------------
-- jsonImport ----------------------------------------
function getJsonImport()
local input = self.getInputs()[7]
return input.value
end
------------------------------------------------------
-- dmg [deprecated] ----------------------------------
function getDMG()
log("Called getDMG(), deprecated")
return "d"
end
function setDMG(params)
log("Called setDMG() " .. params.input)
end
function getATK()
log("Called getATK(), deprecated")
return "d"
end
function setATK(params)
log("Called setATK() " .. params.input)
end
------------------------------------------------------
function lockInputs(toggle)
for i = 1, #self.getButtons() do
self.editButton({index = i - 1, enabled = toggle})
end
for i = 1, #self.getInputs() do
self.editInput({index = i - 1, enabled = toggle})
end
end
function switch_size(obj, player_clicker_color, alt_click)
local sizes = {}
sizes[1] = "Small"
sizes[2] = "Medium"
sizes[3] = "Large"
sizes[4] = "Huge"
sizes[5] = "Gargantuan"
local currentSize = getSize()
local c = 1
for i = 1, #sizes do
if sizes[i] == currentSize then
c = alt_click and i - 1 or i + 1
end
end
if c > #sizes then
c = 1
elseif c <= 0 then
c = #sizes
end
self.editButton(
{
index = 0,
label = sizes[c]
}
)
end
function boss_checkbox()
local btn = self.getButtons()[4]
local isBoss = btn.tooltip == "true"
local color = {
red = {0.6196, 0.2431, 0.2431, 1},
green = {0.1921, 0.4431, 0.1921, 1}
}
if not isBoss then
self.editButton({index = 3, color = color.green})
self.editButton({index = 3, tooltip = "true"})
else
self.editButton({index = 3, color = color.red})
self.editButton({index = 3, tooltip = "false"})
end
end
function create_json_note(obj, player_clicker_color, alt_click)
local vars = {
name = getName(nil, true),
ini = getInitiative(),
hp = getHP(true),
ac = getAC(),
mov = getMovement(),
size = getSize(),
image = getBossCheckbox() and self.getDescription() or nil,
side = _side,
boss_size = getBossSize()
}
if (getBag("note") ~= nil) then
local numberToCreate = getNumberToCreate()
local id = getBag("note")
local bag = getObjectFromGUID(id)
local takeParams = {
position = getNewPos(id),
rotation = getNewRot(id),
callback_function = function(obj)
obj.setName(vars.name)
obj.setDescription(JSON.encode(vars))
if numberToCreate > 1 then
obj.setGMNotes(numberToCreate)
end
obj.setColorTint(_states[vars.side].bright)
obj.call("setData")
end
}
bag.takeObject(takeParams)
end
--local name = getName(nil, true)
--local initiative = getInitiative()
--local hp = getHP(true)
--local ac = getAC()
--local movement = getMovement()
--local size = getSize()
--local image = getBossCheckbox() and self.getDescription() or nil
--local numberToCreate = getNumberToCreate()
--local side = _side
end
-- boss size -----------------------------------------
function getBossSize()
local input = self.getInputs()[8]
if input.value == "" or input.value == nil then
return 1.0
end
return input.value
end
function setBossSize(params)
self.editInput({index = 7, value = params.input})
end
------------------------------------------------------
-- deprecated function, check create_json_note
function create_note(obj, player_clicker_color, alt_click)
--- create note stuff
local name = getName(nil, true)
local initiative = getInitiative()
local hp = getHP(true)
local ac = getAC()
local modi = "0" -- deprecated
local dice = "d" -- deprecated
local movement = getMovement()
local size = getSize()
local image = getBossCheckbox() and self.getDescription() or nil
--local boss_size = getBossSize()
local numberToCreate = getNumberToCreate()
local str =
name ..
"|" .. initiative .. "|" .. hp .. "|" .. ac .. "|" .. modi .. "|" .. dice .. "|" .. movement .. "|" .. size
if image then
str = str .. "\n" .. image
end
if debug then
log(str, "Creating note:")
end
if getBag("note") ~= nil then
local id = getBag("note")
local bag = getObjectFromGUID(id)
local takeParams = {
position = getNewPos(id),
rotation = getNewRot(id),
callback_function = function(obj)
obj.setName(name)
obj.setDescription(str)
if numberToCreate > 1 then
obj.setGMNotes(numberToCreate)
end
end
}
bag.takeObject(takeParams)
end
return str
end
function parseJson()
-- local stuff = mysplit(mysplit(self.getDescription(), "\n")[1], "|")
-- local npc_commander = getObjectFromGUID(commander)
-- npc_commander.call("setName", {input = stuff[1]})
-- npc_commander.call("setINI", {input = stuff[2]})
-- npc_commander.call("setHP", {input = stuff[3]})
-- npc_commander.call("setAC", {input = stuff[4]})
-- npc_commander.call("setATK", {input = stuff[5]})
-- npc_commander.call("setDMG", {input = stuff[6]})
-- if stuff[7] then
-- npc_commander.call("setMovement", {input = stuff[7]})
-- end
-- if stuff[8] then
-- npc_commander.call("setSize", {input = stuff[8]})
-- end
-- local second_line = mysplit(self.getDescription(), "\n")[2]
-- if second_line ~= nil and second_line ~= "" then
-- -- this means it is a boss
-- npc_commander.setDescription(second_line)
-- npc_commander.call("toggleIsBoss", {input = true})
-- else
-- npc_commander.call("toggleIsBoss", {input = false})
-- end
-- if self.getGMNotes() ~= "" then
-- -- this means i have multiple that i want to make
-- local number = tonumber(self.getGMNotes())
-- npc_commander.call("setNumberToCreate", {input = number})
-- end
local json = getJsonImport()
local data = JSON.decode(json)
setName({input = data.name})
setINI(({input = data.ini}))
setHP(({input = data.hp}))
setAC(({input = data.ac}))
setMovement(({input = data.mov}))
setSize({input = data.size})
setSide({input = data.side})
if data.image then
toggleIsBoss({input = true})
self.setDescription(data.image)
else
toggleIsBoss({input = false})
end
end
---------------------------------------
function switch_sides()
if _side == "enemy" then
_side = "ally"
elseif _side == "ally" then
_side = "neutral"
elseif _side == "neutral" then
_side = "enemy"
end
self.editButton({index = 4, color = _states[_side].color})
self.editButton({index = 4, label = _side:gsub("^%l", string.upper)})
end
function setSide(params)
local side = string.lower(params.input)
_side = side
self.editButton({index = 4, color = _states[_side].color})
self.editButton({index = 4, label = _side:gsub("^%l", string.upper)})
end
-- coroutine based variables
local coInitiativeId,
coBossId,
coTokenId,
coBoonsId
function create_npc(obj, player_clicker_color, alt_click)
-- go and move to NPCs or to Boss
local notes = self.getGMNotes()
local vars = JSON.decode(notes)
coBoonsId = vars.boons
coInitiativeId = vars.initiative
if getBossCheckbox() then
coBossId = vars["boss"]
create_thing("boss")
else
coTokenId = vars["token"]
create_thing("token")
end
end
function create_thing(thing)
local result = startLuaCoroutine(self, thing .. "_coroutine")
end
function boss_coroutine()
local boss = getObjectFromGUID(coBossId)
local numberToCreate = getNumberToCreate()
for i = 1, numberToCreate do
local takeParams = {
position = getNewPos(coBossId),
rotation = getNewRot(coBossId),
callback_function = function(spawned)
local image = self.getDescription()
local sID = spawned.getGUID()
spawned.use_hands = true
spawned.call("_starter", {image = image, boss_size = getBossSize()})
-- gotta wait else the game freaks out
-- if you don't save the guid the game gets confused
Wait.time(
function()
local me = getObjectFromGUID(sID)
local details = create_details(i)
details.pawn = me.getGUID()
me.call("_init", {master = self, obj = details})
me.setPositionSmooth(getDestination(), false, false)
create_initiative(details)
create_epics()
end,
0.5
)
end
}
boss.takeObject(takeParams)
coroutine.yield(0)
end
return 1
end
function token_coroutine()
local token = getObjectFromGUID(coTokenId)
local numberToCreate = getNumberToCreate()
for i = 1, numberToCreate do
local takeParams = {
position = getNewPos(coTokenId),
rotation = getNewRot(coTokenId),
callback_function = function(spawned)
spawned.use_hands = true
Wait.time(
function()
local details = create_details(i)
details.pawn = spawned.getGUID()
spawned.call("_init", {master = self, obj = details})
spawned.setPositionSmooth(getDestination(), false, false)
create_initiative(details)
create_epics()
end,
0.5
)
end
}
token.takeObject(takeParams)
coroutine.yield(0)
end
return 1
end
function create_details(nameIdentifier)
local details = {
name = getName(nameIdentifier),
hp = getHP(),
ac = getAC(),
size = getSize(true),
initiative = getInitiative(),
ini_tracker = nil,
movement = getMovement(),
side = _side,
bossSize = getBossSize()
}
local blackName = findBlackName(details.name)
if blackName ~= nil then
details.name = blackName.name
blackName = blackName.black
end
details.maxhp = details.hp
details.blackName = blackName
return details
end
function create_initiative(details)
local initiative = details.initiative
local roll = math.random(1.0, 20.0)
local final = roll + initiative
if final <= 0 then
final = 1
end
local ini = getObjectFromGUID(coInitiativeId)
local takeParams = {
position = getNewPos(coInitiativeId),
rotation = getNewRot(coInitiativeId),
callback_function = function(spawned)
Wait.time(
function()
spawned.call(
"_init",
{
input = {
name = details.name,
modifier = details.initiative,
pawn = details.pawn,
side = details.side
}
}
)
end,
1
)
end
}
ini.takeObject(takeParams)
if _extraParams.lair then
takeParams.callback_function = function(spawned)
Wait.time(
function()
spawned.call(
"_init",
{
input = {
name = "Lair",
modifier = 20,
pawn = "",
side = "lair",
static = true
}
}
)
end,
1
)
end
takeParams.position.y = takeParams.position.y + 1.5
ini.takeObject(takeParams)
end
if _extraParams.epic then
takeParams.callback_function = function(spawned)
Wait.time(
function()
spawned.call(
"_init",
{
input = {
name = "Epic Die",
modifier = 50,
pawn = "",
side = "epic",
static = true
}
}
)
end,
1
)
end
takeParams.position.y = takeParams.position.y + 1.5
ini.takeObject(takeParams)
end
end
function create_epics()
if _extraParams.epicBoons == nil then
return
end
if coBoonsId == nil then
printToColor(
"It seems you have some boons in the data but you didn't setup the boon bag.\nTo use this feature you must have a 'boons' variable in the commander.",
"Black",
Color.Red
)
return
end
local boonBag = getObjectFromGUID(coBoonsId)
local takeParams = {
position = getNewPos(coBoonsId),
rotation = getNewRot(coBoonsId)
}
for i = #_extraParams.epicBoons, 1, -1 do
local boon = _extraParams.epicBoons[i]
takeParams.callback_function = function(spawned)
Wait.time(
function()
if type(boon) == "string" then
spawned.setDescription(boon)
else
spawned.setDescription(boon[1])
spawned.setName(boon[2])
end
spawned.setColorTint({0, 0.454902, 0.85098})
spawned.call("setData")
end,
1
)
end
boonBag.takeObject(takeParams)
takeParams.position.y = takeParams.position.y + 1.5
end
end
-- set _extraParams --------------------------
function setExtraParams(params)
if params == nil then
_extraParams.epic = false
_extraParams.lair = false
_extraParams.epicBoons = nil
return
end
printToColor("Found extra params!", "Black", Color.Blue)
if params.epic ~= nil then
_extraParams.epic = params.epic
printToColor(" epic: [0074D9]" .. tostring(params.epic) .. "[-]", "Black", Color.White)
else
_extraParams.epic = false
end
if params.lair ~= nil then
_extraParams.lair = params.lair
printToColor(" lair: [0074D9]" .. tostring(params.lair) .. "[-]", "Black", Color.White)
else
_extraParams.lair = false
end
if params.epicBoons ~= nil then
_extraParams.epicBoons = params.epicBoons
printToColor(" epicBoons: [0074D9]" .. #params.epicBoons .. "[-]", "Black", Color.White)
else
_extraParams.epicBoons = nil
end
log(_extraParams)
end
----------------------------------------------
-- utils -------------------------------------
function mysplit(inputstr, sep)
if sep == nil then
sep = "%s"
end
local t = {}
i = 1
for str in string.gmatch(inputstr, "([^" .. sep .. "]+)") do
t[i] = str
i = i + 1
end
return t
end
----------------------------------------------
-- called functions --------------------------
function destroy(params)
destroyObject(params.pawn)
end
----------------------------------------------
|
-- This normalizes title to the "pretty" form with spaces,
-- because that is used in the entry_index.
local function normalize_title(title)
return (title:gsub("_", " "))
end
local function eprint(...)
io.stderr:write(...)
io.stderr:write "\n"
end
local function get_entry_redirects(path)
local title_to_redirects = {}
local i = 0
for line in io.lines(path) do
local from, to = line:match "^([^\t]+)\t([^\t]+)$"
i = i + 1
if not from then
eprint("Line #" .. i .. " ," .. line .. ", didn't match pattern")
else
from, to = normalize_title(from), normalize_title(to)
local redirects = title_to_redirects[to]
if not redirects then
redirects = {}
title_to_redirects[to] = redirects
end
table.insert(redirects, from)
end
end
return title_to_redirects
end
local function process_entry_index(path, title_to_redirects)
local i = 0
for line in io.lines(path) do
local title, languages = line:match "^([^\t]+)\t(.+)$"
i = i + 1
if not title then
eprint("Line #" .. i .. " ," .. line .. ", didn't match pattern")
else
title = normalize_title(title)
local redirects = title_to_redirects[title]
print(line)
if redirects then
for _, redirect in ipairs(redirects) do
print(redirect, languages)
end
end
end
end
end
local entry_index, entry_redirects = ...
process_entry_index(entry_index, get_entry_redirects(entry_redirects))
|
game:DefineFastFlag("PlayerSpecificPopupCounter", false)
return function()
return game:GetFastFlag("PlayerSpecificPopupCounter")
end
|
--[[
Includes a series of useful utilities
]]
--checks if two tables are equal to eachother
function table.eq(firstTable, secondTable)
for firstIndex, value in pairs(firstTable) do
if secondTable[firstIndex] ~= value then
return false
end
end
return true
end
function table.print(t)
for i,v in pairs(t) do
print(i,v)
end
end
|
Locales ['es'] = {
['message_title'] = '^3Sistema de alarma',
['message_locked'] = 'Alarma Activada',
['message_unlocked'] = 'Alarma Desactivada',
}
|
package = "blunty666.nodes.gui.events"
class = "PasteEvent"
extends = "BaseEvent"
variables = {
data = NIL,
}
local function checkData(data)
return data -- TODO
end
constructor = function(self, data)
self.super("paste")
self.raw.data = checkData(data)
end
|
function LERider_OnEnterCombat(Unit,Event)
Unit:CastSpell(39782)
Unit:CastSpellOnTarget(31888,Unit:GetClosestPlayer())
end
RegisterUnitEvent(22966, 1, "LERider_OnEnterCombat") |
--[[
################################################################################
#
# Copyright (c) 2014-2020 Ultraschall (http://ultraschall.fm)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
################################################################################
]]
-- Ultraschall Toolbox
-- Preview Audio Before Recording beta 3 (10th of July 2020) - by Meo Mespotine mespotine.de
--
-- 1. Set Editcursor to position, where you want to start recording
-- 2. Start script; a window with an OK-button will pop up
-- 3. Set Editcursor to the position, from where you want to "preview-playback". You can
-- playback until you find the right position
-- 4. When you've found the right position, click "OK" in the opened window
-- 5. You will hear a playback of your audio until you reach your desired recording-position, where
-- recording will start
-- Everything from the recposition until the end of the project will be deleted, before recording starts.
-- That way, you don't need to manually edit wrong stuff out by yourself.
--
-- Good for audioplays, where you want to give the speaker/voice-actor a preview of their last performance or
-- their last sentence they acted, more easily than with usual pre-roll, as you can set the exact spot to restart.
-- Maybe helpful for other things as well?
--
-- Help us making good scripts, donate to our team at: ultraschall.fm/danke
--
-- Cheers
dofile(reaper.GetResourcePath().."/UserPlugins/ultraschall_api.lua")
-- Grab all of the functions and classes from our GUI library
local info = debug.getinfo(1,'S');
script_path = info.source:match[[^@?(.*[\/])[^\/]-$]]
GUI = dofile(script_path .. "ultraschall_gui_lib.lua")
if ultraschall.AnyTrackRecarmed()==false then reaper.MB("There is no track armed for recording", "No Recarmed track", 0) return end
operationSystem = reaper.GetOS()
if string.match(operationSystem, "OS") then
font_size = 14
font_face = "Helvetica"
else
font_size = 16
font_face = "Arial"
end
--retval, measures, cml, fullbeats, cdenom = reaper.TimeMap2_timeToBeats(0, 10)
Preroll_Settings=reaper.SNM_GetIntConfigVar("preroll", -99)
Preroll_Settings_new=6
reaper.SNM_SetIntConfigVar("preroll", Preroll_Settings_new)
OldTime=reaper.SNM_GetDoubleConfigVar("prerollmeas", -99)
if reaper.GetPlayState()~=0 then
Recposition=reaper.GetPlayPosition()
else
Recposition=reaper.GetCursorPosition()
end
if reaper.GetPlayState()&4==4 then reaper.CSurf_OnStop() return end
function main()
Playposition=reaper.GetCursorPosition() -- get current editcursor-position, from where the previewing will start
gfx.quit() -- close gfx-window
if Recposition<Playposition then
-- if playposition is bigger than recposition, then show error-message, clean up and exit
reaper.SNM_SetIntConfigVar("preroll", Preroll_Settings)
reaper.MB("The recording-position must be after the preview-play-position!", "Ooops" ,0)
reaper.SetExtState("ultraschall_PreviewRecording", "Dialog", "0", false)
reaper.DeleteExtState("ultraschall_PreviewRecording", "RecPosition", false) -- lösche Eintrag für Preroll
return
else
-- in all other cases, set the correct pre-roll-measure-settings, start recording(with preroll activated), clean up and exit
trackstringarmed = ultraschall.CreateTrackString_ArmedTracks()
if trackstringarmed=="" then
return
end
if reaper.GetPlayState()~=0 then reaper.CSurf_OnStop() end
reaper.Undo_BeginBlock()
ultraschall.SectionCut(Recposition, reaper.GetProjectLength()+Recposition, trackstringarmed, false)
reaper.SetExtState("ultraschall_PreviewRecording", "RecPosition", Recposition, false)
-- Stelle das MagicRouting so um, dass im preroll auf jeden Fall was zu hören ist:
reaper.SetProjExtState(0, "ultraschall_magicrouting", "step", "editing")
reaper.SetProjExtState(0, "ultraschall_magicrouting", "override", "on")
reaper.MoveEditCursor(Recposition-Playposition, false)
local Gap=Recposition-Playposition
local NewTime=ultraschall.TimeToMeasures(0, Gap)
reaper.SNM_SetDoubleConfigVar("prerollmeas", NewTime)
reaper.CSurf_OnRecord()
reaper.SNM_SetIntConfigVar("preroll", Preroll_Settings)
reaper.SNM_SetDoubleConfigVar("prerollmeas", OldTime)
reaper.Undo_EndBlock("PreviewRecording", -1)
tudelu=false
end
-- gfx.update()
if tudelu~=false then reaper.defer(main) end
end
---- Window settings and user functions ----
reaper.SetExtState("ultraschall_PreviewRecording", "Dialog", "1", false)
GUI.name = "Ultraschall 5 - Preroll Recording"
GUI.w, GUI.h = 350, 80
------------------------------------------------------
-- position always in the center of the screen
------------------------------------------------------
l, t, r, b = 0, 0, GUI.w, GUI.h
__, __, screen_w, screen_h = reaper.my_getViewport(l, t, r, b, l, t, r, b, 1)
GUI.x, GUI.y = (screen_w - GUI.w) / 2, (screen_h - GUI.h) / 2
GUI.elms = { }
-- Inhalt des Fensters - Text und Button
ok_button = GUI.Btn:new(240, 27, 90, 30, " OK", main, "")
table.insert(GUI.elms, ok_button)
label = GUI.Lbl:new( 20 , 20, "Place Editcursor to \nStart of Preview-Playposition \nand click OK", 0)
table.insert(GUI.elms, label)
GUI.Init()
GUI.Main()
function atexit()
reaper.SetExtState("Ultraschall_Windows", GUI.name, 0, false)
reaper.SNM_SetIntConfigVar("preroll", Preroll_Settings)
reaper.SetExtState("ultraschall_PreviewRecording", "Dialog", "0", false) -- lösche Eintrag für Preroll Dialog
-- reaper.DeleteExtState("ultraschall_PreviewRecording", "RecPosition", false) -- lösche Eintrag für Preroll
end
reaper.atexit(atexit)
|
player = game.Players.LocalPlayer
game:GetService("BadgeService"):AwardBadge(player.userId, 24806012) |
local util = require("spec.util")
describe("forin", function()
describe("ipairs", function()
it("with a single variable", util.check [[
local t = { 1, 2, 3 }
for i in ipairs(t) do
print(i)
end
]])
it("with two variables", util.check [[
local t = { 1, 2, 3 }
for i, v in ipairs(t) do
print(i, v)
end
]])
it("with nested ipairs", util.check [[
local t = { {"a", "b"}, {"c"} }
for i, a in ipairs(t) do
for j, b in ipairs(a) do
print(i, j, "value: " .. b)
end
end
]])
it("unknown with nested ipairs", util.lax_check([[
local t = {}
for i, a in ipairs(t) do
for j, b in ipairs(a) do
print(i, j, "value: " .. b)
end
end
]], {
{ msg = "a" },
{ msg = "b" },
}))
it("rejects nested unknown ipairs", util.check_type_error([[
local t = {}
for i, a in ipairs(t) do
for j, b in ipairs(a) do
print(i, j, "value: " .. b)
end
end
]], {
{ msg = "attempting ipairs loop" },
{ msg = "attempting ipairs loop" },
}))
end)
describe("pairs", function()
it("rejects heterogenous records in pairs", util.check_type_error([[
local type Rec = record
n: number
fun: function(number, number)
end
local r: Rec = {}
function foo(init: Rec)
for k, v in pairs(init) do
r[k] = v
end
end
]], {
{ msg = "attempting pairs loop" },
{ msg = "not all fields have the same type" },
{ msg = "cannot index object of type Rec" },
}))
end)
it("with an explicit iterator", util.check [[
local function iter(t): number
end
local t = { 1, 2, 3 }
for i in iter, t do
print(i + 1)
end
]])
it("with an iterator declared as a function type", util.check [[
local function it(): function(): string
return nil
end
for v in it() do
end
]])
it("with a callable record interator", util.check [[
local record R
incr: integer
metamethod __call: function(): integer
end
function foo(incr: integer): R
local x = 0
return setmetatable({incr=incr} as R, {
__call = function(self: R): integer
x = x + self.incr
return x < 4 and x or nil
end
})
end
for i in foo(1) do
print(i + 0)
end
]])
it("catches wrong call to a wrongly declared callable record interator", util.check_type_error([[
local record R
metamethod __call: function(): integer
end
function foo(): R
return setmetatable({} as R, {
__call = function(wrong_self: integer): integer
return nil
end
})
end
for i in foo() do
end
]], {
{ msg = "argument 2: type parameter <@a>: got integer, expected R" }
}))
--[=[ -- TODO: check forin iterator arguments
it("catches wrong call to a wrongly declared callable record interator", util.check_type_error([[
local record R
incr: integer
metamethod __call: function(integer): integer
end
function foo(): R
return nil
end
for i in foo() do
end
]], {
{ msg = "argument 2: type parameter <@a>: got integer, expected R" }
}))
]=]
it("catches when too many values are passed", util.check_type_error([[
local function it(): function(): string
return nil
end
for k, v in it() do
end
]], {
{ x = 14, y = 5, msg = "too many variables for this iterator; it produces 1 value" }
}))
it("catches when too many values are passed, smart behavior about tuples", util.check_type_error([[
local record R
fields: function({number, nil}, string): (function(): string)
fields: function({number, number}, string): (function(): string, string)
fields: function({number} | number, string): (function(): string...)
end
for a, b in R.fields({1}, "hello") do
-- if you try to put "for a, b" here you get an error
end
]], {
{ y = 7, "too many variables for this iterator; it produces 1 value" }
}))
describe("regression tests", function()
it("with an iterator declared as a nominal (#183)", util.check [[
local type Iterator = function(): string
local function it(): Iterator
return nil
end
for v in it() do
end
]])
it("type inference for variadic return (#237)", util.check [[
local function unpacker<T>(arr: {{T}}): function(): T...
local i = 0
return function(): T...
i = i + 1
if not arr[i] then return end
return table.unpack(arr[i])
end
end
for a, b in unpacker{{'a', 'b'}, {'c', 'd'}, {'e', 'f'}} do
print(a .. b)
end
]])
it("accepts nested unresolved values", util.lax_check([[
function fun(xss)
for _, xs in pairs(xss) do
for _, x in pairs(xs) do
for _, u in ipairs({}) do
local v = x[u]
_, v = next(v)
end
end
end
end
]], {
{ msg = "xss" },
{ msg = "_" },
{ msg = "xs" },
{ msg = "_" },
{ msg = "x" },
{ msg = "u" },
{ msg = "v" },
}))
end)
end)
|
local sendText = ""
local printText = false
local Wins_Offset = Hack.GetOffset("DT_CSPlayerResource", "m_iCompetitiveWins")
local Rank_Offset = Hack.GetOffset("DT_CSPlayerResource", "m_iCompetitiveRanking")
local Team_Offset = Hack.GetOffset("DT_BaseEntity", "m_iTeamNum")
function Split (inputstr, sep)
if sep == nil then
sep = "%s"
end
local t={}
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
table.insert(t, str)
end
return t
end
--thx NizeL
function BuildData(msg_data)
local SpaceIdx = 0
for i = 1, string.len(msg_data) do
if (string.byte(string.sub(msg_data, i, i)) == 34) then
SpaceIdx = i
break
end
end
local ChatName = string.sub(msg_data, 1, SpaceIdx-1)
local ChatText = string.sub(msg_data, SpaceIdx)
return {ChatName, ChatText}
end
Hack.RegisterCallback("DispatchUserMessage", function (type, a3, length, data)
if type ~= 6 then return end
local msg = {}
local ChatType = ""
if (data:find("Cstrike_Chat_All", 0)) then
ChatType = "Cstrike_Chat_All"
data = string.sub(data, string.find(data, "Cstrike_Chat_All") + string.len("Cstrike_Chat_All") + 1)
msg = BuildData(data)
elseif (data:find("Cstrike_Chat_CT", 0)) then
ChatType = "Cstrike_Chat_CT"
data = string.sub(data, string.find(data, "Cstrike_Chat_CT") + string.len("Cstrike_Chat_CT") + 1)
msg = BuildData(data)
elseif (data:find("Cstrike_Chat_T", 0)) then
ChatType = "Cstrike_Chat_T"
data = string.sub(data, string.find(data, "Cstrike_Chat_T") + string.len("Cstrike_Chat_T") + 1)
msg = BuildData(data)
end
if #msg == 0 then return end
local username = msg[1]
local text = msg[2]
local args = Split(text, " ")
local ranks = {
"Unranked",
"Silver I",
"Silver II",
"Silver III",
"Silver IV",
"Silver Elite",
"Silver Elite Master",
"Gold Nova I",
"Gold Nova II",
"Gold Nova III",
"Gold Nova Master",
"Master Guardian I",
"Master Guardian II",
"Master Guardian Elite",
"Distinguished Master Guardian",
"Legendary Eagle",
"Legendary Eagle Master",
"Supreme Master First Class",
"The Global Elite"
}
if string.match(args[1], "$dumpwins") then
local returnText = string.sub(text, string.len(args[1]) + 1):sub(1, -2)
local p = {}
local ct = {}
for i=1, 64 do
local Player = IEntityList.GetPlayer(i)
if not Player then goto continue end
local team = Player:GetPropInt(Team_Offset)
if team == 2 then table.insert(p, i) elseif team == 3 then table.insert(ct, i) end
::continue::
end
for i=1, #ct do table.insert(p, ct[i]) end
for i=1, #p do
local Player = IEntityList.GetPlayer(p[i])
if not Player then goto continue end
local PlayerInfo = CPlayerInfo.new()
if (not Player:GetPlayerInfo(PlayerInfo)) then goto continue end
local resource = Player:GetPlayerResource()
local wins = resource:GetPropInt(Wins_Offset)
local rank = resource:GetPropInt(Rank_Offset)
local team = Player:GetPropInt(Team_Offset)
local color = "\x02"
if team == 2 then color = "\x09" elseif team == 3 then color = "\x0C" end
if PlayerInfo.szName == "GOTV" or PlayerInfo.fakeplayer then goto continue end
--IChatElement.ChatPrintf(0, 0, color .. PlayerInfo.szName .. ":\x01 " .. wins .. " Wins (" .. ranks[rank+1] .. ")")
IChatElement.ChatPrintf(0, 0, " " .. color .. PlayerInfo.szName .. ":\x01 " .. wins .. " Wins (" .. ranks[rank+1] .. ")")
::continue::
end
data = ""
end
if string.match(args[1], "$wins") then
local returnText = string.sub(text, string.len(args[1]) + 1):sub(1, -2)
local p = {}
local ct = {}
for i=1, 64 do
local Player = IEntityList.GetPlayer(i)
if not Player then goto continue end
local team = Player:GetPropInt(Team_Offset)
if team == 2 then table.insert(p, i) elseif team == 3 then table.insert(ct, i) end
::continue::
end
for i=1, #ct do table.insert(p, ct[i]) end
for i=1, #p do
local Player = IEntityList.GetPlayer(p[i])
if not Player then goto continue end
local PlayerInfo = CPlayerInfo.new()
if (not Player:GetPlayerInfo(PlayerInfo)) then goto continue end
local resource = Player:GetPlayerResource()
local wins = resource:GetPropInt(Wins_Offset)
local rank = resource:GetPropInt(Rank_Offset)
local team = Player:GetPropInt(Team_Offset)
local color = "???: "
if team == 2 then color = "T: " elseif team == 3 then color = "CT: " end
if PlayerInfo.szName == "GOTV" or PlayerInfo.fakeplayer then goto continue end
--IChatElement.ChatPrintf(0, 0, color .. PlayerInfo.szName .. ":\x01 " .. wins .. " Wins (" .. ranks[rank+1] .. ")")
--Print("say " .. color .. PlayerInfo.szName .. ": " .. wins .. " Wins (" .. ranks[rank+1] .. ")")
IEngine.ExecuteClientCmd("say " .. color .. PlayerInfo.szName .. ": " .. wins .. " Wins (" .. ranks[rank+1] .. ")")
Sleep(0.8)
::continue::
end
data = ""
end
end)
Hack.RegisterCallback("CreateMove", function (cmd, send)
if printText then
IChatElement.ChatPrintf(0, 0, "\x01Set your clantag to \"\x02" .. sendText .. "\x01\"")
printText = false
end
end) |
-- Privates variables
local cdBarWin = nil
local isIn = 'H' --[[ 'H' = horizontal; 'V' = vertical ]]--
local namesAtks = ''
local icons = {}
-- End privates variables
-- Public functions
function init()
cdBarWin = g_ui.displayUI('cdBar', modules.game_interface.getRootPanel())
cdBarWin:setVisible(false)
cdBarWin:move(250,50)
connect(g_game, 'onTextMessage', getParams)
connect(g_game, { onGameEnd = hide } )
connect(LocalPlayer, { onLevelChange = onLevelChange })
g_mouse.bindPress(cdBarWin, function() createMenu() end, MouseRightButton)
createIcons()
end
function terminate()
disconnect(g_game, { onGameEnd = hide })
disconnect(g_game, 'onTextMessage', getParams)
disconnect(LocalPlayer, { onLevelChange = onLevelChange })
destroyIcons()
cdBarWin:destroy()
end
function onLevelChange(localPlayer, value, percent)
g_game.talk("/reloadCDs")
end
function getParams(mode, text)
if not g_game.isOnline() then return end
if mode == MessageModes.Failure then
if string.find(text, '12//,') then
if string.find(text, 'hide') then hide() else show() end
elseif string.find(text, '12|,') then
atualizarCDs(text)
elseif string.find(text, '12&,') then
FixTooltip(text)
end
end
end
function atualizarCDs(text)
if not g_game.isOnline() then return end
if not cdBarWin:isVisible() then return end
local t = text:explode(",")
table.remove(t, 1)
for i = 1, 12 do
local t2 = t[i]:explode("|")
barChange(i, tonumber(t2[1]), tonumber(t2[2]), tonumber(t2[3]))
end
end
function changePercent(progress, icon, perc, num, init)
if not cdBarWin:isVisible() then return end
if init then
progress:setPercent(0)
else
progress:setPercent(progress:getPercent()+perc)
end
if progress:getPercent() >= 100 then
progress:setText("")
return
end
progress:setText(num)
icons[icon:getId()].event = scheduleEvent(function() changePercent(progress, icon, perc, num-1) end, 1000)
end
function barChange(ic, num, lvl, lvlPoke)
if not g_game.isOnline() then return end
if not cdBarWin:isVisible() then return end
local icon = icons['Icon'..ic].icon
local progress = icons['Icon'..ic].progress
if not progress:getTooltip() then return end
local player = g_game.getLocalPlayer()
local pathOn = "moves_icon/"..progress:getTooltip().."_on.png"
icon:setImageSource(pathOn)
if num and num >= 1 then
cleanEvents('Icon'..ic)
changePercent(progress, icon, 100/num, num, true)
else
if (lvlPoke and lvlPoke < lvl) or player:getLevel() < lvl then
progress:setPercent(0)
progress:setText('L.'.. lvl)
progress:setColor('#FF0000')
else
progress:setPercent(100)
progress:setText("")
end
end
end
function FixTooltip(text)
cdBarWin:setHeight(isIn == 'H' and 416 or 40)
cdBarWin:setWidth(isIn == 'H' and 40 or 416)
if not text then text = namesAtks else namesAtks = text end
local t2 = text:explode(",")
local count = 0
for j = 2, 13 do
local ic = icons['Icon'..(j-1)]
ic.icon:setMarginLeft(isIn == 'H' and 4 or ic.dist)
ic.icon:setMarginTop(isIn == 'H' and ic.dist or 4)
if t2[j] == 'n/n' then
ic.icon:hide()
count = count+1
else
ic.icon:show()
ic.progress:setTooltip(t2[j])
ic.progress:setVisible(true)
end
end
if count > 0 and count ~= 12 then
if isIn == "H" then
cdBarWin:setHeight(416 - (count*34))
else
cdBarWin:setWidth(416 - (count*34))
end
elseif count == 12 then
cdBarWin:setHeight(40)
cdBarWin:setWidth(40)
local p = icons['Icon1'].progress
p:setTooltip(false)
p:setVisible(false)
end
end
function createIcons()
local d = 38
for i = 1, 12 do
local icon = g_ui.createWidget('SpellIcon', cdBarWin)
local progress = g_ui.createWidget('SpellProgress', cdBarWin)
icon:setId('Icon'..i)
progress:setId('Progress' ..i)
icons['Icon'..i] = {icon = icon, progress = progress, dist = (i == 1 and 5 or i == 2 and 38 or d + ((i-2)*34)), event = nil}
icon:setMarginTop(icons['Icon'..i].dist)
icon:setMarginLeft(4)
progress:fill(icon:getId())
progress.onClick = function() g_game.talk('m'..i) end
end
end
function destroyIcons()
for i = 1, 12 do
icons['Icon'..i].icon:destroy()
icons['Icon'..i].progress:destroy()
end
cleanEvents()
icons = {}
end
function cleanEvents(icon)
local e = icons[icon]
if icon then
if e and e.event ~= nil then
removeEvent(e.event)
e.event = nil
end
else
for i = 1, 12 do
e = icons['Icon'..i]
cleanEvents('Icon'..i)
e.progress:setPercent(100)
e.progress:setText("")
end
end
end
function createMenu()
local menu = g_ui.createWidget('PopupMenu')
menu:addOption("Set "..(isIn == 'H' and 'Vertical' or 'Horizontal'), function() toggle() end)
menu:display()
end
function toggle()
if not cdBarWin:isVisible() then return end
cdBarWin:setVisible(false)
if isIn == 'H' then
isIn = 'V'
else
isIn = 'H'
end
FixTooltip()
show()
end
function hide()
cleanEvents()
cdBarWin:setVisible(false)
end
function show()
cdBarWin:setVisible(true)
end
-- End public functions |
////////////////////////////////////////
// Maax´s Libary (MLIB) //
// Coded by: Maax //
// //
// Version: v1.0 (Workshop) //
// //
// You are not permitted to //
// reupload this Script! //
// //
////////////////////////////////////////
local PANEL = {}
function PANEL:Init()
self:SetText("")
self:SetColor(Color(255,0,0))
self:SetColorHoverd(Color(230,0,0))
self:SetFont("MLIB.Button")
self:SetTextColor(Color(255,255,255))
self:SetContentAlignment(5)
self:SetGradient(false)
self:SetTextColor(color_white)
self.ButtonAlpha = 255
self.SetText = function(self, text)
self._sText = text
end
self.GetText = function(self)
return self._sText
end
end
function PANEL:SizeToContentsX(padding)
if padding == nil then padding = 0
end
surface.SetFont(self:GetFont())
local tw = surface.GetTextSize(self:GetText())
self:SetWide(tw + padding)
end
function PANEL:IsGradient()
return self._bUniform
end
function PANEL:SetGradient(bBool)
self._bUniform = bBool
end
function PANEL:SetColor(color)
self.Color = color
end
function PANEL:SetColorHoverd(color)
self.ColorHoverd = color
end
function PANEL:SetTextColor(color)
self.ColorText = color
end
function PANEL:RoundFromTallness()
self:SetRoundness(self:GetTall())
end
function PANEL:SetContentAlignment(iInteger)
self._iHorizontalAlignment = (iInteger - 1) % 3
self._iVerticalAlignment = (iInteger == 5 or iInteger == 6 or iInteger == 4) and 1 or (iInteger == 1 or iInteger == 2 or iInteger == 3) and 4 or 3
self._bTopAligned = self._iVerticalAlignment == 3
self._bBottomAligned = self._iVerticalAlignment == 4
self._bLeftAligned = self._iHorizontalAlignment == 0
self._bRightAligned = self._iHorizontalAlignment == 2
end
function PANEL:Paint(w, h)
draw.RoundedBox(4, 0,0, w,h,self.Color)
if self:IsHovered() then
draw.RoundedBox(4, 0,0, w,h,self.ColorHoverd)
end
draw.SimpleText(self:GetText(), self:GetFont(),self:GetWide() / 2,self:GetTall() / 2,self.ColorText, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
vgui.Register("MLIB.Button", PANEL, "DButton")
|
local assert = require('luassert')
local formatter = require('legendary.formatter')
describe('formatter', function()
describe('format(item)', function()
it('formats properly with default formatter', function()
-- ensure using default function
require('legendary.config').formatter = nil
local item = { '<leader>c', ':CommentToggle<CR>', description = 'Toggle comment', mode = { 'n', 'v' } }
local formatted = formatter.format(item)
assert.are.same(formatted, 'n, v │ <leader>c │ Toggle comment')
end)
it('formats properly with custom formatter function', function()
require('legendary.config').formatter = function(item)
return {
item[1],
item[2],
table.concat(item.mode, '│'),
}
end
local item = { '<leader>c', ':CommentToggle<CR>', description = 'Toggle comment', mode = { 'n', 'v' } }
local formatted = formatter.format(item)
assert.are.same(formatted, '<leader>c │ :CommentToggle<CR> │ n│v')
end)
it('formats properly with a different number of columns', function()
require('legendary.config').formatter = function(item)
return {
item[1],
item[2],
table.concat(item.mode, '│'),
item.description,
}
end
local item = { '<leader>c', ':CommentToggle<CR>', description = 'Toggle comment', mode = { 'n', 'v' } }
local formatted = formatter.format(item)
assert.are.same(formatted, '<leader>c │ :CommentToggle<CR> │ n│v │ Toggle comment')
end)
end)
describe('update_padding(item)', function()
before_each(function()
formatter.__clear_padding()
end)
it('sets padding to the length of the longest value in each column', function()
require('legendary.config').formatter = function(item)
return {
item[1],
item[2],
item.description,
}
end
local items = {
{ '<leader>c', ':CommentToggle<CR>', description = 'Toggle comment' },
{ '<leader>s', ':wa<CR>', description = 'Write all buffers' },
{ 'gd', 'lua vim.lsp.buf.definition', description = 'Go to definition with LSP' },
}
vim.tbl_map(function(item)
formatter.update_padding(item)
end, items)
local padding = formatter.get_padding()
assert.are.same(#padding, 3)
assert.are.same(padding[1], #'<leader>c')
assert.are.same(padding[2], #'lua vim.lsp.buf.definition')
assert.are.same(padding[3], #'Go to definition with LSP')
end)
it('computes length correctly when string contains unicode characters', function()
require('legendary.config').formatter = function(item)
return {
item[1],
item[2],
item.description,
}
end
local items = {
{ '∆', '', description = '' },
{ '˚', '', description = '' },
{ 'ݑ', '', description = '' },
}
vim.tbl_map(function(item)
formatter.update_padding(item)
end, items)
local padding = formatter.get_padding()
assert.are.same(#padding, 1)
assert.are.same(padding[1], 1)
end)
end)
describe('lpad(str)', function()
it(
'padds all strings to have the same length based on the padding table, accounting for unicode characters',
function()
require('legendary.config').formatter = function(item)
return {
item[1],
item[2],
item.description,
}
end
local items = {
{ '<leader>c', ':CommentToggle<CR>', description = 'Toggle comment' },
{ '<leader>s', ':wa<CR>', description = 'Write all buffers' },
{ 'gd', 'lua vim.lsp.buf.definition', description = 'Go to definition with LSP' },
{ '∆', ':echo "test"<CR>', description = 'Contains a triangle' },
{ '˚', ':lua print("test")<CR>', description = 'Contains a unicode dot' },
{ 'ݑ', ':e<CR>', description = 'Contains a unicode character' },
}
vim.tbl_map(function(item)
formatter.update_padding(item)
end, items)
local padded = {}
local padding = formatter.get_padding()
vim.tbl_map(function(item)
table.insert(padded, {
formatter.rpad(item[1], padding[1]),
formatter.rpad(item[2], padding[2]),
formatter.rpad(item[3], padding[3]),
})
end, items)
for i, _ in pairs(padded) do
if i < #padded then
assert.are.same(vim.fn.strdisplaywidth(padded[i][1]), vim.fn.strdisplaywidth(padded[i + 1][1]))
assert.are.same(vim.fn.strdisplaywidth(padded[i][2]), vim.fn.strdisplaywidth(padded[i + 1][2]))
assert.are.same(vim.fn.strdisplaywidth(padded[i][3]), vim.fn.strdisplaywidth(padded[i + 1][3]))
end
end
end
)
end)
end)
|
-- Tue Aug 6 00:54:24 2019
-- (c) Alexander Veledzimovich
-- set PHOTON
-- lua<5.3
local utf8 = require('utf8')
local unpack = table.unpack or unpack
local SET = {
APPNAME = love.window.getTitle(),
VER = '1.5',
SAVE = 'photonsave.lua',
FULLSCR = love.window.getFullscreen(),
WID = love.graphics.getWidth(),
HEI = love.graphics.getHeight(),
MIDWID = love.graphics.getWidth() / 2,
MIDHEI = love.graphics.getHeight() / 2,
SCALE = {1,1},
DELAY = 0.4,
EMPTY = {0,0,0,0},
WHITE = {1,1,1,1},
BLACK = {0,0,0,1},
RED = {1,0,0,1},
GREEN = {0,1,0,1},
BLUE = {0,0,1,1},
GRAY = {0.5,0.5,0.5,1},
DARKGRAY = {32/255,32/255,32/255,1},
MAINFNT = nil,
GROUPMARGIN = 5,
SINGHEI = 16,
DOUBHEI = 20,
FORMHEI = 196,
COLORROWHEI = 20,
COLORBOXHEI = 256,
PICKERHEI = 128,
MAXHEX = '#ffffffff',
MARKRAD = 4,
IMGEXT = {'png','jpg','jpeg'},
PHTEXT = 'pht',
TMPDIR = 'tmp',
DEFPATH = '',
PREVIEWSIZE = 256,
PBUFFER = 65536,
PWH = 512,
PSIZE = 8,
PEMIT = 4096,
PTIME = 64,
PSPEED = 2048,
PI = math.pi,
PI2 = math.pi*2,
PQUAD = 16,
COLORS = {
['text'] = '#afafaf',
['window'] = '#2d2d2d',
['header'] = '#282828',
['border'] = '#414141',
['button'] = '#424242',
['button hover'] = '#585858',
['button active'] = '#232323',
['toggle'] = '#646464',
['toggle hover'] = '#787878',
['toggle cursor'] = '#2d2d2d',
['select'] = '#2d2d2d',
['select active'] = '#234343',
['slider'] = '#262626',
['slider cursor'] = '#646464',
['slider cursor hover'] = '#787878',
['slider cursor active'] = '#969696',
['property'] = '#262626',
['edit'] = '#262626',
['edit cursor'] = '#afafaf',
['combo'] = '#2d2d2d',
['chart'] = '#787878',
['chart color'] = '#2d2d2d',
['chart color highlight'] = '#ff0000',
['scrollbar'] = '#282828',
['scrollbar cursor'] = '#646464',
['scrollbar cursor hover'] = '#787878',
['scrollbar cursor active'] = '#969696',
['tab header'] = '#282828'
}
}
SET.VIEWWID = SET.MIDWID
SET.VIEWHEI = SET.MIDHEI
SET.CODEWID = SET.MIDWID
SET.CODEHEI = SET.MIDHEI
SET.EDWID = SET.MIDWID
SET.EDHEI = SET.HEI
SET.BGCLR = SET.DARKGRAY
SET.TXTCLR = SET.WHITE
return SET
|
local registry = require 'lulz.types.registry'
local types = {}
types.type = require 'lulz.types.type'
types.declare = types.type.declare
for name, tp in pairs(require 'lulz.types.builtin') do
types[name] = tp
end
types.find = registry.find
function types.isinstance(obj, tp)
if rawget(tp, 'isinstance') then return tp.isinstance(obj, tp) end
if type(obj) ~= 'table' then return false end
return rawget(obj, '__type__') == tp
end
function types.istype(obj)
return types.isinstance(obj, types.type)
end
function types.typeof(obj)
local typename = type(obj)
if typename ~= 'table' then return types[typename] end
local tp = rawget(obj, '__type__')
if tp and types.isinstance(tp, types.type) then
return tp
end
return types.table
end
return types
|
require("prototypes.constants")
require("prototypes.functions")
--This exists to test the theory of whether you need 1 input per fluid box for max flow, or if you
-- can get away with one fluidbox that has multiple inputs. This function will be used if it can flow at max.
function createOilMultipleFluidboxConnections(entity, recipe_data, side_length)
local side_length_x = entity.drawing_box[2][1] - 0.5
local side_length_y = entity.drawing_box[2][2] + 0.5
local INPUT_SPACING = settings.startup["oil-input-spacing"].value
local OUTPUT_SPACING = settings.startup["oil-output-spacing"].value
--Pipe layout for inputs: Extreme top and bottom edge.
entity.fluid_boxes = nil
entity.fluid_boxes = {
{
base_level = -1,
pipe_connections = {
{
position = {side_length_x, side_length_y},
type = "input"
}
},
production_type = "input"
},
{
base_level = -1,
pipe_connections = {
{
position = {-1*side_length_x, side_length_y},
type = "input"
}
},
production_type = "input"
},
--outputs, ordered by the recipe; heavy->light->PG. Changing this order breaks stuff.
{
base_level = 1,
pipe_connections = {
{
position = {side_length_x, -1*side_length_y},
type = "output"
}
},
production_type = "output"
},
{
base_level = 1,
pipe_connections = {
{
position = {-1*side_length_x, -1*side_length_y},
type = "output"
}
},
production_type = "output"
},
--Heavy and light might need cracking, but PG always gets exported, so it goes in the center.
{
base_level = 1,
pipe_connections = {
{
position = {0, -1*side_length_y},
type = "output"
}
},
production_type = "output"
},
}
--Now that we have the basics established, adding additional connections is easy.
for i,data in pairs(recipe_data["inputs"]) do
--entity.fluid_boxes[i].base_area = data["connections_needed"]*(MAX_FLUID_PER_INPUT_PER_SECOND/100)
for pipe_idx = 2,data["connections_needed"],1 do
local previous_x = entity.fluid_boxes[i].pipe_connections[pipe_idx - 1].position[1]
local previous_y = entity.fluid_boxes[i].pipe_connections[pipe_idx - 1].position[2]
if previous_x < 0 then
previous_x = previous_x + INPUT_SPACING
else
previous_x = previous_x - INPUT_SPACING
end
table.insert(entity.fluid_boxes[i].pipe_connections, { position = {previous_x, previous_y}, type = "input" })
end
end
--output is a bit more complex because there are 3 pipes, 2 on the edges, one in the center.
local toggle = false
for i,data in pairs(recipe_data["outputs"]) do
for pipe_idx = 2,data["connections_needed"],1 do
local previous_x = entity.fluid_boxes[i+2].pipe_connections[pipe_idx - 1].position[1]
local previous_y = entity.fluid_boxes[i+2].pipe_connections[pipe_idx - 1].position[2]
if i == 3 then
if toggle then
previous_x = previous_x + OUTPUT_SPACING*(pipe_idx-1)
toggle = not toggle
else
previous_x = previous_x - OUTPUT_SPACING*(pipe_idx-1)
toggle = not toggle
end
else
if previous_x < 0 then
previous_x = previous_x + OUTPUT_SPACING
else
previous_x = previous_x - OUTPUT_SPACING
end
end
table.insert(entity.fluid_boxes[i+2].pipe_connections, { position = {previous_x, previous_y}, type = "output" })
end
end
end
function createChemMultipleFluidboxConnections(entity, recipe_data, side_length)
local side_length_x = entity.drawing_box[2][1] - 0.5
local side_length_y = entity.drawing_box[2][2] + 0.5
local INPUT_SPACING = settings.startup["oil-input-spacing"].value
local OUTPUT_SPACING = settings.startup["oil-output-spacing"].value
--This makes it so we can directly attach cracking ASIFs to the refinery.
if entity.name == "lc-asif"
then
side_length_x = -1 * side_length_x
end
--Pipe layout for inputs: Extreme top and bottom edge.
entity.fluid_boxes = nil
entity.fluid_boxes = {
{
base_level = -1,
pipe_connections = {
{
position = {side_length_x, side_length_y},
type = "input"
}
},
production_type = "input"
},
{
base_level = -1,
pipe_connections = {
{
position = {-1*side_length_x, side_length_y},
type = "input"
}
},
production_type = "input"
},
--outputs, ordered by the recipe; heavy->light->PG. Changing this order breaks stuff.
{
base_level = 1,
pipe_connections = {
{
position = {side_length_x, -1*side_length_y},
type = "output"
}
},
production_type = "output"
},
{
base_level = 1,
pipe_connections = {
{
position = {-1*side_length_x, -1*side_length_y},
type = "output"
}
},
production_type = "output"
}
}
--Now that we have the basics established, adding additional connections is easy.
for i,data in pairs(recipe_data["inputs"]) do
for pipe_idx = 2,data["connections_needed"],1 do
local previous_x = entity.fluid_boxes[i].pipe_connections[pipe_idx - 1].position[1]
local previous_y = entity.fluid_boxes[i].pipe_connections[pipe_idx - 1].position[2]
if previous_x < 0 then
previous_x = previous_x + INPUT_SPACING
else
previous_x = previous_x - INPUT_SPACING
end
table.insert(entity.fluid_boxes[i].pipe_connections, { position = {previous_x, previous_y}, type = "input" })
end
end
for i,data in pairs(recipe_data["outputs"]) do
for pipe_idx = 2,data["connections_needed"],1 do
local previous_x = entity.fluid_boxes[i+2].pipe_connections[pipe_idx - 1].position[1]
local previous_y = entity.fluid_boxes[i+2].pipe_connections[pipe_idx - 1].position[2]
if previous_x < 0 then
previous_x = previous_x + OUTPUT_SPACING
else
previous_x = previous_x - OUTPUT_SPACING
end
table.insert(entity.fluid_boxes[i+2].pipe_connections, { position = {previous_x, previous_y}, type = "output" })
end
end
end
--Testing was done on whether to use one fluid box per type with many inputs,
-- or one fluidbox per input. The result was ???
function createOilMultipleOilFluidBoxes(entity, recipe_data, side_length)
local side_length_y = side_length + 0.5
local side_length_x = side_length - 0.5
local INPUT_SPACING = settings.startup["oil-input-spacing"].value
local OUTPUT_SPACING = settings.startup["oil-output-spacing"].value
--Pipe layout for inputs: Extreme top and bottom edge.
entity.fluid_boxes = nil
entity.fluid_boxes = {
{
base_level = -1,
pipe_connections = {
{
position = {side_length_x, side_length_y},
type = "input"
}
},
production_type = "input",
--You cannot change the filters without also changing the order of recipe_data.
filter = "water"
},
{
base_level = -1,
pipe_connections = {
{
position = {-1*side_length_x, side_length_y},
type = "input"
}
},
production_type = "input",
filter = "crude-oil"
},
--outputs, ordered by the recipe; heavy->light->PG. Changing this order breaks stuff.
{
base_level = 1,
pipe_connections = {
{
position = {0, -1*side_length_y},
type = "output"
}
},
production_type = "output",
filter = "heavy-oil"
},
{
base_level = 1,
pipe_connections = {
{
position = {-1*side_length_x, -1*side_length_y},
type = "output"
}
},
production_type = "output",
filter = "light-oil"
},
{
base_level = 1,
pipe_connections = {
{
position = {side_length_x, -1*side_length_y},
type = "output"
}
},
production_type = "output",
filter = "petroleum-gas"
},
}
--Now that we have the basics established, adding additional connections is easy.
for i,data in pairs(recipe_data["inputs"]) do
local previous_x = entity.fluid_boxes[i].pipe_connections[1].position[1]
local previous_y = entity.fluid_boxes[i].pipe_connections[1].position[2]
for pipe_idx = 2,data["connections_needed"],1 do
if previous_x < 0 then
previous_x = previous_x + INPUT_SPACING
else
previous_x = previous_x - INPUT_SPACING
end
table.insert(entity.fluid_boxes,
{
base_level = -1,
pipe_connections = {{ position = {previous_x, previous_y}, type = "input" }},
production_type = "input",
filter = data["name"]
}
)
end
end
--output is a bit more complex because there are 3 pipes, 2 on the edges, one in the center.
local toggle = false
for i,data in pairs(recipe_data["outputs"]) do
local previous_x = entity.fluid_boxes[i+2].pipe_connections[1].position[1]
local previous_y = entity.fluid_boxes[i+2].pipe_connections[1].position[2]
for pipe_idx = 2,data["connections_needed"],1 do
if i == 1 then
if toggle then
previous_x = previous_x + OUTPUT_SPACING*(pipe_idx-1)
toggle = not toggle
else
previous_x = previous_x - OUTPUT_SPACING*(pipe_idx-1)
toggle = not toggle
end
else
if previous_x < 0 then
previous_x = previous_x + OUTPUT_SPACING
else
previous_x = previous_x - OUTPUT_SPACING
end
end
table.insert(entity.fluid_boxes,
{
base_level = 1,
pipe_connections = {{ position = {previous_x, previous_y}, type = "output" }},
production_type = "output",
filter = data["name"]
}
)
end
end
end
--We need to know how many pipe connections, we get that from the recipe the ASIF uses.
function createOilRefEntity(name, compression_ratio, recipe_data)
--Pollution
--modify here if you wish to create separate entities for normal/expensive mode.
local total_pollution_value = oil_base_pollution * (oil_per_unit_pwr_drain_penalty * (prod_mod_pollution_penalty * oil_base_modules + 1)) * compression_ratio
local new_entity = util.table.deepcopy(base_oil_entity)
local draw, drain = ComputePowerDrainAndDraw(compression_ratio, oil_total_pwr_draw)
new_entity.fixed_recipe = name .. "-recipe"
new_entity.name = name
new_entity.crafting_speed = 1
new_entity.crafting_categories = { name }
new_entity.energy_source.emissions_per_minute = total_pollution_value
new_entity.energy_source.drain = drain .. "kW"
new_entity.energy_usage = draw .. "kW"
new_entity.allowed_effects = nil
new_entity.module_specification.module_slots = 0
new_entity.scale_entity_info_icon = true
--new_entity.base_productivity = .1*oil_base_modules
new_entity.fast_replaceable_group = name
new_entity.minable.result = name
if settings.startup["ass-alt-map-color"].value then
new_entity.map_color = GRAPHICS_MAP[name].tint
end
--If you tuned a chem plant with a compression_ratio of 27, then enter '27' here.
local TUNED_SCALE_FACTOR = 63
TUNED_SCALE_FACTOR = TUNED_SCALE_FACTOR/2
--params: bld size, beacons on one side per bld, compression ratio
new_drawing_box_size, scale_factor = getScaleFactors(5, 5, compression_ratio, true)
local new_collison_size = new_drawing_box_size - 0.3
local override_size = settings.startup["max-bld-size"].value
local edge_art = nil
if override_size ~= 0
then
new_drawing_box_size = override_size / 2
new_collison_size = new_drawing_box_size - 0.3
--This is /3 instead of /5 because the max bld sizes are all multiples of 3, 3 and 5 are both prime.
scale_factor = override_size / 4 / 2
--We want this before the scale factor gets reduced below.
edge_art = {
filename = "__AssemblerUPSGrade__/graphics/entity/oil-border.png",
frame_count = new_entity.animation["north"].layers[1].frame_count,
height = 256,
priority = "high",
scale = scale_factor,
width = 256,
}
else
--We want this before the scale factor gets reduced below.
edge_art = {
filename = "__AssemblerUPSGrade__/graphics/entity/oil-border.png",
frame_count = new_entity.animation["north"].layers[1].frame_count,
height = 256,
priority = "high",
scale = scale_factor * 1.247,
width = 256,
}
end
--The building is slightly too large overall, so make it a touch smaller.
scale_factor = scale_factor - .5
for i,_ in pairs(new_entity.working_visualisations) do
--flame
if new_entity.working_visualisations[i].animation then
new_entity.working_visualisations[i].animation.scale = scale_factor
new_entity.working_visualisations[i].animation.hr_version.scale = scale_factor
new_entity.working_visualisations[i].animation.shift[1] = new_entity.working_visualisations[i].animation.shift[1] * scale_factor
new_entity.working_visualisations[i].animation.shift[2] = new_entity.working_visualisations[i].animation.shift[2] * scale_factor
new_entity.working_visualisations[i].animation.hr_version.shift[1] = new_entity.working_visualisations[i].animation.hr_version.shift[1] * scale_factor
new_entity.working_visualisations[i].animation.hr_version.shift[2] = new_entity.working_visualisations[i].animation.hr_version.shift[2] * scale_factor
--Water input bottom-right
new_entity.working_visualisations[i]["north_position"][1] = (new_entity.working_visualisations[i]["north_position"][1] + 1) * scale_factor -- + is right, - is left
new_entity.working_visualisations[i]["north_position"][2] = (new_entity.working_visualisations[i]["north_position"][2] - 2.5) * scale_factor --+ is down, - is up
--Water input bottom-left
new_entity.working_visualisations[i]["east_position"][1] = (new_entity.working_visualisations[i]["east_position"][1] - 1.5) * scale_factor
new_entity.working_visualisations[i]["east_position"][2] = (new_entity.working_visualisations[i]["east_position"][2] - 2.05) * scale_factor
--Water input top-right
new_entity.working_visualisations[i]["west_position"][1] = (new_entity.working_visualisations[i]["west_position"][1] + 1.7) * scale_factor
new_entity.working_visualisations[i]["west_position"][2] = (new_entity.working_visualisations[i]["west_position"][2] - 2.05) * scale_factor
--Water input top-left
new_entity.working_visualisations[i]["south_position"][1] = (new_entity.working_visualisations[i]["south_position"][1] - 1.75) * scale_factor
new_entity.working_visualisations[i]["south_position"][2] = (new_entity.working_visualisations[i]["south_position"][2] - 2.75) * scale_factor
else
--Glow at base of flame
for _, dir in pairs({"north_animation","east_animation","west_animation","south_animation"}) do
new_entity.working_visualisations[i][dir].scale = scale_factor
new_entity.working_visualisations[i][dir].hr_version.scale = scale_factor
new_entity.working_visualisations[i][dir].shift[1] = (new_entity.working_visualisations[i][dir].shift[1] - .05) * scale_factor
new_entity.working_visualisations[i][dir].shift[2] = (new_entity.working_visualisations[i][dir].shift[2] - 1.45) * scale_factor
new_entity.working_visualisations[i][dir].hr_version.shift[1] = (new_entity.working_visualisations[i][dir].hr_version.shift[1] - .05) * scale_factor -- + is right, - is left
new_entity.working_visualisations[i][dir].hr_version.shift[2] = (new_entity.working_visualisations[i][dir].hr_version.shift[2] - 1.45) * scale_factor --+ is down, - is up
--And there's always one fucking snowflake
if dir == "west_animation"
then
new_entity.working_visualisations[i][dir].shift[1] = new_entity.working_visualisations[i][dir].shift[1] + (-0.125 * scale_factor )
new_entity.working_visualisations[i][dir].hr_version.shift[1] = new_entity.working_visualisations[i][dir].hr_version.shift[1] + (-0.125 * scale_factor ) -- + is right, - is left
end
end
end
end
new_entity.alert_icon_scale = scale_factor
--Refinery itself
for _,dir in pairs({"north","east","south","west"}) do
for i,_ in pairs(new_entity.animation[dir].layers) do
-- new_entity.animation[dir].layers[i].shift[1] = new_entity.animation[dir].layers[i].shift[1] * scale_factor
new_entity.animation[dir].layers[i].shift[2] = new_entity.animation[dir].layers[i].shift[2] + (-2.5*(scale_factor/TUNED_SCALE_FACTOR))
-- new_entity.animation[dir].layers[i].hr_version.shift[1] = new_entity.animation[dir].layers[i].hr_version.shift[1] * scale_factor
new_entity.animation[dir].layers[i].hr_version.shift[2] = new_entity.animation[dir].layers[i].hr_version.shift[2] + (-2.5*(scale_factor/TUNED_SCALE_FACTOR))
new_entity.animation[dir].layers[i].scale = scale_factor
new_entity.animation[dir].layers[i].hr_version.scale = scale_factor
end
table.insert(new_entity.animation[dir].layers, edge_art)
end
new_entity.collision_box = { {-1*new_collison_size, -1*new_collison_size}, {new_collison_size,new_collison_size} }
new_entity.drawing_box = { {-1*new_drawing_box_size, -1*new_drawing_box_size}, {new_drawing_box_size,new_drawing_box_size} }
new_entity.selection_box = { {-1*new_drawing_box_size, -1*new_drawing_box_size}, {new_drawing_box_size,new_drawing_box_size} }
new_entity.icon = "__AssemblerUPSGrade__/graphics/" .. GRAPHICS_MAP[name].icon
new_entity.icon_size = 64
--Now we create the fluid boxes
createOilMultipleFluidboxConnections(new_entity, recipe_data, new_drawing_box_size)
--Multiple fluid boxes don't render. Only the first fluid box for a given type (whether or not 'filter' is used) renders.
--createOilMultipleOilFluidBoxes(new_entity, recipe_data, new_drawing_box_size)
createEntityRadar(name, new_drawing_box_size)
data:extend({new_entity})
end
function createCrackingChemPlantEntity(name, compression_ratio, recipe_data)
--Pollution
--modify here if you wish to create separate entities for normal/expensive mode.
local total_pollution_value = chem_base_pollution * (chem_per_unit_pwr_drain_penalty * (prod_mod_pollution_penalty * chem_base_modules + 1)) * compression_ratio
local new_entity = util.table.deepcopy(base_chem_entity)
local draw, drain = ComputePowerDrainAndDraw(compression_ratio, chem_total_pwr_draw)
new_entity.fixed_recipe = name .. "-recipe"
new_entity.name = name
new_entity.crafting_speed = 1
new_entity.crafting_categories = { name }
new_entity.energy_source.emissions_per_minute = total_pollution_value
new_entity.energy_source.drain = drain .. "kW"
new_entity.energy_usage = draw .. "kW"
new_entity.allowed_effects = nil
new_entity.module_specification.module_slots = 0
new_entity.scale_entity_info_icon = true
--new_entity.base_productivity = .1*chem_base_modules
new_entity.fast_replaceable_group = name
new_entity.minable.result = name
if settings.startup["ass-alt-map-color"].value then
new_entity.map_color = GRAPHICS_MAP[name].tint
end
--If you tuned a chem plant with a compression_ratio of 27, then enter '27' here.
local TUNED_SCALE_FACTOR = 27
TUNED_SCALE_FACTOR = TUNED_SCALE_FACTOR/2
local new_drawing_box_size = 0
local scale_factor = 0
--params: bld size, beacons on one side per bld, compression ratio
new_drawing_box_size, scale_factor = getScaleFactors(3, 4, compression_ratio, true)
local new_collison_size = new_drawing_box_size - 0.3
local override_size = settings.startup["max-bld-size"].value
if override_size ~= 0
then
new_drawing_box_size = override_size / 2
new_collison_size = new_drawing_box_size - 0.3
scale_factor = override_size / 3 / 2
end
--We want this before the scale factor gets reduced below.
local edge_art = {
filename = "__AssemblerUPSGrade__/graphics/entity/chem-border.png",
frame_count = new_entity.animation["north"].layers[1].frame_count,
line_length = 6,
height = 256,
priority = "high",
scale = scale_factor * .75,
width = 256,
}
--This is the smokestack color and the window color bit being scaled to the correct size.
for i,_ in pairs(new_entity.working_visualisations) do
--smokestack
if new_entity.working_visualisations[i].animation then
--All offsets taken with water in the bottom-right corner.
new_entity.working_visualisations[i].animation.scale = scale_factor
new_entity.working_visualisations[i].animation.hr_version.scale = scale_factor
new_entity.working_visualisations[i].animation.shift[1] = (new_entity.working_visualisations[i].animation.shift[1]) * scale_factor --+ is right, - is left
new_entity.working_visualisations[i].animation.shift[2] = (new_entity.working_visualisations[i].animation.shift[2] + .35) * scale_factor --+ is down, - is up
new_entity.working_visualisations[i].animation.hr_version.shift[1] = (new_entity.working_visualisations[i].animation.hr_version.shift[1]) * scale_factor
new_entity.working_visualisations[i].animation.hr_version.shift[2] = (new_entity.working_visualisations[i].animation.hr_version.shift[2] + .35) * scale_factor
for _, dir in pairs({"north_position","east_position","west_position","south_position"}) do
--And, for reasons unknown, west continues to be a problem.
if dir == "north_position" then
new_entity.working_visualisations[i][dir][1] = (new_entity.working_visualisations[i][dir][1] * 2 + .1) * scale_factor
--For reasons that are unclear to me, the outside smoke animation needs a little extra bump north for some reason.
if i == 3 then
new_entity.working_visualisations[i][dir][2] = (new_entity.working_visualisations[i][dir][2] * 2.25) * scale_factor
else
new_entity.working_visualisations[i][dir][2] = (new_entity.working_visualisations[i][dir][2] * 2) * scale_factor
end
else
new_entity.working_visualisations[i][dir][1] = (new_entity.working_visualisations[i][dir][1] * 2 - .2) * scale_factor --+ is right, - is left
--For reasons that are unclear to me, the outside smoke animation needs a little extra bump north for some reason.
if i == 3 then
new_entity.working_visualisations[i][dir][2] = (new_entity.working_visualisations[i][dir][2] * 2.25 - .1) * scale_factor --+ is down, - is up
else
new_entity.working_visualisations[i][dir][2] = (new_entity.working_visualisations[i][dir][2] * 2 - .1) * scale_factor --+ is down, - is up
end
end
end
else
--Mixing window
for _, dir in pairs({"north_animation","east_animation","west_animation","south_animation"}) do
new_entity.working_visualisations[i][dir].scale = scale_factor
new_entity.working_visualisations[i][dir].hr_version.scale = scale_factor
--And, for reasons unknown, east is out of alignment with the other animations.
if dir == "north_animation" then
new_entity.working_visualisations[i][dir].shift[1] = (new_entity.working_visualisations[i][dir].shift[1] + .5) * scale_factor
new_entity.working_visualisations[i][dir].shift[2] = (new_entity.working_visualisations[i][dir].shift[2] + .4) * scale_factor
new_entity.working_visualisations[i][dir].hr_version.shift[1] = (new_entity.working_visualisations[i][dir].hr_version.shift[1] + .5) * scale_factor
new_entity.working_visualisations[i][dir].hr_version.shift[2] = (new_entity.working_visualisations[i][dir].hr_version.shift[2] + .4) * scale_factor
else
new_entity.working_visualisations[i][dir].shift[1] = (new_entity.working_visualisations[i][dir].shift[1] + .1) * scale_factor --+ is right, - is left
new_entity.working_visualisations[i][dir].shift[2] = (new_entity.working_visualisations[i][dir].shift[2] + .6) * scale_factor --+ is down, - is up
new_entity.working_visualisations[i][dir].hr_version.shift[1] = (new_entity.working_visualisations[i][dir].hr_version.shift[1] + .1) * scale_factor
new_entity.working_visualisations[i][dir].hr_version.shift[2] = (new_entity.working_visualisations[i][dir].hr_version.shift[2] + .6) * scale_factor
end
end
end
end
scale_factor = scale_factor * .85
new_entity.alert_icon_scale = scale_factor
for _,dir in pairs({"north","east","south","west"})
do
for i,_ in pairs(new_entity.animation[dir].layers)
do
-- new_entity.animation[dir].layers[i].shift[1] = new_entity.animation[dir].layers[i].shift[1] * scale_factor
new_entity.animation[dir].layers[i].shift[2] = new_entity.animation[dir].layers[i].shift[2] - (1.5*(scale_factor/TUNED_SCALE_FACTOR))
-- new_entity.animation[dir].layers[i].hr_version.shift[1] = new_entity.animation[dir].layers[i].hr_version.shift[1] * scale_factor
new_entity.animation[dir].layers[i].hr_version.shift[2] = new_entity.animation[dir].layers[i].hr_version.shift[2] - (1.5*(scale_factor/TUNED_SCALE_FACTOR))
new_entity.animation[dir].layers[i].scale = scale_factor
new_entity.animation[dir].layers[i].hr_version.scale = scale_factor
end
table.insert(new_entity.animation[dir].layers, edge_art)
end
new_entity.collision_box = { {-1*new_collison_size, -1*new_collison_size}, {new_collison_size,new_collison_size} }
new_entity.drawing_box = { {-1*new_drawing_box_size, -1*(new_drawing_box_size)}, {new_drawing_box_size,new_drawing_box_size} }
new_entity.selection_box = { {-1*new_drawing_box_size, -1*new_drawing_box_size}, {new_drawing_box_size,new_drawing_box_size} }
new_entity.icon = "__AssemblerUPSGrade__/graphics/" .. GRAPHICS_MAP[name].icon
-- new_entity.icons = {
-- {
-- icon = "__AssemblerUPSGrade__/graphics/" .. GRAPHICS_MAP[name].icon,
-- icon_size = 64,
-- tint = GRAPHICS_MAP[name].tint
-- }
-- }
new_entity.icon_size = 64
createChemMultipleFluidboxConnections(new_entity, recipe_data, new_drawing_box_size)
createEntityRadar(name, new_drawing_box_size)
data:extend({new_entity})
end |
local BOOST = 300
local WIDTH = 1280
local HEIGHT = 720
dofile("game/Pipe.lua");
math.randomseed(os.time())
-- Set up the background layer
local background = newSprite(WIDTH, HEIGHT, 0, 0)
background:setTexture("res/bg.png");
local citybg = {
newSprite(WIDTH, 256, 0, HEIGHT - 310),
newSprite(WIDTH, 256, WIDTH, HEIGHT - 310)
}
for k, v in pairs(citybg) do
v:setTexture("res/city2.png");
end
local city = {
newSprite(WIDTH, 256, 0, HEIGHT - 320),
newSprite(WIDTH, 256, WIDTH, HEIGHT - 320)
}
for k, v in pairs(city) do
v:setTexture("res/city.png");
end
-- Set up the foregorund layer
local pipes = {
Pipe:new(0),
Pipe:new(1),
Pipe:new(2),
Pipe:new(3),
Pipe:new(4),
Pipe:new(5),
}
local grass = {
newSprite(WIDTH, 64, 0, HEIGHT - 64),
newSprite(WIDTH, 64, WIDTH, HEIGHT - 64)
}
for k, v in pairs(grass) do
v:setTexture("res/grass.png");
end
-- Set up the player
local bird = {
sprite = newSprite(64, 32, 100, 100),
vx = 0,
vy = 0
}
bird.sprite:setTexture("res/bird.png");
-- Parallax scrolling
local function parallax(table, speed, dt)
for _, v in pairs(table) do
v:move(-speed * dt, 0)
local x, y = v:getPosition()
if x < -WIDTH then
v:move(WIDTH * 2, 0)
end
end
end
local STATE_BEGIN = 0
local STATE_GAME = 1
local STATE_GAME_OVER = 2
local state = 0
local score = 0
local function gameover()
print("GAME OVER")
print("Score: " .. score)
print("Press space to reset...")
state = STATE_GAME_OVER
end
local function startGame()
print("Press space to begin...")
bird.vx = 0
bird.vy = 0
bird.sprite:setPosition(100, 100)
state = STATE_BEGIN
score= 0
i = 0
for _, pipe in pairs(pipes) do
pipe:reset(i)
i = i + 1
end
end
startGame()
local function stateBegin(dt)
if Keyboard.isKeyPressed("Space") then
state = STATE_GAME
print("Score: " .. score)
end
parallax(grass, 200, dt)
parallax(city, 100, dt)
parallax(citybg, 50, dt)
end
local function stateGame(dt)
if Keyboard.isKeyPressed("Space") and bird.vy > 0 then
bird.vy = -BOOST * dt
end
local x, y = bird.sprite:getPosition()
if y < 0 then
bird.sprite:move(0, -y)
bird.vy = 0
elseif y > HEIGHT - 64 then
gameover()
end
bird.vy = bird.vy + 10 * dt
bird.sprite:move(bird.vx, bird.vy)
bird.vx = bird.vx * 0.99
bird.vy = bird.vy * 0.99
for _, pipe in pairs(pipes) do
pipe:update(dt)
if pipe:xPos() < x and not pipe.dirty then
pipe.dirty = true
score = score + 1
print("Score: " .. score)
end
if bird.sprite:intersects(pipe.top) or bird.sprite:intersects(pipe.bottom) then
gameover()
end
end
parallax(grass, 200, dt)
parallax(city, 100, dt)
parallax(citybg, 50, dt)
end
local function stateGameover(dt)
local x, y = bird.sprite:getPosition()
if y < HEIGHT - 64 then
bird.vy = bird.vy + 5 * dt
else
bird.vy = 0
if Keyboard.isKeyPressed("Space") then
startGame()
end
end
bird.sprite:move(0, bird.vy)
bird.vy = bird.vy * 0.99
end
-- Function called once per frame from C++ side
function update(dt)
if state == STATE_BEGIN then
stateBegin(dt)
elseif state == STATE_GAME then
stateGame(dt)
elseif state == STATE_GAME_OVER then
stateGameover(dt)
end
end |
--Turtle
--A program that gives quick acces to all of the important functions of the turtle
local Tin = nil --Resets the value, if defined somewhere before
local Tin = {...} --(T)urtle(in)put Defines what the user wants the Turtle to do
HT = false --(H)ave (T)oggled This, and others like this, should be used if something is to be toggled.
if Tin[1] == nil then
print("Please enter what you would like the turtle to do, acceptable commands are:")
end
for i = 1, 1000 do
--Code for moving in the four directions
if Tin[i] == "GOF" then --Lets he turtle go forward, if more than one block is desired then the "GOF" should be followed by a number as next argument in the array
if tonumber(Tin[i + 1])then
for k = 1, Tin[i + 1] do
turtle.forward()
end
else
turtle.forward()
end
end
if Tin[i] == "GOB" then --Lets he turtle go back, if more than one block is desired then the "GOB" should be followed by a number as next argument in the array
if tonumber(Tin[i + 1])then
for k = 1, Tin[i + 1] do
turtle.back()
end
else
turtle.back()
end
end
if Tin[i] == "GOD" then --Lets he turtle go down, if more than one block is desired then the "GOD" should be followed by a number as next argument in the array
if tonumber(Tin[i + 1])then
for k = 1, Tin[i + 1] do
turtle.down()
end
else
turtle.down()
end
end
if Tin[i] == "GOU" then --Lets he turtle go up, if more than one block is desired then the "GOU" should be followed by a number as next argument in the array
if tonumber(Tin[i + 1])then
for k = 1, Tin[i + 1] do
turtle.up()
end
else
turtle.up()
end
end
--End of code for moving
--Code for rotating
if Tin[i] == "TRR" then --Rotates the turtle right, is followed by a number that many times
if tonumber(Tin[i + 1])then
for k = 1, Tin[i + 1] do
turtle.turnRight()
end
else
turtle.turnRight()
end
end
if Tin[i] == "TRL" then --Rotates the turtle left, is followed by a number that many times
if tonumber(Tin[i + 1])then
for k = 1, Tin[i + 1] do
turtle.turnLeft()
end
else
turtle.turnLeft()
end
end
--End of rotations
--Here follows the commands for placing and breaking blocks
if Tin[i] == "DGF" then --Makes the turtle dig
turtle.dig()
end
if Tin[i] == "DGU" then --Makes the turtle dig Up
turtle.digUp()
end
if Tin[i] == "DGD" then --Makes the turtle dig down
turtle.digDown()
end
if Tin[i] == "PLF" then --Makes the turtle place its current block
turtle.place()
end
if Tin[i] == "PLU" then --Makes the turtle place its current block upwawrds
turtle.placeUp()
end
if Tin[i] == "PLD" then --Makes the turtle place its current block downwards
turtle.placeDown()
end
--End of placing and breaking
--Code for selecting slot in inventory
if Tin[i] == "SLOT" then --Allows you to set the "inventory cursor"
if tonumber(Tin[i + 1]) then
Tin[i + 1] = Tin[i + 1] + 0
if Tin[i + 1] < 17 then
turtle.select(Tin[i + 1])
else
turtle.select(16)
end
else
turtle.select(1)
print("please follow SLOT with a number for a slot to switch to in the Turtles inventory, will now go to default (slot 1)")
end
end
--End of Slot
--FuelRelated
if Tin[i] == "REF" then --Refuels, follow with number for amount, 1 is default
if tonumber(Tin[i + 1]) then
Tin[i + 1] = Tin[i + 1] + 0 --If this is lacking, it says "turtle:18: Expected number
turtle.refuel(Tin[i + 1])
else
turtle.refuel(1)
end
end
if Tin[i] == "GFU" then --Check Fuel Level
print("Fuel level: "..turtle.getFuelLevel())
end
--End of Fuel related
--Drop / Suck commands
if Tin[i] == "DRF" then --Drops items
if tonumber(Tin[i + 1]) then
Tin[i + 1] = Tin[i + 1] + 0 --Gives an error message about line 18 if this is lacking
turtle.drop(Tin[i + 1])
else
turtle.drop(1)
end
end
if Tin[i] == "DRD" then --Drops items down
if tonumber(Tin[i + 1]) then
Tin[i + 1] = Tin[i + 1] + 0 --Gives an error message about line 18 if this is lacking
turtle.dropDown(Tin[i + 1])
else
turtle.dropDown(1)
end
end
if Tin[i] == "DRU" then --Drops items up
if tonumber(Tin[i + 1]) then
Tin[i + 1] = Tin[i + 1] + 0 --Gives an error message about line 18 if this is lacking
turtle.dropUp(Tin[i + 1])
else
turtle.dropUp(1)
end
end
if Tin[i] == "SCF" then --Suck
turtle.suck()
end
if Tin[i] == "SCU" then --Sucks Up
turtle.suckUp()
end
if Tin[i] == "SCD" then --Sucks Down
turtle.suckDown()
end
--End of Suck / drop
--Attack
if Tin[i] == "ATK" then --Makes the turtle attack, if a number is given
if tonumber(Tin[i + 1])then
for k = 1, Tin[i + 1] do
turtle.attack()
os.sleep(0.4)
end
else
turtle.attack()
end
end
if Tin[i] == "ATKU" then --Makes the turtle attack up, if a number is given
if tonumber(Tin[i + 1])then
for k = 1, Tin[i + 1] do
turtle.attackUp()
os.sleep(0.4)
end
else
turtle.attackUp()
end
end
if Tin[i] == "ATKD" then --Makes the turtle attack down, if a number is given
if tonumber(Tin[i + 1])then
for k = 1, Tin[i + 1] do
turtle.attackDown()
os.sleep(0.4)
end
else
turtle.attackDown()
end
end
--End of attack
if Tin[i] == "WAIT" then --Makes the turtle wait
if tonumber(Tin[i + 1]) then
Tin[i + 1] = Tin[i + 1] + 0
os.sleep(Tin[i + 1])
else
os.sleep(1)
end
end
end
--BUGS!
--if the "Tin[i + 1] = Tin[i + 1] + 0" part is lacking, it will say that the problem is on line 18. 18 is the line with the first "if" |
ITEM.name = "Американский MRE"
ITEM.desc = "Сухой паек, готовый к употреблению является автономным, индивидуальным рационом питания вооруженных сил Соединенных Штатов в полевых условиях, при проведении боевых операций или при других сложных условиях, когда нет поблизости источников нормальной пищи. \n\nХАРАКТЕРИСТИКИ: \n-военный \n-высококачественное изделие \n-здоровое питание \n\nНасыщение 100 \nЖажда 100" --Его описание
ITEM.price = 6435
ITEM.hunger = 100
ITEM.quantity = 3
ITEM.thirst = 100
ITEM.weight = 0.70
ITEM.empty = false
ITEM.exRender = false
ITEM.model = "models/kek1ch/ration_mre.mdl"
ITEM.width = 1
ITEM.height = 2
ITEM.iconCam = {
pos = Vector(0, 0, 200),
ang = Angle(90, 0, -2.2929935455322),
fov = 3
}
ITEM.functions.use = {
name = "употребить",
icon = "icon16/cup.png",
onRun = function(item)
local client = item.player
client:EmitSound( "ration_using/us_ration.wav", 75, 200 )
if item.hunger > 0 then client:restoreHunger(item.hunger) end
if item.thirst > 0 then client:restoreThirst(item.thirst) end
item:setData("quantity", item:getData("quantity", item.quantity or 0) - 1)
client:ScreenFade( SCREENFADE.OUT, Color( 0, 0, 0 ), 1, 3 )
timer.Simple(1,function()
client:ScreenFade( SCREENFADE.IN, Color( 0, 0, 0 ), 1, 3 )
end)
if item:getData("quantity") < 1 then
return true
end
return false;
end,
onCanRun = function(item)
return (!IsValid(item.entity))
end
}
|
-- Notify module
local Notify = {}
-- Variables
local gameWidth = 0
local fadeDuration = 0
local notifyDuration = 0
local notifyTime = 0
local notifyText = nil
-- Initializes notifications
function Notify.init(config)
gameWidth = config.gameWidth or 800
notifyDuration = config.notifyDuration or 1
fadeDuration = config.notifyFadeDuration or notifyDuration / 3
end
-- Shows notification in top right corner of the screen
function Notify.set(text, duration)
notifyText = text or ""
notifyTime = (duration or notifyDuration) + fadeDuration
end
-- Hides current notification
function Notify.reset()
notifyText = nil
notifyTime = 0
end
-- Updates notification
function Notify.update(delta)
if notifyTime > 0 then
notifyTime = notifyTime - delta
end
end
-- Draws notification
function Notify.draw()
if notifyTime > 0 then
local width = love.graphics.getFont():getWidth(notifyText)
local alpha = math.min(255, notifyTime / fadeDuration * 255)
love.graphics.setColor(255, 255, 255, alpha)
love.graphics.print(notifyText, gameWidth - width - 10, 10)
end
end
return Notify
|
local require = GLOBAL.require
local Vector3 = GLOBAL.Vector3
local STRINGS = GLOBAL.STRINGS
local ACTIONS = GLOBAL.ACTIONS
local ActionHandler = GLOBAL.ActionHandler
local LANG = GetModConfigData("LINGUAGEM")
local CNFG_HEALTH = GetModConfigData("HEALTH")
local CNFG_SANITY = GetModConfigData("SANITY")
local CNFG_HUNGER = GetModConfigData("HUNGER")
local CNFG_HUNGER_RATE = GetModConfigData("HUNGER_RATE")
local CNFG_DAMAGE_MULT = GetModConfigData("DAMAGE_MULT")
local CNFG_WALK_SPEED = GetModConfigData("WALK_SPEED")
local CNFG_RUN_SPEED = GetModConfigData("RUN_SPEED")
local CNFG_HUNGER_RATE = GetModConfigData("HUNGER_RATE")
local CNFG_DELAY_EXPLOSIVE = GetModConfigData("DELAY_EXPLOSIVE")
local CNFG_DELAY_PIG = GetModConfigData("DELAY_PIG")
local CNFG_DELAY_SPIDER = GetModConfigData("DELAY_SPIDER")
local CNFG_DELAY_BEEFALO = GetModConfigData("DELAY_BEEFALO")
local CNFG_PIGKING_DURATION = GetModConfigData("PIGKING_DURATION")
local CNFG_PIGMAN_DURATION = GetModConfigData("PIGMAN_DURATION")
local CNFG_SPIDERDEN_QNT = GetModConfigData("SPIDERDEN_QNT")
local CNFG_SPIDERDEN_RANGE = GetModConfigData("SPIDERDEN_RANGE")
local CNFG_BEEFALO_QNT = GetModConfigData("BEEFALO_QNT")
local CNFG_BEEFALO_RANGE = GetModConfigData("BEEFALO_RANGE")
local CNFG_PIGMAN_QNT = GetModConfigData("PIGMAN_QNT")
local CNFG_PIGMAN_RANGE = GetModConfigData("PIGMAN_RANGE")
local CNFG_PIGMAN_HEALTH = GetModConfigData("PIGMAN_HEALTH")
local CNFG_PIGMAN_DAMAGE = GetModConfigData("PIGMAN_DAMAGE")
local CNFG_PIGMAN_ATTACKSPEED = GetModConfigData("PIGMAN_ATTACKSPEED")
local CNFG_PIGMAN_RUNSPEED = GetModConfigData("PIGMAN_RUNSPEED")
local CNFG_PIGMAN_WALKSPEED = GetModConfigData("PIGMAN_WALKSPEED")
-----------------------------------------------------------------------------------
TUNING.BTWS_LANG = LANG
TUNING.BTWS_WES_HEALTH = CNFG_HEALTH + 0
TUNING.BTWS_WES_HUNGER = CNFG_HUNGER + 0
TUNING.BTWS_WES_HUNGER_RATE = CNFG_HUNGER_RATE + 0
TUNING.BTWS_WES_SANITY = CNFG_SANITY + 0
TUNING.BTWS_WES_DAMAGE_MULT = CNFG_DAMAGE_MULT + 0
TUNING.BTWS_WES_WALK_SPEED = CNFG_WALK_SPEED + 0
TUNING.BTWS_WES_RUN_SPEED = CNFG_RUN_SPEED + 0
TUNING.BTWS_DELAY_EXPLOSIVE_BALLOON = CNFG_DELAY_EXPLOSIVE + 0
TUNING.BTWS_DELAY_PIG_BALLOON = CNFG_DELAY_PIG + 0
TUNING.BTWS_DELAY_SPIDER_BALLOON = CNFG_DELAY_SPIDER + 0
TUNING.BTWS_DELAY_BEEFALO_BALLOON = CNFG_DELAY_BEEFALO + 0
TUNING.BTWS_PIGKING_DURATION = CNFG_PIGKING_DURATION + 0
TUNING.BTWS_PIGMAN_DURATION = CNFG_PIGMAN_DURATION + 0
TUNING.BTWS_SPIDERDEN_QNT = CNFG_SPIDERDEN_QNT + 0
TUNING.BTWS_SPIDERDEN_RANGE = CNFG_SPIDERDEN_RANGE + 0
TUNING.BTWS_BEEFALO_QNT = CNFG_BEEFALO_QNT + 0
TUNING.BTWS_BEEFALO_RANGE = CNFG_BEEFALO_RANGE + 0
TUNING.BTWS_PIGMAN_QNT = CNFG_PIGMAN_QNT + 0
TUNING.BTWS_PIGMAN_RANGE = CNFG_PIGMAN_RANGE + 0
TUNING.BTWS_PIGMAN_HEALTH = CNFG_PIGMAN_HEALTH + 0
TUNING.BTWS_PIGMAN_DAMAGE = CNFG_PIGMAN_DAMAGE + 0
TUNING.BTWS_PIGMAN_ATTACKSPEED = CNFG_PIGMAN_ATTACKSPEED + 0
TUNING.BTWS_PIGMAN_RUNSPEED = CNFG_PIGMAN_RUNSPEED + 0
TUNING.BTWS_PIGMAN_WALKSPEED = CNFG_PIGMAN_WALKSPEED + 0
local tablang = ""
--wtf
TUNING.WES_HEALTH = CNFG_HEALTH + 0
TUNING.WES_HUNGER = CNFG_HUNGER + 0
TUNING.WES_SANITY = CNFG_SANITY + 0
Assets = {
Asset("ATLAS", "images/hud/balloomancytab_icon.xml"),
Asset("IMAGE", "images/hud/balloomancytab_icon.tex"),
Asset("ATLAS", "images/inventoryimages/balloonsopile.xml"),
Asset("IMAGE", "images/inventoryimages/balloonsopile.tex"),
Asset("ATLAS", "images/inventoryimages/explosiveballoon_icon.xml"),
Asset("IMAGE", "images/inventoryimages/explosiveballoon_icon.tex"),
Asset("ATLAS", "images/inventoryimages/spiderballoon_icon.xml"),
Asset("IMAGE", "images/inventoryimages/spiderballoon_icon.tex"),
Asset("ATLAS", "images/inventoryimages/pigmanballoon_icon.xml"),
Asset("IMAGE", "images/inventoryimages/pigmanballoon_icon.tex"),
Asset("ATLAS", "images/inventoryimages/beefaloballoon_icon.xml"),
Asset("IMAGE", "images/inventoryimages/beefaloballoon_icon.tex"),
}
PrefabFiles = {
"balloons_empty_explosive",
"balloons_empty_pig",
"balloons_empty_spider",
"balloons_empty_beefalo",
"balloon_pig",
"balloon_spider",
"balloon_beefalo",
"pigking_wes",
"pigman_wes",
}
-----------------------------------------------------------------------------------
if TUNING.BTWS_LANG == "BR" then
STRINGS.CHARACTER_TITLES.wes = "O Silencioso Criador de Balões"
STRINGS.CHARACTER_DESCRIPTIONS.wes = "*Não consegue falar \n*Pratica balãomancia \n*Agora está melhor"
STRINGS.CHARACTER_SURVIVABILITY.wes = "Mínima"
GLOBAL.STRINGS.NAMES.BALLOONS_EMPTY = "Pilha de Baloes"
GLOBAL.STRINGS.RECIPE_DESC.BALLOONS_EMPTY = "Apenas... baloes."
GLOBAL.STRINGS.CHARACTERS.GENERIC.DESCRIBE.BALLOONS_EMPTY = "Baloes vazios?"
GLOBAL.STRINGS.NAMES.BALLOONS_EMPTY_EXPLOSIVE = "Balao Explosivo"
GLOBAL.STRINGS.RECIPE_DESC.BALLOONS_EMPTY_EXPLOSIVE = "Cria uma pequena explosao"
GLOBAL.STRINGS.CHARACTERS.GENERIC.DESCRIBE.BALLOONS_EMPTY_EXPLOSIVE = "Isso ai vai explodir!"
GLOBAL.STRINGS.NAMES.BALLOONS_EMPTY_PIG = "Balao de Porco"
GLOBAL.STRINGS.RECIPE_DESC.BALLOONS_EMPTY_PIG = "Um rei porco temporário e seus súditos!"
GLOBAL.STRINGS.CHARACTERS.GENERIC.DESCRIBE.BALLOONS_EMPTY_PIG = "Saúdam o rei!"
GLOBAL.STRINGS.NAMES.BALLOONS_EMPTY_SPIDER = "Balao de Aranha"
GLOBAL.STRINGS.RECIPE_DESC.BALLOONS_EMPTY_SPIDER = "Vários casulos pra você."
GLOBAL.STRINGS.CHARACTERS.GENERIC.DESCRIBE.BALLOONS_EMPTY_SPIDER = "Eca, aranha!"
GLOBAL.STRINGS.NAMES.BALLOONS_EMPTY_BEEFALO = "Balao de Beefalo"
GLOBAL.STRINGS.RECIPE_DESC.BALLOONS_EMPTY_BEEFALO = "Da pra você uma pequena criaturinha."
GLOBAL.STRINGS.CHARACTERS.GENERIC.DESCRIBE.BALLOONS_EMPTY_BEEFALO = "Pequena e sem pelos."
GLOBAL.STRINGS.NAMES.BALLOON = "Balao Explosivo"
GLOBAL.STRINGS.RECIPE_DESC.BALLOON = "Cria uma pequena explosao"
GLOBAL.STRINGS.CHARACTERS.GENERIC.DESCRIBE.BALLOON = "Vai explodir!"
GLOBAL.STRINGS.NAMES.BALLOON_PIG = "Balao de Porco"
GLOBAL.STRINGS.RECIPE_DESC.BALLOON_PIG = "Empty"
GLOBAL.STRINGS.CHARACTERS.GENERIC.DESCRIBE.BALLOON_PIG = "Vai explodir!"
GLOBAL.STRINGS.NAMES.BALLOON_SPIDER = "Balao de Aranha"
GLOBAL.STRINGS.RECIPE_DESC.BALLOON_SPIDER = "Invoca um pequeno exercito"
GLOBAL.STRINGS.CHARACTERS.GENERIC.DESCRIBE.BALLOON_SPIDER = "Vai explodir!"
GLOBAL.STRINGS.NAMES.BALLOON_BEEFALO = "Balao de Beefalo"
GLOBAL.STRINGS.RECIPE_DESC.BALLOON_BEEFALO = "Da pra voce um amiguinho"
GLOBAL.STRINGS.CHARACTERS.GENERIC.DESCRIBE.BALLOON_BEEFALO = "Vai explodir!"
GLOBAL.STRINGS.NAMES.PIGKING_WES = "Rei Porco"
tablang = "Balãomancia"
else
STRINGS.CHARACTER_TITLES.wes = "The Silent Balloon Maker"
STRINGS.CHARACTER_DESCRIPTIONS.wes = "*Can't talk \n*Practices balloonomancy \n*Are now better"
STRINGS.CHARACTER_SURVIVABILITY.wes = "Slim"
GLOBAL.STRINGS.NAMES.BALLOONS_EMPTY = "Pile of Balloons"
GLOBAL.STRINGS.RECIPE_DESC.BALLOONS_EMPTY = "Just... balloons."
GLOBAL.STRINGS.CHARACTERS.GENERIC.DESCRIBE.BALLOONS_EMPTY = "Empty balloons?"
GLOBAL.STRINGS.NAMES.BALLOONS_EMPTY_EXPLOSIVE = "Explosive Balloon"
GLOBAL.STRINGS.RECIPE_DESC.BALLOONS_EMPTY_EXPLOSIVE = "Makes a little explosion"
GLOBAL.STRINGS.CHARACTERS.GENERIC.DESCRIBE.BALLOONS_EMPTY_EXPLOSIVE = "This will explode!"
GLOBAL.STRINGS.NAMES.BALLOONS_EMPTY_PIG = "Pig Balloon"
GLOBAL.STRINGS.RECIPE_DESC.BALLOONS_EMPTY_PIG = "A temporary Pig King and his followers!"
GLOBAL.STRINGS.CHARACTERS.GENERIC.DESCRIBE.BALLOONS_EMPTY_PIG = "Hail the King!"
GLOBAL.STRINGS.NAMES.BALLOONS_EMPTY_SPIDER = "Spider Balloon"
GLOBAL.STRINGS.RECIPE_DESC.BALLOONS_EMPTY_SPIDER = "Several cocoons for you."
GLOBAL.STRINGS.CHARACTERS.GENERIC.DESCRIBE.BALLOONS_EMPTY_SPIDER = "Eww, spider!"
GLOBAL.STRINGS.NAMES.BALLOONS_EMPTY_BEEFALO = "Beefalo Balloon"
GLOBAL.STRINGS.RECIPE_DESC.BALLOONS_EMPTY_BEEFALO = "Give you a little creature."
GLOBAL.STRINGS.CHARACTERS.GENERIC.DESCRIBE.BALLOONS_EMPTY_BEEFALO = "Small and hairless."
GLOBAL.STRINGS.NAMES.BALLOON = "Explosive Balloon"
GLOBAL.STRINGS.RECIPE_DESC.BALLOON = "Makes a little explosion"
GLOBAL.STRINGS.CHARACTERS.GENERIC.DESCRIBE.BALLOON = "It will explode!"
GLOBAL.STRINGS.NAMES.BALLOON_PIG = "Pig Balloon"
GLOBAL.STRINGS.RECIPE_DESC.BALLOON_PIG = "A temporary Pig King!"
GLOBAL.STRINGS.CHARACTERS.GENERIC.DESCRIBE.BALLOON_PIG = "It will explode!"
GLOBAL.STRINGS.NAMES.BALLOON_SPIDER = "Spider Balloon"
GLOBAL.STRINGS.RECIPE_DESC.BALLOON_SPIDER = "Several cocoons for you."
GLOBAL.STRINGS.CHARACTERS.GENERIC.DESCRIBE.BALLOON_SPIDER = "It will explode!"
GLOBAL.STRINGS.NAMES.BALLOON_BEEFALO = "Beefalo Balloon"
GLOBAL.STRINGS.RECIPE_DESC.BALLOON_BEEFALO = "Give you a little creature."
GLOBAL.STRINGS.CHARACTERS.GENERIC.DESCRIBE.BALLOON_BEEFALO = "It will explode!"
GLOBAL.STRINGS.NAMES.PIGKING_WES = "Pig King"
tablang = "Balloonomancy"
end
-----------------------------------------------------------------------------------
local balloonmancy = AddRecipeTab(
tablang,
12.22222,
"images/hud/balloomancytab_icon.xml",
"balloomancytab_icon.tex",
"mime"
)
-----------------------------------------------------------------------------------
AddRecipe("balloons_empty",
{
GLOBAL.Ingredient("petals", 12),
GLOBAL.Ingredient("rope", 1),
},
balloonmancy,
GLOBAL.TECH.NONE,
nil,
nil,
nil,
1,
"mime",
"images/inventoryimages/balloonsopile.xml",
"balloonsopile.tex"
)
AddRecipe("balloons_empty_explosive",
{
GLOBAL.Ingredient("balloons_empty", 1),
GLOBAL.Ingredient("torch", 1),
GLOBAL.Ingredient("nitre", 5),
},
balloonmancy,
GLOBAL.TECH.NONE,
nil,
nil,
nil,
1,
"mime",
"images/inventoryimages/explosiveballoon_icon.xml",
"explosiveballoon_icon.tex"
)
AddRecipe("balloons_empty_spider",
{
GLOBAL.Ingredient("balloons_empty", 1),
GLOBAL.Ingredient("silk", 15),
GLOBAL.Ingredient("spidergland", 10),
},
balloonmancy,
GLOBAL.TECH.NONE,
nil,
nil,
nil,
1,
"mime",
"images/inventoryimages/spiderballoon_icon.xml",
"spiderballoon_icon.tex"
)
AddRecipe("balloons_empty_pig",
{
GLOBAL.Ingredient("balloons_empty", 1),
GLOBAL.Ingredient("pigskin", 8),
GLOBAL.Ingredient("goldnugget", 10),
},
balloonmancy,
GLOBAL.TECH.NONE,
nil,
nil,
nil,
1,
"mime",
"images/inventoryimages/pigmanballoon_icon.xml",
"pigmanballoon_icon.tex"
)
AddRecipe("balloons_empty_beefalo",
{
GLOBAL.Ingredient("balloons_empty", 1),
GLOBAL.Ingredient("beefalowool", 10),
},
balloonmancy,
GLOBAL.TECH.NONE,
nil,
nil,
nil,
1,
"mime",
"images/inventoryimages/beefaloballoon_icon.xml",
"beefaloballoon_icon.tex"
)
AddAction("CRIARBALAO", "Use", function(act)
local target = act.target or act.invobject
if target ~= nil and target.components.criarbalao ~= nil then
target.components.criarbalao:Criar()
end
return true
end)
AddComponentAction("INVENTORY", "criarbalao", function(inst, doer, actions, right)
table.insert(actions, ACTIONS.CRIARBALAO)
end)
AddStategraphActionHandler("wilson", ActionHandler(ACTIONS.CRIARBALAO, "doshortaction"))
AddStategraphActionHandler("wilson_client", ActionHandler(ACTIONS.CRIARBALAO, "doshortaction")) |
Quest.Config.Storylines["he_fix_it_falafel"] ={
name = "He fix it Falafel",
id = "he_fix_it_falafel",
desc = "Oil and grease",
quests = {
[1] = {
name = "Become a Mechanic",
desc = "Become a Mechanic from the F4 menu",
func = function(ply, data)
return true
end
},
[2] = {
name = "Repair a vehicle part",
desc = "Repair a vehicle part using your tools",
func = function(ply, data)
return true
end
},
[3] = {
name = "Clamp a vehicle",
desc = "Clamp a vehicle using your clamp SWEP",
func = function(ply, data)
return true
end,
reward = function(ply)
Quest.Core.GiveStoryline(ply, "money_guard")
end
},
}
}
-- Become a bus driver
hook.Add("PlayerChangedTeam", "Quest:Progress:he_fix_it_falafel", function(ply, oldTeam, newTeam)
if not (newTeam == TEAM_MECHANIC) then return end
Quest.Core.ProgressQuest(ply, "he_fix_it_falafel", 1)
end)
-- Repair a vehicle
hook.Add("VC_playerRepairedPart", "Quest:Progress:he_fix_it_falafel", function(ply)
Quest.Core.ProgressQuest(ply, "he_fix_it_falafel", 2)
end)
-- Clamp a vehicle
hook.Add("XYZImpoundClamp", "Quest:Progress:he_fix_it_falafel", function(ply, owner, vehicle)
Quest.Core.ProgressQuest(ply, "he_fix_it_falafel", 3)
end)
|
class("CheckWorldBossStateCommand", pm.SimpleCommand).execute = function (slot0, slot1)
slot2 = slot1:getBody()
slot4 = slot2.callback
slot6 = slot2.time or 0
function slot7()
slot0 = getProxy(ChatProxy)
for slot5, slot6 in ipairs(slot1) do
slot6.args.isDeath = true
slot0:UpdateMsg(slot6)
end
for slot7, slot8 in ipairs(slot3) do
slot8.args.isDeath = true
slot2:UpdateMsg(slot8)
end
if slot2 then
slot2()
end
end
print("boss id", slot3, " time:", tonumber)
pg.ConnectionMgr.GetInstance():Send(34515, {
boss_id = slot2.bossId,
last_time = tonumber(slot2.failedCallback)
}, 34516, function (slot0)
if slot0.result == 0 then
if slot0 then
slot0()
end
elseif slot0.result == 1 then
slot1()
pg.TipsMgr.GetInstance():ShowTips(i18n("world_boss_none"))
elseif slot0.result == 3 then
slot1()
pg.TipsMgr.GetInstance():ShowTips(i18n("world_boss_none"))
elseif slot0.result == 6 then
slot1()
pg.TipsMgr.GetInstance():ShowTips(i18n("world_max_challenge_cnt"))
elseif slot0.result == 20 then
slot1()
pg.TipsMgr.GetInstance():ShowTips(i18n("world_boss_none"))
else
pg.TipsMgr.GetInstance():ShowTips(ERROR_MESSAGE[slot0.result] .. slot0.result)
end
end)
end
return class("CheckWorldBossStateCommand", pm.SimpleCommand)
|
savage_guf_drolg = Creature:new {
objectName = "@mob/creature_names:savage_guf_drolg",
socialGroup = "guf_drolg",
faction = "",
level = 15,
chanceHit = 0.31,
damageMin = 170,
damageMax = 180,
baseXp = 831,
baseHAM = 2400,
baseHAMmax = 3000,
armor = 0,
resists = {110,5,5,-1,-1,-1,-1,-1,-1},
meatType = "meat_reptilian",
meatAmount = 550,
hideType = "hide_leathery",
hideAmount = 460,
boneType = "bone_mammal",
boneAmount = 320,
milk = 0,
tamingChance = 0.25,
ferocity = 0,
pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY,
creatureBitmask = PACK,
optionsBitmask = AIENABLED,
diet = CARNIVORE,
templates = {"object/mobile/guf_drolg_hue.iff"},
hues = { 24, 25, 26, 27, 28, 29, 30, 31 },
controlDeviceTemplate = "object/intangible/pet/guf_drolg_hue.iff",
scale = 1.2,
lootGroups = {},
weapons = {},
conversationTemplate = "",
attacks = {
{"",""},
{"intimidationattack",""}
}
}
CreatureTemplates:addCreatureTemplate(savage_guf_drolg, "savage_guf_drolg")
|
--[[
Copyright 2012-2015 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License")
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
require('tap')(function(test)
local math = require('math')
local string = require('string')
local FS = require('fs')
local Path = require('path')
test('fs.read and fs.readSync', function()
local filepath = Path.join(module.dir, 'fixtures', 'x.txt')
print(filepath)
local fd = FS.openSync(filepath, 'r')
local expected = 'xyz\n'
local readCalled = 0
FS.read(fd, #expected, 0, function(err, str, bytesRead)
readCalled = readCalled + 1
assert(not err)
assert(str == expected)
assert(#str == #expected)
end)
local r,e = FS.readSync(fd, #expected, 0)
assert(r == expected)
assert(#r == #expected)
end)
end) |
#include "_T_Lapism_goldentheme.lua"
durability=20,
density=0.05,
growRate=2,
armor=0,
meleeDamage=0,
capacity=0,
|
-- https://github.com/folke/which-key.nvim
require("which-key").setup {
key_labels = {
["<space>"] = "SPC",
["<cr>"] = "RET",
["<tab>"] = "TAB"
}
}
|
data:extend({
{
type = "accumulator",
name = "power-sensor",
icon = "__Red Alerts__/graphics/PowerSensorIcon.png",
flags = {"placeable-neutral", "player-creation"},
minable = {hardness = 0.2, mining_time = 0.5, result = "power-sensor"},
max_health = 100,
corpse = "small-remnants",
collision_box = {{-0.2, -0.2}, {0.2, 0.2}},
selection_box = {{-0.5, -0.5}, {0.5, 0.5}},
energy_source =
{
type = "electric",
buffer_capacity = "15J",
usage_priority = "terciary",
input_flow_limit = "2W",
output_flow_limit = "1W"
},
picture =
{
filename = "__Red Alerts__/graphics/PowerSensorBase.png",
priority = "high",
width = 47,
height = 29,
shift = {0.0, 0.1}
},
charge_animation =
{
filename = "__Red Alerts__/graphics/PowerSensorGreen.png",
width = 47,
height = 29,
line_length = 1,
frame_count = 1,
shift = {0.0, 0.1},
animation_speed = 0
},
charge_cooldown = 600,
charge_light = {intensity = 0.5, size = 4, color={r=0.592157, g=1, b=0.117647}},
discharge_animation =
{
filename = "__Red Alerts__/graphics/PowerSensorYellow.png",
width = 47,
height = 29,
line_length = 1,
frame_count = 1,
shift = {0.0, 0.1},
animation_speed = 0
},
discharge_cooldown = 60,
discharge_light = {intensity = 0.5, size = 4, color={r=0.815686, g=0.670588, b=0.431373}},
vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 },
working_sound =
{
sound =
{
filename = "__base__/sound/accumulator-working.ogg",
volume = 0
},
idle_sound = {
filename = "__base__/sound/accumulator-idle.ogg",
volume = 0
},
max_sounds_per_type = 0
},
circuit_wire_connection_point =
{
shadow =
{
red = {0.008125, 0.484375},
green = {0.108125, 0.484375},
},
wire =
{
red = {0.0925, 0.34375},
green = {0.24875, 0.34375},
}
},
circuit_connector_sprites = get_circuit_connector_sprites({0.3, 0.28125}, {0.3, 0.28125}, 0),
circuit_wire_max_distance = 7.5,
default_output_signal = "signal-A"
},
})
|
--[[
file:api_socket.lua
desc:socket使用
auth:Caorl Luo
]]
local socket = require("skynet.socket")
---@class api_socket
local api_socket = {}
---监听
---@param host ip @地址
---@param port port @端口
---@return socket
function api_socket.listen(host, port)
return socket.listen(host, port)
end
---连接
---@param address ip @地址
---@param port port @端
---@return socket
function api_socket.open(address, port)
return socket.open(address, port)
end
---关闭
---@param fd socket @套接字
function api_socket.close(fd)
socket.close(fd)
end
---关闭
---@param fd socket @套接字
function api_socket.close_fd(fd)
socket.close_fd(fd)
end
---关闭
---@param fd socket @套接字
function api_socket.shutdown(fd)
socket.shutdown(fd)
end
---启动
---@param fd socket @套接字
---@param func function @连接回调
function api_socket.start(fd, func)
socket.start(fd, func)
end
---发送
---@param fd socket @套接字
---@param text string @字符串
function api_socket.write(fd, text)
socket.write(fd, text)
end
---发送
---@param fd socket @套接字
---@param from host @网络地址
---@param data string @字符串数据
function api_socket.sendto(fd, from, data)
socket.sendto(fd, from, data)
end
return api_socket |
slot0 = class("BiliTracker")
slot0.Ctor = function (slot0, slot1)
return
end
slot0.Tracking = function (slot0, slot1, slot2, slot3)
if slot1 == TRACKING_USER_LEVELUP then
print("tracking lvl:" .. slot3)
pg.SdkMgr.GetInstance():SdkLevelUp()
end
end
return slot0
|
return function(keyName, tbl)
assert(typeof(keyName)=="string", "Arg 1 must be a string, got "..typeof(keyName))
assert(typeof(tbl)=="table", "Arg 2 must be a table, got"..typeof(tbl))
local new = {}
for idx,v in ipairs(tbl) do
if v[keyName] ~= nil then
new[v[keyName]] = v
else
warn(("item %s at [%d] has no key %s"):format(tostring(v), idx, tostring(keyName)))
end
end
return new
end |
return {
init_effect = "",
name = "测试-声望-主炮额外一轮攻击1",
time = 0,
picture = "",
desc = "触发:主炮额外一轮攻击1",
stack = 1,
id = 60033,
icon = 60033,
last_effect = "lingxing",
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onChargeWeaponFire"
},
arg_list = {
skill_id = 60017,
target = "TargetSelf"
}
},
{
type = "BattleBuffAddBuff",
trigger = {
"onChargeWeaponBulletCreate"
},
arg_list = {
buff_id = 60032,
target = "TargetSelf",
bulletTrigger = "onBulletKill"
}
},
{
type = "BattleBuffCancelBuff",
trigger = {
"onChargeWeaponFire"
},
arg_list = {
count = 1,
delay = 3
}
}
}
}
|
-- Detect optional mods.
local armor_path = minetest.get_modpath("3d_armor")
-- global runtime storage for data and references
-- contains .motors loaded from mod storage
-- runtime variables and api functions
elevator = {
SPEED = 10, -- Initial speed of a box.
ACCEL = 0.1, -- Acceleration of a box.
VISUAL_INCREASE = 1.75,
VERSION = 8, -- Elevator interface/database version.
PTIMEOUT = 120, -- Maximum time a box can go without players nearby.
boxes = {}, -- Elevator boxes in action.
lastboxes = {}, -- Player near box timeout.
riding = {}, -- Players riding boxes.
formspecs = {}, -- Player formspecs.
}
local MP = minetest.get_modpath(minetest.get_current_modname())
dofile(MP .. "/helpers.lua")
dofile(MP .. "/storage.lua")
dofile(MP .. "/crafts.lua")
dofile(MP .. "/components.lua")
dofile(MP .. "/hooks.lua")
dofile(MP .. "/formspecs.lua")
local phash = elevator.phash
local punhash = elevator.punhash
local get_node = elevator.get_node
-- Cause <sender> to ride <motorhash> beginning at <pos> and targetting <target>.
elevator.create_box = function(motorhash, pos, target, sender)
-- First create the box.
local obj = minetest.add_entity(pos, "elevator:box")
obj:setpos(pos)
-- Attach the player.
sender:setpos(pos)
sender:set_attach(obj, "", {x=0, y=9, z=0}, {x=0, y=0, z=0})
sender:set_eye_offset({x=0, y=-9, z=0},{x=0, y=-9, z=0})
sender:set_properties({visual_size = {x=elevator.VISUAL_INCREASE, y=elevator.VISUAL_INCREASE}})
if armor_path then
armor:update_player_visuals(sender)
end
-- Set the box properties.
obj:get_luaentity().motor = motorhash
obj:get_luaentity().uid = math.floor(math.random() * 1000000)
obj:get_luaentity().attached = sender:get_player_name()
obj:get_luaentity().start = pos
obj:get_luaentity().target = target
obj:get_luaentity().halfway = {x=pos.x, y=(pos.y+target.y)/2, z=pos.z}
obj:get_luaentity().vmult = (target.y < pos.y) and -1 or 1
-- Set the speed.
obj:setvelocity({x=0, y=elevator.SPEED*obj:get_luaentity().vmult, z=0})
obj:setacceleration({x=0, y=elevator.ACCEL*obj:get_luaentity().vmult, z=0})
-- Set the tables.
elevator.boxes[motorhash] = obj
elevator.riding[sender:get_player_name()] = {
motor = motorhash,
pos = pos,
target = target,
box = obj,
}
return obj
end
-- Starting from <pos>, locate a motor hash.
elevator.locate_motor = function(pos)
local p = vector.new(pos)
while true do
local node = get_node(p)
if node.name == "elevator:elevator_on" or node.name == "elevator:elevator_off" then
p.y = p.y + 2
elseif node.name == "elevator:shaft" then
p.y = p.y + 1
elseif node.name == "elevator:motor" then
return phash(p)
else
return nil
end
end
end
elevator.build_motor = function(hash)
local need_saving = false
local motor = elevator.motors[hash]
-- Just ignore motors that don't exist.
if not motor then
return
end
local p = punhash(hash)
local node = get_node(p)
-- And ignore motors that aren't motors.
if node.name ~= "elevator:motor" then
return
end
p.y = p.y - 1
motor.elevators = {}
motor.pnames = {}
motor.labels = {}
-- Run down through the shaft, storing information about elevators.
while true do
local node = get_node(p)
if node.name == "elevator:shaft" then
p.y = p.y - 1
else
p.y = p.y - 1
local node = get_node(p)
if node.name == "elevator:elevator_on" or node.name == "elevator:elevator_off" then
table.insert(motor.elevators, phash(p))
table.insert(motor.pnames, tostring(p.y))
table.insert(motor.labels, "")
p.y = p.y - 1
need_saving = true
else
break
end
end
end
-- Set the elevators fully.
for i,m in ipairs(motor.elevators) do
local pos = punhash(m)
local meta = minetest.get_meta(pos)
meta:set_int("version", elevator.VERSION)
if meta:get_string("motor") ~= hash then
elevator.build_motor(meta:get_string("motor"))
end
motor.labels[i] = meta:get_string("label")
meta:set_string("motor", hash)
if motor.labels[i] ~= meta:get_string("infotext") then
meta:set_string("infotext", motor.labels[i])
end
end
if need_saving then
elevator.save_elevator()
end
end
elevator.unbuild = function(pos, add)
local need_saving = false
local p = table.copy(pos)
p.y = p.y - 1
-- Loop down through the network, set any elevators below this to the off position.
while true do
local node = get_node(p)
if node.name == "elevator:shaft" then
p.y = p.y - 1
else
p.y = p.y - 1
local node = get_node(p)
if node.name == "elevator:elevator_on" or node.name == "elevator:elevator_off" then
local meta = minetest.get_meta(p)
meta:set_string("motor", "")
p.y = p.y - 1
else
break
end
end
end
-- After a short delay, build the motor and handle box removal.
minetest.after(0.01, function(p2, add)
if not p2 or not add then
return
end
p2.y = p2.y + add
local motorhash = elevator.locate_motor(p2)
elevator.build_motor(motorhash)
-- If there's a box below this point, break it.
if elevator.boxes[motorhash] and elevator.boxes[motorhash]:getpos() and p2.y >= elevator.boxes[motorhash]:getpos().y then
elevator.boxes[motorhash] = nil
end
-- If the box does not exist, just clear it.
if elevator.boxes[motorhash] and not elevator.boxes[motorhash]:getpos() then
elevator.boxes[motorhash] = nil
end
end, table.copy(pos), add)
end
-- Ensure an elevator is up to the latest version.
local function upgrade_elevator(pos, meta)
if meta:get_int("version") ~= elevator.VERSION then
minetest.log("action", "[elevator] Updating elevator with old version at "..minetest.pos_to_string(pos))
minetest.after(0, function(pos) elevator.build_motor(elevator.locate_motor(pos)) end, pos)
meta:set_int("version", elevator.VERSION)
meta:set_string("formspec", "")
meta:set_string("infotext", meta:get_string("label"))
end
end
-- Convert off to on when applicable.
local offabm = function(pos, node)
local meta = minetest.get_meta(pos)
upgrade_elevator(pos, meta)
if not elevator.boxes[meta:get_string("motor")] and elevator.motors[meta:get_string("motor")] then
node.name = "elevator:elevator_on"
minetest.swap_node(pos, node)
end
end
minetest.register_abm({
nodenames = {"elevator:elevator_off"},
interval = 1,
chance = 1,
action = offabm,
label = "Elevator (Off)",
})
-- Convert on to off when applicable.
minetest.register_abm({
nodenames = {"elevator:elevator_on"},
interval = 1,
chance = 1,
action = function(pos, node)
local meta = minetest.get_meta(pos)
upgrade_elevator(pos, meta)
if elevator.boxes[meta:get_string("motor")] or not elevator.motors[meta:get_string("motor")] then
node.name = "elevator:elevator_off"
minetest.swap_node(pos, node)
end
end,
label = "Elevator (On)",
})
-- Remove the player from self, and teleport them to pos if specified.
local function detach(self, pos)
local player = minetest.get_player_by_name(self.attached)
local attached = player:get_attach()
if not attached or attached:get_luaentity().uid ~= self.uid then
return
end
player:set_detach()
player:set_eye_offset({x=0, y=0, z=0},{x=0, y=0, z=0})
player:set_properties({visual_size = {x=1, y=1}})
if armor_path then
armor:update_player_visuals(player)
end
if pos then
player:setpos(pos)
minetest.after(0.1, function(pl, p)
pl:setpos(p)
end, player, pos)
end
elevator.riding[self.attached] = nil
end
local box_entity = {
physical = false,
collisionbox = {0,0,0,0,0,0},
visual = "wielditem",
visual_size = {x=1, y=1},
textures = {"elevator:elevator_box"},
attached = "",
motor = false,
target = false,
start = false,
lastpos = false,
halfway = false,
vmult = 0,
on_activate = function(self, staticdata)
-- Don't want the box being destroyed by anything except the elevator system.
self.object:set_armor_groups({immortal=1})
end,
on_step = function(self, dtime)
local pos = self.object:getpos()
-- First, check if this box needs removed.
-- If the motor has a box and it isn't this box.
if elevator.boxes[self.motor] and elevator.boxes[self.motor] ~= self.object then
minetest.log("action", "[elevator] "..minetest.pos_to_string(pos).." broke due to duplication.")
self.object:remove()
return
end
-- If our attached player can't be found.
if not minetest.get_player_by_name(self.attached) then
minetest.log("action", "[elevator] "..minetest.pos_to_string(pos).." broke due to lack of attachee logged in.")
self.object:remove()
elevator.boxes[self.motor] = nil
return
end
-- If our attached player is no longer with us.
if not minetest.get_player_by_name(self.attached):get_attach() or minetest.get_player_by_name(self.attached):get_attach():get_luaentity().uid ~= self.uid then
minetest.log("action", "[elevator] "..minetest.pos_to_string(pos).." broke due to lack of attachee.")
self.object:remove()
elevator.boxes[self.motor] = nil
return
end
-- If our motor's box is nil, we should self-destruct.
if not elevator.boxes[self.motor] then
minetest.log("action", "[elevator] "..minetest.pos_to_string(pos).." broke due to nil entry in boxes.")
detach(self)
self.object:remove()
elevator.boxes[self.motor] = nil
return
end
minetest.get_player_by_name(self.attached):setpos(pos)
-- Ensure lastpos is set to something.
self.lastpos = self.lastpos or pos
-- Loop through all travelled nodes.
for y=self.lastpos.y,pos.y,((self.lastpos.y > pos.y) and -0.3 or 0.3) do
local p = vector.round({x=pos.x, y=y, z=pos.z})
local node = get_node(p)
if node.name == "elevator:shaft" then
-- Nothing, just continue on our way.
elseif node.name == "elevator:elevator_on" or node.name == "elevator:elevator_off" then
-- If this is our target, detach the player here, destroy this box, and update the target elevator without waiting for the abm.
if vector.distance(p, self.target) < 1 then
minetest.log("action", "[elevator] "..minetest.pos_to_string(p).." broke due to arrival.")
detach(self, vector.add(self.target, {x=0, y=-0.4, z=0}))
self.object:remove()
elevator.boxes[self.motor] = nil
offabm(self.target, node)
return
end
else
-- Check if we're in the top part of an elevator, if so it's fine.
local below = vector.add(p, {x=0,y=-1,z=0})
local belownode = get_node(below)
if belownode.name ~= "elevator:elevator_on" and belownode.name ~= "elevator:elevator_off" then
-- If we aren't, then break the box.
minetest.log("action", "[elevator] "..minetest.pos_to_string(p).." broke on "..node.name)
elevator.boxes[self.motor] = nil
detach(self, p)
self.object:remove()
return
end
end
end
self.lastpos = pos
end,
}
minetest.register_entity("elevator:box", box_entity)
|
local fillerStruct = {}
function fillerStruct.decode(data)
local filler = {
_type = "filler",
_raw = data
}
filler.x = data.x or 0
filler.y = data.y or 0
filler.width = data.w or 0
filler.height = data.h or 0
return filler
end
function fillerStruct.encode(rect)
local res = {}
res.__name = "rect"
res.x = rect.x
res.y = rect.y
res.w = rect.width
res.h = rect.height
return res
end
return fillerStruct |
#!/usr/bin/env tarantool
require('strict').on()
package.setsearchroot()
local front = require('frontend-core')
local cartridge = require('cartridge')
local analytics = require('analytics')
local tutorial_bundle = require('cartridge-app.bundle')
local clock = require('clock')
local json = require('json')
local helper = require('app.libs.helper')
local DEFAULT_COOKIE_DOMAIN = "try.tarantool.io"
local ENTERPRISE = 'Enterprise'
local roles = {
'cartridge.roles.vshard-router',
'cartridge.roles.vshard-storage',
'extensions',
'cartridge.roles.crud-router',
'cartridge.roles.crud-storage',
}
local enterprise_roles = {
'space-explorer'
}
local _, tarantool_type = unpack(require('tarantool').package:split(' '))
if tarantool_type == ENTERPRISE then
for _, role in pairs(enterprise_roles) do
table.insert(roles, role)
end
end
local ok, err = cartridge.cfg({
roles = roles,
cluster_cookie = 'try-cartridge-cluster-cookie'
})
front.add('analytics_static', analytics.static_bundle)
front.add('ga', analytics.use_bundle({ ga = '22120502-2' }))
front.add('tutorial', tutorial_bundle)
local auth = require('app.auth')
auth.init()
local last_used = clock.time()
local httpd = cartridge.service_get('httpd')
local cartridge_before_dispatch = httpd.hooks.before_dispatch
local function before_dispatch(httpd, req)
if cartridge_before_dispatch ~= nil and not string.find(req.path, '/last_used') then
local ok, err = cartridge_before_dispatch(httpd, req)
if err then
return nil, err
end
end
if string.find(req.path, '/admin') then
last_used = clock.time()
end
end
local cartridge_after_dispatch = httpd.hooks.after_dispatch
local function after_dispatch(req, resp)
if cartridge_after_dispatch ~= nil then
cartridge_after_dispatch(req, resp)
end
resp.headers = resp.headers or {}
local domain = helper.read_args({ cookie_domain = 'string' }, false).cookie_domain or DEFAULT_COOKIE_DOMAIN
resp.headers['Set-Cookie']=('token=%s;path=/;expires=+7d;domain=%s;HttpOnly'):format(req:cookie('token'), domain)
end
httpd:route(
{ path = '/last_used', public = true },
function()
return {
body = json.encode({ last_used = last_used }),
status = 200
}
end
)
httpd:hook('before_dispatch', before_dispatch)
httpd:hook('after_dispatch', after_dispatch)
assert(ok, tostring(err))
|
counter = 0
function onSave()
node:save(tostring(counter))
end
function onRedstonePowered()
counter=counter+1
node:setInfoLine(tostring(counter))
end
function load(data)
print(data)
counter = tonumber(data)
node:setInfoLine(counter)
end
node:onRedstoneSignal(onRedstonePowered)
node:onSave(onSave)
node:onConfigurationLoaded(load) |
createbaseprojectcpp("GoogleTest", "StaticLib")
files
{
"googlemock/src/gmock-all.cc",
"googletest/src/gtest-all.cc",
}
includedirs
{
"googletest",
"googlemock",
"googletest/include",
"googlemock/include",
} |
--------------------------------------------------------------------------------
waterState = {}
--------------------------------------------------------------------------------
function waterState.enter()
if not isPleasedGiraffe() then return nil, 9999 end -- get out, and dont come back!
local position = mcontroller.position()
local target = waterState.findPosition(position)
if target ~= nil then
return {
targetPosition = target.position,
till = target.till,
timer = entity.randomizeParameterRange("gardenSettings.locateTime"),
located = false
}
end
return nil,entity.configParameter("gardenSettings.cooldown", 15)
end
--------------------------------------------------------------------------------
function waterState.update(dt, stateData)
stateData.timer = stateData.timer - dt
if stateData.targetPosition == nil then
return true
end
local position = mcontroller.position()
local toTarget = world.distance(stateData.targetPosition, position)
local distance = world.magnitude(toTarget)
util.debugLine(mcontroller.position(),vec2.add(mcontroller.position(),toTarget),"red")
if distance < entity.configParameter("gardenSettings.interactRange") then
-- entity.setFacingDirection(util.toDirection(toTarget[1]))
mcontroller.controlFace(util.toDirection(toTarget[1]))
setAnimationState("movement", "work")
if not stateData.located then
stateData.located = true
stateData.timer = entity.randomizeParameterRange("gardenSettings.plantTime")
elseif stateData.timer < 0 then
if stateData.till == nil then
storage.waterMemory = world.mod(vec2.add({0, -1}, stateData.targetPosition), "foreground")
else
-- local modPos = vec2.add({0.5, math.random(1,3)/2}, stateData.targetPosition)
local yoff = waterState.sloped(stateData.targetPosition) and 1 or 0.75
local modPos = vec2.add({0.5, yoff}, stateData.targetPosition)
world.spawnProjectile("watersprinkledroplet", modPos, entity.id(), {0, -1}, false, {power = 0})
if entity.hasSound("water") then entity.playSound("water") end
storage.waterMemory = nil
end
return true, 1
end
else
local dy = entity.configParameter("gardenSettings.fovHeight") / 2
move({toTarget[1], toTarget[2] + dy})
end
return stateData.timer < 0,entity.configParameter("gardenSettings.cooldown", 15)
end
--------------------------------------------------------------------------------
function waterState.sloped(pos)
return world.material({pos[1]+mcontroller.facingDirection(),pos[2]},"foreground") and 1
--local ml = world.material({pos[1]-1,pos[2]},"foreground") if ml then return true end
--local mr = world.material({pos[1]+1,pos[2]},"foreground") if mr then return true end
--return false
end
--------------------------------------------------------------------------------
function waterState.findPosition(position)
position[2] = position[2]+math.ceil(mcontroller.boundBox()[2]) -- lpk: fix so lumbers can do till too
local basePosition = {
math.floor(position[1] + 0.5),
math.floor(position[2] + 0.5) - 1
}
for offset = 1, entity.configParameter("gardenSettings.plantDistance", 10), 1 do
for d = -1, 2, 2 do
local targetPosition = vec2.add({ offset * d, 0 }, basePosition)
local modName = world.mod(vec2.add({0, -1}, targetPosition), "foreground")
-- world.debugText("%s",modName,vec2.add({0, -4+offset%3}, targetPosition),"white")
local success = false
if (storage.waterMemory and modName == storage.waterMemory ) then
local m1 = world.material(targetPosition, "foreground")
local m2 = world.material(vec2.add({0, -1}, targetPosition), "foreground")
success = not m1 and m2 == storage.matMemory
elseif (storage.waterMemory == nil and modName and string.find(modName, "tilleddry")) then
success = true
storage.matMemory = world.material(vec2.add({0, -1}, targetPosition), "foreground")
storage.waterMemory = modName
end
if canReachTarget(targetPosition) and success then
return { position = targetPosition, till = storage.waterMemory}
end
end
end
return nil
end |
-- NetHack 3.6 Samurai.des $NHDT-Date: 1432512783 2015/05/25 00:13:03 $ $NHDT-Branch: master $:$NHDT-Revision: 1.11 $
-- Copyright (c) 1989 by Jean-Christophe Collet
-- Copyright (c) 1991-92 by M. Stephenson, P. Winner
-- NetHack may be freely redistributed. See license for details.
--
des.level_init({ style = "solidfill", fg = " " });
des.level_flags("mazelevel");
des.level_init({ style="mines", fg=".", bg="P", smoothed=true, joined=true, walled=true })
--
des.stair("up")
des.stair("down")
--
des.object()
des.object()
des.object()
des.object()
des.object()
des.object()
des.object()
des.object()
des.object()
--
des.monster("d")
des.monster("wolf")
des.monster("wolf")
des.monster("wolf")
des.monster("wolf")
des.monster("wolf")
des.monster("stalker")
--
des.trap()
des.trap()
des.trap()
des.trap()
|
object_mobile_tatooine_sand_splitter_erib_kurrugh = object_mobile_shared_tatooine_sand_splitter_erib_kurrugh:new {
}
ObjectTemplates:addTemplate(object_mobile_tatooine_sand_splitter_erib_kurrugh, "object/mobile/tatooine_sand_splitter_erib_kurrugh.iff")
|
--[[
AMixer - interface for amixer
(c) 2012, Will Szumski [email protected]
(c) 2012, Adrian Smith, [email protected] (several functions used from his EnhancedDigitalOuput)
--]]
local oo = require("loop.simple")
local io = require("io")
local os = require("os")
local Applet = require("jive.Applet")
local System = require("jive.System")
local Framework = require("jive.ui.Framework")
local SimpleMenu = require("jive.ui.SimpleMenu")
local Textarea = require("jive.ui.Textarea")
local Label = require("jive.ui.Label")
local Popup = require("jive.ui.Popup")
local Checkbox = require("jive.ui.Checkbox")
local RadioGroup = require("jive.ui.RadioGroup")
local RadioButton = require("jive.ui.RadioButton")
local Slider = require("jive.ui.Slider")
local Surface = require("jive.ui.Surface")
local Task = require("jive.ui.Task")
local Timer = require("jive.ui.Timer")
local Icon = require("jive.ui.Icon")
local Window = require("jive.ui.Window")
local debug = require("jive.utils.debug")
local Group = require("jive.ui.Group")
local JIVE_VERSION = jive.JIVE_VERSION
local appletManager = appletManager
local STOP_SERVER_TIMEOUT = 10
local string, ipairs, tonumber, tostring, require, type, table, unpack, assert, math, pairs, tonumber = string, ipairs, tonumber, tostring, require, type, table, unpack, assert, math, pairs, tonumber
module(..., Framework.constants)
oo.class(_M, Applet)
applet = nil
function round(num, idp)
local mult = 10^(idp or 0)
if num >= 0 then return math.floor(num * mult + 0.5) / mult
else return math.ceil(num * mult - 0.5) / mult end
end
local AlsaCapability = oo.class()
-- represents a capability of an simple alsa control
--@param card integer card number that the control is associated with
--@param control table -- see_parseAmixerControls
--@param desc descibres what capability does, if nil overide getDescription()
function AlsaCapability:__init(args)
local obj = oo.rawnew(self)
log:debug('card: ', args.card)
obj.card = args.card
obj.control = args.control
obj.desc = args.desc
return obj
end
function AlsaCapability:getCard()
return self.card -1
end
-- combines name and index
function AlsaCapability:getControlIdentifier()
return '\'' .. self.control.name .. '\'' .. ',' .. self.control.index
end
function AlsaCapability:getStreamModifiers()
if self.playblack then
return 'playback'
elseif self.capture then
return 'capture'
end
return nil
end
-- overide and return a string containing suitable value
--function AlsaCapability:getValue()
-- return ''
--
--end
function AlsaCapability:set(value)
cmd = 'amixer -c ' .. self:getCard() .. ' set ' .. self:getControlIdentifier() .. ' ' .. (self:getStreamModifiers() and self:getStreamModifiers() .. ' ' or '') .. value
log:debug('executing cmd: ', cmd)
os.execute(cmd .. ' > /dev/null')
end
-- returns open file descriptor, so you can parse output
function AlsaCapability:get()
cmd = 'amixer -c ' .. self:getCard() .. ' get ' .. self:getControlIdentifier() .. ' ' .. (self:getStreamModifiers() and self:getStreamModifiers() .. ' ' or '')
log:debug('executing cmd: ', cmd)
local file = io.popen(cmd)
if file == nil then
log:error("the command," .. cmd .. ", failed")
return nil
end
return file
end
function AlsaCapability:setPlayBlack()
self.playblack = true
self.capture = false
end
function AlsaCapability:setCapture()
self.playblack = false
self.capture = true
end
function AlsaCapability:getDescription()
return self.desc
end
function AlsaCapability:getState()
assert(true == false, 'override this method')
end
local PVolumeCapability = oo.class({},AlsaCapability)
function PVolumeCapability:__init(args)
args.desc = applet:string("VOLUME_DESCRIPTION")
super = oo.superclass(PVolumeCapability):__init(args)
local obj = oo.rawnew(self,super)
return obj
end
function PVolumeCapability:setVolumePercent(vol)
assert(type(vol) == 'number', 'volume must be a number')
assert(vol <= 100 and vol >= 0, 'volume must be between 0 and 100')
self:set(vol .. '%')
end
function PVolumeCapability:getState()
file = self:get()
local volume = 'error'
local upper = nil
if not file then
return volume
end
control = applet:_parseAmixerOutput(file).controls[1]
for i,j in pairs(control) do
log:debug(i)
if type(i) == 'string' then
if i:lower():find('volume$') and j then
volume = j
log:debug('volume: ', volume)
upper = control['volume_upper_limit']
log:debug('volume_upper_limit: ', upper)
volume = round(volume * 100 / upper)
log:debug('volume_percent: ', volume)
volume = volume .. '%'
break
end
end
end
return volume
end
local PSwitchCapability = oo.class({},AlsaCapability)
function PSwitchCapability:__init(args)
args.desc = applet:string("MUTE_DESCRIPTION")
super = oo.superclass(PSwitchCapability):__init(args)
local obj = oo.rawnew(self,super)
return obj
end
function PSwitchCapability:getState()
local control_output = self:get()
local state = 'error'
if not control_output then
return state
end
control = applet:_parseAmixerOutput(control_output).controls[1]
if not control['state'] then
return state
end
log:debug('state: ' , control.state)
if control['state'] == 'on' then
return applet:string('UNMUTED')
end
return applet:string('MUTED')
end
function PSwitchCapability:setMuted(flag)
if flag then
self:set('mute')
return
end
self:set('unmute')
end
function PSwitchCapability:getMuted()
local state = self:getState()
if state == 'error' then
log:error('unable to determined muted stated')
return
end
if state == applet:string('MUTED') then
return true
end
return false
end
function PSwitchCapability:toggle()
local isMuted = self:getMuted()
if isMuted then
return self:setMuted(false)
end
return self:setMuted(true)
end
local CapabilityHandler = oo.class()
local PVolumeHandler = oo.class({},CapabilityHandler)
local PSwitchHandler = oo.class({},CapabilityHandler)
function CapabilityHandler:__init(args)
local obj = oo.rawnew(self)
obj.card = args.card
obj.control = args.control
obj.capability = args.capability
obj.callbacks = {}
return obj
end
function CapabilityHandler:addCallback(callback)
assert(type(callback) == 'function', 'callback must be a function')
self.callbacks[#self.callbacks + 1] = callback
end
function CapabilityHandler:_notifyAll(event)
for i,j in ipairs (self.callbacks) do
j(self,event)
end
end
function CapabilityHandler:processEvent()
assert(true == false, 'subclass must override')
end
function CapabilityHandler.getHandler(capability, card, control)
if capability == 'pvolume' then
return PVolumeHandler({capability=capability,card=card,control=control})
elseif capability == 'pswitch' then
return PSwitchHandler({capability=capability,card=card,control=control})
else
log:warn('unknown/ unimplemented capability: ', capability)
end
end
function CapabilityHandler:getState()
return self.capability:getState()
end
function CapabilityHandler:getDescription()
return self.capability:getDescription()
end
function PVolumeHandler:__init(args)
super = oo.superclass(PVolumeHandler):__init(args)
local obj = oo.rawnew(self,super)
obj.capability = PVolumeCapability({card = args.card, control = args.control})
return obj
end
function PVolumeHandler:_setVolume(value)
log:debug('slider value: ', value)
self.capability:setVolumePercent(tonumber(value))
self:_notifyAll()
end
function PVolumeHandler:processEvent()
local VOLUME_STEPS = 99
local VOLUME_MAX = 100
local VOLUME_STEP = VOLUME_MAX / VOLUME_STEPS
local current_volume = tonumber(self:getState():match('%d+'))
log:debug('current_volume: ', current_volume)
local window = Window("text_list", applet:string("VOLUME_DESCRIPTION"), "settingstitle")
self.slider = Slider("volume_slider", 1, VOLUME_STEPS + 1, current_volume,
function(slider, value)
self:_setVolume(value)
end)
window:addWidget(Group("slider_group", {
min = Icon("button_volume_min"),
slider = self.slider,
max = Icon("button_volume_max")
}))
window:addListener(EVENT_WINDOW_POP,
function(event)
self:_notifyAll()
end
)
return window
end
function PSwitchHandler:__init(args)
super = oo.superclass(PSwitchHandler):__init(args)
local obj = oo.rawnew(self,super)
obj.capability = PSwitchCapability({capability=args.capability,card = args.card, control = args.control})
return obj
end
function PSwitchHandler:processEvent()
self.capability:toggle()
self:_notifyAll()
end
function PSwitchHandler:getDescription()
muted = self.capability:getMuted()
if muted then
return applet:string('UNMUTE')
end
return applet:string('MUTE')
end
function updateStartMenu(self,menu)
menu:setHeaderWidget(Textarea("help_text", self:string("HELP_START")))
local cards = self:_parseCards()
self.current_card = self.current_card or 1
len = #cards
local incrementCard = function()
if self.current_card < len then
self.current_card = self.current_card + 1
else
self.current_card = 1
end
log:debug('current card :', self.current_card)
end
local items = {}
items[#items+1] = {
text = cards[self.current_card].desc,
sound = "WINDOWSHOW",
callback = function(event, menuItem)
incrementCard()
self:updateStartMenu(menu)
end,
}
for control_no, control in ipairs(cards[self.current_card].controls) do
-- we only deal with playback devices for now
if control.playback_channels then
items[#items+1] = {
text = control.name,
sound = "WINDOWSHOW",
callback = function(event, menuItem)
self:controlHandler(self.current_card, control)
end,
}
end
end
menu:setItems(items, #items)
end
--function test_caps(self,card,control)
--if control.name:lower() == 'master' then
-- p = PVolumeCapability({card = card, control = control})
-- p:setVolumePercent(20)
-- log:debug(p:getState())
-- a = PSwitchCapability({card = card, control = control})
-- a:setMuted(true)
-- log:debug('muted state: ', a:getMuted())
--end
--end
function updateControlHandlerMenu(self,menu,card,control)
local callback = function(handler,event)
self:updateControlHandlerMenu(menu,card,control)
end
local items = {}
for i, capability in ipairs(control.caps) do
local handler = CapabilityHandler.getHandler(capability,card,control)
if handler then
items[#items+1] = {
text = handler:getDescription(),
sound = "WINDOWSHOW",
callback = function(event, menuItem)
handler:addCallback(callback)
rtn = handler:processEvent()
if oo.instanceof(rtn,Window) then
self:tieAndShowWindow(rtn)
end
end,
}
end
end
menu:setItems(items, #items)
end
function controlHandler(self, card, control)
log:debug('card', card, '\t', 'control', control.name)
local window = Window("text_list", self:string("CAPABILITIES"))
local menu = SimpleMenu("menu")
window:addWidget(menu)
self:updateControlHandlerMenu(menu,card,control)
self:tieAndShowWindow(window)
return window
end
function startMenu(self, menuItem)
applet = self
local window = Window("text_list", self:string("SELECT_CONTROL"))
local menu = SimpleMenu("menu")
window:addWidget(menu)
self:updateStartMenu(menu)
self:tieAndShowWindow(window)
return window
end
--- paste
function pack(...)
return {...}
end
function string:split(sSeparator, nMax, bRegexp)
assert(sSeparator ~= '')
assert(nMax == nil or nMax >= 1)
local aRecord = {}
if self:len() > 0 then
local bPlain = not bRegexp
nMax = nMax or -1
local nField=1 nStart=1
local nFirst,nLast = self:find(sSeparator, nStart, bPlain)
while nFirst and nMax ~= 0 do
aRecord[nField] = self:sub(nStart, nFirst-1)
nField = nField+1
nStart = nLast+1
nFirst,nLast = self:find(sSeparator, nStart, bPlain)
nMax = nMax-1
end
aRecord[nField] = self:sub(nStart)
end
return aRecord
end
function _parseAmixerControls(self, card_no)
local card_no = card_no or 0
local t = nil
local file = io.popen("amixer -c " .. card_no)
if file == nil then
log:error("the command, amixer -c " .. card_no .. ", failed")
return t
end
t = self:_parseAmixerOutput(file)
return t
end
function _parseAmixerOutput(self, file)
local t ={}
-- parsing helper functions
local last
local parse = function(regexp, opt)
local tmp = last or file:read()
if tmp == nil then
return
end
local r = pack(string.match(tmp, regexp))
len = #r
if opt and len == 0 then
last = tmp
else
last = nil
end
-- FIXME: why does return not return the multiple returns from unpack?
-- for multiple returns unpack rtn
if len == 0 then
return nil
elseif len == 1 then
return unpack(r)
else
return r
end
end
local skip = function(number)
if last and number > 0 then
last = nil
number = number - 1
end
while number > 0 do
file:read()
number = number - 1
end
end
local eof = function()
if last then return false end
last = file:read()
return last == nil
end
local controls = {}
local addControlInfo = function (key, val)
if not val then
return
end
controls[#controls][key] = val
end
local extractVolumeInfo = function(channel)
local pattern = ':.-(%d+).*%[(on?f?f?)%].*'
pattern = channel .. pattern
local volume_info = parse(pattern,true) or false and skip(1)
local volume, state
if volume_info then
volume, state = unpack(volume_info)
else
pattern = channel .. ':.*%[(on?f?f?)%].*'
state = parse(pattern,true) or false and skip(1)
pattern = channel .. ':.-(%d+).*'
volume = parse(pattern,true) or false and skip(1)
end
return state, volume
end
while not eof() do
local info = parse('Simple mixer control%s+\'(.*)\',(%d+)')
local name, index
if info then
name, index = unpack(info)
end
local caps = parse('Capabilities:%s+(.*)',true) or false and skip(1)
if caps then
caps = caps:split(' ')
end
local items = parse('Items:%s+(.*)', true) or false and skip(1)
if items then
items = items:gsub('\'','')
items = items:split(' ')
end
local item0 = parse('Item0:%s+(.*)', true) or false and skip(1)
if item0 then
item0 = item0:gsub('\'','')
item0 = item0:gsub(' ','')
end
local playback_channels = parse('Playback channels:%s+(.*)', true) or false and skip(1)
local capture_channels = parse('Capture channels:%s+(.*)', true) or false and skip(1)
local limit_info = parse('Limits:.-(%d+).-(%d+)',true) or false and skip(1)
local lower_limit, upper_limit
if limit_info then
lower_limit, upper_limit = unpack(limit_info)
log:debug('upper / lower volume limit: ' , lower_limit, '/' , upper_limit)
end
local mono_state, mono_volume = extractVolumeInfo('Mono')
local front_left_state, front_left_volume = extractVolumeInfo('Front Left')
local front_right_state, front_right_volume = extractVolumeInfo('Front Right')
state = mono_state or front_left_state or front_right_state
if state then
log:debug('state: ', state)
end
if name then
controls[#controls+1] = {name = name, }
end
-- only adds if non nil
addControlInfo('index',index)
addControlInfo('caps',caps)
addControlInfo('playback_channels',playback_channels)
addControlInfo('capture_channels',capture_channels)
addControlInfo('state',state)
addControlInfo('mono_volume',mono_volume)
addControlInfo('volume_lower_limit',lower_limit)
addControlInfo('volume_upper_limit', upper_limit)
addControlInfo('front_left_volume',front_left_volume)
addControlInfo('front_right_volume',front_right_volume)
addControlInfo('items',items)
addControlInfo('item0',item0)
end
t.controls = controls
file:close()
return t
end
function _parseCards(self)
local t = {}
local cards = io.open("/proc/asound/cards", "r")
if cards == nil then
log:error("/proc/asound/cards could not be opened")
return
end
-- read and parse entries
for line in cards:lines() do
local num, id, desc = string.match(line, "(%d+)%s+%[(.-)%s+%]:%s+(.*)")
if num then
t[#t +1] = self:_parseAmixerControls(num)
t[#t]['id'] = id
t[#t]['desc'] = desc
end
end
cards:close()
return t
end
|
modifier_creature_lich_statue = class({})
--------------------------------------------------------------------------------
function modifier_creature_lich_statue:IsHidden()
return true
end
--------------------------------------------------------------------------------
function modifier_creature_lich_statue:IsPurgable()
return false
end
--------------------------------------------------------------------------------
function modifier_creature_lich_statue:CheckState()
local state = {}
if IsServer() then
state[ MODIFIER_STATE_NO_UNIT_COLLISION ] = true
state[ MODIFIER_STATE_NO_HEALTH_BAR ] = true
state[ MODIFIER_STATE_NOT_ON_MINIMAP ] = true
state[ MODIFIER_STATE_ROOTED ] = true
state[ MODIFIER_STATE_BLIND ] = true
state[ MODIFIER_STATE_DISARMED ] = true
state[ MODIFIER_STATE_ATTACK_IMMUNE ] = true
state[ MODIFIER_STATE_FLYING_FOR_PATHING_PURPOSES_ONLY ] = true
end
return state
end
--------------------------------------------------------------------------------
|
local primitiveTypes = {
Bool = true,
Enum = true,
Float32 = true,
Float64 = true,
Int32 = true,
Int64 = true,
String = true,
Content = true,
}
local function identity(...)
return ...
end
local encoders = {
Bool = identity,
Float32 = identity,
Float64 = identity,
Int32 = identity,
Int64 = identity,
String = identity,
BinaryString = identity,
Content = identity,
CFrame = function(value)
return {value:GetComponents()}
end,
Color3 = function(value)
return {value.r, value.g, value.b}
end,
NumberRange = function(value)
return {value.Min, value.Max}
end,
Rect = function(value)
return {value.Min.X, value.Min.Y, value.Max.X, value.Max.Y}
end,
UDim = function(value)
return {value.Scale, value.Offset}
end,
UDim2 = function(value)
return {value.X.Scale, value.X.Offset, value.Y.Scale, value.Y.Offset}
end,
Vector2 = function(value)
return {value.X, value.Y}
end,
Vector2int16 = function(value)
return {value.X, value.Y}
end,
Vector3 = function(value)
return {value.X, value.Y, value.Z}
end,
Vector3int16 = function(value)
return {value.X, value.Y, value.Z}
end,
}
local directDecoders = {
CFrame = CFrame.new,
Color3 = Color3.new,
Color3uint8 = Color3.fromRGB,
NumberRange = NumberRange.new,
Rect = Rect.new,
UDim = UDim.new,
UDim2 = UDim2.new,
Vector2 = Vector2.new,
Vector2int16 = Vector2int16.new,
Vector3 = Vector3.new,
Vector3int16 = Vector3int16.new,
}
local EncodedValue = {}
function EncodedValue.decode(encodedValue)
if primitiveTypes[encodedValue.Type] then
return true, encodedValue.Value
end
local constructor = directDecoders[encodedValue.Type]
if constructor ~= nil then
return true, constructor(unpack(encodedValue.Value))
end
return false
end
function EncodedValue.encode(rbxValue, reflectionType)
if reflectionType ~= nil then
if reflectionType.type == "data" then
local encoder = encoders[reflectionType.name]
if encoder ~= nil then
return true, {
Type = reflectionType.name,
Value = encoder(rbxValue),
}
end
elseif reflectionType.type == "enum" then
return true, {
Type = "Enum",
Value = rbxValue.Value,
}
end
end
return false
end
return EncodedValue |
--[[
<name>
<expression>
<expression>
opt <expression>
<statements>
]]
return
function(self, node)
node.index = node[1]
node[1] = nil
node.start_val = node[2]
node[2] = nil
node.end_val = node[3]
node[3] = nil
local seek_pos = 4
if (node[seek_pos].type == 'expression') then
node.increment = node[seek_pos]
node[seek_pos] = nil
seek_pos = seek_pos + 1
end
node.body = node[seek_pos]
node[seek_pos] = nil
seek_pos = seek_pos + 1
end
|
local playerModule = require "module.playerModule"
local View = {};
function View:Start(data)
self.view = CS.SGK.UIReference.Setup(self.gameObject);
self.data = data;
self:InitView();
end
function View:InitView()
local side1 = playerModule.GetSelfID();
local side2 = self.data.attacker_pid == side1 and self.data.defender_pid or self.data.attacker_pid;
module.playerModule.Get(side1, function (player)
self.view.side1.name[UI.Text].text = player.name;
utils.IconFrameHelper.Create(self.view.side1.IconFrame, {pid = player.id});
module.playerModule.GetFightData(side1, false, function ()
self.view.side1.rotateNum[SGK.RotateNumber]:Change(0, math.ceil(module.playerModule.GetFightData(side1).capacity));
end)
end)
module.playerModule.Get(side2, function (player)
self.view.side2.name[UI.Text].text = player.name;
utils.IconFrameHelper.Create(self.view.side2.IconFrame, {pid = player.id});
module.playerModule.GetFightData(side2, true, function ()
self.view.side2.rotateNum[SGK.RotateNumber]:Change(0, math.ceil(module.playerModule.GetFightData(side2).capacity));
end)
end)
local action = self.data.winner == side1 and "guild_fight_ani1" or "guild_fight_ani2";
self.view[UnityEngine.Animator]:Play(action);
SGK.Action.DelayTime.Create(4.5):OnComplete(function ()
if self.data and self.data.func then
self.data.func()
end
UnityEngine.GameObject.Destroy(self.gameObject)
end)
end
function View:listEvent()
return {
"",
}
end
function View:onEvent(event, ...)
print("onEvent", event, ...);
if event == "" then
end
end
return View; |
//________________________________
//
// NS2 CustomEntitesMod
// Made by JimWest 2012
//
//________________________________
// LogicTrigger.lua
// Entity for mappers to create teleporters
Script.Load("lua/ExtraEntitiesMod/LogicMixin.lua")
class 'LogicTrigger' (Trigger)
LogicTrigger.kMapName = "logic_trigger"
local networkVars =
{
}
AddMixinNetworkVars(LogicMixin, networkVars)
function LogicTrigger:OnCreate()
Trigger.OnCreate(self)
end
function LogicTrigger:OnInitialized()
Trigger.OnInitialized(self)
if Server then
InitMixin(self, LogicMixin)
self.triggered = false
self.triggerPlayerList = {}
self.timeLastTriggered = 0
self.coolDownTime = self.coolDownTime or 0
end
end
function LogicTrigger:Reset()
if Server then
self.triggered = false
self.triggerPlayerList = {}
self.timeLastTriggered = 0
end
end
if Server then
function LogicTrigger:CheckTrigger(enterEnt)
local timeOk = ((Shared.GetTime() + self.coolDownTime) >= self.timeLastTriggered)
if self.disallowNpcs then
timeOk = not enterEnt.isaNpc
end
if self.enabled and timeOk then
local teamNumber = enterEnt:GetTeamNumber()
local teamOk = false
if self.teamNumber == 0 or self.teamNumber == nil then
teamOk = true
elseif self.teamNumber == 1 then
if teamNumber == 1 then
teamOk = true
end
elseif self.teamNumber == 2 then
if teamNumber == 2 then
teamOk = true
end
end
if teamOk then
local typeOk = false
if self.teamType == 0 or self.teamType == nil then // triggers all the time
typeOk = true
elseif self.teamType == 1 then // trigger once per player
local playerId = enterEnt:GetId()
if not table.contains(self.triggerPlayerList, playerId) then
typeOk = true
table.insert(self.triggerPlayerList, playerId)
end
elseif self.teamType == 2 then // trigger only once
typeOk = not self.triggered
self.triggered = true
elseif self.teamType == 3 then // trigger only once per SteamId
// just ignore npcs here
if enterEnt.isaNpc then
typeOk = true
else
local steamid = Server.GetOwner(enterEnt):GetUserId()
if not table.contains(self.triggerPlayerList, steamid) then
typeOk = true
table.insert(self.triggerPlayerList, steamid)
end
end
end
if typeOk then
self:TriggerOutputs(enterEnt)
self.timeLastTriggered = Shared.GetTime()
end
end
end
end
function LogicTrigger:OnTriggerEntered(enterEnt, triggerEnt)
if enterEnt:isa("Player") and (self.triggerStyle == 0 or self.triggerStyle == nil) then
self:CheckTrigger(enterEnt)
end
end
function LogicTrigger:OnTriggerExited(exitEnt, triggerEnt)
if exitEnt:isa("Player") and self.triggerStyle == 1 then
self:CheckTrigger(exitEnt)
end
end
function LogicTrigger:OnLogicTrigger(player)
self:OnTriggerAction()
end
end
Shared.LinkClassToMap("LogicTrigger", LogicTrigger.kMapName, networkVars) |
object_tangible_tcg_series5_hangar_ships_arc170 = object_tangible_tcg_series5_hangar_ships_shared_arc170:new {
}
ObjectTemplates:addTemplate(object_tangible_tcg_series5_hangar_ships_arc170, "object/tangible/tcg/series5/hangar_ships/arc170.iff")
|
require("busted.runner")()
local name = require("citeproc.citeproc-node-names").name
describe("String split", function ()
local context = {
["initialize-with-hyphen"] = true,
initialize=true,
}
describe("Initialize true:", function ()
context.initialize = true
describe("Space:", function ()
it("ME", function ()
assert.equal("M", name:initialize("ME", " ", context))
end)
it("M.E", function ()
assert.equal("M E", name:initialize("M.E", " ", context))
end)
it("M E.", function ()
assert.equal("M E", name:initialize("M E.", " ", context))
end)
it("John M.E.", function ()
assert.equal("J M E", name:initialize("John M.E.", " ", context))
end)
it("M E", function ()
assert.equal("M E", name:initialize("M E", " ", context))
end)
it("ME.", function ()
assert.equal("ME", name:initialize("ME.", " ", context))
end)
it("Me.", function ()
assert.equal("Me", name:initialize("Me.", " ", context))
end)
it("Ph.M.E.", function ()
assert.equal("Ph M E", name:initialize("Ph.M.E.", " ", context))
end)
it("Ph. M.E.", function ()
assert.equal("Ph M E", name:initialize("Ph. M.E.", " ", context))
end)
end)
describe("Empty:", function ()
it("ME", function ()
assert.equal("M", name:initialize("ME", "", context))
end)
it("M.E", function ()
assert.equal("ME", name:initialize("M.E", "", context))
end)
it("M E.", function ()
assert.equal("ME", name:initialize("M E.", "", context))
end)
it("John M.E.", function ()
assert.equal("JME", name:initialize("John M.E.", "", context))
end)
it("M E", function ()
assert.equal("ME", name:initialize("M E", "", context))
end)
it("ME.", function ()
assert.equal("ME", name:initialize("ME.", "", context))
end)
it("Me.", function ()
assert.equal("Me", name:initialize("Me.", "", context))
end)
it("Ph.M.E.", function ()
assert.equal("PhME", name:initialize("Ph.M.E.", "", context))
end)
it("Ph. M.E.", function ()
assert.equal("PhME", name:initialize("Ph. M.E.", "", context))
end)
end)
describe("Period:", function ()
it("ME", function ()
assert.equal("M.", name:initialize("ME", ".", context))
end)
it("M.E", function ()
assert.equal("M.E.", name:initialize("M.E", ".", context))
end)
it("M E.", function ()
assert.equal("M.E.", name:initialize("M E.", ".", context))
end)
it("John M.E.", function ()
assert.equal("J.M.E.", name:initialize("John M.E.", ".", context))
end)
it("M E", function ()
assert.equal("M.E.", name:initialize("M E", ".", context))
end)
it("ME.", function ()
assert.equal("ME.", name:initialize("ME.", ".", context))
end)
it("Me.", function ()
assert.equal("Me.", name:initialize("Me.", ".", context))
end)
it("Ph.M.E.", function ()
assert.equal("Ph.M.E.", name:initialize("Ph.M.E.", ".", context))
end)
it("Ph. M.E.", function ()
assert.equal("Ph.M.E.", name:initialize("Ph. M.E.", ".", context))
end)
end)
describe("PeriodSpace:", function ()
it("ME", function ()
assert.equal("M.", name:initialize("ME", ". ", context))
end)
it("M.E", function ()
assert.equal("M. E.", name:initialize("M.E", ". ", context))
end)
it("M E.", function ()
assert.equal("M. E.", name:initialize("M E.", ". ", context))
end)
it("John M.E.", function ()
assert.equal("J. M. E.", name:initialize("John M.E.", ". ", context))
end)
it("M E", function ()
assert.equal("M. E.", name:initialize("M E", ". ", context))
end)
it("ME.", function ()
assert.equal("ME.", name:initialize("ME.", ". ", context))
end)
it("Me.", function ()
assert.equal("Me.", name:initialize("Me.", ". ", context))
end)
it("Ph.M.E.", function ()
assert.equal("Ph. M. E.", name:initialize("Ph.M.E.", ". ", context))
end)
it("Ph. M.E.", function ()
assert.equal("Ph. M. E.", name:initialize("Ph. M.E.", ". ", context))
end)
end)
end)
describe("Initialize false:", function ()
context.initialize = false
describe("Space:", function ()
it("ME", function ()
assert.equal("ME", name:initialize("ME", " ", context))
end)
it("M.E", function ()
assert.equal("M E", name:initialize("M.E", " ", context))
end)
it("M E.", function ()
assert.equal("M E", name:initialize("M E.", " ", context))
end)
it("John M.E.", function ()
assert.equal("John M E", name:initialize("John M.E.", " ", context))
end)
it("M E", function ()
assert.equal("M E", name:initialize("M E", " ", context))
end)
it("ME.", function ()
assert.equal("ME", name:initialize("ME.", " ", context))
end)
it("Me.", function ()
assert.equal("Me", name:initialize("Me.", " ", context))
end)
it("Ph.M.E.", function ()
assert.equal("Ph M E", name:initialize("Ph.M.E.", " ", context))
end)
it("Ph. M.E.", function ()
assert.equal("Ph M E", name:initialize("Ph. M.E.", " ", context))
end)
end)
describe("Empty:", function ()
it("ME", function ()
assert.equal("ME", name:initialize("ME", "", context))
end)
it("M.E", function ()
assert.equal("ME", name:initialize("M.E", "", context))
end)
it("M E.", function ()
assert.equal("ME", name:initialize("M E.", "", context))
end)
it("John M.E.", function ()
assert.equal("John ME", name:initialize("John M.E.", "", context))
end)
it("M E", function ()
assert.equal("ME", name:initialize("M E", "", context))
end)
it("ME.", function ()
assert.equal("ME", name:initialize("ME.", "", context))
end)
it("Me.", function ()
assert.equal("Me", name:initialize("Me.", "", context))
end)
it("Ph.M.E.", function ()
assert.equal("PhME", name:initialize("Ph.M.E.", "", context))
end)
it("Ph. M.E.", function ()
assert.equal("PhME", name:initialize("Ph. M.E.", "", context))
end)
end)
describe("Period:", function ()
it("ME", function ()
assert.equal("ME", name:initialize("ME", ".", context))
end)
it("M.E", function ()
assert.equal("M.E.", name:initialize("M.E", ".", context))
end)
it("M E.", function ()
assert.equal("M.E.", name:initialize("M E.", ".", context))
end)
it("John M.E.", function ()
assert.equal("John M.E.", name:initialize("John M.E.", ".", context))
end)
it("M E", function ()
assert.equal("M.E.", name:initialize("M E", ".", context))
end)
it("ME.", function ()
assert.equal("ME.", name:initialize("ME.", ".", context))
end)
it("Me.", function ()
assert.equal("Me.", name:initialize("Me.", ".", context))
end)
it("Ph.M.E.", function ()
assert.equal("Ph.M.E.", name:initialize("Ph.M.E.", ".", context))
end)
it("Ph. M.E.", function ()
assert.equal("Ph.M.E.", name:initialize("Ph. M.E.", ".", context))
end)
end)
describe("PeriodSpace:", function ()
it("ME", function ()
assert.equal("ME", name:initialize("ME", ". ", context))
end)
it("M.E", function ()
assert.equal("M. E.", name:initialize("M.E", ". ", context))
end)
it("M E.", function ()
assert.equal("M. E.", name:initialize("M E.", ". ", context))
end)
it("John M.E.", function ()
assert.equal("John M. E.", name:initialize("John M.E.", ". ", context))
end)
it("M E", function ()
assert.equal("M. E.", name:initialize("M E", ". ", context))
end)
it("ME.", function ()
assert.equal("ME.", name:initialize("ME.", ". ", context))
end)
it("Me.", function ()
assert.equal("Me.", name:initialize("Me.", ". ", context))
end)
it("Ph.M.E.", function ()
assert.equal("Ph. M. E.", name:initialize("Ph.M.E.", ". ", context))
end)
it("Ph. M.E.", function ()
assert.equal("Ph. M. E.", name:initialize("Ph. M.E.", ". ", context))
end)
end)
end)
-- describe("initialize-with-hyphen = false", function()
-- context.options["initialize-with-hyphen"] = false
-- context.initialize = true
-- it("initialize", function()
-- assert.equal("J.L.", name:initialize("Jean-Luc", ".", context))
-- end)
-- end)
end)
|
return [[
{
"Lang" : "pl",
"Name" : "polski",
"Entities.gmod_subway_ezh3.Buttons.Stopkran.EmergencyBrakeValveToggle" : "Hamulec awaryjny",
"Entities.gmod_subway_ezh3.Buttons.Back.BackDoor" : "Drzwi tylne",
"Entities.gmod_subway_ezh3.Buttons.DriverValveBLTLDisconnect.DriverValveBLDisconnectToggle" : "Zawór dwudrożny przewodu głównego",
"Entities.gmod_subway_ezh3.Buttons.DriverValveBLTLDisconnect.DriverValveTLDisconnectToggle" : "Zawór dwudrożny przewodu zasilającego",
"Entities.gmod_subway_ezh3.Buttons.Battery.VBToggle" : "AB: Włącznik akumulatorów baterii",
"Entities.gmod_subway_ezh3.Buttons.FrontPneumatic.FrontBrakeLineIsolationToggle" : "Zawór przewodu głównego sprzęgu powietrznego",
"Entities.gmod_subway_ezh3.Buttons.FrontPneumatic.FrontTrainLineIsolationToggle" : "Zawór przewodu zasilającegosprzęgu powietrznego",
"Entities.gmod_subway_ezh3.Buttons.ASNP.R_ASNPMenuSet" : "Informator: Menu",
"Entities.gmod_subway_ezh3.Buttons.ASNP.R_ASNPUpSet" : "Informator: W górę",
"Entities.gmod_subway_ezh3.Buttons.ASNP.R_ASNPDownSet" : "Informator: W dół",
"Entities.gmod_subway_ezh3.Buttons.ASNP.R_ASNPOnToggle" : "Informator: Włączenie",
"Entities.gmod_subway_ezh3.Buttons.PassengerDoor1.PassengerDoor" : "Drzwi do klasy",
"Entities.gmod_subway_ezh3.Buttons.PassengerDoor.PassengerDoor" : "Drzwi do klasy",
"Entities.gmod_subway_ezh3.Buttons.CabinDoor.CabinDoor" : "Drzwi do kabiny",
"Entities.gmod_subway_ezh3.Buttons.Front.FrontDoor" : "Drzwi przednie",
"Entities.gmod_subway_ezh3.Buttons.GV.GVToggle" : "Wyłącznik główny",
"Entities.gmod_subway_ezh3.Buttons.RearPneumatic.RearTrainLineIsolationToggle" : "Zawór przewodu zasilającego sprzęgu powietrznego",
"Entities.gmod_subway_ezh3.Buttons.RearPneumatic.RearBrakeLineIsolationToggle" : "Zawór przewodu głównego sprzęgu powietrznego",
"Entities.gmod_subway_ezh3.Buttons.Panel.!OCH" : "ОЧ: Kontrolka braku sygnału ARS",
"Entities.gmod_subway_ezh3.Buttons.Panel.!0" : "0: Kontrolka sygnału zatrzymania ARS",
"Entities.gmod_subway_ezh3.Buttons.Panel.!40" : "40: Kontrolka ograniczenia prędkości do 40 km/h",
"Entities.gmod_subway_ezh3.Buttons.Panel.!60" : "60: Kontrolka ograniczenia prędkości do 60 km/h",
"Entities.gmod_subway_ezh3.Buttons.Panel.!70" : "70: Kontrolka ograniczenia prędkości do 70 km/h",
"Entities.gmod_subway_ezh3.Buttons.Panel.!80" : "80: Kontrolka ograniczenia prędkości do 80 km/h",
"Entities.gmod_subway_ezh3.Buttons.Panel.!Speedometer" : "Wskaźnik prędkości [km/h]",
"Entities.gmod_subway_ezh3.Buttons.Panel.!TotalAmpermeter" : "Amperomierz WN [А]",
"Entities.gmod_subway_ezh3.Buttons.Panel.!TotalVoltmeter" : "Woltomierz WN [kV]",
"Entities.gmod_subway_ezh3.Buttons.Panel.!BatteryVoltage" : "Napięcie akumulatorów baterii [V]",
"Entities.gmod_subway_ezh3.Buttons.Panel.!BrakeCylinder" : "Ciśnienie w cylindrach hamulcowych",
"Entities.gmod_subway_ezh3.Buttons.Panel.!LinesPressure" : "Ciśnienie w zbiorniku (czarna) i przewodzie głównym (czerwona)",
"Entities.gmod_subway_ezh3.Buttons.Main.KU1Toggle" : "VMK: Włączenie sprężarki",
"Entities.gmod_subway_ezh3.Buttons.Main.SAMM1Set" : "САММ: Wyłączenie rozruchu",
"Entities.gmod_subway_ezh3.Buttons.Main.SAMM2Set" : "САММ: Start",
"Entities.gmod_subway_ezh3.Buttons.Main.SAMM3Set" : "САММ: Reset",
"Entities.gmod_subway_ezh3.Buttons.Main.SAMMSignal1" : "Kontrolka: Jazda-hamowanie",
"Entities.gmod_subway_ezh3.Buttons.Main.SAMMSignal2" : "Kontrolka: Działanie САММ",
"Entities.gmod_subway_ezh3.Buttons.Main.SAMMSignal3" : "Kontrolka: Włączona jednostka wykonawcza САММ",
"Entities.gmod_subway_ezh3.Buttons.Main.SAMMOnToggle" : "САММ: Włączenie sytemu automatycznego prowadzenia składu",
"Entities.gmod_subway_ezh3.Buttons.Main.SAMMBlokToggle" : "САММ: Jednostka wykonawcza",
"Entities.gmod_subway_ezh3.Buttons.Main.SAMMCommand3Set" : "САММ: X-2",
"Entities.gmod_subway_ezh3.Buttons.Main.SAMMCommand2Set" : "САММ: Doganianie rozkładu",
"Entities.gmod_subway_ezh3.Buttons.Main.SAMMCommand1Set" : "САММ: Zezwolenie",
"Entities.gmod_subway_ezh3.Buttons.Main.KSNSet" : "КСН: Sygnalizacja usterki",
"Entities.gmod_subway_ezh3.Buttons.Main.R_Program1Set" : "Zapowiedź 1",
"Entities.gmod_subway_ezh3.Buttons.Main.R_Program2Set" : "Zapowiedź 2",
"Entities.gmod_subway_ezh3.Buttons.Main.VUSToggle" : "Przyciemnianie świateł jezdnych",
"Entities.gmod_subway_ezh3.Buttons.Main.L_3Toggle" : "Oświetlenie przyrządów",
"Entities.gmod_subway_ezh3.Buttons.Main.VAHToggle" : "Jazda awaryjna",
"Entities.gmod_subway_ezh3.Buttons.Main.DIPonSet" : "Włączanie oświetlenia",
"Entities.gmod_subway_ezh3.Buttons.Main.DIPoffSet" : "Wyłączanie oświetlenia",
"Entities.gmod_subway_ezh3.Buttons.Main.KSDSet" : "KSD: Sprawdzanie sygnalizacji drzwi",
"Entities.gmod_subway_ezh3.Buttons.Main.KVTSet" : "КВТ: Kasowanie hamowania ARS",
"Entities.gmod_subway_ezh3.Buttons.Main.KBSet" : "КB: Czuwak (przycisk)",
"Entities.gmod_subway_ezh3.Buttons.Main.KBLamp" : "LHRK: Ruch reostatu",
"Entities.gmod_subway_ezh3.Buttons.Main.ARSToggle" : "АRS: Automatyczna regulacja prędkości",
"Entities.gmod_subway_ezh3.Buttons.Main.R_UNchToggle" : "UNCh: Wzmacniacz niskich częstotliwości",
"Entities.gmod_subway_ezh3.Buttons.Main.VUD1Toggle" : "VUD: Włącznik sterowania drzwiami",
"Entities.gmod_subway_ezh3.Buttons.Main.R_RadioToggle" : "Zapowiedzi głosowe (wbudowane)",
"Entities.gmod_subway_ezh3.Buttons.Main.ALSToggle" : "АLS: Automatyczna sygnalizacja pociągu",
"Entities.gmod_subway_ezh3.Buttons.Main.VozvratRPSet" : "KVRP: Odblokowanie przekaźnika nadmiarowego",
"Entities.gmod_subway_ezh3.Buttons.Main.RingSet" : "Dzwonek",
"Entities.gmod_subway_ezh3.Buttons.Main.L_2Toggle" : "Oświetlenie kabiny",
"Entities.gmod_subway_ezh3.Buttons.Main.KRZDSet" : "KRZD: Awaryjne zamykanie drzwi",
"Entities.gmod_subway_ezh3.Buttons.Main.KDPSet" : "KDP: Otwieranie prawych drzwi",
"Entities.gmod_subway_ezh3.Buttons.Main.KDLSet" : "KDL: Otwieranie lewych drzwi",
"Entities.gmod_subway_ezh3.Buttons.Main.KAHSet" : "KAH: Jazda awaryjna",
"Entities.gmod_subway_ezh3.Buttons.Main.RezMKSet" : "Awaryjne załączanie sprężarki",
"Entities.gmod_subway_ezh3.Buttons.Main.KRPSet" : "KRP: Rozruch awaryjny",
"Entities.gmod_subway_ezh3.Buttons.Main.RSTToggle" : "VPR: Załączenie radiostacji",
"Entities.gmod_subway_ezh3.Buttons.Main.R_GToggle" : "Głośnik (dźwięk w kabinie)",
"Entities.gmod_subway_ezh3.Buttons.Main.R_ZSToggle" : "ZS: Nagłośnienie klasy",
"Entities.gmod_subway_ezh3.Buttons.Main.Custom2Set" : "Nieużywany przełącznik",
"Entities.gmod_subway_ezh3.Buttons.Main.Custom3Set" : "Nieużywany przełącznik",
"Entities.gmod_subway_ezh3.Buttons.Main.ASNPPlay" : "Odtwarzanie zapowiedzi",
"Entities.gmod_subway_ezh3.Buttons.AV1.VU3Toggle" : "VU3: Oświetlenie kabiny",
"Entities.gmod_subway_ezh3.Buttons.AV1.VU2Toggle" : "VU2: Awaryjne oświetlenie (45 V)",
"Entities.gmod_subway_ezh3.Buttons.AV1.VU1Toggle" : "VU1: Ogrzewanie kabiny (3 kW)\n",
"Entities.gmod_subway_ezh3.Buttons.AVMain.AV8BToggle" : "АV-8B: Wyłącznik automatyczny WN",
"Entities.gmod_subway_ezh3.Buttons.RC1.RC1Toggle" : "RC_ARS: Odłączenie obwodów ARS",
"Entities.gmod_subway_ezh3.Buttons.UAVAPanel.UAVAToggle" : "UAVA: Wyłączenie autostopu",
"Entities.gmod_subway_ezh3.Buttons.UAVAPanel.UAVAContactSet" : "UAVA: odblokowanie przekaźników",
"Entities.gmod_subway_ezh3.Buttons.VUHelper.VUToggle" : "VU: Wyłącznik sterowania",
"Entities.gmod_subway_ezh3.Buttons.HelperPanel.VDLSet" : "VDL: Otwieranie lewych drzwi",
"Entities.gmod_subway_ezh3.Buttons.HelperPanel.VUD2Toggle" : "VUD2: Włącznik sterowania drzwiami",
"Entities.gmod_subway_ezh3.Buttons.EPKDisconnect.EPKToggle" : "EPV: Zawór elektropneumatyczny",
"Entities.gmod_subway_ezh3.Buttons.VU.VUToggle" : "VU: Sterowanie pociągiem",
"Entities.gmod_subway_ezh3.Buttons.ParkingBrake.ParkingBrakeLeft" : "Powrót koła hamulca ręcznego",
"Entities.gmod_subway_ezh3.Buttons.ParkingBrake.ParkingBrakeRight" : "Powrót koła hamulca ręcznego",
"Entities.gmod_subway_ezh3.Buttons.AirDistributor.AirDistributorDisconnectToggle" : "Blokada dystrybutora powietrza",
"Entities.gmod_subway_em508t.Buttons.Stopkran.EmergencyBrakeValveToggle" : "Hamulec awaryjny",
"Entities.gmod_subway_em508t.Buttons.Battery.VBToggle" : "AB: Włącznik akumulatorów baterii (obwody wspomagające NN)",
"Entities.gmod_subway_em508t.Buttons.FrontPneumatic.FrontBrakeLineIsolationToggle" : "Zawór przewodu głównego sprzęgu powietrznego",
"Entities.gmod_subway_em508t.Buttons.FrontPneumatic.FrontTrainLineIsolationToggle" : "Zawór przewodu zasilającego sprzęgu powietrznego",
"Entities.gmod_subway_em508t.Buttons.GV.GVToggle" : "Wyłącznik główny",
"Entities.gmod_subway_em508t.Buttons.RearPneumatic.RearTrainLineIsolationToggle" : "Zawór przewodu zasilającego sprzęgu powietrznego",
"Entities.gmod_subway_em508t.Buttons.RearPneumatic.RearBrakeLineIsolationToggle" : "Zawór przewodu głównego sprzęgu powietrznego",
"Entities.gmod_subway_em508t.Buttons.RearDoor.RearDoor" : "Drzwi do klasy",
"Entities.gmod_subway_em508t.Buttons.Back2.!HVFuse" : "Blok bezpieczników WN",
"Entities.gmod_subway_em508t.Buttons.Back2.!Relays" : "Skrzynia aparatów ładowania baterii akumulatorów i dystrybucji powietrza do siłowników drzwi",
"Entities.gmod_subway_em508t.Buttons.Back2.!Heater" : "Farelka",
"Entities.gmod_subway_em508t.Buttons.Front.FrontDoor" : "Drzwi przednie",
"Entities.gmod_subway_em508t.Buttons.AV1.VU3Toggle" : "VU3: Oświetlenie kabiny\n",
"Entities.gmod_subway_em508t.Buttons.AV1.VU2Toggle" : "VU2: Awaryjne oświetlenie (45 V)",
"Entities.gmod_subway_em508t.Buttons.AV1.VU1Toggle" : "VU1: Ogrzewanie kabiny (3 kW)",
"Entities.gmod_subway_em508t.Buttons.ParkingBrake.ParkingBrakeLeft" : "Powrót koła hamulca ręcznego",
"Entities.gmod_subway_em508t.Buttons.ParkingBrake.ParkingBrakeRight" : "Powrót koła hamulca ręcznego",
"Entities.gmod_subway_em508t.Buttons.CabinDoor.CabinDoor1" : "Drzwi do kabiny",
"Entities.gmod_subway_em508t.Buttons.PassengerDoor.PassengerDoor" : "Drzwi do klasy",
"Entities.gmod_subway_em508t.Buttons.PassengerDoor1.PassengerDoor" : "Drzwi do klasy",
"Entities.gmod_subway_em508t.Buttons.Main.!RedRP" : "RP: Obwody mocy nie załączyły się",
"Entities.gmod_subway_em508t.Buttons.Main.!GreenRP" : "RP: Zadziałanie przekaźnika nadmiarowego",
"Entities.gmod_subway_em508t.Buttons.Main.!SD" : "SD: Sygnalizacja drzwi",
"Entities.gmod_subway_em508t.Buttons.Main.KDLSet" : "Otwieranie lewych drzwi",
"Entities.gmod_subway_em508t.Buttons.Main.KSDSet" : "KSD: Sprawdzanie sygnalizacji drzwi",
"Entities.gmod_subway_em508t.Buttons.Main.VozvratRPSet" : "VozvratRP: Odblokowanie przekaźnika nadmiarowego",
"Entities.gmod_subway_em508t.Buttons.Main.KSNSet" : "Sygnalizacja usterki",
"Entities.gmod_subway_em508t.Buttons.Main.VUD1Toggle" : "Włącznik sterowania drzwiami",
"Entities.gmod_subway_em508t.Buttons.Main.KU1Toggle" : "Włącznik sprężarki",
"Entities.gmod_subway_em508t.Buttons.Main.DIPonSet" : "KU4: Włączanie oświetlenia",
"Entities.gmod_subway_em508t.Buttons.Main.DIPoffSet" : "KU5: Wyłączanie oświetlenia",
"Entities.gmod_subway_em508t.Buttons.Main.RezMKSet" : "Awaryjne załączanie sprężarki",
"Entities.gmod_subway_em508t.Buttons.Main.KDPSet" : "KDP: Otwieranie prawych drzwi",
"Entities.gmod_subway_em508t.Buttons.Main.KRZDSet" : "KU10: Awaryjne zamykanie drzwi",
"Entities.gmod_subway_em508t.Buttons.AVMain.AV8BToggle" : "АV-8B: Wyłącznik automatyczny WN",
"Entities.gmod_subway_em508t.Buttons.VU.VUToggle" : "VU: Wyłącznik sterowania",
"Entities.gmod_subway_em508t.Buttons.VU.!Voltage" : "Napięcie obwodów sterowania",
"Entities.gmod_subway_em508t.Buttons.HelperPanel.VUD2Toggle" : "VUD2: Włącznik sterowania drzwiami",
"Entities.gmod_subway_em508t.Buttons.HelperPanel.VDLSet" : "VDL: Otwieranie lewych drzwi",
"Entities.gmod_subway_em508t.Buttons.DriverValveBLTLDisconnect.DriverValveBLDisconnectToggle" : "Zawór dwudrożny przewodu głównego",
"Entities.gmod_subway_em508t.Buttons.DriverValveBLTLDisconnect.DriverValveTLDisconnectToggle" : "Zawór dwudrożny przewodu zasilającego",
"Entities.gmod_subway_em508t.Buttons.AirDistributor.AirDistributorDisconnectToggle" : "Blokada dystrybutora powietrza"
}
]]
|
local t = Def.ActorFrame{}
t[#t+1] = LoadActor("_background")
t[#t+1] = LoadActor("_particles");
return t |
return {
tag = 'colliders',
summary = 'Add a Collider with a BoxShape to the World.',
description = 'Adds a new Collider to the World with a BoxShape already attached.',
arguments = {
{
name = 'x',
type = 'number',
default = '0',
description = 'The x coordinate of the center of the box.'
},
{
name = 'y',
type = 'number',
default = '0',
description = 'The y coordinate of the center of the box.'
},
{
name = 'z',
type = 'number',
default = '0',
description = 'The z coordinate of the center of the box.'
},
{
name = 'width',
type = 'number',
default = '1',
description = 'The total width of the box, in meters.'
},
{
name = 'height',
type = 'number',
default = 'width',
description = 'The total height of the box, in meters.'
},
{
name = 'depth',
type = 'number',
default = 'width',
description = 'The total depth of the box, in meters.'
}
},
returns = {
{
name = 'collider',
type = 'Collider',
description = 'The new Collider.'
}
},
related = {
'BoxShape',
'Collider',
'World:newCollider',
'World:newCapsuleCollider',
'World:newCylinderCollider',
'World:newMeshCollider',
'World:newSphereCollider'
}
}
|
require("settings")
require("keymaps")
require("plugins")
|
--[[
=== test_hepack
]]
local he = require "he"
local hs = require "he.pack"
local list = he.list
local pp = he.pp
local pack, unpack = hs.pack, hs.unpack
--test equality including the metatable
local function eq(a, b) return he.equal(a, b, true) end
------------------------------------------------------------------------
local s, t, u, v, w
assert(unpack(pack( 0 )) == 0 )
assert(unpack(pack( -1 )) == -1 )
assert(unpack(pack( -2 )) == -2 )
assert(unpack(pack( 239 )) == 239 ) --0xef
assert(unpack(pack( 1000 )) == 1000 )
assert(unpack(pack( 1.02 )) == 1.02 )
assert(unpack(pack( "" )) == "" )
assert(unpack(pack( "aaa" )) == "aaa" )
assert(unpack(pack( ('a'):rep(10000) )) == ('a'):rep(10000) )
assert(unpack(pack( ('a'):rep(1000000) )) == ('a'):rep(1000000) )
assert(eq({}, unpack(pack( {} ))))
assert(eq({{{}}}, unpack(pack( {{{}}} ))))
t = {{a={'aaa'}}, 11, 22}
assert(eq(t, unpack(pack( t ))))
l = he.list{{a={'aaa'}}, 11, 22}
assert(eq(l, unpack(pack( l ))))
-- regular table literals
t = {11, 22, name="abc", {}, {{}}, {x=1, y=1.0}}
s = pack(t)
u = unpack(s)
assert(eq(t, u))
t = {11, y=22, list{33,55}}
s = pack(t)
u = unpack(s)
assert(eq(t, u))
|
while true do
screen:clear()
pad = Controls.read()
if pad:cross() then dofile("script.lua") end
screen:print(220,100,"Game Over", Color.new(255,255,255))
screen:print(210,110,"Press Cross", Color.new(255,255,255))
screen.waitVblankStart()
screen.flip()
end |
local util = require("spec.util")
describe("assignment to multiple variables", function()
it("from a function call", util.check [[
local function foo(): boolean, string
return true, "yeah!"
end
local a, b = foo()
print(b .. " right!")
]])
it("reports unsufficient rvalues as an error, simple", util.check_type_error([[
local a, b = 1, 2
a, b = 3
]], {
{ msg = "variable is not being assigned a value" }
}))
it("reports excess lvalues", util.check_warnings([[
local function foo(_a: integer, _b: string, _c: boolean): string, boolean
return "hi", true
end
local x, y, z, w: string, boolean, integer, boolean
x, y, z, w = foo(1, "hello", true)
]], {
{ y = 6, x = 13, msg = "only 2 values are returned by the function" },
{ y = 6, x = 16, msg = "only 2 values are returned by the function" },
}))
it("reports unsufficient rvalues as an error, tricky", util.check_type_error([[
local type T = record
x: number
y: number
end
function T:returnsTwo(): number, number
return self.x, self.y
end
function T:method()
local a, b: number, number
a, b = self.returnsTwo and self:returnsTwo()
end
]], {
{ msg = "variable is not being assigned a value" }
}))
end)
|
LANGUAGE = {
paper = "Paper"
}
|
object_tangible_quest_outbreak_outbreak_facility_vent = object_tangible_quest_outbreak_shared_outbreak_facility_vent:new {
}
ObjectTemplates:addTemplate(object_tangible_quest_outbreak_outbreak_facility_vent, "object/tangible/quest/outbreak/outbreak_facility_vent.iff")
|
TOOL.Category = "Construction"
TOOL.Name = "#tool.remover.name"
TOOL.Command = nil
TOOL.ConfigName = nil
local function RemoveEntity( ent )
if ( ent:IsValid() ) then
ent:Remove()
end
end
local function DoRemoveEntity( Entity )
if ( !IsValid( Entity ) || Entity:IsPlayer() ) then return false end
-- Nothing for the client to do here
if ( CLIENT ) then return true end
-- Remove all constraints (this stops ropes from hanging around)
constraint.RemoveAll( Entity )
-- Remove it properly in 1 second
timer.Simple( 1, function() RemoveEntity( Entity ) end )
-- Make it non solid
Entity:SetNotSolid( true )
Entity:SetMoveType( MOVETYPE_NONE )
Entity:SetNoDraw( true )
-- Send Effect
local ed = EffectData()
ed:SetEntity( Entity )
util.Effect( "entity_remove", ed, true, true )
return true
end
--[[---------------------------------------------------------
Name: LeftClick
Desc: Remove a single entity
-----------------------------------------------------------]]
function TOOL:LeftClick( trace )
if ( DoRemoveEntity( trace.Entity ) ) then
if ( !CLIENT ) then
self:GetOwner():SendLua( "achievements.Remover()" );
end
return true
end
return false
end
--[[---------------------------------------------------------
Name: RightClick
Desc: Remove this entity and everything constrained
-----------------------------------------------------------]]
function TOOL:RightClick( trace )
local Entity = trace.Entity
if ( !IsValid( Entity ) || Entity:IsPlayer() ) then return false end
-- Client can bail out now.
if ( CLIENT ) then return true end
local ConstrainedEntities = constraint.GetAllConstrainedEntities( trace.Entity )
local Count = 0
-- Loop through all the entities in the system
for _, Entity in pairs( ConstrainedEntities ) do
if ( DoRemoveEntity( Entity ) ) then
Count = Count + 1
end
end
return true
end
--
-- Reload removes all constraints on the targetted entity
--
function TOOL:Reload( trace )
if ( !IsValid( trace.Entity ) || trace.Entity:IsPlayer() ) then return false end
if ( CLIENT ) then return true end
return constraint.RemoveAll( trace.Entity )
end
|
--------------------------------------------------------------------------------
-- WiFi module for 512 KB flash and nodeMCU 0.9.5
--------------------------------------------------------------------------------
local function timeout(timeout_callback)
tmr.stop(1)
wifi.sta.disconnect()
timeout_callback()
end
local function init_wifi(self, ssid, pwd, call_back, timeout_ms, timeout_callback)
tmr.delay(1000000)
if timeout_ms and timeout_callback then
tmr.alarm(2, timeout_ms, 0, function() return timeout(timeout_callback) end)
end
print("Setting up WiFi...")
wifi.sta.disconnect()
wifi.setmode(wifi.STATION)
wifi.sta.config(ssid, pwd)
tmr.alarm(1, 1000, 1, function()
if wifi.sta.getip() then
tmr.stop(2)
tmr.stop(1)
ip, nm, gw = wifi.sta.getip()
info = {IP = ip, netmask = nm, gateway = gw}
if call_back then
call_back(info)
else
print(info.IP .. " " .. info.netmask .. " " .. info.gateway)
end
return
end
end)
end
-- Set module name as parameter of require and return module table
local M = {
init_wifi = init_wifi
}
_G[modname or 'my_wifi'] = M
return M |
describe("constructor '#iterator'", function()
local linq = require("lazylualinq")
it("calls the passed function repeatedly to retrieve items", function()
local progress = 0
local iterator = linq.iterator(function()
progress = progress + 1
return progress % 3, progress
end)
:getIterator()
assert.is_same({ iterator() }, { 1, 1 })
assert.is_same({ iterator() }, { 2, 2 })
assert.is_same({ iterator() }, { 0, 3 })
assert.is_same({ iterator() }, { 1, 4 })
end)
it("yields a numeric key if the function does not provide one", function()
local progress = 0
local iterator = linq.iterator(function()
progress = progress + 1
return progress % 3
end)
:getIterator()
assert.is_same({ iterator() }, { 1, 1 })
assert.is_same({ iterator() }, { 2, 2 })
assert.is_same({ iterator() }, { 0, 3 })
assert.is_same({ iterator() }, { 1, 4 })
end)
it("caches results when multiple iterators are created", function()
local progress = 0
local sequence = linq.iterator(function()
progress = progress + 1
return progress % 3, progress
end)
local iterator1 = sequence:getIterator()
local iterator2 = sequence:getIterator()
assert.is_same({ iterator1() }, { 1, 1 })
assert.is_same({ iterator1() }, { 2, 2 })
assert.is_same({ iterator1() }, { 0, 3 })
assert.is_same({ iterator1() }, { 1, 4 })
assert.is_same(progress, 4)
assert.is_same({ iterator2() }, { 1, 1 })
assert.is_same({ iterator2() }, { 2, 2 })
assert.is_same({ iterator2() }, { 0, 3 })
assert.is_same({ iterator2() }, { 1, 4 })
assert.is_same(progress, 4)
end)
end) |
print('\n\nLoading TrollsAndElves modules...')
--[[function Dynamic_Wrap( mt, name )
if Convars:GetFloat( 'developer' ) == 1 then
local function w(...) return mt[name](...) end
return w
else
return mt[name]
end
end]]--
-- Module loading system (it reports errors)
local totalErrors = 0
local function loadModule(name)
local status, err = pcall(function()
-- Load the module
require(name)
end)
if not status then
-- Add to the total errors
totalErrors = totalErrors+1
-- Tell the user about it
print('WARNING: '..name..' failed to load!')
print(err)
end
end
-- Load Frota
loadModule('lib.json') -- Json Library
loadModule('TrollsAndElves') -- Main program
loadModule('entity_init')
require("moondota/moondota")
if totalErrors == 0 then
-- No loading issues
print('Loaded TrollsAndElves modules successfully!\n')
elseif totalErrors == 1 then
-- One loading error
print('1 TrollsAndElves module failed to load!\n')
else
-- More than one loading error
print(totalErrors..' TrollsAndElves modules failed to load!\n')
end
Convars:RegisterCommand("makeuni", function(cmdname, name, team)
local me = Convars:GetCommandClient():GetAssignedHero()
local unit = CreateUnitByName(name, me:GetOrigin(), true, nil, nil, tonumber(team))
FindClearSpaceForUnit(unit, me:GetOrigin(), true)
end, "Fuck", 0)
Convars:RegisterCommand("creep", function(args)
local h = Convars:GetCommandClient():GetAssignedHero()
CreateUnitByName("npc_dota_creature_creep_melee", h:GetOrigin(), true, nil, nil, 2)
end, "Fuck", 0)
Convars:RegisterCommand("tower", function(args)
local h = Convars:GetCommandClient():GetAssignedHero()
CreateUnitByName("npc_dota_goodguys_tower1_top", h:GetOrigin(), true, nil, nil, 2)
end, "Fuck", 0)
Convars:RegisterCommand("quell", function(args)
local h = Convars:GetCommandClient():GetAssignedHero()
local firework = CreateItem("item_quelling_blade", h, h)
h:AddItem(firework)
end, "Fuck", 0)
Convars:RegisterCommand("nametest2", function(args)
local h = Convars:GetCommandClient():GetAssignedHero()
print(h:GetUnitName())
end, "Fuck", 0)
Convars:RegisterCommand("showitemtest", function(args)
print("FIRING")
FireGameEvent("tae_new_troll", {pid=Convars:GetCommandClient():GetPlayerID()})
end, "Fuck", 0)
Convars:RegisterCommand("showbuildtest", function(args)
print("FIRING")
FireGameEvent("tae_new_elf", {pid=Convars:GetCommandClient():GetPlayerID()})
end, "Fuck", 0)
Convars:RegisterCommand("invo2", function(args)
local h = Convars:GetCommandClient():GetAssignedHero()
local firework = CreateHeroForPlayer( "npc_dota_hero_wisp", Convars:GetCommandClient())
FindClearSpaceForUnit(firework, h:GetOrigin(), false)
end, "Fuck", 0)
Convars:RegisterCommand("invo3", function(args)
local h = Convars:GetCommandClient():GetAssignedHero()
local firework = CreateHeroForPlayer( "npc_dota_hero_invoker", Convars:GetCommandClient())
FindClearSpaceForUnit(firework, h:GetOrigin(), false)
end, "Fuck", 0)
Convars:RegisterCommand("tae_buy_item", function(cmdname, item)
local player = Convars:GetCommandClient()
if player:GetAssignedHero():GetClassname() == "npc_dota_hero_troll_warlord" then
TrollsAndElvesGameMode:TrollBuyItem(player, item)
end
end, "Fuck", 0)
UnitsCustomKV = LoadKeyValues("scripts/npc/npc_units_custom.txt")
ItemsCustomKV = LoadKeyValues("scripts/npc/npc_items_custom.txt") |
local _, ns = ...
local B, C, L, DB, P = unpack(ns)
local S = P:GetModule("Skins")
local _G = getfenv(0)
local select, pairs, type = select, pairs, type
local strfind = string.find
local function reskinChildButton(frame)
if not frame then return end
for i = 1, frame:GetNumChildren() do
local child = select(i, frame:GetChildren())
if child:GetObjectType() == "Button" and child.Text then
B.Reskin(child)
end
end
end
local function RemoveBorder(frame)
for _, region in pairs {frame:GetRegions()} do
if region:GetObjectType() == "Texture" then
local texturePath = region.GetTextureFilePath and region:GetTextureFilePath()
if texturePath and type(texturePath) == "string" and strfind(texturePath, "Quickslot2") then
region:SetTexture("")
end
end
end
end
local function ReskinWAOptions()
local frame = _G.WeakAurasOptions
if not frame or frame.styled then return end
B.StripTextures(frame)
B.SetBD(frame)
B.ReskinInput(frame.filterInput, 18)
B.Reskin(_G.WASettingsButton)
-- Minimize, Close Button
for i = 1, frame:GetNumChildren() do
local child = select(i, frame:GetChildren())
local numRegions = child:GetNumRegions()
local numChildren = child:GetNumChildren()
if numRegions == 3 and numChildren == 1 and child.PixelSnapDisabled then
B.StripTextures(child)
local button = child:GetChildren()
local texturePath = button.GetNormalTexture and button:GetNormalTexture():GetTextureFilePath()
if texturePath and type(texturePath) == "string" and strfind(texturePath, "CollapseButton") then
B.ReskinArrow(button, "up")
button:SetSize(18, 18)
button:ClearAllPoints()
button:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -30, -6)
button.SetNormalTexture = B.Dummy
button.SetPushedTexture = B.Dummy
button:HookScript("OnClick",function(self)
if frame.minimized then
B.SetupArrow(self.__texture, "down")
else
B.SetupArrow(self.__texture, "up")
end
end)
else
B.ReskinClose(button, frame)
button:SetSize(18, 18)
end
end
end
-- Child Groups
local childGroups = {
"texturePicker",
"iconPicker",
"modelPicker",
"importexport",
"texteditor",
"codereview",
}
for _, key in pairs(childGroups) do
local group = frame[key]
if group then
reskinChildButton(group.frame)
end
end
-- IconPicker
local iconPicker = frame.iconPicker.frame
if iconPicker then
for i = 1, iconPicker:GetNumChildren() do
local child = select(i, iconPicker:GetChildren())
if child:GetObjectType() == "EditBox" then
B.ReskinInput(child, 20)
end
end
end
-- Right Side Container
local container = frame.container.content:GetParent()
if container and container.bg then
container.bg:Hide()
end
-- WeakAurasSnippets
local snippets = _G.WeakAurasSnippets
B.StripTextures(snippets)
B.SetBD(snippets)
reskinChildButton(snippets)
-- MoverSizer
local moversizer = frame.moversizer
B.CreateBD(moversizer, 0)
local index = 1
for i = 1, moversizer:GetNumChildren() do
local child = select(i, moversizer:GetChildren())
local numChildren = child:GetNumChildren()
if numChildren == 2 and child:IsClampedToScreen() then
local button1, button2 = child:GetChildren()
if index == 1 then
B.ReskinArrow(button1, "up")
B.ReskinArrow(button2, "down")
else
B.ReskinArrow(button1, "left")
B.ReskinArrow(button2, "right")
end
index = index + 1
end
end
-- TipPopup
for i = 1, frame:GetNumChildren() do
local child = select(i, frame:GetChildren())
if child:GetFrameStrata() == "FULLSCREEN" and child.PixelSnapDisabled and child.backdropInfo then
B.StripTextures(child)
B.SetBD(child)
for j = 1, child:GetNumChildren() do
local child2 = select(j, child:GetChildren())
if child2:GetObjectType() == "EditBox" then
B.ReskinInput(child2, 18)
end
end
break
end
end
frame.styled = true
end
function S:WeakAuras()
local WeakAuras = _G.WeakAuras
if not WeakAuras then return end
-- WeakAurasTooltip
reskinChildButton(_G.WeakAurasTooltipImportButton:GetParent())
B.ReskinRadio(_G.WeakAurasTooltipRadioButtonCopy)
B.ReskinRadio(_G.WeakAurasTooltipRadioButtonUpdate)
local index = 1
local check = _G["WeakAurasTooltipCheckButton"..index]
while check do
B.ReskinCheck(check)
index = index + 1
check = _G["WeakAurasTooltipCheckButton"..index]
end
-- Remove Aura Border (Credit: ElvUI_WindTools)
if WeakAuras.RegisterRegionOptions then
local origRegisterRegionOptions = WeakAuras.RegisterRegionOptions
WeakAuras.RegisterRegionOptions = function(name, createFunction, icon, displayName, createThumbnail, ...)
if type(icon) == "function" then
local OldIcon = icon
icon = function()
local f = OldIcon()
RemoveBorder(f)
return f
end
end
if type(createThumbnail) == "function" then
local OldCreateThumbnail = createThumbnail
createThumbnail = function()
local f = OldCreateThumbnail()
RemoveBorder(f)
return f
end
end
return origRegisterRegionOptions(name, createFunction, icon, displayName, createThumbnail, ...)
end
end
end
function S:WeakAurasOptions()
local WeakAuras = _G.WeakAuras
if not WeakAuras or not WeakAuras.ShowOptions then return end
hooksecurefunc(WeakAuras, "ShowOptions", ReskinWAOptions)
end
function S:WeakAurasTemplates()
local WeakAuras = _G.WeakAuras
if not WeakAuras or not WeakAuras.CreateTemplateView then return end
local origCreateTemplateView = WeakAuras.CreateTemplateView
WeakAuras.CreateTemplateView = function(...)
local group = origCreateTemplateView(...)
reskinChildButton(group.frame)
return group
end
end
S:RegisterSkin("WeakAuras", S.WeakAuras)
S:RegisterSkin("WeakAurasOptions", S.WeakAurasOptions)
S:RegisterSkin("WeakAurasTemplates", S.WeakAurasTemplates) |
RegisterServerEvent("InitInventaire:tradePlayerItem")
AddEventHandler("InitInventaire:tradePlayerItem", function(from, target, type, itemName, itemCount)
print("ezzz")
--[[local _source = from
local sourceXPlayer = ESX.GetPlayerFromId(_source)
local targetXPlayer = ESX.GetPlayerFromId(target)
if type == "item_standard" then
local sourceItem = sourceXPlayer.getInventoryItem(itemName)
local targetItem = targetXPlayer.getInventoryItem(itemName)
if itemCount > 0 and sourceItem.count >= itemCount then
if targetItem.limit ~= -1 and (targetItem.count + itemCount) > targetItem.limit then
else
sourceXPlayer.removeInventoryItem(itemName, itemCount)
TriggerClientEvent('b1g_notify:client:Notify', sourceXPlayer, { type = 'true', text = _U('item_removed') .. itemName})
targetXPlayer.addInventoryItem(itemName, itemCount)
TriggerClientEvent('b1g_notify:client:Notify', targetXPlayer, { type = 'true', text = _U('item_added') .. itemName})
end
end
elseif type == "item_money" then
if itemCount > 0 and sourceXPlayer.getMoney() >= itemCount then
sourceXPlayer.removeMoney(itemCount)
TriggerClientEvent('b1g_notify:client:Notify', sourceXPlayer, { type = 'true', text = _U('money_removed') .. itemCount})
targetXPlayer.addMoney(itemCount)
TriggerClientEvent('b1g_notify:client:Notify', targetXPlayer, { type = 'true', text = _U('money_added') .. itemCount})
end
elseif type == "item_account" then
if itemCount > 0 and sourceXPlayer.getAccount(itemName).money >= itemCount then
sourceXPlayer.removeAccountMoney(itemName, itemCount)
TriggerClientEvent('b1g_notify:client:Notify', sourceXPlayer, { type = 'true', text = _U('money_removed') .. itemCount .. itemName})
targetXPlayer.addAccountMoney(itemName, itemCount)
TriggerClientEvent('b1g_notify:client:Notify', targetXPlayer, { type = 'true', text = _U('money_added') .. itemCount .. itemName})
end
elseif type == "item_weapon" then
if not targetXPlayer.hasWeapon(itemName) then
sourceXPlayer.removeWeapon(itemName)
TriggerClientEvent('b1g_notify:client:Notify', sourceXPlayer, { type = 'true', text = _U('weapon_removed') .. itemName})
targetXPlayer.addWeapon(itemName, itemCount)
TriggerClientEvent('b1g_notify:client:Notify', targetXPlayer, { type = 'true', text = _U('waepon_added') .. itemName})
end
end]]
end)
RegisterServerEvent('InitialCore:InvSyncAmmo')
AddEventHandler('InitialCore:InvSyncAmmo', function(meta, ammo)
local SteamID = GetPlayerIdentifier(source)
MySQL.Async.fetchAll("SELECT Armes FROM playerinfo WHERE SteamID='" .. SteamID .. "'", {}, function(resultgetinv)
if resultgetinv[1] ~= nil then
if resultgetinv[1].Armes ~= nil then
local PlayerInv = json.decode(resultgetinv[1].Armes)
--[[for k, v in pairs(PlayerInv) do
for x, y in pairs(v) do
print(y.ID)
--if meta == y.Data.HashID then
-- y.Data.Munition = ammo
--end
end
end]]
for k in pairs (PlayerInv) do
--print( PlayerInv[k] )
--print(ArmesNom[PlayerArmes[k].ID])
if meta == PlayerInv[k].Data.HashID then
PlayerInv[k].Data.Munition = ammo
end
end
--print("vv" .. json.encode(PlayerInv))
MySQL.Async.execute("UPDATE playerinfo SET Armes='" .. json.encode(PlayerInv) .. "' WHERE SteamID='" .. SteamID .. "'", {}, function()
--TriggerClientEvent('InitialCore:AdvancedNotif', donateur, 'Initial V', '~r~Inventaire', 'Vous avez donné ' .. montant .. ' ' .. item .. '.', 'CHAR_WE', 'INITIALV')
end)
end
end
end)
end)
RegisterServerEvent('InitialCore:GetCoffreVehicle')
AddEventHandler('InitialCore:GetCoffreVehicle', function(Plaque, vehType)
src = source
MySQL.Async.fetchAll("SELECT * FROM coffres WHERE Plaque='" .. Plaque .. "'", {}, function(result)
if result[1] ~= nil then
TriggerClientEvent('InitialCore:OpenCoffreVehicule', src, json.decode(result[1].Contenu), Plaque, vehType)
else
MySQL.Async.execute("INSERT INTO coffres (Plaque, Contenu, VehiculeJoueur) VALUES ('" .. Plaque .. "', '{}', '1');", {}, function()
end)
TriggerClientEvent('InitialCore:OpenCoffreVehicule', src, json.decode('{}'), Plaque, vehType)
end
end)
end)
RegisterServerEvent('InitialCore:RefreshCoffreVehicle')
AddEventHandler('InitialCore:RefreshCoffreVehicle', function(Plaque, vehType)
_src = source
MySQL.Async.fetchAll("SELECT * FROM coffres WHERE Plaque='" .. Plaque .. "'", {}, function(result)
if result[1] ~= nil then
TriggerClientEvent('InitialCore:refreshTrunkInventory', _src, json.decode(result[1].Contenu), Plaque, vehType)
else
MySQL.Async.execute("INSERT INTO coffres (Plaque, Contenu, VehiculeJoueur) VALUES ('" .. Plaque .. "', '{}', '1');", {}, function()
end)
TriggerClientEvent('InitialCore:refreshTrunkInventory', _src, json.decode('{}'), Plaque, vehType)
end
end)
end)
RegisterServerEvent('InitialCore:PutItemCoffreVehicle')
AddEventHandler('InitialCore:PutItemCoffreVehicle', function(Plaque, ID, Nombre, OtherData, Metadata2)
local CoffreAAdd = {}
if ID:sub(1, 7) ~= 'WEAPON_' then
CoffreAAdd[ID] = {}
CoffreAAdd[ID].Montant = Nombre
if Metadata2 then
CoffreAAdd[ID].Data = Metadata2
end
end
if ID == 'argent' then
TriggerEvent('InitialCore:RemoveMoney', source, Nombre)
elseif ID:sub(1, 7) == 'WEAPON_' then
TriggerEvent('InitialCore:DeleteWeapon', source, ID, Nombre, Metadata2.HashID)
else
TriggerEvent('InitialCore:DeleteItem', source, ID, Nombre)
end
MySQL.Async.fetchAll("SELECT Contenu FROM coffres WHERE Plaque='" .. Plaque .. "'", {}, function(result)
if result[1] then
local InvVehiculeActuel = json.decode(result[1].Contenu)
if ID:sub(1, 7) == 'WEAPON_' then
--[[table.insert(InvVehiculeActuel, 1, {
ID = ID,
Data = {Munition = Metadata2.Munition, HashID = Metadata2.HashID}
})]]
-- print(json.encode(InvVehiculeActuel))
-- table.insert(InvVehiculeActuel, ID)
InvVehiculeActuel[math.random(1, 9999999)] = {Nom = ID, Data = Metadata2}
--print(json.encode(InvVehiculeActuel))
else
if InvVehiculeActuel[ID] == nil then
InvVehiculeActuel[ID] = {}
end
if InvVehiculeActuel[ID].Montant ~= nil then
InvVehiculeActuel[ID].Montant = InvVehiculeActuel[ID].Montant + Nombre
else
InvVehiculeActuel[ID] = {}
InvVehiculeActuel[ID].Montant = Nombre
end
if Metadata2 then
InvVehiculeActuel[ID].Data = Metadata2
end
end
MySQL.Async.execute("UPDATE coffres SET Contenu='" .. json.encode(InvVehiculeActuel) .. "' WHERE Plaque='" .. Plaque .. "'", {}, function()
end)
else
if ID:sub(1, 7) == 'WEAPON_' then
--[[table.insert(CoffreAAdd, 1, 'test' = {
ID = ID,
Data = {Munition = Metadata2.Munition, HashID = Metadata2.HashID}
})]]
--table.insert(CoffreAAdd, 1, ID)
CoffreAAdd[math.random(1, 9999999)] = {Nom = ID, Data = Metadata2}
--print(CoffreAAdd[1])
end
MySQL.Async.execute("INSERT INTO coffres (Plaque, Contenu, VehiculeJoueur) VALUES ('" .. Plaque .. "', '" .. json.encode(CoffreAAdd) .. "', '1')" , {}, function()
end)
end
end)
end)
RegisterServerEvent('InitialCore:RemoveItemCoffreVehicle')
AddEventHandler('InitialCore:RemoveItemCoffreVehicle', function(Plaque, ID, Nombre, Metadata2, IDHash, TableID)
local CoffreARem = {}
if not IDHash then
IDHash = 'lul'
end
if IDHash:sub(1, 7) ~= 'WEAPON_' then
CoffreARem[ID] = {}
CoffreARem[ID].Montant = Nombre
if Metadata2 then
CoffreARem[ID].Data = Metadata2
end
if ID == 'argent' then
TriggerEvent('InitialCore:GiveMoney', source, Nombre)
else
TriggerEvent('InitialCore:GiveItem', source, ID, Nombre, Metadata2)
end
end
print('#############')
print(Plaque)
print(ID)
print(Nombre)
print(Metadata2)
print(IDHash)
print(TableID)
print('#############')
MySQL.Async.fetchAll("SELECT Contenu FROM coffres WHERE Plaque='" .. Plaque .. "'", {}, function(result)
if result[1].Contenu ~= '{}' then
local InvVehiculeActuel = json.decode(result[1].Contenu)
print(IDHash:sub(1, 7))
if IDHash:sub(1, 7) == 'WEAPON_' then
print('wearemove')
for k, v in pairs(InvVehiculeActuel) do
print(TableID)
print(k)
if k == TableID then
print('success')
InvVehiculeActuel[TableID] = nil
--print(json.encode(InvVehiculeActuel))
end
end
else
print("ccrem")
if InvVehiculeActuel[ID] == nil then
InvVehiculeActuel[ID] = {}
end
if InvVehiculeActuel[ID].Montant ~= nil then
InvVehiculeActuel[ID].Montant = InvVehiculeActuel[ID].Montant - Nombre
else
InvVehiculeActuel[ID] = {}
InvVehiculeActuel[ID].Montant = Nombre
end
if Metadata2 then
InvVehiculeActuel[ID].Data = Metadata2
end
end
MySQL.Async.execute("UPDATE coffres SET Contenu='" .. json.encode(InvVehiculeActuel) .. "' WHERE Plaque='" .. Plaque .. "'", {}, function()
end)
else
-- MySQL.Async.execute("UPDATE coffres SET Contenu='" .. json.encode(CoffreARem) .. "' WHERE Plaque='" .. Plaque .. "'" , {}, function()
-- end)
end
end)
end)
RegisterServerCallback('getCoffrePropriete', function(source, callback, id)
MySQL.Async.fetchAll("SELECT Contenu FROM coffreproperties WHERE Nom='" .. id .. "'", {}, function(result)
callback(json.decode(result[1].Contenu))
end)
end)
RegisterServerEvent('InitialCore:PutItemPropriete')
AddEventHandler('InitialCore:PutItemPropriete', function(IDP, ID, Nombre, OtherData, Metadata2)
local CoffreAAdd = {}
CoffreAAdd[ID] = {}
CoffreAAdd[ID].Montant = Nombre
if Metadata2 then
CoffreAAdd[ID].Data = Metadata2
end
if ID == 'argent' then
TriggerEvent('InitialCore:RemoveMoney', source, Nombre)
elseif ID:sub(1, 7) == 'WEAPON_' then
TriggerEvent('InitialCore:DeleteWeapon', source, ID, Nombre)
else
TriggerEvent('InitialCore:DeleteItem', source, ID, Nombre)
end
MySQL.Async.fetchAll("SELECT Contenu FROM coffreproperties WHERE Nom='" .. IDP .. "'", {}, function(result)
if result[1].Contenu ~= '{}' then
local InvVehiculeActuel = json.decode(result[1].Contenu)
if InvVehiculeActuel[ID] == nil then
InvVehiculeActuel[ID] = {}
end
if InvVehiculeActuel[ID].Montant ~= nil then
InvVehiculeActuel[ID].Montant = InvVehiculeActuel[ID].Montant + Nombre
else
InvVehiculeActuel[ID] = {}
InvVehiculeActuel[ID].Montant = Nombre
end
if Metadata2 then
InvVehiculeActuel[ID].Data = Metadata2
end
MySQL.Async.execute("UPDATE coffreproperties SET Contenu='" .. json.encode(InvVehiculeActuel) .. "' WHERE Nom='" .. IDP .. "'", {}, function()
end)
else
MySQL.Async.execute("UPDATE coffreproperties SET Contenu='" .. json.encode(CoffreAAdd) .. "' WHERE Nom='" .. IDP .. "'" , {}, function()
end)
end
end)
end)
RegisterServerEvent('InitialCore:RemoveItemPropriete')
AddEventHandler('InitialCore:RemoveItemPropriete', function(IDP, ID, Nombre, OtherData, Metadata2)
local CoffreARem = {}
CoffreARem[ID] = {}
CoffreARem[ID].Montant = Nombre
if Metadata2 then
CoffreARem[ID].Data = Metadata2
end
if ID == 'argent' then
TriggerEvent('InitialCore:GiveMoney', source, Nombre)
elseif ID:sub(1, 7) == 'WEAPON_' then
TriggerEvent('InitialCore:GiveWeapon', source, ID, Nombre)
else
TriggerEvent('InitialCore:GiveItem', source, ID, Nombre, Metadata2)
end
MySQL.Async.fetchAll("SELECT Contenu FROM coffreproperties WHERE Nom='" .. IDP .. "'", {}, function(result)
if result[1].Contenu ~= '{}' then
local InvVehiculeActuel = json.decode(result[1].Contenu)
if InvVehiculeActuel[ID] == nil then
InvVehiculeActuel[ID] = {}
end
if InvVehiculeActuel[ID].Montant ~= nil then
InvVehiculeActuel[ID].Montant = InvVehiculeActuel[ID].Montant - Nombre
else
InvVehiculeActuel[ID] = {}
InvVehiculeActuel[ID].Montant = Nombre
end
if Metadata2 then
InvVehiculeActuel[ID].Data = Metadata2
end
MySQL.Async.execute("UPDATE coffreproperties SET Contenu='" .. json.encode(InvVehiculeActuel) .. "' WHERE Nom='" .. IDP .. "'", {}, function()
end)
else
MySQL.Async.execute("UPDATE coffreproperties SET Contenu='" .. json.encode(CoffreARem) .. "' WHERE Nom='" .. IDP .. "'" , {}, function()
end)
end
end)
end)
-- FOUILLE
IC = {}
IC.Items = {}
MySQL.ready(function()
MySQL.Async.fetchAll("SELECT * FROM itemslist", {}, function(result)
for k,v in ipairs(result) do
IC.Items[v.HashID] = {
Nom = v.Nom,
Poids = v.Poids
}
--print(IC.Items["IDCard#639126586"].Nom)
end
--print(IC.Items["clevoiture"].Nom)
end)
end)
RegisterServerCallback('InitInventaire:getPlayerOtherInventory', function(source, callback, targetid)
local PlayerSteamID = GetPlayerIdentifier(targetid)
MySQL.Async.fetchAll("SELECT Inventaire, Armes, Argent FROM playerinfo WHERE SteamID='" .. PlayerSteamID .. "'", {}, function(resultgetinv)
PlayerArgentFinal = resultgetinv[1].Argent
if resultgetinv[1] ~= nil then
local PlayerInvFinal = {}
local PlayerArmesFinal = {}
if resultgetinv[1].Inventaire ~= nil then
--print('## ' .. resultgetinv[1].Inventaire)
PlayerInv = json.decode(resultgetinv[1].Inventaire)
for k in pairs (PlayerInv) do
--print( PlayerInv[k] )
if k:sub(1, 7) == 'CarteCr' then
table.insert(PlayerInvFinal, {
ID = k,
Nom = "Carte de crédit",
Poids = 0.050,
Nombre = PlayerInv[k].Montant,
Data = PlayerInv[k].Data
})
elseif k:sub(1, 7) == 'Vetemen' then
table.insert(PlayerInvFinal, {
ID = k,
Nom = "Vêtement",
Poids = 0.050,
Nombre = PlayerInv[k].Montant,
Data = PlayerInv[k].Data
})
elseif k:sub(1, 7) == 'CleVoit' then
table.insert(PlayerInvFinal, {
ID = k,
Nom = IC.Items["CleVoiture"].Nom,
Poids = IC.Items["CleVoiture"].Poids,
Nombre = PlayerInv[k].Montant,
Data = PlayerInv[k].Data
})
elseif k:sub(1, 7) == 'facture' then
table.insert(PlayerInvFinal, {
ID = k,
Nom = "Facture",
Poids = 0.001,
Nombre = PlayerInv[k].Montant,
Data = PlayerInv[k].Data
})
elseif k:sub(1, 7) == 'patedec' then
table.insert(PlayerInvFinal, {
ID = k,
Nom = "Pâte de coca (100 g)",
Poids = 0.100,
Nombre = PlayerInv[k].Montant,
Data = PlayerInv[k].Data
})
else
table.insert(PlayerInvFinal, {
--print(k),
ID = k,
Nom = IC.Items[k].Nom,
Poids = IC.Items[k].Poids,
Nombre = PlayerInv[k].Montant,
Data = PlayerInv[k].Data
})
end
end
--for k in pairs (PlayerInvFinal[1]) do
-- print( k )
--end
--print("cc ! " .. PlayerInvFinal[1].ID)
--print("cc ! " .. PlayerInvFinal[1].Nom)
--print("cc ! " .. PlayerInvFinal[1].Nombre)
--print("cc ! " .. PlayerInvFinal[1].Poids)
--print("cc ! " .. PlayerInvFinal[2].ID)
--print("cc ! " .. PlayerInvFinal[2].Nom)
--print("cc ! " .. PlayerInvFinal[2].Nombre)
--print("cc ! " .. PlayerInvFinal[2].Poids)
end
if resultgetinv[1].Armes ~= nil then
PlayerArmes = json.decode(resultgetinv[1].Armes)
--print('## ' .. PlayerInv)
for k in pairs (PlayerArmes) do
--print( PlayerInv[k] )
table.insert(PlayerArmesFinal, {
ID = k,
Nom = ArmesNom[k],
--Poids = IC.Items[k].Poids,
Nombre = PlayerArmes[k].Montant
})
end
--for k in pairs (PlayerInvFinal[1]) do
-- print( k )
--end
--print("cc ! " .. PlayerInvFinal[1].ID)
--print("cc ! " .. PlayerInvFinal[1].Nom)
--print("cc ! " .. PlayerInvFinal[1].Nombre)
--print("cc ! " .. PlayerInvFinal[1].Poids)
--print("cc ! " .. PlayerInvFinal[2].ID)
--print("cc ! " .. PlayerInvFinal[2].Nom)
--print("cc ! " .. PlayerInvFinal[2].Nombre)
--print("cc ! " .. PlayerInvFinal[2].Poids)
end
callback(PlayerInvFinal, PlayerArmesFinal, PlayerArgentFinal)
end
end)
end)
local ArmesNom = {}
ArmesNom.WEAPON_KNIFE = 'Couteau'
ArmesNom.WEAPON_SWITCHBLADE = 'Couteau a cran d\'arret'
ArmesNom.WEAPON_FLASHLIGHT = 'Lampe torche'
ArmesNom.WEAPON_BAT = 'Batte'
ArmesNom.WEAPON_MACHETE = 'Machette'
ArmesNom.WEAPON_SNSPISTOL = 'Pétoire'
ArmesNom.WEAPON_PISTOL = 'Pistolet'
ArmesNom.WEAPON_COMBATPISTOL = 'Pistolet de combat'
RegisterServerCallback('InitInventaire:getOtherInventory', function(source, callback, plate)
--local PlayerSteamID = GetPlayerIdentifier(targetid)
MySQL.Async.fetchAll("SELECT Contenu FROM coffres WHERE Plaque='" .. plate .. "'", {}, function(resultgetinv)
if not resultgetinv[1] then
resultgetinv[1] = {}
resultgetinv[1].Contenu = {}
resultgetinv[1].Contenu = json.encode(resultgetinv[1].Contenu)
end
--PlayerArgentFinal = resultgetinv[1].Argent
if resultgetinv[1] ~= nil then
local PlayerInvFinal = {}
local PlayerArmesFinal = {}
if resultgetinv[1].Contenu ~= nil then
--print('## ' .. resultgetinv[1].Inventaire)
PlayerInv = json.decode(resultgetinv[1].Contenu)
for k, v in pairs (PlayerInv) do
--print( PlayerInv[k].Montant )
--print(v.Nom)
print(v.Nom)
if v.Nom then
if v.Nom:sub(1, 7) == 'WEAPON_' then
table.insert(PlayerInvFinal, {
ID = v.Nom,
Nom = ArmesNom[v.Nom],
Poids = 1500,
Nombre = 1,
Data = v.Data,
IDTable = k
})
end
else
if k:sub(1, 7) == 'CarteCr' then
table.insert(PlayerInvFinal, {
ID = k,
Nom = "Carte de crédit",
Poids = 0.050,
Nombre = PlayerInv[k].Montant,
Data = PlayerInv[k].Data
})
elseif k:sub(1, 7) == 'Vetemen' then
table.insert(PlayerInvFinal, {
ID = k,
Nom = "Vêtement",
Poids = 0.050,
Nombre = PlayerInv[k].Montant,
Data = PlayerInv[k].Data
})
elseif k:sub(1, 7) == 'CleVoit' then
table.insert(PlayerInvFinal, {
ID = k,
Nom = IC.Items["CleVoiture"].Nom,
Poids = IC.Items["CleVoiture"].Poids,
Nombre = PlayerInv[k].Montant,
Data = PlayerInv[k].Data
})
elseif k:sub(1, 7) == 'facture' then
table.insert(PlayerInvFinal, {
ID = k,
Nom = "Facture",
Poids = 0.001,
Nombre = PlayerInv[k].Montant,
Data = PlayerInv[k].Data
})
elseif k:sub(1, 7) == 'patedec' then
table.insert(PlayerInvFinal, {
ID = k,
Nom = "Pâte de coca (100 g)",
Poids = 0.100,
Nombre = PlayerInv[k].Montant,
Data = PlayerInv[k].Data
})
elseif k:sub(1, 6) == 'argent' then
table.insert(PlayerInvFinal, {
ID = "argent",
Nom = "Argent",
Poids = 1*PlayerInv[k].Montant,
Nombre = PlayerInv[k].Montant
})
elseif k:sub(1, 7) == 'Telepho' then
table.insert(PlayerInvFinal, {
ID = k,
Nom = "Téléphone",
Poids = 0.600,
Nombre = PlayerInv[k].Montant,
Data = PlayerInv[k].Data
})
else
table.insert(PlayerInvFinal, {
--print(k),
ID = k,
Nom = IC.Items[k].Nom,
Poids = IC.Items[k].Poids,
Nombre = PlayerInv[k].Montant,
Data = PlayerInv[k].Data
})
end
end
end
--for k in pairs (PlayerInvFinal[1]) do
-- print( k )
--end
--print("cc ! " .. PlayerInvFinal[1].ID)
--print("cc ! " .. PlayerInvFinal[1].Nom)
--print("cc ! " .. PlayerInvFinal[1].Nombre)
--print("cc ! " .. PlayerInvFinal[1].Poids)
--print("cc ! " .. PlayerInvFinal[2].ID)
--print("cc ! " .. PlayerInvFinal[2].Nom)
--print("cc ! " .. PlayerInvFinal[2].Nombre)
--print("cc ! " .. PlayerInvFinal[2].Poids)
end
--[[ if resultgetinv[1].Armes ~= nil then
PlayerArmes = json.decode(resultgetinv[1].Armes)
--print('## ' .. PlayerInv)
for k in pairs (PlayerArmes) do
--print( PlayerInv[k] )
table.insert(PlayerArmesFinal, {
ID = k,
Nom = ArmesNom[k],
--Poids = IC.Items[k].Poids,
Nombre = PlayerArmes[k].Montant
})
end
--for k in pairs (PlayerInvFinal[1]) do
-- print( k )
--end
--print("cc ! " .. PlayerInvFinal[1].ID)
--print("cc ! " .. PlayerInvFinal[1].Nom)
--print("cc ! " .. PlayerInvFinal[1].Nombre)
--print("cc ! " .. PlayerInvFinal[1].Poids)
--print("cc ! " .. PlayerInvFinal[2].ID)
--print("cc ! " .. PlayerInvFinal[2].Nom)
--print("cc ! " .. PlayerInvFinal[2].Nombre)
--print("cc ! " .. PlayerInvFinal[2].Poids)
end]]
callback(PlayerInvFinal, PlayerArmesFinal, PlayerArgentFinal)
end
end)
end)
RegisterServerEvent('InitialCore:SearchAlert')
AddEventHandler('InitialCore:SearchAlert', function(player)
TriggerClientEvent('InitialCore:SearchAlertC', player)
end) |
local e = {}
e.PermissionLevel = {
Custom = -1;
Visitor = 100;
Support = 125;
Observer = 150;
TrialMod = 175;
Aux = 200;
JrMod = 225;
SrMod = 300;
Admin = 400;
}
e.Arguments = {
UsernameInGame = 0;
DisplayNameInGame = 1;
Username = 2;
UserId = 3;
Number = 4;
Text = 5;
Boolean = 6;
Any = 7;
}
e.Necessity = {
Required = 0;
Optional = 1;
}
e.FailureType = {
InvalidArgs = "One or more arguments provided were not of the correct type!";
MissingArgs = "You were missing one or more required arguments!";
InvalidPerms = "You don't have permission to run this command!";
}
e.ArgStrings = {
[e.Arguments.UsernameInGame] = "Player";
[e.Arguments.DisplayNameInGame] = "Player";
[e.Arguments.Username] = "Username";
[e.Arguments.UserId] = "User Id";
[e.Arguments.Number] = "Number";
[e.Arguments.Text] = "Text";
[e.Arguments.Boolean] = "True/False";
[e.Arguments.Any] = "Any";
}
return e |
local Native = require('lib.stdlib.native')
local converter = require('lib.stdlib.enum.converter')
---@class AttackType
local AttackType = {
Normal = 0, --ATTACK_TYPE_NORMAL
Melee = 1, --ATTACK_TYPE_MELEE
Pierce = 2, --ATTACK_TYPE_PIERCE
Siege = 3, --ATTACK_TYPE_SIEGE
Magic = 4, --ATTACK_TYPE_MAGIC
Chaos = 5, --ATTACK_TYPE_CHAOS
Hero = 6, --ATTACK_TYPE_HERO
}
AttackType = converter(Native.ConvertAttackType, AttackType)
return AttackType
|
local state_machine = {}
local sm = state_machine
local EventQueue = {data = {}}
sm.EventQueue = EventQueue
function EventQueue.add(event)
EventQueue.data[#EventQueue.data + 1] = event
end
function EventQueue.pop()
return table.remove(EventQueue.data, 1)
end
function EventQueue.is_empty()
return #EventQueue.data == 0
end
function EventQueue.pump(stateful_objects)
local event = EventQueue.pop()
while event do
for _, stateful_object in ipairs(stateful_objects) do
sm.process(stateful_object, event)
end
event = EventQueue.pop()
end
end
local Event = {}
sm.Event = Event
function Event.new(kind, payload)
local event = {}
setmetatable(event, {__index = sm.Event})
event.kind = kind
event.payload = payload
return event
end
local Emitter = {}
sm.Emitter = Emitter
function Emitter.new(kind)
local emitter = {}
setmetatable(emitter, {__index = sm.Emitter})
emitter.kind = kind
return emitter
end
function Emitter:emit(payload)
local event = Event.new(self.kind, payload)
EventQueue.add(event)
end
local Edge = {}
sm.Edge = Edge
function Edge.new(trigger, guard, effect, to)
local edge = {}
setmetatable(edge, {__index = sm.Edge})
edge.trigger = trigger
edge.guard = guard
edge.effect = effect
edge.to = to
return edge
end
function Edge:matches(event)
if self.trigger and event then
return self.trigger == event.kind
end
return true
end
function Edge:passes_guard(stateful_object, event)
if self.guard then
return self.guard(stateful_object, event)
end
return true
end
function Edge:execute(stateful_object, payload, event)
if self.effect then
self.effect(stateful_object, payload, event)
end
return self.to
end
local initial = 'initial'
local final = 'final'
local regular = 'regular'
local choice = 'choice'
local State = {}
sm.State = State
function State.new(name, transitions)
local state = {}
setmetatable(state, {__index = sm.State})
state.kind = regular
state.name = name
state.transitions = transitions
return state
end
function State.new_choice(name, transitions)
local state = {}
setmetatable(state, {__index = sm.State})
state.kind = choice
state.name = name
state.transitions = transitions
return state
end
function State.new_initial(transition)
local state = {}
setmetatable(state, {__index = sm.State})
state.kind = initial
state.name = initial
state.transitions = {transition}
return state
end
function State.new_final()
local state = {}
setmetatable(state, {__index = sm.State})
state.kind = final
state.name = final
state.transitions = {}
return state
end
local StateMachine = {}
sm.StateMachine = StateMachine
function StateMachine.new(states)
local machine = {}
setmetatable(machine, {__index = sm.StateMachine})
-- TODO: add validation
local state_lookup = {}
for _, state in ipairs(states) do
state_lookup[state.name] = state
end
state_lookup.final = State.new_final()
machine.states = state_lookup
return machine
end
local function lazy_any(fs)
return function(...)
if #fs == 0 then
return false
end
for _, f in ipairs(fs) do
if not f(...) then
return false
end
end
return true
end
end
local function lazy_each(fs)
return function(...)
for _, f in ipairs(fs) do
f(...)
end
end
end
function StateMachine.new_from_table(raw_states)
-- {effect, to}
-- {'name', {trigger, guard, effect, to}, [kind = blah]}
assert(1 <= #raw_states, "No states provided in table")
local initial_transition = raw_states[1]
states = {State.new_initial(sm.Edge.new(nil, nil, initial_transition[1], initial_transition[2]))}
if #raw_states == 1 then
return StateMachine.new(states)
end
local kinds = {regular = State.new, choice = State.new_choice}
for i = 2, #raw_states do
local raw_state = raw_states[i]
local name = raw_state[1]
local kind = regular
if raw_state.kind then
kind = raw_state.kind
end
kind = kinds[kind]
edges = {}
for _, raw_transition in ipairs(raw_state[2]) do
local trigger = raw_transition[1]
local guard = raw_transition[2]
if type(guard) == 'table' then
guard = lazy_any(guard)
end
local effect = raw_transition[3]
if type(effect) == 'table' then
effect = lazy_each(effect)
end
local to = raw_transition[4] or name
edges[#edges + 1] = Edge.new(trigger, guard, effect, to)
end
local state = kind(name, edges)
states[#states + 1] = state
end
return StateMachine.new(states)
end
function StateMachine:initialize_state(stateful_object)
stateful_object.state = {
name = initial,
machine = self,
}
self:process_event(stateful_object, sm.Event.new(nil, nil))
end
function StateMachine:process_event(stateful_object, event)
local current_state_name = stateful_object.state.name
assert(self.states[current_state_name], "Current object state not a state in state machine")
local transition_was_taken = false
repeat
transition_was_taken = false
local state = self.states[current_state_name]
for i, transition in ipairs(state.transitions) do
if transition:matches(event) and
transition:passes_guard(stateful_object, event.payload) then
current_state_name = transition:execute(stateful_object, event.payload, event)
assert(self.states[current_state_name], "State transitioned to does not exist in the state table: " .. current_state_name)
transition_was_taken = true
break
end
end
until self.states[current_state_name].kind == regular or self.states[current_state_name].kind == final or not transition_was_taken
stateful_object.state.name = current_state_name
end
function state_machine.process(stateful_object, event)
stateful_object.state.machine:process_event(stateful_object, event)
end
return state_machine
|
local fs = require "nvim-lsp-installer.fs"
local path = require "nvim-lsp-installer.path"
local installers = require "nvim-lsp-installer.installers"
local platform = require "nvim-lsp-installer.platform"
local npm = require "nvim-lsp-installer.installers.npm"
local process = require "nvim-lsp-installer.process"
local M = {}
local INSTALL_DIR = path.concat { vim.fn.stdpath "data", "lsp_servers", ".zx" }
local ZX_EXECUTABLE = npm.executable(INSTALL_DIR, "zx")
local has_installed_zx = false
local function zx_installer(force)
force = force or false -- be careful with boolean logic if flipping this
return function(_, callback, context)
if has_installed_zx and not force then
callback(true, "zx already installed")
return
end
if vim.fn.executable "npm" ~= 1 or vim.fn.executable "node" ~= 1 then
callback(false, "Cannot install zx because npm and/or node not installed.")
return
end
local is_zx_already_installed = fs.file_exists(ZX_EXECUTABLE)
local npm_command = is_zx_already_installed and "update" or "install"
if not is_zx_already_installed then
context.stdio_sink.stdout(("Preparing for installation… (npm %s zx)\n"):format(npm_command))
end
fs.mkdirp(INSTALL_DIR)
local handle, pid = process.spawn(platform.is_win and "npm.cmd" or "npm", {
args = { npm_command, "zx@1" },
cwd = INSTALL_DIR,
stdio_sink = context.stdio_sink,
}, function(success)
if success then
has_installed_zx = true
callback(true)
else
context.stdio_sink.stderr "Failed to install zx.\n"
callback(false)
end
end)
if handle == nil then
context.stdio_sink.stderr(("Failed to install/update zx. %s\n"):format(pid))
callback(false)
end
end
end
local function exec(file)
return function(server, callback, context)
process.spawn(ZX_EXECUTABLE, {
args = { file },
cwd = server.root_dir,
stdio_sink = context.stdio_sink,
}, callback)
end
end
-- @deprecated Compose your installer using the Lua `std` installers instead.
function M.file(relpath)
local script_path = path.realpath(relpath, 3)
return installers.pipe {
zx_installer(false),
exec(("file:///%s"):format(script_path)),
}
end
return M
|
function event_death_complete(e)
e.self:Say("All Iksar residents.. shall learn.. of my demise. Ungghh!!");
eq.signal(87101,1); -- NPC: Atheling_Plague
end
-------------------------------------------------------------------------------------------------
-- Converted to .lua using MATLAB converter written by Stryd
-- Find/replace data for .pl --> .lua conversions provided by Speedz, Stryd, Sorvani and Robregen
-------------------------------------------------------------------------------------------------
|
require('networks/modules/Concatenation')
require('networks/modules/SpatialConvolution1_fw')
local network = {}
local function deepCopy(tbl)
-- creates a copy of a network with new modules and the same tensors
local copy = {}
for k, v in pairs(tbl) do
if type(v) == 'table' then
copy[k] = deepCopy(v)
else
copy[k] = v
end
end
if torch.typename(tbl) then
torch.setmetatable(copy, torch.typename(tbl))
end
return copy
end
function network.clean(model)
return deepCopy(model):float():clearState()
end
local function convInit(model, name)
for k,v in pairs(model:findModules(name)) do
local n = v.kW*v.kH*v.nOutputPlane
v.weight:normal(0,math.sqrt(2/n))
if cudnn.version >= 4000 then
v.bias = nil
v.gradBias = nil
else
v.bias:zero()
end
end
end
local function bNInit(model, name)
for k,v in pairs(model:findModules(name)) do
v.weight:fill(1)
v.bias:zero()
end
end
local function linearInit(model, name)
for k,v in pairs(model:findModules(name)) do
v.bias:zero()
end
end
function network.getWindowSize(net, ws)
ws = ws or 1
for i = 1,#net.modules do
local module = net:get(i)
if torch.typename(module) == 'cudnn.SpatialConvolution' then
ws = ws + module.kW - 1 - module.padW - module.padH
end
if module.modules then
ws = network.getWindowSize(module, ws)
end
end
return ws
end
function network.init(net)
convInit(net, 'cudnn.SpatialConvolution')
convInit(net, 'nn.SpatialConvolution')
bNInit(net, 'cudnn.SpatialBatchNormalization')
bNInit(net, 'nn.SpatialBatchNormalization')
linearInit(net, 'nn.Linear')
end
function network.fixBorder(vol, direction, ws)
local n = (ws - 1) / 2
for i=1,n do
vol[{{},{},{},direction * i}]:copy(vol[{{},{},{},direction * (n + 1)}])
end
end
local function padConvs(module)
-- Pads the convolutional layers to maintain the image resolution
for i = 1,#module.modules do
local m = module:get(i)
if torch.typename(m) == 'cudnn.SpatialConvolution' then
m.dW = 1
m.dH = 1
if m.kW > 1 then
m.padW = (m.kW - 1) / 2
end
if m.kH > 1 then
m.padH = (m.kH - 1) / 2
end
elseif m.modules then
padConvs(m)
end
end
end
function network.getTestNetwork(model)
-- Replace the model with fully-convolutional network
-- with the same weights, and pad it to maintain resolution
local testModel = model:clone('weight', 'bias')
-- replace linear with 1X1 conv
local nodes, containers = testModel:findModules('nn.Linear')
for i = 1, #nodes do
for j = 1, #(containers[i].modules) do
if containers[i].modules[j] == nodes[i] then
local w = nodes[i].weight
local b = nodes[i].bias
local conv = nn.SpatialConvolution1_fw(w:size(2), w:size(1)):cuda()
conv.weight:copy(w)
conv.bias:copy(b)
-- Replace with a new instance
containers[i].modules[j] = conv
end
end
end
-- replace reshape with concatenation
nodes, containers = testModel:findModules('nn.Reshape')
for i = 1, #nodes do
for j = 1, #(containers[i].modules) do
if containers[i].modules[j] == nodes[i] then
-- Replace with a new instance
containers[i].modules[j] = nn.Concatenation():cuda()
end
end
end
-- pad convolutions
padConvs(testModel)
-- switch to evalutation mode
testModel:evaluate()
return testModel
end
function network.forwardFree(net, input)
-- Forwards the network w.r.t input module by module
-- while cleaning previous modules state
local currentOutput = input
for i=1, #net.modules do
local m = net.modules[i]
local nextOutput
if torch.typename(m) == 'nn.Sequential' then
nextOutput = network.forwardFree(m, currentOutput)
currentOutput = nextOutput:clone()
elseif torch.typename(m) == 'nn.ConcatTable' or torch.typename(m) == 'nn.ParallelTable' then
nextOutput = m:forward(currentOutput)
currentOutput = {}
currentOutput[1] = nextOutput[1]:clone()
currentOutput[2] = nextOutput[2]:clone()
else
nextOutput = m:updateOutput(currentOutput)
currentOutput = nextOutput:clone()
end
m:apply(
function(mod)
mod:clearState()
end
)
collectgarbage()
end
return currentOutput
end
function network.sliceInput(input)
local sizes = torch.LongStorage{input:size(1) / 2, input:size(2), input:size(3), input:size(4)}
local strides = torch.LongStorage{input:stride(1) * 2, input:stride(2), input:stride(3), input:stride(4)}
local input_L = torch.CudaTensor(input:storage(), 1, sizes, strides)
local input_R = torch.CudaTensor(input:storage(), input:stride(1) + 1, sizes, strides)
return input_L, input_R
end
Normalization = nn.Normalize2
Activation = cudnn.ReLU
Convolution = cudnn.SpatialConvolution
Avg = cudnn.SpatialAveragePooling
Max = nn.SpatialMaxPooling
return network
|
local basic_stuff = require("lua_schema.basic_stuff");
local eh_cache = require("lua_schema.eh_cache");
local element_handler = {};
element_handler.__name__ = 'X509DataType';
local mt = { __index = element_handler; };
local _factory = {};
function _factory:new_instance_as_global_element(global_element_properties)
return basic_stuff.instantiate_type_as_doc_root(mt, global_element_properties);
end
function _factory:new_instance_as_local_element(local_element_properties)
return basic_stuff.instantiate_type_as_local_element(mt, local_element_properties);
end
function _factory:instantiate()
local o = {};
local o = setmetatable(o,mt);
return(o);
end
eh_cache.add('{http://www.w3.org/2000/09/xmldsig#}X509DataType', _factory);
do
element_handler.properties = {};
element_handler.properties.element_type = 'C';
element_handler.properties.content_type = 'C';
element_handler.properties.schema_type = '{http://www.w3.org/2000/09/xmldsig#}X509DataType';
element_handler.properties.q_name = {};
element_handler.properties.q_name.ns = 'http://www.w3.org/2000/09/xmldsig#'
element_handler.properties.q_name.local_name = 'X509DataType'
-- No particle properties for a typedef
element_handler.properties.attr = {};
element_handler.properties.attr._attr_properties = {};
element_handler.properties.attr._generated_attr = {};
end
-- element_handler.properties.content_model
do
element_handler.properties.content_model = {
generated_subelement_name = '_sequence_group',
min_occurs = 1,
top_level_group = true,
group_type = 'S',
max_occurs = -1,
{
generated_subelement_name = '_choice_group',
max_occurs = 1,
min_occurs = 1,
group_type = 'C',
top_level_group = false,
'X509IssuerSerial',
'X509SKI',
'X509SubjectName',
'X509Certificate',
'X509CRL',
'any',
},
};
end
-- element_handler.properties.content_fsa_properties
do
element_handler.properties.content_fsa_properties = {
{symbol_type = 'cm_begin', symbol_name = '_sequence_group', generated_symbol_name = '_sequence_group', min_occurs = 1, max_occurs = -1, cm = element_handler.properties.content_model}
,{symbol_type = 'cm_begin', symbol_name = '_choice_group', generated_symbol_name = '_choice_group', min_occurs = 1, max_occurs = 1, cm = element_handler.properties.content_model[1]}
,{symbol_type = 'element', symbol_name = '{http://www.w3.org/2000/09/xmldsig#}X509IssuerSerial', generated_symbol_name = '{http://www.w3.org/2000/09/xmldsig#}X509IssuerSerial', min_occurs = 1, max_occurs = 1, wild_card_type = 0, generated_name = 'X509IssuerSerial', cm = element_handler.properties.content_model[1]}
,{symbol_type = 'element', symbol_name = '{http://www.w3.org/2000/09/xmldsig#}X509SKI', generated_symbol_name = '{http://www.w3.org/2000/09/xmldsig#}X509SKI', min_occurs = 1, max_occurs = 1, wild_card_type = 0, generated_name = 'X509SKI', cm = element_handler.properties.content_model[1]}
,{symbol_type = 'element', symbol_name = '{http://www.w3.org/2000/09/xmldsig#}X509SubjectName', generated_symbol_name = '{http://www.w3.org/2000/09/xmldsig#}X509SubjectName', min_occurs = 1, max_occurs = 1, wild_card_type = 0, generated_name = 'X509SubjectName', cm = element_handler.properties.content_model[1]}
,{symbol_type = 'element', symbol_name = '{http://www.w3.org/2000/09/xmldsig#}X509Certificate', generated_symbol_name = '{http://www.w3.org/2000/09/xmldsig#}X509Certificate', min_occurs = 1, max_occurs = 1, wild_card_type = 0, generated_name = 'X509Certificate', cm = element_handler.properties.content_model[1]}
,{symbol_type = 'element', symbol_name = '{http://www.w3.org/2000/09/xmldsig#}X509CRL', generated_symbol_name = '{http://www.w3.org/2000/09/xmldsig#}X509CRL', min_occurs = 1, max_occurs = 1, wild_card_type = 0, generated_name = 'X509CRL', cm = element_handler.properties.content_model[1]}
,{symbol_type = 'any', symbol_name = '{}any', generated_symbol_name = '{}any', min_occurs = 1, max_occurs = 1, wild_card_type = 1, generated_name = 'any', cm = element_handler.properties.content_model[1]}
,{symbol_type = 'cm_end', symbol_name = '_choice_group', generated_symbol_name = '_choice_group', cm_begin_index = 2, cm = element_handler.properties.content_model[1]}
,{symbol_type = 'cm_end', symbol_name = '_sequence_group', generated_symbol_name = '_sequence_group', cm_begin_index = 1, cm = element_handler.properties.content_model}
};
end
do
element_handler.properties.declared_subelements = {
'{http://www.w3.org/2000/09/xmldsig#}X509IssuerSerial'
,'{http://www.w3.org/2000/09/xmldsig#}X509SKI'
,'{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'
,'{http://www.w3.org/2000/09/xmldsig#}X509Certificate'
,'{http://www.w3.org/2000/09/xmldsig#}X509CRL'
,'{}any'
};
end
do
element_handler.properties.subelement_properties = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'] = {};
do
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].super_element_content_type = require('org.w3.2001.XMLSchema.base64Binary_handler'):instantiate();
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].type_of_simple = 'A';
do
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].properties = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].properties.element_type = 'S';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].properties.content_type = 'S';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].properties.schema_type = '{http://www.w3.org/2001/XMLSchema}base64Binary';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].properties.bi_type = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].properties.bi_type.ns = 'http://www.w3.org/2001/XMLSchema';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].properties.bi_type.name = 'base64Binary';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].properties.bi_type.id = '44';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].properties.attr = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].properties.attr._attr_properties = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].properties.attr._generated_attr = {};
end
do
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].particle_properties = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].particle_properties.q_name = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].particle_properties.q_name.ns = 'http://www.w3.org/2000/09/xmldsig#';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].particle_properties.q_name.local_name = 'X509CRL';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].particle_properties.generated_name = 'X509CRL';
end
-- Simple type properties
do
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].base = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].base.ns = 'http://www.w3.org/2001/XMLSchema';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].base.name = 'base64Binary';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].local_facets = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].facets = basic_stuff.inherit_facets(element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL']);
end
do
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].type_handler = require('org.w3.2001.XMLSchema.base64Binary_handler'):instantiate();
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].get_attributes = basic_stuff.get_attributes;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].is_valid = basic_stuff.simple_is_valid;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].to_xmlua = basic_stuff.simple_to_xmlua;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].get_unique_namespaces_declared = basic_stuff.simple_get_unique_namespaces_declared;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].parse_xml = basic_stuff.parse_xml;
end
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].particle_properties.root_element = false;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].particle_properties.min_occurs = 1;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL'].particle_properties.max_occurs = 1;
end
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'] = {};
do
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].super_element_content_type = require('org.w3.2001.XMLSchema.base64Binary_handler'):instantiate();
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].type_of_simple = 'A';
do
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].properties = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].properties.element_type = 'S';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].properties.content_type = 'S';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].properties.schema_type = '{http://www.w3.org/2001/XMLSchema}base64Binary';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].properties.bi_type = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].properties.bi_type.ns = 'http://www.w3.org/2001/XMLSchema';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].properties.bi_type.name = 'base64Binary';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].properties.bi_type.id = '44';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].properties.attr = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].properties.attr._attr_properties = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].properties.attr._generated_attr = {};
end
do
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].particle_properties = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].particle_properties.q_name = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].particle_properties.q_name.ns = 'http://www.w3.org/2000/09/xmldsig#';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].particle_properties.q_name.local_name = 'X509Certificate';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].particle_properties.generated_name = 'X509Certificate';
end
-- Simple type properties
do
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].base = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].base.ns = 'http://www.w3.org/2001/XMLSchema';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].base.name = 'base64Binary';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].local_facets = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].facets = basic_stuff.inherit_facets(element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate']);
end
do
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].type_handler = require('org.w3.2001.XMLSchema.base64Binary_handler'):instantiate();
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].get_attributes = basic_stuff.get_attributes;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].is_valid = basic_stuff.simple_is_valid;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].to_xmlua = basic_stuff.simple_to_xmlua;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].get_unique_namespaces_declared = basic_stuff.simple_get_unique_namespaces_declared;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].parse_xml = basic_stuff.parse_xml;
end
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].particle_properties.root_element = false;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].particle_properties.min_occurs = 1;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate'].particle_properties.max_occurs = 1;
end
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'] = {};
do
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].super_element_content_type = require('org.w3.2001.XMLSchema.string_handler'):instantiate();
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].type_of_simple = 'A';
do
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].properties = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].properties.element_type = 'S';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].properties.content_type = 'S';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].properties.schema_type = '{http://www.w3.org/2001/XMLSchema}string';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].properties.bi_type = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].properties.bi_type.ns = 'http://www.w3.org/2001/XMLSchema';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].properties.bi_type.name = 'string';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].properties.bi_type.id = '1';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].properties.attr = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].properties.attr._attr_properties = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].properties.attr._generated_attr = {};
end
do
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].particle_properties = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].particle_properties.q_name = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].particle_properties.q_name.ns = 'http://www.w3.org/2000/09/xmldsig#';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].particle_properties.q_name.local_name = 'X509SubjectName';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].particle_properties.generated_name = 'X509SubjectName';
end
-- Simple type properties
do
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].base = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].base.ns = 'http://www.w3.org/2001/XMLSchema';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].base.name = 'string';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].local_facets = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].facets = basic_stuff.inherit_facets(element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName']);
end
do
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].type_handler = require('org.w3.2001.XMLSchema.string_handler'):instantiate();
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].get_attributes = basic_stuff.get_attributes;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].is_valid = basic_stuff.simple_is_valid;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].to_xmlua = basic_stuff.simple_to_xmlua;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].get_unique_namespaces_declared = basic_stuff.simple_get_unique_namespaces_declared;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].parse_xml = basic_stuff.parse_xml;
end
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].particle_properties.root_element = false;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].particle_properties.min_occurs = 1;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName'].particle_properties.max_occurs = 1;
end
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'] = {};
do
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].super_element_content_type = require('org.w3.2001.XMLSchema.base64Binary_handler'):instantiate();
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].type_of_simple = 'A';
do
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].properties = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].properties.element_type = 'S';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].properties.content_type = 'S';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].properties.schema_type = '{http://www.w3.org/2001/XMLSchema}base64Binary';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].properties.bi_type = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].properties.bi_type.ns = 'http://www.w3.org/2001/XMLSchema';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].properties.bi_type.name = 'base64Binary';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].properties.bi_type.id = '44';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].properties.attr = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].properties.attr._attr_properties = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].properties.attr._generated_attr = {};
end
do
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].particle_properties = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].particle_properties.q_name = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].particle_properties.q_name.ns = 'http://www.w3.org/2000/09/xmldsig#';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].particle_properties.q_name.local_name = 'X509SKI';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].particle_properties.generated_name = 'X509SKI';
end
-- Simple type properties
do
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].base = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].base.ns = 'http://www.w3.org/2001/XMLSchema';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].base.name = 'base64Binary';
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].local_facets = {};
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].facets = basic_stuff.inherit_facets(element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI']);
end
do
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].type_handler = require('org.w3.2001.XMLSchema.base64Binary_handler'):instantiate();
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].get_attributes = basic_stuff.get_attributes;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].is_valid = basic_stuff.simple_is_valid;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].to_xmlua = basic_stuff.simple_to_xmlua;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].get_unique_namespaces_declared = basic_stuff.simple_get_unique_namespaces_declared;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].parse_xml = basic_stuff.parse_xml;
end
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].particle_properties.root_element = false;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].particle_properties.min_occurs = 1;
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI'].particle_properties.max_occurs = 1;
end
do
element_handler.properties.subelement_properties['{}any'] =
(basic_stuff.get_element_handler('http://www.w3.org/2001/XMLSchema', 'anyType'):
new_instance_as_local_element({ns = '', local_name = 'any', generated_name = 'any',
root_element = false, min_occurs = 1, max_occurs = 1}));
end
do
element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509IssuerSerial'] =
(basic_stuff.get_element_handler('http://www.w3.org/2000/09/xmldsig#', 'X509IssuerSerialType'):
new_instance_as_local_element({ns = 'http://www.w3.org/2000/09/xmldsig#', local_name = 'X509IssuerSerial', generated_name = 'X509IssuerSerial',
root_element = false, min_occurs = 1, max_occurs = 1}));
end
end
do
element_handler.properties.generated_subelements = {
['_sequence_group'] = {}
,['X509IssuerSerial'] = element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509IssuerSerial']
,['X509SKI'] = element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SKI']
,['X509SubjectName'] = element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509SubjectName']
,['X509Certificate'] = element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509Certificate']
,['X509CRL'] = element_handler.properties.subelement_properties['{http://www.w3.org/2000/09/xmldsig#}X509CRL']
};
end
do
element_handler.type_handler = element_handler;
element_handler.get_attributes = basic_stuff.get_attributes;
element_handler.is_valid = basic_stuff.complex_type_is_valid;
element_handler.to_xmlua = basic_stuff.struct_to_xmlua;
element_handler.get_unique_namespaces_declared = basic_stuff.complex_get_unique_namespaces_declared;
element_handler.parse_xml = basic_stuff.parse_xml
end
return _factory;
|
-- 使用技能后加buff
function apply_modifier(keys)
local caster = keys.caster
local ability = keys.ability
-- 获取当前释放的技能
local event_ability = keys.event_ability
local isItem = event_ability:IsItem()
if not isItem then
local trigger_hp = ability:GetLevelSpecialValueFor("trigger_hp",
ability:GetLevel() -
1)
if caster:GetHealthPercent() <= trigger_hp then
caster:RemoveModifierByName("modifier_bloodthirsty_apply")
caster:RemoveModifierByName("modifier_bloodthirsty_apply_2")
ability:ApplyDataDrivenModifier(caster, caster,
"modifier_bloodthirsty_apply_2", {})
else
caster:RemoveModifierByName("modifier_bloodthirsty_apply")
caster:RemoveModifierByName("modifier_bloodthirsty_apply_2")
ability:ApplyDataDrivenModifier(caster, caster,
"modifier_bloodthirsty_apply", {})
end
end
end
|
settings {
logfile = "/var/log/lsyncd.log",
statusFile = "/var/log/lsyncd.status",
statusInterval = 5,
maxDelays = 1,
inotifyMode = "CloseWrite or Modify",
nodaemon = false,
maxProcesses = 1,
}
sync {
default.rsyncssh,
source = "/etc/dnsmasq-ha-web",
host = "[email protected]",
targetdir = "/etc/dnsmasq",
delay = 5,
delete = "running",
ssh = {
identityFile = "/etc/lsyncd/id_rsa",
},
rsync = {
compress = true,
checksum = true,
archive = true,
rsync_path = "sudo /usr/local/bin/dnsmasq-rsync.sh",
}
}
--- if you have more than 1 remote host, add more sections like above
sync {
default.rsyncssh,
source = "/etc/dnsmasq-ha-web",
host = "[email protected]",
targetdir = "/etc/dnsmasq",
delay = 5,
delete = "running",
ssh = {
identityFile = "/etc/lsyncd/id_rsa",
},
rsync = {
compress = true,
checksum = true,
archive = true,
rsync_path = "sudo /usr/local/bin/dnsmasq-rsync.sh",
}
}
|
function find_nodes_in_area_cache.create_entry(mapblock)
-- print("[cache] creating entry for mapblock " .. dump(mapblock))
local entry = {
mtime = os.time(),
blocks = {}
}
-- create nodename map
for nodename in pairs(find_nodes_in_area_cache.nodenames) do
entry.blocks[nodename] = {}
end
local pos1, pos2 = find_nodes_in_area_cache.get_blocks_from_mapblock(mapblock)
local manip = minetest.get_voxel_manip()
local e1, e2 = manip:read_from_map(pos1, pos2)
local area = VoxelArea:new({MinEdge=e1, MaxEdge=e2})
local node_data = manip:get_data()
-- loop over all blocks and fill cid,param1 and param2
for x=pos1.x,pos2.x do
for y=pos1.y,pos2.y do
for z=pos1.z,pos2.z do
local i = area:index(x,y,z)
local node_id = node_data[i]
local nodename = find_nodes_in_area_cache.node_id_map[node_id]
if nodename then
table.insert(entry.blocks[nodename], {x=x, y=y, z=z})
end
end
end
end
return entry
end
|
--[[-----------------------------------------------------------------------------
EditBox Widget
-------------------------------------------------------------------------------]]
local Type, Version = "CustomEditBox", 1
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local tostring, pairs = tostring, pairs
-- WoW APIs
local PlaySound = PlaySound
local GetCursorInfo, ClearCursor, GetSpellInfo = GetCursorInfo, ClearCursor, GetSpellInfo
local CreateFrame, UIParent = CreateFrame, UIParent
local _G = _G
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: AceGUIEditBoxInsertLink, ChatFontNormal, OKAY
--[[-----------------------------------------------------------------------------
Support functions
-------------------------------------------------------------------------------]]
if not AceGUIEditBoxInsertLink then
-- upgradeable hook
hooksecurefunc("ChatEdit_InsertLink", function(...) return _G.AceGUIEditBoxInsertLink(...) end)
end
function _G.AceGUIEditBoxInsertLink(text)
for i = 1, AceGUI:GetWidgetCount(Type) do
local editbox = _G["AceGUI-3.0EditBox"..i]
if editbox and editbox:IsVisible() and editbox:HasFocus() then
editbox:Insert(text)
return true
end
end
end
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function Control_OnEnter(frame)
frame.obj:Fire("OnEnter")
end
local function Control_OnLeave(frame)
frame.obj:Fire("OnLeave")
end
local function Frame_OnShowFocus(frame)
frame.obj.editbox:SetFocus()
frame:SetScript("OnShow", nil)
end
local function EditBox_OnEscapePressed(frame)
AceGUI:ClearFocus()
end
local function EditBox_OnEnterPressed(frame)
local self = frame.obj
local value = frame:GetText()
local cancel = self:Fire("OnEnterPressed", value)
if not cancel then
PlaySound(856) -- SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON
self:ClearFocus()
end
end
local function EditBox_OnReceiveDrag(frame)
local self = frame.obj
local type, id, info = GetCursorInfo()
local name
if type == "item" then
name = info
elseif type == "spell" then
name = GetSpellInfo(id, info)
elseif type == "macro" then
name = GetMacroInfo(id)
end
if name then
self:SetText(name)
self:Fire("OnEnterPressed", name)
ClearCursor()
AceGUI:ClearFocus()
end
end
local function EditBox_OnTextChanged(frame)
local self = frame.obj
local value = frame:GetText()
if self.ignoreNextSuggestion then
self.ignoreNextSuggestion = nil
return
end
if self.suggestions and #tostring(value) > #tostring(self.lasttext) then
local suggestion = nil
if #value > 0 then
for i, current in pairs(self.suggestions) do
if current:sub(1, #value) == value then
suggestion = current
break
end
end
end
if suggestion then
local remaining = suggestion:sub(#value + 1)
local newValue = value .. remaining
if tostring(value) ~= tostring(self.lasttext) then
self.ignoreNextSuggestion = true
frame:SetText(newValue)
frame:HighlightText(#value, #suggestion)
end
end
end
if tostring(value) ~= tostring(self.lasttext) then
self:Fire("OnTextChanged", value)
self.lasttext = value
end
end
local function EditBox_OnFocusGained(frame)
AceGUI:SetFocus(frame.obj)
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
-- height is controlled by SetLabel
self:SetWidth(200)
self:SetDisabled(false)
self:SetLabel()
self:SetText()
self:SetMaxLetters(0)
end,
["OnRelease"] = function(self)
self:ClearFocus()
end,
["SetDisabled"] = function(self, disabled)
self.disabled = disabled
if disabled then
self.editbox:EnableMouse(false)
self.editbox:ClearFocus()
self.editbox:SetTextColor(0.5,0.5,0.5)
self.label:SetTextColor(0.5,0.5,0.5)
else
self.editbox:EnableMouse(true)
self.editbox:SetTextColor(1,1,1)
self.label:SetTextColor(1,.82,0)
end
end,
["SetText"] = function(self, text)
self.lasttext = text or ""
self.editbox:SetText(text or "")
self.editbox:SetCursorPosition(0)
end,
["GetText"] = function(self, text)
return self.editbox:GetText()
end,
["SetLabel"] = function(self, text)
if text and text ~= "" then
self.label:SetText(text)
self.label:Show()
self.editbox:SetPoint("TOPLEFT",self.frame,"TOPLEFT",7,-18)
self:SetHeight(44)
self.alignoffset = 30
else
self.label:SetText("")
self.label:Hide()
self.editbox:SetPoint("TOPLEFT",self.frame,"TOPLEFT",7,0)
self:SetHeight(26)
self.alignoffset = 12
end
end,
["SetMaxLetters"] = function (self, num)
self.editbox:SetMaxLetters(num or 0)
end,
["ClearFocus"] = function(self)
self.editbox:ClearFocus()
self.frame:SetScript("OnShow", nil)
end,
["SetFocus"] = function(self)
self.editbox:SetFocus()
if not self.frame:IsShown() then
self.frame:SetScript("OnShow", Frame_OnShowFocus)
end
end,
["HighlightText"] = function(self, from, to)
self.editbox:HighlightText(from, to)
end,
["SetSuggestions"] = function(self, suggestions)
self.suggestions = suggestions
end,
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local function Constructor()
local num = AceGUI:GetNextWidgetNum(Type)
local frame = CreateFrame("Frame", nil, UIParent)
frame:Hide()
local editbox = CreateFrame("EditBox", "AceGUI-3.0EditBox"..num, frame, "InputBoxTemplate")
editbox:SetAutoFocus(false)
editbox:SetFontObject(ChatFontNormal)
editbox:SetScript("OnEnter", Control_OnEnter)
editbox:SetScript("OnLeave", Control_OnLeave)
editbox:SetScript("OnEscapePressed", EditBox_OnEscapePressed)
editbox:SetScript("OnEnterPressed", EditBox_OnEnterPressed)
editbox:SetScript("OnTextChanged", EditBox_OnTextChanged)
editbox:SetScript("OnReceiveDrag", EditBox_OnReceiveDrag)
editbox:SetScript("OnMouseDown", EditBox_OnReceiveDrag)
editbox:SetScript("OnEditFocusGained", EditBox_OnFocusGained)
editbox:SetTextInsets(0, 0, 3, 3)
editbox:SetMaxLetters(256)
editbox:SetPoint("BOTTOMLEFT", 6, 0)
editbox:SetPoint("BOTTOMRIGHT")
editbox:SetHeight(19)
local label = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
label:SetPoint("TOPLEFT", 0, -2)
label:SetPoint("TOPRIGHT", 0, -2)
label:SetJustifyH("LEFT")
label:SetHeight(18)
local widget = {
alignoffset = 30,
editbox = editbox,
label = label,
frame = frame,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
editbox.obj = widget
return AceGUI:RegisterAsWidget(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
|
netstream.Hook('TTS:Boombox.Play', function(ply, track_id)
TTS.HTTP(
'/api/server/track/' .. track_id .. '/play',
{
user_id = ply:GetUserID()
},
function(data)
-- PrintTable(data)
local uri = {}
ply:SetNWString("TTS::BoomboxAuthor",
(data.info.track_author or 'No')
.. ' - ' ..
(data.info.track_name or 'No')
)
ply:SetNWString("TTS::BoomboxPly", data.info.user.username .. ' (' .. data.info.user.steamid32 ..')')
if ply:GetInfoNum("avoid_boombox_play", 0) != 0 then return false end
for i,v in pairs(player.GetAll()) do
if v:GetInfoNum("avoid_boombox_play", 0) == 0 then
table.insert(uri, v)
end
end
netstream.Start(uri, 'TTS:Boombox.Play', {
url = data.url,
ply = ply
})
ply:SetNWFloat('TTS::BoomboxVolume', 1)
end
)
end)
netstream.Hook('TTS:Boombox.Pause', function(ply, track_id)
netstream.Start(_, 'TTS:Boombox.Pause', ply)
end)
netstream.Hook('TTS:Boombox.Resume', function(ply, track_id)
netstream.Start(_, 'TTS:Boombox.Resume', ply)
end)
local volumes = {
[1] = 1,
[2] = 0.75,
[3] = 0.50,
[4] = 0.25
}
netstream.Hook('TTS:Boombox.Volume', function(ply)
local volume_now = ply:GetNWFloat('TTS::BoomboxVolume')
local updated = false
for i, v in pairs(volumes) do
-- print(volume_now, v)
if volume_now > v then
ply:SetNWFloat('TTS::BoomboxVolume', v)
updated = true
break
end
end
if !updated then
ply:SetNWFloat('TTS::BoomboxVolume', 1)
end
end)
-- netstream.Start('TTS:Boombox.Volume')
if TTS.DEBUG then
concommand.Add('test_boombox', function(ply)
ply:Give('weapon_boombox')
end)
end
-- RunConsoleCommand('sv_cheats', 1) |
-------------------------------------------------------------------
--------------------------- window:dev services -----------------
-------------------------------------------------------------------
--[[
dev services window
win_devserv.show () -- Show
win_devserv.hide () -- Hide
win_devserv.pos (x,y) -- Position set
internals:
win_devserv.help () -- display help text
date: 17/10/2018
by: Raul Mungai
--]]
-- Load artworks
----------------
css.load_btn_img ("\\buttons\\moddev.png", "devserv") -- app icon
css.load_img ("\\icons\\moddev-i.png", "devserv-i", "icon") -- app icon (small)
css.load_btn_img ("\\buttons\\setCode.png", "setDevID")
css.load_btn_img ("\\buttons\\cancel.png", "cancel")
css.load_btn_img ("\\buttons\\devices.png", "devices") -- app icon button
css.font_mount (thema.workDisk .. "res\\font\\F16B_1_S.txt", "F16B")
css.font_mount (thema.workDisk .. "res\\font\\F16_1_S.txt", "F24B")
-- Global Object
win_devserv = {}
local winname = "win&devserv"
local winnameI = ""
editdevsIDVar = ""
local function win_devserv_create ()
winnameI = css.window_new (winname, false, "win_devserv.help")
-- add title and related buttons
css.window_title_new (winnameI, sknColl.dictGetPhrase("WIN", 33), nil, true)
css.window_title_btnSlected (winnameI, 3, true)
-- ID
local labID_w = 120
local labID_h = 20
-- UID
sknLbl.create("l_devsID", winnameI, 30, 60, labID_w, labID_h, "HorCenter_VertCenter", "Device ID")
sknLbl.font("l_devsID", "F16B")
sknLbl.colors("l_devsID", thema.win_color, "transparent")
sknLbl.show("l_devsID")
sknLbl.create("l_devsIDv", winnameI, 30, 80, labID_w, labID_h, "HorCenter_VertCenter", "")
sknLbl.font("l_devsIDv", "F24B")
sknLbl.colors("l_devsIDv", thema.win_color, "transparent")
sknLbl.show("l_devsIDv")
css.button_new ("setdevsIDb", winnameI, 200, 55, "setDevID", "win_devserv.setID", true, false, "Set devID", thema.win_color)
css.button_new ("dlstb", winnameI, 280, 55, "devices", "win_devserv.devlst", true, false, "Sel device", thema.win_color)
css.button_new ("uidrem", winnameI, 380, 55, "cancel", "win_devserv.uidremove", true, false, "UID Remove", thema.win_color)
end
-- device selection:OK
function win_devserv.selOK()
local si = o_list.selectedItem()
sknLbl.text("l_devsIDv", tostring(si.UID))
end
-- device selection:Canc
function win_devserv.selCanc()
end
-- find device
function win_devserv.devlst ()
local idx = 1
local wd = {}
o_list.init() -- clr list
repeat
wd = wd_manager.item_get (idx)
if wd ~= nil then
if wd.UID ~= 0 then
local widget = wd.wdptr
o_list.addItem(widget.icon, widget.desc, widget.radix ,widget.UID, wd.wdptr)
end
end
idx = idx + 1
until (wd == nil)
o_list.options("txt", false, true)
o_list.show(sknColl.dictGetPhrase("WIN", 30), win_devserv.selOK, win_devserv.seCanc, thema.btn_size)
end
-- change ID confirmation
function win_devserv.changeIDOK ()
sknLbl.text("l_devsIDv", editdevsIDVar)
end
-- set device ID
function win_devserv.setID ()
editdevsIDVar = sknLbl.text("l_devsIDv")
win_kbrd.set ("numbers", "editdevsIDVar", 10, winname, "win_devserv.changeIDOK", "Device UID")
end
-- Delete confirmation: OK
function win_devserv.decConf_OK ()
cccwrp.CCCremoveObj(uid)
win_devserv.hide ()
end
-- Delete confirmation: OK
function win_devserv.decConf_Canc ()
end
-- remove UID
function win_devserv.uidremove ()
local suid = sknLbl.text("l_devsIDv")
if suid == "" then return end
local uid = tonumber(suid)
if uid == 0 then return end
win_popupyn.text (win_devserv.decConf_OK, win_devserv.decConf_Canc, "RIMOZIONE DEVICE", "La rimozione e' definitiva, sei sicuro di voler rimuovere il Device:" .. suid .. " ?")
end
function win_devserv.show ()
sknWin.showRestorable (winname)
end
function win_devserv.hide ()
sknWin.hide (winname)
end
function win_devserv.pos (x,y)
sknWin.pos (winname, x,y)
end
-- display help text
function win_devserv.help (name)
win_helper.help (38, name)
end
win_devserv_create () -- Window creation
|
local WIM = WIM;
--------------------------------------
-- Table Functions --
--------------------------------------
-- Simple shallow copy for copying defaults
function copyTable(src, dest)
if type(dest) ~= type(src) and type(src) == "table" then dest = {} end
if type(src) == "table" then
for k,v in pairs(src) do
if type(v) == "table" then
-- try to index the key first so that the metatable creates the defaults, if set, and use that table
v = copyTable(v, dest[k])
end
dest[k] = v
end
end
return dest or src
end
WIM.copyTable = copyTable;
function WIM.inherritTable(src, dest, ...)
if(type(src) == "table") then
if(type(dest) ~= "table") then dest = {}; end
for k, v in pairs(src) do
local ignoredKey = false;
for i=1, select("#", ...) do
if(tostring(k) == tostring(select(i, ...))) then
ignoredKey = true;
break;
end
end
if(not ignoredKey) then
if(type(v) == "table") then
dest[k] = WIM.inherritTable(v, dest[k], ...);
else
if(dest[k] == nil) then
dest[k] = v
end
end
end
end
return dest;
else
if(dest == nil) then
return src;
else
return dest;
end
end
end
-- a simple function to add an item to a table checking for duplicates.
-- this is ok, since the table is never too large to slow things down.
function WIM.addToTableUnique(tbl, item, prioritize)
local i;
for i=1,table.getn(tbl) do
if(tbl[i] == item) then
return false;
end
end
if(prioritize) then
table.insert(tbl, 1, item);
else
table.insert(tbl, item);
end
return true;
end
-- remove item from table. Return true if removed, false otherwise.
function WIM.removeFromTable(tbl, item)
local i;
for i=1,table.getn(tbl) do
if(tbl[i] == item) then
table.remove(tbl, i);
return true;
end
end
return false;
end
function WIM.isInTable(tbl, val)
for i=1, #tbl do
if(tbl[i] == val) then
return true;
end
end
return false;
end
----------------------------------------------
-- Text Formatting --
----------------------------------------------
function WIM.FormatUserName(user)
if(user ~= nil and not string.find(user, "^|K")) then
user = string.gsub(user, "[A-Z]", string.lower);
user = string.gsub(user, "^[a-z]", string.upper);
user = string.gsub(user, "-[a-z]", string.upper); -- accomodate for cross server...
user = string.gsub(user, " [a-z]", string.upper); -- accomodate second name (BN)
end
return user;
end
----------------------------------------------
-- Gradient Tools --
----------------------------------------------
-- the following bits of code is a result of boredom
-- and determination to get it done. The gradient pattern
-- which I was aiming for could not be manipulated in RGB,
-- however by converting RGB to HSV, the pattern now becomes
-- linear and as such, can now be given any color and
-- have the same gradient effect applied.
function WIM.RGBPercentToHex(r, g, b)
return string.format ("%.2x%.2x%.2x",r*255,g*255,b*255);
end
function WIM.RGBHexToPercent(rgbStr)
local R, G, B = string.sub(rgbStr, 1, 2), string.sub(rgbStr, 3, 4), string.sub(rgbStr, 5, 6);
return tonumber(R, 16)/255, tonumber(G, 16)/255, tonumber(B, 16)/255;
end
function WIM.RGBHextoHSVPerc(rgbStr)
local R, G, B = WIM.RGBHexToPercent(rgbStr);
local i, x, v, f;
x = math.min(R, G);
x = math.min(x, B);
v = math.max(R, G);
v = math.max(v, B);
if(v == x) then
return nil, 0, v;
else
if(R == x) then
f = G - B;
elseif(G == x) then
f = B - R;
else
f = R - G;
end
if(R == x) then
i = 3;
elseif(G == x) then
i = 5;
else
i = 1;
end
return ((i - f /(v - x))/6), (v - x)/v, v;
end
end
function WIM.HSVPerctoRGBPerc(H, S, V)
local m, n, f, i;
if(H == nil) then
return V, V, V;
else
H = H * 6;
if (H == 0) then
H=.01;
end
i = math.floor(H);
f = H - i;
if((i % 2) == 0) then
f = 1 - f; -- if i is even
end
m = V * (1 - S);
n = V * (1 - S * f);
if(i == 6 or i == 0) then
return V, n, m;
elseif(i == 1) then
return n, V, m;
elseif(i == 2) then
return m, V, n;
elseif(i == 3) then
return m, n, V;
elseif(i == 4) then
return n, m, V;
elseif(i == 5) then
return V, m, n;
else
return 0, 0, 0;
end
end
end
-- pass rgb as signle arg hex, or triple arg rgb percent.
-- entering ! before a hex, will return a solid color.
function WIM.getGradientFromColor(...)
local h, s, v, s1, v1, s2, v2;
if(select("#", ...) == 0) then
return 0, 0, 0, 0, 0, 0;
elseif(select("#", ...) == 1) then
if(string.sub(select(1, ...),1, 1) == "!") then
local rgbStr = string.sub(select(1, ...), 2, 7);
local R, G, B = string.sub(rgbStr, 1, 2), string.sub(rgbStr, 3, 4), string.sub(rgbStr, 5, 6);
return tonumber(R, 16)/255, tonumber(G, 16)/255, tonumber(B, 16)/255, tonumber(R, 16)/255, tonumber(G, 16)/255, tonumber(B, 16)/255;
else
h, s, v = WIM.RGBHextoHSVPerc(select(1, ...));
end
else
h, s, v = WIM.RGBHextoHSVPerc(string.format ("%.2x%.2x%.2x",select(1, ...), select(2, ...), select(3, ...)));
end
s1 = math.min(1, s+.29/2);
v1 = math.max(0, v-.57/2);
s2 = math.max(0, s-.29/2);
v2 = math.min(1, s+.57/2);
local r1, g1, b1 = WIM.HSVPerctoRGBPerc(h, s1, v1);
local r2, g2, b2 = WIM.HSVPerctoRGBPerc(h, s2, v2);
return r1, g1, b1, r2, g2, b2;
end
--------------------------------------
-- String Functions --
--------------------------------------
function WIM.paddString(str, paddingChar, minLength, paddRight)
str = tostring(str or "");
paddingChar = tostring(paddingChar or " ");
minLength = tonumber(minLength or 0);
while(string.len(str) < minLength) do
if(paddRight) then
str = str..paddingChar;
else
str = paddingChar..str;
end
end
return str;
end
function WIM.gSplit(splitBy, str)
local index, splitBy, str = 0, splitBy, str;
return function()
index = index + 1;
return select(index, string.split(splitBy, str));
end
end
function WIM.SplitToTable(str, inSplitPattern, outResults )
if not outResults then
return;
end
local theStart = 1
local theSplitStart, theSplitEnd = string.find( str, inSplitPattern, theStart )
while theSplitStart do
table.insert( outResults, string.sub( str, theStart, theSplitStart-1 ) )
theStart = theSplitEnd + 1
theSplitStart, theSplitEnd = string.find( str, inSplitPattern, theStart )
end
table.insert( outResults, string.sub( str, theStart ) )
--if(#outResults > 0) then
-- table.remove(outResults, 1);
--end
end
--------------------------------------
-- Debugging Functions --
--------------------------------------
function WIM.dPrint(t)
if WIM.debug then
DEFAULT_CHAT_FRAME:AddMessage("|cffff0000[WIM Debug]:|r "..tostring(t));
end
end
function dumpGlobals()
local tmp = {};
for var, _ in pairs(_G) do
table.insert(tmp, var);
end
table.sort(tmp);
return tmp;
end
|
local geezify={}
function geezify.geezify_2digit(num)
local oneth_array = {'', '፩', '፪', '፫', '፬', '፭', '፮', '፯', '፰', '፱'}
local tenth_array = {'', '፲', '፳', '፴', '፵', '፶', '፷', '፸', '፹', '፺'}
local tenth_index = math.floor(num / 10)
local oneth_index = num % 10
return tenth_array[tenth_index+1] .. oneth_array[oneth_index+1]
end
function geezify.geezify_4digit(num)
local first2 = math.floor(num/100)
local second2 = num%100
if first2==0 then
return geezify.geezify_2digit(second2)
else
return geezify.geezify_2digit(first2) ..'፻'.. geezify.geezify_2digit(second2)
end
end
function geezify.split_every_4_digit(num)
local a={}
table.insert(a, string.sub(num,1, string.len(num)%4))
for digits in string.gmatch(string.sub(num,(string.len(num)%4)+1 ,-1) ,"%d%d%d%d") do
table.insert(a , digits)
end
return a
end
function geezify.geezify(num)
local digarr = geezify.split_every_4_digit(num)
local converted= ""
for i,v in ipairs(digarr) do
if i==1 and v=='' then
converted = converted
else
if converted==nil or converted == '' then
converted = (converted or '') .. geezify.geezify_4digit(v)
else
converted = (converted or "") ..'፼'.. geezify.geezify_4digit(v)
end
end
end
local geez_no =
string.gsub(
string.gsub(
string.gsub(converted,'፼፩፻', '፼፻')
,'^፩፼', '፼')
,'^(፩፻)', '፻')
return geez_no
end
return geezify
|
do
local FFmpeg = torch.class('FFmpeg')
function FFmpeg:__init(video_path, opts)
self.video_path = video_path
self.opts = opts or ''
self.valid = true
self.fd = nil
end
function FFmpeg:read(nframes)
if self.fd == nil then
-- open ffmpeg pipe
-- this subprocess will send raw RGB values to us, corresponding to frames
local cmd = 'ffmpeg -i ' .. self.video_path .. ' ' .. self.opts .. ' -f image2pipe -pix_fmt rgb24 -loglevel fatal -vcodec ppm -'
self.fd = assert(torch.PipeFile(cmd))
self.fd:binary()
self.fd:quiet()
end
-- read nframes from the pipe
local t
local t2
local dim = {}
for i=1,nframes do
local magic_str = self.fd:readString("*l")
local dim_str = self.fd:readString("*l")
local max_str = self.fd:readString("*l")
if self.fd:hasError() then
self.valid = false
return nil
end
assert(magic_str == "P6")
assert(tonumber(max_str) == 255)
if i == 1 then
for k in string.gmatch(dim_str, '%d+') do table.insert(dim, tonumber(k)) end
assert(#dim == 2)
t = torch.ByteTensor(nframes, dim[2], dim[1], 3):fill(0)
t2 = torch.ByteTensor(dim[2], dim[1], 3)
end
self.fd:readByte(t2:storage())
t[i]:copy(t2)
if self.fd:hasError() then
self.valid = false
return nil
end
end
return t:permute(1,4,2,3)
end
function FFmpeg:close()
if self.fd ~= nil then
self.fd:close()
self.fd = nil
self.valid = false
end
end
function FFmpeg:stats()
-- use ffprobe to find width/height of video
-- this will store self.width, self.height, self.duration
local cmd = 'ffprobe -select_streams v -v error -show_entries stream=width,height,duration -of default=noprint_wrappers=1 ' .. self.video_path
local fd = assert(torch.PipeFile(cmd))
fd:quiet()
local retval = {}
for i=1,3 do
local line = fd:readString('*l')
if fd:hasError() then
self.valid = false
break
end
local split = {}
for k in string.gmatch(line, '[^=]*') do table.insert(split, k) end
retval[split[1]] = tonumber(split[3])
end
fd:close()
return retval
end
end
|
local collect = require("nightfox.lib.collect")
local util = require("nightfox.util")
local M = { fox = "nightfox", has_options = false }
M.options = {
compile_path = util.join_paths(vim.fn.stdpath("cache"), "nightfox"),
compile_file_suffix = "_compiled",
transparent = false,
terminal_colors = true,
dim_inactive = false,
styles = {
comments = "NONE",
functions = "NONE",
keywords = "NONE",
numbers = "NONE",
strings = "NONE",
types = "NONE",
variables = "NONE",
},
inverse = {
match_paren = false,
visual = false,
search = false,
},
modules = {
barbar = true,
cmp = true,
dashboard = true,
diagnostic = {
enable = true,
background = true,
},
fern = true,
fidget = true,
gitgutter = true,
gitsigns = true,
glyph_pallet = true,
hop = true,
illuminate = true,
lightspeed = true,
lsp_saga = true,
lsp_trouble = true,
native_lsp = true,
neogit = true,
nvimtree = true,
sneak = true,
symbol_outline = true,
telescope = true,
treesitter = true,
tsrainbow = true,
whichkey = true,
},
}
function M.set_fox(name)
M.fox = name
end
function M.set_options(opts)
opts = opts or {}
M.options = collect.deep_extend(M.options, opts)
M.has_options = true
end
return M
|
-- HTTP web based client - URI modifier
-- Author:: Pavan Kumar Paluri
-- Copyright @ University of Houston - RTLAB @ 2020
-- init a random value
-- maintain an array of file size requests
local file_size_req = {1000, 100000, 1000000}
-- init a random seed
math.randomseed(os.time()) -- gives a random val on each run
-- HTTP req function that will run at each new request spawned by wrk2
http_req_gen = function()
-- choose a random req
local rand_req = file_size_req[math.random(1, #file_size_req)]
print(rand_req)
-- Define a path that will append a new val to the specified URI
url_path = "http://05943e71.ngrok.io/complex_hmap.php?random_request=" .. rand_req
print(url_path)
-- return the requested object with the current URL path
return wrk.format("GET", url_path)
end
-- invoke the above function
http_req_gen()
|
rvreasons = {}
rvreasons[1] = tr("1a) Offensive Name")
rvreasons[2] = tr("1b) Invalid Name Format")
rvreasons[3] = tr("1c) Unsuitable Name")
rvreasons[4] = tr("1d) Name Inciting Rule Violation")
rvreasons[5] = tr("2a) Offensive Statement")
rvreasons[6] = tr("2b) Spamming")
rvreasons[7] = tr("2c) Illegal Advertising")
rvreasons[8] = tr("2d) Off-Topic Public Statement")
rvreasons[9] = tr("2e) Non-English Public Statement")
rvreasons[10] = tr("2f) Inciting Rule Violation")
rvreasons[11] = tr("3a) Bug Abuse")
rvreasons[12] = tr("3b) Game Weakness Abuse")
rvreasons[13] = tr("3c) Using Unofficial Software to Play")
rvreasons[14] = tr("3d) Hacking")
rvreasons[15] = tr("3e) Multi-Clienting")
rvreasons[16] = tr("3f) Account Trading or Sharing")
rvreasons[17] = tr("4a) Threatening Gamemaster")
rvreasons[18] = tr("4b) Pretending to Have Influence on Rule Enforcement")
rvreasons[19] = tr("4c) False Report to Gamemaster")
rvreasons[20] = tr("Destructive Behaviour")
rvreasons[21] = tr("Excessive Unjustified Player Killing")
rvactions = {}
rvactions[0] = tr("Notation")
rvactions[1] = tr("Name Report")
rvactions[2] = tr("Banishment")
rvactions[3] = tr("Name Report + Banishment")
rvactions[4] = tr("Banishment + Final Warning")
rvactions[5] = tr("Name Report + Banishment + Final Warning")
rvactions[6] = tr("Statement Report")
ruleViolationWindow = nil
reasonsTextList = nil
actionsTextList = nil
function init()
connect(g_game, { onGMActions = loadReasons })
ruleViolationWindow = g_ui.displayUI('ruleviolation')
ruleViolationWindow:setVisible(false)
reasonsTextList = ruleViolationWindow:getChildById('reasonList')
actionsTextList = ruleViolationWindow:getChildById('actionList')
g_keyboard.bindKeyDown('Ctrl+Y', function() show() end)
if g_game.isOnline() then
loadReasons()
end
end
function terminate()
disconnect(g_game, { onGMActions = loadReasons })
g_keyboard.unbindKeyDown('Ctrl+Y')
ruleViolationWindow:destroy()
end
function hasWindowAccess()
return reasonsTextList:getChildCount() > 0
end
function loadReasons()
reasonsTextList:destroyChildren()
actionsTextList:destroyChildren()
local actions = g_game.getGMActions()
for reason, actionFlags in pairs(actions) do
local label = g_ui.createWidget('RVListLabel', reasonsTextList)
label.onFocusChange = onSelectReason
label:setText(rvreasons[reason])
label.reasonId = reason
label.actionFlags = actionFlags
end
if not hasWindowAccess() and ruleViolationWindow:isVisible() then hide() end
end
function show(target, statement)
if g_game.isOnline() and hasWindowAccess() then
if target then
ruleViolationWindow:getChildById('nameText'):setText(target)
end
if statement then
ruleViolationWindow:getChildById('statementText'):setText(statement)
end
ruleViolationWindow:show()
ruleViolationWindow:raise()
end
end
function hide()
ruleViolationWindow:hide()
clearForm()
end
function onSelectReason(reasonLabel, focused)
if reasonLabel.actionFlags and focused then
actionsTextList:destroyChildren()
for actionBaseFlag = 0, #rvactions do
local actionFlagString = rvactions[actionBaseFlag]
if bit32.band(reasonLabel.actionFlags, math.pow(2, actionBaseFlag)) > 0 then
local label = g_ui.createWidget('RVListLabel', actionsTextList)
label:setText(actionFlagString)
label.actionId = actionBaseFlag
end
end
end
end
function report()
local reasonLabel = reasonsTextList:getFocusedChild()
if not reasonLabel then
displayErrorBox(tr("Error"), tr("You must select a reason."))
return
end
local actionLabel = actionsTextList:getFocusedChild()
if not actionLabel then
displayErrorBox(tr("Error"), tr("You must select an action."))
return
end
local target = ruleViolationWindow:getChildById('nameText'):getText()
local reason = reasonLabel.reasonId
local action = actionLabel.actionId
local comment = ruleViolationWindow:getChildById('commentText'):getText()
local statement = ruleViolationWindow:getChildById('statementText'):getText()
local statementId = 0 -- TODO: message unique id ?
local ipBanishment = ruleViolationWindow:getChildById('ipBanCheckBox'):isChecked()
if action == 6 and statement == "" then
displayErrorBox(tr("Error"), tr("No statement has been selected."))
elseif comment == "" then
displayErrorBox(tr("Error"), tr("You must enter a comment."))
else
g_game.reportRuleViolation(target, reason, action, comment, statement, statementId, ipBanishment)
hide()
end
end
function clearForm()
ruleViolationWindow:getChildById('nameText'):clearText()
ruleViolationWindow:getChildById('commentText'):clearText()
ruleViolationWindow:getChildById('statementText'):clearText()
ruleViolationWindow:getChildById('ipBanCheckBox'):setChecked(false)
end
|
-- Copyright (C) 2019 Miku AuahDark
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
-- Base backend class
local path = (...):sub(1, #(...) - #(".backend.base"))
local Luaoop = require(path..".3p.Luaoop")
---@class Backend.Base
local BackendBase = Luaoop.class("Backend.Base")
-- luacheck: no unused args
function BackendBase:__construct()
error("pure virtual method 'BackendBase'")
end
--- Returns backend-defined object for models
---@param str string
---@return userdata
function BackendBase:loadModel(str)
error("pure virtual method 'loadModel'")
end
---@param model userdata
function BackendBase:updateModel(model)
error("pure virtual method 'update'")
end
---@param model userdata
function BackendBase:getModelDimensions(model)
error("pure virtual method 'getModelDimensions'")
end
---@param model userdata
function BackendBase:getModelPartCount(model)
error("pure virtual method 'getModelPartCount'")
end
--- 1-based index of model part, -length on not found
---@param model userdata
---@param name string
---@return number
function BackendBase:getModelPartIndex(model, name)
error("pure virtual method 'getModelPartIndex'")
end
---@param model userdata
---@param index number
---@return number
function BackendBase:getModelPartOpacity(model, index)
error("pure virtual method 'getModelPartOpacity'")
end
---@param model userdata
---@param index number
---@param value number
function BackendBase:setModelPartOpacity(model, index, value)
error("pure virtual method 'setModelPartOpacity'")
end
---@param model userdata
function BackendBase:getModelParameterCount(model)
error("pure virtual method 'getModelParameterCount'")
end
---@param model userdata
---@param name string
function BackendBase:getModelParameterIndex(model, name)
error("pure virtual method 'getModelParameterIndex'")
end
---@param model userdata
---@param index number
---@return number,number,number,number
function BackendBase:getModelParameterValue(model, index)
error("pure virtual method 'getModelParameterValue'")
end
---@param model userdata
---@param index number
---@param value number
function BackendBase:setModelParameterValue(model, index, value)
error("pure virtual method 'setModelParameterValue'")
end
---@param model userdata
---@return string[]
function BackendBase:getModelDrawableNames(model)
error("pure virtual method 'getModelDrawableNames'")
end
---@param model userdata
---@return number
function BackendBase:getModelDrawableRenderOrders(model)
error("pure virtual method 'getModelDrawableRenderOrders'")
end
---@param model userdata
---@return number
function BackendBase:getModelDrawableTextureIndex(model)
error("pure virtual method 'getModelDrawableTextureIndex'")
end
---@param model userdata
---@param index number
---@return number
function BackendBase:getModelDrawableVertexMapCount(model, index)
error("pure virtual method 'getModelDrawableVertexMapCount'")
end
---@param model userdata
---@param index number
---@return number
function BackendBase:getModelDrawableVertexCount(model, index)
error("pure virtual method 'getModelDrawableVertexCount'")
end
---@param model userdata
---@param index number
---@param cast boolean
---@return NVec[]|number[]
function BackendBase:getModelDrawableVertex(model, index, cast)
error("pure virtual method 'getModelDrawableVertex'")
end
---@param model userdata
---@param index number
---@return number[]
function BackendBase:getModelDrawableVertexMap(model, index)
error("pure virtual method 'getModelDrawableVertexMap'")
end
---@param model userdata
---@param index number
---@return NVec[]
function BackendBase:getModelDrawableUV(model, index)
error("pure virtual method 'getModelDrawableUV'")
end
---@param model userdata
---@param index number
---@return number
function BackendBase:getModelDrawableOpacity(model, index)
error("pure virtual method 'getModelDrawableOpacity'")
end
---@param model userdata
---@param index number
---@param flag number
---@return boolean
function BackendBase:getModelDrawableFlagsSet(model, index, flag)
error("pure virtual method 'getModelDrawableFlagsSet'")
end
---@param model userdata
---@param index number
---@param flag number
---@return boolean
function BackendBase:getModelDrawableDynFlagsSet(model, index, flag)
error("pure virtual method 'getModelDrawableDynFlagsSet'")
end
---@param model userdata
---@param index number
---@return number[]
function BackendBase:getModelDrawableClips(model, index)
error("pure virtual method 'getModelDrawableClips'")
end
return BackendBase
|
local function compare(first_value, compare_method, second_value)
if compare_method == "=" then
return first_value == second_value
elseif compare_method == "<=" then
return first_value <= second_value
elseif compare_method == "<" then
return first_value < second_value
elseif compare_method == ">=" then
return first_value >= second_value
elseif compare_method == ">" then
return first_value > second_value
elseif compare_method == "≠" then
return first_value ~= second_value
end
error("Not a valid compare method: " .. compare_method)
end
return {
compare = {
description = "Compare two numbers",
parameters = { "number", "compare-method", "number" },
result = "boolean",
parse = function(params, logic)
local first = params[1]
local compare_method = params[2]
local second = params[3]
return function(entity, current)
local first_value = logic.resolve(first, entity, current)
local second_value = logic.resolve(second, entity, current)
return compare(first_value, compare_method, second_value)
end
end
},
boolean_to_number = {
description = "Convert a boolean to a number. 1 == true and 0 == false",
parameters = { "boolean" },
result = "number",
parse = function(params, logic)
local value = params[1]
return function(entity, current)
local bool = logic.resolve(value, entity, current)
return bool and 1 or 0
end
end
},
["if"] = {
description = "Perform a command if condition is true",
parameters = { "boolean", "command" },
result = "command",
parse = function(params, logic)
local param_condition = params[1]
local param_command = params[2]
return function(entity, current)
local condition = logic.resolve(param_condition, entity, current)
if condition then
return logic.resolve(param_command, entity, current)
end
end
end
}
}
|
-- sample_wu.lua
batch = 172
subtype = "xyz"
require("app.lua")
param1="x"
param2="y"
prepare_something()
run_app()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.