content stringlengths 5 1.05M |
|---|
return {
id = "YONGYEHUANGUANG26",
mode = 2,
once = true,
fadeType = 1,
fadein = 1.5,
scripts = {
{
dir = 1,
side = 2,
bgm = "xinnong-4",
say = "巴伦支海·皇家支援舰队 稍早前",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
dir = 1,
side = 2,
say = "谢菲尔德在海面上一面灵巧地规避着炮火,一面向铁血主力舰队方的向疾驰着。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 202080,
side = 2,
nameColor = "#a9f548",
dir = 1,
say = "不太对劲,袭来的火力密度太小了…",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 403040,
side = 2,
nameColor = "#ff5c5c",
dir = 1,
say = "到此为止了,给我停下!",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 202080,
side = 2,
nameColor = "#a9f548",
dir = 1,
say = "德意志!?",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 403040,
side = 2,
nameColor = "#ff5c5c",
dir = 1,
say = "首先夸奖一下你的勇气吧,区区一艘轻巡洋舰就敢正面迎击我们的主力舰队!",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 403040,
side = 2,
nameColor = "#ff5c5c",
dir = 1,
say = "不过,如果让你靠过去对提尔比茨放鱼雷就麻烦了,就给我留在这里吧!",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 202080,
side = 2,
nameColor = "#a9f548",
dir = 1,
say = "啧,碍事!",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
},
action = {
{
type = "move",
y = 0,
delay = 0.5,
dur = 0.5,
x = 2500
}
}
},
{
expression = 4,
side = 2,
actor = 206060,
nameColor = "#a9f548",
dir = 1,
say = "终于追上你了…!没事吧,谢菲尔德?",
soundeffect = "event:/battle/plane",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
dir = 1,
side = 2,
soundeffect = "event:/battle/wave",
say = "英仙座适时赶来支援,然而舰载机投下的炸弹却穿过了德意志的身体,仅在空旷水面上激起空虚的浪花。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 202080,
nameColor = "#a9f548",
side = 0,
hideOther = true,
dir = 1,
actorName = "谢菲尔德&英仙座",
say = "什么……?!",
subActors = {
{
actor = 206060,
pos = {
x = 1185
}
}
},
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 403040,
side = 2,
nameColor = "#ff5c5c",
dir = 1,
say = "呵呵呵呵呵......哈哈哈哈哈哈哈哈哈哈哈!",
dialogShake = {
speed = 0.09,
x = 10,
number = 2
},
effects = {
{
active = true,
name = "speed"
}
},
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
paintingNoise = true,
nameColor = "#ff5c5c",
side = 2,
actor = 403040,
dir = 1,
say = "震惊吧,低等动物!我们铁血的科技可是世界第一!",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
dir = 1,
side = 2,
say = "伴随着一连串嚣张的笑声,德意志的身体逐渐变的透明,最后完全消失了。",
effects = {
{
active = false,
name = "speed"
}
},
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
dir = 1,
side = 2,
say = "几乎是在同一时间内,提尔比茨、沙恩霍斯特、格奈森瑙、斯佩伯爵......其余的铁血主力也如同幻影一般随着德意志一起消失了。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
dir = 1,
side = 2,
say = "原本庞大的铁血主力舰队,最后只剩零星的巡洋舰和驱逐舰孤零零地行驶在空旷的海面上——",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
expression = 4,
nameColor = "#a9f548",
side = 2,
actor = 206060,
dir = 1,
say = "铁血主力舰队…消失了?",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 201230,
side = 2,
nameColor = "#a9f548",
dir = 1,
say = "就连从雷达上也观测不到它们的信号了!",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 202080,
side = 2,
nameColor = "#a9f548",
dir = 1,
say = "…不但欺骗了雷达,还欺骗了我们的眼睛。铁血居然已经完成了我们尚且处于概念中的干扰设备么...",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
expression = 1,
nameColor = "#a9f548",
side = 2,
actor = 206060,
dir = 1,
say = "谢菲尔德的担心,成真了啊...",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 201230,
side = 2,
nameColor = "#a9f548",
dir = 1,
say = "等等…也就是,说铁血的主力舰队根本就没有到这里来,我们居然被几艘巡洋和驱逐追了这么远么?!",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
},
action = {
{
type = "shake",
y = 30,
delay = 0,
dur = 0.15,
x = 0,
number = 2
}
}
},
{
actor = 206060,
side = 2,
nameColor = "#a9f548",
dir = 1,
say = "…从结果上来说是这样的。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 202080,
side = 2,
nameColor = "#a9f548",
dir = 1,
say = "啧,真让人火大…",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 201230,
side = 2,
nameColor = "#a9f548",
dir = 1,
say = "哇哇…剩下的铁血舰队开始向我们靠过来了,这些应该都是真货了吧!",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 206060,
side = 2,
nameColor = "#a9f548",
dir = 1,
say = "简直像暴雨过后的田鼠……",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 201230,
nameColor = "#a9f548",
side = 0,
hideOther = true,
dir = 1,
actorName = "吸血鬼&谢菲尔德",
say = "…欸?",
subActors = {
{
actor = 202080,
pos = {
x = 1185
}
}
},
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
expression = 4,
nameColor = "#a9f548",
side = 2,
actor = 206060,
dir = 1,
say = "…立刻向司令部报告情况,然后…让我们开始战斗吧。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
}
}
}
|
GUIEditor = {
tab = {},
tabpanel = {},
label = {},
button = {},
window = {},
memo = {}
}
local screenW, screenH = guiGetScreenSize()
GUIEditor.window[1] = guiCreateWindow((screenW - 660) / 2, (screenH - 389) / 2, 660, 389, "AuroraRPG - Business", false)
guiWindowSetSizable(GUIEditor.window[1], false)
guiSetProperty(GUIEditor.window[1], "CaptionColour", "FF0B84FE")
GUIEditor.label[1] = guiCreateLabel(10, 26, 639, 15, "Business Information", false, GUIEditor.window[1])
guiSetFont(GUIEditor.label[1], "default-bold-small")
guiLabelSetHorizontalAlign(GUIEditor.label[1], "center", false)
GUIEditor.memo[1] = guiCreateMemo(10, 45, 630, 148, "Business Name: N/A\nBusiness Type: N/A\nBusiness Owner: N/A\nEarnings per hour: N/A\n\nAbout this business:\nN/A", false, GUIEditor.window[1])
guiMemoSetReadOnly(GUIEditor.memo[1], true)
GUIEditor.tabpanel[1] = guiCreateTabPanel(12, 198, 638, 164, false, GUIEditor.window[1])
GUIEditor.tab[1] = guiCreateTab("Options", GUIEditor.tabpanel[1])
GUIEditor.button[1] = guiCreateButton(241, 46, 140, 37, "Take Ownership", false, GUIEditor.tab[1])
GUIEditor.label[2] = guiCreateLabel(4, 87, 624, 15, "Price: $-----", false, GUIEditor.tab[1])
guiSetFont(GUIEditor.label[2], "default-bold-small")
guiLabelSetHorizontalAlign(GUIEditor.label[2], "center", false)
GUIEditor.label[3] = guiCreateLabel(4, 102, 624, 15, "This requires that you have a business.", false, GUIEditor.tab[1])
guiSetFont(GUIEditor.label[3], "default-bold-small")
guiLabelSetHorizontalAlign(GUIEditor.label[3], "center", false)
GUIEditor.tab[2] = guiCreateTab("Management", GUIEditor.tabpanel[1])
GUIEditor.button[2] = guiCreateButton(10, 45, 146, 33, "Sell this business", false, GUIEditor.tab[2])
GUIEditor.label[4] = guiCreateLabel(4, 88, 634, 15, "5 days without activity on this business then this business will be on sale.", false, GUIEditor.tab[2])
guiSetFont(GUIEditor.label[4], "default-bold-small")
guiLabelSetHorizontalAlign(GUIEditor.label[4], "center", false)
GUIEditor.label[5] = guiCreateLabel(4, 107, 634, 15, "Time to Restock: 0H 0M 0S", false, GUIEditor.tab[2])
guiSetFont(GUIEditor.label[5], "default-bold-small")
guiLabelSetHorizontalAlign(GUIEditor.label[5], "center", false)
GUIEditor.button[3] = guiCreateButton(10, 10, 146, 31, "Restock items", false, GUIEditor.tab[2])
GUIEditor.label[6] = guiCreateLabel(166, 20, 462, 15, "Items Required: 20x Item | 500x Item | 300x Item", false, GUIEditor.tab[2])
guiSetFont(GUIEditor.label[6], "default-bold-small")
GUIEditor.button[4] = guiCreateButton(511, 366, 129, 13, "Close", false, GUIEditor.window[1])
|
StatusMenu = StatusMenu or class()
function StatusMenu:init(parent, menu)
self._menu = menu:Menu({
name = "Status",
auto_foreground = true,
scrollbar = false,
visible = false,
w = 200,
h = 100,
})
local w = BLE.Options:GetValue("MapEditorPanelWidth")
self._text = self._menu:divider({name = "Text", text = "", text_align = "right"})
local gui_right = BLE.Options:GetValue("GUIOnRight")
self._menu:SetPosition(gui_right and menu:W() - w - 200 or w)
if BLE.Options:GetValue("ToolbarPosition") == 2 then
if gui_right then
self._menu:SetPosition(0)
else
self._menu:SetPosition(nil, BLE.Options:GetValue("QuickAccessToolbarSize"))
end
end
end
function StatusMenu:SetVisible(visible)
self._menu:SetVisible(visible)
end
function StatusMenu:SetStatus(status)
if not status then
self:SetVisible(false)
end
if status then
self._text:SetText(status)
end
end
function StatusMenu:ShowKeybindMessage(message)
if message then
self:SetVisible(true)
self._text:SetText(message)
BeardLib:AddDelayedCall("BLEStatusKeybindMessage", 2, function()
self:SetVisible(false)
end)
end
end
function StatusMenu:enabled() return true end |
---------------------- DIMENSIONAL PLANT ----------------------
-- Entity --
dpE = table.deepcopy(data.raw["assembling-machine"]["chemical-plant"])
dpE.name = "DimensionalPlant"
dpE.icon = "__Mobile_Factory_Graphics__/graphics/icons/DimensionalPlant.png"
dpE.icon_size = 32
dpE.icon_mipmaps = 1
dpE.minable = {mining_time = 0.3, result = "DimensionalPlant"}
dpE.crafting_categories = {"Elements"}
dpE.animation = make_4way_animation_from_spritesheet({
layers =
{
{
filename = "__Mobile_Factory_Graphics__/graphics/entity/DimensionalPlant.png",
width = 220,
height = 292,
frame_count = 24,
line_length = 12,
shift = util.by_pixel(0.5, -9),
scale = 0.5
},
{
filename = "__base__/graphics/entity/chemical-plant/hr-chemical-plant-shadow.png",
width = 312,
height = 222,
repeat_count = 24,
frame_count = 1,
shift = util.by_pixel(27, 6),
draw_as_shadow = true,
scale = 0.5
}
}})
data:extend{dpE}
-- Item --
local dpI = {}
dpI.type = "item"
dpI.name = "DimensionalPlant"
dpI.icon = "__Mobile_Factory_Graphics__/graphics/icons/DimensionalPlant.png"
dpI.icon_size = 32
dpI.place_result = "DimensionalPlant"
dpI.subgroup = "DimensionalStuff"
dpI.order = "f"
dpI.stack_size = 5
data:extend{dpI}
-- Recipe --
local dpR = {}
dpR.type = "recipe"
dpR.name = "DimensionalPlant"
dpR.energy_required = 5
dpR.enabled = false
dpR.ingredients =
{
{"DimensionalCircuit", 10},
{"MachineFrame2", 6},
}
dpR.result = "DimensionalPlant"
data:extend{dpR}
-- Technologie --
local dpT = {}
dpT.name = "DimensionalPlant"
dpT.type = "technology"
dpT.icon = "__Mobile_Factory_Graphics__/graphics/icons/DimensionalPlant.png"
dpT.icon_size = 32
dpT.unit = {
count=1200,
time=2,
ingredients={
{"DimensionalSample", 1}
}
}
dpT.prerequisites = {"DimensionalElectronic"}
dpT.effects = {{type="unlock-recipe", recipe="DimensionalPlant"}}
data:extend{dpT} |
local commands = require("commands")
local inputcommands = require("inputcommands")
local insertionSort = require("util.sort")
local gui = require("gui")
local message = require("message")
local input = require("input")
local sort = {}
function cmpKey(key, cmpFunc)
if cmpFunc then
return function(a, b)
return cmpFunc(a.columns[key], b.columns[key])
end
else
return function(a, b)
local va, vb = a.columns[key], b.columns[key]
assert(type(va) == type(vb))
if type(va) == "number" or type(va) == "boolean" then
return va < vb
elseif type(va) == "string" then
return va:lower() < vb:lower()
else
error("Cannot sort " .. type(va))
end
end
end
end
function sort.sort(by)
local tab = gui.getSelectedTab()
if tab then
assert(tab.columns)
local column = nil
if type(by) == "integer" then
column = tab.columns[by]
elseif type(by) == "string" then
column = tab:getColumnByKey(by)
if not column then
message.show(("Column '%s' is not present in this tab"):format(by))
return
end
else
message.show(("Unknown type for sort key '%s' (%s)"):format(type(by), tostring(by)), true)
return
end
insertionSort(tab.items, cmpKey(column.key, column.cmp))
end
end
commands.register("sort", commands.wrap(sort.sort, {"by"}), {"by"})
function sort.sortPrompt()
local tab = gui.getSelectedTab()
if tab and tab.columns then
local entries = {}
for i, column in ipairs(tab.columns) do
table.insert(entries, {
caption = column.key,
command = "sort",
arguments = {by = column.key},
})
end
input.toggle(entries, text)
end
end
commands.register("sortprompt", sort.sortPrompt)
inputcommands.register("Sort", "sortprompt")
return sort
|
local awful = require 'awful'
local naughty = require 'naughty'
local wibox = require 'wibox'
local gears = require 'gears'
local beautiful = require 'beautiful'
local text_taglist = require 'ui.taglist'
local widgets = require 'ui.widgets'
local helpers = require 'helpers'
screen.connect_signal('property::geometry', helpers.set_wallpaper)
awful.screen.connect_for_each_screen(function(s)
helpers.set_wallpaper(s)
s.bar = awful.wibar({
screen = s,
position = 'bottom',
height = beautiful.wibar_height,
width = s.geometry.width - 28,
shape = gears.shape.rounded_bar,
bg = '#00000000'
})
s.bar.y = s.geometry.height - 36
local realbar = wibox.widget {{
layout = wibox.layout.align.horizontal,
expand = 'none',
{
{
layout = wibox.layout.fixed.horizontal,
text_taglist(s)
},
left = beautiful.wibar_spacing,
right = beautiful.wibar_spacing,
widget = wibox.container.margin,
},
{
{ -- Middle widgets
layout = wibox.layout.fixed.horizontal,
spacing = beautiful.wibar_spacing,
widgets.music,
},
left = beautiful.wibar_spacing,
right = beautiful.wibar_spacing,
widget = wibox.container.margin,
},
{
{ -- Right widgets
layout = wibox.layout.fixed.horizontal,
spacing = beautiful.wibar_spacing,
widgets.systray,
widgets.ram_bar,
widgets.time,
widgets.layout
},
left = beautiful.wibar_spacing,
right = beautiful.wibar_spacing,
widget = wibox.container.margin,
},
},
shape = s.bar.shape,
bg = beautiful.wibar_bg,
widget = wibox.container.background,
forced_width = s.geometry.width
}
s.bar:setup {
layout = wibox.layout.align.horizontal,
expand = 'none',
{
{
layout = wibox.layout.fixed.horizontal,
spacing = beautiful.wibar_spacing,
realbar,
},
left = 1, right = 1,
widget = wibox.container.margin,
}
}
end)
|
local config = require 'config'
local u = require 'utilities'
local api = require 'methods'
local plugin = {}
local function doKeyboard_lang()
local keyboard = {
inline_keyboard = {}
}
for lang, flag in pairs(config.available_languages) do
local line = {{text = flag, callback_data = 'langselected:'..lang}}
table.insert(keyboard.inline_keyboard, line)
end
return keyboard
end
function plugin.onTextMessage(msg, blocks)
if msg.chat.type == 'private' or (msg.chat.id < 0 and u.is_allowed('config', msg.chat.id, msg.from)) then
local keyboard = doKeyboard_lang()
api.sendMessage(msg.chat.id, _("*List of available languages*:"), true, keyboard)
end
end
function plugin.onCallbackQuery(msg, blocks)
if msg.chat.type ~= 'private' and not msg.from.admin then
api.answerCallbackQuery(msg.cb_id, _("You are not an admin"))
else
if blocks[1] == 'selectlang' then
local keyboard = doKeyboard_lang()
api.editMessageText(msg.chat.id, msg.message_id, _("*List of available languages*:"), true, keyboard)
else
locale.language = blocks[1]
db:set('lang:'..msg.chat.id, locale.language)
if (blocks[1] == 'ar' or blocks[1] == 'fa') and msg.chat.type ~= 'private' then
db:hset('chat:'..msg.chat.id..':char', 'Arab', 'allowed')
db:hset('chat:'..msg.chat.id..':char', 'Rtl', 'allowed')
end
-- TRANSLATORS: replace 'English' with the name of your language
api.editMessageText(msg.chat.id, msg.message_id, _("English language is *set*").._(".\nPlease note that translators are volunteers, and some strings of the translation you selected _could not have been translated yet_"), true)
end
end
end
plugin.triggers = {
onTextMessage = {config.cmd..'(lang)$'},
onCallbackQuery = {
'^###cb:(selectlang)',
'^###cb:langselected:(%l%l)$',
'^###cb:langselected:(%l%l_%u%u)$'
}
}
return plugin
|
--- The Icey Maze Map Generator.
-- See http://www.roguebasin.roguelikedevelopment.org/index.php?title=Simple_maze for explanation
-- @module ROT.Map.IceyMaze
local ROT = require((...):gsub(('.[^./\\]*'):rep(2) .. '$', ''))
local IceyMaze = ROT.Map:extend("IceyMaze")
--- Constructor.
-- Called with ROT.Map.IceyMaze:new(width, height, regularity)
-- @tparam int width Width in cells of the map
-- @tparam int height Height in cells of the map
-- @tparam int[opt=0] regularity A value used to determine the 'randomness' of the map, 0= more random
function IceyMaze:init(width, height, regularity)
IceyMaze.super.init(self, width, height)
self._regularity= regularity and regularity or 0
end
--- Create.
-- Creates a map.
-- @tparam function callback This function will be called for every cell. It must accept the following parameters:
-- @tparam int callback.x The x-position of a cell in the map
-- @tparam int callback.y The y-position of a cell in the map
-- @tparam int callback.value A value representing the cell-type. 0==floor, 1==wall
-- @treturn ROT.Map.IceyMaze self
function IceyMaze:create(callback)
local w=self._width
local h=self._height
local map=self:_fillMap(1)
w= w%2==1 and w-1 or w-2
h= h%2==1 and h-1 or h-2
local cx, cy, nx, ny = 1, 1, 1, 1
local done =0
local blocked=false
local dirs={
{0,0},
{0,0},
{0,0},
{0,0}
}
repeat
cx=2+2*math.floor(self._rng:random()*(w-1)/2)
cy=2+2*math.floor(self._rng:random()*(h-1)/2)
if done==0 then map[cx][cy]=0 end
if map[cx][cy]==0 then
self:_randomize(dirs)
repeat
if math.floor(self._rng:random()*(self._regularity+1))==0 then self:_randomize(dirs) end
blocked=true
for i=1,4 do
nx=cx+dirs[i][1]*2
ny=cy+dirs[i][2]*2
if self:_isFree(map, nx, ny, w, h) then
map[nx][ny]=0
map[cx+dirs[i][1]][cy+dirs[i][2]]=0
cx=nx
cy=ny
blocked=false
done=done+1
break
end
end
until blocked
end
until done+1>=w*h/4
if not callback then return self end
for y = 1, self._height do
for x = 1, self._width do
callback(x, y, map[x][y])
end
end
return self
end
function IceyMaze:_randomize(dirs)
for i=1,4 do
dirs[i][1]=0
dirs[i][2]=0
end
local rand=math.floor(self._rng:random()*4)
if rand==0 then
dirs[1][1]=-1
dirs[3][2]=-1
dirs[2][1]= 1
dirs[4][2]= 1
elseif rand==1 then
dirs[4][1]=-1
dirs[2][2]=-1
dirs[3][1]= 1
dirs[1][2]= 1
elseif rand==2 then
dirs[3][1]=-1
dirs[1][2]=-1
dirs[4][1]= 1
dirs[2][2]= 1
elseif rand==3 then
dirs[2][1]=-1
dirs[4][2]=-1
dirs[1][1]= 1
dirs[3][2]= 1
end
end
function IceyMaze:_isFree(map, x, y, w, h)
if x<2 or y<2 or x>w or y>h then return false end
return map[x][y]~=0
end
return IceyMaze
|
Bird = Class{}
function Bird:init()
--load bird image from disk and assign its width and height
self.image = love.graphics.newImage('bird.png')
self.width = self.image:getWidth()
self.height = self.image:getHeight()
--position bird in the middle of the screen
self.x = VIRTUAL_WIDTH / 2 - (self.width / 2)
self.y = VIRTUAL_HEIGHT / 2 - (self.height / 2)
end
function Bird:render()
love.graphics.draw(self.image, self.x, self.y)
end |
local _, CLM = ...
local MODELS = CLM.MODELS
local UTILS = CLM.UTILS
local mergeLists = UTILS.mergeLists
local typeof = UTILS.typeof
-- local getIntegerGuid = UTILS.getIntegerGuid
-- local GetGUIDFromEntry = UTILS.GetGUIDFromEntry
local CreateGUIDList = UTILS.CreateGUIDList
local LogEntry = LibStub("EventSourcing/LogEntry")
-- local inflate = UTILS.inflate
local deflate = UTILS.deflate
local RosterCreate = LogEntry:extend("R0")
local RosterDelete = LogEntry:extend("R1")
local RosterRename = LogEntry:extend("R2")
local RosterUpdateConfig = LogEntry:extend("R3")
local RosterUpdateConfigSingle = LogEntry:extend("R4")
local RosterUpdateDefault = LogEntry:extend("R5")
local RosterUpdateDefaultSingle = LogEntry:extend("R6")
local RosterUpdateOverrides = LogEntry:extend("R7")
local RosterUpdateOverridesSingle = LogEntry:extend("R8")
local RosterUpdateProfiles = LogEntry:extend("R9")
local RosterCopyData = LogEntry:extend("RC")
-- ------------ --
-- RosterCreate --
-- ------------ --
function RosterCreate:new(rosterUid, name, pointType)
local o = LogEntry.new(self);
o.n = tostring(name) or ""
o.r = tonumber(rosterUid) or 0
o.p = tonumber(pointType) or 0
return o
end
function RosterCreate:rosterUid()
return self.r
end
function RosterCreate:name()
return self.n
end
function RosterCreate:pointType()
return self.p
end
local RosterCreateFields = mergeLists(LogEntry:fields(), {"r", "n", "p"})
function RosterCreate:fields()
return RosterCreateFields
end
-- ------------ --
-- RosterDelete --
-- ------------ --
function RosterDelete:new(rosterUid)
local o = LogEntry.new(self);
o.r = tonumber(rosterUid) or 0
return o
end
function RosterDelete:rosterUid()
return self.r
end
local RosterDeleteFields = mergeLists(LogEntry:fields(), {"r"})
function RosterDelete:fields()
return RosterDeleteFields
end
-- ------------ --
-- RosterRename --
-- ------------ --
function RosterRename:new(rosterUid, name)
local o = LogEntry.new(self);
o.n = tostring(name) or ""
o.r = tonumber(rosterUid) or 0
return o
end
function RosterRename:rosterUid()
return self.r
end
function RosterRename:name()
return self.n
end
local RosterRenameFields = mergeLists(LogEntry:fields(), {"r", "n"})
function RosterRename:fields()
return RosterRenameFields
end
-- ------------------ --
-- RosterUpdateConfig --
-- ------------------ --
function RosterUpdateConfig:new(rosterUid, config)
local o = LogEntry.new(self);
o.r = tonumber(rosterUid) or 0
if not typeof(config, MODELS.RosterConfiguration) then
config = MODELS.RosterConfiguration:New()
end
o.c = deflate(config)
return o
end
function RosterUpdateConfig:rosterUid()
return self.r
end
function RosterUpdateConfig:config()
return self.c
end
local RosterUpdateConfigFields = mergeLists(LogEntry:fields(), {"r", "c"})
function RosterUpdateConfig:fields()
return RosterUpdateConfigFields
end
-- ------------------------ --
-- RosterUpdateConfigSingle --
-- ------------------------ --
function RosterUpdateConfigSingle:new(rosterUid, config, value)
local o = LogEntry.new(self);
o.r = tonumber(rosterUid) or 0
o.c = tostring(config) or ""
o.v = value
return o
end
function RosterUpdateConfigSingle:rosterUid()
return self.r
end
function RosterUpdateConfigSingle:config()
return self.c
end
function RosterUpdateConfigSingle:value()
return self.v
end
local RosterUpdateConfigSingleFields = mergeLists(LogEntry:fields(), {"r", "c", "v"})
function RosterUpdateConfigSingle:fields()
return RosterUpdateConfigSingleFields
end
-- ------------------- --
-- RosterUpdateDefault --
-- ------------------- --
function RosterUpdateDefault:new(rosterUid, defaults)
local o = LogEntry.new(self);
o.r = tonumber(rosterUid) or 0
o.d = defaults or {}
return o
end
function RosterUpdateDefault:rosterUid()
return self.r
end
function RosterUpdateDefault:defaults()
return self.d
end
local RosterUpdateDefaultFields = mergeLists(LogEntry:fields(), {"r", "d"})
function RosterUpdateDefault:fields()
return RosterUpdateDefaultFields
end
-- ------------------------- --
-- RosterUpdateDefaultSingle --
-- ------------------------- --
function RosterUpdateDefaultSingle:new(rosterUid, slot, baseValue, maxValue)
local o = LogEntry.new(self);
o.r = tonumber(rosterUid) or 0
o.d = tostring(slot) or "" -- not the most optimal but i don't expect it to be changed too often
o.i = tonumber(baseValue) or 0
o.a = tonumber(maxValue) or 0
return o
end
function RosterUpdateDefaultSingle:rosterUid()
return self.r
end
function RosterUpdateDefaultSingle:config()
return self.d
end
function RosterUpdateDefaultSingle:base()
return self.i
end
function RosterUpdateDefaultSingle:max()
return self.a
end
local RosterUpdateDefaultSingleFields = mergeLists(LogEntry:fields(), {"r", "d", "i", "a"})
function RosterUpdateDefaultSingle:fields()
return RosterUpdateDefaultSingleFields
end
-- ------------------------ --
-- RosterUpdateOverrides --
-- ------------------------ --
function RosterUpdateOverrides:new(rosterUid, itemId, base, max)
local o = LogEntry.new(self);
o.r = tonumber(rosterUid) or 0
o.i = tonumber(itemId) or 0
o.b = tonumber(base) or 0
o.a = tonumber(max) or 0
return o
end
function RosterUpdateOverrides:rosterUid()
return self.r
end
function RosterUpdateOverrides:itemId()
return self.i
end
function RosterUpdateOverrides:base()
return self.b
end
function RosterUpdateOverrides:max()
return self.a
end
local RosterUpdateOverridesFields = mergeLists(LogEntry:fields(), {"r", "i", "b", "a"})
function RosterUpdateOverrides:fields()
return RosterUpdateOverridesFields
end
-- --------------------------- --
-- RosterUpdateOverridesSingle --
-- --------------------------- --
function RosterUpdateOverridesSingle:new(rosterUid, itemId, value)
local o = LogEntry.new(self);
o.r = tonumber(rosterUid) or 0
o.o = tonumber(itemId) or 0
o.v = tonumber(value) or 0
return o
end
function RosterUpdateOverridesSingle:rosterUid()
return self.r
end
function RosterUpdateOverridesSingle:itemId()
return self.o
end
function RosterUpdateOverridesSingle:value()
return self.v
end
local RosterUpdateOverridesSingleFields = mergeLists(LogEntry:fields(), {"r", "o", "v"})
function RosterUpdateOverridesSingle:fields()
return RosterUpdateOverridesSingleFields
end
-- -------------------- --
-- RosterUpdateProfiles --
-- -------------------- --
function RosterUpdateProfiles:new(rosterUid, profiles, remove)
local o = LogEntry.new(self);
o.r = tonumber(rosterUid) or 0
o.p = CreateGUIDList(profiles)
o.e = remove and true or false
return o
end
function RosterUpdateProfiles:rosterUid()
return self.r
end
function RosterUpdateProfiles:profiles()
return self.p
end
function RosterUpdateProfiles:remove()
return self.e
end
local RosterUpdateProfilesFields = mergeLists(LogEntry:fields(), {"r", "p", "e"})
function RosterUpdateProfiles:fields()
return RosterUpdateProfilesFields
end
-- -------------------- --
-- RosterCopyData --
-- -------------------- --
function RosterCopyData:new(sourceRosterUid, targetRosterUid, config, defaults, overrides, profiles)
local o = LogEntry.new(self);
o.r = tonumber(sourceRosterUid) or 0
o.a = tonumber(targetRosterUid) or 0
o.c = config and true or false
o.d = defaults and true or false
o.o = overrides and true or false
o.p = profiles and true or false
return o
end
function RosterCopyData:sourceRosterUid()
return self.r
end
function RosterCopyData:targetRosterUid()
return self.a
end
function RosterCopyData:config()
return self.c
end
function RosterCopyData:defaults()
return self.d
end
function RosterCopyData:overrides()
return self.o
end
function RosterCopyData:profiles()
return self.p
end
local RosterCopyDataFields = mergeLists(LogEntry:fields(), {"r", "a", "c", "d", "o", "p"})
function RosterCopyData:fields()
return RosterCopyDataFields
end
MODELS.LEDGER.ROSTER = {
Create = RosterCreate,
Delete = RosterDelete,
Rename = RosterRename,
UpdateConfig = RosterUpdateConfig,
UpdateConfigSingle = RosterUpdateConfigSingle,
UpdateDefault = RosterUpdateDefault,
UpdateDefaultSingle = RosterUpdateDefaultSingle,
UpdateOverrides = RosterUpdateOverrides,
UpdateOverridesSingle = RosterUpdateOverridesSingle,
UpdateProfiles = RosterUpdateProfiles,
CopyData = RosterCopyData,
}
|
ccs = ccs or {}
---ActionManagerEx object
---@class ActionManagerEx : Ref
local ActionManagerEx = {}
ccs.ActionManagerEx = ActionManagerEx
--------------------------------
---Stop an Action with a name.<br>
---param jsonName UI file name<br>
---param actionName action name in the UIfile.<br>
---return ActionObject which named as the param name
---@param jsonName char
---@param actionName char
---@return ActionObject
function ActionManagerEx:stopActionByName(jsonName, actionName) end
--------------------------------
---Gets an ActionObject with a name.<br>
---param jsonName UI file name<br>
---param actionName action name in the UI file.<br>
---return ActionObject which named as the param name
---@param jsonName char
---@param actionName char
---@return ActionObject
function ActionManagerEx:getActionByName(jsonName, actionName) end
--------------------------------
--
---@return int
function ActionManagerEx:getStudioVersionNumber() end
--------------------------------
---@overload fun(char, char, CallFunc):ActionObject
---@overload fun(char, char):ActionObject
---@param jsonName char
---@param actionName char
---@param func CallFunc
---@return ActionObject
function ActionManagerEx:playActionByName(jsonName, actionName, func) end
--------------------------------
---Release all actions.
---@return ActionManagerEx
function ActionManagerEx:releaseActions() end
--------------------------------
---Purges ActionManager point.<br>
---js purge<br>
---lua destroyActionManager
---@return ActionManagerEx
function ActionManagerEx:destroyInstance() end
--------------------------------
---Gets the static instance of ActionManager.<br>
---js getInstance<br>
---lua getInstance
---@return ActionManagerEx
function ActionManagerEx:getInstance() end
return ActionManagerEx |
project "App_SharedMemoryPhysics"
if _OPTIONS["ios"] then
kind "WindowedApp"
else
kind "ConsoleApp"
end
includedirs {".","../../src", "../ThirdPartyLibs",}
links {
"Bullet3Common", "BulletDynamics","BulletCollision", "LinearMath"
}
language "C++"
files {
"PhysicsClient.cpp",
"PhysicsClientSharedMemory.cpp",
"PhysicsClientExample.cpp",
"PhysicsServerExample.cpp",
"PhysicsServerSharedMemory.cpp",
"PhysicsServerSharedMemory.h",
"PhysicsServer.cpp",
"PhysicsServer.h",
"main.cpp",
"PhysicsClientC_API.cpp",
"SharedMemoryCommands.h",
"SharedMemoryPublic.h",
"PhysicsServer.cpp",
"PosixSharedMemory.cpp",
"Win32SharedMemory.cpp",
"InProcessMemory.cpp",
"PhysicsDirect.cpp",
"PhysicsDirect.h",
"PhysicsDirectC_API.cpp",
"PhysicsDirectC_API.h",
"PhysicsLoopBack.cpp",
"PhysicsLoopBack.h",
"PhysicsLoopBackC_API.cpp",
"PhysicsLoopBackC_API.h",
"PhysicsServerCommandProcessor.cpp",
"PhysicsServerCommandProcessor.h",
"TinyRendererVisualShapeConverter.cpp",
"TinyRendererVisualShapeConverter.h",
"../TinyRenderer/geometry.cpp",
"../TinyRenderer/model.cpp",
"../TinyRenderer/tgaimage.cpp",
"../TinyRenderer/our_gl.cpp",
"../TinyRenderer/TinyRenderer.cpp",
"../OpenGLWindow/SimpleCamera.cpp",
"../OpenGLWindow/SimpleCamera.h",
"../Importers/ImportURDFDemo/ConvertRigidBodies2MultiBody.h",
"../Importers/ImportURDFDemo/MultiBodyCreationInterface.h",
"../Importers/ImportURDFDemo/MyMultiBodyCreator.cpp",
"../Importers/ImportURDFDemo/MyMultiBodyCreator.h",
"../Importers/ImportURDFDemo/BulletUrdfImporter.cpp",
"../Importers/ImportURDFDemo/BulletUrdfImporter.h",
"../Importers/ImportURDFDemo/UrdfParser.cpp",
"../Importers/ImportURDFDemo/urdfStringSplit.cpp",
"../Importers/ImportURDFDemo/UrdfParser.cpp",
"../Importers/ImportURDFDemo/UrdfParser.h",
"../Importers/ImportURDFDemo/URDF2Bullet.cpp",
"../Importers/ImportURDFDemo/URDF2Bullet.h",
"../Utils/b3ResourcePath.cpp",
"../Utils/b3Clock.cpp",
"../../Extras/Serialize/BulletWorldImporter/*",
"../../Extras/Serialize/BulletFileLoader/*",
"../Importers/ImportURDFDemo/URDFImporterInterface.h",
"../Importers/ImportURDFDemo/URDFJointTypes.h",
"../Importers/ImportObjDemo/Wavefront2GLInstanceGraphicsShape.cpp",
"../Importers/ImportObjDemo/LoadMeshFromObj.cpp",
"../Importers/ImportSTLDemo/ImportSTLSetup.h",
"../Importers/ImportSTLDemo/LoadMeshFromSTL.h",
"../Importers/ImportColladaDemo/LoadMeshFromCollada.cpp",
"../Importers/ImportColladaDemo/ColladaGraphicsInstance.h",
"../ThirdPartyLibs/Wavefront/tiny_obj_loader.cpp",
"../ThirdPartyLibs/tinyxml/tinystr.cpp",
"../ThirdPartyLibs/tinyxml/tinyxml.cpp",
"../ThirdPartyLibs/tinyxml/tinyxmlerror.cpp",
"../ThirdPartyLibs/tinyxml/tinyxmlparser.cpp",
"../Importers/ImportMeshUtility/b3ImportMeshUtility.cpp",
"../ThirdPartyLibs/stb_image/stb_image.cpp",
}
|
local oo = require("oo")
local bt = require("bt")
local log = require("log")
local nt = require("nt")
local facing = require("facing")
local tb = {}
-- A collection of common turtle behaviours
local function fuel(v)
-- Fuel needed to traverse vector
return math.abs(v.x) + math.abs(v.y) + math.abs(v.z)
end
function tb.hasFuel(pad, ...)
if nt.getFuelLevel() == "unlimited" then
return true
end
local needed = 2
local p
local route={...}
for i,tag in ipairs(route) do
if pad[tag] then
if not p then
p = nt.pos(pad[tag].cs)
end
local next = pad[tag].pos
needed = needed + fuel(next - p)
p = next
end
end
return nt.getFuelLevel() >= needed
end
function tb.hasSpace()
for n=1,16 do
if nt.getItemCount(n) == 0 then
return true
end
end
return false
end
function tb.isAt(pad, tag)
-- Can't compare equality since vector doesn't define the operation
local d = pad[tag].pos - nt.pos(pad[tag].cs)
return d:length() < 0.5
end
function tb.isEmpty()
for n=1,16 do
if nt.getItemCount(n) > 0 then
return false
end
end
return true
end
return tb
|
-- Should Cillia spawn as in real tibia?
local spawnByDay = true
local spawnDay = 'Sunday'
local spawnPosition = Position(32392, 32197, 8)
function onStartup()
if spawnByDay then
if os.date('%A') == spawnDay then
Game.createNpc('Cillia', spawnPosition, false, true)
end
else
Game.createNpc('Cillia', spawnPosition, false, true)
end
return true
end
|
local ease = require "ease"
--local base = require "base"
--local movement = require "movement"
local jump = {
isjumping = false,
}
function jump:set_status(pstatus)
self.isjumping = pstatus
end
function jump.process(pspeed, pmultiplier)
jump:set_status(true)
print(jump.isjumping)
xprejump = x
easedpos = 0
while easedpos < 0.5 do
local framedelta = love.timer.getDelta() / pspeed
if framedelta > 1 then framedelta = 1 end
local newtarget = framedelta
easedpos = ease.easeOutQuad(easedpos + newtarget)
y = y - (easedpos * pmultiplier)
print(y)
end
jump:set_status(false)
end
function jump.jump(pspeed, pmultiplier)
pspeed = pspeed or 1 -- speed in seconds
pmultiplier = pmultiplier or 1 -- jump height
if jump.isjumping == false then
jump:set_status(true)
print("Called")
jump.process(pspeed, pmultiplier)
end
end
return jump
|
workspace "Violet"
architecture "x86_64"
startproject "Violet-Editor"
configurations{
"Debug",
"Release",
"Distribution"
}
flags
{
"MultiProcessorCompile"
}
outputDir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
project "Violet"
location "Violet"
kind "StaticLib"
language "C++"
cppdialect "c++17"
staticruntime "on"
targetdir ("bin/" .. outputDir .. "/%{prj.name}")
objdir("bin-intermediates/" .. outputDir .. "/%{prj.name}")
--Pre-Compiled Header
pchheader "VIOPCH.h"
pchsource "%{prj.name}/src/VIOPCH.cpp"
files{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp",
"%{prj.name}/vendor/stb_image/**.h", --Include stb_image to be included and compiled by the project
"%{prj.name}/vendor/stb_image/**.cpp",
"%{prj.name}/vendor/ImGuizmo/ImGuizmo.h", --Include ImGuizmo to be included and compiled by the project
"%{prj.name}/vendor/ImGuizmo/ImGuizmo.cpp"
}
includedirs{
"%{prj.name}/src", --Include dir for Violet project src folder
"%{prj.name}/vendor/spdlog/include", --Include dir for spdlog
"%{prj.name}/vendor/GLFW/include", --Include dir for GLFW
"%{prj.name}/vendor/Glad/include", --Include dir for Glad
"%{prj.name}/vendor/imgui", --Include dir for ImGui
"%{prj.name}/vendor/glm", --Include dir for glm
"%{prj.name}/vendor/stb_image", --Include dir for stb_image
"%{prj.name}/vendor/entt/single_include/entt", --Include dir for entt
"%{prj.name}/vendor/yaml-cpp/include", --Include dir for yaml-cpp
"%{prj.name}/vendor/ImGuizmo", --Include dir for ImGuizmo
"%{prj.name}/vendor/Box2D/include" --Include dir for Box2D
}
links{
"GLFW",
"Glad",
"ImGui",
"yaml-cpp",
"Box2D"
}
filter "files:Violet/vendor/ImGuizmo/**.cpp"
flags { "NoPCH" }
filter "system:windows"
systemversion "latest"
defines{
"VIO_PLATFORM_WINDOWS",
"GLFW_INCLUDE_NONE" --Avoid including OpenGl headers when ever including GLFW to avoid error from Glad (Glad already includes OpenGl headers)
}
--[[
--When build is set to "SharedLib"
defines{
"VIO_SHARED_LIB",
"VIO_BUILD_DLL"
}
For copying dll file for SharedLib build
postbuildcommands{
("{COPY} %{cfg.buildtarget.relpath} \"../bin/" .. outputDir .. "/Sandbox/\"")
}
--]]
filter "configurations:Debug"
defines "VIO_DEBUG_MODE"
symbols "on"
runtime "Debug"
filter "configurations:Release"
defines "VIO_RELEASE_MODE"
runtime "Release"
optimize "on"
filter "configurations:Distribution"
defines "VIO_DISTRIBUTION_MODE"
runtime "Release"
optimize "on"
project "Sandbox"
location "Sandbox"
kind "ConsoleApp"
language "C++"
cppdialect "c++17"
staticruntime "on"
targetdir("bin/" .. outputDir .. "/%{prj.name}")
objdir("bin-intermediates/" .. outputDir .. "/%{prj.name}")
files{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp"
}
includedirs{
"Violet/vendor/spdlog/include",
"Violet/src",
"Violet/vendor/glm", --Include dir for glm
"Violet/vendor/imgui", --Include dir for ImGui
"Violet/vendor/entt/single_include/entt" --Include dir for entt
}
links{
"Violet"
}
filter "system:windows"
systemversion "latest"
defines{
"VIO_PLATFORM_WINDOWS",
--"VIO_SHARED_LIB" -When Violet build is set to "SharedLib"
}
filter "configurations:Debug"
defines "VIO_DEBUG_MODE"
runtime "Debug"
symbols "On"
filter "configurations:Release"
defines "VIO_RELEASE_MODE"
runtime "Release"
optimize "on"
filter "configurations:Distribution"
defines "VIO_DISTRIBUTION_MODE"
runtime "Release"
optimize "on"
project "Violet-Editor"
location "Violet-Editor"
kind "ConsoleApp"
language "C++"
cppdialect "c++17"
staticruntime "on"
targetdir("bin/" .. outputDir .. "/%{prj.name}")
objdir("bin-intermediates/" .. outputDir .. "/%{prj.name}")
files{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp"
}
includedirs{
"Violet/vendor/spdlog/include",
"Violet/src",
"Violet/vendor/glm", --Include dir for glm
"Violet/vendor/imgui", --Include dir for ImGui
"Violet/vendor/entt/single_include/entt", --Include dir for entt
"Violet/vendor/ImGuizmo" --Include dir for ImGuizmo
}
links{
"Violet"
}
filter "system:windows"
systemversion "latest"
defines{
"VIO_PLATFORM_WINDOWS",
--"VIO_SHARED_LIB" -When Violet build is set to "SharedLib"
}
filter "configurations:Debug"
defines "VIO_DEBUG_MODE"
runtime "Debug"
symbols "On"
filter "configurations:Release"
defines "VIO_RELEASE_MODE"
runtime "Release"
optimize "on"
filter "configurations:Distribution"
defines "VIO_DISTRIBUTION_MODE"
runtime "Release"
optimize "on"
--Submodules
group "Dependencies"
--Include Glad premake file
include "Violet/vendor/Glad"
project "GLFW"
location "GLFW"
kind "StaticLib"
language "C"
staticruntime "on"
targetdir ("bin/" .. outputDir .. "/%{prj.name}")
objdir ("bin-intermediates/" .. outputDir .. "/%{prj.name}")
GLFWSrcDir = "Violet/vendor/GLFW/"
files
{
GLFWSrcDir .."include/GLFW/glfw3.h",
GLFWSrcDir .."include/GLFW/glfw3native.h",
GLFWSrcDir .."src/glfw_config.h",
GLFWSrcDir .."src/context.c",
GLFWSrcDir .."src/init.c",
GLFWSrcDir .."src/input.c",
GLFWSrcDir .."src/monitor.c",
GLFWSrcDir .."src/vulkan.c",
GLFWSrcDir .."src/window.c"
}
filter "system:linux"
pic "on"
systemversion "latest"
files
{
GLFWSrcDir .."src/x11_init.c",
GLFWSrcDir .."src/x11_monitor.c",
GLFWSrcDir .."src/x11_window.c",
GLFWSrcDir .."src/xkb_unicode.c",
GLFWSrcDir .."src/posix_time.c",
GLFWSrcDir .."src/posix_thread.c",
GLFWSrcDir .."src/glx_context.c",
GLFWSrcDir .."src/egl_context.c",
GLFWSrcDir .."src/osmesa_context.c",
GLFWSrcDir .."src/linux_joystick.c"
}
defines
{
"_GLFW_X11"
}
filter "system:windows"
systemversion "latest"
files
{
GLFWSrcDir .."src/win32_init.c",
GLFWSrcDir .."src/win32_joystick.c",
GLFWSrcDir .."src/win32_monitor.c",
GLFWSrcDir .."src/win32_time.c",
GLFWSrcDir .."src/win32_thread.c",
GLFWSrcDir .."src/win32_window.c",
GLFWSrcDir .."src/wgl_context.c",
GLFWSrcDir .."src/egl_context.c",
GLFWSrcDir .."src/osmesa_context.c"
}
defines
{
"_GLFW_WIN32",
"_CRT_SECURE_NO_WARNINGS"
}
filter "configurations:Debug"
runtime "Debug"
symbols "on"
filter "configurations:Release"
runtime "Release"
optimize "on"
project "ImGui"
location "ImGui"
kind "StaticLib"
language "C++"
cppdialect "C++17"
staticruntime "on"
targetdir ("bin/" .. outputDir .. "/%{prj.name}")
objdir ("bin-intermediates/" .. outputDir .. "/%{prj.name}")
ImGuiSrcDir = "Violet/vendor/imgui/"
files
{
ImGuiSrcDir .."imconfig.h",
ImGuiSrcDir .."imgui.h",
ImGuiSrcDir .."imgui.cpp",
ImGuiSrcDir .."imgui_draw.cpp",
ImGuiSrcDir .."imgui_internal.h",
ImGuiSrcDir .."imgui_widgets.cpp",
ImGuiSrcDir .."imstb_rectpack.h",
ImGuiSrcDir .."imstb_textedit.h",
ImGuiSrcDir .."imstb_truetype.h",
ImGuiSrcDir .."imgui_demo.cpp",
ImGuiSrcDir .."imgui_tables.cpp",
ImGuiSrcDir .."backends/imgui_impl_opengl3.h",
ImGuiSrcDir .."backends/imgui_impl_opengl3.cpp",
ImGuiSrcDir .."backends/imgui_impl_glfw.h",
ImGuiSrcDir .."backends/imgui_impl_glfw.cpp",
ImGuiSrcDir .."examples/libs/glfw/include/**",
ImGuiSrcDir .."misc/cpp/imgui_stdlib.h", --imgui_stdlib.h + imgui_stdlib.cpp InputText() wrappers for C++ standard library (STL) type: std::string.
ImGuiSrcDir .."misc/cpp/imgui_stdlib.cpp"
}
includedirs{
ImGuiSrcDir,
ImGuiSrcDir .."examples/libs/glfw/include",
"Violet/vendor/Glad/include"
}
filter "system:windows"
systemversion "latest"
filter "configurations:Debug"
runtime "Debug"
symbols "on"
filter "configurations:Release"
runtime "Release"
optimize "on"
project "yaml-cpp"
location "yaml-cpp"
kind "StaticLib"
language "C++"
cppdialect "C++17"
staticruntime "on"
targetdir ("bin/" .. outputDir .. "/%{prj.name}")
objdir ("bin-intermediates/" .. outputDir .. "/%{prj.name}")
YamlCppSrcDir = "Violet/vendor/yaml-cpp/"
files
{
YamlCppSrcDir .."src/**.h",
YamlCppSrcDir .."src/**.cpp",
YamlCppSrcDir .."include/**.h"
}
includedirs{
YamlCppSrcDir .."include"
}
filter "system:windows"
systemversion "latest"
filter "system:linux"
pic "on"
systemversion "latest"
filter "configurations:Debug"
runtime "Debug"
symbols "on"
filter "configurations:Release"
runtime "Release"
optimize "on"
project "Box2D"
location "Box2D"
kind "StaticLib"
language "C++"
cppdialect "C++17"
staticruntime "on"
targetdir ("bin/" .. outputDir .. "/%{prj.name}")
objdir ("bin-intermediates/" .. outputDir .. "/%{prj.name}")
Box2DSrcDir = "Violet/vendor/Box2D/"
files
{
Box2DSrcDir .."src/**.h",
Box2DSrcDir .."src/**.cpp",
Box2DSrcDir .."include/**.h"
}
includedirs{
Box2DSrcDir .."include",
Box2DSrcDir .."src"
}
filter "system:windows"
systemversion "latest"
filter "system:linux"
pic "on"
systemversion "latest"
filter "configurations:Debug"
runtime "Debug"
symbols "on"
filter "configurations:Release"
runtime "Release"
optimize "on"
group "" --Dependencies
|
local lookup = {
[
' _ ' ..
'| |' ..
'|_|' ..
' '
] = '0',
[
' ' ..
' |' ..
' |' ..
' '
] = '1',
[
' _ ' ..
' _|' ..
'|_ ' ..
' '
] = '2',
[
' _ ' ..
' _|' ..
' _|' ..
' '
] = '3',
[
' ' ..
'|_|' ..
' |' ..
' '
] = '4',
[
' _ ' ..
'|_ ' ..
' _|' ..
' '
] = '5',
[
' _ ' ..
'|_ ' ..
'|_|' ..
' '
] = '6',
[
' _ ' ..
' |' ..
' |' ..
' '
] = '7',
[
' _ ' ..
'|_|' ..
'|_|' ..
' '
] = '8',
[
' _ ' ..
'|_|' ..
' _|' ..
' '
] = '9',
}
local row_pattern = ('[^\n]+\n'):rep(4) .. '*'
local function lines(s)
local lines = {}
for line in s:gmatch('[^\n]+') do
assert(#line % 3 == 0)
table.insert(lines, line)
end
return lines
end
local function parse(row)
local result = ''
local lines = lines(row)
assert(#lines[1] == #lines[2] and
#lines[2] == #lines[3] and
#lines[3] == #lines[4])
for i = 1, #lines[1], 3 do
local character = ''
for line = 1, 4 do
character = character .. lines[line]:sub(i, i + 2)
end
result = result .. (lookup[character] or '?')
end
return result
end
return {
convert = function(s)
local results = {}
for row in s:gmatch(row_pattern) do
table.insert(results, parse(row))
end
return table.concat(results, ',')
end
}
|
--[[
© CloudSixteen.com do not share, re-distribute or modify
without permission of its author (kurozael@gmail.com).
Clockwork was created by Conna Wiles (also known as kurozael.)
http://cloudsixteen.com/license/clockwork.html
--]]
CW_SPANISH = Clockwork.lang:GetTable("Spanish");
CW_SPANISH["PaperWrittenOn"] = "Hay algo escrito.";
CW_SPANISH["PaperIsBlank"] = "Está en blanco.";
CW_SPANISH["Paper"] = "Papel";
CW_SPANISH["Write"] = "Escribir"; |
ITEM.name = "Противогаз ЭО-20 ПБФ"
ITEM.desc = "Модернизированная, значительно более компактная версия классического противогаза ЭО-19 ПБФ. Простая система обеспечивает фильтрацию воздуха от радиационных частиц и химических реагентов. Защита от радиации была усовершенствована добавлением в фильтры свинца, однако, следует отментить, что противогаз не обладает необходимой надежностью для работы в токсичной среде. \n\nХАРАКТЕРИСТИКИ: \n-легкий противогаз \n-удобность: средняя \n-Используется при: ремонте снаряжения (+8)"
ITEM.uniqueID = "gasmask"
ITEM.outfit = ITEM.uniqueID
ITEM.outfitCategory = "hat"
ITEM.exRender = false
ITEM.price = 6888
ITEM.weight = 1.05
ITEM.model = "models/kek1ch/helm_respirator.mdl"
ITEM.width = 2
ITEM.height = 2
ITEM.iconCam = {
pos = Vector(-0.5, 0, 203.82165527344),
ang = Angle(90, 0, 180),
fov = 4.2
} |
local packer = require('packer')
local util = require('packer.util')
local manager = {}
manager.__index = manager
function manager:new(module_names)
local o = {modules = {}, plugins = {}, module_names = module_names}
setmetatable(o, {__index = self})
return o
end
function manager:init()
self:_set_packer_config()
self:_get_modules()
self:_get_plugins()
end
function manager:_set_packer_config()
local plugin_path = util.join_paths(vim.fn.stdpath('config'), 'plugins')
self.packer_config = {
ensure_dependencies = true, -- Should packer install plugin dependencies?
package_root = util.join_paths(vim.fn.stdpath('data'), 'site', 'pack'),
compile_path = util.join_paths(vim.fn.stdpath('data'), 'plugin', 'packer_compiled.lua'),
plugin_package = 'packer', -- The default package for plugins
max_jobs = 4, -- Limit the number of simultaneous jobs. nil means no limit
auto_clean = true, -- During sync(), remove unused plugins
compile_on_sync = true, -- During sync(), run packer.compile()
disable_commands = false, -- Disable creating commands
opt_default = false, -- Default to using opt (as opposed to start) plugins
transitive_opt = true, -- Make dependencies of opt plugins also opt by default
transitive_disable = true, -- Automatically disable dependencies of disabled plugins
auto_reload_compiled = true, -- Automatically reload the compiled file after creating it.
git = {
cmd = 'git', -- The base command for git operations
subcommands = { -- Format strings for git subcommands
update = 'pull --ff-only --progress --rebase=false',
install = 'clone --depth %i --no-single-branch --progress',
fetch = 'fetch --depth 999999 --progress',
checkout = 'checkout %s --',
update_branch = 'merge --ff-only @{u}',
current_branch = 'branch --show-current',
diff = 'log --color=never --pretty=format:FMT --no-show-signature HEAD@{1}...HEAD',
diff_fmt = '%%h %%s (%%cr)',
get_rev = 'rev-parse --short HEAD',
get_msg = 'log --color=never --pretty=format:FMT --no-show-signature HEAD -n 1',
submodules = 'submodule update --init --recursive --progress'
},
depth = 1, -- Git clone depth
clone_timeout = 120, -- Timeout, in seconds, for git clones
default_url_format = 'file://' .. plugin_path .. '/%s' -- Lua format string used for "aaa/bbb" style plugins
},
display = {
non_interactive = false, -- If true, disable display windows for all operations
open_fn = nil, -- An optional function to open a window for packer's display
open_cmd = '65vnew \\[packer\\]', -- An optional command to open a window for packer's display
working_sym = '⟳', -- The symbol for a plugin being installed/updated
error_sym = '✗', -- The symbol for a plugin with an error in installation/updating
done_sym = '✓', -- The symbol for a plugin which has completed installation/updating
removed_sym = '-', -- The symbol for an unused plugin which was removed
moved_sym = '→', -- The symbol for a plugin which was moved (e.g. from opt to start)
header_sym = '━', -- The symbol for the header line in packer's display
show_all_info = true, -- Should packer show all update details automatically?
prompt_border = 'double', -- Border style of prompt popups.
keybindings = { -- Keybindings for the display window
quit = 'q',
toggle_info = '<CR>',
diff = 'd',
prompt_revert = 'r'
}
},
luarocks = {
python_cmd = 'python' -- Set the python command to use for running hererocks
},
log = {level = 'warn'}, -- The default print log level. One of: "trace", "debug", "info", "warn", "error", "fatal".
profile = {
enable = false,
threshold = 1 -- integer in milliseconds, plugins which load faster than this won't be shown in profile output
}
}
end
function manager:_get_modules()
for _, module_name in pairs(self.module_names) do
local m = require(module_name)
if type(m) == 'table' then self.modules[module_name] = m:new() end
end
end
function manager:_get_plugins()
for module_name, m in pairs(self.modules) do
for index, plugin in pairs(m:plugins()) do
table.insert(self.plugins, plugin -- {
-- module_name = module_name,
-- plugin = plugin,
-- index = index
-- }
)
end
end
-- print(vim.inspect(self.plugins))
end
function manager:load_plugins()
packer.init(self.packer_config)
packer.reset()
for _, plugin in pairs(self.plugins) do packer.use(plugin) end
packer.install()
--packer.compile()
vim.cmd [[
autocmd User PackerComplete PackerCompile
]]
end
function manager:set_configs() for _, m in pairs(self.modules) do m:config() end end
return manager
|
q1 = {"Линколн", "Шекспир", "Њутн", "да Винчи", "Мирзахани", "Чаплин"}
msg_birth_a = "рођен (араб)"
msg_birth_r = "рођен (роман)"
msg_year_a = "године (араб)"
msg_year_r = "године (роман)"
|
-- modinfo read by stlrel from http://github.com/stellaris-mods/scripts
return {
path = "folk_tinyoutliner",
name = "Tiny Outliner",
tags = { "Graphics", "Utilities" },
picture = "thumb.png",
supported_version = "1.9.*",
originalUploader = "folk",
remote_file_id = 810204739,
readme = "readme.md",
steambb = "steam.bbcode",
}
|
-- Yuoki has a productivity recipe list... but applies it in the data phase, so yuoki's modules (from yuoki engines, which loads after yuoki itself) don't exist yet and thus aren't updated
-- so, we're stealing that for here and re-running it to get other modules
return
{
recipes =
{
{ name = "y_slag_brick_burn_recipe" },
{ name = "y_slag_brick_recipe" },
{ name = "y_slag_granulate_recipe" },
{ name = "y_hps_steel_recipe" },
{ name = "y_hps_purecopper_recipe" },
{ name = "y_hps_pureiron_recipe" },
{ name = "y-basic-st2-mf-recipe" },
{ name = "y-chip2-recipe" },
{ name = "yi_magnetron_recipe" },
{ name = "y-battery-singleuse1-recipe" },
{ name = "y-battery-singleuse2-recipe" },
{ name = "y-battery-single-use3-recipe" },
{ name = "y_blocked_capa_recipe" },
{ name = "y-crystal-cnd-recipe" },
{ name = "y-quantrinum-recipe" },
{ name = "y-fuel-reactor-recipe" },
{ name = "y-infused-mud-recipe" },
{ name = "y-infused-uca2-recipe" },
{ name = "y_mud2solidfuel_recipe" },
{ name = "y_mixedfuel2rocketfuel_recipe" },
{ name = "y-mixfuel-load-recipe" },
{ name = "y-wooden-brikett-packed-recipe" },
{ name = "y-pure-copper-recipe" },
{ name = "y-pure-iron-recipe" },
{ name = "y-refined-copper" },
{ name = "y-refined-iron" },
{ name = "y-wash-dirt-recipe" },
{ name = "y-mixing-rich-recipe" },
{ name = "y-press-richdust-recipe" },
{ name = "y-orange-stuff_recipe" },
{ name = "y-smelt-crush-res1-recipe" },
{ name = "y-smelt-crush-res2-recipe" },
{ name = "y_quantrinum_infusion_recipe" },
{ name = "y_mox1fuel_recipe" },
{ name = "y_mox1mixed_recipe" },
{ name = "y_mox2fuel_recipe" },
{ name = "y_mox2mixed_recipe" },
{ name = "y_mox2fuelsplit_recipe" },
{ name = "y_structure_element_recipe" },
{ name = "y-bluegear-recipe" },
{ name = "y_structure_vessel_recipe" },
{ name = "y-basic-st1-mf-recipe" },
{ name = "y_chip_plate_recipe" },
{ name = "y_dotzetron_recipe" },
{ name = "y_structure_electric_recipe" },
{ name = "y-heat-pipe-recipe" },
{ name = "y-heat-pipe-recipe" },
{ name = "y-conductive-coil-1-recipe" },
{ name = "y-conductive-wire-1_recipe" },
{ name = "y-crush-unicomp-raw-recipe" },
{ name = "y-crush-fuel-raw-recipe" },
{ name = "y_slag_granulate_recipe" },
{ name = "y_steinmehl_recipe" },
{ name = "y-coaldust-recipe" },
{ name = "y_granulate_wood_recipe" },
{ name = "y-unicomp-raw-recipe" },
{ name = "y-raw-fuelnium-recipe" },
{ name = "y-bullet-case-recipe" },
{ name = "y_ammo_case_recipe" },
{ name = "yi_graphite_recipe" },
{ name = "y_data_crystal_recipe" },
{ name = "y_gauge_analog_recipe" },
-- recipes that yuoki didn't include but probably should have
{ name = "y-chip1-recipe" },
-- our recipes
{ name = "angels-plate-durotal" },
{ name = "angels-refined-durotal" },
{ name = "angels-plate-nuatreel" },
{ name = "angels-refined-nuatreel" },
{ name = "advanced-circuit-y" },
{ name = "processing-unit-y" },
{ name = "advanced-processing-unit-y" },
},
categories =
{
{ name = "yrcat-farm", types = { "agricultural" }},
{ name = "yrcat-fish", types = { "agricultural" }},
{ name = "yrcat_meat", types = { "agricultural" }},
},
} |
---@class math.vec2
---@field x number
---@field y number
local M = {}
M.__index = M
setmetatable(M, { __call = function(_, x, y)
local t = type(x)
if t == 'number' then
y = y or 0
elseif t == 'table' then
x, y = x.x, x.y
x = x or 0
y = y or 0
elseif t == 'nil' then
x, y = 0, 0
else
error('invalid argument')
end
return setmetatable({ ['.type'] = 'vec2', x = x, y = y }, M)
end })
function M:__add(other)
return M(self.x + other.x, self.y + other.y)
end
function M:__sub(other)
return M(self.x - other.x, self.y - other.y)
end
function M:__mul(other)
if type(other) == 'table' then
return M(self.x * other.x, self.y * other.y)
elseif type(other) == 'number' then
return M(self.x * other, self.y * other)
else
error('invalid operand in vec2.__mul')
end
end
function M:__div(other)
if type(other) == 'table' then
return M(self.x / other.x, self.y / other.y)
elseif type(other) == 'number' then
return M(self.x / other, self.y / other)
else
error('invalid operand in vec2.__div')
end
end
function M:__unm()
return M(-self.x, -self.y)
end
function M:__eq(other)
return self.x == other.x and self.y == other.y
end
function M:__tostring()
return '<' .. self.x .. ',' .. self.y .. '>'
end
--------------------------------------------------
function M.one()
return M(1, 1)
end
function M.zero()
return M(0, 0)
end
--------------------------------------------------
function M:angle(other)
if other then
return math.atan2(self:cross(other), self:dot(other))
else
return math.atan2(self.y, self.x)
end
end
function M:add(other)
self.x = self.x + other.x
self.y = self.y + other.y
end
function M:clamp(min, max)
if (self.x < min.x) then
self.x = min.x
end
if (self.x > max.x) then
self.x = max.x
end
if (self.y < min.y) then
self.y = min.y
end
if (self.y > max.y) then
self.y = max.y
end
end
function M:clone()
return M(self.x, self.y)
end
function M:cross(other)
return self.x * other.y - self.y * other.x
end
function M:distance(other)
return math.sqrt(self:distanceSquared(other))
end
function M:distanceSquared(other)
local dx = other.x - self.x
local dy = other.y - self.y
return (dx * dx + dy * dy)
end
function M:dot(other)
return self.x * other.x + self.y * other.y
end
function M:fuzzyEquals(other, var)
local dx = math.abs(other.x - self.x)
local dy = math.abs(other.y - self.y)
return dx <= var and dy <= var
end
function M:getClamped(min, max)
local ret = self:clone()
ret:clamp(min, max)
return ret
end
--- Calculates midpoint between two points
function M:getMidpoint(other)
return M((self.x + other.x) / 2, (self.y + other.y) / 2)
end
function M:getNormalized()
local len = self:length()
return M(self.x / len, self.y / len)
end
--- Calculates perpendicular of v, rotated 90 degrees counter-clockwise -- cross(v, perp(v)) >= 0
function M:getPerp()
return M(-self.y, self.x)
end
--- Calculates the projection of this over other.
---@return math.vec2
function M:getProjection(other)
return other * (self:dot(other) / other:dot(other))
end
function M:getRotateAround(point, angle)
if point:isZero() then
return self:getRotated(angle)
else
return point + (self - point):getRotated(angle)
end
end
--- Complex multiplication of two points ("rotates" two points), or rotate a point by angle.
---@param other math.vec2|number vector or angle
---@return math.vec2
function M:getRotated(other)
local x, y
if type(other) == 'number' then
x, y = math.cos(other), math.sin(other)
else
x, y = other.x, other.y
end
return M(self.x * x - self.y * y, self.x * y + self.y * x)
end
--- Calculates perpendicular of v, rotated 90 degrees clockwise -- cross(v, rperp(v)) <= 0
function M:getRPerp()
return M(self.y, -self.x)
end
function M:getScaled(scalar)
return M(self.x * scalar,
self.y * scalar)
end
function M:isOne()
return self.x == 1 and self.y == 1
end
function M:isZero()
return self.x == 0 and self.y == 0
end
function M:length()
return math.sqrt(self.x * self.x + self.y * self.y)
end
function M:lengthSquared()
return self.x * self.x + self.y * self.y
end
function M:lerp(target, alpha)
return self * (1.0 - alpha) + target * alpha
end
function M:negate()
self.x = -self.x
self.y = -self.y
end
function M:normalize()
local len = self:length()
self.x = self.x / len
self.y = self.y / len
end
--- Rotates this vector by angle (specified in radians) around the given point.
function M:rotate(point, angle)
local sinAngle = math.sin(angle)
local cosAngle = math.cos(angle)
if point:isZero() then
local tempX = self.x * cosAngle - self.y * sinAngle
self.y = self.y * cosAngle + self.x * sinAngle
self.x = tempX
else
local tempX = self.x - point.x
local tempY = self.y - point.y
self.x = tempX * cosAngle - tempY * sinAngle + point.x
self.y = tempY * cosAngle + tempX * sinAngle + point.y
end
end
function M:scale(scalar)
self.x = self.x * scalar
self.y = self.y * scalar
end
function M:set(xx, yy, zz)
self.x = xx
self.y = yy
end
function M:setZero()
self.x, self.y = 0, 0
end
function M:smooth(target, elapsedTime, responseTime)
local delta = (target - self) * (elapsedTime / (elapsedTime + responseTime))
self:add(delta)
end
function M:subtract(other)
self.x = self.x - other.x
self.y = self.y - other.y
end
--
function M:isFinite()
return math.isfinite(self.x) and math.isfinite(self.y)
end
return M
|
return {
{
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 1,
Position = {
{
x = 1840.0032,
y = 450
},
{
x = -400.00032,
y = 450
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
{
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 2,
Position = {
{
x = -400.00032,
y = 450
},
{
x = 1840.0032,
y = 450
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
{
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 3,
Position = {
{
x = 1500.0048,
y = 450
},
{
x = -1300.00032,
y = 450
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
{
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 4,
Position = {
{
x = -49.999968,
y = 540
},
{
x = 1500.0048,
y = 540
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
{
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 5,
Position = {
{
x = -72,
y = 324
},
{
x = 5760,
y = 324
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[8] = {
Type = 0,
nPointCount = 2,
Next = 14,
Delay = 4500,
id = 8,
Position = {
{
x = 0,
y = 954
},
{
x = 0,
y = 747
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[9] = {
Type = 0,
nPointCount = 2,
Next = 15,
Delay = 4500,
id = 9,
Position = {
{
x = 0,
y = -54
},
{
x = 0,
y = 153
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[10] = {
Type = 0,
nPointCount = 2,
Next = 16,
Delay = 4600,
id = 10,
Position = {
{
x = 0,
y = 1053
},
{
x = 0,
y = 702
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[11] = {
Type = 0,
nPointCount = 2,
Next = 17,
Delay = 4600,
id = 11,
Position = {
{
x = 0,
y = -153
},
{
x = 0,
y = 198
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[12] = {
Type = 0,
nPointCount = 2,
Next = 18,
Delay = 4700,
id = 12,
Position = {
{
x = 0,
y = 1152
},
{
x = 0,
y = 648
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[13] = {
Type = 0,
nPointCount = 2,
Next = 19,
Delay = 4700,
id = 13,
Position = {
{
x = 0,
y = -252
},
{
x = 0,
y = 252
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[14] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 14,
Position = {
{
x = 0,
y = 749.9997
},
{
x = 0,
y = -50.00004
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[15] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 15,
Position = {
{
x = 0,
y = 150.0003
},
{
x = 0,
y = 950.004
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[16] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 16,
Position = {
{
x = 0,
y = 700.0002
},
{
x = 0,
y = -50.00004
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[17] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 17,
Position = {
{
x = 0,
y = 199.9998
},
{
x = 0,
y = 950.004
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[18] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 18,
Position = {
{
x = 0,
y = 649.9998
},
{
x = 0,
y = -50.00004
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[19] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 19,
Position = {
{
x = 0,
y = 250.0002
},
{
x = 0,
y = 950.004
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[20] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 20,
Position = {
{
x = 1512,
y = 450
},
{
x = -5760,
y = 450
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[21] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 21,
Position = {
{
x = 90,
y = -50.00004
},
{
x = 90,
y = 950.004
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[22] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 22,
Position = {
{
x = 229.99968,
y = 950.004
},
{
x = 229.99968,
y = -50.00004
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[23] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 23,
Position = {
{
x = 369.99936,
y = -50.00004
},
{
x = 369.99936,
y = 950.004
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[24] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 24,
Position = {
{
x = 510.00048,
y = 950.004
},
{
x = 510.00048,
y = -50.00004
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[25] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 25,
Position = {
{
x = 650.00016,
y = -50.00004
},
{
x = 650.00016,
y = 950.004
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[26] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 26,
Position = {
{
x = 789.99984,
y = 950.004
},
{
x = 789.99984,
y = -50.00004
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[27] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 27,
Position = {
{
x = 929.99952,
y = -50.00004
},
{
x = 929.99952,
y = 950.004
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[28] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 28,
Position = {
{
x = 1070.00064,
y = 950.004
},
{
x = 1070.00064,
y = -50.00004
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[29] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 29,
Position = {
{
x = 1210.00032,
y = -50.00004
},
{
x = 1210.00032,
y = 950.004
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[30] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 30,
Position = {
{
x = 1350,
y = 950.004
},
{
x = 1350,
y = -50.00004
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[31] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 31,
Position = {
{
x = -150.00048,
y = 450
},
{
x = 720,
y = -150.0003
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[32] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 32,
Position = {
{
x = 720,
y = -150.0003
},
{
x = 1590.0048,
y = 450
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[33] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 33,
Position = {
{
x = 1590.0048,
y = 450
},
{
x = 720,
y = 1050.003
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[34] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 34,
Position = {
{
x = 720,
y = 1050.003
},
{
x = -150.00048,
y = 450
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[35] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 35,
Position = {
{
x = 479.99952,
y = -99.9999
},
{
x = 479.99952,
y = 999.999
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[36] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 36,
Position = {
{
x = 960.00048,
y = 999.999
},
{
x = 960.00048,
y = -99.9999
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[37] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 37,
Position = {
{
x = 1550.0016,
y = 299.9997
},
{
x = -99.999936,
y = 299.9997
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[38] = {
Type = 0,
nPointCount = 2,
Next = 0,
Delay = 0,
id = 38,
Position = {
{
x = -99.999936,
y = 600.0003
},
{
x = 1550.0016,
y = 600.0003
},
{
x = 0,
y = 0
},
{
x = 0,
y = 0
}
}
},
[39] = {
Type = 1,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 39,
Position = {
{
x = -99.999936,
y = 999.999
},
{
x = 720,
y = 399.9996
},
{
x = 1539.9936,
y = 999.999
},
{
x = 0,
y = 0
}
}
},
[40] = {
Type = 1,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 40,
Position = {
{
x = -99.999936,
y = 900
},
{
x = 720,
y = 299.9997
},
{
x = 1539.9936,
y = 900
},
{
x = 0,
y = 0
}
}
},
[41] = {
Type = 1,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 41,
Position = {
{
x = -99.999936,
y = 800.0001
},
{
x = 720,
y = 199.9998
},
{
x = 1539.9936,
y = 800.0001
},
{
x = 0,
y = 0
}
}
},
[42] = {
Type = 1,
nPointCount = 3,
Next = 0,
Delay = 0,
id = 42,
Position = {
{
x = 1539.9936,
y = -99.9999
},
{
x = 720,
y = 500.0004
},
{
x = -99.999936,
y = -99.9999
},
{
x = 0,
y = 0
}
}
},
[43] = {
Type = 1,
nPointCount = 3,
Next = 0,
Delay = 0,
id = 43,
Position = {
{
x = 1539.9936,
y = 0
},
{
x = 720,
y = 600.0003
},
{
x = -99.999936,
y = 0
},
{
x = 0,
y = 0
}
}
},
[44] = {
Type = 1,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 44,
Position = {
{
x = 1539.9936,
y = 99.9999
},
{
x = 720,
y = 700.0002
},
{
x = -99.999936,
y = 99.9999
},
{
x = 0,
y = 0
}
}
},
[45] = {
Type = 2,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 45,
Position = {
{
x = 720,
y = 450
},
{
x = 200,
y = 0.5
},
{
x = 0,
y = 8
},
{
x = 0,
y = 0
}
}
},
[46] = {
Type = 2,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 46,
Position = {
{
x = 720,
y = 450
},
{
x = 200,
y = 0.5
},
{
x = 0.314,
y = 8
},
{
x = 0,
y = 0
}
}
},
[47] = {
Type = 2,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 47,
Position = {
{
x = 720,
y = 450
},
{
x = 200,
y = 0.5
},
{
x = 0.628,
y = 8
},
{
x = 0,
y = 0
}
}
},
[48] = {
Type = 2,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 48,
Position = {
{
x = 720,
y = 450
},
{
x = 200,
y = 0.5
},
{
x = 0.942,
y = 8
},
{
x = 0,
y = 0
}
}
},
[49] = {
Type = 2,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 49,
Position = {
{
x = 720,
y = 450
},
{
x = 200,
y = 0.5
},
{
x = 1.256,
y = 8
},
{
x = 0,
y = 0
}
}
},
[50] = {
Type = 2,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 50,
Position = {
{
x = 720,
y = 450
},
{
x = 200,
y = 0.5
},
{
x = 1.57,
y = 8
},
{
x = 0,
y = 0
}
}
},
[51] = {
Type = 2,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 51,
Position = {
{
x = 720,
y = 450
},
{
x = 200,
y = 0.5
},
{
x = 1.884,
y = 8
},
{
x = 0,
y = 0
}
}
},
[52] = {
Type = 2,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 52,
Position = {
{
x = 720,
y = 450
},
{
x = 200,
y = 0.5
},
{
x = 2.198,
y = 8
},
{
x = 0,
y = 0
}
}
},
[53] = {
Type = 2,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 53,
Position = {
{
x = 720,
y = 450
},
{
x = 200,
y = 0.5
},
{
x = 2.512,
y = 8
},
{
x = 0,
y = 0
}
}
},
[54] = {
Type = 2,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 54,
Position = {
{
x = 720,
y = 450
},
{
x = 200,
y = 0.5
},
{
x = 2.826,
y = 8
},
{
x = 0,
y = 0
}
}
},
[55] = {
Type = 2,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 55,
Position = {
{
x = 720,
y = 450
},
{
x = 200,
y = 0.5
},
{
x = 3.14,
y = 8
},
{
x = 0,
y = 0
}
}
},
[56] = {
Type = 2,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 56,
Position = {
{
x = 720,
y = 450
},
{
x = 200,
y = 0.5
},
{
x = 3.454,
y = 8
},
{
x = 0,
y = 0
}
}
},
[57] = {
Type = 2,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 57,
Position = {
{
x = 720,
y = 450
},
{
x = 200,
y = 0.5
},
{
x = 3.768,
y = 8
},
{
x = 0,
y = 0
}
}
},
[58] = {
Type = 2,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 58,
Position = {
{
x = 720,
y = 450
},
{
x = 200,
y = 0.5
},
{
x = 4.082,
y = 8
},
{
x = 0,
y = 0
}
}
},
[59] = {
Type = 2,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 59,
Position = {
{
x = 720,
y = 450
},
{
x = 200,
y = 0.5
},
{
x = 4.396,
y = 8
},
{
x = 0,
y = 0
}
}
},
[60] = {
Type = 2,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 60,
Position = {
{
x = 720,
y = 450
},
{
x = 200,
y = 0.5
},
{
x = 4.71,
y = 8
},
{
x = 0,
y = 0
}
}
},
[61] = {
Type = 2,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 61,
Position = {
{
x = 720,
y = 450
},
{
x = 200,
y = 0.5
},
{
x = 5.024,
y = 8
},
{
x = 0,
y = 0
}
}
},
[62] = {
Type = 2,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 62,
Position = {
{
x = 720,
y = 450
},
{
x = 200,
y = 0.5
},
{
x = 5.338,
y = 8
},
{
x = 0,
y = 0
}
}
},
[63] = {
Type = 2,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 63,
Position = {
{
x = 720,
y = 450
},
{
x = 200,
y = 0.5
},
{
x = 5.652,
y = 8
},
{
x = 0,
y = 0
}
}
},
[64] = {
Type = 2,
nPointCount = 4,
Next = 0,
Delay = 0,
id = 64,
Position = {
{
x = 720,
y = 450
},
{
x = 200,
y = 0.5
},
{
x = 5.966,
y = 8
},
{
x = 0,
y = 0
}
}
}
}
|
data:extend({
{ -- Aircraft category
type = "equipment-category",
name = "aircraft"
},
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
{ -- Gunship grid
type = "equipment-grid",
name = "gunship-equipment-grid",
width = 8,
height = 4,
equipment_categories = {"armor", "aircraft"}
},
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
{ -- Flying Fortress grid
type = "equipment-grid",
name = "flying-fortress-equipment-grid",
width = 13,
height = 12,
equipment_categories = {"armor", "aircraft"}
},
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
{ -- Jet grid
type = "equipment-grid",
name = "jet-equipment-grid",
width = 8,
height = 4,
equipment_categories = {"armor", "aircraft"}
},
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
}) |
data:extend(
{
{
type = "recipe",
name = "cursix-mushroom",
enabled = false,
energy_required = 25,
ingredients =
{
{"wood", 5},
{"iron-gear-wheel", 10},
{"automation-science-pack", 1}
},
result = "cursix-mushroom"
},
{
type = "recipe",
name = "cursix-1up-mushroom",
enabled = false,
energy_required = 25,
ingredients =
{
{"wood", 5},
{"stone", 10},
{"logistic-science-pack", 1}
},
result = "cursix-1up-mushroom"
},
{
type = "recipe",
name = "cursix-poison-mushroom",
enabled = false,
energy_required = 25,
ingredients =
{
{"firearm-magazine", 1},
{"iron-ore", 5},
{"copper-ore", 5}
},
result = "cursix-poison-mushroom"
}
}
)
|
local source = {}
local items = require("cmp_latex_symbols/items")
source.new = function()
return setmetatable({}, { __index = source })
end
source.is_available = function()
return vim.o.filetype == 'markdown' or vim.o.filetype == 'latex'
end
source.get_trigger_characters = function()
return { "\\" }
end
source.get_keyword_pattern = function()
return "\\\\[^[:blank:]]*"
end
source.complete = function(self, request, callback)
if not vim.regex(self.get_keyword_pattern() .. "$"):match_str(request.context.cursor_before_line) then
return callback()
end
if not self.items then
self.items = items
end
callback(self.items)
end
return source
|
local tt=getTickCount()
function menuUstaw()
if getTickCount()-tt<2000 then
outputChatBox("Musisz chwile odczekac.", 255,0,0)
return
end
tt=getTickCount()
local veh=getPedOccupiedVehicle(localPlayer)
if not veh then
outputChatBox("(( Płyty możesz użyc w pojezdzie. ))")
return
end
album=tonumber(getElementData(veh,"audio:id"))
if not album or not albumyMuzyczne[album] then outputDebugString('nope') return false end
if not pojazdMaRadio(veh) then
outputChatBox("(( Ten pojazd nie posiada odtwarzacza płyt. ))")
return
end
if getVehicleOccupant(veh,0)~=localPlayer then -- and getVehicleOccupant(veh,1)~=localPlayer then
outputChatBox("(( Musisz siedzieć z przodu aby włożyć płytę do odtwarzacza. ))")
return
end
setRadioChannel(0)
local aktualnaPlyta=getElementData(veh,"audio:cd")
outputChatBox("Radio zostało włączone")
setElementData(veh, "audio:cd", {album,1})
end
addCommandHandler("wlaczRadio",menuUstaw,false,true)
function menuNext()
local veh=getPedOccupiedVehicle(localPlayer)
if not veh then return end
local aktualnaPlyta=getElementData(veh,"audio:cd")
if aktualnaPlyta and type(aktualnaPlyta)=="table" then
local album,utwor=aktualnaPlyta[1], aktualnaPlyta[2]
if (albumyMuzyczne[album]) then
outputChatBox("Zmieniono utwór.")
setRadioChannel(0)
if albumyMuzyczne[album][utwor+1] then
setElementData(veh,"audio:cd", {album, utwor+1})
return
else
setElementData(veh,"audio:cd", {album, 1})
return
end
end
end
end
addCommandHandler("nextRadio",menuNext,false,true)
function menu_cdEject()
local veh=getPedOccupiedVehicle(localPlayer)
if not veh then return end
local aktualnaPlyta=getElementData(veh,"audio:cd")
if aktualnaPlyta and type(aktualnaPlyta)=="table" then
setRadioChannel(math.random(1,11))
outputChatBox("wyłaczono audio.")
setElementData(veh,"audio:cd", false)
end
end
addCommandHandler('wylaczRadio',menu_cdEject,false,true)
local function destroyAttachedAudio(veh)
local ae=getAttachedElements(veh)
for i,v in ipairs(ae) do
if v and getElementType(v)=="sound" then
destroyElement(v)
end
end
end
local function attachSoundToVehicle(vehicle)
destroyAttachedAudio(vehicle)
local caudio=getElementData(vehicle,"audio:cd")
if not caudio or type(caudio)~="table" or not caudio[1] then return end
if not albumyMuzyczne[tonumber(caudio[1])] then return end
local snd=playSound3D("http://s15038.rbx2.fastd.svpj.pl/psz-muzyka/"..albumyMuzyczne[tonumber(caudio[1])][tonumber(caudio[2])], 0,0, -100, true)
setSoundVolume(snd,1)
attachElements(snd, vehicle)
setElementParent(snd,vehicle)
end
local vehResource=getResourceFromName("freeroam")
addEventHandler("onClientElementDataChange", getResourceRootElement(vehResource), function(dataName, oldValue)
if dataName~="audio:cd" then return end
if getElementType(source)~="vehicle" then return end
attachSoundToVehicle(source)
end, true)
addEventHandler("onClientResourceStart", resourceRoot, function()
for i,v in ipairs(getElementsByType("vehicle", getResourceRootElement(vehResource))) do
local caudio=getElementData(v,"audio:cd")
if caudio and type(caudio)=="table" and caudio[1] then
attachSoundToVehicle(v)
end
end
end)
addEventHandler("onClientVehicleExplode",getRootElement(), function()
if not getElementData(source,"audio:cd") and getElementModel(source)~= 482 then return end
destroyAttachedAudio(source)
end) |
return {
id = "WorldG006",
events = {
{
alpha = 0.3,
code = {
"GuideDetail"
},
style = {
text = "点击详情界面,可以查看已接受的任务",
mode = 2,
posY = -54.13,
dir = 1,
posX = 236.1
},
ui = {
path = "OverlayCamera/Overlay/UIMain/top/right_stage/dock/detail_button",
pathIndex = -1,
triggerType = {
1
},
fingerPos = {
posY = -26.2,
posX = 68.55
}
}
},
{
alpha = 0.5,
ui = {
path = "OverlayCamera/Overlay/UIMain/WorldDetailUI(Clone)/right/tasks/frame/main/scrollrect/content/task_tpl/info",
eventPath = "OverlayCamera/Overlay/UIMain/WorldDetailUI(Clone)/right/tasks/frame/main/scrollrect/content/task_tpl/info",
pathIndex = -1,
triggerType = {
2
},
fingerPos = {
posY = -59.57,
posX = 138.95
}
}
}
}
}
|
if not (redis.call('exists', settings_key) == 1) then
return redis.error_reply('SETTINGS_KEY_NOT_FOUND')
end
if not redis.call('zscore', client_running_key, client) then
-- Register new client
redis.call('zadd', client_running_key, 0, client)
redis.call('hset', client_num_queued_key, client, queued)
redis.call('zadd', client_last_registered_key, 0, client)
end
redis.call('zadd', client_last_seen_key, now, client)
|
----
-- Handles player crafting.
--
-- if not SDK.Player.Craft.HasFreeCrafting(ThePlayer) then
-- SDK.Player.Craft.ToggleFreeCrafting(ThePlayer)
-- end
--
-- **Source Code:** [https://github.com/dstmodders/dst-mod-sdk](https://github.com/dstmodders/dst-mod-sdk)
--
-- @module SDK.Player.Craft
-- @see SDK.Player
--
-- @author [Depressed DST Modders](https://github.com/dstmodders)
-- @copyright 2020
-- @license MIT
-- @release 0.1
----
local Craft = {
character_recipes = {},
}
local SDK
local Value
--- Helpers
-- @section helpers
local function DebugErrorFn(fn_name, ...)
SDK._DebugErrorFn(Craft, fn_name, ...)
end
local function DebugString(...)
SDK._DebugString("[player]", "[craft]", ...)
end
local function ArgPlayer(fn_name, value)
return SDK._ArgPlayer(Craft, fn_name, value)
end
local function ArgRecipe(fn_name, value)
return SDK._ArgRecipe(Craft, fn_name, value)
end
local function ArgRecipes(fn_name, value)
return SDK._ArgRecipes(Craft, fn_name, value)
end
local function GetComponent(fn_name, entity, name)
return SDK._GetComponent(Craft, fn_name, entity, name)
end
local function GetReplica(fn_name, entity, name)
return SDK._GetReplica(Craft, fn_name, entity, name)
end
--- Free Crafting
-- @section free-crafting
--- Checks if a player has a free crafting.
-- @tparam[opt] EntityScript player Player instance (owner by default)
-- @treturn boolean
function Craft.HasFreeCrafting(player)
player = ArgPlayer("HasFreeCrafting", player)
return SDK.Utils.Chain.Get(player, "player_classified", "isfreebuildmode", true)
end
--- Sets a temperature value.
-- @see SDK.Remote.Player.ToggleFreeCrafting
-- @tparam[opt] EntityScript player Player instance (owner by default)
-- @treturn number
function Craft.ToggleFreeCrafting(player)
local fn_name = "ToggleFreeCrafting"
player = ArgPlayer(fn_name, player)
if not player then
return false
end
if TheWorld.ismastersim then
local component = GetComponent(fn_name, player, "builder")
if not component then
return false
end
DebugString("Toggle free crafting:", player:GetDisplayName())
component:GiveAllRecipes()
player:PushEvent("techlevelchange")
return true
end
return SDK.Remote.Player.ToggleFreeCrafting(player)
end
--- Recipe
-- @section recipe
--- Checks if a recipe is learned.
--
-- The learned recipes are retrieved using the `GetLearnedRecipes`.
--
-- **NB!** Free crafting doesn't affect this so it should be handled separately.
--
-- @tparam string recipe Recipe name
-- @tparam[opt] EntityScript player Player instance (owner by default)
-- @treturn boolean
function Craft.IsLearnedRecipe(recipe, player)
local fn_name = "IsLearnedRecipe"
recipe = ArgRecipe(fn_name, recipe)
player = ArgPlayer(fn_name, player)
return recipe and player and SDK.Utils.Table.HasValue(Craft.GetLearnedRecipes(player), recipe)
end
--- Sends a request to lock a recipe.
-- @tparam string recipe Valid recipe
-- @tparam[opt] EntityScript player Player instance (owner by default)
-- @treturn boolean
function Craft.LockRecipe(recipe, player)
local fn_name = "LockRecipe"
recipe = ArgRecipe(fn_name, recipe)
player = ArgPlayer(fn_name, player)
if not recipe or not player then
return false
end
if TheWorld.ismastersim then
local component = GetComponent(fn_name, player, "builder")
if not component then
return false
end
local replica = GetReplica(fn_name, player, "builder")
if not replica then
return false
end
local recipes = SDK.Utils.Chain.Get(player, "components", "builder", "recipes")
if not recipes then
DebugErrorFn(fn_name, "Builder component recipes not found")
return false
end
DebugString("Lock recipe:", recipe, "(" .. player:GetDisplayName() .. ")")
for k, v in pairs(recipes) do
if v == recipe then
table.remove(recipes, k)
end
end
replica:RemoveRecipe(recipe)
return true
end
return SDK.Remote.Player.LockRecipe(recipe, player)
end
--- Sends a request to unlock a recipe.
-- @tparam string recipe Valid recipe
-- @tparam[opt] EntityScript player Player instance (owner by default)
-- @treturn boolean
function Craft.UnlockRecipe(recipe, player)
local fn_name = "UnlockRecipe"
recipe = ArgRecipe(fn_name, recipe)
player = ArgPlayer(fn_name, player)
if not recipe or not player then
return false
end
if TheWorld.ismastersim then
local component = GetComponent(fn_name, player, "builder")
if not component then
return false
end
DebugString("Unlock recipe:", recipe, "(" .. player:GetDisplayName() .. ")")
component:AddRecipe(recipe)
player:PushEvent("unlockrecipe", { recipe = recipe })
return true
end
return SDK.Remote.Player.UnlockRecipe(recipe, player)
end
--- Recipes
-- @section recipes
--- Filters all recipes by a function.
-- @tparam function fn Filter function
-- @tparam[opt] table recipes Recipes to filter (`AllRecipes` by default)
-- @treturn table
function Craft.FilterRecipesBy(fn, recipes)
recipes = ArgRecipes("FilterRecipesBy", recipes)
local t = {}
if type(recipes) == "table" then
for name, data in pairs(recipes) do
if fn(name, data) then
t[name] = data
end
end
end
return t
end
--- Filters all recipes that have been learned.
-- @tparam[opt] table recipes Recipes to filter (`AllRecipes` by default)
-- @tparam[opt] EntityScript player Player instance (owner by default)
-- @treturn table
function Craft.FilterRecipesByLearned(recipes, player)
local fn_name = "FilterRecipesByLearned"
recipes = ArgRecipes(fn_name, recipes)
player = ArgPlayer(fn_name, player)
if not recipes or not player then
return {}
end
return Craft.FilterRecipesBy(function(name)
return Craft.IsLearnedRecipe(name, player)
end, recipes)
end
--- Filters all recipes that haven't been learned.
-- @tparam[opt] table recipes Recipes to filter (`AllRecipes` by default)
-- @tparam[opt] EntityScript player Player instance (owner by default)
-- @treturn table
function Craft.FilterRecipesByNotLearned(recipes, player)
local fn_name = "FilterRecipesByNotLearned"
recipes = ArgRecipes(fn_name, recipes)
player = ArgPlayer(fn_name, player)
if not recipes or not player then
return {}
end
return Craft.FilterRecipesBy(function(name)
return not Craft.IsLearnedRecipe(name, player)
end, recipes)
end
--- Filters all recipes that include a certain field.
-- @tparam string field Field to check
-- @tparam[opt] table recipes Recipes to filter (`AllRecipes` by default)
-- @treturn table
function Craft.FilterRecipesWith(field, recipes)
recipes = ArgRecipes("FilterRecipesWith", recipes)
return recipes and Craft.FilterRecipesBy(function(_, data)
return data[field]
end, recipes) or {}
end
--- Gets all recipes that exclude a certain field.
-- @tparam string field Field to check
-- @tparam[opt] table recipes Recipes to filter (`AllRecipes` by default)
-- @treturn table
function Craft.FilterRecipesWithout(field, recipes)
recipes = ArgRecipes("FilterRecipesWithout", recipes)
return recipes and Craft.FilterRecipesBy(function(_, data)
return not data[field]
end, recipes) or {}
end
--- Gets learned recipes.
--
-- **NB!** Free crafting doesn't affect this as it contains only recipes that were learned when it
-- was disabled.
--
-- @tparam[opt] EntityScript player Player instance (owner by default)
-- @treturn table
function Craft.GetLearnedRecipes(player)
local fn_name = "GetLearnedRecipes"
player = ArgPlayer(fn_name, player)
if not player then
return
end
if TheWorld.ismastersim then
local component = GetComponent(fn_name, player, "builder")
return component and component.recipes
end
local replica = GetReplica(fn_name, player, "builder")
if not replica then
return
end
local recipes = SDK.Utils.Chain.Get(replica, "classified", "recipes")
if not recipes then
return
end
local names = {}
for name, net_bool in pairs(recipes) do
if net_bool:value() then
if Value.IsRecipeValid(name) then
table.insert(names, name)
end
end
end
return names
end
--- Locks all character-specific recipes.
--
-- It locks all character-specific recipes except those stored earlier by the
-- `UnlockCharacterRecipes` method.
function Craft.LockAllCharacterRecipes(player)
player = ArgPlayer("LockAllCharacterRecipes", player)
if not player then
return false
end
local recipes = Craft.FilterRecipesWith("builder_tag")
if SDK.Utils.Table.Count(recipes) > 0 then
DebugString("Locking and restoring all character recipes...")
for name, _ in pairs(recipes) do
if not SDK.Utils.Table.HasValue(Craft.character_recipes[player.userid], name) then
Craft.LockRecipe(name, player)
end
end
Craft.character_recipes[player.userid] = {}
return true
end
DebugErrorFn("LockAllCharacterRecipes", "Character recipes not found")
return false
end
--- Unlocks all character-specific recipes.
--
-- It stores the originally learned recipes in order to restore them when using the corresponding
-- `LockCharacterRecipes` method and then unlocks all character-specific recipes.
function Craft.UnlockAllCharacterRecipes(player)
player = ArgPlayer("UnlockAllCharacterRecipes", player)
if not player then
return false
end
if #Craft.character_recipes[player.userid] == 0 then
local recipes = Craft.FilterRecipesWith("builder_tag")
local learned = Craft.FilterRecipesByLearned(recipes, player)
local learned_total = SDK.Utils.Table.Count(learned)
if learned_total > 0 then
DebugString(
"Storing",
tostring(learned_total),
"previously learned character recipes..."
)
local t = {}
for name, _ in pairs(learned) do
table.insert(t, name)
end
Craft.character_recipes[player.userid] = t
end
if SDK.Utils.Table.Count(recipes) > 0 then
DebugString("Unlocking all character recipes...")
for name, _ in pairs(recipes) do
Craft.UnlockRecipe(name, player)
end
end
return true
end
local total = #Craft.character_recipes[player.userid]
DebugErrorFn(
"UnlockAllCharacterRecipes",
"Already",
tostring(total),
(total > 1 or total == 0) and "recipes are stored" or "recipe is stored"
)
return false
end
--- Lifecycle
-- @section lifecycle
--- Initializes.
-- @tparam SDK sdk
-- @treturn SDK.Player.Craft
function Craft._DoInit(sdk)
SDK = sdk
Value = SDK.Utils.Value
return Craft
end
return Craft
|
--New
includeFile("custom_content/building/military/eow_imperial_endor_base.lua")
includeFile("custom_content/building/military/eow_rebel_transport.lua")
includeFile("custom_content/building/military/gcw_battlefield_base.lua")
includeFile("custom_content/building/military/military_base_shed_imperial_style_cloning_facility_s01.lua")
includeFile("custom_content/building/military/military_base_shed_rebel_style_cloning_facility_s01.lua")
includeFile("custom_content/building/military/military_imperial_clone_tent_small.lua")
includeFile("custom_content/building/military/military_rebel_clone_tent_small.lua")
includeFile("custom_content/building/military/outpost_starport_nonworking.lua")
includeFile("custom_content/building/military/prolog_content_impl_bunker_recon_outpost.lua")
includeFile("custom_content/building/military/talus_coa_aclo_office.lua")
|
if true then
-- comment
end
if true then
-- comment
print("something else after")
end
|
package.path = "../?.lua;" .. package.path
require("tests/mock")
local Queue = require("queue")
describe("Queue", function()
it("records function calls on an object for later execution on any object", function()
local queue = Queue:new()
queue:say_hello("John")
local output = ""
local target = {
say_hello = function(self, name)
output = "Hello " .. name .. "!"
end,
say_goodbye = function(name)
output = "Goodbye " .. name .. "!"
end
}
queue:_start(target)
assert.are.equal("Hello John!", output)
assert.are.same({}, queue)
queue.say_goodbye("John")
queue:_start(target)
assert.are.equal("Goodbye John!", output)
assert.has_error(function() queue.invalid(); queue:_start(target) end,
"libuix->Queue:_start(): attempt to call field 'invalid' (a nil value)")
end)
end)
|
resource_manifest_version '44febabe-d386-4d18-afbe-5e627f4af937'
description 'Server Logging'
version '1.0'
server_script 'server.lua'
client_script 'client.lua'
--edit and cleand up by NebelRebell
|
vim.g.markdown_image_paste = '/home/mark/Pictures/'
|
--- === plugins.core.application.manager ===
---
--- Application manager.
local require = require
local fnutils = require "hs.fnutils"
local config = require "cp.config"
local copy = fnutils.copy
local mod = {}
-- applications -> table
-- Variable
-- A table of registered applications.
local applications = {}
--- plugins.core.application.manager.registerApplication(data) -> none
--- Function
--- Registers a new application.
---
--- Parameters:
--- * data - A table containing the information to register.
---
--- Returns:
--- * None
---
--- Notes:
--- * The data table should contain:
--- * displayName - The display name of the application
--- * bundleID - The bundle ID of the application
--- * searchConsoleToolbar - A table containing the Search Console Toolbar information
--- * legacyGroupID - A string containing the legacy group ID (i.e. "fcpx")
function mod.registerApplication(data)
applications[data.bundleID] = {
displayName = data.displayName,
searchConsoleToolbar = data.searchConsoleToolbar,
legacyGroupID = data.legacyGroupID,
}
end
--- plugins.core.application.manager.getApplications() -> table
--- Function
--- Gets all the registered applications.
---
--- Parameters:
--- * None
---
--- Returns:
--- * A table of all the registered applications.
function mod.getApplications()
return copy(applications)
end
--- plugins.core.application.manager.getSearchConsoleToolbar(bundleID) -> table
--- Function
--- Gets the Search Console Toolbar data for a specific bundle ID.
---
--- Parameters:
--- * bundleID - The bundle ID of the application you want to get.
---
--- Returns:
--- * A table of the Search Sonole Toolbar data for the specified application.
function mod.getSearchConsoleToolbar(bundleID)
return applications[bundleID] and applications[bundleID].searchConsoleToolbar
end
--- plugins.core.application.manager.defaultSearchConsoleToolbar() -> table
--- Function
--- Returns the default search toolbar data.
---
--- Parameters:
--- * None
---
--- Returns:
--- * A table
function mod.defaultSearchConsoleToolbar()
local iconPath = config.basePath .. "/plugins/core/console/images/"
return {
global_applications = { path = iconPath .. "apps.png", priority = 50},
global_shortcuts = { path = iconPath .. "Keyboard.icns", priority = 51},
global_snippets = { path = iconPath .. "snippets.png", priority = 52},
global_keyboardmaestro_macros = { path = iconPath .. "keyboardmaestro.icns", priority = 53},
global_loupedeck_banks = { path = iconPath .. "loupedeckbank.png", priority = 54},
global_loupedeckbanks = { path = iconPath .. "loupedeckplusbank.png", priority = 55},
global_loupedeckct_banks = { path = iconPath .. "loupedeckctbank.png", priority = 56},
global_midibanks = { path = iconPath .. "midibank.png", priority = 57},
global_streamDeckbanks = { path = iconPath .. "streamdeckbank.png", priority = 58},
global_touchbarbanks = { path = iconPath .. "touchbarbank.png", priority = 59},
global_tourbox_banks = { path = iconPath .. "tourboxbank.png", priority = 60},
}
end
local plugin = {
id = "core.application.manager",
group = "core",
dependencies = {
}
}
function plugin.init()
--------------------------------------------------------------------------------
-- Register CommandPost itself as an application:
--------------------------------------------------------------------------------
mod.registerApplication({
bundleID = config.bundleID,
displayName = config.appName,
})
return mod
end
return plugin
|
local taos_lib = require("resty.taos.library")
local taos_data = require("resty.taos.data")
local ffi = require("ffi")
local ffi_cast = ffi.cast
local ffi_new = ffi.new
local ffi_copy = ffi.copy
local ffi_string = ffi.string
local C = taos_lib
local ngx = ngx
local ngx_log = ngx.log
local ngx_DEBUG = ngx.DEBUG
local ngx_WARN = ngx.WARN
local sfmt = string.format
local ok, new_tab = pcall(require, "table.new")
if not ok then
new_tab = function (narr, nrec) return {} end
end
local _M = { _VERSION = '0.1' }
local mt = { __index = _M }
function _M.new(self, cwrap)
local wrapper = {
cwrap = cwrap
}
return setmetatable(wrapper, mt)
end
function _M.query(self, sql, callback, param)
end
function _M.fetch_rows(self, res, callback, param)
end
return _M |
mapFields = require "lib/mapFields"
if target.field == mapFields.getID("NLCSubwayStation") then
selection = self.ask_menu("Hello. Would you like to buy a ticket for the subway?", {
[0] = "Kerning City of Victoria Island"
})
if selection == 0 then
ticket = charInventory.selectTicketToVictoriaFromNLC()
cost = charInventory.getPriceOfTicket(ticket)
if self.ask_yes_no("The ride to Kerning City of Victoria Island takes off every " .. target.as_continent().term .. " minutes, beginning on the hour, and it'll cost you #b" .. cost .. " mesos#k. Are you sure you want to purchase #b#t" .. ticket .. "##k?") then
charInventory.buyTicket(ticket, cost)
else
self.say("You must have some business to take care of here, right?")
end
end
elseif target.field == mapFields.getID("SubwayTicketingBooth") then
selection = self.ask_menu("Hello, I'm in charge of selling tickets for the subway ride for some destination. Which ticket would you like to purchase?", {
[0] = "New Leaf City of Masteria"
})
if selection == 0 then
ticket = charInventory.selectTicketToNLCFromVictoria()
cost = charInventory.getPriceOfTicket(ticket)
if self.ask_yes_no("The ride to New Leaf City of Masteria takes off every " .. target.get_continent().term .. " minutes, beginning on the hour, and it'll cost you #b" .. cost .. " mesos#k. Are you sure you want to purchase #b#t" .. ticket .. "##k?") then
charInventory.buyTicket(ticket, cost)
else
self.say("You must have some business to take care of here, right?")
end
end
else
local to = target.field == mapFields.getID("WaitingRoomFromNLCtoKC") and "New Leaf City" or "Kerning City"
if self.ask_yes_no("Do you want to go back to " .. to .. " subway station now?") then
target.field = target.get_continent().start_ship_move_field
else
self.say("Okay, Plase wait~!")
end
end |
local config = require'lspconfig'.texlab.document_config
require'lspconfig/configs'.texlab = nil -- important, immediately unset the loaded config again
config.default_config.cmd[1] = "./texlab"
return vim.tbl_extend('error', config, {
install_script = [[
os=$(uname -s | tr "[:upper:]" "[:lower:]")
case $os in
linux)
platform="linux"
;;
darwin)
platform="macos"
;;
esac
curl -L -o texlab.tar.gz $(curl -s https://api.github.com/repos/latex-lsp/texlab/releases/latest | grep 'browser_' | cut -d\" -f4 | grep "$platform")
tar -xzf texlab.tar.gz
rm texlab.tar.gz
]]
})
|
local awful = require("awful")
local gears = require("gears")
local gcolor = require("gears.color")
local gfs = require("gears.filesystem")
local xresources = require("beautiful.xresources")
local xrdb = xresources.get_current_theme()
local themes_path = gfs.get_themes_dir()
-- # Inherit default theme
local theme = dofile(themes_path .. "default/theme.lua")
-- # Set wallpaper
theme.wallpaper = gfs.get_configuration_dir() .. "themes/test/bg.png"
-- # Init colors
local colors = {}
if xrdb.background then
colors.bg = xrdb.background .. bg_opacity
else
colors.bg = "747474" .. bg_opacity
end
colors.fg = xrdb.foreground
-- Light bg
colors.primary = xrdb.color1
-- Dark bg
colors.secondary = xrdb.color2
-- Really dark bg
colors.tertiary = xrdb.color0
-- Red
colors.urgency = xrdb.color3
-- # Gaps
theme.useless_gap = 5
-- # Fonts
local font_common = "Noto Sans "
local font_mono = "FuraCode Nerd Font Mono "
theme.font = font_common .. "11"
theme.icon_font = font_mono .. "11"
theme.taglist_font = theme.font
-- # Background
theme.bg_normal = colors.bg
theme.bg_focus = colors.primary
theme.bg_urgent = colors.urgency
theme.bg_minimize = colors.secondary
theme.bg_systray = colors.bg
-- # Foreground
theme.fg_normal = colors.fg
theme.fg_focus = colors.fg
theme.fg_urgent = colors.fg
theme.fg_minimize = colors.fg
-- # Decorations
theme.bar_spacing = 10
theme.border_width = 0
-- # Taglist
theme.taglist_bg_focus = colors.primary .. bg_opacity
theme.taglist_bg_urgent = colors.urgency .. bg_opacity
theme.taglist_bg_occupied = gcolor.transparent
theme.taglist_bg_empty = gcolor.transparent
theme.taglist_bg_volatile = colors.primary .. bg_opacity
theme.taglist_bg_hover = colors.secondary .. bg_opacity
theme.taglist_fg_focus = colors.fg
theme.taglist_fg_urgent = colors.fg
theme.taglist_fg_occupied = colors.fg
theme.taglist_fg_empty = colors.fg
theme.taglist_fg_volatile = colors.fg
theme.taglist_tag_margin = 5
theme.taglist_squares_height = 2
-- The 50 is completely arbitrary
theme.taglist_squares_sel = gears.surface.load_from_shape(50, theme.taglist_squares_height, gears.shape.rectangle, colors.primary)
theme.taglist_squares_unsel = theme.taglist_squares_sel
-- theme.taglist_squares_sel_empty = nil
-- theme.taglist_squares_unsel_empty = nil
-- theme.taglist_squares_resize = nil
-- theme.taglist_disable_icon = nil
-- theme.taglist_spacing = nil
-- theme.taglist_shape = nil
-- theme.taglist_shape_border_width = nil
-- theme.taglist_shape_border_color = nil
-- theme.taglist_shape_empty = nil
-- theme.taglist_shape_border_width_empty = nil
-- theme.taglist_shape_border_color_empty = nil
-- theme.taglist_shape_focus = nil
-- theme.taglist_shape_border_width_focus = nil
-- theme.taglist_shape_border_color_focus = nil
-- theme.taglist_shape_urgent = nil
-- theme.taglist_shape_border_width_urgent = nil
-- theme.taglist_shape_border_color_urgent = nil
-- theme.taglist_shape_volatile = nil
-- theme.taglist_shape_border_width_volatile = nil
-- theme.taglist_shape_border_color_volatile = nil
-- # Tasklist
theme.tasklist_bg_normal = gcolor.transparent
theme.tasklist_bg_focus = gcolor.transparent
theme.tasklist_bg_urgent = colors.urgency
theme.tasklist_bg_minimize = gcolor.transparent
theme.tasklist_plain_task_name = true
theme.tasklist_bg_hover = colors.secondary .. bg_opacity
-- theme.tasklist_fg_normal = nil
-- theme.tasklist_fg_focus = nil
-- theme.tasklist_fg_urgent = nil
theme.tasklist_fg_minimize = colors.fg .. bg_opacity
-- theme.tasklist_bg_image_normal = nil
-- theme.tasklist_bg_image_focus = nil
-- theme.tasklist_bg_image_urgent = nil
-- theme.tasklist_bg_image_minimize = nil
-- theme.tasklist_disable_icon = nil
-- theme.tasklist_disable_task_name = nil
-- theme.tasklist_sticky = nil
-- theme.tasklist_ontop = nil
-- theme.tasklist_above = nil
-- theme.tasklist_below = nil
-- theme.tasklist_floating = nil
-- theme.tasklist_maximized = nil
-- theme.tasklist_maximized_horizontal = nil
-- theme.tasklist_maximized_vertical = nil
-- theme.tasklist_font = nil
-- theme.tasklist_align = nil
-- theme.tasklist_font_focus = nil
-- theme.tasklist_font_minimized = nil
-- theme.tasklist_font_urgent = nil
-- theme.tasklist_spacing = nil
-- theme.tasklist_shape = nil
-- theme.tasklist_shape_border_width = nil
-- theme.tasklist_shape_border_color = nil
-- theme.tasklist_shape_focus = nil
-- theme.tasklist_shape_border_width_focus = nil
-- theme.tasklist_shape_border_color_focus = nil
-- theme.tasklist_shape_minimized = nil
-- theme.tasklist_shape_border_width_minimized = nil
-- theme.tasklist_shape_border_color_minimized = nil
-- theme.tasklist_shape_urgent = nil
-- theme.tasklist_shape_border_width_urgent = nil
-- theme.tasklist_shape_border_color_urgent = nil
-- theme.bg_normal = nil
-- theme.fg_normal = nil
-- theme.font = nil
-- theme.bg_normal = nil
-- theme.bg_focus = nil
-- theme.bg_urgent = nil
-- theme.bg_minimize = nil
-- theme.bg_systray = nil
-- theme.fg_normal = nil
-- theme.fg_focus = nil
-- theme.fg_urgent = nil
-- theme.fg_minimize = nil
-- theme.useless_gap = nil
-- theme.border_width = nil
-- theme.border_color = nil
-- theme.wallpaper = nil
-- theme.bg_normal = nil
-- theme.fg_normal = nil
-- theme.bg_normal = nil
-- theme.fg_normal = nil
-- theme.bg_systray = nil
-- theme.font = nil
-- theme.border_color_marked = nil
-- theme.border_color_floating = nil
-- theme.border_color_maximized = nil
-- theme.border_color_fullscreen = nil
-- theme.border_color_active = nil
-- theme.border_color_normal = nil
-- theme.border_color_urgent = nil
-- theme.border_color_new = nil
-- theme.border_color_floating_active = nil
-- theme.border_color_floating_normal = nil
-- theme.border_color_floating_urgent = nil
-- theme.border_color_floating_new = nil
-- theme.border_color_maximized_active = nil
-- theme.border_color_maximized_normal = nil
-- theme.border_color_maximized_urgent = nil
-- theme.border_color_maximized_new = nil
-- theme.border_color_fullscreen_active = nil
-- theme.border_color_fullscreen_normal = nil
-- theme.border_color_fullscreen_urgent = nil
-- theme.border_color_fullscreen_new = nil
-- theme.border_width = nil
-- theme.border_width_floating = nil
-- theme.border_width_maximized = nil
-- theme.border_width_normal = nil
-- theme.border_width_active = nil
-- theme.border_width_urgent = nil
-- theme.border_width_new = nil
-- theme.border_width_floating_normal = nil
-- theme.border_width_floating_active = nil
-- theme.border_width_floating_urgent = nil
-- theme.border_width_floating_new = nil
-- theme.border_width_maximized_normal = nil
-- theme.border_width_maximized_active = nil
-- theme.border_width_maximized_urgent = nil
-- theme.border_width_maximized_new = nil
-- theme.border_width_fullscreen_normal = nil
-- theme.border_width_fullscreen_active = nil
-- theme.border_width_fullscreen_urgent = nil
-- theme.border_width_fullscreen_new = nil
-- arcchart
-- theme.arcchart_border_color = nil
-- theme.arcchart_color = nil
-- theme.arcchart_border_width = nil
-- theme.arcchart_paddings = nil
-- theme.arcchart_thickness = nil
-- awesome
-- theme.awesome_icon = nil
-- calendar
-- theme.calendar_style = nil
-- theme.calendar_font = nil
-- theme.calendar_spacing = nil
-- theme.calendar_week_numbers = nil
-- theme.calendar_start_sunday = nil
-- theme.calendar_long_weekdays = nil
-- checkbox
-- theme.checkbox_border_width = nil
-- theme.checkbox_bg = nil
-- theme.checkbox_border_color = nil
-- theme.checkbox_check_border_color = nil
-- theme.checkbox_check_border_width = nil
-- theme.checkbox_check_color = nil
-- theme.checkbox_shape = nil
-- theme.checkbox_check_shape = nil
-- theme.checkbox_paddings = nil
-- theme.checkbox_color = nil
-- column
-- theme.column_count = nil
-- cursor
-- theme.cursor_mouse_resize = nil
-- theme.cursor_mouse_move = nil
-- enable
-- theme.enable_spawn_cursor = nil
-- fullscreen
-- theme.fullscreen_hide_border = nil
-- gap
-- theme.gap_single_client = nil
-- graph
-- theme.graph_fg = nil
-- theme.graph_bg = nil
-- theme.graph_border_color = nil
-- hotkeys
-- theme.hotkeys_bg = nil
-- theme.hotkeys_fg = nil
-- theme.hotkeys_border_width = nil
-- theme.hotkeys_border_color = nil
-- theme.hotkeys_shape = nil
-- theme.hotkeys_modifiers_fg = nil
-- theme.hotkeys_label_bg = nil
-- theme.hotkeys_label_fg = nil
-- theme.hotkeys_font = nil
-- theme.hotkeys_description_font = nil
-- theme.hotkeys_group_margin = nil
-- icon
-- theme.icon_theme = nil
-- layout
-- theme.layout_cornernw = nil
-- theme.layout_cornerne = nil
-- theme.layout_cornersw = nil
-- theme.layout_cornerse = nil
-- theme.layout_fairh = nil
-- theme.layout_fairv = nil
-- theme.layout_floating = nil
-- theme.layout_magnifier = nil
-- theme.layout_max = nil
-- theme.layout_fullscreen = nil
-- theme.layout_spiral = nil
-- theme.layout_dwindle = nil
-- theme.layout_tile = nil
-- theme.layout_tiletop = nil
-- theme.layout_tilebottom = nil
-- theme.layout_tileleft = nil
-- layoutlist
-- theme.layoutlist_fg_normal = nil
-- theme.layoutlist_bg_normal = nil
-- theme.layoutlist_fg_selected = nil
-- theme.layoutlist_bg_selected = nil
-- theme.layoutlist_disable_icon = nil
-- theme.layoutlist_disable_name = nil
-- theme.layoutlist_font = nil
-- theme.layoutlist_align = nil
-- theme.layoutlist_font_selected = nil
-- theme.layoutlist_spacing = nil
-- theme.layoutlist_shape = nil
-- theme.layoutlist_shape_border_width = nil
-- theme.layoutlist_shape_border_color = nil
-- theme.layoutlist_shape_selected = nil
-- theme.layoutlist_shape_border_width_selected = nil
-- theme.layoutlist_shape_border_color_selected = nil
-- master
-- theme.master_width_factor = nil
-- theme.master_fill_policy = nil
-- theme.master_count = nil
-- maximized
-- theme.maximized_honor_padding = nil
-- theme.maximized_hide_border = nil
-- menu
-- theme.menu_submenu_icon = nil
-- theme.menu_font = nil
-- theme.menu_height = nil
-- theme.menu_width = nil
-- theme.menu_border_color = nil
-- theme.menu_border_width = nil
-- theme.menu_fg_focus = nil
-- theme.menu_bg_focus = nil
-- theme.menu_fg_normal = nil
-- theme.menu_bg_normal = nil
-- theme.menu_submenu = nil
-- menubar
-- theme.menubar_fg_normal = nil
-- theme.menubar_bg_normal = nil
-- theme.menubar_border_width = nil
-- theme.menubar_border_color = nil
-- theme.menubar_fg_focus = nil
-- theme.menubar_bg_focus = nil
-- theme.menubar_font = nil
-- notification
-- theme.notification_max_width = nil
-- theme.notification_position = nil
-- theme.notification_action_underline_normal = nil
-- theme.notification_action_underline_selected = nil
-- theme.notification_action_icon_only = nil
-- theme.notification_action_label_only = nil
-- theme.notification_action_shape_normal = nil
-- theme.notification_action_shape_selected = nil
-- theme.notification_action_shape_border_color_normal = nil
-- theme.notification_action_shape_border_color_selected = nil
-- theme.notification_action_shape_border_width_normal = nil
-- theme.notification_action_shape_border_width_selected = nil
-- theme.notification_action_icon_size_normal = nil
-- theme.notification_action_icon_size_selected = nil
-- theme.notification_action_bg_normal = nil
-- theme.notification_action_bg_selected = nil
-- theme.notification_action_fg_normal = nil
-- theme.notification_action_fg_selected = nil
-- theme.notification_action_bgimage_normal = nil
-- theme.notification_action_bgimage_selected = nil
-- theme.notification_shape_normal = nil
-- theme.notification_shape_selected = nil
-- theme.notification_shape_border_color_normal = nil
-- theme.notification_shape_border_color_selected = nil
-- theme.notification_shape_border_width_normal = nil
-- theme.notification_shape_border_width_selected = nil
-- theme.notification_icon_size_normal = nil
-- theme.notification_icon_size_selected = nil
-- theme.notification_bg_normal = nil
-- theme.notification_bg_selected = nil
-- theme.notification_fg_normal = nil
-- theme.notification_fg_selected = nil
-- theme.notification_bgimage_normal = nil
-- theme.notification_bgimage_selected = nil
-- theme.notification_font = nil
-- theme.notification_bg = nil
-- theme.notification_fg = nil
-- theme.notification_border_width = nil
-- theme.notification_border_color = nil
-- theme.notification_shape = nil
-- theme.notification_opacity = nil
-- theme.notification_margin = nil
-- theme.notification_width = nil
-- theme.notification_height = nil
-- theme.notification_spacing = nil
-- theme.notification_icon_resize_strategy = nil
-- opacity
-- theme.opacity_normal = nil
-- theme.opacity_active = nil
-- theme.opacity_urgent = nil
-- theme.opacity_new = nil
-- theme.opacity_floating_normal = nil
-- theme.opacity_floating_active = nil
-- theme.opacity_floating_urgent = nil
-- theme.opacity_floating_new = nil
-- theme.opacity_maximized_normal = nil
-- theme.opacity_maximized_active = nil
-- theme.opacity_maximized_urgent = nil
-- theme.opacity_maximized_new = nil
-- theme.opacity_fullscreen_normal = nil
-- theme.opacity_fullscreen_active = nil
-- theme.opacity_fullscreen_urgent = nil
-- theme.opacity_fullscreen_new = nil
-- piechart
-- theme.piechart_border_color = nil
-- theme.piechart_border_width = nil
-- theme.piechart_colors = nil
-- progressbar
-- theme.progressbar_bg = nil
-- theme.progressbar_fg = nil
-- theme.progressbar_shape = nil
-- theme.progressbar_border_color = nil
-- theme.progressbar_border_width = nil
-- theme.progressbar_bar_shape = nil
-- theme.progressbar_bar_border_width = nil
-- theme.progressbar_bar_border_color = nil
-- theme.progressbar_margins = nil
-- theme.progressbar_paddings = nil
-- prompt
-- theme.prompt_fg_cursor = nil
-- theme.prompt_bg_cursor = nil
-- theme.prompt_font = nil
-- theme.prompt_fg = nil
-- theme.prompt_bg = nil
-- radialprogressbar
-- theme.radialprogressbar_border_color = nil
-- theme.radialprogressbar_color = nil
-- theme.radialprogressbar_border_width = nil
-- theme.radialprogressbar_paddings = nil
-- separator
-- theme.separator_thickness = nil
-- theme.separator_border_color = nil
-- theme.separator_border_width = nil
-- theme.separator_span_ratio = nil
-- theme.separator_color = nil
-- theme.separator_shape = nil
-- slider
-- theme.slider_bar_border_width = nil
-- theme.slider_bar_border_color = nil
-- theme.slider_handle_border_color = nil
-- theme.slider_handle_border_width = nil
-- theme.slider_handle_width = nil
-- theme.slider_handle_color = nil
-- theme.slider_handle_shape = nil
-- theme.slider_bar_shape = nil
-- theme.slider_bar_height = nil
-- theme.slider_bar_margins = nil
-- theme.slider_handle_margins = nil
-- theme.slider_bar_color = nil
-- theme.slider_bar_active_color = nil
-- snap
-- theme.snap_bg = nil
-- theme.snap_border_width = nil
-- theme.snap_shape = nil
-- snapper
-- theme.snapper_gap = nil
-- systray
-- theme.systray_icon_spacing = nil
-- titlebar
-- theme.titlebar_fg_normal = nil
-- theme.titlebar_bg_normal = nil
-- theme.titlebar_bgimage_normal = nil
-- theme.titlebar_fg = nil
-- theme.titlebar_bg = nil
-- theme.titlebar_bgimage = nil
-- theme.titlebar_fg_focus = nil
-- theme.titlebar_bg_focus = nil
-- theme.titlebar_bgimage_focus = nil
-- theme.titlebar_floating_button_normal = nil
-- theme.titlebar_maximized_button_normal = nil
-- theme.titlebar_minimize_button_normal = nil
-- theme.titlebar_minimize_button_normal_hover = nil
-- theme.titlebar_minimize_button_normal_press = nil
-- theme.titlebar_close_button_normal = nil
-- theme.titlebar_close_button_normal_hover = nil
-- theme.titlebar_close_button_normal_press = nil
-- theme.titlebar_ontop_button_normal = nil
-- theme.titlebar_sticky_button_normal = nil
-- theme.titlebar_floating_button_focus = nil
-- theme.titlebar_maximized_button_focus = nil
-- theme.titlebar_minimize_button_focus = nil
-- theme.titlebar_minimize_button_focus_hover = nil
-- theme.titlebar_minimize_button_focus_press = nil
-- theme.titlebar_close_button_focus = nil
-- theme.titlebar_close_button_focus_hover = nil
-- theme.titlebar_close_button_focus_press = nil
-- theme.titlebar_ontop_button_focus = nil
-- theme.titlebar_sticky_button_focus = nil
-- theme.titlebar_floating_button_normal_active = nil
-- theme.titlebar_floating_button_normal_active_hover = nil
-- theme.titlebar_floating_button_normal_active_press = nil
-- theme.titlebar_maximized_button_normal_active = nil
-- theme.titlebar_maximized_button_normal_active_hover = nil
-- theme.titlebar_maximized_button_normal_active_press = nil
-- theme.titlebar_ontop_button_normal_active = nil
-- theme.titlebar_ontop_button_normal_active_hover = nil
-- theme.titlebar_ontop_button_normal_active_press = nil
-- theme.titlebar_sticky_button_normal_active = nil
-- theme.titlebar_sticky_button_normal_active_hover = nil
-- theme.titlebar_sticky_button_normal_active_press = nil
-- theme.titlebar_floating_button_focus_active = nil
-- theme.titlebar_floating_button_focus_active_hover = nil
-- theme.titlebar_floating_button_focus_active_press = nil
-- theme.titlebar_maximized_button_focus_active = nil
-- theme.titlebar_maximized_button_focus_active_hover = nil
-- theme.titlebar_maximized_button_focus_active_press = nil
-- theme.titlebar_ontop_button_focus_active = nil
-- theme.titlebar_ontop_button_focus_active_hover = nil
-- theme.titlebar_ontop_button_focus_active_press = nil
-- theme.titlebar_sticky_button_focus_active = nil
-- theme.titlebar_sticky_button_focus_active_hover = nil
-- theme.titlebar_sticky_button_focus_active_press = nil
-- theme.titlebar_floating_button_normal_inactive = nil
-- theme.titlebar_floating_button_normal_inactive_hover = nil
-- theme.titlebar_floating_button_normal_inactive_press = nil
-- theme.titlebar_maximized_button_normal_inactive = nil
-- theme.titlebar_maximized_button_normal_inactive_hover = nil
-- theme.titlebar_maximized_button_normal_inactive_press = nil
-- theme.titlebar_ontop_button_normal_inactive = nil
-- theme.titlebar_ontop_button_normal_inactive_hover = nil
-- theme.titlebar_ontop_button_normal_inactive_press = nil
-- theme.titlebar_sticky_button_normal_inactive = nil
-- theme.titlebar_sticky_button_normal_inactive_hover = nil
-- theme.titlebar_sticky_button_normal_inactive_press = nil
-- theme.titlebar_floating_button_focus_inactive = nil
-- theme.titlebar_floating_button_focus_inactive_hover = nil
-- theme.titlebar_floating_button_focus_inactive_press = nil
-- theme.titlebar_maximized_button_focus_inactive = nil
-- theme.titlebar_maximized_button_focus_inactive_hover = nil
-- theme.titlebar_maximized_button_focus_inactive_press = nil
-- theme.titlebar_ontop_button_focus_inactive = nil
-- theme.titlebar_ontop_button_focus_inactive_hover = nil
-- theme.titlebar_ontop_button_focus_inactive_press = nil
-- theme.titlebar_sticky_button_focus_inactive = nil
-- theme.titlebar_sticky_button_focus_inactive_hover = nil
-- theme.titlebar_sticky_button_focus_inactive_press = nil
-- tooltip
-- theme.tooltip_border_color = nil
-- theme.tooltip_bg = nil
-- theme.tooltip_fg = nil
-- theme.tooltip_font = nil
-- theme.tooltip_border_width = nil
-- theme.tooltip_opacity = nil
-- theme.tooltip_gaps = nil
-- theme.tooltip_shape = nil
-- theme.tooltip_align = nil
-- wibar
-- theme.wibar_stretch = nil
-- theme.wibar_border_width = nil
-- theme.wibar_border_color = nil
-- theme.wibar_ontop = nil
-- theme.wibar_cursor = nil
-- theme.wibar_opacity = nil
-- theme.wibar_type = nil
-- theme.wibar_width = nil
-- theme.wibar_height = nil
-- theme.wibar_bg = nil
-- theme.wibar_bgimage = nil
-- theme.wibar_fg = nil
-- theme.wibar_shape = nil
return theme
|
--
-- Licensed to the Apache Software Foundation (ASF) under one or more
-- contributor license agreements. See the NOTICE file distributed with
-- this work for additional information regarding copyright ownership.
-- The ASF licenses this file to You under the Apache License, Version 2.0
-- (the "License"); you may not use this file except in compliance with
-- the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
--- Upstream helper functions which can be used in xRPC
--
-- @module xrpc.sdk
local core = require("apisix.core")
local xrpc_socket = require("resty.apisix.stream.xrpc.socket")
local ngx_now = ngx.now
local _M = {}
---
-- Returns the connected xRPC upstream socket according to the configuration
--
-- @function xrpc.sdk.connect_upstream
-- @tparam table selected upstream node
-- @tparam table upstream configuration
-- @treturn table|nil the xRPC upstream socket, or nil if failed
function _M.connect_upstream(node, up_conf)
local sk = xrpc_socket.upstream.socket()
local ok, err = sk:connect(node.host, node.port)
if not ok then
core.log.error("failed to connect: ", err)
return nil
end
if up_conf.scheme == "tls" then
local ok, err = sk:sslhandshake(nil, node.host)
if not ok then
core.log.error("failed to handshake: ", err)
return nil
end
end
return sk
end
---
-- Returns the request level ctx with an optional id
--
-- @function xrpc.sdk.get_req_ctx
-- @tparam table xrpc session
-- @tparam string optional ctx id
-- @treturn table the request level ctx
function _M.get_req_ctx(session, id)
if not id then
id = session.id_seq
session.id_seq = session.id_seq + 1
end
local ctx = core.tablepool.fetch("xrpc_ctxs")
session.ctxs[id] = ctx
ctx.rpc_start_time = ngx_now()
return ctx
end
return _M
|
local json = require 'jsonc'
local function config_error(src, ...)
error(src .. ' error: ' .. string.format(...), 0)
end
local has_domains = (os.execute('ls -d "$IPKG_INSTROOT"/lib/gluon/domains/ >/dev/null 2>&1') == 0)
local function get_domains()
local domains = {}
local dirs = io.popen("find \"$IPKG_INSTROOT\"/lib/gluon/domains/ -name '*.json'")
for filename in dirs:lines() do
local name = string.match(filename, '([^/]+).json$')
domains[name] = assert(json.load(filename))
end
dirs:close()
if not next(domains) then
config_error('site', 'no domain configurations found')
end
return domains
end
local site, domain_code, domain, conf
local M = setmetatable({}, { __index = _G })
local function merge(a, b)
local function is_array(t)
local n = 0
for _ in pairs(t) do
n = n + 1
end
return n == #t
end
if not b then return a end
if type(a) ~= type(b) then return b end
if type(b) ~= 'table' then return b end
if not next(b) then return a end
if is_array(a) ~= is_array(b) then return b end
local m = {}
for k, v in pairs(a) do
m[k] = v
end
for k, v in pairs(b) do
m[k] = merge(m[k], v)
end
return m
end
local function path_to_string(path)
return table.concat(path, '.')
end
local function format(val)
if type(val) == 'string' then
return string.format('%q', val)
else
return tostring(val)
end
end
local function array_to_string(array)
local strings = {}
for i, v in ipairs(array) do
strings[i] = format(v)
end
return '[' .. table.concat(strings, ', ') .. ']'
end
function M.table_keys(tbl)
local keys = {}
for k in pairs(tbl) do
keys[#keys + 1] = k
end
return keys
end
local loadpath
local function site_src()
return 'site.conf'
end
local function domain_src()
return 'domains/' .. domain_code .. '.conf'
end
local function conf_src(path)
local src
if has_domains then
if loadpath(nil, domain, unpack(path)) ~= nil then
src = domain_src()
elseif loadpath(nil, site, unpack(path)) ~= nil then
src = site_src()
else
src = site_src() .. ' / ' .. domain_src()
end
else
src = site_src()
end
return src
end
local function var_error(path, val, msg)
local found = 'unset'
if val ~= nil then
found = string.format('%s (a %s value)', format(val), type(val))
end
config_error(conf_src(path), 'expected %s to %s, but it is %s', path_to_string(path), msg, found)
end
function M.in_site(path)
if has_domains and loadpath(nil, domain, unpack(path)) ~= nil then
config_error(domain_src(), '%s is allowed in site configuration only', path_to_string(path))
end
return path
end
function M.in_domain(path)
if has_domains and loadpath(nil, site, unpack(path)) ~= nil then
config_error(site_src(), '%s is allowed in domain configuration only', path_to_string(path))
end
return path
end
function M.this_domain()
return domain_code
end
function M.extend(path, c)
if not path then return nil end
local p = {unpack(path)}
for _, e in ipairs(c) do
p[#p+1] = e
end
return p
end
function loadpath(path, base, c, ...)
if not c or base == nil then
return base
end
if type(base) ~= 'table' then
if path then
var_error(path, base, 'be a table')
else
return nil
end
end
return loadpath(M.extend(path, {c}), base[c], ...)
end
local function loadvar(path)
return loadpath({}, conf, unpack(path))
end
local function check_type(t)
return function(val)
return type(val) == t
end
end
local function check_one_of(array)
return function(val)
for _, v in ipairs(array) do
if v == val then
return true
end
end
return false
end
end
function M.alternatives(...)
local errs = {'All of the following alternatives have failed:'}
for i, f in ipairs({...}) do
local ok, err = pcall(f)
if ok then
return
end
errs[#errs+1] = string.format('%i) %s', i, err)
end
error(table.concat(errs, '\n '), 0)
end
local function check_chanlist(channels)
local is_valid_channel = check_one_of(channels)
return function(chanlist)
for group in chanlist:gmatch("%S+") do
if group:match("^%d+$") then
local channel = tonumber(group)
if not is_valid_channel(channel) then
return false
end
elseif group:match("^%d+-%d+$") then
local from, to = group:match("^(%d+)-(%d+)$")
from = tonumber(from)
to = tonumber(to)
if from >= to then
return false
end
if not is_valid_channel(from) or not is_valid_channel(to) then
return false
end
else
return false
end
end
return true
end
end
function M.need(path, check, required, msg)
local val = loadvar(path)
if required == false and val == nil then
return nil
end
if not check(val) then
var_error(path, val, msg)
end
return val
end
local function need_type(path, type, required, msg)
return M.need(path, check_type(type), required, msg)
end
function M.need_alphanumeric_key(path)
local val = path[#path]
-- We don't use character classes like %w here to be independent of the locale
if type(val) ~= 'string' or not val:match('^[0-9a-zA-Z_]+$') then
var_error(path, val, 'have a string key using only alphanumeric characters and underscores')
end
end
function M.need_string(path, required)
return need_type(path, 'string', required, 'be a string')
end
function M.need_string_match(path, pat, required)
local val = M.need_string(path, required)
if not val then
return nil
end
if not val:match(pat) then
var_error(path, val, "match pattern '" .. pat .. "'")
end
return val
end
function M.need_number(path, required)
return need_type(path, 'number', required, 'be a number')
end
function M.need_number_range(path, min, max, required)
local val = need_type(path, 'number', required)
if not val then
return nil
end
if val < min or val > max then
var_error(path, val, "be in range [" .. min .. ", " .. max .. "]")
end
return val
end
function M.need_boolean(path, required)
return need_type(path, 'boolean', required, 'be a boolean')
end
function M.need_array(path, subcheck, required)
local val = need_type(path, 'table', required, 'be an array')
if not val then
return nil
end
if subcheck then
for i = 1, #val do
subcheck(M.extend(path, {i}))
end
end
return val
end
function M.need_table(path, subcheck, required)
local val = need_type(path, 'table', required, 'be a table')
if not val then
return nil
end
if subcheck then
for k, _ in pairs(val) do
subcheck(M.extend(path, {k}))
end
end
return val
end
function M.need_value(path, value, required)
return M.need(path, function(v)
return v == value
end, required, 'be ' .. tostring(value))
end
function M.need_one_of(path, array, required)
return M.need(path, check_one_of(array), required, 'be one of the given array ' .. array_to_string(array))
end
function M.need_string_array(path, required)
return M.need_array(path, M.need_string, required)
end
function M.need_string_array_match(path, pat, required)
return M.need_array(path, function(e) M.need_string_match(e, pat) end, required)
end
function M.need_array_of(path, array, required)
return M.need_array(path, function(e) M.need_one_of(e, array) end, required)
end
function M.need_chanlist(path, channels, required)
local valid_chanlist = check_chanlist(channels)
return M.need(path, valid_chanlist, required,
'be a space-separated list of WiFi channels or channel-ranges (separated by a hyphen). '
.. 'Valid channels are: ' .. array_to_string(channels))
end
function M.need_domain_name(path)
M.need_string(path)
M.need(path, function(domain_name)
local f = io.open((os.getenv('IPKG_INSTROOT') or '') .. '/lib/gluon/domains/' .. domain_name .. '.json')
if not f then return false end
f:close()
return true
end, nil, 'be a valid domain name')
end
function M.obsolete(path, msg)
local val = loadvar(path)
if val == nil then
return nil
end
if not msg then
msg = 'Check the release notes and documentation for details.'
end
config_error(conf_src(path), '%s is obsolete. %s', path_to_string(path), msg)
end
local check = setfenv(assert(loadfile()), M)
site = assert(json.load((os.getenv('IPKG_INSTROOT') or '') .. '/lib/gluon/site.json'))
local ok, err = pcall(function()
if has_domains then
for k, v in pairs(get_domains()) do
domain_code = k
domain = v
conf = merge(site, domain)
check()
end
else
conf = site
check()
end
end)
if not ok then
io.stderr:write('*** ', err, '\n')
os.exit(1)
end
|
local vim = vim
local utils = require("neo-tree.utils")
local function sort_items(a, b)
if a.type == b.type then
return a.path < b.path
else
return a.type < b.type
end
end
local function deep_sort(tbl)
table.sort(tbl, sort_items)
for _, item in pairs(tbl) do
if item.type == 'directory' then
deep_sort(item.children)
end
end
end
local create_item, set_parents
function create_item(context, path, _type)
local parent_path, name = utils.split_path(path)
if _type == nil then
local stat = vim.loop.fs_stat(path)
_type = stat and stat.type or 'unknown'
end
local item = {
id = path,
name = name,
parent_path = parent_path,
path = path,
type = _type,
}
if item.type == 'link' then
item.is_link = true
item.link_to = vim.loop.fs_realpath(path)
if item.link_to ~= nil then
item.type = vim.loop.fs_stat(item.link_to).type
end
end
if item.type == 'directory' then
item.children = {}
item.loaded = false
context.folders[path] = item
if context.state.search_pattern then
table.insert(context.state.default_expanded_nodes, item.id)
end
else
item.ext = item.name:match("%.(%w+)$")
end
set_parents(context, item)
return item
end
-- function to set (or create) parent folder
function set_parents(context, item)
-- we can get duplicate items if we navigate up with open folders
-- this is probably hacky, but it works
if context.existing_items[item.id] then
return
end
if not item.parent_path then
return
end
local parent = context.folders[item.parent_path]
if parent == nil then
local success
success, parent = pcall(create_item, context, item.parent_path, 'directory')
if not success then
print("error creating item for ", item.parent_path)
end
context.folders[parent.id] = parent
set_parents(context, parent)
end
table.insert(parent.children, item)
context.existing_items[item.id] = true
end
local create_context = function(state)
local context = {
state = state,
folders = {},
existing_items = {},
}
return context
end
return {
create_context = create_context,
create_item = create_item,
deep_sort = deep_sort,
}
|
---@class CS.FairyGUI.UIPanel : CS.UnityEngine.MonoBehaviour
---@field public packageName string
---@field public componentName string
---@field public fitScreen number
---@field public sortingOrder number
---@field public container CS.FairyGUI.Container
---@field public ui CS.FairyGUI.GComponent
---@field public EM_sortingOrder number
---@type CS.FairyGUI.UIPanel
CS.FairyGUI.UIPanel = { }
---@return CS.FairyGUI.UIPanel
function CS.FairyGUI.UIPanel.New() end
function CS.FairyGUI.UIPanel:CreateUI() end
---@param value number
---@param apply boolean
function CS.FairyGUI.UIPanel:SetSortingOrder(value, apply) end
---@param value number
function CS.FairyGUI.UIPanel:SetHitTestMode(value) end
function CS.FairyGUI.UIPanel:CacheNativeChildrenRenderers() end
---@param sortingOrderChanged boolean
---@param fitScreenChanged boolean
function CS.FairyGUI.UIPanel:ApplyModifiedProperties(sortingOrderChanged, fitScreenChanged) end
---@param delta CS.UnityEngine.Vector3
function CS.FairyGUI.UIPanel:MoveUI(delta) end
---@return CS.UnityEngine.Vector3
function CS.FairyGUI.UIPanel:GetUIWorldPosition() end
function CS.FairyGUI.UIPanel:EM_BeforeUpdate() end
---@param context CS.FairyGUI.UpdateContext
function CS.FairyGUI.UIPanel:EM_Update(context) end
function CS.FairyGUI.UIPanel:EM_Reload() end
return CS.FairyGUI.UIPanel
|
index = math.random(2)
decade = 10^index
cifre[3] = math.random(7)
numb1[1] = cifre[3]
for i = 1, 2 do
cifre[3-i] = math.random(10) - 1
numb1[1] = numb1[1] * 10 + cifre[3 - i]
end
if (cifre[index] >= 5) then
cifre[index+1] = cifre[index+1] + 1
end
for i = 1, index do
cifre[i] = 0
end
numb1[2] = cifre[3]
for i = 1, 2 do
numb1[2] = numb1[2] * 10 + cifre[3 - i]
end
temp = cifre[3]
cifre[3] = math.random(9 - temp)
numb2[1] = cifre[3]
for i = 1, 2 do
cifre[3-i] = math.random(10) - 1
numb2[1] = numb2[1] * 10 + cifre[3 - i]
end
if (cifre[index] >= 5) then
cifre[index+1] = cifre[index+1] + 1
end
for i = 1, index do
cifre[i] = 0
end
numb2[2] = cifre[3]
for i = 1, 2 do
numb2[2] = numb2[2] * 10 + cifre[3 - i]
end
if (numb1[2] > numb2[2]) then
summ = numb1[2] - numb2[2]
sign = "-"
else
summ = numb1[2] + numb2[2]
sign = "+"
end
|
local config = require('config');
local party = require('party');
local actions = require('actions');
local packets = require('packets');
local buffs = require('behaviors.buffs')
local healing = require('behaviors.healing');
local jdnc = require('jobs.dnc');
local jbrd = require('jobs.brd');
local spells = packets.spells;
local stoe = packets.stoe;
local abilities = packets.abilities;
local ability_levels = {};
ability_levels[abilities.CORSAIRS_ROLL] = 5;
ability_levels[abilities.NINJA_ROLL] = 8;
ability_levels[abilities.HUNTERS_ROLL] = 11;
ability_levels[abilities.CHAOS_ROLL] = 14;
ability_levels[abilities.MAGUSS_ROLL] = 17;
ability_levels[abilities.HEALERS_ROLL] = 20;
ability_levels[abilities.DRACHEN_ROLL] = 23;
ability_levels[abilities.CHORAL_ROLL] = 26;
ability_levels[abilities.MONKS_ROLL] = 31;
ability_levels[abilities.BEAST_ROLL] = 34;
ability_levels[abilities.SAMURAI_ROLL] = 37;
ability_levels[abilities.EVOKERS_ROLL] = 40;
ability_levels[abilities.ROGUES_ROLL] = 43;
ability_levels[abilities.WARLOCKS_ROLL] = 46;
ability_levels[abilities.FIGHTERS_ROLL] = 49;
ability_levels[abilities.PUPPET_ROLL] = 52;
ability_levels[abilities.GALLANTS_ROLL] = 55;
ability_levels[abilities.WIZARDS_ROLL] = 58;
ability_levels[abilities.DANCERS_ROLL] = 61;
ability_levels[abilities.SCHOLARS_ROLL] = 64;
local jcor = {
ability_levels = ability_levels
};
function jcor:tick()
if (actions.busy) then return end
local cnf = config:get();
local cor = cnf['corsair'];
if (not(cor['roll'])) then return end
local status = party:GetBuffs(0);
if (status[packets.status.EFFECT_INVISIBLE]) then return end
-- CORSAIR ROLLS - TO BE FIXED TO RE-ROLL FOR DOUBLE UPS --
local cnf = config:get();
if (cnf.corsair.rollvar1 and not(status[stoe[cnf.corsair.rollvar1]])) then
if (buffs:IsAble(abilities[cnf.corsair.rollvar1], ability_levels)) then
actions.busy = true;
actions:queue(actions:new()
:next(partial(ability, '"' .. cnf.corsair.roll1 .. '"', '<me>'))
:next(partial(wait, 7))
:next(function(self) actions.busy = false; end));
return;
end
end
if (cnf.corsair.rollvar2 and not(status[stoe[cnf.corsair.rollvar2]])) then
if (buffs:IsAble(abilities[cnf.corsair.rollvar2], ability_levels)) then
actions.busy = true;
actions:queue(actions:new()
:next(partial(ability, '"' .. cnf.corsair.roll2 .. '"', '<me>'))
:next(partial(wait, 7))
:next(function(self) actions.busy = false; end));
return;
end
end
-- ATTACKING AND WEAPONSKILLING
local tp = AshitaCore:GetDataManager():GetParty():GetMemberCurrentTP(0);
local tid = AshitaCore:GetDataManager():GetTarget():GetTargetServerId();
if (cnf.ATTACK_TID and tid ~= cnf.ATTACK_TID) then
cnf.ATTACK_TID = nil;
AshitaCore:GetChatManager():QueueCommand("/follow " .. cnf.leader, 1);
elseif (cnf.ATTACK_TID and tid == cnf.ATTACK_TID and tp >= 1000) then
if (cnf.WeaponSkillID ~= nil ) then
if AshitaCore:GetDataManager():GetPlayer():HasWeaponSkill(tonumber(cnf.WeaponSkillID)) then
for k, v in pairs(packets.weaponskills) do
if (tonumber(cnf.WeaponSkillID) == tonumber(v)) then
AshitaCore:GetChatManager():QueueCommand('/ws "' .. string.gsub(k,"_"," ") .. '" <t>', 1);
end
end
end
end
elseif (cnf.ATTACK_TID) then
AshitaCore:GetChatManager():QueueCommand("/ra <t>", 1);
end
-- SUBJOBS
local sub = AshitaCore:GetDataManager():GetPlayer():GetSubJob();
-- IF SUBJOB IS DANCER, DO DANCER THINGS
if (sub == Jobs.Dancer and cnf.ATTACK_TID ~= nil) then
local status = party:GetBuffs(0);
if (tp >= 150 and buffs:IsAble(abilities.DRAIN_SAMBA, jdnc.ability_levels) and status[stoe.DRAIN_SAMBA] ~= true) then
actions.busy = true;
actions:queue(actions:new()
:next(partial(ability, '"Drain Samba"', '<me>'))
:next(partial(wait, 8))
:next(function(self) actions.busy = false; end));
return;
end
-- IF SUBJOB IS BARD, DO BARD THINGS
elseif (sub == Jobs.Bard and (cnf.bard.songvar1 and not(status[stoe[cnf.bard.songvar1]]))) then
if (buffs:CanCast(spells[cnf.bard.songvar1], jbrd.spell_levels, true)) then
actions.busy = true;
actions:queue(actions:new()
:next(partial(magic, '"' .. cnf.bard.song1 .. '"', '<me>'))
:next(partial(wait, 7))
:next(function(self) actions.busy = false; end));
return;
end
end
end
function jcor:attack(tid)
actions:queue(actions:new()
:next(function(self)
AshitaCore:GetChatManager():QueueCommand('/attack ' .. tid, 0);
end)
:next(function(self)
config:get().ATTACK_TID = tid;
AshitaCore:GetChatManager():QueueCommand('/follow ' .. tid, 0);
end)
);
end
function jcor:corsair(corsair, command, roll)
local cnf = config:get();
local cor = cnf['corsair'];
local onoff = cor['roll'] and 'on' or 'off';
local roll1 = cor['roll1'] or 'none';
local roll2 = cor['roll2'] or 'none';
local rollvar;
if(roll ~= nil) then
rollvar = roll:upper():gsub("'", ""):gsub(" ", "_");
end
if (command ~= nil) then
if (command == 'on' or command == 'true') then
cor['roll'] = true;
onoff = 'on';
elseif (command == 'off' or command == 'false') then
cor['roll'] = false;
onoff = 'off';
elseif (command == '1' and roll and abilities[rollvar]) then
cor['roll1'] = roll;
cor['rollvar1'] = rollvar;
roll1 = roll;
elseif (command == '2' and roll and abilities[rollvar]) then
cor['roll2'] = roll;
cor['rollvar2'] = rollvar;
roll2 = roll;
elseif (command =='1' and roll == 'none') then
cor['roll1'] = nil;
cor['rollvar1'] = nil;
roll1 = 'none';
elseif (command =='2' and roll == 'none') then
cor['roll2'] = nil;
cor['rollvar2'] = nil;
roll2 = 'none';
end
config:save();
end
AshitaCore:GetChatManager():QueueCommand('/l2 I\'m a Corsair!\nrolling: ' .. onoff .. '\n1: ' .. roll1 .. '\n2: ' .. roll2, 1);
end
return jcor;
|
function love.conf(t)
t.console = true -- attach console when running on windows
end |
SubTitles=
{
{{255,255,255}, 0.1, 0.1, 1,"fleetintel#.tga",1},
{{255,255,255}, 0.1, 0.1, 1,"fleetcommand#.tga",1},
{{255,255,255}, 0.1, 0.1, 1,"makaan#.tga",1},
{{255,255,255}, 0.1, 0.1, 1,"keeper#.tga",1},
{{255,255,255}, 0.1, 0.1, 1,"chimera#.tga",1},
{{255,255,255}, 0.1, 0.1, 1,"bentusi#.tga",1},
{{255,255,255}, 0.2, 0.2, 0,"tur_carrier#.tga",1},
{{255,255,255}, 0.1, 0.1, 1,"bishop#.tga",1},
{{200,160,255}, 0.2, 0.2, 0,"tai_scout#.tga",1},
{{255,255,255}, 0.1, 0.1, 1,"tanis#.tga",1},
{{255,255,255}, 0.1, 0.1, 1,"allships#.tga",1},
{{200,160,255}, 0.2, 0.2, 0,"tur_scout#.tga",1},
{{200,160,255}, 0.2, 0.2, 0,"tur_worker#.tga",1},
{{255,255,255}, 0.2, 0.2, 0,"",0},--theme 13(0xd): default for time counters
{{255,255,255}, 0.2, 0.2, 0,"",0},--theme 14(0xe): for close captions
{{255,255,255}, 0.5, 0.5, 1,"fleetintel#.tga",1},--theme 15(0xf): default for location cards
{{255,255,255}, 0.1, 0.1, 1,"kad_spod#.tga",1},
{{255,255,255}, 0.1, 0.1, 1,"kad_mpod#.tga",1},
{{255,255,255}, 0.1, 0.1, 1,"HW1_BentusiTraders#.tga",1},
{{200,160,255}, 0.1, 0.1, 1,"HW1_Kadesh#.tga",1},
{{255,255,255}, 0.2, 0.2, 0,"tur_cruiser#.tga",1},
{{255,255,255}, 0.5, 0.5, 1,"kad_nebula#.tga",1},
{{255,255,255}, 0.1, 0.1, 1,"9ccn#.tga",1},
{{255,255,255}, 0.1, 0.1, 1,"HW1_Emperor#.tga",1},
{{255,255,255}, 0.1, 0.1, 1,"HW1_KharSelim#.tga",1},
{{255,255,255}, 0.1, 0.1, 1,"dreadnaught#.tga",1},
{{255,255,255}, 0.1, 0.1, 1,"allships_vaygr#.tga",1},
{{255,255,255}, 0.1, 0.1, 1,"cmdstation_vaygr#.tga",1},
{{255,255,255}, 0.1, 0.1, 1,"vaygr#.tga",1},
{{255,255,255}, 0.1, 0.1, 1,"tai_assaultfrigate#.tga",1},
{{255,255,255}, 0.1, 0.1, 1,"tai_carrier#.tga",1},
{{255,255,255}, 0.1, 0.1, 1,"tai_battleship#.tga",1},
}
dofilepath("data:leveldata/campaign/tutorial/RPG/script/code_campaign.lua")
dofilepath("player:AutoSave.lua")
for iCampaignName,iCampaign in DTM4Campaign do
if(iCampaign.Map=="All")or(MissionData==iCampaign.Map)then
dofilepath("data:leveldata/campaign/tutorial/RPG/script/campaign/"..iCampaignName..".lua")
end
end
iTheme=1
while(SubTitles[iTheme]~=nil)do
addTheme(iTheme-1, SubTitles[iTheme][1], SubTitles[iTheme][2], SubTitles[iTheme][3], SubTitles[iTheme][4],SubTitles[iTheme][5],SubTitles[iTheme][6])
iTheme=iTheme+1
end
--addTheme(32, {255,255,255}, 0.1, 0.1, 0, "",0)
----------------------------------------------------------------------
--addRegion(regionNumber, textName, iconName)
--region 0: for NIS's
addRegion( 0, "Region0_Text", "", "" )
--region 1: for messages over the letterbox bar at the top of the screen
addRegion( 1, "Region1_Text", "Region1_Icon", "Region1_TextNarrow" )
--region 2: for close captions
addRegion( 2, "Region2_Text", "", "" )
--region 3: for location cards (centred on the screen)
addRegion( 3, "Region3_Text", "", "" )
-- region 4: for time counter
addRegion( 4, "Region4_Text", "", "" )
-- region 5: for general messages
addRegion( 5, "Region5_Text", "", "" )
-- region 6: letter box for animatics
addRegion( 6, "Region6_Text", "", "" )
|
--[=[
Circular buffer (aka fixed-sized FIFO queue) of Lua values.
Written by Cosmin Apreutesei. Public domain.
* Allows removing a value at any position from the queue.
* For a cdata ringbuffer, look at fs.mirror_buffer().
* Implemented as an array, not a linked list, so remove(v) is O(n).
* INDEX is a special key that if given will make find() and remove() O(1).
queue.new(size) -> q create a queue
q:size() get queue capacity
q:count() get queue item count
q:full() -> t|f check if the queue is full
q:empty() -> t|f check if the queue is empty
q:push(v) add a value to the end of the queue
q:pop() -> v|nil remove the first value from the queue (nil if empty)
q:peek() -> v|nil get the first value without popping
q:first() -> v|nil get the first value without popping
q:last() -> v|nil get the last value wihtout popping
q:items() -> iter() -> v iterate values
q:item_at(i) -> v|nil get item at index i in 1..q:count() from tail
q:remove(v) -> t|f remove value (return `true` if found)
]=]
local function new(size, INDEX)
local head = size
local tail = 1
local n = 0
local t = {}
local q = {}
function q:size() return size end
function q:count() return n end
function q:full() return n >= size end
function q:empty() return n == 0 end
local function mi(x) return (x - 1) % size + 1 end
function q:push(v)
assert(v ~= nil)
if n >= size then
return nil, 'full'
end
head = (head % size) + 1
t[head] = v
n = n + 1
if INDEX ~= nil then v[INDEX] = head end
return true
end
function q:pop()
if n == 0 then
return nil
end
local v = t[tail]
t[tail] = false
tail = (tail % size) + 1
n = n - 1
if INDEX ~= nil then v[INDEX] = nil end
return v
end
function q:peek()
if n == 0 then
return nil
end
return t[tail]
end
q.first = q.peek
function q:last()
if n == 0 then
return nil
end
return t[head]
end
function q:items()
local i = 0 --last i
return function()
if i >= n then
return nil
end
i = i + 1
return t[mi(tail + i - 1)]
end
end
function q:item_at(i)
if not (i >= 1 and i <= n) then return nil end
return t[mi(tail + i - 1)]
end
local function remove_at(i)
assert(n > 0)
local from_head = true
if tail <= head then --queue not wrapped around (has one segment).
assert(i >= tail and i <= head)
elseif i <= head then --queue wrapped; i is in the head's segment.
assert(i >= 1)
else --queue wrapped; i is in the tail's segment.
assert(i >= tail and i <= size)
from_head = false
end
if from_head then --move right of i to left.
for i = i, head-1 do t[i] = t[i+1]; if INDEX then t[i][INDEX] = i+1 end end
t[head] = false
if INDEX ~= nil then t[head][INDEX] = nil end
head = mi(head - 1)
else --move left of i to right.
for i = i-1, tail, -1 do t[i+1] = t[i]; if INDEX then t[i+1][INDEX] = i end end
t[tail] = false
if INDEX ~= nil then t[tail][INDEX] = nil end
tail = mi(tail + 1)
end
n = n - 1
end
local find
if INDEX ~= nil then
function find(v)
return v[INDEX]
end
else
function find(v)
for i = 1, n do
local mi = mi(tail + i - 1)
if t[mi] == v then
return mi
end
end
end
end
function q:remove(v)
local mi = find(v)
if not mi then return false end
remove_at(mi)
return true
end
return q
end
return {new = new}
|
-- Copyright (C) Mashape, Inc.
local BaseController = require "kong.api.routes.base_controller"
local PluginsConfigurations = BaseController:extend()
function PluginsConfigurations:new()
PluginsConfigurations.super.new(self, dao.plugins_configurations, "plugins_configurations")
end
return PluginsConfigurations
|
local Narrow, parent = torch.class('nn.Narrow', 'nn.Module')
function Narrow:__init(dimension,offset,length)
parent.__init(self)
self.dimension=dimension
self.index=offset
self.length=length or 1
if not dimension or not offset then
error('nn.Narrow(dimension, offset, length)')
end
end
function Narrow:updateOutput(input)
local dim = self.dimension < 0 and input:dim() + self.dimension + 1 or self.dimension
local length = self.length
if length < 0 then
length = input:size(dim) - self.index + self.length + 2
end
local index = self.index
if self.index < 0 then
index = 1
length = input:size(dim) - length
end
local output=input:narrow(dim, index, length)
self.output = self.output:typeAs(output)
self.output:resizeAs(output):copy(output)
return self.output
end
function Narrow:updateGradInput(input, gradOutput)
local dim = self.dimension < 0 and input:dim() + self.dimension + 1 or self.dimension
local length = self.length
if length < 0 then
length = input:size(dim) - self.index + self.length + 2
end
local index = self.index
if self.index < 0 then
index = 1
length = input:size(dim) - length
end
self.gradInput = self.gradInput:typeAs(input)
self.gradInput:resizeAs(input):zero()
self.gradInput:narrow(dim,index,length):copy(gradOutput)
return self.gradInput
end
|
--[[
Copyright (c) 2013 Romain Meynet
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
--]]
local resources={}
local lg=love.graphics
local lm=love.math
local fontFilename= "assets/diavlo.otf"
--local fontFilename= "assets/FiraMonoOT-Bold.otf"
local function loadFonts()
resources.tinyFont=lg.newFont(fontFilename,16)
resources.font=lg.newFont(fontFilename,20)
resources.titleFont=lg.newFont(fontFilename,32)
resources.menuFont=lg.newFont(fontFilename,24)
end
local function getVitaminImage(radius)
--local id = love.image.newImageData(2*radius,2*radius)
local id = love.image.newImageData(32,32)
local xc = (2*radius-1)/2
local yc = xc
local r2=radius*radius
for x=0,2*radius-1 do
local u2 = (x-xc)*(x-xc)
for y=0,2*radius-1 do
local d2=u2+(y-yc)*(y-yc)
if d2 <=r2 then
z=math.sqrt(r2-d2)
local l=((xc-x)+(yc-y)+z*math.sqrt(2))*0.5/radius
if l<0 then
l=0
end
id:setPixel(x,y,(64+(255-64)*l)/255,(64+(255-64)*l)/255,(64+(255-64)*l)/255,1)
end
end
end
return lg.newImage(id)
end
local function getSnakeImage(radius)
--local id = love.image.newImageData(2*radius,2*radius)
local id = love.image.newImageData(32,32)
local xc = (2*radius-1)/2
local yc = xc
local r2=radius*radius
for x=0,2*radius-1 do
local u2 = (x-xc)*(x-xc)
for y=0,2*radius-1 do
local d2=u2+(y-yc)*(y-yc)
if d2 <=r2 then
z=math.sqrt(r2-d2)
local l=((xc-x)+(yc-y)+z*math.sqrt(2))*0.5/radius
if l<0 then
l=0
end
id:setPixel(x,y,(64+(255-64)*l)/255,(64+(255-64)*l)/255,(64+(255-64)*l)/255,1)
end
end
end
return lg.newImage(id)
end
local function computeGraphics()
resources.vitamins={}
for i=8,16 do
resources.vitamins[i]=getVitaminImage(i)
end
resources.snake={}
resources.snake[7]=getSnakeImage(7)
end
local function computeBackground()
local abs=math.abs
local id = love.image.newImageData(SW,SH)
local c2={10/256,10/256,96/256}
local c1={86/256,96/256,80/256}
local maxr=1
--local minr=0.8
local minr=0.5
--local yrad=maxr/minr
local yrad=2*maxr - minr
local ox= 200*math.random() - 10
local oy= 20*math.random() - 10
local oz= 20*math.random() - 10
for x=0,SW-1 do
local alpha = 2*x/SW*math.pi
for y=0,SH-1 do
local beta = 2 *y/SH*math.pi
--local yy= oy+minr*math.sin(beta)
local yy= oy+yrad*math.sin(beta)
local ur = maxr - minr*math.cos(beta)
local xx = ox+ur*math.cos(alpha)
local zz = oz+ur*math.sin(alpha)
local u1 = lm.noise(xx,yy,zz)
local u2 = lm.noise(2*xx,2*yy,2*zz)
local u3 = lm.noise(4*xx,4*yy,4*zz)
--local u = 2*u1 + u2 + u3/2
local u = u1 + u2/2 + u3/4
--local u=2*u1
--local u = u1
if (u>1) then u=1 end
--u=u*u
id:setPixel(x,y,c1[1] + u*(c2[1]-c1[1]),c1[2] + u*(c2[2]-c1[2]),c1[3] + u*(c2[3]-c1[3]))
end
end
local sx = math.random(100,300)
local sy = math.random(100,300)
resources.bgCanvas = lg.newCanvas(SW,SH)
lg.setCanvas(resources.bgCanvas)
--lg.draw(lg.newImage(id),0,0)
lg.draw(lg.newImage(id),-sx,-sy)
lg.draw(lg.newImage(id),SW-sx,-sy)
lg.draw(lg.newImage(id),-sx,SH-sy)
lg.draw(lg.newImage(id),SW-sx,SH-sy)
lg.setCanvas()
end
function resources.load()
loadFonts()
computeGraphics()
computeBackground()
end
return resources |
local m, s, o
local sid = arg[1]
local raw_modes = {
"faketcp",
"udp",
"icmp",
}
local cipher_modes = {
"aes128cbc",
"xor",
"none",
}
local auth_modes = {
"md5",
"crc32",
"simple",
"none",
}
m = Map("udp2raw", "%s - %s" %{translate("udp2raw-tunnel"), translate("Edit Server")})
m.redirect = luci.dispatcher.build_url("admin/services/udp2raw/servers")
m.sid = sid
if m.uci:get("udp2raw", sid) ~= "servers" then
luci.http.redirect(m.redirect)
return
end
s = m:section(NamedSection, sid, "servers")
s.anonymous = true
s.addremove = false
o = s:option(Value, "alias", translate("Alias(optional)"))
o = s:option(Value, "server_addr", translate("Server"))
o.datatype = "host"
o.rmempty = false
o = s:option(Value, "server_port", translate("Server Port"))
o.datatype = "port"
o.placeholder = "8080"
o = s:option(Value, "listen_addr", translate("Local Listen Host"))
o.datatype = "ipaddr"
o.placeholder = "127.0.0.1"
o = s:option(Value, "listen_port", translate("Local Listen Port"))
o.datatype = "port"
o.placeholder = "2080"
o = s:option(ListValue, "raw_mode", translate("Raw Mode"))
for _, v in ipairs(raw_modes) do o:value(v, v:lower()) end
o.default = "faketcp"
o.rmempty = false
o = s:option(Value, "key", translate("Password"))
o.password = true
o = s:option(ListValue, "cipher_mode", translate("Cipher Mode"))
for _, v in ipairs(cipher_modes) do o:value(v, v:lower()) end
o.default = "aes128cbc"
o = s:option(ListValue, "auth_mode", translate("Auth Mode"))
for _, v in ipairs(auth_modes) do o:value(v, v:lower()) end
o.default = "md5"
o = s:option(Flag, "auto_rule", translate("Auto Rule"), translate("Auto add (and delete) iptables rule."))
o.default = "1"
o = s:option(Flag, "keep_rule", translate("Keep Rule"), translate("Monitor iptables and auto re-add if necessary."))
o:depends("auto_rule", "1")
o = s:option(Value, "seq_mode", translate("seq Mode"), translate("seq increase mode for faketcp."))
o.datatype = "range(0,4)"
o.placeholder = "3"
o = s:option(Value, "lower_level", translate("Lower Level"), translate("Send packets at OSI level 2, format: \"eth0#00:11:22:33:44:55\", or \"auto\"."))
o = s:option(Value, "source_ip", translate("Source-IP"), translate("Force source-ip for Raw Socket."))
o.datatype = "ipaddr"
o = s:option(Value, "source_port", translate("Source-Port"), translate("Force source-port for Raw Socket, TCP/UDP only."))
o.datatype = "port"
o = s:option(Value, "log_level", translate("Log Level"))
o.datatype = "range(0,6)"
o.placeholder = "4"
return m
|
return {'goed','goedaardig','goedaardigheid','goedachten','goedbedoeld','goedbekeken','goedbeschouwd','goedbetaald','goedbloed','goeddeels','goeddoen','goeddunken','goede','goedemannen','goedemiddag','goedemorgen','goedenacht','goedenavond','goedendag','goederen','goederenafgifte','goederenbedrijf','goederenbehandelaar','goederenbeheer','goederenbeurs','goederenbeweging','goederenboek','goederenbureau','goederencode','goederendepot','goederenemplacement','goederenexport','goederenhandel','goederenkantoor','goederenkrediet','goederenlift','goederenlijn','goederenloods','goederenmakelaar','goederenmarkt','goederenmarkten','goederenmateriaal','goederenoverslag','goederenprijs','goederenprijzen','goederenrekening','goederenruil','goederenspoor','goederenspoorlijn','goederenstation','goederenstroom','goederentermijnhandel','goederentermijnmarkt','goederentransport','goederentrein','goederenuitvoer','goederenverkeer','goederenvervoer','goederenverzekering','goederenverzending','goederenvoorraad','goederenwagen','goederenwagon','goederhand','goedertieren','goedertierenheid','goedgebekt','goedgebouwd','goedgeefs','goedgeefsheid','goedgehumeurd','goedgehumeurdheid','goedgekleed','goedgekozen','goedgelovig','goedgelovigheid','goedgeluimd','goedgemutst','goedgevigheid','goedgevormd','goedgevuld','goedgewicht','goedgezind','goedgeinformeerd','goedgunstig','goedgunstigheid','goedhartig','goedhartigheid','goedheid','goedheilig','goedheilige','goedheiligman','goedig','goedigheid','goedje','goedkeuren','goedkeuring','goedkeuringsprocedure','goedkeuringsstempel','goedkeuringstermijn','goedkeuringswet','goedkoop','goedkoopheid','goedlachs','goedleers','goedleven','goedlopend','goedmaken','goedmaker','goedmakertje','goedmaking','goedmarkt','goedmoedig','goedmoedigheid','goednieuwsshow','goedpraten','goedrond','goedschiks','goedsmoeds','goedspreken','goedverkochte','goedverzorgd','goedvinden','goedwillend','goedwillende','goedwillendheid','goedwillig','goedwilligheid','goedzak','goedzakkig','goegemeente','goeierd','goeiig','goeiigheid','goelag','goelijk','goeman','goeroe','goeroeachtig','goesting','goetie','goedgeschreven','goedschrift','goedleggen','goenagoena','goedkeuringsinstantie','goederencorridor','goedkeuringsnummer','goederenbehandeling','goederendistributie','goederenontvangst','goederenrecht','goedkeuringsbeschikking','goedkeuringsbesluit','goedkeuringsformulier','goedkeuringsmerk','goedkeuringsrecht','goedkeuringsproces','goederenpakket','goederenproductie','goederendienst','goederengemeenschap','goedkeuringsmerkteken','goedhals','goededoelenloterij','goedele','goedereede','goeferdinge','goerees','goereese','goereeer','goes','goesenaar','goethals','goetsenhoven','goeie','goeree','goele','goede','goertz','goeman','goettsch','goense','goessen','goedee','goedemans','goedknegt','goesten','goetheer','goei','goedaardige','goedaardiger','goedaardigste','goedbetalende','goedbewaarde','goedbezochte','goeddocht','goeddunk','goeddunkt','goededoelenloterijen','goededoelenorganisaties','goeden','goedendags','goeder','goederenbeurzen','goederencodes','goederendepots','goederenkredieten','goederenliften','goederenloodsen','goederenmakelaars','goederenrekeningen','goederenstations','goederenstromen','goederentreinen','goederenvervoerders','goederenvoorraden','goederenwagens','goederenwagons','goedertierener','goedertierenste','goedgebouwde','goedgedocht','goedgeefse','goedgeefser','goedgehumeurde','goedgekeurd','goedgekeurde','goedgeklede','goedgekomen','goedgelovige','goedgelovigen','goedgeloviger','goedgelovigste','goedgemaakt','goedgemaakte','goedgemikte','goedgeorganiseerde','goedgeplaatste','goedgepraat','goedgeprate','goedgesproken','goedgetrainde','goedgevonden','goedgevormde','goedgezinde','goedgunstige','goedhartige','goedhartiger','goedhartigste','goedheden','goedige','goediger','goedingelichte','goedjes','goedkeur','goedkeurde','goedkeurden','goedkeurend','goedkeurende','goedkeuringen','goedkeuringsprocedures','goedkeurt','goedkomt','goedkoopst','goedkoopste','goedkope','goedkoper','goedkopere','goedlachse','goedlachser','goedleerse','goedlopende','goedmaak','goedmaakt','goedmaakte','goedmaakten','goedmenende','goedmoedige','goedmoediger','goedmoedigste','goedogend','goedogende','goedopgeleide','goedpraat','goedpraatte','goedpraatten','goeds','goedspreekt','goedverdienende','goedverkopende','goedverzorgde','goedvind','goedvindt','goedvond','goedwerkende','goedwillenden','goedwillige','goedzakken','goedzakkige','goeierds','goelijke','goelijkste','goemannen','goeroeachtige','goeroes','goestingen','goedgemutste','goedgeluimde','goedgebekte','goedbedoelde','goedbetaalde','goederenkantoren','goedgevulde','goedkeuringstermijnen','goednieuwsshows','goeiige','goedgeinformeerde','goedgeacht','goedgedaan','goedgelegd','goelags','goeles','goedkeuringsinstanties','goederenbewegingen','goederentransporten','goederenlijnen','goederencorridors','goedkeuringsformulieren','goederenspoorlijnen','goederensporen','goedkeuringsmerken','goedkeuringsprocessen','goederenemplacementen','goederentermijnmarkten','goedkeuringsnummers'} |
local _, NeP = ...
local _G = _G
local strsplit = _G.strsplit
local IsInGroup = _G.IsInGroup
local IsInRaid = _G.IsInRaid
local GetNumGroupMembers = _G.GetNumGroupMembers
NeP.Protected = {}
NeP.Protected.callbacks = {}
local rangeCheck = _G.LibStub("LibRangeCheck-2.0")
local noop = function() end
function NeP.Protected:AddCallBack(func)
if not func() then
table.insert(self.callbacks, func)
end
end
NeP.Protected.Cast = function(spell, target)
NeP.Faceroll:Set(spell, target)
end
NeP.Protected.CastGround = function(spell, target)
NeP.Faceroll:Set(spell, target)
end
NeP.Protected.Macro = noop
NeP.Protected.UseItem = noop
NeP.Protected.UseInvItem = noop
NeP.Protected.TargetUnit = noop
NeP.Protected.SpellStopCasting = noop
NeP.Protected.ObjectExists = noop
NeP.Protected.ObjectCreator = noop
NeP.Protected.GameObjectIsAnimating = noop
NeP.Protected.Distance = function(_, b)
local minRange, maxRange = rangeCheck:GetRange(b)
return maxRange or minRange or 0
end
NeP.Protected.Infront = function(_,b)
return NeP.Helpers:Infront(b) or false
end
NeP.Protected.UnitCombatRange = function(_,b)
return rangeCheck:GetRange(b) or 0
end
NeP.Protected.LineOfSight = function(_,b)
return NeP.Helpers:Infront(b) or false
end
local ValidUnits = {'player', 'mouseover', 'target', 'focus', 'pet',}
local ValidUnitsN = {'boss', 'arena', 'arenapet'}
NeP.Protected.nPlates = {
Friendly = {},
Enemy = {}
}
function NeP.Protected.nPlates:Insert(ref, Obj, GUID)
local distance = NeP.Protected.Distance('player', Obj) or 999
if distance <= NeP.OM.max_distance then
local ObjID = select(6, strsplit('-', GUID))
self[ref][GUID] = {
key = Obj,
name = _G.UnitName(Obj),
distance = distance,
id = tonumber(ObjID or 0),
guid = GUID,
isdummy = NeP.DSL:Get('isdummy')(Obj)
}
end
end
NeP.Protected.OM_Maker = function()
-- If in Group scan frames...
if IsInGroup()
or IsInRaid() then
local prefix = (IsInRaid() and 'raid') or 'party'
for i = 1, GetNumGroupMembers() do
local unit = prefix..i
local pet = prefix..'pet'..i
NeP.OM:Add(unit)
NeP.OM:Add(pet)
NeP.OM:Add(unit..'target')
NeP.OM:Add(pet..'target')
end
end
-- Valid Units
for i=1, #ValidUnits do
local object = ValidUnits[i]
NeP.OM:Add(object)
NeP.OM:Add(object..'target')
end
-- Valid Units with numb (5)
for i=1, #ValidUnitsN do
for k=1, 5 do
local object = ValidUnitsN[i]..k
NeP.OM:Add(object)
NeP.OM:Add(object..'target')
end
end
--nameplates
for i=1, 40 do
local Obj = 'nameplate'..i
if _G.UnitExists(Obj) then
local GUID = _G.UnitGUID(Obj) or '0'
if _G.UnitIsFriend('player',Obj) then
NeP.Protected.nPlates:Insert('Friendly', Obj, GUID)
else
NeP.Protected.nPlates:Insert('Enemy', Obj, GUID)
end
end
end
end
|
local lualine_ok, lualine = pcall(require, "lualine")
if not lualine_ok then
vim.notify("Lualine not found. Statusline is disabled.", "warn")
return
end
lualine.setup({
options = {
theme = "gruvbox-material",
component_separators = "|",
section_separators = "",
globalstatus = true,
},
sections = {
lualine_a = {
{
"mode",
fmt = function(str)
return str:sub(1, 3)
end,
},
},
lualine_b = {
{
"branch",
icon = "",
},
},
},
})
|
local Parser = torch.class("neuralconvo.MovieScriptParser")
function Parser:parse(file)
local f = assert(io.open(file, 'r'))
self.input = f:read("*all")
f:close()
self.pos = 0
self.match = nil
-- Find start of script
repeat self:acceptLine() until self:accept("<pre>")
local dialogs = {}
-- Apply rules until end of script
while not self:accept("</pre>") and self:acceptLine() do
local dialog = self:parseDialog()
if dialog then
table.insert(dialogs, dialog)
end
end
return dialogs
end
-- Returns true if regexp matches and advance position
function Parser:accept(regexp)
local match = string.match(self.input, "^" .. regexp, self.pos)
if match then
self.pos = self.pos + #match
self.match = match
return true
end
end
-- Accept anything up to the end of line
function Parser:acceptLine()
return self:accept(".-\n")
end
function Parser:acceptSep()
while self:accept("</?b>") or self:accept(" +") do end
return self:accept("\n")
end
function Parser:parseDialog()
local dialogs = {}
repeat
local dialog = self:parseSpeech()
if dialog then
table.insert(dialogs, dialog)
end
until not self:acceptSep()
if #dialogs > 0 then
return dialogs
end
end
-- Matches:
--
-- NAME
-- some nice text
-- more text.
--
-- or
--
-- NAME; text
function Parser:parseSpeech()
local name
self:accept("</b>")
self:accept("<b>")
-- Get the character name (all caps)
-- TODO remove parenthesis from name
if self:accept(" +") and self:accept("[A-Z][A-Z%- %.%(%)]+") then
name = self.match
else
return
end
-- Handle inline dialog: `NAME; text`
if self:accept(";") and self:accept("[^\n]+") then
return {
character = name,
text = self.match
}
end
self:accept("\n")
if not self:accept("</b>") then
return
end
-- Get the dialog lines
-- TODO remove parenthesis from text
local lines = {}
while self:accept(" +") do
-- The actual line of dialog
if self:accept("[^\n]+") then
table.insert(lines, self.match)
end
self:accept("\n")
end
if #lines > 0 then
return {
character = name,
text = table.concat(lines)
}
end
end
|
local content = {
-- program data
["data"] = {
["commands"] = {}, -- [name] = function(args)
["variables"] = {}, -- [name] = value
["procedures"] = {}, -- [name] = {code, inputs name}
["labels"] = {} -- [name] = value
},
-- program info
["program"] = {
-- contents of the program
["contents"] = {},
-- program line number
["index"] = 1,
-- procedure output
["report"] = "",
-- procedure break
["break"] = false,
-- previous goto line
["prev goto"] = 0
},
-- interpreter info
["interpreter"] = {
-- program path
["filepath"] = ""
}
}
local functions = require("modules/functions")
local parser = require("modules/parser")
local sub = string.sub
local nilCheck = functions.nilCheck
local calculate_operators = {
["abs"] = math.abs, ["sqrt"] = math.sqrt, ["log"] = math.log, ["pow"] = math.pow,
["sin"] = math.sin, ["cos"] = math.cos, ["tan"] = math.tan,
["asin"] = math.asin, ["acos"] = math.acos, ["atan"] = math.atan
}
local list_edit_commands = {
["add"] = function(list, x, y) -- (edit LIST add VALUE ~ INDEX)
local y = tonumber(y) or #list + 1
table.insert(list, y, x)
return list
end, ["del"] = function(list, x, y) -- (edit LIST del INDEX)
local x = tonumber(x) or #list
table.remove(list, x)
return list
end, ["set"] = function(list, x, y) -- (edit LIST set INDEX VALUE)
local x = tonumber(x) or #list
local y = y or ""
list[x] = y
return list
end
}
-- get and return program data, define it if not found
local function getDataType(typeName, name, default)
local name = name or ""
local dtTable = content["data"][typeName]
local dtItem = dtTable[name]
if dtItem == nil then
dtTable[name] = default
dtItem = dtTable[name]
end
return dtItem
end
-- get and return procedure, define it if not found
function content.getProcedure(name)
return getDataType("procedures", name, {{}, ""})
end
-- check if comparable as numbers
local function comparableAsNumbers(inputs)
for _, item in ipairs(inputs) do
if tonumber(item) == nil then
return false
end
end
return true
end
-- combines each item and returns the result
local function combine(inputs, code)
if #inputs >= 1 then
local product = inputs[1] or ""
table.remove(inputs, 1)
for _, item in ipairs(inputs) do
product = code(product, item)
end
return tostring(product)
end
return ""
end
-- compare each item and returns the result
local function gate(inputs, code)
local ifNumbers = comparableAsNumbers(inputs)
local previous = inputs[1]
table.remove(inputs, 1)
local condition = false
for _, item in ipairs(inputs) do
if ifNumbers then
local x = tonumber(previous) or 0
local y = tonumber(item) or 0
condition = code(x, y)
else
condition = code(previous, item)
end
previous = item
end
return tostring(condition)
end
-- runs a command, used to run line
function content.runCommand(tokens)
-- get command and inputs
local name, inputs = "", {}
for index, item in ipairs(tokens) do
-- repeat function if table
local value = item
if type(item) == "table" then
value = content.runCommand(item) or ""
end
-- set nil values to empty strings
if value == nil then
value = ""
end
-- get value of variable
if sub(value, 1, 1) == "$" then
local name = sub(value, 2) or ""
local variable = content["data"]["variables"][name]
value = variable or ""
end
-- push as command name or an input
if index == 1 then
name = value
else
table.insert(inputs, value)
end
end
-- get and run command or procedure, then return result
local command = content["data"]["commands"][name] or content.getProcedure(name)
if type(command) == "function" then -- command
local output = command(inputs)
return output
elseif type(command) == "table" then -- procedure
local code, name = command[1], command[2] or ""
content["data"]["variables"][name] = functions.encode(inputs) or {}
local previous = content["program"]["index"]
content["program"]["index"] = 0
repeat
content["program"]["index"] = content["program"]["index"] + 1
local number = content["program"]["index"]
local line = code[number] or ""
local text = parser.cleanUpString(line)
if string.gsub(line, "%s+", "") ~= "" then
local tokens = parser.tokenizer(text)
local set = parser.generate(tokens)
local value = content.runCommand(set)
end
if content["program"]["break"] == true then
content["program"]["break"] = false
break
end
until content["program"]["index"] > #code
content["program"]["index"] = previous
return content["program"]["report"] or ""
end
return nil
end
-- runs a line
function content.runLine(line)
local text = parser.cleanUpString(line)
if string.gsub(line, "%s+", "") ~= "" then
local tokens = parser.tokenizer(text)
local set = parser.generate(tokens)
return content.runCommand(set) or ""
end
end
-- runs each line in data.program.contents
local function runContents()
content["program"]["index"] = 1
while content["program"]["index"] <= #content["program"]["contents"] do
local number = content["program"]["index"]
local line = content["program"]["contents"][number] or ""
content.runLine(line)
content["program"]["index"] = content["program"]["index"] + 1
end
end
-- additional input are ~, endless inputs are ..., option inputs are /, code blocks are ;
content["data"]["commands"] = {
-- var NAME VALUE
["var"] = function(inputs)
local name, value = inputs[1], inputs[2]
if nilCheck(name, value) then
content["data"]["variables"][name] = value
end
end,
-- del TYPE ~ NAME
["del"] = function(inputs)
local typeEntry, name = inputs[1], inputs[2]
local types = {"variable", "list", "label"}
if typeEntry ~= nil then
if typeEntry == "all" then
for _, value in ipairs(types) do
content["data"][value .. "s"] = {}
end
elseif name ~= nil and functions.contains(types, typeEntry) then
content["data"][typeEntry .. "s"][name] = nil
end
end
end,
-- (list ...)
["list"] = function(inputs)
return functions.encode(inputs)
end,
-- (edit LIST TYPE X ~ Y)
["edit"] = function(inputs)
local list = inputs[1] or ""
local func = inputs[2] or ""
local x = inputs[3]
local y = inputs[4] or ""
list = functions.decode(list)
func = list_edit_commands[func]
if functions.nilCheck(list, func, x) then
list = func(list, x, y) or {}
return functions.encode(list)
end
end,
-- (get LIST ~ INDEX)
["get"] = function(inputs)
local list = inputs[1] or ""
list = functions.decode(list)
local index = tonumber(inputs[2]) or #list
return list[index] or ""
end,
-- (find LIST VALUE)
["find"] = function(inputs)
local list = inputs[1] or ""
list = functions.decode(list)
local target = inputs[2] or ""
local index = functions.find(list, target) or 0
return tostring(index)
end,
-- (size LIST)
["size"] = function(inputs)
local list = inputs[1] or ""
list = functions.decode(list)
return tostring(#list)
end,
-- (+ ...)
["+"] = function(inputs)
return combine(inputs, function(a, b)
local a = tonumber(a) or 0
local b = tonumber(b) or 0
return a + b
end)
end,
-- (- ...)
["-"] = function(inputs)
return combine(inputs, function(a, b)
local a = tonumber(a) or 0
local b = tonumber(b) or 0
return a - b
end)
end,
-- (* ...)
["*"] = function(inputs)
return combine(inputs, function(a, b)
local a = tonumber(a) or 1
local b = tonumber(b) or 1
return a * b
end)
end,
-- (/ ...)
["/"] = function(inputs)
return combine(inputs, function(a, b)
local a = tonumber(a) or 1
local b = tonumber(b) or 1
return a / b
end)
end,
-- (% ...)
["%"] = function(inputs)
return combine(inputs, function(a, b)
local a = tonumber(a) or 1
local b = tonumber(b) or 1
return a % b
end)
end,
-- (join ...)
["join"] = function(inputs)
return combine(inputs, function(a, b)
return a .. b
end)
end,
-- (round NUMBER ~ up/down)
["round"] = function(inputs)
local output = 0
local number = tonumber(inputs[1]) or 0
local force = inputs[2]
if force ~= nil then
local forceFunctions = {["up"] = math.ceil, ["down"] = math.floor}
local forceFunction = forceFunctions[force]
if forceFunction ~= nil then
output = forceFunction(number)
end
else
output = functions.round(number)
end
return tostring(output)
end,
-- (rand MIN MAX)
["rand"] = function(inputs)
local min, max = tonumber(inputs[1]), tonumber(inputs[2])
if nilCheck(min, max) then
local output = functions.randomFloat(min, max)
return tostring(output) or "0"
end
end,
-- (math operator X ~ Y)
["math"] = function(inputs)
local name = inputs[1]
local x = tonumber(inputs[2])
local y = tonumber(inputs[3])
local operator_inputs = y == nil and {x} or {x, y}
if nilCheck(opreator, x) then
local operator = calculate_operators[name]
if operator ~= nil then
local output = operator(table.unpack(operator_inputs))
return tostring(output) or "0"
end
end
end,
-- (len STRING)
["len"] = function(inputs)
local text = inputs[1] or ""
return tostring(#text)
end,
-- (sub STRING START/INDEX ~ END)
["sub"] = function(inputs)
local text, start = inputs[1], tonumber(inputs[2])
if nilCheck(text, start) then
local finish = tonumber(inputs[3]) or start
return sub(text, start, finish) or ""
end
end,
-- (low STRING)
["low"] = function(inputs)
local text = inputs[1] or ""
return string.lower(text)
end,
-- (up STRING)
["up"] = function(inputs)
local text = inputs[1] or ""
return string.upper(text)
end,
-- (! BOOLEAN)
["!"] = function(inputs)
local truth = inputs[1] or "false"
return tostring(truth == "false")
end,
-- (& ...)
["&"] = function(inputs)
return combine(inputs, function(a, b)
local a = a == "true"
local b = b == "true"
return a and b
end)
end,
-- (~ ...)
["~"] = function(inputs)
return combine(inputs, function(a, b)
local a = a == "true"
local b = b == "true"
return a or b
end)
end,
-- (= ...)
["="] = function(inputs)
return gate(inputs, function(a, b)
return a == b
end)
end,
-- (> ...)
[">"] = function(inputs)
return gate(inputs, function(a, b)
return a > b
end)
end,
-- (< ...)
["<"] = function(inputs)
return gate(inputs, function(a, b)
return a < b
end)
end,
-- (? VALUE IF ~ ELSE ~ OTHER)
["?"] = function(inputs)
local truth = inputs[1]
local whenTrue = inputs[2] or ""
local whenFalse = inputs[3] or ""
local whenOther = inputs[4] or ""
if truth ~= nil then
if truth == "true" then
return whenTrue
elseif truth == "false" then
return whenFalse
else
return whenOther
end
end
end,
-- print ...
["print"] = function(inputs)
local outputs = inputs or {}
print(table.unpack(outputs))
end,
-- (ask)
["ask"] = function()
return io.read() or ""
end,
-- label NAME ~ LINE
["label"] = function(inputs)
local name = inputs[1] or ""
local line = content["program"]["index"]
local value = tonumber(inputs[2]) or line
content["data"]["labels"][name] = value
end,
-- goto LINE/LABEL
["goto"] = function(inputs)
local input = inputs[1] or ""
local line = tonumber(input) or content["data"]["labels"][input]
if line ~= nil then
content["program"]["prev goto"] = content["program"]["index"]
content["program"]["index"] = line - 1
end
end,
-- back
["back"] = function()
content["program"]["index"] = content["program"]["prev goto"]
end,
-- def NAME ~ INPUTS
["def"] = function(inputs)
local name = inputs[1]
if name ~= nil then
local program = content["program"]
local line, block = "", {}
local statement = false
repeat
program["index"] = program["index"] + 1
line = program["contents"][program["index"]] or ""
line = parser.cleanUpString(line)
local tokens = parser.tokenizer(line) or {""}
statement = tokens[1] == "end"
if not statement then
table.insert(block, line)
end
until statement or program["index"] > #program["contents"]
local procedure = content.getProcedure(name)
procedure[1] = block
procedure[2] = inputs[2] or ""
end
end,
-- exit ~ VALUE
["exit"] = function(inputs)
content["program"]["report"] = inputs[1] or ""
content["program"]["break"] = true
end,
-- if BOOLEAN LINE ...
["if"] = function(inputs)
table.insert(inputs, 1, "if")
local values = {}
local elseIndex = -1
for index, item in ipairs(inputs) do
if elseIndex == -1 then
table.insert(values, item)
end
if item == "else" and index % 2 ~= 0 then
table.insert(values, inputs[index + 1])
elseIndex = index
break
end
end
if elseIndex > -1 then
values[elseIndex] = "true"
table.insert(values, elseIndex, "if")
end
local value = ""
for i = 1, #values / 3 do
local truth = values[(i - 1) * 3 + 2]
if truth == "true" then
value = values[(i - 1) * 3 + 3]
break
end
end
local text = parser.cleanUpString(value)
if string.gsub(text, "%s+", "") ~= "" then
local tokens = parser.tokenizer(text)
local set = parser.generate(tokens)
local output = content.runCommand(set)
return output or ""
end
end,
-- loop REPEATER LINE
["loop"] = function(inputs)
local repeater = inputs[1] or ""
local line = inputs[2] or ""
if repeater == "true" then
while true do
content.runLine(line)
end
else
repeater = tonumber(repeater) or 1
for _ = 1, repeater do
content.runLine(line)
end
end
end,
-- while NAME LINE
["while"] = function(inputs)
local variables = content["data"]["variables"]
local name = inputs[1] or ""
local line = inputs[2] or ""
while variables[name] == "true" do
content.runLine(line)
end
end,
-- run ~ PATH
["run"] = function(inputs)
local path = inputs[1] or content["interpreter"]["filepath"]
local file = functions.readFile(path)
if file ~= nil then
content["interpreter"]["filepath"] = path
content["program"]["contents"] = file
runContents()
end
end,
-- about
["about"] = function()
local license = functions.readFile("LICENSE") or {}
license = #license == 0 and {"license file missing"} or license
local info = [[Written in Lua with ZeroBrane Studio and Notepad++.
Designed and Programmed by Daniel Lawson.
Licensed under the MIT License.
Examples are completely free of charage.
Copyright 2021 Daniel Lawson
github.com/Sombrero64/MiniScript
www.lua.org
studio.zerobrane.com
notepad-plus-plus.org]]
print("")
print("=== About MiniScript 2.1 ===")
print(info)
print("------------------")
for _, line in ipairs(license) do
print(line)
end
print("==================")
print("")
end
}
return content |
package.path = package.path .. ';..\\src\\?.lua'
local utils = require "WindowsFirewall.utils"
utils.EachNetworkAdapter(function(adapter)
print("Name: ", adapter:Name())
print("Description: ", adapter:Description())
print("GUID: ", adapter:GUID())
print("MAC: ", adapter:MACAddress())
print("NID: ", adapter:NetConnectionID())
print("ServiceName: ", adapter:ServiceName())
print("*****************************************")
end)
|
--# selene: allow(unused_variable)
---@diagnostic disable: unused-local
--- @param buffer buffer
--- @param first integer
--- @param last integer
function vim.api.nvim__buf_redraw_range(buffer, first, last) end
--- @param buffer buffer
function vim.api.nvim__buf_stats(buffer) end
--- @param ns_id integer
function vim.api.nvim__get_hl_defs(ns_id) end
function vim.api.nvim__get_lib_dir() end
-- Returns object given as argument.
--- @param obj object #Object to return.
--- @return any #its argument.
function vim.api.nvim__id(obj) end
-- Returns array given as argument.
--- @param arr array #Array to return.
--- @return any #its argument.
function vim.api.nvim__id_array(arr) end
-- Returns dictionary given as argument.
--- @param dct dictionary #Dictionary to return.
--- @return any #its argument.
function vim.api.nvim__id_dictionary(dct) end
-- Returns floating-point value given as argument.
--- @param flt float #Value to return.
--- @return any #its argument.
function vim.api.nvim__id_float(flt) end
-- NB: if your UI doesn't use hlstate, this will not return
-- hlstate first time.
--- @param grid integer
--- @param row integer
--- @param col integer
function vim.api.nvim__inspect_cell(grid, row, col) end
--- @param path string
function vim.api.nvim__screenshot(path) end
-- Set active namespace for highlights.
--- @param ns_id integer #the namespace to activate
function vim.api.nvim__set_hl_ns(ns_id) end
-- Gets internal stats.
--- @return any #Map of various internal stats.
function vim.api.nvim__stats() end
-- Adds a highlight to buffer.
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param ns_id integer #namespace to use or -1 for ungrouped
--- highlight
--- @param hl_group string #Name of the highlight group to use
--- @param line integer #Line to highlight (zero-indexed)
--- @param col_start integer #Start of (byte-indexed) column range to
--- highlight
--- @param col_end integer #End of (byte-indexed) column range to
--- highlight, or -1 to highlight to end of line
--- @return any #The ns_id that was used
function vim.api.nvim_buf_add_highlight(buffer, ns_id, hl_group, line, col_start, col_end) end
-- Activates buffer-update events on a channel, or as Lua
-- callbacks.
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param send_buffer boolean #True if the initial notification should
--- contain the whole buffer: first
--- notification will be `nvim_buf_lines_event`
--- . Else the first notification will be
--- `nvim_buf_changedtick_event` . Not for Lua
--- callbacks.
--- @param opts table<string, luaref> #Optional parameters.
--- • on_lines: Lua callback invoked on change.
--- Return`true`to detach. Args:
--- • the string "lines"
--- • buffer handle
--- • b:changedtick
--- • first line that changed (zero-indexed)
--- • last line that was changed
--- • last line in the updated range
--- • byte count of previous contents
--- • deleted_codepoints (if `utf_sizes` is
--- true)
--- • deleted_codeunits (if `utf_sizes` is
--- true)
---
--- • on_bytes: lua callback invoked on change.
--- This callback receives more granular
--- information about the change compared to
--- on_lines. Return`true`to detach. Args:
--- • the string "bytes"
--- • buffer handle
--- • b:changedtick
--- • start row of the changed text
--- (zero-indexed)
--- • start column of the changed text
--- • byte offset of the changed text (from
--- the start of the buffer)
--- • old end row of the changed text
--- • old end column of the changed text
--- • old end byte length of the changed text
--- • new end row of the changed text
--- • new end column of the changed text
--- • new end byte length of the changed text
---
--- • on_changedtick: Lua callback invoked on
--- changedtick increment without text
--- change. Args:
--- • the string "changedtick"
--- • buffer handle
--- • b:changedtick
---
--- • on_detach: Lua callback invoked on
--- detach. Args:
--- • the string "detach"
--- • buffer handle
---
--- • on_reload: Lua callback invoked on
--- reload. The entire buffer content should
--- be considered changed. Args:
--- • the string "detach"
--- • buffer handle
---
--- • utf_sizes: include UTF-32 and UTF-16 size
--- of the replaced region, as args to
--- `on_lines` .
--- • preview: also attach to command preview
--- (i.e. 'inccommand') events.
--- @return any #False if attach failed (invalid parameter, or buffer isn't
--- loaded); otherwise True. TODO: LUA_API_NO_EVAL
function vim.api.nvim_buf_attach(buffer, send_buffer, opts) end
-- call a function with buffer as temporary current buffer
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param fun luaref #Function to call inside the buffer (currently
--- lua callable only)
--- @return any #Return value of function. NB: will deepcopy lua values
--- currently, use upvalues to send lua references in and out.
function vim.api.nvim_buf_call(buffer, fun) end
-- Clears namespaced objects (highlights, extmarks, virtual text)
-- from a region.
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param ns_id integer #Namespace to clear, or -1 to clear all
--- namespaces.
--- @param line_start integer #Start of range of lines to clear
--- @param line_end integer #End of range of lines to clear (exclusive)
--- or -1 to clear to end of buffer.
function vim.api.nvim_buf_clear_namespace(buffer, ns_id, line_start, line_end) end
-- Removes an extmark.
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param ns_id integer #Namespace id from |nvim_create_namespace()|
--- @param id integer #Extmark id
--- @return any #true if the extmark was found, else false
function vim.api.nvim_buf_del_extmark(buffer, ns_id, id) end
-- Unmaps a buffer-local |mapping| for the given mode.
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param mode string
--- @param lhs string
function vim.api.nvim_buf_del_keymap(buffer, mode, lhs) end
-- Removes a buffer-scoped (b:) variable
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param name string #Variable name
function vim.api.nvim_buf_del_var(buffer, name) end
-- Deletes the buffer. See |:bwipeout|
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param opts dictionary #Optional parameters. Keys:
--- • force: Force deletion and ignore unsaved
--- changes.
--- • unload: Unloaded only, do not delete. See
--- |:bunload|
function vim.api.nvim_buf_delete(buffer, opts) end
-- Deactivates buffer-update events on the channel.
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @return any #False if detach failed (because the buffer isn't loaded);
--- otherwise True.
function vim.api.nvim_buf_detach(buffer) end
-- Gets a changed tick of a buffer
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @return any #`b:changedtick` value.
function vim.api.nvim_buf_get_changedtick(buffer) end
-- Gets a map of buffer-local |user-commands|.
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param opts dictionary #Optional parameters. Currently not used.
--- @return any #Map of maps describing commands.
function vim.api.nvim_buf_get_commands(buffer, opts) end
-- Returns position for a given extmark id
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param ns_id integer #Namespace id from |nvim_create_namespace()|
--- @param id integer #Extmark id
--- @param opts dictionary #Optional parameters. Keys:
--- • details: Whether to include the details dict
--- @return any #(row, col) tuple or empty list () if extmark id was absent
function vim.api.nvim_buf_get_extmark_by_id(buffer, ns_id, id, opts) end
-- Gets extmarks in "traversal order" from a |charwise| region
-- defined by buffer positions (inclusive, 0-indexed
-- |api-indexing|).
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param ns_id integer #Namespace id from |nvim_create_namespace()|
--- @param start object #Start of range, given as (row, col) or valid
--- extmark id (whose position defines the bound)
--- @param end_ object #End of range, given as (row, col) or valid
--- extmark id (whose position defines the bound)
--- @param opts dictionary #Optional parameters. Keys:
--- • limit: Maximum number of marks to return
--- • details Whether to include the details dict
--- @return any #List of [extmark_id, row, col] tuples in "traversal
--- order".
function vim.api.nvim_buf_get_extmarks(buffer, ns_id, start, end_, opts) end
-- Gets a list of buffer-local |mapping| definitions.
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param mode string #Mode short-name ("n", "i", "v", ...)
--- @return any #Array of maparg()-like dictionaries describing mappings.
--- The "buffer" key holds the associated buffer handle.
function vim.api.nvim_buf_get_keymap(buffer, mode) end
-- Gets a line-range from the buffer.
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param start integer #First line index
--- @param end_ integer #Last line index (exclusive)
--- @param strict_indexing boolean #Whether out-of-bounds should be an
--- error.
--- @return any #Array of lines, or empty array for unloaded buffer.
function vim.api.nvim_buf_get_lines(buffer, start, end_, strict_indexing) end
-- Return a tuple (row,col) representing the position of the
-- named mark.
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param name string #Mark name
--- @return any #(row, col) tuple
function vim.api.nvim_buf_get_mark(buffer, name) end
-- Gets the full file name for the buffer
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @return any #Buffer name
function vim.api.nvim_buf_get_name(buffer) end
-- Returns the byte offset of a line (0-indexed). |api-indexing|
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param index integer #Line index
--- @return any #Integer byte offset, or -1 for unloaded buffer.
function vim.api.nvim_buf_get_offset(buffer, index) end
-- Gets a buffer option value
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param name string #Option name
--- @return any #Option value
function vim.api.nvim_buf_get_option(buffer, name) end
-- Gets a buffer-scoped (b:) variable.
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param name string #Variable name
--- @return any #Variable value
function vim.api.nvim_buf_get_var(buffer, name) end
-- Checks if a buffer is valid and loaded. See |api-buffer| for
-- more info about unloaded buffers.
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @return any #true if the buffer is valid and loaded, false otherwise.
function vim.api.nvim_buf_is_loaded(buffer) end
-- Checks if a buffer is valid.
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @return any #true if the buffer is valid, false otherwise.
function vim.api.nvim_buf_is_valid(buffer) end
-- Gets the buffer line count
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @return any #Line count, or 0 for unloaded buffer. |api-buffer|
function vim.api.nvim_buf_line_count(buffer) end
-- Creates or updates an extmark.
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param ns_id integer #Namespace id from |nvim_create_namespace()|
--- @param line integer #Line where to place the mark, 0-based
--- @param col integer #Column where to place the mark, 0-based
--- @param opts dictionary #Optional parameters.
--- • id : id of the extmark to edit.
--- • end_line : ending line of the mark, 0-based
--- inclusive.
--- • end_col : ending col of the mark, 0-based
--- exclusive.
--- • hl_group : name of the highlight group used to
--- highlight this mark.
--- • virt_text : virtual text to link to this mark.
--- • virt_text_pos : positioning of virtual text.
--- Possible values:
--- • "eol": right after eol character (default)
--- • "overlay": display over the specified
--- column, without shifting the underlying
--- text.
--- • "right_align": display right aligned in the
--- window.
---
--- • virt_text_win_col : position the virtual text
--- at a fixed window column (starting from the
--- first text column)
--- • virt_text_hide : hide the virtual text when
--- the background text is selected or hidden due
--- to horizontal scroll 'nowrap'
--- • hl_mode : control how highlights are combined
--- with the highlights of the text. Currently
--- only affects virt_text highlights, but might
--- affect`hl_group`in later versions.
--- • "replace": only show the virt_text color.
--- This is the default
--- • "combine": combine with background text
--- color
--- • "blend": blend with background text color.
---
--- • hl_eol : when true, for a multiline highlight
--- covering the EOL of a line, continue the
--- highlight for the rest of the screen line
--- (just like for diff and cursorline highlight).
--- • ephemeral : for use with
--- |nvim_set_decoration_provider| callbacks. The
--- mark will only be used for the current redraw
--- cycle, and not be permantently stored in the
--- buffer.
--- • right_gravity : boolean that indicates the
--- direction the extmark will be shifted in when
--- new text is inserted (true for right, false
--- for left). defaults to true.
--- • end_right_gravity : boolean that indicates the
--- direction the extmark end position (if it
--- exists) will be shifted in when new text is
--- inserted (true for right, false for left).
--- Defaults to false.
--- • priority: a priority value for the highlight
--- group. For example treesitter highlighting
--- uses a value of 100.
--- @return any #Id of the created/updated extmark
function vim.api.nvim_buf_set_extmark(buffer, ns_id, line, col, opts) end
-- Sets a buffer-local |mapping| for the given mode.
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param mode string
--- @param lhs string
--- @param rhs string
--- @param opts dictionary
function vim.api.nvim_buf_set_keymap(buffer, mode, lhs, rhs, opts) end
-- Sets (replaces) a line-range in the buffer.
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param start integer #First line index
--- @param end_ integer #Last line index (exclusive)
--- @param strict_indexing boolean #Whether out-of-bounds should be an
--- error.
--- @param replacement string[] #Array of lines to use as replacement
function vim.api.nvim_buf_set_lines(buffer, start, end_, strict_indexing, replacement) end
-- Sets the full file name for a buffer
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param name string #Buffer name
function vim.api.nvim_buf_set_name(buffer, name) end
-- Sets a buffer option value. Passing 'nil' as value deletes the
-- option (only works if there's a global fallback)
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param name string #Option name
--- @param value object #Option value
function vim.api.nvim_buf_set_option(buffer, name, value) end
-- Sets (replaces) a range in the buffer
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param start_row integer #First line index
--- @param start_col integer
--- @param end_row integer #Last line index
--- @param end_col integer
--- @param replacement string[] #Array of lines to use as replacement
function vim.api.nvim_buf_set_text(buffer, start_row, start_col, end_row, end_col, replacement) end
-- Sets a buffer-scoped (b:) variable
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param name string #Variable name
--- @param value object #Variable value
function vim.api.nvim_buf_set_var(buffer, name, value) end
-- Set the virtual text (annotation) for a buffer line.
--- @param buffer buffer #Buffer handle, or 0 for current buffer
--- @param src_id integer
--- @param line integer #Line to annotate with virtual text
--- (zero-indexed)
--- @param chunks array #A list of [text, hl_group] arrays, each
--- representing a text chunk with specified
--- highlight. `hl_group` element can be omitted for
--- no highlight.
--- @param opts dictionary #Optional parameters. Currently not used.
--- @return any #The ns_id that was used
function vim.api.nvim_buf_set_virtual_text(buffer, src_id, line, chunks, opts) end
-- Calls many API methods atomically.
--- @param calls array #an array of calls, where each call is described
--- by an array with two elements: the request name,
--- and an array of arguments.
--- @return any #Array of two elements. The first is an array of return
--- values. The second is NIL if all calls succeeded. If a
--- call resulted in an error, it is a three-element array
--- with the zero-based index of the call which resulted in an
--- error, the error type and the error message. If an error
--- occurred, the values from all preceding calls will still
--- be returned.
function vim.api.nvim_call_atomic(calls) end
-- Calls a VimL |Dictionary-function| with the given arguments.
--- @param dict object #Dictionary, or String evaluating to a VimL |self|
--- dict
--- @param fn string #Name of the function defined on the VimL dict
--- @param args array #Function arguments packed in an Array
--- @return any #Result of the function call
function vim.api.nvim_call_dict_function(dict, fn, args) end
-- Calls a VimL function with the given arguments.
--- @param fn string #Function to call
--- @param args array #Function arguments packed in an Array
--- @return any #Result of the function call
function vim.api.nvim_call_function(fn, args) end
-- Send data to channel `id` . For a job, it writes it to the
-- stdin of the process. For the stdio channel |channel-stdio|,
-- it writes to Nvim's stdout. For an internal terminal instance
-- (|nvim_open_term()|) it writes directly to terimal output. See
-- |channel-bytes| for more information.
--- @param chan integer #id of the channel
--- @param data string #data to write. 8-bit clean: can contain NUL bytes.
function vim.api.nvim_chan_send(chan, data) end
-- Executes an ex-command.
--- @param command string #Ex-command string
function vim.api.nvim_command(command) end
-- Creates a new, empty, unnamed buffer.
--- @param listed boolean #Sets 'buflisted'
--- @param scratch boolean #Creates a "throwaway" |scratch-buffer| for
--- temporary work (always 'nomodified'). Also sets
--- 'nomodeline' on the buffer.
--- @return any #Buffer handle, or 0 on error
function vim.api.nvim_create_buf(listed, scratch) end
-- Creates a new namespace, or gets an existing one.
--- @param name string #Namespace name or empty string
--- @return any #Namespace id
function vim.api.nvim_create_namespace(name) end
-- Deletes the current line.
function vim.api.nvim_del_current_line() end
-- Unmaps a global |mapping| for the given mode.
--- @param mode string
--- @param lhs string
function vim.api.nvim_del_keymap(mode, lhs) end
-- Removes a global (g:) variable.
--- @param name string #Variable name
function vim.api.nvim_del_var(name) end
-- Echo a message.
--- @param chunks array #A list of [text, hl_group] arrays, each
--- representing a text chunk with specified
--- highlight. `hl_group` element can be omitted
--- for no highlight.
--- @param history boolean #if true, add to |message-history|.
--- @param opts dictionary #Optional parameters. Reserved for future use.
function vim.api.nvim_echo(chunks, history, opts) end
-- Writes a message to the Vim error buffer. Does not append
-- "\n", the message is buffered (won't display) until a linefeed
-- is written.
--- @param str string #Message
function vim.api.nvim_err_write(str) end
-- Writes a message to the Vim error buffer. Appends "\n", so the
-- buffer is flushed (and displayed).
--- @param str string #Message
function vim.api.nvim_err_writeln(str) end
-- Evaluates a VimL |expression|. Dictionaries and Lists are
-- recursively expanded.
--- @param expr string #VimL expression string
--- @return any #Evaluation result or expanded object
function vim.api.nvim_eval(expr) end
-- Executes Vimscript (multiline block of Ex-commands), like
-- anonymous |:source|.
--- @param src string #Vimscript code
--- @param output boolean #Capture and return all (non-error, non-shell
--- |:!|) output
--- @return any #Output (non-error, non-shell |:!|) if `output` is true,
--- else empty string.
function vim.api.nvim_exec(src, output) end
-- Execute Lua code. Parameters (if any) are available as `...`
-- inside the chunk. The chunk can return a value.
--- @param code string #Lua code to execute
--- @param args array #Arguments to the code
--- @return any #Return value of Lua code if present or NIL.
function vim.api.nvim_exec_lua(code, args) end
-- Sends input-keys to Nvim, subject to various quirks controlled
-- by `mode` flags. This is a blocking call, unlike
-- |nvim_input()|.
--- @param keys string #to be typed
--- @param mode string #behavior flags, see |feedkeys()|
--- @param escape_csi boolean #If true, escape K_SPECIAL/CSI bytes in
--- `keys`
function vim.api.nvim_feedkeys(keys, mode, escape_csi) end
-- Gets the option information for all options.
--- @return any #dictionary of all options
function vim.api.nvim_get_all_options_info() end
-- Returns a 2-tuple (Array), where item 0 is the current channel
-- id and item 1 is the |api-metadata| map (Dictionary).
--- @return any #2-tuple [{channel-id}, {api-metadata}]
function vim.api.nvim_get_api_info() end
-- Get information about a channel.
--- @param chan integer
--- @return any #Dictionary describing a channel, with these keys:
--- • "stream" the stream underlying the channel
--- • "stdio" stdin and stdout of this Nvim instance
--- • "stderr" stderr of this Nvim instance
--- • "socket" TCP/IP socket or named pipe
--- • "job" job with communication over its stdio
---
--- • "mode" how data received on the channel is interpreted
--- • "bytes" send and receive raw bytes
--- • "terminal" a |terminal| instance interprets ASCII
--- sequences
--- • "rpc" |RPC| communication on the channel is active
---
--- • "pty" Name of pseudoterminal, if one is used (optional).
--- On a POSIX system, this will be a device path like
--- /dev/pts/1. Even if the name is unknown, the key will
--- still be present to indicate a pty is used. This is
--- currently the case when using winpty on windows.
--- • "buffer" buffer with connected |terminal| instance
--- (optional)
--- • "client" information about the client on the other end
--- of the RPC channel, if it has added it using
--- |nvim_set_client_info()|. (optional)
function vim.api.nvim_get_chan_info(chan) end
-- Returns the 24-bit RGB value of a |nvim_get_color_map()| color
-- name or "#rrggbb" hexadecimal string.
--- @param name string #Color name or "#rrggbb" string
--- @return any #24-bit RGB value, or -1 for invalid argument.
function vim.api.nvim_get_color_by_name(name) end
-- Returns a map of color names and RGB values.
--- @return any #Map of color names and RGB values.
function vim.api.nvim_get_color_map() end
-- Gets a map of global (non-buffer-local) Ex commands.
--- @param opts dictionary #Optional parameters. Currently only supports
--- {"builtin":false}
--- @return any #Map of maps describing commands.
function vim.api.nvim_get_commands(opts) end
-- Gets a map of the current editor state.
--- @param opts dictionary #Optional parameters.
--- • types: List of |context-types| ("regs", "jumps",
--- "bufs", "gvars", …) to gather, or empty for
--- "all".
--- @return any #map of global |context|.
function vim.api.nvim_get_context(opts) end
-- Gets the current buffer.
--- @return any #Buffer handle
function vim.api.nvim_get_current_buf() end
-- Gets the current line.
--- @return any #Current line string
function vim.api.nvim_get_current_line() end
-- Gets the current tabpage.
--- @return any #Tabpage handle
function vim.api.nvim_get_current_tabpage() end
-- Gets the current window.
--- @return any #Window handle
function vim.api.nvim_get_current_win() end
-- Gets a highlight definition by id. |hlID()|
--- @param hl_id integer #Highlight id as returned by |hlID()|
--- @param rgb boolean #Export RGB colors
--- @return any #Highlight definition map
function vim.api.nvim_get_hl_by_id(hl_id, rgb) end
-- Gets a highlight definition by name.
--- @param name string #Highlight group name
--- @param rgb boolean #Export RGB colors
--- @return any #Highlight definition map
function vim.api.nvim_get_hl_by_name(name, rgb) end
-- Gets a highlight group by name
--- @param name string
function vim.api.nvim_get_hl_id_by_name(name) end
-- Gets a list of global (non-buffer-local) |mapping|
-- definitions.
--- @param mode string #Mode short-name ("n", "i", "v", ...)
--- @return any #Array of maparg()-like dictionaries describing mappings.
--- The "buffer" key is always zero.
function vim.api.nvim_get_keymap(mode) end
-- Gets the current mode. |mode()| "blocking" is true if Nvim is
-- waiting for input.
--- @return any #Dictionary { "mode": String, "blocking": Boolean }
function vim.api.nvim_get_mode() end
-- Gets existing, non-anonymous namespaces.
--- @return any #dict that maps from names to namespace ids.
function vim.api.nvim_get_namespaces() end
-- Gets an option value string.
--- @param name string #Option name
--- @return any #Option value (global)
function vim.api.nvim_get_option(name) end
-- Gets the option information for one option
--- @param name string #Option name
--- @return any #Option Information
function vim.api.nvim_get_option_info(name) end
-- Gets info describing process `pid` .
--- @param pid integer
--- @return any #Map of process properties, or NIL if process not found.
function vim.api.nvim_get_proc(pid) end
-- Gets the immediate children of process `pid` .
--- @param pid integer
--- @return any #Array of child process ids, empty if process not found.
function vim.api.nvim_get_proc_children(pid) end
-- Find files in runtime directories
--- @param name string #pattern of files to search for
--- @param all boolean #whether to return all matches or only the first
--- @return any #list of absolute paths to the found files
function vim.api.nvim_get_runtime_file(name, all) end
-- Gets a global (g:) variable.
--- @param name string #Variable name
--- @return any #Variable value
function vim.api.nvim_get_var(name) end
-- Gets a v: variable.
--- @param name string #Variable name
--- @return any #Variable value
function vim.api.nvim_get_vvar(name) end
-- Queues raw user-input. Unlike |nvim_feedkeys()|, this uses a
-- low-level input buffer and the call is non-blocking (input is
-- processed asynchronously by the eventloop).
--- @param keys string #to be typed
--- @return any #Number of bytes actually written (can be fewer than
--- requested if the buffer becomes full).
function vim.api.nvim_input(keys) end
-- Send mouse event from GUI.
--- @param button string #Mouse button: one of "left", "right",
--- "middle", "wheel".
--- @param action string #For ordinary buttons, one of "press", "drag",
--- "release". For the wheel, one of "up", "down",
--- "left", "right".
--- @param modifier string #String of modifiers each represented by a
--- single char. The same specifiers are used as
--- for a key press, except that the "-" separator
--- is optional, so "C-A-", "c-a" and "CA" can all
--- be used to specify Ctrl+Alt+click.
--- @param grid integer #Grid number if the client uses |ui-multigrid|,
--- else 0.
--- @param row integer #Mouse row-position (zero-based, like redraw
--- events)
--- @param col integer #Mouse column-position (zero-based, like redraw
--- events)
function vim.api.nvim_input_mouse(button, action, modifier, grid, row, col) end
-- Gets the current list of buffer handles
--- @return any #List of buffer handles
function vim.api.nvim_list_bufs() end
-- Get information about all open channels.
--- @return any #Array of Dictionaries, each describing a channel with the
--- format specified at |nvim_get_chan_info()|.
function vim.api.nvim_list_chans() end
-- Gets the paths contained in 'runtimepath'.
--- @return any #List of paths
function vim.api.nvim_list_runtime_paths() end
-- Gets the current list of tabpage handles.
--- @return any #List of tabpage handles
function vim.api.nvim_list_tabpages() end
-- Gets a list of dictionaries representing attached UIs.
--- @return any #Array of UI dictionaries, each with these keys:
--- • "height" Requested height of the UI
--- • "width" Requested width of the UI
--- • "rgb" true if the UI uses RGB colors (false implies
--- |cterm-colors|)
--- • "ext_..." Requested UI extensions, see |ui-option|
--- • "chan" Channel id of remote UI (not present for TUI)
function vim.api.nvim_list_uis() end
-- Gets the current list of window handles.
--- @return any #List of window handles
function vim.api.nvim_list_wins() end
-- Sets the current editor state from the given |context| map.
--- @param dict dictionary #|Context| map.
function vim.api.nvim_load_context(dict) end
-- Notify the user with a message
--- @param msg string #Message to display to the user
--- @param log_level integer #The log level
--- @param opts dictionary #Reserved for future use.
function vim.api.nvim_notify(msg, log_level, opts) end
-- Open a terminal instance in a buffer
--- @param buffer buffer #the buffer to use (expected to be empty)
--- @param opts dictionary #Optional parameters. Reserved for future use.
--- @return any #Channel id, or 0 on error
function vim.api.nvim_open_term(buffer, opts) end
-- Open a new window.
--- @param buffer buffer #Buffer to display, or 0 for current buffer
--- @param enter boolean #Enter the window (make it the current window)
--- @param config dictionary #Map defining the window configuration. Keys:
--- • `relative`: Sets the window layout to "floating", placed
--- at (row,col) coordinates relative to:
--- • "editor" The global editor grid
--- • "win" Window given by the `win` field, or
--- current window.
--- • "cursor" Cursor position in current window.
---
--- • `win` : |window-ID| for relative="win".
--- • `anchor`: Decides which corner of the float to place
--- at (row,col):
--- • "NW" northwest (default)
--- • "NE" northeast
--- • "SW" southwest
--- • "SE" southeast
---
--- • `width` : Window width (in character cells).
--- Minimum of 1.
--- • `height` : Window height (in character cells).
--- Minimum of 1.
--- • `bufpos` : Places float relative to buffer
--- text (only when relative="win"). Takes a tuple
--- of zero-indexed [line, column]. `row` and
--- `col` if given are applied relative to this
--- position, else they default to `row=1` and
--- `col=0` (thus like a tooltip near the buffer
--- text).
--- • `row` : Row position in units of "screen cell
--- height", may be fractional.
--- • `col` : Column position in units of "screen
--- cell width", may be fractional.
--- • `focusable` : Enable focus by user actions
--- (wincmds, mouse events). Defaults to true.
--- Non-focusable windows can be entered by
--- |nvim_set_current_win()|.
--- • `external` : GUI should display the window as
--- an external top-level window. Currently
--- accepts no other positioning configuration
--- together with this.
--- • `zindex`: Stacking order. floats with higher`zindex`go on top on floats with lower indices. Must
--- be larger than zero. The following screen
--- elements have hard-coded z-indices:
--- • 100: insert completion popupmenu
--- • 200: message scrollback
--- • 250: cmdline completion popupmenu (when
--- wildoptions+=pum) The default value for
--- floats are 50. In general, values below 100
--- are recommended, unless there is a good
--- reason to overshadow builtin elements.
---
--- • `style`: Configure the appearance of the window.
--- Currently only takes one non-empty value:
--- • "minimal" Nvim will display the window with
--- many UI options disabled. This is useful
--- when displaying a temporary float where the
--- text should not be edited. Disables
--- 'number', 'relativenumber', 'cursorline',
--- 'cursorcolumn', 'foldcolumn', 'spell' and
--- 'list' options. 'signcolumn' is changed to
--- `auto` and 'colorcolumn' is cleared. The
--- end-of-buffer region is hidden by setting
--- `eob` flag of 'fillchars' to a space char,
--- and clearing the |EndOfBuffer| region in
--- 'winhighlight'.
---
--- • `border`: Style of (optional) window border. This can
--- either be a string or an array. The string
--- values are
--- • "none": No border (default).
--- • "single": A single line box.
--- • "double": A double line box.
--- • "rounded": Like "single", but with rounded
--- corners ("╭" etc.).
--- • "solid": Adds padding by a single whitespace
--- cell.
--- • "shadow": A drop shadow effect by blending
--- with the background.
--- • If it is an array, it should have a length
--- of eight or any divisor of eight. The array
--- will specifify the eight chars building up
--- the border in a clockwise fashion starting
--- with the top-left corner. As an example, the
--- double box style could be specified as [
--- "╔", "═" ,"╗", "║", "╝", "═", "╚", "║" ]. If
--- the number of chars are less than eight,
--- they will be repeated. Thus an ASCII border
--- could be specified as [ "/", "-", "\\", "|"
--- ], or all chars the same as [ "x" ]. An
--- empty string can be used to turn off a
--- specific border, for instance, [ "", "", "",
--- ">", "", "", "", "<" ] will only make
--- vertical borders but not horizontal ones. By
--- default, `FloatBorder` highlight is used,
--- which links to `VertSplit` when not defined.
--- It could also be specified by character: [
--- {"+", "MyCorner"}, {"x", "MyBorder"} ].
---
--- • `noautocmd` : If true then no buffer-related
--- autocommand events such as |BufEnter|,
--- |BufLeave| or |BufWinEnter| may fire from
--- calling this function.
--- @return any #Window handle, or 0 on error
function vim.api.nvim_open_win(buffer, enter, config) end
-- Writes a message to the Vim output buffer. Does not append
-- "\n", the message is buffered (won't display) until a linefeed
-- is written.
--- @param str string #Message
function vim.api.nvim_out_write(str) end
-- Parse a VimL expression.
--- @param expr string #Expression to parse. Always treated as a
--- single line.
--- @param flags string #Flags:
--- • "m" if multiple expressions in a row are
--- allowed (only the first one will be
--- parsed),
--- • "E" if EOC tokens are not allowed
--- (determines whether they will stop parsing
--- process or be recognized as an
--- operator/space, though also yielding an
--- error).
--- • "l" when needing to start parsing with
--- lvalues for ":let" or ":for". Common flag
--- sets:
--- • "m" to parse like for ":echo".
--- • "E" to parse like for "<C-r>=".
--- • empty string for ":call".
--- • "lm" to parse for ":let".
--- @param highlight boolean #If true, return value will also include
--- "highlight" key containing array of 4-tuples
--- (arrays) (Integer, Integer, Integer, String),
--- where first three numbers define the
--- highlighted region and represent line,
--- starting column and ending column (latter
--- exclusive: one should highlight region
--- [start_col, end_col)).
--- @return any #
--- • AST: top-level dictionary with these keys:
--- • "error": Dictionary with error, present only if parser
--- saw some error. Contains the following keys:
--- • "message": String, error message in printf format,
--- translated. Must contain exactly one "%.*s".
--- • "arg": String, error message argument.
---
--- • "len": Amount of bytes successfully parsed. With flags
--- equal to "" that should be equal to the length of expr
--- string. (“Successfully parsed” here means
--- “participated in AST creation”, not “till the first
--- error”.)
--- • "ast": AST, either nil or a dictionary with these
--- keys:
--- • "type": node type, one of the value names from
--- ExprASTNodeType stringified without "kExprNode"
--- prefix.
--- • "start": a pair [line, column] describing where node
--- is "started" where "line" is always 0 (will not be 0
--- if you will be using nvim_parse_viml() on e.g.
--- ":let", but that is not present yet). Both elements
--- are Integers.
--- • "len": “length” of the node. This and "start" are
--- there for debugging purposes primary (debugging
--- parser and providing debug information).
--- • "children": a list of nodes described in top/"ast".
--- There always is zero, one or two children, key will
--- not be present if node has no children. Maximum
--- number of children may be found in node_maxchildren
--- array.
---
---
--- • Local values (present only for certain nodes):
--- • "scope": a single Integer, specifies scope for
--- "Option" and "PlainIdentifier" nodes. For "Option" it
--- is one of ExprOptScope values, for "PlainIdentifier"
--- it is one of ExprVarScope values.
--- • "ident": identifier (without scope, if any), present
--- for "Option", "PlainIdentifier", "PlainKey" and
--- "Environment" nodes.
--- • "name": Integer, register name (one character) or -1.
--- Only present for "Register" nodes.
--- • "cmp_type": String, comparison type, one of the value
--- names from ExprComparisonType, stringified without
--- "kExprCmp" prefix. Only present for "Comparison"
--- nodes.
--- • "ccs_strategy": String, case comparison strategy, one
--- of the value names from ExprCaseCompareStrategy,
--- stringified without "kCCStrategy" prefix. Only present
--- for "Comparison" nodes.
--- • "augmentation": String, augmentation type for
--- "Assignment" nodes. Is either an empty string, "Add",
--- "Subtract" or "Concat" for "=", "+=", "-=" or ".="
--- respectively.
--- • "invert": Boolean, true if result of comparison needs
--- to be inverted. Only present for "Comparison" nodes.
--- • "ivalue": Integer, integer value for "Integer" nodes.
--- • "fvalue": Float, floating-point value for "Float"
--- nodes.
--- • "svalue": String, value for "SingleQuotedString" and
--- "DoubleQuotedString" nodes.
function vim.api.nvim_parse_expression(expr, flags, highlight) end
-- Pastes at cursor, in any mode.
--- @param data string #Multiline input. May be binary (containing NUL
--- bytes).
--- @param crlf boolean #Also break lines at CR and CRLF.
--- @param phase integer #-1: paste in a single call (i.e. without
--- streaming). To "stream" a paste, call `nvim_paste` sequentially with these `phase` values:
--- • 1: starts the paste (exactly once)
--- • 2: continues the paste (zero or more times)
--- • 3: ends the paste (exactly once)
--- @return any #
--- • true: Client may continue pasting.
--- • false: Client must cancel the paste.
function vim.api.nvim_paste(data, crlf, phase) end
-- Puts text at cursor, in any mode.
--- @param lines string[] #|readfile()|-style list of lines.
--- |channel-lines|
--- @param type string #Edit behavior: any |getregtype()| result, or:
--- • "b" |blockwise-visual| mode (may include
--- width, e.g. "b3")
--- • "c" |charwise| mode
--- • "l" |linewise| mode
--- • "" guess by contents, see |setreg()|
--- @param after boolean #If true insert after cursor (like |p|), or
--- before (like |P|).
--- @param follow boolean #If true place cursor at end of inserted text.
function vim.api.nvim_put(lines, type, after, follow) end
-- Replaces terminal codes and |keycodes| (<CR>, <Esc>, ...) in a
-- string with the internal representation.
--- @param str string #String to be converted.
--- @param from_part boolean #Legacy Vim parameter. Usually true.
--- @param do_lt boolean #Also translate <lt>. Ignored if `special` is
--- false.
--- @param special boolean #Replace |keycodes|, e.g. <CR> becomes a "\n"
--- char.
function vim.api.nvim_replace_termcodes(str, from_part, do_lt, special) end
-- Selects an item in the completion popupmenu.
--- @param item integer #Index (zero-based) of the item to select. Value
--- of -1 selects nothing and restores the original
--- text.
--- @param insert boolean #Whether the selection should be inserted in the
--- buffer.
--- @param finish boolean #Finish the completion and dismiss the popupmenu.
--- Implies `insert` .
--- @param opts dictionary #Optional parameters. Reserved for future use.
function vim.api.nvim_select_popupmenu_item(item, insert, finish, opts) end
-- Self-identifies the client.
--- @param name string #Short name for the connected client
--- @param version dictionary #Dictionary describing the version, with
--- these (optional) keys:
--- • "major" major version (defaults to 0 if
--- not set, for no release yet)
--- • "minor" minor version
--- • "patch" patch number
--- • "prerelease" string describing a
--- prerelease, like "dev" or "beta1"
--- • "commit" hash or similar identifier of
--- commit
--- @param type string #Must be one of the following values. Client
--- libraries should default to "remote" unless
--- overridden by the user.
--- • "remote" remote client connected to Nvim.
--- • "ui" gui frontend
--- • "embedder" application using Nvim as a
--- component (for example, IDE/editor
--- implementing a vim mode).
--- • "host" plugin host, typically started by
--- nvim
--- • "plugin" single plugin, started by nvim
--- @param methods dictionary #Builtin methods in the client. For a host,
--- this does not include plugin methods which
--- will be discovered later. The key should be
--- the method name, the values are dicts with
--- these (optional) keys (more keys may be
--- added in future versions of Nvim, thus
--- unknown keys are ignored. Clients must only
--- use keys defined in this or later versions
--- of Nvim):
--- • "async" if true, send as a notification.
--- If false or unspecified, use a blocking
--- request
--- • "nargs" Number of arguments. Could be a
--- single integer or an array of two
--- integers, minimum and maximum inclusive.
--- @param attributes dictionary #Arbitrary string:string map of informal
--- client properties. Suggested keys:
--- • "website": Client homepage URL (e.g.
--- GitHub repository)
--- • "license": License description ("Apache
--- 2", "GPLv3", "MIT", …)
--- • "logo": URI or path to image, preferably
--- small logo or icon. .png or .svg format is
--- preferred.
function vim.api.nvim_set_client_info(name, version, type, methods, attributes) end
-- Sets the current buffer.
--- @param buffer buffer #Buffer handle
function vim.api.nvim_set_current_buf(buffer) end
-- Changes the global working directory.
--- @param dir string #Directory path
function vim.api.nvim_set_current_dir(dir) end
-- Sets the current line.
--- @param line string #Line contents
function vim.api.nvim_set_current_line(line) end
-- Sets the current tabpage.
--- @param tabpage tabpage #Tabpage handle
function vim.api.nvim_set_current_tabpage(tabpage) end
-- Sets the current window.
--- @param window window #Window handle
function vim.api.nvim_set_current_win(window) end
-- Set or change decoration provider for a namespace
--- @param ns_id integer #Namespace id from |nvim_create_namespace()|
--- @param opts table<string, luaref> #Callbacks invoked during redraw:
--- • on_start: called first on each screen redraw
--- ["start", tick]
--- • on_buf: called for each buffer being redrawn
--- (before window callbacks) ["buf", bufnr, tick]
--- • on_win: called when starting to redraw a
--- specific window. ["win", winid, bufnr, topline,
--- botline_guess]
--- • on_line: called for each buffer line being
--- redrawn. (The interation with fold lines is
--- subject to change) ["win", winid, bufnr, row]
--- • on_end: called at the end of a redraw cycle
--- ["end", tick]
function vim.api.nvim_set_decoration_provider(ns_id, opts) end
-- Set a highlight group.
--- @param ns_id integer #number of namespace for this highlight
--- @param name string #highlight group name, like ErrorMsg
--- @param val dictionary #highlight definition map, like
--- |nvim_get_hl_by_name|. in addition the following
--- keys are also recognized: `default` : don't
--- override existing definition, like `hi default`
--- `ctermfg` : sets foreground of cterm color
--- `ctermbg` : sets background of cterm color
--- `cterm` : cterm attribute map. sets attributed
--- for cterm colors. similer to `hi cterm` Note: by
--- default cterm attributes are same as attributes
--- of gui color
function vim.api.nvim_set_hl(ns_id, name, val) end
-- Sets a global |mapping| for the given mode.
--- @param mode string #Mode short-name (map command prefix: "n", "i",
--- "v", "x", …) or "!" for |:map!|, or empty string
--- for |:map|.
--- @param lhs string #Left-hand-side |{lhs}| of the mapping.
--- @param rhs string #Right-hand-side |{rhs}| of the mapping.
--- @param opts dictionary #Optional parameters map. Accepts all
--- |:map-arguments| as keys excluding |<buffer>| but
--- including |noremap|. Values are Booleans. Unknown
--- key is an error.
function vim.api.nvim_set_keymap(mode, lhs, rhs, opts) end
|
module('love.math')
function compress() end
function decompress() end
function gammaToLinear() end
function getRandomSeed() end
function getRandomState() end
function isConvex() end
function linearToGamma() end
function newBezierCurve() end
function newRandomGenerator() end
function newTransform() end
function noise() end
function random() end
function randomNormal() end
function setRandomSeed() end
function setRandomState() end
function triangulate() end
|
-- Copyright 2020 Rohit Goswami (HaoZeke) <rog32[at]hi.is>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
--
-- you may not use this file except in compliance with the License.
--
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
--
-- distributed under the License is distributed on an "AS IS" BASIS,
--
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
--
-- See the License for the specific language governing permissions and
--
-- limitations under the License.
help([[
User module to load pyenv
]])
whatis("Name: " .. myModuleName())
whatis("Version: " .. myModuleVersion())
whatis("Category: lang")
whatis("https://github.com/pyenv/pyenv/")
-- Dependencies
always_load("autotools/autotools")
always_load("openssl/1.1.1d")
always_load("bzip2/1.0.8")
always_load("readline/8.1-alpha")
always_load("sqlite/3.32.3")
-- Variables
local home = os.getenv("HOME")
local version = myModuleVersion()
local pkgName = myModuleName()
local pyenvh = pathJoin(home,".pyenv")
-- environment
setenv("PYENV_ROOT",pyenvh)
-- Paths
prepend_path("PATH",pathJoin(pyenvh,"bin"))
|
PLUGIN.name = "Disable Doors"
PLUGIN.author = "SleepyMode"
PLUGIN.desc = "A simple system to disable doors by default."
nut.config.add("disableDoors", true, "Whether or not all doors should be disabled by default.", function(oldValue, newValue)
for k, v in pairs( ents.FindByClass( "door_*" ) ) do
v:setNetVar("disabled", newValue)
end
end, {
category = "server"
})
|
local info = {
version = 1.002,
comment = "presets for textadept for context/metafun",
author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright = "PRAGMA ADE / ConTeXt Development Team",
license = "see context related readme files",
}
local lexer = require("scite-context-lexer")
local context = lexer.context
if context then
function context.synchronize()
local buffer = buffer
local property = lexer.property
local property_int = lexer.property_int
buffer:set_fold_margin_colour (true, property_int["color.light"])
buffer:set_fold_margin_hi_colour (true, property_int["color.white"])
buffer:set_sel_fore (false, property_int["color.dark"])
buffer:set_sel_back (true, property_int["color.selection"])
local MARK_BOOKMARK = textadept.bookmarks.MARK_BOOKMARK
local MARK_WARNING = textadept.run.MARK_WARNING
local MARK_ERROR = textadept.run.MARK_ERROR
-- buffer.marker_fore[MARK_BOOKMARK] = property_int["color.white"]
buffer.marker_back[MARK_BOOKMARK] = property_int["color.blue"]
-- buffer.marker_fore[MARK_WARNING] = property_int["color.white"]
buffer.marker_back[MARK_WARNING] = property_int["color.orange"]
-- buffer.marker_fore[MARK_ERROR] = property_int["color.white"]
buffer.marker_back[MARK_ERROR] = property_int["color.red"]
for i = 25, 31 do
buffer.marker_fore[i] = property_int["color.white"]
buffer.marker_back[i] = property_int["color.grey"]
buffer.marker_back_selected[i] = property_int["color.dark"]
end
local INDIC_BRACEMATCH = textadept.editing .INDIC_BRACEMATCH
local INDIC_HIGHLIGHT = textadept.editing .INDIC_HIGHLIGHT
local INDIC_PLACEHOLDER = textadept.snippets.INDIC_PLACEHOLDER
local INDIC_FIND = ui.find.INDIC_FIND
buffer.indic_fore [INDIC_FIND] = property_int["color.gray"]
buffer.indic_alpha[INDIC_FIND] = 255
buffer.indic_fore [INDIC_BRACEMATCH] = property_int["color.orange"]
buffer.indic_style[INDIC_BRACEMATCH] = buffer.INDIC_BOX -- hard to see (I need to check scite)
buffer.indic_fore [INDIC_HIGHLIGHT] = property_int["color.gray"]
buffer.indic_alpha[INDIC_HIGHLIGHT] = 255
buffer.indic_fore [INDIC_PLACEHOLDER] = property_int["color.gray"]
-- buffer:brace_highlight_indicator(false, INDIC_BRACEMATCH)
-- buffer.call_tip_fore_hlt = property_int["color.blue"]
buffer.edge_colour = property_int["color.grey"]
buffer.tab_width = 4
buffer.use_tabs = false
buffer.indent = 4
buffer.tab_indents = true
buffer.back_space_un_indents = true
buffer.indentation_guides = not CURSES and buffer.IV_LOOKBOTH or buffer.IV_NONE
buffer.sel_eol_filled = true
-- buffer.sel_alpha =
buffer.multiple_selection = true
buffer.additional_selection_typing = true
-- buffer.multi_paste = buffer.MULTIPASTE_EACH
-- buffer.virtual_space_options = buffer.VS_RECTANGULARSELECTION + buffer.VS_USERACCESSIBLE
buffer.rectangular_selection_modifier = buffer.MOD_ALT
buffer.mouse_selection_rectangular_switch = true
-- buffer.additional_sel_alpha =
-- buffer.additional_sel_fore =
-- buffer.additional_sel_back =
-- how to turn of the annoying background behind the current line ...
-- buffer.additional_caret_fore =
-- buffer.additional_carets_blink = false
-- buffer.additional_carets_visible = false
buffer.caret_line_visible = false -- not CURSES and buffer ~= ui.command_entry
buffer.caret_line_visible_always = false
-- buffer.caret_period = 0
-- buffer.caret_style = buffer.CARETSTYLE_BLOCK
buffer.caret_width = 10
buffer.caret_sticky = buffer.CARETSTICKY_ON
buffer.caret_fore = property_int["color.black"]
buffer.caret_line_back = property_int["color.light"]
-- buffer.caret_line_back_alpha =
buffer.view_ws = buffer.WS_INVISIBLE
buffer.view_eol = false
buffer.annotation_visible = buffer.ANNOTATION_BOXED
-- local NUMBER_MARGIN = 0
-- local MARKER_MARGIN = 1
-- local FOLD_MARGIN = 2 -- there are more
--
-- buffer.margin_type_n [NUMBER_MARGIN] = buffer.MARGIN_NUMBER
-- buffer.margin_width_n[NUMBER_MARGIN] = (CURSES and 0 or 4)
-- + 4 * buffer:text_width(buffer.STYLE_LINENUMBER,'9') -- magic
-- buffer.margin_width_n[MARKER_MARGIN] = CURSES and 1 or 4
-- buffer.margin_width_n[FOLD_MARGIN] = CURSES and 1 or 12
--
-- buffer.margin_mask_n[FOLD_MARGIN] = buffer.MASK_FOLDERS
buffer.wrap_mode = buffer.WRAP_NONE
buffer.margin_back_n[0] = property_int["color.linenumber"] -- doesn't work
buffer.property = {
-- ["style.linenumber"] = property["style.linenumber"], -- somehow it fails
}
buffer.property_int = {
-- nothing
}
-- keys [OSX and 'mr' or 'cr' ] = textadept.run.run
-- keys [OSX and 'mR' or (GUI and 'cR' or 'cmr')] = textadept.run.compile
-- keys [OSX and 'mB' or (GUI and 'cB' or 'cmb')] = textadept.run.build
-- keys [OSX and 'mX' or (GUI and 'cX' or 'cmx')] = textadept.run.stop
end
context.synchronize()
end
|
FILTER.Author = "@xayrga"
FILTER.Version = 1.0
FILTER.Name = "VerifyMute"
FILTER.DefaultEnabled = false
FILTER.Requires = {}
FILTER.Priority = 1000
local function FILTERCUSTOM_onUserVerified(thc, thm, groupID, GCO)
if (GCO:getBool("verifymute")==false) then -- skip if filter is not enabled
return false
end
Telegram.restrictChatMember(thc,thm, 0, true, true, true, true);
end
modhook.Add("verUserVerifiedNotify","FilterVerifyMute",FILTERCUSTOM_onUserVerified)
function FILTER:NewUser(user, chat, message, config, verifyData, doubt, from)
if (config:getBool("verifymute")==false) then -- don't continue if the filter is disabled for this chat
--print("Filter not enabled???")
return false
end
print(chat,user,config,message)
Telegram.restrictChatMember(chat,user, 0, false, false, false, false);
return false
end
function FILTER:OnChatMessage(user, chat, message, config, verifyData, doubt)
if (config:getBool("verifymute")==false) then -- don't continue if the filter is disabled for this chat
return false
end
if (verifyData==nil) then -- user has no verifydata, don't delete their stuff.
return false
end
if (message.new_chat_members~=nil) then -- don't delete the join message if the filter is enabled
return false
end
if (verifyData:getBool("verified")==false) then
message:delete() -- Delete their message if they're not verified
end
end
|
AccountData = {}
AccountData.__mt = {__index = AccountData}
AccountData.onChangeHandlers = {}
AccountData.onChangeDoneHandlers = {}
AccountData.map = {}
setmetatable(AccountData.map, {__mode = 'v'}) -- weak table
-- Note: default is always used for guests (even if database would ignore it)
PlayersTable = Database.Table{
name = 'players',
{'player', 'INT UNSIGNED', pk = true, default = 0},
{'serial', 'VARCHAR(32)', default = '', null = true},
{'account', 'VARCHAR(255)', default = '', null = true},
{'time_here', 'INT UNSIGNED', default = 0},
{'first_visit', 'INT UNSIGNED', default = false, null = true},
{'last_visit', 'INT UNSIGNED', default = false, null = true},
{'ip', 'VARCHAR(16)', default = false, null = true},
{'name', 'VARCHAR(32)', default = ''},
{'namePlain', 'VARCHAR(32)', default = ''},
{'online', 'BOOL', default = 0},
{'email', 'VARCHAR(128)', default = false, null = true},
{'players_idx', unique = {'account'}},
}
local DefaultData = false
function AccountData:fillCache()
assert(self.id)
local rows = DbQuery('SELECT * FROM '..PlayersTable..' WHERE player=? LIMIT 1', self.id)
cache = rows[1] or false
self.cache = cache
self.allCached = true
end
function AccountData:getTbl()
if(not self.allCached) then
self:fillCache()
end
return self.cache
end
function AccountData:get(name)
assert(type(self) == 'table' and name)
-- prepare arguments
local fields = name
if(type(fields) ~= 'table') then
fields = {name}
end
local result = {}
for i, field in ipairs(fields) do
-- Check if field value is in cache
if(self.cache[field] == nil) then
-- Load entire row from database
self:fillCache()
end
-- Get value from cache
local value = self.cache[field]
if(value ~= nil) then
result[field] = value
else
Debug.warn('Unknown field '..field)
end
end
-- Return result in proper format
if(type(name) == 'table') then
return result
else
return result[name]
end
end
-- AccountData:set(tbl, silent)
-- AccountData:set(name, value, silent)
function AccountData:set(arg1, arg2, arg3)
assert(type(self) == 'table' and arg1)
local data, silent
if(type(arg1) == 'table') then
data = arg1
silent = arg2
else
data = {[arg1] = arg2 or false}
silent = arg3
end
local set = ''
local params = {}
for k, v in pairs(data) do
local colDef = PlayersTable.colMap[k]
assert(colDef)
if(self.cache[k] == nil or self.cache[k] ~= v) then
if(v == false) then
set = set..','..k..'=NULL'
elseif(type(v) == 'string' and colDef[2] == 'BLOB' and v) then
set = set..','..k..'='..DbBlob(v)
else
set = set..','..k..'=?'
table.insert(params, v)
end
if(not silent) then
for i, handler in ipairs(AccountData.onChangeHandlers) do
handler(self, k, v)
end
--onPostChangeHandlers
end
self.cache[k] = v
end
end
local result = true
if(self.id and set ~= '') then
-- Add player ID at the end of parameters table. Note: we can't use it when calling DbQuery
-- because unpack has to be on the last place. If it's not only one element from table is used.
table.insert(params, self.id)
result = DbQuery('UPDATE '..PlayersTable..' SET '..set:sub(2)..' WHERE player=?', unpack(params))
end
if(not silent) then
for k, v in pairs(data) do
for i, handler in ipairs(AccountData.onChangeDoneHandlers) do
handler(self, k)
end
end
end
return result
end
function AccountData:add(name, num)
assert(type(self) == 'table' and name and num)
local val = AccountData.get(self, name)
assert(type(val) == 'number')
return AccountData.set(self, name, val + num)
end
local function getDefaultData()
if(DefaultData) then return DefaultData end
DefaultData = {}
for i, fieldInfo in ipairs(PlayersTable) do
if(#fieldInfo >= 2) then
assert(fieldInfo.default ~= nil)
DefaultData[fieldInfo[1]] = fieldInfo.default
end
end
return DefaultData
end
function AccountData.create(id)
if(id and AccountData.map[id]) then
return AccountData.map[id]
end
local self = {id = id, cache = {}, allCached = false}
if(id) then
AccountData.map[id] = self
else
self.cache = table.copy(getDefaultData())
self.allCached = true
end
return setmetatable(self, AccountData.__mt)
end
function AccountData.__mt.__index(self, k)
local val = AccountData[k] or rawget(self, k)
if(val ~= nil) then
return val
else
return AccountData.get(self, k)
end
end
function AccountData.__mt.__newindex(self, k, v)
--Debug.info('__newindex '..tostring(k))
AccountData.set(self, k, v)
end
|
local ffi = require("ffi")
local RendererBase = require("gwen.renderers.base")
local BL2Renderer = oo.InheritClass(RendererBase, "Gwen.Renderer.BL2")
local engine = engine
local canvas = canvas
local whiteColor = Color(255, 255, 255, 255)
-- TODO: This whole renderer ignores scaling
function BL2Renderer:SetDrawColor(color)
if color == nil then
canvas.SetDrawColor(whiteColor)
else
canvas.SetDrawColor(color)
end
end
function BL2Renderer:DrawFilledRect(bounds)
canvas.DrawRect(bounds.x, bounds.y, bounds.w, bounds.h)
end
function BL2Renderer:StartClip()
canvas.SetClipRect(
self.clipRegion.x,
self.clipRegion.y,
self.clipRegion.w,
self.clipRegion.h
)
end
function BL2Renderer:EndClip()
canvas.ResetClip()
end
function BL2Renderer:LoadTexture(texName)
local tex = engine.FindObject(texName, engine.Classes.UTexture2D)
if tex == nil then
error("Texture could not be found")
end
return ffi.cast("struct UTexture2D*", tex)
end
function BL2Renderer:DrawTexturedRect(tex, bounds, u, v, ul, vl)
canvas.SetTexture(tex)
canvas.DrawTexturedRectUV(bounds.x, bounds.y, bounds.w, bounds.h, u, v, ul, vl)
end
function BL2Renderer:LoadFont(fontName)
local font = engine.FindObject(fontName, engine.Classes.UFont)
if font == nil then
error("Font could not be found")
end
return ffi.cast("struct UFont*", font)
end
--[[
oo.NotImplemented(RendererBase, "RenderText", "font", "pos", "text")
oo.NotImplemented(RendererBase, "MeasureText", "font", "text")
]]
return BL2Renderer
|
local playsession = {
{"mewmew", {103574}},
{"_Mash_", {24734}},
{"Akhrem", {183209}},
{"A-l-a-n", {695833}},
{"CmdrRat", {351552}},
{"SMikiS", {321691}},
{"FallenAngel1010", {11292}},
{"Leverage", {198472}},
{"xPedion", {18192}},
{"VB11", {340728}},
{"mcskiny", {738164}},
{"oloklir", {664566}},
{"xaddr", {934774}},
{"raskl", {300799}},
{"Arabiato", {225537}},
{"Waldlaeufer17", {8681}},
{"banakeg", {1221587}},
{"Mr.Clear", {2005}},
{"Bunchofrocks", {3046}},
{"Gunter.", {2431}},
{"Factorian12321", {68016}},
{"swisser", {97398}},
{"Corlin", {551556}},
{"MADZEH", {482427}},
{"red11", {548086}},
{"JinNJuice", {119970}},
{"twinotter", {4045}},
{"Giatros", {187378}},
{"ajicurry", {194709}},
{"edensg", {81435}},
{"UTIDI", {361752}},
{"Everken", {45912}},
{"PipWinsAgain", {164997}},
{"linzefeng", {308179}},
{"HardcoreRocco", {754527}},
{"loutanifi", {1663}},
{"danyal_knights", {315417}},
{"Foux3k", {18601}},
{"ryan_gregson2000", {5582}},
{"Gerkiz", {7907}},
{"ValidusVirtu", {292325}},
{"Karmoq", {5047}},
{"p27", {1421324}},
{"Revar", {167430}},
{"vedolv", {44178}},
{"Tazerfingers", {49380}},
{"Kruv", {5430}},
{"Whouser", {372881}},
{"GreySintax", {124011}},
{"kalikas", {557105}},
{"QuaxzRu", {590574}},
{"mk5656", {95439}},
{"chrisisthebe", {78537}},
{"penguincc3", {100925}},
{"RedPandaRam", {16736}},
{"KirillRu", {3589}},
{"TryonHD", {3445}},
{"Leon3", {8972}},
{"Dr.MoonShine", {119918}},
{"DarkChedarCheese", {190256}},
{"changaryyy", {442205}},
{"Zory", {32779}},
{"bhenoa", {14029}},
{"Morgan3rd", {119811}},
{"Cukrosember", {2872}},
{"westbroma", {7808}},
{"woodgoblinx", {6792}},
{"putinss", {131607}},
{"Impatient", {635140}},
{"19cygan85", {263294}},
{"slumberknight", {7729}},
{"Valcries", {1719}},
{"Bryce940", {17233}},
{"Dwimenor", {121186}},
{"bdehaven", {25043}},
{"epicsmokey", {2214}},
{"untouchablez", {3925}},
{"Footy", {88652}},
{"MangaFairy", {30471}},
{"Tracolix", {326}},
{"KloStein", {3858}},
{"Xonic6", {1576}},
{"Conor0709", {16925}},
{"Delqvs", {123054}},
{"Dofolo", {53872}},
{"LucasB2016", {13893}},
{"Vacuolum", {645887}},
{"dpoba", {162196}},
{"Nemesisboi", {263049}},
{"warnotte", {168825}},
{"ksb4145", {94270}},
{"vvictor", {6324}},
{"MeggalBozale", {59149}},
{"craigrood", {24866}},
{"die_ott", {12295}},
{"xcube", {69823}},
{"Thelrian", {220268}},
{"Minifinger", {330587}},
{"Dartemon", {7662}},
{"Liutio", {3696}},
{"helenohyeah", {3399}},
{"mzore", {401716}},
{"Cesare", {17504}},
{"AFD", {5907}},
{"BallisticGamer04", {315638}},
{"ETK03", {9174}},
{"Jeremykyle", {133668}},
{"LegionMammal978", {49596}},
{"PoPiSowy", {4719}},
{"sobitome", {38014}},
{"Poo76765", {4365}},
{"tmoneyfizzle", {1934}},
{"stargazer5683", {322687}},
{"hsxu", {11565}},
{"NekoBaron", {21778}},
{"dawsontyler02", {1834}},
{"flooxy", {5487}},
{"captcougar1969", {3096}},
{"abrown4521", {10349}},
{"Lithidoria", {6265}},
{"brftjx", {2590}},
{"Wiedrock", {38446}},
{"skynavy", {23820}}
}
return playsession |
return {
setup = {
{
"nvim-treesitter/nvim-treesitter",
run = ":TSUpdate",
requires = "nvim-treesitter/nvim-treesitter-textobjects",
},
},
}
|
--do the local variables here ie
local besttime = 0
local bat = 0
local amps = 0
local time = 0
local sats = 0
local speed = 0
local mkerror
local timer
local text = "Mikrokopter"
local temp = 0
local errorcode
local error_txt = {
0 = "Mikrokopter",
1 = "FC not compatible",
2 = "MK3Mag not compatible ",
3 = "no FC communication ",
4 = "no MK3Mag communication ",
5 = "no GPS communication ",
6 = "bad compass value ",
7 = "RC Signal lost ",
8 = "FC spi rx error ",
9 = "ERR: no NC communication ",
10 = "ERR: FC Nick Gyro ",
11 = "ERR: FC Roll Gyro ",
12 = "ERR: FC Yaw Gyro ",
13 = "ERR: FC Nick ACC ",
14 = "ERR: FC Roll ACC ",
15 = "ERR: FC Z-ACC ",
16 = "ERR: Pressure sensor ",
17 = "ERR: FC I2C ",
18 = "ERR: Bl Missing ",
19 = "Mixer Error ",
20 = "FC: Carefree Error ",
21 = "ERR: GPS lost ",
22 = "ERR: Magnet Error ",
23 = "Motor restart ",
24 = "BL Limitation ",
25 = "Waypoint range ",
26 = "ERR:No SD-Card ",
27 = "ERR:SD Logging aborted ",
28 = "ERR:Flying range! ",
29 = "ERR:Max Altitude ",
30 = "No GPS Fix ",
31 = "compass not calibrated ",
32 = "BL Selftest error ",
33 = "no ext. compass",
34 = "compass sensor",
}
--etc
local function init()
-- Initial set up here. Not always needed. This will be run once at model load.
end
local function background()
--tim1 = model.getTimer(1)
--stuff here is done all time
timer = model.getTimer(0)
end
local function run(event)
background()
print(event)
--lines
lcd.drawLine( 0, 31, 211, 31, SOLID, 0)
lcd.drawLine( 0, 53, 211, 53, SOLID, 0)
lcd.drawLine(106, 0, 106, 53, SOLID, 0)
-- bat
lcd.drawText(15, 3, getValue(216) .. " V", MIDSIZE) --"vfas"
lcd.drawTimer(65, 20, timer.value, 0) --timer
lcd.drawText(15, 20, getValue(208) .. " mAh",0) --"fuel" current mAh
lcd.drawText(15, 33, getValue(207) .. " sats", 0) --"rpm" sats in use
lcd.drawText(15, 41, getValue(211) .. " km/h", 0) --"gps-speed"
lcd.drawText(108, 3, "Alt:" .. getValue("altitude") .. " m gAlt:" .. getValue(213) .. "m",0) --altitude and gps altitude
lcd.drawText(108, 12, "Dir: " .. getValue(223),0) --heading
lcd.drawText(108, 20, "I: " .. getValue(217),0) --current
lcd.drawText(108, 33, "Home: " .. getValue(212) .. " m" ,0) --gps distance
lcd.drawText(108, 41, "Dir: home", 0)
--This happens when telemetry screen is on
lcd.drawText (60, 56, "Mikrokopter", 0)
background()
print(event)
--lines
lcd.drawLine( 0, 31, 211, 31, SOLID, 0)
lcd.drawLine( 0, 53, 211, 53, SOLID, 0)
lcd.drawLine(106, 0, 106, 53, SOLID, 0)
-- bat
lcd.drawText(15, 3, getValue(216) .. " V", MIDSIZE) --Voltage
lcd.drawTimer(65, 20, timer.value, 0) --timer
lcd.drawText(15,20, getValue(208) .. " mAh",0) --"fuel" current mAh
lcd.drawText(15,33, getValue(207) .. " sats", 0) --sats in use
lcd.drawText(15,41, getValue(211) .. " km/h", 0) --"gps speed"
lcd.drawText( 108,3, "Alt:" .. getValue("altitude") .. " m gAlt:" .. getValue(213) .. "m",0) --altitude and gps altitude
lcd.drawText( 108,12, "Dir: " .. getValue(223),0) --"heading"
lcd.drawText( 108,20, "I: " .. getValue(217),0) --"current"
lcd.drawText( 108,33, "Home: " .. getValue(212) .. " m" , 0) --"distance"
lcd.drawText( 108,41, "Dir: home", 0)
local t2 = getValue(210) -- temp2 Temperature 2 [degrees celsius]
text = error_txt[t2]
if t2 == 0 then
lcd.drawText (105 - 50 / 2, 56, text, 0)
else
lcd.drawText (20, 56, text, 0)
end
end
return { init=init, background=background, run=run }
|
local tableComponent = {}
local function makeTextEl(content, parent)
return {
type = "text",
content = (parent.properties.prepend or "")
.. content ..
(parent.properties.append or ""),
parent = parent
}
end
local function addClass(node, class)
local prop = node.properties
local cc = prop.class or ""
if #cc > 0 then
local stM, enM = cc:find(class)
if (not stM) or cc:sub(stM - 1, enM + 1):match("%S+") ~= class then
prop.class = cc .. " " .. class
end
else
prop.class = class
end
end
function tableComponent.new(node, renderer)
local t = { node = node, renderer = renderer }
local rtemp = renderer.querySelector("#row-template")
if #rtemp > 0 then
local row = rtemp[1]
for i = 1, #row.parent.children do
if row.parent.children[i] == row then
row.parent.children[i] = nil
end
end
row.properties.id = nil
t.rowTemplate = row
end
local tel = renderer.querySelector("th", node)
foreach(th, tel) do
th.adapter = renderer.components.text.new(th)
end
return setmetatable(t, { __index = tableComponent })
end
function tableComponent:render(surf, position, styles, resolver)
if styles["background-color"] then
local c = resolver({}, "color", styles["background-color"])
if c > 0 then
surf:fillRect(position.left, position.top, position.width, position.height, c)
end
end
local rows = self.renderer.querySelector("tr", self.node)
local flowY = position.top
foreach(row, rows) do
local flowX = position.left
local maxH = 0
local flexTot = 0
local remWidth = position.width
local widths = {}
for j = 1, #row.children do
local td = row.children[j]
if td.styles.width then
local w = resolver({width = position.width, flowW = remWidth}, "width", td.styles.width)
remWidth = remWidth - w
widths[j] = w
else
flexTot = flexTot + (tonumber(td.styles.flex) or 1)
end
end
for j = 1, #row.children do
local td = row.children[j]
if row.styles["line-height"] and not td.styles["line-height"] then
td.styles["line-height"] = row.styles["line-height"]
end
local height = tonumber(td.adapter:resolveHeight(td.styles, { width = 10 }, resolver):sub(1, -3))
local width
if widths[j] then
width = math.floor(widths[j])
else
width = math.floor(remWidth * ((tonumber(td.styles.flex) or 1) / flexTot))
end
td.adapter:render(surf, {
left = flowX,
top = flowY,
width = width,
height = height
}, td.styles, resolver)
maxH = math.max(maxH, height)
flowX = flowX + width
end
if row.styles["background-color"] then
local c = resolver({}, "color", row.styles["background-color"])
if c > 0 then
surf:fillRect(position.left, flowY, position.width, maxH, c)
end
end
flowY = flowY + maxH
end
end
function tableComponent:updateData(data)
self.data = data
-- New data so create and restyle it
local body = self.renderer.querySelector("tbody", self.node)[1]
if self.rowTemplate then
local newChildren = {}
local sortedList = {}
for k, _ in pairs(data) do
sortedList[#sortedList + 1] = k
end
table.sort(sortedList, function(str1, str2)
local cOrder1 = transformedItems[str1].order
local cOrder2 = transformedItems[str2].order
if (cOrder1 or cOrder2) and (cOrder1 ~= cOrder2) then
return (cOrder1 or math.huge) < (cOrder2 or math.huge)
end
str1 = transformedItems[str1].disp
str2 = transformedItems[str2].disp
local i = 0
local c1, c2
repeat
i = i + 1
c1 = str1:sub(i, i):lower()
c2 = str2:sub(i, i):lower()
until i == #str1 or i == #str2 or c1 ~= c2
return c1:byte() < c2:byte()
end)
for sI = 1, #sortedList do
local k = sortedList[sI]
local v = tostring(data[sortedList[sI]])
local skeleton = util.deepClone(self.rowTemplate)
skeleton.parent = body
local tel = self.renderer.querySelector("td", skeleton)
foreach(td, tel) do
td.adapter = self.renderer.components.text.new(td)
end
local stock = self.renderer.querySelector("#stock", skeleton)[1]
local name = self.renderer.querySelector("#name", skeleton)[1]
local price = self.renderer.querySelector("#price", skeleton)[1]
local pricePerStack = self.renderer.querySelector("#price-per-stack", skeleton)[1]
local addy = self.renderer.querySelector("#addy", skeleton)[1]
local addyFull = self.renderer.querySelector("#addy-full", skeleton)[1]
if stock then
stock.children = { makeTextEl(v, stock) }
addClass(stock, "stock")
v = tonumber(v)
if v < (transformedItems[k].critical or config.criticalStock or 10) then
addClass(stock, "critical")
elseif v < (transformedItems[k].low or config.lowStock or 50) then
addClass(stock, "low")
end
end
if name then
name.children = { makeTextEl(transformedItems[k].disp or k, name) }
addClass(name, "name")
end
if price then
price.children = { makeTextEl(transformedItems[k].price, price) }
addClass(price, "price")
end
if pricePerStack then
pricePerStack.children = { makeTextEl(util.round(60 / transformedItems[k].price, 2), pricePerStack) }
addClass(pricePerStack, "price-per-stack")
end
if addy then
addy.children = { makeTextEl(transformedItems[k].addy, addy) }
addClass(addy, "addy")
end
if addyFull then
addyFull.children = { makeTextEl(transformedItems[k].addy .. "@" .. config.name .. ".kst", addyFull) }
addClass(addyFull, "addy-full")
end
newChildren[#newChildren + 1] = skeleton
end
body.children = newChildren
end
self.renderer.processStyles()
end
return tableComponent |
local composer = require("composer");
composer.gotoScene("scenes.menu");
|
local alib = loadmodule("avada_lib")
local common = alib.common
local draw = alib.draw
local menu = loadsubmodule("avada_evade", "menu")
local polygon_helper = loadsubmodule("avada_evade", "modules/polygon_helper")
local clipper = loadclipper()
local myHero = objmanager.player
local mouve_to_mouse = {}
function mouve_to_mouse.run (evader)
local mypos = myHero.pos
local endPos = nil
if(menu.mc.evaders.omni_evade.use_full_distance:get())then
endPos = mypos+(game.mousePos-mypos):norm()*common.GetDistance(mypos, game.mousePos)
else
endPos = mypos+(game.mousePos-mypos):norm()*menu.mc.evaders.mouve_to_mouse.force_distance:get()
end
local current_hits = evader.intersections:get(1):size()
--Calc hits at mousePos
local points_mp = evader.calculate_intersections(endPos, myHero.collisionRadius+menu.mc.myHero.additional_collision_radius:get(), menu.mc.evaders.mouve_to_mouse.max_intersection_precision:get())
local c_hits_mp = (points_mp:size() == 0 and 0 or points_mp:get(1):size())
if(c_hits_mp >= current_hits)then
return false
end
local current_intersections = evader.intersections
local distance = common.GetDistance(mypos, endPos)
local precision = math.floor(distance/menu.mc.evaders.mouve_to_mouse.precision_divisor:get())
local vec_mult = distance/precision
local base_vec = (endPos - mypos):norm()
local max_width = menu.mc.evaders.mouve_to_mouse.max_width:get()
local best_rotation = math.huge
local min_hits = math.huge
for n=max_width*-1,max_width,menu.mc.evaders.mouve_to_mouse.n_step_witdh:get() do
local hits = 0
local steps_with_hits = 0
mbase_vec = polygon_helper.RotateVector3(base_vec, n)
for i=1,precision do
local c_vec = mypos + mbase_vec*(vec_mult*i)
local points = evader.calculate_intersections(c_vec, myHero.collisionRadius+menu.mc.myHero.additional_collision_radius:get(), menu.mc.evaders.mouve_to_mouse.max_intersection_precision:get())
local c_hits = (points:size() == 0 and 0 or points:get(1):size())
if(c_hits >= menu.mc.evaders.mouve_to_mouse.max_intersection_precision:get())then
hits = math.huge
break
else
hits = hits + c_hits
steps_with_hits = steps_with_hits + 1
end
end
if(hits*steps_with_hits < min_hits)then
best_rotation = n
min_hits = hits
end
end
mbase_vec = polygon_helper.RotateVector3(base_vec, best_rotation)
local c_vec = mypos + mbase_vec*(distance)
game.issue("move", c_vec)
evader.method = "mouve_to_mouse"
return true
end
return mouve_to_mouse |
local RobloxReplicatedStorage = game:GetService('RobloxReplicatedStorage')
RemoteEvent_NewFollower = RobloxReplicatedStorage:WaitForChild('NewFollower')
while wait(0) do
for i,v in pairs(game.Players:GetChildren()) do
game.Players.LocalPlayer:RequestFriendship(v)
RemoteEvent_NewFollower:FireServer(v, true)
wait(0.01)
RemoteEvent_NewFollower:FireServer(v, false)
game.Players.LocalPlayer:RevokeFriendship(v)
end
end |
-- NEEDS CHECKING
-- stuff has that comment, search for it
aFunctions = {
team = {
['createteam'] = function ( name, r, g, b )
local success = false
if ( tonumber ( r ) ) and ( tonumber ( g ) ) and ( tonumber ( b ) ) then
success = createTeam ( name, tonumber ( r ), tonumber ( g ), tonumber ( b ) )
else
success = createTeam ( name )
end
if ( not success ) then
outputChatBox ( "Team \""..name.."\" could not be created.", source, 255, 0, 0 )
end
return success, name
end,
['destroyteam'] = function ( team )
if ( ( team ) and ( isElement ( team ) ) and ( getElementType ( team ) == "team" ) ) then
local name = getTeamName ( team )
return destroyElement ( team ), name
else
return false
end
end
},
player = {
['kick'] = function ( player, data )
setTimer ( kickPlayer, 100, 1, player, source, data )
end,
['ban'] = function ( player, data )
setTimer ( banPlayer, 100, 1, player, true, true, true, source, data )
end,
['mute'] = function ( player )
setPlayerMuted ( player, true )
end,
['unmute'] = function ( player )
setPlayerMuted ( player, false )
end,
['freeze'] = function ( player )
setElementFrozen ( player, true )
end,
['unfreeze'] = function ( player )
setElementFrozen ( player, false )
end,
['shout'] = function ( player, text )
local textDisplay = textCreateDisplay ()
local textItem = textCreateTextItem ( "(ADMIN)"..getPlayerName ( source )..":\n\n"..text, 0.5, 0.5, 2, 255, 100, 50, 255, 4, "center", "center" )
textDisplayAddText ( textDisplay, textItem )
textDisplayAddObserver ( textDisplay, player )
setTimer ( textDestroyTextItem, 5000, 1, textItem )
setTimer ( textDestroyDisplay, 5000, 1, textDisplay )
end,
['sethealth'] = function ( player, health )
local health = tonumber ( health )
if ( health ) then
if ( health > 200 or health <= 0 ) then health = 100 end
return setElementHealth ( player, health ), health
else
action = false
end
end,
['setarmour'] = function ( player, armour )
local armour = tonumber ( armour )
if ( armour ) then
if ( armour > 200 or armour <= 0 ) then armour = 100 end
return setPedArmor ( player, armour ), armour
else
return false
end
end,
['setskin'] = function ( player, skin )
local skin = tonumber ( skin )
if ( not skin ) then return false end
return setElementModel ( player, skin ), skin
end,
['setmoney'] = function ( player, value )
local money = tonumber ( value )
if ( not money ) then return false end
if ( not setPlayerMoney ( player, money ) ) then
outputChatBox ( "Invalid money value", source, 255, 0, 0 )
return false
end
return true, money
end,
['setstat'] = function ( player, stat, value )
if ( not value ) then return false end
if ( tonumber ( stat ) == 300 ) then
return setPedFightingStyle ( player, tonumber ( value ) ), "Fighting Style", value
else
return setPedStat ( player, tonumber ( stat ), tonumber ( value ) ), aStats[stat], value
end
end,
['setteam'] = function ( player, team )
if ( getElementType ( team ) == "team" ) then
return setPlayerTeam ( player, team ), getTeamName ( team )
end
return false
end,
['setinterior'] = function ( player, data )
for id, interior in ipairs ( aInteriors ) do
if ( interior["id"] == data ) then
local vehicle = getPedOccupiedVehicle ( player )
setElementInterior ( player, interior["world"] )
local x, y, z = interior["x"] or 0, interior["y"] or 0, interior["z"] or 0
local rot = interior["r"] or 0
if ( vehicle ) then
setElementInterior ( vehicle, interior["world"] )
setElementPosition ( vehicle, x, y, z + 0.2 )
else
setElementPosition ( player, x, y, z + 0.2 )
setPedRotation ( player, rot )
end
return true, interior["id"]
end
end
return false
end,
['setdimension'] = function ( player, dimension )
local dimension = tonumber ( dimension )
if ( dimension ) then
if ( dimension > 65535 ) or ( dimension < 0 ) then dimension = 0 end
return setElementDimension ( player, dimension ), dimension
else
return false
end
end,
['jetpack'] = function ( player )
if ( doesPedHaveJetPack ( player ) ) then
removePedJetPack ( player )
return true, "jetpackr"
else
if ( getPedOccupiedVehicle ( player ) ) then outputChatBox ( "Unable to give a jetpack - "..getPlayerName ( player ).." is in a vehicle", source, 255, 0, 0 )
else
if ( givePedJetPack ( player ) ) then
return true, "jetpacka"
end
end
end
end,
['setgroup'] = function ( player, data )
-- NEEDS CHECKING
local account = getPlayerAccount ( player )
if ( not isGuestAccount ( account ) ) then
local group = aclGetGroup ( data )
if ( group ) then
if ( data == true ) then
aclGroupAddObject ( group, "user."..getAccountName ( account ) )
return true, "admina"
elseif ( data == false ) then
aclGroupRemoveObject ( group, "user."..getAccountName ( account ) )
aPlayers[player]["chat"] = false
return true, "adminr"
end
for id, p in ipairs ( getElementsByType ( "player" ) ) do
if ( hasObjectPermissionTo ( p, "general.adminpanel" ) ) then triggerEvent ( "aSync", p, "admins" ) end
end
else
outputChatBox ( "Error - Admin group not initialized. Please reinstall admin resource.", source, 255, 0 ,0 )
end
else
outputChatBox ( "Error - Player is not logged in.", source, 255, 100 ,100 )
end
end,
['givevehicle'] = function ( player, id )
local pvehicle = getPedOccupiedVehicle ( player )
local vx, vy, vz = getElementVelocity ( player )
local vehicle = nil
if ( pvehicle ) then
local passengers = getVehicleOccupants ( pvehicle )
local x, y, z = getElementPosition ( pvehicle )
local rx, ry, rz = getVehicleRotation ( pvehicle )
local vx, vy, vz = getElementVelocity ( pvehicle )
destroyElement ( pvehicle )
vehicle = createVehicle ( id, x, y, z, rx, ry, rz )
local seats = getVehicleMaxPassengers ( vehicle )
for i, p in ipairs ( passengers ) do
if ( p ~= player ) then
local s = i - 1
if ( s <= seats ) then setTimer ( warpPedIntoVehicle, 500, 1, p, vehicle, s ) end
end
end
else
local x, y, z = getElementPosition ( player )
local r = getPedRotation ( player )
vehicle = createVehicle ( id, x, y, z, 0, 0, r )
end
setElementDimension ( vehicle, getElementDimension ( player ) )
setElementInterior ( vehicle, getElementInterior ( player ) )
warpPedIntoVehicle ( player, vehicle )
setElementVelocity ( vehicle, vx, vy, vz )
return true, getVehicleName ( vehicle )
end,
['giveweapon'] = function ( player, weapon, ammo )
if ( giveWeapon ( player, weapon, ammo, true ) ) then
return true, getWeaponNameFromID ( weapon ), ammo
end
return false
end,
['slap'] = function ( player, data )
if ( getElementHealth ( player ) > 0 ) and ( not isPedDead ( player ) ) then
local slap = tonumber ( data ) or 20
if ( slap > 0 ) then
if ( slap > getElementHealth ( player ) ) then setTimer ( killPed, 50, 1, player )
else setElementHealth ( player, getElementHealth ( player ) - slap ) end
end
local x, y, z = getElementVelocity ( player )
setElementVelocity ( player, x , y, z + 0.2 )
return true, slap
else
return false
end
end,
['getscreen'] = function ( player, quality )
getPlayerScreen ( player, source, quality )
end,
['wrap'] = function ( player )
warpPlayer ( source, player )
end,
['wrapto'] = function ( player, data )
warpPlayer ( player, data )
return true, getPlayerName ( data )
end
},
vehicle = {
['repair'] = function ( player, vehicle )
fixVehicle ( vehicle )
local rx, ry, rz = getVehicleRotation ( vehicle )
if ( rx > 110 ) and ( rx < 250 ) then
local x, y, z = getElementPosition ( vehicle )
setVehicleRotation ( vehicle, rx + 180, ry, rz )
setElementPosition ( vehicle, x, y, z + 2 )
end
end,
['customize'] = function ( player, vehicle, ... )
local data = { ... }
if ( data[1] == "remove" ) then
for id, upgrade in ipairs ( getVehicleUpgrades ( vehicle ) ) do
removeVehicleUpgrade ( vehicle, upgrade )
end
return "customizer"
else
local mdata = ""
for id, upgrade in ipairs ( data ) do
addVehicleUpgrade ( vehicle, upgrade )
if ( mdata == "" ) then mdata = tostring ( upgrade )
else mdata = mdata..", "..upgrade end
end
return true, mdata
end
end,
['setpaintjob'] = function ( player, vehicle, id )
if ( not setVehiclePaintjob ( vehicle, id ) ) then
outputChatBox ( "Invalid Paint job ID", source, 255, 0, 0 )
return false
end
return true, id
end,
['setcolor'] = function ( player, vehicle, ... )
local data = { ... }
for k, color in ipairs ( data ) do
local c = tonumber ( color )
if ( c ) then
if ( c < 0 ) or ( c > 126 ) then
return false
end
else
return false
end
end
if ( not setVehicleColor ( vehicle, tonumber(data[1]), tonumber(data[2]), tonumber(data[3]), tonumber(data[4]) ) ) then
return false
end
end,
['blowvehicle'] = function ( player, vehicle )
setTimer ( blowVehicle, 100, 1, vehicle )
end,
['destroyvehicle'] = function ( player, vehicle )
setTimer ( destroyElement, 100, 1, vehicle )
end
},
resource = {
['start'] = function ( resource )
startResource ( resource, true )
end,
['restart'] = function ( resource )
restartResource ( resource )
end,
['stop'] = function ( resource )
stopResource ( resource )
end,
['setsetting'] = function ( resource, setting, value )
if ( data and setting and value ) then
set ( '*'..getResourceName ( resource )..'.'..setting, value )
end
end
},
server = {
['setgame'] = function ( game )
if ( not setGameType ( tostring ( game ) ) ) then
outputChatBox ( "Error setting game type.", source, 255, 0, 0 )
return false
end
requestSync ( source, SYNC_SERVER )
return true, tostring ( game )
end,
['setmap'] = function ( map )
if ( not setMapName ( tostring ( map ) ) ) then
outputChatBox ( "Error setting map name.", source, 255, 0, 0 )
return false
end
requestSync ( source, SYNC_SERVER )
return true, tostring ( map )
end,
['settime'] = function ( minutes, seconds )
if ( not setTime ( tonumber ( minutes ), tonumber ( seconds ) ) ) then
outputChatBox ( "Error setting time.", source, 255, 0, 0 )
return false
end
return true, tostring ( minutes )..":"..tostring ( seconds )
end,
['setpassword'] = function ( password )
if ( not password or password == "" ) then
setServerPassword ( nil )
requestSync ( source, SYNC_SERVER )
return "resetpassword"
elseif ( string.len ( password ) > 32 ) then
outputChatBox ( "Set password: 32 characters max", source, 255, 0, 0 )
return false
elseif ( not setServerPassword ( password ) ) then
outputChatBox ( "Error setting password", source, 255, 0, 0 )
return false
end
requestSync ( source, SYNC_SERVER )
return true, password
end,
['setweather'] = function ( id )
if ( not setWeather ( tonumber ( id ) ) ) then
outputChatBox ( "Error setting weather.", source, 255, 0, 0 )
return false
end
return true, id.." "..getWeatherNameFromID ( tonumber ( id ) )
end,
['blendweather'] = function ( )
if ( not setWeatherBlended ( tonumber ( id ) ) ) then
outputChatBox ( "Error setting weather.", source, 255, 0, 0 )
return false
end
return true, id.." "..getWeatherNameFromID ( tonumber ( id ) )
end,
['setgamespeed'] = function ( speed )
if ( not setGameSpeed ( tonumber ( speed ) ) ) then
outputChatBox ( "Error setting game speed.", source, 255, 0, 0 )
return false
end
return true, speed
end,
['setgravity'] = function ( gravity )
if ( setGravity ( tonumber ( gravity ) ) ) then
for id, player in ipairs ( getElementsByType ( "player" ) ) do
setPedGravity ( player, getGravity() )
end
else
outputChatBox ( "Error setting gravity.", source, 255, 0, 0 )
return false
end
return true, gravity
end,
['setblurlevel'] = function ( level )
if ( not setBlurLevel ( level ) ) then
outputChatBox ( "Error setting blur level.", source, 255, 0, 0 )
return false
end
return true, level
end,
['setheathazelevel'] = function ( level )
if ( not setHeatHaze ( level ) ) then
outputChatBox ( "Error setting heat haze level.", source, 255, 0, 0 )
return false
end
return true, level
end,
['setwaveheight'] = function ( height )
if ( not setWaveHeight ( height ) ) then
outputChatBox ( "Error setting wave height.", source, 255, 0, 0 )
return false
end
return true, height
end,
['setfpslimit'] = function ( limit )
if ( not setFPSLimit ( limit ) ) then
outputChatBox ( "Error setting fps limit.", source, 255, 0, 0 )
return false
end
return true, limit
end,
['setworldproperty'] = function ( property, enabled )
if ( enabled ) then
local v = enabled == "on" or enabled == "enabled" or enabled == "true"
return setWorldSpecialPropertyEnabled ( property, v ), iif ( v, "enabled", "disabled" ), property
else
return false
end
end,
['setglitch'] = function ( glitch, enabled )
if ( enabled ) then
local v = enabled == "on" or enabled == "enabled" or enabled == "true"
return setGlitchEnabled ( glitch, v ), iif ( v, "enabled", "disabled" ), glitch
else
return false
end
end,
['shutdown'] = function ( reason )
shutdown ( iif ( reason, tostring ( reason ), nil ) )
end
},
admin = {
},
bans = {
}
} |
function connectMQTT(user, password, callback)
mqtt = mqtt.Client("jsf_pump", 1200, user, password) -- 20 min keepalive
mqtt:on("connect", function(con) print ("connected") end)
mqtt:on("offline", function(con)
print ("offline")
node.restart()
end)
-- on receive message
mqtt:on("message", function(conn, topic, data)
print('heap: '..tostring(node.heap()))
if data ~= nil then
print(topic .. ":" )
print(data)
if (topic == "wellSystem/tank_full") then
if data == "true" and autoMode then
turnOffPump()
end
lastMsgTime = tmr.now()
elseif (topic == "wellSystem/tank_empty") then
if data == "true" and autoMode then
turnOnPump()
end
lastMsgTime = tmr.now()
elseif (topic == "wellSystem/pump_on") then
if data == "true" then
turnOnPump()
tmr.alarm(4, pumpRuntime, 1, function()
turnOffPump()
end)
elseif data == "false" then
turnOffPump()
tmr.stop(4)
end
elseif (topic == "wellSystem/"..user.."/setting/pumpTimeout") then
pumpTimeout = tonumber(data)
save_setting('pumpTimeout', pumpTimeout)
mqtt:publish("wellSystem/"..user,"confirm pumpTimeout "..tostring(pumpTimeout), 0, 0, function(conn) end)
elseif (topic == "wellSystem/"..user.."/setting/pumpRuntime") then
pumpRuntime = tonumber(data)
save_setting('pumpRuntime', pumpRuntime)
mqtt:publish("wellSystem/"..user,"confirm pumpRuntime "..tostring(pumpRuntime), 0, 0, function(conn) end)
elseif (topic == "wellSystem/"..user.."/setting/autoMode") then
autoMode = set_auto(data)
if (not autoMode) then
turnOffPump()
end
save_setting('autoMode', tostring(autoMode))
mqtt:publish("wellSystem/"..user,"confirm autoMode "..tostring(autoMode), 0, 0, function(conn) end)
end
end
end)
mqtt:connect("m11.cloudmqtt.com", 19283, 0, function(conn)
print("connected")
mqtt:lwt("wellSystem/"..user, "offline", 0, 0)
-- subscribe all topics starting with wellSystem/ with qos = 0
mqtt:subscribe("wellSystem/#", 0, function(conn)
-- publish a message with data = my_message, QoS = 0, retain = 0
mqtt:publish("wellSystem/"..user,"online", 0, 0, function(conn)
print("sent")
callback()
end)
end)
end)
end
function turnOnPump()
gpio.write(relayPin, 0)
mqtt:publish("wellSystem/"..user,"pump on", 0, 0, function(conn) end)
end
function turnOffPump()
gpio.write(relayPin, 1)
mqtt:publish("wellSystem/"..user,"pump off", 0, 0, function(conn) end)
tmr.stop(4)
end
function controlPump()
print('starting pump control loop')
tmr.alarm(2, 1000, 1, function()
if (tmr.now() - lastMsgTime) > pumpTimeout then
turnOffPump()
end
if (wifi.sta.status() ~= 5) then
tmr.alarm(5, 5000, 0, function() node.restart() end)
else
tmr.stop(5)
end
end)
end
function save_setting(name,value)
file.open(name, 'w')
file.writeline(value)
file.close()
end
function read_setting(name)
file.open(name)
result = string.sub(file.readline(value), 1, -2) -- to remove newline character
file.close()
return result
end
function set_auto(auto)
if (auto == 'true') then
return true
else
return false
end
end
if file.open('wellpump_creds') then
user = string.sub(file.readline(), 1, -2)
password = string.sub(file.readline(), 1, -2)
well_full = true
well_empty = false
lastMsgTime = 0
-- setup settings
if file.open('pumpTimeout') then
file.close()
pumpTimeout = tonumber(read_setting('pumpTimeout'))
else
pumpTimeout = 11*60*1000*1000 -- 11 minute timeout, if no message recieved from water height, shut off pump
save_setting('pumpTimeout', pumpTimeout)
end
if file.open('pumpRuntime') then
file.close()
pumpRuntime = tonumber(read_setting('pumpRuntime'))
else
pumpRuntime = 15*60*1000*1000 -- 15 minute default pump runtime when manually turned on
save_setting('pumpRuntime', pumpRuntime)
end
if file.open('autoMode') then
file.close()
autoMode = set_auto(read_setting('autoMode'))
else
autoMode = true
save_setting('autoMode', tostring(autoMode))
end
connectMQTT(user, password, controlPump)
end
|
--
-- Copyright (C) 2022 Masatoshi Fukunaga
--
-- 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.
--
-- modules
local assert = assert
local find = string.find
local format = string.format
local open = io.open
local remove = os.remove
local rename = os.rename
local sub = string.sub
local type = type
local replace = require('string.replace')
local errno = require('errno')
local getcwd = require('getcwd')
local fstat = require('fstat')
local mkdir = require('mkdir')
local opendir = require('opendir')
local realpath = require('realpath')
local rmdir = require('rmdir')
local basename = require('basename')
-- constants
local ENOENT = errno.ENOENT.code
--- @class BaseDir
--- @field basedir string
--- @field follow_symlink boolean
local BaseDir = {}
BaseDir.__index = BaseDir
--- normalize
--- @param pathname string
--- @return string rpath
function BaseDir:normalize(pathname)
return assert(realpath('/' .. pathname, nil, false))
end
--- dirname
--- @param pathname string
--- @return string dirname
--- @return string filename
function BaseDir:dirname(pathname)
local rpath = self:normalize(pathname)
local filename = basename(rpath)
-- filename does not exists
if filename == '/' then
return rpath, ''
end
-- extract dirname
local dlen = #rpath - #filename
-- remove trailing-slash from dirname
if dlen > 1 then
dlen = dlen - 1
end
return sub(rpath, 1, dlen), filename
end
--- realpath
--- @param pathname string
--- @return string apath
--- @return string err
--- @return string rpath
function BaseDir:realpath(pathname)
local base = self.basedir
local blen = #base
local rpath = self:normalize(pathname)
local apath, err, eno = realpath(base .. rpath)
if err then
if eno == ENOENT then
return nil
end
return nil, err
elseif not self.follow_symlink and
(sub(apath, 1, blen) ~= base or #apath > blen and
sub(apath, blen + 1, blen + 1) ~= '/') then
-- absolute path is not placed at the base directory
return nil
end
return apath, nil, rpath
end
--- stat
--- @param pathname string
--- @return table<string, any> stat
--- @return string err
function BaseDir:stat(pathname)
-- convert relative-path to absolute-path
local apath, err, rpath = self:realpath(pathname)
if not apath then
return nil, err
end
local stat, eno
stat, err, eno = fstat(apath, false)
if err then
if eno == ENOENT then
return nil
end
return nil, format('failed to stat: %s - %s', rpath, err)
end
-- append absolute paths
stat.pathname = apath
stat.rpath = rpath
return stat
end
--- remove
--- @param pathanme string
--- @return boolean ok
--- @return string err
function BaseDir:remove(pathanme)
local rpath = self.basedir .. self:normalize(pathanme)
local ok, err = remove(rpath)
if not ok then
return false, replace(err, self.basedir)
end
return true
end
--- rename
--- @param oldpath string
--- @param newpath string
--- @return boolean ok
--- @return string err
function BaseDir:rename(oldpath, newpath)
local base = self.basedir
oldpath = base .. self:normalize(oldpath)
newpath = base .. self:normalize(newpath)
local ok, err = rename(oldpath, newpath)
if not ok then
return false, err
end
return true
end
--- put
--- @param extpath string
--- @param newpath string
--- @return boolean ok
--- @return string err
function BaseDir:put(extpath, newpath)
newpath = self.basedir .. self:normalize(newpath)
local ok, err = rename(extpath, newpath)
if not ok then
return false, err
end
return true
end
--- open
--- @param pathname string
--- @param mode? string
--- @return file* f
--- @return string err
function BaseDir:open(pathname, mode)
if mode == nil then
mode = 'r'
elseif type(mode) ~= 'string' then
error('mode must be string', 2)
end
local apath, err = self:realpath(pathname)
if not apath then
-- got error or mode is not creation mode
if err or not find(mode, '^[wa]') then
return nil, err
end
local dirpath, filename = self:dirname(pathname)
apath, err = self:realpath(dirpath)
if not apath then
return nil, err
end
apath = apath .. '/' .. filename
end
return open(apath, mode)
end
--- read
--- @param pathname string
--- @return string content
--- @return string err
function BaseDir:read(pathname)
local f, ferr = self:open(pathname)
if not f then
return nil, ferr
end
local src, err = f:read('*a')
f:close()
if err then
return nil, err
end
return src
end
--- rmdir
--- @param pathname string
--- @param recursive? boolean
--- @return boolean ok
--- @return string err
function BaseDir:rmdir(pathname, recursive)
local apath = self.basedir .. self:normalize(pathname)
return rmdir(apath, recursive)
end
--- mkdir
--- @param pathname string
--- @param mode string|integer
--- @return boolean ok
--- @return string err
--- @return integer errno
function BaseDir:mkdir(pathname, mode)
local apath = self.basedir .. self:normalize(pathname)
return mkdir(apath, mode, true, self.follow_symlink)
end
--- opendir
--- @param pathname string
--- @return userdata dir
--- @return string err
function BaseDir:opendir(pathname)
local apath = self.basedir .. self:normalize(pathname)
local dir, derr, eno = opendir(apath, self.follow_symlink)
if dir then
return dir
elseif eno ~= ENOENT then
return nil, format('failed to opendir %s: %s', pathname, derr)
end
end
--- readdir
--- @param pathname string
--- @return string[] entries
--- @return string err
function BaseDir:readdir(pathname)
local dir, err = self:opendir(pathname)
if not dir then
return nil, err
end
local list = {}
local entry
entry, err = dir:readdir()
while entry do
-- ignore '.' and '..' entries
if entry ~= '.' and entry ~= '..' then
list[#list + 1] = entry
end
entry, err = dir:readdir()
end
dir:closedir()
-- failed to readdir
if err then
return nil, format('failed to readdir %s: %s', pathname, err)
end
return list
end
--- new
--- @param pathname string
--- @param follow_symlink? boolean
--- @return BaseDir
local function new(pathname, follow_symlink)
if type(pathname) ~= 'string' then
error('pathname must be string')
elseif follow_symlink ~= nil and type(follow_symlink) ~= 'boolean' then
error('follow_symlink must be boolean')
end
local basedir = pathname
if sub(basedir, 1, 1) ~= '/' then
-- prepend current working direcotry
basedir = getcwd() .. '/' .. basedir
end
-- normalize
basedir = assert(realpath(basedir, nil, false))
-- resolve pathname
follow_symlink = follow_symlink == true
if follow_symlink then
local err
basedir, err = realpath(basedir)
if err then
error(format('failed to access the pathname %q: %s', pathname, err))
end
end
-- check type of entry
local stat, err = fstat(basedir, follow_symlink)
if err then
error(format('failed to get stat %q: %s', pathname, err))
elseif stat.type ~= 'directory' then
error(format('pathname %q is not directory', pathname))
end
return setmetatable({
basedir = basedir,
follow_symlink = follow_symlink,
}, BaseDir)
end
return {
new = new,
}
|
--ELF·莉莉
function c1190005.initial_effect(c)
--
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_GRAVE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetCountLimit(1,1190005)
e1:SetCondition(c1190005.con1)
e1:SetTarget(c1190005.tg1)
e1:SetOperation(c1190005.op1)
c:RegisterEffect(e1)
--
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetCountLimit(1,1190055)
e2:SetRange(LOCATION_MZONE)
e2:SetTarget(c1190005.tg2)
e2:SetOperation(c1190005.op2)
c:RegisterEffect(e2)
end
--
c1190005.named_with_ELF=1
function c1190005.IsELF(c)
local m=_G["c"..c:GetCode()]
return m and m.named_with_ELF
end
--
function c1190005.cfilter(c)
return c:IsFaceup() and c1190005.IsELF(c) and c:IsLevelAbove(3)
end
function c1190005.con1(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(c1190005.cfilter,tp,LOCATION_MZONE,0,1,nil)
end
--
function c1190005.tg1(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chk==0 then return Duel.IsExistingMatchingCard(c1190005.cfilter,tp,LOCATION_MZONE,0,1,nil) and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
--
function c1190005.op1(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)~=0 then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_LEAVE_FIELD_REDIRECT)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetReset(RESET_EVENT+0x47e0000)
e1:SetValue(LOCATION_DECK)
c:RegisterEffect(e1,true)
end
end
--
function c1190005.filter2(c,e,tp)
return c:IsType(TYPE_MONSTER)
end
function c1190005.tg2(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(1-tp) and c1190005.filter2(chkc,e,tp) and chkc:IsLocation(LOCATION_MZONE) end
if chk==0 then return Duel.IsExistingTarget(c1190003.filter2,tp,0,LOCATION_MZONE,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
local g=Duel.SelectTarget(tp,c1190005.filter2,tp,0,LOCATION_MZONE,1,1,nil,e,tp)
Duel.HintSelection(g)
-- Duel.SetOperationInfo(0,CATEGORY_,g,1,0,0)
end
function c1190005.op2(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_SET_AVAILABLE+EFFECT_FLAG_IGNORE_RANGE)
e1:SetCode(EFFECT_FORBIDDEN)
e1:SetTarget(c1190005.bantg)
e1:SetLabelObject(tc)
e1:SetReset(RESET_PHASE+PHASE_END+RESET_OPPO_TURN)
Duel.RegisterEffect(e1,tp)
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_DISABLE)
e2:SetTargetRange(0,LOCATION_MZONE)
e2:SetTarget(c1190005.bantg)
e2:SetLabelObject(tc)
e2:SetReset(RESET_PHASE+PHASE_END+RESET_OPPO_TURN)
Duel.RegisterEffect(e2,tp)
end
end
function c1190005.bantg(e,c)
return c==e:GetLabelObject()
end
|
---------------------------------------------------------------------------------------------
-- Requirement summary:
-- [Policies] <device identifier>. User clears all these applications
--
-- Description:
-- All applications from new device are successfully registered AND the User clears all these applications from the list of registered applications
-- 1. Used preconditions:
-- Delete files and policy table from previous ignition cycle if any
-- Connect new device
-- Register App1
-- Register App2
-- Unregister App1
-- Unregister App2
--
-- 2. Performed steps:
-- Connect second device
--
-- Expected result:
-- Device must be still visible by SDL and must NOT be removed from HMI`s list of connected devices:
-- SDL->HMI: BC.UpdateDeviceList(device1, device2)
-- HMI->SDL: BC.UpdateDeviceList(SUCCESS)
--------------------------------------------------------------------------------------------------------
if config.defaultMobileAdapterType == "WS" or config.defaultMobileAdapterType == "WSS" then
require('user_modules/script_runner').skipTest("Test is not applicable for WS/WSS connection")
end
require('user_modules/script_runner').isTestApplicable({ { extendedPolicy = { "EXTERNAL_PROPRIETARY" } } })
--[[ Required Shared libraries ]]
local actions = require("user_modules/sequences/actions")
local utils = require("user_modules/utils")
local common = require('test_scripts/Capabilities/PersistingHMICapabilities/common')
local SDL = require('SDL')
--[[ Local Variables ]]
local anotherDeviceParams = { host = "1.0.0.1", port = config.mobilePort }
local anotherDeviceName = anotherDeviceParams.host .. ":" .. anotherDeviceParams.port
--[[ Local Functions ]]
local function connectDeviceTwo()
local weDevice = { transportType = "WEBENGINE_WEBSOCKET" }
local devices = {
{
name = anotherDeviceName,
isSDLAllowed = false,
transportType = "WIFI"
},
{
name = utils.getDeviceName(),
transportType = utils.getDeviceTransportType()
}
}
if SDL.buildOptions.webSocketServerSupport == "ON" then
table.insert(devices, 1, weDevice)
end
EXPECT_HMICALL("BasicCommunication.UpdateDeviceList", { deviceList = devices })
:Do(function(_,data)
actions.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {})
end)
utils.addNetworkInterface(2, anotherDeviceParams.host)
actions.mobile.createConnection(2, anotherDeviceParams.host, anotherDeviceParams.port)
actions.mobile.connect(2)
end
--[[ Scenario ]]
common.Title("Preconditions")
common.Step("Clean environment", common.preconditions)
common.Step("Start SDL, HMI", actions.start)
common.Step("Register App1", actions.registerAppWOPTU, { 1 })
common.Step("Register App2", actions.registerAppWOPTU, { 2 })
common.Step("Unregister App1", actions.app.unRegister, { 1 })
common.Step("Unregister App2", actions.app.unRegister, { 2 })
common.Title("Test")
common.Step("Connect another mobile device, verify device list", connectDeviceTwo)
common.Title("Postconditions")
common.Step("Stop SDL", common.postconditions)
|
-- See LICENSE for terms
local default_InstantPassages = 0
local default_NonHomeDomePerformancePenalty = 10
local default_NonHomeDomeServiceThresholdDecrement = 10000
function OnMsg.ClassesPostprocess()
default_InstantPassages = Consts.InstantPassages
default_NonHomeDomePerformancePenalty = Consts.NonHomeDomePerformancePenalty
default_NonHomeDomeServiceThresholdDecrement = Consts.NonHomeDomeServiceThresholdDecrement
end
--~ local SetConsts = ChoGGi.ComFuncs.SetConstsG
local function SetConsts(id, value)
Consts[id] = value
g_Consts[id] = value
end
local mod_EnableMod
local mod_InstantPassages
local function SetOptions()
if mod_EnableMod then
if mod_InstantPassages then
SetConsts("InstantPassages", 1)
else
SetConsts("InstantPassages", default_InstantPassages)
end
SetConsts("NonHomeDomePerformancePenalty", 0)
SetConsts("NonHomeDomeServiceThresholdDecrement", 0)
else
SetConsts("InstantPassages", default_InstantPassages)
SetConsts("NonHomeDomePerformancePenalty", default_NonHomeDomePerformancePenalty)
SetConsts("NonHomeDomeServiceThresholdDecrement", default_NonHomeDomeServiceThresholdDecrement)
end
end
-- fired when settings are changed/init
local function ModOptions()
mod_EnableMod = CurrentModOptions:GetProperty("EnableMod")
mod_InstantPassages = CurrentModOptions:GetProperty("InstantPassages")
-- make sure we're ingame
if not UICity then
return
end
SetOptions()
end
-- load default/saved settings
OnMsg.ModsReloaded = ModOptions
-- fired when Mod Options>Apply button is clicked
function OnMsg.ApplyModOptions(id)
if id == CurrentModId then
ModOptions()
end
end
OnMsg.CityStart = SetOptions
OnMsg.LoadGame = SetOptions
|
local composer = require( "composer" )
local scene = composer.newScene()
local score = require( "score" )
---------------------------------------------------------------------------------
-- All code outside of the listener functions will only be executed ONCE
-- unless "composer.removeScene()" is called.
---------------------------------------------------------------------------------
-- local forward references should go here
---------------------------------------------------------------------------------
display.setStatusBar(display.HiddenStatusBar)
local bg
local title
local button
flag = "GameTwo"
local function gotoSceneMap()
composer.gotoScene("Map", {time=800, effect="fromBottom"})
end
local function gotoSceneSettings()
composer.gotoScene("Settings")
flag = "GameTwo"
end
-- "scene:create
function scene:create( event )
local sceneGroup = self.view
background = display.newImage("background/hospital.png", display.contentCenterX, display.contentCenterY)
sceneGroup:insert(background)
title = display.newText("Gameplay 2", display.contentCenterX, display.contentCenterY - 300, "SFAutomaton", 40)
title:setFillColor(1,0,0)
sceneGroup:insert(title)
buttonMap = display.newRoundedRect( display.contentCenterX, display.contentHeight*.8, display.contentHeight*.2, display.contentCenterY*.5, 20)
buttonMap:setFillColor(1,0,0)
sceneGroup:insert(buttonMap)
buttonSettings = display.newImage("buttons/circle.png", display.contentWidth*.925, display.contentHeight*.1)
buttonSettings.xScale, buttonSettings.yScale = 7, 7
sceneGroup:insert(buttonSettings)
--buttonTest = display.newRect(display.contentCenterX, display.contentCenterY, 100, 100)
buttonMap:addEventListener("tap", gotoSceneMap)
buttonSettings:addEventListener("tap", gotoSceneSettings)
----- Sprite Towers ------
local objectSheet = require("explosionSprite")
local explosionSheet = graphics.newImageSheet("towers/explosion.png", objectSheet:getSheet())
explosion1 = display.newSprite(explosionSheet, objectSheet:getSequences())
explosion1.x, explosion1.y = display.contentCenterX - 500, display.contentCenterY
--explosion1.xScale, explosion1.yScale = 1.25, 1.25
sceneGroup:insert(explosion1)
local objectSheet = require("susanSprite")
local susanSheet = graphics.newImageSheet("towers/susan.png", objectSheet:getSheet())
susan = display.newSprite(susanSheet, objectSheet:getSequences())
susan.x, susan.y = display.contentCenterX - 250, display.contentCenterY
--susan.xScale, susan.yScale = 1.75, 1.75
sceneGroup:insert(susan)
local objectSheet = require("junkieSprite")
local junkieSheet = graphics.newImageSheet("towers/junkie.png", objectSheet:getSheet())
junkie = display.newSprite(junkieSheet, objectSheet:getSequences())
junkie.x, junkie.y = display.contentCenterX, display.contentCenterY
--junkie.xScale, junkie.yScale = 1, 1.50
sceneGroup:insert(junkie)
local objectSheet = require("pharmabobSprite")
local pharmabobSheet = graphics.newImageSheet("towers/pharmabob.png", objectSheet:getSheet())
pharmabob = display.newSprite(pharmabobSheet, objectSheet:getSequences())
pharmabob.x, pharmabob.y = display.contentCenterX + 250, display.contentCenterY
--pharmabob.xScale, pharmabob.yScale = 1.50, 1.50
sceneGroup:insert(pharmabob)
----- scoring -----
local scoreText = score.init(
{
fontSize = 20,
font = "CoolCustomFont.ttf",
x = display.contentCenterX,
y = 30,
maxDigits = 7,
leadingZeros = true
})
-- Initialize the scene here.
-- Example: add display objects to "sceneGroup", add touch listeners, etc.
end
-- "scene:show()"
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
if ( phase == "will" ) then
-- Called when the scene is still off screen (but is about to come on screen).
elseif ( phase == "did" ) then
local function explode1(event)
explosion1:setSequence("explode")
explosion1:play()
end
susanStatus = 0
junkieStatus = 0
pharmabobStatus = 0
local function susanActions(event)
if susanStatus == 0 then
susan:setSequence("idle")
susan:play()
susanStatus = 1
elseif susanStatus == 1 then
susan:setSequence("moneymaking")
susan:play()
susanStatus = 0
end
end
local function junkieActions(event)
if junkieStatus == 0 then
junkie:setSequence("arrival")
junkie:play()
junkieStatus = 1
elseif junkieStatus == 1 then
junkie:setSequence("damaged")
junkie:play()
junkieStatus = 2
elseif junkieStatus == 2 then
junkie:setSequence("final")
junkie:play()
junkieStatus = 0
end
end
local function pharmabobActions(event)
if pharmabobStatus == 0 then
pharmabob:setSequence("idle")
pharmabob:play()
pharmabobStatus = 1
elseif pharmabobStatus == 1 then
pharmabob:setSequence("shooting")
pharmabob:play()
pharmabobStatus = 0
end
end
-- local function walkingMonster4(event)
-- monster4:setSequence("walking")
-- monster4:play()
-- end
-- local function walkingMonster5(event)
-- monster5:setSequence("walking")
-- monster5:play()
-- end
explosion1:addEventListener("tap", explode1)
susan:addEventListener("tap", susanActions)
junkie:addEventListener("tap", junkieActions)
pharmabob:addEventListener("tap", pharmabobActions)
-- monster3:addEventListener("tap", walkingMonster3)
-- monster4:addEventListener("tap", walkingMonster4)
-- monster5:addEventListener("tap", walkingMonster5)
-- Called when the scene is now on screen.
-- Insert code here to make the scene come alive.
-- Example: start timers, begin animation, play audio, etc.
end
end
-- "scene:hide()"
function scene:hide( event )
local sceneGroup = self.view
local phase = event.phase
if ( phase == "will" ) then
explosion1:pause()
junkie:pause()
susan:pause()
pharmabob:pause()
elseif ( phase == "did" ) then
-- Called immediately after scene goes off screen.
end
end
-- "scene:destroy()"
function scene:destroy( event )
local sceneGroup = self.view
-- Called prior to the removal of scene's view ("sceneGroup").
-- Insert code here to clean up the scene.
-- Example: remove display objects, save state, etc.
end
---------------------------------------------------------------------------------
-- Listener setup
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )
---------------------------------------------------------------------------------
return scene
|
require 'funcs'
local GameMode = require 'tetris.modes.gamemode'
local Piece = require 'tetris.components.piece'
local History4RollsRandomizer = require 'tetris.randomizers.history_4rolls'
local MarathonA1Game = GameMode:extend()
MarathonA1Game.name = "Marathon A1"
MarathonA1Game.hash = "MarathonA1"
MarathonA1Game.tagline = "Can you score enough points to reach the title of Grand Master?"
function MarathonA1Game:new()
MarathonA1Game.super:new()
self.roll_frames = 0
self.combo = 1
self.gm_conditions = {
level300 = false,
level500 = false,
level999 = false
}
self.randomizer = History4RollsRandomizer()
self.lock_drop = false
self.enable_hard_drop = false
self.enable_hold = false
self.next_queue_length = 1
end
function MarathonA1Game:getARE()
return 30
end
function MarathonA1Game:getLineARE()
return 27
end
function MarathonA1Game:getDasLimit()
return 15
end
function MarathonA1Game:getLineClearDelay()
return 44
end
function MarathonA1Game:getLockDelay()
return 30
end
local function getRankForScore(score)
if score < 400 then return {rank = "9", next = 400}
elseif score < 800 then return {rank = "8", next = 800}
elseif score < 1400 then return {rank = "7", next = 1400}
elseif score < 2000 then return {rank = "6", next = 2000}
elseif score < 3500 then return {rank = "5", next = 3500}
elseif score < 5500 then return {rank = "4", next = 5500}
elseif score < 8000 then return {rank = "3", next = 8000}
elseif score < 12000 then return {rank = "2", next = 12000}
elseif score < 16000 then return {rank = "1", next = 16000}
elseif score < 22000 then return {rank = "S1", next = 22000}
elseif score < 30000 then return {rank = "S2", next = 30000}
elseif score < 40000 then return {rank = "S3", next = 40000}
elseif score < 52000 then return {rank = "S4", next = 52000}
elseif score < 66000 then return {rank = "S5", next = 66000}
elseif score < 82000 then return {rank = "S6", next = 82000}
elseif score < 100000 then return {rank = "S7", next = 100000}
elseif score < 120000 then return {rank = "S8", next = 120000}
else return {rank = "S9", next = "???"}
end
end
function MarathonA1Game:getGravity()
local level = self.level
if (level < 30) then return 4/256
elseif (level < 35) then return 6/256
elseif (level < 40) then return 8/256
elseif (level < 50) then return 10/256
elseif (level < 60) then return 12/256
elseif (level < 70) then return 16/256
elseif (level < 80) then return 32/256
elseif (level < 90) then return 48/256
elseif (level < 100) then return 64/256
elseif (level < 120) then return 80/256
elseif (level < 140) then return 96/256
elseif (level < 160) then return 112/256
elseif (level < 170) then return 128/256
elseif (level < 200) then return 144/256
elseif (level < 220) then return 4/256
elseif (level < 230) then return 32/256
elseif (level < 233) then return 64/256
elseif (level < 236) then return 96/256
elseif (level < 239) then return 128/256
elseif (level < 243) then return 160/256
elseif (level < 247) then return 192/256
elseif (level < 251) then return 224/256
elseif (level < 300) then return 1
elseif (level < 330) then return 2
elseif (level < 360) then return 3
elseif (level < 400) then return 4
elseif (level < 420) then return 5
elseif (level < 450) then return 4
elseif (level < 500) then return 3
else return 20
end
end
function MarathonA1Game:advanceOneFrame()
if self.clear then
self.roll_frames = self.roll_frames + 1
if self.roll_frames > 2968 then
self.completed = true
end
elseif self.ready_frames == 0 then
self.frames = self.frames + 1
end
return true
end
function MarathonA1Game:onPieceEnter()
if (self.level % 100 ~= 99 and self.level ~= 998) and not self.clear and self.frames ~= 0 then
self.level = self.level + 1
end
end
function MarathonA1Game:onLineClear(cleared_row_count)
self:checkGMRequirements(self.level, self.level + cleared_row_count)
if not self.clear then
local new_level = math.min(self.level + cleared_row_count, 999)
if new_level == 999 then
self.level = 999
self.clear = true
else
self.level = new_level
end
end
end
function MarathonA1Game:updateScore(level, drop_bonus, cleared_lines)
if self.clear then return end
if cleared_lines > 0 then
self.combo = self.combo + (cleared_lines - 1) * 2
self.score = self.score + (
(math.ceil((level + cleared_lines) / 4) + drop_bonus) *
cleared_lines * self.combo
)
self.lines = self.lines + cleared_lines
else
self.drop_bonus = 0
self.combo = 1
end
end
function MarathonA1Game:checkGMRequirements(old_level, new_level)
if old_level < 300 and new_level >= 300 then
if self.score > 12000 and self.frames <= sp(4,15) then
self.gm_conditions["level300"] = true
end
elseif old_level < 500 and new_level >= 500 then
if self.score > 40000 and self.frames <= sp(7,30) then
self.gm_conditions["level500"] = true
end
elseif old_level < 999 and new_level >= 999 then
if self.score > 126000 and self.frames <= sp(13,30) then
self.gm_conditions["level900"] = true
end
end
end
function MarathonA1Game:drawGrid()
self.grid:draw()
if self.piece ~= nil and self.level < 100 then
self:drawGhostPiece(ruleset)
end
end
function MarathonA1Game:drawScoringInfo()
MarathonA1Game.super.drawScoringInfo(self)
love.graphics.setColor(1, 1, 1, 1)
love.graphics.setFont(font_3x5_2)
love.graphics.print(
self.das.direction .. " " ..
self.das.frames .. " " ..
st(self.prev_inputs)
)
love.graphics.printf("NEXT", 64, 40, 40, "left")
love.graphics.printf("GRADE", 240, 120, 40, "left")
love.graphics.printf("SCORE", 240, 200, 40, "left")
love.graphics.printf("NEXT RANK", 240, 260, 90, "left")
love.graphics.printf("LEVEL", 240, 320, 40, "left")
love.graphics.setFont(font_3x5_3)
love.graphics.printf(self.score, 240, 220, 90, "left")
if self.gm_conditions["level300"] and self.gm_conditions["level500"] and self.gm_conditions["level900"] then
love.graphics.printf("GM", 240, 140, 90, "left")
else
love.graphics.printf(getRankForScore(self.score).rank, 240, 140, 90, "left")
end
love.graphics.printf(getRankForScore(self.score).next, 240, 280, 90, "left")
love.graphics.printf(self.level, 240, 340, 40, "right")
love.graphics.printf(self:getSectionEndLevel(), 240, 370, 40, "right")
love.graphics.setFont(font_8x11)
love.graphics.printf(formatTime(self.frames), 64, 420, 160, "center")
end
function MarathonA1Game:getSectionEndLevel()
if self.level >= 900 then return 999
else return math.floor(self.level / 100 + 1) * 100 end
end
function MarathonA1Game:getBackground()
return math.floor(self.level / 100)
end
function MarathonA1Game:getHighscoreData()
return {
grade = self.grade,
score = self.score,
level = self.level,
frames = self.frames,
}
end
return MarathonA1Game
|
local Criterion = torch.class('nn.Criterion')
function Criterion:__init()
self.gradInput = torch.Tensor()
self.output = 0
end
function Criterion:forward(input, target)
end
function Criterion:backward(input, target)
end
function Criterion:write(file)
file:writeObject(self.gradInput)
file:writeDouble(self.output)
end
function Criterion:read(file)
self.gradInput = file:readObject()
self.output = file:readDouble()
end
|
--
-- Created by IntelliJ IDEA.
-- User: chen0
-- Date: 25/7/2017
-- Time: 9:29 AM
-- To change this template use File | Settings | File Templates.
--
local StronglyConnectedComponents = {}
StronglyConnectedComponents.__index = StronglyConnectedComponents
function StronglyConnectedComponents.create()
local s = {}
setmetatable(s, StronglyConnectedComponents)
s.id = {}
s.marked = {}
s.count = 0
return s
end
function StronglyConnectedComponents:run(G)
self.marked = {}
self.id = {}
self.count = 0
for i = 0,G:vertexCount()-1 do
local v = G:vertexAt(i)
self.marked[v] = false
self.id[v] = -1
end
local g_prime = G:reverse()
local topo_sort = require('luagraphs.sort.TopologicalSort').create()
topo_sort:run(g_prime)
local order = topo_sort:path()
for i=0,order:size()-1 do
local v = order:get(i)
if self.marked[v] == false then
self:dfs(G, v)
self.count = self.count + 1
end
end
end
function StronglyConnectedComponents:dfs(G, v)
local adj_v = G:adj(v)
self.marked[v] = true
self.id[v] = self.count
for i=0,adj_v:size()-1 do
local e = adj_v:get(i)
local w = e:other(v)
if self.marked[w] == false then
self:dfs(G, w)
end
end
end
function StronglyConnectedComponents:component(v)
return self.id[v]
end
return StronglyConnectedComponents
|
local formStringClass = '<?xml version="1.0" encoding="utf-8"?><FormData><formMonoClass Class="TCEForm" Encoding="Ascii85">/yXy*/3td4;=F41+]S%7-9[S)8wjBhaO9R]HoK7}lMsjH2I_C;q!qi^+qxopm3Kfq!%Dma2hhF)$K_poB)7+L@pD3sNsL0}z:4a=UG;#ZcYR(mdDGOi$+A_KIq5#[)I_K?:br(3wCkfdu3o^M89!9((jBx%%y=iJ6B-(nYPGMi$Ck#Es?X+$!/5u))%[]*V/0Sn_D]*;euu6OfUHd].NJnlM6-C+D;Mba;5H#*ag73a,$OUnja:-3$l#)(35%$2*]m9)qDPsQXS1c0DeH_SWBsv6SZ@fxzSYh.H1Z(FLo}x:aiPGcMWM7v7xqZ)MoXslMXSwNgr^o.Cp^kZqPs,q3)P!eU%UNpyU+KW[vyruswDm(ww#GY*tx=;Q4(*hG1QRa5oWWcY0kqQz6DSD^Bn)a%r.#5-DQO4Od)yi?xiIj._{#b%@9JHZ*:zOG[o3MB4Cy#w^)OE[.x71Vw.cJ(8;:?6.a}Xv^4+(C{T8ul4-_c+.@sbx7Azb=]L]=C^HobZ#gIy-FU6bs),YN-Kd)%LG0Afifig/B?9folId7zrQ96Oj*z5:bfY*Ui(Et?N2RPJ#dGqycutI{H9@y%aHVVJ3moIA50;We%DN%v27{1ShM%cJ]g=jve@slmsMYH:O/F#S:sN7sTYE7b09#ToIoxkc=2HfeTHD79Vp[.o+]?0,6AxLMm0{QUG3^aSlNfqgh(PoaL;;9EAa=:k$}yC{Yns-S%w9mk4J,j1_0TVDQM;qYO7BK^#[(rJn]2rGO_L0}[]l]6C_#d.aI5Qime;/MahCwh:6R_rZ($r_HhwCejdzA5,7+u33k*_6pAVE-84a;PB}-](rFG6A$Jcsq9^+Htt*6aytoPle][4GDv=jkG*(Yr_m28iP@LY%,8epQ?!$)P+xX=0Cb,QRz2V)rJ/uT(e;_$D#97eqf5;21=2wU;}lHY%{H3sAjiNCS!F{-oYhZ)bTea^x/mA9U0y@O}Y)unaUkP*cC[cQ53JB^hzP^/J!O6/xwl#5kDq8y?;MLEpzG{?oaK_K1#DDbFRy$6rB%Kv%d@S3-j#KVN6[#GARBEK(s$_psl+drRQL-{w#3Dr/tKKCV1*,y68/g]ehS3BepPvrpw*DHMZT9nZyjZi_GR9^M(6mdLZ[9bx.U0xmAb]E[T_9Stnaqj7xE4^[p.4(2P#n@m!1!TdQr*jeM.;jS]l;H0gGCu4x2/!k4B@7clB?yIMX90FOnK}QE,8(PL=B)*MXj,_)]oqwYN-bx5u58ss)AlVNY]52pc9$=*,1cL=:{6()KZVS?dXKwW)wjb6LWCK3]?Ed.ZS}h4v^F;wgQGlr74wI}KI=_iwxn9i,tma7j53-v12HRRCM29L5Hn7g;.asL@6pL+^1W0B5DyWS88_tiC_[fec7sAQFo#4c%,tJ7in!I@</formMonoClass></FormData>'
local formStringImage = '<?xml version="1.0" encoding="utf-8"?><FormData><formMonoImage Class="TCEForm" Encoding="Ascii85">#goBu):ZT+Wtl^dlQI).N^(5n(hQF{X^MQJn@1eo5fn$ZHIXe;RtGr4190F.cqtCN1hVAXjWcD*0l3*K^?z^hx4+qE0Ksbh3I+QToQw1+QkP4f?kNSb@5lX/)jLR@IiYbP=eCTy?ZA0ZI(bMlCiZ8DJe+6*v,mF+jD,(E%sth}1CLRX$vU-f(i9$XRV@:QA!q!f%hX+b6)]dyOt_prhLp]G9=zuU40V/tG9sQgs]],Y[?WW7%bqQH*RxO9*We0CaVdE@Zgdl/@M}s?b/WI$4H*R(bICOq:vG*bM5b2J?8GRcx[DbAAiUL]9lSLiz[S=[8zTH1hct@Prs^Avs4E{u#(j9zj(]G[D0JP0B(qo^2%G=}m+ra!0MJv,XL@_ZnSM_HxTV)cJhf9I9+4KLxJqx*H(z;36.k,8JMD^Qkiz#h)TZim?DT^LGY6G3@@j/pDI11cbh0/UjyJR^0G:vZE5TzyieiSvQC;a(0j_I1#Y1q]28AO^@P9DA)8H^GkPRD[5Z%y%t^HKF?{v6g?tUv!E3cP_:l]R+yV4f4v4-{wf!3Qc8fU38JaQy9#^U-{8!JCVHkhj,CSHPtPb3.lul(V3=_gdgp9Os[Rb%_?;C,WXNw,f/6f.*]R#b*wa-.kPtDstrDfs3NGb%qJ6y3fSIFkJp7HU$DGcFw09Lg7,2RjA700</formMonoImage></FormData>'
local formStringSearch = '<?xml version="1.0" encoding="utf-8"?><FormData><formMonoSearch Class="TCEForm" Encoding="Ascii85">%}#KF,cp%Yq+#;fF0-;[=QS^sGN4#^E)+k6vj(Lgz(5foZ80]sniM43Np}sshx8vPu*}UB$D$ZEpujG;?1GedO3?FSj[d9*9_ZEf$H%Addmm}2)+$66arzA$cAlT_Xuf_XA6=G*0HbI.-8.uu!g/qhUtlts3g:JT8S;Ei8Pt9tftWhe8tkA?5YF5@wd!7n63j#z^fphu@DKC.i]fEtbNTEd!oa?V@#V/Bhcgjz;V/Nw9ABQW?svjc5?1!pqtp+.y:#V{queWtsW_WF(b{)5.y$dp*d;11j?n!ZK7Ww:wZXi1;aQe75VPwUV6PLv=0SmVuvR{A3$n!Ot*VZ[NaGB3,PG0eGa2uqnMwoEEGg1MGo2h9w0RWZXb[==VUtICuU6TZ=Ds_4mZY*khh=iyYS,CX8lABK-]GG6dn)2Tz#q!VV2ZIQ6q=cP;Uo+*pUQ-v+MRD*:K(G;SU(WUA-*kNg7b_GB/BHTpzZr5od4b*DX,(mQ@X]4hvgczwE(1Wz.qx]By8Zz.W:g#F__QU1-}FnoXQ$Iobm_5F;O.co_Rk!?seWbUd3%r10a!Bz0WXhgzBmH-5Hk)z6a%}N^/;fl5exSPS%#XNh:]J%B9xI+R]yBwpGPCTI,4R#Pp0w%_dUq;=0E6KpT4tA(qdfR15HJM.Cc0xAkSUt?Ea@KtuBQUBnk+o8NpsQ3IVqm1=51xRrs;Vu,EiV$kl48LHXD8O%8AYtHPHvp:lb2[,K-T_@VEG6umd%(/dI9OJkQ?v{0-?2%oNq#!.gvA87ox/%zc+P13Wfm_iS0CY9X2zE7acfdDPwv_wxY0$Gv[]S8QP?p]X7IPNwTeo!76BLiXM_13T)T(b^=08,mlCd46yF9SujgZ]d-y)s0ua8mCWAvr)[xZIv4*Iv^1:4(*mOk;lW!%RhkA(M{YArlk.ZT_D)mSHE3(u0{*oMiQ0:gXrAtge{xEZT}juan)rM/p@=flG1K=H?9x;+oPf}?^}@p_B(!z)9MgNLZ?=lpQ=Nm;=0zbuSbPL8o%I)u4$rs_R*pm/9t,@qTwUA;i7_NGrqc25bWK{E[;%N4(fO1YVntn-,Zyz$kFT3!t[s)CeZcRlY6^jH+)mKFW)QxsiGz{zh6UjZmANF/heJ][E!^JSH[[(+c:VU:-Z-Js}=Ww+rATHnTN6/yR#vp]/5-)7vMT_LeRLqX1OmibihP8Na;$dB01?5=S0Q,_iY-dfdTVa/J,CNimP1qg%4R@p5r]*Fv+65CYVE)({5DGGBnlK*GI9j*-4YE1q7q58U3AL02oxU_XPnZR;6Cuei?U3y#F!)=6vIY;ivP37p%9%{2cUL:3?.RO#Dp.},_RHO7Rhdq]!V5=_NOohGtZ16ZQNKKC*gLP3*Dp5}V1@*s</formMonoSearch></FormData>'
function saveForm(name, text)
local path = getCheatEngineDir()..[[\autorun\forms\]]..name
local f, err = io.open(path, "w")
if f == nil then return nil, err end
f:write(text)
f:close()
return true
end
saveForm('formMonoClass.frm', formStringClass)
saveForm('formMonoImage.frm', formStringImage)
saveForm('formMonoSearch.frm', formStringSearch)
formMonoClass = createFormFromFile(getCheatEngineDir()..[[\autorun\forms\formMonoClass.frm]])
formMonoImage = createFormFromFile(getCheatEngineDir()..[[\autorun\forms\formMonoImage.frm]])
formMonoSearch = createFormFromFile(getCheatEngineDir()..[[\autorun\forms\formMonoSearch.frm]])
--[[================================================================================
-- Table Script
--================================================================================]]
function loadTextFile(name, useTableFile)
if useTableFile then
local tableFile = findTableFile(name)
if not tableFile then return nil, 'Unable to open table file "'..tostring(name)..'"' end
local ss = createStringStream()
ss.Position = 0 -- recommended on wiki: https://wiki.cheatengine.org/index.php?title=Lua:Class:TableFile
ss.CopyFrom(tableFile.Stream, 0)
local text = ss.DataString
ss.destroy()
return text
else
local path = getMainForm().openDialog1.InitialDir..name
local f, err = io.open(path, "r")
-- fall back to table file if disk file error (doesn't exist)
if f == nil then return loadTextFile(name, true) end
local text = f:read("*all")
f:close()
return text
end
end
popupMethodsCount = popupMethodsCount or 0
function popupMethodsPopup(sender)
local popup = formMonoClass.popupMethods
-- clear menu items
for i=popup.Items.Count,1,-1 do popup.Items[i-1].destroy() end
-- item to JIT method
local item1 = createMenuItem(popup)
popupMethodsCount = popupMethodsCount + 1
item1.Caption = 'Item '..tostring(popupMethodsCount)
popup.Items.Add(item1)
return true
end
--[[================================================================================
-- bootstrap.lua
--================================================================================]]
function loadTextFile(name, useTableFile)
if useTableFile then
local tableFile = findTableFile(name)
if not tableFile then return nil, 'Unable to open table file "'..tostring(name)..'"' end
local ss = createStringStream()
ss.Position = 0 -- recommended on wiki: https://wiki.cheatengine.org/index.php?title=Lua:Class:TableFile
ss.CopyFrom(tableFile.Stream, 0)
local text = ss.DataString
ss.destroy()
return text
else
local path = getMainForm().openDialog1.InitialDir..name
local f, err = io.open(path, "r")
-- fall back to table file if disk file error (doesn't exist)
if f == nil then return loadTextFile(name, true) end
local text = f:read("*all")
f:close()
return text
end
end
--[[
Save a string to a text file. If useTableFile is true it will be saved as
a TableFile. The directory should be where the cheat file is, it is the
initial directory for the dialog when you are saving your cheat table.
--]]
function saveTextFile(name, text, useTableFile)
if useTableFile then
local tf = findTableFile(name)
if tf ~= nil then
tf.delete()
tf = nil
end
tf = createTableFile(name)
local ss = createStringStream(text)
tf.Stream.CopyFrom(ss, 0)
ss.destroy()
return true
else
local path = getMainForm().saveDialog1.InitialDir..name
local f, err = io.open(path, "w")
if f == nil then return nil, err end
f:write(text)
f:close()
return true
end
end
--[[================================================================================
-- util.lua
--================================================================================]]
util = util or {}
--[[
For mono symbols, you have to surround them in quotes for use in AA
]]
function util.safeAddress(s)
local tbl = {}
for a in string.gmatch(s, "([^+]+)[+]?") do table.insert(tbl, a) end
local result = '"'..tbl[1]..'"'
if #tbl > 1 then result = result..'+'..tbl[2] end
return result
end
function util.split(s, separator)
local tbl = {}
for str in string.gmatch(s, "([^"..separator.."]+)") do table.insert(tbl, str) end
return tbl
end
function util.trim(s)
return (s:gsub("^%s*(.-)%s*$", "%1"))
end
--[[
Pretty-print serialize the passed object and return the results
as a string. This does nice indenting and follows metatables. It
is not guaranteed to provide the same object back if the string is
loaded because it just replaces circular references with a string
among other things. It does try to keep tables/arrays on one line
if there is room (120 characters).
--]]
function util.pretty(value, funcs, indent, done, stack)
indent = indent or 0
funcs = funcs or {}
done = done or {}
stack = stack or { {value=value} } -- initialize with passed value, no key
-- if a 'userdata', use metatable
local l = value
if type(value) == "userdata" then
l = getmetatable(value)
end
if type(l) == "table" then
-- if we've already serialized the table, return string representation
-- to avoid self-referencing in recursion. Only the first serialization
-- will have the full serialized string
if done[l] then return tostring(l) end
done[l] = true
local list = {}
-- here we return "{", the values, and "}"
if (#l > 0) then
-- if we have a count ('#'), then it's just an array of values
for i,v in ipairs(l) do
table.insert(list, util.pretty(v, funcs, indent + 2, done, stack))
end
else
-- no count, so either empty or object with key/value
-- first we sort the keys
local keys = {}
for k,v in pairs(l) do table.insert(keys, k) end
table.sort(keys)
local last = {key = "UNKNOWN", value = "NONE"}
table.insert(stack, last)
for i,k in ipairs(keys) do
local propValue = value[k]
last.key = k
last.value = value[k]
for j,f in ipairs(funcs) do
local returnValue = f(value, k, value[k], stack, indent)
if returnValue ~= nil then
propValue = returnValue
break
end
end
table.insert(list, string.format("%s = %s", tostring(k), util.pretty(propValue, funcs, indent+2, done, stack)))
end
table.remove(stack, #stack)
end
-- now we find the total size, add 200 if there are line breaks
local size = 0
for i,v in ipairs(list) do
size = size + string.len(v) + 2
if string.find(v, "\r\n") then
size = 200
break;
end
end
-- if it's small enough, join with commas
if (size < 120) then
local result = {"{ "}
for i,v in ipairs(list) do
if i > 1 then table.insert(result, ", ") end
table.insert(result, v)
end
table.insert(result, " }")
return table.concat(result);
else
local indentString1 = string.rep(" ", indent)
local indentString2 = string.rep(" ", indent + 2)
local result = {"{\r\n"}
for i,v in ipairs(list) do
table.insert(result, indentString2)
table.insert(result, v)
if (i < #list) then table.insert(result, ",") end
table.insert(result, "\r\n")
end
-- table.insert(result, indentString)
table.insert(result, indentString1)
table.insert(result, "}")
return table.concat(result);
end
end
if type(value) == "string" then
return string.format("\"%s\"", value)
end
return tostring(value)
end
--[[
Values and functions used by util.serialize(t)
---]]
local oddvals = {[tostring(1/0)] = '1/0', [tostring(-1/0)] = '-1/0', [tostring(-(0/0))] = '-(0/0)', [tostring(0/0)] = '0/0'}
local kw = {['and'] = true, ['break'] = true, ['do'] = true, ['else'] = true,
['elseif'] = true, ['end'] = true, ['false'] = true, ['for'] = true,
['function'] = true, ['goto'] = true, ['if'] = true, ['in'] = true,
['local'] = true, ['nil'] = true, ['not'] = true, ['or'] = true,
['repeat'] = true, ['return'] = true, ['then'] = true, ['true'] = true,
['until'] = true, ['while'] = true}
local getchr = function(c)
return "\\" .. c:byte()
end
local make_safe = function(text)
return ("%q"):format(text):gsub('\n', 'n'):gsub("[\128-\255]", getchr)
end
local write = function(t, memo, rev_memo)
local ty = type(t)
if ty == 'number' then
t = format("%.17g", t)
return oddvals[t] or t
elseif ty == 'boolean' or ty == 'nil' then
return tostring(t)
elseif ty == 'string' then
return make_safe(t)
elseif ty == 'table' or ty == 'function' then
if not memo[t] then
local index = #rev_memo + 1
memo[t] = index
rev_memo[index] = t
end
return '_[' .. memo[t] .. ']'
else
error("Trying to serialize unsupported type " .. ty)
end
end
local write_key_value_pair = function(k, v, memo, rev_memo, name)
if type(k) == 'string' and k:match '^[_%a][_%w]*$' and not kw[k] then
return (name and name .. '.' or '') .. k ..'=' .. write(v, memo, rev_memo)
else
return (name or '') .. '[' .. write(k, memo, rev_memo) .. ']=' .. write(v, memo, rev_memo)
end
end
local is_cyclic = function(memo, sub, super)
local m = memo[sub]
local p = memo[super]
return m and p and m < p
end
local write_table_ex = function(t, memo, rev_memo, srefs, name)
if type(t) == 'function' then
return '_[' .. name .. ']=loadstring' .. make_safe(string.dump(t))
end
local m = {}
local mi = 1
for i = 1, #t do -- don't use ipairs here, we need the gaps
local v = t[i]
if v == t or is_cyclic(memo, v, t) then
srefs[#srefs + 1] = {name, i, v}
m[mi] = 'nil'
mi = mi + 1
else
m[mi] = write(v, memo, rev_memo)
mi = mi + 1
end
end
for k,v in pairs(t) do
if type(k) ~= 'number' or math.floor(k) ~= k or k < 1 or k > #t then
if v == t or k == t or is_cyclic(memo, v, t) or is_cyclic(memo, k, t) then
srefs[#srefs + 1] = {name, k, v}
else
m[mi] = write_key_value_pair(k, v, memo, rev_memo)
mi = mi + 1
end
end
end
return '_[' .. name .. ']={' .. table.concat(m, ',') .. '}'
end
--[[
A function more appropriate for serializing objects in a reproduceable way.
--]]
function util.serialize(t)
local memo = {[t] = 0}
local rev_memo = {[0] = t}
local srefs = {}
local result = {}
-- phase 1: recursively descend the table structure
local n = 0
while rev_memo[n] do
result[n + 1] = write_table_ex(rev_memo[n], memo, rev_memo, srefs, n)
n = n + 1
end
-- phase 2: reverse order
for i = 1, n*.5 do
local j = n - i + 1
result[i], result[j] = result[j], result[i]
end
-- phase 3: add all the tricky cyclic stuff
for i, v in ipairs(srefs) do
n = n + 1
result[n] = write_key_value_pair(v[2], v[3], memo, rev_memo, '_[' .. v[1] .. ']')
end
-- phase 4: add something about returning the main table
if result[n]:sub(1, 5) == '_[0]=' then
result[n] = 'return ' .. result[n]:sub(6)
else
result[n + 1] = 'return _[0]'
end
-- phase 5: just concatenate everything
result = table.concat(result, '\n')
return n > 1 and 'local _={}\n' .. result or result
end
function util.map(t, f)
local results = {}
local func = f or tostring
for i,v in ipairs(t) do
table.insert(results, func(v))
end
return results
end
--[[================================================================================
-- notes.lua
--================================================================================]]
notes = notes or {}
notesmt = notesmt or {}
note = note or {}
notemt = notemt or {}
notemt.__index = note
notemt.__lt = function(a,b) return a.key < b.key end
function notes.new(filename, useTableFile)
local obj = {}
setmetatable(obj, {__index = notes})
obj:load(filename, useTableFile)
return obj
end
function notes:load(filename, useTableFile)
self.filename = filename
self.useTableFile = useTableFile
local s = loadTextFile(self.filename, self.useTableFile)
self.dict = {}
if s then self.dict = loadstring(s)() end
self.lastSave = os.clock()
self.lastChange = 0
end
function notes:save()
local text = util.serialize(self.dict)
saveTextFile(self.filename, text, self.useTableFile)
self.lastSave = os.clock()
end
function notes:saveAs(filename, useTableFile)
self.filename = filename
self.useTableFile = useTableFile
self:save()
end
function notes:update(key, text)
if text == nil or string.len(text) == 0 then
if self.dict[key] then self.dict[key] = nil end
else
self.dict[key] = {key = key, text = text}
end
self.lastUpdate = os.clock()
end
function notes:getList()
local keys = {}
for k,n in pairs(self.dict) do table.insert(keys, n) end
return keys
end
--[[================================================================================
-- mono.lua
--================================================================================]]
mono = mono or {}
-- classes
mono.MonoClass = mono.MonoClass or {}
mono.MonoField = mono.MonoField or {}
mono.MonoMethod = mono.MonoMethod or {}
mono.MonoImage = mono.MonoImage or {}
mono.menu = mono.menu or {}
mono.popups = mono.popups or {}
mono.formSelectImage = mono.formSelectImage or {}
mono.formSearch = mono.formSearch or {}
mono.formClass = mono.formClass or {}
-- defines
mono.TYPE_NAMES = {
[0] = 'END',
[1] = 'void',
[2] = 'bool',
[3] = 'char',
[4] = 'sbyte',
[5] = 'byte',
[6] = 'short',
[7] = 'ushort',
[8]= 'int',
[9]= 'uint',
[10] = 'long',
[11] = 'ulong',
[12] = 'float',
[13] = 'double',
[14] = 'string',
[15] = 'ptr',
[16] = 'byref',
[17] = 'valuetype',
[18] = 'class',
[19] = 'var',
[20] = 'array',
[21] = 'genericinst',
[22] = 'typedbyref',
[24] = 'I',
[25] = 'U',
[0x1b] = 'FNPTR',
[0x1c] = 'object',
[0x1d] = 'szarray', -- 0-based one-dim-array
[0x1e] = 'mvar',
[0x1f] = 'CMOD_REQD', -- typedef or typeref token
[0x20] = 'CMOD_OPT', -- optional arg: typedef or typeref token
[0x21] = 'INTERNAL',
[0x40] = 'MODIFIER', -- Or with the following types
[0x41] = 'SENTINEL', -- sentinel for varargs method signature
[0x45] = 'PINNED', -- local var that points to pinned object
[0x55] = 'ENUM', -- an enumeration
}
--[[================================================================================
-- monofield.lua
--================================================================================]]
local MonoField = mono.MonoField
MonoField.mt = {
__index = MonoField,
__tostring = function(t)
return 'MonoField '..tostring(t.id)..' "'..tostring(t.name)..'"'
end,
__lt = function(a, b)
return a.lowerName < b.lowerName
end
}
-- class is a monoclass table, f is a table with results from
-- mono_class_enumFields
function MonoField.new(class, f)
local obj = {
class = class,
id = f.field,
name = f.name,
isStatic = f.isStatic,
isConst = f.isConst,
offset = f.offset,
monoType = f.monotype,
lowerName = string.lower(f.name),
foundTypeName = f.typeName,
typeName = mono.TYPE_NAMES[f.monotype] or 'UnknownType'..tostring(f.monotype)
}
-- should be types where we might have a 'Class'
--if f.monotype == 15 or f.monotype == 16 or f.monotype == 18 or f.monotype then
--end
obj.typeClassId = mono_type_getClass(obj.id)
if obj.typeClassId ~= nil then
-- this is the 'type' of the field
obj.typeClass = class.image.classesById[obj.typeClassId]
if obj.typeClass ~= nil then
obj.typeName = obj.typeClass.name
else
if class.image.missingNames[obj.typeClassId] then
obj.typeName = class.image.missingNames[obj.typeClassId]
else
obj.typeName = mono_class_getFullName(obj.typeClassId)
class.image.missingNames[obj.typeClassId] = obj.typeName
end
end
end
setmetatable(obj, MonoField.mt)
return obj
end
function MonoField:getFullName()
local s = ""
if self.class.namespace ~= nil and self.class.namespace:len() > 0 then s = self.class.namespace..':' end
s = s..self.class.name..'.'
s = s..self.name
return s
end
--[[================================================================================
-- monomethod.lua
--================================================================================]]
local MonoMethod = mono.MonoMethod
MonoMethod.mt = {
__index = MonoMethod,
__tostring = function(t)
return 'MonoMethod '..tostring(t.id)..' "'..tostring(t.name)..'"'
end,
__lt = function(a, b)
return a.lowerName < b.lowerName
end
}
function MonoMethod.new(class, m)
local obj = {
class = class,
id = m.method,
name = m.name,
lowerName = string.lower(m.name),
parameters = {}
}
setmetatable(obj, MonoMethod.mt)
lastmethod = obj
local types, parameternames, returntype = mono_method_getSignature(obj.id)
local typenames={}
local tn
if types ~= nil then
for tn in string.gmatch(types, '([^,]+)') do
table.insert(typenames, tn)
end
end
for i=1,#typenames do
table.insert(obj.parameters, { name = parameternames[i], type = typenames[i] })
end
obj.returnType = returntype
return obj
end
--[[
Get parameters for method
--]]
function MonoMethod:fetchParms()
if self.parms ~= nil then return nil end
if self.class.image.ignoredClassesByName[self.class.name] ~= nil then return nil end
local status, parms = pcall(function()
local result = mono_method_get_parameters(self.id)
return result
end)
if status then
-- success!
self.parms = parms
else
self.class.image.ignoredClassesByName[self.class.name] = true
print('Error with class '..tostring(self.class.name)..' method '..tostring(self.name))
error('Error fetching parameters for '..tostring(self.class.name)..'.'..tostring(self.name))
end
end
--[[================================================================================
-- monoclass.lua
--================================================================================]]
local MonoClass = mono.MonoClass
MonoClass.mt = {
__index = MonoClass,
__tostring = function(t)
return 'MonoClass '..tostring(t.id)..' "'..tostring(t.name)..'"'
end,
__lt = function(a, b)
return a.lowerName < b.lowerName
end
}
local MonoField = mono.MonoField
local MonoMethod = mono.MonoMethod
--[[
Called from MonoImage:_init, 'c' is what is returned from enumerating classes.
--]]
function MonoClass.new(image, c)
local obj = {
name = c.classname,
namespace = c.namespace,
id = c.class,
lowerName = string.lower(c.classname),
image = image
}
setmetatable(obj, MonoClass.mt)
return obj
end
function MonoClass:initFields()
self.fields = {}
self.fieldsByName = {}
self.fieldsByLowerName = {}
local constFieldCount = 0
local temp = mono_class_enumFields(self.id)
for i,f in ipairs(temp) do
local field = MonoField.new(self, f)
table.insert(self.fields, field)
self.fieldsByLowerName[field.lowerName] = field;
self.fieldsByName[field.name] = field
if field.isStatic and field.isConst then
field.constValue = constFieldCount
constFieldCount = constFieldCount + 1
end
end
table.sort(self.fields)
end
function MonoClass:initMethods()
self.methods = {}
self.methodsByName = {}
self.methodsByLowerName = {}
local temp = mono_class_enumMethods(self.id)
for i,m in ipairs(temp) do
local method = MonoMethod.new(self, m)
table.insert(self.methods, method)
self.methodsByName[method.name] = method
self.methodsByLowerName[method.lowerName] = method
end
table.sort(self.methods)
end
--[[================================================================================
-- monoimage.lua
--================================================================================]]
local MonoImage = mono.MonoImage
MonoImage.mt = {
__index = MonoImage,
__tostring = function(t)
return 'MonoImage '..tostring(t.name)
end
}
local MonoClass = mono.MonoClass
--[[
List names of images, a name can be passed to MonoImage.new()
or MonoImage(name) to create a MonoImage instance.
--]]
function MonoImage.enumerate()
local names = {}
mono_enumImages(function(img)
local name = mono_image_get_name(img)
table.insert(names, name)
end)
table.sort(names)
return names
end
--[[
Constructor doesn't do much, call :init(name, progress)
--]]
function MonoImage.new()
local obj = { }
setmetatable(obj, MonoImage.mt)
return obj
end
--[[
init() takes the image name and an optional callback for reporting progress
and when it is complete. The signature for this function is:
function progress(complete, image, message, processed, total)
This callback should be executed on the main CE thread.
--]]
function MonoImage:init(name, progress)
if monopipe == nil then
print('Launching mono data collector...')
LaunchMonoDataCollector()
end
self.domains = mono_enumDomains()
self.domain = self.domains[1]
self.classes = {} -- straight list of all classes
self.classesByName = {} -- dictionary for access by name
self.classesByLowerName = {} -- for access by lower case name
self.classesById = {} -- for access by id
self.ignoredClassesByName = {} -- for ignoring classes in searches, etc.
self.progress = progress
self.name = name or 'Assembly-CSharp' -- intelligent default for unity
-- get id
self.id = nil
mono_enumImages(function(img)
local foundName = mono_image_get_name(img)
if foundName == self.name then self.id = img end
end)
if not self.id then
print('NO ID!')
print('name is', name, self.name)
self:report(false, 'Error finding image named '..tostring(name))
self.progress = nil
self.total = nil
self.count = nil
return false
end
createThread(function(thread)
self.thread = thread
self:_init(thread)
end)
end
--[[
This is the function called by init() on another thread
--]]
function MonoImage:_init(thread)
--print('MonoImage:_init thread is', thread, 'self is', tostring(self))
self.thread = thread
local temp = mono_image_enumClasses(self.id)
-- thread.synchronize(function(th)
-- print('Image '..tostring(self.id)..' has classes: '..tostring(temp))
-- end)
self.classes = {}
self.classesByName = {}
self.classesByLowerName = {}
self.classesById = {}
self.missingNames = {}
self.total = #temp
self.count = 0
self.message = "Getting classes"
self:report(false, "Getting classes")
-- populate classes without much information first so we can
-- access our definitions when filling in parents, properties, etc.
for i,c in ipairs(temp) do
local class = MonoClass.new(self, c)
if class.lowerName ~= nil then
table.insert(self.classes, class)
self.classesByName[class.name] = class
self.classesByLowerName[class.lowerName] = class
self.classesById[class.id] = class
else
--print("Nil lowername for class", c.class)
end
self.count = i
if (i % 100 == 0 or i == #temp) then
self:report(false, 'Fetching classes')
end
end
table.sort(self.classes)
for i,class in ipairs(self.classes) do
class.parentId = mono_class_getParent(class.id)
class.parent = self.classesById[class.parentId]
self.count = i
if (i % 100 == 0 or i == #temp) then
self:report(false, 'Fetching parents')
end
end
self.count = 0
for i,class in ipairs(self.classes) do
class:initFields()
class:initMethods()
self.count = i
if (i % 100 == 0 or i == #temp) then
self:report(false, 'Initializing fields and methods')
end
end
self:report(true, 'Done')
end
--[[
Report progress on the main CE thread to do gui updates
--]]
function MonoImage:report(done, message)
if self.progress ~= nil and self.thread ~= nil then
self.thread.synchronize(function(thread)
self.progress(done, self, message, self.count, self.total)
end)
end
if done then
-- do cleanup here
self.count = nil
self.total = nil
self.progress = nil
self.thread = nil
end
end
--[[================================================================================
-- monomenu.lua
--================================================================================]]
function mono.menu:init(parent)
self.menuSearch = createMenuItem(parent)
self.menuSearch.Caption = 'Search'
self.menuSearch.Name = 'miMonoSearch'
self.menuSearch.OnClick = function(sender) self:OnSearchClick() end
parent.add(self.menuSearch)
end
function mono.menu:OnSearchClick()
if mono.selectedImage then
mono.formSearch:show()
else
mono.formSelectImage:show()
end
end
--[[================================================================================
-- formSelectImage.lua
--================================================================================]]
function mono.formSelectImage:show()
LaunchMonoDataCollector()
formMonoImage.listImages.Visible = true
formMonoImage.buttonSelectImage.Visible = true
formMonoImage.progressImage.Visible = false
formMonoImage.labelMessage.Visible = false
self.imageNames = mono.MonoImage.enumerate()
table.sort(self.imageNames)
local items = formMonoImage.listImages.Items
items.Clear()
for i,name in ipairs(self.imageNames) do items.add(name) end
local handler = function(sender)
mono.formSelectImage.OnSelectImage(self)
end
formMonoImage.buttonSelectImage.OnClick = handler
formMonoImage.listImages.OnDblClick = handler
formMonoImage.show()
end
function mono.formSelectImage:OnSelectImage()
local index = formMonoImage.listImages.ItemIndex + 1
if self.imageNames == nil or index < 1 or index > #self.imageNames then return end
local imageName = self.imageNames[index]
formMonoImage.listImages.Visible = false
formMonoImage.buttonSelectImage.Visible = false
formMonoImage.progressImage.Visible = true
formMonoImage.labelMessage.Visible = true
formMonoImage.labelMessage.Caption = 'Finding classes...'
local image = mono.MonoImage.new()
formMonoImage.progressImage.Min = 0
local progressHandler = function(done, image, message, count, total)
if total ~= nil and total > 0 and count ~= nil and count >= 0 then
message = string.format('%s %d/%d', message, count, total)
formMonoImage.progressImage.Max = total
formMonoImage.progressImage.Position = count
end
formMonoImage.labelMessage.Caption = message
if done then self:OnImageComplete(image) end
end
image:init(imageName, progressHandler)
end
function mono.formSelectImage:OnImageComplete(image)
self.image = image
mono.selectedImage = image
formMonoImage.Close()
mono.formSearch:show()
end
--[[================================================================================
-- formSearch.lua
--================================================================================]]
--[[
Form for searching an image.
Controls:
pageMain.tabSearch - main tab
editSearchText: TCEEdit
listSearchClasses: TCEListView
listSearchFields: TCEListView
listSearchMethods: TCEListView
miImage: TMenuItem - main menu Image entry
miImageSelectImage - entry to re-open select image form
--]]
mono.formSearch.found = mono.formSearch.found or {}
mono.formSearch.found.classes = mono.formSearch.found.classes or {}
mono.formSearch.found.fields = mono.formSearch.found.fields or {}
mono.formSearch.found.methods = mono.formSearch.found.methods or {}
--[[
Show the search form, mono.selectedImage should be set to the
image to search.
--]]
function mono.formSearch:show()
if mono.selectedImage == nil then return end
self.image = mono.selectedImage
-- setup event handlers
formMonoSearch.miImageSelectImage.OnClick = function(sender) self:SelectImageClick() end
formMonoSearch.listSearchClasses.OnData = function(sender, listitem)
self:listSearchClasses_OnData(sender, listitem)
end
formMonoSearch.listSearchClasses.OnDblClick = function(sender)
local class = self.found.classes[sender.ItemIndex + 1]
mono.formClass:show(class, nil, nil)
end
formMonoSearch.listSearchFields.OnData = function(sender, listitem)
self:listSearchFields_OnData(sender, listitem)
end
formMonoSearch.listSearchFields.OnDblClick = function(sender)
local field = self.found.fields[sender.ItemIndex + 1]
if field then
mono.formClass:show(field.class, field, nil)
end
end
formMonoSearch.listSearchMethods.OnData = function(sender, listitem)
self:listSearchMethods_OnData(sender, listitem)
end
formMonoSearch.listSearchMethods.OnDblClick = function(sender)
local method = self.found.methods[sender.ItemIndex + 1]
if method then
mono.formClass:show(method.class, nil, method)
end
end
formMonoSearch.editSearchText.OnChange = function(sender)
self:search(sender.text)
end
-- popups
formMonoSearch.listSearchClasses.PopupMenu = formMonoSearch.popupClasses
local count = 0
formMonoSearch.popupClasses.OnPopup = function(sender)
print('formMonoSearch.popupClasses.OnPopup "'..tostring(sender.name)..'" count '..tostring(count))
count = count + 1
end
-- perform initial search to set 'found' results, probably empty text
self:search(formMonoSearch.editSearchText.Text)
-- show form
formMonoSearch.show()
end
--[[
When menu item to select an image is clicked, hide this form and
show the image select form
--]]
function mono.formSearch:SelectImageClick()
formMonoSearch.close()
mono.formSelectImage:show()
end
--[[
When typing in the edit box to filter results, filter the lists of
classes, fields, and methods with the lower case of the text
--]]
function mono.formSearch:search(text)
local lower = nil
if text ~= nil then lower = text:lower() end
local classes = {}
local methods = {}
local fields = {}
for i,class in ipairs(self.image.classes) do
if lower == nil or class.lowerName:find(lower, 1, true) ~= nil then table.insert(classes, class) end
for j,method in ipairs(class.methods) do
if lower == nil or method.lowerName:find(lower, 1, true) ~= nil then table.insert(methods, method) end
end
for j,field in ipairs(class.fields) do
if lower == nil or field.lowerName:find(lower, 1, true) ~= nil then table.insert(fields, field) end
end
end
self.found.classes = classes
self.found.fields = fields
self.found.methods = methods
formMonoSearch.listSearchClasses.Items.Count = #classes
formMonoSearch.listSearchFields.Items.Count = #fields
formMonoSearch.listSearchMethods.Items.Count = #methods
end
-- handler to display classes in list view
function mono.formSearch:listSearchClasses_OnData(sender, listitem)
local index = listitem.Index + 1
local class = self.found.classes[index]
listitem.Caption = class.name
end
-- handler to display fields in list view
function mono.formSearch:listSearchFields_OnData(sender, listitem)
local field = self.found.fields[listitem.Index + 1]
if field == nil then
listitem.Caption = 'nil index '..tostring(index)
else
listitem.Caption = field.name
listitem.SubItems.text = field.class.name
end
end
-- handler to display methods in list view
function mono.formSearch:listSearchMethods_OnData(sender, listitem)
local method = self.found.methods[listitem.Index + 1]
if method == nil then
listitem.Caption = 'nil index '..tostring(index)
else
listitem.Caption = method.name
listitem.SubItems.text = method.class.name
end
end
--[[================================================================================
-- formClass.lua
--================================================================================]]
local sortByClassThenName = function(a, b)
if a.isConst and not b.isConst then return true end
if b.isConst and not a.isConst then return false end
if a.isConst and b.isConst then return a.constValue < b.constValue end
if a.class.lowerName < b.class.lowerName then return true end
if b.class.lowerName < a.class.lowerName then return false end
return a.name < b.name
end
local sortByClassThenOffset = function(a, b)
if a.isConst and not b.isConst then return true end
if b.isConst and not a.isConst then return false end
if a.isConst and b.isConst then return a.constValue < b.constValue end
if a.class.lowerName < b.class.lowerName then return true end
if b.class.lowerName < a.class.lowerName then return false end
return a.offset < b.offset
end
local sortByName = function(a, b)
if a.isConst and not b.isConst then return true end
if b.isConst and not a.isConst then return false end
if a.isConst and b.isConst then return a.constValue < b.constValue end
return a.lowerName < b.lowerName
end
local sortByOffset = function(a, b)
if a.isConst and not b.isConst then return true end
if b.isConst and not a.isConst then return false end
if a.isConst and b.isConst then return a.constValue < b.constValue end
return a.offset < b.offset
end
--[[
Show the search form, mono.selectedImage should be set to the
image to search.
--]]
function mono.formClass:show(class, field, method)
if mono.selectedImage == nil or class == nil then return end
self.image = mono.selectedImage
self.class = class
-- function to update lists, for setting on menu items that
-- make other changes
local funcUpdate = function(sender) self:setFieldsAndMethods() end
formMonoClass.listFields.OnData = function(sender, listitem)
self:listFields_OnData(sender, listitem)
end
formMonoClass.listFields.OnDblClick = function(sender)
self:listFields_OnDblClick(sender)
end
formMonoClass.listMethods.OnData = function(sender, listitem)
self:listMethods_OnData(sender, listitem)
end
formMonoClass.listMethods.OnDblClick = function(sender)
self:listMethods_OnDblClick(sender)
end
formMonoClass.miSortFieldsByOffset.OnClick = funcUpdate
formMonoClass.miShowInherited.OnClick = funcUpdate
formMonoClass.miShowUsage.OnClick = funcUpdate
-- create our own lists of fields and methods that we can sort
-- and filter
self:setFieldsAndMethods()
-- show form
formMonoClass.show()
end
--[[
Set fields and methods arrays, sorted appropriately and
with extra fields, including possibly parent fields and methods
--]]
function mono.formClass:setFieldsAndMethods()
local other = ''
if formMonoClass.miShowUsage.Checked then other = ' (usage by other classes)' end
formMonoClass.labelClassName.Caption = string.format('Mono Class: %s:%s%s', self.class.namespace, self.class.name, other)
local fields = {}
local methods = {}
if formMonoClass.miShowUsage.Checked then
---------- show where class is used in other classes
for i,class in ipairs(self.image.classes) do
for j,method in ipairs(class.methods) do
local found = false
if method.returnType == self.class.name then
found = true
else
for k,p in ipairs(method.parameters) do
if p.typeName == self.class.name then found = true end
end
end
if found then table.insert(methods, method) end
end
for j,field in ipairs(class.fields) do
if field.typeName == self.class.name then table.insert(fields, field) end
end
end
else
---------- basic class fields and methods
local c = self.class
while c ~= nil do
for i,field in ipairs(c.fields) do
table.insert(fields, field)
end
for i,method in ipairs(c.methods) do
table.insert(methods, method)
end
if formMonoClass.miShowInherited.Checked then
c = c.parent
else
c = nil
end
end
end
if formMonoClass.miSortByClassFirst.Checked then
table.sort(fields, formMonoClass.miSortFieldsByOffset.Checked and sortByClassThenOffset or sortByClassThenName)
table.sort(methods, sortByClassThenName)
else
table.sort(fields, formMonoClass.miSortFieldsByOffset.Checked and sortByOffset or sortByName)
table.sort(methods, sortByName)
end
self.fields = fields
self.methods = methods
formMonoClass.listFields.Items.Count = 0
formMonoClass.listFields.Items.Count = #fields
formMonoClass.listMethods.Items.Count = 0
formMonoClass.listMethods.Items.Count = #methods
end
-- handler to display fields in list view
function mono.formClass:listFields_OnData(sender, listitem)
-- columns are offset (or 'STATIC'), Type, Name
local index = listitem.Index + 1
local field = self.fields[index]
-- columns are Offset, Type, Name
if field.isStatic then
if field.isConst then
listitem.Caption = 'Const:'..string.format('%2X', field.constValue or 0)
else
listitem.Caption = 'Static:'..string.format('%2X', field.offset or 0)
end
else
listitem.Caption = string.format('%02X', field.offset or 0)
end
local className = ''
if field.class.name ~= self.class.name then className = field.class.name end
listitem.SubItems.text = table.concat({field.typeName or '??', field.name, className}, '\n')
end
-- handler to display methods in list view
function mono.formClass:listMethods_OnData(sender, listitem)
local method = self.methods[listitem.Index + 1]
if method == nil then
listitem.Caption = 'nil index '..tostring(listitem.Index + 1)
else
listitem.Caption = method.name
local className = ''
if method.class.name ~= self.class.name then className = method.class.name end
local ps = {}
for i,p in ipairs(method.parameters) do
table.insert(ps, string.format('%s %s', p.type, p.name))
end
local parms = method.returnType..' ('..table.concat(ps, ', ')..')'
--print('className, method.class.name', className, method.class.name)
listitem.SubItems.text = table.concat({ parms, className }, '\n')
end
end
local parameters = { 'RCX', 'RDX', 'R8', 'R9', '[RBP+30]', '[RBP+38]', '[RBP+40]', '[RBP+48]', '[RBP+50]' }
local floatParameters = { 'XMM0', 'XMM1', 'XMM2', 'XMM3', 'XMM4', 'XMM5', 'XMM6'}
function mono.formClass:popupMethod_OnPopup(sender)
end
function mono.formClass:listMethods_OnDblClick(sender)
local method = self.methods[sender.ItemIndex + 1]
--print("method: "..tostring(method.id))
if method then
local address = mono_compile_method(method.id)
--print("address: "..tostring(address))
getMemoryViewForm().DisassemblerView.SelectedAddress = address
getMemoryViewForm().show()
local hookInfo = hookAt(address)
-- have aobString, hookString, returnString, instructions
--[[ how to get method signature
local ps = {}
for i,p in ipairs(method.parameters) do
table.insert(ps, string.format('%s %s', p.type, p.name))
end
local parms = method.returnType..' ('..table.concat(ps, ', ')..')'
]]
local lines = {}
table.insert(lines, "define(hook,"..hookInfo.hookString..")")
table.insert(lines, "define(bytes,"..hookInfo.aobString..")")
table.insert(lines, "")
table.insert(lines, "[enable]")
table.insert(lines, "")
table.insert(lines, "assert(hook, bytes)")
table.insert(lines, "alloc(newmem,$1000, hook)")
table.insert(lines, "{")
-- note: per x64 calling convention, RCX might actually be space for
-- a pre-allocated structure for the return value and other parameters
-- might be moved one further down the list
table.insert(lines, " RCX: "..method.class.name.." (this)")
for i,p in ipairs(method.parameters) do
local param = parameters[i + 1]
if (p.type == "System.Single" or p.type == "System.Double") then param = floatParameters[i + 1] end
table.insert(lines, " "..param..": "..tostring(p.type).." "..tostring(p.name))
end
table.insert(lines, "")
table.insert(lines, " Returns (RAX) "..method.returnType)
table.insert(lines, "}")
table.insert(lines, "")
table.insert(lines, "newmem:")
table.insert(lines, " // original code")
for i,c in ipairs(hookInfo.instructions) do
table.insert(lines, " "..c)
end
table.insert(lines, " jmp hook+"..string.format("%X", hookInfo.returnOffset))
table.insert(lines, "")
table.insert(lines, "hook:")
table.insert(lines, " jmp newmem")
table.insert(lines, "")
table.insert(lines, "[disable]")
table.insert(lines, "")
table.insert(lines, "hook:")
table.insert(lines, " db bytes")
table.insert(lines, "")
table.insert(lines, "dealloc(newmem)")
local t = {}
for i,v in ipairs(lines) do
table.insert(t, v);
table.insert(t, "\r\n")
end
local aa = table.concat(t)
getMemoryViewForm().AutoInject1.DoClick()
for i=0,getFormCount()-1 do --this is sorted from z-level. 0 is top
local f=getForm(i)
if getForm(i).ClassName == 'TfrmAutoInject' then
f.assemblescreen.Lines.Text = aa
break
end
end
end
end
--[[
When double-clicking a field, print out the base address for the statics of the
class and the address of the clicked-on static field.
--]]
function mono.formClass:listFields_OnDblClick(sender)
local field = self.fields[sender.ItemIndex + 1]
if field then
local class = field.class
local image = class.image
local domainId = image.domain
print('double-clicked on class '..tostring(field.class.name)..' field '..tostring(field.name)..' domain '..tostring(domainId))
local address = mono_class_getStaticFieldAddress(domainId, class.id)
print('statics base address: '..string.format("%x", address))
print(class.name..'.'..field.name..': '..string.format("%x", address + field.offset))
end
end
--[[
IN PROGRESS - take an address and create an AA script to hook at that address
expecting MONO code. Will process instructions until 5 bytes (for jmp) are
processed. Basic format is like this for address 'CryingSuns.PlayerStatus:BattleshipState:HasAuxiliarySystemType+28'
[enable]
assert("CryingSuns.PlayerStatus:BattleshipState:HasAuxiliarySystemType":+28, )
]]
function hookAt(address)
local pos = string.find(address, "+", 1, true)
local name = address
local offset = 0
if (pos ~= nil) then
name = string.substring(1, pos - 1)
offset = tonumber(string.sub(pos + 1), 16)
end
local actualAddress = getAddress(name) + offset
local data = {
hookString = util.safeAddress(getNameFromAddress(actualAddress)), -- used for injection, etc
instructions = {},
aobString = ""
}
local aobs = {}
while (offset < 5) do
local parsed = disassembleAndParse(actualAddress + offset)
if #aobs > 0 then table.insert(aobs, " ") end
table.insert(aobs, parsed.bytesString)
table.insert(data.instructions, parsed.instructionString)
offset = offset + parsed.length
end
data.aobString = table.concat(aobs)
data.returnString = util.safeAddress(getNameFromAddress(actualAddress + offset))
data.returnOffset = offset
return data
end
function hookMethod(method)
end
--[[
Expects address to be a number
]]
function disassembleAndParse(address)
local disassembly = disassemble(address)
local parts = util.split(disassembly, "-")
for i = 1,#parts do
if i == 2 then
parts[i] = parts[i]:gsub("%s+", "") -- remove ALL whitespace from bytes
else
parts[i] = parts[i]:gsub("^%s*(.-)%s*$", "%1") -- remove whitespace from ends
end
end
local aob = {}
local i = 1
while i < string.len(parts[2]) do
if (i ~= 1) then table.insert(aob, " ") end
table.insert(aob, string.sub(parts[2], i, i+1))
i = i + 2
end
local instructionString = parts[3]
for k,v in parts[3]:gmatch("[0-9a-fA-F]+") do
if k:len() == 8 or k:len() == 16 then
instructionString = instructionString:gsub(k, getNameFromAddress(k))
end
end
local result = {
address = getAddress(address),
addressString = util.safeAddress(getNameFromAddress(address)),
aob = aob,
bytesString = table.concat(aob),
disassembly = disassembly,
instructionString = instructionString,
length = getInstructionSize(address),
originalInstructionString = parts[3]
}
return result
end
--[[================================================================================
-- Replacement code to activate top level menu
--================================================================================]]
function monohelper_OpenProcessMT(t)
if t ~= nil then
t.destroy()
end
local usesmono=false
local m=enumModules()
local i
for i=1, #m do
if (m[i].Name=='mono.dll') or (string.sub(m[i].Name,1,5)=='mono-') then
usesmono=true
break
end
end
if usesmono then
--create a menu item if needed
if (miMonoHelperTopMenuItem == nil) then
local mfm = getMainForm().Menu
if (mfm) then
local mi
miMonoHelperTopMenuItem = createMenuItem(mfm)
miMonoHelperTopMenuItem.Caption = "Mono Search"
mfm.Items.insert(mfm.Items.Count - 1, miMonoHelperTopMenuItem) --add it before help
mono.menu:init(miMonoHelperTopMenuItem)
end
end
else
--destroy the menu item if needed
if miMonoTopMenuItem~=nil then
miMonoTopMenuItem.miMonoDissect.destroy() --clean up the onclick handler
miMonoTopMenuItem.miMonoActivate.destroy() --clean up the onclick handler
miMonoTopMenuItem.destroy() --also destroys the subitems as they are owned by this menuitem
miMonoTopMenuItem=nil
end
end
end
function monohelper_OpenProcess(processid)
--call the original onOpenProcess if there was one
if monohelper_oldOnOpenProcess~=nil then
monohelper_oldOnOpenProcess(processid)
end
synchronize("monohelper_OpenProcessMT")
end
function monohelper_Init()
monohelper_oldOnOpenProcess = onOpenProcess
onOpenProcess = monohelper_OpenProcess
end
monohelper_Init()
|
local class = require("heart.class")
local M = class.newClass()
function M:init(engine, config)
self.engine = assert(engine)
self.meshLoader = assert(engine.resourceLoaders.mesh)
self.transformComponents = assert(self.engine.componentManagers.transform)
self.meshes = {}
self.transforms = {}
end
function M:createComponent(id, config)
local transform = self.transformComponents.transforms[id]
if config.mesh then
self.meshes[id] = self.meshLoader:loadResource(config.mesh)
else
local vertexCount = assert(config.vertexCount)
local drawMode = config.drawMode or "fan"
local usage = config.usage or "dynamic"
self.meshes[id] = love.graphics.newMesh(vertexCount, drawMode, usage)
end
self.transforms[id] = transform:clone()
end
function M:destroyComponent(id)
self.meshes[id] = nil
self.transforms[id] = nil
end
return M
|
return {
Name = "giveItem";
Aliases = {};
Description = "Gives a player an item with the specified quantity";
Group = "Admin";
Args = {
{
Type = "itemId";
Name = "itemId";
Description = "Item to give";
},
{
Type = "player";
Name = "target";
Description = "Player to give item to";
},
{
Type = "integer";
Name = "quantity";
Description = "Ammount of items to give";
Default = 1;
},
};
} |
--------------------------------
--- MATERIALS (MODELS)
--------------------------------
local Models = {}
MR.Models = Models
-- Networking
net.Receive("Models:Set", function(_, ply)
if SERVER then return; end
Models:Set(LocalPlayer(), net.ReadTable(), net.ReadBool())
end)
net.Receive("Models:Remove", function()
if SERVER then return; end
Models:Remove(LocalPlayer(), net.ReadEntity(), net.ReadBool())
end)
-- Get the original material full path
function Models:GetOriginal(tr)
if IsValid(tr.Entity) then
return tr.Entity:GetMaterials()[1]
end
return nil
end
-- Get the current material full path
function Models:GetCurrent(tr)
if IsValid(tr.Entity) and not tr.Entity:IsPlayer() then
local data = tr.Entity.mr
local material = ""
-- Get a material generated for the model
if data then
newMaterial = MR.CustomMaterials:RevertID(data.newMaterial)
-- Or the original material
else
newMaterial = tr.Entity:GetMaterials()[1]
end
return newMaterial
end
return nil
end
-- Get the original material full path
function Models:GetNew(ent)
if IsValid(ent) and not ent:IsPlayer() then
return ent.mr
end
return nil
end
-- Get the current data
function Models:GetData(ent)
local oldData
-- Model
if IsValid(ent) and not ent:IsPlayer() and ent.mr and not ent.mr.normal then
oldData = table.Copy(ent.mr)
-- Revert the newName if there is data
if oldData and oldData.newMaterial ~= "" then
oldData.newMaterial = MR.CustomMaterials:RevertID(oldData.newMaterial)
end
end
return oldData
end
-- Set model material
function Models:Set(ply, data, isBroadcasted)
-- "Hack": turn it into a removal if newMaterial is nothing
if data.newMaterial == "" then
Models:Remove(ply, data.ent, isBroadcasted)
return
end
-- General first steps
local check = {
material = data.newMaterial,
ent = data.ent or ""
}
if not MR.Materials:SetFirstSteps(ply, isBroadcasted, check, data, "Models") then
return false
end
if SERVER then
-- Send the modification to...
net.Start("Models:Set")
net.WriteTable(data)
net.WriteBool(isBroadcasted)
-- every player
if not MR.Ply:GetFirstSpawn(ply) or ply == MR.SV.Ply:GetFakeHostPly() then
net.Broadcast()
-- the player
else
net.Send(ply)
end
end
-- run once serverside and once on every player clientside
if CLIENT or SERVER and not MR.Ply:GetFirstSpawn(ply) or SERVER and ply == MR.SV.Ply:GetFakeHostPly() then
if SERVER then
-- Set the duplicator
duplicator.StoreEntityModifier(data.ent, "MapRetexturizer_Models", data)
end
-- Create the new material
MR.CustomMaterials:Create(data, "VertexLitGeneric", false, true)
-- Save the Data table inside the model
data.ent.mr = data
-- Set the alpha
if data.alpha then
data.ent:SetRenderMode(RENDERMODE_TRANSALPHA)
data.ent:SetColor(Color(255, 255, 255, 255 * data.alpha))
end
-- Apply the material
data.ent:SetMaterial("!" .. MR.CustomMaterials:IDToString(data.newMaterial))
end
-- Set the Undo
if SERVER and not isBroadcasted and not MR.Ply:GetFirstSpawn(ply) then
undo.Create("Material")
undo.SetPlayer(ply)
undo.AddFunction(function(tab, ent)
if IsValid(ent) and ent.mr then
Models:Remove(ply, ent, isBroadcasted)
end
end, data.ent)
undo.SetCustomUndoText("Undone Material")
undo.Finish()
end
-- General final steps
MR.Materials:SetFinalSteps()
return true
end
-- Remove model material
function Models:Remove(ply, ent, isBroadcasted)
-- Check if there is a modification
if not ent or not IsValid(ent) or ent:IsPlayer() or not ent.mr then
return false
end
-- General first steps
local fakeData = {
newMaterial = "",
ent = ent
}
if not MR.Materials:SetFirstSteps(ply, isBroadcasted, nil, fakeData, "Models") then
return false
end
if SERVER and isBroadcasted then
-- Delete the Data table
ent.mr = nil
-- Clear the duplicator
duplicator.ClearEntityModifier(ent, "MapRetexturizer_Models")
end
if SERVER then
-- Run the remotion on client(s)
net.Start("Models:Remove")
net.WriteEntity(ent)
net.WriteBool(isBroadcasted)
if isBroadcasted then
net.Broadcast()
else
net.Send(ply)
end
elseif CLIENT then
-- Delete the Data table
ent.mr = nil
-- Disable the alpha
ent:SetMaterial("")
ent:SetRenderMode(RENDERMODE_NORMAL)
ent:SetColor(Color(255,255,255,255))
end
-- General final steps
MR.Materials:SetFinalSteps()
return true
end
-- Resize collision model
-- Code ported from Collision Resizer (ENHANCED), made by Tau
function Models:IsValidPhysicsObject(physobj)
return TypeID(physobj) == TYPE_PHYSOBJ and physobj:IsValid()
end
function Models:ResizePhysics(ent, scale)
ent:PhysicsInit(SOLID_VPHYSICS)
local physobj = ent:GetPhysicsObject()
if not Models:IsValidPhysicsObject(physobj) then return false end
local physmesh = physobj:GetMeshConvexes()
if not istable(physmesh) or #physmesh < 1 then return false end
for convexkey, convex in pairs(physmesh) do
for poskey, postab in pairs(convex) do
convex[poskey] = postab.pos * scale
end
end
ent:PhysicsInitMultiConvex(physmesh)
ent:EnableCustomCollisions(true)
return Models:IsValidPhysicsObject(ent:GetPhysicsObject())
end |
object_tangible_furniture_flooring_tile_frn_flooring_tile_s10 = object_tangible_furniture_flooring_tile_shared_frn_flooring_tile_s10:new {
}
ObjectTemplates:addTemplate(object_tangible_furniture_flooring_tile_frn_flooring_tile_s10, "object/tangible/furniture/flooring/tile/frn_flooring_tile_s10.iff")
|
--[[
© 2020 TERRANOVA do not share, re-distribute or modify
without permission of its author.
--]]
ITEM.name = "White Bread Loaf";
ITEM.model = "models/foodnhouseholditems/bread-1.mdl";
ITEM.width = 1;
ITEM.height = 1;
ITEM.description = "A loaf of delicious white bread.";
ITEM.permit = "consumables";
ITEM.category = "Bread";
ITEM.price = 25;
ITEM.restoreHealth = 10;
ITEM.flag = "b" |
local config = {}
local function init()
local bqf = require('bqf')
vim.validate({config = {bqf._config, 'table', true}})
config = vim.tbl_deep_extend('keep', bqf._config or {}, {
auto_enable = true,
magic_window = true,
auto_resize_height = true,
preview = {
auto_preview = true,
border_chars = {'│', '│', '─', '─', '╭', '╮', '╰', '╯', '█'},
delay_syntax = 50,
win_height = 15,
win_vheight = 15,
wrap = false,
should_preview_cb = nil
},
func_map = {
open = '<CR>',
openc = 'o',
split = '<C-x>',
vsplit = '<C-v>',
tab = 't',
tabb = 'T',
ptogglemode = 'zp',
ptoggleitem = 'p',
ptoggleauto = 'P',
pscrollup = '<C-b>',
pscrolldown = '<C-f>',
pscrollorig = 'zo',
prevfile = '<C-p>',
nextfile = '<C-n>',
prevhist = '<',
nexthist = '>',
stoggleup = '<S-Tab>',
stoggledown = '<Tab>',
stogglevm = '<Tab>',
stogglebuf = [['<Tab>]],
sclear = 'z<Tab>',
filter = 'zn',
filterr = 'zN',
fzffilter = 'zf'
},
filter = {
fzf = {
action_for = {
['ctrl-t'] = 'tabedit',
['ctrl-v'] = 'vsplit',
['ctrl-x'] = 'split',
['ctrl-q'] = 'signtoggle'
},
extra_opts = {'--bind', 'ctrl-o:toggle-all'}
}
}
})
bqf._config = nil
end
init()
return config
|
--
-- Virtuajdr dice roller for TS3 init file
--
require("ts3init")
require("Virtuajdr_dice/VJDR_events")
local registeredEvents = {
onTextMessageEvent = diceroll_events.onTextMessageEvent
}
ts3RegisterModule("diceroll", registeredEvents)
|
return {
"icons/elf_skill/skill_dru1-1",
"icons/elf_skill/skill_dru1-2",
"icons/elf_skill/skill_dru10-1",
"icons/elf_skill/skill_dru10-2",
"icons/elf_skill/skill_dru12-1",
"icons/elf_skill/skill_dru12-2",
"icons/elf_skill/skill_dru14-1",
"icons/elf_skill/skill_dru16-1",
"icons/elf_skill/skill_dru18-1",
"icons/elf_skill/skill_dru2-1",
"icons/elf_skill/skill_dru2-2",
"icons/elf_skill/skill_dru20-1",
"icons/elf_skill/skill_dru22-1",
"icons/elf_skill/skill_dru24-1",
"icons/elf_skill/skill_dru26-1",
"icons/elf_skill/skill_dru28-1",
"icons/elf_skill/skill_dru30-1",
"icons/elf_skill/skill_dru32-1",
"icons/elf_skill/skill_dru34-1",
"icons/elf_skill/skill_dru36-1",
"icons/elf_skill/skill_dru38-1",
"icons/elf_skill/skill_dru4-1",
"icons/elf_skill/skill_dru40-1",
"icons/elf_skill/skill_dru42-1",
"icons/elf_skill/skill_dru44-1",
"icons/elf_skill/skill_dru46-1",
"icons/elf_skill/skill_dru6-1",
"icons/elf_skill/skill_dru8-1",
"icons/elf_skill/skill_dru_mag60",
"icons/elf_skill/skill_dru_mag70",
"icons/elf_skill/skill_dru_new15-1",
"icons/elf_skill/skill_dru_new15-2",
"icons/elf_skill/skill_dru_new15-3",
"icons/elf_skill/skill_dru_new15-4",
"icons/elf_skill/skill_dru_new15-5",
"icons/elf_skill/skill_dru_new20-1",
"icons/elf_skill/skill_dru_new20-2",
"icons/elf_skill/skill_dru_new20-3",
"icons/elf_skill/skill_dru_new20-4",
"icons/elf_skill/skill_dru_new20-5",
"icons/elf_skill/skill_dru_new25-1",
"icons/elf_skill/skill_dru_new25-2",
"icons/elf_skill/skill_dru_new25-3",
"icons/elf_skill/skill_dru_new25-4",
"icons/elf_skill/skill_dru_new25-5",
"icons/elf_skill/skill_dru_new25-6",
"icons/elf_skill/skill_dru_new30-1",
"icons/elf_skill/skill_dru_new35-1",
"icons/elf_skill/skill_dru_new45-1",
"icons/elf_skill/skill_dru_new45-2",
"icons/elf_skill/skill_dru_new45-3",
"icons/elf_skill/skill_dru_new45-4",
"icons/elf_skill/skill_dru_new45-5",
"icons/elf_skill/skill_dru_new50-1",
"icons/elf_skill/skill_dru_new50-2",
"icons/elf_skill/skill_dru_new50-3",
"icons/elf_skill/skill_dru_new50-4",
"icons/elf_skill/skill_dru_new50-5",
"icons/elf_skill/skill_dru_new50-6",
"icons/elf_skill/skill_dru_ran60",
"icons/elf_skill/skill_dru_ran70",
"icons/elf_skill/skill_dru_thi60",
"icons/elf_skill/skill_dru_thi70",
"icons/elf_skill/skill_dru_war60",
"icons/elf_skill/skill_dru_war70",
"icons/elf_skill/skill_dru_ward60",
"icons/elf_skill/skill_dru_ward70",
}
|
if GetBot():IsInvulnerable() or not GetBot():IsHero() or not string.find(GetBot():GetUnitName(), "hero") or GetBot():IsIllusion() then
return;
end
local ability_item_usage_generic = dofile( GetScriptDirectory().."/ability_item_usage_generic" )
local utils = require(GetScriptDirectory() .. "/util")
local mutil = require(GetScriptDirectory() .. "/MyUtility")
function AbilityLevelUpThink()
ability_item_usage_generic.AbilityLevelUpThink();
end
function BuybackUsageThink()
ability_item_usage_generic.BuybackUsageThink();
end
function CourierUsageThink()
ability_item_usage_generic.CourierUsageThink();
end
function ItemUsageThink()
ability_item_usage_generic.ItemUsageThink()
end
local castIFDesire = 0;
local castBSDesire = 0;
local castLBDesire = 0;
local abilityIF = nil;
local abilityBS = nil;
local abilityLB = nil;
local npcBot = nil;
function AbilityUsageThink()
if npcBot == nil then npcBot = GetBot(); end
-- Check if we're already using an ability
if mutil.CanNotUseAbility(npcBot) then return end
if abilityIF == nil then abilityIF = npcBot:GetAbilityByName( "huskar_inner_fire" ) end
if abilityBS == nil then abilityBS = npcBot:GetAbilityByName( "huskar_burning_spear" ) end
if abilityLB == nil then abilityLB = npcBot:GetAbilityByName( "huskar_life_break" ) end
-- Consider using each ability
castIFDesire = ability_item_usage_generic.ConsiderAOERadiusAbility(npcBot, abilityIF);
castBSDesire, castBSTarget = ConsiderBurningSpear();
castLBDesire, castLBTarget = ConsiderLifeBreak();
if ( castIFDesire > 0 )
then
npcBot:Action_UseAbility( abilityIF );
return;
end
if ( castBSDesire > 0 )
then
npcBot:Action_UseAbilityOnEntity( abilityBS, castBSTarget );
return;
end
if ( castLBDesire > castIFDesire and castLBDesire > castBSDesire )
then
npcBot:Action_UseAbilityOnEntity( abilityLB, castLBTarget );
return;
end
end
function ConsiderBurningSpear()
-- Make sure it's castable
if ( not abilityBS:IsFullyCastable() ) then
return BOT_ACTION_DESIRE_NONE, 0;
end
-- Get some of its values
local nCastRange = abilityBS:GetCastRange();
local nDamage = abilityBS:GetAbilityDamage();
local nRadius = 0;
local nAttackRange = npcBot:GetAttackRange();
-- If we're going after someone
if mutil.IsGoingOnSomeone(npcBot)
then
local npcTarget = npcBot:GetTarget();
if mutil.IsValidTarget(npcTarget) and mutil.CanCastOnNonMagicImmune(npcTarget) and mutil.IsInRange(npcTarget, npcBot, nAttackRange+200)
then
return BOT_ACTION_DESIRE_MODERATE, npcTarget;
end
end
return BOT_ACTION_DESIRE_NONE, 0;
end
function ConsiderLifeBreak()
-- Make sure it's castable
if ( not abilityLB:IsFullyCastable() or npcBot:IsRooted() ) then
return BOT_ACTION_DESIRE_NONE, 0;
end
local nCastRange = abilityLB:GetCastRange();
if mutil.IsGoingOnSomeone(npcBot)
then
local npcTarget = npcBot:GetTarget();
if mutil.IsValidTarget(npcTarget) and mutil.CanCastOnNonMagicImmune(npcTarget) and mutil.IsInRange(npcTarget, npcBot, nCastRange+200)
then
return BOT_ACTION_DESIRE_VERYHIGH, npcTarget;
end
end
return BOT_ACTION_DESIRE_NONE, 0;
end
|
local api = vim.api
local logger = require('tabout.logger')
local utils = require('tabout.utils')
local config = require('tabout.config')
local tab = require('tabout.tab')
local M = {}
local enabled = false
--[[ If e.g. a smarttabs expr is used for the completion pmu it is stored here ]]
local completion_binding = ''
local completion_back_binding = ''
local enable = function()
if config.options.tabkey ~= '' then
completion_binding = utils.get_rhs(config.options.tabkey, 'i')
if config.options.completion and completion_binding ~= '' then
logger.debug('setting: ' .. config.options.tabkey ..
':!pumvisible() ? "<Plug>(Tabout)" : ' ..
completion_binding)
api.nvim_set_keymap('i', config.options.tabkey,
'!pumvisible() ? "<Plug>(Tabout)" : ' ..
completion_binding,
{silent = true, expr = true})
else
-- The () are needed to prevent characters from flashing up when multiple plugs are defined
-- TODO: investigate why
api.nvim_set_keymap('i', config.options.tabkey, "<Plug>(Tabout)",
{silent = true})
end
end
if config.options.backwards_tabkey ~= '' and config.options.enable_backwards then
completion_back_binding = utils.get_rhs(config.options.backwards_tabkey,
'i')
if config.options.completion and completion_back_binding ~= '' then
logger.debug('setting: ' .. config.options.backwards_tabkey ..
':!pumvisible() ? "<Plug>(TaboutBack)" : ' ..
completion_back_binding)
api.nvim_set_keymap('i', config.options.backwards_tabkey,
'!pumvisible() ? "<Plug>(TaboutBack)" : ' ..
completion_back_binding, {expr = true})
else
api.nvim_set_keymap('i', config.options.backwards_tabkey,
"<Plug>(TaboutBack)", {silent = true})
end
end
enabled = true
logger.debug("enabled")
end
local disable = function()
logger.debug("unsetting: " .. config.options.tabkey)
if config.options.tabkey ~= '' then
utils.unmap('i', config.options.tabkey)
if config.options.completion and completion_binding ~= '' then
logger.debug("resetting: " .. config.options.tabkey .. ": " ..
completion_binding)
-- a map over noremap since otherwise things like smarttabs with compe and vsnip wont work
api.nvim_set_keymap('i', config.options.tabkey, completion_binding,
{
silent = true,
expr = string.sub(completion_binding, 1, 2) == 'v:'
})
end
end
if config.options.backwards_tabkey ~= '' and config.options.enable_backwards then
logger.debug("unsetting: " .. config.options.backwards_tabkey)
utils.unmap('i', config.options.backwards_tabkey)
if config.options.completion and completion_back_binding ~= '' then
logger.debug("resetting: " .. config.options.backwards_tabkey ..
": " .. completion_back_binding)
-- a map over noremap since otherwise things like smarttabs with compe and vsnip wont work
api.nvim_set_keymap('i', config.options.backwards_tabkey,
completion_back_binding, {
silent = true,
expr = string.sub(completion_back_binding, 1, 2) == 'v:'
})
end
end
enabled = false
logger.debug("disabled")
end
M.valid_filetype = function()
local win = vim.api.nvim_get_current_win()
if not enabled or not vim.api.nvim_win_is_valid(win) then return false end
local buf = vim.api.nvim_win_get_buf(win)
local buftype = api.nvim_buf_get_option(buf, "buftype")
if buftype ~= "" then return false end
local filetype = api.nvim_buf_get_option(buf, "filetype")
if vim.tbl_contains(config.options.exclude, filetype) then return false end
end
--- @param options TaboutOptions
M.setup = function(options)
if not vim.fn.exists(':TSInstall') then
logger.warn('nvim-treesitter is missing')
return
end
config.setup(options)
-- DEPRECATED: Remove after the end of 09/2021
utils.register_command('Tabout',
'lua require"tabout.logger".warn(":Tabout will be deprecated soon, use < Plug >(Tabout) instead") require"tabout".tabout()')
-- DEPRECATED: Remove after the end of 09/2021
utils.register_command('TaboutBack',
'lua require"tabout.logger".warn(":TaboutBack will be deprecated soon, use < Plug >(TaboutBack) instead") require"tabout".taboutBack()')
utils.register_command('TaboutToggle', 'lua require"tabout".toggle()')
-- interfacing via plug api to get more flexibility
utils.map('i', '<Plug>(Tabout)', '<Cmd>lua require("tabout").tabout()<CR>')
utils.map('i', '<Plug>(TaboutMulti)',
'<Cmd>lua require("tabout").taboutMulti()<CR>')
utils.map('i', '<Plug>(TaboutBack)',
'<Cmd>lua require("tabout").taboutBack()<CR>')
utils.map('i', '<Plug>(TaboutBackMulti)',
'<Cmd>lua require("tabout").taboutBackMulti()<CR>')
M.toggle()
end
M.toggle = function()
if enabled then
disable()
else
enable()
end
end
M.tabout = function() tab.tabout('forward', enabled) end
M.taboutMulti = function() tab.tabout('forward', enabled, true) end
M.taboutBack = function() tab.tabout('backward', enabled) end
M.taboutBackMulti = function() tab.tabout('backward', enabled, true) end
return M
|
local ConsumerSorter = {}
function ConsumerSorter:new(consumers, empty_trains, trains_with_resource)
o = {}
setmetatable(o, self)
self.__index = self
-- load in the actual consumer train stops
o.consumers = {}
for resource_type, resources in pairs(consumers) do
if empty_trains[resource_type] == nil and trains_with_resource[resource_type] == nil then
-- early exit
if DEBUG_MODE then
logger(string.format('No trains for resource type %s', resource_type))
end
goto nextresourcetype
end
for resource, resource_consumers in pairs(resources) do
for _, consumer_unit_number in pairs(resource_consumers) do
local consumer = global.conductor.train_stops[consumer_unit_number]
if not is_train_stop_enabled(consumer) then
if DEBUG_MODE then
logger(string.format("Consumer stop %s is disabled", consumer.name))
end
elseif not consumer.entity.valid then
if DEBUG_MODE then
logger(string.format("Consumer stop %s entity is no longer valid", consumer.name))
end
else
table.insert(o.consumers, consumer)
end
end
end
::nextresourcetype::
end
return o
end
function ConsumerSorter:NextConsumer()
local keys = {}
for consumer_index, consumer in pairs(self.consumers) do
if consumer.assigned_trains >= consumer.max_number_of_trains then
-- if supplier does not have available train slots, skip to next supplier
if DEBUG_MODE then
logger(
string.format(
" ... consumer %s already at [%d] maximum number of trains [%d]",
consumer.name,
consumer.assigned_trains,
consumer.max_number_of_trains
)
)
end
else
keys[#keys + 1] = {
consumer_index = consumer_index,
consumer = consumer,
position = global.conductor.consumer_round_robin:get_position(consumer.unit_number)
}
end
end
table.sort(
keys,
function(left, right)
if left.consumer.priority < right.consumer.priority then
return true
elseif left.consumer.priority > right.consumer.priority then
return false
end
if left.consumer.assigned_trains < right.consumer.assigned_trains then
return true
elseif left.consumer.assigned_trains > right.consumer.assigned_trains then
return false
end
-- local left_position = global.conductor.consumer_round_robin:get_position(left.consumer.unit_number)
-- local right_position = global.conductor.consumer_round_robin:get_position(right.consumer.unit_number)
return left.position < right.position
end
)
if keys[1] then
return keys[1].consumer_index, keys[1].consumer
end
end
function ConsumerSorter:RemoveConsumer(index)
table.remove(self.consumers, index)
end
return ConsumerSorter
|
includeFile("tangible/theme_park/myyydril/myyydril_grievous_encounter_manager.lua")
includeFile("tangible/theme_park/myyydril/myyydril_machine.lua")
includeFile("tangible/theme_park/myyydril/myyydril_magic_stone.lua")
includeFile("tangible/theme_park/myyydril/myyydril_power_cell.lua")
|
local MoneyLib = require(game.ReplicatedStorage.MoneyLib)
for i,v in pairs(game.ReplicatedStorage.Items:GetChildren()) do
if v:FindFirstChild("Crystals") then
v.Cost.Value = v.Crystals.Value * 100
end
if v.Cost.ClassName == "StringValue" then
local newValue = MoneyLib.ShortToLong(v.Cost.Value)
v.Cost.Name = "StringCost"
local newCost = Instance.new("NumberValue",v)
newCost.Name = "Cost"
newCost.Value = newValue
end
if v:FindFirstChild("Tier") then
if v.ItemType.Value == 5 then
if v.ReqPoints.Value >= 500000 then
v.Tier.Value = 93
elseif v.ReqPoints.Value >= 75000 then
v.Tier.Value = 92
elseif v.ReqPoints.Value >= 20000 then
v.Tier.Value = 91
else
v.Tier.Value = 90
end
end
-- make crystal items worth it to sell.
if v.ItemType.Value == 7 and v:FindFirstChild("Crystals") then
v.Cost.Value = v.Crystals.Value * 100000
end
if v.ItemType.Value == 4 or (v.ItemType.Value == 7 and v.Tier.Value == 21) then
local Tag = Instance.new("BoolValue")
Tag.Name = "Decoration"
Tag.Parent = v
end
if (v.ItemType.Value < 5 and v.ItemType.Value > 0) or v.ItemType.Value == 11 then
if v.Cost.Value >= 10^50 then
v.Tier.Value = 9
elseif v.Cost.Value >= MoneyLib.ShortToLong("1Ud") then
v.Tier.Value = 8
elseif v.Cost.Value >= MoneyLib.ShortToLong("1O") then
v.Tier.Value = 7
elseif v.Cost.Value >= MoneyLib.ShortToLong("25Qn") then
v.Tier.Value = 6
elseif v.Cost.Value >= MoneyLib.ShortToLong("1qd") then
v.Tier.Value = 5
elseif v.Cost.Value >= MoneyLib.ShortToLong("1T") then
v.Tier.Value = 4
elseif v.Cost.Value >= MoneyLib.ShortToLong("1B") then
v.Tier.Value = 3
elseif v.Cost.Value >= MoneyLib.ShortToLong("1M") then
v.Tier.Value = 2
elseif v.Cost.Value >= MoneyLib.ShortToLong("50k") then
v.Tier.Value = 1
else
v.Tier.Value = 0
end
local Tier = game.ReplicatedStorage.Tiers:FindFirstChild(tostring(v.Tier.Value))
if Tier and Tier:FindFirstChild("ReqPoints") then
v.ReqPoints.Value = Tier.ReqPoints.Value
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.