content stringlengths 5 1.05M |
|---|
-- drive.lua
local math = require("math")
local pairs = pairs
module(...)
--[[
calculate computes the wheel angles and speeds.
x and y are the strafe inputs from the operator, w is the rotation speed
about the z-axis.
gyroDeg is the field-centric shift (in degrees).
The units for wheelBase and trackWidth are irrelevant as long as they are
consistent.
(Consult Adam for the math.)
--]]
function calculate(x, y, w, gyroDeg, wheelBase, trackWidth)
local r = math.sqrt(wheelBase ^ 2 + trackWidth ^ 2)
local gyroRad = math.rad(gyroDeg)
y, x = x * math.cos(gyroRad) + y * math.sin(gyroRad), -x * math.sin(gyroRad) + y * math.cos(gyroRad)
local a = y - w * (wheelBase / r)
local b = y + w * (wheelBase / r)
local c = x - w * (trackWidth / r)
local d = x + w * (trackWidth / r)
local wheels = {frontRight={}, frontLeft={}, rearRight={}, rearLeft={}}
wheels.frontRight.speed = math.sqrt(b * b + c * c)
wheels.frontLeft.speed = math.sqrt(b * b + d * d)
wheels.rearLeft.speed = math.sqrt(a * a + d * d)
wheels.rearRight.speed = math.sqrt(a * a + c * c)
wheels.frontRight.angleDeg = math.deg(math.atan2(b, c))
wheels.frontLeft.angleDeg = math.deg(math.atan2(b, d))
wheels.rearLeft.angleDeg = math.deg(math.atan2(a, d))
wheels.rearRight.angleDeg = math.deg(math.atan2(a, c))
-- Normalize wheel speeds
local maxSpeed = math.max(
wheels.frontRight.speed,
wheels.frontLeft.speed,
wheels.rearRight.speed,
wheels.rearLeft.speed
)
if maxSpeed > 1 then
for _, wheel in pairs(wheels) do
wheel.speed = wheel.speed / maxSpeed
end
end
return wheels
end
-- Wraps an angle (in degrees) to (-180, 180].
function normalizeAngle(theta)
while theta > 180 do
theta = theta - 360
end
while theta < -180 do
theta = theta + 360
end
return theta
end
-- Calculate the error and the flip of the motor.
function calculateTurn(current, target)
local err, flip = normalizeAngle(target - current), false
if math.abs(err) > 90 then
err, flip = normalizeAngle(err + 180), true
end
return err, flip
end
function angleError(current, target)
local err, flip = calculateTurn(current, target)
return err
end
function driveScale(err, flip)
local scale
if math.abs(err) < 45 then
scale = math.cos(math.rad(err))
else
scale = 0
end
if flip then
scale = -scale
end
return scale
end
-- vim: ft=lua et ts=4 sts=4 sw=4 |
--[[
Director.lua
@Author : DengSir (tdaddon@163.com)
@Link : https://dengsir.github.io
]]
local ns = select(2, ...)
local Util = ns.Util
local Addon = ns.Addon
local Action = ns.Action
local Condition = ns.Condition
local Director = Addon:NewModule('Director', 'AceEvent-3.0')
function Director:OnInitialize()
self:RegisterEvent('PET_BATTLE_CLOSE', 'ClearScript')
end
function Director:Run()
if not self.script then
return
end
self:Action(self.script:GetScript())
end
function Director:Debug(script)
self:Action(script)
end
function Director:Action(item)
if type(item) == 'table' then
for i, v in ipairs(item) do
if Condition:Run(v[2]) and self:Action(v[1]) then
return true
end
end
elseif type(item) == 'string' then
if Action:Run(item) then
return true
end
else
error('No item')
end
end
local function FormatMacro(tab, action, condition)
if not condition then
return tab .. action
elseif type(condition) == 'string' then
return format('%s%s [ %s ]', tab, action, condition)
else
return format('%s%s [ %s ]', tab, action, table.concat(condition, ' & '))
end
end
local function mergeCondition(dest, ...)
for i = 1, select('#', ...) do
local v = select(i, ...)
if type(v) == 'table' then
mergeCondition(dest, unpack(v))
elseif type(v) == 'string' then
v = v:trim()
if v ~= '' then
tinsert(dest, v)
end
end
end
return dest
end
local function MergeCondition(...)
local condition = mergeCondition({}, ...)
if #condition > 1 then
return condition
elseif #condition == 1 then
return condition[1]
else
return nil
end
end
local function CheckCondition(item)
if type(item) == 'string' then
return Condition:ParseCondition(item)
elseif type(item) == 'table' then
for i, v in ipairs(item) do
CheckCondition(v)
end
elseif not item then
return
else
Util.assert(false, 'Invalid Script (Struct Error)')
end
end
local function CheckAction(item)
if type(item) == 'string' then
return Action:ParseAction(item)
elseif type(item) == 'table' then
for i, v in ipairs(item) do
CheckCondition(v[2])
CheckAction(v[1])
end
else
Util.assert(false, 'Invalid Script (Struct Error)')
end
end
function Director:Check(item)
return pcall(CheckAction, item)
end
function Director:BuildScript(code)
if type(code) ~= 'string' then
return nil, 'No code'
end
local script = {}
local stack = ns.Stack:New()
stack:Push(script)
for line in code:gmatch('[^\r\n]+') do
line = line:trim()
if line ~= '' then
local script = stack:Top()
local action, condition do
if line:find('^%-%-') then
action = line
elseif line:find('[', nil, true) then
action, condition = line:match('^/?(.+)%s+%[(.+)%]$')
else
action = line:match('^/?(.+)$')
end
end
if not action then
return nil, format('Invalid Line: `%s`', line)
end
if condition then
condition = MergeCondition({strsplit('&', condition)})
end
if action == 'if' then
stack:Push({})
tinsert(script, {stack:Top(), condition})
elseif action == 'endif' or action == 'ei' then
stack:Pop()
local parent = stack:Top()
if not parent then
return nil, 'Invalid Script: if endif unpaired'
end
if #script == 1 then
local dest = parent[#parent]
local item = script[1]
dest[1] = item[1]
dest[2] = MergeCondition(dest[2], item[2])
end
else
tinsert(script, {action, condition})
end
end
end
if stack:Top() ~= script then
return nil, 'Invalid Script: if endif unpaired'
end
local ok, err = Director:Check(script)
if not ok then
return nil, err
end
return script
end
function Director:BeautyScript(script, deep)
deep = deep or 0
local tab = strrep(' ', deep * 4)
local sb = {}
for i, v in ipairs(script) do
local condition = MergeCondition(v[2])
local action = v[1]
if type(action) == 'string' then
tinsert(sb, FormatMacro(tab, action, condition))
elseif type(action) == 'table' then
tinsert(sb, FormatMacro(tab, 'if', condition))
tinsert(sb, self:BeautyScript(action, deep + 1))
tinsert(sb, FormatMacro(tab, 'endif'))
end
end
return table.concat(sb, '\n')
end
local function errorhandler(err)
return geterrorhandler()(err)
end
function Director:Select()
local list = {}
for name, plugin in Addon:IterateEnabledPlugins() do
local ok, key = xpcall(function() return plugin:GetCurrentKey() end, errorhandler)
local script = ok and key and plugin:GetScript(key)
if script then
tinsert(list, script)
end
end
return list
end
function Director:SetScript(script)
self.script = script
self:SendMessage('PET_BATTLE_SCRIPT_SCRIPT_UPDATE')
end
function Director:GetScript()
return self.script
end
function Director:ClearScript()
self.script = nil
self:SendMessage('PET_BATTLE_SCRIPT_SCRIPT_UPDATE')
end
|
function love.conf(t)
t.title="Possession"
t.version="11.2"
t.author="Weirdfellows"
t.identity="possessionroguelike"
t.url="http://possessiongame.com"
t.modules.physics=false
t.window.resizable = true
t.window.minwidth=1024
t.window.minheight=768
end |
bh_tusken_death_hunter = Creature:new {
objectName = "@mob/creature_names:tusken_death_hunter",
socialGroup = "tusken_raider",
faction = "tusken_raider",
level = 150,
chanceHit = 0.5,
damageMin = 395,
damageMax = 500,
baseXp = 4916,
baseHAM = 110000,
baseHAMmax = 112000,
armor = 1,
resists = {60,60,60,60,60,60,60,60,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK + KILLER,
optionsBitmask = AIENABLED,
diet = HERBIVORE,
templates = {"object/mobile/tusken_raider.iff"},
lootGroups = {
{
groups = {
{group = "tierone", chance = 2500000},
{group = "tiertwo", chance = 500000},
{group = "tierthree", chance = 500000},
{group = "color_crystals", chance = 500000},
{group = "power_crystals", chance = 1000000},
{group = "nge_all", chance = 1000000},
{group = "weapons_all", chance = 1000000},
{group = "armor_all", chance = 1000000},
{group = "clothing_attachments", chance = 1000000},
{group = "armor_attachments", chance = 1000000}
},
lootChance = 100000000
},
{
groups = {
{group = "tierone", chance = 2500000},
{group = "tiertwo", chance = 500000},
{group = "tierthree", chance = 500000},
{group = "color_crystals", chance = 500000},
{group = "power_crystals", chance = 1000000},
{group = "nge_all", chance = 1000000},
{group = "weapons_all", chance = 1000000},
{group = "armor_all", chance = 1000000},
{group = "clothing_attachments", chance = 1000000},
{group = "armor_attachments", chance = 1000000}
},
lootChance = 5000000
}
},
weapons = {"tusken_weapons"},
conversationTemplate = "",
attacks = merge(marksmanmaster,brawlermaster,fencermaster,riflemanmaster)
}
CreatureTemplates:addCreatureTemplate(bh_tusken_death_hunter, "bh_tusken_death_hunter")
|
-- Copyright (c) 2021 Maksim Tuprikov <insality@gmail.com>. This code is licensed under MIT license
return {}
|
ccs = ccs or {}
---BoneNode object
---@class BoneNode : Node
local BoneNode = {}
ccs.BoneNode = BoneNode
--------------------------------
--
---@return float
function BoneNode:getDebugDrawWidth() end
--------------------------------
---@overload fun():array_table
---@overload fun():array_table
---@return array_table
function BoneNode:getChildBones() end
--------------------------------
--
---@return BlendFunc
function BoneNode:getBlendFunc() end
--------------------------------
---brief: get all bones in this bone tree
---@return array_table
function BoneNode:getAllSubBones() end
--------------------------------
--
---@param blendFunc BlendFunc
---@return BoneNode
function BoneNode:setBlendFunc(blendFunc) end
--------------------------------
--
---@param isDebugDraw bool
---@return BoneNode
function BoneNode:setDebugDrawEnabled(isDebugDraw) end
--------------------------------
---get displayings rect in self transform
---@return rect_table
function BoneNode:getVisibleSkinsRect() end
--------------------------------
---brief: get all skins in this bone tree
---@return array_table
function BoneNode:getAllSubSkins() end
--------------------------------
---@overload fun(string, bool:bool):BoneNode
---@overload fun(Node, bool:bool):BoneNode
---@param skin Node
---@param hideOthers bool
---@return BoneNode
function BoneNode:displaySkin(skin, hideOthers) end
--------------------------------
--
---@return bool
function BoneNode:isDebugDrawEnabled() end
--------------------------------
---@overload fun(Node, bool:bool, bool:bool):BoneNode
---@overload fun(Node, bool:bool):BoneNode
---@param skin Node
---@param display bool
---@param hideOthers bool
---@return BoneNode
function BoneNode:addSkin(skin, display, hideOthers) end
--------------------------------
--
---@return SkeletonNode
function BoneNode:getRootSkeletonNode() end
--------------------------------
--
---@param length float
---@return BoneNode
function BoneNode:setDebugDrawLength(length) end
--------------------------------
---@overload fun():array_table
---@overload fun():array_table
---@return array_table
function BoneNode:getSkins() end
--------------------------------
--
---@return array_table
function BoneNode:getVisibleSkins() end
--------------------------------
--
---@param width float
---@return BoneNode
function BoneNode:setDebugDrawWidth(width) end
--------------------------------
--
---@return float
function BoneNode:getDebugDrawLength() end
--------------------------------
--
---@param color
---@return BoneNode
function BoneNode:setDebugDrawColor(color) end
--------------------------------
--
---@return color4f_table
function BoneNode:getDebugDrawColor() end
--------------------------------
---@overload fun(int):BoneNode
---@overload fun():BoneNode
---@param length int
---@return BoneNode
function BoneNode:create(length) end
--------------------------------
---@overload fun(Node, int, int):BoneNode
---@overload fun(Node, int, string):BoneNode
---@param child Node
---@param localZOrder int
---@param name string
---@return BoneNode
function BoneNode:addChild(child, localZOrder, name) end
--------------------------------
--
---@param renderer Renderer
---@param transform mat4_table
---@param flags int
---@return BoneNode
function BoneNode:draw(renderer, transform, flags) end
--------------------------------
--
---@param name string
---@return BoneNode
function BoneNode:setName(name) end
--------------------------------
--
---@param anchorPoint vec2_table
---@return BoneNode
function BoneNode:setAnchorPoint(anchorPoint) end
--------------------------------
--
---@param localZOrder int
---@return BoneNode
function BoneNode:setLocalZOrder(localZOrder) end
--------------------------------
--
---@param child Node
---@param cleanup bool
---@return BoneNode
function BoneNode:removeChild(child, cleanup) end
--------------------------------
--
---@return bool
function BoneNode:init() end
--------------------------------
--
---@return rect_table
function BoneNode:getBoundingBox() end
--------------------------------
--
---@param contentSize size_table
---@return BoneNode
function BoneNode:setContentSize(contentSize) end
--------------------------------
--
---@param visible bool
---@return BoneNode
function BoneNode:setVisible(visible) end
--------------------------------
--
---@return BoneNode
function BoneNode:BoneNode() end
return BoneNode |
-- vim-highlightedyank
-- Make the yanked region apparent!
-- https://github.com/machakann/vim-highlightedyank
vim.g.highlightedyank_highlight_duration = 200
|
--vim: filetype=lua ts=2 sw=2 sts=2 et :
-- # Dump tables to string
-- Note for Python programmers:
-- To do something like in Python, inherit from ``o``:
--
-- class o(object):
-- def __init__(i, **k): i.__dict__.update(**k)
-- def __repr__(i):
-- return i.__class__.__name__ + str(
-- {k: v for k, v in i.__dict__.items() if k[0] != "_"})
--
local dump,pump,rump
-- ## function pump(t:_table_)
-- Print string of table.
function pump(t) print(dump(t)) end
-- ## function dump(t:_table_)
-- Converts a table to string (without recursion into values).
function dump(t, sep,s,k,keys)
sep, s = "", (t._name or "") .."{"
keys = {}
for k in pairs(t) do keys[#keys+1] = k end
table.sort(keys)
for _,k in pairs(keys) do
if k:sub(1,1) ~= "_" then
s=s .. sep .. tostring(k).."="..tostring(t[k])
sep=", " end end
return s.."}" end
-- ## function rump(t:_table_, pre:_string_)
-- Print string version of a value (with
-- recursion into values.
-- `pre` is a preefix string (show before each entry).
-- (defaults to "").
function rump(t,pre, indent,fmt)
pre, indent = pre or "", indent or 0
if indent < 10 then
for k, v in pairs(t or {}) do
if not (type(k)=='string' and k:match("^_")) then
fmt= pre..string.rep("| ",indent)..tostring(k)..": "
if type(v) == "table" then
print(fmt)
rump(v, pre, indent+1)
else
print(fmt .. tostring(v)) end end end end end
-- ## Return
return {dmup=dump,rump=rump,pump=pump}
|
--[[
LuCI - Lua Configuration Interface
Copyright 2015 Promwad.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.controller.hmactl", package.seeall)
function index()
if not nixio.fs.access("/etc/config/hma") then
return
end
local page
page = entry({"admin", "services", "hma"}, cbi("hma/hma"), _("Hide My Ass!"))
page.dependent = true
entry({"admin", "system", "public_ip"}, call("action_public_ip"))
end
function action_public_ip()
local ipt = io.popen("wget -O - -q http://whatismyip.org/ | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])'")
if ipt then
local res = ""
while true do
l = ipt:read("*l")
if not l then break end
if l then
res = res .. l
end
end
ipt:close()
luci.http.prepare_content("application/json")
luci.http.write_json({ ipstring = res })
end
end
|
object_tangible_collection_rare_rifle_proton = object_tangible_collection_shared_rare_rifle_proton:new {
gameObjectType = 8211,}
ObjectTemplates:addTemplate(object_tangible_collection_rare_rifle_proton, "object/tangible/collection/rare_rifle_proton.iff") |
local awful = require("awful")
local wibox = require("wibox")
local naughty = require("naughty")
local gears = require("gears")
local beautiful = require("beautiful")
local xresources = require("beautiful.xresources")
local dpi = xresources.apply_dpi
local utils = require("utils")
local timer = require("gears.timer")
local audio = {}
local audio_icon = beautiful.audio_icon or nil
local icon_size = beautiful.icon_size or dpi(20)
-- intentionally set ugly fallback colors so I know something's wrong
local top_color = beautiful.audio_bar_top_color or '#22ee22'
local bottom_color = beautiful.audio_bar_bottom_color or '#22ee22'
local top_color_muted = beautiful.audio_bar_top_color_muted or '#aaaaaa'
local bottom_color_muted = beautiful.audio_bar_bottom_color_muted or '#444444'
-- the icon
audio.audio_icon_widget = wibox.widget({
forced_width = icon_size,
forced_height = icon_size,
widget = wibox.widget.imagebox(audio_icon),
})
-- the sidebar audio bar
audio.audio_bar_widget = wibox.widget({
max_value = 100,
bar_shape = beautiful.top_infobar_shape or gears.shape.rectangle,
color = top_color,
margins = {
-- just so I only have to edit the size once at the top of the file
top = icon_size / 5.5,
bottom = icon_size / 5.5,
},
forced_height = beautiful.infobar_height or dpi(10),
forced_width = beautiful.infobar_width or dpi(30),
background_color = bottom_color,
shape = beautiful.bottom_infobar_shape or gears.shape.rectangle,
widget = wibox.widget.progressbar,
})
-- this is where we put together the icon and the sidebar audio bar
audio.audio_widget = wibox.widget({
audio.audio_icon_widget,
utils.pad_width(20),
audio.audio_bar_widget,
layout = wibox.layout.fixed.horizontal,
})
-- the bottom-right audio bar that's supposed to act as a notification
audio.notification_audio_bar = wibox.widget({
max_value = 100,
bar_shape = beautiful.top_infobar_shape or gears.shape.rectangle,
color = top_color,
-- forced height and width don't do anything in this context
-- because the widget stretches to meet the geometry of the
-- parent widget (the widget it's nested in)
-- forced_height = beautiful.infobar_height or dpi(10),
-- forced_width = beautiful.infobar_width or dpi(35),
background_color = bottom_color,
shape = beautiful.bottom_infobar_shape or gears.shape.rectangle,
widget = wibox.widget.progressbar,
})
-- the background for the notification audio bar, on top of which
-- we acutally put the notification
audio.notification_audio_bar_bg = wibox({
x = awful.screen.focused().geometry.width - dpi(400),
y = awful.screen.focused().geometry.height - dpi(100),
height = beautiful.infobar_height or dpi(30),
width = beautiful.infobar_width or dpi(300),
shape = gears.shape.rectangle,
bg = "#00000000",
widget = audio.notification_audio_bar,
ontop = true,
visible = false,
type = 'dock', -- let's let compton know we don't want shadows
})
local function update_widget(event)
-- event is just a line that gets outputted by the 'pactl subscribe 2' command
-- I don't know for sure if the first sink always has the number '0',
-- so this is kind of a hack, but it works pretty well.
-- EDIT: I found out that the default sink is not always '0', but this
-- whole thing still works without a problem
sink_number = '0'
if event then
if string.match(event, 'remove') then
sink_number = '0'
elseif string.match(event, 'new') or string.match(event, 'change') then
sink_number = string.match(event, 'sink #(%d)')
end
end
-- naughty.notify({text = tostring(sink_number)})
awful.spawn.easy_async({"sh", "-c", "pactl list sinks"},
function(stdout)
local current_sink = string.match(stdout, 'Sink #'..sink_number..'.*')
local volume = string.match(current_sink, '(%d+)%% /')
local muted = string.match(stdout, 'Mute: [yes]')
_top_color = top_color
_bottom_color = bottom_color
if muted ~= nil then
_top_color = top_color_muted
_bottom_color = bottom_color_muted
end
-- the sidebar audio widget
local wid = audio.audio_bar_widget
wid.value = tonumber(volume)
wid.color = _top_color
wid.background_color = _bottom_color
-- the notification audio widget
local bottom_wid = audio.notification_audio_bar
bottom_wid.value = tonumber(volume)
bottom_wid.color = _top_color
bottom_wid.background_color = _bottom_color
end
)
end
update_widget()
-- Sleeps until pactl detects an event (volume up/down/toggle/mute)
local volume_script = [[
bash -c '
pactl subscribe 2> /dev/null | grep --line-buffered "sink #"
']]
awful.spawn.with_line_callback(volume_script, {
stdout = function(line)
update_widget(line)
-- naughty.notify({text = tostring(line)})
end
})
return audio
|
--[=[
Utility functions for manipulating terrain
@class TerrainUtils
]=]
local require = require(script.Parent.loader).load(script)
local Region3Utils = require("Region3Utils")
local Region3int16Utils = require("Region3int16Utils")
local Vector3int16Utils = require("Vector3int16Utils")
local TerrainUtils = {}
--[=[
Gets the terrain region from the position and size
@param position Vector3
@param size Vector3
@param resolution number
@return Region3
]=]
function TerrainUtils.getTerrainRegion3(position, size, resolution)
return Region3Utils.fromPositionSize(position, size)
:ExpandToGrid(resolution)
end
--[=[
Gets the terrain region3int16 from a terrain region (in world space) at the resolution
requested.
@param region3 Region3
@param resolution number
@return Region3int16
]=]
function TerrainUtils.getTerrainRegion3int16FromRegion3(region3, resolution)
local position = region3.CFrame.Position/resolution
local size = region3.Size/resolution
return Region3int16Utils.createRegion3int16FromPositionSize(position, size)
end
--[=[
Gets the corner of terrain for a region3
@param region3 Region3
@return Vector3
]=]
function TerrainUtils.getCorner(region3)
local position = region3.CFrame.Position
local halfSize = region3.Size/2
return position - halfSize
end
--[=[
Gets the corner of the region in Vector3int16
@param region3 Region3
@param resolution number
@return Vector3int16
]=]
function TerrainUtils.getCornerint16(region3, resolution)
local corner = TerrainUtils.getCorner(region3)
return Vector3int16Utils.fromVector3(corner/resolution)
end
return TerrainUtils |
-- Tests for 99bottles.lua
local nbottles = require '99bottles'
local total, pass = 1, 1
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
print('99 bottles of beer lyrics:\n')
local lyrics = nbottles(99)
print(lyrics)
print('\n'..('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
|
local cosock = require "cosock"
-- mDNS
local ADDRESS = "224.0.0.251"
local PORT = 5353
-- resolve host name using mDNS. resolution is called with each address
return function(name, resolution)
local labels = {}
for label in string.gmatch(name, "[%a%d-]+") do
table.insert(labels, string.pack("> s1", label))
end
labels = table.concat(labels)
local transaction_id = 0
local type = 1 -- Type: A (Host Address)
local class = 1 -- Class: IN
local question = table.concat({
string.pack("> I2 I2 I2 I2 I2 I2 z I2 I2",
transaction_id,
0, -- Flags
1, -- Questions
0, -- Answer RRs
0, -- Authority RRs
0, -- Additional RRs
labels,
type,
class
),
})
local labels_len = labels:len()
local answer_len = 12 + (labels_len + 1) + 14
local resolver = cosock.socket.udp()
-- ask question, expect unicast response to our ephemeral port
resolver:sendto(question, ADDRESS, PORT)
-- after a short wait, receive all answers and dispatch any resolution
cosock.socket.sleep(0.1)
while cosock.socket.select({resolver}, {}, 0.001) do
local answer = resolver:receive(2048)
if answer_len <= answer:len() then
local
_transaction_id,
flags,
questions,
answers,
authorities,
_, -- Additional RRs (ignore)
_labels,
zero, -- null terminator
_type,
_class,
_, -- TTL (ignore)
length,
a, b, c, d
= string.unpack("> I2 I2 I2 I2 I2 I2 c" .. labels_len .. " B I2 I2 I4 I2 BBBB", answer)
if true
and transaction_id == _transaction_id
and 0x8400 == flags
and 0 == questions
and 1 == answers
and 0 == authorities
and labels == _labels
and 0 == zero
and type == _type
and class == _class & ~0x8000 -- ignore Cache flush: True
and 4 == length
then
local address = table.concat({a, b, c, d}, ".")
resolution(address)
end
end
end
resolver:close()
end
|
fx_version 'cerulean'
game 'gta5'
client_scripts {
"config.lua",
'client/native.lua',
'client/main.lua',
}
server_scripts {
"config.lua",
"@mysql-async/lib/MySQL.lua",
"server/native.lua",
"server/main.lua",
"version_checker.lua"
}
files {
"client/native_min.lua"
}
|
--[[
RTA Timer
Author:
Museus (Discord: Museus#7777)
Track RTA time and display it below the IGT timer
]]
ModUtil.RegisterMod("RtaTimer")
local config = {
ModName = "RtaTimer",
DisplayTimer = true,
MultiWeapon = false,
}
if ModConfigMenu then
ModConfigMenu.Register(config)
end
function RtaTimer.FormatElapsedTime(start_time, current_epoch)
-- Accept a "start" time and "current" time and output it in the format Xh Xm Xs
-- Can change the "string.format" line to change the output
local time_since_launch = current_epoch - start_time
local minutes = 0
local hours = 0
local centiseconds = (time_since_launch % 1) * 100
local seconds = time_since_launch % 60
-- If it hasn't been over a minute, no reason to do this calculation
if time_since_launch > 60 then
minutes = math.floor((time_since_launch % 3600) / 60)
end
-- If it hasn't been over an hour, no reason to do this calculation
if time_since_launch > 3600 then
hours = math.floor(time_since_launch / 3600)
end
-- If it hasn't been over an hour, only display minutes:seconds.centiseconds
if hours == 0 then
return string.format("%02d:%02d.%02d", minutes, seconds, centiseconds)
end
return string.format("%02d:%02d:%02d.%02d", hours, minutes, seconds, centiseconds)
end
function RtaTimer.UpdateRtaTimer()
-- If Timer should not be displayed, make sure it's gone but don't kill thread
-- in case it's enabled in the middle of a run
if not config.DisplayTimer then
PrintUtil.destroyScreenAnchor("RtaTimer")
return
end
local current_time = "00:00.00"
-- If the timer has been reset, it should stay at 00:00.00 until it "starts" again
if not RtaTimer.TimerWasReset then
current_time = RtaTimer.FormatElapsedTime(RtaTimer.StartTime, GetTime({ }))
end
PrintUtil.createOverlayLine(
"RtaTimer",
current_time,
MergeTables(
UIData.CurrentRunDepth.TextFormat,
{
justification = "left",
x_pos = 1820,
y_pos = 90,
}
)
)
end
function RtaTimer.StartRtaTimer()
RtaTimer.Running = true
while RtaTimer.Running do
RtaTimer.UpdateRtaTimer()
-- Update once per frame
wait(0.016)
end
end
ModUtil.WrapBaseFunction("WindowDropEntrance", function( baseFunc, ... )
local val = baseFunc(...)
-- If single run, timer should always restart
-- If multiweapon, only restart if timer was reset
if not config.MultiWeapon or RtaTimer.TimerWasReset then
RtaTimer.StartTime = GetTime({ })
RtaTimer.TimerWasReset = false
end
thread(RtaTimer.StartRtaTimer)
return val
end, RtaTimer)
-- Stop timer when Hades dies (but leave it on screen)
ModUtil.WrapBaseFunction("HadesKillPresentation", function( baseFunc, ...)
RtaTimer.Running = false
baseFunc(...)
end, RtaTimer)
ModUtil.LoadOnce(
function()
-- If not in a run, reset timer and prepare for run start
if CurrentRun.Hero.IsDead then
RtaTimer.TimerWasReset = true
-- If in a run, just start the timer from the time the mod was loaded
else
RtaTimer.TimerWasReset = false
RtaTimer.StartTime = GetTime({ })
thread(RtaTimer.StartRtaTimer)
end
end
) |
-- Revert massive buff of insulated wire recipe
bobmods.lib.recipe.set_energy_required('insulated-cable', 2)
seablock.lib.substingredient('insulated-cable', 'tinned-copper-cable', nil, 8)
seablock.lib.substingredient('insulated-cable', 'rubber', nil, 8)
bobmods.lib.recipe.set_result('insulated-cable', {'insulated-cable', 8})
|
#!/usr/bin/env tarantool
-- Those lines of code are for debug purposes only
-- So you have to ignore them
-- {{
package.preload['mqtt.driver'] = './mqtt/driver.so'
-- }}
box.cfg {wal_mode = 'none'}
local os = require('os')
local mqtt = require('mqtt')
local yaml = require('yaml')
local fiber = require('fiber')
local function F(...)
local desc, ok, emsg = ...
if not ok then
error(string.format("%s failed. Message = %s", desc, emsg))
end
return ...
end
local function E(...)
local desc, ok, emsg = ...
if ok then
error(string.format("%s it should be failed. Message = %s", desc, emsg))
end
return ...
end
local stat = { }
local function stat_inc(key)
if stat[key] == nil then
stat[key] = 0
end
stat[key] = stat[key] + 1
end
local conn = mqtt.new()
assert(type(conn.VERSION) == 'string')
F('on_connect', conn:on_connect(function(success, ret_code, message)
if not success then
print("can't connect msg = %s, ret_code = %d", message, ret_code)
os.exit(1)
end
stat_inc('on_connect')
end))
F('on_publish', conn:on_publish(function(mid)
stat_inc('on_publish')
end))
F('on_subscribe', conn:on_subscribe(function(mid, QoS)
stat_inc('on_subscribe')
end))
F('on_unsubscribe', conn:on_unsubscribe(function(mid)
stat_inc('on_unsubscribe')
end))
F('on_disconnect', conn:on_disconnect(
function(success, ret_code, message)
if not success then
print("can't connect msg = %s, ret_code = %d", message, ret_code)
os.exit(1)
end
stat_inc('on_disconnect')
end
))
F('on_message', conn:on_message(
function(mid, topic, payload, qos, retain)
stat_inc('on_message')
stat[topic .. '_' .. payload] = {mid=mid}
end
))
-- https://github.com/tarantool/mqtt/issues/6 [[
E('connect', conn:connect({port=1889}))
E('connect', conn:connect({host="www.does.not.exist"}))
E('connect', conn:connect({host="127.0.0.1", port=1889}))
E('publish', conn:publish('channel/in_1', 'data_1', 0, false))
E('subscribe', conn:subscribe('channel/in_1'))
E('reconnect', conn:reconnect())
-- ]]
-- Here is setup for defaul Rabbitmq MQTT provider.
-- (!) Except. login_set [[
F('tls_insecure_set', conn:tls_insecure_set(false))
F('connect', conn:connect({host="127.0.0.1", port=1883}))
F('login_set', conn:login_set('user', 'password'))
-- ]]
F('reconnect', conn:reconnect())
F('subscribe', conn:subscribe('some/topic'))
F('will_set', conn:will_set('some/topic', 'str', 0, false))
F('will_clear', conn:will_clear())
F('unsubscribe', conn:unsubscribe('some/topic'))
F('subscribe', conn:subscribe('channel/#'))
F('publish', conn:publish('channel/in_1', 'data_1', 0, false))
F('publish', conn:publish('channel/in_1', 'data_2', 0, false))
F('publish', conn:publish('channel/in_2', 'data_1', 0, false))
F('publish', conn:publish('channel/in_2', 'data_2', 0, false))
F('unsubscribe', conn:unsubscribe('channel/#'))
-- Join
print ("[+] Join result")
fiber.sleep(2.0)
assert(stat.on_message == stat.on_publish)
assert(stat.on_connect == 1)
assert(stat.on_subscribe == 2)
assert(stat['channel/in_1_data_1'] ~= nil)
assert(stat['channel/in_1_data_2'] ~= nil)
assert(stat['channel/in_2_data_1'] ~= nil)
assert(stat['channel/in_2_data_2'] ~= nil)
print ("[+] Done")
F('destroy', conn:destroy())
E('destroy', conn:destroy())
os.exit(0)
|
-- TODO - multi coloured
colours = {
{ name = "red", rgb = {r=1.0, g=0.0, b=0.0} },
{ name = "green", rgb = {r=0.0, g=1.0, b=0.0} },
{ name = "blue", rgb = {r=0.0, g=0.0, b=1.0} },
{ name = "yellow", rgb = {r=1.0, g=1.0, b=0.0} },
{ name = "magenta", rgb = {r=1.0, g=0.0, b=1.0} },
{ name = "cyan", rgb = {r=0.0, g=1.0, b=1.0} },
{ name = "white", rgb = {r=1.0, g=1.0, b=1.0} },
}
fireworks = {
{
name = "flare",
cooldown = 30,
range = 50,
speed = 0.3,
ingredients = { {"grenade", 1} },
stages =
{
{ name = "A", sprite = "flare", explosion="flash", light = {intensity = 0.3, size = 80 }, duration = 60 }
},
display = nil
},
{
name = "firework-large",
cooldown = 30,
range = 50,
speed = 0.3,
ingredients = { {"grenade", 3} },
stages =
{
{ name = "A", sprite = "star", explosion="flash", light = { intensity = 0.9, size = 4 }, duration = 0.1, fragments = 24, fragment_distance = 12, fragment_speed = 0.2 },
{ name = "B", sprite = "spark", explosion="flash", light = { intensity = 0.9, size = 4 }, duration = 0.1 }
},
display = {
budget = 3
}
},
{
name = "firework-medium",
cooldown = 30,
range = 50,
speed = 0.3,
ingredients = { {"grenade", 2} },
stages =
{
{ name = "A", sprite = "star", light = { intensity = 0.9, size = 1 }, duration = 0.1, fragments = 8, fragment_distance = 8, fragment_speed = 0.2 },
{ name = "B", sprite = "spark", light = { intensity = 0.9, size = 1 }, duration = 0.1, fragments = 6, fragment_distance = 4, fragment_speed = 0.3 },
{ name = "C", sprite = "spark", explosion="flash", light = { intensity = 0.9, size = 1 }, duration = 0.1 }
},
display = {
budget = 2
}
},
{
name = "firework-small",
cooldown = 30,
range = 50,
speed = 0.3,
ingredients = { {"grenade", 1} },
stages =
{
{ name = "A", sprite = "star", smoke="sparks", light = { intensity = 0.9, size = 2 }, duration = 0.1, fragments = 12, fragment_distance = 8, fragment_speed = 0.3 },
{ name = "B", sprite = "spark", explosion="flash", smoke="sparks", light = { intensity = 0.9, size = 2 }, duration = 0.1 }
},
display = {
budget = 1
}
}
}
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(..., package.seeall)
local ffi = require("ffi")
local C = ffi.C
local S = require("syscall")
local lib = require("core.lib")
local shm = require("core.shm")
local counter = require("core.counter")
local histogram = require("core.histogram")
local usage = require("program.top.README_inc")
local ethernet = require("lib.protocol.ethernet")
local file = require("lib.stream.file")
local fiber = require("lib.fibers.fiber")
local sleep = require("lib.fibers.sleep")
local op = require("lib.fibers.op")
local cond = require("lib.fibers.cond")
local channel = require("lib.fibers.channel")
local inotify = require("lib.ptree.inotify")
local rrd = require("lib.rrd")
-- First, the global state for the app.
--
local snabb_state = { instances={}, counters={}, histograms={}, rrds={} }
local ui = {
view='interface',
sample_time=nil, sample=nil, prev_sample_time=nil, prev_sample=nil,
tree=nil, focus=nil, wake=cond.new(), rows=24, cols=80,
show_empty=false, show_rates=true,
show_links=true, show_apps=true, show_engine=true,
pause_time=nil }
local function needs_redisplay(keep_tree)
if not keep_tree then ui.tree = nil end
ui.wake:signal()
end
-- Now the core code that monitors /var/run/snabb and updates
-- snabb_state.
--
local function is_dir(name)
local stat = S.lstat(name)
return stat and stat.isdir
end
local function dirsplit(name)
return name:match("^(.*)/([^/]+)$")
end
local function instance_monitor()
local tx = channel.new()
local by_name_root = shm.root..'/by-name'
local by_pid = inotify.directory_inventory_events(shm.root)
local by_name = inotify.directory_inventory_events(by_name_root)
local either = op.choice(by_pid:get_operation(), by_name:get_operation())
fiber.spawn(function()
local by_pid, by_name = {}, {}
for event in either.perform, either do
if event.kind == 'mkdir' or event.kind == 'rmdir' then
-- Ignore; this corresponds to the directories being monitored.
elseif event.kind == 'add' then
local dirname, basename = dirsplit(event.name)
if dirname == shm.root then
local pid = tonumber(basename)
if pid and is_dir(event.name) and not by_pid[pid] and pid ~= S.getpid() then
by_pid[pid] = {name=nil}
tx:put({kind="new-instance", pid=pid})
end
elseif dirname == by_name_root then
local pid_dir = S.readlink(event.name)
if pid_dir then
local root, pid_str = dirsplit(pid_dir)
local pid = pid_str and tonumber(pid_str)
if pid and root == shm.root and not by_name[basename] then
by_name[basename] = pid
tx:put({kind="new-name", name=basename, pid=pid})
end
end
end
elseif event.kind == 'remove' then
local dirname, basename = dirsplit(event.name)
if dirname == shm.root then
local pid = tonumber(basename)
if pid and by_pid[pid] then
by_pid[pid] = nil
tx:put({kind="instance-gone", pid=pid})
end
elseif dirname == by_name_root then
local pid = by_name[basename]
if pid then
by_name[basename] = nil
tx:put({kind="name-gone", name=basename, pid=pid})
end
end
else
println('unexpected event: %s', event.kind, name)
end
end
end)
return tx
end
local function monitor_snabb_instance(pid, instance, counters, histograms, rrds)
local dir = shm.root..'/'..pid
local rx = inotify.recursive_directory_inventory_events(dir)
local rx_op = rx:get_operation()
fiber.spawn(function ()
while true do
local event = rx_op:perform()
if event == nil then break end
local name = event.name:sub(#dir + 2):match('^(.*)%.counter$')
if name then
if event.kind == 'creat' then
local ok, c = pcall(counter.open, event.name:sub(#shm.root+1))
if ok then counters[name] = c end
needs_redisplay()
elseif event.kind == 'rm' then
pcall(counter.delete, counters[name])
counters[name] = nil
needs_redisplay()
end
elseif event.name == dir..'/group' then
local target = S.readlink(event.name)
if target and event.kind == 'creat' then
local dir, group = dirsplit(target)
local root, pid = dirsplit(dir)
instance.group = tonumber(pid)
else
instance.group = nil
end
needs_redisplay()
elseif event.name:match('%.histogram$') then
local name = event.name:sub(#dir + 2):match('^(.*)%.histogram')
if event.kind == 'creat' then
local ok, h = pcall(histogram.open, event.name:sub(#shm.root+1))
if ok then histograms[name] = h end
needs_redisplay()
elseif event.kind == 'rm' then
-- FIXME: no delete!
-- pcall(histogram.delete, counters[name])
histograms[name] = nil
needs_redisplay()
end
elseif event.name:match('%.rrd') then
local name = event.name:sub(#dir + 2):match('^(.*)%.rrd')
if event.kind == 'creat' then
local ok, r = pcall(rrd.open_file, event.name)
if ok then rrds[name] = r end
needs_redisplay()
elseif event.kind == 'rm' then
rrds[name] = nil
needs_redisplay()
end
end
end
end)
end
local function update_snabb_state()
local rx = instance_monitor()
local pending = {}
local instances = snabb_state.instances
local counters, histograms = snabb_state.counters, snabb_state.histograms
local rrds = snabb_state.rrds
for event in rx.get, rx do
local kind, name, pid = event.kind, event.name, event.pid
if kind == 'new-instance' then
instances[pid], pending[pid] = { name = pending[pid] }, nil
counters[pid], histograms[pid], rrds[pid] = {}, {}, {}
monitor_snabb_instance(pid, instances[pid], counters[pid],
histograms[pid], rrds[pid])
elseif kind == 'instance-gone' then
instances[pid], pending[pid] = nil, nil
counters[pid], histograms[pid], rrds[pid] = nil, nil, nil
if ui.focus == pid then ui.focus = nil end
elseif kind == 'new-name' then
if instances[pid] then instances[pid].name = name
else pending[pid] = name end
elseif kind == 'name-gone' then
instances[pid].name, pending[pid] = nil, nil
end
needs_redisplay()
end
end
-- Now we start on the UI. First, here are some low-level interfaces
-- for working with terminals.
--
local function clearterm () io.write('\027[2J') end
local function move(x,y) io.write(string.format('\027[%d;%dH', x, y)) end
local function dsr() io.write(string.format('\027[6n')) end
local function newline() io.write('\027[K\027[E') end
local function printf(fmt, ...) io.write(fmt:format(...)) end
local function println(fmt, ...) printf(fmt, ...); newline(); io.flush() end
local function sgr(fmt,...) io.write('\027['..fmt:format(...)..'m') end
local function scroll(n) io.write(string.format('\027[%dS', n)) end
local function bgcolordefault(n) sgr('49') end
local function fgcolordefault(n) sgr('39') end
local function bgcolor8(n) sgr('48;5;%d', n) end
local function fgcolor8(n) sgr('38;5;%d', n) end
local function bgcolor24(r,g,b) sgr('48;2;%d;%d;%d', r, g, b) end
local function fgcolor24(r,g,b) sgr('38;2;%d;%d;%d', r, g, b) end
local function request_dimensions() move(1000, 1000); dsr(); io.flush() end
local function makeraw (tc)
local ret = S.t.termios()
ffi.copy(ret, tc, ffi.sizeof(S.t.termios))
ret:makeraw()
return ret
end
-- Since we put the terminal into raw mode, we'll need to associate
-- functionality for all keys, and also handle all the escape sequences.
-- Here we set up key binding tables.
--
local function make_key_bindings(default_binding)
local ret = {}
for i=0,255 do ret[string.char(i)] = default_binding end
return ret
end
local function bind_keys(k, f, bindings)
if bindings == nil then bindings = global_key_bindings end
for i=1,#k do bindings[k:sub(i,i)] = f end
end
local function debug_keypress(c)
println('read char: %s (%d)', c, string.byte(c))
end
global_key_bindings = make_key_bindings(debug_keypress)
do
local function unknown_csi(kind, ...)
println('unknown escape-[: %s (%d)', kind, string.byte(kind))
end
csi_key_bindings = make_key_bindings(unknown_csi)
local function csi_current_position(kind, rows, cols)
ui.rows, ui.cols = rows or 24, cols or 80
needs_redisplay(true)
end
bind_keys("R", csi_current_position, csi_key_bindings)
escape_key_bindings = make_key_bindings(fiber.stop)
local function unknown(c)
println('unknown escape sequence: %s (%d)', c, string.byte(c))
end
for i=0x40,0x5f do
bind_keys(string.char(i), unknown, escape_key_bindings)
end
local function read_int()
local ret = 0
for c in io.stdin.peek_char, io.stdin do
local dec = c:byte() - ("0"):byte()
if 0 <= dec and dec <= 9 then
io.stdin:read_char()
ret = ret * 10 + dec
else
return ret
end
end
end
local function csi()
local args = {}
while true do
local ch = io.stdin:peek_char()
if not ch then break end
if not ch:match('[%d;]') then break end
table.insert(args, read_int())
if io.stdin:peek_char() == ';' then io.stdin:read_char() end
end
-- FIXME: there are some allowable characters here.
local kind = io.stdin:read_char()
csi_key_bindings[kind](kind, unpack(args))
end
bind_keys("[", csi, escape_key_bindings)
local function escape_sequence()
if io.stdin.rx:is_empty() then
-- In theory we should see if stdin is readable, and if not wait
-- for a small timeout. However since the input buffer is
-- relatively large, it's unlikey that we'd read an ESC without
-- more bytes unless it's the user wanting to quit the program.
return fiber.stop()
end
local kind = io.stdin:read_char()
escape_key_bindings[kind](kind)
end
bind_keys("\27", escape_sequence)
end
-- React to SIGWINCH by telling the terminal to give us its dimensions
-- via the CSI current position escape sequence.
local function monitor_sigwinch()
local f = file.fdopen(assert(S.signalfd("winch")))
S.sigprocmask("block", "winch")
local buf = ffi.new('uint8_t[128]')
while f:read_some_bytes(buf, 128) > 0 do
request_dimensions()
end
end
-- Right! So we have machinery to know what Snabb instances there are,
-- and we have basic primitives for input and output. The plan is that
-- we'll write functions for rendering the state to the screen; here we
-- go!
--
local function sortedpairs(t)
local keys = {}; for k,_ in pairs(t) do table.insert(keys, k) end
table.sort(keys)
local f, s, i = ipairs(keys)
return function()
local k
i, k = f(s, i)
if i then return k, t[k] end
end
end
local function summarize_histogram(histogram, prev)
local total = histogram.total
if prev then total = total - prev.total end
if total == 0 then return 0, 0, 0 end
local min, max, cumulative = nil, 0, 0
for count, lo, hi in histogram:iterate(prev) do
if count ~= 0 then
if not min then min = lo end
max = hi
cumulative = cumulative + (lo + hi) / 2 * tonumber(count)
end
end
local avg = cumulative / tonumber(total)
return min * 1e6, avg * 1e6, max * 1e6
end
local leaf_mt = {}
local function make_leaf(value, rrd)
return setmetatable({value=value, rrd=rrd}, leaf_mt)
end
local function is_leaf(x) return getmetatable(x) == leaf_mt end
local function compute_histograms_tree(histograms)
if histograms == nil then return {} end
local ret = {}
for k,v in pairs(histograms) do
local branches, leaf = dirsplit(k)
local parent = ret
for branch in branches:split('/') do
if parent[branch] == nil then parent[branch] = {} end
parent = parent[branch]
end
parent[leaf] = make_leaf(function() return v:snapshot() end)
end
return ret
end
local function compute_counters_tree(counters, rrds)
if counters == nil then return {} end
local ret = {}
for k,v in pairs(counters) do
local branches, leaf = dirsplit(k)
if leaf ~= 'dtime' then
local parent = ret
for branch in branches:split('/') do
if parent[branch] == nil then parent[branch] = {} end
parent = parent[branch]
end
parent[leaf] = make_leaf(
function() return counter.read(v) end, rrds[k])
end
end
-- The rxpackets and rxbytes link counters are redundant.
if ret.links then
local links = {}
for link, counters in pairs(ret.links) do
links[link] = { txpackets=counters.txpackets,
txbytes=counters.txbytes,
txdrop=counters.txdrop }
end
ret.links = links
end
return ret
end
local function adjoin(t, k, v)
if t[k] == nil then t[k] = v; return end
if t[k] == v then return end
assert(type(t[k]) == 'table' and not is_leaf(t[k]))
assert(type(v) == 'table' and not is_leaf(v))
for vk, vv in pairs(v) do adjoin(t[k], vk, vv) end
end
-- Return a tree that presents the set of Snabb instances in a tree,
-- where workers are nested inside their parents, and the counters and
-- histograms are part of that tree as well.
local function compute_tree()
local parents = {}
for pid, instance in pairs(snabb_state.instances) do
parents[pid] = instance.group or pid
end
local root = {}
for pid,parent_pid in pairs(parents) do
local parent_instance = snabb_state.instances[parent_pid]
local parent_name = (parent_instance and parent_instance.name) or tostring(parent_pid)
if root[parent_name] == nil then root[parent_name] = {} end
local parent_node = root[parent_name]
local node
if parent_pid == pid then
node = parent_node
else
node = {}
if parent_node.workers == nil then parent_node.workers = {} end
parent_node.workers[pid] = node
end
node.pid = pid
for k,v in pairs(compute_histograms_tree(snabb_state.histograms[pid])) do
adjoin(node, k, v)
end
for k,v in pairs(compute_counters_tree(snabb_state.counters[pid],
snabb_state.rrds[pid] or {})) do
adjoin(node, k, v)
end
end
return root
end
local function nil_if_empty(x)
for k,v in pairs(x) do return x end
return nil
end
-- The ui.tree just represents the structure of the state. Before we go
-- to show that state, we need to sample the associated values (the
-- counters and histograms). Additionally at this point we'll prune out
-- data that the user doesn't want to see.
local function sample_tree(tree)
local ret = {}
for k,v in pairs(tree) do
if is_leaf(v) then v = make_leaf(v.value(), v.rrd)
elseif type(v) == 'table' then v = sample_tree(v) end
ret[k] = v
end
return nil_if_empty(ret)
end
local function prune_sample(tree)
local function prune(name, tree)
if name == 'apps' and not ui.show_apps then return nil end
if name == 'links' and not ui.show_links then return nil end
if name == 'engine' and not ui.show_engine then return nil end
if is_leaf(tree) then
if not ui.show_empty and tonumber(tree.value) == 0 then return nil end
elseif type(tree) == 'table' then
local ret = {}
for k,v in pairs(tree) do ret[k] = prune(k, v) end
return nil_if_empty(ret)
end
return tree
end
local function prune_instance(instance)
local ret = {}
if instance.workers then
ret.workers = {}
for k,v in pairs(instance.workers) do
ret.workers[k] = prune_instance(v)
end
ret.workers = nil_if_empty(ret.workers)
end
if ui.focus == nil or ui.focus == instance.pid then
for k,v in pairs(instance) do
if k ~= 'workers' then ret[k] = prune(k, v) end
end
end
return nil_if_empty(ret)
end
local ret = {}
for k,v in pairs(tree) do ret[k] = prune_instance(v) end
return ret
end
local function compute_rate(v, prev, rrd, t, dt)
if ui.pause_time and t ~= ui.pause_time then
if not rrd then return 0 end
for name,source in pairs(rrd:ref(ui.pause_time)) do
for _,reading in ipairs(source.cf.average) do
return reading.value
end
end
return 0/0
elseif prev then
return tonumber(v - prev)/dt
else
return 0/0
end
end
local function scale(x)
x=tonumber(x)
for _,scale in ipairs {{'T', 1e12}, {'G', 1e9}, {'M', 1e6}, {'k', 1e3}} do
local tag, base = unpack(scale)
if x > base then return x/base, tag end
end
return x, ''
end
local compute_display_tree = {}
local macaddr_string
do
local buf = ffi.new('union { uint64_t u64; uint8_t bytes[6]; }')
function macaddr_string(n)
-- The app read out the address and wrote it to the counter as a
-- uint64, just as if it aliased the address. So, to get the
-- right byte sequence, we can do the same, without swapping.
buf.u64 = n
return ethernet:ntop(buf.bytes)
end
end
-- The state renders to a nested display tree, consisting of "group",
-- "rows", "grid", and "chars" elements.
function compute_display_tree.tree(tree, prev, dt, t)
local function chars(align, fmt, ...)
return {kind='chars', align=align, contents=fmt:format(...)}
end
local function lchars(fmt, ...) return chars('left', fmt, ...) end
tree = prune_sample(tree)
local function visit(tree, prev)
local ret = {kind='rows', contents={}}
for k, v in sortedpairs(tree) do
local prev = prev and prev[k]
local rrd
if is_leaf(v) then
v, rrd = v.value, v.rrd
if is_leaf(prev) then prev = prev.value else prev = nil end
elseif type(v) ~= type(prev) then
prev = nil
end
if type(v) ~= 'table' then
local out
if type(v) == 'cdata' and tonumber(v) then
local units
if k:match('packets') then units = 'PPS'
elseif k:match('bytes') then units = 'bytes/s'
elseif k:match('bits') then units = 'bps'
elseif k:match('breath') then units = 'breaths/s'
elseif k:match('drop') then units = 'PPS'
end
local show_rates = units or tonumber(v) ~= tonumber(prev)
show_rates = show_rates and ui.show_rates
show_rates = show_rates or (ui.pause_time and ui.pause_time ~= t)
if show_rates then
local rate = compute_rate(v, prev, rrd, t, dt)
local v, tag = scale(rate)
out = lchars("%s: %.3f %s%s", k, v, tag, units or "/sec")
elseif k:match('macaddr') then
out = lchars("%s: %s", k, macaddr_string(v))
else
out = lchars("%s: %s", k, lib.comma_value(v))
end
elseif type(v) == 'cdata' then
-- Hackily, assume that the value is a histogram.
out = lchars('%s: %.2f min, %.2f avg, %.2f max',
k, summarize_histogram(v, prev))
else
out = lchars("%s: %s", k, tostring(v))
end
table.insert(ret.contents, out)
end
end
for k, v in sortedpairs(tree) do
if type(v) == 'table' and not is_leaf(v) then
local has_prev = prev and type(prev[k]) == type(v)
local rows = visit(v, has_prev and prev[k])
table.insert(ret.contents, {kind='group', label=k, contents=rows})
end
end
return ret
end
return {kind='rows',
contents={lchars('snabb top: %s',
os.date('%Y-%m-%d %H:%M:%S', ui.pause_time or t)),
lchars('----'),
visit(tree, prev)}}
end
function compute_display_tree.interface(tree, prev, dt, t)
local function chars(align, fmt, ...)
return {kind='chars', align=align, contents=fmt:format(...)}
end
local function lchars(fmt, ...) return chars('left', fmt, ...) end
local function cchars(fmt, ...) return chars('center', fmt, ...) end
local function rchars(fmt, ...) return chars('right', fmt, ...) end
local grid = {}
local rows = {
kind='rows',
contents = {
lchars('snabb top: %s',
os.date('%Y-%m-%d %H:%M:%S', ui.pause_time or t)),
lchars('----'),
{kind='grid', width=6, shrink={true,true}, contents=grid}
}}
local function gridrow(...) table.insert(grid, {...}) end
-- name or \---, pid, breaths/s, latency
-- \- pci device, macaddr, mtu, speed
-- RX: PPS, bps, %, [drops/s]
-- TX: PPS, bps, %, [drops/s]
local function rate(key, counters, prev)
if not counters then return 0/0 end
if not counters[key] then return 0/0 end
local v, rrd = counters[key], nil
prev = prev and prev[key]
if is_leaf(v) then
v, rrd, prev = v.value, v.rrd, is_leaf(prev) and prev.value or nil
end
return compute_rate(v, prev, rrd, t, dt)
end
local function show_traffic(tag, pci, prev)
local pps = rate(tag..'packets', pci, prev)
local bytes = rate(tag..'bytes', pci, prev)
local drops = rate(tag..'drop', pci, prev)
-- 7 bytes preamble, 1 start-of-frame, 4 CRC, 12 interframe gap.
local overhead = (7 + 1 + 4 + 12) * pps
local bps = (bytes + overhead) * 8
local max = tonumber(pci.speed and pci.speed.value) or 0
gridrow(nil,
rchars('%s:', tag:upper()),
lchars('%.3f %sPPS', scale(pps)),
lchars('%.3f %sbps', scale(bps)),
lchars('%.2f%%', bps/max*100),
drops > 0 and rchars('%.3f %sPPS dropped', scale(drops)) or nil)
end
local function show_pci(addr, pci, prev)
local bps, tag = scale(tonumber(pci.speed and pci.speed.value) or 0)
gridrow(rchars('| '), lchars(''))
gridrow(rchars('\\-'),
rchars('%s:', addr),
lchars('%d %sbE, MAC: %s', bps, tag,
macaddr_string(tonumber(pci.macaddr and pci.macaddr.value) or 0)))
show_traffic('rx', pci, prev)
show_traffic('tx', pci, prev)
end
local function union(dst, src)
if type(src) == 'table' and not is_leaf(src) then
for k, v in pairs(src) do
if dst[k] == nil then
dst[k] = v
elseif not is_leaf(v) and not is_leaf(dst[k]) then
union(dst[k], v)
end
end
end
end
local function find_pci_devices(node, ret)
ret = ret or {}
if type(node) == 'table' and not is_leaf(node) then
for k, v in pairs(node) do
if k == 'pci' then
union(ret, v)
else
find_pci_devices(v, ret)
end
end
end
return ret
end
local function show_instance(label, instance, prev)
local pci, prev_pci = find_pci_devices(instance), find_pci_devices(prev)
local engine, prev_engine = instance.engine, prev and prev.engine
local latency = engine and engine.latency and engine.latency.value
local latency_str = ''
if latency then
local prev = prev_engine and prev_engine.latency and prev_engine.latency.value
latency_str = string.format('latency: %.2f min, %.2f avg, %.2f max',
summarize_histogram(latency, prev))
end
gridrow(label,
lchars('PID %s:', instance.pid),
lchars('%.2f %sbreaths/s',
scale(rate('breaths', engine, prev_engine))),
lchars('%s', latency_str))
if instance.workers then
for pid, instance in sortedpairs(instance.workers) do
local prev = prev and prev.workers and prev.workers[pid]
gridrow(rchars('| '), lchars(''))
show_instance(rchars('\\---'), instance, prev)
end
else
-- Note, PCI tree only shown on instances without workers.
for addr, pci in sortedpairs(pci) do
show_pci(addr, pci, prev_pci[addr])
end
end
end
for name, instance in sortedpairs(tree) do
gridrow(lchars(''))
show_instance(lchars('%s', name), instance, prev and prev[name])
end
return rows
end
local function compute_span(row, j, columns)
local span = 1
while j + span <= columns and row[j+1] == nil do
span = span + 1
end
return span
end
-- A tree is nice for data but we have so many counters that really we
-- need to present them as a grid. So, the next few functions try to
-- reorient "rows" display tree instances into "grid".
local function compute_min_width(tree)
if tree.kind == 'group' then
return 2 + compute_min_width(tree.contents)
elseif tree.kind == 'rows' then
local width = 0
for _,tree in ipairs(tree.contents) do
width = math.max(width, compute_min_width(tree))
end
return width
elseif tree.kind == 'grid' then
local columns, width = tree.width, 0
for j=1,columns do
local col_width = 0
for i=1,#tree.contents do
local row = tree.contents[i]
local tree = row[j]
if tree then
local span = compute_span(row, j, columns)
local item_width = compute_min_width(tree)
col_width = math.max(col_width, math.ceil(item_width / span))
end
end
width = width + col_width
end
return width
else
assert(tree.kind == 'chars')
return #tree.contents
end
end
local function compute_height(tree)
if tree.kind == 'group' then
return 1 + compute_height(tree.contents)
elseif tree.kind == 'rows' then
local height = 0
for _,tree in ipairs(tree.contents) do
height = height + compute_height(tree)
end
return height
elseif tree.kind == 'grid' then
local height = 0
for i=1,#tree.contents do
local row_height = 0
for j=1,tree.width do
local tree = tree.contents[i][j]
row_height = math.max(row_height, compute_height(tree))
end
height = height + row_height
end
return height
else
assert(tree.kind == 'chars')
return 1
end
end
local function has_compatible_height(tree, height)
if height <= 0 then
return false
elseif tree.kind == 'group' then
return has_compatible_height(tree.contents, height - 1)
elseif tree.kind == 'rows' then
for _,tree in ipairs(tree.contents) do
height = height - compute_height(tree)
if height <= 0 then return false end
end
return height <= 2
elseif tree.kind == 'chars' then
return height <= 2
else
return false
end
end
local function should_make_grid(tree, indent)
if #tree.contents <= 1 then return 1 end
local width = compute_min_width(tree) + indent
-- Maximum column width of 80.
if width > 80 then return 1 end
-- Minimum column width of 50.
width = math.max(width, 50)
local count = math.floor(ui.cols / width)
if count < 2 then return 1 end
-- Only make a grid out of similar rows.
local contents = tree.contents
local kind, height = contents[1].kind, compute_height(contents[1])
for i=2,#contents do
if contents[i].kind ~= kind then return 1 end
if not has_compatible_height(contents[i], height) then return 1 end
end
return count -- math.min(count, #contents)
end
local function create_grids(tree, indent)
indent = indent or 0
if tree.kind == 'rows' then
local columns = should_make_grid(tree, indent)
if columns > 1 then
local rows = math.ceil(#tree.contents/columns)
local contents = {}
for i=1,rows do
contents[i] = {}
end
for i,tree in ipairs(tree.contents) do
local row, col = ((i-1)%rows)+1, math.ceil(i/rows)
contents[row][col] = tree
end
return {kind='grid', width=columns, contents=contents}
else
local contents = {}
for i,tree in ipairs(tree.contents) do
contents[i] = create_grids(tree, indent)
end
return {kind='rows', contents=contents}
end
elseif tree.kind == 'group' then
return {kind='group', label=tree.label,
contents=create_grids(tree.contents, indent + 2)}
else return tree end
end
-- Finally, here we render the display tree to the screen. Our code
-- always renders a full screen, even when only part of the state
-- changes. We could make that more efficient in the future.
local render = {}
local function render_display_tree(tree, row, col, width)
if row >= ui.rows then
local msg = '[truncated]'
move(ui.rows-1, ui.cols - #msg)
io.write(msg)
return row
else
return assert(render[tree.kind])(tree, row, col, width)
end
end
function render.group(tree, row, col, width)
move(row, col)
printf("%s:", tree.label)
return render_display_tree(tree.contents, row + 1, col + 2, width - 2)
end
function render.rows(tree, row, col, width)
move(row, col)
for _,tree in ipairs(tree.contents) do
row = render_display_tree(tree, row, col, width)
end
return row
end
local function allocate_column_widths(rows, cols, shrink, width)
local widths, expand, total = {}, 0, 0
for j=1,cols do
local col_width = 0
for _,row in ipairs(rows) do
if row[j] then
local span = compute_span(row, j, cols)
local item_width = compute_min_width(row[j])
col_width = math.max(col_width, math.ceil(item_width / span))
end
end
widths[j], total = col_width, total + col_width
if not shrink[j] then expand = expand + 1 end
end
-- Truncate from the right.
for j=1,cols do
-- Inter-column spacing before this column.
local spacing = j - 1
if total + spacing <= width then break end
local trim = math.min(widths[j], total + spacing - width)
widths[j], total = widths[j] - trim, total - trim
end
-- Allocate slack to non-shrinking columns.
for j=1,cols do
if not shrink[j] then
local spacing = j - 1
local pad = math.floor((width-total-spacing)/expand)
widths[j], total, expand = widths[j] + pad, total + pad, expand - 1
end
end
return widths
end
function render.grid(tree, row, col, width)
local widths = allocate_column_widths(
tree.contents, tree.width, tree.shrink or {}, width)
for i=1,#tree.contents do
local next_row = row
local endcol = col + width
local col = endcol
for j=tree.width,1,-1 do
local tree = tree.contents[i][j]
col = col - widths[j]
if tree then
local width = endcol - col
next_row = math.max(
next_row, render_display_tree(tree, row, col, endcol - col))
-- Spacing.
endcol = col - 1
end
-- Spacing.
col = col - 1
end
row = next_row
end
return row
end
function render.chars(tree, row, col, width)
local str = tree.contents
if #str > width then
move(row, col)
io.write(str:sub(1,width))
else
local advance = 0
if tree.align=='right' then advance = width - #str
elseif tree.align=='center' then advance = math.floor((width - #str)/2)
else advance = 0 end
move(row, col + advance)
io.write(tree.contents)
end
return row + 1
end
-- The status line tells the user what keys are available, and also
-- tells them what the current state is (e.g. apps hidden).
local function render_status_line()
local function showhide(key, what)
if ui['show_'..what] then return key..'=hide '..what end
return key..'=show '..what
end
local entries = {}
table.insert(entries, 'q=quit')
if ui.pause_time then
table.insert(entries, 'SPACE=unpause')
table.insert(entries, '[=rewind 1s')
table.insert(entries, ']=advance 1s')
table.insert(entries, '{=rewind 60s')
table.insert(entries, '}=advance 60s')
else
table.insert(entries, 'SPACE=pause')
end
if ui.view == 'interface' then
table.insert(entries, 't=tree view')
else
for _,e in ipairs { 'i=interface view', showhide('a', 'apps'),
showhide('l', 'links'), showhide('e', 'engine'),
showhide('0', 'empty'), showhide('r', 'rates') } do
table.insert(entries, e)
end
local instances = 0
for pid, _ in sortedpairs(snabb_state.instances) do
instances = instances + 1
end
if instances > 1 then
if ui.focus then table.insert(entries, 'u=unfocus '..ui.focus) end
table.insert(entries, '<=focus prev')
table.insert(entries, '>=focus next')
end
end
local col_width, count = 0, 0
for i,entry in ipairs(entries) do
local width = math.max(col_width, #entry + 2)
if width * (count + 1) <= ui.cols then
col_width, count = width, count + 1
else
break
end
end
for i=1,count do
move(ui.rows, 1 + (i-1)*col_width)
io.write(entries[i])
end
end
local function refresh()
move(1,1)
clearterm()
local dt
if ui.prev_sample_time then dt = ui.sample_time - ui.prev_sample_time end
local tree = compute_display_tree[ui.view](
ui.sample, ui.prev_sample, dt, ui.sample_time)
tree = create_grids(tree)
render_display_tree(tree, 1, 1, ui.cols)
render_status_line()
io.flush()
end
local function show_ui()
request_dimensions()
fiber.spawn(monitor_sigwinch)
while true do
local s = snabb_state
if ui.tree == nil then
ui.tree = compute_tree() or {}
ui.prev_sample, ui.prev_sample_time = nil, nil
end
if not ui.pause_time then
ui.prev_sample_time, ui.prev_sample = ui.sample_time, ui.sample
ui.sample_time, ui.sample = rrd.now(), sample_tree(ui.tree) or {}
end
refresh()
ui.wake:wait()
ui.wake = cond.new()
-- Limit UI refresh rate to 40 Hz.
if ui.interactive then sleep.sleep(0.025) end
end
end
-- Tell the display to refresh every second.
local function refresh_display()
while true do
sleep.sleep(1)
needs_redisplay(true)
end
end
-- Here we wire up some more key bindings.
local function in_view(view, f)
return function() if ui.view == view then f() end end
end
local function toggle(tab, k)
return function() tab[k] = not tab[k]; needs_redisplay(true) end
end
local function sortedkeys(t)
local ret = {}
for k,v in sortedpairs(t) do table.insert(ret, k) end
return ret
end
local function focus_prev()
local pids = sortedkeys(snabb_state.instances)
if #pids < 2 then return end
if ui.focus == nil or ui.focus == pids[1] then
ui.focus = pids[#pids]
else
for i,pid in ipairs(pids) do
if pid == ui.focus then
ui.focus = pids[i-1]
break
end
end
end
needs_redisplay(true)
end
local function focus_next()
local pids = sortedkeys(snabb_state.instances)
if #pids < 2 then return end
if ui.focus == nil or ui.focus == pids[#pids] then
ui.focus = pids[1]
else
for i,pid in ipairs(pids) do
if pid == ui.focus then
ui.focus = pids[i+1]
break
end
end
end
needs_redisplay(true)
end
local function unfocus()
ui.focus = nil
needs_redisplay(true)
end
local function tree_view()
ui.view = 'tree'
needs_redisplay(true)
end
local function interface_view()
ui.view = 'interface'
needs_redisplay(true)
end
local function toggle_paused()
if ui.pause_time then
ui.pause_time = nil
else
ui.pause_time = ui.sample_time or rrd.now()
end
needs_redisplay(true)
end
local function rewind(secs)
return function()
if not ui.sample_time then return end -- Ensure we have a sample.
if not ui.pause_time then return end -- Only work when paused.
ui.pause_time = ui.pause_time - secs
needs_redisplay(true)
end
end
bind_keys("0", in_view('tree', toggle(ui, 'show_empty')))
bind_keys("r", in_view('tree', toggle(ui, 'show_rates')))
bind_keys("l", in_view('tree', toggle(ui, 'show_links')))
bind_keys("a", in_view('tree', toggle(ui, 'show_apps')))
bind_keys("e", in_view('tree', toggle(ui, 'show_engine')))
bind_keys(" ", toggle_paused)
bind_keys("u", in_view('tree', unfocus))
bind_keys("t", in_view('interface', tree_view))
bind_keys("i", in_view('tree', interface_view))
bind_keys("[", rewind(1))
bind_keys("]", rewind(-1))
bind_keys("{", rewind(60))
bind_keys("}", rewind(-60))
bind_keys("<", in_view('tree', focus_prev))
bind_keys(">", in_view('tree', focus_next))
bind_keys("AD", global_key_bindings['<'], csi_key_bindings) -- Left and up arrow.
bind_keys("BC", global_key_bindings['>'], csi_key_bindings) -- Right and down arrow.
bind_keys("q\3\31\4", fiber.stop) -- C-d, C-/, q, and C-c.
local function handle_input ()
for c in io.stdin.read_char, io.stdin do
global_key_bindings[c](c)
end
fiber.stop()
end
-- Finally, here's the code!
function run (args)
local opt = {}
function opt.h (arg) print(usage) main.exit(1) end
args = lib.dogetopt(args, opt, "h", {help='h'})
if #args ~= 0 then print(usage) main.exit(1) end
require('lib.fibers.file').install_poll_io_handler()
require('lib.stream.compat').install()
ui.interactive = S.stdin:isatty() and S.stdout:isatty()
if ui.interactive then
ui.saved_tc = assert(S.tcgetattr(S.stdin))
local new_tc = makeraw(ui.saved_tc)
assert(S.tcsetattr(S.stdin, 'drain', new_tc))
scroll(1000)
end
fiber.spawn(update_snabb_state)
fiber.spawn(handle_input)
fiber.spawn(show_ui)
if ui.interactive then
fiber.spawn(refresh_display)
fiber.main()
assert(S.tcsetattr(S.stdin, 'drain', ui.saved_tc))
bgcolordefault()
fgcolordefault()
io.stdout:write_chars('\n')
else
-- FIXME: This doesn't work currently.
local sched = fiber.current_scheduler
while #sched.next > 0 do
sched:run()
sched:schedule_tasks_from_sources()
end
end
end
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:29' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
local CreateLinkAccount_Console = ZO_Object:Subclass()
function CreateLinkAccount_Console:New(control)
local object = ZO_Object.New(self)
object:Initialize(control)
return object
end
function CreateLinkAccount_Console:Initialize(control)
self.control = control
local createLinkAccountScreen_Gamepad_Fragment = ZO_FadeSceneFragment:New(self.control)
CREATE_LINK_ACCOUNT_SCREEN_GAMEPAD_SCENE = ZO_Scene:New("CreateLinkAccountScreen_Gamepad", SCENE_MANAGER)
CREATE_LINK_ACCOUNT_SCREEN_GAMEPAD_SCENE:AddFragment(createLinkAccountScreen_Gamepad_Fragment)
CREATE_LINK_ACCOUNT_SCREEN_GAMEPAD_SCENE:RegisterCallback("StateChange", function(oldState, newState)
if newState == SCENE_SHOWING then
self:PerformDeferredInitialization()
KEYBIND_STRIP:RemoveDefaultExit()
self.optionsList:Activate()
KEYBIND_STRIP:AddKeybindButtonGroup(self.keybindStripDescriptor)
elseif newState == SCENE_HIDDEN then
KEYBIND_STRIP:RemoveKeybindButtonGroup(self.keybindStripDescriptor)
self.optionsList:Deactivate()
KEYBIND_STRIP:RestoreDefaultExit()
end
end)
end
function CreateLinkAccount_Console:PerformDeferredInitialization()
if self.initialized then return end
self.initialized = true
self.activateImagesFragment = nil
self:SetupOptions()
self:InitKeybindingDescriptor()
end
function CreateLinkAccount_Console:AddOption(title, imagesFragment, selectedState)
local option = ZO_GamepadEntryData:New(title)
option:SetFontScaleOnSelection(true)
option.selectedCallback = function() PregameStateManager_SetState(selectedState) end
option.imagesFragment = imagesFragment
self.optionsList:AddEntry("ZO_GamepadMenuEntryTemplate", option)
end
function CreateLinkAccount_Console:SetupOptions()
self.optionsList = ZO_GamepadVerticalParametricScrollList:New(self.control:GetNamedChild("Container"):GetNamedChild("Options"):GetNamedChild("List"))
self.optionsList:SetOnSelectedDataChangedCallback(function(...) self:SelectionChanged(...) end)
self.optionsList:SetAlignToScreenCenter(true)
self.optionsList:Clear()
self.optionsList:AddDataTemplate("ZO_GamepadMenuEntryTemplate", ZO_SharedGamepadEntry_OnSetup, ZO_GamepadMenuEntryTemplateParametricListFunction)
self:AddOption(GetString(SI_CREATEACCOUNT_HEADER), CREATE_ACCOUNT_IMAGES_FRAGMENT_CONSOLE, "CreateAccountSetup")
self:AddOption(GetString(SI_CONSOLE_LINKACCOUNT_HEADER), LINK_ACCOUNT_IMAGES_FRAGMENT_CONSOLE, "LinkAccount")
self.optionsList:Commit()
end
function CreateLinkAccount_Console:SelectionChanged(list, selectedData, oldSelectedData)
local newImagesFragment = selectedData.imagesFragment
if self.activateImagesFragment == newImagesFragment then return end
if self.activateImagesFragment then
CREATE_LINK_ACCOUNT_SCREEN_GAMEPAD_SCENE:RemoveFragment(self.activateImagesFragment)
end
self.activateImagesFragment = newImagesFragment
if newImagesFragment then
CREATE_LINK_ACCOUNT_SCREEN_GAMEPAD_SCENE:AddFragment(newImagesFragment)
end
end
function CreateLinkAccount_Console:InitKeybindingDescriptor()
self.keybindStripDescriptor =
{
alignment = KEYBIND_STRIP_ALIGN_LEFT,
-- Select
{
name = GetString(SI_GAMEPAD_SELECT_OPTION),
keybind = "UI_SHORTCUT_PRIMARY",
callback = function()
local data = self.optionsList:GetTargetData()
if data ~= nil and data.selectedCallback ~= nil then
PlaySound(SOUNDS.POSITIVE_CLICK)
data.selectedCallback()
end
end,
},
-- Back
KEYBIND_STRIP:GenerateGamepadBackButtonDescriptor(function()
PlaySound(SOUNDS.NEGATIVE_CLICK)
PregameStateManager_SetState("AccountLogin")
end)
}
end
---------------------------------------
function CreateLinkAccountScreen_Gamepad_Initialize(self)
CREATE_LINK_ACCOUNT_CONSOLE = CreateLinkAccount_Console:New(self)
end
|
--[[
La suite de fibonaci
--]]
function fibo (a, b, i)
local out_ = 0
local a2 = a
local b2 = b
for j = 0, i + 1 do
io.write(j)
out_ = out_ + a2
local tmp = b2
b2 = b2 + a2
a2 = tmp
end
return out_
end
io.write(fibo(1, 2, 4))
|
--
-- Functions for Lua's operators
--
return {
first = function(x) return x end,
unm = function(x) return -x end,
add = function(x,y) return x + y end,
sub = function(x,y) return x - y end,
mul = function(x,y) return x * y end,
div = function(x,y) return x / y end,
mod = function(x,y) return x % y end,
pow = function(x,y) return x ^ y end,
concat = function(x,y) return x .. y end,
eq = function(x,y) return x == y end,
lt = function(x,y) return x < y end,
le = function(x,y) return x <= y end,
index = function(t,k) return t[k] end,
call = function(f,...) return f(...) end,
}
|
require "Assets.LuaScripts.Modulus.TimeMgr.Handler.BaseTimerHandler"
require "Assets.LuaScripts.Modulus.TimeMgr.Handler.MillTimerHandler"
require "Assets.LuaScripts.Modulus.TimeMgr.Handler.SecTimerHandler"
require "Assets.LuaScripts.Modulus.TimeMgr.Handler.MinTimerHandler"
require "Assets.LuaScripts.Modulus.TimeMgr.Handler.EveryMillHandler"
require "Assets.LuaScripts.Modulus.TimeMgr.TimeMgr" |
--[[
Vectors for operations in a d-dimensional space.
]]
_libs = _libs or {}
require('tables')
require('maths')
local table, math = _libs.tables, _libs.maths
vector = {}
_libs.vectors = vector
_meta = _meta or {}
_meta.V = {}
_meta.V.__index = vector
_meta.V.__class = 'Vector'
-- Constructor for vectors. Optionally provide dimension n, to avoid computing the dimension from the table.
function V(t, n)
local res = {}
res.n = n or t.n or #t
for i = 1, res.n do
res[i] = t[i]
end
return setmetatable(res, _meta.V)
end
_meta.V.__unp = V:args(1)
-- Creates a zero-vector of dimension n.
function vector.zero(n)
return vector.fill(n, 0)
end
-- Creates a vector of dimension n with all values set to k.
function vector.fill(n, k)
local res = {}
for i = 1, n do
res[i] = k
end
res.n = n
return setmetatable(res, _meta.V)
end
-- Creates a euclidean unit vector of dimension n for axis i.
function vector.unit(n, i)
local res = {}
for j = 1, n do
res[j] = i == j and 1 or 0
end
res.n = n
return setmetatable(res, _meta.V)
end
-- Returns the length of a vector measured from 0.
function vector.length(v)
local length = 0
for _, val in ipairs(v) do
length = length + val^2
end
return math.sqrt(length)
end
-- Returns a vector in the same direction as v, normalized to length one.
function vector.normalize(v)
return v:scale(1/v:length())
end
-- Returns the dimension of v. Constant.
function vector.dimension(v)
return v.n
end
-- Returns the dot product between two vectors.
function vector.dot(v1, v2)
local res = 0
for i, val1 in ipairs(v1) do
res = res + val1*v2[i]
end
return res
end
_meta.V.__mul = function(x, y) if type(x) == 'number' then return y:scale(x) elseif type(y) == 'number' then return x:scale(y) else return x:dot(y) end end
-- Returns the cross product of two R^3 vectors.
function vector.cross(v1, v2)
local res = {}
res[1] = v1[2]*v2[3] - v1[3]*v2[2]
res[2] = v1[3]*v2[1] - v1[1]*v2[3]
res[3] = v1[1]*v2[2] - v1[2]*v2[1]
res.n = 3
return setmetatable(res, _meta.V)
end
-- Returns v multiplied by k, i.e. all elements multiplied by the same factor.
function vector.scale(v, k)
local res = {}
for i, val in ipairs(v) do
res[i] = val*k
end
res.n = v.n
return setmetatable(res, _meta.V)
end
-- Returns the vector pointing in the opposite direction of v with the same length.
function vector.negate(v)
return vector.scale(v, -1)
end
_meta.V.__unm = vector.negate
-- Returns v1 added to v2.
function vector.add(v1, v2)
local res = {}
for i, val in ipairs(v1) do
res[i] = val+v2[i]
end
res.n = v1.n
return setmetatable(res, _meta.V)
end
_meta.V.__add = vector.add
-- Returns v1 subtracted by v2.
function vector.subtract(v1, v2)
local res = {}
for i, val in ipairs(v1) do
res[i] = val-v2[i]
end
res.n = v1.n
return setmetatable(res, _meta.V)
end
_meta.V.__sub = vector.subtract
-- Returns the angle described by two vectors (in radians).
function vector.angle(v1, v2)
return ((v1 * v2) / (v1:length() * v2:length())):acos()
end
-- Returns a normalized 2D vector from a radian value.
-- Note that this goes against mathematical convention, which commonly makes the radian go counter-clockwise.
-- This function, instead, goes clockwise, i.e. it will return *(0, -1)* for ''π/2''.
-- This is done to match the game's internal representation, which has the X axis pointing east and the Y axis pointing south.
function vector.from_radian(r)
return V{r:cos(), -r:sin()}
end
-- Returns the radian that describes the direction of the vector.
function vector.to_radian(v)
return (v[2] < 0 and 1 or -1) * v:normalize()[1]:acos()
end
-- Returns the vector in string format: (...)
function vector.tostring(v)
local str = '('
for i, val in ipairs(v) do
if i > 1 then
str = str..', '
end
str = str..tostring(val)
end
return str..')'
end
_meta.V.__tostring = vector.tostring
--[[
Copyright © 2013-2014, Windower
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Windower nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Windower BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
]]
|
AddCSLuaFile()
include("acf/shared/sh_acfm_getters.lua")
local function checkIfDataIsMissile(data)
local guns = list.Get("ACFEnts").Guns
local class = guns[data.Id]
if not (class and class.gunclass) then
return oldDisplayData(data)
end
local classes = list.Get("ACFClasses").GunClass
class = classes[class.gunclass]
return (class.type and class.type == "missile")
end
function ACFM_ModifyRoundDisplayFuncs()
local roundTypes = list.GetForEdit("ACFRoundTypes")
if not ACFM_RoundDisplayFuncs then
ACFM_RoundDisplayFuncs = {}
for k, v in pairs(roundTypes) do
ACFM_RoundDisplayFuncs[k] = v.getDisplayData
end
end
for k, v in pairs(roundTypes) do
local oldDisplayData = ACFM_RoundDisplayFuncs[k]
if oldDisplayData then
v.getDisplayData = function(data)
if not checkIfDataIsMissile(data) then
return oldDisplayData(data)
end
-- NOTE: if these replacements cause side-effects somehow, move to a masking-metatable approach
local MuzzleVel = data.MuzzleVel
local slugMV = data.SlugMV
data.MuzzleVel = 0
data.SlugMV = (slugMV or 0) * (ACF_GetGunValue(data.Id, "penmul") or 1)
local ret = oldDisplayData(data)
data.SlugMV = slugMV
data.MuzzleVel = MuzzleVel
return ret
end
end
end
end
local function configConcat(tbl, sep)
local toConcat = {}
for k, v in pairs(tbl) do
toConcat[#toConcat+1] = tostring(k) .. " = " .. tostring(v)
end
return table.concat(toConcat, sep)
end
function ACFM_ModifyCrateTextFuncs()
local roundTypes = list.GetForEdit("ACFRoundTypes")
if not ACFM_CrateTextFuncs then
ACFM_CrateTextFuncs = {}
for k, v in pairs(roundTypes) do
ACFM_CrateTextFuncs[k] = v.cratetxt
end
end
for k, v in pairs(roundTypes) do
local oldCratetxt = ACFM_CrateTextFuncs[k]
if oldCratetxt then
v.cratetxt = function(data, crate)
local origCrateTxt = oldCratetxt(data)
if not checkIfDataIsMissile(data) then
return origCrateTxt
end
local str = { origCrateTxt }
local guidance = IsValid(crate) and crate.RoundData7 or data.Data7
local fuse = IsValid(crate) and crate.RoundData8 or data.Data8
if guidance then
guidance = ACFM_CreateConfigurable(guidance, ACF.Guidance, bdata, "guidance")
if guidance and guidance.Name ~= "Dumb" then
str[#str+1] = "\n\n"
str[#str+1] = guidance.Name
str[#str+1] = " guidance\n("
str[#str+1] = configConcat(guidance:GetDisplayConfig(), ", ")
str[#str+1] = ")"
end
end
if fuse then
fuse = ACFM_CreateConfigurable(fuse, ACF.Fuse, bdata, "fuses")
if fuse then
str[#str+1] = "\n\n"
str[#str+1] = fuse.Name
str[#str+1] = " fuse\n("
str[#str+1] = configConcat(fuse:GetDisplayConfig(), ", ")
str[#str+1] = ")"
end
end
return table.concat(str)
end
ACF.RoundTypes[k].cratetxt = v.cratetxt
end
end
end
function ACFM_ModifyRoundBaseGunpowder()
local oldGunpowder = ACFM_ModifiedRoundBaseGunpowder and oldGunpowder or ACF_RoundBaseGunpowder
ACF_RoundBaseGunpowder = function(PlayerData, Data, ServerData, GUIData)
PlayerData, Data, ServerData, GUIData = oldGunpowder(PlayerData, Data, ServerData, GUIData)
Data.Id = PlayerData.Id
return PlayerData, Data, ServerData, GUIData
end
ACFM_ModifiedRoundBaseGunpowder = true
end
timer.Simple(1, ACFM_ModifyRoundBaseGunpowder)
timer.Simple(1, ACFM_ModifyRoundDisplayFuncs)
timer.Simple(1, ACFM_ModifyCrateTextFuncs)
-- if CLIENT then
-- timer.Simple(1, ACFM_ModifyRoundGUIFuncs)
-- end
|
require("prototypes.constants")
data.raw["underground-belt"]["express-underground-belt"].max_distance = 11
local stacksize = 50
if settings.startup["ore_stacks_200"].value then
stacksize = 200
data.raw.item["iron-plate"].stack_size = stacksize
data.raw.item["copper-plate"].stack_size = stacksize
data.raw.item["steel-plate"].stack_size = stacksize
data.raw.item["sulfur"].stack_size = stacksize
data.raw.item["plastic-bar"].stack_size = stacksize
elseif settings.startup["ore_stacks_100"].value then
stacksize = 100
end
data.raw.item["iron-ore"].stack_size = stacksize
data.raw.item["copper-ore"].stack_size = stacksize
data.raw.item["stone"].stack_size = stacksize
data.raw.item["uranium-ore"].stack_size = stacksize
data.raw.item["coal"].stack_size = stacksize
--I didn't want to tweak these, but the factorio devs made stupid blueprints that are actually impossible to build at full throughput while beaconed.
data.raw.item["low-density-structure"].stack_size = 100
data.raw.item["rocket-fuel"].stack_size = 100
data.raw.item["rocket-control-unit"].stack_size = 100
data.raw["logistic-robot"]["logistic-robot"].max_payload_size = 7
--Make artillery-turrets not have boosted manual targeting range.
data.raw["artillery-turret"]["artillery-turret"].manual_range_modifier = 1
local density_factor = settings.startup["biter-multipler"].value
--make biters tougher
data.raw["unit-spawner"]["biter-spawner"].result_units[2] = { "medium-biter", {{0.2,0}, {0.6,0.3}, {0.7,0.1}, {.99,0}} }
data.raw["unit-spawner"]["biter-spawner"].result_units[3] = { "big-biter", {{0.5,0}, {.99,0}} }
data.raw["unit-spawner"]["biter-spawner"].result_units[4] = { "behemoth-biter", {{0.9,0}, {.99,1}} }
data.raw["unit-spawner"]["biter-spawner"].spawning_cooldown = spawn_cooldowns
data.raw["unit-spawner"]["biter-spawner"].pollution_absorption_absolute = 1600 * density_factor
data.raw["unit-spawner"]["biter-spawner"].max_count_of_owned_units = max_bugs_per_spawner
data.raw["unit-spawner"]["biter-spawner"].max_friends_around_to_spawn = max_bugs_per_spawner
data.raw["unit-spawner"]["spitter-spawner"].result_units[3] = { "medium-spitter", {{0.4,0}, {0.7,0.3}, {0.9,0.1}, {.99,0}} }
data.raw["unit-spawner"]["spitter-spawner"].result_units[4] = { "big-spitter", {{0.5,0}, {.99,0}} }
data.raw["unit-spawner"]["spitter-spawner"].result_units[5] = { "behemoth-spitter", {{0.9,0}, {.99,1}} }
data.raw["unit-spawner"]["spitter-spawner"].spawning_cooldown = spawn_cooldowns
data.raw["unit-spawner"]["spitter-spawner"].pollution_absorption_absolute = 800 * density_factor
data.raw["unit-spawner"]["spitter-spawner"].max_count_of_owned_units = max_bugs_per_spawner
data.raw["unit-spawner"]["spitter-spawner"].max_friends_around_to_spawn = max_bugs_per_spawner
data.raw["energy-shield-equipment"]["aircraft-energy-shield"].max_shield_value = 250 * density_factor
data.raw["energy-shield-equipment"]["aircraft-energy-shield"].energy_per_shield = 18 / density_factor .. "kJ"
local movespeed = 1
--Since I can't make more biters, I have to make them bigger and meaner. Lame!
--data.raw.unit["behemoth-biter"].movement_speed = movespeed
--data.raw.unit["behemoth-biter"].distance_per_frame = movespeed + .08
data.raw.unit["behemoth-biter"].ai_settings.do_separation = false
--data.raw.unit["behemoth-biter"].ai_settings.path_resolution_modifier = -4
data.raw.unit["behemoth-biter"].dying_explosion = nil
data.raw.unit["behemoth-biter"].max_health = 3000 * density_factor
data.raw.unit["behemoth-biter"].pollution_to_join_attack = 400 * density_factor
data.raw.unit["behemoth-biter"].attack_parameters.ammo_type.action.action_delivery.target_effects.damage.amount = 90 * density_factor
--Increasing this breaks pathing.
--data.raw.unit["behemoth-spitter"].movement_speed = movespeed
--data.raw.unit["behemoth-spitter"].distance_per_frame = movespeed + .08
data.raw.unit["behemoth-spitter"].ai_settings.do_separation = false
--Higher value = lots more CPU use (and more path waypoints?); low values don't help.
--data.raw.unit["behemoth-spitter"].ai_settings.path_resolution_modifier = -4
data.raw.unit["behemoth-spitter"].dying_explosion = nil
data.raw.unit["behemoth-spitter"].max_health = 1500 * density_factor
data.raw.unit["behemoth-spitter"].pollution_to_join_attack = 400 * density_factor
data.raw.unit["behemoth-spitter"].attack_parameters.damage_modifier = 60 * density_factor
--data.raw.fire["acid-splash-fire-spitter-behemoth"].on_damage_tick_effect.action_delivery.target_effects[2].damage.amount = 1 * density_factor
--Disable worm and spawner dying explosions to speed up nukes.
for _,worm in pairs(data.raw.turret) do
worm.dying_explosion = nil
end
for _,spawner in pairs(data.raw["unit-spawner"]) do
spawner.dying_explosion = nil
end
--Custom oil pump, no more pesky beacons!
local newpump = table.deepcopy(data.raw["mining-drill"]["pumpjack"])
for _,layer in pairs(newpump.animations.north.layers) do
layer.tint = { r = 128, b = 128, g = 128, a = 255 }
end
newpump.energy_source.emissions_per_minute = 108
newpump.energy_source.drain = "5760kW"
newpump.energy_usage = "972kW"
newpump.minable.result = "super-pumpjack"
newpump.name = "super-pumpjack"
newpump.module_specification.module_slots = 0
newpump.allowed_effects = {}
newpump.mining_speed = 8
data:extend({newpump})
newpump = table.deepcopy(data.raw.item["pumpjack"])
newpump.name = "super-pumpjack"
newpump.place_result = "super-pumpjack"
newpump.icons = {
{
icon = "__base__/graphics/icons/pumpjack.png",
tint = { r = 128, b = 128, g = 128, a = 255 }
}
}
data:extend({newpump})
newpump = table.deepcopy(data.raw.recipe["pumpjack"])
newpump.name = "super-pumpjack"
newpump.result = "super-pumpjack"
newpump.ingredients = {
{"pumpjack", 1},
{"speed-module-3", 26},
{"beacon", 12}
}
newpump.enabled = true
data:extend({newpump})
--Custom water pump
local newpump = table.deepcopy(data.raw["offshore-pump"]["offshore-pump"])
for _,dir in pairs({"north", "east", "south", "west"})
do
for _,layer in pairs(newpump.graphics_set.animation[dir].layers) do
layer.tint = { r = 128, b = 128, g = 128, a = 255 }
layer.hr_version.tint = { r = 128, b = 128, g = 128, a = 255 }
end
end
newpump.pumping_speed = 200
newpump.minable.result = "super-offshore-pump"
newpump.name = "super-offshore-pump"
newpump.fluid_box.base_area = 10
data:extend({newpump})
newpump = table.deepcopy(data.raw.item["offshore-pump"])
newpump.name = "super-offshore-pump"
newpump.place_result = "super-offshore-pump"
newpump.icons = {
{
icon = "__base__/graphics/icons/offshore-pump.png",
tint = { r = 128, b = 128, g = 128, a = 255 }
}
}
data:extend({newpump})
newpump = table.deepcopy(data.raw.recipe["offshore-pump"])
newpump.name = "super-offshore-pump"
newpump.result = "super-offshore-pump"
newpump.ingredients = {
{"offshore-pump", 10}
}
newpump.enabled = true
data:extend({newpump})
data.raw["artillery-projectile"]["artillery-projectile"].action.action_delivery.target_effects[1].action.radius = 8
--64 is max value due to game engine.
local new_dist = 52
local orig_dist = data.raw["electric-pole"]["big-electric-pole"].maximum_wire_distance
data.raw["electric-pole"]["big-electric-pole"].maximum_wire_distance = new_dist
for i in pairs(data.raw.recipe["big-electric-pole"].ingredients) do
data.raw.recipe["big-electric-pole"].ingredients[i][2] = math.ceil(data.raw.recipe["big-electric-pole"].ingredients[i][2] * (new_dist / orig_dist))
end
--For use with WAR Equipment reactor
u235_gj_per_kg = 79390
u238_gj_per_kg_fast = 80620
u238_gj_per_kg_thermal = 1684.2
--recipe for base fuel cell is 19 238, 1 235 for 10 cells.
data.raw.item["uranium-fuel-cell"].fuel_value = (u235_gj_per_kg + 19 * u238_gj_per_kg_fast)/10 .. "GJ"
--Enhance Artillery shells.
local arty_ammo_bonus = settings.startup["arty-ammo-hold-bonus"].value
local arty_rotation_speed_bonus = settings.startup["arty-rotation-speed-bonus"].value / 100 + 1
local new_hold = data.raw["artillery-turret"]["artillery-turret"]["automated_ammo_count"]
data.raw["artillery-turret"]["artillery-turret"]["automated_ammo_count"] = new_hold + arty_ammo_bonus
new_hold = data.raw["artillery-turret"]["artillery-turret"]["ammo_stack_limit"]
data.raw["artillery-turret"]["artillery-turret"]["ammo_stack_limit"] = new_hold + arty_ammo_bonus
local orig_speed = data.raw["artillery-turret"]["artillery-turret"]["turret_rotation_speed"]
data.raw["artillery-turret"]["artillery-turret"]["turret_rotation_speed"] = orig_speed * arty_rotation_speed_bonus
orig_speed = data.raw["artillery-turret"]["artillery-turret"]["turn_after_shooting_cooldown"]
data.raw["artillery-turret"]["artillery-turret"]["turn_after_shooting_cooldown"] = math.ceil(orig_speed / arty_rotation_speed_bonus)
orig_speed = data.raw["artillery-turret"]["artillery-turret"]["cannon_parking_speed"]
data.raw["artillery-turret"]["artillery-turret"]["cannon_parking_speed"] = orig_speed * arty_rotation_speed_bonus |
local PLUGIN = PLUGIN;
local Clockwork = Clockwork;
-- Called when a player's weapons should be given.
function PLUGIN:PlayerGiveWeapons(player)
if (player:GetFaction() == FACTION_CREMATOR) then
Clockwork.player:GiveSpawnWeapon(player, "cw_immolator");
Clockwork.player:GiveSpawnWeapon(player, "cw_beam_immolator");
end;
end;
-- Called at an interval while a player is connected.
function PLUGIN:PlayerThink(player, curTime, infoTable)
local CrematorSound = "npc/cremator/amb_loop.wav"
local sound = CreateSound(player, "npc/cremator/amb_loop.wav");
local faction = player:GetFaction();
if (player:Alive() and !player:IsRagdolled()) then
if ( faction == FACTION_CREMATOR ) then
-- player:EmitSound(CrematorSound, 65, 50);
sound:Play();
else
-- BroadcastLua("LocalPlayer():ConCommand('stopsound')") Doesn't fukin work
sound:Stop();
end;
end;
end;
-- Called when a player's typing display has started.
function PLUGIN:PlayerStartTypingDisplay(player, code)
local faction = player:GetFaction();
if ( faction == FACTION_CREMATOR ) then
if (code == "n" or code == "y" or code == "w" or code == "r") then
if (!player.typingBeep) then
player.typingBeep = true;
player:EmitSound("npc/overwatch/radiovoice/on3.wav");
end;
end;
end;
end;
-- Called when a player's typing display has finished.
function PLUGIN:PlayerFinishTypingDisplay(player, textTyped)
local faction = player:GetFaction();
if ( faction == FACTION_CREMATOR and textTyped ) then
if (player.typingBeep) then
player:EmitSound("npc/overwatch/radiovoice/off4.wav");
end;
end;
player.typingBeep = nil;
end;
-- Called when a player's character has initialized.
function PLUGIN:PlayerCharacterInitialized(player)
local faction = player:GetFaction();
if (faction == FACTION_CREMATOR) then
Schema:AddCombineDisplayLine( "Rebuilding active Cremator Unit Manifest..", Color(255, 165, 0, 255) );
end;
end;
-- Called when a player's death sound should be played.
function PLUGIN:PlayerPlayDeathSound(player, gender)
local faction = player:GetFaction();
if ( faction == FACTION_CREMATOR ) then
local crmsound = "npc/cremator/crem_die.wav";
for k, v in ipairs( _player.GetAll() ) do
if (v:HasInitialized()) then
if ( faction == FACTION_CREMATOR or faction == FACTION_MPF or faction == FACTION_OTA ) then
v:EmitSound(crmsound);
Schema:AddCombineDisplayLine( "BioSignal lost for Cremator Unit at unknown location..", Color(255, 0, 0, 255) );
end;
end;
end;
end;
return crmsound;
end;
--[[ Called when a player's default inventory is needed. - Broken! There is a Hook for it!
function Schema:GetPlayerDefaultInventory(player, character, inventory)
if (character.faction == FACTION_ADMIN) then
Clockwork.inventory:AddInstance(
inventory, Clockwork.item:CreateInstance("handheld_radio")
);
elseif (character.faction == FACTION_MPF) then
Clockwork.inventory:AddInstance(
inventory, Clockwork.item:CreateInstance("handheld_radio")
);
Clockwork.inventory:AddInstance(
inventory, Clockwork.item:CreateInstance("weapon_pistol")
);
for i = 1, 2 do
Clockwork.inventory:AddInstance(
inventory, Clockwork.item:CreateInstance("ammo_pistol")
);
end;
elseif (character.faction == FACTION_OTA) then
Clockwork.inventory:AddInstance(
inventory, Clockwork.item:CreateInstance("handheld_radio")
);
Clockwork.inventory:AddInstance(
inventory, Clockwork.item:CreateInstance("weapon_pistol")
);
Clockwork.inventory:AddInstance(
inventory, Clockwork.item:CreateInstance("ammo_pistol")
);
Clockwork.inventory:AddInstance(
inventory, Clockwork.item:CreateInstance("weapon_ar2")
);
Clockwork.inventory:AddInstance(
inventory, Clockwork.item:CreateInstance("ammo_ar2")
);
elseif (character.faction == FACTION_CREMATOR) then
Clockwork.inventory:AddInstance(
inventory, Clockwork.item:CreateInstance("handheld_radio")
);
Clockwork.inventory:AddInstance(
inventory, Clockwork.item:CreateInstance("weapon_immolator")
);
else
Clockwork.inventory:AddInstance(
inventory, Clockwork.item:CreateInstance("suitcase")
);
end;
end;
--]]
-- Called when a player's default inventory is needed.
function PLUGIN:GetPlayerDefaultInventory(player, character, inventory)
if (character.faction == FACTION_CREMATOR) then
Clockwork.inventory:AddInstance(
inventory, Clockwork.item:CreateInstance("handheld_radio")
);
end;
end;
-- Called when a player's footstep sound should be played.
function PLUGIN:PlayerFootstep(player, position, foot, sound, volume, recipientFilter)
local clothes = player:GetCharacterData("clothes");
local model = string.lower( player:GetModel() );
local faction = player:GetFaction();
-- if (PLUGIN:PlayerIsCremator(faction)) then
-- if ( faction == FACTION_CREMATOR )
if (string.find(model, "cremator")) then
if (foot == 0) then
local randomSounds = {1, 2, 3};
local randomNumber = math.random(1, 3);
sound = "npc/cremator/foot"..randomSounds[randomNumber]..".wav";
end;
end;
player:EmitSound(sound);
end;
-- Called just after a player spawns.
function PLUGIN:PostPlayerSpawn(player, lightSpawn, changeClass, firstSpawn)
local clothes = player:GetCharacterData("clothes");
local faction = player:GetFaction();
if (!lightSpawn) then
player:SetSharedVar("antidepressants", 0);
Clockwork.datastream:Start(player, "ClearEffects", true);
player.beingSearched = nil;
player.searching = nil;
end;
if (player:GetFaction() == FACTION_CREMATOR) then
player:SetMaxHealth(150);
player:SetMaxArmor(100);
player:SetHealth(150);
player:SetArmor(100);
end;
end;
--[[ Called when a player's pain sound should be played. - It does Loop sounds...
function PLUGIN:PlayerPlayPainSound(player, gender, damageInfo, hitGroup)
local faction = player:GetFaction();
if ( faction == FACTION_CREMATOR ) then
return "npc/cremator/amb_mad.wav";
end;
end;
--]]
--A Function to check if the player can open a Combine Door.
function PLUGIN:PlayerCanUseDoor(player, door)
if player:GetFaction() == FACTION_CREMATOR then
return true;
end;
end;
-- Called when a player's pain sound should be played.
function PLUGIN:PlayerPlayPainSound(player, gender, damageInfo, hitGroup)
local faction = player:GetFaction();
if ( faction == FACTION_CREMATOR ) then
return "npc/combine_soldier/pain"..math.random(1, 3)..".wav";
end;
end; |
util.AddNetworkString( "AM_Notify" )
function AM_Notify( ply, text, broadcast )
if broadcast then
net.Start( "AM_Notify" )
net.WriteString( text )
net.Broadcast()
return
end
net.Start( "AM_Notify" )
net.WriteString( text )
net.Send( ply )
end
function AM_TrimModel( model )
if isstring( model ) then
local removemodel = string.gsub( model, "models/", "" )
local removeextention = string.StripExtension( removemodel )
local replaceslash = string.Replace( removeextention, "/", "%" )
return replaceslash
end
return ""
end
function AM_SaveAllVehicles()
for k,v in pairs( AM_Vehicles ) do
timer.Simple( 0.5, function()
local slashfix = AM_TrimModel( k )
if file.Exists( "addons/Automod/data/automod/vehicles/"..slashfix..".json", "GAME" ) then
print( "[Automod] File for '"..k.."' already exists. Skipping." )
return
end
if !file.Exists( "automod/vehicles", "DATA" ) then file.CreateDir( "automod/vehicles" ) end
file.Write( "automod/vehicles/"..slashfix..".json", util.TableToJSON( v, true ) )
print( "[Automod] Successfully saved '"..k.."' to file." )
end )
end
end
local function AM_SaveVehicle( model )
if AM_Vehicles[model] then
local slashfix = AM_TrimModel( model )
if file.Exists( "automod/vehicles/"..slashfix..".json", "DATA" ) or file.Exists( "addons/Automod/data/automod/vehicles/"..slashfix..".json", "GAME" ) then
print( "[Automod] This vehicle has already been saved. Delete it's data file and try again if you're saving a newer version." )
return
end
file.Write( "automod/vehicles/"..slashfix..".json", util.TableToJSON( AM_Vehicles[model], true ) )
print( "[Automod] Successfully saved "..model.." to Automod files." )
else
MsgC( Color( 255, 0, 0 ), "[Automod] ERROR: The specified model doesn't seem to exist. Check your spelling and vehicle tables." )
end
end
concommand.Add( "AM_SaveVehicle", function( ply, cmd, args )
if IsValid( ply ) and !ply:IsSuperAdmin() then
AM_Notify( ply, "Only superadmins and server operators can access this command!" )
return
end
if #args > 1 then
MsgC( Color( 255, 0, 0 ), "[Automod] ERROR: Please only enter 1 argument." )
return
end
AM_SaveVehicle( args[1] )
end )
local shouldsave = gmsave.ShouldSaveEntity
function gmsave.ShouldSaveEntity( ent, t ) --Finding decent documentation on this function was such a pain, especially now that the facepunch forums are gone
if ent:GetNWBool( "IsAutomodSeat" ) then return false end --Should prevent the seats from duping themselves after loading a save
return shouldsave( ent, t )
end
|
-----------------------------------------
-- ID: 4759
-- Scroll of Blizzard III
-- Teaches the black magic Blizzard III
-----------------------------------------
function onItemCheck(target)
return target:canLearnSpell(151)
end
function onItemUse(target)
target:addSpell(151)
end |
object_mobile_azure_cabal_greel_scoundrel_f_01 = object_mobile_shared_azure_cabal_greel_scoundrel_f_01:new {
}
ObjectTemplates:addTemplate(object_mobile_azure_cabal_greel_scoundrel_f_01, "object/mobile/azure_cabal_greel_scoundrel_f_01.iff")
|
-- file: setup.lua
local module = {}
local function wifi_wait_ip()
if wifi.sta.getip()== nil then
print("IP unavailable, Waiting...")
else
tmr.stop(1)
print("\n====================================")
print("ESP8266 mode is: " .. wifi.getmode())
print("MAC address is: " .. wifi.ap.getmac())
print("IP is " .. wifi.sta.getip())
print("====================================")
app.start()
end
end
local function wifi_start(list_aps)
if list_aps then
local found = false
for _, station_cfg in pairs(config.WIFI) do
for key,value in pairs(list_aps) do
if station_cfg.ssid == key then
wifi.setmode(wifi.STATION);
wifi.sta.config(station_cfg)
wifi.sta.connect()
print("Connecting to " .. key .. " ...")
found = true
--config.SSID = nil -- can save memory
tmr.alarm(1, 2500, 1, wifi_wait_ip)
end
end
end
if not found then
print("Error: Failed to connect to WIFI, no matching config! Found these networks:")
for key,value in pairs(list_aps) do
print(" - " .. key)
end
print("I have configuration for these:")
for _, station_cfg in pairs(config.WIFI) do
print(" - " .. station_cfg.ssid)
end
end
else
print("Error getting AP list")
end
end
function module.start()
print("Configuring Wifi ...")
wifi.setmode(wifi.STATION);
wifi.sta.getap(wifi_start)
end
return module
|
object_mobile_naboo_tanoa_vills = object_mobile_shared_naboo_tanoa_vills:new {
}
ObjectTemplates:addTemplate(object_mobile_naboo_tanoa_vills, "object/mobile/naboo_tanoa_vills.iff")
|
local IO = terralib.includec("stdio.h")
local stdlib = terralib.includec("stdlib.h")
local number = double
local alignment = 8
local function isinteger(x) return math.floor(x) == x end
local llvmprefetch = terralib.intrinsic("llvm.prefetch",{&opaque,int,int,int} -> {})
local dotune = true
-- terra naivel1conv(A : &double, B : &double, C : &double, lda : int, ldb : int, ldc : int, alpha : double)
function symmat(name,I,...)
if not I then return symbol(name) end
local r = {}
for i = 0,I-1 do
r[i] = symmat(name..tostring(i),...)
end
return r
end
local function unalignedload(addr)
return `terralib.attrload(addr, { align = alignment })
end
local function unalignedstore(addr,v)
return `terralib.attrstore(addr,v, { align = alignment })
end
unalignedload,unalignedstore = macro(unalignedload),macro(unalignedstore)
function printMatrix(m,rows,columns)
local matrix = m
for i=0,rows-1 do
for j=0,columns-1 do
io.write(" " .. matrix[i*columns + j])
end
io.write("\n")
end
io.write("\n")
end
function gencmulkernel(NB, RM, RN, prefetch)
local M,N
local A,B,C,mm,nn = symbol("A"),symbol("B"),symbol("C"),symbol("mn"),symbol("nn")
local ldc = symbol("ldc")
local a,b,c,caddr = symmat("a",RM,RN), symmat("b",RM,RN), symmat("c",RM,RN), symmat("caddr",RM,RN)
local load,storec,calcc = terralib.newlist(),terralib.newlist(),terralib.newlist()
for m = 0, RM-1 do
for n = 0, RN - 1 do
load:insert(quote
var [c[m][n]] = C[m*ldc + n]
var [a[m][n]] = A[m*ldc + n]
var [b[m][n]] = B[m*ldc + n]
end)
storec:insert(quote
C[m*ldc + n] = [c[m][n]]
end)
end
end
-- spatial 2D convolution
for m = 0, RM-1 do
for n = 0, RN - 1, 2 do
calcc:insert(
quote
[c[m][n]] = [a[m][n]] * [b[m][n]] - [a[m][n+1]] * [b[m][n+1]]
[c[m][n+1]] = [a[m][n]] * [b[m][n+1]] + [b[m][n]] * [a[m][n+1]]
end
)
end
end
-- NB must be divisible by RN
return terra([A] : &double, [B] : &double, [C] : &double, [ldc] : int)
for [mm] = 0, NB, RM do
for [nn]=0, NB, RN do
[load];
-- llvmprefetch(A + ldc*ldc,0,3,1);
[calcc];
[storec];
A = A + RN
B = B + RN
C = C + RN
end
A = A + RM * ldc - NB
B = B + RM * ldc - NB
C = C + RM * ldc - NB
end
end
end
function gencmul(NB,NBF,RM,RN)
if not isinteger(NB/RM) or not isinteger(NB/(2*RN)) then
return false
end
local NB2 = NB * NBF
local l1cmul = gencmulkernel(NB, RM, 2*RN, false)
return terra(gettime : {} -> double, M : int, N : int, A : &double, B : &double, C : &double,
ldc : int)
[ blockedloop(N,M,{NB2,NB},
function(m,n)
return quote
var MM,NN = min(M-m,NB),min(N-n,NB)
var isboundary = MM < NB or NN < NB
var AA,BB,CC = A + (m*ldc + n), B + (m*ldc + n), C + (m*ldc + n)
l1cmul(AA,
BB,
CC,
ldc)
end end)
]
end
end
terra min(a : int, b : int)
return terralib.select(a < b, a, b)
end
function blockedloop(M,N,blocksizes,bodyfn)
local function generatelevel(n,ii,jj,bb0,bb1)
if n > #blocksizes then
return bodyfn(ii,jj)
end
local blocksize = blocksizes[n]
return quote for i = ii,min(ii+bb0,M),blocksize do
for j = jj,min(jj+bb1,N),blocksize do
[ generatelevel(n+1,i,j,blocksize,blocksize) ]
end end end
end
return generatelevel(1,0,0,M,N)
end
local blocksizes = {16,32,64}
local regblocks = {1,2,4} -- blocksizes must be divisible by RN
local vectors = {1}
-- initialized (defined structure of best)
local best = { gflops = 0, b = 5, rm = 5, rn = 5, v = 1 }
if dotune then
-- local tunefor = 1024
local tunefor = 1024 -- full size of the matrix
--change for 10 later
local harness = require("cmult-matrixtestharness")
for _,b in ipairs(blocksizes) do
for _,rm in ipairs(regblocks) do
for _,rn in ipairs(regblocks) do
for _,v in ipairs(vectors) do
-- same until here
local my_cmul = gencmul(b,1,rm,rn)
if my_cmul then
print(b,rm,rn,v)
my_cmul:compile()
local i = math.floor(tunefor / b) * b
local curr_gflops = 0
local ctyp
local correct, exectimes = harness.timefunctionsCMUL(tostring(number),i,i,3,3, function(M,N,K,L,A,B,C)
my_cmul(nil,M,N,A,B,C,N)
end)
if not correct then print("<error>") break end
print(i,unpack (exectimes),"[OK]")
local curr_gflops = exectimes[1]
-- print(curr_gflops) -- print analysis
if best.gflops < curr_gflops then -- Maximization problem (the greater gflops, the better)
best = { gflops = curr_gflops, b = b, rm = rm, rn = rn, v = v }
terralib.tree.printraw(best)
end
end
end
end
end
end
end
-- local my_convolution = genconvolution(best.b,1,best.rm,best.rn,best.v)
-- terralib.saveobj("my_conv.o", {my_convolution = my_convolution})
|
reclusive_roba = Creature:new {
objectName = "@mob/creature_names:reclusive_roba",
socialGroup = "self",
faction = "",
level = 30,
chanceHit = 0.39,
damageMin = 290,
damageMax = 300,
baseXp = 3005,
baseHAM = 8400,
baseHAMmax = 10200,
armor = 0,
resists = {20,20,20,160,-1,160,-1,-1,-1},
meatType = "meat_carnivore",
meatAmount = 15,
hideType = "hide_leathery",
hideAmount = 30,
boneType = "bone_mammal",
boneAmount = 15,
milk = 0,
tamingChance = 0.25,
ferocity = 0,
pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY,
creatureBitmask = PACK,
optionsBitmask = AIENABLED,
diet = CARNIVORE,
templates = {"object/mobile/roba_hue.iff"},
hues = { 24, 25, 26, 27, 28, 29, 30, 31 },
scale = 1.1,
lootGroups = {},
weapons = {},
conversationTemplate = "",
attacks = {
{"stunattack",""},
{"blindattack",""}
}
}
CreatureTemplates:addCreatureTemplate(reclusive_roba, "reclusive_roba")
|
local panelData = {
type = "panel",
name = "Window Title",
displayName = "Longer Window Title",
author = "Seerah",
version = "1.3",
slashCommand = "/myaddon", --(optional) will register a keybind to open to this panel
registerForRefresh = true, --boolean (optional) (will refresh all options controls when a setting is changed and when the panel is shown)
registerForDefaults = true, --boolean (optional) (will set all options controls back to default values)
}
local optionsTable = {
[1] = {
type = "header",
name = "My Header",
width = "full", --or "half" (optional)
},
[2] = {
type = "description",
--title = "My Title", --(optional)
title = nil, --(optional)
text = "My description text to display. blah blah blah blah blah blah blah - even more sample text!!",
width = "full", --or "half" (optional)
},
[3] = {
type = "dropdown",
name = "My Dropdown",
tooltip = "Dropdown's tooltip text.",
choices = {"table", "of", "choices"},
getFunc = function() return "of" end,
setFunc = function(var) print(var) end,
width = "half", --or "half" (optional)
warning = "Will need to reload the UI.", --(optional)
},
[4] = {
type = "dropdown",
name = "My Dropdown",
tooltip = "Dropdown's tooltip text.",
choices = {"table", "of", "choices"},
getFunc = function() return "of" end,
setFunc = function(var) print(var) end,
width = "half", --or "half" (optional)
warning = "Will need to reload the UI.", --(optional)
},
[5] = {
type = "slider",
name = "My Slider",
tooltip = "Slider's tooltip text.",
min = 0,
max = 20,
step = 1, --(optional)
getFunc = function() return 3 end,
setFunc = function(value) d(value) end,
width = "half", --or "half" (optional)
default = 5, --(optional)
},
[6] = {
type = "button",
name = "My Button",
tooltip = "Button's tooltip text.",
func = function() d("button pressed!") end,
width = "half", --or "half" (optional)
warning = "Will need to reload the UI.", --(optional)
},
[7] = {
type = "submenu",
name = "Submenu Title",
tooltip = "My submenu tooltip", --(optional)
controls = {
[1] = {
type = "checkbox",
name = "My Checkbox",
tooltip = "Checkbox's tooltip text.",
getFunc = function() return true end,
setFunc = function(value) d(value) end,
width = "half", --or "half" (optional)
warning = "Will need to reload the UI.", --(optional)
},
[2] = {
type = "colorpicker",
name = "My Color Picker",
tooltip = "Color Picker's tooltip text.",
getFunc = function() return 1, 0, 0, 1 end, --(alpha is optional)
setFunc = function(r,g,b,a) print(r, g, b, a) end, --(alpha is optional)
width = "half", --or "half" (optional)
warning = "warning text",
},
[3] = {
type = "editbox",
name = "My Editbox",
tooltip = "Editbox's tooltip text.",
getFunc = function() return "this is some text" end,
setFunc = function(text) print(text) end,
isMultiline = false, --boolean
width = "half", --or "half" (optional)
warning = "Will need to reload the UI.", --(optional)
default = "", --(optional)
},
},
},
[8] = {
type = "custom",
reference = "MyAddonCustomControl", --unique name for your control to use as reference
refreshFunc = function(customControl) end, --(optional) function to call when panel/controls refresh
width = "half", --or "half" (optional)
},
[9] = {
type = "texture",
image = "EsoUI\\Art\\ActionBar\\abilityframe64_up.dds",
imageWidth = 64, --max of 250 for half width, 510 for full
imageHeight = 64, --max of 100
tooltip = "Image's tooltip text.", --(optional)
width = "half", --or "half" (optional)
},
}
local LAM = LibStub("LibAddonMenu-2.0")
LAM:RegisterAddonPanel("MyAddon", panelData)
LAM:RegisterOptionControls("MyAddon", optionsTable)
|
AddCSLuaFile()
local name = "Jaguar XFR SEG Photon"
local A = "AMBER"
local R = "RED"
local B = "BLUE"
local W = "WHITE"
local CW = "C_WHITE"
local SW = "S_WHITE"
local EMV = {}
EMV.Siren = 5
EMV.Color = nil
EMV.Skin = 0
EMV.Positions = {
--Front Grill
{ Vector(-7.25,114.075,32.6), Angle(0,0,25.2), "led_sqr" }, -- 1
{ Vector(7.25,114.075,32.6), Angle(0,0,25.2), "led_sqr" }, -- 2
{ Vector(41.6,96.15,30.165), Angle(0,-60,0), "led_single" }, -- 3
{ Vector(-41.6,96.15,30.165), Angle(0,60,0), "led_single" }, -- 4
{ Vector(39.897,-94.9,29.867), Angle(0,-120,0), "led_single" }, -- 5
{ Vector(-39.897,-94.9,29.867), Angle(0,120,0), "led_single" }, -- 6
}
EMV.Sections = {
["grill"] = {
{ {1,B} },
{ {2,B} },
{ {2,B}, {1,B} },
{ {2,B,.6}, {1,B,.6} },
},
["sidelights"] = {
{ {3,B} },
{ {4,B} },
{ {3,B}, {4,B} },
{ {5,B}, {6,B} },
{ {3,B,.6}, {4,B,.6}, {5,B,.6}, {6,B,.6} },
{ {3,B}, {4,B}, {5,B}, {6,B} },
}
}
EMV.Patterns = { -- 0 = blank
["grill"] = {
["code1"] = {
1,1,1,2,2,2
},
["code2"] = {
1,0,1,0,2,0,2,0
},
["steady"] = {
3,4
}
},
["sidelights"] = {
["code1"] = {
3,0,3,0,3,0,4,0,4,0,4,0
},
["code2"] = {
3,0,3,0,4,0,4,0
},
["steady"] = {
6,5
}
}
}
EMV.Sequences = {
Sequences = {
{
Name = "ESCORT",
Components = {
["grill"] = "code1",
["sidelights"] = "code1"
},
Disconnect = {}
},
{
Name = "HIGH PRIORITY",
Components = {
["grill"] = "code2",
["sidelights"] = "code2"
},
Disconnect = {}
},
{
Name = "STEADY",
Components = {
["grill"] = "steady",
["sidelights"] = "steady"
},
Disconnect = {}
},
}
}
EMV.Meta = {
led_sqr = {
AngleOffset = -90,
W = 1.6,
H = 4.8,
Sprite = "sprites/emv/led_square"
},
led_single = {
AngleOffset = -90,
Scale = 0.45,
W = 1.2,
H = 1.2,
Sprite = "sprites/emv/led_single"
},
}
local PI = {}
PI.Meta = {
}
PI.Positions = {
}
PI.States = {}
PI.States.Headlights = {}
PI.States.Brakes = {}
PI.States.Blink_Left = {}
PI.States.Blink_Right = {}
PI.States.Reverse = {}
PI.States.Running = {}
local V = {
// Required information
Name = name,
Class = "prop_vehicle_jeep",
Category = "Emergency Vehicles",
// Optional information
Author = "LoneWolfie, Schmal",
Information = "vroom vroom",
Model = "models/LoneWolfie/jaguar_xfr_pol_und.mdl",
KeyValues = {
vehiclescript = "scripts/vehicles/LWCars/jag_xfr_pol.txt"
},
IsEMV = true,
EMV = EMV,
HasPhoton = true,
Photon = PI
}
list.Set( "Vehicles", V.Name, V )
if EMVU then EMVU:OverwriteIndex( name, EMV ) end
if Photon then Photon:OverwriteIndex( name, PI ) end |
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Packages = script.Parent.Parent.Parent
local Roact = require(Packages.Roact)
local ClientContext = require(script.Parent.ClientContext)
local BusControlsInner = Roact.Component:extend("BusControlsInner")
function BusControlsInner:init()
self.clientSession = self.props.clientSession
end
function BusControlsInner:render()
return nil
end
function BusControlsInner:didMount()
self.connections = {
RunService.Stepped:Connect(function()
local leftDown = UserInputService:IsKeyDown(Enum.KeyCode.A)
local rightDown = UserInputService:IsKeyDown(Enum.KeyCode.D)
if rightDown then
self.clientSession:setSteeringInput(1)
elseif leftDown then
self.clientSession:setSteeringInput(-1)
else
self.clientSession:setSteeringInput(0)
end
end)
}
end
function BusControlsInner:willUnmount()
for _, connection in ipairs(self.connections) do
connection:Disconnect()
end
self.connections = {}
end
local function BusControls()
return ClientContext.with(function(clientSession)
return Roact.createElement(BusControlsInner, {
clientSession = clientSession,
})
end)
end
return BusControls |
local function runString (commandstring)
outputChatBoxR("Executing client-side command: "..commandstring)
local notReturned
--First we test with return
local commandFunction,errorMsg = loadstring("return "..commandstring)
if errorMsg then
--It failed. Lets try without "return"
notReturned = true
commandFunction, errorMsg = loadstring(commandstring)
end
if errorMsg then
--It still failed. Print the error message and stop the function
outputChatBoxR("Error: "..errorMsg)
return
end
--Finally, lets execute our function
results = { pcall(commandFunction) }
if not results[1] then
--It failed.
outputChatBoxR("Error: "..results[2])
return
end
if not notReturned then
local resultsString = ""
local first = true
for i = 2, #results do
if first then
first = false
else
resultsString = resultsString..", "
end
local resultType = type(results[i])
if isElement(results[i]) then
resultType = "element:"..getElementType(results[i])
end
resultsString = resultsString..tostring(results[i]).." ["..resultType.."]"
end
outputChatBoxR("Command results: "..resultsString)
elseif not errorMsg then
outputChatBoxR("Command executed!")
end
end
addCommandHandler("crunt",
function (command, ...)
runString(table.concat({...}, " "))
end
)
function outputChatBoxR(message)
return outputChatBox(message, 200, 250, 200)
end
-- dump the element tree
function map(element, level)
level = level or 0
element = element or getRootElement()
local indent = string.rep(' ', level)
local eType = getElementType(element)
local eID = getElementID(element)
local eChildren = getElementChildren(element)
local tagStart = '<'..eType
if eID then
tagStart = tagStart..' id="'..eID..'"'
end
if #eChildren < 1 then
outputConsole(indent..tagStart..'"/>')
else
outputConsole(indent..tagStart..'">')
for k, child in ipairs(eChildren) do
map(child, level+1)
end
outputConsole(indent..'</'..eType..'>')
end
end
|
local BaseInstance = import("./BaseInstance")
local AnalyticsService = import("./AnalyticsService")
local ContentProvider = import("./ContentProvider")
local CoreGui = import("./CoreGui")
local ContextActionService = import("./ContextActionService")
local CorePackages = import("./CorePackages")
local CreatorType = import("../Enum/CreatorType")
local GuiService = import("./GuiService")
local HttpRbxApiService = import("./HttpRbxApiService")
local HttpService = import("./HttpService")
local InsertService = import("./InsertService")
local InstanceProperty = import("../InstanceProperty")
local LocalizationService = import("./LocalizationService")
local MarketplaceService = import("./MarketplaceService")
local NotificationService = import("./NotificationService")
local Players = import("./Players")
local ReplicatedFirst = import("./ReplicatedFirst")
local ReplicatedStorage = import("./ReplicatedStorage")
local RunService = import("./RunService")
local ServerScriptService = import("./ServerScriptService")
local ServerStorage = import("./ServerStorage")
local StarterPlayer = import("./StarterPlayer")
local Stats = import("./Stats")
local TestService = import("./TestService")
local TextService = import("./TextService")
local TweenService = import("./TweenService")
local UserInputService = import("./UserInputService")
local VirtualInputManager = import("./VirtualInputManager")
local Workspace = import("./Workspace")
local Game = BaseInstance:extend("DataModel")
function Game:init(instance)
AnalyticsService:new().Parent = instance
ContentProvider:new().Parent = instance
CoreGui:new().Parent = instance
CorePackages:new().Parent = instance
ContextActionService:new().Parent = instance
GuiService:new().Parent = instance
HttpRbxApiService:new().Parent = instance
HttpService:new().Parent = instance
InsertService:new().Parent = instance
LocalizationService:new().Parent = instance
MarketplaceService:new().Parent = instance
NotificationService:new().Parent = instance
Players:new().Parent = instance
ReplicatedFirst:new().Parent = instance
ReplicatedStorage:new().Parent = instance
RunService:new().Parent = instance
ServerScriptService:new().Parent = instance
ServerStorage:new().Parent = instance
StarterPlayer:new().Parent = instance
Stats:new().Parent = instance
TestService:new().Parent = instance
TextService:new().Parent = instance
TweenService:new().Parent = instance
UserInputService:new().Parent = instance
VirtualInputManager:new().Parent = instance
Workspace:new().Parent = instance
end
function Game.prototype:GetService(serviceName)
local service = self:FindFirstChildOfClass(serviceName)
if service then
return service
end
-- TODO: Load the service if possible?
error(string.format("Cannot get service %q", tostring(serviceName)), 2)
end
Game.properties.CreatorId = InstanceProperty.readOnly({
getDefault = function()
return 0
end,
})
Game.properties.CreatorType = InstanceProperty.readOnly({
getDefault = function()
return CreatorType.User
end,
})
Game.properties.GameId = InstanceProperty.readOnly({
getDefault = function()
return 0
end,
})
Game.properties.JobId = InstanceProperty.readOnly({
getDefault = function()
return ""
end,
})
Game.properties.PlaceId = InstanceProperty.readOnly({
getDefault = function()
return 0
end,
})
Game.properties.PlaceVersion = InstanceProperty.readOnly({
getDefault = function()
return 0
end,
})
Game.properties.VIPServerId = InstanceProperty.readOnly({
getDefault = function()
return ""
end,
})
Game.properties.VIPServerOwnerId = InstanceProperty.readOnly({
getDefault = function()
return 0
end,
})
return Game |
Pipe = Class{}
PIPE_IMAGE = {
['red'] = love.graphics.newImage('assets/sprites/pipe/RedPipe.png'),
['blue'] = love.graphics.newImage('assets/sprites/pipe/BluePipe.png'),
['green'] = love.graphics.newImage('assets/sprites/pipe/GreenPipe.png'),
}
function Pipe:init(offset, isTop)
self.color = 'blue'
self.isTop = isTop or false
self.width = PIPE_IMAGE[self.color]:getWidth()
self.height = PIPE_IMAGE[self.color]:getHeight()
self.dx = -300
self.x = WINDOW_WIDTH + self.width/2 + 10
self.y = WINDOW_HEIGHT/2 + offset
if self.isTop then
self.y = self.y - self.height/2
else
self.y = self.y + self.height/2
end
end
function Pipe:setColor(color)
assert(color == 'red' or color == 'blue' or color == 'green')
self.color = color
end
function Pipe:update(dt)
self.x = self.x + self.dx * dt
end
function Pipe:render()
if self.isTop then
love.graphics.draw(PIPE_IMAGE[self.color], self.x - self.width/2, self.y + self.height/2, 0, 1.1, -1)
else
love.graphics.draw(PIPE_IMAGE[self.color], self.x - self.width/2, self.y - self.height/2, 0, 1.1, 1)
end
end
|
local Class = require("lib.middleclass")
local Frequency = Class("Frequency")
function Frequency:initialize(r, g, b)
self.r = r
self.g = g
self.b = b
end
return Frequency |
local utils = require(GetScriptDirectory() .. "/util")
local npcBot = GetBot();
local castSFDesire = 0;
local MoveDesire = 0;
local AttackDesire = 0;
local npcBotAR = 0;
local ProxRange = 1500;
function MinionThink( hMinionUnit )
if not hMinionUnit:IsNull() and hMinionUnit ~= nil then
if string.find(hMinionUnit:GetUnitName(), "npc_dota_visage_familiar") then
if ( hMinionUnit:IsUsingAbility() or not hMinionUnit:IsAlive() ) then return end
abilitySF = hMinionUnit:GetAbilityByName( "visage_summon_familiars_stone_form" );
castSFDesire = ConsiderStoneForm(hMinionUnit);
AttackDesire, AttackTarget = ConsiderAttacking(hMinionUnit);
MoveDesire, Location = ConsiderMove(hMinionUnit);
RetreatDesire, RetreatLocation = ConsiderRetreat(hMinionUnit);
if castSFDesire > 0 then
--print("sf")
hMinionUnit:Action_UseAbility(abilitySF);
return
end
if (AttackDesire > 0)
then
--print("attack")
hMinionUnit:Action_AttackUnit( AttackTarget, true );
return
end
if ( RetreatDesire > 0 )
then
--print("retreat")
hMinionUnit:Action_MoveToLocation( RetreatLocation );
return;
end
if (MoveDesire > 0)
then
--print("move")
hMinionUnit:Action_MoveToLocation( Location );
return
end
end
end
end
function CanBeAttacked( npcTarget )
return npcTarget:CanBeSeen() and not npcTarget:IsInvulnerable();
end
function IsDisabled(npcTarget)
if npcTarget:IsRooted( ) or npcTarget:IsStunned( ) or npcTarget:IsHexed( ) or npcTarget:IsNightmared( ) or npcTarget:IsSilenced( ) then
return true;
end
return false;
end
function GetBase()
local RB = Vector(-7200,-6666)
local DB = Vector(7137,6548)
if GetTeam( ) == TEAM_DIRE then
return DB;
elseif GetTeam( ) == TEAM_RADIANT then
return RB;
end
end
function ConsiderStoneForm(hMinionUnit)
if not abilitySF:IsFullyCastable() or
hMinionUnit:HasModifier("modifier_visage_summon_familiars_stone_form_buff")
then
return BOT_ACTION_DESIRE_NONE;
end
local nRadius = abilitySF:GetSpecialValueInt("stun_radius");
local nHealth = hMinionUnit:GetHealth() / hMinionUnit:GetMaxHealth();
local SAStack = 0;
local npcModifier = hMinionUnit:NumModifiers();
for i = 0, npcModifier
do
if hMinionUnit:GetModifierName(i) == "modifier_visage_summon_familiars_damage_charge" then
SAStack = hMinionUnit:GetModifierStackCount(i);
break;
end
end
if nHealth < 0.55 then
return BOT_ACTION_DESIRE_HIGH;
end
if ( npcBot:GetActiveMode() == BOT_MODE_RETREAT and npcBot:GetActiveModeDesire() >= BOT_MODE_DESIRE_HIGH )
then
local tableNearbyEnemyHeroes = hMinionUnit:GetNearbyHeroes( nRadius, true, BOT_MODE_NONE );
if tableNearbyEnemyHeroes ~= nil and #tableNearbyEnemyHeroes >= 1 then
return BOT_ACTION_DESIRE_HIGH;
end
end
if SAStack < 1 then
local tableNearbyEnemyHeroes = hMinionUnit:GetNearbyHeroes( nRadius, true, BOT_MODE_NONE );
if tableNearbyEnemyHeroes ~= nil and #tableNearbyEnemyHeroes >= 1 then
return BOT_ACTION_DESIRE_HIGH;
end
end
return BOT_ACTION_DESIRE_NONE;
end
function ConsiderAttacking(hMinionUnit)
if hMinionUnit:HasModifier("modifier_visage_summon_familiars_stone_form_buff")
then
return BOT_ACTION_DESIRE_NONE, {};
end
local target = npcBot:GetTarget();
local AR = hMinionUnit:GetAttackRange();
local OAR = npcBot:GetAttackRange();
local AD = hMinionUnit:GetAttackDamage();
if target == nil or target:IsTower() or target:IsBuilding() then
target = npcBot:GetAttackTarget();
end
if target ~= nil and CanBeAttacked(target) and GetUnitToUnitDistance(hMinionUnit, npcBot) <= ProxRange then
return BOT_ACTION_DESIRE_MODERATE, target;
end
local enemies = npcBot:GetNearbyHeroes(1300, true, BOT_MODE_NONE);
if not npcBot:IsAlive() or ( npcBot:GetActiveMode() == BOT_MODE_RETREAT and #enemies == 0 ) then
local followTarget = nil;
local closest = nil;
local closestDist = 100000;
for i,id in pairs(GetTeamPlayers(GetTeam())) do
local member = GetTeamMember(i);
if member ~= nil and member:IsAlive() then
local target = member:GetTarget();
if target == nil or target:IsTower() or target:IsBuilding() then
target = member:GetAttackTarget();
end
local distance = GetUnitToUnitDistance(member, hMinionUnit);
if target ~= nil and GetUnitToUnitDistance(member, target) <= ProxRange and distance < closestDist then
closest = member;
closestDist = distance;
followTarget = target;
end
end
end
if closest ~= nil and followTarget ~= nil then
return BOT_ACTION_DESIRE_MODERATE, followTarget;
end
end
return BOT_ACTION_DESIRE_NONE, 0;
end
function ConsiderMove(hMinionUnit)
if hMinionUnit:HasModifier("modifier_visage_summon_familiars_stone_form_buff") or not npcBot:IsAlive() or GetUnitToUnitDistance(hMinionUnit, npcBot) < 100
then
return BOT_ACTION_DESIRE_NONE, {};
end
local target = npcBot:GetAttackTarget()
if target == nil or ( target ~= nil and not CanBeAttacked(target) ) or (target ~= nil and GetUnitToUnitDistance(target, npcBot) > ProxRange) then
return BOT_ACTION_DESIRE_MODERATE, npcBot:GetXUnitsTowardsLocation(Vector(0, 0, 0), 200);
end
return BOT_ACTION_DESIRE_NONE, 0;
end
function ConsiderRetreat(hMinionUnit)
if hMinionUnit:HasModifier("modifier_visage_summon_familiars_stone_form_buff") or hMinionUnit:DistanceFromFountain() == 0
then
return BOT_ACTION_DESIRE_NONE, {};
end
if not npcBot:IsAlive() then
local loc = GetBase()
return BOT_ACTION_DESIRE_HIGH, loc;
end
return BOT_ACTION_DESIRE_NONE, 0;
end
|
-- @Author: KevinZhang
-- @Date: 2017-11-14 20:58:55
-- @Last Modified by KevinZhang
-- @Last Modified time 2018-01-22 11:23:31
local TongZhang = import("..base.TongZhang")
local CardBase = import("..base.CardBase")
local M = class(TongZhang)
-- 牌型:对子
-- 特征:牌点相同的两张牌,不区分花色
function M:ctor(data,ruleDao)
local args = {2,2}
TongZhang.init(self,args)
end
return M; |
---------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
-- INTERPOLATION HELPERS ------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
-- Creates new interpolator, returns its handle
function newInterpolator(...)
local arg = {...}
local input = {}
local value = {}
if #arg == 1 then
input = { arg[1][1] }
value = arg[1][2]
return sasl.newCPPInterpolator(input, value)
end
local N = #arg - 1
local matrix = arg[N + 1]
local size = 1
if N == 0 then
logError('newInterpolator: Number of input arguments into an interpolator must be greater than zero')
return
end
for i = 1,N do
input[i] = arg[i]
size = size * #arg[i]
end
value = extractArrayData(matrix)
if #value ~= size then
logError('newInterpolator: Size dimensions mismatch')
return
end
return sasl.newCPPInterpolator(input, value)
end
---------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
-- Deletes provided interpolator-object
function deleteInterpolator(handle)
sasl.deleteCPPInterpolator(handle)
end
---------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
-- Interpolates current point
function interpolate(x, interp, flag)
if assert(type(x)) == 'number' then
x = { x }
end
if flag == nil then
flag = false
end
return sasl.interpolateCPP(interp, x, flag)
end
---------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
-- Creates self-interpolator object
function selfInterpolator(...)
local r = {}
r.interp = newInterpolator(...)
local temp = function(x, flag)
return interpolate(x, r.interp, flag)
end
r.interpolate = temp
return r
end
---------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------- |
local NegInversion, parent = torch.class('nn.NegInversion', 'nn.Module')
function NegInversion:__init(inversion)
parent.__init(self)
self.inversion = inversion or nil
end
function NegInversion:updateOutput(input)
self.output = input
--print(self.inversion:nElement().."->"..self.output:size(2))
if self.inversion ~= nil and self.inversion:nElement() == self.output:size(2) then
for j=1,self.output:size(2) do
self.output[{{},j}] = (self.inversion[j] > 0) and torch.mul(self.output[{{},j}],-1) or self.output[{{},j}] -- inefficient
end
end
return self.output
end
function NegInversion:updateGradInput(input, gradOutput)
self.gradInput = gradOutput
return self.gradInput
end
function NegInversion:__tostring__()
return torch.type(self)
end
|
return {
---entire buffer text object
setup = function()
vim.keymap.set('x', 'ie', '<cmd>keepjumps normal! gg0oG$<cr>', { silent = true })
vim.keymap.set('x', 'ae', '<cmd>keepjumps normal! gg0oG$<cr>', { silent = true })
vim.keymap.set('o', 'ie', '<cmd>keepjumps normal! ggVG<cr>', { silent = true })
vim.keymap.set('o', 'ae', '<cmd>keepjumps normal! ggVG<cr>', { silent = true })
end
}
|
--
-- Copyright 2010-2021 Branimir Karadzic. All rights reserved.
-- License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
--
project "geometryc"
uuid (os.uuid("geometryc"))
kind "ConsoleApp"
includedirs {
path.join(BX_DIR, "include"),
path.join(BGFX_DIR, "include"),
path.join(BGFX_DIR, "3rdparty"),
path.join(BGFX_DIR, "examples/common"),
}
files {
path.join(BGFX_DIR, "3rdparty/meshoptimizer/src/**.cpp"),
path.join(BGFX_DIR, "3rdparty/meshoptimizer/src/**.h"),
path.join(BGFX_DIR, "src/vertexlayout.**"),
path.join(BGFX_DIR, "tools/geometryc/**.cpp"),
path.join(BGFX_DIR, "tools/geometryc/**.h"),
path.join(BGFX_DIR, "examples/common/bounds.**"),
}
using_bx();
configuration { "mingw-*" }
targetextension ".exe"
links {
"psapi",
}
configuration { "osx*" }
links {
"Cocoa.framework",
}
configuration { "vs20*" }
links {
"psapi",
}
configuration {}
strip()
|
require(game.ServerScriptService.Server.runTests)()
|
return {
postgres = {
up = [[
DO $$
BEGIN
ALTER TABLE IF EXISTS ONLY "header_translator_dictionary" ADD "cache_key" TEXT UNIQUE;
EXCEPTION WHEN DUPLICATE_COLUMN THEN
-- Do nothing, accept existing state
END;
$$;
]]
},
cassandra = {
up = [[
ALTER TABLE header_translator_dictionary ADD cache_key text;
CREATE INDEX IF NOT EXISTS ON header_translator_dictionary (cache_key);
]]
}
} |
local Core = {}
--Quick to use empty sprite
function Core.empty_sprite()
return {
filename = "__core__/graphics/empty.png",
priority = "extra-high",
width = 1,
height = 1
}
end
--Quick to use empty animation
function Core.empty_animation()
return {
filename = Core.empty_sprite().filename,
width = Core.empty_sprite().width,
height = Core.empty_sprite().height,
line_length = 1,
frame_count = 1,
shift = {0, 0},
animation_speed = 1,
direction_count=1
}
end
-- render layers
----"tile-transition", "resource", "decorative", "remnants", "floor", "transport-belt-endings", "corpse", "floor-mechanics", "item", "lower-object", "object", "higher-object-above",
----"higher-object-under", "wires", "lower-radius-visualization", "radius-visualization", "entity-info-icon", "explosion", "projectile", "smoke", "air-object", "air-entity-info-con",
----"light-effect", "selection-box", "arrow", "cursor"
-- collision masks
----"ground-tile", "water-tile", "resource-layer", "floor-layer", "item-layer", "object-layer", "player-layer", "ghost-layer", "doodad-layer", "not-colliding-with-itself"
return Core
|
--
-- Copyright (c) 2017, Jesse Freeman. All rights reserved.
--
-- Licensed under the Microsoft Public License (MS-PL) License.
-- See LICENSE file in the project root for full license information.
--
-- Contributors
-- --------------------------------------------------------
-- This is the official list of Pixel Vision 8 contributors:
--
-- Jesse Freeman - @JesseFreeman
-- Christer Kaitila - @McFunkypants
-- Pedro Medeiros - @saint11
-- Shawn Rakowski - @shwany
--
MouseCursor = {}
MouseCursor.__index = MouseCursor
-- TODO this should be set up like all of the other UI components and not its own object
function MouseCursor:Init()
-- Create a new object for the instance and register it
local _mouseCursor = {}
setmetatable(_mouseCursor, MouseCursor)
-- This defines which set of data to use when drawing the cursor
_mouseCursor.cursorID = 1
-- Reference data for each of the different mouse cursors
_mouseCursor.cursors = {
-- Pointer
{
spriteData = cursorpointer,
offset = {
x = 0,
y = 0
}
},
-- Hand (for interaction)
{
spriteData = cursorhand,
offset = {
x = -6,
y = 0
}
},
-- Input
{
spriteData = cursortext,
offset = {
x = -2,
y = -3
}
},
-- Help (for showing tool tips)
{
spriteData = cursorhelp,
offset = {
x = -2,
y = -3
}
},
-- Wait
{
spriteData = cursorwait,
offset = {
x = -2,
y = -3
}
},
-- Pencil
{
spriteData = cursordraw,
offset = {
x = -2,
y = -3
}
},
-- Eraser
{
spriteData = cursorerase,
offset = {
x = -2,
y = -3
}
}
}
_mouseCursor.pos = {x = -1, y = -1}
-- Return the new instance of the editor ui
return _mouseCursor
end
function MouseCursor:Update(timeDelta, collisionState)
-- Get the collision state's mouse cursor values
--self.cursorID = collisionState.cursorID
-- save the current mouse position
self.pos.x = collisionState.mousePos.x
self.pos.y = collisionState.mousePos.y
end
function MouseCursor:Draw()
-- Need to make sure the mouse is not off screen before drawing it
if(self.pos.x < 0 or self.pos.y < 0) then
return
end
-- get the current sprite data for the current cursor
local cursorData = self.cursors[self.cursorID]
-- Make sure the data isn't undefined
if(cursorData ~= nil) then
local spriteData = cursorData.spriteData
if(spriteData ~= nil) then
-- Draw the new cursor taking into account the cursors offset
DrawSprites(cursorData.spriteData.spriteIDs, self.pos.x + cursorData.offset.x, self.pos.y + cursorData.offset.y, spriteData.width, false, false, DrawMode.SpriteAbove, 0, true, false)
end
end
end
|
--[[
© 2020 TERRANOVA do not share, re-distribute or modify
without permission of its author (zacharyenriquee@gmail.com).
--]]
local Schema = Schema;
local PLUGIN = PLUGIN;
util.AddNetworkString("ixCpSystemRequestTaglines")
util.AddNetworkString("ixCpSystemReceiveTaglines")
function PLUGIN:LoadData()
for _, v in ipairs(self:GetData() or {}) do
local entity = ents.Create("ix_uniformgen")
entity:SetPos(v.pos)
entity:SetAngles(v.angles)
entity:Spawn()
entity:SetModel(v.model)
entity:SetSkin(v.skin or 0)
entity:SetSolid(SOLID_BBOX)
entity:PhysicsInit(SOLID_BBOX)
local physObj = entity:GetPhysicsObject()
if (IsValid(physObj)) then
physObj:EnableMotion(false)
physObj:Sleep()
end
end
local query = mysql:Select("ix_characters")
query:Select("faction")
query:Select("data")
query:WhereLike("faction", "metropolice")
query:Callback(function(result)
if (istable(result) and #result > 0) then
for k, v in pairs(result) do
local data = util.JSONToTable(v.data or "[]")
if(data.cpTagline != nil and data.cpID != nil and cpSystem.cache.taglines) then
table.insert(cpSystem.cache.taglines, {
tagline = data.cpTagline,
id = tonumber(data.cpID)
})
end
end
end
end)
query:Execute()
end
-- Add to the cache that was built on server launch since it doesn't auto refresh the server query for performance reasons.
function PLUGIN:OnCharacterCreated(client, character)
if(character:IsMetropolice()) then
self:AddToCache(character)
self:SendCache()
end
end
-- Remove from the cache when a character is deleted.
function PLUGIN:PreCharacterDeleted(client, character)
self:RemoveFromCache(character)
self:SendCache()
end
function PLUGIN:RemoveFromCache(character)
if(character:IsMetropolice()) then
local tagline = character:GetData("cpTagline")
local id = character:GetData("cpID")
if(id and tagline) then
for k, v in pairs(cpSystem.cache.taglines) do
if(v.tagline == tagline and v.id == id) then
cpSystem.cache.taglines[k] = nil
end
end
end
end
end
function PLUGIN:AddToCache(character)
if(character:IsMetropolice()) then
table.insert(cpSystem.cache.taglines, {
tagline = character:GetTagline() or character:GetData("cpTagline"),
id = character:GetCpid() or tonumber(character:GetData("cpID"))
})
end
end
-- Rebuild for all clients
function PLUGIN:SendCache()
for _, v in ipairs(player.GetAll()) do
netstream.Start(v, "ReceiveTaglineCache", cpSystem.cache.taglines)
end
end
function Schema:PlayerFootstep(client, position, foot, soundName, volume)
local factionTable = ix.faction.Get(client:Team());
local character = client:GetCharacter();
if(character:IsUndercover()) then
client:EmitSound(soundName);
return true;
end;
if (factionTable.runSounds and client:IsRunning()) then
if(istable(factionTable.runSounds[foot])) then
local rand = math.random(1, #factionTable.runSounds[foot])
client:EmitSound(factionTable.runSounds[foot][rand])
else
client:EmitSound(factionTable.runSounds[foot]);
end
return true;
end
client:EmitSound(soundName);
return true;
end
function PLUGIN:PlayerLoadedCharacter(client, character)
local faction = character:GetFaction()
if(faction == FACTION_SCN) then
character:SetClass(CLASS_SCN);
end;
if(faction == FACTION_MPF) then
self:CheckForErrors(client, character)
if(character:GetName() == character:GetCPName()) then
if(!string.find(character:GetName(), ix.config.Get("City Name"))) then
character:SetName(character:GetCPName());
end;
end;
end;
-- Adds player to the correct class --
if(faction == FACTION_MPF) then
if (!string.find(character:GetName(), ix.config.Get("City Name"))) then
character:SetClass(CLASS_MPUH);
character:SetCustomClass("Citizen");
else
character:SetClass(CLASS_MPU);
character:SetCustomClass("Civil Protection");
end;
end;
end;
-- Sometimes data might disappear. Make sure we always have data.
function PLUGIN:CheckForErrors(client, character)
local faction = character:GetFaction()
if(!character:GetData("cpID")) then
character:SetData("cpID", 1);
end
if(!character:GetData("cpTagline")) then
character:SetData("cpTagline", "ERROR");
end
if(!character:GetData("rank")) then
character:SetData("rank", ix.ranks.GetDefaultRank(faction))
end
if(!character:GetData("cpCitizenName")) then
character:SetData("cpCitizenName", "Fatal error")
end
if(!character:GetData("cpCitizenDesc")) then
character:SetData("cpCitizenDesc", "Fatal error")
end
if(!character:GetData("cpDesc")) then
character:SetData("cpDesc", "Fatal error")
end
end
-- Called just after a player spawns.
function PLUGIN:PlayerSpawn(client)
if (client:IsCombine()) then
netstream.Start(client, "RecalculateHUDObjectives", PLUGIN.socioStatus)
end;
end;
function PLUGIN:OnCharacterRankChanged(character, target, rank)
if(target:IsMetropolice()) then
local notification = cpSystem.config.notification;
notification.text = "Your rank has been changed to:";
notification.additional = string.format("'Rank - %s'", rank.displayName)
ix.notify.SendMessage(target:GetPlayer(), notification);
target:UpdateCPStatus()
end;
end
-- Called when we need to setup bodygroups for a rank
function PLUGIN:SetupRankBodygroups(character)
if(character:IsMetropolice()) then
if(!character:IsUndercover()) then
local spec = character:GetSpec()
local rank = character:GetRank()
for k, v in pairs(character:GetRankBodygroups()) do
if((spec and k == 2) and rank.overrideBodygroup != true) then
character:GetPlayer():SetBodygroup(k, v+spec.offset)
else
character:GetPlayer():SetBodygroup(k, v)
end
end
end
return false
else
return true
end
end
net.Receive("ixCpSystemRequestTaglines", function(length, client)
net.Start("ixCpSystemReceiveTaglines")
net.WriteTable(cpSystem.cache.taglines or {})
net.Send(client)
end) |
IncludeDir = {}
IncludeDir["redaxe"] = "%{wks.location}/Redaxe"
IncludeDir["glad"] = "%{wks.location}/Redaxe/vendor/Glad/include"
IncludeDir["glfw"] = "%{wks.location}/Redaxe/vendor/Glfw/include"
IncludeDir["spdlog"] = "%{wks.location}/Redaxe/vendor/SpdLog/include"
IncludeDir["imgui"] = "%{wks.location}/Redaxe/vendor/ImGui"
IncludeDir["glm"] = "%{wks.location}/Redaxe/vendor/Glm/glm"
LibraryDir = {}
-- LibraryDir["name"] = "path"
Libraries = {}
-- Libraries["name"] = "path" |
----------------------------------------------------------------------------------------------------
-- This is a singleton class that manages MOAIDeck.
--
-- @author Makoto
-- @release V3.0.0
----------------------------------------------------------------------------------------------------
-- import
local Config = require "candy.Config"
local Resources = require "candy.asset.Resources"
---@class DeckMgr
local DeckMgr = {}
-- Deck Caches
DeckMgr.imageDecks = setmetatable ( {}, {__mode = "v"} )
DeckMgr.tileImageDecks = setmetatable ( {}, {__mode = "v"} )
DeckMgr.atlasDecks = setmetatable ( {}, {__mode = "v"} )
DeckMgr.nineImageDecks = {} -- setmetatable ( {}, { __mode = "v" } )
---
-- Return the Deck to be used in the Image.
---@param width width
---@param height height
---@param flipX (Optional)flipX
---@param flipY (Optional)flipY
---@return deck
function DeckMgr:getImageDeck ( width, height, flipX, flipY )
flipX = flipX and true or false
flipY = flipY and true or false
local key = width .. "$" .. height .. "$" .. tostring ( flipX ) .. "$" .. tostring ( flipY )
local cache = self.imageDecks
if not cache[ key ] then
cache[ key ] = self:createImageDeck ( width, height, flipX, flipY )
end
return cache[ key ]
end
---
-- Create the Deck to be used in the Image.
---@param width width
---@param height height
---@param flipX (Optional)flipX
---@param flipY (Optional)flipY
---@return deck
function DeckMgr:createImageDeck ( width, height, flipX, flipY )
if Config.VIEWPORT_YFLIP then
flipY = not flipY
end
local u0 = flipX and 1 or 0
local v0 = flipY and 1 or 0
local u1 = flipX and 0 or 1
local v1 = flipY and 0 or 1
local deck = MOAISpriteDeck2D.new ()
deck:setUVRect ( u0, v0, u1, v1 )
deck:setRect ( 0, 0, width, height )
deck.flipX = flipX
deck.flipY = flipY
return deck
end
---
-- Return the Deck to be used in the SheetImage.
---@param textureWidth texture width
---@param textureHeight texture height
---@param tileWidth tile width
---@param tileHeight tile height
---@param spacing spacing
---@param margin margin
---@param gridFlag grid flag
---@param flipX (option)flipX
---@param flipY (option)flipY
---@return deck
function DeckMgr:getTileImageDeck ( textureWidth, textureHeight, tileWidth, tileHeight, spacing, margin, gridFlag, flipX, flipY )
flipX = flipX and true or false
flipY = flipY and true or false
local tw, th = textureWidth, textureHeight
local key = tw .. "$" .. th .. "$" .. tileWidth .. "$" .. tileHeight .. "$" .. spacing .. "$" .. margin .. "$" .. tostring ( gridFlag ) .. "$" .. tostring (flipX) .. "$" .. tostring (flipY)
local cache = self.tileImageDecks
if not cache[ key ] then
cache[ key ] = self:createTileImageDeck ( tw, th, tileWidth, tileHeight, spacing, margin, gridFlag, flipX, flipY )
end
return cache[ key ]
end
---
-- Create the Deck to be used in the SheetImage.
---@param textureWidth texture width
---@param textureHeight texture height
---@param tileWidth tile width
---@param tileHeight tile height
---@param spacing spacing
---@param margin margin
---@param gridFlag grid flag
---@param flipX (option)flipX
---@param flipY (option)flipY
---@return deck
function DeckMgr:createTileImageDeck ( textureWidth, textureHeight, tileWidth, tileHeight, spacing, margin, gridFlag, flipX, flipY )
local tw, th = textureWidth, textureHeight
local tileX = math.floor ( (tw - margin) / (tileWidth + spacing) )
local tileY = math.floor ( (th - margin) / (tileHeight + spacing) )
local deck = MOAIGfxQuadDeck2D.new ()
deck.type = "TileImageDeck"
deck.sheetSize = tileX * tileY
deck:reserve ( deck.sheetSize )
deck.textureWidth = textureWidth
deck.textureHeight = textureHeight
deck.tileWidth = tileWidth
deck.tileHeight = tileHeight
deck.spacing = spacing
deck.margin = margin
deck.gridFlag = gridFlag
deck.flipX = flipX
deck.flipY = flipY
local i = 1
for y = 1, tileY do
for x = 1, tileX do
local sx = (x - 1) * (tileWidth + spacing) + margin
local sy = (y - 1) * (tileHeight + spacing) + margin
local ux0 = sx / tw
local uy0 = sy / th
local ux1 = (sx + tileWidth) / tw
local uy1 = (sy + tileHeight) / th
if not gridFlag then
deck:setRect ( i, 0, 0, tileWidth, tileHeight )
end
deck:setUVRect ( i, flipX and ux1 or ux0, flipY and uy1 or uy0, flipX and ux0 or ux1, flipY and uy0 or uy1 )
i = i + 1
end
end
return deck
end
---
-- Return the Deck for displaying TextureAtlas.
---@param luaFilePath TexturePacker lua file path
---@param flipX (option)flipX
---@param flipY (option)flipY
---@return Texture atlas deck
function DeckMgr:getAtlasDeck ( luaFilePath, flipX, flipY )
flipX = flipX and true or false
flipY = flipY and true or false
local key = luaFilePath .. "$" .. tostring ( flipX ) .. "$" .. tostring ( flipY )
local cache = self.atlasDecks
if not cache[ key ] then
cache[ key ] = self:createAtlasDeck ( luaFilePath, flipX, flipY )
end
return cache[ key ]
end
---
-- Create the Deck for displaying TextureAtlas.
---@param luaFilePath TexturePacker lua file path
---@param flipX (option)flipX
---@param flipY (option)flipY
---@return Texture atlas deck
function DeckMgr:createAtlasDeck ( luaFilePath, flipX, flipY )
local frames = Resources.dofile ( luaFilePath ).frames
local boundsDeck = MOAIBoundsDeck.new ()
boundsDeck:reserveBounds ( #frames )
boundsDeck:reserveIndices ( #frames )
local deck = MOAIGfxQuadDeck2D.new ()
deck:setBoundsDeck ( boundsDeck )
deck:reserve ( #frames )
deck.frames = frames
deck.names = {}
deck.flipX = flipX
deck.flipY = flipY
for i, frame in ipairs ( frames ) do
local uvRect = frame.uvRect
local uv = { uvRect.u0, uvRect.v1, uvRect.u1, uvRect.v1, uvRect.u1, uvRect.v0, uvRect.u0, uvRect.v0 }
local r = frame.spriteColorRect
local b = frame.spriteSourceSize
if frame.textureRotated then
uv = { uv[7], uv[8], uv[1], uv[2], uv[3], uv[4], uv[5], uv[6] }
end
if flipX then
uv = { uv[3], uv[4], uv[1], uv[2], uv[7], uv[8], uv[5], uv[6] }
end
if flipY then
uv = { uv[7], uv[8], uv[5], uv[6], uv[3], uv[4], uv[1], uv[2] }
end
deck:setUVQuad ( i, unpack ( uv ) )
deck.names[ frame.name ] = i
deck:setRect ( i, r.x, r.y, r.x + r.width, r.y + r.height )
boundsDeck:setBounds ( i, 0, 0, 0, b.width, b.height, 0 )
boundsDeck:setIndex ( i, i )
end
return deck
end
---
-- Returns the Deck to draw NineImage.
-- For caching, you must not change the Deck.
---@param fileName fileName
---@return MOAIStretchPatch2D instance
function DeckMgr:getNineImageDeck ( fileName )
local filePath = Resources.getResourceFilePath ( fileName )
local cache = self.nineImageDecks
if not cache[ filePath ] then
cache[ filePath ] = self:createNineImageDeck ( filePath )
end
return cache[ filePath ]
end
---
-- Create the Deck to draw NineImage.
---@param fileName fileName
---@return MOAIStretchPatch2D instance
function DeckMgr:createNineImageDeck ( fileName )
local filePath = Resources.getResourceFilePath ( fileName )
local image = MOAIImage.new ()
image:load ( filePath )
local imageWidth, imageHeight = image:getSize ()
local displayWidth, displayHeight = imageWidth - 2, imageHeight - 2
local stretchRows = self:_createStretchRowsOrColumns ( image, true )
local stretchColumns = self:_createStretchRowsOrColumns ( image, false )
local contentPadding = self:_getNineImageContentPadding ( image )
local texture = Resources.getTexture ( filePath )
local uvRect
if Config.VIEWPORT_YFLIP then
uvRect = { 1 / imageWidth, 1 / imageHeight, (imageWidth - 1) / imageWidth, (imageHeight - 1) / imageHeight }
else
uvRect = { 1 / imageWidth, (imageHeight - 1) / imageHeight, (imageWidth - 1) / imageWidth, 1 / imageHeight }
end
local deck = MOAIStretchPatch2D.new ()
deck.imageWidth = imageWidth
deck.imageHeight = imageHeight
deck.displayWidth = displayWidth
deck.displayHeight = displayHeight
deck.contentPadding = contentPadding
deck:reserveUVRects ( 1 )
deck:setTexture ( texture )
deck:setRect ( 0, 0, displayWidth, displayHeight )
deck:setUVRect ( 1, unpack ( uvRect ) )
deck:reserveRows ( #stretchRows )
deck:reserveColumns ( #stretchColumns )
for i, row in ipairs ( stretchRows ) do
deck:setRow ( i, row.weight, row.stretch )
end
for i, column in ipairs ( stretchColumns ) do
deck:setColumn ( i, column.weight, column.stretch )
end
return deck
end
function DeckMgr:_createStretchRowsOrColumns ( image, isRow )
local stretchs = {}
local imageWidth, imageHeight = image:getSize ()
local targetSize = isRow and imageHeight or imageWidth
local stretchSize = 0
local pr, pg, pb, pa = image:getRGBA ( 0, 1 )
for i = 1, targetSize - 2 do
local r, g, b, a = image:getRGBA ( isRow and 0 or i, isRow and i or 0 )
stretchSize = stretchSize + 1
if pa ~= a then
table.insert ( stretchs, {weight = stretchSize / (targetSize - 2), stretch = pa > 0} )
pa, stretchSize = a, 0
end
end
if stretchSize > 0 then
table.insert ( stretchs, {weight = stretchSize / (targetSize - 2), stretch = pa > 0} )
end
return stretchs
end
function DeckMgr:_getNineImageContentPadding ( image )
local imageWidth, imageHeight = image:getSize ()
local paddingLeft = 0
local paddingTop = 0
local paddingRight = 0
local paddingBottom = 0
for x = 0, imageWidth - 2 do
local r, g, b, a = image:getRGBA ( x + 1, imageHeight - 1 )
if a > 0 then
paddingLeft = x
break
end
end
for x = 0, imageWidth - 2 do
local r, g, b, a = image:getRGBA ( imageWidth - x - 2, imageHeight - 1 )
if a > 0 then
paddingRight = x
break
end
end
for y = 0, imageHeight - 2 do
local r, g, b, a = image:getRGBA ( imageWidth - 1, y + 1 )
if a > 0 then
paddingTop = y
break
end
end
for y = 0, imageHeight - 2 do
local r, g, b, a = image:getRGBA ( imageWidth - 1, imageHeight - y - 2 )
if a > 0 then
paddingBottom = y
break
end
end
return { paddingLeft, paddingTop, paddingRight, paddingBottom }
end
return DeckMgr |
-----------------------------------------------------------------------------------------
-- help.lua
-- (c) 2018, Velocity by Jericho Crosby <jericho.crosby227@gmail.com>
-----------------------------------------------------------------------------------------
local composer = require( "composer" )
local scene = composer.newScene()
local widget = require("widget")
local screenLeft = display.screenOriginX
local screenWidth = display.viewableContentWidth - screenLeft * 2
local screenRight = screenLeft + screenWidth
local screenTop = display.screenOriginY
local screenHeight = display.viewableContentHeight - screenTop * 2
local screenBottom = screenTop + screenHeight
local function switchScene(event, data)
local sceneID = event.target.id
composer.gotoScene( sceneID, {effect = "crossFade", time = 100} )
end
local function setUpDisplay(group)
-- Help Scene background
local background = display.newImageRect(group, "images/backgrounds/background4.png", display.contentWidth + 550, display.contentHeight + 1000)
background.alpha = 1
group:insert(background)
local x, y = -2, 0
local spacing = 65
local height = 300
local back_button = widget.newButton (
{
defaultFile = 'images/buttons/back_button.png',
overFile = 'images/buttons/back_button_pressed.png',
x = x * spacing + display.contentCenterX,
y = display.contentCenterX + y * spacing + height,
onRelease = function()
showUI(false)
composer.gotoScene( "scenes.menu", {effect = "crossFade", time = 100})
end
}
)
back_button:scale(0.080, 0.080)
group:insert(back_button)
local aboutText = [[
Summary:
* Create and view custom events in our in-app custom calander.
* Create and personalize notes and share them with each other.
* Notifications | Private Messaging | and more...
Developed by Jericho crosby
<jericho.crosby227@gmail.com>
Source Code: https://github.com/Chalwk77/Velocity
]]
local paragraphs = {}
local paragraph
local tmpString = aboutText
-- Text Options
local options = {
text = "",
width = display.contentWidth,
fontSize = 8,
font = native.systemFontBold,
align = "left",
}
local yOffset = 10
repeat
local b, e = string.find(tmpString, "\r\n")
if b then
paragraph = string.sub(tmpString, 1, b - 1)
tmpString = string.sub(tmpString, e + 1)
else
paragraph = tmpString
tmpString = ""
end
options.text = paragraph
paragraphs[#paragraphs + 1] = display.newText( options )
paragraphs[#paragraphs].anchorX = 0
paragraphs[#paragraphs].anchorY = 0
paragraphs[#paragraphs].x = 10
paragraphs[#paragraphs].y = yOffset
paragraphs[#paragraphs]:setFillColor(color_table.color("white"), 1)
paragraphs[#paragraphs].alpha = 1
info = paragraphs[#paragraphs]
yOffset = yOffset + paragraphs[#paragraphs].height
until tmpString == nil or string.len( tmpString ) == 0
group:insert(info)
local copyright = display.newText( group, "© 2018, Velocity, Jericho Crosby <jericho.crosby227@gmail.com>", 0, 0, native.systemFontBold, 8 )
local xPos = screenLeft + 10
local yPos = screenBottom - 10
copyright.x = xPos + 120
copyright.y = yPos
copyright:setFillColor( color_table.color("white"), 1)
copyright.alpha = 1
end
function scene:create( event )
local sceneGroup = self.view
setUpDisplay(sceneGroup)
end
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
if ( phase == "will" ) then
end
end
function scene:hide( event )
local sceneGroup = self.view
local phase = event.phase
if ( phase == "will" ) then
-- scene begin
elseif ( phase == "did" ) then
-- scene end
end
end
---------------------------------------------------------------
-- scene listener setup
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
return scene
|
custom = {
alpha = 0,
progress = 0
}
pickColor = {
r = 255,
g = 255,
b = 255
}
customLoops = {
{ img = "files/img/custom/car_color.png", title = "Cor Do Carro", subTitle = "Comprar nova cor do carro.", butText = "Comprar - $40000"},
{ img = "files/img/custom/car_lights.png", title = "Cor Do Farol", subTitle = "Comprar nova cor do farol.", butText = "Comprar - $30000"},
{ img = "files/img/custom/car_nitro.png", title = "Cor Do Nitro", subTitle = "Comprar nova cor do nitro.", butText = "Comprar - $35000"},
{ img = "files/img/custom/police.png", title = "Luzes da Policia", subTitle = "Comprar luzes da policia.", butText = "Comprar - $350000", text1 = "Ligar luzes da policia.", text2 = "Desligar luzes da policia.", state = false},
--{ img = "files/img/custom/soon.png", title = "Donator", subTitle = "Buy for 1 day donate", butText = "Buy - $15000"},
{ img = "files/img/custom/rocket.png", title = "Cor do Tiro", subTitle = "Comprar cor do tiro.", butText = "Comprar - $100000"}
}
function customInterface()
custom.progress = custom.progress+0.005
if label.custom == true then
custom.alpha = interpolateBetween(custom.alpha,0,0,1,0,0,custom.progress,"Linear")
if custom.alpha == 1 then
custom.progress = 0
end
end
if label.custom == false then
custom.alpha = interpolateBetween(custom.alpha,0,0,0,0,0,custom.progress,"Linear")
if custom.alpha == 0 then
custom.progress = 0
removeEventHandler("onClientRender",root,customInterface)
end
end
dxDrawImage(_sX,_sY,resY(30),resY(30),"files/img/custom.png",0,0,0,tocolor(232,232,232,255*custom.alpha))
dxText("Custom",_sX+resY(30),_sY+resY(2),sX,sY,230,230,230,255*custom.alpha,1.0,dxFont(15),"left","top",true,false,false,false)
createButton(_sX+resX(34),_sY+resY(31),resX(664),resY(30),"Selecione a cor aqui antes de comprar!",pickColor.r,pickColor.g,pickColor.b,custom.alpha,dxFont(15))
for i,info in ipairs(customLoops) do
local posY = _sY+resY(62)+(i*resY(50))-resY(50)
if not isMousePosition(_sX+resX(34),posY,resX(698),resY(49)) then
dxDrawRectangle(_sX+resX(34),posY,resX(664),resY(49),tocolor(menu.r,menu.g,menu.b,30*custom.alpha))
end
dxDrawImage(_sX+resX(35),posY+resY(1),resY(47),resY(47),info.img,0,0,0,tocolor(255,255,255,255*custom.alpha))
dxText(info.title,_sX+resY(85),posY-resY(2),sX,sY,255,255,255,255*custom.alpha,1.0,dxFont(18),"left","top",true,false,false,false)
if i ~= 4 then
dxText(info.subTitle,_sX+resY(85),posY+resY(22),sX,sY,255,255,255,255*custom.alpha,1.0,dxFont(15),"left","top",true,false,false,false)
createButton(_sX+resX(547),posY+resY(12),resX(150),resY(26),info.butText,0,236,0,custom.alpha,dxFont(14))
else
if getElementData(localPlayer,"policeHeadLight") == "false" then
dxText(info.subTitle,_sX+resY(85),posY+resY(22),sX,sY,255,255,255,255*custom.alpha,1.0,dxFont(15),"left","top",true,false,false,false)
createButton(_sX+resX(547),posY+resY(12),resX(150),resY(26),info.butText,0,236,0,custom.alpha,dxFont(14))
else
if not info.state then
dxText(info.text1,_sX+resY(85),posY+resY(22),sX,sY,255,255,255,255*custom.alpha,1.0,dxFont(15),"left","top",true,false,false,false)
createButton(_sX+resX(547),posY+resY(12),resX(150),resY(26),"Ativar",0,236,0,custom.alpha,dxFont(14))
else
dxText(info.text2,_sX+resY(85),posY+resY(22),sX,sY,255,255,255,255*custom.alpha,1.0,dxFont(15),"left","top",true,false,false,false)
createButton(_sX+resX(547),posY+resY(12),resX(150),resY(26),"Desativar",255,0,0,custom.alpha,dxFont(14))
end
end
end
end
end
function buttonCustomInterface(button,state)
if ( button == "left" and state == "down" ) then
return false
end
if isMousePosition(_sX+resX(34),_sY+resY(31),resX(664),resY(30)) then
colorPicker.create("1","#FFFFFF","Selecionar Cor")
end
for i,info in ipairs(customLoops) do
local posY = _sY+resY(61)+(i*resY(50))-resY(50)
if isMousePosition(_sX+resX(547),posY+resY(12),resX(150),resY(26)) then
if i == 1 then
callServerFunction("buyCarColor",localPlayer,1,pickColor.r,pickColor.g,pickColor.b)
end
if i == 2 then
callServerFunction("buyCarColor",localPlayer,2,pickColor.r,pickColor.g,pickColor.b)
end
if i == 3 then
callServerFunction("buyCarColor",localPlayer,3,pickColor.r,pickColor.g,pickColor.b)
end
if i == 4 then
if getElementData(localPlayer,"policeHeadLight") == "false" then
callServerFunction("buyPoliceHeadlight",localPlayer)
end
if getElementData(localPlayer,"policeHeadLight") == "true" then
if not customLoops[i].state then
setElementData(localPlayer,"HeadLightState","1")
customLoops[i].state = true
else
setElementData(localPlayer,"HeadLightState","false")
customLoops[i].state = false
end
end
end
if i == 5 then
--callServerFunction("buyDonatorDay",localPlayer,"1")
--end
--if i == 6 then
callServerFunction("buyCarColor",localPlayer,4,pickColor.r,pickColor.g,pickColor.b)
end
end
end
end |
return {
version = "1.1",
luaversion = "5.1",
tiledversion = "1.1.5",
orientation = "orthogonal",
renderorder = "right-down",
width = 100,
height = 100,
tilewidth = 32,
tileheight = 32,
nextobjectid = 14,
properties = {},
tilesets = {
{
name = "Tileset",
firstgid = 1,
filename = "../../../../../Desktop/Tileset.tsx",
tilewidth = 32,
tileheight = 32,
spacing = 0,
margin = 0,
image = "../images/atlas.jpg",
imagewidth = 128,
imageheight = 32,
tileoffset = {
x = 0,
y = 0
},
grid = {
orientation = "orthogonal",
width = 32,
height = 32
},
properties = {},
terrains = {},
tilecount = 4,
tiles = {}
}
},
layers = {
{
type = "tilelayer",
name = "Ground Layer",
x = 0,
y = 0,
width = 100,
height = 100,
visible = true,
opacity = 1,
offsetx = 0,
offsety = 0,
properties = {},
encoding = "lua",
data = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
}
},
{
type = "objectgroup",
name = "Entity Layer",
visible = true,
opacity = 1,
offsetx = 0,
offsety = 0,
draworder = "topdown",
properties = {},
objects = {
{
id = 11,
name = "torch",
type = "spawn",
shape = "rectangle",
x = 1536,
y = 1536,
width = 32,
height = 32,
rotation = 0,
visible = true,
properties = {
["type"] = 0
}
},
{
id = 12,
name = "torch",
type = "torch",
shape = "rectangle",
x = 1504,
y = 1504,
width = 32,
height = 32,
rotation = 0,
visible = true,
properties = {
["type"] = 0
}
}
}
}
}
}
|
local module = {}
table = require(script.Parent.Table)
local switch = {}
setmetatable(switch, {
__call = function(self, item)
if not item then
warn("Switch statement needs a value to be compared")
else
return function(data)
for i, v in pairs(data) do
if item == module.convertFromString(i) then
if type(v) == "function" then
return v()
else
return v
end
end
end
if data.default then
return data.default
end
warn("No default value given, switch case will return nil")
return nil
end
end
end
})
function module.convertFromString(val)
if val == "true" then
return true
end
if val == "false" then
return false
end
if val == "nil" or val == "null" then
return nil
end
local num = tonumber(val)
if num ~= nil and tostring(num) == val then
return num
end
return val
end
function module.CreateVal(valType, parent, name, value)
local inst, success, err
if value then
success, err = pcall(function()
inst = Instance.new(valType)
inst.Parent = parent
inst.Name = name
inst.Value = value
end)
else
local temp = name
name = parent
value = temp
success, err = pcall(function()
inst = Instance.new(valType)
inst.Name = name
inst.Value = value
end)
end
if success then
return inst
else
warn(err)
end
end
function module.ClearChildren(inst, exempt)
if exempt == nil then
inst:ClearAllChildren()
end
for i, v in pairs(inst:GetChildren()) do
if not table.find(exempt, v.Name) then
v:Destroy()
end
end
end
function module.debounce(func)
local isRunning = false
return function(...)
if not isRunning then
isRunning = true
func(...)
isRunning = false
end
end
end
function module.getPlayersByTeam(...)
local players = {}
local teams = {...}
for i, v in pairs(teams) do
if type(v) == "table" then
for index, team in pairs(v) do
print(team)
for _, plr in pairs(team:GetPlayers()) do
table.insert(players, plr)
end
end
else
for _, plr in pairs(v:GetPlayers()) do
table.insert(players, plr)
end
end
end
return players
end
function module.LoadLibrary(libName)
for i, v in pairs(script:GetChildren()) do
if v.Name == libName and v:IsA("ModuleScript") then
return require(v)
end
end
end
module.switch = switch
return module
|
local utils = {}
function utils.get_document_title(splash)
return splash:evaljs("document.title")
end
local secret = require("secret")
utils.hello = secret.hello
return utils
|
-- This is a VT100 terminal output writer for Pandoc.
-- Inwoke with: pandoc -t terminal.lua
-- Copyright (c) 2018 Orange
-- Homepage: https://github.com/Orange-OpenSource/pandoc-terminal-writer
-- This module is released under the MIT License (MIT).
-- Please see LICENCE.txt for details.
-- Author: Camille Oudot
-- Table to store footnotes, so they can be appended at the end of the output.
local notes = {}
-- Pipes an inp(ut) to a cmd
local function pipe(cmd, inp)
local tmp = os.tmpname()
local tmph = io.open(tmp, "w")
tmph:write(inp)
tmph:close()
local outh = io.popen(cmd .. " " .. tmp .. " 2>/dev/null","r")
local result = outh:read("*all")
outh:close()
os.remove(tmp)
return result
end
-- Tells if a given command is available on the system
local function command_exists(cmd)
local h = io.popen("which " .. cmd)
local result = h:read("*all")
h:close()
return not (result == "")
end
-- Look for a syntax highlighter command on the current system
if command_exists("pygmentize") then
highlight = function(s, fmt)
local hl = pipe("pygmentize -l " .. fmt .. " -f console", s)
return hl == "" and s or hl
end
elseif command_exists("highlight") then
highlight = function(s, fmt)
local hl = pipe("highlight -O ansi -S " .. fmt, s)
return hl == "" and s or hl
end
else
highlight = function(s, fmt)
return s
end
end
-- Prints a table recursively
function tprint (tbl, indent)
if not indent then indent = 0 end
for k, v in pairs(tbl) do
formatting = string.rep(" ", indent) .. k .. ": "
if type(v) == "table" then
print(formatting)
tprint(v, indent+1)
else
print(formatting .. v)
end
end
end
--------- Helpers for wrapping long formatted text lines ----------------------
-- Returns the first letter and the remaining characters of the input string.
-- If the string begins with "Set Display Attribute" escape sequences, they are
-- kept alongside the first letter in the first returned value.
--
-- example: get_1st_letter("ABCD")
-- returns: "A", "BCD"
-- get_1st_letter("\27[1mA\27[0mBCD")
-- returns: "27[1mA\27[0m", "BCD"
function get_1st_letter(s)
local function get_1st_letter_rec(s, acc)
if #s == 0 then
return "", ""
elseif #s == 1 then
return s, ""
else
local m = s:match("^\27%[[0-9;]+m")
if m == nil then
local m = s:match("^[^\27]\27%[[0-9;]+m")
if m == nil then
return acc .. s:sub(1,1), s:sub(2)
else
return acc .. m, s:sub(#m + 1)
end
else
return get_1st_letter_rec(s:sub(#m + 1), acc .. m)
end
end
end
return get_1st_letter_rec(s, "")
end
-- Inserts line breaks in 's' every 'w' _actual_ characters, meaning that the
-- escape sequences do not count as a character.
function fold(s, w)
local col = 0
local buf = ""
local h
while #s > 0 do
h, s = get_1st_letter(s)
if col == w then
buf = buf .. "\n"
col = 0
end
buf = buf .. h
col = col + 1
end
return buf
end
-- Returns a substring of 's', starting after 'orig' and of length 'nb'
-- Escape sequences are NOT counted as characters and thus are not cut.
function subString(s, orig, nb)
local col = 0
local buf = ""
local h
while #s > 0 and col < orig do
h, s = get_1st_letter(s)
col = col + 1
end
col = 0
while #s > 0 and col < nb do
h, s = get_1st_letter(s)
buf = buf .. h
col = col + 1
end
return buf
end
-- Merges all consecutive "Set Display Attribute" escape sequences in the input
-- 's' string, and merges them into single ones in the returned string.
--
-- example: simplify_vt100("foo \27[1m\27[2;3m\27[4m bar")
-- returns: "foo \27[1;2;3;4m bar"
function simplify_vt100(s)
local _
while s:match("(\27%[[0-9;]+)m\27%[") do
s, _ = s:gsub("(\27%[[0-9;]+)m\27%[", "%1;")
end
return s
end
-------------------------------------------------------------------------------
-- Blocksep is used to separate block elements.
function Blocksep()
return "\n\n"
end
-- This function is called once for the whole document. Parameters:
-- body is a string, metadata is a table, variables is a table.
-- This gives you a fragment. You could use the metadata table to
-- fill variables in a custom LUA template. Or, pass `--template=...`
-- to pandoc, and pandoc will add do the template processing as
-- usual.
function Doc(body, metadata, variables)
local buffer = {}
local function add(s)
table.insert(buffer, s)
end
add(body)
if #notes > 0 then
add('<ol class="footnotes">')
for _,note in pairs(notes) do
add(note)
end
add('</ol>')
end
return table.concat(buffer,'\n') .. '\n'
end
-- Sets Display Attribute using a VT100 escape sequence
function vt100_sda(s, style)
return string.format(
"\27[%sm%s\27[0m",
style,
string.gsub(
s,
"\27%[0m",
"\27[0m\27[" .. style .. "m"))
end
function Str(s)
return s
end
function Space()
return " "
end
function SoftBreak()
return " "
end
function LineBreak()
return "\n"
end
function Emph(s)
return vt100_sda(s, "3")
end
function Strong(s)
return vt100_sda(s, "1")
end
function Subscript(s)
return "_{" .. s .. "}"
end
function Superscript(s)
return "^{" .. s .. "}"
end
function SmallCaps(s)
return s:upper()
end
function Strikeout(s)
return vt100_sda(s, "9")
end
function Link(s, src, tit, attr)
if s == src then
return vt100_sda(s, "4")
else
return vt100_sda(s, "4") .. " (" .. vt100_sda(src, "2") .. ")"
end
end
function Image(s, src, tit, attr)
return vt100_sda("[Image (" .. tit .. ")](" .. src .. ")", "1")
end
function Code(s, attr)
return vt100_sda(s, "32")
end
function InlineMath(s)
return s
end
function DisplayMath(s)
return s
end
function Note(s)
return s
end
function Span(s, attr)
return s
end
function RawInline(format, str)
return str
end
function Cite(s, cs)
return s
end
function Plain(s)
return s
end
function Para(s)
return s
end
-- lev is an integer, the header level.
function Header(lev, s, attr)
return vt100_sda(string.rep("██", lev - 1) .. "▓▒░ " .. s, "1;33")
end
function BlockQuote(s)
local ret = " ▛\n"
for l in s:gmatch("[^\r\n]+") do
ret = ret .. " ▌ " .. l .. "\n"
end
return ret .. " ▙"
end
function HorizontalRule()
return " _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n"
end
function CodeBlock(s, attr)
local lines = {}
local ret
ret = vt100_sda(" ╭───┬────────┄", "2") .. "\n"
if attr["class"] ~= "" then
s = highlight(s, attr["class"])
end
for l in s:gmatch("([^\n]*)\n?") do
lines[#lines + 1] = l
end
if lines[#lines] == "" then
lines[#lines] = nil
end
for n, l in pairs(lines) do
ret = ret .. vt100_sda(" │" .. string.format("%3d",n) .. "│ ", "2") .. l .. "\n"
end
return ret .. vt100_sda(" ╰───┴───────────┄", "2")
end
depth = 0
function indent(s, fl, ol)
local ret = {}
local i = 1
for l in s:gmatch("[^\r\n]+") do
if i == 1 then
ret[i] = fl .. l
else
ret[i] = ol .. l
end
i = i + 1
end
return table.concat(ret, "\n")
end
function BulletList(items)
local ret = {}
for _, item in pairs(items) do
ret[_] = indent(item, " " .. vt100_sda("•", "2") .. " ", " ")
end
return table.concat(ret, "\n")
end
function OrderedList(items)
local ret = {}
for _, item in pairs(items) do
ret[_] = indent(item, vt100_sda(string.format("%2d.", _), "2") .. " ", " ")
end
return table.concat(ret, "\n")
end
-- Revisit association list STackValue instance.
function DefinitionList(items)
return ""
end
function CaptionedImage(src, tit, caption, attr)
return BlockQuote(vt100_sda("[Image (" .. tit .. ")](" .. src .. ")", "1") .. "\n" .. caption)
end
-- Gets the 'text only' version of a text to display (as they may have been
-- modified with escape sequences before)
local function _getText(txt)
return string.gsub(txt, "\27%[[;%d]+m", "")
end
-- Count viewable chars in UTF-8 strings
-- See http://lua-users.org/wiki/LuaUnicode
function _utf8Len(ustring)
local ulen = 0
for uchar in string.gmatch(ustring, "([%z\1-\127\194-\244][\128-\191]*)") do
ulen = ulen + 1
end
return ulen
end
-- Position text in a wider string (stuffed with blanks)
-- 'way' is '0' to left justify, '1' for right and '2' for center
function _position(txt, width, way)
if way < 0 or way > 2 then
return txt
end
local l = _utf8Len(_getText(txt))
if width > l then
local b = (way == 0 and 0) or math.floor((width - l) / way)
local a = width - l - b
return string.rep(' ', b) .. txt .. string.rep(' ', a)
else
return txt
end
end
MAX_COL_WIDTH = 42
-- Caption is a string, aligns is an array of strings,
-- widths is an array of floats, headers is an array of
-- strings, rows is an array of arrays of strings.
function Table(caption, aligns, widths, headers, rows)
local buffer = {}
local align = {["AlignDefault"] = 0, ["AlignLeft"] = 0, ["AlignRight"] = 1, ["AlignCenter"] = 2}
local function add(s)
table.insert(buffer, s)
end
-- Find maximum width for each column:
local col_width = {}
local row_height = {}
for j, row in pairs(rows) do
row_height[j] = 1
end
local cell_width = 0
local cell_height = 0
for i, header in pairs(headers) do
table.insert(col_width, i, _utf8Len(_getText(header)))
for j, row in pairs(rows) do
cell_width = _utf8Len(_getText(row[i]))
if cell_width > col_width[i] then
col_width[i] = cell_width < MAX_COL_WIDTH and cell_width or MAX_COL_WIDTH
end
cell_height = math.floor(cell_width / MAX_COL_WIDTH) + 1
if cell_height > row_height[j] then
row_height[j] = cell_height
end
end
end
local top_border = '┌'
local row_border = '├'
local bottom_border = '└'
local last = #col_width
local tmpl = ''
for i, w in pairs(col_width) do
tmpl = tmpl .. string.rep('─', w) .. (i < last and 'm' or '')
end
top_border = top_border .. string.gsub(tmpl, 'm', '┬') .. '┐'
row_border = row_border .. string.gsub(tmpl, 'm', '┼') .. '┤'
bottom_border = bottom_border .. string.gsub(tmpl, 'm', '┴') .. '┘'
if caption ~= "" then
add(Strong(caption))
end
local header_row = {}
local empty_header = true
for i, h in pairs(headers) do
table.insert(header_row, Strong(_position(h, col_width[i], 2)))
empty_header = empty_header and h == ""
end
add(top_border)
if empty_header then
head = ""
else
local content = ''
for _, h in pairs(header_row) do
content = content .. '│' .. h
end
add(content .. '│')
add(row_border)
end
for i, row in pairs(rows) do
local content = ''
for k = 1, row_height[i] do -- Break long lines
content = ''
for j, c in pairs(row) do
local s = ''
if (col_width[j]) then
s = subString(c, (k - 1) * MAX_COL_WIDTH, MAX_COL_WIDTH)
content = content .. '│' .. _position(s, col_width[j], align[aligns[j]])
end
end
add(content .. '│')
end
if i < #rows then
add(row_border)
end
end
add(bottom_border)
return table.concat(buffer,'\n')
end
function RawBlock(format, str)
return str
end
function Div(s, attr)
return s
end
-- The following code will produce runtime warnings when you haven't defined
-- all of the functions you need for the custom writer, so it's useful
-- to include when you're working on a writer.
local meta = {}
meta.__index =
function(_, key)
io.stderr:write(string.format("WARNING: Undefined function '%s'\n",key))
return function() return "" end
end
setmetatable(_G, meta)
|
discordlib.optiontype =
{
SUB_COMMAND = 1,
SUB_COMMAND_GROUP = 2,
STRING = 3,
INTEGER = 4,
BOOLEAN = 5,
USER = 6,
CHANNEL = 7,
ROLE = 8,
MENTIONABLE = 9,
NUMBER = 10,
}
function discordlib.slashcmd()
local slashcmd = {
description = "",
options = {}
}
local hasSubcommand = false
local hasOptions = false
function slashcmd.setName(name = !err)
slashcmd.name = name
return slashcmd
end
function slashcmd.setDescription(description = !err)
slashcmd.description = description
return slashcmd
end
function slashcmd.addOption(option = !err)
if hasSubcommand then error("You can't use the ${__FUNCTION__} if you already have a subcommand") end
slashcmd.options[#slashcmd.options + 1] = option
hasOptions = true
return slashcmd
end
function slashcmd.addSubCommand(command = !err)
if hasOptions then error("You can't use the ${__FUNCTION__} if you already have a options") end
command.type = discordlib.optiontype.SUB_COMMAND
slashcmd.options[#slashcmd.options + 1] = command
hasSubcommand = true
return slashcmd
end
function slashcmd.addSubGroup(subgroup = !err)
slashcmd.options[#slashcmd.options + 1] = subgroup
return slashcmd
end
return slashcmd
end
function discordlib.subcommand()
local subcommand = discordlib.slashcmd()
subcommand.type = discordlib.optiontype.SUB_COMMAND
subcommand.addSubCommand = nil
subcommand.addSubGroup = nil
return subcommand
end
function discordlib.subgroup()
local subgroup = discordlib.slashcmd()
subgroup.type = discordlib.optiontype.SUB_COMMAND_GROUP
subgroup.addSubGroup = nil
subgroup.addOption = nil
subgroup.addCommand = subgroup.addSubCommand
subgroup.addSubCommand = nil
return subgroup
end
function discordlib.option()
local option = {
description = "",
type = discordlib.optiontype.STRING
}
function option.setType(type = !err)
option.type = type
return option
end
function option.setName(name = !err)
option.name = name
return option
end
function option.setDescription(description = !err)
option.description = description
return option
end
function option.setRequired(required = !err)
option.required = required
return option
end
function option.addChoice(name = !err, value = !err)
option.choices = option.choices or {}
option.choices[#option.choices + 1] = {
name = name,
value = value
}
return option
end
return option
end |
--[[
MailSlurp API
MailSlurp is an API for sending and receiving emails from dynamically allocated email addresses. It's designed for developers and QA teams to test applications, process inbound emails, send templated notifications, attachments, and more. ## Resources - [Homepage](https://www.mailslurp.com) - Get an [API KEY](https://app.mailslurp.com/sign-up/) - Generated [SDK Clients](https://www.mailslurp.com/docs/) - [Examples](https://github.com/mailslurp/examples) repository
The version of the OpenAPI document: 6.5.2
Contact: contact@mailslurp.dev
Generated by: https://openapi-generator.tech
]]
-- upload_attachment_options class
local upload_attachment_options = {}
local upload_attachment_options_mt = {
__name = "upload_attachment_options";
__index = upload_attachment_options;
}
local function cast_upload_attachment_options(t)
return setmetatable(t, upload_attachment_options_mt)
end
local function new_upload_attachment_options(content_type, filename, base64_contents)
return cast_upload_attachment_options({
["contentType"] = content_type;
["filename"] = filename;
["base64Contents"] = base64_contents;
})
end
return {
cast = cast_upload_attachment_options;
new = new_upload_attachment_options;
}
|
local playsession = {
{"rocifier", {296017}},
{"z903857322", {7977}},
{"Fingerdash", {1793}},
{"Tranic", {9727}},
{"Menander", {2206378}},
{"TiTaN", {1985830}},
{"Nikkichu", {1043679}},
{"Avelix", {368499}},
{"t_Mind", {70149}},
{"everLord", {1583728}},
{"facere", {817235}},
{"Piewdennis", {63894}},
{"davidbutora", {10261}},
{"Olekplane1", {1153022}},
{"askyyer", {1170}},
{"exabyte", {743736}},
{"EPO666", {359681}},
{"Lestibornes", {179230}},
{"Impatient", {2956}},
{"brotzkocken", {194724}},
{"Tomy52499", {291078}},
{"junhinhow", {169379}},
{"marklinCZ", {202654}},
{"cogito123", {237577}},
{"craigrood", {2208}},
{"DevilR", {231551}},
{"Lulaidon", {1172256}},
{"vvictor", {1231515}},
{"Upsidedowneye", {2921}},
{"texanbred", {3810}},
{"minipini55", {218590}},
{"realDonaldTrump", {4373}},
{"FallenAngel1010", {4193}},
{"foggyliziouz", {456646}},
{"Keregan2311", {3265}},
{"stargazer5683", {709}},
{"CmonMate497", {6448}},
{"kaimix", {605948}},
{"AroN57", {303224}},
{"mad58max", {4348}},
{"grombles", {17215}},
{"MuddledBox", {3568}},
{"Tracolix", {82640}},
{"RedPandaRam", {6798}},
{"Velguarder", {12516}}
}
return playsession |
--[[
TheNexusAvenger
Implementation of a command.
--]]
local BaseCommand = require(script.Parent.Parent:WaitForChild("BaseCommand"))
local Command = BaseCommand:Extend()
--[[
Creates the command.
--]]
function Command:__new()
self:InitializeSuper("crash","BasicCommands","Crashes a set of players. Admins can not be crashed.")
self.Arguments = {
{
Type = "nexusAdminPlayers",
Name = "Players",
Description = "Players to crash.",
},
}
--Create the remote event.
local CrashPlayerEvent = Instance.new("RemoteEvent")
CrashPlayerEvent.Name = "CrashPlayer"
CrashPlayerEvent.Parent = self.API.EventContainer
self.CrashPlayerEvent = CrashPlayerEvent
end
--[[
Runs the command.
--]]
function Command:Run(CommandContext,Players)
self.super:Run(CommandContext)
--Crash the players.
for _,Player in pairs(Players) do
if self.API.Authorization:GetAdminLevel(Player) >= 0 then
self:SendError("You can't crash admins.")
else
self.CrashPlayerEvent:FireClient(Player)
end
end
end
return Command |
bt = {}
bt.reset = {}
bt.reset["repeat"]= function(...)
end
local bt_fns = {
reset={},
tick={},
}
-- nodes never call :reset() on themselves
-- distance on x-z plane
function distance(a, b)
local x = a.x - b.x
local z = a.z - b.z
return math.abs(math.sqrt(x*x + z*z))
end
-- 3d distance
function distance3(a, b)
local x = a.x - b.x
local y = a.y - b.y
local z = a.z - b.z
return math.abs(math.sqrt(x*x + z*z + y*y))
end
function tprint (tbl, indent)
local formatting = ""
if not indent then indent = 0 end
if tbl == nil then
print(formatting .. "nil")
return
end
for k, v in pairs(tbl) do
formatting = string.rep(" ", indent) .. k .. ": "
if type(v) == "table" then
print(formatting)
tprint(v, indent+1)
elseif type(v) == 'boolean' then
print(formatting .. tostring(v))
elseif type(v) == 'function' then
print(formatting .. "[function]")
elseif type(v) == 'userdata' then
print(formatting .. "[userdata]")
else
print(formatting .. v)
end
end
end
bt.register_action = function(name, def)
if type(def.reset) ~= "function" then
bt_fns.reset[name] = function(node, data) end
else
bt_fns.reset[name] = def.reset
end
if type(def.tick) ~= "function" then
bt_fns.tick[name] = function(node, data) return "success" end
else
bt_fns.tick[name] = def.tick
end
bt[name] = function(...)
local x = {}
if type(def.ctor) == "function" then
x = def.ctor(...)
end
x.kind = name
if x.name == nil then
x.name = name
end
return x
end
end
bt.reset = function(node, data)
return bt_fns.reset[node.kind](node, data)
end
bt.tick = function(node, data)
--return
return bt_fns.tick[node.kind](node, data)
end
local path = minetest.get_modpath("mobehavior")
dofile(path..'/behaviors/core.lua')
dofile(path..'/behaviors/predicates.lua')
dofile(path..'/behaviors/search.lua')
dofile(path..'/behaviors/movement.lua')
dofile(path..'/behaviors/actions.lua')
dofile(path..'/behaviors/waypoints.lua')
dofile(path..'/behaviors/regions.lua')
dofile(path..'/behaviors/area_stats.lua')
--[[
ideas:
RobChest(items, max) // robs nearby chests of given items
ThrowAt(projectile, target)
FleeFrom(pos, distance)
FleeFromNodes(nodes, distance) -- gets distance away from any nodes
FleeFromPlayer(entity, distance)
Stomp(pos) -- plays stomping animation and eventually destroys node
Attack(entity) -- seek and kill entity
FindNearbyEntity(entity_type)
HealthBelow(n)
HealthAbove(n)
^ for heat, humidity, light, hunger, breath
TossNearbyEntity() -- tosses a nearby entity
SetTimer/IsExpired/HasPassed(name, [number])
ChestHasItems(items)
stack nodes to make stairs when pathfinding is broken
travel up ladders and through doors
buildToHeight
put state/animation/model in the node, check and update in bt.tick/reset
findFlatArea
climbLadder
isChest full/empty
findnonfullchest
*findAvailableChest
craftItem
is target further/closer than x
search for vertical stacks of x height
try to stack nodes to x height
forceload block
biomes
node level
line of sight
eat
drop/collect nearby items
rotate node
set time of day
jump/crouch
change top-level tree
try approach should fail if the node is directly above
build ladder to
drop items from inv
get surface node near
get node(a) x distance away from any other node(b)
get random node in area
is the entity inv full
add/remove node to visited list
try approach, with a bt kid that's called when progress slows
]]
|
include("shared.lua")
ENT.RenderGroup = RENDERGROUP_BOTH
function ENT:Draw()
self:DrawModel()
if self:GetPos():Distance(LocalPlayer():GetPos()) < 600 then
local pos = self:GetPos() + Vector(0, 0, 1) * math.sin(CurTime() * 2) * 2
local PlayersAngle = LocalPlayer():GetAngles()
local ang = Angle( 0, PlayersAngle.y - 180, 0 )
ang:RotateAroundAxis(ang:Right(), -90)
ang:RotateAroundAxis(ang:Up(), 90)
cam.Start3D2D(pos, ang, 0.21)
draw.SimpleTextOutlined( NPCPW.TextAboveHead, "HUDNumber5", 0, -400,NPCPW.TextAboveHeadColor, TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP, 1, NPCPW.TextAboveHeadColorOutline)
cam.End3D2D()
end
end
function ENT:DrawTranslucent()
self:Draw()
end
|
cfg = {}
-- Configure blip colors at cfg/display.lua
cfg.teams = { -- Only one team for each group, you can set multiple teams, groups on same team will see each other's blips
["Politi"] = { -- Team name must be unique
-- groups
"Politi-Job",
"EMS-Job"
},
}
return cfg |
-- Setup work thread
-- ==========================================================
function OnMsg.GameTimeStart()
AutoScanMapInstallThread()
end
function OnMsg.LoadGame()
AutoScanMapInstallThread()
end
local AutoScanMapModActive = true
function AutoScanMapInstallThread()
-- make sure the handler thread is installed at most once
if UICity and not IsValidThread(UICity.AutoScanMapThread_GameTime) then
UICity.AutoScanMapThread_GameTime = CreateGameTimeThread(function()
while AutoScanMapModActive do
Sleep(5000)
AutoScanMap()
end
end)
end
end
-- Automation logic
-- ==========================================================
function AutoScanMap()
-- scan mode
local mode = AutoScanMapConfigMode()
if mode == "off" then
return
end
-- game is not yet initialized
if not UICity then
return
end
-- check the global queue for ongoing exploration
if UICity.ExplorationQueue and #UICity.ExplorationQueue == 0 then
local scanCandidates = { }
-- g_MapSectors is a column [1..10] and row [1..10] matrix of sector information
-- 1, 1 is J0; 1, 10 is J9
for x = 1, const.SectorCount do
for y = 1, const.SectorCount do
local sector = UICity.MapSectors[x][y];
if sector:CanBeScanned() then
-- full scanning is enabled
if mode == "all"
-- do scanning only if deep scanning is not available
or (mode == "normal" and g_Consts.DeepScanAvailable == 0)
-- do scanning only if deep scanning becomes available
or (mode == "deep" and g_Consts.DeepScanAvailable ~= 0) then
scanCandidates[#scanCandidates + 1] = sector
end
end
end
end
-- if there are sectors to scan
if #scanCandidates ~= 0 then
-- find the closest one to existing units and buildings
local closest = nil
local closestDistance = nil
ForEach { classes = "Building,Unit", exec = function(obj)
local pos = obj:GetPos()
-- find closest candidate
for k, sector in ipairs(scanCandidates) do
local sectorPos = sector:GetPos()
-- Eucleidian distance
local dist = (sectorPos:x() - pos:x())^2 + (sectorPos:y() - pos:y())^2
-- if this is the first sector or it is closer than something else before
if not closest or closestDistance > dist then
closest = sector
closestDistance = dist
end
end
end }
-- queue it up for exploration
if not closest then
-- pick a random sector from the candidates
closest = scanCandidates[ AsyncRand (#scanCandidates)]
end
closest:QueueForExploration()
-- prevent the scan animation from being deployed on the main map view
if GetInGameInterfaceMode() ~= "overview" then
closest:SetScanFx(false)
end
OverviewModeDialog:UpdateSectorRollover(closest)
end
end
end
-- ModConfig setup
-- ==========================================================
-- Check if any of the ModConfig mods are installed
function ModConfigAvailable()
-- ModConfig old
local found = table.find_value(ModsLoaded, "steam_id", "1340775972") or
-- ModConfig reborn
table.find_value(ModsLoaded, "steam_id", "1542863522") or false
return found
end
-- See if ModConfig is installed and that notifications are enabled
function AutoScanMapConfigMode()
local g_ModConfigLoaded = ModConfigAvailable()
if g_ModConfigLoaded and ModConfig:IsReady() then
return ModConfig:Get("AutoScanMap", "Mode")
end
return "all"
end
-- ModConfig signals "ModConfigReady" when it can be manipulated
function OnMsg.ModConfigReady()
ModConfig:RegisterMod("AutoScanMap",
T{"AutoScanMap"},
T{"Automatically scan and rescan sectors"}
)
ModConfig:RegisterOption("AutoScanMap", "Mode", {
name = T{"Scan mode"},
desc = T{"Specify how to scan the sectors automatically or turn it off completely.<newline>Normal only performs scanning while only basic scanning is available.<newline>Deep only performs scanning only if the research has been acquired."},
type = "enum",
values = {
{value = "all", label = T{"Normal & Deep"}},
{value = "normal", label = T{"Normal only"}},
{value = "deep", label = T{"Deep only"}},
{value = "off", label = T{"Off"}}
},
default = "all"
})
end |
local F = "__subway__";
require("circuit-connector-sprites")
local power_batch_size = settings.startup["subway-power-batching"].value or 1
local function cwc0c()
return {shadow = {red = {0,0},green = {0,0},copper = {0,0}}, wire = {red = {0,0},green = {0,0},copper = {0,0}}}
end
local function blank()
return {
filename = F.."/graphics/nothing.png",
priority = "high",
width = 1,
height = 1,
}
end
local function ablank()
return {
filename = F.."/graphics/nothing.png",
priority = "high",
width = 1,
height = 1,
frame_count = 1,
}
end
local function ps()
return {
filename = F.."/graphics/component/pipe-connection-south.png",
priority = "extra-high",
width = 44,
height = 32
}
end
local function blankpipepictures()
return {
straight_vertical_single = blank(),
straight_vertical = blank(),
straight_vertical_window = blank(),
straight_horizontal_window = blank(),
straight_horizontal = blank(),
corner_up_right = blank(),
corner_up_left = blank(),
corner_down_right = blank(),
corner_down_left = blank(),
t_up = blank(),
t_down = blank(),
t_right = blank(),
t_left = blank(),
cross = blank(),
ending_up = blank(),
ending_down = blank(),
ending_right = blank(),
ending_left = blank(),
horizontal_window_background = blank(),
vertical_window_background = blank(),
fluid_background = blank(),
low_temperature_flow = blank(),
middle_temperature_flow = blank(),
high_temperature_flow = blank(),
gas_flow = ablank(),
}
end
local function southpipepictures()
return {
straight_vertical_single = blank(),
straight_vertical = ps(),
straight_vertical_window = ps(),
straight_horizontal_window = blank(),
straight_horizontal = blank(),
corner_up_right = blank(),
corner_up_left = blank(),
corner_down_right = ps(),
corner_down_left = ps(),
t_up = blank(),
t_down = ps(),
t_right = ps(),
t_left = ps(),
cross = ps(),
ending_up = blank(),
ending_down = ps(),
ending_right = blank(),
ending_left = blank(),
horizontal_window_background = blank(),
vertical_window_background = blank(),
fluid_background = blank(),
low_temperature_flow = blank(),
middle_temperature_flow = blank(),
high_temperature_flow = blank(),
gas_flow = ablank(),
}
end
-- Factory power I/O
local VALID_POWER_TRANSFER_RATES = {1,2,5,10,20,50,100,200,500,1000,2000,5000,10000,20000,50000,100000} -- MW
local function create_energy_interfaces(size, passive_input, passive_output, icon)
local j = size/2-0.3
local input_priority = (passive_input and "tertiary") or "secondary-input"
local output_priority = (passive_output and "tertiary") or "secondary-output"
for _, transfer_rate in pairs(VALID_POWER_TRANSFER_RATES) do
local buffer_size = transfer_rate*16667*power_batch_size
data:extend({
{
type = "electric-energy-interface",
name = "factory-power-input-" .. size .. "-" .. transfer_rate,
localised_name = {"entity-name.factory-power-input-" .. size},
icon = icon,
icon_size = 32,
flags = {"not-on-map"},
minable = nil,
max_health = 1,
selectable_in_game = false,
energy_source = {
type = "electric",
usage_priority = input_priority,
input_flow_limit = transfer_rate .. "MW",
--output_flow_limit = "0MW",
buffer_capacity = buffer_size .. "J",
render_no_power_icon = false,
},
energy_usage = "0MW",
energy_production = "0MW",
selection_box = {{-j,-j},{j,j}},
collision_box = {{-j,-j},{j,j}},
collision_mask = {},
},
{
type = "electric-energy-interface",
name = "factory-power-output-" .. size .. "-" .. transfer_rate,
localised_name = {"entity-name.factory-power-output-" .. size},
icon = icon,
icon_size = 32,
flags = {"not-on-map"},
minable = nil,
max_health = 1,
selectable_in_game = false,
energy_source = {
type = "electric",
usage_priority = output_priority,
--input_flow_limit = "0MW",
output_flow_limit = transfer_rate .. "MW",
buffer_capacity = buffer_size .. "J",
render_no_power_icon = false,
},
energy_usage = "0MW",
energy_production = "0MW",
selection_box = {{-j,-j},{j,j}},
collision_box = {{-j,-j},{j,j}},
collision_mask = {},
},
})
end
end
create_energy_interfaces(2,true,true,"__base__/graphics/icons/substation.png")
-- true,false would be optimal, but due to a bug it doesn't work. Maybe it'll be fixed.
-- In the meantime we'll have to settle for true,true because that's how factorissimo1 worked.
create_energy_interfaces(8,false,false,F.."/graphics/icon/subway-entrace.png")
-- Connection indicators
local function create_indicator(ctype, suffix, image)
data:extend({
{
type = "storage-tank",
name = "factory-connection-indicator-" .. ctype .. "-" .. suffix,
localised_name = {"entity-name.factory-connection-indicator-" .. ctype},
flags = {"not-on-map"},
minable = nil,
max_health = 500,
selection_box = {{-0.4,-0.4},{0.4,0.4}},
collision_box = {{-0.4,-0.4},{0.4,0.4}},
collision_mask = {},
fluid_box = {
base_area = 1,
pipe_connections = {},
},
two_direction_only = false,
window_bounding_box = {{0,0},{0,0}},
pictures = {
picture = {
sheet = {
filename = F.."/graphics/indicator/" .. image .. ".png",
priority = "extra-high",
frames = 4,
width = 32,
height = 32
},
},
fluid_background = blank(),
window_background = blank(),
flow_sprite = blank(),
gas_flow = ablank(),
},
flow_length_in_ticks = 100,
vehicle_impact_sound = {filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65},
--working_sound = silent,
circuit_wire_connection_points = circuit_connector_definitions["storage-tank"].points,
circuit_connector_sprites = circuit_connector_definitions["storage-tank"].sprites,
circuit_wire_max_distance = 0,
}
})
end
create_indicator("belt", "d0", "green-dir")
create_indicator("chest", "d0", "brown-dir") -- 0 is catchall for "There isn't an entity for this exact value"
create_indicator("chest", "d10", "brown-dir")
create_indicator("chest", "d20", "brown-dir")
create_indicator("chest", "d60", "brown-dir")
create_indicator("chest", "d180", "brown-dir")
create_indicator("chest", "d600", "brown-dir")
create_indicator("chest", "b0", "brown-dot")
create_indicator("chest", "b10", "brown-dot")
create_indicator("chest", "b20", "brown-dot")
create_indicator("chest", "b60", "brown-dot")
create_indicator("chest", "b180", "brown-dot")
create_indicator("chest", "b600", "brown-dot")
create_indicator("fluid", "d0", "blue-dir")
create_indicator("fluid", "d1", "blue-dir")
create_indicator("fluid", "d4", "blue-dir")
create_indicator("fluid", "d10", "blue-dir")
create_indicator("fluid", "d30", "blue-dir")
create_indicator("fluid", "d120", "blue-dir")
create_indicator("fluid", "b0", "blue-dot")
create_indicator("fluid", "b1", "blue-dot")
create_indicator("fluid", "b4", "blue-dot")
create_indicator("fluid", "b10", "blue-dot")
create_indicator("fluid", "b30", "blue-dot")
create_indicator("fluid", "b120", "blue-dot")
create_indicator("circuit", "d0", "red-dir")
create_indicator("circuit", "d1", "red-dir")
create_indicator("circuit", "d10", "red-dir")
create_indicator("circuit", "d60", "red-dir")
create_indicator("circuit", "d180", "red-dir")
create_indicator("circuit", "d600", "red-dir")
-- <E>
create_indicator("energy", "d0", "yellow-dir")
create_indicator("energy", "d1", "yellow-dir")
create_indicator("energy", "d2", "yellow-dir")
create_indicator("energy", "d5", "yellow-dir")
create_indicator("energy", "d10", "yellow-dir")
create_indicator("energy", "d20", "yellow-dir")
create_indicator("energy", "d50", "yellow-dir")
create_indicator("energy", "d100", "yellow-dir")
create_indicator("energy", "d200", "yellow-dir")
create_indicator("energy", "d500", "yellow-dir")
create_indicator("energy", "d1000", "yellow-dir")
create_indicator("energy", "d2000", "yellow-dir")
create_indicator("energy", "d5000", "yellow-dir")
create_indicator("energy", "d10000", "yellow-dir")
create_indicator("energy", "d20000", "yellow-dir")
create_indicator("energy", "d50000", "yellow-dir")
create_indicator("energy", "d100000", "yellow-dir")
-- Other auxiliary entities
local j = 0.99
data:extend({
{
type = "electric-pole",
name = "factory-power-pole",
minable = nil,
max_health = 1,
selection_box = {{-j,-j},{j,j}},
collision_box = {{-j,-j},{j,j}},
collision_mask = {},
maximum_wire_distance = 0,
supply_area_distance = 63,
pictures = table.deepcopy(data.raw["electric-pole"]["substation"].pictures),
radius_visualisation_picture = {
filename = "__base__/graphics/entity/small-electric-pole/electric-pole-radius-visualization.png",
width = 12,
height = 12,
priority = "extra-high-no-scale"
},
connection_points = {cwc0c(), cwc0c(), cwc0c(), cwc0c()},
},
{
type = "lamp",
name = "factory-ceiling-light",
icon = "__base__/graphics/icons/small-lamp.png",
icon_size = 32,
flags = {"not-on-map"},
minable = nil,
max_health = 55,
corpse = "small-remnants",
collision_box = {{-0.15, -0.15}, {0.15, 0.15}},
collision_mask = {},
selection_box = {{-0.5, -0.5}, {0.5, 0.5}},
selectable_in_game = false,
vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 },
energy_source =
{
type = "electric",
usage_priority = "secondary-input",
render_no_power_icon = false,
},
energy_usage_per_tick = "5KW",
light = {intensity = 1, size = 50},
light_when_colored = {intensity = 1, size = 6},
glow_size = 6,
glow_color_intensity = 0.135,
picture_off = blank(),
picture_on = blank(),
signal_to_color_mapping = {},
circuit_wire_connection_point = circuit_connector_definitions["lamp"].points,
circuit_connector_sprites = circuit_connector_definitions["lamp"].sprites,
circuit_wire_max_distance = 0,
},
})
local overlay_controller = table.deepcopy(data.raw["constant-combinator"]["constant-combinator"])
overlay_controller.name = "factory-overlay-controller"
overlay_controller.circuit_wire_max_distance = 0
data:extend({
overlay_controller
})
local function create_dummy_connector(dir, dx, dy, pictures)
data:extend({
{
type = "pipe",
name = "factory-fluid-dummy-connector-" .. dir,
flags = {"not-on-map", "hide-alt-info"},
minable = nil,
max_health = 500,
selection_box = {{-0.4,-0.4},{0.4,0.4}},
selectable_in_game = false,
collision_box = {{-0.4,-0.4},{0.4,0.4}},
collision_mask = {},
fluid_box = {
base_area = 1, -- Heresy
pipe_connections = {
{position = {dx, dy}, type = "output"},
},
},
horizontal_window_bounding_box = {{0,0},{0,0}},
vertical_window_bounding_box = {{0,0},{0,0}},
pictures = pictures,
vehicle_impact_sound = {filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65},
},
})
end
-- Connectors are named by the direction they are facing,
-- so that their names can be generated using cpos.direction_in or cpos.direction_out
create_dummy_connector(defines.direction.south, 0, 1, southpipepictures())
create_dummy_connector(defines.direction.north, 0, -1, blankpipepictures())
create_dummy_connector(defines.direction.east, 1, 0, blankpipepictures())
create_dummy_connector(defines.direction.west, -1, 0, blankpipepictures())
|
-- interface:
PalettesInfo = {
Count = PalettesInfo and PalettesInfo.Count or 200, -- new maximum number of palettes
-- PtrGetBW -> void* __fastcall GetBW(int palID)
-- calling: return mem.call(PalettesInfo.PtrGetBW, 2, palID)
-- PtrGetRed in MM6 (similar)
-- shades of other colors are obtained using traditional means
}
local i4, i2, i1, u4, u2, u1 = mem.i4, mem.i2, mem.i1, mem.u4, mem.u2, mem.u1
local mmver = offsets.MMVersion
local function mmv(...)
return (select(mmver - 5, ...))
end
function events.ScriptsLoaded()
local PalettesCount = PalettesInfo.Count
-- Instead of default 50 palettes we'll make N consequent blocks of 50 palettes each
local BlocksCount = (PalettesCount + 49):div(50)
-- if BlocksCount <= 1 then
-- return
-- end
local PalBlockIndex = mmv(106, 154, 154)
local PalBlockSize = PalBlockIndex*0x4000
local OldPalettes = mmv(0x762D80, 0x80D018, 0x84AFE0)
-- div is unusual here. (-5):div(10) = -1
local BasePalBlock = (mem.malloc((BlocksCount + 1)*PalBlockSize) + 0x3FFF - OldPalettes):div(0x4000)
local NewPalettes = OldPalettes + BasePalBlock*0x4000
local NewPalettesEnd = NewPalettes + BlocksCount*PalBlockSize
mem.fill(NewPalettes, BlocksCount*PalBlockSize, 0)
local IDOff = mmv(0x1A5E00, 0x267A00, 0x267A00)
local MistColorOff = mmv(0x1A5ED0, 0x267AD0, 0x267AD0)
local refs = {
[""] = "%",
BasePalBlock = BasePalBlock,
PalBlockSize = PalBlockSize,
PalBlockIndex = PalBlockIndex,
NewPalettes = NewPalettes,
}
local function c(code)
return (code:gsub("%%(%w*)%%", refs))
end
-- pointers to BW (and Red in MM6)
-- local function GetOffsetBW(i)
-- i = i - BasePalBlock
-- return i:div(PalBlockIndex)*PalBlockSize + (i % PalBlockIndex)*0x200
-- end
-- in Asm
refs.GetPtrBW = c[[
macro GetPtrBW REG, OFF, REGOUT
{
lea eax, [REG - %BasePalBlock%]
xor edx, edx
mov ecx, %PalBlockIndex%
idiv ecx ; eax = i:div(PalBlockIndex)
mov ecx, edx ; ecx = (i % PalBlockIndex)
mov edx, %PalBlockSize%
imul edx ; eax = i:div(PalBlockIndex)*PalBlockSize
sal ecx, 9 ; ecx = (i % PalBlockIndex)*0x200
if REGOUT eq
lea REG, [%NewPalettes% + OFF + eax + ecx]
else
lea REGOUT, [%NewPalettes% + OFF + eax + ecx]
end if
}
GetPtrBW]]
if mmver == 6 then
-- BW
mem.asmpatch(0x434894, c[[
savereg eax, edx
%GetPtrBW% ecx, 0x199600
]])
mem.asmpatch(0x46B70A, c[[
savereg eax, ecx
%GetPtrBW% edx, 0x199600
]])
-- Red
mem.asmpatch(0x46B773, c[[
pop esi
%GetPtrBW% eax, 0x19FA00
]])
mem.asmpatch(0x46B90A, c[[
%GetPtrBW% eax, 0x19FA00
]])
-- for use in Lua
PalettesInfo.PtrGetBW = mem.asmproc(c[[
%GetPtrBW% ecx, 0x199600, eax
ret
]])
PalettesInfo.PtrGetRed = mem.asmproc(c[[
%GetPtrBW% ecx, 0x19FA00, eax
ret
]])
else
local CodeBW = c[[
savereg edx, ecx
%GetPtrBW% eax, 0x261600
]]
mem.asmpatch(mmv(nil, 0x440DC0, 0x43DD0C), CodeBW)
mem.asmpatch(mmv(nil, 0x47BBDC, 0x47AECB), CodeBW)
-- for use in Lua
PalettesInfo.PtrGetBW = mem.asmproc(c[[
%GetPtrBW% ecx, 0x261600, eax
ret
]])
end
-- not in Asm
-- if mmver == 6 then
-- -- Red
-- mem.hook(0x434894, function(d)
-- d.ecx = NewPalettes + 0x199600 + GetOffsetBW(d.ecx)
-- end)
-- mem.hook(0x46B70A, function(d)
-- d.edx = NewPalettes + 0x199600 + GetOffsetBW(d.edx)
-- end)
-- -- BW
-- mem.hook(0x46B777, function(d)
-- d.eax = NewPalettes + 0x19FA00 + GetOffsetBW(d.eax/512)
-- end)
-- mem.hook(0x46B90A, function(d)
-- d.eax = NewPalettes + 0x19FA00 + GetOffsetBW(d.eax)
-- end)
-- else
-- local function BWHook(d)
-- d.eax = NewPalettes + 0x261600 + GetOffsetBW(d.eax/0x200)
-- end
-- mem.hook(mmv(nil, 0x440DC3, 0x43DD0F), BWHook)
-- mem.hook(mmv(nil, 0x47BBDC, 0x47AECE), BWHook)
-- end
-- copy mist/tint colors
local function CopyMist(a)
mem.copy(a + MistColorOff, OldPalettes + MistColorOff, 0x20)
end
-- functions that should run for each block
local function Batcher(ptr)
local size = mem.GetHookSize(ptr)
local std = mem.copycode(ptr, size)
mem.hook(ptr, function(d)
if d.ecx == OldPalettes then
d.ecx = NewPalettes
end
CopyMist(d.ecx)
local a = d.ecx + PalBlockSize
if a < NewPalettesEnd then
mem.call(ptr, 1, a)
end
mem.u4[d.esp] = std
end, size)
end
if mmver == 6 then
Batcher(0x47CD80)
Batcher(0x47CB70)
Batcher(0x47D0E0)
Batcher(0x47D0B0)
-- 47C400 isn't used
elseif mmver == 7 then
Batcher(0x48A5FA)
Batcher(0x48A31C)
Batcher(0x48A35F)
Batcher(0x48A8B2)
Batcher(0x48A889)
Batcher(0x48A2E6)
elseif mmver == 8 then
Batcher(0x489EF2)
Batcher(0x489C19)
Batcher(0x489C5C)
Batcher(0x48A1AA)
Batcher(0x48A181)
Batcher(0x489BE3)
end
-- LoadPalette
local function FindInPals(id)
for p = NewPalettes, NewPalettesEnd - 1, PalBlockSize do
for i = 1, 49 do
if i4[p + IDOff + i*4] == id then
return p
end
end
end
end
local aa = {}
local load_std = mem.copycode(mmv(0x47CBC0, 0x48A3A2, 0x489C9F), mmv(6, 9, 9))
mem.hook(mmv(0x47CBC0, 0x48A3A2, 0x489C9F), function(d)
local id = i4[d.esp + 8]
local p = FindInPals(id) or FindInPals(0) or NewPalettes
CopyMist(p)
d.eax = mem.call(load_std, 1, p, id) + (p - OldPalettes)/0x4000
d.esp = d.esp + 4
d:ret(4)
end, mmv(6, 9, 9))
end |
RegisterNetEvent('8bit_phone:client:SetSettings')
AddEventHandler('8bit_phone:client:SetSettings', function(data)
Config.Settings = data
SendNUIMessage({
action = 'setup',
data = { name = 'settings', data = data }
})
end)
RegisterNUICallback('ToggleMute', function(data, cb)
if data.muted then
Config.Settings.volume = 0
else
Config.Settings.volume = 100
TriggerServerEvent('mythic_sounds:server:PlayWithinDistance', 10.0, 'unmute', 0.025)
end
TriggerServerEvent('mythic_base:server:SaveData', Config.Settings)
cb(true)
end)
RegisterNUICallback('SaveSettings', function(data, cb)
Config.Settings = data
TriggerServerEvent('mythic_base:server:SaveData', Config.Settings)
cb(true)
end) |
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by torvald.
--- DateTime: 2019-11-03 22:00
---
require("document")
local args = {...}
local dir = args[1] or env.PWD
--print("args-1",args[1])
-- resolve relative dir
if args[1] and args[1]:byte(1) ~= 0x2F and args[1]:byte(1) ~= 0x5C then
dir = env.PWD .. args[1]
end
--print("lsdir", dir)
--print("realdir", realdir)
local names = {}
for name, _ in fs.list(dir) do
if fs.isDirectory(dir .. "/" .. name) and name:sub(-1) ~= "/" then -- checking trailing '/' because of the OpenComputers
table.insert(names, name .. "/")
else
table.insert(names, name)
end
end
table.sort(names)
doc.tabulate(names)
|
object_intangible_ship_lambda_pcd = object_intangible_ship_shared_lambda_pcd:new {
}
ObjectTemplates:addTemplate(object_intangible_ship_lambda_pcd, "object/intangible/ship/lambda_pcd.iff")
|
-------------------------------------------------
-- Battery Widget for Awesome Window Manager
-- Shows the battery status using the ACPI tool
-- More details could be found here:
-- https://github.com/streetturtle/awesome-wm-widgets/tree/master/battery-widget
-- @author Pavel Makhov
-- @copyright 2017 Pavel Makhov
-------------------------------------------------
local awful = require("awful")
local naughty = require("naughty")
local watch = require("awful.widget.watch")
local wibox = require("wibox")
-- acpi sample outputs
-- Battery 0: Discharging, 75%, 01:51:38 remaining
-- Battery 0: Charging, 53%, 00:57:43 until charged
local PATH_TO_ICONS = "/usr/share/icons/Arc/status/symbolic/"
local HOME = os.getenv("HOME")
local battery_widget = wibox.widget {
{
id = "icon",
widget = wibox.widget.imagebox,
resize = false
},
layout = wibox.container.margin(_, 0, 0, 3)
}
-- Popup with battery info
-- One way of creating a pop-up notification - naughty.notify
local notification
local function show_battery_status()
awful.spawn.easy_async([[bash -c 'acpi']],
function(stdout, _, _, _)
notification = naughty.notify{
text = stdout,
title = "Battery status",
timeout = 5, hover_timeout = 0.5,
width = 200,
}
end
)
end
-- Alternative to naughty.notify - tooltip. You can compare both and choose the preferred one
--battery_popup = awful.tooltip({objects = {battery_widget}})
-- To use colors from beautiful theme put
-- following lines in rc.lua before require("battery"):
-- beautiful.tooltip_fg = beautiful.fg_normal
-- beautiful.tooltip_bg = beautiful.bg_normal
local function show_battery_warning()
naughty.notify{
icon = HOME .. "/.config/awesome/nichosi.png",
icon_size=100,
text = "Huston, we have a problem",
title = "Battery is dying",
timeout = 5, hover_timeout = 0.5,
position = "bottom_right",
bg = "#F06060",
fg = "#EEE9EF",
width = 300,
}
end
local last_battery_check = os.time()
watch("acpi -i", 10,
function(widget, stdout, stderr, exitreason, exitcode)
local batteryType
local battery_info = {}
local capacities = {}
for s in stdout:gmatch("[^\r\n]+") do
local status, charge_str, time = string.match(s, '.+: (%a+), (%d?%d?%d)%%,?.*')
if string.match(s, 'rate information') then
-- ignore such line
elseif status ~= nil then
table.insert(battery_info, {status = status, charge = tonumber(charge_str)})
else
local cap_str = string.match(s, '.+:.+last full capacity (%d+)')
table.insert(capacities, tonumber(cap_str))
end
end
local capacity = 0
for i, cap in ipairs(capacities) do
capacity = capacity + cap
end
local charge = 0
local status
for i, batt in ipairs(battery_info) do
if batt.charge >= charge then
status = batt.status -- use most charged battery status
-- this is arbitrary, and maybe another metric should be used
end
charge = charge + batt.charge * capacities[i]
end
charge = charge / capacity
if (charge >= 0 and charge < 15) then
batteryType = "battery-empty%s-symbolic"
if status ~= 'Charging' and os.difftime(os.time(), last_battery_check) > 300 then
-- if 5 minutes have elapsed since the last warning
last_battery_check = time()
show_battery_warning()
end
elseif (charge >= 15 and charge < 40) then batteryType = "battery-caution%s-symbolic"
elseif (charge >= 40 and charge < 60) then batteryType = "battery-low%s-symbolic"
elseif (charge >= 60 and charge < 80) then batteryType = "battery-good%s-symbolic"
elseif (charge >= 80 and charge <= 100) then batteryType = "battery-full%s-symbolic"
end
if status == 'Charging' then
batteryType = string.format(batteryType, '-charging')
else
batteryType = string.format(batteryType, '')
end
widget.icon:set_image(PATH_TO_ICONS .. batteryType .. ".svg")
-- Update popup text
-- battery_popup.text = string.gsub(stdout, "\n$", "")
end,
battery_widget)
battery_widget:connect_signal("mouse::enter", function() show_battery_status() end)
battery_widget:connect_signal("mouse::leave", function() naughty.destroy(notification) end)
return battery_widget
|
local n="koolddns"
local i=require"luci.dispatcher"
local o=require"luci.model.network".init()
local m=require"nixio.fs"
local a,t,e
arg[1]=arg[1]or""
a=Map(n,translate("Koolddns Config"))
a.redirect=i.build_url("admin","services","koolddns")
t=a:section(NamedSection,arg[1],"koolddns","")
t.addremove=false
t.dynamic=false
e=t:option(ListValue,"enable",translate("Enable State"))
e.default="1"
e.rmempty=false
e:value("1",translate("Enable"))
e:value("0",translate("Disable"))
e=t:option(Value,"domain",translate("Main Domain"))
e.datatype="host"
e.rmempty=false
e=t:option(Value,"name",translate("Sub Domain"))
e.rmempty=false
e=t:option(ListValue,"record_type",translate("Record Type"))
e.rmempty=false
e.default="A"
e:value("A",translate("A Record"))
e:value("AAAA",translate("AAAA Record"))
e:depends("service","aliddns")
e=t:option(ListValue,"ttl_time",translate("TTL"))
e.rmempty=false
e.default="600"
e:value("600",translate("600s"))
e:value("120",translate("120s"))
e:value("60",translate("60s"))
e:value("10",translate("10s"))
e:depends("service","aliddns")
e=t:option(ListValue,"service",translate("Service Providers"))
if m.access("/usr/bin/klaliddns")then
e:value("aliddns",translate("AliDDNS"))
end
if m.access("/usr/bin/klcloudxns")then
e:value("cloudxns",translate("CloudXNS"))
end
if m.access("/usr/bin/kldnspod")then
e:value("dnspod",translate("DNSPOD"))
end
e.rmempty=false
e=t:option(Value,"accesskey",translate("Access Key"))
e.rmempty=false
e:depends("service","aliddns")
e:depends("service","cloudxns")
e=t:option(Value,"signature",translate("Signature"))
e.rmempty=false
e:depends("service","aliddns")
e:depends("service","cloudxns")
e=t:option(Value,"apitoken",translate("API Token"),translate("Go to dnspod.cn/console/user/security settings, (format: ID, Token), such as: 11220,2d11d8bd2711s8dr56y10564f9648523"))
e.rmempty=false
e:depends("service","dnspod")
e=t:option(Value,"interface",translate("Interface"))
e.rmempty=false
e:value("url",translate("Use the URL to obtain the public IP"))
for a,t in ipairs(o:get_networks())do
if t:name()~="loopback"then e:value(t:name())end
end
e=t:option(Value,"ipurl",translate("Internet Site"))
e:depends("interface","url")
e.default="whatismyip.akamai.com"
e=t:option(Value,"urlinterface",translate("urlInterface"))
e:depends("interface","url")
for a,t in ipairs(o:get_networks())do
if t:name()~="loopback"then e:value(t:name())end
end
return a
|
language.Add("pac_projectile", "Projectile")
local PART = {}
PART.ClassName = "projectile"
PART.Group = 'advanced'
PART.Icon = 'icon16/bomb.png'
pac.StartStorableVars()
pac.GetSet(PART, "Speed", 1)
pac.GetSet(PART, "AddOwnerSpeed", false)
pac.GetSet(PART, "Damping", 0)
pac.GetSet(PART, "Gravity", true)
pac.GetSet(PART, "Collisions", true)
pac.GetSet(PART, "Sphere", false)
pac.GetSet(PART, "Radius", 1)
pac.GetSet(PART, "DamageRadius", 50)
pac.GetSet(PART, "LifeTime", 5)
pac.GetSet(PART, "AimDir", false)
pac.GetSet(PART, "Sticky", false)
pac.GetSet(PART, "Bounce", 0)
pac.GetSet(PART, "BulletImpact", false)
pac.GetSet(PART, "Damage", 0)
pac.GetSet(PART, "DamageType", "generic", {enums = {
generic = 0, --generic damage
crush = 1, --caused by physics interaction
bullet = 2, --bullet damage
slash = 4, --sharp objects, such as manhacks or other npcs attacks
burn = 8, --damage from fire
vehicle = 16, --hit by a vehicle
fall = 32, --fall damage
blast = 64, --explosion damage
club = 128, --crowbar damage
shock = 256, --electrical damage, shows smoke at the damage position
sonic = 512, --sonic damage,used by the gargantua and houndeye npcs
energybeam = 1024, --laser
nevergib = 4096, --don't create gibs
alwaysgib = 8192, --always create gibs
drown = 16384, --drown damage
paralyze = 32768, --same as dmg_poison
nervegas = 65536, --neurotoxin damage
poison = 131072, --poison damage
acid = 1048576, --
airboat = 33554432, --airboat gun damage
blast_surface = 134217728, --this won't hurt the player underwater
buckshot = 536870912, --the pellets fired from a shotgun
direct = 268435456, --
dissolve = 67108864, --forces the entity to dissolve on death
drownrecover = 524288, --damage applied to the player to restore health after drowning
physgun = 8388608, --damage done by the gravity gun
plasma = 16777216, --
prevent_physics_force = 2048, --
radiation = 262144, --radiation
removenoragdoll = 4194304, --don't create a ragdoll on death
slowburn = 2097152, --
explosion = -1, -- util.BlastDamage
fire = -1, -- ent:Ignite(5)
-- env_entity_dissolver
dissolve_energy = 0,
dissolve_heavy_electrical = 1,
dissolve_light_electrical = 2,
dissolve_core_effect = 3,
heal = -1,
armor = -1,
}
})
pac.GetSet(PART, "Spread", 0)
pac.GetSet(PART, "Delay", 0)
pac.GetSet(PART, "Maximum", 0)
pac.GetSet(PART, "Mass", 100)
pac.GetSet(PART, "Attract", 0)
pac.GetSet(PART, "AttractMode", "projectile_nearest", {enums = {
hitpos = "hitpos",
hitpos_radius = "hitpos_radius",
closest_to_projectile = "closest_to_projectile",
closest_to_hitpos = "closest_to_hitpos",
}})
pac.GetSet(PART, "AttractRadius", 200)
pac.SetupPartName(PART, "OutfitPart")
pac.GetSet(PART, "Physical", false)
pac.GetSet(PART, "CollideWithOwner", false)
pac.GetSet(PART, "RemoveOnCollide", false)
pac.EndStorableVars()
function PART:OnShow(from_rendering)
if not from_rendering then
self.trigger = true
end
end
function PART:OnDraw(owner, pos, ang)
if self.trigger then
self:Shoot(pos, ang)
self.trigger = false
end
end
function PART:AttachToEntity(ent)
if not self.OutfitPart:IsValid() then return false end
ent.pac_draw_distance = 0
local tbl = self.OutfitPart:ToTable()
tbl.self.UniqueID = util.CRC(tbl.self.UniqueID .. tbl.self.UniqueID)
local part = pac.CreatePart(tbl.self.ClassName, self:GetPlayerOwner())
local id = part.Id + self:GetPlayerOwner():UniqueID()
part.show_in_editor = false
part.CheckOwner = function(s) s.Owner = ent end
part:SetPlayerOwner(self:GetPlayerOwner())
part:SetTable(tbl)
part:SetHide(false)
part:SetOwner(ent)
ent:CallOnRemove("pac_projectile_" .. id, function() part:Remove() end)
pac.HookEntityRender(ent, part)
ent.RenderOverride = ent.RenderOverride or function()
if self.AimDir then
ent:SetRenderAngles(ent:GetVelocity():Angle())
end
end
ent.pac_projectile_part = part
return true
end
local enable = CreateClientConVar("pac_sv_projectiles", 0, true)
function PART:Shoot(pos, ang)
local physics = self.Physical
if physics then
if pac.LocalPlayer ~= self:GetPlayerOwner() then return end
local tbl = {}
for key in pairs(self:GetStorableVars()) do
tbl[key] = self[key]
end
net.Start("pac_projectile")
net.WriteVector(pos)
net.WriteAngle(ang)
net.WriteTable(tbl)
net.SendToServer()
else
self.projectiles = self.projectiles or {}
local count = 0
for key, ent in pairs(self.projectiles) do
if not ent:IsValid() then
self.projectiles[key] = nil
else
count = count + 1
end
end
local max = math.min(self.Maximum, 100)
if max == 0 then
max = 100
end
if count > max then
return
end
local function spawn()
if not self:IsValid() then return end
local ent = pac.CreateEntity("models/props_junk/popcan01a.mdl")
if not ent:IsValid() then return end
local idx = table.insert(self.projectiles, ent)
ent:AddCallback("PhysicsCollide", function(ent, data)
local phys = ent:GetPhysicsObject()
if self.Bounce > 0 then
timer.Simple(0, function()
if phys:IsValid() then
phys:SetVelocity(data.OurOldVelocity - 2 * (data.HitNormal:Dot(data.OurOldVelocity) * data.HitNormal) * self.Bounce)
end
end)
elseif self.Sticky then
phys:SetVelocity(Vector(0,0,0))
phys:EnableMotion(false)
ent.pac_stuck = data.OurOldVelocity
end
if self.BulletImpact then
ent:FireBullets{
Attacker = ent:GetOwner(),
Damage = 0,
Force = 0,
Num = 1,
Src = data.HitPos - data.HitNormal,
Dir = data.HitNormal,
Distance = 10,
}
end
if self.RemoveOnCollide then
timer.Simple(0.01, function() SafeRemoveEntity(ent) end)
end
end)
ent:SetOwner(self:GetPlayerOwner(true))
ent:SetPos(pos)
ent:SetAngles(ang)
ent:SetCollisionGroup(COLLISION_GROUP_PROJECTILE)
if self.Sphere then
ent:PhysicsInitSphere(math.Clamp(self.Radius, 1, 30))
else
ent:PhysicsInitBox(Vector(1,1,1) * - math.Clamp(self.Radius, 1, 30), Vector(1,1,1) * math.Clamp(self.Radius, 1, 30))
end
ent.RenderOverride = function()
if not self:IsValid() then
return
end
if not self:GetOwner(true):IsValid() then
timer.Simple(0, function() SafeRemoveEntity(ent) end)
end
if self.AimDir then
if ent.pac_stuck then
ent:SetRenderAngles(ent.pac_stuck:Angle())
else
local angle = ent:GetVelocity():Angle()
ent:SetRenderAngles(angle)
ent.last_angle = angle
end
end
end
local phys = ent:GetPhysicsObject()
phys:EnableGravity(self.Gravity)
phys:AddVelocity((ang:Forward() + (VectorRand():Angle():Forward() * self.Spread)) * self.Speed * 1000)
if self.AddOwnerSpeed and ent:GetOwner():IsValid() then
phys:AddVelocity(ent:GetOwner():GetVelocity())
end
phys:EnableCollisions(self.Collisions)
phys:SetDamping(self.Damping, 0)
ent:SetCollisionGroup(COLLISION_GROUP_PROJECTILE)
if self:AttachToEntity(ent) then
timer.Simple(math.Clamp(self.LifeTime, 0, 10), function()
if ent:IsValid() then
if ent.pac_projectile_part and ent.pac_projectile_part:IsValid() then
ent.pac_projectile_part:Remove()
end
timer.Simple(0.5, function()
SafeRemoveEntity(ent)
end)
end
end)
end
end
if self.Delay == 0 then
spawn()
else
timer.Simple(self.Delay, spawn)
end
end
end
function PART:OnRemove()
if self.Physical then
net.Start("pac_projectile_remove_all")
net.SendToServer()
elseif self.projectiles then
for key, ent in pairs(self.projectiles) do
SafeRemoveEntity(ent)
end
self.projectiles = {}
end
end
--[[
function PART:OnHide()
if self.RemoveOnHide then
self:OnRemove()
end
end
]]
do -- physical
local Entity = Entity
local projectiles = {}
pac.AddHook("Think", "pac_projectile", function()
for key, data in pairs(projectiles) do
if not data.ply:IsValid() then
projectiles[key] = nil
goto CONTINUE
end
local ent = Entity(data.ent_id)
if ent:IsValid() and ent:GetClass() == "pac_projectile" then
local part = pac.GetPartFromUniqueID(data.ply:IsPlayer() and data.ply:UniqueID() or data.ply:EntIndex(), data.partuid)
if part:IsValid() and part:GetPlayerOwner() == data.ply then
part:AttachToEntity(ent)
end
projectiles[key] = nil
end
::CONTINUE::
end
end)
net.Receive("pac_projectile_attach", function()
local ply = net.ReadEntity()
local ent_id = net.ReadInt(16)
local partuid = net.ReadString()
if ply:IsValid() then
table.insert(projectiles, {ply = ply, ent_id = ent_id, partuid = partuid})
end
end)
end
pac.RegisterPart(PART)
|
-- Converted From LST file data\pathfinder\paizo\roleplaying_game\core_essentials\ce_abilitycategories.lst
-- From repository https://github.com/pcgen/pcgen at commit 11ceb52482855f2e5f0f6c108c3dc665b12af237
DefineAbilityCategory({
Name="Racial Size",
Category="Racial Size",
Editable=false,
EditPool=true,
FractionalPool=false,
Visible=false,
})
DefineAbilityCategory({
Name="Race Size Selection",
Category="Racial Size",
DisplayLocation="Racial Abilities",
Editable=true,
EditPool=false,
FractionalPool=false,
Plural="Sizes",
Visible=true,
Types={
"Race Size Selection",
},
})
DefineAbilityCategory({
Name="Class Level +4 Ability Adjustment",
Category="Special Ability",
DisplayLocation="Racial Abilities",
Editable=true,
EditPool=true,
FractionalPool=false,
Plural="Class Level +4 Ability Adjustments",
Visible=true,
Types={
"ClassLevelAdjustmentPlus4",
},
})
DefineAbilityCategory({
Name="Class Level +2 Ability Adjustment",
Category="Special Ability",
DisplayLocation="Racial Abilities",
Editable=true,
EditPool=true,
FractionalPool=false,
Plural="Class Level +2 Ability Adjustments",
Visible=true,
Types={
"ClassLevelAdjustmentPlus2",
},
})
DefineAbilityCategory({
Name="Class Level -2 Ability Adjustment",
Category="Special Ability",
DisplayLocation="Racial Abilities",
Editable=true,
EditPool=true,
FractionalPool=false,
Plural="Class Level -2 Ability Adjustments",
Visible=true,
Types={
"ClassLevelAdjustmentMinus2",
},
})
DefineAbilityCategory({
Name="Emotive Duality",
Category="Special Ability",
DisplayLocation="Racial Abilities",
Editable=true,
EditPool=true,
FractionalPool=false,
Plural="Emotive Dualities",
Visible=true,
Types={
"EmotiveDuality",
},
})
DefineAbilityCategory({
Name="Tiefling Language",
Category="Special Ability",
DisplayLocation="Racial Abilities",
Editable=true,
EditPool=false,
FractionalPool=false,
Plural="Tiefling Languages",
Visible=true,
Types={
"TieflingLanguageTrait",
},
})
DefineAbilityCategory({
Name="Ability Focus",
Category="Ability Focus",
Editable=true,
EditPool=false,
FractionalPool=false,
Visible=false,
})
DefineAbilityCategory({
Name="Spell-Like Ability",
Category="Spell-Like Ability",
Editable=false,
EditPool=false,
Visible=false,
})
DefineAbilityCategory({
Name="SLA",
Category="SLA",
Editable=false,
EditPool=false,
Visible=false,
})
DefineAbilityCategory({
Name="Giant Creature Option",
Category="Special Ability",
DisplayLocation="Racial Abilities",
Editable=true,
EditPool=true,
FractionalPool=false,
Plural="Giant Creature Options",
Visible=true,
Types={
"GiantCreatureSelection",
},
})
DefineAbilityCategory({
Name="Setting Specific Language",
Category="Internal",
DisplayLocation="Racial Abilities",
Editable=true,
EditPool=false,
FractionalPool=false,
Visible=true,
Types={
"RaceLanguageSelection",
},
})
DefineAbilityCategory({
Name="Disable First Level Domain Power",
Category="Internal",
AbilityList="DisableDomainLVL1",
DisplayLocation="Class Abilities",
Editable=true,
EditPool=false,
FractionalPool=false,
Visible=true,
})
DefineAbilityCategory({
Name="Class",
Category="CLASS",
Editable=true,
EditPool=true,
FractionalPool=false,
Visible=false,
})
DefineAbilityCategory({
Name="Size",
Category="Internal",
DisplayLocation="Racial Abilities",
Editable=true,
EditPool=false,
FractionalPool=false,
Plural="Sizes",
Visible=true,
Types={
"Size",
},
})
DefineAbilityCategory({
Name="Save Bonus",
Category="Save Bonus",
Editable=true,
EditPool=true,
FractionalPool=false,
Visible=false,
})
|
local UV = require "luv"
local Hub = require "luver.hub"
local Luver = {}
function Luver.start(f)
Hub:fork_callback(f)
UV.run()
end
function Luver.stop()
UV.stop()
end
function Luver.fork(f, ...)
Hub:fork_callback(f, ...)
end
function Luver.sleep(ts)
Hub:sleep(ts)
end
function Luver.now()
return UV.now()
end
function Luver.hrtime()
return UV.hrtime() / (10^9)
end
function Luver.thread(f, ...)
return UV.new_thread(f, ...)
end
return Luver
|
--- GENERATED CODE - DO NOT MODIFY
-- Amazon CloudSearch Domain (cloudsearchdomain-2013-01-01)
local M = {}
M.metadata = {
api_version = "2013-01-01",
json_version = "1.1",
protocol = "rest-json",
checksum_format = "",
endpoint_prefix = "cloudsearchdomain",
service_abbreviation = "",
service_full_name = "Amazon CloudSearch Domain",
signature_version = "v4",
target_prefix = "",
timestamp_format = "",
global_endpoint = "",
uid = "cloudsearchdomain-2013-01-01",
}
local keys = {}
local asserts = {}
keys.FieldStats = { ["count"] = true, ["missing"] = true, ["max"] = true, ["sum"] = true, ["min"] = true, ["sumOfSquares"] = true, ["stddev"] = true, ["mean"] = true, nil }
function asserts.AssertFieldStats(struct)
assert(struct)
assert(type(struct) == "table", "Expected FieldStats to be of type 'table'")
if struct["count"] then asserts.AssertLong(struct["count"]) end
if struct["missing"] then asserts.AssertLong(struct["missing"]) end
if struct["max"] then asserts.AssertString(struct["max"]) end
if struct["sum"] then asserts.AssertDouble(struct["sum"]) end
if struct["min"] then asserts.AssertString(struct["min"]) end
if struct["sumOfSquares"] then asserts.AssertDouble(struct["sumOfSquares"]) end
if struct["stddev"] then asserts.AssertDouble(struct["stddev"]) end
if struct["mean"] then asserts.AssertString(struct["mean"]) end
for k,_ in pairs(struct) do
assert(keys.FieldStats[k], "FieldStats contains unknown key " .. tostring(k))
end
end
--- Create a structure of type FieldStats
-- <p>The statistics for a field calculated in the request.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * count [Long] <p>The number of documents that contain a value in the specified field in the result set.</p>
-- * missing [Long] <p>The number of documents that do not contain a value in the specified field in the result set.</p>
-- * max [String] <p>The maximum value found in the specified field in the result set.</p> <p>If the field is numeric (<code>int</code>, <code>int-array</code>, <code>double</code>, or <code>double-array</code>), <code>max</code> is the string representation of a double-precision 64-bit floating point value. If the field is <code>date</code> or <code>date-array</code>, <code>max</code> is the string representation of a date with the format specified in <a href="http://tools.ietf.org/html/rfc3339">IETF RFC3339</a>: yyyy-mm-ddTHH:mm:ss.SSSZ.</p>
-- * sum [Double] <p>The sum of the field values across the documents in the result set. <code>null</code> for date fields.</p>
-- * min [String] <p>The minimum value found in the specified field in the result set.</p> <p>If the field is numeric (<code>int</code>, <code>int-array</code>, <code>double</code>, or <code>double-array</code>), <code>min</code> is the string representation of a double-precision 64-bit floating point value. If the field is <code>date</code> or <code>date-array</code>, <code>min</code> is the string representation of a date with the format specified in <a href="http://tools.ietf.org/html/rfc3339">IETF RFC3339</a>: yyyy-mm-ddTHH:mm:ss.SSSZ.</p>
-- * sumOfSquares [Double] <p>The sum of all field values in the result set squared.</p>
-- * stddev [Double] <p>The standard deviation of the values in the specified field in the result set.</p>
-- * mean [String] <p>The average of the values found in the specified field in the result set.</p> <p>If the field is numeric (<code>int</code>, <code>int-array</code>, <code>double</code>, or <code>double-array</code>), <code>mean</code> is the string representation of a double-precision 64-bit floating point value. If the field is <code>date</code> or <code>date-array</code>, <code>mean</code> is the string representation of a date with the format specified in <a href="http://tools.ietf.org/html/rfc3339">IETF RFC3339</a>: yyyy-mm-ddTHH:mm:ss.SSSZ.</p>
-- @return FieldStats structure as a key-value pair table
function M.FieldStats(args)
assert(args, "You must provide an argument table when creating FieldStats")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["count"] = args["count"],
["missing"] = args["missing"],
["max"] = args["max"],
["sum"] = args["sum"],
["min"] = args["min"],
["sumOfSquares"] = args["sumOfSquares"],
["stddev"] = args["stddev"],
["mean"] = args["mean"],
}
asserts.AssertFieldStats(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.DocumentServiceException = { ["status"] = true, ["message"] = true, nil }
function asserts.AssertDocumentServiceException(struct)
assert(struct)
assert(type(struct) == "table", "Expected DocumentServiceException to be of type 'table'")
if struct["status"] then asserts.AssertString(struct["status"]) end
if struct["message"] then asserts.AssertString(struct["message"]) end
for k,_ in pairs(struct) do
assert(keys.DocumentServiceException[k], "DocumentServiceException contains unknown key " .. tostring(k))
end
end
--- Create a structure of type DocumentServiceException
-- <p>Information about any problems encountered while processing an upload request.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * status [String] <p>The return status of a document upload request, <code>error</code> or <code>success</code>.</p>
-- * message [String] <p>The description of the errors returned by the document service.</p>
-- @return DocumentServiceException structure as a key-value pair table
function M.DocumentServiceException(args)
assert(args, "You must provide an argument table when creating DocumentServiceException")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["status"] = args["status"],
["message"] = args["message"],
}
asserts.AssertDocumentServiceException(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.BucketInfo = { ["buckets"] = true, nil }
function asserts.AssertBucketInfo(struct)
assert(struct)
assert(type(struct) == "table", "Expected BucketInfo to be of type 'table'")
if struct["buckets"] then asserts.AssertBucketList(struct["buckets"]) end
for k,_ in pairs(struct) do
assert(keys.BucketInfo[k], "BucketInfo contains unknown key " .. tostring(k))
end
end
--- Create a structure of type BucketInfo
-- <p>A container for the calculated facet values and counts.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * buckets [BucketList] <p>A list of the calculated facet values and counts.</p>
-- @return BucketInfo structure as a key-value pair table
function M.BucketInfo(args)
assert(args, "You must provide an argument table when creating BucketInfo")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["buckets"] = args["buckets"],
}
asserts.AssertBucketInfo(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.Hit = { ["fields"] = true, ["highlights"] = true, ["id"] = true, ["exprs"] = true, nil }
function asserts.AssertHit(struct)
assert(struct)
assert(type(struct) == "table", "Expected Hit to be of type 'table'")
if struct["fields"] then asserts.AssertFields(struct["fields"]) end
if struct["highlights"] then asserts.AssertHighlights(struct["highlights"]) end
if struct["id"] then asserts.AssertString(struct["id"]) end
if struct["exprs"] then asserts.AssertExprs(struct["exprs"]) end
for k,_ in pairs(struct) do
assert(keys.Hit[k], "Hit contains unknown key " .. tostring(k))
end
end
--- Create a structure of type Hit
-- <p>Information about a document that matches the search request.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * fields [Fields] <p>The fields returned from a document that matches the search request.</p>
-- * highlights [Highlights] <p>The highlights returned from a document that matches the search request.</p>
-- * id [String] <p>The document ID of a document that matches the search request.</p>
-- * exprs [Exprs] <p>The expressions returned from a document that matches the search request.</p>
-- @return Hit structure as a key-value pair table
function M.Hit(args)
assert(args, "You must provide an argument table when creating Hit")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["fields"] = args["fields"],
["highlights"] = args["highlights"],
["id"] = args["id"],
["exprs"] = args["exprs"],
}
asserts.AssertHit(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.UploadDocumentsResponse = { ["status"] = true, ["warnings"] = true, ["adds"] = true, ["deletes"] = true, nil }
function asserts.AssertUploadDocumentsResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected UploadDocumentsResponse to be of type 'table'")
if struct["status"] then asserts.AssertString(struct["status"]) end
if struct["warnings"] then asserts.AssertDocumentServiceWarnings(struct["warnings"]) end
if struct["adds"] then asserts.AssertAdds(struct["adds"]) end
if struct["deletes"] then asserts.AssertDeletes(struct["deletes"]) end
for k,_ in pairs(struct) do
assert(keys.UploadDocumentsResponse[k], "UploadDocumentsResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type UploadDocumentsResponse
-- <p>Contains the response to an <code>UploadDocuments</code> request.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * status [String] <p>The status of an <code>UploadDocumentsRequest</code>.</p>
-- * warnings [DocumentServiceWarnings] <p>Any warnings returned by the document service about the documents being uploaded.</p>
-- * adds [Adds] <p>The number of documents that were added to the search domain.</p>
-- * deletes [Deletes] <p>The number of documents that were deleted from the search domain.</p>
-- @return UploadDocumentsResponse structure as a key-value pair table
function M.UploadDocumentsResponse(args)
assert(args, "You must provide an argument table when creating UploadDocumentsResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["status"] = args["status"],
["warnings"] = args["warnings"],
["adds"] = args["adds"],
["deletes"] = args["deletes"],
}
asserts.AssertUploadDocumentsResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.SearchStatus = { ["timems"] = true, ["rid"] = true, nil }
function asserts.AssertSearchStatus(struct)
assert(struct)
assert(type(struct) == "table", "Expected SearchStatus to be of type 'table'")
if struct["timems"] then asserts.AssertLong(struct["timems"]) end
if struct["rid"] then asserts.AssertString(struct["rid"]) end
for k,_ in pairs(struct) do
assert(keys.SearchStatus[k], "SearchStatus contains unknown key " .. tostring(k))
end
end
--- Create a structure of type SearchStatus
-- <p>Contains the resource id (<code>rid</code>) and the time it took to process the request (<code>timems</code>).</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * timems [Long] <p>How long it took to process the request, in milliseconds.</p>
-- * rid [String] <p>The encrypted resource ID for the request.</p>
-- @return SearchStatus structure as a key-value pair table
function M.SearchStatus(args)
assert(args, "You must provide an argument table when creating SearchStatus")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["timems"] = args["timems"],
["rid"] = args["rid"],
}
asserts.AssertSearchStatus(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.SuggestResponse = { ["status"] = true, ["suggest"] = true, nil }
function asserts.AssertSuggestResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected SuggestResponse to be of type 'table'")
if struct["status"] then asserts.AssertSuggestStatus(struct["status"]) end
if struct["suggest"] then asserts.AssertSuggestModel(struct["suggest"]) end
for k,_ in pairs(struct) do
assert(keys.SuggestResponse[k], "SuggestResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type SuggestResponse
-- <p>Contains the response to a <code>Suggest</code> request.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * status [SuggestStatus] <p>The status of a <code>SuggestRequest</code>. Contains the resource ID (<code>rid</code>) and how long it took to process the request (<code>timems</code>).</p>
-- * suggest [SuggestModel] <p>Container for the matching search suggestion information.</p>
-- @return SuggestResponse structure as a key-value pair table
function M.SuggestResponse(args)
assert(args, "You must provide an argument table when creating SuggestResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["status"] = args["status"],
["suggest"] = args["suggest"],
}
asserts.AssertSuggestResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.UploadDocumentsRequest = { ["documents"] = true, ["contentType"] = true, nil }
function asserts.AssertUploadDocumentsRequest(struct)
assert(struct)
assert(type(struct) == "table", "Expected UploadDocumentsRequest to be of type 'table'")
assert(struct["documents"], "Expected key documents to exist in table")
assert(struct["contentType"], "Expected key contentType to exist in table")
if struct["documents"] then asserts.AssertBlob(struct["documents"]) end
if struct["contentType"] then asserts.AssertContentType(struct["contentType"]) end
for k,_ in pairs(struct) do
assert(keys.UploadDocumentsRequest[k], "UploadDocumentsRequest contains unknown key " .. tostring(k))
end
end
--- Create a structure of type UploadDocumentsRequest
-- <p>Container for the parameters to the <code>UploadDocuments</code> request.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * documents [Blob] <p>A batch of documents formatted in JSON or HTML.</p>
-- * contentType [ContentType] <p>The format of the batch you are uploading. Amazon CloudSearch supports two document batch formats:</p> <ul> <li>application/json</li> <li>application/xml</li> </ul>
-- Required key: documents
-- Required key: contentType
-- @return UploadDocumentsRequest structure as a key-value pair table
function M.UploadDocumentsRequest(args)
assert(args, "You must provide an argument table when creating UploadDocumentsRequest")
local query_args = {
}
local uri_args = {
}
local header_args = {
["Content-Type"] = args["contentType"],
}
local all_args = {
["documents"] = args["documents"],
["contentType"] = args["contentType"],
}
asserts.AssertUploadDocumentsRequest(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.SearchException = { ["message"] = true, nil }
function asserts.AssertSearchException(struct)
assert(struct)
assert(type(struct) == "table", "Expected SearchException to be of type 'table'")
if struct["message"] then asserts.AssertString(struct["message"]) end
for k,_ in pairs(struct) do
assert(keys.SearchException[k], "SearchException contains unknown key " .. tostring(k))
end
end
--- Create a structure of type SearchException
-- <p>Information about any problems encountered while processing a search request.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * message [String] <p>A description of the error returned by the search service.</p>
-- @return SearchException structure as a key-value pair table
function M.SearchException(args)
assert(args, "You must provide an argument table when creating SearchException")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["message"] = args["message"],
}
asserts.AssertSearchException(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.Hits = { ["cursor"] = true, ["found"] = true, ["hit"] = true, ["start"] = true, nil }
function asserts.AssertHits(struct)
assert(struct)
assert(type(struct) == "table", "Expected Hits to be of type 'table'")
if struct["cursor"] then asserts.AssertString(struct["cursor"]) end
if struct["found"] then asserts.AssertLong(struct["found"]) end
if struct["hit"] then asserts.AssertHitList(struct["hit"]) end
if struct["start"] then asserts.AssertLong(struct["start"]) end
for k,_ in pairs(struct) do
assert(keys.Hits[k], "Hits contains unknown key " .. tostring(k))
end
end
--- Create a structure of type Hits
-- <p>The collection of documents that match the search request.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * cursor [String] <p>A cursor that can be used to retrieve the next set of matching documents when you want to page through a large result set.</p>
-- * found [Long] <p>The total number of documents that match the search request.</p>
-- * hit [HitList] <p>A document that matches the search request.</p>
-- * start [Long] <p>The index of the first matching document.</p>
-- @return Hits structure as a key-value pair table
function M.Hits(args)
assert(args, "You must provide an argument table when creating Hits")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["cursor"] = args["cursor"],
["found"] = args["found"],
["hit"] = args["hit"],
["start"] = args["start"],
}
asserts.AssertHits(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.SuggestStatus = { ["timems"] = true, ["rid"] = true, nil }
function asserts.AssertSuggestStatus(struct)
assert(struct)
assert(type(struct) == "table", "Expected SuggestStatus to be of type 'table'")
if struct["timems"] then asserts.AssertLong(struct["timems"]) end
if struct["rid"] then asserts.AssertString(struct["rid"]) end
for k,_ in pairs(struct) do
assert(keys.SuggestStatus[k], "SuggestStatus contains unknown key " .. tostring(k))
end
end
--- Create a structure of type SuggestStatus
-- <p>Contains the resource id (<code>rid</code>) and the time it took to process the request (<code>timems</code>).</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * timems [Long] <p>How long it took to process the request, in milliseconds.</p>
-- * rid [String] <p>The encrypted resource ID for the request.</p>
-- @return SuggestStatus structure as a key-value pair table
function M.SuggestStatus(args)
assert(args, "You must provide an argument table when creating SuggestStatus")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["timems"] = args["timems"],
["rid"] = args["rid"],
}
asserts.AssertSuggestStatus(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.Bucket = { ["count"] = true, ["value"] = true, nil }
function asserts.AssertBucket(struct)
assert(struct)
assert(type(struct) == "table", "Expected Bucket to be of type 'table'")
if struct["count"] then asserts.AssertLong(struct["count"]) end
if struct["value"] then asserts.AssertString(struct["value"]) end
for k,_ in pairs(struct) do
assert(keys.Bucket[k], "Bucket contains unknown key " .. tostring(k))
end
end
--- Create a structure of type Bucket
-- <p>A container for facet information. </p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * count [Long] <p>The number of hits that contain the facet value in the specified facet field.</p>
-- * value [String] <p>The facet value being counted.</p>
-- @return Bucket structure as a key-value pair table
function M.Bucket(args)
assert(args, "You must provide an argument table when creating Bucket")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["count"] = args["count"],
["value"] = args["value"],
}
asserts.AssertBucket(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.SearchResponse = { ["status"] = true, ["hits"] = true, ["stats"] = true, ["facets"] = true, nil }
function asserts.AssertSearchResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected SearchResponse to be of type 'table'")
if struct["status"] then asserts.AssertSearchStatus(struct["status"]) end
if struct["hits"] then asserts.AssertHits(struct["hits"]) end
if struct["stats"] then asserts.AssertStats(struct["stats"]) end
if struct["facets"] then asserts.AssertFacets(struct["facets"]) end
for k,_ in pairs(struct) do
assert(keys.SearchResponse[k], "SearchResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type SearchResponse
-- <p>The result of a <code>Search</code> request. Contains the documents that match the specified search criteria and any requested fields, highlights, and facet information.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * status [SearchStatus] <p>The status information returned for the search request.</p>
-- * hits [Hits] <p>The documents that match the search criteria.</p>
-- * stats [Stats] <p>The requested field statistics information.</p>
-- * facets [Facets] <p>The requested facet information.</p>
-- @return SearchResponse structure as a key-value pair table
function M.SearchResponse(args)
assert(args, "You must provide an argument table when creating SearchResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["status"] = args["status"],
["hits"] = args["hits"],
["stats"] = args["stats"],
["facets"] = args["facets"],
}
asserts.AssertSearchResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.DocumentServiceWarning = { ["message"] = true, nil }
function asserts.AssertDocumentServiceWarning(struct)
assert(struct)
assert(type(struct) == "table", "Expected DocumentServiceWarning to be of type 'table'")
if struct["message"] then asserts.AssertString(struct["message"]) end
for k,_ in pairs(struct) do
assert(keys.DocumentServiceWarning[k], "DocumentServiceWarning contains unknown key " .. tostring(k))
end
end
--- Create a structure of type DocumentServiceWarning
-- <p>A warning returned by the document service when an issue is discovered while processing an upload request.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * message [String] <p>The description for a warning returned by the document service.</p>
-- @return DocumentServiceWarning structure as a key-value pair table
function M.DocumentServiceWarning(args)
assert(args, "You must provide an argument table when creating DocumentServiceWarning")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["message"] = args["message"],
}
asserts.AssertDocumentServiceWarning(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.SuggestRequest = { ["query"] = true, ["suggester"] = true, ["size"] = true, nil }
function asserts.AssertSuggestRequest(struct)
assert(struct)
assert(type(struct) == "table", "Expected SuggestRequest to be of type 'table'")
assert(struct["query"], "Expected key query to exist in table")
assert(struct["suggester"], "Expected key suggester to exist in table")
if struct["query"] then asserts.AssertQuery(struct["query"]) end
if struct["suggester"] then asserts.AssertSuggester(struct["suggester"]) end
if struct["size"] then asserts.AssertSuggestionsSize(struct["size"]) end
for k,_ in pairs(struct) do
assert(keys.SuggestRequest[k], "SuggestRequest contains unknown key " .. tostring(k))
end
end
--- Create a structure of type SuggestRequest
-- <p>Container for the parameters to the <code>Suggest</code> request.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * query [Query] <p>Specifies the string for which you want to get suggestions.</p>
-- * suggester [Suggester] <p>Specifies the name of the suggester to use to find suggested matches.</p>
-- * size [SuggestionsSize] <p>Specifies the maximum number of suggestions to return. </p>
-- Required key: query
-- Required key: suggester
-- @return SuggestRequest structure as a key-value pair table
function M.SuggestRequest(args)
assert(args, "You must provide an argument table when creating SuggestRequest")
local query_args = {
["q"] = args["query"],
["suggester"] = args["suggester"],
["size"] = args["size"],
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["query"] = args["query"],
["suggester"] = args["suggester"],
["size"] = args["size"],
}
asserts.AssertSuggestRequest(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.SearchRequest = { ["sort"] = true, ["facet"] = true, ["stats"] = true, ["partial"] = true, ["filterQuery"] = true, ["expr"] = true, ["return"] = true, ["cursor"] = true, ["start"] = true, ["queryOptions"] = true, ["query"] = true, ["highlight"] = true, ["queryParser"] = true, ["size"] = true, nil }
function asserts.AssertSearchRequest(struct)
assert(struct)
assert(type(struct) == "table", "Expected SearchRequest to be of type 'table'")
assert(struct["query"], "Expected key query to exist in table")
if struct["sort"] then asserts.AssertSort(struct["sort"]) end
if struct["facet"] then asserts.AssertFacet(struct["facet"]) end
if struct["stats"] then asserts.AssertStat(struct["stats"]) end
if struct["partial"] then asserts.AssertPartial(struct["partial"]) end
if struct["filterQuery"] then asserts.AssertFilterQuery(struct["filterQuery"]) end
if struct["expr"] then asserts.AssertExpr(struct["expr"]) end
if struct["return"] then asserts.AssertReturn(struct["return"]) end
if struct["cursor"] then asserts.AssertCursor(struct["cursor"]) end
if struct["start"] then asserts.AssertStart(struct["start"]) end
if struct["queryOptions"] then asserts.AssertQueryOptions(struct["queryOptions"]) end
if struct["query"] then asserts.AssertQuery(struct["query"]) end
if struct["highlight"] then asserts.AssertHighlight(struct["highlight"]) end
if struct["queryParser"] then asserts.AssertQueryParser(struct["queryParser"]) end
if struct["size"] then asserts.AssertSize(struct["size"]) end
for k,_ in pairs(struct) do
assert(keys.SearchRequest[k], "SearchRequest contains unknown key " .. tostring(k))
end
end
--- Create a structure of type SearchRequest
-- <p>Container for the parameters to the <code>Search</code> request.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * sort [Sort] <p>Specifies the fields or custom expressions to use to sort the search results. Multiple fields or expressions are specified as a comma-separated list. You must specify the sort direction (<code>asc</code> or <code>desc</code>) for each field; for example, <code>year desc,title asc</code>. To use a field to sort results, the field must be sort-enabled in the domain configuration. Array type fields cannot be used for sorting. If no <code>sort</code> parameter is specified, results are sorted by their default relevance scores in descending order: <code>_score desc</code>. You can also sort by document ID (<code>_id asc</code>) and version (<code>_version desc</code>).</p> <p>For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/sorting-results.html">Sorting Results</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
-- * facet [Facet] <p>Specifies one or more fields for which to get facet information, and options that control how the facet information is returned. Each specified field must be facet-enabled in the domain configuration. The fields and options are specified in JSON using the form <code>{"FIELD":{"OPTION":VALUE,"OPTION:"STRING"},"FIELD":{"OPTION":VALUE,"OPTION":"STRING"}}</code>.</p> <p>You can specify the following faceting options:</p> <ul> <li> <p><code>buckets</code> specifies an array of the facet values or ranges to count. Ranges are specified using the same syntax that you use to search for a range of values. For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/searching-ranges.html"> Searching for a Range of Values</a> in the <i>Amazon CloudSearch Developer Guide</i>. Buckets are returned in the order they are specified in the request. The <code>sort</code> and <code>size</code> options are not valid if you specify <code>buckets</code>.</p> </li> <li> <p><code>size</code> specifies the maximum number of facets to include in the results. By default, Amazon CloudSearch returns counts for the top 10. The <code>size</code> parameter is only valid when you specify the <code>sort</code> option; it cannot be used in conjunction with <code>buckets</code>.</p> </li> <li> <p><code>sort</code> specifies how you want to sort the facets in the results: <code>bucket</code> or <code>count</code>. Specify <code>bucket</code> to sort alphabetically or numerically by facet value (in ascending order). Specify <code>count</code> to sort by the facet counts computed for each facet value (in descending order). To retrieve facet counts for particular values or ranges of values, use the <code>buckets</code> option instead of <code>sort</code>. </p> </li> </ul> <p>If no facet options are specified, facet counts are computed for all field values, the facets are sorted by facet count, and the top 10 facets are returned in the results.</p> <p>To count particular buckets of values, use the <code>buckets</code> option. For example, the following request uses the <code>buckets</code> option to calculate and return facet counts by decade.</p> <p><code> {"year":{"buckets":["[1970,1979]","[1980,1989]","[1990,1999]","[2000,2009]","[2010,}"]}} </code></p> <p>To sort facets by facet count, use the <code>count</code> option. For example, the following request sets the <code>sort</code> option to <code>count</code> to sort the facet values by facet count, with the facet values that have the most matching documents listed first. Setting the <code>size</code> option to 3 returns only the top three facet values.</p> <p><code> {"year":{"sort":"count","size":3}} </code></p> <p>To sort the facets by value, use the <code>bucket</code> option. For example, the following request sets the <code>sort</code> option to <code>bucket</code> to sort the facet values numerically by year, with earliest year listed first. </p> <p><code> {"year":{"sort":"bucket"}} </code></p> <p>For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/faceting.html">Getting and Using Facet Information</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
-- * stats [Stat] <p>Specifies one or more fields for which to get statistics information. Each specified field must be facet-enabled in the domain configuration. The fields are specified in JSON using the form:</p> <code>{"FIELD-A":{},"FIELD-B":{}}</code> <p>There are currently no options supported for statistics.</p>
-- * partial [Partial] <p>Enables partial results to be returned if one or more index partitions are unavailable. When your search index is partitioned across multiple search instances, by default Amazon CloudSearch only returns results if every partition can be queried. This means that the failure of a single search instance can result in 5xx (internal server) errors. When you enable partial results, Amazon CloudSearch returns whatever results are available and includes the percentage of documents searched in the search results (percent-searched). This enables you to more gracefully degrade your users' search experience. For example, rather than displaying no results, you could display the partial results and a message indicating that the results might be incomplete due to a temporary system outage.</p>
-- * filterQuery [FilterQuery] <p>Specifies a structured query that filters the results of a search without affecting how the results are scored and sorted. You use <code>filterQuery</code> in conjunction with the <code>query</code> parameter to filter the documents that match the constraints specified in the <code>query</code> parameter. Specifying a filter controls only which matching documents are included in the results, it has no effect on how they are scored and sorted. The <code>filterQuery</code> parameter supports the full structured query syntax. </p> <p>For more information about using filters, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/filtering-results.html">Filtering Matching Documents</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
-- * expr [Expr] <p>Defines one or more numeric expressions that can be used to sort results or specify search or filter criteria. You can also specify expressions as return fields. </p> <p>You specify the expressions in JSON using the form <code>{"EXPRESSIONNAME":"EXPRESSION"}</code>. You can define and use multiple expressions in a search request. For example:</p> <p><code> {"expression1":"_score*rating", "expression2":"(1/rank)*year"} </code> </p> <p>For information about the variables, operators, and functions you can use in expressions, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-expressions.html#writing-expressions">Writing Expressions</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
-- * return [Return] <p>Specifies the field and expression values to include in the response. Multiple fields or expressions are specified as a comma-separated list. By default, a search response includes all return enabled fields (<code>_all_fields</code>). To return only the document IDs for the matching documents, specify <code>_no_fields</code>. To retrieve the relevance score calculated for each document, specify <code>_score</code>. </p>
-- * cursor [Cursor] <p>Retrieves a cursor value you can use to page through large result sets. Use the <code>size</code> parameter to control the number of hits to include in each response. You can specify either the <code>cursor</code> or <code>start</code> parameter in a request; they are mutually exclusive. To get the first cursor, set the cursor value to <code>initial</code>. In subsequent requests, specify the cursor value returned in the hits section of the response. </p> <p>For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/paginating-results.html">Paginating Results</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
-- * start [Start] <p>Specifies the offset of the first search hit you want to return. Note that the result set is zero-based; the first result is at index 0. You can specify either the <code>start</code> or <code>cursor</code> parameter in a request, they are mutually exclusive. </p> <p>For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/paginating-results.html">Paginating Results</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
-- * queryOptions [QueryOptions] <p>Configures options for the query parser specified in the <code>queryParser</code> parameter. You specify the options in JSON using the following form <code>{"OPTION1":"VALUE1","OPTION2":VALUE2"..."OPTIONN":"VALUEN"}.</code></p> <p>The options you can configure vary according to which parser you use:</p> <ul> <li><code>defaultOperator</code>: The default operator used to combine individual terms in the search string. For example: <code>defaultOperator: 'or'</code>. For the <code>dismax</code> parser, you specify a percentage that represents the percentage of terms in the search string (rounded down) that must match, rather than a default operator. A value of <code>0%</code> is the equivalent to OR, and a value of <code>100%</code> is equivalent to AND. The percentage must be specified as a value in the range 0-100 followed by the percent (%) symbol. For example, <code>defaultOperator: 50%</code>. Valid values: <code>and</code>, <code>or</code>, a percentage in the range 0%-100% (<code>dismax</code>). Default: <code>and</code> (<code>simple</code>, <code>structured</code>, <code>lucene</code>) or <code>100</code> (<code>dismax</code>). Valid for: <code>simple</code>, <code>structured</code>, <code>lucene</code>, and <code>dismax</code>.</li> <li><code>fields</code>: An array of the fields to search when no fields are specified in a search. If no fields are specified in a search and this option is not specified, all text and text-array fields are searched. You can specify a weight for each field to control the relative importance of each field when Amazon CloudSearch calculates relevance scores. To specify a field weight, append a caret (<code>^</code>) symbol and the weight to the field name. For example, to boost the importance of the <code>title</code> field over the <code>description</code> field you could specify: <code>"fields":["title^5","description"]</code>. Valid values: The name of any configured field and an optional numeric value greater than zero. Default: All <code>text</code> and <code>text-array</code> fields. Valid for: <code>simple</code>, <code>structured</code>, <code>lucene</code>, and <code>dismax</code>.</li> <li><code>operators</code>: An array of the operators or special characters you want to disable for the simple query parser. If you disable the <code>and</code>, <code>or</code>, or <code>not</code> operators, the corresponding operators (<code>+</code>, <code>|</code>, <code>-</code>) have no special meaning and are dropped from the search string. Similarly, disabling <code>prefix</code> disables the wildcard operator (<code>*</code>) and disabling <code>phrase</code> disables the ability to search for phrases by enclosing phrases in double quotes. Disabling precedence disables the ability to control order of precedence using parentheses. Disabling <code>near</code> disables the ability to use the ~ operator to perform a sloppy phrase search. Disabling the <code>fuzzy</code> operator disables the ability to use the ~ operator to perform a fuzzy search. <code>escape</code> disables the ability to use a backslash (<code>\</code>) to escape special characters within the search string. Disabling whitespace is an advanced option that prevents the parser from tokenizing on whitespace, which can be useful for Vietnamese. (It prevents Vietnamese words from being split incorrectly.) For example, you could disable all operators other than the phrase operator to support just simple term and phrase queries: <code>"operators":["and","not","or", "prefix"]</code>. Valid values: <code>and</code>, <code>escape</code>, <code>fuzzy</code>, <code>near</code>, <code>not</code>, <code>or</code>, <code>phrase</code>, <code>precedence</code>, <code>prefix</code>, <code>whitespace</code>. Default: All operators and special characters are enabled. Valid for: <code>simple</code>.</li> <li><code>phraseFields</code>: An array of the <code>text</code> or <code>text-array</code> fields you want to use for phrase searches. When the terms in the search string appear in close proximity within a field, the field scores higher. You can specify a weight for each field to boost that score. The <code>phraseSlop</code> option controls how much the matches can deviate from the search string and still be boosted. To specify a field weight, append a caret (<code>^</code>) symbol and the weight to the field name. For example, to boost phrase matches in the <code>title</code> field over the <code>abstract</code> field, you could specify: <code>"phraseFields":["title^3", "plot"]</code> Valid values: The name of any <code>text</code> or <code>text-array</code> field and an optional numeric value greater than zero. Default: No fields. If you don't specify any fields with <code>phraseFields</code>, proximity scoring is disabled even if <code>phraseSlop</code> is specified. Valid for: <code>dismax</code>.</li> <li><code>phraseSlop</code>: An integer value that specifies how much matches can deviate from the search phrase and still be boosted according to the weights specified in the <code>phraseFields</code> option; for example, <code>phraseSlop: 2</code>. You must also specify <code>phraseFields</code> to enable proximity scoring. Valid values: positive integers. Default: 0. Valid for: <code>dismax</code>.</li> <li><code>explicitPhraseSlop</code>: An integer value that specifies how much a match can deviate from the search phrase when the phrase is enclosed in double quotes in the search string. (Phrases that exceed this proximity distance are not considered a match.) For example, to specify a slop of three for dismax phrase queries, you would specify <code>"explicitPhraseSlop":3</code>. Valid values: positive integers. Default: 0. Valid for: <code>dismax</code>.</li> <li><code>tieBreaker</code>: When a term in the search string is found in a document's field, a score is calculated for that field based on how common the word is in that field compared to other documents. If the term occurs in multiple fields within a document, by default only the highest scoring field contributes to the document's overall score. You can specify a <code>tieBreaker</code> value to enable the matches in lower-scoring fields to contribute to the document's score. That way, if two documents have the same max field score for a particular term, the score for the document that has matches in more fields will be higher. The formula for calculating the score with a tieBreaker is <code>(max field score) + (tieBreaker) * (sum of the scores for the rest of the matching fields)</code>. Set <code>tieBreaker</code> to 0 to disregard all but the highest scoring field (pure max): <code>"tieBreaker":0</code>. Set to 1 to sum the scores from all fields (pure sum): <code>"tieBreaker":1</code>. Valid values: 0.0 to 1.0. Default: 0.0. Valid for: <code>dismax</code>. </li> </ul>
-- * query [Query] <p>Specifies the search criteria for the request. How you specify the search criteria depends on the query parser used for the request and the parser options specified in the <code>queryOptions</code> parameter. By default, the <code>simple</code> query parser is used to process requests. To use the <code>structured</code>, <code>lucene</code>, or <code>dismax</code> query parser, you must also specify the <code>queryParser</code> parameter. </p> <p>For more information about specifying search criteria, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/searching.html">Searching Your Data</a> in the <i>Amazon CloudSearch Developer Guide</i>.</p>
-- * highlight [Highlight] <p>Retrieves highlights for matches in the specified <code>text</code> or <code>text-array</code> fields. Each specified field must be highlight enabled in the domain configuration. The fields and options are specified in JSON using the form <code>{"FIELD":{"OPTION":VALUE,"OPTION:"STRING"},"FIELD":{"OPTION":VALUE,"OPTION":"STRING"}}</code>.</p> <p>You can specify the following highlight options:</p> <ul> <li> <code>format</code>: specifies the format of the data in the text field: <code>text</code> or <code>html</code>. When data is returned as HTML, all non-alphanumeric characters are encoded. The default is <code>html</code>. </li> <li> <code>max_phrases</code>: specifies the maximum number of occurrences of the search term(s) you want to highlight. By default, the first occurrence is highlighted. </li> <li> <code>pre_tag</code>: specifies the string to prepend to an occurrence of a search term. The default for HTML highlights is <code>&lt;em&gt;</code>. The default for text highlights is <code>*</code>. </li> <li> <code>post_tag</code>: specifies the string to append to an occurrence of a search term. The default for HTML highlights is <code>&lt;/em&gt;</code>. The default for text highlights is <code>*</code>. </li> </ul> <p>If no highlight options are specified for a field, the returned field text is treated as HTML and the first match is highlighted with emphasis tags: <code>&lt;em>search-term&lt;/em&gt;</code>.</p> <p>For example, the following request retrieves highlights for the <code>actors</code> and <code>title</code> fields.</p> <p> <code>{ "actors": {}, "title": {"format": "text","max_phrases": 2,"pre_tag": "<b>","post_tag": "</b>"} }</code></p>
-- * queryParser [QueryParser] <p>Specifies which query parser to use to process the request. If <code>queryParser</code> is not specified, Amazon CloudSearch uses the <code>simple</code> query parser. </p> <p>Amazon CloudSearch supports four query parsers:</p> <ul> <li> <code>simple</code>: perform simple searches of <code>text</code> and <code>text-array</code> fields. By default, the <code>simple</code> query parser searches all <code>text</code> and <code>text-array</code> fields. You can specify which fields to search by with the <code>queryOptions</code> parameter. If you prefix a search term with a plus sign (+) documents must contain the term to be considered a match. (This is the default, unless you configure the default operator with the <code>queryOptions</code> parameter.) You can use the <code>-</code> (NOT), <code>|</code> (OR), and <code>*</code> (wildcard) operators to exclude particular terms, find results that match any of the specified terms, or search for a prefix. To search for a phrase rather than individual terms, enclose the phrase in double quotes. For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/searching-text.html">Searching for Text</a> in the <i>Amazon CloudSearch Developer Guide</i>. </li> <li> <code>structured</code>: perform advanced searches by combining multiple expressions to define the search criteria. You can also search within particular fields, search for values and ranges of values, and use advanced options such as term boosting, <code>matchall</code>, and <code>near</code>. For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/searching-compound-queries.html">Constructing Compound Queries</a> in the <i>Amazon CloudSearch Developer Guide</i>. </li> <li> <code>lucene</code>: search using the Apache Lucene query parser syntax. For more information, see <a href="http://lucene.apache.org/core/4_6_0/queryparser/org/apache/lucene/queryparser/classic/package-summary.html#package_description">Apache Lucene Query Parser Syntax</a>. </li> <li> <code>dismax</code>: search using the simplified subset of the Apache Lucene query parser syntax defined by the DisMax query parser. For more information, see <a href="http://wiki.apache.org/solr/DisMaxQParserPlugin#Query_Syntax">DisMax Query Parser Syntax</a>. </li> </ul>
-- * size [Size] <p>Specifies the maximum number of search hits to include in the response. </p>
-- Required key: query
-- @return SearchRequest structure as a key-value pair table
function M.SearchRequest(args)
assert(args, "You must provide an argument table when creating SearchRequest")
local query_args = {
["sort"] = args["sort"],
["facet"] = args["facet"],
["stats"] = args["stats"],
["partial"] = args["partial"],
["fq"] = args["filterQuery"],
["expr"] = args["expr"],
["return"] = args["return"],
["cursor"] = args["cursor"],
["start"] = args["start"],
["q.options"] = args["queryOptions"],
["q"] = args["query"],
["highlight"] = args["highlight"],
["q.parser"] = args["queryParser"],
["size"] = args["size"],
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["sort"] = args["sort"],
["facet"] = args["facet"],
["stats"] = args["stats"],
["partial"] = args["partial"],
["filterQuery"] = args["filterQuery"],
["expr"] = args["expr"],
["return"] = args["return"],
["cursor"] = args["cursor"],
["start"] = args["start"],
["queryOptions"] = args["queryOptions"],
["query"] = args["query"],
["highlight"] = args["highlight"],
["queryParser"] = args["queryParser"],
["size"] = args["size"],
}
asserts.AssertSearchRequest(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.SuggestionMatch = { ["score"] = true, ["id"] = true, ["suggestion"] = true, nil }
function asserts.AssertSuggestionMatch(struct)
assert(struct)
assert(type(struct) == "table", "Expected SuggestionMatch to be of type 'table'")
if struct["score"] then asserts.AssertLong(struct["score"]) end
if struct["id"] then asserts.AssertString(struct["id"]) end
if struct["suggestion"] then asserts.AssertString(struct["suggestion"]) end
for k,_ in pairs(struct) do
assert(keys.SuggestionMatch[k], "SuggestionMatch contains unknown key " .. tostring(k))
end
end
--- Create a structure of type SuggestionMatch
-- <p>An autocomplete suggestion that matches the query string specified in a <code>SuggestRequest</code>. </p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * score [Long] <p>The relevance score of a suggested match.</p>
-- * id [String] <p>The document ID of the suggested document.</p>
-- * suggestion [String] <p>The string that matches the query string specified in the <code>SuggestRequest</code>. </p>
-- @return SuggestionMatch structure as a key-value pair table
function M.SuggestionMatch(args)
assert(args, "You must provide an argument table when creating SuggestionMatch")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["score"] = args["score"],
["id"] = args["id"],
["suggestion"] = args["suggestion"],
}
asserts.AssertSuggestionMatch(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.SuggestModel = { ["query"] = true, ["suggestions"] = true, ["found"] = true, nil }
function asserts.AssertSuggestModel(struct)
assert(struct)
assert(type(struct) == "table", "Expected SuggestModel to be of type 'table'")
if struct["query"] then asserts.AssertString(struct["query"]) end
if struct["suggestions"] then asserts.AssertSuggestions(struct["suggestions"]) end
if struct["found"] then asserts.AssertLong(struct["found"]) end
for k,_ in pairs(struct) do
assert(keys.SuggestModel[k], "SuggestModel contains unknown key " .. tostring(k))
end
end
--- Create a structure of type SuggestModel
-- <p>Container for the suggestion information returned in a <code>SuggestResponse</code>.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * query [String] <p>The query string specified in the suggest request.</p>
-- * suggestions [Suggestions] <p>The documents that match the query string.</p>
-- * found [Long] <p>The number of documents that were found to match the query string.</p>
-- @return SuggestModel structure as a key-value pair table
function M.SuggestModel(args)
assert(args, "You must provide an argument table when creating SuggestModel")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["query"] = args["query"],
["suggestions"] = args["suggestions"],
["found"] = args["found"],
}
asserts.AssertSuggestModel(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
function asserts.AssertExpr(str)
assert(str)
assert(type(str) == "string", "Expected Expr to be of type 'string'")
end
--
function M.Expr(str)
asserts.AssertExpr(str)
return str
end
function asserts.AssertSort(str)
assert(str)
assert(type(str) == "string", "Expected Sort to be of type 'string'")
end
--
function M.Sort(str)
asserts.AssertSort(str)
return str
end
function asserts.AssertFilterQuery(str)
assert(str)
assert(type(str) == "string", "Expected FilterQuery to be of type 'string'")
end
--
function M.FilterQuery(str)
asserts.AssertFilterQuery(str)
return str
end
function asserts.AssertStat(str)
assert(str)
assert(type(str) == "string", "Expected Stat to be of type 'string'")
end
--
function M.Stat(str)
asserts.AssertStat(str)
return str
end
function asserts.AssertString(str)
assert(str)
assert(type(str) == "string", "Expected String to be of type 'string'")
end
--
function M.String(str)
asserts.AssertString(str)
return str
end
function asserts.AssertReturn(str)
assert(str)
assert(type(str) == "string", "Expected Return to be of type 'string'")
end
--
function M.Return(str)
asserts.AssertReturn(str)
return str
end
function asserts.AssertCursor(str)
assert(str)
assert(type(str) == "string", "Expected Cursor to be of type 'string'")
end
--
function M.Cursor(str)
asserts.AssertCursor(str)
return str
end
function asserts.AssertQueryOptions(str)
assert(str)
assert(type(str) == "string", "Expected QueryOptions to be of type 'string'")
end
--
function M.QueryOptions(str)
asserts.AssertQueryOptions(str)
return str
end
function asserts.AssertSuggester(str)
assert(str)
assert(type(str) == "string", "Expected Suggester to be of type 'string'")
end
--
function M.Suggester(str)
asserts.AssertSuggester(str)
return str
end
function asserts.AssertHighlight(str)
assert(str)
assert(type(str) == "string", "Expected Highlight to be of type 'string'")
end
--
function M.Highlight(str)
asserts.AssertHighlight(str)
return str
end
function asserts.AssertFacet(str)
assert(str)
assert(type(str) == "string", "Expected Facet to be of type 'string'")
end
--
function M.Facet(str)
asserts.AssertFacet(str)
return str
end
function asserts.AssertContentType(str)
assert(str)
assert(type(str) == "string", "Expected ContentType to be of type 'string'")
end
--
function M.ContentType(str)
asserts.AssertContentType(str)
return str
end
function asserts.AssertQuery(str)
assert(str)
assert(type(str) == "string", "Expected Query to be of type 'string'")
end
--
function M.Query(str)
asserts.AssertQuery(str)
return str
end
function asserts.AssertQueryParser(str)
assert(str)
assert(type(str) == "string", "Expected QueryParser to be of type 'string'")
end
--
function M.QueryParser(str)
asserts.AssertQueryParser(str)
return str
end
function asserts.AssertDouble(double)
assert(double)
assert(type(double) == "number", "Expected Double to be of type 'number'")
end
function M.Double(double)
asserts.AssertDouble(double)
return double
end
function asserts.AssertAdds(long)
assert(long)
assert(type(long) == "number", "Expected Adds to be of type 'number'")
assert(long % 1 == 0, "Expected a whole integer number")
end
function M.Adds(long)
asserts.AssertAdds(long)
return long
end
function asserts.AssertLong(long)
assert(long)
assert(type(long) == "number", "Expected Long to be of type 'number'")
assert(long % 1 == 0, "Expected a whole integer number")
end
function M.Long(long)
asserts.AssertLong(long)
return long
end
function asserts.AssertStart(long)
assert(long)
assert(type(long) == "number", "Expected Start to be of type 'number'")
assert(long % 1 == 0, "Expected a whole integer number")
end
function M.Start(long)
asserts.AssertStart(long)
return long
end
function asserts.AssertDeletes(long)
assert(long)
assert(type(long) == "number", "Expected Deletes to be of type 'number'")
assert(long % 1 == 0, "Expected a whole integer number")
end
function M.Deletes(long)
asserts.AssertDeletes(long)
return long
end
function asserts.AssertSuggestionsSize(long)
assert(long)
assert(type(long) == "number", "Expected SuggestionsSize to be of type 'number'")
assert(long % 1 == 0, "Expected a whole integer number")
end
function M.SuggestionsSize(long)
asserts.AssertSuggestionsSize(long)
return long
end
function asserts.AssertSize(long)
assert(long)
assert(type(long) == "number", "Expected Size to be of type 'number'")
assert(long % 1 == 0, "Expected a whole integer number")
end
function M.Size(long)
asserts.AssertSize(long)
return long
end
function asserts.AssertPartial(boolean)
assert(boolean)
assert(type(boolean) == "boolean", "Expected Partial to be of type 'boolean'")
end
function M.Partial(boolean)
asserts.AssertPartial(boolean)
return boolean
end
function asserts.AssertHighlights(map)
assert(map)
assert(type(map) == "table", "Expected Highlights to be of type 'table'")
for k,v in pairs(map) do
asserts.AssertString(k)
asserts.AssertString(v)
end
end
function M.Highlights(map)
asserts.AssertHighlights(map)
return map
end
function asserts.AssertStats(map)
assert(map)
assert(type(map) == "table", "Expected Stats to be of type 'table'")
for k,v in pairs(map) do
asserts.AssertString(k)
asserts.AssertFieldStats(v)
end
end
function M.Stats(map)
asserts.AssertStats(map)
return map
end
function asserts.AssertFields(map)
assert(map)
assert(type(map) == "table", "Expected Fields to be of type 'table'")
for k,v in pairs(map) do
asserts.AssertString(k)
asserts.AssertFieldValue(v)
end
end
function M.Fields(map)
asserts.AssertFields(map)
return map
end
function asserts.AssertFacets(map)
assert(map)
assert(type(map) == "table", "Expected Facets to be of type 'table'")
for k,v in pairs(map) do
asserts.AssertString(k)
asserts.AssertBucketInfo(v)
end
end
function M.Facets(map)
asserts.AssertFacets(map)
return map
end
function asserts.AssertExprs(map)
assert(map)
assert(type(map) == "table", "Expected Exprs to be of type 'table'")
for k,v in pairs(map) do
asserts.AssertString(k)
asserts.AssertString(v)
end
end
function M.Exprs(map)
asserts.AssertExprs(map)
return map
end
function asserts.AssertBlob(blob)
assert(blob)
assert(type(blob) == "string", "Expected Blob to be of type 'string'")
end
function M.Blob(blob)
asserts.AssertBlob(blob)
return blob
end
function asserts.AssertDocumentServiceWarnings(list)
assert(list)
assert(type(list) == "table", "Expected DocumentServiceWarnings to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertDocumentServiceWarning(v)
end
end
--
-- List of DocumentServiceWarning objects
function M.DocumentServiceWarnings(list)
asserts.AssertDocumentServiceWarnings(list)
return list
end
function asserts.AssertFieldValue(list)
assert(list)
assert(type(list) == "table", "Expected FieldValue to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertString(v)
end
end
--
-- List of String objects
function M.FieldValue(list)
asserts.AssertFieldValue(list)
return list
end
function asserts.AssertHitList(list)
assert(list)
assert(type(list) == "table", "Expected HitList to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertHit(v)
end
end
--
-- List of Hit objects
function M.HitList(list)
asserts.AssertHitList(list)
return list
end
function asserts.AssertSuggestions(list)
assert(list)
assert(type(list) == "table", "Expected Suggestions to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertSuggestionMatch(v)
end
end
--
-- List of SuggestionMatch objects
function M.Suggestions(list)
asserts.AssertSuggestions(list)
return list
end
function asserts.AssertBucketList(list)
assert(list)
assert(type(list) == "table", "Expected BucketList to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertBucket(v)
end
end
--
-- List of Bucket objects
function M.BucketList(list)
asserts.AssertBucketList(list)
return list
end
local content_type = require "aws-sdk.core.content_type"
local request_headers = require "aws-sdk.core.request_headers"
local request_handlers = require "aws-sdk.core.request_handlers"
local settings = {}
local function endpoint_for_region(region, use_dualstack)
if not use_dualstack then
if region == "us-east-1" then
return "cloudsearchdomain.amazonaws.com"
end
end
local ss = { "cloudsearchdomain" }
if use_dualstack then
ss[#ss + 1] = "dualstack"
end
ss[#ss + 1] = region
ss[#ss + 1] = "amazonaws.com"
if region == "cn-north-1" then
ss[#ss + 1] = "cn"
end
return table.concat(ss, ".")
end
function M.init(config)
assert(config, "You must provide a config table")
assert(config.region, "You must provide a region in the config table")
settings.service = M.metadata.endpoint_prefix
settings.protocol = M.metadata.protocol
settings.region = config.region
settings.endpoint = config.endpoint_override or endpoint_for_region(config.region, config.use_dualstack)
settings.signature_version = M.metadata.signature_version
settings.uri = (config.scheme or "https") .. "://" .. settings.endpoint
end
--
-- OPERATIONS
--
--- Call Suggest asynchronously, invoking a callback when done
-- @param SuggestRequest
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.SuggestAsync(SuggestRequest, cb)
assert(SuggestRequest, "You must provide a SuggestRequest")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".Suggest",
}
for header,value in pairs(SuggestRequest.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("rest-json", "GET")
if request_handler then
request_handler(settings.uri, "/2013-01-01/suggest?format=sdk&pretty=true", SuggestRequest, headers, settings, cb)
else
cb(false, err)
end
end
--- Call Suggest synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param SuggestRequest
-- @return response
-- @return error_type
-- @return error_message
function M.SuggestSync(SuggestRequest, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.SuggestAsync(SuggestRequest, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call Search asynchronously, invoking a callback when done
-- @param SearchRequest
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.SearchAsync(SearchRequest, cb)
assert(SearchRequest, "You must provide a SearchRequest")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".Search",
}
for header,value in pairs(SearchRequest.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("rest-json", "GET")
if request_handler then
request_handler(settings.uri, "/2013-01-01/search?format=sdk&pretty=true", SearchRequest, headers, settings, cb)
else
cb(false, err)
end
end
--- Call Search synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param SearchRequest
-- @return response
-- @return error_type
-- @return error_message
function M.SearchSync(SearchRequest, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.SearchAsync(SearchRequest, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call UploadDocuments asynchronously, invoking a callback when done
-- @param UploadDocumentsRequest
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.UploadDocumentsAsync(UploadDocumentsRequest, cb)
assert(UploadDocumentsRequest, "You must provide a UploadDocumentsRequest")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".UploadDocuments",
}
for header,value in pairs(UploadDocumentsRequest.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("rest-json", "POST")
if request_handler then
request_handler(settings.uri, "/2013-01-01/documents/batch?format=sdk", UploadDocumentsRequest, headers, settings, cb)
else
cb(false, err)
end
end
--- Call UploadDocuments synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param UploadDocumentsRequest
-- @return response
-- @return error_type
-- @return error_message
function M.UploadDocumentsSync(UploadDocumentsRequest, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.UploadDocumentsAsync(UploadDocumentsRequest, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
return M
|
local function checkLength( value )
return value and #value >= 0 and #value <= 165
end
local allowedImageHosts = {
["imgur.com"] = true,
["hizliresim.com"] = true,
["resimag.com"] = true,
}
local imageExtensions = {
[".jpg"] = true,
[".jpeg"] = true,
[".png"] = true,
[".gif"] = true,
}
function verifyImageURL(url, notEmpty)
if not notEmpty then
if not url or url == "" then
return true
end
end
if string.find(url, "http://", 1, true) or string.find(url, "https://", 1, true) then
local domain = url:match("[%w%.]*%.(%w+%.%w+)") or url:match("^%w+://([^/]+)")
if allowedImageHosts[domain] then
local _extensions = ""
for extension, _ in pairs(imageExtensions) do
if _extensions ~= "" then
_extensions = _extensions..", "..extension
else
_extensions = extension
end
if string.find(url, extension, 1, true) then
return true
end
end
end
end
return false
end
editables = {
{ name = "Kilo", index = "weight", verify = function( v ) return tonumber( v ) and tonumber( v ) >= 30 and tonumber( v ) <= 200 end, instructions = "Enter weight in kg, between 30 and 200." },
{ name = "Boy", index = "height", verify = function( v ) return tonumber( v ) and tonumber( v ) >= 70 and tonumber( v ) <= 220 end, instructions = "Enter height in cm, between 70 and 220." },
{ name = "Saç Rengi", index = 1, verify = checkLength },
{ name = "Saç Stili", index = 2, verify = checkLength },
{ name = "Yüz Hatları", index = 3, verify = checkLength },
{ name = "Fiziksel Özellikler", index = 4, verify = checkLength },
{ name = "Kıyafet", index = 5, verify = checkLength },
{ name = "Aksesuar", index = 6, verify = checkLength },
{ name = "Fotoğraf", index = 7, verify = verifyImageURL, instructions = "Karakterinize göre bir avatar linki girin. ( İzin verilen resim adresi: resimag.com )" }
} |
--[[
ThemePrefsRows: you give it the choices, values, and params, and it'll
generate the rest; quirky behavior to be outlined below. Documentation
will be provided once this system is stabilized.
v0.5.2: Dec. 28, 2010. Throw an error for default/value type mismatches.
v0.5.1: Dec. 27, 2010. Fix Choices not necessarily being strings.
v0.5.0: Dec. 15, 2010. Initial version. Not very well tested.
vyhd wrote this for sm-ssc
--]]
-- unless overridden, these parameters will be used for the OptionsRow
local DefaultParams = {
LayoutType = "ShowAllInRow",
SelectType = "SelectOne",
OneChoiceForAllPlayers = true,
ExportOnChange = false,
EnabledForPlayers = nil,
ReloadRowMessages = nil,
-- takes a function(self, list, pn);
-- if not used, we use the default
LoadSelections = nil,
SaveSelections = nil
}
-- local alias to simplify error reporting
local function GetString(name)
return THEME:GetString("ThemePrefsRows", name)
end
local function DefaultLoad(pref, default, choices, values)
return function(self, list, pn)
local val = ThemePrefs.Get(pref)
-- if our current value is here, set focus to that
for i = 1, #choices do
if values[i] == val then
list[i] = true
return
end
end
-- try the default value
for i = 1, #choices do
if values[i] == default then
list[i] = true
return
end
end
-- set to the first value and output a warning
Warn(GetString("NoDefaultInValues"):format(pref))
list[1] = true
end
end
local function DefaultSave(pref, choices, values)
local msg = "ThemePrefChanged"
local params = {Name = pref}
return function(self, list, pn)
for i = 1, #choices do
if list[i] then
ThemePrefs.Set(pref, values[i])
MESSAGEMAN:Broadcast(msg, params)
break
end
end
end
end
-- This function checks for mismatches between the default value and the
-- values table passed to the ThemePrefRow, e.g. it will return false if
-- you have a boolean default and an integer value. I'm somewhat stricter
-- about types than Lua is because I don't like the unpredictability and
-- complexity of coercing values transparently in a bunch of places.
local function TypesMatch(Values, Default)
local DefaultType = type(Default)
for i, value in ipairs(Values) do
local ValueType = type(value)
if ValueType ~= DefaultType then
Warn(GetString("TypeMismatch"):format(DefaultType, i, ValueType))
return false
end
end
return true
end
local function CreateThemePrefRow(pref, tbl)
-- can't make an option handler without options
if not tbl.Choices then
return nil
end
local Choices = tbl.Choices
local Default = tbl.Default
local Values = tbl.Values and tbl.Values or Choices
local Params = tbl.Params and tbl.Params or {}
-- if the choices aren't strings, make them strings now
for i, str in ipairs(Choices) do
Choices[i] = tostring(Choices[i])
end
-- check to see that Values and Choices have the same length
if #Choices ~= #Values then
Warn(GetString("ChoicesSizeMismatch"))
return nil
end
-- check to see that everything in Values matches the type of Default
if not TypesMatch(Values, Default) then
return nil
end
-- set the name and choices here; we'll do the rest below
local Handler = {Name = pref, Choices = Choices}
-- add all the keys in DefaultParams, get the value from
-- Params if it exists and DefaultParams otherwise
-- (note that we explicitly check for nil, due to bools.)
for k, _ in pairs(DefaultParams) do
Handler[k] = Params[k] ~= nil and Params[k] or DefaultParams[k]
end
-- if we don't have LoadSelections and SaveSelections, make them
if not Handler.LoadSelections then
Handler.LoadSelections = DefaultLoad(pref, Default, Choices, Values)
end
if not Handler.SaveSelections then
Handler.SaveSelections = DefaultSave(pref, Choices, Values)
end
return Handler
end
-- All OptionsRows for preferences are stuck in this table, accessible
-- through GetRow('name') in the namespace or ThemePrefRow('name') in
-- the global namespace. (I like to keep pollution to a minimum.)
local Rows = {}
ThemePrefsRows = {
IsInitted = false,
Init = function(prefs)
for pref, tbl in pairs(prefs) do
Rows[pref] = CreateThemePrefRow(pref, tbl)
end
end,
GetRow = function(pref)
Trace(("GetRow(%s), type %s"):format(pref, type(Rows[pref])))
return Rows[pref]
end
}
-- Global namespace alias
ThemePrefRow = ThemePrefsRows.GetRow
-- UGLY: declare this here, even though it's in the previous namespace,
-- so we can have one call to initialize both systems (ThemePrefsRow is
-- declared after ThemePrefs, so it can't actually be in that file...)
ThemePrefs.InitAll = function(prefs)
Trace("ThemePrefs.InitAll( prefs )")
ThemePrefs.Init(prefs, true)
ThemePrefsRows.Init(prefs)
end
|
local cc = require("classcommons2")
return assert(cc.instance)
|
dofile "build/setup.lua"
require "luci.lucid".start()
|
local event = {}
_OSENV.event = {
timers = {}
}
local function updateTimers()
for k, timer in pairs(_OSENV.event.timers) do
if computer.uptime() >= timer.started + timer.time then
timer.callback()
if timer.type == "after" then
table.remove(_OSENV.event.timers, k)
elseif timer.type == "every" then
timer.started = computer.uptime()
end
end
end
end
function event.after(time, callback)
table.insert(_OSENV.event.timers, {
type = "after",
started = computer.uptime(),
time = time,
callback = callback
})
end
function event.every(time, callback)
table.insert(_OSENV.event.timers, {
type = "every",
started = computer.uptime(),
time = time,
callback = callback
})
end
function event.pull(timeout, filter)
local timeout = timeout or math.huge
local deadline = computer.uptime() + timeout
repeat
local closestTimer = math.huge
for _, timer in pairs(_OSENV.event.timers) do
closestTimer = math.min(closestTimer, timer.started + timer.time)
end
local realDeadline = math.min(deadline, closestTimer)
local signal = { computer.pullSignal(realDeadline - computer.uptime()) }
updateTimers()
if not filter then
return signal
else
for _, v in pairs(filter) do
if v == signal[1] then
return signal
end
end
end
until computer.uptime() > deadline
end
return event |
local Nonogram = require("core.module.model.Nonogram");
local function GameModel()
local model = {};
model.selection_sector = nil;
model.base_nonogram = nil;
model.trace_nonogram = nil;
function model:init(nonogram_data)
self.base_nonogram = Nonogram(nonogram_data);
self.trace_nonogram = Nonogram(nonogram_data);
self.trace_nonogram:forEach(function(sector, row, col)
self.trace_nonogram[row][col] = Nonogram.Sector.Empty;
end);
end
function model:getSelectionSector()
return self.selection_sector or Nonogram.Sector.Filled;
end
function model:setSelectionSector(sector)
self.selection_sector = sector;
end
function model:getBaseNonogram()
return self.base_nonogram;
end
function model:getTraceNonogram()
return self.trace_nonogram;
end
function model:getSector(row, col)
return self.trace_nonogram[row][col];
end
function model:setSector(row, col, sector)
self.trace_nonogram[row][col] = sector;
end
return model;
end
return GameModel; |
-- Abstract: InMobi plugin
-- Version: 1.0
-- Sample code is MIT licensed; see https://www.coronalabs.com/links/code/license
---------------------------------------------------------------------------------------
local widget = require( "widget" )
local inMobi = require( "plugin.inMobi" )
local json = require("json")
display.setStatusBar( display.HiddenStatusBar )
local isAndroid = system.getInfo("platformName") == "Android"
local androidPlacementIds =
{
{unitType = "banner", pid = "1478286408914"}, -- Banner
{unitType = "interstitial", pid = "1480743237023"}, -- Interstitial (Static + Video)
{unitType = "interstitial", pid = "1481289791433"}, -- Rewarded Video
}
local iOSPlacementIds =
{
{unitType = "banner", pid = "1479357133568"}, -- Banner
{unitType = "interstitial", pid = "1479986687313"}, -- Interstitial (Static + Video)
{unitType = "interstitial", pid = "1481821101745"}, -- Rewarded Video
}
local placementIds = isAndroid and androidPlacementIds or iOSPlacementIds
local currentPlacementId = 1
-- Create the background
local background = display.newImageRect("back-whiteorange.png", display.actualContentWidth, display.actualContentHeight)
background.x = display.contentCenterX
background.y = display.contentCenterY
-- Create a text object to show the Lua listener events on screen
local statusText = display.newText(
{
text = "",
font = native.systemFontBold,
fontSize = 16,
align = "left",
width = 320,
height = 200,
})
statusText:setFillColor(0)
statusText.anchorX = 0
statusText.anchorY = 0
statusText.y = display.screenOriginY + 10
local processEventTable = function(event)
local logString = json.prettify(event):gsub("\\","")
logString = "\nPHASE: "..event.phase.." - - - - - - - - - - - -\n" .. logString
print(logString)
return logString
end
local function inMobiListener( event )
statusText.text = processEventTable(event)
end
-- Init the inMobi plugin
inMobi.init(inMobiListener, {
accountId = "652651ebf1c94d619de9a69476396f5a", -- Ingemar
logLevel = "debug",
hasUserConsent = true
})
-- Set the user interests
inMobi.setUserDetails(
{
gender = {"male"},
userInterests = {"Business", "Tech"},
phoneAreaCode = "353",
postCode = "xxx1",
language = "eng",
birthYear = 1986,
age = 30,
ageGroup = "18to24",
education = "collegeOrGraduate",
ethnicity = "caucasian",
})
-- Create a button
local changePidButton = widget.newButton(
{
id = "changePid",
label = "Change PID",
width = 250,
onRelease = function(event)
currentPlacementId = currentPlacementId + 1
if currentPlacementId > #placementIds then
currentPlacementId = 1
end
statusText.text = string.format("Ad type: %s\nPID: %s", placementIds[currentPlacementId].unitType, placementIds[currentPlacementId].pid)
end,
})
changePidButton.x = display.contentCenterX
changePidButton.y = statusText.y + (statusText.height) + 10
local screenOffsetX = (display.actualContentWidth - display.contentWidth) / 2
-- Create a button
local loadAdButton = widget.newButton(
{
label = "Load Ad",
onRelease = function(event)
inMobi.load(placementIds[currentPlacementId].unitType, placementIds[currentPlacementId].pid, {width = display.actualContentWidth, height = 50, autoRefresh = false, refreshInterval = 120})
end,
})
loadAdButton.x = display.contentCenterX
loadAdButton.y = changePidButton.y + changePidButton.height + loadAdButton.height * .15
-- Create a button
local showAdButton = widget.newButton(
{
label = "Show Ad",
onRelease = function(event)
inMobi.show(placementIds[currentPlacementId].pid, { yAlign = "top" })
end,
})
showAdButton.x = display.contentCenterX
showAdButton.y = loadAdButton.y + loadAdButton.height + showAdButton.height * .15
-- Create a button
local hideAdButton = widget.newButton(
{
label = "Hide Ad",
onRelease = function(event)
inMobi.hide(placementIds[currentPlacementId].pid)
end,
})
hideAdButton.x = display.contentCenterX
hideAdButton.y = showAdButton.y + showAdButton.height + hideAdButton.height * .15
|
return (function (modules, ...)
local _G = _G
local error = _G.error
local setfenv = _G.setfenv
local setmetatable = _G.setmetatable
local moduleCache = {}
local packageGlobals = {}
local function makeEnvironment(moduleChunk)
local exports = {}
local moduleEnvironment = setmetatable({}, {
__index = function (self, key)
if exports[key] ~= nil then
return exports[key]
end
return _G[key]
end,
__newindex = exports
})
return setfenv(moduleChunk, moduleEnvironment), exports
end
local function makeModuleHeader(moduleName)
return {
name = moduleName,
globals = packageGlobals
}
end
local function makeReadOnly(tbl)
return setmetatable({}, {
__index = tbl,
__newindex = function (self, key, value) error("module 'exports' table is read only") end
})
end
local import = nil
function import(moduleName, ...)
local moduleChunk = modules[moduleName]
if not moduleChunk then error("bad argument #1 to 'import' (invalid module, got '"..moduleName.."')") end
if not moduleCache[moduleName] then
local moduleHeader = makeModuleHeader(moduleName)
local moduleEnvironment, exports = makeEnvironment(moduleChunk)
moduleEnvironment(moduleHeader, exports, import, import, ...)
moduleCache[moduleName] = makeReadOnly(exports)
end
return moduleCache[moduleName]
end
local loadstring = _G.loadstring
for moduleName, assetChunk in pairs(modules) do
modules[moduleName] = loadstring('return function (module, exports, import, dependency, ...) '..assetChunk..' end', moduleName)()
end
return import('novacbn/gmodproj/main', ...)
end)({['davidm/globtopattern/main'] = "_TYPE = 'module'\
_NAME = 'globtopattern'\
_VERSION = '0.2.1.20120406'\
\
function globtopattern(g)\
-- Some useful references:\
-- - apr_fnmatch in Apache APR. For example,\
-- http://apr.apache.org/docs/apr/1.3/group__apr__fnmatch.html\
-- which cites POSIX 1003.2-1992, section B.6.\
\
local p = \"^\" -- pattern being built\
local i = 0 -- index in g\
local c -- char at index i in g.\
\
-- unescape glob char\
local function unescape()\
if c == '\\\\' then\
i = i + 1; c = g:sub(i,i)\
if c == '' then\
p = '[^]'\
return false\
end\
end\
return true\
end\
\
-- escape pattern char\
local function escape(c)\
return c:match(\"^%w$\") and c or '%' .. c\
end\
\
-- Convert tokens at end of charset.\
local function charset_end()\
while 1 do\
if c == '' then\
p = '[^]'\
return false\
elseif c == ']' then\
p = p .. ']'\
break\
else\
if not unescape() then break end\
local c1 = c\
i = i + 1; c = g:sub(i,i)\
if c == '' then\
p = '[^]'\
return false\
elseif c == '-' then\
i = i + 1; c = g:sub(i,i)\
if c == '' then\
p = '[^]'\
return false\
elseif c == ']' then\
p = p .. escape(c1) .. '%-]'\
break\
else\
if not unescape() then break end\
p = p .. escape(c1) .. '-' .. escape(c)\
end\
elseif c == ']' then\
p = p .. escape(c1) .. ']'\
break\
else\
p = p .. escape(c1)\
i = i - 1 -- put back\
end\
end\
i = i + 1; c = g:sub(i,i)\
end\
return true\
end\
\
-- Convert tokens in charset.\
local function charset()\
i = i + 1; c = g:sub(i,i)\
if c == '' or c == ']' then\
p = '[^]'\
return false\
elseif c == '^' or c == '!' then\
i = i + 1; c = g:sub(i,i)\
if c == ']' then\
-- ignored\
else\
p = p .. '[^'\
if not charset_end() then return false end\
end\
else\
p = p .. '['\
if not charset_end() then return false end\
end\
return true\
end\
\
-- Convert tokens.\
while 1 do\
i = i + 1; c = g:sub(i,i)\
if c == '' then\
p = p .. '$'\
break\
elseif c == '?' then\
p = p .. '.'\
elseif c == '*' then\
p = p .. '.*'\
elseif c == '[' then\
if not charset() then break end\
elseif c == '\\\\' then\
i = i + 1; c = g:sub(i,i)\
if c == '' then\
p = p .. '\\\\$'\
break\
end\
p = p .. escape(c)\
else\
p = p .. escape(c)\
end\
end\
return p\
end",
['novacbn/gmodproj/Packager'] = "local unpack\
unpack = _G.unpack\
local match\
match = string.match\
local insert, sort\
do\
local _obj_0 = table\
insert, sort = _obj_0.insert, _obj_0.sort\
end\
local writeFileSync\
writeFileSync = require(\"fs\").writeFileSync\
local globtopattern\
globtopattern = dependency(\"davidm/globtopattern/main\").globtopattern\
local mapi\
mapi = dependency(\"novacbn/novautils/table\").mapi\
local Set\
Set = dependency(\"novacbn/novautils/collections/Set\").Set\
local WriteBuffer\
WriteBuffer = dependency(\"novacbn/novautils/io/WriteBuffer\").WriteBuffer\
local Default, Object\
do\
local _obj_0 = dependency(\"novacbn/novautils/utilities/Object\")\
Default, Object = _obj_0.Default, _obj_0.Object\
end\
local logInfo, logFatal\
do\
local _obj_0 = dependency(\"novacbn/gmodproj/lib/logging\")\
logInfo, logFatal = _obj_0.logInfo, _obj_0.logFatal\
end\
local PackagerOptions\
PackagerOptions = dependency(\"novacbn/gmodproj/schemas/PackagerOptions\").PackagerOptions\
Packager = Object:extend({\
canCache = false,\
excludedAssets = nil,\
flags = nil,\
isProduction = nil,\
loadedAssets = Default({ }),\
registeredPlatforms = Default({ }),\
resolver = nil,\
targetPlatform = nil,\
constructor = function(self, isProduction, flags, resolver, pluginManager, options)\
self.isProduction, self.resolver = isProduction, resolver\
options = PackagerOptions:new(options)\
self.includedAssets = mapi(options:get(\"includedAssets\"), function(i, v)\
return globtopattern(v)\
end)\
self.excludedAssets = mapi(options:get(\"excludedAssets\"), function(i, v)\
return globtopattern(v)\
end)\
self.canCache = not (flags[\"-nc\"] or flags[\"--no-cache\"])\
pluginManager:dispatchEvent(\"registerPlatforms\", self)\
local targetPlatform = self.registeredPlatforms[options:get(\"targetPlatform\")]\
if not (targetPlatform) then\
logFatal(\"cannot target platform '\" .. tostring(targetPlatform) .. \"'\")\
end\
self.targetPlatform = targetPlatform:new(isProduction)\
end,\
collectDependencies = function(self, defaultAssets)\
local collectedDependencies = Set:fromTable(defaultAssets)\
local excludedAssets = self.excludedAssets\
local assetType, assetPath, loadedAsset, excludedAsset\
for assetName in collectedDependencies:iter() do\
if not (self.loadedAssets[assetName]) then\
assetType, assetPath = self.resolver:resolveAsset(assetName)\
if not (assetType) then\
logFatal(\"asset '\" .. tostring(assetName) .. \"' could not be resolved\")\
end\
self.loadedAssets[assetName] = assetType:new(assetName, assetPath, self.canCache, self.isProduction)\
end\
loadedAsset = self.loadedAssets[assetName]\
loadedAsset:generateAsset()\
local _list_0 = loadedAsset.assetData:get(\"dependencies\")\
for _index_0 = 1, #_list_0 do\
local assetName = _list_0[_index_0]\
excludedAsset = false\
for _index_1 = 1, #excludedAssets do\
local assetPattern = excludedAssets[_index_1]\
if match(assetName, assetPattern) then\
excludedAsset = true\
break\
end\
end\
if not (excludedAsset) then\
collectedDependencies:push(assetName)\
end\
end\
end\
collectedDependencies = collectedDependencies:values()\
sort(collectedDependencies)\
return collectedDependencies\
end,\
registerPlatform = function(self, platformName, platform)\
self.registeredPlatforms[platformName] = platform\
end,\
writePackage = function(self, entryPoint, endPoint)\
local defaultAssets = {\
entryPoint\
}\
if #self.includedAssets > 0 then\
local _list_0 = self.resolver:resolveAssets()\
for _index_0 = 1, #_list_0 do\
local assetName = _list_0[_index_0]\
local _list_1 = self.includedAssets\
for _index_1 = 1, #_list_1 do\
local assetPattern = _list_1[_index_1]\
if match(assetName, assetPattern) then\
insert(defaultAssets, assetName)\
end\
end\
end\
end\
local buffer = WriteBuffer:new()\
buffer:writeString(self.targetPlatform:generatePackageHeader(entryPoint))\
local loadedAsset\
local _list_0 = self:collectDependencies(defaultAssets)\
for _index_0 = 1, #_list_0 do\
local assetName = _list_0[_index_0]\
loadedAsset = self.loadedAssets[assetName]\
buffer:writeString(self.targetPlatform:generatePackageModule(assetName, loadedAsset.assetData:get(\"output\")))\
end\
buffer:writeString(self.targetPlatform:generatePackageFooter())\
local contents = self.targetPlatform:transformPackage(buffer:toString())\
return writeFileSync(endPoint, contents)\
end\
})",
['novacbn/gmodproj/PluginManager'] = "local loadstring, pairs, pcall\
do\
local _obj_0 = _G\
loadstring, pairs, pcall = _obj_0.loadstring, _obj_0.pairs, _obj_0.pcall\
end\
local readFileSync\
readFileSync = require(\"fs\").readFileSync\
local join\
join = require(\"path\").join\
local Default, Object\
do\
local _obj_0 = dependency(\"novacbn/novautils/utilities/Object\")\
Default, Object = _obj_0.Default, _obj_0.Object\
end\
local APPLICATION_CORE_VERSION, PROJECT_PATH, USER_PATH\
do\
local _obj_0 = dependency(\"novacbn/gmodproj/lib/constants\")\
APPLICATION_CORE_VERSION, PROJECT_PATH, USER_PATH = _obj_0.APPLICATION_CORE_VERSION, _obj_0.PROJECT_PATH, _obj_0.USER_PATH\
end\
local logFatal\
logFatal = dependency(\"novacbn/gmodproj/lib/logging\").logFatal\
local isFile\
isFile = dependency(\"novacbn/gmodproj/lib/utilities/fs\").isFile\
local loadPlugin\
loadPlugin = function(pluginName)\
local pluginPath = join(PROJECT_PATH.plugins, pluginName) .. \".lua\"\
if isFile(pluginPath) then\
local contents = readFileSync(pluginPath)\
local pluginChunk, err = loadstring(contents, \"project-plugin:\" .. pluginName)\
if pluginChunk then\
return pluginChunk(), nil\
end\
return nil, err\
end\
pluginPath = join(USER_PATH.plugins, pluginName) .. \".lua\"\
if isFile(pluginPath) then\
local contents = readFileSync(pluginPath)\
local pluginChunk, err = loadstring(contents, \"user-plugin:\" .. pluginName)\
if pluginChunk then\
return pluginChunk(), nil\
end\
return nil, err\
end\
local success, exports = pcall(require, \"plugins/\" .. pluginName)\
if success then\
return exports, nil\
end\
return nil, exports\
end\
PluginManager = Object:extend({\
loadedPlugins = Default({ }),\
constructor = function(self, pluginMap)\
local pluginExports, pluginError\
for pluginName, pluginOptions in pairs(pluginMap) do\
pluginExports, pluginError = loadPlugin(pluginName)\
if not (pluginExports) then\
logFatal(\"plugin '\" .. tostring(pluginName) .. \"' could not be loaded:\\n\" .. tostring(pluginError))\
end\
self.loadedPlugins[pluginName] = pluginExports.Plugin:new(pluginOptions)\
end\
end,\
dispatchEvent = function(self, eventName, ...)\
for pluginName, pluginObject in pairs(self.loadedPlugins) do\
pluginObject[eventName](pluginObject, ...)\
end\
end\
})\
_G.gmodproj = {\
api = {\
Asset = dependency(\"novacbn/gmodproj/api/Asset\").Asset,\
DataAsset = dependency(\"novacbn/gmodproj/api/DataAsset\").DataAsset,\
Platform = dependency(\"novacbn/gmodproj/api/Platform\").Platform,\
Plugin = dependency(\"novacbn/gmodproj/api/Plugin\").Plugin,\
ResourceAsset = dependency(\"novacbn/gmodproj/api/ResourceAsset\").ResourceAsset,\
Schema = dependency(\"novacbn/gmodproj/api/Schema\").Schema,\
Template = dependency(\"novacbn/gmodproj/api/Template\").Template\
},\
require = dependency,\
version = APPLICATION_CORE_VERSION\
}",
['novacbn/gmodproj/Resolver'] = "local unpack\
unpack = _G.unpack\
local match\
match = string.match\
local insert\
insert = table.insert\
local readdirSync\
readdirSync = require(\"fs\").readdirSync\
local basename, dirname, extname, join\
do\
local _obj_0 = require(\"path\")\
basename, dirname, extname, join = _obj_0.basename, _obj_0.dirname, _obj_0.extname, _obj_0.join\
end\
local Set\
Set = dependency(\"novacbn/novautils/collections/Set\").Set\
local Default, Object\
do\
local _obj_0 = dependency(\"novacbn/novautils/utilities/Object\")\
Default, Object = _obj_0.Default, _obj_0.Object\
end\
local ResolverOptions\
ResolverOptions = dependency(\"novacbn/gmodproj/schemas/ResolverOptions\").ResolverOptions\
local PROJECT_PATH\
PROJECT_PATH = dependency(\"novacbn/gmodproj/lib/constants\").PROJECT_PATH\
local isFile\
isFile = dependency(\"novacbn/gmodproj/lib/utilities/fs\").isFile\
local makeStringEscape\
makeStringEscape = dependency(\"novacbn/gmodproj/lib/utilities/string\").makeStringEscape\
local escapePattern = makeStringEscape({\
{\
\"%-\",\
\"%%-\"\
}\
})\
local collectFiles\
collectFiles = function(baseDirectory, files, subDirectory)\
if files == nil then\
files = { }\
end\
local currentDirectory = subDirectory and join(baseDirectory, subDirectory) or baseDirectory\
local _list_0 = readdirSync(currentDirectory)\
for _index_0 = 1, #_list_0 do\
local fileName = _list_0[_index_0]\
if isFile(join(currentDirectory, fileName)) then\
insert(files, subDirectory and subDirectory .. \"/\" .. fileName or fileName)\
else\
collectFiles(baseDirectory, files, subDirectory and subDirectory .. \"/\" .. fileName or fileName)\
end\
end\
return files\
end\
Resolver = Object:extend({\
registeredAssets = Default({ }),\
projectPattern = nil,\
sourceDirectory = nil,\
constructor = function(self, projectAuthor, projectName, sourceDirectory, pluginManager, options)\
self.options = ResolverOptions:new(options)\
pluginManager:dispatchEvent(\"registerAssets\", self)\
self.projectPrefix = tostring(projectAuthor) .. \"/\" .. tostring(projectName)\
self.sourceDirectory = join(PROJECT_PATH.home, sourceDirectory)\
end,\
resolveAsset = function(self, assetName)\
local projectAsset = match(assetName, \"^\" .. tostring(escapePattern(self.projectPrefix)) .. \"/([%w/%-]+)\")\
if projectAsset then\
local assetPath\
for assetExtension, assetType in pairs(self.registeredAssets) do\
assetPath = join(self.sourceDirectory, tostring(projectAsset) .. \".\" .. tostring(assetExtension))\
if isFile(assetPath) then\
return assetType, assetPath\
end\
end\
end\
local assetFile, assetPath\
local searchPaths = self.options:get(\"searchPaths\")\
for assetExtension, assetType in pairs(self.registeredAssets) do\
assetFile = tostring(assetName) .. \".\" .. tostring(assetExtension)\
for _index_0 = 1, #searchPaths do\
local searchPath = searchPaths[_index_0]\
assetPath = join(searchPath, assetFile)\
if isFile(assetPath) then\
return assetType, assetPath\
end\
end\
end\
return nil, nil\
end,\
resolveAssets = function(self)\
local resolvedAssets = Set:new()\
local directoryName\
local _list_0 = collectFiles(self.sourceDirectory)\
for _index_0 = 1, #_list_0 do\
local fileName = _list_0[_index_0]\
for assetExtension, assetType in pairs(self.registeredAssets) do\
if extname(fileName) == \".\" .. assetExtension then\
directoryName = dirname(fileName)\
resolvedAssets:push(self.projectPrefix .. \"/\" .. (directoryName and directoryName .. \"/\" .. basename(fileName, \".\" .. assetExtension) or basename(fileName, \".\" .. assetExtension)))\
end\
end\
end\
local searchPaths = self.options:get(\"searchPaths\")\
for _index_0 = 1, #searchPaths do\
local searchPath = searchPaths[_index_0]\
local _list_1 = collectFiles(searchPath)\
for _index_1 = 1, #_list_1 do\
local fileName = _list_1[_index_1]\
for assetExtension, assetType in pairs(self.registeredAssets) do\
if extname(fileName) == \".\" .. assetExtension then\
directoryName = dirname(fileName)\
resolvedAssets:push(directoryName and directoryName .. \"/\" .. basename(fileName, \".\" .. assetExtension) or basename(fileName, \".\" .. assetExtension))\
end\
end\
end\
end\
return resolvedAssets:values()\
end,\
registerAsset = function(self, assetExtension, assetType)\
self.registeredAssets[assetExtension] = assetType\
end\
})",
['novacbn/gmodproj/api/Asset'] = "local pcall\
pcall = _G.pcall\
local readFileSync, statSync, writeFileSync\
do\
local _obj_0 = require(\"fs\")\
readFileSync, statSync, writeFileSync = _obj_0.readFileSync, _obj_0.statSync, _obj_0.writeFileSync\
end\
local join\
join = require(\"path\").join\
local decode, encode\
do\
local _obj_0 = dependency(\"rxi/json/main\")\
decode, encode = _obj_0.decode, _obj_0.encode\
end\
local Object\
Object = dependency(\"novacbn/novautils/utilities/Object\").Object\
local PROJECT_PATH\
PROJECT_PATH = dependency(\"novacbn/gmodproj/lib/constants\").PROJECT_PATH\
local hashSHA1\
hashSHA1 = dependency(\"novacbn/gmodproj/lib/utilities/openssl\").hashSHA1\
local logInfo, logWarn\
do\
local _obj_0 = dependency(\"novacbn/gmodproj/lib/logging\")\
logInfo, logWarn = _obj_0.logInfo, _obj_0.logWarn\
end\
local isFile\
isFile = dependency(\"novacbn/gmodproj/lib/utilities/fs\").isFile\
local AssetData\
AssetData = dependency(\"novacbn/gmodproj/schemas/AssetData\").AssetData\
Asset = Object:extend({\
assetData = nil,\
assetName = nil,\
assetPath = nil,\
cachePath = nil,\
canCache = nil,\
isCacheable = true,\
isProduction = nil,\
constructor = function(self, assetName, assetPath, canCache, isProduction)\
self.assetName, self.assetPath, self.canCache, self.isProduction = assetName, assetPath, canCache, isProduction\
self.cachePath = join(PROJECT_PATH.cache, hashSHA1(self.assetName))\
end,\
generateAsset = function(self)\
if not (self.assetData) then\
if self.isCacheable and self.canCache and isFile(self.cachePath) then\
local assetData = decode(readFileSync(self.cachePath))\
local success\
success, assetData = pcall(AssetData.new, AssetData, assetData)\
if success then\
self.assetData = assetData\
else\
logWarn(\"Cache of asset '\" .. tostring(self.assetName) .. \"' could not be processed, regenerating asset...\")\
end\
end\
if not (self.assetData) then\
self.assetData = AssetData:new()\
end\
end\
local modificationTime = statSync(self.assetPath).mtime.sec\
if self.assetPath == self.assetData:get(\"metadata.path\") and self.assetData:get(\"metadata.mtime\") == modificationTime then\
return \
end\
local contents = readFileSync(self.assetPath)\
contents = self:preTransform(contents)\
local collectedDependencies = self:collectDependencies(contents)\
local collectDocumentation = self:collectDocumentation(contents)\
contents = self:postTransform(contents)\
self.assetData = AssetData:new({\
metadata = {\
name = self.assetName,\
mtime = modificationTime,\
path = self.assetPath\
},\
dependencies = collectedDependencies,\
exports = collectedDocumentation,\
output = contents\
})\
if self.isCacheable and self.canCache then\
writeFileSync(self.cachePath, encode(self.assetData.options))\
end\
return logInfo(\"\\t...regenerated asset '\" .. tostring(self.assetName) .. \"'\")\
end,\
collectDependencies = function(self, contents)\
return { }\
end,\
collectDocumentation = function(self, contents)\
return { }\
end,\
preTransform = function(self, contents)\
return contents\
end,\
postTransform = function(self, contents)\
return contents\
end\
})",
['novacbn/gmodproj/api/DataAsset'] = "local basename\
basename = require(\"path\").basename\
local block\
block = dependency(\"pkulchenko/serpent/main\").block\
local Asset\
Asset = dependency(\"novacbn/gmodproj/api/Asset\").Asset\
local TEMPLATE_MODULE_LUA\
TEMPLATE_MODULE_LUA = function(assetName, luaTable)\
return \"exports['\" .. tostring(basename(assetName)) .. \"'] = \" .. tostring(luaTable)\
end\
DataAsset = Asset:extend({\
postTransform = function(self, contents)\
local luaTable = block(contents, {\
comment = false\
})\
return TEMPLATE_MODULE_LUA(self.assetName, luaTable)\
end\
})",
['novacbn/gmodproj/api/Platform'] = "local Object\
Object = dependency(\"novacbn/novautils/utilities/Object\").Object\
Platform = Object:extend({\
isProduction = nil,\
constructor = function(self, isProduction)\
self.isProduction = isProduction\
end,\
generatePackageHeader = function(self, entryPoint)\
return \"\"\
end,\
generatePackageModule = function(self, assetName, assetChunk)\
return error(\"bad dispatch to 'generatePackageModule' (method not implemented)\")\
end,\
generatePackageFooter = function(self)\
return \"\"\
end,\
transformPackage = function(self, packageContents)\
return packageContents\
end\
})",
['novacbn/gmodproj/api/Plugin'] = "local Object\
Object = dependency(\"novacbn/novautils/utilities/Object\").Object\
Plugin = Object:extend({\
schema = nil,\
constructor = function(self, options)\
if self.schema then\
self.schema.namespace = \"Plugins['\" .. self.schema.namespace .. \"']\"\
self.options = self.schema:new(options)\
end\
end,\
registerAssets = function(self, resolver) end,\
registerTemplates = function(self, application) end,\
registerPlatforms = function(self, packager) end\
})",
['novacbn/gmodproj/api/ResourceAsset'] = "local basename\
basename = require(\"path\").basename\
local Asset\
Asset = dependency(\"novacbn/gmodproj/api/Asset\").Asset\
local toByteString\
toByteString = dependency(\"novacbn/gmodproj/lib/utilities/string\").toByteString\
local TEMPLATE_MODULE_LUA\
TEMPLATE_MODULE_LUA = function(assetName, byteString)\
return \"local byteTable = \" .. tostring(byteString) .. \"\\nlocal string_char = string.char\\nlocal table_concat = table.concat\\n\\nfor index, byte in ipairs(byteTable) do\\n byteTable[index] = string_char(byte)\\nend\\n\\nexports['\" .. tostring(basename(assetName)) .. \"'] = table_concat(byteTable, '')\"\
end\
ResourceAsset = Asset:extend({\
postTransform = function(self, contents)\
return TEMPLATE_MODULE_LUA(self.assetName, toByteString(contents))\
end\
})",
['novacbn/gmodproj/api/Schema'] = "local pairs\
pairs = _G.pairs\
local gsub, upper\
do\
local _obj_0 = string\
gsub, upper = _obj_0.gsub, _obj_0.upper\
end\
local concat, insert\
do\
local _obj_0 = table\
concat, insert = _obj_0.concat, _obj_0.insert\
end\
local livr = require(\"LIVR/Validator\")\
local deepMerge\
deepMerge = dependency(\"novacbn/novautils/table\").deepMerge\
local Object\
Object = dependency(\"novacbn/novautils/utilities/Object\").Object\
local LIVR_ERROR_LOOKUP = {\
NOT_ARRAY = \"expected array of values\",\
NOT_STRING = \"expected string value\",\
NOT_BOOLEAN = \"expected boolean value\",\
MINIMUM_ITEMS = \"expected a number of minimum array items\",\
WRONG_FORMAT = \"option did not match pattern\"\
}\
local LIVR_UTILITY_RULES = {\
is_key_pairs = function(self, keyCheck, valueCheck)\
local keyValidator = self:is(keyCheck)\
local valueValidator = self:is(valueCheck)\
return function(tbl)\
local err\
for key, value in pairs(tbl) do\
local _\
_, err = keyValidator(key)\
if err then\
return nil, err\
end\
_, err = valueValidator(value)\
if err then\
return nil, err\
end\
end\
return tbl\
end\
end,\
is = function(self, check)\
if type(check) == \"table\" then\
local err = \"NOT_\" .. tostring(upper(check[1]))\
return function(value)\
local valueType = type(value)\
for _index_0 = 1, #check do\
local ruleType = check[_index_0]\
if valueType == ruleType then\
return value\
end\
end\
return nil, err\
end\
else\
local err = \"NOT_\" .. tostring(upper(check))\
return function(value)\
if type(value) == check then\
return value\
end\
return nil, err\
end\
end\
end,\
min_items = function(self, amount)\
return function(value)\
if not (type(value) == \"table\") then\
return nil, \"NOT_ARRAY\"\
end\
if not (#value >= amount) then\
return nil, \"MINIMUM_ITEMS\"\
end\
return value\
end\
end\
}\
livr.register_default_rules(LIVR_UTILITY_RULES)\
local PATTERN_PATH_EXTRACT = \"[^%.]+\"\
local formatOptionsError\
formatOptionsError = function(namespace, errors, stringBuffer)\
local originatingCall = not stringBuffer and true or false\
if originatingCall then\
stringBuffer = { }\
end\
for optionName, errorID in pairs(errors) do\
local _exp_0 = type(errorID)\
if \"string\" == _exp_0 then\
insert(stringBuffer, \"bad option '\" .. tostring(optionName) .. \"' to '\" .. tostring(namespace) .. \"' (\" .. tostring(LIVR_ERROR_LOOKUP[errorID] or errorID) .. \")\")\
else\
if namespace and #namespace > 0 then\
formatOptionsError(tostring(namespace) .. \".\" .. tostring(optionName), errorID, stringBuffer)\
else\
formatOptionsError(optionName, errorID, stringBuffer)\
end\
end\
end\
if originatingCall then\
return concat(stringBuffer, \"\\n\")\
end\
end\
Schema = Object:extend({\
default = nil,\
namespace = nil,\
options = nil,\
schema = nil,\
constructor = function(self, options)\
if options == nil then\
options = { }\
end\
if self.default then\
deepMerge(options, self.default)\
end\
local validator = livr.new(self.schema)\
local errors\
options, errors = validator:validate(options)\
if errors then\
error(formatOptionsError(self.namespace, errors))\
end\
self.options = options\
end,\
get = function(self, dotPath)\
local value = self.options\
gsub(dotPath, PATTERN_PATH_EXTRACT, function(pathElement)\
if not (type(value) == \"table\") then\
error(\"bad argument #1 to 'get' (key '\" .. tostring(pathElement) .. \"' of '\" .. tostring(dotPath) .. \"' is not a table)\")\
end\
value = value[pathElement]\
end)\
return value\
end\
})",
['novacbn/gmodproj/api/Template'] = "local dirname, join\
do\
local _obj_0 = require(\"path\")\
dirname, join = _obj_0.dirname, _obj_0.join\
end\
local existsSync, mkdirSync, writeFileSync\
do\
local _obj_0 = require(\"fs\")\
existsSync, mkdirSync, writeFileSync = _obj_0.existsSync, _obj_0.mkdirSync, _obj_0.writeFileSync\
end\
local Object\
Object = dependency(\"novacbn/novautils/utilities/Object\").Object\
local json = dependency(\"rxi/json/main\")\
local properties = dependency(\"novacbn/properties/exports\")\
local isDir\
isDir = dependency(\"novacbn/gmodproj/lib/utilities/fs\").isDir\
Template = Object:extend({\
projectAuthor = nil,\
projectName = nil,\
projectPath = nil,\
constructor = function(self, projectPath, projectAuthor, projectName)\
self.projectPath, self.projectAuthor, self.projectName = projectPath, projectAuthor, projectName\
end,\
createDirectory = function(self, directoryPath)\
directoryPath = join(self.projectPath, directoryPath)\
if existsSync(directoryPath) then\
error(\"bad argument #1 to 'createDirectory' (path already exists)\")\
end\
if not (isDir(dirname(directoryPath))) then\
error(\"bad argument #1 to 'createDirectory' (parent directory does not exist)\")\
end\
return mkdirSync(directoryPath)\
end,\
write = function(self, filePath, fileContents)\
filePath = join(self.projectPath, filePath)\
if not (isDir(dirname(filePath))) then\
error(\"bad argument #1 to 'write' (parent directory does not exist)\")\
end\
return writeFileSync(filePath, fileContents)\
end,\
writeProperties = function(self, filePath, sourceTable)\
return self:write(filePath, properties.encode(sourceTable, {\
propertiesEncoder = \"moonscript\"\
}))\
end,\
writeJSON = function(self, filePath, sourceTable)\
return self:write(filePath, json.encode(sourceTable))\
end,\
createProject = function(self, ...) end\
})",
['novacbn/gmodproj/commands/bin'] = "local loadfile, print, type\
do\
local _obj_0 = _G\
loadfile, print, type = _obj_0.loadfile, _obj_0.print, _obj_0.type\
end\
local process\
process = _G.process\
local readFileSync\
readFileSync = require(\"fs\").readFileSync\
local join\
join = require(\"path\").join\
local moonscript = require(\"moonscript/base\")\
local ENV_ALLOW_UNSAFE_SCRIPTING, PROJECT_PATH, SYSTEM_OS_TYPE, SYSTEM_UNIX_LIKE\
do\
local _obj_0 = dependency(\"novacbn/gmodproj/lib/constants\")\
ENV_ALLOW_UNSAFE_SCRIPTING, PROJECT_PATH, SYSTEM_OS_TYPE, SYSTEM_UNIX_LIKE = _obj_0.ENV_ALLOW_UNSAFE_SCRIPTING, _obj_0.PROJECT_PATH, _obj_0.SYSTEM_OS_TYPE, _obj_0.SYSTEM_UNIX_LIKE\
end\
local logError, logFatal, logInfo\
do\
local _obj_0 = dependency(\"novacbn/gmodproj/lib/logging\")\
logError, logFatal, logInfo = _obj_0.logError, _obj_0.logFatal, _obj_0.logInfo\
end\
local ScriptingEnvironment\
ScriptingEnvironment = dependency(\"novacbn/gmodproj/lib/ScriptingEnvironment\").ScriptingEnvironment\
local configureEnvironment, readManifest\
do\
local _obj_0 = dependency(\"novacbn/gmodproj/lib/utilities\")\
configureEnvironment, readManifest = _obj_0.configureEnvironment, _obj_0.readManifest\
end\
local execFormat, isFile\
do\
local _obj_0 = dependency(\"novacbn/gmodproj/lib/utilities/fs\")\
execFormat, isFile = _obj_0.execFormat, _obj_0.isFile\
end\
local TEMPLATE_EXECUTION_SUCCESS\
TEMPLATE_EXECUTION_SUCCESS = function(script, status)\
return \"Successfully executed '\" .. tostring(script) .. \"' (\" .. tostring(status) .. \")\"\
end\
local TEMPLATE_EXECUTION_ERROR\
TEMPLATE_EXECUTION_ERROR = function(script)\
return \"Unexpected error occured while executing '\" .. tostring(script) .. \"'\"\
end\
local TEMPLATE_EXECUTION_FAILED\
TEMPLATE_EXECUTION_FAILED = function(script, status)\
return \"Failed to execute '\" .. tostring(script) .. \"' (\" .. tostring(status) .. \")\"\
end\
local TEMPLATE_EXECUTION_SYNTAX\
TEMPLATE_EXECUTION_SYNTAX = function(script)\
return \"Script '\" .. tostring(script) .. \"' had a syntax error\"\
end\
local resolveScript\
resolveScript = function(script)\
local scriptPath = join(PROJECT_PATH.bin, script)\
if isFile(scriptPath .. \".moon\") then\
return function()\
return moonscript.loadfile(scriptPath .. \".moon\")\
end\
elseif isFile(scriptPath .. \".lua\") then\
return function()\
return loadfile(scriptPath .. \".lua\")\
end\
elseif SYSTEM_UNIX_LIKE and isFile(scriptPath .. \".sh\") then\
return nil, function(...)\
return execFormat(\"/usr/bin/env\", \"sh\", scriptPath .. \".sh\", ...)\
end\
elseif SYSTEM_OS_TYPE == \"Windows\" and isFile(scriptPath .. \".bat\") then\
return nil, function(...)\
return execFormat(\"cmd.exe\", scriptPath .. \".bat\", ...)\
end\
end\
end\
formatDescription = function(flags)\
return \"bin <script>\\t\\t\\t\\tExecutes a utility script located in your project's 'bin' directory\"\
end\
executeCommand = function(flags, script, ...)\
configureEnvironment()\
local scriptLoader, shellLoader = resolveScript(script)\
if scriptLoader then\
local scriptChunk, err = scriptLoader()\
if err then\
logError(err)\
logFatal(TEMPLATE_EXECUTION_SYNTAX(script))\
end\
local scriptingEnvironment = ScriptingEnvironment(PROJECT_PATH.home, ENV_ALLOW_UNSAFE_SCRIPTING)\
local success, status, stdout = scriptingEnvironment:executeChunk(scriptChunk, ...)\
if success then\
if status == 0 then\
return logInfo(stdout)\
else\
logError(stdout)\
return logFatal(TEMPLATE_EXECUTION_FAILED(script, status), {\
exit = status\
})\
end\
else\
logError(status)\
return logFatal(TEMPLATE_EXECUTION_ERROR(script), {\
exit = -1\
})\
end\
elseif shellLoader then\
if ENV_ALLOW_UNSAFE_SCRIPTING then\
local success, status, stdout = shellLoader(...)\
if success then\
print(stdout)\
return logInfo(TEMPLATE_EXECUTION_SUCCESS(script, status), {\
exit = status\
})\
else\
logError(stdout)\
return logFatal(TEMPLATE_EXECUTION_FAILED(script, status), {\
exit = status\
})\
end\
else\
return logFatal(\"Unsafe scripting disabled by user!\")\
end\
else\
return logFatal(\"Script '\" .. tostring(script) .. \"' not found!\")\
end\
end",
['novacbn/gmodproj/commands/build'] = "local lower\
lower = string.lower\
local join\
join = require(\"path\").join\
local Packager\
Packager = dependency(\"novacbn/gmodproj/Packager\").Packager\
local PluginManager\
PluginManager = dependency(\"novacbn/gmodproj/PluginManager\").PluginManager\
local Resolver\
Resolver = dependency(\"novacbn/gmodproj/Resolver\").Resolver\
local PROJECT_PATH\
PROJECT_PATH = dependency(\"novacbn/gmodproj/lib/constants\").PROJECT_PATH\
local ElapsedTimer\
ElapsedTimer = dependency(\"novacbn/gmodproj/lib/ElapsedTimer\").ElapsedTimer\
local logFatal, logInfo\
do\
local _obj_0 = dependency(\"novacbn/gmodproj/lib/logging\")\
logFatal, logInfo = _obj_0.logFatal, _obj_0.logInfo\
end\
local configureEnvironment, readManifest\
do\
local _obj_0 = dependency(\"novacbn/gmodproj/lib/utilities\")\
configureEnvironment, readManifest = _obj_0.configureEnvironment, _obj_0.readManifest\
end\
local isDir\
isDir = dependency(\"novacbn/gmodproj/lib/utilities/fs\").isDir\
formatDescription = function(flags)\
return \"build [mode]\\t\\t\\t\\tBuilds your project into distributable Lua files\\n\\t\\t\\t\\t\\t\\t\\t(DEFAULT) 'development', 'production'\"\
end\
executeCommand = function(flags, mode)\
if mode == nil then\
mode = \"development\"\
end\
configureEnvironment()\
local elapsedTimer = ElapsedTimer:new()\
local options = readManifest()\
local pluginManager = PluginManager:new(options:get(\"Plugins\"))\
local resolver = Resolver:new(options:get(\"author\"), options:get(\"name\"), options:get(\"sourceDirectory\"), pluginManager, options:get(\"Resolver\"))\
local packager = Packager:new(lower(mode) == \"production\", flags, resolver, pluginManager, options:get(\"Packager\"))\
local buildDirectory = join(PROJECT_PATH.home, options:get(\"buildDirectory\"))\
if not (isDir(buildDirectory)) then\
logFatal(\"Build directory does not exist!\")\
end\
for entryPoint, targetPackage in pairs(options:get(\"projectBuilds\")) do\
logInfo(\"Building entry point '\" .. tostring(entryPoint) .. \"'\")\
packager:writePackage(entryPoint, join(buildDirectory, targetPackage .. \".lua\"))\
end\
local elapsedTime = elapsedTimer:getFormattedElapsed()\
return logInfo(\"Build completed in \" .. tostring(elapsedTime) .. \"!\")\
end",
['novacbn/gmodproj/commands/new'] = "local pairs, type\
do\
local _obj_0 = _G\
pairs, type = _obj_0.pairs, _obj_0.type\
end\
local match\
match = string.match\
local concat, sort\
do\
local _obj_0 = table\
concat, sort = _obj_0.concat, _obj_0.sort\
end\
local existsSync, mkdirSync\
do\
local _obj_0 = require(\"fs\")\
existsSync, mkdirSync = _obj_0.existsSync, _obj_0.mkdirSync\
end\
local join\
join = require(\"path\").join\
local hasInherited\
hasInherited = dependency(\"novacbn/novautils/utilities/Object\").hasInherited\
local PluginManager\
PluginManager = dependency(\"novacbn/gmodproj/PluginManager\").PluginManager\
local Template\
Template = dependency(\"novacbn/gmodproj/api/Template\").Template\
local MAP_DEFAULT_PLUGINS, PROJECT_PATH\
do\
local _obj_0 = dependency(\"novacbn/gmodproj/lib/constants\")\
MAP_DEFAULT_PLUGINS, PROJECT_PATH = _obj_0.MAP_DEFAULT_PLUGINS, _obj_0.PROJECT_PATH\
end\
local logFatal, logInfo\
do\
local _obj_0 = dependency(\"novacbn/gmodproj/lib/logging\")\
logFatal, logInfo = _obj_0.logFatal, _obj_0.logInfo\
end\
local PATTERN_METADATA_NAME\
PATTERN_METADATA_NAME = dependency(\"novacbn/gmodproj/schemas/ProjectOptions\").PATTERN_METADATA_NAME\
local TemplateRegister\
TemplateRegister = function()\
return {\
registeredTemplates = { },\
registerTemplate = function(self, name, template)\
if not (type(name) == \"string\") then\
error(\"bad argument #1 to 'registerTemplate' (expected string value)\")\
end\
if self.registeredTemplates[name] then\
error(\"bad argument #1 to 'registerTemplate' (template name already registered)\")\
end\
if not (type(template) == \"table\" and hasInherited(Template, template)) then\
error(\"bad argument #2 to 'registerTemplate' (expected Template value)\")\
end\
self.registeredTemplates[name] = template\
end\
}\
end\
formatDescription = function(flags)\
local templateRegister = TemplateRegister()\
local pluginManager = PluginManager:new(MAP_DEFAULT_PLUGINS)\
pluginManager:dispatchEvent(\"registerTemplates\", templateRegister)\
local templateNames\
do\
local _accum_0 = { }\
local _len_0 = 1\
for templateName, template in pairs(templateRegister.registeredTemplates) do\
_accum_0[_len_0] = \"'\" .. templateName .. \"'\"\
_len_0 = _len_0 + 1\
end\
templateNames = _accum_0\
end\
sort(templateNames)\
templateNames = concat(templateNames, \", \")\
return \"new <template> <author> <name>\\t\\tCreates a new directory for your project via a template\\n\\t\\t\\t\\t\\t\\t\\t\" .. tostring(templateNames)\
end\
executeCommand = function(flags, templateName, author, name, ...)\
local templateRegister = TemplateRegister()\
local pluginManager = PluginManager:new(MAP_DEFAULT_PLUGINS)\
pluginManager:dispatchEvent(\"registerTemplates\", templateRegister)\
local template = templateRegister.registeredTemplates[templateName]\
if not (template) then\
logFatal(\"Invalid template '\" .. tostring(templateName) .. \"'!\")\
end\
if not (author and #author > 0 and match(author, PATTERN_METADATA_NAME)) then\
logFatal(\"Project author \" .. tostring(author) .. \" is invalid, must be lowercase alphanumeric and dashes only!\")\
end\
if not (name and #name > 0 and match(name, PATTERN_METADATA_NAME)) then\
logFatal(\"Project name \" .. tostring(name) .. \" is invalid, must be lowercase alphanumeric and dashes only!\")\
end\
local projectPath = join(PROJECT_PATH.home, name)\
if existsSync(projectPath) then\
logFatal(\"Path '\" .. tostring(name) .. \"' is already exists!\")\
end\
mkdirSync(projectPath)\
local loadedTemplate = template:new(projectPath, author, name)\
loadedTemplate:createProject(...)\
return logInfo(\"Successfully generated project at: \" .. tostring(projectPath))\
end",
['novacbn/gmodproj/commands/version'] = "local print\
print = _G.print\
local APPLICATION_CORE_VERSION\
APPLICATION_CORE_VERSION = dependency(\"novacbn/gmodproj/lib/constants\").APPLICATION_CORE_VERSION\
TEXT_COMMAND_VERSION = tostring(APPLICATION_CORE_VERSION[1]) .. \".\" .. tostring(APPLICATION_CORE_VERSION[2]) .. \".\" .. tostring(APPLICATION_CORE_VERSION[3]) .. \" Pre-alpha\"\
formatDescription = function(flags)\
return \"version\\t\\t\\t\\t\\tDisplays the version text of application\"\
end\
executeCommand = function(flags)\
return print(TEXT_COMMAND_VERSION)\
end",
['novacbn/gmodproj/lib/ElapsedTimer'] = "local format\
format = string.format\
local gettime\
gettime = require(\"gettime\").gettime\
local Object\
Object = dependency(\"novacbn/novautils/utilities/Object\").Object\
local getSeconds\
getSeconds = function()\
return gettime() / 1000\
end\
ElapsedTimer = Object:extend({\
startTime = 0,\
constructor = function(self)\
self.startTime = getSeconds()\
end,\
getElapsed = function(self)\
return getSeconds() - self.startTime\
end,\
getFormattedElapsed = function(self)\
return format(\"%.4fs\", getSeconds() - self.startTime)\
end\
})",
['novacbn/gmodproj/lib/ScriptingEnvironment'] = "local assert, error, ipairs, pcall, pairs, setfenv\
do\
local _obj_0 = _G\
assert, error, ipairs, pcall, pairs, setfenv = _obj_0.assert, _obj_0.error, _obj_0.ipairs, _obj_0.pcall, _obj_0.pairs, _obj_0.setfenv\
end\
local match\
match = string.match\
local existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync\
do\
local _obj_0 = require(\"fs\")\
existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync = _obj_0.existsSync, _obj_0.mkdirSync, _obj_0.readFileSync, _obj_0.writeFileSync, _obj_0.unlinkSync\
end\
local decode, encode\
do\
local _obj_0 = require(\"json\")\
decode, encode = _obj_0.decode, _obj_0.encode\
end\
local isAbsolute, join\
do\
local _obj_0 = require(\"path\")\
isAbsolute, join = _obj_0.isAbsolute, _obj_0.join\
end\
local merge\
merge = dependency(\"novacbn/novautils/table\").merge\
local SYSTEM_OS_ARCH, SYSTEM_OS_TYPE, SYSTEM_UNIX_LIKE\
do\
local _obj_0 = dependency(\"novacbn/gmodproj/lib/constants\")\
SYSTEM_OS_ARCH, SYSTEM_OS_TYPE, SYSTEM_UNIX_LIKE = _obj_0.SYSTEM_OS_ARCH, _obj_0.SYSTEM_OS_TYPE, _obj_0.SYSTEM_UNIX_LIKE\
end\
local fromString, toString\
do\
local _obj_0 = dependency(\"novacbn/gmodproj/lib/datafile\")\
fromString, toString = _obj_0.fromString, _obj_0.toString\
end\
local exec, execFormat, isDir, isFile\
do\
local _obj_0 = dependency(\"novacbn/gmodproj/lib/utilities/fs\")\
exec, execFormat, isDir, isFile = _obj_0.exec, _obj_0.execFormat, _obj_0.isDir, _obj_0.isFile\
end\
local assertx = dependency(\"novacbn/gmodproj/lib/utilities/assert\")\
local ChunkEnvironment\
ChunkEnvironment = function(environmentRoot, allowUnsafe)\
local getEnvironmentPath\
getEnvironmentPath = function(path)\
if not (isAbsolute(path) or match(path, \"%.%.\")) then\
return join(environmentRoot, path)\
end\
if allowUnsafe then\
return path\
end\
end\
local environmentTable\
environmentTable = {\
ENV_ALLOW_UNSAFE_SCRIPTING = allowUnsafe,\
SYSTEM_OS_ARCH = SYSTEM_OS_ARCH,\
SYSTEM_OS_TYPE = SYSTEM_OS_TYPE,\
SYSTEM_UNIX_LIKE = SYSTEM_UNIX_LIKE,\
assert = assert,\
error = error,\
exists = function(path)\
path = assertx.argument(getEnvironmentPath(path), 1, \"exists\", \"expected relative path, got '\" .. tostring(path) .. \"'\")\
local hasPath = existsSync(path)\
return hasPath\
end,\
isDir = function(path)\
path = assertx.argument(getEnvironmentPath(path), 1, \"isDir\", \"expected relative path, got '\" .. tostring(path) .. \"'\")\
return isDir(path)\
end,\
isFile = function(path)\
path = assertx.argument(getEnvironmentPath(path), 1, \"isFile\", \"expected relative path, got '\" .. tostring(path) .. \"'\")\
return isFile(path)\
end,\
ipairs = ipairs,\
mkdir = function(path)\
path = assertx.argument(getEnvironmentPath(path), 1, \"mkdir\", \"expected relative path, got '\" .. tostring(path) .. \"'\")\
local hasPath = existsSync(path)\
assertx.argument(not hasPath, 1, \"mkdir\", \"path '\" .. tostring(path) .. \"' already exists\")\
mkdirSync(path)\
return nil\
end,\
pcall = pcall,\
pairs = pairs,\
print = print,\
read = function(path)\
path = assertx.argument(getEnvironmentPath(path), 1, \"read\", \"expected relative path, got '\" .. tostring(path) .. \"'\")\
assertx.argument(isFile(path), 1, \"read\", \"file '\" .. tostring(path) .. \"' does not exist\")\
return readFileSync(path)\
end,\
readDataFile = function(path)\
return fromString(environmentTable.read(path))\
end,\
readJSON = function(path)\
return decode(environmentTable.read(path))\
end,\
remove = function(path)\
path = assertx.argument(getEnvironmentPath(path), 1, \"remove\", \"expected relative path, got '\" .. tostring(path) .. \"'\")\
if isDir(path) then\
rmdir(path)\
else\
unlinkSync(path)\
end\
return nil\
end,\
tostring = tostring,\
write = function(path, contents)\
path = assertx.argument(getEnvironmentPath(path), 1, \"write\", \"expected relative path, got '\" .. tostring(path) .. \"'\")\
writeFileSync(path, contents)\
return nil\
end,\
writeDataFile = function(path, tableData)\
return environmentTable.write(path, toString(tableData))\
end,\
writeJSON = function(path, tableData)\
return environmentTable.write(path, encode(tableData, {\
indent = true\
}))\
end\
}\
if allowUnsafe then\
merge(environmentTable, {\
dependency = dependency,\
require = require,\
exec = exec,\
execFormat = execFormat\
})\
end\
return setmetatable({ }, {\
__index = environmentTable\
})\
end\
do\
local _class_0\
local _base_0 = {\
allowUnsafe = nil,\
environmentRoot = nil,\
executeChunk = function(self, scriptChunk, ...)\
local environmentSandbox = ChunkEnvironment(self.environmentRoot, self.allowUnsafe)\
return pcall(setfenv(scriptChunk, environmentSandbox), ...)\
end\
}\
_base_0.__index = _base_0\
_class_0 = setmetatable({\
__init = function(self, environmentRoot, allowUnsafe)\
self.allowUnsafe = allowUnsafe\
self.environmentRoot = environmentRoot\
end,\
__base = _base_0,\
__name = \"ScriptingEnvironment\"\
}, {\
__index = _base_0,\
__call = function(cls, ...)\
local _self_0 = setmetatable({}, _base_0)\
cls.__init(_self_0, ...)\
return _self_0\
end\
})\
_base_0.__class = _class_0\
ScriptingEnvironment = _class_0\
end",
['novacbn/gmodproj/lib/constants'] = "local getenv\
getenv = os.getenv\
local arch, os\
do\
local _obj_0 = jit\
arch, os = _obj_0.arch, _obj_0.os\
end\
local join\
join = require(\"path\").join\
local isAffirmative\
isAffirmative = dependency(\"novacbn/gmodproj/lib/utilities/string\").isAffirmative\
local userHome\
local _exp_0 = os\
if \"Windows\" == _exp_0 then\
userHome = getenv(\"APPDATA\")\
elseif \"Linux\" == _exp_0 then\
userHome = getenv(\"HOME\")\
end\
APPLICATION_CORE_VERSION = {\
0,\
4,\
0\
}\
ENV_ALLOW_UNSAFE_SCRIPTING = isAffirmative(getenv(\"GMODPROJ_ALLOW_UNSAFE_SCRIPTING\") or \"y\")\
MAP_DEFAULT_PLUGINS = {\
[\"gmodproj-plugin-builtin\"] = { }\
}\
SYSTEM_OS_ARCH = arch\
SYSTEM_OS_TYPE = os\
SYSTEM_UNIX_LIKE = os == \"Linux\" or os == \"OSX\"\
do\
local _with_0 = { }\
_with_0.home = process.cwd()\
_with_0.data = join(_with_0.home, \".gmodproj\")\
_with_0.bin = join(_with_0.home, \"bin\")\
_with_0.manifest = join(_with_0.home, \".gmodmanifest\")\
_with_0.packages = join(_with_0.home, \".gmodpackages\")\
_with_0.cache = join(_with_0.data, \"cache\")\
_with_0.logs = join(_with_0.data, \"logs\")\
_with_0.plugins = join(_with_0.data, \"plugins\")\
PROJECT_PATH = _with_0\
end\
do\
local _with_0 = { }\
_with_0.data = join(userHome, \".gmodproj\")\
_with_0.applications = join(_with_0.home, \"applications\")\
_with_0.cache = join(_with_0.home, \"cache\")\
_with_0.plugins = join(_with_0.home, \"plugins\")\
USER_PATH = _with_0\
end",
['novacbn/gmodproj/lib/datafile'] = "local getmetatable, ipairs, pairs, setfenv, setmetatable, tostring\
do\
local _obj_0 = _G\
getmetatable, ipairs, pairs, setfenv, setmetatable, tostring = _obj_0.getmetatable, _obj_0.ipairs, _obj_0.pairs, _obj_0.setfenv, _obj_0.setmetatable, _obj_0.tostring\
end\
local gsub, match, rep\
do\
local _obj_0 = string\
gsub, match, rep = _obj_0.gsub, _obj_0.match, _obj_0.rep\
end\
local concat, insert\
do\
local _obj_0 = table\
concat, insert = _obj_0.concat, _obj_0.insert\
end\
local loadstring\
loadstring = require(\"moonscript/base\").loadstring\
local isNumericTable, isSequentialTable\
do\
local _obj_0 = dependency(\"novacbn/novautils/table\")\
isNumericTable, isSequentialTable = _obj_0.isNumericTable, _obj_0.isSequentialTable\
end\
local deprecate\
deprecate = dependency(\"novacbn/gmodproj/lib/utilities/deprecate\").deprecate\
local makeStringEscape\
makeStringEscape = dependency(\"novacbn/gmodproj/lib/utilities/string\").makeStringEscape\
local escapeString = makeStringEscape({\
{\
\"\\\\\",\
\"\\\\\\\\\"\
},\
{\
\"'\",\
\"\\\\'\"\
},\
{\
\"\\t\",\
\"\\\\t\"\
},\
{\
\"\\n\",\
\"\\\\n\"\
},\
{\
\"\\r\",\
\"\\\\r\"\
}\
})\
local encodeKeyString\
encodeKeyString = function(stringKey)\
stringKey = escapeString(stringKey)\
if match(stringKey, \"^%a\") then\
return stringKey, false\
end\
return \"'\" .. tostring(stringKey) .. \"'\", true\
end\
local encodeValueString\
encodeValueString = function(stringValue)\
stringValue = escapeString(stringValue)\
return \"'\" .. tostring(stringValue) .. \"'\"\
end\
local encodeKey, encodeValue\
local encodeValueTable\
encodeValueTable = function(tableValue, stackLevel)\
if stackLevel == nil then\
stackLevel = 0\
end\
local stringStack = { }\
local stackTabs = rep(\"\\t\", stackLevel)\
if stackLevel > 0 then\
insert(stringStack, \"{\")\
end\
if isNumericTable(tableValue) and isSequentialTable(tableValue) then\
local encodedValue\
local tableLength = #tableValue\
for index, value in ipairs(tableValue) do\
encodedValue = encodeValue(value, stackLevel + 1)\
if index < tableLength then\
insert(stringStack, stackTabs .. encodedValue .. \",\")\
else\
insert(stringStack, stackTabs .. encodedValue)\
end\
end\
else\
local keyType, encodedKey, keyEncapsulate, valueType, encodedValue\
for key, value in pairs(tableValue) do\
encodedKey, keyEncapsulate = encodeKey(key)\
encodedValue = encodeValue(value, stackLevel + 1)\
if keyEncapsulate then\
insert(stringStack, stackTabs .. \"[\" .. tostring(encodedKey) .. \"]: \" .. tostring(encodedValue))\
else\
insert(stringStack, stackTabs .. tostring(encodedKey) .. \" \" .. tostring(encodedValue))\
end\
end\
end\
if stackLevel > 0 then\
insert(stringStack, rep(\"\\t\", stackLevel - 1) .. \"}\")\
end\
return concat(stringStack, \"\\n\")\
end\
local typeEncodeMap = {\
key = {\
boolean = function(self)\
return self, true\
end,\
number = function(self)\
return self, true\
end,\
string = encodeKeyString\
},\
value = {\
boolean = tostring,\
number = function(self)\
return self\
end,\
string = encodeValueString,\
table = encodeValueTable\
}\
}\
encodeKey = function(key, ...)\
local keyEncoder = typeEncodeMap.key[type(key)]\
if not (keyEncoder) then\
error(\"cannot encode key '\" .. tostring(key) .. \"', unsupported type\")\
end\
return keyEncoder(key, ...)\
end\
encodeValue = function(value, ...)\
local valueEncoder = typeEncodeMap.value[type(value)]\
if not (valueEncoder) then\
error(\"cannot encode value '\" .. tostring(value) .. \"', unsupported type\")\
end\
return valueEncoder(value, ...)\
end\
local KeyPair\
KeyPair = function(name, levelToggle)\
return setmetatable({\
name = name\
}, {\
__call = function(self, value)\
if type(value) == \"table\" then\
local removedKeys = { }\
for key, subValue in pairs(value) do\
if type(subValue) == \"table\" and getmetatable(subValue) then\
if subValue.value ~= nil then\
value[subValue.name] = subValue.value\
end\
insert(removedKeys, key)\
end\
end\
for _index_0 = 1, #removedKeys do\
local key = removedKeys[_index_0]\
value[key] = nil\
end\
end\
self.value = value\
if levelToggle then\
levelToggle(name, value)\
end\
return self\
end\
})\
end\
local ChunkEnvironment\
ChunkEnvironment = function(dataExports)\
if dataExports == nil then\
dataExports = { }\
end\
local topLevel = true\
local levelToggle\
levelToggle = function(key, value)\
dataExports[key] = value\
topLevel = true\
end\
return setmetatable({ }, {\
__index = function(self, key)\
local keyPair = KeyPair(key, topLevel and levelToggle)\
topLevel = false\
return keyPair\
end\
}), dataExports\
end\
loadChunk = function(sourceChunk)\
deprecate(\"novacbn/gmodproj/lib/datafile::loadChunk\", \"novacbn/gmodproj/lib/datafile::loadChunk is deprecated, see 0.4.0 changelog\")\
local chunkEnvironment, dataExports = ChunkEnvironment()\
setfenv(sourceChunk, chunkEnvironment)()\
return dataExports\
end\
fromString = function(sourceString, chunkName)\
if chunkName == nil then\
chunkName = \"DataFile Chunk\"\
end\
deprecate(\"novacbn/gmodproj/lib/datafile::fromString\", \"novacbn/gmodproj/lib/datafile::fromString is deprecated, see 0.4.0 changelog\")\
local sourceChunk = loadstring(sourceString, chunkName)\
return loadChunk(sourceChunk)\
end\
toString = function(sourceTable)\
deprecate(\"novacbn/gmodproj/lib/datafile::toString\", \"novacbn/gmodproj/lib/datafile::toString is deprecated, see 0.4.0 changelog\")\
if not (type(sourceTable) == \"table\") then\
error(\"only table values can be serialized\")\
end\
return typeEncodeMap.value.table(sourceTable, 0)\
end",
['novacbn/gmodproj/lib/logging'] = "local open\
open = io.open\
local date\
date = os.date\
local format\
format = string.format\
local join\
join = require(\"path\").join\
local merge\
merge = dependency(\"novacbn/novautils/table\").merge\
local WriteBuffer\
WriteBuffer = dependency(\"novacbn/novautils/io/WriteBuffer\").WriteBuffer\
local PROJECT_PATH\
PROJECT_PATH = dependency(\"novacbn/gmodproj/lib/constants\").PROJECT_PATH\
local BUFFER_MEMORY_LOG = WriteBuffer:new()\
local HANDLE_FILE_LOG = nil\
local PATH_FILE_LOG = join(PROJECT_PATH.logs, date(\"%Y%m%d-%H%M%S.log\"))\
local TOGGLE_CONSOLE_LOGGING = true\
local TOGGLE_FILE_LOGGING = true\
local makeLogger\
makeLogger = function(tag, color, defaultOptions)\
if defaultOptions == nil then\
defaultOptions = { }\
end\
return function(message, options)\
if options == nil then\
options = { }\
end\
options = merge(options, defaultOptions)\
if TOGGLE_CONSOLE_LOGGING and options.console then\
print(format(\"%s[%-6s%s]%s %s\", color, tag, date(\"%H:%M:%S\"), \"\\27[0m\", message))\
end\
if TOGGLE_FILE_LOGGING and options.file then\
local logMessage = format(\"[%-6s%s] %s\\n\", tag, date(), message)\
if BUFFER_MEMORY_LOG then\
BUFFER_MEMORY_LOG:writeString(logMessage)\
else\
HANDLE_FILE_LOG:write(logMessage)\
end\
end\
if options.exit then\
return process:exit(options.exit)\
end\
end\
end\
enableFileLogging = function()\
if BUFFER_MEMORY_LOG and TOGGLE_FILE_LOGGING then\
HANDLE_FILE_LOG = open(PATH_FILE_LOG, \"wb\")\
HANDLE_FILE_LOG:write(BUFFER_MEMORY_LOG:toString())\
BUFFER_MEMORY_LOG = nil\
end\
end\
toggleConsoleLogging = function(toggle)\
TOGGLE_CONSOLE_LOGGING = toggle and true or false\
end\
toggleFileLogging = function(toggle)\
TOGGLE_FILE_LOGGING = toggle and true or false\
end\
logInfo = makeLogger(\"INFO\", \"\\27[32m\", {\
console = true,\
file = true\
})\
logWarn = makeLogger(\"WARN\", \"\\27[33m\", {\
console = true,\
file = true\
})\
logError = makeLogger(\"ERROR\", \"\\27[31m\", {\
console = true,\
file = true\
})\
logFatal = makeLogger(\"FATAL\", \"\\27[35m\", {\
console = true,\
exit = 1,\
file = true\
})",
['novacbn/gmodproj/lib/utilities'] = "local pcall\
pcall = _G.pcall\
local readFileSync, mkdirSync\
do\
local _obj_0 = require(\"fs\")\
readFileSync, mkdirSync = _obj_0.readFileSync, _obj_0.mkdirSync\
end\
local decode\
decode = dependency(\"novacbn/properties/exports\").decode\
local PROJECT_PATH\
PROJECT_PATH = dependency(\"novacbn/gmodproj/lib/constants\").PROJECT_PATH\
local enableFileLogging, logError, logFatal\
do\
local _obj_0 = dependency(\"novacbn/gmodproj/lib/logging\")\
enableFileLogging, logError, logFatal = _obj_0.enableFileLogging, _obj_0.logError, _obj_0.logFatal\
end\
local isDir, isFile\
do\
local _obj_0 = dependency(\"novacbn/gmodproj/lib/utilities/fs\")\
isDir, isFile = _obj_0.isDir, _obj_0.isFile\
end\
local ProjectOptions\
ProjectOptions = dependency(\"novacbn/gmodproj/schemas/ProjectOptions\").ProjectOptions\
configureEnvironment = function()\
if not (isDir(PROJECT_PATH.data)) then\
mkdirSync(PROJECT_PATH.data)\
end\
if not (isDir(PROJECT_PATH.cache)) then\
mkdirSync(PROJECT_PATH.cache)\
end\
if not (isDir(PROJECT_PATH.plugins)) then\
mkdirSync(PROJECT_PATH.plugins)\
end\
if not (isDir(PROJECT_PATH.logs)) then\
mkdirSync(PROJECT_PATH.logs)\
end\
return enableFileLogging()\
end\
readManifest = function()\
if isDir(PROJECT_PATH.manifest) then\
logFatal(\".gmodmanifest is a directory!\")\
end\
local options = { }\
if isFile(PROJECT_PATH.manifest) then\
options = decode(readFileSync(PROJECT_PATH.manifest), {\
propertiesEncoder = \"moonscript\"\
})\
end\
local success, err = pcall(ProjectOptions.new, ProjectOptions, options)\
if not (success) then\
logError(err)\
logFatal(\"Failed to validate .gmodmanifest!\")\
end\
return err\
end",
['novacbn/gmodproj/lib/utilities/assert'] = "local error\
error = _G.error\
argument = function(conditional, argument, name, tag, stackLevel)\
if stackLevel == nil then\
stackLevel = 2\
end\
if conditional then\
return conditional\
end\
return error(\"bad argument #\" .. tostring(argument) .. \" to '\" .. tostring(name) .. \"' (\" .. tostring(tag) .. \")\", stackLevel)\
end",
['novacbn/gmodproj/lib/utilities/deprecate'] = "local print\
print = _G.print\
local DEPRECATION_FEATURE_KEYS = { }\
deprecate = function(featureKey, text)\
if not (DEPRECATION_FEATURE_KEYS[featureKey]) then\
print(text)\
DEPRECATION_FEATURE_KEYS[featureKey] = true\
end\
end",
['novacbn/gmodproj/lib/utilities/fs'] = "local ipairs\
ipairs = _G.ipairs\
local popen\
popen = io.popen\
local match\
match = string.match\
local concat, insert\
do\
local _obj_0 = table\
concat, insert = _obj_0.concat, _obj_0.insert\
end\
local statSync\
statSync = require(\"fs\").statSync\
formatCommand = function(...)\
local commandArguments = {\
...\
}\
for index, commandArgument in ipairs(commandArguments) do\
if match(commandArgument, \"%s\") then\
commandArguments[index] = \"'\" .. tostring(commandArgument) .. \"'\"\
end\
end\
return concat(commandArguments, \" \")\
end\
exec = function(command)\
local handle = popen(command, \"r\")\
local stdout = handle:read(\"*a\")\
local success, _, status = handle:close()\
return success, status, stdout\
end\
execFormat = function(...)\
return exec(formatCommand(...))\
end\
isDir = function(path)\
local fileStats = statSync(path)\
return fileStats and fileStats.type == \"directory\" or false\
end\
isFile = function(path)\
local fileStats = statSync(path)\
return fileStats and fileStats.type == \"file\" or false\
end",
['novacbn/gmodproj/lib/utilities/openssl'] = "local base64, digest\
do\
local _obj_0 = require(\"openssl\")\
base64, digest = _obj_0.base64, _obj_0.digest\
end\
digest = digest.digest\
decodeB64 = function(str)\
return base64(str, false)\
end\
encodeB64 = function(str)\
return base64(str, true)\
end\
hashMD5 = function(str)\
return digest(\"MD5\", str)\
end\
hashSHA1 = function(str)\
return digest(\"SHA1\", str)\
end\
hashSHA256 = function(str)\
return digest(\"SHA256\", str)\
end",
['novacbn/gmodproj/lib/utilities/string'] = "local tostring\
tostring = _G.tostring\
local byte, gmatch, gsub, lower\
do\
local _obj_0 = string\
byte, gmatch, gsub, lower = _obj_0.byte, _obj_0.gmatch, _obj_0.gsub, _obj_0.lower\
end\
local concat\
concat = table.concat\
local makeLookupMap\
makeLookupMap = dependency(\"novacbn/novautils/table\").makeLookupMap\
local PATTERN_TEMPLATE_TOKEN = \"(%${)(%w+)(})\"\
local MAP_AFFIRMATIVE_VALUES = makeLookupMap({\
\"y\",\
\"yes\",\
\"t\",\
\"true\",\
\"1\"\
})\
isAffirmative = function(userValue)\
return MAP_AFFIRMATIVE_VALUES[lower(userValue)] or false\
end\
makeTemplate = function(stringTemplate)\
return function(templateTokens)\
return gsub(stringTemplate, PATTERN_TEMPLATE_TOKEN, function(startBoundry, tokenName, endBoundry)\
local tokenValue = templateTokens[tokenName]\
if not (tokenValue) then\
return startBoundry .. tokenName .. endBoundry\
end\
return tostring(tokenValue)\
end)\
end\
end\
makeStringEscape = function(lookup)\
return function(value)\
for _index_0 = 1, #lookup do\
local tokens = lookup[_index_0]\
value = gsub(value, tokens[1], tokens[2])\
end\
return value\
end\
end\
toBytes = function(sourceString)\
local _accum_0 = { }\
local _len_0 = 1\
for subString in gmatch(sourceString, \".\") do\
_accum_0[_len_0] = byte(subString)\
_len_0 = _len_0 + 1\
end\
return _accum_0\
end\
toByteString = function(sourceString)\
local byteTable = toBytes(sourceString)\
return \"{\" .. concat(byteTable, \",\") .. \"}\"\
end",
['novacbn/gmodproj/main'] = "local pairs, print, unpack\
do\
local _obj_0 = _G\
pairs, print, unpack = _obj_0.pairs, _obj_0.print, _obj_0.unpack\
end\
local lower, match\
do\
local _obj_0 = string\
lower, match = _obj_0.lower, _obj_0.match\
end\
local concat, insert, remove, sort\
do\
local _obj_0 = table\
concat, insert, remove, sort = _obj_0.concat, _obj_0.insert, _obj_0.remove, _obj_0.sort\
end\
local TEXT_COMMAND_VERSION\
TEXT_COMMAND_VERSION = dependency(\"novacbn/gmodproj/commands/version\").TEXT_COMMAND_VERSION\
local formatCommand\
formatCommand = dependency(\"novacbn/gmodproj/lib/utilities/fs\").formatCommand\
local logFatal, logInfo, toggleConsoleLogging, toggleFileLogging\
do\
local _obj_0 = dependency(\"novacbn/gmodproj/lib/logging\")\
logFatal, logInfo, toggleConsoleLogging, toggleFileLogging = _obj_0.logFatal, _obj_0.logInfo, _obj_0.toggleConsoleLogging, _obj_0.toggleFileLogging\
end\
local APPLICATION_SUB_COMMANDS = {\
bin = dependency(\"novacbn/gmodproj/commands/bin\"),\
build = dependency(\"novacbn/gmodproj/commands/build\"),\
new = dependency(\"novacbn/gmodproj/commands/new\"),\
version = dependency(\"novacbn/gmodproj/commands/version\")\
}\
local APPLICATION_COMMAND_FLAGS = {\
{\
\"-q\",\
\"--quiet\",\
\"Disables logging to console\"\
},\
{\
\"-nc\",\
\"--no-cache\",\
\"Disables caching of built project files\"\
},\
{\
\"-nf\",\
\"--no-file\",\
\"Disables logging to files\"\
}\
}\
local PATTERN_FLAG_MINI = \"%-[%w%-]+\"\
local PATTERN_FLAG_FULL = \"%-%-[%w%-]+\"\
local TEMPLATE_TEXT_HELP\
TEMPLATE_TEXT_HELP = function(version, commands, flags)\
return \"Garry's Mod Project Manager :: \" .. tostring(version) .. \"\\nSyntax:\9\9gmodproj [flags] [command]\\n\\nExamples:\9gmodproj bin prebuild\\n\9\9gmodproj build production\\n\9\9gmodproj new addon novacbn my-addon\\n\\nFlags:\\n\" .. tostring(flags) .. \"\\n\\nCommands:\\n\" .. tostring(commands)\
end\
local displayHelpText\
displayHelpText = function(flags)\
local commandsText\
do\
local _accum_0 = { }\
local _len_0 = 1\
for command, applicationCommand in pairs(APPLICATION_SUB_COMMANDS) do\
_accum_0[_len_0] = command\
_len_0 = _len_0 + 1\
end\
commandsText = _accum_0\
end\
sort(commandsText)\
do\
local _accum_0 = { }\
local _len_0 = 1\
for _index_0 = 1, #commandsText do\
local command = commandsText[_index_0]\
_accum_0[_len_0] = \"\\t\" .. APPLICATION_SUB_COMMANDS[command].formatDescription(flags)\
_len_0 = _len_0 + 1\
end\
commandsText = _accum_0\
end\
commandsText = concat(commandsText, \"\\n\")\
local flagsText\
do\
local _accum_0 = { }\
local _len_0 = 1\
for _index_0 = 1, #APPLICATION_COMMAND_FLAGS do\
local flag = APPLICATION_COMMAND_FLAGS[_index_0]\
_accum_0[_len_0] = \"\\t\" .. tostring(flag[1]) .. \", \" .. tostring(flag[2]) .. \"\\t\\t\\t\\t\" .. tostring(flag[3])\
_len_0 = _len_0 + 1\
end\
flagsText = _accum_0\
end\
flagsText = concat(flagsText, \"\\n\")\
return print(TEMPLATE_TEXT_HELP(TEXT_COMMAND_VERSION, commandsText, flagsText))\
end\
local parseArguments\
parseArguments = function(argv)\
local arguments, flags = { }, { }\
for _index_0 = 1, #argv do\
local argument = argv[_index_0]\
if match(argument, PATTERN_FLAG_MINI) or match(argument, PATTERN_FLAG_FULL) then\
flags[lower(argument)] = true\
else\
insert(arguments, argument)\
end\
end\
return arguments, flags\
end\
local arguments, flags = parseArguments(process.argv)\
local subCommand = remove(arguments, 1)\
toggleConsoleLogging(not (flags[\"-q\"] or flags[\"--quiet\"]))\
toggleFileLogging(not (flags[\"-nf\"] or flags[\"--no-file\"]))\
logInfo(\"Application starting with: \" .. tostring(formatCommand('gmodproj', ...)), {\
console = false,\
file = true\
})\
if subCommand == \"help\" then\
return displayHelpText(flags)\
else\
local applicationCommand = APPLICATION_SUB_COMMANDS[subCommand]\
if applicationCommand then\
return applicationCommand.executeCommand(flags, unpack(arguments))\
else\
return logFatal(\"Sub command '\" .. tostring(subCommand) .. \"' is invalid!\")\
end\
end",
['novacbn/gmodproj/schemas/AssetData'] = "local Schema\
Schema = dependency(\"novacbn/gmodproj/api/Schema\").Schema\
AssetData = Schema:extend({\
schema = {\
metadata = {\
nested_object = {\
name = {\
is = \"string\"\
},\
mtime = {\
is = \"number\"\
},\
path = {\
is = \"string\"\
}\
}\
},\
dependencies = {\
list_of = {\
is = \"string\"\
}\
},\
exports = {\
\"any_object\"\
},\
output = {\
is = \"string\"\
}\
},\
default = {\
metadata = {\
name = \"\",\
mtime = 0,\
path = \"\"\
},\
dependencies = { },\
exports = { },\
output = \"\"\
}\
})",
['novacbn/gmodproj/schemas/PackagerOptions'] = "local Schema\
Schema = dependency(\"novacbn/gmodproj/api/Schema\").Schema\
PackagerOptions = Schema:extend({\
namespace = \"Packager\",\
schema = {\
excludedAssets = {\
list_of = {\
is = \"string\"\
}\
},\
includedAssets = {\
list_of = {\
is = \"string\"\
}\
},\
targetPlatform = {\
is = \"string\"\
}\
},\
default = {\
excludedAssets = { },\
includedAssets = { },\
targetPlatform = \"garrysmod\"\
}\
})",
['novacbn/gmodproj/schemas/ProjectOptions'] = "local Schema\
Schema = dependency(\"novacbn/gmodproj/api/Schema\").Schema\
local MAP_DEFAULT_PLUGINS\
MAP_DEFAULT_PLUGINS = dependency(\"novacbn/gmodproj/lib/constants\").MAP_DEFAULT_PLUGINS\
PATTERN_METADATA_NAME = \"^%l[%l%d%-]*$\"\
PATTERN_METADATA_REPOSITORY = \"^[%w]+://[%w%./%-]+$\"\
PATTERN_METADATA_VERSION = \"^[%d]+.[%d]+.[%d]+$\"\
ProjectOptions = Schema:extend({\
schema = {\
name = {\
is = \"string\",\
like = PATTERN_METADATA_NAME\
},\
author = {\
is = \"string\",\
like = PATTERN_METADATA_NAME\
},\
version = {\
is = \"string\",\
like = PATTERN_METADATA_VERSION\
},\
repository = {\
is = \"string\",\
like = PATTERN_METADATA_REPOSITORY\
},\
buildDirectory = {\
is = \"string\"\
},\
sourceDirectory = {\
is = \"string\"\
},\
projectBuilds = {\
is_key_pairs = {\
\"string\",\
{\
\"string\",\
\"table\"\
}\
}\
},\
Plugins = {\
is_key_pairs = {\
\"string\",\
\"table\"\
}\
},\
Packager = {\
\"any_object\"\
},\
Resolver = {\
\"any_object\"\
}\
},\
default = {\
buildDirectory = \"dist\",\
sourceDirectory = \"src\",\
Plugins = MAP_DEFAULT_PLUGINS\
}\
})",
['novacbn/gmodproj/schemas/ResolverOptions'] = "local join\
join = require(\"path\").join\
local Schema\
Schema = dependency(\"novacbn/gmodproj/api/Schema\").Schema\
local PROJECT_PATH\
PROJECT_PATH = dependency(\"novacbn/gmodproj/lib/constants\").PROJECT_PATH\
ResolverOptions = Schema:extend({\
namespace = \"Resolver\",\
schema = {\
searchPaths = {\
list_of = {\
is = \"string\"\
}\
}\
},\
default = {\
searchPaths = {\
join(PROJECT_PATH.home, \"packages\")\
}\
}\
})",
['novacbn/novautils/bit'] = "if bit then\
exports.arshift = bit.arshift\
exports.band = bit.band\
exports.bnot = bit.bnot\
exports.bor = bit.bor\
exports.bxor = bit.bxor\
exports.lshift = bit.lshift\
exports.rol = bit.rol\
exports.ror = bit.ror\
exports.rshift = bit.rshift\
elseif bit32 then\
exports.arshift = bit32.arshift\
exports.band = bit32.band\
exports.bnot = bit32.bnot\
exports.bor = bit32.bor\
exports.bxor = bit32.bxor\
exports.lshift = bit32.lshift\
exports.rol = bit32.lrotate\
exports.ror = bit32.rrotate\
exports.rshift = bit32.rshift\
else\
error(\"could not find 'bit' LuaJIT or 'bit32' Lua 5.2 libraries\")\
end\
local arshift, band, bor, lshift, rshift\
do\
local _obj_0 = exports\
arshift, band, bor, lshift, rshift = _obj_0.arshift, _obj_0.band, _obj_0.bor, _obj_0.lshift, _obj_0.rshift\
end\
byteFromInt8 = function(value)\
return band(value, 255)\
end\
bytesFromInt16 = function(value)\
return band(rshift(value, 8), 255), band(value, 255)\
end\
bytesFromInt32 = function(value)\
return band(rshift(value, 24), 255), band(rshift(value, 16), 255), band(rshift(value, 8), 255), band(value, 255)\
end\
int8FromByte = function(byte)\
return byte\
end\
int16FromBytes = function(byteOne, byteTwo)\
return bor(lshift(byteOne, 8), byteTwo)\
end\
int32FromBytes = function(byteOne, byteTwo, byteThree, byteFour)\
return bor(lshift(byteOne, 24), lshift(byteTwo, 16), lshift(byteThree, 8), byteFour)\
end",
['novacbn/novautils/collections/BitEnum'] = "local band, bnot, bor\
do\
local _obj_0 = dependency(\"novacbn/novautils/bit\")\
band, bnot, bor = _obj_0.band, _obj_0.bnot, _obj_0.bor\
end\
addFlag = function(bitMask, bitFlag)\
return bor(bitMask, bitFlag)\
end\
hasFlag = function(bitMask, bitFlag)\
return band(bitMask, bitFlag) == bitFlag\
end\
removeFlag = function(bitMask, bitFlag)\
return bnot(bitMask, bitFlag)\
end\
BitEnum = function(fieldNames)\
local nextFlag = 0\
local enumLookup = { }\
for _index_0 = 1, #fieldNames do\
local value = fieldNames[_index_0]\
enumLookup[value] = nextFlag\
nextFlag = nextFlag == 0 and 1 or nextFlag * 2\
end\
return enumLookup\
end",
['novacbn/novautils/collections/ByteArray'] = "local unpack\
unpack = _G.unpack\
local byte, char\
do\
local _obj_0 = string\
byte, char = _obj_0.byte, _obj_0.char\
end\
local concat\
concat = table.concat\
local mapi\
mapi = dependency(\"novacbn/novautils/table\").mapi\
local Object\
Object = dependency(\"novacbn/novautils/utilities/Object\").Object\
ByteArray = Object:extend({\
length = 0,\
fromString = function(self, value)\
local byteArray = self:new()\
for index = 1, #value do\
byteArray[index] = byte(value, index)\
end\
byteArray.length = #value\
return byteArray\
end,\
fromTable = function(self, byteTable)\
local byteArray = self:new()\
for index = 1, #byteTable do\
byteArray[index] = byteTable[index]\
end\
byteArray.length = #byteTable\
return byteArray\
end,\
toString = function(self)\
local byteTable = mapi(self, function(i, v)\
return char(v)\
end)\
return concat(byteTable, \"\")\
end\
})",
['novacbn/novautils/collections/Enum'] = "Enum = function(fieldNames)\
local _tbl_0 = { }\
for index = 1, #fieldNames do\
_tbl_0[fieldNames[index]] = index - 1\
end\
return _tbl_0\
end",
['novacbn/novautils/collections/Iterator'] = "local Object\
Object = dependency(\"novacbn/novautils/utilities/Object\").Object\
Iterator = Object:extend({\
iter = function(self, ...)\
return self:__iter(...)\
end,\
keys = function(self)\
local _accum_0 = { }\
local _len_0 = 1\
for value, key in self:iter() do\
_accum_0[_len_0] = key\
_len_0 = _len_0 + 1\
end\
return _accum_0\
end,\
values = function(self)\
local _accum_0 = { }\
local _len_0 = 1\
for value, key in self:iter() do\
_accum_0[_len_0] = value\
_len_0 = _len_0 + 1\
end\
return _accum_0\
end\
})",
['novacbn/novautils/collections/LinkedList'] = "local Iterator\
Iterator = dependency(\"novacbn/novautils/collections/Iterator\").Iterator\
local Node\
Node = function(value, prev, next)\
return {\
value = value,\
prev = prev,\
next = next,\
removed = false\
}\
end\
LinkedList = Iterator:extend({\
head = nil,\
length = 0,\
tail = nil,\
__iter = function(self, reverse)\
if reverse == nil then\
reverse = false\
end\
local currentNode = {\
next = reverse and self.tail or self.head\
}\
return function()\
if currentNode then\
currentNode = currentNode.next\
if currentNode then\
return currentNode\
end\
end\
end\
end,\
clear = function(self)\
self.head = nil\
self.tail = nil\
end,\
find = function(self, value)\
for node in self:iter() do\
if node.value == value then\
return node\
end\
end\
return nil\
end,\
has = function(self, value)\
for node in self:iter() do\
if node.value == value then\
return true\
end\
end\
return false\
end,\
pop = function(self)\
if not (self.tail) then\
error(\"bad call to 'pop' (no Nodes available to pop)\")\
end\
return self:remove(self.tail)\
end,\
push = function(self, value)\
local node = Node(value, self.tail, nil)\
if self.tail then\
self.tail.next = node\
end\
self.tail = node\
if not (self.head) then\
self.head = node\
end\
self.length = self.length + 1\
return node\
end,\
remove = function(self, node)\
if node.removed then\
error(\"bad argument #1 to 'remove' (node was already removed)\")\
end\
if node.prev then\
node.prev.next = node.next\
end\
if node.next then\
node.next.prev = node.prev\
end\
if self.head == node then\
self.head = node.next\
end\
if self.tail == node then\
self.tail = node.prev\
end\
node.removed = true\
node.prev = nil\
node.next = nil\
self.length = self.length - 1\
return node\
end,\
shift = function(self)\
if not (self.head) then\
error(\"bad call to 'shift' (no nodes available to shift)\")\
end\
return self:remove(self.head)\
end,\
unshift = function(self, value)\
local node = Node(value, nil, self.head)\
if self.head then\
self.head.prev = node\
end\
self.head = node\
if not (self.tail) then\
self.tail = node\
end\
self.length = self.length + 1\
return node\
end,\
values = function(self)\
local _accum_0 = { }\
local _len_0 = 1\
for node in self:iter() do\
_accum_0[_len_0] = node.value\
_len_0 = _len_0 + 1\
end\
return _accum_0\
end\
})",
['novacbn/novautils/collections/Map'] = "local pairs, next\
do\
local _obj_0 = _G\
pairs, next = _obj_0.pairs, _obj_0.next\
end\
local Iterator\
Iterator = dependency(\"novacbn/novautils/collections/Iterator\").Iterator\
Map = Iterator:extend({\
clear = function(self)\
for key, value in pairs(self) do\
self[key] = nil\
end\
end,\
get = function(self, key)\
return self[key]\
end,\
has = function(self, key)\
return self[key] ~= nil\
end,\
find = function(self, searchValue)\
for key, value in pairs(self) do\
if value == searchValue then\
return key\
end\
end\
return nil\
end,\
set = function(self, key, value)\
self[key] = value\
end\
})",
['novacbn/novautils/collections/Set'] = "local type\
type = _G.type\
local insert, remove\
do\
local _obj_0 = table\
insert, remove = _obj_0.insert, _obj_0.remove\
end\
local Iterator\
Iterator = dependency(\"novacbn/novautils/collections/Iterator\").Iterator\
local inRange\
inRange = dependency(\"novacbn/novautils/math\").inRange\
local getCacheKey\
getCacheKey = function(value)\
if type(value) == \"string\" then\
return \"__set_s_\" .. value\
elseif type(value) == \"number\" then\
return \"__set_i_\" .. value\
end\
return value\
end\
Set = Iterator:extend({\
length = 0,\
fromTable = function(self, sourceTable)\
local set = self:new()\
for _index_0 = 1, #sourceTable do\
local value = sourceTable[_index_0]\
set:push(value)\
end\
return set\
end,\
__iter = function(self, reverse)\
local index = reverse and self.length + 1 or 0\
return function()\
index = index + 1\
return self[index], index\
end\
end,\
clear = function(self)\
local key\
for value, index in self:iter() do\
key = getCacheKey(value)\
self[index] = nil\
self[key] = nil\
end\
end,\
find = function(self, searchValue)\
for value, index in self:iter() do\
if value == searchValue then\
return index\
end\
end\
return nil\
end,\
has = function(self, value)\
local key = getCacheKey(value)\
return self[key] ~= nil\
end,\
push = function(self, value)\
if value == nil then\
error(\"bad argument #1 to 'push' (expected value)\")\
end\
local key = getCacheKey(value)\
if not (self[key] == nil) then\
return \
end\
local length = self.length + 1\
self[key] = true\
self[length] = value\
self.length = length\
return length\
end,\
pop = function(self, value)\
return self:remove(self.length)\
end,\
remove = function(self, index)\
if not (inRange(1, self.length)) then\
error(\"bad argument #1 to 'remove' (invalid index)\")\
end\
local key = getCacheKey(self[index])\
self[key] = nil\
self.length = self.length - 1\
return self:remove(self, index)\
end,\
shift = function(self, value)\
if value == nil then\
error(\"bad argument #1 to 'shift' (expected value)\")\
end\
local key = getCacheKey(value)\
if not (self[key] == nil) then\
return \
end\
local length = self.length + 1\
self[key] = true\
insert(self, value, 1)\
return length\
end,\
unshift = function(self)\
return self:remove(1)\
end\
})",
['novacbn/novautils/exports'] = "do\
local _with_0 = exports\
_with_0.collections = {\
BitEnum = dependency(\"novacbn/novautils/collections/BitEnum\").BitEnum,\
ByteArray = dependency(\"novacbn/novautils/collections/ByteArray\").ByteArray,\
Enum = dependency(\"novacbn/novautils/collections/Enum\").Enum,\
Iterator = dependency(\"novacbn/novautils/collections/Iterator\").Iterator,\
LinkedList = dependency(\"novacbn/novautils/collections/LinkedList\").LinkedList,\
Map = dependency(\"novacbn/novautils/collections/Map\").Map,\
Set = dependency(\"novacbn/novautils/collections/Set\").Set\
}\
_with_0.io = {\
ReadBuffer = dependency(\"novacbn/novautils/io/ReadBuffer\").ReadBuffer,\
WriteBuffer = dependency(\"novacbn/novautils/io/WriteBuffer\").WriteBuffer\
}\
_with_0.sources = {\
Event = dependency(\"novacbn/novautils/sources/Event\").Event,\
Signal = dependency(\"novacbn/novautils/sources/Signal\").Signal,\
Transform = dependency(\"novacbn/novautils/sources/Transform\").Transform\
}\
_with_0.bit = getmetatable(dependency(\"novacbn/novautils/bit\")).__index\
_with_0.math = getmetatable(dependency(\"novacbn/novautils/math\")).__index\
_with_0.table = getmetatable(dependency(\"novacbn/novautils/table\")).__index\
end\
do\
local _with_0 = getmetatable(dependency(\"novacbn/novautils/utilities\")).__index\
_with_0.Object = dependency(\"novacbn/novautils/utilities/Object\").Object\
exports.utilities = _with_0\
end",
['novacbn/novautils/io/ReadBuffer'] = "local unpack\
unpack = _G.unpack\
local char\
char = string.char\
local arshift, lshift, int16FromBytes, int32FromBytes\
do\
local _obj_0 = dependency(\"novacbn/novautils/bit\")\
arshift, lshift, int16FromBytes, int32FromBytes = _obj_0.arshift, _obj_0.lshift, _obj_0.int16FromBytes, _obj_0.int32FromBytes\
end\
local ByteArray\
ByteArray = dependency(\"novacbn/novautils/collections/ByteArray\").ByteArray\
ReadBuffer = ByteArray:extend({\
cursor = 0,\
read = function(self, length)\
if length == nil then\
length = 1\
end\
local cursor = self.cursor\
local newCursor = cursor + length\
if newCursor > self.length then\
error(\"bad argument #1 to 'read' (read length exceeds buffer length)\")\
end\
self.cursor = newCursor\
return unpack(self, cursor + 1, newCursor)\
end,\
readFloat32 = function(self) end,\
readFloat64 = function(self) end,\
readInt8 = function(self)\
return arshift(lshift(self:readUInt8(), 24), 24)\
end,\
readInt16 = function(self)\
return arshift(lshift(self:readUInt16(), 16), 16)\
end,\
readInt32 = function(self)\
return arshift(lshift(self:readUInt32(), 32), 32)\
end,\
readString = function(self, length)\
return char(self:read(length))\
end,\
readUInt8 = function(self)\
return self:read(1)\
end,\
readUInt16 = function(self)\
return int16FromBytes(self:read(2))\
end,\
readUInt32 = function(self)\
return int32FromBytes(self:read(4))\
end,\
remaining = function(self)\
return self.length - self.cursor\
end\
})",
['novacbn/novautils/io/WriteBuffer'] = "local type\
type = _G.type\
local byte\
byte = string.byte\
local arshift, lshift, byteFromInt8, bytesFromInt16, bytesFromInt32\
do\
local _obj_0 = dependency(\"novacbn/novautils/bit\")\
arshift, lshift, byteFromInt8, bytesFromInt16, bytesFromInt32 = _obj_0.arshift, _obj_0.lshift, _obj_0.byteFromInt8, _obj_0.bytesFromInt16, _obj_0.bytesFromInt32\
end\
local inRange\
inRange = dependency(\"novacbn/novautils/math\").inRange\
local ByteArray\
ByteArray = dependency(\"novacbn/novautils/collections/ByteArray\").ByteArray\
WriteBuffer = ByteArray:extend({\
write = function(self, ...)\
local varArgs = {\
...\
}\
local length = self.length\
local value\
for index = 1, #varArgs do\
value = varArgs[index]\
if not (type(value) == \"number\") then\
error(\"bad argument #\" .. tostring(index) .. \" to 'write' (expected number)\")\
end\
if not (inRange(value, 0, 255)) then\
error(\"bad argument #\" .. tostring(index) .. \" to 'write' (expected number in range 0...255)\")\
end\
self[index + length] = value\
end\
self.length = self.length + #varArgs\
end,\
writeFloat32 = function(self, value) end,\
writeFloat64 = function(self, value) end,\
writeInt8 = function(self, value)\
return self:write(byteFromInt8(value))\
end,\
writeInt16 = function(self, value)\
return self:write(bytesFromInt16(value))\
end,\
writeInt32 = function(self, value)\
return self:write(bytesFromInt32(value))\
end,\
writeString = function(self, value)\
local length = self.length\
for index = 1, #value do\
self[length + index] = byte(value, index)\
end\
self.length = self.length + #value\
end,\
writeUInt8 = function(self, value)\
return self:write(byteFromInt8(value))\
end,\
writeUInt16 = function(self, value)\
return self:write(bytesFromInt16(value))\
end,\
writeUInt32 = function(self, value)\
return self:write(bytesFromInt32(value))\
end\
})",
['novacbn/novautils/math'] = "local maxF, minF = math.max, math.min\
RANGE_INT8 = {\
min = (0x0000007F + 1) * -1,\
max = 0x0000007F\
}\
RANGE_INT16 = {\
min = (0x00007FFF + 1) * -1,\
max = 0x00007FFF\
}\
RANGE_INT32 = {\
min = (0x7FFFFFFF + 1) * -1,\
max = 0x7FFFFFFF\
}\
RANGE_UINT8 = {\
min = 0x00000000,\
max = 0x000000FF\
}\
RANGE_UINT16 = {\
min = 0x00000000,\
max = 0x00FFFFFF\
}\
RANGE_UINT32 = {\
min = 0x00000000,\
max = 0xFFFFFFFF\
}\
clamp = function(value, min, max)\
return minF(maxF(value, min), max)\
end\
inRange = function(value, min, max)\
return value <= max and value >= min\
end\
isFloat = function(value)\
return value % 1 ~= 0\
end\
isInteger = function(value)\
return value % 1 == 0\
end",
['novacbn/novautils/sources/Event'] = "local unpack\
unpack = _G.unpack\
local Signal\
Signal = dependency(\"novacbn/novautils/sources/Signal\").Signal\
local pack\
pack = dependency(\"novacbn/novautils/utilities\").pack\
Event = Signal:extend({\
dispatch = function(self, ...)\
local varRet\
for node in self:iter() do\
varRet = pack(node.value(...))\
if #varRet > 0 then\
return unpack(varRet)\
end\
end\
return ...\
end\
})",
['novacbn/novautils/sources/Signal'] = "local LinkedList\
LinkedList = dependency(\"novacbn/novautils/collections/LinkedList\").LinkedList\
local makeDetachFunc\
makeDetachFunc = function(signal, node)\
return function()\
if not (node.removed) then\
signal:remove(node)\
return false\
end\
return true\
end\
end\
Signal = LinkedList:extend({\
attach = function(self, listenerFunc)\
local node = self:push(listenerFunc)\
return makeDetachFunc(self, node)\
end,\
dispatch = function(self, ...)\
for node in self:iter() do\
node.value(...)\
end\
end,\
detach = function(self, listenerFunc)\
local node = self:find(listenerFunc)\
if not (node) then\
error(\"bad argument #1 to 'detach' (function not attached)\")\
end\
return self:remove(node)\
end\
})",
['novacbn/novautils/sources/Transform'] = "local unpack\
unpack = _G.unpack\
local Signal\
Signal = dependency(\"novacbn/novautils/sources/Signal\").Signal\
local pack\
pack = dependency(\"novacbn/novautils/utilities\").pack\
Transform = Signal:extend({\
dispatch = function(self, ...)\
local varRet = pack(...)\
local tempRet\
for node in self:iter() do\
tempRet = pack(node.value(unpack(varRet)))\
if #tempRet > 0 then\
varRet = tempRet\
end\
end\
return unpack(varRet)\
end\
})",
['novacbn/novautils/table'] = "local ipairs, pairs, type\
do\
local _obj_0 = _G\
ipairs, pairs, type = _obj_0.ipairs, _obj_0.pairs, _obj_0.type\
end\
clone = function(sourceTable)\
local _tbl_0 = { }\
for key, value in pairs(sourceTable) do\
_tbl_0[key] = type(value) == \"table\" and clone(value) or value\
end\
return _tbl_0\
end\
copy = function(sourceTable)\
local _tbl_0 = { }\
for key, value in pairs(sourceTable) do\
_tbl_0[key] = value\
end\
return _tbl_0\
end\
deepMerge = function(targetTable, sourceTable)\
for key, value in pairs(sourceTable) do\
if type(targetTable[key]) == \"table\" and type(value) == \"table\" then\
deepMerge(targetTable[key], value)\
end\
if targetTable[key] == nil then\
if type(value) == \"table\" then\
value = clone(value)\
end\
targetTable[key] = value\
end\
end\
return targetTable\
end\
deepUpdate = function(targetTable, sourceTable)\
for key, value in pairs(sourceTable) do\
if type(value) == \"table\" then\
if type(targetTable[key]) == \"table\" then\
deepUpdate(targetTable[key], value)\
else\
targetTable[key] = clone(value)\
end\
else\
targetTable[key] = value\
end\
end\
return targetTable\
end\
keysMeta = function(sourceTable, collectionTable)\
if collectionTable == nil then\
collectionTable = { }\
end\
local metaTable = getmetatable(sourceTable)\
if metaTable and type(metaTable.__index) == \"table\" then\
keysMeta(metaTable.__index, collectionTable)\
end\
for key, value in pairs(sourceTable) do\
collectionTable[key] = value\
end\
return collectionTable\
end\
isNumericTable = function(sourceTable)\
for key, value in pairs(sourceTable) do\
if not (type(key) == \"number\") then\
return false\
end\
end\
return true\
end\
isSequentialTable = function(sourceTable)\
local countedLength, previousIndex = 0, nil\
for index, value in ipairs(sourceTable) do\
if previousIndex then\
if (previousIndex - index) > 1 then\
return false\
end\
end\
previousIndex = index\
countedLength = countedLength + 1\
end\
return countedLength == #sourceTable\
end\
makeLookupMap = function(lookupValues)\
local _tbl_0 = { }\
for key, value in pairs(lookupValues) do\
_tbl_0[value] = key\
end\
return _tbl_0\
end\
makeTruthMap = function(lookupValues)\
local _tbl_0 = { }\
for _index_0 = 1, #lookupValues do\
local value = lookupValues[_index_0]\
_tbl_0[value] = true\
end\
return _tbl_0\
end\
map = function(targetTable, func)\
local _tbl_0 = { }\
for key, value in pairs(targetTable) do\
local _key_0, _val_0 = func(key, value)\
_tbl_0[_key_0] = _val_0\
end\
return _tbl_0\
end\
mapi = function(targetTable, func)\
local remappedTable = { }\
local length = 0\
local remappedValue\
for index, value in ipairs(targetTable) do\
remappedValue = func(index, value)\
if not (remappedValue == nil) then\
length = length + 1\
remappedTable[length] = remappedValue\
end\
end\
return remappedTable\
end\
merge = function(targetTable, sourceTable)\
for key, value in pairs(sourceTable) do\
if targetTable[key] == nil then\
if type(value) == \"table\" then\
value = clone(value)\
end\
targetTable[key] = value\
end\
end\
return targetTable\
end\
update = function(targetTable, sourceTable)\
for key, value in pairs(sourceTable) do\
if type(value) == \"table\" then\
value = clone(value)\
end\
targetTable[key] = value\
end\
return targetTable\
end\
slice = function(targetTable, startIndex, endIndex)\
local _accum_0 = { }\
local _len_0 = 1\
for index = startIndex, endIndex do\
_accum_0[_len_0] = targetTable[index]\
_len_0 = _len_0 + 1\
end\
return _accum_0\
end",
['novacbn/novautils/utilities'] = "local select, unpack\
do\
local _obj_0 = _G\
select, unpack = _obj_0.select, _obj_0.unpack\
end\
bind = function(boundFunction, ...)\
local varArgs = pack(...)\
return function(...)\
return boundFunction(unpack(varArgs), ...)\
end\
end\
pack = function(...)\
return {\
n = select(\"#\", ...),\
...\
}\
end",
['novacbn/novautils/utilities/Object'] = "local getmetatable, pairs, rawget, setmetatable, type\
do\
local _obj_0 = _G\
getmetatable, pairs, rawget, setmetatable, type = _obj_0.getmetatable, _obj_0.pairs, _obj_0.rawget, _obj_0.setmetatable, _obj_0.type\
end\
local bind\
bind = dependency(\"novacbn/novautils/utilities\").bind\
local clone, keysMeta\
do\
local _obj_0 = dependency(\"novacbn/novautils/table\")\
clone, keysMeta = _obj_0.clone, _obj_0.keysMeta\
end\
Object = {\
new = function(objectClass, ...)\
local newInstance = setmetatable({ }, objectClass)\
local metaKeys = keysMeta(objectClass)\
for key, value in pairs(metaKeys) do\
if type(value) == \"table\" and isInstance(Decorator, value) then\
value:__initialized(newInstance, key)\
end\
end\
if newInstance.constructor then\
newInstance:constructor(...)\
end\
return newInstance\
end,\
extend = function(parentClass, objectMembers)\
objectMembers.__index = objectMembers\
setmetatable(objectMembers, parentClass)\
for key, value in pairs(objectMembers) do\
if type(value) == \"table\" and isInstance(Decorator, value) then\
value:__assigned(objectMembers, key)\
end\
end\
if parentClass.__extended then\
parentClass:__extended(objectMembers)\
end\
return objectMembers\
end\
}\
Object.__index = Object\
isInstance = function(parentObject, targetObject)\
if rawget(targetObject, \"__index\") ~= targetObject then\
return hasInherited(parentObject, targetObject)\
end\
return false\
end\
hasInherited = function(parentObject, targetObject)\
local metaTable = targetObject\
while metaTable do\
if metaTable == parentObject then\
return true\
end\
metaTable = getmetatable(metaTable)\
end\
return false\
end\
Decorator = Object:extend({\
__call = function(self, ...)\
return self.new(self, ...)\
end,\
__assigned = function(self, objectClass, memberName) end,\
__initialized = function(self, objectInstance, memberName) end\
})\
Default = Decorator:extend({\
constructor = function(self, defaultValue, ...)\
local _exp_0 = type(defaultValue)\
if \"table\" == _exp_0 then\
if hasInherited(Object, defaultValue) then\
self.generator = bind(defaultValue.new, defaultValue, ...)\
else\
self.generator = bind(clone, defaultValue)\
end\
elseif \"function\" == _exp_0 then\
self.generator = bind(defaultValue, ...)\
end\
self.defaultValue = defaultValue\
end,\
__initialized = function(self, newObject, memberName)\
newObject[memberName] = self.generator and self:generator() or self.defaultValue\
end\
})",
['novacbn/properties/encoders/lua'] = "local ipairs, loadstring, pairs, setmetatable, type\
do\
local _obj_0 = _G\
ipairs, loadstring, pairs, setmetatable, type = _obj_0.ipairs, _obj_0.loadstring, _obj_0.pairs, _obj_0.setmetatable, _obj_0.type\
end\
local stderr\
stderr = io.stderr\
local format, match, rep\
do\
local _obj_0 = string\
format, match, rep = _obj_0.format, _obj_0.match, _obj_0.rep\
end\
local concat, insert\
do\
local _obj_0 = table\
concat, insert = _obj_0.concat, _obj_0.insert\
end\
local getKeys, getSortedValues, isArray\
do\
local _obj_0 = dependency(\"novacbn/properties/utilities\")\
getKeys, getSortedValues, isArray = _obj_0.getKeys, _obj_0.getSortedValues, _obj_0.isArray\
end\
do\
local _with_0 = { }\
local options = nil\
_with_0.stackLevel = -1\
_with_0.new = function(self, encoderOptions)\
return setmetatable({\
options = encoderOptions\
}, self)\
end\
_with_0.append = function(self, value, ignoreStack, appendTail)\
if ignoreStack or self.stackLevel < 1 then\
if not (appendTail) then\
return insert(self, value)\
else\
local length = #self\
self[length] = self[length] .. value\
end\
else\
return insert(self, rep(self.options.indentationChar, self.stackLevel) .. value)\
end\
end\
_with_0.boolean = function(self, value)\
return value and \"true\" or \"false\"\
end\
_with_0.boolean_key = function(self, value)\
return \"[\" .. (value and \"true\" or \"false\") .. \"]\"\
end\
_with_0.number = function(self, value)\
return tostring(value)\
end\
_with_0.number_key = function(self, value)\
return \"[\" .. value .. \"]\"\
end\
_with_0.string = function(self, value)\
return format(\"%q\", value)\
end\
_with_0.string_key = function(self, value)\
return match(value, \"^%a+$\") and value or format(\"[%q]\", value)\
end\
_with_0.array = function(self, arr)\
local length = #arr\
local encoder\
for index, value in ipairs(arr) do\
encoder = self[type(value)]\
if not (encoder) then\
error(\"bad argument #1 to 'Encoder.array' (unexpected type)\")\
end\
if encoder == self.table then\
self:encoder(self, value, index < length)\
else\
if index < length then\
self:append(encoder(self, value, true) .. \",\")\
else\
self:append(encoder(self, value, false))\
end\
end\
end\
end\
_with_0.map = function(self, map)\
local keys = getSortedValues(getKeys(map))\
local length = #keys\
local count = 0\
local keyEncoder, value, valueEncoder\
for _index_0 = 1, #keys do\
local key = keys[_index_0]\
keyEncoder = self[type(key) .. \"_key\"]\
if not (keyEncoder) then\
error(\"bad argument #1 to 'Encoder.map' (unexpected key type)\")\
end\
value = map[key]\
valueEncoder = self[type(value)]\
if not (valueEncoder) then\
error(\"bad argument #1 to Encoder.map (unexpected value type)\")\
end\
count = count + 1\
if valueEncoder == self.table then\
self:append(keyEncoder(self, key) .. \" = \")\
valueEncoder(self, value, count < length)\
else\
if count < length then\
self:append(keyEncoder(self, key) .. \" = \" .. valueEncoder(self, value) .. \",\")\
else\
self:append(keyEncoder(self, key) .. \" = \" .. valueEncoder(self, value))\
end\
end\
end\
end\
_with_0.table = function(self, tbl, innerMember, isRoot)\
if not (isRoot) then\
self:append(\"{\", true, true)\
end\
self.stackLevel = self.stackLevel + 1\
if isArray(tbl) then\
self:array(tbl)\
else\
self:map(tbl)\
end\
self.stackLevel = self.stackLevel - 1\
if not (isRoot) then\
return self:append(innerMember and \"},\" or \"}\")\
end\
end\
_with_0.toString = function(self)\
return concat(self, \"\\n\")\
end\
LuaEncoder = _with_0\
end\
LuaEncoder.__index = LuaEncoder\
encode = function(tbl, encoderOptions)\
local encoder = LuaEncoder:new(encoderOptions)\
encoder:table(tbl, false, true)\
return encoder:toString()\
end\
decode = function(value, decoderOptions)\
if not (decoderOptions.allowUnsafe) then\
error(\"bad option 'allowUnsafe' to 'decode' (Lua AST parser not implemented)\")\
end\
local chunk, err = loadstring(\"return {\" .. tostring(value) .. \"}\")\
if err then\
stderr:write(\"bad argument #1 to 'decode' (Lua syntax error)\\n\")\
error(err)\
end\
return chunk()\
end",
['novacbn/properties/encoders/moonscript'] = "local pairs, setmetatable, type\
do\
local _obj_0 = _G\
pairs, setmetatable, type = _obj_0.pairs, _obj_0.setmetatable, _obj_0.type\
end\
local stderr\
stderr = io.stderr\
local format, match, rep\
do\
local _obj_0 = string\
format, match, rep = _obj_0.format, _obj_0.match, _obj_0.rep\
end\
local insert\
insert = table.insert\
local hasMoonScript, moonscript = pcall(require, \"moonscript/base\")\
local getKeys, getSortedValues, isArray\
do\
local _obj_0 = dependency(\"novacbn/properties/utilities\")\
getKeys, getSortedValues, isArray = _obj_0.getKeys, _obj_0.getSortedValues, _obj_0.isArray\
end\
local LuaEncoder\
LuaEncoder = dependency(\"novacbn/properties/encoders/lua\").LuaEncoder\
do\
local _with_0 = { }\
_with_0.new = function(self, encoderOptions)\
return setmetatable({\
options = encoderOptions\
}, self)\
end\
_with_0.boolean_key = function(self, value)\
return value and \"true\" or \"false\"\
end\
_with_0.string_key = function(self, value)\
return match(value, \"^%a+$\") and value or format(\"%q\", value)\
end\
_with_0.map = function(self, map)\
local keys = getSortedValues(getKeys(map))\
local length = #keys\
local count = 0\
local keyEncoder, value, valueEncoder\
for _index_0 = 1, #keys do\
local key = keys[_index_0]\
keyEncoder = self[type(key) .. \"_key\"]\
if not (keyEncoder) then\
error(\"bad argument #1 to 'Encoder.map' (unexpected key type)\")\
end\
value = map[key]\
valueEncoder = self[type(value)]\
if not (valueEncoder) then\
error(\"bad argument #1 to Encoder.map (unexpected value type)\")\
end\
count = count + 1\
if valueEncoder == self.table then\
self:append(keyEncoder(self, key) .. \": \")\
valueEncoder(self, value, count < length)\
else\
self:append(keyEncoder(self, key) .. \": \" .. valueEncoder(self, value))\
end\
end\
end\
_with_0.table = function(self, tbl, innerMember, isRoot)\
self.stackLevel = self.stackLevel + 1\
if isArray(tbl) then\
if not (isRoot) then\
self:append(\"{\", true, true)\
end\
self:array(tbl)\
self.stackLevel = self.stackLevel - 1\
if not (isRoot) then\
return self:append(\"}\")\
end\
else\
self:map(tbl)\
self.stackLevel = self.stackLevel - 1\
end\
end\
MoonScriptEncoder = _with_0\
end\
setmetatable(MoonScriptEncoder, LuaEncoder)\
MoonScriptEncoder.__index = MoonScriptEncoder\
encode = function(tbl, encoderOptions)\
local encoder = MoonScriptEncoder:new(encoderOptions)\
encoder:table(tbl, false, true)\
return encoder:toString()\
end\
decode = function(value, decoderOptions)\
if not (hasMoonScript) then\
error(\"bad dispatch to 'decode' (MoonScript library is not installed)\")\
end\
if not (decoderOptions.allowUnsafe) then\
error(\"bad option 'allowUnsafe' to 'decode' (MoonScript AST parser not implemented)\")\
end\
local chunk, err = moonscript.loadstring(\"{\" .. tostring(value) .. \"}\")\
if err then\
stderr:write(\"bad argument #1 to 'decode' (MoonScript syntax error)\\n\")\
error(err)\
end\
return chunk()\
end",
['novacbn/properties/exports'] = "local type\
type = _G.type\
local propertiesEncoders = {\
lua = dependency(\"novacbn/properties/encoders/lua\"),\
moonscript = dependency(\"novacbn/properties/encoders/moonscript\")\
}\
local EncoderOptions\
EncoderOptions = function(options)\
do\
local _with_0 = options or { }\
_with_0.allowUnsafe = _with_0.allowUnsafe or true\
_with_0.indentationChar = _with_0.indentationChar or \"\\t\"\
_with_0.propertiesEncoder = propertiesEncoders[_with_0.propertiesEncoder or \"lua\"]\
_with_0.sortKeys = _with_0.sortKeys == nil and true or _with_0.sortKeys\
_with_0.sortIgnoreCase = _with_0.sortIgnoreCase == nil and true or _with_0.sortIgnoreCase\
if not (_with_0.propertiesEncoder) then\
error(\"bad option 'propertiesEncoder' to 'EncoderOptions' (invalid value '\" .. tostring(decoderOptions.propertiesEncoder) .. \"')\")\
end\
return _with_0\
end\
end\
local DecoderOptions\
DecoderOptions = function(options)\
do\
local _with_0 = options or { }\
_with_0.allowUnsafe = _with_0.allowUnsafe or true\
_with_0.propertiesEncoder = propertiesEncoders[_with_0.propertiesEncoder or \"lua\"]\
if not (_with_0.propertiesEncoder) then\
error(\"bad option 'propertiesEncoder' to 'DecoderOptions' (invalid value '\" .. tostring(decoderOptions.propertiesEncoder) .. \"')\")\
end\
return _with_0\
end\
end\
encode = function(value, options)\
if not (type(value) == \"table\") then\
error(\"bad argument #1 to 'encode' (expected table)\")\
end\
if not (options == nil or type(options) == \"table\") then\
error(\"bad argument #2 to 'encode' (expected table)\")\
end\
local encoderOptions = EncoderOptions(options)\
return encoderOptions.propertiesEncoder.encode(value, encoderOptions)\
end\
decode = function(value, options)\
if not (type(value) == \"string\") then\
error(\"bad argument #1 to 'decode' (expected string)\")\
end\
if not (options == nil or type(options) == \"table\") then\
error(\"bad argument #2 to 'decode' (expected table)\")\
end\
local decoderOptions = DecoderOptions(options)\
return decoderOptions.propertiesEncoder.decode(value, decoderOptions)\
end",
['novacbn/properties/utilities'] = "local pairs, type\
do\
local _obj_0 = _G\
pairs, type = _obj_0.pairs, _obj_0.type\
end\
local lower\
lower = string.lower\
local sort\
sort = table.sort\
local sortingWeights = {\
boolean = 0,\
number = 1,\
string = 2,\
table = 3\
}\
getKeys = function(tbl)\
local _accum_0 = { }\
local _len_0 = 1\
for key, value in pairs(tbl) do\
_accum_0[_len_0] = key\
_len_0 = _len_0 + 1\
end\
return _accum_0\
end\
getSortedValues = function(tbl, isCaseSensitive)\
local values\
do\
local _accum_0 = { }\
local _len_0 = 1\
for _index_0 = 1, #tbl do\
local value = tbl[_index_0]\
_accum_0[_len_0] = value\
_len_0 = _len_0 + 1\
end\
values = _accum_0\
end\
local aWeight, bWeight, aType, bType\
sort(values, function(a, b)\
aType, bType = type(a), type(b)\
if aType == \"string\" and bType == \"string\" then\
if not (isCaseSensitive) then\
return lower(a) < lower(b)\
end\
return a < b\
elseif aType == \"boolean\" and bType == \"boolean\" then\
if aType == true and bType == false then\
return false\
end\
return true\
elseif aType == \"number\" and bType == \"number\" then\
return a < b\
else\
return sortingWeights[aType] < sortingWeights[bType]\
end\
end)\
return values\
end\
isArray = function(tbl)\
if tbl[1] == nil then\
return false\
end\
local count = 0\
for key, value in pairs(tbl) do\
if not (type(key) == \"number\") then\
return false\
end\
count = count + 1\
end\
if not (count == #tbl) then\
return false\
end\
return true\
end",
['pkulchenko/serpent/main'] = "--[[\
https://github.com/pkulchenko/serpent\
\
Serpent source is released under the MIT License\
\
Copyright (c) 2012-2017 Paul Kulchenko (paul@kulchenko.com)\
\
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 n, v = \"serpent\", \"0.30\" -- (C) 2012-17 Paul Kulchenko; MIT License\
local c, d = \"Paul Kulchenko\", \"Lua serializer and pretty printer\"\
local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'}\
local badtype = {thread = true, userdata = true, cdata = true}\
local getmetatable = debug and debug.getmetatable or getmetatable\
local pairs = function(t) return next, t end -- avoid using __pairs in Lua 5.2+\
local keyword, globals, G = {}, {}, (_G or _ENV)\
for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false',\
'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',\
'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end\
for k,v in pairs(G) do globals[v] = k end -- build func to name mapping\
for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do\
for k,v in pairs(type(G[g]) == 'table' and G[g] or {}) do globals[v] = g..'.'..k end end\
\
local function s(t, opts)\
local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum\
local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge\
local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge)\
local maxlen, metatostring = tonumber(opts.maxlength), opts.metatostring\
local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge)\
local numformat = opts.numformat or \"%.17g\"\
local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0\
local function gensym(val) return '_'..(tostring(tostring(val)):gsub(\"[^%w]\",\"\"):gsub(\"(%d%w+)\",\
-- tostring(val) is needed because __tostring may return a non-string value\
function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end\
local function safestr(s) return type(s) == \"number\" and tostring(huge and snum[tostring(s)] or numformat:format(s))\
or type(s) ~= \"string\" and tostring(s) -- escape NEWLINE/010 and EOF/026\
or (\"%q\"):format(s):gsub(\"\\010\",\"n\"):gsub(\"\\026\",\"\\\\026\") end\
local function comment(s,l) return comm and (l or 0) < comm and ' --[['..select(2, pcall(tostring, s))..']]' or '' end\
local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal\
and safestr(select(2, pcall(tostring, s))) or error(\"Can't serialize \"..tostring(s)) end\
local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r']\
local n = name == nil and '' or name\
local plain = type(n) == \"string\" and n:match(\"^[%l%u_][%w_]*$\") and not keyword[n]\
local safe = plain and n or '['..safestr(n)..']'\
return (path or '')..(plain and path and '.' or '')..safe, safe end\
local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding\
local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'}\
local function padnum(d) return (\"%0\"..tostring(maxn)..\"d\"):format(tonumber(d)) end\
table.sort(k, function(a,b)\
-- sort numeric keys first: k[key] is not nil for numerical keys\
return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub(\"%d+\",padnum))\
< (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub(\"%d+\",padnum)) end) end\
local function val2str(t, name, indent, insref, path, plainindex, level)\
local ttype, level, mt = type(t), (level or 0), getmetatable(t)\
local spath, sname = safename(path, name)\
local tag = plainindex and\
((type(name) == \"number\") and '' or name..space..'='..space) or\
(name ~= nil and sname..space..'='..space or '')\
if seen[t] then -- already seen this element\
sref[#sref+1] = spath..space..'='..space..seen[t]\
return tag..'nil'..comment('ref', level) end\
-- protect from those cases where __tostring may fail\
if type(mt) == 'table' then\
local to, tr = pcall(function() return mt.__tostring(t) end)\
local so, sr = pcall(function() return mt.__serialize(t) end)\
if (opts.metatostring ~= false and to or so) then -- knows how to serialize itself\
seen[t] = insref or spath\
t = so and sr or tr\
ttype = type(t)\
end -- new value falls through to be serialized\
end\
if ttype == \"table\" then\
if level >= maxl then return tag..'{}'..comment('maxlvl', level) end\
seen[t] = insref or spath\
if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty\
if maxlen and maxlen < 0 then return tag..'{}'..comment('maxlen', level) end\
local maxn, o, out = math.min(#t, maxnum or #t), {}, {}\
for key = 1, maxn do o[key] = key end\
if not maxnum or #o < maxnum then\
local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables\
for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end\
if maxnum and #o > maxnum then o[maxnum+1] = nil end\
if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end\
local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output)\
for n, key in ipairs(o) do\
local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse\
if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing\
or opts.keyallow and not opts.keyallow[key]\
or opts.keyignore and opts.keyignore[key]\
or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types\
or sparse and value == nil then -- skipping nils; do nothing\
elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then\
if not seen[key] and not globals[key] then\
sref[#sref+1] = 'placeholder'\
local sname = safename(iname, gensym(key)) -- iname is table for local variables\
sref[#sref] = val2str(key,sname,indent,sname,iname,true) end\
sref[#sref+1] = 'placeholder'\
local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']'\
sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path))\
else\
out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1)\
if maxlen then\
maxlen = maxlen - #out[#out]\
if maxlen < 0 then break end\
end\
end\
end\
local prefix = string.rep(indent or '', level)\
local head = indent and '{\\n'..prefix..indent or '{'\
local body = table.concat(out, ','..(indent and '\\n'..prefix..indent or space))\
local tail = indent and \"\\n\"..prefix..'}' or '}'\
return (custom and custom(tag,head,body,tail,level) or tag..head..body..tail)..comment(t, level)\
elseif badtype[ttype] then\
seen[t] = insref or spath\
return tag..globerr(t, level)\
elseif ttype == 'function' then\
seen[t] = insref or spath\
if opts.nocode then return tag..\"function() --[[..skipped..]] end\"..comment(t, level) end\
local ok, res = pcall(string.dump, t)\
local func = ok and \"((loadstring or load)(\"..safestr(res)..\",'@serialized'))\"..comment(t, level)\
return tag..(func or globerr(t, level))\
else return tag..safestr(t) end -- handle all other types\
end\
local sepr = indent and \"\\n\" or \";\"..space\
local body = val2str(t, name, indent) -- this call also populates sref\
local tail = #sref>1 and table.concat(sref, sepr)..sepr or ''\
local warn = opts.comment and #sref>1 and space..\"--[[incomplete output with shared/self-references skipped]]\" or ''\
return not name and body..warn or \"do local \"..body..sepr..tail..\"return \"..name..sepr..\"end\"\
end\
\
local function deserialize(data, opts)\
local env = (opts and opts.safe == false) and G\
or setmetatable({}, {\
__index = function(t,k) return t end,\
__call = function(t,...) error(\"cannot call functions\") end\
})\
local f, res = (loadstring or load)('return '..data, nil, nil, env)\
if not f then f, res = (loadstring or load)(data, nil, nil, env) end\
if not f then return f, res end\
if setfenv then setfenv(f, env) end\
return pcall(f)\
end\
\
local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end\
\
exports._NAME = n\
exports._COPYRIGHT = c\
exports._DESCRIPTION = d\
exports._VERSION = v\
exports.serialize = s\
exports.load = deserialize\
\
exports.dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end\
exports.line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end\
exports.block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end",
['rxi/json/main'] = "--\
-- json.lua\
--\
-- Copyright (c) 2018 rxi\
--\
-- 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.\
--\
\
exports._version = \"0.1.1\"\
\
-------------------------------------------------------------------------------\
-- Encode\
-------------------------------------------------------------------------------\
\
local encode\
\
local escape_char_map = {\
[ \"\\\\\" ] = \"\\\\\\\\\",\
[ \"\\\"\" ] = \"\\\\\\\"\",\
[ \"\\b\" ] = \"\\\\b\",\
[ \"\\f\" ] = \"\\\\f\",\
[ \"\\n\" ] = \"\\\\n\",\
[ \"\\r\" ] = \"\\\\r\",\
[ \"\\t\" ] = \"\\\\t\",\
}\
\
local escape_char_map_inv = { [ \"\\\\/\" ] = \"/\" }\
for k, v in pairs(escape_char_map) do\
escape_char_map_inv[v] = k\
end\
\
\
local function escape_char(c)\
return escape_char_map[c] or string.format(\"\\\\u%04x\", c:byte())\
end\
\
\
local function encode_nil(val)\
return \"null\"\
end\
\
\
local function encode_table(val, stack)\
local res = {}\
stack = stack or {}\
\
-- Circular reference?\
if stack[val] then error(\"circular reference\") end\
\
stack[val] = true\
\
if val[1] ~= nil or next(val) == nil then\
-- Treat as array -- check keys are valid and it is not sparse\
local n = 0\
for k in pairs(val) do\
if type(k) ~= \"number\" then\
error(\"invalid table: mixed or invalid key types\")\
end\
n = n + 1\
end\
if n ~= #val then\
error(\"invalid table: sparse array\")\
end\
-- Encode\
for i, v in ipairs(val) do\
table.insert(res, encode(v, stack))\
end\
stack[val] = nil\
return \"[\" .. table.concat(res, \",\") .. \"]\"\
\
else\
-- Treat as an object\
for k, v in pairs(val) do\
if type(k) ~= \"string\" then\
error(\"invalid table: mixed or invalid key types\")\
end\
table.insert(res, encode(k, stack) .. \":\" .. encode(v, stack))\
end\
stack[val] = nil\
return \"{\" .. table.concat(res, \",\") .. \"}\"\
end\
end\
\
\
local function encode_string(val)\
return '\"' .. val:gsub('[%z\\1-\\31\\\\\"]', escape_char) .. '\"'\
end\
\
\
local function encode_number(val)\
-- Check for NaN, -inf and inf\
if val ~= val or val <= -math.huge or val >= math.huge then\
error(\"unexpected number value '\" .. tostring(val) .. \"'\")\
end\
return string.format(\"%.14g\", val)\
end\
\
\
local type_func_map = {\
[ \"nil\" ] = encode_nil,\
[ \"table\" ] = encode_table,\
[ \"string\" ] = encode_string,\
[ \"number\" ] = encode_number,\
[ \"boolean\" ] = tostring,\
}\
\
\
encode = function(val, stack)\
local t = type(val)\
local f = type_func_map[t]\
if f then\
return f(val, stack)\
end\
error(\"unexpected type '\" .. t .. \"'\")\
end\
\
\
function exports.encode(val)\
return ( encode(val) )\
end\
\
\
-------------------------------------------------------------------------------\
-- Decode\
-------------------------------------------------------------------------------\
\
local parse\
\
local function create_set(...)\
local res = {}\
for i = 1, select(\"#\", ...) do\
res[ select(i, ...) ] = true\
end\
return res\
end\
\
local space_chars = create_set(\" \", \"\\t\", \"\\r\", \"\\n\")\
local delim_chars = create_set(\" \", \"\\t\", \"\\r\", \"\\n\", \"]\", \"}\", \",\")\
local escape_chars = create_set(\"\\\\\", \"/\", '\"', \"b\", \"f\", \"n\", \"r\", \"t\", \"u\")\
local literals = create_set(\"true\", \"false\", \"null\")\
\
local literal_map = {\
[ \"true\" ] = true,\
[ \"false\" ] = false,\
[ \"null\" ] = nil,\
}\
\
\
local function next_char(str, idx, set, negate)\
for i = idx, #str do\
if set[str:sub(i, i)] ~= negate then\
return i\
end\
end\
return #str + 1\
end\
\
\
local function decode_error(str, idx, msg)\
local line_count = 1\
local col_count = 1\
for i = 1, idx - 1 do\
col_count = col_count + 1\
if str:sub(i, i) == \"\\n\" then\
line_count = line_count + 1\
col_count = 1\
end\
end\
error( string.format(\"%s at line %d col %d\", msg, line_count, col_count) )\
end\
\
\
local function codepoint_to_utf8(n)\
-- http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=iws-appendixa\
local f = math.floor\
if n <= 0x7f then\
return string.char(n)\
elseif n <= 0x7ff then\
return string.char(f(n / 64) + 192, n % 64 + 128)\
elseif n <= 0xffff then\
return string.char(f(n / 4096) + 224, f(n % 4096 / 64) + 128, n % 64 + 128)\
elseif n <= 0x10ffff then\
return string.char(f(n / 262144) + 240, f(n % 262144 / 4096) + 128,\
f(n % 4096 / 64) + 128, n % 64 + 128)\
end\
error( string.format(\"invalid unicode codepoint '%x'\", n) )\
end\
\
\
local function parse_unicode_escape(s)\
local n1 = tonumber( s:sub(3, 6), 16 )\
local n2 = tonumber( s:sub(9, 12), 16 )\
-- Surrogate pair?\
if n2 then\
return codepoint_to_utf8((n1 - 0xd800) * 0x400 + (n2 - 0xdc00) + 0x10000)\
else\
return codepoint_to_utf8(n1)\
end\
end\
\
\
local function parse_string(str, i)\
local has_unicode_escape = false\
local has_surrogate_escape = false\
local has_escape = false\
local last\
for j = i + 1, #str do\
local x = str:byte(j)\
\
if x < 32 then\
decode_error(str, j, \"control character in string\")\
end\
\
if last == 92 then -- \"\\\\\" (escape char)\
if x == 117 then -- \"u\" (unicode escape sequence)\
local hex = str:sub(j + 1, j + 5)\
if not hex:find(\"%x%x%x%x\") then\
decode_error(str, j, \"invalid unicode escape in string\")\
end\
if hex:find(\"^[dD][89aAbB]\") then\
has_surrogate_escape = true\
else\
has_unicode_escape = true\
end\
else\
local c = string.char(x)\
if not escape_chars[c] then\
decode_error(str, j, \"invalid escape char '\" .. c .. \"' in string\")\
end\
has_escape = true\
end\
last = nil\
\
elseif x == 34 then -- '\"' (end of string)\
local s = str:sub(i + 1, j - 1)\
if has_surrogate_escape then\
s = s:gsub(\"\\\\u[dD][89aAbB]..\\\\u....\", parse_unicode_escape)\
end\
if has_unicode_escape then\
s = s:gsub(\"\\\\u....\", parse_unicode_escape)\
end\
if has_escape then\
s = s:gsub(\"\\\\.\", escape_char_map_inv)\
end\
return s, j + 1\
\
else\
last = x\
end\
end\
decode_error(str, i, \"expected closing quote for string\")\
end\
\
\
local function parse_number(str, i)\
local x = next_char(str, i, delim_chars)\
local s = str:sub(i, x - 1)\
local n = tonumber(s)\
if not n then\
decode_error(str, i, \"invalid number '\" .. s .. \"'\")\
end\
return n, x\
end\
\
\
local function parse_literal(str, i)\
local x = next_char(str, i, delim_chars)\
local word = str:sub(i, x - 1)\
if not literals[word] then\
decode_error(str, i, \"invalid literal '\" .. word .. \"'\")\
end\
return literal_map[word], x\
end\
\
\
local function parse_array(str, i)\
local res = {}\
local n = 1\
i = i + 1\
while 1 do\
local x\
i = next_char(str, i, space_chars, true)\
-- Empty / end of array?\
if str:sub(i, i) == \"]\" then\
i = i + 1\
break\
end\
-- Read token\
x, i = parse(str, i)\
res[n] = x\
n = n + 1\
-- Next token\
i = next_char(str, i, space_chars, true)\
local chr = str:sub(i, i)\
i = i + 1\
if chr == \"]\" then break end\
if chr ~= \",\" then decode_error(str, i, \"expected ']' or ','\") end\
end\
return res, i\
end\
\
\
local function parse_object(str, i)\
local res = {}\
i = i + 1\
while 1 do\
local key, val\
i = next_char(str, i, space_chars, true)\
-- Empty / end of object?\
if str:sub(i, i) == \"}\" then\
i = i + 1\
break\
end\
-- Read key\
if str:sub(i, i) ~= '\"' then\
decode_error(str, i, \"expected string for key\")\
end\
key, i = parse(str, i)\
-- Read ':' delimiter\
i = next_char(str, i, space_chars, true)\
if str:sub(i, i) ~= \":\" then\
decode_error(str, i, \"expected ':' after key\")\
end\
i = next_char(str, i + 1, space_chars, true)\
-- Read value\
val, i = parse(str, i)\
-- Set\
res[key] = val\
-- Next token\
i = next_char(str, i, space_chars, true)\
local chr = str:sub(i, i)\
i = i + 1\
if chr == \"}\" then break end\
if chr ~= \",\" then decode_error(str, i, \"expected '}' or ','\") end\
end\
return res, i\
end\
\
\
local char_func_map = {\
[ '\"' ] = parse_string,\
[ \"0\" ] = parse_number,\
[ \"1\" ] = parse_number,\
[ \"2\" ] = parse_number,\
[ \"3\" ] = parse_number,\
[ \"4\" ] = parse_number,\
[ \"5\" ] = parse_number,\
[ \"6\" ] = parse_number,\
[ \"7\" ] = parse_number,\
[ \"8\" ] = parse_number,\
[ \"9\" ] = parse_number,\
[ \"-\" ] = parse_number,\
[ \"t\" ] = parse_literal,\
[ \"f\" ] = parse_literal,\
[ \"n\" ] = parse_literal,\
[ \"[\" ] = parse_array,\
[ \"{\" ] = parse_object,\
}\
\
\
parse = function(str, idx)\
local chr = str:sub(idx, idx)\
local f = char_func_map[chr]\
if f then\
return f(str, idx)\
end\
decode_error(str, idx, \"unexpected character '\" .. chr .. \"'\")\
end\
\
\
function exports.decode(str)\
if type(str) ~= \"string\" then\
error(\"expected argument of type string, got \" .. type(str))\
end\
local res, idx = parse(str, next_char(str, 1, space_chars, true))\
idx = next_char(str, idx, space_chars, true)\
if idx <= #str then\
decode_error(str, idx, \"trailing garbage\")\
end\
return res\
end",
}, ...) |
ATTRIBUTE.name = "Magic Power"
ATTRIBUTE.desc = "Increases Magic Power and Mana regen."
ATTRIBUTE.maxValue = 100
ATTRIBUTE.noStartBonus = false
function ATTRIBUTE:onSetup(client, value)
end |
LinkLuaModifier( "modifier_item_shivas_guard_thinker", LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( "modifier_item_shivas_cuirass", "items/shivas_cuirass.lua",LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( "modifier_item_shivas_cuirass_aura", "items/shivas_cuirass.lua",LUA_MODIFIER_MOTION_NONE )
--------------------------------------------------------------------------------
item_shivas_cuirass = class(ItemBaseClass)
function item_shivas_cuirass:GetIntrinsicModifierName()
return "modifier_item_shivas_cuirass"
end
function item_shivas_cuirass:OnSpellStart()
local hCaster = self:GetCaster()
hCaster:EmitSound( "DOTA_Item.ShivasGuard.Activate" )
CreateModifierThinker( hCaster, self, "modifier_item_shivas_guard_thinker", nil, hCaster:GetAbsOrigin(), hCaster:GetTeamNumber(), false )
end
--------------------------------------------------------------------------------
item_shivas_cuirass_2 = item_shivas_cuirass --luacheck: ignore item_shivas_cuirass_2
--------------------------------------------------------------------------------
modifier_item_shivas_cuirass = class(ModifierBaseClass)
function modifier_item_shivas_cuirass:OnCreated()
self.bonus_intellect = self:GetAbility():GetSpecialValueFor( "bonus_intellect" )
self.bonus_armor = self:GetAbility():GetSpecialValueFor( "bonus_armor" )
self.bonus_attack_speed = self:GetAbility():GetSpecialValueFor( "bonus_attack_speed" )
self.aura_radius = self:GetAbility():GetSpecialValueFor( "aura_radius" )
end
function modifier_item_shivas_cuirass:IsHidden()
return true
end
function modifier_item_shivas_cuirass:IsAura()
return true
end
function modifier_item_shivas_cuirass:IsPurgable()
return false
end
function modifier_item_shivas_cuirass:GetAuraRadius()
return self.aura_radius
end
function modifier_item_shivas_cuirass:GetAuraSearchTeam()
return DOTA_UNIT_TARGET_TEAM_BOTH
end
function modifier_item_shivas_cuirass:GetAuraSearchType()
return DOTA_UNIT_TARGET_ALL
end
function modifier_item_shivas_cuirass:GetModifierAura()
return "modifier_item_shivas_cuirass_aura"
end
function modifier_item_shivas_cuirass:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
MODIFIER_PROPERTY_PHYSICAL_ARMOR_BONUS,
MODIFIER_PROPERTY_STATS_INTELLECT_BONUS,
}
return funcs
end
function modifier_item_shivas_cuirass:GetModifierAttackSpeedBonus_Constant()
return self.bonus_attack_speed
end
function modifier_item_shivas_cuirass:GetModifierPhysicalArmorBonus()
return self.bonus_armor
end
function modifier_item_shivas_cuirass:GetModifierBonusStats_Intellect()
return self.bonus_intellect
end
--------------------------------------------------------------------------------
modifier_item_shivas_cuirass_aura = class(ModifierBaseClass)
function modifier_item_shivas_cuirass_aura:OnCreated()
self.aura_attack_speed = self:GetAbility():GetSpecialValueFor( "aura_attack_speed" )
self.aura_attack_speed_bonus = self:GetAbility():GetSpecialValueFor( "aura_attack_speed_bonus" )
self.aura_positive_armor = self:GetAbility():GetSpecialValueFor( "aura_positive_armor" )
self.aura_negative_armor = self:GetAbility():GetSpecialValueFor( "aura_negative_armor" )
end
function modifier_item_shivas_cuirass_aura:IsDebuff()
if self:GetCaster():GetTeamNumber() ~= self:GetParent():GetTeamNumber() then
return true
end
return false
end
function modifier_item_shivas_cuirass_aura:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
MODIFIER_PROPERTY_PHYSICAL_ARMOR_BONUS,
}
return funcs
end
function modifier_item_shivas_cuirass_aura:GetModifierAttackSpeedBonus_Constant()
if self:GetCaster():GetTeamNumber() ~= self:GetParent():GetTeamNumber() then
return self.aura_attack_speed
end
return self.aura_attack_speed_bonus
end
function modifier_item_shivas_cuirass_aura:GetModifierPhysicalArmorBonus()
if self:GetCaster():GetTeamNumber() ~= self:GetParent():GetTeamNumber() then
return self.aura_negative_armor
end
return self.aura_positive_armor
end
--------------------------------------------------------------------------------
|
--[[
Copyright 2014 Google Inc. All Rights Reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file or at
https://developers.google.com/open-source/licenses/bsd
]]
require 'torch'
require 'image'
local M = {}
-- Copies values from src to dst.
local function update(dst, src)
for k, v in pairs(src) do
dst[k] = v
end
end
-- Copies the config. An error is raised on unknown params.
local function updateDefaults(dst, src)
for k, v in pairs(src) do
if dst[k] == nil then
error("unsupported param: " .. k)
end
end
update(dst, src)
end
local function loadDataset(path)
local dataset = torch.load(path)
dataset.data = dataset.data:type(torch.Tensor():type())
collectgarbage()
dataset.data:mul(1/dataset.data:max())
if dataset.data[1]:dim() ~= 3 then
local sideLen = math.sqrt(dataset.data[1]:nElement())
dataset.data = dataset.data:view(dataset.data:size(1), 1, sideLen, sideLen)
end
assert(dataset.labels:min() == 0, "expecting zero-based labels")
return dataset
end
-- Return a list with pointers to selected examples.
local function selectSamples(examples, nSamples)
local nExamples = examples:size(1)
local samples = {}
for i = 1, nSamples do
samples[i] = examples[torch.random(1, nExamples)]
end
return samples
end
-- Returns a map from {smallerDigit, biggerOrEqualDigit}
-- to an input in the softmax output.
local function createIndexMap(n, k)
assert(k == 2, "expecting k=2")
local indexMap = torch.Tensor(n, n):fill(0/0)
local nextIndex = 1
for i = 1, n do
for j = i, n do
indexMap[i][j] = nextIndex
nextIndex = nextIndex + 1
end
end
assert(k == 2 and nextIndex - 1 == (n * (n + 1))/2, "wrong count for k=2")
return indexMap
end
-- The task is a classification of MNIST digits.
-- Each training example has a MNIST digit placed on a bigger black background.
function M.createData(extraConfig)
local config = {
datasetPath = 'mnist/train.t7',
-- The size of the background.
megapatch_w = 28,
-- The width of a black border.
border = 0,
-- The number of digits in on image.
nDigits = 1,
-- The number of digit classes.
nClasses = 10,
-- The threshold for digit classes.
threshold = 0.1,
-- The range for rescaling digit.
scale = {0.9,1.1},
-- The angle for rotation.
angle = 0,
-- The angle for affine transform.
affine_angle = 0,
-- The random seed.
seed = 100,
-- The task.
task = 'segmentation',
}
updateDefaults(config, extraConfig)
torch.manualSeed(config.seed)
local dataset = loadDataset(config.datasetPath)
assert(dataset.labels:max() < config.nClasses, "expecting labels from {0, .., nClasses - 1}")
local task = require 'utils/task'
local function nextExample()
local results = task(config, dataset)
return results
end
return {
nextExample = nextExample,
}
end
return M
|
object_mobile_dressed_meatlump_hideout_female_03 = object_mobile_shared_dressed_meatlump_hideout_female_03:new {
}
ObjectTemplates:addTemplate(object_mobile_dressed_meatlump_hideout_female_03, "object/mobile/dressed_meatlump_hideout_female_03.iff")
|
require "scriptlets-driver.juju"
framework = Juju:new()
function pre_install_scriptlet(model, event)
current_config = model:load_config()
for u in list_iter(model.units) do
u.open_port(80, current_config.service_port)
end
-- model.set_application_port(4080)
end
function post_start_scriptlet(model, event)
local version = "1.0"
framework:set_application_version(version)
end
framework:register_scriptlet(events.preInstall, "change port", pre_install_scriptlet())
framework:register_scriptlet(events.postStart, "set version", post_start_scriptlet())
|
-- Use <Tab> and <S-Tab> to navigate through popup menu
vim.api.nvim_set_keymap('i', '<Tab>', 'pumvisible() ? "\\<C-n>" : "\\<Tab>"', {expr = true})
vim.api.nvim_set_keymap('i', '<S-Tab>', 'pumvisible() ? "\\<C-p>" : "\\<Tab>"', {expr = true})
-- Set completeopt to have a better completion experience
vim.o.completeopt="menuone,noinsert,noselect"
-- possible value: 'UltiSnips', 'Neosnippet', 'vim-vsnip', 'snippets.nvim'
vim.g.completion_enable_snippet="UltiSnips"
-- Avoid showing message extra message when using completion
vim.o.shortmess = vim.o.shortmess .. "c"
require'lspconfig'.pyright.setup{on_attach=require'completion'.on_attach}
require'lspconfig'.clangd.setup{on_attach=require'completion'.on_attach}
|
function isReturnHome()
local emptySlot = 0;
for i=1, 16 do
if(turtle.getItemCount(i) == 0) then emptySlot = emptySlot + 1 end
end
if(emptySlot <= 0)then return true
else return false
end
end
function returnToHome(z)
for cz=1, z do
upTurtle()
end
end
function returnToCurrentZ(z)
for cz=1, z do
downTurtle()
end
end
function dropAllInventory()
turtle.turnLeft()
turtle.turnLeft()
for i=1, 16 do
turtle.select(i)
if (turtle.refuel(0) == false) then turtle.drop() end
end
turtle.turnLeft()
turtle.turnLeft()
end |
require("harpoon").setup({
projects = {
["/home/theprimeagen/personal/harpoon/{}"] = {
term = {
cmds = {
"echo hello {}"
}
},
},
["/home/theprimeagen/work/nrdp/{}"] = {
term = {
cmds = {
"ninja -C /home/theprimeagen/work/nrdp/builds/{} -j 25 && cp compile_commands.json /home/theprimeagen/work/nrdp/{}\n",
}
}
}
}
})
|
function GM:AddNotify( str, type, length )
notification.AddLegacy( str, type, length )
end
function GM:PaintNotes()
end
|
local php = {}
-- php -r 'var_dump(array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES | ENT_HTML5, "UTF-8")));'
php.getEntityTable = function() return entitytable end
-- see [https://github.com/wikimedia/mediawiki/blob/master/includes/parser/StripState.php], but we don't have Parser.php, no need to unstrip
php.unstrip = function(s) return s end
php.unstripNoWiki = function(s) return s end
php.killMarkers = function(s) return s end
local jsonlib = require("php.lib.json") -- [http://regex.info/blog/lua/json]
--[=[
mwtext.JSON_PRESERVE_KEYS = 1 -- ignored
mwtext.JSON_TRY_FIXING = 2 -- decode
mwtext.JSON_PRETTY = 4 -- encode
]=]
php.jsonEncode = function(value, flags)
local t = {}
if type(flags) ~= 'number' or flags ~= flags then flags = 0 else flags = math.max(0, math.min(7, flags)) end
if flags >= 4 then flags = flags - 4; t.pretty = true end
if flags >= 2 then flags = flags - 2 end
if flags >= 1 then flags = flags - 1; t.JSON_PRESERVE_KEYS = true end
return jsonlib:encode(value, nil, t)
end
php.jsonDecode = function(json, flags)
local t = {}
if type(flags) ~= 'number' or flags ~= flags then flags = 0 else flags = math.max(0, math.min(7, flags)) end
if flags >= 4 then flags = flags - 4 end
if flags >= 2 then flags = flags - 2; t.JSON_TRY_FIXING = true end
if flags >= 1 then flags = flags - 1; t.JSON_PRESERVE_KEYS = true end
return jsonlib:decode(json, nil, t)
end
php.optszh = {
["comma"]="、", -- MediaWiki:comma-separator
["and"]="和", -- MediaWiki:and + MediaWiki:word-separator
["ellipsis"]="…", -- MediaWiki:ellipsis
["nowiki_protocols"]={ ['[Bb][Ii][Tt][Cc][Oo][Ii][Nn]:']='%1:', ['[Gg][Ee][Oo]:']='%1:', ['[Mm][Aa][Gg][Nn][Ee][Tt]:']='%1:', ['[Mm][Aa][Ii][Ll][Tt][Oo]:']='%1:', ['[Nn][Ee][Ww][Ss]:']='%1:', ['[Ss][Ii][Pp]:']='%1:', ['[Ss][Ii][Pp][Ss]:']='%1:', ['[Ss][Mm][Ss]:']='%1:', ['[Tt][Ee][Ll]:']='%1:', ['[Uu][Rr][Nn]:']='%1:', ['[Xx][Mm][Pp][Pp]:']='%1:', }, -- mw:Manual:$wgUrlProtocols
}
php.optsen = {
["comma"]=", ", -- MediaWiki:comma-separator
["and"]=" and ", -- MediaWiki:and + MediaWiki:word-separator
["ellipsis"]="...", -- MediaWiki:ellipsis
["nowiki_protocols"]={ ['[Bb][Ii][Tt][Cc][Oo][Ii][Nn]:']='%1:', ['[Gg][Ee][Oo]:']='%1:', ['[Mm][Aa][Gg][Nn][Ee][Tt]:']='%1:', ['[Mm][Aa][Ii][Ll][Tt][Oo]:']='%1:', ['[Nn][Ee][Ww][Ss]:']='%1:', ['[Ss][Ii][Pp]:']='%1:', ['[Ss][Ii][Pp][Ss]:']='%1:', ['[Ss][Mm][Ss]:']='%1:', ['[Tt][Ee][Ll]:']='%1:', ['[Uu][Rr][Nn]:']='%1:', ['[Xx][Mm][Pp][Pp]:']='%1:', }, -- mw:Manual:$wgUrlProtocols
}
local entitytable = mw.phpdata.entitytable
php.opts = php.optszh
return php
|
local ServerStorage = game:GetService("ServerStorage")
local MonsterDictionary = require(ServerStorage.Monster.MonsterDictionary)
local MonsterBlocks = ServerStorage.MonsterBlocks.MonsterBlock
local RunSerivce = game:GetService("RunService")
local SignalEvent = require(ServerStorage.Utility.SignalEvent)
local CollectionService = game:GetService("CollectionService")
local MonsterBehavior = require(ServerStorage.Monster.MonsterBehavior)
local Monster = {}
Monster.__index = Monster
function Monster.new(monsterBlock, parentRoom)
local newMonster = {}
local self = setmetatable(newMonster, Monster)
--We have to assume that we're being given a valid "monster block" here
--This means it has a certain set of attributes associated with it as well
self.health = monsterBlock:GetAttribute("Health")
self.moveSpeed = monsterBlock:GetAttribute("MoveSpeed")
local newMons = MonsterDictionary["1"]["Model"]:Clone()
self.monsterModel = newMons
--Things that should only be read once we have an actual model
self.monsterHumanoid = self.monsterModel:FindFirstChild("Humanoid")
self.monsterHumanoidHealth = self.monsterHumanoid.Health
self.parentRoom = parentRoom
self.HRP = self.monsterModel:FindFirstChild("HumanoidRootPart")
--For orienting the monster correctly
self.alignOrientation = self.HRP:FindFirstChild("AlignOrientation")
self.worldAttachment = Instance.new("Attachment")
self.worldAttachment.Name = "MonsterAlignAttachment"
self.worldAttachment.Parent = workspace.Terrain
self.alignOrientation.Attachment1 = self.worldAttachment
self.target = nil
self.searchRadius = monsterBlock:GetAttribute("SearchRadius")
self.searchRegion = nil
self.searchingForTarget = true
--Connections for signals
self.ConnectionTable = {}
--These are all the possible states a monster could be in that are useful to connect specific behaviors to
self.SearchForPlayerConnection = SignalEvent.new(self)
self.FoundPlayerConnection = SignalEvent.new(self)
self.InRangeToAttackConnection = SignalEvent.new(self)
self.InRangeToFireProjectileConnection = SignalEvent.new(self)
self.DiedConnection = SignalEvent.new(self)
self.AtSpecificHealthConnection = SignalEvent.new(self)
self.runServiceConnection = nil --This will be connected later....
self.monsterHumanoid.Died:Connect(function()
print("I have died!")
self.parentRoom.MonsterCount.Value = self.parentRoom.MonsterCount.Value - 1
self.runServiceConnection:Disconnect()
self:CleanUp()
end)
CollectionService:AddTag(self.monsterModel, "Monster")
return self
end
function Monster:Spawn(whereToSpawn)
local a = coroutine.wrap(function()
self.monsterModel:SetPrimaryPartCFrame(whereToSpawn)
self.monsterModel.Parent = workspace
self.FoundPlayerConnection:AddNewSignal(MonsterBehavior["MoveTowardsTarget"])
self.FoundPlayerConnection:AddNewSignal(MonsterBehavior["Jump"])
--self.FoundPlayerConnection:AddNewSignal(MonsterBehavior["WindupAttack"])
self:Activate()
wait(5)
self.monsterModel.PrimaryPart.BrickColor = BrickColor.new("Black")
self.monsterModel.Humanoid:TakeDamage(100)
print("Monster should be dead now!")
end)
a()
end
function Monster:OnRunService()
--This is where different behaviors should be defined....
--Roaming, searching, hiding, jumping, etc...
--Then within this behavior there can be other options as well...
--[[
if self.target == nil and self.searchingForTarget then
self:SearchForPlayerInRange()
else
print("Target found: ", self.target.Name)
self.searchingForTarget = false
--self.FoundPlayerConnection:Fire()
end
]]
--wait(0.25)
if self.searchingForTarget then
self:SearchForPlayerInRange()
else
self.FoundPlayerConnection:Fire()
self.alignOrientation.Enabled = true
self.worldAttachment.CFrame = CFrame.new(self.HRP.Position, self.target.HumanoidRootPart.Position)
end
end
--This function begins the process of the monsters AI, such as searching for the players and doing various actions
function Monster:Activate()
self.runServiceConnection = RunSerivce.Heartbeat:Connect(function()
self:OnRunService()
end)
end
function Monster:SearchForPlayerInRange()
self.SearchForPlayerConnection:Fire()
local center = self.HRP.Position
local topCorner = center + Vector3.new(self.searchRadius, self.searchRadius, self.searchRadius)
local bottomCorner = center + Vector3.new(-self.searchRadius, -self.searchRadius, -self.searchRadius)
self.searcingForPlayer = true
self.searchRegion = Region3.new(bottomCorner, topCorner)
local searchParts = workspace:FindPartsInRegion3(self.searchRegion, self.monsterModel)
--[[
local part = Instance.new("Part")
part.Anchored = true
part.CanCollide = false
part.Size = self.searchRegion.Size
part.CFrame = self.searchRegion.CFrame
part.Transparency = 0.95
part.Parent = workspace
]]
print("Attempting to locate player in my range... ")
for i, part in pairs(searchParts) do
if
--Conditions for a player being a valid target
part.Parent:FindFirstChild("Humanoid") and not
CollectionService:HasTag(part.Parent, "Monster")
then
--We've found a player
self.target = part.Parent
self.searchingForTarget = false
print("Found a target as: ", self.target.Name)
self.FoundPlayerConnection:Fire()
end
end
end
function Monster:MoveTowardsTarget()
print("Attempting to move towards target: ", self.target.Name)
self.monsterHumanoid:MoveTo(self.target)
end
function Monster:CleanUp()
self.runServiceConnection = nil
for i, connection in pairs(self.ConnectionTable) do
connection:ClearConnectionTable()
self.ConnectionTable[i] = nil
end
self.runServiceConnection = nil
self.target = nil
self.searchingForTarget = nil
self.monsterModel:Destroy()
self.alignOrientation:Destroy()
self.worldAttachment:Destroy()
end
return Monster
|
local HallCommonHeadItemButton = class(Button, false);
HallCommonHeadItemButton.ctor = function(self, data, index, isNeedTip)
super(self, "hall/common/bg_blank.png");
self.m_imgFiles = data.imgFiles;
self.m_text = data.text;
self.m_index = index;
self.m_isNeedTip = isNeedTip;
local w,h = 195,118;
self:setSize(w,h);
if not table.isEmpty(self.m_imgFiles) then
self.m_showType = 1;
else
self.m_showType = 2;
end
self:init();
end
HallCommonHeadItemButton.dtor = function(self )
end
HallCommonHeadItemButton.init = function(self)
self.m_selBg = UIFactory.createImage("hall/common/tab_bg_sel.png");
self:addChild(self.m_selBg);
self.m_selBg:setAlign(kAlignTop);
self.m_selBg:setVisible(false);
--self.m_selBg:setPos(0,-11);
if self.m_showType == 1 then
--图片
self.m_titleImg = UIFactory.createImage(self.m_imgFiles[1]);
self:addChild(self.m_titleImg);
self.m_titleImg:setAlign(kAlignCenter);
self.m_titleImg:setPos(0,-11);
else
self.m_textView = UIFactory.createText(self.m_text or "", 36);
self:addChild(self.m_textView);
self.m_textView:setAlign(kAlignCenter);
self.m_textView:setPos(0,-11);
end
if self.m_isNeedTip then
self.m_tipImg = UIFactory.createImage("hall/common/new_msg_icon.png");
self:addChild(self.m_tipImg);
self.m_tipImg:setAlign(kAlignTopRight);
self.m_tipImg:setPos(17,6);
end
end
HallCommonHeadItemButton.setChecked = function(self, bool)
self.m_isChecked = bool;
self:setFile(bool and "hall/common/bg_blank.png" or "");
self:setEnable(not bool);
self.m_selBg:setVisible(bool);
if bool then
self:setColor(255,255,255);
if self.m_tipImg then
self.m_tipImg:setVisible(false);
end
end
if self.m_showType == 1 then
--图片
self.m_titleImg:setFile(bool and self.m_imgFiles[2] or self.m_imgFiles[1])
else
local r,g,b = 255,255,255;
if bool then
r,g,b = 255,235,168;
end
self.m_textView:setText(self.m_text or "", 0,0,r,g,b);
end
end
HallCommonHeadItemButton.isChecked = function(self)
return self.m_isChecked;
end
HallCommonHeadItemButton.getIndex = function(self)
return self.m_index;
end
HallCommonHeadItemButton.setTipVisible = function(self, bool)
if self.m_tipImg then
self.m_tipImg:setVisible(bool);
end
end
local HallCommonHeadView = class(Node);
HallCommonHeadView.ctor = function(self, imageFiles, textMap, isNeedTip)
self.m_imageFiles = imageFiles;
self.m_textMap = textMap;
self.m_isNeedTip = isNeedTip;
self:initView();
end
HallCommonHeadView.dtor = function(self)
end
HallCommonHeadView.initView = function(self)
local w,h = 0,118;
if table.isEmpty(self.m_headMenuBtns) then
self.m_headMenuBtns = {};
local size = 0;
if not table.isEmpty(self.m_textMap) then
size = #self.m_textMap;
end
if not table.isEmpty(self.m_imageFiles) then
size = #self.m_imageFiles;
end
for index = 1,size do
local data = {};
if not table.isEmpty(self.m_imageFiles) then
data.imgFiles = self.m_imageFiles[index];
end
if not table.isEmpty(self.m_textMap) then
data.text = self.m_textMap[index]
end
local button = new(HallCommonHeadItemButton, data, index, self.m_isNeedTip);
self:addChild(button);
button:setPos((index - 1 ) * 195, 0);
button:setOnClick(button, function(btn1)
self:onMenuChanged(btn1:getIndex());
end);
self.m_headMenuBtns[index] = button;
w = w + 195;
if index < size then
local imageDivider = UIFactory.createImage("hall/common/tab_line.png");
local imageDividerW, _ = imageDivider:getSize();
imageDivider:setAlign(kAlignLeft);
imageDivider:setPos(index * 195 - imageDividerW / 2, -11);
imageDivider:setLevel(-1);
self:addChild(imageDivider);
--w = w + 2;
end
end
end
self:setSize(w,h);
self:setSelect(1);
end
HallCommonHeadView.onMenuChanged = function(self, index)
self:setSelect(index);
if self.m_menuIndexChangedObj and self.m_menuIndexChangedFunc then
self.m_menuIndexChangedFunc(self.m_menuIndexChangedObj, index);
end
end
HallCommonHeadView.setSelect = function(self, index)
if table.isEmpty(self.m_headMenuBtns) then
self:initView();
end
for k,v in pairs(self.m_headMenuBtns) do
if v then
v:setChecked(v:getIndex() == index);
end
end
end
HallCommonHeadView.getSelect = function(self)
if table.isEmpty(self.m_headMenuBtns) then
self:initView();
end
for k,v in pairs(self.m_headMenuBtns) do
if v and v:isChecked() then
return k;
end
end
end
HallCommonHeadView.setOnMenuIndexChanged = function(self, obj, func)
self.m_menuIndexChangedObj = obj;
self.m_menuIndexChangedFunc = func;
end
HallCommonHeadView.setTipVisible = function(self, index, bool)
for k,v in pairs(self.m_headMenuBtns) do
if v and v:getIndex() == index then
v:setTipVisible(bool);
end
end
end
return HallCommonHeadView; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.