content stringlengths 5 1.05M |
|---|
local SoundManager = {}
local Sounds = game.ReplicatedStorage.Pioneers.Assets.Sound
local TweenService = game:GetService("TweenService")
local masterGroup = Instance.new("SoundGroup", workspace)
local effectGroup = Instance.new("SoundGroup", workspace)
masterGroup.Volume = 1
effectGroup.Volume = 1
local FocusMuteVals = {
on = {
HighGain = -10,
MidGain = -17,
LowGain = -2,
},
off = {
HighGain = 0,
MidGain = 0,
LowGain = 0,
},
info = TweenInfo.new(0.5, Enum.EasingStyle.Linear, Enum.EasingDirection.Out)
}
function SoundManager.init()
spawn(SoundManager.newBGM)
local focusMuteMod = Sounds.Mods.FocusMute:Clone()
focusMuteMod.Parent = masterGroup
end
function SoundManager.newBGM()
local bgm = Sounds.BGM:GetChildren()
local i = math.random(1, #bgm)
music = bgm[i]:Clone()
music.Parent = masterGroup
music.SoundGroup = masterGroup
music.Playing = true
music.Ended:Wait()
music:Destroy()
SoundManager.newBGM()
end
function SoundManager.tempGlobal(sound)
sound.Parent = effectGroup
sound:Play()
sound:Destroy()
end
function SoundManager.tempWorld(sound, inst)
sound.Parent = inst
sound:Destroy()
end
function SoundManager.pullFocus()
TweenService:Create(masterGroup.FocusMute, FocusMuteVals.info, FocusMuteVals.on):Play()
end
function SoundManager.endFocus()
TweenService:Create(masterGroup.FocusMute, FocusMuteVals.info, FocusMuteVals.off):Play()
end
function SoundManager.softSelect()
SoundManager.tempGlobal(Sounds.Effects.SoftSelect:Clone())
end
function SoundManager.success()
SoundManager.tempGlobal(Sounds.Effects.Success:Clone())
end
function SoundManager.initiatePlace()
local effect = Sounds.Effects.InitiatePlace:Clone()
--[[effect.Parent = masterGroup
effect.Playing = true
delay(1, function() effect:Destroy() end)]]--
SoundManager.tempGlobal(effect)
end
function SoundManager.rollover()
local effect = Sounds.Effects.Highlight:Clone()
effect.TimePosition = 0.05
SoundManager.tempGlobal(effect)
end
function SoundManager.transition()
SoundManager.tempGlobal(Sounds.Effects.Transition:Clone())
end
function SoundManager.menuPopup()
SoundManager.tempGlobal(Sounds.Effects.MenuPopup:Clone())
end
function SoundManager.menuClick()
local effect = Sounds.Effects.MenuClick:Clone()
effect.TimePosition = 0.06
SoundManager.tempGlobal(effect)
end
function SoundManager.alert()
SoundManager.tempGlobal(Sounds.Effects.Alert:Clone())
end
function SoundManager.urgentAlert()
SoundManager.tempGlobal(Sounds.Effects.UrgentAlert:Clone())
end
function SoundManager.animSounds(inst, anim)
if not inst then return end
spawn(function()
local hitSignal = anim:GetMarkerReachedSignal("Hit")
local sound
if inst.Name == "Hoe" then
sound = Sounds.Effects.HitWheat:Clone()
elseif inst.Name == "Axe" then
sound = Sounds.Effects.HitTree:Clone()
elseif inst.Name == "Pickaxe" then
sound = Sounds.Effects.HitRock:Clone()
else
return
end
sound.Archivable = false
sound.Parent = inst
sound.SoundGroup = masterGroup
while anim do
hitSignal:Wait()
sound:Play()
end
sound:Destroy()
end)
end
return SoundManager |
MinHeap = {}
MinHeap.__index = MinHeap
local floor = math.floor
function MinHeap.new()
return setmetatable({ n = 0 }, MinHeap)
end
function MinHeap:insertvalue(num)
self[self.n] = num
self.n = self.n + 1
local child = self.n - 1
local parent, temp
while child > 0 do
parent = floor((child - 1)/2)
if self[parent] <= self[child] then
break
end
temp = self[parent]
self[parent] = self[child]
self[child] = temp
child = parent
end
return true
end
function MinHeap:findindex(num, root)
root = root or 0
if root >= self.n or num < self[root] then
return false
end
if num == self[root] then
return root
end
return self:findindex(num, root*2 + 1) or self:findindex(num, root*2 + 2)
end
function MinHeap:deleteindex(index)
if index < 0 or index >= self.n then
return false
end
local deleted = self[index]
self[index] = self[self.n-1]
self[self.n-1] = nil
self.n = self.n - 1
local parent = index
local child, temp
while true do
child = parent*2 + 1
if child >= self.n then
break
end
if child < self.n - 1 and self[child+1] < self[child] then
child = child + 1
end
if self[parent] <= self[child] then
break
end
temp = self[parent]
self[parent] = self[child]
self[child] = temp
parent = child
end
return deleted
end
function MinHeap:deletevalue(num)
local index = self:findindex(num)
if not index then
return false
end
return self:deleteindex(index)
end
function MinHeap:size()
return self.n
end
function MinHeap:empty()
return self.n == 0
end
function MinHeap:__tostring(index, depth)
index = index or 0
depth = depth or 0
if index >= self.n then
return ''
end
return (' '):rep(depth) .. tostring(self[index]) .. '\n' .. self:__tostring(index*2+1, depth+1) .. self:__tostring(index*2+2, depth+1)
end
|
--[[
Licensed under GNU General Public License v2
* (c) 2019, Alphonse Mariyagnanaseelan
Bindings for the treetile layout
--]]
local awful = require("awful")
local gtable = require("gears.table")
local treetile = require("treetile")
local k = {
m = "Mod4",
c = "Mod1",
a = "Control",
s = "Shift",
l = "j",
r = "l",
u = "i",
d = "k",
}
local bindings = { }
function bindings.init(args)
args = gtable.crush({
stop_key = 'Escape',
start_callback = function()
require("naughty").notify {text="treetile editor start"}
end,
stop_callback = function()
require("naughty").notify {text="treetile editor stop"}
end,
root_keybindings = {
{ { k.m }, ",", function() end },
},
keybindings = {
-- Focus (by direction)
{ { }, k.u, function() awful.client.focus.bydirection("up") end },
{ { }, k.d, function() awful.client.focus.bydirection("down") end },
{ { }, k.l, function() awful.client.focus.bydirection("left") end },
{ { }, k.r, function() awful.client.focus.bydirection("right") end },
-- Move
{ { k.m }, k.u, function() awful.client.swap.global_bydirection("up") end },
{ { k.m }, k.d, function() awful.client.swap.global_bydirection("down") end },
{ { k.m }, k.l, function() awful.client.swap.global_bydirection("left") end },
{ { k.m }, k.r, function() awful.client.swap.global_bydirection("right") end },
-- Resize
{ { k.s }, string.upper(k.u), function() awful.client.swap.global_bydirection("up") end },
{ { k.s }, string.upper(k.d), function() awful.client.swap.global_bydirection("down") end },
{ { k.s }, string.upper(k.l), function() awful.client.swap.global_bydirection("left") end },
{ { k.s }, string.upper(k.r), function() awful.client.swap.global_bydirection("right") end },
-- Rotate
{ { }, "r", function() treetile.rotate(client.focus) end },
{ { k.s }, "R", function() treetile.rotate_all(client.focus) end },
-- Swap
{ { }, "s", function() treetile.swap(client.focus) end },
{ { k.s }, "S", function() treetile.swap_all(client.focus) end },
-- -- Layout manipulation
-- { { k.m }, " ", function()
-- awful.layout.inc(1)
-- awful.screen.focused()._layout_popup:show()
-- end,
-- { description = "select next layout", group = "layout" } },
-- { { k.m, k.s }, " ", function()
-- awful.layout.inc(-1)
-- awful.screen.focused()._layout_popup:show()
-- end,
-- { description = "select previous layout", group = "layout" } },
-- -- Useless gaps
-- { { k.a }, k.d, function() awful.tag.incgap(beautiful.useless_gap/2) end,
-- { description = "increase useless gap", group = "command mode" } },
-- { { k.a }, k.u, function() awful.tag.incgap(-beautiful.useless_gap/2) end,
-- { description = "decrease useless gap", group = "command mode" } },
--
-- -- Useless gaps (precise)
-- { { k.a, k.c }, k.d, function() awful.tag.incgap(1) end,
-- { description = "increase useless gap (percise)", group = "command mode" } },
-- { { k.a, k.c }, k.u, function() awful.tag.incgap(-1) end,
-- { description = "increase useless gap (percise)", group = "command mode" } },
--
-- -- Client manipulation
-- { { }, " ", function()
-- if client.focus then
-- client.focus.floating = not client.focus.floating
-- end
-- end },
-- { { }, "z", function()
-- if client.focus then client.focus:kill() end
-- end },
-- { { }, "o", function()
-- if client.focus then client.focus:move_to_screen() end
-- end },
-- { { }, "t", function()
-- if client.focus then client.focus.ontop = not client.focus.ontop end
-- end },
-- { { }, "s", function()
-- if client.focus then client.focus.sticky = not client.focus.sticky end
-- end },
-- { { }, "n", function()
-- if client.focus then client.focus.minimized = true end
-- end },
-- { { }, "m", function()
-- if client.focus then util.toggle_maximized(client.focus) end
-- end },
-- { { }, "f", function()
-- if client.focus then util.toggle_fullscreen(client.focus) end
-- end },
-- { { k.s }, string.upper("n"), function()
-- local c = awful.client.restore()
-- if c then
-- client.focus = c
-- c:raise()
-- end
-- end },
--
-- -- Resize (ratio)
-- { { }, "1", function() set_width_factor((1 / 2 + 2.5) / 10) end, },
-- { { }, "2", function() set_width_factor((2 / 2 + 2.5) / 10) end, },
-- { { }, "3", function() set_width_factor((3 / 2 + 2.5) / 10) end, },
-- { { }, "4", function() set_width_factor((4 / 2 + 2.5) / 10) end, },
-- { { }, "5", function() set_width_factor((5 / 2 + 2.5) / 10) end, },
-- { { }, "6", function() set_width_factor((6 / 2 + 2.5) / 10) end, },
-- { { }, "7", function() set_width_factor((7 / 2 + 2.5) / 10) end, },
-- { { }, "8", function() set_width_factor((8 / 2 + 2.5) / 10) end, },
-- { { }, "9", function() set_width_factor((9 / 2 + 2.5) / 10) end, },
},
}, args or { })
return awful.keygrabber(args)
end
return bindings
|
local skynet = require "skynet"
local socket = require "socket"
local httpd = require "http.httpd"
local sockethelper = require "http.sockethelper"
local urllib = require "http.url"
local service = require "service"
local table = table
local string = string
local webrouter = require "http_webrouter"
local httpserver = {}
local mode = ...
if mode == "agent" then
local function response(id, ...)
local ok, err = httpd.write_response(sockethelper.writefunc(id), ...)
if not ok then
-- if err == sockethelper.socket_error , that means socket closed.
skynet.error(string.format("fd = %d, %s", id, err))
end
end
local function response_static_resource(id, path)
local f = io.open(path, "r")
if not f then
return response(id, 404, "not found")
end
local data = f:read("*a")
f:close()
return response(id, 200, data)
end
skynet.start(function()
local webroot = "/"
local webrouter = require("http_webrouter")
skynet.dispatch("lua", function (_,_,id)
socket.start(id)
-- limit request body size to 8192 (you can pass nil to unlimit)
local code, url, method, header, body = httpd.read_request(sockethelper.readfunc(id), 8192)
--skynet.error(string.format("http receive data id:%s,code:%s",id,code))
if code then
if code ~= 200 then
response(id, code)
else
local querystr = {}
local tmp = {}
if header.host then
table.insert(tmp, string.format("host: %s", header.host))
end
--skynet.error("url: %s",url)
local path, query = urllib.parse(url)
table.insert(tmp, string.format("path: %s", path))
if query then
querystr = urllib.parse_query(query)
for k, v in pairs(querystr) do
table.insert(tmp, string.format("query: %s= %s", k,v))
--print("querystr:"..k.." "..v)
end
end
table.insert(tmp, "-----header----")
for k,v in pairs(header) do
table.insert(tmp, string.format("%s = %s",k,v))
end
table.insert(tmp, "-----body----\n" .. body)
local f = webrouter and webrouter["wechat"]
if f == nil then
if not webroot then
response(id, 404, "not found")
else
response_static_resource(id, string.format("%s%s", webroot, path))
end
else
if type(f) == "function" then
response(id, f(method, header, tmp, querystr))
else
response(id, 200, tostring(f))
end
end
--response(id, code, "ok")
end
else
if url == sockethelper.socket_error then
skynet.error("socket closed")
else
skynet.error(url)
end
end
socket.close(id)
end)
end)
else
skynet.start(function()
local agent = {}
for i= 1, 20 do
agent[i] = skynet.newservice(SERVICE_NAME, "agent")
end
local balance = 1
local id = socket.listen("127.0.0.1", 8004)
skynet.error("Listen web port 8004")
socket.start(id , function(id, addr)
--skynet.error(string.format("%s connected, pass it to agent :%08x", addr, agent[balance]))
skynet.send(agent[balance], "lua", id)
balance = balance + 1
if balance > #agent then
balance = 1
end
end)
end)
end
|
vehicleUpgrades = { names = { }, prices = { } }
lowriders = { [536]=true, [575]=true, [534]=true, [567]=true, [535]=true, [576]=true, [412]=true }
racers = { [562]=true, [565]=true, [559]=true, [561]=true, [560]=true, [558]=true }
_getVehicleCompatibleUpgrades = getVehicleCompatibleUpgrades
function getVehicleCompatibleUpgrades( veh )
local upgrs = _getVehicleCompatibleUpgrades( veh )
local upgrades = { }
for k,v in ipairs( upgrs ) do
if not ( v == 1004 or v == 1005 or v == 1013 or v == 1024 or v == 1023 or v == 1031 or v == 1040 or v == 1041 or v == 1099 or v == 1143 or v == 1145 or v == 1030 or v == 1120 or v == 1121 ) then
table.insert( upgrades, v )
end
end
return upgrades
end
function isVehicleLowrider( vehicle )
local id = getElementModel( vehicle )
return lowriders[ id ]
end
function isVehicleRacer( vehicle )
local id = getElementModel( vehicle )
return racers[ id ]
end
function loadItems( )
local file_root = xmlLoadFile( "moditems.xml" )
local sub_node = xmlFindChild( file_root, "item", 0 )
local i = 1
while sub_node do
vehicleUpgrades.names[ i ] = xmlNodeGetAttribute( sub_node, "name" )
vehicleUpgrades.prices[ i ] = xmlNodeGetAttribute( sub_node, "price" )
sub_node = xmlFindChild( file_root, "item", i )
i = i + 1
end
end
function getItemPrice( itemid )
if not itemid then return false end
if itemid < 1000 or itemid > 1193 then
return false
elseif type( itemid ) ~= 'number' then
return false
end
return vehicleUpgrades.prices[ itemid - 999 ]
end
function getItemName( itemid )
if not itemid then return false end
if itemid > 1193 or itemid < 1000 then
return false
elseif type( itemid ) ~= 'number' then
return false
end
return vehicleUpgrades.names[ itemid - 999 ]
end
function getItemIDFromName( itemname )
if not itemname then
return false
elseif type( itemname ) ~= 'string' then
return false
end
for k,v in ipairs( vehicleUpgrades.names ) do
if v == itemname then
return k + 999
end
end
return false
end
|
local K, C = unpack(select(2, ...))
local Module = K:NewModule("NoTutorials")
local _G = _G
function Module:KillTutorials()
_G.HelpOpenTicketButtonTutorial:Kill()
_G.HelpPlate:Kill()
_G.HelpPlateTooltip:Kill()
_G.EJMicroButtonAlert:Kill()
_G.WorldMapFrame.BorderFrame.Tutorial:Kill()
_G.SpellBookFrameTutorialButton:Kill()
end
function Module:OnEnable()
if not C["General"].DisableTutorialButtons or K.CheckAddOnState("TutorialBuster") then
return
end
self:KillTutorials()
end
|
----------------------------------------------------------------------------------------------------
-- Mock for the environment without Sound.
----------------------------------------------------------------------------------------------------
-- import
local class = require "flower.class"
local BaseSoundMgr = require "flower.audio.BaseSoundMgr"
--- class
local MockSoundMgr = class(BaseSoundMgr)
---
-- Constructor.
function MockSoundMgr:init()
end
return MockSoundMgr |
-- signs_mtg/init.lua
-- Aliases to support loading worlds using nodes following the old naming convention
-- These can also be helpful when using chat commands, for example /giveme
minetest.register_alias("sign_wall", "base_signs:wood_sign_wall")
minetest.register_alias("default:sign_wall", "base_signs:wood_sign_wall")
minetest.register_alias("default:sign_wall_wood", "base_signs:wood_sign_wall")
minetest.register_alias("default:sign_wall_steel", "base_signs:steel_sign_wall")
|
slot2 = "NewbieApi30003"
NewbieApi30003 = class(slot1)
NewbieApi30003.ctor = function (slot0)
slot4 = BaseNewbieApi
ClassUtil.extends(slot2, slot0)
end
NewbieApi30003.checkStart = function (slot0, slot1)
slot4 = gameMgr
if gameMgr.getIsLoginBank(slot3) then
slot4 = slot0
slot0.finish(slot3)
else
slot5 = slot1
BaseNewbieApi.checkStart(slot3, slot0)
end
end
NewbieApi30003.start = function (slot0)
slot3 = slot0
slot0.finish(slot2)
end
NewbieApi30003.destroy = function (slot0)
slot3 = slot0
BaseNewbieApi.destroy(slot2)
end
return
|
--[[
Testing the Bag
--]]
local Collections = require("Collections")
local names = {
alpha = "alpha-value";
beta = "beta-value";
gamma = "gamma-value";
}
local bg = Collections.Bag();
for k,v in pairs(names) do
print("adding: ", k, v)
bg[k] = v;
end;
print("Count after add: ", #bg)
bg["gamma"] = nil;
print("Count, after 1 remove: ", #bg)
print("beta: ", bg["beta"])
-- iterate over items
print("== pairs ==")
for k,v in pairs(bg) do
print(k,v)
end
|
NMS_MOD_DEFINITION_CONTAINER =
{
["MOD_FILENAME"] = "TestMod.pak",
["MOD_AUTHOR"] = "Mjjstral",
["NMS_VERSION"] = "1.77",
["MODIFICATIONS"] =
{
{
["PAK_FILE_SOURCE"] = "NMSARC.59B126E2.pak",
["MBIN_CHANGE_TABLE"] =
{
{
["MBIN_FILE_SOURCE"] = "GCSKYGLOBALS.GLOBALS.MBIN",
["EXML_CHANGE_TABLE"] =
{
{
["PRECEDING_KEY_WORDS"] = "",
["VALUE_CHANGE_TABLE"] =
{
{"MinNightFade", "1.0"}, -- Original "0.62"
{"MaxNightFade", "1.0"} -- Original ""0.68"
}
}
}
} ,
{
["MBIN_FILE_SOURCE"] = "GCSPACESHIPGLOBALS.GLOBAL.MBIN",
["EXML_CHANGE_TABLE"] =
{
{
["PRECEDING_KEY_WORDS"] = "",
["VALUE_CHANGE_TABLE"] =
{
{"HoverTakeoffHeight", "45"}, -- Original "90"
{"HoverMinSpeed", "-1"}, -- Original "1"
{"GroundHeightSmoothTime", "9999999"},-- Original "0" --underwater
{"MiniWarpSpeed", "200000"}, -- Original "20000"
{"MiniWarpChargeTime", "0"} -- Original "2"
}
},
{
["PRECEDING_KEY_WORDS"] = "Control",
["VALUE_CHANGE_TABLE"] =
{
{"MinSpeed", "-5"} -- Original "0"
}
},
{
["PRECEDING_KEY_WORDS"] = "ControlLight",
["VALUE_CHANGE_TABLE"] =
{
{"MinSpeed", "-5"} -- Original "0"
}
},
{
["PRECEDING_KEY_WORDS"] = "ControlHeavy",
["VALUE_CHANGE_TABLE"] =
{
{"MinSpeed", "-5"} -- Original "0"
}
}
}
}
}
} ,
{
["PAK_FILE_SOURCE"] = "NMSARC.515F1D3.pak",
["MBIN_CHANGE_TABLE"] =
{
{
["MBIN_FILE_SOURCE"] = "METADATA\REALITY\TABLES\NMS_REALITY_GCTECHNOLOGYTABLE.MBIN",
["EXML_CHANGE_TABLE"] =
{
{
["SPECIAL_KEY_WORDS"] = {"ID","HYPERDRIVE",},
["PRECEDING_KEY_WORDS"] = "Ship_Hyperdrive_JumpDistance",
["SECTION_UP"] = 1,
["VALUE_CHANGE_TABLE"] =
{
{"Bonus", "9999999"} -- Original "100"
}
},
{
["SPECIAL_KEY_WORDS"] = {"ID","JET1",},
["PRECEDING_KEY_WORDS"] = "Suit_Jetpack_Tank",
["SECTION_UP"] = 1,
["VALUE_CHANGE_TABLE"] =
{
{"Bonus", "9999999"} -- Original "2.75"
}
},
{
["SPECIAL_KEY_WORDS"] = {"ID","LAUNCHER",},
["PRECEDING_KEY_WORDS"] = "Ship_Launcher_TakeOffCost",
["SECTION_UP"] = 1,
["VALUE_CHANGE_TABLE"] =
{
{"Bonus", "0"} -- Original "50"
}
},
}
},
}
}, --13 global replacements
}
}
--NOTE: ANYTHING NOT in table NMS_MOD_DEFINITION_CONTAINER IS IGNORED AFTER THE SCRIPT IS LOADED
--IT IS BETTER TO ADD THINGS AT THE TOP IF YOU NEED TO
--DON'T ADD ANYTHING PASS THIS POINT HERE
|
local unionScienceInfo = {}
function unionScienceInfo:Start(data)
self:initData(data)
self:initUi()
end
function unionScienceInfo:initData(data)
-- ERROR_LOG("ding==========>>>",sprinttb(data))
self.isLock=data.isLock
if data then
self.id = data.id
end
self.info = module.unionScienceModule.GetScienceInfo(self.id)
self.selfUnionLevel=module.unionModule.Manage:GetSelfUnion().unionLevel
self.level = self.info.level
self.nextCfg = module.unionScienceModule.GetScienceCfg(self.id)[self.level + 1]
self.cfg = module.unionScienceModule.GetScienceCfg(self.id)[self.level] or {}
end
function unionScienceInfo:Update()
local now = math.floor(UnityEngine.Time.timeSinceLevelLoad);
if self.last_update_time == now then
return;
end
self.last_update_time = now
self:upResearchTime()
end
function unionScienceInfo:upResearchTime()
local _off = self.info.time - module.Time.now()
if (self.view.root.right.researching.activeSelf and self.nextCfg) and (_off > 0) then
self.view.root.right.researching[UI.Scrollbar].size = (self.nextCfg.need_time - (self.info.time - module.Time.now())) / self.nextCfg.need_time
if (_off / 3600 > 1) then
self.view.root.right.researching.number[UI.Text].text = math.ceil(_off / 3600).."h"
else
self.view.root.right.researching.number[UI.Text].text = math.ceil(_off / 60).."min"
end
end
end
function unionScienceInfo:initInfo()
if self.isLock then
if self.isLock.guild_level > self.selfUnionLevel then
self.view.root.right.research:SetActive(false)
self.view.root.right.researchBtn[UI.Image].material=SGK.QualityConfig.GetInstance().grayMaterial
self.view.root.left.name[UI.Text].text = self.cfg.name or self.nextCfg.name
self.view.root.right.now.nowDesc[UI.Text].text = self.cfg.describe or ""
self.view.root.left.icon[UI.Image]:LoadSprite("icon/"..(self.cfg.icon or self.nextCfg.icon))
self.view.root.left.progress.now[UI.Text].text = tostring(self.level)
self.view.root.left.progress.max[UI.Text].text = tostring(#module.unionScienceModule.GetScienceCfg(self.id))
if self.nextCfg then
self.view.root.right.next.nextDesc[UI.Text].text = self.nextCfg.describe
end
self.view.root.right.lockLevel:SetActive(true)
self.view.root.right.lockLevel[UI.Text].text= string.format("需要公会达到%s级", self.isLock.guild_level)
return
end
end
self.view.root.left.name[UI.Text].text = self.cfg.name or self.nextCfg.name
self.view.root.right.now.nowDesc[UI.Text].text = self.cfg.describe or ""
self.view.root.left.icon[UI.Image]:LoadSprite("icon/"..(self.cfg.icon or self.nextCfg.icon))
if self.nextCfg then
self.view.root.right.next.nextDesc[UI.Text].text = self.nextCfg.describe
for i,v in ipairs(self.nextCfg.consume) do--下一等级的消耗
local _item = utils.ItemHelper.Get(v.type, v.id)
local _view = self.view.root.right.research.itemList[i]
_view.icon[UI.Image]:LoadSprite("icon/".._item.icon)
_view.number[UI.Text].text = "x"..v.value
for i,p in ipairs(module.unionScienceModule.GetDonationInfo().itemList) do
if v.id==p.id and p.value < v.value then
_view.number[UI.Text].color=CS.UnityEngine.Color.red
self.view.root.right.researchBtn[UI.Image].material=SGK.QualityConfig.GetInstance().grayMaterial
end
end
CS.UGUIClickEventListener.Get(_view.icon.gameObject).onClick = function()
DialogStack.PushPrefStact("ItemDetailFrame", {InItemBag=2,id = v.id,type = utils.ItemHelper.TYPE.ITEM})
end
end
if self.nextCfg.need_time / 3600 >= 1 then
self.view.root.right.research.time[UI.Text].text = math.floor(self.nextCfg.need_time / 3600).."h"
else
self.view.root.right.research.time[UI.Text].text = math.floor(self.nextCfg.need_time / 60).."min"
end
else
self.view.root.right.next.nextDesc[UI.Text].text = ""
end
self.view.root.right.research:SetActive(self.nextCfg and true)
self.view.root.right.researching:SetActive(not self.nextCfg)
self.view.root.left.progress.now[UI.Text].text = tostring(self.level)
self.view.root.left.progress.max[UI.Text].text = tostring(#module.unionScienceModule.GetScienceCfg(self.id))
self.view.root.right.researching:SetActive(self.info.time > module.Time.now())
self.view.root.right.research:SetActive((not self.view.root.right.researching.activeSelf) and self.nextCfg)
self.view.root.right.researchBtn:SetActive(self.view.root.right.research.activeSelf and self.nextCfg)
self.view.root.right.lockInfo:SetActive(self.nextCfg == nil)
-- ERROR_LOG("下一等级======>>>",sprinttb(self.nextCfg))
CS.UGUIClickEventListener.Get(self.view.root.right.researchBtn.gameObject).onClick = function()
local _title = module.unionModule.Manage:GetSelfTitle()
-- ERROR_LOG("ding==========>>>",_title)
if (_title ~= 1 and _title ~= 2) then
showDlgError(nil, SGK.Localize:getInstance():getValue("guild_techStudy_info6"))--判断是否是会长
return;
end
if module.unionScienceModule.IsResearching() then
showDlgError(nil, SGK.Localize:getInstance():getValue("guild_techStudy_info4"))
return
end
if self.nextCfg.guild_level > module.unionModule.Manage:GetSelfUnion().unionLevel then
showDlgError(nil, SGK.Localize:getInstance():getValue("guild_techStudy_info5"))
return
end
local _itemList = module.unionScienceModule.GetDonationInfo().itemList
for k,v in pairs(_itemList) do
for i,p in ipairs(self.nextCfg.consume) do
if v.id == p.id then
if p.value > v.value then
local _item = utils.ItemHelper.Get(p.type, p.id)
showDlgError(nil, SGK.Localize:getInstance():getValue("tips_ziyuan_buzu_01", _item.name))
return
end
break
end
end
end
self.view.root.right.researchBtn[CS.UGUIClickEventListener].interactable = false
self.view.root.right.researchBtn[UI.Image].material = SGK.QualityConfig.GetInstance().grayMaterial
local data = module.unionScienceModule.ScienceLevelUp(self.id)
-- coroutine.resume(coroutine.create(function()
-- self.view.root.right.researchBtn[CS.UGUIClickEventListener].interactable = true
-- self.view.root.right.researchBtn[UI.Image].material = nil
-- end))
DialogStack.Pop()
end
end
function unionScienceInfo:initUi()
self.view = CS.SGK.UIReference.Setup(self.gameObject)
CS.UGUIClickEventListener.Get(self.view.root.bg.closeBtn.gameObject).onClick = function()
DialogStack.Pop()
end
CS.UGUIClickEventListener.Get(self.view.mask.gameObject, true).onClick = function()
DialogStack.Pop()
end
self:initInfo()
end
function unionScienceInfo:deActive()
utils.SGKTools.PlayDestroyAnim(self.gameObject)
return true;
end
function unionScienceInfo:listEvent()
return {
"LOCAL_DONATION_CHANGE",
"LOCAL_SCIENCEINFO_CHANGE",
}
end
function unionScienceInfo:onEvent(event, data)
if event == "LOCAL_SCIENCEINFO_CHANGE" then
self:initData()
self:initInfo()
end
end
return unionScienceInfo
|
-- Must be called after app:enable("etlua")
local function render_component(name, data)
local template_f = require("views.components." .. name)
return template_f(data):render_to_string()
end
return render_component
|
HUD = class("HUD", Entity)
function HUD:initialize()
Entity.initialize(self)
self.layer = 1
self.hurtTimer = 0
self.hurtTime = 0.3
self.pad = 5
self.lineSpace = 20
self.healthImg = assets.images.healthIcon
self.shieldImg = assets.images.shieldIcon
self.clockMap = Spritemap:new(assets.images.clockIcon, 9, 9)
self.clockMap:add("spin", { 1, 2, 3, 4, 5, 6, 7, 8 }, 20, true)
self.clockMap:play("spin")
self.hurtOverlay = 0
end
function HUD:update(dt)
if self.hurtTimer > 0 then
self.hurtTimer = self.hurtTimer - dt
end
if self.world.player.shieldRegenTimer > 0 then
self.clockMap:update(dt)
end
end
function HUD:draw()
if self.hurtOverlay > 0 then
love.graphics.setColor(255, 0, 0, self.hurtOverlay)
love.graphics.rectangle("fill", -10, -10, love.graphics.width + 20, love.graphics.height + 20)
end
-- score
love.graphics.setColor(255, 255, 255)
love.graphics.setFont(assets.fonts.main[18])
love.graphics.printf("Score", self.pad, self.pad, love.graphics.width - self.pad * 2, "right")
love.graphics.setFont(assets.fonts.main[12])
love.graphics.printf(self.world.score, self.pad, self.pad + self.lineSpace, love.graphics.width - self.pad * 2, "right")
if not self.world.inWave then
love.graphics.setFont(assets.fonts.main[18])
love.graphics.print("Hiscore", self.pad, self.pad)
love.graphics.setFont(assets.fonts.main[12])
love.graphics.print(data.hiscore, self.pad, self.pad + self.lineSpace)
return
end
love.graphics.setFont(assets.fonts.main[18])
-- health
love.graphics.setColor(255, 50, 50)
love.graphics.draw(self.healthImg, self.pad, self.pad, 0, 2, 2)
if self.world.player.health < self.world.player.maxHealth and self.world.player.regenTimer <= 0 then
love.graphics.setColor(160, 255, 160)
elseif self.hurtTimer > 0 then
love.graphics.setColor(235, 35, 35)
else
love.graphics.setColor(255, 255, 255)
end
love.graphics.print(math.round(self.world.player.health), self.pad * 2 + self.healthImg:getWidth() * 2, self.pad)
-- shield
if self.world.player.shieldAllowed then
love.graphics.setColor(255, 255, 255)
local text, img, width
if self.world.player.shieldEnabled then
text = tostring(math.round(self.world.player.shieldHealth))
img = self.shieldImg
width = img:getWidth()
elseif self.world.player.shieldRegenTimer > 0 then
text = tostring(math.ceil(self.world.player.shieldRegenTimer))
img = self.clockMap
width = img.width
else
text = "Ready"
img = self.shieldImg
width = img:getWidth()
end
if img == self.clockMap then
img:draw(self.pad, self.pad + self.lineSpace, 0, 2, 2)
else
love.graphics.draw(img, self.pad, self.pad + self.lineSpace, 0, 2, 2)
end
love.graphics.print(text, self.pad * 2 + width * 2, self.pad + self.lineSpace)
end
end
function HUD:takenDamage()
self.hurtTimer = self.hurtTime
self.hurtOverlay = 100
self:animate(0.2, { hurtOverlay = 0 });
end
|
local module = {}
module.SSID = {}
module.SSID["NAME"] = "PASSWORD"
module.PORT = 80
return module
|
local M = {}
-- http://stackoverflow.com/questions/6380820/get-containing-path-of-lua-file
function script_path()
local str = debug.getinfo(2, "S").source:sub(2)
return str:match("(.*/)")
end
function M.parse(arg)
local cmd = torch.CmdLine()
cmd:text()
cmd:text('OpenFace')
cmd:text()
cmd:text('Options:')
------------ General options --------------------
cmd:option('-cache',
paths.concat(script_path(), 'work'),
'Directory to cache experiments and data.')
cmd:option('-save', '', 'Directory to save experiment.')
cmd:option('-data',
paths.concat(os.getenv('HOME'), 'openface', 'data',
'casia-facescrub',
'dlib-affine-sz:96'),
-- 'dlib-affine-224-split'),
'Home of dataset. Images separated by identity.')
cmd:option('-manualSeed', 2, 'Manually set RNG seed')
cmd:option('-cuda', true, 'Use cuda.')
cmd:option('-device', 1, 'Cuda device to use.')
cmd:option('-nGPU', 1, 'Number of GPUs to use by default')
cmd:option('-cudnn', true, 'Convert the model to cudnn.')
cmd:option('-cudnn_bench', false, 'Run cudnn to choose fastest option. Increase memory usage')
------------- Data options ------------------------
cmd:option('-nDonkeys', 2, 'number of donkeys to initialize (data loading threads)')
cmd:option('-channelSize', 3, 'channel size')
------------- Training options --------------------
cmd:option('-nEpochs', 1000, 'Number of total epochs to run')
cmd:option('-epochSize', 250, 'Number of batches per epoch')
cmd:option('-epochNumber', 1, 'Manual epoch number (useful on restarts)')
-- GPU memory usage depends on peoplePerBatch and imagesPerPerson.
cmd:option('-peoplePerBatch', 15, 'Number of people to sample in each mini-batch.')
cmd:option('-imagesPerPerson', 20, 'Number of images to sample per person in each mini-batch.')
cmd:option('-testing', true, 'Test with the LFW.')
cmd:option('-testBatchSize', 800, 'Batch size for testing.')
cmd:option('-testDir', '', 'Aligned image directory for testing.')
cmd:option('-testPy', '../evaluation/classify.py', 'Test function')
---------- Model options ----------------------------------
cmd:option('-retrain', 'none', 'provide path to model to retrain with')
cmd:option('-modelDef', '../models/openface/nn4.def.lua', 'path to model definiton')
cmd:option('-imgDim', 96, 'Image dimension. nn2=224, nn4=96')
cmd:option('-embSize', 128, 'size of embedding from model')
cmd:option('-alpha', 0.2, 'margin in TripletLoss')
cmd:option('-criterion', 'none', 'criterion')
cmd:text()
local opt = cmd:parse(arg or {})
os.execute('mkdir -p ' .. opt.cache)
if opt.save == '' then
opt.save = paths.concat(opt.cache, os.date("%Y-%m-%d_%H-%M-%S"))
end
os.execute('mkdir -p ' .. opt.save)
return opt
end
return M
|
--[[--
Provide WebView class.
This class allow to display HTML content in a window.
The WebView highly depends on the underlying OS.
Opening multiple WebView windows is not supported.
A webview requires a thread to run its own event loop, which is not compatible with the base event loop.
This class provide helpers to start webview in a dedicated thread so that the base event loop can be used.
@module jls.util.WebView
--]]
local webviewLib = require('webview')
local class = require('jls.lang.class')
local logger = require('jls.lang.logger')
local event = require('jls.lang.event')
local Promise = require('jls.lang.Promise')
local Thread = require('jls.lang.Thread')
local URL = require('jls.net.URL')
local Channel = require('jls.util.Channel')
-- workaround 2 issues: webview/GTK is changing the locale and cjson do not support such change
local function webviewLib_init(wv)
local locale = os.setlocale()
webviewLib.init(wv)
local newLocale = os.setlocale()
if locale ~= newLocale and not os.getenv('JLS_WEBVIEW_KEEP_LOCALE') then
logger:fine('webview init changed the locale to "'..tostring(newLocale)..'" restoring "'..tostring(locale)..'"')
os.setlocale(locale)
logger:fine('to avoid this behavior, preset the native locale using: os.setlocale("")')
end
end
local function optionsToArgs(options)
return options.title, options.width, options.height, options.resizable, options.debug
end
local function argsToOptions(title, width, height, resizable, debug, fn, data)
if type(title) == 'table' then
return title
end
return {
title = title,
width = width,
height = height,
resizable = resizable,
debug = debug,
fn = fn,
data = data
}
end
--- The WebView class.
-- @type WebView
return class.create(function(webView)
--[[--
Creates a new WebView.
The URL accepts the data, file and http schemes.
@tparam string url the URL of the resource to be viewed.
@tparam[opt] string title the title of the window.
@tparam[opt] number width the width of the opened window.
@tparam[opt] number height the height of the opened window.
@tparam[opt] boolean resizable true if the opened window could be resized.
@tparam[opt] boolean debug true to enable devtools.
@function WebView:new
@usage
local WebView = require('jls.util.WebView')
local webview = WebView:new(WebView.toDataUrl('<html><body>It works!</body></thread>'))
webview:loop()
]]
function webView:initialize(url, title, width, height, resizable, debug)
local options = argsToOptions(title, width, height, resizable, debug)
self._webview = webviewLib.new(url, optionsToArgs(options))
end
function webView:checkAvailable()
if not self._webview then
error('WebView not available')
end
end
function webView:isAvailable()
return self._webview ~= nil
end
--- Processes the webview event loop.
-- This function will block.
-- If you need to use the event loop in a callback then use the open function.
-- @tparam[opt] string mode the loop mode, default, once or nowait.
function webView:loop(mode)
self:checkAvailable()
local r = webviewLib.loop(self._webview, mode)
if r ~= 0 then
self._webview = nil
end
return r
end
--- Registers the specified function to be called from the web page.
-- The JavaScript syntax is window.external.invoke("string value");
-- @tparam function cb The callback to register.
function webView:callback(cb)
if logger:isLoggable(logger.FINE) then
logger:fine('webView:callback('..tostring(cb)..')')
end
self:checkAvailable()
webviewLib.callback(self._webview, cb)
end
--- Evaluates the specified JavaScript code in the web page.
-- @tparam string js The JavaScript code to evaluate.
function webView:eval(js)
if logger:isLoggable(logger.FINE) then
logger:fine('webView:eval('..tostring(js)..')')
end
self:checkAvailable()
webviewLib.eval(self._webview, js, true)
end
--- Sets the webview fullscreen.
-- @tparam boolean fullscreen true to switch the webview to fullscreen.
function webView:fullscreen(fullscreen)
if logger:isLoggable(logger.FINE) then
logger:fine('webView:fullscreen()')
end
self:checkAvailable()
webviewLib.fullscreen(self._webview, fullscreen)
end
--- Sets the webview title.
-- @tparam string title The webview title to set.
function webView:title(title)
if logger:isLoggable(logger.FINE) then
logger:fine('webView:title('..tostring(title)..')')
end
self:checkAvailable()
webviewLib.title(self._webview, title)
end
--- Terminates the webview.
function webView:terminate()
if logger:isLoggable(logger.FINE) then
logger:fine('webView:terminate()')
end
local wv = self._webview
if wv then
self._webview = nil
webviewLib.terminate(wv, true)
end
end
--- Returns the channel associated to this webview or nil.
-- @treturn jls.util.Channel the channel associated to this webview or nil.
function webView:getChannel()
return self._channel
end
--- Returns the thread associated to this webview or nil.
-- @treturn jls.util.Thread the thread associated to this webview or nil.
function webView:getThread()
return self._thread
end
--- Returns the HTTP server associated to this webview or nil.
-- @treturn jls.net.http.HttpServer the HTTP server associated to this webview or nil.
function webView:getHttpServer()
return self._httpServer
end
end, function(WebView)
function WebView._threadChannelOnlyFunction(webviewAsString, channelName, chunk, data)
if event:loopAlive() then
error('event loop is alive')
end
local fn, err = load(chunk, nil, 'b')
if not fn then
error('Unable to load chunk due to "'..tostring(err)..'"')
end
local channel = Channel:new()
channel:connect(channelName):catch(function(reason)
logger:fine('Unable to connect WebView thread due to '..tostring(reason))
channel = nil
end)
event:loop() -- wait for connection
if not channel then
error('Unable to connect WebView thread on "'..tostring(channelName)..'"')
end
local webview = class.makeInstance(WebView)
webview._channel = channel
webview._webview = webviewLib.fromstring(webviewAsString)
function webview:callback(cb)
webview._cb = cb
end
channel:receiveStart(function(message)
if webview._cb then
webview._cb(message)
end
end)
fn(webview, data)
event:loop()
end
-- We need to keep a reference to the thread webview to avoid GC
local WEBVIEW_THREAD_MAP = {}
local function registerWebViewThread(thread, webview)
webview._thread = thread
WEBVIEW_THREAD_MAP[thread] = webview
thread:ended():finally(function()
logger:finer('webview thread ended')
WEBVIEW_THREAD_MAP[thread] = nil
end)
end
local function openWithThreadAndChannel(url, options)
logger:finer('openWithThreadAndChannel()')
if type(options.fn) ~= 'function' then
error('Invalid function argument')
end
local wv = webviewLib.allocate(url, optionsToArgs(options))
local channelServer = Channel:new()
local acceptPromise = channelServer:acceptAndClose()
return channelServer:bind():next(function()
local channelName = channelServer:getName()
local thread = Thread:new(function(...)
local WV = require('jls.util.WebView')
WV._threadChannelOnlyFunction(...)
end)
thread:start(webviewLib.asstring(wv), channelName, string.dump(options.fn), options.data)
return acceptPromise
end):next(function(channel)
webviewLib.callback(wv, function(message)
channel:writeMessage(message, nil, false)
end)
webviewLib_init(wv)
channel:onClose():next(function()
if wv then
webviewLib.terminate(wv)
end
end)
webviewLib.loop(wv) -- Will block
webviewLib.clean(wv)
wv = nil
channel:close(false)
return Promise.resolve()
end)
end
function WebView._threadChannelFunction(webviewAsString, channelName)
if event:loopAlive() then
error('event loop is alive')
end
local wv = webviewLib.fromstring(webviewAsString)
local channel = Channel:new()
channel:connect(channelName):catch(function(reason)
logger:fine('Unable to connect WebView thread due to '..tostring(reason))
channel = nil
end)
event:loop() -- wait for connection
if not channel then
error('Unable to connect WebView thread on "'..tostring(channelName)..'"')
end
webviewLib.callback(wv, function(message)
channel:writeMessage(message, nil, false)
end)
webviewLib_init(wv)
channel:onClose():next(function()
if wv then
webviewLib.terminate(wv)
end
end)
webviewLib.loop(wv)
webviewLib.clean(wv)
wv = nil
channel:close(false)
event:loop()
end
local function openInThreadWithChannel(url, options)
logger:finer('openInThreadWithChannel()')
local webview = class.makeInstance(WebView)
function webview:callback(cb)
webview._cb = cb
end
local channelServer = Channel:new()
local acceptPromise = channelServer:acceptAndClose()
return channelServer:bind():next(function()
local channelName = channelServer:getName()
local thread = Thread:new(function(...)
local WV = require('jls.util.WebView')
WV._threadChannelFunction(...)
end)
local wv = webviewLib.allocate(url, optionsToArgs(options))
thread:start(webviewLib.asstring(wv), channelName)
registerWebViewThread(thread, webview)
webview._webview = wv
return acceptPromise
end):next(function(channel)
webview._channel = channel
channel:receiveStart(function(message)
if webview._cb then
webview._cb(message)
end
end)
--channel:onClose():next(function() webview:terminate() end)
return webview
end)
end
function WebView._threadOpenFunction(webviewAsString, chunk, data)
local wv = webviewLib.fromstring(webviewAsString)
local webview = class.makeInstance(WebView)
webview._webview = wv
webviewLib_init(wv)
if chunk then
local fn, err = load(chunk, nil, 'b')
if fn then
fn(webview, data)
else
error('Unable to load chunk due to "'..tostring(err)..'"')
end
end
webviewLib.loop(wv)
webviewLib.clean(wv)
end
local function openInThread(url, options)
logger:finer('openInThread()')
local webview = class.makeInstance(WebView)
function webview:callback(cb)
error('The WebView callback is not avaible')
end
local wv = webviewLib.allocate(url, optionsToArgs(options))
webview._webview = wv
local thread = Thread:new(function(...)
local WV = require('jls.util.WebView')
WV._threadOpenFunction(...)
end)
local chunk
if type(options.fn) == 'function' then
chunk = string.dump(options.fn)
end
thread:start(webviewLib.asstring(webview._webview), chunk, options.data)
registerWebViewThread(thread, webview)
return Promise.resolve(webview)
end
function WebView._threadWebSocketFunction(webview, wsUrl)
local ws = require('jls.net.http.ws')
if logger:isLoggable(logger.FINE) then
logger:fine('opening WebSocket "'..wsUrl..'"')
end
local webSocket = ws.WebSocket:new(wsUrl)
webSocket:open():next(function()
logger:fine('WebSocket opened, callback available')
webview:callback(function(payload)
webSocket:sendTextMessage(payload)
end)
end)
event:loop() -- wait for connection
end
local function openInThreadWithHttpServer(tUrl, options)
logger:finer('openInThreadWithHttpServer()')
local HttpServer = require('jls.net.http.HttpServer')
local httpServer = HttpServer:new()
local wsPromise
return httpServer:bind(tUrl.host, tUrl.port):next(function()
if type(options.contexts) == 'table' then
for path, handler in pairs(options.contexts) do
httpServer:createContext(path, handler)
end
end
if tUrl.port == 0 then
tUrl.port = select(2, httpServer:getAddress())
end
local url = URL.format(tUrl)
if options.callback == true then
local strings = require('jls.util.strings')
local ws = require('jls.net.http.ws')
local wsPath = '/webview-callback/'
options.fn = function(...)
local WV = require('jls.util.WebView')
WV._threadWebSocketFunction(...)
end
tUrl.scheme = 'ws'
tUrl.path = wsPath
options.data = URL.format(tUrl)
local wsCb
wsPromise, wsCb = Promise.createWithCallback()
httpServer:createContext(strings.escape(wsPath), ws.upgradeHandler, {open = function(newWebSocket)
wsCb(nil, newWebSocket)
end})
if logger:isLoggable(logger.FINE) then
logger:fine('WebSocket context "'..wsPath..'" created')
end
end
if logger:isLoggable(logger.FINE) then
logger:fine('opening WebView url "'..url..'"')
end
return openInThread(url, options)
end):next(function(webview)
webview._httpServer = httpServer
webview:getThread():ended():next(function()
logger:fine('WebView closed')
return httpServer:close()
end):next(function()
logger:fine('WebView HTTP Server closed')
end)
logger:fine('WebView opened')
if wsPromise then
function webview:callback(cb)
webview._cb = cb
end
return wsPromise:next(function(webSocket)
function webSocket:onTextMessage(payload)
if webview._cb then
webview._cb(payload)
end
end
webSocket:readStart()
webview:getThread():ended():next(function()
return webSocket:close()
end):next(function()
logger:fine('WebView WebSocket closed')
end)
return webview
end)
end
return webview
end)
end
--[[--
Opens the specified URL in a new window and returns when the window has been closed.
Passing a function will block the event loop not this function.
@tparam string url the URL of the resource to be viewed.
@param[opt] title the title of the window or a table containing the options.
@tparam[opt] number width the width of the opened window.
@tparam[opt] number height the height of the opened window.
@tparam[opt] boolean resizable true if the opened window could be resized.
@tparam[opt] boolean debug true to enable devtools.
@tparam[opt] function fn a function to be called in a dedicated thread, requires the event loop.
@tparam[opt] string data the data to be passed to the function as a string.
@treturn jls.lang.Promise a promise that resolve when the webview is closed or nil.
@usage
local WebView = require('jls.util.WebView')
WebView.openSync('https://www.lua.org/')
]]
function WebView.openSync(url, title, width, height, resizable, debug, fn, data)
local options = argsToOptions(title, width, height, resizable, debug, fn, data)
if options.fn then
return openWithThreadAndChannel(url, options)
end
logger:finer('open WebView and loop')
local webview = WebView:new(url, optionsToArgs(options))
webview:loop()
end
--[[--
Opens the specified URL in a new window.
Opening a webview in a dedicated thread may not be supported on all platform.
You could specify an HTTP URL with a port to 0 to indicate that an HTTP server should be started on a random port.
@tparam string url the URL of the resource to be viewed.
@param[opt] title the title of the window or a table containing the options.
@tparam[opt] number width the width of the opened window.
@tparam[opt] number height the height of the opened window.
@tparam[opt] boolean resizable true if the opened window could be resized.
@tparam[opt] boolean debug true to enable devtools.
@tparam[opt] function fn a function to be called in the webview context or true to indicate that no callback will be used.
@tparam[opt] string data the data to be passed to the function as a string.
@treturn jls.lang.Promise a promise that resolve when the webview is available.
@usage
local WebView = require('jls.util.WebView')
local FileHttpHandler = require('jls.net.http.handler.FileHttpHandler')
WebView.open('http://localhost:0/index.html'):next(function(webview)
local httpServer = webview:getHttpServer()
httpServer:createContext('/(.*)', FileHttpHandler:new('htdocs'))
end)
]]
function WebView.open(url, title, width, height, resizable, debug, fn, data)
local options = argsToOptions(title, width, height, resizable, debug, fn, data)
if options.fn then
return openInThread(url, options)
end
local tUrl = URL.parse(url)
if tUrl and tUrl.scheme == 'http' and tUrl.host and (tUrl.port == 0 or options.bind) then
return openInThreadWithHttpServer(tUrl, options)
end
return openInThreadWithChannel(url, options)
end
--[[--
Returns an URL representing the specified content.
@tparam string content the HTML content to convert.
@tparam[opt] string mediaType the media type, default is text/html.
@treturn string an URL representing the specified content.
@usage
local url = WebView.toDataUrl('<html><body>Hello</body></thread>'))
]]
function WebView.toDataUrl(content, mediaType)
local data = string.gsub(content, "[ %c!#$%%&'()*+,/:;=?@%[%]]", function(c)
return string.format('%%%02X', string.byte(c))
end)
if type(mediaType) ~= 'string' then
mediaType = 'text/html'
end
return 'data:'..mediaType..','..data
end
end)
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:26' 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.
****************************************************************************
]]
----------------------------
-- Guild Finder Panel --
----------------------------
ZO_GuildFinder_Panel_Shared = ZO_Object:Subclass()
function ZO_GuildFinder_Panel_Shared:New(...)
local panel = ZO_Object.New(self)
panel:Initialize(...)
return panel
end
function ZO_GuildFinder_Panel_Shared:Initialize(control)
self.control = control
local ALWAYS_ANIMATE = true
self.fragment = ZO_FadeSceneFragment:New(control, ALWAYS_ANIMATE)
self.fragment:RegisterCallback("StateChange", function(oldState, newState)
if newState == SCENE_FRAGMENT_SHOWING then
self:OnShowing()
elseif newState == SCENE_FRAGMENT_HIDING then
self:OnHiding()
elseif newState == SCENE_FRAGMENT_HIDDEN then
self:OnHidden()
end
end)
end
function ZO_GuildFinder_Panel_Shared:OnShowing()
-- override in derived classes
end
function ZO_GuildFinder_Panel_Shared:OnHiding()
-- override in derived classes
end
function ZO_GuildFinder_Panel_Shared:OnHidden()
-- override in derived classes
end
function ZO_GuildFinder_Panel_Shared:ShowCategory()
SCENE_MANAGER:AddFragment(self.fragment)
end
function ZO_GuildFinder_Panel_Shared:HideCategory()
SCENE_MANAGER:RemoveFragment(self.fragment)
end
function ZO_GuildFinder_Panel_Shared:GetFragment()
return self.fragment
end |
local status = require("nvimmercurial/status")
local graphlog = require("nvimmercurial/graphlog")
local commands = require("nvimmercurial/commands")
status.register_close_callback(function()
graphlog.close()
end)
graphlog.register_close_callback(function()
status.close()
end)
local commit_msg_buf = -1;
-- Intentionally global. This function is used by the remote client callback to
-- determine if the commit edit buffer is still open or not.
function MercurialGetResult()
return vim.api.nvim_buf_is_loaded(commit_msg_buf) and 1 or 0
end
-- Intentionally global. This function is used by the remote client callback to
-- start editing the commit message.
function MercurialEditCommitMessage(commit_message_filename, client_socket)
vim.api.nvim_command(string.format(':sp %s', commit_message_filename))
commit_msg_buf = vim.fn.bufnr(commit_message_filename)
end
return {
status = status,
graphlog = graphlog,
commands = commands,
}
|
----------------------------------------
-- CCNode
----------------------------------------
CCNodeExtend.remove = CCNodeExtend.removeSelf
function CCNodeExtend:add(child, zorder, tag)
self:addChild(child, zorder or 0, tag or 0)
return self
end
function CCNodeExtend:addTo(target, zorder, tag)
target:addChild(self, zorder or 0, tag or 0)
return self
end
function CCNodeExtend:show()
self:setVisible(true)
return self
end
function CCNodeExtend:hide()
self:setVisible(false)
return self
end
function CCNodeExtend:pos(x, y)
self:setPosition(x, y)
return self
end
function CCNodeExtend:center()
self:setPosition(display.cx, display.cy)
return self
end
function CCNodeExtend:scale(scale)
self:setScale(scale)
return self
end
function CCNodeExtend:rotation(r)
self:setRotation(r)
return self
end
function CCNodeExtend:size(width, height)
if type(width) == "userdata" then
self:setContentSize(width)
else
self:setContentSize(CCSize(width, height))
end
return self
end
function CCNodeExtend:opacity(opacity)
self:setOpacity(opacity)
return self
end
function CCNodeExtend:zorder(z)
self:setZOrder(z)
return self
end
-- actions
function CCNodeExtend:stop()
self:stopAllActions()
return self
end
function CCNodeExtend:fadeIn(time)
self:runAction(CCFadeIn:create(time))
return self
end
function CCNodeExtend:fadeOut(time)
self:runAction(CCFadeOut:create(time))
return self
end
function CCNodeExtend:fadeTo(time, opacity)
self:runAction(CCFadeTo:create(time, opacity))
return self
end
function CCNodeExtend:moveTo(time, x, y)
self:runAction(CCMoveTo:create(time, CCPoint(x or self:getPositionX(), y or self:getPositionY())))
return self
end
function CCNodeExtend:moveBy(time, x, y)
self:runAction(CCMoveBy:create(time, CCPoint(x or 0, y or 0)))
return self
end
function CCNodeExtend:rotateTo(time, rotation)
self:runAction(CCRotateTo:create(time, rotation))
return self
end
function CCNodeExtend:rotateBy(time, rotation)
self:runAction(CCRotateBy:create(time, rotation))
return self
end
function CCNodeExtend:scaleTo(time, scale)
self:runAction(CCScaleTo:create(time, scale))
return self
end
function CCNodeExtend:scaleBy(time, scale)
self:runAction(CCScaleBy:create(time, scale))
return self
end
function CCNodeExtend:skewTo(time, sx, sy)
self:runAction(CCSkewTo:create(time, sx or self:getSkewX(), sy or self:getSkewY()))
end
function CCNodeExtend:skewBy(time, sx, sy)
self:runAction(CCSkewBy:create(time, sx or 0, sy or 0))
end
function CCNodeExtend:tintTo(time, r, g, b)
self:runAction(CCTintTo:create(time, r or 0, g or 0, b or 0))
return self
end
function CCNodeExtend:tintBy(time, r, g, b)
self:runAction(CCTintBy:create(time, r or 0, g or 0, b or 0))
return self
end
----------------------------------------
-- CCSprite
----------------------------------------
CCSpriteExtend.playOnce = CCSpriteExtend.playAnimationOnce
CCSpriteExtend.playForever = CCSpriteExtend.playAnimationForever
function CCSpriteExtend:displayFrame(frame, index)
if type(frame) == "string" then
self:setDisplayFrame(frame, index or 0)
else
self:setDisplayFrame(frame)
end
return self
end
function CCSpriteExtend:flipX(b)
self:setFlipX(b)
return self
end
function CCSpriteExtend:flipY(b)
self:setFlipY(b)
return self
end
----------------------------------------
-- CCLayer
----------------------------------------
function CCLayerExtend:onTouch(listener, isMultiTouches, priority, swallowsTouches)
self:addTouchEventListener(listener, tobool(isMultiTouches), toint(priority), tobool(swallowsTouches))
return self
end
function CCLayerExtend:enableTouch(enabled)
self:setTouchEnabled(enabled)
return self
end
function CCLayerExtend:onKeypad(listener)
self:addKeypadEventListener(listener)
return self
end
function CCLayerExtend:enableKeypad(enabled)
self:setKeypadEnabled(enabled)
return self
end
function CCLayerExtend:onAccelerate(listener)
self:addAccelerateEventListener(listener)
return self
end
function CCLayerExtend:enableAccelerometer(enabled)
self:setAccelerometerEnabled(enabled)
return self
end
|
for i = 1, 10 do
local t = false
repeat
t = f3(i)
if f4() then
break
else
f1()
end
f2()
until true
if t then
break
end
end
|
local p = {}
--[[
luastatus supports using pango markup like attributes.
see bellow for a quick demo of how to use this.
the attributes allowed are the same as the span attributes in pango,
represented inside a table.
]]--
-- For more informations about pango:
-- https://developer.gnome.org/pango/stable/PangoMarkupFormat.html
p.interval = 100000
p.name = "pango demo"
p.status = {
"Normal text",
{foreground="#F00",text="C"},
{foreground="#FF0",text="O"},
{foreground="#0F0",text="L"},
{foreground="#0FF",text="O"},
{foreground="#00F",text="R"},
{foreground="#F0F",text="S "},
{style="italic",text="italic "},
{weight="bold",text="bold "},
{underline="single",text="underline "},
{size="xx-small",text="xx-small :)"}
}
function p.update() end
function p.click() end
return p
|
-- prevent use of loadstring(code)()
-- this is a simple VM which replicates loadstring()() in it's entirety
-- not written by me
local waitDeps = {
'Rerubi';
'LuaK';
'LuaP';
'LuaU';
'LuaX';
'LuaY';
'LuaZ';
}
local holder = script.Parent:WaitForChild("Dependencies"):WaitForChild("VM");
for i,v in pairs(waitDeps) do holder:WaitForChild(v) end
local luaX = require(holder.LuaX)
local luaY = require(holder.LuaY)
local luaZ = require(holder.LuaZ)
local luaU = require(holder.LuaU)
local rerubi = require(holder.Rerubi)
luaX:init()
local LuaState = {}
getfenv().script = nil
return function(str,env)
local f,writer,buff,name
local env = env or getfenv(2)
local name = (env.script and env.script:GetFullName())
local ran,error = pcall(function()
local zio = luaZ:init(luaZ:make_getS(str), nil)
if not zio then return error() end
local func = luaY:parser(LuaState, zio, nil, name or "Plugin_Env")
writer, buff = luaU:make_setS()
luaU:dump(LuaState, func, writer, buff)
f = rerubi(buff.data, env)
end)
if ran then
return f,buff.data
else
return nil,error
end
end |
if mods['Krastorio2'] then
data:extend({
-- -- Basic science
{
type = "bool-setting",
name = "k2-automation-science-pack",
default_value = true,
setting_type = "startup",
order = "AA-AA-S1"
},
-- K2 extended science packs
{
type = "bool-setting",
name = "basic-tech-card",
default_value = true,
hidden = true,
forced_value = true,
setting_type = "startup",
order = "KK-K2-S1"
},
{
type = "bool-setting",
name = "matter-tech-card",
default_value = true,
setting_type = "startup",
order = "KK-K2-S2"
},
{
type = "bool-setting",
name = "advanced-tech-card",
default_value = true,
setting_type = "startup",
order = "KK-K2-S3"
},
{
type = "bool-setting",
name = "singularity-tech-card",
default_value = true,
setting_type = "startup",
order = "KK-K2-S4"
}
})
end |
--- === plugins.core.macosshortcuts ===
---
--- Adds actions for macOS Monterey Shortcuts.
local require = require
--local log = require "hs.logger".new "macosshortcuts"
local shortcuts = require "hs.shortcuts"
local image = require "hs.image"
local config = require "cp.config"
local i18n = require "cp.i18n"
local imageFromPath = image.imageFromPath
local mod = {}
local plugin = {
id = "core.macosshortcuts",
group = "core",
dependencies = {
["core.action.manager"] = "actionmanager",
}
}
function plugin.init(deps)
--------------------------------------------------------------------------------
-- Setup Action Handler:
--------------------------------------------------------------------------------
local icon = imageFromPath(config.basePath .. "/plugins/core/macosshortcuts/images/Shortcuts.icns")
local actionmanager = deps.actionmanager
mod._handler = actionmanager.addHandler("global_macosshortcuts", "global")
:onChoices(function(choices)
local shortcutsList = shortcuts.list()
local description = i18n("macOSShortcutsDescriptions")
for _, item in pairs(shortcutsList) do
choices
:add(item.name)
:subText(description)
:params({
name = item.name,
id = item.id,
})
:id("global_macosshortcuts_" .. item.name)
:image(icon)
end
end)
:onExecute(function(action)
local name = action.name
if name then
shortcuts.run(name)
end
end)
:onActionId(function(params)
return "global_macosshortcuts_" .. params.name
end)
return mod
end
return plugin
|
function onCreate()
-- background shit
makeLuaSprite('bg', 'bg', -500, -300);
setLuaSpriteScrollFactor('bg', 0.9, 0.9);
makeLuaSprite('ground', 'ground', -650, 600);
setLuaSpriteScrollFactor('ground', 0.9, 0.9);
scaleObject('ground', 1.1, 1.1);
-- sprites that only load if Low Quality is turned off
if not lowQuality then
makeLuaSprite('rock', 'rock', -500, -300);
setLuaSpriteScrollFactor('rock', 1.3, 1.3);
scaleObject('rock', 0.9, 0.9);
end
addLuaSprite('bg', false);
addLuaSprite('ground', false);
addLuaSprite('rock', false);
close(true); --For performance reasons, close this script once the stage is fully loaded, as this script won't be used anymore after loading the stage
end |
registerNpc(111, {
walk_speed = 180,
run_speed = 520,
scale = 95,
r_weapon = 0,
l_weapon = 0,
level = 37,
hp = 26,
attack = 165,
hit = 107,
def = 106,
res = 68,
avoid = 59,
attack_spd = 100,
is_magic_damage = 0,
ai_type = 21,
give_exp = 47,
drop_type = 150,
drop_money = 20,
drop_item = 58,
union_number = 58,
need_summon_count = 0,
sell_tab0 = 0,
sell_tab1 = 0,
sell_tab2 = 0,
sell_tab3 = 0,
can_target = 0,
attack_range = 220,
npc_type = 1,
hit_material_type = 1,
face_icon = 0,
summon_mob_type = 0,
quest_type = 0,
height = 0
});
registerNpc(915, {
walk_speed = 180,
run_speed = 410,
scale = 120,
r_weapon = 0,
l_weapon = 0,
level = 53,
hp = 2109,
attack = 168,
hit = 127,
def = 184,
res = 80,
avoid = 61,
attack_spd = 100,
is_magic_damage = 0,
ai_type = 166,
give_exp = 0,
drop_type = 3,
drop_money = 0,
drop_item = 100,
union_number = 100,
need_summon_count = 31,
sell_tab0 = 31,
sell_tab1 = 0,
sell_tab2 = 0,
sell_tab3 = 0,
can_target = 0,
attack_range = 250,
npc_type = 0,
hit_material_type = 1,
face_icon = 0,
summon_mob_type = 0,
quest_type = 0,
height = 0
});
function OnInit(entity)
return true
end
function OnCreate(entity)
return true
end
function OnDelete(entity)
return true
end
function OnDead(entity)
end
function OnDamaged(entity)
end |
--
-- Created by IntelliJ IDEA.
-- User: xinzhang
-- Date: 10/08/2017
-- Time: 11:59 PM
-- To change this template use File | Settings | File Templates.
--
SUMMER_START = 5;
SUMMER_END = 8;
|
local modpath = minetest.get_modpath("ks_metals")
dofile(modpath.."/nodes.lua")
dofile(modpath.."/smelting.lua")
|
local originX = SCREEN_CENTER_X;
local originY = SCREEN_CENTER_Y+82;
local textbanner = 30;
local spacing = 31;
local numcharts = 18;
local voffset = 0;
local paneLabels = {"Taps","Jumps","Holds","Hands","Mines","Other"};
local t = Def.ActorFrame{
OnCommand=cmd(stoptweening;diffusealpha,0;sleep,0.5;linear,0.2;diffusealpha,1);
MusicWheelMessageCommand=function(self,param) if param and param.Direction then voffset = 0; end; end;
StateChangedMessageCommand=function(self)
self:stoptweening();
self:decelerate(0.2);
if Global.state == "GroupSelect" then
self:diffusealpha(0);
else
self:diffusealpha(1);
end
end;
StepsChangedMessageCommand=function(self,param)
if param and param.Player then
local newoffset = 0;
local newindex = Global.pnsteps[param.Player];
while newindex > numcharts do
newoffset = newoffset + 1
newindex = newindex - numcharts
end;
if(newoffset ~= voffset) then
voffset = newoffset
self:playcommand("MusicWheel");
end
end;
end;
};
--//================================================================
function StepsController(self,param)
if param.Player then
if param.Input == "Prev" and param.Button == "Left" then
Global.confirm[param.Player] = 0;
MESSAGEMAN:Broadcast("Deselect");
if #Global.steps > 1 then
Global.pnsteps[param.Player] = Global.pnsteps[param.Player]-1;
if Global.pnsteps[param.Player] < 1 then Global.pnsteps[param.Player] = #Global.steps; end;
Global.pncursteps[param.Player] = Global.steps[Global.pnsteps[param.Player]];
MESSAGEMAN:Broadcast("StepsChanged", { Prev = true , Player = param.Player });
end
end;
if param.Input == "Next" and param.Button == "Right" then
Global.confirm[param.Player] = 0;
MESSAGEMAN:Broadcast("Deselect");
if #Global.steps > 1 then
Global.pnsteps[param.Player] = Global.pnsteps[param.Player]+1;
if Global.pnsteps[param.Player] > #Global.steps then Global.pnsteps[param.Player] = 1; end;
Global.pncursteps[param.Player] = Global.steps[Global.pnsteps[param.Player]];
MESSAGEMAN:Broadcast("StepsChanged", { Next = true , Player = param.Player });
end;
end;
end;
if param.Input == "Cancel" or param.Input == "Back" and Global.level == 2 then
Global.confirm[PLAYER_1] = 0;
Global.confirm[PLAYER_2] = 0;
if Global.prevstate == "MusicWheel" then
Global.level = 2;
Global.selection = 2;
MESSAGEMAN:Broadcast("MainMenu");
Global.selection = SetWheelSelection();
Global.state = "MusicWheel";
else
Global.level = 1;
Global.selection = 3;
Global.state = "MainMenu";
end;
MESSAGEMAN:Broadcast("Deselect");
MESSAGEMAN:Broadcast("StateChanged");
MESSAGEMAN:Broadcast("Return");
end;
end;
--//================================================================
function SelectStep(param)
if param then Global.confirm[param.Player] = 1;
MESSAGEMAN:Broadcast("StepsSelected");
if Global.confirm[PLAYER_1] + Global.confirm[PLAYER_2] >= GAMESTATE:GetNumSidesJoined() then
Global.level = 1;
Global.state = "MainMenu";
Global.selection = 4;
Global.confirm[PLAYER_1] = 0;
Global.confirm[PLAYER_2] = 0;
MESSAGEMAN:Broadcast("StateChanged");
MESSAGEMAN:Broadcast("MainMenu");
end;
end;
end;
--//================================================================
t[#t+1] = LoadActor(THEME:GetPathG("","dim"))..{
InitCommand=cmd(diffuse,0.33,0.33,0.33,0.33;y,originY;x,originX;zoomto,640,220;fadeleft,0.33;faderight,0.33;croptop,0.5);
};
t[#t+1] = LoadActor(THEME:GetPathG("","stepspane"))..{
InitCommand=cmd(animate,false;setstate,1+3;y,originY;x,originX;zoomto,(spacing*numcharts),0.425*self:GetHeight();diffusebottomedge,1,1,1,1);
StateChangedMessageCommand=function(self) self:stoptweening(); self:linear(0.2); if Global.state ~= "SelectSteps" then self:diffusebottomedge(1,1,1,1); else self:diffusebottomedge(0.5,0.5,0.5,1); end; end;
};
t[#t+1] = LoadActor(THEME:GetPathG("","stepspane"))..{
InitCommand=cmd(animate,false;setstate,0+3;horizalign,right;y,originY;x,originX-((spacing*numcharts)/2);zoom,0.425;diffusebottomedge,1,1,1,1);
StateChangedMessageCommand=function(self) self:stoptweening(); self:linear(0.2); if Global.state ~= "SelectSteps" then self:diffusebottomedge(1,1,1,1); else self:diffusebottomedge(0.5,0.5,0.5,1); end; end;
};
t[#t+1] = LoadActor(THEME:GetPathG("","stepspane"))..{
InitCommand=cmd(animate,false;setstate,2+3;horizalign,left;y,originY;x,originX+((spacing*numcharts)/2);zoom,0.425;diffusebottomedge,1,1,1,1);
StateChangedMessageCommand=function(self) self:stoptweening(); self:linear(0.2); if Global.state ~= "SelectSteps" then self:diffusebottomedge(1,1,1,1); else self:diffusebottomedge(0.5,0.5,0.5,1); end; end;
};
for pn in ivalues(GAMESTATE:GetHumanPlayers()) do
--//==========================================
--// RADAR VALUES
--//==========================================
local iconspacing = 36;
local iconadjust = 24;
local radaritems = 5;
local panespacing = 300;
for num=0,radaritems do
--// radar item
t[#t+1] = Def.ActorFrame{
InitCommand=cmd(y,SCREEN_CENTER_Y+112;x,SCREEN_CENTER_X+(panespacing*pnSide(pn));draworder,num);
OnCommand=cmd(visible,SideJoined(pn));
--// ICONS ==================
Def.Sprite{
Texture = THEME:GetPathG("","radar");
InitCommand=cmd(zoom,0.375;animate,false;halign,0.5;valign,0.5;diffuse,PlayerColor(pn);y,12;diffusebottomedge,0.2,0.2,0.2,0.5;diffusealpha,0;);
OnCommand=cmd(setstate,self:GetNumStates() > num and num or 0;playcommand,"StateChanged");
StateChangedMessageCommand=function(self)
self:stoptweening();
self:decelerate(0.15);
if Global.state == "SelectSteps" then
self:diffusealpha(0.5);
else
self:diffusealpha(0);
end;
if pn == PLAYER_1 then
self:x((num*iconspacing)+iconadjust);
elseif pn == PLAYER_2 then
self:x((-radaritems*iconspacing)+(num*iconspacing)-iconadjust);
end;
end;
};
--// LABELS ==================
Def.BitmapText{
Font = Fonts.radar["Label"];
InitCommand=cmd(zoomx,0.31;zoomy,0.3;halign,0.5;valign,0.5;diffuse,PlayerColor(pn);strokecolor,BoostColor(PlayerColor(pn),0.3);vertspacing,-30.9;diffusealpha,0);
OnCommand=cmd(playcommand,"StateChanged");
StateChangedMessageCommand=function(self)
self:stoptweening();
self:decelerate(0.15);
if Global.state == "SelectSteps" then
self:y(32);
self:diffusealpha(1);
else
self:y(28);
self:diffusealpha(0);
end;
if pn == PLAYER_1 then
self:x((num*iconspacing)+iconadjust);
elseif pn == PLAYER_2 then
self:x((-radaritems*iconspacing) + (num*iconspacing)-iconadjust);
end;
self:settext(string.upper((num+1) <= #paneLabels and paneLabels[num+1] or ""));
end;
};
--// NUMBERS ==================
Def.BitmapText{
Font = Fonts.radar["Number"];
InitCommand=cmd(zoomx,0.425;zoomy,0;halign,0.5;valign,0.5;maxwidth,72;diffusealpha,0);
OnCommand=cmd(playcommand,"StateChanged");
StateChangedMessageCommand=function(self)
self:stoptweening();
self:decelerate(0.15);
if Global.state == "SelectSteps" then
self:zoomy(0.45);
self:diffusealpha(1);
else
self:zoomy(0);
self:diffusealpha(0);
end;
if pn == PLAYER_1 then
self:x((num*iconspacing)+iconadjust);
elseif pn == PLAYER_2 then
self:x((-radaritems*iconspacing) + (num*iconspacing)-iconadjust);
end;
end;
StepsChangedMessageCommand=function(self)
local value = 0;
if GAMESTATE:IsSideJoined(pn) and Global.pncursteps[pn] then
value = GetRadar(Global.steps[Global.pnsteps[pn]],pn,num+1);
end;
self:y(20);
self:settext(string.rep("0",3-string.len(value))..value);
if value == 0 then
self:diffusetopedge(1,0.5,0.5,1);
self:diffusebottomedge(0.5,0.5,0.5,1);
self:strokecolor(0.3,0.175,0.175,0.8);
else
self:diffusetopedge(1,1,1,1);
self:diffusebottomedge(BoostColor(PlayerColor(pn),1.5));
self:strokecolor(BoostColor(PlayerColor(pn,0.8),0.25))
end;
end;
};
};
end;
--//==========================================
--// SCORES
--//==========================================
-- personal
local score_width = 112;
local score_height = 0.35;
local score_size = 0.35;
local score_pos = originY + 42;
-- personal
local hs_p = Def.ActorFrame{
InitCommand=cmd(x,_screen.cx - 12;y,score_pos;diffusealpha,0);
StateChangedMessageCommand=function(self)
self:stoptweening();
self:decelerate(Global.state == "SelectSteps" and 0.3 or 0.15);
self:x(Global.state == "SelectSteps" and _screen.cx or _screen.cx - 12);
self:diffusealpha(Global.state == "SelectSteps" and 1 or 0);
end;
LoadActor(THEME:GetPathG("","litepane"))..{
InitCommand=cmd(zoomto,score_width,score_height*self:GetHeight();animate,false;setstate,1)
},
LoadActor(THEME:GetPathG("","litepane"))..{
InitCommand=cmd(zoom,score_height;x,-score_width/2;horizalign,right;animate,false;setstate,0);
},
LoadActor(THEME:GetPathG("","litepane"))..{
InitCommand=cmd(zoom,score_height;x,score_width/2;horizalign,left;animate,false;setstate,2);
},
LoadActor(THEME:GetPathG("","separator"))..{
InitCommand=cmd(zoom,0.3;diffuse,0.1,0.1,0.1,1);
OnCommand=cmd(visible,GAMESTATE:GetNumSidesJoined() > 1);
},
Def.BitmapText{
Font = Fonts.radar["Label"];
Text = string.upper("Personal Best");
InitCommand=cmd(zoomx,0.31;zoomy,0.3;diffuse,HighlightColor();strokecolor,BoostColor(HighlightColor(),0.3);y,-18);
},
};
-- machine
local hs_m = Def.ActorFrame{
InitCommand=cmd(x,_screen.cx + 12;y,score_pos+22);
StateChangedMessageCommand=function(self)
self:stoptweening();
self:decelerate(Global.state == "SelectSteps" and 0.3 or 0.15);
self:x(Global.state == "SelectSteps" and _screen.cx or _screen.cx + 12);
self:diffusealpha(Global.state == "SelectSteps" and 1 or 0);
end;
LoadActor(THEME:GetPathG("","litepane"))..{
InitCommand=cmd(zoomto,score_width,score_height*self:GetHeight();animate,false;setstate,1)
},
LoadActor(THEME:GetPathG("","litepane"))..{
InitCommand=cmd(zoom,score_height;x,-score_width/2;horizalign,right;animate,false;setstate,0);
},
LoadActor(THEME:GetPathG("","litepane"))..{
InitCommand=cmd(zoom,score_height;x,score_width/2;horizalign,left;animate,false;setstate,2);
},
LoadActor(THEME:GetPathG("","separator"))..{
InitCommand=cmd(zoom,0.3;diffuse,0.1,0.1,0.1,1);
OnCommand=cmd(visible,GAMESTATE:GetNumSidesJoined() > 1);
},
Def.BitmapText{
Font = Fonts.radar["Label"];
Text = string.upper("Machine Best");
InitCommand=cmd(zoomx,0.31;zoomy,0.3;diffuse,HighlightColor();strokecolor,BoostColor(HighlightColor(),0.3);y,18);
},
};
local grade_size = 0.1;
for pn in ivalues(GAMESTATE:GetHumanPlayers()) do
if SideJoined(pn) then
--[[
-- personal best grade
hs_p[#hs_p+1] = Def.Sprite{
UpdateScoresMessageCommand=function(self)
local song = Global.song or GAMESTATE:GetCurrentSong();
local steps = Global.pncursteps[pn] or GAMESTATE:GetCurrentSteps(pn);
local hs = GetTopScoreForProfile(song,steps,PROFILEMAN:GetProfile(pn));
local grade = nil;
if hs then
if IsGame("pump") then
grade = PIUHighScoreGrade(hs);
grade = FormatGradePIU(grade);
else
grade = hs:GetGrade();
grade = FormatGrade(grade);
end;
end;
self:Load(grade and THEME:GetPathG("","eval/"..string.gsub(grade,"+","").."_normal") or nil);
self:horizalign(pnAlign(OtherPlayer[pn]));
self:diffuse(GradeColor(grade));
self:diffusetopedge(1,1,1,1);
self:diffusealpha(1/3);
self:zoom(grade_size);
end;
};
-- machine best grade
hs_m[#hs_m+1] = Def.Sprite{
UpdateScoresMessageCommand=function(self)
local song = Global.song or GAMESTATE:GetCurrentSong();
local steps = Global.pncursteps[pn] or GAMESTATE:GetCurrentSteps(pn);
local hs = GetTopScoreForProfile(song,steps,PROFILEMAN:GetMachineProfile());
local grade = nil;
if hs then
if IsGame("pump") then
grade = PIUHighScoreGrade(hs);
grade = FormatGradePIU(grade);
else
grade = hs:GetGrade();
grade = FormatGrade(grade);
end;
end;
self:Load(grade and THEME:GetPathG("","eval/"..string.gsub(grade,"+","").."_normal") or nil);
self:horizalign(pnAlign(OtherPlayer[pn]));
self:diffuse(GradeColor(grade));
self:diffusetopedge(1,1,1,1);
self:diffusealpha(1/3);
self:zoom(grade_size);
end;
};
]]
-- personal best dp
hs_p[#hs_p+1] = Def.BitmapText{
Font = Fonts.stepslist["Percentage"];
InitCommand=cmd(x,GAMESTATE:GetNumSidesJoined() == 1 and 0 or (score_width-8) * 0.5 * pnSide(pn);horizalign,GAMESTATE:GetNumSidesJoined() == 1 and center or pnAlign(pn));
OnCommand=cmd(zoomx,score_size;zoomy,score_size);
UpdateScoresMessageCommand=function(self)
local song = Global.song or GAMESTATE:GetCurrentSong();
local steps = Global.pncursteps[pn] or GAMESTATE:GetCurrentSteps(pn);
local hs = GetTopScoreForProfile(song,steps,PROFILEMAN:GetProfile(pn));
self:stoptweening();
self:diffuse(BoostColor(PlayerColor(pn),1));
--self:diffusetopedge(BoostColor(PlayerColor(pn),1.25));
self:strokecolor(BoostColor(PlayerColor(pn,0.75),0.15));
if hs then
self:settext(FormatDP(hs:GetPercentDP()))
self:diffusealpha(1);
else
self:settext("0%");
self:diffusealpha(0.3);
end
end;
};
-- machine best dp
hs_m[#hs_m+1] = Def.BitmapText{
Font = Fonts.stepslist["Percentage"];
InitCommand=cmd(x,GAMESTATE:GetNumSidesJoined() == 1 and 0 or (score_width-8) * 0.5 * pnSide(pn);horizalign,GAMESTATE:GetNumSidesJoined() == 1 and center or pnAlign(pn));
OnCommand=cmd(zoomx,score_size;zoomy,score_size);
UpdateScoresMessageCommand=function(self)
local song = Global.song or GAMESTATE:GetCurrentSong();
local steps = Global.pncursteps[pn] or GAMESTATE:GetCurrentSteps(pn);
local hs = GetTopScoreForProfile(song,steps,PROFILEMAN:GetMachineProfile());
self:stoptweening();
self:diffuse(0.6,0.6,0.6,1);
--self:diffusetopedge(0.85,0.85,0.85,1);
self:strokecolor(0.1,0.1,0.1,1);
if hs then
self:settext(FormatDP(hs:GetPercentDP()))
self:diffusealpha(1);
else
self:settext("0%");
self:diffusealpha(0.3);
end
end;
};
end;
end;
t[#t+1] = hs_p;
t[#t+1] = hs_m;
--//==========================================
--// CURSOR
--//==========================================
t[#t+1] = Def.ActorFrame{
InitCommand=cmd(playcommand,"StepsChanged");
OnCommand=cmd(visible,SideJoined(pn));
StateChangedMessageCommand=cmd(playcommand,"StepsChanged");
StepsChangedMessageCommand=function(self)
if GAMESTATE:IsSideJoined(pn) then
local index = 1;
self:stoptweening();
self:decelerate(0.15);
if Global.pnsteps[pn] then
index = Global.pnsteps[pn];
if index > numcharts then
index = index % numcharts
end
end;
self:x((originX)+(spacing*(index-1))-((numcharts/2)*spacing)+(spacing/2));
self:y(originY);
end;
end;
LoadActor(THEME:GetPathG("","cursor"))..{
InitCommand=cmd(spin;effectmagnitude,0,0,720;animate,false;zoom,0.475;rotationy,20;rotationx,-50;x,-1;blend,Blend.Add;diffusealpha,0;);
StateChangedMessageCommand=function(self,param)
self:stoptweening();
if param and (param.Prev or param.Next) and param.Player == pn then
self:linear(0.2);
end;
if Global.state ~= "SelectSteps" or not GAMESTATE:IsSideJoined(pn) then
self:diffusealpha(0);
else
self:diffusealpha(1);
end;
end;
OnCommand=function(self)
if pn == PLAYER_1 then
self:setstate(1);
elseif pn == PLAYER_2 then
self:setstate(3);
end;
end;
};
LoadActor(THEME:GetPathG("","label"))..{
InitCommand=cmd(animate,false;zoom,0.36;diffusealpha,0);
OnCommand=cmd(playcommand,"StepsChanged");
StateChangedMessageCommand=cmd(playcommand,"StepsChanged");
StepsChangedMessageCommand=function(self,param)
if GAMESTATE:IsSideJoined(pn) then
local index = 1;
self:stoptweening();
if param and (param.Prev or param.Next) and param.Player == pn then
self:decelerate(0.275);
end;
if Global.state ~= "SelectSteps" or not GAMESTATE:IsSideJoined(pn) then
self:diffusealpha(0)
else
self:diffusealpha(1);
end;
if pn == PLAYER_1 then
self:setstate(0);
self:x(-12);
self:y(-11);
elseif pn == PLAYER_2 then
self:setstate(1);
self:x(11);
self:y(12);
end;
end;
end;
};
};
end;
for i=1,numcharts do
t[#t+1] = Def.BitmapText{
Font = Fonts.stepslist["Main"];
InitCommand=cmd(zoom,0.5;diffuse,1,1,1,0;strokecolor,0,0,0,0.25;y,originY;x,(originX)+(spacing*(i-1))-((numcharts/2)*spacing)+(spacing/2)-1);
OnCommand=cmd(playcommand,"MusicWheel");
MusicWheelMessageCommand=function(self,param)
self:stoptweening();
self:decelerate(0.175);
if param and param.Direction then voffset = 0; end;
local tint;
local offset = voffset * numcharts;
local steps = Global.steps[i + offset];
self:diffuse(1,1,1,1);
self:strokecolor(0,0,0,0.25);
if steps then
local tint = StepsColor(steps);
self:diffuse(tint);
self:diffusetopedge(BoostColor(tint,9));
self:strokecolor(BoostColor(tint,0.25));
if TotalNotes(steps) == 0 then
self:settext("00");
else
self:settext(FormatMeter(steps:GetMeter()));
end
else
self:settext("00");
self:diffusealpha(0.1);
end;
self:x((originX)+(spacing*(i-1))-((numcharts/2)*spacing)+(spacing/2)-1);
end;
};
t[#t+1] = LoadActor(THEME:GetPathG("","separator"))..{
OnCommand=cmd(diffuse,0.1,0.1,0.1,0.9;y,originY+0.5;zoom,0.25;queuecommand,"MusicWheel");
MusicWheelMessageCommand=function(self)
self:x((originX)+(spacing*(i-1))-((numcharts/2)*spacing)+(spacing/2)+14);
if i<numcharts then self:visible(true) else self:visible(false); end;
end;
};
end;
return t |
----------------------------------------------------------------------------------------------------
-- skada module
--
--if Skada its not present, dont use this module
if not IsAddOnLoaded( "Skada" ) then return; end
--get the engine and create the module
local Engine = select(2,...);
local mod = Engine.AddOn:NewModule("skada");
--debug
local debug = Engine.AddOn:GetModule("debug");
--toggle skada window
function mod.Toggle()
local Skada = _G.Skada;
Skada:ToggleWindow();
end
--get sum table
function mod.GetSumtable(tablename, mode)
--get skada
local Skada = _G.Skada;
--default values
local totalsum=0;
local totalpersec=0;
local sumtable={};
local report_set = nil;
--get the set
if(tablename==Engine.CURRENT_DATA) then
report_set = Skada:find_set("current");
elseif(tablename==Engine.OVERALL_DATA) then
report_set = Skada:find_set("total");
end
if(report_set) then
-- For each item in dataset
local nr = 1;
local templable = {};
for i, player in ipairs(report_set.players) do
if player.id then
--get the data from the player
templable = {enclass=player.class,name=player.name,damage=player.damage or 0,healing=player.healing or 0,dps=0,hps=0};
--get the player active time
local totaltime = Skada:PlayerActiveTime(report_set, player) or 0;
--calculate hps or dps
if (mode==Engine.TYPE_DPS) then
if (templable.damage>0) then
templable.dps = templable.damage / math.max(1,totaltime);
totalsum = totalsum + templable.damage;
totalpersec = totalpersec + templable.dps;
--insert the player
table.insert(sumtable,templable);
end
else
if (templable.healing>0) then
templable.hps = templable.healing / math.max(1,totaltime);
totalsum = totalsum + templable.healing;
totalpersec = totalpersec + templable.hps;
--insert the player
table.insert(sumtable,templable);
end
end
end
end
end
--return values
return sumtable, totalsum, totalpersec;
end
--return segment name
function mod.GetSegmentName()
--return skada
local Skada = _G.Skada;
--find the set
local report_set = Skada:find_set("current");
--get the name
if(report_set) then
if (report_set.mobname) then
return report_set.mobname;
else
if (report_set.name) then
return report_set.name;
else
return "";
end
end
else
return "";
end
end
--initialize module
function mod:OnInitialize()
--get the generic meter
mod.meter = Engine.AddOn:GetModule("meter");
---register the damage meter
mod.meter:RegisterMeter("Skada",mod.GetSumtable,mod.GetSegmentName,mod.Toggle);
end |
object_mobile_chief_olum = object_mobile_shared_chief_olum:new {
}
ObjectTemplates:addTemplate(object_mobile_chief_olum, "object/mobile/chief_olum.iff")
|
--Codeforces plugin
local botAPI, discord, pluginName, pluginPath, pluginDir = ...
local plugin = {}
--== Plugin Meta ==--
plugin.name = "Codeforces" --The visible name of the plugin
plugin.icon = ":bar_chart:" --The plugin icon to be shown in the help command
plugin.version = "V0.0.1" --The visible version string of the plugin
plugin.description = "Useful commands for Codeforces users." --The description of the plugin
plugin.author = "Rami#8688" --Usually the discord tag of the author, but could be anything else
plugin.authorEmail = "ramilego4game@gmail.com" --The email of the auther, could be left empty
--== Commands ==--
plugin.commands = {}; local commands = plugin.commands
do
local usageEmbed = discord.embed()
usageEmbed:setTitle("cf_contests")
usageEmbed:setDescription("Work in progress :warning:")
local function compareContests(c1, c2)
if c1.relativeTimeSeconds < 0 and c2.relativeTimeSeconds < 0 then
return c1.relativeTimeSeconds > c2.relativeTimeSeconds
elseif c1.relativeTimeSeconds >= 0 and c2.relativeTimeSeconds >= 0 then
return c1.relativeTimeSeconds < c2.relativeTimeSeconds
else
return c1.relativeTimeSeconds < 0
end
end
function commands.cf_contests(message, reply, commandName, ...)
if commandName == "?" then reply:send(false, usageEmbed) return end --Triggered using the help command
reply:triggerTypingIndicator()
local data, err = discord.utilities.http.request("https://codeforces.com/api/contest.list")
if not data then error(err) end
if data.status ~= "OK" then error(discord.json:encode_pretty(data)) end
local contests = {}
for _, contest in ipairs(data.result) do
if math.abs(contest.relativeTimeSeconds) <= 24*3600 then
table.insert(contests, contest)
end
end
table.sort(contests, compareContests)
local replyEmbed = discord.embed()
replyEmbed:setAuthor("Codeforces", "https://codeforces.com", "https://cdn.discordapp.com/attachments/667745243717828663/699234756843274260/favicon.png")
replyEmbed:setTitle("Available contests (24-hours filtered)")
for i=1, math.min(#contests, 25) do
local contest = contests[i]
local remainingTime = math.abs(contest.relativeTimeSeconds)
remainingTime = string.format("%d:%d:%d",
math.floor(remainingTime/3600),
math.floor(remainingTime/60)%60,
remainingTime%60
)
local duration = string.format("%dh %dm %ds",
math.floor(contest.durationSeconds/3600),
math.floor(contest.durationSeconds/60)%60,
contest.durationSeconds%60
)
replyEmbed:setField(i, contest.name,
string.format(
table.concat({
"URL: https://codeforces.com/contest/%d",
"ID: `%d`",
"Phase: `%s`",
"Frozen: `%s`",
contest.relativeTimeSeconds < 0 and "Until start: `%s`" or "Since start: `%s`",
"Duration: `%s`"
}, "\n"),
contest.id,
contest.id,
contest.phase,
tostring(contest.frozen),
remainingTime,
duration
)
)
end
reply:send(false, replyEmbed)
end
end
return plugin |
--每个服务进程都有一个唯一的服务标识,由服务分组(group)和服务索引(index)两部分构成
--有三种形式:
--servcie_id(string): 2.1
--service_id(number): 131073
--service_name: lobby.1
--在上面的示例中,服务id 2.1中的2表明服务分组(group)为2(lobby),实例编号(index)为1
service_groups =
{
router = 1,
gateway = 2,
lobby = 3,
dbagent = 4,
indexsvr = 5,
mailsvr = 6,
};
service_names =
{
[service_groups.router] = "router",
[service_groups.gateway] = "gateway",
[service_groups.lobby] = "lobby",
[service_groups.dbagent] = "dbagent",
[service_groups.indexsvr] = "indexsvr",
[service_groups.mailsvr] = "mailsvr",
};
service_timeout_value = 5; --通道超时时间,同时也是master租约超时时间
function make_service_id(group, index)
return (group << 16) | index;
end
function get_service_group(id)
return id >> 16;
end
function get_service_index(id)
return id & 0xff;
end
function service_id2str(id)
local group = id >> 16;
local index = id & 0xff;
local fmt = "%s.%s";
return fmt:format(group, index);
end
function service_str2id(str)
local pos = str:find(".");
local group = str:sub(1, pos - 1);
local index = str.sub(pos + 1, #str);
return make_service_id(tonumber(group), tonumber(index));
end
function service_id2name(id)
if id == nil or id == 0 then
return "nil";
end
local group = id >> 16;
local index = id & 0xff;
local fmt = "%s.%s";
return fmt:format(service_names[group], index);
end
|
assets =
{
Asset("ANIM", "anim/cook_pot_food.zip"),
}
local function fn()
local inst = CreateEntity()
inst.entity:AddTransform()
inst.entity:AddAnimState()
MakeInventoryPhysics(inst)
inst.AnimState:SetBuild("cook_pot_food")
inst.AnimState:SetBank("food")
inst.AnimState:PlayAnimation("bonestew", false)
inst:AddTag("meat")
inst:AddComponent("edible")
inst.components.edible.ismeat = true
inst.components.edible.foodtype = "MEAT"
local damage = GetPlayer().components.health.maxhealth
inst.components.edible.healthvalue = -damage
inst:AddComponent("inspectable")
inst:AddComponent("inventoryitem")
inst.components.inventoryitem:ChangeImageName("bonestew")
return inst
end
return Prefab("common/inventory/deadlyfeast", fn, assets)
|
---
--- Generated by MLN Team (https://www.immomo.com)
--- Created by MLN Team.
--- DateTime: 15-01-2020 17:35
---
---
--- 缓存策略
---
---@link https://www.immomo.comCachePolicy.html
---@class CachePolicy @parent class
---@public field name string
---@type CachePolicy
CachePolicy = {
---
--- 缓存策略
---
CACHE_ONLY = "value",
---
--- 缓存策略
---
REFRESH_CACHE_BY_API = "value",
---
--- 缓存策略
---
API_ONLY = "value",
---
--- 缓存策略
---
CACHE_THEN_API = "value",
---
--- 缓存策略
---
CACHE_OR_API = "value"
} |
if UseItem(186) == true then goto label0 end;
do return end;
::label0::
AddItem(186, -1);
Talk(73, "据说”飞雪连天射白鹿,笑书神侠倚碧鸳”这十四字各是那”十四天书”书名的第一个字.你可以此为线索去找.", "talkname73", 0);
Add3EventNum(-2, 0, 0, 701, -1)
do return end;
|
--[[
Copyright 2021 Manticore Games, Inc.
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.
--]]
-- Custom Properties
local vehicle = script:GetCustomProperty("Vehicle"):WaitForObject()
local vehicleServer = script:GetCustomProperty("VehicleServer"):WaitForObject()
local runningLightsOn = script:GetCustomProperty("RunningLightsOn"):WaitForObject()
local runningLightsOff = script:GetCustomProperty("RunningLightsOff"):WaitForObject()
local headLightsOn = script:GetCustomProperty("HeadLightsOn"):WaitForObject()
local headlightsOff = script:GetCustomProperty("HeadlightsOff"):WaitForObject()
local tailLightsOn = script:GetCustomProperty("TailLightsOn"):WaitForObject()
local tailLightsOff = script:GetCustomProperty("TailLightsOff"):WaitForObject()
local reverseLightsOn = script:GetCustomProperty("ReverseLightsOn"):WaitForObject()
local reverseLightsOff = script:GetCustomProperty("ReverseLightsOff"):WaitForObject()
local leftSignalOn = script:GetCustomProperty("LeftSignalOn"):WaitForObject()
local leftSignalOff = script:GetCustomProperty("LeftSignalOff"):WaitForObject()
local rightSignalOn = script:GetCustomProperty("RightSignalOn"):WaitForObject()
local rightSignalOff = script:GetCustomProperty("RightSignalOff"):WaitForObject()
local turnSignalSFX = script:GetCustomProperty("TurnSignalSFX"):WaitForObject()
local lightToggleSFX = script:GetCustomProperty("LightToggleSFX"):WaitForObject()
local hornSFX = script:GetCustomProperty("HornSFX"):WaitForObject()
local lockSFX = script:GetCustomProperty("LockSFX"):WaitForObject()
-- Local Variables
local timeTracker = 0
local signalInAnimation = false
local function SwapVisibility(objectOne, objectTwo, toggle)
if toggle then
if Object.IsValid(objectOne) then
objectOne.visibility = Visibility.INHERIT
end
if Object.IsValid(objectTwo) then
objectTwo.visibility = Visibility.FORCE_OFF
end
else
if Object.IsValid(objectOne) then
objectOne.visibility = Visibility.FORCE_OFF
end
if Object.IsValid(objectTwo) then
objectTwo.visibility = Visibility.INHERIT
end
end
end
-- Function that honks the horn, toggles the lights, toggles the daytime running lights, or plays the lock sound effect
-- based on custom properties from VehiclePack_MkE_VehicleServer script.
function OnPropertyChanged(vehicleScript, property)
local value = vehicleScript:GetCustomProperty(property)
if property == "HornToggle" then
if value then
hornSFX:Play()
end
elseif property == "LightsToggle" then
SwapVisibility(headLightsOn, headlightsOff, value)
if Object.IsValid(lightToggleSFX) then
lightToggleSFX:Play()
end
elseif property == "ActiveToggle" then
SwapVisibility(runningLightsOn, runningLightsOff, value)
elseif property == "VehicleLock" then
lockSFX:Play()
end
end
function ToggleLeftSignal()
signalInAnimation = true
SwapVisibility(leftSignalOn, leftSignalOff, true)
if Object.IsValid(turnSignalSFX) then
turnSignalSFX:Play()
end
Task.Wait(0.5)
SwapVisibility(leftSignalOn, leftSignalOff, false)
Task.Wait(0.5)
signalInAnimation = false
end
function ToggleRightSignal()
signalInAnimation = true
SwapVisibility(rightSignalOn, rightSignalOff, true)
if Object.IsValid(turnSignalSFX) then
turnSignalSFX:Play()
end
Task.Wait(0.5)
SwapVisibility(rightSignalOn, rightSignalOff, false)
Task.Wait(0.5)
signalInAnimation = false
end
function ToggleHazardSignal()
signalInAnimation = true
SwapVisibility(leftSignalOn, leftSignalOff, true)
SwapVisibility(rightSignalOn, rightSignalOff, true)
if Object.IsValid(turnSignalSFX) then
turnSignalSFX:Play()
end
Task.Wait(0.5)
SwapVisibility(leftSignalOn, leftSignalOff, false)
SwapVisibility(rightSignalOn, rightSignalOff, false)
Task.Wait(0.5)
signalInAnimation = false
end
-- Tick function that controls the reverse lights, tail lights, and turn signals based on vehicle movement and turn signal state
-- from VehiclePack_MkE_VehicleServer script.
function Tick(dt)
if vehicle.isBrakeEngaged or vehicle.isHandbrakeEngaged then
SwapVisibility(tailLightsOn, tailLightsOff, true)
else
SwapVisibility(tailLightsOn, tailLightsOff, false)
end
local reversing = vehicleServer:GetCustomProperty("Reversing")
if reversing then
SwapVisibility(reverseLightsOn, reverseLightsOff, true)
else
SwapVisibility(reverseLightsOn, reverseLightsOff, false)
end
local turnSignalState = vehicleServer:GetCustomProperty("TurnSignalState")
if not signalInAnimation then
if turnSignalState == 1 then
Task.Spawn(ToggleLeftSignal, 0)
elseif turnSignalState == 2 then
Task.Spawn(ToggleRightSignal, 0)
elseif turnSignalState == -1 then
Task.Spawn(ToggleHazardSignal, 0)
end
end
end
-- Initialization
vehicleServer.networkedPropertyChangedEvent:Connect(OnPropertyChanged)
|
local nvim_lsp = require('lspconfig')
local cmp = require('cmp')
-- Set hidden https://github.com/neovim/nvim-lspconfig/issues/426
vim.opt.hidden = true
-- AutoComplete
-- Set completeopt to have a better completion experience
vim.o.completeopt = 'menuone,noselect'
cmp.setup({
snippet = {
expand = function(args)
vim.fn["vsnip#anonymous"](args.body) -- For `vsnip` users.
end,
},
mapping = {
['<C-p>'] = cmp.mapping.select_prev_item(),
['<C-n>'] = cmp.mapping.select_next_item(),
['<C-d>'] = cmp.mapping.scroll_docs(-4),
['<C-f>'] = cmp.mapping.scroll_docs(4),
['<C-Space>'] = cmp.mapping.complete(),
['<C-e>'] = cmp.mapping.close(),
['<Enter>'] = cmp.mapping.confirm {
behavior = cmp.ConfirmBehavior.Replace,
select = true,
},
['<Tab>'] = cmp.mapping(cmp.mapping.select_next_item(), { 'i', 's'}),
['<S-Tab>'] = cmp.mapping(cmp.mapping.select_prev_item(), { 'i', 's'}),
},
sources = cmp.config.sources({
{ name = 'nvim_lsp' },
{ name = 'vsnip' },
}, {
{ name = 'buffer' },
})
})
-- Use an on_attach function to only map the following keys
-- after the language server attaches to the current buffer
local on_attach = function(client, bufnr)
local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end
local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end
-- Enable completion triggered by <c-x><c-o>
buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc')
-- Mappings.
-- See `:help vim.lsp.*` for documentation on any of the below functions
local opts = { noremap=true, silent=true }
buf_set_keymap('n', 'gD', '<cmd>lua vim.lsp.buf.declaration()<CR>', opts)
buf_set_keymap('n', 'gd', '<cmd>lua vim.lsp.buf.definition()<CR>', opts)
buf_set_keymap('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts)
buf_set_keymap('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts)
buf_set_keymap('n', 'K', '<cmd>lua vim.lsp.buf.hover()<CR>', opts)
buf_set_keymap('n', '<leader>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts)
buf_set_keymap('n', '<leader>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts)
buf_set_keymap('n', '<leader>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts)
buf_set_keymap('n', '<leader>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts)
buf_set_keymap('n', '<leader>D', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts)
buf_set_keymap('n', '<leader>ca', '<cmd>lua vim.lsp.buf.code_action()<CR>', opts)
buf_set_keymap('n', '<leader>e', '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>', opts)
buf_set_keymap('n', '[d', '<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>', opts)
buf_set_keymap('n', ']d', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', opts)
buf_set_keymap('n', '<leader>q', '<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>', opts)
buf_set_keymap('n', '<leader>f', '<cmd>lua vim.lsp.buf.formatting()<CR>', opts)
end
-- Use a loop to conveniently call 'setup' on multiple servers and
-- map buffer local keybindings when the language server attaches
local servers = {
'rust_analyzer',
'tsserver',
'pylsp'
}
for _, lsp in ipairs(servers) do
nvim_lsp[lsp].setup {
on_attach = on_attach,
flags = {
debounce_text_changes = 150,
},
capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities())
}
end
|
local log = require 'utils.log'
local skynet = require 'skynet'
return function(target)
local ping_service = skynet.newservice('hwtest_ping')
local r, err = skynet.call(ping_service, 'lua', 'ping', target)
if r then
log.debug("PING "..target.." OK")
else
log.debug("PING "..target.." FAILED", err)
end
skynet.call(ping_service, 'lua', 'exit')
return r, err
end
|
-- 3D Transport test with Vacuum and Incident-isotropic BC.
-- SDM: PWLD
-- Test: Nonce
num_procs = 4
--############################################### Check num_procs
if (check_num_procs==nil and chi_number_of_processes ~= num_procs) then
chiLog(LOG_0ERROR,"Incorrect amount of processors. " ..
"Expected "..tostring(num_procs)..
". Pass check_num_procs=false to override if possible.")
os.exit(false)
end
--############################################### Setup mesh
chiMeshHandlerCreate()
newSurfMesh = chiSurfaceMeshCreate();
chiSurfaceMeshImportFromOBJFile(newSurfMesh,
"ChiResources/TestObjects/SquareMesh2x2QuadsBlock.obj",true)
region1 = chiRegionCreate()
chiSurfaceMesherCreate(SURFACEMESHER_PREDEFINED);
chiVolumeMesherCreate(VOLUMEMESHER_EXTRUDER,
ExtruderTemplateType.SURFACE_MESH,
newSurfMesh);
NZ=1
chiVolumeMesherSetProperty(EXTRUSION_LAYER,10.0,NZ,"Charlie");--10.0
chiVolumeMesherSetProperty(EXTRUSION_LAYER,10.0,NZ,"Charlie");--20.0
chiVolumeMesherSetProperty(EXTRUSION_LAYER,10.0,NZ,"Charlie");--30.0
chiVolumeMesherSetProperty(EXTRUSION_LAYER,10.0,NZ,"Charlie");--40.0
chiVolumeMesherSetKBAPartitioningPxPyPz(2,2,1)
chiVolumeMesherSetKBACutsX({0.0})
chiVolumeMesherSetKBACutsY({0.0})
chiVolumeMesherSetProperty(PARTITION_TYPE,KBA_STYLE_XYZ)
chiSurfaceMesherExecute();
chiVolumeMesherExecute();
--############################################### Set Material IDs
vol0 = chiLogicalVolumeCreate(RPP,-1000,1000,-1000,1000,-1000,1000)
chiVolumeMesherSetProperty(MATID_FROMLOGICAL,vol0,0)
vol1 = chiLogicalVolumeCreate(RPP,-10.0,10.0,-10.0,10.0,-1000,1000)
chiVolumeMesherSetProperty(MATID_FROMLOGICAL,vol1,1)
--############################################### Add materials
materials = {}
materials[1] = chiPhysicsAddMaterial("Test Material");
materials[2] = chiPhysicsAddMaterial("Test Material2");
chiPhysicsMaterialAddProperty(materials[1],TRANSPORT_XSECTIONS)
chiPhysicsMaterialAddProperty(materials[2],TRANSPORT_XSECTIONS)
--chiPhysicsMaterialAddProperty(materials[1],ISOTROPIC_MG_SOURCE)
chiPhysicsMaterialAddProperty(materials[2],ISOTROPIC_MG_SOURCE)
num_groups = 168
chiPhysicsMaterialSetProperty(materials[1],TRANSPORT_XSECTIONS,
CHI_XSFILE,"ChiTest/xs_graphite_pure.cxs")
chiPhysicsMaterialSetProperty(materials[2],TRANSPORT_XSECTIONS,
CHI_XSFILE,"ChiTest/xs_air50RH.cxs")
src={}
for g=1,num_groups do
src[g] = 0.0
end
--chiPhysicsMaterialSetProperty(materials[1],ISOTROPIC_MG_SOURCE,FROM_ARRAY,src)
chiPhysicsMaterialSetProperty(materials[2],ISOTROPIC_MG_SOURCE,FROM_ARRAY,src)
chiPhysicsMaterialSetProperty(materials[2],ISOTROPIC_MG_SOURCE,FROM_ARRAY,src)
--############################################### Setup Physics
phys1 = chiLBSCreateSolver()
chiSolverAddRegion(phys1,region1)
chiLBSSetProperty(phys1,DISCRETIZATION_METHOD,PWLD)
chiLBSSetProperty(phys1,SCATTERING_ORDER,1)
--========== Groups
grp = {}
for g=1,num_groups do
grp[g] = chiLBSCreateGroup(phys1)
end
--========== ProdQuad
pquad0 = chiCreateProductQuadrature(GAUSS_LEGENDRE_CHEBYSHEV,2, 2,false)
pquad1 = chiCreateProductQuadrature(GAUSS_LEGENDRE_CHEBYSHEV,8, 8,false)
--========== Groupset def
gs0 = chiLBSCreateGroupset(phys1)
cur_gs = gs0
chiLBSGroupsetAddGroups(phys1,cur_gs,0,62)
chiLBSGroupsetSetQuadrature(phys1,cur_gs,pquad0)
chiLBSGroupsetSetAngleAggDiv(phys1,cur_gs,1)
chiLBSGroupsetSetGroupSubsets(phys1,cur_gs,1)
chiLBSGroupsetSetIterativeMethod(phys1,cur_gs,NPT_GMRES)
chiLBSGroupsetSetResidualTolerance(phys1,cur_gs,1.0e-4)
chiLBSGroupsetSetMaxIterations(phys1,cur_gs,5)
chiLBSGroupsetSetGMRESRestartIntvl(phys1,cur_gs,30)
chiLBSGroupsetSetWGDSA(phys1,cur_gs,30,1.0e-2)
-- chiLBSGroupsetSetTGDSA(phys1,cur_gs,30,1.0e-4,false," ")
gs1 = chiLBSCreateGroupset(phys1)
cur_gs = gs1
chiLBSGroupsetAddGroups(phys1,cur_gs,63,num_groups-1)
chiLBSGroupsetSetQuadrature(phys1,cur_gs,pquad0)
chiLBSGroupsetSetAngleAggDiv(phys1,cur_gs,1)
chiLBSGroupsetSetGroupSubsets(phys1,cur_gs,1)
chiLBSGroupsetSetIterativeMethod(phys1,cur_gs,NPT_GMRES)
chiLBSGroupsetSetResidualTolerance(phys1,cur_gs,1.0e-4)
chiLBSGroupsetSetMaxIterations(phys1,cur_gs,5)
chiLBSGroupsetSetGMRESRestartIntvl(phys1,cur_gs,30)
chiLBSGroupsetSetWGDSA(phys1,cur_gs,30,1.0e-2,false," ")
chiLBSGroupsetSetTGDSA(phys1,cur_gs,30,1.0e-6,false," ")
--############################################### Set boundary conditions
bsrc={}
for g=1,num_groups do
bsrc[g] = 0.0
end
bsrc[1] = 1.0/4.0/math.pi;
--bsrc[1] = 1.0
chiLBSSetProperty(phys1,BOUNDARY_CONDITION,XMIN,LBSBoundaryTypes.INCIDENT_ISOTROPIC,bsrc);
--chiLBSSetProperty(phys1,BOUNDARY_CONDITION,XMAX,INCIDENT_ISOTROPIC,bsrc);
--chiLBSSetProperty(phys1,BOUNDARY_CONDITION,YMIN,INCIDENT_ISOTROPIC,bsrc);
--chiLBSSetProperty(phys1,BOUNDARY_CONDITION,YMAX,INCIDENT_ISOTROPIC,bsrc);
--chiLBSSetProperty(phys1,BOUNDARY_CONDITION,ZMIN,INCIDENT_ISOTROPIC,bsrc);
--chiLBSSetProperty(phys1,BOUNDARY_CONDITION,ZMAX,INCIDENT_ISOTROPIC,bsrc);
--############################################### Initialize and Execute Solver
chiLBSInitialize(phys1)
chiLBSExecute(phys1)
--############################################### Get field functions
fflist,count = chiLBSGetScalarFieldFunctionList(phys1)
--############################################### Exports
if (master_export == nil) then
chiExportFieldFunctionToVTKG(fflist[1],"ZPhi","Phi")
end
--############################################### Plots
|
local THREAD_FILE_NAME = (...):gsub("%.", "/") .. "/thread.lua"
local current = (...)
local load
load = function(path)
local succ, loaded = pcall(require, path)
if not (succ) then
local LC_PATH = current .. '.' .. path
succ, loaded = pcall(require, LC_PATH)
if not (succ) then
LC_PATH = current:gsub("%.[^%..]+$", "") .. '.' .. path
succ, loaded = pcall(require, LC_PATH)
if not (succ) then
error(loaded)
end
end
end
return loaded
end
local loaders = load('loaders')
local getExt
getExt = function(name)
return name:match("[^.]+$")
end
local channelNum = 0
local cache = { }
local new
new = function(path)
local CHANNEL_NAME = "load-channel-" .. channelNum
channelNum = channelNum + 1
local thread = love.thread.newThread(THREAD_FILE_NAME)
local channel = love.thread.getChannel(CHANNEL_NAME)
local ext = getExt(path)
thread:start(path, ext, CHANNEL_NAME, current)
local loader = loaders[ext]
assert(loader, 'Not found loader for format "' .. ext .. '"!')
local data
return function()
if not (data) then
local err = thread:getError()
if err then
error(err)
end
data = channel:pop()
if data then
data = loader.master(data)
else
return false
end
end
return data
end
end
local asset
asset = function(path)
if cache[path] then
return cache[path]()
else
cache[path] = new(path)
return cache[path]()
end
end
local fonts = { }
local sep = love.timer.getTime() * 2
local font
font = function(path, size)
local name = path .. sep .. size
if (fonts[name] == nil) or (fonts[name] == false) then
fonts[name] = asset(path)
return false
elseif type(fonts[name]) == 'function' then
fonts[name] = fonts[name](size)
end
return fonts[name]
end
local obj = {
asset = asset,
font = font
}
local mt = setmetatable(obj, {
__call = function(self, ...)
return asset(...)
end
})
return mt
|
local MemAdmin = require "memadmin"
mem_user_admin = MemAdmin.new("tb_user", "id")
mem_player_admin = MemAdmin.new("tb_player", "playerid")
mem_deskplayer_admin = MemAdmin.new("tb_desk_player", "id")
mem_desk_admin = MemAdmin.new("tb_desk", "deskid")
mem_arena_admin = MemAdmin.new("tb_arena_template", "arenaid")
|
--This class acts as a pipe between the incoming messages and commands.
--It observes the content of the incoming messages, and, depending on the optional flags,
--executes specific commands
--Remember: there can only be one command handler and plugin handler
--per a server handler. Side effects of using multiple command handlers and
--plugin handlers are unknown.
local class = import("classes.baseclass")
local command_handler = class("Command-handler")
local table_utils = import("table-utils")
local purify = import("purify")
function command_handler:__init(parent_server)
self.server_handler = assert(parent_server,"parent server handler not provided")
self.command_pool = {}
self.prefixes = {}
end
function command_handler:add_prefix(prefix)
local purified_prefix = purify.purify_escapes(prefix)
self.prefixes[purified_prefix] = purified_prefix
end
function command_handler:remove_prefix(prefix)
local purified_prefix = purify.purify_escapes(prefix)
if self.prefixes[purified_prefix] then
self.prefix[purified_prefix] = nil
end
end
function command_handler:get_prefixes()
return table_utils.deepcopy(self.prefixes)
end
function command_handler:add_command(command)
assert(type(command) == "table","command object expected")
local purified_name = purify.purify_escapes(command.name)
self.command_pool[purified_name] = command
end
function command_handler:remove_command(command)
assert(type(command) == "table","command object expected")
local purified_name = purify.purify_escapes(command.name)
if self.command_pool[purified_name] then
self.command_pool[purified_name] = nil
end
end
function command_handler:handle(message)
for name,command in pairs(self.command_pool) do
if command.options.regex then
if message.content:match(command.options.regex) then
command:exec(message)
return
end
else
if command.options.prefix then
for _,prefix in pairs(self.prefixes) do
if message.content:find(prefix..name.."$") == 1 or message.content:find(prefix..name.."%s") then
command:exec(message)
return
end
end
else
if message.content:find(name.."$") == 1 or message.content:find(name.."%s") then
command:exec(message)
return
end
end
end
end
end
return command_handler
|
--[=[
Utility functions primarily used to bind animations into update loops of the Roblox engine.
@class StepUtils
]=]
local HttpService = game:GetService("HttpService")
local RunService = game:GetService("RunService")
local StepUtils = {}
--[=[
Binds the given update function to render stepped.
```lua
local spring = Spring.new(0)
local maid = Maid.new()
local startAnimation, maid._stopAnimation = StepUtils.bindToRenderStep(function()
local animating, position = SpringUtils.animating(spring)
print(position)
return animating
end)
spring.t = 1
startAnimation()
```
:::tip
Be sure to call the disconnect function when cleaning up, otherwise you may memory leak.
:::
@param update () -> boolean -- should return true while it needs to update
@return (...) -> () -- Connect function
@return () -> () -- Disconnect function
]=]
function StepUtils.bindToRenderStep(update)
return StepUtils.bindToSignal(RunService.RenderStepped, update)
end
--[=[
Binds an update event to a signal until the update function stops returning a truthy
value.
@param signal Signal | RBXScriptSignal
@param update () -> boolean -- should return true while it needs to update
@return (...) -> () -- Connect function
@return () -> () -- Disconnect function
]=]
function StepUtils.bindToSignal(signal, update)
if typeof(signal) ~= "RBXScriptSignal" then
error("signal must be of type RBXScriptSignal")
end
if type(update) ~= "function" then
error(("update must be of type function, got %q"):format(type(update)))
end
local conn = nil
local function disconnect()
if conn then
conn:Disconnect()
conn = nil
end
end
local function connect(...)
-- Ignore if we have an existing connection
if conn and conn.Connected then
return
end
-- Check to see if we even need to bind an update
if not update(...) then
return
end
-- Avoid reentrance, if update() triggers another connection, we'll already be connected.
if conn and conn.Connected then
return
end
-- Usually contains just the self arg!
local args = {...}
-- Bind to render stepped
conn = signal:Connect(function()
if not update(unpack(args)) then
disconnect()
end
end)
end
return connect, disconnect
end
--[=[
Calls the function once at the given priority level, unless the cancel callback is
invoked.
@param priority number
@param func function -- Function to call
@return function -- Call this function to cancel call
]=]
function StepUtils.onceAtRenderPriority(priority, func)
assert(type(priority) == "number", "Bad priority")
assert(type(func) == "function", "Bad func")
local key = ("StepUtils.onceAtPriority_%s"):format(HttpService:GenerateGUID(false))
local function cleanup()
RunService:UnbindFromRenderStep(key)
end
RunService:BindToRenderStep(key, priority, function()
cleanup()
func()
end)
return cleanup
end
--[=[
Invokes the function once at stepped, unless the cancel callback is called.
```lua
-- Sometimes you need to defer the execution of code to make physics happy
maid:GiveTask(StepUtils.onceAtStepped(function()
part.CFrame = CFrame.new(0, 0, )
end))
```
@param func function -- Function to call
@return function -- Call this function to cancel call
]=]
function StepUtils.onceAtStepped(func)
return StepUtils.onceAtEvent(RunService.Stepped, func)
end
--[=[
Invokes the function once at renderstepped, unless the cancel callback is called.
@param func function -- Function to call
@return function -- Call this function to cancel call
]=]
function StepUtils.onceAtRenderStepped(func)
return StepUtils.onceAtEvent(RunService.RenderStepped, func)
end
--[=[
Invokes the function once at the given event, unless the cancel callback is called.
@param event Signal | RBXScriptSignal
@param func function -- Function to call
@return function -- Call this function to cancel call
]=]
function StepUtils.onceAtEvent(event, func)
assert(type(func) == "function", "Bad func")
local conn
local function cleanup()
if conn then
conn:Disconnect()
conn = nil
end
end
conn = event:Connect(function(...)
cleanup()
func(...)
end)
return cleanup
end
return StepUtils |
--- Generated XboxOneDark with Python
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local Spritesheet = require("Spritesheet")
local XboxOneDark = setmetatable({}, Spritesheet)
XboxOneDark.ClassName = "XboxOneDark"
XboxOneDark.__index = XboxOneDark
function XboxOneDark.new()
local self = setmetatable(Spritesheet.new("rbxassetid://5089898851"), XboxOneDark)
self:AddSprite("DPad", Vector2.new(0, 0), Vector2.new(100, 100))
self:AddSprite(Enum.KeyCode.ButtonA, Vector2.new(100, 0), Vector2.new(100, 100))
self:AddSprite(Enum.KeyCode.ButtonB, Vector2.new(200, 0), Vector2.new(100, 100))
self:AddSprite(Enum.KeyCode.ButtonL1, Vector2.new(300, 0), Vector2.new(100, 100))
self:AddSprite(Enum.KeyCode.ButtonL2, Vector2.new(400, 0), Vector2.new(100, 100))
self:AddSprite(Enum.KeyCode.ButtonR1, Vector2.new(500, 0), Vector2.new(100, 100))
self:AddSprite(Enum.KeyCode.ButtonR2, Vector2.new(600, 0), Vector2.new(100, 100))
self:AddSprite(Enum.KeyCode.ButtonSelect, Vector2.new(700, 0), Vector2.new(100, 100))
self:AddSprite(Enum.KeyCode.ButtonX, Vector2.new(800, 0), Vector2.new(100, 100))
self:AddSprite(Enum.KeyCode.ButtonY, Vector2.new(900, 0), Vector2.new(100, 100))
self:AddSprite(Enum.KeyCode.DPadDown, Vector2.new(0, 100), Vector2.new(100, 100))
self:AddSprite(Enum.KeyCode.DPadLeft, Vector2.new(100, 100), Vector2.new(100, 100))
self:AddSprite(Enum.KeyCode.DPadRight, Vector2.new(200, 100), Vector2.new(100, 100))
self:AddSprite(Enum.KeyCode.DPadUp, Vector2.new(300, 100), Vector2.new(100, 100))
self:AddSprite(Enum.KeyCode.Menu, Vector2.new(400, 100), Vector2.new(100, 100))
self:AddSprite(Enum.KeyCode.Thumbstick2, Vector2.new(500, 100), Vector2.new(100, 100))
self:AddSprite(Enum.KeyCode.Thumbstick1, Vector2.new(600, 100), Vector2.new(100, 100))
return self
end
return XboxOneDark |
world =
{
entitys =
{
[0] = "scripts/test.lua",
[1] = "scripts/stickman.lua",
[2] = "scripts/ground.lua"
}
} |
return {
summary = 'Get the depth of the Texture.',
description = 'Returns the depth of the Texture, or the number of images stored in the Texture.',
arguments = {
{
name = 'mipmap',
type = 'number',
default = '1',
description = 'The mipmap level to get the depth of. This is only valid for volume textures.'
}
},
returns = {
{
name = 'depth',
type = 'number',
description = 'The depth of the Texture.'
}
}
}
|
--[[ only for debug
table_print = require('table_print')
table.print = table_print.print_r
--]]
-- 打印警告信息
function printWarn(text)
print("\nModerncv Warning!\n" .. text .. "\nPlease Check\n\n")
end
-- 获取一个table的所有text
function getText(content)
local newcontent = ""
if type(content) ~= "table" then
return newcontent
end
for k,v in pairs(content) do
if v.t == "Strong" then
newcontent = newcontent .. "\\textbf{" .. getText(v) .. "}"
elseif v.t == "Code" then
newcontent = newcontent .. "\\passthrough{\\lstinline!" .. v.text .. "!}"
elseif v.t == "Space" then
newcontent = newcontent .. " "
elseif v.text ~= nil then
newcontent = newcontent .. v.text
else
newcontent = newcontent .. getText(v)
end
end
return newcontent
end
function setAttr(attr)
if attr == nil then
return ""
else
return attr
end
end
function citeproc(cite, meta)
local newcite = pandoc.Div({}, cite.attr)
local rawend = "\\par %"
if meta.style == "fancy" then
rawend = "}"
end
for k,v in pairs(cite.content) do
if v.t == "Div" then
if meta.style == "fancy" then
table.insert(newcite.content, pandoc.RawBlock("latex", "\\cvlistitem{"))
end
table.insert(newcite.content, v)
table.insert(newcite.content, pandoc.RawBlock("latex", rawend))
elseif v.t == "Header" and v.level == 1 then
table.insert(newcite.content, pandoc.RawBlock("latex", "\\section{" .. getText(v.content) .. "}"))
else
end
end
return newcite
end
-- 一级标题后的列表转为cvlistitem
-- 此函数可能可以优化,不需要getText,定义一个空的Div table,把元素加进去更好
function cvlist(list)
local nlist = pandoc.Div({})
for k,v in pairs(list.content) do
local spanCount = 0
local item = pandoc.Plain({})
local comment = pandoc.Plain({})
local cat = {}
local double = {}
for i,val in pairs(v[1].content) do
if val.t == "Span" then
spanCount = spanCount + 1
if #val.attr.classes > 0 then
if val.attr.classes[1] == "comment" then
table.insert(comment.content, val)
end
if val.attr.classes[1] == "cat" then
table.insert(cat, getText(val.content))
end
if val.attr.classes[1] == "double" then
table.insert(double, pandoc.Plain({val}))
end
end
else
table.insert(item.content, val)
end
end
-- \cvitemwithcomment 优先级最高
if spanCount == 2 and next(comment.content) ~= nil and #cat > 0 then
table.insert(nlist.content, pandoc.RawBlock("latex", "\\cvitemwithcomment{" .. cat[1] .. "}{"))
table.insert(nlist.content, item)
table.insert(nlist.content, pandoc.RawBlock("latex", "}{"))
table.insert(nlist.content, comment)
table.insert(nlist.content, pandoc.RawBlock("latex", "}"))
elseif spanCount == 1 and #cat == 1 then
table.insert(nlist.content, pandoc.RawBlock("latex", "\\cvitem{" .. cat[1] .. "}{"))
table.insert(nlist.content, item)
table.insert(nlist.content,pandoc.RawBlock("latex","}"))
elseif spanCount >= 2 and #cat >= 1 and #double >= 1 and spanCount < 5 then
table.insert(nlist.content, pandoc.RawBlock("latex", "\\cvdoubleitem{" .. cat[1] .. "}{"))
table.insert(nlist.content, double[1])
table.insert(nlist.content, pandoc.RawBlock("latex", "}{" .. getValue(cat[2], "") .. "}{"))
table.insert(nlist.content, getValue(double[2], pandoc.Plain({})))
table.insert(nlist.content, pandoc.RawBlock("latex", "}"))
elseif spanCount == 2 and #cat == 0 and #double == 2 then
table.insert(nlist.content, pandoc.RawBlock("latex", "\\cvlistdoubleitem{"))
table.insert(nlist.content, double[1])
table.insert(nlist.content, pandoc.RawBlock("latex", "}{"))
table.insert(nlist.content, double[2])
table.insert(nlist.content, pandoc.RawBlock("latex", "}"))
else
table.insert(nlist.content, pandoc.RawBlock("latex", "\\cvlistitem{"))
-- 如果以上都不满足,按普通列表,远样返回
table.insert(nlist.content, v[1])
table.insert(nlist.content, pandoc.RawBlock("latex", "}"))
end
if spanCount > 4 then
printWarn("You use more than 4 bracketed_spans in one list item. May cause unexpect result")
end
end
return nlist
end
function cvcolumns(el)
local nblocks = pandoc.Div({})
table.insert(nblocks.content, pandoc.RawBlock("latex", "\\begin{cvcolumns}"))
for k,v in pairs(el.content) do
if v.t == "Div" and v.attr.classes[1] == "cvcolumn" then
local cat = "Cat"
if v.attr.attributes.cat ~= nil then
cat = v.attr.attributes.cat
end
table.insert(nblocks.content, pandoc.RawBlock("latex", "\\cvcolumn{" .. cat .. "}{"))
for j,val in pairs(v.content) do
table.insert(nblocks.content, val)
end
table.insert(nblocks.content, pandoc.RawBlock("latex", "}"))
else
table.insert(nblocks.content, v)
end
end
table.insert(nblocks.content, pandoc.RawBlock("latex", "\\end{cvcolumns}"))
return nblocks
end
function getValue(v, d)
if v ~= nil then
return v
else
return d
end
end
-- 求职信
local letterMeta = 0 -- recipient, opening, closing 都设置才能添加求职信
function letter(el)
local rawtex = ""
if el.level == 1 then
rawtex = "\n\\clearpage\n\\recipient{" .. getText(el.content) .. "}{" .. getValue(el.attr.attributes.company, "Please set company attr") .. "\\\\" .. getValue(el.attr.attributes.addr, "Please set addr attr") .. "\\\\" .. getValue(el.attr.attributes.city, "Please set city attr") .. "}"
letterMeta = letterMeta + 1
elseif el.attr.classes[2] == "date" then
rawtex = "\\date{" .. getText(el.content) .. "}"
elseif el.attr.classes[2] == "opening" then
rawtex = "\\opening{" .. getText(el.content) .. "}"
letterMeta = letterMeta + 1
elseif el.attr.classes[2] == "closing" then
rawtex = "\\closing{" .. getText(el.content) .. "}"
letterMeta = letterMeta + 1
elseif el.attr.classes[2] == "enclosure" then
rawtex = "\\enclosure[" .. getValue(el.attr.attributes.enclosure, "Enclosure") .. "]{" .. getText(el.content) .. "}"
else
end
return pandoc.RawBlock("latex", rawtex)
end
function cventry(el,meta,bracket)
local entry = pandoc.Plain({})
local dt = pandoc.Str("")
local title = pandoc.Str("")
local tag = pandoc.Str("")
local desc = pandoc.Str("")
for k,v in pairs(el.content) do
if v.t == "Str" then
table.insert(entry.content, v)
elseif v.t == "Span" then
if v.attr.classes[1] == "date" then
dt = v
elseif v.attr.classes[1] == "title" then
title = v
elseif v.attr.classes[1] == "tag" then
tag = v
elseif v.attr.classes[1] == "desc" then
desc = v
else
table.insert(entry.content, v)
end
else
table.insert(entry.content, v)
end
end
entry = pandoc.Str(getText(entry))
local tmp
if meta.style == "banking" then
tmp = entry
entry = title
title = tmp
end
local sep = pandoc.RawInline("latex", "}{")
return pandoc.Plain({
pandoc.RawInline("latex", "\\cventry{"),
dt, sep , entry, sep, title, sep, tag, sep, desc, sep,
pandoc.RawInline("latex", bracket)
})
end
function Pandoc(doc)
local nblocks = {}
local inletter = nil
local letterContent = pandoc.Div({})
table.insert(letterContent.content, pandoc.RawBlock("latex", "\\makelettertitle\n\\setlength{\\parindent}{2em}"))
for i,el in pairs(doc.blocks) do
local addEl = nil
local nel = pandoc.Null()
if el.t == "Header" and el.attr.classes[1] == "letter" then
inletter = true
nel = letter(el)
elseif el.t ~= "Header" and inletter ~= nil then
table.insert(letterContent.content, el)
-- 显式分段 module-cv.sh 中会删除所有空行
if el.t == "Para" then
table.insert(letterContent.content, pandoc.RawBlock("latex", "\\par"))
end
-- 带label的section和subsection会影响fancy样式显示,所以手动转一下
elseif el.t == "Header" and el.level == 1 and inletter == nil then
nel = pandoc.RawBlock("latex", "\\section{" .. getText(el.content) .. "}")
elseif el.t == "Header" and el.level == 2 and inletter == nil then
nel = pandoc.RawBlock("latex", "\\subsection{" .. getText(el.content) .. "}")
elseif el.t == "Header" and el.level == 3 and inletter == nil then
local bracket = ""
if i+1 <= #doc.blocks and doc.blocks[i+1].t ~= "BulletList" then
bracket = "}"
end
if i+1 > #doc.blocks then
bracket = "}"
end
nel = cventry(el, doc.meta, bracket)
elseif el.t == "BulletList" and inletter == nil then
if i > 1 and doc.blocks[i-1].t == "Header" and doc.blocks[i-1].level == 3 then
addEl = pandoc.RawBlock("latex", "}")
nel = el
else
nel = cvlist(el)
end
elseif el.t == "Div" and el.attr.identifier == "refs" and inletter == nil then
nel = citeproc(el, doc.meta)
elseif el.t == "Div" and el.attr.classes[1] == "cvcolumns" and inletter == nil then
nel = cvcolumns(el)
else
nel = el
end
table.insert(nblocks, nel)
if addEl ~= nil then
table.insert(nblocks, addEl)
end
end
table.insert(letterContent.content, pandoc.RawBlock("latex", "\\setlength{\\parindent}{0em}\\makeletterclosing"))
if letterMeta == 3 then
table.insert(nblocks, letterContent)
elseif letterMeta > 0 and letterMeta < 3 then
printWarn("If you want to use letter, you need to provide recipient, opening and closing")
else
end
return pandoc.Pandoc(nblocks, doc.meta)
end |
--[[ Author: Firetoad
Date: 12.05.2017 ]]
if modifier_contributor_statue == nil then
modifier_contributor_statue = class({})
end
function modifier_contributor_statue:CheckState()
local state = {
[MODIFIER_STATE_INVULNERABLE] = true,
[MODIFIER_STATE_NOT_ON_MINIMAP] = true,
[MODIFIER_STATE_NO_HEALTH_BAR] = true,
[MODIFIER_STATE_NO_UNIT_COLLISION] = true,
}
return state
end
function modifier_contributor_statue:GetStatusEffectName()
-- return "particles/ambient/contributor_effigy_fx.vpcf"
end
function modifier_contributor_statue:IsHidden()
return true
end
--[[ Author: EarthSalamander
Date: 04.03.2021 ]]
modifier_contributor_filler = modifier_contributor_filler or class({})
function modifier_contributor_filler:IsHidden() return true end
function modifier_contributor_filler:RemoveOnDeath() return false end
function modifier_contributor_filler:DeclareFunctions() return {
MODIFIER_EVENT_ON_MODEL_CHANGED,
MODIFIER_EVENT_ON_TAKEDAMAGE,
MODIFIER_EVENT_ON_DEATH,
} end
function modifier_contributor_filler:OnCreated()
if not IsServer() then return end
self.model = self:GetParent():GetModelName()
end
function modifier_contributor_filler:OnModelChanged()
-- weird bugfix
self:GetParent():SetModel(self.model)
self:GetParent():SetOriginalModel(self.model)
self:GetParent():StartGesture(ACT_DOTA_IDLE)
end
function modifier_contributor_filler:OnTakeDamage(keys)
if keys.unit == self:GetParent() then
if self:GetParent():GetModelName() ~= self.model then
self:OnModelChanged()
end
end
end
function modifier_contributor_filler:OnDeath(keys)
local player_name = PlayerResource:GetPlayerName(keys.attacker:GetPlayerOwnerID())
if self:GetParent() == keys.unit then
CustomGameEventManager:Send_ServerToPlayer(PlayerResource:GetPlayer(0), "send_effigy_death_message", {
player_name = player_name,
unit_name = self:GetParent():GetUnitName(),
})
if self:GetParent().pedestal and self:GetParent().pedestal:IsAlive() then
self:GetParent().pedestal:ForceKill(false)
end
end
end
|
internet = require("delayedLoad.dlua").new("internetCore.dlua");
Internet = internet;
return internet;
|
--[[
- util.lua
- Handy module containing various functions for game development in lua,
particularly with Love2D.
- Authored by Thomas Smallridge (sundowns)
- https://github.com/sundowns/lua-utils
MIT LICENSE
Copyright (c) 2019 Thomas Smallridge
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.
]]
local meta = {
__index = function(table, key)
if key == "l" then
return rawget(table, "love")
elseif key == "m" then
return rawget(table, "maths")
elseif key == "t" then
return rawget(table, "table")
elseif key == "f" then
return rawget(table, "file")
elseif key == "d" then
return rawget(table, "debug")
elseif key == "s" then
return rawget(table, "string")
elseif key == "g" then
return rawget(table, "generic")
else
return rawget(table, key)
end
end
}
local util = {}
util.love = {}
util.maths = {}
util.table = {}
util.file = {}
util.debug = {}
util.string = {}
util.generic = {}
setmetatable(util, meta)
---------------------- TABLES
function util.table.print(table, depth, name)
print("==================")
if not table then
print("<EMPTY TABLE>")
return
end
if type(table) ~= "table" then
assert(false, "Attempted to print NON-TABLE TYPE: " .. type(table))
return
end
if name then
print("Printing table: " .. name)
end
deepprint(table, 0, depth)
end
function deepprint(table, depth, max_depth)
local d = depth or 0
local max = max_depth or 10
local spacer = ""
for i = 0, d do
spacer = spacer .. " "
end
if d > max then
print(spacer .. "<exceeded max depth (" .. max .. ")>")
return
end
for k, v in pairs(table) do
if type(v) == "table" then
print(spacer .. "[" .. k .. "]:")
deepprint(v, d + 1, max)
else
print(spacer .. "[" .. tostring(k) .. "]: " .. tostring(v))
end
end
end
function util.table.printKeys(table, name)
print("==================")
if not table then
print("<EMPTY TABLE>")
return
end
if type(table) ~= "table" then
assert(false, "Attempted to print keys for NON-TABLE TYPE: " .. type(table))
return
end
for k, v in pairs(table) do
print(k)
end
end
function util.table.concat(t1, t2)
for i = 1, #t2 do
t1[#t1 + 1] = t2[i]
end
return t1
end
-- Recursively creates a copy of the given table.
-- Not my code, taken from: https://www.youtube.com/watch?v=dZ_X0r-49cw#t=9m30s
function util.table.copy(orig)
local orig_type = type(orig)
local copy
if orig_type == "table" then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[util.table.copy(orig_key)] = util.table.copy(orig_value)
end
else
copy = orig
end
return copy
end
--sums two tables of numbers together
function util.table.sum(t1, t2)
local result = {}
for key, val in pairs(t1) do
result[key] = (result[key] or 0) + val
end
for key, val in pairs(t2) do
result[key] = (result[key] or 0) + val
end
return result
end
---------------------- MATHS
function util.maths.roundToNthDecimal(num, n)
local mult = 10 ^ (n or 0)
return math.floor(num * mult + 0.5) / mult
end
function util.maths.withinVariance(val1, val2, variance)
local diff = math.abs(val1 - val2)
if diff < variance then
return true
else
return false
end
end
function util.maths.clamp(val, min, max)
assert(min < max, "Minimum value must be less than maximum when clamping values.")
if min - val > 0 then
return min
end
if max - val < 0 then
return max
end
return val
end
function util.maths.midpoint(x1, y1, x2, y2)
assert(x1 and y1 and x2 and y2, "Received invalid input to util.maths.midpoint")
return (x2 + x1) / 2, (y2 + y1) / 2
end
function util.maths.jitterBy(value, spread)
assert(love, "This function uses love.math.random for the time being")
return value + love.math.random(-1 * spread, spread)
end
--Taken from: https://love2d.org/wiki/HSV_color
function util.maths.HSVtoRGB255(hue, sat, val)
if sat <= 0 then
return val, val, val
end
local h, s, v = hue / 256 * 6, sat / 255, val / 255
local c = v * s
local x = (1 - math.abs((h % 2) - 1)) * c
local m, r, g, b = (v - c), 0, 0, 0
if h < 1 then
r, g, b = c, x, 0
elseif h < 2 then
r, g, b = x, c, 0
elseif h < 3 then
r, g, b = 0, c, x
elseif h < 4 then
r, g, b = 0, x, c
elseif h < 5 then
r, g, b = x, 0, c
else
r, g, b = c, 0, x
end
return (r + m) * 255, (g + m) * 255, (b + m) * 255
end
--Taken from: https://love2d.org/wiki/HSV_color
function util.maths.HSVtoRGB(hue, sat, val)
if sat <= 0 then
return val, val, val
end
local h, s, v = hue / 256 * 6, sat / 255, val / 255
local c = v * s
local x = (1 - math.abs((h % 2) - 1)) * c
local m, r, g, b = (v - c), 0, 0, 0
if h < 1 then
r, g, b = c, x, 0
elseif h < 2 then
r, g, b = x, c, 0
elseif h < 3 then
r, g, b = 0, c, x
elseif h < 4 then
r, g, b = 0, x, c
elseif h < 5 then
r, g, b = x, 0, c
else
r, g, b = c, 0, x
end
return (r + m), (g + m), (b + m)
end
function util.maths.distanceBetween(x1, y1, x2, y2)
return math.sqrt(((x2 - x1) ^ 2) + ((y2 - y1) ^ 2))
end
-- rotation is in radians
function util.maths.rotatePointAroundOrigin(x, y, rotation)
local s = math.sin(rotation)
local c = math.cos(rotation)
return x * c - y * s, x * s + y * c
end
---------------------- DEBUG
function util.debug.log(text)
if debug then
print(text)
end
end
---------------------- FILE
function util.file.exists(name)
if love then
assert(false, "Not to be used in love games, use love.filesystem.getInfo")
end
local f = io.open(name, "r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
function util.file.getLuaFileName(url)
return string.gsub(url, ".lua", "")
end
---------------------- LOVE2D
function util.love.resetColour()
love.graphics.setColor(1, 1, 1, 1)
end
function util.love.resetColor()
love.graphics.setColor(1, 1, 1, 1)
end
function util.love.renderStats(x, y)
if not x then
x = 0
end
if not y then
y = 0
end
local stats = love.graphics.getStats()
love.graphics.print("texture memory (MB): " .. stats.texturememory / 1024 / 1024, x, y)
love.graphics.print("drawcalls: " .. stats.drawcalls, x, y + 20)
love.graphics.print("canvasswitches: " .. stats.canvasswitches, x, y + 40)
love.graphics.print("images loaded: " .. stats.images, x, y + 60)
love.graphics.print("canvases loaded: " .. stats.canvases, x, y + 80)
love.graphics.print("fonts loaded: " .. stats.fonts, x, y + 100)
end
if not love then
util.love = nil
end
---------------------- GENERIC
function util.generic.choose(...)
local args = {...}
return args[math.random(1, #args)]
end
-- To specify weight, include an integer in the table after the option. Defaults to 1.
-- eg. choose_weighted({"choice_1", 5}, {"choice_2", 10})
function util.generic.choose_weighted(...)
local args = {...}
-- technically should be done for all of the list but eh
assert(type(args[1]) == "table", "Options for choose_weighted()")
local weighting_sum = 0
for i, v in pairs(args) do
weighting_sum = weighting_sum + (v[2] or 1)
end
local rand = math.random(weighting_sum)
for i, v in pairs(args) do
if rand <= v[2] then
return args[i][1]
end
rand = rand - v[2]
end
assert("Something went very wrong...")
end
---------------------- STRING
function util.string.randomString(l)
if l < 1 then
return nil
end
local stringy = ""
for i = 1, l do
stringy = stringy .. util.string.randomLetter()
end
return stringy
end
function util.string.randomLetter()
return string.char(math.random(97, 122))
end
return util
|
object_mobile_dressed_restuss_lt_wulf = object_mobile_shared_dressed_restuss_lt_wulf:new {
}
ObjectTemplates:addTemplate(object_mobile_dressed_restuss_lt_wulf, "object/mobile/dressed_restuss_lt_wulf.iff")
|
--[[
@file network.lua
@license The MIT License (MIT)
@author Alex <alex@maximum.guru>
@copyright 2016 Alex
--]]
--- @module network
local network = {}
local bit32 = require("bit32")
local bit128 = require("bit128")
local shell = require("lib.shell")
local shrunner = require("shrunner")
-- There are 3 different representations for IPs
-- 1. internal {192,168,1,1} and ipv6 {255,...........}
-- 2. string "192.168.1.1" and ipv6 "ff..:.........."
-- 3. binary 32-bit-number and ipv6 {32-bit-number, 32-bit-number, 32-bit-number, 32-bit-number}
-- internal representation is used for convenience
-- binary representation is used for binary operations
-- string representation is used for user input/output
-- takes a string and returns a string with an ip that has been standardized
function network.canonicalizeIp(ip)
local n, err = network.parseIp(ip)
if err then return nil, err end
if not n then return nil, "Failed to parse IP" end
return network.ip2string(n), nil
end
-- takes string representation and returns internal representation
function network.parseIp(ip)
if ip == nil then return nil, "IP not specified" end
local data, err = network.parseIpv4(ip)
if err then
data, err = network.parseIpv6(ip)
end
if err then
return nil, "Failed to parse IP: "..err
elseif not data then
return nil, "Failed to parse IP"
end
return data, nil
end
-- takes string representation and returns internal representation and cidr
function network.parseSubnet(subnet)
if subnet == nil then return nil, "Subnet not specified" end
local data, err = network.parseIpv4Subnet(subnet)
if err then
data, err = network.parseIpv6Subnet(subnet)
end
if err then
return nil, "Failed to parse subnet: "..err
elseif not data then
return nil, "Failed to parse subnet"
end
return data, nil
end
-- takes string representation and returns internal representation
function network.parseIpv4(ip)
if ip == nil then return nil, "IP not specified" end
ip = tostring(ip)
local matches = {ip:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$")}
for key,value in pairs(matches) do
matches[key] = tonumber(value)
if 0>matches[key] or matches[key]>255 then
return nil, "Not a valid IPv4"
end
end
if #matches ~= 4 then
return nil, "Not a valid IPv4"
end
return matches, nil
end
-- takes string representation and returns internal representation
function network.parseIpv6(ip)
if ip == nil then return nil, "IP not specified" end
ip = tostring(ip)
local matches = {ip:match("^([0-9a-f]*)(:?)([0-9a-f]*)(:?)([0-9a-f]*)(:?)([0-9a-f]*)(:?)([0-9a-f]*)(:?)([0-9a-f]*)(:?)([0-9a-f]*)(:?)([0-9a-f]*)$")}
if #matches < 3 then
return nil, "Not a valid IPv6 '"..ip.."'"
end
if matches[1] == "" then
matches[1] = "0000"
end
local result = {}
local prev
for key,value in pairs(matches) do
if value ~= ":" and value ~= "" then
if #value > 4 then
return nil, "Failed to parse IPv6 '"..ip.."'"
end
value = string.rep("0", 4-#value)..value
table.insert(result, string.lower(value));
end
if prev then
if prev=="" and value==":" then
break
end
end
prev = value
end
if #result < 8 then
local result2 = {}
prev = nil
local begin = false
for key,value in pairs(matches) do
if begin and value ~= ":" and value ~= "" then
if #value > 4 then
return nil, "Failed to parse IPv6"
end
value = string.rep("0", 4-#value)..value
table.insert(result2, string.lower(value));
end
if prev then
if prev=="" and value==":" then
if begin then
return nil, "Failed to parse IPv6 '"..ip.."'"
end
begin = true
end
end
prev = value
end
for i=#result,(7-#result2) do
table.insert(result,"0000")
end
for key,value in pairs(result2) do
table.insert(result,value)
end
end
local ip = {}
for key,value in pairs(result) do
table.insert(ip,tonumber(string.sub(value,1,2),16))
table.insert(ip,tonumber(string.sub(value,3,4),16))
end
return ip, nil
end
-- takes string representation of ip and cidr and returns internal representation and cidr
function network.parseIpv4Subnet(subnet)
if subnet == nil then return nil, "Subnet not specified" end
local ip, cidr = subnet:match("^(%d+%.%d+%.%d+%.%d+)(/?%d*)$")
if ip == nil and cidr == nil then return nil, "Not a valid subnet" end
if cidr == "" then cidr = "/32" end
if cidr:sub(1,1) ~= "/" then return nil, "Not a valid CIDR" end
cidr = cidr:sub(2)
if #cidr == 0 then return nil, "Not a valid CIDR" end
local ip, err = network.parseIpv4(ip)
if err then
return nil, err
end
cidr = tonumber(cidr)
if 0>cidr or cidr>32 then
return nil, "Not a valid IPv4 subnet cidr"
end
return {ip, cidr}, nil
end
-- takes string representation of ip and cidr and returns internal representation and cidr
function network.parseIpv6Subnet(subnet)
if subnet == nil then return nil, "Subnet not specified" end
local ip, cidr = subnet:match("^([0-9a-f]*:?[0-9a-f]*:?[0-9a-f]*:?[0-9a-f]*:?[0-9a-f]*:?[0-9a-f]*:?[0-9a-f]*:?[0-9a-f]*)(/?%d*)$")
if ip == nil and cidr == nil then return nil, "Not a valid subnet" end
if cidr == "" then cidr = "/128" end
if cidr:sub(1,1) ~= "/" then return nil, "Not a valid CIDR" end
cidr = cidr:sub(2)
if #cidr == 0 then return nil, "Not a valid CIDR" end
local ip, err = network.parseIpv6(ip)
if err then
return nil, err
end
cidr = tonumber(cidr)
if 0>cidr or cidr>128 then
return nil, "Not a valid IPv6 subnet cidr"
end
return {ip, cidr}, nil
end
-- takes internal representation and returns string representation
function network.ip2string(ip)
local v6 = #ip > 4
if v6 then
local str = ""
for i=0,7 do
local segment1 = string.format("%x",ip[i*2+1])
segment1 = string.rep("0", 2-#segment1)..segment1
local segment2 = string.format("%x",ip[i*2+2])
segment2 = string.rep("0", 2-#segment2)..segment2
str = str..string.lower(segment1..segment2)
if i < 7 then
str = str..":"
end
end
return str
else
local a1, a2, a3, a4 = unpack(ip)
return a1.."."..a2.."."..a3.."."..a4;
end
end
-- takes internal representation and returns binary representation
function network.ip2binary(ip)
local v6 = #ip > 4
if v6 then
local bin = {}
for i=0,3 do
table.insert(bin, network.ip2binary({ip[i*4+1],ip[i*4+2],ip[i*4+3],ip[i*4+4]}))
end
return bin
else
local bin = 0;
bin = bit32.bor(bin,ip[1])
bin = bit32.lshift(bin,8)
bin = bit32.bor(bin,ip[2])
bin = bit32.lshift(bin,8)
bin = bit32.bor(bin,ip[3])
bin = bit32.lshift(bin,8)
bin = bit32.bor(bin,ip[4])
return bin
end
end
-- takes binary representation and returns internal representation
function network.binaryToIp(bin)
if type(bin) == "table" then
local ipv6 = {}
for i=1,4 do
local segment = network.binaryToIp(bin[i])
for key,value in pairs(segment) do
table.insert(ipv6, value)
end
end
return ipv6
else
local a1, a2, a3, a4
a4 = bit32.band(0xFF,bin)
bin = bit32.rshift(bin,8)
a3 = bit32.band(0xFF,bin)
bin = bit32.rshift(bin,8)
a2 = bit32.band(0xFF,bin)
bin = bit32.rshift(bin,8)
a1 = bit32.band(0xFF,bin)
return {a1, a2, a3, a4};
end
end
-- takes cidr and returns binary representation of subnet mask
function network.Ipv4cidrToBinaryMask(cidr)
return bit32.lshift(bit32.bnot(0), 32-cidr)
end
-- takes cidr and returns binary representation of subnet mask
function network.Ipv6cidrToBinaryMask(cidr)
return bit128.lshift(bit128.bnot({0,0,0,0}), 128-cidr)
end
function network.getInterface(ifname)
local ipv4subnets, err = network.getInterfaceIpv4subnets(ifname)
if err then return nil, err end
local ipv6subnets, err = network.getInterfaceIpv6subnets(ifname)
if err then return nil, err end
return { ["name"] = ifname, ["ipv4subnets"] = ipv4subnets, ["ipv6subnets"] = ipv6subnets }, nil
end
function network.getInterfaces()
local procnetdev, err = io.open("/proc/net/dev", "r")
if err then
return nil, err
end
local ifs = {}
for l in procnetdev:lines() do
local ifname = string.match(string.lower(l), "^%s*(%w+):")
if ifname then
local iface, err = network.getInterface(ifname)
if iface then ifs[ifname] = iface end
end
end
procnetdev:close()
return ifs, nil
end
function network.getInterfaceIpv4subnets(interface)
interface = string.lower(interface)
local ipcmd = shrunner.popen(shell.escape({"ip", "addr", "show", interface}), 'r')
if not ipcmd then
return nil, "Failed to get IPv4 address for interface "..interface
end
local subnets = {}
for l in ipcmd:lines() do
local subnet = string.match(string.lower(l), "^%s*inet%s+(%d+%.%d+%.%d+%.%d+/%d+)%s")
if subnet then
local subnet, err = network.parseIpv4Subnet(subnet)
if not err and subnet then table.insert(subnets, subnet) end
end
end
ipcmd:close()
return subnets, nil
end
function network.getInterfaceIpv6subnets(interface)
interface = string.lower(interface)
local procnetif, err = io.open("/proc/net/if_inet6")
if err then
return nil, err
end
local subnets = {}
local ifs = {}
for l in procnetif:lines() do
local addr, cidr, iface = string.match(string.lower(l), "^([0-9a-f]+)%s[0-9a-f]+%s([0-9a-f]+)%s.*%s(%w+)$")
if addr and cidr and iface == interface then
local ipv6 = {}
for i=0,15 do table.insert(ipv6, tonumber(addr:sub(i*2+1,i*2+2),16)) end
table.insert(subnets, {ipv6, tonumber(cidr, 16)})
end
end
procnetif:close()
return subnets, nil
end
-- returns subnet prefix address
function network.subnetAddr(subnet)
local ip, cidr = unpack(subnet)
local v6 = #ip > 4
ip = network.ip2binary(ip);
if v6 then
return network.binaryToIp(bit128.band(ip, network.Ipv6cidrToBinaryMask(cidr)))
else
return network.binaryToIp(bit32.band(ip, network.Ipv4cidrToBinaryMask(cidr)))
end
end
function network.compareSubnet(subnet1, subnet2)
local ip1, cidr1 = unpack(subnet1)
local ip2, cidr2 = unpack(subnet2)
if #ip1 ~= #ip2 then return false end
if cidr1 ~= cidr2 then return false end
return network.ip2string(network.subnetAddr(subnet1)) == network.ip2string(network.subnetAddr(subnet2))
end
function network.isIpInSubnet(ip, subnet)
local prefixip, cidr = unpack(subnet)
return network.compareSubnet({ip, cidr}, subnet)
end
function network.getInterfaceBySubnet(subnet)
local ip, cidr = unpack(subnet)
local v6 = #ip > 4
local interfaces, err = network.getInterfaces()
if err then
return nil, err
end
for name,interface in pairs(interfaces) do
local ifsubnets
if v6 then
ifsubnets = interface.ipv6subnets
else
ifsubnets = interface.ipv4subnets
end
for k,ifsubnet in pairs(ifsubnets) do
if network.compareSubnet(ifsubnet, subnet) then
return interface, nil
end
end
end
return nil, nil
end
function network.getIpv4TransitInterface()
local ipcmd = shrunner.popen("ip route show", 'r')
if not ipcmd then
return nil, "Failed to get routing table"
end
for l in ipcmd:lines() do
local interface = string.match(string.lower(l), "^default%s.*dev%s([^%s]+)%s")
if interface then
ipcmd:close()
local iface, err = network.getInterface(interface)
if iface then return iface, nil end
end
end
ipcmd:close()
return nil, nil
end
function network.getIpv6TransitInterface()
local ipcmd = shrunner.popen("ip -6 route show", 'r')
if not ipcmd then
return nil, "Failed to get routing table"
end
for l in ipcmd:lines() do
local interface = string.match(string.lower(l), "^default%s.*dev%s([^%s]+)%s")
if interface then
ipcmd:close()
local iface, err = network.getInterface(interface)
if iface then return iface, nil end
end
end
ipcmd:close()
return nil, nil
end
function network.ping(addr)
local ip, err = network.parseIp(addr)
if err then return nil, err end
local v6 = #ip > 4
if v6 then
return network.ping6(addr)
else
return network.ping4(addr)
end
end
function network.ping4(addr)
for k,i in pairs({1,2,3}) do
local ipcmd = shrunner.popen(shell.escape({"ping", "-c", i, "-s", 0, "-W", 1, addr}), 'r')
if not ipcmd then
return nil, "Failed to execute ping"
end
local pings = nil
local works = false
for l in ipcmd:lines() do
local loss = string.match(string.lower(l), "%s(%d+)%%%s.*loss")
if loss then
works = true
if tonumber(loss) < 100 then
pings = true
break
else
pings = false
break
end
end
end
ipcmd:close()
if not works then
return nil, "Failed to determine the number of packets received pinging "..addr
end
if pings then return true, nil end
end
return false, nil
end
function network.ping6(addr)
for k,i in pairs({1,2,3}) do
local ipcmd = shrunner.popen(shell.escape({"ping6", "-c", i, "-s", 0, "-W", 1, addr}), 'r')
if not ipcmd then
return nil, "Failed to execute ping"
end
local pings = nil
local works = false
for l in ipcmd:lines() do
local loss = string.match(string.lower(l), "%s(%d+)%%%s.*loss")
if loss then
works = true
if tonumber(loss) < 100 then
pings = true
break
else
pings = false
break
end
end
end
ipcmd:close()
if not works then
return nil, "Failed to determine the number of packets received pinging "..addr
end
if pings then return true, nil end
end
return false, nil
end
function network.setIpv4Forwading(value)
local ipforward, err = io.open("/proc/sys/net/ipv4/ip_forward", "w")
if err then
return nil, err
end
ipforward:write(tostring(value))
ipforward:close()
-- TODO: determine if this is needed
--local cmd = shell.escape({"iptables","--append","FORWARD","-j","DROP"})
--local retval = shrunner.execute(cmd)
--if retval ~= 0 then
-- return nil, "iptables failed"
--end
return true, nil
end
function network.setIpv6Forwading(value)
local ipforward, err = io.open("/proc/sys/net/ipv6/conf/all/forwarding", "w")
if err then
return nil, err
end
ipforward:write(tostring(value))
ipforward:close()
-- TODO: determine if this is needed
--local cmd = shell.escape({"ip6tables","--append","FORWARD","-j","DROP"})
--local retval = shrunner.execute(cmd)
--if retval ~= 0 then
-- return nil, "iptables failed"
--end
return true, nil
end
-- takes a string, returns boolean
function network.isAuthorizedIp(ip)
local ip, err = network.parseIp(ip)
if err then return nil, err end
local v6 = #ip > 4
for subnetStr in string.gmatch(config.daemon.authorizedNetworks, ",?([^,]+),?") do
local subnet, err = network.parseSubnet(subnetStr)
if err then return nil, "Failed to parse authorizedNetworks setting in config: "..err end
if network.isIpInSubnet(ip, subnet) then
return true, nil
end
end
return false, nil
end
function network.setInterfaceIp(interface, subnet)
local ip, cidr = unpack(subnet)
ip = network.ip2string(ip)
cidr = tostring(cidr)
local cmd = shell.escape({"ip", "addr", "add", ip.."/"..cidr, "dev", interface.name})
local retval = shrunner.execute(cmd)
if retval ~= 0 then
return nil, "Failed to add interface IP address"
end
return true, nil
end
function network.unsetInterfaceIp(interface, subnet)
local ip, cidr = unpack(subnet)
ip = network.ip2string(ip)
cidr = tostring(cidr)
local cmd = shell.escape({"ip", "addr", "del", ip.."/"..cidr, "dev", interface.name})
local retval = shrunner.execute(cmd)
if retval ~= 0 then
return nil, "Failed to remove interface IP address"
end
return true, nil
end
function network.setRoute(interface, subnet)
local ip, cidr = unpack(subnet)
local v6 = #ip > 4
ip = network.ip2string(ip)
cidr = tostring(cidr)
if v6 then
cmd = shell.escape({"ip", "-6", "route", "add", ip.."/"..cidr, "dev", interface.name})
else
cmd = shell.escape({"ip", "route", "add", ip.."/"..cidr, "dev", interface.name})
end
local retval = shrunner.execute(cmd)
if retval ~= 0 then
return nil, "Failed to add route"
end
return true, nil
end
function network.unsetRoute(interface, subnet)
local ip, cidr = unpack(subnet)
local v6 = #ip > 4
ip = network.ip2string(ip)
cidr = tostring(cidr)
if v6 then
cmd = shell.escape({"ip", "-6", "route", "del", ip.."/"..cidr, "dev", interface.name})
else
cmd = shell.escape({"ip", "route", "del", ip.."/"..cidr, "dev", interface.name})
end
local retval = shrunner.execute(cmd)
if retval ~= 0 then
return nil, "Failed to add route"
end
return true, nil
end
function network.setDefaultRoute(interface, v6, gatewayIp)
-- ignore errors
network.unsetDefaultRoute(v6)
local cmd = {"ip", "route", "add", "default"}
if v6 then table.insert(cmd, 2, "-6") end
if gatewayIp then
table.insert(cmd, "via")
table.insert(cmd, network.ip2string(gatewayIp))
end
table.insert(cmd, "dev")
table.insert(cmd, interface.name)
local src, ifsubnets
if v6 then
ifsubnets = interface.ipv6subnets
else
ifsubnets = interface.ipv4subnets
end
for k,ifsubnet in pairs(ifsubnets) do
local addr, cidr = unpack(ifsubnet)
src = network.ip2string(addr)
break
end
table.insert(cmd, "src")
table.insert(cmd, src)
local retval = shrunner.execute(shell.escape(cmd))
if retval ~= 0 then
return nil, "Failed to configure default route"
end
return true, nil
end
function network.unsetDefaultRoute(v6)
local retval
if v6 then
retval = shrunner.execute("ip -6 route del default")
else
retval = shrunner.execute("ip route del default")
end
if retval ~= 0 then
return nil, "Failed to remove default route"
end
return true, nil
end
function network.setupNat4(interface, transitInterface)
-- set up nat
local cmd = shell.escape({"iptables","--table","nat","--append","POSTROUTING","--out-interface",transitInterface.name,"-j","MASQUERADE"})
local retval = shrunner.execute(cmd)
if retval ~= 0 then
return nil, "iptables failed"
end
local cmd = shell.escape({"iptables","--append","FORWARD","--in-interface",interface.name,"-j","ACCEPT"})
local retval = shrunner.execute(cmd)
if retval ~= 0 then
return nil, "iptables failed"
end
return true, nil
end
function network.setupNat6(interface, transitInterface)
-- set up nat
local cmd = shell.escape({"ip6tables","--table","nat","--append","POSTROUTING","--out-interface",transitInterface.name,"-j","MASQUERADE"})
local retval = shrunner.execute(cmd)
if retval ~= 0 then
return nil, "iptables failed"
end
local cmd = shell.escape({"ip6tables","--append","FORWARD","--in-interface",interface.name,"-j","ACCEPT"})
local retval = shrunner.execute(cmd)
if retval ~= 0 then
return nil, "iptables failed"
end
return true, nil
end
function network.setupTunnel(interfaceName, mode, remoteIp, localIp)
if #remoteIp ~= #localIp then
return nil, "address family mismatch"
end
v6 = #remoteIp > 4
local cmd = {"ip", "tunnel", "add", interfaceName, "mode", mode, "remote", network.ip2string(remoteIp), "local", network.ip2string(localIp)}
if v6 then table.insert(cmd, 2, "-6") end
local retval = shrunner.execute(shell.escape(cmd))
if retval ~= 0 then
return nil, "Failed to set up tunnel"
end
return true, nil
end
function network.teardownTunnel(interfaceName)
local cmd = {"ip", "tunnel", "del", interfaceName}
local retval = shrunner.execute(shell.escape(cmd))
if retval ~= 0 then
return nil, "Failed to tear down tunnel"
end
return true, nil
end
function network.upInterface(interfaceName)
local cmd = {"ip", "link", "set", "dev", interfaceName, "up"}
local retval = shrunner.execute(shell.escape(cmd))
if retval ~= 0 then
return nil, "Failed to bring up interface"
end
return true, nil
end
function network.downInterface(interfaceName)
local cmd = {"ip", "link", "set", "dev", interfaceName, "down"}
local retval = shrunner.execute(shell.escape(cmd))
if retval ~= 0 then
return nil, "Failed to bring down interace"
end
return true, nil
end
return network
|
local rR, rG, rB = 100, 250, 100
local function npack(...)
return {_n=select('#',...);...}
end
local function crun(commandstring)
outputChatBox("Executing client command:" .. commandstring, rR, rG, rB)
local results = npack( assert(loadstring(commandstring))() )
local resultsString = ""
local first = true
for i=1, results._n do
local result = results[i]
if first then
first = false
else
resultsString = resultsString..", "
end
local resultType = type(result)
if resultType == "userdata" and isElement(result) then
resultType = "element:"..getElementType(result)
end
resultsString = resultsString..tostring(result).." ["..resultType.."]"
end
outputChatBox("Command executed! Results: " ..resultsString, rR, rG, rB)
return unpack(results)
end
addCommandHandler("crung",
function (command, ...)
crun("return "..table.concat({...}, " "))
end
)
function map(element, level)
level = level or 0
element = element or getRootElement()
local indent = string.rep(' ', level)
local eType = getElementType(element)
local eID = getElementID(element) or ""
local eChildren = getElementChildren(element)
if #eChildren < 1 then
outputConsole(indent..'<'..eType..' id="'..eID..'"/>')
else
outputConsole(indent..'<'..eType..' id="'..eID..'">')
for k, child in ipairs(eChildren) do map(child, level+1) end
outputConsole(indent..'</'..eType..'>')
end
end
|
reaper.AddProjectMarker(0, false,
reaper.GetPlayState() & 1 == 1 and
reaper.GetPlayPosition() or
reaper.GetCursorPosition(), 0,
"Multicam - Switch to camera " ..
string.match(select(2, reaper.get_action_context()),
"leafac_.-(%d+).*%.lua$"), -1)
|
require "config.settings"
local animations = {}
local defaults = {
file = "sprites",
size = {
height = 16,
width = 16
}
}
local crystal_animation = {
stand = {
fps = 1,
frames = { 0 }
},
walk = {
fps = 4,
frames = { 0, 1, 0, 1 }
},
attack = {
fps = 1,
frames = { 0 }
},
use = {
fps = 1,
frames = { 0 }
},
cast = {
fps = 1,
frames = { 0 }
},
hurt = {
fps = 1,
frames = { 0, 1, 0, 1 }
},
down = {
fps = 1,
frames = { 0, 1, 0, 1 }
},
dead = {
fps = 1,
frames = { 2 }
},
fear = {
fps = 1,
frames = { 0, 1, 0, 1 }
},
rise = {
fps = 1,
frames = { 0 }
}
}
local mini_animation = {
stand = {
fps = 1,
frames = { 0 }
},
walk = {
fps = 4,
frames = { 0, 1, 0, 1 }
},
attack = {
fps = 1,
frames = { 0 }
},
use = {
fps = 1,
frames = { 0 }
},
cast = {
fps = 1,
frames = { 0 }
},
hurt = {
fps = 1,
frames = { 0 }
},
down = {
fps = 1,
frames = { 0 }
},
dead = {
fps = 1,
frames = { 0 }
},
fear = {
fps = 1,
frames = { 0 }
},
rise = {
fps = 1,
frames = { 0 }
}
}
local basic_animation = {
stand = {
fps = 1,
frames = { 0 }
},
walk = {
fps = 4,
frames = { 1, 0, 2, 0}
},
attack = {
fps = 2 * turns_per_second,
frames = { 3, 4, 4, 4 },
activation_frame = 1,
},
use = {
fps = 2 * turns_per_second,
frames = { 5, 6, 5, 6 }
},
cast = {
fps = 2 * turns_per_second,
frames = { 7, 8, 7, 8 }
},
hurt = {
fps = 1 * turns_per_second,
frames = { 9 }
},
down = {
fps = 1,
frames = { 10 }
},
dead = {
fps = 1,
frames = { 11 }
},
fear = {
fps = 2 * turns_per_second,
frames = {12, 13},
},
rise = {
fps = 2 * turns_per_second,
frames = { 11, 10, 0 }
}
}
animations.types = {
human_male = {
basic = defaults,
coordinates = {
x = 0,
y = 0
},
animations = basic_animation
},
human_mini = {
basic = defaults,
coordinates = {
x = 16 * 16,
y = 16 * 0
},
animations = mini_animation
},
human_female = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 1
},
animations = basic_animation
},
witch = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 2
},
animations = basic_animation
},
ranger = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 3
},
animations = basic_animation
},
cat_girl = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 4
},
animations = basic_animation
},
cat_girl_mini = {
basic = defaults,
coordinates = {
x = 16 * 16,
y = 16 * 4
},
animations = mini_animation
},
evana = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 5,
},
animations = basic_animation
},
bunny_girl = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 6,
},
animations = basic_animation
},
rat_king = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 7
},
animations = basic_animation
},
rat = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 8
},
animations = basic_animation
},
elf = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 9,
},
animations = basic_animation
},
imp = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 10,
},
animations = basic_animation
},
strawberry_monster = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 11
},
animations = basic_animation
},
inn_keeper = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 12
},
animations = basic_animation
},
hobo = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 13
},
animations = basic_animation
},
viking = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 14
},
animations = basic_animation
},
trenchcoat = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 15
},
animations = basic_animation
},
thief_female = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 16
},
animations = basic_animation
},
knight_male = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 17
},
animations = basic_animation
},
cleric_female = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 18
},
animations = basic_animation
},
cleric_female_mini = {
basic = defaults,
coordinates = {
x = 16 * 14,
y = 16 * 18
},
animations = mini_animation
},
pig_man = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 19
},
animations = basic_animation
},
pig_man_mini = {
basic = defaults,
coordinates = {
x = 16 * 14,
y = 16 * 19
},
animations = mini_animation
},
santa = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 20
},
animations = basic_animation
},
skeleton = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 21
},
animations = basic_animation
},
sir_cavalion = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 22
},
animations = basic_animation
},
sir_cavalion_mini = {
basic = defaults,
coordinates = {
x = 16 * 16,
y = 16 * 22
},
animations = mini_animation
},
mountain_man = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 23
},
animations = basic_animation
},
queen = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 24
},
animations = basic_animation
},
french_maid = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 25
},
animations = basic_animation
},
cook = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 26
},
animations = basic_animation
},
knight_female = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 27
},
animations = basic_animation
},
knight_female_mini = {
basic = defaults,
coordinates = {
x = 16 * 14,
y = 16 * 27
},
animations = mini_animation
},
ghost_girl = {
basic = defaults,
coordinates = {
x = 0,
y = 16 * 28
},
animations = basic_animation
},
dragon = {
basic = {
file = "sprites",
size = {
height = 32,
width = 32
}
},
coordinates = {
x = 0,
y = 16 * 30
},
animations = basic_animation
},
crystal = {
basic = {
file = "sprites",
size = {
height = 32,
width = 32
}
},
coordinates = {
x = 16 * 26,
y = 16 * 27
},
animations = crystal_animation
},
cleric_blonde = {
basic = defaults,
coordinates = {
x = 16 * 16,
y = 16 * 5,
},
animations = basic_animation
},
cleric_blonde_mini = {
basic = defaults,
coordinates = {
x = 16 * 30,
y = 16 * 5
},
animations = mini_animation
},
cleric_cyan = {
basic = defaults,
coordinates = {
x = 16 * 16,
y = 16 * 6,
},
animations = basic_animation
},
cleric_cyan_mini = {
basic = defaults,
coordinates = {
x = 16 * 30,
y = 16 * 6
},
animations = mini_animation
},
cleric_green = {
basic = defaults,
coordinates = {
x = 16 * 16,
y = 16 * 7,
},
animations = basic_animation
},
cleric_green_mini = {
basic = defaults,
coordinates = {
x = 16 * 30,
y = 16 * 7
},
animations = mini_animation
},
cleric_black = {
basic = defaults,
coordinates = {
x = 16 * 16,
y = 16 * 8,
},
animations = basic_animation
},
cleric_black_mini = {
basic = defaults,
coordinates = {
x = 16 * 30,
y = 16 * 8
},
animations = mini_animation
},
thief = {
basic = defaults,
coordinates = {
x = 16 * 16,
y = 16 * 9
},
animations = basic_animation
},
rabbit = {
basic = defaults,
coordinates = {
x = 16 * 16,
y = 16 * 10
},
animations = basic_animation
},
wolf = {
basic = defaults,
coordinates = {
x = 16 * 16,
y = 16 * 11
},
animations = basic_animation
},
wolf_mini = {
basic = defaults,
coordinates = {
x = 16 * 16,
y = 16 * 3
},
animations = mini_animation
},
priest = {
basic = defaults,
coordinates = {
x = 16 * 16,
y = 16 * 12
},
animations = basic_animation
},
page = {
basic = defaults,
coordinates = {
x = 16 * 16,
y = 16 * 13
},
animations = basic_animation
},
page_mini = {
basic = defaults,
coordinates = {
x = 16 * 30,
y = 16 * 13
},
animations = mini_animation
},
medea = {
basic = defaults,
coordinates = {
x = 16 * 16,
y = 16 * 14
},
animations = basic_animation
},
medea_mini = {
basic = defaults,
coordinates = {
x = 16 * 30,
y = 16 * 14
},
animations = mini_animation
},
barbarian = {
basic = defaults,
coordinates = {
x = 16 * 16,
y = 16 * 15
},
animations = basic_animation
},
barbarian_mini = {
basic = defaults,
coordinates = {
x = 16 * 30,
y = 16 * 15
},
animations = mini_animation
},
bounty_hunter = {
basic = defaults,
coordinates = {
x = 16 * 16,
y = 16 * 16
},
animations = basic_animation
},
bounty_hunter_mini = {
basic = defaults,
coordinates = {
x = 16 * 30,
y = 16 * 16
},
animations = mini_animation
},
soldier = {
basic = defaults,
coordinates = {
x = 16 * 16,
y = 16 * 17
},
animations = basic_animation
},
soldier_mini = {
basic = defaults,
coordinates = {
x = 16 * 30,
y = 16 * 17
},
animations = mini_animation
},
guild_master = {
basic = defaults,
coordinates = {
x = 16 * 16,
y = 16 * 18
},
animations = basic_animation
},
zombie = {
basic = defaults,
coordinates = {
x = 16 * 16,
y = 16 * 19
},
animations = basic_animation
},
}
return animations
|
local Vector3 = require("Scripts/Vector3")
function DeleteCoin(entity)
DeleteEntity(entity)
end
function PlayerLeft(entity, inputValue, deltaTime)
if inputValue > 0.2 then
local ComponentPhysics = GetComponentPhysics(entity)
local currentRotation = GetRotation(ComponentPhysics)
local y = currentRotation:getX()
y = y + (inputValue * 4)
currentRotation:setY(y)
SetRotation(ComponentPhysics, currentRotation);
end
end
function PlayerRight(entity, inputValue, deltaTime)
if inputValue > 0.2 then
local ComponentPhysics = GetComponentPhysics(entity)
local currentRotation = GetRotation(ComponentPhysics)
local y = currentRotation:getX()
y = y - (inputValue * 4)
currentRotation:setY(y)
SetRotation(ComponentPhysics, currentRotation);
end
end
function PlayerForward(entity, inputValue, deltaTime)
if inputValue > 0.2 then
local ComponentPhysics = GetComponentPhysics(entity)
local ComponentDirection = GetComponentDirection(entity)
local currentDirection = GetDirection(ComponentDirection)
local currentVelocity = GetVelocity(ComponentPhysics)
local changeVelocity = Vector3:new(1, 0, 0)
local rotationMatrix = CreateRotationMatrix(currentDirection)
changeVelocity = MultiplyMatrixVector(rotationMatrix, changeVelocity)
changeVelocity = changeVelocity:multiply(inputValue * 8)
currentVelocity = currentVelocity:add(changeVelocity)
SetVelocity(ComponentPhysics, currentVelocity);
end
end
function PlayerBackward(entity, inputValue, deltaTime)
if inputValue > 0.2 then
local ComponentPhysics = GetComponentPhysics(entity)
local ComponentDirection = GetComponentDirection(entity)
local currentDirection = GetDirection(ComponentDirection)
local currentVelocity = GetVelocity(ComponentPhysics)
local changeVelocity = Vector3:new(-1, 0, 0)
local rotationMatrix = CreateRotationMatrix(currentDirection)
changeVelocity = MultiplyMatrixVector(rotationMatrix, changeVelocity)
changeVelocity = changeVelocity:multiply(inputValue * 8)
currentVelocity = currentVelocity:add(changeVelocity)
SetVelocity(ComponentPhysics, currentVelocity);
end
end
function PlayerJump(entity, inputValue, deltaTime)
if inputValue > 0.2 then
local ComponentPhysics = GetComponentPhysics(entity)
if GetTouchingGround(ComponentPhysics) then
local currentImpulse = GetImpulse(ComponentPhysics)
local y = currentImpulse:getY()
y = y + (inputValue * 2)
currentImpulse:setY(y)
SetImpulse(ComponentPhysics, currentImpulse)
end
end
end
function PlayerShoot(entity, inputValue, deltaTime)
if inputValue > 0.2 then
local ComponentState = GetComponentState(entity)
local timeLastShoot = GetValue(ComponentState, "timeSinceShoot", "float", 0)
if timeLastShoot <= 0 then
SetValue(ComponentState, "timeSinceShoot", 0.5)
local bulletComponentPosition = GetComponentPosition(entity)
local bulletComponentDirection = GetComponentDirection(entity)
local currentPosition = GetPosition(bulletComponentPosition)
local currentDirection = GetDirection(bulletComponentDirection)
local changePosition = Vector3:new(1, 0, 0)
local rotationMatrix = CreateRotationMatrix(currentDirection)
changePosition = MultiplyMatrixVector(rotationMatrix, changePosition)
local bulletEntity = CreateEntity();
local position = currentPosition:add(changePosition);
local direction = Vector3:new(0, 1, 0);
local size = Vector3:new(0.05, 0.05, 0.05);
local angularLimits = Vector3:new(1, 1, 1);
local cuboid = CreateCollisionCuboid(size);
local collisionFunctionMap = CreateCollisionFunctionMap()
AddToCollisionFunctionMap(collisionFunctionMap, "PLAYER", "DestroyBullet")
AddToCollisionFunctionMap(collisionFunctionMap, "WALL", "DestroyBullet")
AddComponentPosition(bulletEntity, position);
AddComponentDirection(bulletEntity, direction, 0);
AddComponentPhysics(bulletEntity, cuboid, 0.1, "PBULLET", angularLimits, false, collisionFunctionMap);
AddComponentModel(bulletEntity, "Bullet");
AddComponentNormalTexture(bulletEntity, "BoxNormal");
AddComponentTexture(bulletEntity, "Box");
AddComponentShader(bulletEntity, "NormalShader");
AddComponentShadowShader(bulletEntity, "DirectionalShadow", "PointShadow");
AddComponentAnimation(bulletEntity, "BulletMovement");
AddComponentState(bulletEntity);
local bulletComponentState = GetComponentState(bulletEntity);
SetValue(bulletComponentState, "xDirection", changePosition:getX())
SetValue(bulletComponentState, "yDirection", changePosition:getY())
SetValue(bulletComponentState, "zDirection", changePosition:getZ())
SetValue(bulletComponentState, "BulletTime", 5)
FinishEntity(bulletEntity);
end
end
end
function PlayerDown(entity)
local ComponentState = GetComponentState(entity)
local currentScore = GetValue(ComponentState, "Health", "integer", 100)
currentScore = currentScore - 10
SetValue(ComponentState, "Health", currentScore)
end |
function vehicleGui()
local screenW, screenH = guiGetScreenSize()
vehicleWindow = guiCreateGridList((screenW - 231) / 2, (screenH - 292) / 2, 231, 288, false)
guiSetAlpha(vehicleWindow, 0.90)
guiSetProperty(vehicleWindow, "AlwaysOnTop", "True")
guiSetVisible(vehicleWindow,false)
vehicleWindowButtonSpawn = guiCreateButton(7, 258, 102, 23, "spawn vehicle", false, vehicleWindow)
vehicleWindowButtonClose = guiCreateButton(158, 258, 66, 24, "close", false, vehicleWindow)
vehicleWindowGridlist = guiCreateGridList(7, 25, 217, 227, false, vehicleWindow)
guiGridListAddColumn(vehicleWindowGridlist, "Vehicles", 0.85)
vehicleWindowLabel = guiCreateLabel(7, 5, 217, 15, "VEHICLE SPAWNER MENU", false, vehicleWindow)
guiSetFont(vehicleWindowLabel, "default-bold-small")
guiLabelSetHorizontalAlign(vehicleWindowLabel, "center", false)
guiLabelSetVerticalAlign(vehicleWindowLabel, "center")
for _,v in ipairs(vehicles) do
local row = guiGridListAddRow(vehicleWindowGridlist)
guiGridListSetItemText(vehicleWindowGridlist, row, 1, v[2], false, false)
guiGridListSetItemData(vehicleWindowGridlist, row, 1, {v[1],v[3],v[4],v[5],v[6],v[7],v[8],v[9]})
end
addEventHandler("onClientGUIClick",buttonVehicles,openVehicleGui,false)
addEventHandler("onClientGUIClick",vehicleWindowButtonClose,closeVehicleGui,false)
addEventHandler("onClientGUIClick", vehicleWindowButtonSpawn, vehicle, false)
end
addEventHandler("onClientResourceStart", resourceRoot, vehicleGui)
function openVehicleGui()
if (guiGridListGetSelectedItem( gridlistPlayers1 ) ~= -1) then
triggerEvent("disableError",localPlayer)
setElementData(localPlayer,"isGui",true)
guiSetVisible(hiddenGridlist,true) -- hidden gridlist to dont allow select other players from player list
guiSetVisible(errorWindow,false)
guiSetVisible(kickWindow,false)
guiSetVisible(messageWindow,false)
guiSetVisible(muteWindow,false)
guiSetVisible(warpWindow,false)
guiSetVisible(weatherWindow,false)
guiSetVisible(banWindow,false)
guiSetVisible(dayzStatsWindow,false)
guiSetVisible(giveWindow,false)
guiSetVisible(vehicleWindow,true)
else
triggerEvent("enableError",localPlayer)
end
end
function closeVehicleGui()
guiSetVisible(hiddenGridlist,false) -- hidden gridlist to dont allow select other players from player list
guiSetVisible(vehicleWindow,false)
setElementData(localPlayer,"isGui",false)
end |
require("core.lsp").run("javascript")
|
--[[
GuildMemberNotifier
Author: @ChrisAnn
Thanks to SoulGemsCounter, Combat Log Statistics and XPNotifier for being inspiration
]]
GuildMemberNotifier = {}
GuildMemberNotifier.name = "GuildMemberNotifier"
GuildMemberNotifier.version = "1.1.2"
GuildMemberNotifier.debug = false
GuildMemberNotifier.guildTable = {
[1] = true;
[2] = true;
[3] = true;
[4] = true;
[5] = true;
}
function GuildMemberNotifier.Initialise(eventCode, addOnName)
if (addOnName ~= GuildMemberNotifier.name) then return end
zo_callLater(function() d("Guild Member Notifier Initialised.") end, 4000)
EVENT_MANAGER:RegisterForEvent(GuildMemberNotifier.name, EVENT_GUILD_MEMBER_PLAYER_STATUS_CHANGED, GuildMemberNotifier.OnGuildMemberPlayerStatusChanged)
end
function GuildMemberNotifier.OnGuildMemberPlayerStatusChanged(eventCode, guildId, playerName, previousStatus, currentStatus)
GuildMemberNotifier.Log("[eventCode:"..eventCode.."][guildId:"..guildId.."][playerName:"..playerName.."][previousStatus:"..previousStatus.."][currentStatus:"..currentStatus.."]")
if (GuildMemberNotifier.guildTable[guildId] == true) then
if (currentStatus == PLAYER_STATUS_ONLINE and playerName ~= GetDisplayName()) then
d(string.format("|r|cFFC700 %s from '%s' has logged on", playerName, GetGuildName(guildId)))
end
if (currentStatus == PLAYER_STATUS_OFFLINE) then
d(string.format("|r|cFFC700 %s from '%s' has logged off", playerName, GetGuildName(guildId)))
end
end
end
SLASH_COMMANDS["/gmn"] = function (commands)
local options = GuildMemberNotifier.SplitSlashOptions(commands)
if (#options == 0 or options[1] == "help") then
d("GuildMemberNotifier Help")
d("Enter '/gmn {guildId} {on|off}'")
d("eg '/gmn 2 off' to turn off alerts for guild 2")
else
local guildId = tonumber(options[1])
local active = options[2]
if (guildId ~= nil and (guildId > 0 and guildId <= 5)) then
GuildMemberNotifier.Log("[guildId:"..guildId.."]")
else
d("Unrecognised GuildId. Enter '/gmn help'")
end
if (active == 'on') then
GuildMemberNotifier.guildTable[guildId] = true
d("Guild Member notifications ON for "..GetGuildName(guildId))
elseif (active == 'off') then
GuildMemberNotifier.guildTable[guildId] = false
d("Guild Member notifications OFF for "..GetGuildName(guildId))
else
d("Unrecognised command. Enter '/gmn help'")
if (active ~= nil) then
GuildMemberNotifier.Log("[active:"..active.."]")
end
end
end
end
function GuildMemberNotifier.SplitSlashOptions(commands)
local options = {}
local searchResult = { string.match(commands,"^(%S*)%s*(.-)$") }
for i,v in pairs(searchResult) do
if (v ~= nil and v ~= "") then
options[i] = string.lower(v)
end
end
return options
end
function GuildMemberNotifier.Log(message)
if (GuildMemberNotifier.debug) then
d("|r|c888888 " .. message)
end
end
EVENT_MANAGER:RegisterForEvent(GuildMemberNotifier.name, EVENT_ADD_ON_LOADED, GuildMemberNotifier.Initialise)
|
--[[
CCScene:transition("cf",{"crossFade",1,CCOrientation.Left})
CCScene:add("firstScene",CCScene())
CCScene:run("firstScene","fadeIn")
CCScene:forward("firstScene","cf")
CCScene:back("crossFade")
CCScene:clearHistory()
--]]
local CCScene = require("CCScene")
local CCDirector = require("CCDirector")
local scenes = {}
local transitions = {}
local currentScene
local sceneStack = {}
function CCScene:transition(name,item)
transitions[name] = item
end
function CCScene:add(name,scene)
scenes[name] = scene
scene:slot("Cleanup",function()
scenes[name] = nil
end)
end
function CCScene:remove(name)
local scene = scenes[name]
if scene then
scene:cleanup()
scenes[name] = nil
return true
end
return false
end
local function runScene(scene,tname,cleanup)
local data = tname and transitions[tname]
local transition
if data then
local args = {data[2],scene}
for i = 3,#data do
args[i] = data[i]
end
transition = CCScene[data[1]](CCScene,unpack(args))
end
if CCDirector.sceneStackSize == 0 then
CCDirector:run(transition or scene)
else
CCDirector:replaceScene(transition or scene,cleanup)
end
end
function CCScene:run(sname,tname)
local scene = scenes[sname]
if scene then
if #sceneStack > 0 then
sceneStack = {}
end
currentScene = scene
runScene(scene,tname,true)
end
end
function CCScene:forward(sname,tname)
local scene = scenes[sname]
if scene then
table.insert(sceneStack,currentScene)
currentScene = scene
runScene(scene,tname,false)
end
end
function CCScene:back(tname)
local lastScene = table.remove(sceneStack)
if lastScene then
currentScene = lastScene
runScene(lastScene,tname,false)
end
end
function CCScene:clearHistory()
currentScene = CCDirector.currentScene
sceneStack = {}
end
return CCScene
|
#!/usr/bin/env lua
local exec = require "tek.lib.exec"
local c = exec.run(function()
error "child error"
end)
print "parent done"
--[[
parent done
luatask: bin/task/test30.lua:4: child error
stack traceback:
[C]: in function 'error'
bin/task/test30.lua:4: in function <bin/task/test30.lua:3>
[C]: ?
]]--
|
require "/scripts/util.lua"
require "/scripts/vec2.lua"
require "/scripts/interp.lua"
require "/lib/stardust/color.lua"
function init()
script.setUpdateDelta(3) -- was 5
self.drawPath = "/startech/objects/power/"
self.dMeter = self.drawPath .. "battery.meter.png"
dPos = vec2.add(objectAnimator.position(), {-1, 0})
if objectAnimator.direction() == 1 then dPos[1] = dPos[1] + 5/8 end
dPos = vec2.add(dPos, vec2.mul({3, 16 - 5}, 1/8))
end
function update()
local batLevel = animationConfig.animationParameter("level") or 0 -- float, 0..1
if batLevel == lastBatLevel then return nil end -- let's ease up a lil
lastBatLevel = batLevel
localAnimator.clearDrawables()
localAnimator.clearLightSources()
localAnimator.addDrawable({
image = table.concat({
self.dMeter , "?addmask=", self.dMeter, ";0;",
10 - math.floor(batLevel * 10),
"?multiply=", color.toHex(color.fromHsl{math.max(0, batLevel*1.25 - 0.25) * 1/3, 1, 0.5, 1})
}),
position = vec2.add(objectAnimator.position(), { -1/8, 3/8 }),
fullbright = true,
centered = false,
zlevel = 10
})
end
--
|
local E, L, V, P, G = unpack(select(2, ...)); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
local S = E:GetModule('Skins')
--Cache global variables
--Lua functions
local _G = _G
local pairs = pairs
--WoW API / Variables
--Global variables that we don't cache, list them here for mikk's FindGlobals script
-- GLOBALS: KEY_BINDINGS_DISPLAYED
local function LoadSkin()
if E.private.skins.blizzard.enable ~= true or E.private.skins.blizzard.binding ~= true then return end
local buttons = {
"defaultsButton",
"unbindButton",
"okayButton",
"cancelButton",
}
local KeyBindingFrame = _G["KeyBindingFrame"]
for _, v in pairs(buttons) do
S:HandleButton(KeyBindingFrame[v])
end
KeyBindingFrame.header:StripTextures()
_G["KeyBindingFrameScrollFrame"]:StripTextures()
S:HandleScrollBar(_G["KeyBindingFrameScrollFrameScrollBar"])
S:HandleCheckBox(KeyBindingFrame.characterSpecificButton)
KeyBindingFrame.header:ClearAllPoints()
KeyBindingFrame.header:Point("TOP", KeyBindingFrame, "TOP", 0, -4)
KeyBindingFrame:StripTextures()
KeyBindingFrame:SetTemplate("Transparent")
_G["KeyBindingFrameCategoryList"]:StripTextures()
_G["KeyBindingFrameCategoryList"]:SetTemplate("Transparent")
KeyBindingFrame.bindingsContainer:StripTextures()
KeyBindingFrame.bindingsContainer:SetTemplate("Transparent")
for i = 1, KEY_BINDINGS_DISPLAYED, 1 do
local button1 = _G["KeyBindingFrameKeyBinding"..i.."Key1Button"]
local button2 = _G["KeyBindingFrameKeyBinding"..i.."Key2Button"]
S:HandleButton(button1)
S:HandleButton(button2)
end
KeyBindingFrame.okayButton:Point("BOTTOMLEFT", KeyBindingFrame.unbindButton, "BOTTOMRIGHT", 3, 0)
KeyBindingFrame.cancelButton:Point("BOTTOMLEFT", KeyBindingFrame.okayButton, "BOTTOMRIGHT", 3, 0)
KeyBindingFrame.unbindButton:Point("BOTTOMRIGHT", KeyBindingFrame, "BOTTOMRIGHT", -211, 16)
end
S:AddCallbackForAddon("Blizzard_BindingUI", "Binding", LoadSkin)
|
#! /usr/bin/env texlua
local lfs = require("lfs")
local os = require("os")
local io = require("io")
local OS_TYPE = os["type"]
local OS_NAME = os["name"]
local IS_UNIX = OS_TYPE == "unix"
local VERSION = "1.0"
local print = print
local exit = os.exit
local execute = os.execute
local __FILE__ = arg[0]
local i = 1
local verbose = false
for _,r in ipairs(arg) do
if r == "--verbose" then
verbose = true
elseif r == "-v" then
verbose = true
end
end
print("MathDataBase configure tool v"..VERSION)
if verbose then
s = "Host operating system: %s (%s)"
print(s:format(OS_TYPE, OS_NAME))
end
local mdb_Tool, mdb_root, mdb_Style
mdb_Tool = __FILE__:match(IS_UNIX and "(.*)/" or "(.*)[/\\]")
if mdb_Tool == nil then
mdb_Tool = lfs.currentdir()
else
if IS_UNIX then
if not mdb_Tool:match("^/") then
mdb_Tool = lfs.currentdir() .."/".. mdb_Tool
end
else
if not mdb_Tool:match("^%u:") then
mdb_Tool = lfs.currentdir() .."\\".. mdb_Tool
end
end
end
mdb_root = mdb_Tool:match(IS_UNIX and "(.*)/" or "(.*)[/\\]")
mdb_Style = mdb_root .."/Style"
if verbose then
s = "MathDataBase location: %s"
print(s:format(mdb_root))
end
local function fs_mode(path)
return lfs.attributes (path, "mode")
end
local function is_directory(path)
local mode,err_msg,err_code = fs_mode (path)
return mode == "directory",err_msg,err_code
end
if not IS_UNIX then
print("Please activate the developper mode")
print("Press return to continue")
io.read()
end
-- Where is the local texmf
local HOME
if IS_UNIX then
HOME = os.getenv("HOME")
else
HOME = os.getenv("HOMEDRIVE")..os.getenv("HOMEPATH")
end
if verbose then
print("HOME: "..HOME)
end
local function capture(cmd)
local f = assert(io.popen(cmd,'r'))
local s = assert(f:read('a'))
f:close()
return s
end
local TEXMFHOME = capture("kpsewhich --var-value=TEXMFHOME"):gsub('[\n\r]+', '')
local TEXMFHOME_ok = is_directory(TEXMFHOME)
if not TEXMFHOME_ok then
local dir = TEXMFHOME:match(".*/")
if dir then
TEXMFHOME_ok = is_directory(dir) or lfs.mkdir(TEXMFHOME)
else
print("Votre dossier texmf personnel ne semble pas configuré")
if not IS_UNIX then
print("Sur MikTeX, voir le dernier paragraphe de https://miktex.org/kb/texmf-roots")
end
print("Quel est le chemin vers votre dossier texmf personnel?")
local MAX = 3
while true do
TEXMFHOME = io.read()
if TEXMFHOME:len() == 0 then
print("Annulation")
exit(1)
end
TEXMFHOME_ok = is_directory(TEXMFHOME)
if TEXMFHOME_ok then
break
else
print("Pas de dossier "..TEXMFHOME)
if MAX > 0 then
MAX = MAX - 1
else
print("Annulation")
exit(1)
end
end
end
end
end
if verbose then
print("Personal texmf tree: ".. TEXMFHOME)
end
TEXMFHOME_tex = TEXMFHOME.."/tex"
TEXMFHOME_tex_latex = TEXMFHOME_tex.."/latex"
if TEXMFHOME_ok then
if (is_directory(TEXMFHOME_tex)
or lfs.mkdir(TEXMFHOME_tex))
and (is_directory(TEXMFHOME_tex_latex)
or lfs.mkdir(TEXMFHOME_tex_latex)) then
-- print("Votre dossier texmf personnel est\n"..TEXMFHOME)
else
print("Votre dossier texmf personnel semble être\n"..TEXMFHOME)
print("Mais il manque le dossier\n"..TEXMFHOME_tex_latex)
end
end
-- Configure MathDataBase
local cfg_path = TEXMFHOME_tex_latex.."/MDB.cfg"
local yorn,err_msg,err_code
if fs_mode(cfg_path) ~= nil then
yorn,err_msg,err_code = os.remove(cfg_path)
if not yorn then
print("Can't remove "..cfg_path, err_msg)
exit(err_code)
end
end
if verbose then
print("Removed "..cfg_path)
end
local fh = assert(io.open(cfg_path,"w"))
local s = [[
%% MathDataBase configuration file: DO NOT EDIT
\MDBConfigure {
path={%s/},
}
]]
fh:write(s:format(mdb_root))
fh:close()
fh = assert(io.open(cfg_path,"r"))
s = fh:read("a")
fh:close()
assert(s:match("MathDataBase"))
if verbose then
print("Content of "..cfg_path..":")
print(s)
end
fh = assert(io.open(mdb_Style.."/MathDataBase.sty","r"))
s = fh:read("a")
fh:close()
if not s:match("MathDataBase") then
print("Échec: MathDataBase est corrompu")
exit(1)
end
local mdb_path = TEXMFHOME_tex_latex.."/MDB"
if fs_mode(mdb_path) ~= nil then
yorn,err_msg,err_code = os.remove(mdb_path)
if not yorn then
if IS_UNIX then
print("Can't remove "..mdb_path, err_msg)
exit(err_code)
else
local cmd = [[rmdir "%s"]]
cmd = cmd:format(mdb_path)
if verbose then
print("Executing: "..cmd)
end
execute(cmd)
if fs_mode(mdb_path) ~= nil then
s = [[
Please remove file at: %s
once done, press return to continue]]
print(s:format(mdb_path))
end
end
end
if verbose then
print("Removed "..mdb_path)
end
end
yorn, err_msg, err_code = lfs.link(mdb_Style, TEXMFHOME_tex_latex.."/MDB", true)
if yorn == nil then
if IS_UNIX then
print("Échec", err_msg)
exit(err_code)
else
local cmd = [[mklink /D "%s" "%s"]]
cmd = cmd:format(mdb_path, mdb_Style)
if verbose then
print("Executing: "..cmd)
end
execute(cmd)
end
end
fh = assert(io.open(mdb_path.."/MathDataBase.sty","r"))
s = fh:read("a")
fh:close()
if s:len() == 0 then
print("Échec")
if not IS_UNIX then
s = [[
Impossible de terminer la configuration automatique sur Windows:
Vous devez terminer manuellement
1) Dans PowerShell, exécuter la commande:
mklink /D "%s" "%s"
2) Dans PowerShell, exécuter la commande:
kpsewhich MathDataBase.sty
]]
print(s:format(mdb_path, mdb_Style))
end
exit(1)
end
if verbose then
print("Created link "..mdb_path.." -> "..mdb_Style)
end
s = capture("kpsewhich MathDataBase.sty")
if verbose then
print("kpsewhich MathDataBase.sty: "..s)
end
if s:match("MathDataBase.sty") then
print([[
Configuration réussie: vous pouvez utiliser
\RequirePackage{MathDataBase}
dans vos documents LaTeX.]])
else
print("Échec de la configuration automatique")
end
|
ESX = nil
local PlayerData = {}
CreateThread(function()
while ESX == nil do
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
Citizen.Wait(0)
end
Citizen.Wait(5000)
PlayerData = ESX.GetPlayerData()
end)
RegisterNetEvent('esx:playerLoaded')
AddEventHandler('esx:playerLoaded', function(xPlayer)
PlayerData = xPlayer
end)
RegisterNetEvent('esx:setJob')
AddEventHandler('esx:setJob', function(job)
PlayerData.job = job
end)
local blips_cache = { }
local server_has_heartbeat = false
local blip_types = Config.Blips
Citizen.CreateThread(function()
while true do
Citizen.Wait(15 * 1000)
server_has_heartbeat = false
SetTimeout(5 * 1000, function()
if not server_has_heartbeat then
for check_follow_id_key, data in pairs(blips_cache) do
if not blips_cache[check_follow_id_key].has_server_validated then
RemoveBlip(data.blip_id)
RemoveBlip(data.synced_blip_id)
blips_cache[check_follow_id_key] = nil
end
end
end
end)
end
end)
local passes = 0
RegisterNetEvent('badBlips:client:syncMyBlips')
AddEventHandler('badBlips:client:syncMyBlips', function(blips)
local me_ped = PlayerPedId()
server_has_heartbeat = true
for _, properties in ipairs(blips) do
local follow_on_source = properties[5]
local follow_id_key = properties[4] .. '_' .. properties[5]
if not blips_cache[follow_id_key] then
blips_cache[follow_id_key] = { properties = { } }
end
blips_cache[follow_id_key].needs_server = true
local is_networked = NetworkIsPlayerActive(GetPlayerFromServerId(follow_on_source))
if is_networked then
local me_player = GetPlayerServerId(PlayerId())
if Config.hide_my_blip and follow_on_source == me_player then
blips_cache[follow_id_key].ignored = true
end
blips_cache[follow_id_key].needs_server = false
blips_cache[follow_id_key].player_ped = GetPlayerPed(GetPlayerFromServerId(follow_on_source))
end
if not blips_cache[follow_id_key].ignored then
if blips_cache[follow_id_key].is_created and not blips_cache[follow_id_key].needs_removal then
local blip_id = blips_cache[follow_id_key].blip_id
blips_cache[follow_id_key].properties = properties
blips_cache[follow_id_key].has_server_validated = true
doUpdateBlip(follow_id_key, blip_id, properties)
else
local blip_id = doAddBlip(properties)
blips_cache[follow_id_key].is_created = true
blips_cache[follow_id_key].blip_id = blip_id
blips_cache[follow_id_key].properties = properties
blips_cache[follow_id_key].has_server_validated = true
end
end
end
for _, __ in pairs(blips_cache) do
if not blips_cache[_].has_server_validated then
if blips_cache[_].synced_blip_id then
RemoveBlip(blips_cache[_].synced_blip_id)
blips_cache[_].synced_blip_id = false
end
if blips_cache[_].blip_id then
RemoveBlip(blips_cache[_].blip_id)
blips_cache[_].blip_id = false
end
blips_cache[_] = nil
end
if blips_cache[_] then
blips_cache[_].has_server_validated = false
end
end
end)
RegisterNetEvent('szymczakovv:openMenu')
AddEventHandler('szymczakovv:openMenu', function()
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'gpsmen',
{
title = 'GPS',
align = 'center',
elements = {
{label = 'Uruchom GPS', value = 'turnon'},
{label = 'Zniszcz GPS', value = 'destroy'},
}
}, function(data2, menu2)
if data2.current.value == 'turnon' then
menu2.close()
TriggerServerEvent("szymczakovv:refreshGPS")
Citizen.Wait(1500)
elseif data2.current.value == 'destroy' then
menu2.close()
TriggerServerEvent("szymczakovv:destroyGPS")
Citizen.Wait(1500)
end
end, function(data2, menu2)
menu2.close()
end)
end)
RegisterNetEvent('szymczakovv:lostGPS')
AddEventHandler('szymczakovv:lostGPS', function(characterInfo, coords)
ESX.ShowNotification("~r~Utracono połączenie z nadajnikiem ~w~" .. characterInfo)
local alpha = 250
local gpsBlip = AddBlipForCoord(coords.x, coords.y, coords.z)
SetBlipSprite(gpsBlip, 280)
SetBlipColour(gpsBlip, 3)
SetBlipAlpha(gpsBlip, alpha)
SetBlipScale(gpsBlip, 1.2)
SetBlipAsShortRange(gpsBlip, false)
SetBlipCategory(gpsBlip, 15)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString("# OSTATNIA LOKALIZACJA " .. characterInfo)
EndTextCommandSetBlipName(gpsBlip)
for i=1, 25, 1 do
PlaySound(-1, "Bomb_Disarmed", "GTAO_Speed_Convoy_Soundset", 0, 0, 1)
Wait(300)
PlaySound(-1, "OOB_Cancel", "GTAO_FM_Events_Soundset", 0, 0, 1)
Wait(300)
end
while alpha ~= 0 do
Citizen.Wait(180 * 4)
alpha = alpha - 1
SetBlipAlpha(gpsBlip, alpha)
if alpha == 0 then
RemoveBlip(gpsBlip)
return
end
end
end)
function doUpdateBlip(follow_id_key, blip_id, properties)
if blips_cache[follow_id_key].needs_server then
if not blips_cache[follow_id_key].blip_id then
RemoveBlip(blips_cache[follow_id_key].synced_blip_id)
local new_blip_id = doAddBlip(properties)
blips_cache[follow_id_key].synced_blip_id = nil
blips_cache[follow_id_key].blip_id = new_blip_id
end
if blips_cache[follow_id_key].blip_id then
if DoesBlipExist(blips_cache[follow_id_key].blip_id) then
SetBlipCoords(blip_id, properties[1] + 0.001,properties[2] + 0.001,properties[3] + 0.001)
end
end
end
end
function doAddBlip(properties)
local blip_id = AddBlipForCoord(properties[1] + 0.001,properties[2] + 0.001,properties[3] + 0.001)
setBlipProperties(blip_id, properties)
return blip_id
end
Citizen.CreateThread(function()
while PlayerData.job == nil do
Wait(100)
end
while true do
Citizen.Wait(1000)
for follow_id_key, data in pairs(blips_cache) do
if not blips_cache[follow_id_key].needs_server and not blips_cache[follow_id_key].needs_removal then
if not blips_cache[follow_id_key].synced_blip_id then
if blips_cache[follow_id_key].blip_id then
RemoveBlip(blips_cache[follow_id_key].blip_id)
blips_cache[follow_id_key].blip_id = nil
end
if DoesEntityExist(blips_cache[follow_id_key].player_ped) then
local new_blip_id = AddBlipForEntity(blips_cache[follow_id_key].player_ped)
blips_cache[follow_id_key].synced_blip_id = new_blip_id
end
end
if GetBlipFromEntity(data.player_ped) then
local blip_id = blips_cache[follow_id_key].synced_blip_id
local veh = GetVehiclePedIsIn(data.player_ped, false)
if veh ~= 0 then
SetBlipRotation(blip_id, math.ceil(GetEntityHeading(veh)))
end
setBlipProperties(blips_cache[follow_id_key].synced_blip_id, data.properties)
end
end
end
end
end)
function setBlipProperties(blip_id, properties)
while PlayerData.job == nil do
Citizen.Wait(100)
end
local current_type = GetBlipSprite(blip_id)
local current_color = GetBlipColour(blip_id)
local template_type = properties[4]
local type = Config.default_type._type
local color = Config.default_type._color
local scale = Config.default_type._scale
local alpha = Config.default_type._alpha
local show_local_indicator = Config.default_type._show_local_direction
local show_off_screen = Config.default_type._show_off_screen
local label = Config.default_type._label
if blip_types[template_type]._type then type = blip_types[template_type]._type end
if blip_types[template_type]._color then color = blip_types[template_type]._color end
if blip_types[template_type]._scale then scale = blip_types[template_type]._scale end
if blip_types[template_type]._alpha then alpha = blip_types[template_type]._alpha end
if blip_types[template_type]._show_local_direction then show_local_indicator = blip_types[template_type]._show_local_direction end
if blip_types[template_type]._show_off_screen then show_off_screen = blip_types[template_type]._show_off_screen end
if blip_types[template_type]._label then _label = blip_types[template_type]._label end
if current_type ~= type or current_color ~= color then
SetBlipSprite(blip_id, type)
SetBlipColour(blip_id, color)
SetBlipScale(blip_id, scale)
SetBlipAlpha(blip_id, alpha)
SetBlipAsShortRange(not show_off_screen)
if show_local_indicator then
ShowHeadingIndicatorOnBlip(blip_id, true)
end
if properties[4] == 'unknown' then
SetBlipHiddenOnLegend(blip_id)
BeginTextCommandSetBlipName('STRING')
AddTextComponentString('Nieznany')
EndTextCommandSetBlipName(blip_id)
else
local str = "[" .. _label .. "] ".. properties[7] .. " " .. properties[8] .. " - " .. PlayerData.job.grade_label
BeginTextCommandSetBlipName('STRING')
AddTextComponentString(str)
EndTextCommandSetBlipName(blip_id)
end
end
end |
ITEM.name = "Mica"
ITEM.model ="models/lostsignalproject/items/artefacts/mica.mdl"
ITEM.description = "A hollowed out shell of stone, with a hard, slightly rubbery black mass coating the insides."
ITEM.longdesc = "This artifact seems to be a rarer variant of the 'Slug' artifact, however the conditions under which it is formed are not known. The inner black mass seems to breathe and throb regularly, and will respond to being touched and shaken. Scientists are very interested in this specimen, as it seems to be some sort of unknown lifeform."
ITEM.width = 1
ITEM.height = 1
ITEM.price = 10750
ITEM.flag = "A"
ITEM.rarity = 5
ITEM.baseweight = 4.900
ITEM.varweight = 0.400
|
minetest.register_entity("holoemitter:entity", {
initial_properties = {},
on_step = function(self, dtime)
-- sanity checks
if not self.data or not self.data.emitterpos then
self.object:remove()
return
end
if not self.dtime then
-- set dtime
self.dtime = dtime
else
-- increment
self.dtime = self.dtime + dtime
end
if self.dtime < 2 then
-- skip check
return
end
if not holoemitter.is_active(self.data.emitterpos, self.data.session) then
self.object:remove()
return
end
end,
on_punch = function(self, puncher)
if not self.data or not self.data.emitterpos then
self.object:remove()
return
end
digilines.receptor_send(self.data.emitterpos, holoemitter.digiline_rules, "holoemitter", {
playername = puncher:get_player_name(),
action = "punch",
id = self.data.id
})
return true
end,
on_rightclick = function(self, clicker)
if not self.data or not self.data.emitterpos then
self.object:remove()
return
end
digilines.receptor_send(self.data.emitterpos, holoemitter.digiline_rules, "holoemitter", {
playername = clicker:get_player_name(),
action = "rightclick",
id = self.data.id
})
end,
get_staticdata = function(self)
return minetest.serialize(self.data)
end,
on_activate = function(self, staticdata)
self.data = minetest.deserialize(staticdata)
if not self.data then
self.object:remove()
return
end
self.object:set_properties(self.data.properties)
end
});
|
--[[
Copyright (c) 2010-2012 Matthias Richter
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.
Except as contained in this notice, the name(s) of the above copyright holders
shall not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization.
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.
]]--
local Timer = {}
Timer.__index = Timer
local function new()
return setmetatable({functions = {}}, Timer)
end
function Timer:update(dt)
local to_remove = {}
for func, delay in pairs(self.functions) do
delay = delay - dt
if delay <= 0 then
to_remove[#to_remove+1] = func
end
self.functions[func] = delay
end
for _,func in ipairs(to_remove) do
self.functions[func] = nil
func(func)
end
end
function Timer:add(delay, func)
assert(not self.functions[func], "Function already scheduled to run.")
self.functions[func] = delay
return func
end
function Timer:addPeriodic(delay, func, count)
local count = count or math.huge -- exploit below: math.huge - 1 = math.huge
return self:add(delay, function(f)
if func(func) == false then return end
count = count - 1
if count > 0 then
self:add(delay, f)
end
end)
end
function Timer:cancel(func)
self.functions[func] = nil
end
function Timer:clear()
self.functions = {}
end
local function Interpolator(length, func)
local t = 0
return function(dt, ...)
t = t + dt
return t <= length and func((t-dt)/length, ...) or nil
end
end
local function Oscillator(length, func)
local t = 0
return function(dt, ...)
t = (t + dt) % length
return func(t/length, ...)
end
end
-- default timer
local default = new()
-- the module
return setmetatable({
new = new,
update = function(...) return default:update(...) end,
add = function(...) return default:add(...) end,
addPeriodic = function(...) return default:addPeriodic(...) end,
cancel = function(...) return default:cancel(...) end,
clear = function(...) return default:clear(...) end,
Interpolator = Interpolator,
Oscillator = Oscillator
}, {__call = new})
|
--[[
Input: A length-2 table of length-K tables
Input[1]: K tables
Input[2]: K tables
Output: A length-K table of length-2 tables
Output[i]: {Input[1][i], input[2][i]}
--]]
local CrossMergeTable, parent = torch.class('nn.CrossMergeTable', 'nn.Module')
function CrossMergeTable:__init()
parent.__init(self)
self.gradInput = {}
end
function CrossMergeTable:updateOutput(input)
assert(#input == 2)
assert(#input[1] == #input[2])
self.output = {}
for i = 1, #input[1] do
self.output[i] = {input[1][i], input[2][i]}
end
return self.output
end
function CrossMergeTable:updateGradInput(input, gradOutput)
for i = 1, 2 do
if not self.gradInput[i] then
self.gradInput[i] = {}
end
end
for i = 1, #gradOutput do
self.gradInput[1][i] = gradOutput[i][1]
self.gradInput[2][i] = gradOutput[i][2]
end
return self.gradInput
end
function CrossMergeTable:__tostring__()
return string.format('%s()', torch.type(self))
end
|
-- skynet.error output
local logfile
local function write_log(file, str)
file:write(str, "\n")
file:flush()
end
-- because log service error will not write right. use xpcall for debug log service
-- if no err_msg in log/wlua.log then set `daemon = nil` in `conf/wlua.conf` .
local ok, err_msg = xpcall(function()
local skynet = require "skynet.manager"
local config = require "config"
-- is daemon
local daemon = config.get("daemon")
-- log config
local logpath = config.get("wlua_logpath")
logfile = io.open(logpath, "a+")
local auto_cutlog = config.get("wlua_auto_cutlog", true)
-- sighup commond
local sighup_file = config.get("wlua_sighup_file")
local util_date = require "util.date"
local util_file = require "util.file"
local util_string = require "util.string"
local log = require "log"
local function reopen_log()
logfile:close()
logfile = io.open(logpath, "a+")
end
local function auto_reopen_log()
-- run clear at 0:00 am
local futrue = util_date.get_next_zero() - util_date.now()
skynet.timeout(futrue * 100, auto_reopen_log)
local date_name = os.date("%Y%m%d%H%M%S", util_date.now())
local newname = string.format("%s.%s", logpath, date_name)
os.rename(logpath, newname)
reopen_log()
end
-- get time str. one second format once
local last_time = 0
local last_str_time
local function get_str_time()
local cur = util_date.now()
if last_time ~= cur then
last_str_time = os.date("%Y-%m-%d %H:%M:%S", cur)
end
return last_str_time
end
skynet.register_protocol {
name = "text",
id = skynet.PTYPE_TEXT,
unpack = skynet.tostring,
dispatch = function(_, addr, str)
local time = get_str_time()
str = string.format("[%08x][%s] %s", addr, time, str)
if not daemon then
print(str)
end
write_log(logfile, str)
end
}
-- sighup cmd functions
local SIGHUP_CMD = {}
-- cmd for stop server
function SIGHUP_CMD.stop()
-- TODO: broadcast stop signal
log.warn("Handle SIGHUP, wlua will be stop.")
skynet.sleep(100)
skynet.abort()
end
-- cmd for cut log
function SIGHUP_CMD.cutlog()
reopen_log()
end
-- cmd for reload
function SIGHUP_CMD.reload()
log.warn("Begin reload.")
skynet.call(".main", "lua", "reload")
log.warn("End reload.")
end
local function get_sighup_cmd()
local cmd = util_file.get_first_line(sighup_file)
if not cmd then
return
end
cmd = util_string.trim(cmd)
return SIGHUP_CMD[cmd]
end
-- 捕捉sighup信号(kill -1)
skynet.register_protocol {
name = "SYSTEM",
id = skynet.PTYPE_SYSTEM,
unpack = function(...) return ... end,
dispatch = function()
local func = get_sighup_cmd()
if func then
func()
else
log.error(string.format("Unknow sighup cmd, Need set sighup file. wlua_sighup_file: '%s'", sighup_file))
end
end
}
-- other skynet cmd
local CMD = {}
skynet.start(function()
skynet.register ".log"
skynet.dispatch("lua", function(_, _, cmd, ...)
local f = CMD[cmd]
if f then
skynet.ret(skynet.pack(f(...)))
else
log.error("Invalid cmd. cmd:", cmd)
end
end)
-- auto reopen log
if auto_cutlog then
local ok, msg = pcall(auto_reopen_log)
if not ok then
if not daemon then
print(msg)
end
write_log(logfile, msg)
end
end
end)
end, debug.traceback)
if not ok then
print(err_msg)
write_log(logfile, err_msg)
end
|
function read(file)
local f = assert(io.open(file, "rb"))
local content = f:read("*all")
f:close()
return content
end
rules = read("engine/cfg/test-lang-rules.txt")
words = read("engine/cfg/test-lang-words.txt")
lang = Lang.new()
lang:init_rules(rules)
lang:init_words(words)
sentence = "eat a clean apple"
end_states = {"ActionSentence", "QuestionSentence"}
print("Rules:\n")
print(rules)
print([[accepted derivations: {"ActionSentence", "QuestionSentence"}]])
print("\nparsing", sentence)
ast = lang:parse_sentence(sentence, end_states)
assert(ast, "invalid sentence")
print("sentence parse-type:", ast.end_state_name)
print("\nDerivation:")
print(ast.ast)
--print(AST.WORD)
--print(ast.ast.value.rule[1].value.tagged.ast.value.word.origin)
|
fbase_at_st = Creature:new {
objectName = "@mob/creature_names:fbase_at_st",
socialGroup = "imperial",
faction = "imperial",
level = 205,
chanceHit = 11.5,
damageMin = 1170,
damageMax = 2050,
baseXp = 20500,
baseHAM = 139000,
baseHAMmax = 200000,
armor = 3,
resists = {135,135,-1,200,200,15,15,200,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = ATTACKABLE + OVERT,
creatureBitmask = PACK + KILLER,
optionsBitmask = AIENABLED,
diet = NONE,
templates = {"object/mobile/atst.iff"},
lootGroups = {},
conversationTemplate = "",
defaultAttack = "defaultdroidattack",
defaultWeapon = "object/weapon/ranged/vehicle/vehicle_atst_ranged.iff",
}
CreatureTemplates:addCreatureTemplate(fbase_at_st, "fbase_at_st")
|
local _={}
_[1]={"error","function call \"fn\" is ambigous; may be at least either:\n\9function type dispatch ambigous.fn(a::number) (at test/tests/function type dispatch ambigous.ans:4)\n\9function type dispatch ambigous.fn(x::number) (at test/tests/function type dispatch ambigous.ans:1); at test/tests/function type dispatch ambigous.ans:7"}
return {_[1]}
--[[
{ "error", 'function call "fn" is ambigous; may be at least either:\n\tfunction type dispatch ambigous.fn(a::number) (at test/tests/function type dispatch ambigous.ans:4)\n\tfunction type dispatch ambigous.fn(x::number) (at test/tests/function type dispatch ambigous.ans:1); at test/tests/function type dispatch ambigous.ans:7' }
]]-- |
-- helper.lua
local helper = {}
local _string_table = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z'}
-- 获得随机字符串,包括字母和数字
function helper.random_string(byte)
local byte = byte or 12
local str_sum = #_string_table
local ret = ""
for i = 1, byte do
ret = ret .. _string_table[math.random(1, str_sum)]
end
return ret
end
function helper.dump(obj)
local getIndent, quoteStr, wrapKey, wrapVal, dumpObj
getIndent = function(level)
return string.rep("\t", level)
end
quoteStr = function(str)
return '"' .. string.gsub(str, '"', '\\"') .. '"'
end
wrapKey = function(val)
if type(val) == "number" then
return "[" .. val .. "]"
elseif type(val) == "string" then
return "[" .. quoteStr(val) .. "]"
else
return "[" .. tostring(val) .. "]"
end
end
wrapVal = function(val, level)
if type(val) == "table" then
return dumpObj(val, level)
elseif type(val) == "number" then
return val
elseif type(val) == "string" then
return quoteStr(val)
else
return tostring(val)
end
end
dumpObj = function(obj, level)
if type(obj) ~= "table" then
return wrapVal(obj)
end
level = level + 1
local tokens = {}
tokens[#tokens + 1] = "{"
for k, v in pairs(obj) do
tokens[#tokens + 1] = getIndent(level) .. wrapKey(k) .. " = " .. wrapVal(v, level) .. ","
end
tokens[#tokens + 1] = getIndent(level - 1) .. "}"
return table.concat(tokens, "\n")
end
return dumpObj(obj, 0)
end
return helper
|
-- @file plugin/lua_repl.lua A tool Node for building a Lua REPL in-editor
-- This file is part of Godot Lua PluginScript: https://github.com/gilzoide/godot-lua-pluginscript
--
-- Copyright (C) 2021 Gil Barbosa Reis.
--
-- 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.
local LuaREPL = {
is_tool = true,
extends = "Node",
}
local index_G = { __index = _G }
local function get_error(text)
text = tostring(text)
return 'Error: ' .. (text:match(":%d+:%s*(.+)") or text)
end
function LuaREPL:_init()
-- Local environment, to avoid messing up _G
self.env = setmetatable({
print = function(...)
return self:print(...)
end,
}, index_G)
end
-- Cache nodes
function LuaREPL:_ready()
self.output = self:get_node("Output")
self.line_edit = self:get_node("Footer/LineEdit")
end
-- Prints a line to output
function LuaREPL:print(...)
self.output:add_text(string.join('\t', ...))
self.output:add_text('\n')
end
-- Runs a line, printing the results/error
function LuaREPL:dostring(text)
self:print('> ' .. text)
text = tostring(text):gsub('^%s*%=', '', 1)
local f, err_msg = load('return ' .. text, nil, nil, self.env)
if not f then
f, err_msg = load(text, nil, nil, self.env)
end
if f then
local result = table.pack(pcall(f))
if not result[1] then
self:print(get_error(result[2]))
elseif result.n > 1 then
self:print(table.unpack(result, 2, result.n))
end
else
self:print(get_error(err_msg))
end
self.line_edit:clear()
end
-- Clear output text
function LuaREPL:clear()
self.output:clear()
end
-- Signal handlers
function LuaREPL:_on_LineEdit_text_entered(text)
self:dostring(text)
end
function LuaREPL:_on_RunButton_pressed()
self:dostring(self.line_edit.text)
end
function LuaREPL:_on_ClearButton_pressed()
self:clear()
end
return LuaREPL
|
LinkLuaModifier( "arc_warden_tempest_double_modifier", "heroes/hero_arc_warden/arc_warden_tempest_double_lua.lua", LUA_MODIFIER_MOTION_NONE )
arc_warden_tempest_double = class({})
function arc_warden_tempest_double:OnSpellStart()
local caster = self:GetCaster()
local spawn_location = caster:GetOrigin()
local health_cost = 1 - (self:GetSpecialValueFor("health_cost") / 100)
local mana_cost = 1 - (self:GetSpecialValueFor("mana_cost") / 100)
local duration = self:GetSpecialValueFor("duration")
local health_after_cast = caster:GetHealth() * mana_cost
local mana_after_cast = caster:GetMana() * health_cost
caster:SetHealth(health_after_cast)
caster:SetMana(mana_after_cast)
local double = CreateUnitByName( caster:GetUnitName(), spawn_location, true, caster, caster:GetOwner(), caster:GetTeamNumber())
double:SetControllableByPlayer(caster:GetPlayerID(), false)
local caster_level = caster:GetLevel()
for i = 2, caster_level do
double:HeroLevelUp(false)
end
for ability_id = 0, 15 do
local ability = double:GetAbilityByIndex(ability_id)
if ability then
ability:SetLevel(caster:GetAbilityByIndex(ability_id):GetLevel())
if ability:GetName() == "arc_warden_tempest_double" then
ability:SetActivated(false)
end
end
end
for item_id = 0, 5 do
local item_in_caster = caster:GetItemInSlot(item_id)
if item_in_caster ~= nil then
local item_name = item_in_caster:GetName()
if not (item_name == "item_aegis" or item_name == "item_smoke_of_deceit" or item_name == "item_recipe_refresher" or item_name == "item_refresher" or item_name == "item_ward_observer" or item_name == "item_ward_sentry") then
local item_created = CreateItem( item_in_caster:GetName(), double, double)
double:AddItem(item_created)
item_created:SetCurrentCharges(item_in_caster:GetCurrentCharges())
end
end
end
double:SetHealth(health_after_cast)
double:SetMana(mana_after_cast)
double:SetMaximumGoldBounty(0)
double:SetMinimumGoldBounty(0)
double:SetDeathXP(0)
double:SetAbilityPoints(0)
double:SetHasInventory(false)
double:SetCanSellItems(false)
double:AddNewModifier(caster, self, "arc_warden_tempest_double_modifier", nil)
double:AddNewModifier(caster, self, "modifier_kill", {["duration"] = duration})
end
arc_warden_tempest_double_modifier = class({})
function arc_warden_tempest_double_modifier:DeclareFunctions()
return {MODIFIER_PROPERTY_SUPER_ILLUSION, MODIFIER_PROPERTY_ILLUSION_LABEL, MODIFIER_PROPERTY_IS_ILLUSION, MODIFIER_EVENT_ON_TAKEDAMAGE }
end
function arc_warden_tempest_double_modifier:GetIsIllusion()
return true
end
function arc_warden_tempest_double_modifier:GetModifierSuperIllusion()
return true
end
function arc_warden_tempest_double_modifier:GetModifierIllusionLabel()
return true
end
function arc_warden_tempest_double_modifier:OnTakeDamage( event )
if event.unit:IsAlive() == false then
event.unit:MakeIllusion()
end
end
function arc_warden_tempest_double_modifier:GetStatusEffectName()
return "particles/status_fx/status_effect_ancestral_spirit.vpcf"
end
function arc_warden_tempest_double_modifier:IsHidden()
return true
end
function arc_warden_tempest_double_modifier:GetAttributes()
return MODIFIER_ATTRIBUTE_PERMANENT
end |
talus_aakuan_champion_camp_neutral_large_theater = Lair:new {
mobiles = {{"aakuan_champion",1},{"aakuan_anarchist",1},{"aakuan_assassin",1}},
spawnLimit = 15,
buildingsVeryEasy = {"object/building/poi/corellia_selonian_separatists_large1.iff","object/building/poi/corellia_selonian_separatists_large2.iff"},
buildingsEasy = {"object/building/poi/corellia_selonian_separatists_large1.iff","object/building/poi/corellia_selonian_separatists_large2.iff"},
buildingsMedium = {"object/building/poi/corellia_selonian_separatists_large1.iff","object/building/poi/corellia_selonian_separatists_large2.iff"},
buildingsHard = {"object/building/poi/corellia_selonian_separatists_large1.iff","object/building/poi/corellia_selonian_separatists_large2.iff"},
buildingsVeryHard = {"object/building/poi/corellia_selonian_separatists_large1.iff","object/building/poi/corellia_selonian_separatists_large2.iff"},
missionBuilding = "object/tangible/lair/base/objective_power_transformer.iff",
mobType = "npc",
buildingType = "theater"
}
addLairTemplate("talus_aakuan_champion_camp_neutral_large_theater", talus_aakuan_champion_camp_neutral_large_theater)
|
---------------------------------------------------------------------------------------------
-- Requirement summary:
-- [Policies] External UCS: PTU without "external_consent_status_groups" struct
-- [Policies] External UCS: PreloadedPT without "external_consent_status_groups" struct
--
-- Description:
-- In case:
-- SDL receives PolicyTableUpdate without "external_consent_status_groups:
-- [<functional_grouping>: <Boolean>]” -> of "device_data" -> "<device identifier>"
-- -> "user_consent_records" -> "<app id>" section
-- SDL must:
-- a. consider this PTU as valid (with the pre-conditions of all other valid PTU content)
-- b. do not create this "external_consent_status_groups" field of the corresponding "appID" section
-- in the Policies database.
--
-- Preconditions:
-- 1. Start SDL (make sure 'external_consent_status_groups' section is omitted in PreloadedPT)
--
-- Steps:
-- 1. Register app
-- 2. Activate app
-- 3. Perform PTU
-- 4. Verify status of update
--
-- Expected result:
-- PTU finished successfully with UP_TO_DATE status
--
-- Note: Script is designed for EXTERNAL_PROPRIETARY flow
---------------------------------------------------------------------------------------------
require('user_modules/script_runner').isTestApplicable({ { extendedPolicy = { "EXTERNAL_PROPRIETARY" } } })
--[[ General configuration parameters ]]
config.defaultProtocolVersion = 2
--[[ Required Shared Libraries ]]
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local testCasesForExternalUCS = require('user_modules/shared_testcases/testCasesForExternalUCS')
--[[ Local variables ]]
local checkedStatus = "UP_TO_DATE"
local checkedSection = "external_consent_status_groups"
local grpId = "Location-1"
--[[ General Precondition before ATF start ]]
commonFunctions:SDLForceStop()
commonSteps:DeleteLogsFileAndPolicyTable()
testCasesForExternalUCS.removePTS()
--[[ General Settings for configuration ]]
Test = require("user_modules/connecttest_resumption")
require('user_modules/AppTypes')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:ConnectMobile()
self:connectMobile()
end
function Test:StartSession()
testCasesForExternalUCS.startSession(self, 1)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:RAI()
testCasesForExternalUCS.registerApp(self, 1)
end
function Test:ActivateApp()
testCasesForExternalUCS.activateApp(self, 1, checkedStatus)
end
function Test:CheckStatus_UP_TO_DATE()
local reqId = self.hmiConnection:SendRequest("SDL.GetStatusUpdate")
EXPECT_HMIRESPONSE(reqId, { status = checkedStatus })
end
function Test.RemovePTS()
testCasesForExternalUCS.removePTS()
end
function Test:StartSession()
testCasesForExternalUCS.startSession(self, 2)
end
function Test:RAI_2()
testCasesForExternalUCS.registerApp(self, 2)
EXPECT_HMICALL("BasicCommunication.PolicyUpdate")
:Do(function(_, d) testCasesForExternalUCS.pts = testCasesForExternalUCS.createTableFromJsonFile(d.params.file) end)
end
function Test:CheckPTS()
if not testCasesForExternalUCS.pts then
self:FailTestCase("PTS was not created")
else
if testCasesForExternalUCS.pts.policy_table.functional_groupings[grpId][checkedSection] ~= nil then
self:FailTestCase("Section '" .. checkedSection .. "' was found in PTS")
else
print("Section '".. checkedSection .. "' doesn't exist in PTS")
print(" => OK")
end
end
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.StopSDL()
StopSDL()
end
return Test
|
local colors = require 'onedark.colors'
vim.cmd('highlight clear')
if vim.g.syntax_on ~= nil then
vim.cmd('syntax reset')
end
vim.cmd('set t_Co=256')
vim.g.colors_name = 'onedark'
local terminal_italics = vim.g.onedark_terminal_italics or false
local red = colors.red
local dark_red = colors.dark_red
local green = colors.green
local yellow = colors.yellow
local dark_yellow = colors.dark_yellow
local blue = colors.blue
local purple = colors.purple
local cyan = colors.cyan
local white = colors.white
local black = colors.black
local visual_black = colors.visual_black
local comment_grey = colors.comment_grey
local gutter_fg_grey = colors.gutter_fg_grey
local cursor_grey = colors.cursor_grey
local visual_grey = colors.visual_grey
local menu_grey = colors.menu_grey
local special_grey = colors.special_grey
local vertsplit = colors.vertsplit
vim.g.terminal_ansi_colors = {
black.gui, red.gui, green.gui, yellow.gui,
blue.gui, purple.gui, cyan.gui, white.gui,
visual_grey.gui, dark_red.gui, green.gui, dark_yellow.gui,
blue.gui, purple.gui, cyan.gui, comment_grey.gui,
}
local function h(group, style)
if not terminal_italics then
if style.cterm == 'italic' then
style.cterm = nil
end
if style.gui == 'italic' then
style.gui = nil
end
end
local guifg, guibg, guisp, ctermfg, ctermbg
if style.fg then
guifg = style.fg.gui
ctermfg = style.fg.cterm
else
guifg = 'NONE'
ctermfg = 'NONE'
end
if style.bg then
guibg = style.bg.gui
ctermbg = style.bg.cterm
else
guibg = 'NONE'
ctermbg = 'NONE'
end
if style.sp then
guisp = style.sp.gui
else
guisp = 'NONE'
end
local gui = style.gui or 'NONE'
local cterm = style.cterm or 'NONE'
vim.cmd('highlight ' .. group
.. ' guifg=' .. guifg
.. ' guibg=' .. guibg
.. ' guisp=' .. guisp
.. ' gui=' .. gui
.. ' ctermfg=' .. ctermfg
.. ' ctermbg=' .. ctermbg
.. ' cterm=' .. cterm
)
end
h('Comment', { fg = comment_grey, gui = 'italic', cterm = 'italic' })
h('Constant', { fg = cyan })
h('String', { fg = green })
h('Character', { fg = green })
h('Number', { fg = dark_yellow })
h('Boolean', { fg = dark_yellow })
h('Float', { fg = dark_yellow })
h('Identifier', { fg = red })
h('Function', { fg = blue })
h('Statement', { fg = purple })
h('Conditional', { fg = purple })
h('Repeat', { fg = purple })
h('Label', { fg = purple })
h('Operator', { fg = purple })
h('Keyword', { fg = red })
h('Exception', { fg = purple })
h('PreProc', { fg = yellow })
h('Include', { fg = blue })
h('Define', { fg = purple })
h('Macro', { fg = purple })
h('PreCondit', { fg = yellow })
h('Type', { fg = yellow })
h('StorageClass', { fg = yellow })
h('Structure', { fg = yellow })
h('Typedef', { fg = yellow })
h('Special', { fg = blue })
h('SpecialChar', { fg = dark_yellow })
h('Tag', { })
h('Delimiter', { })
h('SpecialComment', { fg = comment_grey })
h('Debug', { })
h('Underlined', { gui = 'underline', cterm = 'underline' })
h('Ignore', { })
h('Error', { fg = red })
h('Todo', { fg = purple })
h('ColorColumn', { bg = cursor_grey })
h('Conceal', { })
h('Cursor', { fg = black, bg = blue })
h('CursorIM', { })
h('CursorColumn', { bg = cursor_grey })
if vim.wo.diff then
h('CursorLine', { gui = 'underline' })
else
h('CursorLine', { bg = cursor_grey })
end
h('Directory', { fg = blue })
h('DiffAdd', { bg = green, fg = black })
h('DiffChange', { fg = yellow, gui = 'underline', cterm = 'underline' })
h('DiffDelete', { bg = red, fg = black })
h('DiffText', { bg = yellow, fg = black })
if vim.g.onedark_hide_endofbuffer or false then
h('EndOfBuffer', { fg = black })
end
h('ErrorMsg', { fg = red })
h('VertSplit', { fg = vertsplit })
h('Folded', { fg = comment_grey })
h('FoldColumn', { })
h('SignColumn', { })
h('IncSearch', { fg = yellow, bg = comment_grey })
h('LineNr', { fg = gutter_fg_grey })
h('CursorLineNr', { })
h('MatchParen', { fg = blue, gui = 'underline', cterm = 'underline' })
h('ModeMsg', { })
h('MoreMsg', { })
h('NonText', { fg = special_grey })
h('Normal', { fg = white, bg = black })
h('Pmenu', { bg = menu_grey })
h('PmenuSel', { fg = black, bg = blue })
h('PmenuSbar', { bg = special_grey })
h('PmenuThumb', { bg = white })
h('Question', { fg = purple })
h('QuickFixLine', { fg = black, bg = yellow })
h('Search', { fg = black, bg = yellow })
h('SpecialKey', { fg = special_grey })
h('SpellBad', { fg = red, gui = 'underline', cterm = 'underline' })
h('SpellCap', { fg = dark_yellow })
h('SpellLocal', { fg = dark_yellow })
h('SpellRare', { fg = dark_yellow })
h('StatusLine', { fg = white, bg = cursor_grey })
h('StatusLineNC', { fg = comment_grey })
h('StatusLineTerm', { fg = white, bg = cursor_grey })
h('StatusLineTermNC', { fg = comment_grey })
h('TabLine', { fg = comment_grey })
h('TabLineFill', { })
h('TabLineSel', { fg = white })
h('Terminal', { fg = white, bg = black })
h('Title', { fg = green })
h('Visual', { fg = visual_black, bg = visual_grey })
h('VisualNOS', { bg = visual_grey })
h('WarningMsg', { fg = yellow })
h('WildMenu', { fg = black, bg = blue })
-- Termdebug
h('debugPC', { bg = special_grey })
h('debugBreakpoint', { fg = black, bg = red })
-- CSS
h('cssAttrComma', { fg = purple })
h('cssAttributeSelector', { fg = green })
h('cssBraces', { fg = white })
h('cssClassName', { fg = dark_yellow })
h('cssClassNameDot', { fg = dark_yellow })
h('cssDefinition', { fg = purple })
h('cssFontAttr', { fg = dark_yellow })
h('cssFontDescriptor', { fg = purple })
h('cssFunctionName', { fg = blue })
h('cssIdentifier', { fg = blue })
h('cssImportant', { fg = purple })
h('cssInclude', { fg = white })
h('cssIncludeKeyword', { fg = purple })
h('cssMediaType', { fg = dark_yellow })
h('cssProp', { fg = white })
h('cssPseudoClassId', { fg = dark_yellow })
h('cssSelectorOp', { fg = purple })
h('cssSelectorOp2', { fg = purple })
h('cssTagName', { fg = red })
-- Fish Shell
h('fishKeyword', { fg = purple })
h('fishConditional', { fg = purple })
-- Go
h('goDeclaration', { fg = purple })
h('goBuiltins', { fg = cyan })
h('goFunctionCall', { fg = blue })
h('goVarDefs', { fg = red })
h('goVarAssign', { fg = red })
h('goVar', { fg = purple })
h('goConst', { fg = purple })
h('goType', { fg = yellow })
h('goTypeName', { fg = yellow })
h('goDeclType', { fg = cyan })
h('goTypeDecl', { fg = purple })
-- HTML (keep consistent with Markdown, below)
h('htmlArg', { fg = dark_yellow })
h('htmlBold', { fg = dark_yellow, gui = 'bold', cterm = 'bold' })
h('htmlEndTag', { fg = white })
h('htmlH1', { fg = red })
h('htmlH2', { fg = red })
h('htmlH3', { fg = red })
h('htmlH4', { fg = red })
h('htmlH5', { fg = red })
h('htmlH6', { fg = red })
h('htmlItalic', { fg = purple, gui = 'italic', cterm = 'italic' })
h('htmlLink', { fg = cyan, gui = 'underline', cterm = 'underline' })
h('htmlSpecialChar', { fg = dark_yellow })
h('htmlSpecialTagName', { fg = red })
h('htmlTag', { fg = white })
h('htmlTagN', { fg = red })
h('htmlTagName', { fg = red })
h('htmlTitle', { fg = white })
-- JavaScript
h('javaScriptBraces', { fg = white })
h('javaScriptFunction', { fg = purple })
h('javaScriptIdentifier', { fg = purple })
h('javaScriptNull', { fg = dark_yellow })
h('javaScriptNumber', { fg = dark_yellow })
h('javaScriptRequire', { fg = cyan })
h('javaScriptReserved', { fg = purple })
-- http//github.com/pangloss/vim-javascript
h('jsArrowFunction', { fg = purple })
h('jsClassKeyword', { fg = purple })
h('jsClassMethodType', { fg = purple })
h('jsDocParam', { fg = blue })
h('jsDocTags', { fg = purple })
h('jsExport', { fg = purple })
h('jsExportDefault', { fg = purple })
h('jsExtendsKeyword', { fg = purple })
h('jsFrom', { fg = purple })
h('jsFuncCall', { fg = blue })
h('jsFunction', { fg = purple })
h('jsGenerator', { fg = yellow })
h('jsGlobalObjects', { fg = yellow })
h('jsImport', { fg = purple })
h('jsModuleAs', { fg = purple })
h('jsModuleWords', { fg = purple })
h('jsModules', { fg = purple })
h('jsNull', { fg = dark_yellow })
h('jsOperator', { fg = purple })
h('jsStorageClass', { fg = purple })
h('jsSuper', { fg = red })
h('jsTemplateBraces', { fg = dark_red })
h('jsTemplateVar', { fg = green })
h('jsThis', { fg = red })
h('jsUndefined', { fg = dark_yellow })
-- http//github.com/othree/yajs.vim
h('javascriptArrowFunc', { fg = purple })
h('javascriptClassExtends', { fg = purple })
h('javascriptClassKeyword', { fg = purple })
h('javascriptDocNotation', { fg = purple })
h('javascriptDocParamName', { fg = blue })
h('javascriptDocTags', { fg = purple })
h('javascriptEndColons', { fg = white })
h('javascriptExport', { fg = purple })
h('javascriptFuncArg', { fg = white })
h('javascriptFuncKeyword', { fg = purple })
h('javascriptIdentifier', { fg = red })
h('javascriptImport', { fg = purple })
h('javascriptMethodName', { fg = white })
h('javascriptObjectLabel', { fg = white })
h('javascriptOpSymbol', { fg = cyan })
h('javascriptOpSymbols', { fg = cyan })
h('javascriptPropertyName', { fg = green })
h('javascriptTemplateSB', { fg = dark_red })
h('javascriptVariable', { fg = purple })
-- JSON
h('jsonCommentError', { fg = white })
h('jsonKeyword', { fg = red })
h('jsonBoolean', { fg = dark_yellow })
h('jsonNumber', { fg = dark_yellow })
h('jsonQuote', { fg = white })
h('jsonMissingCommaError', { fg = red, gui = 'reverse' })
h('jsonNoQuotesError', { fg = red, gui = 'reverse' })
h('jsonNumError', { fg = red, gui = 'reverse' })
h('jsonString', { fg = green })
h('jsonStringSQError', { fg = red, gui = 'reverse' })
h('jsonSemicolonError', { fg = red, gui = 'reverse' })
-- LESS
h('lessVariable', { fg = purple })
h('lessAmpersandChar', { fg = white })
h('lessClass', { fg = dark_yellow })
-- Markdown (keep consistent with HTML, above)
h('markdownBlockquote', { fg = comment_grey })
h('markdownBold', { fg = dark_yellow, gui = 'bold', cterm = 'bold' })
h('markdownCode', { fg = green })
h('markdownCodeBlock', { fg = green })
h('markdownCodeDelimiter', { fg = green })
h('markdownH1', { fg = red })
h('markdownH2', { fg = red })
h('markdownH3', { fg = red })
h('markdownH4', { fg = red })
h('markdownH5', { fg = red })
h('markdownH6', { fg = red })
h('markdownHeadingDelimiter', { fg = red })
h('markdownHeadingRule', { fg = comment_grey })
h('markdownId', { fg = purple })
h('markdownIdDeclaration', { fg = blue })
h('markdownIdDelimiter', { fg = purple })
h('markdownItalic', { fg = purple, gui = 'italic', cterm = 'italic' })
h('markdownLinkDelimiter', { fg = purple })
h('markdownLinkText', { fg = blue })
h('markdownListMarker', { fg = red })
h('markdownOrderedListMarker', { fg = red })
h('markdownRule', { fg = comment_grey })
h('markdownUrl', { fg = cyan, gui = 'underline', cterm = 'underline' })
-- Perl
h('perlFiledescRead', { fg = green })
h('perlFunction', { fg = purple })
h('perlMatchStartEnd', { fg = blue })
h('perlMethod', { fg = purple })
h('perlPOD', { fg = comment_grey })
h('perlSharpBang', { fg = comment_grey })
h('perlSpecialString', { fg = dark_yellow })
h('perlStatementFiledesc', { fg = red })
h('perlStatementFlow', { fg = red })
h('perlStatementInclude', { fg = purple })
h('perlStatementScalar', { fg = purple })
h('perlStatementStorage', { fg = purple })
h('perlSubName', { fg = yellow })
h('perlVarPlain', { fg = blue })
-- PHP
h('phpVarSelector', { fg = red })
h('phpOperator', { fg = white })
h('phpParent', { fg = white })
h('phpMemberSelector', { fg = white })
h('phpType', { fg = purple })
h('phpKeyword', { fg = purple })
h('phpClass', { fg = yellow })
h('phpUseClass', { fg = white })
h('phpUseAlias', { fg = white })
h('phpInclude', { fg = purple })
h('phpClassExtends', { fg = green })
h('phpDocTags', { fg = white })
h('phpFunction', { fg = blue })
h('phpFunctions', { fg = cyan })
h('phpMethodsVar', { fg = dark_yellow })
h('phpMagicConstants', { fg = dark_yellow })
h('phpSuperglobals', { fg = red })
h('phpConstants', { fg = dark_yellow })
-- Ruby
h('rubyBlockParameter', { fg = red})
h('rubyBlockParameterList', { fg = red })
h('rubyClass', { fg = purple})
h('rubyConstant', { fg = yellow})
h('rubyControl', { fg = purple })
h('rubyEscape', { fg = red})
h('rubyFunction', { fg = blue})
h('rubyGlobalVariable', { fg = red})
h('rubyInclude', { fg = blue})
h('rubyIncluderubyGlobalVariable', { fg = red})
h('rubyInstanceVariable', { fg = red})
h('rubyInterpolation', { fg = cyan })
h('rubyInterpolationDelimiter', { fg = red })
h('rubyInterpolationDelimiter', { fg = red})
h('rubyRegexp', { fg = cyan})
h('rubyRegexpDelimiter', { fg = cyan})
h('rubyStringDelimiter', { fg = green})
h('rubySymbol', { fg = cyan})
-- Sass
-- http//github.com/tpope/vim-haml
h('sassAmpersand', { fg = red })
h('sassClass', { fg = dark_yellow })
h('sassControl', { fg = purple })
h('sassExtend', { fg = purple })
h('sassFor', { fg = white })
h('sassFunction', { fg = cyan })
h('sassId', { fg = blue })
h('sassInclude', { fg = purple })
h('sassMedia', { fg = purple })
h('sassMediaOperators', { fg = white })
h('sassMixin', { fg = purple })
h('sassMixinName', { fg = blue })
h('sassMixing', { fg = purple })
h('sassVariable', { fg = purple })
-- http//github.com/cakebaker/scss-syntax.vim
h('scssExtend', { fg = purple })
h('scssImport', { fg = purple })
h('scssInclude', { fg = purple })
h('scssMixin', { fg = purple })
h('scssSelectorName', { fg = dark_yellow })
h('scssVariable', { fg = purple })
-- TeX
h('texStatement', { fg = purple })
h('texSubscripts', { fg = dark_yellow })
h('texSuperscripts', { fg = dark_yellow })
h('texTodo', { fg = dark_red })
h('texBeginEnd', { fg = purple })
h('texBeginEndName', { fg = blue })
h('texMathMatcher', { fg = blue })
h('texMathDelim', { fg = blue })
h('texDelimiter', { fg = dark_yellow })
h('texSpecialChar', { fg = dark_yellow })
h('texCite', { fg = blue })
h('texRefZone', { fg = blue })
-- TypeScript
h('typescriptReserved', { fg = purple })
h('typescriptEndColons', { fg = white })
h('typescriptBraces', { fg = white })
-- XML
h('xmlAttrib', { fg = dark_yellow })
h('xmlEndTag', { fg = red })
h('xmlTag', { fg = red })
h('xmlTagName', { fg = red })
-- airblade/vim-gitgutter
h("GitGutterAdd", { fg = green })
h("GitGutterChange", { fg = yellow })
h("GitGutterDelete", { fg = red })
-- dense-analysis/ale
h('ALEError', { fg = red, gui = 'underline', cterm = 'underline' })
h('ALEWarning', { fg = yellow, gui = 'underline', cterm = 'underline'})
h('ALEInfo', { gui = 'underline', cterm = 'underline'})
-- easymotion/vim-easymotion
h('EasyMotionTarget', { fg = red, gui = 'bold', cterm = 'bold' })
h('EasyMotionTarget2First', { fg = yellow, gui = 'bold', cterm = 'bold' })
h('EasyMotionTarget2Second', { fg = dark_yellow, gui = 'bold', cterm = 'bold' })
h('EasyMotionShade', { fg = comment_grey })
-- lewis6991/gitsigns.nvim
vim.cmd('hi link GitSignsAdd GitGutterAdd')
vim.cmd('hi link GitSignsChange GitGutterChange')
vim.cmd('hi link GitSignsDelete GitGutterDelete')
-- mhinz/vim-signify
vim.cmd('hi link SignifySignAdd GitGutterAdd')
vim.cmd('hi link SignifySignChange GitGutterChange')
vim.cmd('hi link SignifySignDelete GitGutterDelete')
-- neomake/neomake
h('NeomakeWarningSign', { fg = yellow })
h('NeomakeErrorSign', { fg = red })
h('NeomakeInfoSign', { fg = blue })
-- plasticboy/vim-markdown (keep consistent with Markdown, above)
h('mkdDelimiter', { fg = purple })
h('mkdHeading', { fg = red })
h('mkdLink', { fg = blue })
h('mkdURL', { fg = cyan, gui = 'underline', cterm = 'underline' })
-- prabirshrestha/vim-lsp
h("LspError", { fg = red })
h("LspWarning", { fg = yellow })
h("LspInformation", { fg = blue })
h("LspHint", { fg = cyan })
-- tpope/vim-fugitive
h('diffAdded', { fg = green })
h('diffRemoved', { fg = red })
-- Git Highlighting
h('gitcommitComment', { fg = comment_grey })
h('gitcommitUnmerged', { fg = green })
h('gitcommitOnBranch', { })
h('gitcommitBranch', { fg = purple })
h('gitcommitDiscardedType', { fg = red })
h('gitcommitSelectedType', { fg = green })
h('gitcommitHeader', { })
h('gitcommitUntrackedFile', { fg = cyan })
h('gitcommitDiscardedFile', { fg = red })
h('gitcommitSelectedFile', { fg = green })
h('gitcommitUnmergedFile', { fg = yellow })
h('gitcommitFile', { })
h('gitcommitSummary', { fg = white })
h('gitcommitOverflow', { fg = red })
vim.cmd('hi link gitcommitNoBranch gitcommitBranch')
vim.cmd('hi link gitcommitUntracked gitcommitComment')
vim.cmd('hi link gitcommitDiscarded gitcommitComment')
vim.cmd('hi link gitcommitSelected gitcommitComment')
vim.cmd('hi link gitcommitDiscardedArrow gitcommitDiscardedFile')
vim.cmd('hi link gitcommitSelectedArrow gitcommitSelectedFile')
vim.cmd('hi link gitcommitUnmergedArrow gitcommitUnmergedFile')
-- Neovim terminal colors
vim.g.terminal_color_0 = black.gui
vim.g.terminal_color_1 = red.gui
vim.g.terminal_color_2 = green.gui
vim.g.terminal_color_3 = yellow.gui
vim.g.terminal_color_4 = blue.gui
vim.g.terminal_color_5 = purple.gui
vim.g.terminal_color_6 = cyan.gui
vim.g.terminal_color_7 = white.gui
vim.g.terminal_color_8 = visual_grey.gui
vim.g.terminal_color_9 = dark_red.gui
vim.g.terminal_color_10 = green.gui
vim.g.terminal_color_11 = dark_yellow.gui
vim.g.terminal_color_12 = blue.gui
vim.g.terminal_color_13 = purple.gui
vim.g.terminal_color_14 = cyan.gui
vim.g.terminal_color_15 = comment_grey.gui
vim.g.terminal_color_background = vim.g.terminal_color_0
vim.g.terminal_color_foreground = vim.g.terminal_color_7
-- Neovim LSP colors
if vim.diagnostic then
h('DiagnosticError', { fg = red })
h('DiagnosticWarn', { fg = yellow })
h('DiagnosticInfo', { fg = blue })
h('DiagnosticHint', { fg = cyan })
h('DiagnosticUnderlineError', { fg = red, gui = 'underline', cterm = 'underline' })
h('DiagnosticUnderlineWarn', { fg = yellow, gui = 'underline', cterm = 'underline' })
h('DiagnosticUnderlineInfo', { fg = blue, gui = 'underline', cterm = 'underline' })
h('DiagnosticUnderlineHint', { fg = cyan, gui = 'underline', cterm = 'underline' })
h('DiagnosticSignError', { fg = red })
h('DiagnosticSignWarn', { fg = yellow })
h('DiagnosticSignInfo', { fg = blue })
h('DiagnosticSignHint', { fg = cyan })
h('DiagnosticVirtualTextError', { fg = red, bg = cursor_grey })
h('DiagnosticVirtualTextWarn', { fg = yellow, bg = cursor_grey })
h('DiagnosticVirtualTextInfo', { fg = blue, bg = cursor_grey })
h('DiagnosticVirtualTextHint', { fg = cyan, bg = cursor_grey })
else
h('LspDiagnosticsDefaultError', { fg = red })
h('LspDiagnosticsDefaultWarning', { fg = yellow })
h('LspDiagnosticsDefaultInformation', { fg = blue })
h('LspDiagnosticsDefaultHint', { fg = cyan })
h('LspDiagnosticsUnderlineError', { fg = red, gui = 'underline', cterm = 'underline' })
h('LspDiagnosticsUnderlineWarning', { fg = yellow, gui = 'underline', cterm = 'underline' })
h('LspDiagnosticsUnderlineInformation', { fg = blue, gui = 'underline', cterm = 'underline' })
h('LspDiagnosticsUnderlineHint', { fg = cyan, gui = 'underline', cterm = 'underline' })
h('LspDiagnosticsSignError', { fg = red })
h('LspDiagnosticsSignWarning', { fg = yellow })
h('LspDiagnosticsSignInformation', { fg = blue })
h('LspDiagnosticsSignHint', { fg = cyan })
h('LspDiagnosticsVirtualTextError', { fg = red, bg = cursor_grey })
h('LspDiagnosticsVirtualTextWarning', { fg = yellow, bg = cursor_grey })
h('LspDiagnosticsVirtualTextInformation', { fg = blue, bg = cursor_grey })
h('LspDiagnosticsVirtualTextHint', { fg = cyan, bg = cursor_grey })
end
vim.o.background = 'dark'
|
local colouriser = require("arshamiser.colouriser")
local palette = require("arshamiser.palette")
colouriser.setup(palette.dark, "arshamiser_dark")
-- selene: allow(global_usage)
_G.CURRENT_PALETTE = palette.dark
|
local sickle = Action()
function sickle.onUse(player, item, fromPosition, target, toPosition, isHotkey)
return ActionsLib.useSickle(player, item, fromPosition, target, toPosition, isHotkey)
or ActionsLib.destroyItem(player, target, toPosition)
end
sickle:id(3293, 3306, 32595)
sickle:register()
|
--[[
********************************
* *
* The Moon Project *
* *
********************************
This software is provided as free and open source by the
staff of The Moon Project, in accordance with
the GPL license. This means we provide the software we have
created freely and it has been thoroughly tested to work for
the developers, but NO GUARANTEE is made it will work for you
as well. Please give credit where credit is due, if modifying,
redistributing and/or using this software. Thank you.
Staff of Moon Project, Feb 2008
~~End of License Agreement
--Moon April 2008]]
function SunbladeMagister_OnCombat(Unit, Event)
Unit:RegisterAIUpdateEvent(3000)
end
function SunbladeMagister_Frostbolt(Unit, Event)
local plr = Unit:GetRandomPlayer(1)
if(plr) then
Unit:FullCastSpellOnTarget(46035, plr)
end
end
function SunbladeMagister_ArcaneNova(Unit)
local arcaneflip = math.random(6)
local plr = Unit:GetRandomPlayer(7)
if((arcaneflip == 1) and (plr ~= nil)) then
Unit:FullCastSpellOnTarget(46036, plr)
else
end
end
function SunbladeMagister_OnLeaveCombat(Unit)
Unit:RemoveEvents()
Unit:RemoveAIUpdateEvent()
end
function SunbladeMagister_OnDied(Unit)
Unit:RemoveEvents()
Unit:RemoveAIUpdateEvent()
end
RegisterUnitEvent(24685, 1, "SunbladeMagister_OnCombat")
RegisterUnitEvent(24685, 21,"SunbladeMagister_Frostbolt")
RegisterUnitEvent(24685, 21,"SunbladeMagister_ArcaneNova")
RegisterUnitEvent(24685, 2, "SunbladeMagister_OnLeaveCombat")
RegisterUnitEvent(24685, 4, "SunbladeMagister_OnDied") |
-- Copyright (c) Sony Computer Entertainment America LLC.
-- All rights Reserved.
--
-- Master Premake configuration script, included by all solution scripts.
--
sdk = {}
--
-- Locate the top of the SDK source tree, making the hardcoded assumption
-- that it is two levels above the location of this script.
--
sdk.rootdir = path.getabsolute("../..")
--
-- Well-known locations in the tree.
--
sdk.bindir = path.join(sdk.rootdir, "bin/%{sdk.platform(cfg)}")
sdk.libdir = path.join(sdk.rootdir, "lib/%{sdk.platform(cfg)}")
sdk.objdir = path.join(sdk.rootdir, "tmp/%{sdk.platform(cfg)}/%{prj.name}")
--
-- Sony-specific configurations (for use with the configurations function).
--
sdk.DEBUG = "Debug"
sdk.DEVELOPMENT = "Development"
sdk.PROFILE = "Profile"
sdk.RELEASE = "Release"
--
-- Sony-specific platforms (for use with the platforms function).
--
sdk.WIN32_DLL_DCRT = "Win32 DLL DCRT"
sdk.WIN32_STATIC_DCRT = "Win32 Static DCRT"
sdk.WIN32_STATIC_SCRT = "Win32 Static SCRT"
sdk.WIN64_DLL_DCRT = "Win64 DLL DCRT"
sdk.WIN64_STATIC_DCRT = "Win64 Static DCRT"
sdk.WIN64_STATIC_SCRT = "Win64 Static SCRT"
filter { "platforms:Win32 * or Win64 *" }
system "Windows"
filter { "platforms:Win32 *" }
architecture "x32"
filter { "platforms:Win64 *" }
architecture "x64"
--
-- Extend Premake's solution function to configure the default set of build
-- configurations and platforms.
--
function sdk_solution(name)
local action = sdk.cleanaction()
local sln = solution(name)
filename (name .. "_" .. (action or ""))
return sln
end
--
-- Extend Premake's project function to provide the default SDK configuration,
-- such as output and include directories.
--
function sdk_project(name)
local prj = project(name)
-- Prevent collisions between projects with the same file extensions.
-- VS 2008 and 2010 got there first, so those remain undecorated. All
-- other versions get a version suffix.
local action = sdk.cleanaction()
if action:startswith("vs") and action ~= "vs2008" and action ~= "vs2010" then
if not prj.name:find(action) then
filename (name .. "_" .. action)
end
end
-- Remove all solution configurations and platforms; start with a clean slate.
removeconfigurations { "*" }
removeplatforms { "*" }
-- The default location for an sdk project is in a /build subdirectory
-- in the same folder as the source .lua file. This can be changed
-- via sdk_build_location (to move the /build directory), or sdk_location
-- (to remove it all together but preserve Imogen .target file locations).
sdk_build_location(".")
premake.api.deprecations("off")
language "C++"
flags { "FatalWarnings", "NoRuntimeChecks" }
warnings "Extra"
-- set the default output paths for all projects
targetdir(sdk.bindir)
objdir(sdk.objdir)
-- The /component root folder is always included
--includedirs { path.join(sdk.rootdir, "components") }
filter { "kind:SharedLib" }
implibdir(sdk.libdir)
filter { "kind:StaticLib" }
targetdir(sdk.libdir)
-- Avoid link issues on build server; see PREMAKE-15
filter { "action:vs2008" }
flags "NoImplicitLink"
-- Describe the build configurations
filter { "Debug" }
flags { "Symbols" }
defines { "_DEBUG", "DEBUG", "WWS_BUILD_DEBUG", "WWS_ASSERTS_ENABLED=1", "WWS_MINIMUM_LOG_LEVEL_COMPILE_TIME=kWwsLogDebug" }
filter { "Development" }
flags { "Symbols" }
defines { "NDEBUG", "WWS_BUILD_DEVELOPMENT", "WWS_ASSERTS_ENABLED=1", "WWS_MINIMUM_LOG_LEVEL_COMPILE_TIME=kWwsLogDebug" }
optimize "Speed"
filter { "Profile" }
flags { "Symbols" }
defines { "NDEBUG", "WWS_BUILD_PROFILE", "WWS_ASSERTS_ENABLED=0", "WWS_MINIMUM_LOG_LEVEL_COMPILE_TIME=kWwsLogDisable" }
optimize "Speed"
filter { "Release" }
flags { "Symbols" }
defines { "NDEBUG", "WWS_BUILD_RELEASE", "WWS_ASSERTS_ENABLED=0", "WWS_MINIMUM_LOG_LEVEL_COMPILE_TIME=kWwsLogDisable" }
optimize "Speed"
-- Windows configuration
filter { "platforms:Win32 * or Win64 *" }
flags { "NoIncrementalLink" }
defines { "WIN32", "_WIN32", "_WINDOWS", "_MBCS", "_CRT_SECURE_NO_WARNINGS", "_CRT_SECURE_NO_DEPRECATE" }
debugformat "C7"
filter { "platforms:Win64 *" }
defines { "WIN64", "_WIN64" }
filter { "platforms:* DLL *" }
defines { "WWS_TARGET_LINK_DYNAMIC" }
filter { "platforms:* SCRT" }
flags { "StaticRuntime" }
filter { "kind:SharedLib", "platforms:* DLL *" }
defines { "_USRDLL", "_WINDLL" }
filter { "kind:StaticLib or SharedLib", "system:Windows" }
targetprefix("lib")
-- Clear context and done
premake.api.deprecations(iif(_OPTIONS.fataldeprecations, "error", "on"))
filter {}
return prj
end
--
-- Sets the location for the project in the form of /build/{project name}.
-- The loc parameter should be the desired location of the /build directory
-- relative to the source .lua file.
--
function sdk_build_location(loc)
loc = path.getabsolute(path.join(_SCRIPT_DIR, loc))
loc = path.join(loc, "build/%{prj.name}")
sdk_location(loc)
end
--
-- Extend Premake's location function to properly handle Imogen .target file
-- location. The loc parameter should be the desired location of the project
-- file relative to the source .lua file.
--
function sdk_location(loc)
location(loc)
end
--
-- Extend Premake's kind function to provide target specific configuration values,
-- like defines and compiler flags.
--
function sdk_kind(value)
value = value:lower()
if value == "library" then
kind("StaticLib")
filter { "platforms:* DLL *" }
kind("SharedLib")
else
kind(value)
end
filter {}
end
--
-- Translate Premake's action name into the appropriate Imogen compatible version.
--
function sdk.imogenaction()
local action = sdk.cleanaction()
local map = {
vs2005 = "vc80",
vs2008 = "vc90",
vs2010 = "vc100",
vs2012 = "vc110",
vs2013 = "vc120",
}
return (map[action] or "")
end
--
-- Translates the human-readable Premake platform into the right Imogen
-- compatible replacement.
--
function sdk.platform(cfg)
local action = sdk.cleanaction()
-- convert spaces to underscores and make lowercase
local platform = cfg.platform or ""
platform = platform:gsub(" ", "_")
platform = platform:lower()
platform = platform .. "_" .. sdk.imogenaction()
if cfg.buildcfg then
platform = platform .. "_" .. cfg.buildcfg:lower()
end
return platform
end
--
-- Returns the action name without any 'ng' suffix
-- TODO: this can go away once everyone is switched off the old names
--
function sdk.cleanaction()
local action = _ACTION
if action:endswith("ng") then
action = action:sub(1, -3)
end
return action
end
--
-- Check for a custom configuration script at the top of the SDK tree.
--
local local_config = "../../local_config.lua"
if os.isfile(local_config) then
include(local_config)
end
--
-- Common platform groups (for use with the platforms function). Needs to be
-- built after customization script has run in case any of the configurations
-- or platforms are turned off there.
--
sdk.CONFIGS_ALL = { sdk.DEBUG, sdk.DEVELOPMENT, sdk.PROFILE, sdk.RELEASE }
sdk.WIN32_ALL = { sdk.WIN32_DLL_DCRT, sdk.WIN32_STATIC_DCRT, sdk.WIN32_STATIC_SCRT }
sdk.WIN64_ALL = { sdk.WIN64_DLL_DCRT, sdk.WIN64_STATIC_DCRT, sdk.WIN64_STATIC_SCRT }
sdk.WIN_DLL_ALL = { sdk.WIN32_DLL_DCRT, sdk.WIN64_DLL_DCRT }
sdk.WIN_STATIC_ALL = { sdk.WIN32_STATIC_DCRT, sdk.WIN32_STATIC_SCRT, sdk.WIN64_STATIC_DCRT, sdk.WIN64_STATIC_SCRT }
sdk.WIN_SCRT_ALL = { sdk.WIN32_STATIC_SCRT, sdk.WIN64_STATIC_SCRT }
sdk.WIN_DCRT_ALL = { sdk.WIN32_STATIC_DCRT, sdk.WIN64_STATIC_DCRT }
sdk.WIN_ALL = { sdk.WIN32_ALL, sdk.WIN64_ALL }
sdk.PLATFORMS_ALL = { sdk.WIN_ALL }
--
-- Allow the configuration and platform lists to be overridden on the command
-- line. Processed after the groups are built so those symbols can be used
-- as part of the argument lists.
--
newoption {
trigger = "configs",
value = "symbols",
description = "Choose a subset of build configurations",
}
newoption {
trigger = "platforms",
value = "symbols",
description = "Choose a subset of build platforms",
}
function sdk.customize(defaultList, userList)
if userList then
-- get a flat list of all possible values
local possible = table.flatten(defaultList)
-- turn user's list into a flat list of allowed values
userList = userList:explode(",")
local allowed = {}
table.foreachi(userList, function(symbol)
local item = sdk[symbol:upper()]
if not item then
error(string.format("No such configuration '%s'", symbol), 0)
end
if type(item) == "table" then
allowed = table.join(allowed, table.flatten(item))
else
table.insert(allowed, item)
end
end)
-- set all disallowed SDK configuration tokens to nil
for key, value in pairs(sdk) do
if table.contains(possible, value) and not table.contains(allowed, value) then
sdk[key] = nil
end
end
-- remove disallowed symbols from all configuration groups
function purge(list)
local n = #list
for i = n, 1, -1 do
local item = list[i]
if type(item) == "table" then
purge(item)
elseif item then
if not table.contains(allowed, item) then
table.remove(list, i)
end
end
end
end
purge(defaultList)
end
end
sdk.customize(sdk.CONFIGS_ALL, _OPTIONS.configs)
sdk.customize(sdk.PLATFORMS_ALL, _OPTIONS.platforms)
--
-- Command line argument to treat deprecation warnings as errors, to make it
-- a little easier to track them down.
--
newoption {
trigger = "fataldeprecations",
description = "Treat deprecation warnings as errors",
}
--
-- Add the wws_premake version information to generated projects.
--
_WWS_PREMAKE_VERSION = _WWS_PREMAKE_VERSION or os.getenv("_WWS_PREMAKE_VERSION")
if _WWS_PREMAKE_VERSION == "" or _WWS_PREMAKE_VERSION == "no" then
_WWS_PREMAKE_VERSION = false
end
if _WWS_PREMAKE_VERSION == nil then
_WWS_PREMAKE_VERSION = "wws_premake"
-- grab the component version
local f = io.open("wws_premake.component")
if f then
local t = f:read("*all")
t:gsub("<version>(.-)</version>", function(c)
_WWS_PREMAKE_VERSION = _WWS_PREMAKE_VERSION .. " " .. c
end, 1)
f:close()
end
-- see if I can grab SVN information too. Requires a command line client
local br, rev
local i = os.outputof('svn info .')
i:gsub("Relative URL: (.-)\n", function(c) br = c end)
i:gsub("Last Changed Rev: (.-)\n", function(c) rev = c end)
if br and rev then
i = string.format(" (SVN %s r%s)", br, rev)
_WWS_PREMAKE_VERSION = _WWS_PREMAKE_VERSION .. i
end
end
local function xmlDeclaration(base)
base()
if _WWS_PREMAKE_VERSION then
_p('<!-- %s -->', _WWS_PREMAKE_VERSION)
end
end
if _ACTION ~= "test" then
premake.override(premake.vstudio.vc2010, "xmlDeclaration", xmlDeclaration)
premake.override(premake.vstudio.cs2005, "xmlDeclaration", xmlDeclaration)
premake.override(premake.make, "header", function(base, target)
if _WWS_PREMAKE_VERSION then
_p('# %s', _WWS_PREMAKE_VERSION)
end
base(target)
end)
end
|
function nut.char.create(data, callback)
local timeStamp = os.date("%Y-%m-%d %H:%M:%S", os.time())
data.money = data.money or nut.config.get("defMoney", 0)
nut.db.insertTable({
_name = data.name or "",
_desc = data.desc or "",
_model = data.model or "models/error.mdl",
_schema = SCHEMA and SCHEMA.folder or "nutscript",
_createTime = timeStamp,
_lastJoinTime = timeStamp,
_steamID = data.steamID,
_faction = data.faction or "Unknown",
_money = data.money,
_data = data.data
}, function(_, charID)
local client
for k, v in ipairs(player.GetAll()) do
if (v:SteamID64() == data.steamID) then
client = v
break
end
end
local character = nut.char.new(data, charID, client, data.steamID)
character.vars.inv = {}
hook.Run("CreateDefaultInventory", character)
:next(function(inventory)
character.vars.inv[1] = inventory
nut.char.loaded[charID] = character
if (callback) then
callback(charID)
end
end)
end)
end
function nut.char.restore(client, callback, noCache, id)
local steamID64 = client:SteamID64()
local fields = {"_id"}
for _, var in pairs(nut.char.vars) do
if (var.field) then
fields[#fields + 1] = var.field
end
end
fields = table.concat(fields, ", ")
local condition = "_schema = '"..nut.db.escape(SCHEMA.folder)
.."' AND _steamID = "..steamID64
if (id) then
condition = condition.." AND _id = "..id
end
local query = "SELECT "..fields.." FROM nut_characters WHERE "..condition
nut.db.query(query, function(data)
local characters = {}
local results = data or {}
local done = 0
if (#results == 0) then
if (callback) then
callback(characters)
end
return
end
for k, v in ipairs(results) do
local id = tonumber(v._id)
if (not id) then
ErrorNoHalt(
"[NutScript] Attempt to load character '"
..(data._name or "nil").."' with invalid ID!"
)
continue
end
local data = {}
for k2, v2 in pairs(nut.char.vars) do
if (v2.field and v[v2.field]) then
local value = tostring(v[v2.field])
if (type(v2.default) == "number") then
value = tonumber(value) or v2.default
elseif (type(v2.default) == "boolean") then
value = tobool(value)
elseif (type(v2.default) == "table") then
value = util.JSONToTable(value)
end
data[k2] = value
end
end
characters[#characters + 1] = id
local character = nut.char.new(data, id, client)
hook.Run("CharacterRestored", character)
character.vars.inv = {}
nut.inventory.loadAllFromCharID(id)
-- Try to get a default inventory if one does not exist.
:next(function(inventories)
if (#inventories == 0) then
local promise =
hook.Run("CreateDefaultInventory", character)
assert(
promise ~= nil,
"No default inventory available"
)
return promise:next(function(inventory)
assert(
inventory ~= nil,
"No default inventory available"
)
return {inventory}
end)
end
return inventories
end, function(err)
print("Failed to load inventories for "..tostring(id))
print(err)
if (IsValid(client)) then
client:ChatPrint(
"A server error occured while loading your"..
" inventories. Check server log for details."
)
end
end)
-- Then, store all the inventories.
:next(function(inventories)
character.vars.inv = inventories
nut.char.loaded[id] = character
done = done + 1
if (done == #results and callback) then
callback(characters)
end
end)
end
end)
end
function nut.char.cleanUpForPlayer(client)
for _, charID in pairs(client.nutCharList or {}) do
local character = nut.char.loaded[charID]
if (not character) then return end
netstream.Start(nil, "charDel", character:getID())
nut.inventory.cleanUpForCharacter(character)
nut.char.loaded[charID] = nil
hook.Run("CharacterCleanUp", character)
end
end
local function removePlayer(client)
if (client:getChar() and client:getChar():getID() == id) then
client:KillSilent()
client:setNetVar("char", nil)
client:Spawn()
end
end
function nut.char.delete(id, client)
assert(type(id) == "number", "id must be a number")
if (IsValid(client)) then
removePlayer(client)
else
for _, client in ipairs(player.GetAll()) do
if (not table.HasValue(client.nutCharList or {}, id)) then continue end
table.RemoveByValue(client.nutCharList, id)
removePlayer(client)
end
end
hook.Run("PreCharacterDelete", id)
for index, charID in pairs(client.nutCharList) do
if (charID == id) then
table.remove(client.nutCharList, index)
break
end
end
nut.char.loaded[id] = nil
netstream.Start(nil, "charDel", id)
nut.db.query("DELETE FROM nut_characters WHERE _id = "..id)
nut.db.query(
"SELECT _invID FROM nut_inventories WHERE _charID = "..id,
function(data)
if (data) then
for _, inventory in ipairs(data) do
nut.inventory.deleteByID(tonumber(inventory._invID))
end
end
end
)
hook.Run("OnCharacterDelete", client, id)
end
|
game = {
positions = {{},{},{},{}}
}
Resources = {}
assets = {
SpriteBatches = {
cards = love.graphics.newSpriteBatch( love.graphics.newImage( "graphics/sprites.png" ), 100 )
}
}
Clickables = require("Clickables")
Sprite = require("Sprite")
SliderTile = require("entities/SliderTile")
game.changeState = function (state)
game.state = state
state:load()
end
game.tick = 0
|
local months={"JAN","MAR","MAY","JUL","AUG","OCT","DEC"}
local daysPerMonth={31+28,31+30,31+30,31,31+30,31+30,0}
function find5weMonths(year)
local list={}
local startday=((year-1)*365+math.floor((year-1)/4)-math.floor((year-1)/100)+math.floor((year-1)/400))%7
for i,v in ipairs(daysPerMonth) do
if startday==4 then list[#list+1]=months[i] end
if i==1 and year%4==0 and year%100~=0 or year%400==0 then
startday=startday+1
end
startday=(startday+v)%7
end
return list
end
local cnt_months=0
local cnt_no5we=0
for y=1900,2100 do
local list=find5weMonths(y)
cnt_months=cnt_months+#list
if #list==0 then
cnt_no5we=cnt_no5we+1
end
print(y.." "..#list..": "..table.concat(list,", "))
end
print("Months with 5 weekends: ",cnt_months)
print("Years without 5 weekends in the same month:",cnt_no5we)
|
description = [[
Determines which Security layer and Encryption level is supported by the
RDP service. It does so by cycling through all existing protocols and ciphers.
When run in debug mode, the script also returns the protocols and ciphers that
fail and any errors that were reported.
The script was inspired by MWR's RDP Cipher Checker
http://labs.mwrinfosecurity.com/tools/2009/01/12/rdp-cipher-checker/
]]
---
-- @usage
-- nmap -p 3389 --script rdp-enum-encryption <ip>
--
-- @output
-- PORT STATE SERVICE
-- 3389/tcp open ms-wbt-server
-- | rdp-enum-encryption:
-- | Security layer
-- | CredSSP: SUCCESS
-- | Native RDP: SUCCESS
-- | SSL: SUCCESS
-- | RDP Encryption level: High
-- | 128-bit RC4: SUCCESS
-- |_ FIPS 140-1: SUCCESS
--
author = "Patrik Karlsson"
license = "Same as Nmap--See http://nmap.org/book/man-legal.html"
local bin = require("bin")
local nmap = require("nmap")
local table = require("table")
local shortport = require("shortport")
local rdp = require("rdp")
local stdnse = require("stdnse")
categories = {"safe", "discovery"}
portrule = shortport.port_or_service(3389, "ms-wbt-server")
local function enum_protocols(host, port)
local PROTOCOLS = {
["Native RDP"] = 0,
["SSL"] = 1,
["CredSSP"] = 3
}
local ERRORS = {
[1] = "SSL_REQUIRED_BY_SERVER",
[2] = "SSL_NOT_ALLOWED_BY_SERVER",
[3] = "SSL_CERT_NOT_ON_SERVER",
[4] = "INCONSISTENT_FLAGS",
[5] = "HYBRID_REQUIRED_BY_SERVER"
}
local res_proto = { name = "Security layer" }
for k, v in pairs(PROTOCOLS) do
local comm = rdp.Comm:new(host, port)
if ( not(comm:connect()) ) then
return false, "ERROR: Failed to connect to server"
end
local cr = rdp.Request.ConnectionRequest:new(v)
local status, response = comm:exch(cr)
comm:close()
if ( not(status) ) then
return false, response
end
local pos, success = bin.unpack("C", response.itut.data)
if ( success == 2 ) then
table.insert(res_proto, ("%s: SUCCESS"):format(k))
elseif ( nmap.debugging() > 0 ) then
local pos, err = bin.unpack("C", response.itut.data, 5)
if ( err > 0 ) then
table.insert(res_proto, ("%s: FAILED (%s)"):format(k, ERRORS[err] or "Unknown"))
else
table.insert(res_proto, ("%s: FAILED"):format(k))
end
end
end
table.sort(res_proto)
return true, res_proto
end
local function enum_ciphers(host, port)
local CIPHERS = {
{ ["40-bit RC4"] = 1 },
{ ["56-bit RC4"] = 8 },
{ ["128-bit RC4"] = 2 },
{ ["FIPS 140-1"] = 16 }
}
local ENC_LEVELS = {
[0] = "None",
[1] = "Low",
[2] = "Client Compatible",
[3] = "High",
[4] = "FIPS Compliant",
}
local res_ciphers = {}
local function get_ordered_ciphers()
local i = 0
return function()
i = i + 1
if ( not(CIPHERS[i]) ) then return end
for k,v in pairs(CIPHERS[i]) do
return k, v
end
end
end
for k, v in get_ordered_ciphers() do
local comm = rdp.Comm:new(host, port)
if ( not(comm:connect()) ) then
return false, "ERROR: Failed to connect to server"
end
local cr = rdp.Request.ConnectionRequest:new()
local status, response = comm:exch(cr)
if ( not(status) ) then
break
end
local msc = rdp.Request.MCSConnectInitial:new(v)
local status, response = comm:exch(msc)
comm:close()
if ( status ) then
local pos, enc_level = bin.unpack("C", response.itut.data, 95 + 8)
local pos, enc_cipher= bin.unpack("C", response.itut.data, 95 + 4)
if ( enc_cipher == v ) then
table.insert(res_ciphers, ("%s: SUCCESS"):format(k))
end
res_ciphers.name = ("RDP Encryption level: %s"):format(ENC_LEVELS[enc_level] or "Unknown")
elseif ( nmap.debugging() > 0 ) then
table.insert(res_ciphers, ("%s: FAILURE"):format(k))
end
end
return true, res_ciphers
end
action = function(host, port)
local result = {}
local status, res_proto = enum_protocols(host, port)
if ( not(status) ) then
return res_proto
end
local status, res_ciphers = enum_ciphers(host, port)
if ( not(status) ) then
return res_ciphers
end
table.insert(result, res_proto)
table.insert(result, res_ciphers)
return stdnse.format_output(true, result)
end |
local formatting = require("modules.completion.formatting")
vim.cmd([[packadd cmp-nvim-lsp]])
if not packer_plugins["nvim-lsp-installer"].loaded then
vim.cmd([[packadd nvim-lsp-installer]])
end
if not packer_plugins["lsp_signature.nvim"].loaded then
vim.cmd([[packadd lsp_signature.nvim]])
end
if not packer_plugins["cmp-nvim-lsp"].loaded then
vim.cmd([[packadd cmp-nvim-lsp]])
end
if not packer_plugins["lspsaga.nvim"].loaded then
vim.cmd([[packadd lspsaga.nvim]])
end
local nvim_lsp = require("lspconfig")
local lsp_installer = require("nvim-lsp-installer")
local signs = { Error = "✗", Warn = "", Hint = "", Info = "" }
for type, icon in pairs(signs) do
local hl = "DiagnosticSign" .. type
vim.fn.sign_define(hl, { text = icon, texthl = hl, numhl = hl })
end
local border = {
{ "╭", "FloatBorder" },
{ "─", "FloatBorder" },
{ "╮", "FloatBorder" },
{ "│", "FloatBorder" },
{ "╯", "FloatBorder" },
{ "─", "FloatBorder" },
{ "╰", "FloatBorder" },
{ "│", "FloatBorder" },
}
local function goto_definition(split_cmd)
local util = vim.lsp.util
local log = require("vim.lsp.log")
local api = vim.api
local handler = function(_, result, ctx)
if result == nil or vim.tbl_isempty(result) then
local _ = log.info() and log.info(ctx.method, "No location found")
return nil
end
if split_cmd then
vim.cmd(split_cmd)
end
if vim.tbl_islist(result) then
util.jump_to_location(result[1])
if #result > 1 then
util.set_qflist(util.locations_to_items(result))
api.nvim_command("copen")
api.nvim_command("wincmd p")
end
else
util.jump_to_location(result)
end
end
return handler
end
local function lsp_highlight_document(client)
if client.server_capabilities.document_highlight then
vim.api.nvim_exec(
[[
augroup lsp_document_highlight
autocmd! * <buffer>
autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight()
autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references()
augroup END
]],
false
)
end
end
vim.lsp.handlers["textDocument/definition"] = goto_definition("split")
vim.lsp.handlers["textDocument/hover"] = vim.lsp.with(vim.lsp.handlers.hover, { border = border })
vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with(vim.lsp.handlers.signature_help, { border = border })
-- Override default format setting
vim.lsp.handlers["textDocument/formatting"] = function(err, result, ctx)
if err ~= nil or result == nil then
return
end
if
vim.api.nvim_buf_get_var(ctx.bufnr, "init_changedtick") == vim.api.nvim_buf_get_var(ctx.bufnr, "changedtick")
then
local view = vim.fn.winsaveview()
vim.lsp.util.apply_text_edits(result, ctx.bufnr, "utf-16")
vim.fn.winrestview(view)
if ctx.bufnr == vim.api.nvim_get_current_buf() then
vim.b.saving_format = true
vim.cmd([[update]])
vim.b.saving_format = false
end
end
end
lsp_installer.settings({
ui = {
icons = {
server_installed = "✓",
server_pending = "➜",
server_uninstalled = "✗",
},
},
})
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities.textDocument.completion.completionItem.documentationFormat = {
"markdown",
"plaintext",
}
capabilities.textDocument.completion.completionItem.snippetSupport = true
capabilities.textDocument.completion.completionItem.preselectSupport = true
capabilities.textDocument.completion.completionItem.insertReplaceSupport = true
capabilities.textDocument.completion.completionItem.labelDetailsSupport = true
capabilities.textDocument.completion.completionItem.deprecatedSupport = true
capabilities.textDocument.completion.completionItem.commitCharactersSupport = true
capabilities.textDocument.completion.completionItem.tagSupport = {
valueSet = { 1 },
}
capabilities.textDocument.completion.completionItem.resolveSupport = {
properties = { "documentation", "detail", "additionalTextEdits" },
}
local function custom_attach(client)
vim.cmd([[autocmd ColorScheme * highlight NormalFloat guibg=#1f2335]])
vim.cmd([[autocmd ColorScheme * highlight FloatBorder guifg=white guibg=#1f2335]])
vim.cmd([[autocmd CursorHold * lua vim.diagnostic.open_float(nil, {focus=false})]])
require("lsp_signature").on_attach({
bind = true,
use_lspsaga = false,
floating_window = true,
fix_pos = true,
hint_enable = true,
hi_parameter = "Search",
handler_opts = { "double" },
})
if client.server_capabilities.document_formatting then
vim.cmd([[augroup Format]])
vim.cmd([[autocmd! * <buffer>]])
vim.cmd([[autocmd BufWritePost <buffer> lua require'modules.completion.formatting'.format()]])
vim.cmd([[augroup END]])
end
lsp_highlight_document(client)
vim.diagnostic.config({
virtual_text = false,
signs = true,
underline = false,
update_in_insert = false,
severity_sort = true,
})
end
local function switch_source_header_splitcmd(bufnr, splitcmd)
bufnr = nvim_lsp.util.validate_bufnr(bufnr)
local params = { uri = vim.uri_from_bufnr(bufnr) }
vim.lsp.buf_request(bufnr, "textDocument/switchSourceHeader", params, function(err, result)
if err then
error(tostring(err))
end
if not result then
print("Corresponding file can’t be determined")
return
end
vim.api.nvim_command(splitcmd .. " " .. vim.uri_to_fname(result))
end)
end
-- Override server settings here
local enhance_server_opts = {
["sqls"] = function(opts)
opts.cmd = { "sqls" }
opts.args = { "-config ~/.config/sqls/config.yml" }
opts.filetypes = { "sql", "mysql" }
opts.on_attach = function(client)
client.server_capabilities.document_formatting = false
custom_attach(client)
end
end,
["sumneko_lua"] = function(opts)
opts.settings = {
Lua = {
diagnostics = { globals = { "vim", "packer_plugins" } },
workspace = {
library = {
[vim.fn.expand("$VIMRUNTIME/lua")] = true,
[vim.fn.expand("$VIMRUNTIME/lua/vim/lsp")] = true,
},
maxPreload = 100000,
preloadFileSize = 10000,
},
telemetry = { enable = false },
},
}
opts.on_attach = function(client)
client.server_capabilities.document_formatting = false
custom_attach(client)
end
end,
["clangd"] = function(opts)
opts.args = {
"--background-index",
"-std=c++20",
"--pch-storage=memory",
"--clang-tidy",
"--suggest-missing-includes",
}
opts.capabilities.offsetEncoding = { "utf-16" }
opts.single_file_support = true
opts.commands = {
ClangdSwitchSourceHeader = {
function()
switch_source_header_splitcmd(0, "edit")
end,
description = "Open source/header in current buffer",
},
ClangdSwitchSourceHeaderVSplit = {
function()
switch_source_header_splitcmd(0, "vsplit")
end,
description = "Open source/header in a new vsplit",
},
ClangdSwitchSourceHeaderSplit = {
function()
switch_source_header_splitcmd(0, "split")
end,
description = "Open source/header in a new split",
},
}
-- Disable `clangd`'s format
opts.on_attach = function(client)
client.server_capabilities.document_formatting = false
custom_attach(client)
end
end,
["jsonls"] = function(opts)
opts.settings = {
json = {
-- Schemas https://www.schemastore.org
schemas = {
{
fileMatch = { "package.json" },
url = "https://json.schemastore.org/package.json",
},
{
fileMatch = { "tsconfig*.json" },
url = "https://json.schemastore.org/tsconfig.json",
},
{
fileMatch = {
".prettierrc",
".prettierrc.json",
"prettier.config.json",
},
url = "https://json.schemastore.org/prettierrc.json",
},
{
fileMatch = { ".eslintrc", ".eslintrc.json" },
url = "https://json.schemastore.org/eslintrc.json",
},
{
fileMatch = {
".babelrc",
".babelrc.json",
"babel.config.json",
},
url = "https://json.schemastore.org/babelrc.json",
},
{
fileMatch = { "lerna.json" },
url = "https://json.schemastore.org/lerna.json",
},
{
fileMatch = {
".stylelintrc",
".stylelintrc.json",
"stylelint.config.json",
},
url = "http://json.schemastore.org/stylelintrc.json",
},
{
fileMatch = { "/.github/workflows/*" },
url = "https://json.schemastore.org/github-workflow.json",
},
},
},
}
opts.on_attach = function(client)
client.server_capabilities.document_formatting = true
custom_attach(client)
end
end,
["tsserver"] = function(opts)
-- Disable `tsserver`'s format
opts.on_attach = function(client)
client.server_capabilities.document_formatting = false
custom_attach(client)
end
end,
["dockerls"] = function(opts)
-- Disable `dockerls`'s format
opts.on_attach = function(client)
client.server_capabilities.document_formatting = false
custom_attach(client)
end
end,
["pylsp"] = function(opts)
opts.settings = {
pylsp = {
pylint = { enabled = false },
flake8 = { enabled = false },
pycodestyle = { enabled = true },
pyflakes = { enabled = false },
yapf = { enabled = true },
},
}
opts.on_attach = function(client)
client.server_capabilities.document_formatting = true
custom_attach(client)
end
end,
["r_language_server"] = function(opts)
opts.on_attach = function(client)
client.server_capabilities.document_formatting = true
custom_attach(client)
end
end,
["gopls"] = function(opts)
opts.settings = {
gopls = {
usePlaceholders = true,
analyses = {
nilness = true,
shadow = true,
unusedparams = true,
unusewrites = true,
},
},
}
-- Disable `gopls`'s format
opts.on_attach = function(client)
client.server_capabilities.document_formatting = false
custom_attach(client)
end
end,
["remark_ls"] = function(opts)
opts.on_attach = function(client)
client.server_capabilities.document_formatting = false
custom_attach(client)
end
end,
["jdtls"] = function(opts)
opts.single_file_support = true
opts.on_attach = function(client)
client.server_capabilities.document_formatting = true
custom_attach(client)
end
end,
["phpactor"] = function(opts)
opts.single_file_support = true
opts.on_attach = function(client)
client.server_capabilities.document_formatting = true
custom_attach(client)
end
end,
}
lsp_installer.on_server_ready(function(server)
local opts = {
capabilities = capabilities,
flags = { debounce_text_changes = 500 },
on_attach = custom_attach,
}
if enhance_server_opts[server.name] then
enhance_server_opts[server.name](opts)
end
server:setup(opts)
end)
-- https://github.com/vscode-langservers/vscode-html-languageserver-bin
nvim_lsp.html.setup({
cmd = { "vscode-html-languageserver", "--stdio" },
filetypes = { "html", "htmldjango" },
init_options = {
configurationSection = { "html", "css", "javascript" },
embeddedLanguages = { css = true, javascript = true },
},
settings = {},
single_file_support = true,
flags = { debounce_text_changes = 500 },
capabilities = capabilities,
on_attach = function(client)
client.server_capabilities.document_formatting = false
custom_attach(client)
end,
})
nvim_lsp.hls.setup({
single_file_support = true,
flags = { debounce_text_changes = 500 },
capabilities = capabilities,
on_attach = function(client)
require("aerial").on_attach(client)
client.server_capabilities.document_formatting = true
custom_attach(client)
end,
})
local efmls = require("efmls-configs")
-- Init `efm-langserver` here.
efmls.init({
on_attach = custom_attach,
capabilities = capabilities,
init_options = { documentFormatting = true, codeAction = true },
})
-- Require `efmls-configs-nvim`'s config here
local vint = require("efmls-configs.linters.vint")
local clangtidy = require("efmls-configs.linters.clang_tidy")
local eslint = require("efmls-configs.linters.eslint")
local flake8 = require("efmls-configs.linters.flake8")
local shellcheck = require("efmls-configs.linters.shellcheck")
local staticcheck = require("efmls-configs.linters.staticcheck")
local luafmt = require("efmls-configs.formatters.stylua")
local clangfmt = require("efmls-configs.formatters.clang_format")
local goimports = require("efmls-configs.formatters.goimports")
local prettier = require("efmls-configs.formatters.prettier")
local shfmt = require("efmls-configs.formatters.shfmt")
local alex = require("efmls-configs.linters.alex")
local pylint = require("efmls-configs.linters.pylint")
local yapf = require("efmls-configs.formatters.yapf")
local vulture = require("efmls-configs.linters.vulture")
-- Add your own config for formatter and linter here
local rustfmt = require("modules.completion.efm.formatters.rustfmt")
local sqlfmt = require("modules.completion.efm.formatters.sqlfmt")
-- Override default config here
flake8 = vim.tbl_extend("force", flake8, {
prefix = "flake8: max-line-length=160, ignore F403 and F405",
lintStdin = true,
lintIgnoreExitCode = true,
lintFormats = { "%f:%l:%c: %t%n%n%n %m" },
lintCommand = "flake8 --max-line-length 160 --extend-ignore F403,F405 --format '%(path)s:%(row)d:%(col)d: %(code)s %(code)s %(text)s' --stdin-display-name ${INPUT} -",
})
-- Setup formatter and linter for efmls here
efmls.setup({
vim = { formatter = vint },
lua = { formatter = luafmt },
c = { formatter = clangfmt, linter = clangtidy },
cpp = { formatter = clangfmt, linter = clangtidy },
go = { formatter = goimports, linter = staticcheck },
latex = { linter = alex },
-- python = {formatter = yapf},
vue = { formatter = prettier },
typescript = { formatter = prettier, linter = eslint },
javascript = { formatter = prettier, linter = eslint },
typescriptreact = { formatter = prettier, linter = eslint },
javascriptreact = { formatter = prettier, linter = eslint },
yaml = { formatter = prettier },
json = { formatter = prettier, linter = eslint },
html = { formatter = prettier },
css = { formatter = prettier },
scss = { formatter = prettier },
sh = { formatter = shfmt, linter = shellcheck },
markdown = { formatter = prettier },
rust = { formatter = rustfmt },
sql = { formatter = sqlfmt },
htmldjango = { formatter = prettier },
})
formatting.configure_format_on_save()
|
config = {
var0 = "true"
}
|
ITEM.name = "Glock 19"
ITEM.desc = "Пистолет американского производства, ценимый многими сталкерами за высокие боевые и эксплуатационные качества. Это отличное оружие, особенно в умелых руках и при должной сноровке. \n\nБоеприпасы 9x19"
ITEM.price = 16272
ITEM.model = "models/wick/weapons/stalker/stcopwep/w_glock_model_stcop.mdl"
ITEM.class = "weapon_cop_glock"
ITEM.weaponCategory = "2"
ITEM.category = "Оружие"
ITEM.height = 1
ITEM.width = 2
ITEM.exRender = false
ITEM.iconCam = {
pos = Vector(-2.2999999523163, 200, -0.54000002145767),
ang = Angle(0, 270, 0),
fov = 3.6
}
ITEM.weight = 1.23 |
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- CloneTrooper1019, 2020
-- Realism Server
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local CollectionService = game:GetService("CollectionService")
local setLookAngles = Instance.new("RemoteEvent")
setLookAngles.Archivable = false
setLookAngles.Name = "SetLookAngles"
setLookAngles.Parent = ReplicatedStorage
local function onReceiveLookAngles(player, pitch, yaw)
if typeof(pitch) ~= "number" or pitch ~= pitch then
return
end
if typeof(yaw) ~= "number" or yaw ~= yaw then
return
end
pitch = math.clamp(pitch, -1, 1)
yaw = math.clamp(yaw, -1, 1)
setLookAngles:FireAllClients(player, pitch, yaw)
end
local function onCharacterAdded(character)
local humanoid = character:WaitForChild("Humanoid", 10)
if humanoid and humanoid:IsA("Humanoid") then
CollectionService:AddTag(humanoid, "RealismHook")
end
end
local function onPlayerAdded(player)
if player.Character then
onCharacterAdded(player.Character)
end
player.CharacterAdded:Connect(onCharacterAdded)
end
for _,player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)
setLookAngles.OnServerEvent:Connect(onReceiveLookAngles)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
--[[
Consume svg colors, generate a list of colors sorted by luminance
Change the order of l1 > l2 in the orderByBrightness function
to change from white/black to black/whate
]]
local spairs = require("spairs")
local svgcolors = require("svgcolors")
local coloring = require("coloring")
local luma = coloring.luma
local function orderByBrightness(t, a, b)
local l1 = luma(t[a])
local l2 = luma(t[b])
return l1 > l2
end
print("return {")
for k,v in spairs(svgcolors, orderByBrightness) do
print (string.format("{name = '%s', value = {%d, %d, %d}};", k,v[1], v[2],v[3]))
end
print("};") |
module("luci.controller.oh3c", package.seeall)
function index()
entry({"admin", "network", "oh3c"}, cbi("oh3c/usermgr"), "OH3C", 30).dependent=false
end
|
local json = config.json
return {
handler = function(context)
context.response.headers["content-type"] = "application/json"
if config.empty_as_array then
if type(context.output) == 'table' and next(context.output) == nil then
return context.response.send('[]')
end
end
context.response.send(json.encode(context.output))
end,
options = {
predicate = function(context)
if context.output == nil then
return false
end
if config.default then
return true
end
local accept = context.request.headers.accept
local content = context.request.headers["content-type"]
return (accept and (accept:find("application/json") or accept:find("*/*"))) or
(content and content:find("application/json") and not accept)
end
}
}
|
dbcore = {}
dbcore.resultmappers={}
dbcore.insert_statements={}
dbcore.queries={}
function dbcore.init(db_path)
dbcore.dbpath = db_path
print("DB Path:", dbcore.dbpath)
local sqlite3 = require("lsqlite3")
dbcore.db = sqlite3.open_memory()
read_configs()
populate_db()
end
function read_configs()
configfile = dbcore.dbpath .. "config"
dbcore.configs = {}
for i in io.lines(configfile) do
table.insert(dbcore.configs, i)
end
end
function populate_db()
for _,mod in pairs(dbcore.configs) do
local mod_config = require(mod)
create_tables(mod_config.all_table_definitions)
populate_tables(mod_config.populate)
prepare_queries(mod_config.queries)
end
end
function create_tables(table_definitions)
for table_definition in table_definitions() do
assert( dbcore.db:exec(table_definition))
end
end
function populate_tables(populate)
local parser = require("ftcsv")
for stmt, csv in populate() do
st = dbcore.db:prepare(stmt)
-- print ("Initialisiere Tabelle aus " .. csv)
local parsedTable = parser.parse(dbcore.dbpath .. csv, ";")
if texio then
log_out = {}
table.insert(log_out, "\n(")
table.insert(log_out, dbcore.dbpath)
table.insert(log_out, csv)
table.insert(log_out, ") ")
texio.write("log", table.concat(log_out))
end
for k,v in pairs(parsedTable) do
st:bind_names(v)
st:step()
st:reset()
end
end
end
function prepare_queries(queries)
for querykey, st, resultitem, mapper in queries() do
dbcore.queries[querykey] = {
querystmt = assert(dbcore.db:prepare(st)),
resultitem = resultitem,
mapper = mapper
}
end
end
function insert_error(result)
if (#result == 0) then
table.insert(result, "__error__")
end
return result
end
function singleresult(v, querykey)
local resultitem_name = dbcore.queries[querykey].resultitem;
local result = v[resultitem_name]
return result
end;
function dbcore.read_from_db(querykey, values, error_mapper)
local result = {}
local result_filter = error_mapper or insert_error
local mapper = dbcore.queries[querykey].mapper or singleresult
local stmt = dbcore.queries[querykey].querystmt
stmt:bind_names(values)
for row in stmt:nrows() do
table.insert(result, mapper(row, querykey))
end
stmt:reset()
return result_filter(result)
end
return dbcore
|
--- Defines reverse lookup table.
---
--- # Examples
---
--- ```lua
--- event.on_built_entity(function(e)
--- local player = game.get_player(e.player_index)
--- local controller_name = reverse_defines.controllers[player.controller_type]
--- end)
--- ```
local flib_reverse_defines = {}
-- TODO: Figure out how to document this. Will likely require parsing Factorio's docs.
local function build_reverse_defines(lookup_table, base_table)
lookup_table = lookup_table or {}
for k, v in pairs(base_table) do
if type(v) == "table" then
lookup_table[k] = {}
build_reverse_defines(lookup_table[k], v)
else
lookup_table[v] = k
end
end
end
build_reverse_defines(flib_reverse_defines, defines)
return flib_reverse_defines
|
function Collectionator.Utilities.GetRealmAndFaction()
local realm = Auctionator.Variables.GetConnectedRealmRoot()
local faction = UnitFactionGroup("player")
return realm .. "_" .. faction
end
|
blocFunctions = {}
function function_binding(toBind)
for k, v in pairs(toBind) do
blocFunctions[k] = function(position)
local newObjs = {};
for i in string.gmatch(v, "%S+") do
table.insert(newObjs, Engine.Scene:createGameObject(i)({position = position}));
end
return newObjs
end
end
end
function Object:uninit()
Object.initialized = false;
end
function Object:init(path)
print("Init terrain", path)
if not Object.initialized and file_exists(path) then
This:initialize();
print("Terrain initialized");
local lines = lines_from(path)
local maxY;
local maxX;
local sprSize;
local load_table = {};
print("Lines", inspect(lines));
for i, str in pairs(lines) do
if maxY == nil or i>maxY then
maxY = i;
end
load_table[i] = {}
for j = 1, #str do
if maxX == nil or j>maxX then
maxX = j;
end
local char = str:sub(j,j);
load_table[i][j] = char;
end
end
print("Loadtable", inspect(load_table));
local offset = {x = (maxX/2), y = (maxY/2)};
for i, v in pairs(load_table) do
Object.elements[i] = {}
for j, v2 in pairs(v) do
if v2 ~= " " then
local position = { x = j-1, y = i-1 };
print("Loading element", v2);
Object.elements[i][j] = blocFunctions[v2](position);
if sprSize == nil then
sprSize = Object.elements[i][j][1].getSprSize();
end
end
end
end
print("Setting camera");
local pVec = obe.Transform.UnitVector(
offset.x * sprSize.x,
offset.y * sprSize.y
);
local ySize = maxY/Engine.Scene:getCamera():getSize().y;
local xSize = maxX/Engine.Scene:getCamera():getSize().x;
local pSize = sprSize.x * (ySize > xSize and ySize or xSize);
local camera = Engine.Scene:getCamera();
camera:setPosition(pVec, obe.Transform.Referential.Center);
camera:scale(pSize, obe.Transform.Referential.Center);
print("Terrain done :)");
Object.initialized = true;
end
end
function Local.Init(toBind)
function_binding(toBind);
Object.elements = {};
end
function file_exists(path)
local f = io.open(path, "r")
if f then f:close() end
return f ~= nil
end
function lines_from(path)
lines = {}
for line in io.lines(path) do
lines[#lines + 1] = line
end
return lines
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.