content
stringlengths
5
1.05M
require("KeyCodes") --[[ Properties that will be exposed to c++ Currently only numeric values supported --]] Props = { XOffset = 0, YOffset = 1 } --[[ Called once a frame Params: Entity: the entity this script belongs to ts: The time (in seconds) since the last update --]] function OnUpdate(Entity, ts) local transform = Entity:Get__TransformComponent() transform.Translation.x = math.sin(transform.Rotation.z) + Props.XOffset transform.Translation.y = math.cos(transform.Rotation.z) + Props.YOffset transform.Rotation.z = transform.Rotation.z + 3 * ts local sprite = Entity:Get__SpriteRendererComponent() sprite.Color.x = (math.sin(transform.Rotation.z)/2) + .5 sprite.Color.z = (math.cos(transform.Rotation.z)/2) + .5 end
--[[ Copyright 2014 Sergej Nisin 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 MyWorldsState = {} local this = {} MyWorldsState.this = this local BUTTON_WIDTH = 0 local BUTTON_HEIGHT = 0 local BUTTON_BORDER = 0 function MyWorldsState.load() BUTTON_WIDTH = 130*pixelscale BUTTON_HEIGHT = 130*pixelscale BUTTON_BORDER = 10*pixelscale this.buttonimg = RessourceManager.images.buttons.worldbutton this.levels = SaveManager.save.myworlds this.selectedworld = 1 end function MyWorldsState.enter() SoundManager.playMusic("menu") local numinrow, offs = this.getWorldVars() local rows = math.floor(#this.levels/numinrow) local contentheight = rows*(offs+BUTTON_HEIGHT)+offs this.scroll = ScrollManager.new({ offTop = game.offY, clickcallback = this.mouseclicked, contentHeight = contentheight }) end function MyWorldsState.update(dt) this.scroll:update(dt) end function MyWorldsState.draw() local numinrow, offs = this.getWorldVars() for i, v in ipairs(this.levels) do this.drawWorldButton(i, v) --if i<=math.floor(#levels/15) then --this.drawWorldButton(i, (i-1)%numinrow*(love.graphics.getWidth()/numinrow)+offs, math.floor((i-1)/numinrow)*(BUTTON_HEIGHT+offs)+offs-this.scroll.scrollY) --end end this.drawWorldButton(#this.levels + 1, {}, true) love.graphics.setColor(255,255,255,255) local barimg = RessourceManager.images.bar love.graphics.draw(barimg, 0, 0, 0, love.graphics.getWidth()/barimg:getWidth(), (50*pixelscale)/barimg:getHeight()) ButtonManager.drawBackButton() this.scroll:drawScrollBar() end function MyWorldsState.wheelmoved(x, y) this.scroll:wheelmoved(x, y) end function MyWorldsState.mousepressed(x, y, button, istouch) this.scroll:mousepressed(x, y, button, istouch) end function this.mouseclicked(x, y, button) if y > game.offY then local hit = false for i, v in ipairs(this.levels) do local numinrow, offs = this.getWorldVars() if ButtonManager.check((i-1)%numinrow*(love.graphics.getWidth()/numinrow)+offs, math.floor((i-1)/numinrow)*(BUTTON_HEIGHT+offs)+offs-this.scroll.scrollY, BUTTON_WIDTH, BUTTON_HEIGHT) then print("[myworlds] world "..i) hit = true this.selectedworld = i StateManager.addState("selection", { {ret="edit",t="Edit"}, {ret="play",t="Play"}, {ret="rename",t="Rename"}, {ret="delete",t="Delete"} }) return end end if not hit then local i = #this.levels + 1 local numinrow, offs = this.getWorldVars() if ButtonManager.check((i-1)%numinrow*(love.graphics.getWidth()/numinrow)+offs, math.floor((i-1)/numinrow)*(BUTTON_HEIGHT+offs)+offs-this.scroll.scrollY, BUTTON_WIDTH, BUTTON_HEIGHT) then print("[myworlds] new world") this.levels[i] = { name = "New World "..i, levels = {} } SaveManager.saveGame() StateManager.setState("selectlevel", "myworld", i) end end else if ButtonManager.checkBackButton(mx, my) then StateManager.setState("menu") end end end function MyWorldsState.keypressed(k) if k == "escape" then StateManager.setState("menu") end end function MyWorldsState.mousereleased(x, y, button, istouch) this.scroll:mousereleased(x, y, button, istouch) end function MyWorldsState.resize(width, height) local numinrow, offs = this.getWorldVars() local rows = math.floor(#this.levels/numinrow) local contentheight = rows*(offs+BUTTON_HEIGHT)+offs this.scroll:setContentHeight(contentheight) end function MyWorldsState.returned(selection) if selection then if selection == "edit" then StateManager.setState("selectlevel", "myworld", this.selectedworld) elseif selection == "play" then StateManager.setState("selectlevel", "playmyworld", this.selectedworld) elseif selection == "rename" then elseif selection == "delete" then StateManager.addState("selection", { {t="Are you sure you want to delete\n\""..this.levels[this.selectedworld].name.."\"?"}, {ret="yesdelete",t="Yes"}, {ret="nodelete",t="No"} }) elseif selection == "yesdelete" then table.remove(this.levels, this.selectedworld) SaveManager.saveGame() elseif selection == "nodelete" then end end end function this.drawWorldButton(worldnum, world, addworld) local numinrow, offs = this.getWorldVars() local x = (worldnum-1)%numinrow*(love.graphics.getWidth()/numinrow)+offs local y = math.floor((worldnum-1)/numinrow)*(BUTTON_HEIGHT+offs)+offs-this.scroll.scrollY local drawimg = this.buttonimg love.graphics.setColor(255,255,255,255) love.graphics.draw(drawimg, x, y, 0, BUTTON_WIDTH/drawimg:getWidth(), BUTTON_HEIGHT/drawimg:getHeight()) if not addworld then love.graphics.setColor(0,160,160,255) love.graphics.printf(worldnum..". "..world.name, x+BUTTON_BORDER, y+10, BUTTON_WIDTH-BUTTON_BORDER*2, "center") love.graphics.setColor(0,0,0,255) local numlevels = #this.levels[worldnum].levels love.graphics.printf(numlevels.." levels", x, y+BUTTON_HEIGHT-10-font:getHeight(), BUTTON_WIDTH, "center") else love.graphics.setColor(0,160,160,255) love.graphics.printf("New World", x+BUTTON_BORDER, y+10, BUTTON_WIDTH-BUTTON_BORDER*2, "center") end end function this.getWorldVars() local numinrow = math.max(math.floor(love.graphics.getWidth()/(BUTTON_WIDTH*1.2)),1) --if love.graphics.getWidth() < BUTTON_WIDTH*2 then -- numinrow = 1 --end local offs = (love.graphics.getWidth()/numinrow-BUTTON_WIDTH)/2 return numinrow, offs end StateManager.registerState("myworlds", MyWorldsState)
module(..., package.seeall) local util = require "tundra.util" local native = require "tundra.native" local function mk_defvariant(name) return { Name = name; Options = {} } end local default_variants = { mk_defvariant "debug", mk_defvariant "production", mk_defvariant "release" } local default_subvariants = { "default" } local _config_class = {} -- Table constructor to make tundra.lua syntax a bit nicer in the Configs array function _G.Config(args) local name = args.Name if not name then error("no `Name' specified for configuration") end if not name:match("^[%w_]+-[%w_]+$") then errorf("configuration name %s doesn't follow <platform>-<toolset> pattern", name) end if args.SubConfigs then if not args.DefaultSubConfig then errorf("configuration %s has `SubConfigs' but no `DefaultSubConfig'", name) end end return setmetatable(args, _config_class) end local function analyze_targets(configs, variants, subvariants) local build_tuples = {} local build_configs = {} local build_variants = {} local build_subvariants = {} for _, cfg in pairs(configs) do if not cfg.Virtual then -- skip virtual configs if not cfg.SupportedHosts then if cfg.DefaultOnHost then if type(cfg.DefaultOnHost) == "table" then cfg.SupportedHosts = cfg.DefaultOnHost else cfg.SupportedHosts = { cfg.DefaultOnHost } end else printf("1.0-compat: config %s doesn't specify SupportedHosts -- will never be built", cfg.Name); cfg.SupportedHosts = { } end end local lut = util.make_lookup_table(cfg.SupportedHosts) if lut[native.host_platform] then build_configs[#build_configs + 1] = cfg end end end for _, var in pairs(variants) do build_variants[#build_variants + 1] = var end for var, _ in pairs(subvariants) do build_subvariants[#build_subvariants + 1] = var end for _, config in ipairs(build_configs) do if config.Virtual then croak("can't build configuration %s directly; it is a support configuration only", config.Name) end for _, variant in ipairs(build_variants) do for _, subvariant in ipairs(build_subvariants) do build_tuples[#build_tuples + 1] = { Config = config, Variant = variant, SubVariant = subvariant } end end end if #build_tuples == 0 then errorf("no build tuples available\n") end return build_tuples end -- Custom pcall error handler to scan for syntax errors (thrown as tables) and -- report them without a backtrace, trying to get the filename and line number -- right so the user can fix their build file. function syntax_error_catcher(err_obj) if type(err_obj) == "table" and err_obj.Class and err_obj.Message then local i = 1 -- Walk down the stack until we find a function that isn't sourced from -- a file. These have 'source' names that don't start with an @ sign. -- Because we read all files into memory before executing them, this -- will give us the source filename of the user script. while true do local info = debug.getinfo(i, 'Sl') --print(util.tostring(info)) if not info then break end if info.what == "C" or (info.source:sub(1, 1) == "@" and info.source ~= "@units.lua") then i = i + 1 else local fn = info.source if info.source:sub(1, 1) == "@" then fn = info.source:sub(2) end if info.currentline == -1 then return string.format("%s: %s", err_obj.Class, err_obj.Message) else return string.format("%s(%d): %s: %s", fn, info.currentline, err_obj.Class, err_obj.Message) end end end return string.format("%s: %s", err_obj.Class, err_obj.Message) else return debug.traceback(err_obj, 2) end end -- A place to store the result of the user's build script calling Build() local build_result = nil -- The Build function is the main entry point for "tundra.lua" when invoked. function _G.Build(args) if type(args.Configs) ~= "table" or #args.Configs == 0 then croak("Need at least one config; got %s", util.tostring(args.Configs or "none at all")) end local configs, variants, subvariants = {}, {}, {} -- Legacy support: run "Config" constructor automatically on naked tables -- passed in Configs array. for idx = 1, #args.Configs do local cfg = args.Configs[idx] if getmetatable(cfg) ~= _config_class then cfg = Config(cfg) args.Configs[idx] = cfg end configs[cfg.Name] = cfg end for _, dir in util.nil_ipairs(args.ScriptDirs) do -- Make sure dir is sane and ends with a slash dir = dir:gsub("[/\\]", SEP):gsub("[/\\]$", "") local expr = dir .. SEP .. "?.lua" -- Add user toolset dir first so they can override builtin scripts. package.path = expr .. ";" .. package.path end if args.Variants then for i, x in ipairs(args.Variants) do if type(x) == "string" then args.Variants[i] = mk_defvariant(x) else assert(x.Name) if not x.Options then x.Options = {} end end end end local variant_array = args.Variants or default_variants for _, variant in ipairs(variant_array) do variants[variant.Name] = variant end local subvariant_array = args.SubVariants or default_subvariants for _, subvariant in ipairs(subvariant_array) do subvariants[subvariant] = true end local default_variant = variant_array[1] if args.DefaultVariant then for _, x in ipairs(variant_array) do if x.Name == args.DefaultVariant then default_variant = x end end end local default_subvariant = args.DefaultSubVariant or subvariant_array[1] local build_tuples = analyze_targets(configs, variants, subvariants) local passes = args.Passes or { Default = { Name = "Default", BuildOrder = 1 } } printf("%d valid build tuples", #build_tuples) -- Validate pass data for id, data in pairs(passes) do if not data.Name then croak("Pass %s has no Name attribute", id) elseif not data.BuildOrder then croak("Pass %s has no BuildOrder attribute", id) end end -- Assume syntax for C and DotNet is always needed -- for now. Could possible make an option for which generator sets to load -- in the future. require "tundra.syntax.native" require "tundra.syntax.dotnet" build_result = { BuildTuples = build_tuples, BuildData = args, Passes = passes, Configs = configs, DefaultVariant = default_variant, DefaultSubVariant = default_subvariant, ContentDigestExtensions = args.ContentDigestExtensions, Options = args.Options, } end function run(build_script_fn) local f, err = io.open(build_script_fn, 'r') if not f then croak("%s", err) end local text = f:read("*all") f:close() local script_globals, script_globals_mt = {}, {} script_globals_mt.__index = _G setmetatable(script_globals, script_globals_mt) local chunk, error_msg = loadstring(text, build_script_fn) if not chunk then croak("%s", error_msg) end setfenv(chunk, script_globals) local success, result = xpcall(chunk, syntax_error_catcher) if not success then print("Build script execution failed") croak("%s", result or "") end local result = build_result build_result = nil return result end
function main(splash, args) assert(splash:autoload("https://code.jquery.com/jquery-2.1.3.min.js")) assert(splash:go(splash.args.url)) local version = splash:evaljs("$.fn.jquery") return 'JQuery version: ' .. version end
-- config model return { install_dir = home()..'/cwm/', start_plugs = 'auto' }
-- Implements a Sparse Tensor in CSC format local SparseTensor = torch.class('torch.SparseTensor') function SparseTensor:__init(data, offsets, shape) self.data = data or torch.Tensor() self.offsets = offsets self.shape = shape self.isSparse = true end function SparseTensor:clone() return torch.SparseTensor(data:clone(), offsets:clone()) end function SparseTensor:nDimension() return 2 end function SparseTensor:dim() return self:nDimension() end function SparseTensor:numNonzero() return self.data:size(2) end function SparseTensor:numElement() return self.shape[1]*self.shape[2] end function SparseTensor:size() return self.shape end function SparseTensor:copy(other) return self.data[{2,{}}]:copy(other.data[{2,{}}]) end function SparseTensor:fill(value) self.data[{2,{}}]:fill(value) end function SparseTensor:zero() self.data[{2,{}}]:fill(0) end function SparseTensor:narrow(dim, index, size) assert(dim == 1, 'only implemented for first dimension') assert(index < self.offsets:size(), 'index out of bounds') local startIdx = self.offsets[index] local endIdx = index+size-1 == self.offsets:size() and self.data:size(1) endIdx = endIdx or self.offsets[index+size-1] return torch.SparseTensor(self.data:narrow(2,startIdx,endIdx-startIdx+1), self.offsets:narrow(1,index,size)) end function SparseTensor:select(dim, index) assert(dim == 1, 'only implemented for first dimension') assert(index < self.offsets:size(), 'index out of bounds') local startIdx = 1+self.offsets[index] local endIdx = index == self.offsets:size() and self.data:size(1) or self.offsets[index] return torch.SparseTensor(self.data[{{},{startIdx,endIdx}}], torch.Tensor(endIdx-startIdx+1)) end function SparseTensor:apply(fn) self.data[{2,{}}]:apply(fn) end
--A lot of Thanks to iUltimateLP and his mod SimpleTeleporters for inspiration and for the use of His Code and graphics require("config") DIVIDER = 60 data:extend({ { type = "accumulator", name = "Teleporter_Beacon", icon = "__PersonalTeleporter__/graphics/icon.png", icon_size = 32, flags = {"placeable-neutral", "player-creation"}, minable = {hardness = 0.2, mining_time = 0.5, result = "Teleporter_Beacon"}, max_health = 150, corpse = "medium-remnants", collision_box = {{-2, -2}, {2,2}}, collision_mask = {"water-tile", "item-layer", "object-layer"}, selection_box = {{-2, -2}, {2, 2}}, render_layer = decorative, energy_source = { type = "electric", buffer_capacity = TIER_01_BUFFER_CAPACITY.."MJ", usage_priority = "secondary-input", input_flow_limit = TIER_01_FLOW_LIMIT.."MW", output_flow_limit = "0W" }, picture = { filename = "__PersonalTeleporter__/graphics/tiers/orange/spritesheet.png", priority = "extra-high", width = 128, height = 128, line_length = 16, frame_count = 16, shift = {0, 0} }, charge_animation = { filename = "__PersonalTeleporter__/graphics/tiers/orange/spritesheet.png", width = 128, height = 128, line_length = 16, frame_count = 16, shift = {0, 0}, animation_speed = 0.5 }, charge_cooldown = 30, charge_light = {intensity = 0.3, size = 7}, discharge_animation = { filename = "__PersonalTeleporter__/graphics/tiers/orange/spritesheet.png", width = 128, height = 128, line_length = 16, frame_count = 16, shift = {0, 0}, animation_speed = 0.5 }, discharge_cooldown = 60, discharge_light = {intensity = 0.7, size = 7}, }, { type = "train-stop", name = "TP_marker", icon = "__PersonalTeleporter__/graphics/icon.png", flags = {"placeable-off-grid", "placeable-neutral", "player-creation", "filter-directions"}, order = "y", selectable_in_game = false, minable = {mining_time = 1, result = "train-stop"}, max_health = 1, render_layer = "tile", final_render_layer = "tile", collision_box = {{0,0}, {0,0}}, selection_box = {{0,0}, {0,0}}, drawing_box = {{0,0}, {0,0}}, tile_width = 1, tile_height = 1, icon_size = 32, animation_ticks_per_frame = 0, vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0 }, working_sound = { sound = { filename = "__base__/sound/train-stop.ogg", volume = 0 } }, circuit_wire_connection_points = {}, circuit_connector_sprites = circuit_connector_definitions["train-station"].sprites, } })
return require('packer').startup(function(use) -- Packer can manage itself use 'wbthomason/packer.nvim' -------------------------- plugins ------------------------------------------- -- nvim-tree use { 'kyazdani42/nvim-tree.lua', requires = 'kyazdani42/nvim-web-devicons' } -- bufferline use { 'akinsho/bufferline.nvim', requires = 'kyazdani42/nvim-web-devicons' } -- treesitter use { 'nvim-treesitter/nvim-treesitter', run = ':TSUpdate' } -- Comment use 'numToStr/Comment.nvim' -- nvim-autopairs use 'windwp/nvim-autopairs' -------------------------- lsp ------------------------------------------- -- lspconfig use {'neovim/nvim-lspconfig', 'williamboman/nvim-lsp-installer'} -- nvim-cmp use 'hrsh7th/cmp-nvim-lsp' -- { name = nvim_lsp } use 'hrsh7th/cmp-buffer' -- { name = 'buffer' }, use 'hrsh7th/cmp-path' -- { name = 'path' } use 'hrsh7th/cmp-cmdline' -- { name = 'cmdline' } use 'hrsh7th/nvim-cmp' -- vsnip use 'hrsh7th/cmp-vsnip' -- { name = 'vsnip' } use 'hrsh7th/vim-vsnip' use 'rafamadriz/friendly-snippets' -- lspkind use 'onsails/lspkind-nvim' -- use 'github/copilot.vim' use 'simrat39/rust-tools.nvim' --------------------------- colorscheme ------------------------------------ -- gruvbox use { "ellisonleao/gruvbox.nvim", requires = {"rktjmp/lush.nvim"} } -- zephyr use 'glepnir/zephyr-nvim' -- nord use 'shaunsingh/nord.nvim' -- onedark use 'ful1e5/onedark.nvim' ------------------------------------ -- -- which-key -- use 'folke/which-key.nvim' -- telescope use 'nvim-lua/popup.nvim' use 'nvim-lua/plenary.nvim' use { 'nvim-telescope/telescope.nvim', requires = {{'nvim-lua/plenary.nvim'}} } -- use { -- "folke/trouble.nvim", -- requires = "kyazdani42/nvim-web-devicons", -- config = function() -- require("trouble").setup { -- -- your configuration comes here -- -- or leave it empty to use the default settings -- -- refer to the configuration section below -- } -- end -- } -- rust-tools -- use 'simrat39/rust-tools.nvim' -- nvim-cmp -- use 'hrsh7th/cmp-nvim-lsp' -- use 'hrsh7th/cmp-buffer' -- use 'hrsh7th/cmp-path' -- use 'hrsh7th/cmp-cmdline' -- use 'hrsh7th/nvim-cmp' -- use 'hrsh7th/cmp-vsnip' -- vsnip -- use 'hrsh7th/vim-vsnip' -- use "rafamadriz/friendly-snippets" -- use 'nvim-autopairs' -- use "windwp/nvim-autopairs" -- surround -- use "blackCauldron7/surround.nvim" -- nvim-coloizer -- use 'norcalli/nvim-colorizer.lua' end)
local M = {} M.config = function() -- CMP -- ========================================= lvim.builtin.cmp.sources = { { name = "nvim_lsp", max_item_count = 4 }, { name = "cmp_tabnine", max_item_count = 4 }, { name = "buffer", max_item_count = 3 }, { name = "path", max_item_count = 3 }, { name = "luasnip", max_item_count = 3 }, { name = "nvim_lua" }, { name = "treesitter" }, { name = "crates" }, } lvim.builtin.cmp.documentation.border = { "╭", "─", "╮", "│", "╯", "─", "╰", "│" } -- Dashboard -- ========================================= lvim.builtin.dashboard.active = true lvim.builtin.dashboard.custom_section["m"] = { description = { " Marks " }, command = "Telescope marks", } -- NvimTree -- ========================================= -- lvim.builtin.nvimtree.auto_open = 0 -- lvim.builtin.nvimtree.hide_dotfiles = 0 -- Treesitter -- ========================================= lvim.builtin.treesitter.context_commentstring.enable = true lvim.builtin.treesitter.ensure_installed = { "bash", "c", "javascript", "json", "lua", "python", "typescript", "css", "rust", "java", "yaml", "ruby" } lvim.builtin.treesitter.ignore_install = { "haskell" } -- lvim.builtin.treesitter.incremental_selection = { -- enable = true, -- keymaps = { -- init_selection = "<C-n>", -- node_incremental = "<C-n>", -- scope_incremental = "<C-s>", -- node_decremental = "<C-r>", -- }, -- } -- lvim.builtin.treesitter.indent = { enable = true, disable = { "yaml", "python" } } -- treesitter is buggy :( lvim.builtin.treesitter.matchup.enable = true -- lvim.treesitter.textsubjects.enable = true -- lvim.treesitter.playground.enable = true -- lvim.builtin.treesitter.query_linter = { -- enable = true, -- use_virtual_text = true, -- lint_events = { "BufWrite", "CursorHold" }, -- } -- lvim.builtin.treesitter.on_config_done = function() -- require("nvim-treesitter.parsers").get_parser_configs().solidity = { -- install_info = { -- url = "https://github.com/JoranHonig/tree-sitter-solidity", -- files = { "src/parser.c" }, -- requires_generate_from_grammar = true, -- }, -- filetype = "solidity", -- } -- end -- Telescope -- ========================================= lvim.builtin.telescope.defaults.path_display = { shorten = 10 } lvim.builtin.telescope.defaults.layout_strategy = "horizontal" lvim.builtin.telescope.defaults.file_ignore_patterns = { "vendor/*" } -- Terminal -- ========================================= lvim.builtin.terminal.active = true -- lvim.builtin.terminal.execs = { -- { "lazygit", "gg", "LazyGit" }, -- } -- WhichKey -- ========================================= lvim.builtin.lualine.sections.lualine_a = { "mode" } end return M
local HttpService = game:GetService("HttpService") local Promise = require(script.Parent.Services.Promise) local function fetch() return Promise.new(function(resolve, reject) local status, response = pcall(HttpService.GetAsync, HttpService, "https://api.github.com/repos/va1kio/commander/tags") if status then resolve(HttpService:JSONDecode(response)) else reject(response) end end) end return function() local status, response = fetch():await() if status then for _,v in ipairs(response) do if tostring(string.match(v.name, "%d+%.%d+%.%d+")) ~= v.name then continue else return v.name end end else return false, HttpService.HttpEnabled end end
require("lualib_bundle"); __TS__SourceMapTraceBack(debug.getinfo(1).short_src, {["4"] = 1,["5"] = 1,["6"] = 4,["7"] = 4,["8"] = 6,["9"] = 6,["10"] = 6,["11"] = 6,["12"] = 6,["14"] = 6,["15"] = 7,["16"] = 8,["17"] = 10,["18"] = 11,["19"] = 13,["20"] = 6,["21"] = 15,["22"] = 15,["23"] = 17,["24"] = 18,["25"] = 17,["26"] = 21,["27"] = 22,["28"] = 21,["29"] = 25,["30"] = 26,["31"] = 25,["32"] = 29,["33"] = 30,["34"] = 29,["35"] = 33,["36"] = 34,["37"] = 33,["38"] = 6,["39"] = 6}); local ____exports = {} local ____Event = require("Lilac.Events.Event") local Event = ____Event.default local ____SceneNode = require("Lilac.GUI.SceneNode") local BaseSceneNode = ____SceneNode.BaseSceneNode ____exports.default = (function() ____exports.default = __TS__Class() local Runtime = ____exports.default Runtime.name = "Runtime" __TS__ClassExtends(Runtime, BaseSceneNode) function Runtime.prototype.____constructor(self, ...) BaseSceneNode.prototype.____constructor(self, ...) self.updating = __TS__New(Event) self.drawing = __TS__New(Event) self.mousePressed = __TS__New(Event) self.mouseReleased = __TS__New(Event) self.quitting = __TS__New(Event) end function Runtime.prototype.onLoad(self, gameContext) end function Runtime.prototype.onUpdate(self, args, gameContext) self.updating:invoke(args, gameContext) end function Runtime.prototype.onDraw(self, args, gameContext) self.drawing:invoke(args, gameContext) end function Runtime.prototype.onMousePressed(self, args, gameContext) self.mousePressed:invoke(args, gameContext) end function Runtime.prototype.onMouseReleased(self, args, gameContext) self.mousePressed:invoke(args, gameContext) end function Runtime.prototype.onQuiting(self, args, gameContext) self.quitting:invoke(args, gameContext) end return Runtime end)() return ____exports
local LocalizationService = game:GetService("LocalizationService") local CoreGui = game:GetService('CoreGui') local Players = game:GetService("Players") -- Waiting for the player ensures that the RobloxLocaleId has been set. if Players.LocalPlayer == nil then Players:GetPropertyChangedSignal("LocalPlayer"):Wait() end local coreScriptTableTranslator local function getTranslator() if coreScriptTableTranslator == nil then coreScriptTableTranslator = CoreGui.CoreScriptLocalization:GetTranslator( LocalizationService.RobloxLocaleId) end return coreScriptTableTranslator end local RobloxTranslator = {} function RobloxTranslator:FormatByKey(key, args) return getTranslator():FormatByKey(key, args) end return RobloxTranslator
local playsession = { {"Serennie", {992123}}, {"REDgalko", {628746}}, {"xaero54", {1007332}}, {"Zory", {25182}}, {"Terarink", {1006256}}, {"sasha21168", {213092}}, {"cipps", {214650}}, {"Dk-077", {720178}}, {"15944831778", {562805}}, {"JailsonBR", {922535}}, {"vad7ik", {479031}}, {"Nikkichu", {939152}}, {"dorpdorp", {938233}}, {"KIRkomMAX", {677520}}, {"NNigelm", {28731}}, {"Shaathan", {3630}}, {"UTIDI", {817639}}, {"matam666", {664602}}, {"Aldnoah5566", {35246}}, {"Fexx", {383741}}, {"hyunbeen", {131923}}, {"Menander", {31909}}, {"gmhinch1", {17754}}, {"kaimix", {789265}}, {"Nalleknas", {299127}}, {"QuaxzRu", {35327}}, {"Rayeth", {162070}}, {"Kondi20_PL", {24589}}, {"Urx", {70916}}, {"50fffff", {7891}}, {"TheWickedMaster", {7882}}, {"RonnDlear", {115032}}, {"Selcet", {25402}}, {"Allall", {3605}}, {"Pustelnik", {606854}}, {"90182si", {6476}}, {"chrisisthebe", {682}}, {"Lastaustralian", {626727}}, {"andrekoul", {703134}}, {"Brender", {62291}}, {"Averest", {512194}}, {"pomabroad", {9070}}, {"WiredMesh", {515012}}, {"TheLiveSupport", {517249}}, {"AndreyE", {638275}}, {"kelvinh92", {44503}}, {"TilenT2", {2182}}, {"guoguomiao", {6608}}, {"jagger23", {414239}}, {"Giatros", {5108}}, {"robertkruijt", {383086}}, {"Thoren41", {32904}}, {"Dimava", {517577}}, {"gabrielbr000", {373262}}, {"Masterpascoe", {9969}}, {"JuanMore", {462282}}, {"16_bytes", {5863}}, {"Cydo_00", {31166}}, {"Anubi5", {250041}}, {"SuddenDeathMP", {57791}}, {"banakeg", {353511}}, {"Roeno1997", {92387}}, {"IamTzu", {178838}}, {"anghelnicky", {4728}}, {"xjohnson", {76183}}, {"a_kid", {264548}}, {"kittyflow", {936}}, {"minipini55", {41947}}, {"abnoeh", {77553}}, {"Dworld", {90672}}, {"Daveyboy80", {149324}}, {"IAmTog", {11576}}, {"tickterd", {153494}}, {"tkdgjs5088", {13573}}, {"manstro011", {146804}}, {"Gerkiz", {120621}}, {"17801076781", {6278}}, {"Maxfreez21", {104349}}, {"igorshp", {103009}}, {"hyperdingo", {14273}}, {"Krengrus", {10411}}, {"Flamongo", {3196}}, {"jackazzm", {60068}}, {"wekkka", {28024}}, {"redlabel", {1625}}, {"H4N", {8640}} } return playsession
object_mobile_dressed_meatlump_hideout_male_06 = object_mobile_shared_dressed_meatlump_hideout_male_06:new { } ObjectTemplates:addTemplate(object_mobile_dressed_meatlump_hideout_male_06, "object/mobile/dressed_meatlump_hideout_male_06.iff")
local Twig = require "orb:orb/metas/twig" local Header_M = {} local Header = Twig:inherit "header" Header_M.header = Header function Header.toMarkdown(header, scroll, skein) local phrase = ("#"):rep(header:select("level")():len()) scroll:add(phrase) for i = 2, #header do header[i]:toMarkdown(scroll, skein) end end return Header_M
local callback = {} function callback.color(state, neighState, substance) local O = substance[1] local G = substance[2] local B = substance[3] local kind = state and state.kind local r,g,b,a local debugMode = love.keyboard.isDown('lctrl') or love.keyboard.isDown("1") or love.keyboard.isDown("2") or love.keyboard.isDown("3") or love.keyboard.isDown("4") if debugMode then --CA if kind=='vessel' then r = 255 g = 255 b = 0 elseif kind=='proliferative' then r = 255 g = 255 b = 255 elseif kind=='quiescent' then r = 170 g = 170 b = 170 elseif kind=='necrotic' then r = 0 g = 0 b = 0 else --RD if love.keyboard.isDown("1") then r = O/O0*255 g = 0 b = 0 elseif love.keyboard.isDown("2") then r = 0 g = G/G0*255 b = 0 elseif love.keyboard.isDown("3") then r = 0 g = 0 b = B/Bv*255 elseif love.keyboard.isDown("4") then r = O/O0*255 g = G/G0*255 b = B/Bv*255 else r = 0 g = 0 b = 0 a = 0 end r = math.min(r, 255) g = math.min(g, 255) b = math.min(b, 255) end else --non-debugMode local kind2 = neighState[1] and neighState[1].kind if kind=='proliferative' or kind=='quiescent' or kind=='necrotic' or (kind=='vessel' and (kind2=='proliferative' or kind2=='quiescent' or kind2=='necrotic')) then r = 255 g = 0 b = 0 a = 127 else r = 0 g = 0 b = 0 a = 0 end end return r,g,b,a end function callback.encode(state, neighState, substance) local kind = state and state.kind local kind2 = neighState[1] and neighState[1].kind if kind=='proliferative' or kind=='quiescent' or kind=='necrotic' or (kind=='vessel' and (kind2=='proliferative' or kind2=='quiescent' or kind2=='necrotic')) then return '1' else return '0' end end return callback
local Config = require('vgit.core.Config') return Config:new({ enabled = true, format = function(blame, git_config) local config_author = git_config['user.name'] local author = blame.author if config_author == author then author = 'You' end local commit_message = blame.commit_message if not blame.committed then author = 'You' commit_message = 'Uncommitted changes' return string.format(' %s • %s', author, commit_message) end local max_commit_message_length = 255 if #commit_message > max_commit_message_length then commit_message = commit_message:sub(1, max_commit_message_length) .. '...' end return string.format( ' %s, %s • %s', author, blame:age().display, commit_message ) end, })
-- MOAI UI -- Copyright (c) 2012-2012 Klei Entertainment Inc. -- All Rights Reserved. local array = require( "modules/array" ) local mui_component = require( "mui/widgets/mui_component" ) local mui_defs = require( "mui/mui_defs" ) local mui_scroller = class( mui_component ) function mui_scroller:init( def ) mui_component.init( self, MOAIProp2D.new(), def ) self._prop:setBounds( -def.w/2, -def.h/2, 0, def.w/2, def.h/2, 0 ) end function mui_scroller:handleInputEvent( ev ) if ev.eventType == mui_defs.EVENT_MouseWheel then if ev.delta ~= 0 then self:dispatchEvent( { eventType = mui_defs.EVENT_Scroll, delta = ev.delta } ) end return true end return false end return mui_scroller
-- See https://github.com/CelestialCartographers/Loenn/blob/master/src/fast_unpack.lua --[==[ Faster unpack for Lua 5.1. Uses a cache of functions which are each optimized for one specific number of varargs. Improves performance by up to two orders of magnitude in LuaJIT. Author: Vexatos MIT License Copyright (c) 2021 Vexatos Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]==] local fast_unpack = {} local unpack_mt = {} function unpack_mt.__call(u, tbl, i, j) i = i or 1 j = j or #tbl if not (u[i] and u[i][j]) then if not u[i] then u[i] = {} end local values = {} for ind = i, j do table.insert(values, string.format("t[%d]", ind)) end u[i][j] = assert(load(string.format("return function(t) return %s end", table.concat(values, ","))))() end return u[i][j](tbl) end setmetatable(fast_unpack, unpack_mt) unpack_orig = unpack unpack = fast_unpack
-- Copyright 2021 SMS -- License(Apache-2.0) include "deps/premake/solution_items.lua" workspace "math" architecture "x86_64" startproject "tests" flags "MultiProcessorCompile" configurations {"Debug", "Release"} solution_items { "README.md", "premake5.lua"} filter "configurations:Debug" defines "DEBUG" runtime "Debug" symbols "on" filter "configurations:Release" defines "NDEBUG" runtime "Release" optimize "on" deps = {} deps["googletest"] = "%{wks.location}/deps/googletest/googletest" deps_inc = {} deps_inc["googletest"] = "%{deps.googletest}/include" output_dir = "%{cfg.system}-%{cfg.architecture}-%{cfg.buildcfg}" include "include/Math" include "tests"
---------------------------------------- -- -- -- USEFUL ALIASES -- -- -- ---------------------------------------- local cmd = vim.cmd -- to execute Vim commands e.g. cmd('pwd') local fn = vim.fn -- to call Vim functions e.g. fn.bufnr() local g = vim.g -- a table to access global variables local opt = vim.opt -- to set options ---------------------------------------- -- -- -- PACKAGE MANAGEMENT -- -- -- ---------------------------------------- require "paq" { -- Let Paq manage itself "savq/paq-nvim"; 'haishanh/night-owl.vim'; "neovim/nvim-lspconfig"; "hrsh7th/nvim-compe"; "tpope/vim-fugitive"; 'tpope/vim-surround'; 'nvim-lua/plenary.nvim'; 'jose-elias-alvarez/null-ls.nvim'; 'jose-elias-alvarez/nvim-lsp-ts-utils'; 'kosayoda/nvim-lightbulb'; 'lewis6991/gitsigns.nvim'; 'idanarye/vim-merginal'; {'neovim/nvim-lspconfig'}; {'junegunn/fzf', run = fn['fzf#install']}; {'junegunn/fzf.vim'}; {'ojroques/nvim-lspfuzzy'}; "justinmk/vim-sneak"; { "neoclide/coc.nvim", branch = 'release' }; 'tribela/vim-transparent'; 'christoomey/vim-tmux-navigator'; 'terrortylor/nvim-comment'; 'preservim/nerdtree'; 'ryanoasis/vim-devicons'; -- Always load this as the last one } require('nvim_comment').setup() ---------------------------------------- -- -- -- EDITOR GENERAL CFG -- -- -- ---------------------------------------- cmd 'colorscheme night-owl' opt.expandtab = true -- Use spaces instead of tabs opt.hidden = true -- Enable background buffers opt.ignorecase = true -- Ignore case opt.joinspaces = false -- No double spaces with join opt.list = true -- Show some invisible characters opt.number = true -- Show line numbers opt.relativenumber = true -- Relative line numbers opt.scrolloff = 4 -- Lines of context opt.shiftround = true -- Round indent opt.shiftwidth = 2 -- Size of an indent opt.sidescrolloff = 8 -- Columns of context opt.smartcase = true -- Do not ignore case with capitals opt.smartindent = true -- Insert indents automatically opt.splitbelow = true -- Put new windows below current opt.splitright = true -- Put new windows right of current opt.tabstop = 2 -- Number of spaces tabs count for opt.termguicolors = true -- True color support opt.wildmode = {'list', 'longest'} -- Command-line completion mode opt.wrap = false -- Disable line wrap -- highlight yanked text disabled in visual mode cmd 'au TextYankPost * lua vim.highlight.on_yank {on_visual = false}' -- show a lightbulb if a code action is available at the current cursor position cmd [[autocmd CursorHold,CursorHoldI * lua require'nvim-lightbulb'.update_lightbulb()]] g['sneak#label'] = 1 cmd 'let mapleader = " "' ---------------------------------------- -- -- -- MAPPINGS -- -- -- ---------------------------------------- -- Configures mappings local function map(mode, lhs, rhs, opts) local options = {noremap = true} if opts then options = vim.tbl_extend('force', options, opts) end vim.api.nvim_set_keymap(mode, lhs, rhs, options) end -- The function is called `t` for `termcodes`. -- You don't have to call it that, but I find the terseness convenient local function t(str) -- Adjust boolean arguments as needed return vim.api.nvim_replace_termcodes(str, true, true, true) end map('', '<leader>c', '"+y') -- Copy to clipboard in normal, visual, select and operator modes map('i', '<C-u>', '<C-g>u<C-u>') -- Make <C-u> undo-friendly map('i', '<C-w>', '<C-g>u<C-w>') -- Make <C-w> undo-friendly -- <Tab> to navigate the completion menu map('i', '<S-Tab>', 'pumvisible() ? "\\<C-p>" : "\\<Tab>"', {expr = true}) map('i', '<Tab>', 'pumvisible() ? "\\<C-n>" : "\\<Tab>"', {expr = true}) map('n', '<C-l>', '<cmd>noh<CR>') -- Clear highlights cmd('nnoremap <expr> <C-p> (len(system(\'git rev-parse\')) ? \':Files\' : \':GFiles --exclude-standard --others --cached\')."\\<cr>"') map('', '<C-o>', '<cmd>Rg<CR>') -- Search in all files ---------------------------------------- -- -- -- LSP -- -- -- ---------------------------------------- local lsp = require 'lspconfig' local lspfuzzy = require 'lspfuzzy' -- enable null-ls integration (optional) require("null-ls").setup {} -- We use the default settings for ccls and pylsp: the option table can stay empty lsp.tsserver.setup { on_attach = function(client, bufnr) -- disable tsserver formatting if you plan on formatting via null-ls client.resolved_capabilities.document_formatting = false local ts_utils = require("nvim-lsp-ts-utils") -- defaults ts_utils.setup { debug = false, disable_commands = false, enable_import_on_completion = false, -- import all import_all_timeout = 5000, -- ms import_all_priorities = { buffers = 4, -- loaded buffer names buffer_content = 3, -- loaded buffer content local_files = 2, -- git files or files with relative path markers same_file = 1, -- add to existing import statement }, import_all_scan_buffers = 100, import_all_select_source = false, -- eslint eslint_enable_code_actions = true, eslint_enable_disable_comments = true, eslint_bin = "eslint", eslint_config_fallback = nil, eslint_enable_diagnostics = false, -- formatting enable_formatting = false, formatter = "prettier", formatter_config_fallback = nil, -- update imports on file move update_imports_on_move = false, require_confirmation_on_move = false, watch_dir = nil, } -- required to fix code action ranges ts_utils.setup_client(client) -- no default maps, so you may want to define some here local opts = {silent = true} vim.api.nvim_buf_set_keymap(bufnr, "n", "gs", ":TSLspOrganize<CR>", opts) vim.api.nvim_buf_set_keymap(bufnr, "n", "gq", ":TSLspFixCurrent<CR>", opts) vim.api.nvim_buf_set_keymap(bufnr, "n", "gr", ":TSLspRenameFile<CR>", opts) vim.api.nvim_buf_set_keymap(bufnr, "n", "gi", ":TSLspImportAll<CR>", opts) end } lspfuzzy.setup {} -- Make the LSP client use FZF instead of the quickfix list map('n', '<space>,', '<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>') map('n', '<space>;', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>') map('n', '<space>a', '<cmd>lua vim.lsp.buf.code_action()<CR>') map('n', '<space>d', '<cmd>lua vim.lsp.buf.definition()<CR>') map('n', '<space>f', '<cmd>lua vim.lsp.buf.formatting()<CR>') map('n', '<space>h', '<cmd>lua vim.lsp.buf.hover()<CR>') map('n', '<space>m', '<cmd>lua vim.lsp.buf.rename()<CR>') map('n', '<space>r', '<cmd>lua vim.lsp.buf.references()<CR>') map('n', '<space>s', '<cmd>lua vim.lsp.buf.document_symbol()<CR>') cmd "map f <Plug>Sneak_s" cmd "map F <Plug>Sneak_S" cmd "command! -nargs=0 Prettier :CocCommand prettier.formatFile" map('n', '<silent>gd', t'<Plug>(coc-definition)') map('n', '<silent>grn', t'<Plug>(coc-rename)') -- cmd "nmap <silent> gd <Plug>(coc-definition)" -- cmd "nmap <silent> grn <Plug>(coc-rename)" -- Copy to clipboard map('v', '<leader>y', '"+y', {noremap = true}) map('n', '<leader>Y', '"+yg_', {noremap = true}) map('n', '<leader>y', '"+y', {noremap = true}) map('n', '<leader>yy', '"+yy', {noremap = true}) -- Paste from clipboard map('n', '<leader>p', '"+p', {noremap = true}) map('n', '<leader>P', '"+P', {noremap = true}) map('v', '<leader>p', '"+p', {noremap = true}) map('v', '<leader>P', '"+P', {noremap = true}) -- File tree map('n', '<leader>pt', "<cmd>NERDTreeToggle<CR>") -- Git map('n', '<leader>gs', "<cmd>G<CR>") map('n', '<leader>gp', "<cmd>G push<CR>") map('n', '<leader>gb', "<cmd>Merginal<CR>") -- Reload config map('n', '<leader>hr', '<cmd>source $MYVIMRC<CR>')
local account = require('account') local chat = require('core.chat') local command = require('core.command') local ffi = require('ffi') local io = require('io') local math = require('math') local memory = require('memory') local player = require('player') local scanner = require('core.scanner') local settings = require('settings') local struct_lib = require('struct') local windower = require('core.windower') local win32 = require('win32') local enumerable = require('enumerable') local ffi_new = ffi.new local ffi_gc = ffi.gc local ffi_cast = ffi.cast local ffi_C = ffi.C local add_text = chat.add_text local ptr = struct_lib.ptr local struct = struct_lib.struct local float = struct_lib.float local uint32 = struct_lib.uint32 local bool = struct_lib.bool local HeapAlloc = win32.def({ name = 'HeapAlloc', returns = 'void*', parameters = { 'void*', 'uint32_t', 'size_t' }, failure = false }) local HeapFree = win32.def({ name = 'HeapFree', returns = 'bool', parameters = { 'void*', 'uint32_t', 'void*' }, failure = false }) local HeapCreate = win32.def({ name = 'HeapCreate', returns = 'void*', parameters = { 'uint32_t', 'size_t', 'size_t' }, failure = false }) local HeapDestroy = win32.def({ name = 'HeapDestroy', returns = 'bool', parameters = { 'void*' }, failure = false }) local defaults = { distance = 6, cameraSpeed = 1.0 } local options = settings.load(defaults) local readyToRender = false local logToFile = function(stringToLog, boolPrint) local file = io.open(windower.user_path .. '\\cameralog.txt', "a"); file:write(tostring(stringToLog), "\n"); file:close(file); if boolPrint then print(stringToLog) end end --################################################### --# SET UP Camera Speed Adjustment --################################################### local originalValues = { 0xD8, 0x4C, 0x24, 0x24, -- fmul dword ptr [esp+24] 0x8B, 0x16, -- mov edx,[esi] } local codeCaveValues = { 0xD8, 0x05, 0x00, 0x00, 0x00, 0x00, -- fadd dword ptr [00000000] 0xD8, 0x4C, 0x24, 0x24, -- fmul dword ptr [esp+24] 0x8B, 0x16, -- mov edx,[esi] 0xE9, 0x00, 0x00, 0x00, 0x00 -- jmp to return point } local try = function(d, e) if d == false then error(e.ErrorMsg) end return d end --Create memory location to store Code Cave local codeCaveHeap = try(ffi_gc(HeapCreate(0x40000, 0, 0), function(heap) destroyed = true HeapDestroy(codeCaveHeap) end), {ErrorMsg = "Failed to create memory location for code cave."}) -- Allocate the space for the Code Cave local codeCave = ffi_cast('uint8_t*', try(HeapAlloc(codeCaveHeap, 8, 17), {ErrorMsg = "Failed to allocate memory for code cave."})) -- Populate general structure of code cave for i = 1, #codeCaveValues do codeCave[i-1] = codeCaveValues[i] end -- Create memory location to store Camera Speed local cameraSpeedAdjustmentHeap = try(ffi_gc(HeapCreate(0x40000, 0, 0), function(heap) destroyed = true HeapDestroy(cameraSpeedAdjustmentHeap) end), {ErrorMsg = "Failed to create memory location to save speed adjustment"}) -- Allocate and set Camera speed based on settings local cameraSpeedAdjustment_Ptr = ffi_cast('float*', try(HeapAlloc(cameraSpeedAdjustmentHeap, 8, ffi.sizeof('float')), {ErrorMsg = "Failed to allocate memory for speed adjustment"})) cameraSpeedAdjustment_Ptr[0] = ffi_new('float', options.cameraSpeed) -- Push in pointer to Camera Speed into the Code Cave local camSpeedInCave = ffi_cast('float**',codeCave + 0x02) camSpeedInCave[0] = cameraSpeedAdjustment_Ptr; -- Push cam speed pointer into code cave -- Get the point where we are injecting code to jump to code cave local caveJmpPoint = ffi_cast('uint8_t*', scanner.scan('&D84C24248B168BCED80D')) -- Push in pointer to the return point into the Code Cave local returnJmpOffset = ffi_cast('int32_t*', codeCave + 0x0D) returnJmpOffset[0] = (caveJmpPoint + 0x06) - (codeCave + 0x0C) - 0x05 -- Get point where we are going to push in Pointer for where the Code Cave is local caveJmpOffset = ffi_cast('int32_t*', caveJmpPoint + 0x01) -- Set up the Jump to the Code Cave caveJmpPoint[0] = 0xE9 caveJmpOffset[0] = (codeCave - caveJmpPoint - 0x05) caveJmpPoint[5] = 0x90 --################################################### --# Camera Distance --################################################### local vector_3f = struct({ x = {0x0, float}, z = {0x4, float}, y = {0x8, float}, }) local camera = struct({ position = {0x44, vector_3f}, focal = {0x50, vector_3f} }) memory.pointerToCamera = struct({signature = '83C40485C974118B116A01FF5218C705*'}, { camera = {0x0, ptr(camera)} }) memory.cameraConnect = struct({signature = '80A0B2000000FBC605*????????00'}, { isConnected = {0x0, bool} }) local ptrToCamera = memory.pointerToCamera local cameraConnect = memory.cameraConnect local follow = memory.follow readyToRender = true local coroutine_sleep_frame = coroutine.sleep_frame coroutine.schedule(function() while(true) do if readyToRender and ptrToCamera and ptrToCamera.camera ~= nil and cameraConnect.isConnected and not follow.first_person_view then local camera = ptrToCamera.camera local diff_x = camera.position.x - camera.focal.x local diff_z = camera.position.z - camera.focal.z local diff_y = camera.position.y - camera.focal.y local distance = 1 / math.sqrt(diff_x * diff_x + diff_z * diff_z + diff_y * diff_y) * options.distance camera.position.x = diff_x * distance + camera.focal.x camera.position.z = diff_z * distance + camera.focal.z camera.position.y = diff_y * distance + camera.focal.y end coroutine_sleep_frame() end end) local restorePointers = function() for i = 1, #originalValues do caveJmpPoint[i-1] = originalValues[i] end end account.login:register(function () coroutine.schedule(function() readyToRender = true; end, 5); end) account.logout:register(function() readyToRender = false; end) --################################################### --# Commands --################################################### local setCameraSpeed = function(newSpeed) cameraSpeedAdjustment_Ptr[0] = newSpeed options.cameraSpeed = newSpeed end local setDistance = function(newDistance) local num = tonumber(newDistance) if num ~= nil then options.distance = num setCameraSpeed(num / 6.0) settings.save() add_text("Distance changed to " .. newDistance) end end local startRender = function() readyToRender = true add_text("Starting distance adjustment") end local stopRender = function() readyToRender = true add_text("Stopping distance adjustment") end local displayHelp = function() add_text("</xicamera | /camera | /xicam | /cam>") add_text("Set Distance: <distance|d> <###>") add_text("Start/Stop: <start|stop>") end local camera = command.new('camera') local cam = command.new('cam') local xicamera = command.new('xicamera') local xicam = command.new('xicam') -- define chat functions enumerable.all({camera, cam, xicamera, xicam}, function(cmd) enumerable.all({'distance', 'd'}, function (fn) cmd:register(fn, setDistance, '<newDistance:integer>') end) enumerable.all({'help', 'h'}, function (fn) cmd:register(fn, displayHelp) end) cmd:register('start', startRender) cmd:register('stop', stopRender) end) --TODO replace with unload event gc_global = ffi_new('int*') ffi_gc(gc_global, restorePointers) --[[ Copyright © 2021, Hokuten All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Chiaia nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Chiaia BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ]]
require('src/test') require('src/core') require('src/builtins') require('src/contextlib') require('src/objects') require('src/logging') require('src/string') require('src/system') fixture('app', function(monkeypatch) local calls = list() monkeypatch.setattr('appRun', function() calls:append('run') end) monkeypatch.setattr('appKill', function() calls:append('kill') end) return calls end) fixture('temp_dir', function(monkeypatch, request) local dir_name = '_tmp_tst' if rootDir then dir_name = os.path_join(rootDir(), dir_name) end io.popen('mkdir '..dir_name):close() request.addfinalizer(function() io.popen('rm -R '..dir_name):close() end) return dir_name .. '/' end) describe('contextlib', it('Exception', function() -- TODO: Exception test --local Ex = Exception('Ex') --local x, y = tostring(Ex), tostring(Ex()) --local s = '' --for i, v in pairs(x) do -- if y[i] ~= v then s = s..v end --end --print(x, y) --print(s) --assertEqual(tostring(Ex), tostring(Ex()), -- 'Exceptions return different messages') --local _, e1 = pcall(error, tostring(Ex)) --local _, e2 = pcall(error, tostring(Ex())) --assertRequal(e1, e2, 'Exceptions return different messages') end), it('try', function() local result = try(function() return 1 end) assertEqual(result, 1, 'try did not return function result') result = try(function() error() end, function() end) assertEqual(result, nil, 'Failing try did not return nil') local l = list() result = try( function() l:append(1) error() end, function() l:append(2) end, function() l:append(3) end ) assertEqual(result, nil, 'Failing try did not return nil') assertEqual(l, list{1,2,3}, 'Incorrect execution order for try, except, finally') end), it('except', function() local l = list() local x assertEqual(except()('err'), nil, 'Empty except returned exception') assertEqual(except(function(err) return err end)('err'), 'err', 'Return exception except did not return exception') x = except( '.*', function(err) l:append(err) end )('err') assertEqual(l[-1], 'err', 'Catch all except did not append error') assertEqual(x, nil, 'Caught exception returned error') x = except( 'err', function(err) l:append(err) end )('err') assertEqual(l[-1], 'err', 'Catch err except did not return error') assertEqual(x, nil, 'Caught exception returned error') x = except( {'err'}, function(err) l:append(err) end )('err') assertEqual(l[-1], 'err', 'Catch {err} except did not return error') assertEqual(x, nil, 'Caught exception returned error') x = except( 'arbitrary', function(err) l:append(err) end )('errortastic') assertEqual(l[-1], 'err', 'Catch arbitrary except returned error') assertEqual(x, 'errortastic', 'Uncaught exception did not return error') local Ex = Exception('Ex') local e = Ex('err1') x = except( Ex, function(err) l:append(tostring(err):split('\n')[1]) end )(e) assertEqual(l[-1], '<Ex> err1', 'Did not catch Exception') assertEqual(x, nil, 'Caught Exception returned error') local e = Ex('err2') x = except( 'arbitrary', function(err) l:append(tostring(err):split('\n')[1]) end )(e) assertEqual(l[-1], '<Ex> err1', 'Did not catch Exception') assertEqual(x, e, 'Caught Exception returned error') end), it('try_except', function() local Ex = Exception('Ex') local e = Ex('err1') local exFail = function() error(e) end local l = list() --successful try local result = try( exFail, except() ) assertEqual(result, nil, 'TryExceptPass did not return nil') result = try( exFail, except(Ex) ) assertEqual(result, nil, 'Caught exception did not return nil') result = try( exFail, except('.*', function(e) l:append(e) end) ) assertEqual(result, nil, 'Caught exception did not return nil') assertEqual(l[-1], e, 'Catch function did not execute') result = try( exFail, except(Ex, function(e) l:append('a') end) ) assertEqual(result, nil, 'Caught exception did not return nil') assertEqual(l[-1], 'a', 'Catch function did not execute') --failing try assertRaises(Ex, function() try( exFail, except('sdfsdfsdf') ) end, 'Uncaught exception did not raise') assertRaises(Ex, function() try( exFail, except(Exception('other')) ) end, 'Uncaught exception did not raise') assertRaises(Ex, function() try( exFail, except({Exception('other'), Exception('other2')}) ) end, 'Uncaught exception did not raise') assertRaises(Ex, function() try( exFail, except({'asdsdf', 'sfsdfsdf'}) ) end, 'Uncaught exception did not raise') assertRaises(Ex, function() try( exFail, except({Exception('other'), Exception('other2')}) ) end, 'Uncaught exception did not raise') end), it('try_except_nested', function() local Ex = Exception('Ex') local Ex2 = Exception('Xe2') local e = Ex('err1') local e2 = Ex2('err1') local l = list() result = try( function() error(e) end, except(Ex, function() try( function() error(e2) end, except(function(err) l:append(err) end) ) end) ) assertEqual(result, nil, 'Caught exception did not return nil') assertEqual(l[-1], e2, 'Caught exception returned incorrect error') assertRaises(Ex2, function() try( function() error(e) end, except(Ex, function() try( function() error(e2) end, except(Ex, function(err) l:append('a') end) ) end) ) end, 'Uncaught exception did not raise') assertEqual(l[-1], e2, 'Caught exception returned incorrect error') end), it('ContextManager', function() local l = list() local Q = class('Q', ContextManager) function Q:__enter() l:append(1) return 2 end function Q:__exit(_type, value) ContextManager.__exit(self, _type, value) l:append(3) end with(Q(), function(v) l:append(v) end) assertEqual(l, list{1,2,3}, 'with ContextManager: incorrect execution order') end), it('contextmanager', function() local l = list() local q = contextmanager(function(a) l:append(1) yield(a) l:append(3) end) with(q(2), function(v) l:append(v) end) assertEqual(l, list{1,2,3}, 'with contextmanager: incorrect execution order') end), it('contextmanager error', function() local l = list() local fails = contextmanager(function(b) l:append(1) yield(b) error('Damn') l:append(3) end) assertRaises('Damn', function() with(fails('v'), function(v) l:append(2) end) end, 'Contextmanager did not error') assertEqual(l, list{1, 2}, 'Did not run erroring contextmanager correctly') end), it('nested contextmanager', function() local l = list() local inner = contextmanager(function(b) l:append('inner enter') yield(b) l:append('inner exit') end) local outer = contextmanager(function(a) l:append('outer enter') with(inner(a), function() yield(a * 2) end) l:append('outer exit') end) with(outer(1), function(v) l:append(v * 10) end) assertEqual(l, list{'outer enter', 'inner enter', 20, 'inner exit', 'outer exit'}, 'Did not execute nested contextmanagers in correct order') end), it('nested with', function() local l = list() local outer = contextmanager(function(a) l:append('outer enter') yield(a) l:append('outer exit') end) local inner = contextmanager(function(b) l:append('inner enter') yield(b * 2) l:append('inner exit') end) with(outer(1), function(v) with(inner(v), function(q) l:append(q * 10) end) end) assertEqual(l, list{'outer enter', 'inner enter', 20, 'inner exit', 'outer exit'}, 'Did not execute nested with in correct order') end), it('open', function(temp_dir) -- TODO: Fix for mobile -- local fle -- with(open(temp_dir..'t.txt', 'w'), function(f) fle = f; f:write('hello') end) -- assert(type(fle == 'userdata'), 'with open did not open a file') -- assertRaises( -- 'attempt to use a closed file', -- function() fle:read() end, -- 'with open did not close file after operation' -- ) -- assert(isFile(temp_dir..'t.txt'), 'open did not create file') -- assertEqual(readLines(temp_dir..'t.txt'), list{'hello'}, -- 'with open did not write to file') end), it('suppress', function() assertEqual(with(suppress(), function() error(ValueError) end), nil, 'Empty suppress raised error') assertEqual(with(suppress('.*'), function() error(ValueError) end), nil, 'All suppress returned error') assertEqual(with(suppress(ValueError), function() error(ValueError) end), nil, 'ValueError suppress returned error') assertRaises(ValueError, function() with(suppress(AssertionError), function() error(ValueError) end) end, 'AssertionError suppress did not return error') end), it('run_and_close', function(monkeypatch, app) monkeypatch.setattr('appState', function() return 'ACTIVE' end) with(run_and_close('app'), function() app:append('do') end) assert(requal(app, {'kill', 'run', 'do', 'kill'}), 'Did not run and kill in correct order') app:clear() monkeypatch.setattr('appState', function() return 'NOT RUNNING' end) with(run_and_close('app', false), function() app:append('do') end) assert(requal(app, {'run', 'do'}), 'Did not run and kill in correct order') end), it('run_if_closed', function(monkeypatch, app) monkeypatch.setattr('appState', function() return 'ACTIVE' end) with(run_if_closed('app'), function() app:append('do') end) assert(requal(app, {'do'}), 'Did not run if closed in correct order') app:clear() monkeypatch.setattr('appState', function() return 'NOT RUNNING' end) with(run_if_closed('app'), function() app:append('do') end) assert(requal(app, {'run', 'do', 'kill'}), 'Did not run if closed in correct order') end), it('time_ensured', function() local time_ns = num(exe('date +%s%N')) with(time_ensured(0.01), function() end) -- TODO: Fix time_ensured for mobile -- local diff = round((num(exe('date +%s%N')) - time_ns) / 1000000000, 2) -- assert(diff == 0.01, 'Ensure time did not take correct amount of time') end) ) run_tests()
local super = Class("KeyboardFocusManager", LuaObject, function() static.getCurrentKeyboardFocusManager = function() return LuaObject.getSingleton(static) end end).getSuperclass() KeyboardFocusManager.FORWARD_TRAVERSAL = 0 KeyboardFocusManager.BACKWARD_TRAVERSAL = 1 function KeyboardFocusManager:init() super.init(self) self.focusOwner = nil self.defaultPolicy = DefaultFocusTraversalPolicy() return self end function KeyboardFocusManager:getDefaultFocusTraversalPolicy() return self.defaultPolicy end function KeyboardFocusManager:getFocusOwner() return self.focusOwner end function KeyboardFocusManager:setGlobalFocusOwner(newFocusOwner) local currentFocusOwner = self:getFocusOwner() local temporary, descendant = false, newFocusOwner if (currentFocusOwner) then self.currentFocusOwnerEvent = FocusEvent(currentFocusOwner, FocusEvent.FOCUS_LOST, temporary, descendant) if(currentFocusOwner.processEvent) then currentFocusOwner:processEvent(self.currentFocusOwnerEvent) end end if(newFocusOwner) then self.newFocusOwnerEvent = FocusEvent(descendant, FocusEvent.FOCUS_GAINED, temporary, currentFocusOwner) if(newFocusOwner.processEvent) then newFocusOwner:processEvent(self.newFocusOwnerEvent) end end self.focusOwner = newFocusOwner end function KeyboardFocusManager:setGlobalFocusOwnerSilent(newFocusOwner) self.focusOwner = newFocusOwner end function KeyboardFocusManager:focusPreviousComponent(aComponent) if (aComponent ~= nil) then aComponent:transferFocusBackward() end end function KeyboardFocusManager:focusNextComponent(aComponent) if (aComponent ~= nil) then --aComponent:transferFocus(true) end end function KeyboardFocusManager:upFocusCycle(aComponent) if (aComponent ~= nil) then aComponent:transferFocusUpCycle() end end function KeyboardFocusManager:downFocusCycle(aContainer) if (aContainer ~= nil and aContainer.isFocusCycleRoot()) then aContainer:transferFocusDownCycle() end end function KeyboardFocusManager:processKeyEvent(focusedComponent, e) if (focusedComponent:getFocusTraversalKeysEnabled()) then self:focusNextComponent(focusedComponent) end end function KeyboardFocusManager:clearGlobalFocusOwner() end
return function(self) self.processed_text = {} self.line_with_text.indents_obj.indent_chunk = self.indent_chunk self.line_with_text:init() self.line_with_text.indent = self.next_line_indent self.num_line_feeds = 0 end
function love.conf(t) t.releases = { title = "Going Home", author = "Brandon Blanker Lim-it", email = "flamendless8@gmail.com", homepage = "http:flamendless.github.com/brbl", description = "A Pixelated Survival Horror Game", version = "1.0.2" } t.window.width = 1024 t.window.height = 512 t.window.resizable = false t.window.title = "Going Home" t.externalstorage = true t.version = "11.2" t.window.icon = "assets/icon.png" t.identity = "GoingHome" --console --io.stdout:setvbuf("no") lovedebug = debug debug = false debugMode = false gameplay_record = false cheat = false pro_version = true apple_ver = false end
local nvim = require'nvim' local load_module = require'tools'.helpers.load_module local set_mapping = nvim.mappings.set_mapping local hop = load_module'hop' if not hop then return false end hop.setup{} set_mapping{ mode = 'n', lhs = [[\]], rhs = "<cmd>lua require'hop'.hint_char1()<CR>", args = {noremap = true}, } return true
------------------------------------------------------------------------------- -- -- Date and time widget with calendar popup display for Awesome 3.5 -- Copyright (C) 2011-2016 Tuomas Jormola <tj@solitudo.net> -- -- Licensed under the terms of GNU General Public License Version 2.0. -- -- Description: -- -- This widget displays date and time and when the mouse cursor -- hovers over the widget, a calendar for current month is displayed. -- You can navigate between months by using mouse scroll wheel. -- -- Widget uses calendar2 module by Bzed. -- http://awesome.naquadah.org/wiki/Calendar_widget#Module_for_3.4 -- -- -- Theme: -- -- The widget uses following colors if available in the Awesome theme. -- -- theme.fg_focus - text color of the current date in calendar -- theme.bg_focus - background color of the current date in calendar -- ------------------------------------------------------------------------------- local awful = require('awful') local beautiful = require('beautiful') local calendar2 = require('calendar2') local string = { format = string.format } module('delightful.widgets.datetime') function load() local widget = awful.widget.textclock() local calendar_format = '%s' if beautiful.fg_focus and beautiful.bg_focus then calendar_format = string.format('<span color="%s" background="%s">%%s</span>', beautiful.fg_focus, beautiful.bg_focus) end calendar2.addCalendarToWidget(widget, calendar_format) return { widget } -- no icon end
local random = Random.new() local function fillStoreSupply() local storeSupply = {} for i = 1, 10 do local ranVal = random:NextInteger(1,3) local item = (ranVal == 1 and "Fruit") or (ranVal == 2 and "Vegetable") or "Shoe" table.insert(storeSupply, item) end return storeSupply end local supplyTable = fillStoreSupply() local function factorial(n) assert(n == math.floor(n), "n must be a whole number.") local factorial = 1 --Empty product should be 1 while n > 0 do factorial = factorial * n n = n - 1 end return factorial end print(factorial(12)) local function sum(...) local args = {...} local sum = 0 for _, number in pairs(args) do sum = sum + number end return sum end local num = sum(7, 9, 12, 3, 2, 6, 13) print(num) local elapsedTime = 0 spawn(function() while wait(1) do elapsedTime = elapsedTime + 1 print(elapsedTime) end end) print("Code after loop can still execute!") local function factorial(n) assert(n == math.floor(n), "n must be a whole number.") if n < 1 then return 1 else return n * factorial(n - 1) end end print(factorial(6)) local function checkEquality(table1, table2) print("Variable 1: ".. tostring(table1)) print("Variable 2: ".. tostring(table2)) print("First and second variable same table = ".. tostring(table1 == table2)) end local group = {"Ashitosh", "Hayden", "Sofi"} local groupClone = group checkEquality(group, groupClone) local items = { Egg = {fragile = true;}; Water = {wet = true}; } local function recursiveCopy(targetTable) local tableCopy = {} for index, value in pairs(targetTable) do if type(value) == "table" then value = recursiveCopy(value) end tableCopy[index] = value end return tableCopy end local itemsClone = recursiveCopy(items) checkEquality(items, itemsClone)
local Draw = require("api.Draw") local Gui = require("api.Gui") local IInput = require("api.gui.IInput") local IUiLayer = require("api.gui.IUiLayer") local InputHandler = require("api.gui.InputHandler") local UiTheme = require("api.gui.UiTheme") local QuickMenuList = require("api.gui.QuickMenuList") local QuickMenuPrompt = class.class("QuickMenuPrompt", IUiLayer) QuickMenuPrompt:delegate("input", IInput) local last_page function QuickMenuPrompt:init() local pages = { { title = "Info", items = { { text = "Help", action = "help" }, { text = "Log", action = "message_log" }, { text = "Chara", action = "chara_info" }, nil, { text = "Journal", action = "journal" }, nil } }, { title = "Action", items = { { text = "Wear", action = "wear" }, { text = "Rest", action = "rest" }, { text = "Spell", action = "cast" }, { text = "Skill", action = "skill" }, { text = "Fire", action = "fire" }, { text = "Dig", action = "dig" } } }, { title = "Etc", items = { { text = "Pray", action = "pray" }, { text = "Ammo", action = "ammo" }, { text = "Interact", action = "interact" }, nil, { text = "Bash", action = "bash" }, nil } }, } self.list = QuickMenuList:new(pages) self.list:select_page(1) self.frame = 0 self.input = InputHandler:new() self.input:forward_to(self.list) self.input:bind_keys(self:make_keymap()) if last_page then end end function QuickMenuPrompt:make_keymap() return { escape = function() self.canceled = true end, cancel = function() self.canceled = true end } end function QuickMenuPrompt:relayout(x, y) self.t = UiTheme.load(self) self.list:relayout(50, 345) end function QuickMenuPrompt:on_query() Gui.play_sound("base.cursor1") end function QuickMenuPrompt:draw() self.list:draw() end function QuickMenuPrompt:update(dt) local result = self.list:update(dt) if result then return result.action or "" end if self.canceled then return nil, "canceled" end end return QuickMenuPrompt
local utils = require('utils') local plugins ={ { paq = {'savq/paq-nvim', as = 'paq.nvim', opt = true}, setup = utils.require('plugins.paq').setup }, { paq = {'windwp/nvim-autopairs', as = 'autopairs.nvim'}, setup = utils.require('nvim-autopairs').setup }, { paq = {'norcalli/nvim-colorizer.lua', as = 'colorizer.nvim'}, setup = utils.require('colorizer').setup }, { paq = {'tpope/vim-commentary', as = 'commentary.vim'} }, { paq = {'hrsh7th/nvim-compe', as = 'compe.nvim'}, setup = utils.require('plugins.compe').setup }, { paq = {'mfussenegger/nvim-dap', as = 'dap.nvim'}, setup = utils.require('plugins.dap').setup }, { paq = {'rcarriga/nvim-dap-ui', as = 'dap-ui.nvim'}, setup = utils.require('dapui').setup }, { paq = {'tommcdo/vim-exchange', as = 'exchange.vim'} }, { paq = {'phaazon/hop.nvim'}, setup = utils.require('plugins.hop').setup }, { paq = {'tommcdo/vim-lion', as = 'lion.vim'}, setup = function() vim.g.lion_squeeze_spaces = 1 end }, { paq = {'neovim/nvim-lspconfig', as = 'lspconfig.nvim'}, setup = utils.require('plugins.lspconfig').setup }, { paq = {'nvim-telescope/telescope.nvim'}, setup = utils.require('plugins.telescope').setup }, { paq = {'nvim-telescope/telescope-dap.nvim'}, setup = utils.require('plugins.telescope-dap').setup }, { paq = {'ishan9299/modus-theme-vim', as = 'modus-theme.nvim'}, setup = utils.require('plugins.modus-theme').setup }, { paq = {'kristijanhusak/orgmode.nvim'}, setup = utils.require('orgmode').setup }, { paq = {'nvim-lua/plenary.nvim'} }, { paq = {'nvim-lua/popup.nvim'} }, { paq = {'tpope/vim-repeat', as = 'repeat.vim'} }, { paq = {'dstein64/nvim-scrollview', as = 'scrollview.nvim'} }, { paq = {'tpope/vim-surround', as = 'surround.vim'} }, { paq = {'nvim-treesitter/nvim-treesitter', as = 'tree-sitter.nvim', run = function() vim.cmd('TSUpdate') end} }, { paq = {'tpope/vim-unimpaired', as = 'unimpaired.vim'} }, { paq = {'tpope/vim-vinegar', as = 'vinegar.vim'}, setup = utils.require('plugins.vinegar').setup }, { paq = {'folke/which-key.nvim'}, setup = utils.require('plugins.which-key').setup } } local paqs = {} for i, p in ipairs(plugins) do paqs[i] = p.paq pcall(p.setup) end local function init_paq() vim.cmd [[packadd paq.nvim]] utils.require'paq'(paqs) end return {init_paq = init_paq}
scriptId = 'com.lloydtorres.imgur' scriptTitle = 'Imgur Connector' -- Lua script to enable browsing Imgur using the Myo. -- A lot of the code was taken from the Myo SDK docs. -- Variables fistMade = false -- Flags for holding fist referenceRoll = myo.getRoll() currentRoll = referenceRoll -- Effects function nextPicture() myo.keyboard("right_arrow","press") myo.notifyUserAction() end function prevPicture() myo.keyboard("left_arrow","press") myo.notifyUserAction() end function scrollUp() myo.keyboard("up_arrow","press") end function scrollDown() myo.keyboard("down_arrow","press") end function resizePicture() myo.keyboard("return","press") myo.notifyUserAction() end -- Helpers function conditionallySwapWave(pose) -- Changes waveIn/waveOut to be waveLeft/waveRight instead if myo.getArm() == "left" then if pose == "waveIn" then pose = "waveOut" elseif pose == "waveOut" then pose = "waveIn" end end return pose end -- Callbacks function onPoseEdge(pose, edge) pose = conditionallySwapWave(pose) -- Other gestures if myo.isUnlocked() and edge == "on" then pose = conditionallySwapWave(pose) if pose == "waveOut" then nextPicture() myo.unlock("timed") elseif pose == "waveIn" then prevPicture() myo.unlock("timed") elseif pose == "fingersSpread" then resizePicture() myo.unlock("timed") elseif pose == "fist" then -- Sets up fist movement myo.unlock("hold") referenceRoll = myo.getRoll() fistMade = true end end if pose == "fist" and edge == "off" then fistMade = false myo.unlock("timed") end end function onPeriodic() -- Lock after inactivity currentRoll = myo.getRoll() if fistMade then -- Moves page when fist is held and Myo is rotated subtractive = currentRoll - referenceRoll if subtractive > 0.12 then scrollDown() elseif subtractive < -0.12 then scrollUp() end end end function onForegroundWindowChange(app, title) return string.match(title,"%- Imgur %-") or string.match(title,"%- Imgur") end function activeAppName() return "Imgur" end function onActiveChange(isActive) if not isActive then unlocked = false end end
-- -- from src/crnd.c -- -- void init_rnd(unsigned long) to crnd; :init -- unsigned long irnd(void) to crnd; :irnd -- double rnd(void) to crnd; :rnd -- local M = require 'crnd' local crnd = M.crnd function p(m, n, crnd) for _=1,n do for _=1,m do io.write(("%10.7f"):format(crnd:rnd())) end io.write("\n") end end do local c = crnd(12345) p(8, 20, c) end
local ChainList = require 'init' ChainList.run();
local M = { } function M.locate() local location = vim.fn.getmousepos() if location.winid == 0 then if location.screenrow > vim.o.lines - vim.o.cmdheight then location.cmdline = true else location.statusline = true end location.winid = nil location.winrow = nil location.wincol = nil location.line = nil location.column = nil return location end if location.winrow == 0 then location.tabline = true location.line = nil location.column = nil return location end if location.line == 0 or location.column == 0 then if vim.o.laststatus < 3 and location.winrow == vim.fn.winheight(location.winid) + 1 then location.statusline = true else location.border = true end location.line = nil location.column = nil return location end local wininfo = vim.fn.getwininfo(location.winid)[1] local winconfig = vim.api.nvim_win_get_config(location.winid) location.bufnr = wininfo.bufnr location.winnr = wininfo.winnr if wininfo.loclist == 1 then location.loclist = true end if wininfo.terminal == 1 then location.terminal = true end if wininfo.quickfix == 1 then location.quickfix = true end if winconfig.focusable then location.focusable = true end if winconfig.relative ~= '' then location.floatingwindow = true end if location.wincol <= wininfo.textoff then location.margin = true if vim.api.nvim_win_get_option(location.winid, 'number') then local screenattr = vim.fn.screenattr(location.screenrow, location.screencol) local numberattr = vim.fn.screenattr(location.screenrow, location.screencol + wininfo.textoff - location.wincol) if screenattr == numberattr then location.numbercolumn = true end end if not location.numbercolumn and vim.api.nvim_win_get_option(location.winid, 'foldcolumn') ~= '0' then -- TODO: vim.fn.foldlevel for specific bufnr local foldlevel = location.bufnr == vim.fn.bufnr() and vim.fn.foldlevel(location.line) or 0 if location.wincol <= foldlevel then location.foldcolumn = true -- TODO: Replace vim.opt.fillchars with nvim_win_get_option(location.winid) and nvim_get_option local screenchar = vim.fn.nr2char(vim.fn.screenchar(location.screenrow, location.screencol)) local fillchars = vim.opt.fillchars:get() if screenchar == (fillchars['foldopen'] or '-') then location.foldtoggle = true elseif screenchar == (fillchars['foldclose'] or '+') then location.foldtoggle = true elseif screenchar == (fillchars['foldsep'] or '│') then location.foldseparator = true elseif screenchar == (fillchars['foldsep'] or '|') then location.foldseparator = true end end end if not location.numbercolumn and not location.foldcolumn and vim.api.nvim_win_get_option(location.winid, 'signcolumn') ~= '0' then location.signcolumn = true end return location end -- TODO: vim.fn.foldclosed for specific bufnr if location.bufnr == vim.fn.bufnr() and vim.fn.foldclosed(location.line) ~= -1 then location.closedfold = true return location end local eof = vim.fn.screenpos(location.winid, vim.fn.line('$', location.winid), 1) if location.screenrow > eof.row then location.eof = true return location end local eol = vim.fn.screenpos(location.winid, location.line, 2147483647) if location.screencol >= eol.endcol then location.eol = true if location.screencol == eol.endcol and vim.api.nvim_win_get_option(location.winid, 'list') then -- TODO: Replace vim.opt.listchars with nvim_win_get_option(location.winid) and nvim_get_option local eolchar = vim.opt.listchars:get()['eol'] or '' if eolchar ~= '' then location.eolchar = true end end -- NOTE: vim.fn.screenchar returns blended characters instead of spaces on floating windows if not location.eolchar and not location.floatingwindow then local hastext = vim.fn.screenchar(location.screenrow, location.screencol) ~= 32 or location.screencol > eol.endcol + 1 and vim.fn.screenchar(location.screenrow, location.screencol - 1) ~= 32 if hastext then location.virtualtext = true end end end return location end function M.input(keys) vim.fn.feedkeys(vim.api.nvim_replace_termcodes(keys, true, true, true), 'ni') end return M
local packageName = "Chat Extensions" local logger = GPM.Logger( packageName ) if (CLIENT) then --[[------------------------------------------------------------------------- chat_sound - ConVar ---------------------------------------------------------------------------]] do local chat_sound = CreateClientConVar( "chat_sound", "1", true, false, "Enables chat new message sound.", 0, 1 ):GetBool() cvars.AddChangeCallback("chat_sound", function( name, old, new ) logger:info( "Chat sound is {1}", new == "0" and "disabled" or "enabled" ) chat_sound = new == "1" end, packageName) local chat_AddText = environment.saveFunc( "chat.AddText", chat.AddText ) local chat_PlaySound = chat.PlaySound function chat.AddText( ... ) chat_AddText( ... ) if (chat_sound) then chat_PlaySound() end end end --[[------------------------------------------------------------------------- PrePlayerChat & PostPlayerChat ---------------------------------------------------------------------------]] hook.Add("PostGamemodeLoaded", "PrePlayerChat & PostPlayerChat", function() language.Add( "dead", "Dead" ) language.Add( "team", "Team" ) language.Add( "console", "Console" ) local red = Color( 255, 30, 40 ) local green = Color( 30, 160, 40 ) local TEXT_FILTER_CHAT = TEXT_FILTER_CHAT local TEXT_FILTER_GAME_CONTENT = TEXT_FILTER_GAME_CONTENT local IsValid = IsValid local hook_Run = hook.Run local bit_band = bit.band local util_FilterText = util.FilterText local language_GetPhrase = language.GetPhrase local chat_filter = cvars.Number( "cl_chatfilters", 0 ) cvars.AddChangeCallback("cl_chatfilters", function( name, old, new ) chat_filter = tonumber( new ) end) function GAMEMODE:OnPlayerChat( ply, strText, isTeam, isDead, ... ) local pre = hook_Run( "PrePlayerChat", ply, strText, isTeam, isDead, ... ) if (pre ~= nil) then local post = hook_Run( "PostPlayerChat", ply, strText, isTeam, isDead, ... ) if (post ~= nil) then return post end return pre end if IsValid( ply ) then local data = {} if (isDead) then table.insert( data, red ) table.insert( data, "*" .. language_GetPhrase( "dead" ):upper() .. "* " ) end if (isTeam) then table.insert( data, green ) table.insert( data, "(" .. language_GetPhrase( "team" ):upper() .. ") " ) end table.insert( data, ply ) table.insert( data, color_white ) table.insert( data, ": " .. util.FilterText( strText, (bit.band( chat_filter, 64 ) ~= 0) and TEXT_FILTER_CHAT or TEXT_FILTER_GAME_CONTENT, ply ) ) chat.AddText( unpack( data ) ) else chat.AddText( language_GetPhrase( "console" ), color_white, ": ", strText ) end local post = hook_Run( "PostPlayerChat", ply, strText, isTeam, isDead, ... ) if (post ~= nil) then return post end return true end end) end if (SERVER) then --[[------------------------------------------------------------------------- Chat Commands ---------------------------------------------------------------------------]] do local cmd_starts = CreateConVar("chat_command_symbols", "/ !", FCVAR_ARCHIVE, " - List of chat commands start symbols"):GetString() local start_symbols = cmd_starts:Split( " " ) cvars.AddChangeCallback("chat_command_symbols", function( name, old, new ) start_symbols = new:Split( " " ) logger:info( "Now chat commands starts with {1}", table.concat( start_symbols, " " ) ) end, packageName) local echo_commands = CreateConVar("chat_echo_commands", "0", FCVAR_ARCHIVE, " - Logs every chat command in console.", 0, 1 ):GetBool() cvars.AddChangeCallback("chat_echo_commands", function( name, old, new ) echo_commands = new == "1" end, packageName) local table_insert = table.insert local ipairs = ipairs hook.Add("PlayerSay", "ChatCommands", function( ply, text, ... ) for num, start in ipairs( start_symbols ) do if text:StartWith( start ) then local data = text:Replace( start, "" ):Split( " " ) local args = {} for num, str in ipairs( data ) do if (num == 1) then continue end table_insert( args, str ) end local cmd = data[1] if (echo_commands) then logger:info( "{1}: {2}{3} {4}", ply, start, cmd, table.concat( args, " " ) ) end local pre = hook.Run( "PreChatCommand", ply, cmd, args, ... ) if (pre == nil) then if (pre == true) then return text end if (pre == false) then return "" end local on = hook.Run( "ChatCommand", ply, cmd, args, ... ) if (on == nil) then return end if (on == true) then return text end if (on == false) then return "" end local post = hook.Run( "PostChatCommand", ply, cmd, args, ... ) if (post == nil) then return on end if (post == true) then return text end if (post == false) then return "" end return post end return pre end end end) end end
local http = require "luci.http" local sys = require "luci.sys" module("luci.pccontroller.myip", package.seeall) need_authentication = false function index() local myip = http.getenv('HTTP_X_FORWARDED_FOR') if not myip then myip = sys.getenv().REMOTE_ADDR end http.prepare_content('text/html') http.write('<!DOCTYPE html>') http.write('<head><title>Device IP Address</title>') http.write('<meta http-equiv="X-UA-Compatible" content="IE=edge"></meta>') http.write('<meta content=width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0"></meta>') http.write('</head><body><h1 style="font-size:36px;text-align:center;margin-top:50px">') http.write(tostring(myip)) http.write('</h1></body></html>') end
local home = {} local timer = 0 local color1 = 1 local color2 = 1 local color3 = 1 function home:update (dt) timer = timer + dt if timer > 0.3 then color1 = math.random() color2 = math.random() color3 = math.random() timer = 0 end end function home:keypressed (key) if key == 'escape' then love.event.quit() end end function home:render () Printf('Match 3', Fonts.large, {color1,color2,color3}, 0, 60, VIRTUAL_WIDTH, 'center', true) Printf('by', Fonts.small, {1,1,1}, 0, 120, VIRTUAL_WIDTH, 'center', true) Printf('Iury Ramos Garcia', Fonts.small, {1,1,1}, 0, 140, VIRTUAL_WIDTH, 'center', true) Printf('Click to Start', Fonts.small, { 0.5+color1*0.5, 0.5+color1*0.5, 0.5+color1*0.5 }, 0, VIRTUAL_HEIGHT-70, VIRTUAL_WIDTH, 'center', true) Printf('v1.1 (2021)', Fonts.small, {1,1,1}, 20, VIRTUAL_HEIGHT-28, VIRTUAL_WIDTH, 'left', true) end function home:mousepressed (_, _, button) if button == 1 then Gamestate.switch(States.game) end end return home
require("isolater/common/commonController"); require("hall/onlineSocket/onlineSocketManager"); require("common/nativeEvent"); require("util/TableLib"); require("hall/ranklist/socket/rankSocketProcesser"); require("hall/ranklist/data/rankListDataInterface"); require("hall/community/data/communityDataInterface"); local RankScene = require("hall/ranklist/widget/rankScene"); -- 排行榜列表controler -- 作者:JasonWang RankController = class(CommonController); RankController.s_cmds = { goBack = 1, rankTabItemClick = 3, mineRankBtnClick = 4, DayChangeBtnClick = 5, requestUserInfo = 6; AddConfirmClick = 7; getRankTabList = 8; }; RankController.ctor = function(self, state, viewClass, viewConfig) self.m_state = state; self.m_curTab = nil; self.m_curFlag = RankListConstants.eFlag.Today; RankListDataInterface.getInstance():setObserver(self); CommunityDataInterface.getInstance():setObserver(self); end RankController.resume = function(self) CommonController.resume(self); end RankController.dtor = function(self) RankListDataInterface.getInstance():clearObserver(self); CommunityDataInterface.getInstance():clearObserver(self); end --获取rank的tab RankController.getRankTabList = function(self) local rankTabList = RankListDataInterface.getInstance():getRankTabList(); self:updateView(RankScene.s_cmds.updateTabs, rankTabList); local getBundleData = self:getBundleData(); local rankType = getBundleData or RankListDataInterface.getInstance():getPreferDisplayRankType(); self:onRankTabItemClick(rankType); end --获取tab回调 RankController.onGetRankListTabCallBack = function(self, isSuccess, rankTabList) if isSuccess then self:updateView(RankScene.s_cmds.updateTabs, rankTabList); self:onRankTabItemClick( RankListDataInterface.getInstance():getPreferDisplayRankType() ); end end --获取某个rank的list RankController.getRankList = function(self, mid, rankType, flag) local info, updateFlag = RankListDataInterface.getInstance():getRankListData(rankType, flag, mid); if table.isEmpty(info) then self:updateView(RankScene.s_cmds.PreRankList, updateFlag); else self:updateView(RankScene.s_cmds.LoadRankList, info, rankType); end end --@delegate RankController.onRankListDataCallBack = function(self, isSuccess, rankType,flag, info) LoadingView.getInstance():hidden(); self:updateView(RankScene.s_cmds.LoadRankList, info, rankType); end --获取某个rank某个mid对应的info RankController.getRankInfo = function(self, mid, rankType, flag) local info = RankListDataInterface.getInstance():getUserRankInfo(rankType, flag, mid); if table.isEmpty(info) then self:updateView(RankScene.s_cmds.PreRankInfo); else self:updateView(RankScene.s_cmds.LoadMyRankInfo, info, rankType, flag); end end --@delegate RankController.onUserRankInfoCallBack = function(self, isSuccess, mid, rankType, flag,info) LoadingView.getInstance():hidden(); self:updateView(RankScene.s_cmds.LoadMyRankInfo, info, rankType, flag) end --返回 RankController.onGoBack = function(self) self.m_state:popState(); end --点击提升排名 RankController.onMineRankBtnClick = function(self) UBReport.getInstance():report(UBConfig.kHallRankQuickUp, string.format("curTab_%s", self.m_curTab or "")); --去商城 RechargeDataInterface.getInstance():setToRechargeMode( RechargeDataInterface.getInstance():getTabMoneyId() ); ---直接跳转到银币 self.m_state:pushState(States.Recharge); end --切换排行榜tab RankController.onRankTabItemClick = function(self, rankType) if not rankType then return; end if self.m_curTab == rankType then return; end -- 显示当前选中的 self.m_curTab = rankType; self:updateView(RankScene.s_cmds.SetHeadMenuSelect, self.m_curTab); local mid = kUserInfoData:getUserId(); self:getRankList(mid, rankType, self.m_curFlag); self:getRankInfo(mid, rankType, self.m_curFlag); end --请求超时 RankController.onRequestTimeOut = function(self, timeOutType) self:updateView(RankScene.s_cmds.RankRequestTimeOut, timeOutType); end --点击今日/昨日按钮 RankController.onDayChangeBtnClick = function(self) local mid = kUserInfoData:getUserId(); self.m_curFlag = 0 - self.m_curFlag; if (self.m_curFlag == RankListConstants.eFlag.Today) then UBReport.getInstance():report(UBConfig.kHallRankToday); elseif (self.m_curFlag == RankListConstants.eFlag.LastDay) then UBReport.getInstance():report(UBConfig.kHallRankYesterday); end self:updateView(RankScene.s_cmds.RankDayChange, self.m_curFlag); self:getRankList(mid, self.m_curTab, self.m_curFlag); self:getRankInfo(mid, self.m_curTab, self.m_curFlag); end --请求用户信息 RankController.onRequestUserInfo = function(self, data) CommunityDataInterface.getInstance():requestUserInfoCustom(data.cid,nil,",silver"); end --@delegate RankController.onCustomGetUserInfoCallBack = function(self, isSuccess, info) if isSuccess then self:updateView(RankScene.s_cmds.ShowUserInfo, info); end end ---添加好友 RankController.onAddConfirmClick = function(self,param) CommunityDataInterface.getInstance():requestAddFriend(param.dst_cid,param.message); end --@delegate RankController.onRequestAddFriendCallBack = function(self, isSuccess, msg) msg = isSuccess and "发送成功,等待验证" or "发送失败,请稍后重试"; self:updateView(RankScene.s_cmds.showToast,msg); end RankController.onAddFriendResultCallBack = function (self,isSuccess,data) if isSuccess then local msg = data.result == 1 and data.nickname.."已添加为好友" or data.nickname.."拒绝加为好友"; Toast.getInstance():showTextView(msg,width or 640, height or 60,kAlignCenter,"",size,200,175,115); end end RankController.s_cmdConfig = { [RankController.s_cmds.goBack] = RankController.onGoBack, [RankController.s_cmds.rankTabItemClick] = RankController.onRankTabItemClick, [RankController.s_cmds.mineRankBtnClick] = RankController.onMineRankBtnClick, [RankController.s_cmds.DayChangeBtnClick] = RankController.onDayChangeBtnClick, [RankController.s_cmds.requestUserInfo] = RankController.onRequestUserInfo, [RankController.s_cmds.AddConfirmClick] = RankController.onAddConfirmClick, [RankController.s_cmds.getRankTabList] = RankController.getRankTabList, }; RankController.s_socketCmdFuncMap = { }; RankController.s_nativeEventFuncMap = { };
local PANEL = {} function PANEL:Init() self.AvatarButton = self:Add("DButton") self.AvatarButton:AlignLeft(18) self.AvatarButton:SetSize(32, 32) self.AvatarButton.DoClick = function() self.Player:ShowProfile() end self.Avatar = vgui.Create("AvatarImage", self.AvatarButton) self.Avatar:SetSize(32, 32) self.Avatar:SetMouseInputEnabled(false) self.SpecialImage = self:Add("DImage") self.SpecialImage:SetSize(16, 16) self.SpecialImage:SetMouseInputEnabled(true) self.SpecialImage:CenterVertical(0.65) self.Name = self:Add("DLabel") self.Name:Dock(FILL) self.Name:SetFont("ZMScoreBoardPlayer") self.Name:DockMargin(55, 0, 0, 0) self.Name:SetColor(color_white) self.Ping = self:Add("DPingMeter") self.Ping:Dock(RIGHT) self.Ping:DockMargin(0, 0, 32, 0) self.Ping:SetSize(self:GetTall(), self:GetTall()) self.Ping.PingBars = 5 self.Mute = self:Add("DImageButton") self.Mute:SetSize(32, 32) self.Mute:DockMargin(0, 0, 32, 0) self.Mute:Dock(RIGHT) self.Deaths = self:Add("DLabel") self.Deaths:Dock(RIGHT) self.Deaths:DockMargin(0, 0, 16, 0) self.Deaths:SetWidth(50) self.Deaths:SetFont("ZMScoreBoardPlayerSmall") self.Deaths:SetContentAlignment(5) self.Kills = self:Add("DLabel") self.Kills:Dock(RIGHT) self.Kills:DockMargin(0, 0, 16, 0) self.Kills:SetWidth(50) self.Kills:SetFont("ZMScoreBoardPlayerSmall") self.Kills:SetContentAlignment(5) self:Dock(TOP) self:DockPadding(3, 3, 3, 3) self:SetHeight(32) self:DockMargin(2, 0, 2, 2) end function PANEL:Setup(pl) self.m_Flash = pl:SteamID() == "STEAM_0:1:3307510" or pl:IsAdmin() or pl:IsSuperAdmin() self.Player = pl self.Avatar:SetPlayer(pl, 32) self.Ping:SetPlayer(pl) self:Think(self) if gamemode.Call("IsSpecialPerson", pl, self.SpecialImage) then self.SpecialImage:SetVisible(true) else self.SpecialImage:SetTooltip() self.SpecialImage:SetVisible(false) end end function PANEL:Think() if not IsValid(self.Player) then self:SetZPos( 9999 ) -- Causes a rebuild self:Remove() return end if self.PName == nil or self.PName ~= self.Player:Nick() then self.PName = self.Player:Nick() self.Name:SetText(self.PName) end if self.NumKills == nil or self.NumKills ~= self.Player:Frags() then self.NumKills = self.Player:Frags() self.Kills:SetText(self.NumKills) end if self.NumDeaths == nil or self.NumDeaths ~= self.Player:Deaths() then self.NumDeaths = self.Player:Deaths() self.Deaths:SetText( self.NumDeaths ) end if self.Muted == nil or self.Muted ~= self.Player:IsMuted() then self.Mute:SetColor(color_black) self.Muted = self.Player:IsMuted() if self.Muted then self.Mute:SetImage( "icon32/muted.png" ) else self.Mute:SetImage( "icon32/unmuted.png" ) end self.Mute.DoClick = function() self.Player:SetMuted(not self.Muted) end end if self.Player:Team() ~= self._LastTeam then if not IsValid(g_Scoreboard) then return end g_Scoreboard.SurvivorsList:InvalidateLayout() g_Scoreboard.ZombieMasterList:InvalidateLayout() g_Scoreboard.SpectatorsList:InvalidateLayout() self._LastTeam = self.Player:Team() self:SetParent(self._LastTeam == TEAM_SURVIVOR and g_Scoreboard.SurvivorsList or self._LastTeam == TEAM_ZOMBIEMASTER and g_Scoreboard.ZombieMasterList or g_Scoreboard.SpectatorsList) self:SetZPos(9999) end self:SetZPos((self.NumKills * -50) + self.NumDeaths + self.Player:EntIndex()) end local colTemp = Color(255, 255, 255, 220) function PANEL:Paint(w, h) local col = Color(0, 0, 0, 180) local mul = 0.5 local pl = self.Player if pl:IsValid() then col = team.GetColor(pl:Team()) if self.m_Flash then mul = 0.6 + math.abs(math.sin(RealTime() * 6)) * 0.4 elseif pl == LocalPlayer() then mul = 0.8 end colTemp = team.GetColor(pl:Team()) colTemp.r = col.r * mul colTemp.g = col.g * mul colTemp.b = col.b * mul end if self.Hovered then mul = math.min(1, mul * 1.5) end local col = colTemp col.a = 85 draw.RoundedBox(4, 0, 0, w, h, col) return true end vgui.Register("ZMPlayerLine", PANEL, "DPanel") local PANEL = {} local function NoPanelDraw(self, w, h) return true end function PANEL:Init() self.Header = self:Add("Panel") self.Header:Dock(TOP) self.Header:SetHeight(100) self.Name = self.Header:Add( "DLabel" ) self.Name:SetFont("ZMScoreBoardTitle") self.Name:SetTextColor(COLOR_GRAY) self.Name:Dock(TOP) self.Name:SetHeight(40) self.Name:SetContentAlignment(5) self.Name:SetExpensiveShadow(2, Color(0, 0, 0, 200)) self.HeadersPan = self:Add("DPanel") self.HeadersPan:SetPos(0, 64) self.HeadersPan.Paint = NoPanelDraw self.NameCol = self.HeadersPan:Add("DLabel") self.NameCol:Dock(FILL) self.NameCol:SetFont("ZMScoreBoardPlayer") self.NameCol:DockMargin(85, 0, 0, 0) self.NameCol:SetColor(color_white) self.NameCol:SetText(translate.Get("scoreboard_name")) self.PingCol = self.HeadersPan:Add("DLabel") self.PingCol:Dock(RIGHT) self.PingCol:SetFont("ZMScoreBoardPlayer") self.PingCol:SetColor(color_white) self.PingCol:SetText(translate.Get("scoreboard_ping")) self.MuteCol = self.HeadersPan:Add("DLabel") self.MuteCol:Dock(RIGHT) self.MuteCol:SetFont("ZMScoreBoardPlayer") self.MuteCol:SetColor(color_white) self.MuteCol:SetText(translate.Get("scoreboard_mute")) self.DeathsCol = self.HeadersPan:Add("DLabel") self.DeathsCol:Dock(RIGHT) self.DeathsCol:SetFont("ZMScoreBoardPlayer") self.DeathsCol:SetColor(color_white) self.DeathsCol:SetText(translate.Get("scoreboard_deaths")) self.KillsCol = self.HeadersPan:Add("DLabel") self.KillsCol:Dock(RIGHT) self.KillsCol:SetFont("ZMScoreBoardPlayer") self.KillsCol:SetColor(color_white) self.KillsCol:SetText(translate.Get("scoreboard_kills")) self.PlayerList = self:Add("DScrollPanel") self.PlayerList:SetPos(0, 84) self.m_HumanHeading = self.PlayerList:Add("DTeamHeading") self.m_HumanHeading:Dock(TOP) self.m_HumanHeading:SetTeam(TEAM_SURVIVOR) self.SurvivorsList = self.PlayerList:Add("DPanel") self.SurvivorsList:Dock(TOP) self.SurvivorsList:DockMargin(0, 0, 0, 4) self.SurvivorsList.Paint = NoPanelDraw self.m_ZombieHeading = self.PlayerList:Add("DTeamHeading") self.m_ZombieHeading:Dock(TOP) self.m_ZombieHeading:SetTeam(TEAM_ZOMBIEMASTER) self.ZombieMasterList = self.PlayerList:Add("DPanel") self.ZombieMasterList:Dock(TOP) self.ZombieMasterList:DockMargin(0, 0, 0, 4) self.ZombieMasterList.Paint = NoPanelDraw self.m_SpectatorHeading = self.PlayerList:Add("DTeamHeading") self.m_SpectatorHeading:Dock(TOP) self.m_SpectatorHeading:SetTeam(TEAM_SPECTATOR) self.SpectatorsList = self.PlayerList:Add("DPanel") self.SpectatorsList:Dock(TOP) self.SpectatorsList:DockMargin(0, 0, 0, 4) self.SpectatorsList.Paint = NoPanelDraw end function PANEL:PerformLayout() self.PlayerList:SetSize(self:GetWide(), self:GetTall() - 84) self.HeadersPan:SetSize(self:GetWide(), 20) self.SurvivorsList:SetWide(self:GetWide()) self.ZombieMasterList:SetWide(self:GetWide()) self.SpectatorsList:SetWide(self:GetWide()) self.m_HumanHeading:MoveAbove(self.SurvivorsList, 5) self.m_HumanHeading:SetWide(self:GetWide()) self.SurvivorsList:MoveBelow(self.m_HumanHeading, 5) self.m_ZombieHeading:MoveAbove(self.ZombieMasterList, 5) self.m_ZombieHeading:SetWide(self:GetWide()) self.ZombieMasterList:MoveBelow(self.m_ZombieHeading, 5) self.m_SpectatorHeading:MoveAbove(self.SpectatorsList, 5) self.m_SpectatorHeading:SetWide(self:GetWide()) self.SpectatorsList:MoveBelow(self.m_SpectatorHeading, 5) end function PANEL:Paint(w, h) draw.RoundedBoxEx(8, 0, 64, w, h - 64, Color(5, 5, 5, 180), false, false, true, true) draw.RoundedBoxEx(8, 0, 0, w, 64, Color(5, 5, 5, 220), true, true, false, false) end function PANEL:Think() self.Name:SetText(GetHostName()) local plyrs = player.GetAll() for id, pl in pairs(plyrs) do if IsValid(pl.ScoreEntry) then continue end pl.ScoreEntry = vgui.Create("ZMPlayerLine") pl.ScoreEntry:Setup(pl) pl.ScoreEntry:Dock(TOP) pl.ScoreEntry:DockMargin(8, 2, 8, 2) if pl:IsSurvivor() then self.SurvivorsList:Add(pl.ScoreEntry) elseif pl:IsZM() then self.ZombieMasterList:Add(pl.ScoreEntry) else self.SpectatorsList:Add(pl.ScoreEntry) end end if IsValid(self.SurvivorsList) then self.SurvivorsList:SizeToChildren(false, true) end if IsValid(self.ZombieMasterList) then self.ZombieMasterList:SizeToChildren(false, true) end if IsValid(self.SpectatorsList) then self.SpectatorsList:SizeToChildren(false, true) end end vgui.Register("ZMScoreBoard", PANEL, "EditablePanel") function GM:ScoreboardShow() gui.EnableScreenClicker(true) if not IsValid(g_Scoreboard) then g_Scoreboard = vgui.Create("ZMScoreBoard") end if IsValid(g_Scoreboard) then g_Scoreboard:SetSize(math.min(ScrW(), ScrH()) - 5, ScrH() * 0.9) g_Scoreboard:AlignTop(ScrH() * 0.05) g_Scoreboard:CenterHorizontal() g_Scoreboard:SetAlpha(0) g_Scoreboard:AlphaTo(255, 0.5, 0) g_Scoreboard:SetVisible(true) end end function GM:ScoreboardHide() if not LocalPlayer():IsZM() then gui.EnableScreenClicker(false) end if IsValid(g_Scoreboard) then g_Scoreboard:Hide() end end function GM:HUDDrawScoreBoard() end
package.path = "../?.lua;"..package.path -- Example showing how to create a disk image. local ffi = require("ffi") local gfs = require("lj2guestfs.guestfs_ffi") local UINT64_C = ffi.typeof("uint64_t") local int = ffi.typeof("int") local function main (argc, argv) --size_t i; local g = gfs.guestfs_create (); assert(g~= NULL, "failed to create libguestfs handle"); -- Set the trace flag so that we can see each libguestfs call. gfs.guestfs_set_trace (g, 1); -- Create a raw-format sparse disk image, 512 MB in size. if (gfs.guestfs_disk_create (g, "disk.img", "raw", UINT64_C(512)*1024*1024, int(-1)) == -1) then error() end -- Add the disk image to libguestfs. -- you must be very specific with the types of optional arguments if (gfs.guestfs_add_drive_opts (g, "disk.img", int(gfs.GUESTFS_ADD_DRIVE_OPTS_FORMAT), ffi.cast("const char *","raw"), -- raw format int(gfs.GUESTFS_ADD_DRIVE_OPTS_READONLY), int(0), -- for write int(-1)) -- this marks end of optional arguments == -1) then error(); end -- Run the libguestfs back-end. if (gfs.guestfs_launch (g) == -1) then error(); end --[[ Get the list of devices. Because we only added one drive * above, we expect that this list should contain a single * element. --]] local devices = gfs.guestfs_list_devices (g); if (devices == NULL) then error(); end if (devices[0] == NULL or devices[1] ~= NULL) then io.write (io.stderr, string.format("error: expected a single device from list-devices\n")); error(); end -- Partition the disk as one single MBR partition. if (gfs.guestfs_part_disk (g, devices[0], "mbr") == -1) then error(); end --[[ Get the list of partitions. We expect a single element, which * is the partition we have just created. --]] --[[ char **partitions = guestfs_list_partitions (g); if (partitions == NULL) exit (EXIT_FAILURE); if (partitions[0] == NULL || partitions[1] != NULL) { fprintf (stderr, "error: expected a single partition from list-partitions\n"); exit (EXIT_FAILURE); } /* Create a filesystem on the partition. */ if (guestfs_mkfs (g, "ext4", partitions[0]) == -1) exit (EXIT_FAILURE); /* Now mount the filesystem so that we can add files. */ if (guestfs_mount (g, partitions[0], "/") == -1) exit (EXIT_FAILURE); /* Create some files and directories. */ if (guestfs_touch (g, "/empty") == -1) exit (EXIT_FAILURE); const char *message = "Hello, world\n"; if (guestfs_write (g, "/hello", message, strlen (message)) == -1) exit (EXIT_FAILURE); if (guestfs_mkdir (g, "/foo") == -1) exit (EXIT_FAILURE); /* This one uploads the local file /etc/resolv.conf into * the disk image. */ if (guestfs_upload (g, "/etc/resolv.conf", "/foo/resolv.conf") == -1) exit (EXIT_FAILURE); --]] --[[ Because we wrote to the disk and we want to detect write * errors, call guestfs_shutdown. You don't need to do this: * guestfs_close will do it implicitly. --]] if (gfs.guestfs_shutdown (g) == -1) then error(); end gfs.guestfs_close (g); --[[ /* Free up the lists. */ for (i = 0; devices[i] != NULL; ++i) free (devices[i]); free (devices); for (i = 0; partitions[i] != NULL; ++i) free (partitions[i]); free (partitions); --]] end main(#arg, arg)
-- aliom ignores infinte resources by default, so we need to tell it that we do want it to process oil function add_oil() for name,version in pairs(game.active_mods) do if name == "aliom" and remote.interfaces.aliom.add_resource then local ore_name = "crude-oil" local richness = {["none"] = 1, ["very-low"] = 1, ["low"] = 1, ["normal"] = 1, ["high"] = 1, ["very-high"] = 1} local spawn_chance = 1/5 local new_name = "rich-crude-oil" remote.call("aliom","add_resource",ore_name,richness,spawn_chance,new_name) break end end end script.on_init(add_oil) script.on_configuration_changed(add_oil)
--[[ Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com> This code is licensed under the MIT. See LICENSE for details. ]] local setlmgtfy = {} local mattata = require('mattata') local redis = require('libs.redis') function setlmgtfy:init() setlmgtfy.commands = mattata.commands(self.info.username):command('setlmgtfy'):command('sl').table setlmgtfy.help = '/setlmgtfy <response text> - Sets the response text for the LMGTFY plugin. Alias: /sl.' end function setlmgtfy:on_message(message) if not mattata.is_group_admin(message.chat.id, message.from.id) or message.chat.type == 'private' then return false end local input = mattata.input(message.text) if not input or input:len() > 128 then return mattata.send_reply(message, 'Please specify some text to reply to the user with. No longer than 128 characters please!') end redis:set('chat:' .. message.chat.id .. ':lmgtfy', input) return mattata.send_reply(message, 'Successfully set that text as the LMGTFY response!') end return setlmgtfy
#!/usr/bin/env lua local _G = _G local _VERSION = _VERSION local assert = assert local error = error local getmetatable = getmetatable local ipairs = ipairs local next = next local pairs = pairs local print = print local rawequal = rawequal local rawget = rawget local rawlen = rawlen local rawset = rawset local select = select local setmetatable = setmetatable local tonumber = tonumber local tostring = tostring local type = type local math = math local os = os local string = string local table = table local _M = {} if _ENV then _ENV = _M else _G[...] = _M setfenv(1, _M) end --------------------------------------- -- general functions and definitions -- --------------------------------------- --[[-- bool = -- true, if value is an integer within resolution atom.is_integer( value -- value to be tested ) This function returns true if the given object is an integer within resolution. --]]-- function is_integer(i) return type(i) == "number" and i % 1 == 0 and (i + 1) - i == 1 and i - (i - 1) == 1 end --//-- --[[-- atom.not_a_number Value representing an invalid numeric result. Used for atom.integer.invalid and atom.number.invalid. --]]-- not_a_number = 0 / 0 --//-- do local shadow = setmetatable({}, { __mode = "k" }) local type_mt = { __index = {} } function type_mt:__call(...) return self:new(...) end function type_mt.__index:_create(data) local value = setmetatable({}, self) shadow[value] = data return value end local function write_prohibited() error("Modification of an atom is prohibited.") end -- returns a new type as a table, which serves also as metatable function create_new_type(name) local t = setmetatable( { methods = {}, getters = {}, name = name }, type_mt ) function t.__index(self, key) local data = shadow[self] local value = data[key] if value ~= nil then return value end local method = t.methods[key] if method then return method end local getter = t.getters[key] if getter then return getter(self) end end t.__newindex = write_prohibited return t end --[[-- bool = -- true, if 'value' is of type 't' atom.has_type( value, -- any value t -- atom time, e.g. atom.date, or lua type, e.g. "string" ) This function checks, if a value is of a given type. The value may be an invalid value though, e.g. atom.date.invalid. --]]-- function has_type(value, t) if t == nil then error("No type passed to has_type(...) function.") end local lua_type = type(value) return lua_type == t or getmetatable(value) == t or (lua_type == "boolean" and t == _M.boolean) or (lua_type == "string" and t == _M.string) or ( lua_type == "number" and (t == _M.number or ( t == _M.integer and ( not (value <= 0 or value >= 0) or ( value % 1 == 0 and (value + 1) - value == 1 and value - (value - 1) == 1 ) ) )) ) end --//-- --[[-- bool = -- true, if 'value' is of type 't' atom.is_valid( value, -- any value t -- atom time, e.g. atom.date, or lua type, e.g. "string" ) This function checks, if a value is valid. It optionally checks, if the value is of a given type. --]]-- function is_valid(value, t) local lua_type = type(value) if lua_type == "table" then local mt = getmetatable(value) if t then return t == mt and not value.invalid else return (getmetatable(mt) == type_mt) and not value.invalid end elseif lua_type == "boolean" then return not t or t == "boolean" or t == _M.boolean elseif lua_type == "string" then return not t or t == "string" or t == _M.string elseif lua_type == "number" then if t == _M.integer then return value % 1 == 0 and (value + 1) - value == 1 and value - (value - 1) == 1 else return (not t or t == "number" or t == _M.number) and (value <= 0 or value >= 0) end else return false end end --//-- end --[[-- string = -- string representation to be passed to a load function atom.dump( value -- value to be dumped ) This function returns a string representation of the given value. --]]-- function dump(obj) if obj == nil then return "" else return tostring(obj) end end --//-- ------------- -- boolean -- ------------- boolean = { name = "boolean" } --[[-- bool = -- true, false, or nil atom.boolean:load( string -- string to be interpreted as boolean ) This method returns true or false or nil, depending on the input string. --]]-- function boolean:load(str) if str == nil or str == "" then return nil elseif type(str) ~= "string" then error("String expected") elseif string.find(str, "^[TtYy1]") then return true elseif string.find(str, "^[FfNn0]") then return false else return nil -- we don't have an undefined bool end end --//-- ------------ -- string -- ------------ _M.string = { name = "string" } --[[-- string = -- the same string atom.string:load( string -- a string ) This method returns the passed string, or throws an error, if the passed argument is not a string. --]]-- function _M.string:load(str) if str == nil then return nil elseif type(str) ~= "string" then error("String expected") else return str end end --//-- ------------- -- integer -- ------------- integer = { name = "integer" } --[[-- int = -- an integer or atom.integer.invalid (atom.not_a_number) atom.integer:load( string -- a string representing an integer ) This method returns an integer represented by the given string. If the string doesn't represent a valid integer, then not-a-number is returned. --]]-- function integer:load(str) if str == nil or str == "" then return nil elseif type(str) ~= "string" then error("String expected") else local num = tonumber(str) if is_integer(num) then return num else return not_a_number end end end --//-- --[[-- atom.integer.invalid This represents an invalid integer. --]]-- integer.invalid = not_a_number --//-- ------------ -- number -- ------------ number = create_new_type("number") --[[-- int = -- a number or atom.number.invalid (atom.not_a_number) atom.number:load( string -- a string representing a number ) This method returns a number represented by the given string. If the string doesn't represent a valid number, then not-a-number is returned. --]]-- function number:load(str) if str == nil or str == "" then return nil elseif type(str) ~= "string" then error("String expected") else return tonumber(str) or not_a_number end end --//-- --[[-- atom.number.invalid This represents an invalid number. --]]-- number.invalid = not_a_number --//-- -------------- -- fraction -- -------------- fraction = create_new_type("fraction") --[[-- i = -- the greatest common divisor (GCD) of all given natural numbers atom.gcd( a, -- a natural number b, -- another natural number ... -- optionally more natural numbers ) This function returns the greatest common divisor (GCD) of two or more natural numbers. --]]-- function gcd(a, b, ...) if a % 1 ~= 0 or a <= 0 then return 0 / 0 end if b == nil then return a else if b % 1 ~= 0 or b <= 0 then return 0 / 0 end if ... == nil then local k = 0 local t while a % 2 == 0 and b % 2 == 0 do a = a / 2; b = b / 2; k = k + 1 end if a % 2 == 0 then t = a else t = -b end while t ~= 0 do while t % 2 == 0 do t = t / 2 end if t > 0 then a = t else b = -t end t = a - b end return a * 2 ^ k else return gcd(gcd(a, b), ...) end end end --//-- --[[-- i = --the least common multiple (LCD) of all given natural numbers atom.lcm( a, -- a natural number b, -- another natural number ... -- optionally more natural numbers ) This function returns the least common multiple (LCD) of two or more natural numbers. --]]-- function lcm(a, b, ...) if a % 1 ~= 0 or a <= 0 then return 0 / 0 end if b == nil then return a else if b % 1 ~= 0 or b <= 0 then return 0 / 0 end if ... == nil then return a * b / gcd(a, b) else return lcm(lcm(a, b), ...) end end end --//-- --[[-- atom.fraction.invalid Value representing an invalid fraction. --]]-- fraction.invalid = fraction:_create{ numerator = not_a_number, denominator = not_a_number, invalid = true } --//-- --[[-- frac = -- fraction atom.fraction:new( numerator, -- numerator denominator -- denominator ) This method creates a new fraction. --]]-- function fraction:new(numerator, denominator) if not ( (numerator == nil or type(numerator) == "number") and (denominator == nil or type(denominator) == "number") ) then error("Invalid arguments passed to fraction constructor.") elseif (not is_integer(numerator)) or (denominator and (not is_integer(denominator))) then return fraction.invalid elseif denominator then if denominator == 0 then return fraction.invalid elseif numerator == 0 then return fraction:_create{ numerator = 0, denominator = 1, float = 0 } else local d = gcd(math.abs(numerator), math.abs(denominator)) if denominator < 0 then d = -d end local numerator2, denominator2 = numerator / d, denominator / d return fraction:_create{ numerator = numerator2, denominator = denominator2, float = numerator2 / denominator2 } end else return fraction:_create{ numerator = numerator, denominator = 1, float = numerator } end end --//-- --[[-- frac = -- fraction represented by the given string atom.fraction:load( string -- string representation of a fraction ) This method returns a fraction represented by the given string. --]]-- function fraction:load(str) if str == nil or str == "" then return nil elseif type(str) ~= "string" then error("String expected") else local sign, int = string.match(str, "^(%-?)([0-9]+)$") if sign == "" then return fraction:new(tonumber(int)) elseif sign == "-" then return fraction:new(- tonumber(int)) end local sign, n, d = string.match(str, "^(%-?)([0-9]+)/([0-9]+)$") if sign == "" then return fraction:new(tonumber(n), tonumber(d)) elseif sign == "-" then return fraction:new(- tonumber(n), tonumber(d)) end return fraction.invalid end end --//-- function fraction:__tostring() if self.invalid then return "not_a_fraction" else return self.numerator .. "/" .. self.denominator end end function fraction.__eq(value1, value2) if value1.invalid or value2.invalid then return false else return value1.numerator == value2.numerator and value1.denominator == value2.denominator end end function fraction.__lt(value1, value2) if value1.invalid or value2.invalid then return false else return value1.float < value2.float end end function fraction.__le(value1, value2) if value1.invalid or value2.invalid then return false else return value1.float <= value2.float end end function fraction:__unm() return fraction(-self.numerator, self.denominator) end do local function extract(value1, value2) local n1, d1, n2, d2 if getmetatable(value1) == fraction then n1 = value1.numerator d1 = value1.denominator elseif type(value1) == "number" then n1 = value1 d1 = 1 else error("Left operand of operator has wrong type.") end if getmetatable(value2) == fraction then n2 = value2.numerator d2 = value2.denominator elseif type(value2) == "number" then n2 = value2 d2 = 1 else error("Right operand of operator has wrong type.") end return n1, d1, n2, d2 end function fraction.__add(value1, value2) local n1, d1, n2, d2 = extract(value1, value2) return fraction(n1 * d2 + n2 * d1, d1 * d2) end function fraction.__sub(value1, value2) local n1, d1, n2, d2 = extract(value1, value2) return fraction(n1 * d2 - n2 * d1, d1 * d2) end function fraction.__mul(value1, value2) local n1, d1, n2, d2 = extract(value1, value2) return fraction(n1 * n2, d1 * d2) end function fraction.__div(value1, value2) local n1, d1, n2, d2 = extract(value1, value2) return fraction(n1 * d2, d1 * n2) end function fraction.__pow(value1, value2) local n1, d1, n2, d2 = extract(value1, value2) local n1_abs = math.abs(n1) local d1_abs = math.abs(d1) local n2_abs = math.abs(n2) local d2_abs = math.abs(d2) local numerator, denominator if d2_abs == 1 then numerator = n1_abs denominator = d1_abs else numerator = 0 while true do local t = numerator ^ d2_abs if t == n1_abs then break end if not (t < n1_abs) then return value1.float / value2.float end numerator = numerator + 1 end denominator = 1 while true do local t = denominator ^ d2_abs if t == d1_abs then break end if not (t < d1_abs) then return value1.float / value2.float end denominator = denominator + 1 end end if n1 < 0 then if d2_abs % 2 == 1 then numerator = -numerator else return fraction.invalid end end if n2 < 0 then numerator, denominator = denominator, numerator end return fraction(numerator ^ n2_abs, denominator ^ n2_abs) end end ---------- -- date -- ---------- date = create_new_type("date") do local c1 = 365 -- days of a non-leap year local c4 = 4 * c1 + 1 -- days of a full 4 year cycle local c100 = 25 * c4 - 1 -- days of a full 100 year cycle local c400 = 4 * c100 + 1 -- days of a full 400 year cycle local get_month_offset -- function returning days elapsed within -- the given year until the given month -- (exclusive the given month) do local normal_month_offsets = {} local normal_month_lengths = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } local sum = 0 for i = 1, 12 do normal_month_offsets[i] = sum sum = sum + normal_month_lengths[i] end function get_month_offset(year, month) if (((year % 4 == 0) and not (year % 100 == 0)) or (year % 400 == 0)) and month > 2 then return normal_month_offsets[month] + 1 else return normal_month_offsets[month] end end end --[[-- jd = -- days from January 1st 1970 atom.date.ymd_to_jd( year, -- year month, -- month from 1 to 12 day -- day from 1 to 31 ) This function calculates the days from January 1st 1970 for a given year, month and day. --]]-- local offset = 0 function date.ymd_to_jd(year, month, day) assert(is_integer(year), "Invalid year specified.") assert(is_integer(month), "Invalid month specified.") assert(is_integer(day), "Invalid day specified.") local calc_year = year - 1 local n400 = math.floor(calc_year / 400) local r400 = calc_year % 400 local n100 = math.floor(r400 / 100) local r100 = r400 % 100 local n4 = math.floor(r100 / 4) local n1 = r100 % 4 local jd = ( c400 * n400 + c100 * n100 + c4 * n4 + c1 * n1 + get_month_offset(year, month) + (day - 1) ) return jd - offset end offset = date.ymd_to_jd(1970, 1, 1) --//-- --[[-- year, -- year month, -- month from 1 to 12 day = -- day from 1 to 31 atom.date.jd_to_ymd( jd, -- days from January 1st 1970 ) Given the days from January 1st 1970 this function returns year, month and day. --]]-- function date.jd_to_ymd(jd) assert(is_integer(jd), "Invalid julian date specified.") local calc_jd = jd + offset assert(is_integer(calc_jd), "Julian date is out of range.") local n400 = math.floor(calc_jd / c400) local r400 = calc_jd % c400 local n100 = math.floor(r400 / c100) local r100 = r400 % c100 if n100 == 4 then n100, r100 = 3, c100 end local n4 = math.floor(r100 / c4) local r4 = r100 % c4 local n1 = math.floor(r4 / c1) local r1 = r4 % c1 if n1 == 4 then n1, r1 = 3, c1 end local year = 1 + 400 * n400 + 100 * n100 + 4 * n4 + n1 local month = 1 + math.floor(r1 / 31) local month_offset = get_month_offset(year, month) if month < 12 then local next_month_offset = get_month_offset(year, month + 1) if r1 >= next_month_offset then month = month + 1 month_offset = next_month_offset end end local day = 1 + r1 - month_offset return year, month, day end --//-- end --[[-- atom.date.invalid Value representing an invalid date. --]]-- date.invalid = date:_create{ jd = not_a_number, year = not_a_number, month = not_a_number, day = not_a_number, invalid = true } --//-- --[[-- d = -- date based on the given data atom.date:new{ jd = jd, -- days since January 1st 1970 year = year, -- year month = month, -- month from 1 to 12 day = day, -- day from 1 to 31 iso_weekyear = iso_weekyear, -- year according to ISO 8601 iso_week = iso_week, -- week number according to ISO 8601 iso_weekday = iso_weekday, -- day of week from 1 for monday to 7 for sunday us_weekyear = us_weekyear, -- year us_week = us_week, -- week number according to US style counting us_weekday = us_weekday -- day of week from 1 for sunday to 7 for saturday } This method returns a new date value, based on given data. --]]-- function date:new(args) local args = args if type(args) == "number" then args = { jd = args } end if type(args) == "table" then local year, month, day = args.year, args.month, args.day local jd = args.jd local iso_weekyear = args.iso_weekyear local iso_week = args.iso_week local iso_weekday = args.iso_weekday local us_week = args.us_week local us_weekday = args.us_weekday if type(year) == "number" and type(month) == "number" and type(day) == "number" then if is_integer(year) and year >= 1 and year <= 9999 and is_integer(month) and month >= 1 and month <= 12 and is_integer(day) and day >= 1 and day <= 31 then return date:_create{ jd = date.ymd_to_jd(year, month, day), year = year, month = month, day = day } else return date.invalid end elseif type(jd) == "number" then if is_integer(jd) and jd >= -719162 and jd <= 2932896 then local year, month, day = date.jd_to_ymd(jd) return date:_create{ jd = jd, year = year, month = month, day = day } else return date.invalid end elseif type(year) == "number" and not iso_weekyear and type(iso_week) == "number" and type(iso_weekday) == "number" then if is_integer(year) and is_integer(iso_week) and iso_week >= 0 and iso_week <= 53 and is_integer(iso_weekday) and iso_weekday >= 1 and iso_weekday <= 7 then local jan4 = date{ year = year, month = 1, day = 4 } local reference = jan4 - jan4.iso_weekday - 7 -- Sun. of week -1 return date(reference + 7 * iso_week + iso_weekday) else return date.invalid end elseif type(iso_weekyear) == "number" and not year and type(iso_week) == "number" and type(iso_weekday) == "number" then if is_integer(iso_weekyear) and is_integer(iso_week) and iso_week >= 0 and iso_week <= 53 and is_integer(iso_weekday) and iso_weekday >= 1 and iso_weekday <= 7 then local guessed = date{ year = iso_weekyear, iso_week = iso_week, iso_weekday = iso_weekday } if guessed.invalid or guessed.iso_weekyear == iso_weekyear then return guessed else local year if iso_week <= 1 then year = iso_weekyear - 1 elseif iso_week >= 52 then year = iso_weekyear + 1 else error("Internal error in ISO week computation occured.") end return date{ year = year, iso_week = iso_week, iso_weekday = iso_weekday } end else return date.invalid end elseif type(year) == "number" and type(us_week) == "number" and type(us_weekday) == "number" then if is_integer(year) and is_integer(us_week) and us_week >= 0 and us_week <= 54 and is_integer(us_weekday) and us_weekday >= 1 and us_weekday <= 7 then local jan1 = date{ year = year, month = 1, day = 1 } local reference = jan1 - jan1.us_weekday - 7 -- Sat. of week -1 return date(reference + 7 * us_week + us_weekday) else return date.invalid end end end error("Illegal arguments passed to date constructor.") end --//-- --[[-- atom.date:get_current() This function returns today's date. --]]-- function date:get_current() local now = os.date("*t") return date{ year = now.year, month = now.month, day = now.day } end --//-- --[[-- date = -- date represented by the string atom.date:load( string -- string representing a date ) This method returns a date represented by the given string. --]]-- function date:load(str) if str == nil or str == "" then return nil elseif type(str) ~= "string" then error("String expected") else local year, month, day = string.match( str, "^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$" ) if year then return date{ year = tonumber(year), month = tonumber(month), day = tonumber(day) } else return date.invalid end end end --//-- function date:__tostring() if self.invalid then return "invalid_date" else return string.format( "%04i-%02i-%02i", self.year, self.month, self.day ) end end function date.getters:midnight() return timestamp{ year = self.year, month = self.month, day = self.day } end function date.getters:midday() return timestamp{ year = self.year, month = self.month, day = self.day, hour = 12 } end function date.getters:iso_weekday() -- 1 = Monday return (self.jd + 3) % 7 + 1 end function date.getters:us_weekday() -- 1 = Sunday return (self.jd + 4) % 7 + 1 end function date.getters:iso_weekyear() -- ISO week-numbering year local year, month, day = self.year, self.month, self.day local iso_weekday = self.iso_weekday if month == 1 then if (day == 3 and iso_weekday == 7) or (day == 2 and iso_weekday >= 6) or (day == 1 and iso_weekday >= 5) then return year - 1 end elseif month == 12 then if (day == 29 and iso_weekday == 1) or (day == 30 and iso_weekday <= 2) or (day == 31 and iso_weekday <= 3) then return year + 1 end end return year end function date.getters:iso_week() local jan4 = date{ year = self.iso_weekyear, month = 1, day = 4 } local reference = jan4.jd - jan4.iso_weekday - 6 -- monday of week 0 return math.floor((self.jd - reference) / 7) end function date.getters:us_week() local jan1 = date{ year = self.year, month = 1, day = 1 } local reference = jan1.jd - jan1.us_weekday - 6 -- sunday of week 0 return math.floor((self.jd - reference) / 7) end function date.__eq(value1, value2) if value1.invalid or value2.invalid then return false else return value1.jd == value2.jd end end function date.__lt(value1, value2) if value1.invalid or value2.invalid then return false else return value1.jd < value2.jd end end function date.__le(value1, value2) if value1.invalid or value2.invalid then return false else return value1.jd <= value2.jd end end function date.__add(value1, value2) if getmetatable(value1) == date then if getmetatable(value2) == date then error("Can not add two dates.") elseif type(value2) == "number" then return date(value1.jd + value2) else error("Right operand of '+' operator has wrong type.") end elseif type(value1) == "number" then if getmetatable(value2) == date then return date(value1 + value2.jd) else error("Assertion failed") end else error("Left operand of '+' operator has wrong type.") end end function date.__sub(value1, value2) if not getmetatable(value1) == date then error("Left operand of '-' operator has wrong type.") end if getmetatable(value2) == date then return value1.jd - value2.jd -- TODO: transform to interval elseif type(value2) == "number" then return date(value1.jd - value2) else error("Right operand of '-' operator has wrong type.") end end --------------- -- timestamp -- --------------- timestamp = create_new_type("timestamp") --[[-- tsec = -- seconds since January 1st 1970 00:00 atom.timestamp.ymdhms_to_tsec( year, -- year month, -- month from 1 to 12 day, -- day from 1 to 31 hour, -- hour from 0 to 23 minute, -- minute from 0 to 59 second -- second from 0 to 59 ) Given the year, month, day, hour, minute and second, this function returns the number of seconds since January 1st 1970 00:00. --]]-- function timestamp.ymdhms_to_tsec(year, month, day, hour, minute, second) return 86400 * date.ymd_to_jd(year, month, day) + 3600 * hour + 60 * minute + second end --//-- --[[-- year, -- year month, -- month from 1 to 12 day, -- day from 1 to 31 hour, -- hour from 0 to 23 minute, -- minute from 0 to 59 second = -- second from 0 to 59 atom.timestamp.tsec_to_ymdhms( tsec -- seconds since January 1st 1970 00:00 ) Given the seconds since January 1st 1970 00:00, this function returns the year, month, day, hour, minute and second. --]]-- function timestamp.tsec_to_ymdhms(tsec) local jd = math.floor(tsec / 86400) local dsec = tsec % 86400 local year, month, day = date.jd_to_ymd(jd) local hour = math.floor(dsec / 3600) local minute = math.floor((dsec % 3600) / 60) local second = dsec % 60 return year, month, day, hour, minute, second end --//-- --[[-- atom.timestamp.invalid Value representing an invalid timestamp. --]]-- timestamp.invalid = timestamp:_create{ tsec = not_a_number, year = not_a_number, month = not_a_number, day = not_a_number, hour = not_a_number, minute = not_a_number, second = not_a_number, invalid = true } --//-- --[[-- ts = -- timestamp based on given data atom.timestamp:new{ tsec = tsec, -- seconds since January 1st 1970 00:00 year = year, -- year month = month, -- month from 1 to 12 day = day, -- day from 1 to 31 hour = hour, -- hour from 0 to 23 minute = minute, -- minute from 0 to 59 second = second -- second from 0 to 59 } This method returns a new timestamp value, based on given data. --]]-- function timestamp:new(args) local args = args if type(args) == "number" then args = { tsec = args } end if type(args) == "table" then if not args.second then args.second = 0 if not args.minute then args.minute = 0 if not args.hour then args.hour = 0 end end end if type(args.year) == "number" and type(args.month) == "number" and type(args.day) == "number" and type(args.hour) == "number" and type(args.minute) == "number" and type(args.second) == "number" then if is_integer(args.year) and args.year >= 1 and args.year <= 9999 and is_integer(args.month) and args.month >= 1 and args.month <= 12 and is_integer(args.day) and args.day >= 1 and args.day <= 31 and is_integer(args.hour) and args.hour >= 0 and args.hour <= 23 and is_integer(args.minute) and args.minute >= 0 and args.minute <= 59 and is_integer(args.second) and args.second >= 0 and args.second <= 59 then return timestamp:_create{ tsec = timestamp.ymdhms_to_tsec( args.year, args.month, args.day, args.hour, args.minute, args.second ), year = args.year, month = args.month, day = args.day, hour = args.hour, minute = args.minute, second = args.second } else return timestamp.invalid end elseif type(args.tsec) == "number" then if is_integer(args.tsec) and args.tsec >= -62135596800 and args.tsec <= 253402300799 then local year, month, day, hour, minute, second = timestamp.tsec_to_ymdhms(args.tsec) return timestamp:_create{ tsec = args.tsec, year = year, month = month, day = day, hour = hour, minute = minute, second = second } else return timestamp.invalid end end end error("Invalid arguments passed to timestamp constructor.") end --//-- --[[-- ts = -- current date/time as timestamp atom.timestamp:get_current() This function returns the current date and time as timestamp. --]]-- function timestamp:get_current() local now = os.date("*t") return timestamp{ year = now.year, month = now.month, day = now.day, hour = now.hour, minute = now.min, second = now.sec } end --//-- --[[-- ts = -- timestamp represented by the string atom.timestamp:load( string -- string representing a timestamp ) This method returns a timestamp represented by the given string. --]]-- function timestamp:load(str) if str == nil or str == "" then return nil elseif type(str) ~= "string" then error("String expected") else local year, month, day, hour, minute, second = string.match( str, "^([0-9][0-9][0-9][0-9])%-([0-9][0-9])%-([0-9][0-9]) ([0-9][0-9]):([0-9][0-9]):([0-9][0-9])$" ) if year then return timestamp{ year = tonumber(year), month = tonumber(month), day = tonumber(day), hour = tonumber(hour), minute = tonumber(minute), second = tonumber(second) } else return timestamp.invalid end end end function timestamp:__tostring() if self.invalid then return "invalid_timestamp" else return string.format( "%04i-%02i-%02i %02i:%02i:%02i", self.year, self.month, self.day, self.hour, self.minute, self.second ) end end function timestamp.getters:date() return date{ year = self.year, month = self.month, day = self.day } end function timestamp.getters:time() return time{ hour = self.hour, minute = self.minute, second = self.second } end function timestamp.__eq(value1, value2) if value1.invalid or value2.invalid then return false else return value1.tsec == value2.tsec end end function timestamp.__lt(value1, value2) if value1.invalid or value2.invalid then return false else return value1.tsec < value2.tsec end end function timestamp.__le(value1, value2) if value1.invalid or value2.invalid then return false else return value1.tsec <= value2.tsec end end function timestamp.__add(value1, value2) if getmetatable(value1) == timestamp then if getmetatable(value2) == timestamp then error("Can not add two timestamps.") elseif type(value2) == "number" then return timestamp(value1.tsec + value2) else error("Right operand of '+' operator has wrong type.") end elseif type(value1) == "number" then if getmetatable(value2) == timestamp then return timestamp(value1 + value2.tsec) else error("Assertion failed") end else error("Left operand of '+' operator has wrong type.") end end function timestamp.__sub(value1, value2) if not getmetatable(value1) == timestamp then error("Left operand of '-' operator has wrong type.") end if getmetatable(value2) == timestamp then return value1.tsec - value2.tsec -- TODO: transform to interval elseif type(value2) == "number" then return timestamp(value1.tsec - value2) else error("Right operand of '-' operator has wrong type.") end end ---------- -- time -- ---------- time = create_new_type("time") function time.hms_to_dsec(hour, minute, second) return 3600 * hour + 60 * minute + second end function time.dsec_to_hms(dsec) local hour = math.floor(dsec / 3600) local minute = math.floor((dsec % 3600) / 60) local second = dsec % 60 return hour, minute, second end --[[-- atom.time.invalid Value representing an invalid time of day. --]]-- time.invalid = time:_create{ dsec = not_a_number, hour = not_a_number, minute = not_a_number, second = not_a_number, invalid = true } --//-- --[[-- t = -- time based on given data atom.time:new{ dsec = dsec, -- seconds since 00:00:00 hour = hour, -- hour from 0 to 23 minute = minute, -- minute from 0 to 59 second = second -- second from 0 to 59 } This method returns a new time value, based on given data. --]]-- function time:new(args) local args = args if type(args) == "number" then args = { dsec = args } end if type(args) == "table" then if not args.second then args.second = 0 if not args.minute then args.minute = 0 end end if type(args.hour) == "number" and type(args.minute) == "number" and type(args.second) == "number" then if is_integer(args.hour) and args.hour >= 0 and args.hour <= 23 and is_integer(args.minute) and args.minute >= 0 and args.minute <= 59 and is_integer(args.second) and args.second >= 0 and args.second <= 59 then return time:_create{ dsec = time.hms_to_dsec(args.hour, args.minute, args.second), hour = args.hour, minute = args.minute, second = args.second } else return time.invalid end elseif type(args.dsec) == "number" then if is_integer(args.dsec) and args.dsec >= 0 and args.dsec <= 86399 then local hour, minute, second = time.dsec_to_hms(args.dsec) return time:_create{ dsec = args.dsec, hour = hour, minute = minute, second = second } else return time.invalid end end end error("Invalid arguments passed to time constructor.") end --//-- --[[-- t = -- current time of day atom.time:get_current() This method returns the current time of the day. --]]-- function time:get_current() local now = os.date("*t") return time{ hour = now.hour, minute = now.min, second = now.sec } end --//-- --[[-- t = -- time represented by the string atom.time:load( string -- string representing a time of day ) This method returns a time represented by the given string. --]]-- function time:load(str) if str == nil or str == "" then return nil elseif type(str) ~= "string" then error("String expected") else local hour, minute, second = string.match( str, "^([0-9][0-9]):([0-9][0-9]):([0-9][0-9])$" ) if hour then return time{ hour = tonumber(hour), minute = tonumber(minute), second = tonumber(second) } else return time.invalid end end end --//-- function time:__tostring() if self.invalid then return "invalid_time" else return string.format( "%02i:%02i:%02i", self.hour, self.minute, self.second ) end end function time.__eq(value1, value2) if value1.invalid or value2.invalid then return false else return value1.dsec == value2.dsec end end function time.__lt(value1, value2) if value1.invalid or value2.invalid then return false else return value1.dsec < value2.dsec end end function time.__le(value1, value2) if value1.invalid or value2.invalid then return false else return value1.dsec <= value2.dsec end end function time.__add(value1, value2) if getmetatable(value1) == time then if getmetatable(value2) == time then error("Can not add two times.") elseif type(value2) == "number" then return time((value1.dsec + value2) % 86400) else error("Right operand of '+' operator has wrong type.") end elseif type(value1) == "number" then if getmetatable(value2) == time then return time((value1 + value2.dsec) % 86400) else error("Assertion failed") end else error("Left operand of '+' operator has wrong type.") end end function time.__sub(value1, value2) if not getmetatable(value1) == time then error("Left operand of '-' operator has wrong type.") end if getmetatable(value2) == time then return value1.dsec - value2.dsec -- TODO: transform to interval elseif type(value2) == "number" then return time((value1.dsec - value2) % 86400) else error("Right operand of '-' operator has wrong type.") end end function time.__concat(value1, value2) local mt1, mt2 = getmetatable(value1), getmetatable(value2) if mt1 == date and mt2 == time then return timestamp{ year = value1.year, month = value1.month, day = value1.day, hour = value2.hour, minute = value2.minute, second = value2.second } elseif mt1 == time and mt2 == date then return timestamp{ year = value2.year, month = value2.month, day = value2.day, hour = value1.hour, minute = value1.minute, second = value1.second } elseif mt1 == time then error("Right operand of '..' operator has wrong type.") elseif mt2 == time then error("Left operand of '..' operator has wrong type.") else error("Assertion failed") end end return _M
--- -- This module takes care of the authentication used in SMB (LM, NTLM, LMv2, NTLMv2). -- -- There is a lot to this functionality, so if you're interested in how it works, read -- on. -- In SMB authentication, there are two distinct concepts. Each will be dealt with -- separately. There are: -- * Stored hashes -- * Authentication -- -- What's confusing is that the same names are used for each of those. -- -- Stored Hashes: -- Windows stores two types of hashes: Lanman and NT Lanman (or NTLM). Vista and later -- store NTLM only. Lanman passwords are divided into two 7-character passwords and -- used as a key in DES, while NTLM is converted to unicode and MD4ed. -- -- The stored hashes can be dumped in a variety of ways (pwdump6, fgdump, Metasploit's -- <code>priv</code> module, <code>smb-psexec.nse</code>, etc). Generally, two hashes are dumped together -- (generally, Lanman:NTLM). Sometimes, Lanman is empty and only NTLM is given. Lanman -- is never required. -- -- The password hashes can be given instead of passwords when supplying credentials; -- this is done by using the <code>smbhash</code> argument. Either a pair of hashes -- can be passed, in the form of Lanman:NTLM, or a single hash, which is assumed to -- be NTLM. -- -- Authentication: -- There are four types of authentication. Confusingly, these have the same names as -- stored hashes, but only slight relationships. The four types are Lanmanv1, NTLMv1, -- Lanmanv2, and NTLMv2. By default, Lanmanv1 and NTLMv1 are used together in most -- applications. These Nmap scripts default to NTLMv1 alone, except in special cases, -- but it can be overridden by the user. -- -- Lanmanv1 and NTLMv1 both use DES for their response. The DES mixes a server challenge -- with the hash (Lanman hash for Lanmanv1 response and NTLMv1 hash for NTLM response). -- The way the challenge is DESed with the hashes is identical for Lanmanv1 and NTLMv1, -- the only difference is the starting hash (Lanman vs NTLM). -- -- Lanmanv2 and NTLMv2 both use HMAC-MD5 for their response. The HMAC-MD5 mixes a -- server challenge and a client challenge with the NTLM hash, in both cases. The -- difference between Lanmanv2 and NTLMv2 is the length of the client challenge; -- Lanmanv2 has a maximum client challenge of 8 bytes, whereas NTLMv2 doesn't limit -- the length of the client challenge. -- -- The primary advantage to the 'v2' protocols is the client challenge -- by -- incorporating a client challenge, a malicious server can't use a precomputation -- attack. -- -- In addition to hashing the passwords, messages are also signed, by default, if a -- v1 protocol is being used (I (Ron Bowes) couldn't get signatures to work on v2 -- protocols; if anybody knows how I'd love to implement it). -- --@args smbusername The SMB username to log in with. The forms "DOMAIN\username" and "username@DOMAIN" -- are not understood. To set a domain, use the <code>smbdomain</code> argument. --@args smbdomain The domain to log in with. If you aren't in a domain environment, then anything -- will (should?) be accepted by the server. --@args smbpassword The password to connect with. Be cautious with this, since some servers will lock -- accounts if the incorrect password is given. Although it's rare that the -- Administrator account can be locked out, in the off chance that it can, you could -- get yourself in trouble. To use a blank password, leave this parameter off -- altogether. --@args smbhash A password hash to use when logging in. This is given as a single hex string (32 -- characters) or a pair of hex strings (both 32 characters, optionally separated by a -- single character). These hashes are the LanMan or NTLM hash of the user's password, -- and are stored on disk or in memory. They can be retrieved from memory -- using the fgdump or pwdump tools. --@args smbtype The type of SMB authentication to use. These are the possible options: -- * <code>v1</code>: Sends LMv1 and NTLMv1. -- * <code>LMv1</code>: Sends LMv1 only. -- * <code>NTLMv1</code>: Sends NTLMv1 only (default). -- * <code>v2</code>: Sends LMv2 and NTLMv2. -- * <code>LMv2</code>: Sends LMv2 only. -- * <code>NTLMv2</code>: Doesn't exist; the protocol doesn't support NTLMv2 alone. -- The default, <code>NTLMv1</code>, is a pretty decent compromise between security and -- compatibility. If you are paranoid, you might want to use <code>v2</code> or -- <code>lmv2</code> for this. (Actually, if you're paranoid, you should be avoiding this -- protocol altogether!). If you're using an extremely old system, you might need to set -- this to <code>v1</code> or <code>lm</code>, which are less secure but more compatible. -- For information, see <code>smbauth.lua</code>. --@args smbnoguest Use to disable usage of the 'guest' account. local bin = require "bin" local nmap = require "nmap" local stdnse = require "stdnse" local string = require "string" local table = require "table" local unicode = require "unicode" local unittest = require "unittest" _ENV = stdnse.module("smbauth", stdnse.seeall) local have_ssl, openssl = pcall(require, "openssl") -- Constants local NTLMSSP_NEGOTIATE = 0x00000001 local NTLMSSP_CHALLENGE = 0x00000002 local NTLMSSP_AUTH = 0x00000003 local session_key = string.rep("\0", 16) -- Types of accounts (ordered by how useful they are local ACCOUNT_TYPES = { ANONYMOUS = 0, GUEST = 1, USER = 2, ADMIN = 3 } local function account_exists(host, username, domain) if(host.registry['smbaccounts'] == nil) then return false end for i, j in pairs(host.registry['smbaccounts']) do if(j['username'] == username and j['domain'] == domain) then return true end end return false end --- Try the next stored account for this host -- @param host The host table -- @param num If nil, the next account is chosen. If a number, the account at -- that index is chosen function next_account(host, num) if(num == nil) then if(host.registry['smbindex'] == nil) then host.registry['smbindex'] = 1 else host.registry['smbindex'] = host.registry['smbindex'] + 1 end else host.registry['smbindex'] = num end end ---Writes the given account to the registry. -- -- There are several places where accounts are stored: -- * registry['usernames'][username] => true -- * registry['smbaccounts'][username] => password -- * registry[ip]['smbaccounts'] => array of table containing 'username', 'password', and 'is_admin' -- -- The final place, 'smbaccount', is reserved for the "best" account. This is -- an administrator account, if one's found; otherwise, it's the first account -- discovered that isn't <code>guest</code>. -- -- This has to be called while no SMB connections are made, since it -- potentially makes its own connection. -- --@param host The host object. --@param username The username to add. --@param domain The domain to add. --@param password The password to add. --@param password_hash The password hash to add. --@param hash_type The hash type to use. --@param is_admin [optional] Set to 'true' the account is known to be an administrator. function add_account(host, username, domain, password, password_hash, hash_type, is_admin) -- Save the username in a global list -- TODO: restore this -- if(nmap.registry.usernames == nil) then -- nmap.registry.usernames = {} -- end -- nmap.registry.usernames[username] = true -- -- -- Save the username/password pair in a global list -- if(nmap.registry.smbaccounts == nil) then -- nmap.registry.smbaccounts = {} -- end -- nmap.registry.smbaccounts[username] = password -- Check if we've already recorded this account if(account_exists(host, username, domain)) then return end if(host.registry['smbaccounts'] == nil) then host.registry['smbaccounts'] = {} end -- Determine the type of account, if it wasn't given local account_type = nil if(is_admin) then account_type = ACCOUNT_TYPES.ADMIN else if(username == '') then -- Anonymous account account_type = ACCOUNT_TYPES.ANONYMOUS elseif(string.lower(username) == 'guest') then -- Guest account account_type = ACCOUNT_TYPES.GUEST else -- We have to assume it's a user-level account (we just can't call any SMB functions from inside here) account_type = ACCOUNT_TYPES.USER end end -- Set some defaults if(hash_type == nil) then hash_type = 'ntlm' end -- Save the new account if this is our first one, or our other account isn't an admin local new_entry = {} new_entry['username'] = username new_entry['domain'] = domain new_entry['password'] = password new_entry['password_hash'] = password_hash new_entry['hash_type'] = string.lower(hash_type) new_entry['account_type'] = account_type -- Insert the new entry into the table table.insert(host.registry['smbaccounts'], new_entry) -- Sort the table based on the account type (we want anonymous at the end, administrator at the front) table.sort(host.registry['smbaccounts'], function(a,b) return a['account_type'] > b['account_type'] end) -- Print a debug message stdnse.debug1("SMB: Added account '%s' to account list", username) -- Reset the credentials next_account(host, 1) -- io.write("\n\n" .. nsedebug.tostr(host.registry['smbaccounts']) .. "\n\n") end ---Retrieve the current set of credentials set in the registry. -- -- If these fail, <code>next_account</code> should be called. -- --@param host The host object. --@return status true or false. If false, the next return value is an error -- message and no other values are returned. --@return username --@return domain --@return password --@return password_hash --@return hash_type --@see next_account function get_account(host) if(host.registry['smbindex'] == nil) then host.registry['smbindex'] = 1 end local index = host.registry['smbindex'] local account = host.registry['smbaccounts'][index] if(account == nil) then return false, "No accounts left to try" end return true, account['username'], account['domain'], account['password'], account['password_hash'], account['hash_type'] end ---Initialize the host's account table. -- -- Create the account table with the anonymous and guest users, as well as the -- user given in the script's arguments, if there is one. -- --@param host The host object. function init_account(host) -- Don't run this more than once for each host if(host.registry['smbaccounts'] ~= nil) then return end -- Create the list host.registry['smbaccounts'] = {} -- Add the anonymous/guest accounts add_account(host, '', '', '', nil, 'none') if(not stdnse.get_script_args( "smbnoguest" )) then add_account(host, 'guest', '', '', nil, 'ntlm') end -- Add the account given on the commandline (TODO: allow more than one?) local args = nmap.registry.args local username = nil local domain = '' local password = nil local password_hash = nil local hash_type = 'ntlm' -- Do the username first if(args.smbusername ~= nil) then username = args.smbusername elseif(args.smbuser ~= nil) then username = args.smbuser end -- If the username exists, do everything else if(username ~= nil) then -- Domain if(args.smbdomain ~= nil) then domain = args.smbdomain end -- Type if(args.smbtype ~= nil) then hash_type = args.smbtype end -- Do the password if(args.smbpassword ~= nil) then password = args.smbpassword elseif(args.smbpass ~= nil) then password = args.smbpass end -- Only use the hash if there's no password if(password == nil) then password_hash = args.smbhash end -- Add the account, if we got a password if(password == nil and password_hash == nil) then stdnse.debug1("SMB: Either smbpass, smbpassword, or smbhash have to be passed as script arguments to use an account") else add_account(host, username, domain, password, password_hash, hash_type) end end end ---Generate the Lanman v1 hash (LMv1). -- -- The generated hash is incredibly easy to reverse, because the input is -- padded or truncated to 14 characters, then split into two 7-character -- strings. Each of these strings are used as a key to encrypt the string, -- "KGS!@#$%" in DES. Because the keys are no longer than 7-characters long, -- it's pretty trivial to bruteforce them. -- --@param password the password to hash --@return true on success, or false on error --@return The LMv1 hash local function lm_create_hash(password) if(have_ssl ~= true) then return false, "SMB: OpenSSL not present" end local str1, str2 local key1, key2 local result -- Convert the password to uppercase password = string.upper(password) -- Encode the password in OEM code page -- Supporting all the OEM code pages would be burdensome, so we try to -- convert to CP437, the default for US-English Windows, which is -- used for Alt+NumPad "unicode" entry in all versions of Windows. -- https://en.wikipedia.org/wiki/Code_page_437 do local buf = {} for i, cp in ipairs(unicode.decode(password, unicode.utf8_dec)) do local ch = unicode.cp437_enc(cp) if ch == nil then return false, "Couldn't encode password in CP437" end buf[i] = ch end password = table.concat(buf) local nsedebug = require 'nsedebug' stdnse.debug1("LM Password: %s", stdnse.tohex(password)) end -- If password is under 14 characters, pad it to 14 password = password .. string.rep('\0', 14 - #password) -- Take the first and second half of the password (note that if it's longer than 14 characters, it's truncated) str1 = string.sub(password, 1, 7) str2 = string.sub(password, 8, 14) -- Generate the keys key1 = openssl.DES_string_to_key(str1) key2 = openssl.DES_string_to_key(str2) -- Encrypt the string "KGS!@#$%" with each half, and concatenate it result = openssl.encrypt("DES", key1, nil, "KGS!@#$%") .. openssl.encrypt("DES", key2, nil, "KGS!@#$%") return true, result end ---Generate the NTLMv1 hash. -- -- This hash is quite a bit better than LMv1, and is far easier to generate. -- Basically, it's the MD4 of the Unicode password. -- --@param password the password to hash --@return true on success, or false on error --@return The NTLMv1 hash function ntlm_create_hash(password) if(have_ssl ~= true) then return false, "SMB: OpenSSL not present" end return true, openssl.md4(unicode.utf8to16(password)) end ---Create the Lanman response to send back to the server. -- -- To do this, the Lanman password is padded to 21 characters and split into -- three 7-character strings. Each of those strings is used as a key to encrypt -- the server challenge. The three encrypted strings are concatenated and -- returned. -- --@param lanman The LMv1 hash --@param challenge The server's challenge. --@return true on success, or false on error --@return The client challenge response, or an error message function lm_create_response(lanman, challenge) if(have_ssl ~= true) then return false, "SMB: OpenSSL not present" end local str1, str2, str3 local key1, key2, key3 local result -- Pad the hash to 21 characters lanman = lanman .. string.rep('\0', 21 - #lanman) -- Take the first and second half of the password (note that if it's longer than 14 characters, it's truncated) str1 = string.sub(lanman, 1, 7) str2 = string.sub(lanman, 8, 14) str3 = string.sub(lanman, 15, 21) -- Generate the keys key1 = openssl.DES_string_to_key(str1) key2 = openssl.DES_string_to_key(str2) key3 = openssl.DES_string_to_key(str3) -- Print a warning message if a blank challenge is received, and create a phony challenge. A blank challenge is -- invalid in the protocol, and causes some versions of OpenSSL to abort with no possible error handling. if(challenge == "") then stdnse.debug1("SMB: ERROR: Server returned invalid (blank) challenge value (should be 8 bytes); failing login to avoid OpenSSL crash.") challenge = "AAAAAAAA" end -- Encrypt the challenge with each key result = openssl.encrypt("DES", key1, nil, challenge) .. openssl.encrypt("DES", key2, nil, challenge) .. openssl.encrypt("DES", key3, nil, challenge) return true, result end ---Create the NTLM response to send back to the server. -- -- This is actually done the exact same way as the Lanman hash, -- so I call the <code>Lanman</code> function. -- --@param ntlm The NTLMv1 hash --@param challenge The server's challenge. --@return true on success, or false on error --@return The client challenge response, or an error message function ntlm_create_response(ntlm, challenge) if(have_ssl ~= true) then return false, "SMB: OpenSSL not present" end return lm_create_response(ntlm, challenge) end ---Create the NTLM mac key, which is used for message signing. -- -- For basic authentication, this is the md4 of the NTLM hash, concatenated -- with the response hash; for extended authentication, this is just the md4 of -- the NTLM hash. -- --@param ntlm_hash The NTLM hash. --@param ntlm_response The NTLM response. --@param is_extended Should be set if extended security negotiations are being used. --@return The NTLM mac key function ntlm_create_mac_key(ntlm_hash, ntlm_response, is_extended) if(have_ssl ~= true) then return false, "SMB: OpenSSL not present" end if(is_extended) then return openssl.md4(ntlm_hash) else return openssl.md4(ntlm_hash) .. ntlm_response end end ---Create the LM mac key, which is used for message signing. -- -- For basic authentication, it's the first 8 bytes of the lanman hash, -- followed by 8 null bytes, followed by the lanman response; for extended -- authentication, this is just the first 8 bytes of the lanman hash followed -- by 8 null bytes. -- --@param lm_hash The LM hash. --@param lm_response The LM response. --@param is_extended Should be set if extended security negotiations are being used. --@return The LM mac key function lm_create_mac_key(lm_hash, lm_response, is_extended) if(have_ssl ~= true) then return false, "SMB: OpenSSL not present" end if(is_extended) then return string.sub(lm_hash, 1, 8) .. string.rep('\0', 8) else return string.sub(lm_hash, 1, 8) .. string.rep('\0', 8) .. lm_response end end ---Create the NTLMv2 hash. -- -- The NTLMv2 hash is based on the NTLMv1 hash (for easy upgrading), the -- username, and the domain. Essentially, the NTLM hash is used as a HMAC-MD5 -- key, which is used to hash the unicode domain concatenated with the unicode -- username. -- --@param ntlm The NTLMv1 hash. --@param username The username we're using. --@param domain The domain. --@return true on success, or false on error --@return The NTLMv2 hash or an error message function ntlmv2_create_hash(ntlm, username, domain) if(have_ssl ~= true) then return false, "SMB: OpenSSL not present" end local unicode = "" username = unicode.utf8to16(string.upper(username)) domain = unicode.utf8to16(string.upper(domain)) return true, openssl.hmac("MD5", ntlm, username .. domain) end ---Create the LMv2 response, which can be sent back to the server. -- -- This is identical to the <code>NTLMv2</code> function, -- except that it uses an 8-byte client challenge. -- -- The reason for LMv2 is a long and twisted story. Well, not really. The -- reason is basically that the v1 hashes are always 24-bytes, and some servers -- expect 24 bytes, but the NTLMv2 hash is more than 24 bytes. So, the only way -- to keep pass-through compatibility was to have a v2-hash that was guaranteed -- to be 24 bytes. So LMv2 was born -- it has a 16-byte hash followed by the -- 8-byte client challenge, for a total of 24 bytes. And now you've learned -- something -- --@param ntlm The NVLMv1 hash. --@param username The username we're using. --@param domain The domain. --@param challenge The server challenge. --@return true on success, or false on error --@return The LMv2 response, or an error message function lmv2_create_response(ntlm, username, domain, challenge) if(have_ssl ~= true) then return false, "SMB: OpenSSL not present" end return ntlmv2_create_response(ntlm, username, domain, challenge, 8) end ---Create the NTLMv2 response, which can be sent back to the server. -- -- This is done by using the HMAC-MD5 algorithm with the NTLMv2 hash as a key, -- and the server challenge concatenated with the client challenge for the -- data. The resulting hash is concatenated with the client challenge and -- returned. -- -- The "proper" implementation for this uses a certain structure for the client -- challenge, involving the time and computer name and stuff (if you don't do -- this, Wireshark tells you it's a malformed packet). In my tests, however, I -- couldn't get Vista to recognize a client challenge longer than 24 bytes, and -- this structure was guaranteed to be much longer than 24 bytes. So, I just -- use a random string generated by OpenSSL. I've tested it on every Windows -- system from Windows 2000 to Windows Vista, and it has always worked. -- --@param ntlm The NVLMv1 hash. --@param username The username we're using. --@param domain The domain. --@param challenge The server challenge. --@param client_challenge_length number of random bytes of client challenge to use --@return true on success, or false on error --@return The NTLMv2 response, or an error message function ntlmv2_create_response(ntlm, username, domain, challenge, client_challenge_length) if(have_ssl ~= true) then return false, "SMB: OpenSSL not present" end local client_challenge = openssl.rand_bytes(client_challenge_length) local status, ntlmv2_hash = ntlmv2_create_hash(ntlm, username, domain) return true, openssl.hmac("MD5", ntlmv2_hash, challenge .. client_challenge) .. client_challenge end ---Generate the Lanman and NTLM password hashes. -- -- The password itself is taken from the function parameters, the script -- arguments, and the registry (in that order). If no password is set, then the -- password hash is used (which is read from all the usual places). If neither -- is set, then a blank password is used. -- -- The output passwords are hashed based on the hash type. -- --@param ip The ip address of the host, used for registry lookups. --@param username The username, which is used for v2 passwords. --@param domain The username, which is used for v2 passwords. --@param password [optional] The overriding password. --@param password_hash [optional] The overriding password hash. Shouldn't be -- set if password is set. --@param challenge The server challenge. --@param hash_type The way in which to hash the password. --@param is_extended Set to 'true' if extended security negotiations are being -- used (this has to be known for the message-signing key to -- be generated properly). --@return lm_response, to be send directly back to the server --@return ntlm_response, to be send directly back to the server --@reutrn mac_key used for message signing. function get_password_response(ip, username, domain, password, password_hash, hash_type, challenge, is_extended) local status local lm_hash = nil local ntlm_hash = nil local mac_key = nil local lm_response, ntlm_response -- Check for a blank password if(password == nil and password_hash == nil) then stdnse.debug2("SMB: Couldn't find password or hash to use (assuming blank)") password = "" end -- The anonymous user requires a single 0-byte instead of a LANMAN hash (don't ask me why, but it doesn't work without) if(hash_type == 'none') then return '\0', '', nil end -- If we got a password, hash it if(password ~= nil) then status, lm_hash = lm_create_hash(password) status, ntlm_hash = ntlm_create_hash(password) else if(password_hash ~= nil) then if(string.find(password_hash, "^" .. string.rep("%x%x", 16) .. "$")) then stdnse.debug2("SMB: Found a 16-byte hex string") lm_hash = bin.pack("H", password_hash:sub(1, 32)) ntlm_hash = bin.pack("H", password_hash:sub(1, 32)) elseif(string.find(password_hash, "^" .. string.rep("%x%x", 32) .. "$")) then stdnse.debug2("SMB: Found a 32-byte hex string") lm_hash = bin.pack("H", password_hash:sub(1, 32)) ntlm_hash = bin.pack("H", password_hash:sub(33, 64)) elseif(string.find(password_hash, "^" .. string.rep("%x%x", 16) .. "." .. string.rep("%x%x", 16) .. "$")) then stdnse.debug2("SMB: Found two 16-byte hex strings") lm_hash = bin.pack("H", password_hash:sub(1, 32)) ntlm_hash = bin.pack("H", password_hash:sub(34, 65)) else stdnse.debug1("SMB: ERROR: Hash(es) provided in an invalid format (should be 32, 64, or 65 hex characters)") lm_hash = nil ntlm_hash = nil end end end -- At this point, we should have a good lm_hash and ntlm_hash if we're getting one if(lm_hash == nil or ntlm_hash == nil) then stdnse.debug2("SMB: Couldn't determine which password to use, using a blank one") return "", "" end -- Output what we've got so far stdnse.debug2("SMB: Lanman hash: %s", stdnse.tohex(lm_hash)) stdnse.debug2("SMB: NTLM hash: %s", stdnse.tohex(ntlm_hash)) -- Hash the password the way the user wants if(hash_type == "v1") then -- LM and NTLM are hashed with their respective algorithms stdnse.debug2("SMB: Creating v1 response") status, lm_response = lm_create_response(lm_hash, challenge) status, ntlm_response = ntlm_create_response(ntlm_hash, challenge) mac_key = ntlm_create_mac_key(ntlm_hash, ntlm_response, is_extended) elseif(hash_type == "lm") then -- LM is hashed with its algorithm, NTLM is blank stdnse.debug2("SMB: Creating LMv1 response") status, lm_response = lm_create_response(lm_hash, challenge) ntlm_response = "" mac_key = lm_create_mac_key(lm_hash, lm_response, is_extended) elseif(hash_type == "ntlm") then -- LM and NTLM both use the NTLM algorithm stdnse.debug2("SMB: Creating NTLMv1 response") status, lm_response = ntlm_create_response(ntlm_hash, challenge) status, ntlm_response = ntlm_create_response(ntlm_hash, challenge) mac_key = ntlm_create_mac_key(ntlm_hash, ntlm_response, is_extended) elseif(hash_type == "v2") then -- LM and NTLM are hashed with their respective v2 algorithms stdnse.debug2("SMB: Creating v2 response") status, lm_response = lmv2_create_response(ntlm_hash, username, domain, challenge) status, ntlm_response = ntlmv2_create_response(ntlm_hash, username, domain, challenge, 24) elseif(hash_type == "lmv2") then -- LM is hashed with its v2 algorithm, NTLM is blank stdnse.debug2("SMB: Creating LMv2 response") status, lm_response = lmv2_create_response(ntlm_hash, username, domain, challenge) ntlm_response = "" else -- Default to NTLMv1 if(hash_type ~= nil) then stdnse.debug1("SMB: Invalid login type specified ('%s'), using default (NTLM)", hash_type) else stdnse.debug1("SMB: No login type specified, using default (NTLM)") end status, lm_response = ntlm_create_response(ntlm_hash, challenge) status, ntlm_response = ntlm_create_response(ntlm_hash, challenge) end stdnse.debug2("SMB: Lanman response: %s", stdnse.tohex(lm_response)) stdnse.debug2("SMB: NTLM response: %s", stdnse.tohex(ntlm_response)) return lm_response, ntlm_response, mac_key end ---Generate an NTLMSSP security blob. --@param security_blob The server's security blob, or nil if this is the first -- message --@param ip The ip address of the host, used for registry lookups. --@param username The username, which is used for v2 passwords. --@param domain The username, which is used for v2 passwords. --@param password [optional] The overriding password. --@param password_hash [optional] The overriding password hash. Shouldn't be -- set if password is set. --@param hash_type The way in which to hash the password. --@param flags The NTLM flags as a number function get_security_blob(security_blob, ip, username, domain, password, password_hash, hash_type, flags) local pos = 1 local new_blob local flags = flags or 0x00008215 -- (NEGOTIATE_SIGN_ALWAYS | NEGOTIATE_NTLM | NEGOTIATE_SIGN | REQUEST_TARGET | NEGOTIATE_UNICODE) if(security_blob == nil) then -- If security_blob is nil, this is the initial packet new_blob = bin.pack("<zIILL", "NTLMSSP", -- Identifier NTLMSSP_NEGOTIATE, -- Type flags, -- Flags 0, -- Calling workstation domain 0 -- Calling workstation name ) return true, new_blob, "", "" else -- Parse the old security blob local pos, identifier, message_type, domain_length, domain_max, domain_offset, server_flags, challenge, reserved = bin.unpack("<LISSIIA8A8", security_blob, 1) local lanman, ntlm, mac_key = get_password_response(ip, username, domain, password, password_hash, hash_type, challenge, true) -- Convert the username and domain to unicode (TODO: Disable the unicode flag, evaluate if that'll work) local hostname = unicode.utf8to16("nmap") username = unicode.utf8to16(username) domain = (#username > 0 ) and unicode.utf8to16(domain) or "" ntlm = (#username > 0 ) and ntlm or "" lanman = (#username > 0 ) and lanman or '\0' local domain_offset = 0x40 local username_offset = domain_offset + #domain local hostname_offset = username_offset + #username local lanman_offset = hostname_offset + #hostname local ntlm_offset = lanman_offset + #lanman local sessionkey_offset = ntlm_offset + #ntlm new_blob = bin.pack("<zISSISSISSISSISSISSIIAAAAAA", "NTLMSSP", NTLMSSP_AUTH, #lanman, #lanman, lanman_offset, ( #ntlm > 0 and #ntlm - 16 or 0 ), ( #ntlm > 0 and #ntlm - 16 or 0 ), ntlm_offset, #domain, #domain, domain_offset, #username, #username, username_offset, #hostname, #hostname, hostname_offset, #session_key, #session_key, sessionkey_offset, flags, domain, username, hostname, lanman, ntlm, session_key) return true, new_blob, mac_key end end --- -- Host information for NTLM security -- @class table -- @name host_info -- @field target_realm Target Name Data -- @field netbios_computer_name Server name -- @field netbios_domain_name Domain name -- @field fqdn DNS server name -- @field dns_domain_name DNS domain name -- @field dns_forest_name DNS tree name -- @field timestamp Timestamp --- -- Gets host info from a security blob -- @param security_blob The NTLM security blob -- @return A host_info table containing the data in the blob. -- @see host_info function get_host_info_from_security_blob(security_blob) local ntlm_challenge = {} --local pos, identifier, message_type, domain_length, domain_max, domain_offset, server_flags, challenge, reserved, target_info_length, target_info_max, target_info_offset = bin.unpack("<A8ISSIILLSSI", security_blob) local pos, identifier, message_type, domain_length, domain_max, domain_offset, server_flags, challenge, reserved, target_info_length, target_info_max, target_info_offset = bin.unpack("<A8ISSIILLSSI", security_blob) -- Do some validation on the NTLMSSP message if ( identifier ~= "NTLMSSP\0" ) then stdnse.debug1("SMB: Invalid NTLM challenge message: unexpected signature." ) return false, "Invalid NTLM challenge message" -- Per MS-NLMP, this field must be 2 for an NTLM challenge message elseif ( message_type ~= 0x2 ) then stdnse.debug1("SMB: Invalid NTLM challenge message: unexpected message type: %d.", message_type ) return false, "Invalid message type in NTLM challenge message" end -- Parse the TargetName data (i.e. the server authentication realm) if ( domain_length > 0 ) then local length = domain_length local pos = domain_offset + 1 -- +1 to convert to Lua's 1-based indexes local target_realm pos, target_realm = bin.unpack( string.format( "A%d", length ), security_blob, pos ) ntlm_challenge[ "target_realm" ] = unicode.utf16to8( target_realm ) end -- Parse the TargetInfo data (Wireshark calls this the "Address List") if ( target_info_length > 0 ) then -- Definition of AvId values (IDs for AV_PAIR (attribute-value pair) structures), -- as defined by the NTLM Authentication Protocol specification [MS-NLMP]. local NTLM_AV_ID_VALUES = { MsvAvEOL = 0x0, MsvAvNbComputerName = 0x1, MsvAvNbDomainName = 0x2, MsvAvDnsComputerName = 0x3, MsvAvDnsDomainName = 0x4, MsvAvDnsTreeName = 0x5, MsvAvFlags = 0x6, MsvAvTimestamp = 0x7, MsvAvRestrictions = 0x8, MsvAvTargetName = 0x9, MsvAvChannelBindings = 0xA, } -- Friendlier names for AvId values, to be used as keys in the results table -- e.g. ntlm_challenge[ "dns_computer_name" ] -> "host.test.local" local NTLM_AV_ID_NAMES = { [NTLM_AV_ID_VALUES.MsvAvNbComputerName] = "netbios_computer_name", [NTLM_AV_ID_VALUES.MsvAvNbDomainName] = "netbios_domain_name", [NTLM_AV_ID_VALUES.MsvAvDnsComputerName] = "fqdn", [NTLM_AV_ID_VALUES.MsvAvDnsDomainName] = "dns_domain_name", [NTLM_AV_ID_VALUES.MsvAvDnsTreeName] = "dns_forest_name", [NTLM_AV_ID_VALUES.MsvAvTimestamp] = "timestamp", } local length = target_info_length local pos = target_info_offset + 1 -- +1 to convert to Lua's 1-based indexes local target_info pos, target_info = bin.unpack( string.format( "A%d", length ), security_blob, pos ) pos = 1 -- reset pos to 1, since we'll be working out of just the target_info repeat local value, av_id, av_len pos, av_id, av_len = bin.unpack( "<SS", target_info, pos ) pos, value = bin.unpack( string.format( "A%d", av_len ), target_info, pos ) local friendly_name = NTLM_AV_ID_NAMES[ av_id ] if ( av_id == NTLM_AV_ID_VALUES.MsvAvEOL ) then break elseif ( av_id == NTLM_AV_ID_VALUES.MsvAvTimestamp ) then -- this is a FILETIME value (see [MS-DTYP]), representing the time in 100-ns increments since 1/1/1601 ntlm_challenge[ friendly_name ] = bin.unpack( "<L", value ) elseif ( friendly_name ) then ntlm_challenge[ friendly_name ] = unicode.utf16to8( value ) end until ( pos >= #target_info ) end return ntlm_challenge end ---Create an 8-byte message signature that's sent with all SMB packets. -- --@param mac_key The key used for authentication. It's the concatenation of the -- session key and the response hash. --@param data The packet to generate the signature for. This should be the -- packet that's about to be sent, except with the signature slot -- replaced with the sequence number. --@return The 8-byte signature. The signature is equal to the first eight bytes -- of md5(mac_key .. smb_data) function calculate_signature(mac_key, data) if(have_ssl) then return string.sub(openssl.md5(mac_key .. data), 1, 8) else return string.rep('\0', 8) end end if not unittest.testing() then return _ENV end test_suite = unittest.TestSuite:new() test_suite:add_test(unittest.equal( stdnse.tohex(select(-1, lm_create_hash("passphrase"))), "855c3697d9979e78ac404c4ba2c66533" ), "lm_create_hash" ) test_suite:add_test(unittest.equal( stdnse.tohex(select(-1, ntlm_create_hash("passphrase"))), "7f8fe03093cc84b267b109625f6bbf4b" ), "ntlm_create_hash" ) test_suite:add_test(unittest.equal( stdnse.tohex(select(-1, lm_create_hash("ÅÇÅÇ"))), "1830f5732b438091aad3b435b51404ee" ), "lm_create_hash" ) test_suite:add_test(unittest.equal( stdnse.tohex(select(-1, ntlm_create_hash("öäü"))), "4848bcb81cf018c3b70ea1479bd1374d" ), "ntlm_create_hash" ) return _ENV;
local function onevent(ev, ...) local vv, r if stead.api_atleast(1, 6, 3) then vv, r = stead.call(game, ev, ...); if r == false then return vv, false end if vv == false then return nil, false end return vv end end local go = function (self, where, back, noenter, noexit, nodsc) local was = self.where; local need_scene = false; local ret if not stead.in_walk_call then ret = function(rc) stead.in_walk_call = false return nil end else ret = function(rc) return rc end end stead.in_walk_call = true if where == nil then return nil, ret(false) end if not isRoom(stead.ref(where)) then error ("Trying to go nowhere: "..where); end if not isRoom(stead.ref(self.where)) then error ("Trying to go from nowhere: "..self.where); end if stead.in_entered_call or stead.in_onexit_call then error ("Do not use walk from left/entered action! Use exit/enter action instead:" .. self.where); end local v, r, jump; if not isVroom(stead.ref(where)) and not stead.in_exit_call and not noexit then stead.in_exit_call = true -- to break recurse v,r = stead.call(stead.ref(self.where), 'exit', stead.ref(where)); stead.in_exit_call = nil if r == false or (stead.api_atleast(1, 3, 0) and v == false and r == nil) then return v, ret(r) end if stead.api_atleast(2, 4, 0) then jump = stead.rawget(_G, 'PLAYER_MOVED') else jump = (self.where ~= was) end if jump then where = stead.deref(self.where) -- jump end end local res = v; v = nil; if not isVroom(stead.ref(where)) then self.where = stead.deref(where); end if not jump and not noenter then v, r = stead.call(stead.ref(where), 'enter', stead.ref(was)); if r == false or (stead.api_atleast(1, 3, 0) and v == false and r == nil) then self.where = was; return stead.par(stead.scene_delim, res, v), ret(r) end end if stead.api_atleast(2, 4, 0) then need_scene = not stead.rawget(_G, 'PLAYER_MOVED'); else need_scene = not (stead.ref(where) ~= stead.ref(self.where)) end res = stead.par(stead.scene_delim, res, v); if not back then stead.ref(where).__from__ = stead.deref(was); end ret() stead.rawset(_G, 'PLAYER_MOVED', true) if need_scene and not nodsc then stead.need_scene() end if not stead.in_walk_call then local to = self.where if not noexit then self.where = was stead.in_onexit_call = true v = stead.call(stead.ref(was), 'left', stead.ref(to)); stead.in_onexit_call = false res = stead.par(stead.scene_delim, res, v); end self.where = stead.deref(to) if not noenter then stead.in_entered_call = true v = stead.call(stead.ref(to), 'entered', stead.ref(was)); stead.in_entered_call = false res = stead.par(stead.scene_delim, res, v); end if stead.tonum(stead.ref(to).__visited) then stead.ref(to).__visited = stead.ref(to).__visited + 1; elseif stead.here().__visited == nil then stead.ref(to).__visited = 1 end if not stead.api_atleast(1, 6, 3) and isDialog(stead.ref(to)) then stead.dialog_rescan(stead.ref(to)) end end return res; end stead.player_go = function(self, where) -- cmd iface local w = stead.ref(self.where).way:srch(where); if not w then return nil,false end return self:walk(w); end stead.player_walk = function(self, where, ...) -- real work local v, r, vv; vv, r = onevent('onwalk', stead.ref(where), ...); if vv == false then return end if r == false then return vv end v, r = stead.go(self, where, ...); if stead.type(vv) == 'string' then v = stead.par(stead.space_delim, vv, v); end return v, r; end stead.player_back = function(self) -- deprecated error ("Do not use stead.me():back(). It's deprecated.", 2) end stead.back = function(w) if isDialog(stead.here()) and not isDialog(stead.from()) then return stead.walkout(w); end return stead.walkback(w); end back = stead.back stead.walkback = function(w) if isRoom(stead.ref(w)) then return stead.me():walk(w, true); end return stead.me():walk(stead.from(), true); end walkback = stead.walkback stead.walk = function(what, back, noenter, noexit, nodsc, ...) return stead.me():walk(what, back, noenter, noexit, nodsc, ...); end walk = stead.walk stead.walkin = function(what) return stead.me():walk(what, false, false, true); end walkin = stead.walkin stead.walkout = function(what) if isRoom(stead.ref(what)) then return stead.me():walk(what, true, true, false, true); end return stead.me():walk(stead.from(), true, true, false, true); end walkout = stead.walkout function visited(w) if not w then w = stead.here() end w = stead.ref(w) if w == nil then return nil; end if not isRoom(w) then error ("Wrong parameter to visited.", 2); end return w.__visited end stead.visited = visited function visits(w) local n = stead.visited(w) if not n then n = 0 end return n end stead.visits = visits iface.fmt = function(self, cmd, st, moved, r, av, objs, pv) -- st -- changed state (main win), move -- loc changed local l, vv if st then av = txtem(av); pv = txtem(pv); -- if not PLAYER_MOVED then r = txtem(r) -- end if isForcedsc(stead.here()) or stead.rawget(_G, 'NEED_SCENE') then l = stead.here():scene(); end end if moved then vv = stead.fmt(stead.cat(stead.par(stead.scene_delim, r, l, av, objs, pv), '^')); else vv = stead.fmt(stead.cat(stead.par(stead.scene_delim, l, r, av, objs, pv), '^')); end return vv end stead.go = function(...) local r,v = go(...) if stead.type(r) == 'string' and stead.cctx() then stead.pr (r) end -- if stead.in_life_call then -- ACTION_TEXT = nil -- end if r == nil and v == nil then if stead.cctx() then stead.cctx().action = true else r = true end end return r,v end iface.cmd = stead.hook(iface.cmd, function(f, ...) stead.rawset(_G, 'NEED_SCENE', nil) return f(...) end) player = stead.inherit(player, function(v) v.look = function(s) if not stead.started then game:start() end if game._time == 0 then return stead.walk(stead.here(), false, false, true); end stead.need_scene() if stead.api_atleast(1, 3, 5) then return true -- force action end end return v end) pl = player(pl) -- reinit -- vim:ts=4
require("plugins.nvim-tree") require("plugins.nvim-lspconfig") require("plugins.nvim-lightbulb") require("plugins.nvim-cmp") require("plugins.nvim-lspconfig") require("plugins.nvim-dap") require("plugins.nvim-dap-ui") require("plugins.nvim-tree") require("plugins.nvim-tmux-navigation") require("plugins.gitsigns") require("plugins.lualine") require("plugins.neoformat") require("plugins.lspkind") require("plugins.treesitter") require("nvim-autopairs").setup() require("trouble").setup() require("lsp_signature").setup()
-- It works only if x is even and y > 2. local brain = function (x, y, snake, food, synaptic_vesicle) local body = snake.get_body() local head = body[1] if synaptic_vesicle.neurotransmmitter == nil then synaptic_vesicle.neurotransmmitter = "left" end if synaptic_vesicle.neurotransmmitter == "left" then if head.x == 0 then synaptic_vesicle.neurotransmmitter = "up" snake.set_direction("up") end elseif synaptic_vesicle.neurotransmmitter == "up" then if head.y == 0 then synaptic_vesicle.neurotransmmitter = "right1" snake.set_direction("right") end elseif synaptic_vesicle.neurotransmmitter == "right1" then synaptic_vesicle.neurotransmmitter = "down" snake.set_direction("down") elseif synaptic_vesicle.neurotransmmitter == "right2" then synaptic_vesicle.neurotransmmitter = "up" snake.set_direction("up") elseif synaptic_vesicle.neurotransmmitter == "down" then if head.x ~= x - 1 and head.y == y - 2 then synaptic_vesicle.neurotransmmitter = "right2" snake.set_direction("right") elseif head.x == x - 1 and head.y == y - 1 then synaptic_vesicle.neurotransmmitter = "left" snake.set_direction("left") end end return synaptic_vesicle end return brain
local x, y = ... if editor then x = editor.x y = editor.y end return entity(1) { ["droptune.components.render.Sprite"] = { ["resource"] = "test.Textures.love-logo", }, ["droptune.components.Position"] = { ["x"] = x, ["y"] = y, ["rot"] = 0, }, }
--- --- Generated by EmmyLua(https://github.com/EmmyLua) --- Created by wakfu. --- DateTime: 2020/8/4 17:58 --- local example = {} -- local json = require('module_tools.json') local Http = require('module_http.module_http') function example.get() local request = Http.new() local code, response = request:get("https://www.wanandroid.com/hotkey/json") :send({ name = "sss" }) :query({ name = "nihao" }) :End() if code == 0 then local ok, result = pcall(json.decode, response) return ok and 0 or -1, result else return code, response end end function example.post() local request = Http.new() local code, response = request:post("http://0.0.0.0:8080/api/invoice/order") :type("form") :send({ platforms = 2, account = "13000000000" }) :set({ Session = "111" }) :End() if code == 0 then local ok, result = pcall(json.decode, response) return ok and 0 or -1, result else return code, response end end return example
----------------------------------- -- Ability: Third Eye -- Anticipates and dodges the next attack directed at you. -- Obtained: Samurai Level 15 -- Recast Time: 1:00 -- Duration: 0:30 ----------------------------------- require("scripts/globals/settings") require("scripts/globals/status") ----------------------------------- function onAbilityCheck(player, target, ability) if (player:hasStatusEffect(tpz.effect.SEIGAN)) then ability:setRecast(ability:getRecast()/2) end return 0, 0 end function onUseAbility(player, target, ability) player:addStatusEffect(tpz.effect.THIRD_EYE, 0, 0, 30) --power keeps track of procs end
return { summary = 'Clear the event queue.', description = 'Clears the event queue, removing any unprocessed events.', arguments = {}, returns = {} }
AddCSLuaFile("shared.lua") include("shared.lua") function ENT:Initialize() self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetCollisionGroup(COLLISION_GROUP_WORLD) local PhysObj = self:GetPhysicsObject() if IsValid(PhysObj) then PhysObj:Wake() end timer.Simple(30, function() if IsValid(self) then self:Remove() end end) end
--MADE BY X9n (NOT THE SCRIPT) REGULAR SCRIPT: Go down to line 4 and put your name where it says "YOUR NAME HERE" and replace anything you want your name to be in line 4 where it says "YOUR NEW NAME HERE" local You = "Killbook" local head = workspace[You].Head:Clone() local model = Instance.new("Model",workspace) local humanoid = Instance.new("Humanoid",model) head.Parent = model model.Name = You.." YOUR NEW NAME HERE" humanoid.MaxHealth = 0 local w = Instance.new("Weld",model) w.Part0,w.Part1 = workspace[You].Head,head
-- The Computer Language Benchmarks Game -- http://benchmarksgame.alioth.debian.org/ -- contributed by Mike Pall -- requires LGMP "A GMP package for Lua 5.1" -- with matrix optimization, courtesy of Wim Couwenberg local g, aux = {}, {} require "c-gmp"(g, aux) local add, mul, div = g.mpz_add, g.mpz_mul_si, g.mpz_tdiv_q local init, get = g.mpz_init_set_d, g.mpz_get_d local u, v, w local function produce(n1, n2, d, k) mul(n1, 2 * k - 1, u) add(n2, n2, v) mul(n1, k - 1, w) add(u, v, n1) mul(n2, k + 2, u) add(w, u, n2) mul(d, 2 * k + 1, d) end local function extract(n1, n2, d, y) mul(d, -10 * y, u) mul(n1, 10, n1) add(n1, u, n1) mul(n2, 10, n2) add(n2, u, n2) end local function digit(n1, n2, d) local y = get(div(n1, d, u)) if y == get(div(n2, d, v)) then return y end end -- Generate successive digits of PI. local function pidigits(N) local write = io.write local k = 1 local n1, n2, d = init(4), init(3), init(1) u, v, w = init(0), init(0), init(0) local i = 0 while i < N do local y = digit(n1, n2, d) if y then write(y) i = i + 1; if i % 10 == 0 then write("\t:", i, "\n") end extract(n1, n2, d, y) else produce(n1, n2, d, k) k = k + 1 end end if i % 10 ~= 0 then write(string.rep(" ", 10 - N % 10), "\t:", N, "\n") end end local N = tonumber(arg and arg[1]) or 27 pidigits(N)
--[[ ORIGINAL CODE https://github.com/DevTestingPizza/vSync REVAMPED BY Kalinka https://github.com/KalinkaGit/vSyncR ]]-- CurrentWeather = Config.StartWeather local baseTime = Config.BaseTime local timeOffset = Config.TimeOffset local freezeTime = Config.FreezeTime local blackout = Config.Blackout local newWeatherTimer = Config.NewWeatherTimer RegisterServerEvent('vSync:requestSync') AddEventHandler('vSync:requestSync', function() TriggerClientEvent('vSync:updateWeather', -1, CurrentWeather, blackout) TriggerClientEvent('vSync:updateTime', -1, baseTime, timeOffset, freezeTime) end) function isAllowedToChange(player) if Config.AdminById then for k, v in ipairs(Config.Admins) do for k2, v2 in ipairs(GetPlayerIdentifiers(player)) do if string.lower(v2) == string.lower(v) then return true end end end else for k, v in ipairs(Config.Ace) do if IsPlayerAceAllowed(player, v) then return true end end end return false end RegisterCommand('freezetime', function(source, args) if source ~= 0 then if isAllowedToChange(source) then freezeTime = not freezeTime if freezeTime then TriggerClientEvent('vSync:notify', source, _U('time_frozenc')) else TriggerClientEvent('vSync:notify', source, _U('time_unfrozenc')) end else TriggerClientEvent('chatMessage', source, '', {255,255,255}, _U('not_allowed')) end else freezeTime = not freezeTime if freezeTime then print(_U('time_now_frozen')) else print(_U('time_now_unfrozen')) end end end) RegisterCommand('freezeweather', function(source, args) if source ~= 0 then if isAllowedToChange(source) then Config.DynamicWeather = not Config.DynamicWeather if not Config.DynamicWeather then TriggerClientEvent('vSync:notify', source, _U('dynamic_weather_disabled')) else TriggerClientEvent('vSync:notify', source, _U('dynamic_weather_enabled')) end else TriggerClientEvent('chatMessage', source, '', {255,255,255}, _U('not_allowed')) end else Config.DynamicWeather = not Config.DynamicWeather if not Config.DynamicWeather then print(_U('weather_now_frozen')) else print(_U('weather_now_unfrozen')) end end end) RegisterCommand('weather', function(source, args) if source == 0 then local validWeatherType = false if args[1] == nil then print(_U('weather_invalid_syntax')) return else for i,wtype in ipairs(Config.AvailableWeatherTypes) do if wtype == string.upper(args[1]) then validWeatherType = true end end if validWeatherType then print(_U('weather_updated')) CurrentWeather = string.upper(args[1]) newWeatherTimer = 10 TriggerEvent('vSync:requestSync') else print(_U('weather_invalid')) end end else if isAllowedToChange(source) then local validWeatherType = false if args[1] == nil then TriggerClientEvent('chatMessage', source, '', {255,255,255}, _U('weather_invalid_syntaxc')) else for i,wtype in ipairs(Config.AvailableWeatherTypes) do if wtype == string.upper(args[1]) then validWeatherType = true end end if validWeatherType then TriggerClientEvent('vSync:notify', source, _U('weather_willchangeto', string.lower(args[1]))) CurrentWeather = string.upper(args[1]) newWeatherTimer = 10 TriggerEvent('vSync:requestSync') else TriggerClientEvent('chatMessage', source, '', {255,255,255}, _U('weather_invalidc')) end end else TriggerClientEvent('chatMessage', source, '', {255,255,255}, _U('not_access')) print(_U('weather_accessdenied')) end end end, false) RegisterCommand('blackout', function(source) if source == 0 then blackout = not blackout if blackout then print(_U('blackout_enabled')) else print(_U('blackout_disabled')) end else if isAllowedToChange(source) then blackout = not blackout if blackout then TriggerClientEvent('vSync:notify', source, _U('blackout_enabledc')) else TriggerClientEvent('vSync:notify', source, _U('blackout_disabledc')) end TriggerEvent('vSync:requestSync') end end end) RegisterCommand('morning', function(source) if source == 0 then print(_U('time_console')) return end if isAllowedToChange(source) then ShiftToMinute(0) ShiftToHour(9) TriggerClientEvent('vSync:notify', source, _U('time_morning')) TriggerEvent('vSync:requestSync') end end) RegisterCommand('noon', function(source) if source == 0 then print(_U('time_console')) return end if isAllowedToChange(source) then ShiftToMinute(0) ShiftToHour(12) TriggerClientEvent('vSync:notify', source, _U('time_noon')) TriggerEvent('vSync:requestSync') end end) RegisterCommand('evening', function(source) if source == 0 then print(_U('time_console')) return end if isAllowedToChange(source) then ShiftToMinute(0) ShiftToHour(18) TriggerClientEvent('vSync:notify', source, _U('time_evening')) TriggerEvent('vSync:requestSync') end end) RegisterCommand('night', function(source) if source == 0 then print(_U('time_console')) return end if isAllowedToChange(source) then ShiftToMinute(0) ShiftToHour(23) TriggerClientEvent('vSync:notify', source, _U('time_night')) TriggerEvent('vSync:requestSync') end end) function ShiftToMinute(minute) timeOffset = timeOffset - ( ( (baseTime+timeOffset) % 60 ) - minute ) end function ShiftToHour(hour) timeOffset = timeOffset - ( ( ((baseTime+timeOffset)/60) % 24 ) - hour ) * 60 end RegisterCommand('time', function(source, args, rawCommand) if source == 0 then if tonumber(args[1]) ~= nil and tonumber(args[2]) ~= nil then local argh = tonumber(args[1]) local argm = tonumber(args[2]) if argh < 24 then ShiftToHour(argh) else ShiftToHour(0) end if argm < 60 then ShiftToMinute(argm) else ShiftToMinute(0) end print(_U('time_change', argh, argm)) TriggerEvent('vSync:requestSync') else print(_U('time_invalid')) end elseif source ~= 0 then if isAllowedToChange(source) then if tonumber(args[1]) ~= nil and tonumber(args[2]) ~= nil then local argh = tonumber(args[1]) local argm = tonumber(args[2]) if argh < 24 then ShiftToHour(argh) else ShiftToHour(0) end if argm < 60 then ShiftToMinute(argm) else ShiftToMinute(0) end local newtime = math.floor(((baseTime+timeOffset)/60)%24) .. ":" local minute = math.floor((baseTime+timeOffset)%60) if minute < 10 then newtime = newtime .. "0" .. minute else newtime = newtime .. minute end TriggerClientEvent('vSync:notify', source, _U('time_changec', newtime)) TriggerEvent('vSync:requestSync') else TriggerClientEvent('chatMessage', source, '', {255,255,255}, _U('time_invalid')) end else TriggerClientEvent('chatMessage', source, '', {255,255,255}, _U('not_access')) print(_U('time_access')) end end end) Citizen.CreateThread(function() while true do Citizen.Wait(0) local newBaseTime = os.time(os.date("!*t"))/2 + 360 if freezeTime then timeOffset = timeOffset + baseTime - newBaseTime end baseTime = newBaseTime end end) Citizen.CreateThread(function() while true do Citizen.Wait(5000) TriggerClientEvent('vSync:updateTime', -1, baseTime, timeOffset, freezeTime) end end) Citizen.CreateThread(function() while true do Citizen.Wait(300000) TriggerClientEvent('vSync:updateWeather', -1, CurrentWeather, blackout) end end) Citizen.CreateThread(function() while true do newWeatherTimer = newWeatherTimer - 1 Citizen.Wait(60000) if newWeatherTimer == 0 then if Config.DynamicWeather then NextWeatherStage() end newWeatherTimer = 10 end end end) function NextWeatherStage() if CurrentWeather == "CLEAR" or CurrentWeather == "CLOUDS" or CurrentWeather == "EXTRASUNNY" then local new = math.random(1,2) if new == 1 then CurrentWeather = "CLEARING" else CurrentWeather = "OVERCAST" end elseif CurrentWeather == "CLEARING" or CurrentWeather == "OVERCAST" then local new = math.random(1,6) if new == 1 then if CurrentWeather == "CLEARING" then CurrentWeather = "FOGGY" else CurrentWeather = "RAIN" end elseif new == 2 then CurrentWeather = "CLOUDS" elseif new == 3 then CurrentWeather = "CLEAR" elseif new == 4 then CurrentWeather = "EXTRASUNNY" elseif new == 5 then CurrentWeather = "SMOG" else CurrentWeather = "FOGGY" end elseif CurrentWeather == "THUNDER" or CurrentWeather == "RAIN" then CurrentWeather = "CLEARING" elseif CurrentWeather == "SMOG" or CurrentWeather == "FOGGY" then CurrentWeather = "CLEAR" end TriggerEvent("vSync:requestSync") end print("vSync Revamped by Kalinka loaded!")
local Spell = { } Spell.LearnTime = 360 Spell.ApplyFireDelay = 0.4 Spell.Category = HpwRewrite.CategoryNames.Healing Spell.OnlyIfLearned = { "Episkey" } Spell.Description = [[ For maximum effect of the spell, the incantation had to be repeated thrice; firstly slowing the flow of blood to prevent death by exsanguination; the second to clear residue and begin to heal the wounds; and the third to fully knit the wounds, although dittany had to be applied to prevent scarring. This is counter-spell to Sectumsempra - twice casted it will stop bleeding. Hold self-cast key to heal yourself. ]] Spell.NodeOffset = Vector(-624, 446, 0) Spell.AccuracyDecreaseVal = 0.2 if SERVER then util.AddNetworkString("hpwrewrite_VulneraSD") else -- It seems like RemoveAllDecals does nothing on serverside net.Receive("hpwrewrite_VulneraSD", function() local ply = net.ReadEntity() if ply:IsValid() then ply:RemoveAllDecals() end end) end function Spell:OnFire(wand) local ent = wand:HPWGetAimEntity(300) if IsValid(ent) and (ent:IsPlayer() or ent:IsNPC()) then if not self.Victims[ent] then self.Victims[ent] = 0 end self.Victims[ent] = self.Victims[ent] + 1 if self.Victims[ent] > 3 then self.Victims[ent] = 1 end local name = "hpwrewrite_vulnerasanentur_handler" .. ent:EntIndex() if self.Victims[ent] == 1 then timer.Create(name, 0.4, 10, function() if ent:IsValid() then ent:SetHealth(math.min(ent:GetMaxHealth(), ent:Health() + 1)) end end) elseif self.Victims[ent] == 2 then -- Counter shit to sectumsempra hook.Remove("Think", "hpwrewrite_sectum_handler" .. ent:EntIndex()) timer.Create(name, 0.3, 10, function() if ent:IsValid() then ent:SetHealth(math.min(ent:GetMaxHealth(), ent:Health() + 2)) net.Start("hpwrewrite_VulneraSD") net.WriteEntity(ent) net.Broadcast() end end) elseif self.Victims[ent] == 3 then timer.Remove(name) ent:SetHealth(ent:GetMaxHealth()) net.Start("hpwrewrite_VulneraSD") net.WriteEntity(ent) net.Broadcast() end timer.Create("hpwrewrite_vulnerasanentur_handler2" .. ent:EntIndex(), 2, 1, function() self.Victims[ent] = 0 end) end sound.Play("npc/antlion/idle3.wav", wand:GetPos(), 55, math.random(240, 255)) end function Spell:OnSpellGiven(ply) if SERVER then self.Victims = { } end return true end HpwRewrite:AddSpell("Vulnera Sanentur", Spell)
if not modules then modules = { } end modules ['util-lua'] = { version = 1.001, comment = "companion to luat-lib.mkiv", author = "Hans Hagen, PRAGMA-ADE, Hasselt NL", comment = "the strip code is written by Peter Cawley", copyright = "PRAGMA ADE / ConTeXt Development Team", license = "see context related readme files" } -- we will remove the 5.1 code some day soon local rep, sub, byte, dump, format = string.rep, string.sub, string.byte, string.dump, string.format local load, loadfile, type, collectgarbage = load, loadfile, type, collectgarbage utilities = utilities or {} utilities.lua = utilities.lua or { } local luautilities = utilities.lua local report_lua = logs.reporter("system","lua") local report_mem = logs.reporter("system","lua memory") local tracestripping = false local tracememory = false luautilities.stripcode = true -- support stripping when asked for luautilities.alwaysstripcode = false -- saves 1 meg on 7 meg compressed format file (2012.08.12) luautilities.nofstrippedchunks = 0 luautilities.nofstrippedbytes = 0 local strippedchunks = { } -- allocate() luautilities.strippedchunks = strippedchunks if not LUATEXENGINE then --- probably mtxrun ... LUATEXENGINE = status.luatex_engine and string.lower(status.luatex_engine) JITSUPPORTED = LUATEXENGINE == "luajittex" or jit CONTEXTLMTXMODE = CONTEXTLMTXMODE or (LUATEXENGINE == "luametatex" and 1) or 0 end luautilities.suffixes = { tma = "tma", tmc = (CONTEXTLMTXMODE and CONTEXTLMTXMODE > 0 and "tmd") or (jit and "tmb") or "tmc", lua = "lua", luc = (CONTEXTLMTXMODE and CONTEXTLMTXMODE > 0 and "lud") or (jit and "lub") or "luc", lui = "lui", luv = "luv", luj = "luj", tua = "tua", -- tuc = "tuc", tuc = (CONTEXTLMTXMODE and CONTEXTLMTXMODE > 0 and "tud") or (jit and "tub") or "tuc", } -- environment.loadpreprocessedfile can be set to a preprocessor local function register(name) -- makes no sense runtime if tracestripping then report_lua("stripped bytecode from %a",name or "unknown") end strippedchunks[#strippedchunks+1] = name luautilities.nofstrippedchunks = luautilities.nofstrippedchunks + 1 end local function stupidcompile(luafile,lucfile,strip) local code = io.loaddata(luafile) if code and code ~= "" then code = load(code) if code then code = dump(code,strip and luautilities.stripcode or luautilities.alwaysstripcode) if code and code ~= "" then register(name) io.savedata(lucfile,code) return true, 0 end else report_lua("fatal error %a in file %a",1,luafile) end else report_lua("fatal error %a in file %a",2,luafile) end return false, 0 end -- quite subtle ... doing this wrong incidentally can give more bytes function luautilities.loadedluacode(fullname,forcestrip,name,macros) -- quite subtle ... doing this wrong incidentally can give more bytes name = name or fullname if macros then macros = lua.macros end local code, message if macros then code, message = macros.loaded(fullname,true,false) else code, message = loadfile(fullname) end if code then code() else report_lua("loading of file %a failed:\n\t%s",fullname,message or "no message") code, message = loadfile(fullname) end if forcestrip and luautilities.stripcode then if type(forcestrip) == "function" then forcestrip = forcestrip(fullname) end if forcestrip or luautilities.alwaysstripcode then register(name) return load(dump(code,true)), 0 else return code, 0 end elseif luautilities.alwaysstripcode then register(name) return load(dump(code,true)), 0 else return code, 0 end end function luautilities.strippedloadstring(code,name,forcestrip) -- not executed local code, message = load(code) if not code then report_lua("loading of file %a failed:\n\t%s",name,message or "no message") end if forcestrip and luautilities.stripcode or luautilities.alwaysstripcode then register(name) return load(dump(code,true)), 0 -- not yet executed else return code, 0 end end function luautilities.loadstring(code,name) -- not executed local code, message = load(code) if not code then report_lua("loading of file %a failed:\n\t%s",name,message or "no message") end return code, 0 end function luautilities.compile(luafile,lucfile,cleanup,strip,fallback) -- defaults: cleanup=false strip=true report_lua("compiling %a into %a",luafile,lucfile) os.remove(lucfile) local done = stupidcompile(luafile,lucfile,strip ~= false) if done then report_lua("dumping %a into %a stripped",luafile,lucfile) if cleanup == true and lfs.isfile(lucfile) and lfs.isfile(luafile) then report_lua("removing %a",luafile) os.remove(luafile) end end return done end function luautilities.loadstripped(...) local l = load(...) if l then return load(dump(l,true)) end end -- local getmetatable, type = getmetatable, type -- -- local types = { } -- -- function luautilities.registerdatatype(d,name) -- types[getmetatable(d)] = name -- end -- -- function luautilities.datatype(d) -- local t = type(d) -- if t == "userdata" then -- local m = getmetatable(d) -- return m and types[m] or "userdata" -- else -- return t -- end -- end -- -- luautilities.registerdatatype(lpeg.P("!"),"lpeg") -- -- print(luautilities.datatype(lpeg.P("oeps"))) -- These finalizers will only be invoked when we have a proper lua_close -- call (which is not happening in luatex tex node yes) or finish with an -- os.exit(n,true). local finalizers = { } setmetatable(finalizers, { __gc = function(t) for i=1,#t do pcall(t[i]) -- let's not crash end end } ) function luautilities.registerfinalizer(f) finalizers[#finalizers+1] = f end function luautilities.checkmemory(previous,threshold,trace) -- threshold in MB local current = collectgarbage("count") if previous then local checked = (threshold or 64)*1024 local delta = current - previous if current - previous > checked then collectgarbage("collect") local afterwards = collectgarbage("count") if trace or tracememory then report_mem("previous %r MB, current %r MB, delta %r MB, threshold %r MB, afterwards %r MB", previous/1024,current/1024,delta/1024,threshold,afterwards) end return afterwards elseif trace or tracememory then report_mem("previous %r MB, current %r MB, delta %r MB, threshold %r MB", previous/1024,current/1024,delta/1024,threshold) end end return current end
local EditorEntity = require("core.EditorEntity") local InputEvent = require("input.InputEvent") --------------------------------------------------------------------------------- -- -- @type CanvasTool -- --------------------------------------------------------------------------------- local CanvasTool = Class( EditorEntity, "CanvasTool" ) function CanvasTool:init() EditorEntity.init(self, {name="CanvasTool"}) self.items = {} end function CanvasTool:clear() end function CanvasTool:getCurrentView() return self.parent:getView() end function CanvasTool:updateCanvas() self:getCurrentView():updateCanvas() end --------------------------------------------------------------------------------- function CanvasTool:installInput( inputDevice ) assert( inputDevice ) self.inputDevice = inputDevice end function CanvasTool:getInput() return self.inputDevice end --------------------------------------------------------------------------------- function CanvasTool:addCanvasItem( item ) local view = self:getCurrentView() view:addCanvasItem( item ) self.items[ item ] = true item.tool = self return item end function CanvasTool:removeCanvasItem( item ) local view = self:getCurrentView() view:removeCanvasItem( item ) self.items[ item ] = nil item.tool = nil return item end --------------------------------------------------------------------------------- function CanvasTool:findTopLevelPropComponents( entities ) local found = {} if not entities then return false end for e in pairs( entities ) do local p = e.parent local isTop = true while p do if entities[ p ] then isTop = false break end p = p.parent end if isTop then if e.getProp then found[e] = true elseif e.findMethod then local com = e:findMethod( "getProp" ) -- this for component with prop if com then found[com] = true end end end end return found end --------------------------------------------------------------------------------- function CanvasTool:getSelection( key ) return getSelection( key or 'scene' ) end function CanvasTool:updateSelection() end --------------------------------------------------------------------------------- function CanvasTool:onSelectionChanged( selection ) self:updateSelection() end --------------------------------------------------------------------------------- return CanvasTool
-- pastebin run fUqJGjit shell.run("pastebin get wPtGKMam git.lua") shell.run("./git.lua VHirtz CC-mastermind / API") shell.run("mv CC-mastermind/API/startup.lua /startup.lua")
local OVALE, Ovale = ... local OvaleSigil = Ovale:NewModule("OvaleSigil", "AceEvent-3.0") Ovale.OvaleSigil = OvaleSigil local OvaleProfiler = Ovale.OvaleProfiler local OvalePaperDoll = nil local OvaleSpellBook = nil local OvaleState = nil local ipairs = ipairs local tinsert = table.insert local tremove = table.remove local API_GetTime = GetTime local activated_sigils = {} OvaleProfiler:RegisterProfiling(OvaleSigil) function OvaleSigil:OnInitialize() OvalePaperDoll = Ovale.OvalePaperDoll OvaleSpellBook = Ovale.OvaleSpellBook OvaleState = Ovale.OvaleState activated_sigils["flame"] = {} activated_sigils["silence"] = {} activated_sigils["misery"] = {} activated_sigils["chains"] = {} end function OvaleSigil:OnEnable() if Ovale.playerClass == "DEMONHUNTER" then self:RegisterEvent("UNIT_SPELLCAST_SUCCEEDED") OvaleState:RegisterState(self, self.statePrototype) end end function OvaleSigil:OnDisable() if Ovale.playerClass == "DEMONHUNTER" then OvaleState:UnregisterState(self) self:UnregisterEvent("UNIT_SPELLCAST_SUCCEEDED") end end local sigil_start = { [204596] = { type="flame"}, -- Sigil of flame [189111] = { type="flame", talent=8}, -- Infernal strike [202137] = { type="silence"}, -- Sigil of Silence [207684] = { type="misery"}, -- Sigil of Misery [202138] = { type="chains"}, -- Sigil of Chains } local sigil_end = { [204598] = { type="flame"}, [204490] = { type="silence"}, [207685] = { type="misery"}, [204834] = { type="chains"}, } local QUICKENED_SIGILS_TALENT = 15 function OvaleSigil:UNIT_SPELLCAST_SUCCEEDED(event, unitId, spellName, spellRank, guid, spellId, ...) if (not OvalePaperDoll:IsSpecialization("vengeance")) then return end if (unitId == nil or unitId ~= "player") then return end local id = tonumber(spellId) --print(event .. " " .. spellName .. " " .. id) -- queue all the sigils when they are cast if (sigil_start[id] ~= nil) then local s = sigil_start[id]; local t = s.type local tal = s.talent or nil; if (tal == nil or OvaleSpellBook:GetTalentPoints(tal) > 0) then if(OvaleSpellBook:GetTalentPoints(QUICKENED_SIGILS_TALENT) > 0) then tinsert(activated_sigils[t], API_GetTime()+2.5) else tinsert(activated_sigils[t], API_GetTime()+3.5) end end end -- unqueue all the sigils when they finished charging if(sigil_end[id] ~= nil) then local s = sigil_end[id]; local t = s.type tremove(activated_sigils[t], 1) end end OvaleSigil.statePrototype = {} local statePrototype = OvaleSigil.statePrototype statePrototype.IsSigilCharging = function(state, type, atTime) atTime = atTime or state.currentTime if(#activated_sigils[type] == 0) then return false end local charging = false for _,v in ipairs(activated_sigils[type]) do charging = charging or atTime < v end return charging end
local cfg = require("config").entity.toolman local core = require("core") local hexagon = require("hexagon") local buff = require("buff") local template = { health_cap = 1000, energy = 0, resistance = {}, } return function() local obj = core.new_character("entity.toolman", cfg.template, {{ name = "skill.toolman.attack", type = "effect", cooldown = 1, remain = 0, enable = true, cost = 0, update = core.skill_update, use = function(self) local entity = self.owner local area = hexagon.adjacent(entity.pos) entity.map:damage(entity, area, { ratio = 1, element = "physical", accuracy = true, }) return true end, }}) obj.energy = 0 return obj end
require "Build" require "Utils" require "../Helpers" local llvm = path.getabsolute(basedir .. "/../deps/llvm") -- Prevent premake from inserting /usr/lib64 search path on linux. GCC does not need this path specified -- as compiler automatically knows where to look for system libs. Insertion of this path causes issues -- when system has clang/llvm libs installed. Build would link to system libraries instead of custom -- build required by CppSharp. if os.istarget("linux") then premake.tools.gcc.libraryDirectories['architecture']['x86_64'] = function(cfg) return {} end end -- If we are inside vagrant then clone and build LLVM outside the shared folder, -- otherwise file I/O performance will be terrible. if is_vagrant() then llvm = os.getenv("HOME") .. "/llvm" end function get_llvm_rev() return cat(basedir .. "/LLVM-commit") end function get_clang_rev() return cat(basedir .. "/Clang-commit") end function clone_llvm() local llvm_release = get_llvm_rev() print("LLVM release: " .. llvm_release) local clang_release = get_clang_rev() print("Clang release: " .. clang_release) if os.ishost("windows") then extract = extract_7z else extract = extract_tar_gz end local archive = 'llvm-'..llvm_release..'.tar.gz' if os.isfile(archive) then print('Archive '..archive..' already exists.') else download('https://github.com/llvm-mirror/llvm/archive/'..llvm_release..'.tar.gz', archive) end if os.isdir(llvm) then os.rmdir(llvm) if os.isdir(llvm) then print('Removing '..llvm..' directory failed. Please remove it manually and restart.') return end end extract(archive, '.') os.rename('llvm-'..llvm_release, llvm) archive = 'clang-'..clang_release..'.tar.gz' if os.isfile(archive) then print('Archive '..archive..' already exists.') else download('https://github.com/llvm-mirror/clang/archive/'..clang_release..'.tar.gz', archive) end extract(archive, '.') os.rename('clang-'..clang_release, llvm..'/tools/clang') end function get_vs_version() local function map_msvc_to_vs_version(major, minor) if major == "19" and minor >= "10" then return "vs2017" elseif major == "19" then return "vs2015" elseif major == "18" then return "vs2013" elseif major == "17" then return "vs2012" else error("Unknown MSVC compiler version, run in VS command prompt.") end end local out = outputof("cl") local major, minor = string.match(out, '(%d+).(%d+).%d+.?%d*%s+') return map_msvc_to_vs_version(major, minor) end function get_toolset_configuration_name(arch) if not arch then arch = target_architecture() end if os.istarget("windows") then local vsver = _ACTION if not string.starts(vsver, "vs") then vsver = get_vs_version() end return table.concat({vsver, arch}, "-") end -- FIXME: Implement for non-Windows platforms return table.concat({arch}, "-") end -- Returns a string describing the package configuration. -- Example: llvm-f79c5c-windows-vs2015-x86-Debug function get_llvm_package_name(rev, conf, arch) if not rev then rev = get_llvm_rev() end rev = string.sub(rev, 0, 6) local components = {"llvm", rev, os.target()} local toolset = get_toolset_configuration_name(arch) table.insert(components, toolset) if os.istarget("linux") then local version = GccVersion() if version < "5.0.0" then -- Minor version matters only with gcc 4.8/4.9 version = string.match(version, "%d+.%d+") else version = string.match(version, "%d+") end table.insert(components, "gcc-"..version) end if not conf then conf = get_llvm_configuration_name() end table.insert(components, conf) if os.istarget("linux") then if GccVersion() >= "4.9.0" and not UseCxx11ABI() then table.insert(components, "no-cxx11") end end return table.concat(components, "-") end function get_llvm_configuration_name(debug) if debug == true then return "Debug" end return os.istarget("windows") and "RelWithDebInfo" or "Release" end function get_7z_path() local path = "C:\\Program Files\\7-Zip\\7z.exe" if os.isfile(path) then return string.format('"%s"', path) end return "7z.exe" end function extract_7z(archive, dest_dir) return execute_or_die(string.format("%s x %s -o%s -y", get_7z_path(), archive, dest_dir), true) end function extract_tar_xz(archive, dest_dir) execute("mkdir -p " .. dest_dir, true) return execute_or_die(string.format("tar xJf %s -C %s", archive, dest_dir), true) end function extract_tar_gz(archive, dest_dir) execute("mkdir -p " .. dest_dir, true) return execute_or_die(string.format("tar xf %s -C %s", archive, dest_dir), true) end local use_7zip = os.ishost("windows") local archive_ext = use_7zip and ".7z" or ".tar.xz" function download_llvm() local toolset = get_toolset_configuration_name() if toolset == "vs2012" or toolset == "vs2013" or toolset == "vs2015" then error("Pre-compiled LLVM packages for your VS version are not available.\n" .. "Please upgrade to a newer VS version or compile LLVM manually.") end local base = "https://github.com/mono/CppSharp/releases/download/CppSharp/" local pkg_name = get_llvm_package_name() local archive = pkg_name .. archive_ext -- check if we already have the file downloaded if os.isfile(archive) then print("Archive " .. archive .. " already exists.") else download(base .. archive, archive) end -- extract the package if os.isdir(pkg_name) then print("Directory " .. pkg_name .. " already exists.") else if use_7zip then extract_7z(archive, pkg_name) else extract_tar_xz(archive, pkg_name) end end end function cmake(gen, conf, builddir, options) local cwd = os.getcwd() os.chdir(builddir) local cmake = os.ishost("macosx") and "/Applications/CMake.app/Contents/bin/cmake" or "cmake" if options == nil then options = "" end if not UseCxx11ABI() then options = options.." -DCMAKE_CXX_FLAGS='-D_GLIBCXX_USE_CXX11_ABI=0'" end local cmd = cmake .. " -G " .. '"' .. gen .. '"' .. ' -DCLANG_BUILD_TOOLS=false' .. ' -DCLANG_INSTALL_SCANBUILD=false' .. ' -DCLANG_INSTALL_SCANVIEW=false' .. ' -DCLANG_TOOL_CLANG_DIFF_BUILD=false' .. ' -DCLANG_TOOL_CLANG_FUNC_MAPPING_BUILD=false' .. ' -DCLANG_TOOL_CLANG_IMPORT_TEST_BUILD=false' .. ' -DCLANG_TOOL_CLANG_OFFLOAD_BUNDLER_BUILD=false' .. ' -DCLANG_TOOL_CLANG_REFACTOR_BUILD=false' .. ' -DCLANG_TOOL_CLANG_RENAME_BUILD=false' .. ' -DCLANG_TOOL_DRIVER_BUILD=false' .. ' -DCLANG_TOOL_HANDLE_CXX_BUILD=false' .. ' -DCLANG_TOOL_HANDLE_LLVM_BUILD=false' .. ' -DLLVM_BUILD_TOOLS=false' .. ' -DLLVM_ENABLE_LIBEDIT=false' .. ' -DLLVM_ENABLE_ZLIB=false' .. ' -DLLVM_ENABLE_TERMINFO=false' .. ' -DLLVM_ENABLE_LIBXML2=false' .. ' -DLLVM_INCLUDE_EXAMPLES=false' .. ' -DLLVM_INCLUDE_DOCS=false' .. ' -DLLVM_INCLUDE_TESTS=false' .. ' -DLLVM_TOOL_BUGPOINT_BUILD=false' .. ' -DLLVM_TOOL_BUGPOINT_PASSES_BUILD=false' .. ' -DLLVM_TOOL_CLANG_TOOLS_EXTRA_BUILD=false' .. ' -DLLVM_TOOL_COMPILER_RT_BUILD=false' .. ' -DLLVM_TOOL_DRAGONEGG_BUILD=false' .. ' -DLLVM_TOOL_DSYMUTIL_BUILD=false' .. ' -DLLVM_TOOL_GOLD_BUILD=false' .. ' -DLLVM_TOOL_LLC_BUILD=false' .. ' -DLLVM_TOOL_LLDB_BUILD=false' .. ' -DLLVM_TOOL_LLD_BUILD=false' .. ' -DLLVM_TOOL_LLGO_BUILD=false' .. ' -DLLVM_TOOL_LLI_BUILD=false' .. ' -DLLVM_TOOL_LLVM_AR_BUILD=false' .. ' -DLLVM_TOOL_LLVM_AS_BUILD=false' .. ' -DLLVM_TOOL_LLVM_AS_FUZZER_BUILD=false' .. ' -DLLVM_TOOL_LLVM_BCANALYZER_BUILD=false' .. ' -DLLVM_TOOL_LLVM_CAT_BUILD=false' .. ' -DLLVM_TOOL_LLVM_CFI_VERIFY_BUILD=false' .. ' -DLLVM_TOOL_LLVM_CONFIG_BUILD=false' .. ' -DLLVM_TOOL_LLVM_COV_BUILD=false' .. ' -DLLVM_TOOL_LLVM_CVTRES_BUILD=false' .. ' -DLLVM_TOOL_LLVM_CXXDUMP_BUILD=false' .. ' -DLLVM_TOOL_LLVM_CXXFILT_BUILD=false' .. ' -DLLVM_TOOL_LLVM_C_TEST_BUILD=false' .. ' -DLLVM_TOOL_LLVM_DEMANGLE_FUZZER_BUILD=false' .. ' -DLLVM_TOOL_LLVM_DIFF_BUILD=false' .. ' -DLLVM_TOOL_LLVM_DIS_BUILD=false' .. ' -DLLVM_TOOL_LLVM_DWP_BUILD=false' .. ' -DLLVM_TOOL_LLVM_DWARFDUMP_BUILD=false' .. ' -DLLVM_TOOL_LLVM_EXEGESIS_BUILD=false' .. ' -DLLVM_TOOL_LLVM_EXTRACT_BUILD=false' .. ' -DLLVM_TOOL_LLVM_GO_BUILD=false' .. ' -DLLVM_TOOL_LLVM_ISEL_FUZZER_BUILD=false' .. ' -DLLVM_TOOL_LLVM_JITLISTENER_BUILD=false' .. ' -DLLVM_TOOL_LLVM_LINK_BUILD=false' .. ' -DLLVM_TOOL_LLVM_LTO_BUILD=false' .. ' -DLLVM_TOOL_LLVM_LTO2_BUILD=false' .. ' -DLLVM_TOOL_LLVM_MCMARKUP_BUILD=false' .. ' -DLLVM_TOOL_LLVM_MC_ASSEMBLE_FUZZER_BUILD=false' .. ' -DLLVM_TOOL_LLVM_MC_BUILD=false' .. ' -DLLVM_TOOL_LLVM_MC_DISASSEMBLE_FUZZER_BUILD=false' .. ' -DLLVM_TOOL_LLVM_MCA_BUILD=false' .. ' -DLLVM_TOOL_LLVM_MC_FUZZER_BUILD=false' .. ' -DLLVM_TOOL_LLVM_MODEXTRACT_BUILD=false' .. ' -DLLVM_TOOL_LLVM_MT_BUILD=false' .. ' -DLLVM_TOOL_LLVM_NM_BUILD=false' .. ' -DLLVM_TOOL_LLVM_OBJCOPY_BUILD=false' .. ' -DLLVM_TOOL_LLVM_OBJDUMP_BUILD=false' .. ' -DLLVM_TOOL_LLVM_OPT_FUZZER_BUILD=false' .. ' -DLLVM_TOOL_LLVM_OPT_REPORT_BUILD=false' .. ' -DLLVM_TOOL_LLVM_PDBDUMP_BUILD=false' .. ' -DLLVM_TOOL_LLVM_PDBUTIL_BUILD=false' .. ' -DLLVM_TOOL_LLVM_PROFDATA_BUILD=false' .. ' -DLLVM_TOOL_LLVM_PDBUTIL_BUILD=false' .. ' -DLLVM_TOOL_LLVM_RC_BUILD=false' .. ' -DLLVM_TOOL_LLVM_READOBJ_BUILD=false' .. ' -DLLVM_TOOL_LLVM_RTDYLD_BUILD=false' .. ' -DLLVM_TOOL_LLVM_SHLIB_BUILD=false' .. ' -DLLVM_TOOL_LLVM_SIZE_BUILD=false' .. ' -DLLVM_TOOL_LLVM_SPECIAL_CASE_LIST_FUZZER_BUILD=false' .. ' -DLLVM_TOOL_LLVM_SPLIT_BUILD=false' .. ' -DLLVM_TOOL_LLVM_STRESS_BUILD=false' .. ' -DLLVM_TOOL_LLVM_STRINGS_BUILD=false' .. ' -DLLVM_TOOL_LLVM_SYMBOLIZER_BUILD=false' .. ' -DLLVM_TOOL_LLVM_UNDNAME_BUILD=false' .. ' -DLLVM_TOOL_LLVM_XRAY_BUILD=false' .. ' -DLLVM_TOOL_LTO_BUILD=false' .. ' -DLLVM_TOOL_MSBUILD_BUILD=false' .. ' -DLLVM_TOOL_OBJ2YAML_BUILD=false' .. ' -DLLVM_TOOL_OPT_BUILD=false' .. ' -DLLVM_TOOL_OPT_VIEWER_BUILD=false' .. ' -DLLVM_TOOL_SANCOV_BUILD=false' .. ' -DLLVM_TOOL_SANSTATS_BUILD=false' .. ' -DLLVM_TOOL_VERIFY_USELISTORDER_BUILD=false' .. ' -DLLVM_TOOL_XCODE_TOOLCHAIN_BUILD=false' .. ' -DLLVM_TOOL_YAML2OBJ_BUILD=false' .. ' -DCLANG_BUILD_EXAMPLES=false ' .. ' -DCLANG_INCLUDE_DOCS=false ' .. ' -DCLANG_INCLUDE_TESTS=false' .. ' -DCLANG_ENABLE_ARCMT=false' .. ' -DCLANG_ENABLE_STATIC_ANALYZER=false' .. ' -DCLANG_TOOL_ARCMT_TEST_BUILD=false' .. ' -DCLANG_TOOL_CLANG_CHECK_BUILD=false' .. ' -DCLANG_TOOL_CLANG_FORMAT_BUILD=false' .. ' -DCLANG_TOOL_CLANG_FORMAT_VS_BUILD=false' .. ' -DCLANG_TOOL_CLANG_FUZZER_BUILD=false' .. ' -DCLANG_TOOL_C_ARCMT_TEST_BUILD=false' .. ' -DCLANG_TOOL_C_INDEX_TEST_BUILD=false' .. ' -DCLANG_TOOL_DIAGTOOL_BUILD=false' .. ' -DCLANG_TOOL_LIBCLANG_BUILD=false' .. ' -DCLANG_TOOL_SCAN_BUILD_BUILD=false' .. ' -DCLANG_TOOL_SCAN_VIEW_BUILD=false' .. ' -DLLVM_TARGETS_TO_BUILD="X86"' .. ' -DCMAKE_BUILD_TYPE=' .. conf .. ' ..' .. ' -DCMAKE_OSX_DEPLOYMENT_TARGET=10.11' .. ' ' .. options execute_or_die(cmd) os.chdir(cwd) end function clean_llvm(llvm_build) if os.isdir(llvm_build) then os.rmdir(llvm_build) end end function get_cmake_generator() local vsver = get_vs_version() if vsver == "vs2017" then return "Visual Studio 15 2017" elseif vsver == "vs2015" then return "Visual Studio 14 2015" else error("Cannot map to CMake configuration due to unknown MSVC version") end end function build_llvm(llvm_build) if not os.isdir(llvm) then print("LLVM/Clang directory does not exist, cloning...") clone_llvm() end os.mkdir(llvm_build) local conf = get_llvm_configuration_name() local use_msbuild = false if os.ishost("windows") and use_msbuild then cmake(get_cmake_generator(), conf, llvm_build) local llvm_sln = path.join(llvm_build, "LLVM.sln") msbuild(llvm_sln, conf) else local options = os.ishost("macosx") and "-DLLVM_ENABLE_LIBCXX=true" or "" local is32bits = target_architecture() == "x86" if is32bits then options = options .. (is32bits and " -DLLVM_BUILD_32_BITS=true" or "") end cmake("Ninja", conf, llvm_build, options) ninja('"' .. llvm_build .. '"') ninja('"' .. llvm_build .. '"', "clang-headers") end end function package_llvm(conf, llvm, llvm_build) local rev = git.rev_parse('"' .. llvm .. '"', "HEAD") if string.is_empty(rev) then rev = get_llvm_rev() end local out = get_llvm_package_name(rev, conf) if os.isdir(out) then os.rmdir(out) end os.mkdir(out) os.copydir(llvm .. "/include", out .. "/include") os.copydir(llvm_build .. "/include", out .. "/build/include") local llvm_msbuild_libdir = "/" .. conf .. "/lib" local lib_dir = os.ishost("windows") and os.isdir(llvm_msbuild_libdir) and llvm_msbuild_libdir or "/lib" local llvm_build_libdir = llvm_build .. lib_dir if os.ishost("windows") and os.isdir(llvm_build_libdir) then os.copydir(llvm_build_libdir, out .. "/build" .. lib_dir, "*.lib") else os.copydir(llvm_build_libdir, out .. "/build/lib", "*.a") end os.copydir(llvm .. "/tools/clang/include", out .. "/tools/clang/include") os.copydir(llvm_build .. "/tools/clang/include", out .. "/build/tools/clang/include") os.copydir(llvm_build .. "/lib/clang", out .. "/lib/clang") os.copydir(llvm .. "/tools/clang/lib/CodeGen", out .. "/tools/clang/lib/CodeGen", "*.h") os.copydir(llvm .. "/tools/clang/lib/Driver", out .. "/tools/clang/lib/Driver", "*.h") os.copydir(llvm .. "/tools/clang/lib/Driver/ToolChains", out .. "/tools/clang/lib/Driver/ToolChains", "*.h") local out_lib_dir = out .. "/build" .. lib_dir if os.ishost("windows") then os.rmfiles(out_lib_dir, "LLVM*ObjCARCOpts*.lib") os.rmfiles(out_lib_dir, "clang*ARC*.lib") os.rmfiles(out_lib_dir, "clang*Matchers*.lib") os.rmfiles(out_lib_dir, "clang*Rewrite*.lib") os.rmfiles(out_lib_dir, "clang*StaticAnalyzer*.lib") os.rmfiles(out_lib_dir, "clang*Tooling*.lib") else os.rmfiles(out_lib_dir, "libllvm*ObjCARCOpts*.a") os.rmfiles(out_lib_dir, "libclang*ARC*.a") os.rmfiles(out_lib_dir, "libclang*Matchers*.a") os.rmfiles(out_lib_dir, "libclang*Rewrite*.a") os.rmfiles(out_lib_dir, "libclang*StaticAnalyzer*.a") os.rmfiles(out_lib_dir, "libclang*Tooling*.a") end return out end function archive_llvm(dir) local archive = dir .. archive_ext if os.isfile(archive) then os.remove(archive) end local cwd = os.getcwd() os.chdir(dir) if use_7zip then execute_or_die(string.format("%s a -mx9 %s *", get_7z_path(), path.join("..", archive))) else execute_or_die("tar cJf " .. path.join("..", archive) .. " *") end os.chdir(cwd) if is_vagrant() then os.copyfile(archive, "/cppsharp") end end if _ACTION == "clone_llvm" then clone_llvm() os.exit() end if _ACTION == "build_llvm" then local llvm_build = path.join(llvm, get_llvm_package_name()) clean_llvm(llvm_build) build_llvm(llvm_build) os.exit() end if _ACTION == "package_llvm" then local conf = get_llvm_configuration_name() local llvm_build = path.join(llvm, get_llvm_package_name()) local pkg = package_llvm(conf, llvm, llvm_build) archive_llvm(pkg) os.exit() end if _ACTION == "download_llvm" then download_llvm() os.exit() end
-- Planet Region Definitions -- -- {"regionName", x, y, shape and size, tier, {"spawnGroup1", ...}, maxSpawnLimit} -- For circle and ring, x and y are the center point -- For rectangles, x and y are the bottom left corner. x2 and y2 (see below) are the upper right corner -- Shape and size is a table with the following format depending on the shape of the area: -- - Circle: {CIRCLE, radius} -- - Rectangle: {RECTANGLE, x2, y2} -- - Ring: {RING, inner radius, outer radius} -- Tier is a bit mask with the following possible values where each hexadecimal position is one possible configuration. -- That means that it is not possible to have both a spawn area and a no spawn area in the same region, but -- a spawn area that is also a no build zone is possible. require("scripts.managers.spawn_manager.regions") talus_regions = { {"aakuan_champions_cave", 5928, 4656, {CIRCLE, 150}, NOSPAWNAREA + NOBUILDZONEAREA}, {"aakuan_tent", -3685, -550, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"ageyn_foothills", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"an_imperial_outpost", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"animal_skull", 2118, 1272, {CIRCLE, 50}, NOSPAWNAREA + NOBUILDZONEAREA}, {"arch_and_torches", 1467, -2672, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"at_st_wreckage", -3200, 4757, {CIRCLE, 75}, NOSPAWNAREA + NOBUILDZONEAREA}, {"aqualish_fishing_spot", 5345, 4543, {CIRCLE, 150}, NOSPAWNAREA + NOBUILDZONEAREA}, {"azaki_plains_1", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"azaki_plains_2", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"azaki_plains_3", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"backbone", -5730, 2857, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"bones", -1242, 1496, {CIRCLE, 20}, NOSPAWNAREA + NOBUILDZONEAREA}, {"bones_2", -4715, 1130, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"boulder", -861, 1019, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"bridge", -150, 325, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"bridge_and_debris", 5475, 1080, {CIRCLE, 75}, NOSPAWNAREA + NOBUILDZONEAREA}, {"bridge_struts", -3988, 979, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"broken_at_at", -2436, -2210, {CIRCLE, 100}, NOSPAWNAREA + NOBUILDZONEAREA}, {"broken_bridge", -4051, 3660, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"broken_droid", -2600, 100, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"broken_machinery", -4354, 1540, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"broken_probe_droid", -4803, 5165, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"broken_strut", -1635, -325, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"broken_walls", 1117, 1489, {CIRCLE, 50}, NOSPAWNAREA + NOBUILDZONEAREA}, {"building_ruins", 5188, -1735, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"burning_rocks", 4310, 2560, {CIRCLE, 50}, NOSPAWNAREA + NOBUILDZONEAREA}, {"bushes", -4455, 4060, {CIRCLE, 20}, NOSPAWNAREA + NOBUILDZONEAREA}, {"camp", -5875, -180, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"camp_2", 2337, 2937, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"campsite", -2715, -2265, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"central_plains", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"chunker_bunker", 1374, 1470, {CIRCLE, 75}, NOSPAWNAREA + NOBUILDZONEAREA}, {"circle_of_rocks", -5673, 5289, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"circle_of_rocks_2", -5100, 4720, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"corsec_vs_flail_battle", 3030, 6100, {CIRCLE, 200}, NOSPAWNAREA + NOBUILDZONEAREA}, {"dath_tree", -60, 980, {CIRCLE, 15}, NOSPAWNAREA + NOBUILDZONEAREA}, {"dath_tree_2", -701, 156, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"dearic", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"dearic_easy_newbie", 432, -3008, {CIRCLE, 1750}, SPAWNAREA + NOWORLDSPAWNAREA, {"talus_easy"}, 256}, {"dearic_medium_newbie", 432, -3008, {RING, 1750, 2500}, SPAWNAREA + NOWORLDSPAWNAREA, {"talus_medium"}, 384}, {"debris", 1709, 784, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"debris_2", -1735, -2890, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"debris_3", -1010, -5090, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"debris_4", -6318, 1253, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"derik_hur_highlands_1", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"derik_hur_highlands_2", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"derik_hur_highlands_3", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"detainment_center", 4984, -6027, {CIRCLE, 150}, NOSPAWNAREA + NOBUILDZONEAREA}, {"diseased_debris", -5140, 3700, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"diseased_ruins", -5114, 3211, {CIRCLE, 50}, NOSPAWNAREA + NOBUILDZONEAREA}, {"downed_shuttle", -2400, 2035, {CIRCLE, 75}, NOSPAWNAREA + NOBUILDZONEAREA}, {"eastern_mountains", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"eastern_plains", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"escape_pod", -4983, 5753, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"flag", -3460, 1550, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"flag_and_ruins", -3800, -6500, {CIRCLE, 50}, NOSPAWNAREA + NOBUILDZONEAREA}, {"forest", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"forest_1", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"forest_2", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"forest_3", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"forest_4", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"forest_5", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"fountain", 3888, 3390, {CIRCLE, 50}, NOSPAWNAREA + NOBUILDZONEAREA}, {"fountain_2", -3155, -925, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"grasslands", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"grasslands_1", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"grasslands_2", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"grasslands_3", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"grasslands_4", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"grasslands_5", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"hard_aakuan_se", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"hard_dalyrake_ne", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"hard_dalyrake_sw", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"hard_grand_wrix_nw", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"hard_grand_wrix_se", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"hard_guf_drolg_ne", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"hard_guf_drolg_se", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"hard_selonian_sw", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"hunters_tent", 1118, -1765, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"hut_and_graves", -2245, 900, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"imperial_house_2", 1721, 1623, {CIRCLE, 50}, NOSPAWNAREA + NOBUILDZONEAREA}, {"imperial_tower", 3209, 1264, {CIRCLE, 50}, NOSPAWNAREA + NOBUILDZONEAREA}, {"imperial_vs_rebel_battle", -2448, 3764, {CIRCLE, 200}, NOSPAWNAREA + NOBUILDZONEAREA}, {"krayt_skull", -1117, 3753, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"lake_bondoma", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"large_broken_tower", -5515, 1065, {CIRCLE, 50}, NOSPAWNAREA + NOBUILDZONEAREA}, {"lookout_tower", -4377, 2667, {CIRCLE, 50}, NOSPAWNAREA + NOBUILDZONEAREA}, {"lost_aqualish_cave", -4355, -1426, {CIRCLE, 200}, NOSPAWNAREA + NOBUILDZONEAREA}, {"lost_village_of_durbin", 4200, 1000, {CIRCLE, 200}, NOSPAWNAREA + NOBUILDZONEAREA}, {"machinery", -1469, 1228, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"machinery_2", -4018, 4623, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"makeshift_tent", 86, 1579, {CIRCLE, 50}, NOSPAWNAREA + NOBUILDZONEAREA}, {"marker", 2472, 786, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"medium_devil_gulginaw_nw", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"medium_sludge_panther_sw", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"medium_wolf_kima_ne", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"medium_wolf_kima_nw", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"metal_objects", -564, 1269, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"mountains", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"mountains_1", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"mountains_2", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"mountains_3", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"mountains_4", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"mountains_5", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"mountains_6", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"mountains_7", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"mountains_8", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"mudflats_1", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"mudflats_2", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"nashal", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"nashal_easy_newbie", 4352, 5209, {CIRCLE, 1750}, SPAWNAREA + NOWORLDSPAWNAREA, {"talus_easy"}, 256}, {"nashal_medium_newbie", 4352, 5209, {RING, 1750, 2500}, SPAWNAREA + NOWORLDSPAWNAREA, {"talus_medium"}, 384}, {"narshal_river_race_track_1", 3787, 4764, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"narshal_river_race_track_2", 3485, 4556, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"narshal_river_race_track_3", 3042, 4565, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"narshal_river_race_track_4", 2248, 5169, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"narshal_river_race_track_5", 1839, 4966, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"narshal_river_race_track_6", 1583, 5062, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"narshal_river_race_track_7", 1499, 4802, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"narshal_river_race_track_8", 1485, 4366, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"narshal_river_race_track_9", 2248, 3905, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"narshal_river_race_track_10", 1886, 3211, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"narshal_river_race_track_11", 2448, 2457, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"narshal_river_race_track_12", 2841, 2923, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"narshal_river_race_track_13", 3670, 3475, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"narshal_river_race_track_14", 4129, 3652, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"narshal_river_race_track_15", 4511, 4054, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"narshal_river_race_track_16", 4529, 4831, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"north_crimson_flats_1", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"north_crimson_flats_2", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"north_crimson_flats_3", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"northeast_forest", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"northern_forest", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"northern_mountains", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"northwest_forest", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"old_comms_mast", -1650, 3381, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"pillar", 616, 1102, {CIRCLE, 50}, NOSPAWNAREA + NOBUILDZONEAREA}, {"pillar_red_haze", -5100, 1272, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"pillars", 4972, 3848, {CIRCLE, 50}, NOSPAWNAREA + NOBUILDZONEAREA}, {"pillars_2", -4975, -590, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"pile_of_rocks", -2790, 910, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"prairie", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"prairie_1", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"quarantined_building", 3900, -2850, {CIRCLE, 150}, NOSPAWNAREA + NOBUILDZONEAREA}, {"rebel_camp", 3101, -4046, {CIRCLE, 75}, NOSPAWNAREA + NOBUILDZONEAREA}, {"rebel_installation", 2377, -4993, {CIRCLE, 75}, NOSPAWNAREA + NOBUILDZONEAREA}, {"red_fire", -1830, 1437, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"ribcage", -4470, 67, {CIRCLE, 45}, NOSPAWNAREA + NOBUILDZONEAREA}, {"river", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"rocks", -6000, 5952, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"ruins", -1396, 2114, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"ruins_2", -1600, -540, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"ruins_3", -3489, 3698, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"ruins_4", -3333, 5175, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"ruins_5", -4758, 3933, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"science_equipment", -3650, 6333, {CIRCLE, 75}, NOSPAWNAREA + NOBUILDZONEAREA}, {"shadowbrak_ridge", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"skeleton_and_rocks", -3169, 5734, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"skeleton_and_ruins", -3393, 2500, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"skulls_and_fire", -5100, 2357, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"skyspear_forest", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"smugglers_shipment", -3444, 6186, {CIRCLE, 50}, NOSPAWNAREA + NOBUILDZONEAREA}, {"south_crimson_flats_1", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"south_crimson_flats_2", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"south_crimson_flats_3", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"southern_coast", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"southwest_forest", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"spring", -3231, 4203, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"static_tall_tree", 3642, 500, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"statue", -3247, 3427, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"statue_head", -5040, 115, {CIRCLE, 45}, NOSPAWNAREA + NOBUILDZONEAREA}, {"stone_arch", -5225, 4600, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"stone_arrangement", 169, 3407, {CIRCLE, 50}, NOSPAWNAREA + NOBUILDZONEAREA}, {"stone_arrangement_2", -3700, 4390, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"stone_blocks", -733, 2033, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"swamp", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"table", 5415, 2655, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"talus_imperial_outpost", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"talus_imperial_outpost_easy_newbie", -2186, 2300, {CIRCLE, 1000}, SPAWNAREA + NOWORLDSPAWNAREA, {"talus_easy"}, 256}, {"talus_imperial_outpost_medium_newbie", -2186, 2300, {RING, 1000, 1750}, SPAWNAREA + NOWORLDSPAWNAREA, {"talus_medium"}, 384}, {"tendin_vale", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"three_pillars", -5697, 4010, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"three_spikes", -3920, 4125, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"three_stones", -1362, 1060, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"three_stone_pyramid", -5400, 4300, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"tie_bomber_debris", 4846, -4720, {CIRCLE, 75}, NOSPAWNAREA + NOBUILDZONEAREA}, {"tie_bomber_wing", -5283, 5053, {CIRCLE, 75}, NOSPAWNAREA + NOBUILDZONEAREA}, {"tree_stump", -3245, 4321, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"tree_with_skulls", -5477, 5810, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"two_stones", -3710, 2891, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"wall", 2810, 5583, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"walled_island", 2454, 2483, {CIRCLE, 30}, NOSPAWNAREA + NOBUILDZONEAREA}, {"weapons_depot", -4935, -3112, {CIRCLE, 150}, NOSPAWNAREA + NOBUILDZONEAREA}, {"western_mountains", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"western_plains", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"world_spawner", 0, 0, {CIRCLE, -1}, SPAWNAREA + WORLDSPAWNAREA, {"talus_world", "global"}, 2048}, {"yitsarin_river_canyon_1", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"yitsarin_river_canyon_2", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"yitsarin_river_canyon_3", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"yitsarin_river_canyon_4", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"yitsarin_river_canyon_5", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"yitsarin_river_canyon_6", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"yitsarin_river_canyon_7", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA}, {"yitsarin_river_canyon_8", 0, 0, {CIRCLE, 0}, UNDEFINEDAREA} }
function onCreate() --Iterate over all notes for i = 0, getProperty('unspawnNotes.length')-1 do --Check if the note is a 5uaty if getPropertyFromGroup('unspawnNotes', i, 'noteType') == '5uaty' then setPropertyFromGroup('unspawnNotes', i, 'texture', '5UATY/BULLET5uaty_assets'); --Change texture end end --debugPrint('Script started!') end
local awful = require("awful") local gears = require("gears") local gfs = gears.filesystem local wibox = require("wibox") local beautiful = require("beautiful") local xresources = require("beautiful.xresources") local dpi = xresources.apply_dpi local helpers = require('helpers') local get_taglist = function(s) -- Taglist buttons local taglist_buttons = gears.table.join( awful.button({}, 1, function(t) t:view_only() end), awful.button({modkey}, 1, function(t) if client.focus then client.focus:move_to_tag(t) end end), awful.button({}, 3, awful.tag.viewtoggle), awful.button({modkey}, 3, function(t) if client.focus then client.focus:toggle_tag(t) end end), awful.button({}, 4, function(t) awful.tag.viewnext(t.screen) end), awful.button({}, 5, function(t) awful.tag.viewprev(t.screen) end) ) -- Function to update the tags local update_tags = function(self, c3) local textbox = self:get_children_by_id('icon_role')[1] if c3.selected then textbox.markup = helpers.colorize_text("", beautiful.yellow) elseif #c3:clients() == 0 then textbox.markup = helpers.colorize_text("", beautiful.fg0) else textbox.markup = helpers.colorize_text("", beautiful.aqua) end end local taglist = awful.widget.taglist { screen = s, filter = awful.widget.taglist.filter.all, style = {shape = gears.shape.rectangle}, layout = {spacing = 0, layout = wibox.layout.fixed.horizontal}, widget_template = { { { id = 'icon_role', font = beautiful.font_taglist, widget = wibox.widget.textbox }, id = 'margin_role', left = dpi(10), right = dpi(10), widget = wibox.container.margin }, id = 'background_role', widget = wibox.container.background, create_callback = function(self, c3, index, objects) update_tags(self, c3) self:connect_signal('mouse::enter', function() if self.bg ~= beautiful.xbackground then self.backup = self.bg self.has_backup = true end self.bg = beautiful.xbackground end) self:connect_signal('mouse::leave', function() if self.has_backup then self.bg = self.backup end end) end, update_callback = function(self, c3, index, objects) update_tags(self, c3) end }, buttons = taglist_buttons } return taglist end return get_taglist
local merge = pl.tablex.merge local fromHexAlpha = poon.utils.colors.fromHexAlpha local color = fromHexAlpha('#81ecec', 0.5) local endColor = fromHexAlpha('#00cec9', 0.5) local strokeColor = merge(color, { alpha=1 }, true) local rectanglePreview = hs.drawing.rectangle(hs.geometry.rect(0, 0, 0, 0)) rectanglePreview:setStrokeWidth(2) rectanglePreview:setStrokeColor(strokeColor) rectanglePreview:setFillGradient(color, endColor, 45) rectanglePreview:setRoundedRectRadii(2, 2) rectanglePreview:setStroke(true):setFill(true) rectanglePreview:setLevel("floating") local function openIterm() local frame = rectanglePreview:frame() local createItermWithBounds = string.format([[ if application "iTerm" is not running then launch application "iTerm" end if tell application "iTerm" set newWindow to (create window with default profile) set the bounds of newWindow to {%i, %i, %i, %i} end tell ]], frame.x, frame.y, frame.x + frame.w, frame.y + frame.h) hs.osascript.applescript(createItermWithBounds) end local fromPoint = nil local drag_event = hs.eventtap.new( { hs.eventtap.event.types.mouseMoved }, function(e) local toPoint = hs.mouse.getAbsolutePosition() local newFrame = hs.geometry.new({ x1 = fromPoint.x, y1 = fromPoint.y, x2 = toPoint.x, y2 = toPoint.y, }) rectanglePreview:setFrame(newFrame) return nil end ) local flags_event = hs.eventtap.new( { hs.eventtap.event.types.flagsChanged }, function(e) local flags = e:getFlags() if flags.ctrl and flags.shift then fromPoint = hs.mouse.getAbsolutePosition() local startFrame = hs.geometry.rect(fromPoint.x, fromPoint.y, 0, 0) rectanglePreview:setFrame(startFrame) drag_event:start() rectanglePreview:show() elseif fromPoint ~= nil then fromPoint = nil drag_event:stop() rectanglePreview:hide() openIterm() end return nil end ) flags_event:start()
--[[-- request.register_mime_type( filename_extension, mime_type ) Registers a mime type for a given filename extension (case sensitive). --]]-- function request.register_mime_type(filename_extension, mime_type) request.configure(function() request._mime_types[filename_extension] = mime_type end) end
------------------------------------------------------------------------------- -- Load necessary libraries and files ------------------------------------------------------------------------------- require 'torch' require 'xlua' require 'optim' require 'nn' require 'nnx' require 'nngraph' require 'hdf5' require 'string' require 'image' paths.dofile('util/img.lua') paths.dofile('util/eval.lua') paths.dofile('util/Logger.lua') torch.setdefaulttensortype('torch.FloatTensor') -- Project directory projectDir = paths.concat(os.getenv('HOME'),'object3d/pose-hg/pose-hg-train') ------------------------------------------------------------------------------- -- Process command line options ------------------------------------------------------------------------------- if not opt then local opts = paths.dofile('opts.lua') opt = opts.parse(arg) print('Saving everything to: ' .. opt.save) os.execute('mkdir -p ' .. opt.save) if opt.GPU == -1 then nnlib = nn else require 'cutorch' require 'cunn' require 'cudnn' nnlib = cudnn cutorch.setDevice(opt.GPU) end if opt.branch ~= 'none' or opt.continue then -- Continuing training from a prior experiment -- Figure out which new options have been set local setOpts = {} for i = 1,#arg do if arg[i]:sub(1,1) == '-' then table.insert(setOpts,arg[i]:sub(2,-1)) end end -- Where to load the previous options/model from if opt.branch ~= 'none' then opt.load = opt.expDir .. '/' .. opt.branch else opt.load = opt.expDir .. '/' .. opt.expID end -- Keep previous options, except those that were manually set local opt_ = opt opt = torch.load(opt_.load .. '/options.t7') opt.save = opt_.save opt.load = opt_.load opt.continue = opt_.continue for i = 1,#setOpts do opt[setOpts[i]] = opt_[setOpts[i]] end epoch = opt.lastEpoch + 1 -- If there's a previous optimState, load that too if paths.filep(opt.load .. '/optimState.t7') then optimState = torch.load(opt.load .. '/optimState.t7') optimState.learningRate = opt.LR end else epoch = 1 end opt.epochNumber = epoch -- Training hyperparameters -- (Some of these aren't relevant for rmsprop which is the optimization we use) if not optimState then optimState = { learningRate = opt.LR, learningRateDecay = opt.LRdecay, momentum = opt.momentum, dampening = 0.0, weightDecay = opt.weightDecay } end -- Optimization function optfn = optim[opt.optMethod] -- Random number seed if opt.manualSeed ~= -1 then torch.manualSeed(opt.manualSeed) else torch.seed() end -- Save options to experiment directory torch.save(opt.save .. '/options.t7', opt) end ------------------------------------------------------------------------------- -- Load in annotations ------------------------------------------------------------------------------- annotLabels = {'train', 'valid'} annot,ref = {},{} for _,l in ipairs(annotLabels) do local a, namesFile if opt.dataset == 'mpii' and l == 'valid' and opt.finalPredictions == 1 then a = hdf5.open(opt.dataDir .. '/annot/test.h5') namesFile = io.open(opt.dataDir .. '/annot/test_images.txt') else a = hdf5.open(opt.dataDir .. '/annot/' .. l .. '.h5') namesFile = io.open(opt.dataDir .. '/annot/' .. l .. '_images.txt') end annot[l] = {} -- Read in annotation information local tags = {'part', 'center', 'scale'} for _,tag in ipairs(tags) do annot[l][tag] = a:read(tag):all() end annot[l]['nsamples'] = annot[l]['part']:size()[1] -- Load in image file names (reading strings wasn't working from hdf5) annot[l]['images'] = {} local toIdxs = {} local idx = 1 for line in namesFile:lines() do annot[l]['images'][idx] = line if not toIdxs[line] then toIdxs[line] = {} end table.insert(toIdxs[line], idx) idx = idx + 1 end namesFile:close() -- This allows us to reference multiple people who are in the same image annot[l]['imageToIdxs'] = toIdxs -- Set up reference for training parameters ref[l] = {} ref[l].nsamples = annot[l]['nsamples'] ref[l].iters = opt[l .. 'Iters'] ref[l].batchsize = opt[l .. 'Batch'] ref[l].log = Logger(paths.concat(opt.save, l .. '.log'), opt.continue) end ref.predict = {} ref.predict.nsamples = annot.valid.nsamples ref.predict.iters = annot.valid.nsamples ref.predict.batchsize = 1 -- Default input is assumed to be an image and output is assumed to be a heatmap -- This can change if an hdf5 file is used, or if opt.task specifies something different nParts = annot['train']['part']:size(2) dataDim = {3, opt.inputRes, opt.inputRes} labelDim = {nParts, opt.outputRes, opt.outputRes} -- Load up task specific variables/functions -- (this allows a decent amount of flexibility in network input/output and training) paths.dofile('util/' .. opt.task .. '.lua') function applyFn(fn, t, t2) -- Helper function for applying an operation whether passed a table or tensor local t_ = {} if type(t) == "table" then if t2 then for i = 1,#t do t_[i] = applyFn(fn, t[i], t2[i]) end else for i = 1,#t do t_[i] = applyFn(fn, t[i]) end end else t_ = fn(t, t2) end return t_ end
MathUtils = {} MathUtils.__index = MathUtils --- Utilities for math-related/algorithmic operations function MathUtils:create() local this = {} setmetatable(this, self) return this end --- Get the path from (fromX, fromY) to (toX, toY) that would result in a line. The path includes BOTH the starting -- point and the ending point. -- @param fromX {int} - The X coordinate of the first point -- @param fromY {int} - The Y coordinate of the first point -- @param toX {int} - The X coordinate of the second point -- @param toY {int} - The Y coordinate of the second point function MathUtils:getDiscreteLine(fromX, fromY, toX, toY) local dx = math.abs(toX - fromX) local dy = math.abs(toY - fromY) local reverse = dx < dy if reverse then fromX, fromY = fromY, fromX toX, toY = toY, toX dx, dy = dy, dx end local incUp = -2 * dx + 2 * dy local incDown = 2 * dy local incX = (fromX <= toX) and 1 or -1 local incY = (fromY <= toY) and 1 or -1 local d = -dx + 2 * dy local x = fromX local y = fromY local n = 0 local points = { } for i = 0, dx do n = n + 1 points[n] = reverse and { x = y, y = x } or { x = x, y = y } x = x + incX if d > 0 then y = y + incY d = d + incUp else d = d + incDown end end return points end
local Channelling = {} local sourceName = "channelling" local channelHistory = {} local currentChannelTarget = '' local currentChannelPower = 1 local currentChannelCount = 0 local function channel(args) send("channel "..currentChannelPower.. " "..currentChannelTarget) currentChannelCount = currentChannelCount + currentChannelPower Events.raiseEvent("messageEvent", {message="<yellow>Channelled "..currentChannelCount.." to "..currentChannelTarget.."\n"}) channelHistory[currentChannelTarget].count = currentChannelCount Events.raiseEvent("channeledEvent", {power = currentChannelPower ,count = currentChannelCount ,target = currentChannelTarget}) Channelling.save() end local function channelSetup(args) local power = args["power"] local target = args["target"] currentChannelTarget = target currentChannelPower = power currentChannelCount = 0 channelHistory[target] = {power = currentChannelPower, count = currentChannelCount} Events.addListener("BEBTconcEvent", sourceName, channel) Events.raiseEvent("messageEvent", {message="<yellow>Channelling "..currentChannelPower.." to "..currentChannelTarget.."\n"}) Channelling.save() end local function channelResume(args) local target = args["target"] if target == "" and currentChannelTarget ~= "" then Events.addListener("BEBTconcEvent", sourceName, channel) Events.raiseEvent("messageEvent", {message="<yellow>Channelling "..currentChannelPower.." to "..currentChannelTarget.."\n"}) elseif channelHistory[target] then currentChannelTarget = target currentChannelPower = channelHistory[currentChannelTarget].power currentChannelCount = channelHistory[currentChannelTarget].count Events.addListener("BEBTconcEvent", sourceName, channel) Events.raiseEvent("messageEvent", {message="<yellow>Channelling "..currentChannelPower.." to "..currentChannelTarget.."\n"}) end Channelling.save() end local function channelOff(args) Events.raiseEvent("messageEvent", {message="<yellow>Stopped Channelling\n"}) Events.removeListener("BEBTconcEvent", sourceName) end local function changeTarget(args) local target = args["target"] currentChannelTarget = target if channelHistory[currentChannelTarget] then currentChannelCount = channelHistory[currentChannelTarget].count else channelHistory[currentChannelTarget] = {} currentChannelCount = 0 end Events.raiseEvent("messageEvent", {message="<yellow>Changed target to "..currentChannelTarget.." with current count of "..currentChannelCount.."\n"}) Channelling.save() end local function changePower(args) local power = args["power"] currentChannelPower = power channelHistory[currentChannelTarget].power = power Events.raiseEvent("messageEvent", {message="<yellow>Channelling "..currentChannelPower.." to "..currentChannelTarget.."\n"}) Channelling.save() end local function channelStatus(args) local target = args["target"] if target == "" and currentChannelTarget ~= "" then Events.raiseEvent("messageEvent", {message="<yellow>Status: Channelling "..currentChannelPower.." to "..currentChannelTarget.."\n"}) elseif channelHistory[target] then local power = channelHistory[target].power local count = channelHistory[target].count Events.raiseEvent("messageEvent", {message="<yellow>Status: Channelled "..power.." to "..target.." for a total of "..count.."\n"}) end end local function loaderFunction(sentTable) if sentTable then currentChannelPower = sentTable["currentChannelPower"] or 1 currentChannelTarget = sentTable["currentChanneTarget"] or "" currentChannelCount = sentTable["currentChannelCount"] or 0 channelHistory = sentTable["channelHistory"] or {} end end local function load() Events.raiseEvent("loadEvent", {sourceName = sourceName, functionToSendData = loaderFunction}) end local function save() Events.raiseEvent("saveEvent", { sourceName = sourceName ,tableToSave = { channelHistory = channelHistory ,currentChannelPower = currentChannelPower ,currentChannelTarget = currentChannelTarget ,currentChannelCount = currentChannelCount } }) end local function setup(args) Events.addListener("channelSetupEvent", sourceName, channelSetup) Events.addListener("channelResumeEvent", sourceName, channelResume) Events.addListener("channelOffEvent", sourceName, channelOff) Events.addListener("channelStatusEvent", sourceName, channelStatus) Events.addListener("channelTargetEvent", sourceName, changeTarget) Events.addListener("channelPowerEvent", sourceName, changePower) end local function unsetup(args) Events.removeListener("channelSetupEvent", sourceName) Events.removeListener("channelResumeEvent", sourceName) Events.removeListener("channelOffEvent", sourceName) Events.removeListener("channelStatusEvent", sourceName) Events.removeListener("channelTargetEvent", sourceName) Events.removeListener("channelPowerEvent", sourceName) end local function resetup(args) unsetup(args) setup(args) end Channelling = { setup = setup ,unsetup = unsetup ,resetup = resetup ,load = load ,save = save } return Channelling
module 'mock' CLASS: MsgTarget () :MODEL{ Field 'targets' :array( Entity ) :ref(); } mock.registerComponent( 'MsgTarget', MsgTarget ) function MsgTarget:__init() self.targets = {} self.includeChildren = false end function MsgTarget:sendMsg( msg, data, source ) source = source or self for i, target in ipairs( self.targets ) do if target then target:tell( msg, data, source ) end end end -- function MsgTarget:pendMsg( msg, data, source ) -- self:getEntity() -- end
dofile('./config.lua') dofile('./msg.lua') dofile('./base.lua') Extensions = dofile('./Extensions.lua') patterns = dofile('./patterns.lua') function string:isgroup() return self:match('-100(%d+)') or false end function PreProccess(data) if (data._ == "updateNewMessage") then local msg = data.message local input_text = (msg.content.text or ''):lower():gsub('^[!#/]' , '') local group_chat = msg.chat_id local sender_id = msg.sender_user_id local pid , text , plang = patterns.GetID(input_text) if sender_id == 777000 then tdbot.forwardMessages(config.sudo_users[0], fromchatid, msg.id, 0, nil, dl_cb) end function getCH(Extra, Result) function StartShell(ex, res) if tostring(group_chat):isgroup() then if not database:hget('chash:title:'..source_hash , group_chat) then database:hset('chash:title:'..source_hash , group_chat , Result.title) end if database:hget('active:group:'..source_hash , group_chat) then --- chek group is installed to bot or not if not database:get('work:'..source_hash..group_chat) then print(colors("%{red}%{whitebg}GROUP EXPIRE END%{reset}")) end end end print(colors("Chat Name : %{cyan}"..(Result.title or '').."%{reset} | %{red}"..(group_chat or '').."%{reset} %{blue}"..os.date().."%{reset} %{yellow}>>>%{reset} %{green}"..(res.first_name or '').." "..(res.last_name or '').."%{reset}%{red}"..(msg.sender_user_id or '').."%{reset} : %{bright}"..input_text.."%{reset}\n")) end tdbot.getUser(sender_id, StartShell, nil) end tdbot.getChat(group_chat, getCH, nil) Extensions.run(data) msg_rvc (msg) if pid and text and plang then use_update(data , pid, text, plang) end --[[elseif (data._ == "updateMessageEdited") then local msg = data local group_chat = msg.chat_id local sender_id = msg.sender_user_id function DoEditCallback(agent24h, msg) tdbot_update_callback (msg) end tdbot.getMessage(group_chat, data.message_id, DoEditCallback, nil)]] end end function tdbot_update_callback(data) local ok , result = xpcall(PreProccess , debug.traceback , data) if not ok then --if a bug happens print(result) sendText(328977214, 0, result, nil, "html" , nil , autodelete) sendText(data.message.chat_id, 0, '🐞 اختلال در سیستم لطفا بعدا تلاش کنید', nil, "html" , nil , autodelete) end end
local ngx_log = ngx.log local ngx_DEBUG = ngx.DEBUG local ngx_ERR = ngx.ERR local ngx_INFO = ngx.INFO local ngx_WARN = ngx.WARN local ngx_worker_pid = ngx.worker.pid local _M = { _VERSION = "0.0.1", worker = {}, cluster = {}, } local zedcup = require("zedcup") local GLOBALS = zedcup.globals() local DEBUG = GLOBALS.DEBUG local utils = require("zedcup.utils") local session = require("zedcup.session") local function acquire_cluster_lock(key) if not key or type(key) ~= "string" then return error("[zedcup] Attempted to acquire cluster lock with bad key") end local session, err = session.get() if not session then ngx_log(ngx_ERR, "[zedcup] Failed to get session: ", err) return false, err end local consul, err = utils.consul_client() if not consul then return false, err end -- Attempt to acquire the lock local lock_key = GLOBALS.prefix.."/locks/"..key local res, err = consul:put_key(lock_key, "locked: "..ngx_worker_pid(), {acquire = session}) if err or res.status ~= 200 or type(res.body) ~= "boolean" then -- Failed to acquire lock ngx_log(ngx_INFO, "[zedcup] Failed to acquire cluster lock: ", key, " ", session, " ", res.status, " ", err, " ", res.body ) return false, res end if res.body == false then if DEBUG then ngx_log(ngx_DEBUG, "[zedcup] Missed cluster lock: ", key, " ", session, " ", res.status, " ", res.body ) end return false end if DEBUG then ngx_log(ngx_DEBUG, "[zedcup] Acquired cluster lock: ", key, " ", session) end return true end _M.cluster.acquire = acquire_cluster_lock local function release_cluster_lock(key) if not key or type(key) ~= "string" then return error("[zedcup] Attempted to acquire cluster lock with bad key") end local session, err = session.get() if not session then ngx_log(ngx_ERR, "[zedcup] Failed to get session: ", err) return false, err end local consul, err = utils.consul_client() if not consul then return false, err end -- Attempt to release the lock local lock_key = GLOBALS.prefix.."/locks/"..key local res, err = consul:put_key(lock_key, "unlocked: "..ngx_worker_pid(), {release = session}) if err then return false, err elseif res.status ~= 200 or res.body ~= true then -- Failed to acquire lock ngx_log(ngx_INFO, "[zedcup] Failed to release cluster lock: ", key, " ", res.status, " ", err) return false, res end if DEBUG then ngx_log(ngx_DEBUG, "[zedcup] Released cluster lock: ", key) end return true end _M.cluster.release = release_cluster_lock local function acquire_worker_lock(key, ttl) if not key or type(key) ~= "string" then return error("[zedcup] Attempted to acquire worker lock with bad key") end local global_config = zedcup.config() if not global_config then return nil, "Could not retrieve zedcup config" end local pid = ngx_worker_pid() local dict = GLOBALS.dicts["locks"] if not dict then error("[zedcup] could not find dict") end ttl = ttl or global_config.worker_lock_ttl key = "zedcup_worker_lock_"..key local lock, err = dict:add(key, pid, ttl) if lock then if DEBUG then ngx_log(ngx_DEBUG, "[zedcup] Acquired worker lock: ", key) end return true end if err == 'exists' then if DEBUG then ngx_log(ngx_DEBUG, "[zedcup] Missed worker lock: ", key) end return false else ngx_log(ngx_WARN, "[zedcup] Could not add worker lock key ", key, ": ", err) return false end end _M.worker.acquire = acquire_worker_lock local function release_worker_lock(key) if not key or type(key) ~= "string" then return error("[zedcup] Attempted to release worker lock with bad key") end local dict = GLOBALS.dicts["locks"] if not dict then error("[zedcup] could not find dict") end key = "zedcup_worker_lock_"..key local pid, err = dict:get(key) if not pid then return false, err end if pid == ngx_worker_pid() then local ok, err = dict:delete(key) if not ok then ngx_log(ngx_ERR, "[zedcup] Failed to delete key '", key, "': ", err) return false end return true end return false end _M.worker.release = release_worker_lock return _M
local _, AddonToolkitModule = ... local _, AddonToolkit = AddonToolkitModule.AddOn(...) local _, Method = AddonToolkit.Module("Method") local format = import("string").format local ipairs = import("ipairs") local table = import("table") local pairs = import("pairs") local setmetatable = import("setmetatable") local next = import("next") local type = import("type") local unpack = import("unpack") -- Schema for self-documenting function usage using metatables with __call to -- add arg definition processing/help text local function usage_message(function_table) local msg = format("Usage: %s({", function_table.name) for i, required_arg in ipairs(function_table.required_arguments) do msg = msg .. format("%s=%s, ", required_arg, i) end for arg, default_value in pairs(function_table.default_arguments) do msg = msg .. format("[%s=<%s>]", arg, default_value) end return msg .. "})" end local function usage_error_message(function_table, args, missing_args) return format("Invalid call to function_table %s. Got args %s. Usage: %s", function_table.name, args, function_table.usage ) end local function shallow_copy(object) if type(object) == "table" then local copy = {} -- Don't improperly use the __pairs metamethod in Lua 5.2 for key, value in next, object do copy[key] = value end return copy end -- Most values in Lua are immutable return object end local function parse_args(function_table, args) args = args or {} local missing_required_args = {} -- FinalArgs consists of all required and default arguments. local final_args = {} for _, required_arg in ipairs(function_table.required_arguments) do if args[required_arg] == nil then table.insert(missing_required_args, required_arg) else final_args[required_arg] = args[required_arg] end end if next(missing_required_args) then error(usage_error_message(function_table, args, missing_required_args), 2) end for arg, default in pairs(function_table.default_arguments) do if args[arg] == nil then final_args[arg] = default else final_args[arg] = args[arg] end end local varargs = {} for _, v in ipairs(args) do table.insert(varargs, v) end return final_args, varargs end local function_metatable = { __call = function(function_table, a, b, c) if c ~= nil then error("You specified too many arguments for " .. function_table.name .. ". Specify arguments using an argument table!") end local self, args = nil, nil if a ~= nil and b ~= nil then self = a args = b elseif b == nil then args = a else error(format("Error when calling function %s. Got %s, %s. " .. "You must always specify args, and can optionally specify self", function_table.name, tostring(a), tostring(b) )) end local parsed_args, varargs = parse_args(function_table, args) if self then return function_table.impl(self, parsed_args, unpack(varargs)) end return function_table.impl(parsed_args, unpack(varargs)) end, __tostring = function(function_table) return format("<Function: %s>", function_table.name) end } local function method(args) if not args.name or not args.impl then error("Must specify function name and impl") end local function_table = { name = args.name, required_arguments = args.required_arguments or {}, default_arguments = args.default_arguments or {}, impl = args.impl, } function_table.usage = usage_message(function_table) return setmetatable(function_table, function_metatable) end export("method", method)
aurum_hand = {} local function hand_dig(time) return {times = {[3] = time}, uses = 0, maxlevel = 0} end aurum_hand.def = { wield_image = "wieldhand.png", wield_scale = vector.new(1, 1, 2.5), tool_capabilities = { full_punch_interval = 0.9, max_drop_level = 0, groupcaps = { dig_handle = { times = { [1] = 2, [2] = 1.5, [3] = 0.5, }, uses = 0, maxlevel = 3, }, dig_long_handle = { times = { [1] = 15, [2] = 10, [3] = 5, }, uses = 0, maxlevel = 3, }, -- The hand can dig the lowest levels of all other groups, but slowly. dig_pick = hand_dig(6), dig_chop = hand_dig(3), dig_dig = hand_dig(1.5), dig_snap = hand_dig(0.5), }, damage_groups = { impact = 1, }, }, groups = {not_in_creative_inventory = 1, tool_hand = 1, tool = 1}, _enchant_levels = 2, _enchants = {"hand"}, } minetest.register_tool(":", b.t.combine(aurum_hand.def, { type = "none", }))
function init() setName("Blur") setDesc("Blurs texture") setSize(100, 24+64+8+8+18+7+4) addOutput(24+32) addInput("Texture", 24+64+8+8) addParameter("Intensity", "Blur intensity", 24+64+8+8+18, 10, 0, 100, true) end function apply() tileSize = getTileSize() intensity = getValue(1, 0, 0, 100.0) radius = math.floor(tileSize*intensity) kernel = { } a = 1.0/(2.0*radius*radius) b = 1.0/(math.sqrt(2.0*math.pi)*radius) c = 1.0 r = -radius total = 0 for i=0, radius*2 do x = r*r kernel[i] = b*math.exp(-x*b) total = total+kernel[i] r = r+1 end for i=0, radius*2 do kernel[i] = kernel[i]/total if radius==0 then kernel[i] = 1 end end blurr = { } blurg = { } blurb = { } for i=0, tileSize*tileSize-1 do x = i%tileSize y = math.floor(i/tileSize) sumr = 0; sumg = 0; sumb = 0; for bx=0, radius*2 do cr, cg, cb = getValue(0, x-radius+bx, y, 1.0) sumr = sumr+cr*kernel[bx] sumg = sumg+cg*kernel[bx] sumb = sumb+cb*kernel[bx] end blurr[i] = sumr blurg[i] = sumg blurb[i] = sumb end for i=0, tileSize*tileSize-1 do x = i%tileSize y = math.floor(i/tileSize) sumr = 0; sumg = 0; sumb = 0; for by=0, radius*2 do ny = y-radius+by while ny<0 do ny=ny+tileSize end while ny>=tileSize do ny=ny-tileSize end index = ny*tileSize+x cr = blurr[index] cg = blurg[index] cb = blurb[index] sumr = sumr+cr*kernel[by] sumg = sumg+cg*kernel[by] sumb = sumb+cb*kernel[by] end setPixel(0, x, y, sumr, sumg, sumb) end end
object_tangible_painting_painting_corl_01 = object_tangible_painting_shared_painting_corl_01:new { } ObjectTemplates:addTemplate(object_tangible_painting_painting_corl_01, "object/tangible/painting/painting_corl_01.iff")
AddTask("Badlands", { locks={LOCKS.ADVANCED_COMBAT,LOCKS.MONSTERS_DEFEATED,LOCKS.TIER4}, keys_given={KEYS.HOUNDS,KEYS.TIER5, KEYS.ROCKS}, room_choices={ ["Lightning"] = 1, ["Badlands"] = 3, ["HoundyBadlands"] = 2, ["BarePlain"] = 1, ["BuzzardyBadlands"] = 2, }, room_bg=GROUND.DIRT, background_room="BGBadlands", colour={r=1,g=0.6,b=1,a=1}, }) AddTask("Oasis", { locks={LOCKS.ADVANCED_COMBAT,LOCKS.TIER4, LOCKS.MONSTERS_DEFEATED}, keys_given={KEYS.ROCKS, KEYS.TIER5}, room_choices={ ["Badlands"] = 3, ["PondyGrass"] = 1, ["BuzzardyBadlands"] = 2, }, room_bg=GROUND.DIRT, background_room="BGBadlands", colour={r=.05,g=.5,b=.05,a=1}, })
function love.conf(t) t.identity = nil t.version = "0.10.2" t.console = false t.accelerometerjoystick = false t.externalstorage = false t.gammacorrect = false t.window.title = "PlaceTool" t.window.icon = nil t.window.width = 0 t.window.height = 0 t.window.borderless = false t.window.resizable = true t.window.minwidth = 400 t.window.minheight = 300 t.window.fullscreen = false t.window.fullscreentype = "desktop" t.window.vsync = false t.window.msaa = 0 t.window.display = 1 t.window.highdpi = false t.window.x = nil t.window.y = nil t.modules.audio = false t.modules.event = true t.modules.graphics = true t.modules.image = true t.modules.joystick = false t.modules.keyboard = true t.modules.math = true t.modules.mouse = true t.modules.physics = true t.modules.sound = false t.modules.system = true t.modules.timer = true t.modules.touch = true t.modules.video = true t.modules.window = true t.modules.thread = true 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 releasePlayer(cid) if not Player(cid) then return end npcHandler:releaseFocus(cid) npcHandler:resetNpc(cid) end local function creatureSayCallback(cid, type, msg) if not npcHandler:isFocused(cid) then return false end local player = Player(cid) if msgcontains(msg, 'mission') then if player:getLevel() < 35 then npcHandler:say('Indeed there is something to be done, but I need someone more experienced. Come back later if you want to.', cid) addEvent(releasePlayer, 1000, cid) return true end if player:getStorageValue(Storage.TibiaTales.IntoTheBonePit) == -1 then npcHandler:say({ 'Indeed, there is something you can do for me. You must know I am researching for a new spell against the undead. ...', 'To achieve that I need a desecrated bone. There is a cursed bone pit somewhere in the dungeons north of Thais where the dead never rest. ...', 'Find that pit, dig for a well-preserved human skeleton and conserve a sample in a special container which you receive from me. Are you going to help me?' }, cid) npcHandler.topic[cid] = 1 elseif player:getStorageValue(Storage.TibiaTales.IntoTheBonePit) == 1 then npcHandler:say({ 'The rotworms dug deep into the soil north of Thais. Rumours say that you can access a place of endless moaning from there. ...', 'No one knows how old that common grave is but the people who died there are cursed and never come to rest. A bone from that pit would be perfect for my studies.' }, cid) addEvent(releasePlayer, 1000, cid) elseif player:getStorageValue(Storage.TibiaTales.IntoTheBonePit) == 2 then player:setStorageValue(Storage.TibiaTales.IntoTheBonePit, 3) if player:removeItem(4864, 1) then player:addItem(6300, 1) npcHandler:say('Excellent! Now I can try to put my theoretical thoughts into practice and find a cure for the symptoms of undead. Here, take this for your efforts.', cid) else npcHandler:say({ 'I am so glad you are still alive. Benjamin found the container with the bone sample inside. Fortunately, I inscribe everything with my name, so he knew it was mine. ...', 'I thought you have been haunted and killed by the undead. I\'m glad that this is not the case. Thank you for your help.' }, cid) end addEvent(releasePlayer, 1000, cid) else npcHandler:say('I am very glad you helped me, but I am very busy at the moment.', cid) addEvent(releasePlayer, 1000, cid) end elseif msgcontains(msg, 'yes') then if npcHandler.topic[cid] == 1 then player:addItem(4863, 1) player:setStorageValue(Storage.TibiaTales.IntoTheBonePit, 1) npcHandler:say({ 'Great! Here is the container for the bone. Once, I used it to collect ectoplasma of ghosts, but it will work here as well. ...', 'If you lose it, you can buy a new one from the explorer\'s society in North Port or Port Hope. Ask me about the mission when you come back.' }, cid) addEvent(releasePlayer, 1000, cid) end elseif msgcontains(msg, 'no') then if npcHandler.topic[cid] == 1 then npcHandler:say('Ohh, then I need to find another adventurer who wants to earn a great reward. Bye!', cid) addEvent(releasePlayer, 1000, cid) end end return true end npcHandler:setMessage(MESSAGE_GREET, 'Greetings, |PLAYERNAME|! Looking for wisdom and power, eh?') npcHandler:setMessage(MESSAGE_FAREWELL, 'Farewell.') npcHandler:setMessage(MESSAGE_WALKAWAY, 'Farewell.') npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:addModule(FocusModule:new())
local SourceSkyname = GetConVar("sv_skyname"):GetString() --We need the source of the maps original skybox texture so we can manipulate it. local SourceSkyPre = {"lf","ft","rt","bk","dn","up",} local SourceSkyMat = { Material("skybox/"..SourceSkyname.."lf"), Material("skybox/"..SourceSkyname.."ft"), Material("skybox/"..SourceSkyname.."rt"), Material("skybox/"..SourceSkyname.."bk"), Material("skybox/"..SourceSkyname.."dn"), Material("skybox/"..SourceSkyname.."up"), } function ChangeSkybox(skyboxname) for i = 1,6 do local D = Material("skybox/"..skyboxname..SourceSkyPre[i]):GetTexture("$basetexture") SourceSkyMat[i]:SetTexture("$basetexture",D) end end
-- access_limit_frequency_token_bucket.lua local limit_frequency_token_bucket = require "limit_frequency_token_bucket" -- 对于内部重定向或子请求,不进行限制。因为这些并不是真正对外的请求。 if ngx.req.is_internal() then return end limit_frequency_token_bucket.incoming()
local utils = {} -- This function transform timestamp from sec/millisec into microseconds for Device2 format compatibility function utils.getTimestamp(timestamp) if not timestamp then return os.time(os.date("!*t")) * 1000000 elseif type(timestamp) ~= "number" then return os.time(os.date("!*t")) * 1000000 -- Could parse string? elseif timestamp < 100000000000 then return timestamp * 1000000 elseif timestamp < 100000000000000 then return timestamp * 1000 end return timestamp end return utils
-- CONST.OPH version 1.10 -- Constants for OPL -- Last edited on 19 May 1997 -- (C) Copyright Psion PLC 1997 -- General constants -- 2022-01-18: Formatting and minor modifications by tomsci KTrue = -1 KFalse = 0 -- Special keys KKeyEsc = 27 KKeySpace = 32 KKeyDel = 8 KKeyTab = 9 KKeyEnter = 13 KGetMenu = 4150 KKeyUpArrow = 4105 KKeyDownArrow = 4106 KKeyLeftArrow = 4103 KKeyRightArrow = 4104 KKeyPageUp = 4100 KKeyPageDown = 4101 KKeyPageLeft = 4098 KKeyPageRight = 4099 -- Month numbers KJanuary = 1 KFebruary = 2 KMarch = 3 KApril = 4 KMay = 5 KJune = 6 KJuly = 7 KAugust = 8 KSeptember = 9 KOctober = 10 KNovember = 11 KDecember = 12 -- Graphics KDefaultWin = 1 KgModeSet = 0 KgModeClear = 1 KgModeInvert = 2 KtModeSet = 0 KtModeClear = 1 KtModeInvert = 2 KtModeReplace = 3 KgStyleNormal = 0 KgStyleBold = 1 KgStyleUnder = 2 KgStyleInverse = 4 KgStyleDoubleHeight = 8 KgStyleMonoFont = 16 KgStyleItalic = 32 -- For 32-bit status words IOWAIT and IOWAITSTAT32 -- Use KErrFilePending (-46) for 16-bit status words -- KStatusPending32 = 0x80000001 -- Error codes KErrGenFail = -1 KErrInvalidArgs = -2 KErrOs = -3 KErrNotSupported = -4 KErrUnderflow = -5 KErrOverflow = -6 KErrOutOfRange = -7 KErrDivideByZero = -8 KErrInUse = -9 KErrNoMemory = -10 KErrNoSegments = -11 KErrNoSemaphore = -12 KErrNoProcess = -13 KErrAlreadyOpen = -14 KErrNotOpen = -15 KErrImage = -16 KErrNoReceiver = -17 KErrNoDevices = -18 KErrNoFileSystem = -19 KErrFailedToStart = -20 KErrFontNotLoaded = -21 KErrTooWide = -22 KErrTooManyItems = -23 KErrBatLowSound = -24 KErrBatLowFlash = -25 KErrExists = -32 KErrNotExists = -33 KErrWrite = -34 KErrRead = -35 KErrEof = -36 KErrFull = -37 KErrName = -38 KErrAccess = -39 KErrLocked = -40 KErrDevNotExist = -41 KErrDir = -42 KErrRecord = -43 KErrReadOnly = -44 KErrInvalidIO = -45 KErrFilePending = -46 KErrVolume = -47 KErrIOCancelled = -48 -- OPL specific errors KErrSyntax = -77 KOplStructure = -85 KErrIllegal = -96 KErrNumArg = -97 KErrUndef = -98 KErrNoProc = -99 KErrNoFld = -100 KErrOpen = -101 KErrClosed = -102 KErrRecSize = -103 KErrModLoad = -104 KErrMaxLoad = -105 KErrNoMod = -106 KErrNewVer = -107 KErrModNotLoaded = -108 KErrBadFileType = -109 KErrTypeViol = -110 KErrSubs = -111 KErrStrTooLong = -112 KErrDevOpen = -113 KErrEsc = -114 KErrMaxDraw = -117 KErrDrawNotOpen = -118 KErrInvalidWindow = -119 KErrScreenDenied = -120 KErrOpxNotFound = -121 KErrOpxVersion = -122 KErrOpxProcNotFound = -123 KErrStopInCallback = -124 KErrIncompUpdateMode = -125 KErrInTransaction = -126 -- For ALERT KAlertEsc = 1 KAlertEnter = 2 KAlertSpace = 3 -- For BUSY and GIPRINT KBusyTopLeft = 0 KBusyBottomLeft = 1 KBusyTopRight = 2 KBusyBottomRight = 3 KBusyMaxText = 80 -- For CMD$ KCmdAppName = 1 -- Full path name used to start program KCmdUsedFile = 2 KCmdLetter = 3 -- For CMD$(3) KCmdLetterCreate = "C" KCmdLetterOpen = "O" KCmdLetterRun = "R" -- For CURSOR KCursorTypeNotFlashing = 2 KCursorTypeGrey = 4 -- For DATIM$ - offsets KDatimOffDayName = 1 KDatimOffDay = 5 KDatimOffMonth = 8 KDatimOffYear = 12 KDatimOffHour = 17 KDatimOffMinute = 20 KDatimOffSecond = 23 -- For dBUTTON KDButtonNoLabel = 0x100 KDButtonPlainKey = 0x200 KDButtonDel = 8 KDButtonTab = 9 KDButtonEnter = 13 KDButtonEsc = 27 KDButtonSpace = 32 -- For dEDITMULTI and printing KParagraphDelimiter = 0x06 KLineBreak = 0x07 KPageBreak = 0x08 KTabCharacter = 0x09 KNonBreakingTab = 0x0a KNonBreakingHyphen = 0x0b KPotentialHyphen = 0x0c KNonBreakingSpace = 0x10 KPictureCharacter = 0x0e KVisibleSpaceCharacter = 0x0f -- For DEFAULTWIN KDefWin4ColourMode = 1 KDefWin16ColourMode = 2 -- For dFILE KDFileNameLen = 255 -- flags KDFileEditBox = 0x0001 KDFileAllowFolders = 0x0002 KDFileFoldersOnly = 0x0004 KDFileEditorDisallowExisting = 0x0008 KDFileEditorQueryExisting = 0x0010 KDFileAllowNullStrings = 0x0020 KDFileAllowWildCards = 0x0080 KDFileSelectorWithRom = 0x0100 KDFileSelectorWithSystem = 0x0200 -- Opl-related Uids for dFILE KUidDirectFileStore = 0x10000037 -- tomsci: conflicts KUidOplInterpreter = 0x10000077 KUidOplApp = 0x10000074 KUidOplDoc = 0x10000075 KUidOPO = 0x10000073 KUidOplFile = 0x1000008A KUidOpxDll = 0x1000005D -- For DIALOG KDlgCancel = 0 -- For dINIT (flags for dialogs) KDlgButRight = 1 KDlgNoTitle = 2 KDlgFillScreen = 4 KDlgNoDrag = 8 KDlgDensePack = 16 -- For DOW KMonday = 1 KTuesday = 2 KWednesday = 3 KThursday = 4 KFriday = 5 KSaturday = 6 KSunday = 7 -- For dPOSITION KDPositionLeft = -1 KDPositionCentre = 0 KDPositionRight = 1 -- For dTEXT KDTextLeft = 0 KDTextRight = 1 KDTextCentre = 2 KDTextBold = 0x100 -- Ignored in Eikon KDTextLineBelow = 0x200 KDTextAllowSelection = 0x400 KDTextSeparator = 0x800 -- For dTIME KDTimeAbsNoSecs = 0 KDTimeAbsWithSecs = 1 KDTimeDurationNoSecs = 2 KDTimeDurationWithSecs = 3 -- Flags for dTIME (for ORing combinations) KDTimeWithSeconds = 1 KDTimeDuration = 2 KDTimeNoHours = 4 KDTime24Hour = 8 -- For dXINPUT KDXInputMaxLen = 16 -- For FINDFIELD KFindCaseDependent = 16 KFindBackwards = 0 KFindForwards = 1 KFindBackwardsFromEnd = 2 KFindForwardsFromStart = 3 -- For FLAGS KFlagsAppFileBased = 1 KFlagsAppIsHidden = 2 -- For gBORDER and gXBORDER KBordSglShadow = 1 KBordSglGap = 2 KBordDblShadow = 3 KBordDblGap = 4 KBordGapAllRound = 0x100 KBordRoundCorners = 0x200 KBordLosePixel = 0x400 -- For gBUTTON KButtS3 = 0 KButtS3Raised = 0 KButtS3Pressed = 1 KButtS3a = 1 KButtS3aRaised = 0 KButtS3aSemiPressed = 1 KButtS3aSunken = 2 KButtS5 = 2 KButtS5Raised = 0 KButtS5SemiPressed = 1 KButtS5Sunken = 2 KButtLayoutTextRightPictureLeft = 0 KButtLayoutTextBottomPictureTop = 1 KButtLayoutTextTopPictureBottom = 2 KButtLayoutTextLeftPictureRight = 3 KButtTextRight = 0 KButtTextBottom = 1 KButtTextTop = 2 KButtTextLeft = 3 KButtExcessShare = 0x00 KButtExcessToText = 0x10 KButtExcessToPicture = 0x20 -- For gCLOCK KgClockS5System = 6 KgClockS5Analog = 7 KgClockS5Digital = 8 KgClockS5LargeAnalog = 9 KgClockS5Formatted = 11 -- For gCREATE KgCreateInvisible = 0 KgCreateVisible = 1 KgCreateHasShadow = 0x0010 -- tomsci: updated -- Color mode constants KgCreate2GrayMode = 0x0000 KgCreate4GrayMode = 0x0001 KgCreate16GrayMode = 0x0002 KgCreate256GrayMode = 0x0003 KgCreate16ColorMode = 0x0004 KgCreate256ColorMode = 0x0005 KgCreate64KColorMode = 0x0006 KgCreate16MColorMode = 0x0007 KgCreateRGBColorMode = 0x0008 KgCreate4KColorMode = 0x0009 -- For GETCMD$ KGetCmdLetterCreate = "C" KGetCmdLetterOpen = "O" KGetCmdLetterExit = "X" KGetCmdLetterUnknown = "U" -- For gLOADBIT KgLoadBitReadOnly = 0 KgLoadBitWriteable = 1 -- For gRANK KgRankForeground = 1 KgRankBackGround = 32767 -- For gPOLY - array subscripts KgPolyAStartX = 1 KgPolyAStartY = 2 KgPolyANumPairs = 3 KgPolyANumDx1 = 4 KgPolyANumDy1 = 5 -- For gPRINTB KgPrintBRightAligned = 1 KgPrintBLeftAligned = 2 KgPrintBCentredAligned = 3 -- The defaults KgPrintBDefAligned = KgPrintBLeftAligned KgPrintBDefTop = 0 KgPrintBDefBottom = 0 KgPrintBDefMargin = 0 -- For gXBORDER KgXBorderS3Type = 0 KgXBorderS3aType = 1 KgXBorderS5Type = 2 -- For gXPRINT KgXPrintNormal = 0 KgXPrintInverse = 1 KgXPrintInverseRound = 2 KgXPrintThinInverse = 3 KgXPrintThinInverseRound = 4 KgXPrintUnderlined = 5 KgXPrintThinUnderlined = 6 -- For KMOD KKmodShift = 2 KKmodControl = 4 KKmodPsion = 8 KKmodCaps = 16 KKmodFn = 32 -- For mCARD and mCASC KMenuDimmed = 0x1000 KMenuSymbolOn = 0x2000 KMenuSymbolIndeterminate = 0x4000 KMenuCheckBox = 0x0800 KMenuOptionStart = 0x0900 KMenuOptionMiddle = 0x0A00 KMenuOptionEnd = 0x0B00 -- For mPOPUP position type -- Specifies which corner of the popup is given by the coordinates KMPopupPosTopLeft = 0 KMPopupPosTopRight = 1 KMPopupPosBottomLeft = 2 KMPopupPosBottomRight = 3 -- For PARSE$ - array subscripts KParseAOffFSys = 1 KParseAOffDev = 2 KParseAOffPath = 3 KParseAOffFilename = 4 KParseAOffExt = 5 KParseAOffWild = 6 -- Wild-card flags KParseWildNone = 0 KParseWildFilename = 1 KParseWildExt = 2 KParseWildBoth = 3 -- For SCREENINFO - array subscripts KSInfoALeft = 1 KSInfoATop = 2 KSInfoAScrW = 3 KSInfoAScrH = 4 KSInfoAReserved1 = 5 KSInfoAFont = 6 KSInfoAPixW = 7 KSInfoAPixH = 8 KSInfoAReserved2 = 9 KSInfoAReserved3 = 10 -- For SETFLAGS KRestrictTo64K = 0x0001 KAutoCompact = 0x0002 KTwoDigitExponent = 0x0004 KSendSwitchOnMessage = 0x010000 -- For GetEvent32 -- Array indexes KEvAType = 1 KEvATime = 2 -- Event array keypress subscripts KEvAKMod = 4 KEvAKRep = 5 -- Pointer event array subscripts KEvAPtrOplWindowId = 3 KEvAPtrWindowId = 3 KEvAPtrType = 4 KEvAPtrModifiers = 5 KEvAPtrPositionX = 6 KEvAPtrPositionY = 7 KEvAPtrScreenPosX = 8 KEvAPtrScreenPosY = 9 -- Event types KEvNotKeyMask = 0x400 KEvFocusGained = 0x401 KEvFocusLost = 0x402 KEvSwitchOn = 0x403 KEvCommand = 0x404 KEvDateChanged = 0x405 KEvKeyDown = 0x406 KEvKeyUp = 0x407 KEvPtr = 0x408 KEvPtrEnter = 0x409 KEvPtrExit = 0x40A -- Pointer event types KEvPtrPenDown = 0 KEvPtrPenUp = 1 KEvPtrButton1Down = KEvPtrPenDown KEvPtrButton1Up = KEvPtrPenUp KEvPtrButton2Down = 2 KEvPtrButton2Up = 3 KEvPtrButton3Down = 4 KEvPtrButton3Up = 5 KEvPtrDrag = 6 KEvPtrMove = 7 KEvPtrButtonRepeat = 8 KEvPtrSwitchOn = 9 KKeyMenu = 4150 KKeySidebarMenu = 10000 -- For PointerFilter KPointerFilterEnterExit = 0x1 KPointerFilterMove = 0x2 KPointerFilterDrag = 0x4 -- Code page 1252 ellipsis (“windows latin 1") KScreenEllipsis = 133 KScreenLineFeed = 10 -- For gCLOCK KClockLocaleConformant = 6 KClockSystemSetting = KClockLocaleConformant KClockAnalog = 7 KClockDigital = 8 KClockLargeAnalog = 9 -- GClock 10 no longer supported (use slightly changed gCLOCK 11) KClockFormattedDigital = 11 -- For gFONT -- tomsci: UIDs converted with lua -e "for line in io.lines() do print((line:gsub('(%s+)([0-9]+)%s*', function(s, m) return string.format('%s0x%08X', s, tonumber(m)) end))) end" KFontArialBold8 = 0x100001EF KFontArialBold11 = 0x100001F0 KFontArialBold13 = 0x100001F1 KFontArialNormal8 = 0x100001F2 KFontArialNormal11 = 0x100001F3 KFontArialNormal13 = 0x100001F4 KFontArialNormal15 = 0x100001F5 KFontArialNormal18 = 0x100001F6 KFontArialNormal22 = 0x100001F7 KFontArialNormal27 = 0x100001F8 KFontArialNormal32 = 0x100001F9 KFontTimesBold8 = 0x100001FA KFontTimesBold11 = 0x100001FB KFontTimesBold13 = 0x100001FC KFontTimesNormal8 = 0x100001FD KFontTimesNormal11 = 0x100001FE KFontTimesNormal13 = 0x100001FF KFontTimesNormal15 = 0x10000200 KFontTimesNormal18 = 0x10000201 KFontTimesNormal22 = 0x10000202 KFontTimesNormal27 = 0x10000203 KFontTimesNormal32 = 0x10000204 KFontCourierBold8 = 0x1000025E KFontCourierBold11 = 0x1000025F KFontCourierBold13 = 0x10000260 KFontCourierNormal8 = 0x10000261 KFontCourierNormal11 = 0x10000262 KFontCourierNormal13 = 0x10000263 KFontCourierNormal15 = 0x10000264 KFontCourierNormal18 = 0x10000265 KFontCourierNormal22 = 0x10000266 KFontCourierNormal27 = 0x10000267 KFontCourierNormal32 = 0x10000268 KFontTiny4 = 0x10000030 KFontEiksym15 = 0x100000CD KFontSquashed = 0x100000F5 KFontDigital35 = 0x10000128 -- For IOOPEN -- Mode category 1 KIoOpenModeOpen = 0x0000 KIoOpenModeCreate = 0x0001 KIoOpenModeReplace = 0x0002 KIoOpenModeAppend = 0x0003 KIoOpenModeUnique = 0x0004 -- Mode category 2 KIoOpenFormatBinary = 0x0000 KIoOpenFormatText = 0x0020 -- Mode category 3 KIoOpenAccessUpdate = 0x0100 KIoOpenAccessRandom = 0x0200 KIoOpenAccessShare = 0x0400 -- tomsci: added -- For IOSEEK KIoSeekFromStart = 1 KIoSeekFromEnd = 2 KIoSeekFromCurrent = 3 KIoSeekFirstRecord = 6 -- Language code for CAPTION KLangEnglish = 1 KLangFrench = 2 KLangGerman = 3 KLangSpanish = 4 KLangItalian = 5 KLangSwedish = 6 KLangDanish = 7 KLangNorwegian = 8 KLangFinnish = 9 KLangAmerican = 10 KLangSwissFrench = 11 KLangSwissGerman = 12 KLangPortuguese = 13 KLangTurkish = 14 KLangIcelandic = 15 KLangRussian = 16 KLangHungarian = 17 KLangDutch = 18 KLangBelgianFlemish = 19 KLangAustralian = 20 KLangBelgianFrench = 21 KLangAustrian = 22 KLangNewZealand = 23 KLangInternationalFrench = 24
local ingredient_dialog = {} toggle_ingredients_chat = true ingredient_said = false ingredient_dialog["pln_rt1_12"] = "Zutat hinzugefügt" --Comment out the parts of the script you dont want in chat by adding two dashes at the start of the line ingredient_dialog["pln_rt1_20"] = "Füge Salzsäure zu" --Commenting these parts out will stop them from being shown in game ingredient_dialog["pln_rt1_22"] = "Füge Ätznatron zu" ingredient_dialog["pln_rt1_24"] = "Füge Chlorwasserstoff zu" ingredient_dialog["pln_rt1_28"] = "Meth ist fertig" ingredient_dialog["pln_rat_stage1_20"] = "Füge Salzsäure zu" ingredient_dialog["pln_rat_stage1_22"] = "Füge Ätznatron zu" ingredient_dialog["pln_rat_stage1_24"] = "Füge Chlorwasserstoff zu" ingredient_dialog["pln_rat_stage1_28"] = "Meth ist fertig" local _queue_dialog_orig = DialogManager.queue_dialog function DialogManager:queue_dialog(id, ...) if ingredient_dialog[id] == last_ingredient then ingredient_said = true else ingredient_said = false end if ingredient_dialog[id] and toggle_ingredients_chat and not ingredient_said then managers.chat:send_message(ChatManager.GAME, managers.network.account:username() or "Offline", ingredient_dialog[id]) --Comment this out to stop messages being sent in chat last_ingredient = ingredient_dialog[id] elseif ingredient_dialog[id] and not toggle_ingredients_chat then managers.hud:show_hint({text = ingredient_dialog[id]}) last_ingredient = ingredient_dialog[id] end if ingredient_dialog[id] == "Füge Salzsäure zu" or ingredient_dialog[id] == "Füge Ätznatron zu" or ingredient_dialog[id] == "Füge Chlorwasserstoff zu" then ingredient_said = true end return _queue_dialog_orig(self, id, ...) end
-------------------------------------------------------------------------------- -- modules that extend functionality of the table. -------------------------------------------------------------------------------- local M = {} -------------------------------------------------------------------------------- -- Returns the position found by searching for a matching value from the array. -- @param array table array -- @param value Search value -- @return If one is found the index. 0 if not found. -------------------------------------------------------------------------------- function M.indexOf(array, value) for i, v in ipairs(array) do if v == value then return i end end return 0 end function M.concat(...) local dest = {} local args = {...} for i, t in ipairs(args) do for j, v in ipairs(src) do dest[#dest + 1] = v end end return dest end function M.reverse(t) local dest = {} local size = #t for i = 1, size do dest[i] = t[size - i + 1] end return dest end -------------------------------------------------------------------------------- -- Adds an element to the table. -- If the element was present, the element will return false without the need for additional. -- If the element does not exist, and returns true add an element. -- @param t table -- @param o element -- @return If it already exists, false. If you add is true. -------------------------------------------------------------------------------- function M.insertElement(t, o) if M.indexOf(t, o) > 0 then return false end M.insert(t, o) return true end -------------------------------------------------------------------------------- -- This removes the element from the table. -- If you have successfully removed, it returns the index of the yuan. -- If there is no element, it returns 0. -- @param t table -- @param o element -- @return index -------------------------------------------------------------------------------- function M.removeElement(t, o) local i = M.indexOf(t, o) if i == 0 then return 0 end M.remove(t, i) return i end return M
function love.conf(t) t.title = "miko lovejam intro" t.author = "miko" t.identity = "mario" t.screen.width = 800 t.screen.height = 600 end
local level = require "game/level" local camera = require "game/camera" local game = { dt = 0 } function game:load() for i = 1, #e do e.delete(i) end level:load("res/levels/0.png") res.sound.ambience:play() love.window.setMode(200, 500, {fullscreen=true, msaa=0}) self.camera = camera(800, 400, 1, 1, 0) self.background_hue = 0 self.background_delta = -1 end function game:update(dt) self.dt = dt s(s.sound, s.player, s.inputReset) end function game:draw() love.graphics.setBackgroundColor(0, 0, 0) self.camera:set() love.graphics.setShader(effect) s(s.block, s.sprite, s.debug) self.camera:unset() end return game
local util = require('util') local item = { type = "item", name = "train-scaling-stop", icon = "__train-scaling__/graphics/icons/train-scaling-stop.png", icon_size = 32, flags = {}, subgroup = "transport", order = "a[train-system]-cz[train-scaling-stop]", place_result = "train-scaling-stop", stack_size = 10 } local recipe = { type = "recipe", name = "train-scaling-stop", enabled = false, ingredients = { {"train-stop", 1}, {"locomotive", 1}, {"advanced-circuit", 15}, }, result = "train-scaling-stop" } local technology = { type = "technology", name = "train-scaling", icon_size = 128, icon = "__base__/graphics/technology/railway.png", effects = { { type = "unlock-recipe", recipe = "train-scaling-stop" } }, prerequisites = { "rail-signals", "advanced-electronics" }, unit = { count = 500, ingredients = { {"automation-science-pack", 1}, {"logistic-science-pack", 1}, {"chemical-science-pack", 1}, }, time = 30 }, order = "c-g-c-z" } local entity = util.table.deepcopy(data.raw["train-stop"]["train-stop"]) entity.name = "train-scaling-stop" entity.color = {r = 1, g = 0.45, b = 0, a = 0.8} entity.icon = "__train-scaling__/graphics/icons/train-scaling-stop.png" entity.icon_size = 32 entity.minable.result = "train-scaling-stop" local player = util.table.deepcopy(data.raw["character"]["character"]) player.name = "train-scaling-driver" player.collision_mask = {"ghost-layer"} local signal_group = { type = "item-subgroup", name = "train-scaling-signal", group = "signals", order = "z[train-scaling-signal]" } local up_signal = { type = "virtual-signal", name = "signal-train-scale-up", icon = "__train-scaling__/graphics/icons/signal-train-scale-up.png", icon_size = 32, subgroup = "train-scaling-signal", order = "a[special]-a[train-scale-up]" } local down_signal = { type = "virtual-signal", name = "signal-train-scale-down", icon = "__train-scaling__/graphics/icons/signal-train-scale-down.png", icon_size = 32, subgroup = "train-scaling-signal", order = "a[special]-b[train-scale-down]" } data:extend({ item, recipe, entity, player, technology, signal_group, up_signal, down_signal })
--[=[ Useful utility functions involving CFrame values. @class CFrameUtils ]=] local UP = Vector3.new(0, 1, 0) local CFrameUtils = {} --[=[ Makes a CFrame look at a position and target with bias towards the upVector. ```lua -- orient a hypothetical gun such that it's relative to the root part's upVector local gunCFrame = CFrameUtils.lookAt(gunPos, gunTarget, rootPart.CFrame.upVector) ``` @param position Vector3 @param target Vector3 @param upVector Vector3? -- Optional, defaults to (0, 1, 0) @return CFrame ]=] function CFrameUtils.lookAt(position, target, upVector) upVector = upVector or UP local forwardVector = (position - target).Unit local rightVector = forwardVector:Cross(upVector) local upVector2 = rightVector:Cross(forwardVector) return CFrame.fromMatrix(position, rightVector, upVector2) end --[=[ Returns a CFrame which is minimally rotated from cframe such that the following condition is true: ``` returnedCFrame:VectorToWorldSpace(localAxis) = worldGoal ``` ```lua -- Redirects an axis from world space up, to a spawn block's up vector -- so we could spawn something there. cframe = CFrameUtils.redirectLocalAxis(cframe, Vector3.new(0, 1, 0), spawnBlock.CFrame.upVector) ``` @param cframe CFrame @param localAxis Vector3 @param worldGoal Vector3 @return CFrame ]=] function CFrameUtils.redirectLocalAxis(cframe, localAxis, worldGoal) local localGoal = cframe:VectorToObjectSpace(worldGoal) local m = localAxis.magnitude*localGoal.magnitude local d = localAxis:Dot(localGoal) local c = localAxis:Cross(localGoal) local R = CFrame.new(0, 0, 0, c.x, c.y, c.z, d + m) if R == R then return cframe*R else return cframe end end --[=[ Constructs a CFrame from a position, upVector, and rightVector even if these upVector and rightVectors are not orthogonal to each other. :::note upVector and rightVector do not need to be orthogonal. However, if they are parallel, this function returns nil. Always check to ensure that the value returned is reasonable before continuing. ::: @param position Vector3 @param upVector Vector3 @param rightVector Vector3 @return CFrame? ]=] function CFrameUtils.fromUpRight(position, upVector, rightVector) local forwardVector = rightVector:Cross(upVector) if forwardVector.magnitude == 0 then return nil end forwardVector = forwardVector.Unit local rightVector2 = forwardVector:Cross(upVector) return CFrame.fromMatrix(position, rightVector2, upVector) end --[=[ Scales just the positional part of a CFrame. @param cframe CFrame @param scale number @return CFrame ]=] function CFrameUtils.scalePosition(cframe, scale) if scale == 1 then return cframe else local position = cframe.p return cframe - position + position*scale end end return CFrameUtils
local toolName = "TNS|Crossfire setup|TNE" ---- ######################################################################### ---- # # ---- # Copyright (C) OpenTX # -----# # ---- # License GPLv2: http://www.gnu.org/licenses/gpl-2.0.html # ---- # # ---- # This program is free software; you can redistribute it and/or modify # ---- # it under the terms of the GNU General Public License version 2 as # ---- # published by the Free Software Foundation. # ---- # # ---- # This program is distributed in the hope that it will be useful # ---- # but WITHOUT ANY WARRANTY; without even the implied warranty of # ---- # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # ---- # GNU General Public License for more details. # ---- # # ---- ######################################################################### local devices = { } local lineIndex = 1 local pageOffset = 0 local function createDevice(id, name) local device = { id = id, name = name, timeout = 0 } return device end local function getDevice(name) for i=1, #devices do if devices[i].name == name then return devices[i] end end return nil end local function parseDeviceInfoMessage(data) local id = data[2] local name = "" local i = 3 while data[i] ~= 0 do name = name .. string.char(data[i]) i = i + 1 end local device = getDevice(name) if device == nil then device = createDevice(id, name) devices[#devices + 1] = device end local time = getTime() device.timeout = time + 3000 -- 30s if lineIndex == 0 then lineIndex = 1 end end local devicesRefreshTimeout = 0 local function refreshNext() local command, data = crossfireTelemetryPop() if command == nil then local time = getTime() if time > devicesRefreshTimeout then devicesRefreshTimeout = time + 100 -- 1s crossfireTelemetryPush(0x28, { 0x00, 0xEA }) end elseif command == 0x29 then parseDeviceInfoMessage(data) end end local function selectDevice(step) lineIndex = 1 + ((lineIndex + step - 1 + #devices) % #devices) end -- Init local function init() lineIndex = 0 pageOffset = 0 end -- Main local function run(event) if event == nil then error("Cannot be run as a model script!") return 2 elseif event == EVT_VIRTUAL_EXIT then return 2 elseif event == EVT_VIRTUAL_NEXT then selectDevice(1) elseif event == EVT_VIRTUAL_PREV then selectDevice(-1) end lcd.clear() lcd.drawScreenTitle("CROSSFIRE SETUP", 0, 0) if #devices == 0 then lcd.drawText(24, 28, "Waiting for Crossfire devices...") else for i=1, #devices do local attr = (lineIndex == i and INVERS or 0) if event == EVT_VIRTUAL_ENTER and attr == INVERS then crossfireTelemetryPush(0x28, { devices[i].id, 0xEA }) return "device.lua" end lcd.drawText(0, i*8+9, devices[i].name, attr) end end refreshNext() return 0 end return { init=init, run=run }
--[[// https://github.com/Rerumu/Rerumu-Parser \\]]-- local Encode, Decode, Extract; local SetMeta = setmetatable; local Tostring = tostring; local Tonumber = tonumber; local Concat = table.concat; local Gsub, Sub = string.gsub, string.sub; local Match = string.match; local Type = typeof; local Beat = game:GetService("RunService").Heartbeat local C3, V3, CF, Ray, Bri = Color3.new, Vector3.new, CFrame.new, Ray.new, BrickColor.new; -- Yell at me for this lengthy definition later. local U2, U, V2, Inew = UDim2.new, UDim.new, Vector2.new, Instance.new; local Pcall = pcall; -- Because I don't think listing everything individually would work, a bit of performance with memoization would help right? local Index = function(Ins, Prop) return Ins[Prop]; end; local Properties = setmetatable({}, { __index = function(self, ClassName) -- It's not neat to have to do many checks so I decided on this. local Got = {}; self[ClassName] = Got; return Got; end; __call = function(self, Instance, Property) -- Much neater to have both things here. local Found = self[Instance.ClassName][Property]; local R if (Found == nil) then Found, R = Pcall(Index, Instance, Property); self[Instance.ClassName][Property] = Found; return (Found and R) or nil; end; if Found then return Instance[Property]; end; end; }); -- Handles memoization of instance properties for performance boosts past 1st use. local PropertiesStored = { -- Was too lazy to list so you have fun. 'ClassName', 'Name'; -- Name of properties, for obvious reasons you will always need a ClassName property (creating instance). }; local EFormat, DFormat = {}, {}; local Backs = { {'\b', '\\b'}; {'\t', '\\t'}; {'\n', '\\n'}; {'\f', '\\f'}; {'\r', '\\r'}; {'"', '\\"'}; {'\\', '\\\\'}; }; for Idx = 1, #Backs do local Pair = Backs[Idx]; EFormat[Pair[1]] = Pair[2]; DFormat[Pair[2]] = Pair[1]; end; Backs = nil; local __tMemoize = { __index = function(self, String) local Res = Match(self[1], String); self[2] = Res; return Res; end; }; local function SafeString(String, EncStr) if EncStr then return (Gsub(String, '[\b\t\n\f\r\\"]', EFormat)); else return (Gsub(String, '\\.', DFormat)); end; end; function Extract(Data) local Mem = SetMeta({Data}, __tMemoize); if Mem['^%[.-%]$'] then -- Things are decoded here, feel free to add. return Decode(Mem[2]); elseif Mem['^"(.-)"$'] then return SafeString(Mem[2]); elseif Mem['^true$'] then return true; elseif Mem['^false$'] then return false; elseif (Mem['^I(%[.-%])$']) then local InstData = Decode(Mem[2]); local Inst = Inew(InstData.ClassName); local Children = InstData.Children; InstData.ClassName = nil; InstData.Children = nil; for Name, Value in next, InstData do Inst[Name] = Value; end; if Children then for _, Child in next, Children do Child.Parent = Inst; end; end; return Inst; elseif (Mem['^B%[(%d+)%]$']) then return Bri(Mem[2]); elseif (Mem['^R%[(.+)%]$']) then local A, B, C, X, Y, Z = Match(Mem[2], '(.+),(.+),(.+),(.+),(.+),(.+)'); return Ray(V3(A, B, C), V3(X, Y, Z)); elseif (Mem['^CF%[(.+)%]$']) then return CF(Match(Mem[2], '(.+),(.+),(.+),(.+),(.+),(.+),(.+),(.+),(.+),(.+),(.+),(.+)')); elseif (Mem['^V3%[(.+)%]$']) then return V3(Match(Mem[2], '(.+),(.+),(.+)')); elseif (Mem['^V2%[(.+)%]$']) then return V2(Match(Mem[2], '(.+),(.+)')); elseif (Mem['^C3%[(.+)%]$']) then return C3(Match(Mem[2], '(.+),(.+),(.+)')); elseif (Mem['^U2%[(.+)%]$']) then return U2(Match(Mem[2], '(.+),(.+),(.+),(.+)')); elseif (Mem['^U%[(.+)%]$']) then return U(Match(Mem[2], '(.+),(.+)')); else return Tonumber(Data); end; end; function Encode(Table, Buff) local Result = {}; local Buff = Buff or {}; for Index, Value in next, Table do local Idx, Val = '', 'null'; local ValT = Type(Value); if (Type(Index) == 'string') then Idx = Concat{'"', SafeString(Index, true), '":'}; end; if (ValT == 'number') or (ValT == 'boolean') then -- Things are encoded here; feel free to add. Val = Tostring(Value); elseif (ValT == 'string') then Val = Concat{'"', SafeString(Value, true), '"'}; elseif (ValT == 'table') and (not Buff[Value]) then Buff[Value] = true; Val = Encode(Value, Buff); elseif (ValT == 'Instance') then local Child = Value'GetChildren'; local Props = {}; for _, Name in next, PropertiesStored do Props[Name] = Properties(Value, Name); end; if (#Child ~= 0) then Props.Children = Child; end; Val = Concat{'I', Encode(Props)}; elseif (ValT == 'BrickColor') then Val = Concat{'B[', Value.Number, ']'}; elseif (ValT == 'Ray') then local Ori, Dir = Value.Origin, Value.Direction; Val = Concat{'R[', Concat({Ori.X, Ori.Y, Ori.Z, Dir.X, Dir.Y, Dir.Z}, ','), ']'}; elseif (ValT == 'CFrame') then Val = Concat{'CF[', Concat({Value:components()}, ','), ']'}; elseif (ValT == 'Vector3') then Val = Concat{'V3[', Concat({Value.X, Value.Y, Value.Z}, ','), ']'}; elseif (ValT == 'Vector2') then Val = Concat{'V2[', Value.X, ',', Value.Y, ']'}; elseif (ValT == 'Color3') then Val = Concat{'C3[', Concat({Value.r, Value.g, Value.b}, ','), ']'}; elseif (ValT == 'UDim2') then Val = Concat{'U2[', Concat({Value.X.Scale, Value.X.Offset, Value.Y.Scale, Value.Y.Offset}, ','), ']'}; elseif (ValT == 'UDim') then Val = Concat{'U[', Value.Scale, ',', Value.Offset, ']'}; end; Result[#Result + 1] = (Idx .. Val); end; return Concat{'[', Concat(Result, ';'), ']'}; end; function Decode(String) local Result = {}; local Tables = 0; local Len = #String; local Esc, Quo; local Layer; for Idx = 1, Len do local Char = Sub(String, Idx, Idx); if Layer then Layer[#Layer + 1] = Char; elseif (not Layer) and (Idx ~= 1) then Layer = {Char}; end; if (not Esc) then if (Char == '\\') then Esc = true; elseif (Char == '"') then Quo = (not Quo); elseif ((not Quo) and (Char == ';') and (Tables == 1)) or (Idx == Len) then local Lay = Concat(Layer); local Index = Match(Gsub(Lay, '\\"', ''), '^".-":.+$'); if Index then Index = false; for Idz = 2, #Layer do local Char = Layer[Idz]; if (not Index) then if (Char == '"') then Index = Idz - 1; break; else Index = (Char == '\\'); end; else Index = false; end; end; Result[SafeString(Sub(Lay, 2, Index))] = Extract(Sub(Lay, Index + 3, -2)); else Result[#Result + 1] = Extract(Sub(Lay, 1, -2)); end; Layer = nil; elseif (not Quo) then if (Char == '[') then Tables = Tables + 1; elseif (Char == ']') then Tables = Tables - 1; end; end; else Esc = false; end if Idx%300 == 0 then Beat:wait() end end; return Result; end; function noTabEncode(obj, buff) if not obj then return obj end return Encode({_PSEUDO_TAB = true, Stuff = obj}, buff) end function noTabDecode(str) if not str then return str end local ret = Decode(str) if ret and ret._PSEUDO_TAB then return ret.Stuff else return ret end end return {Encode = noTabEncode, Decode = noTabDecode, RealEncode = Encode, RealDecode = Decode};
local addon, ns = ... local UIP = UIParent local CF = CreateFrame local _G = _G local unpack = unpack local wipe = wipe print(addon.." loaded") local width = 600 local height = 300 -- content data func local function generateScrollChildData(scrollChild,maxx) local genv = getfenv(0) -- Collect the names of all possible globally defined fonts local fonts = {} for k, v in pairs(genv) do if type(v) == "table" and type(v.GetObjectType) == "function" then local otype = v:GetObjectType() if otype == "Font" then table.insert(fonts, k) end end end -- Sort the list alphabetically table.sort(fonts) -- Create a table that will contain the font strings themselves scrollChild.fstrings = scrollChild.fstrings or {} -- This changes the padding between font strings vertically local PADDING = 5 -- Store the max width and overall height of the scroll child local height = 0 local width = 0 -- Iterate the list of fonts collected for idx, fname in ipairs(fonts) do -- If the font string is not created, do so if not scrollChild.fstrings[idx] then print(idx, fname) scrollChild.fstrings[idx] = scrollChild:CreateFontString("FPreviewFS" .. idx, "OVERLAY") end -- Set the font string to the correct font object, set the text to be the -- name of the font and set the height/width of the font string based on -- the size of the resulting 'string'. local fs = scrollChild.fstrings[idx] fs:SetFontObject(genv[fname]) fs:SetText(fname) local fwidth = fs:GetStringWidth() local fheight = fs:GetStringHeight() --fs:SetSize(fwidth, fheight) fs:SetHeight(fheight) -- Place the font strings in rows starting at the top-left if idx == 1 then fs:SetPoint("TOPLEFT", 0, 0) height = height + fheight else fs:SetPoint("TOPLEFT", scrollChild.fstrings[idx - 1], "BOTTOMLEFT", 0, - PADDING) height = height + fheight + PADDING end -- Update the 'max' width of the frame width = (fwidth > width) and fwidth or width end scrollChild:SetSize(width, height) scrollChild:SetHeight(height) end local function genData(scrollChild,maxx) if not maxx then maxx = 99 end scrollChild.data = scrollChild.data or {} local padding = 10 local height = 0 local width = 0 for i=1, maxx do scrollChild.data[i] = scrollChild.data[i] or scrollChild:CreateFontString(nil, nil, "GameFontBlackMedium") local fs = scrollChild.data[i] fs:SetText("String"..i) local fheight = fs:GetStringHeight() if i == 1 then fs:SetPoint("TOPLEFT", 0, 0) else fs:SetPoint("TOPLEFT", scrollChild.data[i - 1], "BOTTOMLEFT", 0, -padding) end height = height + fheight + padding end scrollChild:SetHeight(height) end -- // SCROLLFRAME TEMPLATES --template = "UIPanelScrollFrameTemplate" --template = "UIPanelScrollFrameTemplate2" --template = "MinimalScrollFrameTemplate" --template = "FauxScrollFrameTemplate" --template = "FauxScrollFrameTemplateLight" --template = "ListScrollFrameTemplate" -- // SCROLLBAR TEMPLATES --template = "UIPanelScrollBarTemplate" --template = "UIPanelScrollBarTrimTemplate" --template = "UIPanelScrollBarTemplateLightBorder" --template = "MinimalScrollBarTemplate" --scroll frame local scrollFrame = CreateFrame("ScrollFrame", addon, UIP, "UIPanelScrollFrameTemplate") scrollFrame:SetSize(width, height) scrollFrame:SetPoint("CENTER", UIParent, 0, 0) local scrollBar = _G[addon.."ScrollBar"] print(scrollBar:GetWidth()) --debug texture local tex = scrollFrame:CreateTexture(nil, "BACKGROUND") tex:SetTexture(1,1,1) tex:SetVertexColor(1,1,0,0.3) tex:SetAllPoints() --hack for the UIPanelScrollBarTemplate template that UIPanelScrollFrameTemplate is using --I want the cosmetic border, so we add it manually local tex = scrollFrame:CreateTexture(nil,"BACKGROUND",nil,-6) tex:SetPoint("TOP",scrollFrame) tex:SetPoint("RIGHT",scrollBar,3.7,0) tex:SetPoint("BOTTOM",scrollFrame) tex:SetWidth(scrollBar:GetWidth()+10) tex:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-ScrollBar") tex:SetTexCoord(0,0.45,0.1640625,1) --debug texture local tex2 = scrollFrame:CreateTexture(nil,"BACKGROUND",nil,-8) tex2:SetTexture(1,1,1) tex2:SetVertexColor(1,0,1,0.3) tex2:SetAllPoints(tex) --scroll child local scrollChild = CreateFrame("Frame", "$parentScrollChild1") scrollChild:SetWidth(scrollFrame:GetWidth()) local tex = scrollChild:CreateTexture(nil, "BACKGROUND") tex:SetTexture(1,1,1) tex:SetVertexColor(0,1,1,0.3) tex:SetAllPoints() --LOAD SOME DATA and set the framesize generateScrollChildData(scrollChild,20) --genData(scrollChild,20) scrollFrame:SetScrollChild(scrollChild) scrollFrame:EnableMouse(true) --make sure you cannot move the panel out of the screen scrollFrame:SetClampedToScreen(true) scrollFrame:SetMovable(true) scrollFrame:SetResizable(true) scrollFrame:SetUserPlaced(true) scrollFrame:SetScript("OnSizeChanged", function(self) scrollChild:SetWidth(self:GetWidth()) end) local frame = CF("Frame", "$parentResize", scrollFrame) frame:SetSize(26,26) frame:SetPoint("BOTTOMRIGHT",30,-30) local texture = frame:CreateTexture(nil, "BACKGROUND", nil, -8) texture:SetAllPoints() texture:SetTexture(1,1,1) texture:SetVertexColor(0,1,1,0.6) --bugfix frame:EnableMouse(true) frame:RegisterForDrag("LeftButton") frame:SetScript("OnDragStart", function(self) if InCombatLockdown() then return end self:GetParent():StartSizing() end) frame:SetScript("OnDragStop", function(self) if InCombatLockdown() then return end self:GetParent():StopMovingOrSizing() end) frame:SetScript("OnEnter", function(self) GameTooltip:SetOwner(self, "ANCHOR_TOP") GameTooltip:AddLine(addon, 0, 1, 0.5, 1, 1, 1) GameTooltip:AddLine("Resize me!", 1, 1, 1, 1, 1, 1) GameTooltip:Show() end) frame:SetScript("OnLeave", function(self) GameTooltip:Hide() end)
function start (song) print("Song: " .. song .. " @ " .. bpm .. " downscroll: " .. downscroll) end local defaultHudX = 0 local defaultHudY = 0 local tvX = 0 local tvY = 0 local defaultWindowX = 0 local defaultWindowY = 0 local lastStep = 0 --default positions -- changeBoyfriendCharacter('bf', 970, 350) -- changeDadCharacter('dad', -70, 90) local dadY = 0 function update (elapsed) local currentBeat = (songPos / 1000)*(bpm/60) if fly then setActorY(dadY + 50 * math.cos((currentBeat * 0.60) * math.pi), 'dad') end end function beatHit (beat) end function stepHit (step) if curStep == 1 then --for testing end if curStep == 900 then -- da changing notes setupNoteSplash('-maijin') changeStaticNotes('maijin', 'maijin') end if curStep >= 256 and curStep < 1664 then if curStep % 64 == 16 or curStep % 64 == 20 then for i = 0,7 do setActorAngle(0, i) tweenAnglePsych(i, 360, 0.2, 'quintout') end end end --[[if curStep == 272 or curStep == 276 or curStep == 336 or curStep == 340 or curStep == 400 or curStep == 404 or curStep == 464 or curStep == 468 or curStep == 528 or curStep == 532 then -- da spins 1 for i = 0,7 do setActorAngle(0, i) tweenAnglePsych(i, 360, 0.2, 'quintout') end end if curStep == 592 or curStep == 596 or curStep == 656 or curStep == 660 or curStep == 720 or curStep == 724 or curStep == 784 or curStep == 788 or curStep == 848 or curStep == 852 then -- da spins 2 for i = 0,7 do setActorAngle(0, i) tweenAnglePsych(i, 360, 0.2, 'quintout') end end if curStep == 912 or curStep == 916 or curStep == 976 or curStep == 980 or curStep == 1040 or curStep == 1044 or curStep == 1104 or curStep == 1108 or curStep == 1160 or curStep == 1164 then -- da spins part 3 for i = 0,7 do setActorAngle(0, i) tweenAnglePsych(i, 360, 0.2, 'quintout') end end ]]-- end function dadNoteHit() end
require ("lib.lclass") require ("lib.yanecos.Processor") require ("src.data.TileData") require ("src.data.AnimationData") require ("src.data.TransformData") class "TileProcessor" ("Processor") function TileProcessor:TileProcessor (entityManager) self.em = entityManager self.intrests = { TileData:getClass (), } end function TileProcessor:onUpdate (dt) local tiles = self.em:findEntitiesWithData (self.intrests) for _, eid in pairs (tiles) do local tile = self.em:getData (eid, TileData:getClass ()) local transform = self.em:getData (eid, TransformData:getClass ()) transform.x = TileData.Size.w * tile.x transform.y = TileData.Size.h * tile.y end end function TileProcessor:onRender () end
collAgent:importAll() return true
-- GUI handler for Sign Placer. function init() self.signFolder = "PUT_SIGNS_HERE/" end -- Searches the folder with generated signs given by name function search(name) if pcall(function() root.assetJson("/"..self.signFolder..name.."/"..name.." [0,0].json") end) then widget.setText("lblWarning", "^#00ff00;All Good") return true else widget.setText("lblWarning", "^#ff0000;Folder Not Found") return false end end -- Sets the dimension settings visible function autoDimension() local is_not_checked = not widget.getChecked("cbAutoDim") widget.setVisible("lblX", is_not_checked) widget.setVisible("txbX", is_not_checked) widget.setVisible("lblY", is_not_checked) widget.setVisible("txbY", is_not_checked) if not is_not_checked then widget.setText("txbX", "") widget.setText("txbY", "") end end -- Determines the dimensions of the original image (in signs :P) function findDimension(name) local i = 0 local j = 0 while true do if not pcall(function() root.assetJson("/"..self.signFolder..name.."/"..name.." ["..i..",0].json") end) then break else i = i + 1 end end while true do if not pcall(function() root.assetJson("/"..self.signFolder..name.."/"..name.." [0,"..j.."].json") end) then break else j = j + 1 end end return i, j end -- Final function function accept() local name = widget.getText("txbName") -- if not found, return with an error if not search(name) then widget.setText("lblWarning", "^#ff0000;Folder Not Found") return end -- if the dimensions are wrong, return with an error if tonumber(widget.getText("txbX")) and tonumber(widget.getText("txbX")) <= 0 or tonumber(widget.getText("txbY")) and tonumber(widget.getText("txbY")) <= 0 then widget.setText("lblWarning", "^#ff0000;Numbers must be positive") return end wNumber, hNumber = findDimension(name) -- if the dimensions are wrong, return with an error if not widget.getChecked("cbAutoDim") then if not tonumber(widget.getText("txbX")) or tonumber(widget.getText("txbX")) > wNumber or not tonumber(widget.getText("txbY")) or tonumber(widget.getText("txbY")) > hNumber then widget.setText("lblWarning", "^#ff0000;Incorrect custom dimensions") return else wNumber = tonumber(widget.getText("txbX")) hNumber = tonumber(widget.getText("txbY")) end end --status.setStatusProperty("signPlacer", { name = widget.getText("txbName"), wNumber = wNumber, hNumber = hNumber }) widget.setText("txbX", wNumber) widget.setText("txbY", hNumber) -- settings are confirmed and being transfered to the item itself world.sendEntityMessage(player.id(), "signPlacerMessage", { name = name, wNumber = wNumber, hNumber = hNumber }) end
att.PrintName = "halo non precision weapon multiplier" att.Icon = Material("entities/tfa_hce_snow_objectiveflag.png", "smooth mips") att.Description = "Further triples headshot damage." att.Desc_Pros = { "pro.headshotdamage" } att.Desc_Cons = { } att.AutoStats = true att.Slot = "halo_passive" att.Hook_BulletHit = function(wep, data) if CLIENT then return end if data.tr.HitGroup == HITGROUP_HEAD then data.damage = data.damage * 0.6 end end
require "Math" local Object = require "Object" local Physics = require "Physics" GameObject = { -- Draw Variables -- sprite = nil, color = {255, 255, 255, 255}, -- Physics Variables -- collisions = 0, bounciness = -0.9, rigidBody = Physics.NONE, scaleX = scaleX or 1, scaleY = scaleY or 1, posX = 0, posY = 0, velX = 0, velY = 0 } GameObject = Object:extend("GameObject", GameObject) -- Constrcutor -- function GameObject:init(sprite, scale) local obj = {} setmetatable(obj, self) self.__index = self obj.id = Object.UUID() obj.sprite = sprite obj.scaleX = scale obj.scaleY = scale return obj end function GameObject:getDimensions() if self.sprite == nil then return 0, 0 end return self.sprite:getWidth() * self.scaleX, self.sprite:getHeight() * self.scaleY end function GameObject:getWidth() if self.sprite == nil then return 0 end return self.sprite:getWidth() * self.scaleX end function GameObject:getHeight() if self.sprite == nil then return 0 end return self.sprite:getHeight() * self.scaleY end function GameObject:getPosition() return self.posX, self.posY end function GameObject:setPosition(x, y) self.posX = x self.posY = y end function GameObject:getVelocity() return self.velX, self.velY end function GameObject:setVelocity(x, y, vel) if vel ~= nil then x, y = math.normalize(x, y) x = x * vel y = y * vel end self.velX = x self.velY = y end function GameObject:update(dt) -- Gravity -- if bit.band(self.rigidBody, Physics.DYNAMIC) > 0 then self.velY = self.velY + Physics.gravity * dt end -- Movement -- self.posX = self.posX + self.velX * dt self.posY = self.posY + self.velY * dt end function GameObject:onCollisionEnter(other, sides, dt) if (bit.band(sides, Physics.CLEFT ) > 0) then self.velX = -math.abs(self.velX) * self.bounciness end if (bit.band(sides, Physics.CRIGHT ) > 0) then self.velX = math.abs(self.velX) * self.bounciness end if (bit.band(sides, Physics.CTOP ) > 0) then self.velY = -math.abs(self.velY) * self.bounciness end if (bit.band(sides, Physics.CBOTTOM) > 0) then self.velY = math.abs(self.velY) * self.bounciness end end -- TODO change velocity not position function GameObject:onCollisionStay(other, sides, dt) if bit.band(self.rigidBody, Physics.DYNAMIC) > 0 then if (bit.band(sides, Physics.CLEFT ) > 0) then self.velX = self.velX + dt * 1000 end if (bit.band(sides, Physics.CRIGHT ) > 0) then self.velX = self.velX - dt * 1000 end if (bit.band(sides, Physics.CTOP ) > 0) then self.velY = self.velY + dt * 1000 end if (bit.band(sides, Physics.CBOTTOM) > 0) then self.velY = self.velY - dt * 1000 end end local moveX, moveY if bit.band(self.rigidBody, Physics.DYNAMIC) > 0 and other and other.posX then moveX = bit.band(sides, Physics.CRIGHT ) > 0 and -self.posX - self:getWidth() + other.posX or bit.band(sides, Physics.CLEFT ) > 0 and -self.posX + other.posX + other:getWidth() or 0 moveY = bit.band(sides, Physics.CBOTTOM) > 0 and -self.posY - self:getHeight() + other.posY or bit.band(sides, Physics.CTOP ) > 0 and -self.posY + other.posY + other:getHeight() or 0 moveX = math.clamp(moveX, -math.abs(self.velX), math.abs(self.velX)) moveY = math.clamp(moveY, -math.abs(self.velY), math.abs(self.velY)) self.posX = self.posX + moveX self.posY = self.posY + moveY end self.velX = self.velX * (1 - dt) self.velY = self.velY * (1 - dt) end function GameObject:onCollisionExit(other, sides, dt) end function GameObject:draw() if self.sprite == nil then return end love.graphics.setColor(self.color) self.sprite:draw(self.posX, self.posY, 0, self.scaleX, self.scaleY) love.graphics.setColor(255, 255, 255, 255) end