content
stringlengths 5
1.05M
|
---|
--- Tests a regression with table hashing
local queue, hash = {}, {}
for i = 1, 5e6 do
if math.random() > 0.3 then
local id = math.random(1, 2147483647)
hash[id] = true
queue[#queue + 1] = id
end
if #queue > 1 and math.random() > 0.2 then
local id = table.remove(queue, 1)
hash[id] = nil
end
end
|
local inferencerule = [[\vspace{-2\parskip}\hspace{14pt}\rule{0.3\linewidth}{0.5pt}\vspace{-\parskip}]]
function HorizontalRule(el)
return pandoc.RawBlock('tex', inferencerule)
end |
local eslint = {
lintCommand = "eslint_d -f visualstudio --stdin --stdin-filename ${INPUT}",
lintFormats = {"%f(%l,%c): %tarning %m", "%f(%l,%c): %trror %m"},
lintStdin = true,
lintIgnoreExitCode = true,
lintSource = "eslint",
formatCommand = "eslint_d --fix-to-stdout --stdin --stdin-filename ${INPUT}",
formatStdin = true
}
local jq = {
lintCommand = "jq .",
lintFormats = {"parse %trror: %m at line %l, column %c"},
lintSource = "jq"
}
local prettier = {
formatCommand = 'prettierd "${INPUT}"',
formatStdin = true
}
local shellcheck = {
lintCommand = "shellcheck -f gcc -x -",
lintStdin = true,
lintFormats = {
"%f:%l:%c: %trror: %m", "%f:%l:%c: %tarning: %m", "%f:%l:%c: %tote: %m"
},
lintSource = "shellcheck"
}
return {
css = {prettier},
html = {prettier},
javascript = {prettier, eslint},
javascriptreact = {prettier, eslint},
json = {prettier, jq},
markdown = {prettier},
pandoc = {prettier},
sh = {shellcheck},
typescript = {prettier, eslint},
typescriptreact = {prettier, eslint},
yaml = {prettier}
}
|
local cf = require "cf"
local sys = require "sys"
local collectgarbage = collectgarbage
local fmt = string.format
local u, k = '0.0', '0.0'
local utime, ktime = nil, nil
local USAGE = [[
stat [command] :
[cpu] - CPU kernel space and user space usage of the current process.
[mem] - Memory usage report of the current process.
[page] - `hard_page_fault` and `soft_page_fault` of the current process.
[all] - Return all of the above information.
]]
local CPU = [[
CPU(User): %2.2f%%
CPU(Kernel): %2.2f%%
]]
local MEM = [[
Lua Memory: %s
Swap Memory: %s
Total Memory: %s
]]
local PAGE = [[
Hard Page Faults: %d
Soft Page Faults: %d
]]
cf.at(1, function ()
local info = sys.usage()
if not info then
return
end
local su, sk = info.utime, info.ktime
if not utime or not ktime then
u, k = su, sk
utime, ktime = su, sk
else
u, k = (su - utime) * 1e2, (sk - ktime) * 1e2
utime, ktime = su, sk
end
-- print(u, utime, k, ktime)
end)
local function calc_usage(size)
if size > 1024 * 1024 * 128 then
size = fmt("%.4f/TB", size / 1024 / 1024 / 1024)
elseif size > 1024 * 128 then
size = fmt("%.4f/GB", size / 1024 / 1024)
elseif size > 1024 then
size = fmt("%.4f/MB", size / 1024)
else
size = fmt("%.4f/KB", size)
end
return (size)
end
local function get_info(cpu, mem, page)
local info, err = sys.usage()
if not info then
return fmt("\r\nERROR: %s\r\n", err)
end
local str = ""
if cpu then
str = str .. fmt(CPU, u, k)
end
if mem then
str = str .. fmt(MEM, calc_usage(collectgarbage("count")), calc_usage(sys.os() == 'Linux' and info.swap or info.swap * 1e-3), calc_usage(sys.os() == 'Linux' and info.rss or info.rss * 1e-3))
end
if page then
str = str .. fmt(PAGE, info.hard_page_fault, info.soft_page_fault)
end
return str
end
return function (action)
-- CPU使用率
if action == 'cpu' or action == 'c' then
return get_info(true, false, false)
end
-- 内存使用率
if action == 'mem' or action == 'm' then
return get_info(false, true, false)
end
-- 缺页 (PAGE FAULTS)
if action == 'page' or action == 'p' then
return get_info(false, false, true)
end
-- 获取所有信息
if action == 'all' or action == 'a' then
return get_info(true, true, true)
end
return USAGE
end
|
local symbols = require('symbols-outline.symbols')
local ui = require('symbols-outline.ui')
local config = require('symbols-outline.config')
local M = {}
-- copies an array and returns it because lua usually does references
local function array_copy(t)
local ret = {}
for _, value in ipairs(t) do table.insert(ret, value) end
return ret
end
-- parses result into a neat table
function M.parse(result, depth, heirarchy)
local ret = {}
for index, value in pairs(result) do
-- the heirarchy is basically a table of booleans which tells whether
-- the parent was the last in its group or not
local hir = heirarchy or {}
-- how many parents this node has, 1 is the lowest value because its
-- easier to work it
local level = depth or 1
-- whether this node is the last in its group
local isLast = index == #result
local children = nil
if value.children ~= nil then
-- copy by value because we dont want it messing with the hir table
local child_hir = array_copy(hir)
table.insert(child_hir, isLast)
children = M.parse(value.children, level + 1, child_hir)
end
-- support SymbolInformation[]
-- https://microsoft.github.io/language-server-protocol/specification#textDocument_documentSymbol
local selectionRange = value.selectionRange
if value.selectionRange == nil then
selectionRange = value.location.range
end
local range = value.range
if value.range == nil then
range = value.location.range
end
table.insert(ret, {
deprecated = value.deprecated,
kind = value.kind,
icon = symbols.icon_from_kind(value.kind),
name = value.name,
detail = value.detail,
line = selectionRange.start.line,
character = selectionRange.start.character,
range_start = range.start.line,
range_end = range["end"].line,
children = children,
depth = level,
isLast = isLast,
heirarchy = hir
});
end
return ret
end
function M.flatten(outline_items)
local ret = {}
for _, value in ipairs(outline_items) do
table.insert(ret, value)
if value.children ~= nil then
local inner = M.flatten(value.children)
for _, value_inner in ipairs(inner) do
table.insert(ret, value_inner)
end
end
end
return ret
end
local function table_to_str(t)
local ret = ""
for _, value in ipairs(t) do ret = ret .. tostring(value) end
return ret
end
local function str_to_table(str)
local t = {}
for i = 1, #str do t[i] = str:sub(i, i) end
return t
end
function M.get_lines(flattened_outline_items)
local lines = {}
for _, value in ipairs(flattened_outline_items) do
local line = str_to_table(string.rep(" ", value.depth))
if config.options.show_guides then
-- makes the guides
for index, _ in ipairs(line) do
-- all items start with a space (or two)
if index == 1 then
line[index] = " "
-- if index is last, add a bottom marker if current item is last,
-- else add a middle marker
elseif index == #line then
if value.isLast then
line[index] = ui.markers.bottom
else
line[index] = ui.markers.middle
end
-- else if the parent was not the last in its group, add a
-- vertical marker because there are items under us and we need
-- to point to those
elseif not value.heirarchy[index] then
line[index] = ui.markers.vertical
end
end
end
local final_prefix = {}
-- Add 1 space between the guides
for _, v in ipairs(line) do
table.insert(final_prefix, v)
table.insert(final_prefix, " ")
end
table.insert(lines, table_to_str(final_prefix) .. value.icon .. " " ..
value.name)
end
return lines
end
function M.get_details(flattened_outline_items)
local lines = {}
for _, value in ipairs(flattened_outline_items) do
table.insert(lines, value.detail or "")
end
return lines
end
return M
|
local S
if (minetest.get_modpath("intllib")) then
S = intllib.Getter()
else
S = function(s,a,...)a={a,...}return s:gsub("@(%d+)",function(n)return a[tonumber(n)]end)end
end
local whereami = {}
whereami.playerhuds = {}
whereami.settings = {}
whereami.settings.hud_pos = { x = 0.5, y = 0 }
whereami.settings.hud_offset = { x = 0, y = 15 }
whereami.settings.hud_alignment = { x = 0, y = 0 }
local set = tonumber(minetest.setting_get("whereami_hud_pos_x"))
if set then whereami.settings.hud_pos.x = set end
set = tonumber(minetest.setting_get("whereami_hud_pos_y"))
if set then whereami.settings.hud_pos.y = set end
set = tonumber(minetest.setting_get("whereami_hud_offset_x"))
if set then whereami.settings.hud_offset.x = set end
set = tonumber(minetest.setting_get("whereami_hud_offset_y"))
if set then whereami.settings.hud_offset.y = set end
set = minetest.setting_get("whereami_hud_alignment")
if set == "left" then
whereami.settings.hud_alignment.x = 1
elseif set == "center" then
whereami.settings.hud_alignment.x = 0
elseif set == "right" then
whereami.settings.hud_alignment.x = -1
end
function whereami.init_hud(player)
local name = player:get_player_name()
whereami.playerhuds[name] = player:hud_add({
hud_elem_type = "text",
text = "",
position = whereami.settings.hud_pos,
offset = { x = whereami.settings.hud_offset.x, y = whereami.settings.hud_offset.y },
alignment = whereami.settings.hud_alignment,
number = 0xFFFFFF,
scale= { x = 100, y = 20 },
})
end
function whereami.update_hud_displays(player)
local name = player:get_player_name()
local pos = vector.round(player:getpos())
player:hud_change(
whereami.playerhuds[name],
"text",
S("@1 Coordinates: X=@2, Y=@3, Z=@4",name, pos.x, pos.y, pos.z)
)
end
minetest.register_on_newplayer(whereami.init_hud)
minetest.register_on_joinplayer(whereami.init_hud)
minetest.register_on_leaveplayer(function(player)
whereami.playerhuds[player:get_player_name()] = nil
end)
local updatetimer = 0
minetest.register_globalstep(function(dtime)
updatetimer = updatetimer + dtime
if updatetimer > 0.1 then
local players = minetest.get_connected_players()
for i=1, #players do
whereami.update_hud_displays(players[i])
end
updatetimer = updatetimer - dtime
end
end)
|
local redis = require "resty.redis"
local m = {}
function m.get()
local red = redis:new()
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.say("failed to connect: ", err)
return nil
end
return red
end
function m.call(callback, ...)
local red = m.get()
if not red then
return nil
end
local res = callback(red, ...)
--local ok, err = red:set_keepalive(10000, 100)
--if not ok then
-- ngx.say("failed to set keepalive: ", err)
-- return nil
--end
return res
end
return m
|
local cmp = require("cmp")
local lspkind = {
Text = "",
Method = "",
Function = "",
Constructor = "",
Field = "ﰠ",
Variable = "",
Class = "ﴯ",
Interface = "",
Module = "",
Property = "ﰠ",
Unit = "塞",
Value = "",
Enum = "",
Keyword = "",
Snippet = "",
Color = "",
File = "",
Reference = "",
Folder = "",
EnumMember = "",
Constant = "",
Struct = "פּ",
Event = "",
Operator = "",
TypeParameter = "",
}
local border = require("plugins.lsp.utils").border
cmp.setup({
documentation = {
border = border,
winhighlight = "Normal:FloatBorder",
},
experimental = {
ghost_text = false,
},
snippet = {
expand = function(args)
vim.fn["UltiSnips#Anon"](args.body)
end,
},
formatting = {
deprecated = true,
format = function(entry, vim_item)
vim_item.kind = lspkind[vim_item.kind] .. " " .. vim_item.kind
vim_item.menu = ({
buffer = "[Buffer]",
path = "[Path]",
nvim_lsp = "[LSP]",
luasnip = "[LuaSnip]",
user_dictionary = "[Dictionary]",
})[entry.source.name]
vim_item.dup = ({
buffer = 0,
})[entry.source.name] or 1
return vim_item
end,
},
mapping = {
["<C-d>"] = cmp.mapping(cmp.mapping.scroll_docs(-4), { "i", "c" }),
["<C-f>"] = cmp.mapping(cmp.mapping.scroll_docs(4), { "i", "c" }),
["<C-e>"] = cmp.mapping({
i = cmp.mapping.abort(),
c = cmp.mapping.close(),
}),
["<C-y>"] = cmp.config.disable,
["<CR>"] = cmp.mapping.confirm({ select = true }),
},
sources = cmp.config.sources({
{ name = "nvim_lsp", max_item_count = 20 },
{ name = "ultisnips", max_item_count = 2 },
{ name = "buffer", max_item_count = 4 },
{ name = "path" },
{ name = "nvim_lua" },
}),
})
|
local ATTACH_REQUEST_KEY = "attached-to-passive-element"
local DRIVER_REQUEST_KEY = "driven-by-passive-element"
local OCCUPANT_REQUEST_KEY = "occupying-passive-vehicle"
local TOWING_REQUEST_KEY = "towed-by-passive-element"
local function elementPassiveModePreChangeHandler(enabled)
if enabled then
-- no special cases for enabling passive mode
return
end
local elementType = getElementType(source)
if elementType == "vehicle" then
local driver = getVehicleOccupant(source)
if driver and doesPassiveRequestExist(driver, OCCUPANT_REQUEST_KEY) then
for key, _ in pairs(getPassiveRequests(driver)) do
if key ~= OCCUPANT_REQUEST_KEY then
-- the driver will lose passive mode request inherited from the
-- vehicle, but they also have other passive mode requests, so they
-- will remain passive and now the vehicle will inherit passive from
-- the driver
cancelEvent()
removePassiveRequest(driver, OCCUPANT_REQUEST_KEY)
createPassiveRequest(source, DRIVER_REQUEST_KEY)
break
end
end
end
elseif elementType == "ped" or elementType == "player" then
local vehicle = getPedDrivenVehicle(source)
if vehicle and doesPassiveRequestExist(vehicle, DRIVER_REQUEST_KEY) then
for key, _ in pairs(getPassiveRequests(vehicle)) do
if key ~= DRIVER_REQUEST_KEY then
-- the vehicle will lose passive mode request inherited from the
-- driver, but it also has other passive mode requests, so it
-- will remain passive and now the driver will inherit passive
-- from the vehicle
cancelEvent()
removePassiveRequest(vehicle, DRIVER_REQUEST_KEY)
createPassiveRequest(source, OCCUPANT_REQUEST_KEY)
break
end
end
end
end
end
addEventHandler(
"onElementPassiveModePreChange", root, elementPassiveModePreChangeHandler
)
local function elementPassiveModeChangeHandler(enabled)
local elementType = getElementType(source)
-- attached elements inheritance
if enabled then
for _, element in ipairs(getAttachedElements(source)) do
if canElementTypeBePassive(getElementType(element)) then
createPassiveRequest(element, ATTACH_REQUEST_KEY)
end
end
else
for _, element in ipairs(getAttachedElements(source)) do
if doesPassiveRequestExist(element, ATTACH_REQUEST_KEY) then
removePassiveRequest(element, ATTACH_REQUEST_KEY)
end
end
end
if elementType == "vehicle" then
-- vehicle occupant inheritance
local occupants = getVehicleOccupants(source)
if occupants then
if enabled then
-- occupants should now inherit passive from the vehicle
for seat, occupant in pairs(occupants) do
if seat == 0 and doesPassiveRequestExist(source, DRIVER_REQUEST_KEY) then
-- skip the driver from whom the vehicle is inheriting passive
else
createPassiveRequest(occupant, OCCUPANT_REQUEST_KEY)
end
end
else
-- occupants should now stop inheriting passive from the vehicle
for seat, occupant in pairs(occupants) do
if doesPassiveRequestExist(occupant, OCCUPANT_REQUEST_KEY) then
removePassiveRequest(occupant, OCCUPANT_REQUEST_KEY)
end
end
end
end
-- towed vehicle inheritance
local towedVehicle = getVehicleTowedByVehicle(source)
if towedVehicle then
if enabled then
createPassiveRequest(towedVehicle, TOWING_REQUEST_KEY)
elseif doesPassiveRequestExist(towedVehicle, TOWING_REQUEST_KEY) then
removePassiveRequest(towedVehicle, TOWING_REQUEST_KEY)
end
end
elseif elementType == "ped" or elementType == "player" then
-- vehicle driver inheritance
local vehicle = getPedDrivenVehicle(source)
if vehicle then
if enabled then
-- the vehicle should now inherit passive from the driver, unless the
-- driver is inheriting passive mode from the vehicle
if not doesPassiveRequestExist(source, OCCUPANT_REQUEST_KEY) then
createPassiveRequest(vehicle, DRIVER_REQUEST_KEY)
end
else
-- the vehicle should now stop inheriting passive from the driver
if doesPassiveRequestExist(vehicle, DRIVER_REQUEST_KEY) then
removePassiveRequest(vehicle, DRIVER_REQUEST_KEY)
end
end
end
end
end
addEventHandler("onElementPassiveModeChange", root, elementPassiveModeChangeHandler)
local function vehicleEnterHandler(ped, seat)
if seat == 0 and isElementPassive(ped) then
-- passive ped/player entering driver seat - vehicle inherits passive mode
createPassiveRequest(source, DRIVER_REQUEST_KEY)
elseif isElementPassive(source) then
-- ped/player entering a passive vehicle - ped/player inherits passive mode
createPassiveRequest(ped, OCCUPANT_REQUEST_KEY)
end
end
addEventHandler("onVehicleEnter", root, vehicleEnterHandler)
local function vehicleExitHandler(ped, seat)
if seat == 0 and doesPassiveRequestExist(source, DRIVER_REQUEST_KEY) then
-- vehicle stops inheriting passive mode from passive driver
removePassiveRequest(source, DRIVER_REQUEST_KEY)
elseif doesPassiveRequestExist(ped, OCCUPANT_REQUEST_KEY) then
-- ped/player stops inheriting passive mode from passive vehicle
removePassiveRequest(ped, OCCUPANT_REQUEST_KEY)
end
end
addEventHandler("onVehicleExit", root, vehicleExitHandler)
local function pedWastedHandler()
local vehicle = getPedOccupiedVehicle(source)
if not vehicle then return end
if getPedOccupiedVehicleSeat(source) == 0 and
doesPassiveRequestExist(vehicle, DRIVER_REQUEST_KEY) then
-- vehicle stops inheriting passive mode from passive driver
removePassiveRequest(vehicle, DRIVER_REQUEST_KEY)
elseif doesPassiveRequestExist(source, OCCUPANT_REQUEST_KEY) then
-- ped/player stops inheriting passive mode from passive vehicle
removePassiveRequest(source, OCCUPANT_REQUEST_KEY)
end
end
addEventHandler("onPedWasted", root, pedWastedHandler)
addEventHandler("onPlayerWasted", root, pedWastedHandler)
local function trailerAttachHandler(towingVehicle)
-- source is towed by towingVehicle
if isElementPassive(towingVehicle) then
createPassiveRequest(source, TOWING_REQUEST_KEY)
end
end
addEventHandler("onTrailerAttach", root, trailerAttachHandler)
local function trailerDetachHandler(towingVehicle)
-- source is towed by towingVehicle
if doesPassiveRequestExist(source, TOWING_REQUEST_KEY) then
removePassiveRequest(source, TOWING_REQUEST_KEY)
end
end
addEventHandler("onTrailerDetach", root, trailerDetachHandler)
|
-- Just an example, supposed to be placed in /lua/custom/
local M = {}
-- make sure you maintain the structure of `core/default_config.lua` here,
-- example of changing theme:
M.ui = {
theme = "gruvchad",
}
local userPlugins = require "custom.plugins" -- path to table
M.plugins = {
install = userPlugins
}
return M
|
data:extend({
{
type = "item-subgroup",
name = "throwers",
group = "logistics",
order = "ca"
},
{
type = "item-subgroup",
name = "RT",
group = "logistics",
order = "cb"
}
}) |
require("tech-updates")
require("zirconium-recipe-updates")
require("zircon-matter")
require("map-gen-preset-updates")
require("omni")
require("strange-matter")
local util = require("__bzzirconium__.data-util");
util.add_minable_result("simple-entity", "rock-huge", {name="zircon", amount_min = 15, amount_max=25})
util.add_minable_result("simple-entity", "sand-rock-big", {name="zircon", amount_min = 15, amount_max=25})
util.add_minable_result("simple-entity", "rock-big", {name="zircon", amount_min = 15, amount_max=25})
|
--- cpp extensions
-- @author [Alejandro Baez](https://twitter.com/a_baez)
-- @coypright 2015
-- @license MIT (see LICENSE)
-- @module cpp
local snipping = {
true,
-- functions and structs
fn = '%1(T) %2(name)(%3(arguments))%4(;)',
struct = "struct %1(name) %2(;)",
enum = "enum %1(name) %2(;)",
["type"] = "typedef %1(type) %2(alias);%0",
union = "union %1(type_name) {\n\t%0\n} %2( object_name);",
template = "template <class %1(T)>\n%1 %2(name)(%3param) \n{\n\t%0\n}",
tem = "template <typename %1(T)>\n%0",
-- class details
class = "class %1(name) %2(;)",
public = "public:\n\t%0",
private = "private:\n\t%0",
protected = "protected:\n\t%0",
-- random
['in'] = '#include %1(<%2(name)>)%0',
['/*'] = "/*\n * %0\n */",
['{'] = "{\n\t%0\n",
['def'] = '#ifndef %1(name)\n#define %1\n%0\n#endif // %1',
-- conditional
['for'] = 'for (%1(i) = %2(0); %1 %3(<) %4(10); %5(%1++)) {\n\t%0\n}',
['while'] = 'while (%1(expr)) {\n\t%0\n}',
['do'] = 'do {\n\t%1\n} while (%2); %0',
-- if
['if'] = 'if (%1(expr)) {\n\t%2\n} %0',
['else'] = 'else {\n\t%0\n}',
['switch'] = 'switch (%1(expr)) {\n%1\ndefault:\n\t%0\n}',
['case'] = 'case %1(expr):\n\t%2\n%0',
}
local function connecting()
--- settings to enable on connect
buffer.tab_width = 4
buffer.use_tabs = false
buffer.edge_column = 79
end
return {
connecting = connecting,
snipping = snipping
}
|
--------------------------------
-- @module CompareFunction
-- @parent_module ccb
--- Enum ccb.CompareFunction
---@class ccb.CompareFunction
local CompareFunction = {}
ccb.CompareFunction = CompareFunction
---@type number
CompareFunction.NEVER = 0
---@type number
CompareFunction.LESS = 1
---@type number
CompareFunction.LESS_EQUAL = 2
---@type number
CompareFunction.GREATER = 3
---@type number
CompareFunction.GREATER_EQUAL = 4
---@type number
CompareFunction.EQUAL = 5
---@type number
CompareFunction.NOT_EQUAL = 6
---@type number
CompareFunction.ALWAYS = 7
return nil
|
object_tangible_loot_npc_loot_healing_chemical_generic = object_tangible_loot_npc_loot_shared_healing_chemical_generic:new {
}
ObjectTemplates:addTemplate(object_tangible_loot_npc_loot_healing_chemical_generic, "object/tangible/loot/npc/loot/healing_chemical_generic.iff")
|
-- Standard awesome library
local gears = require("gears")
local awful = require("awful")
local hotkeys_popup = require("awful.hotkeys_popup")
-- Theme handling library
local beautiful = require("beautiful")
-- Theme library
local beautiful = require("beautiful")
local xresources = require("beautiful.xresources")
local dpi = xresources.apply_dpi
-- Notifications library
local naughty = require("naughty")
-- Bling
local bling = require("module.bling")
local playerctl = bling.signal.playerctl.lib()
-- Machi
local machi = require("module.layout-machi")
-- Helpers
local helpers = require("helpers")
-- Default modkey.
modkey = "Mod4"
alt = "Mod1"
ctrl = "Control"
shift = "Shift"
-- Launcher
awful.keyboard.append_global_keybindings({
awful.key({modkey}, "Return", function()
awful.spawn(terminal)
end,
{description = "open terminal", group = "launcher"}),
awful.key({modkey}, "d", function()
awful.spawn(launcher)
end,
{description = "open applications menu", group = "launcher"}),
awful.key({modkey, shift}, "d", function()
dashboard_toggle()
end,
{description = "toggle dashboard", group = "launcher"}),
awful.key({modkey}, "f", function()
awful.spawn(file_manager)
end,
{description = "open file manager", group = "launcher"}),
awful.key({modkey}, "w", function()
awful.spawn.with_shell(browser)
end,
{description = "open web browser", group = "launcher"}),
awful.key({modkey}, "x", function()
awful.spawn.with_shell("xcolor-pick")
end,
{description = "open color-picker", group = "launcher"})
})
-- Client and Tabs Bindings
awful.keyboard.append_global_keybindings({
awful.key({alt}, "a", function()
bling.module.tabbed.pick_with_dmenu()
end,
{description = "pick client to add to tab group", group = "tabs"}),
awful.key({alt}, "s", function()
bling.module.tabbed.iter()
end,
{description = "iterate through tabbing group", group = "tabs"}),
awful.key({alt}, "d", function()
bling.module.tabbed.pop()
end,
{description = "remove focused client from tabbing group",group = "tabs"}),
awful.key({modkey}, "Down", function()
awful.client.focus.bydirection("down")
bling.module.flash_focus.flashfocus(client.focus)
end,
{description = "focus down", group = "client"}),
awful.key({modkey}, "Up", function()
awful.client.focus.bydirection("up")
bling.module.flash_focus.flashfocus(client.focus)
end,
{description = "focus up", group = "client"}),
awful.key({modkey}, "Left", function()
awful.client.focus.bydirection("left")
bling.module.flash_focus.flashfocus(client.focus)
end,
{description = "focus left", group = "client"}),
awful.key({modkey}, "Right", function()
awful.client.focus.bydirection("right")
bling.module.flash_focus.flashfocus(client.focus)
end,
{description = "focus right", group = "client"}),
awful.key({modkey}, "j", function()
awful.client.focus.byidx(1)
end,
{description = "focus next by index", group = "client"}),
awful.key({modkey}, "k", function()
awful.client.focus.byidx(-1)
end,
{description = "focus previous by index", group = "client"}),
awful.key({modkey, "Shift"}, "j", function()
awful.client.swap.byidx(1)
end,
{description = "swap with next client by index", group = "client"}),
awful.key({modkey, "Shift"}, "k", function()
awful.client.swap.byidx(-1)
end,
{description = "swap with previous client by index", group = "client"}),
awful.key({modkey}, "u",
awful.client.urgent.jumpto,
{description = "jump to urgent client", group = "client"}),
awful.key({alt}, "Tab", function()
awesome.emit_signal("bling::window_switcher::turn_on")
end,
{description = "window switcher", group = "client"})
})
-- Hotkeys
awful.keyboard.append_global_keybindings({
-- Brightness Control
awful.key({}, "XF86MonBrightnessUp", function()
awful.spawn("brightnessctl set 5%+ -q")
end,
{description = "increase brightness", group = "hotkeys"}),
awful.key({}, "XF86MonBrightnessDown", function()
awful.spawn("brightnessctl set 5%- -q")
end,
{description = "decrease brightness", group = "hotkeys"}),
-- Volume control
awful.key({}, "XF86AudioRaiseVolume", function()
helpers.volume_control(5)
end,
{description = "increase volume", group = "hotkeys"}),
awful.key({}, "XF86AudioLowerVolume", function()
helpers.volume_control(-5)
end,
{description = "decrease volume", group = "hotkeys"}),
awful.key({}, "XF86AudioMute", function()
helpers.volume_control(0)
end,
{description = "mute volume", group = "hotkeys"}),
-- Music
awful.key({}, "XF86AudioPlay", function()
playerctl:play_pause()
end,
{description = "toggle music", group = "hotkeys"}),
awful.key({}, "XF86AudioPrev", function()
playerctl:previous()
end,
{description = "previous music", group = "hotkeys"}),
awful.key({}, "XF86AudioNext", function()
playerctl:next()
end,
{description = "next music", group = "hotkeys"}),
-- Screenshots
awful.key({}, "Print", function()
awful.spawn.with_shell("screensht full")
end,
{description = "take a full screenshot", group = "hotkeys"}),
awful.key({alt}, "Print", function()
awful.spawn.with_shell("screensht area")
end,
{description = "take a area screenshot", group = "hotkeys"}),
-- Flameshot screenshot
awful.key({modkey, ctrl}, "s", function()
awful.spawn.with_shell("flameshot gui")
end,
{description = "Takes Flameshot screenshot", group = "hotkeys"}),
-- Lockscreen
awful.key({modkey, ctrl}, "l", function()
lock_screen_show()
end,
{description = "lock screen", group = "hotkeys"})
})
-- Awesome stuff
awful.keyboard.append_global_keybindings({
awful.key({modkey}, "F1",
hotkeys_popup.show_help,
{description = "show help", group = "awesome"}),
awful.key({modkey, ctrl}, "r",
awesome.restart,
{description = "reload awesome", group = "awesome"}),
awful.key({modkey, ctrl}, "q",
awesome.quit,
{description = "quit awesome", group = "awesome"})
})
-- Layout Machi
awful.keyboard.append_global_keybindings({
awful.key({modkey}, ".", function()
machi.default_editor.start_interactive()
end,
{description = "edit the current layout if it is a machi layout", group = "layout"}),
awful.key({modkey}, "/", function()
machi.switcher.start(client.focus)
end,
{description = "switch between windows for a machi layout", group = "layout"})
})
awful.keyboard.append_global_keybindings({
-- Screen
awful.key({modkey, "Control"}, "j", function()
awful.screen.focus_relative(1)
end,
{description = "focus the next screen", group = "screen"}),
awful.key({modkey, "Control"}, "k", function()
awful.screen.focus_relative(-1)
end,
{description = "focus the previous screen", group = "screen"}),
-- Layout
awful.key({modkey}, "l", function()
awful.tag.incmwfact(0.05)
end,
{description = "increase master width factor", group = "layout"}),
awful.key({modkey}, "h", function()
awful.tag.incmwfact(-0.05)
end,
{description = "decrease master width factor", group = "layout"}),
awful.key({modkey, "Shift"}, "h", function()
awful.tag.incnmaster(1, nil, true)
end,
{description = "increase the number of master clients", group = "layout"}),
awful.key({modkey, "Shift"}, "l", function()
awful.tag.incnmaster(-1, nil, true)
end,
{description = "decrease the number of master clients", group = "layout"}),
awful.key({modkey, "Control"}, "h", function()
awful.tag.incncol(1, nil, true)
end,
{description = "increase the number of columns", group = "layout"}),
awful.key({modkey, "Control"}, "l", function()
awful.tag.incncol(-1, nil, true)
end,
{description = "decrease the number of columns", group = "layout"}),
awful.key({modkey}, "space", function()
awful.layout.inc(1)
end,
{description = "select next layout", group = "layout"}),
awful.key({modkey, "Shift"}, "space", function()
awful.layout.inc(-1)
end,
{description = "select previous layout", group = "layout"}),
-- Tag
awful.key({ modkey, alt}, "Left",
awful.tag.viewprev,
{description = "view previous", group = "tag"}),
awful.key({ modkey, alt}, "Right",
awful.tag.viewnext,
{description = "view next", group = "tag"}),
awful.key({ modkey}, "Escape",
awful.tag.history.restore,
{description = "go back", group = "tag"}),
-- Set Layout
awful.key({modkey, "Control"}, "w", function()
awful.layout.set(awful.layout.suit.max)
end,
{description = "set max layout", group = "tag"}),
awful.key({modkey}, "s", function()
awful.layout.set(awful.layout.suit.tile)
end,
{description = "set tile layout", group = "tag"}),
awful.key({modkey, shift}, "s", function()
awful.layout.set(awful.layout.suit.floating)
end,
{description = "set floating layout", group = "tag"}),
--Client
awful.key({modkey, "Control"}, "n", function()
local c = awful.client.restore()
-- Focus restored client
if c then
c:emit_signal("request::activate", "key.unminimize", {raise = true})
end
end,
{description = "restore minimized", group = "client"})
})
-- Client management keybinds
client.connect_signal("request::default_keybindings", function()
awful.keyboard.append_client_keybindings({
awful.key({modkey, "Shift"}, "f", function(c)
c.fullscreen = not c.fullscreen
c:raise()
end,
{description = "toggle fullscreen", group = "client"}),
awful.key({modkey}, "q", function(c)
c:kill()
end,
{description = "close", group = "client"}),
awful.key({modkey, "Control"}, "space",
awful.client.floating.toggle,
{description = "toggle floating", group = "client"}),
awful.key({modkey, "Control"}, "Return", function(c)
c:swap(awful.client.getmaster())
end,
{description = "move to master", group = "client"}),
awful.key({modkey}, "o", function(c)
c:move_to_screen() end,
{description = "move to screen", group = "client"}),
awful.key({modkey, shift}, "b", function(c)
c.floating = not c.floating
c.width = 400
c.height = 200
awful.placement.bottom_right(c)
c.sticky = not c.sticky
end,
{description = "toggle keep on top", group = "client"}),
awful.key({modkey}, "n", function(c)
-- The client currently has the input focus, so it cannot be
-- minimized, since minimized clients can't have the focus.
c.minimized = true
end, {description = "minimize", group = "client"}),
awful.key({modkey}, "m", function(c)
c.maximized = not c.maximized
c:raise()
end, {description = "(un)maximize", group = "client"}),
awful.key({modkey, "Control"}, "m", function(c)
c.maximized_vertical = not c.maximized_vertical
c:raise()
end, {description = "(un)maximize vertically", group = "client"}),
awful.key({modkey, "Shift"}, "m", function(c)
c.maximized_horizontal = not c.maximized_horizontal
c:raise()
end, {description = "(un)maximize horizontally", group = "client"}),
-- On the fly padding change
awful.key({modkey, shift}, "=",
function() helpers.resize_padding(5) end,
{description = "add padding", group = "screen"}),
awful.key({modkey, shift}, "-",
function() helpers.resize_padding(-5) end,
{description = "subtract padding", group = "screen"}),
-- On the fly useless gaps change
awful.key({modkey}, "=", function() helpers.resize_gaps(5) end,
{description = "add gaps", group = "screen"}),
awful.key({modkey}, "-", function() helpers.resize_gaps(-5) end,
{description = "subtract gaps", group = "screen"}),
-- Single tap: Center client
-- Double tap: Center client + Floating + Resize
awful.key({modkey}, "c", function(c)
awful.placement.centered(c, {
honor_workarea = true,
honor_padding = true
})
helpers.single_double_tap(nil, function()
helpers.float_and_resize(c, screen_width * 0.25,
screen_height * 0.28)
end)
end)
})
end)
-- Num row keybinds
awful.keyboard.append_global_keybindings({
awful.key {
modifiers = {modkey},
keygroup = "numrow",
description = "only view tag",
group = "tag",
on_press = function(index)
local screen = awful.screen.focused()
local tag = screen.tags[index]
if tag then tag:view_only() end
end
}, awful.key {
modifiers = {modkey, "Control"},
keygroup = "numrow",
description = "toggle tag",
group = "tag",
on_press = function(index)
local screen = awful.screen.focused()
local tag = screen.tags[index]
if tag then awful.tag.viewtoggle(tag) end
end
}, awful.key {
modifiers = {modkey, "Shift"},
keygroup = "numrow",
description = "move focused client to tag",
group = "tag",
on_press = function(index)
if client.focus then
local tag = client.focus.screen.tags[index]
if tag then client.focus:move_to_tag(tag) end
end
end
}, awful.key {
modifiers = {modkey, "Control", "Shift"},
keygroup = "numrow",
description = "toggle focused client on tag",
group = "tag",
on_press = function(index)
if client.focus then
local tag = client.focus.screen.tags[index]
if tag then client.focus:toggle_tag(tag) end
end
end
}
})
-- Mouse bindings on desktop
------------------------------
awful.mouse.append_global_mousebindings({
-- Left click
awful.button({}, 1, function()
naughty.destroy_all_notifications()
if mymainmenu then
mymainmenu:hide()
end
end),
-- Middle click
awful.button({}, 2, function()
dashboard_toggle()
end),
-- Right click
awful.button({}, 3, function()
mymainmenu:toggle()
end),
-- Side key
awful.button({}, 4, awful.tag.viewprev),
awful.button({}, 5, awful.tag.viewnext)
})
-- Mouse buttons on the client
--------------------------------
client.connect_signal("request::default_mousebindings", function()
awful.mouse.append_client_mousebindings({
awful.button({}, 1, function(c)
c:activate{context = "mouse_click"}
end),
awful.button({modkey}, 1, function(c)
c:activate{context = "mouse_click", action = "mouse_move"}
end),
awful.button({modkey}, 3, function(c)
c:activate{context = "mouse_click", action = "mouse_resize"}
end)
})
end)
|
local M = {}
--- Fix a filename to ensure that it doesn't contain any illegal characters
-- @param filename
-- @return Filename with illegal characters replaced
local function fix(filename)
filename = filename:gsub("([^0-9a-zA-Z%._ ])", function(c) return string.format("%%%02X", string.byte(c)) end)
filename = filename:gsub(" ", "+")
return filename
end
--- Get an application specific save file path to a filename. The path will be
-- based on the sys.get_save_file() function and the project title (with whitespace)
-- replaced by underscore
-- @param filename
-- @return Save file path
local function get_save_file_path(filename)
local path = sys.get_save_file(fix(sys.get_config("project.title"):gsub(" ", "_")), filename)
return path
end
local function load_image(url, cb)
local filename = url
local path = get_save_file_path(filename)
http.request(url, "GET", function(self, id, response)
local image_data = response.response
if response.status == 200 then
local f = io.open(path, "wb")
if f then
f:write(image_data)
f:flush()
f:close()
end
elseif response.status == 304 then
if not image_data then
local f = io.open(path, "rb")
image_data = f:read("*a")
f:close()
end
else
image_data = nil
end
if image_data then
image_data = image.load(image_data)
end
cb(image_data)
end)
end
function M.create()
return {
node_to_url = {},
url_to_image = {},
}
end
function M.clear(cache)
for url,_ in pairs(cache.url_to_image) do
gui.delete_texture(url)
end
url_to_image = {}
node_to_url = {}
end
function M.load(cache, url, node, cb)
assert(url, "You must provide a url")
assert(node, "You must provide a node")
-- is the node using another texture?
-- remove texture refence and unload if it is no longer in use
local url_on_node = cache.node_to_url[node]
if url_on_node and url_on_node ~= url then
local img = cache.url_to_image[url_on_node]
cache.node_to_url[node] = nil
img.nodes[node] = nil
if not next(img.nodes) and img.loaded then
gui.delete_texture(url_on_node)
cache.url_to_image[url_on_node] = nil
end
end
-- has the url already been loaded
local img = cache.url_to_image[url]
if not img then
img = {
url = url,
nodes = {},
loading = false,
loaded = false,
}
cache.url_to_image[url] = img
end
-- associate the node with the image
cache.node_to_url[node] = url
img.nodes[node] = true
if not img.loading then
if not img.loaded then
img.loading = true
load_image(url, function(image_data)
img.loaded = true
img.loading = false
if not image_data then
print("Unable to load image")
else
gui.new_texture(url, image_data.width, image_data.height, image_data.type, image_data.buffer, false)
for n,_ in pairs(img.nodes) do
gui.set_texture(n, url)
end
end
if cb then cb() end
end)
else
for n,_ in pairs(img.nodes) do
gui.set_texture(n, url)
end
if cb then cb() end
end
end
end
return M |
object_tangible_component_bio_base_bio_component_armor = object_tangible_component_bio_shared_base_bio_component_armor:new {
}
ObjectTemplates:addTemplate(object_tangible_component_bio_base_bio_component_armor, "object/tangible/component/bio/base_bio_component_armor.iff")
|
-- Created by Elfansoer
--[[
Ability checklist (erase if done/checked):
- Scepter Upgrade
- Break behavior
- Linken/Reflect behavior
- Spell Immune/Invulnerable/Invisible behavior
- Illusion behavior
- Stolen behavior
]]
--------------------------------------------------------------------------------
modifier_midas_golden_valkyrie_passive = class({})
--------------------------------------------------------------------------------
-- Classifications
function modifier_midas_golden_valkyrie_passive:IsHidden()
return true
end
function modifier_midas_golden_valkyrie_passive:IsPurgable()
return false
end
function modifier_midas_golden_valkyrie_passive:GetAttributes()
return MODIFIER_ATTRIBUTE_PERMANENT
end
--------------------------------------------------------------------------------
-- Initializations
function modifier_midas_golden_valkyrie_passive:OnCreated( kv )
end
function modifier_midas_golden_valkyrie_passive:AddBit( bit )
self:SetStackCount( flag:Add( self:GetStackCount(), bit ) )
end
function modifier_midas_golden_valkyrie_passive:HasBit( bit )
return flag:Exist( self:GetStackCount(), bit )
end
--------------------------------------------------------------------------------
-- Helper: flag Calculations
if not flag then
flag = {}
end
-- Returns true if flag b is within state a
function flag:Exist(a,b)
local p,c,d=1,0,b
while a>0 and b>0 do
local ra,rb=a%2,b%2
if ra+rb>1 then c=c+p end
a,b,p=(a-ra)/2,(b-rb)/2,p*2
end
return c==d
end
-- Adds flag b to state a, if not exist
function flag:Add(a,b)
if flag:Exist(a,b) then
return a
else
return a+b
end
end
-- Removes flag b to state a, if exist
function flag:Min(a,b)
if flag:Exist(a,b) then
return a-b
else
return a
end
end
|
local luapatch = require("luapatch")
luapatch.addInstanceMethod("BaseClass","funcInstance2","BaseClass_funcInstance2","int")
luapatch.addClassMethod("BaseClass","funcClass2","BaseClass_funcClass2","int")
--4种情况,有oc有 lua 覆盖
--oc没有 lua 添加
--oc有 lua没有
--上面三种都会调用到oc中实现的祖父函数,(都是将ORIGfuncInstance命名为父类函数的实现)
--lua有 oc没有(这个会调用到派生类中的实现,ORIGfuncInstance被命名为派生类中的实现了)
--super这个还是太复杂了,是否有简单的方法
--或者总结规律
--规定之后
function BaseClass_funcInstance2(instance)
-- body
print("call BaseClass_funcInstance2")
return 1;
end
function BaseClass_funcClass2(className)
-- body
print("call BaseClass_funcClass2")
return 2;
end
|
local ui = {_version = "0.0.33"}
local HERE = ...
local MODULES = HERE..".modules"
ui.modules = {}
ui.modules.button = require(MODULES..".button")
ui.modules.dial, ui.modules.arc = require(MODULES..".radialbuttons")()
ui.modules.scroll = require(MODULES..".scrolllib")
ui.modules.slider = require(MODULES..".slider")
ui.modules.set = require(MODULES..".uisets")
ui.newRectangleButton = ui.modules.button.newRectangleButton
ui.newPolygonButton = ui.modules.button.newPolygonButton
ui.newCircleButton = ui.modules.button.newCircleButton
ui.newDial = ui.modules.dial.new
ui.newArcButton = ui.modules.arc.new
ui.newScrollViewport = ui.modules.scroll.newViewport
ui.newSlider = ui.modules.slider.new
ui.newSet = ui.modules.set.new
return ui
|
local setmetatable = setmetatable
local wibox = require("wibox")
local capi = { widget = widget }
local module={}
local data = {}
local function update()
end
local function new(args)
local spacer = wibox.widget.textbox()
spacer:set_text(args.text or "")
spacer.width = args.width or 0
return spacer
end
return setmetatable(module, { __call = function(_, ...) return new(...) end })
|
require("common/commonGameLayer");
local OnlookerUserItem = class(CommonGameLayer,false)
OnlookerUserItem.s_controls = {
head = ToolKit.getIndex();
icon_vip = ToolKit.getIndex();
icon_friend = ToolKit.getIndex();
nick = ToolKit.getIndex();
};
OnlookerUserItem.ctor = function(self,data)
local config = require("view/kScreen_1280_800/games/common2/onlooker/onlooker_user_item");
super(self, config);
self.m_ctrls = OnlookerUserItem.s_controls;
self.m_data = table.verify(data);
self:setSize(self.m_root:getSize());
self:_initView(self.m_data);
end
OnlookerUserItem.dtor = function(self)
self.m_data = nil;
end
--data = {
-- sex = 0;
-- avatar = "";
-- nick = "123433";
-- isVip = true;
-- isFriend = true;
-- };
OnlookerUserItem._initView = function(self,data)
local icon_vip = self:findViewById(self.m_ctrls.icon_vip);
local icon_friend = self:findViewById(self.m_ctrls.icon_friend);
local nick = self:findViewById(self.m_ctrls.nick);
local color = data.isVip and {255,241,10} or {238,206,144};
local align = data.isFriend and kAlignTopLeft or kAlignLeft;
local x,y = nick:getPos();
local y = data.isFriend and y or 0;
icon_vip:setLevel(1);
icon_vip:setVisible(data.isVip);
icon_friend:setVisible(data.isFriend);
nick:setAlign(align);
nick:setPos(x,y);
nick:setText(string.subUtfStrByCn(data.nick or "", 1, 6, ".."),1,nil,unpack(color));
local defaultHeadFile = UserBaseInfoIsolater.getInstance():getHeadBySex(data.sex);
self:_setHeadImage(defaultHeadFile);
if not string.isEmpty(data.avatar) then
ImageCache.getInstance():request(data.avatar, self, self.onImageDownload);
end
end
OnlookerUserItem.onImageDownload = function(self,url,fileName)
if not string.isEmpty(fileName) then
self:_setHeadImage(fileName);
end
end
OnlookerUserItem._setHeadImage = function (self, image)
local head = self:findViewById(self.m_ctrls.head);
if self.m_headImage then
head:removeChild(self.m_headImage);
end
delete(self.m_headImage);
self.m_headImage = new(Mask, image, "isolater/mask_head_72.png");
head:addChild(self.m_headImage);
self.m_headImage:setFillParent(true,true);
self.m_headImage:setAlign(kAlignCenter);
end
OnlookerUserItem.getData = function(self)
return self.m_data;
end
OnlookerUserItem.s_controlConfig =
{
[OnlookerUserItem.s_controls.head] = {"head"};
[OnlookerUserItem.s_controls.icon_vip] = {"head","icon_vip"};
[OnlookerUserItem.s_controls.icon_friend] = {"icon_friend"};
[OnlookerUserItem.s_controls.nick] = {"nick"};
};
return OnlookerUserItem; |
--数据库配置
--Copyright (C) Yuanlun He.
--local require = require
local ngx_shared = ngx.shared
local _M = require('vendor.Session')
--_M._VERSION= '0.01'
--_M.exptime = 1800, --修改session失效时间时,打开默认30分钟
--_M.cache = ngx_shared['session_cache'], --使用ngx的缓存时打开,此为默认项
--使用memcached缓存打开以下配置
--_M.cache = require("vendor.Memcache"):new{host="127.0.0.1",port="11211"},
return _M
|
local Keys = {
["ESC"] = 322, ["F1"] = 288, ["F2"] = 289, ["F3"] = 170, ["F5"] = 166, ["F6"] = 167, ["F7"] = 168, ["F8"] = 169, ["F9"] = 56, ["F10"] = 57,
["~"] = 243, ["1"] = 157, ["2"] = 158, ["3"] = 160, ["4"] = 164, ["5"] = 165, ["6"] = 159, ["7"] = 161, ["8"] = 162, ["9"] = 163, ["-"] = 84, ["="] = 83, ["BACKSPACE"] = 177,
["TAB"] = 37, ["Q"] = 44, ["W"] = 32, ["E"] = 38, ["R"] = 45, ["T"] = 245, ["Y"] = 246, ["U"] = 303, ["P"] = 199, ["["] = 39, ["]"] = 40, ["ENTER"] = 18,
["CAPS"] = 137, ["A"] = 34, ["S"] = 8, ["D"] = 9, ["F"] = 23, ["G"] = 47, ["H"] = 74, ["K"] = 311, ["L"] = 182,
["LEFTSHIFT"] = 21, ["Z"] = 20, ["X"] = 73, ["C"] = 26, ["V"] = 0, ["B"] = 29, ["N"] = 249, ["M"] = 244, [","] = 82, ["."] = 81,
["LEFTCTRL"] = 36, ["LEFTALT"] = 19, ["SPACE"] = 22, ["RIGHTCTRL"] = 70,
["HOME"] = 213, ["PAGEUP"] = 10, ["PAGEDOWN"] = 11, ["DELETE"] = 178,
["LEFT"] = 174, ["RIGHT"] = 175, ["TOP"] = 27, ["DOWN"] = 173,
["NENTER"] = 201, ["N4"] = 108, ["N5"] = 60, ["N6"] = 107, ["N+"] = 96, ["N-"] = 97, ["N7"] = 117, ["N8"] = 61, ["N9"] = 118
}
ESX = nil
local Caught_KEY = Keys['G']
local SuccessLimit = 0.09 -- Maxim 0.1 (high value, low success chances)
local AnimationSpeed = 0.0015
local ShowChatMSG = true -- or false
local IsFishing = false
local CFish = false
local BarAnimation = 0
local Faketimer = 0
local RunCodeOnly1Time = true
local PosX = 0.5
local PosY = 0.1
local TimerAnimation = 0.1
Citizen.CreateThread(function()
while ESX == nil do
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
Citizen.Wait(1)
end
end)
function GetCar() return GetVehiclePedIsIn(GetPlayerPed(-1), false) end
function GetPed() return GetPlayerPed(-1) end
function text(x,y,scale,text)
SetTextFont(0)
SetTextProportional(0)
SetTextScale(scale, scale)
SetTextColour(255,255,255,255)
SetTextDropShadow(0,0,0,0,255)
SetTextEdge(2, 0, 0, 0, 255)
SetTextEntry("STRING")
AddTextComponentString(text)
DrawText(x, y)
end
function FishGUI(bool)
if not bool then return end
DrawRect(PosX,PosY+0.005,TimerAnimation,0.005,255,255,0,255)
DrawRect(PosX,PosY,0.1,0.01,0,0,0,255)
TimerAnimation = TimerAnimation - 0.0001025
if BarAnimation >= SuccessLimit then
DrawRect(PosX,PosY,BarAnimation,0.01,102,255,102,150)
else
DrawRect(PosX,PosY,BarAnimation,0.01,255,51,51,150)
end
if BarAnimation <= 0 then
up = true
end
if BarAnimation >= PosY then
up = false
end
if not up then
BarAnimation = BarAnimation - AnimationSpeed
else
BarAnimation = BarAnimation + AnimationSpeed
end
text(0.4,0.05,0.35, "Vous en avez un, ferrez-le en appuyant sur [G]")
end
function PlayAnim(ped,base,sub,nr,time)
Citizen.CreateThread(function()
RequestAnimDict(base)
while not HasAnimDictLoaded(base) do
Citizen.Wait(1)
end
if IsEntityPlayingAnim(ped, base, sub, 3) then
ClearPedSecondaryTask(ped)
else
for i = 1,nr do
TaskPlayAnim(ped, base, sub, 8.0, -8, -1, 16, 0, 0, 0, 0)
Citizen.Wait(time)
end
end
end)
end
function AttachEntityToPed(prop,bone_ID,x,y,z,RotX,RotY,RotZ)
BoneID = GetPedBoneIndex(GetPed(), bone_ID)
obj = CreateObject(GetHashKey(prop), 1729.73, 6403.90, 34.56, true, true, true)
vX,vY,vZ = table.unpack(GetEntityCoords(GetPed()))
xRot, yRot, zRot = table.unpack(GetEntityRotation(GetPed(),2))
AttachEntityToEntity(obj, GetPed(), BoneID, x,y,z, RotX,RotY,RotZ, false, false, false, false, 2, true)
return obj
end
RegisterNetEvent('esx_fishing:startFishing')
AddEventHandler('esx_fishing:startFishing', function()
if not IsPedInAnyVehicle(GetPed(), false) then
if not IsPedSwimming(GetPed()) then
if IsEntityInWater(GetPed()) then
if ESX.UI.Menu.IsOpen('default', 'es_extended', 'inventory') then
ESX.UI.Menu.Close('default', 'es_extended', 'inventory')
end
if ESX.UI.Menu.IsOpen('default', 'es_extended', 'inventory_item') then
ESX.UI.Menu.Close('default', 'es_extended', 'inventory_item')
end
IsFishing = true
if ShowChatMSG then ESX.ShowNotification("Vous avez lancé votre appât, attendez qu'un poisson morde ...") end
RunCodeOnly1Time = true
BarAnimation = 0
else
ESX.ShowNotification('Action impossible, vous devez être dans l\'eau')
end
else
ESX.ShowNotification('Action impossible')
end
else
ESX.ShowNotification('Action impossible')
end
end)
RegisterNetEvent('esx_fishing:onEatFish')
AddEventHandler('esx_fishing:onEatFish', function()
local playerPed = GetPlayerPed(-1)
local health = GetEntityHealth(playerPed) + 25
SetEntityHealth(playerPed, health)
end)
Citizen.CreateThread(function()
while true do Citizen.Wait(1)
while IsFishing do
local time = 4*3000
TaskStandStill(GetPed(), time+7000)
FishRod = AttachEntityToPed('prop_fishing_rod_01',60309, 0,0,0, 0,0,0)
PlayAnim(GetPed(),'amb@world_human_stand_fishing@base','base',4,3000)
Citizen.Wait(time)
CFish = true
IsFishing = false
end
while CFish do
Citizen.Wait(1)
FishGUI(true)
if RunCodeOnly1Time then
Faketimer = 1
PlayAnim(GetPed(),'amb@world_human_stand_fishing@idle_a','idle_c',1,0) -- 10sec
RunCodeOnly1Time = false
end
if TimerAnimation <= 0 then
CFish = false
TimerAnimation = 0.1
StopAnimTask(GetPed(), 'amb@world_human_stand_fishing@idle_a','idle_c',2.0)
Citizen.Wait(200)
DeleteEntity(FishRod)
if ShowChatMSG then ESX.ShowNotification("Le poisson s'est échappé ...") end
end
if IsControlJustPressed(1, Caught_KEY) then
if BarAnimation >= SuccessLimit then
CFish = false
TimerAnimation = 0.1
if ShowChatMSG then ESX.ShowNotification("Vous avez attrapé un poisson !") end
StopAnimTask(GetPed(), 'amb@world_human_stand_fishing@idle_a','idle_c',2.0)
Citizen.Wait(200)
DeleteEntity(FishRod)
TriggerServerEvent('esx_fishing:caughtFish')
else
CFish = false
TimerAnimation = 0.1
StopAnimTask(GetPed(), 'amb@world_human_stand_fishing@idle_a','idle_c',2.0)
Citizen.Wait(200)
DeleteEntity(FishRod)
if ShowChatMSG then ESX.ShowNotification("Le poisson s'est échappé !") end
end
end
end
end
end)
Citizen.CreateThread(function() -- Thread for timer
while true do
Citizen.Wait(1000)
Faketimer = Faketimer + 1
end
end) |
local SpeakNato
do
SpeakNato = {}
function SpeakNato:new()
local newInstanceWithState = {}
setmetatable(newInstanceWithState, self)
self.__index = self
return newInstanceWithState
end
end
SpeakNato.speakQnh = function(fourDigits)
SpeakNato._speak(SpeakNato._getNatoStringForFourDigitNumber(fourDigits))
end
SpeakNato.speakFrequency = function(threeDigitsDecimalThreeDigits)
SpeakNato._speak(SpeakNato._getNatoStringForFrequency(threeDigitsDecimalThreeDigits))
end
SpeakNato.speakTransponderCode = function(fourDigits)
SpeakNato._speak(SpeakNato._getNatoStringForFourDigitNumber(fourDigits))
end
SpeakNato._getNatoStringForFourDigitNumber = function(string)
string = string:gsub("000$", "towsent ")
return SpeakNato._getNatoStringForNumbers(string)
end
SpeakNato._getNatoStringForFrequency = function(str)
local trailingZeroCapture = str:match("^[1-9][0-9][0-9]%.[0-9][0-9]-([0]-)$")
if (trailingZeroCapture ~= nil) then
str = str:sub(1, str:len() - trailingZeroCapture:len())
end
return SpeakNato._getNatoStringForNumbers(str)
end
SpeakNato._getNatoStringForNumbers = function(string)
string = string:gsub("0", "zeero ")
string = string:gsub("1", "won ")
string = string:gsub("2", "too ")
string = string:gsub("3", "tree ")
string = string:gsub("4", "fore ")
string = string:gsub("5", "five ")
string = string:gsub("6", "siccs ")
string = string:gsub("7", "seven ")
string = string:gsub("8", "ate ")
string = string:gsub("9", "niner ")
string = string:gsub("%.", "decimal ")
return string
end
TRACK_ISSUE("Tech Debt", "This function is not yet required. It's waste, implemented too soon.", "But it sounded good.")
SpeakNato._getNatoStringForLetters = function(string)
string = string:gsub("A", " alfah ")
string = string:gsub("B", " brahvoh ")
string = string:gsub("C", " charlie ")
string = string:gsub("D", " delta ")
string = string:gsub("E", " echo ")
string = string:gsub("F", " foxtrot ")
string = string:gsub("G", " golf ")
string = string:gsub("H", " hotell ")
string = string:gsub("I", " inndeeah ")
string = string:gsub("J", " juliet ")
string = string:gsub("K", " kilo ")
string = string:gsub("L", " lima ")
string = string:gsub("M", " mike ")
string = string:gsub("N", " novemmber ")
string = string:gsub("O", " oscar ")
string = string:gsub("P", " papa ")
string = string:gsub("Q", " kebec ")
string = string:gsub("R", " romeo ")
string = string:gsub("S", " sierrahh ")
string = string:gsub("T", " tango ")
string = string:gsub("U", " uniform ")
string = string:gsub("V", " victor ")
string = string:gsub("W", " whizzkee ")
string = string:gsub("X", " x ray ")
string = string:gsub("Y", " yankee ")
string = string:gsub("Z", " zulu ")
return string
end
SpeakNato._speak = function(string)
XPLMSpeakString(string)
end
return SpeakNato
|
local bitser = require("bitser")
local pprint = require("pprint")
local util = {}
function util.Sleep(s)
if type(s) ~= "number" then
error("Unable to wait if parameter 'seconds' isn't a number: " .. type(s))
end
-- http://lua-users.org/wiki/SleepFunction
local ntime = os.clock() + s
repeat
until os.clock() > ntime
end
function util.IsEmpty(var)
if var == nil then
return true
end
if var == "" then
return true
end
if type(var) == "table" and not next(var) then
return true
end
return false
end
--- Extends @var to the @length with @char. Example 1: "test", 6, " " = "test " | Example 2: "verylongstring", 5, " " = "veryl"
---@param var string any string you want to extend or cut
---@param length number
---@param char any
---@return string
function util.ExtendAndCutStringToLength(var, length, char)
if type(var) ~= "string" then
error("var is not a string.", 2)
end
if type(length) ~= "number" then
error("length is not a number.", 2)
end
if type(char) ~= "string" or string.len(char) > 1 then
error("char is not a character. string.len(char) > 1 = " .. string.len(char), 2)
end
local new_var = ""
local len = string.len(var)
for i = 1, length, 1 do
local char_of_var = var:sub(i, i)
if char_of_var ~= "" then
new_var = new_var .. char_of_var
else
new_var = new_var .. char
end
end
return new_var
end
function util.serialise(data)
return bitser.dumps(data)
end
--- Deserialise data
---@param data any
---@return any
function util.deserialise(data)
return bitser.loads(data)
end
--https://noita.fandom.com/wiki/Modding:_Utilities#Easier_entity_debugging
function util.str(var)
if type(var) == "table" then
local s = "{ "
for k, v in pairs(var) do
if type(k) ~= "number" then
k = '"' .. k .. '"'
end
s = s .. "[" .. k .. "] = " .. util.str(v) .. ","
end
return s .. "} "
end
return tostring(var)
end
--https://noita.fandom.com/wiki/Modding:_Utilities#Easier_entity_debugging
function util.debug_entity(e)
local parent = EntityGetParent(e)
local children = EntityGetAllChildren(e)
local comps = EntityGetAllComponents(e)
local msg = "--- ENTITY DATA ---\n"
msg = msg .. ("Parent: [" .. parent .. "] " .. (EntityGetName(parent) or "nil") .. "\n")
msg = msg .. (" Entity: [" .. util.str(e) .. "] " .. (EntityGetName(e) or "nil") .. "\n")
msg = msg .. (" Tags: " .. (EntityGetTags(e) or "nil") .. "\n")
if (comps ~= nil) then
for _, comp in ipairs(comps) do
msg = msg .. (" Comp: [" .. comp .. "] " .. (ComponentGetTypeName(comp) or "nil") .. "\n")
end
end
if children == nil then
return
end
for _, child in ipairs(children) do
local comps = EntityGetAllComponents(child)
msg = msg .. (" Child: [" .. child .. "] " .. EntityGetName(child) .. "\n")
for _, comp in ipairs(comps) do
msg = msg .. (" Comp: [" .. comp .. "] " .. (ComponentGetTypeName(comp) or "nil") .. "\n")
end
end
msg = msg .. ("--- END ENTITY DATA ---" .. "\n")
logger:debug(msg)
end
function util.pprint(var)
pprint(var)
end
function util.getLocalOwner()
return {
username = tostring(ModSettingGet("noita-mp.username")),
guid = tostring(ModSettingGet("noita-mp.guid"))
}
end
return util
|
-- Wind area
WindArea = {
Properties = {
bActive = 1,
Size = { x=10,y=10,z=10 },
bEllipsoidal = 1,
FalloffInner = 0,
Dir = { x=0,y=0,z=0 },
Speed = 0,
AirResistance = 0,
AirDensity = 0,
},
Editor = {
Icon = "Tornado.bmp",
},
_PhysTable = { Area={}, },
}
-------------------------------------------------------
function WindArea:OnLoad(table)
self.bActive = table.bActive
end
-------------------------------------------------------
function WindArea:OnSave(table)
table.bActive = self.bActive
end
------------------------------------------------------------------------------------------------------
function WindArea:OnInit()
self.bActive = self.Properties.bActive;
if (self.bActive == 1) then
self:PhysicalizeThis();
end
end
------------------------------------------------------------------------------------------------------
-- OnPropertyChange called only by the editor.
------------------------------------------------------------------------------------------------------
function WindArea:OnPropertyChange()
self.bActive = self.Properties.bActive;
self:PhysicalizeThis();
end
------------------------------------------------------------------------------------------------------
-- OnReset called only by the editor.
------------------------------------------------------------------------------------------------------
function WindArea:OnReset()
end
------------------------------------------------------------------------------------------------------
function WindArea:PhysicalizeThis()
if (self.bActive == 1) then
local Properties = self.Properties;
local Area = self._PhysTable.Area;
Area.type = AREA_BOX;
Area.box_max = Properties.Size;
Area.box_min = { x = -Area.box_max.x, y = -Area.box_max.y, z = -Area.box_max.z };
if (Properties.bEllipsoidal == 1 or Properties.FalloffInner < 1) then
Area.falloffInner = Properties.FalloffInner;
else
Area.falloffInner = -1;
end
if (Properties.Dir.x == 0 and Properties.Dir.y == 0 and Properties.Dir.z == 0) then
Area.uniform = 0;
Area.wind = {x = 0, y = 0, z = Properties.Speed};
else
Area.uniform = 2;
Area.wind = { x = Properties.Dir.x * Properties.Speed, y = Properties.Dir.y * Properties.Speed, z = Properties.Dir.z * Properties.Speed };
end
Area.resistance = Properties.AirResistance;
Area.density = Properties.AirDensity;
self:Physicalize( 0,PE_AREA,self._PhysTable );
else
self:DestroyPhysics();
end
end
------------------------------------------------------------------------------------------------------
function WindArea:Event_Activate()
if (self.bActive ~= 1) then
self.bActive = 1;
self:PhysicalizeThis();
end
end
------------------------------------------------------------------------------------------------------
function WindArea:Event_Deactivate()
if (self.bActive ~= 0) then
self.bActive = 0;
self:PhysicalizeThis();
end
end
WindArea.FlowEvents =
{
Inputs =
{
Deactivate = { WindArea.Event_Deactivate, "bool" },
Activate = { WindArea.Event_Activate, "bool" },
},
Outputs =
{
Deactivate = "bool",
Activate = "bool",
},
}
|
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by Lovnx.
--- DateTime: 2018/5/11 11:39
---
local http = require "resty.http"
local balancer = require "ngx.balancer"
local json = require "cjson"
local ok, new_tab = pcall(require, "table.new")
if not ok or type(new_tab) ~= "function" then
new_tab = function (narr, nrec) return {} end
end
local _M = new_tab(0, 100)
_M.VERSION = "0.0.1"
local mt = { __index = _M }
local default_dict_name = "eureka_balancer"
-- refresh success idle time (s)
local watch_refresh_idle_time = 10
-- refresh failed retry idle time (s)
local refresh_retry_idle_time = 5
-- max idle timeout (in ms) when the connection is in the pool
local http_max_idle_timeout = 60000
-- the maximal size of the pool every nginx worker process
local http_pool_size = 10
local function _timer(...)
local ok, err = ngx.timer.at(...)
if not ok then
ngx.log(ngx.ERR, "eureka.balancer: failed to create timer: ", err)
end
end
function split(s, p)
local rt= {}
string.gsub(s, '[^'..p..']+', function(w) table.insert(rt, w) end )
return rt
end
-- build eureka service uri
local function build_eureka_uri(eureka_url_index)
local uri = _M.eureka_service_urls[eureka_url_index]
local ipAddr = split(uri, ":")
local ip = ipAddr[1]
local port = ipAddr[2]
return ip, port
end
-- build eureka request params
local function build_eureka_params(service_name)
local uri = "/eureka/apps/" .. service_name
local headers = {["Accept"]="application/json"}
local eureka_service_basic_authentication = _M.eureka_service_basic_authentication
if eureka_service_basic_authentication then
local basic_authentication = "Basic " .. eureka_service_basic_authentication
headers = {["Accept"]="application/json", ["Authorization"]=basic_authentication}
end
local params = {path=uri, method="GET", headers=headers}
return params
end
local function incr_eureka_url_index(eureka_url_index)
if eureka_url_index >= #_M.eureka_service_urls then
eureka_url_index = 1
else
eureka_url_index = eureka_url_index + 1
end
return eureka_url_index
end
-- parse eureka result
local function parse_service(body)
local ok, res_json = pcall(function()
return json.decode(body)
end)
if not ok then
return nil, "JSON decode error"
end
local service = {}
service.upstreams = {}
for k, v in pairs(res_json) do
local passing = true
local instances = v["instance"]
for i, instance in pairs(instances) do
local status = instance["status"]
if status == "UP" then
local ipAddr = instance["ipAddr"]
local port = instance["port"]["$"]
table.insert(service.upstreams, {ip=ipAddr, port=port})
end
end
--ngx.log(ngx.INFO, "eureka.balancer: instance", json.encode(service.upstreams))
end
return service
end
-- cache service to ngx shared dict
local function cache_service(service_name, service)
if not _M.shared_cache then
return nil
end
ngx.log(ngx.INFO, "eureka.balancer: cache service to ngx shared: ", service_name, " ", json.encode(service))
_M.shared_cache:set(service_name, json.encode(service))
end
-- get service from ngx shared dict
local function aquire_service(service_name)
if not _M.shared_cache then
return nil
end
local service_json = _M.shared_cache:get(service_name)
ngx.log(ngx.INFO, "eureka.balancer: aquire service from ngx shared: service_name: ", service_name, " ", service_json)
return service_json and json.decode(service_json) or nil
end
-- only update upstreams if service already exist (round robin cursor)
local function cache_service_upstreams(service_name, service)
if not _M.shared_cache then
return nil
end
ngx.log(ngx.INFO, "eureka.balancer: cache service upstreams to ngx shared: ", service_name, " ", json.encode(service))
local cached_service = aquire_service(service_name)
if cached_service ~= nil then
cached_service.upstreams = service.upstreams
cache_service(service_name, cached_service)
else
cache_service(service_name, service)
end
end
-- refresh service from eureka
local function refresh_service(service_name, eureka_url_index)
local httpc = http:new()
--connect_timeout, send_timeout, read_timeout (in ms)
httpc:set_timeouts(3000, 10000, 10000)
local params = build_eureka_params(service_name)
local s_ip, s_port = build_eureka_uri(eureka_url_index)
ngx.log(ngx.INFO, "eureka.balancer: refresh_service : ", eureka_url_index, " ", s_ip, ":", s_port)
local ok, err = httpc:connect(s_ip, s_port)
if err ~= nil then
ngx.log(ngx.ERR, "eureka.balancer: failed to connect eureka server: ", s_ip, ":", s_port, " ", err)
return nil, err
end
local res, err = httpc:request(params)
if err ~= nil then
ngx.log(ngx.ERR, "eureka.balancer: failed to request eureka server: ", s_ip, ":", s_port, " ", err)
return nil, err
end
if res.status ~= 200 then
return nil, "bad response code: " .. res.status
end
local body = res:read_body()
local service, err = parse_service(body)
if err ~= nil then
ngx.log(ngx.ERR, "eureka.balancer: failed to parse eureka service response: ", s_ip, ":", s_port, " ", err)
return nil, err
end
local ok, err = httpc:set_keepalive(http_max_idle_timeout, http_pool_size)
--local ok, err = httpc:set_keepalive()
if err ~= nil then
ngx.log(ngx.ERR, "eureka.balancer: failed to set keepalive for http client: ", err)
end
return service
end
local function watch(premature, service_name, eureka_url_index)
if premature then
return nil
end
eureka_url_index = eureka_url_index or 1
local service, err = refresh_service(service_name, eureka_url_index)
if err ~= nil then
ngx.log(ngx.ERR, "eureka.balancer: failed watching service: ", service_name)
eureka_url_index = incr_eureka_url_index(eureka_url_index)
ngx.log(ngx.ERR, "eureka.balancer: failed watching service eureka_url_index: ", eureka_url_index)
_timer(refresh_retry_idle_time, watch, service_name, eureka_url_index)
return nil
end
service.name = service_name
cache_service_upstreams(service_name, service)
_timer(watch_refresh_idle_time, watch, service_name, eureka_url_index)
end
-- watch services
function _M.watch_service(service_list)
if ngx.worker.id() > 0 then
return
end
for k,v in pairs(service_list) do
_timer(0, watch, v, 1)
end
end
-- round_robin incr service.cursor
local function incr_service_cursor(service)
service = service or {}
if service.cursor == nil then
service.cursor = 1
else
service.cursor = service.cursor + 1
end
if service.cursor > #service.upstreams then
service.cursor = 1
end
return service.cursor
end
--round_robin
function _M.round_robin(service_name)
local service = aquire_service(service_name)
if service == nil then
ngx.log(ngx.ERR, "eureka.balancer: service not found: ", service_name)
return ngx.exit(500)
end
if service.upstreams == nil or #service.upstreams == 0 then
ngx.log(ngx.ERR, "eureka.balancer: no peers for service: ", service_name)
return ngx.exit(500)
end
incr_service_cursor(service)
-- TODO: https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/balancer.md#get_last_failure
if not balancer.get_last_failure() then
balancer.set_more_tries(#service.upstreams - 1)
end
-- Picking next backend server
local backend_server = service.upstreams[service.cursor]
-- update service cursor
cache_service(service_name, service)
local ok, err = balancer.set_current_peer(backend_server["ip"], backend_server["port"])
if not ok then
ngx.log(ngx.ERR, "eureka.balancer: failed to set the current peer: ", err)
return ngx.exit(500)
end
end
--ip_hash
function _M.ip_hash(service_name)
local service = aquire_service(service_name)
if service == nil then
ngx.log(ngx.ERR, "eureka.balancer: service not found: ", service_name)
return ngx.exit(500)
end
local bs_size = #service.upstreams
if service.upstreams == nil or bs_size == 0 then
ngx.log(ngx.ERR, "eureka.balancer: no peers for service: ", service_name)
return ngx.exit(500)
end
local remote_ip = ngx.var.remote_addr
--local remote_port = ngx.var.remote_port
local hash_key = remote_ip
local hash = ngx.crc32_long(hash_key)
local index = (hash % bs_size) + 1
local backend_server = service.upstreams[index]
local ok, err = balancer.set_current_peer(backend_server["ip"], backend_server["port"])
if not ok then
ngx.log(ngx.ERR, "eureka.balancer: failed to set the current peer: ", err)
return ngx.exit(500)
end
end
local function set_shared_dict_name(dict_name)
dict_name = dict_name or default_dict_name
_M.shared_cache = ngx.shared[dict_name]
if not _M.shared_cache then
ngx.log(ngx.ERR, "eureka.balancer: unable to access shared dict ", dict_name)
return ngx.exit(ngx.ERROR)
end
end
-- set eureka service urls
function _M.set_eureka_service_url(eureka_service_urls)
_M.eureka_service_urls = eureka_service_urls
if not _M.eureka_service_urls then
ngx.log(ngx.ERR, "eureka.balancer: require set eureka_service_urls")
return ngx.exit(ngx.ERROR)
end
end
-- set eureka basic authentication info
function _M.set_eureka_service_basic_authentication(eureka_service_basic_authentication)
_M.eureka_service_basic_authentication = eureka_service_basic_authentication
end
function _M.new(self, opts)
opts = opts or {}
if opts.dict_name ~= nil then
set_shared_dict_name(opts.dict_name)
end
return setmetatable({}, mt)
end
return _M |
local M = {}
local config = {
size = vim.fn.float2nr(vim.o.lines * 0.25),
notify_timeout = 1000,
}
local notify = vim.F.npcall(require, "notify")
local terminal = require("toggleterm.terminal").Terminal
local task_runner = terminal:new({ direction = "horizontal", count = 9 })
local last_cmd = ""
local function notification(message, level)
local title = "TaskRun"
if notify then
notify(message, level, {
title = title,
timeout = config.notify_timeout,
})
else
-- vim.notify(("[%s] %s"):format(title, message), level)
end
end
local function get_exit_status()
local bufnr = task_runner.bufnr
local ln = vim.api.nvim_buf_line_count(bufnr)
while ln >= 1 do
local l = vim.api.nvim_buf_get_lines(bufnr, ln - 1, ln, true)[1]
ln = ln - 1
local exit_code = string.match(l, "^%[Process exited ([0-9]+)%]$")
if exit_code ~= nil then
return tonumber(exit_code)
end
end
end
local function send_notify()
if vim.api.nvim_buf_is_valid(task_runner.bufnr) then
local result = get_exit_status()
if result == nil then
return "Finished"
elseif result == 0 then
notification("Success", vim.log.levels.INFO)
return "Success"
elseif result >= 1 then
notification("Error", vim.log.levels.WARN)
return "Error"
end
return "Finished"
end
return "Command"
end
function M.notify()
local timer = vim.loop.new_timer()
-- Because "Process exited" message is not displayed immediately after TermClose
timer:start(100, 0, vim.schedule_wrap(send_notify))
end
function M.run(cmd)
if task_runner:is_open() then
task_runner:shutdown()
end
last_cmd = cmd
task_runner = terminal:new({ cmd = cmd, direction = "horizontal", count = 9 })
task_runner:open(config.size, "horizontal", true)
-- require('toggleterm.ui').save_window_size()
vim.cmd([[let g:toglleterm_win_num = winnr()]])
vim.cmd([[setlocal number]])
vim.cmd([[stopinsert | wincmd p]])
end
function M.run_last()
if last_cmd == "" then
print("Please start TaskRun with arguments")
return
end
M.run(last_cmd)
end
function M.toggle()
task_runner:toggle(config.size)
if task_runner:is_open() then
vim.cmd("wincmd p")
end
end
local function toggle_term_shutdown()
if task_runner:is_open() then
task_runner:shutdown()
end
end
function M.close()
toggle_term_shutdown()
if vim.api.nvim_win_is_valid(vim.g.toglleterm_win_num) then
vim.api.nvim_win_close(vim.g.toglleterm_win_num)
end
end
function M.setup(opts)
opts = opts or {}
config = vim.tbl_deep_extend("keep", opts, config)
vim.api.nvim_create_user_command("TaskRun", "lua require('taskrun').run(<q-args>)", { force = true, nargs = "+" })
vim.api.nvim_create_user_command("TaskRunToggle", "lua require('taskrun').toggle()", { force = true, nargs = 0 })
vim.api.nvim_create_user_command("TaskRunLast", "lua require('taskrun').run_last()", { force = true, nargs = 0 })
vim.cmd([[
augroup taskrun
autocmd!
autocmd TermClose term://*#toggleterm#9* ++nested if winbufnr(g:toglleterm_win_num) != -1 | execute g:toglleterm_win_num . "wincmd w" | $ | wincmd p | endif
autocmd TermClose term://*#toggleterm#9* ++nested lua print(require('taskrun').notify())
" https://github.com/neovim/neovim/issues/13078
autocmd VimLeavePre * lua require('taskrun').close()
augroup END
]])
end
return M
|
object_tangible_food_spice_spice_sedative_h4b_01 = object_tangible_food_spice_shared_spice_sedative_h4b_01:new {
}
ObjectTemplates:addTemplate(object_tangible_food_spice_spice_sedative_h4b_01, "object/tangible/food/spice/spice_sedative_h4b_01.iff")
|
return {
User = require('litcord.structures.User'),
Channel = require('litcord.structures.Channel'),
Message = require('litcord.structures.Message'),
Reaction = require('litcord.structures.Reaction'),
Server = require('litcord.structures.Server'),
Member = require('litcord.structures.Member'),
Role = require('litcord.structures.Role'),
Invite = require('litcord.structures.Invite'),
Overwrite = require('litcord.structures.Overwrite'),
} |
local Addon = (select(2, ...))
local Dominos = LibStub("AceAddon-3.0"):GetAddon("Dominos")
local LSM = LibStub('LibSharedMedia-3.0')
--[[ global references ]]--
local _G = _G
local min = math.min
local max = math.max
local GetSpellInfo = _G.GetSpellInfo
local GetTime = _G.GetTime
local GetNetStats = _G.GetNetStats
local UnitCastingInfo = _G.UnitCastingInfo or _G.CastingInfo
local UnitChannelInfo = _G.UnitChannelInfo or _G.ChannelInfo
local IsHarmfulSpell = _G.IsHarmfulSpell
local IsHelpfulSpell = _G.IsHelpfulSpell
local ICON_OVERRIDES = {
-- replace samwise with cog
[136235] = 136243
}
--[[ constants ]]--
local LATENCY_BAR_ALPHA = 0.7
local SPARK_ALPHA = 0.7
--[[ casting bar ]]--
local CastBar = Dominos:CreateClass('Frame', Dominos.Frame)
function CastBar:New(id, units, ...)
local bar = CastBar.proto.New(self, id, ...)
bar.units = type(units) == "table" and units or {units}
bar:Layout()
bar:RegisterEvents()
return bar
end
function CastBar:OnCreate()
self:SetFrameStrata('HIGH')
self:SetScript('OnEvent', self.OnEvent)
local container = CreateFrame('Frame', nil, self)
container:SetAllPoints(container:GetParent())
container:SetAlpha(0)
self.container = container
local fout = container:CreateAnimationGroup()
fout:SetLooping('NONE')
fout:SetScript('OnFinished', function() container:SetAlpha(0); self:OnFinished() end)
local a = fout:CreateAnimation('Alpha')
a:SetFromAlpha(1)
a:SetToAlpha(0)
a:SetDuration(0.5)
self.fout = fout
local fin = container:CreateAnimationGroup()
fin:SetLooping('NONE')
fin:SetScript('OnFinished', function() container:SetAlpha(1) end)
a = fin:CreateAnimation('Alpha')
a:SetFromAlpha(0)
a:SetToAlpha(1)
a:SetDuration(0.2)
self.fin = fin
local bg = container:CreateTexture(nil, 'BACKGROUND')
bg:SetVertexColor(0, 0, 0, 0.5)
self.bg = bg
local icon = container:CreateTexture(nil, 'ARTWORK')
icon:SetTexCoord(0.08, 0.92, 0.08, 0.92)
self.icon = icon
local lb = container:CreateTexture(nil, 'OVERLAY')
lb:SetBlendMode('ADD')
self.latencyBar = lb
local sb = CreateFrame('StatusBar', nil, container)
sb:SetScript('OnValueChanged', function(_, value)
self:OnValueChanged(value)
end)
local timeText = sb:CreateFontString(nil, 'OVERLAY', 'GameFontHighlightSmall')
timeText:SetJustifyH('RIGHT')
self.timeText = timeText
local labelText = sb:CreateFontString(nil, 'OVERLAY', 'GameFontHighlightSmall')
labelText:SetJustifyH('LEFT')
self.labelText = labelText
local spark = CreateFrame('StatusBar', nil, sb)
local st = spark:CreateTexture(nil, 'ARTWORK')
st:SetColorTexture(1, 1, 1, SPARK_ALPHA)
st:SetGradientAlpha('HORIZONTAL', 0, 0, 0, 0, 1, 1, 1, SPARK_ALPHA)
st:SetBlendMode('BLEND')
st:SetHorizTile(true)
spark:SetStatusBarTexture(st)
spark:SetAllPoints(sb)
self.spark = spark
self.statusBar = sb
local border = CreateFrame('Frame', nil, container)
border:SetBackdropBorderColor(TOOLTIP_DEFAULT_COLOR.r, TOOLTIP_DEFAULT_COLOR.g, TOOLTIP_DEFAULT_COLOR.b)
border:SetFrameLevel(sb:GetFrameLevel() + 3)
border:SetAllPoints(container)
border:SetBackdrop{
edgeFile = [[Interface\DialogFrame\UI-DialogBox-Border]],
edgeSize = 16,
insets = { left = 5, right = 5, top = 5, bottom = 5 },
}
self.border = border
self.props = {}
return self
end
function CastBar:OnFree()
self:UnregisterAllEvents()
LSM.UnregisterAllCallbacks(self)
end
function CastBar:OnLoadSettings()
if not self.sets.display then
self.sets.display = {
icon = false,
time = true,
border = true
}
end
self:SetProperty("font", self:GetFontID())
self:SetProperty("texture", self:GetTextureID())
self:SetProperty("reaction", "neutral")
end
function CastBar:GetDefaults()
return {
point = 'CENTER',
x = 0,
y = 30,
padW = 1,
padH = 1,
texture = 'blizzard',
font = 'Friz Quadrata TT',
display = {
icon = false,
time = true,
border = true
}
}
end
--[[ frame events ]]--
function CastBar:OnEvent(event, ...)
local func = self[event]
if func then
func(self, event, ...)
end
end
function CastBar:OnUpdateCasting(elapsed)
local sb = self.statusBar
local _, vmax = sb:GetMinMaxValues()
local v = sb:GetValue() + elapsed
if v < vmax then
sb:SetValue(v)
else
sb:SetValue(vmax)
self:SetProperty('state', nil)
end
end
function CastBar:OnUpdateChanneling(elapsed)
local sb = self.statusBar
local vmin = sb:GetMinMaxValues()
local v = sb:GetValue() - elapsed
if v > vmin then
sb:SetValue(v)
else
sb:SetValue(vmin)
self:SetProperty('state', nil)
end
end
function CastBar:OnChannelingValueChanged(value)
self.timeText:SetFormattedText('%.1f', value)
self.spark:SetValue(value)
end
function CastBar:OnCastingValueChanged(value)
self.timeText:SetFormattedText('%.1f', self.tend - value)
self.spark:SetValue(value)
end
function CastBar:OnFinished()
self:Reset()
end
--[[ game events ]]--
function CastBar:RegisterEvents()
local registerUnitEvents = function(...)
self:RegisterUnitEvent('UNIT_SPELLCAST_CHANNEL_START', ...)
self:RegisterUnitEvent('UNIT_SPELLCAST_CHANNEL_UPDATE', ...)
self:RegisterUnitEvent('UNIT_SPELLCAST_CHANNEL_STOP', ...)
self:RegisterUnitEvent('UNIT_SPELLCAST_START', ...)
self:RegisterUnitEvent('UNIT_SPELLCAST_STOP', ...)
self:RegisterUnitEvent('UNIT_SPELLCAST_FAILED', ...)
self:RegisterUnitEvent('UNIT_SPELLCAST_FAILED_QUIET', ...)
self:RegisterUnitEvent('UNIT_SPELLCAST_INTERRUPTED', ...)
self:RegisterUnitEvent('UNIT_SPELLCAST_DELAYED', ...)
end
registerUnitEvents(unpack(self.units))
LSM.RegisterCallback(self, 'LibSharedMedia_Registered')
end
-- channeling events
function CastBar:UNIT_SPELLCAST_CHANNEL_START(event, unit, castID, spellID)
self:SetProperty("unit", unit)
self:UpdateChanneling(true)
self:SetProperty("castID", castID)
self:SetProperty("state", "start")
end
function CastBar:UNIT_SPELLCAST_CHANNEL_UPDATE(event, unit, castID, spellID)
if castID ~= self:GetProperty('castID') then return end
self:UpdateChanneling()
end
function CastBar:UNIT_SPELLCAST_CHANNEL_STOP(event, unit, castID, spellID)
if castID ~= self:GetProperty('castID') then return end
self:SetProperty("state", nil)
end
function CastBar:UNIT_SPELLCAST_START(event, unit, castID, spellID)
self:SetProperty("unit", unit)
self:UpdateCasting(true)
self:SetProperty("castID", castID)
self:SetProperty("state", "start")
end
function CastBar:UNIT_SPELLCAST_STOP(event, unit, castID, spellID)
if castID ~= self:GetProperty('castID') then return end
self:SetProperty("state", nil)
end
function CastBar:UNIT_SPELLCAST_FAILED(event, unit, castID, spellID)
if castID ~= self:GetProperty('castID') then return end
self:SetProperty("reaction", "failed")
self:SetProperty("label", _G.FAILED)
self:SetProperty("state", nil)
end
CastBar.UNIT_SPELLCAST_FAILED_QUIET = CastBar.UNIT_SPELLCAST_FAILED
function CastBar:UNIT_SPELLCAST_INTERRUPTED(event, unit, castID, spellID)
if castID ~= self:GetProperty('castID') then return end
self:SetProperty("reaction", "interrupted")
self:SetProperty("label", _G.INTERRUPTED)
self:SetProperty("state", nil)
end
function CastBar:UNIT_SPELLCAST_DELAYED(event, unit, castID, spellID)
if castID ~= self:GetProperty('castID') then return end
self:UpdateCasting()
end
function CastBar:LibSharedMedia_Registered(event, mediaType, key)
if mediaType == LSM.MediaType.STATUSBAR and key == self:GetTextureID() then
self:texture_update(key)
elseif mediaType == LSM.MediaType.FONT and key == self:GetFontID() then
self:font_update(key)
end
end
--[[ attribute events ]]--
function CastBar:mode_update(mode)
if mode == 'cast' then
self:SetScript('OnUpdate', self.OnUpdateCasting)
elseif mode == 'channel' then
self:SetScript('OnUpdate', self.OnUpdateChanneling)
elseif mode == 'demo' then
self:SetupDemo()
end
end
function CastBar:state_update(state)
if state == 'start' then
self.fout:Stop()
self.fin:Play()
else
self:SetScript('OnUpdate', nil)
self.fin:Stop()
self.fout:Play()
end
end
function CastBar:label_update(text)
self.labelText:SetText(text or '')
end
function CastBar:time_update(text)
self.timeText:SetText(text or '')
end
function CastBar:icon_update(texture)
self.icon:SetTexture(texture and ICON_OVERRIDES[texture] or texture)
end
function CastBar:spell_update(spellID)
if spellID and IsHelpfulSpell(spellID) then
self:SetProperty("reaction", "help")
elseif spellID and IsHarmfulSpell(spellID) then
self:SetProperty("reaction", "harm")
else
self:SetProperty("reaction", "neutral")
end
end
function CastBar:reaction_update(reaction)
if reaction == "failed" or reaction == "interrupted" then
self.statusBar:SetStatusBarColor(1, 0, 0)
self.latencyBar:SetVertexColor(1, 0, 0, 0, LATENCY_BAR_ALPHA)
elseif reaction == "help" then
self.statusBar:SetStatusBarColor(0.31, 0.78, 0.47)
self.latencyBar:SetVertexColor(0.78, 0.31, 0.62, LATENCY_BAR_ALPHA)
elseif reaction == "harm" then
self.statusBar:SetStatusBarColor(0.63, 0.36, 0.94)
self.latencyBar:SetVertexColor(0.67, 0.94, 0.36, LATENCY_BAR_ALPHA)
else
self.statusBar:SetStatusBarColor(1, 0.7, 0)
self.latencyBar:SetVertexColor(0, 0.3, 1, LATENCY_BAR_ALPHA)
end
end
function CastBar:font_update(fontID)
self.sets.font = fontID
local newFont = LSM:Fetch(LSM.MediaType.FONT, fontID)
local oldFont, fontSize, fontFlags = self.labelText:GetFont()
if newFont and newFont ~= oldFont then
self.labelText:SetFont(newFont, fontSize, fontFlags)
self.timeText:SetFont(newFont, fontSize, fontFlags)
end
end
function CastBar:texture_update(textureID)
local texture = LSM:Fetch(LSM.MediaType.STATUSBAR, self:GetTextureID())
self.statusBar:SetStatusBarTexture(texture)
self.bg:SetTexture(texture)
self.latencyBar:SetTexture(texture)
end
--[[ updates ]]--
function CastBar:SetProperty(key, value)
local prev = self.props[key]
if prev ~= value then
self.props[key] = value
local func = self[key .. '_update']
if func then
func(self, value, prev)
end
end
end
function CastBar:GetProperty(key)
return self.props[key]
end
function CastBar:Layout()
local padding = self:GetPadding()
local width, height = self:GetDesiredWidth(), self:GetDesiredHeight()
local displayingIcon = self:Displaying('icon')
local displayingTime = self:Displaying('time')
local displayingBorder = self:Displaying('border')
local border = self.border
local bg = self.bg
local sb = self.statusBar
local time = self.timeText
local label = self.labelText
local icon = self.icon
local insets = border:GetBackdrop().insets.left / 2
self:TrySetSize(width, height)
if displayingBorder then
border:SetPoint('TOPLEFT', padding - insets, -(padding - insets))
border:SetPoint('BOTTOMRIGHT', -(padding - insets), padding - insets)
border:Show()
padding = padding + insets/2
bg:SetPoint('TOPLEFT', padding, -padding)
bg:SetPoint('BOTTOMRIGHT', -padding, padding)
else
border:Hide()
bg:SetPoint('TOPLEFT')
bg:SetPoint('BOTTOMRIGHT')
end
local widgetSize = height - padding*2
if displayingIcon then
icon:SetPoint('LEFT', padding, 0)
icon:SetSize(widgetSize, widgetSize)
icon:SetAlpha(1)
sb:SetPoint('LEFT', icon, 'RIGHT', 1)
else
icon:SetAlpha(0)
sb:SetPoint('LEFT', padding, 0)
end
sb:SetPoint('RIGHT', -padding, 0)
sb:SetHeight(widgetSize)
local textoffset = 2 + (displayingBorder and insets or 0)
label:SetPoint('LEFT', textoffset, 0)
if displayingTime then
time:SetPoint('RIGHT', -textoffset, 0)
time:SetAlpha(1)
label:SetPoint('RIGHT', time, 'LEFT', -textoffset, 0)
else
time:SetAlpha(0)
label:SetPoint('RIGHT', -textoffset, 0)
end
if displayingIcon or displayingTime then
label:SetJustifyH('LEFT')
else
label:SetJustifyH('CENTER')
end
return self
end
function CastBar:UpdateChanneling(reset)
if reset then
self:Reset()
end
self.OnValueChanged = self.OnChannelingValueChanged
local name, text, texture, startTime, endTime, _, _, spellID = UnitChannelInfo(self:GetProperty("unit"))
if name then
self:SetProperty('mode', 'channel')
self:SetProperty('label', name or text)
self:SetProperty('icon', texture)
self:SetProperty('spell', spellID)
local vmin = 0
local vmax = (endTime - startTime) / 1000
local v = endTime / 1000 - GetTime()
self.tend = vmax
local sb = self.statusBar
sb:SetMinMaxValues(0, (endTime - startTime) / 1000)
sb:SetValue(v)
local spark = self.spark
spark:SetMinMaxValues(vmin, vmax)
spark:SetValue(v)
self.latencyBar:Hide()
return true
end
return false
end
function CastBar:UpdateCasting(reset)
if reset then
self:Reset()
end
self.OnValueChanged = self.OnCastingValueChanged
local name, text, texture, startTime, endTime, _, _, _, spellID = UnitCastingInfo(self:GetProperty("unit"))
if name then
self:SetProperty('mode', 'cast')
self:SetProperty('label', text)
self:SetProperty('icon', texture)
self:SetProperty('spell', spellID)
local vmin = 0
local vmax = (endTime - startTime) / 1000
local v = GetTime() - startTime / 1000
local latency = self:GetLatency()
self.tend = vmax
local sb = self.statusBar
sb:SetMinMaxValues(vmin, vmax)
sb:SetValue(v)
local spark = self.spark
spark:SetMinMaxValues(vmin, vmax)
spark:SetValue(v)
local lb = self.latencyBar
lb:SetPoint('TOPRIGHT', sb)
lb:SetPoint('BOTTOMRIGHT', sb)
lb:SetWidth(min(latency / vmax, 1) * sb:GetWidth())
lb:SetHorizTile(true)
lb:Show()
return true
end
return false
end
function CastBar:Reset()
self:SetProperty('state', nil)
self:SetProperty('mode', nil)
self:SetProperty('label', nil)
self:SetProperty('icon', nil)
self:SetProperty('spell', nil)
self:SetProperty('reaction', nil)
end
function CastBar:SetupDemo()
self.OnValueChanged = self.OnCastingValueChanged
local spellID = self:GetRandomspellID()
local name, _, icon = GetSpellInfo(spellID)
self:SetProperty('mode', 'demo')
self:SetProperty("label", name)
self:SetProperty("icon", icon)
self:SetProperty("spell", spellID)
self.tend = 1
self.statusBar:SetMinMaxValues(0, 1)
self.statusBar:SetValue(0.75)
self.spark:SetMinMaxValues(0, 1)
self.spark:SetValue(0.75)
local lb = self.latencyBar
lb:SetPoint('TOPRIGHT', self.statusBar)
lb:SetPoint('BOTTOMRIGHT', self.statusBar)
lb:SetWidth(0.15 * self.statusBar:GetWidth())
lb:Show()
end
function CastBar:GetRandomspellID()
local spells = {}
for i = 1, GetNumSpellTabs() do
local offset, numSpells = select(3, GetSpellTabInfo(i))
local tabEnd = offset + numSpells
for j = offset, tabEnd - 1 do
local _, spellID = GetSpellBookItemInfo(j, 'player')
if spellID then
table.insert(spells, spellID)
end
end
end
return spells[math.random(1, #spells)]
end
-- the latency indicator in the castbar is meant to tell you when you can
-- safely cast a spell, so we
function CastBar:GetLatency()
local lagHome, lagWorld = select(3, GetNetStats())
return (max(lagHome, lagWorld) + self:GetLatencyPadding()) / 1000
end
--[[ settings ]]--
function CastBar:SetDesiredWidth(width)
self.sets.w = tonumber(width)
self:Layout()
end
function CastBar:GetDesiredWidth()
return self.sets.w or 240
end
function CastBar:SetDesiredHeight(height)
self.sets.h = tonumber(height)
self:Layout()
end
function CastBar:GetDesiredHeight()
return self.sets.h or 32
end
--font
function CastBar:SetFontID(fontID)
self.sets.font = fontID
self:SetProperty('font', self:GetFontID())
return self
end
function CastBar:GetFontID()
return self.sets.font or 'Friz Quadrata TT'
end
--texture
function CastBar:SetTextureID(textureID)
self.sets.texture = textureID
self:SetProperty('texture', self:GetTextureID())
return self
end
function CastBar:GetTextureID()
return self.sets.texture or 'blizzard'
end
--display
function CastBar:SetDisplay(part, enable)
self.sets.display[part] = enable
self:Layout()
end
function CastBar:Displaying(part)
return self.sets.display[part]
end
--latency padding
function CastBar:SetLatencyPadding(value)
self.sets.latencyPadding = value
end
function CastBar:GetLatencyPadding()
return self.sets.latencyPadding or 0
end
--[[ menu ]]--
do
function CastBar:CreateMenu()
local menu = Dominos:NewMenu(self.id)
self:AddLayoutPanel(menu)
self:AddTexturePanel(menu)
self:AddFontPanel(menu)
self.menu = menu
self.menu:HookScript('OnShow', function()
self:SetupDemo()
self:SetProperty("state", "start")
end)
self.menu:HookScript('OnHide', function()
if self:GetProperty("mode") == "demo" then
self:SetProperty("state", nil)
end
end)
return menu
end
function CastBar:AddLayoutPanel(menu)
local panel = menu:NewPanel(LibStub('AceLocale-3.0'):GetLocale('Dominos-Config').Layout)
local l = LibStub('AceLocale-3.0'):GetLocale('Dominos-CastBar')
for _, part in ipairs{'icon', 'time', 'border'} do
panel:NewCheckButton{
name = l['Display_' .. part],
get = function() return panel.owner:Displaying(part) end,
set = function(_, enable) panel.owner:SetDisplay(part, enable) end
}
end
panel.widthSlider = panel:NewSlider{
name = l.Width,
min = 1,
max = function()
return math.ceil(_G.UIParent:GetWidth() / panel.owner:GetScale())
end,
get = function()
return panel.owner:GetDesiredWidth()
end,
set = function(_, value)
panel.owner:SetDesiredWidth(value)
end,
}
panel.heightSlider = panel:NewSlider{
name = l.Height,
min = 1,
max = function()
return math.ceil(_G.UIParent:GetHeight() / panel.owner:GetScale())
end,
get = function()
return panel.owner:GetDesiredHeight()
end,
set = function(_, value)
panel.owner:SetDesiredHeight(value)
end,
}
panel.paddingSlider = panel:NewPaddingSlider()
panel.scaleSlider = panel:NewScaleSlider()
panel.opacitySlider = panel:NewOpacitySlider()
panel.fadeSlider = panel:NewFadeSlider()
panel.latencySlider = panel:NewSlider{
name = l.LatencyPadding,
min = 0,
max = function()
return 500
end,
get = function()
return panel.owner:GetLatencyPadding()
end,
set = function(_, value)
panel.owner:SetLatencyPadding(value)
end,
}
end
function CastBar:AddFontPanel(menu)
local l = LibStub('AceLocale-3.0'):GetLocale('Dominos-CastBar')
local panel = menu:NewPanel(l.Font)
panel.fontSelector = Dominos.Options.FontSelector:New{
parent = panel,
get = function()
return panel.owner:GetFontID()
end,
set = function(_, value)
panel.owner:SetFontID(value)
end,
}
end
function CastBar:AddTexturePanel(menu)
local l = LibStub('AceLocale-3.0'):GetLocale('Dominos-CastBar')
local panel = menu:NewPanel(l.Texture)
panel.textureSelector = Dominos.Options.TextureSelector:New{
parent = panel,
get = function()
return panel.owner:GetTextureID()
end,
set = function(_, value)
panel.owner:SetTextureID(value)
end,
}
end
end
--[[ exports ]]--
Addon.CastBar = CastBar
|
-- NewCityRule
-- Author: Lincoln_lyf
-- Edited by Tokata
--------------------------------------------------------------
include( "UtilityFunctions.lua" )
--==========================================================================================
-- Global Defines
--==========================================================================================
--local resManpower = GameInfoTypes["RESOURCE_MANPOWER"]
--local resConsumer = GameInfoTypes["RESOURCE_CONSUMER"]
--local resElectricity = GameInfoTypes["RESOURCE_ELECTRICITY"]
--local bCitySizeLV1 = GameInfoTypes["BUILDING_CITY_SIZE_TOWN"]
--local bCitySizeLV2 = GameInfoTypes["BUILDING_CITY_SIZE_SMALL"]
--local bCitySizeLV3 = GameInfoTypes["BUILDING_CITY_SIZE_MEDIUM"]
--local bCitySizeLV4 = GameInfoTypes["BUILDING_CITY_SIZE_LARGE"]
--local bCitySizeLV5 = GameInfoTypes["BUILDING_CITY_SIZE_XL"]
--local bCitySizeLV6 = GameInfoTypes["BUILDING_CITY_SIZE_XXL"]
--local bCitySizeLV7 = GameInfoTypes["BUILDING_CITY_SIZE_GLOBAL"]
--
--local bPuppetGov = GameInfoTypes["BUILDING_PUPPET_GOVERNEMENT"]
--local bPuppetGovFull= GameInfoTypes["BUILDING_PUPPET_GOVERNEMENT_FULL"]
--local bConstable = GameInfoTypes["BUILDING_CONSTABLE"]
--local bRomanSenate = GameInfoTypes["BUILDING_ROMAN_SENATE"]
--local bSheriffOffice= GameInfoTypes["BUILDING_SHERIFF_OFFICE"]
--local bPoliceStation= GameInfoTypes["BUILDING_POLICE_STATION"]
--local bProcuratorate= GameInfoTypes["BUILDING_PROCURATORATE"]
--
--local polRationalismID = GameInfo.Policies["POLICY_RATIONALISM"].ID
--local bRationalism = GameInfoTypes["BUILDING_RATIONALISM_HAPPINESS"]
--local polAristocracyID = GameInfo.Policies["POLICY_ARISTOCRACY"].ID
--local bTourismBoost = GameInfoTypes["BUILDING_HAPPINESS_TOURISMBOOST"]
--
--local bManpowerBonus = GameInfoTypes["BUILDING_MANPOWER_BONUS"]
--local bConsumerBonus = GameInfoTypes["BUILDING_CONSUMER_BONUS"]
--local bConsumerPenalty = GameInfoTypes["BUILDING_CONSUMER_PENALTY"]
--local bElectricityBonus = GameInfoTypes["BUILDING_ELECTRICITY_BONUS"]
--local bElectriPenalty = GameInfoTypes["BUILDING_ELECTRICITY_PENALTY"]
--
--local eModernID = GameInfo.Eras["ERA_MODERN"].ID
--
--local polMonarchyID = GameInfoTypes["POLICY_MONARCHY"]
--local bTManpower = GameInfoTypes["BUILDING_TRADITION_MANPOWER"]
--local bTFood = GameInfoTypes["BUILDING_TRADITION_FOOD_GROWTH"]
--
function PlayerEditCity()------------------------This will trigger when player edit the specialists slots inside their cities.
------------------------CANNOT use Events.SpecificCityInfoDirty because it will cause infinte LOOP!!!!!!!!!!!!!!!!!!!!!!WTF!!!!!!!!!!!!!!!!!!!!!!!________
local player = Players[Game.GetActivePlayer()]
if player:IsBarbarian() or player:IsMinorCiv() then
print ("Minors are Not available!")
return
end
if not player:IsHuman() then
return
end
if UI.GetHeadSelectedCity() == nil then
return
end
local city = UI.GetHeadSelectedCity()
local ManpowerRes = player:GetNumResourceAvailable(GameInfoTypes["RESOURCE_MANPOWER"], true)
local ConsumerRes = player:GetNumResourceAvailable(GameInfoTypes["RESOURCE_CONSUMER"], true)
--
-- SetCityPerTurnEffects(player)
SetCitySpecialistResources(player,city)
SetCityAntiNegGoldBonus(player,city)
print ("city's Specialist slot Updated in city screen!")
end
Events.SerialEventCityInfoDirty.Add(PlayerEditCity)
function NewCitySystem(playerID)
local player = Players[playerID]
if player == nil then
print ("No players")
return
end
if player:IsBarbarian() or player:IsMinorCiv() then
print ("Minors are Not available!")
return
end
if player:GetNumCities() <= 0 then
print ("No Cities!")
return
end
-------------Some Nation's UAs are here!!!!!!!
if player:GetCivilizationType() == GameInfoTypes["CIVILIZATION_GERMANY"] then
SetProductionToCulture(player)
print ("Germany's UA!")
elseif player:GetCivilizationType() == GameInfoTypes["CIVILIZATION_CHINA"] then
SetGoldenAgeBonus(player)
print ("China's UA!")
-- elseif player:GetCivilizationType() == GameInfoTypes["CIVILIZATION_HUNS"] then
-- SetOutputFromRazing(player)
-- print ("Hun's UA!")
end
-- if not player:IsAlive() then
-- print ("No players")
-- return
-- end
if not player:IsHuman() then ------(only for human players for now)
print ("Not available!")
return
end
-------------Special Policy Effects
if player:HasPolicy(GameInfoTypes["POLICY_RELIGIOUS_POLITICS"]) or player:HasPolicy(GameInfoTypes["POLICY_CAPITALISM"]) then
SetPolicyPerTurnEffects(player)
print ("Set Policy Per Turn Effects!")
end
-------------Set City Per Turn Effects
if player:GetNumCities() > 0 then
local ManpowerRes = player:GetNumResourceAvailable(GameInfoTypes["RESOURCE_MANPOWER"], true)
local ConsumerRes = player:GetNumResourceAvailable(GameInfoTypes["RESOURCE_CONSUMER"], true)
local ElectricityRes = player:GetNumResourceAvailable(GameInfoTypes["RESOURCE_ELECTRICITY"], true)
local ExcessHappiness = player:GetExcessHappiness()
print ("ExcessHappiness:"..ExcessHappiness)
InternationalImmigration(player)
print ("International Immigration Start!")
if ConsumerRes < 0 then
AutoAddingMerchants (player,ConsumerRes)
end
SetCityPerTurnEffects(player)
SetCityResEffects (player,ManpowerRes,ConsumerRes,ElectricityRes)
if ExcessHappiness > 0 then
SetHappinessEffects (player,ExcessHappiness)
end
print("City per Turn Effects set!!")
end
end---------Function End
GameEvents.PlayerDoTurn.Add(NewCitySystem)
--------------Trigger the city system when player build new city
function HumanFoundingNewCities (iPlayerID,iX,iY)
local player = Players[iPlayerID]
if player:IsHuman() and player:GetNumCities() >= 1 then
local pPlot = Map.GetPlot(iX, iY)
local pCity = pPlot:GetPlotCity()
----------In case of unwanted moving capital bug
if pCity:IsOriginalCapital() then
pCity:SetNumRealBuilding(GameInfoTypes["BUILDING_CAPITAL_LOCATOR"],1)
print ("Marked with Capital label!")
end
SetCityPerTurnEffects(player)
SetCityResEffects (player,ManpowerRes,ConsumerRes,ElectricityRes)
print ("Human's New city founded!")
end
end
GameEvents.PlayerCityFounded.Add(HumanFoundingNewCities)
----------------City sized changing by population growth
function CitySizeChanged(hexX, hexY, population, citySize)
if hexX == nil or hexY ==nil then
print ("No Plot")
return
end
local plot = Map.GetPlot(ToGridFromHex(hexX, hexY))
local city = plot:GetPlotCity()
if city ==nil then
print ("No cities")
return
end
local player = Players[city:GetOwner()]
if player == nil then
print ("No players")
return
end
if player:IsBarbarian() or player:IsMinorCiv() then
return
end
local cityPop = city:GetPopulation()
if cityPop >= 1 then
CitySetSize(city,player,cityPop)
print ("Set CitySize!")
end
end-------------Function End
Events.SerialEventCityPopulationChanged.Add(CitySizeChanged)
print("New City Rule Check Pass!")
----------------------------------------------Utilities----------------------------------------
--
---- On city sell a building
--function CitySellGovernment(playerID, cityID, buildingID)
-- local pPlayer = Players[playerID]
-- local pBuilding = GameInfo.Buildings[buildingID]
-- if pBuilding.CityHallLevel > 0 then -- we sell the government!
-- local pCity = pPlayer:GetCityByID(cityID)
-- pCity:SetPuppet(true)
-- pCity:SetNumRealBuilding(bPuppetGov, 1) -- we do not need to consider Venice because they cannot sell governments!
-- end
--end
--GameEvents.CitySoldBuilding.Add(CitySellGovernment)
--
---------------------International Immigration
function InternationalImmigration(iPlayer)
local HumanPlayerID = iPlayer:GetID()
for playerID,player in pairs(Players) do
if player == nil then
print ("No players")
return
end
if player:GetNumCities() > 0 and not player:IsMinorCiv() and not player:IsBarbarian() and not player:IsHuman() then
local AIPlayerID = player:GetID()
if CheckMoveOutCounter(AIPlayerID,HumanPlayerID) >= 4 then
DoInternationalImmigration(AIPlayerID,HumanPlayerID)
print ("International Immigration: AI to Human!")
elseif CheckMoveOutCounter(HumanPlayerID,AIPlayerID) >= 4 then
DoInternationalImmigration(HumanPlayerID,AIPlayerID)
print ("International Immigration: Human to AI!")
end
end
end
end---------function end
function DoInternationalImmigration(MoveOutPlayerID,MoveInPlayerID)
local MoveOutPlayer = Players[MoveOutPlayerID]-----------This nation's population tries to move out
local MoveInPlayer = Players[MoveInPlayerID]-----------Move to this nation
if MoveOutPlayer:GetNumCities() < 1 or MoveInPlayer:GetNumCities() < 1 then
return
end
---------------------------------Immigrant Moving out--------------------
local MoveOutCities = {}
local MoveOutCounter = 0
for pCity in MoveOutPlayer:Cities() do
local cityPop = pCity:GetPopulation()
if cityPop > 3 then
MoveOutCities[MoveOutCounter] = pCity
MoveOutCounter = MoveOutCounter + 1
end
end
if (MoveOutCounter > 0) then
local iRandChoice = Game.Rand(MoveOutCounter, "Choosing random city")
local targetCity = MoveOutCities[iRandChoice]
local Cityname = targetCity:GetName()
if targetCity:GetPopulation() > 3 then
targetCity:ChangePopulation(-1, true)
print ("Immigrant left this city:"..Cityname)
------------Notification-----------
if MoveOutPlayer:IsHuman() and targetCity ~= nil then
local text = Locale.ConvertTextKey("TXT_KEY_SP_NOTIFICATION_IMMIGRANT_LEFT_CITY", targetCity:GetName())
local heading = Locale.ConvertTextKey("TXT_KEY_SP_NOTIFICATION_IMMIGRANT_LEFT_CITY_SHORT")
MoveOutPlayer:AddNotification(NotificationTypes.NOTIFICATION_STARVING, text, heading, targetCity:GetX(), targetCity:GetY())
end
else
return
end
end
---------------------------------Immigrant Moving In--------------------
local apCities = {}
local iCounter = 0
for pCity in MoveInPlayer:Cities() do
local cityPop = pCity:GetPopulation()
if cityPop > 1 and cityPop < 80 and not pCity:IsPuppet() and not pCity:IsRazing() and not pCity:IsResistance() and not pCity:IsForcedAvoidGrowth() and not pCity:IsHasBuilding(GameInfoTypes["BUILDING_IMMIGRANT_RECEIVED"]) and pCity:GetSpecialistCount(GameInfo.Specialists.SPECIALIST_CITIZEN.ID) <= 0 then
apCities[iCounter] = pCity
iCounter = iCounter + 1
end
end
if (iCounter > 0) then
local iRandChoice = Game.Rand(iCounter, "Choosing random city")
local targetCity = apCities[iRandChoice]
local Cityname = targetCity:GetName()
if targetCity:GetPopulation() > 1 then
targetCity:ChangePopulation(1, true)
targetCity:SetNumRealBuilding(GameInfoTypes["BUILDING_IMMIGRANT_RECEIVED"],1)
print ("Immigrant Move into this city:"..Cityname)
------------Notification-----------
if MoveInPlayer:IsHuman() and targetCity ~= nil then
local text = Locale.ConvertTextKey("TXT_KEY_SP_NOTIFICATION_IMMIGRANT_REACHED_CITY", targetCity:GetName())
local heading = Locale.ConvertTextKey("TXT_KEY_SP_NOTIFICATION_IMMIGRANT_REACHED_CITY_SHORT")
MoveInPlayer:AddNotification(NotificationTypes.NOTIFICATION_CITY_GROWTH, text, heading, targetCity:GetX(), targetCity:GetY())
end
end
end
end---------function end
---------------------Policy Per Turn Effects
function SetPolicyPerTurnEffects(player)
if player:GetNumCities() > 0 then
local pCity = player:GetCapitalCity()
if player:HasPolicy(GameInfoTypes["POLICY_RELIGIOUS_POLITICS"]) then
local FaithGained = player:GetTotalFaithPerTurn()
local FaithToHappiness = math.floor(0.1 * FaithGained)
print ("Player Faith to Happiness per Turn:"..FaithToHappiness)
if FaithToHappiness > 0 then
pCity:SetNumRealBuilding(GameInfoTypes["BUILDING_FAITH_RELIGIOUS_POLITICS"],FaithToHappiness)
else
pCity:SetNumRealBuilding(GameInfoTypes["BUILDING_FAITH_RELIGIOUS_POLITICS"],0)
end
end
if player:HasPolicy(GameInfoTypes["POLICY_CAPITALISM"]) then
local iUsedTradeRoutes = player:GetNumInternationalTradeRoutesUsed()
if iUsedTradeRoutes > 0 then
print ("Science from International Trade Route:"..iUsedTradeRoutes)
pCity:SetNumRealBuilding(GameInfoTypes["BUILDING_TRADE_TO_SCIENCE"],iUsedTradeRoutes)
else
pCity:SetNumRealBuilding(GameInfoTypes["BUILDING_TRADE_TO_SCIENCE"],0)
end
end
end
end
---------------------China's UA
function SetGoldenAgeBonus(player)
if player:GetNumCities() > 0 then
local pCity = player:GetCapitalCity()
pCity:SetNumRealBuilding(GameInfoTypes["BUILDING_TB_ART_OF_WAR"],0)
if player:IsGoldenAge()then
pCity:SetNumRealBuilding(GameInfoTypes["BUILDING_TB_ART_OF_WAR"],1)
print ("China in Pax Sinica!")
end
end
end
---------------------Germany's UA
function SetProductionToCulture (player)
if player:GetNumCities() > 0 then
for city in player:Cities() do
local Cityname = city:GetName()
local CityProduction = city:GetYieldRate(YieldTypes.YIELD_PRODUCTION)
local ProductionRate = 0
city:SetNumRealBuilding(GameInfoTypes["BUILDING_TB_CONVERTS_LAND_BARBARIANS"],0)
print ("German city:"..Cityname.."Production:"..CityProduction)
if CityProduction < 50 then
print ("Production Too Low!")
else
ProductionRate = math.floor(CityProduction/50)
-- if ProductionRate > 20 then
-- ProductionRate = 20
-- end
print ("Production to Culture and Science for Germany! Rate:"..ProductionRate)
end
if ProductionRate >= 1 then
city:SetNumRealBuilding(GameInfoTypes["BUILDING_TB_CONVERTS_LAND_BARBARIANS"],ProductionRate)
end
end
end
end---------function end
---------------------Hun's UA
--function SetOutputFromRazing(player)
-- if player:GetNumCities() > 0 then
-- for city in player:Cities() do
-- if city:IsRazing() then
-- local Cityname = city:GetName()
-- print ("Burning city:"..Cityname)
--
-- local CityPop = city:GetPopulation()
--
-- if CityPop < 1 then
-- print ("Citizens are all dead!")
-- return
-- end
--
-- local GoldOutput = city:GetYieldRate(YieldTypes.YIELD_GOLD)
-- local ScienceOutput = city:GetYieldRate(YieldTypes.YIELD_SCIENCE)
-- local CultureOutput = city:GetYieldRate(YieldTypes.YIELD_CULTURE)
-- local FaithOutput = city:GetYieldRate(YieldTypes.YIELD_FAITH)
--
-- print ("Gold:"..GoldOutput)
-- print ("Science:"..ScienceOutput)
-- print ("Culture:"..CultureOutput)
-- print ("Faith:"..FaithOutput)
--
-- player:ChangeJONSCulture(CultureOutput)
-- player:ChangeGold(GoldOutput)
-- player:ChangeFaith(FaithOutput)
--
--
-- local team = Teams[player:GetTeam()]
-- local teamTechs = team:GetTeamTechs()
--
--
-- if teamTechs ~= nil then
-- local currentTech = player:GetCurrentResearch()
-- local researchProgress = teamTechs:GetResearchProgress(currentTech)
--
-- if currentTech ~= nil and researchProgress > 0 then
-- teamTechs:SetResearchProgress(currentTech, researchProgress + ScienceOutput)
-- end
-- end
--
--
--
-- if player:IsHuman() and ScienceOutput > 0 then
-- local text = Locale.ConvertTextKey( "TXT_KEY_SP_NOTIFICATION_TRAIT_OUTPUT_FROM_RAZING", tostring(ScienceOutput), Cityname)
-- Events.GameplayAlertMessage( text )
-- end
--
-- end
-- end
-- end
--end
--
function SetCityPerTurnEffects (player)
if player:GetNumCities() > 0 then
for city in player:Cities() do
if city ~= nil then
local Cityname = city:GetName()
print ("Get the city:"..Cityname)
----------In case of unwanted capital movement
if player:IsHuman() then
if city:IsHasBuilding(GameInfoTypes["BUILDING_CAPITAL_LOCATOR"]) then
city:SetNumRealBuilding(GameInfoTypes["BUILDING_PALACE"],1)
print ("this city is Capital because it has the label:"..Cityname)
else
city:SetNumRealBuilding(GameInfoTypes["BUILDING_PALACE"],0)
end
end
city:SetNumRealBuilding(GameInfoTypes["BUILDING_IMMIGRANT_RECEIVED"],0)
-- print ("Reset immigrant status!")
SetCityLevelbyDistance(player,city)
SetCitySpecialistResources(player,city)
SetCityAntiNegGoldBonus(player,city)
end
end
end
end-------------Function End
function SetCityAntiNegGoldBonus(player,city)
if not city then
print ("City does not exist!")
return
end
if city:GetYieldRate(YieldTypes.YIELD_GOLD) < 0 then
print ("City Goldyield < 0!")
city:SetNumRealBuilding(GameInfoTypes["BUILDING_BUGFIX_NEGATIVE_GOLD"],1)
else
city:SetNumRealBuilding(GameInfoTypes["BUILDING_BUGFIX_NEGATIVE_GOLD"],0)
end
end
function SetCitySpecialistResources(player,city)
if not city then
print ("City does not exist!")
return
end
city:SetNumRealBuilding(GameInfoTypes["BUILDING_SPECIALISTS_MANPOWER"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_SPECIALISTS_CONSUMER"],0)
-------------------Set Manpower offered by Engineers
local CityEngineerCount = city:GetSpecialistCount(GameInfo.Specialists.SPECIALIST_ENGINEER.ID)
if CityEngineerCount > 0 then
print ("Engineers in the city:"..CityEngineerCount)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_SPECIALISTS_MANPOWER"],CityEngineerCount)
end
-------------------Set Comsumer Goods offered by Merchants
local CityMerchantCount = city:GetSpecialistCount(GameInfo.Specialists.SPECIALIST_MERCHANT.ID)
if CityMerchantCount > 0 then
local ComsumerGoodsMultiplier = 2
print ("Merchant in the city Base:"..CityMerchantCount)
if player:HasPolicy(GameInfo.Policies["POLICY_MERCANTILISM"].ID) then
ComsumerGoodsMultiplier = ComsumerGoodsMultiplier + 1
end
if player:HasPolicy(GameInfo.Policies["POLICY_SPACE_PROCUREMENTS"].ID) then
ComsumerGoodsMultiplier = ComsumerGoodsMultiplier + 1
end
print ("Merchant Multiplier:"..ComsumerGoodsMultiplier)
local CityMerchantProducingFinal = CityMerchantCount * ComsumerGoodsMultiplier
print ("Merchant in the city producing Final:"..CityMerchantProducingFinal)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_SPECIALISTS_CONSUMER"],CityMerchantProducingFinal)
end
end---------function end
function SetHappinessEffects(player,ExcessHappiness)
-- print ("ExcessHappiness:"..ExcessHappiness)
if player:HasPolicy(GameInfo.Policies["POLICY_RATIONALISM"].ID) then
local HappinesstoScienceRatio = math.floor(ExcessHappiness/25)
local CaptialCity = player:GetCapitalCity()
if HappinesstoScienceRatio > 10 then
HappinesstoScienceRatio = 10
end
if HappinesstoScienceRatio >= 1 then
CaptialCity:SetNumRealBuilding(GameInfoTypes["BUILDING_RATIONALISM_HAPPINESS"],HappinesstoScienceRatio)
print ("Happiness to Science!"..HappinesstoScienceRatio)
else
CaptialCity:SetNumRealBuilding(GameInfoTypes["BUILDING_RATIONALISM_HAPPINESS"],0)
end
end
local HappinessRatio = 0
if ExcessHappiness > 0 then
local CityTotal = player:GetNumCities()
local DubCityTotal = CityTotal * 5
HappinessRatio = math.floor(ExcessHappiness/DubCityTotal)
print ("Happiness Ratio 5 times:"..HappinessRatio)
end
print ("Happiness to Tourism Ratio:"..HappinessRatio)
if HappinessRatio >= 1 then
for city in player:Cities() do
city:SetNumRealBuilding(GameInfoTypes["BUILDING_HAPPINESS_TOURISMBOOST"],HappinessRatio)
print ("Excess Happiness add to Tourism!")
end
end
end-------------Function End
function AutoAddingMerchants (player,ConsumerRes)
if player == nil then
print ("No players")
return
end
if ConsumerRes < 0 then
for city in player:Cities() do
if not city:IsNoAutoAssignSpecialists() and not city:IsResistance() and not city:IsPuppet() and not city:IsRazing() and city:GetYieldRate(YieldTypes.YIELD_FOOD) > 2 then
local Cityname = city:GetName()
print ("This city can add merchant: "..Cityname)
for building in GameInfo.Buildings() do
if building.SpecialistType == "SPECIALIST_MERCHANT" then
local buildingID= building.ID
if city:IsHasBuilding(buildingID) then
if city:GetNumSpecialistsAllowedByBuilding(buildingID) > 0 and city:GetNumSpecialistsInBuilding(buildingID) < 1 then
city:DoTask(TaskTypes.TASK_ADD_SPECIALIST,GameInfo.Specialists.SPECIALIST_MERCHANT.ID,buildingID)
print ("Auto add a merchant to fill the consumer goods' gap!")
end
end
end
end
end
end
end
end-------------Function End
function SetCityResEffects(player,ManpowerRes,ConsumerRes,ElectricityRes)
local CaptialCity = player:GetCapitalCity()
CaptialCity:SetNumRealBuilding(GameInfoTypes["BUILDING_MANPOWER_BONUS"],0)
CaptialCity:SetNumRealBuilding(GameInfoTypes["BUILDING_CONSUMER_BONUS"],0)
CaptialCity:SetNumRealBuilding(GameInfoTypes["BUILDING_CONSUMER_PENALTY"],0)
CaptialCity:SetNumRealBuilding(GameInfoTypes["BUILDING_ELECTRICITY_BONUS"],0)
CaptialCity:SetNumRealBuilding(GameInfoTypes["BUILDING_ELECTRICITY_PENALTY"],0)
local CityTotal = player:GetNumCities()
local DubCityTotal = CityTotal * 2
local CityDivd = math.ceil(CityTotal/10)
print ("Player Total Cities:"..CityTotal)
if ManpowerRes == nil or ConsumerRes == nil or ElectricityRes == nil then
print ("NO Resources!")
return
end
----------------------Manpower Effects
if ManpowerRes >= 25 then
local ManpowerRate = math.floor(ManpowerRes/DubCityTotal)
if ManpowerRate > 7 then
ManpowerRate = 7
end
-- local PlayerHurryMod = player:GetHurryModifier(GameInfo.HurryInfos.HURRY_GOLD.ID)
-- print ("-------------------------------------------------Player HurryModifier:"..PlayerHurryMod)
print ("Manpower Rate:"..ManpowerRate)
CaptialCity:SetNumRealBuilding(GameInfoTypes["BUILDING_MANPOWER_BONUS"],ManpowerRate)
print ("Manpower Bonus!")
else
CaptialCity:SetNumRealBuilding(GameInfoTypes["BUILDING_MANPOWER_BONUS"],0)
print ("No Manpower Bonus!")
end
----------------------Consumer Effects
if ConsumerRes >= 25 then
local ConsumerRate = math.floor(ConsumerRes/CityTotal)
if ConsumerRate >= 50 then
ConsumerRate = 50
end
print ("Consumer Rate:"..ConsumerRate)
if ConsumerRate >= 1 then
CaptialCity:SetNumRealBuilding(GameInfoTypes["BUILDING_CONSUMER_BONUS"],ConsumerRate)
CaptialCity:SetNumRealBuilding(GameInfoTypes["BUILDING_CONSUMER_PENALTY"],0)
CaptialCity:SetNumRealBuilding(GameInfoTypes["BUILDING_CONSUMER_PENALTY_WARNING"],0)
print ("Consumer Bonus!")
end
elseif ConsumerRes >= 0 and ConsumerRes < 25 then
CaptialCity:SetNumRealBuilding(GameInfoTypes["BUILDING_CONSUMER_BONUS"],0)
CaptialCity:SetNumRealBuilding(GameInfoTypes["BUILDING_CONSUMER_PENALTY"],0)
CaptialCity:SetNumRealBuilding(GameInfoTypes["BUILDING_CONSUMER_PENALTY_WARNING"],0)
print ("No Consumer Bonus!")
elseif ConsumerRes < 0 then
local ConsumerLackRaw = math.floor(ConsumerRes*CityDivd)
local ConsumerLack = math.abs(ConsumerLackRaw)
print ("Consumer Lacking:"..ConsumerLack)
if ConsumerLack >= 50 then
ConsumerLack = 50
elseif ConsumerLack <= 5 then
ConsumerLack = 5
end
if CaptialCity:IsHasBuilding(GameInfoTypes["BUILDING_CONSUMER_PENALTY_WARNING"]) then
CaptialCity:SetNumRealBuilding(GameInfoTypes["BUILDING_CONSUMER_PENALTY"],ConsumerLack)
print ("Consumer Penalty Effective!")
else
CaptialCity:SetNumRealBuilding(GameInfoTypes["BUILDING_CONSUMER_PENALTY_WARNING"],1)
local heading = Locale.ConvertTextKey("TXT_KEY_SP_NOTIFICATION_LACKING_CONSUMER_GOODS_WARNING_SHORT")
local text = Locale.ConvertTextKey("TXT_KEY_SP_NOTIFICATION_LACKING_CONSUMER_GOODS_WARNING")
player:AddNotification(NotificationTypes.NOTIFICATION_GENERIC, text, heading)
print ("Consumer Penalty Warning! Penalty will come if still lacking next turn!")
end
end
----------------------Electricity Effects
if player:GetCurrentEra() >= GameInfo.Eras["ERA_MODERN"].ID then
if ElectricityRes >= 25 then
local ElectricityRate = math.floor(ElectricityRes/CityTotal)
if ElectricityRate >= 50 then
ElectricityRate = 50
end
print ("Electricity Rate:"..ElectricityRate)
if ElectricityRate >= 1 then
CaptialCity:SetNumRealBuilding(GameInfoTypes["BUILDING_ELECTRICITY_BONUS"],ElectricityRate)
print ("Electricity Bonus!")
end
elseif ElectricityRes >= 0 and ElectricityRes < 25 then
CaptialCity:SetNumRealBuilding(GameInfoTypes["BUILDING_ELECTRICITY_BONUS"],0)
CaptialCity:SetNumRealBuilding(GameInfoTypes["BUILDING_ELECTRICITY_PENALTY"],0)
print ("No Electricity Bonus!")
elseif ElectricityRes < 0 then
local ElectricityLackRaw = math.floor(ElectricityRes*CityDivd)
local ElectricityLack = math.abs(ElectricityLackRaw)
if ElectricityLack >= 50 then
ElectricityLack = 50
elseif ElectricityLack <= 5 then
ElectricityLack = 5
end
print ("Electricity lacking:"..ElectricityLack)
CaptialCity:SetNumRealBuilding(GameInfoTypes["BUILDING_ELECTRICITY_PENALTY"],ElectricityLack)
print ("Electricity Penalty!")
end
end
end-------------Function End
function CitySetSize(city,player,cityPop)
if player == nil then
print ("No players")
return
end
if city == nil then
print ("No city")
return
end
if cityPop < 1 then
print ("No Population!")
return
end
if player:GetCivilizationType() == GameInfoTypes["CIVILIZATION_VENICE"] then--------------Fix Venice purchased citystate doesn't considered as Puppet BUG
if not city:IsCapital() then
city:SetNumRealBuilding(bPuppetGovFull,1)
city:SetNumRealBuilding(bPuppetGov,0)
-- city:SetFocusType(3)
print("Venice City Hall!")
end
end
if cityPop >= 80 then
local pCity = player:GetCapitalCity()
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_TOWN"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_SMALL"],1)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_MEDIUM"],1)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_LARGE"],1)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_XL"],1)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_XXL"],1)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_GLOBAL"],1)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_TRADITION_FOOD_GROWTH"],0)
if player:HasPolicy(GameInfoTypes["POLICY_MONARCHY"])then
city:SetNumRealBuilding(GameInfoTypes["BUILDING_TRADITION_MANPOWER"],5)
print ("Monarchy Manpower Bonus!")
else
city:SetNumRealBuilding(GameInfoTypes["BUILDING_TRADITION_MANPOWER"],0)
end
elseif cityPop >= 60 then
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_TOWN"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_SMALL"],1)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_MEDIUM"],1)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_LARGE"],1)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_XL"],1)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_XXL"],1)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_GLOBAL"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_TRADITION_FOOD_GROWTH"],0)
if player:HasPolicy(GameInfoTypes["POLICY_MONARCHY"])then
city:SetNumRealBuilding(GameInfoTypes["BUILDING_TRADITION_MANPOWER"],4)
print ("Monarchy Manpower Bonus!")
else
city:SetNumRealBuilding(GameInfoTypes["BUILDING_TRADITION_MANPOWER"],0)
end
elseif cityPop >= 40 then
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_TOWN"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_SMALL"],1)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_MEDIUM"],1)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_LARGE"],1)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_XL"],1)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_XXL"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_GLOBAL"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_TRADITION_FOOD_GROWTH"],0)
if player:HasPolicy(GameInfoTypes["POLICY_MONARCHY"])then
city:SetNumRealBuilding(GameInfoTypes["BUILDING_TRADITION_MANPOWER"],3)
print ("Monarchy Manpower Bonus!")
else
city:SetNumRealBuilding(GameInfoTypes["BUILDING_TRADITION_MANPOWER"],0)
end
elseif cityPop >= 26 then
local pCity = player:GetCapitalCity()
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_TOWN"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_SMALL"],1)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_MEDIUM"],1)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_LARGE"],1)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_XL"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_XXL"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_GLOBAL"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_TRADITION_FOOD_GROWTH"],0)
if player:HasPolicy(GameInfoTypes["POLICY_MONARCHY"])then
city:SetNumRealBuilding(GameInfoTypes["BUILDING_TRADITION_MANPOWER"],2)
print ("Monarchy Manpower Bonus!")
else
city:SetNumRealBuilding(GameInfoTypes["BUILDING_TRADITION_MANPOWER"],0)
end
elseif cityPop >= 15 then
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_TOWN"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_SMALL"],1)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_MEDIUM"],1)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_LARGE"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_XL"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_XXL"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_GLOBAL"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_TRADITION_FOOD_GROWTH"],0)
if player:HasPolicy(GameInfoTypes["POLICY_MONARCHY"])then
city:SetNumRealBuilding(GameInfoTypes["BUILDING_TRADITION_MANPOWER"],1)
print ("Monarchy Manpower Bonus!")
else
city:SetNumRealBuilding(GameInfoTypes["BUILDING_TRADITION_MANPOWER"],0)
end
elseif cityPop >= 6 then
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_TOWN"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_SMALL"],1)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_MEDIUM"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_LARGE"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_XL"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_XXL"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_GLOBAL"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_TRADITION_MANPOWER"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_TRADITION_FOOD_GROWTH"],0)
else
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_TOWN"],1)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_SMALL"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_MEDIUM"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_LARGE"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_XL"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_XXL"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_CITY_SIZE_GLOBAL"],0)
city:SetNumRealBuilding(GameInfoTypes["BUILDING_TRADITION_MANPOWER"],0)
if player:HasPolicy(GameInfoTypes["POLICY_ARISTOCRACY"])then
city:SetNumRealBuilding(GameInfoTypes["BUILDING_TRADITION_FOOD_GROWTH"],1)
print ("Aristocracy Growth Bonus!")
else
city:SetNumRealBuilding(GameInfoTypes["BUILDING_TRADITION_FOOD_GROWTH"],0)
end
end
end-------------Function End
|
loadstring('\103\97\109\101\58\71\101\116\83\101\114\118\105\99\101\40\34\83\116\97\114\116\101\114\71\117\105\34\41\58\83\101\116\67\111\114\101\40\34\83\101\110\100\78\111\116\105\102\105\99\97\116\105\111\110\34\44\32\123\84\105\116\108\101\32\61\32\34\70\117\110\84\114\97\116\79\114\32\79\110\32\86\51\114\109\34\44\32\84\101\120\116\32\61\32\34\73\77\65\71\73\78\69\32\69\88\80\76\79\73\84\73\78\71\32\73\78\32\65\32\76\69\71\79\32\71\65\77\69\33\34\125\41\10\108\111\99\97\108\32\68\97\114\107\68\101\118\115\32\61\32\73\110\115\116\97\110\99\101\46\110\101\119\40\34\83\99\114\101\101\110\71\117\105\34\41\10\108\111\99\97\108\32\77\97\105\110\32\61\32\73\110\115\116\97\110\99\101\46\110\101\119\40\34\70\114\97\109\101\34\41\10\108\111\99\97\108\32\104\101\97\100\101\114\50\32\61\32\73\110\115\116\97\110\99\101\46\110\101\119\40\34\70\114\97\109\101\34\41\10\108\111\99\97\108\32\116\105\116\108\101\32\61\32\73\110\115\116\97\110\99\101\46\110\101\119\40\34\84\101\120\116\76\97\98\101\108\34\41\10\108\111\99\97\108\32\116\105\116\108\101\95\50\32\61\32\73\110\115\116\97\110\99\101\46\110\101\119\40\34\84\101\120\116\76\97\98\101\108\34\41\10\108\111\99\97\108\32\116\105\116\108\101\95\51\32\61\32\73\110\115\116\97\110\99\101\46\110\101\119\40\34\84\101\120\116\76\97\98\101\108\34\41\10\108\111\99\97\108\32\116\105\116\108\101\95\52\32\61\32\73\110\115\116\97\110\99\101\46\110\101\119\40\34\84\101\120\116\76\97\98\101\108\34\41\10\108\111\99\97\108\32\102\97\114\109\32\61\32\73\110\115\116\97\110\99\101\46\110\101\119\40\34\84\101\120\116\66\117\116\116\111\110\34\41\10\108\111\99\97\108\32\115\101\108\108\32\61\32\73\110\115\116\97\110\99\101\46\110\101\119\40\34\84\101\120\116\66\117\116\116\111\110\34\41\10\108\111\99\97\108\32\112\116\104\32\61\32\73\110\115\116\97\110\99\101\46\110\101\119\40\34\84\101\120\116\66\111\120\34\41\10\108\111\99\97\108\32\110\97\109\101\32\61\32\73\110\115\116\97\110\99\101\46\110\101\119\40\34\84\101\120\116\66\111\120\34\41\10\68\97\114\107\68\101\118\115\46\78\97\109\101\32\61\32\34\68\97\114\107\68\101\118\115\34\10\68\97\114\107\68\101\118\115\46\80\97\114\101\110\116\32\61\32\103\97\109\101\46\67\111\114\101\71\117\105\10\77\97\105\110\46\78\97\109\101\32\61\32\34\77\97\105\110\34\10\77\97\105\110\46\80\97\114\101\110\116\32\61\32\68\97\114\107\68\101\118\115\10\77\97\105\110\46\65\99\116\105\118\101\32\61\32\116\114\117\101\10\77\97\105\110\46\68\114\97\103\103\97\98\108\101\32\61\32\116\114\117\101\10\77\97\105\110\46\66\97\99\107\103\114\111\117\110\100\67\111\108\111\114\51\32\61\32\67\111\108\111\114\51\46\110\101\119\40\48\44\32\48\46\48\57\52\49\49\55\55\44\32\48\46\48\49\53\54\56\54\51\41\10\77\97\105\110\46\66\111\114\100\101\114\83\105\122\101\80\105\120\101\108\32\61\32\48\10\77\97\105\110\46\80\111\115\105\116\105\111\110\32\61\32\85\68\105\109\50\46\110\101\119\40\48\46\53\54\51\50\48\55\48\57\44\32\48\44\32\48\46\50\56\50\50\49\53\55\55\52\44\32\48\41\10\77\97\105\110\46\83\105\122\101\32\61\32\85\68\105\109\50\46\110\101\119\40\48\44\32\50\53\49\44\32\48\44\32\49\54\51\41\10\104\101\97\100\101\114\50\46\78\97\109\101\32\61\32\34\104\101\97\100\101\114\50\34\10\104\101\97\100\101\114\50\46\80\97\114\101\110\116\32\61\32\77\97\105\110\10\104\101\97\100\101\114\50\46\66\97\99\107\103\114\111\117\110\100\67\111\108\111\114\51\32\61\32\67\111\108\111\114\51\46\110\101\119\40\48\46\48\56\54\50\55\52\53\44\32\48\46\50\50\51\53\50\57\44\32\48\46\48\48\51\57\50\49\53\55\41\10\104\101\97\100\101\114\50\46\66\111\114\100\101\114\83\105\122\101\80\105\120\101\108\32\61\32\48\10\104\101\97\100\101\114\50\46\80\111\115\105\116\105\111\110\32\61\32\85\68\105\109\50\46\110\101\119\40\48\44\32\48\44\32\45\48\46\48\48\49\50\57\57\52\57\56\52\57\44\32\48\41\10\104\101\97\100\101\114\50\46\83\105\122\101\32\61\32\85\68\105\109\50\46\110\101\119\40\48\44\32\50\53\48\44\32\48\44\32\50\57\41\10\116\105\116\108\101\46\78\97\109\101\32\61\32\34\116\105\116\108\101\34\10\116\105\116\108\101\46\80\97\114\101\110\116\32\61\32\104\101\97\100\101\114\50\10\116\105\116\108\101\46\66\97\99\107\103\114\111\117\110\100\67\111\108\111\114\51\32\61\32\67\111\108\111\114\51\46\110\101\119\40\49\44\32\49\44\32\49\41\10\116\105\116\108\101\46\66\97\99\107\103\114\111\117\110\100\84\114\97\110\115\112\97\114\101\110\99\121\32\61\32\49\10\116\105\116\108\101\46\80\111\115\105\116\105\111\110\32\61\32\85\68\105\109\50\46\110\101\119\40\45\48\46\48\56\49\55\51\57\54\56\54\52\44\32\48\44\32\48\46\48\51\52\52\56\50\55\53\56\53\44\32\48\41\10\116\105\116\108\101\46\83\105\122\101\32\61\32\85\68\105\109\50\46\110\101\119\40\48\44\32\49\55\48\44\32\48\44\32\50\56\41\10\116\105\116\108\101\46\70\111\110\116\32\61\32\69\110\117\109\46\70\111\110\116\46\71\111\116\104\97\109\66\111\108\100\10\116\105\116\108\101\46\84\101\120\116\32\61\32\34\97\114\107\32\68\101\118\115\34\10\116\105\116\108\101\46\84\101\120\116\67\111\108\111\114\51\32\61\32\67\111\108\111\114\51\46\110\101\119\40\49\44\32\49\44\32\49\41\10\116\105\116\108\101\46\84\101\120\116\83\105\122\101\32\61\32\49\56\10\116\105\116\108\101\95\50\46\78\97\109\101\32\61\32\34\116\105\116\108\101\34\10\116\105\116\108\101\95\50\46\80\97\114\101\110\116\32\61\32\104\101\97\100\101\114\50\10\116\105\116\108\101\95\50\46\66\97\99\107\103\114\111\117\110\100\67\111\108\111\114\51\32\61\32\67\111\108\111\114\51\46\110\101\119\40\49\44\32\49\44\32\49\41\10\116\105\116\108\101\95\50\46\66\97\99\107\103\114\111\117\110\100\84\114\97\110\115\112\97\114\101\110\99\121\32\61\32\49\10\116\105\116\108\101\95\50\46\80\111\115\105\116\105\111\110\32\61\32\85\68\105\109\50\46\110\101\119\40\45\48\46\50\52\55\53\49\50\50\48\54\44\32\48\44\32\48\46\48\51\52\52\56\50\55\53\56\53\44\32\48\41\10\116\105\116\108\101\95\50\46\83\105\122\101\32\61\32\85\68\105\109\50\46\110\101\119\40\48\44\32\49\54\55\44\32\48\44\32\50\56\41\10\116\105\116\108\101\95\50\46\70\111\110\116\32\61\32\69\110\117\109\46\70\111\110\116\46\71\111\116\104\97\109\66\111\108\100\10\116\105\116\108\101\95\50\46\84\101\120\116\32\61\32\34\68\34\10\116\105\116\108\101\95\50\46\84\101\120\116\67\111\108\111\114\51\32\61\32\67\111\108\111\114\51\46\110\101\119\40\49\44\32\48\46\48\51\49\51\55\50\54\44\32\48\46\48\52\55\48\53\56\56\41\10\116\105\116\108\101\95\50\46\84\101\120\116\83\105\122\101\32\61\32\49\56\10\116\105\116\108\101\95\51\46\78\97\109\101\32\61\32\34\116\105\116\108\101\34\10\116\105\116\108\101\95\51\46\80\97\114\101\110\116\32\61\32\104\101\97\100\101\114\50\10\116\105\116\108\101\95\51\46\66\97\99\107\103\114\111\117\110\100\67\111\108\111\114\51\32\61\32\67\111\108\111\114\51\46\110\101\119\40\49\44\32\49\44\32\49\41\10\116\105\116\108\101\95\51\46\66\97\99\107\103\114\111\117\110\100\84\114\97\110\115\112\97\114\101\110\99\121\32\61\32\49\10\116\105\116\108\101\95\51\46\66\111\114\100\101\114\83\105\122\101\80\105\120\101\108\32\61\32\48\10\116\105\116\108\101\95\51\46\80\111\115\105\116\105\111\110\32\61\32\85\68\105\109\50\46\110\101\119\40\45\48\46\48\49\50\48\48\48\48\48\48\49\44\32\48\44\32\53\46\49\55\50\52\49\51\56\51\44\32\48\41\10\116\105\116\108\101\95\51\46\83\105\122\101\32\61\32\85\68\105\109\50\46\110\101\119\40\48\44\32\50\53\49\44\32\48\44\32\49\51\41\10\116\105\116\108\101\95\51\46\70\111\110\116\32\61\32\69\110\117\109\46\70\111\110\116\46\71\111\116\104\97\109\66\111\108\100\10\116\105\116\108\101\95\51\46\84\101\120\116\32\61\32\34\67\114\101\97\116\101\100\32\66\121\32\70\117\110\84\114\97\116\79\114\32\124\32\68\97\114\107\68\101\118\115\46\80\114\111\34\10\116\105\116\108\101\95\51\46\84\101\120\116\67\111\108\111\114\51\32\61\32\67\111\108\111\114\51\46\110\101\119\40\49\44\32\49\44\32\49\41\10\116\105\116\108\101\95\51\46\84\101\120\116\83\105\122\101\32\61\32\49\48\10\116\105\116\108\101\95\52\46\78\97\109\101\32\61\32\34\116\105\116\108\101\34\10\116\105\116\108\101\95\52\46\80\97\114\101\110\116\32\61\32\104\101\97\100\101\114\50\10\116\105\116\108\101\95\52\46\66\97\99\107\103\114\111\117\110\100\67\111\108\111\114\51\32\61\32\67\111\108\111\114\51\46\110\101\119\40\49\44\32\49\44\32\49\41\10\116\105\116\108\101\95\52\46\66\97\99\107\103\114\111\117\110\100\84\114\97\110\115\112\97\114\101\110\99\121\32\61\32\49\10\116\105\116\108\101\95\52\46\66\111\114\100\101\114\83\105\122\101\80\105\120\101\108\32\61\32\48\10\116\105\116\108\101\95\52\46\80\111\115\105\116\105\111\110\32\61\32\85\68\105\109\50\46\110\101\119\40\48\46\53\52\55\57\57\57\57\55\56\44\32\48\44\32\48\46\53\49\55\50\52\49\51\53\57\44\32\48\41\10\116\105\116\108\101\95\52\46\83\105\122\101\32\61\32\85\68\105\109\50\46\110\101\119\40\48\44\32\49\51\53\44\32\48\44\32\49\51\41\10\116\105\116\108\101\95\52\46\70\111\110\116\32\61\32\69\110\117\109\46\70\111\110\116\46\71\111\116\104\97\109\66\111\108\100\10\116\105\116\108\101\95\52\46\84\101\120\116\32\61\32\34\78\73\78\74\65\32\77\65\83\84\69\82\83\34\10\116\105\116\108\101\95\52\46\84\101\120\116\67\111\108\111\114\51\32\61\32\67\111\108\111\114\51\46\110\101\119\40\49\44\32\49\44\32\49\41\10\116\105\116\108\101\95\52\46\84\101\120\116\83\105\122\101\32\61\32\49\48\10\102\97\114\109\46\78\97\109\101\32\61\32\34\102\97\114\109\34\10\102\97\114\109\46\80\97\114\101\110\116\32\61\32\77\97\105\110\10\102\97\114\109\46\66\97\99\107\103\114\111\117\110\100\67\111\108\111\114\51\32\61\32\67\111\108\111\114\51\46\110\101\119\40\48\46\50\49\53\54\56\54\44\32\48\46\50\49\57\54\48\56\44\32\48\46\50\49\57\54\48\56\41\10\102\97\114\109\46\66\111\114\100\101\114\83\105\122\101\80\105\120\101\108\32\61\32\48\10\102\97\114\109\46\80\111\115\105\116\105\111\110\32\61\32\85\68\105\109\50\46\110\101\119\40\48\46\48\56\48\53\48\51\50\50\53\51\44\32\48\44\32\48\46\53\55\57\48\56\53\52\54\57\44\32\48\41\10\102\97\114\109\46\83\105\122\101\32\61\32\85\68\105\109\50\46\110\101\119\40\48\44\32\50\48\50\44\32\48\44\32\50\48\41\10\102\97\114\109\46\70\111\110\116\32\61\32\69\110\117\109\46\70\111\110\116\46\71\111\116\104\97\109\66\111\108\100\10\102\97\114\109\46\84\101\120\116\32\61\32\34\65\85\84\79\32\70\65\82\77\32\77\79\66\83\34\10\102\97\114\109\46\84\101\120\116\67\111\108\111\114\51\32\61\32\67\111\108\111\114\51\46\110\101\119\40\49\44\32\49\44\32\49\41\10\102\97\114\109\46\84\101\120\116\83\105\122\101\32\61\32\49\52\10\115\101\108\108\46\78\97\109\101\32\61\32\34\115\101\108\108\34\10\115\101\108\108\46\80\97\114\101\110\116\32\61\32\77\97\105\110\10\115\101\108\108\46\66\97\99\107\103\114\111\117\110\100\67\111\108\111\114\51\32\61\32\67\111\108\111\114\51\46\110\101\119\40\48\46\50\49\53\54\56\54\44\32\48\46\50\49\57\54\48\56\44\32\48\46\50\49\57\54\48\56\41\10\115\101\108\108\46\66\111\114\100\101\114\83\105\122\101\80\105\120\101\108\32\61\32\48\10\115\101\108\108\46\80\111\115\105\116\105\111\110\32\61\32\85\68\105\109\50\46\110\101\119\40\48\46\48\56\48\53\48\51\49\56\48\54\44\32\48\44\32\48\46\55\53\51\54\49\52\52\50\54\44\32\48\41\10\115\101\108\108\46\83\105\122\101\32\61\32\85\68\105\109\50\46\110\101\119\40\48\44\32\50\48\50\44\32\48\44\32\50\48\41\10\115\101\108\108\46\70\111\110\116\32\61\32\69\110\117\109\46\70\111\110\116\46\71\111\116\104\97\109\66\111\108\100\10\115\101\108\108\46\84\101\120\116\32\61\32\34\65\85\84\79\32\83\69\76\76\32\69\86\69\82\89\84\72\73\78\71\34\10\115\101\108\108\46\84\101\120\116\67\111\108\111\114\51\32\61\32\67\111\108\111\114\51\46\110\101\119\40\49\44\32\49\44\32\49\41\10\115\101\108\108\46\84\101\120\116\83\105\122\101\32\61\32\49\52\10\112\116\104\46\78\97\109\101\32\61\32\34\112\116\104\34\10\112\116\104\46\80\97\114\101\110\116\32\61\32\77\97\105\110\10\112\116\104\46\66\97\99\107\103\114\111\117\110\100\67\111\108\111\114\51\32\61\32\67\111\108\111\114\51\46\110\101\119\40\48\46\50\49\53\54\56\54\44\32\48\46\50\49\57\54\48\56\44\32\48\46\50\49\57\54\48\56\41\10\112\116\104\46\66\111\114\100\101\114\67\111\108\111\114\51\32\61\32\67\111\108\111\114\51\46\110\101\119\40\48\46\51\56\52\51\49\52\44\32\48\44\32\48\46\48\48\51\57\50\49\53\55\41\10\112\116\104\46\80\111\115\105\116\105\111\110\32\61\32\85\68\105\109\50\46\110\101\119\40\48\46\48\56\51\54\54\53\51\52\49\49\44\32\48\44\32\48\46\50\52\50\49\52\48\56\55\52\44\32\48\41\10\112\116\104\46\83\105\122\101\32\61\32\85\68\105\109\50\46\110\101\119\40\48\44\32\50\48\50\44\32\48\44\32\49\56\41\10\112\116\104\46\70\111\110\116\32\61\32\69\110\117\109\46\70\111\110\116\46\71\111\116\104\97\109\10\112\116\104\46\84\101\120\116\32\61\32\34\83\116\97\114\116\32\65\114\101\97\32\66\97\99\107\34\10\112\116\104\46\84\101\120\116\67\111\108\111\114\51\32\61\32\67\111\108\111\114\51\46\110\101\119\40\49\44\32\49\44\32\49\41\10\112\116\104\46\84\101\120\116\83\105\122\101\32\61\32\49\52\10\110\97\109\101\46\78\97\109\101\32\61\32\34\110\97\109\101\34\10\110\97\109\101\46\80\97\114\101\110\116\32\61\32\77\97\105\110\10\110\97\109\101\46\66\97\99\107\103\114\111\117\110\100\67\111\108\111\114\51\32\61\32\67\111\108\111\114\51\46\110\101\119\40\48\46\50\49\53\54\56\54\44\32\48\46\50\49\57\54\48\56\44\32\48\46\50\49\57\54\48\56\41\10\110\97\109\101\46\66\111\114\100\101\114\67\111\108\111\114\51\32\61\32\67\111\108\111\114\51\46\110\101\119\40\48\46\51\56\52\51\49\52\44\32\48\44\32\48\46\48\48\51\57\50\49\53\55\41\10\110\97\109\101\46\80\111\115\105\116\105\111\110\32\61\32\85\68\105\109\50\46\110\101\119\40\48\46\48\56\51\54\54\53\51\52\49\49\44\32\48\44\32\48\46\51\56\57\51\56\48\49\53\55\44\32\48\41\10\110\97\109\101\46\83\105\122\101\32\61\32\85\68\105\109\50\46\110\101\119\40\48\44\32\50\48\50\44\32\48\44\32\49\56\41\10\110\97\109\101\46\70\111\110\116\32\61\32\69\110\117\109\46\70\111\110\116\46\71\111\116\104\97\109\10\110\97\109\101\46\84\101\120\116\32\61\32\34\78\79\32\78\69\69\68\33\33\33\33\33\33\34\10\110\97\109\101\46\84\101\120\116\67\111\108\111\114\51\32\61\32\67\111\108\111\114\51\46\110\101\119\40\49\44\32\49\44\32\49\41\10\110\97\109\101\46\84\101\120\116\83\105\122\101\32\61\32\49\52\10\102\97\114\109\46\77\111\117\115\101\66\117\116\116\111\110\49\68\111\119\110\58\99\111\110\110\101\99\116\40\102\117\110\99\116\105\111\110\40\41\10\102\97\114\109\46\66\97\99\107\103\114\111\117\110\100\67\111\108\111\114\51\32\61\32\67\111\108\111\114\51\46\110\101\119\40\48\46\48\48\51\57\50\49\53\55\44\32\48\46\51\55\50\53\52\57\44\32\48\46\49\51\55\50\53\53\41\10\9\108\111\99\97\108\32\112\97\116\104\32\61\32\112\116\104\46\84\101\120\116\32\45\45\32\80\97\116\104\32\70\111\114\32\77\111\98\115\10\108\111\99\97\108\32\108\112\32\61\32\103\97\109\101\46\80\108\97\121\101\114\115\46\76\111\99\97\108\80\108\97\121\101\114\10\108\111\99\97\108\32\116\97\114\103\101\116\59\10\108\111\99\97\108\32\101\110\101\109\105\101\115\32\61\32\123\125\10\119\104\105\108\101\32\116\114\117\101\32\100\111\10\108\112\46\67\104\97\114\97\99\116\101\114\46\72\117\109\97\110\111\105\100\82\111\111\116\80\97\114\116\46\65\110\99\104\111\114\101\100\32\61\32\102\97\108\115\101\10\119\97\105\116\40\41\10\101\110\101\109\105\101\115\32\61\32\103\97\109\101\46\87\111\114\107\115\112\97\99\101\46\78\80\67\115\46\83\112\97\119\110\115\91\112\97\116\104\93\58\71\101\116\67\104\105\108\100\114\101\110\40\41\32\45\45\32\65\108\108\32\116\104\101\32\109\111\98\115\32\116\97\114\103\101\116\101\100\10\32\102\111\114\32\105\44\118\32\105\110\32\112\97\105\114\115\40\101\110\101\109\105\101\115\41\32\100\111\10\32\105\102\32\118\46\67\108\97\115\115\78\97\109\101\32\61\61\32\39\77\111\100\101\108\39\32\116\104\101\110\10\116\97\114\103\101\116\32\61\32\101\110\101\109\105\101\115\91\105\93\10\9\9\9\32\32\32\32\32\32\32\32\32\32\32\32\32\32\32\108\112\46\67\104\97\114\97\99\116\101\114\46\72\117\109\97\110\111\105\100\82\111\111\116\80\97\114\116\46\67\70\114\97\109\101\32\61\32\67\70\114\97\109\101\46\110\101\119\40\118\46\72\117\109\97\110\111\105\100\82\111\111\116\80\97\114\116\46\80\111\115\105\116\105\111\110\32\43\32\86\101\99\116\111\114\51\46\110\101\119\40\48\44\49\44\51\41\44\118\46\72\117\109\97\110\111\105\100\82\111\111\116\80\97\114\116\46\80\111\115\105\116\105\111\110\41\10\103\97\109\101\46\87\111\114\107\115\112\97\99\101\91\103\97\109\101\46\80\108\97\121\101\114\115\46\76\111\99\97\108\80\108\97\121\101\114\46\78\97\109\101\93\58\70\105\110\100\70\105\114\115\116\67\104\105\108\100\79\102\67\108\97\115\115\40\39\84\111\111\108\39\41\58\65\99\116\105\118\97\116\101\40\41\32\119\97\105\116\40\41\10\32\32\32\32\101\110\100\10\101\110\100\10\101\110\100\10\101\110\100\41\10\115\101\108\108\46\77\111\117\115\101\66\117\116\116\111\110\49\68\111\119\110\58\99\111\110\110\101\99\116\40\102\117\110\99\116\105\111\110\40\41\10\9\115\101\108\108\46\66\97\99\107\103\114\111\117\110\100\67\111\108\111\114\51\32\61\32\67\111\108\111\114\51\46\110\101\119\40\48\46\48\48\51\57\50\49\53\55\44\32\48\46\51\55\50\53\52\57\44\32\48\46\49\51\55\50\53\53\41\10\9\108\111\99\97\108\32\112\108\114\32\61\32\103\97\109\101\46\80\108\97\121\101\114\115\46\76\111\99\97\108\80\108\97\121\101\114\46\67\104\97\114\97\99\116\101\114\46\72\117\109\97\110\111\105\100\82\111\111\116\80\97\114\116\10\119\104\105\108\101\32\119\97\105\116\40\41\32\100\111\10\103\97\109\101\46\87\111\114\107\115\112\97\99\101\46\82\105\110\103\115\46\83\101\108\108\46\67\70\114\97\109\101\32\61\32\112\108\114\46\67\70\114\97\109\101\10\101\110\100\10\101\110\100\41\10\103\97\109\101\58\71\101\116\83\101\114\118\105\99\101\40\34\83\116\97\114\116\101\114\71\117\105\34\41\58\83\101\116\67\111\114\101\40\34\83\101\110\100\78\111\116\105\102\105\99\97\116\105\111\110\34\44\32\123\84\105\116\108\101\32\61\32\34\87\65\82\78\73\78\71\33\34\44\32\84\101\120\116\32\61\32\34\69\81\85\73\80\32\89\79\85\82\32\87\69\65\80\79\78\32\66\69\70\79\82\69\32\85\83\73\78\71\33\34\125\41')() |
-- Extensible Application Framework Package Manager source repository manager.
-- This program is used to add, remove listed add-on repositories, and retrieving their description.
-- Every subcommand option is standalone and needs to use flag to run itself.
local arguments, options = ...
local component = require("component")
local filesystem = require("filesystem")
local httpstream = require("xaf/utility/httpstream")
local xafcore = require("xaf/core/xafcore")
local xafcoreMath = xafcore:getMathInstance()
local xafcoreTable = xafcore:getTableInstance()
local gpu = component.getPrimary("gpu")
local gpuWidth, gpuHeight = gpu.getResolution()
if (options.h == true or options.help == true) then
print("----------------------------------")
print("-- XAF Package Manager - Manual --")
print("----------------------------------")
print(" >> NAME")
print(" >> xaf-pm repository - Source repository management program")
print()
print(" >> SYNOPSIS")
print(" >> xaf-pm repository")
print(" >> xaf-pm repository [-a | --add] <identifier> [priority]")
print(" >> xaf-pm repository [-h | --help]")
print(" >> xaf-pm repository [-i | --info] <identifier>")
print(" >> xaf-pm repository [-l | --list] [page]")
print(" >> xaf-pm repository [-p | --priority] <index> <priority>")
print(" >> xaf-pm repository [-r | --remove] <index>")
print()
print(" >> DESCRIPTION")
print(" >> This script let the user manage XAF PM add-on package source repositories.")
os.exit()
end
if (options.l == true or options.list == true or options.p == true or options.priority == true or -- First group, offline (local only) commands - do not need internet component.
options.r == true or options.remove == true) then
local pathRoot = "io.github.aquaver"
local pathProject = "xaf-framework"
local pathData = "data"
local pathName = "pm-source.info"
local sourcePath = filesystem.concat(pathRoot, pathProject, pathData, pathName)
local sourceData = {}
if (filesystem.exists(sourcePath) == true) then
sourceData = xafcoreTable:loadFromFile(sourcePath)
else
print("--------------------------------------")
print("-- XAF Package Manager - Controller --")
print("--------------------------------------")
print(" >> Cannot find the source repositories list file")
print(" >> Reinstall XAF package or download this file manually")
print(" >> Missing file name: " .. pathName)
os.exit()
end
if (options.l == true or options.list == true) then
local indexLength = #sourceData
local indexRaw = arguments[1]
local index = 0
if (indexRaw == nil) then
index = 1
elseif (tonumber(indexRaw) == nil) then
print("--------------------------------------")
print("-- XAF Package Manager - Controller --")
print("--------------------------------------")
print(" >> Invalid repository list index value")
print(" >> This value must be natural number (or empty as 1)")
print(" >> Use 'xaf-pm repository [-l | --list]' again with proper index")
os.exit()
else
if (xafcoreMath:checkNatural(tonumber(indexRaw), true) == false) then
print("--------------------------------------")
print("-- XAF Package Manager - Controller --")
print("--------------------------------------")
print(" >> Invalid repository list index value")
print(" >> This value must be natural number (or empty as 1)")
print(" >> Use 'xaf-pm repository [-l | --list]' again with proper index")
os.exit()
else
index = tonumber(indexRaw)
end
end
print("--------------------------------------")
print("-- XAF Package Manager - Controller --")
print("--------------------------------------")
print(" >> Retrieving source repository list")
if (sourceData["default"] == nil) then
print(" >> Default repository not found")
else
print(" >> Default repository: " .. sourceData["default"])
end
for i = (index - 1) * 10 + 1, (index - 1) * 10 + 10 do
if (sourceData[i]) then
print(" >> [" .. i .. "] " .. sourceData[i])
else
break
end
end
if (sourceData[(index - 1) * 10 + 11]) then
print(" >> More repositories on 'xaf-pm repository [-l | --list] " .. index + 1 .. "'")
end
elseif (options.p == true or options.priority == true) then
local indexLength = #sourceData
local indexRaw = arguments[1]
local index = 0
local priorityRaw = arguments[2]
local priority = 0
if (tonumber(indexRaw) == nil) then
print("--------------------------------------")
print("-- XAF Package Manager - Controller --")
print("--------------------------------------")
print(" >> Invalid repository index value")
print(" >> This value must be natural number (up to: " .. indexLength .. ')')
print(" >> Use 'xaf-pm repository [-p | --priority]' again with proper index")
os.exit()
else
if (xafcoreMath:checkNatural(tonumber(indexRaw), true) == false or tonumber(indexRaw) > indexLength) then
print("--------------------------------------")
print("-- XAF Package Manager - Controller --")
print("--------------------------------------")
print(" >> Invalid repository index value")
print(" >> This value must be natural number (up to: " .. indexLength .. ')')
print(" >> Use 'xaf-pm repository [-p | --priority]' again with proper index")
os.exit()
else
index = tonumber(indexRaw)
end
end
if (tonumber(priorityRaw) == nil) then
print("--------------------------------------")
print("-- XAF Package Manager - Controller --")
print("--------------------------------------")
print(" >> Invalid repository new priority value")
print(" >> This value must be natural number (up to: " .. indexLength .. ')')
print(" >> Use 'xaf-pm repository [-p | --priority]' again with proper priority value")
os.exit()
else
if (xafcoreMath:checkNatural(tonumber(priorityRaw), true) == false or tonumber(indexRaw) > indexLength) then
print("--------------------------------------")
print("-- XAF Package Manager - Controller --")
print("--------------------------------------")
print(" >> Invalid repository new priority value")
print(" >> This value must be natural number (up to: " .. indexLength .. ')')
print(" >> Use 'xaf-pm repository [-p | --priority]' again with proper priority value")
os.exit()
else
priority = tonumber(priorityRaw)
end
end
local listFile = filesystem.open(sourcePath, 'w')
local removedEntry = table.remove(sourceData, index)
listFile:write("[#] Extensible Application Framework Package Manager source repository list." .. '\n')
listFile:write("[#] This file is used to store user added custom XAF add-on package repositories." .. '\n')
listFile:write("[#] Data represented in XAF Table Format." .. '\n' .. '\n')
listFile:close()
table.insert(sourceData, priority, removedEntry)
xafcoreTable:saveToFile(sourceData, sourcePath, true)
print("--------------------------------------")
print("-- XAF Package Manager - Controller --")
print("--------------------------------------")
print(" >> Successfully changed priority of repository: " .. removedEntry)
print(" >> It is available now under index '" .. priority .. "' instead of '" .. index .. "'")
elseif (options.r == true or options.remove == true) then
local indexLength = #sourceData
local indexRaw = arguments[1]
local index = 0
if (tonumber(indexRaw) == nil) then
print("--------------------------------------")
print("-- XAF Package Manager - Controller --")
print("--------------------------------------")
print(" >> Invalid repository removal index value")
print(" >> This value must be natural number (up to: " .. indexLength .. ')')
print(" >> Use 'xaf-pm repository [-r | --remove]' again with proper index")
os.exit()
else
if (xafcoreMath:checkNatural(tonumber(indexRaw), true) == false or tonumber(indexRaw) > indexLength) then
print("--------------------------------------")
print("-- XAF Package Manager - Controller --")
print("--------------------------------------")
print(" >> Invalid repository removal index value")
print(" >> This value must be natural number (up to: " .. indexLength .. ')')
print(" >> Use 'xaf-pm repository [-r | --remove]' again with proper index")
os.exit()
else
index = tonumber(indexRaw)
end
local listFile = filesystem.open(sourcePath, 'w')
local removedEntry = table.remove(sourceData, index)
listFile:write("[#] Extensible Application Framework Package Manager source repository list." .. '\n')
listFile:write("[#] This file is used to store user added custom XAF add-on package repositories." .. '\n')
listFile:write("[#] Data represented in XAF Table Format." .. '\n' .. '\n')
listFile:close()
xafcoreTable:saveToFile(sourceData, sourcePath, true)
print("--------------------------------------")
print("-- XAF Package Manager - Controller --")
print("--------------------------------------")
print(" >> Successfully removed following repository: " .. removedEntry)
print(" >> Package Manager will no longer install add-ons from it")
end
end
os.exit()
end
if (options.a == true or options.add == true or options.i == true or options.info == true) then -- Second group, online commands - required internet card component to work.
if (component.isAvailable("internet") == false) then
print("--------------------------------------")
print("-- XAF Package Manager - Controller --")
print("--------------------------------------")
print(" >> Internet card component is not available")
print(" >> Package Manager cannot connect to target repository")
os.exit()
else
print("--------------------------------------")
print("-- XAF Package Manager - Controller --")
print("--------------------------------------")
print(" >> Internet card component found")
print(" >> Trying to connect to target repository...")
end
local targetAddress = "https://raw.githubusercontent.com/"
local targetRepository = arguments[1]
local targetPriority = arguments[2]
local targetPath = "/master/_config/repository.info"
if (options.a == true or options.add == true) then
if (targetRepository == nil) then
print(" >> Invalid target repository identifier, must not be empty")
print(" >> Required format: userName/repositoryName")
os.exit()
end
local inetAddress = targetAddress .. targetRepository .. targetPath
local inetComponent = component.getPrimary("internet")
local inetConnection = httpstream:new(inetComponent, inetAddress)
local inetResponse = 0
inetConnection:setMaxTimeout(0.5)
if (inetConnection:connect() == true) then
local infoData = ''
local infoTable = {}
for dataChunk in inetConnection:getData() do
infoData = infoData .. dataChunk
end
inetResponse = inetConnection:getResponseCode()
inetConnection:disconnect()
inetComponent = nil
if (inetResponse == 404) then
print(" >> Target repository does not exist on GitHub service")
print(" >> Ensure you entered valid repository identifier")
print(" >> Required format: userName/repositoryName")
os.exit()
else
infoTable = xafcoreTable:loadFromString(infoData)
infoData = ''
if (infoTable["repository-description"] and infoTable["repository-owner"] and infoTable["repository-title"] and infoTable["repository-xaf"]) then
local pathRoot = "io.github.aquaver"
local pathProject = "xaf-framework"
local pathData = "data"
local pathName = "pm-source.info"
local sourcePath = filesystem.concat(pathRoot, pathProject, pathData, pathName)
local sourceData = {}
local sourceLength = 0
if (filesystem.exists(sourcePath) == true) then
sourceData = xafcoreTable:loadFromFile(sourcePath)
sourceLength = #sourceData
else
print(" >> Cannot find the source repositories list file")
print(" >> Reinstall XAF package or download this file manually")
print(" >> Missing file name: " .. pathName)
os.exit()
end
if (targetPriority == nil) then
targetPriority = 1
table.insert(sourceData, 1, targetRepository)
elseif (tonumber(targetPriority) == nil) then
print(" >> Invalid new repository priority value")
print(" >> This value must be natural number (up to: " .. sourceLength + 1 .. ')')
print(" >> Use 'xaf-pm repository [-a | --add]' again with proper priority value")
os.exit()
else
if (xafcoreMath:checkNatural(tonumber(targetPriority), true) == false or tonumber(targetPriority) > sourceLength + 1) then
print(" >> Invalid new repository priority value")
print(" >> This value must be natural number (up to: " .. sourceLength + 1 .. ')')
print(" >> Use 'xaf-pm repository [-a | --add]' again with proper priority value")
os.exit()
else
table.insert(sourceData, tonumber(targetPriority), targetRepository)
end
end
local listFile = filesystem.open(sourcePath, 'w')
local addedRepository = targetRepository
listFile:write("[#] Extensible Application Framework Package Manager source repository list." .. '\n')
listFile:write("[#] This file is used to store user added custom XAF add-on package repositories." .. '\n')
listFile:write("[#] Data represented in XAF Table Format." .. '\n' .. '\n')
listFile:close()
xafcoreTable:saveToFile(sourceData, sourcePath, true)
print(" >> Successfully added following repository: " .. addedRepository)
print(" >> Package Manager will install programs from it with '" .. targetPriority .. "' priority")
else
print(" >> Invalid repository description file detected")
print(" >> Try running 'xaf-pm repository [-a | --add]' again")
print(" >> If this message appears again, contact the repository owner")
os.exit()
end
end
else
print(" >> Cannot connect to target repository")
print(" >> Try running 'xaf-pm repository [-a | --add]' again")
os.exit()
end
elseif (options.i == true or options.info == true) then
if (targetRepository == nil) then
print(" >> Invalid target repository identifier, must not be empty")
print(" >> Required format: userName/repositoryName")
os.exit()
end
local inetAddress = targetAddress .. targetRepository .. targetPath
local inetComponent = component.getPrimary("internet")
local inetConnection = httpstream:new(inetComponent, inetAddress)
local inetResponse = 0
inetConnection:setMaxTimeout(0.5)
if (inetConnection:connect() == true) then
local infoData = ''
local infoTable = {}
for dataChunk in inetConnection:getData() do
infoData = infoData .. dataChunk
end
inetResponse = inetConnection:getResponseCode()
inetConnection:disconnect()
inetComponent = nil
if (inetResponse == 404) then
print(" >> Target repository does not exist on GitHub service")
print(" >> Ensure you entered valid repository identifier")
print(" >> Required format: userName/repositoryName")
os.exit()
else
infoTable = xafcoreTable:loadFromString(infoData)
infoData = ''
if (infoTable["repository-description"] and infoTable["repository-owner"] and infoTable["repository-title"] and infoTable["repository-xaf"]) then
print(" >> Successfully connected to target repository:")
print(" >> Repository title: " .. infoTable["repository-title"])
print(" >> Repository owner: " .. infoTable["repository-owner"])
print(" >> Repository required XAF version: " .. infoTable["repository-xaf"])
print(string.rep('-', gpuWidth))
print(infoTable["repository-description"])
else
print(" >> Invalid repository description file detected")
print(" >> Try running 'xaf-pm repository [-i | --info]' again")
print(" >> If this message appears again, contact the repository owner")
end
end
else
print(" >> Cannot connect to target repository")
print(" >> Try running 'xaf-pm repository [-i | --info]' again")
os.exit()
end
end
os.exit()
end
print("--------------------------------------")
print("-- XAF Package Manager - Controller --")
print("--------------------------------------")
print(" >> Source repository management program")
print(" >> Use 'xaf-pm repository [-h | --help]' for command manual")
|
local function put (where, key, value)
local existant = where[key]
if (type(existant) == 'table') and (type(value) == 'table') then
for k,v in pairs(value) do
put(existant, k, v)
end
else
where[key] = value
end
end
return function(base, new)
new = new or {}
base = base or {}
local result = {}
for k,v in pairs(base) do
result[k] = v
end
for k,v in pairs(new) do
put(result, k, v)
end
return result
end |
local ignoreweapon =
{
armaak = {1},
armcarry = {1},
armaas = {1},
armraz = {2},
cormak = {1,3},
coraak = {1},
coramph = {2},
}
local iconFormat = '.dds'
return ignoreweapon, iconFormat
|
if not loadStatFile then
dofile("statdesc.lua")
end
loadStatFile("passive_skill_stat_descriptions.txt")
local out = io.open("../Data/3_0/LegionPassives.lua", "w")
local stats = dat("Stats")
local alternatePassiveSkillDat = dat("AlternatePassiveSkills")
local alternatePassiveAdditionsDat = dat("AlternatePassiveAdditions")
local LEGION_PASSIVE_GROUP = 1e9
---@type fun(thing:string|table|number):string
function stringify(thing)
if type(thing) == 'string' then
return thing
elseif type(thing) == 'number' then
return ""..thing;
elseif type(thing) == 'table' then
local s = "{";
for k,v in pairs(thing) do
s = s.."\n\t"
if type(k) == 'number' then
s = s.."["..k.."] = "
else
s = s.."[\""..k.."\"] = "
end
if type(v) == 'string' then
s = s.."\""..stringify(v).."\", "
else
if type(v) == "boolean" then
v = v and "true" or "false"
end
val = stringify(v)..", "
if type(v) == "table" then
val = string.gsub(val, "\n", "\n\t")
end
s = s..val;
end
end
return s.."\n}"
end
end
---@type table <string, table> @this is the structure used to generate the final data file Data/3_0/LegionPassives
local data = {};
data.nodes = {};
data.groups = {};
data.additions = {};
local ksCount = -1;
for i=1, alternatePassiveSkillDat.rowCount do
---@type table<string, boolean|string|number>
local datFileRow = {};
for j=1,#alternatePassiveSkillDat.cols-1 do
local key = alternatePassiveSkillDat.spec[j].name
datFileRow[key] = alternatePassiveSkillDat:ReadCell(i, j)
end
---@type table<string, boolean|string|number|table>
local legionPassiveNode = {};
-- id
legionPassiveNode.id = datFileRow.Id;
-- icon
legionPassiveNode.icon = datFileRow.DDSIcon;
-- is keystone
legionPassiveNode.ks = isValueInTable(datFileRow.PassiveType, 4) and true or false
if legionPassiveNode.ks then
ksCount = ksCount + 1
end
-- is notable
legionPassiveNode['not'] = isValueInTable(datFileRow.PassiveType, 3) and true or false
-- node name
legionPassiveNode.dn = datFileRow.Name;
-- is mastery wheel
legionPassiveNode.m = false
-- self explanatory
legionPassiveNode.isJewelSocket = false
legionPassiveNode.isMultipleChoice = false
legionPassiveNode.isMultipleChoiceOption = false
legionPassiveNode.passivePointsGranted = 0
-- class starting node
legionPassiveNode.spc = {}
-- display text
legionPassiveNode.sd = {}
legionPassiveNode.stats = {}
for idx,statKey in pairs(datFileRow.StatsKeys) do
refRow = statKey._rowIndex
statId = stats:ReadCell(refRow, 1)
range = datFileRow["Stat"..idx]
legionPassiveNode.stats[statId] = {
["min"] = range[1],
["max"] = range[2],
}
end
for _, line in ipairs(describeStats(legionPassiveNode.stats)) do
table.insert(legionPassiveNode.sd, line)
end
-- Node group, legion nodes don't use it, so we set it arbitrarily
legionPassiveNode.g = LEGION_PASSIVE_GROUP
--
-- group orbit distance
legionPassiveNode.o = legionPassiveNode.ks and 4 or 3
legionPassiveNode.oidx = legionPassiveNode.ks and ksCount * 3 or math.floor(math.random() * 1e5)
-- attributes granted
legionPassiveNode.sa = 0
legionPassiveNode.da = 0
legionPassiveNode.ia = 0
-- connected nodes
legionPassiveNode.out = {}
legionPassiveNode["in"] = {}
data.nodes[legionPassiveNode.id] = legionPassiveNode;
end
data.groups[LEGION_PASSIVE_GROUP] = {
["x"] = -6500,
["y"] = -6500,
["oo"] = {},
["n"] = {}
}
for k,v in pairs(data.nodes) do
table.insert(data.groups[LEGION_PASSIVE_GROUP].n, k)
end
for i=1, alternatePassiveAdditionsDat.rowCount do
---@type table<string, boolean|string|number>
local datFileRow = {};
for j=1,#alternatePassiveAdditionsDat.cols-1 do
local key = alternatePassiveAdditionsDat.spec[j].name
datFileRow[key] = alternatePassiveAdditionsDat:ReadCell(i, j)
end
---@type table<string, boolean|string|number|table>
local legionPassiveAddition = {};
-- id
legionPassiveAddition.id = datFileRow.Id;
-- Additions have no name, so we construct one for the UI (also, Lua patterns are too limiting :( )
legionPassiveAddition.dn = string.gsub(string.gsub(string.gsub(datFileRow.Id, "_", " "), "^%w* ", ""), "^%w* ", "")
legionPassiveAddition.dn = legionPassiveAddition.dn:gsub("(%l)(%w*)", function(a,b) return string.upper(a)..b end)
-- stat descriptions
legionPassiveAddition.sd = {};
legionPassiveAddition.stats = {}
for idx,statKey in pairs(datFileRow.StatsKeys) do
refRow = statKey + 1
statId = stats:ReadCell(refRow, 1)
range = datFileRow["Stat"..idx]
legionPassiveAddition.stats[statId] = {
["min"] = range[1],
["max"] = range[2],
}
end
for _, line in ipairs(describeStats(legionPassiveAddition.stats)) do
table.insert(legionPassiveAddition.sd, line)
end
data.additions[legionPassiveAddition.id] = legionPassiveAddition;
end
str = stringify(data)
out:write("-- This file is automatically generated, do not edit!\n-- Item data (c) Grinding Gear Games\n\n")
out:write("return "..str)
out:close()
print("Legion passives exported.") |
local M = {}
local winnr = -1
local buffsize = 0
local setcursor = false
local lines = {}
function M.moveup()
if vim.api.nvim_win_get_cursor(winnr)[1] > 1 then
vim.api.nvim_win_set_cursor(winnr, {vim.api.nvim_win_get_cursor(winnr)[1]-1,0})
vim.cmd [[ redraw! ]]
end
end
function M.movedown()
if vim.api.nvim_win_get_cursor(winnr)[1] < buffsize then
vim.api.nvim_win_set_cursor(winnr, {vim.api.nvim_win_get_cursor(winnr)[1]+1,0})
vim.cmd [[ redraw! ]]
end
end
function M.open()
vim.cmd [[ above new ]]
vim.api.nvim_command('edit '..lines[vim.api.nvim_win_get_cursor(winnr)[1]])
end
function M.test()
local log_buf = vim.api.nvim_create_buf(true, true)
local edit_buf = vim.api.nvim_create_buf(true, true)
local lastjob = -1
vim.cmd [[ below new ]]
winnr = vim.fn.win_getid()
vim.api.nvim_set_current_buf(log_buf)
vim.cmd [[ setlocal cursorline ]]
vim.cmd [[ below new ]]
vim.cmd [[ resize 1 ]]
vim.api.nvim_set_current_buf(edit_buf)
vim.cmd [[ startinsert ]]
local opts = { noremap=true, silent=true, nowait=true }
vim.api.nvim_buf_set_keymap(edit_buf, "i", "<Down>", '<Cmd>lua require"async_cout".movedown()<cr>', opts)
vim.api.nvim_buf_set_keymap(edit_buf, "i", "<Up>", '<Cmd>lua require"async_cout".moveup()<cr>', opts)
vim.api.nvim_buf_set_keymap(edit_buf, "i", "<CR>", '<Cmd>lua require"async_cout".open()<cr>', opts)
Clear = function()
vim.api.nvim_buf_set_lines(log_buf, 0, -1, true, { '' })
end
run = function(inlines)
lines = {}
buffsize = 0
setcursor = false
local function on_event(job_id, data, event)
if event == "stdout" or event == "stderr" then
if data then
for k, v in ipairs(data) do
if v ~= "" and v ~= "\r" and v~=nil then
local n = string.gsub(v, "\r", "")
if(n ~= nil) then
table.insert(lines, n)
end
end
end
if job_id == lastjob then
vim.api.nvim_buf_set_lines(log_buf, 0, -1, true, lines)
buffsize = table.getn(lines)
end
if setcursor == false then
vim.api.nvim_win_set_cursor(winnr, {1,0})
setcursor = true
end
end
end
if event == "exit" then
end
end
lastjob =
vim.fn.jobstart(
"es -path . " .. table.concat(inlines, " "),
{
on_stderr = on_event,
on_stdout = on_event,
on_exit = on_event
})
end
local callback = function(_, _, tick, firstline, lastline, new_lastline, _, _, _)
local editlines = vim.api.nvim_buf_get_lines(edit_buf, 0, -1, true)
local to_schedule = function()
if lastjob ~= -1 then
vim.fn.jobstop(lastjob)
end
run(editlines)
end
vim.schedule(to_schedule)
end
vim.api.nvim_buf_attach(edit_buf, false, { on_lines = callback })
end
return M
|
print("loaded shared")
|
-- Doubles the skill AP cost, up to 6.
-- Also increases the minimum AP cost for Mobility skills to 4.
local function WotL_ChangeSkillAP(skill, type)
local AP = Ext.StatGetAttribute(skill, "ActionPoints")
if AP ~= nil and AP ~= 0 then
local new = math.min(2*AP, 6)
if ENUM_WotL_MobilitySkillTypes[type] then
new = math.max(new, 4)
end
WotL_ModulePrint("AP: " .. tostring(AP) .. " -> " .. tostring(new), "Skill")
Ext.StatSetAttribute(skill, "ActionPoints", new)
end
end
-- Changes the scaling of skill damages from physical armor to magic armor.
-- It also applies a scaling factor, since there's no SourceShieldMagicArmor
-- damage type.
local function WotL_ChangeSkillDamage(skill)
local source = Ext.StatGetAttribute(skill, "Damage")
for type, list in pairs(ENUM_WotL_ArmorDamageSourceTypes) do
if source == type then
local damage = Ext.StatGetAttribute(skill, "Damage Multiplier")
for replace, multiplier in pairs(list) do
local new = math.ceil(damage * multiplier)
WotL_ModulePrint("Skill: " .. tostring(skill), "Skill")
WotL_ModulePrint("Source: " .. tostring(source) .. " -> " .. tostring(replace), "Skill")
WotL_ModulePrint("Damage: " .. tostring(damage) .. " -> " .. tostring(new), "Skill")
Ext.StatSetAttribute(skill, "Damage", replace)
Ext.StatSetAttribute(skill, "Damage Multiplier", new)
break
end
break
end
end
end
-- Replaces the description parameters from armor to magic armor. The actual potion
-- or status changes happens on the appropriate modules.
local function WotL_ChangeSkillDescription(skill)
local params = Ext.StatGetAttribute(skill, "StatsDescriptionParams")
local new, count = string.gsub(params, ":Armor", ":MagicArmor")
if count > 0 then
WotL_ModulePrint("Description Parameters: " .. params .. " -> " .. new, "Skill")
Ext.StatSetAttribute(skill, "StatsDescriptionParams", new)
end
end
-- TODO: Change the book usage requirements alongside the skills. Might have to save the skills
-- here with their new requirements somewhere for later usage
-- Doubles the Memorization Requirements of Mobility skills, with a maximum of 5.
local function WotL_ChangeSkillMemorizationRequirements(skill, type)
local memRequirements = Ext.StatGetAttribute(skill, "MemorizationRequirements")
if ENUM_WotL_MobilitySkillTypes[type] then
for _, r in pairs(memRequirements) do
if not r["Not"] then
r["Param"] = math.min(2*r["Param"], 5)
end
end
WotL_ModuleTPrint(memRequirements, "Skill")
Ext.StatSetAttribute(skill, "MemorizationRequirements", memRequirements)
end
end
-- Decreases the skill range, only if it's between 5 and 25 m.
local function WotL_ChangeSkillRange(skill, type)
for attribute, typeList in pairs(ENUM_WotL_SkillRangeAttributes) do
if typeList[type] then
local range = Ext.StatGetAttribute(skill, attribute)
if range > 5 and range < 25 then
local new = math.ceil(WotL_Truncate(WotL_NormalizeRange(range), 1))
WotL_ModulePrint("Range (" .. attribute .. "): " .. tostring(range) .. " -> " .. tostring(new), "Skill")
Ext.StatSetAttribute(skill, attribute, new)
end
end
end
end
-------------------------------------------- PRESETS --------------------------------------------
local WotL_SkillsLookFor = {}
local WotL_SkillsProperties = {}
-- Saves the stats and properties that will suffer preset changes.
local function WotL_PrepareSkillPresets()
for skill, list in pairs(ENUM_WotL_SkillPresets) do
WotL_SkillsLookFor[skill] = true
for attribute, _ in pairs(list) do
WotL_SkillsProperties[attribute] = true
end
end
end
local WotL_DefaultSkillProperties = {}
-- Applies the preset changes, based on the stats and properties saved of the root parent.
-- If the root parent matches the defined stat, the current stat suffer the preset change
-- if the property value matches the default value for the root parent stat.
local function WotL_ChangeSkillPreset(skill)
if WotL_SkillsLookFor[skill] then
WotL_DefaultSkillProperties[skill] = {}
for attribute, _ in pairs(WotL_SkillsProperties) do
WotL_DefaultSkillProperties[skill][attribute] = Ext.StatGetAttribute(skill, attribute)
end
end
for stat, list in pairs(ENUM_WotL_SkillPresets) do
local parent = WotL_GetRootParent(skill)
if parent == stat then
for attribute, value in pairs(list) do
local curr = Ext.StatGetAttribute(skill, attribute)
if curr == WotL_DefaultSkillProperties[parent][attribute] then
WotL_ModulePrint("------ PRESET APPLIED ------", "Skill")
WotL_ModulePrint(tostring(attribute) .. ": " .. tostring(curr) .. " -> " .. tostring(value), "Skill")
Ext.StatSetAttribute(skill, attribute, value)
end
end
break
end
end
end
---------------------------------------- MODULE FUNCTION ----------------------------------------
function WotL_ModuleSkill()
WotL_PrepareSkillPresets()
for _, skill in pairs(Ext.GetStatEntries("SkillData")) do
WotL_ModulePrint("Skill: " .. skill, "Skill")
local type = Ext.StatGetAttribute(skill, "SkillType")
WotL_ChangeSkillAP(skill, type)
WotL_ChangeSkillDamage(skill)
WotL_ChangeSkillDescription(skill)
WotL_ChangeSkillMemorizationRequirements(skill, type)
WotL_ChangeSkillRange(skill, type)
WotL_ChangeSkillPreset(skill)
end
end
|
if not modules then modules = { } end modules ['util-fil'] = {
version = 1.001,
comment = "companion to luat-lib.mkiv",
author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright = "PRAGMA ADE / ConTeXt Development Team",
license = "see context related readme files"
}
local tonumber = tonumber
local byte = string.byte
local char = string.char
-- Here are a few helpers (the starting point were old ones I used for parsing
-- flac files). In Lua 5.3 we can probably do this better. Some code will move
-- here.
-- We could comment those that are in fio and sio.
utilities = utilities or { }
local files = { }
utilities.files = files
-- we could have a gc method that closes but files auto close anyway
local zerobased = { }
function files.open(filename,zb)
local f = io.open(filename,"rb")
if f then
zerobased[f] = zb or false
end
return f
end
function files.close(f)
zerobased[f] = nil
f:close()
end
function files.size(f)
local current = f:seek()
local size = f:seek("end")
f:seek("set",current)
return size
end
files.getsize = files.size
function files.setposition(f,n)
if zerobased[f] then
f:seek("set",n)
else
f:seek("set",n - 1)
end
end
function files.getposition(f)
if zerobased[f] then
return f:seek()
else
return f:seek() + 1
end
end
function files.look(f,n,chars)
local p = f:seek()
local s = f:read(n)
f:seek("set",p)
if chars then
return s
else
return byte(s,1,#s)
end
end
function files.skip(f,n)
if n == 1 then
f:read(n)
else
f:seek("set",f:seek()+n)
end
end
function files.readbyte(f)
return byte(f:read(1))
end
function files.readbytes(f,n)
return byte(f:read(n),1,n)
end
function files.readbytetable(f,n)
-- return { byte(f:read(n),1,n) }
local s = f:read(n or 1)
return { byte(s,1,#s) } -- best use the real length
end
function files.readchar(f)
return f:read(1)
end
function files.readstring(f,n)
return f:read(n or 1)
end
function files.readinteger1(f) -- one byte
local n = byte(f:read(1))
if n >= 0x80 then
return n - 0x100
else
return n
end
end
files.readcardinal1 = files.readbyte -- one byte
files.readcardinal = files.readcardinal1
files.readinteger = files.readinteger1
files.readsignedbyte = files.readinteger1
function files.readcardinal2(f)
local a, b = byte(f:read(2),1,2)
return 0x100 * a + b
end
function files.readcardinal2le(f)
local b, a = byte(f:read(2),1,2)
return 0x100 * a + b
end
function files.readinteger2(f)
local a, b = byte(f:read(2),1,2)
if a >= 0x80 then
return 0x100 * a + b - 0x10000
else
return 0x100 * a + b
end
end
function files.readinteger2le(f)
local b, a = byte(f:read(2),1,2)
if a >= 0x80 then
return 0x100 * a + b - 0x10000
else
return 0x100 * a + b
end
end
function files.readcardinal3(f)
local a, b, c = byte(f:read(3),1,3)
return 0x10000 * a + 0x100 * b + c
end
function files.readcardinal3le(f)
local c, b, a = byte(f:read(3),1,3)
return 0x10000 * a + 0x100 * b + c
end
function files.readinteger3(f)
local a, b, c = byte(f:read(3),1,3)
if a >= 0x80 then
return 0x10000 * a + 0x100 * b + c - 0x1000000
else
return 0x10000 * a + 0x100 * b + c
end
end
function files.readinteger3le(f)
local c, b, a = byte(f:read(3),1,3)
if a >= 0x80 then
return 0x10000 * a + 0x100 * b + c - 0x1000000
else
return 0x10000 * a + 0x100 * b + c
end
end
function files.readcardinal4(f)
local a, b, c, d = byte(f:read(4),1,4)
return 0x1000000 * a + 0x10000 * b + 0x100 * c + d
end
function files.readcardinal4le(f)
local d, c, b, a = byte(f:read(4),1,4)
return 0x1000000 * a + 0x10000 * b + 0x100 * c + d
end
function files.readinteger4(f)
local a, b, c, d = byte(f:read(4),1,4)
if a >= 0x80 then
return 0x1000000 * a + 0x10000 * b + 0x100 * c + d - 0x100000000
else
return 0x1000000 * a + 0x10000 * b + 0x100 * c + d
end
end
function files.readinteger4le(f)
local d, c, b, a = byte(f:read(4),1,4)
if a >= 0x80 then
return 0x1000000 * a + 0x10000 * b + 0x100 * c + d - 0x100000000
else
return 0x1000000 * a + 0x10000 * b + 0x100 * c + d
end
end
function files.readfixed2(f)
local a, b = byte(f:read(2),1,2)
if a >= 0x80 then
tonumber((a - 0x100) .. "." .. b)
else
tonumber(( a ) .. "." .. b)
end
end
-- (real) (n>>16) + ((n&0xffff)/65536.0)) but no cast in lua (we could use unpack)
function files.readfixed4(f)
local a, b, c, d = byte(f:read(4),1,4)
if a >= 0x80 then
tonumber((0x100 * a + b - 0x10000) .. "." .. (0x100 * c + d))
else
tonumber((0x100 * a + b ) .. "." .. (0x100 * c + d))
end
end
-- (real) ((n<<16)>>(16+14)) + ((n&0x3fff)/16384.0))
if bit32 then
local extract = bit32.extract
local band = bit32.band
function files.read2dot14(f)
local a, b = byte(f:read(2),1,2)
if a >= 0x80 then
local n = -(0x100 * a + b)
return - (extract(n,14,2) + (band(n,0x3FFF) / 16384.0))
else
local n = 0x100 * a + b
return (extract(n,14,2) + (band(n,0x3FFF) / 16384.0))
end
end
end
function files.skipshort(f,n)
f:read(2*(n or 1))
end
function files.skiplong(f,n)
f:read(4*(n or 1))
end
-- writers (kind of slow)
if bit32 then
local rshift = bit32.rshift
function files.writecardinal2(f,n)
local a = char(n % 256)
n = rshift(n,8)
local b = char(n % 256)
f:write(b,a)
end
function files.writecardinal4(f,n)
local a = char(n % 256)
n = rshift(n,8)
local b = char(n % 256)
n = rshift(n,8)
local c = char(n % 256)
n = rshift(n,8)
local d = char(n % 256)
f:write(d,c,b,a)
end
function files.writecardinal2le(f,n)
local a = char(n % 256)
n = rshift(n,8)
local b = char(n % 256)
f:write(a,b)
end
function files.writecardinal4le(f,n)
local a = char(n % 256)
n = rshift(n,8)
local b = char(n % 256)
n = rshift(n,8)
local c = char(n % 256)
n = rshift(n,8)
local d = char(n % 256)
f:write(a,b,c,d)
end
else
local floor = math.floor
function files.writecardinal2(f,n)
local a = char(n % 256)
n = floor(n/256)
local b = char(n % 256)
f:write(b,a)
end
function files.writecardinal4(f,n)
local a = char(n % 256)
n = floor(n/256)
local b = char(n % 256)
n = floor(n/256)
local c = char(n % 256)
n = floor(n/256)
local d = char(n % 256)
f:write(d,c,b,a)
end
function files.writecardinal2le(f,n)
local a = char(n % 256)
n = floor(n/256)
local b = char(n % 256)
f:write(a,b)
end
function files.writecardinal4le(f,n)
local a = char(n % 256)
n = floor(n/256)
local b = char(n % 256)
n = floor(n/256)
local c = char(n % 256)
n = floor(n/256)
local d = char(n % 256)
f:write(a,b,c,d)
end
end
function files.writestring(f,s)
f:write(char(byte(s,1,#s)))
end
function files.writebyte(f,b)
f:write(char(b))
end
if fio and fio.readcardinal1 then
files.readcardinal1 = fio.readcardinal1
files.readcardinal2 = fio.readcardinal2
files.readcardinal3 = fio.readcardinal3
files.readcardinal4 = fio.readcardinal4
files.readcardinal1le = fio.readcardinal1le or files.readcardinal1le
files.readcardinal2le = fio.readcardinal2le or files.readcardinal2le
files.readcardinal3le = fio.readcardinal3le or files.readcardinal3le
files.readcardinal4le = fio.readcardinal4le or files.readcardinal4le
files.readinteger1 = fio.readinteger1
files.readinteger2 = fio.readinteger2
files.readinteger3 = fio.readinteger3
files.readinteger4 = fio.readinteger4
files.readinteger1le = fio.readinteger1le or files.readinteger1le
files.readinteger2le = fio.readinteger2le or files.readinteger2le
files.readinteger3le = fio.readinteger3le or files.readinteger3le
files.readinteger4le = fio.readinteger4le or files.readinteger4le
files.readfixed2 = fio.readfixed2
files.readfixed4 = fio.readfixed4
files.read2dot14 = fio.read2dot14
files.setposition = fio.setposition
files.getposition = fio.getposition
files.readbyte = files.readcardinal1
files.readsignedbyte = files.readinteger1
files.readcardinal = files.readcardinal1
files.readinteger = files.readinteger1
local skipposition = fio.skipposition
files.skipposition = skipposition
files.readbytes = fio.readbytes
files.readbytetable = fio.readbytetable
function files.skipshort(f,n)
skipposition(f,2*(n or 1))
end
function files.skiplong(f,n)
skipposition(f,4*(n or 1))
end
end
if fio and fio.writecardinal1 then
files.writecardinal1 = fio.writecardinal1
files.writecardinal2 = fio.writecardinal2
files.writecardinal3 = fio.writecardinal3
files.writecardinal4 = fio.writecardinal4
files.writecardinal1le = fio.writecardinal1le
files.writecardinal2le = fio.writecardinal2le
files.writecardinal3le = fio.writecardinal3le
files.writecardinal4le = fio.writecardinal4le
files.writeinteger1 = fio.writeinteger1 or fio.writecardinal1
files.writeinteger2 = fio.writeinteger2 or fio.writecardinal2
files.writeinteger3 = fio.writeinteger3 or fio.writecardinal3
files.writeinteger4 = fio.writeinteger4 or fio.writecardinal4
files.writeinteger1le = files.writeinteger1le or fio.writecardinal1le
files.writeinteger2le = files.writeinteger2le or fio.writecardinal2le
files.writeinteger3le = files.writeinteger3le or fio.writecardinal3le
files.writeinteger4le = files.writeinteger4le or fio.writecardinal4le
end
if fio and fio.readcardinaltable then
files.readcardinaltable = fio.readcardinaltable
files.readintegertable = fio.readintegertable
else
local readcardinal1 = files.readcardinal1
local readcardinal2 = files.readcardinal2
local readcardinal3 = files.readcardinal3
local readcardinal4 = files.readcardinal4
function files.readcardinaltable(f,n,b)
local t = { }
if b == 1 then for i=1,n do t[i] = readcardinal1(f) end
elseif b == 2 then for i=1,n do t[i] = readcardinal2(f) end
elseif b == 3 then for i=1,n do t[i] = readcardinal3(f) end
elseif b == 4 then for i=1,n do t[i] = readcardinal4(f) end end
return t
end
local readinteger1 = files.readinteger1
local readinteger2 = files.readinteger2
local readinteger3 = files.readinteger3
local readinteger4 = files.readinteger4
function files.readintegertable(f,n,b)
local t = { }
if b == 1 then for i=1,n do t[i] = readinteger1(f) end
elseif b == 2 then for i=1,n do t[i] = readinteger2(f) end
elseif b == 3 then for i=1,n do t[i] = readinteger3(f) end
elseif b == 4 then for i=1,n do t[i] = readinteger4(f) end end
return t
end
end
|
--[[
Copyright 2019 Manticore Games, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--]]
-- Internal custom properties
local COMPONENT_ROOT = script:GetCustomProperty("ComponentRoot"):WaitForObject()
local CONTAINER = script:GetCustomProperty("Container"):WaitForObject()
local PANEL = script:GetCustomProperty("Panel"):WaitForObject()
local LINE_TEMPLATE = script:GetCustomProperty("LineTemplate")
-- User exposed properties
local RESOURCE_TO_TRACK = COMPONENT_ROOT:GetCustomProperty("Resource")
local HIDE_AT_ROUND_END = COMPONENT_ROOT:GetCustomProperty("HideAtRoundEnd")
-- Constants
local LOCAL_PLAYER = Game.GetLocalPlayer()
local FRIENDLY_COLOR = Color.New(0.0, 0.25, 1.0)
local ENEMY_COLOR = Color.New(1.0, 0.0, 0.0)
-- Variables
local playerLines = {}
local atRoundEnd = false
-- nil OnPlayerJoined(Player)
-- Add a line to the scoreboard when a player joins
function OnPlayerJoined(player)
local newLine = World.SpawnAsset(LINE_TEMPLATE, {parent = PANEL})
newLine.y = newLine.height * (#playerLines + 1)
table.insert(playerLines, newLine)
end
-- nil OnPlayerLeft(Player)
-- Remove a line when a player leaves
function OnPlayerLeft(player)
playerLines[#playerLines]:Destroy()
playerLines[#playerLines] = nil
end
-- nil OnRoundStart()
-- Handles showing the scoreboard if HideAtRoundEnd is selected
function OnRoundStart()
atRoundEnd = false
end
-- nil OnRoundEnd()
-- Handles hiding the scoreboard if HideAtRoundEnd is selected
function OnRoundEnd()
atRoundEnd = true
end
-- bool ComparePlayers(Player, Player)
-- Comparing function that sets the sorting order
function ComparePlayers(player1, player2)
local player1Resource = player1:GetResource(RESOURCE_TO_TRACK)
local player2Resource = player2:GetResource(RESOURCE_TO_TRACK)
if player1Resource ~= player2Resource then
return player1Resource > player2Resource
end
-- Use name to ensure consistent order for players that are tied
return player1.name < player2.name
end
-- nil Tick(float)
-- Update visibility and displayed information
function Tick(deltaTime)
if not atRoundEnd then
CONTAINER.visibility = Visibility.INHERIT
local players = Game.GetPlayers()
table.sort(players, ComparePlayers)
for i, player in ipairs(players) do
local teamColor = FRIENDLY_COLOR
local playerResource = player:GetResource(RESOURCE_TO_TRACK)
if player ~= LOCAL_PLAYER and Teams.AreTeamsEnemies(player.team, LOCAL_PLAYER.team) then
teamColor = ENEMY_COLOR
end
local line = playerLines[i]
line:GetCustomProperty("OrderText"):WaitForObject().text = tostring(i)
line:GetCustomProperty("Name"):WaitForObject().text = player.name
line:GetCustomProperty("Name"):WaitForObject():SetColor(teamColor)
line:GetCustomProperty("Icon"):WaitForObject():SetImage(player)
line:GetCustomProperty("ScoreText"):WaitForObject().text = tostring(playerResource)
end
else
CONTAINER.visibility = Visibility.FORCE_OFF
end
end
-- Initialize
local headerLine = World.SpawnAsset(LINE_TEMPLATE, {parent = PANEL})
headerLine:GetCustomProperty("OrderText"):WaitForObject().text = ""
headerLine:GetCustomProperty("Name"):WaitForObject().text = "Player"
headerLine:GetCustomProperty("ScoreText"):WaitForObject().text = "Level"
Game.playerLeftEvent:Connect(OnPlayerLeft)
Game.playerJoinedEvent:Connect(OnPlayerJoined)
if HIDE_AT_ROUND_END then
Game.roundStartEvent:Connect(OnRoundStart)
Game.roundEndEvent:Connect(OnRoundEnd)
end |
SwitchServantCommand = {}
SwitchServantCommand.__index = SwitchServantCommand
setmetatable(SwitchServantCommand, {
__call = function (cls, ...)
return cls.new(...)
end,
})
function SwitchServantCommand:new(current, target)
local self = setmetatable({}, SwitchServantCommand)
self.current = current
self.target = target
return self
end
function SwitchServantCommand:getCurrent()
if (self.current < 1 or self.current > 3) then
scriptExit('[SwitchServantCommand] Invalid Current Position')
end
return Location(215 + Config.SWITCH_CURRENT_POSITION_OFFSET * (self.current - 1), 520)
end
function SwitchServantCommand:getTarget()
if (self.target < 1 or self.target > 3) then
scriptExit('[SwitchServantCommand] Invalid Target')
end
return Location(1115 + Config.SWITCH_CURRENT_POSITION_OFFSET * (self.target - 1), 520)
end
function SwitchServantCommand:execute()
-- TODO: Implement a better switch command.
local cmd = MasterSkillCommand:new(3, nil)
cmd:execute()
wait(1)
click(self:getCurrent())
wait(0.2)
click(self:getTarget())
wait(1)
click('btnSwitch.png')
wait(1)
return true
end
|
SF.Vectors = {}
--- Vector type
-- @shared
local vec_methods, vec_metamethods = SF.Typedef( "Vector" )
local wrap, unwrap = SF.CreateWrapper( vec_metamethods, true, false, debug.getregistry().Vector )
SF.DefaultEnvironment.Vector = function ( ... )
return wrap( Vector( ... ) )
end
SF.Vectors.Wrap = wrap
SF.Vectors.Unwrap = unwrap
SF.Vectors.Methods = vec_methods
SF.Vectors.Metatable = vec_metamethods
--- __newindex metamethod
function vec_metamethods.__newindex ( t, k, v )
if type( k ) == "number" then
if k >= 1 and k <= 3 then
SF.UnwrapObject( t ).__newindex( SF.UnwrapObject( t ), k, v )
end
elseif k == "x" or k == "y" or k == "z" then
SF.UnwrapObject( t ).__newindex( SF.UnwrapObject( t ), k, v )
else
rawset( t, k, v )
end
end
local _p = vec_metamethods.__index
--- __index metamethod
function vec_metamethods.__index ( t, k )
if type( k ) == "number" then
if k >= 1 and k <= 3 then
return unwrap( t )[ k ]
end
else
if k == "x" or k == "y" or k == "z" then
return unwrap( t )[ k ]
end
end
return _p[ k ]
end
--- tostring metamethod
-- @return string representing the vector.
function vec_metamethods:__tostring ()
return unwrap( self ):__tostring()
end
--- multiplication metamethod
-- @param n Scalar to multiply against vector
-- @return Scaled vector.
function vec_metamethods:__mul ( n )
SF.CheckType( n, "number" )
return wrap( unwrap( self ):__mul( n ) )
end
--- division metamethod
-- @param n Scalar to divide the Vector by
-- @return Scaled vector.
function vec_metamethods:__div ( n )
SF.CheckType( n, "number" )
return SF.WrapObject( unwrap( self ):__div( n ) )
end
--- add metamethod
-- @param v Vector to add
-- @return Resultant vector after addition operation.
function vec_metamethods:__add ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
return wrap( unwrap( self ):__add( unwrap( v ) ) )
end
--- sub metamethod
-- @param v Vector to subtract
-- @return Resultant vector after subtraction operation.
function vec_metamethods:__sub ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
return wrap( unwrap( self ):__sub( unwrap( v ) ) )
end
--- unary minus metamethod
-- @returns negated vector.
function vec_metamethods:__unm ()
return wrap( unwrap( self ):__unm() )
end
--- equivalence metamethod
-- @returns bool if both sides are equal.
function vec_metamethods:__eq ( ... )
return SF.Sanitize( unwrap( self ):__eq( SF.Unsanitize( ... ) ) )
end
--- Add vector - Modifies self.
-- @param v Vector to add
-- @return nil
function vec_methods:add ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
unwrap( self ):Add( unwrap( v ) )
end
--- Get the vector's angle.
-- @return Angle
function vec_methods:getAngle ()
return SF.WrapObject( unwrap( self ):Angle() )
end
--- Returns the Angle between two vectors.
-- @param v Second Vector
-- @return Angle
function vec_methods:getAngleEx ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
return SF.WrapObject( unwrap( self ):AngleEx( unwrap( v ) ) )
end
--- Calculates the cross product of the 2 vectors, creates a unique perpendicular vector to both input vectors.
-- @param v Second Vector
-- @return Vector
function vec_methods:cross ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
return wrap( unwrap( self ):Cross( unwrap( v ) ) )
end
--- Returns the pythagorean distance between the vector and the other vector.
-- @param v Second Vector
-- @return Number
function vec_methods:getDistance ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
return unwrap( self ):Distance( unwrap( v ) )
end
--- Returns the squared distance of 2 vectors, this is faster Vector:getDistance as calculating the square root is an expensive process.
-- @param v Second Vector
-- @return Number
function vec_methods:getDistanceSqr ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
return unwrap( self ):DistToSqr( unwrap( v ) )
end
--- Dot product is the cosine of the angle between both vectors multiplied by their lengths. A.B = ||A||||B||cosA.
-- @param v Second Vector
-- @return Number
function vec_methods:dot ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
return unwrap( self ):Dot( unwrap( v ) )
end
--- Returns a new vector with the same direction by length of 1.
-- @return Vector Normalised
function vec_methods:getNormalized ()
return wrap( unwrap( self ):GetNormalized() )
end
--- Is this vector and v equal within tolerance t.
-- @param v Second Vector
-- @param t Tolerance number.
-- @return bool True/False.
function vec_methods:isEqualTol ( v, t )
SF.CheckType( v, SF.Types[ "Vector" ] )
SF.CheckType( t, "number" )
return unwrap( self ):IsEqualTol( unwrap( v ), t )
end
--- Are all fields zero.
-- @return bool True/False
function vec_methods:isZero ()
return unwrap( self ):IsZero()
end
--- Get the vector's Length.
-- @return number Length.
function vec_methods:getLength ()
return unwrap( self ):Length()
end
--- Get the vector's length squared ( Saves computation by skipping the square root ).
-- @return number length squared.
function vec_methods:getLengthSqr ()
return unwrap( self ):LengthSqr()
end
--- Returns the length of the vector in two dimensions, without the Z axis.
-- @return number length
function vec_methods:getLength2D ()
return unwrap( self ):Length2D()
end
--- Returns the length squared of the vector in two dimensions, without the Z axis. ( Saves computation by skipping the square root )
-- @return number length squared.
function vec_methods:getLength2DSqr ()
return unwrap( self ):Length2DSqr()
end
--- Scalar Multiplication of the vector. Self-Modifies.
-- @param n Scalar to multiply with.
-- @return nil
function vec_methods:mul ( n )
SF.CheckType( n, "number" )
unwrap( self ):Mul( n )
end
--- Set's all vector fields to 0.
-- @return nil
function vec_methods:setZero ()
unwrap( self ):Zero()
end
--- Normalise the vector, same direction, length 0. Self-Modifies.
-- @return nil
function vec_methods:normalize ()
unwrap( self ):Normalize()
end
--- Rotate the vector by Angle a. Self-Modifies.
-- @param a Angle to rotate by.
-- @return nil.
function vec_methods:rotate ( a )
SF.CheckType( a, SF.Types[ "Angle" ] )
unwrap( self ):Rotate( SF.UnwrapObject( a ) )
end
--- Copies the values from the second vector to the first vector. Self-Modifies.
-- @param v Second Vector
-- @return nil
function vec_methods:set ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
unwrap( self ):Set( unwrap( v ) )
end
--- Subtract v from this Vector. Self-Modifies.
-- @param v Second Vector.
-- @return nil
function vec_methods:sub ( v )
SF.CheckType( v, SF.Types[ "Vector" ] )
unwrap( self ):Sub( unwrap( v ) )
end
--- Translates the vectors position into 2D user screen coordinates. Self-Modifies.
-- @return nil
function vec_methods:toScreen ()
return unwrap( self ):ToScreen()
end
--- Returns whenever the given vector is in a box created by the 2 other vectors.
-- @param v1 Vector used to define AABox
-- @param v2 Second Vector to define AABox
-- @return bool True/False.
function vec_methods:withinAABox ( v1, v2 )
SF.CheckType( v1, SF.Types[ "Vector" ] )
SF.CheckType( v2, SF.Types[ "Vector" ] )
return unwrap( self ):WithinAABox( unwrap( v1 ), unwrap( v2 ) )
end
|
function love.load() --Declare function
local width, height = love.window.getMode( ) --Get the size of window
--4 is the size of our "pixel" 8 are the sum of borders
rowSize = math.floor(width/4)
columnSize = math.floor(height/4)
gridSize = columnSize*rowSize
--"Pixels" colors that we will use to draw the fire
Colors = {}
Colors.ref = love.graphics.newImage("colors.png") --Load an image
for i=1,36 do --We have 36 colors to represent intensity
--Quads are a part of an original image
Colors[i] = love.graphics.newQuad(
( ( (i - 1) * 24 ) + i ), 0, --X and Y of the color that we want
4, 4, --Both 4 are the size of our "pixel" again
Colors.ref:getDimensions()
)
end
--This grid represents the fire
Grid = {}
for i=1,gridSize do
Grid[i] = 36
end
end
--Timer is a global variable
--usually isn't a good pratice
--but we don't want anything too complex
--so this works fine
Timer = 0
--dt is the delta time between tha last and current call of update()
function love.update(dt)
Timer = Timer + dt
--This is the easiest way to do something like sleep()
if Timer >= 0.05 then
--Finally let's put fire on the screen
for index in ipairs(Grid) do
--If the pixel is in the first row
if index <= rowSize then
--We take the below pixel
index = index + rowSize
end
--Taking a random value will enable us to do a effect really good
local decay = math.random(0, 1)
--To have the decay effect then the force of current pixel
-- will be the force of below pixel less the decay
local force = Grid[ index - rowSize ] - decay
--Make sure that force is bigger than 1
if force < 1 then force = 1 end
--and smaller than 36
if force > 36 then force = 36 end
--If you want just a random decay of a pixel
-- on below pixel then add something like:
--"local Grid[index] = force"
--But just a random decay ins't enough
--We want to write something like wind
--This must be complex right?
--Spoiler: No.
--To do this just put a chance of
-- a pixel to affect its neighborn and not
-- just the below pixel
Grid[index - decay] = force
end
Timer = 0 --Don't forget to reset the timer
end
end
function love.draw() --Let's draw something
--We need to catch every pixel in Grid (its index and intensity)
for index, force in ipairs(Grid) do
--Here if we invert the index we can upside down
-- the Grid order, just subtract the actual index from
-- Grid's total length
index = #Grid - index
--The rest of division of the pixel's index by
-- the rowSize is his position in its row
local x = (index % rowSize)*4 --4 is the pixel size
--The result of division of the pixel's index by
-- the rowSize is the row that it is in but
--a division can return fraction and we don't want it
-- then I use math.floor( ) to round the result
local y = math.floor( ( index - 1 ) / rowSize ) * 4 --4 is the pixel size again
--Then finally we draw the pixel on the screen
love.graphics.draw(Colors.ref, Colors[force], x, y)
end
end
function love.keypressed(key)
if key == "escape" then love.event.push('quit') end
end
|
return {
uptime = os.clock,
} |
--[[----------------------------------------------------------------------------
Application Name:
ScriptUnittestRunner
Summary:
Running the defined unittests
Description:
This app is part of the ScriptUnittest sample. It triggers the runUnittest function
from the ScriptUnittest App. This sample can also be used to trigger unittests from
multiple apps
How to run:
To show this sample it is also required to run both, this App and the ScriptUnittest App.
Clicking the "Start Unittest" button on the user interface prints the according message
to the console.
Implementation:
To add unittests from other apps, their according CROWN can be added to the tests table.
All unittests are then run, but each test is stopped when the test fails.
In order to work, the served function must follow the Syntax CROWNname.runUnittest
------------------------------------------------------------------------------]]
--Start of Global Scope---------------------------------------------------------
-- Variable to hold all Apps(CROWNs) which have a served runUnittest function
-- To add another App serve the runUnittestFunction in that app under their namespace
-- Then adding the value to the 'tests' table e.g. {MyAppOne,MyAppTwo}
local tests = {ScriptUnittest} --luacheck: ignore
--End of Global Scope-----------------------------------------------------------
--Start of Function and Event Scope---------------------------------------------
-- Function is triggered from UI
-- all 'runUnittest' functions from the specified CROWNs in tests are run.
-- each test stops at the failing function.
local function runTests()
for i = 1, #tests do
local appName, result, failPath = tests[i].runUnittest()
if result then
print(appName .. ': Unittest passed')
else
print(appName .. ': Unittest failed in path: ' .. failPath)
end
end
end
-- Serving function for user interface button
Script.serveFunction('ScriptUnittestRunner.runTests', runTests)
--End of Function and Event Scope-----------------------------------------------
|
ITEM.Name = 'Text Hat'
ITEM.Price = 1000
ITEM.Model = 'models/extras/info_speech.mdl'
ITEM.NoPreview = true
local MaxTextLength = 32
function ITEM:PostPlayerDraw(ply, modifications, ply2)
if not ply == ply2 then return end
if not ply:Alive() then return end
if ply.IsSpec and ply:IsSpec() then return end
local offset = Vector(0, 0, 79)
local ang = LocalPlayer():EyeAngles()
local pos = ply:GetPos() + offset + ang:Up()
ang:RotateAroundAxis(ang:Forward(), 90)
ang:RotateAroundAxis(ang:Right(), 90)
cam.Start3D2D(pos, Angle(0, ang.y, 90), 0.1)
draw.DrawText(string.sub(modifications.text or ply:Nick(), 1, MaxTextLength), "PS_Heading", 2, 2, modifications.color or Color(255, 255, 255, 255), TEXT_ALIGN_CENTER)
cam.End3D2D()
end
function ITEM:Modify(modifications)
Derma_StringRequest("Text", "What text do you want your hat to say?", "", function(text)
if string.find(text, "#") then
text = string.gsub(text, "#", "")
end
modifications.text = string.sub(text, 1, MaxTextLength)
PS:ShowColorChooser(self, modifications)
end)
end
-- Since this item has modifications we return a table of only what should be allowed for security reasons
function ITEM:SanitizeTable( modifications )
local tab = {}
tab.text = modifications.text and string.sub(modifications.text, 1, MaxTextLength) or nil
tab.color = modifications.color and Color(modifications.color.r or 255, modifications.color.g or 255, modifications.color.b or 255, 255) or Color(255,255,255)
return tab
end
|
info = {
["name"] = "Nyaa",
["id"] = "Kikyou.r.Nyaa",
["desc"] = "Nyaa搜索, nyaa.si",
["version"] = "0.1",
}
function search(keyword,page)
--kiko_HttpGet arg:
-- url: string
-- query: table, {["key"]=value} value: string
-- header: table, {["key"]=value} value: string
local err,reply=kiko.httpget("https://nyaa.si/",{["f"]="0",["c"]="0_0",["q"]=keyword,["p"]=math.ceil(page)})
if err~=nil then error(err) end
local content = reply["content"]
local _,_,pageCount=string.find(content,"(%d+)</a>%s*</li>%s*<li class=\"next\">")
if pageCount==nil then
pageCount=1
end
local rowPos=1
local itemsList={}
rowPos=string.find(content,"<tr class=\"default\">",rowPos,true)
while rowPos~=nil do
local _,cpos,url,title=string.find(content,"<td colspan=\"2\">.-<a href=\"(/view/%d+)\" title=\"(.-)\">",rowPos)
url="https://nyaa.si" .. url
title=string.gsub(title,"&","&")
title=string.gsub(title,"⁢","<")
title=string.gsub(title,">",">")
title=string.gsub(title,""","\"")
title=string.gsub(title," "," ")
local _,cpos,magnet=string.find(content,"<a href=\"(magnet.-)\">",cpos)
magnet=string.gsub(magnet,"&","&")
local _,cpos,size=string.find(content,"<td class=\"text%-center\">(.-)</td>",cpos)
local _,cpos,time=string.find(content,"<td class=\"text%-center\".->(.-)</td>",cpos)
rowPos=cpos
table.insert(itemsList,{
["title"]=title,
["size"]=size,
["time"]=time,
["magnet"]=magnet,
["url"]=url
})
rowPos=string.find(content,"<tr class=\"default\">",rowPos,true)
end
if rawlen(itemsList)==0 then
pageCount=0
end
return itemsList, tonumber(pageCount)
end |
local tbTable = GameMain:GetMod("MagicHelper")
local tbMagic = tbTable:GetMagic("TTMG_1_3")
function tbMagic:GetLuDing()
local target = ThingMgr:FindThingByID(self.targetId)
local value1 = self.bind.PropertyMgr.Practice.AccumulativeLing
local value2 = target.PropertyMgr.Practice.AccumulativeLing
local value3 = self.bind:GetProperty("MaxAccumulativeLingAddV")
local value4 = target:GetProperty("MaxAccumulativeLingAddV")
local maxvalue1 = self.bind.PropertyMgr.Practice:GetMaxAccumulativeLing()
local maxvalue2 = target.PropertyMgr.Practice:GetMaxAccumulativeLing()
local num = 0.1 * target.PropertyMgr.Practice.Potential
if value1 >= 100000 then
return 1
else
if value2 <= 0 then
if self.bind.LuaHelper:IsLearnedEsoteric("Gong_TTMG_1_3") then
if maxvalue2 <= 0 then
return 1
else
self.bind.PropertyMgr:SetPropertyOverwrite("MaxAccumulativeLingAddV", value3 + num)
target.PropertyMgr:SetPropertyOverwrite("MaxAccumulativeLingAddV", value4 - num)
end
else
return 1
end
else
self.bind.PropertyMgr.Practice.AccumulativeLing = value1 + num
target.PropertyMgr.Practice.AccumulativeLing = value2 - num
self.bind.PropertyMgr:ModifierProperty("NpcLingMaxValue", num, 0, 0, 0)
target.PropertyMgr:ModifierProperty("NpcLingMaxValue", -num, 0, 0, 0)
self.bind.PropertyMgr:SetPropertyOverwrite("MaxAccumulativeLingAddV", value3 + num)
target.PropertyMgr:SetPropertyOverwrite("MaxAccumulativeLingAddV", value4 - num)
end
end
end
function tbMagic:GetLuDingSudden()
local target = ThingMgr:FindThingByID(self.targetId)
local value1 = self.bind.PropertyMgr.Practice.AccumulativeLing
local value2 = target.PropertyMgr.Practice.AccumulativeLing
local value3 = self.bind:GetProperty("MaxAccumulativeLingAddV")
local value4 = target:GetProperty("MaxAccumulativeLingAddV")
local maxvalue1 = self.bind.PropertyMgr.Practice:GetMaxAccumulativeLing()
local maxvalue2 = target.PropertyMgr.Practice:GetMaxAccumulativeLing()
self.bind.PropertyMgr.Practice.AccumulativeLing = value1 + value2
target.PropertyMgr.Practice.AccumulativeLing = 0
target.PropertyMgr:ModifierProperty("NpcLingMaxValue", -value2, 0, 0, 0)
target.PropertyMgr:SetPropertyOverwrite("MaxAccumulativeLingAddV", value4 - maxvalue2)
end
function tbMagic:EnableCheck(npc)
if npc.LuaHelper:GetGongName() == "Gong_TTMG" then
return true
else
return false
end
end
function tbMagic:TargetCheck(key, t)
if not t or t.ThingType ~= CS.XiaWorld.g_emThingType.Npc then
return false
end
if t.Race.RaceType == CS.XiaWorld.g_emNpcRaceType.Animal then
return false
end
if t.ThingType == CS.XiaWorld.g_emThingType.Npc then
if t.Camp ~= CS.XiaWorld.Fight.g_emFightCamp.Player then
if t.IsDisciple then
return true
else
return false
end
else
return false
end
else
return false
end
end
function tbMagic:MagicEnter(IDs, IsThing)
self.targetId = IDs[0]
end
function tbMagic:MagicStep(dt, duration)
local target = ThingMgr:FindThingByID(self.targetId)
self:SetProgress(duration / self.magic.Param1)
if self.bind.LuaHelper:IsLearnedEsoteric("Gong_TTMG_1_3") then
return 1
else
local target = ThingMgr:FindThingByID(self.targetId)
local value1 = self.bind.PropertyMgr.Practice.AccumulativeLing
local value2 = target.PropertyMgr.Practice.AccumulativeLing
local value3 = self.bind:GetProperty("MaxAccumulativeLingAddV")
local value4 = target:GetProperty("MaxAccumulativeLingAddV")
local maxvalue1 = self.bind.PropertyMgr.Practice:GetMaxAccumulativeLing()
local maxvalue2 = target.PropertyMgr.Practice:GetMaxAccumulativeLing()
local num = 0.1 * target.PropertyMgr.Practice.Potential
if value1 >= 100000 then
return 1
else
if value2 <= 0 then
if self.bind.LuaHelper:IsLearnedEsoteric("Gong_TTMG_1_3") then
if maxvalue2 <= 0 then
return 1
else
self.bind.PropertyMgr:SetPropertyOverwrite("MaxAccumulativeLingAddV", value3 + num)
target.PropertyMgr:SetPropertyOverwrite("MaxAccumulativeLingAddV", value4 - num)
end
else
return 1
end
else
self.bind.PropertyMgr.Practice.AccumulativeLing = value1 + num
target.PropertyMgr.Practice.AccumulativeLing = value2 - num
self.bind.PropertyMgr:SetPropertyOverwrite("MaxAccumulativeLingAddV", value3 + num)
target.PropertyMgr:SetPropertyOverwrite("MaxAccumulativeLingAddV", value4 - num)
end
end
if duration >= self.magic.Param1 then
return 1
end
return 0
end
end
function tbMagic:MagicLeave(success)
if success then
local target = ThingMgr:FindThingByID(self.targetId)
if target then
if self.bind.LuaHelper:IsLearnedEsoteric("Gong_TTMG_1_3") then
local target = ThingMgr:FindThingByID(self.targetId)
local value1 = self.bind.PropertyMgr.Practice.AccumulativeLing
local value2 = target.PropertyMgr.Practice.AccumulativeLing
local value3 = self.bind:GetProperty("MaxAccumulativeLingAddV")
local value4 = target:GetProperty("MaxAccumulativeLingAddV")
local maxvalue1 = self.bind.PropertyMgr.Practice:GetMaxAccumulativeLing()
local maxvalue2 = target.PropertyMgr.Practice:GetMaxAccumulativeLing()
self.bind.PropertyMgr.Practice.AccumulativeLing = value1 + value2 * 0.1
target.PropertyMgr.Practice.AccumulativeLing = 0
self.bind.PropertyMgr:SetPropertyOverwrite("MaxAccumulativeLingAddV", value3 + maxvalue2 * 0.1)
target.PropertyMgr:SetPropertyOverwrite("MaxAccumulativeLingAddV", value4 - maxvalue2)
self.bind.LuaHelper:TriggerStory("TTMG_1_3")
end
end
end
end |
RatingsHandler = {}
local MESSAGE_PREFIX = "[Map Ratings] "
function RatingsHandler.handlePlayerRate (player, cmd)
local forumid = exports.gc:getPlayerForumID(player)
if not forumid then outputChatBox(MESSAGE_PREFIX .. "You have to be logged in to a Green-Coins account to rate a map.", player, 255,0,0) return end
local playerCooldownSeconds = RatingsCooldown.getPlayerCooldownSeconds(player)
if playerCooldownSeconds then
outputChatBox(MESSAGE_PREFIX .. "Please wait ".. playerCooldownSeconds .. " seconds before rating a map.", player, 255,0,0)
return
end
local connection = Database.getConnection()
local mapresourcename = getResourceName( exports.mapmanager:getRunningGamemodeMap() )
local rating = cmd == "like" and 1 or 0
local mapname = getResourceInfo(exports.mapmanager:getRunningGamemodeMap() , "name") or mapresourcename
if not connection then
outputChatBox(MESSAGE_PREFIX .. "Could not make connection to database. Please try again later.", player, 255,0,0)
return
end
local currentRating = CurrentMapRatings.getByForumID(forumid)
if currentRating == cmd then
if cmd == "like" then
outputChatBox(MESSAGE_PREFIX .. "You already liked this map.", player, 255, 0, 0, true)
else
outputChatBox(MESSAGE_PREFIX .. "You already disliked this map.", player, 255, 0, 0, true)
end
return
end
local save = dbExec(connection,"INSERT INTO mapratings (forumid, mapresourcename, rating) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE rating = ?", forumid, mapresourcename, rating, rating)
if save then
if currentRating == false then
if cmd == "like" then
outputChatBox(MESSAGE_PREFIX .. "You liked the map: "..mapname, player, 225, 170, 90, true)
else
outputChatBox(MESSAGE_PREFIX .. "You disliked the map: "..mapname, player, 225, 170, 90, true)
end
else
if cmd == "like" then
outputChatBox(MESSAGE_PREFIX .. "Changed from dislike to like.", player, 225, 170, 90, true)
else
outputChatBox(MESSAGE_PREFIX .. "Changed from like to dislike.", player, 225, 170, 90, true)
end
end
-- Update ratings, recount and trigger updates
CurrentMapRatings.setByForumID(forumid, rating)
Broadcaster.broadcastCurrentMap()
RatingsCooldown.setPlayerInCooldown(player)
else
outputChatBox(MESSAGE_PREFIX .. "Something went wrong while saving your map rating. Please try again or inform a developer.", player, 255, 0, 0, true)
return
end
end
addCommandHandler('like', RatingsHandler.handlePlayerRate, false, false)
addCommandHandler('dislike', RatingsHandler.handlePlayerRate, false, false)
|
local colors = {
head = Color(192, 57, 43, 255),
back = Color(236, 240, 241, 255),
text = Color(255, 255, 255, 255),
text_blue = Color(52, 152, 219, 255),
btn = Color(52, 73, 94, 255),
btn_hover = Color(44, 62, 80, 255),
btn_disabled = Color(52, 73, 94, 150),
open = Color(46, 204, 113, 255),
open_hover = Color(39, 174, 96, 255),
open_disabled = Color(46, 2014, 113, 150),
cancel = Color(231, 76, 60, 255),
cancel_hover = Color(192, 57, 43, 255),
bar = Color(189, 195, 199, 255),
barup = Color(127, 140, 141, 255),
closed = Color(230, 126, 34, 255),
closed_hover = Color(211, 84, 0, 255),
info_back = Color(189, 195, 199, 255),
gray = Color(189, 195, 199, 255),
gray_hover = Color(127, 140, 141, 255),
}
--[[asdf]]--
surface.CreateFont("stockHead", {font = "OpenSans-Bold", size = 60, weight = 500})
surface.CreateFont("stockBtn", {font = "OpenSans-Regular", size = 30, weight = 500})
surface.CreateFont("stockBtnSmall", {font = "OpenSans-Light", size = 15, weight = 500})
local c = nil;
local frame = nil;
local function CreateChartMenu(link, name)
if (c) then c:Close(); end
if (frame) then frame:SetVisible(false); end
local f = vgui.Create("DFrame");
f:SetPos(100, 100);
f:SetSize(837, 545);
f:SetTitle(" ");
f:SetVisible(true);
f:MakePopup();
f:Center();
f.ChartName = name;
f:ShowCloseButton(false);
f.Paint = function()
draw.RoundedBox(0, 0, 0, f:GetWide(), f:GetTall(), colors.back);
draw.RoundedBox(0, 0, 0, f:GetWide(), 100, colors.head);
draw.SimpleText("Chart for "..name, "stockHead", f:GetWide() / 2, 20, colors.text, TEXT_ALIGN_CENTER);
end
c = f;
local ht = vgui.Create("DHTML", f);
ht:SetSize(f:GetWide() - 20, f:GetTall() - 180);
ht:SetPos(10, 110);
ht:OpenURL(link);
local close = vgui.Create("DButton", f);
close:SetText("");
close:SetSize(f:GetWide() - 20, 50);
close:SetPos(10, f:GetTall() - 60);
close.DoClick = function()
c = nil;
frame:SetVisible(true);
f:Close();
end
local ca = false;
function close:OnCursorEntered() ca = true; end
function close:OnCursorExited() ca = false; end
close.Paint = function()
if (ca) then
draw.RoundedBox(0, 0, 0, close:GetWide(), close:GetTall(), colors.cancel_hover);
else
draw.RoundedBox(0, 0, 0, close:GetWide(), close:GetTall(), colors.cancel);
end
draw.SimpleText("Close", "stockBtn", close:GetWide() / 2, 10, colors.text, TEXT_ALIGN_CENTER);
end
end
net.Receive("StockMenu_Open", function()
local stocklist = net.ReadTable();
local opt = nil;
local action = nil;
local function PricePerStock(symb)
local li = stocklist["query"]["results"]["quote"]; //client table
for k,v in pairs(li) do
if (v["Symbol"] == symb) then return v["LastTradePriceOnly"] or 0; end
end
end
local f = vgui.Create("DFrame");
f:SetPos(100, 100);
f:SetSize(ScrW() - 100, ScrH() - 100);
f:SetTitle(" ");
f:SetVisible(true);
f:MakePopup();
f:Center();
f:ShowCloseButton(false);
f.Paint = function()
draw.RoundedBox(0, 0, 0, f:GetWide(), f:GetTall(), colors.back);
draw.RoundedBox(0, 0, 0, f:GetWide(), 100, colors.head);
draw.SimpleText("GStock Market", "stockHead", f:GetWide() / 2, 20, colors.text, TEXT_ALIGN_CENTER)
end
frame = f;
local pan = vgui.Create("DScrollPanel", f);
pan:SetSize(f:GetWide() - 355, f:GetTall() - 120);
pan:SetPos(10, 110);
pan:GetVBar().Paint = function() draw.RoundedBox(0, 0, 0, pan:GetVBar():GetWide(), pan:GetVBar():GetTall(), Color(255, 255, 255, 0)) end
pan:GetVBar().btnUp.Paint = function() draw.RoundedBox(0, 0, 0, pan:GetVBar().btnUp:GetWide(), pan:GetVBar().btnUp:GetTall(), colors.barup) end
pan:GetVBar().btnDown.Paint = function() draw.RoundedBox(0, 0, 0, pan:GetVBar().btnDown:GetWide(), pan:GetVBar().btnDown:GetTall(), colors.barup) end
pan:GetVBar().btnGrip.Paint = function(w, h) draw.RoundedBox(0, 0, 0, pan:GetVBar().btnGrip:GetWide(), pan:GetVBar().btnGrip:GetTall(), colors.bar) end
local slist = vgui.Create("DIconLayout", pan);
slist:SetSize(pan:GetWide() - 15, pan:GetTall());
slist:SetPos(0, 0);
slist:SetSpaceY(5);
slist:SetSpaceX(5);
local function UpdateList()
local lis = stocklist["query"]["results"]["quote"];
for k,v in pairs(lis) do
local li = slist:Add("DPanel");
li:SetSize(400, 200);
li.Paint = function()
draw.RoundedBox(0, 0, 0, li:GetWide(), li:GetTall(), colors.btn);
draw.TexturedQuad{
texture = surface.GetTextureID("gui/gradient");
color = colors.info_back;
x = 0,
y = 0;
w = li:GetWide();
h = 40;
}
end
local lbl = vgui.Create("DLabel", li);
lbl:SetText(stock.RealNameList[v["Symbol"]]);
lbl:SetPos(10, 5);
lbl:SetFont("stockBtn");
lbl:SetTextColor(colors.text);
lbl:SizeToContents();
local per = vgui.Create("DLabel", li);
per:SetText("Percent Change: "..v["PercentChange"]);
per:SetPos(10, 45);
per:SetFont("stockBtn");
if (string.find(v["PercentChange"], "+")) then
per:SetTextColor(colors.open);
else
per:SetTextColor(colors.cancel);
end
per:SizeToContents();
local pr = vgui.Create("DLabel", li);
pr:SetText("Price Per Share: $"..v["LastTradePriceOnly"]);
pr:SetPos(10, 80);
pr:SetFont("stockBtn");
pr:SetTextColor(colors.text);
pr:SizeToContents();
local mc = vgui.Create("DLabel", li);
mc:SetText("Company Worth: $"..v["MarketCapitalization"]);
mc:SetPos(10, 115);
mc:SetFont("stockBtn");
mc:SetTextColor(colors.text);
mc:SizeToContents();
local oc = vgui.Create("DLabel", li);
oc:SetText("Last Open/Close: $"..v["Open"].."/$"..v["PreviousClose"]);
oc:SetPos(10, 150);
oc:SetFont("stockBtn");
oc:SetTextColor(colors.text);
oc:SizeToContents();
local btn = vgui.Create("DButton", li);
btn:SetText(" ");
btn:SetFont("stockBtnSmall");
btn:SetPos(li:GetWide() - 100, 0);
btn:SetSize(100, 40);
btn.ChartURL = "https://chart.finance.yahoo.com/z?s="..v["Symbol"].."&t=1y&q=&l=&z=l&a=v&p=s&lang=en-US®ion=US";
btn.SymName = lbl:GetText();
btn.DoClick = function()
CreateChartMenu(btn.ChartURL, btn.SymName);
end
local ba = false;
function btn:OnCursorEntered() ba = true; end
function btn:OnCursorExited() ba = false; end
btn.Paint = function()
if (ba) then
draw.RoundedBox(0, 0, 0, btn:GetWide(), btn:GetTall(), colors.gray_hover);
else
draw.RoundedBox(0, 0, 0, btn:GetWide(), btn:GetTall(), colors.gray);
end
draw.SimpleText("Chart", "stockBtn", btn:GetWide() / 2, 5, colors.text, TEXT_ALIGN_CENTER);
end
end
end
UpdateList();
local stLbl = vgui.Create("DLabel", f);
stLbl:SetPos(f:GetWide() - 335, 110);
stLbl:SetText("Choose a stock:");
stLbl:SetFont("stockBtn");
stLbl:SetTextColor(colors.text_blue);
stLbl:SizeToContents();
local stBox = vgui.Create("DComboBox", f);
stBox:SetPos(f:GetWide() - 335, 145)
stBox:SetSize(325, 40);
stBox:SetValue("Stock");
for k,v in pairs(stock.RealNameList) do
stBox:AddChoice(v);
end
local canDo = vgui.Create("DLabel", f);
canDo:SetPos(f:GetWide() - 335, 175);
canDo:SetText(" ");
canDo:SetFont("stockBtnSmall");
canDo:SetTextColor(colors.text_blue);
canDo:SizeToContents();
local numLbl = vgui.Create("DLabel", f);
numLbl:SetPos(f:GetWide() - 335, 225);
numLbl:SetText("Number of shares to buy/sell:");
numLbl:SetFont("stockBtn");
numLbl:SetTextColor(colors.text_blue);
numLbl:SizeToContents();
local num = vgui.Create("DTextEntry", f);
num:SetPos(f:GetWide() - 335, 260);
num:SetSize(325, 40);
num:SetText("0");
num:SetNumeric(true);
num.OnTextChanged = function()
if (string.len(num:GetValue()) > stock.SharesPerStock) then num:SetText("1000"); end
end
stBox.OnSelect = function(panel, ind, val)
opt = val;
local key = table.KeyFromValue(stock.RealNameList, opt);
local shares = LocalPlayer():GetShares(key);
canDo:SetText("Shares "..shares.."/"..stock.SharesPerStock);
canDo:SetSize(325, 50);
end
local actBox = vgui.Create("DComboBox", f);
actBox:SetPos(f:GetWide() - 335, 310)
actBox:SetSize(325, 40);
actBox:SetValue("Buy or Sell");
actBox:AddChoice("Buy");
actBox:AddChoice("Sell");
actBox.OnSelect = function(p, i, val)
action = val;
end
local cost = vgui.Create("DLabel", f);
cost:SetPos(f:GetWide() - 335, f:GetTall() - 185);
cost:SetText(" ");
cost:SetFont("stockBtn");
cost:SetTextColor(colors.text_blue);
cost:SizeToContents();
local doit = vgui.Create("DButton", f);
doit:SetText("");
doit:SetSize(325, 50);
doit:SetPos(f:GetWide() - 335, f:GetTall() - 120);
doit:SetDisabled(true);
doit.DoClick = function()
if (opt && action && num:GetValue()) then
net.Start("Player_ShareActions")
net.WriteString(num:GetValue());
net.WriteString(opt);
net.WriteString(action);
net.SendToServer();
f:Close();
end
end
local ba = false;
function doit:OnCursorEntered() ba = true; end
function doit:OnCursorExited() ba = false; end
doit.Paint = function()
if (doit:GetDisabled()) then
draw.RoundedBox(0, 0, 0, doit:GetWide(), doit:GetTall(), colors.open_disabled);
else
if (ba) then
draw.RoundedBox(0, 0, 0, doit:GetWide(), doit:GetTall(), colors.open_hover);
else
draw.RoundedBox(0, 0, 0, doit:GetWide(), doit:GetTall(), colors.open);
end
end
draw.SimpleText("Do it!", "stockBtn", doit:GetWide() / 2, 10, colors.text, TEXT_ALIGN_CENTER);
end
function f:Think()
if (!opt or !action or !tonumber(num:GetValue())) then return; end
if (doit:GetDisabled()) then doit:SetDisabled(false); end
if (string.find(num:GetValue(), "-")) then
cost:SetText("No negative amounts please!");
cost:SetSize(320, 70);
doit:SetDisabled(true);
return;
end
local key = table.KeyFromValue(stock.RealNameList, opt);
local pric = PricePerStock(key);
local pric_tot = (tonumber(pric) * tonumber(num:GetValue()));
if (action == "Buy") then
cost:SetText("This will cost you: $"..string.Comma(pric_tot));
cost:SetSize(320, 70);
else //selling
cost:SetText("If you have enough shares, \nyou will get: $"..string.Comma(pric_tot));
cost:SetSize(320, 70);
cost:SetPos(f:GetWide() - 335, f:GetTall() - 225)
end
end
local cancel = vgui.Create("DButton", f);
cancel:SetText("");
cancel:SetSize(325, 50);
cancel:SetPos(f:GetWide() - 335, f:GetTall() - 60);
cancel.DoClick = function()
f:Close();
end
local ca = false;
function cancel:OnCursorEntered() ca = true; end
function cancel:OnCursorExited() ca = false; end
cancel.Paint = function()
if (ca) then
draw.RoundedBox(0, 0, 0, cancel:GetWide(), cancel:GetTall(), colors.cancel_hover);
else
draw.RoundedBox(0, 0, 0, cancel:GetWide(), cancel:GetTall(), colors.cancel);
end
draw.SimpleText("Cancel", "stockBtn", cancel:GetWide() / 2, 10, colors.text, TEXT_ALIGN_CENTER);
end
net.Receive("NewStockDataReceived", function()
if (IsValid(f)) then
MsgN("New stock data received! Updating layout..");
slist:Clear();
UpdateList(); //reload the diconlayout
end
end)
end)
net.Receive("ChatMsg_CL", function()
local msg = net.ReadString();
chat.AddText(stock.BracketColor, "[", stock.StockTextColor, "GStock", stock.BracketColor, "] ", stock.MsgColor, msg);
end) |
return {'yasar','yasin','yasmien','yasmin','yasmina','yasmine','yasser','yassin','yassine','yasars','yasins','yasmiens','yasmins','yasminas','yasmines','yassers','yassins','yassines'} |
local ObjectManager = require("managers.object.object_manager")
heroOfTatIntercomConvoHandler = conv_handler:new {}
function heroOfTatIntercomConvoHandler:getInitialScreen(pPlayer, pNpc, pConvTemplate)
local convoTemplate = LuaConversationTemplate(pConvTemplate)
local playerID = CreatureObject(pPlayer):getObjectID()
local inProgressID = readData("hero_of_tat:ranch_player_id")
if (inProgressID ~= 0 and inProgressID ~= playerID) then
return convoTemplate:getScreen("intro_noquest")
elseif (readData(playerID .. ":hero_of_tat_honor:accepted") == 1) then
if (readData(playerID .. ":hero_of_tat_honor:distract_wife") == 1) then
return convoTemplate:getScreen("intro_alreadytalked")
else
return convoTemplate:getScreen("intro")
end
else
return convoTemplate:getScreen("intro_noquest")
end
end
function heroOfTatIntercomConvoHandler:runScreenHandlers(pConvTemplate, pPlayer, pNpc, selectedOption, pConvScreen)
local screen = LuaConversationScreen(pConvScreen)
local screenID = screen:getScreenID()
local pConvScreen = screen:cloneScreen()
local clonedConversation = LuaConversationScreen(pConvScreen)
if (screenID == "blast_it" or screenID == "go_talk_to_her") then
writeData(CreatureObject(pPlayer):getObjectID() .. ":hero_of_tat_honor:distracting_wife", 1)
end
return pConvScreen
end
|
//afkkick default config
local function SetupDefaultConfig()
local DefaultConfig = { }
DefaultConfig.kPauseChangeDelay = 5
DefaultConfig.kPauseMaxPauses = 3
DefaultConfig.kPausedReadyNotificationDelay = 30
DefaultConfig.kPausedMaxDuration = 0
DefaultConfig.kPauseChatCommands = { "pause" }
DefaultConfig.kUnPauseChatCommands = { "unpause" }
return DefaultConfig
end
DAK:RegisterEventHook("PluginDefaultConfigs", {PluginName = "pause", DefaultConfig = SetupDefaultConfig })
local function SetupDefaultLanguageStrings()
local DefaultLangStrings = { }
DefaultLangStrings["PauseResumeMessage"] = "Game Resumed. %s have %s pauses remaining"
DefaultLangStrings["PausePausedMessage"] = "Game Paused."
DefaultLangStrings["PauseWarningMessage"] = "Game will %s in %.1f seconds."
DefaultLangStrings["PauseResumeWarningMessage"] = "Game will automatically resume in %.1f seconds."
DefaultLangStrings["PausePlayerMessage"] = "%s has paused the game."
DefaultLangStrings["PauseTeamReadiedMessage"] = "%s readied for %s, resuming game."
DefaultLangStrings["PauseTeamReadyMessage"] = "%s readied for %s, waiting for the %s."
DefaultLangStrings["PauseTeamReadyPeriodicMessage"] = "%s are ready, waiting for the %s."
DefaultLangStrings["PauseNoTeamReadyMessage"] = "No team is ready to resume, type unpause in console to ready for your team."
DefaultLangStrings["PauseCancelledMessage"] = "Game Pause Cancelled."
DefaultLangStrings["PauseTooManyPausesMessage"] = "Your team is out of pauses."
return DefaultLangStrings
end
DAK:RegisterEventHook("PluginDefaultLanguageDefinitions", SetupDefaultLanguageStrings) |
AddCSLuaFile()
ENT.Type = "anim"
function ENT:Initialize()
self:AddCallback("BuildBonePositions", self.BoneItUp)
if SERVER then
self:AddEffects(bit.bor(EF_BONEMERGE, EF_BONEMERGE_FASTCULL)) --fastcull seems to fix laggy bullshit garbage
end
self:GetParent():SetSubMaterial(0, "models/effects/vol_light001")
end
function ENT:BoneItUp(boneCount)
local boneId = self:LookupBone("ValveBiped.Bip01_Head1")
if not boneId then return end
local matrix = self:GetBoneMatrix(boneId)
if not matrix then return end
matrix:Scale(Vector(.01, .01, .01))
self:SetBoneMatrix(boneId, matrix)
end
|
-- Abreviaçoes
local g = vim.g
local cmd = vim.cmd
local opt = vim.opt
-- Leader
g.mapleader = ','
opt.title = true
opt.signcolumn = "yes"
opt.splitbelow = true
opt.splitright = true
opt.termguicolors = true
opt.fillchars = { vert = ' ' }
opt.showtabline = 2
opt.scrolloff = 5
opt.mouse = 'a'
opt.undolevels = 1000
opt.shortmess:append "sI"
opt.showmode = true
opt.hidden = true
opt.wrapscan = true
opt.backup = true
opt.writebackup = false
opt.showcmd = true
opt.showmatch = true
opt.ignorecase = true
opt.hlsearch = true
opt.smartcase = true
opt.errorbells = false
opt.joinspaces = false
opt.lazyredraw = true
opt.encoding = 'UTF-8'
opt.fileformat = 'unix'
opt.softtabstop = 2
opt.expandtab = true
opt.shiftwidth = 2
opt.number = true
opt.colorcolumn = "+1"
opt.signcolumn = 'yes'
opt.relativenumber = true
opt.foldenable = false
opt.cursorline = true
|
local Tram = require('modutram.grid_module.Tram')
-- @module modutram.grid_module.TramBidirectionalRight
local TramBidirectionalRightClass = {}
function TramBidirectionalRightClass:new(Tram)
local TramBidirectionalRight = Tram
TramBidirectionalRight.class = 'TramBidirectionalRight'
return TramBidirectionalRight
end
function TramBidirectionalRightClass.getParentClass()
return Tram
end
return TramBidirectionalRightClass |
require 'spec_helper'
describe["_.first"] = function()
it["should return the first item"] = function()
input = { 1,2,3,4 }
result = _.first(input)
expect(result).should_be(1)
end
describe["when passing in a size"] = function()
it["should return an array with the first n items"] = function()
input = { 1,2,3,4 }
result = _.first(input,2)
expect(result).should_equal {1,2}
end
end
end
spec:report(true) |
local fn = vim.fn
-- Automatically install packer
local install_path = fn.stdpath "data" .. "/site/pack/packer/start/packer.nvim"
if fn.empty(fn.glob(install_path)) > 0 then
PACKER_BOOTSTRAP = fn.system {
"git",
"clone",
"--depth",
"1",
"https://github.com/wbthomason/packer.nvim",
install_path,
}
print "Installing packer close and reopen Neovim..."
vim.cmd [[packadd packer.nvim]]
end
-- Autocommand that reloads neovim whenever you save the plugins.lua file
vim.cmd [[
augroup packer_user_config
autocmd!
autocmd BufWritePost plugins.lua source <afile> | PackerSync
augroup end
]]
-- Use a protected call so we don"t error out on first use
local status_ok, packer = pcall(require, "packer")
if not status_ok then
return
end
-- Have packer use a popup window
packer.init {
display = {
open_fn = function()
return require("packer.util").float { border = "rounded" }
end,
},
}
---- Plugins ----
return packer.startup(function(use)
use "wbthomason/packer.nvim"
use "lewis6991/impatient.nvim"
use "nvim-lua/plenary.nvim"
use "nvim-lua/popup.nvim"
use "rcarriga/nvim-notify"
---- Treesitter related
use {
"nvim-treesitter/nvim-treesitter",
run = ":TSUpdate",
}
use "p00f/nvim-ts-rainbow" -- Rainbow paranthesis
use {
"JoosepAlviste/nvim-ts-context-commentstring", -- For context dependent commenting
}
use {
"romgrk/nvim-treesitter-context", -- Shows context of current position using floatin window
after = "nvim-treesitter",
config = function()
require("treesitter-context").setup()
end,
}
-- Quick fix window
use { "kevinhwang91/nvim-bqf", ft = "qf" }
-- file types
use "nathom/filetype.nvim"
---- Telescope related
use "nvim-telescope/telescope.nvim"
use {
"nvim-telescope/telescope-fzf-native.nvim", -- Native C sorting for better performance
run = "make",
after = "telescope.nvim",
config = function()
require("telescope").load_extension "fzf"
end,
}
use {
"nvim-telescope/telescope-frecency.nvim",
after = "telescope.nvim",
config = function()
require("telescope").load_extension "frecency"
end,
requires = { "tami5/sqlite.lua" },
}
-- Search headings
use {
"crispgm/telescope-heading.nvim",
after = "telescope.nvim",
config = function()
require("telescope").load_extension "heading"
end,
}
-- Symbols
use "nvim-telescope/telescope-symbols.nvim"
-- Project management
use {
"ahmedkhalf/project.nvim", -- Superior project management
after = "telescope.nvim",
config = function()
require("project_nvim").setup {}
require("telescope").load_extension "projects"
end,
}
---- LSP related
use "neovim/nvim-lspconfig"
use "williamboman/nvim-lsp-installer"
use "tamago324/nlsp-settings.nvim"
use "jose-elias-alvarez/null-ls.nvim"
use {
"rmagatti/goto-preview", -- Preview goto definition in floating window
after = "nvim-lspconfig",
config = function()
require("goto-preview").setup {}
end,
}
-- completions
use {
"ray-x/lsp_signature.nvim", -- Show function signatures
after = "nvim-lspconfig",
config = function()
require("lsp_signature").setup()
end,
}
-- Diagonostics
use {
"folke/trouble.nvim", -- A pretty list for showing diagnostics
opt = true,
after = "nvim-lspconfig",
cmd = { "Trouble", "TroubleClose", "TroubleToggle", "TroubleRefersh" },
config = function()
require("trouble").setup()
end,
}
use "antoinemadec/FixCursorHold.nvim"
-- Code navigation
use {
"simrat39/symbols-outline.nvim", -- A tree like view for navigating symbols
after = "nvim-lspconfig",
cmd = { "SymbolsOutline", "SymbolsOutlineOpen", "SymbolsOutlineClose" },
config = function()
require("symbols-outline").setup()
end,
}
-- Spell check
use {
"lewis6991/spellsitter.nvim", -- Speechecker
after = "nvim-treesitter",
config = function()
require("spellsitter").setup()
end,
}
---- Completions
use "hrsh7th/nvim-cmp"
use {
"hrsh7th/cmp-buffer", -- buffer completions
}
use {
"hrsh7th/cmp-path", -- path completions
}
use {
"hrsh7th/cmp-cmdline", -- cmdline completions
opt = true,
event = "CmdlineEnter",
}
use {
"hrsh7th/cmp-nvim-lsp", -- lsp completions
}
use { "tzachar/cmp-tabnine", run = "./install.sh", requires = "hrsh7th/nvim-cmp" } -- tabnine
use {
"petertriho/cmp-git", -- git issue/pull request completions
opt = true,
ft = "gitcommit",
config = function()
require("cmp_git").setup()
end,
}
-- icons
use "onsails/lspkind-nvim" -- Icons for completions
-- snippets
use "L3MON4D3/LuaSnip"
use {
"saadparwaiz1/cmp_luasnip", -- snippet completions
}
use "rafamadriz/friendly-snippets"
-- documentation
use {
"kkoomen/vim-doge", -- generates documentation skeletons
run = ":call doge#install()",
opt = true,
cmd = { "DogeGenerate", "DogeCreateDocStandard" },
}
-- Brackets
use "windwp/nvim-autopairs"
---- Keybindings
use "folke/which-key.nvim"
use { "jdhao/better-escape.vim", event = "InsertEnter" }
-- Commenting
use {
"numToStr/Comment.nvim", -- Smart powerful commenting framework
}
---- Git
use "tpope/vim-fugitive" -- The premier vim plugin for Git
use "TimUntersberger/neogit"
use {
"pwntester/octo.nvim", -- Edit GitHub issues and pull requests
config = function()
require("octo").setup()
end,
cmd = { "Octo" },
}
use "lewis6991/gitsigns.nvim"
-- git diffs
use {
"sindrets/diffview.nvim", -- Diffview functionality similar to vscode
cmd = { "DiffviewOpen", "DiffviewFileHistory" },
}
---- Motions, windows and navigation
use "ggandor/lightspeed.nvim"
use "mfussenegger/nvim-ts-hint-textobject"
use "edluffy/specs.nvim"
use "tpope/vim-repeat"
use "tpope/vim-unimpaired"
use "tpope/vim-surround"
use "michaeljsmith/vim-indent-object"
use "nvim-treesitter/nvim-treesitter-textobjects"
use {
"mizlan/iswap.nvim", -- Interactively swap treesitter elements
opt = true,
cmd = { "ISwap", "ISwapWith" },
}
-- Search
use "tpope/vim-abolish"
use "windwp/nvim-spectre"
use {
"kevinhwang91/nvim-hlslens",
config = function()
require("hlslens").setup()
end,
}
-- Peek
use {
"nacro90/numb.nvim",
config = function()
require("numb").setup()
end,
}
-- Marks
use {
"chentau/marks.nvim",
config = function()
require("marks").setup {}
end,
}
-- Window management
use "famiu/bufdelete.nvim"
-- Terminals
use "akinsho/toggleterm.nvim"
-- Awesome + Neovim + TMUX Navigation
use "intrntbrn/awesomewm-vim-tmux-navigator"
---- Language specific
-- LaTeX
-- TODO: LaTeX support with vimtex(?)
-- Python
use {
"untitled-ai/jupyter_ascending.vim", -- Edit jupytext file and keep it in syc with .ipynb
opt = true,
ft = { "python" },
}
---- Themes and eye candy
use "folke/tokyonight.nvim"
use "EdenEast/nightfox.nvim"
use {
"norcalli/nvim-colorizer.lua",
config = function()
require("colorizer").setup()
end,
}
-- Smooth buffer change when opening quick et al.
use {
"luukvbaal/stabilize.nvim",
config = function()
require("stabilize").setup()
end,
}
-- Highlight current mode in cursorline
use {
"mvllow/modes.nvim",
event = "BufRead",
config = function()
vim.opt.cursorline = true
require("modes").setup()
end,
}
-- Smooth scrolling
use {
"karb94/neoscroll.nvim",
config = function()
require("neoscroll").setup()
require("telescope").load_extension "neoclip"
end,
}
use "tpope/vim-sleuth" -- Automatically adjust shiftwidth and expandtab
-- Highlights
-- Show registers
use "tversteeg/registers.nvim"
-- Clipboard
use {
"AckslD/nvim-neoclip.lua", -- Clipboard manager inspired by clipmenu
config = function()
require("neoclip").setup()
end,
}
-- Tabline
use "akinsho/bufferline.nvim"
-- Statusline
use "nvim-lualine/lualine.nvim"
use {
"SmiteshP/nvim-gps",
config = function()
require("nvim-gps").setup()
end,
}
-- Dashboard
use {
"goolord/alpha-nvim", -- A fast framework for making a greeter
config = function()
require("alpha").setup(require("alpha.themes.dashboard").opts)
end,
}
-- Files and explorer
use {
"kyazdani42/nvim-tree.lua",
config = function()
require("nvim-tree").setup {}
end,
}
use "kyazdani42/nvim-web-devicons"
-- Indentation
use "lukas-reineke/indent-blankline.nvim"
-- Zen mode
use {
"folke/twilight.nvim",
config = function()
require("twilight").setup {}
end,
}
use {
"Pocco81/TrueZen.nvim",
config = function()
require("true-zen").setup()
end,
cmd = { "TZMinimalist", "TZFocus", "TZAtaraxis" },
}
---- Remote editing
-- FIXME: :DistantInstall throws an error
use {
"chipsenkbeil/distant.nvim", -- Edit remote files using local environment
config = function()
require("distant").setup {
-- Applies Chip"s personal settings to every machine you connect to
-- 1. Ensures that distant servers terminate with no connections
-- 2. Provides navigation bindings for remote directories
-- 3. Provides keybinding to jump into a remote file"s parent directory
["*"] = require("distant.settings").chip_default(),
}
end,
cmd = { "DistantRun", "DistantOpen", "DistantConnet", "DistantLaunch" },
}
---- Code execution
-- FIXME: Had to manually run "install.sh", wait for update
use {
"michaelb/sniprun",
run = "bash ./install.sh",
cmd = { "SnipRun", "SnipInfo" },
}
use {
"rcarriga/vim-ultest", -- Runs tests
requires = { "vim-test/vim-test" },
run = ":UpdateRemotePlugins",
cmd = { "Ultest", "UltestLast", "UltestAttach", "UltestSummary" },
}
---- Note taking
-- NOTE: Might consider replacing this with telekasten.nvim
use "oberblastmeister/neuron.nvim"
-- Markdown preview
use {
"iamcco/markdown-preview.nvim",
run = "cd app && yarn install",
ft = "markdown",
cmd = { "MarkdownPreview" },
}
use { "ellisonleao/glow.nvim", cmd = "Glow" }
-- TODOS
use {
"folke/todo-comments.nvim", -- Highlight and list TODOs in your files
requires = "nvim-lua/plenary.nvim",
config = function()
require("todo-comments").setup {}
end,
}
-- org-mode
use {
"nvim-orgmode/orgmode",
config = function()
require("orgmode").setup {}
end,
}
---- Miscellaneous
use "wakatime/vim-wakatime"
use "gpanders/editorconfig.nvim"
use {
"RishabhRD/nvim-cheat.sh", -- Query cht.sh from nevim
opt = true,
requires = { "RishabhRD/popfix" },
cmd = { "Cheat", "CheatList", "CheatWithoutComments", "CheatListWithoutComments" },
}
-- Automatically set up your configuration after cloning packer.nvim
-- Put this at the end after all plugins
if PACKER_BOOTSTRAP then
require("packer").sync()
end
end)
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:27' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
--Gamepad fragments
local ALWAYS_ANIMATE = true
-- Quadrant System Gamepad Grid Backgrounds: DO NOT BLOAT! --
GAMEPAD_NAV_QUADRANT_1_BACKGROUND_FRAGMENT = ZO_TranslateFromLeftSceneFragment:New(ZO_SharedGamepadNavQuadrant_1_Background)
ZO_BackgroundFragment:Mixin(GAMEPAD_NAV_QUADRANT_1_BACKGROUND_FRAGMENT)
GAMEPAD_NAV_QUADRANT_1_INSTANT_BACKGROUND_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_SharedGamepadNavQuadrant_1_Background)
GAMEPAD_NAV_QUADRANT_2_BACKGROUND_FRAGMENT = ZO_FadeSceneFragment:New(ZO_SharedGamepadNavQuadrant_2_Background)
ZO_BackgroundFragment:Mixin(GAMEPAD_NAV_QUADRANT_2_BACKGROUND_FRAGMENT)
GAMEPAD_NAV_QUADRANT_1_2_BACKGROUND_FRAGMENT = ZO_TranslateFromLeftSceneFragment:New(ZO_SharedGamepadNavQuadrant_1_2_Background)
ZO_BackgroundFragment:Mixin(GAMEPAD_NAV_QUADRANT_1_2_BACKGROUND_FRAGMENT)
GAMEPAD_NAV_QUADRANT_4_BACKGROUND_FRAGMENT = ZO_FadeSceneFragment:New(ZO_SharedGamepadNavQuadrant_4_Background)
ZO_BackgroundFragment:Mixin(GAMEPAD_NAV_QUADRANT_4_BACKGROUND_FRAGMENT)
GAMEPAD_NAV_QUADRANT_2_3_BACKGROUND_FRAGMENT = ZO_FadeSceneFragment:New(ZO_SharedGamepadNavQuadrant_2_3_Background, ALWAYS_ANIMATE)
ZO_BackgroundFragment:Mixin(GAMEPAD_NAV_QUADRANT_2_3_BACKGROUND_FRAGMENT)
GAMEPAD_NAV_QUADRANT_2_3_4_BACKGROUND_FRAGMENT = ZO_FadeSceneFragment:New(ZO_SharedGamepadNavQuadrant_2_3_4_Background, ALWAYS_ANIMATE)
GAMEPAD_NAV_QUADRANT_1_2_3_BACKGROUND_FRAGMENT = ZO_TranslateFromLeftSceneFragment:New(ZO_SharedGamepadNavQuadrant_1_2_3_Background)
-- END Quadrant System Gamepad Grid Backgrounds: DO NOT BLOAT! --
GAMEPAD_NAV_QUADRANT_2_3_FURNITURE_ITEM_PREVIEW_OPTIONS_FRAGMENT = ZO_ItemPreviewOptionsFragment:New({
paddingLeft = ZO_GAMEPAD_PANEL_WIDTH + ZO_GAMEPAD_SAFE_ZONE_INSET_X,
paddingRight = ZO_GAMEPAD_PANEL_WIDTH + ZO_GAMEPAD_SAFE_ZONE_INSET_X,
dynamicFramingConsumedWidth = ZO_GAMEPAD_PANEL_WIDTH + ZO_GAMEPAD_SAFE_ZONE_INSET_X,
dynamicFramingConsumedHeight = 400,
forcePreparePreview = false,
previewInEmptyWorld = true,
previewBufferMS = 300
})
GAMEPAD_NAV_QUADRANT_2_3_4_FURNITURE_ITEM_PREVIEW_OPTIONS_FRAGMENT = ZO_ItemPreviewOptionsFragment:New({
paddingLeft = ZO_GAMEPAD_PANEL_WIDTH + ZO_GAMEPAD_SAFE_ZONE_INSET_X,
paddingRight = ZO_GAMEPAD_SAFE_ZONE_INSET_X,
dynamicFramingConsumedWidth = ZO_GAMEPAD_UI_REFERENCE_WIDTH - ZO_GAMEPAD_PANEL_WIDTH - (ZO_GAMEPAD_SAFE_ZONE_INSET_X * 2),
dynamicFramingConsumedHeight = 400,
forcePreparePreview = false,
previewInEmptyWorld = true,
previewBufferMS = 300
})
GAMEPAD_NAV_QUADRANT_3_4_ITEM_PREVIEW_OPTIONS_FRAGMENT = ZO_ItemPreviewOptionsFragment:New({
paddingLeft = (ZO_GAMEPAD_PANEL_WIDTH * 2) + ZO_GAMEPAD_SAFE_ZONE_INSET_X,
paddingRight = ZO_GAMEPAD_SAFE_ZONE_INSET_X,
dynamicFramingConsumedWidth = ZO_GAMEPAD_UI_REFERENCE_WIDTH - (ZO_GAMEPAD_PANEL_WIDTH * 2) - (ZO_GAMEPAD_SAFE_ZONE_INSET_X * 2),
dynamicFramingConsumedHeight = 400,
forcePreparePreview = false,
previewBufferMS = 300,
})
GAMEPAD_NAV_QUADRANT_2_3_4_ITEM_PREVIEW_OPTIONS_FRAGMENT = ZO_ItemPreviewOptionsFragment:New({
paddingLeft = ZO_GAMEPAD_PANEL_WIDTH + ZO_GAMEPAD_SAFE_ZONE_INSET_X,
paddingRight = 0,
dynamicFramingConsumedWidth = 1150,
dynamicFramingConsumedHeight = 400,
forcePreparePreview = false,
previewBufferMS = 300
})
GAMEPAD_RIGHT_TOOLTIP_ITEM_PREVIEW_OPTIONS_FRAGMENT = ZO_ItemPreviewOptionsFragment:New({
paddingLeft = 0,
paddingRight = ZO_GAMEPAD_PANEL_WIDTH + ZO_GAMEPAD_SAFE_ZONE_INSET_X,
dynamicFramingConsumedWidth = 700,
dynamicFramingConsumedHeight = 400,
})
GAMEPAD_COLLECTIONS_ITEM_PREVIEW_OPTIONS_FRAGMENT = ZO_ItemPreviewOptionsFragment:New({
paddingLeft = ZO_GAMEPAD_PANEL_WIDTH + ZO_GAMEPAD_SAFE_ZONE_INSET_X,
paddingRight = 0,
dynamicFramingConsumedWidth = 1150,
dynamicFramingConsumedHeight = 400,
forcePreparePreview = false,
previewBufferMS = 300,
})
local ZO_Gamepad_GuildNameFooterFragment = ZO_FadeSceneFragment:Subclass()
function ZO_Gamepad_GuildNameFooterFragment:New(...)
return ZO_FadeSceneFragment.New(self, ...)
end
function ZO_Gamepad_GuildNameFooterFragment:Initialize(...)
ZO_FadeSceneFragment.Initialize(self, ...)
self.guildName = nil
self.guildNameControl = self.control:GetNamedChild("GuildName")
end
function ZO_Gamepad_GuildNameFooterFragment:SetGuildName(guildName)
self.guildName = guildName
self.guildNameControl:SetText(guildName)
end
function ZO_Gamepad_GuildNameFooterFragment:Show()
ZO_FadeSceneFragment.Show(self)
end
ZO_GUILD_NAME_FOOTER_FRAGMENT = ZO_Gamepad_GuildNameFooterFragment:New(ZO_Gamepad_GuildNameFooter)
OPTIONS_MENU_INFO_PANEL_FRAGMENT = ZO_FadeSceneFragment:New(ZO_GamepadOptionsTopLevelInfoPanel)
GAMEPAD_COLLECTIONS_BOOK_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_GamepadCollections)
GAMEPAD_COLLECTIONS_BOOK_FRAGMENT:SetHideOnSceneHidden(true)
GAMEPAD_COLLECTIONS_BOOK_DLC_PANEL_FRAGMENT = ZO_FadeSceneFragment:New(ZO_GamepadCollectionsDLCPanel, true)
GAMEPAD_COLLECTIONS_BOOK_HOUSING_PANEL_FRAGMENT = ZO_FadeSceneFragment:New(ZO_GamepadCollectionsHousingPanel, true)
GAMEPAD_COLLECTIONS_BOOK_GRID_LIST_PANEL_FRAGMENT = ZO_FadeSceneFragment:New(ZO_GamepadCollectionsGridListPanel, true)
GAMEPAD_ACTIVITY_FINDER_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_ActivityFinderRoot_Gamepad)
GAMEPAD_ACTIVITY_FINDER_FRAGMENT:SetHideOnSceneHidden(true)
GAMEPAD_HOUSING_FURNITURE_BROWSER_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_HousingFurnitureBrowser_GamepadTopLevel)
GAMEPAD_ALCHEMY_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_GamepadAlchemyTopLevel)
GAMEPAD_ALCHEMY_FRAGMENT:SetHideOnSceneHidden(true)
GAMEPAD_ALCHEMY_MODE_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_GamepadAlchemyTopLevelContainerMode)
GAMEPAD_ALCHEMY_INVENTORY_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_GamepadAlchemyTopLevelContainerInventory)
GAMEPAD_ALCHEMY_SLOTS_FRAGMENT = ZO_FadeSceneFragment:New(ZO_GamepadAlchemyTopLevelSlotContainer)
GAMEPAD_QUICKSLOT_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_GamepadQuickslotToplevel)
GAMEPAD_QUICKSLOT_FRAGMENT:SetHideOnSceneHidden(true)
GAMEPAD_QUICKSLOT_SELECTED_TOOLTIP_FRAGMENT = ZO_FadeSceneFragment:New(ZO_GamepadQuickslotToplevelSelectedTooltipContainer)
GAMEPAD_GUILD_HUB_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_GamepadGuildHubTopLevel)
GAMEPAD_GUILD_HUB_FRAGMENT:SetHideOnSceneHidden(true)
GAMEPAD_GUILD_HOME_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_GamepadGuildHomeTopLevel)
GAMEPAD_GUILD_HOME_FRAGMENT:SetHideOnSceneHidden(true)
GAMEPAD_RESTYLE_FRAGMENT = ZO_FadeSceneFragment:New(ZO_RestyleTopLevel_Gamepad)
GAMEPAD_RESTYLE_ROOT_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_RestyleTopLevel_GamepadMaskContainer)
GAMEPAD_RESTYLE_DYEING_PANEL_FRAGMENT = ZO_FadeSceneFragment:New(ZO_RestyleTopLevel_GamepadDyePanel)
GAMEPAD_INVENTORY_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_GamepadInventoryTopLevel)
GAMEPAD_INVENTORY_FRAGMENT:SetHideOnSceneHidden(true)
GAMEPAD_EMOTES_FRAGMENT = ZO_FadeSceneFragment:New(ZO_GamepadPlayerEmoteTopLevel)
GAMEPAD_ENCHANTING_FRAGMENT = ZO_FadeSceneFragment:New(ZO_GamepadEnchantingTopLevel)
GAMEPAD_ENCHANTING_MODE_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_GamepadEnchantingTopLevelContainerMode)
GAMEPAD_ENCHANTING_INVENTORY_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_GamepadEnchantingTopLevelContainerInventory)
GAMEPAD_SKILLS_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_GamepadSkillsTopLevel)
GAMEPAD_SKILLS_FRAGMENT:SetHideOnSceneHidden(true)
GAMEPAD_QUEST_JOURNAL_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_QuestJournal_GamepadTopLevel)
GAMEPAD_QUEST_JOURNAL_FRAGMENT:SetHideOnSceneHidden(true)
GAMEPAD_LEADERBOARDS_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_Leaderboards_Gamepad)
GAMEPAD_LEADERBOARDS_FRAGMENT:SetHideOnSceneHidden(true)
GAMEPAD_LEADERBOARDS_LIST_FRAGMENT = ZO_FadeSceneFragment:New(ZO_LeaderboardList_Gamepad)
GAMEPAD_SMITHING_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_GamepadSmithingTopLevel)
GAMEPAD_SMITHING_FRAGMENT:SetHideOnSceneHidden(true)
GAMEPAD_SMITHING_MODE_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_GamepadSmithingTopLevelMaskContainer)
GAMEPAD_SMITHING_REFINE_INVENTORY_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_GamepadSmithingTopLevelMaskRefinementInventory)
GAMEPAD_SMITHING_REFINE_FLOATING_FRAGMENT = ZO_FadeSceneFragment:New(ZO_GamepadSmithingTopLevelRefinement)
GAMEPAD_SMITHING_DECONSTRUCT_INVENTORY_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_GamepadSmithingTopLevelMaskDeconstructionInventory)
GAMEPAD_SMITHING_DECONSTRUCT_FLOATING_FRAGMENT = ZO_FadeSceneFragment:New(ZO_GamepadSmithingTopLevelDeconstruction)
GAMEPAD_SMITHING_CREATION_CREATE_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_GamepadSmithingTopLevelMaskCreationCreate)
GAMEPAD_SMITHING_CREATION_FLOATING_FRAGMENT = ZO_FadeSceneFragment:New(ZO_GamepadSmithingTopLevelCreation)
GAMEPAD_SMITHING_IMPROVEMENT_INVENTORY_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_GamepadSmithingTopLevelMaskImprovementInventory)
GAMEPAD_SMITHING_IMPROVEMENT_FLOATING_FRAGMENT = ZO_FadeSceneFragment:New(ZO_GamepadSmithingTopLevelImprovement)
GAMEPAD_SMITHING_RESEARCH_RESEARCH_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_GamepadSmithingTopLevelMaskResearchResearch)
GAMEPAD_SMITHING_RESEARCH_CONFIRM_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_GamepadSmithingTopLevelMaskResearchConfirm)
GAMEPAD_LORE_LIBRARY_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_Gamepad_LoreLibrary)
GAMEPAD_LORE_LIBRARY_FRAGMENT:SetHideOnSceneHidden(true)
GAMEPAD_BOOK_SET_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_Gamepad_BookSet)
GAMEPAD_BOOK_SET_FRAGMENT:SetHideOnSceneHidden(true)
GAMEPAD_LOOT_PICKUP_FRAGMENT = ZO_FadeSceneFragment:New(ZO_Gamepad_LootPickup, GAMEPAD_GRID_NAV2)
GAMEPAD_LOOT_INVENTORY_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_Gamepad_LootInventory)
GAMEPAD_ACHIEVEMENTS_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_Gamepad_Achievements)
GAMEPAD_ACHIEVEMENTS_FRAGMENT:SetHideOnSceneHidden(true)
GAMEPAD_ACHIEVEMENTS_FOOTER_FRAGMENT = ZO_FadeSceneFragment:New(ZO_Gamepad_Achievements_FooterBar)
GAMEPAD_CADWELL_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_Gamepad_Cadwell)
GAMEPAD_CADWELL_FRAGMENT:SetHideOnSceneHidden(true)
GAMEPAD_REPAIR_KITS_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_Gamepad_RepairKits)
GAMEPAD_APPLY_ENCHANT_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_Gamepad_ApplyEnchant)
GAMEPAD_SOUL_GEM_ITEM_CHARGER_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_Gamepad_SoulGemItemCharger)
GAMEPAD_MAIL_MANAGER_FRAGMENT = ZO_FadeSceneFragment:New(ZO_MailManager_Gamepad)
GAMEPAD_AVA_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_CampaignBrowser_GamepadTopLevel)
GAMEPAD_AVA_FRAGMENT:SetHideOnSceneHidden(true)
GAMEPAD_AVA_CAMPAIGN_INFO_FRAGMENT = ZO_FadeSceneFragment:New(ZO_CampaignBrowser_GamepadTopLevelCampaignInfo)
GAMPEAD_AVA_RANK_FRAGMENT = ZO_FadeSceneFragment:New(ZO_CampaignBrowser_GamepadTopLevelAvaRankFooter)
GAMEPAD_GROUP_MENU_FRAGMENT = ZO_FadeSceneFragment:New(ZO_GroupMenuGamepad)
GAMEPAD_GROUP_LFG_OPTIONS_FRAGMENT = ZO_FadeSceneFragment:New(ZO_GroupRoleMenu_Gamepad)
GAMEPAD_GROUP_LIST_FRAGMENT = ZO_FadeSceneFragment:New(ZO_GroupMenuGamepadGroupList)
GAMEPAD_GROUP_MEMBERS_FRAGMENT = ZO_FadeSceneFragment:New(ZO_GroupMembers_Gamepad)
GAMEPAD_GROUPING_TOOLS_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_GroupingToolsGamepad)
GAMEPAD_GROUPING_TOOLS_LOCATION_INFO_FRAGMENT = ZO_FadeSceneFragment:New(ZO_GroupingToolsGamepadLocationInfo)
GAMEPAD_BUY_BAG_SPACE_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_GamepadBuyBagSpaceTopLevel)
GAMEPAD_BUY_BANK_SPACE_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_GamepadBankingBuyBankSpaceTopLevel)
GAMEPAD_BANKING_WITHDRAW_DEPOSIT_GOLD_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_GamepadBankingWithdrawDepositGoldTopLevel)
GAMEPAD_NOTIFICATIONS_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_GamepadNotifications)
GAMEPAD_NOTIFICATIONS_FRAGMENT:SetHideOnSceneHidden(true)
GAMEPAD_PROVISIONER_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_GamepadProvisionerTopLevel)
GAMEPAD_PROVISIONER_FRAGMENT:SetHideOnSceneHidden(true)
GAMEPAD_PROVISIONER_RECIPELIST_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_GamepadProvisionerTopLevelContainerRecipe)
GAMEPAD_PROVISIONER_OPTIONS_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_GamepadProvisionerTopLevelContainerOptions)
GAMEPAD_VENDOR_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_StoreWindow_Gamepad)
GAMEPAD_FENCE_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_FenceWindow_Gamepad)
GAMEPAD_BANKING_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_GamepadBankingTopLevel)
GAMEPAD_GUILD_BANK_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_GuildBankTopLevel_Gamepad)
GAMEPAD_GUILD_BANK_FRAGMENT:SetHideOnSceneHidden(true)
GAMEPAD_GUILD_BANK_WITHDRAW_DEPOSIT_GOLD_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_GuildBankWithdrawDepositGoldTopLevel_Gamepad)
GAMEPAD_GUILD_KIOSK_PURCHASE_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_Gamepad_GuildKiosk_Purchase)
GAMEPAD_GUILD_KIOSK_BID_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_Gamepad_GuildKiosk_Bid)
GAMEPAD_TRADING_HOUSE_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_TradingHouse_Gamepad)
GAMEPAD_TRADING_HOUSE_FRAGMENT:SetHideOnSceneHidden(true)
GAMEPAD_TRADING_HOUSE_CREATE_LISTING_ROOT_FRAGMENT = ZO_FadeSceneFragment:New(ZO_TradingHouse_CreateListing_Gamepad)
GAMEPAD_TRADING_HOUSE_CREATE_LISTING_LIST_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_TradingHouse_CreateListing_GamepadMaskContainer)
GAMEPAD_RESTYLE_STATION_LIST_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_RestyleStation_Gamepad_TLMaskContainer)
GAMEPAD_OUTFITS_SELECTOR_ROOT_FRAGMENT = ZO_CreateQuadrantConveyorFragment(ZO_Outfits_Selector_GamepadMaskContainer)
GAMEPAD_ZONE_STORIES_FRAGMENT = ZO_SimpleSceneFragment:New(ZO_ZoneStoriesTopLevel_Gamepad)
GAMEPAD_ZONE_STORIES_FRAGMENT:SetHideOnSceneHidden(true)
|
--[[
Copyright 2014-2015 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local normalize = require('semver').normalize
local gte = require('semver').gte
local log = require('log').log
local queryDb = require('pkg').queryDb
local colorize = require('pretty-print').colorize
return function (db, deps, newDeps)
local addDep, processDeps
function processDeps(dependencies)
if not dependencies then return end
for alias, dep in pairs(dependencies) do
local name, version = dep:match("^([^@]+)@?(.*)$")
if #version == 0 then
version = nil
end
if type(alias) == "number" then
alias = name:match("([^/]+)$")
end
if not name:find("/") then
error("Package names must include owner/name at a minimum")
end
if version then
local ok
ok, version = pcall(normalize, version)
if not ok then
error("Invalid dependency version: " .. dep)
end
end
addDep(alias, name, version)
end
end
function addDep(alias, name, version)
local meta = deps[alias]
if meta then
if name ~= meta.name then
local message = string.format("%s %s ~= %s",
alias, meta.name, name)
log("alias conflict", message, "failure")
return
end
if version then
if not gte(meta.version, version) then
local message = string.format("%s %s ~= %s",
alias, meta.version, version)
log("version conflict", message, "failure")
return
end
end
else
local author, pname = name:match("^([^/]+)/(.*)$")
local match, hash = db.match(author, pname, version)
if not match then
error("No such "
.. (version and "version" or "package") .. ": "
.. name
.. (version and '@' .. version or ''))
end
local kind
meta, kind, hash = assert(queryDb(db, hash))
meta.db = db
meta.hash = hash
meta.kind = kind
deps[alias] = meta
end
processDeps(meta.dependencies)
end
processDeps(newDeps)
local names = {}
for k in pairs(deps) do
names[#names + 1] = k
end
table.sort(names)
for i = 1, #names do
local name = names[i]
local meta = deps[name]
log("including dependency", string.format("%s (%s)",
colorize("highlight", name), meta.path or meta.version))
end
return deps
end
|
local win = am.window{
clear_color = vec4(0.1, 0.03, 0.01, 1),
letterbox = false,
}
win.scene = am.blend("add_alpha")
^ am.particles2d{
source_pos = win:mouse_position(),
source_pos_var = vec2(20),
max_particles = 1000,
emission_rate = 500,
start_particles = 0,
life = 0.4,
life_var = 0.1,
angle = math.rad(90),
angle_var = math.rad(180),
speed = 200,
start_color = vec4(1, 0.3, 0.01, 0.5),
start_color_var = vec4(0.1, 0.05, 0.0, 0.1),
end_color = vec4(0.5, 0.8, 1, 1),
end_color_var = vec4(0.1),
start_size = 30,
start_size_var = 10,
end_size = 2,
end_size_var = 2,
gravity = vec2(0, 2000),
}
:action(function(node)
node.source_pos = win:mouse_position()
end)
win.scene:action(am.tween(win.scene"particles2d", 10, {gravity = vec2(0, -2000)}))
|
-- PseudoInstance to spawn Material Design Ripples inside its Parent (with rounded edge support!)
-- @author Validark
local ContentProvider = game:GetService("ContentProvider")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Resources = require(ReplicatedStorage:WaitForChild("Resources"))
local Debug = Resources:LoadLibrary("Debug")
local Tween = Resources:LoadLibrary("Tween")
local Color = Resources:LoadLibrary("Color")
local Typer = Resources:LoadLibrary("Typer")
local Janitor = Resources:LoadLibrary("Janitor")
local Enumeration = Resources:LoadLibrary("Enumeration")
local PseudoInstance = Resources:LoadLibrary("PseudoInstance")
local RIPPLE_START_DIAMETER = 0
local RIPPLE_OVERBITE = 1.05
local RippleContainer = Instance.new("Frame") -- Make sure ZIndex is higher than parent by 1
RippleContainer.AnchorPoint = Vector2.new(0.5, 0.5)
RippleContainer.BackgroundTransparency = 1
RippleContainer.BorderSizePixel = 0
RippleContainer.ClipsDescendants = true
RippleContainer.Name = "RippleContainer"
RippleContainer.Size = UDim2.new(1, 0, 1, 0)
RippleContainer.Position = UDim2.new(0.5, 0, 0.5, 0)
local RippleStartSize = UDim2.new(0, RIPPLE_START_DIAMETER, 0, RIPPLE_START_DIAMETER)
local Circle = Instance.new("ImageLabel")
Circle.AnchorPoint = Vector2.new(0.5, 0.5)
Circle.BackgroundTransparency = 1
Circle.Size = RippleStartSize
Circle.Image = "rbxassetid://517259585"
Circle.Name = "Ripple"
spawn(function()
ContentProvider:PreloadAsync{Circle.Image}
end)
local Deceleration = Enumeration.EasingFunction.Deceleration.Value
Enumeration.RipplerStyle = {"Full", "Icon", "Round"}
local CornerData = {
[2] = {
0.380, 0.918,
0.918, 1.000,
};
[4] = {
0.000, 0.200, 0.690, 0.965,
0.200, 0.965, 1.000, 1.000,
0.690, 1.000, 1.000, 1.000,
0.965, 1.000, 1.000, 1.000,
};
[8] = {
0.000, 0.000, 0.000, 0.000, 0.224, 0.596, 0.851, 0.984,
0.000, 0.000, 0.000, 0.596, 1.000, 1.000, 1.000, 1.000,
0.000, 0.000, 0.722, 1.000, 1.000, 1.000, 1.000, 1.000,
0.000, 0.596, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000,
0.224, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000,
0.596, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000,
0.851, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000,
0.984, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000, 1.000,
};
}
do
local t = {
Radius0 = 0;
}
for BorderRadius, Data in next, CornerData do
t["Radius" .. BorderRadius] = BorderRadius
for i = 1, #Data do
Data[i] = 1 - Data[i] -- Opacity -> Transparency
end
end
Enumeration.BorderRadius = t
end
local function MakeContainer(GlobalContainer, Size, Position, ImageTransparency)
local Container = Instance.new("ImageLabel")
if ImageTransparency ~= nil and ImageTransparency ~= 0 then
Container.ImageTransparency = ImageTransparency
end
Container.BackgroundTransparency = 1
Container.ClipsDescendants = true
Container.Position = Position
Container.Size = Size
Container.Parent = GlobalContainer
return Container
end
local function MakeOuterBorders(RippleFrames, Container, X, Y) -- TODO: Optimize first two frames which can be eliminated
local NumRippleFrames = #RippleFrames
RippleFrames[NumRippleFrames + 1] = MakeContainer(Container, UDim2.new(1, -2*X, 0, 1), UDim2.new(0, X, 0, Y))
RippleFrames[NumRippleFrames + 2] = MakeContainer(Container, UDim2.new(1, -2*X, 0, 1), UDim2.new(0, X, 1, -Y - 1))
RippleFrames[NumRippleFrames + 3] = MakeContainer(Container, UDim2.new(0, 1, 1, -2*X), UDim2.new(0, Y, 0, X))
RippleFrames[NumRippleFrames + 4] = MakeContainer(Container, UDim2.new(0, 1, 1, -2*X), UDim2.new(1, -Y - 1, 0, X))
end
local PixelSize = UDim2.new(0, 1, 0, 1)
local function DestroyRoundRipple(self)
for i = 1, #self do
local Object = self[i]
self[i] = nil
Object:Destroy()
end
end;
local RoundRippleMetatable = {
__index = function(self, i)
if i == "Size" then
return RippleStartSize
elseif i == "ImageTransparency" then
return self.Transparency
elseif i == "Destroy" then
return DestroyRoundRipple
end
end;
__newindex = function(self, i, v)
if i == "Size" then
for a = 1, #self do
self[a].Size = v
end
elseif i == "ImageTransparency" then
for a = 1, #self do
local RippleFrame = self[a]
local Parent = RippleFrame.Parent
if Parent then
RippleFrame.ImageTransparency = (1 - v) * Parent.ImageTransparency + v
end
end
end
end;
}
return PseudoInstance:Register("Rippler", {
Internals = {
"CurrentRipple", "RippleFrames";
SetCurrentRipple = function(self, Ripple)
if self.CurrentRipple then
Tween(self.CurrentRipple, "ImageTransparency", 1, Deceleration, self.RippleFadeDuration, false, true)
end
self.CurrentRipple = Ripple
end
};
Events = {};
Properties = {
Style = Typer.AssignSignature(2, Typer.EnumerationOfTypeRipplerStyle, function(self, Style)
self:rawset("Style", Style)
end);
BorderRadius = Typer.AssignSignature(2, Typer.EnumerationOfTypeBorderRadius, function(self, Value)
self:rawset("BorderRadius", Value)
local BorderRadius = Value.Value
local RippleFrames = self.RippleFrames
if RippleFrames then
DestroyRoundRipple(RippleFrames)
end
if BorderRadius == 0 then
self.Style = Enumeration.RipplerStyle.Full
else
self.Style = Enumeration.RipplerStyle.Round
local Data = CornerData[BorderRadius]
if not RippleFrames then
RippleFrames = {}
self.RippleFrames = RippleFrames
end
local MiddleSquarePoint
local Container = self.Container
for j = 0, BorderRadius - 1 do
if Data[BorderRadius * j + (j + 1)] == 0 then
MiddleSquarePoint = j
break
end
end
MakeOuterBorders(RippleFrames, Container, BorderRadius, 0)
-- Make large center frame
RippleFrames[#RippleFrames + 1] = MakeContainer(Container, UDim2.new(1, -2 * MiddleSquarePoint, 1, -2 * MiddleSquarePoint), UDim2.new(0, MiddleSquarePoint, 0, MiddleSquarePoint))
do -- Make other bars to fill
local X = MiddleSquarePoint
local Y = MiddleSquarePoint - 1
while Data[BorderRadius * Y + (X + 1)] == 0 do
MakeOuterBorders(RippleFrames, Container, X, Y)
X = X + 1
Y = Y - 1
end
end
do
local a = 0
local amax = BorderRadius * BorderRadius
local NumRippleFrames = #RippleFrames
while a < amax do
local PixelTransparency = Data[a + 1]
if PixelTransparency ~= 1 then
if PixelTransparency ~= 0 then
local X = a % BorderRadius
local Y = (a - X) / BorderRadius
local V = -1 - X
local W = -1 - Y
RippleFrames[NumRippleFrames + 1] = MakeContainer(Container, PixelSize, UDim2.new(0, X, 0, Y), PixelTransparency)
RippleFrames[NumRippleFrames + 2] = MakeContainer(Container, PixelSize, UDim2.new(0, X, 1, W), PixelTransparency)
RippleFrames[NumRippleFrames + 3] = MakeContainer(Container, PixelSize, UDim2.new(1, V, 0, Y), PixelTransparency)
RippleFrames[NumRippleFrames + 4] = MakeContainer(Container, PixelSize, UDim2.new(1, V, 1, W), PixelTransparency)
NumRippleFrames = NumRippleFrames + 4
end
end
a = a + 1
end
end
end
end);
RippleFadeDuration = Typer.Number;
MaxRippleDiameter = Typer.Number;
RippleExpandDuration = Typer.Number;
RippleColor3 = Typer.AssignSignature(2, Typer.Color3, function(self, RippleColor3)
if self.CurrentRipple then
self.CurrentRipple.ImageColor3 = RippleColor3
end
self:rawset("RippleColor3", RippleColor3)
end);
RippleTransparency = Typer.AssignSignature(2, Typer.Number, function(self, RippleTransparency)
if self.CurrentRipple then
self.CurrentRipple.ImageTransparency = RippleTransparency
end
self:rawset("RippleTransparency", RippleTransparency)
end);
Container = Typer.AssignSignature(2, Typer.InstanceWhichIsAGuiObject, function(self, Container)
if self.BorderRadius.Value ~= 0 then Debug.Error("Can only set container when BorderRadius is 0") end
self.Janitor:LinkToInstance(Container)
self.Janitor:Add(Container, "Destroy", "Container")
self:rawset("Container", Container)
end);
Parent = function(self, Parent) -- Manually check this one
if Parent == nil then
self.Janitor:Remove("ZIndexChanged")
self.Container.Parent = nil
else
local ParentType = typeof(Parent)
local IsGuiObject = ParentType == "Instance" and Parent:IsA("GuiObject") or ParentType == "userdata" and Parent.ClassName == "RoundedFrame"
if IsGuiObject and self.Container ~= Parent then
local function ZIndexChanged()
self.Container.ZIndex = Parent.ZIndex + 1
end
self.Janitor:Add(Parent:GetPropertyChangedSignal("ZIndex"):Connect(ZIndexChanged), "Disconnect", "ZIndexChanged")
ZIndexChanged()
self.Container.Parent = Parent
else
Debug.Error("bad argument #2 to Parent, expected GuiObject, got %s", Parent)
end
end
self:rawset("Parent", Parent)
end;
};
Methods = {
Down = Typer.AssignSignature(2, Typer.OptionalNumber, Typer.OptionalNumber, function(self, X, Y)
local Container = self.Container
local Diameter
local ContainerAbsoluteSizeX = Container.AbsoluteSize.X
local ContainerAbsoluteSizeY = Container.AbsoluteSize.Y
-- Get near corners
X = (X or (0.5 * ContainerAbsoluteSizeX + Container.AbsolutePosition.X)) - Container.AbsolutePosition.X
Y = (Y or (0.5 * ContainerAbsoluteSizeY + Container.AbsolutePosition.Y)) - Container.AbsolutePosition.Y
if self.Style == Enumeration.RipplerStyle.Icon then
Diameter = 2 * Container.AbsoluteSize.Y
self.Container.ClipsDescendants = false
else
-- Get far corners
local V = X - ContainerAbsoluteSizeX
local W = Y - ContainerAbsoluteSizeY
-- Calculate distance between mouse and corners
local a = (X*X + Y*Y) ^ 0.5
local b = (X*X + W*W) ^ 0.5
local c = (V*V + Y*Y) ^ 0.5
local d = (V*V + W*W) ^ 0.5
-- Find longest distance between mouse and a corner and decide Diameter
Diameter = 2 * (a > b and a > c and a > d and a or b > c and b > d and b or c > d and c or d) * RIPPLE_OVERBITE
-- Cap Diameter
if self.MaxRippleDiameter < Diameter then
Diameter = self.MaxRippleDiameter
end
end
-- Create Ripple Object
local Ripple = Circle:Clone()
Ripple.ImageColor3 = self.RippleColor3
Ripple.ImageTransparency = self.RippleTransparency
Ripple.Position = UDim2.new(0, X, 0, Y)
Ripple.ZIndex = Container.ZIndex + 1
Ripple.Parent = Container
if self.Style == Enumeration.RipplerStyle.Round and self.BorderRadius.Value ~= 0 then
local Ripples = {Transparency = Ripple.ImageTransparency}
local RippleFrames = self.RippleFrames
local NumRipples = #RippleFrames
for i = 1, NumRipples do
local RippleFrame = RippleFrames[i]
local NewRipple = Ripple:Clone()
local AbsolutePosition = Ripple.AbsolutePosition - RippleFrame.AbsolutePosition + 0.5*Ripple.AbsoluteSize
NewRipple.Position = UDim2.new(0, AbsolutePosition.X, 0, AbsolutePosition.Y)
NewRipple.ImageTransparency = (1 - self.RippleTransparency) * RippleFrame.ImageTransparency + self.RippleTransparency
NewRipple.Parent = RippleFrame
Ripples[i] = NewRipple
end
Ripple:Destroy()
Ripple = setmetatable(Ripples, RoundRippleMetatable)
end
self:SetCurrentRipple(Ripple)
return Tween(Ripple, "Size", UDim2.new(0, Diameter, 0, Diameter), Deceleration, self.RippleExpandDuration)
end);
Up = function(self)
self:SetCurrentRipple(false)
end;
Ripple = Typer.AssignSignature(2, Typer.OptionalNumber, Typer.OptionalNumber, Typer.OptionalNumber, function(self, X, Y, Duration)
self:Down(X, Y)
delay(Duration or 0.15, function()
self:SetCurrentRipple(false)
end)
end);
};
Init = function(self, Container)
self.Style = Enumeration.RipplerStyle.Full
self.BorderRadius = 0
self.Container = Container or RippleContainer:Clone()
self.RippleTransparency = 0.84
self.RippleColor3 = Color.White
self.MaxRippleDiameter = math.huge
self.RippleExpandDuration = 0.5
self.RippleFadeDuration = 1
self:superinit()
end;
})
|
local ts = require('vim.treesitter.query')
local ts_utils = require('nvim-treesitter.ts_utils')
local Promise = require('orgmode.utils.promise')
local uv = vim.loop
local utils = {}
local debounce_timers = {}
local query_cache = {}
---@param file string
---@param callback function
---@param as_string boolean
function utils.readfile(file, callback, as_string)
uv.fs_open(file, 'r', 438, function(err1, fd)
if err1 then
return callback(err1)
end
uv.fs_fstat(fd, function(err2, stat)
if err2 then
return callback(err2)
end
uv.fs_read(fd, stat.size, 0, function(err3, data)
if err3 then
return callback(err3)
end
uv.fs_close(fd, function(err4)
if err4 then
return callback(err4)
end
local lines = data
if not as_string then
lines = vim.split(data, '\n')
table.remove(lines, #lines)
end
return callback(nil, lines)
end)
end)
end)
end)
end
function utils.open(target)
if vim.fn.executable('xdg-open') then
return vim.fn.system(string.format('xdg-open %s', target))
end
if vim.fn.executable('open') then
return vim.fn.system(string.format('open %s', target))
end
if vim.fn.has('win32') then
return vim.fn.system(string.format('start "%s"', target))
end
end
---@param msg string
---@param additional_msg table
---@param store_in_history boolean
function utils.echo_warning(msg, additional_msg, store_in_history)
return utils._echo(msg, 'WarningMsg', additional_msg, store_in_history)
end
---@param msg string
---@param additional_msg table
---@param store_in_history boolean
function utils.echo_error(msg, additional_msg, store_in_history)
return utils._echo(msg, 'ErrorMsg', additional_msg, store_in_history)
end
---@param msg string
---@param additional_msg table
---@param store_in_history boolean
function utils.echo_info(msg, additional_msg, store_in_history)
return utils._echo(msg, nil, additional_msg, store_in_history)
end
---@private
function utils._echo(msg, hl, additional_msg, store_in_history)
vim.cmd([[redraw!]])
if type(msg) == 'table' then
msg = table.concat(msg, '\n')
end
local msg_item = { string.format('[orgmode] %s', msg) }
if hl then
table.insert(msg_item, hl)
end
local msg_list = { msg_item }
if additional_msg then
msg_list = utils.concat(msg_list, additional_msg)
end
local store = true
if type(store_in_history) == 'boolean' then
store = store_in_history
end
return vim.api.nvim_echo(msg_list, store, {})
end
---@param word string
---@return string
function utils.capitalize(word)
return (word:gsub('^%l', string.upper))
end
---@param isoweekday number
---@return number
function utils.convert_from_isoweekday(isoweekday)
if isoweekday == 7 then
return 1
end
return isoweekday + 1
end
---@param weekday number
---@return number
function utils.convert_to_isoweekday(weekday)
if weekday == 1 then
return 7
end
return weekday - 1
end
---@param tbl table
---@param callback function
---@param acc any
---@return table
function utils.reduce(tbl, callback, acc)
for i, v in pairs(tbl) do
acc = callback(acc, v, i)
end
return acc
end
--- Concat one table at the end of another table
---@param first table
---@param second table
---@param unique boolean
---@return table
function utils.concat(first, second, unique)
for _, v in ipairs(second) do
if not unique or not vim.tbl_contains(first, v) then
table.insert(first, v)
end
end
return first
end
function utils.menu(title, items, prompt)
local content = { title .. '\\n' .. string.rep('-', #title) }
local valid_keys = {}
for _, item in ipairs(items) do
if item.separator then
table.insert(content, string.rep(item.separator or '-', item.length or 80))
else
valid_keys[item.key] = item
table.insert(content, string.format('%s %s', item.key, item.label))
end
end
prompt = prompt or 'key'
table.insert(content, prompt .. ': ')
vim.cmd(string.format('echon "%s"', table.concat(content, '\\n')))
local char = vim.fn.nr2char(vim.fn.getchar())
vim.cmd([[redraw!]])
local entry = valid_keys[char]
if not entry or not entry.action then
return
end
return entry.action()
end
function utils.keymap(mode, lhs, rhs, opts)
return vim.api.nvim_set_keymap(
mode,
lhs,
rhs,
vim.tbl_extend('keep', opts or {}, {
nowait = true,
silent = true,
noremap = true,
})
)
end
function utils.buf_keymap(buf, mode, lhs, rhs, opts)
return vim.api.nvim_buf_set_keymap(
buf,
mode,
lhs,
rhs,
vim.tbl_extend('keep', opts or {}, {
nowait = true,
silent = true,
noremap = true,
})
)
end
function utils.esc(cmd)
return vim.api.nvim_replace_termcodes(cmd, true, false, true)
end
function utils.parse_tags_string(tags)
local parsed_tags = {}
for _, tag in ipairs(vim.split(tags or '', ':')) do
if tag:find('^[%w_%%@#]+$') then
table.insert(parsed_tags, tag)
end
end
return parsed_tags
end
function utils.tags_to_string(taglist)
local tags = ''
if #taglist > 0 then
tags = ':' .. table.concat(taglist, ':') .. ':'
end
return tags
end
function utils.ensure_array(val)
if type(val) ~= 'table' then
return { val }
end
return val
end
function utils.humanize_minutes(minutes)
if minutes == 0 then
return 'Now'
end
local is_past = minutes < 0
local minutes_abs = math.abs(minutes)
if minutes_abs < 60 then
if is_past then
return string.format('%d min ago', minutes_abs)
end
return string.format('in %d min', minutes_abs)
end
local hours = math.floor(minutes_abs / 60)
local remaining_minutes = minutes_abs - (hours * 60)
if remaining_minutes == 0 then
if is_past then
return string.format('%d hr ago', hours)
end
return string.format('in %d hr', hours)
end
if is_past then
return string.format('%d hr and %d min ago', hours, remaining_minutes)
end
return string.format('in %d hr and %d min', hours, remaining_minutes)
end
---@param query string
---@param node table
---@param file_content string[]
---@param file_content_str string
---@return table[]
function utils.get_ts_matches(query, node, file_content, file_content_str)
local matches = {}
local ts_query = query_cache[query]
if not ts_query then
ts_query = ts.parse_query('org', query)
query_cache[query] = ts_query
end
for _, match, _ in ts_query:iter_matches(node, file_content_str) do
local items = {}
for id, matched_node in pairs(match) do
local name = ts_query.captures[id]
local node_text = utils.get_node_text(matched_node, file_content)
items[name] = {
node = matched_node,
text_list = node_text,
text = node_text[1],
}
end
table.insert(matches, items)
end
return matches
end
---@param node userdata
---@param content string[]
---@return string[]
function utils.get_node_text(node, content)
if not node then
return {}
end
local start_row, start_col, end_row, end_col = node:range()
if start_row ~= end_row then
local start_line = start_row + 1
local end_line = end_row + 1
if end_col == 0 then
end_line = end_row
end
local range = end_line - start_line + 1
local lines = {}
if range < 5000 then
lines = { unpack(content, start_line, end_line) }
else
local chunks = math.floor(range / 5000)
local leftover = range % 5000
for i = 1, chunks do
lines = utils.concat(lines, { unpack(content, (i - 1) * 5000 + 1, i * 5000) })
end
if leftover > 0 then
local s = chunks * 5000
lines = utils.concat(lines, { unpack(content, s + 1, s + leftover) })
end
end
lines[1] = string.sub(lines[1], start_col + 1)
if end_col > 0 then
lines[#lines] = string.sub(lines[#lines], 1, end_col)
end
return lines
else
local line = content[start_row + 1]
-- If line is nil then the line is empty
return line and { string.sub(line, start_col + 1, end_col) } or {}
end
end
---@param node table
---@param type string
---@return table
function utils.get_closest_parent_of_type(node, type, accept_at_cursor)
local parent = node
if not accept_at_cursor then
parent = node:parent()
end
while parent do
if parent:type() == type then
return parent
end
parent = parent:parent()
end
end
function utils.debounce(name, fn, ms)
local result = nil
return function(...)
local argv = { ... }
if debounce_timers[name] then
debounce_timers[name]:stop()
debounce_timers[name]:close()
debounce_timers[name] = nil
end
local timer = uv.new_timer()
debounce_timers[name] = timer
timer:start(
ms,
0,
vim.schedule_wrap(function()
result = fn(unpack(argv))
end)
)
return result
end
end
---@param name string
---@return function
function utils.profile(name)
local start_time = os.clock()
return function()
return print(name, string.format('%.2f', os.clock() - start_time))
end
end
---@param arg_lead string
---@param list string[]
---@param split_chars string[]
---@return string[]
function utils.prompt_autocomplete(arg_lead, list, split_chars)
split_chars = split_chars or { '+', '-', ':', '&', '|' }
local split_chars_str = vim.pesc(table.concat(split_chars, ''))
local split_rgx = string.format('[%s]', split_chars_str)
local match_rgx = string.format('[^%s]*$', split_chars_str)
local parts = vim.split(arg_lead, split_rgx)
local base = arg_lead:gsub(match_rgx, '')
local last = arg_lead:match(match_rgx)
local matches = vim.tbl_filter(function(tag)
return tag:match('^' .. vim.pesc(last)) and not vim.tbl_contains(parts, tag)
end, list)
return vim.tbl_map(function(tag)
return base .. tag
end, matches)
end
---@param items table
function utils.choose(items)
items = items or {}
local output = {}
for _, item in ipairs(items) do
table.insert(output, { '[' })
table.insert(output, { item.choice_text, item.choice_hl or 'Normal' })
table.insert(output, { ']' })
if item.desc_text then
table.insert(output, { ' ' })
table.insert(output, { item.desc_text, item.desc_hl or 'Normal' })
end
table.insert(output, { ' ' })
end
table.insert(output, { '\n' })
vim.api.nvim_echo(output, true, {})
local raw = vim.fn.nr2char(vim.fn.getchar())
local char = string.lower(raw)
vim.cmd('redraw!')
for _, item in ipairs(items) do
if char == string.lower(item.choice_value) then
return { choice_value = item.choice_value, choice_text = item.choice_text, raw = raw, ctx = item.ctx }
end
end
end
---@param fn function
---@return Promise
function utils.promisify(fn)
if getmetatable(fn) ~= Promise then
return Promise.resolve(fn)
end
return fn
end
---@param file File
---@param parent_node userdata
---@param children_names string[]
---@return table
function utils.get_named_children_nodes(file, parent_node, children_names)
local child_node_info = {}
if children_names then
-- Only grab information for specific named children
for _, child_name in ipairs(children_names) do
children_names[child_name] = false
end
end
vim.tbl_map(function(node)
if not children_names or children_names[node:type()] ~= nil then
local text
local text_list = utils.get_node_text(node, file.file_content)
if #text_list == 0 then
text = ''
else
text = text_list[1]
end
child_node_info[node:type()] = {
node = node,
text = text,
text_list = text_list,
}
end
end, ts_utils.get_named_children(parent_node))
return child_node_info
end
---@param file File
---@param cursor string[]
---@param accept_at_cursor boolean
---@return nil|table
function utils.get_nearest_block_node(file, cursor, accept_at_cursor)
local current_node = file:get_node_at_cursor(cursor)
local block_node = utils.get_closest_parent_of_type(current_node, 'block', accept_at_cursor)
if not block_node then
return
end
-- Block might not have contents yet, which is fine
local children_nodes = file:get_ts_matches(
'(block name: (expr) @name parameter: (expr) @parameters contents: (contents)? @contents)',
block_node
)[1]
if not children_nodes or not children_nodes.name or not children_nodes.parameters then
return
end
return {
node = block_node,
children = children_nodes,
}
end
return utils
|
BaekNpc = {
click = async(function(player, npc)
local t = {
graphic = convertGraphic(npc.look, "monster"),
color = npc.lookColor
}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = npc.ID
local opts = {"Buy", "Sell"}
local menu = player:menuString("Hello! How can I help you today?", opts)
if menu == "Buy" then
player:buyExtend(
"I think I can accomodate some of the things you need. What would you like?",
BaekNpc.buyItems()
)
elseif menu == "Sell" then
player:sellExtend(
"What are you willing to sell today?",
BaekNpc.sellItems()
)
end
end),
buyItems = function()
local buyItems = {
"clear_water_song",
"sacred_poem",
"war_poem",
"moon_paper",
"legend"
}
return buyItems
end,
sellItems = function()
local sellItems = BaekNpc.buyItems()
if (Config.bossDropSalesEnabled) then
table.insert(sellItems, "chung_ryong_key")
table.insert(sellItems, "baekho_key")
table.insert(sellItems, "hyun_moo_key")
table.insert(sellItems, "ju_jak_key")
end
return sellItems
end,
onSayClick = async(function(player, npc)
local speech = string.lower(player.speech)
local baekDialog = Tools.configureDialog(player, npc)
if speech == "chung ryong" or speech == "baekho" or speech == "ju jak" or speech == "hyun moo" then
Tools.checkKarma(player)
if player.level < 99 then
player:dialogSeq(
{
baekDialog,
"You are too young to be changing your mind on such matters. Return later, and we can talk again."
},
0
)
return
end
if player.class >= 10 then
player:dialogSeq(
{
baekDialog,
"You cannot join an NPC subpath while you belong to a PC subpath."
},
0
)
return
end
if (not player:karmaCheck("ox") and not Config.freeNpcSubpathsEnabled) then
player:dialogSeq({baekDialog, "Come back when your karma is higher."}, 0)
return
end
if (player.quest["blessed_by_watcher"] == 0 and not Config.freeNpcSubpathsEnabled) then
-- not blessed
player:dialogSeq({baekDialog, "You have not been blessed."}, 0)
return
end
if (not player:hasLegend("dog_linguist") and not Config.freeNpcSubpathsEnabled) then
return
end
if player.class > 4 then
player:dialogSeq(
{baekDialog, "You have already committed to a subpath."},
0
)
return
end
-- only 4 basic paths
if speech == "chung ryong" and player.class ~= 1 then
return
end
if speech == "baekho" and player.class ~= 2 then
return
end
if speech == "ju jak" and player.class ~= 3 then
return
end
if speech == "hyun moo" and player.class ~= 4 then
return
end
player:dialogSeq(
{
baekDialog,
"Hmm... yes, I have studied the ways of the four totem animals. Do you wish to attain knowledge and power few mortals will know?",
"You must be committed to serve the totem animals. Should you choose this arduous path, you will NEVER be able to join a subpath.",
"To prove your devotion, you must make many sacrifices. First, you must bring to me a Favor from one of the Mythic animals.",
"Then you must bring me ten hides from the most dreaded of caves, where the exits are not easily found and the enemies hide in shadows.",
"Finally, you must sacrifice 1,000,000,000 experience to complete the most difficult studying involved."
},
1
)
local favors = {
"dragons_favor",
"roosters_favor",
"dogs_favor",
"horses_favor",
"monkeys_favor",
"oxs_favor",
"pigs_favor",
"rabbits_favor",
"rats_favor",
"sheeps_favor",
"snakes_favor",
"tigers_favor"
}
local favorFound = ""
for i = 1, #favors do
if player:hasItem(favors[i], 1) == true then
favorFound = favors[i]
end
end
if (favorFound == "" and not Config.freeNpcSubpathsEnabled) then
-- no favvor found
player:dialogSeq(
{
baekDialog,
"If you ally with a Mythic animal, they will give you Favor."
},
0
)
return
end
if (not Config.freeNpcSubpathsEnabled) then
player:removeItem(favorFound, 1, 9)
end
if (player:hasItem("splendid_tiger_pelt", 10) ~= true and not Config.freeNpcSubpathsEnabled) then
player:dialogSeq(
{
baekDialog,
"You have forgotten the hides! As punishment for failing to follow my instructions, you must now bring me another Favor as well."
},
0
)
return
end
if (not Config.freeNpcSubpathsEnabled) then
player:removeItem("splendid_tiger_pelt", 10, 9)
end
if player.exp < 1000000000 then
player:dialogSeq(
{
baekDialog,
"You must have forgotten the experience needed! As punishment for failing to follow my instructions, you must now bring me another Favor as well as more hides."
},
0
)
return
end
player.exp = player.exp - 1000000000
player:sendStatus()
if not player:hasLegend("attained_totem_mastery") then
player:addLegend(
"Attained Totem Mastery (" .. curT() .. ")",
"attained_totem_mastery",
3,
128
)
end
if player.baseClass == 1 then
player:updatePath(6, player.mark)
end
if player.baseClass == 2 then
player:updatePath(7, player.mark)
end
if player.baseClass == 3 then
player:updatePath(8, player.mark)
end
if player.baseClass == 4 then
player:updatePath(9, player.mark)
end
player:calcStat()
broadcast(
-1,
"[SUBPATH]: Congratulations to our newest " .. player.classNameMark .. " " .. player.name .. "!"
)
local tbook = {graphic = convertGraphic(20, "item"), color = 0}
player:dialogSeq(
{
tbook,
"You study for many days under the tutelage of Baek. You learn many rituals and legends."
},
1
)
player:dialogSeq(
{
baekDialog,
"You are ready. You will now be able to learn new rituals from your Guildmaster. Go well, my friend!"
},
0
)
end
if speech == "compass" then
Tools.checkKarma(player)
player:dialogSeq(
{
baekDialog,
"Hello there, you're looking for a compass, huh?",
"Well, I don't have the normal compasses, they are so dull.",
"Seriously, who really needs a compass that only points one way?",
"Everybody knows which way north is, it's to the north!",
"No, no... my compasses have a real use. They show you how to get to some place.",
"I don't bother with just the basic places, if you can't find Buya or Koguryo, then you just don't deserve to have eyes.",
"Anyways, if there is some place you need to go tell me, and I can make a compass to get you there."
},
0
)
end
if speech == "nagnag" then
Tools.checkKarma(player)
if player.quest["baek_compass"] == 0 then
player.quest["baek_compass"] = 1
player:dialogSeq(
{
baekDialog,
"A compass to Nagnag's palace? They seem to be in high demand these days.",
"Unfortunately, it is in such high demand that I have run out of parts for it.",
"If you were to get the parts I need, I could show you what you need to do.",
"Bring me a soup bowl, to hold the water in.",
"A bit of fine metal, for the needle.",
"Get that, and then come back to me."
},
0
)
return
end
if player.quest["baek_compass"] == 1 then
if player:hasItem("soup_bowl", 1) ~= true then
player:dialogSeq(
{
baekDialog,
"Where is the soup bowl? Can't do anything without it, you know."
},
0
)
return
end
if player:hasItem("fine_metal", 1) ~= true then
player:dialogSeq(
{
baekDialog,
"I also need the Fine metal, my shipment hasn't arrived. Come back when you get some."
},
0
)
return
end
player:removeItem("soup_bowl", 1, 9)
player:removeItem("fine_metal", 1, 9)
player:addItem("nagnang_compass", 10)
player:dialogSeq(
{
baekDialog,
"Ahhh, now let me see, what were the directions again... 192... 284... 82... 76...",
"A little water for the bowl, and we are done! There are a couple of them",
"Good luck using it, the parts were not top of the line, so you can only use each one once.",
"If you need another just tell me."
},
0
)
return
end
end
end)
}
|
---@meta
---@class crypt
local crypt = {}
---计算 hash
---@param key any
---@return string
function crypt.hashkey(key)
end
---生成一个8位的 key
---@return string
function crypt.randomkey()
end
---des 加密
---@param key number
---@param data string
---@param padding number | nil @对齐模式 默认 iso7816_4
---@return string
function crypt.desencode(key, data, padding)
end
---desc 解密
---@param key number
---@param data string
---@param padding number | nil @对齐模式 默认 iso7816_4
---@return string
function crypt.desdecode(key, data, padding)
end
---hex 编码
---@param data string
---@return string
function crypt.hexencode(data)
end
---hex 解码
---@param data string
---@return string
function crypt.hexdecode(data)
end
---hmac 签名
---@param challenge string @挑战消息
---@param secret string @密钥
---@return string
function crypt.hmac64(challenge, secret)
end
---hmac md5签名
---@param msg string
---@param secret string
---@return string
function crypt.hmac64_md5(msg, secret)
end
---dh交换
---@param key string
---@return string
function crypt.dhexchange(key)
end
---密钥计算
---@param dhkey string @经过 exchange 后的密钥
---@param selfkey string @原始
function crypt.dhsecret(dhkey, selfkey)
end
---base64编码
---@param msg string
---@return string
function crypt.base64encode(msg)
end
---base64解码
---@param msg string
---@return string
function crypt.base64decode(msg)
end
---sha1
---@param msg string
---@return string
function crypt.sha1(msg)
end
function crypt.hmac_sha1()
end
---hmac hash
---@param key string
---@param msg string
---@return string
function crypt.hmac_hash(key, msg)
end
---xor 字符串
---@param s1 string
---@param key string
---@return lightuserdata
function crypt.xor_str(s1, key)
end
return crypt
|
slot0 = Mathf.Clamp
slot1 = Mathf.Sqrt
slot2 = Mathf.Min
slot3 = Mathf.Max
slot4 = setmetatable
slot5 = rawget
slot7 = tolua.initget(slot6)
slot7.zero = function ()
return slot0.New(0, 0, 0, 0)
end
slot7.one = function ()
return slot0.New(1, 1, 1, 1)
end
slot7.magnitude = ({
__index = function (slot0, slot1)
if slot0(slot1, slot1) == nil and slot0(slot2, slot1) ~= nil then
return slot2(slot0)
end
return slot2
end,
__call = function (slot0, slot1, slot2, slot3, slot4)
return slot0({
x = slot1 or 0,
y = slot2 or 0,
z = slot3 or 0,
w = slot4 or 0
}, slot1)
end,
New = function (slot0, slot1, slot2, slot3)
return slot0({
x = slot0 or 0,
y = slot1 or 0,
z = slot2 or 0,
w = slot3 or 0
}, slot1)
end,
Set = function (slot0, slot1, slot2, slot3, slot4)
slot0.x = slot1 or 0
slot0.y = slot2 or 0
slot0.z = slot3 or 0
slot0.w = slot4 or 0
end,
Get = function (slot0)
return slot0.x, slot0.y, slot0.z, slot0.w
end,
Lerp = function (slot0, slot1, slot2)
return slot1.New(slot0.x + (slot1.x - slot0.x) * slot0(slot2, 0, 1), slot0.y + (slot1.y - slot0.y) * slot0(slot2, 0, 1), slot0.z + (slot1.z - slot0.z) * slot0(slot2, 0, 1), slot0.w + (slot1.w - slot0.w) * slot0(slot2, 0, 1))
end,
MoveTowards = function (slot0, slot1, slot2)
if slot2 < slot1 - slot0:Magnitude() and slot4 ~= 0 then
slot3:Mul(slot2)
slot3:Add(slot0)
return slot3
end
return slot1
end,
Scale = function (slot0, slot1)
return slot0.New(slot0.x * slot1.x, slot0.y * slot1.y, slot0.z * slot1.z, slot0.w * slot1.w)
end,
SetScale = function (slot0, slot1)
slot0.x = slot0.x * slot1.x
slot0.y = slot0.y * slot1.y
slot0.z = slot0.z * slot1.z
slot0.w = slot0.w * slot1.w
end,
Normalize = function (slot0)
return vector4.New(slot0.x, slot0.y, slot0.z, slot0.w):SetNormalize()
end,
SetNormalize = function (slot0)
if slot0:Magnitude() == 1 then
return slot0
elseif slot1 > 1e-05 then
slot0:Div(slot1)
else
slot0:Set(0, 0, 0, 0)
end
return slot0
end,
Div = function (slot0, slot1)
slot0.x = slot0.x / slot1
slot0.y = slot0.y / slot1
slot0.z = slot0.z / slot1
slot0.w = slot0.w / slot1
return slot0
end,
Mul = function (slot0, slot1)
slot0.x = slot0.x * slot1
slot0.y = slot0.y * slot1
slot0.z = slot0.z * slot1
slot0.w = slot0.w * slot1
return slot0
end,
Add = function (slot0, slot1)
slot0.x = slot0.x + slot1.x
slot0.y = slot0.y + slot1.y
slot0.z = slot0.z + slot1.z
slot0.w = slot0.w + slot1.w
return slot0
end,
Sub = function (slot0, slot1)
slot0.x = slot0.x - slot1.x
slot0.y = slot0.y - slot1.y
slot0.z = slot0.z - slot1.z
slot0.w = slot0.w - slot1.w
return slot0
end,
Dot = function (slot0, slot1)
return slot0.x * slot1.x + slot0.y * slot1.y + slot0.z * slot1.z + slot0.w * slot1.w
end,
Project = function (slot0, slot1)
return slot1 * slot0:Dot(slot1) / slot0.Dot(slot1, slot1)
end,
Distance = function (slot0, slot1)
return slot0.Magnitude(slot0 - slot1)
end,
Magnitude = function (slot0)
return slot0(slot0.x * slot0.x + slot0.y * slot0.y + slot0.z * slot0.z + slot0.w * slot0.w)
end,
SqrMagnitude = function (slot0)
return slot0.x * slot0.x + slot0.y * slot0.y + slot0.z * slot0.z + slot0.w * slot0.w
end,
Min = function (slot0, slot1)
return slot0.New(slot1(slot0.x, slot1.x), slot1(slot0.y, slot1.y), slot1(slot0.z, slot1.z), slot1(slot0.w, slot1.w))
end,
Max = function (slot0, slot1)
return slot0.New(slot1(slot0.x, slot1.x), slot1(slot0.y, slot1.y), slot1(slot0.z, slot1.z), slot1(slot0.w, slot1.w))
end,
__tostring = function (slot0)
return string.format("[%f,%f,%f,%f]", slot0.x, slot0.y, slot0.z, slot0.w)
end,
__div = function (slot0, slot1)
return slot0.New(slot0.x / slot1, slot0.y / slot1, slot0.z / slot1, slot0.w / slot1)
end,
__mul = function (slot0, slot1)
return slot0.New(slot0.x * slot1, slot0.y * slot1, slot0.z * slot1, slot0.w * slot1)
end,
__add = function (slot0, slot1)
return slot0.New(slot0.x + slot1.x, slot0.y + slot1.y, slot0.z + slot1.z, slot0.w + slot1.w)
end,
__sub = function (slot0, slot1)
return slot0.New(slot0.x - slot1.x, slot0.y - slot1.y, slot0.z - slot1.z, slot0.w - slot1.w)
end,
__unm = function (slot0)
return slot0.New(-slot0.x, -slot0.y, -slot0.z, -slot0.w)
end,
__eq = function (slot0, slot1)
return slot0.SqrMagnitude(slot2) < 1e-10
end
})["Magnitude"]
slot7.normalized = ()["Normalize"]
slot7.sqrMagnitude = ()["SqrMagnitude"]
UnityEngine.Vector4 =
slot4(, )
return
|
local typedefs = require "kong.db.schema.typedefs"
return {
name = "ip-restriction",
fields = {
{ protocols = typedefs.protocols_http },
{ config = {
type = "record",
fields = {
{ allow = { type = "array", elements = typedefs.ip_or_cidr, }, },
{ deny = { type = "array", elements = typedefs.ip_or_cidr, }, },
{ status = { type = "number", required = false } },
{ message = { type = "string", required = false } },
},
},
},
},
entity_checks = {
{ at_least_one_of = { "config.allow", "config.deny" }, },
},
}
|
require("src/ball")
require("src/bounds")
require("src/enemy")
require("src/player")
require("src/score")
require("src/util")
function love.load()
love.physics.setMeter(64)
world = love.physics.newWorld(0, 0, true)
player:load(world)
enemy:load(world)
bounds:load(world)
ball:load(world)
score:load()
end
function love.update(dt)
world:update(dt)
player:update(dt)
enemy:update(dt)
ball:update(dt)
score:update(dt)
end
function love.draw()
score:draw()
player:draw()
enemy:draw()
ball:draw()
end
|
local resty_redis = require("resty.redis")
local utils = require("foxcaves.utils")
local config = require("foxcaves.config").redis
local error = error
local ngx = ngx
local M = {}
require("foxcaves.module_helper").setmodenv()
function M.make(close_on_shutdown)
local redis, err = resty_redis:new()
if not redis then
error("Error initializing Redis: " .. err)
end
redis:set_timeout(60000)
local ok
ok, err = redis:connect(config.host, config.port)
if not ok then
error("Error connecting to Redis: " .. err)
end
if close_on_shutdown then
utils.register_shutdown(function()
redis:close()
end)
else
utils.register_shutdown(function()
redis:set_keepalive(config.keepalive_timeout or 10000, config.keepalive_count or 10)
end)
end
return redis
end
function M.get_shared()
local redis = ngx.ctx.__redis
if redis then
return redis
end
redis = M.make()
ngx.ctx.__redis = redis
return redis
end
return M
|
module("XEventModule", package.seeall)
function new(szName)
local obj = {
}
setmetatable(obj, {__index=XEventModule})
obj:Init(szName)
return obj
end
function Init(self, szName)
self.name = szName
self.events = {
}
self.active = false
end
function Name(self)
return self.name
end
function Active(self)
if not self.active then
self.active = true
self:OnActive()
end
end
function GetActive(self)
return self.active
end
function Detive(self)
if self.active then
self.active = false
self:OnDetive()
end
end
function Unload(self, destroyFlag)
if self.dispatcher then
self.dispatcher:Unload(self:Name(), destroyFlag)
end
if destroyFlag then
self:ResetEvent()
end
end
function SetDispatcher(self, dispatcher)
self.dispatcher = dispatcher
end
function GetDispatcher(self)
return self.dispatcher
end
function SubscribeEvent(self, nID, evtCallback)
if not self.events[nID] then
self.events[nID] = evtCallback
end
end
function FireEvent(self, nID, evtArgs)
return self.events[nID](self, evtArgs)
end
function HasEvent(self, nID)
return self.events[nID]
end
function RemoveEvent(self, nID)
if self.events[nID] then
self.events[nID] = nil
end
end
function ResetEvent(self)
self.events = {}
end
function OnActive(self)
end
function OnDetive(self)
end
function OnDestroy(self)
end
|
local HARD_RESERVE_OFFSET = 16777215
local function sortWeightedMap(a, b)
if not a or not b then return false end
return a[2] > b[2]
end
function GogoLoot:BuildWeightedPlayerMap(jsonData) -- build a weighted player map for quicker lookups
local map = {}
local reserveCountItems = 0
local reserveCountTotal = 0
local function insertReserve(table, reserve, modifier)
if not reserve or not reserve.item or not reserve.name then -- should never happen
print("Bad data softres in profile!")
return
end
if not table[reserve.item] then
table[reserve.item] = {}
reserveCountItems = reserveCountItems + 1
end
tinsert(table[reserve.item], {reserve.name, modifier + (reserve.rollBonus or 0)})
reserveCountTotal = reserveCountTotal + 1
end
if jsonData.hardreserves then
for _, reserve in pairs(jsonData.hardreserves) do -- ensure hardreserves are above regular reserves
insertReserve(map, reserve, HARD_RESERVE_OFFSET)
end
end
if jsonData.softreserves then
for _, reserve in pairs(jsonData.softreserves) do
insertReserve(map, reserve, 0)
end
end
for _, weightMap in pairs(map) do
-- sort players by their weight
table.sort(weightMap, sortWeightedMap)
end
--print("Loaded Softres.it profile, " .. tostring(reserveCountItems) .. " items, " .. tostring(reserveCountTotal) .. " reserves.")
GogoLoot_Config.softres.itemCount = reserveCountItems
GogoLoot_Config.softres.reserveCount = reserveCountTotal
return map
end
function GogoLoot:SetSoftresProfile(data)
if data == GogoLoot_Config.softres.profiles._current_data then
-- dont replace profile and overwrite removed (completed) reserves
return
end
if not data or string.len(data) < 4 then
return -- invalid profile
end
local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
local function decodeBase64(data)
data = string.gsub(data, '[^'..b..'=]', '')
return (data:gsub('.', function(x)
if (x == '=') then return '' end
local r,f='',(b:find(x)-1)
for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end
return r;
end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x)
if (#x ~= 8) then return '' end
local c=0
for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end
return string.char(c)
end))
end
data = decodeBase64(data)
data = LibStub:GetLibrary("LibDeflate"):DecompressZlib(data)
--print("json data: " .. data)
local decoded = GogoLoot.json.decode(data)
if decoded then
GogoLoot_Config.softres.profiles.current = decoded
GogoLoot_Config.softres.profiles.weightedPlayerMap = GogoLoot:BuildWeightedPlayerMap(decoded)
GogoLoot_Config.softres.profiles._current_data = data
else
GogoLoot_Config.softres.profiles.current = nil
GogoLoot_Config.softres.profiles.weightedPlayerMap = nil
GogoLoot_Config.softres.profiles._current_data = nil
end
end
GogoLoot.softresRemoveQueue = {}
GogoLoot.softresRemoveRoll = {}
function GogoLoot:HandleSoftresLooted(slot)
local id = GogoLoot.softresRemoveQueue[slot]
if id then
local map = GogoLoot_Config.softres.profiles.weightedPlayerMap[id]
if map then
--print("Removed softres for " .. slot)
map[1][2] = -1
table.sort(map, sortWeightedMap) -- re-sort players
end
GogoLoot.softresRemoveQueue[slot] = nil -- this should probably be in the above if, but if this went wrong we should fail here and not more catastrophically later
end
end
function GogoLoot:HandleSoftresRollWin(player, id)
local weights = GogoLoot_Config.softres.profiles.weightedPlayerMap[id]
if weights then
for index, target in pairs(weights) do
if strlower(target[1]) == player then
target[2] = -1
break
end
end
table.sort(weights, sortWeightedMap)
end
end
function GogoLoot:MirrorServerNames(playerList)
local newList = {}
for player, id in pairs(playerList) do
if string.find(player, "-") then -- player is cross-realm
newList[string.sub(player, 1, string.find(player, "-")-1)] = id
end
newList[player] = id
end
return newList
end
-- list of mobs / loot slots that have already been announced this session
local _announced_mobs = {}
function GogoLoot:HandleSoftresLoot(lootItemId, playerList, slot, mobGUID)
if not GogoLoot_Config.enableSoftres or not GogoLoot_Config.softres.profiles.weightedPlayerMap then
return false -- no softres profile
end
playerList = GogoLoot:MirrorServerNames(playerList)
local weightMap = GogoLoot_Config.softres.profiles.weightedPlayerMap[lootItemId]
if not weightMap then
return false -- no reserve for this item
end
local weightMapClean = {} -- remove players that already got the item and players that arent in the group
for _,reserve in pairs(weightMap) do
if reserve[2] >= 0 and playerList[strlower(reserve[1])] then
tinsert(weightMapClean, reserve)
end
end
weightMap = weightMapClean
if #weightMap == 0 then
return false -- no valid reserve for this item
elseif #weightMap == 1 then
if weightMap[1][2] < 0 then
return false -- already received item
end
if GogoLoot.softresRemoveQueue[slot] ~= lootItemId then
SendChatMessage(string.format(GogoLoot.SOFTRES_LOOT, select(2, GetItemInfo(lootItemId)), weightMap[1][1]), UnitInRaid("Player") and "RAID" or "PARTY")
GogoLoot.softresRemoveQueue[slot] = lootItemId
end
return weightMap[1][1] -- only 1 player reserved
end
if weightMap[1][2] >= HARD_RESERVE_OFFSET then -- item is hard reserved
if GogoLoot.softresRemoveQueue[slot] ~= lootItemId then
SendChatMessage(string.format(GogoLoot.SOFTRES_LOOT_HARD, select(2, GetItemInfo(lootItemId)), weightMap[1][1]), UnitInRaid("Player") and "RAID" or "PARTY")
GogoLoot.softresRemoveQueue[slot] = lootItemId
end
return weightMap[1][1] -- only 1 player can hard reserve? Otherwise we should combine like below
end
local targetList = ""
local targetTable = {}
for index, target in pairs(weightMap) do
local targetBonus = ""
if target[2] > 0 then
targetBonus = "[+" .. tostring(target[2]) .. "]" -- add roll bonus behind name
end
tinsert(targetTable, target[1])
if index == 1 then
targetList = target[1] .. targetBonus
elseif index == #weightMap then
targetList = targetList .. ", and " .. target[1] .. targetBonus
else
targetList = targetList .. ", " .. target[1] .. targetBonus
end
end
GogoLoot:showLootFrame("Softres loot conflict")
local lootKey = (mobGUID or "") .. "-" .. tostring(slot or 0) .. "-" .. tostring(lootItemId or 0)
if not _announced_mobs[lootKey] then
_announced_mobs[lootKey] = true -- prevent announcing the roll more than once, even if the events are fired multiple times (addon conflict?)
SendChatMessage(string.format(GogoLoot.SOFTRES_ROLL, select(2, GetItemInfo(lootItemId)), targetList), UnitInRaid("Player") and "RAID" or "PARTY")
end
return targetTable -- players must roll
end
|
local migration = {}
function migration.global()
end
function migration.player_table(player_table)
local preferences = player_table.preferences
local mb_defaults = preferences.mb_defaults
if mb_defaults then
mb_defaults.machine = mb_defaults.module
mb_defaults.module = nil
end
local optional_columns = preferences.optional_production_columns
if optional_columns then
preferences.pollution_column = optional_columns.pollution_column
preferences.line_comment_column = optional_columns.line_comments
preferences.optional_production_columns = nil
end
end
function migration.subfactory(subfactory)
end
function migration.packed_subfactory(packed_subfactory)
end
return migration |
data:extend(
{
{
type = "recipe-category",
name = "iron-recycling"
},
{
type = "recipe-category",
name = "copper-recycling"
},
{
type = "recipe-category",
name = "only-iron-recycling"
},
{
type = "recipe-category",
name = "only-copper-recycling"
},
{
type = "recipe-category",
name = "both-recycling"
},
{
type = "recipe-category",
name = "recycle-destroying"
},
{
type = "recipe-category",
name = "recycle-shredding"
}
})
|
-----------------------------------
-- Area: Bibiki Bay
-- NPC: Clamming Point
-----------------------------------
local ID = require("scripts/zones/Bibiki_Bay/IDs");
require("scripts/globals/keyitems");
-----------------------------------
-- Local Variables
-----------------------------------
-- clammingItems = item id, weight, drop rate, improved drop rate
local clammingItems = {
1311, 6, 0.001, 0.003, -- Oxblood
885, 6, 0.002, 0.006, -- Turtle Shell
1193, 6, 0.003, 0.009, -- HQ Crab Shell
1446, 6, 0.004, 0.012, -- Lacquer Tree Log
4318, 6, 0.005, 0.015, -- Bibiki Urchin
1586, 6, 0.008, 0.024, -- Titanictus Shell
5124, 20, 0.011, 0.033, -- Tropical Clam
690, 6, 0.014, 0.042, -- Elm Log
887, 6, 0.017, 0.051, -- Coral Fragment
703, 6, 0.021, 0.063, -- Petrified Log
691, 6, 0.025, 0.075, -- Maple Log
4468, 6, 0.029, 0.087, -- Pamamas
3270, 6, 0.033, 0.099, -- HQ Pugil Scales
888, 6, 0.038, 0.114, -- Seashell
4328, 6, 0.044, 0.132, -- Hobgoblin Bread
485, 6, 0.051, 0.153, -- Broken Willow Rod
510, 6, 0.058, 0.174, -- Goblin Armor
5187, 6, 0.065, 0.195, -- Elshimo Coconut
507, 6, 0.073, 0.219, -- Goblin Mail
881, 6, 0.081, 0.243, -- Crab Shell
4325, 6, 0.089, 0.267, -- Hobgoblin Pie
936, 6, 0.098, 0.294, -- Rock Salt
4361, 6, 0.107, 0.321, -- Nebimonite
864, 6, 0.119, 0.357, -- Fish Scales
4484, 6, 0.140, 0.420, -- Shall Shell
624, 6, 0.178, 0.534, -- Pamtam Kelp
1654, 35, 0.225, 0.675, -- Igneous Rock
17296, 7, 0.377, 0.784, -- Pebble
5123, 11, 0.628, 0.892, -- Jacknife
5122, 3, 1.000, 1.000 -- Bibiki Slug
};
-----------------------------------
-- Local Functions
-----------------------------------
local function giveImprovedResults(player)
if (player:getMod(tpz.mod.CLAMMING_IMPROVED_RESULTS) > 0) then
return 1;
end
return 0;
end;
local function giveReducedIncidents(player)
if (player:getMod(tpz.mod.CLAMMING_REDUCED_INCIDENTS) > 0) then
return 0.05;
end
return 0.1;
end;
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
if (player:hasKeyItem(tpz.ki.CLAMMING_KIT)) then
player:setLocalVar("ClammingPointID", npc:getID());
if (GetServerVariable("ClammingPoint_" .. npc:getID() .. "_InUse") == 1) then
player:messageSpecial(ID.text.IT_LOOKS_LIKE_SOMEONE);
else
if (player:getCharVar("ClammingKitBroken") > 0) then -- Broken bucket
player:messageSpecial(ID.text.YOU_CANNOT_COLLECT);
else
local delay = GetServerVariable("ClammingPoint_" .. npc:getID() .. "_Delay");
if ( delay > 0 and delay > os.time()) then -- player has to wait a little longer
player:messageSpecial(ID.text.IT_LOOKS_LIKE_SOMEONE);
else
SetServerVariable("ClammingPoint_" .. npc:getID() .. "_InUse", 1);
SetServerVariable("ClammingPoint_" .. npc:getID() .. "_Delay", 0);
player:startEvent(20, 0, 0, 0, 0, 0, 0, 0, 0);
end
end
end
else
player:messageSpecial(ID.text.AREA_IS_LITTERED);
end;
end;
function onEventUpdate(player,csid,option)
if (csid == 20) then
if (player:getCharVar("ClammingKitSize") == 200 and math.random() <= giveReducedIncidents(player)) then
player:setLocalVar("SomethingJumpedInBucket", 1);
else
local dropRate = math.random();
local improvedResults = giveImprovedResults(player);
for itemDrop = 3, #clammingItems, 4 do
if (dropRate <= clammingItems[itemDrop + improvedResults]) then
player:setLocalVar("ClammedItem", clammingItems[itemDrop - 2]);
player:addCharVar("ClammedItem_" .. clammingItems[itemDrop - 2], 1);
player:addCharVar("ClammingKitWeight", clammingItems[itemDrop - 1]);
if (player:getCharVar("ClammingKitWeight") > player:getCharVar("ClammingKitSize")) then -- Broken bucket
player:setCharVar("ClammingKitBroken", 1);
end
break;
end
end
end
end
end;
function onEventFinish(player,csid,option)
if (csid == 20) then
if (player:getLocalVar("SomethingJumpedInBucket") > 0) then
player:setLocalVar("SomethingJumpedInBucket", 0);
player:messageSpecial(ID.text.SOMETHING_JUMPS_INTO);
player:setCharVar("ClammingKitBroken", 1);
for item = 1, #clammingItems, 4 do -- Remove items from bucket
player:setCharVar("ClammedItem_" .. clammingItems[item], 0);
end
else
local clammedItem = player:getLocalVar("ClammedItem");
if (clammedItem > 0) then
if (player:getCharVar("ClammingKitBroken") > 0) then --Broken bucket
player:messageSpecial(ID.text.THE_WEIGHT_IS_TOO_MUCH, clammedItem);
for item = 1, #clammingItems, 4 do -- Remove items from bucket
player:setCharVar("ClammedItem_" .. clammingItems[item], 0);
end
else
player:messageSpecial(ID.text.YOU_FIND_ITEM, clammedItem);
end
SetServerVariable("ClammingPoint_" .. player:getLocalVar("ClammingPointID") .. "_Delay", os.time() + 10);
player:setLocalVar("ClammedItem", 0);
end
end
SetServerVariable("ClammingPoint_" .. player:getLocalVar("ClammingPointID") .. "_InUse", 0);
player:setLocalVar("ClammingPointID", 0);
end
end; |
_cursor = _{
extends = _mob,
update = function(this)
if btnp(0) then
this:move(this.x-1,this.y)
elseif btnp(1) then
this:move(this.x+1,this.y)
elseif btnp(2) then
this:move(this.x,this.y-1)
elseif btnp(3) then
this:move(this.x,this.y+1)
end
if btnp(4) then
this.editor:set_tile(this.x,this.y)
end
_mob.update(this)
end,
move = function(this, x, y)
_mob.move(this, mid(x,world_size,1), mid(y,world_size,1), true)
end,
draw = function(this)
local x, y = this:real_position()
color(flr(frame/10) % 2 == 0 and 7 or 6)
local inner, inner_b = flr(tile_size - tile_size/4), flr(tile_size/4)-1
line(x+inner_b,y-1,x-1,y-1)
line(x-1,y+inner_b)
line(x+inner,y-1,x+tile_size,y-1)
line(x+tile_size,y+inner_b)
line(x+tile_size,y+inner,x+tile_size,y+tile_size)
line(x+inner,y+tile_size)
line(x+inner_b,y+tile_size,x-1,y+tile_size)
line(x-1,y+inner)
end,
}
|
local M = {}
function M.config()
local options = {
pairs_map = {
["'"] = "'",
['"'] = '"',
["("] = ")",
["["] = "]",
["{"] = "}",
["`"] = "`",
},
disable_filetype = { "TelescopePrompt" },
disable_in_macro = false,
ignored_next_char = string.gsub([[ [%w%%%'%[%"%.] ]], "%s+", ""),
enable_moveright = true,
enable_afterquote = true,
enable_check_bracket_line = true,
check_ts = true,
map_bs = true,
map_c_w = false,
}
require("nvim-autopairs").setup(options)
end
return setmetatable({}, {
__call = function()
return M.config()
end,
})
|
local E, C, L = select(2, ...):unpack()
if not C.actionbar.bars.enable then return end
----------------------------------------------------------------------------------------
-- ExtraActionBar (modified from ShestakUI)
----------------------------------------------------------------------------------------
local _G = _G
local CreateFrame = CreateFrame
local RegisterStateDriver = RegisterStateDriver
local unpack, tinsert = unpack, tinsert
local UIParent = _G.UIParent
local ExtraActionBarFrame = _G.ExtraActionBarFrame
local ExtraActionButton1 = _G.ExtraActionButton1
local ZoneAbilityFrame = _G.ZoneAbilityFrame
local cfg = C.actionbar.bars.barextra
local num = 1
--create the frame to hold the buttons
local extraBar = CreateFrame("Frame", "DarkUI_ExtraBarHolder", UIParent, "SecureHandlerStateTemplate")
extraBar:SetWidth(num * cfg.button.size + (num - 1) * cfg.button.space)
extraBar:SetHeight(cfg.button.size)
extraBar:SetPoint(unpack(cfg.pos))
extraBar.buttonList = {}
--move the buttons into position and reparent them
ExtraActionBarFrame:EnableMouse(false)
ExtraAbilityContainer:SetParent(extraBar)
ExtraAbilityContainer:ClearAllPoints()
ExtraAbilityContainer:SetPoint("CENTER", extraBar)
ExtraAbilityContainer.ignoreFramePositionManager = true
--create the mouseover functionality
if cfg.fader_mouseover then
E:ButtonBarFader(extraBar, extraBar.buttonList, cfg.fader_mouseover.fadeIn, cfg.fader_mouseover.fadeOut)
end
--create the combat fader
if cfg.fader_combat then
E:CombatFrameFader(extraBar, cfg.fader_combat.fadeIn, cfg.fader_combat.fadeOut)
end
--the extra button
local button = ExtraActionButton1
tinsert(extraBar.buttonList, button) --add the button object to the list
button:SetSize(cfg.button.size, cfg.button.size)
--show/hide the frame on a given state driver
RegisterStateDriver(extraBar, "visibility", "[extrabar] show; hide")
--zone ability
local zoneBar = CreateFrame("Frame", "ZoneAbilityBarHolder", UIParent)
zoneBar:SetWidth(cfg.button.size)
zoneBar:SetHeight(cfg.button.size)
zoneBar:SetPoint("BOTTOM", extraBar, "TOP", 0, 10)
ZoneAbilityFrame:SetParent(zoneBar)
ZoneAbilityFrame:ClearAllPoints()
ZoneAbilityFrame:SetPoint("CENTER", 0, 0)
ZoneAbilityFrame.ignoreFramePositionManager = true
ZoneAbilityFrame.Style:SetAlpha(0)
hooksecurefunc(ZoneAbilityFrame, "UpdateDisplayedZoneAbilities", function(self)
for spellButton in self.SpellButtonContainer:EnumerateActive() do
if spellButton and not spellButton.styled then
spellButton.NormalTexture:SetAlpha(0)
spellButton:SetPushedTexture(C.media.button.pushed) --force it to gain a texture
spellButton:GetHighlightTexture():SetColorTexture(1, 1, 1, .25)
--spellButton:StripTextures()
spellButton:SetSize(cfg.button.size, cfg.button.size)
spellButton:CreateTextureBorder()
spellButton.Icon:SetTexCoord(0.1, 0.9, 0.1, 0.9)
spellButton.Icon:SetPoint("TOPLEFT", spellButton, 2, -2)
spellButton.Icon:SetPoint("BOTTOMRIGHT", spellButton, -2, 2)
spellButton.Icon:SetDrawLayer("BACKGROUND", 7)
spellButton.Count:SetFont(unpack(C.media.standard_font))
spellButton.Count:SetShadowOffset(1, -1)
spellButton.Count:SetPoint("BOTTOMRIGHT", 0, 1)
spellButton.Count:SetJustifyH("RIGHT")
spellButton.Cooldown:SetAllPoints(spellButton.Icon)
spellButton.styled = true
end
end
end)
-- Fix button visibility
hooksecurefunc(ZoneAbilityFrame, "SetParent", function(self, parent)
if parent == ExtraAbilityContainer then
self:SetParent(zoneBar)
end
end)
|
local Skada = Skada
local L = LibStub("AceLocale-3.0"):GetLocale("Skada")
local AceGUI = LibStub("AceGUI-3.0")
local pairs, type, tsort = pairs, type, table.sort
local format, sbyte = string.format, string.byte
local GetCursorPosition = GetCursorPosition
local GetScreenWidth, GetScreenHeight = GetScreenWidth, GetScreenHeight
local CreateFrame = CreateFrame
local UIDropDownMenu_CreateInfo = UIDropDownMenu_CreateInfo
local UIDropDownMenu_AddButton = UIDropDownMenu_AddButton
local CloseDropDownMenus = CloseDropDownMenus
local ToggleDropDownMenu = ToggleDropDownMenu
local iconName = "|T%s:19:19:0:-1:32:32:2:30:2:30|t %s"
-- references: windows, modes, sets
local windows, modes, sets = nil, nil, nil
-- guesses the dropdown location
local function getDropdownPoint()
local x, y = GetCursorPosition(UIParent)
x = x / UIParent:GetEffectiveScale()
y = y / UIParent:GetEffectiveScale()
local point = (x > GetScreenWidth() / 2) and "RIGHT" or "LEFT"
point = ((y > GetScreenHeight() / 2) and "TOP" or "BOTTOM") .. point
return point, x, y
end
-- Configuration menu.
function Skada:OpenMenu(window)
self.skadamenu = self.skadamenu or CreateFrame("Frame", "SkadaMenu", UIParent, "UIDropDownMenuTemplate")
self.skadamenu.displayMode = "MENU"
self.skadamenu.win = window
self.skadamenu.initialize = self.skadamenu.initialize or function(self, level)
if not level then return end
local info = UIDropDownMenu_CreateInfo()
if level == 1 then
-- window menus
windows = Skada:GetWindows()
for i = 1, #windows do
local win = windows[i]
if win and win.db then
wipe(info)
info.text = win.db.name
info.hasArrow = 1
info.value = win
info.notCheckable = 1
info.colorCode = (self.win and self.win == win) and "|cffffd100"
UIDropDownMenu_AddButton(info, level)
end
end
-- create window
wipe(info)
info.text = L["Create Window"]
info.func = Skada.NewWindow
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
-- toggle window
wipe(info)
info.text = L["Toggle Windows"]
info.func = function()
Skada:ToggleWindow()
end
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.disabled = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
-- quick access menu
wipe(info)
info.text = L["Quick Access"]
info.value = "shortcut"
info.hasArrow = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.disabled = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
-- Can't report if we are not in a mode.
if not self.win or (self.win and self.win.selectedmode) then
wipe(info)
info.text = L["Report"]
info.value = "report"
info.func = function()
Skada:OpenReportWindow(self.win)
end
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
end
if self.win then
wipe(info)
info.text = L["Select Segment"]
info.value = "segment"
info.hasArrow = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
end
-- delete segment menu
wipe(info)
info.text = L["Delete Segment"]
info.value = "delete"
info.hasArrow = 1
info.disabled = (not Skada.char.sets or #Skada.char.sets == 0)
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
if Skada.db.profile.setstokeep > 0 then
-- keep segment
wipe(info)
info.text = L["Keep Segment"]
info.value = "keep"
info.hasArrow = 1
info.disabled = (not Skada.char.sets or #Skada.char.sets == 0)
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
end
wipe(info)
info.disabled = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
-- start new segment
wipe(info)
info.text = L["Start New Segment"]
info.func = function()
Skada:NewSegment()
end
info.notCheckable = 1
info.disabled = (Skada.current == nil)
UIDropDownMenu_AddButton(info, level)
-- start new phase
wipe(info)
info.text = L["Start New Phase"]
info.func = function()
Skada:NewPhase()
end
info.notCheckable = 1
info.disabled = (Skada.current == nil)
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.disabled = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
-- reset
wipe(info)
info.text = L["Reset"]
info.func = function()
Skada:ShowPopup()
end
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
-- Configure
wipe(info)
info.text = L["Configure"]
info.func = function()
Skada:OpenOptions(self.win)
end
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
-- Close menu item
wipe(info)
info.text = CLOSE
info.func = function()
CloseDropDownMenus()
end
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
elseif level == 2 then
if type(UIDROPDOWNMENU_MENU_VALUE) == "table" then
local win = UIDROPDOWNMENU_MENU_VALUE
-- window
wipe(info)
info.text = L["Window"]
info.isTitle = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
-- lock window
wipe(info)
info.text = L["Lock Window"]
info.func = function()
win.db.barslocked = (win.db.barslocked ~= true) and true or nil
Skada:ApplySettings(win.db.name)
end
info.checked = win.db.barslocked
UIDropDownMenu_AddButton(info, level)
-- hide window
wipe(info)
info.text = L["Hide Window"]
info.func = function()
if win:IsShown() then
win.db.hidden = true
win:Hide()
else
win.db.hidden = false
win:Show()
end
Skada:ApplySettings(win.db.name, true)
end
info.checked = not win:IsShown()
UIDropDownMenu_AddButton(info, level)
-- snap window
if win.db.display == "bar" then
wipe(info)
info.text = L["Sticky Window"]
info.func = function()
win.db.sticky = (win.db.sticky ~= true) and true or nil
if not win.db.sticky then
windows = Skada:GetWindows()
for i = 1, #windows do
local w = windows[i]
if w and w.db and w.db.sticked and w.db.sticked[win.db.name] then
w.db.sticked[win.db.name] = nil
end
end
end
Skada:ApplySettings(win.db.name)
end
info.checked = win.db.sticky
UIDropDownMenu_AddButton(info, level)
end
-- clamped to screen
wipe(info)
info.text = L["Clamped To Screen"]
info.func = function()
win.db.clamped = (win.db.clamped ~= true) and true or nil
Skada:ApplySettings(win.db.name)
end
info.checked = win.db.clamped
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.disabled = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
-- window
if win.db.display == "bar" then
wipe(info)
info.text = L["Options"]
info.isTitle = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
if Skada.db.profile.showself ~= true then
wipe(info)
info.text = L["Always show self"]
info.func = function()
win.db.showself = (win.db.showself ~= true) and true or nil
Skada:ApplySettings(win.db.name)
end
info.checked = (win.db.showself == true)
UIDropDownMenu_AddButton(info, level)
end
if Skada.db.profile.showtotals ~= true then
wipe(info)
info.text = L["Show totals"]
info.func = function()
win.db.showtotals = (win.db.showtotals ~= true) and true or nil
win:Wipe(true)
Skada:UpdateDisplay()
end
info.checked = (win.db.showtotals == true)
UIDropDownMenu_AddButton(info, level)
end
wipe(info)
info.text = L["Include set"]
info.func = function()
win.db.titleset = (win.db.titleset ~= true) and true or nil
Skada:ApplySettings(win.db.name)
end
info.checked = (win.db.titleset == true)
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.text = L["Encounter Timer"]
info.func = function()
win.db.combattimer = (win.db.combattimer ~= true) and true or nil
Skada:ApplySettings(win.db.name)
end
info.checked = (win.db.combattimer == true)
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.disabled = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
end
-- delete window
wipe(info)
info.text = L["Delete Window"]
info.func = function()
return Skada:DeleteWindow(win.db.name)
end
info.notCheckable = 1
info.leftPadding = 16
info.colorCode = "|cffeb4c34"
UIDropDownMenu_AddButton(info, level)
elseif UIDROPDOWNMENU_MENU_VALUE == "segment" then
wipe(info)
info.text = L["Total"]
info.func = function()
self.win:set_selected_set("total")
Skada:UpdateDisplay()
end
info.checked = (self.win.selectedset == "total")
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.text = L["Current"]
info.func = function()
self.win:set_selected_set("current")
Skada:UpdateDisplay()
end
info.checked = (self.win.selectedset == "current")
UIDropDownMenu_AddButton(info, level)
if #Skada.char.sets > 0 then
wipe(info)
info.disabled = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
sets = Skada:GetSets()
for i = 1, #sets do
local set = sets[i]
wipe(info)
info.text = Skada:GetSetLabel(set)
info.func = function()
self.win:set_selected_set(i)
Skada:UpdateDisplay()
end
if set.gotboss then
info.colorCode = set.success and "|cff19ff19" or "|cffff1919"
elseif set.type == "pvp" or set.type == "arena" then
info.colorCode = "|cffffd100"
end
info.checked = (self.win.selectedset == i)
UIDropDownMenu_AddButton(info, level)
end
end
elseif UIDROPDOWNMENU_MENU_VALUE == "delete" then
sets = Skada:GetSets()
for i = 1, #sets do
local set = sets[i]
wipe(info)
info.text = Skada:GetSetLabel(set)
info.func = function()
Skada:DeleteSet(set, i)
end
info.notCheckable = 1
if set.gotboss then
info.colorCode = set.success and "|cff19ff19" or "|cffff1919"
elseif set.type == "pvp" or set.type == "arena" then
info.colorCode = "|cffffd100"
end
UIDropDownMenu_AddButton(info, level)
end
elseif UIDROPDOWNMENU_MENU_VALUE == "keep" then
local num, kept = 0, 0
sets = Skada:GetSets()
for i = 1, #sets do
local set = sets[i]
num = num + 1
if set.keep then kept = kept + 1 end
wipe(info)
info.text = Skada:GetSetLabel(set)
info.func = function()
set.keep = (set.keep ~= true) and true or nil
self.win:UpdateDisplay()
end
info.checked = set.keep
info.keepShownOnClick = true
if set.gotboss then
info.colorCode = set.success and "|cff19ff19" or "|cffff1919"
elseif set.type == "pvp" or set.type == "arena" then
info.colorCode = "|cffffd100"
end
UIDropDownMenu_AddButton(info, level)
end
if num > 0 then
wipe(info)
info.disabled = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.text = L["Select All"]
info.func = function()
sets = Skada:GetSets()
for i = 1, #sets do
sets[i].keep = true
end
end
info.notCheckable = 1
info.leftPadding = 16
info.disabled = (num == kept)
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.text = L["Deselect All"]
info.func = function()
sets = Skada:GetSets()
for i = 1, #sets do
sets[i].keep = nil
end
end
info.notCheckable = 1
info.leftPadding = 16
info.disabled = (kept == 0)
UIDropDownMenu_AddButton(info, level)
end
elseif UIDROPDOWNMENU_MENU_VALUE == "shortcut" then
-- time measure
wipe(info)
info.text = L["Time Measure"]
info.isTitle = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.text = L["Activity Time"]
info.func = function()
Skada.db.profile.timemesure = 1
Skada:ApplySettings(true)
end
info.checked = (Skada.db.profile.timemesure == 1)
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.text = L["Effective Time"]
info.func = function()
Skada.db.profile.timemesure = 2
Skada:ApplySettings(true)
end
info.checked = (Skada.db.profile.timemesure == 2)
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.disabled = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
-- number format
wipe(info)
info.text = L["Number format"]
info.isTitle = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.text = L["Condensed"]
info.func = function()
Skada.db.profile.numberformat = 1
Skada:ApplySettings(true)
end
info.checked = (Skada.db.profile.numberformat == 1)
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.text = L["Comma"]
info.func = function()
Skada.db.profile.numberformat = 2
Skada:ApplySettings(true)
end
info.checked = (Skada.db.profile.numberformat == 2)
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.text = L["Detailed"]
info.func = function()
Skada.db.profile.numberformat = 3
Skada:ApplySettings(true)
end
info.checked = (Skada.db.profile.numberformat == 3)
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.disabled = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
-- number format
wipe(info)
info.text = OTHER
info.isTitle = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.text = L["Show totals"]
info.func = function()
Skada.db.profile.showtotals = (Skada.db.profile.showtotals ~= true) and true or nil
Skada:Wipe()
Skada:UpdateDisplay(true)
end
info.checked = (Skada.db.profile.showtotals == true)
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.text = L["Show rank numbers"]
info.func = function()
Skada.db.profile.showranks = (Skada.db.profile.showranks ~= true) and true or nil
Skada:ApplySettings()
end
info.checked = (Skada.db.profile.showranks == true)
info.keepShownOnClick = 1
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.text = L["Always show self"]
info.func = function()
Skada.db.profile.showself = (Skada.db.profile.showself ~= true) and true or nil
Skada:ApplySettings()
end
info.checked = (Skada.db.profile.showself == true)
info.keepShownOnClick = 1
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.text = L["Aggressive combat detection"]
info.func = function()
Skada.db.profile.tentativecombatstart = (Skada.db.profile.tentativecombatstart ~= true) and true or nil
Skada:ApplySettings()
end
info.checked = (Skada.db.profile.tentativecombatstart == true)
info.keepShownOnClick = 1
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.text = L["Absorbed Damage"]
info.func = function()
Skada.db.profile.absdamage = (Skada.db.profile.absdamage ~= true) and true or nil
Skada:ApplySettings()
end
info.checked = (Skada.db.profile.absdamage == true)
info.keepShownOnClick = 1
UIDropDownMenu_AddButton(info, level)
end
elseif level == 3 then
if UIDROPDOWNMENU_MENU_VALUE == "modes" then
modes = Skada:GetModes()
for i = 1, #modes do
local mode = modes[i]
wipe(info)
info.text = mode.moduleName
info.checked = (Skada.db.profile.report.mode == mode.moduleName)
info.func = function()
Skada.db.profile.report.mode = mode.moduleName
end
UIDropDownMenu_AddButton(info, level)
end
elseif UIDROPDOWNMENU_MENU_VALUE == "segment" then
wipe(info)
info.text = L["Total"]
info.func = function()
Skada.db.profile.report.set = "total"
end
info.checked = (Skada.db.profile.report.set == "total")
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.text = L["Current"]
info.func = function()
Skada.db.profile.report.set = "current"
end
info.checked = (Skada.db.profile.report.set == "current")
UIDropDownMenu_AddButton(info, level)
sets = Skada:GetSets()
for i = 1, #sets do
local set = sets[i]
wipe(info)
info.text = Skada:GetSetLabel(set)
info.func = function()
Skada.db.profile.report.set = i
end
info.checked = (Skada.db.profile.report.set == i)
UIDropDownMenu_AddButton(info, level)
end
end
end
end
local x, y
self.skadamenu.point, x, y = getDropdownPoint()
ToggleDropDownMenu(1, nil, self.skadamenu, "UIParent", x, y)
end
function Skada:SegmentMenu(window)
if self.testMode then return end
self.segmentsmenu = self.segmentsmenu or CreateFrame("Frame", "SkadaWindowButtonsSegments", UIParent, "UIDropDownMenuTemplate")
self.segmentsmenu.displayMode = "MENU"
self.segmentsmenu.win = window
self.segmentsmenu.initialize = self.segmentsmenu.initialize or function(self, level)
if not level or not self.win then return end
local info = UIDropDownMenu_CreateInfo()
wipe(info)
info.text = L["Total"]
info.func = function()
self.win:set_selected_set("total")
Skada:UpdateDisplay()
end
info.checked = (self.win.selectedset == "total")
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.text = L["Current"]
info.func = function()
self.win:set_selected_set("current")
Skada:UpdateDisplay()
end
info.checked = (self.win.selectedset == "current")
UIDropDownMenu_AddButton(info, level)
if #Skada.char.sets > 0 then
wipe(info)
info.disabled = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
sets = Skada:GetSets()
for i = 1, #sets do
local set = sets[i]
wipe(info)
info.text = Skada:GetSetLabel(set)
info.func = function()
self.win:set_selected_set(i)
Skada:UpdateDisplay()
end
info.checked = (self.win.selectedset == i)
if set.gotboss then
info.colorCode = set.success and "|cff19ff19" or "|cffff1919"
elseif set.type == "pvp" or set.type == "arena" then
info.colorCode = "|cffffd100"
end
UIDropDownMenu_AddButton(info, level)
end
end
end
local x, y
self.segmentsmenu.point, x, y = getDropdownPoint()
ToggleDropDownMenu(1, nil, self.segmentsmenu, "UIParent", x, y)
end
do
local categorized, categories
local function sort_categories(a, b)
local a_score = (a == OTHER) and 1000 or 0
local b_score = (b == OTHER) and 1000 or 0
a_score = a_score + (sbyte(a, 1) * 10) + sbyte(a, 1)
b_score = b_score + (sbyte(b, 1) * 10) + sbyte(b, 1)
return a_score < b_score
end
function Skada:ModeMenu(window)
self.modesmenu = self.modesmenu or CreateFrame("Frame", "SkadaWindowButtonsModes", UIParent, "UIDropDownMenuTemplate")
-- so we call it only once.
if categorized == nil then
categories, categorized = {}, {}
modes = Skada:GetModes()
for i = 1, #modes do
local mode = modes[i]
categorized[mode.category] = categorized[mode.category] or {}
categorized[mode.category][#categorized[mode.category] + 1] = mode
if not tContains(categories, mode.category) then
categories[#categories + 1] = mode.category
end
end
tsort(categories, sort_categories)
end
self.modesmenu.displayMode = "MENU"
self.modesmenu.win = window
self.modesmenu.initialize = self.modesmenu.initialize or function(self, level)
if not level or not self.win then return end
local info = UIDropDownMenu_CreateInfo()
if level == 1 then
if #categories > 0 then
for i = 1, #categories do
local category = categories[i]
wipe(info)
info.text = category
info.value = category
info.hasArrow = 1
info.notCheckable = 1
if self.win and self.win.selectedmode and (self.win.selectedmode.category == category or (self.win.parentmode and self.win.parentmode.category == category)) then
info.colorCode = "|cffffd100"
end
UIDropDownMenu_AddButton(info, level)
end
wipe(info)
info.disabled = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
end
-- Close menu item
wipe(info)
info.text = CLOSE
info.func = function()
CloseDropDownMenus()
end
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
elseif level == 2 and categorized[UIDROPDOWNMENU_MENU_VALUE] then
for i = 1, #categorized[UIDROPDOWNMENU_MENU_VALUE] do
local mode = categorized[UIDROPDOWNMENU_MENU_VALUE][i]
wipe(info)
if Skada.db.profile.moduleicons and mode.metadata and mode.metadata.icon then
info.text = format(iconName, mode.metadata.icon, mode.moduleName)
else
info.text = mode.moduleName
end
info.func = function()
self.win:DisplayMode(mode)
CloseDropDownMenus()
end
if self.win and self.win.selectedmode and (self.win.selectedmode == mode or self.win.parentmode == mode) then
info.checked = 1
info.colorCode = "|cffffd100"
end
UIDropDownMenu_AddButton(info, level)
end
end
end
local x, y
self.modesmenu.point, x, y = getDropdownPoint()
ToggleDropDownMenu(1, nil, self.modesmenu, "UIParent", x, y)
end
end
do
local strtrim = strtrim or string.trim
local UnitExists, UnitName = UnitExists, UnitName
-- handles reporting
local function DoReport(window, barid)
local mode = Skada.db.profile.report.mode
local set = Skada.db.profile.report.set
local channel = Skada.db.profile.report.channel
local chantype = Skada.db.profile.report.chantype
local number = Skada.db.profile.report.number
if channel == "whisper" then
channel = Skada.db.profile.report.target
if channel and #strtrim(channel) == 0 then
channel = nil
end
elseif channel == "target" then
if UnitExists("target") then
local toon, realm = UnitName("target")
if realm and #realm > 0 then
channel = toon .. "-" .. realm
else
channel = toon
end
else
channel = nil
end
end
if channel and chantype and mode and set and number then
Skada:Report(channel, chantype, mode, set, number, window, barid)
-- hide report window if shown.
if Skada.reportwindow and Skada.reportwindow:IsShown() then
Skada.reportwindow:Hide()
end
else
Skada:Print("Error: Whisper target not found")
end
end
local function DestroyWindow()
if Skada.reportwindow then
-- remove AceGUI hacks before recycling the widget
local frame = Skada.reportwindow
frame.LayoutFinished = frame.orig_LayoutFinished
frame.frame:SetScript("OnKeyDown", nil)
frame.frame:EnableKeyboard(false)
frame:ReleaseChildren()
frame:Release()
Skada.reportwindow = nil
end
end
local function CreateReportWindow(window)
Skada.reportwindow = AceGUI:Create("Window")
local frame = Skada.reportwindow
frame:SetLayout("List")
frame:EnableResize(false)
frame:SetWidth(225)
frame:SetPoint("CENTER", UIParent, "CENTER", 0, 0)
if window then
frame:SetTitle(L["Report"] .. format(" - %s", window.db.name))
else
frame:SetTitle(L["Report"])
end
frame:SetCallback("OnClose", function(widget, callback) DestroyWindow() end)
-- make the frame closable with Escape button
_G.SkadaReportWindow = frame.frame
UISpecialFrames[#UISpecialFrames + 1] = "SkadaReportWindow"
-- slight AceGUI hack to auto-set height of Window widget:
frame.orig_LayoutFinished = frame.LayoutFinished
frame.LayoutFinished = function(self, _, height)
frame:SetHeight(height + 57)
end
local barid
if window then
Skada.db.profile.report.set = window.selectedset
Skada.db.profile.report.mode = window.db.mode
-- report a specific line
if window.selectedset and window.selectedmode then
local linebox = AceGUI:Create("Dropdown")
linebox:SetLabel(L["Line"])
linebox:SetList({[""] = L["None"]})
for i = 1, #window.dataset do
local data = window.dataset[i]
if data and data.id and not data.ignore then
linebox:AddItem(data.id, format("%s %s", data.text or data.label, data.valuetext))
end
end
linebox:SetCallback("OnValueChanged", function(f, e, value) barid = (value ~= "") and value or nil end)
linebox:SetValue(barid or "")
frame:AddChild(linebox)
end
else
-- Mode, default last chosen or first available.
local modebox = AceGUI:Create("Dropdown")
modebox:SetLabel(L["Mode"])
modebox:SetList({})
modes = Skada:GetModes()
for i = 1, #modes do
modebox:AddItem(modes[i].moduleName, modes[i].moduleName)
end
modebox:SetCallback("OnValueChanged", function(f, e, value) Skada.db.profile.report.mode = value end)
modebox:SetValue(Skada.db.profile.report.mode or Skada:GetModes()[1])
frame:AddChild(modebox)
-- Segment, default last chosen or last set.
local setbox = AceGUI:Create("Dropdown")
setbox:SetLabel(L["Segment"])
setbox:SetList({total = L["Total"], current = L["Current"]})
sets = Skada:GetSets()
for i = 1, #sets do
setbox:AddItem(i, sets[i].name)
end
setbox:SetCallback("OnValueChanged", function(f, e, value) Skada.db.profile.report.set = value end)
setbox:SetValue(Skada.db.profile.report.set or Skada.char.sets[1])
frame:AddChild(setbox)
end
local channellist = {
whisper = {L["Whisper"], "whisper", true},
target = {L["Whisper Target"], "whisper"},
say = {CHAT_MSG_SAY, "preset"},
raid = {CHAT_MSG_RAID, "preset"},
party = {CHAT_MSG_PARTY, "preset"},
guild = {CHAT_MSG_GUILD, "preset"},
officer = {CHAT_MSG_OFFICER, "preset"},
self = {L["Self"], "self"}
}
local list = {GetChannelList()}
for i = 1, #list, 2 do
local chan = list[i + 1]
if chan ~= "Trade" and chan ~= "General" and chan ~= "LocalDefense" and chan ~= "LookingForGroup" then -- These should be localized.
channellist[chan] = {format("%s: %d/%s", L["Channel"], list[i], chan), "channel"}
end
end
-- Channel, default last chosen or Say.
local channelbox = AceGUI:Create("Dropdown")
channelbox:SetLabel(L["Channel"])
channelbox:SetList({})
for chan, kind in pairs(channellist) do
channelbox:AddItem(chan, kind[1])
end
local origchan = Skada.db.profile.report.channel or "say"
if not channellist[origchan] then
origchan = "say"
end
channelbox:SetValue(origchan)
channelbox:SetCallback("OnValueChanged", function(f, e, value)
Skada.db.profile.report.channel = value
Skada.db.profile.report.chantype = channellist[value][2]
if channellist[origchan][3] ~= channellist[value][3] then
-- redraw in-place to add/remove whisper widget
local point, relativeTo, relativePoint, xOfs, yOfs = frame:GetPoint()
DestroyWindow()
CreateReportWindow(window)
Skada.reportwindow:SetPoint(point, relativeTo, relativePoint, xOfs, yOfs)
end
end)
frame:AddChild(channelbox)
local lines = AceGUI:Create("Slider")
lines:SetLabel(L["Lines"])
lines:SetValue(Skada.db.profile.report.number ~= nil and Skada.db.profile.report.number or 10)
lines:SetSliderValues(1, 25, 1)
lines:SetCallback("OnValueChanged", function(self, event, value)
Skada.db.profile.report.number = value
end)
lines:SetFullWidth(true)
frame:AddChild(lines)
if channellist[origchan][3] then
local whisperbox = AceGUI:Create("EditBox")
whisperbox:SetLabel(L["Whisper Target"])
whisperbox:SetText(Skada.db.profile.report.target or "")
whisperbox:SetCallback("OnEnterPressed", function(box, event, text)
-- remove spaces which are always non-meaningful and can sometimes cause problems
if strlenutf8(text) == #text then
local ntext = text:gsub("%s", "")
if ntext ~= text then
text = ntext
whisperbox:SetText(text)
end
end
Skada.db.profile.report.target = text
frame.button.frame:Click()
end)
whisperbox:SetCallback("OnTextChanged", function(box, event, text)
Skada.db.profile.report.target = text
end)
whisperbox:SetFullWidth(true)
frame:AddChild(whisperbox)
end
local report = AceGUI:Create("Button")
frame.button = report
report:SetText(L["Report"])
report:SetCallback("OnClick", function()
DoReport(window, barid)
end)
report:SetFullWidth(true)
frame:AddChild(report)
end
function Skada:OpenReportWindow(window)
if self.testMode then
return -- nothing to do.
elseif IsShiftKeyDown() then
DoReport(window) -- quick report?
elseif self.reportwindow == nil then
CreateReportWindow(window)
elseif self.reportwindow:IsShown() then
self.reportwindow:Hide()
else
self.reportwindow:Show()
end
end
end
function Skada:PhaseMenu(window)
if self.testMode or not self.tempsets or #self.tempsets == 0 then return end
if self.testMode then return end
self.phasesmenu = self.phasesmenu or CreateFrame("Frame", "SkadaWindowButtonsPhases", UIParent, "UIDropDownMenuTemplate")
self.phasesmenu.displayMode = "MENU"
self.phasesmenu.initialize = self.phasesmenu.initialize or function(self, level)
if not level then return end
local info = UIDropDownMenu_CreateInfo()
for i = #Skada.tempsets, 1, -1 do
wipe(info)
local set = Skada.tempsets[i]
info.text = format(L["%s - Phase %s"], set.mobname or L["Unknown"], set.phase)
info.func = function()
if set.stopped then
Skada:ResumeSegment(nil, i)
else
Skada:StopSegment(nil, i)
end
end
info.notCheckable = 1
info.colorCode = set.stopped and "|cffff1919"
UIDropDownMenu_AddButton(info, level)
end
wipe(info)
info.disabled = 1
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
wipe(info)
info.text = L["All Segments"]
info.func = function()
if Skada.current.stopped then
Skada:ResumeSegment()
else
Skada:StopSegment()
end
end
info.colorCode = Skada.current.stopped and "|cffff1919"
info.notCheckable = 1
UIDropDownMenu_AddButton(info, level)
end
local x, y
self.phasesmenu.point, x, y = getDropdownPoint()
ToggleDropDownMenu(1, nil, self.phasesmenu, "UIParent", x, y)
end |
local localized, CHILDS, CONTENTS = ...
local M = {}
local json = require "json"
local sponsor_image
local sponsor_playlist = {}
local loaded_event_id
local playback_idx = 0
local Config = (function()
local sponsored_events = {}
util.file_watch(localized "config.json", function(raw)
print("updated config")
local config = json.decode(raw)
if #config.events == 0 then
sponsored_events = {}
else
sponsored_events = {}
for idx = 1, #config.events do
local event = config.events[idx]
local eventid = event.event_id
local playlist = event.playlist
local items = {}
for idx = 1, #playlist do
local item = playlist[idx]
items[#items + 1] = {
asset_name = localized(item.file.asset_name),
type = item.file.type,
}
end
sponsored_events["id" .. eventid] = items
end
end
end)
return {
get_sponsored_events = function() return sponsored_events end;
}
end)()
local function cycled(items, offset)
offset = offset % #items + 1
return items[offset], offset
end
local function setContains(set, key)
return set[key] ~= nil
end
local function load_sponsors_for_event(event_id)
if event_id ~= loaded_event_id then
local ok = setContains(Config.get_sponsored_events(), "id" .. event_id)
if not ok then
sponsor_image = nil
sponsor_playlist = {}
loaded_event_id = nil
playback_idx = 0
print("NO SPONSOR IMAGES FOUND FOR: " .. event_id)
else
playback_idx = 0
sponsor_playlist = Config.get_sponsored_events()["id" .. event_id]
loaded_event_id = event_id
print("LOADING SPONSOR IMAGES FOR: " .. event_id)
end
else
print("SPONSOR IMAGES ALREADY LOADED FOR: " .. loaded_event_id)
end
end
util.data_mapper {
["eventid"] = function(eventid)
load_sponsors_for_event(eventid)
end;
}
local function get_next_sponsor_image()
local item
item, playback_idx = cycled(sponsor_playlist, playback_idx)
print("------SPONSOR PLAYBACK INDEX " .. playback_idx);
print("Next sponsor image: " .. item.asset_name)
local success, asset = pcall(resource.open_file, item.asset_name)
if not success then
print("CANNOT GRAB ASSET: ", asset)
return
end
return {
item = item,
asset = asset
}
end
print "Sponsor image player init"
function M.has_content()
if #sponsor_playlist > 0 then
return true
end
return false
end
function M.get_surface()
if M.has_content() then
local next_asset = get_next_sponsor_image()
local type = next_asset.item.type
if (type == "video") then
return resource.load_video {
file = next_asset.asset;
audio = false;
looped = false;
paused = false;
}
elseif (type == "image") then
return resource.load_image(next_asset.asset)
end
end
end
function M.unload()
--print "sub module is unloaded"
end
function M.content_update(name)
--print("sub module content update", name)
end
function M.content_remove(name)
--print("sub module content delete", name)
end
return M
|
require "sys"
local loader = {}
loader.load = function(path)
if global_config:get_integer("FeatureToggle.EnableShowInternalAttributeId", 0) ~= 1 then
log.warn('failed: diable')
return false
end
loader.dll = sys.load_library(path)
return loader.dll ~= nil
end
loader.unload = function()
if loader.dll then
sys.unload_library(loader.dll)
loader.dll = nil
end
end
return loader
|
local fio = require('fio')
local t = require('luatest')
local helpers = require('test.helper')
local etcd2_client = require('cartridge.etcd2-client')
local stateboard_client = require('cartridge.stateboard-client')
local g_etcd2 = t.group('integration.failover_stateful.etcd2_ordinal_changed')
local g_stateboard = t.group('integration.failover_stateful.stateboard_ordinal_changed')
local core_uuid = helpers.uuid('c')
local C1; local core_1_uuid = helpers.uuid('c', 'c', 1)
local storage1_uuid = helpers.uuid('b', 1)
local storage1_1_uuid = helpers.uuid('b', 'b', 1)
local storage1_2_uuid = helpers.uuid('b', 'b', 2)
local storage1_3_uuid = helpers.uuid('b', 'b', 3)
local storage2_uuid = helpers.uuid('d', 2)
local storage2_1_uuid = helpers.uuid('d', 'd', 1)
local storage2_2_uuid = helpers.uuid('d', 'd', 2)
local function setup_cluster(g)
g.cluster = helpers.Cluster:new({
datadir = g.datadir,
use_vshard = true,
server_command = helpers.entrypoint('srv_basic'),
cookie = require('digest').urandom(6):hex(),
replicasets = {
{
alias = 'core-1',
uuid = core_uuid,
roles = {'vshard-router', 'failover-coordinator'},
servers = {
{alias = 'core-1', instance_uuid = core_1_uuid},
},
},
{
alias = 'storage-1',
uuid = storage1_uuid,
roles = {'vshard-storage'},
servers = {
{alias = 'storage-1-leader', instance_uuid = storage1_1_uuid},
{alias = 'storage-1-replica', instance_uuid = storage1_2_uuid},
{alias = 'storage-1-replica-2', instance_uuid = storage1_3_uuid},
},
},
{
alias = 'storage-2',
uuid = storage2_uuid,
roles = {'vshard-storage'},
servers = {
{alias = 'storage-1-leader', instance_uuid = storage2_1_uuid},
{alias = 'storage-1-replica', instance_uuid = storage2_2_uuid},
},
},
},
})
C1 = g.cluster:server('core-1')
C1.state_provider = 'etcd'
g.cluster:start()
end
g_stateboard.before_all(function()
local g = g_stateboard
g.datadir = fio.tempdir()
g.kvpassword = require('digest').urandom(6):hex()
g.state_provider = helpers.Stateboard:new({
command = helpers.entrypoint('srv_stateboard'),
workdir = fio.pathjoin(g.datadir, 'stateboard'),
net_box_port = 14401,
net_box_credentials = {
user = 'client',
password = g.kvpassword,
},
env = {
TARANTOOL_LOCK_DELAY = 2,
TARANTOOL_PASSWORD = g.kvpassword,
},
})
g.state_provider:start()
g.client = stateboard_client.new({
uri = 'localhost:' .. g.state_provider.net_box_port,
password = g.kvpassword,
call_timeout = 1,
})
setup_cluster(g)
t.assert(g.cluster.main_server:call(
'package.loaded.cartridge.failover_set_params',
{{
mode = 'stateful',
state_provider = 'tarantool',
tarantool_params = {
uri = g.state_provider.net_box_uri,
password = g.kvpassword,
},
}}
))
end)
g_etcd2.before_all(function()
local g = g_etcd2
local etcd_path = os.getenv('ETCD_PATH')
t.skip_if(etcd_path == nil, 'etcd missing')
local URI = 'http://127.0.0.1:14001'
g.datadir = fio.tempdir()
g.state_provider = helpers.Etcd:new({
workdir = fio.tempdir('/tmp'),
etcd_path = etcd_path,
peer_url = 'http://127.0.0.1:17001',
client_url = 'http://127.0.0.1:14001',
})
g.state_provider:start()
g.client = etcd2_client.new({
prefix = 'failover_stateful_test',
endpoints = {URI},
lock_delay = 3,
username = '',
password = '',
request_timeout = 1,
})
setup_cluster(g)
t.assert(g.cluster.main_server:call(
'package.loaded.cartridge.failover_set_params',
{{
mode = 'stateful',
state_provider = 'etcd2',
etcd2_params = {
prefix = 'failover_stateful_test',
endpoints = {URI},
lock_delay = 3,
},
}}
))
end)
local function after_all(g)
g.cluster:stop()
g.state_provider:stop()
fio.rmtree(g.state_provider.workdir)
fio.rmtree(g.datadir)
end
g_stateboard.after_all(function() after_all(g_stateboard) end)
g_etcd2.after_all(function() after_all(g_etcd2) end)
local function add(name, fn)
g_stateboard[name] = fn
g_etcd2[name] = fn
end
local q_promote = [[
return require('cartridge').failover_promote(...)
]]
g_stateboard.before_test('test_ordinal_changed', function()
for _, instance in ipairs(g_stateboard.cluster.servers) do
instance:exec(function()
local fiber = require'fiber'
rawset(_G, 'netbox_call', package.loaded.errors.netbox_call)
package.loaded.errors.netbox_call = function(conn, fn, ...)
if fn == 'set_vclockkeeper' then
fiber.sleep(1)
end
return _G.netbox_call(conn, fn, ...)
end
end)
end
end)
g_stateboard.after_test('test_ordinal_changed', function()
for _, instance in ipairs(g_stateboard.cluster.servers) do
instance:exec(function()
package.loaded.errors.netbox_call = _G.netbox_call
end)
end
end)
g_etcd2.before_test('test_ordinal_changed', function()
for _, instance in ipairs(g_etcd2.cluster.servers) do
instance:exec(function()
rawset(_G, 'test_etcd2_client_ordinal_errnj', true)
end)
end
end)
g_etcd2.after_test('test_ordinal_changed', function()
for _, instance in ipairs(g_etcd2.cluster.servers) do
instance:exec(function()
rawset(_G, 'test_etcd2_client_ordinal_errnj', nil)
end)
end
end)
add('test_ordinal_changed', function()
helpers.retrying({}, function()
local ok, err = C1:eval(q_promote, {
{[storage1_uuid] = storage1_2_uuid,
[storage2_uuid] = storage2_2_uuid},
{force_inconsistency = false}
})
t.assert_equals(ok, true, err)
t.assert_not(err)
end)
local ok, err = C1:eval(q_promote, {
{[core_uuid] = core_1_uuid,
[storage1_uuid] = storage1_1_uuid,
[storage2_uuid] = storage2_1_uuid},
{
force_inconsistency = true,
skip_error_on_change = C1.state_provider == 'etcd',
}
})
t.assert_equals(ok, true, err)
t.assert_not(err)
end)
|
-- tests des routines trigonométriques pour NodeMCU
print("\ntest_trigo1.lua zf1808201.1758 \n")
-- chargement des routines trigonométriques
dofile("trigo3.lua")
for i = 0, 4*math.pi, 4*math.pi/64 do
a=i
b=math.tan(a)
print("arctangente: "..a..", "..b..", "..math.atan(b)..", "..zatan(b)..", "..math.atan(b)/zatan(b))
-- print("sinus: "..a..", "..math.sin(a)..", "..zsin(a)..", "..math.sin(a)/zsin(a))
-- print("cosinus: "..a..", "..math.cos(a)..", "..zcos(a)..", "..math.cos(a)/zcos(a))
-- print("tangente: "..a..", "..math.tan(a)..", "..ztan(a)..", "..math.tan(a)/ztan(a))
b=math.sin(a)
-- print("arcsinus: "..a..", "..b..", "..math.asin(b)..", "..zasin(b)..", "..math.asin(b)/zasin(b))
b=math.cos(a)
-- print("arccosinus: "..a..", "..b..", "..math.acos(b)..", "..zacos(b)..", "..math.acos(b)/zacos(b))
end
print("\n")
y=2.5525440310417
print("y: "..y)
x=math.cos(y)
print("x: "..x)
print("math.acos: "..math.acos(x))
z=math.sqrt(1-x*x)/x
print("z: "..z)
print("zatan: "..zatan(z))
--
|
-----------------------------------
-- Area: Ru'Lud Gardens
-- NPC: Recruitment Moogle
-- Standard Info NPC
-----------------------------------
local ID = require("scripts/zones/RuLude_Gardens/IDs")
require("scripts/globals/settings")
-----------------------------------
function onTrade(player, npc, trade)
local gil = trade:getGil()
local count = trade:getItemCount()
local item = {
20573, -- 1- Aern Dagger 20573
20577, -- 2- Chicken Knife II 20577
20569, -- 3- Esikuva 20569
20570, -- 4- Norgish Dagger 20570
20576, -- 5- Qutrub Knife 20576
20674, -- 6- Aern Sword 20674
18912, -- 7- Ark Saber 18912
18913, -- 8- Ark Sword 18913
20665, -- 9- Kam'lanaut's Sword 20665
21608, -- 10- Onion Sword II 21608
21609, -- 11- Save the Queen II 21609
21658, -- 12- Brave Blade II 21658
21682, -- 13- Lament 21682
21681, -- 14- Ophidian Sword 21681
21742, -- 15- Aern Axe 21742
18545, -- 16- Ark Tabar 18545
21741, -- 17- Demonic Axe 21741
21745, -- 18- Dullahan Axe 21745
21744, -- 19- Gramk's Axe 21744
21761, -- 20- Za'Dha Chopper 21761
18563, -- 21- Ark Scythe 18563
20909, -- 22- Hoe 20909
21860, -- 23- Aern Spear 21860
20933, -- 24- Hotengeki 20933
21862, -- 25- Mizukage-no-naginata 21862
21863, -- 26- Tzee Xicu's Blade 21863
18464, -- 27- Ark Tachi 18464
17831, -- 28- Hardwood Katana 17831
18436, -- 29- Lotus Katana 18436
18441, -- 30- Shinai 18441
17830, -- 31- Wooden Katana 17830
22065, -- 32- Aern Staff 22065
18600, -- 33- Caver's Shovel 18600
22072, -- 34- Lamia Staff 22072
21154, -- 35- Malice Masher +1 21154
22070, -- 36- Ranine Staff 22070
17565, -- 37- Trick Staff 17565
18846, -- 38- Battledore 18846
22005, -- 39- Burrower's Wand 22005
18866, -- 40- Club Hammer 18866
22039, -- 41- Floral Hagoita 22039
21118, -- 42- Green Spriggan Club 21118
21113, -- 43- Purple Spriggan Club 21113
21114, -- 44- Red Spriggan Club 21114
17032, -- 45- Gobbie Gavel 17032
21086, -- 46- Heartstopper 21086
22020, -- 47- Jingly Rod +1 22020
18871, -- 48- Kitty Rod 18871
18869, -- 49- Lady Bell +1 18869
18880, -- 50- Maestro's Baton 18880
18881, -- 51- Melomane Mallet 18881
17031, -- 52- Shell Scepter 17031
22004, -- 53- Soulflayer's Wand 22004
22112, -- 54- Mizukage-no-yumi 22112
21272, -- 55- Troll Gun 21272
26409, -- 56- Dullahan Shield 26409
28661, -- 57- Glinting Shield 28661
26412, -- 58- Kam'lanaut's Shield 26412
28670, -- 59- Leafkin Shield 28670
28651, -- 60- Metal Slime Shield 28651
28650, -- 61- She-slime Shield 28650
28655, -- 62- Slime Shield 28655
25606, -- 63- Agent Hood (Male only) 25606
25604, -- 64- Buffalo Cap 25604
23737, -- 65- Byakko Masque 23737
26694, -- 66- Cassie's Cap 26694
26730, -- 67- Celeste Cap 26730
11812, -- 68- Charity Cap 11812
11500, -- 69- Chocobo Beret 11500
26729, -- 70- Corolla 26729
25669, -- 71- Crab Cap +1 25669
25648, -- 72- Curmudgeon's Helmet 25648
26728, -- 73- Frosty Cap 26728
27716, -- 74- Green Moogle Masque 27716
25649, -- 75- Gazer's Helmet 25649
27715, -- 76- Goblin Masque 27715
25587, -- 77- Kakai Cap +1 25587
23730, -- 78- Karakul Cap 23730
27759, -- 79- Korrigan Beret 27759
25639, -- 80- Korrigan Masque 25639
26704, -- 81- Lycopodium Masque +1 26704
15204, -- 82- Mandragora Beret 15204
27714, -- 83- Mirth Masquette 27714
10429, -- 84- Moogle Masque 10429
12491, -- 85- Onion Cap (WAR Only) 12491
25638, -- 86- Pachypodium Masque 25638
25650, -- 87- Retching Helmet 25650
23731, -- 88- Royal Chocobo Beret 23731
10875, -- 89- Snowman Cap 10875
11485, -- 90- Spelunker's Helm 11485
25607, -- 91- Starlet Flower (Female Only) 25607
27734, -- 92- Straw Hat (Female Only) 27734
27718, -- 93- Worm Masque +1 27718
26520, -- 94- Akitu Shirt 26520
27906, -- 95- Chocobo Suit +1 27906
25755, -- 96- Crustacean Shirt 25755
26524, -- 97- Gil Nabber Shirt 26524
27866, -- 98- Goblin Suit 27866
26518, -- 99- Jody Shirt 26518
26519, -- 100- Mandragora Shirt 26519
26545, -- 101- Mithkabob Shirt 26545
27904, -- 102- Morass Tunic 27904
26964, -- 103- Pupil's Camisa 26964
26946, -- 104- Pupil's Shirt 26946
11320, -- 105- Skeleton Robe 11320
27111, -- 106- Agent Cuffs (Male Only) 27111
27112, -- 107- Starlet Gloves (Female Only) 27112
27296, -- 108- Agent Pants (Male Only) 27296
28185, -- 109- Alliance Pants 28185
28186, -- 110- Morass Pants 28186
25850, -- 111- Pink Subligar 25850
27281, -- 112- Pupil's Trousers 27281
27297, -- 113- Starlet Skirt (Female Only) 27297
27467, -- 114- Agent Boots (Male Only) 27467
28324, -- 115- Alliance Boots 28324
28325, -- 116- Morass Boots 28325
27455, -- 117- Pupil's Shoes 27455
27468, -- 118- Starlet Boots (Female Only) 27468
27733} -- 119- Straw Hat (Male Only) 27733
if (trade:hasItemQty(8715, 1) and gil > 0 and gil < 120 and count == 2) then
player:tradeComplete()
player:addItem(item[gil])
player:messageSpecial(ID.text.ITEM_OBTAINED, item[gil])
player:addGil(gil)
player:messageSpecial(ID.text.GIL_OBTAINED, gil)
end
end
function onTrigger(player, npc)
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
|
-- Plugins start here, source from Packer:
return require('packer').startup(function(use)
-- Alpha (dashboard) for neovim
use { 'goolord/alpha-nvim',
config = require('configuration.screen'),
}
-- Packer can manage itself
use 'wbthomason/packer.nvim'
--
-- LSP
--
-- Rooter, go to project working directory automatically
use { 'ahmedkhalf/project.nvim',
config = require('configuration.project')
}
-- Unusable variables and functions markup.
use { 'narutoxy/dim.lua',
--config = require('configuration.dim')
}
-- CPP modern syntax.
use 'bfrg/vim-cpp-modern'
-- LSP auto-complet
use 'neovim/nvim-lspconfig'
use 'hrsh7th/vim-vsnip'
-- Zen Mode
use {
"folke/zen-mode.nvim",
config = require('configuration.zen-mode')
}
-- Dim
use {
"folke/twilight.nvim",
config = require('configuration.twilight')
}
-- Signs for built-in marks.
use { 'chentau/marks.nvim',
config = require('configuration.marks')
}
-- Signature for LSP
--use { 'ray-x/lsp_signature.nvim',
-- config = require('configuration.lsp_signature')
--}
-- Indent align.
use 'godlygeek/tabular'
--
-- Menu
--
-- Snippets for nvim-cmp
use {
"rafamadriz/friendly-snippets",
event = "InsertEnter",
}
-- Completion menu
use { 'hrsh7th/nvim-cmp',
config = require('configuration.cmp-config'),
requires = {
{ "octaltree/cmp-look" },
--
{ "hrsh7th/cmp-nvim-lsp" },
--
{ "hrsh7th/cmp-nvim-lua" },
-- Buffer words.
{ "hrsh7th/cmp-buffer" },
-- Path autocompletion.
{ "hrsh7th/cmp-path" },
--
{ "hrsh7th/cmp-cmdline" },
--
{ "saadparwaiz1/cmp_luasnip" },
--
{ "hrsh7th/vim-vsnip" },
--
{ "hrsh7th/cmp-vsnip" },
--
-- Signature for functions.
{ 'hrsh7th/cmp-nvim-lsp-signature-help' },
--
{ "hrsh7th/vim-vsnip-integ" },
-- FIXIT: Fork to calculate simple arithmetic expressions and show on the menu.
{ "gabrielbdsantos/cmp-calc" },
-- Emoji
{ "hrsh7th/cmp-emoji" },
},
}
-- Snippets for lua
use { "L3MON4D3/LuaSnip",
config = "luasnip",
}
-- Icons on menu
use 'onsails/lspkind-nvim'
-- NIM support (syntax, folding).
use 'baabelfish/nvim-nim'
-- File-tree manager.
use { '/home/iris/Git/Forking/neo-tree.nvim/',
config = require('configuration.neo-tree'),
requires = {
"nvim-lua/plenary.nvim",
"kyazdani42/nvim-web-devicons", -- not strictly required, but recommended
"MunifTanjim/nui.nvim"
},
}
--
-- GIT
--
-- Show signs of GIT written in lua
use { 'lewis6991/gitsigns.nvim',
requires = { 'nvim-lua/plenary.nvim' },
config = require('configuration.git-signs')
}
--
-- Movement
--
-- List registers to open.
use 'tversteeg/registers.nvim'
-- Restore folds and cursor position
use 'senderle/restoreview'
-- Fold code.
use{ 'anuvyklack/pretty-fold.nvim',
config = require('configuration.pretty-fold')
}
-- Multi line like Sublime Text (My first Text Editor <3)
--use { 'mg979/vim-visual-multi',
--}
-- Start a * or # search from a visual block.
-- Parse English
use { 'jose-elias-alvarez/null-ls.nvim',
config = require('configuration.null-ls')
}
-- File manager (nnn)
--use 'mcchrish/nnn.vim'
-- Smooth scroll with neoscroll
use { 'karb94/neoscroll.nvim',
config = require('configuration.neoscroll')
}
-- File explorer
-- use { 'kyazdani42/nvim-tree.lua',
-- requires = 'kyazdani42/nvim-web-devicons',
-- config = require('configuration.nvim-tree')
-- }
-- Telescope
use { 'nvim-telescope/telescope.nvim',
requires = { {'nvim-lua/popup.nvim'}, {'nvim-lua/plenary.nvim'} },
config = require('configuration.telescope'),
}
--
-- Appearance
--
-- Scrollbar with LSP
use { 'petertriho/nvim-scrollbar',
config = require('configuration.nvim-scrollbar'),
requires = 'kevinhwang91/nvim-hlslens'
}
-- Status information for LSP.
--use { 'j-hui/fidget.nvim',
-- config = require('fidget').setup{}
--}
-- Special words highlited in comments
use { "folke/todo-comments.nvim",
requires = "nvim-lua/plenary.nvim",
config = require('configuration.todo-comments')
}
-- EWW parser for Vim
use 'elkowar/yuck.vim'
-- Indent lines without conceal!!!
-- use { "lukas-reineke/indent-blankline.nvim",
-- config = require('configuration.indent-blankline')
-- }
-- Close buffer without messing up with the window.
use 'famiu/bufdelete.nvim'
-- Treesitter (more highlight for syntax_on)
use { 'nvim-treesitter/nvim-treesitter',
run = ':TSUpdate',
}
-- Move faster between context.
use { 'andymass/vim-matchup',
config = require('configuration.vim-matchup')
}
-- Show your functions/classes at the top of the screen.
-- use 'romgrk/nvim-treesitter-context'
-- Tabs (galaxyline)
use { 'glepnir/galaxyline.nvim',
branch = 'main',
-- your statusline
config = require('configuration.galaxyline'),
-- some optional icons
requires = {'kyazdani42/nvim-web-devicons', opt = true}
}
-- Tabs of buffers
use { 'akinsho/bufferline.nvim',
config = require('configuration.bufferline'),
requires = 'kyazdani42/nvim-web-devicons'
}
-- Colorizer for strings.
use { 'RRethy/vim-hexokinase',
config = require('configuration.vim-hexokinase'),
run = 'cd ~/.local/share/nvim/site/pack/packer/start/vim-hexokinase && make hexokinase'
}
-- Theme (dark and light)
use '/home/iris/Git/Projects/arcoiris-nvim-theme'
end)
|
--Start of Global Scope---------------------------------------------------------
print('AppEngine Version: ' .. Engine.getVersion())
assert(Shape3D, 'Shape3D API not present, check device capabilities')
-- Creating viewer
local viewer = View.create("viewer3D1")
-- Setting up graphical overlay attributes
local shapeDecoration = View.ShapeDecoration.create()
shapeDecoration:setLineColor(0, 255, 0) -- Green
shapeDecoration:setPointSize(16)
shapeDecoration:setLineWidth(3)
shapeDecoration:setFillColor(0, 200, 0) -- Darker Green
local intersectionDecoration = View.ShapeDecoration.create()
intersectionDecoration:setLineColor(255, 0, 0) -- Red
intersectionDecoration:setLineWidth(5)
intersectionDecoration:setPointType('DOT')
intersectionDecoration:setPointSize(16)
local pointDecoration = View.ShapeDecoration.create()
pointDecoration:setLineColor(0, 0, 255) -- Blue
pointDecoration:setPointType('DOT')
pointDecoration:setPointSize(16)
--End of Global Scope-----------------------------------------------------------
--Start of Function and Event Scope---------------------------------------------
local function main()
viewer:clear()
local w = 300
local pc = PointCloud.create()
pc:appendPoint(0, 0, 0)
pc:appendPoint(0, 0, w)
pc:appendPoint(0, w, 0)
pc:appendPoint(0, w, w)
pc:appendPoint(w, 0, 0)
pc:appendPoint(w, 0, w)
pc:appendPoint(w, w, 0)
pc:appendPoint(w, w, w)
local pcViewId = viewer:addPointCloud(pc)
-- Line segment
local startLine = Point.create(0, 430, -200)
local endLine = Point.create(320, 50, 700)
local line = Shape3D.createLineSegment(startLine, endLine)
viewer:addShape(line, shapeDecoration, nil, pcViewId)
viewer:addShape(startLine, pointDecoration, nil, pcViewId)
viewer:addShape(endLine, pointDecoration, nil, pcViewId)
-- Ellipse
local ellipsePose = Transform.createTranslation3D(10, 50, 150)
local ellipse = Shape3D.createEllipse(40, 100, ellipsePose)
viewer:addShape(ellipse, shapeDecoration, nil, pcViewId)
-- Elliptic cylinder
local ellipticcylinderPose = Transform.createRigidAxisAngle3D({0, 1, 1}, 3.14 / 3, 150, 350, 140)
local ellipticcylinder = Shape3D.createEllipticCylinder(80, 200, 150, ellipticcylinderPose)
viewer:addShape(ellipticcylinder, shapeDecoration, nil, pcViewId)
-- Intersection points between line segment and elliptical cylinder
local linecylPts = ellipticcylinder:getIntersectionPoints(line:toLine())
for _, pt in ipairs(linecylPts) do
viewer:addShape(pt, intersectionDecoration, nil, pcViewId)
end
-- Rectangle
local rectangle = Shape3D.createRectangle(120, 300):rotateY(3.14 / 3):rotateZ(3.14 / 5):translate(0, 0, 170)
viewer:addShape(rectangle, shapeDecoration, nil, pcViewId)
-- Intersection line between the planes of the ellipse and the rectangle
-- Crop to bounding box of rectangle
local ellipseRectLine = Shape3D.getIntersectionLine(ellipse:toPlane(), rectangle:toPlane())
ellipseRectLine = ellipseRectLine:cropLine(rectangle:getBoundingBox())
viewer:addShape(ellipseRectLine, intersectionDecoration, nil, pcViewId)
-- Polygon
local polyPoints = {
Point.create(600, 200, 100),
Point.create(530, 300, 150),
Point.create(620, 505, 200),
Point.create(650, 250, 100),
Point.create(700, 300, 150),
Point.create(720, 200, 100)
}
local polygon = Shape3D.createPolygon(polyPoints)
viewer:addShape(polygon, shapeDecoration, nil, pcViewId)
-- Polyline
local polyline = Shape3D.createPolyline(polyPoints)
viewer:addShape(polyline, shapeDecoration, nil, pcViewId)
-- Sphere
local sphere = Shape3D.createSphere(120):translate(100, 150, 300)
viewer:addShape(sphere, shapeDecoration, nil, pcViewId)
-- Cone
local cone = Shape3D.createCone(100, 200):translate(0, 0, 300)
viewer:addShape(cone, shapeDecoration, nil, pcViewId)
viewer:present()
print('App finished.')
end
Script.register('Engine.OnStarted', main)
--End of Function and Event Scope--------------------------------------------------
|
-- Teenage Mutant Ninja Turtles (U)[!].rom
-- Written by QFox
-- 31 july 2008
-- Displays Hitboxes, Enemy HP, and various stats on screen
local function box(x1,y1,x2,y2,color)
-- gui.text(50,50,x1..","..y1.." "..x2..","..y2);
if (x1 > 0 and x1 < 255 and x2 > 0 and x2 < 255 and y1 > 0 and y1 < 241 and y2 > 0 and y2 < 241) then
gui.drawbox(x1,y1,x2,y2,color);
end;
end;
local function text(x,y,str)
if (x > 0 and x < 255 and y > 0 and y < 240) then
gui.text(x,y,str);
end;
end;
local function pixel(x,y,color)
if (x > 0 and x < 255 and y > 0 and y < 240) then
gui.drawpixel(x,y,color);
end;
end;
while (true) do
local stuff = 0x023C; -- start of tile data, 4 bytes each, y, ?, ?, x. every tile appears to be 10x10px
-- print boxes for all the tiles
-- invalid tiles are automatically hidden because their x/y coords are out of range, i guess
for i=0,0x30 do
x = memory.readbyte(stuff+3+(i*4));
y = memory.readbyte(stuff+(i*4));
box(x,y+1,x+7,y+16,"red");
end;
-- print player's health
local x = memory.readbyte(0x0480);
local y = memory.readbyte(0x0460);
local hp = memory.readbyte(0x0077+memory.readbyte(0x0067)); -- get health of current char, there are 4 chars and 4 healths
text(x-10,y-20,hp);
-- print enemy hp
local startx = 0x0484;
local starty = 0x0464;
local starthp = 0x0564;
for i=0,11 do
x = memory.readbyte(startx+i);
y = memory.readbyte(starty+i);
hp = memory.readbyte(starthp+i);
--box(x-5,y-5,x+5,y+5,"green"); -- their 'center', or whatever it is.
text(x-5,y-20,hp);
end;
FCEU.frameadvance();
end; |
--
-- SjoCi kockája TS3-ra / SjoCi's dice for TS3
--
local function onTextMessageEvent(serverConnectionHandlerID, targetMode, toID, fromID, fromName, fromUniqueIdentifier, message, ffIgnored)
local kezdet = string.sub(message,1,1)
if kezdet=="(" then
local dpos = string.find(message,"d")
if dpos~=nil then
if dpos<=4 then
local epos = string.find(message,")")
if epos~=nil then
if epos<=dpos+4 and epos~=dpos+1 then
local jo = 1
local szamok = {}
if string.sub(message,2,2) ~= "d" then
for i=1,dpos-2,1 do
szamok[i]=0
local szov = string.sub(message,2,dpos-1)
for j=0,9,1 do
if tonumber(string.sub(szov,i,i))==j then
szamok[i]=1
end
end
if szamok[i]==0 then
jo = 0
end
end
end
if jo==1 then
local jo2 = 1
for i=dpos+1,epos-1,1 do
szamok[i]=0
szov = string.sub(message,dpos+1,epos-1)
for j=0,9,1 do
if tonumber(string.sub(szov,i-dpos,i-dpos))==j then
szamok[i]=1
end
end
if szamok[i]==0 then
jo2 = 0
end
end
if jo2==1 then
if string.len(string.sub(message,2,dpos-1)) <= 3 or string.sub(message,2,dpos-1) == "d" then
local dice = tonumber(string.sub(message,dpos+1,epos-1))
local numberor = 1
if string.sub(message,2,2)~="d" then
numberor = tonumber(string.sub(message,2,dpos-1))
end
if dice ~= 1 and numberor<=25 then
local legkev = 1
local legtobb = dice
local csatorna = ts3.getChannelOfClient(serverConnectionHandlerID, fromID)
local koca = 0
local totalkoca = 0
local sendMsg = "[b]["..fromName.."][/b] rolled the dice [b]("..string.sub(message,2,dpos-1).."d"..dice..")[/b]:\n"
math.randomseed(tonumber(tostring(os.clock()):reverse():sub(1,6)))
math.random()
math.random()
math.random()
math.randomseed(tonumber(tostring(os.clock()):reverse():sub(1,6))+math.random())
math.random()
math.random()
math.random()
if tonumber(string.sub(message,2,dpos-1))~=1 and string.sub(message,2,2)~="d" then
for i=1,tonumber(string.sub(message,2,dpos-1)),1 do
math.random()
math.random()
math.random()
koca = math.random(dice)
sendMsg = sendMsg..i..". = "
if koca==legkev then
sendMsg = sendMsg.."[b]"..koca.."[/b] -\n"
elseif koca==legtobb then
sendMsg = sendMsg.."[b]"..koca.."[/b] !\n"
else
sendMsg = sendMsg.."[b]"..koca.."[/b]\n"
end
totalkoca = totalkoca + koca
end
sendMsg = sendMsg.."Total: [b]"..totalkoca.."[/b]"
else
math.random()
math.random()
math.random()
koca = math.random(dice)
if koca==legkev then
sendMsg = sendMsg.."[b]"..koca.."[/b] -\n"
elseif koca==legtobb then
sendMsg = sendMsg.."[b]"..koca.."[/b] !\n"
else
sendMsg = sendMsg.."[b]"..koca.."[/b]\n"
end
end
ts3.requestSendChannelTextMsg(serverConnectionHandlerID, sendMsg, csatorna)
end
end
end
end
end
end
end
end
end
return 0
end
diceroll_events = {
onTextMessageEvent = onTextMessageEvent
}
|
local awful = require('awful')
local gears = require('gears')
local wibox = require('wibox')
local beautiful = require('beautiful')
local colors = require('themes.dracula.colors')
local dpi = require('beautiful').xresources.apply_dpi
local screen_geometry = require('awful').screen.focused().geometry
local width = dpi(410)
local format_item = function(widget)
return wibox.widget {
{
{
layout = wibox.layout.align.vertical,
expand = 'none',
nil,
widget,
nil
},
margins = dpi(5),
widget = wibox.container.margin
},
shape = function(cr, width, height)
gears.shape.rounded_rect(cr, width, height, beautiful.groups_radius)
end,
bg = 'transparent',
widget = wibox.container.background
}
end
local title = wibox.widget {
{
{
spacing = dpi(0),
layout = wibox.layout.flex.vertical,
format_item(
{
layout = wibox.layout.fixed.horizontal,
spacing = dpi(16),
require('widget.dracula-icon'),
require('widget.bluetooth-center.title-text'),
}
),
},
margins = dpi(5),
widget = wibox.container.margin
},
shape = function(cr, width, height)
gears.shape.rounded_rect(cr, width, height, beautiful.groups_radius)
end,
bg = colors.alpha(colors.selection, 'F2'),
forced_width = width,
forced_height = 70,
ontop = true,
border_width = dpi(2),
border_color = colors.background,
widget = wibox.container.background,
layout,
}
local buttons = wibox.widget {
{
{
spacing = dpi(0),
layout = wibox.layout.flex.vertical,
format_item(
{
layout = wibox.layout.fixed.horizontal,
spacing = dpi(16),
require('widget.bluetooth-center.power-button'),
require('widget.bluetooth-center.devices-button'),
require('widget.bluetooth-center.search-button'),
}
),
},
margins = dpi(5),
widget = wibox.container.margin
},
shape = function(cr, width, height)
gears.shape.rounded_rect(cr, width, height, beautiful.groups_radius)
end,
bg = colors.alpha(colors.selection, 'F2'),
forced_width = 400,
forced_height = 70,
border_width = dpi(2),
border_color = colors.background,
widget = wibox.container.background,
layout,
}
local devices_text = wibox.widget {
{
{
spacing = dpi(0),
layout = wibox.layout.flex.vertical,
format_item(
{
layout = wibox.layout.fixed.horizontal,
spacing = dpi(16),
require('widget.bluetooth-center.devices-text'),
}
),
},
margins = dpi(5),
widget = wibox.container.margin
},
shape = function(cr, width, height)
gears.shape.rounded_rect(cr, width, height, beautiful.groups_radius)
end,
bg = colors.alpha(colors.selection, 'F2'),
forced_width = width,
forced_height = 70,
ontop = true,
border_width = dpi(2),
border_color = colors.background,
widget = wibox.container.background,
layout,
}
local devices_panel = wibox.widget {
{
{
spacing = dpi(0),
layout = wibox.layout.flex.vertical,
format_item(
{
layout = wibox.layout.fixed.horizontal,
spacing = dpi(16),
require('widget.bluetooth-center.devices-panel'),
}
),
},
margins = dpi(5),
widget = wibox.container.margin
},
shape = function(cr, width, height)
gears.shape.rounded_rect(cr, width, height, beautiful.groups_radius)
end,
bg = colors.alpha(colors.selection, 'F2'),
forced_width = width,
ontop = true,
border_width = dpi(2),
border_color = colors.background,
widget = wibox.container.background,
layout,
}
bluetoothCenter = wibox(
{
x = screen_geometry.width-width-dpi(8),
y = screen_geometry.y+dpi(35),
visible = false,
ontop = true,
screen = screen.primary,
type = 'splash',
height = screen_geometry.height-dpi(35),
width = width,
bg = 'transparent',
fg = '#FEFEFE',
}
)
awesome.connect_signal(
"bluetoothCenter:toggle",
function()
if bluetoothCenter.visible == false then
blue_status = true
bluetoothCenter.visible = true
elseif bluetoothCenter.visible == true then
blue_status = false
bluetoothCenter.visible = false
end
end
)
bluetoothCenter:setup {
spacing = dpi(15),
title,
buttons,
devices_text,
devices_panel,
layout = wibox.layout.fixed.vertical,
}
|
return {
Analogous = require(script.Analogous),
Complementary = require(script.Complementary),
Monochromatic = require(script.Monochromatic),
SplitComplementary = require(script.SplitComplementary),
Tetradic = require(script.Tetradic),
Triadic = require(script.Triadic),
Vibrant = require(script.Vibrant),
}
|
local types = require "resty.nettle.types.common"
local context = require "resty.nettle.types.ripemd160"
local lib = require "resty.nettle.library"
local ffi = require "ffi"
local ffi_new = ffi.new
local ffi_str = ffi.string
local setmetatable = setmetatable
local ripemd160 = setmetatable({}, {
__call = function(_, data, len)
local ctx = ffi_new(context)
lib.nettle_ripemd160_init(ctx)
lib.nettle_ripemd160_update(ctx, len or #data, data)
lib.nettle_ripemd160_digest(ctx, 20, types.uint8_t_20)
return ffi_str(types.uint8_t_20, 20)
end
})
ripemd160.__index = ripemd160
function ripemd160.new()
local self = setmetatable({ context = ffi_new(context) }, ripemd160)
lib.nettle_ripemd160_init(self.context)
return self
end
function ripemd160:update(data, len)
return lib.nettle_ripemd160_update(self.context, len or #data, data)
end
function ripemd160:digest()
lib.nettle_ripemd160_digest(self.context, 20, types.uint8_t_20)
return ffi_str(types.uint8_t_20, 20)
end
return ripemd160
|
ccs = ccs or {}
---RotationSkewFrame object
---@class RotationSkewFrame : SkewFrame
local RotationSkewFrame = {}
ccs.RotationSkewFrame = RotationSkewFrame
--------------------------------
--
---@return RotationSkewFrame
function RotationSkewFrame:create() end
--------------------------------
--
---@return Frame
function RotationSkewFrame:clone() end
--------------------------------
--
---@return RotationSkewFrame
function RotationSkewFrame:RotationSkewFrame() end
return RotationSkewFrame |
if(_G["WM"] == nil) then WM = (function(m,h) h(nil,(function() end), (function(e) _G[m] = e end)) end) end -- WLPM MM fallback
-- Warcraft 3 eventDispatcher module by ScorpioT1000 / 2020
WM("eventDispatcher", function(import, export, exportDefault)
local handlers = {}
exportDefault({
-- Subscribe to an event with the callback function that takes an event param
-- The event param is an object with "data", "name" and "stopPropagation" properties
-- You can set event.stopPropagation = true inside the callback
-- to break current dispatch loop
--- @param eventName string
--- @param callback function
on = function(eventName, callback)
if(handlers[eventName] == nil) then
handlers[eventName] = {}
end
table.insert(handlers[eventName], callback)
end,
-- Unsubscribe from the event. Specify the same function ref from on() to avoid every subscription removal
--- @param eventName string
--- @param specialCallback function
off = function(eventName, specialCallback)
local callbacks = handlers[eventName]
if(callbacks ~= nil) then
if(specialCallback ~= nil) then
local counter = #callbacks
for i = #callbacks, 1, -1 do
if(callbacks[i] == specialCallback) then
table.remove(callbacks, i)
end
end
else
handlers[eventName] = nil
end
end
end,
-- Dispatch the event and pass a data to it (optional)
--- @param eventName string
--- @param data
dispatch = function(eventName, data)
local callbacks = handlers[eventName]
local event = {
name = eventName,
data = data,
stopPropagation = false
}
if(callbacks == nil) then
return
end
for i,callback in pairs(callbacks) do
callback(event)
if(event.stopPropagation) then
return
end
end
end,
-- Removes all handlers
clear = function()
handlers = {}
end
})
end) |
Global("Locales", {})
Global("PLAYER_PRODUCER", 1)
Global("UNIT_PRODUCER", 2)
Global("SPELL_PRODUCER", 3)
Global("ABILITY_PRODUCER", 4)
Global("BUFF_PRODUCER", 5)
Global("UNKNOWN_PRODUCER", 6)
local localeGroup = common.GetAddonRelatedTextGroup(common.GetLocalization()) or common.GetAddonRelatedTextGroup("eng")
function getLocale()
return setmetatable(Locales,
{__index = function(t,k)
if type(k) == "number" then
if k == PLAYER_PRODUCER then
return localeGroup:GetText("PLAYER_PRODUCER")
elseif k == UNIT_PRODUCER then
return localeGroup:GetText("UNIT_PRODUCER")
elseif k == SPELL_PRODUCER then
return localeGroup:GetText("SPELL_PRODUCER")
elseif k == ABILITY_PRODUCER then
return localeGroup:GetText("ABILITY_PRODUCER")
elseif k == BUFF_PRODUCER then
return localeGroup:GetText("BUFF_PRODUCER")
elseif k == UNKNOWN_PRODUCER then
return localeGroup:GetText("UNKNOWN_PRODUCER")
else
return nil
end
end
if localeGroup:HasText(k) then
return localeGroup:GetText(k)
end
end
}
)
end
|
local schema = require "kong.plugins.librato-analytics.schema"
describe("kong.plugins.librato-analytics.schema", function()
it("should return a table", function()
assert.is.equal("table", type(schema))
end)
describe(".fields", function()
it("is a table", function()
assert.is.equal("table", type(schema.fields))
end)
it("a Librato username is optional", function()
assert.is.False(schema.fields.username.required)
end)
it("a Librato token is optional", function()
assert.is.False(schema.fields.token.required)
end)
it("has the default host for Librato", function()
assert.is.equal("metrics-api.librato.com", schema.fields.host.default)
end)
it("has the default path for Librato", function()
assert.is.equal("/v1/metrics", schema.fields.path.default)
end)
end)
end)
|
local LevelMgr = {}
local Level = require("Game.Logic.Level")
-- 点号相当于静态方法
-- 冒号相当于成员方法
function LevelMgr.Initialize(self)
-- body
self.currentLevel = nil
EventMgr.RegisterEvent(1,1, LevelMgr.TestEvent)
end
function LevelMgr.TestEvent(self, name)
UnityEngine.Debug("LevelMgr TestEvent"..name)
end
function LevelMgr:SetLevelClass(level)
self.currentLevel = level
end
function LevelMgr:Start()
if self.currentLevel ~= nil then
return
end
local currentFloor = 1
local m = PlayerMgr:GetMainPlayer()
local nextLevel = m:GetFloor() + 1
local isHave = false
if isHave then
-- 初始化关卡数据
local cfg = ConfigMgr.GetItem("Level", nextLevel)
local level = Level:new(cfg)
self:SetLevelClass(level)
level:Start()
-- m:SetFloor(nextLevel)
end
end
function LevelMgr:End()
if self.currentLevel == nil then
return
end
self.currentLevel:Destroy()
end
function LevelMgr:Update(delta)
if self.currentLevel ~= nil then
self.currentLevel:Update(delta)
end
end
return LevelMgr |
if mods["space-exploration"] and not mods["Krastorio2"] then
if settings.startup["cs2-tweaks-sand-water-landfill"].value == true then
local data_util = require("__space-exploration-postprocess__/data_util")
local result_count = 1
if settings.startup["cs2-tweaks-more-landfill"].value == true then
result_count = 10
end
data:extend({
{
type = "recipe",
name = "landfill-2",
localized_name = { "item-name.landfill" },
localized_description = { "item-description.landfill" },
energy_required = 1,
enabled = false,
category = "crafting-with-fluid",
icons = {
{icon = data.raw.item.landfill.icon, icon_size = data.raw.item.landfill.icon_size},
{icon = data.raw.item.sand.icon, icon_size = data.raw.item.sand.icon_size, scale = 0.33*64/data.raw.item.sand.icon_size},
},
ingredients =
{
{"sand", 50},
{ type = "fluid", name = "water", amount = 50 }
},
result= "landfill",
result_count = result_count,
order = "z-a-c",
allow_decomposition = false,
}
})
data_util.tech_lock_recipes("landfill", {"landfill-2"})
end
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.