content
stringlengths
5
1.05M
-- add modes: debug and release add_rules("mode.debug", "mode.release") -- define target target("${TARGETNAME}") -- set kind set_kind("shared") -- add include dirs add_includedirs("inc") -- generate relocatable device code for device linker of dependents. -- if __device__ or __global__ functions will be called cross file, -- or dynamic parallelism will be used, -- this instruction should be opted in. -- add_cuflags("-rdc=true") -- add files add_files("src/**.cu") -- generate SASS code for SM architecture of current host add_cugencodes("native") -- generate PTX code for the virtual architecture to guarantee compatibility add_cugencodes("compute_30") -- -- generate SASS code for each SM architecture -- add_cugencodes("sm_30", "sm_35", "sm_37", "sm_50", "sm_52", "sm_60", "sm_61", "sm_70", "sm_75") -- -- generate PTX code from the highest SM architecture to guarantee forward-compatibility -- add_cugencodes("compute_75") ${FAQ}
local mod = DBM:NewMod("d589", "DBM-Scenario-MoP") local L = mod:GetLocalizedStrings() mod:SetRevision(("$Revision: 2 $"):sub(12, -3)) mod:SetZone() mod:RegisterCombat("scenario", 1104) mod:RegisterEventsInCombat( "SPELL_AURA_APPLIED", "SPELL_AURA_REMOVED", "UNIT_DIED" ) mod.onlyNormal = true --Todo, Add some more resource gathering warnings/timers? Unfortunately none of those events got recorded by transcriptor. it appears they are all UNIT_AURA only :\ --Commander Scargash local warnBloodRage = mod:NewTargetAnnounce(134974, 3)--15 second target fixate --Commander Scargash local specWarnBloodrage = mod:NewSpecialWarningRun(134974) --Commander Scargash local timerBloodRage = mod:NewTargetTimer(15, 134974) local soundBloodRage = mod:NewSound(134974) mod:RemoveOption("HealthFrame") function mod:SPELL_AURA_APPLIED(args) if args.spellId == 134974 then warnBloodRage:Show(args.destName) timerBloodRage:Start(args.destName) if args:IsPlayer() then specWarnBloodrage:Show() soundBloodRage:Play() end end end function mod:SPELL_AURA_REMOVED(args) if args.spellId == 134974 then timerBloodRage:Cancel(args.destname) end end function mod:UNIT_DIED(args) local cid = self:GetCIDFromGUID(args.destGUID) if cid == 68474 then--Commander Scargash end end
#!/usr/bin/env lua local ui = require "tek.ui" ui.ThemeName = "dark tutorial" ui.UserStyles = false ui.Application:new { Children = { ui.Window:new { Index = 0, updateInterval = function(self) for i = 1, 10 do local n = math.random(1, 28) local e = self:getById("button"..n) e:setValue("Text", tostring(self.Index)) self.Index = self.Index + 1 if self.Index == 10000 then self.Application:quit() end end end, show = function(self) ui.Window.show(self) self.Window:addInputHandler(ui.MSG_INTERVAL, self, self.updateInterval) end, hide = function(self) ui.Window.hide(self) self.Window:remInputHandler(ui.MSG_INTERVAL, self, self.updateInterval) end, Width = "auto", HideOnEscape = true, Columns = 2, Children = { ui.Group:new { Legend = "outer1", Columns = 2, SameSize = true, Children = { ui.Button:new { Id = "button1", }, ui.Button:new { Id = "button2", }, ui.Button:new { Id = "button3", }, ui.Group:new { Columns = 2, SameSize = true, Legend = "inner1", Children = { ui.Button:new { Id = "button13", }, ui.Button:new { Id = "button14", }, ui.Button:new { Id = "button15", }, ui.Button:new { Id = "button16", } } } } }, ui.Group:new { Columns = 2, SameSize = true, Legend = "outer2", Children = { ui.Button:new { Id = "button4", }, ui.Button:new { Id = "button5", }, ui.Button:new { Id = "button6", }, ui.Group:new { Columns = 2, SameSize = true, Legend = "inner2", Children = { ui.Button:new { Id = "button17", }, ui.Button:new { Id = "button18", }, ui.Button:new { Id = "button19", }, ui.Button:new { Id = "button20", } } } } }, ui.Group:new { Columns = 2, SameSize = true, Legend = "outer3", Children = { ui.Button:new { Id = "button7", }, ui.Button:new { Id = "button8", }, ui.Button:new { Id = "button9", }, ui.Group:new { Columns = 2, SameSize = true, Legend = "inner3", Children = { ui.Button:new { Id = "button21", }, ui.Button:new { Id = "button22", }, ui.Button:new { Id = "button23", }, ui.Button:new { Id = "button24", } } } } }, ui.Group:new { Columns = 2, SameSize = true, Legend = "outer4", Children = { ui.Button:new { Id = "button10", }, ui.Button:new { Id = "button11", }, ui.Button:new { Id = "button12", }, ui.Group:new { Columns = 2, SameSize = true, Legend = "inner4", Children = { ui.Button:new { Id = "button25", }, ui.Button:new { Id = "button26", }, ui.Button:new { Id = "button27", }, ui.Button:new { Id = "button28", } } } } } } } } }:run()
local game = require 'game' return{ name = 'cloudbomb_horizontal', type = 'projectile', friction = 0.01 * game.step, width = 9, height = 9, frameWidth = 9, frameHeight = 9, handle_x = 5, handle_y = 5, solid = true, lift = game.gravity, playerCanPickUp = false, enemyCanPickUp = true, canPlayerStore = false, velocity = { x = 0, y = 0}, --initial vel isn't used since this is insantly picked up throwVelocityX = 350, throwVelocityY = 0, horizontalLimit = 300, stayOnScreen = false, damage = 10, idletime = 0, knockback = 450, throw_sound = 'acorn_bomb', animations = { default = {'once', {'1-10,1'}, 0.2}, thrown = {'loop', {'10-13,1'}, 0.2}, finish = {'once', {'1-9,1'}, 0.22}, }, collide = function(node, dt, mtv_x, mtv_y,projectile) --projectile.animation = projectile.finishAnimation if not node.isPlayer then return end if projectile.thrown then if projectile.direction == 'left' then node.velocity.x = -projectile.knockback else node.velocity.x = projectile.knockback end node:hurt(projectile.damage) projectile:die() end end, update = function(dt,projectile) projectile.thrown = true end, enter = function(dt,projectile) projectile.thrown = true end, leave = function(projectile) projectile:die() end, }
return function() local Container = script.Parent local App = Container.Parent local UIBlox = App.Parent local Packages = UIBlox.Parent local Roact = require(Packages.Roact) local mockStyleComponent = require(UIBlox.Utility.mockStyleComponent) local VerticalScrollView = require(Container.VerticalScrollView) describe("mount/unmount", function() it("should mount and unmount with default properties", function() local verticalScrollViewWithStyle = mockStyleComponent({ verticalScrollView = Roact.createElement(VerticalScrollView) }) local handle = Roact.mount(verticalScrollViewWithStyle) expect(handle).to.be.ok() Roact.unmount(handle) end) it("should mount and unmount with valid properties", function() local verticalScrollViewWithStyle = mockStyleComponent({ verticalScrollView = Roact.createElement(VerticalScrollView, { position = UDim2.new(0, 50, 0,100), size = UDim2.new(1, 30, 1, 50), canvasSizeY = UDim.new(2, 0), elasticBehavior = Enum.ElasticBehavior.Always, [Roact.Change.CanvasPosition] = function()end, [Roact.Change.CanvasSize] = function()end, [Roact.Ref] = Roact.createRef(), }) }) local handle = Roact.mount(verticalScrollViewWithStyle) expect(handle).to.be.ok() Roact.unmount(handle) end) it("should mount and unmount when gamepad focusable", function() local verticalScrollViewWithStyle = mockStyleComponent({ verticalScrollView = Roact.createElement(VerticalScrollView, { position = UDim2.new(0, 50, 0,100), size = UDim2.new(1, 30, 1, 50), canvasSizeY = UDim.new(2, 0), elasticBehavior = Enum.ElasticBehavior.Always, isGamepadFocusable = true, [Roact.Change.CanvasPosition] = function()end, [Roact.Change.CanvasSize] = function()end, [Roact.Ref] = Roact.createRef(), }) }) local handle = Roact.mount(verticalScrollViewWithStyle) expect(handle).to.be.ok() Roact.unmount(handle) end) it("mount should throw when created with invalid properties", function() local function expectToThrowForInvalidProps(props) local verticalScrollViewWithStyle = mockStyleComponent({ verticalScrollView = Roact.createElement(VerticalScrollView, props) }) expect(function() Roact.mount(verticalScrollViewWithStyle) end).to.throw() end expectToThrowForInvalidProps({ position = 3 }) expectToThrowForInvalidProps({ size = 3 }) expectToThrowForInvalidProps({ canvasSizeY = 3 }) expectToThrowForInvalidProps({ paddingHorizontal = 3 }) expectToThrowForInvalidProps({ NotInTheInterface = "Really it is not there" }) end) it("should accept and assign a ref", function() local ref = Roact.createRef() local element = mockStyleComponent({ verticalScrollView = Roact.createElement(VerticalScrollView, { [Roact.Ref] = ref }) }) local instance = Roact.mount(element) expect(ref.current).to.be.ok() expect(ref.current:IsA("Instance")).to.be.ok() Roact.unmount(instance) end) end) describe("margins", function() it("should have margins of X when explicitly passed X", function() local ref = Roact.createRef() local element = mockStyleComponent({ verticalScrollView = Roact.createElement(VerticalScrollView, { [Roact.Ref] = ref, paddingHorizontal = 42, }) }) local instance = Roact.mount(element) expect(ref.current.scrollingFrameInnerMargin.PaddingLeft.Offset).to.equal(42) local innerPaddingRight = ref.current.scrollingFrameInnerMargin.PaddingRight.Offset local outerPaddingRight = ref.current.Parent.scrollingFrameOuterMargins.PaddingRight.Offset expect(innerPaddingRight + outerPaddingRight).to.equal(42) Roact.unmount(instance) end) it("should have margins of 12 when small", function() local ref = Roact.createRef() local element = mockStyleComponent({ Roact.createElement("Frame", { Size = UDim2.fromOffset(100, 100), }, { verticalScrollView = Roact.createElement(VerticalScrollView, { [Roact.Ref] = ref, }) }) }) local instance = Roact.mount(element) expect(ref.current.scrollingFrameInnerMargin.PaddingLeft.Offset).to.equal(12) local innerPaddingRight = ref.current.scrollingFrameInnerMargin.PaddingRight.Offset local outerPaddingRight = ref.current.Parent.scrollingFrameOuterMargins.PaddingRight.Offset expect(innerPaddingRight + outerPaddingRight).to.equal(12) Roact.unmount(instance) end) it("should have margins of 24 when medium", function() local ref = Roact.createRef() local element = mockStyleComponent({ Roact.createElement("Frame", { Size = UDim2.fromOffset(500, 500), }, { verticalScrollView = Roact.createElement(VerticalScrollView, { [Roact.Ref] = ref, }) }) }) local instance = Roact.mount(element) expect(ref.current.scrollingFrameInnerMargin.PaddingLeft.Offset).to.equal(24) local innerPaddingRight = ref.current.scrollingFrameInnerMargin.PaddingRight.Offset local outerPaddingRight = ref.current.Parent.scrollingFrameOuterMargins.PaddingRight.Offset expect(innerPaddingRight + outerPaddingRight).to.equal(24) Roact.unmount(instance) end) it("should have margins of 48 when large", function() local ref = Roact.createRef() local element = mockStyleComponent({ Roact.createElement("Frame", { Size = UDim2.fromOffset(800, 800), }, { verticalScrollView = Roact.createElement(VerticalScrollView, { [Roact.Ref] = ref, }) }) }) local instance = Roact.mount(element) expect(ref.current.scrollingFrameInnerMargin.PaddingLeft.Offset).to.equal(48) local innerPaddingRight = ref.current.scrollingFrameInnerMargin.PaddingRight.Offset local outerPaddingRight = ref.current.Parent.scrollingFrameOuterMargins.PaddingRight.Offset expect(innerPaddingRight + outerPaddingRight).to.equal(48) Roact.unmount(instance) end) end) end
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end local function creatureSayCallback(cid, type, msg) if not npcHandler:isFocused(cid) then return false end local player = Player(cid) if(msgcontains(msg, "trouble") and player:getStorageValue(Storage.TheInquisition.WalterGuard) < 1 and player:getStorageValue(Storage.TheInquisition.Mission01) ~= -1) then npcHandler:say("I think there is a pickpocket in town.", cid) npcHandler.topic[cid] = 1 elseif(msgcontains(msg, "authorities")) then if(npcHandler.topic[cid] == 1) then npcHandler:say("Well, sooner or later we will get hold of that delinquent. That's for sure.", cid) npcHandler.topic[cid] = 2 end elseif(msgcontains(msg, "avoided")) then if(npcHandler.topic[cid] == 2) then npcHandler:say("You can't tell by a person's appearance who is a pickpocket and who isn't. You simply can't close the city gates for everyone.", cid) npcHandler.topic[cid] = 3 end elseif(msgcontains(msg, "gods allow")) then if(npcHandler.topic[cid] == 3) then npcHandler:say("If the gods had created the world a paradise, no one had to steal at all.", cid) npcHandler.topic[cid] = 0 if(player:getStorageValue(Storage.TheInquisition.WalterGuard) < 1) then player:setStorageValue(Storage.TheInquisition.WalterGuard, 1) player:setStorageValue(Storage.TheInquisition.Mission01, player:getStorageValue(Storage.TheInquisition.Mission01) + 1) -- The Inquisition Questlog- "Mission 1: Interrogation" player:getPosition():sendMagicEffect(CONST_ME_HOLYAREA) end end end return true end npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:addModule(FocusModule:new())
hook.Add("Initialize", "AttachmentVendorOverride", function() if (ATTACHMENT_VENDOR.override.enable != true) then return; end // CW2 if (istable(CustomizableWeaponry)) then ATTACHMENT_VENDOR.override.CWGiveAttachments = CustomizableWeaponry.giveAttachments; CustomizableWeaponry.giveAttachments = function(ply, tbl, noNotify) ply:giveWeaponAttachments(tbl, !noNotify); end; ATTACHMENT_VENDOR.override.CWRemoveAttachment = CustomizableWeaponry.removeAttachment; function CustomizableWeaponry.removeAttachment(cw, ply, att, noNetwork) ply:removeWeaponAttachments(att, !noNetwork); end; end local PlayerMeta = FindMetaTable("Player"); // CW2Mag if (ATTACHMENT_VENDOR.cw2Mags.enable) then ATTACHMENT_VENDOR.override.CW2AddMagazine = PlayerMeta.cwAddMagazine; PlayerMeta.cwAddMagazine = function(self, mag, amt, noNetwork) self:giveWeaponAttachments(mag, amt, !noNetwork); end; ATTACHMENT_VENDOR.override.CW2RemoveMagazine = PlayerMeta.cwRemoveMagazine; PlayerMeta.cwRemoveMagazine = PlayerMeta.removeWeaponAttachments; end // FAS2 if (istable(FAS2_Attachments)) then ATTACHMENT_VENDOR.override.FASPickupAttachment = PlayerMeta.FAS2_PickUpAttachment; PlayerMeta.FAS2_PickUpAttachment = function(self, att, noNotify) self:giveWeaponAttachments(att, !noNotify); end; ATTACHMENT_VENDOR.override.FASRemoveAttachment = PlayerMeta.FAS2_RemoveAttachment; PlayerMeta.FAS2_RemoveAttachment = PlayerMeta.removeWeaponAttachments; end end);
local AddonName, AddonTable = ... AddonTable.trade = { -- Meat/Fish 124117, 124119, 124120, 124121, 142336, -- General 136342, 124124, 151568, -- Misc 18365, }
local Command = {} Command.cmd = function(commands) for _, value in ipairs(commands) do vim.cmd(value) end end return Command
WireToolSetup.setCategory( "Vehicle Control", "Visuals" ) WireToolSetup.open( "cam", "Cam Controller", "gmod_wire_cameracontroller", nil, "Cam Controllers" ) if ( CLIENT ) then language.Add( "Tool.wire_cam.name", "Cam Controller Tool (Wire)" ) language.Add( "Tool.wire_cam.desc", "Spawns a constant Cam Controller prop for use with the wire system." ) language.Add( "Tool.wire_cam.parentlocal", "Coordinates local to parent" ) language.Add( "Tool.wire_cam.freemove", "Free movement" ) language.Add( "Tool.wire_cam.automove", "Client side movement" ) language.Add( "Tool.wire_cam.localmove", "Localized movement" ) language.Add( "Tool.wire_cam.allowzoom", "Client side zooming" ) language.Add( "Tool.wire_cam.autounclip", "Auto un-clip" ) language.Add( "Tool.wire_cam.autounclip_ignorewater", "Auto un-clip ignores water" ) language.Add( "Tool.wire_cam.drawplayer", "Draw player" ) language.Add( "Tool.wire_cam.drawparent", "Draw parent" ) language.Add( "Tool.wire_cam.smooth_amount", "Smooth speed (default: 18)" ) WireToolSetup.setToolMenuIcon( "icon16/camera.png" ) end WireToolSetup.BaseLang() WireToolSetup.SetupMax( 20 ) if SERVER then function TOOL:GetConVars() return self:GetClientNumber( "parentlocal" ), self:GetClientNumber( "automove" ), self:GetClientNumber( "freemove" ), self:GetClientNumber( "localmove" ), self:GetClientNumber( "allowzoom" ), self:GetClientNumber( "autounclip" ), self:GetClientNumber( "drawplayer" ), self:GetClientNumber( "autounclip_ignorewater" ), self:GetClientNumber( "drawparent" ) end end TOOL.ClientConVar[ "model" ] = "models/jaanus/wiretool/wiretool_siren.mdl" TOOL.ClientConVar[ "parentlocal" ] = "0" TOOL.ClientConVar[ "automove" ] = "0" TOOL.ClientConVar[ "freemove" ] = "0" TOOL.ClientConVar[ "localmove" ] = "0" TOOL.ClientConVar[ "allowzoom" ] = "0" TOOL.ClientConVar[ "autounclip" ] = "0" TOOL.ClientConVar[ "autounclip_ignorewater" ] = "0" TOOL.ClientConVar[ "drawplayer" ] = "1" TOOL.ClientConVar[ "drawparent" ] = "1" TOOL.ClientConVar[ "smooth_amount" ] = "18" WireToolSetup.SetupLinking(false, "pod") function TOOL.BuildCPanel(panel) WireDermaExts.ModelSelect(panel, "wire_cam_model", list.Get( "Wire_Misc_Tools_Models" ), 1) panel:CheckBox("#Tool.wire_cam.parentlocal", "wire_cam_parentlocal" ) panel:CheckBox("#Tool.wire_cam.automove", "wire_cam_automove" ) panel:Help( "Allow the player to rotate the camera using their mouse. When active, the position input becomes the center of the camera's orbit." ) panel:CheckBox("#Tool.wire_cam.freemove", "wire_cam_freemove" ) panel:Help( "Modifies mouse input to allow 360 degree rotation. The 'UnRoll' input can be toggled to match the parent entity's roll. (NOTE: only used if 'client side movement' is enabled)" ) panel:CheckBox("#Tool.wire_cam.localmove", "wire_cam_localmove" ) panel:Help( "Determines whether the client side movement is local to the parent or not (NOTE: only used if 'client side movement' is enabled)" ) panel:CheckBox("#Tool.wire_cam.allowzoom", "wire_cam_allowzoom" ) panel:Help( "Allow the player to move the camera in and out using the scroller on their mouse. The 'Distance' input is used as an offset for this. (NOTE: only used if 'client side movement' is enabled. NOTE: The cam controller's outputs might be wrong when this is enabled, because the server doesn't know how much they've zoomed - it only knows what the 'Distance' input is set to)." ) panel:CheckBox("#Tool.wire_cam.autounclip", "wire_cam_autounclip" ) panel:Help( "Automatically prevents the camera from clipping into walls by moving it closer to the parent entity (or cam controller if no parent is specified)." ) panel:CheckBox("#Tool.wire_cam.autounclip_ignorewater", "wire_cam_autounclip_ignorewater" ) panel:CheckBox("#Tool.wire_cam.drawplayer", "wire_cam_drawplayer" ) panel:Help( "Enable/disable the player being able to see themselves. Useful if you want to position the camera inside the player's head." ) panel:CheckBox("#Tool.wire_cam.drawparent", "wire_cam_drawparent" ) panel:Help( "Enable/disable the rendering of the parent entity. Useful if you want to position the camera inside the parent." ) panel:Help( "As you may have noticed, there are a lot of behaviours that change depending on which checkboxes are checked. For a detailed walk-through of everything, go to http://wiki.wiremod.com/wiki/Cam_Controller") panel:NumSlider( "#Tool.wire_cam.smooth_amount", "wire_cam_smooth_amount", 4, 30, 1 ) panel:Help( "Smooth speed is a client side setting, and is not saved on the cam controller entity. Changing it will immediately affect all cam controllers you use." ) end
local Collection = require(script.Collection) local PureCollection = require(script.PureCollection) local Registry = require(script.Registry) return { Collection = Collection, PureCollection = PureCollection, Registry = Registry, }
--[[ Copyright (c) 2018, Vsevolod Stakhov <vsevolod@highsecure.ru> Copyright (c) 2019, Carsten Rosenberg <c.rosenberg@heinlein-support.de> 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. ]]-- --[[[ -- @module lua_scanners_common -- This module contains common external scanners functions --]] local rspamd_logger = require "rspamd_logger" local rspamd_regexp = require "rspamd_regexp" local lua_util = require "lua_util" local lua_redis = require "lua_redis" local lua_magic_types = require "lua_magic/types" local fun = require "fun" local exports = {} local function log_clean(task, rule, msg) msg = msg or 'message or mime_part is clean' if rule.log_clean then rspamd_logger.infox(task, '%s: %s', rule.log_prefix, msg) else lua_util.debugm(rule.name, task, '%s: %s', rule.log_prefix, msg) end end local function match_patterns(default_sym, found, patterns, dyn_weight) if type(patterns) ~= 'table' then return default_sym, dyn_weight end if not patterns[1] then for sym, pat in pairs(patterns) do if pat:match(found) then return sym, '1' end end return default_sym, dyn_weight else for _, p in ipairs(patterns) do for sym, pat in pairs(p) do if pat:match(found) then return sym, '1' end end end return default_sym, dyn_weight end end local function yield_result(task, rule, vname, dyn_weight, is_fail, maybe_part) local all_whitelisted = true local patterns local symbol local threat_table local threat_info local flags if type(vname) == 'string' then threat_table = {vname} elseif type(vname) == 'table' then threat_table = vname end -- This should be more generic if not is_fail then patterns = rule.patterns symbol = rule.symbol threat_info = rule.detection_category .. 'found' if not dyn_weight then dyn_weight = 1.0 end elseif is_fail == 'fail' then patterns = rule.patterns_fail symbol = rule.symbol_fail threat_info = "FAILED with error" dyn_weight = 0.0 elseif is_fail == 'encrypted' then patterns = rule.patterns symbol = rule.symbol_encrypted threat_info = "Scan has returned that input was encrypted" dyn_weight = 1.0 elseif is_fail == 'macro' then patterns = rule.patterns symbol = rule.symbol_macro threat_info = "Scan has returned that input contains macros" dyn_weight = 1.0 end for _, tm in ipairs(threat_table) do local symname, symscore = match_patterns(symbol, tm, patterns, dyn_weight) if rule.whitelist and rule.whitelist:get_key(tm) then rspamd_logger.infox(task, '%s: "%s" is in whitelist', rule.log_prefix, tm) else all_whitelisted = false rspamd_logger.infox(task, '%s: result - %s: "%s - score: %s"', rule.log_prefix, threat_info, tm, symscore) if maybe_part and rule.show_attachments and maybe_part:get_filename() then local fname = maybe_part:get_filename() task:insert_result(symname, symscore, string.format("%s|%s", tm, fname)) else task:insert_result(symname, symscore, tm) end end end if rule.action and is_fail ~= 'fail' and not all_whitelisted then threat_table = table.concat(threat_table, '; ') if rule.action ~= 'reject' then flags = 'least' end task:set_pre_result(rule.action, lua_util.template(rule.message or 'Rejected', { SCANNER = rule.name, VIRUS = threat_table, }), rule.name, nil, nil, flags) end end local function message_not_too_large(task, content, rule) local max_size = tonumber(rule.max_size) if not max_size then return true end if #content > max_size then rspamd_logger.infox(task, "skip %s check as it is too large: %s (%s is allowed)", rule.log_prefix, #content, max_size) return false end return true end local function message_not_too_small(task, content, rule) local min_size = tonumber(rule.min_size) if not min_size then return true end if #content < min_size then rspamd_logger.infox(task, "skip %s check as it is too small: %s (%s is allowed)", rule.log_prefix, #content, min_size) return false end return true end local function message_min_words(task, rule) if rule.text_part_min_words then local text_parts_empty = false local text_parts = task:get_text_parts() local filter_func = function(p) return p:get_words_count() <= tonumber(rule.text_part_min_words) end fun.each(function(p) text_parts_empty = true rspamd_logger.infox(task, '%s: #words is less then text_part_min_words: %s', rule.log_prefix, rule.text_part_min_words) end, fun.filter(filter_func, text_parts)) return text_parts_empty else return true end end local function dynamic_scan(task, rule) if rule.dynamic_scan then if rule.action ~= 'reject' then local metric_result = task:get_metric_score('default') local metric_action = task:get_metric_action('default') local has_pre_result = task:has_pre_result() -- ToDo: needed? -- Sometimes leads to FPs --if rule.symbol_type == 'postfilter' and metric_action == 'reject' then -- rspamd_logger.infox(task, '%s: aborting: %s', rule.log_prefix, "result is already reject") -- return false --elseif metric_result[1] > metric_result[2]*2 then if metric_result[1] > metric_result[2]*2 then rspamd_logger.infox(task, '%s: aborting: %s', rule.log_prefix, 'score > 2 * reject_level: ' .. metric_result[1]) return false elseif has_pre_result and metric_action == 'reject' then rspamd_logger.infox(task, '%s: aborting: %s', rule.log_prefix, 'pre_result reject is set') return false else return true, 'undecided' end else return true, 'dynamic_scan is not possible with config `action=reject;`' end else return true end end local function need_check(task, content, rule, digest, fn, maybe_part) local uncached = true local key = digest local function redis_av_cb(err, data) if data and type(data) == 'string' then -- Cached data = lua_util.str_split(data, '\t') local threat_string = lua_util.str_split(data[1], '\v') local score = data[2] or rule.default_score if threat_string[1] ~= 'OK' then if threat_string[1] == 'MACRO' then yield_result(task, rule, 'File contains macros', 0.0, 'macro', maybe_part) elseif threat_string[1] == 'ENCRYPTED' then yield_result(task, rule, 'File is encrypted', 0.0, 'encrypted', maybe_part) else lua_util.debugm(rule.name, task, '%s: got cached threat result for %s: %s - score: %s', rule.log_prefix, key, threat_string[1], score) yield_result(task, rule, threat_string, score, false, maybe_part) end else lua_util.debugm(rule.name, task, '%s: got cached negative result for %s: %s', rule.log_prefix, key, threat_string[1]) end uncached = false else if err then rspamd_logger.errx(task, 'got error checking cache: %s', err) end end local f_message_not_too_large = message_not_too_large(task, content, rule) local f_message_not_too_small = message_not_too_small(task, content, rule) local f_message_min_words = message_min_words(task, rule) local f_dynamic_scan = dynamic_scan(task, rule) if uncached and f_message_not_too_large and f_message_not_too_small and f_message_min_words and f_dynamic_scan then fn() end end if rule.redis_params and not rule.no_cache then key = rule.prefix .. key if lua_redis.redis_make_request(task, rule.redis_params, -- connect params key, -- hash key false, -- is write redis_av_cb, --callback 'GET', -- command {key} -- arguments) ) then return true end end return false end local function save_cache(task, digest, rule, to_save, dyn_weight, maybe_part) local key = digest if not dyn_weight then dyn_weight = 1.0 end local function redis_set_cb(err) -- Do nothing if err then rspamd_logger.errx(task, 'failed to save %s cache for %s -> "%s": %s', rule.detection_category, to_save, key, err) else lua_util.debugm(rule.name, task, '%s: saved cached result for %s: %s - score %s - ttl %s', rule.log_prefix, key, to_save, dyn_weight, rule.cache_expire) end end if type(to_save) == 'table' then to_save = table.concat(to_save, '\v') end local value_tbl = {to_save, dyn_weight} if maybe_part and rule.show_attachments and maybe_part:get_filename() then local fname = maybe_part:get_filename() table.insert(value_tbl, fname) end local value = table.concat(value_tbl, '\t') if rule.redis_params and rule.prefix then key = rule.prefix .. key lua_redis.redis_make_request(task, rule.redis_params, -- connect params key, -- hash key true, -- is write redis_set_cb, --callback 'SETEX', -- command { key, rule.cache_expire or 0, value } ) end return false end local function create_regex_table(patterns) local regex_table = {} if patterns[1] then for i, p in ipairs(patterns) do if type(p) == 'table' then local new_set = {} for k, v in pairs(p) do new_set[k] = rspamd_regexp.create_cached(v) end regex_table[i] = new_set else regex_table[i] = {} end end else for k, v in pairs(patterns) do regex_table[k] = rspamd_regexp.create_cached(v) end end return regex_table end local function match_filter(task, rule, found, patterns, pat_type) if type(patterns) ~= 'table' or not found then return false end if not patterns[1] then for _, pat in pairs(patterns) do if pat_type == 'ext' and tostring(pat) == tostring(found) then return true elseif pat_type == 'regex' and pat:match(found) then return true end end return false else for _, p in ipairs(patterns) do for _, pat in ipairs(p) do if pat_type == 'ext' and tostring(pat) == tostring(found) then return true elseif pat_type == 'regex' and pat:match(found) then return true end end end return false end end -- borrowed from mime_types.lua -- ext is the last extension, LOWERCASED -- ext2 is the one before last extension LOWERCASED local function gen_extension(fname) local filename_parts = lua_util.str_split(fname, '.') local ext = {} for n = 1, 2 do ext[n] = #filename_parts > n and string.lower(filename_parts[#filename_parts + 1 - n]) or nil end return ext[1],ext[2],filename_parts end local function check_parts_match(task, rule) local filter_func = function(p) local mtype,msubtype = p:get_type() local detected_ext = p:get_detected_ext() local fname = p:get_filename() local ext, ext2 if rule.scan_all_mime_parts == false then -- check file extension and filename regex matching --lua_util.debugm(rule.name, task, '%s: filename: |%s|%s|', rule.log_prefix, fname) if fname ~= nil then ext,ext2 = gen_extension(fname) --lua_util.debugm(rule.name, task, '%s: extension, fname: |%s|%s|%s|', rule.log_prefix, ext, ext2, fname) if match_filter(task, rule, ext, rule.mime_parts_filter_ext, 'ext') or match_filter(task, rule, ext2, rule.mime_parts_filter_ext, 'ext') then lua_util.debugm(rule.name, task, '%s: extension matched: |%s|%s|', rule.log_prefix, ext, ext2) return true elseif match_filter(task, rule, fname, rule.mime_parts_filter_regex, 'regex') then lua_util.debugm(rule.name, task, '%s: filname regex matched', rule.log_prefix) return true end end -- check content type string regex matching if mtype ~= nil and msubtype ~= nil then local ct = string.format('%s/%s', mtype, msubtype):lower() if match_filter(task, rule, ct, rule.mime_parts_filter_regex, 'regex') then lua_util.debugm(rule.name, task, '%s: regex content-type: %s', rule.log_prefix, ct) return true end end -- check detected content type (libmagic) regex matching if detected_ext then local magic = lua_magic_types[detected_ext] or {} if match_filter(task, rule, detected_ext, rule.mime_parts_filter_ext, 'ext') then lua_util.debugm(rule.name, task, '%s: detected extension matched: |%s|', rule.log_prefix, detected_ext) return true elseif magic.ct and match_filter(task, rule, magic.ct, rule.mime_parts_filter_regex, 'regex') then lua_util.debugm(rule.name, task, '%s: regex detected libmagic content-type: %s', rule.log_prefix, magic.ct) return true end end -- check filenames in archives if p:is_archive() then local arch = p:get_archive() local filelist = arch:get_files_full(1000) for _,f in ipairs(filelist) do ext,ext2 = gen_extension(f.name) if match_filter(task, rule, ext, rule.mime_parts_filter_ext, 'ext') or match_filter(task, rule, ext2, rule.mime_parts_filter_ext, 'ext') then lua_util.debugm(rule.name, task, '%s: extension matched in archive: |%s|%s|', rule.log_prefix, ext, ext2) --lua_util.debugm(rule.name, task, '%s: extension matched in archive: %s', rule.log_prefix, ext) return true elseif match_filter(task, rule, f.name, rule.mime_parts_filter_regex, 'regex') then lua_util.debugm(rule.name, task, '%s: filename regex matched in archive', rule.log_prefix) return true end end end end -- check text_part has more words than text_part_min_words_check if rule.scan_text_mime and rule.text_part_min_words and p:is_text() and p:get_words_count() >= tonumber(rule.text_part_min_words) then return true end if rule.scan_image_mime and p:is_image() then return true end if rule.scan_all_mime_parts ~= false then if detected_ext then -- We know what to scan! local magic = lua_magic_types[detected_ext] or {} if p:is_attachment() or magic.av_check ~= false then return true end elseif p:is_attachment() then -- Just rely on attachment property return true end end return false end return fun.filter(filter_func, task:get_parts()) end local function check_metric_results(task, rule) if rule.action ~= 'reject' then local metric_result = task:get_metric_score('default') local metric_action = task:get_metric_action('default') local has_pre_result = task:has_pre_result() if rule.symbol_type == 'postfilter' and metric_action == 'reject' then return true, 'result is already reject' elseif metric_result[1] > metric_result[2]*2 then return true, 'score > 2 * reject_level: ' .. metric_result[1] elseif has_pre_result and metric_action == 'reject' then return true, 'pre_result reject is set' else return false, 'undecided' end else return false, 'dynamic_scan is not possible with config `action=reject;`' end end exports.log_clean = log_clean exports.yield_result = yield_result exports.match_patterns = match_patterns exports.condition_check_and_continue = need_check exports.save_cache = save_cache exports.create_regex_table = create_regex_table exports.check_parts_match = check_parts_match exports.check_metric_results = check_metric_results setmetatable(exports, { __call = function(t, override) for k, v in pairs(t) do if _G[k] ~= nil then local msg = 'function ' .. k .. ' already exists in global scope.' if override then _G[k] = v print('WARNING: ' .. msg .. ' Overwritten.') else print('NOTICE: ' .. msg .. ' Skipped.') end else _G[k] = v end end end, }) return exports
pg = pg or {} pg.enemy_data_statistics_52 = { [805200] = { cannon = 394, reload = 150, speed_growth = 0, cannon_growth = 0, rarity = 3, air = 0, torpedo = 742, dodge = 100, durability_growth = 0, antiaircraft = 235, luck = 0, reload_growth = 0, dodge_growth = 0, hit_growth = 0, star = 4, hit = 31, antisub_growth = 0, air_growth = 0, battle_unit_type = 95, base = 163, durability = 34652, armor_growth = 0, torpedo_growth = 0, luck_growth = 0, speed = 37, armor = 0, id = 805200, antiaircraft_growth = 0, antisub = 0, bound_bone = { cannon = { { 0.61, 0.49, 0 } }, vicegun = { { 0.61, 0.49, 0 } }, torpedo = { { 0.31, 0.17, 0 } }, antiaircraft = { { 0.61, 0.49, 0 } } }, smoke = { { 70, { { "smoke", { 0.23, 0.486, -0.481 } } } }, { 40, { { "smoke", { -0.56, 2.91, -0.14 } } } } }, equipment_list = { 100223, 100432, 317007, 317012, 318102 } }, [805300] = { cannon = 646, reload = 150, speed_growth = 0, cannon_growth = 0, rarity = 3, air = 0, torpedo = 891, dodge = 29, durability_growth = 0, antiaircraft = 290, luck = 0, reload_growth = 0, dodge_growth = 0, hit_growth = 0, star = 4, hit = 31, antisub_growth = 0, air_growth = 0, battle_unit_type = 95, base = 204, durability = 62820, armor_growth = 0, torpedo_growth = 0, luck_growth = 0, speed = 20, armor = 0, id = 805300, antiaircraft_growth = 0, antisub = 0, appear_fx = { "appearQ" }, equipment_list = { 100202, 100342, 100432, 318103, 100572 } }, [805400] = { cannon = 678, reload = 150, speed_growth = 0, cannon_growth = 0, pilot_ai_template_id = 20001, air = 0, rarity = 4, dodge = 36, torpedo = 955, durability_growth = 0, antiaircraft = 340, reload_growth = 0, dodge_growth = 0, hit_growth = 0, star = 5, hit = 32, antisub_growth = 0, air_growth = 0, battle_unit_type = 95, base = 209, durability = 62200, armor_growth = 0, torpedo_growth = 0, luck_growth = 0, speed = 22, luck = 0, id = 805400, antiaircraft_growth = 0, antisub = 0, armor = 0, bound_bone = { cannon = { { 0.088, 0.917, 0 } }, vicegun = { { 0.694, 0.853, 0 } }, torpedo = { { 0.088, 0.917, 0 } }, antiaircraft = { { 0.096, 3.156, 0 } } }, equipment_list = { 100203, 100432, 318104, 318108 } }, [9001] = { cannon = 35, armor = 0, battle_unit_type = 20, speed_growth = 0, pilot_ai_template_id = 20005, air = 0, speed = 15, dodge = 0, id = 9001, cannon_growth = 350, rarity = 1, reload_growth = 0, dodge_growth = 0, friendly_cld = 1, star = 2, hit = 14, antisub_growth = 0, air_growth = 0, reload = 150, base = 101, durability = 500, armor_growth = 0, torpedo_growth = 2800, luck_growth = 0, hit_growth = 160, luck = 0, torpedo = 65, durability_growth = 8260, antisub = 0, antiaircraft = 80, antiaircraft_growth = 920, appear_fx = { "appearQ" }, equipment_list = { 100218, 100427 } }, [9002] = { cannon = 42, reload = 150, speed_growth = 0, cannon_growth = 350, pilot_ai_template_id = 20005, air = 0, rarity = 1, dodge = 0, torpedo = 80, durability_growth = 8820, antiaircraft = 80, reload_growth = 0, dodge_growth = 0, hit_growth = 160, star = 2, hit = 14, antisub_growth = 0, air_growth = 0, battle_unit_type = 20, base = 105, durability = 560, armor_growth = 0, torpedo_growth = 3000, luck_growth = 0, speed = 15, luck = 0, id = 9002, antiaircraft_growth = 920, antisub = 0, armor = 0, appear_fx = { "appearsmall" }, equipment_list = { 100227, 100430 } }, [9003] = { cannon = 38, reload = 150, speed_growth = 0, cannon_growth = 350, pilot_ai_template_id = 20005, air = 0, rarity = 1, dodge = 0, torpedo = 72, durability_growth = 8520, antiaircraft = 80, reload_growth = 0, dodge_growth = 0, hit_growth = 160, star = 2, hit = 14, antisub_growth = 0, air_growth = 0, battle_unit_type = 20, base = 102, durability = 540, armor_growth = 0, torpedo_growth = 2800, luck_growth = 0, speed = 15, luck = 0, id = 9003, antiaircraft_growth = 920, antisub = 0, armor = 0, appear_fx = { "appearsmall" }, equipment_list = { 100218, 100427 } }, [9004] = { cannon = 40, reload = 150, speed_growth = 0, cannon_growth = 350, pilot_ai_template_id = 20005, air = 0, rarity = 1, dodge = 0, torpedo = 70, durability_growth = 8580, antiaircraft = 80, reload_growth = 0, dodge_growth = 0, hit_growth = 160, star = 2, hit = 14, antisub_growth = 0, air_growth = 0, battle_unit_type = 20, base = 103, durability = 545, armor_growth = 0, torpedo_growth = 2800, luck_growth = 0, speed = 15, luck = 0, id = 9004, antiaircraft_growth = 920, antisub = 0, armor = 0, appear_fx = { "appearsmall" }, equipment_list = { 100227, 100430 } }, [9005] = { cannon = 100, reload = 150, speed_growth = 0, cannon_growth = 626, pilot_ai_template_id = 10001, air = 0, rarity = 4, dodge = 18, torpedo = 240, durability_growth = 27000, antiaircraft = 105, reload_growth = 0, dodge_growth = 270, hit_growth = 210, star = 3, hit = 20, antisub_growth = 0, air_growth = 0, battle_unit_type = 60, base = 174, durability = 4000, armor_growth = 0, torpedo_growth = 5200, luck_growth = 0, speed = 36, luck = 0, id = 9005, antiaircraft_growth = 2200, antisub = 0, armor = 0, appear_fx = { "appearQ" }, equipment_list = { 318013, 318014, 318015, 318016 } }, [9006] = { cannon = 100, reload = 150, speed_growth = 0, cannon_growth = 626, pilot_ai_template_id = 10001, air = 0, rarity = 4, dodge = 18, torpedo = 240, durability_growth = 27000, antiaircraft = 105, reload_growth = 0, dodge_growth = 270, hit_growth = 210, star = 3, hit = 20, antisub_growth = 0, air_growth = 0, battle_unit_type = 60, base = 173, durability = 4000, armor_growth = 0, torpedo_growth = 5200, luck_growth = 0, speed = 36, luck = 0, id = 9006, antiaircraft_growth = 2200, antisub = 0, armor = 0, appear_fx = { "appearQ" }, equipment_list = { 318017, 318018, 318019 } }, [9007] = { cannon = 80, reload = 150, speed_growth = 0, cannon_growth = 576, pilot_ai_template_id = 10001, air = 0, rarity = 4, dodge = 18, torpedo = 180, durability_growth = 24000, antiaircraft = 105, reload_growth = 0, dodge_growth = 270, hit_growth = 210, star = 3, hit = 20, antisub_growth = 0, air_growth = 0, battle_unit_type = 60, base = 159, durability = 3800, armor_growth = 0, torpedo_growth = 5200, luck_growth = 0, speed = 36, luck = 0, id = 9007, antiaircraft_growth = 2200, antisub = 0, armor = 0, appear_fx = { "appearQ" }, equipment_list = { 318020, 318021, 318022 } }, [9008] = { cannon = 90, reload = 150, speed_growth = 0, cannon_growth = 576, pilot_ai_template_id = 10001, air = 0, rarity = 4, dodge = 18, torpedo = 220, durability_growth = 25000, antiaircraft = 105, reload_growth = 0, dodge_growth = 270, hit_growth = 210, star = 3, hit = 20, antisub_growth = 0, air_growth = 0, battle_unit_type = 60, base = 171, durability = 4000, armor_growth = 0, torpedo_growth = 5200, luck_growth = 0, speed = 36, luck = 0, id = 9008, antiaircraft_growth = 2200, antisub = 0, armor = 0, appear_fx = { "appearQ" }, equipment_list = { 318023, 318024, 318025, 318026 } }, [9009] = { cannon = 100, reload = 150, speed_growth = 0, cannon_growth = 626, pilot_ai_template_id = 10001, air = 0, rarity = 3, dodge = 18, torpedo = 240, durability_growth = 27000, antiaircraft = 105, reload_growth = 0, dodge_growth = 270, hit_growth = 210, star = 4, hit = 20, antisub_growth = 0, air_growth = 0, battle_unit_type = 50, base = 169, durability = 4400, armor_growth = 0, torpedo_growth = 5200, luck_growth = 0, speed = 36, luck = 0, id = 9009, antiaircraft_growth = 2200, antisub = 0, armor = 0, appear_fx = { "appearQ" }, equipment_list = { 318027, 318028 } }, [9010] = { cannon = 100, reload = 150, speed_growth = 0, cannon_growth = 626, pilot_ai_template_id = 10001, air = 0, rarity = 3, dodge = 18, torpedo = 240, durability_growth = 27000, antiaircraft = 105, reload_growth = 0, dodge_growth = 270, hit_growth = 210, star = 4, hit = 20, antisub_growth = 0, air_growth = 0, battle_unit_type = 50, base = 170, durability = 4400, armor_growth = 0, torpedo_growth = 5200, luck_growth = 0, speed = 36, luck = 0, id = 9010, antiaircraft_growth = 2200, antisub = 0, armor = 0, appear_fx = { "appearQ" }, equipment_list = { 318029, 318030 } }, [9011] = { cannon = 95, reload = 150, speed_growth = 0, cannon_growth = 616, pilot_ai_template_id = 10001, air = 0, rarity = 3, dodge = 18, torpedo = 230, durability_growth = 26000, antiaircraft = 105, reload_growth = 0, dodge_growth = 270, hit_growth = 210, star = 4, hit = 20, antisub_growth = 0, air_growth = 0, battle_unit_type = 50, base = 165, durability = 4500, armor_growth = 0, torpedo_growth = 5200, luck_growth = 0, speed = 36, luck = 0, id = 9011, antiaircraft_growth = 2200, antisub = 0, armor = 0, equipment_list = { 318031, 318032 } }, [9012] = { cannon = 95, reload = 150, speed_growth = 0, cannon_growth = 616, pilot_ai_template_id = 10001, air = 0, rarity = 3, dodge = 18, torpedo = 230, durability_growth = 26000, antiaircraft = 105, reload_growth = 0, dodge_growth = 270, hit_growth = 210, star = 4, hit = 20, antisub_growth = 0, air_growth = 0, battle_unit_type = 50, base = 166, durability = 4500, armor_growth = 0, torpedo_growth = 5200, luck_growth = 0, speed = 36, luck = 0, id = 9012, antiaircraft_growth = 2200, antisub = 0, armor = 0, appear_fx = { "appearQ" }, equipment_list = { 318033, 318034 } }, [9013] = { cannon = 95, reload = 150, speed_growth = 0, cannon_growth = 626, pilot_ai_template_id = 10001, air = 0, rarity = 3, dodge = 18, torpedo = 230, durability_growth = 29000, antiaircraft = 105, reload_growth = 0, dodge_growth = 270, hit_growth = 210, star = 4, hit = 20, antisub_growth = 0, air_growth = 0, battle_unit_type = 50, base = 175, durability = 4600, armor_growth = 0, torpedo_growth = 5200, luck_growth = 0, speed = 36, luck = 0, id = 9013, antiaircraft_growth = 2200, antisub = 0, armor = 0, appear_fx = { "appearQ" }, equipment_list = { 318035, 318036 } } } return
SetupExternalManagedProject("CppSharp.Parser.Gen")
--item-group if data.raw["item-group"]["bob-logistics"] then data.raw["item-group"]["bob-logistics"].icon = "__morebobs_shiny__/graphics/category/electronics-machine-chip.png" end if data.raw["item-group"]["bob-logistics"] then data.raw["item-group"]["bob-logistics"].icon_size = 128 end if data.raw["item-group"]["bob-gems"] then data.raw["item-group"]["bob-gems"].icon = "__morebobs_shiny__/graphics/category/gem.png" end if data.raw["item-group"]["bob-gems"] then data.raw["item-group"]["bob-gems"].icon_size = 128 end if data.raw["item-group"]["bob-resource-products"] then data.raw["item-group"]["bob-resource-products"].icon = "__base__/graphics/technology/advanced-material-processing.png" end if data.raw["item-group"]["bob-resource-products"] then data.raw["item-group"]["bob-resource-products"].icon_size = 128 end if data.raw["item-group"]["bob-fluid-products"] then data.raw["item-group"]["bob-fluid-products"].icon = "__base__/graphics/technology/advanced-chemistry.png" end if data.raw["item-group"]["bob-fluid-products"] then data.raw["item-group"]["bob-fluid-products"].icon_size = 128 end if data.raw["item-group"]["bob-intermediate-products"] then data.raw["item-group"]["bob-intermediate-products"].icon = "__morebobs_shiny__/graphics/category/advanced-electronics_old.png" end if data.raw["item-group"]["bob-intermediate-products"] then data.raw["item-group"]["bob-intermediate-products"].icon_size = 128 end if data.raw["item-group"]["bobmodules"] then data.raw["item-group"]["bobmodules"].icon = "__morebobs_shiny__/graphics/category/modules.png" end if data.raw["item-group"]["bobmodules"] then data.raw["item-group"]["bobmodules"].icon_size = 64 end if data.raw["item-group"]["void"] then data.raw["item-group"]["void"].icon = "__morebobs_shiny__/graphics/category/void.png" end if data.raw["item-group"]["void"] then data.raw["item-group"]["void"].icon_size = 128 end
local api = vim.api local luv = vim.loop local renderer = require'nvim-tree.renderer' local config = require'nvim-tree.config' local git = require'nvim-tree.git' local diagnostics = require'nvim-tree.diagnostics' local pops = require'nvim-tree.populate' local utils = require'nvim-tree.utils' local view = require'nvim-tree.view' local events = require'nvim-tree.events' local populate = pops.populate local refresh_entries = pops.refresh_entries local first_init_done = false local M = {} M.Tree = { entries = {}, cwd = nil, loaded = false, target_winid = nil, } function M.init(with_open, with_reload) M.Tree.entries = {} if not M.Tree.cwd then M.Tree.cwd = luv.cwd() end if config.use_git() then git.git_root(M.Tree.cwd) end populate(M.Tree.entries, M.Tree.cwd) local stat = luv.fs_stat(M.Tree.cwd) M.Tree.last_modified = stat.mtime.sec if with_open then M.open() elseif view.win_open() then M.refresh_tree() end if with_reload then renderer.draw(M.Tree, true) M.Tree.loaded = true end if not first_init_done then events._dispatch_ready() first_init_done = true end end function M.redraw() renderer.draw(M.Tree, true) end local function get_node_at_line(line) local index = view.View.hide_root_folder and 1 or 2 local function iter(entries) for _, node in ipairs(entries) do if index == line then return node end index = index + 1 if node.open == true then local child = iter(node.entries) if child ~= nil then return child end end end end return iter end local function get_line_from_node(node, find_parent) local node_path = node.absolute_path if find_parent then node_path = node.absolute_path:match("(.*)"..utils.path_separator) end local line = 2 local function iter(entries, recursive) for _, entry in ipairs(entries) do local n = M.get_last_group_node(entry) if node_path:match('^'..n.match_path..'$') ~= nil then return line, entry end line = line + 1 if entry.open == true and recursive then local _, child = iter(entry.entries, recursive) if child ~= nil then return line, child end end end end return iter end function M.get_node_at_cursor() local winnr = view.get_winnr() local hide_root_folder = view.View.hide_root_folder if not winnr then return end local cursor = api.nvim_win_get_cursor(view.get_winnr()) local line = cursor[1] if view.is_help_ui() then local help_lines = require'nvim-tree.renderer.help'.compute_lines() local help_text = get_node_at_line(line+1)(help_lines) return {name = help_text} else if line == 1 and M.Tree.cwd ~= "/" and not hide_root_folder then return { name = ".." } end if M.Tree.cwd == "/" then line = line + 1 end return get_node_at_line(line)(M.Tree.entries) end end -- If node is grouped, return the last node in the group. Otherwise, return the given node. function M.get_last_group_node(node) local next = node while next.group_next do next = next.group_next end return next end function M.unroll_dir(node) node.open = not node.open if node.has_children then node.has_children = false end if #node.entries > 0 then renderer.draw(M.Tree, true) else if config.use_git() then git.git_root(node.absolute_path) end populate(node.entries, node.link_to or node.absolute_path, node) renderer.draw(M.Tree, true) end diagnostics.update() end local function refresh_git(node) if not node then node = M.Tree end git.update_status(node.entries, node.absolute_path or node.cwd, node, false) for _, entry in pairs(node.entries) do if entry.entries and #entry.entries > 0 then refresh_git(entry) end end end -- TODO update only entries where directory has changed local function refresh_nodes(node) refresh_entries(node.entries, node.absolute_path or node.cwd, node) for _, entry in ipairs(node.entries) do if entry.entries and entry.open then refresh_nodes(entry) end end end -- this variable is used to bufferize the refresh actions -- so only one happens every second at most local refreshing = false function M.refresh_tree(disable_clock) if not M.Tree.cwd or (not disable_clock and refreshing) or vim.v.exiting ~= vim.NIL then return end refreshing = true refresh_nodes(M.Tree) local use_git = config.use_git() if use_git then vim.schedule(function() git.reload_roots() refresh_git(M.Tree) M.redraw() end) end vim.schedule(diagnostics.update) if view.win_open() then renderer.draw(M.Tree, true) else M.Tree.loaded = false end vim.defer_fn(function() refreshing = false end, vim.g.nvim_tree_refresh_wait or 1000) end function M.set_index_and_redraw(fname) local i local hide_root_folder = view.View.hide_root_folder if M.Tree.cwd == '/' or hide_root_folder then i = 0 else i = 1 end local reload = false local function iter(entries) for _, entry in ipairs(entries) do i = i + 1 if entry.absolute_path == fname then return i end if fname:match(entry.match_path..utils.path_separator) ~= nil then if #entry.entries == 0 then reload = true populate(entry.entries, entry.absolute_path, entry) end if entry.open == false then reload = true entry.open = true end if iter(entry.entries) ~= nil then return i end elseif entry.open == true then iter(entry.entries) end end end local index = iter(M.Tree.entries) if not view.win_open() then M.Tree.loaded = false return end renderer.draw(M.Tree, reload) if index then view.set_cursor({index, 0}) end end ---Get user to pick a window. Selectable windows are all windows in the current ---tabpage that aren't NvimTree. ---@return integer|nil -- If a valid window was picked, return its id. If an --- invalid window was picked / user canceled, return nil. If there are --- no selectable windows, return -1. function M.pick_window() local tabpage = api.nvim_get_current_tabpage() local win_ids = api.nvim_tabpage_list_wins(tabpage) local tree_winid = view.get_winnr(tabpage) local exclude = config.window_picker_exclude() local selectable = vim.tbl_filter(function (id) local bufid = api.nvim_win_get_buf(id) for option, v in pairs(exclude) do local ok, option_value = pcall(api.nvim_buf_get_option, bufid, option) if ok and vim.tbl_contains(v, option_value) then return false end end local win_config = api.nvim_win_get_config(id) return id ~= tree_winid and win_config.focusable and not win_config.external end, win_ids) -- If there are no selectable windows: return. If there's only 1, return it without picking. if #selectable == 0 then return -1 end if #selectable == 1 then return selectable[1] end local chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" if vim.g.nvim_tree_window_picker_chars then chars = tostring(vim.g.nvim_tree_window_picker_chars):upper() end local i = 1 local win_opts = {} local win_map = {} local laststatus = vim.o.laststatus vim.o.laststatus = 2 -- Setup UI for _, id in ipairs(selectable) do local char = chars:sub(i, i) local ok_status, statusline = pcall(api.nvim_win_get_option, id, "statusline") local ok_hl, winhl = pcall(api.nvim_win_get_option, id, "winhl") win_opts[id] = { statusline = ok_status and statusline or "", winhl = ok_hl and winhl or "" } win_map[char] = id api.nvim_win_set_option(id, "statusline", "%=" .. char .. "%=") api.nvim_win_set_option( id, "winhl", "StatusLine:NvimTreeWindowPicker,StatusLineNC:NvimTreeWindowPicker" ) i = i + 1 if i > #chars then break end end vim.cmd("redraw") print("Pick window: ") local _, resp = pcall(utils.get_user_input_char) resp = (resp or ""):upper() utils.clear_prompt() -- Restore window options for _, id in ipairs(selectable) do for opt, value in pairs(win_opts[id]) do api.nvim_win_set_option(id, opt, value) end end vim.o.laststatus = laststatus return win_map[resp] end function M.open_file(mode, filename) if mode == "tabnew" then M.open_file_in_tab(filename) return end local tabpage = api.nvim_get_current_tabpage() local win_ids = api.nvim_tabpage_list_wins(tabpage) local target_winid if vim.g.nvim_tree_disable_window_picker == 1 then target_winid = M.Tree.target_winid else target_winid = M.pick_window() end if target_winid == -1 then target_winid = M.Tree.target_winid elseif target_winid == nil then return end local do_split = mode == "split" or mode == "vsplit" local vertical = mode ~= "split" -- Check if filename is already open in a window local found = false for _, id in ipairs(win_ids) do if filename == api.nvim_buf_get_name(api.nvim_win_get_buf(id)) then if mode == "preview" then return end found = true api.nvim_set_current_win(id) break end end if not found then if not target_winid or not vim.tbl_contains(win_ids, target_winid) then -- Target is invalid, or window does not exist in current tabpage: create -- new window local window_opts = config.window_options() local splitside = view.is_vertical() and "vsp" or "sp" vim.cmd(window_opts.split_command .. " " .. splitside) target_winid = api.nvim_get_current_win() M.Tree.target_winid = target_winid -- No need to split, as we created a new window. do_split = false elseif not vim.o.hidden then -- If `hidden` is not enabled, check if buffer in target window is -- modified, and create new split if it is. local target_bufid = api.nvim_win_get_buf(target_winid) if api.nvim_buf_get_option(target_bufid, "modified") then do_split = true end end local cmd if do_split then cmd = string.format("%ssplit ", vertical and "vertical " or "") else cmd = "edit " end cmd = cmd .. vim.fn.fnameescape(filename) api.nvim_set_current_win(target_winid) vim.cmd(cmd) view.resize() end if mode == "preview" then view.focus() return end if vim.g.nvim_tree_quit_on_open == 1 then view.close() end renderer.draw(M.Tree, true) end function M.open_file_in_tab(filename) local close = vim.g.nvim_tree_quit_on_open == 1 if close then view.close() else -- Switch window first to ensure new window doesn't inherit settings from -- NvimTree if M.Tree.target_winid > 0 and api.nvim_win_is_valid(M.Tree.target_winid) then api.nvim_set_current_win(M.Tree.target_winid) else vim.cmd("wincmd p") end end -- This sequence of commands are here to ensure a number of things: the new -- buffer must be opened in the current tabpage first so that focus can be -- brought back to the tree if it wasn't quit_on_open. It also ensures that -- when we open the new tabpage with the file, its window doesn't inherit -- settings from NvimTree, as it was already loaded. vim.cmd("edit " .. vim.fn.fnameescape(filename)) local alt_bufid = vim.fn.bufnr("#") if alt_bufid ~= -1 then api.nvim_set_current_buf(alt_bufid) end if not close then vim.cmd("wincmd p") end vim.cmd("tabe " .. vim.fn.fnameescape(filename)) end function M.collapse_all() local function iter(nodes) for _, node in pairs(nodes) do if node.open then node.open = false end if node.entries then iter(node.entries) end end end iter(M.Tree.entries) M.redraw() end function M.change_dir(name) local foldername = name == '..' and vim.fn.fnamemodify(M.Tree.cwd, ':h') or name local no_cwd_change = vim.fn.expand(foldername) == M.Tree.cwd if no_cwd_change then return end vim.cmd('lcd '..vim.fn.fnameescape(foldername)) M.Tree.cwd = foldername M.init(false, true) end function M.set_target_win() local id = api.nvim_get_current_win() local tree_id = view.get_winnr() if tree_id and id == tree_id then M.Tree.target_winid = 0 return end M.Tree.target_winid = id end function M.open() M.set_target_win() local cwd = vim.fn.getcwd() view.open() local respect_buf_cwd = vim.g.nvim_tree_respect_buf_cwd or 0 if M.Tree.loaded and (respect_buf_cwd == 1 and cwd ~= M.Tree.cwd) then M.change_dir(cwd) end renderer.draw(M.Tree, not M.Tree.loaded) M.Tree.loaded = true end function M.sibling(node, direction) if not direction then return end local iter = get_line_from_node(node, true) local node_path = node.absolute_path local line = 0 local parent, _ -- Check if current node is already at root entries for index, entry in ipairs(M.Tree.entries) do if node_path:match('^'..entry.match_path..'$') ~= nil then line = index end end if line > 0 then parent = M.Tree else _, parent = iter(M.Tree.entries, true) if parent ~= nil and #parent.entries > 1 then line, _ = get_line_from_node(node)(parent.entries) end -- Ignore parent line count line = line - 1 end local index = line + direction if index < 1 then index = 1 elseif index > #parent.entries then index = #parent.entries end local target_node = parent.entries[index] line, _ = get_line_from_node(target_node)(M.Tree.entries, true) view.set_cursor({line, 0}) renderer.draw(M.Tree, true) end function M.close_node(node) M.parent_node(node, true) end function M.parent_node(node, should_close) if node.name == '..' then return end should_close = should_close or false local iter = get_line_from_node(node, true) if node.open == true and should_close then node.open = false else local line, parent = iter(M.Tree.entries, true) if parent == nil then line = 1 elseif should_close then parent.open = false end api.nvim_win_set_cursor(view.get_winnr(), {line, 0}) end renderer.draw(M.Tree, true) end function M.toggle_ignored() pops.config.filter_ignored = not pops.config.filter_ignored return M.refresh_tree() end function M.toggle_dotfiles() pops.config.filter_dotfiles = not pops.config.filter_dotfiles return M.refresh_tree() end function M.toggle_help() view.toggle_help() return M.redraw() end function M.dir_up(node) if not node or node.name == ".." then return M.change_dir('..') else local newdir = vim.fn.fnamemodify(M.Tree.cwd, ':h') M.change_dir(newdir) return M.set_index_and_redraw(node.absolute_path) end end return M
object_tangible_holiday_empire_day_remembrance_day_rebel_banner = object_tangible_holiday_empire_day_shared_remembrance_day_rebel_banner:new { } ObjectTemplates:addTemplate(object_tangible_holiday_empire_day_remembrance_day_rebel_banner, "object/tangible/holiday/empire_day/remembrance_day_rebel_banner.iff")
--[[ Snapper: to generate delta stats based on specific period. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Script template can be either Lua or JSON format, elements: Mandatory: sql: can be a SQL string, or an array that in Lua/Json format, refer to command 'grid' for more detail Optional: 1. group_by: Optional, the columns that used for groupping the aggregation(similar to SQL 'GROUP BY' list) The columns that not listed in both 'group_by' and 'delta_by' will only show the post result 2. delta_by: Optional, the columns that for aggregation(similar to SQL 'SUM(...)' list) 3. order_by: The columns that used to sort the final result, "-<column_name>" means desc ordering. 4. top_by : Optional, if not specified then it equals to 'group_by', it is the subset of 'group_by' columns 5. per_second: 'on' or 'off'(default), controls if to devide the delta stats by elapsed seconds 6. autohide: 'on' or 'off'(default),when a 'sql' is an array, and one of which returns no rows, then controls whether to show this sql 7. top_mode: 'on' or 'off'(default), controls whether to clear the screen before print the result 8. calc_rules: the additional formula on a specific column after the 'delta_by' columns is calculated 9. fixed_title: true or false(default), controls whether not to change the 'delta_by' column titles 10.include_zero: true or false(default), controls whether not to show the row in case of its 'delta_by' columns are all 0 11.set_ratio: true or false(default), controls whether not to add a percentage column on each 'delta_by' columns 12.before_sql: the statements that executed before the 1st snapshot 13.after_sql: the statements that executed after the 2nd snapshot 14:column_formatter: the column format of some fields. refer to command 'col' 15:variables: a map that describe the additional variables, refer to commands 'var' and 'def' 16:zero2null: replace zero value as empty string The belowing variables can be referenced by the SQLs in 'snapper': 1. :snap_cmd : The command that included by EOF 2. :snap_interval : The elapsed seconds betweens 2 snapshots --]] local env,pairs,ipairs,table,tonumber,pcall,type,loadstring=env,pairs,ipairs,table,tonumber,pcall,type,loadstring local sleep,math,cfg=env.sleep,env.math,env.set local console,getHeight=console,console.getScreenHeight local snapper=env.class(env.scripter) function snapper:ctor() self.command="snap" self.ext_name='snap' self.help_title='Calculate a period of db/session performance/waits. ' self.usage=[[<name1>[,<name2>...] { {<seconds>|BEGIN|END} [args] | [args] "<command to be snapped>"} [-top] [-sec] Options: -top: show result in top-style -sec: show delta stats based on per second, instead of the whole period Description: 1. calc the delta stats within a specific seconds: @@NAME <name1>[,<name2>...] $PROMPTCOLOR$<seconds>$NOR$ [args] 2. calc the delta stats for a specific series of commands: 1) @@NAME <name1>[,<name2>...] $PROMPTCOLOR$BEGIN$NOR$ [args] 2) <run other commands> 3) @@NAME <name1>[,<name2>...] $PROMPTCOLOR$END$NOR$ 3. calc the delta stats for a specific command: @@NAME <name1>[,<name2>...] [args] "<command to be snapped>" 4. calc the delta stats for a specific series of commands: @@NAME <name1>[,<name2>...] [args] $PROMPTCOLOR$<<EOF$NOR$ <run other commands> $HIY$EOF$NOR$ 5. calc the delta stats with repeat interval: @@NAME <name1>[,<name2>...] $PROMPTCOLOR$<seconds>+$NOR$ [args] @@NAME <name1>[,<name2>...] $PROMPTCOLOR$+$NOR$ [args] <"command"|EOF commands> Of which: $HEADCOLOR$<name1>[,<name2>...]$NOR$ is the snap commands listed below $HEADCOLOR$args$NOR$ is the parameter that required for the specific script $HEADCOLOR$EOF$NOR$ is the unix EOF style, the keyword is not limited to just 'EOF' ]] end function snapper:parse(name,txt,args,file) txt=env.var.update_text(txt,1,args) txt=table.totable(txt) local cmd={} for k,v in pairs(txt) do cmd[tostring(k):lower()]=v end cmd.name=name return cmd,args end function snapper:after_script() self.cmds,self.args=nil,nil self.db:close_cache('Internal_snapper') if self.top_mode==true then console:exitDisplay() env.printer.top_mode=false end if self.autosize then grid.col_auto_size=self.autosize end if self.var_context then env.var.import_context(table.unpack(self.var_context)) self.var_context=nil end if self.start_flag then self.start_flag,self.snap_cmd,self.is_repeat,self.is_first_top=false self:trigger('after_exec_action') self.db:commit() cfg.set("internal","back") cfg.set("feed","back") cfg.set("digits","back") cfg.set("sep4k",'back') end end function snapper:get_time() return self:trigger('get_db_time') or "unknown" end function snapper:build_data(sqls,args,variables) local clock,time = os.timer(),os.date('%Y-%m-%d %H:%M:%S') local rs,rsidx=nil,{} if type(variables)=="table" then for name,val in pairs(variables) do if val=='#REFCURSOR' or val=='#CURSOR' or not args[name] then args[name]=val end end end if type(sqls)=="string" then rs=self.db:grid_call({sqls},-1,args,"Internal_snapper") else rs=self.db:grid_call(sqls,-1,args,"Internal_snapper") end local grid_cost=self.db.grid_cost or (os.timer()-clock)/2 clock=clock+grid_cost local function scanrs(rs) for k,v in ipairs(rs) do if type(v)=="table" then if not rs[k]._is_result then scanrs(v) else rsidx[#rsidx+1]=v end end end end if type(variables)=="table" then for name,val in pairs(variables) do if (val=='#REFCURSOR' or val=='#CURSOR') and type(args[name])=="userdata" then rsidx[#rsidx+1]=self.db.resultset:rows(args[name],-1) end end end if type(rs)=="table" then scanrs(rs) rs.rsidx=rsidx end return rs,clock,time,os.timer()-clock end function snapper:run_sql(sql,main_args,cmds,files) local db,print_args=self.db self.autosize=cfg.get('colautosize','trim') self.var_context={env.var.backup_context()} local interval=main_args[1].V1 local args={} self.is_repeat=false local itv=interval:match("^(%d*)%+$") if itv then if itv=='' then itv='1' end interval,self.is_repeat=itv,tonumber(itv) end local snap_cmd if interval~="END" then for i=20,1,-1 do local pos="V"..i local str=main_args[1][pos] if str and str ~= db_core.NOT_ASSIGNED then if str:trim():find("%s") then local command=env.parse_args(2,str) if command and command[1] and env._CMDS[command[1]:upper()] then snap_cmd=str interval="BEGIN" end end break end end end self.snap_cmd=snap_cmd self.per_second,self.top_mode=nil for k,v in pairs(main_args) do if type(v)=="table" then local idx=0; args[k]={} for i=1,20 do local x="V"..i local y=tostring(v[x]):upper() if y=="-SEC" then self.per_second=true elseif y=="-TOP" then self.top_mode=true elseif not (v[x]==snap_cmd or i==1 and (tonumber(interval) or self.is_repeat or y=="END" or y=="BEGIN")) then idx=idx+1 args[k]["V"..idx]=v[x] end end for x,y in pairs(v) do if not tostring(x):find('^V%d+$') then args[k][x]=y end end else args[k]=v end end local begin_flag if interval then interval=interval:upper() if interval=="END" then if self.start_time then self.start_time=nil self:next_exec() end return elseif interval=="BEGIN" then self.start_time=os.clock() begin_flag=true end end env.checkerr(begin_flag~=nil or tonumber(interval),'Usage: '..self.command..' <names> <interval>|BEGIN|END [args] ') self.db:assert_connect() self.cmds,self.args={},{} self.start_flag=true cfg.set("feed","off") cfg.set("autocommit","off") cfg.set("digits",2) cfg.set("sep4k",'on') cfg.set("heading",'on') cfg.set("internal",'on') self:trigger('before_exec_action') local clock=os.timer() for idx,text in ipairs(sql) do local cmd,arg=self:parse(cmds[idx],sql[idx],args[idx],files[idx]) local per_second=(cmd.per_second~=nil and cmd.per_second) or self.per_second self.cmds[cmds[idx]],self.args[cmds[idx]]=cmd,arg arg.snap_cmd=(snap_cmd or ''):sub(1,2000) arg.snap_interval=tonumber(interval) or 0 arg.per_second=(per_second=='on' or per_second==true) and 1 or 0 cmd.per_second=arg.per_second==1 and true or false if cmd.before_sql then env.eval_line(cmd.before_sql,true,true) end cmd.begin_time=os.timer() cmd.rs2,cmd.clock,cmd.starttime,cmd.fetch_time2=self:build_data(cmd.sql,arg,cmd.variables) end self.db:commit() if snap_cmd then env.eval_line(snap_cmd,true,true) self:next_exec() elseif not begin_flag then local timer=interval+clock-os.timer() if timer>0 then sleep(timer) end self:next_exec() end end function snapper:next_exec() local cmds,args,db,clock=self.cmds,self.args,self.db,os.timer() --self:trigger('before_exec_action') for name,cmd in pairs(cmds) do self.db.grid_cost=nil args[name].snap_interval=clock - cmd.begin_time local rs,clock1,starttime,fetch_time1=self:build_data(cmd.sql,args[name],cmd.variables) cmd.begin_time=clock if type(cmd.rs2)=="table" and type(rs)=="table" then cmd.rs1,cmd.clock,cmd.endtime,cmd.elapsed,cmd.fetch_time1=rs,clock1,starttime,clock1-cmd.clock,fetch_time1 end if not self.is_repeat and cmd.after_sql then env.eval_line(cmd.after_sql,true,true) end end self.db:commit() local result,groups={} local define_column=env.var.define_column for name,cmd in pairs(cmds) do if cmd.rs1 and cmd.rs2 then local calc_clock,formatter=os.timer(),cmd.column_formatter or {} local defined_formatter,k1={} for k,v in pairs(formatter) do if k:find('%s') then k1=env.parse_args(99,k) else k1={'format',k} end define_column(v,table.unpack(k1)) local cols=v:split("%s*,+%s*") for _,col in ipairs(cols) do defined_formatter[col:upper()]=k1 end end for idx,_ in ipairs(cmd.rs1.rsidx) do local rs1,rs2=cmd.rs1.rsidx[idx],cmd.rs2.rsidx[idx] local agg_idx,grp_idx,top_grp_idx,agg_model_idx,found_top={},{},{},{} local title=rs2[1] local cols=#title local min_agg_pos,top_agg_idx,top_agg=1e4 local is_groupped=false local calc_cols={} local props={per_second=cmd.per_second} for k,v in pairs(cmd) do if type(k)=="string" then props[k]=v end end for k,v in pairs(rs2) do if type(k)=="string" then props[k]=v end end local calc_rules={} local order_by=props.order_by local elapsed=props.per_second and props.elapsed or 1 local zero2null=tostring(props.zero2null) props.group_by=props.group_by or props.grp_cols props.top_by=props.top_by or props.top_grp_cols props.delta_by=props.delta_by or props.agg_cols props.group_by=props.group_by and (','..table.concat(props.group_by:upper():split("%s*,+%s*"),',')..',') or nil props.top_by=props.top_by and (','..table.concat(props.top_by:upper():split("%s*,+%s*"),',')..',') props.delta_by=','..table.concat((props.delta_by and props.delta_by:upper() or ''):split("%s*,+%s*"),',')..',' if type(order_by)=="string" then order_by=(','..table.concat(order_by:upper():split("%s*,+%s*"),',')..','):gsub('%s*,[%s,]*',',') end for k,v in pairs(props.calc_rules or {}) do if type(k)=="string" then calc_rules[k:upper()]=v:gsub('%[([^%]]+)%]',function(col) return '['..col:upper()..']' end) end end for i,k in ipairs(title) do local tit=k:upper() local idx=props.delta_by:find(','..tit..',',1,true) if calc_rules[tit] then local v=calc_rules[tit] for i,x in ipairs(rs1[1]) do v=v:replace('['..x:upper()..']','\1'..i..'\2',true) end calc_cols[i]='return '..v end if idx then is_groupped=true if min_agg_pos> idx then min_agg_pos,top_agg=idx,i end agg_idx[i],title[i]=idx,props.fixed_title and k or elapsed~=1 and not props.topic and (k..'/s') or ('*'..k) local fmt = defined_formatter[title[i]] or defined_formatter[tit] if fmt then define_column(title[i],table.unpack(fmt)) end if type(order_by)=="string" then if order_by:find(',-'..tit..',',1,true) then order_by=order_by:replace(',-'..tit..',',',-'..i..',',true) end if order_by:find(','..tit..',',1,true) then order_by=order_by:replace(','..tit..',',','..i..',',true) end end else if not props.group_by or props.group_by:find(','..tit..',',1,true) then grp_idx[i]=true end if props.top_by and props.top_by:find(','..tit..',',1,true) then found_top=true top_grp_idx[i]=true end end end if type(order_by)=="string" then order_by=order_by:trim(',') end if not found_top then top_grp_idx=grp_idx end result,groups=table.new(1,#rs1+10),{} local autosize1,autosize2=props.autosize,grid.col_auto_size if autosize1 then grid.col_auto_size=autosize1 end local grid=grid.new(true) local idx,top_idx,counter={},{},0 local function make_index(row) counter=0 for k,_ in pairs(top_grp_idx) do counter=counter+1 top_idx[counter]=row[k] or "" end counter=0 for k,_ in pairs(grp_idx) do counter=counter+1 idx[counter]=row[k] or "" end return table.concat(idx,'\1\2\1'),table.concat(top_idx,'\1\2\1') end local top_data,r,d,data,index,top_index=table.new(1,#rs1+10) props.max_rows=props.height==0 and 300 or props.max_rows or cfg.get(self.command.."rows") if not is_groupped then grid=rs1 if order_by and grid.sort then grid.sort(grid,order_by) end else local sum=0 local function check_zero(col,num,row) if num==0 and (zero2null=='on' or zero2null=='true') then row[col]='' end if props.include_zero then sum=1 return elseif calc_cols[col] or sum==1 then return end sum=(num and math.round(num,3)~=0) and 1 or 0 end grid:add(title) for rx=2,#rs1 do local row=table.new(cols,0) for ix=1,cols do row[ix]=rs1[rx][ix] end index,top_index=make_index(row) data=result[index] if not top_data[top_index] then top_data[top_index]={} groups[#groups+1]=top_index end sum=0 if not data then result[index],top_data[top_index][#top_data[top_index]+1]=row,row for k,_ in pairs(agg_idx) do local d=tonumber(row[k]) row[k]=d and math.round(d/elapsed,2) or nil check_zero(k,d,row) end else for k,_ in pairs(agg_idx) do r,d=tonumber(row[k]),tonumber(data[k]) if r or d then data[k]=math.round((d or 0)+(r or 0)/elapsed,2) check_zero(k,data[k],data) end end end result[index]['_non_zero_']=sum>0 end for rx=2,#rs2 do local row=rs2[rx] index=make_index(row) data=result[index] if data then sum=0 for k,_ in pairs(agg_idx) do r,d=tonumber(row[k]),tonumber(data[k]) if r and d then data[k]=math.round(d-r/elapsed,2) check_zero(k,data[k],data) end end result[index]['_non_zero_']=sum>0 end end if #groups>0 then local func=function(a,b) return a[top_agg_idx]>b[top_agg_idx] end for index,group_name in ipairs(groups) do if #top_data[group_name]>1 and top_agg_idx then table.sort(top_data[group_name],func) end if top_data[group_name][1]['_non_zero_'] then local row=top_data[group_name][1] for k,v in pairs(calc_cols) do for i,x in ipairs(rs1[1]) do v=v:gsub('\1'..i..'\2',row[i]==nil and '0' or tostring(row[i])) end v=loadstring(v) if v then local done,rtn=pcall(v) if done then row[k]=(rtn~=rtn or rtn==nil or rtn==1/0 or rtn==-1/0 ) and '' or type(rtn)=="number" and math.round(rtn,2) or rtn check_zero(k,row[k],row) end end end grid:add(row) end end idx='' for i,_ in pairs(agg_idx) do idx=idx..(-i)..',' if props.set_ratio=='on' then grid:add_calc_ratio(i) end end grid:sort(order_by or idx,true) end end if autosize1 then grid.col_auto_size=autosize2 end setmetatable(rs2,nil) table.clear(rs2) for k,v in pairs(props) do rs2[k]=v end for k,v in pairs(grid) do rs2[k]=v end setmetatable(rs2,getmetatable(grid)) end local per_second=cmd.per_second and '(per Second)' or '' local top_mode=cmd.top_mode~=nil and cmd.top_mode or self.top_mode local cost=string.format('(SQL:%.2f Calc:%.2f)',cmd.fetch_time1+cmd.fetch_time2,os.timer()-calc_clock) local title=string.format('\n$REV$[%s#%s%s]: From %s to %s%s:$NOR$',self.command,name,per_second,cmd.starttime,cmd.endtime, env.set.get("debug")~="SNAPPER" and '' or cost) if top_mode then env.printer.top_mode=true if not self.is_first_top then reader:clearScreen() if #cmd.rs2.rsidx~=1 then console:initDisplay() end self.is_first_top=true; end end if #cmd.rs2.rsidx==1 then if top_mode then reader:clearScreen() end print(title..'\n') env.grid.print(cmd.rs2.rsidx[1],nil,nil,nil,cmd.max_rows and cmd.max_rows+2 or cfg.get(self.command.."rows")) else if top_mode then cmd.rs2.max_rows=getHeight(console)-3 end env.grid.merge(cmd.rs2,true,title:trim()) end env.var.import_context(table.unpack(self.var_context)) end end if self.is_repeat then for name,cmd in pairs(cmds) do cmd.rs2,cmd.rs1,cmd.starttime,cmd.fetch_time2=cmd.rs1,nil,cmd.endtime,cmd.fetch_time1 --print(args[name].snap_interval) end if self.snap_cmd then env.eval_line(self.snap_cmd,true,true) else local timer=self.is_repeat+clock-os.timer()-0.1 if timer>0 then sleep(timer) end end return self:next_exec() end self:trigger('after_exec_action') end function snapper:__onload() cfg.init(self.command.."rows","50",nil,"db.core","Number of max records for the '"..self.command.."' command result","5 - 3000") end snapper.finalize='N/A' return snapper
--region BaseView.lua --Date 2019/03/30 --Author NormanYang --View 层基类 --endregion local setmetatable = setmetatable local wait = coroutine.wait BaseView = {} local this = BaseView; this.__index = this; --创建View对象-- function BaseView:New(bundleName, atlasName) return setmetatable({bundleName = bundleName, atlasName = atlasName, isShow = false, isLoaded = false}, this); end --显示View对象 function BaseView:Show(args) self.args = args; logWarn("Show Object:--->>" .. self.bundleName); UIManager:ShowUI(self.bundleName); self.isLoaded = true; self.isShow = true; end --隐藏View对象 function BaseView:Hide() logWarn("Hide Object:--->>" .. self.bundleName); UIManager:HideUI(self.bundleName); self.isShow = false; end --销毁View对象 function BaseView:Close() logWarn("Destroy Object:--->>" .. self.bundleName); UIManager:CloseUI(self.bundleName); self.isLoaded = false; end --获取界面Atlas function BaseView:SetAtlas(func) local GetLoader = BaseLoad.GetLoader; self.viewAtlas = GetLoader(self.atlasName); if (not self.viewAtlas) then wait(0.1); self.viewAtlas = GetLoader(self.atlasName); end if (func) then spawn(func) end; return self.viewAtlas; end --释放View对象 function BaseView:Destroy() setmetatable(self, {}); end --发送通知-- function BaseView.SendNotification(notifyName, ...) Facade.SendNotification(notifyName, ...); end --显示弹出框 function ShowMsgBox(content, confirm, cancel) this.SendNotification(NotifyName.ShowUI, MsgBox, content, confirm, cancel); end --显示弹出tips function ShowMsgTips(content) this.SendNotification(NotifyName.ShowUI, MsgTips, content); end return this
jilljoo_jab_missions = { { missionType = "escort", primarySpawns = { { npcTemplate = "jilljoo_slave", npcName = "Sadelli" } }, secondarySpawns = { { npcTemplate = "thug", npcName = "a Thug" }, { npcTemplate = "thug", npcName = "a Thug" }, }, itemSpawns = {}, rewards = { { rewardType = "credits", amount = 1000 }, } }, { missionType = "escort", primarySpawns = { { npcTemplate = "jilljoo_slave", npcName = "Soolami" } }, secondarySpawns = { { npcTemplate = "thug", npcName = "a Thug" }, { npcTemplate = "slaver", npcName = "a Slaver" }, }, itemSpawns = {}, rewards = { { rewardType = "credits", amount = 2000 }, } }, { missionType = "assassinate", primarySpawns = { { npcTemplate = "woff_btar", npcName = "Woff B'tar" } }, secondarySpawns = { { npcTemplate = "jabba_thug", npcName = "a Jabba Thug" }, { npcTemplate = "jabba_thug", npcName = "a Jabba Thug" }, }, itemSpawns = {}, rewards = { { rewardType = "credits", amount = 4000 }, } }, } npcMapJilljooJab = { { spawnData = { npcTemplate = "jilljoo_jab", x = 10.58, z = -0.89, y = -3.56, direction = 237.7, cellID = 1256058, position = STAND }, worldPosition = { x = -3001, y = 2161 }, npcNumber = 1, stfFile = "@static_npc/tatooine/jilljoo_jab", missions = jilljoo_jab_missions }, } JilljooJab = ThemeParkLogic:new { npcMap = npcMapJilljooJab, className = "JilljooJab", screenPlayState = "jilljoo_jab_quest", planetName = "tatooine", distance = 800 } registerScreenPlay("JilljooJab", true) jilljoo_jab_mission_giver_conv_handler = mission_giver_conv_handler:new { themePark = JilljooJab } jilljoo_jab_mission_target_conv_handler = mission_target_conv_handler:new { themePark = JilljooJab }
function _G.q(...) local objects = vim.tbl_map(vim.inspect, {...}) print(unpack(objects)) return ... end vim.cmd[[command! -nargs=1 -complete=lua Q lua q(<args>)]] function _G.t(str) return vim.api.nvim_replace_termcodes(str, true, true, true) end --- Jump to the next entry in the jumplist which is a child of the current working directory. function _G.jump_to_last_in_project() local cwd = vim.fn.getcwd() local jumplist, current = unpack(vim.fn.getjumplist()) for position = current - 1, 1, -1 do local jump = jumplist[position] local path = vim.api.nvim_buf_get_name(jump.bufnr) if vim.startswith(path, cwd) then return vim.api.nvim_win_set_buf(0, jump.bufnr) end end end --- Jump to the last entry in the jumplist which is a child of the current working directory. function _G.jump_to_next_in_project() local cwd = vim.fn.getcwd() local jumplist, current = unpack(vim.fn.getjumplist()) for position = current, #jumplist, 1 do local jump = jumplist[position] local path = vim.api.nvim_buf_get_name(jump.bufnr) if vim.startswith(path, cwd) then return vim.api.nvim_win_set_buf(0, jump.bufnr) end end end vim.diagnostic.config({ severity_sort = true })
object_mobile_npe_dressed_rakqua_shaman_02 = object_mobile_npe_shared_dressed_rakqua_shaman_02:new { } ObjectTemplates:addTemplate(object_mobile_npe_dressed_rakqua_shaman_02, "object/mobile/npe/dressed_rakqua_shaman_02.iff")
SCHEMA.name = "Military RP (WIP)" SCHEMA.introname = "Military RP (WIP)" SCHEMA.author = "ChazNN" SCHEMA.desc = "A Serious Military RP" function SCHEMA:isArmyFaction(faction) return faction == FACTION_ARMY or faction == FACTION_ARMYCOMMAND end function SCHEMA:isNavyFaction(faction) return faction == FACTION_NAVY or faction == FACTION_NAVYCOMMAND end function SCHEMA:isMarineFaction(faction) return faction == FACTION_MARINE or faction == FACTION_MARINECOMMAND end function SCHEMA:isAirForceFaction(faction) return faction == FACTION_AF or faction == FACTION_AFCOMMAND end do local playerMeta = FindMetaTable("Player") function playerMeta:isArmy() return SCHEMA:isArmyFaction(self:Team()) end function playerMeta:isNavy() return SCHEMA:isNavyFaction(self:Team()) end function playerMeta:isMarine() return SCHEMA:isMarineFaction(self:Team()) end function playerMeta:isAirForce() return SCHEMA:isAirForceFaction(self:Team()) end function playerMeta:getArmyRank() local name = self:Name() for k, v in ipairs(SCHEMA.rctRanks) do local rank = string.PatternSafe(v) if (name:find("[%D+]"..rank.."[%D+]")) then return v end end for k, v in ipairs(SCHEMA.enlistedRanks) do local rank = string.PatternSafe(v) if (name:find("[%D+]"..rank.."[%D+]")) then return v end end for k, v in ipairs(SCHEMA.ncoRanks) do local rank = string.PatternSafe(v) if (name:find("[%D+]"..rank.."[%D+]")) then return v end end for k, v in ipairs(SCHEMA.officerRanks) do local rank = string.PatternSafe(v) if (name:find("[%D+]"..rank.."[%D+]")) then return v end end end function playerMeta:getNavyRank() local name = self:Name() for k, v in ipairs(SCHEMA.rctRanks) do local rank = string.PatternSafe(v) if (name:find("[%D+]"..rank.."[%D+]")) then return v end end for k, v in ipairs(SCHEMA.enlistedRanks) do local rank = string.PatternSafe(v) if (name:find("[%D+]"..rank.."[%D+]")) then return v end end for k, v in ipairs(SCHEMA.ncoRanks) do local rank = string.PatternSafe(v) if (name:find("[%D+]"..rank.."[%D+]")) then return v end end for k, v in ipairs(SCHEMA.officerRanks) do local rank = string.PatternSafe(v) if (name:find("[%D+]"..rank.."[%D+]")) then return v end end end function playerMeta:getMarineRank() local name = self:Name() for k, v in ipairs(SCHEMA.rctRanks) do local rank = string.PatternSafe(v) if (name:find("[%D+]"..rank.."[%D+]")) then return v end end for k, v in ipairs(SCHEMA.enlistedRanks) do local rank = string.PatternSafe(v) if (name:find("[%D+]"..rank.."[%D+]")) then return v end end for k, v in ipairs(SCHEMA.ncoRanks) do local rank = string.PatternSafe(v) if (name:find("[%D+]"..rank.."[%D+]")) then return v end end for k, v in ipairs(SCHEMA.officerRanks) do local rank = string.PatternSafe(v) if (name:find("[%D+]"..rank.."[%D+]")) then return v end end end function playerMeta:getAirforceRank() local name = self:Name() for k, v in ipairs(SCHEMA.rctRanks) do local rank = string.PatternSafe(v) if (name:find("[%D+]"..rank.."[%D+]")) then return v end end for k, v in ipairs(SCHEMA.enlistedRanks) do local rank = string.PatternSafe(v) if (name:find("[%D+]"..rank.."[%D+]")) then return v end end for k, v in ipairs(SCHEMA.ncoRanks) do local rank = string.PatternSafe(v) if (name:find("[%D+]"..rank.."[%D+]")) then return v end end for k, v in ipairs(SCHEMA.officerRanks) do local rank = string.PatternSafe(v) if (name:find("[%D+]"..rank.."[%D+]")) then return v end end end function playerMeta:isArmyRank(rank) if (type(rank) == "table") then local name = self:Name() for k, v in ipairs(rank) do local rank = string.PatternSafe(v) if (name:find("[%D+]"..rank.."[%D+]")) then return v end end return false else return self:getArmyRank() == rank end end function playerMeta:isNavyRank(rank) if (type(rank) == "table") then local name = self:Name() for k, v in ipairs(rank) do local rank = string.PatternSafe(v) if (name:find("[%D+]"..rank.."[%D+]")) then return v end end return false else return self:getNavyRank() == rank end end function playerMeta:isMarineRank(rank) if (type(rank) == "table") then local name = self:Name() for k, v in ipairs(rank) do local rank = string.PatternSafe(v) if (name:find("[%D+]"..rank.."[%D+]")) then return v end end return false else return self:getMarineRank() == rank end end function playerMeta:isAirforceRank(rank) if (type(rank) == "table") then local name = self:Name() for k, v in ipairs(rank) do local rank = string.PatternSafe(v) if (name:find("[%D+]"..rank.."[%D+]")) then return v end end return false else return self:getAirForceRank() == rank end end function playerMeta:getArmyRank() for k, v in ipairs(team.GetPlayers(FACTION_ARMY)) do local commanderRanks = string.Explode(",", nut.config.get("rankCommander", "RCT"):gsub("%s", "")) local officerRanks = string.Explode(",", nut.config.get("rankOfficer", "RCT"):gsub("%s", "")) local ncoRanks = string.Explode(",", nut.config.get("rankNco", "RCT"):gsub("%s", "")) local enlistedRanks = string.Explode(",", nut.config.get("rankEnlisted", "RCT"):gsub("%s", "")) local name = string.PatternSafe(v:Name()) for k, v in ipairs(commandRanks) do if (name:find(v)) then return CLASS_ARMY_COMMAND end end for k, v in ipairs(officerRanks) do if (name:find(v)) then return CLASS_ARMY_OFFICER end end for k, v in ipairs(enlistedRanks) do if (name:find(v)) then return CLASS_ARMY_ENLISTED end end for k, v in ipairs(ncoRanks) do if (name:find(v)) then return CLASS_ARMY_NCO end end return CLASS_ARMY_RCT end end function playerMeta:getNavyRank() for k, v in ipairs(team.GetPlayers(FACTION_NAVY)) do local commanderRanks = string.Explode(",", nut.config.get("rankCommander", "RCT"):gsub("%s", "")) local officerRanks = string.Explode(",", nut.config.get("rankOfficer", "RCT"):gsub("%s", "")) local ncoRanks = string.Explode(",", nut.config.get("rankNco", "RCT"):gsub("%s", "")) local enlistedRanks = string.Explode(",", nut.config.get("rankEnlisted", "RCT"):gsub("%s", "")) local name = string.PatternSafe(v:Name()) for k, v in ipairs(commandRanks) do if (name:find(v)) then return CLASS_NAVY_COMMANDER end end for k, v in ipairs(officerRanks) do if (name:find(v)) then return CLASS_NAVY_OFFICER end end for k, v in ipairs(ncoRanks) do if (name:find(v)) then return CLASS_NAVY_NCO end end for k, v in ipairs(enlistedRanks) do if (name:find(v)) then return CLASS_NAVY_ENLISTED end end return CLASS_NAVY_RCT end end function playerMeta:getMarineRank() for k, v in ipairs(team.GetPlayers(FACTION_MARINE)) do local commanderRanks = string.Explode(",", nut.config.get("rankCommander", "RCT"):gsub("%s", "")) local officerRanks = string.Explode(",", nut.config.get("rankOfficer", "RCT"):gsub("%s", "")) local ncoRanks = string.Explode(",", nut.config.get("rankNco", "RCT"):gsub("%s", "")) local enlistedRanks = string.Explode(",", nut.config.get("rankEnlisted", "RCT"):gsub("%s", "")) local name = string.PatternSafe(v:Name()) for k, v in ipairs(commandRanks) do if (name:find(v)) then return CLASS_MARINE_COMMANDER end end for k, v in ipairs(officerRanks) do if (name:find(v)) then return CLASS_MARINE_OFFICER end end for k, v in ipairs(ncoRanks) do if (name:find(v)) then return CLASS_MARINE_NCO end end for k, v in ipairs(enlistedRanks) do if (name:find(v)) then return CLASS_MARINE_ENLISTED end end return CLASS_MARINE_RCT end end function playerMeta:getAirforceRank() for k, v in ipairs(team.GetPlayers(FACTION_AF)) do local officerRanks = string.Explode(",", nut.config.get("rankCommander", "RCT"):gsub("%s", "")) local officerRanks = string.Explode(",", nut.config.get("rankOfficer", "RCT"):gsub("%s", "")) local ncoRanks = string.Explode(",", nut.config.get("rankNco", "RCT"):gsub("%s", "")) local enlistedRanks = string.Explode(",", nut.config.get("rankEnlisted", "RCT"):gsub("%s", "")) local name = string.PatternSafe(v:Name()) for k, v in ipairs(commandRanks) do if (name:find(v)) then return CLASS_AF_COMMANDER end end for k, v in ipairs(officerRanks) do if (name:find(v)) then return CLASS_AF_OFFICER end end for k, v in ipairs(ncoRanks) do if (name:find(v)) then return CLASS_AF_NCO end end for k, v in ipairs(enlistedRanks) do if (name:find(v)) then return CLASS_AF_ENLISTED end end return CLASS_AF_RCT end end function SCHEMA:isDispatch(client) return client:isArmyRank(self.officerRanks) or client:isArmyRank(self.commandRanks) end function SCHEMA:isDispatch(client) return client:isNavyRank(self.officerRanks) end function SCHEMA:isDispatch(client) return client:isMarineRank(self.officerRanks) end function SCHEMA:isDispatch(client) return client:isAirForceRank(self.officerRanks) end function playerMeta:getDigits() if (self:isCombine()) then local name = self:Name():reverse() local digits = name:match("(%d+)") if (digits) then return tostring(digits):reverse() end end return "UNKNOWN" end if (SERVER) then function playerMeta:addDisplay(text, color) if (self:isCombine()) then netstream.Start(self, "cDisp", text, color) end end function SCHEMA:addDisplay(text, color) local receivers = {} for k, v in ipairs(player.GetAll()) do if (v:isCombine()) then receivers[#receivers + 1] = v end end netstream.Start(receivers, "cDisp", text, color) end end end nut.util.include("sh_config.lua") nut.util.include("sh_commands.lua") nut.util.includeDir("hooks") if (SERVER) then SCHEMA.objectives = SCHEMA.objectives or "" concommand.Add("nut_setupnexusdoors", function(client, command, arguments) if (!IsValid(client)) then if (!nut.plugin.list.doors) then return MsgN("[NutScript] Door plugin is missing!") end local name = table.concat(arguments, " ") for _, entity in ipairs(ents.FindByClass("func_door")) do if (!entity:HasSpawnFlags(256) and !entity:HasSpawnFlags(1024)) then entity:setNetVar("noSell", true) entity:setNetVar("name", !name:find("%S") and "Nexus" or name) end end nut.plugin.list.doors:SaveDoorData() MsgN("[NutScript] Nexus doors have been set up.") end end) end for k, v in pairs(SCHEMA.beepSounds) do for k2, v2 in ipairs(v.on) do util.PrecacheSound(v2) end for k2, v2 in ipairs(v.off) do util.PrecacheSound(v2) end end for k, v in pairs(SCHEMA.deathSounds) do for k2, v2 in ipairs(v) do util.PrecacheSound(v2) end end for k, v in pairs(SCHEMA.painSounds) do for k2, v2 in ipairs(v) do util.PrecacheSound(v2) end end for k, v in pairs(SCHEMA.rankModels) do nut.anim.SetModelClass(v, "metrocop") player_manager.AddValidModel("combine", v) util.PrecacheModel(v) end nut.util.include("sh_voices.lua") if (SERVER) then function SCHEMA:saveObjectives() nut.data.set("objectives", self.objectives, false, true) end function SCHEMA:saveVendingMachines() local data = {} for k, v in ipairs(ents.FindByClass("nut_vendingm")) do data[#data + 1] = {v:GetPos(), v:GetAngles(), v:getNetVar("stocks"), v:getNetVar("active")} end nut.data.set("vendingm", data) end function SCHEMA:saveDispensers() local data = {} for k, v in ipairs(ents.FindByClass("nut_dispenser")) do data[#data + 1] = {v:GetPos(), v:GetAngles(), v:GetDisabled() == true and true or nil} end nut.data.set("dispensers", data) end function SCHEMA:loadObjectives() self.objectives = nut.data.get("objectives", "", false, true) end function SCHEMA:loadVendingMachines() local data = nut.data.get("vendingm") or {} for k, v in ipairs(data) do local entity = ents.Create("nut_vendingm") entity:SetPos(v[1]) entity:SetAngles(v[2]) entity:Spawn() entity:setNetVar("stocks", v[3] or {}) entity:setNetVar("active", v[4]) end end function SCHEMA:loadDispensers() for k, v in ipairs(nut.data.get("dispensers") or {}) do local entity = ents.Create("nut_dispenser") entity:SetPos(v[1]) entity:SetAngles(v[2]) entity:Spawn() if (v[3]) then entity:SetDisabled(true) end end end end nut.chat.register("dispatch", { color = Color(192, 57, 43), onCanSay = function(client) if (!SCHEMA:isDispatch(client)) then client:notifyLocalized("notAllowed") return false end end, onChatAdd = function(speaker, text) chat.AddText(Color(192, 57, 43), L("icFormat", "Dispatch", text)) end, prefix = {"/dispatch"} }) nut.chat.register("request", { color = Color(210, 77, 87), onChatAdd = function(speaker, text) chat.AddText(Color(210, 77, 87), text) end, onCanHear = function(speaker, listener) return listener:isCombine() end }) nut.flag.add("y", "Access to the light blackmarket items.") nut.flag.add("Y", "Access to the heavy blackmarket items.") nut.currency.set("", "token", "tokens") --marines nut.anim.SetModelClass("models/player/pmc_3/pmc__05.mdl", "metrocop") nut.anim.SetModelClass("models/player/pmc_3/pmc__07.mdl", "metrocop") nut.anim.SetModelClass("models/player/pmc_3/pmc__03.mdl", "metrocop") nut.anim.SetModelClass("models/player/pmc_5/pmc__01.mdl", "metrocop") --army nut.anim.SetModelClass("models/player/pmc_6/pmc__05.mdl", "metrocop") nut.anim.SetModelClass("models/player/pmc_6/pmc__07.mdl", "metrocop") nut.anim.SetModelClass("models/player/pmc_6/pmc__03.mdl", "metrocop") nut.anim.SetModelClass("models/player/pmc_6/pmc__01.mdl", "metrocop") --navy nut.anim.SetModelClass("models/player/pmc_1/pmc__08.mdl", "metrocop") nut.anim.SetModelClass("models/player/pmc_1/pmc__07.mdl", "metrocop") nut.anim.SetModelClass("models/player/pmc_1/pmc__03.mdl", "metrocop") nut.anim.SetModelClass("models/player/pmc_1/pmc__01.mdl", "metrocop") --air force nut.anim.SetModelClass("metrocop", "models/player/pmc_3/pmc__10.mdl") nut.anim.SetModelClass("models/player/pmc_3/pmc__07.mdl", "metrocop") nut.anim.SetModelClass("models/player/pmc_3/pmc__03.mdl", "metrocop") nut.anim.SetModelClass("models/player/pmc_3/pmc__01.mdl", "metrocop") --marines nut.anim.setModelClass("models/player/pmc_3/pmc__05.mdl", "metrocop") nut.anim.setModelClass("models/player/pmc_3/pmc__07.mdl", "metrocop") nut.anim.setModelClass("models/player/pmc_3/pmc__03.mdl", "metrocop") nut.anim.setModelClass("models/player/pmc_5/pmc__01.mdl", "metrocop") --army nut.anim.setModelClass("models/player/pmc_6/pmc__05.mdl", "metrocop") nut.anim.setModelClass("models/player/pmc_6/pmc__07.mdl", "metrocop") nut.anim.setModelClass("models/player/pmc_6/pmc__03.mdl", "metrocop") nut.anim.setModelClass("models/player/pmc_6/pmc__01.mdl", "metrocop") --navy nut.anim.setModelClass("models/player/pmc_1/pmc__08.mdl", "metrocop") nut.anim.setModelClass("models/player/pmc_1/pmc__07.mdl", "metrocop") nut.anim.setModelClass("models/player/pmc_1/pmc__03.mdl", "metrocop") nut.anim.setModelClass("models/player/pmc_1/pmc__01.mdl", "metrocop") --air force nut.anim.setModelClass("metrocop", "models/player/pmc_3/pmc__10.mdl") nut.anim.setModelClass("models/player/pmc_3/pmc__10.mdl", "metrocop") nut.anim.setModelClass("models/player/pmc_3/pmc__07.mdl", "metrocop") nut.anim.setModelClass("models/player/pmc_3/pmc__03.mdl", "metrocop") nut.anim.setModelClass("models/player/pmc_3/pmc__01.mdl", "metrocop")
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local allow_registration = module:get_option_boolean("allow_registration", false); if allow_registration then module:depends("register_ibr"); module:depends("watchregistrations"); end module:depends("user_account_management");
local Class = require "lib.hump.Class" local Component = require "component.Component" local Signals = require "constants.Signals" local HPComponent = Class{} HPComponent:include(Component) function HPComponent:init(hp, hitSignal) assert(hp and hitSignal, "arguments missing") Component.init(self) self.type = "hp" self._hp = hp self._hitSignal = hitSignal end function HPComponent:conception() self.owner.events:register(self._hitSignal, function() self._hp = self._hp - 1 if self._hp <= 0 then Signal.emit(Signals.KILL_ENTITY, self.owner) end end) Component.conception(self) end return HPComponent
local path = debug.getinfo(1).short_src:match("([^%.]*)[\\/][^%.]*%..*$"):gsub("[\\/]", ".") .. "." local engine = require(path .. "core") function love.run() engine:init() local engine_event = engine.event love.graphics.setFont(love.graphics.newFont()) love.handlers = setmetatable({ keypressed = function(b, u) if love.keypressed then love.keypressed(b, u) end engine_event:fire_keydown(b, u) end, keyreleased = function(b) if love.keyreleased then love.keyreleased(b) end engine_event:fire_keyup(b) end, mousepressed = function(x, y, b) if love.mousepressed then love.mousepressed(x, y, b) end engine_event:fire_mousedown(x, y, b) end, mousereleased = function(x, y, b) if love.mousereleased then love.mousereleased(x, y, b) end engine_event:fire_mouseup(x, y, b) end, joystickpressed = function(j, b) if love.joystickpressed then love.joystickpressed(j, b) end engine_event:fire_joydown(j, b) end, joystickreleased = function(j, b) if love.joystickreleased then love.joystickreleased(j, b) end engine_event:fire_joyup(j, b) end, focus = function(f) if love.focus then love.focus(f) end engine_event:fire_focus(f) end, quit = function() return end, }, { __index = function(self, name) error("Unknown event: " .. name) end, }) math.randomseed(os.time()) math.random() math.random() if love.load then love.load(arg) end local dt = 0 local event, timer, graphics = love.event, love.timer, love.graphics while (true) do if (event) then event.pump() for e, a, b, c, d in event.poll() do if (e == "quit") then if (not love.quit or not love.quit()) then if (love.audio) then love.audio.stop() end engine:close() return end end love.handlers[e](a, b, c, d) end end if (timer) then timer.step() dt = timer.getDelta() end if (love.update) then love.update(dt) end engine_event:fire_update(dt) if (graphics) then graphics.clear() engine_event:fire_draw() if (love.draw) then love.draw() end end if (timer) then timer.sleep(0.001) end if (graphics) then graphics.present() end end end return engine
-- Nvim-tree Configuration local mapping_config = require "jesse.mapping.plugin.nvim-tree" require("nvim-tree").setup { disable_netrw = true, hijack_netrw = true, hijack_cursor = true, view = { auto_resize = true, mappings = { list = mapping_config.list, }, }, }
local test = {} test['should before of string'] = function() local str1 = "this is a test" local str2 = "this is" assert( str1:mid(1, 7) == str2 ) end test['should middle of string'] = function() local str1 = "this is a test" local str2 = "is a" assert( str1:mid(6, 4) == str2 ) end test['should end of string'] = function() local str1 = "this is a test" local str2 = "test" assert( str1:mid(11, 4) == str2 ) end test['should return init after end string'] = function() local str1 = "this is a test" local str2 = "is a test" assert( str1:mid(6, -1) == str2 ) end test['should return empty string if start is 0'] = function() local str = "this is a test" assert( str:mid(0, 1) == "", 'resultado ' .. str:mid(1, 1)) end test['should return empty string if start is major 0 and length is 0'] = function() local str = "" assert( str:mid(3, 0) == "", 'resultado ' .. str:mid(3, 0)) end test['should return empty string if index is major and len is negative'] = function() local str = "/" assert( str:mid(4, -4) == "", 'resultado ' .. str:mid(4, -4)) end return test
print('sleeping 5 mins') node.dsleep(5*60*1000000)
function onRecalculateRating() if ratingName == 'Perfect!!' then setRatingName('Cool!!') elseif ratingName == 'Sick!' then setRatingName('Sick!') elseif ratingName == 'Great' then setRatingName('Skill Issue') elseif ratingName == 'Good' then setRatingName('Ratio') elseif ratingName == 'Meh' then setRatingName('Welp') elseif ratingName == 'Bruh' then setRatingName('Smh smh') elseif ratingName == 'Bad' then setRatingName('Sus') elseif ratingName == 'Shit' then setRatingName('WTF') elseif ratingName == 'You Suck!' then setRatingName('Die.') end end
local BasePlugin = require "kong.plugins.base_plugin" local CustomHandler = BasePlugin:extend() local kong = kong.response local ngx = ngx function CustomHandler:new() CustomHandler.super.new(self, "orgcode") end function CustomHandler:init_worker() CustomHandler.super.init_worker(self) end function CustomHandler:certificate(config) CustomHandler.super.certificate(self) end function CustomHandler:rewrite(config) CustomHandler.super.rewrite(self) end function replace_host_from_redis(red, orgcode) local value = red:hget("organization_env",orgcode) if type(value) == "string" and value ~= "" then local values = strsplit(value, ":") if type(values[1]) == "string" and values[1] ~= "" then ngx.ctx.balancer_data.host = values[1] -- 反向代理到其他网关,需要保持路径不变 ngx.var.upstream_uri = ngx.var.uri end if type(values[2]) == "string" and values[2] ~= "" then ngx.ctx.balancer_data.port = values[2] end return end end function strsplit (inputstr, sep) if sep == nil then sep = "%s" end local t={} for str in string.gmatch(inputstr, "([^"..sep.."]+)") do table.insert(t, str) end return t end function CustomHandler:access(config) CustomHandler.super.access(self) local ip = config.redis_host local passwd = config.redis_passwd local port = 6379 local redis = require "resty.redis" local red = redis:new() red:set_timeout(50000) -- 1 sec local ok, err = red:connect(ip, port) if not ok then ngx.log(ngx.ERR, "connect redis fail") return end local res, err = red:auth(passwd) if not res then ngx.log(ngx.ERR, "auth redis fail") return end local headers = ngx.req.get_headers() local query_header = headers["orgcode"] if query_header then replace_host_from_redis(red, query_header) end end function CustomHandler:header_filter(config) CustomHandler.super.header_filter(self) end function CustomHandler:body_filter(config) CustomHandler.super.body_filter(self) end function CustomHandler:log(config) CustomHandler.super.log(self) end return CustomHandler
include("shared.lua"); -- Called when the entity initializes. function ENT:Initialize() end -- Called when the entity should draw. function ENT:Draw() self.Entity:DrawModel() end -- Called when the entity should think. function ENT:Think() local dlight = DynamicLight( self:EntIndex() ) if ( dlight ) then local r, g, b, a = self:GetColor() dlight.Pos = self:GetPos() dlight.r = 253 dlight.g = 222 dlight.b = 23 dlight.Brightness = 0 dlight.Size = 698 dlight.Decay = 5 dlight.DieTime = CurTime() + 0.1 end end
require 'nn' --require 'cunn' require 'cudnn' --require 'dpnn' --require 'nnx' --local inn = require 'inn' -- if not nn.SpatialConstDiagonal then -- torch.class('nn.SpatialConstDiagonal', 'inn.ConstAffine') -- end --local utils = paths.dofile('modelUtils.lua') --require 'models/DeepMask' local M = {} function M.setup(opt, checkpoint) local model if checkpoint then local modelPath = paths.concat(opt.resume, checkpoint.modelFile) assert(paths.filep(modelPath), 'Saved model not found: ' .. modelPath) print('=> Resuming model from ' .. modelPath) model = torch.load(modelPath) elseif opt.retrain ~= 'none' then assert(paths.filep(opt.retrain), 'File not found: ' .. opt.retrain) print('Loading model from file: ' .. opt.retrain) model = torch.load(opt.retrain) else local modelFileName = 'models/' .. opt.netType print('=> Creating model from file: ' .. modelFileName .. '.lua') model = require(modelFileName)(opt) end cudnn.convert(model, cudnn) local criterionFileName = 'models/' .. opt.criterionType criterionFileName = criterionFileName .. '-criterion' local criterion local f = io.open(criterionFileName .. '.lua', "r") if f ~= nil then io.close(f) criterion = require(criterionFileName)(opt) end return model, criterion end return M
require 'Scripts/premake-defines' require 'Scripts/premake-common' require 'Scripts/premake-triggers' require 'Scripts/premake-settings' --require 'Scripts/premake-vscode/vscode' root_dir = os.getcwd() Arch = "" if _OPTIONS["arch"] then Arch = _OPTIONS["arch"] else if _OPTIONS["os"] then _OPTIONS["arch"] = "arm" Arch = "arm" else _OPTIONS["arch"] = "x64" Arch = "x64" end end workspace( settings.workspace_name ) location "build" startproject "Runtime" flags 'MultiProcessorCompile' outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}" targetdir ("bin/%{outputdir}/") objdir ("bin-int/%{outputdir}/obj/") if Arch == "arm" then architecture "ARM" elseif Arch == "x64" then architecture "x86_64" elseif Arch == "x86" then architecture "x86" end print("Arch = ", Arch) configurations { "Debug", "Release", "Production" } group "External" require("Lumos/External/box2d/premake5") SetRecommendedSettings() require("Lumos/External/lua/premake5") SetRecommendedSettings() require("Lumos/External/imgui/premake5") SetRecommendedSettings() require("Lumos/External/freetype/premake5") SetRecommendedSettings() require("Lumos/External/SPIRVCrosspremake5") SetRecommendedSettings() require("Lumos/External/spdlog/premake5") SetRecommendedSettings() require("Lumos/External/meshoptimizer/premake5") SetRecommendedSettings() if not os.istarget(premake.IOS) and not os.istarget(premake.ANDROID) then require("Lumos/External/GLFWpremake5") SetRecommendedSettings() end filter {} group "" include "Lumos/premake5" include "Runtime/premake5" include "Editor/premake5"
local system = require "system" local mysql = require "mysql" local json = require "rapidjson" local function serialize(obj) local lua = "" local t = type(obj) if t == "number" then lua = lua .. obj elseif t == "boolean" then lua = lua .. tostring(obj) elseif t == "string" then lua = lua .. string.format("%q", obj) elseif t == "table" then lua = lua .. "{" for k, v in pairs(obj) do lua = lua .. "[" .. serialize(k) .. "]=" .. serialize(v) .. "," end local metatable = getmetatable(obj) if metatable ~= nil and type(metatable.__index) == "table" then for k, v in pairs(metatable.__index) do lua = lua .. "[" .. serialize(k) .. "]=" .. serialize(v) .. "," end end lua = lua .. "}" elseif t == "nil" then return nil else error("can not serialize a " .. t .. " type.") end return lua end local db = mysql.connect({ host="127.0.0.1", port=3306, database="test", user="root", password="123" }) local rr1 = db:query("update vendors set vend_name='friend' where vend_id=1") print("rr1", json.encode(rr1)) local rr2 = db:query("update vendors sevend_name='friend' where vend_id=1") print("rr2", json.encode(rr2)) local ret1 = db:query("select * from vendors") print("ret1", json.encode(ret1)) local ret2 = db:query("select 2001%7;") print("ret2", json.encode(ret2)) db:close()
--[[ Name: sh_mayor_ss_menu.lua For: TalosLife By: TalosLife ]]-- local App = {} App.Name = "Secret Service" App.ID = "nsa.exe" App.Panel = "SRPComputer_AppWindow_SecretService" App.Icon = "nomad/computer/icon_ss.png" App.DekstopIcon = true App.StartMenuIcon = true --App code --End app code GM.Apps:Register( App ) if SERVER then return end --App UI local Panel = {} function Panel:Init() self.m_pnlAvatar = vgui3D.Create( "AvatarImage", self ) self.m_pnlLabelName = vgui3D.Create( "DLabel", self ) self.m_pnlLabelName:SetTextColor( Color(255, 255, 255, 255) ) self.m_pnlLabelName:SetFont( "Trebuchet18" ) self.m_pnlLabelName:SetMouseInputEnabled( false ) self.m_pnlBtnFire = vgui3D.Create( "DButton", self ) self.m_pnlBtnFire:SetText( "Fire" ) self.m_pnlBtnFire.DoClick = function() GAMEMODE.Net:RequestFireSS( self.m_pPlayer ) end self.m_pnlBtnFire:SetTextColor( Color(255, 255, 255, 255) ) end function Panel:SetPlayer( pPlayer ) self.m_pPlayer = pPlayer self.m_pnlAvatar:SetSize( 32, 32 ) self.m_pnlAvatar:SetPlayer( pPlayer ) self.m_pnlLabelName:SetText( pPlayer:Nick() ) self:InvalidateLayout() end function Panel:Think() if not IsValid( self.m_pPlayer ) then self:Remove() end end function Panel:PerformLayout( intW, intH ) self.m_pnlLabelName:SizeToContents() self.m_pnlAvatar:SetPos( 0, 0 ) self.m_pnlAvatar:SetSize( intH, intH ) self.m_pnlLabelName:SetPos( self.m_pnlAvatar:GetWide() +5, 0 ) self.m_pnlBtnFire:SetSize( 64, 16 ) self.m_pnlBtnFire:SetPos( self.m_pnlAvatar:GetWide() +5, intH -self.m_pnlBtnFire:GetTall() -3 ) end vgui.Register( "SRPComputer_AppWindow_SecretService_EmployCard", Panel, "EditablePanel" ) local Panel = {} function Panel:Init() self.m_pnlCanvas = vgui3D.Create( "SRPComputer_ScrollPanel", self ) self.m_tblPlayerCards = {} self:Populate() local hookID = ("UpdateSSApp_%p"):format( self ) hook.Add( "GamemodeOnGetSSApps", hookID, function( tblApps ) if not ValidPanel( self ) then hook.Remove( "GamemodeOnGetSSApps", hookID ) return end self:Populate() end ) self.m_pnlLabelCap = vgui3D.Create( "DLabel", self ) self.m_pnlLabelCap:SetTextColor( Color(255, 255, 255, 255) ) self.m_pnlLabelCap:SetFont( "Trebuchet18" ) self.m_pnlLabelCap:SetMouseInputEnabled( false ) end function Panel:Think() if CurTime() < (self.m_intLastThink or 0) then return end local cap = GAMEMODE.Jobs:CalcJobPlayerCap( JOB_SSERVICE ) local num = GAMEMODE.Jobs:GetNumPlayers( JOB_SSERVICE ) self.m_pnlLabelCap:SetText( num.. "/".. cap.. " Employees" ) self:InvalidateLayout() self.m_intLastThink = CurTime() +1 end function Panel:Populate() for k, v in pairs( player.GetAll() ) do if GAMEMODE.Jobs:GetPlayerJobID( v ) ~= JOB_SSERVICE then continue end self:CreatePlayerCard( v ) end --for i = 1, 11 do -- self:CreatePlayerCard( LocalPlayer() ) --end end function Panel:CreatePlayerCard( pPlayer ) local card = vgui3D.Create( "SRPComputer_AppWindow_SecretService_EmployCard", self.m_pnlCanvas ) card:SetPlayer( pPlayer ) table.insert( self.m_tblPlayerCards, card ) self.m_pnlCanvas:AddItem( card ) return card end function Panel:PerformLayout( intW, intH ) self.m_pnlLabelCap:SizeToContents() self.m_pnlLabelCap:SetPos( 0, intH -self.m_pnlLabelCap:GetTall() ) self.m_pnlCanvas:SetPos( 0, 0 ) self.m_pnlCanvas:SetSize( intW, intH -self.m_pnlLabelCap:GetTall() ) for _, pnl in pairs( self.m_tblPlayerCards ) do if not ValidPanel( pnl ) then continue end pnl:DockMargin( 0, 0, 0, 5 ) pnl:SetTall( 38 ) pnl:Dock( TOP ) end end vgui.Register( "SRPComputer_AppWindow_SecretService_TabEmploy", Panel, "EditablePanel" ) local Panel = {} function Panel:Init() self.m_pnlAvatar = vgui3D.Create( "AvatarImage", self ) self.m_pnlLabelName = vgui3D.Create( "DLabel", self ) self.m_pnlLabelName:SetTextColor( Color(255, 255, 255, 255) ) self.m_pnlLabelName:SetFont( "Trebuchet18" ) self.m_pnlLabelName:SetMouseInputEnabled( false ) self.m_pnlBtnApprove = vgui3D.Create( "DButton", self ) self.m_pnlBtnApprove:SetText( "Accept" ) self.m_pnlBtnApprove.DoClick = function() GAMEMODE.Net:RequestApproveSSApp( self.m_pPlayer ) end self.m_pnlBtnApprove:SetTextColor( Color(255, 255, 255, 255) ) self.m_pnlBtnDeny = vgui3D.Create( "DButton", self ) self.m_pnlBtnDeny:SetText( "Deny" ) self.m_pnlBtnDeny.DoClick = function() GAMEMODE.Net:RequestDenySSApp( self.m_pPlayer ) end self.m_pnlBtnDeny:SetTextColor( Color(255, 255, 255, 255) ) end function Panel:SetPlayer( pPlayer ) self.m_pPlayer = pPlayer self.m_pnlAvatar:SetSize( 32, 32 ) self.m_pnlAvatar:SetPlayer( pPlayer ) self.m_pnlLabelName:SetText( pPlayer:Nick() ) self:InvalidateLayout() end function Panel:Think() if not IsValid( self.m_pPlayer ) then self:Remove() end end function Panel:PerformLayout( intW, intH ) self.m_pnlLabelName:SizeToContents() self.m_pnlAvatar:SetPos( 0, 0 ) self.m_pnlAvatar:SetSize( intH, intH ) self.m_pnlLabelName:SetPos( self.m_pnlAvatar:GetWide() +5, 0 ) self.m_pnlBtnApprove:SetSize( 64, 16 ) self.m_pnlBtnDeny:SetSize( 64, 16 ) self.m_pnlBtnApprove:SetPos( self.m_pnlAvatar:GetWide() +5, intH -self.m_pnlBtnApprove:GetTall() -3 ) self.m_pnlBtnDeny:SetPos( self.m_pnlAvatar:GetWide() +self.m_pnlBtnApprove:GetWide() +10, intH -self.m_pnlBtnDeny:GetTall() -3 ) end vgui.Register( "SRPComputer_AppWindow_SecretService_AppCard", Panel, "EditablePanel" ) local Panel = {} function Panel:Init() self.m_pnlCanvas = vgui3D.Create( "SRPComputer_ScrollPanel", self ) local hookID = ("UpdateSSApp_%p"):format( self ) hook.Add( "GamemodeOnGetSSApps", hookID, function( tblApps ) if not ValidPanel( self ) then hook.Remove( "GamemodeOnGetSSApps", hookID ) return end self:Populate( tblApps ) end ) self.m_tblPlayerCards = {} self:Populate( GAMEMODE.m_tblSSApps or {} ) end function Panel:Populate( tblApps ) for k, v in pairs( self.m_tblPlayerCards ) do if ValidPanel( v ) then v:Remove() end end self.m_tblPlayerCards = {} for pl, _ in pairs( tblApps ) do if IsValid( pl ) then self:CreatePlayerCard( pl ) end end --for i = 1, 12 do -- self:CreatePlayerCard( LocalPlayer() ) --end self:InvalidateLayout() end function Panel:CreatePlayerCard( pPlayer ) local card = vgui3D.Create( "SRPComputer_AppWindow_SecretService_AppCard", self.m_pnlCanvas ) card:SetPlayer( pPlayer ) table.insert( self.m_tblPlayerCards, card ) self.m_pnlCanvas:AddItem( card ) return card end function Panel:PerformLayout( intW, intH ) self.m_pnlCanvas:SetPos( 0, 0 ) self.m_pnlCanvas:SetSize( intW, intH ) for _, pnl in pairs( self.m_tblPlayerCards ) do if not ValidPanel( pnl ) then continue end pnl:DockMargin( 0, 0, 0, 5 ) pnl:SetTall( 38 ) pnl:Dock( TOP ) end end vgui.Register( "SRPComputer_AppWindow_SecretService_TabApps", Panel, "EditablePanel" ) local Panel = {} function Panel:Init() self:GetParent():SetTitle( App.Name ) self:GetParent():SetSize( 280, 400 ) self:GetParent():SetPos( 50, 50 ) self.m_pnlTabs = vgui3D.Create( "SRPComputer_DPropertySheet", self ) self.m_pnlTabs:AddSheet( "Employees", vgui3D.Create("SRPComputer_AppWindow_SecretService_TabEmploy", self.m_pnlTabs), "icon16/briefcase.png", nil, nil, "" ) self.m_pnlTabs:AddSheet( "Applications", vgui3D.Create("SRPComputer_AppWindow_SecretService_TabApps", self.m_pnlTabs), "icon16/book_open.png", nil, nil, "" ) end function Panel:PerformLayout( intW, intH ) self.m_pnlTabs:SetPos( 0, 0 ) self.m_pnlTabs:SetSize( intW, intH ) end vgui.Register( "SRPComputer_AppWindow_SecretService", Panel, "EditablePanel" )
return Def.ActorFrame { --Def.ControllerStateDisplay { -- InitCommand=function(self) -- self:LoadGameController() --end, --}; Def.DeviceList { Font = "Common Normal", InitCommand = function(self) self:x(SCREEN_LEFT + 20):y(SCREEN_TOP + 80):zoom(0.8):halign(0) end }, Def.InputList { Font = "Common Normal", InitCommand = function(self) self:x(SCREEN_CENTER_X - 250):y(SCREEN_CENTER_Y):zoom(1):halign(0):vertspacing(8) end } }
setenv(myModuleName(),myModuleFullName())
--- -- @classmod Color local middleclass = require("middleclass") local typeutils = require("typeutils") --- -- @table instance -- @tfield number red [0, 1] -- @tfield number green [0, 1] -- @tfield number blue [0, 1] local Color = middleclass("Color") --- -- @function new -- @tparam number red [0, 1] -- @tparam number green [0, 1] -- @tparam number blue [0, 1] -- @treturn Color function Color:initialize(red, green, blue) assert(typeutils.is_positive_number(red, 1)) assert(typeutils.is_positive_number(green, 1)) assert(typeutils.is_positive_number(blue, 1)) self.red = red self.green = green self.blue = blue end --- -- @treturn {number,number,number} -- red, green and blue values in the range [0, 1] function Color:channels() return {self.red, self.green, self.blue} end return Color
-------------------------------------------------------------------------------------- -- this is the ActionPattern class which extends PlanElement -- -- an ActionPattern is an aggregate defined by: -- -- . unique name identifier -- -- . list of actions in an ordered sequence -- -- . status that is -- -- . IDLE -- -- . RUNNING -- -- . SUCCESS -- -- . FAILURE -- -- -- -- tick() steps through the sequence in order, ticks each action and only: -- -- . moves on to next action when prev action returns SUCCESS -- -- . returns SUCCESS once all actions return SUCCESS -- -- -- -- for more on POSH Action Patterns see: -- -- http://www.cs.bath.ac.uk/~jjb/web/BOD/AgeS02/node10.html -- -------------------------------------------------------------------------------------- ActionPattern = Class{__includes = PlanElement} function ActionPattern:init(name, actions) self.name = name --string name self.actions = actions --list of actions self.status = IDLE -- self.index = 1 end function ActionPattern:tick() for _,action in pairs(self.actions) do self.status = action:tick() --tick child if self.status == FAILURE or self.status ==RUNNING then break end --continue end -- return SUCCESS --return running, failure, or success return self.status --return running, failure, or success end function ActionPattern:oldtick() --print('ticking action pattern', self.name, 'with', #self.actions, 'actions and index is', self.index) if self.index > #self.actions then --all child actions executed with success self.index = 1 -- reset index --print('returning AP success and resetting index to', self.index) return SUCCESS else --otherwise, tick through children local childStatus = IDLE --print('ticking AP child', self.actions[self.index].name) childStatus = self.actions[self.index]:tick() --tick child at current index if childStatus == SUCCESS then --increment index to next child when current child returns success self.index = self.index + 1 --print(self.actions[self.index].name 'returned success and incremented index to', self.index) --status remains running elseif childStatus == RUNNING then --print(self.actions[self.index].name 'returned running and index remains', self.index) return childStatus --index remains on current child elseif childStatus == FAILURE then self.index = 1 -- reset index --print(self.actions[self.index].name 'returned failure and reset index to', self.index) return FAILURE end end end
-- -- Licensed to the Apache Software Foundation (ASF) under one or more -- contributor license agreements. See the NOTICE file distributed with -- this work for additional information regarding copyright ownership. -- The ASF licenses this file to You under the Apache License, Version 2.0 -- (the "License"); you may not use this file except in compliance with -- the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- local encode_json = require("cjson.safe").encode local ngx = ngx local ngx_say = ngx.say local ngx_header = ngx.header local error = error local select = select local type = type local ngx_exit = ngx.exit local insert_tab = table.insert local concat_tab = table.concat local str_sub = string.sub local tonumber = tonumber local _M = {version = 0.1} local resp_exit do local t = {} local idx = 1 function resp_exit(code, ...) idx = 0 if code and type(code) ~= "number" then insert_tab(t, code) code = nil end if code then ngx.status = code end for i = 1, select('#', ...) do local v = select(i, ...) if type(v) == "table" then local body, err = encode_json(v) if err then error("failed to encode data: " .. err, -2) else idx = idx + 1 insert_tab(t, idx, body) end elseif v ~= nil then idx = idx + 1 insert_tab(t, idx, v) end end if idx > 0 then ngx_say(concat_tab(t, "", 1, idx)) end if code then return ngx_exit(code) end end end -- do _M.exit = resp_exit function _M.say(...) resp_exit(nil, ...) end function _M.set_header(...) if ngx.headers_sent then error("headers have already been sent", 2) end for i = 1, select('#', ...), 2 do ngx_header[select(i, ...)] = select(i + 1, ...) end end function _M.get_upstream_status(ctx) -- $upstream_status maybe including mutiple status, only need the last one return tonumber(str_sub(ctx.var.upstream_status or "", -3)) end return _M
-- ============================================================= -- Copyright Roaming Gamer, LLC. 2008-2018 (All Rights Reserved) -- ============================================================= local getTimer = system.getTimer -- == -- fnn( ... ) - Return first argument from list that is not nil. -- ... - Any number of any type of arguments. -- == local function fnn( ... ) for i = 1, #arg do local theArg = arg[i] if(theArg ~= nil) then return theArg end end return nil end -- == -- round(val, n) - Rounds a number to the nearest decimal places. (http://lua-users.org/wiki/FormattingNumbers) -- val - The value to round. -- n - Number of decimal places to round to. -- == local function round(val, n) if (n) then return math.floor( (val * 10^n) + 0.5) / (10^n) else return math.floor(val+0.5) end end if( not _G.ssk ) then _G.ssk = {} end local easyBench = {} _G.ssk.easyBench = easyBench local beginTime = 0 local endTime = 0 easyBench.start = function() beginTime = getTimer() end easyBench.stop = function() endTime = getTimer() end easyBench.getTime = function() return (endTime-beginTime) end easyBench.getMetrics = function( iterations, decimalPlaces ) iterations = iterations or 1 decimalPlaces = decimalPlaces or 2 local ms = (endTime-beginTime) local perMS = iterations/ms local perS = perMS * 1000 return ms, round(ms/1000,decimalPlaces), round(perMS,decimalPlaces), round(perS,decimalPlaces) end -- FROM SIMPLE BENCH local getTimer = system.getTimer local fnn local round -- Functions for measuring execution times -- local function measureExcutionTime( func, iter ) local func = func local startTime local endTime if( iter ) then startTime = getTimer() for i = 1, iter do func() end endTime = getTimer() else startTime = getTimer() func() endTime = getTimer() end return endTime - startTime end local function measureVSTime( func1, func2, iter ) local time1 = measureExcutionTime( func1, iter ) local time2 = measureExcutionTime( func2, iter ) local delta = time1-time2 if( math.abs(delta) < 0.01 ) then return time1, time2, delta, 0 end if( delta > 0 ) then local speedup = round( 1/(delta/time2), 4) * 100 return time1,time2,delta,speedup else local speedup = round( 1/(delta/time1), 4) * 100 return time1,time2,delta,speedup end end -- Functions for measuring memory usage an deltas -- local lastMem local function getMemCount( collect ) local collect = fnn( collect, true ) if( collect ) then collectgarbage( "collect" ) end local curMem = collectgarbage("count") if(lastMem == nil) then lastMem = curMem end local delta = curMem - lastMem lastMem = curMem return curMem,lastMem end -- Helper functions -- local mFloor = math.floor round = function (val, n) if (n) then return mFloor( (val * 10^n) + 0.5) / (10^n) else return mFloor(val+0.5) end end fnn = function ( ... ) for i = 1, #arg do local theArg = arg[i] if(theArg ~= nil) then return theArg end end return nil end --[[ USAGE SAMPLE -- -- -- local round = bench.round local mRand = math.random local subVec = math2d.subVec local angle2Vec = math2d.angle2Vec local angle2Vec2 = math2d.angle2Vec2 local vec2Angle = math2d.vec2Angle local normVec = math2d.normVec local lenVecR = rmath2d.length local mSqrt = math.sqrt local vec = { x = 100, y = 100 } -- Slow version local function test1( iter) for i = 1, 100000 do lenVecR( vec ) end end -- Faster Version local function test2() for i = 1, 100000 do mSqrt(vec.x*vec.x+vec.y*vec.y) end end -- Measuring attempt 1 (one iteration per test) -- local time1,time2,delta,speedup = bench.measureABTime( test1, test2 ) print( "\nSingle run 100,000 calculations.") print( "Test 1: " .. round(time1/1000,2) .. " seconds.") print( "Test 2: " .. round(time2/1000,2) .. " seconds.") print( "Test 2 is " .. speedup .. " percent faster .") if( speedup == 0 ) then print( "Tests may have run too fast to measure appreciable speedup.") end ]] easyBench.measureTime = measureExcutionTime easyBench.measureABTime = measureVSTime easyBench.getMemCount = getMemCount easyBench.round = round return easyBench
-- Definition of the neural network used to learn entity embeddings. -- To run a simple unit test that checks the forward and backward passes, just run : -- th entities/learn_e2v/model_a.lua if not opt then -- unit tests unit_tests = true dofile 'utils/utils.lua' require 'nn' cmd = torch.CmdLine() cmd:option('-type', 'double', 'type: double | float | cuda | cudacudnn') cmd:option('-batch_size', 7, 'mini-batch size (1 = pure stochastic)') cmd:option('-num_words_per_ent', 100, 'num positive words per entity per iteration.') cmd:option('-num_neg_words', 25, 'num negative words in the partition function.') cmd:option('-loss', 'nce', 'nce | neg | is | maxm') cmd:option('-init_vecs_title_words', false, 'whether the entity embeddings should be initialized with the average of title word embeddings. Helps to speed up convergence speed of entity embeddings learning.') opt = cmd:parse(arg or {}) word_vecs_size = 5 ent_vecs_size = word_vecs_size lookup_ent_vecs = nn.LookupTable(100, ent_vecs_size) end -- end unit tests if not unit_tests then ent_vecs_size = word_vecs_size -- Init ents vectors print('\n==> Init entity embeddings matrix. Num ents = ' .. get_total_num_ents()) lookup_ent_vecs = nn.LookupTable(get_total_num_ents(), ent_vecs_size) -- Zero out unk_ent_thid vector for unknown entities. lookup_ent_vecs.weight[unk_ent_thid]:copy(torch.zeros(ent_vecs_size)) -- Init entity vectors with average of title word embeddings. -- This would help speed-up training. if opt.init_vecs_title_words then print('Init entity embeddings with average of title word vectors to speed up learning.') for ent_thid = 1,get_total_num_ents() do local init_ent_vec = torch.zeros(ent_vecs_size) local ent_name = get_ent_name_from_wikiid(get_wikiid_from_thid(ent_thid)) words_plus_stop_words = split_in_words(ent_name) local num_words_title = 0 for _,w in pairs(words_plus_stop_words) do if contains_w(w) then -- Remove stop words. init_ent_vec:add(w2vutils.M[get_id_from_word(w)]:float()) num_words_title = num_words_title + 1 end end if num_words_title > 0 then if num_words_title > 3 then assert(init_ent_vec:norm() > 0, ent_name) end init_ent_vec:div(num_words_title) end if init_ent_vec:norm() > 0 then lookup_ent_vecs.weight[ent_thid]:copy(init_ent_vec) end end end collectgarbage(); collectgarbage(); print(' Done init.') end ---------------- Model Definition -------------------------------- cosine_words_ents = nn.Sequential() :add(nn.ConcatTable() :add(nn.Sequential() :add(nn.SelectTable(1)) :add(nn.SelectTable(2)) -- ctxt words vectors :add(nn.Normalize(2)) :add(nn.View(opt.batch_size, opt.num_words_per_ent * opt.num_neg_words, ent_vecs_size))) :add(nn.Sequential() :add(nn.SelectTable(3)) :add(nn.SelectTable(1)) :add(lookup_ent_vecs) -- entity vectors :add(nn.Normalize(2)) :add(nn.View(opt.batch_size, 1, ent_vecs_size)))) :add(nn.MM(false, true)) :add(nn.View(opt.batch_size * opt.num_words_per_ent, opt.num_neg_words)) model = nn.Sequential() :add(cosine_words_ents) :add(nn.View(opt.batch_size * opt.num_words_per_ent, opt.num_neg_words)) if opt.loss == 'is' then model = nn.Sequential() :add(nn.ConcatTable() :add(model) :add(nn.Sequential() :add(nn.SelectTable(1)) :add(nn.SelectTable(3)) -- unigram distributions at power :add(nn.Log()) :add(nn.View(opt.batch_size * opt.num_words_per_ent, opt.num_neg_words)))) :add(nn.CSubTable()) elseif opt.loss == 'nce' then model = nn.Sequential() :add(nn.ConcatTable() :add(model) :add(nn.Sequential() :add(nn.SelectTable(1)) :add(nn.SelectTable(3)) -- unigram distributions at power :add(nn.MulConstant(opt.num_neg_words - 1)) :add(nn.Log()) :add(nn.View(opt.batch_size * opt.num_words_per_ent, opt.num_neg_words)))) :add(nn.CSubTable()) end --------------------------------------------------------------------------------------------- ------- Cuda conversions: if string.find(opt.type, 'cuda') then model = model:cuda() --- This has to be called always before cudnn.convert end if string.find(opt.type, 'cudacudnn') then cudnn.convert(model, cudnn) end --- Unit tests if unit_tests then print('Network model unit tests:') local inputs = {} inputs[1] = {} inputs[1][1] = correct_type(torch.ones(opt.batch_size * opt.num_words_per_ent * opt.num_neg_words)) -- ctxt words inputs[2] = {} inputs[2][1] = correct_type(torch.ones(opt.batch_size * opt.num_words_per_ent)) -- ent wiki words inputs[3] = {} inputs[3][1] = correct_type(torch.ones(opt.batch_size)) -- ent th ids inputs[3][2] = torch.ones(opt.batch_size) -- ent wikiids -- ctxt word vecs inputs[1][2] = correct_type(torch.ones(opt.batch_size * opt.num_words_per_ent * opt.num_neg_words, word_vecs_size)) inputs[1][3] = correct_type(torch.randn(opt.batch_size * opt.num_words_per_ent * opt.num_neg_words)) local outputs = model:forward(inputs) assert(outputs:size(1) == opt.batch_size * opt.num_words_per_ent and outputs:size(2) == opt.num_neg_words) print('FWD success!') model:backward(inputs, correct_type(torch.randn(opt.batch_size * opt.num_words_per_ent, opt.num_neg_words))) print('BKWD success!') end
-- Copyright 2021 SmartThings -- -- 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 capabilities = require "st.capabilities" --- @type st.zwave.CommandClass local cc = require "st.zwave.CommandClass" --- @type st.zwave.CommandClass.Battery local Battery = (require "st.zwave.CommandClass.Battery")({ version = 1 }) --- @type st.zwave.CommandClass.Configuration local Configuration = (require "st.zwave.CommandClass.Configuration")({ version = 1 }) local EVERSPRING_ILLUMINANCE_FINGERPRINTS = { { manufacturerId = 0x0060, productType = 0x0007, productId = 0x0001 } -- Everspring Illuminance Sensor } --- Determine whether the passed device is everspring_illuminance_sensor --- --- @param driver Driver driver instance --- @param device Device device isntance --- @return boolean true if the device proper, else false local function can_handle_everspring_illuminace_sensor(opts, driver, device, ...) for _, fingerprint in ipairs(EVERSPRING_ILLUMINANCE_FINGERPRINTS) do if device:id_match(fingerprint.manufacturerId, fingerprint.productType, fingerprint.productId) then return true end end return false end local function do_configure(self, device) -- Auto report time interval in minutes device:send(Configuration:Set({parameter_number = 5, size = 2, configuration_value = 20})) -- Auto report lux change threshold device:send(Configuration:Set({parameter_number = 6, size = 2, configuration_value = 30})) end local everspring_illuminance_sensor = { lifecycle_handlers = { doConfigure = do_configure }, NAME = "everspring illuminance sensor", can_handle = can_handle_everspring_illuminace_sensor } return everspring_illuminance_sensor
object_building_mustafar_structures_must_bandit_fence_16m = object_building_mustafar_structures_shared_must_bandit_fence_16m:new { } ObjectTemplates:addTemplate(object_building_mustafar_structures_must_bandit_fence_16m, "object/building/mustafar/structures/must_bandit_fence_16m.iff")
return { entities = { {"electric-mining-drill", {x = 0.5, y = 0.5}, {dir = "west", }}, {"iron-chest", {x = -1.5, y = 0.5}, {items = {["copper-ore"] = {type = "random", min = 1, max = 75}}, }}, }, }
local function not_impl() error("Function not implemented"); end local mime = require "mime"; module "encodings" stringprep = {}; base64 = { encode = mime.b64, decode = not_impl }; --mime.unb64 is buggy with \0 return _M;
setobjecttype("destructables")
--[[ Unit tests for the DBM module of the Lua/APR binding. Author: Peter Odding <peter@peterodding.com> Last Change: June 30, 2011 Homepage: http://peterodding.com/code/lua/apr/ License: MIT --]] local status, apr = pcall(require, 'apr') if not status then pcall(require, 'luarocks.require') apr = require 'apr' end local helpers = require 'apr.test.helpers' local dbmfile = helpers.tmpname() local dbm = assert(apr.dbm_open(dbmfile, 'n')) local dbmkey, dbmvalue = 'the key', 'the value' assert(not dbm:firstkey()) -- nothing there yet assert(dbm:store(dbmkey, dbmvalue)) local function checkdbm() assert(dbm:exists(dbmkey)) assert(dbm:fetch(dbmkey) == dbmvalue) assert(dbm:firstkey() == dbmkey) assert(not dbm:nextkey(dbmkey)) -- only 1 record exists end checkdbm() assert(dbm:close()) local file1, file2 = assert(apr.dbm_getnames(dbmfile)) assert(apr.stat(file1, 'type') == 'file') assert(not file2 or apr.stat(file2, 'type') == 'file') dbm = assert(apr.dbm_open(dbmfile, 'w')) checkdbm() assert(dbm:delete(dbmkey)) assert(not dbm:fetch(dbmkey)) assert(not dbm:firstkey()) -- Test tostring(dbm). assert(tostring(dbm):find '^dbm %([x%x]+%)$') assert(dbm:close()) assert(tostring(dbm):find '^dbm %(closed%)$') -- Cleanup. apr.file_remove(file1) if file2 then apr.file_remove(file2) end
//----------------------------------------------------------------------------------------------- // //shared file for information revolving the ghoul entity // //@author TotallyNotLuna/luna/StudioNightly //@version 21/4/18 //----------------------------------------------------------------------------------------------- ENT.Base = "base_nextbot" ENT.Spawnable = true ENT.AdminSpawnable = true ENT.Author = "Luna <3" ENT.Category = "Moon Bots" ENT.PrintName = "Glowing One" ENT.Instructions = "Shinnny O.o" function ENT:SetupDataTables() self:NetworkVar("Float",0,"HairColor") self:NetworkVar("Float",1,"BodyColorR") self:NetworkVar("Float",2,"BodyColorG") self:NetworkVar("Float",3,"BodyColorB") end
local skynet = require "skynet" require "skynet.manager" local httpc = require "http.httpc" local dns = require "dns" local cjson = require "cjson" local function request(host, url, msg) local content = cjson.encode(msg) local header = {} local respheader = {} local status, body = httpc.request("post", host, url, respheader, header,content) if status ~= 200 then return {} end return cjson.decode(body) end local CMD = {} function CMD.post(host, url, msg) print(host, url, msg) return request(host, url, msg) end skynet.start(function() httpc.dns() -- set dns server httpc.timeout = 100 -- set timeout 1 second skynet.dispatch("lua", function(_, _, cmd, ...) local f = CMD[cmd] if f then skynet.ret(skynet.pack(f(...))) end end) skynet.register("httpclient") end)
---@class hmultiBoard 多面板/多列榜 hmultiBoard = {} --- 根据玩家创建多面板 --- 多面板是可以每个玩家看到的都不一样的 --- yourData会返回当前的多面板和玩家索引 --- 你需要设置数据传回到create中来,拼凑多面板数据,二维数组,行列模式 ---@alias hmultiBoard fun(whichBoard: userdata,playerIndex:number):void ---@param key string 多面板唯一key ---@param refreshFrequency number 刷新频率 ---@param yourData hmultiBoard | "function(whichBoard,playerIndex) return {{value = "标题",icon = "图标"}} end" hmultiBoard.create = function(key, refreshFrequency, yourData) --判断玩家各自的多面板属性 for pi = 1, hplayer.qty_max, 1 do local p = hplayer.players[pi] if (his.playing(p)) then local pmb = hcache.get(p, CONST_CACHE.PLAYER_MULTI_BOARD) if (pmb == nil) then pmb = { visible = true, timer = nil, boards = {} } hcache.set(p, CONST_CACHE.PLAYER_MULTI_BOARD, pmb) end if (pmb.boards[key] ~= nil) then cj.DestroyMultiboard(pmb.boards[key]) end pmb.boards[key] = cj.CreateMultiboard() --title cj.MultiboardSetTitleText(pmb.boards[key], "多面板") -- pmb.timer = htime.setInterval(refreshFrequency, function() --检查玩家是否隐藏了多面板 -mbv if (pmb.visible ~= true) then if (cj.GetLocalPlayer() == p) then cj.MultiboardDisplay(pmb.boards[key], false) end --而且隐藏就没必要展示数据了,后续流程中止 return end local data = yourData(pmb.boards[key], pi) local totalRow = #data local totalCol = 0 if (totalRow > 0) then totalCol = #data[1] end if (totalRow <= 0 or totalCol <= 0) then print_err("Multiboard:-totalRow -totalCol") return end --设置行列数 cj.MultiboardSetRowCount(pmb.boards[key], totalRow) cj.MultiboardSetColumnCount(pmb.boards[key], totalCol) local widthCol = {} for row = 1, totalRow, 1 do for col = 1, totalCol, 1 do local item = cj.MultiboardGetItem(pmb.boards[key], row - 1, col - 1) local isSetValue = false local isSetIcon = false local width = 0 local valueType = type(data[row][col].value) if (valueType == "string" or valueType == "number") then isSetValue = true if (valueType == "number") then data[row][col].value = tostring(data[row][col].value) end width = width + string.mb_len(data[row][col].value) if ((row - 1) == pi) then data[row][col].value = hcolor.yellow(data[row][col].value) end cj.MultiboardSetItemValue(item, data[row][col].value) end if (type(data[row][col].icon) == "string") then isSetIcon = true cj.MultiboardSetItemIcon(item, data[row][col].icon) width = width + 3 end cj.MultiboardSetItemStyle(item, isSetValue, isSetIcon) if (widthCol[col] == nil) then widthCol[col] = 0 end if (width > widthCol[col]) then widthCol[col] = width end end end for row = 1, totalRow, 1 do for col = 1, totalCol, 1 do cj.MultiboardSetItemWidth( cj.MultiboardGetItem(pmb.boards[key], row - 1, col - 1), widthCol[col] / 140 ) end end --显示 if (cj.GetLocalPlayer() == p) then cj.MultiboardDisplay(pmb.boards[key], true) end end) end end end --- 设置标题 ---@param whichBoard userdata ---@param title string hmultiBoard.setTitle = function(whichBoard, title) cj.MultiboardSetTitleText(whichBoard, title) end
local Player = game.Players.LocalPlayer if Player:FindFirstChild("BaseDataLoaded") then script.Parent:Destroy() else local module = require(script.Parent.LoadGuiScript) script.Parent.Contents.Visible = true module.init() end
local customize_layout = {} customize_layout.initialize_custom_layout = function () local screen = mouse.screen screen.tags[1].master_width_factor = 0.20 screen.tags[2].master_width_factor = 0.20 screen.tags[1]:view_only() -- To set a layout per tag: -- screen.tags[2].layout = awful.layout.suit.tile.bottom end return customize_layout -- vim: ft=lua sts=2 sw=2
-- 22.01.13 Changed texture to that of the wood from the minimal development game local S = cottages.S minetest.register_node("cottages:fence_small", { description = S("small fence"), drawtype = "nodebox", -- top, bottom, side1, side2, inner, outer tiles = {"cottages_minimal_wood.png"}, paramtype = "light", paramtype2 = "facedir", groups = {snappy=2,choppy=2,oddly_breakable_by_hand=2}, node_box = { type = "fixed", fixed = { { -0.45, -0.35, 0.46, 0.45, -0.20, 0.50}, { -0.45, 0.00, 0.46, 0.45, 0.15, 0.50}, { -0.45, 0.35, 0.46, 0.45, 0.50, 0.50}, { -0.50, -0.50, 0.46, -0.45, 0.50, 0.50}, { 0.45, -0.50, 0.46, 0.50, 0.50, 0.50}, }, }, selection_box = { type = "fixed", fixed = { { -0.50, -0.50, 0.4, 0.50, 0.50, 0.5}, }, }, is_ground_content = false, }) minetest.register_node("cottages:fence_corner", { description = S("small fence corner"), drawtype = "nodebox", -- top, bottom, side1, side2, inner, outer tiles = {"cottages_minimal_wood.png"}, paramtype = "light", paramtype2 = "facedir", groups = {snappy=2,choppy=2,oddly_breakable_by_hand=2}, node_box = { type = "fixed", fixed = { { -0.45, -0.35, 0.46, 0.45, -0.20, 0.50}, { -0.45, 0.00, 0.46, 0.45, 0.15, 0.50}, { -0.45, 0.35, 0.46, 0.45, 0.50, 0.50}, { -0.50, -0.50, 0.46, -0.45, 0.50, 0.50}, { 0.45, -0.50, 0.46, 0.50, 0.50, 0.50}, { 0.46, -0.35, -0.45, 0.50, -0.20, 0.45}, { 0.46, 0.00, -0.45, 0.50, 0.15, 0.45}, { 0.46, 0.35, -0.45, 0.50, 0.50, 0.45}, { 0.46, -0.50, -0.50, 0.50, 0.50, -0.45}, { 0.46, -0.50, 0.45, 0.50, 0.50, 0.50}, }, }, selection_box = { type = "fixed", fixed = { { -0.50, -0.50,-0.5, 0.50, 0.50, 0.5}, }, }, is_ground_content = false, }) minetest.register_node("cottages:fence_end", { description = S("small fence end"), drawtype = "nodebox", -- top, bottom, side1, side2, inner, outer tiles = {"cottages_minimal_wood.png"}, paramtype = "light", paramtype2 = "facedir", groups = {snappy=2,choppy=2,oddly_breakable_by_hand=2}, node_box = { type = "fixed", fixed = { { -0.45, -0.35, 0.46, 0.45, -0.20, 0.50}, { -0.45, 0.00, 0.46, 0.45, 0.15, 0.50}, { -0.45, 0.35, 0.46, 0.45, 0.50, 0.50}, { -0.50, -0.50, 0.46, -0.45, 0.50, 0.50}, { 0.45, -0.50, 0.46, 0.50, 0.50, 0.50}, { 0.46, -0.35, -0.45, 0.50, -0.20, 0.45}, { 0.46, 0.00, -0.45, 0.50, 0.15, 0.45}, { 0.46, 0.35, -0.45, 0.50, 0.50, 0.45}, { 0.46, -0.50, -0.50, 0.50, 0.50, -0.45}, { 0.46, -0.50, 0.45, 0.50, 0.50, 0.50}, { -0.50, -0.35, -0.45, -0.46, -0.20, 0.45}, { -0.50, 0.00, -0.45, -0.46, 0.15, 0.45}, { -0.50, 0.35, -0.45, -0.46, 0.50, 0.45}, { -0.50, -0.50, -0.50, -0.46, 0.50, -0.45}, { -0.50, -0.50, 0.45, -0.46, 0.50, 0.50}, }, }, selection_box = { type = "fixed", fixed = { { -0.50, -0.50,-0.5, 0.50, 0.50, 0.5}, }, }, is_ground_content = false, }) minetest.register_craft({ output = "cottages:fence_small 3", recipe = { {cottages.craftitem_fence, cottages.craftitem_fence}, } }) -- xfences can be configured to replace normal fences - which makes them uncraftable if ( minetest.get_modpath("xfences") ~= nil ) then minetest.register_craft({ output = "cottages:fence_small 3", recipe = { {"xfences:fence","xfences:fence" }, } }) end minetest.register_craft({ output = "cottages:fence_corner", recipe = { {"cottages:fence_small","cottages:fence_small" }, } }) minetest.register_craft({ output = "cottages:fence_small 2", recipe = { {"cottages:fence_corner" }, } }) minetest.register_craft({ output = "cottages:fence_end", recipe = { {"cottages:fence_small","cottages:fence_small", "cottages:fence_small" }, } }) minetest.register_craft({ output = "cottages:fence_small 3", recipe = { {"cottages:fence_end" }, } })
local torchxtest = {} local precision_forward = 1e-6 local precision_backward = 1e-6 local nloop = 50 local mytester --e.g. usage: th -ltorchx -e "torchx.test{'treemax','find'}" function torchxtest.treemax() local treeSize = {3,3,2} -- 13,14,25 18 = 3x3x2 -- 6,7,12 6 = 3x2 -- 7,5 2 = 2 local tensor = torch.Tensor{0,0,0,0,0,13, 1,1,1,1,1,10, 0,6, 2,5, 7,5} local maxVal, maxIdx = torch.treemax(tensor, treeSize) mytester:assert(maxVal == 7, "treemax maxVal 1") mytester:assert(maxIdx == 17, "treemax maxIdx 1") -- 27,14,25 local tensor = torch.Tensor{0,0,0,0,0,27, 1,1,1,1,1,10, 0,6, 2,5, 7,5} local maxVal, maxIdx = torch.treemax(tensor, treeSize) mytester:assert(maxVal == 27, "treemax maxVal 2") mytester:assert(maxIdx == 6, "treemax maxIdx 2") end function torchxtest.find() local tensor = torch.Tensor{1,2,3,4,5,6,0.6,0,2} local indice = torch.LongTensor(torch.find(tensor, 2)) mytester:assertTensorEq(indice, torch.LongTensor{2,9}, 0.00001, "find (1D) err") local tensor = torch.Tensor{{1,2,3,4,5},{5,6,0.6,0,2}} local indice = torch.find(tensor, 2) mytester:assertTableEq(indice, {2,10}, 0.00001, "find (2D) err") local indice = torch.find(tensor:t(), 2) mytester:assertTableEq(indice, {3,10}, 0.00001, "find (2D transpose) err A") local indice = torch.find(tensor:t(), 5) mytester:assertTableEq(indice, {2,9}, 0.00001, "find (2D transpose) err B") local indice = torch.find(tensor, 2, 2) mytester:assertTableEq(indice, {{2},{5}}, 0.00001, "find (2D row-wise) err") end function torchxtest.remap() local a, b, c, d = torch.randn(3,4), torch.randn(3,4), torch.randn(2,4), torch.randn(1) local e, f, g, h = torch.randn(3,4), torch.randn(3,4), torch.randn(2,4), torch.randn(1) local t1 = {a:clone(), {b:clone(), c:clone(), {d:clone()}}} local t2 = {e:clone(), {f:clone(), g:clone(), {h:clone()}}} torch.remap(t1, t2, function(x, y) x:add(y) end) mytester:assertTensorEq(a:add(e), t1[1], 0.000001, "error remap a add") mytester:assertTensorEq(b:add(f), t1[2][1], 0.000001, "error remap b add") mytester:assertTensorEq(c:add(g), t1[2][2], 0.000001, "error remap c add") mytester:assertTensorEq(d:add(h), t1[2][3][1], 0.000001, "error remap d add") local __, t3 = torch.remap(t2, nil, function(x, y) y:resizeAs(x):copy(x) end) mytester:assertTensorEq(e, t3[1], 0.000001, "error remap e copy") mytester:assertTensorEq(f, t3[2][1], 0.000001, "error remap f copy") mytester:assertTensorEq(g, t3[2][2], 0.000001, "error remap g copy") mytester:assertTensorEq(h, t3[2][3][1], 0.000001, "error remap h copy") local t4, __ = torch.remap(nil, t2, function(x, y) x:resize(y:size()):copy(y) end, torch.LongTensor()) mytester:assert(torch.type(t4[1]) == 'torch.LongTensor', "error remap e copy") mytester:assert(torch.type(t4[2][1]) == 'torch.LongTensor', "error remap f copy") mytester:assert(torch.type(t4[2][2]) == 'torch.LongTensor', "error remap g copy") mytester:assert(torch.type(t4[2][3][1]) == 'torch.LongTensor', "error remap h copy") end function torchxtest.group() local tensor = torch.Tensor{3,4,5,1,2, 5,3,2,1,3, 5,2,3} local groups, val, idx = torch.group(tensor) mytester:assert(groups[1].idx:size(1) == 2) mytester:assert(groups[2].idx:size(1) == 3) mytester:assert(groups[3].idx:size(1) == 4) mytester:assert(groups[4].idx:size(1) == 1) mytester:assert(groups[5].idx:size(1) == 3) local tensor2 = tensor:index(1, torch.randperm(tensor:size(1)):long()) local val2, idx2 = torch.Tensor(), idx:clone() local groups = torch.group(val2, idx2, tensor2) mytester:assert(groups[1].idx:size(1) == 2) mytester:assert(groups[2].idx:size(1) == 3) mytester:assert(groups[3].idx:size(1) == 4) mytester:assert(groups[4].idx:size(1) == 1) mytester:assert(groups[5].idx:size(1) == 3) mytester:assertTensorEq(val, val2, 0.00001) mytester:assertTensorNe(idx2, idx, 0.00001) -- this was failing for me local tensor = torch.Tensor{1,2,0} local groups, val, idx = torch.group(tensor) mytester:assert(groups[1] and groups[2] and groups[0]) end function torchxtest.concat() local tensors = {torch.randn(3,4), torch.randn(3,6), torch.randn(3,8)} local res = torch.concat(tensors, 2) local res2 = torch.Tensor(3,4+6+8) res2:narrow(2,1,4):copy(tensors[1]) res2:narrow(2,5,6):copy(tensors[2]) res2:narrow(2,11,8):copy(tensors[3]) mytester:assertTensorEq(res,res2,0.00001) local tensors = {torch.randn(2,3,4), torch.randn(2,3,6), torch.randn(2,3,8)} local res = torch.concat(tensors, 3) local res2 = torch.Tensor(2,3,4+6+8) res2:narrow(3,1,4):copy(tensors[1]) res2:narrow(3,5,6):copy(tensors[2]) res2:narrow(3,11,8):copy(tensors[3]) mytester:assertTensorEq(res,res2,0.00001) res:zero():concat(tensors, 3) mytester:assertTensorEq(res,res2,0.00001) end function torchxtest.AliasMultinomial() local probs = torch.Tensor(10):uniform(0,1) probs:div(probs:sum()) local a = torch.Timer() local am = torch.AliasMultinomial(probs) print("setup in "..a:time().real.." seconds") a:reset() am:draw() print("draw in "..a:time().real.." seconds") local output = torch.LongTensor(1000, 1000) a:reset() am:batchdraw(output) print("batchdraw in "..a:time().real.." seconds") local counts = torch.Tensor(10):zero() output:apply(function(x) counts[x] = counts[x] + 1 end) counts:div(counts:sum()) mytester:assertTensorEq(probs, counts, 0.001) end function torchxtest.MultiCudaTensor() if not pcall(function() require 'cutorch' end) then return end if cutorch.getDeviceCount() < 2 then return end local origdevice = cutorch.getDevice() local inputsize, outputsize = 200, 100 local weight = torch.CudaTensor(inputsize, outputsize):uniform(0,1) local tensors = { cutorch.withDevice(1, function() return weight[{{},{1, outputsize/2}}]:clone() end), cutorch.withDevice(2, function() return weight[{{},{(outputsize/2)+1, outputsize}}]:clone() end) } local mweight = torch.MultiCudaTensor(2, tensors) mytester:assert(mweight.catdim == 2) -- test size mytester:assertTableEq(mweight:size():totable(), {inputsize, outputsize}, 0.000001) mytester:assert(mweight:size(1) == inputsize) mytester:assert(mweight:size(2) == outputsize) -- test dim mytester:assert(mweight:dim() == 2) -- test transpose local mwt = mweight:t() mytester:assert(mwt.catdim == 1) mytester:assertTableEq(mwt:size():totable(), {outputsize, inputsize}, 0.000001) -- test index local nindex = 3 local res = torch.CudaTensor() local indices = torch.LongTensor(nindex):random(1,inputsize):cuda() mweight.index(res, mweight, 1, indices) local res2 = torch.CudaTensor() weight.index(res2, weight, 1, indices) mytester:assert(res:getDevice() == res2:getDevice()) mytester:assertTensorEq(res, res2, 0.00001) mytester:assertTensorEq(weight[{{},{1, outputsize/2}}]:float(), mweight.tensors[1]:float(), 0.00001) mytester:assertTensorEq(weight[{{},{(outputsize/2)+1, outputsize}}]:float(), mweight.tensors[2]:float(), 0.00001) -- test indexAdd local src = torch.CudaTensor(nindex, outputsize):fill(1) weight:indexAdd(1, indices, src) mweight:indexAdd(1, indices, src) mytester:assertTensorEq(weight[{{},{1, outputsize/2}}]:float(), mweight.tensors[1]:float(), 0.00001) mytester:assertTensorEq(weight[{{},{(outputsize/2)+1, outputsize}}]:float(), mweight.tensors[2]:float(), 0.00001) -- test add (updateParameters) mweight:add(1, mweight) weight:add(1, weight) mytester:assertTensorEq(weight[{{},{1, outputsize/2}}]:float(), mweight.tensors[1]:float(), 0.00001) mytester:assertTensorEq(weight[{{},{(outputsize/2)+1, outputsize}}]:float(), mweight.tensors[2]:float(), 0.00001) -- test mul (updateGradParameters) mweight:mul(2) weight:mul(2) mytester:assertTensorEq(weight[{{},{1, outputsize/2}}]:float(), mweight.tensors[1]:float(), 0.00001) mytester:assertTensorEq(weight[{{},{(outputsize/2)+1, outputsize}}]:float(), mweight.tensors[2]:float(), 0.00001) -- test addmm local input = torch.CudaTensor(5, outputsize):uniform(0,1) local output = torch.CudaTensor(5, inputsize):zero() mweight.addmm(output, 0, output, 1, input, mweight:t()) local output2 = output:clone():zero() weight.addmm(output2, 0, output2, 1, input, weight:t()) mytester:assertTensorEq(output, output2, 0.0001) -- test norm local norm = mweight:norm() local norm2 = weight:norm() mytester:assert(math.abs(norm - norm2) < 0.0001) -- test zero mweight:zero() for i=1,2 do cutorch.withDevice(i, function() mytester:assert(mweight.tensors[i]:sum() == 0) end) end -- test clone local mw2 = mweight:clone() mytester:assert(mw2.tensors[1]:getDevice() == mweight.tensors[1]:getDevice()) mytester:assert(mw2.tensors[2]:getDevice() == mweight.tensors[2]:getDevice()) cutorch.withDevice(1, function() mytester:assertTensorEq(mw2.tensors[1], mweight.tensors[1], 0.000001) end) cutorch.withDevice(2, function() mytester:assertTensorEq(mw2.tensors[2], mweight.tensors[2], 0.000001) end) -- test resizeAs mw2.tensors[1]:resize(mw2.tensors[1]:size(1)/2, mw2.tensors[1]:size(2)) mw2.tensors[2]:resize(mw2.tensors[2]:size(1)/2, mw2.tensors[2]:size(2)) mw2:resizeAs(mweight) mytester:assertTableEq(mw2.tensors[1]:size():totable(), mweight.tensors[1]:size():totable(), 0.000001) mytester:assertTableEq(mw2.tensors[2]:size():totable(), mweight.tensors[2]:size():totable(), 0.000001) cutorch.withDevice(1, function() mytester:assertTensorEq(mw2.tensors[1], mweight.tensors[1], 0.000001) end) cutorch.withDevice(2, function() mytester:assertTensorEq(mw2.tensors[2], mweight.tensors[2], 0.000001) end) -- test copy cutorch.withDevice(1, function() mweight.tensors[1]:uniform(0,1) end) cutorch.withDevice(2, function() mweight.tensors[2]:uniform(0,1) end) mw2:copy(mweight) cutorch.withDevice(1, function() mytester:assertTensorEq(mw2.tensors[1], mweight.tensors[1], 0.000001) end) cutorch.withDevice(2, function() mytester:assertTensorEq(mw2.tensors[2], mweight.tensors[2], 0.000001) end) -- test uniform mw2:uniform(-2, -1) cutorch.withDevice(1, function() mytester:assert(mw2.tensors[1]:min() >= -2 and mw2.tensors[1]:max() <= -1) end) cutorch.withDevice(2, function() mytester:assert(mw2.tensors[2]:min() >= -2 and mw2.tensors[2]:max() <= -1) end) mytester:assert(cutorch.getDevice() == origdevice) end function torchx.test(tests) local oldtype = torch.getdefaulttensortype() torch.setdefaulttensortype('torch.FloatTensor') math.randomseed(os.time()) mytester = torch.Tester() mytester:add(torchxtest) mytester:run(tests) torch.setdefaulttensortype(oldtype) end
// Generated by github.com/davyxu/tabtoy // Version: 2.8.10 module table { export var TMapEventRefresh : table.ITMapEventRefreshDefine[] = [ { Id : 1, TypeRand : [ "1001-500", "1002-500", "1003-500", "2001-500", "2002-500", "3001-100", "3002-100" ], RangeMin : 0, RangeMax : 1000, Num : 3 }, { Id : 2, TypeRand : [ "1001-500", "1002-500", "1003-500", "2001-500", "2002-500", "3001-100", "3002-100" ], RangeMin : 1000, RangeMax : 2000, Num : 5 }, { Id : 3, TypeRand : [ "1001-500", "1002-500", "1003-500", "2001-500", "2002-500", "3001-100", "3002-100" ], RangeMin : 2000, RangeMax : 4000, Num : 7 }, { Id : 4, TypeRand : [ "1001-500", "1002-500", "1003-500", "2001-500", "2002-500", "3001-100", "3002-100" ], RangeMin : 4000, RangeMax : 6000, Num : 9 }, { Id : 5, TypeRand : [ "1001-500", "1002-500", "1003-500", "2001-500", "2002-500", "3001-100", "3002-100" ], RangeMin : 6000, RangeMax : 10000, Num : 10 } ] // Id export var TMapEventRefreshById : game.Dictionary<table.ITMapEventRefreshDefine> = {} function readTMapEventRefreshById(){ for(let rec of TMapEventRefresh) { TMapEventRefreshById[rec.Id] = rec; } } readTMapEventRefreshById(); }
--[[ Copyright (c) 2016 Technicolor Delivery Technologies, SAS The source code form of this Transformer component is subject to the terms of the Clear BSD license. You can redistribute it and/or modify it under the terms of the Clear BSD License (http://directory.fsf.org/wiki/License:ClearBSD) See LICENSE file for more details. ]] --- The UBUS connection for mappings -- @module transformer.mapper.ubus -- -- Mappings are not allowed (by convention) to create their own UBUS connection. -- They should use this helper to get a shared connection. -- -- So mappings must never require ubus directly. -- -- The typical use in a mapping file is: -- local conn = mapper("ubus").connect() -- -- and then later -- conn:call(...) -- Setup a single ubus connection to share with all mappings. -- Make sure no-one can close the shared connection. -- For event sending we need to use a different connection. -- Otherwise somebody listening for that event on the same -- connection will not receive it (!!). local logger = require("tch.logger") local conn local event_conn do local ubus = require("ubus") -- Override the default UBUS call timeout of 30 seconds to 2 seconds. -- If a UBUS call happens to a daemon while it is being started or stopped, -- this call can hang causing all other Transformer calls to hang as well. conn = ubus.connect(nil, 2) event_conn = ubus.connect() if not conn or not event_conn then error("Failed to connect to ubusd") end local __index = getmetatable(conn).__index __index.close = function() -- just ignore a close request end -- override the call() method to be able to log a message when -- a timeout happens local call = __index.call __index.call = function(_, path, method, ...) local ret, rv = call(conn, path, method, ...) -- Check ubusmsg.h for the possible return code values if not ret and tonumber(rv) == 7 then logger:warning("ubus call timeout on calling %s %s. %s", path, method, debug.traceback()) end return ret, rv end -- override the send() method to -- use the dedicated event connection local send = __index.send __index.send = function(_, ...) send(event_conn, ...) end end local M = {} --- Function to connect to UBUS -- @returns a ubus connection object. function M.connect() return conn end return M
local r = game:service("RunService"); function rv() return 5*math.random()-2.5; end function spawn(spawnTime) local droplet = Instance.new("Part") local headPos = game.Workspace.coffeelord:findFirstChild("Head").Position droplet.Position = Vector3.new(headPos.x, headPos.y-5, headPos.z) droplet.Size = Vector3.new(1, 1, 1) droplet.Velocity = Vector3.new(rv(), 50, rv()) droplet.BrickColor = BrickColor.new(192) droplet.Shape = 0 droplet.Anchored = false droplet.BottomSurface = 0 droplet.TopSurface = 0 droplet.Name = "Droplet" .. spawnTime droplet.Parent = script.Parent droplet.CanCollide = False local delete delete = function(time) if time > spawnTime + 10000000000000000000000000000000000000000000000000000000000000 then droplet.Parent = nil r.Stepped:disconnect(delete) end end r.Stepped:connect(delete) end local nextTime = 0 while true do time = r.Stepped:wait() if time > nextTime then spawn(time) nextTime = time + 0.1 end end
require "module.EtSocket"
local Dropout, Parent = torch.class('nn.Dropout', 'nn.Module') function Dropout:__init(p,v1,inplace) Parent.__init(self) self.p = p or 0.5 self.train = true self.inplace = inplace -- version 2 scales output during training instead of evaluation self.v2 = not v1 if self.p >= 1 or self.p < 0 then error('<Dropout> illegal percentage, must be 0 <= p < 1') end self.noise = torch.Tensor() end function Dropout:updateOutput(input) if self.inplace then self.output:set(input) else self.output:resizeAs(input):copy(input) end if self.p > 0 then if self.train then self.noise:resizeAs(input) self.noise:bernoulli(1-self.p) if self.v2 then self.noise:div(1-self.p) end self.output:cmul(self.noise) elseif not self.v2 then self.output:mul(1-self.p) end end return self.output end function Dropout:updateGradInput(input, gradOutput) if self.inplace then self.gradInput:set(gradOutput) else self.gradInput:resizeAs(gradOutput):copy(gradOutput) end if self.train then if self.p > 0 then self.gradInput:cmul(self.noise) -- simply mask the gradients with the noise vector end else if not self.v2 and self.p > 0 then self.gradInput:mul(1-self.p) end end return self.gradInput end function Dropout:setp(p) self.p = p end function Dropout:__tostring__() return string.format('%s(%f)', torch.type(self), self.p) end function Dropout:clearState() if self.noise then self.noise:set() end return Parent.clearState(self) end
-- If you're not sure your plugin is executing, uncomment the line below and restart Kong -- then it will throw an error which indicates the plugin is being loaded at least. --assert(ngx.get_phase() == "timer", "The world is coming to an end!") -- Grab pluginname from module name local plugin_name = ({...})[1]:match("^kong%.plugins%.([^%.]+)") -- load the base plugin object and create a subclass local plugin = require("kong.plugins.base_plugin"):extend() local kong = kong -- constructor function plugin:new() plugin.super.new(self, plugin_name) -- do initialization here, runs in the 'init_by_lua_block', before worker processes are forked end --------------------------------------------------------------------------------------------- -- In the code below, just remove the opening brackets; `[[` to enable a specific handler -- -- The handlers are based on the OpenResty handlers, see the OpenResty docs for details -- on when exactly they are invoked and what limitations each handler has. -- -- The call to `.super.xxx(self)` is a call to the base_plugin, which does nothing, except logging -- that the specific handler was executed. --------------------------------------------------------------------------------------------- --[[ handles more initialization, but AFTER the worker process has been forked/created. -- It runs in the 'init_worker_by_lua_block' function plugin:init_worker() plugin.super.init_worker(self) -- your custom code here end --]] --[[ runs in the ssl_certificate_by_lua_block handler function plugin:certificate(plugin_conf) plugin.super.certificate(self) -- your custom code here end --]] --[[ runs in the 'rewrite_by_lua_block' (from version 0.10.2+) -- IMPORTANT: during the `rewrite` phase neither the `api` nor the `consumer` will have -- been identified, hence this handler will only be executed if the plugin is -- configured as a global plugin! function plugin:rewrite(plugin_conf) plugin.super.rewrite(self) -- your custom code here end --]] ---[[ runs in the 'access_by_lua_block' function plugin:access(plugin_conf) plugin.super.access(self) local req_headers = kong.request.get_headers() local match, upstream local match_before, match_now = -1 for _, rule in ipairs(plugin_conf.rules) do match = true match_now = 0 for rule_header_name, rule_header_value in pairs(rule.headers) do if req_headers[rule_header_name] ~= rule_header_value then match = false break end match_now = match_now + 1 end if match then upstream = match_now <= match_before and upstream or rule.upstream_name match_before = match_now end end kong.log.inspect(upstream) if upstream then kong.service.set_upstream(upstream) kong.response.set_header("X-Upstream-Name", upstream) end end --]] ---[[ runs in the 'header_filter_by_lua_block' function plugin:header_filter(plugin_conf) plugin.super.header_filter(self) -- your custom code here, for example; end --]] --[[ runs in the 'body_filter_by_lua_block' function plugin:body_filter(plugin_conf) plugin.super.body_filter(self) -- your custom code here end --]] --[[ runs in the 'log_by_lua_block' function plugin:log(plugin_conf) plugin.super.log(self) -- your custom code here end --]] -- set the plugin priority, which determines plugin execution order plugin.PRIORITY = 1000 -- return our plugin object return plugin
-- mod-version:2 -- lite-xl 2.0 local syntax = require "core.syntax" syntax.add { name = "Go", files = { "%.go$" }, comment = "//", patterns = { { pattern = "//.-\n", type = "comment" }, { pattern = { "/%*", "%*/" }, type = "comment" }, { pattern = { '"', '"', '\\' }, type = "string" }, { pattern = { "`", "`", '\\' }, type = "string" }, { pattern = { "'", "'", '\\' }, type = "string" }, { pattern = "0[oO_][0-7]+", type = "number" }, { pattern = "-?0x[%x_]+", type = "number" }, { pattern = "-?%d+_%d", type = "number" }, { pattern = "-?%d+[%d%.eE]*f?", type = "number" }, { pattern = "-?%.?%d+f?", type = "number" }, { pattern = "[%+%-=/%*%^%%<>!~|&]", type = "operator" }, { pattern = ":=", type = "operator" }, { pattern = "[%a_][%w_]*%f[(]", type = "function" }, -- function call { pattern = "func()%s*[%a_][%w_]*()%f[%[(]", type = {"keyword", "function", "normal"} }, -- function statement { pattern = "[%a_][%w_]*", type = "symbol" }, }, symbols = { ["if"] = "keyword", ["else"] = "keyword", ["elseif"] = "keyword", ["for"] = "keyword", ["continue"] = "keyword", ["return"] = "keyword", ["struct"] = "keyword", ["switch"] = "keyword", ["case"] = "keyword", ["default"] = "keyword", ["const"] = "keyword", ["package"] = "keyword", ["import"] = "keyword", ["func"] = "keyword", ["var"] = "keyword", ["type"] = "keyword", ["interface"] = "keyword", ["select"] = "keyword", ["break"] = "keyword", ["range"] = "keyword", ["chan"] = "keyword", ["defer"] = "keyword", ["go"] = "keyword", ["fallthrough"] = "keyword", ["goto"] = "keyword", ["int"] = "keyword2", ["int64"] = "keyword2", ["int32"] = "keyword2", ["int16"] = "keyword2", ["int8"] = "keyword2", ["uint"] = "keyword2", ["uint64"] = "keyword2", ["uint32"] = "keyword2", ["uint16"] = "keyword2", ["uint8"] = "keyword2", ["uintptr"] = "keyword2", ["float64"] = "keyword2", ["float32"] = "keyword2", ["map"] = "keyword2", ["string"] = "keyword2", ["rune"] = "keyword2", ["bool"] = "keyword2", ["byte"] = "keyword2", ["error"] = "keyword2", ["complex64"] = "keyword2", ["complex128"] = "keyword2", ["true"] = "literal", ["false"] = "literal", ["nil"] = "literal", }, }
-- ####################################### -- ## Project: HUD iLife ## -- ## For MTA: San Andreas ## -- ## Name: HudComponent_Scoreboard.lua ## -- ## Author: Noneatme ## -- ## Version: 1.0 ## -- ## License: See top Folder ## -- ####################################### -- FUNCTIONS / METHODS -- local cFunc = {}; -- Local Functions local cSetting = {}; -- Local Settings HudComponent_Scoreboard = {}; HudComponent_Scoreboard.__index = HudComponent_Scoreboard; --[[ ]] -- /////////////////////////////// -- ///// New ////// -- ///// Returns: Object ////// -- /////////////////////////////// function HudComponent_Scoreboard:New(...) local obj = setmetatable({}, {__index = self}); if obj.Constructor then obj:Constructor(...); end return obj; end -- /////////////////////////////// -- ///// GetPlayersInFactioN////// -- ///// Returns: void ////// -- /////////////////////////////// function HudComponent_Scoreboard:GetOnlinePlayerDatas() local iPlayers, iFactionPlayers, iAdmins = 0, 0, 0; for index, player in pairs(getElementsByType("player")) do iPlayers = iPlayers+1; -- ADMINS -- local data = "Adminlevel" if(getElementData(player, data)) then local lvl = tonumber(getElementData(player, data)); if(lvl) and (lvl > 0) and (lvl <= 5) then iAdmins = iAdmins+1; end end -- FRAKTIONSABFRAGE -- data = "Fraktion" if(getElementData(player, data)) then iFactionPlayers = iFactionPlayers+1; end end return self:GetPlayersCount(), iFactionPlayers, iAdmins; end -- /////////////////////////////// -- ///// Render ////// -- ///// Returns: void ////// -- /////////////////////////////// function HudComponent_Scoreboard:Render() if(hud.components[self.sName].enabled ~= 1) then return end; local component_name = self.sName local xo, yo = hud.components[component_name].sx, hud.components[component_name].sy; local wo, ho = hud.components[component_name].width*hud.components[component_name].zoom, hud.components[component_name].height*hud.components[component_name].zoom; local alpha = hud.components[component_name].alpha; local x, y, w, h = xo, yo, wo, ho; dxSetRenderTarget(self.renderTarget, true); dxSetBlendMode("blend") -- Set 'modulate_add' when drawing stuff on the render target local function drawBackground() dxDrawImage(0, 0, wo, ho, self.pfade.images.."background.png", 0, 0, 0, tocolor(255, 255, 255, 255)) end local function drawRectangles() -- Oben dxDrawRectangle(0, 0, w, 35, tocolor(0, 0, 0, 220)); dxDrawLine(0, 35, w, 35, tocolor(0, 0, 0, 255)); -- Unten dxDrawRectangle(0, h-35, w, 35, tocolor(0, 0, 0, 220)); dxDrawLine(0, h-35, w, h-35, tocolor(0, 0, 0, 255)); end local function drawServerInformations() dxSetBlendMode("modulate_add") -- OBEN -- -- UNTEN -- local iPlayers, iFactionPlayers, iAdmins = self:GetOnlinePlayerDatas(); local str = { "#FFFFFFSpieler Online: "..iPlayers, "#FFFFFFZivi: "..self.m_tblFactionPlayers[0], "#0000FFLSPD: "..self.m_tblFactionPlayers[1], "#B3B3B3SpF: "..self.m_tblFactionPlayers[2], "#007D00GS: "..self.m_tblFactionPlayers[3], "#9600E6Ballas: "..self.m_tblFactionPlayers[4], "#E69100LSV: "..self.m_tblFactionPlayers[5], "#0067C7S.A.T: "..self.m_tblFactionPlayers[6], "#878787L.S.M: "..self.m_tblFactionPlayers[7], "#FFFFFFAdmins: "..iAdmins, } local fullString = "" for index, part in ipairs(str) do if (index == 1) then fullString = part else fullString = fullString.."#FFFFFF | "..part; end end dxSetBlendMode("modulate_add") dxDrawText(fullString, 38, h-25, w, h-25, tocolor(255, 255, 255, 255), 0.3, hud.fonts.nunito, "left", "top", false, false, false, true) dxDrawText(_Gsettings.boardURL, 5, h-30, w-5, h-35, tocolor(255, 255, 255, 255), 0.4, hud.fonts.nunito, "right") dxSetBlendMode("blend") -- Image -- dxDrawImage(2, h-33, 32, 32, "res/images/mainmenu/logo_umriss.png", getTickCount()/10) dxDrawImage(2, h-28, 32, 26, "res/images/mainmenu/logo.png") dxSetBlendMode("blend") end local function drawPlayers() local curY = 45; local scale = 1.5; -- haelfte local curYadd = 40/scale; local function drawTitel() dxDrawText("Ping", 7, 7, 0, 0, tocolor(255, 255, 255, 255), 0.4, hud.fonts.nunito); dxDrawText("Spielername", 85, 7, 0, 0, tocolor(255, 255, 255, 255), 0.4, hud.fonts.nunito); dxDrawText("Corporation", 260, 7, 0, 0, tocolor(255, 255, 255, 255), 0.4, hud.fonts.nunito); dxDrawText("Sozialer Status", 460-20, 7, 0, 0, tocolor(255, 255, 255, 255), 0.4, hud.fonts.nunito); dxDrawText("Spielzeit", 610, 7, 0, 0, tocolor(255, 255, 255, 255), 0.4, hud.fonts.nunito); dxDrawText("Info", 730, 7, 0, 0, tocolor(255, 255, 255, 255), 0.4, hud.fonts.nunito); end local function player(index) local player = self.sortedPlayers[index]; if not(player) or not(isElement(player)) or not(getPlayerName(player)) then self:RefreshPlayers() outputConsole("Player "..tostring(player).." not online, refreshing scoreboard"); end local playerOnline = true; if(getElementData(player, "Online") ~= true) then -- playerOnline = false; end local function draw() local function getMinuswertFromWertZwischen0und1(iWert) if(iWert < 0.10) then return 64-((64/6)*1); elseif(iWert < 0.20) then return 64-((64/6)*1); elseif(iWert < 0.30) then return 64-((64/6)*2); elseif(iWert < 0.40) then return 64-((64/6)*3); elseif(iWert < 0.50) then return 64-((64/6)*3); elseif(iWert < 0.60) then return 64-((64/6)*4); elseif(iWert < 0.70) then return 64-((64/6)*4); elseif(iWert < 0.80) then return 64-((64/6)*5); elseif(iWert < 0.90) then return 64-((64/6)*5); elseif(iWert < 1) then return 64-((64/6)*6); end return 64; end -- Linie -- local factionID = tonumber(getElementData(player, "Fraktion")) local color; local alpha = 125; if not(factionID) or (factionID == 0) then color = tocolor(0, 0, 0, alpha); else if(self.factionColors[factionID]) then color = self.factionColors[factionID]; else color = tocolor(0, 0, 0, alpha); end end dxDrawImage(5, curY, w-10, 35/scale, self.pfade.images.."line.png", 0, 0, 0, color); local ping = getPlayerPing(player); local wert = 1-(ping / self.m_iBadPing); if(wert > 1) then wert = 1; end local drawMinusWert = getMinuswertFromWertZwischen0und1(wert); -- Ping -- dxDrawImageSection(7.5*scale, curY+(8/scale), (32/scale)-((drawMinusWert/scale)/2), (32/scale), 0, 0, 64-drawMinusWert, 64, self.pfade.images.."ping.png", 0, 0, 0, tocolor(255, 255, 255, 255)); dxDrawText(getPlayerPing(player), 55/scale, curY+(8/scale), 320/scale, curY+(40/scale), tocolor(255, 255, 255, 255), 0.18/scale, hud.fonts.droidsans, "left", "top", true) -- Name -- local name = getPlayerName(player) dxDrawText(name, 140/scale, curY+(2/scale), 320/scale, curY+(40/scale), tocolor(255, 255, 255, 255), 0.25/scale, hud.fonts.droidsans, "left", "top", true); -- Bild -- local skin = tonumber(getElementData(player, "p:Skin")); if not(skin) then skin = "unknow.jpg" end local file = self.pfade.skins.."unknow.jpg"; if(fileExists(self.pfade.skins..skin..".jpg")) and (playerOnline) then file = self.pfade.skins..skin..".jpg"; end --dxDrawImageSection(100/scale, curY+2, 15, 20, 15, 150, 135, 130, file) dxSetBlendMode("add") dxDrawImage(100/scale, curY+2, 20, 20, file) dxSetBlendMode("modulate_add") -- Fraktion -- local faction = (getElementData(player,"Fraktionsname") or "Verbindet...") local color222 = tocolor(255, 255, 255, 255) if(getElementData(player, "CorporationName")) then faction = (getElementData(player, "CorporationName")) color222 = tocolor(getColorFromString(getElementData(player, "CorporationColor"))) end dxDrawText(faction, 360/scale, curY+(2/scale), 650/scale, curY+(40/scale), color222, 0.25/scale, hud.fonts.droidsans, "left", "top", true); -- Status -- local status = (getElementData(player, "Status") or ""); dxDrawText(status, 630/scale, curY+(2/scale), 900/scale, curY+(40/scale), tocolor(255, 255, 255, 255), 0.25/scale, hud.fonts.droidsans, "left", "top", true); -- Spielzeit -- local spielzeit = ""; if(getElementData(player,"Playtime")) then spielzeit = (math.floor(getElementData(player,"Playtime")/60))..":"..(getElementData(player,"Playtime")%60) end dxDrawText(spielzeit, 910/scale, curY+(2/scale), 1000/scale, curY+(40/scale), tocolor(255, 255, 255, 255), 0.25/scale, hud.fonts.droidsans, "left", "top", true); -- Icons -- dxSetRenderTarget(nil); local icons = self:GetPlayerValidIcons(player) dxSetRenderTarget(self.renderTarget); local curAdX = 0; local increm = 33/scale for index, icon in ipairs(icons) do local file; if(type(icon) ~= "string") then file = icon; else file = self.pfade.images.."icons/"..icon..".png"; end dxSetBlendMode("add") dxDrawImage(1050/scale+curAdX, curY+(2/scale), 32/scale, 32/scale, file, 0, 0, 0, tocolor(255, 255, 255, 250)); dxSetBlendMode("modulate_add") curAdX = curAdX+increm; end end local function variablenPlus() curY = curY+curYadd; end -- DRAW -- dxSetBlendMode("modulate_add") draw(); variablenPlus(); dxSetBlendMode("add") end dxSetBlendMode("modulate_add") drawTitel(); for i = self.m_iStartIndex, self.m_iStartIndex+self.m_iMaxIndexToRender, 1 do if(self.sortedPlayers[i]) then player(i); end end dxSetBlendMode("add") end drawBackground(); drawRectangles(); drawServerInformations(); drawPlayers(); dxSetRenderTarget(nil); dxDrawImage(xo, yo, wo, ho, self.renderTarget, 0, 0, 0, tocolor(255, 255, 255, alpha)) end -- /////////////////////////////// -- ///generatePlayerCorpLogo////// -- ///// Returns: void ////// -- /////////////////////////////// function HudComponent_Scoreboard:generatePlayerCorpLogo(uPlayer) local tbl = getElementData(uPlayer, "CorporationLogo"); self.m_tblCorpLogos[uPlayer] = viewCorpGUI:drawLogo(tbl) end -- /////////////////////////////// -- ///// GetPlayerValidIcons////// -- ///// Returns: void ////// -- /////////////////////////////// function HudComponent_Scoreboard:GetPlayerValidIcons(player) local icons = {} local index = 1; local function addIcon(sName) icons[index] = sName; index = index+1; end -- Adminlevel -- if(getElementData(player, "Adminlevel")) and (tonumber(getElementData(player, "Adminlevel"))> 0) and (tonumber(getElementData(player, "Adminlevel")) <= 5) then addIcon("admin"); else addIcon("user") end -- Medal of Honor -- --[[ if(getElementData(player, "VIP")) and (getElementData(player, "VIP") == true) then addIcon("vip"); end--]] -- Faction -- if(getElementData(player, "CorporationLogo")) then if(toboolean(config:getConfig("lowrammode")) ~= true) then if not(self.m_tblCorpLogos[player]) then self:generatePlayerCorpLogo(player) end addIcon(self.m_tblCorpLogos[player]) end end -- Gaengie Icons -- -- Ruhemodus if(getElementData(player, "Ruhemodus")) and (getElementData(player, "Ruhemodus") == true) then addIcon("ruhe"); else if(tonumber(getElementData(player, "Adminlevel")) and (tonumber(getElementData(player, "Adminlevel")) == 4)) then addIcon("ruhe") end end -- AFK -- if(getElementData(player, "p:AFK")) and (getElementData(player, "p:AFK") == true) then addIcon("afk"); end return icons; end -- /////////////////////////////// -- ///// RefreshPlayers ////// -- ///// Returns: void ////// -- /////////////////////////////// function HudComponent_Scoreboard:RefreshPlayers() self.sortedPlayers = {} self.m_tblFactionPlayers = {} for index, l in pairs(self.m_tblCorpLogos) do if(isElement(l)) then destroyElement(l) end end self.m_tblCorpLogos = {} local tblPlayers = getElementsByType("player") local i = 1; -- Sort by Playername if(self.m_sSortBy == "players") then for index, player in ipairs(tblPlayers) do self.sortedPlayers[i] = player; i = i+1; end end -- Sort by Faction if(self.m_sSortBy == "faction") then local playerDone = {} for index = 0, self.m_iMaxFactions, 1 do if not(self.m_tblFactionPlayers[index]) then self.m_tblFactionPlayers[index] = 0 end; for index2, player in pairs(tblPlayers) do if not(playerDone[player]) then if((getElementData(player, "Fraktion")) and (tonumber(getElementData(player, "Fraktion")) == index)) then self.sortedPlayers[i] = player; i = i+1; playerDone[player] = true; self.m_tblFactionPlayers[index] = self.m_tblFactionPlayers[index]+1; else if not((getElementData(player, "Fraktion"))) then playerDone[player] = true; self.sortedPlayers[i] = player; i = i+1; self.m_tblFactionPlayers[0] = self.m_tblFactionPlayers[0]+1; end end end end end for i = 0, self.m_iMaxFactions, 1 do if not(self.m_tblFactionPlayers[i]) then self.m_tblFactionPlayers[i] = 0; end end end -- Sort by Status -- if(self.m_sSortBy == "status") then end if(self.m_iStartIndex+self.m_iMaxIndexToRender > self:GetPlayersCount()) then self.m_iStartIndex = 1; end -- outputConsole("Refreshed Scoreboard Players"); end -- /////////////////////////////// -- ///// Toggle ////// -- ///// Returns: void ////// -- /////////////////////////////// function HudComponent_Scoreboard:Toggle(key, state) local component_name = "scoreboard" local bBool; if(state == "down") then bBool = 1 clientBusy = true; else bBool = 0 clientBusy = false; end if (bBool == nil) then hud.components[component_name].enabled = not (hud.components[component_name].enabled); else hud.components[component_name].enabled = bBool; end -- outputChatBox(tostring(hud.components[component_name].enabled)) if(getTickCount()-self.m_iStartTick > 60000) then self:RefreshPlayers(); self.m_iStartTick = getTickCount(); end end -- /////////////////////////////// -- ///// ScrollUp ////// -- ///// Returns: void ////// -- /////////////////////////////// function HudComponent_Scoreboard:ScrollUp(...) if(hud.components[self.sName].enabled == 1) then if(self.m_iStartIndex > 1) then self.m_iStartIndex = self.m_iStartIndex-1; end end end -- /////////////////////////////// -- ///// ScrollDown ////// -- ///// Returns: void ////// -- /////////////////////////////// function HudComponent_Scoreboard:ScrollDown(...) if(hud.components[self.sName].enabled == 1) then if(self.m_iStartIndex+self.m_iMaxIndexToRender < self:GetPlayersCount()) then self.m_iStartIndex = self.m_iStartIndex+1; end end end -- /////////////////////////////// -- ///// getPlayersCount ////// -- ///// Returns: void ////// -- /////////////////////////////// function HudComponent_Scoreboard:GetPlayersCount() return #self.sortedPlayers; end -- /////////////////////////////// -- ///// SortBy ////// -- ///// Returns: void ////// -- /////////////////////////////// function HudComponent_Scoreboard:SortBy(sString) self.m_sSortBy = sString; self:RefreshPlayers(); end -- /////////////////////////////// -- ///// doUpdate ////// -- ///// Returns: void ////// -- /////////////////////////////// function HudComponent_Scoreboard:doUpdate() end -- /////////////////////////////// -- ///// Constructor ////// -- ///// Returns: void ////// -- /////////////////////////////// function HudComponent_Scoreboard:Constructor(iType) -- Klassenvariablen -- self.sName = "scoreboard" self.toggleFunc = function(...) self:Toggle(...) end self.scrollUp = function(...) self:ScrollUp(...) end self.scrollDown = function(...) self:ScrollDown(...) end self.m_funcRefresh = function(...) self:doUpdate(...) end self.wX = hud.components[self.sName].width; self.wH = hud.components[self.sName].height; self.scoreW, self.scoreH = self.wX, self.wH self.factionColors = { [0] = tocolor(0, 0, 0, 200), -- Zivilist [1] = tocolor(0, 50, 0, 200), -- LSPD [2] = tocolor(0, 50, 50, 200), -- Special Forces [3] = tocolor(0, 90, 10, 200), -- Grove Street [4] = tocolor(50, 0, 80, 200), -- Ballas [5] = tocolor(70, 50, 0, 200), -- Vagos [6] = tocolor(0, 20, 80, 200), -- SAT [7] = tocolor(50, 50, 50, 200), -- Mechaniker } self.m_tblFactionPlayers = {} self.m_tblCorpLogos = {} self.m_iStartIndex = 1; self.m_iMaxIndexToRender = 12; self.m_iMaxFactions = 7; self.m_sSortBy = "faction"; self.m_iBadPing = 500; self.sortedPlayers = {} self.pfade = {} self.pfade.images = "res/images/hud/component_"..self.sName.."/"; self.pfade.skins = "res/images/hud/skins/" self.renderTarget = dxCreateRenderTarget(self.scoreW, self.scoreH, true); self.m_iStartTick = getTickCount(); bindKey("tab", "both", self.toggleFunc) bindKey("mouse_wheel_up", "down", self.scrollUp) bindKey("mouse_wheel_down", "down", self.scrollDown) self:RefreshPlayers(); addCommandHandler("sortby", function(cmd, sT) self.m_sSortBy = sT end) -- outputDebugString("[CALLING] HudComponent_Scoreboard: Constructor"); end -- EVENT HANDLER --
SonLPC=UGen:new{name="SonLPC"} function SonLPC.ar(buff,inp,hop,poles) buff = buff or -1;inp = inp or 0;hop = hop or 0.5;poles = poles or 4 return SonLPC:MultiNew{2,buff,inp,hop,poles} end SonLPCSynth=UGen:new{name="SonLPCSynth"} function SonLPCSynth.ar(chain) chain = chain or -1; return SonLPCSynth:MultiNew{2,chain} end SonLPCError=UGen:new{name="SonLPCError"} function SonLPCError.ar(chain) chain = chain or -1; return SonLPCError:MultiNew{2,chain} end SonLPCSynthInput=UGen:new{name="SonLPCSynthInput"} function SonLPCSynthInput.ar(chain,inp,useG) chain = chain or -1;inp = inp or 0;useG = useG or 0 return SonLPCSynthInput:MultiNew{2,chain,inp,useG} end SonLPCSynthIn=UGen:new{name="SonLPCSynthIn"} function SonLPCSynthIn.ar(chain,inp) chain = chain or -1;inp = inp or 0 return SonLPCSynthIn:MultiNew{2,chain,inp} end SonLPCMorph=UGen:new{name="SonLPCMorph"} function SonLPCMorph.ar(chain, chain2) chain = chain or -1;chain2 = chain2 or -1; return SonLPCMorph:MultiNew{2,chain, chain2} end
-- file: food.lua Food = Object.extend(Object) --- Constructor of a Food class ---@param position table function Food:new(position) self.position = position end --- Execute routines relationed the food elements by transition into frames ---@param dt any function Food:update(dt) end --- Draw elements like a snake food function Food:draw() end --- Realocate a food object on the game plan function MoveFood() local possibleFoodPositions = {} for foodX = 1, GridXCount do for foodY = 1, GridYCount do local possible = true for segmentIndex, segment in ipairs(SnakePlayer.segments) do if foodX == segment.x and foodY == segment.y then possible = false end end if possible then table.insert(possibleFoodPositions, { x = foodX, y = foodY }) end end end FoodObj = Food(possibleFoodPositions[love.math.random(#possibleFoodPositions)]) end
local utils = {} local Log = require "core.log" local uv = vim.loop local api = vim.api -- recursive Print (structure, limit, separator) local function r_inspect_settings(structure, limit, separator) limit = limit or 100 -- default item limit separator = separator or "." -- indent string if limit < 1 then print "ERROR: Item limit reached." return limit - 1 end if structure == nil then io.write("-- O", separator:sub(2), " = nil\n") return limit - 1 end local ts = type(structure) if ts == "table" then for k, v in pairs(structure) do -- replace non alpha keys with ["key"] if tostring(k):match "[^%a_]" then k = '["' .. tostring(k) .. '"]' end limit = r_inspect_settings(v, limit, separator .. "." .. tostring(k)) if limit < 0 then break end end return limit end if ts == "string" then -- escape sequences structure = string.format("%q", structure) end separator = separator:gsub("%.%[", "%[") if type(structure) == "function" then -- don't print functions io.write("-- rvim", separator:sub(2), " = function ()\n") else io.write("rvim", separator:sub(2), " = ", tostring(structure), "\n") end return limit - 1 end function utils.generate_settings() -- Opens a file in append mode local file = io.open("lv-settings.lua", "w") -- sets the default output file as test.lua io.output(file) -- write all `rvim` related settings to `lv-settings.lua` file r_inspect_settings(rvim, 10000, ".") -- closes the open file io.close(file) end -- autoformat function utils.toggle_autoformat() if rvim.format_on_save then require("core.autocmds").define_augroups { autoformat = { { "BufWritePre", "*", ":silent lua vim.lsp.buf.formatting_sync()", }, }, } Log:debug "Format on save active" end if not rvim.format_on_save then vim.cmd [[ if exists('#autoformat#BufWritePre') :autocmd! autoformat endif ]] Log:debug "Format on save off" end end function utils.reload_lv_config() require("core.lualine").config() local config = require "config" config:load() require("keymappings").setup() -- this should be done before loading the plugins vim.cmd("source " .. utils.join_paths(get_runtime_dir(), "rvim", "lua", "plugins.lua")) local plugins = require "plugins" utils.toggle_autoformat() local plugin_loader = require "plugin-loader" plugin_loader:cache_reset() plugin_loader:load { plugins, rvim.plugins } vim.cmd ":PackerInstall" vim.cmd ":PackerCompile" -- vim.cmd ":PackerClean" require("lsp").setup() Log:info "Reloaded configuration" end function utils.unrequire(m) package.loaded[m] = nil _G[m] = nil end function utils.gsub_args(args) if args == nil or type(args) ~= "table" then return args end local buffer_filepath = vim.fn.fnameescape(vim.api.nvim_buf_get_name(0)) for i = 1, #args do args[i] = string.gsub(args[i], "${FILEPATH}", buffer_filepath) end return args end --- Returns a table with the default values that are missing. --- either paramter can be empty. --@param config (table) table containing entries that take priority over defaults --@param default_config (table) table contatining default values if found function utils.apply_defaults(config, default_config) config = config or {} default_config = default_config or {} local new_config = vim.tbl_deep_extend("keep", vim.empty_dict(), config) new_config = vim.tbl_deep_extend("keep", new_config, default_config) return new_config end --- Checks whether a given path exists and is a file. --@param path (string) path to check --@returns (bool) function utils.is_file(path) local stat = uv.fs_stat(path) return stat and stat.type == "file" or false end --- Checks whether a given path exists and is a directory --@param path (string) path to check --@returns (bool) function utils.is_directory(path) local stat = uv.fs_stat(path) return stat and stat.type == "directory" or false end function utils.write_file(path, txt, flag) uv.fs_open(path, flag, 438, function(open_err, fd) assert(not open_err, open_err) uv.fs_write(fd, txt, -1, function(write_err) assert(not write_err, write_err) uv.fs_close(fd, function(close_err) assert(not close_err, close_err) end) end) end) end utils.join_paths = _G.join_paths function utils.write_file(path, txt, flag) uv.fs_open(path, flag, 438, function(open_err, fd) assert(not open_err, open_err) uv.fs_write(fd, txt, -1, function(write_err) assert(not write_err, write_err) uv.fs_close(fd, function(close_err) assert(not close_err, close_err) end) end) end) end function utils.debounce(ms, fn) local timer = vim.loop.new_timer() return function(...) local argv = { ... } timer:start(ms, 0, function() timer:stop() vim.schedule_wrap(fn)(unpack(argv)) end) end end function utils.search_file(file, args) local Job = require "plenary.job" local stderr = {} local stdout, ret = Job :new({ command = "grep", args = { args, file }, cwd = get_cache_dir(), on_stderr = function(_, data) table.insert(stderr, data) end, }) :sync() return stdout, ret, stderr end function utils.file_contains(file, query) local stdout, ret, stderr = utils.search_file(file, query) if ret == 0 then return true end if not vim.tbl_isempty(stderr) then error(vim.inspect(stderr)) end if not vim.tbl_isempty(stdout) then error(vim.inspect(stdout)) end return false end function utils.log_contains(query) local logfile = require("core.log"):get_path() local stdout, ret, stderr = utils.search_file(logfile, query) if ret == 0 then return true end if not vim.tbl_isempty(stderr) then error(vim.inspect(stderr)) end if not vim.tbl_isempty(stdout) then error(vim.inspect(stdout)) end if not vim.tbl_isempty(stderr) then error(vim.inspect(stderr)) end return false end -- TODO: find a new home for these autocommands function utils.nmap_options(key, action, options) api.nvim_set_keymap('n', key, action, options) end function utils.nmap(key, action) utils.nmap_options(key, action, {}) end function utils.imap(key, action) api.nvim_set_keymap('i', key, action, {}) end function utils.vmap(key, action) api.nvim_set_keymap('v', key, action, {}) end function utils.inoremap(key, action) api.nvim_set_keymap('i', key, action, { noremap = true }) end function utils.xnoremap(key, action) api.nvim_set_keymap('x', key, action, { noremap = true }) end function utils.nnoremap(key, action) utils.nmap_options(key, action, { noremap = true, silent= true }) end function utils.noremap(key, action) utils.nmap_options(key, action, { noremap = true }) end function utils.xmap(key, action) api.nvim_set_keymap('x', key, action, {}) end function utils.xnoremap(key, action) api.nvim_set_keymap('x', key, action, { noremap = true }) end function utils.isOneOf(list, x) for _, v in pairs(list) do if v == x then return true end end return false end function _G.plugin_loaded(plugin_name) return false end return utils
------------------------------------------------------------------------------- -- - Vimwiki API - -- Represents module for accessing vimwiki specific functions for easier -- creation of vimwiki reviews ------------------------------------------------------------------------------- local M = {} -- Normalizes passed vimwiki index -- This is meant to be used on user input index where: -- 0 = default vimwiki -- 1 = first vimwiki -- 2 = second vimwiki -- etc.. function M.normalize_vimwiki_index(vimwiki_index) if (vimwiki_index == 0) then local current_index = vim.fn['vimwiki#vars#get_bufferlocal']('wiki_nr') if (current_index < 0) then current_index = 0 end return current_index + 1 else return vimwiki_index end end -- Gets syntax of vimwiki based on passed index function M.get_vimwiki_syntax(vimwiki_index) vimwiki_index = M.normalize_vimwiki_index(vimwiki_index) return vim.g.vimwiki_wikilocal_vars[vimwiki_index]['syntax'] end -- Gets extension of vimwiki based on passed index function M.get_vimwiki_extension(vimwiki_index) vimwiki_index = M.normalize_vimwiki_index(vimwiki_index) return vim.g.vimwiki_wikilocal_vars[vimwiki_index]['ext'] end -- Gets syntax local variable from vimwiki -- Useful for taking templates from vimwiki function M.get_vimwiki_syntaxlocal(key, syntax) if not syntax then syntax = vim.fn['vimwiki#vars#get_wikilocal']['syntax'] end return vim.fn['vimwiki#vars#get_syntaxlocal'](key, syntax) end return M
local SPAWNOBJECT = script:GetCustomProperty("SPAWNOBJECT") local IMPACTSOUND = script:GetCustomProperty("IMPACTSOUND") local WEAPON = script:FindAncestorByType('Weapon') if not WEAPON:IsA('Weapon') then error(script.name .. " should be part of Weapon object hierarchy.") end function Complete( impactTransform ) local impactpos = impactTransform:GetPosition() local impactrot = impactTransform:GetRotation() local Spawn = World.SpawnAsset(SPAWNOBJECT, {position = impactpos, rotation = Rotation.New(0,0,impactrot.z) }) if WEAPON.owner then Spawn:SetNetworkedCustomProperty("Team", WEAPON.owner.team) end end function OnTargetImpactedEvent (weapon, impactData) local impactPosition = impactData:GetHitResult():GetImpactPosition() if IMPACTSOUND then World.SpawnAsset(IMPACTSOUND, {position = impactPosition}) end if Object.IsValid(impactData.projectile) then if impactData.projectile.bouncesRemaining == 0 then Complete(impactData.projectile:GetWorldTransform()) return end end end function OnProjectileSpawned(weapon, projectile) projectile.lifeSpanEndedEvent:Connect(function(destroyedProjectile) Complete(impactData.projectile:GetWorldTransform()) end) end -- Initialize WEAPON.targetImpactedEvent:Connect(OnTargetImpactedEvent) WEAPON.projectileSpawnedEvent:Connect(OnProjectileSpawned)
local integrations = {} for _, v in pairs(script:GetChildren()) do integrations[v.Name] = require(v) end return integrations
local uv = require "lluv" uv.timer():start(100, function() error('SOME_ERROR_MESSAGE') end) local pass = false uv.run(function(msg) print('ERROR MESSAGE:') print(msg) print("-------------------") pass = not not string.find(msg, 'SOME_ERROR_MESSAGE', nil, true) end) if not pass then print('Fail!') os.exit(-1) end print('Done!')
----------------------------------- -- Area: Ship bound for Selbina -- NPC: Rajmonda -- Type: Guild Merchant: Fishing Guild -- !pos 1.841 -2.101 -9.000 220 ----------------------------------- require("scripts/globals/settings") require("scripts/globals/shop") local ID = require("scripts/zones/Ship_bound_for_Selbina/IDs") ----------------------------------- function onTrade(player, npc, trade) end function onTrigger(player, npc) if (player:sendGuild(520, 1, 23, 5)) then player:showText(npc, ID.text.RAJMONDA_SHOP_DIALOG) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) end
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") function ENT.Initialize(self) self:SetModel("models/props_wasteland/laundry_cart002.mdl") self:SetUseType(SIMPLE_USE) self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) self.cooldown = 0 end function ENT:Use(activator, caller) if CurTime() < self.cooldown then return end if self:GetHoldingClothes() <= 0 then return end local ent = ents.Create("xyz_prison_laundry_clothes") ent:SetPos(self:GetPos() + (self:GetUp() * 20)) ent:Spawn() ent:SetDirty(true) self:SetHoldingClothes(self:GetHoldingClothes() - 1) self.cooldown = CurTime() + 1 end function ENT:StartTouch(ent) if CurTime() < self.cooldown then return end -- Check the ent is clothes if not (ent:GetClass() == "xyz_prison_laundry_clothes") then return end -- Check if dirty if not ent.isDirty then return end -- Check if already prepped for deleting if ent.prepDelete then return end -- Check the cart space if self:GetHoldingClothes() >= PrisonSystem.Config.Laundry.CartLimit then return end self:SetHoldingClothes(self:GetHoldingClothes() + 1) ent.prepDelete = true ent:Remove() self.cooldown = CurTime() + 1 end
--- Decoder must take in a image and return a message local adversarialModel = nn.Sequential() --- input dimension batchsize * 3 * 32 * 32 local ConvBNReLU = dofile('./ConvBNReLU.lua') -- ConvBNReLU(adversarialModel, 3, opt.messageLength) if opt.small or opt.grayscale then ConvBNReLU(adversarialModel, 1, opt.adversaryFeatureDepth) else ConvBNReLU(adversarialModel, 3, opt.adversaryFeatureDepth) end for i=1,opt.adversaryConvolutions do ConvBNReLU(adversarialModel, opt.adversaryFeatureDepth, opt.adversaryFeatureDepth) end -- ConvBNReLU(adversarialModel, opt.adversaryFeatureDepth, opt.messageLength) if opt.aveMax then adversarialModel:add(nn.SpatialAveragePooling(opt.maxPoolWindowSize, opt.maxPoolWindowSize, opt.maxPoolStride, opt.maxPoolStride)) adversarialModel:add(nn.SpatialMaxPooling((opt.imageSize - opt.maxPoolWindowSize) / opt.maxPoolStride + 1, (opt.imageSize - opt.maxPoolWindowSize) / opt.maxPoolStride + 1)) end if opt.maxAve then adversarialModel:add(nn.SpatialMaxPooling(opt.maxPoolWindowSize, opt.maxPoolWindowSize, opt.maxPoolStride, opt.maxPoolStride)) adversarialModel:add(nn.SpatialAveragePooling((opt.imageSize - opt.maxPoolWindowSize) / opt.maxPoolStride + 1, (opt.imageSize - opt.maxPoolWindowSize) / opt.maxPoolStride + 1)) end if not opt.maxAve and not opt.aveMax then adversarialModel:add(nn.SpatialAdaptiveAveragePooling(1, 1)) end --- 1 * 1 * opt.adversaryFeatureDepth adversarialModel:add(nn.View(opt.adversaryFeatureDepth):setNumInputDims(3)) adversarialModel:add(nn.Linear(opt.adversaryFeatureDepth,2)) -- adversarialModel:add(nn.Sigmoid()) -- -- adversarialModel:add(nn.View(opt.adversaryFeatureDepth):setNumInputDims(3)) -- adversarialModel:add(nn.Tanh()) --- output dimension batchsize * opt.adversaryFeatureDepth local adv_description = "adversary_large" if opt.aveMax then adv_description = "adversary_ave_max" end if opt.maxAve then adv_description = "adversary_max_ave" end return adversarialModel, adv_description
require "ISUI/ISUIElement" ---@class ISPanelJoypad : ISUIElement ISPanelJoypad = ISUIElement:derive("ISPanelJoypad"); --************************************************************************-- --** ISPanelJoypad:initialise --** --************************************************************************-- function ISPanelJoypad:initialise() ISUIElement.initialise(self); end function ISPanelJoypad:setVisible(visible, joypadData) if visible and joypadData then joypadData.focus = self updateJoypadFocus(joypadData) end ISUIElement.setVisible(self, visible); end function ISPanelJoypad:insertNewLineOfButtons(button1, button2, button3, button4, button5, button6, button7, button8, button9, button10) local newLine = {}; if button1 then table.insert(newLine, button1); end if button2 then table.insert(newLine, button2); end if button3 then table.insert(newLine, button3); end if button4 then table.insert(newLine, button4); end if button5 then table.insert(newLine, button5); end if button6 then table.insert(newLine, button6); end if button7 then table.insert(newLine, button7); end if button8 then table.insert(newLine, button8); end if button9 then table.insert(newLine, button9); end if button10 then table.insert(newLine, button10); end self.joypadButtons = newLine; table.insert(self.joypadButtonsY, newLine); return newLine; end function ISPanelJoypad:insertNewListOfButtons(list) self.joypadButtons = list; table.insert(self.joypadButtonsY, list); end function ISPanelJoypad:insertNewListOfButtonsList(list) self.joypadButtons = list; table.insert(self.joypadButtonsY, list); end function ISPanelJoypad:noBackground() self.background = false; end function ISPanelJoypad:close() self:setVisible(false); end function ISPanelJoypad:setISButtonForA(button) self.ISButtonA = button; button:setJoypadButton(Joypad.Texture.AButton); end function ISPanelJoypad:setISButtonForB(button) self.ISButtonB = button; button:setJoypadButton(Joypad.Texture.BButton); end function ISPanelJoypad:setISButtonForY(button) self.ISButtonY = button; button:setJoypadButton(Joypad.Texture.YButton); end function ISPanelJoypad:setISButtonForX(button) self.ISButtonX = button; button:setJoypadButton(Joypad.Texture.XButton); end function ISPanelJoypad:onJoypadDown(button) local children = self:getVisibleChildren(self.joypadIndexY) local child = children[self.joypadIndex] if button == Joypad.AButton and child and (child.isButton or child.isCombobox or child.isTickBox or child.isKnob or child.isRadioButtons) then child:forceClick(); return; end if button == Joypad.BButton and child and child.isCombobox and child.expanded then child.expanded = false; child:hidePopup(); return; end if button == Joypad.BButton and self.ISButtonB then self.ISButtonB:forceClick(); elseif button == Joypad.AButton and self.ISButtonA then self.ISButtonA:forceClick(); elseif button == Joypad.XButton and self.ISButtonX then self.ISButtonX:forceClick(); elseif button == Joypad.YButton and self.ISButtonY then self.ISButtonY:forceClick(); end end function ISPanelJoypad:getVisibleChildren(joypadIndexY) local children = {} if self.joypadButtonsY[joypadIndexY] then local children1 = self.joypadButtonsY[joypadIndexY] for _,child in ipairs(children1) do if child:isVisible() then table.insert(children, child) end end end return children end function ISPanelJoypad:onJoypadDirLeft(joypadData) local children = self:getVisibleChildren(self.joypadIndexY) local child = children[self.joypadIndex] if child and child.isSlider then child:onJoypadDirLeft(joypadData) elseif #children > 0 and self.joypadIndex > 1 then children[self.joypadIndex]:setJoypadFocused(false, joypadData); self.joypadIndex = self.joypadIndex - 1; children[self.joypadIndex]:setJoypadFocused(true, joypadData); end self:ensureVisible() end function ISPanelJoypad:onJoypadDirRight(joypadData) local children = self:getVisibleChildren(self.joypadIndexY) local child = children[self.joypadIndex] if child and child.isSlider then child:onJoypadDirRight(joypadData) elseif #children > 0 and self.joypadIndex ~= #children then children[self.joypadIndex]:setJoypadFocused(false, joypadData); self.joypadIndex = self.joypadIndex + 1; children[self.joypadIndex]:setJoypadFocused(true, joypadData); end self:ensureVisible() end function ISPanelJoypad:onJoypadDirUp(joypadData) local children = self:getVisibleChildren(self.joypadIndexY) local child = children[self.joypadIndex] if child and child.isCombobox and child.expanded then child:onJoypadDirUp(joypadData) elseif child and child.isRadioButtons and child.joypadIndex > 1 then child:onJoypadDirUp(joypadData) elseif child and child.isTickBox and child.joypadIndex > 1 then child:onJoypadDirUp(joypadData) elseif child and child.isKnob then child:onJoypadDirUp(joypadData) else if #self.joypadButtonsY > 0 and self.joypadIndexY > 1 then child:setJoypadFocused(false, joypadData); self.joypadIndexY = self.joypadIndexY - 1; self.joypadButtons = self.joypadButtonsY[self.joypadIndexY]; children = self:getVisibleChildren(self.joypadIndexY) if self.joypadIndex > #children then self.joypadIndex = #children; end children[self.joypadIndex]:setJoypadFocused(true, joypadData); end end self:ensureVisible() end function ISPanelJoypad:onJoypadDirDown(joypadData) local children = self:getVisibleChildren(self.joypadIndexY) local child = children[self.joypadIndex] if child and child.isCombobox and child.expanded then child:onJoypadDirDown(joypadData) elseif child and child.isRadioButtons and child.joypadIndex < #child.options then child:onJoypadDirDown(joypadData) elseif child and child.isTickBox and child.joypadIndex < #child.options then child:onJoypadDirDown(joypadData) elseif child and child.isKnob then child:onJoypadDirDown(joypadData) else if #self.joypadButtonsY > 0 and self.joypadIndexY ~= #self.joypadButtonsY then child:setJoypadFocused(false, joypadData); self.joypadIndexY = self.joypadIndexY + 1; self.joypadButtons = self.joypadButtonsY[self.joypadIndexY]; children = self:getVisibleChildren(self.joypadIndexY) if self.joypadIndex > #children then self.joypadIndex = #children; end children[self.joypadIndex]:setJoypadFocused(true, joypadData); end end self:ensureVisible() end function ISPanelJoypad:getJoypadFocus() local children = self:getVisibleChildren(self.joypadIndexY) return children[self.joypadIndex] end function ISPanelJoypad:setJoypadFocus(child, joypadData) for indexY,buttons in ipairs(self.joypadButtonsY) do for indexX,button in ipairs(buttons) do if button == child then self:clearJoypadFocus(joypadData) self.joypadIndexY = indexY self.joypadIndex = indexX self.joypadButtons = buttons child:setJoypadFocused(true, joypadData) return end end end end function ISPanelJoypad:restoreJoypadFocus(joypadData) local child = self:getJoypadFocus() if child then child:setJoypadFocused(true, joypadData) end end function ISPanelJoypad:clearJoypadFocus(joypadData) local child = self:getJoypadFocus() if child then child:setJoypadFocused(false, joypadData) end end function ISPanelJoypad:ensureVisible() if not self.joyfocus then return end local children = self:getVisibleChildren(self.joypadIndexY) local child = children[self.joypadIndex] if not child then return end local y = child:getY() if y - 40 < 0 - self:getYScroll() then self:setYScroll(0 - y + 40) elseif y + child:getHeight() + 40 > 0 - self:getYScroll() + self:getHeight() then self:setYScroll(0 - (y + child:getHeight() + 40 - self:getHeight())) end end function ISPanelJoypad:isFocusOnControl() local children = self:getVisibleChildren(self.joypadIndexY) local child = children[self.joypadIndex] if child and child.isCombobox and child.expanded then return true elseif child and child.isRadioButtons and child.joypadIndex > 1 then return true elseif child and child.isTickBox and child.joypadIndex > 1 then return true elseif child and child.isKnob then return true end return false end function ISPanelJoypad:onMouseUp(x, y) if not self.moveWithMouse then return; end if not self:getIsVisible() then return; end self.moving = false; if ISMouseDrag.tabPanel then ISMouseDrag.tabPanel:onMouseUp(x,y); end ISMouseDrag.dragView = nil; end function ISPanelJoypad:onMouseUpOutside(x, y) if not self.moveWithMouse then return; end if not self:getIsVisible() then return; end self.moving = false; ISMouseDrag.dragView = nil; end function ISPanelJoypad:onMouseDown(x, y) if not self.moveWithMouse then return; end if not self:getIsVisible() then return; end self.downX = x; self.downY = y; self.moving = true; self:bringToTop(); end function ISPanelJoypad:onMouseMoveOutside(dx, dy) if not self.moveWithMouse then return; end self.mouseOver = false; if self.moving then self:setX(self.x + dx); self:setY(self.y + dy); self:bringToTop(); end end function ISPanelJoypad:onMouseMove(dx, dy) if not self.moveWithMouse then return; end self.mouseOver = true; if self.moving then self:setX(self.x + dx); self:setY(self.y + dy); self:bringToTop(); --ISMouseDrag.dragView = self; end end --************************************************************************-- --** ISPanelJoypad:render --** --************************************************************************-- function ISPanelJoypad:prerender() if self.background then self:drawRectStatic(0, 0, self.width, self.height, self.backgroundColor.a, self.backgroundColor.r, self.backgroundColor.g, self.backgroundColor.b); self:drawRectBorderStatic(0, 0, self.width, self.height, self.borderColor.a, self.borderColor.r, self.borderColor.g, self.borderColor.b); end end --************************************************************************-- --** ISPanelJoypad:new --** --************************************************************************-- function ISPanelJoypad:new (x, y, width, height) local o = {} --o.data = {} o = ISUIElement:new(x, y, width, height); setmetatable(o, self) self.__index = self o.x = x; o.y = y; o.background = true; o.backgroundColor = {r=0, g=0, b=0, a=0.5}; o.borderColor = {r=0.4, g=0.4, b=0.4, a=1}; o.width = width; o.height = height; o.anchorLeft = true; o.anchorRight = false; o.anchorTop = true; o.anchorBottom = false; o.joypadButtons = {}; o.joypadIndex = 0; o.joypadButtonsY = {}; o.joypadIndexY = 0; o.moveWithMouse = false; return o end
-- get all Dependencies require 'src/Dependencies' --Love Function Load function love.load() --Fonts bebasFont = love.graphics.newFont('fonts/BebasNeue-Regular.ttf', 40) gSounds = { ['BulletShoot'] = love.audio.newSource('Sounds/BulletShoot.wav', 'static') } gImages = { ['targetPng'] = love.graphics.newImage('Images/Target.png'), ['Character'] = love.graphics.newImage('Images/Character.png') } --Randomseed math.randomseed(os.time()) --StateMachine gStateMachine = StateMachine{ --StartScreen Start ['start'] = function() return StartState() end, --Play State ['play'] = function() return PlayState() end, --Victory State ['victory'] = function() return VictoryState() end } --Grapgucs love.graphics.setDefaultFilter('nearest', 'nearest') love.window.setTitle('Unammed') --Push set Virtual Size push:setupScreen(VIRTUAL_WIDTH, VIRTUAL_HEIGHT, WINDOW_WIDTH, WINDOW_HEIGHT, { vsync = true, fullscreen = false, resizable = true }) --Set StateMachine to Start gStateMachine:change('start') --KeyPress Global love.keyboard.keysPressed = {} end --Rezie Function function love.resize(w, h) --Push Rezie Function push:resize(w, h) end --Update Function function love.update(dt) --Get State Machine update gStateMachine:update(dt) --Reset KeysPressed love.keyboard.keysPressed = {} end --Draw Function function love.draw() --Draw in Push virtual Width and Height push:apply('start') --Render StateMachine State Render gStateMachine:render() displayFPS() push:apply('end') end --Get FPS and Display it function displayFPS() -- simple FPS display across all states love.graphics.setFont(bebasFont) love.graphics.setColor(0, 1, 0, 1) love.graphics.print('FPS: ' .. tostring(love.timer.getFPS()), 5, 5) end --Dectet Key press and record in table WasPressed to make global function love.keypressed(key) love.keyboard.keysPressed[key] = true end --Dectet if certain Key was pressed returns true or false function love.keyboard.wasPressed(key) if love.keyboard.keysPressed[key] then return true else return false end end
--[[ ItemSystems.ItemThemes ================ The Customizable properties of the Item System. You can modify item themes and sounds from the ItemTypes or ItemThemes folder in the ItemRegistry folder located in the hierarchy. ]] local Item = script:GetCustomProperty("Item") local ITEM_THEME_FOLDER = script:GetCustomProperty("ItemThemeFolder"):WaitForObject() local ITEM_TYPES_FOLDER = script:GetCustomProperty("ItemTypesFolder"):WaitForObject() local RARITY_COLORS = {} local RARITY_INDICATORS = {} local ITEM_SFX = {} -- local ITEM_SFX = { -- Armor = script:GetCustomProperty("SFX_EquipArmor"), -- Axe = script:GetCustomProperty("SFX_EquipAxe"), -- Boots = script:GetCustomProperty("SFX_EquipBoots"), -- Dagger = script:GetCustomProperty("SFX_EquipDagger"), -- Greatsword = script:GetCustomProperty("SFX_EquipGreatsword"), -- Focus = script:GetCustomProperty("SFX_EquipFocus"), -- Helmet = script:GetCustomProperty("SFX_EquipHelmet"), -- Mace = script:GetCustomProperty("SFX_EquipMace"), -- Shield = script:GetCustomProperty("SFX_EquipShield"), -- Staff = script:GetCustomProperty("SFX_EquipStaff"), -- Sword = script:GetCustomProperty("SFX_EquipSword"), -- Trinket = script:GetCustomProperty("SFX_EquipTrinket"), -- Warhammer = script:GetCustomProperty("SFX_EquipWarhammer"), -- Wand = script:GetCustomProperty("SFX_EquipWand"), -- Misc = script:GetCustomProperty("SFX_MiscPickup"), -- Consumable = script:GetCustomProperty("SFX_ConsumablePickup"), -- } for _, rarity in pairs(ITEM_THEME_FOLDER:GetChildren()) do local rarityName = rarity.name local rarityColor = rarity:GetCustomProperty("RarityColor") local lootDropIndiactor = rarity:GetCustomProperty("LootRarityIndicator") assert(rarityColor, string.format("%s in ItemRarities folder is missing RarityColor custom property.", rarityName)) RARITY_COLORS[rarityName] = rarityColor RARITY_INDICATORS[rarityName] = lootDropIndiactor end for _, type in pairs(ITEM_TYPES_FOLDER:GetChildren()) do local typeName = type.name local typeSFX = type:GetCustomProperty("EquipSFX") assert(typeSFX,string.format("%s in ItemTypes does not have a EquipSFX custom property.",typeName)) ITEM_SFX[typeName] = typeSFX end local STAT_ICONS = { Health = script:GetCustomProperty("StatIconHealth"), HealthPercent = script:GetCustomProperty("StatIconHealth"), Defense = script:GetCustomProperty("StatIconDefense"), Attack = script:GetCustomProperty("StatIconAttack"), Magic = script:GetCustomProperty("StatIconMagic"), CritChance = script:GetCustomProperty("StatIconCritChance"), Haste = script:GetCustomProperty("StatIconHaste"), CDR = script:GetCustomProperty("StatIconCDR"), Tenacity = script:GetCustomProperty("StatIconTenacity"), Value = script:GetCustomProperty("StatIconValue"), } local ITEM_STAT_FORMATS = { Health = "+%d", HealthPercent = "+%d%%", Defense = "+%d", Attack = "+%d", Magic = "+%d", CritChance = "+%d%%", Haste = "+%d%%", CDR = "+%d%%", Tenacity = "+%d%%", Value = "+%d", } local PLAYER_STAT_FORMATS = { Health = "%d", Defense = "%d", Attack = "%d", Magic = "%d", CritChance = "%d%%", Haste = "%d%%", CDR = "%d%%", Tenacity = "%d%%", } local PLAYER_STAT_DISPLAY_NAMES = { Health = "Health", Defense = "Defense", Attack = "Attack", Magic = "Magic", CritChance = "Crit Chance", Haste = "Haste", CDR = "Cooldown Reduction", Tenacity = "Tenacity" } local PLAYER_STAT_EXPLANATIONS = { Health = "Increases hitpoints", Defense = "Reduces damage taken", Attack = "Increases physical damage dealt", Magic = "Increases magical damage dealt", CritChance = "Increases critical strike chance", Haste = "Increases running speed", CDR = "Reduces ability cooldown time", Tenacity = "Reduces hostile status effect duration", } return { GetRarityColor = function(rarity) return Color.New(RARITY_COLORS[rarity]) end, GetRarityLootIndicator = function(rarity) return RARITY_INDICATORS[rarity] end, GetStatIcon = function(statName) return STAT_ICONS[statName] end, GetItemStatFormattedValue = function(statName, statValue) return string.format(ITEM_STAT_FORMATS[statName], statValue) end, GetPlayerStatFormattedValue = function(statName, statValue) return string.format(PLAYER_STAT_FORMATS[statName], statValue) end, GetPlayerStatDisplayName = function(statName) return PLAYER_STAT_DISPLAY_NAMES[statName] end, GetPlayerStatExplanation = function(statName) return PLAYER_STAT_EXPLANATIONS[statName] end, GetItemSFX = function(itemType) local SuprressWarning = false -- Change this to true if you don't care about the warning messages. if not ITEM_SFX[itemType] then if not SuprressWarning then warn(string.format("Item type: %s does not have an associated SFX custom property. This will default to Misc SFX. Consider adding one to ItemThemes or supress the warning inside the script.",itemType)) end return ITEM_SFX["Misc"] end return ITEM_SFX[itemType] end, }
resource_manifest_version '44febabe-d386-4d18-afbe-5e627f4af937' files{ 'index.html', 'css/style.css', 'img/cursor.png', 'img/MyLogo.png', 'img/fondo.jpg', 'fonts/Anton-Regular.ttf', 'js/cursor.js', 'media/audio.mp3' } loadscreen 'index.html' author 'Nekix' description 'SAX = Mala calidad'
EMVU.AddCustomSiren("nypdssr", { Name = "NYPD Smart Siren Rumbler", -- The name that shows on the HUD. Category = "Other", -- The category the siren shows up under. Set = { {Name = "WAIL", Sound = "emv/sirens/nypd_smartsiren_rumbler/emv_wail.wav", Icon="wail"}, {Name = "YELP", Sound = "emv/sirens/nypd_smartsiren_rumbler/emv_yelp.wav", Icon="yelp"}, {Name = "PHSR", Sound = "emv/sirens/nypd_smartsiren_rumbler/emv_priority.wav", Icon="phaser"}, {Name = "HI-LO", Sound = "emv/sirens/nypd_smartsiren_rumbler/emv_hilo.wav", Icon="hilo"}, }, Horn = "emv/sirens/nypd_smartsiren_rumbler/emv_horn.wav", Manual = "emv/sirens/nypd_smartsiren_rumbler/emv_manual.wav", })
-- initialize all player-related globals function setup_global() global.player_data = global.player_data or {} for i,_ in pairs(game.players) do if not global.player_data[i] then global.player_data[i] = create_player_data(i) end end end -- when a new player first joins the game, create their data function on_player_created(e) global.player_data[e.player_index] = create_player_data(e.player_index) end -- create player data function create_player_data(player_index) if global.player_data[player_index] then return global.player_data[player_index] end local data = {} -- player action status data.cur_drawing = false data.cur_editing = false -- current tilegrid data data.cur_tilegrid_index = global.next_tilegrid_index -- drawing metadata data.last_capsule_tick = 0 data.last_capsule_pos = { x = 0, y = 0 } -- gui references local player = game.players[player_index] data.mod_gui = mod_gui.get_frame_flow(player) data.center_gui = player.gui.center data.settings = create_player_settings(player_index) return data end -- create player settings function create_player_settings(player_index) local data = {} -- runtime settings data.increment_divisor = 5 data.split_divisor = 4 data.grid_type = 1 data.grid_autoclear = true data.restrict_to_cardinals = false data.log_selection_area = game.players[player_index].mod_settings['log-selection-area'].value return data end -- when a player changes a setting in the mod settings GUI function on_player_mod_setting_changed(e) if e.setting_type == 'runtime-per-user' then global.player_data[e.player_index].settings.log_selection_area = game.players[e.player_index].mod_settings['log-selection-area'].value end end local setting_associations = { gridtype_dropdown = 'grid_type', autoclear_checkbox = 'grid_autoclear', drawonground_checkbox = 'draw_tilegrid_on_ground', increment_divisor_textfield = 'increment_divisor', split_divisor_textfield = 'split_divisor', increment_divisor_slider = 'increment_divisor', split_divisor_slider = 'split_divisor', increment_divisor_textfield = 'increment_divisor', split_divisor_textfield = 'split_divisor', restrict_to_cardinals_checkbox = 'restrict_to_cardinals' } -- when a setting is changed in the tapeline settings GUI function change_setting(e) local value local type = e.element.type if e.element.type == 'drop-down' then value = e.element.selected_index elseif type == 'textfield' then value = e.element.text elseif type == 'checkbox' then value = e.element.state elseif type == 'slider' then value = e.element.slider_value end if global.player_data[e.player_index].cur_editing then global[global.player_data[e.player_index].cur_tilegrid_index].settings[setting_associations[e.match]] = value update_tilegrid_settings(e.player_index) else global.player_data[e.player_index].settings[setting_associations[e.match]] = value end end -- detect if the player is holding the tapeline capsule, and show/hide the settings menu accordingly function on_item(e) local player = game.players[e.player_index] local stack = player.cursor_stack if stack and stack.valid_for_read and stack.name == 'tapeline-capsule' then -- if holding the tapeline open_settings_menu(player) set_settings_frame_mode(false, player) else -- hide settings GUI close_settings_menu(player) end end -- detect if the current slider value is different from the setting, and if so, change it function check_slider_change(e) local value = e.element.slider_value local player_data = global.player_data[e.player_index] local settings if player_data.cur_editing then settings = global[player_data.cur_tilegrid_index].settings else settings = player_data.settings end if value ~= settings[setting_associations[e.match]] then change_setting(e) end end stdlib.event.register({'on_init', 'on_configuration_changed'}, setup_global) stdlib.event.register(defines.events.on_player_created, on_player_created) stdlib.event.register(defines.events.on_runtime_mod_setting_changed, on_player_mod_setting_changed) stdlib.event.register(defines.events.on_player_cursor_stack_changed, on_item)
inventory = {} function inventory:init() inventory.pieces = {} for i = 1, 1 do table.insert(inventory.pieces, piece:new(0, 0, piece.types[love.math.random(5)+1], "white", love.math.random(9), love.math.random(3)-1)) end end --not meant to be executed every frame, only when needed function inventory:update() inventory.pieces = {} if #level.objects.playerPieces > 0 then for i = 1, #level.objects.playerPieces do table.insert(inventory.pieces, level.objects.playerPieces[i]) end end end function inventory:draw() inventory:drawPieceListGUI() end function inventory:drawPieceListGUI() if #inventory.pieces > 0 then for i = 1, #inventory.pieces do love.graphics.draw(sprite_sheet, inventory.pieces[i].sprite, 10, i*sprites_1.height+30) end end end
local complex = { r= 3, i= 5 } local mti = { __tostring = function( n ) return n.r.."+".. n.i.."i" end, __len = function( n ) return math.sqrt(n.r*n.r + n.i * n.i) end } setmetatable( complex, mti ) print( tostring(complex ) ) print( #complex )
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(...,package.seeall) -- Implementation of IPsec ESP using AES-GCM with 16 byte ICV and -- “Extended Sequence Numbers” (see RFC 4303 and RFC 4106). Provides -- address-family independent encapsulation/decapsulation routines for -- “tunnel mode” and “transport mode” routines for IPv6. -- -- Notes: -- -- * Wrapping around of the Extended Sequence Number is *not* detected because -- it is assumed to be an unrealistic scenario as it would take 584 years to -- overflow the counter when transmitting 10^9 packets per second. -- -- * IP fragments are *not* rejected by the routines in this library, and are -- expected to be handled prior to encapsulation/decapsulation. -- See the “Reassembly” section of RFC 4303 for details: -- https://tools.ietf.org/html/rfc4303#section-3.4.1 local header = require("lib.protocol.header") local datagram = require("lib.protocol.datagram") local ethernet = require("lib.protocol.ethernet") local ipv6 = require("lib.protocol.ipv6") local esp = require("lib.protocol.esp") local esp_tail = require("lib.protocol.esp_tail") local aes_gcm = require("lib.ipsec.aes_gcm") local seq_no_t = require("lib.ipsec.seq_no_t") local lib = require("core.lib") local ffi = require("ffi") local C = ffi.C local logger = require("lib.logger").new({ rate = 32, module = 'esp' }) local htons, htonl, ntohl = lib.htons, lib.htonl, lib.ntohl require("lib.ipsec.track_seq_no_h") local window_t = ffi.typeof("uint8_t[?]") PROTOCOL = 50 -- https://tools.ietf.org/html/rfc4303#section-2 local ipv6_ptr_t = ffi.typeof("$ *", ipv6:ctype()) local function ipv6_fl (ip) return bit.lshift(ntohl(ip.v_tc_fl), 12) end local esp_header_ptr_t = ffi.typeof("$ *", esp:ctype()) local esp_trailer_ptr_t = ffi.typeof("$ *", esp_tail:ctype()) local ETHERNET_SIZE = ethernet:sizeof() local IPV6_SIZE = ipv6:sizeof() local ESP_SIZE = esp:sizeof() local ESP_TAIL_SIZE = esp_tail:sizeof() local TRANSPORT6_PAYLOAD_OFFSET = ETHERNET_SIZE + IPV6_SIZE -- NB: `a' must be a power of two local function padding (a, l) return bit.band(-l, a-1) end -- AEAD identifier from: -- https://github.com/YangModels/yang/blob/master/experimental/ietf-extracted-YANG-modules/ietf-ipsec@2018-01-08.yang function esp_new (conf) local aead if conf.aead == "aes-gcm-16-icv" then aead = aes_gcm.aes_128_gcm elseif conf.aead == "aes-256-gcm-16-icv" then aead = aes_gcm.aes_256_gcm else error("Unsupported AEAD: "..conf.aead) end assert(conf.spi, "Need SPI.") local o = { cipher = aead:new(conf.spi, conf.key, conf.salt), spi = conf.spi, seq = ffi.new(seq_no_t), pad_to = 4 -- minimal padding } o.ESP_CTEXT_OVERHEAD = o.cipher.IV_SIZE + ESP_TAIL_SIZE o.ESP_OVERHEAD = ESP_SIZE + o.ESP_CTEXT_OVERHEAD + o.cipher.AUTH_SIZE return o end encrypt = {} function encrypt:new (conf) return setmetatable(esp_new(conf), {__index=encrypt}) end -- Increment sequence number. function encrypt:next_seq_no () self.seq.no = self.seq.no + 1 end function encrypt:padding (length) -- See https://tools.ietf.org/html/rfc4303#section-2.4 return padding(self.pad_to, length + self.ESP_CTEXT_OVERHEAD) end function encrypt:encode_esp_trailer (ptr, next_header, pad_length) local esp_trailer = ffi.cast(esp_trailer_ptr_t, ptr) esp_trailer.next_header = next_header esp_trailer.pad_length = pad_length end function encrypt:encrypt_payload (ptr, length) self:next_seq_no() local seq, low, high = self.seq, self.seq:low(), self.seq:high() self.cipher:encrypt(ptr, seq, low, high, ptr, length, ptr + length) end function encrypt:encode_esp_header (ptr) local esp_header = ffi.cast(esp_header_ptr_t, ptr) esp_header.spi = htonl(self.spi) esp_header.seq_no = htonl(self.seq:low()) ffi.copy(ptr + ESP_SIZE, self.seq, self.cipher.IV_SIZE) end -- Encapsulation in transport mode is performed as follows: -- 1. Grow p to fit ESP overhead -- 2. Append ESP trailer to p -- 3. Encrypt payload+trailer in place -- 4. Move resulting ciphertext to make room for ESP header -- 5. Write ESP header function encrypt:encapsulate_transport6 (p) if p.length < TRANSPORT6_PAYLOAD_OFFSET then return nil end local ip = ffi.cast(ipv6_ptr_t, p.data + ETHERNET_SIZE) local payload = p.data + TRANSPORT6_PAYLOAD_OFFSET local payload_length = p.length - TRANSPORT6_PAYLOAD_OFFSET local pad_length = self:padding(payload_length) local overhead = self.ESP_OVERHEAD + pad_length p = packet.resize(p, p.length + overhead) local tail = payload + payload_length + pad_length self:encode_esp_trailer(tail, ip.next_header, pad_length) local ctext_length = payload_length + pad_length + ESP_TAIL_SIZE self:encrypt_payload(payload, ctext_length) local ctext = payload + ESP_SIZE + self.cipher.IV_SIZE C.memmove(ctext, payload, ctext_length + self.cipher.AUTH_SIZE) self:encode_esp_header(payload) ip.next_header = PROTOCOL ip.payload_length = htons(payload_length + overhead) return p end -- Encapsulation in tunnel mode is performed as follows: -- (In tunnel mode, the input packet must be an IP frame already stripped of -- its Ethernet header.) -- 1. Grow and shift p to fit ESP overhead -- 2. Append ESP trailer to p -- 3. Encrypt payload+trailer in place -- 4. Write ESP header -- (The resulting packet contains the raw ESP frame, without IP or Ethernet -- headers.) function encrypt:encapsulate_tunnel (p, next_header) local pad_length = self:padding(p.length) local trailer_overhead = pad_length + ESP_TAIL_SIZE + self.cipher.AUTH_SIZE local orig_length = p.length p = packet.resize(p, orig_length + trailer_overhead) local tail = p.data + orig_length + pad_length self:encode_esp_trailer(tail, next_header, pad_length) local ctext_length = orig_length + pad_length + ESP_TAIL_SIZE self:encrypt_payload(p.data, ctext_length) local len = p.length p = packet.shiftright(p, ESP_SIZE + self.cipher.IV_SIZE) self:encode_esp_header(p.data) return p end decrypt = {} function decrypt:new (conf) local o = esp_new(conf) o.MIN_SIZE = o.ESP_OVERHEAD + padding(o.pad_to, o.ESP_OVERHEAD) o.CTEXT_OFFSET = ESP_SIZE + o.cipher.IV_SIZE o.PLAIN_OVERHEAD = ESP_SIZE + o.cipher.IV_SIZE + o.cipher.AUTH_SIZE local window_size = conf.window_size or 128 o.window_size = window_size + padding(8, window_size) o.window = ffi.new(window_t, o.window_size / 8) o.resync_threshold = conf.resync_threshold or 1024 o.resync_attempts = conf.resync_attempts or 8 o.decap_fail = 0 o.auditing = conf.auditing o.copy = packet.allocate() return setmetatable(o, {__index=decrypt}) end function decrypt:decrypt_payload (ptr, length, ip) -- NB: bounds check is performed by caller local esp_header = ffi.cast(esp_header_ptr_t, ptr) local iv_start = ptr + ESP_SIZE local ctext_start = ptr + self.CTEXT_OFFSET local ctext_length = length - self.PLAIN_OVERHEAD local seq_low = ntohl(esp_header.seq_no) local seq_high = tonumber( C.check_seq_no(seq_low, self.seq.no, self.window, self.window_size) ) local error = nil if seq_high < 0 or not self.cipher:decrypt( ctext_start, seq_low, seq_high, iv_start, ctext_start, ctext_length ) then if seq_high < 0 then error = "replayed" else error = "integrity error" end self.decap_fail = self.decap_fail + 1 if self.decap_fail > self.resync_threshold then seq_high = self:resync(ptr, length, seq_low, seq_high) if seq_high then error = nil end end end if error then self:audit(error, ntohl(esp_header.spi), seq_low, ip) return nil end self.decap_fail = 0 self.seq.no = C.track_seq_no( seq_high, seq_low, self.seq.no, self.window, self.window_size ) local esp_trailer_start = ctext_start + ctext_length - ESP_TAIL_SIZE local esp_trailer = ffi.cast(esp_trailer_ptr_t, esp_trailer_start) local ptext_length = ctext_length - esp_trailer.pad_length - ESP_TAIL_SIZE return ctext_start, ptext_length, esp_trailer.next_header end -- Decapsulation in transport mode is performed as follows: -- 1. Parse IP and ESP headers and check Sequence Number -- 2. Decrypt ciphertext in place -- 3. Parse ESP trailer and update IP header -- 4. Move cleartext up to IP payload -- 5. Shrink p by ESP overhead function decrypt:decapsulate_transport6 (p) if p.length - TRANSPORT6_PAYLOAD_OFFSET < self.MIN_SIZE then return nil end local ip = ffi.cast(ipv6_ptr_t, p.data + ETHERNET_SIZE) local payload = p.data + TRANSPORT6_PAYLOAD_OFFSET local payload_length = p.length - TRANSPORT6_PAYLOAD_OFFSET local ptext_start, ptext_length, next_header = self:decrypt_payload(payload, payload_length, ip) if not ptext_start then return nil end ip.next_header = next_header ip.payload_length = htons(ptext_length) C.memmove(payload, ptext_start, ptext_length) p = packet.resize(p, TRANSPORT6_PAYLOAD_OFFSET + ptext_length) return p end -- Decapsulation in tunnel mode is performed as follows: -- (In tunnel mode, the input packet must be already stripped of its outer -- Ethernet and IP headers.) -- 1. Parse ESP header and check Sequence Number -- 2. Decrypt ciphertext in place -- 3. Parse ESP trailer and shrink p by overhead -- (The resulting packet contains the raw ESP payload (i.e. an IP frame), -- without an Ethernet header.) function decrypt:decapsulate_tunnel (p) if p.length < self.MIN_SIZE then return nil end local ptext_start, ptext_length, next_header = self:decrypt_payload(p.data, p.length) if not ptext_start then return nil end p = packet.shiftleft(p, self.CTEXT_OFFSET) p = packet.resize(p, ptext_length) return p, next_header end function decrypt:audit (reason, spi, seq, ip) if not self.auditing then return end -- The information RFC4303 says we SHOULD log: logger:log(("Rejected packet (spi=%d, seq=%d, " .."src_ip=%s, dst_ip=%s, flow_id=0x%x, " .."reason=%q)") :format(spi, seq, ip and ipv6:ntop(ip.src_ip) or "unknown", ip and ipv6:ntop(ip.dst_ip) or "unknown", ip and ipv6_fl(ip) or 0, reason)) end function decrypt:resync (ptr, length, seq_low, seq_high) local iv_start = ptr + ESP_SIZE local ctext_start = ptr + self.CTEXT_OFFSET local ctext_length = length - self.PLAIN_OVERHEAD if seq_high < 0 then -- The sequence number looked replayed, we use the last seq_high we have -- seen seq_high = self.seq:high() else -- We failed to decrypt in-place, undo the damage to recover the original -- ctext (ignore bogus auth data) self.cipher:encrypt( ctext_start, iv_start, seq_low, seq_high, ctext_start, ctext_length ) end local p_orig = packet.append(packet.resize(self.copy, 0), ptr, length) for i = 1, self.resync_attempts do seq_high = seq_high + 1 if self.cipher:decrypt( ctext_start, seq_low, seq_high, iv_start, ctext_start, ctext_length ) then return seq_high else ffi.copy(ptr, p_orig.data, length) end end end function selftest () local conf = { spi = 0x0, aead = "aes-gcm-16-icv", key = "00112233445566778899AABBCCDDEEFF", salt = "00112233", resync_threshold = 16, resync_attempts = 8 } local enc, dec = encrypt:new(conf), decrypt:new(conf) local payload = packet.from_string( [[abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789]] ) local d = datagram:new(payload) local ip = ipv6:new({}) ip:payload_length(payload.length) d:push(ip) d:push(ethernet:new({type=0x86dd})) local p = d:packet() -- Check integrity print("original", lib.hexdump(ffi.string(p.data, p.length))) local p_enc = assert(enc:encapsulate_transport6(packet.clone(p)), "encapsulation failed") print("encrypted", lib.hexdump(ffi.string(p_enc.data, p_enc.length))) local p2 = assert(dec:decapsulate_transport6(packet.clone(p_enc)), "decapsulation failed") print("decrypted", lib.hexdump(ffi.string(p2.data, p2.length))) assert(p2.length == p.length and C.memcmp(p.data, p2.data, p.length) == 0, "integrity check failed") -- ... for tunnel mode local p_enc = assert(enc:encapsulate_tunnel(packet.clone(p), 42), "encapsulation failed") print("enc. (tun)", lib.hexdump(ffi.string(p_enc.data, p_enc.length))) local p2, nh = dec:decapsulate_tunnel(packet.clone(p_enc)) assert(p2 and nh == 42, "decapsulation failed") print("dec. (tun)", lib.hexdump(ffi.string(p2.data, p2.length))) assert(p2.length == p.length and C.memcmp(p.data, p2.data, p.length) == 0, "integrity check failed") -- Check invalid packets. assert(not enc:encapsulate_transport6(packet.from_string("invalid")), "encapsulated invalid packet") assert(not dec:decapsulate_transport6(packet.from_string("invalid")), "decapsulated invalid packet") -- ... for tunnel mode assert(not dec:decapsulate_tunnel(packet.from_string("invalid")), "decapsulated invalid packet") -- Check minimum packet. local p_min = packet.from_string("012345678901234567890123456789012345678901234567890123") p_min.data[18] = 0 -- Set IPv6 payload length to zero p_min.data[19] = 0 -- ... assert(p_min.length == TRANSPORT6_PAYLOAD_OFFSET) print("original", lib.hexdump(ffi.string(p_min.data, p_min.length))) local e_min = assert(enc:encapsulate_transport6(packet.clone(p_min))) print("encrypted", lib.hexdump(ffi.string(e_min.data, e_min.length))) assert(e_min.length == dec.MIN_SIZE+TRANSPORT6_PAYLOAD_OFFSET) e_min = assert(dec:decapsulate_transport6(e_min), "decapsulation of minimum packet failed") print("decrypted", lib.hexdump(ffi.string(e_min.data, e_min.length))) assert(e_min.length == TRANSPORT6_PAYLOAD_OFFSET) assert(p_min.length == e_min.length and C.memcmp(p_min.data, e_min.data, p_min.length) == 0, "integrity check failed") -- ... for tunnel mode print("original", "(empty)") local e_min = assert(enc:encapsulate_tunnel(packet.allocate(), 0)) print("enc. (tun)", lib.hexdump(ffi.string(e_min.data, e_min.length))) e_min = assert(dec:decapsulate_tunnel(e_min)) assert(e_min.length == 0) -- Tunnel/transport mode independent tests for _, op in ipairs( {{encap=function (p) return enc:encapsulate_transport6(p) end, decap=function (p) return dec:decapsulate_transport6(p) end}, {encap=function (p) return enc:encapsulate_tunnel(p, 0) end, decap=function (p) return dec:decapsulate_tunnel(p) end}} ) do -- Check transmitted Sequence Number wrap around C.memset(dec.window, 0, dec.window_size / 8) -- clear window enc.seq.no = 2^32 - 1 -- so next encapsulated will be seq 2^32 dec.seq.no = 2^32 - 1 -- pretend to have seen 2^32-1 local px = op.encap(packet.clone(p)) assert(op.decap(px), "Transmitted Sequence Number wrap around failed.") assert(dec.seq:high() == 1 and dec.seq:low() == 0, "Lost Sequence Number synchronization.") -- Check Sequence Number exceeding window C.memset(dec.window, 0, dec.window_size / 8) -- clear window enc.seq.no = 2^32 dec.seq.no = 2^32 + dec.window_size + 1 local px = op.encap(packet.clone(p)) dec.auditing = true assert(not op.decap(px), "Accepted out of window Sequence Number.") assert(dec.seq:high() == 1 and dec.seq:low() == dec.window_size+1, "Corrupted Sequence Number.") dec.auditing = false -- Test anti-replay: From a set of 15 packets, first send all those -- that have an even sequence number. Then, send all 15. Verify that -- in the 2nd run, packets with even sequence numbers are rejected while -- the others are not. -- Then do the same thing again, but with offset sequence numbers so that -- we have a 32bit wraparound in the middle. local offset = 0 -- close to 2^32 in the 2nd iteration for offset = 0, 2^32-7, 2^32-7 do -- duh C.memset(dec.window, 0, dec.window_size / 8) -- clear window dec.seq.no = offset for i = 1+offset, 15+offset do if (i % 2 == 0) then enc.seq.no = i-1 -- so next seq will be i local px = op.encap(packet.clone(p)) assert(op.decap(px), "rejected legitimate packet seq=" .. i) assert(dec.seq.no == i, "Lost sequence number synchronization") end end for i = 1+offset, 15+offset do enc.seq.no = i-1 local px = op.encap(packet.clone(p)) if (i % 2 == 0) then assert(not op.decap(px), "accepted replayed packet seq=" .. i) else assert(op.decap(px), "rejected legitimate packet seq=" .. i) end end end -- Check that packets from way in the past/way in the future (further -- than the biggest allowable window size) are rejected This is where we -- ultimately want resynchronization (wrt. future packets) C.memset(dec.window, 0, dec.window_size / 8) -- clear window dec.seq.no = 2^34 + 42 enc.seq.no = 2^36 + 24 local px = op.encap(packet.clone(p)) assert(not op.decap(px), "accepted packet from way into the future") enc.seq.no = 2^32 + 42 local px = op.encap(packet.clone(p)) assert(not op.decap(px), "accepted packet from way into the past") -- Test resynchronization after having lost >2^32 packets enc.seq.no = 0 dec.seq.no = 0 C.memset(dec.window, 0, dec.window_size / 8) -- clear window local px = op.encap(packet.clone(p)) -- do an initial packet assert(op.decap(px), "decapsulation failed") enc.seq:high(3) -- pretend there has been massive packet loss enc.seq:low(24) for i = 1, dec.resync_threshold do local px = op.encap(packet.clone(p)) assert(not op.decap(px), "decapsulated pre-resync packet") end local px = op.encap(packet.clone(p)) assert(op.decap(px), "failed to resynchronize") -- Make sure we don't accidentally resynchronize with very old replayed -- traffic enc.seq.no = 42 for i = 1, dec.resync_threshold do local px = op.encap(packet.clone(p)) assert(not op.decap(px), "decapsulated very old packet") end local px = op.encap(packet.clone(p)) assert(not op.decap(px), "resynchronized with the past!") end end
--[[ Copyright (c) 2011-2012 qeeplay.com http://dualface.github.com/quick-cocos2d-x/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] --[[-- Query information about the system (get device information, current language, etc) and execute system functions (show alert view, show input box, etc). <br /> Following properties predefined: - **device.platform** the platform name (the OS name), i.e. one of the following: ios, android, blackberry, mac, windows, linux. - **device.environment** returns the environment that the app is running in. i.e. one of the following: simulator, device. - **device.model** returns the device model (as specified by the manufacturer) : - On iOS: return iPhone, iPad - On Android: return Android device model name - On Mac, windows, linux: return "unknown" - **device.language** returns the default language on the device : Value | Language ----------- | ------------- cn | Chinese fr | French it | Italian gr | German sp | Spanish ru | Russian jp | Japanese en | English - **device.writeablePath** returns the writeable path. ]] local device = {} device.platform = "unknown" device.environment = "simulator" device.model = "unknown" local sharedApplication = CCApplication:sharedApplication() local target = sharedApplication:getTargetPlatform() if target == kTargetWindows then device.platform = "windows" elseif target == kTargetLinux then device.platform = "linux" elseif target == kTargetMacOS then device.platform = "mac" elseif target == kTargetAndroid then device.platform = "android" elseif target == kTargetIphone or target == kTargetIpad then device.platform = "ios" if target == kTargetIphone then device.model = "iphone" else device.model = "ipad" end elseif target == kTargetBlackBerry then device.platform = "blackberry" end if sharedApplication.getTargetEnvironment and sharedApplication:getTargetEnvironment() == kTargetDevice then device.environment = "device" end local language_ = sharedApplication:getCurrentLanguage() if language_ == kLanguageChinese then language_ = "cn" elseif language_ == kLanguageFrench then language_ = "fr" elseif language_ == kLanguageItalian then language_ = "it" elseif language_ == kLanguageGerman then language_ = "gr" elseif language_ == kLanguageSpanish then language_ = "sp" elseif language_ == kLanguageRussian then language_ = "ru" else language_ = "en" end device.language = language_ device.writeablePath = CCFileUtils:sharedFileUtils():getWriteablePath() echoInfo("# device.platform = " .. device.platform) echoInfo("# device.environment = " .. device.environment) echoInfo("# device.model = " .. device.model) echoInfo("# device.language = " .. device.language) echoInfo("# device.writeablePath = " .. device.writeablePath) echoInfo("#") --[[-- Displays a platform-specific activity indicator. ### Note: Supported platform: ios, android. ]] function device.showActivityIndicator() CCNative:showActivityIndicator() end --[[-- Hides activity indicator. ### Note: Supported platform: ios, android. ]] function device.hideActivityIndicator() CCNative:hideActivityIndicator() end --[[-- Displays a popup alert box with one or more buttons. Program activity, including animation, will continue in the background, but all other user interactivity will be blocked until the user selects a button or cancels the dialog. ### Paramters: - string **title** The title string displayed in the alert - string **message** Message string displayed in the alert text. - table **buttonLabels** Table of strings, each of which will create a button with the corresponding label. - function **listener** The listener to be notified when a user presses any button in the alert box. ### Note: Supported platform: ios, android, mac. ]] function device.showAlert(title, message, buttonLabels, listener) buttonLabels = totable(buttonLabels) local defaultLabel = "" if #buttonLabels > 0 then defaultLabel = buttonLabels[1] table.remove(buttonLabels, 1) end CCNative:createAlert(title, message, defaultLabel) for i, label in ipairs(buttonLabels) do CCNative:addAlertButton(label) end if type(listener) ~= "function" then listener = function() end end CCNative:showAlertLua(listener) end --[[-- Dismisses an alert box programmatically. For example, you may wish to have a popup alert that automatically disappears after ten seconds even if the user doesn’t click it. In that case, you could call this function at the end of a ten-second timer. ### Note: Supported platform: ios, android, mac. ]] function device.cancelAlert() CCNative:cancelAlert() end --[[-- Returns OpenUDID for device. > OpenUDID is a drop-in replacement for the deprecated uniqueIdentifier property of the UIDevice class on iOS (a.k.a. UDID) and otherwise is an industry-friendly equivalent for iOS and Android. ### Returns: - string OpenUDID ### Note: Supported platform: ios, android, mac. ]] function device.getOpenUDID() return CCNative:getOpenUDID() end --[[-- Open a web page in the browser; create an email; or call a phone number. Note: Executing this function will make the app background and switch to the built-in browser, email or phone app. ### Parameters: - string **url** url can be one of the following: - Web link: "http://dualface.github.com/quick-cocos2d-x/" - Email address: "mailto:nobody@mycompany.com". The email address url can also contain subject and body parameters, both of which must be url encoded.<br /> Example: "mailto:nobody@mycompany.com?subject=Hi%20there&body=I%20just%20wanted%20to%20say%2C%20Hi!"<br /> Try this URL encoder to encode your text. - Phone number: "tel:123-456-7890" ### Note: Supported platform: ios, android. ]] function device.openURL(url) CCNative:openURL(url) end --[[-- Displays a popup input dialog with ok and cancel button. ### Parameters: - string **title** The title string displayed in the input dialog - string **message** Message string displayed in the input dialog - string **defaultValue** Displayed in the text box. ### Returns: - string User entered text. If uesr cancel input dialog, return nil. ### Note: Supported platform: mac, windows. ]] function device.showInputBox(title, message, defaultValue) title = title or "INPUT TEXT" message = message or "INPUT TEXT, CLICK OK BUTTON" defaultValue = defaultValue or "" return CCNative:getInputText(title, message, defaultValue) end return device
function onKill(creature, target) local targetMonster = target:getMonster() if not targetMonster then return true end if targetMonster:getName():lower() ~= 'ungreez' then return true end local player = creature:getPlayer() if player:getStorageValue(Storage.TheInquisition.Questline) == 18 then -- The Inquisition Questlog- 'Mission 6: The Demon Ungreez' player:setStorageValue(Storage.TheInquisition.Mission06, 2) player:setStorageValue(Storage.TheInquisition.Questline, 19) end return true end
local expired_items_metric if minetest.get_modpath("monitoring") then expired_items_metric = monitoring.counter( "pipeworks_expired_items_count", "Number of expired items" ) end local function cleanup() local now = os.time() for _, entity in pairs(pipeworks.luaentity.entities) do if not entity.ctime then -- set creation time if not already set entity.ctime = now else -- check expiration time local delta = now - entity.ctime if delta > monitoring.pipeworks.item_expiration_seconds then -- entity expired, remove entity:remove() if expired_items_metric then expired_items_metric.inc() end end end end minetest.after(10, cleanup) end -- start initial cleanup after 10 minutes minetest.after(monitoring.pipeworks.item_expiration_seconds, cleanup)
UI = { help = false, messageTimer = 0, message = nil, } function UI.init() end function UI.update(dt) local sy = math.floor((WINDOW_H-300)/2) local sx = math.floor(WINDOW_W/2) love.graphics.setFont(font_title) suit.Label("Sprit3r", sx-100, sy, 200) love.graphics.setFont(font) if not UI.help then love.graphics.setFont(font_model) local str = "Drag and drop an image or voxel file here!" suit.Label(UI.message or str, sx-100, sy+210, 200) love.graphics.setFont(font) else local str="Sprit3r is a minimalist software used to display sprites in 3D. This is done using spritesheets,".. " where each tile represents one layer of the model. The software is not an image editor, but it will update the model in real time".. " while you edit your models in another software." suit.Label(str, sx-200, sy+75, 400) str = "Supported file formats: .png and .vox" suit.Label(str, sx-220, sy+185, 440) str = "Created by evgiz.net" suit.Label(str, sx-200, sy+225, 400) end if suit.Button(not UI.help and "Help/About" or "Back", WINDOW_W/2-75, WINDOW_H-45, 150, 25).hit then UI.help = not UI.help end if suit.Button("View Example", WINDOW_W/2-75, WINDOW_H-75, 150, 25).hit then viewer:new(love.filesystem.newFile("example.png", "r")) end end local img = love.graphics.newImage("example.png") img:setFilter("nearest", "nearest") local quads = nil function UI.draw() if UI.help then return end local sy = math.floor((WINDOW_H-300)/2+150) local scale = 3 if quads==nil then quads={} for i=1,10 do quads[i] = love.graphics.newQuad(i*32, 0, 32, 32, img:getWidth(), img:getHeight()) end end for i=1,10 do love.graphics.draw(img, quads[i], WINDOW_W/2, sy-i*scale*2, math.rad(love.timer.getTime()*20), scale,scale, 16,16) love.graphics.draw(img, quads[i], WINDOW_W/2, sy-i*scale*2-1, math.rad(love.timer.getTime()*20), scale,scale, 16,16) love.graphics.draw(img, quads[i], WINDOW_W/2, sy-i*scale*2-2, math.rad(love.timer.getTime()*20), scale,scale, 16,16) love.graphics.draw(img, quads[i], WINDOW_W/2, sy-i*scale*2-3, math.rad(love.timer.getTime()*20), scale,scale, 16,16) end end return UI
----------------------------------- -- Area: The Shrine of Ru'Avitau -- Mob: Seiryu (Pet version) ----------------------------------- require("scripts/globals/status"); ----------------------------------- function onMonsterMagicPrepare(mob,target) if (mob:hasStatusEffect(tpz.effect.HUNDRED_FISTS,0) == false) then local rnd = math.random(); if (rnd < 0.5) then return 186; -- aeroga 3 elseif (rnd < 0.7) then return 157; -- aero 4 elseif (rnd < 0.9) then return 208; -- tornado else return 237; -- choke end end return 0; -- Still need a return, so use 0 when not casting end; function onMobDeath(mob, player, isKiller) end;
local skynet = require "skynet" require "skynet.manager" local table = table local assert = assert local math_fmod = math.fmod local function launch_slave(conf) local command_handler if conf.name == "db_slave_offline" then conf.dirtyagent = nil command_handler = conf.offlineagent.command_handler elseif conf.name == "db_slave_dirty" then conf.offlineagent = nil command_handler = conf.dirtyagent.command_handler else assert(false, "launch_slave conf.name error"..conf.name) end skynet.dispatch("lua", function(_,_, ...) command_handler(...) end) end local function launch_master(conf) local instance = conf.instance or 8 assert(instance > 1) local slave = {} local offline_slave skynet.dispatch("lua", function(_,source,command, uid, ...) skynet.error(_,source,command, uid, ...) if command == "saveall" then skynet.send(offline_slave, "lua", command, uid, ...) skynet.ret(nil) else if not uid then uid = 0 end slaveid=math_fmod(uid, instance-1) + 1 skynet.send(slave[slaveid], "lua", command, uid, ...) skynet.ret(nil) end end) for i=1,instance-1 do table.insert(slave, skynet.newservice(SERVICE_NAME, "db_slave_dirty")) end table.insert(slave, skynet.newservice(SERVICE_NAME, "db_slave_offline")) offline_slave = slave[instance] end local function dbserver(conf) skynet.start(function() if conf.name == "db_master" then launch_slave = nil conf.dirtyagent = nil conf.offlineagent = nil launch_master(conf) else assert(conf.name=="db_slave_offline" or conf.name=="db_slave_dirty", "dbserver conf.name error"..conf.name) launch_slave(conf) end end) end return dbserver
local class = require("heart.class") local M = class.newClass() function M:init(game, config) self.game = assert(game) self.physicsDomain = assert(self.game.domains.physics) self.boneComponents = assert(self.game.componentManagers.bone) end function M:createComponent(entityId, config) local transform = self.boneComponents.transforms[entityId] local bodyId2 = self.game:findAncestorComponent(entityId, "body") local bodyId1 = self.game:findAncestorComponent(bodyId2, "body", 1) local body1 = self.physicsDomain.bodies[bodyId1] local body2 = self.physicsDomain.bodies[bodyId2] local x1 = config.x1 or 0 local y1 = config.y1 or 0 x1, y1 = transform:transformPoint(x1, y1) local x2 = config.x2 or 0 local y2 = config.y2 or 0 x2, y2 = transform:transformPoint(x2, y2) local collideConnected = config.collideConnected == true local joint = love.physics.newRevoluteJoint( body1, body2, x1, y1, x2, y2, collideConnected) joint:setUserData(entityId) joint:setMaxMotorTorque(config.maxMotorTorque or 0) joint:setMotorEnabled(config.motorEnabled == true) joint:setMotorSpeed(config.motorSpeed or 0) joint:setLimitsEnabled(config.limitsEnabled == true) local lowerLimit = config.lowerLimit or 0 local upperLimit = config.upperLimit or 0 joint:setLimits(lowerLimit, upperLimit) self.physicsDomain.revoluteJoints[entityId] = joint return joint end function M:destroyComponent(entityId) self.physicsDomain.revoluteJoints[entityId]:destroy() self.physicsDomain.revoluteJoints[entityId] = nil end return M
local M = {} local vim = vim local api = require('findr/api') local utils = require('findr/utils') local view = require('findr/view') local model = require('findr/model') local sources = require('findr/sources') local user_io = require('findr/controller/user_io') local maps = require('findr/controller/maps') local startloc = 1 local selected_loc = 2 local winnum = -1 local bufnum = -1 local source = sources.files local filetype = source.filetype local prompt = '> ' local use_history = source.history local num_tab = 0 local prev_input = -1 function M.init(new_source, directory) source = new_source if source.init then source.init() end if source.filetype then filetype = source.filetype else filetype = 'findr' end winnum = api.call_function('winnr', {}) view.init(filetype) api.command('lcd '..directory) M.reset() if source.history then use_history = source.history else use_history = false end if use_history then model.history.source() end bufnum = api.call_function('bufnr',{}) end function M.update() local input = user_io.getinput(prompt) if input ~= prev_input then num_tab = 0 model.update(input, source.table) selected_loc = math.min(utils.tablelength(model.display)+1, 2) view.redraw(model.display, input, selected_loc) end prev_input = input end function M.select_next() local success = model.select_next() selected_loc = selected_loc + ( success and 1 or 0 ) if selected_loc == api.call_function('winheight',{'.'})+1 then selected_loc = selected_loc - 1 model.scroll_down() end view.redraw(model.display, user_io.getinput(prompt), selected_loc) num_tab = 0 end function M.select_prev() local success = model.select_prev() selected_loc = selected_loc - ( success and 1 or 0 ) if selected_loc == startloc and success then selected_loc = selected_loc + 1 model.scroll_up() elseif not success then selected_loc = 1 end view.redraw(model.display, user_io.getinput(prompt), selected_loc) num_tab = 0 end function M.history_next() model.history.next() local dir, input = model.history.get() local idx, jump_point = model.history.get_jumpoint() M.change_dir(dir) model.history.set_jumpoint(idx, jump_point) view.setinput(prompt, input) api.command('startinsert!') num_tab = 0 end function M.history_prev() model.history.prev() local dir, input = model.history.get() local idx, jump_point = model.history.get_jumpoint() M.change_dir(dir) model.history.set_jumpoint(idx, jump_point) view.setinput(prompt, input) api.command('startinsert!') num_tab = 0 end local function reset_scroll() api.command('call feedkeys("\\<c-o>zh", "n")') end local function hard_reset_scroll() api.command('set wrap') api.command('set nowrap') end function M.reset() num_tab = 0 model.reset() startloc = 1 selected_loc = 2 if use_history then local cwd = api.call_function('getcwd',{}) model.history.reset(cwd, '') end if not source.prompt then prompt = '> ' else prompt = source.prompt() end view.setinput(prompt, '') model.update('', source.table) view.redraw(model.display, '', selected_loc) api.command('normal ze') api.command('startinsert!') end function M.change_dir(dir) if dir == '~' or api.call_function('isdirectory', {dir}) == 1 then api.command('lcd '..dir) M.reset() end end function M.parent_dir() local input = user_io.getinput(prompt) M.change_dir('../') view.setinput(prompt, input) end local function on_prompt() local pos if api.vim8 then pos = api.call_function('getcurpos', {})[4]-1 else pos = vim.api.nvim_win_get_cursor(0)[2] end return pos == string.len(prompt) end function M.backspace() if on_prompt() then if filetype == 'findr-files' then M.parent_dir() end else reset_scroll() if api.vim8 then api.command('call feedkeys("\\<left>\\<delete>", "n")') else vim.api.nvim_command('call nvim_feedkeys("\\<BS>", "n", v:true)') end end end function M.clear() if not on_prompt() then if api.vim8 then local pos = api.call_function('getcurpos', {})[4]-1 local line = api.call_function('getline', {1}) local input = string.sub(line,pos+1,string.len(line)) view.setinput(prompt, input) api.call_function('setpos', {'.', {0, 1, string.len(prompt)+1}}) if string.len(line) == pos+1 then api.command('call feedkeys("\\<left>", "n")') end else local pos = vim.api.nvim_win_get_cursor(0)[2] local line = vim.api.nvim_call_function('getline', {startloc}) local input = string.sub(line,pos+1,string.len(line)) view.setinput(prompt, input) vim.api.nvim_win_set_cursor(0, {1, string.len(prompt)}) end hard_reset_scroll() end end function M.delete_prev_word() if not on_prompt() then if api.vim8 then local pos = api.call_function('getcurpos', {})[4]-1 local line = api.call_function('getline', {1}) local before = string.sub(line, string.len(prompt)+1,pos+1) local del_idx = string.find(before, "%s*[^ ]*%s*$")-1 before = string.sub(before, 0, del_idx) local input = string.sub(line,pos+1,string.len(line)) view.setinput(prompt, before..input) api.call_function('setpos', {'.', {0, 1, string.len(prompt) + string.len(before)+1}}) if string.len(line) == pos+1 then api.command('call feedkeys("\\<left>", "n")') end else local pos = vim.api.nvim_win_get_cursor(0)[2] local line = vim.api.nvim_call_function('getline', {startloc}) local input = string.sub(line,pos+1,string.len(line)) local before = string.sub(line, string.len(prompt)+1,pos+1) local del_idx = string.find(before, "%s*[^ ]*%s*$")-1 before = string.sub(before, 0, del_idx) view.setinput(prompt, before..input) vim.api.nvim_win_set_cursor(0, {1, string.len(prompt) + string.len(before)}) end hard_reset_scroll() elseif filetype == 'findr-files' then M.parent_dir() end end function M.clear_to_parent() if not on_prompt() then if api.vim8 then local pos = api.call_function('getcurpos', {})[4]-1 local line = api.call_function('getline', {1}) local input = string.sub(line,pos+1,string.len(line)) view.setinput(prompt, input) api.call_function('setpos', {'.', {0, 1, string.len(prompt)+1}}) if string.len(line) == pos+1 then api.command('call feedkeys("\\<left>", "n")') end else local pos = vim.api.nvim_win_get_cursor(0)[2] local line = vim.api.nvim_call_function('getline', {startloc}) local input = string.sub(line,pos+1,string.len(line)) view.setinput(prompt, input) vim.api.nvim_win_set_cursor(0, {1, string.len(prompt)}) end hard_reset_scroll() elseif filetype == 'findr-files' then M.parent_dir() end end function M.left() if not on_prompt() then api.command('call feedkeys("\\<left>", "n")') reset_scroll() end end function M.delete() local pos local line if api.vim8 then pos = api.call_function('getpos', {'.'})[2]-1 line = api.call_function('getline', {startloc}) else pos = vim.api.nvim_win_get_cursor(0)[2] line = vim.api.nvim_call_function('getline', {startloc}) end if pos ~= string.len(line) then api.command('call feedkeys("\\<delete>", "n")') end end function M.expand() local input = user_io.getinput(prompt) if input == '~' then M.change_dir('~') else local filename = user_io.get_filename(prompt) if api.call_function('isdirectory', {filename}) == 1 then M.change_dir(filename) elseif num_tab >= 1 then M.edit() api.command('call feedkeys("\\<esc>", "n")') else num_tab = num_tab + 1 end end end function M.quit() api.command(winnum..'windo echo ""') api.command('silent bw '..bufnum) end function M.edit(editcmd) local fname if filetype == 'findr-files' then fname = user_io.get_filename(prompt) else fname = user_io.get_selected(prompt) end local command = source.sink(fname, editcmd) if use_history then model.history.update(user_io.get_dir_file_pair(prompt)) model.history.write() end M.quit() api.command(winnum..'windo '..command) end maps.set() return M
--[[ Info.lua --]] return { appName = "Collection Agent", author = "Rob Cole", authorsWebsite = "www.robcole.com", donateUrl = "http://www.robcole.com/Rob/Donate", platforms = { 'Windows', 'Mac' }, pluginId = "com.robcole.lightroom.CollectionAgent", xmlRpcUrl = "http://www.robcole.com/Rob/_common/cfpages/XmlRpc.cfm", LrPluginName = "rc Collection Agent", LrSdkMinimumVersion = 3.0, LrSdkVersion = 5.0, LrPluginInfoUrl = "http://www.robcole.com/Rob/ProductsAndServices/CollectionAgentLrPlugin", LrPluginInfoProvider = "ExtendedManager.lua", LrToolkitIdentifier = "com.robcole.lightroom.CollectionAgent", LrInitPlugin = "Init.lua", LrShutdownPlugin = "Shutdown.lua", LrExportMenuItems = { { title = "&Maintain Dumb Copies of Smart Collections", file = "mMaintDumbSmarts.lua", }, { title = "&Duplicate (Collection or Set)", file = "mDuplicate.lua", }, { title = "&Set Sync Source (Collection or Set)", file = "mSetSyncSource.lua", }, { title = "&Sync (Selected Collections or Sets)", file = "mSync.lua", }, { title = "&Set Copy Sources (Collections and/or Sets)", file = "mSetCopySources.lua", }, { title = "&Copy (Collections and/or Sets)", file = "mCopy.lua", }, { title = "&Import All (Smart Collections)", file = "mImportAll.lua", }, { title = "&Edit (Selected Photos) As Collection", file = "mEdit.lua", }, }, VERSION = { display = "4.0.3 Build: 2015-01-23 02:54:15" }, }
--[[ ******************************************************************************** Project owner: RageQuit community Project name: GTW-RPG Developers: Mr_Moose Source code: https://github.com/404rq/GTW-RPG/ Bugtracker: https://discuss.404rq.com/t/issues Suggestions: https://discuss.404rq.com/t/development Version: Open source License: BSD 2-Clause Status: Stable release ******************************************************************************** ]]-- -- Object ids: 822 plant, 1454 bale -- Globals plants_age = { } player_plants = { } plants_pos = {{{ }}} seed_moey = 90 -- Finds the nearest plant function find_nearest(player) local x,y,z = getElementPosition(player) local dist = 16 if not plants_pos[player] then plants_pos[player] = { } end for w=1, #plants_pos[player] do if plants_pos[player][w][1] and plants_pos[player][w][2] and plants_pos[player][w][3] then local lx,ly,lz = plants_pos[player][w][1],plants_pos[player][w][2],plants_pos[player][w][3] if dist > getDistanceBetweenPoints3D( x,y,z, lx,ly,lz ) then dist = getDistanceBetweenPoints3D( x,y,z, lx,ly,lz ) end end end return dist or 16 end -- Plant the seed function plantSeed( player ) if getPlayerTeam(player) == getTeamFromName("Civilians") and getElementData(player, "Occupation") == "Farmer" and getPlayerMoney(player) > seed_moey and getPedOccupiedVehicle(player) and getElementModel( getPedOccupiedVehicle( player )) == 531 and player_plants[player] < 200 then -- Plant the seed local x,y,z = getElementPosition(player) if not plants_pos then plants_pos = { } end if find_nearest(player) > 15 then takePlayerMoney(player, seed_moey) local plant = createObject( 822, x, y, z-1 ) local plantCol = createColSphere( x, y, z-2, 5 ) local blip = createBlip( x, y, z, 0, 1, 255, 0, 0, 150, 0, 100, player ) setObjectScale( plant, 0.005 ) if not plants_pos[player] then plants_pos[player] = { } end if not plants_pos[player][player_plants[player]] then plants_pos[player][player_plants[player]] = { } end -- Make the plant grow up plants_age[plant] = 0; local currentPlantsCounter = player_plants[player] plants_pos[player][currentPlantsCounter][1] = x plants_pos[player][currentPlantsCounter][2] = y plants_pos[player][currentPlantsCounter][3] = z local time_to_grow = math.random(285, 320) setTimer( function() setObjectScale( plant, getObjectScale(plant)+0.005 ) plants_age[plant] = plants_age[plant] + 1 end, 4000, time_to_grow ) -- Status message exports.GTWtopbar:dm( "Farmer: Your seed has been planted, make sure it's safe from intruders!", player, 0, 255, 0 ) player_plants[player] = player_plants[player] + 1; -- Show status setTimer( function() if isElement(blip) then setBlipColor( blip, 0, 255, 0, 100 ) end end, time_to_grow*4000, 1 ) -- Clean up setTimer( function() if isElement(plant) then destroyElement(plant) destroyElement(plantCol) destroyElement(blip) plants_age[plant] = nil plants_pos[player][currentPlantsCounter][1] = nil plants_pos[player][currentPlantsCounter][2] = nil plants_pos[player][currentPlantsCounter][3] = nil -- Status message if isElement(player) then exports.GTWtopbar:dm( "Farmer: Your plant rotted and was destroyed", player, 255, 200, 0 ) end end end, 7200000, 1 ) addEventHandler( "onColShapeHit", plantCol, function ( hitElement, matchingdimension ) if hitElement and isElement(hitElement) and getElementType(hitElement) == "player" and getPedOccupiedVehicle(hitElement) and getElementModel( getPedOccupiedVehicle( hitElement )) == 532 and plants_age[plant] and plants_age[plant] > time_to_grow - 1 then -- Clear and makes a bale plants_age[plant] = nil setElementModel(plant, 1454) setBlipColor( blip, 255, 200, 0, 100 ) setElementCollisionsEnabled( plant, false ) local px,py,pz = getElementPosition(plant) setElementPosition(plant, px,py,pz+1.1) -- Status message exports.GTWtopbar:dm( "Farmer: One of your plants has been harvested", player, 255, 200, 0 ) elseif hitElement and isElement(hitElement) and getElementType(hitElement) == "player" and not getPedOccupiedVehicle(hitElement) and getElementModel(plant) == 1454 then -- Pay for the bale givePlayerMoney(hitElement,math.random(150,300)) -- Increase stats by 1/plant local playeraccount = getPlayerAccount( hitElement ) local farmer_plants = exports.GTWcore:get_account_data( playeraccount, "GTWdata.stats.plants_harvested" ) or 0 exports.GTWcore:set_account_data( playeraccount, "GTWdata.stats.plants_harvested", farmer_plants + 1 ) -- Status message exports.GTWtopbar:dm( "Farmer: One of your plants has been sold", player, 255, 200, 0 ) player_plants[player] = player_plants[player] - 1 if isElement(plant) then destroyElement(plant) destroyElement(plantCol) destroyElement(blip) plants_pos[player][currentPlantsCounter][1] = nil plants_pos[player][currentPlantsCounter][2] = nil plants_pos[player][currentPlantsCounter][3] = nil plants_age[plant] = nil end end end) else exports.GTWtopbar:dm( "Farmer: You can't plant your seed too close to eachothers", player, 255, 0, 0 ) end elseif player_plants[player] and player_plants[player] > 199 then exports.GTWtopbar:dm( "Farmer: You can't plant more seed right now, let your current plants be ready first", player, 255, 0, 0 ) end end addCommandHandler( "plant", plantSeed ) for w,pl in pairs(getElementsByType("player")) do bindKey( pl, "n", "down", "plant" ) player_plants[pl] = 0 end addCommandHandler("gtwinfo", function(plr, cmd) outputChatBox("[GTW-RPG] "..getResourceName( getThisResource())..", by: "..getResourceInfo( getThisResource(), "author")..", v-"..getResourceInfo( getThisResource(), "version")..", is represented", plr) end) addEventHandler("onPlayerLogin", root, function() bindKey( source, "n", "down", "plant" ) player_plants[source] = 0 end) function enterVehicle( thePlayer, seat, jacked ) if getElementModel(source) == 531 and getElementData(thePlayer, "Occupation") == "Farmer" then exports.GTWtopbar:dm( "Farmer: Press n to plant your seed", thePlayer, 255, 200, 0 ) end end addEventHandler ( "onVehicleEnter", getRootElement(), enterVehicle )
--[[ UI面板类型的枚举 enum_PanelName = { [1] = "LoginPanel", [2] = "RegisterPanel" } --]] Unity = CS.UnityEngine; Sockets = CS.System.Net.Sockets; playerData = {} --玩家数据 propsOwned = {}--拥有的道具 shopItem = {} --商店物品 --DG = CS.DG.Tweening.DoTween;
------------------------------------------------------------------------------ -- -- This file is part of the Corona game engine. -- For overview and more information on licensing please refer to README.md -- Home page: https://github.com/coronalabs/corona -- Contact: support@coronalabs.com -- ------------------------------------------------------------------------------ -- -- Platform dependent initialization for Simulators -- -- Tell luacheck not to flag our builtin globals -- luacheck: globals system -- luacheck: globals display -- luacheck: globals native -- luacheck: globals network -- luacheck: globals easing -- luacheck: globals Runtime -- luacheck: globals graphics -- luacheck: globals loadstring local params = ... local onShellComplete = params.onShellComplete local exitCallback = params.exitCallback -------------------------------------------------------------------------------- local PluginSync = { queue = {}, now = os.time(), -- This is the catalog of plugin manifest. clientCatalogFilename = 'catalog.json', clientCatalog = { Version = 3 }, -- It's not mandatory to declare this here. We're doing it for the sake -- of making it clear that we're going to populate these values later. CatalogFilenamePath = "", } local json = require("json") -- luacheck: push -- luacheck: ignore 212 -- Unused argument. function PluginSync:debugPrint(...) -- Uncomment to get verbose reporting on PluginSync activities -- print("PluginSync: ", ...) end -- luacheck: pop function PluginSync:LoadCatalog() local f = io.open( self.CatalogFilenamePath ) if not f then return end local content = f:read( "*a" ) f:close() if not content then return end local catalog = json.decode( content ) if not catalog then return end if not catalog.Version then -- This file isn't versioned. return end if catalog.Version ~= self.clientCatalog.Version then -- We want to use the catalog ONLY when the -- version number is an exact match. return end local catalogBuildNumber = catalog.CoronaBuild if catalogBuildNumber ~= system.getInfo("build") then return end self.clientCatalog = catalog end function PluginSync:initialize( platform ) self.platform = platform self.CatalogFilenamePath = system.pathForFile( self.clientCatalogFilename, system.PluginsDirectory ) self:LoadCatalog() end function PluginSync:UpdateClientCatalog() self.clientCatalog.CoronaBuild = system.getInfo("build") local content = json.encode( self.clientCatalog ) local f, ioErrorMessage = io.open( self.CatalogFilenamePath, 'w' ) -- erase previous contents if f then f:write( content ) f:close() else local message = "Error updating Corona's plugin catalog." if ( type( ioErrorMessage ) == "string" ) and ( string.len( ioErrorMessage ) > 0 ) then message = message .. "\nReason: " .. ioErrorMessage end print( message ) end end function PluginSync:addPluginToQueueIfRequired( required_plugin ) local pluginName = required_plugin.pluginName local publisherId = required_plugin.publisherId local key = tostring(publisherId) .. '/' .. pluginName required_plugin.clientCatalogKey = key -- Find reasons to queue the plugin for download. local should_queue = false local manifest = self.clientCatalog[ key ] should_queue = should_queue or ( not manifest ) if type(manifest) == 'table' and type(manifest.lastUpdate) == 'number' then local age = os.difftime(self.now, manifest.lastUpdate) -- update plugins every 24 hours or so should_queue = should_queue or ( age > 86400 ) else should_queue = true end if should_queue then -- Queue for download. table.insert( self.queue, required_plugin ) end end local function collectPlugins(localQueue, extractLocation, platform, continueOnError, asyncOnComplete) local plugins = {} for i=1,#localQueue do local pluginInfo = localQueue[i] plugins[pluginInfo.pluginName] = {} if pluginInfo.json then plugins[pluginInfo.pluginName] = json.decode(pluginInfo.json) end plugins[pluginInfo.pluginName].publisherId = pluginInfo.publisherId if continueOnError and asyncOnComplete then if type(plugins[pluginInfo.pluginName].supportedPlatforms) == 'table' then if not plugins[pluginInfo.pluginName].supportedPlatforms[platform] then if plugins[pluginInfo.pluginName].supportedPlatforms[platform] ~= false then plugins[pluginInfo.pluginName].supportedPlatforms[platform] = true end end end end end local _, sim_build_number = string.match( system.getInfo( "build" ), '(%d+)%.(%d+)' ) local collectorParams = { pluginPlatform = platform, plugins = plugins, destinationDirectory = system.pathForFile("", system.PluginsDirectory), build = sim_build_number, extractLocation = extractLocation, continueOnError = continueOnError, } return params.shellPluginCollector(json.encode(collectorParams), asyncOnComplete) end function PluginSync:downloadQueuedPlugins( onComplete ) -- Only download if there have been keys added if #self.queue == 0 then -- Nothing to do. return end self.onComplete = onComplete collectPlugins(self.queue, system.pathForFile("", system.PluginsDirectory), self.platform, true, function(result) local updateTime = self.now if type(result.result) == 'string' then updateTime = nil local res = result.result:gsub('%[(.-)%]%((https?://.-)%)', '%1 (%2)') print("WARNING: there was an issue while downloading simulator plugin placeholders:\n" .. res) end for i=1,#self.queue do local key = self.queue[i].clientCatalogKey self.clientCatalog[ key ] = { lastUpdate = updateTime } end self:UpdateClientCatalog() self.onComplete() end) end local function onInternalRequestUnzipPlugins( event ) -- Verify that a destination path was provided. local destinationPath = event.destinationPath if type( destinationPath ) ~= "string" then return "onInternalRequestUnzipPlugins() Destination path argument was not provided." end -- Do not continue if this app does not use any plugins. if #params.plugins <= 0 then return true end local result = collectPlugins(params.plugins, destinationPath, event.platform or params.platform, false, nil) if result == nil then return true else return result end end Runtime:addEventListener( "_internalRequestUnzipPlugins", onInternalRequestUnzipPlugins ) local function onInternalQueryAreAllPluginsAvailable( _ ) return true end Runtime:addEventListener( "_internalQueryAreAllPluginsAvailable", onInternalQueryAreAllPluginsAvailable ) local function loadMain( onComplete ) PluginSync:initialize( params.platform ) if not params.shellPluginCollector then -- No way to download. onComplete( ) return end local required_plugins = params.plugins if ( not required_plugins ) or ( #required_plugins == 0 ) then -- Nothing to download. onComplete( ) return end -- Find what needs to be downloaded. for i=1,#required_plugins do PluginSync:addPluginToQueueIfRequired( required_plugins[i] ) end if #PluginSync.queue == 0 then -- Nothing to download. onComplete( ) else -- Download. PluginSync:downloadQueuedPlugins( onComplete ) end end loadMain( onShellComplete ) -- Only override os.exit if a function is provided if exitCallback then _G.os.exit = function( code ) print( code ) exitCallback( code ) end end --------------------------------------------------------------------------------
project "MFVE" _enginefiledir = "%{wks.location}/mfve/" location(_enginefiledir) uuid(os.uuid()) kind "StaticLib" language "C++" cppdialect "C++17" --staticruntime "on" targetdir(_apptargetdir) objdir(_appobjdir) defines { --# GLFW #-- "GLFW_INCLUDE_VULKAN", --# glm #-- "GLM_FORCE_RADIANS", "GLM_FORCE_DEPTH_ZERO_TO_ONE" } files { --# mfve Src #-- _enginefiledir .. "src/**.h", _enginefiledir .. "src/**.c", _enginefiledir .. "src/**.hpp", _enginefiledir .. "src/**.cpp", --# glm #-- "%{IncludeDir.glm}/glm/**.hpp", "%{IncludeDir.glm}/glm/**.inl", --# Cpp Log #-- "%{IncludeDir.CppLog}/CppLog/**.h", --# whereami #-- "%{IncludeDir.whereami}/**.h", "%{IncludeDir.whereami}/**.c", --# stb #-- "%{IncludeDir.stb}/**.h", "%{IncludeDir.stb}/**.c", } includedirs { _enginefiledir .. "src/", --# Vendor #-- "%{IncludeDir.GLFW}", "%{IncludeDir.glm}", "%{IncludeDir.CppLog}", "%{IncludeDir.whereami}", "%{IncludeDir.stb}", --# Vulkan SDK #-- "%{VULKAN_SDK}/include/" } libdirs { --# Vulkan SDK #-- "%{VULKAN_SDK}/lib/" } links { --# Vendor #-- "GLFW" } filter "action: vs*" pchheader("mfve_pch.h") pchsource(_enginefiledir .. "src/mfve_pch.cpp") filter "action: not vs*" pchheader ("mfve_pch.h") filter "system:linux" links { --# OS Links #-- "dl", "pthread", "X11", "Xxf86vm", "Xrandr", "Xi", --# SPIR-V & ShaderC #-- "shaderc_combined", "spirv-cross-core", "spirv-cross-glsl", --# Vulkan SDK #-- "vulkan" } filter "system:windows" systemversion "latest" defines { "_CRT_SECURE_NO_WARNINGS", "_ALLOW_ITERATOR_DEBUG_LEVEL_MISMATCH" } links { --# SPIR-V & ShaderC #-- "shaderc_combined.lib", --"shaderc_shared.lib", "spirv-cross-core.lib", "spirv-cross-glsl.lib", --# Vulkan SDK #-- "vulkan-1.lib", "VkLayer_utils.lib" } filter "configurations:Debug" defines { "MFVE_DEBUG", "MFVE_ENABLE_LOGGER", "MFVE_ENABLE_VK_VALIDATION" } symbols "On" filter "configurations:Release" defines { "MFVE_RELEASE" } runtime "Release" optimize "On" -- Must change runtime to Release for Windows. filter { "configurations:Debug", "system:windows" } runtime "Release" filter { "configurations:Debug", "system:not windows" } runtime "Debug"
local function overwrite_setting(setting_type, setting_name, value) -- setting_type: [bool-setting | int-setting | double-setting | string-setting] if data.raw[setting_type] then local s = data.raw[setting_type][setting_name] if s then if setting_type == 'bool-setting' then s.forced_value = value else s.default_value = value s.allowed_values = {value} end s.hidden = true else log('Error: missing setting ' .. setting_name) end else log('Error: missing setting type ' .. setting_type) end end -- Bob's Modules if mods['bobmodules'] then overwrite_setting('bool-setting', 'bobmods-modules-enablegreenmodules', false) overwrite_setting('bool-setting', 'bobmods-modules-enablerawspeedmodules', false) overwrite_setting('bool-setting', 'bobmods-modules-enablerawproductivitymodules', false) overwrite_setting('bool-setting', 'bobmods-modules-enablegodmodules', false) overwrite_setting('bool-setting', 'bobmods-modules-enableproductivitylimitation', true) overwrite_setting('bool-setting', 'bobmods-modules-productivityhasspeed', true) overwrite_setting('bool-setting', 'bobmods-modules-transmitproductivity', false) overwrite_setting('double-setting', 'bobmods-modules-perlevel-bonus-speed', 0.05) overwrite_setting('double-setting', 'bobmods-modules-perlevel-bonus-pollution', 0.025) overwrite_setting('double-setting', 'bobmods-modules-perlevel-bonus-consumption', 0.05) overwrite_setting('double-setting', 'bobmods-modules-perlevel-bonus-productivity', 0.015) overwrite_setting('double-setting', 'bobmods-modules-perlevel-bonus-pollutioncreate', 0.2) overwrite_setting('double-setting', 'bobmods-modules-perlevel-penalty-speed', 0) overwrite_setting('double-setting', 'bobmods-modules-perlevel-penalty-pollution', 0.01) overwrite_setting('double-setting', 'bobmods-modules-perlevel-penalty-consumption', 0.05) overwrite_setting('double-setting', 'bobmods-modules-start-bonus-speed', 0.2) overwrite_setting('double-setting', 'bobmods-modules-start-bonus-pollution', 0) overwrite_setting('double-setting', 'bobmods-modules-start-bonus-consumption', 0.2) overwrite_setting('double-setting', 'bobmods-modules-start-bonus-productivity', 0) overwrite_setting('double-setting', 'bobmods-modules-start-bonus-pollutioncreate', 0) overwrite_setting('double-setting', 'bobmods-modules-start-penalty-speed', 0.15) overwrite_setting('double-setting', 'bobmods-modules-start-penalty-pollution', 0.02) overwrite_setting('double-setting', 'bobmods-modules-start-penalty-consumption', 0.4) end
local time = {} local nf = util.NiceFloat local EVENT = 1 local PRINT = 2 function time:Start() self.start = SysTime() self.finished = nil self.events = {} self.prints = {} return self end function time:Log(event) if not self.start then self:Start() end -- Print later so as to not induce too much blocking I/O table.insert(self.events, {EVENT, event, SysTime()}) end function time:Finish() self.finished = SysTime() local last = self.start for k, v in ipairs(self.events) do if v[1] == EVENT then self:Print(v[2], "took", nf(v[3]-last), " - T+"..nf(v[3]-self.start)) last = v[3] elseif v[1] == PRINT then self:Print(table.UnpackNil(v[2])) end end self:Print("Finished in ", nf(self.finished-self.start)) self.start = nil end function time:Print(...) if self.finished then MsgC(Color(31, 255, 150), SPrint("["..self.name.."] ", ...).."\n") else table.insert(self.events, {PRINT, table.PackNil(...)}) end end function XLIB.Time(name) if not name or not tostring(name) then XLIB.WarnTrace("XLIB.Time needs a stringable identifier!!!") name = SysTime() end return setmetatable({name=tostring(name)}, {__index=time, __call=time.Log}) end
-- Copyright (C) Izio, Inc - All Rights Reserved -- Unauthorized copying of this file, via any medium is strictly prohibited -- Proprietary and confidential -- Written by Romain Billot <romainbillot3009@gmail.com>, Jully 2017 RegisterNetEvent("iWeapons:cbSearchInfos") local weaponPed = {} local weaponsLoaded = false local currentMenu local currentShop = {hash="s_m_m_ammucountry", x=1692.733, y=3761.895, z=34.705, a=218.535} local alreadySearched = false -- Configure the coordinates for the vendors. local weapon_peds = { {hash="s_m_m_ammucountry", x=1692.733, y=3761.895, z=34.705, a=218.535}, {hash="s_m_m_ammucountry", x=-330.933, y=6085.677, z=31.455, a=207.323}, {hash="s_m_y_ammucity_01", x=253.629, y=-51.305, z=69.941, a=59.656}, {hash="s_m_y_ammucity_01", x=841.363, y=-1035.350, z=28.195, a=328.528}, {hash="s_m_y_ammucity_01", x=-661.317, y=-933.515, z=21.829, a=152.798}, {hash="s_m_y_ammucity_01", x=-1304.413, y=-395.902, z=36.696, a=44.440}, {hash="s_m_y_ammucity_01", x=-1118.037, y=2700.568, z=18.554, a=196.070}, {hash="s_m_y_ammucity_01", x=2566.596, y=292.286, z=108.735, a=337.291}, {hash="s_m_y_ammucity_01", x=-3173.182, y=1089.176, z=20.839, a=223.930}, } local weaponsSubMenu = { ["cata"] = { title = "Catégorie A", name = "cata", buttons = { -- {name = "Catégorie A", targetFunction = "BuyWeapon", targetArrayParam = "cata" }, -- {name = "Catégorie B", targetFunction = "BuyWeapon", targetArrayParam = "catb" }, -- {name = "Catégorie C", targetFunction = "BuyWeapon", targetArrayParam = "catc" }, -- {name = "Catégorie D", targetFunction = "BuyWeapon", targetArrayParam = "catd" }, -- {name = "Retour aux catégorie", targetFunction = "OpenMenu", targetArrayParam = weaponsMainMenu["main"] } } }, ["catb"] = { title = "Catégorie B", name = "catb", buttons = { -- {name = "Catégorie A", targetFunction = "BuyWeapon", targetArrayParam = "cata" }, -- {name = "Catégorie B", targetFunction = "BuyWeapon", targetArrayParam = "catb" }, -- {name = "Catégorie C", targetFunction = "BuyWeapon", targetArrayParam = "catc" }, -- {name = "Catégorie D", targetFunction = "BuyWeapon", targetArrayParam = "catd" }, -- {name = "Retour aux catégorie", targetFunction = "OpenMenu", targetArrayParam = weaponsMainMenu["main"] } } }, ["catc"] = { title = "Catégorie C", name = "catc", buttons = { {name = "Arme1 test", targetFunction = "BuyWeapon", targetArrayParam = "WEAPON_KNIFE" }, {name = "Arme2 test", targetFunction = "BuyWeapon", targetArrayParam = "WEAPON_NIGHTSTICK" }, -- {name = "Catégorie C", targetFunction = "BuyWeapon", targetArrayParam = "catc" }, -- {name = "Catégorie D", targetFunction = "BuyWeapon", targetArrayParam = "catd" }, -- {name = "Retour aux catégorie", targetFunction = "OpenMenu", targetArrayParam = weaponsMainMenu["main"] } } }, ["catd"] = { title = "Catégorie D", name = "catd", buttons = { {name = "Arme1 test", targetFunction = "BuyWeapon", targetArrayParam = "WEAPON_VINTAGEPISTOL" }, {name = "Arme2 test", targetFunction = "BuyWeapon", targetArrayParam = "WEAPON_POOLCUE" }, -- {name = "Catégorie C", targetFunction = "BuyWeapon", targetArrayParam = "catc" }, -- {name = "Catégorie D", targetFunction = "BuyWeapon", targetArrayParam = "catd" }, -- {name = "Retour aux catégorie", targetFunction = "OpenMenu", targetArrayParam = weaponsMainMenu["main"] } } } } local weaponsMainMenu = { ["main"] = { title = "Acheter une arme", name = "main", buttons = { } } } Citizen.CreateThread(function() while true do Citizen.Wait(0) playerPed = GetPlayerPed(-1) playerCoords = GetEntityCoords(playerPed, 0) if (not weaponsLoaded) then for k,v in pairs(weapon_peds) do RequestModel(GetHashKey(v.hash)) while not HasModelLoaded(GetHashKey(v.hash)) do Wait(1) end -- Load the animation for the vendors RequestAnimDict("amb@prop_human_bum_shopping_cart@male@base") while not HasAnimDictLoaded("amb@prop_human_bum_shopping_cart@male@base") do Wait(0) end weaponPed = CreatePed(4, v.hash, v.x, v.y, v.z, v.a, false, false) SetBlockingOfNonTemporaryEvents(weaponPed, true) SetPedFleeAttributes(weaponPed, 0, 0) SetEntityInvincible(weaponPed, true) -- Annimations SetAmbientVoiceName(weaponPed, "AMMUCITY") TaskPlayAnim(weaponPed,"amb@prop_human_bum_shopping_cart@male@base","base", 8.0, 0.0, -1, 1, 0, 0, 0, 0) end weaponsLoaded = true end -- Check if the player is at the store and show him the menu for k,v in pairs(weapon_peds) do local doordist = Vdist(playerCoords.x, playerCoords.y, playerCoords.z, v.x, v.y, v.z) if doordist < 11 then SetCurrentPedWeapon(playerPed, GetHashKey("WEAPON_UNARMED"), true) end if doordist < 4 then currentShop = v if Menu.hidden then buyWeaponInfo("Appuyez sur ~INPUT_CONTEXT~ pour regarder les armes", 0) end if IsControlJustPressed(1, 38) then if not(alreadySearched) then TriggerServerEvent("iWeapons:searchInfos") else Menu.hidden = not(Menu.hidden) if not(Menu.hidden) then OpenMenu(weaponsMainMenu["main"]) end end --Open menu elseif IsControlJustPressed(1, 177) then if currentMenu == "main" then CloseMenu("test") print("closed") else OpenMenu(weaponsMainMenu["main"]) print("opened main by back") end end elseif Vdist(playerCoords.x, playerCoords.y, playerCoords.z, currentShop.x, currentShop.y, currentShop.z) >= 4 and not(Menu.hidden) then CloseMenu("osef") print("closed2") end end Menu.renderGUI() end end) function OpenMenu(menu) ClearMenu() MenuTitle = menu.title for i = 1, #menu.buttons do Menu.addButton(menu.buttons[i].name, menu.buttons[i].targetFunction, menu.buttons[i].targetArrayParam) end Menu.hidden = false currentMenu = menu.name end function CloseMenu(fake) ClearMenu() Menu.hidden = true currentMenu = nil end function buyWeaponInfo(text, state) SetTextComponentFormat("STRING") AddTextComponentString(text) DisplayHelpTextFromStringLabel(0, state, 0, -1) end function BuyWeapon(weaponHash) TriggerServerEvent("iweapons:checkForBuy", weaponHash) end RegisterNetEvent("iWeapons:giveWeapon") AddEventHandler("iWeapons:giveWeapon", function(weapon) GiveWeaponToPed(GetPlayerPed(-1), GetHashKey(weapon), 2000, false) end) AddEventHandler("iWeapons:cbSearchInfos", function(weaponInfos) for i = 1, #weaponInfos do table.insert(weaponsMainMenu["main"].buttons, {name = weaponInfos[i].name .. " " .. weaponInfos[i].weight .."g, ".. weaponInfos[i].price .."$.", targetFunction = "BuyWeapon", targetArrayParam = weaponInfos[i].hash }) end alreadySearched = true Menu.hidden = not(Menu.hidden) if not(Menu.hidden) then OpenMenu(weaponsMainMenu["main"]) end end)
-- Contribution by Guy Mc Donald -- adds jpg files to a tree -- dynamically fills subdirectories in the tree require 'iuplua' require 'iupluacontrols' require 'lfs' require "imlua" require "cdlua" require "cdluaim" require "iupluacd" function View(name) local filename = name..".jpg" local image = im.FileImageLoad(filename) local height = 740 local width = 1020 local cnv = iup.canvas{rastersize =width.."x"..height, border = "NO"} cnv.image = image function cnv:map_cb() self.canvas = cd.CreateCanvas(cd.IUP, self) end function cnv:action() self.canvas:Activate() self.canvas:Clear() self.image:cdCanvasPutImageRect(self.canvas,0,0,width,height,0,0,0,0) end local dlg = iup.dialog{cnv, parentdialog="main"} dlg:show() end function get_dir (dir_path) local files = {} local dirs = {} for f in lfs.dir(dir_path) do if f ~= '.' and f ~= '..' then if lfs.attributes(dir_path..'/'..f,'mode') == 'file' then if string.upper(string.sub(f,-3))=="JPG" then table.insert(files,string.sub(f,1,string.len(f)-4)) end else table.insert(dirs,f.."/") end end end return files,dirs end tree = iup.tree {} tree.addexpanded = "no" function set (id,value,attrib) iup.TreeSetUserId(tree,id,{value,attrib}) end function get(id) return iup.TreeGetUserId(tree,id) end function fill (dir_path,id) local files,dirs = get_dir(dir_path) id = id + 1 local state = "STATE"..id for i = #files,1,-1 do tree.addleaf = files[i] set(id,dir_path..'/'..files[i]) end for i = #dirs,1,-1 do tree.addbranch = dirs[i] set(id,dir_path..'/'..dirs[i],'dir') tree['addleaf'..id] = "dummy" -- add a dummy node so branchopen_cb can be called end end function tree:executeleaf_cb(id) local t=get(id) --*** Selected Photo *** if t[2]~='dir' then View(t[1]) end end function tree:branchopen_cb(id) tree.value = id local t = get(id) if t[2] == 'dir' then tree['delnode'..id+1] = 'selected' -- remove dummy fill(t[1],id) set(id,t[1],'xdir') -- mark branch as filled end end --Let's get started! dir_path="D:/scuri/Media/Outras" local dlg = iup.dialog{tree; title = "Photo Options"} iup.SetHandle("main", dlg) dlg:map() fill(dir_path,0) dlg:show() iup.MainLoop()