content
stringlengths 5
1.05M
|
---|
---@class KeySubType @enum
KeySubType = {}
---
--- 1
KeySubType.KEY_NORMAL = 1
---
--- 2
KeySubType.KEY_GOLDEN = 2
---
--- 3
KeySubType.KEY_DOUBLEPACK = 3
---
--- 4
KeySubType.KEY_CHARGED = 4
return KeySubType
|
local player_called
local in_call = false
function tvRP.phoneCallWaiting(player, waiting)
if waiting then
player_called = player
else
player_called = nil
end
end
function tvRP.phoneHangUp()
tvRP.disconnectVoice("phone", nil)
end
-- phone channel behavior
tvRP.registerVoiceCallbacks("phone", function(player)
print("(vRPvoice-phone) requested by "..player)
if player == player_called then
player_called = nil
return true
end
end,
function(player, is_origin)
print("(vRPvoice-phone) connected to "..player)
in_call = true
tvRP.setVoiceState("phone", nil, true)
tvRP.setVoiceState("world", nil, true)
end,
function(player)
print("(vRPvoice-phone) disconnected from "..player)
in_call = false
if not tvRP.isSpeaking() then -- end world voice if not speaking
tvRP.setVoiceState("world", nil, false)
end
end)
AddEventHandler("vRP:NUIready", function()
-- phone channel config
tvRP.configureVoice("phone", cfg.phone_voice_config)
end)
Citizen.CreateThread(function()
while true do
Citizen.Wait(500)
if in_call then -- force world voice if in a phone call
tvRP.setVoiceState("world", nil, true)
end
end
end)
|
---
-- @classmod abtesting.adapter.policy
-- @release 0.0.1
local modulename = "abtestingAdminPolicyGroup"
local _M = { _VERSION = "0.0.1" }
local mt = { __index = _M }
local ERRORINFO = require('abtesting.error.errcode').info
local runtimeModule = require('abtesting.adapter.runtime')
local policyModule = require('abtesting.adapter.policy')
local redisModule = require('abtesting.utils.redis')
local systemConf = require('abtesting.utils.init')
local handler = require('abtesting.error.handler').handler
local utils = require('abtesting.utils.utils')
local log = require('abtesting.utils.log')
local ERRORINFO = require('abtesting.error.errcode').info
local cjson = require('cjson.safe')
local doresp = utils.doresp
local dolog = utils.dolog
local doerror = utils.doerror
local redisConf = systemConf.redisConf
local divtypes = systemConf.divtypes
local prefixConf = systemConf.prefixConf
local policyLib = prefixConf.policyLibPrefix
local runtimeLib = prefixConf.runtimeInfoPrefix
local domain_name = prefixConf.domainname
local policyGroupModule = require('abtesting.adapter.policygroup')
local policyGroupLib = prefixConf.policyGroupPrefix
local getPolicyGroupId = function()
local policyGroupId = tonumber(ngx.var.arg_policygroupid)
if not policyGroupId or policyGroupId < 0 then
local info = ERRORINFO.PARAMETER_TYPE_ERROR
local desc = "policyGroupId invalid"
local response = doresp(info, desc)
log:errlog(dolog(info, desc))
ngx.say(response)
return nil
end
return policyGroupId
end
local getPolicyGroup = function()
local request_body = ngx.var.request_body
local postData = cjson.decode(request_body)
if not request_body then
-- ERRORCODE.PARAMETER_NONE
local errinfo = ERRORINFO.PARAMETER_NONE
local desc = 'request_body or post data'
local response = doresp(errinfo, desc)
log:errlog(dolog(errinfo, desc))
ngx.say(response)
return nil
end
if not postData then
-- ERRORCODE.PARAMETER_ERROR
local errinfo = ERRORINFO.PARAMETER_ERROR
local desc = 'postData is not a json string'
local response = doresp(errinfo, desc)
log:errlog(dolog(errinfo, desc))
ngx.say(response)
return nil
end
local policy_cnt = 0
local policyGroup = {}
for k, v in pairs(postData) do
policy_cnt = policy_cnt + 1
local idx = tonumber(k)
if not idx or type(v) ~= 'table' then
local errinfo = ERRORINFO.PARAMETER_ERROR
local desc = 'policyGroup error'
local response = doresp(errinfo, desc)
log:errlog(dolog(errinfo, desc))
ngx.say(response)
return nil
end
local policy = v
local divtype = policy.divtype
local divdata = policy.divdata
if not divtype or not divdata then
-- ERRORCODE.PARAMETER_NONE
local errinfo = ERRORINFO.PARAMETER_NONE
local desc = "policy divtype or policy divdata"
local response = doresp(errinfo, desc)
log:errlog(dolog(errinfo, desc))
ngx.say(response)
return nil
end
if not divtypes[divtype] then
-- ERRORCODE.PARAMETER_TYPE_ERROR
local errinfo = ERRORINFO.PARAMETER_TYPE_ERROR
local desc = "unsupported divtype"
local response = doresp(errinfo, desc)
log:errlog(dolog(errinfo, desc))
ngx.say(response)
return nil
end
if policyGroup[idx] then
--不能混淆,优先级不能重复
local errinfo = ERRORINFO.PARAMETER_TYPE_ERROR
local desc = "policy in policy group should not overlap"
local response = doresp(errinfo, desc)
log:errlog(dolog(errinfo, desc))
ngx.say(response)
return nil
end
policyGroup[idx] = policy
end
if policy_cnt ~= #policyGroup then
local errinfo = ERRORINFO.PARAMETER_TYPE_ERROR
local desc = "index of policy in policy_group should be one by one"
local response = doresp(errinfo, desc)
log:errlog(dolog(errinfo, desc))
ngx.say(response)
return nil
end
return policyGroup
end
_M.checkPolicy = function(option)
local db = option.db
local policyGroup = getPolicyGroup()
if not policyGroup then
return false
end
local steps = #policyGroup
if steps < 1 then
local errinfo = ERRORINFO.PARAMETER_NONE
local desc = "blank policy group"
local response = doresp(errinfo, desc)
log:errlog(dolog(errinfo, desc))
ngx.say(response)
return false
end
local pfunc = function()
local policyGroupMod = policyGroupModule:new(db.redis,
policyGroupLib, policyLib)
return policyGroupMod:check(policyGroup)
end
local status, info = xpcall(pfunc, handler)
if not status then
local response = doerror(info)
ngx.say(response)
return false
end
local chkout = info
local valid = chkout[1]
local err = chkout[2]
local desc = chkout[3]
if not valid then
local response = doresp(err, desc)
ngx.say(response)
log:errlog(dolog(err, desc))
return false
end
return true
end
_M.check = function(option)
local status = _M.checkPolicy(option)
if not status then return end
local response = doresp(ERRORINFO.SUCCESS)
ngx.say(response)
return true
end
_M.set = function(option)
local status = _M.checkPolicy(option)
if not status then return end
local db = option.db
local policyGroup = getPolicyGroup()
if not policyGroup then
return false
end
local pfunc = function()
local policyGroupMod = policyGroupModule:new(db.redis,
policyGroupLib, policyLib)
return policyGroupMod:set(policyGroup)
end
local status, info = xpcall(pfunc, handler)
if not status then
local response = doerror(info)
ngx.say(response)
return false
end
local data = info
local response = doresp(ERRORINFO.SUCCESS, _, data)
ngx.say(response)
return true
end
_M.get = function(option)
local db = option.db
local policyGroupId = getPolicyGroupId()
if not policyGroupId then
return false
end
local pfunc = function()
local policyGroupMod = policyGroupModule:new(db.redis,
policyGroupLib, policyLib)
return policyGroupMod:get(policyGroupId)
end
local status, info = xpcall(pfunc, handler)
if not status then
local response = doerror(info)
ngx.say(response)
return false
end
local data = info
local response = doresp(ERRORINFO.SUCCESS, _, data)
ngx.say(response)
return true
end
_M.del = function(option)
local db = option.db
local policyGroupId = getPolicyGroupId()
if not policyGroupId then
return false
end
local pfunc = function()
local policyGroupMod = policyGroupModule:new(db.redis,
policyGroupLib, policyLib)
return policyGroupMod:del(policyGroupId)
end
local status, info = xpcall(pfunc, handler)
if not status then
local response = doerror(info)
ngx.say(response)
return false
end
local response = doresp(ERRORINFO.SUCCESS)
ngx.say(response)
return true
end
return _M
|
require("config")
--Item
if stackchanges == true then
require("prototypes.stackchanges")
end
if inventorychanges == true then
require("prototypes.inventorychanges")
end
--Item group
require("prototypes.item-groups-automatization")
require("prototypes.item-group-changes")
require("prototypes.item-groups-energy")
require("prototypes.item-groups-logistic")
require("prototypes.item-groups-mining")
require("prototypes.item-groups-module")
require("prototypes.item-groups-nuclear")
require("prototypes.item-groups-transport")
require("prototypes.item-groups-trains")
require("prototypes.item-groups-decorative")
require("prototypes.item-groups-vehicles")
require("prototypes.item-groups-armor")
require("prototypes.item-groups-plates")
require("prototypes.item-groups-intermediate")
require("prototypes.item-groups-defense")
require("prototypes.item-groups-liquids")
--Tech
require("prototypes.tech") |
local t = Def.ActorFrame{};
t[#t+1] = Def.ActorFrame{
OnCommand=cmd(diffusealpha,0;sleep,0.2;linear,0.2;diffusealpha,1);
GainFocusCommand=function(s) setenv("PlayCourse",1) end;
LoseFocusCommand=function(s) setenv("PlayCourse",0) end;
OffCommand=function(self)
if getenv("PlayCourse") == 1 then
self:sleep(0.2):linear(0.1):zoomy(0)
elseif getenv("PlayMusic") == 1 then
self:sleep(0.2):linear(0.1):addx(SCREEN_WIDTH)
else
self:sleep(0.2):linear(0.1):addx(-SCREEN_WIDTH)
end;
end;
Def.ActorFrame{
OnCommand=cmd(zoomy,0.5;sleep,0.2;linear,0.1;zoomy,1;linear,0.05;zoomx,1.1;linear,0.1;zoomx,1);
Def.ActorFrame{
GainFocusCommand=cmd(finishtweening;queuecommand,"Anim");
AnimCommand=cmd(sleep,2;queuecommand,"Anim");
LoseFocusCommand=cmd(finishtweening;stopeffect);
Def.ActorFrame{
InitCommand=cmd(diffusealpha,0;);
GainFocusCommand=cmd(queuecommand,"Anim");
AnimCommand=cmd(finishtweening;diffusealpha,0;sleep,0.6;linear,0.2;diffusealpha,0.5;linear,0.7;diffusealpha,0);
LoadActor("back")..{
InitCommand=cmd(addy,-38);
GainFocusCommand=cmd(queuecommand,"Anim");
AnimCommand=cmd(finishtweening;zoom,0.75;sleep,0.6;linear,1;zoom,1.1);
};
};
};
Def.ActorFrame{
GainFocusCommand=cmd(finishtweening;queuecommand,"Anim");
AnimCommand=cmd(sleep,2;queuecommand,"Anim");
LoseFocusCommand=cmd(finishtweening;stopeffect);
Def.ActorFrame{
InitCommand=cmd(diffusealpha,0;);
GainFocusCommand=cmd(queuecommand,"Anim");
AnimCommand=cmd(finishtweening;diffusealpha,0;sleep,0.6;linear,0.2;diffusealpha,0.5;linear,0.7;diffusealpha,0);
LoadActor("back")..{
InitCommand=cmd(addy,-38);
GainFocusCommand=cmd(queuecommand,"Anim");
AnimCommand=cmd(finishtweening;zoom,0.75;sleep,0.8;linear,0.9;zoom,0.95);
};
};
};
Def.ActorFrame{
GainFocusCommand=cmd(finishtweening;queuecommand,"Anim");
AnimCommand=cmd(sleep,2;queuecommand,"Anim");
LoseFocusCommand=cmd(finishtweening;stopeffect);
Def.ActorFrame{
InitCommand=cmd(diffusealpha,0;);
GainFocusCommand=cmd(queuecommand,"Anim");
AnimCommand=cmd(finishtweening;diffusealpha,0;sleep,0.6;linear,0.2;diffusealpha,0.25;linear,0.7;diffusealpha,0);
LoadActor(THEME:GetPathG("","_sharedX2/PlayMode/spinner.png"))..{
InitCommand=cmd(addy,-38;zoom,1.2;blend,Blend.Add;diffusealpha,0.5;);
GainFocusCommand=cmd(queuecommand,"Anim");
AnimCommand=cmd(rotationz,0;sleep,0.6;linear,1;rotationz,360);
};
};
};
LoadActor("base.png")..{
InitCommand=cmd(addy,-40;);
GainFocusCommand=function(s) s:stoptweening():Load(THEME:GetPathG("ScreenSelectPlayMode","Scroll ChoiceCourse/base.png")) end;
LoseFocusCommand=function(s) s:stoptweening():Load(THEME:GetPathG("ScreenSelectPlayMode","Scroll ChoiceCourse/base dark.png")) end;
};
Def.ActorFrame{
GainFocusCommand=cmd(finishtweening;queuecommand,"Anim");
AnimCommand=cmd(sleep,2;queuecommand,"Anim");
LoseFocusCommand=cmd(finishtweening;stopeffect);
Def.ActorFrame{
InitCommand=cmd(diffusealpha,0;);
GainFocusCommand=cmd(queuecommand,"Anim");
AnimCommand=cmd(finishtweening;diffusealpha,0;sleep,0.8;linear,0.2;diffusealpha,1;linear,0.6;diffusealpha,0);
LoadActor("highlight")..{
InitCommand=cmd(addy,-38);
GainFocusCommand=cmd(queuecommand,"Anim");
AnimCommand=cmd(finishtweening;zoom,0.5;sleep,0.8;linear,0.9;zoom,1);
};
};
};
LoadActor("char.png")..{
InitCommand=cmd(addy,-88;addx,14);
GainFocusCommand=function(s) s:stoptweening():Load(THEME:GetPathG("ScreenSelectPlayMode","Scroll ChoiceCourse/char.png")) end;
LoseFocusCommand=function(s) s:stoptweening():Load(THEME:GetPathG("ScreenSelectPlayMode","Scroll ChoiceCourse/char dark.png")) end;
};
};
Def.ActorFrame{
InitCommand=cmd(addy,186;);
OnCommand=cmd(diffusealpha,0;sleep,0.3;linear,0.2;diffusealpha,1);
LoadActor(THEME:GetPathG("","_sharedX2/PlayMode/infomid.png"))..{
InitCommand=cmd(zoom,0.95;diffusealpha,0.5);
OnCommand=cmd(zoomy,0;sleep,0.3;linear,0.2;zoomy,1);
};
Def.Sprite{
InitCommand=cmd(diffusealpha,1;xy,-36,14);
OnCommand=cmd(diffusealpha,0;sleep,0.3;linear,0.2;diffusealpha,1);
GainFocusCommand=function(self) self:Load(THEME:GetPathG("ScreenSelectPlayMode","Scroll ChoiceCourse/text.png")) end;
LoseFocusCommand=function(self) self:Load(THEME:GetPathG("ScreenSelectPlayMode","Scroll ChoiceCourse/text dark.png")) end;
};
Def.ActorFrame{
InitCommand=cmd(valign,1;y,-56;diffusealpha,1);
OnCommand=cmd(y,0;sleep,0.3;linear,0.2;y,-56);
LoadActor(THEME:GetPathG("","_sharedX2/PlayMode/infotop.png"));
Def.Sprite{
InitCommand=cmd(x,20;y,-54;diffusealpha,1);
GainFocusCommand=function(self) self:Load(THEME:GetPathG("ScreenSelectPlayMode","Scroll ChoiceCourse/title.png")) end;
LoseFocusCommand=function(self) self:Load(THEME:GetPathG("ScreenSelectPlayMode","Scroll ChoiceCourse/title dark.png")) end;
OnCommand=cmd(y,0;sleep,0.2;linear,0.1;y,2);
};
Def.ActorFrame{
Def.Sprite{
Texture="course 1x7.png";
InitCommand=cmd(pause;SetAllStateDelays,0.2;x,-184;diffusealpha,0);
GainFocusCommand=cmd(play;diffusealpha,1);
LoseFocusCommand=cmd(pause;setstate,0;diffusealpha,0);
};
LoadActor("course icon off.png")..{
InitCommand=cmd(x,-184;diffusealpha,1);
OnCommand=cmd(diffusealpha,0;sleep,0.2;smooth,0.2;diffusealpha,1);
GainFocusCommand=cmd(diffusealpha,0);
LoseFocusCommand=cmd(diffusealpha,1);
};
};
};
LoadActor(THEME:GetPathG("","_sharedX2/PlayMode/infobottom.png"))..{
InitCommand=cmd(valign,1;y,66);
OnCommand=cmd(y,0;sleep,0.3;linear,0.2;y,66);
};
};
};
return t;
|
local helpers = require("test.functional.helpers")(after_each)
local exec_lua, feed = helpers.exec_lua, helpers.feed
local ls_helpers = require("helpers")
local Screen = require("test.functional.ui.screen")
describe("Extra-nodes:", function()
local screen
before_each(function()
helpers.clear()
ls_helpers.session_setup_luasnip()
screen = Screen.new(50, 3)
screen:attach()
screen:set_default_attr_ids({
[0] = { bold = true, foreground = Screen.colors.Blue },
[1] = { bold = true, foreground = Screen.colors.Brown },
[2] = { bold = true },
[3] = { background = Screen.colors.LightGray },
})
end)
after_each(function()
screen:detach()
end)
it("matchNode works with simple strings", function()
local snip = [[
s("trig", {
i(1),
m(1, "aaa%d", "bbb", "ccc")
})
]]
ls_helpers.static_docstring_test(snip, { "ccc" }, { "$1ccc$0" })
exec_lua("ls.snip_expand(" .. snip .. ")")
screen:expect({
grid = [[
^ccc |
{0:~ }|
{2:-- INSERT --} |]],
})
-- change text so it matches:
feed("aaa3")
exec_lua("ls.active_update_dependents()")
screen:expect({
grid = [[
aaa3^bbb |
{0:~ }|
{2:-- INSERT --} |]],
})
-- ensure multiline works.
feed("<Cr>cccc")
exec_lua("ls.active_update_dependents()")
screen:expect({
grid = [[
aaa3 |
cccc^bbb |
{2:-- INSERT --} |]],
})
end)
it("matchNode works with functions", function()
local snip = [[
s("trig", {
i(1),
m(1,
function(args) return #args[1][1] == 3 end,
function(args) return tostring(#args[1][1]) end,
function(args) return "nope" end )
})
]]
ls_helpers.static_docstring_test(snip, { "nope" }, { "$1nope$0" })
exec_lua("ls.snip_expand(" .. snip .. ")")
screen:expect({
grid = [[
^nope |
{0:~ }|
{2:-- INSERT --} |]],
})
-- make i_1 match:
feed("aaa")
exec_lua("ls.active_update_dependents()")
screen:expect({
grid = [[
aaa^3 |
{0:~ }|
{2:-- INSERT --} |]],
})
feed("<BS>")
exec_lua("ls.active_update_dependents()")
screen:expect({
grid = [[
aa^nope |
{0:~ }|
{2:-- INSERT --} |]],
})
-- ensure multiline works.
feed("a<Cr>")
exec_lua("ls.active_update_dependents()")
screen:expect({
grid = [[
aaa |
^3 |
{2:-- INSERT --} |]],
})
end)
it("matchNode works with lambdas", function()
-- create bigger screen for this test.
-- TODO: rewrite all tests for this screen-size.
screen:detach()
helpers.clear()
ls_helpers.session_setup_luasnip()
screen = Screen.new(50, 5)
screen:attach()
screen:set_default_attr_ids({
[0] = { bold = true, foreground = Screen.colors.Blue },
[1] = { bold = true, foreground = Screen.colors.Brown },
[2] = { bold = true },
[3] = { background = Screen.colors.LightGray },
})
local snip = [[
s("trig", {
i(1, "best"),
m(1,
l._1:gsub("e", "a"):match("tast"),
l._1:gsub("e", "u"),
l._1:gsub("e", "o") )
})
]]
ls_helpers.static_docstring_test(
snip,
{ "bestbost" },
{ "${1:best}bost$0" }
)
exec_lua("ls.snip_expand(" .. snip .. ")")
screen:expect({
grid = [[
^b{3:est}bost |
{0:~ }|
{0:~ }|
{0:~ }|
{2:-- SELECT --} |]],
})
feed("test")
exec_lua("ls.active_update_dependents()")
screen:expect({
grid = [[
test^tust |
{0:~ }|
{0:~ }|
{0:~ }|
{2:-- INSERT --} |]],
})
feed("<BS>e")
exec_lua("ls.active_update_dependents()")
screen:expect({
grid = [[
tese^toso |
{0:~ }|
{0:~ }|
{0:~ }|
{2:-- INSERT --} |]],
})
-- ensure multiline works.
feed("<Cr>test")
exec_lua("ls.active_update_dependents()")
screen:expect({
grid = [[
tese |
test^tusu |
tust |
{0:~ }|
{2:-- INSERT --} |]],
})
end)
it(
"matchNode uses return of condition-function for `if` if unspecified",
function()
local snip = [[
s("trig", {
i(1, "aaa"),
m(1, function(args)
return (#args[1][1] == 3 and args[1] or nil)
end)
})
]]
ls_helpers.static_docstring_test(
snip,
{ "aaaaaa" },
{ "${1:aaa}aaa$0" }
)
exec_lua("ls.snip_expand(" .. snip .. ")")
screen:expect({
grid = [[
^a{3:aa}aaa |
{0:~ }|
{2:-- SELECT --} |]],
})
-- replace matching text
feed("aa")
exec_lua("ls.active_update_dependents()")
screen:expect({
grid = [[
aa^ |
{0:~ }|
{2:-- INSERT --} |]],
})
end
)
it(
"matchNode uses return of match on condition-pattern for `if` if unspecified",
function()
local snip = [[
s("trig", {
i(1, "12"),
m(1, "%d(%d)")
})
]]
ls_helpers.static_docstring_test(snip, { "122" }, { "${1:12}2$0" })
exec_lua("ls.snip_expand(" .. snip .. ")")
screen:expect({
grid = [[
^1{3:2}2 |
{0:~ }|
{2:-- SELECT --} |]],
})
feed("aa")
exec_lua("ls.active_update_dependents()")
screen:expect({
grid = [[
aa^ |
{0:~ }|
{2:-- INSERT --} |]],
})
end
)
it(
"matchNode uses return of condition-lambda for `if` if unspecified",
function()
local snip = [[
s("trig", {
i(1, "1324"),
m(1, l._1:gsub("[123]", "0"):match("00(%d%d)"))
})
]]
ls_helpers.static_docstring_test(
snip,
{ "132404" },
{ "${1:1324}04$0" }
)
exec_lua("ls.snip_expand(" .. snip .. ")")
screen:expect({
grid = [[
^1{3:324}04 |
{0:~ }|
{2:-- SELECT --} |]],
})
feed("4444")
exec_lua("ls.active_update_dependents()")
screen:expect({
grid = [[
4444^ |
{0:~ }|
{2:-- INSERT --} |]],
})
end
)
end)
|
--[[
Assign AutoStart Fix v1.1.0.1
See README.md for more information
MIT License
Copyright (c) 2020 Down Right Technical 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.
--]]
local pluginName = select(1,...);
local componentName = select(2,...);
local signalTable = select(3,...);
local my_handle = select(4,...);
-- ****************************************************************
-- speed up global functions, by creating local cache
-- this can be very important for high speed plugins
-- caring about performance is imperative for plugins with execute function
-- ****************************************************************
local F=string.format;
local E=Echo;
-- ****************************************************************
-- plugin main entry point
-- ****************************************************************
local function Main(display_handle,argument)
local input = ""
if argument ~= nil then
-- got an inline argument
input = argument
else
-- no argument prompt in the UI
input = TextInput("Enter Sequence Number or range (e.g. 1,2-4)")
end
local sequences, stringSequences = Drt.calculateRange(input)
if sequences == nil then
Echo("No Valid Ranges")
return
end
-- create an undo session.
local undo = CreateUndo("Adding Macros AutoStart Macros to Sequences " .. stringSequences)
-- use our returned sequences to insert the CueZero and CueEnd Macros
for k, v in pairs(sequences) do
-- make sure object exists!
-- assign the macros
local cmdString = string.format('Set Seq %d "CmdEnable" "Yes"', v)
Cmd(cmdString, undo)
cmdString = string.format('Set Seq %d Cue 0 "Cmd" "Set Seq %d AutoStart No"', v, v)
Cmd(cmdString, undo)
cmdString = string.format('Set Seq %d Cue "OffCue" "Cmd" "Set Seq %d AutoStart Yes"', v, v)
Cmd(cmdString, undo)
end
CloseUndo(undo)
end
-- ****************************************************************
-- plugin exit cleanup entry point
-- ****************************************************************
local function Cleanup()
end
-- ****************************************************************
-- plugin execute entry point
-- ****************************************************************
local function Execute(Type,...)
end
-- ****************************************************************
-- return the entry points of this plugin :
-- ****************************************************************
return Main,Cleanup,Execute
|
cflags{
'-Wall', '-Wpedantic',
'-Wno-overflow', -- ioctl opcode conversion
'-D _GNU_SOURCE',
'-include $dir/config.h',
}
lib('libcommon.a', {'log.c', 'ud_socket.c'})
exe('acpid', {
'acpid.c',
'acpi_ids.c',
'connection_list.c',
'event.c',
'input_layer.c',
'inotify_handler.c',
'libnetlink.c',
'netlink.c',
'proc.c',
'sock.c',
'libcommon.a',
})
file('bin/acpid', '755', '$outdir/acpid')
man{'acpid.8'}
exe('acpi_listen', {'acpi_listen.c', 'libcommon.a'})
file('bin/acpi_listen', '755', '$outdir/acpi_listen')
man{'acpi_listen.8'}
fetch 'git'
|
-- Module dependencies
local MODULE = require( script:GetCustomProperty("ModuleManager") )
function COMBAT() return MODULE:Get("standardcombo.Combat.Wrap") end
local CONST = require(script:GetCustomProperty("CONST"))
local function META_AP()
return _G["Meta.Ability.Progression"]
end
local function META_Consumables()
return _G["Consumables"]
end
local Equipment = script:FindAncestorByType("Equipment")
local ConsumablesNetwork = script:GetCustomProperty("ConsumablesNetwork"):WaitForObject()
local HealingPotionVFX = script:GetCustomProperty("HealingPotionVFX")
local CooldownTimers = {
HealingPotion = 0.0
}
local bindEvent
function OnBindingPressed(player, bind)
-- Health Potion
if bind == "ability_extra_1" and ConsumablesNetwork:GetCustomProperty("HealingPotion") == 0 and not player.isDead then
local MaxHitPoints = player.maxHitPoints * 0.75
-- Check if the player is below 75% health
if player.hitPoints >= MaxHitPoints then return end
local dmg = Damage.New()
local HealAmount = META_Consumables().GetValue(player, META_Consumables().HEALTH_POTION)
if MaxHitPoints - player.hitPoints < HealAmount then -- Check that we don't heal above 75%
HealAmount = MaxHitPoints - player.hitPoints
end
dmg.amount = -HealAmount
dmg.reason = DamageReason.COMBAT
dmg.sourcePlayer = player
local attackData = {
object = player,
damage = dmg,
source = dmg.sourcePlayer,
position = nil,
rotation = nil,
tags = {Type = "HealthPotion"}
}
local vfx = META_AP().SpawnAsset(HealingPotionVFX, {position = player:GetWorldPosition() - Vector3.New(0,0,100)})
vfx:AttachToPlayer(player, "root")
COMBAT().ApplyDamage(attackData)
CooldownTimers["HealingPotion"] = 60
end
end
function OnScriptDestroyed()
bindEvent:Disconnect()
bindEvent = nil
end
while not Equipment.owner do Task.Wait() end
function Tick(deltaTime)
for name, value in pairs(CooldownTimers) do
if value > 0 then
value = value - deltaTime
if value < 0 then value = 0 end
CooldownTimers[name] = value
ConsumablesNetwork:SetNetworkedCustomProperty(name, CoreMath.Round(value, 1))
end
end
end
bindEvent = Equipment.owner.bindingPressedEvent:Connect(OnBindingPressed)
script.destroyEvent:Connect(OnScriptDestroyed) |
--
-- theme.lua
-- Theme config
--
local gears = require("gears")
local helpers = require("helpers")
local dpi = require("beautiful").xresources.apply_dpi
local theme = {}
-- ========================================
-- Variables
-- ========================================
-- Theme color
local color = {
lightblue = "#8fbcbb",
darkblue = "#2e3440",
red = "#bf616a",
orange = "#d08770",
yellow = "#ebcb8b",
green = "#a3be8c",
white = "#eceff4",
black = "#000000",
}
-- Theme font
local font = "HackGen Console"
-- ========================================
-- Icons
-- ========================================
-- Icons path
theme.icons_path = gears.filesystem.get_configuration_dir() .. "icons/"
-- Define the icon theme for application icons. If not set then the icons
-- from /usr/share/icons and /usr/share/icons/hicolor will be used.
theme.icon_theme = "zafiro-icon-theme"
-- ========================================
-- Common
-- ========================================
-- Font
theme.font = font .. " 10"
-- Background
theme.bg_normal = color.black
theme.bg_dark = color.black
theme.bg_focus = color.black
theme.bg_urgent = color.black
theme.bg_minimize = color.black
theme.bg_systray = color.black
-- Foreground
theme.fg_normal = color.white
theme.fg_focus = color.lightblue
theme.fg_urgent = color.red
theme.fg_minimize = color.darkblue
-- Borders/Gaps
theme.useless_gap = dpi(7)
theme.screen_margin = theme.useless_gap
theme.border_width = dpi(1)
theme.border_radius = dpi(5)
theme.border_focus = color.lightblue
theme.border_marked = color.red
theme.border_normal = color.black
-- Tooltips
theme.tooltip_font = theme.font
theme.tooltip_padding_x = dpi(10)
theme.tooltip_padding_y = dpi(10)
-- Notification
theme.notification_width = dpi(350)
theme.notification_margin = dpi(15)
theme.notification_border_width = dpi(0)
theme.notification_icon_size = dpi(48)
theme.notification_fg = color.white
theme.notification_bg = color.darkblue .. "aa"
theme.notification_bg_critical = color.red .. "aa"
theme.notification_font = theme.font
-- ========================================
-- Components
-- ========================================
-- Topbar
theme.topbar_position = "top"
theme.topbar_height = dpi(28)
theme.topbar_margin = theme.useless_gap
theme.topbar_padding_x = dpi(5)
-- Exit screen
theme.exit_screen_bg = theme.bg_normal .. "aa"
theme.exit_screen_button_spacing = dpi(48)
theme.exit_screen_caption_spacing = dpi(8)
theme.exit_screen_icon_size = dpi(48)
-- Lock screen
theme.lock_screen_icons_path = theme.icons_path .. "lock_screen/"
theme.lock_screen_bg = theme.bg_normal .. "aa"
theme.lock_screen_width = dpi(800)
theme.lock_screen_spacing_x = dpi(10)
theme.lock_screen_spacing_y = dpi(30)
theme.lock_screen_title_icon = theme.lock_screen_icons_path .. "lock_screen_padlock.svg"
theme.lock_screen_title_icon_size = dpi(40)
theme.lock_screen_title_font = font .. " 24"
theme.lock_screen_dot_icon = theme.lock_screen_icons_path .. "lock_screen_dot.svg"
theme.lock_screen_dot_spacing = dpi(5)
theme.lock_screen_dot_color = theme.fg_normal
theme.lock_screen_dot_size = dpi(20)
theme.lock_screen_warning_icon = theme.lock_screen_icons_path .. "lock_screen_warning.svg"
-- Window switcher
theme.window_switcher_bg = theme.bg_normal .. "aa"
theme.window_switcher_margin_x = dpi(20)
theme.window_switcher_margin_y = dpi(25)
theme.window_switcher_width = dpi(500)
theme.window_switcher_spacing_x = dpi(7)
theme.window_switcher_spacing_y = dpi(15)
theme.window_switcher_icon_height = dpi(15)
theme.window_switcher_icon_width = dpi(15)
-- ========================================
-- Widgets
-- ========================================
-- Clickable container
theme.clickable_container_padding_x = dpi(10)
theme.clickable_container_padding_y = dpi(7)
-- Systray
theme.systray_icon_spacing = dpi(10)
-- Taglist
theme.taglist_spacing = dpi(5)
theme.taglist_bg_empty = theme.bg_normal
theme.taglist_bg_occupied = theme.bg_normal
theme.taglist_bg_urgent = theme.bg_normal
theme.taglist_bg_focus = theme.bg_normal
theme.taglist_fg_empty = theme.fg_normal
theme.taglist_fg_occupied = theme.fg_normal
theme.taglist_fg_urgent = theme.fg_urgent
theme.taglist_fg_focus = theme.fg_focus
-- Tasklist
theme.tasklist_font = theme.font
theme.tasklist_icon_visible = " "
theme.tasklist_icon_hidden = " "
theme.tasklist_bg_normal = theme.bg_normal
theme.tasklist_bg_focus = theme.bg_focus
theme.tasklist_bg_urgent = theme.bg_urgent
theme.tasklist_fg_normal = theme.fg_normal
theme.tasklist_fg_focus = theme.fg_focus
theme.tasklist_fg_urgent = theme.fg_urgent
-- Calendar
theme.calendar_padding = dpi(20)
theme.calendar_spacing = dpi(10)
-- System tray
theme.bg_systray = theme.bg_normal
theme.systray_icon_spacing = dpi(5)
-- Battery
theme.battery_fg_normal = theme.fg_normal
theme.battery_fg_urgent = theme.fg_urgent
-- Layout
theme.layout_tile = theme.icons_path .. "layouts/tiled.png"
theme.layout_floating = theme.icons_path .. "layouts/floating.png"
theme.layout_max = theme.icons_path .. "layouts/maximized.png"
-- Hotkeys
theme.hotkeys_font = font .. " Bold 10"
theme.hotkeys_description_font = font .. " 10"
theme.hotkeys_bg = color.black .. "aa"
theme.hotkeys_border_width = dpi(0)
theme.hotkeys_shape = helpers.rrect
theme.hotkeys_modifiers_fg = color.yellow
theme.hotkeys_label_fg = color.white
theme.hotkeys_label_bg = color.darkblue
theme.hotkeys_group_margin = dpi(40)
return theme
|
Locales['de'] = {
['cant_rob'] = '~r~Je kunt dit niet roven',
['press_stop'] = 'Druk op [DEL] om te stoppen',
['max_amount'] = '~r~Het maximale bedrag bereikt',
['min_police'] = 'Er moet minstens ~b~%s politie~s~ in de stad zijn om te kunnen beroven',
['no_room'] = '~r~Je kunt de buit niet vasthouden',
['bought'] = 'Je hebt zojuist ~y~%sx~s~ ~b~%s~s~ gekocht voor ~r~$%s~s~',
} |
--[[
Addon: Lib
For: G-Core
By: SlownLS ( www.g-core.fr )
]]
GCore.Lib.Sample = GCore.Lib.Sample or {}
local tblInfos = {}
local tblModels = {
"models/player/Group01/Female_01.mdl",
"models/player/Group01/Female_02.mdl",
"models/player/Group01/Female_03.mdl",
"models/player/Group01/Female_04.mdl",
"models/player/Group01/Female_06.mdl",
"models/player/group01/male_01.mdl",
"models/player/Group01/Male_02.mdl",
"models/player/Group01/male_03.mdl",
"models/player/Group01/Male_04.mdl",
"models/player/Group01/Male_05.mdl",
"models/player/Group01/Male_06.mdl",
"models/player/Group01/Male_07.mdl",
"models/player/Group01/Male_08.mdl",
"models/player/Group01/Male_09.mdl"
}
function GCore.Lib.Sample:Reset()
if IsValid(GCore.Lib.Sample.Panel) then GCore.Lib.Sample.Panel:Remove() end
end
function GCore.Lib.Sample:ChoosePlayer()
local frame = vgui.Create("GCore:DFrame")
:SetSize(700,361)
:SetHeader("G-Core Lib",50,{marginRight = 10})
:Center()
:SetDraggable(true)
:MakePopup()
:FadeIn(0.5)
function frame:PaintOver(w,h)
surface.SetDrawColor(GCore.Lib:GetColor('primary'))
surface.DrawRect(220,60,3,h-70)
end
local pModel = vgui.Create("GCore:DModelPanel",frame)
:SetSize(200,frame:GetTall()-110)
:SetPos(10,60)
:SetModel(tblModels[1])
:SetFOV( 18 )
:SetCamPos( Vector( 210, 0, 70 ) )
:SetLookAt( Vector( 0, 0, 36 ) )
:CanTurn(true)
local btnValid = vgui.Create("GCore:DButton",frame)
:SetSize(200,30)
:SetPos(10,frame:GetTall()-30-10)
:SetFont(GCore.Lib:GetFont(18,"Roboto"))
:SetDefaultText('Valider',{type="fas",size=18,unicode="f00c"})
local pSearch = vgui.Create("GCore:DTextEntry",frame)
:SetSize(frame:GetWide()-240,30)
:SetPos(230,60)
:SetFont(GCore.Lib:GetFont(16,"Roboto"))
:SetLabel('Nom du model',{type="fas",size=18,unicode="f002"})
local pList = vgui.Create("GCore:DScrollPanel",frame)
:SetSize(frame:GetWide()-240,frame:GetTall()-110)
:SetPos(230,100)
:AddIconLayout(10,10)
:SetSearchBar(pSearch,"model")
for k,v in SortedPairs(tblModels or {}) do
local pMdl = vgui.Create("GCore:DModelPanel",pList:GetIconLayout())
:SetSize(100,140)
:SetModel(v)
:CanTurn(true)
:SetFOV(45)
pMdl.model = v
function pMdl:DoClick()
pModel:SetModel(v)
end
function pMdl:PaintOver(w,h)
local col = GCore.Lib:LerpColor(
self,
"borderColor",
{
default = Color(0,0,0,0),
to = GCore.Lib:GetColor('lightRed')
},
string.upper(pModel:GetModel()) == string.upper(v),
7
)
surface.SetDrawColor(col)
surface.DrawOutlinedRect(0,0,w,h)
end
end
end
function GCore.Lib.Sample:Sample()
local frame = vgui.Create("GCore:DFrame")
:SetSize(700,361)
:SetHeader("G-Core Lib",50,{marginRight = 10})
:Center()
:SetDraggable(true)
:MakePopup()
:FadeIn(0.5)
-- :SetBorderRadius(8)
function frame:PaintOver(w,h)
local intMaringTop = 0
if self.tblHeader then intMaringTop = self.tblHeader.height end
draw.SimpleText( "Présentation G-Core Lib !", GCore.Lib:GetFont(24,"Roboto"),w/2,intMaringTop+15,color_white,1)
draw.SimpleText( "Vous êtes :", GCore.Lib:GetFont(18,"Roboto"),10,intMaringTop+150,color_white)
end
local pName = vgui.Create("GCore:DTextEntry",frame)
:SetSize(frame:GetWide()-20,40)
:SetPos(10,100)
:SetFont(GCore.Lib:GetFont(18,"Roboto"))
:SetLabel('Votre Prénom',{type="fas",size=18,unicode="f4ff"})
:SetPlaceholderText('Entrez votre prénom...')
-- :SetBorderRadius(8)
local pAge = vgui.Create("GCore:DTextEntry",frame)
:SetSize(frame:GetWide()-20,40)
:SetPos(10,150)
:SetFont(GCore.Lib:GetFont(18,"Roboto"))
:SetNumeric(true)
:SetLabel('Votre Age',{type="fas",size=18,unicode="f1fd"})
:SetPlaceholderText('Entrez votre âge...')
local pRadio = vgui.Create("GCore:DRadio",frame)
for i = 1, 2 do
local strLabel = "Un Homme"
if i == 2 then strLabel = "Une Femme" end
local pCheckBox = vgui.Create("GCore:DCheckBox",frame)
:SetSize(18,18)
:SetPos(80,225+(i*25)-25)
:SetLabel(strLabel, {
font = GCore.Lib:GetFont(18,"Roboto"),
color = color_white
})
:AddToRadio(pRadio)
:SetValueRadio(i)
pRadio:Select(1)
end
local pRules = vgui.Create("GCore:DCheckBox",frame)
:SetSize(18,18)
:SetPos(10,283)
:SetLabel("En jouant sur le serveur, vous acceptez les règles.", {
font = GCore.Lib:GetFont(18,"Roboto"),
color = color_white
})
local btnValid = vgui.Create("GCore:DButton",frame)
:SetSize(frame:GetWide()-20,40)
:SetPos(10,311)
:SetFont(GCore.Lib:GetFont(18,"Roboto"))
:SetDefaultText('Valider',{type="fas",size=18,unicode="f00c"})
-- :SetBorderRadius(8)
function btnValid:DoClick()
GCore.Lib:Confirm("Confirmez ?","Confirmez-vous ces informations ?",{blur=true}, function()
chat.AddText(GCore.Lib:GetColor('lightRed'),"----------------------------------------")
chat.AddText(GCore.Lib:GetColor('lightRed'),"[G-Core] : ", color_white, "Prénom: " .. GCore.Lib:Ternary(string.len(pName:GetValue()) < 1,"Non défini",pName:GetValue()) )
chat.AddText(GCore.Lib:GetColor('lightRed'),"[G-Core] : ", color_white, "Age: " .. GCore.Lib:Ternary(string.len(pAge:GetValue()) < 1,"Non défini",pAge:GetValue() .. " ans") )
chat.AddText(GCore.Lib:GetColor('lightRed'),"[G-Core] : ", color_white, "Sexe: " .. GCore.Lib:Ternary(pRadio:GetValueRadio() == 1,"Homme","Femme") )
chat.AddText(GCore.Lib:GetColor('lightRed'),"----------------------------------------")
tblInfos.name = GCore.Lib:Ternary(string.len(pName:GetValue()) < 1,"Non défini",pName:GetValue())
tblInfos.age = GCore.Lib:Ternary(string.len(pAge:GetValue()) < 1,"Non défini",pAge:GetValue() .. " ans")
tblInfos.sexe = GCore.Lib:Ternary(pRadio:GetValueRadio() == 1,"Homme","Femme")
frame:FadeOut(0.5,true,function()
GCore.Lib.Sample:ChoosePlayer()
end)
end)
end
GCore.Lib.Sample.Panel = frame
end
concommand.Add("gcore_lib_sample",function()
GCore.Lib.Sample:Reset()
GCore.Lib.Sample:Sample()
end) |
--[[
The approach of avoiding constructors when saving tables with cycles is too radical. It is possible to save the table in a more pleasant format using constructors for the general case, and to use assignments later only to fix sharing and loops.
Reimplement function save using this approach. Add to it all the goodies that you have implemented in the previous exercises (indentation, record syntax, and list syntax).
]]
function serialize(name, value, saved)
local function valid_identifier(k)
-- Nifty little trick and a lot easier than trying to do the work that Lua already does
return load(tostring(k) .. "= 1") and true or false
end
--[[
Keep track of both saved and in progress items so that we can inline references to fully-defined items and only queue assignments when the reference would not be valid.
]]
saved = saved or {}
inprogress = {}
assignments = {}
local function aux(name, value, indent)
indent = indent or ""
if type(value) == "number" then
io.write(tostring(value))
elseif type(value) == "string" then
io.write(string.format("%q", value))
elseif type(value) == "table" then
if saved[value] then
io.write(saved[value])
else
inprogress[value] = name
io.write("{\n")
-- Array part
for i, v in ipairs(value) do
if inprogress[v] then
assignments[name .. "[" .. i .. "] = " .. inprogress[v]] = true
else
local fname = string.format("%s[%s]", name, i)
io.write(indent .. " "); aux(fname, v, indent .. " "); io.write(",\n")
end
end
-- Everything else
for k, v in pairs(value) do
if type(k) ~= "number" or k > #value then
if inprogress[v] then
assignments[string.format("%s[%s] = %s", name, k, inprogress[v])] = true
else
if valid_identifier(k) then
io.write(indent .. " " .. tostring(k) .. " = ")
aux(string.format("%s[%s]", name, tostring(k)), v, indent .. " ")
else
local dispname = string.format("[\"%s\"]", k)
io.write(indent .. " " .. dispname .. " = ")
aux(name .. dispname, v, indent .. " ")
end
io.write(",\n")
end
end
end
io.write(indent .. "}")
inprogress[value] = nil
saved[value] = name
end
else
error("cannot serialize a " .. type(value))
end
end
io.write(name, " = ")
aux(name, value)
io.write("\n")
for v in pairs(assignments) do
io.write(v .. "\n")
end
end
c = {5,6,4}
b = {1,2,3}
a = {
-- Array
"first",
{"second"},
-- Valid identifier
c = 3,
-- Invalid identifier
["for"] = 4,
[5] = 5,
-- Duplicated reference
[7] = c,
[6] = c,
-- Saved reference
b = b
}
-- Self-reference, cycle not in array section
a["self"] = a
-- Self-reference, cycle in array section
a[3] = a
-- Self-reference, not the top-level item
a["cycle"] = {}
a["cycle"]["loopback"] = a["cycle"]
local saved = {}
-- Just want to make sure this gets saved
serialize("b", b, saved)
--[[
b = {
1,
2,
3,
}
]]
-- Now make sure we handle all the crazy stuff
serialize("a", a, saved)
--[=[
a = {
"first",
{
"second",
},
["5"] = 5,
["6"] = {
5,
6,
4,
},
["7"] = a[["6"]],
["for"] = 4,
b = b,
c = 3,
cycle = {
},
}
a[3] = a
a[self] = a
a[cycle][loopback] = a[cycle]
]=]
|
local Protocol = {
-- information level --
INFO = "info", -- suggestion
-- e.g.) performance issue
WARN = "warn", -- reccommendation
-- e.g.) result may be broken (professionals can ignore)
ERR = "error", -- execution is impossible
};
Protocol.__index = Protocol;
function Protocol.new(ctx)
local L = {
ctx = ctx,
upk = std.msgpack.unpacker(),
input = {},
output = {},
};
return std.lua.setMetatable(L, Protocol);
end
function Protocol:openInput(name, trait, desc)
self.input[name] = {
value = nil,
trait = trait,
desc = desc,
};
self.ctx.send(std.msgpack.pack({
interface = "lambda",
command = "openInput",
param = {
name = name,
desc = desc,
trait = trait.param,
value = trait.param.def,
},
}));
end
function Protocol:closeInput(name)
self.input[name] = nil;
self.ctx.send(std.msgpack.pack({
interface = "lambda",
command = "closeInput",
param = {
name = name,
},
}));
end
function Protocol:openOutput(name, trait, desc)
self.output[name] = {
value = nil,
trait = trait,
};
self.ctx.send(std.msgpack.pack({
interface = "lambda",
command = "openOutput",
param = {
name = name,
desc = desc,
trait = trait.param,
},
}));
end
function Protocol:closeOutput(name)
self.output[name] = nil;
self.ctx.send(std.msgpack.pack({
interface = "lambda",
command = "closeOutput",
param = {
name = name,
},
}));
end
function Protocol:getInput(name)
local i = self.input[name];
return i.value or i.trait.default;
end
function Protocol:setOutput(name, value)
local o = self.output[name];
self.ctx.send(std.msgpack.pack({
interface = "lambda",
command = "output",
param = {
name = name,
value = o.trait:serialize(value),
},
}));
end
function Protocol:inform(lv, msg, type, name)
self.ctx.send(std.msgpack.pack({
interface = "lambda",
command = "inform",
param = {
level = lv,
msg = msg,
target = {
type = type,
name = name,
},
},
}));
end
function Protocol:informInput(lv, name, msg)
self:inform(lv, msg, "input", name);
end
function Protocol:informOutput(lv, name, msg)
self:inform(lv, msg, "output", name);
end
function Protocol:done()
self.ctx.send(std.msgpack.pack({ result = true, }));
end
function Protocol:handle()
function err_(msg)
self.ctx.send(std.msgpack.pack({success = false, msg = msg}));
end
function proc_(req)
if not req.command then
return false; -- response from clients is ignored in this protocol
end
if req.interface and (req.interface ~= "lambda") then
err_("unknown interface")
return false;
end
local switch = {};
function switch.input()
local i = self.input[req.param.name];
if i == nil then
err_("unknown name");
return false;
end
local v = req.param.value;
if not i.trait:test(v) then
err_("invalid value");
return false;
end
i.value = i.trait:deserialize(v);
self:done();
return false;
end
function switch.exec()
return true;
end
local dlg = switch[req.command];
if dlg then
return dlg();
else
err_("unknown command");
return false;
end
end
local receiver = self.ctx.recv();
while true do
local cnt = 0;
while cnt == 0 do
cnt = self.upk:unpack(receiver:await());
if not cnt then
return false;
end
end
for i = 1, cnt do
local req = self.upk:pop();
if proc_(req) then
return true;
end
end
end
end
return {
Protocol = Protocol,
};
|
cstrlib = require "cstrlib"
function PrintTrimmedString(str1)
print("[" .. cstrlib.trim(str1) .. "]")
end
PrintTrimmedString(" asdfasd a asdf ")
PrintTrimmedString(" [hello] w orld ")
|
local lwtk = require"lwtk"
local Application = lwtk.Application
local Column = lwtk.Column
local Row = lwtk.Row
local Space = lwtk.Space
local PushButton = lwtk.PushButton
local TextInput = lwtk.TextInput
local TextLabel = lwtk.TextLabel
local TitleText = lwtk.TitleText
local FocusGroup = lwtk.FocusGroup
local app = Application("example03.lua")
local confirmCloseWindows = lwtk.WeakKeysTable()
local function confirmClose(callback)
return function(widget)
local winToBeClosed = widget:getRoot()
local confirmWin = confirmCloseWindows[winToBeClosed]
if not callback then
callback = function() winToBeClosed:close() end
end
if not confirmWin or confirmWin:isClosed() then
confirmWin = app:newWindow {
Column {
TextLabel { text = "Are you sure?" },
Row {
PushButton { text = "&Yes", onClicked = function() callback()
confirmWin:close() end },
PushButton { text = "&No", onClicked = function() confirmWin:close() end },
}
}
}
confirmCloseWindows[winToBeClosed] = confirmWin
confirmWin:show()
else
confirmWin:show()
confirmWin:requestFocus()
end
end
end
local winCounter = 0
local function newWin(rows, columns)
local column = lwtk.Column {}
for i = 1, rows do
local row = lwtk.Row {}
column:addChild(row)
for j = 1, columns do
row:addChild(FocusGroup { id="focusGroup_"..i.."_"..j,
Column {
id = "form",
onInputChanged = function(widget, input)
local fullInput = #widget:childById("inp1").text > 0
and #widget:childById("inp2").text > 0
and #widget:childById("inp3").text > 0
and #widget:childById("inp4").text > 0
and #widget:childById("inp5").text > 0
widget:childById("b1"):setDisabled(not fullInput)
end,
Row {
Column {
TitleText { id = "title", text = "Please enter data ("..i.."|"..j..")" },
Row {
Column {
TextLabel { input = "form/inp1", text = "&First Name:" },
TextLabel { input = "form/inp2", text = "&Last Name:" },
TextLabel { input = "form/inp3", text = "S&treet:" },
TextLabel { input = "form/inp4", text = "Cit&y:" },
TextLabel { input = "form/inp5", text = "&Country:" },
},
Column {
style = {
{ "Columns@TextInput", 30 }
},
TextInput { id = "inp1" }, -- focus = true ,
TextInput { id = "inp2" },
TextInput { id = "inp3" },
TextInput { id = "inp4" },
TextInput { id = "inp5" }--, default = "b1"
},
}
},
},
Space {},
Row {
Space {},
PushButton { id = "b1", text = "&OK",
disabled = true,
default = true,
onClicked = function(widget)
widget:byId("form/title"):setText("Hello "..widget:byId("form/inp1").text)
widget:byId("form/title"):triggerLayout()
end
},
PushButton { text = "&Quit", onClicked = confirmClose() },
PushButton { text = "&Other", },
Space {},
}
}
})
end
end
winCounter = winCounter + 1
local win = app:newWindow {
title = "example03 - "..winCounter,
onClose = confirmClose(),
column
}
local c = win:childById("focusGroup_1_2/inp1")
if c then c:setFocus() end
win:show()
end
local function filterNumeric(widget, input)
if input:match("^%d+$") then
return input
end
end
local mainWin = app:newWindow {
title = "example03",
onClose = confirmClose(),
Column {
TitleText { text = "Welcome to lwtk!" },
onInputChanged = function(widget)
widget:childById("newWindow"):setDisabled( #widget:childById("columns").text == 0
or #widget:childById("rows").text == 0)
end,
Row {
style = {
{ "MaxColumns@TextInput", 3 }
},
TextLabel { text = "Rows:" },
TextInput { id = "rows", text = "3", focus = true, filterInput = filterNumeric,
initActions = {"CursorToEndOfLine"} },
TextLabel { text = "Columns:" },
TextInput { id = "columns", text = "4", filterInput = filterNumeric,
initActions = {"CursorToEndOfLine"} },
Space {}
},
Row {
PushButton { id = "newWindow",
text = "&New Window", default = true, onClicked = function(widget)
newWin(tonumber(widget:byId"rows".text),
tonumber(widget:byId"columns".text))
end },
PushButton { text = "&Quit", onClicked = confirmClose(function() app:close() end) },
}
}
}
mainWin:show()
app:runEventLoop()
|
-- rVignette: core
-- zork, 2018
-----------------------------
-- Variables
-----------------------------
local A, L = ...
-----------------------------
-- Functions
-----------------------------
local function OnVignetteAdded(self,event,id)
if not id then return end
self.vignettes = self.vignettes or {}
if self.vignettes[id] then return end
local vignetteInfo = C_VignetteInfo.GetVignetteInfo(id)
if not vignetteInfo then return end
local filename, width, height, txLeft, txRight, txTop, txBottom = GetAtlasInfo(vignetteInfo.atlasName)
if not filename then return end
local atlasWidth = width/(txRight-txLeft)
local atlasHeight = height/(txBottom-txTop)
local str = string.format("|T%s:%d:%d:0:0:%d:%d:%d:%d:%d:%d|t", filename, 0, 0, atlasWidth, atlasHeight, atlasWidth*txLeft, atlasWidth*txRight, atlasHeight*txTop, atlasHeight*txBottom)
PlaySoundFile("Sound\\Interface\\RaidWarning.ogg")
RaidNotice_AddMessage(RaidWarningFrame, str.." "..vignetteInfo.name.." spotted!", ChatTypeInfo["RAID_WARNING"])
print(str.." "..vignetteInfo.name,"spotted!")
self.vignettes[id] = true
end
-----------------------------
-- Init
-----------------------------
--eventHandler
local eventHandler = CreateFrame("Frame")
eventHandler:RegisterEvent("VIGNETTE_MINIMAP_UPDATED")
eventHandler:SetScript("OnEvent", OnVignetteAdded) |
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
--WoW API / Variables
local CreateFrame = CreateFrame
local hooksecurefunc = hooksecurefunc
--Global variables that we don't cache, list them here for mikk's FindGlobals script
-- GLOBALS:
local function LoadSkin()
if E.private.skins.blizzard.enable ~= true or E.private.skins.blizzard.losscontrol ~= true then return end
--/run LossOfControlFrame.fadeTime = 2000; LossOfControlFrame_SetUpDisplay(LossOfControlFrame, true, 'CONFUSE', 2094, 'Disoriented', [[Interface\Icons\Spell_Shadow_MindSteal]], 72101.9765625, 7.9950003623962, 8, 0, 5, 2)
local LossOfControlFrame = _G["LossOfControlFrame"]
local IconBackdrop = CreateFrame("Frame", nil, LossOfControlFrame)
IconBackdrop:SetTemplate()
IconBackdrop:SetOutside(LossOfControlFrame.Icon)
IconBackdrop:SetFrameLevel(LossOfControlFrame:GetFrameLevel() - 1)
LossOfControlFrame.Icon:SetTexCoord(.1, .9, .1, .9)
LossOfControlFrame:StripTextures()
LossOfControlFrame.AbilityName:ClearAllPoints()
LossOfControlFrame:Size(LossOfControlFrame.Icon:GetWidth() + 50)
local font = E.media.normFont
hooksecurefunc("LossOfControlFrame_SetUpDisplay", function(self)
self.Icon:ClearAllPoints()
self.Icon:Point("CENTER", self, "CENTER", 0, 0)
self.AbilityName:ClearAllPoints()
self.AbilityName:Point("BOTTOM", self, 0, -28)
self.AbilityName.scrollTime = nil;
self.AbilityName:FontTemplate(font, 20, 'OUTLINE')
self.TimeLeft.NumberText:ClearAllPoints()
self.TimeLeft.NumberText:Point("BOTTOM", self, 4, -58)
self.TimeLeft.NumberText.scrollTime = nil;
self.TimeLeft.NumberText:FontTemplate(font, 20, 'OUTLINE')
self.TimeLeft.SecondsText:ClearAllPoints()
self.TimeLeft.SecondsText:Point("BOTTOM", self, 0, -80)
self.TimeLeft.SecondsText.scrollTime = nil;
self.TimeLeft.SecondsText:FontTemplate(font, 20, 'OUTLINE')
-- always stop shake animation on start
if self.Anim:IsPlaying() then
self.Anim:Stop()
end
end)
end
S:AddCallback("LossControl", LoadSkin)
|
--
-- Dust bins attach to any sawmill, or milling tool and collects the fallen dust
--
-- For now it only connects to the sawmill
local Cuboid = assert(foundation.com.Cuboid)
local ng = Cuboid.new_fast_node_box
local Groups = assert(foundation.com.Groups)
local table_merge = assert(foundation.com.table_merge)
local Directions = assert(foundation.com.Directions)
local ItemInterface = assert(yatm.items.ItemInterface)
local ItemDevice = assert(yatm.items.ItemDevice)
local dust_bin_item_interface = ItemInterface.new_simple("main")
function dust_bin_item_interface:allow_insert_item(pos, dir, item_stack)
local def = item_stack:get_definition()
return Groups.has_group(def, "dust")
end
function dust_bin_item_interface:on_insert_item(pos, dir, item_stack)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
if not inv:is_empty("main") then
local node = minetest.get_node(pos)
local new_name = "yatm_woodcraft:dust_bin_sawdust"
if new_name ~= node.name then
node.name = new_name
minetest.swap_node(pos, node)
end
end
end
function dust_bin_item_interface:on_extract_item(pos, dir, count_or_item_stack)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
if inv:is_empty("main") then
local node = minetest.get_node(pos)
local new_name = "yatm_woodcraft:dust_bin_empty"
if new_name ~= node.name then
node.name = new_name
minetest.swap_node(pos, node)
end
end
end
local function dust_bin_on_construct(pos)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
inv:set_size("main", 9)
end
local function dust_bin_on_rightclick(pos, node, clicker, item_stack, _pointed_thing)
if item_stack:is_empty() then
-- extract any item from self, we don't care, just give us something
local saw_dust = ItemDevice.extract_item(pos, Directions.D_UP, 1, true)
if saw_dust then
clicker:get_inventory():add_item("main", saw_dust)
end
else
-- But if you have something in hand
local def = item_stack:get_definition()
if Groups.has_group(def, "dust") then
-- It's dust, we can place it in the bin
local stack = item_stack:peek_item(1)
local remaining = ItemDevice.insert_item(pos, Directions.D_UP, stack, true)
if remaining and remaining:is_empty() then
item_stack:take_item(1)
end
end
end
end
local groups = {
cracky = 1,
dust_bin = 1, -- so neighbour nodes what it is.
item_interface_in = 1, -- in just for the bins
item_interface_out = 1,
}
yatm.register_stateful_node("yatm_woodcraft:dust_bin", {
basename = "yatm_woodcraft:dust_bin",
description = "Dust Bin",
codex_entry_id = "yatm_woodcraft:dust_bin",
groups = groups,
paramtype = "none",
paramtype2 = "facedir",
drawtype = "nodebox",
item_interface = dust_bin_item_interface,
on_construct = dust_bin_on_construct,
on_rightclick = dust_bin_on_rightclick,
}, {
empty = {
groups = table_merge(groups, { empty_dust_bin = 1 }),
tiles = {
"yatm_dust_bin_top.png",
"yatm_dust_bin_bottom.png",
"yatm_dust_bin_side.png",
"yatm_dust_bin_side.png^[transformFX",
"yatm_dust_bin_back.png",
"yatm_dust_bin_front.png",
},
node_box = {
type = "fixed",
fixed = {
ng( 0, 0, 0, 16, 16, 2),
ng( 0, 0, 0, 2, 16, 16),
ng( 0, 0, 14, 16, 16, 2),
ng(14, 0, 0, 2, 16, 16),
ng( 2, 0, 2, 12, 1, 12),
},
},
},
sawdust = {
groups = table_merge(groups, { not_in_creative_inventory = 1 }),
tiles = {
"yatm_dust_bin_top.png^(yatm_sawdust_base.png^[mask:yatm_dust_bin_top.mask.png)",
"yatm_dust_bin_bottom.png",
"yatm_dust_bin_side.png",
"yatm_dust_bin_side.png^[transformFX",
"yatm_dust_bin_back.png",
"yatm_dust_bin_front.png",
},
node_box = {
type = "fixed",
fixed = {
ng( 0, 0, 0, 16, 16, 2),
ng( 0, 0, 0, 2, 16, 16),
ng( 0, 0, 14, 16, 16, 2),
ng(14, 0, 0, 2, 16, 16),
ng( 2, 0, 2, 12, 14, 12),
},
},
}
})
|
-- Mock version of various items for testing
local _M = {}
local r = {
puts = function(r, ...) print(...) end,
getcookie = function(r, name) return nil end,
strcmp_match = function(str, pat)
pat = pat:gsub("%.", "%%."):gsub("*", ".+")
return str:match(pat)
end,
ivm_set = function(r, key, val) _M['ivm_' .. key] = val end,
ivm_get = function(r, key) return _M['ivm_' .. key] end,
}
local function account(uid)
return {
credentials = {
uid = uid,
},
internal = {
oauth_used = 'localhost',
},
}
end
return {
r = r,
account = account
}
|
pcall(require, 'luarocks.loader')
---@diagnostic disable-next-line: lowercase-global
root = root or {}
local awful = require('awful')
local beautiful = require('beautiful')
local gears = require('gears')
require('awful.autofocus')
local config = require('config')
local bar = require('bar')
local errors = require('errors')
local keybindings = require('keybindings')
local rules = require('rules')
local signals = require('signals')
errors.startup_errors()
errors.runtime_errors()
beautiful.init(gears.filesystem.get_configuration_dir()..'/theme.lua')
awful.layout.layouts = config.layouts
awful.screen.connect_for_each_screen(bar.setup)
root.keys(keybindings.global_keys)
awful.rules.rules = rules
signals.setup()
-- TODO:
-- other keymaps when using scylla/kyria keyboard
|
--constants
--pin assignments:
CS_BREW = 3
CS_STEAM = 4
STEAM_PIN = 1
SSR_PIN = 2
--calibration:
BREW_ZERO = 7620.5 --adc reading at 0C
STEAM_ZERO = 7620.5
--safety:
HIGH_TEMP_LOCKOUT = 170 --temp above this value is an error, or thermal runaway
LOW_TEMP_LOCKOUT = 10 --temp below this value is an error (or a broken furnace)
--initialize interfaces:
gpio.mode(STEAM_PIN, gpio.INPUT, gpio.PULLUP)
gpio.mode(SSR_PIN, gpio.OUTPUT)
gpio.write(SSR_PIN, 0)
gpio.mode(CS_BREW, gpio.OUTPUT)
gpio.write(CS_BREW, 1)
gpio.mode(CS_STEAM, gpio.OUTPUT)
gpio.write(CS_STEAM, 1)
local function start_ap()
--switch from sta to ap in case wifi is not set-up
print('wifi sta not connecting... setting up AP')
--TODO
end
local function main()
node.LFS.temp_control() --start PID routine
node.LFS.server() --start HTTP / WS server
node.LFS.ws_controller() --initialize server-side WS responder
--read config file into PID controller
local f = file.open('config', 'r')
if f ~= nil then
local cfg = f:readline()
while cfg ~= nil do
--initialize config the same way we set values from websockets
ws_on_message(cfg, 1)
cfg = f:readline()
end
f:close()
end
local poll_wifi_retries = 0
local function poll_wifi(timer)
poll_wifi_retries = poll_wifi_retries + 1
if wifi.getmode() ~= wifi.STATION then
wifi.setmode(wifi.STATION)
end
if wifi.sta.status() == wifi.STA_GOTIP then
local ip, nm, gw = wifi.sta.getip()
print('wifi sta connected with IP: '..ip)
else
if poll_wifi_retries > 10 then
start_ap()
else
tmr.create():alarm(1000, tmr.ALARM_SINGLE, poll_wifi)
end
end
end
poll_wifi()
end
startup = tmr.create()
startup:alarm(2000, tmr.ALARM_SINGLE, main)
print('station mac address for setting static ip: '..wifi.sta.getmac())
print('starting in 2 sec call startup:unregister() to stop')
|
local Name, Addon = ...
local Models, Store, Util = Addon.Models, Addon.Store, Addon.Util
local Self = Addon.Craft
-- Craft tradeskill lines
Self.LINE_ALCHEMY = 171
Self.LINE_BLACKSMITHING = 164
Self.LINE_ENCHANTING = 333
Self.LINE_ENGINEERING = 202
Self.LINE_INSCRIPTION = 773
Self.LINE_JEWELCRAFTING = 755
Self.LINE_LEATHERWORKING = 165
Self.LINE_TAILORING = 197
Self.LINE_SKINNING = 393
Self.LINE_MINING = 186
Self.LINE_HERBALISM = 182
Self.LINE_SMELTING = nil -- TODO
Self.LINE_COOKING = 185
Self.LINE_FISHING = 356
Self.LINE_ARCHAEOLOGY = nil -- TODO
-- Craft tradeskill spell ids
Self.PROF_ALCHEMY = 2259
Self.PROF_BLACKSMITHING = 3100
Self.PROF_ENCHANTING = 7411
Self.PROF_ENGINEERING = 4036
Self.PROF_INSCRIPTION = 45357
Self.PROF_JEWELCRAFTING = 25229
Self.PROF_LEATHERWORKING = 2108
Self.PROF_TAILORING = 3908
Self.PROF_SKINNING = 8613
Self.PROF_MINING = 2575
Self.PROF_HERBALISM = 2366
Self.PROF_SMELTING = 2656
Self.PROF_COOKING = 2550
Self.PROF_FISHING = 131474
Self.PROF_ARCHAEOLOGY = 78670
function Self.IsInfoAvailable()
return C_TradeSkillUI.IsTradeSkillReady() and not (C_TradeSkillUI.IsTradeSkillGuild() or C_TradeSkillUI.IsTradeSkillLinked() or C_TradeSkillUI.IsNPCCrafting())
end
function Self.GetCurrentLine()
local line, _, _, _, _, parentLine = C_TradeSkillUI.GetTradeSkillLine()
return parentLine or line
end |
QuickAccess = QuickAccess or class()
function QuickAccess:init(parent, menu)
self._parent = parent
local normal = not Global.editor_safe_mode
local size = BLE.Options:GetValue("QuickAccessToolbarSize")
local toolbar_position = BLE.Options:GetValue("ToolbarPosition")
local reversed = BLE.Options:GetValue("GUIOnRight")
if toolbar_position == 1 then
position = reversed and "TopLeft" or "TopRight"
elseif toolbar_position == 2 then
position = "CenterTop"
reversed = false
elseif toolbar_position == 3 then
position = "CenterBottom"
reversed = false
end
self._menu = menu:Menu({
name = "Toolbar",
auto_foreground = true,
scrollbar = false,
visible = self:value("QuickAccessToolbar"),
position = position,
align_method = toolbar_position > 1 and "reversed_grid" or "reversed",
private = {offset = 0}
})
local icons = BLE.Utils.EditorIcons
self._values = {
{name = "SnapRotation", rect = icons.snap_rotation, reversed = reversed, max = 360, default = 90, help = "Sets the amount(in degrees) that the unit will rotate", help2 = "Reset snap rotation to 90 degrees"},
{name = "GridSize", rect = icons.grid, reversed = not reversed, max = 10000, default = 100, help = "Sets the amount(in centimeters) that the unit will move", help2 = "Reset grid size to 100 centimeters"}
}
self._toggles = {
{name = "IgnoreFirstRaycast", rect = icons.ignore_raycast, offset = reversed and 0, help = "Ignore First Raycast"},
{name = "ShowElements", rect = icons.show_elements, help = "Show Elements"},
{name = "EditorUnits", rect = icons.editor_units, help = "Draw editor units"},
{name = "rotation_widget_toggle", rect = icons.rotation_widget, callback = ClassClbk(self, "toggle_widget", "rotation"), help = "Toggle Rotation Widget", enabled = normal and self._parent._has_fix},
{name = "move_widget_toggle", rect = icons.move_widget, offset = reversed and {2,0} or 0, callback = ClassClbk(self, "toggle_widget", "move"), help = "Toggle Move Widget", enabled = normal and self._parent._has_fix}
}
self._buttons = {
{name = "GeneralOptions", rect = icons.settings_gear, offset = reversed and 0, callback = "open_options", help = "General Options"},
{name = "Deselect", rect = icons.cross_box, callback = "deselect_unit", help = "Deselect", enabled = normal and self._parent._has_fix},
{name = "TeleportPlayer", rect = icons.teleport, callback = "drop_player", help = "Teleport Player To Camera Position", enabled = normal and self._parent._has_fix},
{name = "TeleportToSelection", rect = icons.teleport_selection, callback = "to_selection", help = "Teleport Camera To Selection", enabled = normal and self._parent._has_fix},
{name = "LocalTransform", rect = icons.local_transform, offset = reversed and {2,0} or 0, callback = "toggle_local_move", help = "Local Transform Orientation", enabled = normal and self._parent._has_fix}
}
local opt = {h = size, offset = {0, 2}, background_color = BLE.Options:GetValue("ToolbarBackgroundColor"), align_method = reversed and "grid" or "reversed_grid"}
if toolbar_position == 2 then
opt.offset = {2, 0}
elseif toolbar_position == 3 then
opt.offset = {2, 1}
end
self:build_buttons(self._menu:holder("Buttons", opt))
self:build_toggles(self._menu:holder("Toggles", opt))
if toolbar_position == 3 then
opt.offset = {0, 1}
else
opt.offset = 0
end
self:build_values(self._menu:holder("Values", opt))
self:AlignItems(self._menu, toolbar_position > 1)
self._menu:AlignItems()
end
function QuickAccess:build_values(parent)
for _, value in pairs(self._values) do
local t = self:NumberBox(parent, value.name, value)
end
self:AlignItems(parent)
end
function QuickAccess:NumberBox(parent, name, params)
local width = self._menu:Items()[1]:W() / 2
local holder = parent:holder(name.."_panel", {
offset = 0,
w = width,
size = parent:H(),
h = parent:H(),
align_method = params.reversed and "grid" or "grid_from_right_reversed"
})
holder:tb_imgbtn(name.."_icon", ClassClbk(self, "ResetNumberBox", name, params.default), nil, params.rect, {offset = 0, border_bottom = true, size = holder:H(), help = params.help2, background_color = BLE.Options:GetValue("ToolbarButtonsColor")})
holder:numberbox(name, ClassClbk(self, "SetOptionValue"), self:value(name), {offset = 0, w = (width-parent:H())-1, size = holder:H() * 0.75, h = holder:H(), text_offset = 0, min = 1, max = params.max, floats = 0, text = false, help = params.help, background_color = BLE.Options:GetValue("ToolbarButtonsColor")})
end
function QuickAccess:build_toggles(parent)
for _, toggle in pairs(self._toggles) do
local t = self:Toggle(parent, toggle, "textures/editor_icons_df")
if toggle.name:match("_widget_toggle") then
self:update_widget_toggle(t)
elseif not toggle.callback then
self:UpdateToggle(toggle.name, self:value(toggle.name))
end
end
self:AlignItems(parent)
end
function QuickAccess:Toggle(parent, params, tx)
local item = parent:tb_imgbtn(params.name, params.callback or ClassClbk(self, "ToggleOptionValue", params.name), nil, params.rect, {
w = parent:H(),
h = parent:H(),
offset = params.offset or {2, 0},
help = params.help,
enabled = params.enabled,
disabled_alpha = 0.2,
enabled_color = 1,
background_color = BLE.Options:GetValue("ToolbarButtonsColor")
})
return item
end
function QuickAccess:build_buttons(parent)
for _, button in pairs(self._buttons) do
parent:tb_imgbtn(button.name, ClassClbk(self, button.callback), nil, button.rect, {
w = parent:H(),
h = parent:H(),
offset = button.offset or {2, 0},
help = button.help,
enabled = button.enabled,
disabled_alpha = 0.2,
background_color = BLE.Options:GetValue("ToolbarButtonsColor")
})
end
self:AlignItems(parent)
end
function QuickAccess:AlignItems(panel, additive)
local max_w = 0
local function align(item)
if additive then
max_w = max_w + item:W()+2
else
max_w = item:Right()
end
end
local items = panel:Items()
if panel.align_method == "reversed_grid" then
for i=#items, 1, -1 do
align(items[i])
end
else
for i=1, #items do
align(items[i])
end
end
panel:SetSize(max_w)
end
function QuickAccess:SetVisible(visible)
self._menu:SetVisible(visible)
end
function QuickAccess:SetOptionValue(item)
local opt = BLE.Utils:GetPart("opt")
local name, value = item:Name(), item:Value()
item = opt:GetItem(name)
item:SetValue(value, true)
end
function QuickAccess:ToggleOptionValue(name, item)
local opt = BLE.Utils:GetPart("opt")
local op_item = opt:GetItem(name)
local value = not op_item:Value()
op_item:SetValue(value, true)
item.img:set_alpha(value and 1 or 0.5)
item:SetEnabled(item.enabled)
item:SetBorder({bottom = value})
end
function QuickAccess:UpdateToggle(name, val)
local item = self._menu:GetItem(name)
if item then
item.img:set_alpha(val and 1 or 0.5)
item:SetBorder({bottom = val})
end
end
function QuickAccess:UpdateNumberBox(name)
local inputItem = self._menu:GetItem(name)
local value = self:value(name)
inputItem:SetValue(value)
end
function QuickAccess:ResetNumberBox(name, val)
local inputItem = self._menu:GetItem(name)
inputItem:SetValue(val)
self:SetOptionValue(inputItem)
end
function QuickAccess:toggle_widget(name, item)
if ctrl() then return end
item = item or self._menu:GetItem(name.."_widget_toggle")
local menu = item.parent
if not item.enabled then return end
self._parent["toggle_"..name.."_widget"](self._parent)
self._parent:use_widgets(self._parent:selected_unit() ~= nil)
self:update_widget_toggle(item)
end
function QuickAccess:update_widget_toggle(item)
local name = item.name:gsub("_widget_toggle", "")
local enabled = self._parent[name.."_widget_enabled"](self._parent)
item:SetBorder({bottom = enabled})
item.img:set_alpha(enabled and 1 or 0.5)
end
function QuickAccess:update_local_move(val)
local buttonItem = self._menu:GetItem("LocalTransform")
local rect = val and BLE.Utils.EditorIcons.local_transform or BLE.Utils.EditorIcons.global_transform
buttonItem.img:set_image("textures/editor_icons_df", unpack(rect))
buttonItem:SetHelp((val and "Local" or "Global") .. " Transform Orientation")
end
function QuickAccess:update_grid_size() self:UpdateNumberBox("GridSize") end
function QuickAccess:update_snap_rotation() self:UpdateNumberBox("SnapRotation") end
function QuickAccess:toggle_local_move() self._parent:toggle_local_move() end
function QuickAccess:deselect_unit() BLE.Utils:GetPart("static"):deselect_unit() end
function QuickAccess:drop_player() game_state_machine:current_state():freeflight_drop_player(self._parent._camera_pos, Rotation(self._parent._camera_rot:yaw(), 0, 0)) end
function QuickAccess:to_selection() return BLE.Utils:GetPart("static"):KeyFPressed() end
function QuickAccess:open_options()
BLE.Menu:select_page("options")
BLE.Menu:set_enabled(true)
end
function QuickAccess:enabled() return self:value("QuickAccessToolbar") end
function QuickAccess:value(n) return BLE.Options:GetValue("Map/" .. n, "Value") end |
local status_ok, lsp_installer = pcall(require, "nvim-lsp-installer")
if not status_ok then
vim.notify("could not load lsp_installer")
return
end
-- Register a handler that will be called for all installed servers.
-- Alternatively, you may also register handlers on specific server instances instead (see example below).
lsp_installer.on_server_ready(function(server)
local opts = {
on_attach = require("user.lsp.handlers").on_attach,
capabilities = require("user.lsp.handlers").capabilities,
}
if server.name == "gopls" then
local gopls_opts = require("user.lsp.settings.gopls")
opts = vim.tbl_deep_extend("force", gopls_opts, opts)
end
if server.name == "sumneko_lua" then
local sumneko_opts = require("user.lsp.settings.sumneko_lua")
opts = vim.tbl_deep_extend("force", sumneko_opts, opts)
end
-- This setup() function is exactly the same as lspconfig's setup function.
-- Refer to https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md
server:setup(opts)
end)
-- organize imports
-- https://github.com/neovim/nvim-lspconfig/issues/115#issuecomment-902680058
function OrganizeImports(timeoutms)
local params = vim.lsp.util.make_range_params()
params.context = { only = { "source.organizeImports" } }
local result = vim.lsp.buf_request_sync(0, "textDocument/codeAction", params, timeoutms)
for _, res in pairs(result or {}) do
for _, r in pairs(res.result or {}) do
if r.edit then
vim.lsp.util.apply_workspace_edit(r.edit, "UTF-8")
else
vim.lsp.buf.execute_command(r.command)
end
end
end
end
|
require("moonsc").import_tags()
-- We test that typexpr is evaluated at runtime.
-- If the original value of var1 is used, the invocation will
-- fail (test215sub1.scxml is not of type 'foo', even if the
-- platform supports foo as a type). If the runtime value is
-- used, the invocation will succeed
return _scxml{ initial="s0",
_datamodel{
_data{ id="var1", expr="'foo'" },
},
_state{ id="s0",
_onentry{
_send{ event="timeout", delay="5s" },
_assign{ location="var1", expr="'scxml'" },
},
_invoke{ typeexpr="var1",
_content{ text=[[
require("moonsc").import_tags()
-- When invoked, terminate returning done.invoke.
-- This proves that the invocation succeeded.
return _scxml{ initial="subFinal", _final{ id="subFinal" }}
]]},
},
_transition{ event="done.invoke", target="pass" },
_transition{ event="*", target="fail" },
},
_final{id='pass'},
_final{id='fail'},
}
|
local cjson = require "cjson"
local helpers = require "spec.helpers"
for _, strategy in helpers.each_strategy() do
describe("Plugin: acl (API) [#" .. strategy .. "]", function()
local consumer
local admin_client
local bp
local db
lazy_setup(function()
bp, db = helpers.get_db_utils(strategy, {
"routes",
"services",
"plugins",
"consumers",
"acls",
})
assert(helpers.start_kong({
database = strategy,
}))
admin_client = helpers.admin_client()
end)
lazy_teardown(function()
if admin_client then
admin_client:close()
end
helpers.stop_kong()
end)
describe("/consumers/:consumer/acls/", function()
lazy_setup(function()
db:truncate()
consumer = bp.consumers:insert({
username = "bob"
}, { nulls = true })
end)
before_each(function()
db:truncate("acls")
end)
describe("POST", function()
it("creates an ACL association", function()
local res = assert(admin_client:post("/consumers/bob/acls", {
body = {
group = "admin"
},
headers = {
["Content-Type"] = "application/json"
}
}))
local body = assert.res_status(201, res)
local json = cjson.decode(body)
assert.equal(consumer.id, json.consumer.id)
assert.equal("admin", json.group)
end)
describe("errors", function()
it("returns bad request", function()
local res = assert(admin_client:post("/consumers/bob/acls", {
body = {},
headers = {
["Content-Type"] = "application/json"
}
}))
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ group = "required field missing" }, json.fields)
end)
end)
end)
describe("GET", function()
lazy_teardown(function()
db:truncate("acls")
end)
it("retrieves the first page", function()
bp.acls:insert_n(3, { consumer = { id = consumer.id } })
local res = assert(admin_client:get("/consumers/bob/acls"))
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.is_table(json.data)
assert.equal(3, #json.data)
end)
end)
end)
describe("/consumers/:consumer/acls/:id", function()
local acl, acl2
before_each(function()
db:truncate("acls")
acl = bp.acls:insert {
group = "hello",
consumer = { id = consumer.id },
}
acl2 = bp.acls:insert {
group = "hello2",
consumer = { id = consumer.id },
}
end)
describe("GET", function()
it("retrieves by id", function()
local res = assert(admin_client:get("/consumers/bob/acls/" .. acl.id))
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.equal(acl.id, json.id)
end)
it("retrieves by group", function()
local res = assert(admin_client:get("/consumers/bob/acls/" .. acl.group))
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.equal(acl.id, json.id)
end)
it("retrieves ACL by id only if the ACL belongs to the specified consumer", function()
bp.consumers:insert {
username = "alice"
}
local res = assert(admin_client:get("/consumers/bob/acls/" .. acl.id))
assert.res_status(200, res)
res = assert(admin_client:get("/consumers/alice/acls/" .. acl.id))
assert.res_status(404, res)
end)
it("retrieves ACL by group only if the ACL belongs to the specified consumer", function()
local res = assert(admin_client:get("/consumers/bob/acls/" .. acl.group))
assert.res_status(200, res)
res = assert(admin_client:get("/consumers/alice/acls/" .. acl.group))
assert.res_status(404, res)
end)
end)
describe("PUT", function()
it("updates an ACL's groupname", function()
local res = assert(admin_client:put("/consumers/bob/acls/pro", {
body = {},
headers = {
["Content-Type"] = "application/json"
}
}))
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.equal(consumer.id, json.consumer.id)
assert.equal("pro", json.group)
end)
describe("errors", function()
it("returns bad request", function()
local res = assert(admin_client:put("/consumers/bob/acls/f7852533-9160-4f5a-ae12-1ab99219ea95", {
body = {
group = 123,
},
headers = {
["Content-Type"] = "application/json"
}
}))
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ group = "expected a string" }, json.fields)
end)
end)
end)
describe("PATCH", function()
it("updates an ACL group by id", function()
local previous_group = acl.group
local res = assert(admin_client:patch("/consumers/bob/acls/" .. acl.id, {
body = {
group = "updatedGroup"
},
headers = {
["Content-Type"] = "application/json"
}
}))
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.not_equal(previous_group, json.group)
end)
it("updates an ACL group by group", function()
local previous_group = acl.group
local res = assert(admin_client:patch("/consumers/bob/acls/" .. acl.group, {
body = {
group = "updatedGroup2"
},
headers = {
["Content-Type"] = "application/json"
}
}))
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.not_equal(previous_group, json.group)
end)
describe("errors", function()
it("handles invalid input", function()
local res = assert(admin_client:patch("/consumers/bob/acls/" .. acl.id, {
body = {
group = 123,
},
headers = {
["Content-Type"] = "application/json"
}
}))
local body = assert.res_status(400, res)
local json = cjson.decode(body)
assert.same({ group = "expected a string" }, json.fields)
end)
end)
end)
describe("DELETE", function()
it("deletes an ACL group by id", function()
local res = assert(admin_client:delete("/consumers/bob/acls/" .. acl.id))
assert.res_status(204, res)
end)
it("deletes an ACL group by group", function()
local res = assert(admin_client:delete("/consumers/bob/acls/" .. acl2.group))
assert.res_status(204, res)
end)
describe("errors", function()
it("returns 404 on missing group", function()
local res = assert(admin_client:delete("/consumers/bob/acls/blah"))
assert.res_status(404, res)
end)
it("returns 404 if not found", function()
local res = assert(admin_client:delete("/consumers/bob/acls/00000000-0000-0000-0000-000000000000"))
assert.res_status(404, res)
end)
end)
end)
end)
describe("/acls", function()
local consumer2
describe("GET", function()
lazy_setup(function()
db:truncate("acls")
for i = 1, 3 do
bp.acls:insert {
group = "group" .. i,
consumer = { id = consumer.id },
}
end
consumer2 = bp.consumers:insert {
username = "bob-the-buidler"
}
for i = 1, 3 do
bp.acls:insert {
group = "group" .. i,
consumer = { id = consumer2.id },
}
end
end)
it("retrieves all the acls with trailing slash", function()
local res = assert(admin_client:get("/acls/"))
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.is_table(json.data)
assert.equal(6, #json.data)
end)
it("retrieves all the acls without trailing slash", function()
local res = assert(admin_client:get("/acls"))
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.is_table(json.data)
assert.equal(6, #json.data)
end)
it("paginates through the acls", function()
local res = assert(admin_client:get("/acls?size=3"))
local body = assert.res_status(200, res)
local json_1 = cjson.decode(body)
assert.is_table(json_1.data)
assert.equal(3, #json_1.data)
res = assert(admin_client:get("/acls", {
query = {
size = 3,
offset = json_1.offset,
}
}))
body = assert.res_status(200, res)
local json_2 = cjson.decode(body)
assert.is_table(json_2.data)
assert.equal(3, #json_2.data)
assert.not_same(json_1.data, json_2.data)
-- Disabled: on Cassandra, the last page still returns a
-- next_page token, and thus, an offset proprty in the
-- response of the Admin API.
--assert.is_nil(json_2.offset) -- last page
end)
end)
end)
describe("/acls/:acl_id/consumer", function()
describe("GET", function()
local credential
lazy_setup(function()
db:truncate("acls")
credential = db.acls:insert {
group = "foo-group",
consumer = { id = consumer.id },
}
end)
it("retrieves a Consumer from an acl's id", function()
local res = assert(admin_client:get("/acls/" .. credential.id .. "/consumer"))
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.same(consumer, json)
end)
end)
end)
end)
end
|
--加上需要require的路径
package.path = package.path..
";./lua/sandbox/?.lua;"
JSONLIB = require("JSON")
utils = require("utils")
local less = false
local maxLine = 10
local maxLen = 500
--重写print函数
function print(...)
if less then return end
if lua_run_result_var ~= "" then
lua_run_result_var = lua_run_result_var.."\r\n"
end
for i=1,select('#', ...) do
lua_run_result_var = lua_run_result_var..tostring(select(i, ...))
if i ~= select('#', ...) then
lua_run_result_var = lua_run_result_var.."\t"
end
end
local _, count = lua_run_result_var:gsub("\n", "\n")
if count >= maxLine then
lua_run_result_var = lua_run_result_var.."\r\n...\r\n余下输出过多,自动省略"
less = true
end
if lua_run_result_var:len() >= maxLen then
lua_run_result_var = lua_run_result_var:sub(maxLen).."\r\n...\r\n余下输出过多,自动省略"
less = true
end
end
json = {
null = "\0",
decode = function (s)--安全的,带解析结果返回的json解析函数
local result, info = pcall(function(t) return JSONLIB:decode(t) end, s)
if result then
return info, true
else
return {}, false, info
end
end,
encode = function (t)
return JSONLIB:encode(t,nil,{null=json.null})
end
}
do
local runCount = 0
local start = os.time()
local ot = os.time
local e = error
local function trace (event, line)
runCount = runCount + 1
if runCount > 100000 then
e("运行代码量超过阈值")
end
if ot() - start >= 5 then
e("代码运行超时")
end
end
debug.sethook(trace, "l")
end
loadstring = load
pack = {
pack = string.pack,
unpack = function (s,f,h)
local t
if h then
t = table.pack(string.unpack(f,s:sub(h)))
else
t = table.pack(string.unpack(f,s))
end
table.insert(t,1,table.remove(t,#t))
return table.unpack(t)
end,
}
BIT = require("bit")
bit = BIT.bit32
bit.bit = function(b) return bit.lshift(1,b) end
bit.isset = function(v,p) return bit.rshift(v,p) % 2 == 1 end
bit.isclear = function(v,p) return not bit.isset(v,p) end
nvm = require("nvm")
log = {
info = print,
trace = print,
debug = print,
warn = print,
error = print,
fatal = print,
}
misc = require("misc")
--安全的函数
local safeFunctions = {
assert = true,
setmetatable = true,
getmetatable = true,
error = true,
ipairs = true,
next = true,
pairs = true,
pcall = true,
select = true,
tonumber = true,
tostring = true,
type = true,
unpack = true,
_VERSION = true,
xpcall = true,
coroutine = true,
string = true,
table = true,
math = true,
print = true,
_G = true,
lua_run_result_var = true,
os = true,
JSONLIB = true,
json = true,
loadstring = true,
pack = true,
lockbox = true,
crypto = true,
bit = true,
nvm = true,
log = true,
misc = true,
}
--安全的os函数
local safeOsFunctions = {
clock = true,
difftime = true,
time = true,
date = true,
}
--去除所有不安全函数
for fnc in pairs(os) do
if not safeOsFunctions[fnc] then
os[fnc] = nil
end
end
for fnc in pairs(_G) do
if not safeFunctions[fnc] then
_G[fnc] = nil
end
end
|
local windAttack = {}
windAttack.name = "windAttackTrigger"
windAttack.placements = {
name = "wind_attack"
}
return windAttack |
--[[
GD50
Pokemon
Author: Colton Ogden
[email protected]
]]
Entity = Class{}
function Entity:init(def)
self.direction = 'down'
self.animations = self:createAnimations(def.animations)
self.mapX = def.mapX
self.mapY = def.mapY
self.width = def.width
self.height = def.height
self.x = (self.mapX - 1) * TILE_SIZE
-- halfway raised on the tile just to simulate height/perspective
self.y = (self.mapY - 1) * TILE_SIZE - self.height / 2
end
function Entity:changeState(name)
self.stateMachine:change(name)
end
function Entity:changeAnimation(name)
self.currentAnimation = self.animations[name]
end
function Entity:createAnimations(animations)
local animationsReturned = {}
for k, animationDef in pairs(animations) do
animationsReturned[k] = Animation {
texture = animationDef.texture or 'entities',
frames = animationDef.frames,
interval = animationDef.interval
}
end
return animationsReturned
end
--[[
Called when we interact with this entity, as by pressing enter.
]]
function Entity:onInteract()
end
function Entity:processAI(params, dt)
self.stateMachine:processAI(params, dt)
end
function Entity:update(dt)
self.currentAnimation:update(dt)
self.stateMachine:update(dt)
end
function Entity:render()
self.stateMachine:render()
end |
workspace "Minigames"
architecture "x64"
configurations
{
"Debug",
"Release",
"Dist"
}
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
include "Minigames"
include "Minigames/vendor/glfw"
include "Minigames/vendor/glad"
include "Minigames/vendor/ImGui"
|
--Design
pokedexWindow = nil
--functions
Painel = {
pokedex = {
['pnlDescricao'] = "",
['pnlAtaques'] = "",
['pnlHabilidades'] = "",
}
}
openedDex = {}
dexMax = 0
function init()
connect(g_game, { onEditText = showPokemonDescription, onGameEnd = hide } )
end
function showPokedex()
if pokedexWindow then
pokedexWindow:destroy()
end
pokedexWindow = g_ui.displayUI('game_pokedex')
end
function terminate()
disconnect(g_game, { onEditText = showPokemonDescription, onGameEnd = hide } )
end
function hide()
pokedexWindow:destroy()
end
function Painel.show(childName)
pokedexWindow:getChildById('pnlDescricao'):getChildById('lblConteudo'):setText(Painel.pokedex['pnlDescricao'])
pokedexWindow:getChildById('pnlAtaques'):getChildById('lblConteudo'):setText(Painel.pokedex['pnlAtaques'])
pokedexWindow:getChildById('pnlHabilidades'):getChildById('lblConteudo'):setText(Painel.pokedex['pnlHabilidades'])
pokedexWindow:getChildById('pnlDescricao'):setVisible(false)
pokedexWindow:getChildById('scrDescricao'):setVisible(false)
pokedexWindow:getChildById('pnlAtaques'):setVisible(false)
pokedexWindow:getChildById('scrAtaques'):setVisible(false)
pokedexWindow:getChildById('pnlHabilidades'):setVisible(false)
pokedexWindow:getChildById('scrHabilidades'):setVisible(false)
pokedexWindow:getChildById(childName):setVisible(true)
pokedexWindow:getChildById('scr'..childName:sub(4,#childName)):setVisible(true)
end
function showPokemonDescription(id, itemId, maxLength, texto, writter, time)
if not g_game.isOnline() then return end --Se nao estiver online
local name = texto:match('Name: (.-)\n')
local type = texto:match('Type: (.-)\n')
--Se for chamada de pokedex
if name and type then
showPokedex()
--Required Level
local requieredLevel = texto:match('Required level: (.-)\n')
--Evolution Description
local evoDesc = texto:match('\nEvolutions:\n(.-)\n')
--MOVES
local moves = texto:match('\nMoves:\n(.-)\nAbility:')
--Ability
local ability = texto:sub(texto:find('Ability:\n')+9,#texto)
pokedexWindow:getChildById('lblPokeName'):setText(name)
if name:find("Shiny") then
name = name:sub(7,#name)
pokedexWindow:getChildById('lblPokeName'):setColor("red")
end
local f = io.open("modules/game_pokedex/imagens/pokemons/"..name..".png","r");
if not f then
print("Not found poke image called "..name)
else
f:close()
pokedexWindow:getChildById('imgPokemon'):setImage("/game_pokedex/imagens/pokemons/"..name..".png")
end
Painel.pokedex["pnlDescricao"] = "Tipo: "..type.."\nNivel Requerido: "..requieredLevel.."\n\nEvolucoes:\n"..evoDesc
Painel.pokedex["pnlAtaques"] = moves
Painel.pokedex["pnlHabilidades"] = ability
Painel.show('pnlDescricao')
end
end |
return {'abdicatie','abdiceren','abdij','abdijbier','abdijcomplex','abdijgebouw','abdijkerk','abdijsiroop','abdiqueren','abdis','abdomen','abdominaal','abdijgemeenschap','abdijhoeve','abdijsite','abd','abdallah','abdel','abdelaziz','abdelkader','abdelkarim','abdellah','abdoel','abdul','abdullah','abdullahi','abdurrahman','abdi','abdalla','abdellaoui','abdicaties','abdiceer','abdiceerde','abdiceerden','abdiceert','abdijen','abdijkerken','abdissen','abdomens','abdijgebouwen','abdiqueerde','abdominale','abds','abdallahs','abdels','abdelaziz','abdelkaders','abdelkarims','abdellahs','abdoels','abduls','abdullahs','abdullahis','abdurrahmans','abdijbieren','abdijbiertje','abdijsites'} |
--- A double queue.
-- Taken from "Programming in Lua" (http://www.lua.org/pil/11.4.html)
-- Modified to not allow nil values, and returns nil if pop_first or pop_last is used when the queue is empty.
-- @module Queue
-- @usage local Queue = require('stdlib/queue')
local fail_if_missing = require 'stdlib/core'['fail_if_missing']
Queue = {} --luacheck: allow defined top
Queue.mt = {__index = Queue}
--- Constructs a new Queue object.
-- @treturn Queue A new, empty queue
function Queue.new()
local queue = {first = 0, last = -1}
setmetatable(queue, Queue.mt)
return queue
end
--- load global.queue or queues during on_load, as metatables are not persisted
-- This is only needed if you are using the queue as an object and storing it in global
-- @tparam Queue,... ...
-- @usage global.myqueue1 = Queue.new()
-- global.myqueue2 = Queue.new()
-- script.on_load(function() Queue.load(myqueue1, myqueue2))
function Queue.load(...)
if not ... then return end
for _, queue in pairs({...}) do
if queue.first then
setmetatable(queue, Queue.mt)
end
end
end
--- Push a new element to the front of the queue.
-- @tparam Queue queue the queue to push an element to
-- @param value the element to push
function Queue.push_first(queue, value)
fail_if_missing(value)
local first = queue.first - 1
queue.first = first
queue[first] = value
end
--- Push a new element to the back of the queue.
-- @tparam Queue queue the queue to push an element to
-- @param value the element to push
function Queue.push_last(queue, value)
fail_if_missing(value)
local last = queue.last + 1
queue.last = last
queue[last] = value
end
--- Remove and Return the element at the front of the queue.
-- @tparam Queue queue the queue to retrieve the element from
-- @return the element at the front of the queue
function Queue.pop_first(queue)
if Queue.is_empty(queue) then
return nil
end
local first = queue.first
local value = queue[first]
queue[first] = nil -- to allow garbage collection
queue.first = first + 1
return value
end
--- Return the element at the front of the queue.
-- @tparam Queue queue the queue to retrieve the element from
-- @return the element at the front of the queue
function Queue.peek_first (queue)
return queue[queue.first]
end
--- Remove and Return the element at the back of the queue.
-- @tparam Queue queue the queue to retrieve the element from
-- @return the element at the back of the queue
function Queue.pop_last(queue)
if Queue.is_empty(queue) then
return nil
end
local last = queue.last
local value = queue[last]
queue[last] = nil -- to allow garbage collection
queue.last = last - 1
return value
end
--- Return the element at the back of the queue.
-- @tparam Queue queue the queue to retrieve the element from
-- @return the element at the back of the queue
function Queue.peek_last (queue)
return queue[queue.last]
end
--- Returns true if the given queue is empty.
-- @tparam Queue queue the queue to check
-- @treturn boolean true if queue is empty
function Queue.is_empty(queue)
return queue.first > queue.last
end
--- Returns the number of items in the queue
-- @tparam Queue queue the queue to check
-- @treturn number the number of items in the queue
function Queue.count(queue)
if queue.first > queue.last then
return 0
else
return queue.last - queue.first + 1
end
end
return Queue
|
description 'Custom Loadscreen'
resource_manifest_version '77731fab-63ca-442c-a67b-abc70f28dfa5'
files {
'index.html',
'intro.mp4',
'styles.css',
'music.mp3'
}
loadscreen 'index.html' |
----------------------------------------------------------------------------------------------------
-- Creator Tools LUA Utilities File
----------------------------------------------------------------------------------------------------
--[[
This file includes useful functions for usage in Creator Tools Lua scripts.
Simply include this line in any script (if running a script from another location that users this file,
make sure to point to the correct path):
local ctUtil = require("CtUtil")
Then you can simply call any function like:
ctUtil.testFunction()
It is also possible of course to copy entire specific functions from this list directly into your script.
In that case remove the CtUtil part from the function name, and then simply call it normally like:
testFunction
--]]
local CtUtil = {}
-- Test function
function CtUtil.testFunction()
-- Show that the class import and test function executes by printing a line
print("Test function called")
end
-- Just a separator for printing to the console. Set an optional global printToConsole boolean variable to control printing.
function CtUtil.dashSepPrint()
local dashSep = "------------------------------------------------------------"
if printToConsole == nil then printToConsole = true end
if printToConsole then print(dashSep) end
end
-- More readable debug printing. Set an optional global printToConsole boolean variable to control printing.
function CtUtil.debugPrint(debugMessage)
if printToConsole == nil then printToConsole = true end
if printToConsole then print(debugMessage) end
end
-- Function for nicely printing the table results. Set an optional global printToConsole boolean variable to control printing.
function CtUtil.debugPrintR(arr)
if printToConsole == nil then printToConsole = true end
if printToConsole then
local str = ""
i = 1
for index,value in pairs(arr) do
indentStr = i.."\t"
str = str..indentStr..index..": "..value.."\n"
i = i+1
end
print(str)
end
end
-- Check if a Kontakt instruments is connected and print instruments information
function CtUtil.instrumentConnected()
print('LUA Script path: '..scriptPath)
if not instrument then
print('Error: The following error message informs you that the Creator Tools are not '..
'focused on a Kontakt instrument. To solve this, load an instrument in '..
'Kontakt and select it from the instrument dropdown menu on top.')
else
print('Instrument connected')
end
end
-- Check if a file has a valid audio file extension
function CtUtil.isAudioFile(file)
local extensionList = {
".wav",
".aif",
".aiff",
".rex",
".rx2",
".snd",
".ncw"
}
local checkFile = false
if filesystem.isRegularFile(file) then
for k,v in pairs(extensionList) do
if filesystem.extension(file) == v then checkFile = true end
end
end
return checkFile
end
-- Check if a value is in a range.
function CtUtil.isInRange(val,min,max)
return val >= min and val <= max
end
-- Check for a valid path and print the result
function CtUtil.pathCheck(path)
local path = filesystem.preferred(path)
if not filesystem.exists(path) then print ('Path not found') end
return path
end
-- Function for nicely printing the table results
function CtUtil.print_r(arr)
local str = ""
i = 1
for index,value in pairs(arr) do
indentStr = i.."\t"
str = str..indentStr..index..": "..value.."\n"
i = i+1
end
print(str)
end
-- Round a number to the nearest integer
function CtUtil.round(n)
return n % 1 >= 0.5 and math.ceil(n) or math.floor(n)
end
-- Scan a directory and load all files into a table, optionally recursive
function CtUtil.samplesFolder(path,recursive)
-- Error handling: If arguments aren't provided, declare defaults
if path == nil then
path = scriptPath
else
path = filesystem.preferred(path)
end
if recursive == nil then recursive = true end
print ("The samples are located in " .. path)
-- Declare an empty table which we will fill with the samples.
samples = {}
i = 1
if recursive then
for _,p in filesystem.directoryRecursive(path) do
if filesystem.isRegularFile(p) then
samples[i] = p
i = i+1
end
end
else
for _,p in filesystem.directory(path) do
if filesystem.isRegularFile(p) then
samples[i] = p
i = i+1
end
end
end
-- Return a table with the samples
return samples
end
-- Split a string and return the result after the seperator
function CtUtil.stringSplit(inputString,sep)
for s in string.gmatch(inputString, "[^"..sep.."]+") do
return s
end
end
-- Function for checking how a string starts.
function CtUtil.stringStarts(inputString,startWith)
return string.sub(inputString,1,string.len(startWith))==startWith
end
-- Return the size of a table
function CtUtil.tableSize(t)
local count = 0
for _ in pairs(t) do count = count + 1 end
return count
end
-- Check if a value exists in a table
function CtUtil.tableValueCheck (t, v)
for index, value in ipairs(t) do
if value == v then
return true
end
end
return false
end
-- Return where a value was found in a table
function CtUtil.tableValueIndex (t, v)
for index, value in ipairs(t) do
if value == v then
return index
end
end
end
-- return the CtUtil object
return CtUtil
|
-- Exports for 'Entity'
return {
CharacterEntity = require(script.CharacterEntity),
Entity = require(script.Entity),
} |
local suit = require 'lib.suit'
local bitser = require 'lib.bitser'
TheMenu = Engine:EntityClass('TheMenu')
_G.MenuStage = {
Loading = 0,
MainMenu = 1,
Playing = 2,
Gameover = 3,
}
local DEFAULT_SETTINGS = {
fullscreen = false,
volume = 1
}
function TheMenu:loadPreferences()
self.settings = DEFAULT_SETTINGS
if love.filesystem.getInfo('userpreferences.lua') ~= nil then
self.settings = util.mergeTables(self.settings, bitser.loadLoveFile('userpreferences.lua'))
print("Loaded preferences")
self.volumeSlider = { value = self.settings.volume, min = 0, max = 1 }
love.audio.setVolume(self.settings.volume)
end
end
function TheMenu:savePreferences()
if self.settings then
bitser.dumpLoveFile('userpreferences.lua', self.settings)
print("Saved preferences")
end
end
function TheMenu:setup()
self:loadPreferences()
--self.font = Engine:getAsset('fonts/HelvetiPixel.ttf:24').handle
--self.bigFont = Engine:getAsset('fonts/HelvetiPixel.ttf:60').handle
self.jfcFontForSuit = love.graphics.newFont('fonts/HelvetiPixel.ttf', 24)
self.jfcBigFontForSuit = love.graphics.newFont('fonts/HelvetiPixel.ttf', 40)
self.gameTitle = self.gameTitle or "Morning Gory"
self.stage = self.stage or MenuStage.Loading
self.stageChangeWallTime = self.stageChangeWallTime or love.timer.getTime()
self.isPaused = util.default(self.isPaused, false)
self.wasPaused = util.default(self.wasPaused, false)
self.wasRestart = util.default(self.wasRestart, false)
self.targetLevel = self.targetLevel or nil
self.targetLevelIdx = self.targetLevelIdx or nil
self.gameState = self.gameState or nil
self.leveltimes = self.leveltimes or {}
love.window.setTitle(self.gameTitle)
self.ambientSound = self.ambientSound or Engine:getAsset('sfx/ambience.mp3')
self.ambientSoundSource = self.ambientSoundSource or self.ambientSound.handle:clone()
self.volumeSlider = self.volumeSlider or { value = self.settings.volume, min = 0, max = 1 }
self.fadeFrac = self.fadeFrac or 0.0
end
function TheMenu:specialUpdate(time, dt)
Engine.UP:pushEvent('menu special update')
-- https://suit.readthedocs.io/en/latest/layout.html#
local winW, winH = love.graphics.getDimensions()
local menuW = 600
local menuY = winH - 700
local menuButtonH = 60
local doCommonMenuButtons = function()
if suit.Button('Toggle Fullscreen', { font = self.jfcBigFontForSuit }, suit.layout:row(menuW, menuButtonH)).hit then
love.window.setFullscreen(not love.window.getFullscreen(), 'desktop')
end
if suit.Button("Quit Game", { font = self.jfcBigFontForSuit }, suit.layout:row(nil, menuButtonH)).hit then
love.event.quit()
end
suit.Label("", { font = self.jfcFontForSuit }, suit.layout:row(200, 70))
suit.layout:push(suit.layout:row(nil, 40))
suit.Label("Master Volume", { font = self.jfcFontForSuit }, suit.layout:col(200, 20))
if suit.Slider(self.volumeSlider, suit.layout:col(menuW - 240)).changed then
self.settings.volume = self.volumeSlider.value
love.audio.setVolume(self.settings.volume)
end
suit.Label(("%.02f"):format(self.volumeSlider.value), suit.layout:col(40))
suit.layout:pop()
suit.layout:push(suit.layout:row(nil, 140))
if suit.Button("Cancel", { font = self.jfcFontForSuit }, suit.layout:col(menuW / 2 - 5 / 2, menuButtonH / 2)).hit then
self:loadPreferences()
self.isPaused = false
end
if suit.Button("Save", { font = self.jfcFontForSuit }, suit.layout:col(menuW / 2 - 5 / 2, menuButtonH / 2)).hit then
self:savePreferences()
if self.isPaused then self.isPaused = false end
end
suit.layout:pop()
end
suit.layout:reset(winW / 2 - menuW / 2, menuY, 5, 5) -- /* offX, offY, padX, padY */
if self.stage == MenuStage.Loading then
-- todo if loading starts to take a bit?
self:gotoStage(MenuStage.MainMenu)
elseif self.stage == MenuStage.MainMenu then
--suit.layout:reset(winW / 2 - menuW / 2, 0.3 * winH - 100, 5, 5) -- /* offX, offY, padX, padY */
--
----suit.Label(self.gameTitle, { align = "center", font = self.jfcBigFontForSuit }, suit.layout:row(menuW, 2 * menuButtonH))
--suit.Label("", { align = "center", font = self.jfcBigFontForSuit }, suit.layout:row(menuW, 2 * menuButtonH))
--
--if suit.Button('Play', suit.layout:row(menuW, menuButtonH)).hit then
-- self:gotoStage(MenuStage.Playing)
--end
suit.Label("", { align = "center", font = self.jfcBigFontForSuit }, suit.layout:row(menuW, 5 * menuButtonH))
if suit.Button("Start Game", { font = self.jfcBigFontForSuit }, suit.layout:row(menuW, menuButtonH)).hit then
self:loadLevel(1)
end
doCommonMenuButtons()
elseif self.stage == MenuStage.Playing then
if not self.ambientSoundSource:isPlaying() then
self.ambientSoundSource:setVolume(0.1)
self.ambientSoundSource:play()
self.ambientSoundSource:setLooping(true)
end
if not love.window.hasFocus() and not IS_DEBUG then
self.isPaused = true
end
if self.isPaused then
if not self.wasPaused then
Engine:onPause()
end
--suit.ImageButton(Engine:getAsset('art/ash.png').handle, suit.layout:row(menuW, 2 * menuButtonH))
suit.Label("Paused", { align = "center", font = self.jfcBigFontForSuit }, suit.layout:row(menuW, 2 * menuButtonH))
if suit.Button("Resume", { font = self.jfcBigFontForSuit }, suit.layout:row(nil, menuButtonH)).hit then
self.isPaused = false
end
if suit.Button("Restart Level", { font = self.jfcBigFontForSuit }, suit.layout:row(nil, menuButtonH)).hit then
self:loadLevel('curr', true)
self.isPaused = false
end
if suit.Button("Skip Level", { font = self.jfcBigFontForSuit }, suit.layout:row(nil, menuButtonH)).hit then
self:loadLevel('next')
self.isPaused = false
end
if suit.Button("Restart Game", { font = self.jfcBigFontForSuit }, suit.layout:row(nil, menuButtonH)).hit then
--self:loadLevel(1)
--self.isPaused = false
self:gotoStage(MenuStage.Loading)
end
doCommonMenuButtons()
else
if self.wasPaused then
Engine:onResume()
end
Engine:accumulateUpdateTime(dt)
if not GAMESTATE.player.alive then
suit.layout:reset(winW / 2 - menuW / 2, menuY, 5, 5) -- /* offX, offY, padX, padY */
suit.Label("Press R to restart", { align = "center", font = self.jfcBigFontForSuit }, suit.layout:row(menuW, 2 * menuButtonH))
end
end
self.wasPaused = self.isPaused
if self.gameState and self.gameState.player then
self.gameState.player.inputActive = not suit.hasKeyboardFocus() and not self.isPaused
end
elseif self.stage == MenuStage.Gameover then
suit.Label("", { align = "center", font = self.jfcBigFontForSuit }, suit.layout:row(menuW, 2 * menuButtonH))
suit.Label("Thanks for playing!\n\nMorning Gory\nMade for Spring Jam 2021\nBy Ettiene, Keegan, Luke and Declan", { align = "center", font = self.jfcBigFontForSuit }, suit.layout:row(menuW, 8 * menuButtonH))
if suit.Button("Continue", { font = self.jfcBigFontForSuit }, suit.layout:row(menuW, menuButtonH)).hit then
self:gotoStage(MenuStage.Loading)
end
end
if IS_DEBUG then
love.window.setTitle(string.format('%s - %1.3fms / %3.1fFPS', self.gameTitle, love.timer.getAverageDelta() * 1000, love.timer.getFPS()))
end
Engine.UP:popEvent()
end
local levels = {
{ tiledmap = Engine:getAsset('src/maps/entrance.lua'), label = "Morning Gory", },
{ tiledmap = Engine:getAsset('src/maps/riseandshine.lua'), label = "Rise and Shine", },
{ tiledmap = Engine:getAsset('src/maps/spikes.lua'), label = "Spikes", },
{ tiledmap = Engine:getAsset('src/maps/back_and_forth.lua'), label = "Back and Forth", },
{ tiledmap = Engine:getAsset('src/maps/hallway_escape.lua'), label = "Hallway Escape", },
{ tiledmap = Engine:getAsset('src/maps/laser_push.lua'), label = "Light Grid", },
{ tiledmap = Engine:getAsset('src/maps/pits.lua'), label = "Pits", },
{ tiledmap = Engine:getAsset('src/maps/lighty_mcLightface.lua'), label = "Lighty McLightface", },
{ tiledmap = Engine:getAsset('src/maps/pipework.lua'), label = "Mission Probable", },
{ tiledmap = Engine:getAsset('src/maps/kaffeine withdrawal.lua'), label = "Kaffeine Withdrawal", },
{ tiledmap = Engine:getAsset('src/maps/tubular.lua'), label = "Tubular", },
{ tiledmap = Engine:getAsset('src/maps/hide_and_seek.lua'), label = "Hide and Seek", },
{ tiledmap = Engine:getAsset('src/maps/seafloor_cavern.lua'), label = "Sea Floor Cavern", },
{ tiledmap = Engine:getAsset('src/maps/rolling_out.lua'), label = "Rolling Out", },
}
if IS_DEBUG then
local extraLevels = {
{ tiledmap = Engine:getAsset('src/maps/remote_control.lua'), label = "Remote Control", },
{ tiledmap = Engine:getAsset('src/maps/zigzag.lua'), label = "Zig Zag", },
{ tiledmap = Engine:getAsset('src/maps/test_level.lua'), label = "Test Level", },
}
for _, levelInfo in ipairs(extraLevels) do table.insert(levels, levelInfo) end
end
function TheMenu:gotoStage(newStage)
if self.stage == MenuStage.Playing then
self.gameState = Engine:Remove(self.gameState)
self.isPaused = false
end
if newStage == MenuStage.Playing then
if self.targetLevel == nil then
self.targetLevelIdx = 1
self.targetLevel = levels[self.targetLevelIdx]
end
GAMETIME = 0
self.gameState = GameState.new(self, { level = self.targetLevel, })
end
self.stage = newStage
self.stageChangeWallTime = love.timer.getTime()
end
function TheMenu:loadLevel(targetIdx, isRestart)
self.fadeFrac = 1.0
self.wasRestart = isRestart or false
local isGameover = false
if targetIdx == 'curr' then
targetIdx = self.targetLevelIdx
elseif targetIdx == 'next' then
targetIdx = math.indexWrap(self.targetLevelIdx + 1, #levels)
if targetIdx == 1 then
isGameover = true
end
end
if levels[targetIdx] then
self.targetLevelIdx = targetIdx
self.targetLevel = levels[self.targetLevelIdx]
if not isGameover then
self:gotoStage(MenuStage.Playing)
else
self:gotoStage(MenuStage.Gameover)
end
end
end
function TheMenu:setFade(frac)
self.fadeFrac = frac
end
function TheMenu:specialRender()
local winW, winH = love.graphics.getDimensions()
if GAMETIME < 10.0 then
self.fadeFrac = math.remapClamp(GAMETIME, 0, 1, 1, 0)
end
love.mouse.setVisible(self.stage ~= MenuStage.Playing or self.isPaused or IS_DEBUG)
if self.stage ~= MenuStage.MainMenu then
love.graphics.setColor(0, 0, 0, self.fadeFrac)
love.graphics.rectangle('fill', 0, 0, winW, winH)
end
local promptFont = Engine:getAsset('PromptFont')
love.graphics.setColor(1, 1, 1, 1)
love.graphics.setFont(promptFont.handle)
--local text, showSplash = "", false
--if self.stage == MenuStage.MainMenu then
-- showSplash = true
-- --text = controls .. "\nR to start game now."
--elseif self.stage == MenuStage.Gameover then
-- showSplash = true
-- text = "Thanks for playing!\n\nMorning Gory\nMade for Spring Jam 2021\nBy Ettiene, Keegan, Luke and Declan\n\n\nPress any key to continue."
--elseif self.stage == MenuStage.Playing and self.isPaused then
-- text = "ESCAPE to resume.\nF to toggle fullscreen."
--end
if self.isPaused then
love.graphics.setColor(0, 0, 0, 0.7)
love.graphics.rectangle('fill', 0, 0, winW, winH)
end
if self.stage == MenuStage.Playing and not GAMESTATE.player.alive then
love.graphics.setColor(1, 0, 0, 0.1)
love.graphics.rectangle('fill', 0, 0, winW, winH)
end
if self.stage == MenuStage.MainMenu or self.stage == MenuStage.Gameover then
local bgVideo = Engine:getAsset('art/menu/purplesmoke.ogv').handle
if not bgVideo:isPlaying() then
bgVideo:rewind()
bgVideo:play()
end
love.graphics.draw(bgVideo, 0, 0, 0, winH / bgVideo:getHeight(), winH / bgVideo:getHeight())
local img = Engine:getAsset('art/menu/logo.png').handle
local vertSize = winH / 720 * 400
local scale = vertSize / img:getHeight()
local imgSize = Vec(img:getWidth(), img:getHeight()) * scale
love.graphics.draw(img, winW / 2 - imgSize.x / 2, 30, 0, scale, scale)
local vampImg = Engine:getAsset('art/menu/vamp.png').handle
local vampScale = (winH / vampImg:getHeight()) / 1.5
local vampImgSize = Vec(vampImg:getWidth(), vampImg:getHeight()) * vampScale
love.graphics.draw(vampImg, winW - vampImgSize.x, winH - vampImgSize.y, 0, vampScale, vampScale)
end
if self.stage == MenuStage.Gameover then
-- AAAAAAHHHHH
love.graphics.setColor(0, 0, 0, 0.4)
love.graphics.rectangle('fill', (winW - 600) / 2, winH - 360, 600, winH)
end
if self.stage == MenuStage.MainMenu or (self.stage == MenuStage.Playing and self.isPaused) then
local scale = math.remapClamp(winH, 720, 1440, 0.4, 0.7)
local controls = "WASD or ARROW KEYS to move.\nE or SPACE to interact."
if ALLOW_ACCELERATE then
controls = controls .. "\nSHIFT to accelerate time."
end
controls = controls .. "\nR to restart."
local actualTextW, actualTextH = promptFont.handle:getWidth(controls), promptFont.handle:getHeight(controls)
local textW, lineH = actualTextW * scale, actualTextH * scale
love.graphics.setColor(1, 1, 1, 1)
love.graphics.printf(controls, winW - textW - 18, winH - 5 * lineH, actualTextW, 'right', 0, scale, scale)
end
if self.stage == MenuStage.Gameover then
local text = ""
local totalTime = 0
for lvlIdx in ipairs(levels) do
local time = self.leveltimes[lvlIdx]
if time ~= nil then
text = text .. string.format("Level %d completed in %.2fs\n", lvlIdx, time)
totalTime = totalTime + time
else
text = text .. string.format("Level %d not completed.\n", lvlIdx)
end
end
text = text .. string.format("Total completion time %.2fs\n", totalTime)
local promptFont = Engine:getAsset('PromptFont')
love.graphics.setFont(promptFont.handle)
local scale = math.remapClamp(winH, 720, 1440, 0.45, 0.7)
local textW, lineH = promptFont.handle:getWidth(text) * scale, promptFont.handle:getHeight(text) * scale
love.graphics.setColor(1, 1, 1, 1)
love.graphics.printf(text, 10, 54, 1200, 'left', 0, scale, scale)
end
love.graphics.reset()
love.graphics.push()
suit.draw()
love.graphics.pop()
end
function TheMenu:onKeyPressed(key, scancode, isrepeat)
if suit.hasKeyboardFocus() then
suit.keypressed(key)
return
end
if isrepeat then return end
--if self.stage == MenuStage.Gameover and love.timer.getTime() > self.stageChangeWallTime + 0.6 then
-- self:gotoStage(MenuStage.MainMenu)
--end
if key == 'escape' and self.stage == MenuStage.Playing then
self.isPaused = not self.isPaused
return
end
if key == 'r' and self.stage == MenuStage.Playing then
self:loadLevel('curr', true)
return
end
if key == 'r' and self.stage == MenuStage.MainMenu then
self:gotoStage(MenuStage.Playing)
end
--if key == 'f' then
-- love.window.setFullscreen(not love.window.getFullscreen(), 'desktop')
--end
if IS_DEBUG and key == 'f1' then
self:gotoStage(MenuStage.Loading)
return
end
if IS_DEBUG and key == 'f12' then
self:gotoStage(MenuStage.Gameover)
return
end
if IS_DEBUG and key == 'f5' then
self:loadLevel('next')
end
if self.gameState and self.gameState.player then
self.gameState.player:onKeyPressed(key, scancode)
end
end
function TheMenu:onKeyReleased(key, scancode)
if self.gameState and self.gameState.player then
self.gameState.player:onKeyReleased(key, scancode)
end
end
function TheMenu:onTextEdited(text, start, length)
suit.textedited(text, start, length)
end
function TheMenu:onTextInput(text)
suit.textinput(text)
end
function TheMenu:onMouseWheel(dx, dy)
--if Engine.camera then
-- local rate = 0.3
-- Engine.camera:setZoomScale(Engine.camera:getZoomScale() * (dy < 0 and (1 + rate) or 1 / (1 + rate)))
--end
end
|
local ParallelTable, parent = torch.class('nn.ParallelTable', 'nn.Module')
function ParallelTable:__init()
parent.__init(self)
self.modules = {}
self.output = {}
self.gradInput = {}
end
function ParallelTable:add(module)
table.insert(self.modules, module)
end
function ParallelTable:get(index)
return self.modules[index]
end
function ParallelTable:size()
return #self.modules
end
function ParallelTable:forward(input)
for i=1,#self.modules do
self.output[i] = self.modules[i]:forward(input[i])
end
return self.output
end
function ParallelTable:backward(input, gradOutput)
for i,module in ipairs(self.modules) do
self.gradInput[i]= module:backward(input[i], gradOutput[i])
end
return self.gradInput
end
function ParallelTable:zeroGradParameters()
for _,module in ipairs(self.modules) do
module:zeroGradParameters()
end
end
function ParallelTable:updateParameters(learningRate)
for _,module in ipairs(self.modules) do
module:updateParameters(learningRate)
end
end
function ParallelTable:write(file)
parent.write(self, file)
file:writeObject(self.modules)
end
function ParallelTable:read(file)
parent.read(self, file)
self.modules = file:readObject()
end
function ParallelTable:share(mlp,...)
for i=1,#self.modules do
self.modules[i]:share(mlp.modules[i],...);
end
end
|
--[[
A Frame that has an AbsoluteSize equal to the screen size, regardless of
the size of its parent. The size of this frame cannot be changed in any
way. This will error if used on the server.
This may be used the same as any ScreenGui.
]]
local GuiService = game:GetService("GuiService")
local Workspace = game:GetService("Workspace")
local Roact = require(game.ReplicatedStorage.Roact)
local e = Roact.createElement
local ScreenFrame = Roact.Component:extend("ScreenFrame")
function ScreenFrame:init()
self.state = {
_screenSize = Vector2.new(0, 0),
_parentAbsolutePosition = Vector2.new(0, 0),
}
end
function ScreenFrame:render()
return e("Frame", {
Size = UDim2.new(0, self.state._screenSize.X, 0, self.state._screenSize.Y),
Position = UDim2.new(0, -self.state._parentAbsolutePosition.X, 0, -self.state._parentAbsolutePosition.Y),
BackgroundTransparency = 1,
[Roact.Ref] = function(rbx)
self._ref = rbx
end,
}, self.props[Roact.Children])
end
function ScreenFrame:_parentDidChange()
self:setState({
_parentAbsolutePosition = self._ref.Parent.AbsolutePosition,
})
end
function ScreenFrame:_viewportSizeDidChange()
local topLeftInset, bottomLeftInset = GuiService:GetGuiInset()
local viewportSize = Workspace.CurrentCamera.ViewportSize
local screenSize = viewportSize - topLeftInset - bottomLeftInset
self:setState({
_screenSize = screenSize,
})
end
function ScreenFrame:didMount()
self:_parentDidChange()
self:_viewportSizeDidChange()
-- Parent will cause this frame to be unmounted, so we can assume that parent is constant.
self._parentConnection = self._ref.Parent:GetPropertyChangedSignal("AbsolutePosition"):Connect(function()
self:_parentDidChange()
end)
-- Assume the current camera does not change.
self._cameraConnection = Workspace.CurrentCamera:GetPropertyChangedSignal("ViewportSize"):Connect(function()
self:_viewportSizeDidChange()
end)
end
function ScreenFrame:willUnmount()
self._parentConnection:Disconnect()
self._cameraConnection:Disconnect()
end
return ScreenFrame
|
POT_GROW_TIME = 60 * 15;
MAX_POT = 5;
local MIXTURE = {}
MIXTURE.ID = 51;
MIXTURE.Results = "drug_cocaine";
MIXTURE.Ingredients = {"drug_coca_seeds", "item_pot"};
MIXTURE.Requires = {
{GENE_INTELLIGENCE, 1},
{GENE_DEXTERITY, 1},
};
MIXTURE.Free = true;
MIXTURE.RequiresHeatSource = false;
MIXTURE.RequiresWaterSource = false;
MIXTURE.RequiresSawHorse = false;
function MIXTURE.CanMix ( player, pos )
if (player:Team() != TEAM_CITIZEN) then
player:Notify("You cannot do this as a government official.");
return false;
end
local NumDrugs = 0;
for k, v in pairs(ents.FindByClass('ent_coca')) do
if v:GetTable().ItemSpawner == player then
NumDrugs = NumDrugs + 1;
end
end
local VipCoke = MAX_POT;
if(player:GetLevel() == 99) then
VipCoke = 6;
elseif(player:GetLevel() == 98) then
VipCoke = 8
elseif(player:GetLevel() <= 97) then
VipCoke = 10
end
if (NumDrugs >= VipCoke) then
if (player:GetLevel() == 100) then
player:Notify("Bronze VIP coke limit reached");
elseif(player:GetLevel() == 99) then
player:Notify("Silver VIP coke limit reached");
elseif(player:GetLevel() == 98) then
player:Notify("Gold VIP coke limit reached");
elseif(player:GetLevel() == 97) then
player:Notify("Diamond VIP coke limit reached");
elseif(player:GetLevel() <= 96) then
player:Notify("Admin coke limit reached");
else
player:Notify("Guest coke limit reached");
end
return false;
end
return true;
end
GM:RegisterMixture(MIXTURE); |
local io = require('io')
local lswCliShell = {}
function lswCliShell.blue(self, text)
return "\027[0;34m" .. text .. "\027[0m"
end
function lswCliShell.green(self, text)
return "\027[0;32m" .. text .. "\027[0m"
end
function lswCliShell.red(self, text)
return "\027[0;31m" .. text .. "\027[0m"
end
function lswCliShell.white(self, text)
return "\027[1;37m" .. text .. "\027[0m"
end
function lswCliShell.yellow(self, text)
return "\027[1;33m" .. text .. "\027[0m"
end
function lswCliShell.help(self, commands)
print('the following commands are available')
for k, v in pairs(commands or {}) do
print("\t" .. v.cmd .. "\t\t" .. v.desc)
end
end
function lswCliShell.prompt(self, prefix)
if prefix then prefix = prefix .. ' ' end
io.write(lswCliShell:blue((prefix or '')) .. '> ')
return io.read()
end
return lswCliShell
|
Locales['fr'] = {
-- DialogBox Name
['dialogbox_playerid'] = 'ID du Joueur (8 Caractères Maximum):',
['dialogbox_amount'] = 'Montant (8 Caractères Maximum):',
['dialogbox_amount_ammo'] = 'Montant de Munitions (8 Caractères Maximum):',
['dialogbox_vehiclespawner'] = 'Nom du Véhicule (50 Caractères Maximum):',
['dialogbox_xyz'] = 'Position XYZ (50 Caractères Maximum):',
-- Menu Default Vars
['default_gps'] = 'Aucun',
['default_demarche'] = 'Normal',
['default_voice'] = 'Normal',
-- Menu Notification
['missing_rights'] = 'Vous n\'avez pas les ~r~droits~w~',
['no_vehicle'] = 'Vous n\'êtes pas dans un véhicule',
['players_nearby'] = 'Aucun joueur à proximité',
['amount_invalid'] = 'Montant Invalide',
['in_vehicle_give'] = 'Impossible de donner %s dans un véhicule',
['in_vehicle_drop'] = 'Impossible de jeter %s dans un véhicule',
['not_usable'] = '%s n\'est pas utilisable',
['not_droppable'] = '%s n\'est pas jetable',
['gave_ammo'] = 'Vous avez donné x%s munitions à %s',
['no_ammo'] = 'Vous ne possédez pas de munitions',
['not_enough_ammo'] = 'Vous ne possédez pas autant de munitions',
['accessories_no_ears'] = 'Vous ne possédez pas d\'Accessoire d\'Oreilles',
['accessories_no_glasses'] = 'Vous ne possédez pas de Lunettes',
['accessories_no_helmet'] = 'Vous ne possédez pas de Casque/Chapeau',
['accessories_no_mask'] = 'Vous ne possédez pas de Masque',
['admin_noclipon'] = 'NoClip ~g~activé',
['admin_noclipoff'] = 'NoClip ~r~désactivé',
['admin_godmodeon'] = 'Mode invincible ~g~activé',
['admin_godmodeoff'] = 'Mode invincible ~r~désactivé',
['admin_ghoston'] = 'Mode fantôme ~g~activé',
['admin_ghostoff'] = 'Mode fantôme ~r~désactivé',
['admin_vehicleflip'] = 'Voiture retourné',
['admin_tpmarker'] = 'Téléporté sur le marqueur !',
['admin_nomarker'] = 'Pas de marqueur sur la carte !',
-- Main Menu
['mainmenu_subtitle'] = '~g~Adezou RôlePlay',
['mainmenu_gps_button'] = '📟 ~g~GPS',
['mainmenu_approach_button'] = '🚶 ~o~Démarche',
['mainmenu_voice_button'] = '🔊 ~b~Voix',
['gps'] = '📟 ~g~GPS: ~b~%s',
['approach'] = '🚶 ~o~Démarche: ~b~%s',
['voice'] = '🔊 ~b~Voix: ~b~%s',
-- Menu Voice Level
['voice_whisper'] = 'Chuchoter',
['voice_normal'] = 'Normal',
['voice_cry'] = 'Crier',
-- Inventory Menu
['inventory_title'] = '🎒 ~y~Inventaire',
['inventory_actions_subtitle'] = 'Inventaire: Action',
['inventory_use_button'] = 'Utiliser',
['inventory_give_button'] = 'Donner',
['inventory_drop_button'] = 'Jeter',
-- Loadout Menu
['loadout_title'] = '🔫 ~g~Gestion des Armes',
['loadout_actions_subtitle'] = 'Armes: Action',
['loadout_give_button'] = 'Donner',
['loadout_givemun_button'] = 'Donner Munitions',
['loadout_drop_button'] = 'Jeter',
-- Wallet Menu
['wallet_title'] = '👛 ~q~Portefeuille',
['wallet_option_give'] = 'Donner',
['wallet_option_drop'] = 'Jeter',
['wallet_job_button'] = '~b~Métier:~w~ %s - %s',
['wallet_job2_button'] = '~r~Organisation:~w~ %s - %s',
['wallet_money_button'] = '💵 Argent: ~g~$%s',
['wallet_bankmoney_button'] = '💳 Banque: ~b~$%s',
['wallet_blackmoney_button'] = '💸 Argent Sale: ~r~$%s',
['wallet_show_idcard_button'] = '📇 Montrer sa ~b~carte d\'identité',
['wallet_check_idcard_button'] = '📇 Regarder sa ~b~carte d\'identité',
['wallet_show_driver_button'] = '📇 Montrer son ~g~permis de conduire',
['wallet_check_driver_button'] = '📇 Regarder son ~g~permis de conduire',
['wallet_show_firearms_button'] = '📇 Montrer son ~r~permis port d\'armes',
['wallet_check_firearms_button'] = '📇 Regarder son ~r~permis port d\'armes',
-- Bills Menu
['bills_title'] = '📝 ~r~Factures',
-- Clothes Menu
['clothes_title'] = '🧥 ~b~Vêtements',
['clothes_top'] = '👔 Haut',
['clothes_pants'] = '👖 Bas',
['clothes_shoes'] = '🥾 Chaussures',
['clothes_bag'] = '🎒 Sac',
['clothes_bproof'] = '🦺 Gilet par Balle',
-- Accessories Menu
['accessories_title'] = '🧢 ~b~Accessoires',
['accessories_ears'] = '🦻 Accessoire d\'Oreilles',
['accessories_glasses'] = '😎 Lunettes',
['accessories_helmet'] = '🧢 Chapeau/Casque',
['accessories_mask'] = '🎭 Masque',
-- Animation Menu
['animation_title'] = '👋 ~y~Animations',
['animation_party_title'] = '🕺 Festives',
['animation_party_smoke'] = 'Fumer une cigarette',
['animation_party_playsong'] = 'Jouer de la musique',
['animation_party_dj'] = 'DJ',
['animation_party_dancing'] = 'Faire la Fête',
['animation_party_airguitar'] = 'Air Guitar',
['animation_party_shagging'] = 'Air Shagging',
['animation_party_rock'] = 'Rock\'n\'roll',
['animation_party_drunk'] = 'Bourré sur place',
['animation_party_vomit'] = 'Vomir en voiture',
['animation_salute_title'] = '👋 Salutations',
['animation_salute_saluate'] = 'Saluer',
['animation_salute_serrer'] = 'Serrer la main',
['animation_salute_tchek'] = 'Tchek',
['animation_salute_bandit'] = 'Salut bandit',
['animation_salute_military'] = 'Salut Militaire',
['animation_work_title'] = '🔨 Travail',
['animation_work_suspect'] = 'Se rendre',
['animation_work_fisherman'] = 'Pêcheur',
['animation_work_inspect'] = 'Police : enquêter',
['animation_work_radio'] = 'Police : parler à la radio',
['animation_work_circulation'] = 'Police : circulation',
['animation_work_binoculars'] = 'Police : jumelles',
['animation_work_harvest'] = 'Agriculture : récolter',
['animation_work_repair'] = 'Dépanneur : réparer le moteur',
['animation_work_observe'] = 'Médecin : observer',
['animation_work_talk'] = 'Taxi : parler au client',
['animation_work_bill'] = 'Taxi : donner la facture',
['animation_work_buy'] = 'Epicier : donner les courses',
['animation_work_shot'] = 'Barman : servir un shot',
['animation_work_picture'] = 'Journaliste : Prendre une photo',
['animation_work_notes'] = 'Tout : Prendre des notes',
['animation_work_hammer'] = 'Tout : Coup de marteau',
['animation_work_beg'] = 'SDF : Faire la manche',
['animation_work_statue'] = 'SDF : Faire la statue',
['animation_mood_title'] = '👼 Humeurs',
['animation_mood_felicitate'] = 'Féliciter',
['animation_mood_nice'] = 'Super',
['animation_mood_you'] = 'Toi',
['animation_mood_come'] = 'Viens',
['animation_mood_what'] = 'Keskya ?',
['animation_mood_me'] = 'A moi',
['animation_mood_seriously'] = 'Je le savais, putain',
['animation_mood_tired'] = 'Etre épuisé',
['animation_mood_shit'] = 'Je suis dans la merde',
['animation_mood_facepalm'] = 'Facepalm',
['animation_mood_calm'] = 'Calme-toi',
['animation_mood_why'] = 'Qu\'est ce que j\'ai fait ?',
['animation_mood_fear'] = 'Avoir peur',
['animation_mood_fight'] = 'Fight ?',
['animation_mood_notpossible'] = 'C\'est pas Possible !',
['animation_mood_embrace'] = 'Enlacer',
['animation_mood_fuckyou'] = 'Doigt d\'honneur',
['animation_mood_wanker'] = 'Branleur',
['animation_mood_suicide'] = 'Balle dans la tête',
['animation_sports_title'] = '🏋️ Sports',
['animation_sports_muscle'] = 'Montrer ses muscles',
['animation_sports_weightbar'] = 'Barre de musculation',
['animation_sports_pushup'] = 'Faire des pompes',
['animation_sports_abs'] = 'Faire des abdos',
['animation_sports_yoga'] = 'Faire du yoga',
['animation_other_title'] = '⚙️ Divers',
['animation_other_beer'] = 'Bière en Zik',
['animation_other_sit'] = 'S\'asseoir',
['animation_other_waitwall'] = 'Attendre contre un mur',
['animation_other_ontheback'] = 'Couché sur le dos',
['animation_other_stomach'] = 'Couché sur le ventre',
['animation_other_clean'] = 'Nettoyer',
['animation_other_cooking'] = 'Préparer à manger',
['animation_other_search'] = 'Position de Fouille',
['animation_other_selfie'] = 'Prendre un selfie',
['animation_other_door'] = 'Ecouter à une porte',
['animation_pegi_title'] = '💋 PEGI 21',
['animation_pegi_hsuck'] = 'Homme se faire suc** en voiture',
['animation_pegi_fsuck'] = 'Femme suc** en voiture',
['animation_pegi_hfuck'] = 'Homme bais** en voiture',
['animation_pegi_ffuck'] = 'Femme bais** en voiture',
['animation_pegi_scratch'] = 'Se gratter les couilles',
['animation_pegi_charm'] = 'Faire du charme',
['animation_pegi_golddigger'] = 'Pose michto',
['animation_pegi_breast'] = 'Montrer sa poitrine',
['animation_pegi_strip1'] = 'Strip Tease 1',
['animation_pegi_strip2'] = 'Strip Tease 2',
['animation_pegi_stripfloor'] = 'Strip Tease au sol',
-- Vehicle Menu
['vehicle_title'] = '🚙 ~g~Gestion Véhicule',
['vehicle_engine_button'] = 'Allumer/Eteindre le Moteur',
['vehicle_door_button'] = 'Ouvrir/Fermer Porte',
['vehicle_hood_button'] = 'Ouvrir/Fermer Capot',
['vehicle_trunk_button'] = 'Ouvrir/Fermer Coffre',
['vehicle_door_frontleft'] = 'Avant Gauche',
['vehicle_door_frontright'] = 'Avant Droite',
['vehicle_door_backleft'] = 'Arrière Gauche',
['vehicle_door_backright'] = 'Arrière Droite',
-- Boss Management Menu
['bossmanagement_title'] = '🏭 ~o~Gestion Entreprise: %s',
['bossmanagement_chest_button'] = 'Coffre Entreprise:',
['bossmanagement_hire_button'] = 'Recruter',
['bossmanagement_fire_button'] = 'Virer',
['bossmanagement_promote_button'] = 'Promouvoir',
['bossmanagement_demote_button'] = 'Destituer',
-- Boss Management 2 Menu
['bossmanagement2_title'] = '🏭 ~r~Gestion Entreprise: %s',
['bossmanagement2_chest_button'] = 'Coffre Entreprise:',
['bossmanagement2_hire_button'] = 'Recruter',
['bossmanagement2_fire_button'] = 'Virer',
['bossmanagement2_promote_button'] = 'Promouvoir',
['bossmanagement2_demote_button'] = 'Destituer',
-- Admin Menu
['admin_title'] = '👑 ~y~Administration',
['admin_goto_button'] = '~b~TP sur Joueur',
['admin_bring_button'] = '~b~TP Joueur sur moi',
['admin_tpxyz_button'] = '~b~TP sur Coordonées',
['admin_noclip_button'] = '~o~NoClip',
['admin_godmode_button'] = '~o~Mode Invincible',
['admin_ghostmode_button'] = '~o~Mode Fantôme',
['admin_spawnveh_button'] = '~g~Faire apparaître un Véhicule',
['admin_repairveh_button'] = '~g~Réparer Véhicule',
['admin_flipveh_button'] = '~g~Retourner le véhicule',
['admin_givemoney_button'] = '~r~S\'octroyer de l\'argent',
['admin_givebank_button'] = '~r~S\'octroyer de l\'argent (banque)',
['admin_givedirtymoney_button'] = '~r~S\'octroyer de l\'argent sale',
['admin_showxyz_button'] = '~q~Afficher/Cacher Coordonnées',
['admin_showname_button'] = '~q~Afficher/Cacher Noms des Joueurs',
['admin_tpmarker_button'] = '~b~TP sur le Marqueur',
['admin_revive_button'] = '~o~Réanimer un Joueur',
['admin_changeskin_button'] = '~p~Changer l\'Apparence',
['admin_saveskin_button'] = '~p~Sauvegarder l\'Apparence'
} |
local Skada = Skada
Skada:AddLoadableModule("Resurrects", function(L)
if Skada:IsDisabled("Resurrects") then return end
local mod = Skada:NewModule(L["Resurrects"])
local playermod = mod:NewModule(L["Resurrect spell list"])
local targetmod = mod:NewModule(L["Resurrect target list"])
local pairs, tostring, format = pairs, tostring, string.format
local GetSpellInfo = Skada.GetSpellInfo or GetSpellInfo
local _
local spellschools = {
[20484] = 0x08, -- Rebirth
[20608] = 0x08 -- Reincarnation
}
local function log_resurrect(set, data)
local player = Skada:GetPlayer(set, data.playerid, data.playername, data.playerflags)
if player then
player.ress = (player.ress or 0) + 1
set.ress = (set.ress or 0) + 1
-- saving this to total set may become a memory hog deluxe.
if (set == Skada.total and not Skada.db.profile.totalidc) or not data.spellid then return end
-- spell
local spell = player.resspells and player.resspells[data.spellid]
if not spell then
player.resspells = player.resspells or {}
player.resspells[data.spellid] = {count = 0}
spell = player.resspells[data.spellid]
end
spell.count = spell.count + 1
-- spell targets
if data.dstName then
spell.targets = spell.targets or {}
spell.targets[data.dstName] = (spell.targets[data.dstName] or 0) + 1
end
end
end
local data = {}
local function SpellResurrect(ts, event, srcGUID, srcName, srcFlags, dstGUID, dstName, dstFlags, spellid)
if not spellid then return end
data.spellid = spellid
data.playerid = srcGUID
data.playername = srcName
data.playerflags = srcFlags
data.dstGUID = dstGUID
data.dstName = dstName
data.dstFlags = dstFlags
Skada:DispatchSets(log_resurrect, data)
end
function playermod:Enter(win, id, label)
win.actorid, win.actorname = id, label
win.title = format(L["%s's resurrect spells"], label)
end
function playermod:Update(win, set)
win.title = format(L["%s's resurrect spells"], win.actorname or L["Unknown"])
if not set or not win.actorname then return end
local actor, enemy = set:GetActor(win.actorname, win.actorid)
if enemy then return end -- unuavailable for enemies yet
local total = actor and actor.ress or 0
if total > 0 and actor.resspells then
if win.metadata then
win.metadata.maxvalue = 0
end
local nr = 0
for spellid, spell in pairs(actor.resspells) do
nr = nr + 1
local d = win:nr(nr)
d.id = spellid
d.spellid = spellid
d.label, _, d.icon = GetSpellInfo(spellid)
d.spellschool = spellschools[spellid]
d.value = spell.count
d.valuetext = Skada:FormatValueCols(
mod.metadata.columns.Count and d.value,
mod.metadata.columns.sPercent and Skada:FormatPercent(d.value, total)
)
if win.metadata and d.value > win.metadata.maxvalue then
win.metadata.maxvalue = d.value
end
end
end
end
function targetmod:Enter(win, id, label)
win.actorid, win.actorname = id, label
win.title = format(L["%s's resurrect targets"], label)
end
function targetmod:Update(win, set)
win.title = format(L["%s's resurrect targets"], win.actorname or L["Unknown"])
if not set or not win.actorname then return end
local actor, enemy = set:GetActor(win.actorname, win.actorid)
if enemy then return end -- unavailable for enemies yet
local total = actor and actor.ress or 0
local targets = (total > 0) and actor:GetRessTargets()
if targets then
if win.metadata then
win.metadata.maxvalue = 0
end
local nr = 0
for targetname, target in pairs(targets) do
nr = nr + 1
local d = win:nr(nr)
d.id = target.id or targetname
d.label = targetname
d.text = target.id and Skada:FormatName(targetname, target.id)
d.class = target.class
d.role = target.role
d.spec = target.spec
d.value = target.count
d.valuetext = Skada:FormatValueCols(
mod.metadata.columns.Count and d.value,
mod.metadata.columns.sPercent and Skada:FormatPercent(d.value, total)
)
if win.metadata and d.value > win.metadata.maxvalue then
win.metadata.maxvalue = d.value
end
end
end
end
function mod:Update(win, set)
win.title = L["Resurrects"]
local total = set.ress or 0
if total > 0 then
if win.metadata then
win.metadata.maxvalue = 0
end
local nr = 0
for i = 1, #set.players do
local player = set.players[i]
if player and player.ress then
nr = nr + 1
local d = win:nr(nr)
d.id = player.id or player.name
d.label = player.name
d.text = player.id and Skada:FormatName(player.name, player.id)
d.class = player.class
d.role = player.role
d.spec = player.spec
d.value = player.ress
d.valuetext = Skada:FormatValueCols(
self.metadata.columns.Count and d.value,
self.metadata.columns.Percent and Skada:FormatPercent(d.value, total)
)
if win.metadata and d.value > win.metadata.maxvalue then
win.metadata.maxvalue = d.value
end
end
end
end
end
function mod:OnEnable()
self.metadata = {
valuesort = true,
click1 = playermod,
click2 = targetmod,
columns = {Count = true, Percent = false, sPercent = false},
icon = [[Interface\Icons\spell_holy_resurrection]]
}
-- no total click.
playermod.nototal = true
targetmod.nototal = true
Skada:RegisterForCL(
SpellResurrect,
"SPELL_RESURRECT",
{src_is_interesting = true, dst_is_interesting = true}
)
Skada:AddMode(self)
end
function mod:OnDisable()
Skada:RemoveMode(self)
end
function mod:AddToTooltip(set, tooltip)
if (set.ress or 0) > 0 then
tooltip:AddDoubleLine(L["Resurrects"], set.ress, 1, 1, 1)
end
end
function mod:GetSetSummary(set)
return tostring(set.ress or 0), set.ress or 0
end
do
local playerPrototype = Skada.playerPrototype
function playerPrototype:GetRessTargets(tbl)
if self.resspells then
tbl = wipe(tbl or Skada.cacheTable)
for _, spell in pairs(self.resspells) do
if spell.targets then
for name, count in pairs(spell.targets) do
if not tbl[name] then
tbl[name] = {count = count}
else
tbl[name].count = tbl[name].count + count
end
if not tbl[name].class then
local actor = self.super:GetActor(name)
if actor then
tbl[name].id = actor.id
tbl[name].class = actor.class
tbl[name].role = actor.role
tbl[name].spec = actor.spec
end
end
end
end
end
return tbl
end
end
end
end) |
-- handles loading in sprite sheet resources
-- the format of spritesheet data is actually Lua code that is executed in a sandbox
-- copyright 2016 Samuel Baird MIT Licence
local module = require('core.module')
local sandbox = require('util.sandbox')
local display_data = require('lt.display_data')
return module(function (resources)
local asset_suffix = ''
local loaded_sheets = {}
local images = {}
local clips = {}
local debug_output = function (...)
-- optionally display a list of all assets
-- print(...)
end
-- access loaded assets ------------------------------
function resources.get_image_data(name)
return images[name]
end
function resources.get_clip_data(name)
return clips[name]
end
-- asset loading -------------------------------------
function resources.set_asset_suffix(suffix)
asset_suffix = suffix
end
function resources.get_asset_suffix()
return asset_suffix
end
function resources.load_font(name, size)
end
function resources.load_spritesheet(basepath, name, prefix)
debug_output('load ' .. name .. asset_suffix .. '_description.ldata')
prefix = prefix or ''
-- record what we ended up loading
local loaded_sheet = {
name = name,
prefix = prefix,
textures = {},
images = {},
clips = {},
}
loaded_sheets[name] = loaded_sheet
-- sandboxed callback functions to handle parsing the description
local sandbox = sandbox({
prefix = prefix,
ipairs = ipairs,
sheet = function (filename, width, height, image_list)
debug_output(' sheet ' .. filename)
-- load the texture itself
local texture = love.graphics.newImage(basepath .. filename)
loaded_sheet.textures[filename] = texture
-- register all the sprites in the texture
for _, image in ipairs(image_list) do
debug_output(' image ' .. image.name)
-- the logical size of this sprite against the texture size
local width_scale = (image.xy[3] - image.xy[1]) / ((image.uv[3] - image.uv[1]) * texture:getWidth())
local height_scale = (image.xy[4] - image.xy[2]) / ((image.uv[4] - image.uv[2]) * texture:getHeight())
local quad = love.graphics.newQuad(
image.uv[1] * texture:getWidth() * width_scale, -- scaled offset
image.uv[2] * texture:getHeight() * height_scale, -- scaled offset
image.xy[3] - image.xy[1], image.xy[4] - image.xy[2], -- logical size
texture:getWidth() * width_scale, -- scaled texture size
texture:getHeight() * height_scale -- scaled texture size
)
-- create and cache the image data object
local image_data = display_data.image_data(image.name, texture, quad, image.xy)
loaded_sheet.images[image.name] = image_data
images[prefix .. image.name] = image_data
-- create a single frame clip version of each image (for convenience where clips may replace static images later)
local clip_data = display_data.clip_data(image.name)
local frame_data = clip_data:add_frame()
frame_data:add_image_content(nil, image_data)
loaded_sheet.clips[image.name] = clip_data
clips[prefix .. image.name] = clip_data
end
end,
clip = function (name, frames)
local clip_data = display_data.clip_data(name)
for frame_no, frame in ipairs(frames) do
local frame_data = clip_data:add_frame(frame.label)
for _, entry in ipairs(frame.content or {}) do
if entry.image then
assert(loaded_sheet.images[entry.image])
frame_data:add_image_content(
entry.instance,
loaded_sheet.images[entry.image],
unpack(entry.transform)
)
end
end
end
loaded_sheet.clips[name] = clip_data
clips[prefix .. name] = clip_data
end,
})
-- load the ldata file and execute it within the sandbox
local ldata = love.filesystem.read(basepath .. name .. asset_suffix .. '_description.ldata')
sandbox:execute_string(ldata)
-- once all clips are loaded link clip data directly to other image and clip_data
-- also record frame numbers for all ranges based on labels
for _, clip in pairs(loaded_sheet.clips) do
clip:link_resources(resources)
debug_output(' clip ' .. clip.name)
for _, frame in ipairs(clip.frames) do
if frame.label then
debug_output(' frame ' .. frame.label)
end
end
end
end
-- TODO: unload
end) |
return require(script.Parent.util:WaitForChild("compileSubmodules"))(script) |
local _M = {}
_M.BizhawkDir = "C:/desres/biz/"
_M.StateDir = _M.BizhawkDir .. "Lua/SNES/metroid-learning/state/"
_M.PoolDir = _M.BizhawkDir .. "Lua/SNES/metroid-learning/pool/"
--[[
At the moment the first in list will get loaded.
Rearrange for other savestates. (will be redone soon)
--]]
_M.State = {
"DP1.state", -- Donut Plains 1
"YI1.state", -- Yoshi's Island 1
"YI2.state", -- Yoshi's Island 2
}
_M.NeatConfig = {
--Filename = "DP1.state",
Filename = _M.PoolDir .. _M.State[1],
Population = 300,
DeltaDisjoint = 2.0,
DeltaWeights = 0.4,
DeltaThreshold = 1.0,
StaleSpecies = 15,
MutateConnectionsChance = 0.25,
PerturbChance = 0.90,
CrossoverChance = 0.75,
LinkMutationChance = 2.0,
NodeMutationChance = 0.50,
BiasMutationChance = 0.40,
StepSize = 0.1,
DisableMutationChance = 0.4,
EnableMutationChance = 0.2,
TimeoutConstant = 20,
MaxNodes = 1000000,
}
_M.ButtonNames = {
"A",
"B",
"X",
"Y",
"Up",
"Down",
"Left",
"Right",
"L",
"R",
"Select",
"Start"
}
_M.BoxRadius = 6
_M.InputSize = (_M.BoxRadius*2+1)*(_M.BoxRadius*2+1)
_M.Running = false
return _M |
require('bufferline').setup {
options = {
offsets = {{filetype = "NvimTree", text = "", padding = 1 }},
}
}
|
diamondShopRecordMoreInfo_titleName=[[兑换成功,奖品已发放]]
diamondShopRecordMoreInfo_Text1=[[确定]]
|
local key = KEYS[1];
local entry = ARGV[1];
local increment = tonumber(ARGV[2]) or 0;
local limit = tonumber(ARGV[3]) or 0;
local clientVersion = tonumber(ARGV[4]) or 0;
local existingVersion = tonumber(redis.call("HGET", key, "_version")) or 0;
-- Limited counter is not exact. Every client should use timestampt or incrementing value
-- as client ID. Whenever a new client is introduced, existing counter cache is wiped.
-- This should ensure that normally counters are limited but on a server failure when a client
-- restarts then old values to not collide with new ones.
if clientVersion > existingVersion then
redis.call("DEL", key);
redis.call("HSET", key, "_version", clientVersion);
end;
local current = tonumber(redis.call("HGET", key, entry)) or 0;
if increment == 0 then
return {1, current};
end;
if increment < 0 then
-- Remove entry
if current < 1 then
-- nothing to do here
return {1, 0};
end;
current = tonumber(redis.call("HINCRBY", key, entry, increment)) or 0;
return {1, current};
end;
-- Add entry
if current >= limit then
-- over capacity
return {0, current};
end;
current = tonumber(redis.call("HINCRBY", key, entry, increment)) or 0;
return {1, current};
|
---------------------------------------------------------------------------------------------------
-- Common module
---------------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.mobileHost = "127.0.0.1"
config.defaultProtocolVersion = 2
config.application1.registerAppInterfaceParams.syncMsgVersion.majorVersion = 5
--[[ Required Shared libraries ]]
local actions = require("user_modules/sequences/actions")
local hmi_values = require('user_modules/hmi_values')
local commonPreconditions = require('user_modules/shared_testcases/commonPreconditions')
local utils = require ('user_modules/utils')
--[[ Module ]]
local m = actions
m.type = "FILE"
local preconditionsOrig = m.preconditions
--[[ @preconditions: Expand initial precondition with removing storage folder
--! @parameters: none
--! return: none
--]]
function m.preconditions()
preconditionsOrig()
local storage = commonPreconditions:GetPathToSDL() .. "storage/*"
assert(os.execute("rm -rf " .. storage))
end
local startOrigin = m.start
function m.start()
local params = hmi_values.getDefaultHMITable()
table.insert(params.TTS.GetCapabilities.params.speechCapabilities, m.type)
startOrigin(params)
end
function m.putFile(params, pAppId, self)
if not pAppId then pAppId = 1 end
local mobileSession = m.getMobileSession(pAppId, self);
local cid = mobileSession:SendRPC("PutFile", params.requestParams, params.filePath)
mobileSession:ExpectResponse(cid, { success = true, resultCode = "SUCCESS"})
end
function m.getPathToFileInStorage(fileName)
return commonPreconditions:GetPathToSDL() .. "storage/"
.. m.getMobileAppId() .. "_"
.. m.getDeviceMAC() .. "/" .. fileName
end
m.getDeviceName = utils.getDeviceName
m.getDeviceMAC = utils.getDeviceMAC
function m.getMobileAppId(pAppId)
if not pAppId then pAppId = 1 end
return config["application" .. pAppId].registerAppInterfaceParams.fullAppID
end
return m
|
fx_version 'adamant'
games { 'gta5' }
description 'NPC-Garages'
version '1.0.0'
--resource_manifest_version '05cfa83c-a124-4cfa-a768-c24a5811d8f9'
client_script "@npc-scripts/client/errorlog.lua"
client_script "@npc-infinity/client/cl_lib.lua"
server_script "@npc-infinity/server/sv_lib.lua"
server_scripts {
'server/server.lua',
'server/s_chopshop.lua'
}
client_script {
'client/client.lua',
'client/illegal_parts.lua',
'client/chopshop.lua',
'client/gui.lua'
} |
function PIS:SetSettings(ply, tbl)
ply.pingsSettings = tbl
end
function PIS:SetSetting(ply, setting, value, ignoreSave)
ply.pingsSettings[setting] = value
if (ignoreSave) then return end
PIS:SaveSettings(ply)
end
function PIS:GetSettings(ply)
if (!ply.pingsSettings) then
ply.pingsSettings = PIS.Config.DefaultSettings
end
return ply.pingsSettings
end
PING_STATUS_DEFAULT = 0
PING_STATUS_CONFIRMED = 1
PING_STATUS_REJECTED = 2
PING_COMMAND_CONFIRM = 0
function PIS:GetKeyName(key)
if (!isnumber(key)) then return "UNKNOWN KEY" end
if (key >= MOUSE_MIDDLE) then
if (key == MOUSE_MIDDLE) then
return "MIDDLE MOUSE"
elseif (key == MOUSE_4) then
return "MOUSE 4"
elseif (key == MOUSE_5) then
return "MOUSE 5"
elseif (key == MOUSE_WHEEL_UP) then
return "MOUSE WHEEL UP"
elseif (key == MOUSE_WHEEL_DOWN) then
return "MOUSE WHEEL DOWN"
else
return "UNKNOWN MOUSE"
end
else
return input.GetKeyName(key) and input.GetKeyName(key):upper() or "UNKNOWN KEY"
end
end
PIS.PingCache = {}
function PIS:GetPingIcon(mat)
if not PIS.PingCache[mat] then
PIS.PingCache[mat] = Material("inflexible/"..mat..".png","smooth")
end
return PIS.PingCache[mat]
end
|
--***********************************************************
--** ROBERT JOHNSON **
--***********************************************************
require "TimedActions/ISBaseTimedAction"
---@class ISDisinfect : ISBaseTimedAction
ISDisinfect = ISBaseTimedAction:derive("ISDisinfect");
function ISDisinfect:isValid()
if ISHealthPanel.DidPatientMove(self.character, self.otherPlayer, self.bandagedPlayerX, self.bandagedPlayerY) then
return false
end
return self.character:getInventory():contains(self.alcohol)
end
function ISDisinfect:waitToStart()
if self.character == self.otherPlayer then
return false
end
self.character:faceThisObject(self.otherPlayer)
return self.character:shouldBeTurning()
end
function ISDisinfect:update()
if self.character ~= self.otherPlayer then
self.character:faceThisObject(self.otherPlayer)
end
local jobType = getText("ContextMenu_Disinfect")
ISHealthPanel.setBodyPartActionForPlayer(self.otherPlayer, self.bodyPart, self, jobType, { disinfect = true })
self.character:setMetabolicTarget(Metabolics.LightDomestic);
end
function ISDisinfect:start()
if self.character == self.otherPlayer then
self:setActionAnim(CharacterActionAnims.Bandage);
self:setAnimVariable("BandageType", ISHealthPanel.getBandageType(self.bodyPart));
self.character:reportEvent("EventBandage");
else
self:setActionAnim("Loot")
self.character:SetVariable("LootPosition", "Mid")
self.character:reportEvent("EventLootItem");
end
self:setOverrideHandModels(nil, nil);
end
function ISDisinfect:stop()
ISHealthPanel.setBodyPartActionForPlayer(self.otherPlayer, self.bodyPart, nil, nil, nil)
ISBaseTimedAction.stop(self);
end
function ISDisinfect:perform()
-- needed to remove from queue / start next.
ISBaseTimedAction.perform(self);
self.bodyPart:setAlcoholLevel(self.bodyPart:getAlcoholLevel() + self.alcohol:getAlcoholPower());
local addPain = (self.alcohol:getAlcoholPower() * 13) - (self.doctorLevel / 2)
if self.doctor:getAccessLevel() ~= "None" then
self.bodyPart:setAdditionalPain(self.bodyPart:getAdditionalPain() + addPain);
end
if(instanceof(self.alcohol, "Food")) then
self.alcohol:setThirstChange(self.alcohol:getThirstChange() + 0.1);
if(self.alcohol:getBaseHunger() < 0) then
self.alcohol:setHungChange(self.alcohol:getHungChange() + 0.1);
end
if self.alcohol:getThirstChange() > -0.01 or self.alcohol:getHungerChange() > -0.01 then
self.alcohol:Use();
end
elseif (instanceof(self.alcohol, "DrainableComboItem")) then
self.alcohol:Use();
end
if isClient() then
sendDisinfect(self.otherPlayer:getOnlineID(), self.bodyPart:getIndex(), self.alcohol:getAlcoholPower());
if self.doctor:getAccessLevel() ~= "None" then
sendAdditionalPain(self.otherPlayer:getOnlineID(), self.bodyPart:getIndex(), addPain);
end
end
ISHealthPanel.setBodyPartActionForPlayer(self.otherPlayer, self.bodyPart, nil, nil, nil)
end
function ISDisinfect:new(doctor, otherPlayer, alcohol, bodyPart)
local o = {}
setmetatable(o, self)
self.__index = self;
o.character = doctor;
o.doctor = doctor;
o.otherPlayer = otherPlayer;
o.doctorLevel = doctor:getPerkLevel(Perks.Doctor);
o.alcohol = alcohol;
o.bodyPart = bodyPart;
o.stopOnWalk = bodyPart:getIndex() > BodyPartType.ToIndex(BodyPartType.Groin);
o.stopOnRun = true;
o.bandagedPlayerX = otherPlayer:getX();
o.bandagedPlayerY = otherPlayer:getY();
o.maxTime = 120 - (o.doctorLevel * 4);
if doctor:isTimedActionInstant() then
o.maxTime = 1;
end
if doctor:getAccessLevel() ~= "None" then
o.doctorLevel = 10;
end
return o;
end
|
-- Draws a 160×100 PNG image.
--
-- Requires a T3 display setup and the libPNGimage library, which you can
-- install using the following command:
--
-- hpm install libpngimage
local path = require("shell").resolve((...))
local png = require("libPNGimage")
local wbuffer = require("wonderful.buffer")
local fb = wbuffer.Framebuffer {w = 160, h = 50, depth = 8, debug = false}
fb:optimize()
local img = png.newFromFile(path)
print("Setting...")
os.sleep(0)
for y = 1, 50, 1 do
for x = 1, 160, 1 do
local ru, gu, bu = img:getPixel(x - 1, 2 * y - 2)
local rb, gb, bb = img:getPixel(x - 1, 2 * y - 1)
fb:set(x, y,
(ru * 0x10000 +
gu * 0x100 +
bu),
(rb * 0x10000 +
gb * 0x100 +
bb), 1, "▀")
end
os.sleep(0)
end
print("Rendering...")
os.sleep(0)
fb:flush(1, 1, require("component").gpu)
require("event").pull("interrupted")
|
--[[
Test `test4` on `dconv` tool, a model-based, semantic complete
datatype automatic generation.
Test created using (Lua) Busted Framework.
This test does sanity checks for the basic output of the tool.
Testing DDBLX and convert_ddblx --> DYNAMIC CONVERSION
Using ROS2/rclc
Main Author: Enea Scioni, <[email protected]>
2018, KU Leuven, Belgium
--]]
require 'busted.runner'()
-- Load Models subject to test
dprotofile = 'busted/test4/dproto/ros-example.dproto'
--[[ Load all necessary stuff --]]
dconv = require('dproto-conv-gen')
ddr_models = {ros2=true}
dconv.init_runtime(dprotofile,ddr_models)
-- Aliases
DDBLX = dconv.DDBLX
describe('creating DDBLX', function()
it('plain c99 test',function()
assert.has.no_errors(function()
p = DDBLX('plain_position')
o = DDBLX('plain_rotation')
pose = DDBLX('plain_pose')
p.x = 1
p.y = 2
p.z = 3
o[{0,0}] = 1.0; o[{1,1}] = 1.0; o[{2,2}] = 1.0
pose.position.x = 111
pose.position.y = 222
pose.position.z = 66.6
end)
assert.equal(1,p.x)
assert.equal(2,p.y)
assert.equal(3,p.z)
assert.equal(1,o(0,0))
assert.equal(1,o(1,1))
assert.equal(1,o(2,2))
assert.equal(111,pose.position.x)
assert.equal(222,pose.position.y)
assert.equal(66.6,pose.position.z)
end)
it('ROS2/rclc test', function()
assert.has.no_error(function()
p = DDBLX('ros_position')
o = DDBLX('ros_quaternion')
pose = DDBLX('ros_pose')
p[0] = 24
p[1] = -24
p[2] = 5
end)
assert.equal(24,p[0])
assert.equal(-24,p[1])
assert.equal(5,p[2])
end)
end)
describe('conversions tests', function()
it('conversion plain_position->ros_position',function()
assert.has.no_error(function()
pp = DDBLX('plain_position')
rp = DDBLX('ros_position')
pp.x = 1
pp.y = 2
pp.z = 3
dconv.convert(pp,rp)
end)
assert.equal(1,rp[0])
assert.equal(2,rp[1])
assert.equal(3,rp[2])
end)
it('conversion ros_quaternion->plain_rotation (uses conversion)',function()
assert.has.no_error(function()
op = DDBLX('plain_rotation')
ro = DDBLX('ros_quaternion')
ro.w = 1.0
dconv.convert(ro,op)
end)
assert.equal(1.0,op(0,0))
assert.equal(1.0,op(1,1))
assert.equal(1.0,op(2,2))
assert.equal(0.0,op(2,0))
assert.equal(0.0,op(0,1))
assert.equal(0.0,op(2,1))
end)
it('conversion ros_pose->plain_pose (uses conversion)',function()
assert.has.no_error(function()
ppose = DDBLX('plain_pose')
rpose = DDBLX('ros_pose')
rpose.position.x = 111
rpose.position.z = 666
rpose.orientation.w = 1
dconv.convert(rpose,ppose)
end)
assert.equal(111,ppose.position.x)
assert.equal(0,ppose.position.y)
assert.equal(666,ppose.position.z)
assert.equal(1.0,ppose.orientation(0,0))
assert.equal(1.0,ppose.orientation(1,1))
assert.equal(1.0,ppose.orientation(2,2))
assert.equal(0.0,ppose.orientation(2,0))
assert.equal(0.0,ppose.orientation(0,1))
assert.equal(0.0,ppose.orientation(2,1))
end)
end) |
local zigzag = {}
function zigzag.encode(int)
if int < 0 then
return ~(int << 1)
else
return int << 1
end
end
function zigzag.decode(uint)
if uint & 1 == 1 then
return ~(uint >> 1)
else
return uint >> 1
end
end
return zigzag |
inspect = require("inspect")
-- Creates 50x versions of each recipe from selected categories
require("scripts.recipeSetup")
-- Create the item groups for these new recipes
require("scripts.itemGroupSetup")
-- Adds big items to list of productivity module usable items
require("scripts.productivityFix")
-- Creates dummy items with recipe icons so tag images can match recip icons (normally only item icons are available)
require("scripts.tagIcons")
-- Big Loader prototype and item definition (moved to data-final to capture visual updates on default loader some mods implement)
local create_bigloader = require("prototypes.bigloader")
create_bigloader("wsf-factory-loader")
-- Update Loader speed to fastest available loaders or belts in current mod set
require("scripts.updateLoaderSpeed") |
local _ = _ or function(k, ...) return ImportPackage("i18n").t(GetPackageName(), k, ...) end
-------------------------------------------------------
----------- CONFIG FILE FOR KEYS SHORTCUTS ------------
-------------------------------------------------------
INTERACT_KEY = "E" -- To interact with something
PHONE_OPEN_KEY = "K" -- To open the phone
PHONE_CLOSE_KEY = "Escape" -- To close the phone
HOUSING_MENU_KEY = "F1" -- To show the housing menu
ID_CARD_MENU_KEY = "F5" -- To show the ID CARD menu
JOB_MENU_KEY = "F3" -- To show the job menu
INVENTORY_KEY = "F4" -- To show the inventory
SHORTCUT_VIEWER_KEY = "F10" -- To display the shortcuts
ANIMATION_MENU_KEY = "G" -- To open the animation wheel
MAP_OPEN_KEY = "M" -- To open the big map
MAP_ZOOMIN_KEY = "Page Up" -- To zoom in the map
MAP_ZOOMOUT_KEY = "Page Down" -- To zoom out in the map
FPS_KEY = "V" -- To toggle FPS mode
VEHICLE_LOCK_KEY = "U" -- To lock the vehicle
VEHICLE_MENU_KEY = "F2" -- To open the vehicle menu
VEHICLE_ENGINE_KEY = "X" -- To toggle vehicle engine
VEHICLE_TRUNK_KEY = "O" -- To open the vehicle trunk
VEHICLE_HOOD_KEY = "I" -- To open the vehicle hood
ADMIN_MENU_KEY = "F9" -- To show the admin menu
function GetAllKeybinds()
return {
{label = _("INTERACT_KEY"), key = INTERACT_KEY},
{label = _("PHONE_OPEN_KEY"), key = PHONE_OPEN_KEY},
{label = _("PHONE_CLOSE_KEY"), key = PHONE_CLOSE_KEY},
{label = _("HOUSING_MENU_KEY"), key = HOUSING_MENU_KEY},
{label = _("ID_CARD_MENU_KEY"), key = ID_CARD_MENU_KEY},
{label = _("JOB_MENU_KEY"), key = JOB_MENU_KEY},
{label = _("INVENTORY_KEY"), key = INVENTORY_KEY},
{label = _("SHORTCUT_VIEWER_KEY"), key = SHORTCUT_VIEWER_KEY},
{label = _("ANIMATION_MENU_KEY"), key = ANIMATION_MENU_KEY},
{label = _("MAP_OPEN_KEY"), key = MAP_OPEN_KEY},
{label = _("MAP_ZOOMIN_KEY"), key = MAP_ZOOMIN_KEY},
{label = _("MAP_ZOOMOUT_KEY"), key = MAP_ZOOMOUT_KEY},
{label = _("FPS_KEY"), key = FPS_KEY},
{label = _("VEHICLE_LOCK_KEY"), key = VEHICLE_LOCK_KEY},
{label = _("VEHICLE_MENU_KEY"), key = VEHICLE_MENU_KEY},
{label = _("VEHICLE_ENGINE_KEY"), key = VEHICLE_ENGINE_KEY},
{label = _("VEHICLE_TRUNK_KEY"), key = VEHICLE_TRUNK_KEY},
{label = _("VEHICLE_HOOD_KEY"), key = VEHICLE_HOOD_KEY},
{label = _("ADMIN_MENU_KEY"), key = ADMIN_MENU_KEY},
}
end
|
vim.g.operator_sandwich_no_default_key_mappings = 1
vim.g.sandwich_no_default_key_mappings = 1
|
--[[
Variables
]]
local ActiveParticles = {}
local BlacklistedParticles = {}
--[[
Functions
]]
function LoadParticleDictionary(dictionary)
if not HasNamedPtfxAssetLoaded(dictionary) then
RequestNamedPtfxAsset(dictionary)
while not HasNamedPtfxAssetLoaded(dictionary) do
Citizen.Wait(0)
end
end
end
function StartParticleAtCoord(ptDict, ptName, looped, coords, rot, scale, alpha, color, duration)
LoadParticleDictionary(ptDict)
UseParticleFxAssetNextCall(ptDict)
SetPtfxAssetNextCall(ptDict)
local particleHandle
if looped then
particleHandle = StartParticleFxLoopedAtCoord(ptName, coords.x, coords.y, coords.z, rot.x, rot.y, rot.z, scale or 1.0)
if color then
SetParticleFxLoopedColour(particleHandle, color.r, color.g, color.b, false)
end
SetParticleFxLoopedAlpha(particleHandle, alpha or 10.0)
if duration then
Citizen.Wait(duration)
StopParticleFxLooped(particleHandle, 0)
end
else
SetParticleFxNonLoopedAlpha(alpha or 10.0)
if color then
SetParticleFxNonLoopedColour(color.r, color.g, color.b)
end
StartParticleFxNonLoopedAtCoord(ptName, coords.x, coords.y, coords.z, rot.x, rot.y, rot.z, scale or 1.0)
end
return particleHandle
end
function StartParticleOnEntity(ptDict, ptName, looped, entity, bone, offset, rot, scale, alpha, color, evolution, duration)
LoadParticleDictionary(ptDict)
UseParticleFxAssetNextCall(ptDict)
local particleHandle, boneID
if bone and GetEntityType(entity) == 1 then
boneID = GetPedBoneIndex(entity, bone)
elseif bone then
boneID = GetEntityBoneIndexByName(entity, bone)
end
if looped then
if bone then
particleHandle = StartParticleFxLoopedOnEntityBone(ptName, entity, offset.x, offset.y, offset.z, rot.x, rot.y, rot.z, boneID, scale)
else
particleHandle = StartParticleFxLoopedOnEntity(ptName, entity, offset.x, offset.y, offset.z, rot.x, rot.y, rot.z, scale)
end
if evolution then
SetParticleFxLoopedEvolution(particleHandle, evolution.name, evolution.amount, false)
end
if color then
SetParticleFxLoopedColour(particleHandle, color.r, color.g, color.b, false)
end
SetParticleFxLoopedAlpha(particleHandle, alpha)
if duration then
Citizen.Wait(duration)
StopParticleFxLooped(particleHandle, 0)
end
else
SetParticleFxNonLoopedAlpha(alpha or 10.0)
if color then
SetParticleFxNonLoopedColour(color.r, color.g, color.b)
end
if bone then
StartParticleFxNonLoopedOnPedBone(ptName, entity, offset.x, offset.y, offset.z, rot.x, rot.y, rot.z, boneID, scale)
else
StartParticleFxNonLoopedOnEntity(ptName, entity, offset.x, offset.y, offset.z, rot.x, rot.y, rot.z, scale)
end
end
return particleHandle
end
function AddBlacklistedParticle(pDict, pName)
BlacklistedParticles[('%s@%s'):format(pDict, pName)] = true
end
function RemoveBlacklistedParticle(pDict, pName)
BlacklistedParticles[('%s@%s'):format(pDict, pName)] = nil
end
function IsParticleBlacklisted(pDict, pName)
return BlacklistedParticles[('%s@%s'):format(pDict, pName)]
end
--[[
Exports
]]
exports("StartParticleAtCoord", StartParticleAtCoord)
exports("StartParticleOnEntity", StartParticleOnEntity)
exports("AddBlacklistedParticle", AddBlacklistedParticle)
exports("RemoveBlacklistedParticle", RemoveBlacklistedParticle)
exports("IsParticleBlacklisted", IsParticleBlacklisted)
--[[
Events
]]
RegisterNetEvent("particle:sync:coord")
AddEventHandler("particle:sync:coord", function(ptDict, ptName, looped, position, duration, ptID)
if type(position.coords) == "table" then
local particles = {}
if IsParticleBlacklisted(ptDict, ptName) then return end
for _, coords in ipairs(position.coords) do
local particle = promise:new()
Citizen.CreateThread(function()
local particleHandle = StartParticleAtCoord(ptDict, ptName, looped, coords, position.rot, position.scale, position.alpha, position.color, duration)
particle:resolve(particleHandle)
end)
particles[#particles + 1] = particle
end
if not duration and ptID then
ActiveParticles[ptID] = particles
end
else
local particleHandle = StartParticleAtCoord(ptDict, ptName, looped, position.coords, position.rot, position.scale, position.alpha, position.color, duration)
if not duration and ptID then
ActiveParticles[ptID] = particleHandle
end
end
end)
RegisterNetEvent("particle:sync:entity")
AddEventHandler("particle:sync:entity", function(ptDict, ptName, looped, target, bone, position, duration, ptID)
local entity = NetworkGetEntityFromNetworkId(target)
if IsParticleBlacklisted(ptDict, ptName) then return end
if type(bone) == "table" then
local particles = {}
for _, boneName in ipairs(bone) do
local particle = promise:new()
Citizen.CreateThread(function()
local particleHandle = StartParticleOnEntity(ptDict, ptName, looped, entity, boneName, position.offset, position.rot, position.scale, position.alpha, position.color, position.evolution, duration)
particle:resolve(particleHandle)
end)
particles[#particles + 1] = particle
end
if not duration and ptID then
ActiveParticles[ptID] = particles
end
else
local particleHandle = StartParticleOnEntity(ptDict, ptName, looped, entity, bone, position.offset, position.rot, position.scale, position.alpha, position.color, position.evolution, duration)
if not duration and ptID then
ActiveParticles[ptID] = particleHandle
end
end
end)
RegisterNetEvent("particle:sync:player")
AddEventHandler("particle:sync:player", function(ptDict, ptName, looped, target, bone, position, duration, ptID)
local entity = GetPlayerPed(GetPlayerFromServerId(target))
if IsParticleBlacklisted(ptDict, ptName) then return end
if type(bone) == "table" then
local particles = {}
for _, boneName in ipairs(bone) do
local particle = promise:new()
Citizen.CreateThread(function()
local particleHandle = StartParticleOnEntity(ptDict, ptName, looped, entity, boneName, position.offset, position.rot, position.scale, position.alpha, position.color, position.evolution, duration)
particle:resolve(particleHandle)
end)
particles[#particles + 1] = particle
end
if not duration and ptID then
ActiveParticles[ptID] = particles
end
else
local particleHandle = StartParticleOnEntity(ptDict, ptName, looped, entity, bone, position.offset, position.rot, position.scale, position.alpha, position.color, position.evolution, duration)
if not duration and ptID then
ActiveParticles[ptID] = particleHandle
end
end
end)
RegisterNetEvent("particle:sync:toggle:stop")
AddEventHandler("particle:sync:toggle:stop", function(ptID)
if ActiveParticles[ptID] then
if type(ActiveParticles[ptID]) == "table" then
for _, particleHandle in ipairs(ActiveParticles[ptID]) do
StopParticleFxLooped(Citizen.Await(particleHandle), 0)
end
else
StopParticleFxLooped(ActiveParticles[ptID], 0)
end
ActiveParticles[ptID] = nil
end
end)
RegisterNetEvent("particle:explosion:coord")
AddEventHandler("particle:explosion:coord", function(position, expType)
AddExplosion(position, expType or 29, 5.0, 1, 0, 1, 1)
Wait(500)
StopFireInRange(position, 5.0)
end)
--[[
Threads
]]
Citizen.CreateThread(function()
TriggerServerEvent("particles:player:ready")
end) |
-- Revert Artisanal Reskins recipe icons
if mods['reskins-angels'] then
local slag_processing_list = {
'slag-processing-1',
'slag-processing-2',
'slag-processing-3',
'slag-processing-4',
'slag-processing-5',
'slag-processing-6'
}
for _,name in pairs(slag_processing_list) do
seablock.reskins.clear_icon_specification(name, 'recipe')
end
end
-- Remove I overlay from recipes
seablock.reskins.clear_icon_specification('explosives', 'recipe')
seablock.reskins.clear_icon_specification('liquid-rubber-1', 'recipe')
seablock.reskins.clear_icon_specification('solid-rubber', 'recipe')
|
AddCSLuaFile()
ENT.Base = "arccw_ammo"
ENT.RenderGroup = RENDERGROUP_TRANSLUCENT
ENT.PrintName = "Magnum Ammo (Large)"
ENT.Category = "ArcCW - Ammo"
ENT.Spawnable = true
ENT.Model = "models/items/arccw/magnum_ammo_closed.mdl"
ENT.AmmoType = "357"
ENT.AmmoCount = 60
ENT.Scale = 1.5
ENT.DetonationDamage = 50
ENT.DetonationRadius = 128
ENT.DetonationSound = "weapons/357_fire2.wav" |
--サイバネット・リカバー
--Cynet Recover
--Scripted by Eerie Code
function c100318021.initial_effect(c)
--activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--special summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(100318021,0))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e2:SetCode(EVENT_DESTROYED)
e2:SetRange(LOCATION_SZONE)
e2:SetCountLimit(1,100318021)
e2:SetCondition(c100318021.spcon)
e2:SetTarget(c100318021.sptg)
e2:SetOperation(c100318021.spop)
c:RegisterEffect(e2)
end
function c100318021.cfilter(c,tp)
return c:GetPreviousControler()==tp and c:IsPreviousLocation(LOCATION_MZONE)
and c:IsPreviousPosition(POS_FACEUP) and bit.band(c:GetPreviousTypeOnField(),TYPE_LINK)~=0
and (c:IsReason(REASON_BATTLE) or c:IsReason(REASON_EFFECT) and c:GetReasonPlayer()~=tp)
end
function c100318021.spcon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c100318021.cfilter,1,nil,tp)
end
function c100318021.filter(c,e,tp)
return not c:IsType(TYPE_LINK) and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEUP_DEFENSE)
end
function c100318021.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c100318021.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c100318021.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c100318021.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c100318021.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP_DEFENSE)
end
end
|
local DebugLogger = require "lil.DebugLogger"
local ThreadUtils = require("lil.ThreadUtils")
local PATTERN_GENERATOR_MAP =
{
["%{iso8601}d"] = function()
DebugLogger.log("building ISO 8601 format date for pattern")
local utcDateTime = os.date("!*t")
return string.format("%04d-%02d-%02dT%02d:%02d:%02dZ",
utcDateTime.year, utcDateTime.month, utcDateTime.day,
utcDateTime.hour, utcDateTime.min, utcDateTime.sec)
end,
["%d"] = function()
DebugLogger.log("building default locale format date for pattern")
return os.date("%c")
end,
["%t"] = function()
return ThreadUtils.getCurrentThreadId()
end,
["%l"] = function(level)
return ("%-5s"):format(string.upper(level))
end,
["%n"] = function(_, loggerName, creator)
return loggerName or creator
end
}
return PATTERN_GENERATOR_MAP
|
local class = require('middleclass')
local Controller = require('mvc.Controller')
local HasSignals = require('HasSignals')
local cjson = require('cjson')
local SoundMng = require('app.helpers.SoundMng')
local CreateRoomDKController = class("CreateRoomDKController", Controller):include(HasSignals)
local tools = require('app.helpers.tools')
function CreateRoomDKController:initialize(groupInfo, createmode,paymode)
Controller.initialize(self)
HasSignals.initialize(self)
self.groupInfo = groupInfo
self.createmode = createmode
self.paymode = 1
if paymode then
self.paymode = paymode.payMode
end
end
function CreateRoomDKController:viewDidLoad()
local app = require("app.App"):instance()
self.view:layout(self.groupInfo, self.createmode,self.paymode)
self.listener = {
app.session.room:on('createRoom', function(msg)
if msg.errorCode then
self:delShowWaiting()
end
if msg.enterOnCreate and msg.enterOnCreate == 1 then
-- self:clickBack()
self:delShowWaiting()
end
end),
app.session.room:on('Group_setRoomConfigResult', function(msg)
self:clickBack()
end),
app.session.room:on('roomConfigFlag', function(msg)
self.view:freshHasSave(msg.data)
end),
app.session.room:on('closeDK', function(msg)
self.emitter:emit('back')
end),
app.session.room:on('showOther', function(msg)
if msg == 'dk' then
self.view:setVisible(true)
self.view:freshTab('dk')
else
self.view:setVisible(false)
end
end),
}
if self.groupInfo then
app.session.room:roomConfigFlag(self.groupInfo)
end
end
function CreateRoomDKController:finalize()-- luacheck: ignore
for i = 1, #self.listener do
self.listener[i]:dispose()
end
end
function CreateRoomDKController:clickCreate()
local app = require("app.App"):instance()
local options = self.view:getOptions()
if options.scoreOption.choushui_dk < 0 or options.scoreOption.choushui_dk >= 100 then
tools.showRemind("请调整抽水比例")
return
end
if not options.scoreOption.join or not options.scoreOption.tui or not options.scoreOption.qiang then
tools.showRemind("抽水设置不能为空")
return
end
local gameIdx = app.session.depu.gameIdx
self.view:showWaiting()
app.session.room:createRoom(gameIdx, options, self.groupInfo)
end
function CreateRoomDKController:clickQuickStart()
local app = require("app.App"):instance()
local options = self.view:getOptions()
if options.scoreOption.choushui_dk < 0 or options.scoreOption.choushui_dk >= 100 then
tools.showRemind("请调整抽水比例")
return
end
if not options.scoreOption.join or not options.scoreOption.tui or not options.scoreOption.qiang then
tools.showRemind("抽水设置不能为空")
return
end
local gameIdx = app.session.depu.gameIdx
local gameplay = options.gameplay
self.view:showWaiting()
app.session.room:quickStart(self.groupInfo, gameplay, gameIdx)
end
function CreateRoomDKController:clickSureBtn()
local app = require("app.App"):instance()
local options = self.view:getOptions()
if options.scoreOption.choushui_dk < 0 or options.scoreOption.choushui_dk >= 100 then
tools.showRemind("请调整抽水比例")
return
end
if not options.scoreOption.join or not options.scoreOption.tui or not options.scoreOption.qiang then
tools.showRemind("抽水设置不能为空")
return
end
local gameIdx = app.session.depu.gameIdx
local gameplay = options.gameplay
app.session.room:roomConfig(gameplay, options, self.groupInfo)
end
function CreateRoomDKController:clickBack()
local app = require("app.App"):instance()
app.session.room:closeAll()
self.emitter:emit('back')
end
------------------------------------------------------------------------------------------
--三个问号提示的点击事件
function CreateRoomDKController:clickRoomPriceLayer()
self.view:freshPriceLayer(false)
end
function CreateRoomDKController:clickPriceWhy()
self.view:freshPriceLayer(true)
end
function CreateRoomDKController:clickquickLayer()
self.view:freshquickLayer(false)
end
function CreateRoomDKController:clickquickWhy()
self.view:freshquickLayer(true)
end
function CreateRoomDKController:clickChoushuiLayer(sender)
local data = sender:getComponent("ComExtensionData"):getCustomProperty()
local body = cjson.decode(data)
self.view:freshChoushuiLayer(false,body)
end
function CreateRoomDKController:clickChoushuiSelect(sender)
local data = sender:getComponent("ComExtensionData"):getCustomProperty()
local body = cjson.decode(data)
self.view:freshChoushuiLayer(true,body)
end
--------------------------------------------------------------------------------------------
function CreateRoomDKController:clickNotOpen()
local tools = require('app.helpers.tools')
tools.showRemind('暂未开放,敬请期待')
end
--------------------------------------------------------------------------------------------
--左边选择模式点击事件
function CreateRoomDKController:clickChangeGameType(sender)
SoundMng.playEft('btn_click.mp3')
local data = sender:getComponent("ComExtensionData"):getCustomProperty()
local app = require("app.App"):instance()
if data == 'dk' then
app.session.room:setCurrentType('dk')
self.view:freshTab('dk')
else
self.view:setVisible(false)
app.session.room:showOther(data)
end
end
function CreateRoomDKController:clickchangetype(sender)
SoundMng.playEft('btn_click.mp3')
local data = 'dk'
local app = require("app.App"):instance()
self.view:freshTab(data)
end
--------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------
--各模式的刷新事件
function CreateRoomDKController:clickBase(sender)
SoundMng.playEft('btn_click.mp3')
local data = sender:getComponent("ComExtensionData"):getCustomProperty()
self.view:freshbase(data,sender)
end
function CreateRoomDKController:clickPeopleSelect(sender)
SoundMng.playEft('btn_click.mp3')
local data = sender:getComponent("ComExtensionData"):getCustomProperty()
self.view:freshpeopleSelect(data,sender)
end
function CreateRoomDKController:clickroomPrice(sender)
SoundMng.playEft('btn_click.mp3')
local data = sender:getComponent("ComExtensionData"):getCustomProperty()
self.view:freshroomPrice(data,sender)
end
function CreateRoomDKController:clickputMoney(sender)
SoundMng.playEft('btn_click.mp3')
local data = sender:getComponent("ComExtensionData"):getCustomProperty()
self.view:freshputmoney(data,sender)
end
function CreateRoomDKController:clickLimit(sender)
SoundMng.playEft('btn_click.mp3')
local data = sender:getComponent("ComExtensionData"):getCustomProperty()
self.view:freshlimit(data,sender)
end
function CreateRoomDKController:clickStartMode(sender)
SoundMng.playEft('btn_click.mp3')
local data = sender:getComponent("ComExtensionData"):getCustomProperty()
self.view:freshstartMode(data,sender)
end
function CreateRoomDKController:clickWanfa(sender)
SoundMng.playEft('btn_click.mp3')
self.view:freshwanfa()
end
function CreateRoomDKController:clickWinner(sender)
SoundMng.playEft('btn_click.mp3')
local data = sender:getComponent("ComExtensionData"):getCustomProperty()
self.view:freshWinner(data,sender)
end
-------------------------------------------------------------------------------------
return CreateRoomDKController
|
--
-- Update and install World of Warcraft addons from the command line.
-- Author : Phanx <[email protected]>
-- Website: https://gitlab.com/phanx/wow-addon-updater
-- License: Zlib - see LICENSE.txt for full text
--
local cleanHTML = dofile("utils/cleanHTML.lua")
local decodeEntities = dofile("utils/decodeEntities.lua")
local encodeURL = dofile("utils/encodeURL.lua")
local exports = {}
local function getTimestamp(y, m, d, hh, mm)
return os.time({
year = tonumber(y) or 2099,
month = tonumber(m) or 1,
day = tonumber(d) or 1,
hour = tonumber(hh) or 12,
minute = tonumber(mm) or 0,
})
end
--[[
info
Maps CLI acesskey to site name, and name to human-facing title
--]]
local info = {
{ key = "c", id = "curseforge", name = "CurseForge" },
{ key = "a", id = "wowace", name = "WowAce" },
{ key = "i", id = "wowinterface", name = "WoWInterface" },
}
for i = 1, #info do
local site = info[i]
info[site.key] = site
info[site.id] = site
end
exports.info = info
--[[
getFilesListURL
--]]
local getFilesListURL = {}
exports.getFilesListURL = getFilesListURL
getFilesListURL["curseforge"] = function(id) return "https://wow.curseforge.com/projects/" .. id .. "/files" end
getFilesListURL["wowace"] = function(id) return "https://www.wowace.com/projects/" .. id .. "/files" end
getFilesListURL["wowinterface"] = function(id) return "https://www.wowinterface.com/downloads/fileinfo.php?id=" .. id end
--[[
parseFilesList
--]]
local parseFilesList = {}
exports.parseFilesList = parseFilesList
local function sortFilesByDate(a, b)
return (a.date or 0) > (b.date or 0)
end
parseFilesList["curseforge"] = function(url, html, t)
html = cleanHTML(html)
t = t or {}
local host = url:match("https://[^/]+")
for tr in html:gmatch('<tr class="project%-file%-list%-item">(.-)</tr>') do
local name = tr:match('data%-action="file%-link" data%-id="[^"]+" data%-name="([^"]+)"')
local link = tr:match('<a class="button tip fa%-icon%-download icon%-only" href="([^"]+)"')
local date = tr:match('data%-epoch="(%d+)"')
if name and link and date then
table.insert(t, {
name = name,
link = host .. link,
date = tonumber(date),
})
end
end
if #t > 0 then
table.sort(t, sortFilesByDate)
end
return t
end
parseFilesList["wowace"] = parseFilesList["curseforge"]
parseFilesList["wowinterface"] = function(url, html, t)
html = cleanHTML(html)
t = t or {}
local host = url:match("https://[^/]+")
if url:find("/downloads/landing%.php") then
local file = t[1]
if file then
local link = html:match('<div class="manuallink">.- <a href="(.-)">Click here</a>')
file.link = decodeEntities(link)
file.middleman = false
end
return t
end
do
local name = html:match('<div id="version">Version: ([^<]+)</div>')
local link = decodeEntities(html:match('<a[^>]* href="(/downloads/[^"]+)">Download</a>'))
local d, m, y, hh, mm, am = html:match('<div id="safe">Updated: (%d+)%-(%d+)%-(%d+) (%d+):(%d+) ([AP]M)</div>')
if am == "PM" then hh = tonumber(hh) + 12 end
local updated = getTimestamp(y, m, d, hh, mm)
if name and link and updated then
table.insert(t, {
name = name,
link = host .. link,
date = updated,
middleman = true,
})
end
end
--[[
for tr in html:gmatch('<tr class="project%-file%-list%-item">(.-)</tr>') do
local name = tr:match('data%-action="file%-link" data%-id="[^"]+" data%-name="([^"]+)"')
local link = tr:match('<a class="button tip fa%-icon%-download icon%-only" href="([^"]+)"')
local date = tr:match('<div id="safe">Updated: 06-18-17 02:46 AM</div>')
if name and link and date then
table.insert(t, {
name = name,
link = host .. link,
date = tonumber(date),
})
end
end
]]
if #t > 0 then
table.sort(t, sortFilesByDate)
end
return t
end
--[[
getSearchURL
Construct a search URL for the given query term
--]]
local getSearchURL = {}
exports.getSearchURL = getSearchURL
getSearchURL["curseforge"] = function(term)
return "https://wow.curseforge.com/search?search=" .. encodeURL(term)
end
getSearchURL["wowace"] = function(term)
return "https://www.wowace.com/search?search=" .. encodeURL(term)
end
getSearchURL["wowinterface"] = function(term)
-- TODO: it should be POST to match the actual site
return "https://www.wowinterface.com/downloads/search.php?search=" .. encodeURL(term)
end
--[[
parseProjectURL
Parse URL for an addon site and ID/slug
--]]
local function parseProjectURL(url)
if type(url) ~= "string" then return end
local id = url:match("//wow.curseforge.com/projects/([^/]+)")
if id then
return "curseforge", id
end
id = url:match("//www.wowace.com/projects/([^/]+)")
if id then
return "wowace", id
end
-- WoWInterface usually has a "www" subdomain, but can also have
-- an author name subdomain if coming from an Author Portal page.
id = url:match("[/%.]wowinterface.com/downloads/info(%d+)")
or url:match("[/%.]wowinterface.com/downloads/fileinfo%.php%?id=(%d+)")
or url:match("[/%.]wowinterface.com/downloads/download(%d+)")
if id then
return "wowinterface", id
end
end
exports.parseProjectURL = parseProjectURL
--[[
parseSearchResults
Parse an HTML document and return a list of search results
parser = parseSearchResults[site]
- site: string
parser(html, t)
- html: string
- t: optional, table into which to insert results
--]]
local parseSearchResults = {}
exports.parseSearchResults = parseSearchResults
parseSearchResults["curseforge"] = function(html, t)
t = t or {}
for tr in cleanHTML(html):gmatch('<tr class="results">.-</tr>') do
local id, name = tr:match('<a href="/projects/([^"?/]+)[^"]*">(.-)</a>')
name = name and name:gsub("<[^>]+>", "") -- remove <span>s used to highlight search terms
local author = tr:match('<a href="/members/[^"]+">([^<]+)</a>')
local date = tr:match(' data%-epoch="(%d+)"')
if id and name and author then
table.insert(t, {
site = "curseforge",
id = id,
name = name,
author = author,
date = tonumber(date),
})
end
end
return t
end
parseSearchResults["wowace"] = function(html, t)
t = parseSearchResults["curseforge"](html, t)
for _, result in pairs(t) do
result.site = "wowace"
end
return t
end
parseSearchResults["wowinterface"] = function(html, t)
t = t or {}
local cleanedHtml = cleanHTML(html)
if cleanedHtml:match('>Addon Info.<') then
local id = cleanedHtml:match('/downloads/download(%d+)%-')
local name = cleanedHtml:match('<h1>(.-)</h1>')
local author = cleanedHtml:match('/forums/member%.php[^"]+"><b>(.-)</b>')
local d, m, y, hh, mm, am = cleanedHtml:match('<div id="safe">Updated: (%d+)%-(%d+)%-(%d+) (%d+):(%d+) ([AP]M)</div>')
if hh and am == "PM" then hh = tonumber(hh) + 12 end
local date = getTimestamp(y, m, d, hh, mm)
if id and name and author then
table.insert(t, {
site = "wowinterface",
id = id,
name = name,
author = author,
date = date,
})
end
else
for tr in cleanedHtml:gmatch('<tr>(.-)</tr>') do
local id, name = tr:match('<a href="fileinfo.php%?[^"]*id=(%d+)[^"]*">(.-)</a>')
local author = tr:match('<a href="/forums/member%.php[^"]+">(.-)</a>')
local m, d, y = cleanedHtml:match('<td align="center" class="alt1">(%d+)%-(%d+)%-(%d+)</td>')
local date = getTimestamp(y, m, d)
if id and name and author then
table.insert(t, {
site = "wowinterface",
id = id,
name = name,
author = author,
date = date,
})
end
end
end
return t
end
return exports
|
local GearBase = require("Gears.GearBase")
local GearXY = class('GearXY', GearBase)
function GearXY:ctor(owner)
GearXY.super.ctor(self, owner)
end
function GearXY:init()
self._default = { x=self._owner.x, y=self._owner.y }
self._storage = {}
end
function GearXY:addStatus(pageId, buffer)
local gv;
if pageId == nil then
gv = self._default
else
gv = {}
self._storage[pageId] = gv;
end
gv.x = buffer:readInt();
gv.y = buffer:readInt();
end
function GearXY:apply()
local gv = self._storage[self.controller.selectedPageId]
if not gv then gv = self._default end
if self.tween and UIPackage._constructing == 0 and not GearBase.disableAllTweenEffect then
if self._tweener then
if self._tweener.endValue.x ~= gv.x or self._tweener.endValue.y ~= gv.y then
self._tweener:kill(true)
self._tweener = nil
else
return
end
end
if gv.x ~= self._owner.x or gv.y ~= self._owner.y then
if self._owner:checkGearController(0, self.controller) then
self._displayLockToken = self._owner:addDisplayLock()
end
self._tweener = GTween.to(self._owner.x,self._owner.y, gv.x, gv.y, self.duration)
:setDelay(self.delay)
:setEase(self.easeType)
:setTarget(self)
:onUpdate(self.onTweenUpdate, self)
:onComplete(self.onTweenComplete, self)
end
else
self._owner._gearLocked = true;
self._owner:setPosition(gv.x, gv.y)
self._owner._gearLocked = false;
end
end
function GearXY:onTweenUpdate(tweener)
self._owner._gearLocked = true;
self._owner:setPosition(tweener.value.x, tweener.value.y);
self._owner._gearLocked = false;
end
function GearXY:onTweenComplete(tweener)
self._tweener = nil
if self._displayLockToken~=0 then
self._owner:releaseDisplayLock(self._displayLockToken);
self._displayLockToken = 0;
end
self._owner:emit("gearStopped");
end
function GearXY:updateState()
local gv = self._storage[self.controller.selectedPageId]
if not gv then
gv = {}
self._storage[self.controller.selectedPageId] = gv
end
gv.x = self._owner.x;
gv.y = self._owner.y;
end
function GearXY:updateFromRelations(dx, dy)
if self.controller~=nil and self._storage~=nil then
for _,gv in pairs(_storage) do
gv.x = gv.x + dx;
gv.y = gv.y + dy;
end
self._default.x = self._default.x + dx;
self._default.y = self._default.y + dy;
self:updateState();
end
end
return GearXY |
workspace "Praction"
architecture "x64"
configurations
{
"Debug",
"Release",
"Dist"
}
--[[ output directory is the location of built files --]]
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
--[[ cfg.buildcfg : debug/release/etc --]]
--[[ cfg.system : windows/mac/linux --]]
--[[ cfg.architecture : x64/x86/etc --]]
-- Include directories are set relative to root folder (solution directory)
IncludeDir = {}
IncludeDir["GLFW"] = "Praction/vendor/GLFW/include"
IncludeDir["Glad"] = "Praction/vendor/Glad/include"
IncludeDir["ImGui"] = "Praction/vendor/imgui"
-- IncludeDir is a struct that will grow as more directories are to be included
include "Praction/vendor/GLFW"
include "Praction/vendor/Glad"
include "Praction/vendor/imgui"
project "Praction"
location "Praction"
kind "SharedLib"
language "C++"
staticruntime "off"
--[[ binaries executable --]]
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
--[[ prj.name : project name --]]
--[[ object files --]]
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
--[[ precompiled files --]]
pchheader "ptpch.h"
pchsource "Praction/src/ptpch.cpp"
files
{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp"
}
includedirs
{
"%{prj.name}/src",
"%{prj.name}/vendor/spdlog/include",
"%{IncludeDir.GLFW}",
"%{IncludeDir.Glad}",
"%{IncludeDir.ImGui}"
}
links
{
"GLFW",
"Glad",
"ImGui",
"opengl32.lib"
}
filter "system:windows"
cppdialect "C++17"
systemversion "latest"
defines
{
"PT_PLATFORM_WINDOWS",
"PT_BUILD_DLL",
"GLFW_INCLUDE_NONE"
}
--[[ automatically copies game engine's dll into sanbox's after each build --]]
postbuildcommands
{
("{COPY} %{cfg.buildtarget.relpath} ../bin/" .. outputdir .. "/Sandbox")
}
filter "configurations:Debug"
defines "PT_DEBUG"
runtime "Debug"
symbols "On"
filter "configurations:Release"
defines "PT_RELEASE"
runtime "Release"
optimize "On"
filter "configurations:Dist"
defines "PT_DIST"
runtime "Release"
optimize "On"
project "Sandbox"
location "Sandbox"
kind "ConsoleApp"
language "C++"
staticruntime "off"
--[[ binaries --]]
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
--[[ object files --]]
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
files
{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp"
}
includedirs
{
"Praction/vendor/spdlog/include",
"Praction/src"
}
links
{
"Praction"
}
filter "system:windows"
cppdialect "C++17"
systemversion "latest"
defines
{
"PT_PLATFORM_WINDOWS"
}
filter "configurations:Debug"
defines "PT_DEBUG"
runtime "Debug"
symbols "On"
filter "configurations:Release"
defines "PT_RELEASE"
runtime "Release"
optimize "On"
filter "configurations:Dist"
defines "PT_DIST"
runtime "Release"
optimize "On"
|
object_tangible_loot_npc_loot_heroic_sm_generator = object_tangible_loot_npc_loot_shared_heroic_sm_generator:new {
}
ObjectTemplates:addTemplate(object_tangible_loot_npc_loot_heroic_sm_generator, "object/tangible/loot/npc/loot/heroic_sm_generator.iff")
|
local sprite_demo = class({})
--for the demo state ui
sprite_demo.name = "sprites and entities"
sprite_demo.description = ([[
complex sprite management and lots of particle spam
(space to add an extra firework)
]]):dedent()
--setup
function sprite_demo:new(parent)
self.k = ferris.kernel()
--tilemap layer
:add_system("tiles", require("src.systems.tile_system"){
map = assets.map.sprites,
image = assets.image.tiles,
tilesize = vec2(8, 8),
})
--arbitrary behaviours
:add_system("behaviour", ferris.systems.behaviour_system())
--2d z sorted sprites
:add_system("sprite", ferris.systems.sprite_system())
--sprite animation management
:add_system("animation", ferris.systems.animation_system())
--create the ferris wheel entity, which handles the fireworks and all the rest
require("src.demos.sprites.wheel")(self.k.systems, {
pos = vec2(21, 8):scalar_mul_inplace(8),
})
end
function sprite_demo:update(dt)
self.k:update(dt)
end
function sprite_demo:draw()
self.k:draw()
end
return sprite_demo
|
AddCSLuaFile()
ENT.Model = "models/props_wasteland/gaspump001a.mdl"
ENT.Type = "anim"
ENT.Base = "base_anim"
ENT.PrintName = "Shop"
ENT.Author = "Piengineer"
ENT.Contact = "http://steamcommunity.com/id/Piengineer12/"
ENT.Purpose = "A shop to sell things."
ENT.Instructions = "Press 'Use' to open up the menu."
ENT.Category = "Pointshop"
ENT.Spawnable = true
ENT.AdminOnly = true
if SERVER then
util.AddNetworkString("OpenShopMenu")
util.AddNetworkString("OpenBuyMenu")
util.AddNetworkString("ShopUpdate")
util.AddNetworkString("ShopBuy")
util.AddNetworkString("ShopBuyModify")
util.AddNetworkString("RevalidModel")
--resource.AddFile("materials/vgui/entities/ps_shop.vmt")
-- The above just wastes space at this point.
end
function ENT:SpawnFunction( ply, tr, class )
if ( !tr.Hit ) then return end
local SpawnPos = tr.HitPos + tr.HitNormal * 30
local SpawnAng = ply:EyeAngles()
SpawnAng.p = 0
SpawnAng.y = SpawnAng.y + 90
local ent = ents.Create( class )
ent:SetPos( SpawnPos )
ent:SetAngles( SpawnAng )
ent:Spawn()
ent:Activate()
return ent
end
function ENT:SetupDataTables()
self:NetworkVar("String",0,"ShopItemName")
self:NetworkVar("Int",0,"ShopItemPrice")
self:NetworkVar("Bool",0,"Locked")
self:NetworkVar("String",1,"ShopModel")
end
function ENT:Initialize()
if self:GetShopModel() ~= nil and util.IsValidModel(self:GetShopModel()) then
self:SetModel( self:GetShopModel() )
else
self:SetModel( self.Model )
end
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
if SERVER then self:PhysicsInit( SOLID_VPHYSICS ) end
-- Make prop to fall on spawn
local phys = self:GetPhysicsObject()
if ( IsValid( phys ) ) then phys:Wake() end
if SERVER then self:SetUseType(SIMPLE_USE) end
end
function ENT:Use(activator, ply)
if IsValid(ply) and ply:IsPlayer() then
if PS == nil then net.Start("VerifyPointshop",true); net.Send(ply); return end
if not self:GetLocked() and ply:IsAdmin() then
net.Start("OpenShopMenu",true)
net.WriteEntity(self)
net.Send(ply)
elseif self:GetLocked() then
net.Start("OpenBuyMenu",true)
net.WriteEntity(self)
net.WriteString(self:GetShopItemName())
net.WriteInt(self:GetShopItemPrice(),32)
net.Send(ply)
end
end
end
function ENT:Draw()
self.Entity:DrawModel()
end
-- Client UI
local panelx = 400
local panely = 300
local funclen = 150
local inputname = ""
local inputprice = 0
local modelname = ""
net.Receive("OpenShopMenu", function()
if not CLIENT then return end
local shop = net.ReadEntity()
if not IsValid(shop) then notification.AddLegacy( "Shop is nonexistent!", NOTIFY_ERROR, 5 ); surface.PlaySound( "buttons/button10.wav" ); return end
local Main = vgui.Create("DFrame")
Main:SetSize( panelx, panely )
Main:Center()
Main:SetTitle( "Edit Shop" )
Main:SetVisible( true )
Main:SetDraggable( true )
Main:ShowCloseButton( true )
Main:MakePopup()
Main.Paint = function( self, w, h ) -- 'function Frame:Paint( w, h )' works too
local points = LocalPlayer():PS_GetPoints() ~= nil and LocalPlayer():PS_GetPoints() or 0
draw.RoundedBox( 4, 0, 0, w, h, Color( 127, 0, 0, 255 ) ) -- Draw a box instead of the frame
if Main:IsActive() then draw.RoundedBox( 4, 0, 0, w, 24, Color( 191, 0, 0, 255 ) ) end
draw.SimpleText("Item ClassName","PS_ButtonText1",w/2,60,Color(255,255,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_BOTTOM)
draw.SimpleText("Item Price","PS_ButtonText1",w/2,120,Color(0,255,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_BOTTOM)
draw.SimpleText("Shop Model","PS_ButtonText1",w/2,180,Color(0,255,255,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_BOTTOM)
if PS.Items[inputname] ~= nil then draw.SimpleText("Item: "..PS.Items[inputname].Name..". Original Price: "..PS.Items[inputname].Price.." "..PS.Config.PointsName,
"DermaDefault",w/2,80,Color(0,255,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_TOP) end
end
--ItemName validation indicator.
local ItemCheck = vgui.Create( "DImage",Main)
ItemCheck:SetPos(panelx/2+funclen/2+2,60+2)
ItemCheck:SetSize(16,16)
--ItemName entry.
local ItemName = vgui.Create( "DTextEntry",Main)
ItemName:SetPos(-1,60)
ItemName:SetSize(funclen, 20)
ItemName:CenterHorizontal()
ItemName:SetText(inputname)
ItemCheck:SetImage(PS.Items[inputname] and "icon16/tick.png" or "icon16/cross.png")
ItemName.OnChange = function(self)
inputname = self:GetValue()
ItemCheck:SetImage(PS.Items[inputname] and "icon16/tick.png" or "icon16/cross.png")
end
--ItemName browser button.
local ItemBrowserStart = vgui.Create( "DButton",Main)
ItemBrowserStart:SetText("Browse...")
ItemBrowserStart:SetPos(panelx/2+funclen/2+20,60)
ItemBrowserStart:SetSize(80, 20)
ItemBrowserStart.DoClick = function()
-- ItemBrowser window.
local ItemBrowser = vgui.Create( "DFrame" )
ItemBrowser:SetSize( panelx, panely )
ItemBrowser:Center()
ItemBrowser:MakePopup()
ItemBrowser:SetTitle( "Item Browser" )
ItemBrowser.Paint = function( self, w, h )
draw.RoundedBox( 4, 0, 0, w, h, Color( 0, 127, 127, 255 ) )
if ItemBrowser:IsActive() then draw.RoundedBox( 4, 0, 0, w, 24, Color( 0, 191, 191, 255 ) ) end
end
local ItemBrowserGUI = vgui.Create( "DFileBrowser", ItemBrowser )
ItemBrowserGUI:Dock( FILL )
ItemBrowserGUI:SetPath( "LUA" )
ItemBrowserGUI:SetBaseFolder( "pointshop/items" )
ItemBrowserGUI:SetOpen( true )
function ItemBrowserGUI:OnSelect(path,panel)
local matched = string.match(path,"%/.*%/.*%/(.*)%.lua") -- This line took about ONE HOUR to make. Why are patterns so hard to understand?
if matched ~= "__category" then
ItemCheck:SetImage(PS.Items[matched] and "icon16/tick.png" or "icon16/cross.png")
ItemName:SetText(matched)
inputname = matched
end
end
function ItemBrowserGUI:OnDoubleClick( path, panel )
ItemBrowser:Close()
end
function Main:OnClose()
if IsValid(ItemBrowser) then
ItemBrowser:Close()
end
end
end
--ItemPrice validation indicator.
local ItemTick = vgui.Create( "DImage",Main)
ItemTick:SetPos(panelx/2+funclen/2+2,120+2)
ItemTick:SetSize(16,16)
--ItemPrice entry.
local ItemPrice = vgui.Create( "DTextEntry",Main)
ItemPrice:SetPos(-1,120)
ItemPrice:SetSize(funclen, 20)
ItemPrice:CenterHorizontal()
ItemPrice:SetText(inputprice ~= 0 and inputprice or "")
ItemPrice:SetNumeric(true)
ItemTick:SetImage(inputprice >= 0 and "icon16/tick.png" or "icon16/cross.png")
ItemPrice.OnChange = function(self)
inputprice = tonumber(self:GetValue()) or 0
ItemTick:SetImage(inputprice >= 0 and "icon16/tick.png" or "icon16/cross.png")
end
--Model validation indicator.
local ModelCheck = vgui.Create( "DImage",Main)
ModelCheck:SetPos(panelx/2+funclen/2+2,180+2)
ModelCheck:SetSize(16,16)
--Model entry.
local ModelName = vgui.Create( "DTextEntry",Main)
ModelName:SetPos(-1,180)
ModelName:SetSize(funclen, 20)
ModelName:CenterHorizontal()
ModelName:SetText(modelname)
if util.IsValidModel(modelname) or modelname == "" then
ModelCheck:SetImage("icon16/tick.png")
else
ModelCheck:SetImage("icon16/cross.png")
end
ModelName.OnChange = function(self)
modelname = self:GetValue()
if util.IsValidModel(modelname) or modelname == "" then
ModelCheck:SetImage("icon16/tick.png")
else
ModelCheck:SetImage("icon16/cross.png")
end
end
--Model revalidation button.
local ModelRecheck = vgui.Create( "DButton",Main)
ModelRecheck:SetText("Verify Model")
ModelRecheck:SetPos(panelx/2+funclen/2+20,180)
ModelRecheck:SetSize(80, 20)
ModelRecheck.DoClick = function()
net.Start("RevalidModel",true)
net.WriteString(modelname)
net.SendToServer()
timer.Simple(RealFrameTime(),function()
if IsValid(ModelCheck) then
if util.IsValidModel(modelname) or modelname == "" then
ModelCheck:SetImage("icon16/tick.png")
else
ModelCheck:SetImage("icon16/cross.png")
end
end
end)
end
--Set button.
local ItemSet = vgui.Create( "DButton", Main )
ItemSet:SetText( "Save" )
ItemSet:SetPos(panelx/2-funclen/2,220)
ItemSet:SetSize(funclen, 60)
ItemSet.DoClick = function()
if PS.Items[inputname] == nil then notification.AddLegacy( "Invalid item!", NOTIFY_ERROR, 5 ); surface.PlaySound( "buttons/button10.wav" ); return end
if modelname == "" then modelname = shop:GetModel() end
if not util.IsValidModel(modelname) then notification.AddLegacy( "Invalid model! Leave blank for default model.", NOTIFY_ERROR, 5 ); surface.PlaySound( "buttons/button10.wav" ); return end
if inputprice < 0 then notification.AddLegacy( "Price can't be negative!", NOTIFY_ERROR, 5 ); surface.PlaySound( "buttons/button10.wav" ); return end
inputprice = math.min(inputprice,2147483647)
if not IsValid(shop) then notification.AddLegacy( "Shop is nonexistent!", NOTIFY_ERROR, 5 ); surface.PlaySound( "buttons/button10.wav" ); Main:Remove(); return end
net.Start("ShopUpdate",true)
net.WriteEntity(shop)
net.WriteString(inputname)
net.WriteInt(inputprice,32)
net.WriteString(modelname)
net.SendToServer()
Main:Close()
end
end)
net.Receive("OpenBuyMenu", function()
if not CLIENT then return end
local shop = net.ReadEntity()
if not IsValid(shop) then notification.AddLegacy( "Shop is nonexistent!", NOTIFY_ERROR, 5 ); surface.PlaySound( "buttons/button10.wav" ); return end
local item = net.ReadString()
local name = PS.Items[item].Name
local price = net.ReadInt(32)
local Main = vgui.Create("DFrame")
Main:SetSize( panelx, panely )
Main:Center()
Main:SetTitle( "Shop" )
Main:SetVisible( true )
Main:SetDraggable( true )
Main:ShowCloseButton( true )
Main:MakePopup()
Main.Paint = function( self, w, h ) -- 'function Frame:Paint( w, h )' works too
local points = LocalPlayer():PS_GetPoints() ~= nil and LocalPlayer():PS_GetPoints() or 0
draw.RoundedBox( 4, 0, 0, w, h, Color( 127, 0, 0, 255 ) ) -- Draw a box instead of the frame
draw.RoundedBox( 4, 0, 0, w, 24, Color( 191, 0, 0, 255 ) )
draw.SimpleText("This shop is selling","PS_ButtonText1",w/2,panely/2-60,Color(255,255,255,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_BOTTOM)
draw.SimpleText(name,"PS_ButtonText1",w/2,panely/2-40,Color(0,255,255,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_BOTTOM)
draw.SimpleText("for","PS_ButtonText1",w/2,panely/2-20,Color(255,255,255,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_BOTTOM)
draw.SimpleText(price.." "..PS.Config.PointsName,"PS_ButtonText1",w/2,panely/2,Color(0,255,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_BOTTOM)
draw.SimpleText("You have "..points.." "..PS.Config.PointsName,"PS_ButtonText1",w/2,panely/2+40,Color(255,255,0,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_BOTTOM)
end
--Buy/sell button.
local ItemSet = vgui.Create( "DButton", Main )
ItemSet:SetText( "Buy!" )
ItemSet:SetPos(panelx/2-funclen/2,panely-90)
ItemSet:SetSize(funclen, 60)
ItemSet.DoClick = function()
if LocalPlayer():PS_HasItem(item) then notification.AddLegacy( "You already have this!", NOTIFY_ERROR, 5 ); surface.PlaySound( "buttons/button10.wav" ); return end
if not IsValid(shop) then notification.AddLegacy( "Shop is nonexistent!", NOTIFY_ERROR, 5 ); surface.PlaySound( "buttons/button10.wav" ); Main:Remove(); return end
if price > LocalPlayer():PS_GetPoints() then notification.AddLegacy( "Not enough "..PS.Config.PointsName.."!", NOTIFY_ERROR, 5 ); surface.PlaySound( "buttons/button10.wav" ); return end
net.Start("ShopBuy",true)
net.WriteEntity(shop)
net.SendToServer()
Main:Close()
end
--Unlock button.
if LocalPlayer():IsAdmin() then
local ItemSet = vgui.Create( "DButton", Main )
ItemSet:SetText( "Reset" )
ItemSet:SetTextColor(Color(255,0,0,255))
ItemSet:SetPos(panelx/2+funclen/2+30,panely-90)
ItemSet:SetSize(60, 60)
ItemSet.DoClick = function()
if not IsValid(shop) then notification.AddLegacy( "Shop is nonexistent!", NOTIFY_ERROR, 5 ); surface.PlaySound( "buttons/button10.wav" ); Main:Remove(); return end
net.Start("ShopBuyModify",true)
net.WriteEntity(shop)
net.SendToServer()
Main:Close()
end
if IsValid(LocalPlayer().PBSIE) then
--Interfacer connect button.
local StartCon = vgui.Create( "DButton",Main)
StartCon:SetText("Connect...")
StartCon:SetTextColor(Color(0,0,255,255))
StartCon:SetPos(panelx/2-funclen/2-90,panely-90)
StartCon:SetSize(60, 60)
StartCon.DoClick = function()
net.Start("InterUpdate")
net.WriteInt(LocalPlayer().PBSI,8)
net.WriteEntity(LocalPlayer().PBSIE)
net.WriteEntity(shop)
net.SendToServer()
LocalPlayer().PBSI = nil
LocalPlayer().PBSIE = nil
chat.AddText(Color(0,255,0),"[PSBanks] ",Color(0,127,255),"Shop Connected!")
StartCon:Remove()
end
end
end
end)
-- Server UI
net.Receive("ShopUpdate", function(bits,sender)
if not sender:IsPlayer() or not SERVER then return end
local target = net.ReadEntity()
if not IsValid(target) or not sender:IsAdmin() then return end --It *might* have been deleted after the player sent it idk
local name = net.ReadString()
if PS.Items[name] == nil then return end
local price = net.ReadInt(32)
if price == nil or price < 0 then return end
local model = net.ReadString()
if not util.IsValidModel(model) then return end
target:SetShopItemName(name)
target:SetShopItemPrice(price)
target:SetLocked(true)
if model ~= target:GetModel() then
target:SetModel(model)
target:SetShopModel(model)
target:PhysicsInit( SOLID_VPHYSICS )
local phys = target:GetPhysicsObject()
if ( IsValid( phys ) ) then phys:Wake() end
end
end)
net.Receive("ShopBuy", function(bits,sender)
if not sender:IsPlayer() or not SERVER then return end
local target = net.ReadEntity()
if not IsValid(target) then return end --It *might* have been deleted after the player sent it idk
if sender:PS_GetPoints() >= target:GetShopItemPrice() then
sender:PS_TakePoints(target:GetShopItemPrice())
PS.Items[target:GetShopItemName()]:OnBuy(sender)
sender:ChatPrint("Bought "..PS.Items[target:GetShopItemName()].Name..".")
if PS.Items[target:GetShopItemName()].SingleUse then return end
sender:PS_GiveItem(target:GetShopItemName())
sender:PS_EquipItem(target:GetShopItemName())
end
end)
net.Receive("ShopBuyModify", function(bits,sender)
if not sender:IsPlayer() or not SERVER then return end
local target = net.ReadEntity()
if not IsValid(target) then return end
if sender:IsAdmin() and target:GetLocked() then
target:SetLocked(false)
if target.Model ~= target:GetModel() then
target:SetModel(target.Model)
target:PhysicsInit( SOLID_VPHYSICS )
local phys = target:GetPhysicsObject()
if ( IsValid( phys ) ) then phys:Wake() end
end
end
end)
net.Receive("RevalidModel", function(bits,sender)
if not sender:IsPlayer() or not SERVER then return end
local target = net.ReadString()
util.IsValidModel(Model(target)) -- This apparently tells the client it's there. So, don't do anything.
end) |
-------------
-- Defines --
-------------
#wg_show = 1
#wg_isshown = 2
#wg_move = 3
#wg_resize = 4
#wg_getsize = 5
#wg_getpos = 6
#wg_reset = 7
-------------------
-- Custom events --
-------------------
addEvent ( "onRafalhAddWidget" )
addEvent ( "onRafalhGetWidgets" )
|
RecalcForceCommand = {
name = "recalcforce",
}
AddCommand(RecalcForceCommand)
|
local meta = getrawmetatable(game)
local old = meta.__namecall
setreadonly(meta, false)
meta.__namecall = newcclosure(function(self,...)
local method = getnamecallmethod()
local args = {...}
if method == "FireServer" and self.Name == "StaminaWaste" then
return nil
else
return old(self,...)
end
end) |
local c = require('component')
local event = require('event')
local filesystem = require('filesystem')
local log = require('log')('media')
local MEDIA_FOLDER = '/media/'
started = false
local getAllFsAddr = function() return c.list('filesystem') end
local getFsProxy = function(addr) return c.proxy(addr) end
local getAllFs = pipe(getAllFsAddr, keys, map(getFsProxy))
local isFsAccepted = function(fs)
local label = fs.getLabel()
if label == 'tmpfs' then return false end
if fs.address == filesystem.get('/').address then
return false
end
return Boolean(label)
end
local handleFsAdded = log.wrap(function(_, addr, componentType)
if componentType == 'filesystem' then
local fs = c.proxy(addr)
if isFsAccepted(fs) then
local mediaPath = filesystem.concat(MEDIA_FOLDER, fs.getLabel())
filesystem.mount(addr, mediaPath)
end
end
end)
local handleFsRemoved = log.wrap(function(_, addr, componentType)
if componentType == 'filesystem' then
filesystem.umount(addr)
end
end)
_G.reload = function()
forEach(function(fs)
if isFsAccepted(fs) then
local mediaPath = filesystem.concat(MEDIA_FOLDER, fs.getLabel())
if not filesystem.exists(mediaPath) then
filesystem.mount(fs.address, mediaPath)
end
end
end, getAllFs())
print('> filesystem /media/ mounting points reloaded')
end
_G.start = function()
if started then return; end
log.clean()
event.listen('component_added', handleFsAdded)
event.listen('component_removed', handleFsRemoved)
reload()
started = true
print("> started media")
end
function stop()
if not started then return; end
event.ignore('component_added', handleFsAdded)
event.ignore('component_removed', handleFsRemoved)
started = false
print("> stopped media")
end
_G.restart = function()
stop()
start()
end
_G.status = function()
if started
then print("> media: ON")
else print("> media: OFF")
end
end |
PROJECT = "hi"
VERSION = "1.0.0"
local sys = require "sys"
sys.taskInit(function()
while 1 do
log.info("luatos", "hi", os.date())
sys.wait(1000)
end
end)
-- 用户代码已结束---------------------------------------------
-- 结尾总是这一句
sys.run()
-- sys.run()之后后面不要加任何语句!!!!!
|
-- Squigs!
-- spliney kind of line squiggles... sorta like the roundrect version of a spline
--
-- Scott Lawrence - [email protected]
displayW = playdate.display.getWidth()
displayH = playdate.display.getHeight()
class('Squig').extends( Object )
function Squig:init()
Squig.super.init( self )
-- not used.
end
-- draw an auto squig
--- sorta like the roundrect version of a spline.
function Squig.drawAutoSquig( x1, y1, x2, y2 )
local gfx = playdate.graphics
-- if it's backwards, swap it
if( x1 > x2 ) then
x1, y1, x2, y2 = x2, y2, x1, y1
end
-- make the radius dependent on the squig deltas
local dx = math.abs( x2-x1 )
local dy = math.abs( y2-y1 )
local radius = math.min( dy/4, dx/4 )
if( radius > 32 ) then
radius = 32
end
local r2 = radius + radius
local xh = (x2+x1)/2
local yh = (y2+y1)/2
if( y1 < y2 ) then
-- draw for quadrants 2 and 4
gfx.drawLine( x1, y1, xh-radius, y1 )
gfx.drawArc( xh-radius, y1+radius, radius, 0, 90 )
gfx.drawLine( xh, y1+radius, xh, y2-radius )
gfx.drawArc( xh+radius, y2-radius, radius, 180, 270 )
gfx.drawLine( xh+radius, y2, x2, y2 )
else
gfx.drawLine( x1, y1, xh-radius, y1 )
gfx.drawArc( xh-radius, y1-radius, radius, 90, 180 )
gfx.drawLine( xh, y1-radius, xh, y2+radius )
gfx.drawArc( xh+radius, y2+radius, radius, 270, 360 )
gfx.drawLine( xh+radius, y2, x2, y2 )
end
--Squig.drawLeftHalfSquig( x1, y1, xh, yh )
--Squig.drawRightHalfSquig( xh, yh, x2, y2 )
return xh, yh
end
function Squig.drawLeftHalfSquig( x1, y1, x2, y2 )
-- if it's backwards, swap it
if( x1 > x2 ) then
x1, y1, x2, y2 = x2, y2, x1, y1
end
local dx = math.abs( x2-x1 )
local dy = math.abs( y2-y1 )
local radius = math.floor( math.min( dy/2, dx/2 ))
if( radius > 32 ) then
radius = 32
end
if( y1 < y2 ) then
gfx.drawLine( x1, y1, x2-radius, y1 )
gfx.drawArc( x2-radius, y1+radius, radius, 0, 90 )
gfx.drawLine( x2, y1+radius, x2, y2 )
else
gfx.drawLine( x1, y1, x2-radius, y1 )
gfx.drawArc( x2-radius, y1-radius, radius, 90, 180 )
gfx.drawLine( x2, y1-radius, x2, y2 )
end
end
function Squig.drawRightHalfSquig( x1, y1, x2, y2 )
-- if it's backwards, swap it
if( x1 > x2 ) then
x1, y1, x2, y2 = x2, y2, x1, y1
end
local dx = math.abs( x2-x1 )
local dy = math.abs( y2-y1 )
local radius = math.floor( math.min( dy/2, dx/2 ))
if( radius > 32 ) then
radius = 32
end
if( y1 < y2 ) then
-- bottom half
gfx.drawLine( x1, y1, x1, y2-radius )
gfx.drawArc( x1+radius, y2-radius, radius, 180, 270 )
gfx.drawLine( x1+radius, y2, x2, y2 )
else
-- top half
gfx.drawLine( x1, y1, x1, y2+radius )
gfx.drawArc( x1+radius, y2+radius, radius, 270, 360 )
gfx.drawLine( x1+radius, y2, x2, y2 )
end
end
function Squig.drawTrioSquig( x1, y1, xC, yC, x2, y2 )
Squig.drawLeftHalfSquig( x1, y1, xC, yC )
Squig.drawRightHalfSquig( xC, yC, x2, y2 )
end
function Squig.drawTrioPercentSquig( x1, y1, xP, yP, x2, y2 )
local xC = x1 + ( x2 - x1 ) * xP
local yC = y1 + ( y2 - y1 ) * yP
Squig.drawLeftHalfSquig( x1, y1, xC, yC )
Squig.drawRightHalfSquig( xC, yC, x2, y2 )
return xC, yC
end
|
client_script "simexe.lua"
|
FPP = FPP or {}
FPP.entOwners = FPP.entOwners or {}
FPP.entTouchability = FPP.entTouchability or {}
FPP.entTouchReasons = FPP.entTouchReasons or {}
local touchTypes = {
Physgun = 1,
Gravgun = 2,
Toolgun = 4,
PlayerUse = 8,
EntityDamage = 16
}
local reasonSize = 4 -- bits
local reasons = {
[1] = "owner", -- you can't touch other people's props
[2] = "world",
[3] = "disconnected",
[4] = "blocked",
[5] = "constrained",
[6] = "buddy",
[7] = "shared",
[8] = "player", -- you can't pick up players
}
local function receiveTouchData(len)
repeat
local entIndex = net.ReadUInt(32)
local ownerIndex = net.ReadUInt(32)
local touchability = net.ReadUInt(5)
local reason = net.ReadUInt(20)
FPP.entOwners[entIndex] = ownerIndex
FPP.entTouchability[entIndex] = touchability
FPP.entTouchReasons[entIndex] = reason
until net.ReadBit() == 1
end
net.Receive("FPP_TouchabilityData", receiveTouchData)
function FPP.entGetOwner(ent)
local idx = FPP.entOwners[ent:EntIndex()]
ent.FPPOwner = idx and Entity(idx) or nil
return ent.FPPOwner
end
function FPP.canTouchEnt(ent, touchType)
ent.FPPCanTouch = FPP.entTouchability[ent:EntIndex()]
if not touchType or not ent.FPPCanTouch then
return ent.FPPCanTouch
end
return bit.bor(ent.FPPCanTouch, touchTypes[touchType]) == ent.FPPCanTouch
end
local touchTypeMultiplier = {
["Physgun"] = 0,
["Gravgun"] = 1,
["Toolgun"] = 2,
["PlayerUse"] = 3,
["EntityDamage"] = 4
}
function FPP.entGetTouchReason(ent, touchType)
local idx = FPP.entTouchReasons[ent:EntIndex()] or 0
ent.FPPCanTouchWhy = idx
if not touchType then return idx end
local maxReasonValue = 15
-- 1111 shifted to the right touch type
local touchTypeMask = bit.lshift(maxReasonValue, reasonSize * touchTypeMultiplier[touchType])
-- Extract reason for touch type from reason number
local touchTypeReason = bit.band(idx, touchTypeMask)
-- Shift it back to the right
local reasonNr = bit.rshift(touchTypeReason, reasonSize * touchTypeMultiplier[touchType])
local reason = reasons[reasonNr]
local owner = ent:CPPIGetOwner()
if reasonNr == 1 then -- convert owner to the actual player
return not isnumber(owner) and IsValid(owner) and owner:Nick() or "Unknown player"
elseif reasonNr == 6 then
return "Buddy (" .. (IsValid(owner) and owner:Nick() or "Unknown player") .. ")"
end
return reason
end
|
-- The tested strategy.
strategy = "MaCross"
-- Path to the parameters file for the strategy.
strategyParams = "data/params/MaCross-backtest.lua"
-- Ask user confirmation before launching the backtest.
confirmLaunch = true
-- If false, only the start parameters will be used with one thread.
optimizationMode = false
-- What paramters generator to use ("genetic" coming later) (optmization mode only).
-- Choices: "complete"
paramsGenerator = "complete"
-- How to sort the results and find the best generated parameters.
-- Choices: "profit"
resultRanking = "profit"
-- If true, show the details of each trade at the end (non-optimization mode only).
showTradeDetails = true
-- If true, log every trade action in real time (buy/sell/adjust/close).
showTradeActions = true
-- Number of threads used for the test (optimization mode only).
threads = 3
-- Source bars.
history = "data/history/EURUSD_MetaQuotes_2011-10-31_2011-11-04.csv"
pair = "EURUSD" -- Two 3 characters currencies ISO 4217.
digits = 5
maxGapSize = 60 -- Generate up to X 1 minute bars before creating a gap in history.
-- Deposit in units of the counter currency.
deposit = 10000
-- Period in minutes.
period = 1
-- Spread in pips.
spread = 1.3
-- Minimal offset in pips between current price and target SL/TP price for opening and adjusting positions.
minPriceOffset = 5
-- false -> Maximum tick generation (up to 12 per 1-minute bar).
-- true -> Simple and faster tick generation (up to 4 per 1-minute bar).
fewerTicks = false
-- If true, the 2 plot files will be generated (non-optimization mode only).
plotOutput = true
-- Path to the plot data file.
plotDataFile = "backtest-result.dat"
-- Path to the plot settings file.
plotSettingsFile = "backtest-result.plt"
|
local cluster_reactor = assert(yatm.cluster.reactor)
local cluster_energy = yatm.cluster.energy
if not cluster_energy then
return
end
local function energy_bus_refresh_infotext(pos, node)
local meta = minetest.get_meta(pos)
local infotext =
cluster_reactor:get_node_infotext(pos) .. "\n" ..
cluster_energy:get_node_infotext(pos)
meta:set_string("infotext", infotext)
end
local energy_bus_reactor_device = {
kind = "energy_bus",
groups = {
energy_bus = 1,
device = 1,
},
default_state = "off",
states = {
conflict = "yatm_reactors:energy_bus_error",
error = "yatm_reactors:energy_bus_error",
off = "yatm_reactors:energy_bus_off",
on = "yatm_reactors:energy_bus_on",
idle = "yatm_reactors:energy_bus_idle",
}
}
local energy_bus_yatm_network = {
kind = "reactor_energy_bus",
groups = {
energy_producer = 1,
},
default_state = energy_bus_reactor_device.default_state,
states = energy_bus_reactor_device.states,
energy = {}
}
function energy_bus_yatm_network.energy.produce_energy(pos, node, dtime, ot)
return 0
end
yatm_reactors.register_stateful_reactor_node({
basename = "yatm_reactors:reactor_energy_bus",
description = "Reactor Energy Bus",
groups = {
cracky = 1,
yatm_energy_device = 1,
yatm_cluster_energy = 1,
},
drop = energy_bus_reactor_device.states.off,
tiles = {
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png^[transformFX",
"yatm_reactor_casing.plain.png",
"yatm_reactor_energy_bus_front.off.png"
},
paramtype = "none",
paramtype2 = "facedir",
reactor_device = energy_bus_reactor_device,
yatm_network = energy_bus_yatm_network, -- needed for energy
refresh_infotext = energy_bus_refresh_infotext,
}, {
error = {
tiles = {
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png^[transformFX",
"yatm_reactor_casing.plain.png",
"yatm_reactor_energy_bus_front.error.png"
},
},
on = {
tiles = {
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png^[transformFX",
"yatm_reactor_casing.plain.png",
"yatm_reactor_energy_bus_front.on.png"
},
},
idle = {
tiles = {
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png",
"yatm_reactor_casing.plain.png^[transformFX",
"yatm_reactor_casing.plain.png",
"yatm_reactor_energy_bus_front.idle.png"
},
}
})
|
--[[
Login.MouseButton1Down:connect(function()
if Login.Text == "trial" then
Main.Visible = false
Unlock.Visible = true
end
end)
--]]
local Synapse = Instance.new("ScreenGui")
local Main = Instance.new("ImageLabel")
local Frame = Instance.new("Frame")
local ReadyToBegn = Instance.new("TextLabel")
local Username = Instance.new("TextBox")
local Username2 = Instance.new("TextLabel")
local Password = Instance.new("TextBox")
local Password2 = Instance.new("TextLabel")
local Reset = Instance.new("TextButton")
local Register = Instance.new("TextButton")
local Login = Instance.new("TextButton")
local Extra = Instance.new("ImageLabel")
local Logo = Instance.new("ImageLabel")
local Scripting = Instance.new("TextLabel")
local Unlock = Instance.new("Frame")
local Text = Instance.new("TextLabel")
Synapse.Name = "Synapse"
Synapse.Parent = game.CoreGui
Main.Name = "Main"
Main.Parent = Synapse
Main.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
Main.BackgroundTransparency = 1.000
Main.Position = UDim2.new(0.0229218416, 0, 0.0542156659, 0)
Main.Size = UDim2.new(0, 317, 0, 50)
Main.Image = "http://www.roblox.com/asset/?id=5582792701"
Frame.Parent = Main
Frame.BackgroundColor3 = Color3.fromRGB(42, 42, 42)
Frame.BorderSizePixel = 0
Frame.Position = UDim2.new(-0.000719241682, 0, 0.751786828, 0)
Frame.Size = UDim2.new(0, 323, 0, 365)
ReadyToBegn.Name = "ReadyToBegn"
ReadyToBegn.Parent = Frame
ReadyToBegn.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
ReadyToBegn.BackgroundTransparency = 1.000
ReadyToBegn.Position = UDim2.new(0.0256648064, 0, 0.172125757, 0)
ReadyToBegn.Size = UDim2.new(0, 200, 0, 37)
ReadyToBegn.Font = Enum.Font.Gotham
ReadyToBegn.Text = "Ready to begin?"
ReadyToBegn.TextColor3 = Color3.fromRGB(255, 255, 255)
ReadyToBegn.TextSize = 23.000
Username.Name = "Username"
Username.Parent = Frame
Username.BackgroundColor3 = Color3.fromRGB(100, 100, 100)
Username.BorderColor3 = Color3.fromRGB(125, 125, 125)
Username.Position = UDim2.new(0.0670250803, 0, 0.364292949, 0)
Username.Size = UDim2.new(0, 280, 0, 21)
Username.ClearTextOnFocus = false
Username.Font = Enum.Font.Gotham
Username.Text = ""
Username.TextColor3 = Color3.fromRGB(255, 255, 255)
Username.TextSize = 14.000
Username.TextWrapped = true
Username.TextXAlignment = Enum.TextXAlignment.Left
Username2.Name = "Username2"
Username2.Parent = Username
Username2.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
Username2.BackgroundTransparency = 1.000
Username2.Position = UDim2.new(-0.255454451, 0, -1.79420328, 0)
Username2.Size = UDim2.new(0, 208, 0, 37)
Username2.Font = Enum.Font.Arial
Username2.Text = "Username"
Username2.TextColor3 = Color3.fromRGB(255, 255, 255)
Username2.TextSize = 13.000
Password.Name = "Password"
Password.Parent = Frame
Password.BackgroundColor3 = Color3.fromRGB(100, 100, 100)
Password.BorderColor3 = Color3.fromRGB(125, 125, 125)
Password.Position = UDim2.new(0.0670249388, 0, 0.51041919, 0)
Password.Size = UDim2.new(0, 280, 0, 21)
Password.ClearTextOnFocus = false
Password.Font = Enum.Font.Gotham
Password.Text = ""
Password.TextColor3 = Color3.fromRGB(255, 255, 255)
Password.TextSize = 14.000
Password.TextXAlignment = Enum.TextXAlignment.Left
Password2.Name = "Password2"
Password2.Parent = Password
Password2.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
Password2.BackgroundTransparency = 1.000
Password2.Position = UDim2.new(-0.255454451, 0, -1.41325164, 0)
Password2.Size = UDim2.new(0, 208, 0, 37)
Password2.Font = Enum.Font.Arial
Password2.Text = "Password"
Password2.TextColor3 = Color3.fromRGB(255, 255, 255)
Password2.TextSize = 13.000
Reset.Name = "Reset"
Reset.Parent = Frame
Reset.BackgroundColor3 = Color3.fromRGB(100, 100, 100)
Reset.BorderColor3 = Color3.fromRGB(125, 125, 125)
Reset.Position = UDim2.new(0.0256648101, 0, 0.86956507, 0)
Reset.Size = UDim2.new(0, 115, 0, 34)
Reset.Font = Enum.Font.Gotham
Reset.Text = "Reset Password"
Reset.TextColor3 = Color3.fromRGB(255, 255, 255)
Reset.TextSize = 14.000
Register.Name = "Register"
Register.Parent = Frame
Register.BackgroundColor3 = Color3.fromRGB(100, 100, 100)
Register.BorderColor3 = Color3.fromRGB(125, 125, 125)
Register.Position = UDim2.new(0.410484254, 0, 0.86956507, 0)
Register.Size = UDim2.new(0, 87, 0, 34)
Register.Font = Enum.Font.Gotham
Register.Text = "Register"
Register.TextColor3 = Color3.fromRGB(255, 255, 255)
Register.TextSize = 14.000
Login.Name = "Login"
Login.Parent = Frame
Login.BackgroundColor3 = Color3.fromRGB(81, 23, 255)
Login.BorderColor3 = Color3.fromRGB(125, 125, 125)
Login.Position = UDim2.new(0.700588644, 0, 0.86956507, 0)
Login.Size = UDim2.new(0, 90, 0, 34)
Login.Font = Enum.Font.Gotham
Login.Text = "Login"
Login.TextColor3 = Color3.fromRGB(255, 255, 255)
Login.TextSize = 14.000
Login.MouseButton1Down:connect(function()
if Password.Text == "trial" then
Main.Visible = false
Unlock.Visible = true
end
end)
Extra.Name = "Extra"
Extra.Parent = Frame
Extra.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
Extra.BackgroundTransparency = 1.000
Extra.Position = UDim2.new(0, 0, -0.102984495, 0)
Extra.Size = UDim2.new(0, 323, 0, 100)
Extra.Image = "http://www.roblox.com/asset/?id=5582792701"
Logo.Name = "Logo"
Logo.Parent = Extra
Logo.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
Logo.BackgroundTransparency = 1.000
Logo.BorderColor3 = Color3.fromRGB(27, 42, 53)
Logo.Position = UDim2.new(0.00919235777, 0, -0.361534715, 0)
Logo.Size = UDim2.new(0, 216, 0, 121)
Logo.Image = "http://www.roblox.com/asset/?id=5583032368"
Scripting.Name = "Scripting"
Scripting.Parent = Extra
Scripting.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
Scripting.BackgroundTransparency = 1.000
Scripting.Position = UDim2.new(0.0317897722, 0, 0.449392557, 0)
Scripting.Size = UDim2.new(0, 200, 0, 15)
Scripting.Font = Enum.Font.Gotham
Scripting.Text = "Let's get scripting."
Scripting.TextColor3 = Color3.fromRGB(255, 255, 255)
Scripting.TextSize = 22.000
Unlock.Name = "Unlock"
Unlock.Parent = Synapse
Unlock.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
Unlock.Position = UDim2.new(0.438489646, 0, 0.0531309284, 0)
Unlock.Size = UDim2.new(0, 173, 0, 403)
Unlock.Visible = false
Text.Name = "Text"
Text.Parent = Unlock
Text.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
Text.Size = UDim2.new(0, 173, 0, 403)
Text.Font = Enum.Font.SourceSans
Text.Text = "congrats u unlocked nothing still working on the executor lol"
Text.TextColor3 = Color3.fromRGB(0, 0, 0)
Text.TextSize = 14.000
Text.TextWrapped = true
local function FQDBZV_fake_script() -- Main.LocalScript
local script = Instance.new('LocalScript', Main)
local UIS = game:GetService("UserInputService")
function dragify(Frame)
dragToggle = nil
local dragSpeed = 5
dragInput = nil
dragStart = nil
local dragPos = nil
function updateInput(input)
local Delta = input.Position - dragStart
local Position = UDim2.new(startPos.X.Scale, startPos.X.Offset + Delta.X, startPos.Y.Scale, startPos.Y.Offset + Delta.Y)
game:GetService("TweenService"):Create(Frame, TweenInfo.new(1), {Position = Position}):Play()
end
Frame.InputBegan:Connect(function(input)
if (input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Touch) and UIS:GetFocusedTextBox() == nil then
dragToggle = true
dragStart = input.Position
startPos = Frame.Position
input.Changed:Connect(function()
if input.UserInputState == Enum.UserInputState.End then
dragToggle = false
end
end)
end
end)
Frame.InputChanged:Connect(function(input)
if input.UserInputType == Enum.UserInputType.MouseMovement or input.UserInputType == Enum.UserInputType.Touch then
dragInput = input
end
end)
game:GetService("UserInputService").InputChanged:Connect(function(input)
if input == dragInput and dragToggle then
updateInput(input)
end
end)
end
dragify(script.Parent)
end
coroutine.wrap(FQDBZV_fake_script)()
|
redis.replicate_commands()
local injected_time = tonumber(ARGV[1])
local redis_time = redis.call('time')
local local_time = redis_time[1] + 0.000001 * redis_time[2]
local now = injected_time or local_time
local current_bucket_levels = {}
local new_bucket_levels = {}
local timeouts = {}
local exceeded = false
for key_index, key in ipairs(KEYS) do
local arg_index = key_index * 5 - 3
local rate = tonumber(ARGV[arg_index])
local size = tonumber(ARGV[arg_index + 1])
local amount = tonumber(ARGV[arg_index + 2])
local bucket = redis.call('hmget', key, 'time', 'level')
local last_time = tonumber(bucket[1]) or now
local before_level = tonumber(bucket[2]) or size
local elapsed = math.max(0, now - last_time)
local gained = rate * elapsed
local current_level = math.min(size, before_level + gained)
current_bucket_levels[key_index] = current_level
if amount > 0 then
local limit = tonumber(ARGV[arg_index + 3]) or 0
local new_level = current_level - amount
local seconds_to_full = (size - new_level) / rate
timeouts[key_index] = seconds_to_full
if new_level < limit then
local allow_charge_adjustment = tonumber(ARGV[arg_index + 4]) or 0
if allow_charge_adjustment > 0 then
new_level = limit
else
exceeded = true
end
end
new_bucket_levels[key_index] = new_level
end
end
local levels_to_report
local charged
if exceeded or #new_bucket_levels == 0 then
levels_to_report = current_bucket_levels
charged = 0
else
levels_to_report = new_bucket_levels
charged = 1
for key_index, key in ipairs(KEYS) do
local new_level = new_bucket_levels[key_index]
local timeout = timeouts[key_index]
redis.call('hmset', key,
'time', string.format("%.16g", now),
'level', string.format("%.16g", new_level)
)
redis.call('expire', key, math.ceil(timeout))
end
end
local formatted_levels = {}
for index, value in ipairs(levels_to_report) do
formatted_levels[index] = string.format("%.16g", value)
end
return {charged, formatted_levels}
|
require("busted.runner")()
local logging = require("norn.logging")
describe("logging", function ()
describe("explode", function ()
it("should stringify empty table", function ()
local tbl = {}
local s = tostring(logging.explode(tbl))
assert.equals(s, "{}")
end)
it("should stringify a sequence", function ()
local tbl = { 2, 4, 6 }
local s = tostring(logging.explode(tbl))
assert.equals(s, [[{
[1] = 2
[2] = 4
[3] = 6
}]])
end)
it("should sort and quote string keys", function ()
local tbl = { foo = 5, bar = 10 }
local s = tostring(logging.explode(tbl))
assert.equals(s, [[{
["bar"] = 10
["foo"] = 5
}]])
end)
it("should quote string values", function ()
local tbl = { "foo", "bar" }
local s = tostring(logging.explode(tbl))
assert.equals(s, [[{
[1] = "foo"
[2] = "bar"
}]])
end)
it("should escape strings", function ()
local tbl = { ["foo'bar"] = 'fuzz"buzz' }
local s = tostring(logging.explode(tbl))
assert.equals(s, [[{
["foo'bar"] = "fuzz\"buzz"
}]])
end)
it("should explode nested tables", function ()
local tbl = {
[{ fuzz = "buzz" }] = { "foo", "bar" }
}
local s = tostring(logging.explode(tbl))
assert.equals(s, [[{
[{
["fuzz"] = "buzz"
}] = {
[1] = "foo"
[2] = "bar"
}
}]])
end)
it("should call custom __tostring", function ()
local a = setmetatable({}, {
__tostring = function (...)
return "a"
end
})
local b = setmetatable({}, {
__tostring = function (...)
return "b"
end
})
local tbl = { [a] = b }
local s = tostring(logging.explode(tbl))
assert.equals(s, [[{
[a] = b
}]])
end)
end)
end) |
---@class campingText
campingText = {};
-- menu text
campingText.placeCampfire = getText("ContextMenu_Build_a_fire");
campingText.addPetrol = getText("ContextMenu_Add_petrol");
campingText.lightCampfire = getText("ContextMenu_Light_fire");
campingText.addTent = getText("ContextMenu_Put_up_tent");
campingText.removeTent = getText("ContextMenu_Take_down_tent");
campingText.removeCampfire = getText("ContextMenu_Remove_fire");
campingText.putOutCampfire = getText("ContextMenu_Put_out_fire");
campingText.sleepInTent = getText("ContextMenu_Sleep_in_tent");
campingText.lightFromKindle = getText("ContextMenu_Light_fire_with_kindling");
campingText.addFuel = getText("ContextMenu_Add_fuel_to_fire");
|
--!strict
local Types = require(script.Parent.Parent.Types)
local spec: Types.Spec = function(practModule, describe)
local decorate = (require :: any)(practModule.decorate)
local Symbols = (require :: any)(practModule.Symbols)
describe('decorate', function(it)
it('Should create a Decorate element with empty props', function(expect)
local element = decorate()
expect.equal(Symbols.ElementKinds.Decorate, element[Symbols.ElementKind])
expect.deep_equal({}, element.props)
end)
it('Should accept props', function(expect)
local element = decorate({foo = 'Fighters'})
expect.equal(Symbols.ElementKinds.Decorate, element[Symbols.ElementKind])
expect.deep_equal({foo='Fighters'}, element.props)
end)
it('Should accept props and children', function(expect)
local element = decorate({foo = 'Fighters'}, {})
expect.equal(Symbols.ElementKinds.Decorate, element[Symbols.ElementKind])
expect.deep_equal({foo='Fighters', [Symbols.Children] = {}}, element.props)
end)
it('Should accept children without props', function(expect)
local element = decorate(nil, {})
expect.equal(Symbols.ElementKinds.Decorate, element[Symbols.ElementKind])
expect.deep_equal({[Symbols.Children] = {}}, element.props)
end)
it('Should accept read-only props with no children argument', function(expect)
local props = {}
table.freeze(props)
local element = decorate(props)
expect.equal(Symbols.ElementKinds.Decorate, element[Symbols.ElementKind])
expect.equal(props, element.props)
end)
end)
end
return spec |
local source = {}
local cmp = require('cmp')
source.new = function()
local self = setmetatable({}, { __index = source })
self.items = nil
return self
end
source.get_trigger_characters = function()
return {
'Ex',
'In',
'As',
'Li',
'Eq',
'E:',
'I:',
'A:',
'L:',
}
end
local ltrim = function(s)
return s:match('^%s*(.*)')
end
local get_items = function(account_path)
-- improved version is based on https://github.com/nathangrigg/vim-beancount/blob/master/autoload/beancount.vim
vim.api.nvim_exec(
string.format(
[[python3 <<EOB
from beancount.loader import load_file
from beancount.core import data
accounts = set()
entries, _, _ = load_file('%s')
for index, entry in enumerate(entries):
if isinstance(entry, data.Open):
accounts.add(entry.account)
vim.command('let b:beancount_accounts = [{}]'.format(','.join(repr(x) for x in sorted(accounts))))
EOB]],
account_path
),
true
)
local items = {}
for _, s in ipairs(vim.b.beancount_accounts) do
table.insert(items, {
label = s,
kind = cmp.lsp.CompletionItemKind.Property,
})
end
return items
end
local split_accounts = function(str)
local sep = ':'
local t = {}
for s in string.gmatch(str, '([^' .. sep .. ']+)') do
table.insert(t, s)
end
return t
end
source.complete = function(self, request, callback)
if vim.bo.filetype ~= 'beancount' then
callback()
return
end
local account_path = request.option.account
if account_path == nil or not vim.fn.filereadable(account_path) then
vim.api.nvim_echo({
{ 'cmp_beancount', 'ErrorMsg' },
{ ' ' .. 'Accounts file is not set' },
}, true, {})
callback()
return
end
if not self.items then
self.items = get_items(request.option.account)
end
local prefix_mode = false
local input = ltrim(request.context.cursor_before_line):lower()
local prefixes = split_accounts(input)
local pattern = ''
for i, prefix in ipairs(prefixes) do
if i == 1 then
pattern = string.format('%s%%a*', prefix:lower())
else
pattern = string.format('%s:%s%%a*', pattern, prefix:lower())
end
end
if #prefixes > 1 and pattern ~= '' then
prefix_mode = true
end
local items = {}
local count = 0
for _, item in ipairs(self.items) do
if prefix_mode then
if string.match(item.label:lower(), pattern) then
table.insert(items, {
word = item.label,
label = item.label,
kind = item.kind,
textEdit = {
filterText = input,
newText = item.label,
range = {
start = {
line = request.context.cursor.row - 1,
character = request.offset - string.len(input),
},
['end'] = {
line = request.context.cursor.row - 1,
character = request.context.cursor.col - 1,
},
},
},
})
count = count + 1
end
else
if vim.startswith(item.label:lower(), input) then
table.insert(items, item)
count = count + 1
end
end
if count >= 10 then
break
end
end
callback(items)
end
return source
|
components = {}
toLoad = recursiveEnumerate("components")
for _, path in ipairs(toLoad) do
if path:sub(-3) == "lua" then
-- clean up the string
path = path:gsub("/", ".") -- replace / with .
path = path:sub(1, -5) -- remove .lua
name = path:sub(12) -- really?
components[name] = require(path) -- sandbox this?
assert(type(components[name]) == "table", string.format("Component \"%s\" didn't return a table.", name))
end
end
|
--------------------------------
-- @module LayerColor
-- @extend Layer,BlendProtocol
-- @parent_module cc
--------------------------------
-- change width and height in Points<br>
-- since v0.8
-- @function [parent=#LayerColor] changeWidthAndHeight
-- @param self
-- @param #float w
-- @param #float h
--------------------------------
-- change height in Points
-- @function [parent=#LayerColor] changeHeight
-- @param self
-- @param #float h
--------------------------------
-- change width in Points
-- @function [parent=#LayerColor] changeWidth
-- @param self
-- @param #float w
--------------------------------
-- @overload self, color4b_table, float, float
-- @overload self
-- @overload self, color4b_table
-- @function [parent=#LayerColor] create
-- @param self
-- @param #color4b_table color
-- @param #float width
-- @param #float height
-- @return LayerColor#LayerColor ret (return value: cc.LayerColor)
--------------------------------
--
-- @function [parent=#LayerColor] draw
-- @param self
-- @param #cc.Renderer renderer
-- @param #mat4_table transform
-- @param #unsigned int flags
--------------------------------
--
-- @function [parent=#LayerColor] getDescription
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
--
-- @function [parent=#LayerColor] setContentSize
-- @param self
-- @param #size_table var
return nil
|
local args = ...;
local ac = args.PiroGame.class('AudioComponent', args.PiroGame.Component);
function ac:initialize(file, t, id)
args.PiroGame.Component.initialize(self, id);
self.file = file;
self.type = t;
end
function ac:activate()
-- print('AudioComponent', self, self.id, 'activation. For', self.entity, self.entity.id);
if (self.file ~= nil) then
self.source = love.audio.newSource(self.file, self.type);
-- print('Created source:', self.source, '(', type(self.source), ')');
end
end
function ac:deactivate()
self.source = nil;
end
function ac:play()
if self.source ~= nil then
self.source:play();
end
end
return ac;
|
JASS_MAX_ARRAY_SIZE = 8192
PLAYER_NEUTRAL_PASSIVE = 15
PLAYER_NEUTRAL_AGGRESSIVE = 12
PLAYER_COLOR_RED = cj.ConvertPlayerColor(0)
PLAYER_COLOR_BLUE = cj.ConvertPlayerColor(1)
PLAYER_COLOR_CYAN = cj.ConvertPlayerColor(2)
PLAYER_COLOR_PURPLE = cj.ConvertPlayerColor(3)
PLAYER_COLOR_YELLOW = cj.ConvertPlayerColor(4)
PLAYER_COLOR_ORANGE = cj.ConvertPlayerColor(5)
PLAYER_COLOR_GREEN = cj.ConvertPlayerColor(6)
PLAYER_COLOR_PINK = cj.ConvertPlayerColor(7)
PLAYER_COLOR_LIGHT_GRAY = cj.ConvertPlayerColor(8)
PLAYER_COLOR_LIGHT_BLUE = cj.ConvertPlayerColor(9)
PLAYER_COLOR_AQUA = cj.ConvertPlayerColor(10)
PLAYER_COLOR_BROWN = cj.ConvertPlayerColor(11)
RACE_HUMAN = cj.ConvertRace(1)
RACE_ORC = cj.ConvertRace(2)
RACE_UNDEAD = cj.ConvertRace(3)
RACE_NIGHTELF = cj.ConvertRace(4)
RACE_DEMON = cj.ConvertRace(5)
RACE_OTHER = cj.ConvertRace(7)
PLAYER_GAME_RESULT_VICTORY = cj.ConvertPlayerGameResult(0)
PLAYER_GAME_RESULT_DEFEAT = cj.ConvertPlayerGameResult(1)
PLAYER_GAME_RESULT_TIE = cj.ConvertPlayerGameResult(2)
PLAYER_GAME_RESULT_NEUTRAL = cj.ConvertPlayerGameResult(3)
ALLIANCE_PASSIVE = cj.ConvertAllianceType(0)
ALLIANCE_HELP_REQUEST = cj.ConvertAllianceType(1)
ALLIANCE_HELP_RESPONSE = cj.ConvertAllianceType(2)
ALLIANCE_SHARED_XP = cj.ConvertAllianceType(3)
ALLIANCE_SHARED_SPELLS = cj.ConvertAllianceType(4)
ALLIANCE_SHARED_VISION = cj.ConvertAllianceType(5)
ALLIANCE_SHARED_CONTROL = cj.ConvertAllianceType(6)
ALLIANCE_SHARED_ADVANCED_CONTROL = cj.ConvertAllianceType(7)
ALLIANCE_RESCUABLE = cj.ConvertAllianceType(8)
ALLIANCE_SHARED_VISION_FORCED = cj.ConvertAllianceType(9)
VERSION_REIGN_OF_CHAOS = cj.ConvertVersion(0)
VERSION_FROZEN_THRONE = cj.ConvertVersion(1)
ATTACK_TYPE_NORMAL = cj.ConvertAttackType(0)
ATTACK_TYPE_MELEE = cj.ConvertAttackType(1)
ATTACK_TYPE_PIERCE = cj.ConvertAttackType(2)
ATTACK_TYPE_SIEGE = cj.ConvertAttackType(3)
ATTACK_TYPE_MAGIC = cj.ConvertAttackType(4)
ATTACK_TYPE_CHAOS = cj.ConvertAttackType(5)
ATTACK_TYPE_HERO = cj.ConvertAttackType(6)
DAMAGE_TYPE_UNKNOWN = cj.ConvertDamageType(0)
DAMAGE_TYPE_NORMAL = cj.ConvertDamageType(4)
DAMAGE_TYPE_ENHANCED = cj.ConvertDamageType(5)
DAMAGE_TYPE_FIRE = cj.ConvertDamageType(8)
DAMAGE_TYPE_COLD = cj.ConvertDamageType(9)
DAMAGE_TYPE_LIGHTNING = cj.ConvertDamageType(10)
DAMAGE_TYPE_POISON = cj.ConvertDamageType(11)
DAMAGE_TYPE_DISEASE = cj.ConvertDamageType(12)
DAMAGE_TYPE_DIVINE = cj.ConvertDamageType(13)
DAMAGE_TYPE_MAGIC = cj.ConvertDamageType(14)
DAMAGE_TYPE_SONIC = cj.ConvertDamageType(15)
DAMAGE_TYPE_ACID = cj.ConvertDamageType(16)
DAMAGE_TYPE_FORCE = cj.ConvertDamageType(17)
DAMAGE_TYPE_DEATH = cj.ConvertDamageType(18)
DAMAGE_TYPE_MIND = cj.ConvertDamageType(19)
DAMAGE_TYPE_PLANT = cj.ConvertDamageType(20)
DAMAGE_TYPE_DEFENSIVE = cj.ConvertDamageType(21)
DAMAGE_TYPE_DEMOLITION = cj.ConvertDamageType(22)
DAMAGE_TYPE_SLOW_POISON = cj.ConvertDamageType(23)
DAMAGE_TYPE_SPIRIT_LINK = cj.ConvertDamageType(24)
DAMAGE_TYPE_SHADOW_STRIKE = cj.ConvertDamageType(25)
DAMAGE_TYPE_UNIVERSAL = cj.ConvertDamageType(26)
WEAPON_TYPE_WHOKNOWS = cj.ConvertWeaponType(0)
WEAPON_TYPE_METAL_LIGHT_CHOP = cj.ConvertWeaponType(1)
WEAPON_TYPE_METAL_MEDIUM_CHOP = cj.ConvertWeaponType(2)
WEAPON_TYPE_METAL_HEAVY_CHOP = cj.ConvertWeaponType(3)
WEAPON_TYPE_METAL_LIGHT_SLICE = cj.ConvertWeaponType(4)
WEAPON_TYPE_METAL_MEDIUM_SLICE = cj.ConvertWeaponType(5)
WEAPON_TYPE_METAL_HEAVY_SLICE = cj.ConvertWeaponType(6)
WEAPON_TYPE_METAL_MEDIUM_BASH = cj.ConvertWeaponType(7)
WEAPON_TYPE_METAL_HEAVY_BASH = cj.ConvertWeaponType(8)
WEAPON_TYPE_METAL_MEDIUM_STAB = cj.ConvertWeaponType(9)
WEAPON_TYPE_METAL_HEAVY_STAB = cj.ConvertWeaponType(10)
WEAPON_TYPE_WOOD_LIGHT_SLICE = cj.ConvertWeaponType(11)
WEAPON_TYPE_WOOD_MEDIUM_SLICE = cj.ConvertWeaponType(12)
WEAPON_TYPE_WOOD_HEAVY_SLICE = cj.ConvertWeaponType(13)
WEAPON_TYPE_WOOD_LIGHT_BASH = cj.ConvertWeaponType(14)
WEAPON_TYPE_WOOD_MEDIUM_BASH = cj.ConvertWeaponType(15)
WEAPON_TYPE_WOOD_HEAVY_BASH = cj.ConvertWeaponType(16)
WEAPON_TYPE_WOOD_LIGHT_STAB = cj.ConvertWeaponType(17)
WEAPON_TYPE_WOOD_MEDIUM_STAB = cj.ConvertWeaponType(18)
WEAPON_TYPE_CLAW_LIGHT_SLICE = cj.ConvertWeaponType(19)
WEAPON_TYPE_CLAW_MEDIUM_SLICE = cj.ConvertWeaponType(20)
WEAPON_TYPE_CLAW_HEAVY_SLICE = cj.ConvertWeaponType(21)
WEAPON_TYPE_AXE_MEDIUM_CHOP = cj.ConvertWeaponType(22)
WEAPON_TYPE_ROCK_HEAVY_BASH = cj.ConvertWeaponType(23)
PATHING_TYPE_ANY = cj.ConvertPathingType(0)
PATHING_TYPE_WALKABILITY = cj.ConvertPathingType(1)
PATHING_TYPE_FLYABILITY = cj.ConvertPathingType(2)
PATHING_TYPE_BUILDABILITY = cj.ConvertPathingType(3)
PATHING_TYPE_PEONHARVESTPATHING = cj.ConvertPathingType(4)
PATHING_TYPE_BLIGHTPATHING = cj.ConvertPathingType(5)
PATHING_TYPE_FLOATABILITY = cj.ConvertPathingType(6)
PATHING_TYPE_AMPHIBIOUSPATHING = cj.ConvertPathingType(7)
RACE_PREF_HUMAN = cj.ConvertRacePref(1)
RACE_PREF_ORC = cj.ConvertRacePref(2)
RACE_PREF_NIGHTELF = cj.ConvertRacePref(4)
RACE_PREF_UNDEAD = cj.ConvertRacePref(8)
RACE_PREF_DEMON = cj.ConvertRacePref(16)
RACE_PREF_RANDOM = cj.ConvertRacePref(32)
RACE_PREF_USER_SELECTABLE = cj.ConvertRacePref(64)
MAP_CONTROL_USER = cj.ConvertMapControl(0)
MAP_CONTROL_COMPUTER = cj.ConvertMapControl(1)
MAP_CONTROL_RESCUABLE = cj.ConvertMapControl(2)
MAP_CONTROL_NEUTRAL = cj.ConvertMapControl(3)
MAP_CONTROL_CREEP = cj.ConvertMapControl(4)
MAP_CONTROL_NONE = cj.ConvertMapControl(5)
GAME_TYPE_MELEE = cj.ConvertGameType(1)
GAME_TYPE_FFA = cj.ConvertGameType(2)
GAME_TYPE_USE_MAP_SETTINGS = cj.ConvertGameType(4)
GAME_TYPE_BLIZ = cj.ConvertGameType(8)
GAME_TYPE_ONE_ON_ONE = cj.ConvertGameType(16)
GAME_TYPE_TWO_TEAM_PLAY = cj.ConvertGameType(32)
GAME_TYPE_THREE_TEAM_PLAY = cj.ConvertGameType(64)
GAME_TYPE_FOUR_TEAM_PLAY = cj.ConvertGameType(128)
MAP_FOG_HIDE_TERRAIN = cj.ConvertMapFlag(1)
MAP_FOG_MAP_EXPLORED = cj.ConvertMapFlag(2)
MAP_FOG_ALWAYS_VISIBLE = cj.ConvertMapFlag(4)
MAP_USE_HANDICAPS = cj.ConvertMapFlag(8)
MAP_OBSERVERS = cj.ConvertMapFlag(16)
MAP_OBSERVERS_ON_DEATH = cj.ConvertMapFlag(32)
MAP_FIXED_COLORS = cj.ConvertMapFlag(128)
MAP_LOCK_RESOURCE_TRADING = cj.ConvertMapFlag(256)
MAP_RESOURCE_TRADING_ALLIES_ONLY = cj.ConvertMapFlag(512)
MAP_LOCK_ALLIANCE_CHANGES = cj.ConvertMapFlag(1024)
MAP_ALLIANCE_CHANGES_HIDDEN = cj.ConvertMapFlag(2048)
MAP_CHEATS = cj.ConvertMapFlag(4096)
MAP_CHEATS_HIDDEN = cj.ConvertMapFlag(8192)
MAP_LOCK_SPEED = cj.ConvertMapFlag(8192 * 2)
MAP_LOCK_RANDOM_SEED = cj.ConvertMapFlag(8192 * 4)
MAP_SHARED_ADVANCED_CONTROL = cj.ConvertMapFlag(8192 * 8)
MAP_RANDOM_HERO = cj.ConvertMapFlag(8192 * 16)
MAP_RANDOM_RACES = cj.ConvertMapFlag(8192 * 32)
MAP_RELOADED = cj.ConvertMapFlag(8192 * 64)
MAP_PLACEMENT_RANDOM = cj.ConvertPlacement(0)
MAP_PLACEMENT_FIXED = cj.ConvertPlacement(1)
MAP_PLACEMENT_USE_MAP_SETTINGS = cj.ConvertPlacement(2)
MAP_PLACEMENT_TEAMS_TOGETHER = cj.ConvertPlacement(3)
MAP_LOC_PRIO_LOW = cj.ConvertStartLocPrio(0)
MAP_LOC_PRIO_HIGH = cj.ConvertStartLocPrio(1)
MAP_LOC_PRIO_NOT = cj.ConvertStartLocPrio(2)
MAP_DENSITY_NONE = cj.ConvertMapDensity(0)
MAP_DENSITY_LIGHT = cj.ConvertMapDensity(1)
MAP_DENSITY_MEDIUM = cj.ConvertMapDensity(2)
MAP_DENSITY_HEAVY = cj.ConvertMapDensity(3)
MAP_DIFFICULTY_EASY = cj.ConvertGameDifficulty(0)
MAP_DIFFICULTY_NORMAL = cj.ConvertGameDifficulty(1)
MAP_DIFFICULTY_HARD = cj.ConvertGameDifficulty(2)
MAP_DIFFICULTY_INSANE = cj.ConvertGameDifficulty(3)
MAP_SPEED_SLOWEST = cj.ConvertGameSpeed(0)
MAP_SPEED_SLOW = cj.ConvertGameSpeed(1)
MAP_SPEED_NORMAL = cj.ConvertGameSpeed(2)
MAP_SPEED_FAST = cj.ConvertGameSpeed(3)
MAP_SPEED_FASTEST = cj.ConvertGameSpeed(4)
PLAYER_SLOT_STATE_EMPTY = cj.ConvertPlayerSlotState(0)
PLAYER_SLOT_STATE_PLAYING = cj.ConvertPlayerSlotState(1)
PLAYER_SLOT_STATE_LEFT = cj.ConvertPlayerSlotState(2)
SOUND_VOLUMEGROUP_UNITMOVEMENT = cj.ConvertVolumeGroup(0)
SOUND_VOLUMEGROUP_UNITSOUNDS = cj.ConvertVolumeGroup(1)
SOUND_VOLUMEGROUP_COMBAT = cj.ConvertVolumeGroup(2)
SOUND_VOLUMEGROUP_SPELLS = cj.ConvertVolumeGroup(3)
SOUND_VOLUMEGROUP_UI = cj.ConvertVolumeGroup(4)
SOUND_VOLUMEGROUP_MUSIC = cj.ConvertVolumeGroup(5)
SOUND_VOLUMEGROUP_AMBIENTSOUNDS = cj.ConvertVolumeGroup(6)
SOUND_VOLUMEGROUP_FIRE = cj.ConvertVolumeGroup(7)
GAME_STATE_DIVINE_INTERVENTION = cj.ConvertIGameState(0)
GAME_STATE_DISCONNECTED = cj.ConvertIGameState(1)
GAME_STATE_TIME_OF_DAY = cj.ConvertFGameState(2)
PLAYER_STATE_GAME_RESULT = cj.ConvertPlayerState(0)
PLAYER_STATE_RESOURCE_GOLD = cj.ConvertPlayerState(1)
PLAYER_STATE_RESOURCE_LUMBER = cj.ConvertPlayerState(2)
PLAYER_STATE_RESOURCE_HERO_TOKENS = cj.ConvertPlayerState(3)
PLAYER_STATE_RESOURCE_FOOD_CAP = cj.ConvertPlayerState(4)
PLAYER_STATE_RESOURCE_FOOD_USED = cj.ConvertPlayerState(5)
PLAYER_STATE_FOOD_CAP_CEILING = cj.ConvertPlayerState(6)
PLAYER_STATE_GIVES_BOUNTY = cj.ConvertPlayerState(7)
PLAYER_STATE_ALLIED_VICTORY = cj.ConvertPlayerState(8)
PLAYER_STATE_PLACED = cj.ConvertPlayerState(9)
PLAYER_STATE_OBSERVER_ON_DEATH = cj.ConvertPlayerState(10)
PLAYER_STATE_OBSERVER = cj.ConvertPlayerState(11)
PLAYER_STATE_UNFOLLOWABLE = cj.ConvertPlayerState(12)
PLAYER_STATE_GOLD_UPKEEP_RATE = cj.ConvertPlayerState(13)
PLAYER_STATE_LUMBER_UPKEEP_RATE = cj.ConvertPlayerState(14)
PLAYER_STATE_GOLD_GATHERED = cj.ConvertPlayerState(15)
PLAYER_STATE_LUMBER_GATHERED = cj.ConvertPlayerState(16)
PLAYER_STATE_NO_CREEP_SLEEP = cj.ConvertPlayerState(25)
UNIT_STATE_LIFE = cj.ConvertUnitState(0)
UNIT_STATE_MAX_LIFE = cj.ConvertUnitState(1)
UNIT_STATE_MANA = cj.ConvertUnitState(2)
UNIT_STATE_MAX_MANA = cj.ConvertUnitState(3)
AI_DIFFICULTY_NEWBIE = cj.ConvertAIDifficulty(0)
AI_DIFFICULTY_NORMAL = cj.ConvertAIDifficulty(1)
AI_DIFFICULTY_INSANE = cj.ConvertAIDifficulty(2)
PLAYER_SCORE_UNITS_TRAINED = cj.ConvertPlayerScore(0)
PLAYER_SCORE_UNITS_KILLED = cj.ConvertPlayerScore(1)
PLAYER_SCORE_STRUCT_BUILT = cj.ConvertPlayerScore(2)
PLAYER_SCORE_STRUCT_RAZED = cj.ConvertPlayerScore(3)
PLAYER_SCORE_TECH_PERCENT = cj.ConvertPlayerScore(4)
PLAYER_SCORE_FOOD_MAXPROD = cj.ConvertPlayerScore(5)
PLAYER_SCORE_FOOD_MAXUSED = cj.ConvertPlayerScore(6)
PLAYER_SCORE_HEROES_KILLED = cj.ConvertPlayerScore(7)
PLAYER_SCORE_ITEMS_GAINED = cj.ConvertPlayerScore(8)
PLAYER_SCORE_MERCS_HIRED = cj.ConvertPlayerScore(9)
PLAYER_SCORE_GOLD_MINED_TOTAL = cj.ConvertPlayerScore(10)
PLAYER_SCORE_GOLD_MINED_UPKEEP = cj.ConvertPlayerScore(11)
PLAYER_SCORE_GOLD_LOST_UPKEEP = cj.ConvertPlayerScore(12)
PLAYER_SCORE_GOLD_LOST_TAX = cj.ConvertPlayerScore(13)
PLAYER_SCORE_GOLD_GIVEN = cj.ConvertPlayerScore(14)
PLAYER_SCORE_GOLD_RECEIVED = cj.ConvertPlayerScore(15)
PLAYER_SCORE_LUMBER_TOTAL = cj.ConvertPlayerScore(16)
PLAYER_SCORE_LUMBER_LOST_UPKEEP = cj.ConvertPlayerScore(17)
PLAYER_SCORE_LUMBER_LOST_TAX = cj.ConvertPlayerScore(18)
PLAYER_SCORE_LUMBER_GIVEN = cj.ConvertPlayerScore(19)
PLAYER_SCORE_LUMBER_RECEIVED = cj.ConvertPlayerScore(20)
PLAYER_SCORE_UNIT_TOTAL = cj.ConvertPlayerScore(21)
PLAYER_SCORE_HERO_TOTAL = cj.ConvertPlayerScore(22)
PLAYER_SCORE_RESOURCE_TOTAL = cj.ConvertPlayerScore(23)
PLAYER_SCORE_TOTAL = cj.ConvertPlayerScore(24)
EVENT_GAME_VICTORY = cj.ConvertGameEvent(0)
EVENT_GAME_END_LEVEL = cj.ConvertGameEvent(1)
EVENT_GAME_VARIABLE_LIMIT = cj.ConvertGameEvent(2)
EVENT_GAME_STATE_LIMIT = cj.ConvertGameEvent(3)
EVENT_GAME_TIMER_EXPIRED = cj.ConvertGameEvent(4)
EVENT_GAME_ENTER_REGION = cj.ConvertGameEvent(5)
EVENT_GAME_LEAVE_REGION = cj.ConvertGameEvent(6)
EVENT_GAME_TRACKABLE_HIT = cj.ConvertGameEvent(7)
EVENT_GAME_TRACKABLE_TRACK = cj.ConvertGameEvent(8)
EVENT_GAME_SHOW_SKILL = cj.ConvertGameEvent(9)
EVENT_GAME_BUILD_SUBMENU = cj.ConvertGameEvent(10)
EVENT_PLAYER_STATE_LIMIT = cj.ConvertPlayerEvent(11)
EVENT_PLAYER_ALLIANCE_CHANGED = cj.ConvertPlayerEvent(12)
EVENT_PLAYER_DEFEAT = cj.ConvertPlayerEvent(13)
EVENT_PLAYER_VICTORY = cj.ConvertPlayerEvent(14)
EVENT_PLAYER_LEAVE = cj.ConvertPlayerEvent(15)
EVENT_PLAYER_CHAT = cj.ConvertPlayerEvent(16)
EVENT_PLAYER_END_CINEMATIC = cj.ConvertPlayerEvent(17)
EVENT_PLAYER_UNIT_ATTACKED = cj.ConvertPlayerUnitEvent(18)
EVENT_PLAYER_UNIT_RESCUED = cj.ConvertPlayerUnitEvent(19)
EVENT_PLAYER_UNIT_DEATH = cj.ConvertPlayerUnitEvent(20)
EVENT_PLAYER_UNIT_DECAY = cj.ConvertPlayerUnitEvent(21)
EVENT_PLAYER_UNIT_DETECTED = cj.ConvertPlayerUnitEvent(22)
EVENT_PLAYER_UNIT_HIDDEN = cj.ConvertPlayerUnitEvent(23)
EVENT_PLAYER_UNIT_SELECTED = cj.ConvertPlayerUnitEvent(24)
EVENT_PLAYER_UNIT_DESELECTED = cj.ConvertPlayerUnitEvent(25)
EVENT_PLAYER_UNIT_CONSTRUCT_START = cj.ConvertPlayerUnitEvent(26)
EVENT_PLAYER_UNIT_CONSTRUCT_CANCEL = cj.ConvertPlayerUnitEvent(27)
EVENT_PLAYER_UNIT_CONSTRUCT_FINISH = cj.ConvertPlayerUnitEvent(28)
EVENT_PLAYER_UNIT_UPGRADE_START = cj.ConvertPlayerUnitEvent(29)
EVENT_PLAYER_UNIT_UPGRADE_CANCEL = cj.ConvertPlayerUnitEvent(30)
EVENT_PLAYER_UNIT_UPGRADE_FINISH = cj.ConvertPlayerUnitEvent(31)
EVENT_PLAYER_UNIT_TRAIN_START = cj.ConvertPlayerUnitEvent(32)
EVENT_PLAYER_UNIT_TRAIN_CANCEL = cj.ConvertPlayerUnitEvent(33)
EVENT_PLAYER_UNIT_TRAIN_FINISH = cj.ConvertPlayerUnitEvent(34)
EVENT_PLAYER_UNIT_RESEARCH_START = cj.ConvertPlayerUnitEvent(35)
EVENT_PLAYER_UNIT_RESEARCH_CANCEL = cj.ConvertPlayerUnitEvent(36)
EVENT_PLAYER_UNIT_RESEARCH_FINISH = cj.ConvertPlayerUnitEvent(37)
EVENT_PLAYER_UNIT_ISSUED_ORDER = cj.ConvertPlayerUnitEvent(38)
EVENT_PLAYER_UNIT_ISSUED_POINT_ORDER = cj.ConvertPlayerUnitEvent(39)
EVENT_PLAYER_UNIT_ISSUED_TARGET_ORDER = cj.ConvertPlayerUnitEvent(40)
EVENT_PLAYER_UNIT_ISSUED_UNIT_ORDER = cj.ConvertPlayerUnitEvent(40)
EVENT_PLAYER_HERO_LEVEL = cj.ConvertPlayerUnitEvent(41)
EVENT_PLAYER_HERO_SKILL = cj.ConvertPlayerUnitEvent(42)
EVENT_PLAYER_HERO_REVIVABLE = cj.ConvertPlayerUnitEvent(43)
EVENT_PLAYER_HERO_REVIVE_START = cj.ConvertPlayerUnitEvent(44)
EVENT_PLAYER_HERO_REVIVE_CANCEL = cj.ConvertPlayerUnitEvent(45)
EVENT_PLAYER_HERO_REVIVE_FINISH = cj.ConvertPlayerUnitEvent(46)
EVENT_PLAYER_UNIT_SUMMON = cj.ConvertPlayerUnitEvent(47)
EVENT_PLAYER_UNIT_DROP_ITEM = cj.ConvertPlayerUnitEvent(48)
EVENT_PLAYER_UNIT_PICKUP_ITEM = cj.ConvertPlayerUnitEvent(49)
EVENT_PLAYER_UNIT_USE_ITEM = cj.ConvertPlayerUnitEvent(50)
EVENT_PLAYER_UNIT_LOADED = cj.ConvertPlayerUnitEvent(51)
EVENT_UNIT_DAMAGED = cj.ConvertUnitEvent(52)
EVENT_UNIT_DEATH = cj.ConvertUnitEvent(53)
EVENT_UNIT_DECAY = cj.ConvertUnitEvent(54)
EVENT_UNIT_DETECTED = cj.ConvertUnitEvent(55)
EVENT_UNIT_HIDDEN = cj.ConvertUnitEvent(56)
EVENT_UNIT_SELECTED = cj.ConvertUnitEvent(57)
EVENT_UNIT_DESELECTED = cj.ConvertUnitEvent(58)
EVENT_UNIT_STATE_LIMIT = cj.ConvertUnitEvent(59)
EVENT_UNIT_ACQUIRED_TARGET = cj.ConvertUnitEvent(60)
EVENT_UNIT_TARGET_IN_RANGE = cj.ConvertUnitEvent(61)
EVENT_UNIT_ATTACKED = cj.ConvertUnitEvent(62)
EVENT_UNIT_RESCUED = cj.ConvertUnitEvent(63)
EVENT_UNIT_CONSTRUCT_CANCEL = cj.ConvertUnitEvent(64)
EVENT_UNIT_CONSTRUCT_FINISH = cj.ConvertUnitEvent(65)
EVENT_UNIT_UPGRADE_START = cj.ConvertUnitEvent(66)
EVENT_UNIT_UPGRADE_CANCEL = cj.ConvertUnitEvent(67)
EVENT_UNIT_UPGRADE_FINISH = cj.ConvertUnitEvent(68)
EVENT_UNIT_TRAIN_START = cj.ConvertUnitEvent(69)
EVENT_UNIT_TRAIN_CANCEL = cj.ConvertUnitEvent(70)
EVENT_UNIT_TRAIN_FINISH = cj.ConvertUnitEvent(71)
EVENT_UNIT_RESEARCH_START = cj.ConvertUnitEvent(72)
EVENT_UNIT_RESEARCH_CANCEL = cj.ConvertUnitEvent(73)
EVENT_UNIT_RESEARCH_FINISH = cj.ConvertUnitEvent(74)
EVENT_UNIT_ISSUED_ORDER = cj.ConvertUnitEvent(75)
EVENT_UNIT_ISSUED_POINT_ORDER = cj.ConvertUnitEvent(76)
EVENT_UNIT_ISSUED_TARGET_ORDER = cj.ConvertUnitEvent(77)
EVENT_UNIT_HERO_LEVEL = cj.ConvertUnitEvent(78)
EVENT_UNIT_HERO_SKILL = cj.ConvertUnitEvent(79)
EVENT_UNIT_HERO_REVIVABLE = cj.ConvertUnitEvent(80)
EVENT_UNIT_HERO_REVIVE_START = cj.ConvertUnitEvent(81)
EVENT_UNIT_HERO_REVIVE_CANCEL = cj.ConvertUnitEvent(82)
EVENT_UNIT_HERO_REVIVE_FINISH = cj.ConvertUnitEvent(83)
EVENT_UNIT_SUMMON = cj.ConvertUnitEvent(84)
EVENT_UNIT_DROP_ITEM = cj.ConvertUnitEvent(85)
EVENT_UNIT_PICKUP_ITEM = cj.ConvertUnitEvent(86)
EVENT_UNIT_USE_ITEM = cj.ConvertUnitEvent(87)
EVENT_UNIT_LOADED = cj.ConvertUnitEvent(88)
EVENT_WIDGET_DEATH = cj.ConvertWidgetEvent(89)
EVENT_DIALOG_BUTTON_CLICK = cj.ConvertDialogEvent(90)
EVENT_DIALOG_CLICK = cj.ConvertDialogEvent(91)
EVENT_GAME_LOADED = cj.ConvertGameEvent(256)
EVENT_GAME_TOURNAMENT_FINISH_SOON = cj.ConvertGameEvent(257)
EVENT_GAME_TOURNAMENT_FINISH_NOW = cj.ConvertGameEvent(258)
EVENT_GAME_SAVE = cj.ConvertGameEvent(259)
EVENT_PLAYER_ARROW_LEFT_DOWN = cj.ConvertPlayerEvent(261)
EVENT_PLAYER_ARROW_LEFT_UP = cj.ConvertPlayerEvent(262)
EVENT_PLAYER_ARROW_RIGHT_DOWN = cj.ConvertPlayerEvent(263)
EVENT_PLAYER_ARROW_RIGHT_UP = cj.ConvertPlayerEvent(264)
EVENT_PLAYER_ARROW_DOWN_DOWN = cj.ConvertPlayerEvent(265)
EVENT_PLAYER_ARROW_DOWN_UP = cj.ConvertPlayerEvent(266)
EVENT_PLAYER_ARROW_UP_DOWN = cj.ConvertPlayerEvent(267)
EVENT_PLAYER_ARROW_UP_UP = cj.ConvertPlayerEvent(268)
EVENT_PLAYER_UNIT_SELL = cj.ConvertPlayerUnitEvent(269)
EVENT_PLAYER_UNIT_CHANGE_OWNER = cj.ConvertPlayerUnitEvent(270)
EVENT_PLAYER_UNIT_SELL_ITEM = cj.ConvertPlayerUnitEvent(271)
EVENT_PLAYER_UNIT_SPELL_CHANNEL = cj.ConvertPlayerUnitEvent(272)
EVENT_PLAYER_UNIT_SPELL_CAST = cj.ConvertPlayerUnitEvent(273)
EVENT_PLAYER_UNIT_SPELL_EFFECT = cj.ConvertPlayerUnitEvent(274)
EVENT_PLAYER_UNIT_SPELL_FINISH = cj.ConvertPlayerUnitEvent(275)
EVENT_PLAYER_UNIT_SPELL_ENDCAST = cj.ConvertPlayerUnitEvent(276)
EVENT_PLAYER_UNIT_PAWN_ITEM = cj.ConvertPlayerUnitEvent(277)
EVENT_UNIT_SELL = cj.ConvertUnitEvent(286)
EVENT_UNIT_CHANGE_OWNER = cj.ConvertUnitEvent(287)
EVENT_UNIT_SELL_ITEM = cj.ConvertUnitEvent(288)
EVENT_UNIT_SPELL_CHANNEL = cj.ConvertUnitEvent(289)
EVENT_UNIT_SPELL_CAST = cj.ConvertUnitEvent(290)
EVENT_UNIT_SPELL_EFFECT = cj.ConvertUnitEvent(291)
EVENT_UNIT_SPELL_FINISH = cj.ConvertUnitEvent(292)
EVENT_UNIT_SPELL_ENDCAST = cj.ConvertUnitEvent(293)
EVENT_UNIT_PAWN_ITEM = cj.ConvertUnitEvent(294)
LESS_THAN = cj.ConvertLimitOp(0)
LESS_THAN_OR_EQUAL = cj.ConvertLimitOp(1)
EQUAL = cj.ConvertLimitOp(2)
GREATER_THAN_OR_EQUAL = cj.ConvertLimitOp(3)
GREATER_THAN = cj.ConvertLimitOp(4)
NOT_EQUAL = cj.ConvertLimitOp(5)
UNIT_TYPE_HERO = cj.ConvertUnitType(0)
UNIT_TYPE_DEAD = cj.ConvertUnitType(1)
UNIT_TYPE_STRUCTURE = cj.ConvertUnitType(2)
UNIT_TYPE_FLYING = cj.ConvertUnitType(3)
UNIT_TYPE_GROUND = cj.ConvertUnitType(4)
UNIT_TYPE_ATTACKS_FLYING = cj.ConvertUnitType(5)
UNIT_TYPE_ATTACKS_GROUND = cj.ConvertUnitType(6)
UNIT_TYPE_MELEE_ATTACKER = cj.ConvertUnitType(7)
UNIT_TYPE_RANGED_ATTACKER = cj.ConvertUnitType(8)
UNIT_TYPE_GIANT = cj.ConvertUnitType(9)
UNIT_TYPE_SUMMONED = cj.ConvertUnitType(10)
UNIT_TYPE_STUNNED = cj.ConvertUnitType(11)
UNIT_TYPE_PLAGUED = cj.ConvertUnitType(12)
UNIT_TYPE_SNARED = cj.ConvertUnitType(13)
UNIT_TYPE_UNDEAD = cj.ConvertUnitType(14)
UNIT_TYPE_MECHANICAL = cj.ConvertUnitType(15)
UNIT_TYPE_PEON = cj.ConvertUnitType(16)
UNIT_TYPE_SAPPER = cj.ConvertUnitType(17)
UNIT_TYPE_TOWNHALL = cj.ConvertUnitType(18)
UNIT_TYPE_ANCIENT = cj.ConvertUnitType(19)
UNIT_TYPE_TAUREN = cj.ConvertUnitType(20)
UNIT_TYPE_POISONED = cj.ConvertUnitType(21)
UNIT_TYPE_POLYMORPHED = cj.ConvertUnitType(22)
UNIT_TYPE_SLEEPING = cj.ConvertUnitType(23)
UNIT_TYPE_RESISTANT = cj.ConvertUnitType(24)
UNIT_TYPE_ETHEREAL = cj.ConvertUnitType(25)
UNIT_TYPE_MAGIC_IMMUNE = cj.ConvertUnitType(26)
ITEM_TYPE_PERMANENT = cj.ConvertItemType(0)
ITEM_TYPE_CHARGED = cj.ConvertItemType(1)
ITEM_TYPE_POWERUP = cj.ConvertItemType(2)
ITEM_TYPE_ARTIFACT = cj.ConvertItemType(3)
ITEM_TYPE_PURCHASABLE = cj.ConvertItemType(4)
ITEM_TYPE_CAMPAIGN = cj.ConvertItemType(5)
ITEM_TYPE_MISCELLANEOUS = cj.ConvertItemType(6)
ITEM_TYPE_UNKNOWN = cj.ConvertItemType(7)
ITEM_TYPE_ANY = cj.ConvertItemType(8)
ITEM_TYPE_TOME = cj.ConvertItemType(2)
CAMERA_FIELD_TARGET_DISTANCE = cj.ConvertCameraField(0)
CAMERA_FIELD_FARZ = cj.ConvertCameraField(1)
CAMERA_FIELD_ANGLE_OF_ATTACK = cj.ConvertCameraField(2)
CAMERA_FIELD_FIELD_OF_VIEW = cj.ConvertCameraField(3)
CAMERA_FIELD_ROLL = cj.ConvertCameraField(4)
CAMERA_FIELD_ROTATION = cj.ConvertCameraField(5)
CAMERA_FIELD_ZOFFSET = cj.ConvertCameraField(6)
BLEND_MODE_NONE = cj.ConvertBlendMode(0)
BLEND_MODE_DONT_CARE = cj.ConvertBlendMode(0)
BLEND_MODE_KEYALPHA = cj.ConvertBlendMode(1)
BLEND_MODE_BLEND = cj.ConvertBlendMode(2)
BLEND_MODE_ADDITIVE = cj.ConvertBlendMode(3)
BLEND_MODE_MODULATE = cj.ConvertBlendMode(4)
BLEND_MODE_MODULATE_2X = cj.ConvertBlendMode(5)
RARITY_FREQUENT = cj.ConvertRarityControl(0)
RARITY_RARE = cj.ConvertRarityControl(1)
TEXMAP_FLAG_NONE = cj.ConvertTexMapFlags(0)
TEXMAP_FLAG_WRAP_U = cj.ConvertTexMapFlags(1)
TEXMAP_FLAG_WRAP_V = cj.ConvertTexMapFlags(2)
TEXMAP_FLAG_WRAP_UV = cj.ConvertTexMapFlags(3)
FOG_OF_WAR_MASKED = cj.ConvertFogState(1)
FOG_OF_WAR_FOGGED = cj.ConvertFogState(2)
FOG_OF_WAR_VISIBLE = cj.ConvertFogState(4)
CAMERA_MARGIN_LEFT = 0
CAMERA_MARGIN_RIGHT = 1
CAMERA_MARGIN_TOP = 2
CAMERA_MARGIN_BOTTOM = 3
EFFECT_TYPE_EFFECT = cj.ConvertEffectType(0)
EFFECT_TYPE_TARGET = cj.ConvertEffectType(1)
EFFECT_TYPE_CASTER = cj.ConvertEffectType(2)
EFFECT_TYPE_SPECIAL = cj.ConvertEffectType(3)
EFFECT_TYPE_AREA_EFFECT = cj.ConvertEffectType(4)
EFFECT_TYPE_MISSILE = cj.ConvertEffectType(5)
EFFECT_TYPE_LIGHTNING = cj.ConvertEffectType(6)
SOUND_TYPE_EFFECT = cj.ConvertSoundType(0)
SOUND_TYPE_EFFECT_LOOPED = cj.ConvertSoundType(1)
|
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ==========
PlaceObj('StoryBit', {
ActivationEffects = {
PlaceObj('ModifyObject', {
'Prop', "water_consumption",
'Percent', "<baseincrease>",
'ModifyId', "WaterChip",
}),
},
Category = "Tick_FounderStageDone",
Effects = {},
Enabled = true,
Image = "UI/Messages/Events/26_colonist.tga",
MainMapExclusive = false,
Prerequisites = {
PlaceObj('CheckObjectCount', {
'Label', "Colonist",
'Filters', {},
'Condition', "<=",
'Amount', 500,
}),
PlaceObj('PickFromLabel', {
'Label', "Dome",
'Conditions', {
PlaceObj('CheckObjectCount', {
'Label', "Colonist",
'InDome', true,
'Filters', {},
'Condition', ">",
'Amount', 0,
}),
},
}),
PlaceObj('SupplyMissionsEnabled', nil),
PlaceObj('IsMapEnvironment', nil),
},
ScriptDone = true,
Text = T(727840641132, --[[StoryBit WaterChip Text]] "The chip controls the water recycling for <DisplayName> dome. Without it water consumption there will increase by <baseincrease>%.\n\nWe were supposed to get replacement water chips but it seems they were wrongly delivered somewhere in Southern California on Earth.\n\nThe water chip is quite complex and it will take us <sols(base_time_to_fix)> Sols to manufacture it here on Mars. Alternatively, we can import a new one from Earth."),
TextReadyForValidation = true,
TextsDone = true,
Title = T(648156407702, --[[StoryBit WaterChip Title]] "Water Chip"),
VoicedText = T(958368945245, --[[voice:narrator]] "The terminal softly beeps, indicating that the water chip for one of our Domes has failed."),
group = "Buildings",
id = "WaterChip",
qa_info = PlaceObj('PresetQAInfo', {
data = {
{
action = "Modified",
time = 1625143968,
},
},
}),
PlaceObj('StoryBitParamPercent', {
'Name', "baseincrease",
'Value', 400,
}),
PlaceObj('StoryBitParamSols', {
'Name', "base_time_to_fix",
'Value', 4320000,
}),
PlaceObj('StoryBitReply', {
'Text', T(691139803107, --[[StoryBit WaterChip Text]] "Import Water Chip from Earth."),
'OutcomeText', "custom",
'CustomOutcomeText', T(526125635228, --[[StoryBit WaterChip CustomOutcomeText]] "It should arrive in <sols(short_time)> Sols and will cost us <funding(funding_cost)>"),
'Cost', "<funding_cost>",
'Comment', "IMPORTANT - remember to change follow up events and use WaterChip modifier ID",
}),
PlaceObj('StoryBitParamSols', {
'Name', "short_time",
'Value', 1440000,
}),
PlaceObj('StoryBitParamFunding', {
'Name', "funding_cost",
'Value', 250000000,
}),
PlaceObj('StoryBitOutcome', {
'Prerequisites', {},
'Enables', {
"WaterChip_QuickFix",
},
'Effects', {},
}),
PlaceObj('StoryBitReply', {
'Text', T(936678147521, --[[StoryBit WaterChip Text]] "We can build a temporary filtration device."),
'OutcomeText', "custom",
'CustomOutcomeText', T(706858999316, --[[StoryBit WaterChip CustomOutcomeText]] "Dome consumption reduced to <hydroincrease>%"),
'Prerequisite', PlaceObj('IsCommander', {
'CommanderProfile', "hydroengineer",
}),
}),
PlaceObj('StoryBitParamPercent', {
'Name', "hydroincrease",
'Value', 200,
}),
PlaceObj('StoryBitOutcome', {
'Prerequisites', {},
'Enables', {
"WaterChip_NormalFix",
},
'Effects', {
PlaceObj('ModifyObject', {
'Prop', "water_consumption",
'Percent', "<hydroincrease>",
'ModifyId', "WaterChip",
}),
},
}),
PlaceObj('StoryBitReply', {
'Text', T(600215200963, --[[StoryBit WaterChip Text]] "Try to speed up the manufacture process."),
'OutcomeText', "custom",
'CustomOutcomeText', T(203822416172, --[[StoryBit WaterChip CustomOutcomeText]] "Chance to fail, wasting even more Water"),
}),
PlaceObj('StoryBitParamPercent', {
'Name', "failincrease",
'Value', 600,
}),
PlaceObj('StoryBitOutcome', {
'Prerequisites', {},
'Weight', 50,
'Text', T(502618099999, --[[StoryBit WaterChip Text]] "The repair team managed to find a workaround and have cut down the repair time down to <sols(short_time)> Sols."),
'Enables', {
"WaterChip_QuickFix",
},
'Effects', {},
}),
PlaceObj('StoryBitOutcome', {
'Prerequisites', {},
'Weight', 50,
'Text', T(624966350717, --[[StoryBit WaterChip Text]] "The repair team failed to find a quicker solution and one of their pipe probes caused a serious issue, raising the total Water consumption by <failincrease>%."),
'Enables', {
"WaterChip_NormalFix",
},
'Effects', {
PlaceObj('ModifyObject', {
'Prop', "water_consumption",
'Percent', "<failincrease>",
'ModifyId', "WaterChip",
}),
},
}),
PlaceObj('StoryBitReply', {
'Text', T(733902281605, --[[StoryBit WaterChip Text]] "Let’s hope our Water reserves will hold until the chip is manufactured."),
}),
PlaceObj('StoryBitOutcome', {
'Prerequisites', {},
'Enables', {
"WaterChip_NormalFix",
},
'Effects', {},
}),
})
|
#!/usr/local/bin/lua
local P ={balance=0};
if _REQUIREDNAME == nil then
Named= P
else
_G[_REQUIREDNAME] = P
end
function Named:setname()
return self.name or "";
end
function Named:getname(n)
self.name = n
end
return Named;
|
-- Thanks to Shagu/pfUI
local cache = { }
local healthscan = CreateFrame("GameTooltip", "ufiHpScanner", UIParent, "GameTooltipTemplate")
healthscan:SetOwner(healthscan,"ANCHOR_NONE")
local healthbar = healthscan:GetChildren()
local cache_update = CreateFrame("Frame")
cache_update:RegisterEvent("UNIT_HEALTH")
cache_update:RegisterEvent("PLAYER_TARGET_CHANGED")
cache_update:SetScript("OnEvent", function()
if event == "PLAYER_TARGET_CHANGED" and UnitIsDead("target") then
healthscan:SetUnit("target")
cache[UnitName("target")] = healthbar:GetValue()
elseif event == "UNIT_HEALTH" and UnitIsDead(arg1) and UnitName(arg1) then
healthscan:SetUnit(arg1)
cache[UnitName(arg1)] = healthbar:GetValue()
elseif event == "UNIT_HEALTH" and UnitName(arg1) then
cache[UnitName(arg1)] = nil
end
end)
local oldUnitHealth = UnitHealth
function _G.UnitHealth(arg)
if UnitIsDead(arg) and cache[UnitName(arg)] then
return cache[UnitName(arg)]
else
return oldUnitHealth(arg)
end
end
|
-- testsupport.lua: A simple UpperCaseFile unit used for Tundra's test harness
module(..., package.seeall)
local util = require 'tundra.util'
local nodegen = require 'tundra.nodegen'
local depgraph = require 'tundra.depgraph'
local mt = nodegen.create_eval_subclass {}
function mt:create_dag(env, data, deps)
return depgraph.make_node {
Env = env,
Pass = data.Pass,
Label = "UpperCaseFile \$(@)",
Action = "tr a-z A-Z < \$(<) > \$(@)",
InputFiles = { data.InputFile },
OutputFiles = { data.OutputFile },
Dependencies = deps,
}
end
nodegen.add_evaluator("UpperCaseFile", mt, {
Name = { Type = "string", Required = "true" },
InputFile = { Type = "string", Required = "true" },
OutputFile = { Type = "string", Required = "true" },
})
|
-- paralyzer_blue
return {
["paralyzer_blue"] = {
usedefaultexplosions = false,
bluespark = {
air = true,
class = [[dirt]],
count = 1,
ground = true,
underwater = 1,
water = true,
properties = {
color = [[0.2, 0.06, 0.9]],
pos = [[1, 0, 0]],
size = [[0.1 r0.9 d0.02]],
sizeexpansion = 0.5,
slowdown = 0,
},
},
groundflash = {
circlealpha = 0.555,
circlegrowth = 3,
flashalpha = 3,
flashsize = 5.0,
ttl = 6,
color = {
[1] = 0.10000000149012,
[2] = 0.059999998658895,
[3] = 0.89999997615814,
},
},
heatcloud = {
air = true,
count = 1,
ground = true,
water = true,
properties = {
heat = 5,
heatfalloff = 1,
maxheat = 5,
pos = [[0, -0.15, 0]],
size = 0.55,
sizegrowth = 0.25,
sizemod = 0,
sizemodmod = 0,
speed = [[0, 0.10r, 0]],
},
},
smoke = {
air = true,
count = 1,
ground = true,
water = true,
properties = {
agespeed = 0.03,
color = 0.0,
pos = [[0, 0, 0]],
size = 0.2,
sizeexpansion = 0.1,
speed = [[0, 0.6, 0.0]],
startsize = 0.1,
},
},
},
}
|
-- TP All Cars
for get, Car in pairs(workspace.Vehicles:GetChildren()) do
if Car.Name == Firetruck.Name then
Car:MoveTo(workspace[game.Players.LocalPlayer.Name].Torso.Position + Vector3.new(math.random(0,20),0,math.random(0,20)))
end
end |
local nmap = require "nmap"
local rpc = require "rpc"
local shortport = require "shortport"
local stdnse = require "stdnse"
local table = require "table"
description = [[
Detects vulnerabilities and gathers information (such as version
numbers and hardware support) from VxWorks Wind DeBug agents.
Wind DeBug is a SunRPC-type service that is enabled by default on many devices
that use the popular VxWorks real-time embedded operating system. H.D. Moore
of Metasploit has identified several security vulnerabilities and design flaws
with the service, including weakly-hashed passwords and raw memory dumping.
See also:
http://www.kb.cert.org/vuls/id/362332
]]
---
-- @usage
-- nmap -sU -p 17185 --script wdb-version <target>
-- @output
-- 17185/udp open wdb Wind DeBug Agent 2.0
-- | wdb-version:
-- | VULNERABLE: Wind River Systems VxWorks debug service enabled. See http://www.kb.cert.org/vuls/id/362332
-- | Agent version: 2.0
-- | VxWorks version: VxWorks5.4.2
-- | Board Support Package: PCD ARM940T REV 1
-- | Boot line: host:vxWorks.z
--@xmloutput
-- <elem>VULNERABLE: Wind River Systems VxWorks debug service enabled. See http://www.kb.cert.org/vuls/id/362332</elem>
-- <elem key="Agent version">2.0</elem>
-- <elem key="VxWorks version">5.4</elem>
-- <elem key="Board Support Package">Alcatel CMM MPC8245/100</elem>
-- <elem key="Boot line">lanswitchCmm:</elem>
author = "Daniel Miller"
license = "Same as Nmap--See https://nmap.org/book/man-legal.html"
categories = {"default", "safe", "version", "discovery", "vuln"}
-- WDB protocol information
-- http://www.vxdev.com/docs/vx55man/tornado-api/wdbpcl/wdb.html
-- http://www.verysource.com/code/2817990_1/wdb.h.html
-- Metasploit scanner module
-- https://github.com/rapid7/metasploit-framework/blob/master/lib/msf/core/exploit/wdbrpc.rb
portrule = shortport.version_port_or_service(17185, "wdbrpc", {"udp"} )
rpc.RPC_version["wdb"] = { min=1, max=1 }
local WDB_Procedure = {
["WDB_TARGET_PING"] = 0,
["WDB_TARGET_CONNECT"] = 1,
["WDB_TARGET_DISCONNECT"] = 2,
["WDB_TARGET_MODE_SET"] = 3,
["WDB_TARGET_MODE_GET"] = 4,
}
local function checksum(data)
local sum = 0
local p = 5 -- skip first 4 bytes
while p < #data do
local c
c, p = (">I2"):unpack(data, p)
sum = sum + c
end
sum = (sum & 0xffff) + (sum >> 16)
return ~sum & 0xffff
end
local seqnum = 0
local function seqno()
seqnum = seqnum + 1
return seqnum
end
local function request(comm, procedure, data)
local packet = comm:EncodePacket( nil, procedure, {type = rpc.Portmap.AuthType.NULL}, nil )
local wdbwrapper = (">I4I4"):pack(#data + #packet + 8, seqno())
local sum = checksum(packet .. "\0\0\0\0" .. wdbwrapper .. data)
return packet .. (">I2I2"):pack(0xffff, sum) .. wdbwrapper .. data
end
local function stripnull(str)
return (str:gsub("\0*$",""))
end
local function decode_reply(data, pos)
local wdberr, len
local done = data:len()
local info = {}
local _
pos, _ = rpc.Util.unmarshall_uint32(data, pos)
pos, _ = rpc.Util.unmarshall_uint32(data, pos)
pos, wdberr = rpc.Util.unmarshall_uint32(data, pos)
info["error"] = wdberr & 0xc0000000
if info["error"] ~= 0x00000000 then
stdnse.debug1("Error from decode_reply: %x", info["error"])
return nil, info
end
pos, len = rpc.Util.unmarshall_uint32(data, pos)
if len ~= 0 then
pos, info["agent_ver"] = rpc.Util.unmarshall_vopaque(len, data, pos)
end
pos, info["agent_mtu"] = rpc.Util.unmarshall_uint32(data, pos)
pos, info["agent_mod"] = rpc.Util.unmarshall_uint32(data, pos)
pos, info["rt_type"] = rpc.Util.unmarshall_uint32(data, pos)
pos, len = rpc.Util.unmarshall_uint32(data, pos)
if pos == done then return pos, info end
if len ~= 0 then
pos, info["rt_vers"] = rpc.Util.unmarshall_vopaque(len, data, pos)
end
pos, info["rt_cpu_type"] = rpc.Util.unmarshall_uint32(data, pos)
pos, len = rpc.Util.unmarshall_uint32(data, pos)
info["rt_has_fpp"] = ( len ~= 0 )
pos, len = rpc.Util.unmarshall_uint32(data, pos)
info["rt_has_wp"] = ( len ~= 0 )
pos, info["rt_page_size"] = rpc.Util.unmarshall_uint32(data, pos)
pos, info["rt_endian"] = rpc.Util.unmarshall_uint32(data, pos)
pos, len = rpc.Util.unmarshall_uint32(data, pos)
if len ~= 0 then
pos, info["rt_bsp_name"] = rpc.Util.unmarshall_vopaque(len, data, pos)
end
pos, len = rpc.Util.unmarshall_uint32(data, pos)
if len ~= 0 then
pos, info["rt_bootline"] = rpc.Util.unmarshall_vopaque(len, data, pos)
end
if pos == done then return pos, info end
pos, info["rt_membase"] = rpc.Util.unmarshall_uint32(data, pos)
if pos == done then return pos, info end
pos, info["rt_memsize"] = rpc.Util.unmarshall_uint32(data, pos)
if pos == done then return pos, info end
pos, info["rt_region_count"] = rpc.Util.unmarshall_uint32(data, pos)
if pos == done then return pos, info end
pos, len = rpc.Util.unmarshall_uint32(data, pos)
if len ~= 0 then
info["rt_regions"] = {}
for i = 1, len do
pos, info["rt_regions"][i] = rpc.Util.unmarshall_uint32(data, pos)
end
end
if pos == done then return pos, info end
pos, len = rpc.Util.unmarshall_uint32(data, pos)
if len == nil then return pos, info end
if len ~= 0 then
pos, info["rt_hostpool_base"] = rpc.Util.unmarshall_vopaque(len, data, pos)
end
if pos == done then return pos, info end
pos, len = rpc.Util.unmarshall_uint32(data, pos)
if len ~= 0 then
pos, info["rt_hostpool_size"] = rpc.Util.unmarshall_vopaque(len, data, pos)
end
return pos, info
end
action = function(host, port)
local comm = rpc.Comm:new("wdb", 1)
local status, err = comm:Connect(host, port)
if not status then
return stdnse.format_output(false, err)
end
local packet = request(comm, WDB_Procedure["WDB_TARGET_CONNECT"], (">I4I4I4"):pack(2, 0, 0))
if not comm:SendPacket(packet) then
return stdnse.format_output(false, "Failed to send request")
end
local status, data = comm:ReceivePacket()
if not status then
--return stdnse.format_output(false, "Failed to read data")
return nil
end
nmap.set_port_state(host, port, "open")
local pos, header = comm:DecodeHeader(data, 1)
if not header then
return stdnse.format_output(false, "Failed to decode header")
end
if pos == #data then
return stdnse.format_output(false, "No WDB data in reply")
end
local pos, info = decode_reply(data, pos)
if not pos then
return stdnse.format_output(false, "WDB error: "..info.error)
end
port.version.name = "wdb"
port.version.name_confidence = 10
port.version.product = "Wind DeBug Agent"
port.version.version = stripnull(info["agent_ver"])
if port.version.ostype ~= nil then
port.version.ostype = "VxWorks " .. stripnull(info["rt_vers"])
end
nmap.set_port_version(host, port)
-- Clean up (some agents will continue to send data until we disconnect)
packet = request(comm, WDB_Procedure["WDB_TARGET_DISCONNECT"], (">I4I4I4"):pack(2, 0, 0))
if not comm:SendPacket(packet) then
return stdnse.format_output(false, "Failed to send request")
end
local o = stdnse.output_table()
table.insert(o, "VULNERABLE: Wind River Systems VxWorks debug service enabled. See http://www.kb.cert.org/vuls/id/362332")
if info.agent_ver then
o["Agent version"] = stripnull(info.agent_ver)
end
--table.insert(o, "Agent MTU: " .. info.agent_mtu)
if info.rt_vers then
o["VxWorks version"] = stripnull(info.rt_vers)
end
-- rt_cpu_type is an enum type, but I don't have access to
-- cputypes.h, where it is defined
--table.insert(o, "CPU Type: " .. info.rt_cpu_type)
if info.rt_bsp_name then
o["Board Support Package"] = stripnull(info.rt_bsp_name)
end
if info.rt_bootline then
o["Boot line"] = stripnull(info.rt_bootline)
end
return o
end
|
local beautiful = require("beautiful")
local gears = require("gears")
local gfs = require("gears.filesystem")
require("config.key")
require("config.icons")
require("config.menu")
require("config.notif")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.