content
stringlengths
5
1.05M
object_building_kashyyyk_thm_kash_arch_wood_s01 = object_building_kashyyyk_shared_thm_kash_arch_wood_s01:new { } ObjectTemplates:addTemplate(object_building_kashyyyk_thm_kash_arch_wood_s01, "object/building/kashyyyk/thm_kash_arch_wood_s01.iff")
ShadeInk.kInkRange = 10 -- kScanRadius is 20 -- make the effect the same for both teams ShadeInk.kShadeInkMarineEffect = PrecacheAsset("cinematics/shade_ink.cinematic") ShadeInk.kShadeInkAlienEffect = ShadeInk.kShadeInkMarineEffect function ShadeInk:GetUpdateTime() return 0.1 -- was 2.0 end if Server then function ShadeInk:Perform() DestroyEntitiesWithinRange("Scan", self:GetOrigin(), Scan.kScanDistance) -- FYI detectable is not the same as sighted local ents = GetEntitiesWithMixinForTeamWithinRange("Detectable", self:GetTeamNumber(), self:GetOrigin(), ShadeInk.kInkRange) for _, ent in ipairs(ents) do if ent.SetDetected then ent:SetDetected(false) end end end end if Client then function ShadeInk:Perform() local local_player = Client.GetLocalPlayer() if local_player and local_player.RemoveMarkFromTargetId then local playersInRange = GetEntitiesForTeamWithinRange("Player", self:GetTeamNumber(), self:GetOrigin(), ShadeInk.kInkRange) local data = local_player.clientLOSdata for index, player in ipairs(playersInRange) do if data.damagedAt and data.damagedAt[player:GetId()] and data.remove then data.remove[player:GetId()] = true end --local_player:RemoveMarkFromTargetId(player:GetId()) end end end end
local Effect = require 'prefabs/effects/effect' local Effects = require 'prefabs/effects/effecttype' local cmp = require 'component/common' return { Bullet = { width = 5, height = 5, add_render = function(proj) proj:add_component(cmp.Sprite, Resource.Image.Bullet) return proj end, damage = 2, destroy_effect = function(world, x, y) return Effect(world, x, y, Effects.Block({1, 1, 1}, 10, 10), { life_span = 0.1, start_scale = {1, 1}, end_scale = {0.5, 0.5} }) end, tile_hit_sound = Resource.Sound.BulletTileHit }, Sting = { width = 2, height = 2, add_render = function(proj) local canvas = love.graphics.newCanvas(10, 1) canvas:renderTo(function() lg.setColor(1, 0, 0.2, 1) lg.rectangle('fill', 0, 0, 10, 2) -- graphics.rectangle('fill', 0, 0, 4, 4) end) proj:add_component(cmp.Sprite, canvas) return proj end, damage = 1, tile_hit_sound = Resource.Sound.BulletTileHit }, Ball = { width = 2, height = 2, sx = 0.6, sy = 0.6, add_render = function(proj) local canvas = love.graphics.newCanvas(12, 12) canvas:renderTo(function() lg.setColor(1, 1, 1, 1) lg.draw(Resource.Image.Ball, 0, 0) end) proj:add_component(cmp.Sprite, canvas) return canvas end, damage = 1, destroy_effect = function(world, x, y) return Effect(world, x, y, Effects.Block({sugar.rgb('#ffc2d8')}), {life_span = 0.1, start_scale = {0.5, 0.5}}) end, tile_hit_sound = Resource.Sound.BulletTileHit } }
function divide(parametro) linha = {} n = 0 -- parametro para espaço "*l" for i in string.gmatch(io.read(parametro), "%S+") do n = n + 1 linha[n] = i end return linha end -------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------- local Rabbit = { }--criar a classe Rabbit Rabbit.__index = Rabbit function Rabbit:new(usagi) --constructor return setmetatable({usagi=usagi}, Rabbit) end function Rabbit:yume_nikki() -- Referenciamos atributos do próprio objeto utilizando “self” m=10 if self.usagi%2==0 then m=m+2 end for r=self.usagi,self.usagi+m,1 do if (r%2~=0 and r~=1) then self:saida(r) end end end function Rabbit:saida(r) io.write(string.format("%d\n",r)) end ------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------ function main() yamori=divide("*l") local shika =Rabbit:new(tonumber(yamori[1])) --cria um novo objeto da classe Rabbit shika:yume_nikki()--chamado de um método de rabbit--acessando um atributo de Rabbit end main()
local OAuth = require "kong.plugins.google-logging.google.core.oauth" local HTTPClient = require "kong.plugins.google-logging.google.core.http" local BatchQueue = require "kong.tools.batch_queue" local kong = kong local plugin_name = ({...})[1]:match("^kong%.plugins%.([^%.]+)") local socket = require "socket" local cjson = require "cjson" local function send_to_logging(oauth, entries, resource, log_id) local logging_client = HTTPClient(oauth, "logging.googleapis.com/v2/") local log_entries = {} for _, entry in pairs(entries) do local preciceSeconds = entry.timestamp local seconds = math.floor(preciceSeconds) local milliSeconds = math.floor((preciceSeconds - seconds) * 1000) local isoTime = os.date("!%Y-%m-%dT%T.", seconds) .. tostring(milliSeconds) .. "Z" table.insert(log_entries, { { logName = "projects/" .. oauth:GetProjectID() .. "/logs/" .. log_id, resource = resource, timestamp = isoTime, labels = { source = "kong-google-logging" }, jsonPayload = entry.data, httpRequest = entry.request, }, }) end local post, code = logging_client:Request("entries:write", { entries = log_entries, partialSuccess = false, }, nil, "POST") if code ~= 200 then kong.log.err("Failed to write logs: " .. post[1]) return false, post[1] end return true end local function log_entry() local logs = kong.log.serialize() local entry = { timestamp = socket.gettime(), data = { upstream_uri = logs.upstream_uri, uri = logs.request.uri, latency_request = logs.latencies.request, latency_gateway = logs.latencies.kong, latency_proxy = logs.latencies.proxy, }, request = { requestMethod = logs.request.method, requestUrl = logs.request.url, requestSize = logs.request.size, status = logs.response.status, responseSize = logs.response.size, userAgent = logs.request["user-agent"], remoteIp = logs.client_ip, serverIp = logs.tries ~= nil and table.getn(logs.tries) > 0 and logs.tries[1].ip or nil, latency = tostring(logs.latencies.request / 1000) .. "s", } } if logs.service then entry.data.service = logs.service.name entry.request.protocol = logs.service.protocol end if logs.route then entry.data.route = logs.route.name end if logs.consumer then entry.data.consumer = logs.consumer.username end return entry; end -- load the base plugin object and create a subclass local plugin = require("kong.plugins.base_plugin"):extend() -- constructor function plugin:new() plugin.super.new(self, plugin_name) self.queues = {} -- cached key file when reading it from disk self.key_cache = nil end function plugin:get_key(conf) -- use the key specified in the config if conf.google_key then return conf.google_key end -- read the key from the specified path if conf.google_key_file then if self.key_file_cache ~= nil then return self.key_file_cache end local file_content = assert(assert(io.open(conf.google_key_file)):read("*a")) self.key_file_cache = cjson.decode(file_content) return self.key_file_cache end return nil end function plugin:get_queue(conf) local sessionKey = 'default' local key = self:get_key(conf) if key == nil then kong.log.err("No key file or key specified") return nil end local existingQueue = self.queues[sessionKey] if existingQueue ~= nil then return existingQueue end local scope = "https://www.googleapis.com/auth/logging.write" local oauth = OAuth(nil, key, scope) if oauth == nil then kong.log.err("Failed to create OAuth") return nil end local process = function(entries) return send_to_logging(oauth, entries, conf.resource, conf.log_id) end -- { -- Opts table with control values. Defaults shown: -- retry_count = 0, -- number of times to retry processing -- batch_max_size = 1000, -- max number of entries that can be queued before they are queued for processing -- process_delay = 1, -- in seconds, how often the current batch is closed & queued -- flush_timeout = 2, -- in seconds, how much time passes without activity before the current batch is closed and queued local q, err = BatchQueue.new(process, { retry_count = conf.retry_count, flush_timeout = conf.flush_timeout, batch_max_size = conf.batch_max_size, process_delay = 5, }) if not q then kong.log.err("could not create queue: ", err) return nil end self.queues[sessionKey] = q return q end ---[[ runs in the 'log_by_lua_block' function plugin:log(conf) plugin.super.log(self) local queue = self:get_queue(conf) queue:add(log_entry()) end return plugin
local string = string local Container = require('sanity/util/container') local FontIcon = require('sanity/util/fonticon') local spawn = require('awful.spawn') local net = require('lain.widget.net') local fixed = require('wibox.layout.fixed') local widget = require('wibox.widget') local text = require('sanity/util/text') local disconnect_color = colors.red local color = colors.white local no_connection = '' local wifi_connected = '直' local wired_connected = '' local network_icon = FontIcon {icon = no_connection, color = color} local vpn_icon = FontIcon {icon = '', color = color} local empty_str = '' local container = Container { widget = widget { layout = fixed.horizontal, network_icon, vpn_icon, }, color = color, } local nmcli_command = 'nmcli -t | grep %s | grep connect | awk \'{ print $4,$5,$6,$7,$8,$9 }\'' local function query_nmcli(device_name, callback) local command = string.format(nmcli_command, device_name) spawn.easy_async_with_shell(command, callback) end local function network_update() local wired = false local wifi = false local wifi_signal for interface_name, interface in pairs(net_now.devices) do if interface.state == "up" and (text.startswith(interface_name, 'enp')or text.startswith(interface_name, 'wlp')) then if interface.ethernet then wired = interface_name elseif interface.wifi then wifi = interface_name wifi_signal = interface.signal end end end query_nmcli('-e tun0 -e VPN', function(stdout) local is_vpn_enabled = stdout ~= empty_str vpn_icon.visible = is_vpn_enabled if wired then network_icon:update(wired_connected, color) container:set_tooltip_color('Network', 'Wired', colors.green) elseif wifi then query_nmcli(wifi, function(s) network_icon:update(wifi_connected, color) container:set_tooltip_color('Network', s, colors.green) end) else -- no interfaces were connected network_icon:update(no_connection, disconnect_color) container:set_tooltip_color('Network', 'No Connection', colors.red) end end) end net { timeout = 5, units = 1, wifi_state = 'on', eth_state = 'on', settings = network_update } return container
local a = require "plenary.async.async" local await = a.await local async = a.async local vararg = require "plenary.vararg" local uv = vim.loop -- local control = a.control local control = require "plenary.async.control" local channel = control.channel local M = {} local defer_swapped = function(timeout, callback) vim.defer_fn(callback, timeout) end ---Sleep for milliseconds ---@param ms number M.sleep = a.wrap(defer_swapped, 2) ---This will COMPLETELY block neovim ---please just use a.run unless you have a very special usecase ---for example, in plenary test_harness you must use this ---@param async_function Future ---@param timeout number: Stop blocking if the timeout was surpassed. Default 2000. M.block_on = function(async_function, timeout) async_function = M.protected(async_function) local stat, ret a.run(async_function, function(_stat, ...) stat = _stat ret = { ... } end) local function check() if stat == false then error("Blocking on future failed " .. unpack(ret)) end return stat == true end if not vim.wait(timeout or 2000, check, 20, false) then error "Blocking on future timed out or was interrupted" end return unpack(ret) end M.will_block = function(async_func) return function() M.block_on(async_func) end end M.join = function(async_fns) local len = #async_fns local results = {} local done = 0 local tx, rx = channel.oneshot() for i, async_fn in ipairs(async_fns) do assert(type(async_fn) == "function", "type error :: future must be function") local cb = function(...) results[i] = { ... } done = done + 1 if done == len then tx() end end a.run(async_fn, cb) end rx() return results end ---Returns a future that when run will select the first async_function that finishes ---@param async_funs table: The async_function that you want to select ---@return ... M.run_first = a.wrap(function(async_funs, step) local ran = false for _, future in ipairs(async_funs) do assert(type(future) == "function", "type error :: future must be function") local callback = function(...) if not ran then ran = true step(...) end end future(callback) end end, 2) M.run_all = function(async_fns, callback) a.run(function() M.join(async_fns) end, callback) end function M.apcall(async_fn, ...) local nargs = a.get_leaf_function_argc(async_fn) if nargs then local tx, rx = channel.oneshot() local stat, ret = pcall(async_fn, vararg.rotate(nargs, tx, ...)) if not stat then return stat, ret else return stat, rx() end else return pcall(async_fn, ...) end end function M.protected(async_fn) return function() return M.apcall(async_fn) end end ---An async function that when called will yield to the neovim scheduler to be able to call the api. M.scheduler = a.wrap(vim.schedule, 1) return M
--New includeFile("custom_content/building/content/nova_orion_station/chapter_8_space_station.lua")
-- Button Controller -- MrLonely1221 -- April 16, 2019 --[[ ButtonController:Initialize(); ButtonController:GetButtons(); ButtonController:GetButton(buttonId); ButtonController:AddButton(name, sizeX, sizeY, posX, posY, color, text, image); --]] local ButtonController = {ButtonHolder = nil; Buttons = {}; Theme = "Light";}; function ButtonController:Initialize() self.ButtonHolder = Instance.new("ScreenGui", self.Player:WaitForChild("PlayerGui")); self.ButtonHolder.Name = "Buttons"; self.ButtonHolder.ResetOnSpawn = false; end; function ButtonController:GetButtons() return self.Buttons; end; function ButtonController:GetButton(buttonId) return self.Buttons[buttonId]; end; function ButtonController:AddButton(name, sizeX, sizeY, square, posX, posY, color, text, image) assert(name, "Must provide a button name"); assert(sizeX, "sizeX parameter missing"); assert(sizeY, "sizeY parameter missing"); assert(posX, "posX parameter missing"); assert(posY, "posY parameter missing"); assert(color, "color parameter missing"); assert((text and image == nil) or (image and text == nil), "You can only have one item displayed on a button"); local Button = self.Modules.Button.new(name, color, square, text, image); Button:SetSize(sizeX, sizeY) :SetPosition(posX, posY); table.insert(self.Buttons, Button); return Button; end; function ButtonController:Start() self:Initialize(); wait(2); self:AddButton("Test", 0.2, 0.2, true, 0.5, 0.9, BrickColor.Red(), "Test", nil):SetTheme("Dark"):SetTap(function() self:GetButton(1):SetColor(BrickColor.Random()); end):SetLongPress(function(positions, state) if state == Enum.UserInputState.Begin then print("Began touchLongPress"); elseif state == Enum.UserInputState.End then print("Ended touchLongPress"); end; end); while wait(2) do self:GetButton(1):SetSize(0.25, 0.1); wait(2); self:GetButton(1):SetSize(0.2, 0.1); end; end; function ButtonController:Init() end; return ButtonController;
local listeners = {} --[[ Subscribe to event Arguments: class originator = Class with subscribe method string event = Event name string identifier = Unique name to identify the event function func = Callback Return: nil ]] function Subscribe(originator, event, identifier, func) listeners[originator] = listeners[originator] or {} if not listeners[originator][event] then originator.Subscribe(event, function(...) for k, listener in pairs(listeners[originator][event]) do listener(...) end end) end listeners[originator][event] = listeners[originator][event] or {} listeners[originator][event][identifier] = func end --[[ Unsubscribe to event Arguments: class originator = Class with subscribe method string event = Event name Return: nil ]] function Unsubscribe(originator, event, identifier) if listeners[originator] and listeners[originator][event] then listeners[originator][event][identifier] = nil end end
-- programme pour faire clignoter une LED avec un rapport on/off print("\n blink_led2.lua zf200718.1204 \n") zLED=4 zTm_On_LED = 50 --> en ms zTm_Off_LED = 500 --> en ms zFlag_LED = 0 function blink_LED () if zFlag_LED==gpio.LOW then zFlag_LED=gpio.HIGH ztmr_LED:alarm(zTm_Off_LED, tmr.ALARM_SINGLE, blink_LED) else zFlag_LED=gpio.LOW ztmr_LED:alarm(zTm_On_LED, tmr.ALARM_SINGLE, blink_LED) end gpio.write(zLED, zFlag_LED) end gpio.mode(zLED, gpio.OUTPUT) ztmr_LED = tmr.create() blink_LED ()
local m = vim.api.nvim_set_keymap local n = {noremap = true} local s = {silent = true} local o = {noremap = true, silent = true} m("n", "<leader>q", ":q<CR>", o) m("n", "<leader>qx", ":q!<CR>", o) m("n", "<leader>x", ":qa<CR>", o) m("n", "<leader>xx", ":qa!<CR>", o) m("n", "<C-n>", ":NvimTreeToggle<CR>", o) m("n", "<C-h>", "<C-w>h", s) m("n", "<C-j>", "<C-w>j", s) m("n", "<C-k>", "<C-w>k", s) m("n", "<C-l>", "<C-w>l", s) m("n", "<TAB>", ":bnext<CR>", s) m("n", "<S-TAB>", ":bprevious<CR>", s) m("i", "hh", "<ESC>", o) m("i", "HH", "<ESC>", o) m("x", "hh", "<ESC>", o) m("x", "HH", "<ESC>", o) m("", "<up>", "<nop>", n) m("", "<down>", "<nop>", n) m("", "<left>", "<nop>", n) m("", "<right>", "<nop>", n) m("v", "<", "<gv", o) m("v", ">", ">gv", o) m("x", "K", ":move '<--1<CR>gv-gv", o) m("x", "J", ":move '>+1<CR>gv-gv", o) m("n", "<leader>fe", ":set foldenable<CR>", o) m("n", "<leader>nf", ":set nofoldenable<CR>", o) m("n", "<leader>hl", ":set hls<CR>", o) m("n", "<leader>nh", ":set nohls<CR>", o) m("n", "<leader><CR>", ":so %<CR>", o) -- m("", "<leader>c", '"+y', o) m("n", "F", ":Format<CR>", o) m("n", "K", "<Cmd>lua vim.lsp.buf.hover()<CR>", o) m("n", "gd", "<Cmd>lua vim.lsp.buf.definition()<CR>", o) m("n", "<leader>a", "<Cmd>lua vim.lsp.buf.code_action()<CR>", o) m("n", "<leader>a", "<Cmd>lua vim.lsp.buf.range_code_action()<CR>", o) m("n", "<leader>ow", ":FlutterOutlineToggle<CR>", o) m("n", "<leader>ht", ":set filetype=html<CR>gg=G", o)
object_tangible_shipcontrol_turret_ladder = object_tangible_shipcontrol_shared_turret_ladder:new { } ObjectTemplates:addTemplate(object_tangible_shipcontrol_turret_ladder, "object/tangible/shipcontrol/turret_ladder.iff")
return PlaceObj("ModDef", { "dependencies", { PlaceObj("ModDependency", { "id", "ChoGGi_Library", "title", "ChoGGi's Library", "version_major", 9, "version_minor", 6, }), }, "title", "Drones Harvest Rocks", "version", 4, "version_major", 0, "version_minor", 4, "image", "Preview.png", "id", "ChoGGi_DronesHarvestRocks", "steam_id", "1680679455", "pops_any_uuid", "05b09756-8673-4cfb-aa0e-6972134cda0a", "author", "ChoGGi", "lua_revision", 1001569, "code", { "Code/Script.lua", }, "description", [[Use the Salvage button to make drones harvest waste rock from small rocks. Requested by Truthowl.]], })
local TOCNAME,Addon = ... Addon.Tool=Addon.Tool or {} local Tool=Addon.Tool Tool.IconClassTexture="Interface\\GLUES\\CHARACTERCREATE\\UI-CHARACTERCREATE-CLASSES" Tool.IconClassTextureWithoutBorder="Interface\\WorldStateFrame\\ICONS-CLASSES" Tool.IconClassTextureCoord=CLASS_ICON_TCOORDS Tool.IconClass={ ["WARRIOR"]= "|TInterface\\WorldStateFrame\\ICONS-CLASSES:0:0:0:0:256:256:0:64:0:64|t", ["MAGE"]= "|TInterface\\WorldStateFrame\\ICONS-CLASSES:0:0:0:0:256:256:64:128:0:64|t", ["ROGUE"]= "|TInterface\\WorldStateFrame\\ICONS-CLASSES:0:0:0:0:256:256:128:192:0:64|t", ["DRUID"]= "|TInterface\\WorldStateFrame\\ICONS-CLASSES:0:0:0:0:256:256:192:256:0:64|t", ["HUNTER"]= "|TInterface\\WorldStateFrame\\ICONS-CLASSES:0:0:0:0:256:256:0:64:64:128|t", ["SHAMAN"]= "|TInterface\\WorldStateFrame\\ICONS-CLASSES:0:0:0:0:256:256:64:128:64:128|t", ["PRIEST"]= "|TInterface\\WorldStateFrame\\ICONS-CLASSES:0:0:0:0:256:256:128:192:64:128|t", ["WARLOCK"]= "|TInterface\\WorldStateFrame\\ICONS-CLASSES:0:0:0:0:256:256:192:256:64:128|t", ["PALADIN"]= "|TInterface\\WorldStateFrame\\ICONS-CLASSES:0:0:0:0:256:256:0:64:128:192|t", } Tool.IconClassBig={ ["WARRIOR"]= "|TInterface\\WorldStateFrame\\ICONS-CLASSES:18:18:-4:4:256:256:0:64:0:64|t", ["MAGE"]= "|TInterface\\WorldStateFrame\\ICONS-CLASSES:18:18:-4:4:256:256:64:128:0:64|t", ["ROGUE"]= "|TInterface\\WorldStateFrame\\ICONS-CLASSES:18:18:-4:4:256:256:128:192:0:64|t", ["DRUID"]= "|TInterface\\WorldStateFrame\\ICONS-CLASSES:18:18:-4:4:256:256:192:256:0:64|t", ["HUNTER"]= "|TInterface\\WorldStateFrame\\ICONS-CLASSES:18:18:-4:4:256:256:0:64:64:128|t", ["SHAMAN"]= "|TInterface\\WorldStateFrame\\ICONS-CLASSES:18:18:-4:4:256:256:64:128:64:128|t", ["PRIEST"]= "|TInterface\\WorldStateFrame\\ICONS-CLASSES:18:18:-4:4:256:256:128:192:64:128|t", ["WARLOCK"]= "|TInterface\\WorldStateFrame\\ICONS-CLASSES:18:18:-4:4:256:256:192:256:64:128|t", ["PALADIN"]= "|TInterface\\WorldStateFrame\\ICONS-CLASSES:18:18:-4:4:256:256:0:64:128:192|t", } Tool.RaidIconNames=ICON_TAG_LIST Tool.RaidIcon={ "|TInterface\\TargetingFrame\\UI-RaidTargetingIcon_1:0|t", -- [1] "|TInterface\\TargetingFrame\\UI-RaidTargetingIcon_2:0|t", -- [2] "|TInterface\\TargetingFrame\\UI-RaidTargetingIcon_3:0|t", -- [3] "|TInterface\\TargetingFrame\\UI-RaidTargetingIcon_4:0|t", -- [4] "|TInterface\\TargetingFrame\\UI-RaidTargetingIcon_5:0|t", -- [5] "|TInterface\\TargetingFrame\\UI-RaidTargetingIcon_6:0|t", -- [6] "|TInterface\\TargetingFrame\\UI-RaidTargetingIcon_7:0|t", -- [7] "|TInterface\\TargetingFrame\\UI-RaidTargetingIcon_8:0|t", -- [8] } Tool.Classes=CLASS_SORT_ORDER Tool.ClassName=LOCALIZED_CLASS_NAMES_MALE Tool.ClassColor=RAID_CLASS_COLORS Tool.NameToClass={} for eng,name in pairs(LOCALIZED_CLASS_NAMES_MALE) do Tool.NameToClass[name]=eng Tool.NameToClass[eng]=eng end for eng,name in pairs(LOCALIZED_CLASS_NAMES_FEMALE) do Tool.NameToClass[name]=eng end local _tableAccents = { ["�"] = "A", ["�"] = "A", ["�"] = "A", ["�"] = "A", ["�"] = "Ae", ["�"] = "A", ["�"] = "AE", ["�"] = "C", ["�"] = "E", ["�"] = "E", ["�"] = "E", ["�"] = "E", ["�"] = "I", ["�"] = "I", ["�"] = "I", ["�"] = "I", ["�"] = "D", ["�"] = "N", ["�"] = "O", ["�"] = "O", ["�"] = "O", ["�"] = "O", ["�"] = "Oe", ["�"] = "O", ["�"] = "U", ["�"] = "U", ["�"] = "U", ["�"] = "Ue", ["�"] = "Y", ["�"] = "P", ["�"] = "s", ["�"] = "a", ["�"] = "a", ["�"] = "a", ["�"] = "a", ["�"] = "ae", ["�"] = "a", ["�"] = "ae", ["�"] = "c", ["�"] = "e", ["�"] = "e", ["�"] = "e", ["�"] = "e", ["�"] = "i", ["�"] = "i", ["�"] = "i", ["�"] = "i", ["�"] = "eth", ["�"] = "n", ["�"] = "o", ["�"] = "o", ["�"] = "o", ["�"] = "o", ["�"] = "oe", ["�"] = "o", ["�"] = "u", ["�"] = "u", ["�"] = "u", ["�"] = "ue", ["�"] = "y", ["�"] = "p", ["�"] = "y", ["�"] = "ss", } -- Hyperlink local function EnterHyperlink(self,link,text) --print(link,text) local part=Tool.Split(link,":") if part[1]=="spell" or part[1]=="unit" or part[1]=="item" or part[1]=="enchant" or part[1]=="player" or part[1]=="quest" or part[1]=="trade" then GameTooltip_SetDefaultAnchor(GameTooltip,UIParent) GameTooltip:SetOwner(UIParent,"ANCHOR_PRESERVE") GameTooltip:ClearLines() GameTooltip:SetHyperlink(link) GameTooltip:Show() end end local function LeaveHyperlink(self) GameTooltip:Hide() end function Tool.EnableHyperlink(frame) frame:SetHyperlinksEnabled(true); frame:SetScript("OnHyperlinkEnter",EnterHyperlink) frame:SetScript("OnHyperlinkLeave",LeaveHyperlink) end -- EventHandler local eventFrame local function EventHandler(self,event,...) for i,Entry in pairs(self._GPIPRIVAT_events) do if Entry[1]==event then Entry[2](...) end end end local function UpdateHandler(self,...) for i,Entry in pairs(self._GPIPRIVAT_updates) do Entry(...) end end function Tool.RegisterEvent(event,func) if eventFrame==nil then eventFrame=CreateFrame("Frame") end if eventFrame._GPIPRIVAT_events==nil then eventFrame._GPIPRIVAT_events={} eventFrame:SetScript("OnEvent",EventHandler) end tinsert(eventFrame._GPIPRIVAT_events,{event,func}) eventFrame:RegisterEvent(event) end function Tool.OnUpdate(func) if eventFrame==nil then eventFrame=CreateFrame("Frame") end if eventFrame._GPIPRIVAT_updates==nil then eventFrame._GPIPRIVAT_updates={} eventFrame:SetScript("OnUpdate",UpdateHandler) end tinsert(eventFrame._GPIPRIVAT_updates,func) end -- move frame local function MovingStart(self) self:StartMoving() end local function MovingStop(self) self:StopMovingOrSizing() if self._GPIPRIVAT_MovingStopCallback then self._GPIPRIVAT_MovingStopCallback(self) end end function Tool.EnableMoving(frame,callback) frame:SetMovable(true) frame:EnableMouse(true) frame:RegisterForDrag("LeftButton") frame:SetScript("OnDragStart",MovingStart) frame:SetScript("OnDragStop",MovingStop) frame._GPIPRIVAT_MovingStopCallback=callback end -- misc tools function Tool.GuildNameToIndex(name, searchOffline) name = string.lower(name) for i = 1,GetNumGuildMembers(searchOffline) do if string.lower( string.match((GetGuildRosterInfo(i)),"(.-)-")) == name then return i end end end function Tool.RunSlashCmd(cmd) DEFAULT_CHAT_FRAME.editBox:SetText(cmd) ChatEdit_SendText(DEFAULT_CHAT_FRAME.editBox, 0) end function Tool.RGBtoEscape(r, g, b,a) if type(r)=="table" then a=r.a g=r.g b=r.b r=r.r end r = r~=nil and r <= 1 and r >= 0 and r or 1 g = g~=nil and g <= 1 and g >= 0 and g or 1 b = b~=nil and b <= 1 and b >= 0 and b or 1 a = a~=nil and a <= 1 and a >= 0 and a or 1 return string.format("|c%02x%02x%02x%02x", a*255, r*255, g*255, b*255) end function Tool.RGBPercToHex(r, g, b) r = r <= 1 and r >= 0 and r or 0 g = g <= 1 and g >= 0 and g or 0 b = b <= 1 and b >= 0 and b or 0 return string.format("%02x%02x%02x", r*255, g*255, b*255) end function Tool.GetRaidIcon(name) local x=string.gsub(string.lower(name),"[%{%}]","") return ICON_TAG_LIST[x] and Tool.RaidIcon[ICON_TAG_LIST[x]] or name end function Tool.UnitDistanceSquared(uId) --partly copied from DBM -- * Paul Emmerich (Tandanu @ EU-Aegwynn) (DBM-Core) -- * Martin Verges (Nitram @ EU-Azshara) (DBM-GUI) local range if UnitIsUnit(uId, "player") then range=0 else local distanceSquared, checkedDistance = UnitDistanceSquared(uId) if checkedDistance then range=distanceSquared elseif C_Map.GetBestMapForUnit(uId)~= C_Map.GetBestMapForUnit("player") then range = 1000000 elseif IsItemInRange(8149, uId) then range = 64 -- 8 --Voodoo Charm elseif CheckInteractDistance(uId, 3) then range = 100 --10 elseif CheckInteractDistance(uId, 2) then range = 121 --11 elseif IsItemInRange(14530, uId) then range = 324 --18--Heavy Runecloth Bandage. (despite popular sites saying it's 15 yards, it's actually 18 yards verified by UnitDistanceSquared elseif IsItemInRange(21519, uId) then range = 529 --23--Item says 20, returns true until 23. elseif IsItemInRange(1180, uId) then range = 1089 --33--Scroll of Stamina elseif UnitInRange(uId) then range = 1849--43 item scheck of 34471 also good for 43 else range = 10000 end end return range end function Tool.Merge(t1,...) for index=1 , select("#",...) do for i,v in pairs(select(index,...)) do t1[i]=v end end return t1 end function Tool.iMerge(t1,...) for index=1 , select("#",...) do local var=select(index,...) if type(var)=="table" then for i,v in ipairs(var) do if tContains(t1,v)==false then tinsert(t1,v) end end else tinsert(t1,var) end end return t1 end function Tool.stripChars(str) return string.gsub(str,"[%z\1-\127\194-\244][\128-\191]*", _tableAccents) end function Tool.CreatePattern(pattern,maximize) pattern = string.gsub(pattern, "[%(%)%-%+%[%]]", "%%%1") if not maximize then pattern = string.gsub(pattern, "%%s", "(.-)") else pattern = string.gsub(pattern, "%%s", "(.+)") end pattern = string.gsub(pattern, "%%d", "%(%%d-%)") if not maximize then pattern = string.gsub(pattern, "%%%d%$s", "(.-)") else pattern = string.gsub(pattern, "%%%d%$s", "(.+)") end pattern = string.gsub(pattern, "%%%d$d", "%(%%d-%)") --pattern = string.gsub(pattern, "%[", "%|H%(%.%-%)%[") --pattern = string.gsub(pattern, "%]", "%]%|h") return pattern end function Tool.Combine(t,sep,first,last) if type(t)~="table" then return "" end sep=sep or " " first=first or 1 last= last or #t local ret="" for i=first,last do ret=ret..sep..tostring(t[i]) end return string.sub(ret,string.len(sep)+1) end function Tool.iSplit(inputstr, sep) if sep == nil then sep = "%s" end local t={} for str in string.gmatch(inputstr, "([^"..sep.."]+)") do if tContains(t, str)==false then table.insert(t,tonumber(str)) end end return t end function Tool.Split(inputstr, sep) if sep == nil then sep = "%s" end local t={} for str in string.gmatch(inputstr, "([^"..sep.."]+)") do if tContains(t, str)==false then table.insert(t, str) end end return t end -- Size local ResizeCursor local SizingStop=function(self,button) self:GetParent():StopMovingOrSizing() if self.GPI_DoStop then self.GPI_DoStop(self:GetParent()) end end local SizingStart=function(self,button) self:GetParent():StartSizing(self.GPI_SIZETYPE) if self.GPI_DoStart then self.GPI_DoStart(self:GetParent()) end end local SizingEnter=function(self) if not (GetCursorInfo()) then ResizeCursor:Show() ResizeCursor.Texture:SetTexture(self.GPI_Cursor) ResizeCursor.Texture:SetRotation(math.rad(self.GPI_Rotation),0.5,0.5) end end local SizingLeave=function(self,button) ResizeCursor:Hide() end local sizecount=0 local CreateSizeBorder=function(frame,name,a1,x1,y1,a2,x2,y2,cursor,rot,OnStart,OnStop) local FrameSizeBorder sizecount=sizecount+1 FrameSizeBorder=CreateFrame("Frame",(frame:GetName() or TOCNAME..sizecount).."_size_"..name,frame) FrameSizeBorder:SetPoint("TOPLEFT", frame, a1, x1, y1) FrameSizeBorder:SetPoint("BOTTOMRIGHT", frame, a2, x2,y2 ) FrameSizeBorder.GPI_SIZETYPE=name FrameSizeBorder.GPI_Cursor = cursor FrameSizeBorder.GPI_Rotation = rot FrameSizeBorder.GPI_DoStart=OnStart FrameSizeBorder.GPI_DoStop=OnStop FrameSizeBorder:SetScript("OnMouseDown", SizingStart) FrameSizeBorder:SetScript("OnMouseUp", SizingStop) FrameSizeBorder:SetScript("OnEnter", SizingEnter) FrameSizeBorder:SetScript("OnLeave", SizingLeave) return FrameSizeBorder end local ResizeCursor_Update=function(self) local X, Y = GetCursorPosition() local Scale = self:GetEffectiveScale() self:SetPoint("CENTER", UIParent, "BOTTOMLEFT", X / Scale, Y / Scale) end function Tool.EnableSize(frame,border,OnStart,OnStop) if not ResizeCursor then ResizeCursor = CreateFrame("Frame", nil, UIParent) ResizeCursor:Hide() ResizeCursor:SetWidth(24) ResizeCursor:SetHeight(24) ResizeCursor:SetFrameStrata("TOOLTIP") ResizeCursor.Texture = ResizeCursor:CreateTexture() ResizeCursor.Texture:SetAllPoints() ResizeCursor:SetScript("OnUpdate", ResizeCursor_Update) end border=border or 8 frame:EnableMouse(true) frame:SetResizable(true) -- path= "Interface\\AddOns\\".. TOCNAME .. "\\Resize\\" CreateSizeBorder(frame,"BOTTOM","BOTTOMLEFT", border, border, "BOTTOMRIGHT", -border, 0,"Interface\\CURSOR\\UI-Cursor-SizeLeft",45,OnStart,OnStop) CreateSizeBorder(frame,"TOP","TOPLEFT", border, 0, "TOPRIGHT", -border, -border,"Interface\\CURSOR\\UI-Cursor-SizeLeft",45,OnStart,OnStop) CreateSizeBorder(frame,"LEFT","TOPLEFT", 0,-border, "BOTTOMLEFT", border, border,"Interface\\CURSOR\\UI-Cursor-SizeRight",45,OnStart,OnStop) CreateSizeBorder(frame,"RIGHT","TOPRIGHT",-border,-border, "BOTTOMRIGHT", 0, border,"Interface\\CURSOR\\UI-Cursor-SizeRight",45,OnStart,OnStop) CreateSizeBorder(frame,"TOPLEFT","TOPLEFT", 0,0, "TOPLEFT", border, -border,"Interface\\CURSOR\\UI-Cursor-SizeRight",0,OnStart,OnStop) CreateSizeBorder(frame,"BOTTOMLEFT","BOTTOMLEFT", 0,0, "BOTTOMLEFT", border, border, "Interface\\CURSOR\\UI-Cursor-SizeLeft",0,OnStart,OnStop) CreateSizeBorder(frame,"TOPRIGHT","TOPRIGHT", 0,0, "TOPRIGHT", -border, -border, "Interface\\CURSOR\\UI-Cursor-SizeLeft",0,OnStart,OnStop) CreateSizeBorder(frame,"BOTTOMRIGHT","BOTTOMRIGHT", 0,0, "BOTTOMRIGHT", -border, border, "Interface\\CURSOR\\UI-Cursor-SizeRight",0,OnStart,OnStop) end -- popup local PopupDepth local function PopupClick(self, arg1, arg2, checked) if type(self.value)=="table" then self.value[arg1]=not self.value[arg1] self.checked=self.value[arg1] if arg2 then arg2(self.value,arg1,checked) end elseif type(self.value)=="function" then self.value(arg1,arg2) end end local function PopupAddItem(self,text,disabled,value,arg1,arg2) local c=self._Frame._GPIPRIVAT_Items.count+1 self._Frame._GPIPRIVAT_Items.count=c if not self._Frame._GPIPRIVAT_Items[c] then self._Frame._GPIPRIVAT_Items[c]={} end local t=self._Frame._GPIPRIVAT_Items[c] t.text=text or "" t.disabled=disabled or false t.value=value t.arg1=arg1 t.arg2=arg2 t.MenuDepth=PopupDepth end local function PopupAddSubMenu(self,text,value) if text~=nil and text~="" then PopupAddItem(self,text,"MENU",value) PopupDepth=value else PopupDepth=nil end end local PopupLastWipeName local function PopupWipe(self,WipeName) self._Frame._GPIPRIVAT_Items.count=0 PopupDepth=nil if UIDROPDOWNMENU_OPEN_MENU == self._Frame then ToggleDropDownMenu(nil, nil, self._Frame, self._where, self._x, self._y) if WipeName == PopupLastWipeName then return false end end PopupLastWipeName=WipeName return true end local function PopupCreate(frame, level, menuList) if level==nil then return end local info = UIDropDownMenu_CreateInfo() for i=1,frame._GPIPRIVAT_Items.count do local val=frame._GPIPRIVAT_Items[i] if val.MenuDepth==menuList then if val.disabled=="MENU" then info.text=val.text info.notCheckable = true info.disabled=false info.value=nil info.arg1=nil info.arg2=nil info.func=nil info.hasArrow=true info.menuList=val.value --info.isNotRadio=true else info.text=val.text if type(val.value)=="table" then info.checked=val.value[val.arg1] or false info.notCheckable = false else info.notCheckable = true end info.disabled=(val.disabled==true or val.text=="" ) info.keepShownOnClick=(val.disabled=="keep") info.value=val.value info.arg1=val.arg1 if type(val.value)=="table" then info.arg2=frame._GPIPRIVAT_TableCallback elseif type(val.value)=="function" then info.arg2=val.arg2 end info.func=PopupClick info.hasArrow=false info.menuList=nil --info.isNotRadio=true end UIDropDownMenu_AddButton(info,level) end end end local function PopupShow(self,where,x,y) where=where or "cursor" if UIDROPDOWNMENU_OPEN_MENU ~= self._Frame then UIDropDownMenu_Initialize(self._Frame, PopupCreate, "MENU") end ToggleDropDownMenu(nil, nil, self._Frame, where, x,y) self._where=where self._x=x self._y=y end function Tool.CreatePopup(TableCallback) local popup={} popup._Frame=CreateFrame("Frame", nil, UIParent, "UIDropDownMenuTemplate") popup._Frame._GPIPRIVAT_TableCallback=TableCallback popup._Frame._GPIPRIVAT_Items={} popup._Frame._GPIPRIVAT_Items.count=0 popup.AddItem=PopupAddItem popup.SubMenu=PopupAddSubMenu popup.Show=PopupShow popup.Wipe=PopupWipe return popup end -- TAB local function SelectTab(self) if not self._gpi_combatlock or not InCombatLockdown() then local parent=self:GetParent() PanelTemplates_SetTab(parent,self:GetID()) for i=1, parent.numTabs do parent.Tabs[i].content:Hide() end self.content:Show() if parent.Tabs[self:GetID()].OnSelect then parent.Tabs[self:GetID()].OnSelect(self) end end end function Tool.TabHide(frame,id) if id and frame.Tabs and frame.Tabs[id] then frame.Tabs[id]:Hide() elseif not id and frame.Tabs then for i=1, frame.numTabs do frame.Tabs[i]:Hide() end end end function Tool.TabShow(frame,id) if id and frame.Tabs and frame.Tabs[id] then frame.Tabs[id]:Show() elseif not id and frame.Tabs then for i=1, frame.numTabs do frame.Tabs[i]:Show() end end end function Tool.SelectTab(frame,id) if id and frame.Tabs and frame.Tabs[id] then SelectTab(frame.Tabs[id]) end end function Tool.TabOnSelect(frame,id,func) if id and frame.Tabs and frame.Tabs[id] then frame.Tabs[id].OnSelect=func end end function Tool.GetSelectedTab(frame) if frame.Tabs then for i=1, frame.numTabs do if frame.Tabs[i].content:IsShown() then return i end end end return 0 end function Tool.AddTab(frame,name,tabFrame,combatlockdown) local frameName if type(frame)=="string" then frameName=frame frame=_G[frameName] else frameName=frame:GetName() end if type(tabFrame)=="string" then tabFrame=_G[tabFrame] end frame.numTabs=frame.numTabs and frame.numTabs+1 or 1 if frame.Tabs==nil then frame.Tabs={} end frame.Tabs[frame.numTabs]=CreateFrame("Button",frameName.."Tab"..frame.numTabs, frame, "CharacterFrameTabButtonTemplate") frame.Tabs[frame.numTabs]:SetID(frame.numTabs) frame.Tabs[frame.numTabs]:SetText(name) frame.Tabs[frame.numTabs]:SetScript("OnClick",SelectTab) frame.Tabs[frame.numTabs]._gpi_combatlock=combatlockdown frame.Tabs[frame.numTabs].content=tabFrame tabFrame:Hide() if frame.numTabs==1 then frame.Tabs[frame.numTabs]:SetPoint("TOPLEFT",frame,"BOTTOMLEFT",5,4) else frame.Tabs[frame.numTabs]:SetPoint("TOPLEFT",frame.Tabs[frame.numTabs-1],"TOPRIGHT",-14,0) end SelectTab(frame.Tabs[frame.numTabs]) SelectTab(frame.Tabs[1]) return frame.numTabs end -- DataBrocker local DataBrocker=false function Tool.AddDataBrocker(icon,onClick,onTooltipShow,text) if LibStub ~= nil and DataBrocker ~= true then local Launcher = LibStub('LibDataBroker-1.1',true) if Launcher ~= nil then DataBrocker=true Launcher:NewDataObject(TOCNAME, { type = "launcher", icon = icon, OnClick = onClick, OnTooltipShow = onTooltipShow, tocname = TOCNAME, label = text or GetAddOnMetadata(TOCNAME, "Title"), }) end end end -- Slashcommands local slash,slashCmd local function slashUnpack(t,sep) local ret="" if sep==nil then sep=", " end for i=1,#t do if i~=1 then ret=ret..sep end ret=ret.. t[i] end return ret end function Tool.PrintSlashCommand(prefix,subSlash,p) p=p or print prefix=prefix or "" subSlash=subSlash or slash local colCmd="|cFFFF9C00" for i,subcmd in ipairs(subSlash) do local words= (type(subcmd[1])=="table") and "|r("..colCmd..slashUnpack(subcmd[1],"|r/"..colCmd).."|r)"..colCmd or subcmd[1] if words=="%" then words="<value>" end if subcmd[2]~=nil and subcmd[2]~="" then p(colCmd.. ((type(slashCmd)=="table" ) and slashCmd[1] or slashCmd).. " ".. prefix .. words .."|r: "..subcmd[2]) end if type(subcmd[3])=="table" then Tool.PrintSlashCommand(prefix..words.." ",subcmd[3],p) end end end local function DoSlash(deep,msg,subSlash) for i,subcmd in ipairs(subSlash) do local ok=(type(subcmd[1])=="table") and tContains(subcmd[1],msg[deep]) or (subcmd[1]==msg[deep] or (subcmd[1]=="" and msg[deep]==nil)) if subcmd[1]=="%" then local para=Tool.iMerge( {unpack(subcmd,4)},{unpack(msg,deep)}) return subcmd[3](unpack( para ) ) end if ok then if type(subcmd[3])=="function" then return subcmd[3](unpack(subcmd,4)) elseif type(subcmd[3])=="table" then return DoSlash(deep+1,msg,subcmd[3]) end end end Tool.PrintSlashCommand(Tool.Combine(msg," ",1,deep-1).." ",subSlash) return nil end local function mySlashs(msg) if msg=="help" then local colCmd="|cFFFF9C00" print("|cFFFF1C1C"..GetAddOnMetadata(TOCNAME, "Title") .." ".. GetAddOnMetadata(TOCNAME, "Version") .." by "..GetAddOnMetadata(TOCNAME, "Author")) print(GetAddOnMetadata(TOCNAME, "Notes")) if type(slashCmd)=="table" then print("SlashCommand:",colCmd,slashUnpack(slashCmd,"|r, "..colCmd),"|r") end Tool.PrintSlashCommand() else DoSlash(1,Tool.Split(msg," "),slash) end end function Tool.SlashCommand(cmds,subcommand) slash=subcommand slashCmd=cmds if type(cmds)=="table" then for i,cmd in ipairs(cmds) do _G["SLASH_"..TOCNAME..i]= cmd end else _G["SLASH_"..TOCNAME.."1"]= cmds end SlashCmdList[TOCNAME]=mySlashs end
local State = require("stateBase") local ConcreteState1 = State:new() function ConcreteState1:handle(context) print(context:getHour()) print("ConcreteState1:handle") end return ConcreteState1
local L = LibStub("AceLocale-3.0"):GetLocale("IceHUD", false) local RangeCheck = IceCore_CreateClass(IceElement) RangeCheck.prototype.scheduledEvent = nil local LibRange = nil local DogTag = nil -- Constructor -- function RangeCheck.prototype:init() RangeCheck.super.prototype.init(self, "RangeCheck") self.scalingEnabled = true LibRange = LibStub("LibRangeCheck-2.0", true) end function RangeCheck.prototype:Enable(core) RangeCheck.super.prototype.Enable(self, core) if IceHUD.IceCore:ShouldUseDogTags() then DogTag = LibStub("LibDogTag-3.0", true) self:RegisterFontStrings() else self.scheduledEvent = self:ScheduleRepeatingTimer("UpdateRange", 0.1) end end function RangeCheck.prototype:Disable(core) RangeCheck.super.prototype.Disable(self, core) if DogTag then self:UnregisterFontStrings() else self:CancelTimer(self.scheduledEvent, true) end end function RangeCheck.prototype:GetDefaultSettings() local defaults = RangeCheck.super.prototype.GetDefaultSettings(self) defaults["rangeString"] = "Range: [HostileColor Range]" defaults["vpos"] = 220 defaults["hpos"] = 0 defaults["enabled"] = false return defaults end function RangeCheck.prototype:GetOptions() local opts = RangeCheck.super.prototype.GetOptions(self) opts["vpos"] = { type = "range", name = L["Vertical Position"], desc = L["Vertical Position"], get = function() return self.moduleSettings.vpos end, set = function(info, v) self.moduleSettings.vpos = v self:Redraw() end, min = -300, max = 600, step = 1, disabled = function() return not self.moduleSettings.enabled end, order = 31 } opts["hpos"] = { type = "range", name = L["Horizontal Position"], desc = L["Horizontal Position"], get = function() return self.moduleSettings.hpos end, set = function(info, v) self.moduleSettings.hpos = v self:Redraw() end, min = -500, max = 500, step = 1, disabled = function() return not self.moduleSettings.enabled end, order = 32 } opts["rangeString"] = { type = 'input', name = L["Range string"], desc = L["DogTag-formatted string to use for the range display (only available if LibDogTag is being used)\n\nType /dogtag for a list of available tags"], get = function() return self.moduleSettings.rangeString end, set = function(info, v) v = DogTag:CleanCode(v) self.moduleSettings.rangeString = v self:RegisterFontStrings() self:Redraw() end, disabled = function() return not self.moduleSettings.enabled or not DogTag or not LibRange end, usage = '', order = 33 } return opts end function RangeCheck.prototype:Redraw() RangeCheck.super.prototype.Redraw(self) if (self.moduleSettings.enabled) then self:CreateFrame(true) end end function RangeCheck.prototype:CreateFrame(redraw) if not (self.frame) then self.frame = CreateFrame("Frame", "IceHUD_"..self.elementName, self.parent) end self.frame:SetScale(self.moduleSettings.scale) self.frame:SetFrameStrata("BACKGROUND") self.frame:SetWidth(200) self.frame:SetHeight(32) self.frame:ClearAllPoints() self.frame:SetPoint("TOP", self.parent, "TOP", self.moduleSettings.hpos, self.moduleSettings.vpos) self.frame.rangeFontString = self:FontFactory(--[[self.moduleSettings.fontSize+1]] 13, self.frame, self.frame.rangeFontString) self.frame.rangeFontString:SetJustifyH("CENTER") self.frame.rangeFontString:SetJustifyV("TOP") self.frame.rangeFontString:SetAllPoints(self.frame) end function RangeCheck.prototype:RegisterFontStrings() if DogTag and LibRange then DogTag:AddFontString(self.frame.rangeFontString, self.frame, self.moduleSettings.rangeString, "Unit", { unit = "target" }) DogTag:UpdateAllForFrame(self.frame) end end function RangeCheck.prototype:UnregisterFontStrings() if DogTag then DogTag:RemoveFontString(self.frame.rangeFontString) end end -- this function is called every 0.1 seconds only if LibDogTag is not being used function RangeCheck.prototype:UpdateRange() if LibRange and UnitExists("target") then local min, max = LibRange:getRange("target") if min then if max then self.frame.rangeFontString:SetText("Range: " .. min .. " - " .. max) else self.frame.rangeFontString:SetText("Range: " .. min .. "+") end else self.frame.rangeFontString:SetText("Unknown") end self.frame.rangeFontString:SetWidth(0) else self.frame.rangeFontString:SetText() end end IceHUD.RangeCheck = RangeCheck:new()
-- -- string.lua -- Additions to Lua's built-in string functions. -- Copyright (c) 2002-2008 Jason Perkins and the Premake project -- -- -- Returns an array of strings, each of which is a substring of s -- formed by splitting on boundaries formed by `pattern`. -- function string.explode(s, pattern, plain) if (pattern == '') then return false end local pos = 0 local arr = { } for st,sp in function() return s:find(pattern, pos, plain) end do table.insert(arr, s:sub(pos, st-1)) pos = sp + 1 end table.insert(arr, s:sub(pos)) return arr end -- -- Find the last instance of a pattern in a string. -- function string.findlast(s, pattern, plain) local curr = 0 repeat local next = s:find(pattern, curr + 1, plain) if (next) then curr = next end until (not next) if (curr > 0) then return curr end end -- -- Returns true if `haystack` starts with the sequence `needle`. -- function string.startswith(haystack, needle) return (haystack:find(needle, 1, true) == 1) end
return function() local FromKeys = require(script.Parent.FromKeys) describe("Set/FromKeys", function() it("should return an empty table given an empty table", function() local Result = FromKeys({}) expect(next(Result)).never.to.be.ok() end) it("should return correctly for one item", function() local Result = FromKeys({A = 1234}) expect(Result.A).to.equal(true) end) it("should return correctly for multiple items", function() local Result = FromKeys({A = 1, B = 2, C = 3}) expect(Result.A).to.equal(true) expect(Result.B).to.equal(true) expect(Result.C).to.equal(true) end) end) end
-- Behavior for observer (5) in the level yasha_thief routine = function(O) O:gotoTile(4.5, 25) O:wait(1) O:gotoTile(12.5, 25) O:wait(1) end
require("ItemTweaker_Copy_CC"); --TIEONSPEARHEADS --Weapons TweakItem("Base.SpearChippedStone","DisplayCategory","WepMelee");
if not pcall(require, 'telescope') then return end require('telescope').setup { defaults = { vimgrep_arguments = { 'rg', '--color=never', '--no-heading', '--with-filename', '--line-number', '--column', '--smart-case', }, prompt_prefix = '> ', selection_caret = '> ', entry_prefix = ' ', initial_mode = 'insert', selection_strategy = 'reset', sorting_strategy = 'descending', layout_strategy = 'horizontal', layout_config = { horizontal = { preview_width = 0.6, }, vertical = { preview_height = 0.5, }, preview_cutoff = 120, prompt_position = 'bottom', }, file_sorter = require('telescope.sorters').get_fuzzy_file, file_ignore_patterns = {}, generic_sorter = require('telescope.sorters').get_generic_fuzzy_sorter, winblend = 0, border = {}, borderchars = { '─', '│', '─', '│', '╭', '╮', '╯', '╰' }, color_devicons = true, use_less = true, set_env = { ['COLORTERM'] = 'truecolor' }, -- default = nil, file_previewer = require('telescope.previewers').vim_buffer_cat.new, grep_previewer = require('telescope.previewers').vim_buffer_vimgrep.new, qflist_previewer = require('telescope.previewers').vim_buffer_qflist.new, extensions = { fzy_native = { override_generic_sorter = true, override_file_sorter = true, }, fzf_writer = { use_highlighter = false, minimum_grep_characters = 6, }, frecency = { db_root = '~/.local/share/nvim/db_root', show_scores = false, show_unindexed = true, ignore_patterns = { '*.git/*', '*/tmp/*' }, disable_devicons = false, workspaces = { -- TODO: Need to investigate this further: ['conf'] = '~/.config', ['data'] = '~/.local/share', -- ['project'] = '~/projects', ['repo'] = '~/Repositories', ['docs'] = '~/Documents', -- ['wiki'] = '/home/my_username/wiki', }, }, }, -- Developer configurations: Not meant for general override buffer_previewer_maker = require('telescope.previewers').buffer_previewer_maker, }, } TrySource 'plugins.telescope.pickers' TrySource 'plugins.telescope.keymaps'
-- Not placeable, too hardcoded for general use local summitGemManager = {} summitGemManager.name = "summitGemManager" summitGemManager.depth = 0 summitGemManager.texture = "@Internal@/summit_gem_manager" summitGemManager.nodeVisibility = "always" summitGemManager.nodeDepth = -10010 function summitGemManager.nodeTexture(room, entity, node, index) return string.format("collectables/summitgems/%s/gem00", index - 1) end return summitGemManager
local _, ns = ... local oGlow = ns.oGlow local argcheck = oGlow.argcheck local pipesTable = ns.pipesTable local filtersTable = {} local activeFilters = {} local numFilters = 0 function oGlow:RegisterFilter(name, type, filter, desc) argcheck(name, 2, 'string') argcheck(type, 3, 'string') argcheck(filter, 4, 'function') argcheck(desc, 5, 'string', 'nil') if(filtersTable[name]) then return nil, 'Filter function is already registered.' end filtersTable[name] = {type, filter, name, desc} numFilters = numFilters + 1 return true end do local function iter(_, n) local n, t = next(filtersTable, n) if(t) then return n, t[1], t[4] end end function oGlow.IterateFilters() return iter, nil, nil end end function oGlow:RegisterFilterOnPipe(pipe, filter) argcheck(pipe, 2, 'string') argcheck(filter, 3, 'string') if(not pipesTable[pipe]) then return nil, 'Pipe does not exist.' end if(not filtersTable[filter]) then return nil, 'Filter does not exist.' end if(not activeFilters[pipe]) then local filterTable = filtersTable[filter] local display = filterTable[1] activeFilters[pipe] = {} activeFilters[pipe][display] = {} table.insert(activeFilters[pipe][display], filterTable) else local filterTable = filtersTable[filter] local ref = activeFilters[pipe][filterTable[1]] for _, func in next, ref do if(func == filter) then return nil, 'Filter function is already registered.' end end table.insert(ref, filterTable) end if(not oGlowDB.EnabledFilters[filter]) then oGlowDB.EnabledFilters[filter] = {} end oGlowDB.EnabledFilters[filter][pipe] = true return true end oGlow.IterateFiltersOnPipe = function(pipe) local t = activeFilters[pipe] return coroutine.wrap(function() if(t) then for _, sub in next, t do for k, v in next, sub do coroutine.yield(v[3], v[1], v[4]) end end end end) end function oGlow:UnregisterFilterOnPipe(pipe, filter) argcheck(pipe, 2, 'string') argcheck(filter, 3, 'string') if(not pipesTable[pipe]) then return nil, 'Pipe does not exist.' end if(not filtersTable[filter]) then return nil, 'Filter does not exist.' end local filterTable = filtersTable[filter] local ref = activeFilters[pipe][filterTable[1]] if(ref) then for k, func in next, ref do if(func == filterTable) then table.remove(ref, k) oGlowDB.EnabledFilters[filter][pipe] = nil return true end end end end function oGlow:GetNumFilters() return numFilters end ns.filtersTable = filtersTable ns.activeFilters = activeFilters
local Player = class('Player', Base) Player.static.SPEED = 200 Player.static.RADIUS = 20 local radius = Player.RADIUS local AttackCharacter = require('player.attack_character') local DefenseCharacter = require('player.defense_character') local getUVs = require('getUVs') function Player:initialize(joystick, keyboard, attacker_mesh, defender_mesh, x1, y1, x2, y2, group_index) Base.initialize(self) assert(is_num(group_index)) self.keyboard = keyboard self.joystick = joystick self.attacker_mesh = attacker_mesh self.defender_mesh = defender_mesh self.group_index = group_index local ax, ay = game.map:gridToPixel(x1, y1) local dx, dy = game.map:gridToPixel(x2, y2) local w, h = push:getWidth() / game.map.width, push:getHeight() / game.map.height self.attackers = { AttackCharacter:new(self, ax, ay, radius, 0, Player.SPEED) } self.defenders = { DefenseCharacter:new(self, dx, dy, radius, 0, Player.SPEED) } self.t = 0 end function Player:update(dt) self.t = self.t + dt for _,attacker in ipairs(self.attackers) do attacker:update(dt) end local dx, dy = 0, 0 if self.joystick then dx = self.joystick:getGamepadAxis("leftx") dy = self.joystick:getGamepadAxis("lefty") if math.abs(dx) < 0.2 then dx = 0 end if math.abs(dy) < 0.2 then dy = 0 end else local isDown = love.keyboard.isDown for k,v in pairs(self.keyboard.directions) do if isDown(k) then dx = dx + v.x dy = dy + v.y end end end local phi = math.atan2(dy, dx) for _,attacker in ipairs(self.attackers) do if dx ~= 0 or dy ~= 0 then attacker:setAngle(phi) end attacker:setLinearVelocity(dx * attacker.speed, dy * attacker.speed) end for _,defender in ipairs(self.defenders) do if dx ~= 0 or dy ~= 0 then defender:setAngle(phi + math.pi) end defender:setLinearVelocity(-dx * defender.speed, -dy * defender.speed) end end function Player:gamepadpressed(button) for _,attacker in ipairs(self.attackers) do attacker:gamepadpressed(button) end end function Player:keypressed(button) if self.keyboard[button] == 'attack' then for _,attacker in ipairs(self.attackers) do attacker:gamepadpressed('a') end end end function Player:draw() for i,attacker in ipairs(self.attackers) do g.draw(self.attacker_mesh, attacker.x, attacker.y, attacker.rotation + math.pi / 2) do local index = math.abs(self.group_index) local quad = game.sprites.quads['player_' .. index .. '_sword'] g.draw(game.sprites.texture, quad, attacker.x, attacker.y, attacker.sword.angle) end end for _,defender in ipairs(self.defenders) do g.draw(self.defender_mesh, defender.x, defender.y, self.t * 1.5) end end return Player
local g = vim.g local function mapnoremap(mode, lhs, rhs, opts) local options = { noremap = true } if opts then options = vim.tbl_extend('force', options, opts) end vim.api.nvim_set_keymap(mode, lhs, rhs, options) end -- Spacebar is <Leader> mapnoremap('', '<Space>', '<Nop>', { silent = true }) g.mapleader = ' ' g.maplocalleader = ' ' -- Fast save, save quit, force exit mapnoremap('n', '<Leader>w', ':w!<CR>') mapnoremap('n', '<Leader>x', ':x<CR>') mapnoremap('n', '<Leader>qq', ':q<CR>') mapnoremap('n', '<Leader>qa', ':qa!<CR>') mapnoremap('n', '<Leader>wq', ':wq!<CR>') -- Better cursor movement on wrapped line mapnoremap('n', 'k', 'gk') mapnoremap('n', 'j', 'gj') mapnoremap('v', 'k', 'gk') mapnoremap('v', 'j', 'gj') mapnoremap('n', '<Up>', 'gk') mapnoremap('n', '<Down>', 'gj') mapnoremap('v', '<Up>', 'gk') mapnoremap('v', '<Down>', 'gj') mapnoremap('i', '<Up>', '<C-o>gk') mapnoremap('i', '<Down>', '<C-o>gj') -- Y to yank from cursor to end of line mapnoremap('n', 'Y', 'y$') -- Move paragraph mapnoremap('', 'K', '{') mapnoremap('', 'J', '}') -- Move to first and last char mapnoremap('', 'H', '^') mapnoremap('', 'L', '$') -- Move between splits mapnoremap('n', '<C-k>', '<C-w><C-k>') mapnoremap('n', '<C-j>', '<C-w><C-j>') mapnoremap('n', '<C-h>', '<C-w><C-h>') mapnoremap('n', '<C-l>', '<C-w><C-l>') -- Open new split mapnoremap('n', '<Leader>s', ':new<CR>') mapnoremap('n', '<Leader>v', ':vnew<CR>') -- Move cursors in Insert mode mapnoremap('i', '<C-k>', '<Up>') mapnoremap('i', '<C-j>', '<Down>') mapnoremap('i', '<C-h>', '<Left>') mapnoremap('i', '<C-l>', '<Right>') -- Tab navigation mapnoremap('n', '<Leader>tn', ':tabnew<CR>') mapnoremap('n', '<Leader>tq', ':tabclose<CR>') mapnoremap('n', '<Leader>th', ':tabprev<CR>') mapnoremap('n', '<Leader>tl', ':tabnext<CR>') -- Open new tab with current buffer's path mapnoremap('n', '<Leader>te', ':tabedit <C-r>=expand("%:p:h")<CR>/') -- Indent or de-indent mapnoremap('n', '<Tab>', '>>') mapnoremap('n', '<S-Tab>', '<<') mapnoremap('v', '<Tab>', '>gv') mapnoremap('v', '<S-Tab>', '<gv') -- FzfLua mapnoremap('n', '<Leader>fz', ':FzfLua<CR>') mapnoremap('n', '<Leader>ff', ':FzfLua files<CR>') mapnoremap('n', '<Leader>fg', ':FzfLua live_grep<CR>') mapnoremap('n', '<Leader>fc', ':FzfLua git_commits<CR>') mapnoremap('n', '<Leader>fb', ':FzfLua buffers<CR>') mapnoremap('n', '<Leader>fh', ':FzfLua help_tags<CR>') mapnoremap('n', '<Leader>fk', ':FzfLua keymaps<CR>') mapnoremap('n', '<Leader>fe', ':FzfLua lsp_document_diagnostics<CR>') mapnoremap('n', '<Leader>fr', ':FzfLua lsp_references<CR>') mapnoremap('n', '<Leader>fd', ':FzfLua lsp_typedefs<CR>') -- Trouble mapnoremap('n', '<Leader>xx', ':TroubleToggle<CR>') mapnoremap('n', '<Leader>xr', ':TroubleToggle lsp_references<CR>') -- nvim-tree mapnoremap('n', '<C-f>', ':NvimTreeToggle<CR>') -- null-ls mapnoremap('n', '<Leader>pp', ':lua vim.lsp.buf.formatting()<CR>') mapnoremap('v', '<Leader>pp', ':lua vim.lsp.buf.range_formatting()<CR>') -- FTerm mapnoremap('n', '<C-t>', ':lua require("FTerm").toggle()<CR>') mapnoremap('t', '<C-t>', '<C-\\><C-n>:lua require("FTerm").toggle()<CR>')
module(..., lunit.testcase, package.seeall) local common = dofile("common.lua") local http = require("luanode.http") local net = require("luanode.net") function test() local gotReq = false local server = http.createServer(function (self, req, res) common.error('got req') gotReq = true assert_equal('GET', req.method) assert_equal('/blah', req.url) assert_equal("mapdevel.trolologames.ru:443", req.headers.host) assert_equal("http://mapdevel.trolologames.ru", req.headers.origin) assert_equal("", req.headers.cookie) end) server:listen(common.PORT, function () local c = net.createConnection(common.PORT) c:addListener('connect', function () common.error('client wrote message') c:write( "GET /blah HTTP/1.1\r\n" .. "Host: mapdevel.trolologames.ru:443\r\n" .. "Cookie:\r\n" .. "Origin: http://mapdevel.trolologames.ru\r\n" .. "\r\n\r\nhello world" ) end) c:addListener('end', function () c:finish() end) c:addListener('close', function () common.error('client close') server:close() end) end) process:addListener('exit', function () assert_true(gotReq) end) process:loop() end
module 'character' -------------------------------------------------------------------- local _messageEventTypes = {} function registerActionMessageEventType( t, clas ) if _messageEventTypes[ t ] then _error( 'duplicated action message event type', t ) end _messageEventTypes[ t ] = clas end -------------------------------------------------------------------- CLASS: TrackMessage ( CharacterActionTrack ) :MODEL{} function TrackMessage:__init() self.name = 'message' end function TrackMessage:getType() return 'message' end function TrackMessage:getDefaultEventType() return 'simple' end function TrackMessage:getEventTypes() local names = {} for k,clas in pairs( _messageEventTypes ) do table.insert( names, k ) end table.sort( names ) return names end function TrackMessage:createEvent( evType ) local clas = _messageEventTypes[ evType ] assert( clas ) return clas() end function TrackMessage:toString() return '<msg>' .. tostring( self.name ) end -------------------------------------------------------------------- registerCharacterActionTrackType( 'Message', TrackMessage ) -------------------------------------------------------------------- CLASS: EventMessage ( CharacterActionEvent ) :MODEL{ Field 'message' :string(); Field 'arg' :string() } function EventMessage:__init() self.length = 0 self.name = 'message' self.arg = false end function EventMessage:isResizable() return true end function EventMessage:start( state, pos ) state.target:tell( self.message, self ) end function EventMessage:toString() return tostring( self.message ) end registerActionMessageEventType( 'simple', EventMessage )
-- Battle Matchmaker -- Version 1.4.0 g_players={} g_ui_id=0 g_popups={} g_status_text=nil g_vehicles={} g_spawned_vehicles={} g_players={} g_status_dirty=false g_finish_dirty=false g_in_game=false g_in_countdown=false g_timer=0 g_remind_interval=3600 g_supply_buttons={ MG_K={42,50}, MG_AP={45,50}, MG_I={46,50}, LA_K={47,50}, LA_HE={48,50}, LA_F={49,50}, LA_AP={50,50}, LA_I={51,50}, RA_K={52,25}, RA_HE={53,25}, RA_F={54,25}, RA_AP={55,25}, RA_I={56,25}, HA_K={57,10}, HA_HE={58,10}, HA_F={59,10}, HA_AP={60,10}, HA_I={61,10}, BS_K={62,1}, BS_HE={63,1}, BS_F={64,1}, BS_AP={65,1}, BS_I={66,1}, AS_HE={68,1}, AS_F={66,1}, AS_AP={70,1}, } g_default_savedata={ base_hp=property.slider('Default Vehicle HP', 0, 5000, 100, 2000), battery_name='killed', supply_ammo_amount=property.slider('Default Ammo Supply', 0, 100, 1, 40), order_command=property.checkbox('Default Order Command Enabled', true), cd_time_sec=property.slider('Default Countdown time (sec)', 5, 60, 1, 10), game_time_min=property.slider('Default Game time (min)', 1, 60, 1, 20), remind_time_min=property.slider('Default Remind time (min)', 1, 10, 1, 1), tps_enable=property.checkbox('Default Third Person Enabled', false), } -- Commands -- g_commands={ { name='join', auth=true, action=function(peer_id, is_admin, is_auth, team_name, target_peer_id) if g_in_game then announce('Cannot join after game start..', peer_id) return end if not checkTargetPeerId(target_peer_id, peer_id, is_admin) then return end join(target_peer_id or peer_id, team_name) end, args={ {name='team_name', type='string', require=true}, {name='peer_id', type='integer', require=false}, }, }, { name='leave', auth=true, action=function(peer_id, is_admin, is_auth, target_peer_id) if not checkTargetPeerId(target_peer_id, peer_id, is_admin) then return end leave(target_peer_id or peer_id) end, args={ {name='peer_id', type='integer', require=false}, }, }, { name='die', auth=true, action=function(peer_id, is_admin, is_auth, target_peer_id) if not g_in_game then announce('Cannot die before game start.', peer_id) return end if not checkTargetPeerId(target_peer_id, peer_id, is_admin) then return end kill(target_peer_id or peer_id) end, args={ {name='peer_id', type='integer', require=false}, }, }, { name='ready', auth=true, action=function(peer_id, is_admin, is_auth, target_peer_id) if g_in_game then announce('Cannot ready after game start.', peer_id) return end if not checkTargetPeerId(target_peer_id, peer_id, is_admin) then return end ready(target_peer_id or peer_id) end, args={ {name='peer_id', type='integer', require=false}, }, }, { name='wait', auth=true, action=function(peer_id, is_admin, is_auth, target_peer_id) if g_in_game then announce('Cannot wait after game start.', peer_id) return end if not checkTargetPeerId(target_peer_id, peer_id, is_admin) then return end wait(target_peer_id or peer_id) end, args={ {name='peer_id', type='integer', require=false}, }, }, { name='order', auth=true, action=function(peer_id, is_admin, is_auth) if g_in_game then announce('Cannot order after game start.', peer_id) return end if not g_savedata.order_command then announce('Order command is not available.', peer_id) return end local player=g_players[peer_id] if not player then announce('Joind player not found. peer_id:'..tostring(peer_id), peer_id) return end if not player.alive then announce('Dead player cannot order vehicle.', peer_id) return end if player.vehicle_id<=0 then announce('Vehicle not found.', peer_id) return end local m=server.getPlayerPos(peer_id) local x, y, z=server.getPlayerLookDirection(peer_id) local m2=matrix.translation(x*8,0,z*8) server.setVehiclePos(player.vehicle_id, matrix.multiply(m2, m)) local name=server.getPlayerName(peer_id) announce('Vehicle orderd by '..name..'.', -1) end, }, { name='pause', auth=true, action=function(peer_id, is_admin, is_auth) pause() end, }, { name='resume', auth=true, action=function(peer_id, is_admin, is_auth) resume(true, peer_id) end, }, { name='reset', admin=true, action=function(peer_id, is_admin, is_auth) g_players={} g_vehicles={} g_status_dirty=true setPopup('status', false) finishGame() announce('Reset game.', -1) end, }, { name='reset_ui', auth=true, action=function(peer_id, is_admin, is_auth) renewPopupIds() announce('Refresh ui ids.', -1) end, }, { name='set_hp', admin=true, action=function(peer_id, is_admin, is_auth, hp) g_savedata.base_hp=hp reregisterVehicles() announce('Set base vehicle hp to '..tostring(g_savedata.base_hp), -1) end, args={ {name='hp', type='integer', require=true}, }, }, { name='set_battery', admin=true, action=function(peer_id, is_admin, is_auth, battery_name) g_savedata.battery_name=battery_name reregisterVehicles() announce('Set lifeline battery name to '..tostring(g_savedata.battery_name), -1) end, args={ {name='battery_name', type='string', require=true}, }, }, { name='set_ammo', admin=true, action=function(peer_id, is_admin, is_auth, supply_ammo_amount) g_savedata.supply_ammo_amount=supply_ammo_amount reregisterVehicles() announce('Set supply ammo count to '..tostring(g_savedata.supply_ammo_amount), -1) end, args={ {name='supply_ammo_amount', type='integer', require=true}, }, }, { name='set_order', admin=true, action=function(peer_id, is_admin, is_auth, enabled) if enabled then announce('order command enabled.', -1) g_savedata.order_command=true else announce('order command disabled.', -1) g_savedata.order_command=false end end, args={ {name='true|false', type='boolean', require=true}, }, }, { name='set_cd_time', admin=true, action=function(peer_id, is_admin, is_auth, cd_time_sec) if cd_time_sec<1 then announce('Cannot set time under 1.', peer_id) return end g_savedata.cd_time_sec=cd_time_sec announce('Set countdown time to '..tostring(cd_time_sec)..' sec.', -1) end, args={ {name='second', type='number', require=true}, }, }, { name='set_game_time', admin=true, action=function(peer_id, is_admin, is_auth, game_time_min) if game_time_min<1 then announce('Cannot set time under 1.', peer_id) return end g_savedata.game_time_min=game_time_min announce('Set game time to '..tostring(game_time_min)..' min.', -1) end, args={ {name='minute', type='number', require=true}, }, }, { name='set_remind_time', admin=true, action=function(peer_id, is_admin, is_auth, remind_time_min) if remind_time_min<1 then announce('Cannot set time under 1.', peer_id) return end g_savedata.remind_time_min=remind_time_min announce('Set remind time to '..tostring(remind_time_min)..' min.', -1) end, args={ {name='minute', type='number', require=true}, }, }, { name='set_tps', admin=true, action=function(peer_id, is_admin, is_auth, enabled) if enabled then announce('Third person enabled.', -1) g_savedata.tps_enable=true else announce('Third person disabled.', -1) g_savedata.tps_enable=false end end, args={ {name='true|false', type='boolean', require=true}, }, }, } function findCommand(command) for i,command_define in ipairs(g_commands) do if command_define.name==command then return command_define end end end function showHelp(peer_id, is_admin, is_auth) local commands_help='Commands:\n' local any_commands=false for i,command_define in ipairs(g_commands) do if checkAuth(command_define, is_admin, is_auth) then local args='' if command_define.args then for i,arg in ipairs(command_define.args) do if arg.require then args=args..' ['..arg.name..']' else args=args..' ('..arg.name..')' end end end commands_help=commands_help..' - ?mm '..command_define.name..args..'\n' any_commands=true end end if any_commands then announce(commands_help, peer_id) else announce('Permitted command is not found.', peer_id) end end function checkAuth(command, is_admin, is_auth) return is_admin or (not command.admin and (is_auth or not command.auth)) end function checkTargetPeerId(target_peer_id, peer_id, is_admin) if not target_peer_id then return true end if not is_admin then announce('Permission denied. Only admin can specify target_peer_id.', peer_id) return false end local _, is_success=server.getPlayerName(target_peer_id) if not is_success then announce('Invalid peer_id.', peer_id) return false end return true end -- Callbacks -- function onCreate(is_world_create) for k,v in pairs(g_default_savedata) do if not g_savedata[k] then g_savedata[k]=v end end registerPopup('status', -0.9, 0.2) registerPopup('countdown', 0, 0.7) setSettingsToStandby() end function onDestroy() server.removePopup(-1, g_ui_id) clearPopups() end function onTick() for i=1,#g_vehicles do updateVehicle(g_vehicles[i]) end if g_in_countdown then if g_timer>0 then local sec=g_timer//60 g_timer=g_timer-1 g_countdown_text=string.format('Start in\n%.0f', sec) setPopup('countdown', true, string.format('Start in\n%.0f', sec)) else startGame() notify('Game Start', 'Panzer Vor!', 9, -1) end end if g_in_game then if g_timer>0 then local sec=g_timer//60 g_timer=g_timer-1 local time_text=string.format('%02.f:%02.f', sec//60,sec%60) setPopup('countdown', true, time_text) if g_timer>0 and g_timer%g_remind_interval==0 then server.notify(-1, 'Time reminder', time_text..' left.', 1) end else finishGame() notify('Game End', 'Timeup!', 9, -1) end end if g_finish_dirty then g_finish_dirty=false checkFinish() end if g_status_dirty then g_status_dirty=false updateStatus() end updatePopups() end function onPlayerJoin(steam_id, name, peer_id, is_admin, is_auth) renewPopupIds() end function onPlayerLeave(steam_id, name, peer_id, admin, auth) leave(peer_id) end function onPlayerDie(steam_id, name, peer_id, is_admin, is_auth) kill(peer_id) end function onButtonPress(vehicle_id, peer_id, button_name) if not peer_id or peer_id<0 then return end if g_savedata.supply_ammo_amount<=0 then return end local equipment_data=g_supply_buttons[button_name] if not equipment_data then return end local equipment_id=equipment_data[1] local equipment_amount=equipment_data[2] local character_id=server.getPlayerCharacterID(peer_id) local current_equipment_id=server.getCharacterItem(character_id, 1) if current_equipment_id>0 then if current_equipment_id~=equipment_id then announce('Your large inventory is full.', peer_id) end return end announce(tostring(vehicle_id), peer_id) local vehicle=findVehicle(vehicle_id) if vehicle and vehicle.remain_ammo<=0 then announce('Out of ammo.', peer_id) return end server.setCharacterItem(character_id, 1, equipment_id, true, equipment_amount) if vehicle then vehicle.remain_ammo=vehicle.remain_ammo-1 announce('Ammo here! (Remain:'..tostring(vehicle.remain_ammo)..')', peer_id) else announce('Ammo here!', peer_id) end end function onPlayerSit(peer_id, vehicle_id, seat_name) local player=g_players[peer_id] if not player or not player.alive then return end local vehicle=registerVehicle(vehicle_id) if vehicle and vehicle.alive then player.vehicle_id=vehicle_id end g_status_dirty=true end function onVehicleSpawn(vehicle_id, peer_id, x, y, z, cost) if not peer_id or peer_id<0 then return end g_spawned_vehicles[vehicle_id]=peer_id end function onVehicleLoad(vehicle_id) local peer_id=g_spawned_vehicles[vehicle_id] if not peer_id then return end g_spawned_vehicles[vehicle_id]=nil local player=g_players[peer_id] if not player or not player.alive then return end local vehicle=registerVehicle(vehicle_id) if vehicle and vehicle.alive then player.vehicle_id=vehicle_id end g_status_dirty=true end function onVehicleDespawn(vehicle_id, peer_id) g_spawned_vehicles[vehicle_id]=nil unregisterVehicle(vehicle_id) end function onVehicleDamaged(vehicle_id, damage_amount, voxel_x, voxel_y, voxel_z) if not g_in_game then return end if damage_amount<=0 then return end local vehicle=findVehicle(vehicle_id) if not vehicle then return end if vehicle.hp then vehicle.hp=math.max(vehicle.hp-damage_amount,0) g_status_dirty=true end end function onCustomCommand(full_message, peer_id, is_admin, is_auth, command, one, two, three, four, five) if command~='?mm' then return end if not one then showHelp(peer_id, is_admin, is_auth) announce( 'Current settings:\n'.. ' - base hp: '..tostring(g_savedata.base_hp)..'\n'.. ' - battery name: '..g_savedata.battery_name..'\n'.. ' - ammo amount: '..tostring(g_savedata.supply_ammo_amount)..'\n'.. ' - order command enabled: '..tostring(g_savedata.order_command)..'\n'.. ' - countdown time: '..tostring(g_savedata.cd_time_sec)..'sec\n'.. ' - game time: '..tostring(g_savedata.game_time_min)..'min\n'.. ' - remind time: '..tostring(g_savedata.remind_time_min)..'min\n'.. ' - third person enabled: '..tostring(g_savedata.tps_enable), peer_id) return end local command_define=findCommand(one) if not command_define then announce('Command "'..one..'" not found.', peer_id) return end if not checkAuth(command_define, is_admin, is_auth) then announce('Permission denied.', peer_id) return end local args={two, three, four, five} if command_define.args then for i,arg_define in ipairs(command_define.args) do if #args < i then if arg_define.require then announce('Argument not enough. Except ['..arg_define.name..'].', peer_id) return end break end local value=convert(args[i], arg_define.type) if value==nil then announce('Except '..arg_define.type..' to ['..arg_define.name..'].', peer_id) return end args[i]=value end end command_define.action(peer_id, is_admin, is_auth, table.unpack(args)) end -- Player Functions -- function join(peer_id, team) local name, is_success=server.getPlayerName(peer_id) if not is_success then return end local player={ name=name, team=team, alive=true, ready=false, vehicle_id=-1, } g_players[peer_id]=player local character_id=server.getPlayerCharacterID(peer_id) local vehicle_id, is_success=server.getCharacterVehicle(character_id) if is_success then local vehicle=registerVehicle(vehicle_id) if vehicle and vehicle.alive then player.vehicle_id=vehicle_id end end g_status_dirty=true announce('You joined to '..team..'.', peer_id) pause() end function leave(peer_id) local player=g_players[peer_id] if not player then return end g_players[peer_id]=nil g_status_dirty=true announce('You leaved from '..player.team..'.', peer_id) if g_in_game then g_finish_dirty=true else if player.ready then pause() else resume() end end end function kill(peer_id) local player=g_players[peer_id] if not player or not player.alive then return end player.alive=false g_status_dirty=true notify('Kill Log', player.name..' is dead.', 9, -1) g_finish_dirty=true end function ready(peer_id) if g_in_game then return end local player=g_players[peer_id] if not player or player.ready then return end if not player.alive then announce('Cannot ready for dead player.', peer_id) return end player.ready=true resume() g_status_dirty=true end function wait(peer_id) if g_in_game then return end local player=g_players[peer_id] if not player or not player.ready then return end player.ready=false pause() g_status_dirty=true end -- Vehicle Functions -- function findVehicle(vehicle_id) for i=1,#g_vehicles do local vehicle=g_vehicles[i] if vehicle.vehicle_id==vehicle_id then return vehicle,i end end end function registerVehicle(vehicle_id) local vehicle=findVehicle(vehicle_id) if vehicle then return vehicle end vehicle={ vehicle_id=vehicle_id, alive=true, remain_ammo=g_savedata.supply_ammo_amount//1|0, } local base_hp=g_savedata.base_hp if base_hp and base_hp>0 then vehicle.hp=math.max(base_hp//1|0,1) end local battery_name=g_savedata.battery_name if battery_name then local battery, is_success=server.getVehicleBattery(vehicle_id, battery_name) if is_success and battery.charge>0 then vehicle.battery_name=battery_name end end if vehicle.hp or vehicle.battery_name then table.insert(g_vehicles, vehicle) return vehicle end end function unregisterVehicle(vehicle_id) local vehicle,index=findVehicle(vehicle_id) if not vehicle then return end table.remove(g_vehicles,index) for _,player in pairs(g_players) do if player.vehicle_id==vehicle_id then player.vehicle_id=-1 end end g_status_dirty=true end function reregisterVehicles() for i=1,#g_vehicles do local vehicle=g_vehicles[i] if vehicle.alive then vehicle.hp=nil local base_hp=g_savedata.base_hp if base_hp and base_hp>0 then vehicle.hp=math.max(base_hp//1|0,1) end vehicle.battery_name=nil local battery_name=g_savedata.battery_name if battery_name then local battery, is_success=server.getVehicleBattery(vehicle.vehicle_id, battery_name) if is_success and battery.charge>0 then vehicle.battery_name=battery_name end end vehicle.remain_ammo=g_savedata.supply_ammo_amount//1|0 g_status_dirty=true end end end function updateVehicle(vehicle) if not vehicle.alive then return end local vehicle_id=vehicle.vehicle_id if vehicle.battery_name then local battery, is_success=server.getVehicleBattery(vehicle_id, vehicle.battery_name) if is_success and battery.charge<=0 then vehicle.alive=false end end if vehicle.hp==0 then vehicle.alive=false end if vehicle.alive then return end -- explode local vehicle_matrix, is_success=server.getVehiclePos(vehicle_id) if is_success then server.spawnExplosion(vehicle_matrix, 0.17) end -- kill for peer_id,player in pairs(g_players) do if player.vehicle_id==vehicle_id then -- force getout local player_matrix, is_success=server.getPlayerPos(peer_id) if is_success then server.setPlayerPos(peer_id, player_matrix) end player.vehicle_id=-1 kill(peer_id) end end server.setVehicleTooltip(vehicle_id, 'Destroyed') g_status_dirty=true end -- System Functions -- function updateStatus() local team_stats={} local any=false for _,player in pairs(g_players) do local stat=team_stats[player.team] if not stat then stat='' end local hp=nil local battery_name=nil if player.vehicle_id>=0 then local vehicle=findVehicle(player.vehicle_id) if vehicle then hp=vehicle.hp battery_name=vehicle.battery_name end end team_stats[player.team]=stat..'\n'..playerToString(player.name,player.alive,player.ready,hp,battery_name) any=true end if any then local status_text='' local first=true for team,stat in pairs(team_stats) do if not first then status_text=status_text..'\n\n' end status_text=status_text..'* Team '..team..' *'..stat first=false end setPopup('status', true, status_text) else setPopup('status', false) end end function playerToString(name, alive, ready, hp, bat) local stat_text=alive and (g_in_game and 'Alive' or (ready and 'Ready' or 'Wait')) or 'Dead' local hp_text=hp and string.format('\nHP:%.0f',hp) or '' local battery_text=bat and '\n(B)' or '' return name..'\nStat:'..stat_text..hp_text..battery_text end function resume(force, peer_id) if g_in_game or g_in_countdown then return end local ready=true local teams={} for peer_id,player in pairs(g_players) do ready=ready and player.ready teams[player.team]=true end if not ready then if force then announce('There is unready player(s).', peer_id) end return end local team_count=getTableCount(teams) if team_count<1 or (team_count<2 and not force) then if force then announce('There are not enough registered teams.', peer_id) end return end announce('Countdown start.', -1) g_timer=g_savedata.cd_time_sec*60//1|0 g_in_countdown=true g_status_dirty=true end function pause() if g_in_game or not g_in_countdown then return end announce('Countdown stop.', -1) setPopup('countdown', false) g_in_countdown=false g_status_dirty=true end function checkFinish() if not g_in_game then return end local team_aliver_counts={} local any=false for _,player in pairs(g_players) do local add=player.alive and 1 or 0 local count=team_aliver_counts[player.team] team_aliver_counts[player.team]=count and (count+add) or add any=true end if not any then finishGame() notify('Game End', 'No player. Game is interrupted.', 6, -1) return end local alive_team_count=0 local alive_team_name='' for team_name,team_aliver_count in pairs(team_aliver_counts) do if team_aliver_count>0 then alive_team_count=alive_team_count+1 alive_team_name=team_name end end if alive_team_count>1 then return end finishGame() if alive_team_count==1 then notify('Game End', 'Team '..alive_team_name..' Win!', 9, -1) else notify('Game End', 'Draw Game!', 9, -1) end end function startGame() g_in_game=true g_in_countdown=false g_status_dirty=true g_timer=g_savedata.game_time_min*60*60//1|0 g_remind_interval=g_savedata.remind_time_min*60*60//1|0 for _,player in pairs(g_players) do player.ready=false end setSettingsToBattle() end function finishGame() g_in_game=false g_in_countdown=false g_status_dirty=true setPopup('countdown', false) setSettingsToStandby() end function setSettingsToBattle() local tps_enable=g_savedata.tps_enable server.setGameSetting('third_person', tps_enable) server.setGameSetting('third_person_vehicle', tps_enable) server.setGameSetting('vehicle_damage', true) server.setGameSetting('player_damage', true) server.setGameSetting('map_show_players', false) server.setGameSetting('map_show_vehicles', false) end function setSettingsToStandby() server.setGameSetting('third_person', true) server.setGameSetting('third_person_vehicle', true) server.setGameSetting('vehicle_damage', false) server.setGameSetting('player_damage', false) server.setGameSetting('map_show_players', true) server.setGameSetting('map_show_vehicles', true) end -- UI function registerPopup(name, x, y) table.insert(g_popups, { name=name, x=x, y=y, ui_id=server.getMapID(), is_show=false, text='', is_dirty=true, }) end function findPopup(name) for i,popup in ipairs(g_popups) do if popup.name==name then return popup end end end function setPopup(name, is_show, text) local popup=findPopup(name) if not popup then return end if popup.is_show~=is_show then popup.is_show=is_show popup.is_dirty=true end if popup.text~=text then popup.text=text popup.is_dirty=true end end function updatePopups() for i,popup in ipairs(g_popups) do if popup.is_dirty then popup.is_dirty=false server.setPopupScreen(-1, popup.ui_id, popup.name, popup.is_show, popup.text, popup.x, popup.y) end end end function renewPopupIds() for i,popup in ipairs(g_popups) do server.removeMapID(-1, popup.ui_id) popup.ui_id=server.getMapID() popup.is_dirty=true end end function clearPopups() for i,popup in ipairs(g_popups) do server.removeMapID(-1, popup.ui_id) end g_popups={} end -- Utility Functions -- function announce(text, peer_id) server.announce('[Matchmaker]', text, peer_id) end function notify(title, text, type, peer_id) server.notify(-1, title, text, type) announce(title..'\n'..text, peer_id) end function getTableCount(table) local count=0 for idx,p in pairs(table) do count=count+1 end return count end function clamp(x,a,b) return x<a and a or x>b and b or x end function convert(value, type) local converter=g_converters[type] if converter then return converter(value) end return value end g_converters={ integer=function(v) v=tonumber(v) return v and v//1|0 end, number=function(v) return tonumber(v) end, boolean=function(v) if v=='true' then return true end if v=='false' then return false end end, }
local eq = assert.are.same local operations = require'neogit.operations' local harness = require'tests.git_harness' local in_prepared_repo = harness.in_prepared_repo local get_current_branch = harness.get_current_branch --local status = require'neogit.status' local input = require'tests.mocks.input' local function act(normal_cmd) vim.cmd('normal '..normal_cmd) end describe('branch popup', function () it('can switch to another branch in the repository', in_prepared_repo(function () input.value = 'second-branch' act('bb') operations.wait('checkout_branch') eq('second-branch', get_current_branch()) end)) it('can switch to another local branch in the repository', in_prepared_repo(function () input.value = 'second-branch' act('bl') operations.wait('checkout_local-branch') eq('second-branch', get_current_branch()) end)) it('can create a new branch', in_prepared_repo(function () input.value = 'branch-from-test' act('bc') operations.wait('checkout_create-branch') eq('branch-from-test', get_current_branch()) end)) end)
local LibNumbers = Wheel("LibNumbers") assert(LibNumbers, "UnitManaText requires LibNumbers to be loaded.") -- Lua API local _G = _G local math_floor = math.floor local pairs = pairs local tonumber = tonumber local tostring = tostring local unpack = unpack -- WoW API local UnitIsConnected = _G.UnitIsConnected local UnitIsDeadOrGhost = _G.UnitIsDeadOrGhost local UnitIsPlayer = _G.UnitIsPlayer local UnitPower = _G.UnitPower local UnitPowerMax = _G.UnitPowerMax local UnitPowerType = _G.UnitPowerType -- Number Abbreviation local short = LibNumbers:GetNumberAbbreviationShort() local large = LibNumbers:GetNumberAbbreviationLong() -- IDs local ManaID = Enum.PowerType.Mana or 0 local UpdateValue = function(element, unit, min, max) if element.showDeficit then if element.showPercent then if element.showMaximum then element:SetFormattedText("%s / %s - %.0f%%", short(max - min), short(max), math_floor(min/max * 100)) else element:SetFormattedText("%s / %.0f%%", short(max - min), math_floor(min/max * 100)) end else if element.showMaximum then element:SetFormattedText("%s / %s", short(max - min), short(max)) else element:SetFormattedText("%s", short(max - min)) end end else if element.showPercent then if element.showMaximum then element:SetFormattedText("%s / %s - %.0f%%", short(min), short(max), math_floor(min/max * 100)) else element:SetFormattedText("%s / %.0f%%", short(min), math_floor(min/max * 100)) end else if element.showMaximum then element:SetFormattedText("%s / %s", short(min), short(max)) else element:SetFormattedText("%s", short(min)) end end end end local Update = function(self, event, unit) if (not unit) or (unit ~= self.unit) then return end local element = self.ManaText if (UnitIsDeadOrGhost(unit) or (not UnitIsPlayer(unit)) or (not UnitIsConnected(unit))) then if (element:IsShown()) then element:Hide() end return end local currentID, currentType = UnitPowerType(unit) if (currentType == "MANA") then if (element:IsShown()) then element:Hide() end return end if element.PreUpdate then element:PreUpdate(unit) end local min = UnitPower(unit, ManaID) or 0 local max = UnitPowerMax(unit, ManaID) or 0 if (min == 0) or (max == 0) then if (element:IsShown()) then element:Hide() end return end if element.colorMana then local r, g, b = unpack(self.colors.power.MANA) element:SetTextColor(r, g, b) end (element.OverrideValue or UpdateValue) (element, unit, min, max) if (not element:IsShown()) then element:Show() end if element.PostUpdate then return element:PostUpdate(unit, min, max) end end local Proxy = function(self, ...) return (self.ManaText.Override or Update)(self, ...) end local ForceUpdate = function(element) return Proxy(element._owner, "Forced", element._owner.unit) end local Enable = function(self) local element = self.ManaText if element then element._owner = self element.ForceUpdate = ForceUpdate local unit = self.unit if element.frequent and ((unit == "player") or (unit == "pet")) then self:RegisterEvent("UNIT_POWER_FREQUENT", Proxy) else self:RegisterEvent("UNIT_POWER_UPDATE", Proxy) end self:RegisterEvent("UNIT_POWER_BAR_SHOW", Proxy) self:RegisterEvent("UNIT_POWER_BAR_HIDE", Proxy) self:RegisterEvent("UNIT_DISPLAYPOWER", Proxy) self:RegisterEvent("UNIT_CONNECTION", Proxy) self:RegisterEvent("UNIT_MAXPOWER", Proxy) self:RegisterEvent("UNIT_FACTION", Proxy) return true end end local Disable = function(self) local element = self.ManaText if element then element:Hide() self:UnregisterEvent("UNIT_POWER_FREQUENT", Proxy) self:UnregisterEvent("UNIT_POWER_UPDATE", Proxy) self:UnregisterEvent("UNIT_POWER_BAR_SHOW", Proxy) self:UnregisterEvent("UNIT_POWER_BAR_HIDE", Proxy) self:UnregisterEvent("UNIT_DISPLAYPOWER", Proxy) self:UnregisterEvent("UNIT_CONNECTION", Proxy) self:UnregisterEvent("UNIT_MAXPOWER", Proxy) self:UnregisterEvent("UNIT_FACTION", Proxy) end end -- Register it with compatible libraries for _,Lib in ipairs({ (Wheel("LibUnitFrame", true)), (Wheel("LibNamePlate", true)) }) do Lib:RegisterElement("PowerText", Enable, Disable, Proxy, 4) end
-- -- Copyright (c) 2015, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. -- -- Author: Alexander M Rush <[email protected]> -- Sumit Chopra <[email protected]> -- Jason Weston <[email protected]> -- The utility tool box local util = {} function util.string_shortfloat(t) return string.format('%2.4g', t) end function util.shuffleTable(t) local rand = math.random local iterations = #t local j for i = iterations, 2, -1 do j = rand(i) t[i], t[j] = t[j], t[i] end end function util.string_split(s, c) if c==nil then c=' ' end local t={} while true do local f=s:find(c) if f==nil then if s:len()>0 then table.insert(t, s) end break end if f > 1 then table.insert(t, s:sub(1,f-1)) end s=s:sub(f+1,s:len()) end return t end function util.add(tab, key) local cur = tab for i = 1, #key-1 do local new_cur = cur[key[i]] if new_cur == nil then cur[key[i]] = {} new_cur = cur[key[i]] end cur = new_cur end cur[key[#key]] = true end function util.has(tab, key) local cur = tab for i = 1, #key do cur = cur[key[i]] if cur == nil then return false end end return true end function util.isnan(x) return x ~= x end return util
notice = {} notice.red = {1, 0.5, 0.5} notice.white = {1, 1, 1} notice.notices = {} notice.duration = 5 --seconds notice.fadetime = 0.5 function notice.new(text, color, duration) local duration = duration or notice.duration local text = text or "" local color = color or notice.white table.insert(notice.notices, {text=text:lower(), color=color, life=duration, duration=duration}) end function notice.update(dt) for i = #notice.notices, 1, -1 do local v = notice.notices[i] v.life = v.life - dt if v.life <= 0 then table.remove(notice.notices, i) end end end function notice.draw() local y = 0 for i = #notice.notices, 1, -1 do local v = notice.notices[i] --get width by finding longest line local split = v.text:split("|") local longest = #split[1] for i = 2, #split do if #split[i] > longest then longest = #split[i] end end local height = #split*10+3 actualy = notice.gety(y, v.life, height, v.duration) local targetrect = {width*16 - longest*8-5, actualy, longest*8+5, height} local scissor = {(width*16 - longest*8-5)*scale, y*scale, (longest*8+5)*scale, (actualy-y+height)*scale} love.graphics.setScissor(unpack(scissor)) love.graphics.setColor(0, 0, 0, 0.8) love.graphics.rectangle("fill", targetrect[1]*scale, targetrect[2]*scale, targetrect[3]*scale, targetrect[4]*scale) love.graphics.setColor(1, 1, 1, 1) drawrectangle(targetrect[1]+1, targetrect[2]+1, targetrect[3]-2, targetrect[4]-2) love.graphics.setColor(v.color) properprint(v.text, (targetrect[1]+2)*scale, (actualy+3)*scale) y = actualy+height love.graphics.setScissor() end love.graphics.setColor(1, 1, 1) end function notice.gety(y, life, height, duration) if life > duration-notice.fadetime then return y - height*((life-(duration-notice.fadetime))/notice.fadetime)^2 elseif life < notice.fadetime then return y - height*((notice.fadetime-life)/notice.fadetime)^2 else return y end end
--[[-- Registration, parsing, and handling of commands. Commands can be ran through the chat with slash commands or they can be executed through the console. ]] -- @module ix.command --- When registering commands with `ix.command.Add`, you'll need to pass in a valid command structure. This is simply a table -- with various fields defined to describe the functionality of the command. -- @realm shared -- @table CommandStructure -- @field[type=function] OnRun This function is called when the command has passed all the checks and can execute. The first two -- arguments will be the running command table and the calling player. If the arguments field has been specified, the arguments -- will be passed as regular function parameters rather than in a table. -- -- When the arguments field is defined: `OnRun(self, client, target, length, message)` -- -- When the arguments field is NOT defined: `OnRun(self, client, arguments)` -- @field[type=string,opt="@noDesc"] description The help text that appears when the user types in the command. If the string is -- prefixed with `"@"`, it will use a language phrase. -- @field[type=table,opt=nil] argumentNames An array of strings corresponding to each argument of the command. This ignores the -- name that's specified in the `OnRun` function arguments and allows you to use any string to change the text that displays -- in the command's syntax help. When using this field, make sure that the amount is equal to the amount of arguments, as such: -- COMMAND.arguments = {ix.type.character, ix.type.number} -- COMMAND.argumentNames = {"target char", "cash (1-1000)"} -- @field[type=table,opt] arguments If this field is defined, then additional checks will be performed to ensure that the -- arguments given to the command are valid. This removes extra boilerplate code since all the passed arguments are guaranteed -- to be valid. See `CommandArgumentsStructure` for more information. -- @field[type=boolean,opt=false] adminOnly Provides an additional check to see if the user is an admin before running. -- @field[type=boolean,opt=false] superAdminOnly Provides an additional check to see if the user is a superadmin before running. -- @field[type=string,opt=nil] privilege Manually specify a privilege name for this command. It will always be prefixed with -- `"Helix - "`. This is used in the case that you want to group commands under the same privilege, or use a privilege that -- you've already defined (i.e grouping `/CharBan` and `/CharUnban` into the `Helix - Ban Character` privilege). -- @field[type=function,opt=nil] OnCheckAccess This callback checks whether or not the player is allowed to run the command. -- This callback should **NOT** be used in conjunction with `adminOnly` or `superAdminOnly`, as populating those -- fields create a custom a `OnCheckAccess` callback for you internally. This is used in cases where you want more fine-grained -- access control for your command. -- -- Keep in mind that this is a **SHARED** callback; the command will not show up the client if the callback returns `false`. --- Rather than checking the validity for arguments in your command's `OnRun` function, you can have Helix do it for you to -- reduce the amount of boilerplate code that needs to be written. This can be done by populating the `arguments` field. -- -- When using the `arguments` field in your command, you are specifying specific types that you expect to receive when the -- command is ran successfully. This means that before `OnRun` is called, the arguments passed to the command from a user will -- be verified to be valid. Each argument is an `ix.type` entry that specifies the expected type for that argument. Optional -- arguments can be specified by using a bitwise OR with the special `ix.type.optional` type. When specified as optional, the -- argument can be `nil` if the user has not entered anything for that argument - otherwise it will be valid. -- -- Note that optional arguments must always be at the end of a list of arguments - or rather, they must not follow a required -- argument. The `syntax` field will be automatically populated when using strict arguments, which means you shouldn't fill out -- the `syntax` field yourself. The arguments you specify will have the same names as the arguments in your OnRun function. -- -- Consider this example command: -- ix.command.Add("CharSlap", { -- description = "Slaps a character with a large trout.", -- adminOnly = true, -- arguments = { -- ix.type.character, -- bit.bor(ix.type.number, ix.type.optional) -- }, -- OnRun = function(self, client, target, damage) -- -- WHAM! -- end -- }) -- Here, we've specified the first argument called `target` to be of type `character`, and the second argument called `damage` -- to be of type `number`. The `damage` argument is optional, meaning that the command will still run if the user has not -- specified any value for the damage. In this case, we'll need to check if it was specified by doing a simple -- `if (damage) then`. The syntax field will be automatically populated with the value `"<target: character> [damage: number]"`. -- @realm shared -- @table CommandArgumentsStructure ix.command = ix.command or {} ix.command.list = ix.command.list or {} local COMMAND_PREFIX = "/" local function ArgumentCheckStub(command, client, given) local arguments = command.arguments local result = {} for i = 1, #arguments do local bOptional = bit.band(arguments[i], ix.type.optional) == ix.type.optional local argType = bOptional and bit.bxor(arguments[i], ix.type.optional) or arguments[i] local argument = given[i] if (!argument and !bOptional) then return L("invalidArg", client, i) end if (argType == ix.type.string) then if (!argument and bOptional) then result[#result + 1] = nil else result[#result + 1] = tostring(argument) end elseif (argType == ix.type.text) then result[#result + 1] = table.concat(given, " ", i) or "" break elseif (argType == ix.type.number) then local value = tonumber(argument) if (!bOptional and !value) then return L("invalidArg", client, i) end result[#result + 1] = value elseif (argType == ix.type.player or argType == ix.type.character) then local bPlayer = argType == ix.type.player local value = ix.util.FindPlayer(argument) -- FindPlayer emits feedback for us if (!value and !bOptional) then return L(bPlayer and "plyNoExist" or "charNoExist", client) end -- check for the character if we're using the character type if (!bPlayer) then local character = value:GetCharacter() if (!character) then return L("charNoExist", client) end value = character end result[#result + 1] = value elseif (argType == ix.type.steamid) then local value = argument:match("STEAM_(%d+):(%d+):(%d+)") if (!value and bOptional) then return L("invalidArg", client, i) end result[#result + 1] = value elseif (argType == ix.type.bool) then if (argument == nil and bOptional) then result[#result + 1] = nil else result[#result + 1] = tobool(argument) end end end return result end --- Creates a new command. -- @realm shared -- @string command Name of the command (recommended in UpperCamelCase) -- @tab data A `CommandStructure` describing the command function ix.command.Add(command, data) data.name = string.gsub(command, "%s", "") data.description = data.description or "" command = command:lower() data.uniqueID = command -- Why bother adding a command if it doesn't do anything. if (!data.OnRun) then return ErrorNoHalt("Command '"..command.."' does not have a callback, not adding!\n") end -- Add a function to get the description that can be overridden. if (!data.GetDescription) then -- Check if the description is using a language string. if (data.description:sub(1, 1) == "@") then function data:GetDescription() return L(self.description:sub(2)) end else -- Otherwise just return the raw description. function data:GetDescription() return self.description end end end -- OnCheckAccess by default will rely on CAMI for access information with adminOnly/superAdminOnly being fallbacks if (!data.OnCheckAccess) then if (data.group) then ErrorNoHalt("Command '" .. data.name .. "' tried to use the deprecated field 'group'!\n") return end local privilege = "Helix - " .. (isstring(data.privilege) and data.privilege or data.name) -- we could be using a previously-defined privilege if (!CAMI.GetPrivilege(privilege)) then CAMI.RegisterPrivilege({ Name = privilege, MinAccess = data.superAdminOnly and "superadmin" or (data.adminOnly and "admin" or "user"), Description = data.description }) end function data:OnCheckAccess(client) local bHasAccess, _ = CAMI.PlayerHasAccess(client, privilege, nil) return bHasAccess end end -- if we have an arguments table, then we're using the new command format if (data.arguments) then local bFirst = true local bLastOptional = false local bHasArgumentNames = istable(data.argumentNames) data.syntax = "" -- @todo deprecate this in favour of argumentNames data.argumentNames = bHasArgumentNames and data.argumentNames or {} -- if one argument is supplied by itself, put it into a table if (!istable(data.arguments)) then data.arguments = {data.arguments} end if (bHasArgumentNames and #data.argumentNames != #data.arguments) then return ErrorNoHalt(string.format( "Command '%s' doesn't have argument names that correspond to each argument\n", command )) end -- check the arguments table to see if its entries are valid for i = 1, #data.arguments do local argument = data.arguments[i] local argumentName = debug.getlocal(data.OnRun, 2 + i) if (argument == ix.type.optional) then return ErrorNoHalt(string.format( "Command '%s' tried to use an optional argument for #%d without specifying type\n", command, i )) elseif (!isnumber(argument)) then return ErrorNoHalt(string.format( "Command '%s' tried to use an invalid type for argument #%d\n", command, i )) elseif (argument == ix.type.array or bit.band(argument, ix.type.array) > 0) then return ErrorNoHalt(string.format( "Command '%s' tried to use an unsupported type 'array' for argument #%d\n", command, i )) end local bOptional = bit.band(argument, ix.type.optional) > 0 argument = bOptional and bit.bxor(argument, ix.type.optional) or argument if (!ix.type[argument]) then return ErrorNoHalt(string.format( "Command '%s' tried to use an invalid type for argument #%d\n", command, i )) elseif (!isstring(argumentName)) then return ErrorNoHalt(string.format( "Command '%s' is missing function argument for command argument #%d\n", command, i )) elseif (argument == ix.type.text and i != #data.arguments) then return ErrorNoHalt(string.format( "Command '%s' tried to use a text argument outside of the last argument\n", command )) elseif (!bOptional and bLastOptional) then return ErrorNoHalt(string.format( "Command '%s' tried to use an required argument after an optional one\n", command )) end -- text is always optional and will return an empty string if nothing is specified, rather than nil if (argument == ix.type.text) then data.arguments[i] = bit.bor(ix.type.text, ix.type.optional) bOptional = true end if (!bHasArgumentNames) then data.argumentNames[i] = argumentName end data.syntax = data.syntax .. (bFirst and "" or " ") .. string.format((bOptional and "[%s: %s]" or "<%s: %s>"), argumentName, ix.type[argument]) bFirst = false bLastOptional = bOptional end if (data.syntax:len() == 0) then data.syntax = "<none>" end else data.syntax = data.syntax or "<none>" end -- Add the command to the list of commands. local alias = data.alias if (alias) then if (istable(alias)) then for _, v in ipairs(alias) do ix.command.list[v:lower()] = data end elseif (isstring(alias)) then ix.command.list[alias:lower()] = data end end ix.command.list[command] = data end --- Returns true if a player is allowed to run a certain command. -- @realm shared -- @player client Player to check access for -- @string command Name of the command to check access for -- @treturn bool Whether or not the player is allowed to run the command function ix.command.HasAccess(client, command) command = ix.command.list[command:lower()] if (command) then if (command.OnCheckAccess) then return command:OnCheckAccess(client) else return true end end return false end --- Returns a table of arguments from a given string. -- Words separated by spaces will be considered one argument. To have an argument containing multiple words, they must be -- contained within quotation marks. -- @realm shared -- @string text String to extract arguments from -- @treturn table Arguments extracted from string -- @usage PrintTable(ix.command.ExtractArgs("these are \"some arguments\"")) -- > 1 = these -- > 2 = are -- > 3 = some arguments function ix.command.ExtractArgs(text) local skip = 0 local arguments = {} local curString = "" for i = 1, #text do if (i <= skip) then continue end local c = text:sub(i, i) if (c == "\"") then local match = text:sub(i):match("%b"..c..c) if (match) then curString = "" skip = i + #match arguments[#arguments + 1] = match:sub(2, -2) else curString = curString..c end elseif (c == " " and curString != "") then arguments[#arguments + 1] = curString curString = "" else if (c == " " and curString == "") then continue end curString = curString..c end end if (curString != "") then arguments[#arguments + 1] = curString end return arguments end --- Returns an array of potential commands by unique id. -- When bSorted is true, the commands will be sorted by name. When bReorganize is true, it will move any exact match to the top -- of the array. When bRemoveDupes is true, it will remove any commands that have the same NAME. -- @realm shared -- @string identifier Search query -- @bool[opt=false] bSorted Whether or not to sort the commands by name -- @bool[opt=false] bReorganize Whether or not any exact match will be moved to the top of the array -- @bool[opt=false] bRemoveDupes Whether or not to remove any commands that have the same name -- @treturn table Array of command tables whose name partially or completely matches the search query function ix.command.FindAll(identifier, bSorted, bReorganize, bRemoveDupes) local result = {} local iterator = bSorted and SortedPairs or pairs local fullMatch identifier = identifier:lower() if (identifier == "/") then -- we don't simply copy because we need numeric indices for _, v in iterator(ix.command.list) do result[#result + 1] = v end return result elseif (identifier:sub(1, 1) == "/") then identifier = identifier:sub(2) end for k, v in iterator(ix.command.list) do if (k:match(identifier)) then local index = #result + 1 result[index] = v if (k == identifier) then fullMatch = index end end end if (bReorganize and fullMatch and fullMatch != 1) then result[1], result[fullMatch] = result[fullMatch], result[1] end if (bRemoveDupes) then local commandNames = {} -- using pairs intead of ipairs because we might remove from array for k, v in pairs(result) do if (commandNames[v.name]) then table.remove(result, k) end commandNames[v.name] = true end end return result end if (SERVER) then util.AddNetworkString("ixCommand") --- Attempts to find a player by an identifier. If unsuccessful, a notice will be displayed to the specified player. The -- search criteria is derived from `ix.util.FindPlayer`. -- @realm server -- @player client Player to give a notification to if the player could not be found -- @string name Search query -- @treturn[1] player Player that matches the given search query -- @treturn[2] nil If a player could not be found -- @see ix.util.FindPlayer function ix.command.FindPlayer(client, name) local target = isstring(name) and ix.util.FindPlayer(name) or NULL if (IsValid(target)) then return target else client:NotifyLocalized("plyNoExist") end end --- Forces a player to execute a command by name. -- @realm server -- @player client Player who is executing the command -- @string command Full name of the command to be executed. This string gets lowered, but it's good practice to stick with -- the exact name of the command -- @tab arguments Array of arguments to be passed to the command -- @usage ix.command.Run(player.GetByID(1), "Roll", {10}) function ix.command.Run(client, command, arguments) if ((client.ixCommandCooldown or 0) > RealTime()) then return end command = ix.command.list[tostring(command):lower()] if (!command) then return end -- we throw it into a table since arguments get unpacked and only -- the arguments table gets passed in by default local argumentsTable = arguments arguments = {argumentsTable} -- if feedback is non-nil, we can assume that the command failed -- and is a phrase string local feedback -- check for group access if (command.OnCheckAccess) then local bSuccess, phrase = command:OnCheckAccess(client) feedback = !bSuccess and L(phrase and phrase or "noPerm", client) or nil end -- check for strict arguments if (!feedback and command.arguments) then arguments = ArgumentCheckStub(command, client, argumentsTable) if (isstring(arguments)) then feedback = arguments end end -- run the command if all the checks passed if (!feedback) then local results = {command:OnRun(client, unpack(arguments))} local phrase = results[1] -- check to see if the command has returned a phrase string and display it if (isstring(phrase)) then if (IsValid(client)) then if (phrase:sub(1, 1) == "@") then client:NotifyLocalized(phrase:sub(2), unpack(results, 2)) else client:Notify(phrase) end else -- print message since we're running from the server console print(phrase) end end client.ixCommandCooldown = RealTime() + 0.5 if (IsValid(client)) then ix.log.Add(client, "command", COMMAND_PREFIX .. command.name, argumentsTable and table.concat(argumentsTable, " ")) end else client:Notify(feedback) end end --- Parses a chat string and runs the command if one is found. Specifically, it checks for commands in a string with the -- format `/CommandName some arguments` -- @realm server -- @player client Player who is executing the command -- @string text Input string to search for the command format -- @string[opt] realCommand Specific command to check for. If this is specified, it will not try to run any command that's -- found at the beginning - only if it matches `realCommand` -- @tab[opt] arguments Array of arguments to pass to the command. If not specified, it will try to extract it from the -- string specified in `text` using `ix.command.ExtractArgs` -- @treturn bool Whether or not a command has been found -- @usage ix.command.Parse(player.GetByID(1), "/roll 10") function ix.command.Parse(client, text, realCommand, arguments) if (realCommand or text:utf8sub(1, 1) == COMMAND_PREFIX) then -- See if the string contains a command. local match = realCommand or text:lower():match(COMMAND_PREFIX.."([_%w]+)") -- is it unicode text? if (!match) then local post = string.Explode(" ", text) local len = string.len(post[1]) match = post[1]:utf8sub(2, len) end match = match:lower() local command = ix.command.list[match] -- We have a valid, registered command. if (command) then -- Get the arguments like a console command. if (!arguments) then arguments = ix.command.ExtractArgs(text:sub(#match + 3)) end -- Runs the actual command. ix.command.Run(client, match, arguments) else if (IsValid(client)) then client:NotifyLocalized("cmdNoExist") else print("Sorry, that command does not exist.") end end return true end return false end concommand.Add("ix", function(client, _, arguments) local command = arguments[1] table.remove(arguments, 1) ix.command.Parse(client, nil, command or "", arguments) end) net.Receive("ixCommand", function(length, client) if ((client.ixNextCmd or 0) < CurTime()) then local command = net.ReadString() local indices = net.ReadUInt(4) local arguments = {} for _ = 1, indices do local value = net.ReadType() if (isstring(value) or isnumber(value)) then arguments[#arguments + 1] = tostring(value) end end ix.command.Parse(client, nil, command, arguments) client.ixNextCmd = CurTime() + 0.2 end end) else --- Request the server to run a command. This mimics similar functionality to the client typing `/CommandName` in the chatbox. -- @realm client -- @string command Unique ID of the command -- @param ... Arguments to pass to the command -- @usage ix.command.Send("roll", 10) function ix.command.Send(command, ...) local arguments = {...} net.Start("ixCommand") net.WriteString(command) net.WriteUInt(#arguments, 4) for _, v in ipairs(arguments) do net.WriteType(v) end net.SendToServer() end end
local HTTP = game:GetService("HttpService") local LOCA = game:GetService("LocalizationService") local ReplicatedStorage = game:GetService("ReplicatedStorage") local Anticheat = require(ReplicatedStorage.Shared.Anticheat) local Misc = ReplicatedStorage:WaitForChild("Misc") local baseUrl = "robeatscsgame.com/api/" baseUrl = "https://" .. baseUrl print(baseUrl) local function sendScore(data) local headers = { ["Content-Type"] = "application/json"; } local params = { Headers=headers; Body=HTTP:JSONEncode(data); Method="POST"; Url=baseUrl.."/score"; } local res = nil local suc, err = pcall(function() res = HTTP:RequestAsync(params) end) if not suc then warn(err) else print("Score sent with a status code of: " .. res.StatusCode) if res.StatusCode ~= 200 then return {} end local ret = {} local suc, err = pcall(function() ret = HTTP:JSONDecode(res.Body) end) if not suc then ret = {} end return ret end end local function getPlays(p_ID) p_ID = "P"..tostring(p_ID) local headers = { ["Content-Type"] = "application/json"; } local params = { Headers=headers; Method="GET"; Url=baseUrl.."/user/" + p_ID; } local res = nil local suc, err = pcall(function() res = HTTP:RequestAsync(params) end) if not suc then warn(err) return {} else if res.StatusCode ~= 200 then return {} end local ret = {} local suc, err = pcall(function() ret = HTTP:JSONDecode(res.Body) end) if not suc then ret = {} end return ret end end local function getMapLeaderboard(m_ID) local headers = { ["Content-Type"] = "application/json"; } local params = { Headers=headers; Method="GET"; Url=baseUrl.."/maps/" .. m_ID; } local res = nil local suc, err = pcall(function() res = HTTP:RequestAsync(params) end) if not suc then warn(err) return {} else if res.StatusCode ~= 200 then return {} end local ret = {} local suc, err = pcall(function() ret = HTTP:JSONDecode(res.Body) end) if not suc then ret = {} end return ret end end local function getGlobalLeaderboard() local headers = { ["Content-Type"] = "application/json"; } local params = { Headers=headers; Method="GET"; Url=baseUrl.."/global"; } local res = nil local suc, err = pcall(function() res = HTTP:RequestAsync(params) end) if not suc then warn(err) return {} else if res.StatusCode ~= 200 then return {} end local ret = {} local suc, err = pcall(function() ret = HTTP:JSONDecode(res.Body) end) if not suc then ret = {} end return ret end end local function getStats(p_ID) p_ID = "P"..tostring(p_ID) local headers = { ["Content-Type"] = "application/json"; } local params = { Headers=headers; Method="GET"; Url=baseUrl.."/stats/" .. p_ID; } local res = nil local suc, err = pcall(function() res = HTTP:RequestAsync(params) end) if not suc then warn(err) return {} else print(res.Body, res.StatusCode) if res.StatusCode ~= 200 then return {} end local ret = {} local suc, err = pcall(function() ret = HTTP:JSONDecode(res.Body) end) print(ret) if not suc then ret = {} end return ret end end -------------------------------------------------------------------------------------------------------------------- local hint = Instance.new("Hint") hint.Parent = workspace function getIdFromMap(map_name) local retString = "" for char in string.gmatch(map_name, ".") do if char ~= "[" then if char == "]" then break end retString = retString .. char end end return retString end --------------------- function calculateRating(rate, acc, difficulty) local ratemult = 1 if rate then if rate >= 1 then ratemult = 1 + (rate-1) * 0.6 else ratemult = 1 + (rate-1) * 2 end end return ratemult * ((acc/97)^4) * difficulty end local function valStat(stat) if stat ~= nil then return (stat.Rank ~= nil and stat.Data ~= nil) else return false end end local function getAvatarUrl(p_ID) local uri = game:GetService("Players"):GetUserThumbnailAsync(p_ID, Enum.ThumbnailType.HeadShot, Enum.ThumbnailSize.Size420x420) return uri end function round(num, numDecimalPlaces) local mult = 10^(numDecimalPlaces or 0) return math.floor(num * mult + 0.5) / mult end game.Players.PlayerAdded:Connect(function(p) local p_ID = p.UserId local leaderstats = Instance.new("IntValue") leaderstats.Parent = p leaderstats.Name = "leaderstats" local rank = Instance.new("StringValue") rank.Parent = leaderstats rank.Name = "Rank" local rating = Instance.new("NumberValue") rating.Parent = leaderstats rating.Name = "Rating" local country = Instance.new("StringValue") country.Parent = leaderstats country.Name = "Country" country.Value = LOCA:GetCountryRegionForPlayerAsync(p) local data = getStats(p_ID) if valStat(data) then if data.Rank then rank.Value = "#" .. tostring(tonumber(data.Rank) + 1) end if data.Data.Rating then rating.Value = data.Data.Rating end else rank.Value = "#??" rating.Value = 0 end end) game.Players.PlayerRemoving:Connect(function(p) -- idk bye i guess end) Misc.GetSongLeaderboard.OnServerInvoke = function(player, m_ID) return getMapLeaderboard(m_ID).content end Misc.GetTopPlays.OnServerInvoke = function(player) local p_ID = "P" .. tostring(player.UserId) return getPlays(p_ID) end Misc.GetGlobalLeaderboard.OnServerInvoke = function() return getGlobalLeaderboard() end Misc.SubmitScore.OnServerInvoke = function(player, data) local RBLXLeaderstats = player:WaitForChild("leaderstats") data.userid = player.UserId data.username = player.Name sendScore(data) end --[[local function CalculatePlayerRating(p_ID) local maps = game.ReplicatedStorage:WaitForChild("Songs") local ratings = {} local names = {} local rating = 0 local maxNumOfScores = 25 table.sort(ratings, function(a,b) return a > b end) for i, r in pairs(ratings) do if (not (i > maxNumOfScores)) then if i <= 10 then rating = rating + r * 1.5 else rating = rating + r end end end local plr_rating = math.floor(100 * rating / 30) / 100 return plr_rating end]]--
include("data/scripts/lib/utils/enum") EnumUtils.addNextKey(OrderButtonType, "Trade") if onClient() then local autotrade_initUI = MapCommands.initUI function MapCommands.initUI() autotrade_initUI() local order = {tooltip = "Trade"%_t, icon = "data/textures/icons/battery-pack.png", callback = "onTradePressed", type = OrderButtonType.Trade} table.insert(orders, order) local button = ordersContainer:createRoundButton(Rect(), order.icon, order.callback) button.tooltip = order.tooltip table.insert(orderButtons, button) end function MapCommands.onTradePressed() local player = Player() player:sendChatMessage("Fuck you") --MapCommands.clearOrdersIfNecessary() --MapCommands.enqueueOrder("addTradeOrder") end end
-- internationalization boilerplate local MP = minetest.get_modpath(minetest.get_current_modname()) local S, NS = dofile(MP.."/intllib.lua") -- A do-nothing "structural" node, to ensure all digtron nodes that are supposed to be connected to each other can be connected to each other. minetest.register_node("digtron:structure", { description = S("Digtron Structure"), _doc_items_longdesc = digtron.doc.structure_longdesc, _doc_items_usagehelp = digtron.doc.structure_usagehelp, groups = {cracky = 3, oddly_breakable_by_hand=3, digtron = 1}, drop = "digtron:structure", tiles = {"digtron_plate.png"}, drawtype = "nodebox", sounds = digtron.metal_sounds, climbable = true, walkable = false, paramtype = "light", is_ground_content = false, node_box = { type = "fixed", fixed = { {0.3125, 0.3125, -0.5, 0.5, 0.5, 0.5}, {0.3125, -0.5, -0.5, 0.5, -0.3125, 0.5}, {-0.5, 0.3125, -0.5, -0.3125, 0.5, 0.5}, {-0.5, -0.5, -0.5, -0.3125, -0.3125, 0.5}, {-0.3125, 0.3125, 0.3125, 0.3125, 0.5, 0.5}, {-0.3125, -0.5, 0.3125, 0.3125, -0.3125, 0.5}, {-0.5, -0.3125, 0.3125, -0.3125, 0.3125, 0.5}, {0.3125, -0.3125, 0.3125, 0.5, 0.3125, 0.5}, {-0.5, -0.3125, -0.5, -0.3125, 0.3125, -0.3125}, {0.3125, -0.3125, -0.5, 0.5, 0.3125, -0.3125}, {-0.3125, 0.3125, -0.5, 0.3125, 0.5, -0.3125}, {-0.3125, -0.5, -0.5, 0.3125, -0.3125, -0.3125}, } }, }) -- A modest light source that will move with the digtron, handy for working in a tunnel you aren't bothering to install permanent lights in. minetest.register_node("digtron:light", { description = S("Digtron Light"), _doc_items_longdesc = digtron.doc.light_longdesc, _doc_items_usagehelp = digtron.doc.light_usagehelp, groups = {cracky = 3, oddly_breakable_by_hand=3, digtron = 1}, drop = "digtron:light", tiles = {"digtron_plate.png^digtron_light.png"}, drawtype = "nodebox", paramtype = "light", is_ground_content = false, light_source = 10, sounds = default.node_sound_glass_defaults(), paramtype2 = "wallmounted", node_box = { type = "wallmounted", wall_top = {-0.25, 0.3125, -0.25, 0.25, 0.5, 0.25}, wall_bottom = {-0.25, -0.5, -0.25, 0.25, -0.3125, 0.25}, wall_side = {-0.5, -0.25, -0.25, -0.1875, 0.25, 0.25}, }, }) -- A simple structural panel minetest.register_node("digtron:panel", { description = S("Digtron Panel"), _doc_items_longdesc = digtron.doc.panel_longdesc, _doc_items_usagehelp = digtron.doc.panel_usagehelp, groups = {cracky = 3, oddly_breakable_by_hand=3, digtron = 1}, drop = "digtron:panel", tiles = {"digtron_plate.png"}, drawtype = "nodebox", paramtype = "light", is_ground_content = false, sounds = digtron.metal_sounds, paramtype2 = "facedir", node_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -0.375, 0.5}, }, collision_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -0.4375, 0.5}, }, }) -- A simple structural panel minetest.register_node("digtron:edge_panel", { description = S("Digtron Edge Panel"), _doc_items_longdesc = digtron.doc.edge_panel_longdesc, _doc_items_usagehelp = digtron.doc.edge_panel_usagehelp, groups = {cracky = 3, oddly_breakable_by_hand=3, digtron = 1}, drop = "digtron:edge_panel", tiles = {"digtron_plate.png"}, drawtype = "nodebox", paramtype = "light", is_ground_content = false, sounds = digtron.metal_sounds, paramtype2 = "facedir", node_box = { type = "fixed", fixed = { {-0.5, -0.5, 0.375, 0.5, 0.5, 0.5}, {-0.5, -0.5, -0.5, 0.5, -0.375, 0.375} }, }, collision_box = { type = "fixed", fixed = { {-0.5, -0.5, 0.4375, 0.5, 0.5, 0.5}, {-0.5, -0.5, -0.5, 0.5, -0.4375, 0.4375} }, }, }) minetest.register_node("digtron:corner_panel", { description = S("Digtron Corner Panel"), _doc_items_longdesc = digtron.doc.corner_panel_longdesc, _doc_items_usagehelp = digtron.doc.corner_panel_usagehelp, groups = {cracky = 3, oddly_breakable_by_hand=3, digtron = 1}, drop = "digtron:corner_panel", tiles = {"digtron_plate.png"}, drawtype = "nodebox", paramtype = "light", is_ground_content = false, sounds = digtron.metal_sounds, paramtype2 = "facedir", node_box = { type = "fixed", fixed = { {-0.5, -0.5, 0.375, 0.5, 0.5, 0.5}, {-0.5, -0.5, -0.5, 0.5, -0.375, 0.375}, {-0.5, -0.375, -0.5, -0.375, 0.5, 0.375}, }, }, collision_box = { type = "fixed", fixed = { {-0.5, -0.5, 0.4375, 0.5, 0.5, 0.5}, {-0.5, -0.5, -0.5, 0.5, -0.4375, 0.4375}, {-0.5, -0.4375, -0.5, -0.4375, 0.5, 0.4375}, }, }, })
COMMAND.name = 'ForceGetUp' COMMAND.description = 'command.forcegetup.description' COMMAND.syntax = 'command.forcegetup.syntax' COMMAND.permission = 'assistant' COMMAND.category = 'permission.categories.roleplay' COMMAND.arguments = 1 COMMAND.player_arg = 1 COMMAND.aliases = { 'forcegetup', 'plygetup' } function COMMAND:on_run(player, targets, delay) delay = math.clamp(tonumber(delay) or 0, 0, 60) for k, v in ipairs(targets) do if IsValid(v) and v:Alive() and v:is_ragdolled() then v:set_ragdoll_state(RAGDOLL_FALLENOVER) timer.simple(delay, function() if IsValid(v) and v:Alive() and v:is_ragdolled() then v:set_ragdoll_state(RAGDOLL_NONE) end end) end end self:notify_staff('command.forcegetup.message', { player = get_player_name(player), target = util.player_list_to_string(targets), time = delay }) end
local test = {} local json = require('arken.json') local Class = require('arken.oop.Class') local Person = Class.new("Person", "ActiveRecord") test.beforeAll = function() ActiveRecord.reset() ActiveRecord.config = "config/active_record_sqlite.json" local sql = [[ CREATE TABLE IF NOT EXISTS person ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR(250), observation TEXT, created_at TEXT, updated_at TEXT, total REAL )]] Person.adapter():execute(sql) end test.before = function() ActiveRecord.begin() end test.after = function() ActiveRecord.rollback() end test.afterAll = function() ActiveRecord.config = nil end test.should_insert_in_the_database = function() local p = Person.new() p.name = "Chris Weidman" p:save() local result for row in Person.adapter():connect():execute([[ SELECT * FROM person ]]):each() do result = row end assert(result.name == 'Chris Weidman', json.encode(result)) end test.define_primary_key = function() local p = Person.new() p.name = "Chris Weidman" p:save() assert(p.id > 0, json.encode(result)) end test.define_created_at = function() local p = Person.new() p.name = "Chris Weidman" p:save() assert(type(p.created_at) == 'string', p.created_at) end test.define_update_at_with_the_value_of_created_at = function() local p = Person.new() p.name = "Chris Weidman" p:save() assert(p.created_at == p.updated_at, p.update_at) end return test
--{{{ Screen locker command local locker_cmd = '~/dotfiles/bin/locker ' if beautiful.wallpaper then locker_cmd = locker_cmd .. beautiful.wallpaper end --}}} -- {{{ Autostart applications function run_once(cmd) findme = cmd firstspace = cmd:find(" ") if firstspace then findme = cmd:sub(0, firstspace-1) end awful.util.spawn_with_shell("pgrep -u $USER -x " .. findme .. " > /dev/null || (" .. cmd .. ")") end run_once(locker_cmd) run_once("nm-applet") -- run_once("urxvtd") -- run_once("unclutter -root") -- }}} -- {{{ Rules awful.rules.rules = { -- All clients will match this rule. { rule = { }, properties = { border_width = beautiful.border_width, border_color = beautiful.border_normal, focus = awful.client.focus.filter, keys = clientkeys, buttons = clientbuttons, size_hints_honor = false } }, { rule = { class = "URxvt" }, properties = { opacity = 0.99 } }, { rule = { class = "MPlayer" }, properties = { floating = true } }, { rule = { class = "Dwb" }, properties = { tag = tags[1][1] } }, { rule = { class = "Iron" }, properties = { tag = tags[1][1] } }, { rule = { instance = "plugin-container" }, properties = { tag = tags[1][1] } }, { rule = { class = "Gimp" }, properties = { tag = tags[1][4] } }, { rule = { class = "Gimp", role = "gimp-image-window" }, properties = { maximized_horizontal = true, maximized_vertical = true } }, } -- }}} -- {{{ Signals -- Signal function to execute when a new client appears. local sloppyfocus_last = {c=nil} client.connect_signal("manage", function (c, startup) -- Enable sloppy focus client.connect_signal("mouse::enter", function(c) if awful.layout.get(c.screen) ~= awful.layout.suit.magnifier and awful.client.focus.filter(c) then -- Skip focusing the client if the mouse wasn't moved. if c ~= sloppyfocus_last.c then client.focus = c sloppyfocus_last.c = c end end end) local titlebars_enabled = false if titlebars_enabled and (c.type == "normal" or c.type == "dialog") then -- buttons for the titlebar local buttons = awful.util.table.join( awful.button({ }, 1, function() client.focus = c c:raise() awful.mouse.client.move(c) end), awful.button({ }, 3, function() client.focus = c c:raise() awful.mouse.client.resize(c) end) ) -- Widgets that are aligned to the right local right_layout = wibox.layout.fixed.horizontal() right_layout:add(awful.titlebar.widget.floatingbutton(c)) right_layout:add(awful.titlebar.widget.maximizedbutton(c)) right_layout:add(awful.titlebar.widget.stickybutton(c)) right_layout:add(awful.titlebar.widget.ontopbutton(c)) right_layout:add(awful.titlebar.widget.closebutton(c)) -- The title goes in the middle local middle_layout = wibox.layout.flex.horizontal() local title = awful.titlebar.widget.titlewidget(c) title:set_align("center") middle_layout:add(title) middle_layout:buttons(buttons) -- Now bring it all together local layout = wibox.layout.align.horizontal() layout:set_right(right_layout) layout:set_middle(middle_layout) awful.titlebar(c,{size=16}):set_widget(layout) end end) -- No border for maximized clients client.connect_signal("focus", function(c) if c.maximized_horizontal == true and c.maximized_vertical == true then c.border_color = beautiful.border_normal else c.border_color = beautiful.border_focus end end) client.connect_signal("unfocus", function(c) c.border_color = beautiful.border_normal end) -- }}} -- {{{ Arrange signal handler for s = 1, screen.count() do screen[s]:connect_signal("arrange", function () local clients = awful.client.visible(s) local layout = awful.layout.getname(awful.layout.get(s)) if #clients > 0 then -- Fine grained borders and floaters control for _, c in pairs(clients) do -- Floaters always have borders if awful.client.floating.get(c) or layout == "floating" then c.border_width = beautiful.border_width -- No borders with only one visible client elseif #clients == 1 or layout == "max" then c.border_width = 0 else c.border_width = beautiful.border_width end end end end) end -- }}}
local M = {} function M.temporary(str) vim.validate({ str = { str, "string", true } }) local path = vim.fn.tempname() local f = io.open(path, "w") if str then f:write(str) end f:close() return path end function M.find_upward_dir(child_pattern) local found_file = vim.fn.findfile(child_pattern, ".;") if found_file ~= "" then return vim.fn.fnamemodify(found_file, ":p:h") end local found_dir = vim.fn.finddir(child_pattern, ".;") if found_dir ~= "" then return vim.fn.fnamemodify(found_dir, ":p:h:h") end return nil end function M.find_upward_file(child_pattern) local found_file = vim.fn.findfile(child_pattern, ".;") if found_file ~= "" then return vim.fn.fnamemodify(found_file, ":p") end return nil end function M.escape(path) return ([[`='%s'`]]):format(path:gsub("'", "''")) end return M
local helpers = require('test.functional.helpers')(after_each) local thelpers = require('test.functional.terminal.helpers') local lfs = require('lfs') local clear = helpers.clear local nvim_prog = helpers.nvim_prog local feed_command = helpers.feed_command local feed_data = thelpers.feed_data if helpers.pending_win32(pending) then return end describe('autoread TUI FocusGained/FocusLost', function() local screen before_each(function() clear() screen = thelpers.screen_setup(0, '["'..nvim_prog ..'", "-u", "NONE", "-i", "NONE", "--cmd", "set noswapfile noshowcmd noruler"]') end) it('external file change', function() local path = 'xtest-foo' local expected_addition = [[ line 1 line 2 line 3 line 4 ]] helpers.write_file(path, '') lfs.touch(path, os.time() - 10) feed_command('edit '..path) feed_data('\027[O') screen:expect{grid=[[ {1: } | {4:~ }| {4:~ }| {4:~ }| {5:xtest-foo }| :edit xtest-foo | {3:-- TERMINAL --} | ]]} helpers.write_file(path, expected_addition) feed_data('\027[I') screen:expect{grid=[[ {1:l}ine 1 | line 2 | line 3 | line 4 | {5:xtest-foo }| "xtest-foo" 4L, 28C | {3:-- TERMINAL --} | ]]} end) end)
object_mobile_ep3_jyykle_vulture = object_mobile_shared_ep3_jyykle_vulture:new { } ObjectTemplates:addTemplate(object_mobile_ep3_jyykle_vulture, "object/mobile/ep3_jyykle_vulture.iff")
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire User" ENT.RenderGroup = RENDERGROUP_BOTH ENT.WireDebugName = "User" function ENT:SetupDataTables() self:NetworkVar( "Float", 0, "BeamLength" ) end if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Inputs = WireLib.CreateInputs(self, {"Fire"}) self:Setup(2048) end function ENT:Setup(Range) if Range then self:SetBeamLength(Range) end end function ENT:TriggerInput(iname, value) if iname == "Fire" and value ~= 0 then local vStart = self:GetPos() local trace = util.TraceLine( { start = vStart, endpos = vStart + (self:GetUp() * self:GetBeamLength()), filter = { self }, }) if not IsValid(trace.Entity) then return false end local ply = self:GetPlayer() if not IsValid(ply) then ply = self end if not hook.Run( "PlayerUse", ply, trace.Entity ) then return false end if trace.Entity.Use then trace.Entity:Use(self,ply,USE_ON,0) else trace.Entity:Fire("use","1",0) end end end duplicator.RegisterEntityClass("gmod_wire_user", WireLib.MakeWireEnt, "Data", "Range")
sir("DieRollInterceptable", 1) ssr("DieRollDescription", "Great Disaster") ssr("DieRollChoice1", "Earthquake") ssr("DieRollChoice2", "Earthquake") ssr("DieRollChoice3", "Earthquake") ssr("DieRollChoice4", "Eruption") ssr("DieRollChoice5", "Great River") ssr("DieRollChoice6", "Plague") ssr("DieRollChoice7", "Fallen Star") ssr("DieRollChoice8", "Primordial") sir("DieSides", 8) push("System.DieRoll") sir("DieRollInterceptable", 0) local result = gir("DieRollResult") if (result >= 1 and result <= 3) then push("Disaster.Earthquake") elseif (result == 4) then push("Disaster.VolcanicEruption") elseif (result == 5) then if (gir("RiverCount") <= 2) then push("Primordial.UndergroundRiver") else push("Disaster.Earthquake") end elseif (result == 6) then push("Disaster.Plague") elseif (result == 7) then push("Disaster.FallenStar") elseif (result == 8) then push("Primordial._DieRoll") end
return { { effect_list = { { type = "BattleBuffAddAttrRatio", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "dodgeRate", number = -500 } } } }, { effect_list = { { type = "BattleBuffAddAttrRatio", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "dodgeRate", number = -610 } } } }, { effect_list = { { type = "BattleBuffAddAttrRatio", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "dodgeRate", number = -720 } } } }, { effect_list = { { type = "BattleBuffAddAttrRatio", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "dodgeRate", number = -830 } } } }, { effect_list = { { type = "BattleBuffAddAttrRatio", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "dodgeRate", number = -940 } } } }, { effect_list = { { type = "BattleBuffAddAttrRatio", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "dodgeRate", number = -1050 } } } }, { effect_list = { { type = "BattleBuffAddAttrRatio", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "dodgeRate", number = -1160 } } } }, { effect_list = { { type = "BattleBuffAddAttrRatio", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "dodgeRate", number = -1270 } } } }, { effect_list = { { type = "BattleBuffAddAttrRatio", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "dodgeRate", number = -1380 } } } }, { effect_list = { { type = "BattleBuffAddAttrRatio", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "dodgeRate", number = -1500 } } } }, init_effect = "", name = "", time = 10, color = "red", picture = "", desc = "降低机动", stack = 1, id = 13793, icon = 13790, last_effect = "Darkness", effect_list = { { type = "BattleBuffAddAttrRatio", trigger = { "onAttach", "onRemove" }, arg_list = { attr = "dodgeRate", number = -500 } } } }
-- Commands by Devieth. -- Script for SAPP api_version = "1.10.0.0" -- Vanished player list player_vanished = {} player_respawn_time = {} function OnScriptLoad() register_callback(cb['EVENT_TICK'], "OnEventTick") register_callback(cb['EVENT_COMMAND'], "OnEventCommand") register_callback(cb['EVENT_DIE'], "OnPlayerDeath") end function OnScriptUnload() end -- We need this cause SAPP. function OnEventCommand(PlayerIndex, Command, Enviroment, Password) -- Make 'Message' a local and default it to false to prevent blocking other commands. local Message = false -- Tokenize the string (and remove quotations.) local t = tokenizestring(string.lower(string.gsub(Command, '"', "")), " ") -- Get command mode (enable or disable.) local Command, Mode = process_command(t[1]) -- Are they an admin or is this being executed from the console. if get_var(PlayerIndex, "$lvl") ~= "-1" or Enviroment == "0" then if Command == "vanish" then -- Execute the command. Message = command_vanish(t[2], PlayerIndex, Mode) elseif Command == "resp" then Message = command_respawn_time(t[2], PlayerIndex, t[3]) Allow = false end end -- Wes a message return from the command. if Message then -- Return result to the executer. rcon_return(tonumber(Enviroment), PlayerIndex, Message) return false end end function OnEventTick() for i = 1,16 do if player_present(i) then if player_vanished[i] then -- Set player's visable bipd Z coord below the map. write_float(get_player(i) + 0x100, -1000) end end end end function OnPlayerDeath(VictimIndex, KillerIndex) if player_respawn_time[tonumber(VictimIndex)] then -- Set player respawn time. write_dword(get_player(VictimIndex) + 0x2C, player_respawn_time[tonumber(VictimIndex)] * 30) end end function command_vanish(TargetIndex, UserIndex, Mode) -- Is there a target? if TargetIndex then -- If so make sure they are a valid target. local PlayerIndex = get_valid_player(TargetIndex, UserIndex) if PlayerIndex then -- Mode 1 = enable if Mode == 1 then player_vanished[PlayerIndex] = true return get_name(PlayerIndex).. " has vanished." else -- mode 0 = disable player_vanished[PlayerIndex] = false return get_name(PlayerIndex).. " has unvanished." end end return "Error: Player is not present." end return "Error: No player specified." end function command_respawn_time(TargetIndex, UserIndex, Time) if TargetIndex then local PlayerIndex = get_valid_player(TargetIndex, UserIndex) if PlayerIndex then if tonumber(Time) then player_respawn_time[PlayerIndex] = tonumber(Time) return get_name(PlayerIndex).."'s respawn time set to "..tonumber(Time).." seconds." end player_respawn_time[PlayerIndex] = nil return get_name(PlayerIndex).."'s respawn time has been reset." end return "Error: Player is not present." end return "Error: No player specified." end function get_name(PlayerIndex) return get_var(PlayerIndex, "$name") end function get_valid_player(Player, UserIndex) local PlayerIndex = nil if Player ~= nil then if string.lower(Player) == "me" then return tonumber(UserIndex) end if tonumber(Player) then if tonumber(Player) > 0 and tonumber(Player) < 17 then if player_present(tonumber(Player)) then PlayerIndex = tonumber(Player) end end end end return PlayerIndex end function rcon_return(Enviroment, PlayerIndex, Message) local Compatable_Message = string.gsub(tostring(Message), "|t", " ") if Enviroment == 0 then -- Console cprint(Compatable_Message,14) elseif Enviroment == 1 then -- Rcon rprint(PlayerIndex, Message) elseif Enviroment == 2 then -- Chat say(PlayerIndex, Compatable_Message) end end function process_command(Command) if string.sub(Command, 1,2) == "un" then return string.sub(Command, 3, string.len(Command)), 0 end return Command, 1 end function tokenizestring(inputstr, sep) if sep == nil then sep = "%s" end local t={} ; i=1 for str in string.gmatch(inputstr, "([^"..sep.."]+)") do t[i] = str i = i + 1 end return t end
return redis.call('RPUSH',KEYS[1],ARGV[1]);
describe('utility functions', function() describe('time conversions', function() it('converts back and forth', function() wow.state.localTime = 100 wow.state.serverTime = 200 assert.same(180, wow.addon.LocalToServer(80)) assert.same(80, wow.addon.ServerToLocal(180)) end) it('clamps to zero', function() wow.state.localTime = 100 wow.state.serverTime = 200 assert.same(0, wow.addon.LocalToServer(0)) assert.same(0, wow.addon.ServerToLocal(0)) end) end) describe('non-combat eventer', function() local function eventer(wow, events) local counts = {} local handlers = {} for _, e in ipairs(events) do handlers[e] = function() counts[e] = (counts[e] or 0) + 1 end end wow.addon.NonCombatEventer(handlers) assert.same({}, counts) return counts end it('works like a normal eventer outside of combat', function() local event = 'SKILL_LINES_CHANGED' local counts = eventer(wow, {event}) wow.state:SendEvent(event) assert.same({ [event] = 1 }, counts) end) it('waits till after combat to fire', function() local event = 'SKILL_LINES_CHANGED' local counts = eventer(wow, {event}) wow.state:EnterCombat() wow.state:SendEvent(event) assert.same({}, counts) wow.state:SendEvent(event) assert.same({}, counts) wow.state:LeaveCombat() assert.same({ [event] = 2 }, counts) end) it('supports PLAYER_REGEN_ENABLED', function() local event = 'PLAYER_REGEN_ENABLED' local counts = eventer(wow, {event}) wow.state:SendEvent(event) assert.same({ [event] = 1 }, counts) end) end) describe('pre-click button', function() it('returns the button', function() local count = 0 local button = wow.addon.PreClickButton('Foo', 'moo', function() count = count + 1 return 'cow' .. count end) assert.equal(wow.env.mooFoo, button) button:Click() wow.state:EnterCombat() button:Click() wow.state:LeaveCombat() button:Click() assert.same({ { macro = 'cow1' }, { macro = 'moo' }, { macro = 'cow2' }, }, wow.state.commands) end) end) describe('updater', function() it('runs on first tick', function() local count = 0 wow.addon.Updater(10000, function() count = count + 1 end) wow.state:TickUpdate(1) assert.same(1, count) end) it('respects period', function() local count = 0 wow.addon.Updater(10000, function() count = count + 1 end) for _ = 1, 9999 do wow.state:TickUpdate(1) end assert.same(1, count) wow.state:TickUpdate(1) assert.same(1, count) wow.state:TickUpdate(1) assert.same(2, count) end) end) end)
--- -- Viewport.lua - ViewportFrame with limited simulated physics and controls -- local ReplicatedStorage = game:GetService("ReplicatedStorage") local Create = ReplicatedStorage.Common.Create local CreateModule = require(Create.CreateModule) local Viewport = {} Viewport.__index = Viewport function Viewport.new(parent, disableInput) local self = setmetatable({}, Viewport) local viewport = Instance.new("ViewportFrame") viewport.Active = true viewport.BackgroundColor3 = Color3.fromRGB(0, 0, 0) viewport.BorderSizePixel = 0 viewport.Parent = parent self.Viewport = viewport local camera = Instance.new("Camera") viewport.CurrentCamera = camera camera.Parent = viewport self.Camera = camera self.FocalPoint = Vector3.new(0, 0, 0) self.Rotation = Vector2.new(0, 0) self.Offset = Vector3.new(0, 0, 0) self.Zoom = 1 -- Smaller number = more zoom if disableInput then return self end -- Input Handling local function handleScroll(input) local scroll = input.Position.Z self.Zoom = self.Zoom - scroll * 0.1 self:updateCamera() end local mouseDown = false viewport.InputBegan:Connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Touch then mouseDown = true elseif input.UserInputType == Enum.UserInputType.MouseWheel then handleScroll(input) end end) local lastPos viewport.InputChanged:Connect(function(input) if (input.UserInputType == Enum.UserInputType.MouseMovement or input.UserInputType == Enum.UserInputType.Touch) and mouseDown then if lastPos then local kSensitivity = 1 -- Pixels per degree local delta = input.Position - lastPos local dX = delta.X / kSensitivity * math.pi / 180 local dY = delta.Y / kSensitivity * math.pi / 180 local kMaxXRot = math.pi / 2 - 1e-1 -- Prevent weirdness that is too much of a pain to deal with. local targetX = math.min(math.max(self.Rotation.X + dY, -kMaxXRot), kMaxXRot) local targetY = (self.Rotation.Y - dX) % (2 * math.pi) self.Rotation = Vector2.new(targetX, targetY) self:updateCamera() end lastPos = input.Position elseif input.UserInputType == Enum.UserInputType.MouseWheel then handleScroll(input) end end) viewport.InputEnded:Connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Touch then mouseDown = false lastPos = nil end end) return self end function Viewport:updateSubject() CreateModule.fixJoints(self.Viewport) end function Viewport:setFocalCFrame(cf) self.FocalPoint = (cf * (cf - cf.Position):Inverse()).Position end function Viewport:updateCamera() local rotation = CFrame.fromEulerAnglesYXZ(self.Rotation.X, self.Rotation.Y, 0) self.Camera.CFrame = CFrame.lookAt(self.FocalPoint + rotation * self.Offset * self.Zoom, self.FocalPoint) end return Viewport
-------------------------------------------------------------------------- -- Crytek Source File. -- Copyright (C), Crytek Studios, 2001-2006. -------------------------------------------------------------------------- -- $Id$ -- $DateTime$ -- Description: Switch entity for both FG and Prefab use. -- -------------------------------------------------------------------------- -- History: -- - 19:5:2006 : Created by Sascha Gundlach -- -------------------------------------------------------------------------- Switch = { Client = {}, Server = {}, Properties = { fileModel = "objects/props/industrial/electrical/lightswitch/lightswitch_local1.cgf", Switch = "Props_Interactive.switches.small_switch", ModelSubObject = "", fileModelDestroyed = "", DestroyedSubObject = "", fHealth = 100, bDestroyable = 0, bUsable = 1, UseMessage = "Use Light Switch", bTurnedOn = 0, Physics = { bRigidBody = 0, bRigidBodyActive = 0, bRigidBodyAfterDeath = 1, bResting = 1, Density = -1, Mass = 1, }, Sound = { soundTurnOnSound = "", soundTurnOffSound = "", }, SwitchPos = { bShowSwitch = 1, On = 35, Off = -35, }, SmartSwitch = { bUseSmartSwitch=0, Entity = "", TurnedOnEvent = "", TurnedOffEvent = "", }, Breakage = { fLifeTime = 20, fExplodeImpulse = 0, bSurfaceEffects = 1, }, Destruction = { bExplode = 0, Effect = "", EffectScale = 0, Radius = 0, Pressure = 0, Damage = 0, Decal = "", Direction = {x=0, y=0, z=-1}, }, }, Editor = { Icon = "switch.bmp", IconOnTop = 1, }, States = {"TurnedOn","TurnedOff","Destroyed"}, fCurrentSpeed = 0, fDesiredSpeed = 0, LastHit = { impulse = {x=0,y=0,z=0}, pos = {x=0,y=0,z=0}, }, shooterId = nil, } Net.Expose{ Class = Switch, ClientMethods = { OnUsed_Internal = { RELIABLE_ORDERED, PRE_ATTACH, ENTITYID }, Destroy = { RELIABLE_ORDERED, PRE_ATTACH }, }, ServerMethods = { SvRequestUse = { RELIABLE_ORDERED, PRE_ATTACH, ENTITYID }, }, } function Switch:OnPropertyChange() self:OnReset(); end; function Switch:OnSave(tbl) tbl.switch=self.switch; tbl.usable=self.usable; end; function Switch:OnLoad(tbl) self.switch=tbl.switch; self.usable=tbl.usable; if(self:GetState() ~= "Destroyed") then self:PhysicalizeThis(0); self:SetCurrentSlot(0); else local tmp=self.Properties.Physics.bRigidBody; self.Properties.Physics.bRigidBody=self.Properties.Physics.bRigidBodyAfterDeath; self:PhysicalizeThis(1); self.Properties.Physics.bRigidBody=tmp; self:SetCurrentSlot(1); end end; function Switch:OnReset() local props=self.Properties; self.health=props.fHealth; self.usable=self.Properties.bUsable; if(not EmptyString(props.fileModel))then self:LoadSubObject(0,props.fileModel,props.ModelSubObject); end; if(not EmptyString(props.fileModelDestroyed))then self:LoadSubObject(1, props.fileModelDestroyed,props.DestroyedSubObject); elseif(not EmptyString(props.DestroyedSubObject))then self:LoadSubObject(1,props.fileModel,props.DestroyedSubObject); end; self:SetCurrentSlot(0); self:PhysicalizeThis(0); if(not EmptyString(self.Properties.Switch))then self:SpawnSwitch(); end; if(self.Properties.bTurnedOn==1)then self:GotoState("TurnedOn"); else self:GotoState("TurnedOff"); end; end; function Switch:PhysicalizeThis(slot) local physics = self.Properties.Physics; EntityCommon.PhysicalizeRigid( self,slot,physics,1 ); end; function Switch.Client:OnHit(hit, remote) CopyVector(self.LastHit.pos, hit.pos); CopyVector(self.LastHit.impulse, hit.dir); self.LastHit.impulse.x = self.LastHit.impulse.x * hit.damage; self.LastHit.impulse.y = self.LastHit.impulse.y * hit.damage; self.LastHit.impulse.z = self.LastHit.impulse.z * hit.damage; end function Switch.Server:OnHit(hit) self.shooterId=hit.shooterId; BroadcastEvent( self,"Hit" ); if (self.Properties.bDestroyable==1) then self.health=self.health-hit.damage; if(self.health<=0)then self.allClients:Destroy(); end; end end; function Switch:Explode() local props=self.Properties; local hitPos = self.LastHit.pos; local hitImp = self.LastHit.impulse; self:BreakToPieces( 0, 0, props.Breakage.fExplodeImpulse, hitPos, hitImp, props.Breakage.fLifeTime, props.Breakage.bSurfaceEffects ); if(NumberToBool(self.Properties.Destruction.bExplode))then local explosion=self.Properties.Destruction; g_gameRules:CreateExplosion(self.shooterId,self.id,explosion.Damage,self:GetWorldPos(),explosion.Direction,explosion.Radius,nil,explosion.Pressure,explosion.HoleSize,explosion.Effect,explosion.EffectScale); end; self:SetCurrentSlot(1); if(props.Physics.bRigidBodyAfterDeath==1)then local tmp=props.Physics.bRigidBody; props.Physics.bRigidBody=1; self:PhysicalizeThis(1); props.Physics.bRigidBody=tmp; else self:PhysicalizeThis(1); end; self:RemoveDecals(); self:AwakePhysics(1); self:OnDestroy(); end; function Switch:SetCurrentSlot(slot) if (slot == 0) then self:DrawSlot(0, 1); self:DrawSlot(1, 0); else self:DrawSlot(0, 0); self:DrawSlot(1, 1); end; self.currentSlot = slot; end function Switch:SetSwitch(state) if(self.switch==nil)then return;end; local props=self.Properties.SwitchPos; if(props.bShowSwitch==0)then return;end; local props=self.Properties.SwitchPos; local rot={x=0,y=0,z=0}; if(state==1)then self.switch:GetAngles(rot); rot.y=props.On*g_Deg2Rad; else self.switch:GetAngles(rot); rot.y=props.Off*g_Deg2Rad; end; self.switch:SetAngles(rot); end; function Switch:SpawnSwitch() if(self.switch)then Entity.DetachThis(self.switch.id,0); System.RemoveEntity(self.switch.id); self.switch=nil; end; local props=self.Properties.SwitchPos; if(props.bShowSwitch==0)then return;end; if(self.switch==nil)then if(self.Properties.Switch=="")then Log("No switch found for switch object "..self:GetName()); else local spawnParams = {}; spawnParams.class = "BasicEntity"; Log("self.Properties.Switch: "..self.Properties.Switch); spawnParams.archetype=self.Properties.Switch; spawnParams.name = self:GetName().."_switch"; spawnParams.flags = 0; spawnParams.position=self:GetPos(); self.switch=System.SpawnEntity(spawnParams); self:AttachChild(self.switch.id,0); self.switch:SetWorldPos(self:GetPos()); self.switch:SetWorldAngles(self:GetAngles()); self:SetSwitch(self.Properties.bTurnedOn); end; end; end; function Switch:OnDestroy() if(self.switch)then Entity.DetachThis(self.switch.id,0); System.RemoveEntity(self.switch.id); self.switch=nil; end; end ---------------------------------------------------------------------------------------------------- function Switch.Server:OnInit() if(not self.bInitialized)then self:OnReset(); self.bInitialized=1; self.usable=1; end; end; ---------------------------------------------------------------------------------------------------- function Switch.Client:OnInit() if(not self.bInitialized)then self:OnReset(); self.bInitialized=1; end; end; ---------------------------------------------------------------------------------------------------- -- Entry point for OnUsed events function Switch:OnUsed(user, idx) self.server:SvRequestUse(user.id); end; ---------------------------------------------------------------------------------------------------- -- clients use this to request a use to the server function Switch.Server:SvRequestUse(userId) self.allClients:OnUsed_Internal(userId); end; ---------------------------------------------------------------------------------------------------- -- the function that really does the work when the switch is used function Switch.Client:OnUsed_Internal(userId) self:ActivateOutput( "UsedBy", userId ); if(self:GetState()=="TurnedOn")then self:GotoState("TurnedOff"); elseif(self:GetState()=="TurnedOff")then self:GotoState("TurnedOn"); elseif(self:GetState()=="Destroyed")then return end; BroadcastEvent(self, "Used"); end; function Switch:IsUsable(user) if((self:GetState()~="Destroyed") and self.usable==1)then return 2; else return 0; end; end; function Switch:GetUsableMessage(idx) if(self.Properties.bUsable==1)then return self.Properties.UseMessage; else return "@use_object"; end; end; function Switch:PlaySound(sound) if(sound and sound~="")then local snd=self.Properties.Sound["sound"..sound]; -- REINSTANTIATE!!! --local sndFlags=bor(SOUND_DEFAULT_3D, 0); if(snd and snd~="")then -- REINSTANTIATE!!! --self.soundid=self:PlaySoundEvent(snd,g_Vectors.v000,g_Vectors.v010,sndFlags,0,SOUND_SEMANTIC_MECHANIC_ENTITY); else --System.Log("Failed to play "..sound.." sound!"); end; end; end; function Switch:CheckSmartSwitch(switch) local props=self.Properties.SmartSwitch; if(props.bUseSmartSwitch==1)then local entities=System.GetEntitiesInSphere(self:GetPos(),50); local targets={}; for i,v in ipairs(entities) do if(v:GetName()==props.Entity)then table.insert(targets,v); end; end --Get closest table.sort(targets, function(a, b) local dista=self:GetDistance(a.id); local distb=self:GetDistance(b.id); if(dista<distb)then return true; end end); local target=targets[1]; if(target)then if(props[switch]~="")then local evtName="Event_"..props[switch]; local evtProc=target[evtName]; if(type(evtProc)=="function")then --System.Log("Sending: "..switch.." to "..target:GetName()); evtProc(target); else System.Log(self:GetName().." was trying to send an invalid event! Check entity properties!"); end; end; end; end; end; ---------------------------------------------------------------------------------- ------------------------------------Events---------------------------------------- ---------------------------------------------------------------------------------- function Switch:Event_Destroyed() BroadcastEvent(self, "Destroyed"); self:GotoState("Destroyed"); end; function Switch:Event_TurnedOn() BroadcastEvent(self, "TurnedOn"); self:GotoState("TurnedOn"); end; function Switch:Event_TurnedOff() BroadcastEvent(self, "TurnedOff"); self:GotoState("TurnedOff"); end; function Switch:Event_Switch() if(self:GetState()~="Destroyed")then if(self:GetState()=="TurnedOn")then self:GotoState("TurnedOff"); elseif(self:GetState()=="TurnedOff")then self:GotoState("TurnedOn"); end; end; end; function Switch:Event_Hit(sender) BroadcastEvent( self,"Hit" ); end; function Switch:Event_Enable(sender) self.usable=1; BroadcastEvent( self,"Enable" ); end; function Switch:Event_Disable(sender) self.usable=0; BroadcastEvent( self,"Disable" ); end; function Switch:Event_Hide(sender) self:Hide(1); BroadcastEvent( self,"Hide" ); end; function Switch:Event_Unhide(sender) self:Hide(0); BroadcastEvent( self,"Unhide" ); end; ----------- This is just a bridge call. When the server decides that the switch is destroyed, in the OnHit function, it calls this on all clients to actually destroy it. ----------- Can't make GotoState() a client side callable function to just call it directly, because it is an internal C function. function Switch.Client:Destroy() self:GotoState( "Destroyed" ); end; ---------------------------------------------------------------------------------- ------------------------------------States---------------------------------------- ---------------------------------------------------------------------------------- Switch.Client.TurnedOn = { OnBeginState = function( self ) self:PlaySound("TurnOnSound"); --temporarily disabled self:SetSwitch(1); self:CheckSmartSwitch("TurnedOnEvent"); BroadcastEvent(self, "TurnedOn"); end, OnEndState = function( self ) end, } Switch.Client.TurnedOff = { OnBeginState = function( self ) self:PlaySound("TurnOffSound"); --temporarily disabled self:SetSwitch(0); self:CheckSmartSwitch("TurnedOffEvent"); BroadcastEvent(self, "TurnedOff") end, OnEndState = function( self ) end, } Switch.Client.Destroyed= { OnBeginState = function( self ) self:Explode(); BroadcastEvent(self, "Destroyed") end, OnEndState = function( self ) end, } ---------------------------------------------------------------------------------- -------------------------------Flow-Graph Ports----------------------------------- ---------------------------------------------------------------------------------- Switch.FlowEvents = { Inputs = { Switch = { Switch.Event_Switch }, TurnedOn = { Switch.Event_TurnedOn }, TurnedOff = { Switch.Event_TurnedOff }, Hit = { Switch.Event_Hit, "bool" }, Destroyed = { Switch.Event_Destroyed, "bool" }, Disable = { Switch.Event_Disable, "bool" }, Enable = { Switch.Event_Enable, "bool" }, Hide = { Switch.Event_Hide, "bool" }, Unhide = { Switch.Event_Unhide, "bool" }, }, Outputs = { Hit = "bool", TurnedOn = "bool", TurnedOff = "bool", Destroyed = "bool", Disable = "bool", Enable = "bool", Hide = "bool", Unhide = "bool", UsedBy = "entity" }, }
local gcd = require("math.greatest_common_divisor") return function( a, -- number b -- number ) -- |a * b / gcd(a, b)| reordered in order to keep intermediate results small (to not hit number representation bounds) return math.abs(a / gcd(a, b) * b) -- least common multiple of a and b end
local L = Grid2Options.L function Grid2Options:MakeStatusDebuffsListOptions(status, options, optionParams) options.aurasList = { type = "input", dialogControl = "Grid2ExpandedEditBox", order = 155, width = "full", name = "", multiline = 16, get = function() local auras = {} for _,aura in pairs(status.dbx.auras) do auras[#auras+1]= (type(aura)=="number") and GetSpellInfo(aura) or aura end return table.concat( auras, "\n" ) end, set = function(_, v) wipe(status.dbx.auras) local auras = { strsplit("\n,", strtrim(v)) } for _,name in pairs(auras) do local aura = strtrim(name) if #aura>0 then table.insert(status.dbx.auras, tonumber(aura) or aura ) end end status:Refresh(true) end, hidden = function() return status.dbx.auras==nil end } return options end function Grid2Options:MakeStatusDebuffsFilterOptions(status, options, optionParams) self:MakeHeaderOptions( options, "Display" ) options.strictFiltering = { type = "toggle", width = "full", name = '|cFFffff00' .. L["Use strict filtering (all conditions must be met)."], desc = L[""], order = 80.5, get = function() return not status.dbx.lazyFiltering end, set = function(_,v) status.dbx.lazyFiltering = (not v) or nil status:Refresh(true) end, hidden = function() return status.dbx.useWhiteList end, } options.showDispelDebuffs = { type = "toggle", name = L["Dispellable by Me"], desc = L["Display debuffs i can dispell"], order = 81, get = function () return status.dbx.filterDispelDebuffs~=false end, set = function (_, v) if v then status.dbx.filterDispelDebuffs = nil else status.dbx.filterDispelDebuffs = false end if v~=nil and status.dbx.auras then status.dbx.aurasBak = status.dbx.auras status.dbx.auras = nil end status:Refresh(true) end, hidden = function() return status.dbx.useWhiteList end } options.showNonDispelDebuffs = { type = "toggle", name = L["Non Dispellable by Me"], desc = L["Display debuffs i can not dispell"], order = 81.5, get = function () return status.dbx.filterDispelDebuffs~=true end, set = function (_, v) status.dbx.filterDispelDebuffs = not v or nil if v~=nil and status.dbx.auras then status.dbx.aurasBak = status.dbx.auras status.dbx.auras = nil end status:Refresh(true) end, hidden = function() return status.dbx.useWhiteList end } options.filterSep00 = { type = "description", name = "", order = 81.9 } options.showTypedDebuffs = { type = "toggle", name = L["Typed Debuffs"], desc = L["Display Magic, Curse, Poison or Disease type debuffs."], order = 82, get = function () return status.dbx.filterTyped~=true end, set = function (_, v) status.dbx.filterTyped = (not v) or nil status:Refresh(true) end, hidden = function() return status.dbx.useWhiteList end } options.showUntypedDebuffs = { type = "toggle", name = L["Untyped Debuffs"], desc = L["Display debuffs with no type."], order = 83, get = function () return status.dbx.filterTyped~=false end, set = function (_, v) if v then status.dbx.filterTyped = nil else status.dbx.filterTyped = false end status:Refresh(true) end, hidden = function() return status.dbx.useWhiteList end } options.filterSep0 = { type = "description", name = "", order = 83.5 } options.showNonBossDebuffs = { type = "toggle", name = L["Non Boss Debuffs"], desc = L["Display debuffs not casted by Bosses"], order = 84, get = function () return status.dbx.filterBossDebuffs~=false end, set = function (_, v) if v then status.dbx.filterBossDebuffs = nil else status.dbx.filterBossDebuffs = false end status:Refresh(true) end, hidden = function() return status.dbx.useWhiteList end } options.showBossDebuffs = { type = "toggle", name = L["Boss Debuffs"], desc = L["Display debuffs direct casted by Bosses"], order = 85, get = function () return status.dbx.filterBossDebuffs~=true end, set = function (_, v) status.dbx.filterBossDebuffs = (not v) or nil status:Refresh(true) end, hidden = function() return status.dbx.useWhiteList end } options.filterSep1 = { type = "description", name = "", order = 85.5 } options.showShortDebuffs = { type = "toggle", name = L["Short Duration"], desc = L["Display debuffs with duration below 5 minutes."], order = 86, get = function () return status.dbx.filterLongDebuffs~=false end, set = function (_, v) if v then status.dbx.filterLongDebuffs = nil else status.dbx.filterLongDebuffs = false end status:Refresh(true) end, hidden = function() return status.dbx.useWhiteList end } options.showLongDebuffs = { type = "toggle", name = L["Long Duration"], desc = L["Display debuffs with duration above 5 minutes."], order = 87, get = function () return status.dbx.filterLongDebuffs~=true end, set = function (_, v) status.dbx.filterLongDebuffs = (not v) and true or nil status:Refresh(true) end, hidden = function() return status.dbx.useWhiteList end } options.filterSep2 = { type = "description", name = "", order = 87.5 } options.showNonSelfDebuffs = { type = "toggle", name = L["Non Self Casted"], desc = L["Display non self debuffs"], order = 88, get = function () return status.dbx.filterCaster~=false end, set = function (_, v) if v then status.dbx.filterCaster = nil else status.dbx.filterCaster = false end status:Refresh(true) end, hidden = function() return status.dbx.useWhiteList end } options.showSelfDebuffs = { type = "toggle", name = L["Self Casted"], desc = L["Display self debuffs"], order = 89, get = function () return status.dbx.filterCaster~=true end, set = function (_, v) status.dbx.filterCaster = (not v) and true or nil status:Refresh(true) end, hidden = function() return status.dbx.useWhiteList end } options.filterSep3 = { type = "description", name = "", order = 89.5 } options.useWhiteList = { type = "toggle", name = L["Whitelist"], desc = L["Display only debuffs contained in a user defined list."], order = 90, get = function () return status.dbx.useWhiteList and status.dbx.auras~=nil end, set = function (_, v) status.dbx.filterDispelDebuffs = nil status.dbx.filterLongDebuffs = nil status.dbx.filterBossDebuffs = nil status.dbx.filterCaster = nil status.dbx.filterTyped = nil if v then status.dbx.auras = status.dbx.auras or status.dbx.aurasBak or {} status.dbx.aurasBak = nil status.dbx.useWhiteList = true else status.dbx.aurasBak = status.dbx.auras status.dbx.auras = nil status.dbx.useWhiteList = nil end status:Refresh(true) self:MakeStatusOptions(status) end, } options.useBlackList = { type = "toggle", name = L["Blacklist"], desc = L["Ignore debuffs contained in a user defined list. This condition is always strict."], order = 91, get = function () return (not status.dbx.useWhiteList) and status.dbx.auras~=nil end, set = function (_, v) if v then status.dbx.auras = status.dbx.auras or status.dbx.aurasBak or {} status.dbx.aurasBak = nil else status.dbx.aurasBak = status.dbx.auras status.dbx.auras = nil end status.dbx.useWhiteList = nil status:Refresh(true) self:MakeStatusOptions(status) end, } end function Grid2Options:MakeStatusDebuffsGeneralOptions(status, options, optionParams) self:MakeStatusAuraDescriptionOptions(status, options, optionParams) self:MakeStatusAuraCommonOptions(status, options, optionParams) self:MakeStatusAuraTextOptions(status, options, optionParams) self:MakeStatusColorOptions(status, options, optionParams) self:MakeStatusAuraColorThresholdOptions(status, options, optionParams) self:MakeStatusBlinkThresholdOptions(status, options, optionParams) self:MakeStatusDebuffsFilterOptions(status, options, optionParams) return options end Grid2Options:RegisterStatusOptions("debuffs", "debuff", function(self, status, options, optionParams) self:MakeStatusTitleOptions(status, options, optionParams) options.settings = { type = "group", order = 10, name = L['General'], args = self:MakeStatusDebuffsGeneralOptions(status,{}, optionParams), } options.debuffslist = { type = "group", order = 20, name = L[ status.dbx.useWhiteList and 'Whitelist' or 'Blacklist'], desc = L["Type a list of debuffs, one debuff per line."], args = self:MakeStatusDebuffsListOptions(status,{}, optionParams), hidden = function() return status.dbx.auras==nil end } options.load = { type = "group", order = 30, name = L['Load'], args = self:MakeStatusLoadOptions( status, {}, optionParams ) } options.indicators = { type = "group", order = 40, name = L['indicators'], args = self:MakeStatusIndicatorsOptions(status,{}, optionParams) } end,{ groupOrder = 20, hideTitle = true, isDeletable = true, })
require 'torch' require 'nn' require 'image' local utils = require 'utils.misc' local DataLoader = require 'utils.DataLoader' require 'loadcaffe' cmd = torch.CmdLine() cmd:text('Options') cmd:option('-batch_size', 10, 'batch size') cmd:option('-split', 'train', 'train/val') cmd:option('-debug', 0, 'set debug = 1 for lots of prints') -- bookkeeping cmd:option('-seed', 981723, 'Torch manual random number generator seed') cmd:option('-proto_file', 'models/VGG_ILSVRC_19_layers_deploy.prototxt') cmd:option('-model_file', 'models/VGG_ILSVRC_19_layers.caffemodel') cmd:option('-data_dir', 'data', 'Data directory.') cmd:option('-feat_layer', 'relu7', 'Layer to extract features from') cmd:option('-input_image_dir', 'data', 'Image directory') -- gpu/cpu cmd:option('-gpuid', -1, '0-indexed id of GPU to use. -1 = CPU') opt = cmd:parse(arg or {}) torch.manualSeed(opt.seed) if opt.gpuid >= 0 then local ok, cunn = pcall(require, 'cunn') local ok2, cutorch = pcall(require, 'cutorch') if not ok then print('package cunn not found!') end if not ok2 then print('package cutorch not found!') end if ok and ok2 then print('using CUDA on GPU ' .. opt.gpuid .. '...') cutorch.setDevice(opt.gpuid + 1) cutorch.manualSeed(opt.seed) else print('If cutorch and cunn are installed, your CUDA toolkit may be improperly configured.') print('Check your CUDA toolkit installation, rebuild cutorch and cunn, and try again.') print('Falling back to CPU mode') opt.gpuid = -1 end end loader = DataLoader.create(opt.data_dir, opt.batch_size, opt, 'fc7_feat') cnn = loadcaffe.load(opt.proto_file, opt.model_file) if opt.gpuid >= 0 then cnn = cnn:cuda() end cnn_fc7 = nn.Sequential() for i = 1, #cnn.modules do local layer = cnn:get(i) local name = layer.name cnn_fc7:add(layer) if name == opt.feat_layer then break end end cnn_fc7:evaluate() if opt.gpuid >= 0 then cnn_fc7 = cnn_fc7:cuda() end tmp_image_id = {} for i = 1, #loader.data[opt.split] do tmp_image_id[loader.data[opt.split][i].image_id] = 1 end image_id = {} idx = 1 for i, v in pairs(tmp_image_id) do image_id[idx] = i idx = idx + 1 end fc7 = torch.DoubleTensor(#image_id, 4096) idx = 1 if opt.gpuid >= 0 then fc7 = fc7:cuda() end repeat local timer = torch.Timer() img_batch = torch.zeros(opt.batch_size, 3, 224, 224) img_id_batch = {} for i = 1, opt.batch_size do if not image_id[idx] then break end local fp = path.join(opt.input_image_dir, string.format('%s2014/COCO_%s2014_%.12d.jpg', opt.split, opt.split, image_id[idx])) if opt.debug == 1 then print(idx) print(fp) end img_batch[i] = utils.preprocess(image.scale(image.load(fp, 3), 224, 224)) img_id_batch[i] = image_id[idx] idx = idx + 1 end if opt.gpuid >= 0 then img_batch = img_batch:cuda() end fc7_batch = cnn_fc7:forward(img_batch:narrow(1, 1, #img_id_batch)) for i = 1, fc7_batch:size(1) do if opt.debug == 1 then print(idx - fc7_batch:size(1) + i - 1) end fc7[idx - fc7_batch:size(1) + i - 1]:copy(fc7_batch[i]) end if opt.gpuid >= 0 then cutorch.synchronize() end local time = timer:time().real print(idx-1 .. '/' .. #image_id .. " " .. time) collectgarbage() until idx >= #image_id torch.save(path.join(opt.data_dir, opt.split .. '_fc7.t7'), fc7) torch.save(path.join(opt.data_dir, opt.split .. '_fc7_image_id.t7'), image_id)
-- Projectiles.Lua -- Projectile definitions for LoveExtension library -- Copyright (c) 2011 Robert MacGregor local Projectiles = { } Projectiles.imageManager = require("scripts/Image.lua") Projectiles.enemyManager = require("scripts/Enemy.lua") Projectiles.collisionManager = require("scripts/Collision.lua") Projectiles.soundManager = require("scripts/Sound.lua") Projectiles.itemManager = require("scripts/Item.lua") require("scripts/Randomlua.lua") Projectiles.mTwister = twister(0) -- Default Beam local DefaultBeam = { Animation = { }, StartHealth = 1, MaxHealth = 1 } local DefaultBeamAnimation = { Speed = 0, Frame = { } } function DefaultBeam.update(dt, Object) if (Object.Position.X >= 650) then Object.delete() end Object.setPosition(vector2d(Object.Position.X + (dt * 120), Object.Position.Y)) --- Hacked Collision Detection for i = 1, Projectiles.enemyManager.getCount() do local Enemy = Projectiles.enemyManager.getEnemy(i) if (Projectiles.collisionManager.checkCollision(Object, Enemy)) then if (Enemy.Health <= 1 and Object.DELETE_ME == nil) then Enemy.delete() Object.delete() local Rnd = Projectiles.mTwister:random(1,4) if (Rnd < 4) then local newItem = Projectiles.itemManager.addItem(Projectiles.itemManager.ItemDataBase.Money) newItem.playAnimation("Animation") newItem.setPosition(Enemy.getPosition()) newItem.setScale(vector2d(1.5,1.5)) newItem.setVisible(true) newItem.Value = 10 end love.audio.play( Projectiles.soundManager.loadSound("media/sounds/Damage.wav")) elseif (Enemy.Health > 1 and Object.DELETE_ME == nil) then Enemy.Health = Enemy.Health - 1 Object.delete() love.audio.play( Projectiles.soundManager.loadSound("media/sounds/Damage.wav")) end end end end DefaultBeamAnimation.FrameCount = 1 DefaultBeamAnimation.Frame[1] = Projectiles.imageManager.loadImage("media/textures/Beam.png") DefaultBeam.Animation["BeamAnimation"] = DefaultBeamAnimation table.insert(Projectiles, DefaultBeam) Projectiles["DefaultBeam"] = DefaultBeam -- Missile local Missile = { Animation = { }, StartHealth = 1, MaxHealth = 1 } local MissileAnimation = { Speed = 0, Frame = { } } function Missile.update(dt, Object) if (Object.Position.X >= 650) then Object.delete() end Object.setPosition(vector2d(Object.Position.X + (dt * 120), Object.Position.Y)) --- Hacked Collision Detection for i = 1, Projectiles.enemyManager.getCount() do local Enemy = Projectiles.enemyManager.getEnemy(i) if (Projectiles.collisionManager.checkCollision(Object, Enemy)) then if (Enemy.Health <= 1 and Object.DELETE_ME == nil) then Enemy.delete() Object.delete() local Rnd = Projectiles.mTwister:random(1,4) if (Rnd < 4) then local newItem = Projectiles.itemManager.addItem(Projectiles.itemManager.ItemDataBase.Money) newItem.playAnimation("Animation") newItem.setPosition(Enemy.getPosition()) newItem.setScale(vector2d(1.5,1.5)) newItem.setVisible(true) newItem.Value = 10 end love.audio.play( Projectiles.soundManager.loadSound("media/sounds/Damage.wav")) elseif (Enemy.Health > 1 and Object.DELETE_ME == nil) then Enemy.Health = Enemy.Health - 2 Object.delete() love.audio.play( Projectiles.soundManager.loadSound("media/sounds/Damage.wav")) end end end end MissileAnimation.FrameCount = 1 MissileAnimation.Frame[1] = Projectiles.imageManager.loadImage("media/textures/Missile.png") Missile.Animation["Animation"] = MissileAnimation table.insert(Projectiles, Missile) Projectiles["Missile"] = Missile -- PeaShooter Beam local PeaShooterBeam = { Animation = { }, StartHealth = 1, MaxHealth = 1 } local PeaShooterBeamAnimation = { Speed = 0, Frame = { } } function PeaShooterBeam.update(dt, Object) if (Object.Position.X <= -20) then Object.delete() end Object.setPosition(vector2d(Object.Position.X - (dt * 120), Object.Position.Y)) end PeaShooterBeamAnimation.FrameCount = 1 PeaShooterBeamAnimation.Frame[1] = Projectiles.imageManager.loadImage("media/textures/Beam.png") PeaShooterBeam.Animation["BeamAnimation"] = PeaShooterBeamAnimation table.insert(Projectiles, PeaShooterBeam) Projectiles["PeaShooterBeam"] = PeaShooterBeam return Projectiles
----------------------------------- -- Area: Western Altepa Desert -- NPC: _3h0 (Altepa Gate) -- !pos -19 12 131 125 ----------------------------------- local ID = require("scripts/zones/Western_Altepa_Desert/IDs") ----------------------------------- function onTrade(player, npc, trade) end function onTrigger(player, npc) if npc:getAnimation() == tpz.anim.CLOSE_DOOR then if player:getZPos() > 137 then npc:openDoor(3.2) else player:messageSpecial(ID.text.THE_DOOR_IS_LOCKED) end end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) end
pcreate = function(name,desc) return { PluginName = name, PluginDescription = desc, Commands = {} } end paddcmd = function(plugin,name,listname,desc,aliases,func) plugin.Commands[name] = { ListName = listname, Description = desc, Aliases = aliases or {}, Function = func } end
local combat = Combat() combat:setParameter(COMBAT_PARAM_TYPE, COMBAT_FIREDAMAGE) combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_FIREAREA) local area = createCombatArea(AREA_CROSS5X5) combat:setArea(area) function onGetFormulaValues(player, level, maglevel) min = -((level / 5) + (maglevel * 8) + 50) max = -((level / 5) + (maglevel * 12) + 75) return min, max end combat:setCallback(CALLBACK_PARAM_LEVELMAGICVALUE, "onGetFormulaValues") function onCastSpell(creature, var) return combat:execute(creature, var) end
--[[------------------------------------------------------------------------- Footsteps and logic. - Overrides default footstepsounds with terrain-sounds ---------------------------------------------------------------------------]] local NetL = {"npc_zombie", "npc_poisonzombie", "npc_vortigaunt", "npc_antlion", "npc_fastzombie"} -- These entites only play sounds serverside and needs to be networked. local BL = {"npc_hunter"} -- Tehse entities should not get their sound replaced local find = string.find local bAlwaysFootstep = false -- This is set to true on cold maps local defaultSnowName = "snow.step" local defaultSnowSnd = { "stormfox/footstep/footstep_snow0.ogg", "stormfox/footstep/footstep_snow1.ogg", "stormfox/footstep/footstep_snow2.ogg", "stormfox/footstep/footstep_snow3.ogg", "stormfox/footstep/footstep_snow4.ogg", "stormfox/footstep/footstep_snow5.ogg", "stormfox/footstep/footstep_snow6.ogg", "stormfox/footstep/footstep_snow7.ogg", "stormfox/footstep/footstep_snow8.ogg", "stormfox/footstep/footstep_snow9.ogg" } if SERVER then util.AddNetworkString("StormFox2.feetfix") end -- We use this to cache the last foot for the players. local lastFoot = {} hook.Add("PlayerFootstep", "StormFox2.lastfootprint", function(ply, pos, foot, sound, volume, filter, ...) lastFoot[ply] = foot end) -- Local functions local noSpam = {} local cache = {} -- Returns the foot from sounddata local function GetFootstep(tab) local ent = tab.Entity if not ent or not IsValid(ent) then return end if not ent:IsPlayer() and not ent:IsNPC() and not ent:IsNextBot() then return end if (noSpam[ent] or 0) > CurTime() then return end -- Check to see if it is a footstep local OriginalSnd = tab.OriginalSoundName:lower() local foot = -1 if cache[OriginalSnd] then foot = cache[OriginalSnd] elseif string.match(OriginalSnd, "npc_antlionguard.farstep") or string.match(OriginalSnd, "npc_antlionguard.nearstep") then foot = lastFoot[ent] or -1 elseif find(OriginalSnd, "stepleft",1,true) or find(OriginalSnd, "gallopleft",1,true) then foot = 0 cache[OriginalSnd] = 0 elseif find(OriginalSnd, "stepright",1,true) or find(OriginalSnd, "gallopright",1,true) then foot = 1 cache[OriginalSnd] = 1 elseif find(OriginalSnd, ".footstep",1,true) or find(tab.SoundName:lower(),"^player/footsteps",1) then foot = lastFoot[ent] or -1 else -- Invalid return end -- No footstep spam noSpam[ent] = CurTime() + 0.1 return foot end -- TraceHull for the given entity local function EntTraceTexture(ent,pos) -- Returns the texture the entity is "on" local mt = ent:GetMoveType() if mt < 2 or mt > 3 then return end -- Not walking. local filter = ent if ent.GetViewEntity then filter = ent:GetViewEntity() end local t = util.TraceHull( { start = pos + Vector(0,0,30), endpos = pos + Vector(0,0,-60), maxs = ent:OBBMaxs(), mins = ent:OBBMins(), collisiongroup = ent:GetCollisionGroup(), filter = filter } ) if not t.Hit then return end -- flying if t.Entity and IsValid(t.Entity) and t.HitNonWorld and t.HitTexture == "**studio**" then return end return t.HitTexture end -- Returns true if the entity is on replaced texture. local function IsOnReplacedTex(ent,snd,pos) local sTexture = EntTraceTexture(ent,pos) if not sTexture then return false,"nil" end local mat = Material(sTexture) if not mat then return false, sTexture end if mat:IsError() and (ent:IsNPC() or string.find(snd,"grass") or string.find(snd,"dirt")) then -- Used by maps return true, sTexture end if StormFox2.Terrain.HasMaterialChanged(mat) then return true, sTexture end return false,sTexture end -- Footstep overwrite and logic hook.Add("EntityEmitSound", "StormFox2.footstep.detecter", function(data) if not StormFox2.Terrain then return end local cT = StormFox2.Terrain.GetCurrent() if not cT then return end -- Only enable if we edit or need footsteps. if not (bAlwaysFootstep or (cT and cT.footstepLisen)) then return end -- Check if the server has disabled the footprint logic on their side. if SERVER and not game.SinglePlayer() and not StormFox2.Setting.GetCache("footprint_enablelogic",true) then return end -- Check if it is a footstep sound of some sort. local foot = GetFootstep(data) -- Returns [-1 = invalid, 0 = left, 1 = right] if not foot then return end -- Checks to see if the texturem the entity stands on, have been replaced. local bReplace, sTex = IsOnReplacedTex(data.Entity,data.SoundName:lower(),data.Pos or data.Entity:GetPos()) -- Overwrite the sound if needed. local changed if bReplace and cT.footprintSnds then if cT.footprintSnds[2] then data.OriginalSoundName = cT.footprintSnds[2] .. (foot == 0 and "left" or "right") end if not cT.footprintSnds[1] then data.SoundName = "ambient/_period.wav" else data.SoundName = table.Random(cT.footprintSnds[1]) data.OriginalSoundName = data.SoundName end changed = true end -- Call footstep hook hook.Run("StormFox2.terrain.footstep", data.Entity, foot, data.SoundName, sTex, bReplace ) -- Singleplayer and server-sounds fix if SERVER and (game.SinglePlayer() or table.HasValue(NetL, data.Entity:GetClass())) then net.Start("StormFox2.feetfix",true) net.WriteEntity(data.Entity) net.WriteInt(foot or 1,2) net.WriteString(data.SoundName) net.WriteString(sTex) net.WriteBool(bReplace) net.Broadcast() end -- Call terrain function if cT.footstepFunc then cT.footstepFunc(data.Entity, foot, data.SoundName, sTex, bReplace) end return changed end) -- Singleplayer and entity fix if CLIENT then net.Receive("StormFox2.feetfix",function() local cT = StormFox2.Terrain.GetCurrent() if not cT then return end local ent = net.ReadEntity() if not IsValid(ent) then return end local foot = net.ReadInt(2) local sndName = net.ReadString() local sTex = net.ReadString() local bReplace = net.ReadBool() if cT.footstepFunc then cT.footstepFunc(ent, foot, sndName, sTex, bReplace) end hook.Run("StormFox2.terrain.footstep", ent, foot, sndName, sTex, bReplace) end) end --[[------------------------------------------------------------------------- Footprint render ---------------------------------------------------------------------------]] if CLIENT then local sin,cos,rad,clamp,ceil,min = math.sin,math.cos,math.rad,math.Clamp,math.ceil,math.min local prints = {} local footstep_maxlife = 30 local function ET(pos,pos2,mask,filter) local t = util.TraceLine( { start = pos, endpos = pos + pos2, mask = mask, filter = filter } ) if not t then -- tracer failed, this should not happen. Create a fake result. local t = {} t.HitPos = pos + pos2 return t end t.HitPos = t.HitPos or (pos + pos2) return t end local function AddPrint(ent,foot) -- Foot calc local velspeed = ent:GetVelocity():Length() local y = rad(ent:GetAngles().y) local fy = y + rad((foot * 2 - 1) * -90) local l = 5 * ent:GetModelScale() local ex = Vector(cos(fy) * l + cos(y) * l,sin(fy) * l + sin(y) * l,0) local pos = ent:GetPos() + ex -- Find impact local tr = ET(pos + Vector(0,0,20),Vector(0,0,-40),MASK_SOLID_BRUSHONLY,ent) if not tr.Hit then return end -- In space? -- If no bone_angle then angle math local normal = -tr.HitNormal -- CalcAng local yawoff if ent:IsPlayer() then yawoff = normal:Angle().y - ent:EyeAngles().y + 180 else yawoff = normal:Angle().y - ent:GetAngles().y + 180 end table.insert(prints,{tr.HitPos, normal,foot,ent:GetModelScale() or 1,CurTime() + footstep_maxlife,clamp(velspeed / 300,1,2),yawoff}) -- pos, normal,foot,scale, life, lengh, yawoff end -- Footprint logic local BL = {"npc_hunter","monster_bigmomma","npc_vortigaunt","npc_dog","npc_fastzombie","npc_stalker"} -- Blacklist footprints local function CanPrint(ent) local c = ent:GetClass() for i,v in ipairs(BL) do if find(c, v,1,true) then return false end end if find(ent:GetModel(),"_torso",1,true) then return false end return true end hook.Add("StormFox2.terrain.footstep", "StormFox2.terrain.makefootprint", function(ent, foot, sSnd, sTexture, bReplace ) if foot < 0 then return end -- Invalid foot if not bReplace and bAlwaysFootstep then -- This is a cold map, check for snow if not find(sTexture:lower(),"snow",1,true) then return end elseif bReplace then -- This is terrain local cT = StormFox2.Terrain.GetCurrent() if not cT then return end if not cT.footprints then return end else -- Invalid return end if not CanPrint(ent) then return end if not StormFox2.Setting.GetCache("footprint_enabled",true) then return end if StormFox2.Setting.GetCache("footprint_playeronly",false) and not ent:IsPlayer() then return end local n_max = StormFox2.Setting.GetCache("footprint_max",200) if #prints > n_max then table.remove(prints, 1) end AddPrint(ent,foot) end) -- Footprint render local mat = {Material("stormfox2/effects/foot_hq.png"),Material("stormfox2/effects/foot_hql.png"),Material("stormfox2/effects/foot_m.png"),Material("stormfox2/effects/foot_s.png")} local function getMat(q,foot) if q == 1 then if foot == 0 then return mat[2] else return mat[1] end end return mat[q + 1] end local DrawQuadEasy = render.DrawQuadEasy local bC = Color(0,0,0,255) hook.Add("PreDrawOpaqueRenderables","StormFox2.Terrain.Footprints",function() if not StormFox2.Setting.GetCache("footprint_enabled",true) then return end if #prints < 1 then return end local lp = StormFox2.util.RenderPos() local del = {} local footstep_dis = StormFox2.Setting.GetCache("footprint_distance",2000,"The renderdistance for footprints") ^ 2 for k,v in pairs(prints) do local pos,normal,foot,scale,life,lengh,yawoff = v[1],v[2],v[3],v[4],v[5],v[6],v[7] local blend = life - CurTime() if blend <= 0 then table.insert(del,k) else local q = min(ceil(lp:DistToSqr(pos) / footstep_dis),4) if q >= 4 then continue end render.SetMaterial(getMat(q,foot)) if foot == 0 and q > 1 then DrawQuadEasy( pos + Vector(0,0,q / 3 + 1), normal, 6 * scale, 10 * scale * lengh, bC, yawoff ) else DrawQuadEasy( pos + Vector(0,0,q / 3), normal, -6 * scale, 10 * scale * lengh, bC, yawoff ) end end end for i = #del,1,-1 do table.remove(prints,del[i]) end end) end -- If the map is cold or has snow, always check for footsteps. bAlwaysFootstep = StormFox2.Map.IsCold() or StormFox2.Map.HasSnow() -- This is a cold map. if CLIENT then StormFox2.Setting.AddCL("footprint_enabled",true) -- Add footprint setting StormFox2.Setting.AddCL("footprint_max",200) -- Add footprint setting StormFox2.Setting.AddCL("footprint_distance",2000) -- Add footprint setting StormFox2.Setting.AddCL("footprint_playeronly",false) -- Add footprint setting end StormFox2.Setting.AddSV("footprint_enablelogic",true)
local mongo = require "api-umbrella.utils.mongo" local nillify_json_nulls = require "api-umbrella.utils.nillify_json_nulls" local _M = {} function _M.fetch(last_fetched_version) local raw_result, err = mongo.first("config_versions", { sort = "-version", query = { version = { ["$gt"] = { ["$date"] = last_fetched_version, }, }, }, }) if err then return nil, err else local result = {} if raw_result then if raw_result["config"] then nillify_json_nulls(raw_result["config"]) if raw_result["config"]["apis"] then result["apis"] = raw_result["config"]["apis"] end if raw_result["config"]["website_backends"] then result["website_backends"] = raw_result["config"]["website_backends"] end end if raw_result["version"] then result["version"] = raw_result["version"]["$date"] end end return result end end return _M
object_intangible_vehicle_basilisk_war_droid = object_intangible_vehicle_shared_basilisk_war_droid:new { } ObjectTemplates:addTemplate(object_intangible_vehicle_basilisk_war_droid, "object/intangible/vehicle/basilisk_war_droid.iff")
-- This file is subject to copyright - contact [email protected] for more information. -- INSTALL: CINEMA surface.CreateFont("ScoreboardTitle", { font = "Righteous", size = 52, weight = 400 }) surface.CreateFont("ScoreboardTitleSmall", { font = "Righteous", size = 36, weight = 400 }) surface.CreateFont("ScoreboardServerName", { font = "Lato-Light", size = 22, weight = 200 }) surface.CreateFont("ScoreboardName", { font = "Lato-Light", size = 22, weight = 800 }) surface.CreateFont("ScoreboardLocation", { font = "Lato", size = 16, weight = 200 }) surface.CreateFont("ScoreboardPing", { font = "Lato", size = 18, weight = 200 }) afkClockMaterial = Material("icon16/time.png") showAFKs = false local PLAYERLIST = {} PLAYERLIST.TitleHeight = BrandTitleBarHeight PLAYERLIST.ServerHeight = 32 PLAYERLIST.PlyHeight = 48 concommand.Add("mute", function(ply, cmd, args, argss) local v = Ply(argss) if v then v.ClickMuted = not v.ClickMuted print(v.ClickMuted and "Muted" or "Unmuted", v) UpdateMutes() end end) function UpdateMutes() for k, v in pairs(player.GetAll()) do if v ~= LocalPlayer() then v:SetMuted((v.ClickMuted or false) or (v:IsAFK() and MuteVoiceConVar:GetInt() >= 2)) end end end timer.Create("updatemutes", 1, 0, UpdateMutes) function PLAYERLIST:Init() if (IsValid(LASTSCOREBOARD)) then LASTSCOREBOARD:Remove() end LASTSCOREBOARD = self self.Title = Label("SWAMP CINEMA", self) self.Title:SetFont("ScoreboardTitle") self.Title:SetColor(Color(255, 255, 255)) self.ServerName = vgui.Create("ScoreboardServerName", self) self.PlayerList = vgui.Create("TheaterList", self) self.PlayerList.VBar.btnGrip.OnMousePressed = function(pnl, code) if (code == MOUSE_RIGHT) then local menu = DermaMenu() local lettertab = {} --lettertab["!"] = false for i = 0, 127 do lettertab[string.char(i)] = false end --lettertab["Bottom"] = false for ply, listitem in pairs(self.Players) do local start = tostring(string.upper(string.sub(ply:Nick(), 1, 1))) if (string.byte(start) < 65) then start = "?" end if (string.byte(start) > 90) then start = string.char(126) end if (lettertab[start] == nil or lettertab[start] == false or ply:Nick() < (lettertab[start].Player and IsValid(lettertab[start].Player) and lettertab[start].Player:Nick() or "")) then lettertab[start] = listitem end end for letter, first in SortedPairs(lettertab) do if (first ~= false or (string.byte(letter) >= 65 and string.byte(letter) <= 90)) then if (letter == "?") then letter = "Top" end if (letter == "~") then letter = "Bottom" end local opt = menu:AddOption("Jump To: " .. letter, function() if (first ~= false) then self.PlayerList:ScrollToChild(first) end end) if (first == false) then opt:SetEnabled(false) end end end menu:Open() return end self.PlayerList.VBar:Grip(1) end self.Players = {} self.NextUpdate = 0.0 end function PLAYERLIST:AddPlayer(ply) local panel = vgui.Create("ScoreboardPlayer") panel:SetParent(self) panel:SetPlayer(ply) panel:SetVisible(true) self.Players[ply] = panel self.PlayerList:AddItem(panel) end function PLAYERLIST:RemovePlayer(ply) if ValidPanel(self.Players[ply]) then self.PlayerList:RemoveItem(self.Players[ply]) self.Players[ply]:Remove() self.Players[ply] = nil end end function PLAYERLIST:Paint(w, h) surface.SetDrawColor(BrandColorGrayDarker) surface.DrawRect(0, 0, self:GetWide(), self:GetTall()) local xp, _ = self:GetPos() BrandBackgroundPattern(0, 0, self:GetWide(), self.Title:GetTall(), xp) BrandDropDownGradient(0, self.Title:GetTall(), self:GetWide()) end function PLAYERLIST:Think() if RealTime() > self.NextUpdate then for ply in pairs(self.Players) do if not IsValid(ply) then self:RemovePlayer(ply) end end for _, ply in pairs(player.GetHumans()) do if self.Players[ply] == nil then self:AddPlayer(ply) end end self.ServerName:Update() self:InvalidateLayout(true) self.NextUpdate = RealTime() + 1.0 end end function PLAYERLIST:PerformLayout() if RealTime() < self.NextUpdate then return end table.sort(self.PlayerList.Items, function(a, b) if not a or not a.Player or not IsValid(a.Player) then return false end if not b or not b.Player or not IsValid(b.Player) then return true end return string.lower(a.Player:Nick()) < string.lower(b.Player:Nick()) end) local curY = PLAYERLIST.TitleHeight + PLAYERLIST.ServerHeight for _, panel in pairs(self.PlayerList.Items) do panel:InvalidateLayout(true) panel:UpdatePlayer() panel:SetWide(self:GetWide()) curY = curY + self.PlyHeight + 2 end self.Title:SizeToContents() self.Title:SetTall(PLAYERLIST.TitleHeight) self.Title:CenterHorizontal() self.ServerName:SizeToContents() self.ServerName:AlignTop(PLAYERLIST.TitleHeight) self.ServerName:SetWide(self:GetWide()) self.ServerName:SetTall(PLAYERLIST.ServerHeight) self.ServerName:CenterHorizontal() self.PlayerList:Dock(FILL) self.PlayerList:DockMargin(0, self.TitleHeight + self.ServerHeight, 0, 0) self.PlayerList:SizeToContents() self:SetTall(math.min(curY, ScrH() * 0.8)) end vgui.Register("ScoreboardPlayerList", PLAYERLIST) local PLAYER = {} PLAYER.Padding = SS_COMMONMARGIN function PLAYER:Init() self:SetTall(PLAYERLIST.PlyHeight) self.Name = Label("Unknown", self) self.Name:SetFont("ScoreboardName") self.Name:SetColor(Color(255, 255, 255, 255)) self.AvatarButton = vgui.Create("DButton", self) self.AvatarButton:SetSize(32, 32) self.Avatar = vgui.Create("AvatarImage", self) self.Avatar:SetSize(32, 32) self.Avatar:SetZPos(1) self.Avatar:SetVisible(false) self.Avatar:SetMouseInputEnabled(false) self.Location = Label("Unknown", self) self.Location:SetFont("ScoreboardLocation") self.Location:SetColor(Color(255, 255, 255, 80)) self.Location:SetPos(0, 8) self.FriendIcon = vgui("DImage", self, function(p) p:SetSize(16, 16) p:SetPos(30, 27) p:SetZPos(2) p:SetImage("chev/icon/friend.png") end) --holder for all these little buttons so we can dock them away from the edge vgui("DPanel", self, function(p) p.Paint = noop p:SetWide(256) p:SetTall(24) p:Dock(RIGHT) local dockv = (p:GetParent():GetTall() - 24) / 2 p:DockMargin(0, dockv, SS_COMMONMARGIN, dockv) --p.PerformLayout = function(pnl,w,h) --p:SizeToChildren(true,false) --end self.Mute = vgui("DImageButton", function(p) p:SetSize(22, 22) p:DockMargin(1, 1, 1, 1) p:Dock(RIGHT) p:SetStretchToFit(true) p:SetImage("icon32/unmuted.png") p:SetToolTip("Toggle Voice Mute") end) self.ChatMute = vgui("DImageButton", function(p) p:SetSize(22, 22) p:DockMargin(1, 1, 1, 1) p:Dock(RIGHT) p:SetStretchToFit(true) p:SetImage("theater/chatunmuted.png") p:SetToolTip("Toggle Chat Mute") end) self.Ping = vgui("ScoreboardPlayerPing", function(p) p:Dock(RIGHT) p:DockMargin(2, 0, 2, 0) p:SetSize(28, 16) end) self.Country = vgui("DImageButton", function(p) p:SetSize(16, 12) p:DockMargin(2, 6, 2, 7) p:Dock(RIGHT) p:SetImage("countries/us.png") end) if (showAFKs or LocalPlayer():IsStaff()) then self.AFK = vgui("DImage", function(p) p:SetSize(16, 16) p:DockMargin(2, 4, 2, 4) p:Dock(RIGHT) p:SetImage("icon16/time.png") p:SetTooltip("AFK") p:CenterVertical() end) end end) end function PLAYER:UpdatePlayer() if not IsValid(self.Player) then local parent = self:GetParent() if ValidPanel(parent) and parent.RemovePlayer then parent:RemovePlayer(self.Player) end return end if self.Player.ClickMuted then self.Mute:SetImage("icon32/muted.png") else self.Mute:SetImage("icon32/unmuted.png") end if self.Player.IsChatMuted then self.ChatMute:SetImage("theater/chatmuted.png") else self.ChatMute:SetImage("theater/chatunmuted.png") end self.Mute.DoClick = function() self.Player.ClickMuted = not (self.Player.ClickMuted or false) net.Start("SetMuted") net.WriteEntity(self.Player) net.WriteBool(self.Player.ClickMuted) net.SendToServer() if self.Player.ClickMuted then self.Mute:SetImage("icon32/muted.png") else self.Mute:SetImage("icon32/unmuted.png") end UpdateMutes() end self.ChatMute.DoClick = function() self.Player.IsChatMuted = not self.Player.IsChatMuted print("muted" .. self.Player:Nick() .. "'s chat") if self.Player.IsChatMuted then self.ChatMute:SetImage("theater/chatmuted.png") else self.ChatMute:SetImage("theater/chatunmuted.png") end end local code = self.Player:GetNetworkedString("cntry") if code == "" then if self.Country ~= nil and self.Country.Remove ~= nil then self.Country:Remove() end else if self.Country ~= nil and self.Country.SetImage ~= nil then self.Country:SetImage("countries/" .. string.lower(code) .. ".png") self.Country:SetToolTip("Click to learn about: " .. string.upper(code)) self.Country.isocode = code self.Country.DoClick = function(pnl) ShowMotd("https://en.wikipedia.org/wiki/ISO_3166-1:" .. string.upper(pnl.isocode)) end end end self.Name:SetText(self.Player.TrueName and self.Player:TrueName() or self.Player:Name()) self.Location:SetText(string.upper(self.Player:GetLocationName() or "Unknown")) self.Ping:Update() end function PLAYER:SetPlayer(ply) self.Player = ply self.AvatarButton.DoClick = function() local menu = DermaMenu() local prof = menu:AddOption("View Profile", function() self.Player:ShowProfile() end) prof:SetIcon("icon16/user.png") menu:AddOption("Give Points", function() local gp = vgui.Create('DPointShopGivePoints') gp.playerselect:ChooseOption(self.Player:Nick(), self.Player:UniqueID()) gp.selected_uid = self.Player:UniqueID() gp:Update() end):SetIcon("icon16/coins.png") menu:AddOption("Request Teleport To", function() RunConsoleCommand("say_team", "/tp " .. self.Player:Nick()) end):SetIcon("icon16/world.png") if (LocalPlayer():IsStaff()) then menu:AddOption("Copy SteamID", function() SetClipboardText(self.Player:SteamID()) end):SetIcon("icon16/user_red.png") menu:AddOption("Copy SteamID64", function() SetClipboardText(self.Player:SteamID64()) end):SetIcon("icon16/user_red.png") end menu:Open() end self.AvatarButton.DoRightClick = self.AvatarButton.DoClick self.Avatar:SetPlayer(ply, 64) self.Avatar:SetVisible(true) if ply:GetFriendStatus() == "friend" then self.FriendIcon:Show() else self.FriendIcon:Hide() end self.Ping:SetPlayer(ply) self:UpdatePlayer() end function PLAYER:PerformLayout() self.Name:SizeToContents() self.Name:AlignTop(self.Padding - 4) --if self.Player:GetNWBool("afk") then --self.Name:AlignLeft( self.Avatar:GetWide() + 16 + 16 ) --else self.Name:AlignLeft(self.Avatar:GetWide() + 16) --end self.Location:SizeToContents() self.Location:AlignTop(self.Name:GetTall() + 5) self.Location:AlignLeft(self.Avatar:GetWide() + 16) self.AvatarButton:AlignTop(self.Padding) self.AvatarButton:AlignLeft(self.Padding) self.AvatarButton:CenterVertical() self.Avatar:SizeToContents() self.Avatar:AlignTop(self.Padding) self.Avatar:AlignLeft(self.Padding) self.Avatar:CenterVertical() end function PLAYER:Paint(w, h) surface.SetDrawColor(BrandColorGrayDark) surface.DrawRect(0, 0, self:GetSize()) surface.SetDrawColor(255, 255, 255, 255) local xp = 364 if (IsValid(self.Player) and IsValid(self.AFK)) then self.AFK:SetVisible(self.Player:GetNWBool("afk")) -- else -- self:SetVisible(false) end if self.Player:IsStaff() then --local xp = ({self.Name:GetPos()})[1] + self.Name:GetWide() + 4 local str = self.Player:GetRankName() surface.SetDrawColor(255, 255, 255, 255) surface.SetFont("DermaDefault") xp = xp - ({surface.GetTextSize(str)})[1] surface.DrawRect(xp, 17, ({surface.GetTextSize(str)})[1] + 4, 13) draw.SimpleText(str, "DermaDefault", xp + 2, 17, Color(0, 0, 0, 255), TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP) end end vgui.Register("ScoreboardPlayer", PLAYER) local PLAYERPING = {} PLAYERPING.Padding = 0 function PLAYERPING:Init() self.Heights = {3, 6, 9, 12} self.PingAmounts = {300, 225, 150, 75} end function PLAYERPING:Update() local ping = self.Player:Ping() self.PingVal = ping end function PLAYERPING:SetPlayer(ply) self.Player = ply self:Update() end function PLAYERPING:Paint(w, h) if (not self:IsHovered()) then local maxh = self.Heights[#self.Heights] local bar = 5 local total = #self.Heights * bar local x = w / 2 - (total / 2) for i, height in pairs(self.Heights) do if self.PingVal < self.PingAmounts[i] then surface.SetDrawColor(255, 255, 255, 255) else surface.SetDrawColor(255, 255, 255, 10) end surface.DrawRect(x, (h / 2) - (maxh / 2) + (maxh - height), bar - 2, height) x = x + bar end -- Lit/Main x = 0 surface.SetDrawColor(255, 255, 255, 255) else surface.SetTextColor(255, 255, 255, 10) surface.SetFont("ScoreboardPing") local zeros = "000" if self.PingVal >= 1 then zeros = "00" end if self.PingVal >= 10 then zeros = "0" end if self.PingVal >= 100 then zeros = "" end local tw, th = surface.GetTextSize(zeros) surface.SetTextPos(0, h / 2 - th / 2) surface.DrawText(zeros) surface.SetTextColor(255, 255, 255, 255) surface.SetTextPos(tw, h / 2 - th / 2) surface.DrawText(self.PingVal) end end vgui.Register("ScoreboardPlayerPing", PLAYERPING) local SERVERNAME = {} SERVERNAME.Padding = 8 function SERVERNAME:Init() self.Name = Label("Unknown", self) self.Name:SetFont("ScoreboardServerName") self.Name:SetColor(Color(255, 255, 255)) self.MapName = Label("Unknown", self) self.MapName:SetFont("ScoreboardServerName") self.MapName:SetColor(Color(255, 255, 255)) end function SERVERNAME:Update() self.Name:SetText(game.GetMap()) local players = SV_PLYCOUNT or table.Count(player.GetHumans()) local ttext = tostring(players) .. " Players Online" if players == 1 then ttext = "One Player Online" end local x, y = self:LocalCursorPos() local xs, ys = self:GetSize() showAFKs = false if x > 0 and y > 0 and x < xs and y < ys then showAFKs = true local count = 0 local count2 = 0 for k, v in pairs(player.GetHumans()) do if v:GetNWBool("afk") then count = count + 1 if not (v:InTheater()) then count2 = count2 + 1 end end end ttext = tostring(count) .. " / " .. tostring(players) .. " AFK (" .. tostring(count2) .. " AFK + !InTheater) " end self.MapName:SetText(ttext) self:PerformLayout() end function SERVERNAME:PerformLayout() self.Name:SizeToContents() self.Name:AlignLeft(self.Padding) self.Name:AlignTop(3) self.MapName:SizeToContents() self.MapName:AlignRight(self.Padding) self.MapName:AlignTop(3) end vgui.Register("ScoreboardServerName", SERVERNAME)
-- ============================================================= -- Copyright Roaming Gamer, LLC. 2008-2018 (All Rights Reserved) -- ============================================================= local files = ssk.files local header = [[ -- ============================================================= -- !!! THIS FILE IS GENERATED DO NOT EDIT !!! -- ============================================================= -- local mgr = require mgr_path base_params ]] local base_params = [[ -- ============================================================= -- ======= BASE PARAMS -- ============================================================= local base_params = {} ]] local template = [[-- ============================ -- ======= prefix1bname1 Button -- ============================ local params params_clone params.w = bwidth params.h = bheight params.unselImgSrc = "img_pathbimage_unsel" params.selImgSrc = "img_pathbimage_sel" params.toggledImgSrc = "img_pathbimage_toggled" params.lockedImgSrc = "img_pathbimage_locked" mgr:addButtonPreset( "prefix2bname2", params )]] -- ============================================================= -- Module Begins -- ============================================================= local utils = {} function utils.generateButtonPresets( params , debugEn ) params = params or {} local base = params.base local mgr = params.mgr or "ssk2.core.interfaces.buttons" local images = params.images or "images/buttons/" local prefix = params.prefix local saveFile = params.saveFile or "scripts/presets_gen" -- local path = ssk.files.resource.getPath(images) local allFiles = ssk.files.util.findAllFiles(path) -- local template = template local header = header -- header = string.gsub( header, "mgr_path", "'" .. mgr .. "'" ) template = string.gsub( template, "img_path", images ) if( base ) then local base_params = base_params for k,v in pairs( base ) do -- string if( type(v) == "string" ) then base_params = base_params .. "base_params." .. k .. " = " .. "'" .. v .. "'" .. "\n" -- boolean elseif( type(v) == "boolean" ) then --base_params = base_params .. k .. " = " .. (v and "true" or "false" ) base_params = base_params .. "base_params." .. k .. " = " .. tostring(v) .. "\n" -- number elseif( type(v) == "number" ) then base_params = base_params .. "base_params." .. k .. " = " .. tostring(v) .. "\n" -- table elseif( type(v) == "table" ) then base_params = base_params .. "base_params." .. k .. " = " .. "{ " for i = 1, #v do base_params = base_params .. tonumber(v[i]) if( i < #v ) then base_params = base_params .. ", " end end base_params = base_params .. " }\n" end end header = string.gsub( header, "base_params", "\n" .. base_params ) template = string.gsub( template, "params_clone", "= table.shallowCopy( base_params )" ) else header = string.gsub( header, "base_params", "" ) template = string.gsub( template, "params_clone", "= {}" ) end -- for k,v in pairs(allFiles) do if( not string.match( v, "%.png" ) and not string.match( v, "%.jpg" ) ) then allFiles[k] = nil end end -- if( debugEn ) then table.dump(allFiles) end -- local processed = {} -- Process filenames for k,v in pairs( allFiles ) do local rec = {} processed[#processed+1] = rec -- local filename = v local parts = string.split( filename, "%." ) local ext = parts[#parts] local prefix = parts[1] local parts = string.split( prefix, "_" ) rec.filename = filename rec.ext = ext rec.type = ( #parts == 1 ) and "basic" or parts[2] rec.name = parts[1] end -- --table.print_r( processed ) local function findNameByType( name, btype ) for i = 1,#processed do local rec = processed[i] if( rec.name == name and rec.type == btype ) then return rec end end return nil end local function addToggled( out, rec ) if( findNameByType( rec.name, "toggled" ) ) then out = string.gsub( out, "bimage_toggled", rec.name .. "_toggled." .. rec.ext ) end -- if( string.match( out, "bimage_toggled") ) then local tmp = string.split(out,"\n") out = "" for i = 1, #tmp do if( string.match( tmp[i], "bimage_toggled") ) then else out = out .. tmp[i] out = (i<#tmp) and (out .. "\n") or out end end end -- return out end local function addLocked( out, rec ) if( findNameByType( rec.name, "locked" ) ) then out = string.gsub( out, "bimage_locked", rec.name .. "_locked." .. rec.ext ) end -- if( string.match( out, "bimage_locked") ) then local tmp = string.split(out,"\n") out = "" for i = 1, #tmp do if( string.match( tmp[i], "bimage_locked") ) then else out = out .. tmp[i] out = (i<#tmp) and (out .. "\n") or out end end end -- return out end -- -- Generate Presets File -- local generated = {} -- local outPath = ssk.files.resource.getPath( saveFile ) ssk.files.util.writeFile( header, outPath ) -- Basic Buttons for i = 1, #processed do local rec = processed[i] if( rec.type == "basic" and not generated[rec.name] ) then generated[rec.name] = true -- local bwidth, bheight = ssk.misc.getImageSize ( images .. rec.filename ) local out = template out = string.gsub( out, "bname1", string.upper(rec.name) ) out = string.gsub( out, "bname2", rec.name ) if( prefix ) then out = string.gsub( out, "prefix1", string.upper( prefix .. "_" ) .. "_" ) out = string.gsub( out, "prefix2", prefix .. "_" ) else out = string.gsub( out, "prefix1", "" ) out = string.gsub( out, "prefix2", "" ) end out = string.gsub( out, "bimage_unsel", rec.filename ) out = string.gsub( out, "bimage_sel", rec.filename ) out = string.gsub( out, "bwidth", bwidth ) out = string.gsub( out, "bheight", bheight ) out = addToggled( out, rec ) -- just to clean out = addLocked( out, rec ) -- just to clean --print(out) -- ssk.files.util.appendFile( out, outPath ) ssk.files.util.appendFile( "\n", outPath ) ssk.files.util.appendFile( "\n", outPath ) end end -- sel/unsel buttons for i = 1, #processed do local rec = processed[i] local other if( rec.type == "sel" ) then other = findNameByType( rec.name, "unsel" ) end if( other and not generated[rec.name] ) then generated[rec.name] = true -- local bwidth, bheight = ssk.misc.getImageSize ( images .. rec.filename ) local out = template out = string.gsub( out, "bname1", string.upper(rec.name) ) out = string.gsub( out, "bname2", rec.name ) if( prefix ) then out = string.gsub( out, "prefix1", string.upper( prefix .. "_" ) .. "_" ) out = string.gsub( out, "prefix2", prefix .. "_" ) else out = string.gsub( out, "prefix1", "" ) out = string.gsub( out, "prefix2", "" ) end out = string.gsub( out, "bimage_unsel", rec.name .. "_unsel." .. rec.ext ) out = string.gsub( out, "bimage_sel", rec.name .. "_sel." .. rec.ext ) out = string.gsub( out, "bwidth", bwidth ) out = string.gsub( out, "bheight", bheight ) out = addToggled( out, rec ) out = addLocked( out, rec ) --print(out) -- ssk.files.util.appendFile( out, outPath ) ssk.files.util.appendFile( "\n", outPath ) ssk.files.util.appendFile( "\n", outPath ) end end -- on/off buttons for i = 1, #processed do local rec = processed[i] local other if( rec.type == "on" ) then other = findNameByType( rec.name, "off" ) end if( other and not generated[rec.name] ) then generated[rec.name] = true -- local bwidth, bheight = ssk.misc.getImageSize ( images .. rec.filename ) local out = template out = string.gsub( out, "bname1", string.upper(rec.name) ) out = string.gsub( out, "bname2", rec.name ) if( prefix ) then out = string.gsub( out, "prefix1", string.upper( prefix .. "_" ) .. "_" ) out = string.gsub( out, "prefix2", prefix .. "_" ) else out = string.gsub( out, "prefix1", "" ) out = string.gsub( out, "prefix2", "" ) end out = string.gsub( out, "bimage_unsel", rec.name .. "_off." .. rec.ext ) out = string.gsub( out, "bimage_sel", rec.name .. "_on." .. rec.ext ) out = string.gsub( out, "bwidth", bwidth ) out = string.gsub( out, "bheight", bheight ) out = addToggled( out, rec ) out = addLocked( out, rec ) --print(out) -- ssk.files.util.appendFile( out, outPath ) ssk.files.util.appendFile( "\n", outPath ) ssk.files.util.appendFile( "\n", outPath ) end end end -- == -- (Re-) Position Buttons -- If useTransitions is 'true', then move buttons with transition.* lib. -- == utils.positionButtons = function( buttons, tween, params ) if( not buttons or #buttons == 0 ) then return end -- local buttonW = buttons[1].contentWidth if( not tween ) then local totalBW = #buttons * buttonW tween = math.floor( (fullw - totalBW )/(#buttons+1) ) end local curX = centerX - ((#buttons * buttonW) + ((#buttons-1) * tween))/2 + buttonW/2 for i = 1, #buttons do local button = buttons[i] if( params ) then local function onComplete() button:resetStartPosition() end params.time = params.time or 500 params.transition = params.transition or easing.outBack params.x = curX params.onComplete = onComplete transition.to( button, params ) else button.x = curX button:resetStartPosition() end curX = curX + buttonW + tween end end return utils
--[[ Copyright (c) 2016-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. --]] require('torch') local MPI = require('torchmpi.env') local wrap = require('torchmpi.wrap') local cache = require('torchmpi.cache') local PS = require('torchmpi.parameterserver.env') require("torchmpi.parameterserver.update") require("torchmpi.parameterserver.downpourupdate") require("torchmpi.parameterserver.easgdupdate") -- Creates a parameter server from a tensor, allocating space for and copying -- the local portion (shard) of the tensor:data(). -- -- parameterserver_init is a blocking collective operation that must be run on -- all processes in the communicator so they can synchronize and shard properly. -- -- For each such process, a local shard is inited with the -- *corresponding values of of that process*. -- In particular, suppose process_i has a local tensor_i uniformly initialized -- to value 'i'. -- Then, after running PS.init(tensor_i) on each process_i, -- the distributed parameter server will contain -- shard[0] shard[1] ... shard[MPI.size() - 1] -- 0 1 MPI.size() - 1 -- If you want a uniform sharded tensor initialization, you can make all processes -- synchronize to some value first with a broadcast then init the parameterserver. -- -- Details: -- 1. A parameterserver allocates and owns a lcoal shard for holding the parameters as well -- as a local buffer shard for send/receives. -- This local buffer shard is tied to the shape of the tensor, its size is determined -- by sharding the tensor on all the processes participating in the MPI communicator. -- 2. Parameter server initialization is a blocking operation (synchronized with MPI.barriers) -- Therefore all ranks must initialize all parameterservers for matching tensors in the -- same order. The ordering property is important because MPI tags have to match. -- 3. In geenral, you can use a parameterserver inited with a tensor t1 to synchronize -- with a tensor t2: -- - if t1 and t2 have the same number of elements (see below). -- - if t1 and t2 are contiguous tensors PS.init = function(t) assert(t:nElement() >= MPI.size(), 'NYI: corner case where nElement < MPI.size()') local fun = 'torchmpi_parameterserver_init_TH'..torch.type(t):gsub('torch.', '') return wrap.executeTensorFun(fun, t) end PS.send = function(ps, t, rule) local rule = rule or 'none' assert(type(rule) == 'string', 'Usage parameterserver.send(cdata<void*>, *Tensor, string)' .. ' but parameter #2 is: ' .. type(rule)) assert(type(ps) == 'cdata', 'Usage parameterserver.send(cdata<void*>, *Tensor, string)' .. ' but parameter #2 is: ' .. type(ps)) local fun = 'torchmpi_parameterserver_send_TH'..torch.type(t):gsub('torch.', '') return wrap.executePSFun(fun, ps, t, rule or 'none') end PS.receive = function(ps, t) assert(type(ps) == 'cdata', 'Usage parameterserver.send(cdata<void*>, *Tensor)' .. ' but parameter #2 is: ' .. type(ps)) local fun = 'torchmpi_parameterserver_receive_TH'..torch.type(t):gsub('torch.', '') return wrap.executePSFun(fun, ps, t) end PS.free = function(ps) assert(type(ps) == 'cdata', 'Usage parameterserver.send(cdata<void*>, *Tensor)' .. ' but parameter #2 is: ' .. type(ps)) MPI.C.torchmpi_parameterserver_free(ps) end PS.freeAll = function() MPI.C.torchmpi_parameterserver_free_all() end PS.syncHandle = function(sh) return MPI.C.torchmpi_parameterserver_synchronize_handle(sh); end ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- The following is a set of helper functions that operate on lists of tensor -- and save bookkeeping information in torchmpi.cache. -- They make implementation choices which may not work for you but at least -- they allow to build a simple dataparallel, downpour and easgd -- (see examples/mnist/mnist_parameterserver_*). -- -- Be sure to understand the assumptions if you use them. ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Takes a table of tensors, usually coming from net:parameters() -- Can be either weights or gradients local function sanityCheckTensors(tensors) for i, t in ipairs(tensors) do assert(torch.isTensor(t), 'Not a tensor ' .. torch.type(t)) assert(cache.prefetchTensorReferences[t], 'No prefetchTensor for tensor @' .. tostring(t:cdata())) assert(cache.parameterServers[t], 'No parameterserver for tensor @' .. tostring(t:cdata())) end end -- Initialize on parameterserver client/server pair for each tensor in the -- list -- Takes: -- 1. tensors: a table of tensors, usually coming from net:parameters(). -- Can be either weights or gradients -- 2. prefetchAllocator: a prefetch alloc function to control where the prefetch -- tensor should live, if for instance you are short for GPU memory. -- Defaults to a simple tensor:clone function. -- 3. psInitFun: a parameter server init function which informs how to -- intialize the sharded tensor. Defaults to copying the tensor from the -- rank 0. PS.initTensors = function(tensors, prefetchAllocator, psInitFun) local prefetchAllocator = prefetchAllocator or function(t) local cputensor = torch.type(t):find('Cuda') and cutorch.createCudaHostTensor():resize(t:nElement()):copy(t) or t:clone() return cputensor end local psInitFun = function(ps, t) if MPI.rank() == 0 then PS.syncHandle(PS.send(ps, t, 'copy')) end MPI.barrier() end for i, t in ipairs(tensors) do assert(not cache.parameterServers[t]) cache.prefetchTensorReferences[t] = prefetchAllocator(t) cache.parameterServers[t] = PS.init(cache.prefetchTensorReferences[t]) psInitFun(cache.parameterServers[t], cache.prefetchTensorReferences[t]) end sanityCheckTensors(tensors) end -- Takes a table of tensors, usually coming from net:parameters() -- For each tensor t, receives the corresponding shards from -- cache.parameterServers[t] into a local prefetched tensor -- cache.prefetchTensorReferences[t]. -- Returns a table of handles on which you can run PS.syncHandle to make sure -- the prefetch is complete. PS.prefetchTensors = function(tensors) sanityCheckTensors(tensors) local handles = {} for i, t in ipairs(tensors) do table.insert(handles, PS.receive( cache.parameterServers[t], cache.prefetchTensorReferences[t])) end return handles end -- Takes a table of tensors, usually coming from net:parameters() -- Takes a localUpdateRule function(prefetched, t) which applies prefetched -- to t. PS.integrateTensors = function(tensors, localUpdateRule) sanityCheckTensors(tensors) for i, t in ipairs(tensors) do localUpdateRule(cache.prefetchTensorReferences[t], t) end end -- Takes a table of tensors, usually coming from net:parameters() -- Can be either weights or gradients -- Optionally takes a localUpdateRule function(prefetched, t) which -- applies the prefetched to t. -- Returns a table of handles on which you can run PS.syncHandle to make -- sure the send is complete. PS.sendTensors = function(tensors, updates, remoteUpdateRule, localPreprocessFun) local sendAllocator = function(t) local cputensor = torch.type(t):find('Cuda') and cutorch.createCudaHostTensor():resize(t:nElement()):copy(t) or t return cputensor end sanityCheckTensors(tensors) localPreprocessFun = localPreprocessFun or function(t) return t end local sync = false local handles = {} for i, t in ipairs(updates) do cache.sendTensorReferences[t] = cache.sendTensorReferences[t] or sendAllocator(t) if cache.sendTensorReferences[t] ~= t then -- Only taken for cuda tensors that have been copied to pinned cache.sendTensorReferences[t]:copyAsync(t) sync = true end end if sync then cutorch.synchronize() end for i, t in ipairs(updates) do table.insert(handles, PS.send(cache.parameterServers[tensors[i]], localPreprocessFun(cache.sendTensorReferences[t]), remoteUpdateRule)) end return handles end PS.syncHandles = function(handles) for i, h in ipairs(handles) do PS.syncHandle(h) end return {} end return PS
return {'xiv'}
object_tangible_component_armor_armor_segment_enhancement_assault = object_tangible_component_armor_shared_armor_segment_enhancement_assault:new { } ObjectTemplates:addTemplate(object_tangible_component_armor_armor_segment_enhancement_assault, "object/tangible/component/armor/armor_segment_enhancement_assault.iff")
-- Copyright 2022 Erick Israel Vazquez Neri -- -- 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 battery = require "st.capabilities".battery local button = require "st.capabilities".button local switch_level = require "st.capabilities".switchLevel local Uint16 = require "st.zigbee.data_types".Uint16 local PowerConfiguration = require "st.zigbee.zcl.clusters".PowerConfiguration local Basic = require "st.zigbee.zcl.clusters".Basic local Groups = require "st.zigbee.zcl.clusters".Groups local OnOffButton = require "custom".OnOffButton local ReadTuyaSpecific = require "custom".ReadTuyaSpecific local UnkownBasic = require "custom".UnknownBasic local send_cluster_bind_request = require "emitter".send_cluster_bind_request local send_attr_configure_reporting = require "emitter".send_attr_configure_reporting local send_button_capability_setup = require "emitter".send_button_capability_setup local send_zigbee_message = require "emitter".send_zigbee_message -- generates endpoint reference based -- on component id string reference. -- -- @param component_id string local function _component_to_endpoint(_, component_id) if component_id == "battery" then return 0 end local ep = component_id:match("button(%d)") return ep and tonumber(ep) or 1 end -- generates component id reference -- based on endpoint notified by -- _component_to_endpoint. -- -- @param ep number (endpoint) local function _endpoint_to_component(_, ep) if ep == 0 then return "battery" end return tonumber(ep) == 1 and "main" or "button"..ep end -- init lifecycle -- -- handler component vs endpoint -- configuration for consistency -- -- @param device ZigbeeDevice local function init(_, device) device:set_component_to_endpoint_fn(_component_to_endpoint) device:set_endpoint_to_component_fn(_endpoint_to_component) if device:supports_capability_by_id(switch_level.ID) then device:emit_event(switch_level.level(50)) end end -- added lifecycle -- -- handles initual -- state configuration -- -- @param device ZigbeeDevice local function added(_, device) return send_button_capability_setup( device, device:component_count() - 1, -- exclude "battery" component { "pushed", "double", "held" }) end -- doConfigure lifecycle -- -- handles cluster attribute -- configuration of report and -- request binding -- -- @param driver ZigbeeDriver -- @param device ZigbeeDevice local function do_configure(driver, device) local err = "failed to configure device: " local hub_zigbee_eui = driver.environment_info.hub_zigbee_eui local operation_mode = device.preferences.operationMode == "SCENE" and 0x01 or 0x00 local zigbee_group = Uint16(device.preferences.zigbeeGroup) local override_group_on_update = device.preferences.overrideGroupOnUpdate -- [[ -- battery capability setup -- if device supports it -- ]] if device:supports_capability_by_id(battery.ID) then -- bind request assert(send_cluster_bind_request( device, hub_zigbee_eui, PowerConfiguration.ID), err.."BindRequest - PowerConfiguration.BatteryPercentageRemaining") -- configure reporting assert(send_attr_configure_reporting( device, PowerConfiguration.attributes.BatteryPercentageRemaining, -- min report time 5mins, max report time 6 hours, report on minimal change { min_rep=3600, max_rep=21600, min_change=1 }), err.."PowerConfiguration.BatteryPercentageRemaining") -- TODO: IS IT IMPORTANT? -- SUBSCRIBE TO BATTERY VOLTAGE -- assert(send_attr_configure_reporting( -- device, PowerConfiguration.attributes.BatteryVoltage), -- err.."PowerConfiguration.BatteryVoltage") end --[[ -- button capability setup -- if device supports it -- -- The following sequence of Zigbee Messages -- defines the steps to guarantee the compatibility -- at network level. --]] if device:supports_capability_by_id(button.ID) then -- read metadata from Basic assert(send_zigbee_message(device, Basic.attributes.ManufacturerName:read(device))) assert(send_zigbee_message(device, Basic.attributes.ZCLVersion:read(device))) assert(send_zigbee_message(device, Basic.attributes.ApplicationVersion:read(device))) assert(send_zigbee_message(device, Basic.attributes.ModelIdentifier:read(device))) assert(send_zigbee_message(device, Basic.attributes.PowerSource:read(device))) assert(send_zigbee_message(device, UnkownBasic:read(device))) -- read tuya-specific assert(send_zigbee_message(device, ReadTuyaSpecific(device))) assert(send_zigbee_message(device, OnOffButton:read(device))) -- read battery values assert(send_zigbee_message(device, PowerConfiguration.attributes.BatteryPercentageRemaining:read(device))) assert(send_zigbee_message(device, PowerConfiguration.attributes.BatteryVoltage:read(device))) -- device mode definition assert(send_zigbee_message(device, OnOffButton:write(device, operation_mode))) assert(send_zigbee_message(device, OnOffButton:read(device))) -- zigbee group configuration if override_group_on_update then assert(send_zigbee_message(device, Groups.server.commands.RemoveAllGroups(device))) end assert(send_zigbee_message(device, Groups.server.commands.AddGroup(device, zigbee_group, "dimmer mode"))) assert(send_zigbee_message(device, Groups.server.commands.ViewGroup(device))) assert(send_zigbee_message(device, Groups.server.commands.GetGroupMembership(device, { zigbee_group }))) -- TODO: CHECK PURPOSE OF DeviceTemperatureConfiguration CLUSTER -- TODO: CHECK PURPOSE OF Identify.IdentifyTime CLUSTER end end return { init=init, added=added, do_configure=do_configure }
local CassandraFactory = require "kong.dao.cassandra.factory" local spec_helper = require "spec.spec_helpers" local timestamp = require "kong.tools.timestamp" local cassandra = require "cassandra" local constants = require "kong.constants" local DaoError = require "kong.dao.error" local utils = require "kong.tools.utils" local cjson = require "cjson" local uuid = require "uuid" -- Raw session for double-check purposes local session -- Load everything we need from the spec_helper local env = spec_helper.get_env() -- test environment local faker = env.faker local dao_factory = env.dao_factory local configuration = env.configuration configuration.cassandra = configuration.databases_available[configuration.database].properties -- An utility function to apply tests on core collections. local function describe_core_collections(tests_cb) for type, dao in pairs({ api = dao_factory.apis, consumer = dao_factory.consumers, plugin_configuration = dao_factory.plugins_configurations }) do local collection = type == "plugin_configuration" and "plugins_configurations" or type.."s" describe(collection, function() tests_cb(type, collection) end) end end -- An utility function to test if an object is a DaoError. -- Naming is due to luassert extensibility's restrictions local function daoError(state, arguments) local stub_err = DaoError("", "") return getmetatable(stub_err) == getmetatable(arguments[1]) end local say = require("say") say:set("assertion.daoError.positive", "Expected %s\nto be a DaoError") say:set("assertion.daoError.negative", "Expected %s\nto not be a DaoError") assert:register("assertion", "daoError", daoError, "assertion.daoError.positive", "assertion.daoError.negative") -- Let's go describe("Cassandra DAO", function() setup(function() spec_helper.prepare_db() -- Create a parallel session to verify the dao's behaviour session = cassandra.new() session:set_timeout(configuration.cassandra.timeout) local _, err = session:connect(configuration.cassandra.hosts, configuration.cassandra.port) assert.falsy(err) local _, err = session:set_keyspace(configuration.cassandra.keyspace) assert.falsy(err) end) teardown(function() if session then local _, err = session:close() assert.falsy(err) end spec_helper.reset_db() end) describe("Collections schemas", function() describe_core_collections(function(type, collection) it("should have statements for all unique and foreign schema fields", function() for column, schema_field in pairs(dao_factory[collection]._schema) do if schema_field.unique then assert.truthy(dao_factory[collection]._queries.__unique[column]) end if schema_field.foreign then assert.truthy(dao_factory[collection]._queries.__foreign[column]) end end end) end) end) describe("Factory", function() describe(":prepare()", function() it("should prepare all queries in collection's _queries", function() local new_factory = CassandraFactory({ hosts = "127.0.0.1", port = 9042, timeout = 1000, keyspace = configuration.cassandra.keyspace }) local err = new_factory:prepare() assert.falsy(err) -- assert collections have prepared statements for _, collection in ipairs({ "apis", "consumers" }) do for k, v in pairs(new_factory[collection]._queries) do local cache_key if type(v) == "string" then cache_key = v elseif v.query then cache_key = v.query end if cache_key then assert.truthy(new_factory[collection]._statements_cache[cache_key]) end end end end) it("should raise an error if cannot connect to Cassandra", function() local new_factory = CassandraFactory({ hosts = "127.0.0.1", port = 45678, timeout = 1000, keyspace = configuration.cassandra.keyspace }) local err = new_factory:prepare() assert.truthy(err) assert.is_daoError(err) assert.True(err.database) assert.are.same("Cassandra error: connection refused", err.message) end) end) end) -- describe Factory -- -- Core DAO Collections (consumers, apis, plugins_configurations) -- describe("DAO Collections", function() describe(":insert()", function() describe("APIs", function() it("should insert in DB and add generated values", function() local api_t = faker:fake_entity("api") local api, err = dao_factory.apis:insert(api_t) assert.falsy(err) assert.truthy(api.id) assert.truthy(api.created_at) end) it("should not insert an invalid api", function() -- Nil local api, err = dao_factory.apis:insert() assert.falsy(api) assert.truthy(err) assert.True(err.schema) assert.are.same("Cannot insert a nil element", err.message) -- Invalid schema UNIQUE error (already existing API name) local api_rows, err = session:execute("SELECT * FROM apis LIMIT 1;") assert.falsy(err) local api_t = faker:fake_entity("api") api_t.name = api_rows[1].name local api, err = dao_factory.apis:insert(api_t) assert.truthy(err) assert.is_daoError(err) assert.True(err.unique) assert.are.same("name already exists with value "..api_t.name, err.message.name) assert.falsy(api) -- Duplicated name local apis, err = session:execute("SELECT * FROM apis") assert.falsy(err) assert.truthy(#apis > 0) local api_t = faker:fake_entity("api") api_t.name = apis[1].name local api, err = dao_factory.apis:insert(api_t) assert.falsy(api) assert.truthy(err) assert.is_daoError(err) assert.True(err.unique) assert.are.same("name already exists with value "..api_t.name, err.message.name) end) end) describe("Consumers", function() it("should insert an consumer in DB and add generated values", function() local consumer_t = faker:fake_entity("consumer") local consumer, err = dao_factory.consumers:insert(consumer_t) assert.falsy(err) assert.truthy(consumer.id) assert.truthy(consumer.created_at) end) end) describe("Plugin Configurations", function() it("should not insert in DB if invalid", function() -- Without an api_id, it's a schema error local plugin_t = faker:fake_entity("plugin_configuration") local plugin, err = dao_factory.plugins_configurations:insert(plugin_t) assert.falsy(plugin) assert.truthy(err) assert.is_daoError(err) assert.True(err.schema) assert.are.same("api_id is required", err.message.api_id) -- With an invalid api_id, it's an FOREIGN error local plugin_t = faker:fake_entity("plugin_configuration") plugin_t.api_id = uuid() local plugin, err = dao_factory.plugins_configurations:insert(plugin_t) assert.falsy(plugin) assert.truthy(err) assert.is_daoError(err) assert.True(err.foreign) assert.are.same("api_id "..plugin_t.api_id.." does not exist", err.message.api_id) -- With invalid api_id and consumer_id, it's an EXISTS error local plugin_t = faker:fake_entity("plugin_configuration") plugin_t.api_id = uuid() plugin_t.consumer_id = uuid() local plugin, err = dao_factory.plugins_configurations:insert(plugin_t) assert.falsy(plugin) assert.truthy(err) assert.is_daoError(err) assert.True(err.foreign) assert.are.same("api_id "..plugin_t.api_id.." does not exist", err.message.api_id) assert.are.same("consumer_id "..plugin_t.consumer_id.." does not exist", err.message.consumer_id) end) it("should insert a plugin configuration in DB and add generated values", function() local api_t = faker:fake_entity("api") local api, err = dao_factory.apis:insert(api_t) assert.falsy(err) local consumers, err = session:execute("SELECT * FROM consumers") assert.falsy(err) assert.True(#consumers > 0) local plugin_t = faker:fake_entity("plugin_configuration") plugin_t.api_id = api.id plugin_t.consumer_id = consumers[1].id local plugin, err = dao_factory.plugins_configurations:insert(plugin_t) assert.falsy(err) assert.truthy(plugin) assert.truthy(plugin.consumer_id) end) it("should not insert twice a plugin with same api_id, consumer_id and name", function() -- Insert a new API for a fresh start local api, err = dao_factory.apis:insert(faker:fake_entity("api")) assert.falsy(err) assert.truthy(api.id) local consumers, err = session:execute("SELECT * FROM consumers") assert.falsy(err) assert.True(#consumers > 0) local plugin_t = faker:fake_entity("plugin_configuration") plugin_t.api_id = api.id plugin_t.consumer_id = consumers[#consumers].id -- This should work local plugin, err = dao_factory.plugins_configurations:insert(plugin_t) assert.falsy(err) assert.truthy(plugin) -- This should fail local plugin, err = dao_factory.plugins_configurations:insert(plugin_t) assert.falsy(plugin) assert.truthy(err) assert.is_daoError(err) assert.True(err.unique) assert.are.same("Plugin already exists", err.message) end) it("should not insert a plugin if this plugin doesn't exist (not installed)", function() local plugin_t = faker:fake_entity("plugin_configuration") plugin_t.name = "world domination plugin" -- This should fail local plugin, err = dao_factory.plugins_configurations:insert(plugin_t) assert.falsy(plugin) assert.truthy(err) assert.is_daoError(err) assert.are.same("Plugin \"world domination plugin\" not found", err.message.value) end) it("should validate a plugin value schema", function() -- Success -- Insert a new API for a fresh start local api, err = dao_factory.apis:insert(faker:fake_entity("api")) assert.falsy(err) assert.truthy(api.id) local consumers, err = session:execute("SELECT * FROM consumers") assert.falsy(err) assert.True(#consumers > 0) local plugin_t = { api_id = api.id, consumer_id = consumers[#consumers].id, name = "keyauth", value = { key_names = { "x-kong-key" } } } local plugin, err = dao_factory.plugins_configurations:insert(plugin_t) assert.falsy(err) assert.truthy(plugin) local ok, err = dao_factory.plugins_configurations:delete(plugin.id) assert.True(ok) assert.falsy(err) -- Failure plugin_t.name = "ratelimiting" plugin_t.value = { period = "hello" } local plugin, err = dao_factory.plugins_configurations:insert(plugin_t) assert.truthy(err) assert.is_daoError(err) assert.truthy(err.schema) assert.are.same("\"hello\" is not allowed. Allowed values are: \"second\", \"minute\", \"hour\", \"day\", \"month\", \"year\"", err.message["value.period"]) assert.falsy(plugin) end) end) end) -- describe :insert() describe(":update()", function() describe_core_collections(function(type, collection) it("should return nil if no entity was found to update in DB", function() local t = faker:fake_entity(type) t.id = uuid() -- Remove immutable fields for k,v in pairs(dao_factory[collection]._schema) do if v.immutable and not v.required then t[k] = nil end end -- No entity to update local entity, err = dao_factory[collection]:update(t) assert.falsy(entity) assert.falsy(err) end) end) describe("APIs", function() -- Cassandra sets to NULL unset fields specified in an UPDATE query -- https://issues.apache.org/jira/browse/CASSANDRA-7304 it("should update in DB without setting to NULL unset fields", function() local apis, err = session:execute("SELECT * FROM apis") assert.falsy(err) assert.True(#apis > 0) local api_t = apis[1] api_t.name = api_t.name.." updated" -- This should not set those values to NULL in DB api_t.created_at = nil api_t.public_dns = nil api_t.target_url = nil local api, err = dao_factory.apis:update(api_t) assert.falsy(err) assert.truthy(api) local apis, err = session:execute("SELECT * FROM apis WHERE name = '"..api_t.name.."'") assert.falsy(err) assert.are.same(1, #apis) assert.truthy(apis[1].id) assert.truthy(apis[1].created_at) assert.truthy(apis[1].public_dns) assert.truthy(apis[1].target_url) assert.are.same(api_t.name, apis[1].name) end) it("should prevent the update if the UNIQUE check fails", function() local apis, err = session:execute("SELECT * FROM apis") assert.falsy(err) assert.True(#apis > 0) local api_t = apis[1] api_t.name = api_t.name.." unique update attempt" -- Should not work because UNIQUE check fails api_t.public_dns = apis[2].public_dns local api, err = dao_factory.apis:update(api_t) assert.falsy(api) assert.truthy(err) assert.is_daoError(err) assert.True(err.unique) assert.are.same("public_dns already exists with value "..api_t.public_dns, err.message.public_dns) end) end) describe("Consumers", function() it("should update in DB if entity can be found", function() local consumers, err = session:execute("SELECT * FROM consumers") assert.falsy(err) assert.True(#consumers > 0) local consumer_t = consumers[1] -- Should be correctly updated in DB consumer_t.custom_id = consumer_t.custom_id.."updated" local consumer, err = dao_factory.consumers:update(consumer_t) assert.falsy(err) assert.truthy(consumer) local consumers, err = session:execute("SELECT * FROM consumers WHERE custom_id = '"..consumer_t.custom_id.."'") assert.falsy(err) assert.True(#consumers == 1) assert.are.same(consumer_t.name, consumers[1].name) end) end) describe("Plugin Configurations", function() it("should update in DB if entity can be found", function() local plugins_configurations, err = session:execute("SELECT * FROM plugins_configurations") assert.falsy(err) assert.True(#plugins_configurations > 0) local plugin_conf_t = plugins_configurations[1] plugin_conf_t.value = cjson.decode(plugin_conf_t.value) plugin_conf_t.enabled = false local plugin_conf, err = dao_factory.plugins_configurations:update(plugin_conf_t) assert.falsy(err) assert.truthy(plugin_conf) local plugins_configurations, err = session:execute("SELECT * FROM plugins_configurations WHERE id = ?", { cassandra.uuid(plugin_conf_t.id) }) assert.falsy(err) assert.are.same(1, #plugins_configurations) end) end) end) -- describe :update() describe(":delete()", function() setup(function() spec_helper.drop_db() spec_helper.seed_db(nil, 100) end) describe_core_collections(function(type, collection) it("should return false if there was nothing to delete", function() local ok, err = dao_factory[collection]:delete(uuid()) assert.is_not_true(ok) assert.falsy(err) end) it("should delete an entity if it can be found", function() local entities, err = session:execute("SELECT * FROM "..collection) assert.falsy(err) assert.truthy(entities) assert.True(#entities > 0) local success, err = dao_factory[collection]:delete(entities[1].id) assert.falsy(err) assert.True(success) local entities, err = session:execute("SELECT * FROM "..collection.." WHERE id = "..entities[1].id ) assert.falsy(err) assert.truthy(entities) assert.are.same(0, #entities) end) end) end) -- describe :delete() describe(":find()", function() setup(function() spec_helper.drop_db() spec_helper.seed_db(nil, 100) end) describe_core_collections(function(type, collection) it("should find entities", function() local entities, err = session:execute("SELECT * FROM "..collection) assert.falsy(err) assert.truthy(entities) assert.True(#entities > 0) local results, err = dao_factory[collection]:find() assert.falsy(err) assert.truthy(results) assert.are.same(#entities, #results) end) it("should allow pagination", function() -- 1st page local rows_1, err = dao_factory[collection]:find(2) assert.falsy(err) assert.truthy(rows_1) assert.are.same(2, #rows_1) assert.truthy(rows_1.next_page) -- 2nd page local rows_2, err = dao_factory[collection]:find(2, rows_1.next_page) assert.falsy(err) assert.truthy(rows_2) assert.are.same(2, #rows_2) end) end) end) -- describe :find() describe(":find_one()", function() describe_core_collections(function(type, collection) it("should find one entity by id", function() local entities, err = session:execute("SELECT * FROM "..collection) assert.falsy(err) assert.truthy(entities) assert.True(#entities > 0) local result, err = dao_factory[collection]:find_one(entities[1].id) assert.falsy(err) assert.truthy(result) end) it("should handle an invalid uuid value", function() local result, err = dao_factory[collection]:find_one("abcd") assert.falsy(result) assert.True(err.invalid_type) assert.are.same("abcd is an invalid uuid", err.message.id) end) end) describe("Plugin Configurations", function() it("should deserialize the table property", function() local plugins_configurations, err = session:execute("SELECT * FROM plugins_configurations") assert.falsy(err) assert.truthy(plugins_configurations) assert.True(#plugins_configurations > 0) local plugin_t = plugins_configurations[1] local result, err = dao_factory.plugins_configurations:find_one(plugin_t.id) assert.falsy(err) assert.truthy(result) assert.are.same("table", type(result.value)) end) end) end) -- describe :find_one() describe(":find_by_keys()", function() describe_core_collections(function(type, collection) it("should refuse non queryable keys", function() local results, err = session:execute("SELECT * FROM "..collection) assert.falsy(err) assert.truthy(results) assert.True(#results > 0) local t = results[1] local results, err = dao_factory[collection]:find_by_keys(t) assert.truthy(err) assert.is_daoError(err) assert.True(err.schema) assert.falsy(results) -- All those fields are indeed non queryable for k,v in pairs(err.message) do assert.is_not_true(dao_factory[collection]._schema[k].queryable) end end) it("should handle empty search fields", function() local results, err = dao_factory[collection]:find_by_keys({}) assert.falsy(err) assert.truthy(results) assert.True(#results > 0) end) it("should handle nil search fields", function() local results, err = dao_factory[collection]:find_by_keys(nil) assert.falsy(err) assert.truthy(results) assert.True(#results > 0) end) it("should query an entity by its queryable fields", function() local results, err = session:execute("SELECT * FROM "..collection) assert.falsy(err) assert.truthy(results) assert.True(#results > 0) local t = results[1] local q = {} -- Remove nonqueryable fields for k, schema_field in pairs(dao_factory[collection]._schema) do if schema_field.queryable then q[k] = t[k] elseif schema_field.type == "table" then t[k] = cjson.decode(t[k]) end end local results, err = dao_factory[collection]:find_by_keys(q) assert.falsy(err) assert.truthy(results) -- in case of plugins configurations if t.consumer_id == constants.DATABASE_NULL_ID then t.consumer_id = nil end assert.are.same(t, results[1]) end) end) end) -- describe :find_by_keys() -- -- Plugins configuration additional behaviour -- describe("Plugin Configurations", function() local api_id local inserted_plugin setup(function() spec_helper.drop_db() spec_helper.seed_db(nil, 100) end) it("should find distinct plugins configurations", function() local res, err = dao_factory.plugins_configurations:find_distinct() assert.falsy(err) assert.truthy(res) assert.are.same(8, #res) assert.truthy(utils.array_contains(res, "keyauth")) assert.truthy(utils.array_contains(res, "basicauth")) assert.truthy(utils.array_contains(res, "ratelimiting")) assert.truthy(utils.array_contains(res, "tcplog")) assert.truthy(utils.array_contains(res, "udplog")) assert.truthy(utils.array_contains(res, "filelog")) assert.truthy(utils.array_contains(res, "cors")) assert.truthy(utils.array_contains(res, "request_transformer")) end) it("should insert a plugin and set the consumer_id to a 'null' uuid if none is specified", function() -- Since we want to specifically select plugins configurations which have _no_ consumer_id sometimes, we cannot rely on using -- NULL (and thus, not inserting the consumer_id column for the row). To fix this, we use a predefined, nullified uuid... -- Create an API local api_t = faker:fake_entity("api") local api, err = dao_factory.apis:insert(api_t) assert.falsy(err) local plugin_t = faker:fake_entity("plugin_configuration") plugin_t.api_id = api.id local plugin, err = dao_factory.plugins_configurations:insert(plugin_t) assert.falsy(err) assert.truthy(plugin) assert.falsy(plugin.consumer_id) -- for next test api_id = api.id inserted_plugin = plugin inserted_plugin.consumer_id = nil end) it("should select a plugin configuration by 'null' uuid consumer_id and remove the column", function() -- Now we should be able to select this plugin local rows, err = dao_factory.plugins_configurations:find_by_keys { api_id = api_id, consumer_id = constants.DATABASE_NULL_ID } assert.falsy(err) assert.truthy(rows[1]) assert.are.same(inserted_plugin, rows[1]) assert.falsy(rows[1].consumer_id) end) end) -- describe plugins configurations end) -- describe DAO Collections -- -- KeyAuth plugin collection -- describe("KeyAuthCredentials", function() it("should not insert in DB if consumer does not exist", function() -- Without an consumer_id, it's a schema error local app_t = faker:fake_entity("keyauth_credential") app_t.consumer_id = nil local app, err = dao_factory.keyauth_credentials:insert(app_t) assert.falsy(app) assert.truthy(err) assert.is_daoError(err) assert.True(err.schema) assert.are.same("consumer_id is required", err.message.consumer_id) -- With an invalid consumer_id, it's a FOREIGN error local app_t = faker:fake_entity("keyauth_credential") app_t.consumer_id = uuid() local app, err = dao_factory.keyauth_credentials:insert(app_t) assert.falsy(app) assert.truthy(err) assert.is_daoError(err) assert.True(err.foreign) assert.are.same("consumer_id "..app_t.consumer_id.." does not exist", err.message.consumer_id) end) it("should insert in DB and add generated values", function() local consumers, err = session:execute("SELECT * FROM consumers") assert.falsy(err) assert.truthy(#consumers > 0) local app_t = faker:fake_entity("keyauth_credential") app_t.consumer_id = consumers[1].id local app, err = dao_factory.keyauth_credentials:insert(app_t) assert.falsy(err) assert.truthy(app.id) assert.truthy(app.created_at) end) it("should find an KeyAuth Credential by public_key", function() local app, err = dao_factory.keyauth_credentials:find_by_keys { key = "user122" } assert.falsy(err) assert.truthy(app) end) it("should handle empty strings", function() local apps, err = dao_factory.keyauth_credentials:find_by_keys { key = "" } assert.falsy(err) assert.are.same({}, apps) end) end) -- -- Rate Limiting plugin collection -- describe("Rate Limiting Metrics", function() local ratelimiting_metrics = dao_factory.ratelimiting_metrics local api_id = uuid() local identifier = uuid() after_each(function() spec_helper.drop_db() end) it("should return nil when ratelimiting metrics are not existing", function() local current_timestamp = 1424217600 local periods = timestamp.get_timestamps(current_timestamp) -- Very first select should return nil for period, period_date in pairs(periods) do local metric, err = ratelimiting_metrics:find_one(api_id, identifier, current_timestamp, period) assert.falsy(err) assert.are.same(nil, metric) end end) it("should increment ratelimiting metrics with the given period", function() local current_timestamp = 1424217600 local periods = timestamp.get_timestamps(current_timestamp) -- First increment local ok, err = ratelimiting_metrics:increment(api_id, identifier, current_timestamp) assert.falsy(err) assert.True(ok) -- First select for period, period_date in pairs(periods) do local metric, err = ratelimiting_metrics:find_one(api_id, identifier, current_timestamp, period) assert.falsy(err) assert.are.same({ api_id = api_id, identifier = identifier, period = period, period_date = period_date, value = 1 -- The important part }, metric) end -- Second increment local ok, err = ratelimiting_metrics:increment(api_id, identifier, current_timestamp) assert.falsy(err) assert.True(ok) -- Second select for period, period_date in pairs(periods) do local metric, err = ratelimiting_metrics:find_one(api_id, identifier, current_timestamp, period) assert.falsy(err) assert.are.same({ api_id = api_id, identifier = identifier, period = period, period_date = period_date, value = 2 -- The important part }, metric) end -- 1 second delay current_timestamp = 1424217601 periods = timestamp.get_timestamps(current_timestamp) -- Third increment local ok, err = ratelimiting_metrics:increment(api_id, identifier, current_timestamp) assert.falsy(err) assert.True(ok) -- Third select with 1 second delay for period, period_date in pairs(periods) do local expected_value = 3 if period == "second" then expected_value = 1 end local metric, err = ratelimiting_metrics:find_one(api_id, identifier, current_timestamp, period) assert.falsy(err) assert.are.same({ api_id = api_id, identifier = identifier, period = period, period_date = period_date, value = expected_value -- The important part }, metric) end end) it("should throw errors for non supported methods of the base_dao", function() assert.has_error(ratelimiting_metrics.find, "ratelimiting_metrics:find() not supported") assert.has_error(ratelimiting_metrics.insert, "ratelimiting_metrics:insert() not supported") assert.has_error(ratelimiting_metrics.update, "ratelimiting_metrics:update() not supported") assert.has_error(ratelimiting_metrics.delete, "ratelimiting_metrics:delete() not yet implemented") assert.has_error(ratelimiting_metrics.find_by_keys, "ratelimiting_metrics:find_by_keys() not supported") end) end) -- describe rate limiting metrics end)
function onEvent(name, value1, value2) if name == 'Play Sound' then playSound(value1, value2); end end
local PLAYER = PLAYER or FindMetaTable("Player") --Managing their data local function ct(tbl, temp) -- Copy Table local out = table.Copy(tbl) for key, val in pairs(temp) do -- Loop through all items on the table if istable(val) then -- If it's a table, we want to re-iterate if not istable(out[key]) then out[key] = {} end out[key] = ct(out[key], val) elseif type(out[key]) ~= type(val) then -- If it's not a table, we want to make sure the types match out[key] = val; end end return out end function PLAYER:CheckData() if not IsValid(self) then return end local d = table.Copy(nadmin.defaults.userdata) if self:IsBot() then return d end -- We don't want to save bot data, nor should they have any data nadmin.userdata[self:SteamID()] = ct(nadmin.userdata[self:SteamID()] or {}, d) return nadmin.userdata[self:SteamID()] end function nadmin:CheckData(id) if not isstring(id) then return end local d = table.Copy(nadmin.defaults.userdata) nadmin.userdata[id] = ct(nadmin.userdata[id] or {}, d) return nadmin.userdata[id] end function PLAYER:SaveData() if not IsValid(self) then return end if self:IsBot() then return end -- We don't want to save bot data self:CheckData() file.Write("nadmin/userdata/" .. string.lower(string.Replace(self:SteamID(), ":", ",")) .. ".txt", util.TableToJSON(nadmin.userdata[self:SteamID()], true)) end function nadmin:SaveData(id) if not isstring(id) then return end local user = nadmin:CheckData(id) file.Write("nadmin/userdata/" .. string.lower(string.Replace(id, ":", ",")) .. ".txt", util.TableToJSON(user, true)) end --HasGodMode fix for client if not isfunction(PLAYER.oldGodEnable) then PLAYER.oldGodEnable = PLAYER.GodEnable end if not isfunction(PLAYER.oldGodDisable) then PLAYER.oldGodDisable = PLAYER.GodDisable end function PLAYER:GodEnable() if not IsValid(self) then return end self:SetNWBool("nadmin_god", true) self:oldGodEnable() end function PLAYER:GodDisable() if not IsValid(self) then return end self:SetNWBool("nadmin_god", false) self:oldGodDisable() end -- Teleportation function PLAYER:AddReturnPosition(pos) if not IsValid(self) then return end local store = pos if not isvector(pos) then store = self:GetPos() end if not nadmin.plyReturns[self:SteamID()] then nadmin.plyReturns[self:SteamID()] = {} end local ret = nadmin.plyReturns[self:SteamID()] table.insert(ret, store) if #ret > 5 then table.remove(ret, 1) end end --Rank stuff function PLAYER:SetRank(rank) if not IsValid(self) then return false end self:CheckData() if istable(rank) then self:SetNWString("nadmin_rank", rank.id) if not self:IsBot() and rank.id ~= "NULL" then nadmin.userdata[self:SteamID()].rank = rank.id end self:SetUserGroup(rank.id) return true else local r = nadmin:FindRank(rank) if istable(r) then self:SetNWString("nadmin_rank", r.id) if not self:IsBot() and rank.id ~= "NULL" then nadmin.userdata[self:SteamID()].rank = r.id end self:SetUserGroup(r.id) return true end end return false end -- Level stuff function PLAYER:SetLevel(level, exp) if not IsValid(self) then return end if not isnumber(level) then return end local newLevel = nadmin:Ternary(level < 0, math.ceil(level), math.floor(level)) local xpToLevel = GetXpToLevel(level) local xp = (level - newLevel) * xpToLevel if isnumber(exp) then xp = xp + exp end self:SetNWInt("nadmin_level", newLevel) self:SetNWInt("nadmin_xp", xp) if not self:IsBot() then self:CheckData() nadmin.userdata[self:SteamID()].level.lvl = newLevel nadmin.userdata[self:SteamID()].level.xp = xp end end function PLAYER:AddExperience(xp) if not IsValid(self) then return end if self:IsBot() then return end if not isnumber(xp) then return end local maxChanges = 128 --Prevent an infinite while loop local changes = 0 local level = self:GetNWInt("nadmin_level", 1) local oldLevel = level local c = self:GetNWInt("nadmin_xp", 0) + xp local xpToLevel = GetXpToLevel(level) while (c >= xpToLevel or c < 0) and changes < maxChanges do changes = changes + 1 if c >= xpToLevel then level = level + 1 c = c - xpToLevel else --Must be less than xpToLevel level = level - 1 c = c + xpToLevel end xpToLevel = GetXpToLevel(level) end self:SetNWInt("nadmin_level", level) self:SetNWInt("nadmin_xp", c) if not self:IsBot() then self:CheckData() nadmin.userdata[self:SteamID()].level.lvl = level nadmin.userdata[self:SteamID()].level.xp = c end if oldLevel ~= level then nadmin:Notify(self, nadmin.colors.blue, "You have leveled up ", nadmin.colors.white, tostring(level - oldLevel), nadmin.colors.blue, " " .. nadmin:Ternary(level - oldLevel == 1, "time", "times") .. ", now you are level ", nadmin.colors.white, level, nadmin.colors.blue, ".") return true end return false end --Nicknaming function PLAYER:SetNick(nick, no_save) if not IsValid(self) then return end if isstring(nick) then if nick == self:RealName() then self:SetNWString("nadmin_nickname", self:RealName()) if not no_save then nadmin.userdata[self:SteamID()].forcedName = "" end else self:SetNWString("nadmin_nickname", nick) if not no_save then nadmin.userdata[self:SteamID()].forcedName = nick end end else self:SetNWString("nadmin_nickname", self:RealName()) if not no_save then nadmin.userdata[self:SteamID()].forcedName = "" end end end -- Playtime function PLAYER:SetPlayTime(time) if not IsValid(self) then return false end self:SetNWInt("nadmin_playtime", tonumber(time)) if not self:IsBot() then self:CheckData() nadmin.userdata[self:SteamID()].playtime = time end end -- Remove props function PLAYER:RemoveProps() if not IsValid(self) then return end for i, ent in ipairs(ents.GetAll()) do if CPPI and ent.CPPIGetOwner then if ent:CPPIGetOwner() == self then ent:Remove() end else if ent.nadmin_owner == self then ent:Remove() end end end end
local class = {} function class:MessageAble(ctx, http) local Messageable = {} function Messageable:send(message) local msg = { content = message, tts = false } http:Route("POST", msg, ctx) end return Messageable end function class:TextChannel(prop, http) local channel = {} channel.id = prop.channel_id or nil local context = "/channels/"..channel.id.."/messages" local messageable = self:MessageAble(context, http) channel.send = messageable.send return channel end return class
-------------------------------- -- @module TransitionZoomFlipAngular -- @extend TransitionSceneOriented -- @parent_module cc -------------------------------- -- @overload self, float, cc.Scene -- @overload self, float, cc.Scene, int -- @function [parent=#TransitionZoomFlipAngular] create -- @param self -- @param #float t -- @param #cc.Scene s -- @param #int o -- @return TransitionZoomFlipAngular#TransitionZoomFlipAngular ret (return value: cc.TransitionZoomFlipAngular) -------------------------------- -- -- @function [parent=#TransitionZoomFlipAngular] TransitionZoomFlipAngular -- @param self -- @return TransitionZoomFlipAngular#TransitionZoomFlipAngular self (return value: cc.TransitionZoomFlipAngular) return nil
--[[ --- Day 23: Experimental Emergency Teleportation --- ]]-- local printf = function(s,...) return io.write(s:format(...)) end local fname = arg[1] local verbose = (fname == '-v') if verbose then fname = arg[2] end local bots = {} local maxr = 0 local maxb local minx = 100000000000 local maxx = -100000000000 local miny = 100000000000 local maxy = -100000000000 local minz = 100000000000 local maxz = -100000000000 local function readbots () local infile = io.open(fname or "2018_advent_23a.txt") local line = infile:read("l") while line do -- pos=<0,0,0>, r=4 local x,y,z,r = line:match("pos=<(%-?%d+),(%-?%d+),(%-?%d+)>, r=(%d+)") local tr = tonumber(r) local tz = tonumber(z) local ty = tonumber(y) local tx = tonumber(x) bots[#bots+1] = {x = tx, y = ty, z = tz, r = tr} if tr > maxr then maxr = tr maxb = bots[#bots] end minx = math.min(minx, tx) maxx = math.max(maxx, tx) miny = math.min(miny, ty) maxy = math.max(maxy, ty) minz = math.min(minz, tz) maxz = math.max(maxz, tz) line = infile:read("l") end printf("Read %d bots with max r = %d, x=%d..%d y=%d..%d z=%d..%d\n", #bots, maxr, minx, maxx, miny, maxy, minz, maxz) infile:close() end local function taxidist (p, b) return math.abs(p.x - b.x) + math.abs(p.y - b.y) + math.abs(p.z - b.z) end local m_n = 0 -- number of values local m_oldM local m_oldS local mind = 100000000000 local maxd = -100000000000 local function statpush (x) mind = math.min(mind, x) maxd = math.max(maxd, x) m_n = m_n + 1 -- See Knuth TAOCP vol 2, 3rd edition, page 232 if (m_n == 1) then m_oldM = x m_newM = x m_oldS = 0.0 else m_newM = m_oldM + (x - m_oldM) / m_n m_newS = m_oldS + (x - m_oldM) * (x - m_newM) -- set up for next iteration m_oldM = m_newM m_oldS = m_newS end end local function statmean () return (m_n > 0) and m_newM or 0.0 end local function statvariance () return (m_n > 1) and (m_newS / (m_n - 1)) or 0.0 end local function statstddev () return math.sqrt(statvariance()) end local function part1 () readbots() local count = 0 for i = 1, #bots do if taxidist(maxb, bots[i]) <= maxr then count = count + 1 end end printf("Part1: bots in range: %d\n", count) end intersects = {} local function part2a () local n = #bots for i = 1, n do intersects[i] = 0 end for i = 1, n - 1 do for j = i + 1, n do local d = taxidist(bots[i], bots[j]) statpush(d) if d < (bots[i].r + bots[j].r) then -- intersect intersects[i] = intersects[i] + 1 intersects[j] = intersects[j] + 1 end end end end local function part2 () part2a() printf("Distance min %d mean %g max %d stdvar %g\n", mind, statmean(), maxd, statvariance()) if verbose then for i = 1, #bots do printf("%d\n", intersects[i]) end end end local abs = math.abs local function part2b () -- this is a translation of seligman99's Python solution after I gave up -- https://pastebin.com/e7LdSNQe local x0 = minx local xn = maxx local y0 = miny local yn = maxy local z0 = minz local zn = maxz local dist = 1 while dist < maxx - minx do dist = dist * 2 end while true do if verbose then printf("Major loop: %d %d %d\n", dist, x0, xn) end local target_count = 0 local best = nil local best_val = nil for x = x0, xn + 1, dist do for y = y0, yn + 1, dist do for z = z0, zn + 1, dist do if verbose then printf("%d %d %d\n", x, y, z) end local count = 0 local bdist local calc for b = 1, #bots do local bx = bots[b].x local by = bots[b].y local bz = bots[b].z bdist = bots[b].r calc = abs(x - bx) + abs(y - by) + abs(z - bz) -- we want integer math here (floor) if (calc - bdist) // dist <= 0 then count = count + 1 end end if verbose then printf("Count calc bdist: %d %d %d\n", count, calc, bdist) end if count > target_count then target_count = count best_val = abs(x) + abs(y) + abs(z) best = {x, y, z} elseif count == target_count then if best_val == nil or abs(x) + abs(y) + abs(z) < best_val then best_val = abs(x) + abs(y) + abs(z) best = {x, y, z} end end end end end if dist == 1 then printf("The max count I found was: %d with val % d\n", target_count, best_val) return best_val else x0, xn = best[1] - dist, best[1] + dist y0, yn = best[2] - dist, best[2] + dist z0, zn = best[3] - dist, best[3] + dist -- we want integer math here, floor dist = dist // 2 end end end part1() part2b() print "Done"
wind_harpy_tornado_checker_modifier = class({}) function wind_harpy_tornado_checker_modifier:OnCreated( kv ) self.damage = self:GetAbility():GetSpecialValueFor("damage") end function wind_harpy_tornado_checker_modifier:DeclareFunctions() local funcs = { MODIFIER_PROPERTY_TOOLTIP, } return funcs end function wind_harpy_tornado_checker_modifier:OnTooltip( params ) return self.damage end function wind_harpy_tornado_checker_modifier:GetAttributes() return MODIFIER_ATTRIBUTE_IGNORE_INVULNERABLE end function wind_harpy_tornado_checker_modifier:IsHidden() return false end function wind_harpy_tornado_checker_modifier:IsPurgable() return false end function wind_harpy_tornado_checker_modifier:IsPurgeException() return false end function wind_harpy_tornado_checker_modifier:IsStunDebuff() return false end function wind_harpy_tornado_checker_modifier:IsDebuff() return true end
object_tangible_component_weapon_new_weapon_enhancement_melee_slot_one_s06 = object_tangible_component_weapon_new_weapon_shared_enhancement_melee_slot_one_s06:new { } ObjectTemplates:addTemplate(object_tangible_component_weapon_new_weapon_enhancement_melee_slot_one_s06, "object/tangible/component/weapon/new_weapon/enhancement_melee_slot_one_s06.iff")
--[[ ALGORITMO É uma sequencia de comandos em uma ordem logica e sequencial a fim de realizar um objetivo pré definido. Ex. Jogar papel no lixo 1 - Pegar o papel 2 - Amassar o papel 3 - Encontrar a lixeira 4 - Jogar o papel na lixeira Ex. escovar os dentes 1 - Ir ao banheiro 2 - Abrir o armario 3 - Pegar a escova 4 - Pegar a bisnaga com pasta de dente 5 - Abrir a bisnaga 6 - Colocar a pasta na escova 7 - Fechar a bisnaga 8 - Molhar a escova 9 - Mover a escova para a boca 10 - Escovar os dentes 11 - Cuspir na pia 12 - Colocar a escova na pia 13 - Abrir a torneira 14 - Pegar agua 15 - Enxaguar a boca 16 - Cuspir na pia 17 - Lava a escova 18 - Guardar a escova ]]--
--[[ AutoApply.lua @Author : DengSir ([email protected]) @Link : https://dengsir.github.io ]] BuildEnv(...) AutoApply = Addon:NewModule('AutoApply', 'AceEvent-3.0', 'AceBucket-3.0', 'AceTimer-3.0') function AutoApply:OnInitialize() self.applies = {} self.events = {'LFG_LIST_SEARCH_RESULT_UPDATED', 'LFG_LIST_SEARCH_RESULTS_RECEIVED'} end function AutoApply:Add(apply) tinsert(self.applies, apply) end function AutoApply:Pickup() return tremove(self.applies, 1) end function AutoApply:Start() if self.co then return end self.co = coroutine.create(function() self:Process() self.co = nil end) assert(coroutine.resume(self.co)) end function AutoApply:Reset() if self.bucket then self:UnregisterBucket(self.bucket) self.bucket = nil end if self.timer then self:CancelTimer(self.timer) self.timer = nil end self:UnregisterEvent('LFG_LIST_SEARCH_FAILED') end function AutoApply:Wakeup(flag, ...) self:Reset() assert(coroutine.resume(self.co, flag, ...)) end function AutoApply:Search(apply) C_LFGList.Search(apply:GetSearchArgs()) self.timer = self:ScheduleTimer(function() return self:Wakeup(true) end, 10) self.bucket = self:RegisterBucketEvent(self.events, 1, function() local activities = {} local wait = false local count, list = C_LFGList.GetSearchResults() for _, id in ipairs(list) do local activity = Activity:Get(id) if not activity:IsDelisted() or not activity:GetActivityID() then local match, ready = apply:Match(activity) wait = wait or not ready if match then tinsert(activities, activity) if apply:IsOneBreak() then return self:Wakeup(true, activities) end end end end if not wait then return self:Wakeup(true, activities) end end) self:RegisterEvent('LFG_LIST_SEARCH_FAILED', function() self:Reset() self:ScheduleTimer('Search', 3, apply) end) end function AutoApply:SearchApply(apply) self:Search(apply) return coroutine.yield() end function AutoApply:Sleep(n) C_Timer.After(n, function() coroutine.resume(self.co) end) coroutine.yield() end function AutoApply:Process() repeat local apply = self:Pickup() if not apply then return end local activityName = apply:GetName() local flag, activities = self:SearchApply(apply) if not flag or not activities then return end if type(apply.SortHandler) == 'function' then sort(activities, function(a, b) return apply:SortHandler(a) < apply:SortHandler(b) end) end local count = 0 for _, activity in ipairs(activities) do local usable, reason do if activity then usable, reason = BrowsePanel:CheckSignUpStatus(activity) else usable, reason = false, L['没有找到活动'] end end if activity and usable then C_LFGList.ApplyToGroup(activity:GetID(), '', apply:IsTank(), apply:IsHealer(), apply:IsDamager()) count = count + 1 apply:Log(activity, true, reason) self:Sleep(2) else apply:Log(activity, false, reason) end end apply:LogDone(count, #activities) until false end
local E, L, V, P, G = unpack(select(2, ...)); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB local S = E:GetModule('Skins') --Lua functions local _G = _G --WoW API / Variables local function LoadSkin() if E.private.skins.blizzard.questChoice ~= true then return end local QuestChoiceFrame = _G.QuestChoiceFrame for i = 1, 4 do local option = QuestChoiceFrame["Option"..i] local rewards = option.Rewards local item = rewards.Item local icon = item.Icon local currencies = rewards.Currencies item.IconBorder:SetAlpha(0) S:HandleIcon(icon) icon:SetDrawLayer("ARTWORK") for j = 1, 3 do local cu = currencies["Currency"..j] S:HandleIcon(cu.Icon) end end QuestChoiceFrame:CreateBackdrop("Transparent") S:HandleButton(_G.QuestChoiceFrameOption1.OptionButtonsContainer.OptionButton1) S:HandleButton(_G.QuestChoiceFrameOption2.OptionButtonsContainer.OptionButton1) S:HandleButton(_G.QuestChoiceFrameOption3.OptionButtonsContainer.OptionButton1) S:HandleButton(_G.QuestChoiceFrameOption4.OptionButtonsContainer.OptionButton1) S:HandleCloseButton(QuestChoiceFrame.CloseButton) QuestChoiceFrame.CloseButton:SetFrameLevel(10) end S:AddCallbackForAddon("Blizzard_QuestChoice", "QuestChoice", LoadSkin)
--if you wanna see the mouse X and Y coordinates turn this on count = 0 mouseX = display.newText( count , display.contentCenterX, 60, native.systemFont, 40 ) mouseX:setFillColor( 0, 0, 0 ) mouseY = display.newText( count , display.contentCenterX, 120, native.systemFont, 40 ) mouseY:setFillColor( 0, 0, 0 ) local function onMouseEvent( event ) mouseX.text = event.x mouseY.text = event.y end Runtime:addEventListener( "mouse", onMouseEvent )
local middot = '·' local raquo = '»' local small_l = 'ℓ' -- Override default `foldtext()`, which produces something like: -- -- +--- 2 lines: source $HOME/.config/nvim/pack/bundle/opt/vim-pathogen/autoload/pathogen.vim-------------------------------- -- -- Instead returning: -- -- »··[2ℓ]··: source $HOME/.config/nvim/pack/bundle/opt/vim-pathogen/autoload/pathogen.vim··································· -- local foldtext = function() local lines = '[' .. (vim.v.foldend - vim.v.foldstart + 1) .. small_l .. ']' local first = ({vim.api.nvim_buf_get_lines(0, vim.v.foldstart - 1, vim.v.foldstart, true)[1]:gsub(' *', '', 1)})[1] local dashes = ({vim.v.folddashes:gsub('-', middot)})[1] return raquo .. middot .. middot .. lines .. dashes .. ': ' .. first end return foldtext
local logic = require "logic" remote.add_interface("advanced-combinator", { resolve = function(param, entity, current) local logic_data = logic.logic[param.name] if not logic_data then error("No such function name: " .. param.name) end local parsed = logic.parse(logic_data, param.params, entity) return parsed(entity, current) end, add_function = function(name, function_declaration) if logic.logic[name] then error("Function " .. name .. " already exists") end local callback_interface = function_declaration.parse function_declaration.parse = function(params) -- Prepare parameters so that they can be sent between mods. -- Mods needs to call `remote.call("advanced-combinator", "resolve", param_value, entity, current)` for _, v in pairs(params) do if type(v) == "table" then v.func = nil end end return function(entity, current) return remote.call(callback_interface.interface, callback_interface.func, params, entity, current) end end logic.logic[name] = function_declaration end })
arg = nil -- import flower = require "flower" tests = require "tests" require "LuaUnit" -- setting local screenWidth = MOAIEnvironment.horizontalResolution or 320 local screenHeight = MOAIEnvironment.verticalResolution or 480 local screenDpi = MOAIEnvironment.screenDpi or 120 local viewScale = math.floor(screenDpi / 240) + 1 -- open scene flower.openWindow("Flower samples", screenWidth, screenHeight, viewScale) -- run tests LuaUnit:setVerbosity( 1 ) LuaUnit:run(unpack(tests)) --os.exit(LuaUnit:run(unpack(tests)))
BANANA_SYMBOL_COLOR1 = "00f7f26c"; BANANA_SYMBOL_COLOR2 = "00f69218"; BANANA_SYMBOL_COLOR3 = "00cb32dd"; BANANA_SYMBOL_COLOR4 = "000fb20a"; BANANA_SYMBOL_COLOR5 = "008cb0c5"; BANANA_SYMBOL_COLOR6 = "00007aff"; BANANA_SYMBOL_COLOR7 = "00d7422e"; BANANA_SYMBOL_COLOR8 = "00e7e4d9"; BANANA_SYMBOL_COLORHM = "00d0d0d0"; BANANA_RAID_TARGET_X = { [1] = "RAID_TARGET_1", [2] = "RAID_TARGET_2", [3] = "RAID_TARGET_3", [4] = "RAID_TARGET_4", [5] = "RAID_TARGET_5", [6] = "RAID_TARGET_6", [7] = "RAID_TARGET_7", [8] = "RAID_TARGET_8", } BANANA_RAID_CURSORS = { [1] = "Interface\\AddOns\\BananaBar3\\Images\\rs1", [2] = "Interface\\AddOns\\BananaBar3\\Images\\rs2", [3] = "Interface\\AddOns\\BananaBar3\\Images\\rs3", [4] = "Interface\\AddOns\\BananaBar3\\Images\\rs4", [5] = "Interface\\AddOns\\BananaBar3\\Images\\rs5", [6] = "Interface\\AddOns\\BananaBar3\\Images\\rs6", [7] = "Interface\\AddOns\\BananaBar3\\Images\\rs7", [8] = "Interface\\AddOns\\BananaBar3\\Images\\rs8", [9] = "Interface\\AddOns\\BananaBar3\\Images\\rs9", --hunter's mark } BANANA_RAID_CURSORS_GREY = { [1] = "Interface\\AddOns\\BananaBar3\\Images\\rs1x", [2] = "Interface\\AddOns\\BananaBar3\\Images\\rs2x", [3] = "Interface\\AddOns\\BananaBar3\\Images\\rs3x", [4] = "Interface\\AddOns\\BananaBar3\\Images\\rs4x", [5] = "Interface\\AddOns\\BananaBar3\\Images\\rs5x", [6] = "Interface\\AddOns\\BananaBar3\\Images\\rs6x", [7] = "Interface\\AddOns\\BananaBar3\\Images\\rs7x", [8] = "Interface\\AddOns\\BananaBar3\\Images\\rs8x", [9] = "Interface\\AddOns\\BananaBar3\\Images\\rs9x", --hunter's mark } BANANA_OVL_GREEN = "Interface\\AddOns\\BananaBar3\\Images\\OverlayGreen66"; BANANA_OVL_RED = "Interface\\AddOns\\BananaBar3\\Images\\OverlayRed66"; BANANA_OVL_YELLOW = "Interface\\AddOns\\BananaBar3\\Images\\OverlayYellow66"; BANANA_OVL_MAGENTA = "Interface\\AddOns\\BananaBar3\\Images\\OverlayMagenta66"; BANANA_TEXTURE_NULL = "Interface\\AddOns\\BananaBar3\\Images\\null"; BANANA_TEXTURE_X = "Interface\\AddOns\\BananaBar3\\Images\\x"; BANANA_TEXTURE_ENEMY = "Interface\\AddOns\\BananaBar3\\Images\\rp_enemy"; BANANA_TEXTURE_FRIEND = "Interface\\AddOns\\BananaBar3\\Images\\rp_friend"; BANANA_TEXTURE_OFFLINE = "Interface\\AddOns\\BananaBar3\\Images\\rp_offline"; BANANA_TEXTURE_OFFLINE2 = "Interface\\AddOns\\BananaBar3\\Images\\rp_offline2"; BANANA_TEXTURE_AWAY = "Interface\\AddOns\\BananaBar3\\Images\\rp_away"; BANANA_TEXTURE_DEAD = "Interface\\AddOns\\BananaBar3\\Images\\rp_dead"; BANANA_TEXTURE_GHOST = "Interface\\AddOns\\BananaBar3\\Images\\rp_ghost"; BANANA_TEXTURE_DRUID = "Interface\\AddOns\\BananaBar3\\Images\\healer_druid"; BANANA_TEXTURE_PRIEST = "Interface\\AddOns\\BananaBar3\\Images\\healer_priest"; BANANA_TEXTURE_SHAMAN = "Interface\\AddOns\\BananaBar3\\Images\\healer_shaman"; BANANA_TEXTURE_PALADIN = "Interface\\AddOns\\BananaBar3\\Images\\healer_paladin"; BANANA_TEXTURE_RAIDICONS_FLAT = "Interface\\AddOns\\BananaBar3\\Images\\RaidTargetingIconsFlat"; BANANA_TEXTURE_RAIDICONS = "Interface\\TargetingFrame\\UI-RaidTargetingIcons"; BANANA_TEXTURE_HUNTERSMARK = "Interface\\AddOns\\BananaBar3\\Images\\HuntermarkArrow"; BANANA_TEXTURE_MINIMAPICON = "Interface\\AddOns\\BananaBar3\\Images\\BananaBar64" BANANA_SOUND_SET = "Interface\\AddOns\\BananaBar3\\Sound\\BananaSetSymbol.mp3" BANANA_SOUND_REMOVE = "Interface\\AddOns\\BananaBar3\\Sound\\BananaPlop1.mp3" BANANA_SOUND_REMOVE_ALL = "Interface\\AddOns\\BananaBar3\\Sound\\BananaPlop8.mp3" BANANA_SOUND_ERROR = "Interface\\AddOns\\BananaBar3\\Sound\\BananaNo.mp3" BANANA_ABILITY_HUNTER_SNIPERSHOT = "Interface\\Icons\\Ability_Hunter_SniperShot"; BANANA_DOCK_NONE = 0 BANANA_DOCK_TOP = 1 BANANA_DOCK_RIGHT = 2 BANANA_DOCK_BOTTOM = 3 BANANA_DOCK_LEFT = 4 BANANA_RAIDSYMBOL_BUTTON_COUNT = 8; BANANA_UNKNOWN_BUTTON_COUNT = 4; BANANA_MAX_BUTTONS = 8+BANANA_UNKNOWN_BUTTON_COUNT;
--[[ skyfactory_quests ================ Copyright (C) 2018-2019 Quentin Bazin LGPLv2.1+ See LICENSE.txt for more information ]]-- local page = 2 quest_lib.pages[page] = {} quest_lib.pages[page].quests = { --[[{ name = 'Sieve Gravel, Sand or Dust to get ore pieces', hint = 'default:gravel', quest = 'pickup_ore_pieces', count = 8, reward = 'default:gravel 64', pickup = {'fs_sieve:iron_ore_piece'}, },]]-- { name = 'Craft a Bucket', hint = 'bucket:bucket_empty', quest = 'craft_bucket', count = 1, reward = 'default:gold_lump', craft = {'bucket:bucket_empty'}, }, { name = 'Craft and place a Wooden Crucible to get Water from Leaves', hint = 'fs_crucible:crucible_wood', quest = 'craft_wooden_crucible', count = 1, reward = 'default:leaves 42', placenode = {'fs_crucible:crucible_wood'}, }, { name = 'Make Clay by mixing Water and Dust in a Barrel', hint = 'default:clay_lump', quest = 'dig_clay', count = 4, reward = 'default:clay 4', dignode = {'default:clay'}, }, { name = 'Craft and place a Crucible to get Lava from Cobblestone', hint = 'fs_crucible:crucible', quest = 'craft_crucible', count = 1, reward = 'default:torch', placenode = {'fs_crucible:crucible'}, }, } quest_lib.pages[page].get_description = function(player_name) return { "Hey "..player_name..", Come Up Here!", "Wow, look at that view... of... nothing...", "You should get to work extending this island.", "Perhaps you could start getting some ores too?", } end
local folderOfThisFile = (...):match("(.-)[^%/%.]+$") -- ゲームクラス local Game = require(folderOfThisFile .. 'class') -- クラス local Application = require 'Application' local Field = require 'Field' -- 初期化 function Game:initialize(...) Application.initialize(self, ...) end -- 読み込み function Game:load(...) -- スクリーンサイズ self.width, self.height = love.graphics.getDimensions() -- フィールド self.field = Field { width = 300, height = 300, numHorizontal = 10, numVertical = 10, maxEntities = 10000, } for i = 1, 0 do self.field:emplaceEntity { x = love.math.random(self.field.width), y = love.math.random(self.field.height), angle = math.pi * 2 * 0.25, components = { (require 'components.Seed') {}, }, } end for i = 1, 10 do self.field:emplaceEntity { x = love.math.random(self.field.width), y = love.math.random(self.field.height), angle = math.pi * 2 * 0.25, components = { (require 'components.Leg') {}, (require 'components.Head') {}, (require 'components.Body') {}, (require 'components.Eye') {}, }, } end -- 移動モード self.move = false self.moveOrigin = { x = 0, y = 0 } self.offsetOrigin = { x = 0, y = 0 } self.offset = { x = 0, y = 0 } self.zoom = 0 self.speed = 1 self:setOffset() end -- 更新 function Game:update(dt, ...) dt = dt * self.speed -- 中クリック if love.mouse.isDown(3) then if not self.move then -- 移動モード開始 self.move = true self.moveOrigin.x, self.moveOrigin.y = love.mouse.getPosition() self.offsetOrigin.x, self.offsetOrigin.y = self.offset.x, self.offset.y else -- 移動中 local x, y = love.mouse.getPosition() self:setOffset(self.offsetOrigin.x + x - self.moveOrigin.x, self.offsetOrigin.y + y - self.moveOrigin.y) end else if self.move then -- 移動モード終了 self.move = false end end self.field:update(dt) end -- 描画 function Game:draw(...) -- フィールド描画 love.graphics.push() do love.graphics.translate(self.offset.x, self.offset.y) love.graphics.scale(self:scale()) self.field:draw() end love.graphics.pop() -- デバッグ love.graphics.setColor(1, 1, 1) local str = 'FPS: ' .. tostring(love.timer.getFPS()) .. '\nscale = ' .. self:scale() .. '\nzoom = ' .. self.zoom .. '\nspeed = ' .. self.speed .. '\n' local x, y = love.mouse.getPosition() x, y = (x - self.offset.x) / self:scale(), (y - self.offset.y) / self:scale() str = str .. 'x = ' .. x .. ', y = ' .. y .. '\n\nsquare\n' local square = self.field:getSquare(x, y) if square then str = str .. 'animal = ' .. square.nutrients.animal .. '' str = str .. ', plantal = ' .. square.nutrients.plantal .. '' str = str .. ', mineral = ' .. square.nutrients.mineral .. '' str = str .. '\ndecomposer.amount = ' .. square.decomposer.amount .. '\n' end str = str .. '\nentities = ' .. #self.field.entities .. '\n\n' local entity = self.field.entities[1] if entity then str = str .. 'entity [1]\n' str = str .. ' x = ' .. entity.x .. ', y = ' .. entity.y .. '\n' for _, c in ipairs(entity.components) do str = str .. ' ' .. c.class.name .. '\n' if c.nutrients then str = str .. ' life = ' .. c.life .. ', health = ' .. c.health .. ', energy = ' .. c.energy .. ', cost = ' .. c.cost .. '\n' str = str .. ' nutrients.animal = ' .. c.nutrients.animal .. ', .plantal = ' .. c.nutrients.plantal .. ', .mineral = ' .. c.nutrients.mineral .. '\n' end end end love.graphics.print(str) end -- キー入力 function Game:keypressed(key, scancode, isrepeat) if key == '1' then self.speed = 1 elseif key == '2' then self.speed = 2 elseif key == '3' then self.speed = 4 elseif key == '4' then self.speed = 8 elseif key == '5' then self.speed = 16 elseif key == '6' then self.speed = 32 elseif key == '7' then self.speed = 64 elseif key == '8' then self.speed = 128 elseif key == '9' then self.speed = 256 elseif key == '0' then self.speed = 0 else end end -- キー離した function Game:keyreleased(key, scancode) end -- テキスト入力 function Game:textinput(text) end -- マウス入力 function Game:mousepressed(x, y, button, istouch, presses) end -- マウス離した function Game:mousereleased(x, y, button, istouch, presses) end -- マウス移動 function Game:mousemoved(x, y, dx, dy, istouch) end -- マウスホイール function Game:wheelmoved(x, y) if y < 0 and self.zoom > -19 then -- ズームアウト self.zoom = self.zoom - 1 self:setOffset() elseif y > 0 and self.zoom < 9 then -- ズームイン self.zoom = self.zoom + 1 self:setOffset() end end -- リサイズ function Game:resize(width, height) self.width, self.height = width, height self:setOffset() end -- リサイズ function Game:scale() if self.zoom == 0 then return 1 elseif self.zoom > 0 then return self.zoom + 1 elseif self.zoom < 0 then return 1 / math.abs(self.zoom - 1) end end -- オフセットの設定 function Game:setOffset(x, y) local s = self:scale() self.offset.x = math.max(-self.field.width * s + self.width * 0.5, math.min(x or self.offset.x, self.width * 0.5)) self.offset.y = math.max(-self.field.height * s + self.height * 0.5, math.min(y or self.offset.y, self.height * 0.5)) self.field:setViewport(-self.offset.x / s, -self.offset.y / s, self.width / s, self.height / s) end
----------------------------------------------------------------------------------------------------------------------- -- RedFlat map layout -- ----------------------------------------------------------------------------------------------------------------------- -- Tiling with user defined geometry ----------------------------------------------------------------------------------------------------------------------- -- Grab environment ----------------------------------------------------------------------------------------------------------------------- local ipairs = ipairs local pairs = pairs local math = math local unpack = unpack or table.unpack local awful = require("awful") local timer = require("gears.timer") local redflat = require("redflat") local redutil = require("redflat.util") local common = require("redflat.layout.common") local rednotify = require("redflat.float.notify") local hasitem = awful.util.table.hasitem -- Initialize tables for module ----------------------------------------------------------------------------------------------------------------------- local map = { data = setmetatable({}, { __mode = "k" }), scheme = setmetatable({}, { __mode = "k" }), keys = {} } map.name = "usermap" map.notification = true map.notification_style = {} local hitimer map.hilight_timeout = 0.2 -- default keys map.keys.layout = { { { "Mod4" }, "s", function() map.swap_group() end, { description = "Change placement direction for group", group = "Layout" } }, { { "Mod4" }, "v", function() map.new_group(true) end, { description = "Create new vertical group", group = "Layout" } }, { { "Mod4" }, "b", function() map.new_group(false) end, { description = "Create new horizontal group", group = "Layout" } }, { { "Mod4", "Control" }, "v", function() map.insert_group(true) end, { description = "Insert new vertical group before active", group = "Layout" } }, { { "Mod4", "Control" }, "b", function() map.insert_group(false) end, { description = "Insert new horizontal group before active", group = "Layout" } }, { { "Mod4" }, "d", function() map.delete_group() end, { description = "Destroy group", group = "Layout" } }, { { "Mod4", "Control" }, "d", function() map.clean_groups() end, { description = "Destroy all empty groups", group = "Layout" } }, { { "Mod4" }, "a", function() map.set_active() end, { description = "Set active group", group = "Layout" } }, { { "Mod4" }, "f", function() map.move_to_active() end, { description = "Move focused client to active group", group = "Layout" } }, { { "Mod4", "Control" }, "a", function() map.hilight_active() end, { description = "Hilight active group", group = "Layout" } }, { { "Mod4" }, ".", function() map.switch_active(1) end, { description = "Activate next group", group = "Layout" } }, { { "Mod4" }, ",", function() map.switch_active(-1) end, { description = "Activate previous group", group = "Layout" } }, { { "Mod4" }, "]", function() map.move_group(1) end, { description = "Move active group to the top", group = "Layout" } }, { { "Mod4" }, "[", function() map.move_group(-1) end, { description = "Move active group to the bottom", group = "Layout" } }, { { "Mod4" }, "r", function() map.reset_tree() end, { description = "Reset layout structure", group = "Layout" } }, } map.keys.resize = { { { "Mod4" }, "h", function() map.incfactor(nil, 0.1, false) end, { description = "Increase window horizontal size factor", group = "Resize" } }, { { "Mod4" }, "l", function() map.incfactor(nil, -0.1, false) end, { description = "Decrease window horizontal size factor", group = "Resize" } }, { { "Mod4" }, "k", function() map.incfactor(nil, 0.1, true) end, { description = "Increase window vertical size factor", group = "Resize" } }, { { "Mod4" }, "j", function() map.incfactor(nil, -0.1, true) end, { description = "Decrease window vertical size factor", group = "Resize" } }, { { "Mod4", "Control" }, "h", function() map.incfactor(nil, 0.1, false, true) end, { description = "Increase group horizontal size factor", group = "Resize" } }, { { "Mod4", "Control" }, "l", function() map.incfactor(nil, -0.1, false, true) end, { description = "Decrease group horizontal size factor", group = "Resize" } }, { { "Mod4", "Control" }, "k", function() map.incfactor(nil, 0.1, true, true) end, { description = "Increase group vertical size factor", group = "Resize" } }, { { "Mod4", "Control" }, "j", function() map.incfactor(nil, -0.1, true, true) end, { description = "Decrease group vertical size factor", group = "Resize" } }, } map.keys.all = awful.util.table.join(map.keys.layout, map.keys.resize) -- Support functions ----------------------------------------------------------------------------------------------------------------------- -- Layout action notifications -------------------------------------------------------------------------------- local function notify(txt) if map.notification then rednotify:show(redutil.table.merge({ text = txt }, map.notification_style)) end end -- Calculate geometry for single client or group -------------------------------------------------------------------------------- local function cut_geometry(wa, is_vertical, size) if is_vertical then local g = { x = wa.x, y = wa.y, width = wa.width, height = size } wa.y = wa.y + size return g else local g = { x = wa.x, y = wa.y, width = size, height = wa.height } wa.x = wa.x + size return g end end -- Build container for single client or group -------------------------------------------------------------------------------- function map.construct_itempack(cls, wa, is_vertical, parent) local pack = { items = {}, wa = wa, cls = { unpack(cls) }, is_vertical = is_vertical, parent = parent } -- Create pack of items with base properties ------------------------------------------------------------ for i, c in ipairs(cls) do pack.items[i] = { client = c, child = nil, factor = 1 } end -- Update pack clients ------------------------------------------------------------ function pack:set_cls(clist) local current = { unpack(clist) } -- update existing items, remove overage if need for i, item in ipairs(self.items) do if not item.child then if #current > 0 then self.items[i].client = current[1] table.remove(current, 1) else self.items[i] = nil end end end -- create additional items if need for _, c in ipairs(current) do self.items[#self.items + 1] = { client = c, child = nil, factor = 1 } end end -- Get current pack clients ------------------------------------------------------------ function pack:get_cls() local clist = {} for _, item in ipairs(self.items) do if not item.child then clist[#clist + 1] = item.client end end return clist end -- Update pack geometry ------------------------------------------------------------ function pack:set_wa(workarea) self.wa = workarea end -- Get number of items reserved for single client only ------------------------------------------------------------ function pack:get_places() local n = 0 for _, item in ipairs(self.items) do if not item.child then n = n + 1 end end return n end -- Get child index ------------------------------------------------------------ function pack:get_child_id(pack_) for i, item in ipairs(self.items) do if item.child == pack_ then return i end end end -- Check if container with inheritors keep any real client ------------------------------------------------------------ function pack:is_filled() local filled = false for _, item in ipairs(self.items) do if not item.child then return true else filled = filled or item.child:is_filled() end end return filled end -- Increase window size factor for item with index ------------------------------------------------------------ function pack:incfacror(index, df, vertical) if vertical == self.is_vertical then self.items[index].factor = math.max(self.items[index].factor + df, 0.1) elseif self.parent then local pi = self.parent:get_child_id(self) self.parent:incfacror(pi, df, vertical) end end -- Recalculate geometry for every item in container ------------------------------------------------------------ function pack:rebuild() -- vars local geometries = {} local weight = 0 local area = awful.util.table.clone(self.wa) local direction = self.is_vertical and "height" or "width" -- check factor norming for _, item in ipairs(self.items) do if not item.child or item.child:is_filled() then weight = weight + item.factor end end if weight == 0 then return geometries end -- geomentry calculation for i, item in ipairs(self.items) do if not item.child or item.child:is_filled() then local size = self.wa[direction] / weight * item.factor local g = cut_geometry(area, self.is_vertical, size, i) if item.child then item.child:set_wa(g) else geometries[item.client] = g end end end return geometries end return pack end -- Build layout tree -------------------------------------------------------------------------------- local function construct_tree(wa, t) -- Initial structure on creation ------------------------------------------------------------ local tree = map.scheme[t] and map.scheme[t].construct(wa) or map.base_construct(wa) -- Find pack contaner for client ------------------------------------------------------------ function tree:get_pack(c) for _, pack in ipairs(self.set) do for i, item in ipairs(pack.items) do if not item.child and c == item.client then return pack, i end end end end -- Create new contaner in place of client ------------------------------------------------------------ function tree:create_group(c, is_vertical) local parent, index = self:get_pack(c) local new_pack = map.construct_itempack({}, {}, is_vertical, parent) self.set[#self.set + 1] = new_pack parent.items[index] = { child = new_pack, factor = 1 } self.active = #self.set awful.client.setslave(c) notify("New " .. (is_vertical and "vertical" or "horizontal") .. " group") end -- Insert new contaner in before active ------------------------------------------------------------ function tree:insert_group(is_vertical) local pack = self.set[self.active] local new_pack = map.construct_itempack({}, pack.wa, is_vertical, pack.parent) if pack.parent then for _, item in ipairs(pack.parent.items) do if item.child == pack then item.child = new_pack; break end end end new_pack.items[1] = { child = pack, factor = 1, client = nil } table.insert(self.set, self.active, new_pack) pack.parent = new_pack notify("New " .. (is_vertical and "vertical" or "horizontal") .. " group") end -- Destroy the given container ------------------------------------------------------------ function tree:delete_group(pack) pack = pack or self.set[self.active] local index = hasitem(self.set, pack) local has_child = pack:get_places() < #pack.items -- some containers can't be destroyed -- root container if #self.set == 1 then notify("Cant't destroy last group") return end -- container with many inheritors if has_child and #pack.items > 1 then notify("Cant't destroy group with inheritors") return end -- disconnect container from parent if pack.parent then for i, item in ipairs(pack.parent.items) do if item.child == pack then if has_child then -- container in container case -- inheritor can be transmit to parent without changing geometry item.child = pack.items[1].child else -- container without inheritors can be safaly destroyed table.remove(pack.parent.items, i) end break end end end -- destroy container table.remove(self.set, index) if not self.set[self.active] then self.active = #self.set end notify("Group " .. tostring(index) .. " destroyed") end -- Destroy all empty containers ------------------------------------------------------------ function tree:cleanup() for i = #self.set, 1, -1 do if #self.set[i].items == 0 then tree:delete_group(self.set[i]) elseif #self.set[i].items == 1 and self.set[i].items[1].child then self.set[i].items[1].child.wa = self.set[i].wa tree:delete_group(self.set[i]) end end end -- Recalculate geometry for whole layout ------------------------------------------------------------ function tree:rebuild(clist) local current = { unpack(clist) } local geometries = {} -- distributing clients among existing contaners for _, pack in ipairs(self.set) do local n = pack:get_places() local chunk = { unpack(current, 1, n) } current = { unpack(current, n + 1) } pack:set_cls(chunk) end -- distributing clients among existing contaners if #current > 0 then for _, c in ipairs(current) do if self.autoaim then self.active = self:aim() end local refill = awful.util.table.join(self.set[self.active]:get_cls(), { c }) self.set[self.active]:set_cls(refill) end -- local refill = awful.util.table.join(self.set[self.active]:get_cls(), current) -- self.set[self.active]:set_cls(refill) end -- recalculate geomery for every container in tree for _, pack in ipairs(self.set) do geometries = awful.util.table.join(geometries, pack:rebuild()) end return geometries end return tree end -- Layout manipulation functions ----------------------------------------------------------------------------------------------------------------------- -- Change container placement direction -------------------------------------------------------------------------------- function map.swap_group() local c = client.focus if not c then return end local t = c.screen.selected_tag local pack = map.data[t]:get_pack(c) pack.is_vertical = not pack.is_vertical t:emit_signal("property::layout") end -- Create new container for client -------------------------------------------------------------------------------- function map.new_group(is_vertical) local c = client.focus if not c then return end local t = c.screen.selected_tag map.data[t].autoaim = false map.data[t]:create_group(c, is_vertical) if hitimer then return end hitimer = timer({ timeout = map.hilight_timeout }) hitimer:connect_signal("timeout", function() redflat.service.navigator.hilight.show(map.data[t].set[map.data[t].active].wa) hitimer:stop() hitimer = nil end ) hitimer:start() -- autostart option doesn't work? end -- Destroy active container -------------------------------------------------------------------------------- function map.delete_group() local t = mouse.screen.selected_tag map.data[t].autoaim = false map.data[t]:delete_group() t:emit_signal("property::layout") end -- Check if client exist in layout tree -------------------------------------------------------------------------------- function map.check_client(c) if c.sticky then return true end for _, t in ipairs(c:tags()) do for k, _ in pairs(map.data) do if k == t then return true end end end end -- Remove client from layout tree and change tree structure -------------------------------------------------------------------------------- function map.clean_client(c) for t, _ in pairs(map.data) do local pack, index = map.data[t]:get_pack(c) if pack then table.remove(pack.items, index) end end end -- Destroy all empty containers -------------------------------------------------------------------------------- function map.clean_groups() local t = mouse.screen.selected_tag map.data[t].autoaim = false map.data[t]:cleanup() t:emit_signal("property::layout") end -- Set active container (new client will be allocated to this one) -------------------------------------------------------------------------------- function map.set_active(c) c = c or client.focus if not c then return end local t = c.screen.selected_tag local pack = map.data[t]:get_pack(c) if pack then map.data[t].autoaim = false map.data[t].active = hasitem(map.data[t].set, pack) redflat.service.navigator.hilight.show(pack.wa) notify("Active group index: " .. tostring(map.data[t].active)) end end -- Hilight active container (navigetor widget feature) -------------------------------------------------------------------------------- function map.hilight_active() local t = mouse.screen.selected_tag local pack = map.data[t].set[map.data[t].active] redflat.service.navigator.hilight.show(pack.wa) end -- Switch active container by index -------------------------------------------------------------------------------- function map.switch_active(n) local t = mouse.screen.selected_tag local na = map.data[t].active + n if map.data[t].set[na] then map.data[t].autoaim = false map.data[t].active = na --local pack = map.data[t].set[na] notify("Active group index: " .. tostring(na)) end redflat.service.navigator.hilight.show(map.data[t].set[map.data[t].active].wa) end -- Move client to active container -------------------------------------------------------------------------------- function map.move_to_active(c) c = c or client.focus if not c then return end local t = c.screen.selected_tag local pack, index = map.data[t]:get_pack(c) if pack then table.remove(pack.items, index) awful.client.setslave(c) end end -- Increase window size factor for client -------------------------------------------------------------------------------- function map.incfactor(c, df, is_vertical, on_group) c = c or client.focus if not c then return end local t = c.screen.selected_tag local pack, index = map.data[t]:get_pack(c) if not pack then return end -- fix this? if on_group and pack.parent then index = pack.parent:get_child_id(pack) pack = pack.parent end if pack then pack:incfacror(index, df, is_vertical) t:emit_signal("property::layout") end end -- Move element inside his container -------------------------------------------------------------------------------- function map.move_group(dn) local t = mouse.screen.selected_tag local pack = map.data[t].set[map.data[t].active] if pack.parent then map.data[t].autoaim = false local i = pack.parent:get_child_id(pack) if pack.parent.items[i + dn] then pack.parent.items[i], pack.parent.items[i + dn] = pack.parent.items[i + dn], pack.parent.items[i] t:emit_signal("property::layout") end end end -- Insert new group before active -------------------------------------------------------------------------------- function map.insert_group(is_vertical) local t = mouse.screen.selected_tag map.data[t].autoaim = false map.data[t]:insert_group(is_vertical) t:emit_signal("property::layout") end -- Reset layout structure -------------------------------------------------------------------------------- function map.reset_tree() local t = mouse.screen.selected_tag map.data[t] = nil t:emit_signal("property::layout") end -- Base layout scheme ----------------------------------------------------------------------------------------------------------------------- -- TODO: fix unused arg function map.base_set_new_pack(cls, wa, _, parent, factor) local pack = map.construct_itempack(cls, wa, true, parent) table.insert(parent.items, { child = pack, factor = factor or 1 }) return pack end map.base_autoaim = true function map.base_aim(tree) if #tree.set[2].items == 0 then return 2 end local active = #tree.set[3].items > #tree.set[2].items and 2 or 3 return active end function map.base_construct(wa) local tree = { set = {}, active = 1, autoaim = map.base_autoaim, aim = map.base_aim } tree.set[1] = map.construct_itempack({}, wa, false) tree.set[2] = map.base_set_new_pack({}, wa, true, tree.set[1]) tree.set[3] = map.base_set_new_pack({}, wa, true, tree.set[1]) return tree end -- Tile function ----------------------------------------------------------------------------------------------------------------------- function map.arrange(p) local wa = awful.util.table.clone(p.workarea) local cls = p.clients local data = map.data local t = p.tag or screen[p.screen].selected_tag -- nothing to tile here if #cls == 0 then return end -- init layout tree if not data[t] then data[t] = construct_tree(wa, t) end -- tile p.geometries = data[t]:rebuild(cls) end -- Keygrabber ----------------------------------------------------------------------------------------------------------------------- map.maingrabber = function(mod, key) for _, k in ipairs(map.keys.all) do if redutil.key.match_grabber(k, mod, key) then k[3](); return true end end end map.key_handler = function (mod, key, event) if event == "press" then return end if map.maingrabber(mod, key) then return end if common.grabbers.swap(mod, key, event) then return end if common.grabbers.base(mod, key, event) then return end end -- Redflat navigator support functions ----------------------------------------------------------------------------------------------------------------------- function map:set_keys(keys, layout) layout = layout or "all" if keys then self.keys[layout] = keys if layout ~= "all" then self.keys.all = awful.util.table.join(self.keys.layout, map.keys.resize) end end self.tip = awful.util.table.join(self.keys.all, common.keys.swap, common.keys.base, common.keys._fake) end function map.startup() if not map.tip then map:set_keys() end end -- End ----------------------------------------------------------------------------------------------------------------------- return map
TOOL.Category = "Marty's Tools" TOOL.Name = "Binder" TOOL.Information = { { name = "left" } } local boundNpcs = boundNpcs or {} -- if SERVER then -- util.AddNetworkString("BindNPC") -- end -- if CLIENT then -- net.Receive("BindNPC", function(length) -- local ent = net.ReadEntity() -- local ragdoll = net.ReadEntity() -- local add = net.ReadBool() -- if add then -- boundNpcs[ent] = ragdoll -- else -- boundNpcs[ent] = nil -- end -- end) -- end function TOOL:LeftClick(trace) if (IsValid(trace.Entity) && !trace.Entity:IsNPC()) then return false end if (!duplicator.IsAllowed(trace.Entity:GetClass())) then return false end if (CLIENT) then trace.Entity:SetIK(false) return true end print("start bind") local entity = trace.Entity local model = entity:GetModel() local ragdoll = ents.Create("prop_ragdoll") ragdoll:SetModel(model) ragdoll:SetPos(entity:GetPos()) print("create ragdoll") local originalColor = entity:GetColor() local originalMode = entity:GetRenderMode() entity:SetColor(Color(255, 255, 255, 0)) entity:SetRenderMode(RENDERMODE_TRANSCOLOR) entity:SetCollisionGroup(COLLISION_GROUP_DEBRIS) boundNpcs[entity] = ragdoll ragdoll:Spawn() local clean = {} print("Bone count", entity:GetBoneCount() - 1) for i = 0, ragdoll:GetPhysicsObjectCount() - 1 do local bone = ragdoll:GetPhysicsObjectNum( i ) if ( IsValid(bone) ) then local boneId = ragdoll:TranslatePhysBoneToBone( i ) local pos, ang = entity:GetBonePosition( boneId ) if ( pos ) then bone:SetPos( pos ) end if ( ang ) then bone:SetAngles( ang ) end -- local con, rope = constraint.Elastic( -- entity, -- ragdoll, -- boneId, -- boneId, -- pos - entity:GetPos(), -- bone:GetPos() - ragdoll:GetPos(), -- 500, -- 150, -- 1, -- "cable/cable", -- 0.5, -- 1, -- Color(255, 255, 255, 255) -- ) -- if con then -- table.insert(clean, rope) -- table.insert(clean, con) -- end end end print("successful constraints: ", #clean) undo.Create("prop") undo.AddEntity(ragdoll) for _, v in pairs(clean) do undo.AddEntity(v) end undo.SetPlayer(self:GetOwner()) undo.AddFunction(function() if (!IsValid(entity)) then return end boundNpcs[entity] = nil entity:SetColor(originalColor) entity:SetRenderMode(originalMode) for _, v in pairs(clean) do v:Remove() end end) undo.Finish("Bound entity") end function TOOL.BuildCPanel(CPanel) CPanel:AddControl("Header", { description = "Bind entities" }) CPanel:AddControl("Label", { text = "There are no controls currently" }) end hook.Add("Think", "MartyToolsBoundRagdolls", function() for npc, ragdoll in pairs(boundNpcs) do if (ragdoll == nil) then continue end for i = 0, ragdoll:GetPhysicsObjectCount() - 1 do local bone = ragdoll:GetPhysicsObjectNum( i ) if ( IsValid(bone) ) then bone:Wake() local boneId = ragdoll:TranslatePhysBoneToBone( i ) local pos, ang = npc:GetBonePosition( boneId ) -- if ( pos ) then bone:SetPos( pos ) end -- if ( ang ) then bone:SetAngles( ang ) end local diff = pos - bone:GetPos() local v = bone:GetVelocity() bone:SetVelocity(diff * 10 - (v * 0.5)) bone:ApplyForceCenter(diff * 20 * bone:GetMass()) bone:ApplyForceOffset(diff * 2, pos + ang:Forward() * 50) end end end end) hook.Add("OnNPCKilled", "MartyToolsBoundNpc", function(npc) if (boundNpcs[npc]) then boundNpcs[npc] = nil end end)
local S = technic.getter minetest.register_craft({ output = 'technic:wind_mill_frame 5', recipe = { {'technic:carbon_steel_ingot', '', 'technic:carbon_steel_ingot'}, {'', 'technic:carbon_steel_ingot', ''}, {'technic:carbon_steel_ingot', '', 'technic:carbon_steel_ingot'}, } }) minetest.register_craft({ output = 'technic:wind_mill', recipe = { {'', 'basic_materials:motor', ''}, {'technic:carbon_steel_ingot', 'technic:carbon_steel_block', 'technic:carbon_steel_ingot'}, {'', 'technic:mv_cable', ''}, } }) minetest.register_node("technic:wind_mill_frame", { description = S("Wind Mill Frame"), drawtype = "glasslike_framed", tiles = {"technic_carbon_steel_block.png", "default_glass.png"}, sunlight_propagates = true, groups = {cracky=3}, sounds = default.node_sound_stone_defaults(), paramtype = "light", }) local function check_wind_mill(pos) if pos.y < 30 then return false end pos = {x=pos.x, y=pos.y, z=pos.z} for i = 1, 20 do pos.y = pos.y - 1 local node = minetest.get_node_or_nil(pos) if not node then -- we reached CONTENT_IGNORE, we can assume, that nothing changed -- as the user will have to load the block to change it return end if node.name ~= "technic:wind_mill_frame" then return false end end return true end local run = function(pos, node) local meta = minetest.get_meta(pos) local machine_name = S("Wind %s Generator"):format("MV") local check = check_wind_mill(pos) if check == false then meta:set_int("MV_EU_supply", 0) meta:set_string("infotext", S("%s Improperly Placed"):format(machine_name)) elseif check == true then local power = math.min(pos.y * 100, 5000) meta:set_int("MV_EU_supply", power) meta:set_string("infotext", S("@1 (@2)", machine_name, technic.EU_string(power))) end -- check == nil: assume nothing has changed end minetest.register_node("technic:wind_mill", { description = S("Wind %s Generator"):format("MV"), tiles = {"technic_carbon_steel_block.png"}, paramtype2 = "facedir", groups = {cracky=1, technic_machine=1, technic_mv=1}, connect_sides = {"top", "bottom", "back", "left", "right"}, sounds = default.node_sound_stone_defaults(), drawtype = "nodebox", paramtype = "light", node_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5}, -- Main box {-0.1, -0.1, -0.5, 0.1, 0.1, -0.6}, -- Shaft {-0.1, -1, -0.6, 0.1, 1, -0.7}, -- Vertical blades {-1, -0.1, -0.6, 1, 0.1, -0.7}, -- Horizontal blades } }, on_construct = function(pos) local meta = minetest.get_meta(pos) meta:set_string("infotext", S("Wind %s Generator"):format("MV")) meta:set_int("MV_EU_supply", 0) end, technic_run = run, }) technic.register_machine("MV", "technic:wind_mill", technic.producer)
local M = {} local sched=require 'sched' local selector = require "tasks/selector" local nixio = require 'nixio' --executes s on the console and returns the output local run_shell = function (s) local f = io.popen(s) -- runs command local l = f:read("*a") -- read output of command f:close() return l end M.init = function(masks_to_watch) M.events = { file_add = {}, file_del = {}, } M.task = sched.run(function() require 'catalog'.get_catalog('tasks'):register(masks_to_watch, sched.running_task) if #run_shell('which inotifywait')==0 then error('inotifywait not available') end local paths_to_watch = {} for _, mask in ipairs(masks_to_watch) do --print('DDDDDDDDDDDDD+', mask) --string.match(mask, '^(.*%/)[^%/]*$') local dir = nixio.fs.dirname(mask) paths_to_watch[dir..'/']=true --print('DDDDDDDDDDDDD-', dir) end local command = 'inotifywait -q -c -m -e create,delete' for path, _ in pairs(paths_to_watch) do command = command..' '..path end --print('+++++++++INOTIFY:', command) local watcherfd=selector.grab_stdout (command, 'line', nil) local waitd_inotify={watcherfd.events.data} --generate events for already existing files for _, devmask in ipairs(masks_to_watch) do for devfile in nixio.fs.glob(devmask) do print('existing file', devfile) sched.schedule_signal(M.events.file_add, devfile, devmask) end end --monitor files while true do local _,line=sched.wait(waitd_inotify) if line then local path, action, file = string.match(line, '^([^,]+),(.+),([^,]+)$') local fullpath=path..file --print('INOTIFY', action, fullpath) if action=='CREATE' then for _, mask in ipairs(masks_to_watch) do for devfile in nixio.fs.glob(mask) do if devfile==fullpath then print('FILE+', fullpath, mask) sched.schedule_signal(M.events.file_add, fullpath, mask) end --print('confline starting', devfile, modulename) --local devmodule = require ('../drivers/filedev/'..modulename) --devmodule.init(devfile) end end elseif action=='DELETE' then print('FILE-', fullpath) sched.schedule_signal(M.events.file_del, fullpath) end end end end) end return M
local http = require "lib.http.http"; local _M = {}; -- 发起请求,lua_resty_http function _M.request(uri, options, timeout) local is_success, code, response_body, response_err, response_header; local httpc = http.new(); if (timeout == nil or timeout == ngx.null) then timeout = 10000; end httpc:set_timeout(timeout); local res, err = httpc:request_uri(uri, options); if res then if res.status == ngx.HTTP_OK then is_success = true; code = res.status; response_body = res.body; response_header = res.headers; else is_success = false; code = res.status; response_body = res.body; response_header = res.headers; end else is_success = false; code = -1; response_err = err; end return is_success, code, response_body, response_err, response_header; end --[[ capture方式模拟httpclient,只用于内部 需要在nginx配置文件中添加 location ~/_uagHttpclientProxy/(.*) { internal; proxy_pass http://wec-iap-auth/$1$is_args$args; } --]] function _M.capture(uri, options) local isSuccess, code, bodyResult, errResult; local err = ""; local res = ngx.location.capture("/_uagHttpclientProxy/" .. uri, options); if res then if res.status == ngx.HTTP_OK then isSuccess = true; code = res.status; bodyResult = res.body; else isSuccess = false; code = res.status; end else isSuccess = false; code = -1; errResult = err; end return isSuccess, code, bodyResult, errResult; end return _M;
-- optional wifi connection monitor -- prints messages when wifi fails or gets restored -- note wifi reconnection is normally an automatic & silent process. This lib prints advice. wifidiscon = 0 wifi.eventmon.register(wifi.eventmon.STA_CONNECTED , function(T) node.task.post(function () print("Wifi connect: ", T.SSID) end ) wifidiscon = 0 end ) wifi.eventmon.register(wifi.eventmon.STA_GOT_IP , function(T) node.task.post(function () print(T.IP) end ) end ) wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED , function(T) if wifidiscon ~= T.reason then node.task.post(function () print("Wifi disconnect: ", T.SSID, T.reason) end ) wifidiscon = T.reason end end ) -- the magic codes? -- http://nodemcu.readthedocs.io/en/dev/en/modules/wifi/#wifieventmon-module
pp(package.cpath) local uv = require('luv') local function create_server(host, port, on_connection) local server = uv.new_tcp() server:bind(host, port) server:listen(128, function(err) -- Make sure there was no problem setting up listen assert(not err, err) -- Accept the client local client = uv.new_tcp() server:accept(client) on_connection(client) end) return server end local server = create_server("0.0.0.0", 0, function (client) client:read_start(function (err, chunk) -- Crash on errors assert(not err, err) if chunk then -- Echo anything heard client:write(chunk) else -- When the stream ends, close the socket client:close() end end) end) print("TCP Echo server listening on port " .. server:getsockname().port) uv.run()
-- $Id: language.us.lua 18737 2010-06-04 17:09:02Z karl $ --[[ language.us.dat (and the start of language.dat.lua), used by: - a special luatex version of hyphen.cfg (derived from the babel system); - a special luatex version of etex.src (from the e-TeX distributon). See luatex-hyphen.pdf (currently part of the hyph-utf8 package) for details. DO NOT EDIT THIS FILE (language.dat.lua)! It is generated by tlmgr. See language.dat (or language.us) for more information. Warning: formats using this file also use one of language.dat or language.def. Update them accordingly. The interaction between these files is documented in luatex-hyphen.pdf, but here is a summary: - a language must be mentioned in language.dat or language.def to be available; if, in addition, it is: - not mentioned in language.dat.lua, then it is dumped in the format; - mentioned in language.dat.lua with a key special="disabled:<reason>", then it is not available at all; - mentioned in language.dat.lua with a normal entry, then it will not be dumped in the format, but loaded at runtime when activated. ]] return { ["english"]={ loader="hyphen.tex", special="language0", -- should be dumped in the format lefthyphenmin=2, righthyphenmin=3, synonyms={"usenglish","USenglish","american"}, }, -- dumylang and zerohyph are dumped in the format, -- since they contain either very few or no patterns at all -- END of language.us.lua (missing '}' appended after all entries)
CompositeEntities = { data = {} -- [""} = { -- base_entity = "", -- component_entities = -- { -- entity_name = "", -- offset = { x=0, y=0 }, -- operable=false, -- lable="train-stop-name" -- } -- } } -- global.composite_entities = { { type="name", entity_list = {} } } -- global.composite_entity_parent = { [entity] = parent_index } local function rotate_offset( offset, direction ) offset = Position.to_table( offset ) if direction == defines.direction.north then return { offset.x, offset.y } elseif direction == defines.direction.east then return { offset.y, -offset.x } elseif direction == defines.direction.south then return { -offset.x, -offset.y } elseif direction == defines.direction.west then return { -offset.y, offset.x } end return offset end CompositeEntities.register_composite = function( data ) setmetatable(data, {__index = CompositeEntities}) CompositeEntities.data[data.base_entity] = data end CompositeEntities.create_linked = function(entity) if not entity or not entity.valid then return end global.composite_entity_parent = global.composite_entity_parent or {} global.composite_entities = global.composite_entities or {} -- record base entity local _data = CompositeEntities.data[entity.name] if _data then local _new_global = { type = entity.name, entity_list = {} } local _new_global_index = (#global.composite_entities) + 1 local _surface = entity.surface local _position = entity.position local _direction = entity.direction local _force = entity.force if _data.keep_cluster == nil then _data.keep_cluster = true end if _data.destroy_origional == nil then _data.destroy_origional = true end if _data.destroy_origional then entity.destroy() elseif _data.keep_cluster then table.insert( _new_global.entity_list, entity ) global.composite_entity_parent[entity.unit_number] = _new_global_index end for _, _child in pairs(_data.component_entities) do local _child_name = _child.entity_name if type(_child_name) == "table" then _child_name = _child_name[math.random(1, #_child_name)] end local _offset = _child.offset and Position.to_table(_child.offset) or { x=0, y=0 } if _child.offset_area then _child.offset_area = Area.to_table(_child.offset_area) _offset.x = _offset.x + _child.offset_area.left_top.x + (math.random() * (_child.offset_area.right_bottom.x - _child.offset_area.left_top.x)) _offset.y = _offset.y + _child.offset_area.left_top.y + (math.random() * (_child.offset_area.right_bottom.y - _child.offset_area.left_top.y)) end local _new_direction = _direction if _child.direction then _new_direction = (_new_direction + _child.direction) % 8 end local _new_position = Tile.from_position( Position.add( _position, rotate_offset( _offset, _direction ) ) ) local _parameters = { name = _child_name, direction = _new_direction, position = _new_position, surface = _surface, force = _force } if _child.type then _parameters.type = _child.type end if _child.force then _parameters.force = game.forces[_child.force] end if _child.amount then _parameters.amount = _child.amount end if not _child.can_fail or _surface.can_place_entity(_parameters) then local _new_child = _surface.create_entity(_parameters) if _new_child then if _child.operable ~= nil then _new_child.operable = _child.operable end if _child.minable ~= nil then _new_child.minable = _child.minable end if _child.rotatable ~= nil then _new_child.rotatable = _child.rotatable end if _child.lable ~= nil and _new_child.supports_backer_name() then _new_child.backer_name = _child.lable end if _data.keep_cluster then table.insert( _new_global.entity_list, _new_child ) print(serpent.block(global.composite_entity_parent)) global.composite_entity_parent[_new_child.unit_number] = _new_global_index end game.raise_event(defines.events.on_built_entity, {created_entity=_new_child, player_index=1}) end end end if _data.keep_cluster then global.composite_entities[_new_global_index] = _new_global end return _new_global.entity_list end return { entity } end CompositeEntities.destroy_linked = function(entity) global.composite_entity_parent = global.composite_entity_parent or {} global.composite_entities = global.composite_entities or {} if not entity or not entity.valid then return end local _parent_index = global.composite_entity_parent[entity.unit_number] if not _parent_index then return end local _parent = global.composite_entities[_parent_index] if not _parent then return end for _, _entity in pairs(_parent.entity_list) do if _entity ~= entity then global.composite_entity_parent[_entity] = nil _entity.destroy() end end global.composite_entity_parent[entity] = nil global.composite_entities[_parent_index] = nil end -- event - on created Event.register({ defines.events.on_built_entity, defines.events.on_robot_built_entity, defines.events.on_trigger_created_entity }, function(event) if event.created_entity then CompositeEntities.create_linked( event.created_entity ) elseif event.entity then CompositeEntities.create_linked( event.entity ) end end) -- event - on destroyed/mined Event.register({ defines.events.on_preplayer_mined_item, defines.events.on_robot_pre_mined, defines.events.on_entity_died, }, function(event) CompositeEntities.destroy_linked( event.entity ) end)
local gct = require("gpioctrl") gct:Low(4) server_run = false function StartServer() --print("Start Http Server!") dofile('logicserver.lc') server_run = true gct:High(4) end wifi.ap.config({ ssid = 'NodeMCU', auth = wifi.WPA_WPA2_PSK,pwd="779686611" }); wifi.ap.setip({ip="1.8.8.1",netmask="255.255.255.0",gateway="1.8.8.1"}) wifi.setmode(wifi.STATIONAP) StartServer()
--[[ Copyright 2012 Rackspace 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 Emitter = require('core').Emitter local timer = require('timer') local consts = require('../util/constants') local misc = require('../util/misc') local logging = require('logging') local UpgradePollEmitter = Emitter:extend() function UpgradePollEmitter:initialize() self.stopped = nil self._options = {} self._options.exit_on_upgrade = virgo.exit_on_upgrade == 'true' self._options.restart_on_upgrade = virgo.restart_on_upgrade == 'true' end function UpgradePollEmitter:calcTimeout() return misc.calcJitter(consts.UPGRADE_INTERVAL, consts.UPGRADE_INTERVAL_JITTER) end function UpgradePollEmitter:_emit() process.nextTick(function() self:emit('upgrade', self.options) end) end function UpgradePollEmitter:forceUpgradeCheck(options) self._options = misc.merge(self._options, options) self:_emit() end function UpgradePollEmitter:_registerTimeout() if self.stopped then return end -- Check for upgrade local timeoutCallback timeoutCallback = function() self:_emit() self:_registerTimeout() end local timeout = self:calcTimeout() logging.debugf('Using Upgrade Timeout %ums', timeout) self._timer = timer.setTimeout(timeout, timeoutCallback) end function UpgradePollEmitter:start() self.stopped = nil if self._timer then return end -- On Startup check for upgrade self:_emit() self:_registerTimeout() end function UpgradePollEmitter:stop() if self._timer then timer.clearTimer(self._timer) end self.stopped = true end function UpgradePollEmitter:onSuccess() local reason if self._options.exit_on_upgrade then reason = consts.SHUTDOWN_UPGRADE elseif self._options.restart_on_upgrade then reason = consts.SHUTDOWN_RESTART end self:emit('shutdown', reason) end local exports = {} exports.UpgradePollEmitter = UpgradePollEmitter return exports
-- utils.lua local M = {} -- The module to export local cmd = vim.cmd -- helper function to create maps function M.map(mode, lhs, rhs, opts) local options = {noremap = true} if opts then options = vim.tbl_extend('force', options, opts) end vim.api.nvim_set_keymap(mode, lhs, rhs, options) end -- We will create a few autogroup, this function will help to avoid -- always writing cmd('augroup' .. group) etc.. function M.create_augroup(autocmds, name) cmd ('augroup ' .. name) cmd('autocmd!') for _, autocmd in ipairs(autocmds) do cmd('autocmd ' .. table.concat(autocmd, ' ')) end cmd('augroup END') end function M.test() print('test') end -- We want to be able to access utils in all our configuration files -- so we add the module to the _G global variable. _G.utils = M return M -- Export the module
local mg = require "moongen" local memory = require "memory" local device = require "device" local ts = require "timestamping" local stats = require "stats" local hist = require "histogram" local PKT_SIZE = 80 local ETH_DST = "11:12:13:14:15:16" local function getRstFile(...) local args = { ... } for i, v in ipairs(args) do result, count = string.gsub(v, "%-%-result%=", "") if (count == 1) then return i, result end end return nil, nil end function configure(parser) parser:description("Generates bidirectional CBR traffic with hardware rate control and measure latencies.") parser:argument("dev1", "Device to transmit/receive from."):convert(tonumber) parser:option("-r --rate", "Transmit rate in Mbit/s."):default(10000):convert(tonumber) parser:option("-f --file", "Filename of the latency histogram."):default("histogram.csv") end function master(args) local dev1 = device.config({port = args.dev1, rxQueues = 2, txQueues = 2}) device.waitForLinks() dev1:getTxQueue(0):setRate(args.rate) mg.startTask("loadSlave", dev1:getTxQueue(0)) stats.startStatsTask{dev1} mg.waitForTasks() end function loadSlave(queue) local mem = memory.createMemPool(function(buf) buf:getTestPacket():fill{} -- modify packet name here end) local bufs = mem:bufArray() while mg.running() do bufs:alloc(PKT_SIZE) queue:send(bufs) end end
local api = trinium.api local S = tinker.S local tool_station_formspec = [[ size[8,6.5] list[context;inputs;1,0;3,2;] list[context;output;6,0.5;1,1;] list[current_player;main;0,2.5;8,4;] listring[context;output] listring[current_player;main] listring[context;inputs] image[4.5,0.5;1,1;trinium_gui.arrow.png] ]] local function recalculate(pos) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() inv:set_stack("output", 1, "") table.walk(tinker.tools, function(v, k) local c, count = v.components, api.count_stacks(inv, "inputs", true) if count ~= #c then return end if not table.every(c, function(c1) return inv:contains_item("inputs", "tinker_phase:part_" .. c1.name) end) then return end local stack = ItemStack("tinker_phase:tool_" .. k) local meta2 = stack:get_meta() local durability, level, times, traits = 0, v.level_boost, {}, {} local color table.walk(c, function(c1) if c1.type == 1 then local x = inv:remove_item("inputs", "tinker_phase:part_" .. c1.name) inv:add_item("inputs", x) local data = x:get_meta():get_string("material_data"):data() durability = durability + data.base_durability if level < data.level then level = data.level end for k1, v1 in pairs(data.traits) do traits[k1] = math.max(traits[k1] or 0, v1) end table.insert(times, data.base_speed) color = data.color meta2:set_string("material_name", data.description) end end) level = level + v.level_boost table.walk(c, function(c1) if c1.type == 2 then local x = inv:remove_item("inputs", "tinker_phase:part_" .. c1.name) inv:add_item("inputs", x) local data = x:get_meta():get_string("material_data"):data() durability = durability * data.rod_durability for k1, v1 in pairs(data.traits) do traits[k1] = math.max(traits[k1] or 0, v1) end end end) if level < 0 then return end traits = table.filter(traits, function(_, k1) if tinker.modifiers[k1] and tinker.modifiers[k1].incompat then local x = tinker.modifiers[k1].incompat return table.every(x, function(v1) return not traits[v1] end) end return true end) times = math.geometrical_avg(times) local times2 = table.map(v.times, function(v1, k1) return { times = api.table_multiply(tinker.base[k1], v1 / times), uses = 0, maxlevel = level, } end) meta2:set_int("max_durability", durability * v.durability_mult) meta2:set_int("current_durability", durability * v.durability_mult) meta2:set_string("color", "#" .. color) meta2:set_tool_capabilities { full_punch_interval = 1.0, max_drop_level = level, groupcaps = times2, } meta2:set_int("modifiers_left", 3) meta2:set_string("modifiers", minetest.serialize(traits)) for k1, v1 in pairs(traits) do if tinker.modifiers[k1] and tinker.modifiers[k1].after_create then tinker.modifiers[k1].after_create(v1, meta2) end end meta2:set_string("description", v.update_description(stack)) inv:set_stack("output", 1, stack) end) end minetest.register_node("tinker_phase:tool_station", { description = S"Tool Station", tiles = {"tinker_phase.assembly_table.png", "tinker_phase.table_bottom.png", "tinker_phase.table_side.png"}, sounds = trinium.sounds.default_wood, drawtype = "nodebox", node_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.5, -0.25, 0.25, -0.25}, {0.5, -0.5, -0.5, 0.25, 0.25, -0.25}, {-0.5, -0.5, 0.5, -0.25, 0.25, 0.25}, {0.5, -0.5, 0.5, 0.25, 0.25, 0.25}, {-0.5, 0.25, -0.5, 0.5, 0.5, 0.5}, } }, groups = { choppy = 2 }, after_place_node = function(pos) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() api.initialize_inventory(inv, { inputs = 6, output = 1 }) meta:set_string("formspec", tool_station_formspec) end, allow_metadata_inventory_put = function(_, list_name, _, stack) return list_name == "inputs" and minetest.get_item_group(stack:get_name(), "_tinker_phase_part") ~= 0 and stack:get_count() or 0 end, allow_metadata_inventory_move = function(_, from_list, _, to_list, _, count) return from_list == "inputs" and to_list == "inputs" and count or 0 end, on_metadata_inventory_move = recalculate, on_metadata_inventory_put = recalculate, on_metadata_inventory_take = function(pos, list_name) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() if list_name == "output" then for i = 1, 6 do local stack = inv:get_stack("inputs", i) stack:take_item() inv:set_stack("inputs", i, stack) end end recalculate(pos) end, })
-- This uses -- The global awesome object -- the global screen class : https://awesomewm.org/doc/api/classes/screen.html -- the global client class : https://awesomewm.org/doc/api/classes/client.html -- luacheck: globals screen client awesome -- If LuaRocks is installed, make sure that packages installed through it are -- found (e.g. lgi). If LuaRocks is not installed, do nothing. pcall(require, "luarocks.loader") -- Standard awesome library local gears = require("gears") local awful = require("awful") local wibox = require("wibox") require("awful.autofocus") -- Theme handling library local beautiful = require("beautiful") -- Notification library local naughty = require("naughty") local menubar = require("menubar") -- Enable hotkeys help widget for VIM and other apps -- when client with a matching name is opened: require("awful.hotkeys_popup.keys") -- * Initialize -- Themes define colours, icons, font and wallpapers. -- awful.spawn.with_shell("xrdb -merge ~/.Xresources") beautiful.init(awful.util.getdir("config") .. "themes/gorgehousse/theme.lua") local helpers = require("helpers") local hostname = helpers.getHostname() or "Windows" local config = require("config") -- Change to 'require("keys-bepo")' to switch local keys = require("keys") -- Set globalkeys and desktop buttons do -- luacheck: globals root root.keys(keys.globalkeys) root.buttons(keys.desktopbuttons) end local titlebars = require("titlebars") -- * Add a titlebar if titlebars_enabled is set to true in the rules. client.connect_signal( "request::titlebars", function(c) -- ** buttons for the titlebar local buttons = titlebars.buttons awful.titlebar(c):setup { { -- ** Left awful.titlebar.widget.iconwidget(c), buttons = buttons, layout = wibox.layout.fixed.horizontal }, { -- ** Middle { -- *** Title align = "center", widget = awful.titlebar.widget.titlewidget(c) }, buttons = buttons, layout = wibox.layout.flex.horizontal }, { -- ** Right awful.titlebar.widget.floatingbutton(c), awful.titlebar.widget.maximizedbutton(c), awful.titlebar.widget.stickybutton(c), awful.titlebar.widget.ontopbutton(c), awful.titlebar.widget.closebutton(c), layout = wibox.layout.fixed.horizontal() }, layout = wibox.layout.align.horizontal } end ) local bar if hostname == "Kadabra" then bar = require("bar_themes.gorgehousse") else bar = require("bar_themes.aligatueur") end bar.setup_bar() -- * {{{ Error handling -- Check if awesome encountered an error during startup and fell back to -- _nother config (This code will only ever execute for the fallback config) if awesome.startup_errors then naughty.notify( { preset = naughty.config.presets.critical, title = "Oops, there were errors during startup!", text = awesome.startup_errors } ) end -- Handle runtime errors after startup do local in_error = false awesome.connect_signal( "debug::error", function(err) -- Make sure we don't go into an endless error loop if in_error then return end in_error = true naughty.notify( { preset = naughty.config.presets.critical, title = "Oops, an error happened!", text = tostring(err) } ) in_error = false end ) end -- }}} -- * {{{ Variable definitions -- Table of layouts to cover with awful.layout.inc, order matters. awful.layout.layouts = { awful.layout.suit.floating, awful.layout.suit.tile, awful.layout.suit.tile.left, awful.layout.suit.tile.bottom, awful.layout.suit.tile.top, awful.layout.suit.fair, awful.layout.suit.fair.horizontal, awful.layout.suit.spiral, awful.layout.suit.spiral.dwindle, awful.layout.suit.max, awful.layout.suit.max.fullscreen, awful.layout.suit.magnifier, awful.layout.suit.corner.nw -- awful.layout.suit.corner.ne, -- awful.layout.suit.corner.sw, -- awful.layout.suit.corner.se, } -- }}} -- * {{{ Menu -- ** Create a launcher widget and a main menu -- ** Menubar configuration -- local app_folders = config.app_folders menubar.utils.terminal = config.terminal -- Set the terminal for applications that require it -- }}} -- * Wallpaper local function set_wallpaper(s) -- Wallpaper if beautiful.wallpaper then local wallpaper = beautiful.wallpaper -- If wallpaper is a function, call it with the screen if type(wallpaper) == "function" then wallpaper = wallpaper(s) end gears.wallpaper.maximized(wallpaper, s, true) end end -- Re-set wallpaper when a screen's geometry changes (e.g. different resolution) screen.connect_signal("property::geometry", set_wallpaper) awful.screen.connect_for_each_screen( function(s) -- Wallpaper set_wallpaper(s) local names = {"main", "www", "term", "read", "office", "irc", "7", "8", "9"} local l = awful.layout.suit -- Just to save some typing: use an alias. local layouts = { l.tile, l.tile, l.tile, l.tile, l.tile, l.tile, l.tile, l.tile, l.floating } -- Each screen has its own tag table. awful.tag(names, s, layouts) end ) -- }}} -- * {{{ Rules -- Rules to apply to new clients (through the "manage" signal). awful.rules.rules = { -- ** All clients will match this rule. { rule = {}, properties = { border_width = beautiful.border_width, border_color = beautiful.border_normal, focus = awful.client.focus.filter, raise = true, keys = keys.clientkeys, buttons = keys.clientbuttons, screen = awful.screen.preferred, placement = awful.placement.no_overlap + awful.placement.no_offscreen } }, -- ** Floating clients. { rule_any = { instance = { "DTA", -- Firefox addon DownThemAll. "copyq", -- Includes session name in class. "pinentry" }, class = { "Arandr", "Blueman-manager", "Gpick", "Kruler", "MessageWin", -- kalarm. "KeePassXC", "Nextcloud", "Sxiv", "Tor Browser", -- Needs a fixed window size to avoid fingerprinting by screen size. "Wpa_gui", "veromix", "xtightvncviewer", "fst" }, -- Note that the name property shown in xprop might be set slightly after creation of the client -- and the name shown there might not match defined rules here. name = { "Event Tester" -- xev. }, role = { "AlarmWindow", -- Thunderbird's calendar. "ConfigManager", -- Thunderbird's about:config. "pop-up" -- e.g. Google Chrome's (detached) Developer Tools. } }, properties = {floating = true} }, -- ** Add titlebars to dialogs { rule_any = { type = {"dialog"} }, properties = {titlebars_enabled = true} }, -- ** Remove titlebars from normal clients { rule_any = { type = {"normal"} }, properties = {titlebars_enabled = false} } -- ** EXAMPLE Set Firefox to always map on the tag named "2" on screen 1. -- { rule = { class = "Firefox" }, -- properties = { screen = 1, tag = "2" } }, } -- }}} -- * {{{ Signals -- ** Signal function to execute when a new client appears. client.connect_signal( "manage", function(c) -- Set the windows at the slave, -- i.e. put it at the end of others instead of setting it master. if not awesome.startup then awful.client.setslave(c) end if awesome.startup and not c.size_hints.user_position and not c.size_hints.program_position then -- Prevent clients from being unreachable after screen count changes. awful.placement.no_offscreen(c) end end ) -- ** Enable sloppy focus, so that focus follows mouse. client.connect_signal( "mouse::enter", function(c) c:emit_signal("request::activate", "mouse_enter", {raise = false}) end ) client.connect_signal( "focus", function(c) c.border_color = beautiful.border_focus end ) client.connect_signal( "unfocus", function(c) c.border_color = beautiful.border_normal end ) -- }}} -- * {{{ Autostart awful.spawn.with_shell("~/.config/awesome/autostart.sh") -- }}}