content
stringlengths
5
1.05M
return { ping = { ping = "PINGING...", pong = "PONG! ``{{arg1}}MS``", description = "SHOWZ PUNG PONG" }, help = { embedTitle = "HALP FOR TIGER 2.0.0.0", embedDescription = "UZE LE REACTSHUNS TO FILTAR THRU LE COMMANDZ", description = "SHOWS DIS MENU", } }
local M = {} M.config = function() local status_ok, command_center = pcall(require, "command_center") if not status_ok then return end -- local noremap = { noremap = true } -- local silent_noremap = { noremap = true, silent = true } command_center.add({ { description = "Search within the project (Live grep)", cmd = "<CMD>Telescope live_grep<CR>" }, { description = "Select entire text", cmd = "<CMD>call feedkeys('GVgg')<CR>" }, { description = "Show file browser", cmd = "<CMD>Telescope file_browser<CR>" }, { description = "Find files", cmd = "<CMD>lua require('telescope.builtin').find_files()<CR>" }, { description = "Find hidden files", cmd = "<CMD>Telescope find_files hidden=true<CR>" }, { description = "Find Git files", cmd = "<CMD>lua require('user.telescope').git_files()<CR>" }, { description = "Show recent files", cmd = "<CMD>Telescope oldfiles<CR>" }, { description = "Rerun last search", cmd = "<CMD>lua require('telescope.builtin').resume({cache_index=3})<CR>" }, { description = "Search inside current buffer", cmd = "<CMD>Telescope current_buffer_fuzzy_find<CR>" }, { description = "Quit", cmd = "<CMD>qa<CR>" }, { description = "Save all files", cmd = "<CMD>wa<CR>" }, { description = "Save current file", cmd = "<CMD>w<CR>" }, { description = "Search word", cmd = "<CMD>lua require('user.telescope').find_string()<CR>" }, { description = "Format document", cmd = "<CMD>lua vim.lsp.buf.format()<CR>" }, { description = "Workspace diagnostics", cmd = "<CMD>Telescope diagnostics<CR>" }, { description = "Workspace symbols", cmd = "<CMD>Telescope lsp_workspace_symbols<CR>" }, { description = "List projects", cmd = "<CMD>Telescope projects<CR>" }, { description = "Build project", cmd = "<CMD>AsyncTask project-build<CR>" }, { description = "Run project", cmd = "<CMD>AsyncTask project-run<CR>" }, { description = "Show tasks", cmd = "<CMD>AsyncTaskList<CR>" }, { description = "Show opened buffers", cmd = "<CMD>Telescope buffers<CR>" }, { description = "Find man pages", cmd = "<CMD>Telescope man_pages<CR>" }, { description = "Check health", cmd = "<CMD>checkhealth<CR>" }, { description = "Switch colorschemes", cmd = "<CMD>Telescope colorscheme<CR>" }, { description = "Command history", cmd = "<CMD>lua require('telescope.builtin').command_history()<CR>" }, { description = "Show all available commands", cmd = "<CMD>Telescope commands<CR>" }, { description = "Toggle cursor column", cmd = "<CMD>set cursorcolumn!<CR>" }, { description = "Toggle cursor line", cmd = "<CMD>set cursorline!<CR>" }, { description = "Show jumplist", cmd = "<CMD>Telescope jumplist<CR>" }, { description = "Show workspace git commits", cmd = "<CMD>Telescope git_commits<CR>" }, { description = "Show all key maps", cmd = "<CMD>Telescope keymaps<CR>" }, { description = "Toggle paste mode", cmd = "<CMD>set paste!<CR>" }, { description = "Show registers", cmd = "<CMD>lua require('telescope.builtin').registers()<CR>" }, { description = "Toggle relative number", cmd = "<CMD>set relativenumber!<CR>" }, { description = "Reload vimrc", cmd = "<CMD>source $MYVIMRC<CR>" }, { description = "Toggle search highlighting", cmd = "<CMD>set hlsearch!<CR>" }, { description = "Show search history", cmd = "<CMD>lua require('telescope.builtin').search_history()<CR>" }, { description = "Toggle spell checker", cmd = "<CMD>set spell!<CR>" }, { description = "Edit vim options", cmd = "<CMD>Telescope vim_options<CR>" }, { description = "Show Cheatsheet", cmd = "<CMD>help index<CR>" }, { description = "Quick reference", cmd = "<CMD>help quickref<CR>" }, { description = "Find help documentations", cmd = "<CMD>lua require('telescope.builtin').help_tags()<CR>" }, { description = "Help summary", cmd = "<CMD>help summary<CR>" }, { description = "Help tips", cmd = "<CMD>help tips<CR>" }, { description = "Help tutorial", cmd = "<CMD>help tutor<CR>" }, { description = "List brakpoints", cmd = "<CMD>lua require'telescope'.extensions.dap.list_breakpoints{}<CR>" }, { description = "Clear breakpoints", cmd = "<CMD>lua require('dap.breakpoints').clear()<CR>" }, { description = "Close DAP repl", cmd = "<CMD>lua require'dap'.close(); require'dap'.repl.close()<CR>" }, { description = "Show DAP commands", cmd = "<CMD>lua require'telescope'.extensions.dap.commands{}<CR>" }, { description = "Show DAP configurations", cmd = "<CMD>lua require'telescope'.extensions.dap.configurations{}<CR>", }, { description = "DAP continue", cmd = "<CMD>lua require'dap'.continue()<CR>" }, { description = "Show DAP frames", cmd = "<CMD>lua require'telescope'.extensions.dap.frames{}<CR>" }, { description = "DAP pause", cmd = "<CMD>lua require'dap'.pause()<CR>" }, { description = "DAP repl", cmd = "<CMD>lua require'dap'.repl.open(); vim.cmd(\"wincmd w|resize 12\")<CR>" }, { description = "DAP run to cursor", cmd = "<CMD>lua require'dap'.run_to_cursor()<CR>" }, { description = "DAP step back", cmd = "<CMD>lua require'dap'.step_back()<CR>" }, { description = "DAP step into", cmd = "<CMD>lua require'dap'.step_into()<CR>" }, { description = "DAP step out", cmd = "<CMD>lua require'dap'.step_out()<CR>" }, { description = "DAP step over", cmd = "<CMD>lua require'dap'.step_over()<CR>" }, { description = "DAP toggle breakpoint", cmd = "<CMD>lua require'dap'.toggle_breakpoint()<CR>" }, }, command_center.mode.ADD_ONLY) end return M
pVehicle = getPedOccupiedVehicle ( localPlayer ) local lastVehicle = nil -- Yeah, lots of eventhandlers for one thing. -- This will be triggered when a player is warped into a vehicle. addEventHandler ( "onClientPlayerVehicleEnter", localPlayer, function ( vehicle ) pVehicle = vehicle checkVehicleChange ( ) end ) -- For when a player dies whilst inside a vehicle addEventHandler ( "onClientPlayerWasted", localPlayer, function() logCreated = false pVehicle = false setVisible ( false ) end ) -- And exiting normally. addEventHandler ( "onClientVehicleStartExit", root, function ( player ) -- Possible fix for when someone is trying to jack a locked vehicle, you cant open the editor anymore. if player == localPlayer and not isVehicleLocked ( source ) then clearLog ( ) pVehicle = false setVisible ( false ) end end ) -- When the vehicle explodes where you're in addEventHandler ( "onClientVehicleExplode", root, function ( ) if getPedOccupiedVehicle ( localPlayer ) == source then clearLog ( ) pVehicle = false setVisible ( false ) end end ) -- When the vehicle you're in destroys addEventHandler("onClientElementDestroy", root, function() if (source == localPlayer.vehicle) then clearLog() pVehicle = false setVisible(false) end end ) -- For when the vehicle element model changes. addEventHandler ( "onClientElementStreamIn", root, function ( ) if getElementType ( source ) == "vehicle" and source == getPedOccupiedVehicle ( localPlayer ) then pVehicle = source triggerEvent ( "updateVehicleText", pVehicle ) forceVehicleChange ( ) end end ) -- Update the editor menu if the vehicle is changed function checkVehicleChange ( ) if pVehicle then triggerEvent ( "updateVehicleText", pVehicle ) if pVehicle ~= lastVehicle then requestMiniLog ( pVehicle ) lastVehicle = pVehicle guiShowView ( "engine" ) end end end function forceVehicleChange ( ) guiDestroyWarningWindow ( ) if pVehicle then triggerEvent ( "updateVehicleText", pVehicle ) requestMiniLog ( pVehicle ) end lastVehicle = pVehicle guiShowView ( "engine" ) end
local M = {} M.Color = require("colorbuddy.color").Color M.Group = require("colorbuddy.group").Group M.colors = require("colorbuddy.color").colors M.styles = require("colorbuddy.style").styles return M
-- $Id: featuredefs_post.lua 3171 2008-11-06 09:06:29Z det $ -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- file: featuredefs_post.lua -- brief: featureDef post processing -- author: Dave Rodgers -- author: lurker & jK, heavily modead by TA devs -- -- Copyright (C) 2008,2009. -- Licensed under the terms of the GNU GPL, v2 or later. -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function isbool(x) return (type(x) == 'boolean') end local function istable(x) return (type(x) == 'table') end local function isnumber(x) return (type(x) == 'number') end local function isstring(x) return (type(x) == 'string') end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- Per-unitDef featureDefs -- local UnitDefs = DEFS.unitDefs local function defaultDamageFunc(ud, coef) --nonlinear scaling, makes the the wrecks of low hitpoints units stronger and opposite for strong unit bT = 5000 -- threshold, damage values above this value will be lowered, and below increased bC = 0.75 -- smoothing coef, 1 won't make any change to the damage, 0 on the other hand, will force the value to be very close to the threshold return ((ud.maxdamage / bT) ^ bC) * bT * coef end local function defaultMetalFunc(ud, coef) return ud.buildcostmetal * coef end local featureConfig = { [0] = { suffix = " Wreckage", damageFunc = function(ud) return defaultDamageFunc(ud, 0.8) end, metalFunc = function(ud) return defaultMetalFunc(ud, 0.75) end, }, --dead [1] = { suffix = " Debris", damageFunc = function(ud) return defaultDamageFunc(ud, 1) end, metalFunc = function(ud) return defaultMetalFunc(ud, 0.4) end, }, --heap ~ dead wreckage [2] = { suffix = " Metal Shards", damageFunc = function(ud) return defaultDamageFunc(ud, 0.5) end, metalFunc = function(ud) return defaultMetalFunc(ud, 0.25) end, }, --heap2 ~ dead heap [3] = { suffix = " Metal Dust", damageFunc = function(ud) return defaultDamageFunc(ud, 0.4) end, metalFunc = function(ud) return defaultMetalFunc(ud, 0.10) end, } --heap3 ~ dead heap2 -- deeper nesting wont't be accepted } local skipUnits = { ['cormaw'] = true, ['cordrag'] = true, ['corfdrag'] = true, ['corfort'] = true, ['coredrag'] = true, ['armclaw'] = true, ['armdrag'] = true, ['armfdrag'] = true, ['armfort'] = true, ['armedrag'] = true, ['tlldtns'] = true, ['tlladt'] = true, ['tlldt'] = true, ['tlledrag'] = true, ['talon_fdrag'] = true, ['talon_drag'] = true, ['talon_fort'] = true, ['talon_edrag'] = true, ['gok_drag'] = true, ['gok_fdrag'] = true, ['gok_fort'] = true, ['gok_claw'] = true, ['gok_edrag'] = true, } local function processFeature(fname, ud, level) config = featureConfig[level] if config then -- accept only meaningful levels fd = FeatureDefs[fname] fd.description = (ud.name or "Mysterious") .. config.suffix if ud.category:find("COMMANDER") then return end fd.damage = config.damageFunc(ud) fd.metal = config.metalFunc(ud) end end local function recursiveHeap(fd, ud, heapLevel) if isstring(fd.featuredead) then fname = fd.featuredead innerFd = FeatureDefs[fname] --Spring.Echo(innerFd) if innerFd then -- unitfeature has some featureDead processFeature(fname, ud, heapLevel) recursiveHeap(innerFd, ud, heapLevel + 1) end end end local function processUnitFeatures(ud) if skipUnits[ud.unitname or ""] then return end --Spring.Echo("PUF") if (isstring(ud.corpse) and istable(ud.featuredefs)) then fname = ud.corpse fd = FeatureDefs[fname] -- Spring.Echo(fd) if (fd) then -- unit has some corpse if (ud.corpse:lower():find("heap")) then -- lets treat that corpse as a heap processFeature(fname, ud, 1) else -- or as a dead (by default) processFeature(fname, ud, 0) end recursiveHeap(fd, ud, 1) end end end local function ProcessUnitDef(udName, ud) local fds = ud.featuredefs if (not istable(fds)) then return end -- add this unitDef's featureDefs for fdName, fd in pairs(fds) do if (isstring(fdName) and istable(fd)) then local fullName = udName .. '_' .. fdName FeatureDefs[fullName] = fd fd.filename = ud.filename end end -- FeatureDead name changes for fdName, fd in pairs(fds) do if (isstring(fdName) and istable(fd)) then if (isstring(fd.featuredead)) then local fullName = udName .. '_' .. fd.featuredead:lower() if (FeatureDefs[fullName]) then fd.featuredead = fullName end end end end -- convert the unit corpse name if (isstring(ud.corpse)) then local fullName = udName .. '_' .. ud.corpse:lower() local fd = FeatureDefs[fullName] if (fd) then ud.corpse = fullName end end processUnitFeatures(ud) end -------------------------------------------------------------------------------- -- Process the unitDefs for udName, ud in pairs(UnitDefs) do if (isstring(udName) and istable(ud)) then ProcessUnitDef(udName, ud) end end -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
project "Compression-zstd" AddModuleConfig() uuid "BB7C69B1-33CC-4FF8-8CC8-D8A46A07A3FF" pchheader "stdafx_zstd.h" pchsource "../src/stdafx_zstd.cpp" includedirs { "../Externals/zstd/lib", }
local hit_effects = require("__base__/prototypes/entity/hit-effects") local sounds = require("__base__/prototypes/entity/sounds") function electric_mining_drill_animation() return { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill.png", line_length = 6, width = 84, height = 80, frame_count = 30, animation_speed = electric_drill_animation_speed, frame_sequence = electric_drill_animation_sequence, direction_count = 1, shift = util.by_pixel(0, -12), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill.png", line_length = 6, width = 162, height = 156, frame_count = 30, animation_speed = electric_drill_animation_speed, frame_sequence = electric_drill_animation_sequence, direction_count = 1, shift = util.by_pixel(1, -11), scale = 0.83 } } end function electric_mining_drill_shadow_animation() return { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-shadow.png", line_length = 7, width = 112, height = 26, frame_count = 21, animation_speed = electric_drill_animation_speed, frame_sequence = electric_drill_animation_shadow_sequence, draw_as_shadow = true, shift = util.by_pixel(20, 6), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-shadow.png", line_length = 7, width = 218, height = 56, frame_count = 21, animation_speed = electric_drill_animation_speed, frame_sequence = electric_drill_animation_shadow_sequence, draw_as_shadow = true, shift = util.by_pixel(21, 5), scale = 0.83 } } end function electric_mining_drill_horizontal_animation() return { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-horizontal.png", line_length = 6, width = 40, height = 80, frame_count = 30, animation_speed = electric_drill_animation_speed, frame_sequence = electric_drill_animation_sequence, direction_count = 1, shift = util.by_pixel(2, -12), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-horizontal.png", line_length = 6, width = 80, height = 160, frame_count = 30, animation_speed = electric_drill_animation_speed, frame_sequence = electric_drill_animation_sequence, direction_count = 1, shift = util.by_pixel(2, -12), scale = 0.83 } } end function electric_mining_drill_horizontal_front_animation() return { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-horizontal-front.png", line_length = 6, width = 32, height = 76, frame_count = 30, animation_speed = electric_drill_animation_speed, frame_sequence = electric_drill_animation_sequence, direction_count = 1, shift = util.by_pixel(-2, 4), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-horizontal-front.png", line_length = 6, width = 66, height = 154, frame_count = 30, animation_speed = electric_drill_animation_speed, frame_sequence = electric_drill_animation_sequence, direction_count = 1, shift = util.by_pixel(-3, 3), scale = 0.83 } } end function electric_mining_drill_horizontal_shadow_animation() return { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-horizontal-shadow.png", line_length = 7, width = 92, height = 80, frame_count = 21, animation_speed = electric_drill_animation_speed, frame_sequence = electric_drill_animation_shadow_sequence, draw_as_shadow = true, shift = util.by_pixel(32, 2), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-horizontal-shadow.png", line_length = 7, width = 180, height = 164, frame_count = 21, animation_speed = electric_drill_animation_speed, frame_sequence = electric_drill_animation_shadow_sequence, draw_as_shadow = true, shift = util.by_pixel(33, 1), scale = 0.83 } } end data:extend( { { type = "mining-drill", name = "advanced-electric-mining-drill", icon = "__base__/graphics/icons/electric-mining-drill.png", icon_size = 64, icon_mipmaps = 4, flags = {"placeable-neutral", "player-creation"}, minable = {mining_time = 0.3, result = "advanced-electric-mining-drill"}, max_health = 300, resource_categories = {"basic-solid"}, corpse = "electric-mining-drill-remnants", dying_explosion = "electric-mining-drill-explosion", collision_box = {{ -2.4, -2.4}, {2.4, 2.4}}, selection_box = {{ -2.5, -2.5}, {2.5, 2.5}}, damaged_trigger_effect = hit_effects.entity(), input_fluid_box = { production_type = "input-output", pipe_picture = assembler2pipepictures(), pipe_covers = pipecoverspictures(), base_area = 1, height = 2, base_level = -1, pipe_connections = { { position = {-3, 0} }, { position = {3, 0} }, { position = {0, 3} } } }, working_sound = { sound = { filename = "__base__/sound/electric-mining-drill.ogg", volume = 0.5 }, audible_distance_modifier = 0.6, fade_in_ticks = 4, fade_out_ticks = 20 }, vehicle_impact_sound = sounds.generic_impact, open_sound = sounds.machine_open, close_sound = sounds.machine_close, graphics_set = { drilling_vertical_movement_duration = 10 / electric_drill_animation_speed, animation_progress = 1, min_animation_progress = 0, max_animation_progress = 30, status_colors = electric_mining_drill_status_colors(), circuit_connector_layer = "object", circuit_connector_secondary_draw_order = { north = 14, east = 30, south = 30, west = 30 }, animation = { north = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-N.png", line_length = 1, width = 96, height = 104, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -4), repeat_count = 5, hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-N.png", line_length = 1, width = 190, height = 208, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -4), repeat_count = 5, scale = 0.83 } }, { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-N-output.png", line_length = 5, width = 32, height = 34, frame_count = 5, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-4, -44), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-N-output.png", line_length = 5, width = 60, height = 66, frame_count = 5, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-3, -44), scale = 0.83 } }, { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-N-shadow.png", line_length = 1, width = 106, height = 104, frame_count = 1, animation_speed = electric_drill_animation_speed, draw_as_shadow = true, shift = util.by_pixel(6, -4), repeat_count = 5, hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-N-shadow.png", line_length = 1, width = 212, height = 204, frame_count = 1, animation_speed = electric_drill_animation_speed, draw_as_shadow = true, shift = util.by_pixel(6, -3), repeat_count = 5, scale = 0.83 } } } }, east = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-E.png", line_length = 1, width = 96, height = 94, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -4), repeat_count = 5, hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-E.png", line_length = 1, width = 192, height = 188, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -4), repeat_count = 5, scale = 0.83 } }, { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-E-output.png", line_length = 5, width = 26, height = 38, frame_count = 5, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(30, -8), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-E-output.png", line_length = 5, width = 50, height = 74, frame_count = 5, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(30, -8), scale = 0.5 } }, { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-E-shadow.png", line_length = 1, width = 112, height = 92, frame_count = 1, animation_speed = electric_drill_animation_speed, draw_as_shadow = true, shift = util.by_pixel(10, 2), repeat_count = 5, hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-E-shadow.png", line_length = 1, width = 222, height = 182, frame_count = 1, animation_speed = electric_drill_animation_speed, draw_as_shadow = true, shift = util.by_pixel(10, 2), repeat_count = 5, scale = 0.83 } } } }, south = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-S.png", line_length = 1, width = 92, height = 98, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -2), repeat_count = 5, hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-S.png", line_length = 1, width = 184, height = 192, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -1), repeat_count = 5, scale = 0.83 } }, { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-S-shadow.png", line_length = 1, width = 106, height = 102, frame_count = 1, animation_speed = electric_drill_animation_speed, draw_as_shadow = true, shift = util.by_pixel(6, 2), repeat_count = 5, hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-S-shadow.png", line_length = 1, width = 212, height = 204, frame_count = 1, animation_speed = electric_drill_animation_speed, draw_as_shadow = true, shift = util.by_pixel(6, 2), repeat_count = 5, scale = 0.83 } } } }, west = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-W.png", line_length = 1, width = 96, height = 94, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -4), repeat_count = 5, hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-W.png", line_length = 1, width = 192, height = 188, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -4), repeat_count = 5, scale = 0.83 } }, { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-W-output.png", line_length = 5, width = 24, height = 28, frame_count = 5, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-30, -12), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-W-output.png", line_length = 5, width = 50, height = 60, frame_count = 5, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-31, -13), scale = 0.83 } }, { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-W-shadow.png", line_length = 1, width = 102, height = 92, frame_count = 1, animation_speed = electric_drill_animation_speed, draw_as_shadow = true, shift = util.by_pixel(-6, 2), repeat_count = 5, hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-W-shadow.png", line_length = 1, width = 200, height = 182, frame_count = 1, animation_speed = electric_drill_animation_speed, draw_as_shadow = true, shift = util.by_pixel(-5, 2), repeat_count = 5, scale = 0.83 } } } } }, shift_animation_waypoints = { -- Movement should be between 0.25-0.4 distance -- Bounds -0.5 - 0.6 north = { {0, 0}, {0, -0.3}, {0, 0.1}, {0, 0.5}, {0, 0.2}, {0, -0.1}, {0, -0.5}, {0, -0.15}, {0, 0.25}, {0, 0.6}, {0, 0.3} }, -- Bounds -1 - 0 east = { {0, 0}, {-0.4, 0}, {-0.1, 0}, {-0.5, 0}, {-0.75, 0}, {-1, 0}, {-0.65, 0}, {-0.3, 0}, {-0.9, 0}, {-0.6, 0}, {-0.3, 0} }, -- Bounds -1 - 0 south = { {0, 0}, {0, -0.4}, {0, -0.1}, {0, -0.5}, {0, -0.75}, {0, -1}, {0, -0.65}, {0, -0.3}, {0, -0.9}, {0, -0.6}, {0, -0.3} }, -- Bounds 0 - 1 west = { {0, 0}, {0.4, 0}, {0.1, 0}, {0.5, 0}, {0.75, 0}, {1, 0}, {0.65, 0}, {0.3, 0}, {0.9, 0}, {0.6, 0}, {0.3, 0} } }, shift_animation_waypoint_stop_duration = 195 / electric_drill_animation_speed, shift_animation_transition_duration = 30 / electric_drill_animation_speed, working_visualisations = { -- dust animation 1 { constant_speed = true, synced_fadeout = true, align_to_waypoint = true, apply_tint = "resource-color", animation = electric_mining_drill_smoke(), north_position = { 0, 0.36 }, east_position = { 0, 0 }, south_position = { 0, 0.36 }, west_position = { 0, 0 } }, -- dust animation directional 1 { constant_speed = true, fadeout = true, apply_tint = "resource-color", north_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-N-smoke.png", line_length = 5, width = 24, height = 30, frame_count = 10, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-3, -66), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-N-smoke.png", line_length = 5, width = 42, height = 58, frame_count = 10, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-2, -66), scale = 0.83 } } } }, east_animation = nil, south_animation = nil, west_animation = nil }, -- drill back animation { animated_shift = true, always_draw = true, north_animation = { layers = { electric_mining_drill_animation(), electric_mining_drill_shadow_animation() } }, east_animation = { layers = { electric_mining_drill_horizontal_animation(), electric_mining_drill_horizontal_shadow_animation() } }, south_animation = { layers = { electric_mining_drill_animation(), electric_mining_drill_shadow_animation() } }, west_animation = { layers = { electric_mining_drill_horizontal_animation(), electric_mining_drill_horizontal_shadow_animation() } } }, -- dust animation 2 { constant_speed = true, synced_fadeout = true, align_to_waypoint = true, apply_tint = "resource-color", animation = electric_mining_drill_smoke_front(), north_position = { 0, 0.36 }, east_position = { 0, 0 }, south_position = { 0, 0.36 }, west_position = { 0, 0 } }, -- dust animation directional 2 { constant_speed = true, fadeout = true, apply_tint = "resource-color", north_animation = nil, east_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-E-smoke.png", line_length = 5, width = 24, height = 28, frame_count = 10, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(36, -18), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-E-smoke.png", line_length = 5, width = 46, height = 56, frame_count = 10, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(36, -18), scale = 0.83 } } } }, south_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-S-smoke.png", line_length = 5, width = 24, height = 18, frame_count = 10, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-3, 30), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-S-smoke.png", line_length = 5, width = 48, height = 36, frame_count = 10, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-3, 30), scale = 0.83 } } } }, west_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-W-smoke.png", line_length = 5, width = 26, height = 30, frame_count = 10, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-39, -18), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-W-smoke.png", line_length = 5, width = 46, height = 54, frame_count = 10, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-39, -18), scale = 0.83 } } } } }, -- drill front animation { animated_shift = true, always_draw = true, --north_animation = util.empty_sprite(), east_animation = electric_mining_drill_horizontal_front_animation(), --south_animation = util.empty_sprite(), west_animation = electric_mining_drill_horizontal_front_animation() }, -- front frame { always_draw = true, north_animation = nil, east_animation = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-E-front.png", line_length = 1, width = 66, height = 74, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(31, 10), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-E-front.png", line_length = 1, width = 136, height = 148, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(31, 10), scale = 0.83 } }, south_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-S-output.png", line_length = 5, width = 44, height = 28, frame_count = 5, animation_speed = electric_drill_animation_speed, shift = util.by_pixel(-2, 34), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-S-output.png", line_length = 5, width = 84, height = 56, frame_count = 5, animation_speed = electric_drill_animation_speed, shift = util.by_pixel(-1, 34), scale = 0.83 } }, { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-S-front.png", line_length = 1, width = 96, height = 54, frame_count = 1, animation_speed = electric_drill_animation_speed, repeat_count = 5, shift = util.by_pixel(0, 40), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-S-front.png", line_length = 1, width = 190, height = 104, frame_count = 1, animation_speed = electric_drill_animation_speed, repeat_count = 5, shift = util.by_pixel(0, 40), scale = 0.83 } } } }, west_animation = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-W-front.png", line_length = 1, width = 68, height = 70, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-33, 12), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-W-front.png", line_length = 1, width = 134, height = 140, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-33, 12), scale = 0.83 } } }, -- LEDs electric_mining_drill_status_leds_working_visualisation(), -- light --electric_mining_drill_primary_light, electric_mining_drill_secondary_light } }, wet_mining_graphics_set = { drilling_vertical_movement_duration = 10 / electric_drill_animation_speed, animation_progress = 1, min_animation_progress = 0, max_animation_progress = 30, status_colors = electric_mining_drill_status_colors(), circuit_connector_layer = "object", circuit_connector_secondary_draw_order = { north = 14, east = 48, south = 48, west = 48 }, animation = { north = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-N-wet.png", line_length = 1, width = 96, height = 100, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -8), repeat_count = 5, hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-N-wet.png", line_length = 1, width = 190, height = 198, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -7), repeat_count = 5, scale = 0.83 } }, { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-N-output.png", line_length = 5, width = 32, height = 34, frame_count = 5, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-4, -44), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-N-output.png", line_length = 5, width = 60, height = 66, frame_count = 5, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-3, -44), scale = 0.83 } }, { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-N-wet-shadow.png", line_length = 1, width = 124, height = 110, frame_count = 1, animation_speed = electric_drill_animation_speed, draw_as_shadow = true, shift = util.by_pixel(12, 2), repeat_count = 5, hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-N-wet-shadow.png", line_length = 1, width = 248, height = 222, frame_count = 1, animation_speed = electric_drill_animation_speed, draw_as_shadow = true, shift = util.by_pixel(12, 1), repeat_count = 5, scale = 0.83 } } } }, west = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-W-wet.png", line_length = 1, width = 96, height = 106, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(2, -10), repeat_count = 5, hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-W-wet.png", line_length = 1, width = 194, height = 208, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(1, -9), repeat_count = 5, scale = 0.83 } }, { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-W-output.png", line_length = 5, width = 24, height = 28, frame_count = 5, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-30, -12), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-W-output.png", line_length = 5, width = 50, height = 60, frame_count = 5, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-31, -13), scale = 0.83 } }, { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-W-wet-shadow.png", line_length = 1, width = 132, height = 102, frame_count = 1, animation_speed = electric_drill_animation_speed, draw_as_shadow = true, shift = util.by_pixel(8, 6), repeat_count = 5, hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-W-wet-shadow.png", line_length = 1, width = 260, height = 202, frame_count = 1, animation_speed = electric_drill_animation_speed, draw_as_shadow = true, shift = util.by_pixel(9, 6), repeat_count = 5, scale = 0.83 } } } }, south = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-S-wet.png", line_length = 1, width = 98, height = 106, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -6), repeat_count = 5, hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-S-wet.png", line_length = 1, width = 192, height = 208, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(1, -5), repeat_count = 5, scale = 0.83 } }, { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-S-wet-shadow.png", line_length = 1, width = 124, height = 98, frame_count = 1, animation_speed = electric_drill_animation_speed, draw_as_shadow = true, shift = util.by_pixel(12, 4), repeat_count = 5, hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-S-wet-shadow.png", line_length = 1, width = 248, height = 192, frame_count = 1, animation_speed = electric_drill_animation_speed, draw_as_shadow = true, shift = util.by_pixel(12, 5), repeat_count = 5, scale = 0.83 } } } }, east = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-E-wet.png", line_length = 1, width = 98, height = 106, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-2, -10), repeat_count = 5, hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-E-wet.png", line_length = 1, width = 194, height = 208, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-2, -9), repeat_count = 5, scale = 0.83 } }, { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-E-output.png", line_length = 5, width = 26, height = 38, frame_count = 5, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(30, -8), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-E-output.png", line_length = 5, width = 50, height = 74, frame_count = 5, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(30, -8), scale = 0.83 } }, { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-E-wet-shadow.png", line_length = 1, width = 112, height = 100, frame_count = 1, animation_speed = electric_drill_animation_speed, draw_as_shadow = true, shift = util.by_pixel(10, 6), repeat_count = 5, hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-E-wet-shadow.png", line_length = 1, width = 226, height = 202, frame_count = 1, animation_speed = electric_drill_animation_speed, draw_as_shadow = true, shift = util.by_pixel(9, 5), repeat_count = 5, scale = 0.83 } } } } }, shift_animation_waypoints = { -- Movement should be between 0.25-0.4 distance -- Bounds -0.5 - 0.2 north = { {0, 0}, {0, -0.4}, {0, -0.1}, {0, 0.2} }, -- Bounds -0.3 - 0 east = { {0, 0}, {-0.3, 0}, {0, 0}, {-0.25, 0} }, -- Bounds -0.7 - 0 south = { {0, 0}, {0, -0.4}, {0, -0.7}, {0, -0.3} }, -- Bounds 0 - 0.3 west = { {0, 0}, {0.3, 0}, {0, 0}, {0.25, 0} } }, shift_animation_waypoint_stop_duration = 195 / electric_drill_animation_speed, shift_animation_transition_duration = 30 / electric_drill_animation_speed, working_visualisations = { -- dust animation 1 { constant_speed = true, synced_fadeout = true, align_to_waypoint = true, apply_tint = "resource-color", animation = electric_mining_drill_smoke(), north_position = { 0, 0.36 }, east_position = { 0, 0 }, south_position = { 0, 0.36 }, west_position = { 0, 0 } }, -- dust animation directional 1 { constant_speed = true, fadeout = true, apply_tint = "resource-color", north_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-N-smoke.png", line_length = 5, width = 24, height = 30, frame_count = 10, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-3, -66), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-N-smoke.png", line_length = 5, width = 42, height = 58, frame_count = 10, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-2, -66), scale = 0.83 } } } }, east_animation = nil, south_animation = nil, west_animation = nil }, -- drill back animation { animated_shift = true, always_draw = true, north_animation = { layers = { electric_mining_drill_animation(), electric_mining_drill_shadow_animation() } }, east_animation = { layers = { electric_mining_drill_horizontal_animation(), electric_mining_drill_horizontal_shadow_animation() } }, south_animation = { layers = { electric_mining_drill_animation(), electric_mining_drill_shadow_animation() } }, west_animation = { layers = { electric_mining_drill_horizontal_animation(), electric_mining_drill_horizontal_shadow_animation() } } }, -- dust animation 2 { constant_speed = true, synced_fadeout = true, align_to_waypoint = true, apply_tint = "resource-color", animation = electric_mining_drill_smoke_front() }, -- dust animation directional 2 { constant_speed = true, fadeout = true, apply_tint = "resource-color", north_animation = nil, east_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-E-smoke.png", line_length = 5, width = 24, height = 28, frame_count = 10, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(36, -18), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-E-smoke.png", line_length = 5, width = 46, height = 56, frame_count = 10, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(36, -18), scale = 0.83 } } } }, south_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-S-smoke.png", line_length = 5, width = 24, height = 18, frame_count = 10, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-3, 30), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-S-smoke.png", line_length = 5, width = 48, height = 36, frame_count = 10, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-3, 30), scale = 0.83 } } } }, west_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-W-smoke.png", line_length = 5, width = 26, height = 30, frame_count = 10, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-39, -18), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-W-smoke.png", line_length = 5, width = 46, height = 54, frame_count = 10, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-39, -18), scale = 0.83 } } } } }, -- fluid window background (bottom) { -- render_layer = "lower-object-above-shadow", secondary_draw_order = -49, always_draw = true, north_animation = nil, east_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-E-wet-window-background.png", line_length = 1, width = 12, height = 8, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -52), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-E-wet-window-background.png", line_length = 1, width = 22, height = 14, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -52), scale = 0.83 } } } }, south_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-S-wet-window-background.png", line_length = 1, width = 16, height = 12, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-2, -44), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-S-wet-window-background.png", line_length = 1, width = 30, height = 20, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-2, -43), scale = 0.83 } } } }, west_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-W-wet-window-background.png", line_length = 1, width = 12, height = 8, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -52), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-W-wet-window-background.png", line_length = 1, width = 22, height = 14, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -52), scale = 0.83 } } } } }, -- fluid base (bottom) { always_draw = true, -- render_layer = "lower-object-above-shadow", secondary_draw_order = -48, apply_tint = "input-fluid-base-color", north_animation = nil, east_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-E-wet-fluid-background.png", line_length = 1, width = 12, height = 8, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -52), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-E-wet-fluid-background.png", line_length = 1, width = 22, height = 14, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -52), scale = 0.83 } } } }, south_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-S-wet-fluid-background.png", line_length = 1, width = 14, height = 8, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-2, -42), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-S-wet-fluid-background.png", line_length = 1, width = 28, height = 18, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-2, -43), scale = 0.83 } } } }, west_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-W-wet-fluid-background.png", line_length = 1, width = 12, height = 8, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -52), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-W-wet-fluid-background.png", line_length = 1, width = 22, height = 14, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -52), scale = 0.83 } } } } }, -- fluid flow (bottom) { --render_layer = "lower-object-above-shadow", secondary_draw_order = -47, always_draw = true, apply_tint = "input-fluid-flow-color", north_animation = nil, east_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-E-wet-fluid-flow.png", line_length = 1, width = 12, height = 8, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -52), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-E-wet-fluid-flow.png", line_length = 1, width = 24, height = 14, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -52), scale = 0.83 } } } }, south_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-S-wet-fluid-flow.png", line_length = 1, width = 14, height = 8, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-2, -42), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-S-wet-fluid-flow.png", line_length = 1, width = 26, height = 16, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-2, -42), scale = 0.83 } } } }, west_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-W-wet-fluid-flow.png", line_length = 1, width = 12, height = 8, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -52), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-W-wet-fluid-flow.png", line_length = 1, width = 24, height = 14, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -52), scale = 0.83 } } } } }, -- drill front animation { animated_shift = true, always_draw = true, --north_animation = util.empty_sprite(), east_animation = electric_mining_drill_horizontal_front_animation(), --south_animation = util.empty_sprite(), west_animation = electric_mining_drill_horizontal_front_animation() }, -- fluid window background (front) { always_draw = true, north_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-N-wet-window-background.png", line_length = 1, width = 86, height = 44, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, 10), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-N-wet-window-background.png", line_length = 1, width = 172, height = 90, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, 9), scale = 0.83 } } } }, west_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-W-wet-window-background-front.png", line_length = 1, width = 40, height = 54, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(21, 10), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-W-wet-window-background-front.png", line_length = 1, width = 80, height = 106, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(21, 10), scale = 0.83 } } } }, south_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-S-wet-window-background-front.png", line_length = 1, width = 86, height = 14, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -12), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-S-wet-window-background-front.png", line_length = 1, width = 172, height = 22, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -12), scale = 0.83 } } } }, east_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-E-wet-window-background-front.png", line_length = 1, width = 40, height = 54, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-21, 10), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-E-wet-window-background-front.png", line_length = 1, width = 82, height = 110, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-21, 9), scale = 0.83 } } } } }, -- fluid base (front) { always_draw = true, apply_tint = "input-fluid-base-color", north_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-N-wet-fluid-background.png", line_length = 1, width = 90, height = 46, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, 10), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-N-wet-fluid-background.png", line_length = 1, width = 178, height = 94, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, 9), scale = 0.83 } } } }, west_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-W-wet-fluid-background-front.png", line_length = 1, width = 40, height = 54, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(21, 10), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-W-wet-fluid-background-front.png", line_length = 1, width = 80, height = 102, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(21, 11), scale = 0.83 } } } }, south_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-S-wet-fluid-background-front.png", line_length = 1, width = 90, height = 16, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -12), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-S-wet-fluid-background-front.png", line_length = 1, width = 178, height = 28, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -12), scale = 0.83 } } } }, east_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-E-wet-fluid-background-front.png", line_length = 1, width = 40, height = 54, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-21, 10), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-E-wet-fluid-background-front.png", line_length = 1, width = 82, height = 106, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-21, 10), scale = 0.83 } } } } }, -- fluid flow (front) { always_draw = true, apply_tint = "input-fluid-flow-color", north_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-N-wet-fluid-flow.png", line_length = 1, width = 86, height = 44, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, 10), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-N-wet-fluid-flow.png", line_length = 1, width = 172, height = 88, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, 10), scale = 0.83 } } } }, west_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-W-wet-fluid-flow-front.png", line_length = 1, width = 40, height = 50, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(21, 12), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-W-wet-fluid-flow-front.png", line_length = 1, width = 78, height = 102, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(21, 11), scale = 0.83 } } } }, south_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-S-wet-fluid-flow-front.png", line_length = 1, width = 86, height = 12, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -12), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-S-wet-fluid-flow-front.png", line_length = 1, width = 172, height = 22, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, -12), scale = 0.83 } } } }, east_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-E-wet-fluid-flow-front.png", line_length = 1, width = 40, height = 54, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-21, 10), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-E-wet-fluid-flow-front.png", line_length = 1, width = 78, height = 106, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-21, 10), scale = 0.83 } } } } }, -- front frame (wet) { always_draw = true, north_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-N-wet-front.png", line_length = 1, width = 100, height = 66, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, 24), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-N-wet-front.png", line_length = 1, width = 200, height = 130, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, 24), scale = 0.83 } } } }, west_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-W-wet-front.png", line_length = 1, width = 104, height = 72, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-6, 12), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-W-wet-front.png", line_length = 1, width = 208, height = 144, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-6, 12), scale = 0.83 } } } }, south_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-S-output.png", line_length = 5, width = 44, height = 28, frame_count = 5, animation_speed = electric_drill_animation_speed, shift = util.by_pixel(-2, 34), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-S-output.png", line_length = 5, width = 84, height = 56, frame_count = 5, animation_speed = electric_drill_animation_speed, shift = util.by_pixel(-1, 34), scale = 0.83 } }, { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-S-wet-front.png", line_length = 1, width = 96, height = 70, frame_count = 1, animation_speed = electric_drill_animation_speed, repeat_count = 5, shift = util.by_pixel(0, 24), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-S-wet-front.png", line_length = 1, width = 192, height = 140, frame_count = 1, animation_speed = electric_drill_animation_speed, repeat_count = 5, shift = util.by_pixel(0, 24), scale = 0.83 } } } }, east_animation = { layers = { { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-E-wet-front.png", line_length = 1, width = 106, height = 76, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(3, 10), hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-E-wet-front.png", line_length = 1, width = 208, height = 148, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(3, 11), scale = 0.83 } } } } }, -- LEDs electric_mining_drill_status_leds_working_visualisation(), -- light --electric_mining_drill_primary_light, electric_mining_drill_secondary_light } }, integration_patch = { north = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-N-integration.png", line_length = 1, width = 110, height = 108, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-2, 2), repeat_count = 5, hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-N-integration.png", line_length = 1, width = 216, height = 218, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-1, 1), repeat_count = 5, scale = 0.83 } }, east = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-E-integration.png", line_length = 1, width = 116, height = 108, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(4, 2), repeat_count = 5, hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-E-integration.png", line_length = 1, width = 236, height = 214, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(3, 2), repeat_count = 5, scale = 0.83 } }, south = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-S-integration.png", line_length = 1, width = 108, height = 114, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, 4), repeat_count = 5, hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-S-integration.png", line_length = 1, width = 214, height = 230, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(0, 3), repeat_count = 5, scale = 0.83 } }, west = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-W-integration.png", line_length = 1, width = 118, height = 106, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-4, 2), repeat_count = 5, hr_version = { priority = "high", filename = "__base__/graphics/entity/electric-mining-drill/hr-electric-mining-drill-W-integration.png", line_length = 1, width = 234, height = 214, frame_count = 1, animation_speed = electric_drill_animation_speed, direction_count = 1, shift = util.by_pixel(-4, 1), repeat_count = 5, scale = 0.83 } } }, mining_speed = 3.75, energy_source = { type = "electric", emissions_per_minute = 10, usage_priority = "secondary-input" }, energy_usage = "625kW", resource_searching_radius = 5.49, vector_to_place_result = {0, -2.85}, module_specification = { module_slots = 5 }, radius_visualisation_picture = { filename = "__base__/graphics/entity/electric-mining-drill/electric-mining-drill-radius-visualization.png", width = 10, height = 10 }, monitor_visualization_tint = {r=78, g=173, b=255}, fast_replaceable_group = "mining-drill", circuit_wire_connection_points = circuit_connector_definitions["electric-mining-drill"].points, circuit_connector_sprites = circuit_connector_definitions["electric-mining-drill"].sprites, circuit_wire_max_distance = default_circuit_wire_max_distance } })
function plugindef() finaleplugin.RequireSelection = true finaleplugin.Author = "Carl Vine" finaleplugin.AuthorURL = "http://carlvine.com" finaleplugin.Copyright = "CC0 https://creativecommons.org/publicdomain/zero/1.0/" finaleplugin.Version = "v1.3" finaleplugin.Date = "2022/06/13" finaleplugin.CategoryTags = "MIDI" finaleplugin.Notes = [[ Change the playback START and STOP times for every note in the selected area on one or all layers. To affect playback "Note Durations" must be enabled under "Playback/Record Options". ]] return "MIDI Duration", "MIDI Duration", "Change MIDI note start and stop times" end -- RetainLuaState will return global variables: -- start_offset, stop_offset and layer_number function show_error(error_type, actual_value) local errors = { bad_offset = "Offset times must be reasonable,\nsay -9999 to 9999\n(not ", bad_layer_number = "Layer number must be an\ninteger between zero and 4\n(not ", } finenv.UI():AlertNeutral("script: " .. plugindef(), errors[error_type] .. actual_value .. ")") end function get_user_choices() local current_vert, vert_step = 10, 25 local mac_offset = finenv.UI():IsOnMac() and 3 or 0 -- extra y-offset for Mac text box local edit_horiz = 120 local dialog = finale.FCCustomWindow() local str = finale.FCString() str.LuaString = plugindef() dialog:SetTitle(str) local answer = {} local texts = { -- static text, default value { "Start time:", start_offset or 0 }, { "Stop time:", stop_offset or 0 }, { "Layer# 1-4 (0 = all):", layer_number or 0 }, } for i,v in ipairs(texts) do str.LuaString = v[1] local static = dialog:CreateStatic(0, current_vert) static:SetText(str) static:SetWidth(edit_horiz) answer[i] = dialog:CreateEdit(edit_horiz, current_vert - mac_offset) answer[i]:SetInteger(v[2]) current_vert = current_vert + vert_step end dialog:CreateOkButton() dialog:CreateCancelButton() return (dialog:ExecuteModal(nil) == finale.EXECMODAL_OK), answer[1]:GetInteger(), answer[2]:GetInteger(), answer[3]:GetInteger() end function change_midi_duration() local ok = false is_ok, start_offset, stop_offset, layer_number = get_user_choices() if not is_ok then return end -- user cancelled if start_offset < -9999 or start_offset > 9999 or stop_offset < -9999 or stop_offset > 9999 then show_error("bad_offset", start_offset .. " / " .. stop_offset) return end if layer_number < 0 or layer_number > 4 then show_error("bad_layer_number", layer_number) return end if finenv.RetainLuaState ~= nil then finenv.RetainLuaState = true end for entry in eachentrysaved(finenv.Region(), layer_number) do local perf_mod = finale.FCPerformanceMod() if entry:IsNote() then perf_mod:SetNoteEntry(entry) for note in each(entry) do perf_mod:LoadAt(note) -- don't change durations of tied notes! if not note.TieBackwards then perf_mod.StartOffset = start_offset end if not note.Tie then perf_mod.EndOffset = stop_offset end perf_mod:SaveAt(note) end end end end change_midi_duration()
local Tables = {} Tables.__index = Tables ---Returns a copy of the provided table with shuffled entries. ---@param orderedTable table an ordered table that we want to shuffle. ---@return table shuffledTable a copy of the provided table with shuffled entries. function Tables.ShuffleTable(orderedTable) local tempTable = {table.unpack(orderedTable)} local shuffledTable = {} for i = #tempTable, 1, -1 do local j = math.random(i) tempTable[i], tempTable[j] = tempTable[j], tempTable[i] table.insert(shuffledTable, tempTable[i]) end return shuffledTable end ---Takes an ordered table containing ordered tables and returns an ordered table ---of shuffled tables. ---@param tableWithOrderedTables table ordered table with ordered tables. ---@return table tableWithShuffledTables ordered table with shuffled tables. function Tables.ShuffleTables(tableWithOrderedTables) local tempTable = {table.unpack(tableWithOrderedTables)} local tableWithShuffledTables = {} for orderedTableIndex, orderedTable in ipairs(tempTable) do tableWithShuffledTables[orderedTableIndex] = Tables.ShuffleTable( orderedTable ) end return tableWithShuffledTables end ---Returns a single level indexed table containing all entries from 2nd level ---tables of the provided twoLevelTable. ---@param twoLevelTable table a table of tables. ---@return table singleLevelTable a single level table with all 2nd level table entries. function Tables.GetTableFromTables(twoLevelTable) local tempTable = {table.unpack(twoLevelTable)} local singleLevelTable = {} for _, secondLevelTable in ipairs(tempTable) do for _, entry in ipairs(secondLevelTable) do table.insert(singleLevelTable, entry) end end return singleLevelTable end ---Concatenates two indexed tables. It keeps the order provided in argument, ---i.e. elements of table1 will start at first index, and elements of table2 ---will start at #table1+1. ---Only supports concatenation of two indexed tables, not key-value tables. ---@param table1 table first of the two tables to join. ---@param table2 table second of the two tables to join. ---@return table concatenatedTable concatenated table. function Tables.ConcatenateTables(table1, table2) local concatenatedTable = {table.unpack(table1)} for _, value in ipairs(table2) do table.insert(concatenatedTable, value) end return concatenatedTable end function Tables.RemoveDuplicates(tableIn) print(tableIn) if tableIn == nil then return nil elseif #tableIn < 2 then return {table.unpack(tableIn)} end local hash = {} local tableOut = {} for _, v in ipairs(tableIn) do if not hash[v] then tableOut[#tableOut+1] = v hash[v] = true end end return tableOut end function Tables.Index(table, value) for index, v in ipairs(table) do if v == value then return index end end return nil end --[[ Table shallow copy and deep copy code adapted from Penlight's tablex <https://github.com/lunarmodules/Penlight> Copyright (C) 2009-2016 Steve Donovan, David Manura. 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 function complain (idx,msg) print("ERROR! Argument " .. idx .. " is not " + msg) end local function check_meta (val) if type(val) == 'table' then return true end return getmetatable(val) end local function types_is_iterable (val) local mt = check_meta(val) if mt == true then return true end return mt and mt.__pairs and true end local function assert_arg_iterable (idx,val) if not types_is_iterable(val) then complain(idx,"iterable") end end --- make a shallow copy of a table --- @param tab table an iterable source --- @return table new table function Tables.Copy (t) assert_arg_iterable(1,t) local res = {} for k,v in pairs(t) do res[k] = v end return res end local function cycle_aware_copy(t, cache) if type(t) ~= 'table' then return t end if cache[t] then return cache[t] end assert_arg_iterable(1,t) local res = {} cache[t] = res local mt = getmetatable(t) for k,v in pairs(t) do k = cycle_aware_copy(k, cache) v = cycle_aware_copy(v, cache) res[k] = v end setmetatable(res,mt) return res end --- make a deep copy of a table, recursively copying all the keys and fields. --- This supports cycles in tables; cycles will be reproduced in the copy. --- This will also set the copied table's metatable to that of the original. --- @param tab table A table --- @return table new table function Tables.DeepCopy(t) return cycle_aware_copy(t,{}) end return Tables
physicsFolderCMenu = ContextMenuClass.New("RDynamics") physicsFolderCMenu.xpos = 200; physicsFolderCMenu.ypos = 500; physicsFolderCMenu.panel1.cutWindow=1; physicsFolderCMenu.panel1.cutPanel=panels[4]; physicsFolderCMenu.Redraw(physicsFolderCMenu) item =physicsFolderCMenu.AddListItem(physicsFolderCMenu,"Select Models") function item.CustomSelected(this) selectPhysicsModelsForm.Show(selectPhysicsModelsForm) end dRegisterFeature(physicsFolderCMenu)
-------------------------------------------------------------------------------- -- 0160-string.lua: tests for string-related tools -- This file is a part of lua-nucleo library -- Copyright (c) lua-nucleo authors (see file `COPYRIGHT` for the license) -------------------------------------------------------------------------------- local make_suite = assert(loadfile('test/test-lib/init/strict.lua'))(...) local arguments = import 'lua-nucleo/args.lua' { 'arguments' } local ensure, ensure_equals, ensure_strequals, ensure_tequals, ensure_returns, ensure_fails_with_substring = import 'lua-nucleo/ensure.lua' { 'ensure', 'ensure_equals', 'ensure_strequals', 'ensure_tequals', 'ensure_returns', 'ensure_fails_with_substring' } local make_concatter, trim, escape_string, htmlspecialchars, fill_placeholders_ex, fill_placeholders, fill_curly_placeholders, cdata_wrap, cdata_cat, split_by_char, split_by_offset, count_substrings, kv_concat, escape_lua_pattern, escape_for_json, starts_with, ends_with, create_escape_subst, url_encode, integer_to_string_with_base, cut_with_ellipsis, number_to_string, serialize_number, get_escaped_chars_in_ranges, tjson_simple, string_exports = import 'lua-nucleo/string.lua' { 'make_concatter', 'trim', 'escape_string', 'htmlspecialchars', 'fill_placeholders_ex', 'fill_placeholders', 'fill_curly_placeholders', 'cdata_wrap', 'cdata_cat', 'split_by_char', 'split_by_offset', 'count_substrings', 'kv_concat', 'escape_lua_pattern', 'escape_for_json', 'starts_with', 'ends_with', 'create_escape_subst', 'url_encode', 'integer_to_string_with_base', 'cut_with_ellipsis', 'number_to_string', 'serialize_number', 'get_escaped_chars_in_ranges', 'tjson_simple' } local ordered_pairs = import 'lua-nucleo/tdeepequals.lua' { 'ordered_pairs' } local math_pi = math.pi local table_concat = table.concat -------------------------------------------------------------------------------- local test = make_suite("string", string_exports) -------------------------------------------------------------------------------- test:tests_for "make_concatter" test "make_concatter-basic" (function() local cat, concat = make_concatter() ensure_equals("cat is function", type(cat), "function") ensure_equals("concat is function", type(concat), "function") ensure_equals("cat returns self", cat("42"), cat) ensure_equals("concat on single element", concat(), "42") end) test "make_concatter-empty" (function() local cat, concat = make_concatter() ensure_equals("concat on empty data is empty string", concat(), "") end) test "make_concatter-simple" (function() local cat, concat = make_concatter() cat "a" cat "bc" (42) cat "" "d" "" ensure_equals("concat", concat(), "abc42d") end) test "make_concatter-embedded-zeroes" (function() local cat, concat = make_concatter() cat "a" "\0" "bc\0" "def\0" ensure_equals("concat", concat(), "a\0bc\0def\0") end) test "make_concatter-glue" (function() local cat, concat = make_concatter() cat "a" "\0" "bc\0" "def\0" ensure_equals("concat", concat("{\0}"), "a{\0}\0{\0}bc\0{\0}def\0") end) -------------------------------------------------------------------------------- test:tests_for "trim" test "trim-basic" (function() ensure_equals("empty string", trim(""), "") ensure_equals("none", trim("a"), "a") ensure_equals("left", trim(" b"), "b") ensure_equals("right", trim("c "), "c") ensure_equals("both", trim(" d "), "d") ensure_equals("middle", trim("e f"), "e f") ensure_equals("many", trim("\t \t \tg \th\t \t "), "g \th") end) -------------------------------------------------------------------------------- test:tests_for "starts_with" test "starts_with-minimal" (function() ensure_equals("trivial", starts_with("", ""), true) ensure_equals("strings always start with empty string", starts_with("abc", ""), true) ensure_equals("1..1", starts_with("abc", "a"), true) ensure_equals("1..2", starts_with("abc", "ab"), true) ensure_equals("1..3", starts_with("abc", "abc"), true) ensure_equals("1..4", starts_with("abc", "abcb"), false) ensure_equals("special char", starts_with("abc", "\000"), false) ensure_equals("binary-safe", starts_with("Русский язык велик и могуч", "Русский я"), true) ensure_equals("against number", starts_with("foo", 1), false) ensure_equals("against boolean", starts_with("foo", false), false) ensure_equals("against table", starts_with("foo", { }), false) ensure_equals("against nil", starts_with("foo", nil), false) end) test:tests_for "ends_with" test "ends_with-minimal" (function() ensure_equals("trivial", ends_with("", ""), true) ensure_equals("strings always end with empty string", ends_with("abc", ""), true) ensure_equals("1..1", ends_with("abc", "c"), true) ensure_equals("1..2", ends_with("abc", "bc"), true) ensure_equals("1..3", ends_with("abc", "abc"), true) ensure_equals("1..4", ends_with("abc", "abc "), false) ensure_equals("special char", ends_with("abc", "\000"), false) ensure_equals("binary-safe", ends_with("Русский язык велик и могуч", "к и могуч"), true) ensure_equals("against number", ends_with("foo", 1), false) ensure_equals("against boolean", ends_with("foo", false), false) ensure_equals("against table", ends_with("foo", { }), false) ensure_equals("against nil", ends_with("foo", nil), false) end) -------------------------------------------------------------------------------- test:tests_for "escape_string" test "escape_string-minimal" (function() ensure_equals( "Equal strings", escape_string("simple str without wrong chars"), "simple str without wrong chars" ) ensure_equals("escaped str exceptions", escape_string("\009\010"), "\t\n") ensure_equals( "escaped str", escape_string("\000\001\128"), "%00%01%80" ) local str_test = "" for i = 0, 255 do str_test = str_test .. string.char(i) end ensure_equals("escaped str all symbols 129 - 255", escape_string(str_test), [[%00%01%02%03%04%05%06%07%08]] .. "\t\n" .. [[%0B%0C%0D%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F !"#$%]] .. [[&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghij]] .. [[klmnopqrstuvwxyz{|}~%7F%80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%]] .. [[8F%90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4%A5%]] .. [[A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%]] .. [[BD%BE%BF%C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1%D2%D3%]] .. [[D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%]] .. [[EB%EC%ED%EE%EF%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF]]) end) -------------------------------------------------------------------------------- test:tests_for "create_escape_subst" test "create_escape_subst-minimal" (function() local escape_subst = create_escape_subst("\\%03d") local str_test = "" for i = 0, 255 do str_test = str_test .. string.char(i) end ensure_equals( "Equal strings", tostring( str_test ):gsub("[%c%z\128-\255]", escape_subst), [[\000\001\002\003\004\005\006\007\008]] .. "\t\n" .. [[\011\012\013\014\015\016\017]] .. [[\018\019\020\021\022\023\024\025\026\027\028\029\030\031 !"#$%&'()*+]] .. [[,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmno]] .. [[pqrstuvwxyz{|}~\127\128\129\130\131\132\133\134\135\136\137\138\139\]] .. [[140\141\142\143\144\145\146\147\148\149\150\151\152\153\154\155\156\]] .. [[157\158\159\160\161\162\163\164\165\166\167\168\169\170\171\172\173\]] .. [[174\175\176\177\178\179\180\181\182\183\184\185\186\187\188\189\190\]] .. [[191\192\193\194\195\196\197\198\199\200\201\202\203\204\205\206\207\]] .. [[208\209\210\211\212\213\214\215\216\217\218\219\220\221\222\223\224\]] .. [[225\226\227\228\229\230\231\232\233\234\235\236\237\238\239\240\241\]] .. [[242\243\244\245\246\247\248\249\250\251\252\253\254\255]] ) end) -------------------------------------------------------------------------------- test:tests_for "htmlspecialchars" test "htmlspecialchars-minimal" (function() -- Uses texts from PHP 5.3.0 htmlspecialchars tests local buf = { } -- We need special cat, not using make_concatter local cat = function(v) -- Matching var_dump for strings arguments("string", v) buf[#buf + 1] = 'string(' buf[#buf + 1] = #v buf[#buf + 1] = ') "' buf[#buf + 1] = v -- Unquoted buf[#buf + 1] = "\"\n" end -- normal string cat (htmlspecialchars("<br>Testing<p>New file.</p> ")) -- long string cat (htmlspecialchars("<br>Testing<p>New file.</p><p><br>File <b><i><u>WORKS!!!</i></u></b></p><br><p>End of file!!!</p>")) -- checking behavior of quote cat (htmlspecialchars("A 'quote' is <b>bold</b>")) local expected = [[ string(46) "&lt;br&gt;Testing&lt;p&gt;New file.&lt;/p&gt; " string(187) "&lt;br&gt;Testing&lt;p&gt;New file.&lt;/p&gt;&lt;p&gt;&lt;br&gt;File &lt;b&gt;&lt;i&gt;&lt;u&gt;WORKS!!!&lt;/i&gt;&lt;/u&gt;&lt;/b&gt;&lt;/p&gt;&lt;br&gt;&lt;p&gt;End of file!!!&lt;/p&gt;" string(46) "A &apos;quote&apos; is &lt;b&gt;bold&lt;/b&gt;" ]] ensure_strequals("escaped", table.concat(buf), expected) end) -------------------------------------------------------------------------------- test:tests_for "escape_lua_pattern" test "escape_lua_pattern-basic" (function() ensure_strequals( "escapinng lua pattern", escape_lua_pattern("abc^$()%.[]*+-?\0xyz"), "abc%^%$%(%)%%%.%[%]%*%+%-%?%zxyz" ) ensure_strequals( "no escapinng", escape_lua_pattern("just normal string 12345"), "just normal string 12345" ) end) test "escape_lua_pattern-find" (function() local cat, concat = make_concatter() for i = 0, 255 do cat(string.char(i)) end local input_string = concat() -- contains all possible symbols for i = 0, 255 do -- check all possible symbols local char = string.char(i) local i_start, i_end = input_string:find(escape_lua_pattern(char)) ensure("match for " .. char .. " is found", i_start) ensure_equals("match for " .. char .. " is one symbol", i_start, i_end) ensure_equals("position for " .. char .. " is correct", i_start, i + 1) end end) -------------------------------------------------------------------------------- test:tests_for 'cdata_wrap' 'cdata_cat' -------------------------------------------------------------------------------- test "cdata_wrap-cdata_cat" (function() local check = function(value, expected) do local actual = cdata_wrap(value) ensure_strequals("cdata_wrap", actual, expected) end do local cat, concat = make_concatter() cdata_cat(cat, value) ensure_strequals("cdata_cat", concat(), expected) end end check("", "<![CDATA[]]>") check("embedded\0zero", "<![CDATA[embedded\0zero]]>") check("<![CDATA[xxx]]>", "<![CDATA[<![CDATA[xxx]]]]><![CDATA[>]]>") end) -------------------------------------------------------------------------------- test:tests_for "split_by_char" test "split_by_char-basic" (function() ensure_fails_with_substring( "both empty", function() split_by_char("", "") end, "Invalid delimiter" ) ensure_fails_with_substring( "empty delimiter", function() split_by_char("abc", "") end, "Invalid delimiter" ) ensure_fails_with_substring( "empty delimiter & bad arg type for string", function() split_by_char(1, "") end, "Param str must be a string" ) ensure_tequals("empty string", split_by_char("", " "), { }) -- NOTE: Test logic for split_* based on reversability of spliting: -- split_by_char("mLoremIpsum", "m") must return { "", "Lore", "Ipsu", "" }. ensure_tequals( "string explode", split_by_char("mLoremIpsum", "m"), { "", "Lore", "Ipsu", "" } ) ensure_strequals( "reversability: string implode after explode", table_concat(split_by_char("mLoremIpsum", "m"), "m"), "mLoremIpsum" ) ensure_tequals("trailing delimiter", split_by_char("t ", " "), { "t", "" }) ensure_tequals("leading delimiter", split_by_char(" t", " "), { "", "t" }) ensure_tequals( "leading and trailing delimiter", split_by_char(" t ", " "), { "", "t", "" } ) ensure_tequals( "word not divided", split_by_char("Lorem!", "t"), { "Lorem!" } ) ensure_tequals( "phrase with escapes", split_by_char("\nLorem \tipsum?#$%^&*()_+|~/\t \001dolor \007sit\n", " "), { "\nLorem", "\tipsum?#$%^&*()_+|~/\t", "\001dolor", "\007sit\n" } ) ensure_tequals( "phrase with escapes and zero", split_by_char("\nLorem \tipsum?#$%^&*()_+|~/\t \0dolor \007sit.\n", " "), { "\nLorem", "\tipsum?#$%^&*()_+|~/\t", "\0dolor", "\007sit.\n" } ) ensure_fails_with_substring( "space string, delimiter with escapes and zero", function() split_by_char(" ", "\nLorem \tipsum?#$%^&*()_+|~/\t \0dolor \007sit.\n") end, "Invalid delimiter" ) ensure_fails_with_substring( "empty string & delimiter with escapes and zero", function() split_by_char("", "\nLorem \tipsum?#$%^&*()_+|~/\t \0dolor \007sit.\n") end, "Invalid delimiter" ) ensure_tequals( "quirky delimiter", split_by_char("\000\000", "\000"), { "", "", "" } ) ensure_tequals( "rich text and zero delimiter", split_by_char("Барсик!", "\000"), { "Барсик!" } ) end) -------------------------------------------------------------------------------- test:tests_for 'split_by_offset' test:test "split_by_offset-basic" (function() local BASIC_STRING = "Lorem ipsum dolor sit amet" ensure_fails_with_substring( "test with offset > #str", function() split_by_offset(BASIC_STRING, 100) end, "offset greater than str length" ) ensure_fails_with_substring( "test with offset = #str+1", function() split_by_offset(BASIC_STRING, 1 + #BASIC_STRING) end, "offset greater than str length" ) ensure_returns( "offset < 0", 2, { BASIC_STRING, BASIC_STRING }, split_by_offset(BASIC_STRING, -1) ) ensure_returns( "offset = 0", 2, { "", BASIC_STRING }, split_by_offset(BASIC_STRING, 0) ) ensure_returns( "offset = 1", 2, { "L", "orem ipsum dolor sit amet" }, split_by_offset(BASIC_STRING, 1) ) ensure_returns( "max offset", 2, { BASIC_STRING, "" }, split_by_offset(BASIC_STRING, #BASIC_STRING) ) ensure_returns( "max offset and skip 0", 2, { BASIC_STRING, "" }, split_by_offset(BASIC_STRING, #BASIC_STRING, 0) ) ensure_returns( "max offset and skip -2", 2, { BASIC_STRING, "et" }, split_by_offset(BASIC_STRING, #BASIC_STRING, -2) ) ensure_returns( "max offset and skip -max", 2, { BASIC_STRING, BASIC_STRING }, split_by_offset(BASIC_STRING, #BASIC_STRING, -#BASIC_STRING) ) ensure_returns( "max offset and skip under begin", 2, { BASIC_STRING, BASIC_STRING }, split_by_offset(BASIC_STRING, #BASIC_STRING, -1 - #BASIC_STRING) ) ensure_returns( "max offset and skip max", 2, { BASIC_STRING, "" }, split_by_offset(BASIC_STRING, #BASIC_STRING, 1 + #BASIC_STRING) ) ensure_returns( "offset 1 and skip 0", 2, { "L", "orem ipsum dolor sit amet" }, split_by_offset(BASIC_STRING, 1, 0) ) ensure_returns( "offset 1 and skip 5", 2, { "L", "ipsum dolor sit amet" }, split_by_offset(BASIC_STRING, 1, 5) ) ensure_returns( "offset 5 and skip 5", 2, { "Lorem", "m dolor sit amet" }, split_by_offset(BASIC_STRING, 5, 5) ) end) -------------------------------------------------------------------------------- test:tests_for "fill_placeholders_ex" test "fill_placeholders_ex-basic" (function() ensure_strequals( "both empty", fill_placeholders_ex("%$%((.-)%)", "", { }), "" ) ensure_strequals( "empty dict", fill_placeholders_ex("%$%((.-)%)", "test", { }), "test" ) ensure_strequals( "empty str", fill_placeholders_ex("%$%((.-)%)", "", { a = 42 }), "" ) ensure_strequals( "missing key", fill_placeholders_ex("%$%((.-)%)", "$(b)", { a = 42 }), "$(b)" ) ensure_strequals( "bad format", fill_placeholders_ex("%$%((.-)%)", "$a", { a = 42 }), "$a" ) ensure_strequals( "missing right brace", fill_placeholders_ex("%$%((.-)%)", "$a)", { a = 42 }), "$a)" ) ensure_strequals( "missing left brace", fill_placeholders_ex("%$%((.-)%)", "$(a", { a = 42 }), "$(a" ) ensure_strequals( "proper usage", fill_placeholders_ex("%$%((.-)%)", "a = `$(a)'", { a = 42 }), "a = `42'" ) ensure_tequals( "check for no extra data being generated", { fill_placeholders_ex("%$%((.-)%)", "a = `$(a)'", { a = 42 }) }, { "a = `42'" } ) ensure_strequals( "extra key", fill_placeholders_ex("%$%((.-)%)", "a = `$(a)'", { a = 42, b = 43 }), "a = `42'" ) ensure_strequals( "two keys", fill_placeholders_ex( "%$%((.-)%)", "`$(key)' = `$(value)'", { key = "a", value = 42 } ), "`a' = `42'" ) ensure_strequals( "empty string key", fill_placeholders_ex("%$%((.-)%)", "`$()'", { [""] = 42 }), "`42'" ) ensure_strequals( "extra braces", fill_placeholders_ex("%$%((.-)%)", "$(a `$(a)')", { a = 42 }), "$(a `$(a)')" ) ensure_strequals( "extra braces pragmatic", fill_placeholders_ex("%$%((.-)%)", "$(a `$(a)')", { ["a `$(a"] = 42 }), "42')" ) ensure_strequals( "extra right round brace", fill_placeholders_ex("%$%((.-)%)", "`$(a)')", { a = 42 }), "`42')" ) ensure_strequals( "extra right curly brace", fill_placeholders_ex("%$%((.-)%)", "`$(a)'}", { a = 42 }), "`42'}" ) ensure_strequals( "curly: both empty", fill_placeholders_ex("%${(.-)}", "", { }), "" ) ensure_strequals( "curly: empty dict", fill_placeholders_ex("%${(.-)}", "test", { }), "test" ) ensure_strequals( "curly: empty str", fill_placeholders_ex("%${(.-)}", "", { a = 42 }), "" ) ensure_strequals( "curly: missing key", fill_placeholders_ex("%${(.-)}", "${b}", { a = 42 }), "${b}" ) ensure_strequals( "curly: bad format", fill_placeholders_ex("%${(.-)}", "$a", { a = 42 }), "$a" ) ensure_strequals( "curly: missing right brace", fill_placeholders_ex("%${(.-)}", "$a}", { a = 42 }), "$a}" ) ensure_strequals( "curly: missing left brace", fill_placeholders_ex("%${(.-)}", "${a", { a = 42 }), "${a" ) ensure_strequals( "curly: proper usage", fill_placeholders_ex("%${(.-)}", "a = `${a}'", { a = 42 }), "a = `42'" ) ensure_tequals( "curly: check for no extra data being generated", { fill_placeholders_ex("%${(.-)}", "a = `${a}'", { a = 42 }) }, { "a = `42'" } ) ensure_strequals( "curly: extra key", fill_placeholders_ex("%${(.-)}", "a = `${a}'", { a = 42, b = 43 }), "a = `42'" ) ensure_strequals( "curly: two keys", fill_placeholders_ex( "%${(.-)}", "`${key}' = `${value}'", { key = "a", value = 42 } ), "`a' = `42'" ) ensure_strequals( "curly: empty string key", fill_placeholders_ex("%${(.-)}", "`${}'", { [""] = 42 }), "`42'" ) ensure_strequals( "curly: extra braces", fill_placeholders_ex("%${(.-)}", "${a `${a}'}", { a = 42 }), "${a `${a}'}" ) ensure_strequals( "curly: extra braces pragmatic", fill_placeholders_ex("%${(.-)}", "${a `${a}'}", { ["a `${a"] = 42 }), "42'}" ) ensure_strequals( "curly: extra right brace", fill_placeholders_ex("%${(.-)}", "`${a}'}", { a = 42 }), "`42'}" ) ensure_strequals( "curly: extra round braces", fill_placeholders_ex("%${(.-)}", "${a `${a}'}", { a = 42 }), "${a `${a}'}" ) ensure_strequals( "curly: extra right curly brace", fill_placeholders_ex("%${(.-)}", "`${a}'}", { a = 42 }), "`42'}" ) ensure_strequals( "curly: extra right round brace", fill_placeholders_ex("%${(.-)}", "`${a}')", { a = 42 }), "`42')" ) end) -------------------------------------------------------------------------------- test:test_for "fill_placeholders" (function() ensure_strequals("both empty", fill_placeholders("", { }), "") ensure_strequals("empty dict", fill_placeholders("test", { }), "test") ensure_strequals("empty str", fill_placeholders("", { a = 42 }), "") ensure_strequals( "missing key", fill_placeholders("$(b)", { a = 42 }), "$(b)" ) ensure_strequals("bad format", fill_placeholders("$a", { a = 42 }), "$a") ensure_strequals( "missing right brace", fill_placeholders("$a)", { a = 42 }), "$a)" ) ensure_strequals( "missing left brace", fill_placeholders("$(a", { a = 42 }), "$(a" ) ensure_strequals( "proper usage", fill_placeholders("a = `$(a)'", { a = 42 }), "a = `42'" ) ensure_tequals( "check for no extra data being generated", { fill_placeholders("a = `$(a)'", { a = 42 }) }, { "a = `42'" } ) ensure_strequals( "extra key", fill_placeholders("a = `$(a)'", { a = 42, b = 43 }), "a = `42'" ) ensure_strequals( "two keys", fill_placeholders("`$(key)' = `$(value)'", { key = "a", value = 42 }), "`a' = `42'" ) ensure_strequals( "empty string key", fill_placeholders("`$()'", { [""] = 42 }), "`42'" ) ensure_strequals( "extra braces", fill_placeholders("$(a `$(a)')", { a = 42 }), "$(a `$(a)')" ) ensure_strequals( "extra braces pragmatic", fill_placeholders("$(a `$(a)')", { ["a `$(a"] = 42 }), "42')" ) ensure_strequals( "extra right brace", fill_placeholders("`$(a)')", { a = 42 }), "`42')" ) end) -------------------------------------------------------------------------------- test:test_for "fill_curly_placeholders" (function() ensure_strequals( "both empty", fill_curly_placeholders("", { }), "" ) ensure_strequals( "empty dict", fill_curly_placeholders("test", { }), "test" ) ensure_strequals( "empty str", fill_curly_placeholders("", { a = 42 }), "" ) ensure_strequals( "missing key", fill_curly_placeholders("${b}", { a = 42 }), "${b}" ) ensure_strequals( "bad format", fill_curly_placeholders("$a", { a = 42 }), "$a" ) ensure_strequals( "missing right brace", fill_curly_placeholders("$a}", { a = 42 }), "$a}" ) ensure_strequals( "missing left brace", fill_curly_placeholders("${a", { a = 42 }), "${a" ) ensure_strequals( "proper usage", fill_curly_placeholders("a = `${a}'", { a = 42 }), "a = `42'" ) ensure_tequals( "check for no extra data being generated", { fill_curly_placeholders("a = `${a}'", { a = 42 }) }, { "a = `42'" } ) ensure_strequals( "extra key", fill_curly_placeholders("a = `${a}'", { a = 42, b = 43 }), "a = `42'" ) ensure_strequals( "two keys", fill_curly_placeholders("`${key}' = `${value}'", { key = "a", value = 42 }), "`a' = `42'" ) ensure_strequals( "empty string key", fill_curly_placeholders("`${}'", { [""] = 42 }), "`42'" ) ensure_strequals( "extra braces", fill_curly_placeholders("${a `${a}'}", { a = 42 }), "${a `${a}'}" ) ensure_strequals( "extra braces pragmatic", fill_curly_placeholders("${a `${a}'}", { ["a `${a"] = 42 }), "42'}" ) ensure_strequals( "extra right brace", fill_curly_placeholders("`${a}'}", { a = 42 }), "`42'}" ) end) -------------------------------------------------------------------------------- test:tests_for 'count_substrings' test:test "count_substrings-basic" (function() local BASIC_STRING = "Lorem ipsum dolor sit amet, consectetur adipiscing elit" ensure_fails_with_substring( "both empty", function() count_substrings("", "") end, "substring must be not empty" ) ensure_equals("str empty", count_substrings("", BASIC_STRING), 0) ensure_fails_with_substring( "substr empty", function() count_substrings(BASIC_STRING, "") end, "substring must be not empty" ) ensure_equals("str equal substr", count_substrings("t", "t"), 1) ensure_equals("zero count", count_substrings(BASIC_STRING, "est"), 0) ensure_equals("positive count", count_substrings(BASIC_STRING, "o"), 4) ensure_equals( "positive count for word", count_substrings(BASIC_STRING, "sit"), 1 ) ensure_equals( "special character string", count_substrings( "\nLorem \tipsum?#$%^&*()_+|~/\t \0dolor \007sit.\n", "o" ), 3 ) end) -------------------------------------------------------------------------------- test:tests_for 'kv_concat' test:test "kv_concat-basic" (function() ensure_strequals("empty, no iterator and pairs glue", kv_concat({ }, ""), "") ensure_strequals("empty, no iterator", kv_concat({ }, "", ""), "") ensure_strequals("empty table, no iterator", kv_concat({ }, " ", " "), "") ensure_strequals("empty table", kv_concat({ }, " ", " ", pairs), "") ensure_strequals( "pairs iterator", kv_concat({ 3, "2", 1, "!?#$%^&*()_+|~/" }, " ", ",", pairs), "1 3,2 2,3 1,4 !?#$%^&*()_+|~/" ) ensure_strequals( "ipairs iterator", kv_concat({ 3, "2", 1, "!?#$%^&*()_+|~/" }, " ", ",", ipairs), "1 3,2 2,3 1,4 !?#$%^&*()_+|~/" ) ensure_strequals("empty table, ipairs", kv_concat({ }, " ", ",", ipairs), "") ensure_strequals( "ipairs cut not an integer indexes", kv_concat({ x = 3, y = "2", 1, "!?#$%^&*()_+|~/" }, "=", ",", ipairs), "1=1,2=!?#$%^&*()_+|~/" ) -- Feature: We have to use very slow ordered_pairs() due to undefined -- traversal order with regular pairs(), which can break compatibility -- between Lua 5.1 and LuaJIT 2 ensure_strequals( "2 integer 2 non-integer indexes result unorder with pairs", kv_concat( {x = 3, y = "2", z = 1, aaa = "!?#$%^&*()_+|~/"}, "=", ",", ordered_pairs ), "aaa=!?#$%^&*()_+|~/,x=3,y=2,z=1" ) ensure_strequals( "2 integer 2 non-integer indexes result unorder with pairs", kv_concat({ x = 3, y = "2", 1, "!?#$%^&*()_+|~/" }, "=", ",", pairs), "1=1,2=!?#$%^&*()_+|~/,y=2,x=3" ) ensure_strequals( "2 integer 2 non-integer indexes result unorder with no function", kv_concat({ x = 3, y = "2", 1, "!?#$%^&*()_+|~/" }, "=", ","), "1=1,2=!?#$%^&*()_+|~/,y=2,x=3" ) -- Feature: nested tables is not allowed ensure_fails_with_substring( "nested tables are invalid", function() kv_concat({ 3, "2", { 1, "!?#$%^&*()_+|~/" } }, " ", ",", pairs) end, "invalid value" ) end) -------------------------------------------------------------------------------- test:tests_for "escape_for_json" test "escape_for_json-basic" (function() ensure_strequals( "letters and slash", escape_for_json("abcXYZs/n"), "\"abcXYZs/n\"" ) ensure_strequals("slash and backslash", escape_for_json("s/\n"), "\"s/\\n\"") ensure_strequals( "escape sequences", escape_for_json("\"s/\n\b\fu\rper\t\v"), "\"\\\"s/\\n\\b\\fu\\rper\\t\\v\"" ) ensure_strequals("double backslash", escape_for_json(" \\ "), "\" \\\\ \"") ensure_strequals("slash num", escape_for_json(" /007 "), "\" /007 \"") end) test "escape_for_json-injection" (function() ensure_strequals( "common json injection", escape_for_json( "';alert(String.fromCharCode(88,83,83))//\';alert(String.fromCharC" .. "ode(88,83,83))//\";alert(String.fromCharCode(88,83,83))//\";alert" .. "(String.fromCharCode(88,83,83))//--></SCRIPT>\">'><SCRIPT>alert(S" .. "tring.fromCharCode(88,83,83))</SCRIPT>" ), "\"';alert(String.fromCharCode(88,83,83))//';alert(String.fromCharCode" .. "(88,83,83))//\\\";alert(String.fromCharCode(88,83,83))//\\\";alert(St" .. "ring.fromCharCode(88,83,83))//--></SCRIPT>\\\">'><SCRIPT>alert(String" .. ".fromCharCode(88,83,83))</SCRIPT>\"" ) end) -------------------------------------------------------------------------------- test:test_for "url_encode" (function() ensure_strequals("empty", url_encode(""), "") ensure_strequals("simple", url_encode("test"), "test") ensure_strequals("test with number", url_encode("test555"), "test555") ensure_strequals("test with space", url_encode("test string"), "test+string") ensure_strequals( "symbols", url_encode("1234567890-=!@#$%^&*()_+"), "1234567890-%3D%21%40%23%24%25%5E%26%2A%28%29_%2B" ) end) -------------------------------------------------------------------------------- test:test_for "integer_to_string_with_base" (function() ensure_equals("simple", integer_to_string_with_base(10, 26), "A") ensure_equals("empty base", integer_to_string_with_base(10), "10") ensure_equals("test with negative numbers", integer_to_string_with_base(-11, 26), "-B") ensure_equals("test with zero and empty base", integer_to_string_with_base(0), "0") ensure_equals("test with zero and non-empty base", integer_to_string_with_base(0, 15), "0") -- NOTE: integer_to_string_with_base(-0) can produce '0' or '-0', depending on -- previous code. See: -- http://thread.gmane.org/gmane.comp.lang.lua.general/90837/focus=90838 -- http://article.gmane.org/gmane.comp.lang.lua.general/12950 ensure( "test with negative zero and empty base", integer_to_string_with_base(-0) == "0" or integer_to_string_with_base(-0) == "-0" ) local n = 136 local base = 36 local str = integer_to_string_with_base(n, base) ensure_equals("test with tonumber", tonumber(str, base), n) ensure_fails_with_substring("test with empty params", integer_to_string_with_base, "n must be a number") ensure_fails_with_substring( "test with string value of base", function() integer_to_string_with_base(10, "asd") end, "base must be a number" ) ensure_fails_with_substring( "test with negative base", function() integer_to_string_with_base(10, -10) end, "base out of range" ) ensure_fails_with_substring( "test on nan", function() integer_to_string_with_base(0/0) end, "n is nan" ) ensure_fails_with_substring( "test on +inf", function() integer_to_string_with_base(1/0) end, "n is inf" ) ensure_fails_with_substring( "test on -inf", function() integer_to_string_with_base(-1/0) end, "n is inf" ) ensure_fails_with_substring( "test on -inf", function() integer_to_string_with_base(-1/0) end, "n is inf" ) end) test:test_for "cut_with_ellipsis" (function() local test_string = "test long string" ensure_equals( "test with string with correct max length", cut_with_ellipsis(test_string, #test_string), test_string ) ensure_equals( "test with string length - 1", cut_with_ellipsis(test_string, #test_string - 1), "test long st..." ) ensure_equals( "test with string length - 2", cut_with_ellipsis(test_string, #test_string - 2), "test long s..." ) ensure_equals( "test with string length - 3", cut_with_ellipsis(test_string, #test_string - 3), "test long ..." ) ensure_equals( "test with string with excess max length", cut_with_ellipsis(test_string, #test_string + 50), test_string ) ensure_equals( "test with string with default max length", cut_with_ellipsis(test_string), test_string ) ensure_equals( "test with cutting long string", cut_with_ellipsis(test_string, 12), "test long..." ) ensure_equals( "test with max length = 1", cut_with_ellipsis(test_string, 1), "t" ) ensure_equals( "test with max length = 2", cut_with_ellipsis(test_string, 2), "te" ) ensure_equals( "test with max length = 3", cut_with_ellipsis(test_string, 3), "tes" ) ensure_equals( "test with max length = 4", cut_with_ellipsis(test_string, 4), "t..." ) ensure_equals( "test with empty string", cut_with_ellipsis(""), "" ) ensure_fails_with_substring( "test with non-positive required string length", function() cut_with_ellipsis(test_string, 0) end, "required string length must be positive" ) end) -------------------------------------------------------------------------------- test:test_for "number_to_string" (function() ensure_strequals("inf", number_to_string(1/0), "1/0") ensure_strequals("-inf", number_to_string(-1/0), "-1/0") ensure_strequals("nan", number_to_string(0/0), "0/0") end) test:test_for "serialize_number" (function() ensure_strequals("inf", serialize_number( 1/0), "1/0") ensure_strequals("-inf", serialize_number(-1/0), "-1/0") ensure_strequals("nan", serialize_number(0/0), "0/0") ensure_strequals("123", serialize_number(123), "123") local pi_15 = loadstring("return " .. ("%.15g"):format(math_pi))() local pi_16 = loadstring("return " .. ("%.16g"):format(math_pi))() local pi_17 = loadstring("return " .. serialize_number(math_pi))() local pi_18 = loadstring("return " .. ("%.18g"):format(math_pi))() local pi_55 = loadstring("return " .. ("%.55g"):format(math_pi))() ensure( "serialize pi by %.15g", pi_15 ~= math.pi ) ensure( "serialize pi by %.16g", pi_16 == math.pi ) ensure( "serialize pi by %.17g", pi_17 == math.pi ) ensure( "serialize pi by %.18g", pi_18 == math.pi ) ensure( "serialize pi by %.55g", pi_55 == math.pi ) local one_third_15 = loadstring("return " .. ("%.15g"):format(1/3))() local one_third_16 = loadstring("return " .. ("%.16g"):format(1/3))() local one_third_17 = loadstring("return " .. serialize_number(1/3))() local one_third_18 = loadstring("return " .. ("%.18g"):format(1/3))() local one_third_55 = loadstring("return " .. ("%.55g"):format(1/3))() ensure( "serialize 1/3 by %.15g", one_third_15 ~= 1/3 ) ensure( "serialize 1/3 by %.16g", one_third_16 == 1/3 ) ensure( "serialize 1/3 by %.17g", one_third_17 == 1/3 ) ensure( "serialize 1/3 by %.18g", one_third_18 == 1/3 ) ensure( "serialize 1/3 by %.55g", one_third_55 == 1/3 ) end) -------------------------------------------------------------------------------- test:tests_for 'get_escaped_chars_in_ranges' test:test "get_escaped_chars_in_ranges-basic" (function() -- Invalid tests (argument errors). ensure_fails_with_substring( "missed argument", get_escaped_chars_in_ranges, "argument must be a table" ) ensure_fails_with_substring( "invalid type argument", function() get_escaped_chars_in_ranges("asd") end, "argument must be a table" ) ensure_fails_with_substring( "one element in table", function() get_escaped_chars_in_ranges({ "asd" }) end, "argument must have even number of elements" ) ensure_fails_with_substring( "three elements in table", function() get_escaped_chars_in_ranges({ "1", "2", "3" }) end, "argument must have even number of elements" ) -- Valid tests: -- Chars range boundaries ensure_strequals("equal str", get_escaped_chars_in_ranges({ "e", "e" }), "%e") ensure_strequals("equal int", get_escaped_chars_in_ranges({ "6", "6" }), "%6") ensure_strequals( "2 integers in string", get_escaped_chars_in_ranges({ "7", "8" }), "%7%8" ) ensure_strequals( "4 ints in string", get_escaped_chars_in_ranges({ "7", "8", "45", "33" }), "%7%8" ) ensure_strequals( "2-digit int in string", get_escaped_chars_in_ranges({ "66", "77", "45", "33" }), "%6%7" ) ensure_strequals( "range in int in string", get_escaped_chars_in_ranges({ "22", "77", "4", "254" }), "%2%3%4%5%6%7" ) ensure_strequals( "max range in int in string", get_escaped_chars_in_ranges({ "0", "9", "A", "Z" }), "%0%1%2%3%4%5%6%7%8%9%A%B%C%D%E%F%G%H%I%J%K%L%M%N%O%P%Q%R%S%T%U%V%W%X%Y%Z" ) ensure_strequals( "char range", get_escaped_chars_in_ranges({ "a", "d", "4", "25" }), "%a%b%c%d" ) ensure_strequals( "char and int in str range", get_escaped_chars_in_ranges({ "a", "d", "4", "9" }), "%a%b%c%d%4%5%6%7%8%9" ) ensure_strequals( "from 0 to A", get_escaped_chars_in_ranges({ "0", "A" }), "%0%1%2%3%4%5%6%7%8%9%:%;%<%=%>%?%@%A" ) ensure_strequals( "from space to ~", get_escaped_chars_in_ranges({ " ", "~" }), "% %!%\"%#%$%%%&%'%(%)%*%+%,%-%.%/%0%1%2%3%4%5%6%7%8%9%:%;%<%=%>%?%@%A" .. "%B%C%D%E%F%G%H%I%J%K%L%M%N%O%P%Q%R%S%T%U%V%W%X%Y%Z%[%\\%]%^%_%`%a%b%c" .. "%d%e%f%g%h%i%j%k%l%m%n%o%p%q%r%s%t%u%v%w%x%y%z%{%|%}%~" ) -- Integers range boundaries ensure_strequals( "integer range", get_escaped_chars_in_ranges({ 32, 58 }), "% %!%\"%#%$%%%&%'%(%)%*%+%,%-%.%/%0%1%2%3%4%5%6%7%8%9%:" ) ensure_strequals( "from ch(32) to ch(32)", get_escaped_chars_in_ranges({ 32, 126 }), "% %!%\"%#%$%%%&%'%(%)%*%+%,%-%.%/%0%1%2%3%4%5%6%7%8%9%:%;%<%=%>%?%@%A" .. "%B%C%D%E%F%G%H%I%J%K%L%M%N%O%P%Q%R%S%T%U%V%W%X%Y%Z%[%\\%]%^%_%`%a%b%c" .. "%d%e%f%g%h%i%j%k%l%m%n%o%p%q%r%s%t%u%v%w%x%y%z%{%|%}%~" ) -- Mixed range boundaries ensure_strequals( "all mixed up", get_escaped_chars_in_ranges({ "0", 50 }), "%0%1%2" ) ensure_strequals( "from ch(32) to ~", get_escaped_chars_in_ranges({ 32, "~" }), "% %!%\"%#%$%%%&%'%(%)%*%+%,%-%.%/%0%1%2%3%4%5%6%7%8%9%:%;%<%=%>%?%@%A" .. "%B%C%D%E%F%G%H%I%J%K%L%M%N%O%P%Q%R%S%T%U%V%W%X%Y%Z%[%\\%]%^%_%`%a%b%c" .. "%d%e%f%g%h%i%j%k%l%m%n%o%p%q%r%s%t%u%v%w%x%y%z%{%|%}%~" ) ensure_strequals( "from space to ch(126)", get_escaped_chars_in_ranges({ " ", 126 }), "% %!%\"%#%$%%%&%'%(%)%*%+%,%-%.%/%0%1%2%3%4%5%6%7%8%9%:%;%<%=%>%?%@%A" .. "%B%C%D%E%F%G%H%I%J%K%L%M%N%O%P%Q%R%S%T%U%V%W%X%Y%Z%[%\\%]%^%_%`%a%b%c" .. "%d%e%f%g%h%i%j%k%l%m%n%o%p%q%r%s%t%u%v%w%x%y%z%{%|%}%~" ) ensure_strequals( "integer range and letters", get_escaped_chars_in_ranges({ 32, 58, "a", "h" }), "% %!%\"%#%$%%%&%'%(%)%*%+%,%-%.%/%0%1%2%3%4%5%6%7%8%9%:%a%b%c%d%e%f%g%h" ) ensure_strequals( "all mixed up", get_escaped_chars_in_ranges({ 32, 58, "a", "h", 34, 38, "0", 50 }), "% %!%\"%#%$%%%&%'%(%)%*%+%,%-%.%/%0%1%2%3%4%5%6%7%8%9%:%a%b%c%d%e%f%g" .. "%h%\"%#%$%%%&%0%1%2" ) end) -------------------------------------------------------------------------------- test:test_for "tjson_simple" (function() -- Helpers local coroutine_create = coroutine.create local ensure_tjson_fails = function(msg, data, error_msg) ensure_fails_with_substring( msg, function() tjson_simple(data) end, error_msg ) end local ensure_tjson_unsupported_type = function(data) ensure_tjson_fails( "unsupported type check", data, "tjson_simple: value type `" .. type(data) .. "' not supported" ) end -- Single values: number, string, boolean ensure_strequals('single integer (positive)', tjson_simple(123), '123') ensure_strequals('single integer (negative)', tjson_simple(-123), '-123') ensure_strequals('single float', tjson_simple(123.123), '123.123') ensure_strequals('single string', tjson_simple('Just text'), '"Just text"') ensure_strequals('single boolean (true)', tjson_simple(true), 'true') ensure_strequals('single boolean (false)', tjson_simple(false), 'false') -- Unsupported types: nil, function, thread, userdata ensure_tjson_unsupported_type(nil) ensure_tjson_unsupported_type(function() end) ensure_tjson_unsupported_type(coroutine_create(function() end)) ensure_tjson_unsupported_type(newproxy()) -- Unsupported values: NaN, +Inf, -Inf ensure_tjson_fails('unsupported value', 1/0, "tjson_simple: `Inf' value not supported") ensure_tjson_fails('unsupported value', -1/0, "tjson_simple: `Inf' value not supported") ensure_tjson_fails('unsupported value', 0/0, "tjson_simple: `NaN' value not supported") -- Tables ensure_strequals( 'table to array', tjson_simple({1, -1, 123.123, 'abc', true, false, { }}), '[1,-1,123.123,"abc",true,false,[]]' ) ensure_strequals( 'table to object', tjson_simple( {a = 1, b = -1, c = 123.123, d = 'abc', e = true, f = false, j = {1}} ), '{"a":1,"c":123.123,"b":-1,"e":true,"d":"abc","j":[1],"f":false}' ) ensure_strequals('empty table', tjson_simple({ }), '[]') ensure_strequals('empty tables', tjson_simple({ { }, { } }), '[[],[]]') -- Exceptions local self_reference_tbl = { } self_reference_tbl[1] = self_reference_tbl ensure_tjson_fails( 'self reference', self_reference_tbl, "tjson_simple: can't handle self-references" ) local mixed_keys_tbl = { "a", "b" } mixed_keys_tbl["c"] = "d" ensure_tjson_fails( 'mixed keys', mixed_keys_tbl, "tjson_simple: non-string keys are not supported" ) local non_string_key_tbl = { } non_string_key_tbl[1.23] = 1 ensure_tjson_fails( 'non string keys', non_string_key_tbl, "tjson_simple: non-string keys are not supported" ) end) --------------------------------------------------------------------------------
local root = (...) .. "." local modules = { "Children", "Compose" } local Rukt = {} for _, moduleName in ipairs(modules) do Rukt[moduleName] = require(root .. moduleName) end return Rukt
local cqueues = require 'cqueues' local tcheck = require 'tcheck' local xerror = require 'tulip.xerror' local function register_packages(app, cfg) local pkgs = {} -- First, require the top-level keys that represent packages. for k, v in pairs(cfg) do local full_name -- if there is no '.' in the key, try first as 'tulip.pkg.<key>' local ok, pkg = false, nil if not string.find(k, '.', 1, true) then full_name = 'tulip.pkg.'..k ok, pkg = pcall(require, full_name) end if not ok then full_name = k ok, pkg = pcall(require, k) end if not ok then xerror.throw('package not found: %s: %s', k, pkg) end if pkgs[full_name] then xerror.throw('package already required: %s', full_name) end pkgs[full_name] = { package = pkg, defined_name = k, config = v, } if pkg.replaces then if pkgs[pkg.replaces] then xerror.throw('package %s replaces %s, which is already required', full_name, pkg.replaces) end pkgs[pkg.replaces] = true end if pkg.app then for appk, appv in pairs(pkg.app) do app[appk] = appv end end end app.packages = pkgs for _, v in pairs(pkgs) do if v ~= true then local pkg = v.package -- check fulfilled dependencies if pkg.requires then for _, dep in ipairs(pkg.requires) do if not pkgs[dep] then xerror.throw('package %s requires package %s', v.defined_name, dep) end end end -- register the package pkg.register(v.config, app) end end end -- Returns the __name of the metatable of o, or nil if none. local function metatable_name(o) if type(o) == 'table' then local mt = getmetatable(o) return mt and mt.__name end end local LOGLEVELS = { d = 1, debug = 1, e = 1000, error = 1000, i = 10, info = 10, w = 100, warning = 100, -- support reverse-lookup too [1] = 'd', [10] = 'i', [100] = 'w', [1000] = 'e', } local App = {__name = 'tulip.App'} App.__index = App -- Registers a name with a value in the collection identified by field. -- If append is true and a value already exists for that name, then each -- value in the array part of v is appended to the existing value. -- Otherwise if append is false and a value already exists, an error -- is thrown. -- Internal method for extenders of App instance. function App:_register(field, name, v, append) local coll = self[field] or {} if coll[name] then if append then local ar = coll[name] for _, vv in ipairs(v) do table.insert(ar, vv) end else if string.match(field, '^_') then field = string.sub(field, 2) end xerror.throw('%s: %q is already registered', field, name) end end coll[name] = v self[field] = coll end -- Lookup a name and return its registered value in the collection -- identified by field. Internal method for extenders of App instance. function App:_lookup(field, name) local coll = self[field] if not coll then return end if not string.find(name, '.', 1, true) then local v = coll['tulip.pkg.' .. name] if v then return v end end return coll[name] end -- Resolve the names registered in the coll array by replacing the names -- with the values registered in the collection identified by field. -- Internal method for extenders of App instance. function App:_resolve(field, coll) for i, v in ipairs(coll) do local typ = type(v) if typ == 'string' then local vi = self:_lookup(field, v) if not vi then if string.match(field, '^_') then field = string.sub(field, 2) end xerror.throw('no %s registered for %q', field, v) end coll[i] = vi elseif metatable_name(v) == 'tulip.App' then v:activate() end end end -- Returns true if name is a registered package for this App instance. -- If exact is true, this exact package must be registered (i.e. it must -- not be a drop-in replacement for it). -- Returns true if the package is registered, or nil and an error message -- indicating that the package is not registered, so it can also be -- called inside an xerror.must call. function App:has_package(name, exact) local pkg = self.packages and self.packages[name] if pkg and (pkg ~= true or not exact) then return true end return nil, string.format('package %s is not registered', name) end -- Encodes the table t to the specified mime type, using the -- registered encoders. It panics if no encoder supports this mime type, -- otherwise returns the encoded string or nil and an error. function App:encode(t, mime) if self.encoders then for _, enc in pairs(self.encoders) do local s, err = enc(t, mime) if s or err then return s, err end end end xerror.throw('no encoder registered for MIME type %q', mime) end -- Decodes the string s encoded as the specified mime type, using -- the registered decoders. It panics if no decoder supports this mime type, -- otherwise returns the decoded value or nil and an error. function App:decode(s, mime) if self.decoders then for _, dec in pairs(self.decoders) do local t, err = dec(s, mime) if t ~= nil or err then return t, err end end end xerror.throw('no decoder registered for MIME type %q', mime) end -- Logs the t table at level lvl to all registered loggers. function App:log(lvl, t) local types = tcheck({'string|number', 'table'}, lvl, t) if types[1] == 'string' then lvl = LOGLEVELS[lvl] or 0 end -- ignore if requested log level is higher if not self.log_level or lvl < self.log_level then return end -- log to all registered backends if self.loggers then -- if it maps to a well-known level char, use it, otherwise keep the -- numeric level. t.level = LOGLEVELS[lvl] or lvl for _, l in pairs(self.loggers) do l(t) end end end -- Register an encoder in the list of encoders. It panics if an encoder -- is already registered for that name. function App:register_encoder(name, enc) tcheck({'*', 'string', 'table|function'}, self, name, enc) self:_register('encoders', name, enc) end -- Get the registered encoder instance for that name, or nil if none. function App:lookup_encoder(name) tcheck({'*', 'string'}, self, name) return self:_lookup('encoders', name) end -- Register a decoder in the list of decoders. It panics if a decoder is -- already registered for that name. function App:register_decoder(name, dec) tcheck({'*', 'string', 'table|function'}, self, name, dec) self:_register('decoders', name, dec) end -- Get the registered decoder instance for that name, or nil if none. function App:lookup_decoder(name) tcheck({'*', 'string'}, self, name) return self:_lookup('decoders', name) end -- Register a finalizer in the list of finalizers. It panics if a finalizer -- is already registered for that name. function App:register_finalizer(name, fz) tcheck({'*', 'string', 'table|function'}, self, name, fz) self:_register('finalizers', name, fz) end -- Get the registered finalizer instance for that name, or nil if none. function App:lookup_finalizer(name) tcheck({'*', 'string'}, self, name) return self:_lookup('finalizers', name) end -- Register a logger in the list of loggers. It panics if a logger is -- already registered for that name. function App:register_logger(name, lg) tcheck({'*', 'string', 'table|function'}, self, name, lg) self:_register('loggers', name, lg) end -- Get the registered logger instance for that name, or nil if none. function App:lookup_logger(name) tcheck({'*', 'string'}, self, name) return self:_lookup('loggers', name) end -- Activates all packages registered by the app. Panics if activation -- fails (that is, the activate function of packages should throw on -- error). Receives the cqueue instance that will be used by the application. function App:activate(cq) tcheck({'tulip.App', 'userdata|nil'}, self, cq) if type(self.log_level) == 'string' then self.log_level = LOGLEVELS[self.log_level] end for _, pkg in pairs(self.packages) do if pkg ~= true then local cfg = pkg.config pkg = pkg.package if pkg.activate then pkg.activate(cfg, self, cq) end end end return true end -- Runs the application, activating any registered package and -- calling App:main. It returns the value(s) returned by App:main -- and calls any registered finalizer before returning. -- It panics if activation fails (that is, the activate method -- of packages should throw an error if they fail to activate). function App:run() local cq = cqueues.new() self:activate(cq) if not self.main then xerror.throw('no main field registered by app') end local res = table.pack(self:main(cq)) if self.finalizers then for _, f in pairs(self.finalizers) do f(self) end end return table.unpack(res, 1, res.n) end -- Returns a function that creates an App instance for the -- provided configuration. return function (cfg) tcheck('table', cfg) local o = {config = cfg} setmetatable(o, App) -- require and register all config packages register_packages(o, cfg) return o end
local function defaults() LobbyTimer = 30 RoundDuration = 300 RoundEndTime = 5 RoundCount = 0 RoundLimit = 5 RoundScore = {red = 0, blue = 0} end defaults() function RoundMsg(asd) net.Start("Cheats:RoundMsg") net.WriteString(asd) net.Broadcast() end function GameStop() RoundMsg("Stopping game..") hook.Remove("Think","CHRoundThink") SetGlobalBool("Lobby",false) SetGlobalBool("Deathmatch",true) timer.Remove("LOBBYTIMER") timer.Remove("ROUNDTIMER") timer.Remove("ROUNDENDTIMER") defaults() for k,v in pairs(player.GetAll())do if(v:Team() != 0)then net.Start("Cheats:GameStop") net.Send(v) end end end --GameStop() function RoundStart() teamf.ScrambleDM() SetGlobalBool("Lobby",false) for k,v in pairs(player.GetAll())do if(v:Team() == 1 or v:Team() == 2)then v:UnSpectate() v:Spawn() hook.Call("PlayerLoadout", GAMEMODE, v) net.Start("Cheats:RoundStart") net.WriteInt(RoundScore.red, 8) net.WriteInt(RoundScore.blue, 8) net.Send(v) end end hook.Add("Think","CHRoundThink",function() local red = team.GetPlayers(1) local blue = team.GetPlayers(2) local both = table.Add(red,blue) local ra = false local ba = false for k,v in pairs(both)do if(v:Team() == 1 and v:Alive())then ra = true end if(v:Team() == 2 and v:Alive())then ba = true end end if(!ba)then timer.Remove("ROUNDTIMER") RoundScore.red = RoundScore.red+1 RoundEnd(1) elseif(!ra)then timer.Remove("ROUNDTIMER") RoundScore.blue = RoundScore.blue+1 RoundEnd(2) end end) timer.Create("ROUNDTIMER",RoundDuration,1,function() RoundEnd(0) end) end function GameLobby() SetGlobalBool("Lobby",true) SetGlobalBool("Deathmatch",false) timer.Create("LOBBYTIMER",LobbyTimer,1,RoundStart) for k,v in pairs(player.GetAll())do if(v:Team() != 0)then net.Start("Cheats:GameLobby") net.WriteInt(LobbyTimer, 8) net.Send(v) end end end function RoundEnd(winner) local loser if(winner == 1)then loser = 2 elseif(winner == 2)then loser = 1 end if(winner != 0)then for k,v in pairs(team.GetPlayers(winner))do net.Start("Cheats:RoundWin") net.Send(v) end for k,v in pairs(team.GetPlayers(loser))do net.Start("Cheats:RoundLoss") net.Send(v) end else for k,v in pairs(player.GetAll())do net.Start("Cheats:RoundTie") net.Send(v) end end hook.Remove("Think","CHRoundThink") RoundCount = RoundCount+1 if(RoundCount >= RoundLimit and (RoundScore.red != RoundScore.blue))then GameWin() else timer.Create("ROUNDENDTIMER",RoundEndTime,1,RoundStart) for k,v in pairs(player.GetAll())do if(v:Team() != 0)then net.Start("Cheats:RoundEnd") net.Send(v) end end end end function GameWin() hook.Remove("Think","CHRoundThink") defaults() SetGlobalBool("Deathmatch",true) timer.Create("ROUNDENDTIMER",RoundEndTime,1,function() for k,v in pairs(player.GetAll())do if(v:Team() != 0)then v:UnSpectate() v:SetTeam(3) v:Spawn() end end end) for k,v in pairs(player.GetAll())do if(v:Team() != 0)then net.Start("Cheats:GameWin") net.Send(v) end end end
require('settings/telescope') require('settings/autosave') require('settings/neogit') require('settings/treesitter') require('settings/neorg') require('settings/lualine') require('settings/cmp') require('settings/substitute') require('settings/dial') require('settings/comment') require('settings/yabs') require('settings/camelcase') require('settings/bqf')
AddRemoteEvent("ATMDeposit", function(player, amount) if player_data[player] == nil then return end if player_data[player].cash >= amount then player_data[player].cash = player_data[player].cash - amount player_data[player].balance = player_data[player].balance + amount AddPlayerChat(player, _("deposit_successful")) SetPlayerPropertyValue(player, "cash", player_data[player].cash, true) SetPlayerPropertyValue(player, "balance", player_data[player].balance, true) else AddPlayerChat(player, _("not_enough_cash")) end end) AddRemoteEvent("ATMWithdraw", function(player, amount) if player_data[player] == nil then return end if player_data[player].balance >= amount then player_data[player].balance = player_data[player].balance - amount player_data[player].cash = player_data[player].cash + amount AddPlayerChat(player, _("withdraw_successful")) SetPlayerPropertyValue(player, "cash", player_data[player].cash, true) SetPlayerPropertyValue(player, "balance", player_data[player].balance, true) else AddPlayerChat(player, _("not_enough_balance")) end end)
local fn = vim.fn local fmt = string.format -- Global namespace -----------------------------------------------------------------------------// --- Inspired by @tjdevries' astraunauta.nvim/ @TimUntersberger's config --- store all callbacks in one global table so they are able to survive re-requiring this file _G.__as_global_callbacks = __as_global_callbacks or {} _G.as = { _store = __as_global_callbacks, --- work around to place functions in the global scope but namespaced within a table. --- TODO: refactor this once nvim allows passing lua functions to mappings mappings = {}, } -- inject mapping helpers into the global namespace -- R "as.utils.mappings" local installed function as._create(f) table.insert(as._store, f) return #as._store end function as._execute(id) return as._store[id]() end function as._expr(id) return vim.api.nvim_replace_termcodes(as._store[id](), true, true, true) end -- check item in array local function has_value(tab, val) for _, value in ipairs(tab) do if value == val then return true end end return false end function as.plugin_installed(plugin_name) if not installed then local dirs = fn.expand( fn.stdpath "data" .. "/site/pack/deps/opt/*", true, true ) local opt = fn.expand( fn.stdpath "data" .. "/site/pack/packer/opt/*", true, true ) vim.list_extend(dirs, opt) installed = vim.tbl_map(function(path) return fn.fnamemodify(path, ":t") end, dirs) end return vim.tbl_contains(installed, plugin_name) end function as.nvim_create_augroups(definitions) for group_name, definition in pairs(definitions) do vim.cmd("augroup " .. group_name) vim.cmd "autocmd!" for _, def in ipairs(definition) do local command = table.concat( vim.tbl_flatten { "autocmd", def }, " " ) vim.cmd(command) end vim.cmd "augroup END" end end --- Find the first entry for which the predicate returns true. -- @param t The table -- @param predicate The function called for each entry of t -- @return The entry for which the predicate returned True or nil function as.find_first(t, predicate) for _, entry in pairs(t) do if predicate(entry) then return entry end end return nil end --- Check if the predicate returns True for at least one entry of the table. -- @param t The table -- @param predicate The function called for each entry of t -- @return True if predicate returned True at least once, false otherwise function as.contains(t, predicate) return as.find_first(t, predicate) ~= nil end function as.executable(e) return fn.executable(e) > 0 end function as.rm_duplicates_tbl(arr) local newArray = {} local checkerTbl = {} for _, element in ipairs(arr) do -- [[if there is not yet a value at the index of element, then it will -- be nil, which will operate like false in an if statement -- ]] if not checkerTbl[element] then checkerTbl[element] = true table.insert(newArray, element) end end return newArray end local L = vim.log.levels function as.safe_require(module, opts) opts = opts or { silent = false } local ok, result = pcall(require, module) if not ok and not opts.silent then vim.notify( result, L.ERROR, { title = fmt("Error requiring: %s", module) } ) end return ok, result end function _G.open_lsp_log() local path = vim.lsp.get_log_path() vim.cmd("edit " .. path) end function _G.open_lvim_log() vim.cmd("edit " .. O.plugin.lsp.debug.logfile) end function _G.stop_lsp_allclient() vim.cmd [[lsp.stop_client(lsp.get_active_clients())]] end vim.cmd "command! -nargs=0 LspLog call v:lua.open_lsp_log()" vim.cmd "command! -nargs=0 LspLogLvim call v:lua.open_lvim_log()" vim.cmd "command! -nargs=0 LspRestart call v:lua.reload_lsp()" vim.cmd "command! -nargs=0 LspAllStop call v:lua.stop_lsp_allclient()"
AccountHeadCcsItem = class("AccountHeadCcsItem") AccountHeadCcsItem.onCreationComplete = function (slot0) ClassUtil.extends(slot0, CcsListViewItem) slot0._items = {} slot1 = 1 while true do if not slot0["iconNode" .. slot1] then break else table.insert(slot0._items, slot2) end slot1 = slot1 + 1 end end AccountHeadCcsItem.updateView = function (slot0) if slot0._data then for slot4, slot5 in ipairs(slot0._items) do slot5.root:setData(slot0._data[slot4]) end end end AccountHeadCcsItem.onClick = function (slot0, slot1) for slot5, slot6 in pairs(slot0._items) do if DisplayUtil.hitTestNode(slot6, slot1) and slot0._data[slot5] then slot0.model:setHeadSelectedGender(slot0._data[slot5].gender) slot0.model:setHeadSelectedId(slot0._data[slot5].faceId, slot0._data[slot5].gender ~= slot0.model:getHeadSelectedGender()) break end end end AccountHeadCcsItem.onPushDownChanged = function (slot0, slot1, slot2, slot3) for slot7, slot8 in pairs(slot0._items) do if slot2 and DisplayUtil.hitTestNode(slot8, slot3) then TweenLite.to(slot8.root, 0.2, { scale = 1.1 }) else TweenLite.to(slot8.root, 0.2, { scale = 1 }) end end end AccountHeadCcsItem.getPushZoomView = function (slot0) return nil end AccountHeadCcsItem.destroy = function (slot0) for slot4, slot5 in pairs(slot0._items) do slot5.root:destroy() end CcsListViewItem.destroy(slot0) end return
local LinkedList = {} LinkedList.__index = LinkedList function LinkedList:push(v) local old_head = self._head self._head = { v = v, next = old_head } if old_head then old_head.prev = self._head end if not self._tail then self._tail = self._head end end function LinkedList:pop() local v = self._head.v self._head = self._head.next if not self._head then self._tail = nil end return v end function LinkedList:unshift(v) local old_tail = self._tail self._tail = { v = v, prev = old_tail } if old_tail then old_tail.next = self._tail end if not self._head then self._head = self._tail end end function LinkedList:shift() local v = self._tail.v self._tail = self._tail.prev if self._tail then self._tail.next = nil end return v end function LinkedList:count() local count = 0 local current = self._head while current do count = count + 1 current = current.next end return count end function LinkedList:delete(v) local current = self._head while current do if current.v == v then if self._head == current then self._head = current.next end if self._tail == current then self._tail = current.prev end if current.prev then current.prev.next = current.next end if current.next then current.next.prev = current.prev end end current = current.next end end return function() return setmetatable({}, LinkedList) end
local gunSettings = { fireMode = "SEMI"; damage = 25; headshotMultiplier = 1.5; rateOfFire = 300; --Rounds per minute range = 500; rayColor = Color3.fromRGB(255, 160, 75); raySize = Vector2.new(0.25, 0.25); --Width and height debrisTime = 0.075; } return gunSettings
//Marine Stuctures kPowerNodeCost = 0 kExtractorCost = 10 kExtractorBuildTime = 10 kInfantryPortalCost = 15 kInfantryPortalBuildTime = 7 kCommandStationCost = 15 kCommandStationBuildTime = 15 kNanoShieldResearchCost = 20 kNanoSnieldResearchTime = 60 kCatPackTechResearchCost = 20 kCatPackTechResearchTime = 60 kMACCost = 3 kMACBuildTime = 5 kARCCost = 10 kARCBuildTime = 7 kRoboticsFactoryCost = 10 kUpgradeRoboticsFactoryCost = 5 kRoboticsFactoryBuildTime = 8 kUpgradeRoboticsFactoryTime = 20 kSentryCost = 5 kSentryBuildTime = 3 kSentryBatteryCost = 5 kSentryBatteryBuildTime = 5 kSentryBatteryRange = 8.0 kObservatoryCost = 10 kObservatoryBuildTime = 15 kObservatoryScanCost = 3 kObservatoryDistressBeaconCost = 10 kPhaseGateCost = 15 kPhaseTechResearchCost = 10 kPhaseTechResearchTime = 45 kPhaseGateBuildTime = 12 kArmsLabCost = 20 kArmsLabBuildTime = 17 kWeapons1ResearchCost = 20 kWeapons2ResearchCost = 30 kWeapons3ResearchCost = 40 kArmor1ResearchCost = 20 kArmor2ResearchCost = 30 kArmor3ResearchCost = 40 kWeapons1ResearchTime = 60 kWeapons2ResearchTime = 90 kWeapons3ResearchTime = 120 kArmor1ResearchTime = 60 kArmor2ResearchTime = 90 kArmor3ResearchTime = 120 kArmoryCost = 10 kArmoryBuildTime = 12 kShotgunTechResearchTime = 30 kMineResearchTime = 30 kAdvancedArmoryUpgradeCost = 30 kAdvancedArmoryResearchTime = 90 kWelderCost = 1 kWelderDropCost = 1 kNumMines = 3 kMineCost = 10 kDropMineCost = 10 kMineResearchCost = 10 kGrenadeLauncherCost = 15 kGrenadeLauncherDropCost = 15 kGrenadeLauncherTechResearchCost = 15 kShotgunCost = 20 kShotgunDropCost = 20 kShotgunTechResearchCost = 20 kFlamethrowerCost = 20 kFlamethrowerDropCost = 20 kFlamethrowerTechResearchCost = 20 kGrenadeTechResearchCost = 10 kGrenadeTechResearchTime = 45 kClusterGrenadeCost = 2 kGasGrenadeCost = 2 kPulseGrenadeCost = 2 kPrototypeLabCost = 40 kPrototypeLabBuildTime = 20 kJetpackCost = 15 kJetpackDropCost = 15 kJetpackTechResearchCost = 25 kJetpackTechResearchTime = 90 kExosuitCost = 30 kExosuitTechResearchCost = 20 kExosuitTechResearchTime = 90 kExosuitUpgradeTechResearchTime = 60 //Aliens // Each upgrade costs this much extra evolution time kUpgradeGestationTime = 2 kEvolutionGestateTime = 3 kEggGestateTime = 45 kDrifterBuildTime = 4 kSkulkUpgradeCost = 0 kSkulkGestateTime = 3 kGorgeCost = 10 kGorgeEggCost = 10 kGorgeUpgradeCost = 1 kGorgeGestateTime = 7 kLerkCost = 30 kLerkEggCost = 30 kLerkUpgradeCost = 3 kLerkGestateTime = 15 kFadeCost = 40 kFadeEggCost = 40 kFadeUpgradeCost = 4 kFadeGestateTime = 25 kOnosCost = 60 kOnosEggCost = 60 kOnosUpgradeCost = 6 kOnosGestateTime = 30 //structures // entrance and exit kNumGorgeTunnels = 2 kGorgeTunnelCost = 5 kGorgeTunnelBuildTime = 10 kClogCost = 0 kClogsPerHive = 20 kHydrasPerHive = 5 kHydraCost = 3 kHydraBuildTime = 13 kNumWebsPerGorge = 10 kCystBuildTime = 5 kHarvesterCost = 8 kHarvesterBuildTime = 38 kWhipCost = 10 kWhipBuildTime = 20 kHiveCost = 40 kHiveBuildTime = 180 // This is for CragHive, ShadeHive and ShiftHive kUpgradeHiveCost = 10 kUpgradeHiveResearchTime = 20 kResearchBioMassOneCost = 20 kBioMassOneTime = 30 kResearchBioMassTwoCost = 30 kBioMassTwoTime = 40 kResearchBioMassThreeCost = 40 kBioMassThreeTime = 50 kResearchBioMassFourCost = 50 kBioMassFourTime = 60 kShellCost = 10 kShellBuildTime = 18 kCragCost = 10 kCragBuildTime = 25 kSpurCost = 10 kSpurBuildTime = 16 kShiftCost = 10 kShiftBuildTime = 18 kVeilCost = 10 kVeilBuildTime = 14 kShadeCost = 10 kShadeBuildTime = 18
----------------------------------- -- Area: Mount_Kamihr ----------------------------------- require("scripts/globals/zone") ----------------------------------- zones = zones or {} zones[tpz.zone.MOUNT_KAMIHR] = { text = { }, mob = { }, npc = { }, } return zones[tpz.zone.MOUNT_KAMIHR]
dofile('/home/raj/workspace/p4-traffictool/samples/mri/output/wireshark/mri_1_ipv4.lua') dofile('/home/raj/workspace/p4-traffictool/samples/mri/output/wireshark/mri_2_ipv4_option.lua') dofile('/home/raj/workspace/p4-traffictool/samples/mri/output/wireshark/mri_3_mri.lua') dofile('/home/raj/workspace/p4-traffictool/samples/mri/output/wireshark/mri_4_swids.lua')
-- God local function PlayerHasGod() return Script().StateWatcher:GetState("god") == true end local function PlayerSetGod(on) local playerid = GetLocalPlayerEntityId() Script().StateWatcher:SetState("god", on) if on then ActivateInvincibility(playerid) SetPawnImmuneToDeath(playerid, 1) ScriptHook.ShowNotification(1, "Player God Mode", "ON") else RemoveInvincibility(playerid) SetPawnImmuneToDeath(playerid, 0) ScriptHook.ShowNotification(1, "Player God Mode", "OFF") end end -- Unlimited Ammo local function PlayerHasUnlimitedAmmo() return Script().StateWatcher:GetState("unlimitedAmmo") == true end local function PlayerSetUnlimitedAmmo(on) Script().StateWatcher:SetState("unlimitedAmmo", on) Script().StateWatcher:UnlimitedAmmo() end -- Noclip local function ToggleNoclip() ScriptHook.SetLocalPlayerNoclip(not ScriptHook.HasLocalPlayerNoclip()) end -- Invisible local function PlayerIsInvisible() return Script().StateWatcher:GetState("invisible") == true end -- Player Info local function PlayerInfoMenu() local menu = UI.SimpleMenu() menu:SetTitle("Player Info") local playerid = GetLocalPlayerEntityId() -- Items local godIdx = menu:AddCheckbox("God Mode") local invisibleIdx = menu:AddCheckbox("Invisible Mode") local unlAmmoIdx = menu:AddCheckbox("Unlimited Ammo") local noclipIdx = menu:AddCheckbox("Noclip") local idButton = menu:AddButton("ID: " .. tostring(playerid), function() print(playerid) end) local nameButton = menu:AddButton("Name: " .. tostring(GetEntityName(playerid)), function() print(GetEntityName(playerid)) end) local healthButton = menu:AddButton("Health: " .. tostring(GetCurrentHealth(playerid)), function() print(GetCurrentHealth(playerid)) end) local xPosButton = menu:AddButton("Position X: " .. tostring(GetEntityPosition(playerid, 0)), function() print("Position X: " .. tostring(GetEntityPosition(playerid, 0)) .. " Y: " .. tostring(GetEntityPosition(playerid, 1)) .. " Z: " .. tostring(GetEntityPosition(playerid, 2))) end) local yPosButton = menu:AddButton("Position Y: " .. tostring(GetEntityPosition(playerid, 1)), function() print("Position X: " .. tostring(GetEntityPosition(playerid, 0)) .. " Y: " .. tostring(GetEntityPosition(playerid, 1)) .. " Z: " .. tostring(GetEntityPosition(playerid, 2))) end) local zPosButton = menu:AddButton("Position Z: " .. tostring(GetEntityPosition(playerid, 2)), function() print("Position X: " .. tostring(GetEntityPosition(playerid, 0)) .. " Y: " .. tostring(GetEntityPosition(playerid, 1)) .. " Z: " .. tostring(GetEntityPosition(playerid, 2))) end) local xRotButton = menu:AddButton("Rotation X: " .. tostring(GetEntityAngle(playerid, 0)), function() print("Rotation X: " .. tostring(GetEntityAngle(playerid, 0)) .. " Y: " .. tostring(GetEntityAngle(playerid, 1)) .. " Z: " .. tostring(GetEntityAngle(playerid, 2))) end) local yRotButton = menu:AddButton("Rotation Y: " .. tostring(GetEntityAngle(playerid, 1)), function() print("Rotation X: " .. tostring(GetEntityAngle(playerid, 0)) .. " Y: " .. tostring(GetEntityAngle(playerid, 1)) .. " Z: " .. tostring(GetEntityAngle(playerid, 2))) end) local zRotButton = menu:AddButton("Rotation Z: " .. tostring(GetEntityAngle(playerid, 2)), function() print("Rotation X: " .. tostring(GetEntityAngle(playerid, 0)) .. " Y: " .. tostring(GetEntityAngle(playerid, 1)) .. " Z: " .. tostring(GetEntityAngle(playerid, 2))) end) -- Update menu:OnUpdate(function() menu:SetChecked(godIdx, PlayerHasGod()) menu:SetChecked(invisibleIdx, PlayerIsInvisible()) menu:SetChecked(unlAmmoIdx, PlayerHasUnlimitedAmmo()) menu:SetChecked(noclipIdx, ScriptHook.HasLocalPlayerNoclip()) menu:SetEntryText(healthButton, "Health: " .. tostring(GetCurrentHealth(playerid))) menu:SetEntryText(xPosButton, "Position X: " .. tostring(GetEntityPosition(playerid, 0))) menu:SetEntryText(yPosButton, "Position Y: " .. tostring(GetEntityPosition(playerid, 1))) menu:SetEntryText(zPosButton, "Position Z: " .. tostring(GetEntityPosition(playerid, 2))) menu:SetEntryText(xRotButton, "Rotatin X: " .. tostring(GetEntityAngle(playerid, 0))) menu:SetEntryText(yRotButton, "Rotatin Y: " .. tostring(GetEntityAngle(playerid, 1))) menu:SetEntryText(zRotButton, "Rotatin Z: " .. tostring(GetEntityAngle(playerid, 2))) end) return menu end -- Player local function PlayerMenu() local menu = UI.SimpleMenu() menu:SetTitle("Player") -- Items local godIdx = menu:AddCheckbox("God Mode", "Toggle invincibility", function() PlayerSetGod(not PlayerHasGod()) end) local invisibleIdx = menu:AddCheckbox("Invisible Mode", "Toggle visibility", function() Script().StateWatcher:SetState("invisible", not PlayerIsInvisible()) ScriptHook.SetEntityIsVisible(GetLocalPlayerEntityId(), not PlayerIsInvisible(), 0) end) local unlAmmoIdx = menu:AddCheckbox("Unlimited Ammo", "No reload, always full clips", function() PlayerSetUnlimitedAmmo(not PlayerHasUnlimitedAmmo()) end) -- Noclip local noclipIdx = menu:AddCheckbox("Noclip / Fly", "Enable/Disable flying", ToggleNoclip) -- Noclip Speed local speedIdx = menu:AddList("Noclip Speed", function(_,_,_,_, idx, speed) Script():ApplyCameraSpeed("noclip", "normal", speed) end) for _,v in pairs({ 0.5, 1, 2, 3, 5, 10, 15, 20, 25, 50, 75, 100 }) do menu:AddListEntry(speedIdx, tostring(v)) end -- Noclip Shift Speed local shiftSpeedIdx = menu:AddList("Noclip Shift Speed", function(_,_,_,_, idx, speed) Script():ApplyCameraSpeed("noclip", "shift", speed) end) for _,v in pairs({ 5, 10, 25, 50, 75, 100, 150, 200, 250, 350, 450 }) do menu:AddListEntry(shiftSpeedIdx, tostring(v)) end -- Persistent local speedData = Script():ReadCameraSpeeds("noclip") menu:SelectListEntryByValue(speedIdx, tostring(speedData.normal)) menu:SelectListEntryByValue(shiftSpeedIdx, tostring(speedData.shift)) speedData.ready = true -- Info -- TODO: Currently experiencing a crash --menu:AddButton("Player Info", "Shows all player information", PlayerInfoMenu) -- Update menu:OnUpdate(function() menu:SetChecked(godIdx, PlayerHasGod()) menu:SetChecked(invisibleIdx, PlayerIsInvisible()) menu:SetChecked(unlAmmoIdx, PlayerHasUnlimitedAmmo()) menu:SetChecked(noclipIdx, ScriptHook.HasLocalPlayerNoclip()) menu:SetEntryEnabled(noclipIdx, not ScriptHook.HasLocalPlayerFreeCamera()) end) return menu end table.insert(SimpleTrainerMenuItems, { "Player", "Godmode, noclip, unlimited ammo", Script():CacheMenu(PlayerMenu) })
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- file: config.lua -- brief: configfile for handler.lua -- author: jK -- -- Copyright (C) 2011-2013. -- Licensed under the terms of the GNU GPL, v2 or later. -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --// randomize each run math.randomseed(os.time()) --// 0: disabled --// 1: enabled, but can be overriden by widget.GetInfo().unsafe --// 2: always enabled SAFEWRAP = 1 SAFEDRAW = false --// requires SAFEWRAP to work --// VFSMODE = VFS.RAW_FIRST --// when false, the handler will `compress` some output (e.g. list of started widgets) handler.verbose = false or true -- FIXME: Not used local function LoadLibraries() for _, lib in pairs(VFS.SubDirs("libs_sb/")) do local addonDir = lib .. LUA_NAME .. "/widgets" if #VFS.DirList(addonDir) > 0 then table.insert(ADDON_DIRS, addonDir) end end end if LUA_NAME == "LuaUI" then --// Config & Widget Locations ORDER_FILENAME = LUAUI_DIRNAME .. 'Config/' .. Game.modShortName .. '_order.lua' CONFIG_FILENAME = LUAUI_DIRNAME .. 'Config/' .. Game.modShortName .. '_data.lua' KNOWN_FILENAME = LUAUI_DIRNAME .. 'Config/' .. Game.modShortName .. '_known.lua' ADDON_DIRS = { LUA_DIRNAME .. 'Addons/'; LUA_DIRNAME .. 'Widgets/'; LUA_DIRNAME .. 'SystemAddons/'; LUA_DIRNAME .. 'SystemWidgets/'; } --// Create the "LuaUI/Config" directory Spring.CreateDir(LUAUI_DIRNAME .. 'Config') handler:Load(LUAUI_DIRNAME .. "SystemWidgets/BlockUserWidgets.lua" --[[, VFS.ZIP]]) else AddonNames = handler.AddonName .. "s/" ADDON_DIRS = { LUA_DIRNAME .. 'Addons/'; LUA_DIRNAME .. AddonNames; LUA_DIRNAME .. 'SystemAddons/'; LUA_DIRNAME .. 'System' .. AddonNames; } end -- LoadLibraries()
----------------------------------- -- Area: Cloister of Tremors -- Mob: Galgalim -- Involved in Quest: The Puppet Master ----------------------------------- require("scripts/globals/settings") ----------------------------------- function onMobDeath(mob, player, isKiller) player:setCharVar("BCNM_Killed", 1) record = 300 partyMembers = 6 pZone = player:getZoneID() player:startEvent(32001, 0, record, 0, (os.time() - player:getCharVar("BCNM_Timer")), partyMembers, 0, 0) end function onEventUpdate(player, csid, option) -- printf("onUpdate CSID: %u", csid) -- printf("onUpdate RESULT: %u", option) end function onEventFinish(player, csid, option) -- printf("onFinish CSID: %u", csid) -- printf("onFinish RESULT: %u", option) end
AllMapsRatings = {} local mapRatings = { -- [resourceName] = {likes = 0, dislikes = 0} } local function parseReceivedRatings(received) local allRatings = {} for _, v in ipairs(received) do allRatings[v.mapresourcename] = {likes = v.likes or 0, dislikes = v.dislikes or 0} end return allRatings end function AllMapsRatings.getRating(resourceName) assert(type(resourceName) == "string", "Invalid argument, should be string. Got: " .. type(resourceName)) return mapRatings[resourceName] and { likes=mapRatings[resourceName].likes, dislikes=mapRatings[resourceName].dislikes } or { likes=0, dislikes=0 } end function AllMapsRatings.receiveRatingsFromDatabase(ratings) mapRatings = parseReceivedRatings(ratings) end function AllMapsRatings.request() RatingsFetcher.requestAll() end
-- libtiff 4.0.6 -- http://www.libtiff.org/ -- ftp://ftp.remotesensing.org/pub/libtiff/tiff-4.0.6.zip -- /external/libtiff group "Libraries" project "libtiff" kind "StaticLib" language "C++" location "../build/projects" targetdir "../build/lib/%{cfg.buildcfg}/%{cfg.platform}" filter "configurations:Debug" targetname "libtiff-d" filter{} os.copyfile( "./libtiff/libtiff/tif_config.vc.h", "../build/config/tif_config.h" ) os.copyfile( "./libtiff/libtiff/tiffconf.vc.h", "../build/config/tiffconf.h" ) defines { "USE_WIN32_FILEIO", "HAVE_SNPRINTF" } disablewarnings { "4133", -- LPCTSTR conversion incorrect in tif_win32.c "4311", -- pointer truncation "4312", -- Conversion to thandle_t of greater size } includedirs { "../build/config/" } files { "./libtiff/libtiff/t4.h", "./libtiff/libtiff/tiff.h", "./libtiff/libtiff/tiffio.h", "./libtiff/libtiff/tiffio.hxx", "./libtiff/libtiff/tiffiop.h", "./libtiff/libtiff/tiffvers.h", "./libtiff/libtiff/uvcode.h", "./libtiff/libtiff/tif_aux.c", "./libtiff/libtiff/tif_close.c", "./libtiff/libtiff/tif_codec.c", "./libtiff/libtiff/tif_color.c", "./libtiff/libtiff/tif_compress.c", "./libtiff/libtiff/tif_dir.c", "./libtiff/libtiff/tif_dir.h", "./libtiff/libtiff/tif_dirinfo.c", "./libtiff/libtiff/tif_dirread.c", "./libtiff/libtiff/tif_dirwrite.c", "./libtiff/libtiff/tif_dumpmode.c", "./libtiff/libtiff/tif_error.c", "./libtiff/libtiff/tif_extension.c", "./libtiff/libtiff/tif_fax3.c", "./libtiff/libtiff/tif_fax3.h", "./libtiff/libtiff/tif_fax3sm.c", "./libtiff/libtiff/tif_getimage.c", "./libtiff/libtiff/tif_jpeg.c", "./libtiff/libtiff/tif_ojpeg.c", "./libtiff/libtiff/tif_flush.c", "./libtiff/libtiff/tif_luv.c", "./libtiff/libtiff/tif_lzw.c", "./libtiff/libtiff/tif_next.c", "./libtiff/libtiff/tif_open.c", "./libtiff/libtiff/tif_packbits.c", "./libtiff/libtiff/tif_pixarlog.c", "./libtiff/libtiff/tif_predict.c", "./libtiff/libtiff/tif_predict.h", "./libtiff/libtiff/tif_print.c", "./libtiff/libtiff/tif_read.c", "./libtiff/libtiff/tif_stream.cxx", "./libtiff/libtiff/tif_swab.c", "./libtiff/libtiff/tif_strip.c", "./libtiff/libtiff/tif_thunder.c", "./libtiff/libtiff/tif_tile.c", "./libtiff/libtiff/tif_version.c", "./libtiff/libtiff/tif_warning.c", "./libtiff/libtiff/tif_write.c", "./libtiff/libtiff/tif_zip.c", "./libtiff/libtiff/tif_win32.c", }
require "utils" local sys = require "sys" local elasticsearch = require "elasticsearch" local es = elasticsearch:new { domain = "http://localhost:9200" -- domain参数一定要以http/https://开头, 并且结尾不能加上/ } local function test_get_status_info( ... ) -- -- 获取节点信息 -- local ok, ret = es:status() -- print(ok) var_dump(ret) -- -- 获取当前节点状态 -- local ok, ret = es:nodes_status() -- print(ok) var_dump(ret) -- -- 获取集群监控状态 -- local ok, ret = es:cluster_health() -- print(ok) var_dump(ret) end local function test_create_and_delete_index() -- -- 创建索引 -- local ok, ret = es:create_index("humans") -- print(ok) var_dump(ret) -- -- 删除索引 -- local ok, ret = es:delete_index("humans") -- print(ok) var_dump(ret) -- 批量删除索引 -- local ok, ret = es:delete_specify_index({"humans", "humans"}) -- print(ok) var_dump(ret) -- -- 删除所有索引(慎用) -- local ok, ret = es:delete_all_index() -- print(ok) var_dump(ret) end local function test_insert_and_get_and_delete_document() -- -- 插入文档(自动生成ID) -- local ok, ret = es:add_document("humans", "chinese", {name = "CandyMi", age = 29}) -- print(ok) var_dump(ret) -- 插入指定ID的文档 -- local ok, ret = es:add_id_document("humans", "chinese", 1, {name = "車先生", age = 29, role = "father"}) -- print("为index[humans]types[chinese]创建id为[1]document:", ok) var_dump(ret) -- -- 查询指定ID文档(仅显示source信息) -- local ok, ret = es:get_document_lite("humans", "chinese", 1, {"name", "age"}) -- print("查询index[humans]types[chinese]内id为[1]document", ok) var_dump(ret) -- -- 查询指定ID文档(显示所有document信息) -- local ok, ret = es:get_document_extra("humans", "chinese", 1, {"name", "age"}) -- print("查询index[humans]types[chinese]内的所有文档", ok) var_dump(ret) -- -- 批量查询文档 -- local ok, ret = es:mget_document ({ -- { id = 1, index = "humans", type = "chinese" }, -- { id = 1, index = "humans", type = "chinese" }, -- { id = 1, index = "humans", type = "chinese" }, -- }, {"name", "age"}) -- print("批量查询指定id的文档", ok) var_dump(ret) -- -- 删除指定ID的文档 -- local ok, ret = es:delete_document("humans", "chinese", 1) -- print(ok) var_dump(ret) end local function test_update_document() -- -- 完整更新文档 -- local ok, ret = es:update_document("humans", "chinese", 5, {name = "TZ太太", age = 33}) -- print(ok) var_dump(ret) -- -- 局部更新文档 -- local ok, ret = es:update_document_columns("humans", "chinese", 5, {name = "TZ先生", age = 1}) -- print(ok) var_dump(ret) end local function test_search_document() -- local documents = { -- [1] = {name = "車爪鱼", age = 23, role = "daughter"}, -- [2] = {name = "車哥哥", age = 25, role = "Son"}, -- [3] = {name = "車太太", age = 27, role = "mother"}, -- [4] = {name = "車先生", age = 29, role = "father"}, -- } -- for id, document in ipairs(documents) do -- local ts = sys.now() -- document.create_at = os.date("%Y年-%m月-%d日 %H时%M分%S秒 ", ts // 1) .. string.format("%.03f", ts - ts // 1) -- local ok, ret = es:add_id_document("humans", "chinese", id, document) -- print(ok) var_dump(ret) -- end -- -- 按照年龄降序显示上述内容 -- local ok, ret = es:search_document("humans", "chinese", nil, { { age = { order = "desc" } } }, nil, nil) -- print(ok) var_dump(ret) end -- -- 测试获取es服务器状态 -- test_get_status_info() -- -- 测试创建、删除索引 -- test_create_and_delete_index() -- 测试插入、获取、删除文档 -- test_insert_and_get_and_delete_document()
#!/usr/bin/lua local fmt = string.format local function dump_fmt(n, str) for i = 1, n do io.stdout:write(" ") end if not str then local s = '' end io.stdout:write(tostring(str)) end --for no share child table and loop table local function __dump(t, depth) depth = depth + 1 if type(t) == "number" then io.stdout:write(t) elseif type(t) == "string" then io.stdout:write(fmt("%q", t)); elseif type(t) == "table" then dump_fmt(0, "{\n") for k, v in pairs(t) do dump_fmt(depth, "[ ") __dump(k, depth) io.stdout:write(fmt(" ]%4s%4s", "=", " ")) __dump(v, depth) io.stdout:write(",\n") end dump_fmt(depth - 1, "}") else error("unknown type") end end local function dump(t) __dump(t, 0) dump_fmt(0, "\n") end util = { dump = dump, } return util
wifiwidget = widget({type = "textbox", name = "wifiwidget", align = "right" }) function wifiInfo() spacer = " " local w = assert(io.popen("awk 'NR==3 {print substr(\$3,0,2) \"%\"}' /proc/net/wireless ",'r')) local wifiStrength = (w:read('*a')) w:close() wifiwidget.text = " Wifi:"..spacer..wifiStrength..spacer end wifiInfo() awful.hooks.timer.register(15, function() wifiInfo() end)
function displayFPS() setColor(colors['black']) love.graphics.print('FPS: ' .. tostring(love.timer.getFPS()), 0, 0) end -- loads game data function loadData() -- using the bitser library data is serialized for and deserialized for easy storage if love.filesystem.exists('save-data.dat') then return bitser.loadLoveFile('save-data.dat') else newGame = true end end -- loads achievement data into game function loadAchievementData() if love.filesystem.exists('achievement-data.dat') then return bitser.loadLoveFile('achievement-data.dat') end return false end -- saves achievement data to achievement file function saveAchievementData(data) thread:start(channel) achievementData = {"achievements"} achievementUnlock = {} for i, achievement in pairs(data) do table.insert(achievementUnlock, achievement.unlocked) end table.insert(achievementData, achievementUnlock) channel:push(achievementData) end -- resets ALL data function saveReset() love.filesystem.remove("save-data.dat") love.filesystem.remove("achievement-data.dat") achievementSystem:reset() saveAchievementData(achievementSystem.achievements) print("Resetting saves...\n\n") end -- saves game data function saveData(data) thread:start(channel) gameData = {"game"} table.insert(gameData, data) channel:push(gameData) end -- helper functions function setColor(color) local r, g, b, a = love.graphics.getColor() -- research showed setColor lags when overused if r ~= color[1] and g ~= color[2] or b ~= color[3] then love.graphics.setColor(color) end end function clear(table) for i = 1, #table do table[i] = nil end end -- scrolling function love.wheelmoved(x, y) if y > 0 then velY = velY - 75 elseif y < 0 then velY = velY + 75 end end function GenerateGrid(index1, index2) local maze = {} local maxTokens = math.random(3, 5) local tokenCount = 0 for i = 0, GRID_LENGTH do maze[i + 1] = {} for j = 0, GRID_LENGTH do maze[i + 1][j + 1] = Block(i, j) -- generate tokens if math.random() < 0.01 and tokenCount < maxTokens then maze[i + 1][j + 1].hasToken = true tokenCount = tokenCount + 1 end end end -- generate goal ladderX = index1 ladderY = index2 maze[index1][index2].hasLadder = true return maze, tokenCount end function carveMaze(maze) -- first index represents the East or West side -- second index represents the North or South side -- maybe... -- maze bias local trash math.random(#DIRECTIONS) local possibleDirs = DIRECTIONS[math.random(#DIRECTIONS)] -- Remove diagonol biased walls for i = 1, #maze - 1 do -- SE if possibleDirs[1] == "S" and possibleDirs[2] == "E" then maze[i][#maze].walls["E"] = nil maze[i + 1][#maze].walls["W"] = nil maze[#maze][i].walls["S"] = nil maze[#maze][i + 1].walls["N"] = nil end -- SW if possibleDirs[1] == "S" and possibleDirs[2] == "W" then maze[i][#maze].walls["E"] = nil maze[i + 1][#maze].walls["W"] = nil maze[1][i].walls["S"] = nil maze[1][i + 1].walls["N"] = nil end -- NE if possibleDirs[1] == "N" and possibleDirs[2] == "E" then maze[i][1].walls["E"] = nil maze[i + 1][1].walls["W"] = nil maze[#maze][i].walls["S"] = nil maze[#maze][i + 1].walls["N"] = nil end -- NW if possibleDirs[1] == "N" and possibleDirs[2] == "W" then maze[i][1].walls["E"] = nil maze[i + 1][1].walls["W"] = nil maze[1][i].walls["S"] = nil maze[1][i + 1].walls["N"] = nil end end for i, col in pairs(maze) do for j, row in pairs(maze[i]) do local currentBlock = maze[i][j] -- gets next carve local nextDir = possibleDirs[math.random(#possibleDirs)] if j > 1 and nextDir == "N" then currentBlock.walls["N"] = nil maze[i][j - 1].walls["S"] = nil end if j < GRID_LENGTH + 1 and nextDir == "S" then currentBlock.walls["S"] = nil maze[i][j + 1].walls["N"] = nil end if i > 1 and nextDir == "W" then currentBlock.walls["W"] = nil maze[i - 1][j].walls["E"] = nil end if i < GRID_LENGTH + 1 and nextDir == "E" then currentBlock.walls["E"] = nil maze[i + 1][j].walls["W"] = nil end end end return maze end function GenerateQuads(atlas, tilewidth, tileheight) local sheetWidth = atlas:getWidth() / tilewidth local sheetHeight = atlas:getHeight() / tileheight local sheetCounter = 1 local spritesheet = {} for y = 0, sheetHeight - 1 do for x = 0, sheetWidth - 1 do spritesheet[sheetCounter] = love.graphics.newQuad(x * tilewidth, y * tileheight, tilewidth, tileheight, atlas:getDimensions()) sheetCounter = sheetCounter + 1 end end return spritesheet end
-- Copyright 2022 SmartThings -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local clusters = require "st.zigbee.zcl.clusters" local DoorLock = clusters.DoorLock local devices = { LOCK_WITHOUT_CODES = { FINGERPRINTS = { { model = "E261-KR0B0Z0-HA" }, { mfr = "Danalock", model = "V3-BTZB" } }, CONFIGURATION = { { cluster = DoorLock.ID, attribute = DoorLock.attributes.LockState.ID, minimum_interval = 0, maximum_interval = 3600, data_type = DoorLock.attributes.LockState.base_type, reportable_change = 1 } } } } local configurations = {} configurations.get_device_configuration = function(zigbee_device) for _, device in pairs(devices) do for _, fingerprint in pairs(device.FINGERPRINTS) do if zigbee_device:get_manufacturer() == fingerprint.mfr and zigbee_device:get_model() == fingerprint.model then return device.CONFIGURATION end end end return nil end return configurations
local lgi = require("lgi") local DBus = require("utils.dbus_wrapper.bus") local Call = require("utils.dbus_wrapper.call") local constants = require("utils.constants") local sig = require("theme.fly.signal") local Gio = lgi.Gio local GLib = lgi.GLib local nm = {} local id, type local bus local function get_current_active_connection() local call = Call.new() call.name = "org.freedesktop.NetworkManager" call.path = "/org/freedesktop/NetworkManager" call.interface = "org.freedesktop.DBus.Properties" call.member = "Get" call.args = GLib.Variant("(ss)", { "org.freedesktop.NetworkManager", "ActivatingConnection" }) call.timeout = -1 local f, body = call(bus) local s = body[1]:get_string() local path = string.format("%s", s) call.path = path call.interface = "org.freedesktop.DBus.Properties" call.member = "GetAll" call.args = GLib.Variant("(s)", { "org.freedesktop.NetworkManager.Connection.Active" }) f, body = call(bus) if f then return body[1] end return nil end local function emit_state_signal(state) awesome.emit_signal(sig.network_manager.state_changed, state, { id = id, type = type }) end local function network_state_changed(conn, sender, object_path, interface_name, signal_name, user_data) local state = tonumber(user_data[1]) if state == constants.NM_STATE_UNKNOWN or state == constants.NM_STATE_ASLEEP or state == constants.NM_STATE_DISCONNECTED or state == constants.NM_STATE_DISCONNECTING then id = nil type = nil emit_state_signal(constants.NETWORK_DISCONNECTED) end if state == constants.NM_STATE_CONNECTING then local result = get_current_active_connection() if result then id = result.Id type = result.Type emit_state_signal(constants.NETWORK_CONNECTING) end end if state == constants.NM_STATE_CONNECTED_LOCAL or state == constants.NM_STATE_CONNECTED_SITE then emit_state_signal(constants.NETWORK_CONNECTED_NO_INTERNET) end if state == constants.NM_STATE_CONNECTED_GLOBAL then emit_state_signal(constants.NETWORK_CONNECTED) end end function nm:init(config) Gio.Async.call(function() bus = DBus.new(Gio.BusType.SYSTEM) local result = get_current_active_connection() if result then if not id and not type then id = result.Id type = result.Type end local state = result.State if state == constants.NM_ACTIVE_CONNECTION_STATE_UNKNOWN or state == constants.NM_ACTIVE_CONNECTION_STATE_DEACTIVATING or state == constants.NM_ACTIVE_CONNECTION_STATE_DEACTIVATED then emit_state_signal(constants.NETWORK_DISCONNECTED) end if state == constants.NM_ACTIVE_CONNECTION_STATE_ACTIVATING then emit_state_signal(constants.NETWORK_CONNECTING) end if state == constants.NM_ACTIVE_CONNECTION_STATE_ACTIVATED then emit_state_signal(constants.NETWORK_CONNECTED) end end bus:signal_subscribe("org.freedesktop.NetworkManager", "org.freedesktop.NetworkManager", "StateChanged", nil, nil, Gio.DBusSignalFlags.NONE, network_state_changed) end)() end return nm
object_ship_nova_orion_boss_ship_tier2 = object_ship_shared_nova_orion_boss_ship_tier2:new { } ObjectTemplates:addTemplate(object_ship_nova_orion_boss_ship_tier2, "object/ship/nova_orion_boss_ship_tier2.iff")
object_mobile_coa_lag_personnel_hum_f3 = object_mobile_shared_coa_lag_personnel_hum_f3:new { } ObjectTemplates:addTemplate(object_mobile_coa_lag_personnel_hum_f3, "object/mobile/coa_lag_personnel_hum_f3.iff")
local Net = {} Net.open_browser = _ENV.native.net.open_browser return Net
local rules = require "scripts.rules" local animations = require "character.animations" local Character = require "character.character" local CastleSteward = Character:new() function CastleSteward:new(o, control) o = o or Character:new(o, control) setmetatable(o, self) self.__index = self return o end function CastleSteward:create() Character.create(self) self:set_skin("inn_keeper") local stats = self.data.stats stats.name = "Castle Steward" stats.hit_die = "d6", rules.set_ability_scores_map(stats, { str = 10, dex = 10, con = 10, int = 13, wis = 13, cha = 13, }) end function CastleSteward:on_interact(interactor_name) local dialogue = { start = { text = "I am the castle steward.", options = { { text = "I see.", go_to = 'end' }, } } } if self.control.data.know_of_thefts then table.insert(dialogue.start.options, { text = "I heard your cutley is being stolen.", go_to = 'stolen' } ) dialogue.stolen = { text = "Yes. It would be a problem if the silverware were gone too, but the thief seems content with just the cheap steel and iron forks. The queen, nonetheless, is not happy about it. If you have any suspects, please talke to me.", go_to = 'end', } end if self.control.data.cook_confessed then table.insert(dialogue.start.options, { text = "The cook confessed. He is the thief.", go_to = 'confessed' } ) dialogue.confessed = { text = "I'll inform the queen. About the imps, we don't have the men to protect the castle if they intent on attacking us, even armed with forks and whatnot.", go_to = 'end', callback = function() self.control.loaded_character_data.cook.stats.status.dead = true self.control.data.cook_arrested = true end } else if self.control.data.know_of_cook_in_the_tower and self.control.data.know_of_cook_in_the_tower and not self.control.data.received_key_from_steward then table.insert(dialogue.start.options, { text = "The cook is suspect, give me the key to his room.", go_to = 'key' } ) dialogue.key = { text = "I see. Here it is. Please, continue your investigation.", go_to = 'end', callback = function() self.control:add_item_to_inventory('player', 'cook_key', 'cook_key', 'item') self.control.data.received_key_from_steward = true end } end end if self.control.data.cook_arrested then dialogue.start = { text = "Nice day to you.", go_to = 'end' } end sfml_dialogue(dialogue) end return CastleSteward
-- 根据外面传过来的IDList 做“集合去重” local key=KEYS[1]; local args=ARGV local i=0; local result={}; for m,n in ipairs(args) do local ishit=redis.call("sismember",key,n); if(ishit) then table.insert(result,1,n); end end return result;
local route_214_0 = DoorSlot("route_214","0") local route_214_0_hub = DoorSlotHub("route_214","0",route_214_0) route_214_0:setHubIcon(route_214_0_hub) local route_214_1 = DoorSlot("route_214","1") local route_214_1_hub = DoorSlotHub("route_214","1",route_214_1) route_214_1:setHubIcon(route_214_1_hub)
--[[ -- @Name: tasknManager -- @Author: Lupus590 -- @License: MIT -- @URL: -- TODO: url -- -- If you are interested in the above format: http://www.computercraft.info/forums2/index.php?/topic/18630-rfc-standard-for-program-metadata-for-graphical-shells-use/ -- -- The MIT License (MIT) -- -- Copyright 2019 Lupus590 -- -- 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 running = false local oldError = error local function error(mess, level) running = false return oldError(mess, (level or 1) +1) end -- TODO: use argValidationUtils? local function argChecker(position, value, validTypesList, level) -- check our own args first, sadly we can't use ourself for this if type(position) ~= "number" then error("argChecker: arg[1] expected number got "..type(position),2) end -- value could be anything, it's what the caller wants us to check for them if type(validTypesList) ~= "table" then error("argChecker: arg[3] expected table got "..type(validTypesList),2) end if not validTypesList[1] then error("argChecker: arg[3] table must contain at least one element",2) end for k, v in ipairs(validTypesList) do if type(v) ~= "string" then error("argChecker: arg[3]["..tostring(k).."] expected string got "..type(v),2) end end if type(level) ~= "nil" and type(level) ~= "number" then error("argChecker: arg[4] expected number or nil got "..type(level),2) end level = level and level + 1 or 3 -- check the client's stuff for k, v in ipairs(validTypesList) do if type(value) == v then return end end local expectedTypes if #validTypesList == 1 then expectedTypes = validTypesList[1] else expectedTypes = table.concat(validTypesList, ", ", 1, #validTypesList - 1) .. " or " .. validTypesList[#validTypesList] end error("arg["..tostring(position).."] expected "..expectedTypes .." got "..type(value), level) end local patience = require("treeFarm.libs.patience") local config = require("treeFarm.libs.config") local fileNamePrefix = ".taskManager" local taskLibrary = {} -- every task we know about -- how do I edit tasks? should I be able to? -- have a getTask and replaceTask commands? local taskQueue = {} -- triggered tasks which need to run (task name only, lookup in taskLibrary) local inProgressTasks = {} -- tasks which have been marked as started but not completed (task name only, lookup in taskLibrary) local function saveTaskLibrary() local ok, err = config.save(fileNamePrefix..".taskLibrary", taskLibrary) if not ok then error("taskManager: couldn't save taskLibrary. Got error:\n"..err) end end local function loadTaskLibrary() local ok, data = config.load(fileNamePrefix..".taskLibrary") if not ok then if data == "not a file" then taskLibrary = {} return end error("taskManager: couldn't load taskLibrary. Got error:\n"..data) end taskLibrary = data end local function saveTaskQueue() local ok, err = config.save(fileNamePrefix..".taskQueue",taskQueue) if not ok then error("taskManager: couldn't save taskQueue. Got error:\n"..err) end end local function loadTaskQueue() local ok, data = config.load(fileNamePrefix..".taskQueue") if not ok then if data == "not a file" then taskQueue = {} return end error("taskManager: couldn't load taskQueue. Got error:\n"..data) end taskQueue = data end local function saveInProgressTasks() local ok, err = config.save(fileNamePrefix..".inProgressTasks",data) if not ok then error("taskManager: couldn't save inProgressTasks. Got error:\n"..err) end end local function loadInProgressTasks() local ok, data = config.load(fileNamePrefix..".inProgressTasks") if not ok then if data == "not a file" then inProgressTasks = {} return end error("taskManager: couldn't load inProgressTasks. Got error:\n"..data) end inProgressTasks = data end local exampleTriggerList = { -- nil is treated as wildcard {"timer", timerId}, {"patienceTimer", patienceTimerId}, {"rednet_message", nil, nil, approveProtocol}, -- any rednet message with that protocal } local function validateTriggerList(argPosition, triggerList, level) argChecker(1, argPosition, {"number"}) argChecker(2, triggerList, {"table"}) argChecker(3, level, {"number","nil"}) level = level + 1 or 2 if #triggerList == 0 then error("arg["..argPosition.."] table has no valid keys, tasks must have at least one tigger event", level) end for keyOfCurrentTriggerValue, currentTrigger in ipairs(triggerList) do -- validate the event arg if type(currentTrigger) ~= "table" then error("arg["..argPosition.."]["..keyOfCurrentTriggerValue.."] expected table got "..type(currentTrigger),level) end if type(currentTrigger[1]) ~= "string" then error("arg["..argPosition.."]["..keyOfCurrentTriggerValue.."][1] expected string got "..type(currentTrigger[1]) .."\n this should be an event name like the first return value of os.pullEvent. The other values of the table can be the arguments of that event, nils are treated as wildcards for the arguments.",level) end -- we checked the first value for a string already but skipping that will take more effort than it's worth for currentTriggerKey, currentTriggerValue in pairs(currentTrigger) do if not pcall(textutils.serialize, currentTriggerValue) then error("arg["..argPosition.."]["..keyOfCurrentTriggerValue.."]["..currentTriggerKey.."] could not serialize value with type " ..type(currentTriggerValue),level) end end end end local function addTask(name, triggerList, priority, recuring) argChecker(1, name, {"string"}) argChecker(2, triggerList, {"table"}) validateTriggerList(2, triggerList) argChecker(3, priority, {"number"}) argChecker(4, recuring, {"boolean", "nil"}) recuring = recuring or false local uniqueTaskId = string.format("%08x", math.random(1, 2147483647)) taskLibrary[uniqueTaskId] = { triggerList = triggerList, priority = priority, recuring = recuring, uniqueTaskId = uniqueTaskId, name = name } saveTaskLibrary() return true, uniqueTaskId end local function removeTask(uniqueTaskId) argChecker(1, uniqueTaskId, {"string"}) for k, v in ipairs(taskQueue) do while v.taskId == uniqueTaskId do -- have to do this as we are editing as we iterate table.remove(taskQueue, k) v = taskQueue[k] end end taskLibrary[uniqueTaskId] = nil inProgressTasks[uniqueTaskId] = nil saveInProgressTasks() saveTaskQueue() -- we might not have changed it but whatever saveTaskLibrary() end local doLoop = true local function exitLoop() doLoop = false end local function queueTask(taskId, triggeredEvent) argChecker(1, taskId, {"string"}) argChecker(2, triggeredEvent, {"table"}) if not taskLibrary[taskId] then return false, "task doesn't exist" end -- TODO: what do we do with retriggered tasks already in progress or in the queue? #askDiscord -- should the client care about the event that triggered the task? os.queueEvent(taskEventType, taskLibrary[taskId].name, taskId, triggeredEvent) table.add(taskQueue, {taskId=taskId, triggeredEvent=triggeredEvent}) saveTaskQueue() return true end local function enterLoop(taskFileNamePrefix) argChecker(1, taskFileNamePrefix, {"string", "nil"}) fileNamePrefix = taskFileNamePrefix or fileNamePrefix if running then return false, "already running" end running = true; doLoop = true loadTaskQueue() loadTaskLibrary() loadInProgressTasks() local function eventMatchesThisTrigger(event, trigger) for k, v in pairs(trigger) do if type(k) == "number" and event[k] ~= v then return false end end return true end local function eventMatchesATriggerInList(event, triggerList) for _, trigger in ipairs(triggerList) do if event[1] == trigger[1] and eventMatchesThisTrigger(event, trigger) then return true end end return false end while doLoop do local event = table.pack(os.pullEvent()) if event[1] ~= taskEventType then -- ignore task events as we queue them for taskId, taskData in pairs(taskLibrary) do if eventMatchesATriggerInList(event, taskData.triggerList) then queueTask(taskId, event) end end end end running = false -- just in case people want to start us again return true end local function isRunning() return running end local taskEventType = "task" local function waitForTask(taskName, uniqueTaskId) argChecker(1, taskName, {"string", "nil"}) argChecker(2, uniqueTaskId, {"string", "nil"}) while true do local _, eventTaskName, eventTaskId, triggerEventData = os.pullEvent(taskEventType) if taskName == eventTaskName and uniqueTaskId == eventTaskId then return eventTaskName, eventTaskId, triggerEventData end end end -- doing tasks out of order is fine, maybe the current task host can't do the first task local function markTaskAsStarted(uniqueTaskId, taskHostId) argChecker(1, uniqueTaskId, {"string"}) argChecker(2, taskHostId, {"string"}) for k, v in ipairs(taskQueue) do if v.taskId == uniqueTaskId then local startedTask = table.remove(taskQueue, k) inProgressTasks[uniqueTaskId] = taskHostId saveInProgressTasks() saveTaskQueue() return true end end return false, "task doesn't exist or has not been triggered" end -- TODO: how to interrupt tasks? #Hive -- put the task back in the queue? -- preferably with the progress preserved local function markTaskAsComplete(uniqueTaskId, taskHostId) argChecker(1, uniqueTaskId, {"string"}) argChecker(2, taskHostId, {"string"}) if inProgressTasks[uniqueTaskId] == taskHostId then inProgressTasks[uniqueTaskId] = nil saveInProgressTasks() return true elseif inProgressTasks[uniqueTaskId] then return false, "task is owned by another task host" end return false, "task has not been started or doesn't exist" end local function taskIsInprogress(uniqueTaskId) argChecker(1, uniqueTaskId, {"string"}) return inProgressTasks[uniqueTaskId] and true or false end local function copyTable(from) local copy = {} for k, v in pairs(from) do if type(v) == "table" then copy[k] = copyTable(v) else copy[k] = v end end return copy end local function getInprogressTasks() return copyTable(inProgressTasks) end local function getTaskQueue() return copyTable(taskQueue) end local function getTaskLibrary() return copyTable(taskLibrary) end local function getTaskInfoById(taskId) if taskLibrary[taskId] then return true, copyTable(taskLibrary[taskId]) end return false, "could not find that task" end local taskManager = { addTask = addTask, removeTask = removeTask, exitLoop = exitLoop, queueTask = queueTask, -- here to allow manual task triggering enterLoop = enterLoop, run = enterLoop, start = enterLoop, stop = exitLoop, isRunning = isRunning, hasStarted = isRunning, taskEventType = taskEventType, waitForTask = waitForTask, markTaskAsStarted = markTaskAsStarted, markTaskAsComplete = markTaskAsComplete, taskIsInprogress = taskIsInprogress, getInprogressTasks = getInprogressTasks, getTaskQueue = getTaskQueue, getTaskLibrary = getTaskLibrary, getTaskInfoById = getTaskInfoById, }
Property = {} Property.__index = Property function Property:Create(info) if not info or not info.id then error("invalid property definition (no info or id)") end local property = setmetatable(info, Property) return property end function Property:HasKey(id) if not self.keys then return false end return self.keys[id] end
module(..., package.seeall) -------------------------------------------------------------------------------- -- Event Handler -------------------------------------------------------------------------------- function onCreate(e) scrollView = widget.ScrollView { scene = scene, bouncePolicy = {false, false}, } tileMap = tiled.TileMap() tileMap:loadLueFile("desert.lue") scrollView:addContent(tileMap) end
ELONA.i18n:add { net = { failed_to_send = "送信に失敗した。", failed_to_receive = "受信に失敗した。", chat = { wait_more = "もう少し待った方がいい気がする。", message = "「{$1}」", sent_message = "{$1}{$2}{$3}", }, death = { sent_message = "{$1}{$2}は{$4}で{$3}{$5}", }, wish = { sent_message = "{$1}{$2}は狂喜して叫んだ。{$3}{$4}", }, news = { bomb = "[パルミア・タイムズ {$1}] {$4}で核爆弾炸裂。復旧には3日を要する見込み", void = "[パルミア・タイムズ {$1}] {$2}{$3}すくつ{$4}階層に到達", ehekatl = "[パルミア・タイムズ {$1}] {$2}{$3}エヘカトル像を入手", fire = "[パルミア・タイムズ {$1}] ノイエルで大火災。何者かが巨人を解放か", }, alias = { message = "素敵な異名コンテスト♪1", title = "投票箱", hint = "決定 [投票する項目を選択] ", choice = "投票項目", vote = "備考", submit = "あなたの異名を登録する", cannot_vote_until = "あなたの投票権はまだ復活していない({$1}まで)", prompt = "どの候補に投票する?", rank = "第{$1}位", selected = "候補", ok = "オッケー", need_to_wait = "まだ投票権が復活していない。", i_like = "「{$1}は素敵!」", you_vote = "投票した。", }, }, }
local key = ModPath .. ' ' .. RequiredScript if _G[key] then return else _G[key] = true end function VehicleStateParked:update(t, dt) if self._unit:vehicle():velocity():length() < 0.002 then return end self.super.update(self, t, dt) end
paths.dofile('layers/Residual.lua') local function hourglass(n, numIn, numOut, inp) -- Upper branch local up1 = Residual(numIn,256)(inp) local up2 = Residual(256,256)(up1) local up4 = Residual(256,numOut)(up2) -- Lower branch local pool = nnlib.SpatialMaxPooling(2,2,2,2)(inp) local low1 = Residual(numIn,256)(pool) local low2 = Residual(256,256)(low1) local low5 = Residual(256,256)(low2) local low6 if n > 1 then low6 = hourglass(n-1,256,numOut,low5) else low6 = Residual(256,numOut)(low5) end local low7 = Residual(numOut,numOut)(low6) local up5 = nn.SpatialUpSamplingNearest(2)(low7) -- Bring two branches together return nn.CAddTable()({up4,up5}) end local function lin(numIn,numOut,inp) -- Apply 1x1 convolution, no stride, no padding local l_ = nnlib.SpatialConvolution(numIn,numOut,1,1,1,1,0,0)(inp) return nnlib.ReLU(true)(nn.SpatialBatchNormalization(numOut)(l_)) end function createModel() local inp = nn.Identity()() -- Initial processing of the image local cnv1_ = nnlib.SpatialConvolution(3,64,7,7,2,2,3,3)(inp) -- 128 local cnv1 = nnlib.ReLU(true)(nn.SpatialBatchNormalization(64)(cnv1_)) local r1 = Residual(64,128)(cnv1) local pool = nnlib.SpatialMaxPooling(2,2,2,2)(r1) -- 64 local r4 = Residual(128,128)(pool) local r5 = Residual(128,128)(r4) local r6 = Residual(128,256)(r5) -- First hourglass local hg1 = hourglass(4,256,512,r6) -- Linear layers to produce first set of predictions local l1 = lin(512,512,hg1) local l2 = lin(512,256,l1) -- First predicted heatmaps local out1 = nnlib.SpatialConvolution(256,outputDim[1][1],1,1,1,1,0,0)(l2) local out1_ = nnlib.SpatialConvolution(outputDim[1][1],256+128,1,1,1,1,0,0)(out1) -- Concatenate with previous linear features local cat1 = nn.JoinTable(2)({l2,pool}) local cat1_ = nnlib.SpatialConvolution(256+128,256+128,1,1,1,1,0,0)(cat1) local int1 = nn.CAddTable()({cat1_,out1_}) -- Second hourglass local hg2 = hourglass(4,256+128,512,int1) -- Linear layers to produce predictions again local l3 = lin(512,512,hg2) local l4 = lin(512,512,l3) -- Output heatmaps local out2 = nnlib.SpatialConvolution(512,outputDim[2][1],1,1,1,1,0,0)(l4) -- Final model local model = nn.gModule({inp}, {out1,out2}) return model end
--[[ Assume the following code: a = {}; a.a = a What would be the value of a.a.a.a? Is any a in that sequence somehow different from the others? Now, add the next line to the previous code: a.a.a.a = 3 What would be the value of a.a.a.a now? ]]-- a = {}; a.a = a -- The same as a["a"] = a print(a.a.a.a) -- The same as a["a"].a.a = a.a.a = a["a"].a = a.a = a["a"] = a a.a.a.a = 3 -- The same as a = 3 print(a.a.a.a) -- Error. 3.3.3.3 !??!?!
Battery = Class{__includes = GameObject} function Battery:init(x,y,active,globalPositioning) GameObject.init(self,x,y,active,globalPositioning) self.source = textures['ButtonCycles'] self.cycle = cycles['BatteryPower'] self.pos = {x=x, y=y} self.charge = 15*3 end function Battery:update() GameObject.update(self) end function Battery:render() battery_charge = 6 - math.ceil(self.charge / (6*15)) love.graphics.draw( self.source, self.cycle[battery_charge], self.pos.x, self.pos.y, 0, 1, 1, 0, 0 ) end
local cURL = require("lcurl") -- open output file f = assert(io.open("example_homepage.html", "w")) cURL.easy() -- setup url :setopt_url("http://www.example.com/") -- setup file object as writer :setopt_writefunction(f) -- perform, invokes callbacks :perform() -- close easy :close() -- close output file f:close() print("Done")
local ColorReductor = {} local ColorHelper = require 'supernova.helpers.color' local TableHelper = require 'supernova.helpers.table' local ANSI = require 'supernova.core.ansi' ColorReductor['COLOR_PALETTES'] = { [256] = require 'supernova.core.reductor.256_vga', [16] = require 'supernova.core.reductor.16_vga', [8] = {} } ColorReductor['COLOR_PALETTES'][8] = TableHelper.pack(TableHelper.unpack( ColorReductor['COLOR_PALETTES'][16], 1, 8 )) function ColorReductor.rgb_to_code(rgb) local result = ColorHelper.nearest(rgb, ColorReductor['COLOR_PALETTES'][256]) return result.colors[1].code end function ColorReductor.code_to_sgr(sgr_code, color_code, colors) local result = ColorHelper.nearest( ColorReductor['COLOR_PALETTES'][256][color_code].rgb, colors ) local color_index = result.colors[1].code if color_index > 8 then color_index = color_index - 8 end color_index = color_index - 1 local color if sgr_code == ANSI.SGR_CODES.color then if result.colors[1].code > 8 then color = 90 + color_index else color = 30 + color_index end elseif sgr_code == ANSI.SGR_CODES.background then if result.colors[1].code > 8 then color = 100 + color_index else color = 40 + color_index end end return color end function ColorReductor.code_to_sgr_16(sgr_code, color_code) return ColorReductor.code_to_sgr(sgr_code, color_code, ColorReductor['COLOR_PALETTES'][16]) end function ColorReductor.code_to_sgr_8(sgr_code, color_code) return ColorReductor.code_to_sgr(sgr_code, color_code, ColorReductor['COLOR_PALETTES'][8]) end return ColorReductor
local playsession = { {"WorldofWarIII", {71819}}, {"LtDerp", {71803}} } return playsession
Citizen.CreateThread(function() while true do Citizen.Wait(0) if GetPlayerWantedLevel(PlayerId()) ~= 0 then SetPlayerWantedLevel(PlayerId(), 0, false) SetPlayerWantedLevelNow(PlayerId(), false) SetPoliceIgnorePlayer(PlayerId(), true) SetDispatchCopsForPlayer(PlayerId(), false) SetDitchPoliceModels() end local playerPed = GetPlayerPed(-1) local playerLocalisation = GetEntityCoords(playerPed) ClearAreaOfCops(playerLocalisation.x, playerLocalisation.y, playerLocalisation.z, 400.0) end end) -- Anti car jack -- -- Citizen.CreateThread(function() -- while true do -- if DoesEntityExist(GetVehiclePedIsTryingToEnter(PlayerPedId())) then -- local veh = GetVehiclePedIsTryingToEnter(PlayerPedId()) -- local lock = GetVehicleDoorLockStatus(veh) -- -- if lock == 7 then -- SetVehicleDoorsLocked(veh, 2) -- end -- -- local pedd = GetPedInVehicleSeat(veh, -1) -- -- if pedd then -- SetPedCanBeDraggedOut(pedd, false) -- end -- end -- Citizen.Wait(0) -- end -- end)
local giftBagTextFiles = { ["Public/CMP_LevelUpEquipment/Stats/Generated/Data/Armor.txt"] = "Public/SorcerousSundriesFixed_bec8c59f-7ae9-478d-9a9e-f49d22aa520f/Stats/Generated/Data/LLSUNDRIES_Armor.txt", ["Public/CMP_LevelUpEquipment/Stats/Generated/Data/Shield.txt"] = "Public/SorcerousSundriesFixed_bec8c59f-7ae9-478d-9a9e-f49d22aa520f/Stats/Generated/Data/LLSUNDRIES_Shield.txt", ["Public/CMP_LevelUpEquipment/Stats/Generated/Data/Weapon.txt"] = "Public/SorcerousSundriesFixed_bec8c59f-7ae9-478d-9a9e-f49d22aa520f/Stats/Generated/Data/LLSUNDRIES_Weapon.txt", } --- Reverts all of the Sundries overrides to all weapon/armor/shield stat files. --- Sundries overrides everythign, including NPC stats, to add combo categories. --- We can just add the categories with the extender to maintain compatibility instead. for file,override in pairs(giftBagTextFiles) do Ext.AddPathOverride(file, override) --Ext.Print("[SorcerousSundriesFixed:Shared.lua] Overriding gift bag file ("..file..") with ("..override..").") end local STAT_BLACKLIST = { NoWeapon = true, NoShield = true, } local WEAPON_PREFIX_BLACKLIST = { Damage_ = true, DamageSurface_ = true, Status_ = true, Skill_ = true, } local comboCategories = { Armor = { Helmet = "UpgradeArmour", Breast = "UpgradeArmour", Leggings = "UpgradeArmour", Boots = "UpgradeArmour", Gloves = "UpgradeArmour", Ring = "UpgradeJewellery", Ring2 = "UpgradeJewellery", Belt = "UpgradeJewellery", Amulet = "UpgradeJewellery", }, Weapon = "UpgradeWeapon", Shield = "UpgradeShield" } local function StartsWith(target,str) return string.sub(target,1,string.len(str))==str end local function IgnoreWeapon(stat) local itemgroup = Ext.StatGetAttribute(stat, "ItemGroup") if itemgroup == nil or itemgroup == "" then return true end for word,b in pairs(WEAPON_PREFIX_BLACKLIST) do if b == true then --if string.find(stat, word) then return true end if StartsWith(stat, word) then return true end end end return false end local function IgnoreStat(stat, statType) if string.sub(stat, 1, 1) == "_" or STAT_BLACKLIST[stat] == true then -- Ignore NPC weapons return true end local modifierType = Ext.StatGetAttribute(stat, "ModifierType") if modifierType ~= nil and modifierType ~= "Item" then -- Ignore Boost, Skill, etc return true end if statType == "Weapon" and IgnoreWeapon(stat) then return true end return false end local function HasComboCategory(categoryTable, category) if categoryTable == nil then return false end for i,v in pairs(categoryTable) do if v == category then return true end end return false end local function AddComboCategories() --Ext.Print("===================================================================") --Ext.Print("[SorcerousSundriesFixed] Adding crafting categories to all non-NPC equipment stats.") local totalOverrides = 0 for statType,v in pairs(comboCategories) do local stats = Ext.GetStatEntries(statType) for i,stat in pairs(stats) do if not IgnoreStat(stat, statType) then local addCategory = nil if type(v) == "table" then local slot = Ext.StatGetAttribute(stat, "Slot") addCategory = v[slot] else addCategory = v end if addCategory ~= nil then local combocategory = Ext.StatGetAttribute(stat, "ComboCategory") if not HasComboCategory(combocategory, addCategory) then if type(combocategory) == "table" then combocategory[#combocategory+1] = addCategory Ext.StatSetAttribute(stat, "ComboCategory", combocategory) totalOverrides = totalOverrides + 1 else Ext.StatSetAttribute(stat, "ComboCategory", {addCategory}) totalOverrides = totalOverrides + 1 end end end end end end Ext.Print("[SorcerousSundriesFixed] Added upgrade categories to ("..tostring(totalOverrides)..") stats.") --Ext.Print("===================================================================") end Ext.RegisterListener("StatsLoaded", AddComboCategories) --Ext.RegisterListener("ModuleResume", AddComboCategories) --Ext.RegisterListener("ModuleLoading", AddComboCategories)
local create = require "create" function newWall( x, y, w, h ) walls[#walls + 1] = newColl( "wall", x, y, w, h ) end function lineToRect( x1, y1, x2, y2, size ) if( x1 == x2 ) then local x = x1 local y = math.min( y1, y2 ) local w = size local h = math.max( y1, y2 ) - y + size return x, y, w, h else local x = math.min( x1, x2 ) local y = y1a local w = math.max( x1, x2 ) - x + size local h = size return x, y, w, h end end function newMap() -- reset stuff ( or make them for the first time ) walls = {} effects = {} tanks = {} bullets = {} colliders = {} -- local minMapSize = 300 local maxMapSize = 200 local minWallCount = 20 local maxWallCount = 40 local minWallSize = 10 local maxWallSize = 100 -- generate walls -- rect of the whole map local top = love.math.random( -minMapSize, -maxMapSize ) -- local left = love.math.random( -300, -200 ) local left = top * love.graphics.getWidth() / love.graphics.getHeight() local down = -top local right = -left camera.scale = ( love.graphics.getHeight() - 30 ) / ( down - top ) -- big border walls newWall( -3000, -3000, left + 3000, 6000 ) newWall( -3000, -3000, 6000, top + 3000 ) newWall( -3000, down, 6000, 3000 ) newWall( right, -3000, 3000, 6000 ) -- generating the maze local wallCount = love.math.random( minWallCount, maxWallCount ) for i = 1, wallCount do local ok = false while( not ok ) do local new = {} new.x = love.math.random( left, right ) new.y = love.math.random( top, down ) new.w = love.math.random( minWallSize, maxWallSize ) new.h = love.math.random(minWallSize, maxWallSize ) ok = true for j, wall in ipairs( walls ) do if( wall.x and isColliding( wall, new ) ) then ok = false break end end if( ok )then newWall( new.x, new.y, new.w, new.h ) end end --newWall( love.math.random( left, right ), love.math.random( top, down ), love.math.random( minWallSize, maxWallSize ), love.math.random(minWallSize, maxWallSize ) ) end -- make the tanks from the player table for i = 1, #players do tanks[i] = create.tank( 0, 0, players[i] ) end -- put the players somewhere nice for i = 1, #tanks do while( true ) do local x, y = love.math.random( top + 20, down - 20), love.math.random( left + 20, right - 20) local mov = {} local item mov.x, mov.y = x - tanks[i].x, y - tanks[i].y mov, item = collide( tanks[i].collider, mov ) tanks[i].x = tanks[i].x + mov.x tanks[i].y = tanks[i].y + mov.y tanks[i].rotation = love.math.random()*math.pi*2 if( item.what == "nothing" ) then break end end end end
local pn = GAMESTATE:GetEnabledPlayers()[1] local profile = GetPlayerOrMachineProfile(pn) local user = playerConfig:get_data(pn_to_profile_slot(pn)).Username local pass = playerConfig:get_data(pn_to_profile_slot(pn)).Password if isAutoLogin() then DLMAN:LoginWithToken(user, pass) end local screenChoices = { ScreenNetSelectMusic = true, ScreenSelectMusic = true, } local replayScore local isEval local t = Def.ActorFrame{ LoginFailedMessageCommand = function(self) SCREENMAN:SystemMessage("Login Failed!") end, LoginMessageCommand=function(self) SCREENMAN:SystemMessage("Login Successful!") GHETTOGAMESTATE:setOnlineStatus("Online") end, LogOutMessageCommand=function(self) SCREENMAN:SystemMessage("Logged Out!") GHETTOGAMESTATE:setOnlineStatus("Local") end, TriggerReplayBeginMessageCommand = function(self, params) replayScore = params.score isEval = params.isEval self:sleep(0.1) self:queuecommand("DelayedReplayBegin") end, DelayedReplayBeginCommand = function(self) if isEval then SCREENMAN:GetTopScreen():ShowEvalScreenForScore(replayScore) else SCREENMAN:GetTopScreen():PlayReplay(replayScore) end end, CurrentSongChangedMessageCommand = function(self) if profile:IsCurrentChartPermamirror() then local modslevel = "ModsLevel_Preferred" local playeroptions = GAMESTATE:GetPlayerState():GetPlayerOptions(modslevel) playeroptions:Mirror(false) end end, PlayingSampleMusicMessageCommand = function(self) local leaderboardEnabled = playerConfig:get_data(pn_to_profile_slot(PLAYER_1)).leaderboardEnabled and DLMAN:IsLoggedIn() if leaderboardEnabled and GAMESTATE:GetCurrentSteps() then local chartkey = GAMESTATE:GetCurrentSteps():GetChartKey() if screenChoices[SCREENMAN:GetTopScreen():GetName()] then if SCREENMAN:GetTopScreen():GetMusicWheel():IsSettled() then DLMAN:RequestChartLeaderBoardFromOnline( chartkey, function(leaderboard) end ) end end end end } t[#t+1] = Def.Quad{ InitCommand=function(self) self:y(SCREEN_HEIGHT):halign(0):valign(1):zoomto(SCREEN_WIDTH,200):diffuse(getMainColor("background")):fadetop(1) end } t[#t+1] = LoadActor("../_frame") t[#t+1] = LoadActor("profilecard") t[#t+1] = LoadActor("tabs") t[#t+1] = LoadActor("currentsort") t[#t+1] = StandardDecorationFromFileOptional("BPMDisplay","BPMDisplay") t[#t+1] = StandardDecorationFromFileOptional("BPMLabel","BPMLabel") t[#t+1] = LoadActor("../_cursor") t[#t+1] = LoadActor("bgm") local largeImageText = string.format("%s: %5.2f",profile:GetDisplayName(), profile:GetPlayerRating()) GAMESTATE:UpdateDiscordMenu(largeImageText) return t
--[[----------------------------------------------------------------------- * | Copyright (C) Shaobo Wan (Tinywan) * |------------------------------------------------------------------------ * | Author: Tinywan * | Date Time : 2019/5/28 16:25 * | Email: Overcome.wan@Gmail.com * | Desc: 网关接口限流 https://github.com/openresty/lua-resty-limit-traffic * |------------------------------------------------------------------------ --]] local limit_conn = require "resty.limit.conn" local limit_req = require "resty.limit.req" local limit_traffic = require "resty.limit.traffic" local lim1, err = limit_req.new("my_req_store", 3, 2) assert(lim1, err) local lim2, err = limit_req.new("my_req_store", 2, 1) assert(lim2, err) local lim3, err = limit_conn.new("my_conn_store", 10, 10, 0.5) assert(lim3, err) local limiters = {lim1, lim2, lim3} local host = ngx.var.host local client = ngx.var.binary_remote_addr local keys = {host, client, client} local states = {} local delay, err = limit_traffic.combine(limiters, keys, states) if not delay then if err == "rejected" then return ngx.exit(503) end ngx.log(ngx.ERR, "failed to limit traffic: ", err) return ngx.exit(500) end if lim3:is_committed() then local ctx = ngx.ctx ctx.limit_conn = lim3 ctx.limit_conn_key = keys[3] end print("sleeping ", delay, " sec, states: ", table.concat(states, ", ")) if delay >= 0.001 then ngx.sleep(delay) end
EditorLootBag = EditorLootBag or class(MissionScriptEditor) EditorLootBag.USES_POINT_ORIENTATION = true EditorLootBag._test_units = {} function EditorLootBag:create_element() self.super.create_element(self) self._element.class = "ElementLootBag" self._element.values.spawn_dir = Vector3(0, 0, 1) self._element.values.push_multiplier = 0 self._element.values.carry_id = "none" self._element.values.from_respawn = false end function EditorLootBag:test_element() local unit_name = 'units/payday2/pickups/gen_pku_lootbag/gen_pku_lootbag' local throw_distance_multiplier = 1 if self._element.values.carry_id ~= 'none' then unit_name = tweak_data.carry[self._element.values.carry_id].unit or unit_name local carry_type = tweak_data.carry[self._element.values.carry_id].type throw_distance_multiplier = tweak_data.carry.types[carry_type].throw_distance_multiplier or throw_distance_multiplier end local unit = safe_spawn_unit(unit_name, self._unit:position(), self._unit:rotation()) table.insert(self._test_units, unit) local push_value = self._element.values.push_multiplier and self._element.values.spawn_dir * self._element.values.push_multiplier or 0 unit:push(100, 600 * push_value * throw_distance_multiplier) end function EditorLootBag:stop_test_element() for _, unit in ipairs(self._test_units) do if alive(unit) then World:delete_unit(unit) end end self._test_units = {} end function EditorLootBag:update(t, dt) local kb = Input:keyboard() local speed = 60 * dt self._element.values.spawn_dir = self._element.values.spawn_dir or Vector3() if kb:down(Idstring("left")) then self._element.values.spawn_dir = self._element.values.spawn_dir:rotate_with(Rotation(speed, 0, 0)) end if kb:down(Idstring("right")) then self._element.values.spawn_dir = self._element.values.spawn_dir:rotate_with(Rotation(-speed, 0, 0)) end if kb:down(Idstring("up")) then self._element.values.spawn_dir = self._element.values.spawn_dir:rotate_with(Rotation(0, 0, speed)) end if kb:down(Idstring("down")) then self._element.values.spawn_dir = self._element.values.spawn_dir:rotate_with(Rotation(0, 0, -speed)) end local from = self._element.values.position local to = from + self._element.values.spawn_dir * 100000 local ray = World:raycast("ray", from, to) if ray and ray.unit then Application:draw_sphere(ray.position, 25, 1, 0, 0) Application:draw_arrow(self._element.values.position, self._element.values.position + self._element.values.spawn_dir * 50, 0.75, 0.75, 0.75, 0.1) end EditorLootBag.super.update(self, t, dt) end function EditorLootBag:_build_panel() self:_create_panel() self:NumberCtrl("push_multiplier", {floats = 1, min = 0, help = "Use this to add a velocity to a physic push on the spawned unit"}) self:ComboCtrl("carry_id", table.list_add({"none"}, tweak_data.carry:get_carry_ids()), {help = "Select a carry_id to be created."}) self:BooleanCtrl("from_respawn") self:Text("This element can spawn loot bags, control the spawn direction using your arrow keys") end EditorLootBagTrigger = EditorLootBagTrigger or class(MissionScriptEditor) function EditorLootBagTrigger:create_element() self.super.create_element(self) self._element.class = "ElementLootBagTrigger" self._element.values.elements = {} self._element.values.trigger_type = "load" end function EditorLootBagTrigger:_build_panel() self:_create_panel() self:BuildElementsManage("elements", nil, {"ElementLootBag"}) self:ComboCtrl("trigger_type", {"load", "spawn"}, {help = "Select a trigger type for the selected elements"}) self:Text("This element is a trigger to point_loot_bag element.") end
local variable = "example"
_G.RenderingDepth = { -- under Salt = 90, Spikes = 100, Tomb = 110, Devices = 120, VampireDead = 150, Default = 200, Player = 220, Key = 240, VampireAlive = 250, God = 9001, -- over } _G.DrawSimpleEntImage = function(ent, imageAsset) if imageAsset then love.graphics.push() --love.graphics.points(0, 0) local drawBounds = Vec(1, 1) * (imageAsset.scale or 1) local scale = drawBounds / imageAsset.size love.graphics.translate(0.5 - 0.5 * drawBounds.x, 0.5 - 0.5 * drawBounds.y) love.graphics.scale(scale:xy()) love.graphics.draw(imageAsset.handle) love.graphics.pop() end end _G.DrawSimpleEntAnim = function(ent, animAsset, frac) if animAsset then love.graphics.push() local drawBounds = Vec(1, 1) * (animAsset.scale or 1) local scale = drawBounds / animAsset.fullSize local frameIdx = math.floor(frac * animAsset.frames) if animAsset.loop then frameIdx = math.mod(frameIdx, animAsset.frames) else frameIdx = math.clamp(frameIdx, 0, animAsset.frames - 1) end local quad = animAsset.quads[frameIdx + 1] love.graphics.translate(0.5 - 0.5 * drawBounds.x, 0.5 - 0.5 * drawBounds.y) love.graphics.scale(scale:xy()) love.graphics.draw(animAsset.handle, quad, 0, 0, 0, animAsset.frames, 1) love.graphics.pop() end end
-- the RGB color values return { white = 0xf0f0f0, orange = 0xf2b233, magenta = 0xe57fd8, lightblue = 0x99b2f2, yellow = 0xdede6c, lime = 0x7fcc19, pink = 0xf2b2cc, gray = 0x4c4c4c, silver = 0x999999, cyan = 0x4c9962, purple = 0xb266e5, blue = 0x253192, brown = 0x7f664c, green = 0x57a64e, red = 0xcc4c4c, black = 0x191919 }
local md local Plugin = {} function Plugin:JoinTeam(gamerules, player, newTeamNumber, force, shineForce) local cancel = false if TGNS.IsGameplayTeamNumber(newTeamNumber) then local client = TGNS.GetClient(player) if not (force or shineForce) and not TGNS.GetIsClientVirtual(client) then local playerList = TGNS.GetPlayerList() if #TGNS.GetTeamClients(newTeamNumber, playerList) >= 8 then local otherPlayingTeamNumber = TGNS.GetOtherPlayingTeamNumber(newTeamNumber) if #TGNS.GetTeamClients(otherPlayingTeamNumber, playerList) < 8 then cancel = true TGNS.SendToTeam(player, otherPlayingTeamNumber) md:ToPlayerNotifyInfo(player, string.format("You were placed on %s to preserve 8v8.", TGNS.GetTeamName(otherPlayingTeamNumber))) end end end end if cancel then return false end end function Plugin:Initialise() self.Enabled = true md = TGNSMessageDisplayer.Create("TEAMS") return true end function Plugin:Cleanup() --Cleanup your extra stuff like timers, data etc. self.BaseClass.Cleanup( self ) end Shine:RegisterExtension("enforceteamsizes", Plugin )
local M = {} function M.get(cp) return { NeogitBranch = { fg = cp.catppuccin4 }, NeogitRemote = { fg = cp.catppuccin4 }, NeogitHunkHeader = { bg = cp.catppuccin9, fg = cp.catppuccin10 }, NeogitHunkHeaderHighlight = { bg = cp.catppuccin12, fg = cp.catppuccin9 }, NeogitDiffContextHighlight = { bg = cp.catppuccin15, fg = cp.catppuccin0 }, NeogitDiffDeleteHighlight = { fg = cp.catppuccin5, bg = cp.catppuccin1 }, NeogitDiffAddHighlight = { fg = cp.catppuccin9, bg = cp.catppuccin1 }, } end return M
local cutils = require 'libcutils' local qmem = require 'Q/UTILS/lua/qmem' qmem.init() local cmd = string.format("find %s -type f -delete", qmem.q_data_dir) return function() os.execute(cmd) -- TODO P4 add rmdir functionality to cutils and use instead of os.exec end
-- Bufferline require('bufferline').setup { options = { numbers = "none", close_command = "bdelete! %d", right_mouse_command = "vertical sbuffer %d", left_mouse_command = "buffer %d", middle_mouse_command = nil, indicator_icon = '▎', buffer_close_icon = '', modified_icon = '●', close_icon = nil, left_trunc_marker = '', right_trunc_marker = '', name_formatter = function(buf) if buf.name:match('%.md') then return vim.fn.fnamemodify(buf.name, ':t:r') end end, max_name_length = 18, max_prefix_length = 15, -- prefix used when a buffer is de-duplicated tab_size = 18, diagnostics = "nvim_lsp", diagnostics_indicator = function(count, level, diagnostics_dict, context) local icon = level:match("error") and " " or " " return " " .. icon .. count end, custom_filter = function(buf_number) if vim.bo[buf_number].filetype ~= "<i-dont-want-to-see-this>" then return true end if vim.fn.bufname(buf_number) ~= "<buffer-name-I-dont-want>" then return true end if vim.fn.getcwd() == "<work-repo>" and vim.bo[buf_number].filetype ~= "wiki" then return true end end, offsets = { { filetype = "NvimTree", text = function() return vim.fn.getcwd() end, highlight = "Directory", text_align = "center" } }, show_buffer_icons = true, show_buffer_close_icons = true, show_close_icon = true, show_tab_indicators = true, persist_buffer_sort = true, separator_style = "thick", enforce_regular_tabs = false, always_show_bufferline = true, sort_by = "id" }, custom_areas = { right = function() local result = {} local error = vim.diagnostic.get(0, [[Error]]) local warning = vim.diagnostic.get(0, [[Warning]]) local info = vim.diagnostic.get(0, [[Information]]) local hint = vim.diagnostic.get(0, [[Hint]]) if error ~= 0 then table.insert(result, {text = "  " .. error, guifg = "#EC5241"}) end if warning ~= 0 then table.insert(result, {text = "  " .. warning, guifg = "#EFB839"}) end if hint ~= 0 then table.insert(result, {text = "  " .. hint, guifg = "#A3BA5E"}) end if info ~= 0 then table.insert(result, {text = "  " .. info, guifg = "#7EA9A7"}) end return result end, } }
local tree_utils = require("kotaro.parser.tree_utils") local identify_containers_visitor = {} function identify_containers_visitor:new() return setmetatable({ scopes = {} }, { __index = identify_containers_visitor }) end function identify_containers_visitor:visit_leaf(node) end local function mark_block(node, block_start, block_end) local cb = function(n) n.block_start = block_start n.block_end = block_end end block_start.is_block_start = true block_end.is_block_end = true tree_utils.each_leaf(node, cb) end function identify_containers_visitor:visit_node(node, visit) if node:type() == "constructor_expression" then for _, child in ipairs(node:children()) do child:first_leaf().opening_bracket = node:first_leaf() end node:first_leaf().matching_bracket = node:last_leaf() node:last_leaf().matching_bracket = node:first_leaf() node:first_leaf().is_block_start = true node:last_leaf().is_block_end = true assert(node:first_leaf().matching_bracket.value == "}") assert(node:last_leaf().matching_bracket.value == "{") end if node:type() == "function_parameters_and_body" then -- mark the parameter list between '(' and ')' as a block node[4].function_start = node.parent[2] node[2].matching_bracket = node[4] node[4].matching_bracket = node[2] mark_block(node, node[2], node[4]) end if node:type() == "expression" then if node:is_unary() then node:operator().is_unary_op = true elseif node:is_binary() then node:operator().is_binary_op = true end end if node:type() == "suffixed_expression" then for i = 2, #node do local leaf = node[i]:first_leaf() if leaf then leaf.first_suffix = node[2] end end end if node:type() == "if_block" then local if_start = node[2] local if_clause_start local if_clause for _, v in node:iter_rest() do if v.value == "if" or v.value == "elseif" then if if_clause then if_clause.next_if_clause = v if_clause = nil end if_clause_start = v elseif v.value == "then" then v.if_clause_start = if_clause_start if_clause_start.if_clause_end = v if_clause = v if_clause_start = nil elseif v.value == "end" and if_clause then if_clause.next_if_clause = v end if v.value ~= "if" then v.if_start = if_start end end end if tree_utils.is_block(node) then local block_start = node:first_leaf() local block_end = node:last_leaf() mark_block(node, block_start, block_end) end visit(self, node, visit) end return identify_containers_visitor
object_building_kashyyyk_poi_kash_rryatt_lvl2_bush_md = object_building_kashyyyk_shared_poi_kash_rryatt_lvl2_bush_md:new { } ObjectTemplates:addTemplate(object_building_kashyyyk_poi_kash_rryatt_lvl2_bush_md, "object/building/kashyyyk/poi_kash_rryatt_lvl2_bush_md.iff")
local skynet = require "skynet" local function inject(source) return skynet.call("check", "code", source) end return function () inject([[print "hello"]]) inject([[print(skynet)]]) inject([[ local bewater = require "bw.bewater" print(bewater.traceback()) ]]) inject([[print(check_list)]]) end
local Debug = require("Debug"); --[[ Test Cases --]] print("Debugger Present: ",Debug:isDebuggerPresent()); print(Debug:write("Hello World"));
require 'totem' require 'distributions' local myTest = {} local tester = totem.Tester() function myTest.chi2PDF() tester:assert(cephes.isinf(distributions.chi2.pdf(0, 1))) tester:assertalmosteq(distributions.chi2.pdf(1, 1), 0.241970724519143, 1e-15) tester:assertalmosteq(distributions.chi2.pdf(2, 1), 0.103776874355149, 1e-15) tester:assertalmosteq(distributions.chi2.pdf(5, 1), 0.014644982561926, 1e-15) tester:assertalmosteq(distributions.chi2.pdf(0, 9), 0 , 1e-15) tester:assertalmosteq(distributions.chi2.pdf(1, 9), 0.002304483090659, 1e-15) tester:assertalmosteq(distributions.chi2.pdf(2, 9), 0.015813618949356, 1e-15) tester:assertalmosteq(distributions.chi2.pdf(5, 9), 0.087172515249562, 1e-15) end function myTest.chi2LogPDF() tester:assertalmosteq(distributions.chi2.logpdf(1, 1),-1.418938533204673, 1e-15) tester:assertalmosteq(distributions.chi2.logpdf(2, 1),-2.265512123484645, 1e-15) tester:assertalmosteq(distributions.chi2.logpdf(5, 1),-4.223657489421723, 1e-15) tester:assertalmosteq(distributions.chi2.logpdf(1, 9),-6.072898883362196, 1e-15) tester:assertalmosteq(distributions.chi2.logpdf(2, 9),-4.146883751402387, 1e-15) tester:assertalmosteq(distributions.chi2.logpdf(5, 9),-2.439866189842844, 1e-15) end function myTest.chi2CDF() tester:assertalmosteq(distributions.chi2.cdf(0, 1), 0 , 1e-15) tester:assertalmosteq(distributions.chi2.cdf(1, 1), 0.682689492137086, 1e-15) tester:assertalmosteq(distributions.chi2.cdf(2, 1), 0.842700792949715, 1e-15) tester:assertalmosteq(distributions.chi2.cdf(5, 1), 0.974652681322532, 1e-15) tester:assertalmosteq(distributions.chi2.cdf(0, 9), 0 , 1e-15) tester:assertalmosteq(distributions.chi2.cdf(1, 9), 0.000562497302168, 1e-15) tester:assertalmosteq(distributions.chi2.cdf(2, 9), 0.008532393371186, 1e-15) tester:assertalmosteq(distributions.chi2.cdf(5, 9), 0.165691739806592, 1e-15) end tester:add(myTest) return tester:run()
local M = {} function M.lazy_require(require_path) return setmetatable({}, { __call = function(_, ...) return require(require_path)(...) end, __index = function(_, key) return require(require_path)[key] end, __newindex = function(_, key, value) require(require_path)[key] = value end, }) end function M.pop(tbl, key, default) local val = default if tbl[key] then val = tbl[key] tbl[key] = nil end return val end function M.crop(val, min, max) return math.min(math.max(min, val), max) end function M.zip(first, second) local new = {} for i, val in pairs(first) do new[i] = { val, second[i] } end return new end local function split_hex_colour(hex) hex = hex:gsub("#", "") return { tonumber(hex:sub(1, 2), 16), tonumber(hex:sub(3, 4), 16), tonumber(hex:sub(5, 6), 16) } end function M.blend(fg_hex, bg_hex, alpha) local channels = M.zip(split_hex_colour(fg_hex), split_hex_colour(bg_hex)) local blended = {} for i, i_chans in pairs(channels) do blended[i] = M.round(M.crop(alpha * i_chans[1] + (1 - alpha) * i_chans[2], 0, 255)) end return string.format("#%02x%02x%02x", unpack(blended)) end function M.round(num, decimals) if decimals then return tonumber(string.format("%." .. decimals .. "f", num)) end return math.floor(num + 0.5) end function M.partial(func, ...) local args = { ... } return function(...) local final = {} vim.list_extend(final, args) vim.list_extend(final, { ... }) return func(unpack(final)) end end function M.get_win_config(win) local success, conf = pcall(vim.api.nvim_win_get_config, win) if not success or not conf.row then return false, conf end for _, field in pairs({ "row", "col" }) do if type(conf[field]) == "table" then conf[field] = conf[field][false] end end return success, conf end function M.set_win_config(win, conf) for _, field in pairs({ "height", "width" }) do conf[field] = math.max(M.round(conf[field]), 1) end return (pcall(vim.api.nvim_win_set_config, win, conf)) end M.FIFOQueue = require("notify.util.queue") function M.rgb_to_numbers(s) local colours = {} for a in string.gmatch(s, "[A-Fa-f0-9][A-Fa-f0-9]") do colours[#colours + 1] = tonumber(a, 16) end return colours end function M.numbers_to_rgb(colours) local colour = "#" for _, num in pairs(colours) do colour = colour .. string.format("%X", num) end return colour end function M.deep_equal(t1, t2, ignore_mt) local ty1 = type(t1) local ty2 = type(t2) if ty1 ~= ty2 then return false end if ty1 ~= "table" then return t1 == t2 end local mt = getmetatable(t1) if not ignore_mt and mt and mt.__eq then return t1 == t2 end local checked for k1, v1 in pairs(t1) do local v2 = t2[k1] checked[k1] = true if v2 == nil or not M.deep_equal(v1, v2, ignore_mt) then return false end end for k2, _ in pairs(t2) do if not checked[k2] then return false end end return true end function M.update_configs(updates) for win, win_updates in pairs(updates) do local exists, conf = M.get_win_config(win) if exists then for _, field in pairs({ "row", "col", "height", "width" }) do conf[field] = win_updates[field] or conf[field] end M.set_win_config(win, conf) end end end function M.highlight(name, fields) local fields_string = "" for field, value in pairs(fields) do fields_string = fields_string .. " " .. field .. "=" .. value end if fields_string ~= "" then vim.cmd("hi " .. name .. fields_string) end end return M
----------------------------------------- -- ID: 4717 -- Scroll of Refresh -- Teaches the white magic Refresh ----------------------------------------- function onItemCheck(target) return target:canLearnSpell(109) end function onItemUse(target) target:addSpell(109) end
local pairs = pairs local ipairs = ipairs local lor = require("lor.index") local errorRouter = lor:Router() errorRouter:get("/", function(req, res, next) res:render("error", { msg = req.query.errMsg -- injected by the invoke request }) end) return errorRouter
-- Used for localization, choose either built-in or intllib. local MP, S, NS = nil if (minetest.get_modpath("intllib") == nil) then S = minetest.get_translator("castle_tapestries") else -- internationalization boilerplate MP = minetest.get_modpath(minetest.get_current_modname()) S, NS = dofile(MP.."/intllib.lua") end -- cottages support local use_cottages = minetest.get_modpath("cottages") local tapestry = {} minetest.register_alias("castle:tapestry_top", "castle_tapestries:tapestry_top") minetest.register_alias("castle:tapestry", "castle_tapestries:tapestry") minetest.register_alias("castle:tapestry_long", "castle_tapestries:tapestry_long") minetest.register_alias("castle:tapestry_very_long", "castle_tapestries:tapestry_very_long") minetest.register_node("castle_tapestries:tapestry_top", { drawtype = "nodebox", description = S("Tapestry Top"), tiles = {"default_wood.png"}, sunlight_propagates = true, groups = {flammable=3,oddly_breakable_by_hand=3}, sounds = default.node_sound_defaults(), paramtype = "light", paramtype2 = "facedir", node_box = { type = "fixed", fixed = { {-0.6,-0.5,0.375,0.6,-0.375,0.5}, }, }, selection_box = { type = "fixed", fixed = { {-0.6,-0.5,0.375,0.6,-0.375,0.5}, }, }, }) minetest.register_craft({ type = "shapeless", output = 'castle_tapestries:tapestry_top', recipe = {'default:stick'}, }) tapestry.colours = { "white", "grey", "black", "red", "yellow", "green", "cyan", "blue", "magenta", "orange", "violet", "dark_grey", "dark_green", "pink", "brown", } -- Regular-length tapestry minetest.register_node("castle_tapestries:tapestry", { drawtype = "mesh", mesh = "castle_tapestry.obj", description = S("Tapestry"), tiles = {"castle_tapestry.png"}, inventory_image = "castle_tapestry_inv.png", groups = {oddly_breakable_by_hand=3,flammable=3, ud_param2_colorable = 1}, sounds = default.node_sound_defaults(), paramtype = "light", paramtype2 = "colorwallmounted", palette = "unifieddyes_palette_colorwallmounted.png", selection_box = { type = "wallmounted", wall_side = {-0.5,-0.5,0.4375,0.5,1.5,0.5}, }, after_place_node = unifieddyes.fix_rotation_nsew, on_dig = unifieddyes.on_dig, on_rotate = unifieddyes.fix_after_screwdriver_nsew }) -- Long tapestry minetest.register_node("castle_tapestries:tapestry_long", { drawtype = "mesh", mesh = "castle_tapestry_long.obj", description = S("Tapestry (Long)"), tiles = {"castle_tapestry.png"}, inventory_image = "castle_tapestry_long_inv.png", groups = {oddly_breakable_by_hand=3,flammable=3, ud_param2_colorable = 1}, sounds = default.node_sound_defaults(), paramtype = "light", paramtype2 = "colorwallmounted", palette = "unifieddyes_palette_colorwallmounted.png", selection_box = { type = "wallmounted", wall_side = {-0.5,-0.5,0.4375,0.5,2.5,0.5}, }, after_place_node = unifieddyes.fix_rotation_nsew, on_dig = unifieddyes.on_dig, on_rotate = unifieddyes.fix_after_screwdriver_nsew }) -- Very long tapestry minetest.register_node("castle_tapestries:tapestry_very_long", { drawtype = "mesh", mesh = "castle_tapestry_very_long.obj", description = S("Tapestry (Very Long)"), tiles = {"castle_tapestry.png"}, inventory_image = "castle_tapestry_very_long_inv.png", groups = {oddly_breakable_by_hand=3,flammable=3, ud_param2_colorable = 1}, sounds = default.node_sound_defaults(), paramtype = "light", paramtype2 = "colorwallmounted", palette = "unifieddyes_palette_colorwallmounted.png", selection_box = { type = "wallmounted", wall_side = {-0.5,-0.5,0.4375,0.5,3.5,0.5}, }, after_place_node = unifieddyes.fix_rotation_nsew, on_dig = unifieddyes.on_dig, on_rotate = unifieddyes.fix_after_screwdriver_nsew }) -- Crafting minetest.register_craft({ type = "shapeless", output = 'castle_tapestries:tapestry', recipe = {'wool:white', 'default:stick'}, }) minetest.register_craft({ type = "shapeless", output = 'castle_tapestries:tapestry_long', recipe = {'wool:white', 'castle_tapestries:tapestry'}, }) minetest.register_craft({ type = "shapeless", output = 'castle_tapestries:tapestry_very_long', recipe = {'wool:white', 'castle_tapestries:tapestry_long'}, }) if use_cottages then minetest.register_craft({ type = "shapeless", output = 'castle_tapestries:tapestry', recipe = {'cottages:wool', 'default:stick'}, }) minetest.register_craft({ type = "shapeless", output = 'castle_tapestries:tapestry_long', recipe = {'cottages:wool', 'castle_tapestries:tapestry'}, }) minetest.register_craft({ type = "shapeless", output = 'castle_tapestries:tapestry_very_long', recipe = {'cottages:wool', 'castle_tapestries:tapestry_long'}, }) end unifieddyes.register_color_craft({ output = "castle_tapestries:tapestry", palette = "wallmounted", type = "shapeless", neutral_node = "castle_tapestries:tapestry", recipe = { "NEUTRAL_NODE", "MAIN_DYE", } }) unifieddyes.register_color_craft({ output = "castle_tapestries:tapestry_long", palette = "wallmounted", type = "shapeless", neutral_node = "castle_tapestries:tapestry_long", recipe = { "NEUTRAL_NODE", "MAIN_DYE", } }) unifieddyes.register_color_craft({ output = "castle_tapestries:tapestry_very_long", palette = "wallmounted", type = "shapeless", neutral_node = "castle_tapestries:tapestry_very_long", recipe = { "NEUTRAL_NODE", "MAIN_DYE", } }) -- Convert static tapestries to param2 color local old_static_tapestries = {} for _, color in ipairs(tapestry.colours) do table.insert(old_static_tapestries, "castle:tapestry_"..color) table.insert(old_static_tapestries, "castle:long_tapestry_"..color) table.insert(old_static_tapestries, "castle:very_long_tapestry_"..color) end minetest.register_lbm({ name = "castle_tapestries:convert_tapestries", label = "Convert tapestries to use param2 color", run_at_every_load = false, nodenames = old_static_tapestries, action = function(pos, node) local oldname = node.name local color = string.sub(oldname, string.find(oldname, "_", -12) + 1) if color == "red" then color = "medium_red" elseif color == "cyan" then color = "medium_cyan" elseif color == "blue" then color = "medium_blue" elseif color == "magenta" then color = "medium_magenta" end local paletteidx, _ = unifieddyes.getpaletteidx("unifieddyes:"..color, "wallmounted") local old_fdir = math.floor(node.param2 % 32) local new_fdir = 3 if old_fdir == 0 then new_fdir = 3 elseif old_fdir == 1 then new_fdir = 4 elseif old_fdir == 2 then new_fdir = 2 elseif old_fdir == 3 then new_fdir = 5 end local param2 = paletteidx + new_fdir local newname = "castle_tapestries:tapestry" if string.find(oldname, ":long") then newname = "castle_tapestries:tapestry_long" elseif string.find(oldname, ":very_long") then newname = "castle_tapestries:tapestry_very_long" end minetest.set_node(pos, { name = newname, param2 = param2 }) local meta = minetest.get_meta(pos) meta:set_string("dye", "unifieddyes:"..color) end })
--[[ MIT License Copyright (c) 2019 Eryn L. K. 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. --]] --[[ Repository: https://github.com/evaera/roblox-lua-promise - An implementation of Promises similar to Promise/A+ - Author: evaera - Modifications by Crazyman32 (December 29, 2019) Static Methods: Promise.new(callback) Promise.Async(callback) Promise.Resolve(...) Promise.Reject(...) Promise.Try(...) Promise.All(promises) Promise.Some(promises, amount) Promise.Any(promises) Promise.AllSettled(promises) Proimse.Race(promises) Promise.Is(object) Promise.Promisify(callback) Promise.Delay(seconds) Object Methods: promise:Timeout(seconds, timeoutValue) promise:GetStatus() promise:Then(successHandler, failureHandler) promise:Catch(failureCallback) promise:Tap(tapCallback) promise:ThenCall(callback, ...) promise:ThenReturn(...) promise:Cancel() promise:Destroy() promise:Finally(finallyHandler) promise:FinallyCall(callback, ...) promise:FinallyReturn(...) promise:Done(finallyHandler) promise:DoneCall(callback, ...) promise:DoneReturn(...) promise:AwaitStatus() promise:Await() promise:Expect(...) promise:AwaitValue(...) --]] local ERROR_YIELD_NEW = "Yielding inside Promise.new is not allowed! Use Promise.async or create a new thread in the Promise executor!" local ERROR_YIELD_THEN = "Yielding inside andThen/catch is not allowed! Instead, return a new Promise from andThen/catch." local ERROR_NON_PROMISE_IN_LIST = "Non-promise value passed into %s at index %s" local ERROR_NON_LIST = "Please pass a list of promises to %s" local ERROR_NON_FUNCTION = "Please pass a handler function to %s!" local RunService = game:GetService("RunService") --[[ Packs a number of arguments into a table and returns its length. Used to cajole varargs without dropping sparse values. ]] local function pack(...) local len = select("#", ...) return len, { ... } end --[[ Returns first value (success), and packs all following values. ]] local function packResult(...) local result = (...) return result, pack(select(2, ...)) end --[[ Calls a non-yielding function in a new coroutine. Handles errors if they happen. ]] local function ppcall(yieldError, callback, ...) -- Wrapped because C functions can't be passed to coroutine.create! local co = coroutine.create(function(...) return callback(...) end) local ok, len, result = packResult(coroutine.resume(co, ...)) if ok and coroutine.status(co) ~= "dead" then error(yieldError, 2) end return ok, len, result end --[[ Creates a function that invokes a callback with correct error handling and resolution mechanisms. ]] local function createAdvancer(traceback, callback, resolve, reject) return function(...) local ok, resultLength, result = ppcall(ERROR_YIELD_THEN, callback, ...) if ok then resolve(unpack(result, 1, resultLength)) else reject(result[1] .. "\n" .. traceback) end end end local function isEmpty(t) return next(t) == nil end local Promise = {} Promise.prototype = {} Promise.__index = Promise.prototype Promise.Status = setmetatable({ Started = "Started", Resolved = "Resolved", Rejected = "Rejected", Cancelled = "Cancelled", }, { __index = function(_, k) error(("%s is not in Promise.Status!"):format(k), 2) end }) --[[ Constructs a new Promise with the given initializing callback. This is generally only called when directly wrapping a non-promise API into a promise-based version. The callback will receive 'resolve' and 'reject' methods, used to start invoking the promise chain. Second parameter, parent, is used internally for tracking the "parent" in a promise chain. External code shouldn't need to worry about this. ]] function Promise.new(callback, parent) if parent ~= nil and not Promise.is(parent) then error("Argument #2 to Promise.new must be a promise or nil", 2) end local self = { -- Used to locate where a promise was created _source = debug.traceback(), _status = Promise.Status.Started, -- Will be set to the Lua error string if it occurs while executing. _error = nil, -- A table containing a list of all results, whether success or failure. -- Only valid if _status is set to something besides Started _values = nil, -- Lua doesn't like sparse arrays very much, so we explicitly store the -- length of _values to handle middle nils. _valuesLength = -1, -- Tracks if this Promise has no error observers.. _unhandledRejection = true, -- Queues representing functions we should invoke when we update! _queuedResolve = {}, _queuedReject = {}, _queuedFinally = {}, -- The function to run when/if this promise is cancelled. _cancellationHook = nil, -- The "parent" of this promise in a promise chain. Required for -- cancellation propagation. _parent = parent, _consumers = setmetatable({}, { __mode = "k"; }), } if parent and parent._status == Promise.Status.Started then parent._consumers[self] = true end setmetatable(self, Promise) local function resolve(...) self:_resolve(...) end local function reject(...) self:_reject(...) end local function onCancel(cancellationHook) if cancellationHook then if self._status == Promise.Status.Cancelled then cancellationHook() else self._cancellationHook = cancellationHook end end return self._status == Promise.Status.Cancelled end local ok, _, result = ppcall( ERROR_YIELD_NEW, callback, resolve, reject, onCancel ) if not ok then self._error = result[1] or "error" reject((result[1] or "error") .. "\n" .. self._source) end return self end function Promise._newWithSelf(executor, ...) local args local promise = Promise.new(function(...) args = {...} end, ...) executor(promise, unpack(args)) return promise end function Promise._new(traceback, executor, ...) return Promise._newWithSelf(function(self, ...) self._source = traceback executor(...) end, ...) end --[[ Promise.new, except pcall on a new thread is automatic. ]] function Promise.async(callback) local traceback = debug.traceback() local promise promise = Promise.new(function(resolve, reject, onCancel) local connection connection = RunService.Heartbeat:Connect(function() connection:Disconnect() local ok, err = pcall(callback, resolve, reject, onCancel) if not ok then promise._error = err or "error" reject(err .. "\n" .. traceback) end end) end) return promise end Promise.Async = Promise.async --[[ Create a promise that represents the immediately resolved value. ]] function Promise.resolve(...) local length, values = pack(...) return Promise.new(function(resolve) resolve(unpack(values, 1, length)) end) end Promise.Resolve = Promise.resolve --[[ Create a promise that represents the immediately rejected value. ]] function Promise.reject(...) local length, values = pack(...) return Promise.new(function(_, reject) reject(unpack(values, 1, length)) end) end Promise.Reject = Promise.reject --[[ Begins a Promise chain, turning synchronous errors into rejections. ]] function Promise.try(...) return Promise.resolve():andThenCall(...) end Promise.Try = Promise.try --[[ Returns a new promise that: * is resolved when all input promises resolve * is rejected if ANY input promises reject ]] function Promise._all(traceback, promises, amount) if type(promises) ~= "table" then error(ERROR_NON_LIST:format("Promise.all"), 3) end -- We need to check that each value is a promise here so that we can produce -- a proper error rather than a rejected promise with our error. for i, promise in pairs(promises) do if not Promise.is(promise) then error((ERROR_NON_PROMISE_IN_LIST):format("Promise.all", tostring(i)), 3) end end -- If there are no values then return an already resolved promise. if #promises == 0 or amount == 0 then return Promise.resolve({}) end return Promise._newWithSelf(function(self, resolve, reject, onCancel) self._source = traceback -- An array to contain our resolved values from the given promises. local resolvedValues = {} local newPromises = {} -- Keep a count of resolved promises because just checking the resolved -- values length wouldn't account for promises that resolve with nil. local resolvedCount = 0 local rejectedCount = 0 local done = false local function cancel() for _, promise in ipairs(newPromises) do promise:cancel() end end -- Called when a single value is resolved and resolves if all are done. local function resolveOne(i, ...) if done then return end resolvedCount = resolvedCount + 1 if amount == nil then resolvedValues[i] = ... else resolvedValues[resolvedCount] = ... end if resolvedCount >= (amount or #promises) then done = true resolve(resolvedValues) cancel() end end onCancel(cancel) -- We can assume the values inside `promises` are all promises since we -- checked above. for i = 1, #promises do table.insert( newPromises, promises[i]:andThen( function(...) resolveOne(i, ...) end, function(...) rejectedCount = rejectedCount + 1 if amount == nil or #promises - rejectedCount < amount then cancel() done = true reject(...) end end ) ) end if done then cancel() end end) end function Promise.all(promises) return Promise._all(debug.traceback(), promises) end Promise.All = Promise.all function Promise.some(promises, amount) assert(type(amount) == "number", "Bad argument #2 to Promise.some: must be a number") return Promise._all(debug.traceback(), promises, amount) end Promise.Some = Promise.some function Promise.any(promises) return Promise._all(debug.traceback(), promises, 1):andThen(function(values) return values[1] end) end Promise.Any = Promise.any function Promise.allSettled(promises) if type(promises) ~= "table" then error(ERROR_NON_LIST:format("Promise.allSettled"), 2) end -- We need to check that each value is a promise here so that we can produce -- a proper error rather than a rejected promise with our error. for i, promise in pairs(promises) do if not Promise.is(promise) then error((ERROR_NON_PROMISE_IN_LIST):format("Promise.allSettled", tostring(i)), 2) end end -- If there are no values then return an already resolved promise. if #promises == 0 then return Promise.resolve({}) end return Promise.new(function(resolve, _, onCancel) -- An array to contain our resolved values from the given promises. local fates = {} local newPromises = {} -- Keep a count of resolved promises because just checking the resolved -- values length wouldn't account for promises that resolve with nil. local finishedCount = 0 -- Called when a single value is resolved and resolves if all are done. local function resolveOne(i, ...) finishedCount = finishedCount + 1 fates[i] = ... if finishedCount >= #promises then resolve(fates) end end onCancel(function() for _, promise in ipairs(newPromises) do promise:cancel() end end) -- We can assume the values inside `promises` are all promises since we -- checked above. for i = 1, #promises do table.insert( newPromises, promises[i]:finally( function(...) resolveOne(i, ...) end ) ) end end) end Promise.AllSettled = Promise.allSettled --[[ Races a set of Promises and returns the first one that resolves, cancelling the others. ]] function Promise.race(promises) assert(type(promises) == "table", ERROR_NON_LIST:format("Promise.race")) for i, promise in pairs(promises) do assert(Promise.is(promise), (ERROR_NON_PROMISE_IN_LIST):format("Promise.race", tostring(i))) end return Promise.new(function(resolve, reject, onCancel) local newPromises = {} local finished = false local function cancel() for _, promise in ipairs(newPromises) do promise:cancel() end end local function finalize(callback) return function (...) cancel() finished = true return callback(...) end end if onCancel(finalize(reject)) then return end for _, promise in ipairs(promises) do table.insert( newPromises, promise:andThen(finalize(resolve), finalize(reject)) ) end if finished then cancel() end end) end Promise.Race = Promise.race --[[ Is the given object a Promise instance? ]] function Promise.is(object) if type(object) ~= "table" then return false end return type(object.andThen) == "function" end Promise.Is = Promise.is --[[ Converts a yielding function into a Promise-returning one. ]] function Promise.promisify(callback) return function(...) local traceback = debug.traceback() local length, values = pack(...) return Promise.new(function(resolve, reject) coroutine.wrap(function() local ok, resultLength, resultValues = packResult(pcall(callback, unpack(values, 1, length))) if ok then resolve(unpack(resultValues, 1, resultLength)) else reject((resultValues[1] or "error") .. "\n" .. traceback) end end)() end) end end Promise.Promisify = Promise.promisify --[[ Creates a Promise that resolves after given number of seconds. ]] do local connection local queue = {} local function enqueue(callback, seconds) table.insert(queue, { callback = callback, startTime = tick(), endTime = tick() + math.max(seconds, 1/60) }) table.sort(queue, function(a, b) return a.endTime < b.endTime end) if not connection then connection = RunService.Heartbeat:Connect(function() while #queue > 0 and queue[1].endTime <= tick() do local item = table.remove(queue, 1) item.callback(tick() - item.startTime) end if #queue == 0 then connection:Disconnect() connection = nil end end) end end local function dequeue(callback) for i, item in ipairs(queue) do if item.callback == callback then table.remove(queue, i) break end end end function Promise.delay(seconds) assert(type(seconds) == "number", "Bad argument #1 to Promise.delay, must be a number.") -- If seconds is -INF, INF, or NaN, assume seconds is 0. -- This mirrors the behavior of wait() if seconds < 0 or seconds == math.huge or seconds ~= seconds then seconds = 0 end return Promise.new(function(resolve, _, onCancel) enqueue(resolve, seconds) onCancel(function() dequeue(resolve) end) end) end Promise.Delay = Promise.delay end --[[ Rejects the promise after `seconds` seconds. ]] function Promise.prototype:timeout(seconds, timeoutValue) return Promise.race({ Promise.delay(seconds):andThen(function() return Promise.reject(timeoutValue == nil and "Timed out" or timeoutValue) end), self }) end Promise.prototype.Timeout = Promise.prototype.timeout function Promise.prototype:getStatus() return self._status end Promise.prototype.GetStatus = Promise.prototype.getStatus --[[ Creates a new promise that receives the result of this promise. The given callbacks are invoked depending on that result. ]] function Promise.prototype:_andThen(traceback, successHandler, failureHandler) self._unhandledRejection = false -- Create a new promise to follow this part of the chain return Promise._new(traceback, function(resolve, reject) -- Our default callbacks just pass values onto the next promise. -- This lets success and failure cascade correctly! local successCallback = resolve if successHandler then successCallback = createAdvancer( traceback, successHandler, resolve, reject ) end local failureCallback = reject if failureHandler then failureCallback = createAdvancer( traceback, failureHandler, resolve, reject ) end if self._status == Promise.Status.Started then -- If we haven't resolved yet, put ourselves into the queue table.insert(self._queuedResolve, successCallback) table.insert(self._queuedReject, failureCallback) elseif self._status == Promise.Status.Resolved then -- This promise has already resolved! Trigger success immediately. successCallback(unpack(self._values, 1, self._valuesLength)) elseif self._status == Promise.Status.Rejected then -- This promise died a terrible death! Trigger failure immediately. failureCallback(unpack(self._values, 1, self._valuesLength)) elseif self._status == Promise.Status.Cancelled then -- We don't want to call the success handler or the failure handler, -- we just reject this promise outright. reject("Promise is cancelled") end end, self) end function Promise.prototype:andThen(successHandler, failureHandler) assert( successHandler == nil or type(successHandler) == "function", ERROR_NON_FUNCTION:format("Promise:andThen") ) assert( failureHandler == nil or type(failureHandler) == "function", ERROR_NON_FUNCTION:format("Promise:andThen") ) return self:_andThen(debug.traceback(), successHandler, failureHandler) end Promise.prototype.AndThen = Promise.prototype.andThen Promise.prototype.Then = Promise.prototype.andThen --[[ Used to catch any errors that may have occurred in the promise. ]] function Promise.prototype:catch(failureCallback) assert( failureCallback == nil or type(failureCallback) == "function", ERROR_NON_FUNCTION:format("Promise:catch") ) return self:_andThen(debug.traceback(), nil, failureCallback) end Promise.prototype.Catch = Promise.prototype.catch --[[ Like andThen, but the value passed into the handler is also the value returned from the handler. ]] function Promise.prototype:tap(tapCallback) assert(type(tapCallback) == "function", ERROR_NON_FUNCTION:format("Promise:tap")) return self:_andThen(debug.traceback(), function(...) local callbackReturn = tapCallback(...) if Promise.is(callbackReturn) then local length, values = pack(...) return callbackReturn:andThen(function() return unpack(values, 1, length) end) end return ... end) end Promise.prototype.Tap = Promise.prototype.tap --[[ Calls a callback on `andThen` with specific arguments. ]] function Promise.prototype:andThenCall(callback, ...) assert(type(callback) == "function", ERROR_NON_FUNCTION:format("Promise:andThenCall")) local length, values = pack(...) return self:_andThen(debug.traceback(), function() return callback(unpack(values, 1, length)) end) end Promise.prototype.AndThenCall = Promise.prototype.andThenCall Promise.prototype.ThenCall = Promise.prototype.andThenCall --[[ Shorthand for an andThen handler that returns the given value. ]] function Promise.prototype:andThenReturn(...) local length, values = pack(...) return self:_andThen(debug.traceback(), function() return unpack(values, 1, length) end) end Promise.prototype.AndThenReturn = Promise.prototype.andThenReturn Promise.prototype.ThenReturn = Promise.prototype.andThenReturn --[[ Cancels the promise, disallowing it from rejecting or resolving, and calls the cancellation hook if provided. ]] function Promise.prototype:cancel() if self._status ~= Promise.Status.Started then return end self._status = Promise.Status.Cancelled if self._cancellationHook then self._cancellationHook() end if self._parent then self._parent:_consumerCancelled(self) end for child in pairs(self._consumers) do child:cancel() end self:_finalize() end Promise.prototype.Cancel = Promise.prototype.cancel Promise.prototype.Destroy = Promise.prototype.cancel --[[ Used to decrease the number of consumers by 1, and if there are no more, cancel this promise. ]] function Promise.prototype:_consumerCancelled(consumer) if self._status ~= Promise.Status.Started then return end self._consumers[consumer] = nil if next(self._consumers) == nil then self:cancel() end end --[[ Used to set a handler for when the promise resolves, rejects, or is cancelled. Returns a new promise chained from this promise. ]] function Promise.prototype:_finally(traceback, finallyHandler, onlyOk) if not onlyOk then self._unhandledRejection = false end -- Return a promise chained off of this promise return Promise._new(traceback, function(resolve, reject) local finallyCallback = resolve if finallyHandler then finallyCallback = createAdvancer( traceback, finallyHandler, resolve, reject ) end if onlyOk then local callback = finallyCallback finallyCallback = function(...) if self._status == Promise.Status.Rejected then return resolve(self) end return callback(...) end end if self._status == Promise.Status.Started then -- The promise is not settled, so queue this. table.insert(self._queuedFinally, finallyCallback) else -- The promise already settled or was cancelled, run the callback now. finallyCallback(self._status) end end, self) end function Promise.prototype:finally(finallyHandler) assert( finallyHandler == nil or type(finallyHandler) == "function", ERROR_NON_FUNCTION:format("Promise:finally") ) return self:_finally(debug.traceback(), finallyHandler) end Promise.prototype.Finally = Promise.prototype.finally --[[ Calls a callback on `finally` with specific arguments. ]] function Promise.prototype:finallyCall(callback, ...) assert(type(callback) == "function", ERROR_NON_FUNCTION:format("Promise:finallyCall")) local length, values = pack(...) return self:_finally(debug.traceback(), function() return callback(unpack(values, 1, length)) end) end Promise.prototype.FinallyCall = Promise.prototype.finallyCall --[[ Shorthand for a finally handler that returns the given value. ]] function Promise.prototype:finallyReturn(...) local length, values = pack(...) return self:_finally(debug.traceback(), function() return unpack(values, 1, length) end) end Promise.prototype.FinallyReturn = Promise.prototype.finallyReturn --[[ Similar to finally, except rejections are propagated through it. ]] function Promise.prototype:done(finallyHandler) assert( finallyHandler == nil or type(finallyHandler) == "function", ERROR_NON_FUNCTION:format("Promise:finallyO") ) return self:_finally(debug.traceback(), finallyHandler, true) end Promise.prototype.Done = Promise.prototype.done --[[ Calls a callback on `done` with specific arguments. ]] function Promise.prototype:doneCall(callback, ...) assert(type(callback) == "function", ERROR_NON_FUNCTION:format("Promise:doneCall")) local length, values = pack(...) return self:_finally(debug.traceback(), function() return callback(unpack(values, 1, length)) end, true) end Promise.prototype.DoneCall = Promise.prototype.doneCall --[[ Shorthand for a done handler that returns the given value. ]] function Promise.prototype:doneReturn(...) local length, values = pack(...) return self:_finally(debug.traceback(), function() return unpack(values, 1, length) end, true) end Promise.prototype.DoneReturn = Promise.prototype.doneReturn --[[ Yield until the promise is completed. This matches the execution model of normal Roblox functions. ]] function Promise.prototype:awaitStatus() self._unhandledRejection = false if self._status == Promise.Status.Started then local bindable = Instance.new("BindableEvent") self:finally(function() bindable:Fire() end) bindable.Event:Wait() bindable:Destroy() end if self._status == Promise.Status.Resolved then return self._status, unpack(self._values, 1, self._valuesLength) elseif self._status == Promise.Status.Rejected then return self._status, unpack(self._values, 1, self._valuesLength) end return self._status end Promise.prototype.AwaitStatus = Promise.prototype.awaitStatus --[[ Calls awaitStatus internally, returns (isResolved, values...) ]] function Promise.prototype:await(...) local length, result = pack(self:awaitStatus(...)) local status = table.remove(result, 1) return status == Promise.Status.Resolved, unpack(result, 1, length - 1) end Promise.prototype.Await = Promise.prototype.await --[[ Calls await and only returns if the Promise resolves. Throws if the Promise rejects or gets cancelled. ]] function Promise.prototype:expect(...) local length, result = pack(self:awaitStatus(...)) local status = table.remove(result, 1) assert( status == Promise.Status.Resolved, tostring(result[1] == nil and "" or result[1]) ) return unpack(result, 1, length - 1) end Promise.prototype.Expect = Promise.prototype.expect Promise.prototype.awaitValue = Promise.prototype.expect Promise.prototype.AwaitValue = Promise.prototype.expect --[[ Intended for use in tests. Similar to await(), but instead of yielding if the promise is unresolved, _unwrap will throw. This indicates an assumption that a promise has resolved. ]] function Promise.prototype:_unwrap() if self._status == Promise.Status.Started then error("Promise has not resolved or rejected.", 2) end local success = self._status == Promise.Status.Resolved return success, unpack(self._values, 1, self._valuesLength) end function Promise.prototype:_resolve(...) if self._status ~= Promise.Status.Started then if Promise.is((...)) then (...):_consumerCancelled(self) end return end -- If the resolved value was a Promise, we chain onto it! if Promise.is((...)) then -- Without this warning, arguments sometimes mysteriously disappear if select("#", ...) > 1 then local message = ( "When returning a Promise from andThen, extra arguments are " .. "discarded! See:\n\n%s" ):format( self._source ) warn(message) end local chainedPromise = ... local promise = chainedPromise:andThen( function(...) self:_resolve(...) end, function(...) -- The handler errored. Replace the inner stack trace with our outer stack trace. if chainedPromise._error then return self:_reject((chainedPromise._error or "") .. "\n" .. self._source) end self:_reject(...) end ) if promise._status == Promise.Status.Cancelled then self:cancel() elseif promise._status == Promise.Status.Started then -- Adopt ourselves into promise for cancellation propagation. self._parent = promise promise._consumers[self] = true end return end self._status = Promise.Status.Resolved self._valuesLength, self._values = pack(...) -- We assume that these callbacks will not throw errors. for _, callback in ipairs(self._queuedResolve) do callback(...) end self:_finalize() end function Promise.prototype:_reject(...) if self._status ~= Promise.Status.Started then return end self._status = Promise.Status.Rejected self._valuesLength, self._values = pack(...) -- If there are any rejection handlers, call those! if not isEmpty(self._queuedReject) then -- We assume that these callbacks will not throw errors. for _, callback in ipairs(self._queuedReject) do callback(...) end else -- At this point, no one was able to observe the error. -- An error handler might still be attached if the error occurred -- synchronously. We'll wait one tick, and if there are still no -- observers, then we should put a message in the console. local err = tostring((...)) coroutine.wrap(function() RunService.Heartbeat:Wait() -- Someone observed the error, hooray! if not self._unhandledRejection then return end -- Build a reasonable message local message if self._error then message = ("Unhandled promise rejection:\n\n%s"):format(err) else message = ("Unhandled promise rejection:\n\n%s\n\n%s"):format( err, self._source ) end warn(message) end)() end self:_finalize() end --[[ Calls any :finally handlers. We need this to be a separate method and queue because we must call all of the finally callbacks upon a success, failure, *and* cancellation. ]] function Promise.prototype:_finalize() for _, callback in ipairs(self._queuedFinally) do -- Purposefully not passing values to callbacks here, as it could be the -- resolved values, or rejected errors. If the developer needs the values, -- they should use :andThen or :catch explicitly. callback(self._status) end if self._parent and self._error == nil then self._error = self._parent._error end -- Allow family to be buried if not Promise.TEST then self._parent = nil self._consumers = nil end end return Promise
local E, L, V, P, G = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, GlobalDB local S = E:GetModule('Skins') --Lua functions local _G = _G local unpack = unpack --WoW API / Variables local CreateFrame = CreateFrame local function PetButtons(btn, p) local button = _G[btn] local icon = _G[btn..'IconTexture'] local highlight = button:GetHighlightTexture() button:StripTextures() if button.Checked then button.Checked:SetColorTexture(unpack(E.media.rgbvaluecolor)) button.Checked:SetAllPoints(icon) button.Checked:SetAlpha(0.3) end if highlight then highlight:SetColorTexture(1, 1, 1, 0.3) highlight:SetAllPoints(icon) end if icon then icon:SetTexCoord(unpack(E.TexCoords)) icon:ClearAllPoints() icon:Point("TOPLEFT", p, -p) icon:Point("BOTTOMRIGHT", -p, p) button:SetFrameLevel(button:GetFrameLevel() + 2) if not button.backdrop then button:CreateBackdrop(nil, true) button.backdrop:SetAllPoints() end end end local function LoadSkin() if E.private.skins.blizzard.enable ~= true or E.private.skins.blizzard.stable ~= true then return end local PetStableFrame = _G.PetStableFrame S:HandlePortraitFrame(PetStableFrame, true) _G.PetStableLeftInset:StripTextures() _G.PetStableBottomInset:StripTextures() _G.PetStableFrameInset:SetTemplate('Transparent') S:HandleButton(_G.PetStablePrevPageButton) -- Required to remove graphical glitch from Prev page button S:HandleButton(_G.PetStableNextPageButton) -- Required to remove graphical glitch from Next page button S:HandleRotateButton(_G.PetStableModelRotateRightButton) S:HandleRotateButton(_G.PetStableModelRotateLeftButton) local p = E.PixelMode and 1 or 2 local PetStableSelectedPetIcon = _G.PetStableSelectedPetIcon if PetStableSelectedPetIcon then PetStableSelectedPetIcon:SetTexCoord(unpack(E.TexCoords)) local b = CreateFrame("Frame", nil, PetStableSelectedPetIcon:GetParent()) b:Point("TOPLEFT", PetStableSelectedPetIcon, -p, p) b:Point("BOTTOMRIGHT", PetStableSelectedPetIcon, p, -p) PetStableSelectedPetIcon:Size(37,37) PetStableSelectedPetIcon:SetParent(b) b:SetTemplate() end for i = 1, _G.NUM_PET_ACTIVE_SLOTS do PetButtons('PetStableActivePet' .. i, p) end for i = 1, _G.NUM_PET_STABLE_SLOTS do PetButtons('PetStableStabledPet' .. i, p) end end S:AddCallback("Stable", LoadSkin)
--[[ Licensed under GNU General Public License v2 * (c) 2013, Luke Bonham --]] local newtimer = require("lain.helpers").newtimer local wibox = require("wibox") local io = { open = io.open } local tonumber = tonumber local setmetatable = setmetatable -- coretemp -- lain.widgets.temp local temp = {} local function worker(args) local args = args or {} local timeout = args.timeout or 5 local tempfile = args.tempfile or "/sys/class/thermal/thermal_zone0/temp" local settings = args.settings or function() end temp.widget = wibox.widget.textbox('') function update() local f = io.open(tempfile) if f ~= nil then coretemp_now = tonumber(f:read("*a")) / 1000 f:close() else coretemp_now = "N/A" end widget = temp.widget settings() end newtimer("coretemp", timeout, update) return temp.widget end return setmetatable(temp, { __call = function(_, ...) return worker(...) end })
if true then print("Executed") end if part.Transparency == 1 then part.CanCollide = true end local humanoid = char.Humanoid if humanoid.Health > 0 then print("Player is alive!") end if not part.Anchored then part.Material = Enum.Material.Neon end local item1 = "Fruit" local item2 = "Vegetable" if item1 == "Fruit" and item2 == "Fruit" then print("Both fruit.") --No output as requirements not met. end local item = "Vegetable" if item == "Fruit" or item == "Vegetable" then print("Is produce.") --Prints as one requirement is met. end if myInstance:IsA("BasePart") then print(myInstance.Name.. "'s transparency is ".. myInstance.Transparency) end local heavy = true local strengthRequired = 0 if heavy then strengthRequired = 100 else strengthRequired = 50 end print(strengthRequired) local numFruits = 0 local numVeggies = 0 local notProduce = 0 local item = "Fruit" if item == "Fruit" then numFruits = numFruits + 1 elseif item == "Vegetable" then numVeggies = numVeggies + 1 else notProduce = notProduce + 1 end local isAnchored = Part.Anchored and "Anchored" or "Unanchored"
local ipmatcher = require "resty.ipmatcher" local ngx = ngx local kong = kong local error = error local IpRestrictionHandler = { PRIORITY = 990, VERSION = "2.0.0", } local function match_bin(list, binary_remote_addr) local ip, err = ipmatcher.new(list) if err then return error("failed to create a new ipmatcher instance: " .. err) end local is_match is_match, err = ip:match_bin(binary_remote_addr) if err then return error("invalid binary ip address: " .. err) end return is_match end function IpRestrictionHandler:access(conf) local binary_remote_addr = ngx.var.binary_remote_addr if not binary_remote_addr then return kong.response.error(403, "Cannot identify the client IP address, unix domain sockets are not supported.") end local status = conf.status or 403 local message = conf.message or "Your IP address is not allowed" if conf.deny and #conf.deny > 0 then local blocked = match_bin(conf.deny, binary_remote_addr) if blocked then return kong.response.error(status, message) end end if conf.allow and #conf.allow > 0 then local allowed = match_bin(conf.allow, binary_remote_addr) if not allowed then return kong.response.error(status, message) end end end return IpRestrictionHandler
ys = ys or {} slot1 = class("BattleBuffAddAttrRatio", ys.Battle.BattleBuffAddAttr) ys.Battle.BattleBuffAddAttrRatio = slot1 slot1.__name = "BattleBuffAddAttrRatio" slot1.Ctor = function (slot0, slot1) slot0.super.Ctor(slot0, slot1) end slot1.GetEffectType = function (slot0) return slot0.Battle.BattleBuffEffect.FX_TYPE_MOD_ATTR end slot1.SetArgs = function (slot0, slot1, slot2) slot0._group = slot0._tempData.arg_list.group or slot2:GetID() slot0._attr = slot0._tempData.arg_list.attr slot0._attrBound = slot0._tempData.arg_list.attrBound slot5 = slot0._tempData.arg_list.gurantee or 0 slot0._number = slot0._tempData.arg_list.number * slot0.Battle.BattleAttr.GetBase(slot1, slot0._tempData.arg_list.convertAttr or slot0._attr) * 0.0001 slot0._numberBase = slot0._number if slot0._attrBound then slot0._numberBase = math.min(slot0._numberBase, slot0._attrBound) end end return
require('nvim-ts-autotag').setup()
require("Menu/MainMenu/mainMenuStyle.lua") require("Game/mapInfo.lua") require("Menu/MainMenu/mapInformation.lua") require("Menu/MainMenu/settingsCombobox.lua") CustomeGameMenu = {} function CustomeGameMenu.new(panel) local self = {} --this = SceneNode() local mapTable = {} local levelInfo = MapInfo.new() --local mapInfoTable = nil local curentDirectory = "Map" -- local selectedFile = "" local selectedMapButton --GUI local mainPanel local iconImage local mapLabel local difficutyBox local gameModeBox local mapListPanel local diffNames = {} local labels = {} --Select local gameModes = {"default", "survival", "rush", "training", "leveler"} local menuPrevSelect --menuPrevSelect=Config() local files function self.languageChanged() for i=1, #labels do labels[i]:setText(language:getText(labels[i]:getTag())) end difficutyBox.updateLanguage() gameModeBox.updateLanguage() end local function splitString(str,sep) local array = {} local reg = string.format("([^%s]+)",sep) for mem in string.gmatch(str,reg) do table.insert(array, mem) end return array end local function setDefaultButtonColor(button,num) local set = false if num then set = num%2==0 else set = tonumber(string.match(button:getTag():toString(),"(.*):"))%2==0 end if set then button:setEdgeColor(Vec4(1,1,1,0.05), Vec4(1,1,1,0.05)) button:setInnerColor(Vec4(1,1,1,0.05), Vec4(1,1,1,0.05), Vec4(1,1,1,0.05)) else button:setEdgeColor(Vec4(0), Vec4(0)) button:setInnerColor(Vec4(0), Vec4(0), Vec4(0)) end end local function setSelectedButtonColor(button) selectedNum = button button:setEdgeColor(Vec4(1,1,1,0.25), Vec4(1,1,1,0.25)) button:setInnerColor(Vec4(1,1,1,0.25), Vec4(1,1,1,0.25), Vec4(1,1,1,0.25)) end local function mapInfoLoaded() local mapFolder = Core.getDataFolder(curentDirectory) for i=1, #files do local file = files[i].file --file = File() local panels = mapTable[file:getPath()] local mapInfoItem = MapInformation.getMapInfoFromFileName(file:getName(), file:getPath()) print("Update "..file:getPath().." found "..(panels and "Panels" or "nil").." and "..(mapInfoItem and "mapInfoItem" or "nil").."\n") if panels and mapInfoItem then panels.gameMode:setText(mapInfoItem.gameMode) end end end function self.changedVisibility(panel) MapInformation.setMapInfoLoadedFunction(mapInfoLoaded) end local function changeDifficulty(tag, index) if difficutyBox.isEnabled()==true then --set difficulty levelInfo.setLevel(index) -- menuPrevSelect:get("custom"):get("selectedDifficulty"):setInt(index) -- difficutyBox.setIndex(index) end end local function updateWaveCount() --force game mode update local activeGameMode = gameModeBox and gameModeBox.getIndexText() or "" -- print("updateWaveCount("..levelInfo.getGameMode()..")") for i=1, #files do if files[i].waveCountLabel then local file = files[i].file local filePath = file:getPath() local mapInfoItem = MapInformation.getMapInfoFromFileName(file:getName(), file:getPath()) if activeGameMode=="survival" then files[i].waveCountLabel:setText( mapInfoItem and "100" or "" ) else files[i].waveCountLabel:setText( mapInfoItem and tostring(mapInfoItem.waveCount) or "" ) end end end end local function changeGameMode(tag, index) print("changeGameMode("..gameModes[index]..")") --set game mode levelInfo.setGameMode(gameModes[index]) -- gameModeBox.setIndex(index) -- if levelInfo.getGameMode()=="survival" or levelInfo.getGameMode()=="rush" then changeDifficulty("",2) difficutyBox.setEnabled(false) else difficutyBox.setEnabled(true) end updateWaveCount() menuPrevSelect:get("custom"):get("selectedGameMode"):setInt(index) end local function startMap(button) local mapFile = File(selectedFile) levelInfo.setIsCampaign(false) levelInfo.setMapFileName(selectedFile) levelInfo.setMapName(mapFile:getName()) levelInfo.setGameMode(gameModeBox.getIndexText()) if mapFile:isFile() then local mapInfo = MapInformation.getMapInfoFromFileName(mapFile:getName(), mapFile:getPath()) levelInfo.setIsCartMap(mapInfo and mapInfo.gameMode=="Cart" or false) levelInfo.setWaveCount(mapInfo and mapInfo.waveCount or 25) levelInfo.setPlayerCount(mapInfo and mapInfo.players or 1) if mapInfo then levelInfo.setChangedDifficultyMax(mapInfo.difficultyIncreaseMax) levelInfo.setChangedDifficultyMin(mapInfo.difficultyIncreaseMin) end levelInfo.setLevel(difficutyBox.getIndex()) end -- menuPrevSelect:save() -- Core.startMap(selectedFile) local worker = Worker("Menu/loadingScreen.lua", true) worker:start() end local function addMapInfoPanel(panel) local infoPanel = panel:add(Panel(PanelSize(Vec2(-1, -1)))) infoPanel:setLayout(FallLayout(Alignment.TOP_CENTER, PanelSize(Vec2(0,0.005)))) infoPanel:setPadding(BorderSize(Vec4(0.005),true)) infoPanel:setBackground(Gradient(Vec4(0,0,0,0.9), Vec4(0,0,0,0.9))) iconImage = infoPanel:add(Image(PanelSize(Vec2(-1), Vec2(1)), Text("noImage"))) iconImage:setBorder(Border( BorderSize(Vec4(MainMenuStyle.borderSize)), MainMenuStyle.borderColor)) mapLabel = infoPanel:add(Label(PanelSize(Vec2(-1, 0.03)), "The island world", Vec3(0.7), Alignment.MIDDLE_CENTER)) --difficulty local rowPanel = infoPanel:add(Panel(PanelSize(Vec2(-1, 0.03)))) labels[1] = rowPanel:add(Label(PanelSize(Vec2(-0.6,-1)), language:getText("difficulty"), Vec3(0.7))) labels[1]:setTag("difficulty") local optionsNames = {"easy", "normal", "hard", "extreme", "insane"} difficutyBox = SettingsComboBox.new(rowPanel,PanelSize(Vec2(-1)), optionsNames, "difficulty", optionsNames[2], changeDifficulty ) --Game mode rowPanel = infoPanel:add(Panel(PanelSize(Vec2(-1, 0.03)))) labels[2] = rowPanel:add(Label(PanelSize(Vec2(-0.6,-1)), language:getText("game mode"), Vec3(0.7))) labels[2]:setTag("game mode") local optionsTooltip = {"default tooltip", "survival tooltip", "training tooltip", "leveler tooltip"} gameModeBox = SettingsComboBox.new(rowPanel,PanelSize(Vec2(-1)), gameModes, "game mode", gameModes[1], changeGameMode, optionsTooltip ) local startAGameButton = infoPanel:add(MainMenuStyle.createButton(Vec2(-1,0.03), Vec2(7,1), language:getText("start game"))) startAGameButton:setTag("start game") startAGameButton:addEventCallbackExecute(startMap) labels[3] = startAGameButton end local function getMapIndex(filePath) for i=1, #files do local file = files[i].file if file:isFile() and file:getPath()==filePath then return i end end return 0 end local function workMapName(mapName) if mapName:sub(1,5)=="Co-op" then return mapName:sub(7) end return mapName end local function changeMapTo(filePath) local mNum = getMapIndex(filePath) if mNum>=1 then selectedFile = filePath local mapFile = File(filePath) if mapFile:isFile() then mapLabel:setText( workMapName(mapFile:getName()) ) local mapInfo = MapInformation.getMapInfoFromFileName(mapFile:getName(), mapFile:getPath()) local imageName = mapInfo and mapInfo.icon or nil local texture = Core.getTexture(imageName and imageName or "noImage") levelInfo.setIsCartMap(mapInfo and mapInfo.gameMode=="Cart" or false) levelInfo.setWaveCount(mapInfo and mapInfo.waveCount or 25) if mapInfo then levelInfo.setChangedDifficultyMax(mapInfo.difficultyIncreaseMax) levelInfo.setChangedDifficultyMin(mapInfo.difficultyIncreaseMin) end menuPrevSelect:get("custom"):get("selectedMap"):setString(filePath) iconImage:setTexture(texture) end --set selected color if selectedMapButton then setDefaultButtonColor(selectedMapButton) end selectedMapButton = files[mNum].button setSelectedButtonColor(selectedMapButton) end end local function customeGameChangedMap(button) print("==================================================================") print("customeGameChangedMap()") local mNum,path = string.match(button:getTag():toString(),"(.*):(.*)") --mNum = tonumber(mNum) changeMapTo(path) updateWaveCount() end local function changeFolder(dirPath) curentDirectory = dirPath self.updateMaps() if selectedMapButton then customeGameChangedMap(selectedMapButton) end end local function changeFolderButton(button) print("changeFolder: "..button:getTag():toString().."\n") changeFolder(button:getTag():toString()) end local function addRowButton(file, num) local button = mapListPanel:add(Button(PanelSize(Vec2(-1,0.03)), "", ButtonStyle.SQUARE)) local waveCountLabel = nil button:setLayout(FlowLayout(Alignment.TOP_LEFT)) if file then if file:isDirectory() then button:setTag(curentDirectory.."/"..file:getName()) button:addEventCallbackExecute(changeFolderButton) local img = button:add(Image(PanelSize(Vec2(-1), Vec2(1)), Text("icon_table.tga") )) img:setUvCoord(Vec2(0.75,0.0),Vec2(0.875,0.0625)) elseif file:isFile() then button:setTag(tostring(num)..":"..file:getPath()) button:addEventCallbackExecute(customeGameChangedMap) button:add(Panel(PanelSize(Vec2(-1), Vec2(1)))) end --mapName local name = file:getName() local l1 = workMapName(name) local label = button:add(Label(PanelSize(Vec2(-0.65, -1)), l1, Vec4(0.85))) label:setCanHandleInput(false) --gameMode local mapInfoItem = MapInformation.getMapInfoFromFileName(file:getName(), file:getPath()) if mapInfoItem == nil then mapInfoItem = {gameMode = " "} end local gameModeLabel = button:add(Label(PanelSize(Vec2(-0.5, -1)), mapInfoItem.gameMode, Vec3(0.85), Alignment.MIDDLE_LEFT)) gameModeLabel:setCanHandleInput(false) --wave counter local str = mapInfoItem.waveCount and tostring(mapInfoItem.waveCount) or "" waveCountLabel = button:add(Label(PanelSize(Vec2(-1, -1)), str, Vec3(0.85))) waveCountLabel:setCanHandleInput(false) mapTable[file:getPath()] = {gameMode = gameModeLabel} else local folders = splitString(curentDirectory, "/") local strDirectory = folders[1] for i=2, #folders - 1 do strDirectory = strDirectory.."/"..folders[i] end button:setTag(strDirectory) local img = button:add(Image(PanelSize(Vec2(-1), Vec2(1)), Text("icon_table.tga") )) img:setUvCoord(Vec2(0.75,0.0),Vec2(0.875,0.0625)) button:addEventCallbackExecute(changeFolderButton) local label = button:add(Label(PanelSize(Vec2(-0.80, -1)), " ..", Vec4(0.85))) label:setCanHandleInput(false) end button:setTextColor(Vec3(0.7)) button:setTextHoverColor(Vec3(0.92)) button:setTextDownColor(Vec3(1)) setDefaultButtonColor(button, num) button:setEdgeHoverColor(Vec4(1,1,1,0.4), Vec4(1,1,1,0.4)) button:setEdgeDownColor(Vec4(1,1,1,0.4), Vec4(1,1,1,0.4)) button:setInnerHoverColor(Vec4(1,1,1,0.4), Vec4(1,1,1,0.45), Vec4(1,1,1,0.4)) button:setInnerDownColor(Vec4(1,1,1,0.3), Vec4(1,1,1,0.4), Vec4(1,1,1,0.3)) return button, waveCountLabel end function self.updateMaps() local mapFolder = Core.getDataFolder(curentDirectory) local tFiles = mapFolder:getFiles() files = {} for i=1, #tFiles do files[i]={file = tFiles[i], button=nil} end mapTable = {} selectedMapButton = nil mapListPanel:clear() local count = 0 if curentDirectory ~= "Map" then count = count + 1 addRowButton(nil, count) end for i=1, #files do local file = files[i].file --file = File() if file:isDirectory() and file:getName() ~= "hidden" and file:getName() ~= "Campaign" then count = count + 1 addRowButton(file, count) end end for i=1, #files do local file = files[i].file --file = File() if file:isFile() then count = count + 1 local button, waveCountLabel = addRowButton(file, count) files[i].button = button files[i].waveCountLabel = waveCountLabel -- if selectedMapButton == nil and MapInformation.getMapInfoFromFileName(file:getName(), file:getPath()) then -- selectedMapButton = button -- end end end --update wave count updateWaveCount() end local function addMapsPanel(panel) local mapsPanel = panel:add(Panel(PanelSize(Vec2(-0.6, -1)))) mapsPanel:setBackground(Gradient(Vec4(1,1,1,0.01), Vec4(1,1,1,0.025))) local headerPanel = mapsPanel:add(Panel(PanelSize(Vec2(-1, 0.035)))) headerPanel:setBackground(Gradient(Vec4(1,1,1,0.05), Vec4(1,1,1,0.1))) headerPanel:add(Panel(PanelSize(Vec2(-1),Vec2(1))))--spacing --heaterPanel:add(Label(PanelSize(Vec2(-1), Vec2(1)))) labels[5] = headerPanel:add(Label(PanelSize(Vec2(-0.65, -1)), language:getText("name"), Vec4(0.95))) labels[6] = headerPanel:add(Label(PanelSize(Vec2(-0.5, -1)), language:getText("type"), Vec3(0.95))) labels[7] = headerPanel:add(Label(PanelSize(Vec2(-1.0, -1)), language:getText("wave"), Vec3(0.95))) labels[5]:setTag("name") labels[6]:setTag("type") labels[7]:setTag("wave") mapListPanel = mapsPanel:add(Panel(PanelSize(Vec2(-1, -1)))) mapListPanel:setEnableYScroll() self.updateMaps() end -- local function getDir(path) local dir = {} for str in string.gmatch(path,"([^/]+)") do dir[#dir+1] = str end --remove last as this should only be the file if #dir>=1 then dir[#dir] = nil end return dir end local function replaceAllWrongPath(path) local ret = "" for str in string.gmatch(path,"([^\\]+)") do if ret~="" then ret = ret.."/"..str else ret = str end end return ret end -- -- -- function init() selectedFile = "" --Previosly selected menuPrevSelect = Config("menuPrevSelect") --Options panel mainPanel = panel:add(Panel(PanelSize(Vec2(-1)))) mainPanel:setLayout(FallLayout(Alignment.TOP_CENTER, PanelSize(Vec2(0,0.01)))) --Top menu button panel labels[4] = mainPanel:add(Label(PanelSize(Vec2(-1,0.04)), language:getText("custome game"), Vec3(0.94), Alignment.MIDDLE_CENTER)) labels[4]:setTag("custome game") --Add BreakLine local breakLinePanel = mainPanel:add(Panel(PanelSize(Vec2(-0.9,0.002)))) local gradient = Gradient() gradient:setGradientColorsHorizontal({Vec3(0.45),Vec3(0.66),Vec3(0.45)}) breakLinePanel:setBackground(gradient) local sPanel = mainPanel:add(Panel(PanelSize(Vec2(-0.9, -0.95)))) sPanel:setBorder(Border( BorderSize(Vec4(MainMenuStyle.borderSize)), MainMenuStyle.borderColor)) --Add map panel addMapsPanel(sPanel) --add midle Border line sPanel:add(Panel(PanelSize(Vec2(MainMenuStyle.borderSize,-1),PanelSizeType.WindowPercentBasedOny))):setBackground(Sprite(MainMenuStyle.borderColor)) --Add info panel addMapInfoPanel(sPanel) -- if selectedMapButton then -- customeGameChangedMap(selectedMapButton) -- end MapInformation.setMapInfoLoadedFunction(mapInfoLoaded) --set previous selected settings or a default setting if menuPrevSelect:get("custom"):exist("selectedMap") then --manage if the map is in a sub folder local path = menuPrevSelect:get("custom"):get("selectedMap"):getString() local dir = getDir(replaceAllWrongPath(path)) if #dir>2 then --the map is in a sub folder local folder for i=2, #dir do--i=2 because the first is "Data" wich is not used for map path if i~=2 then folder = folder.."/"..dir[i] else folder = dir[i] end end changeFolder(folder) end --previous selection available changeMapTo(path) else --no previous selection available for i=1, #files do local file = files[i].file if file:isFile() then changeMapTo(file:getPath()) break end end end if menuPrevSelect:get("custom"):exist("selectedDifficulty") then --previous selection available local diffIndex = menuPrevSelect:get("custom"):get("selectedDifficulty"):getInt() changeDifficulty("",diffIndex) else --no previous selection available changeDifficulty("",2) end if menuPrevSelect:get("custom"):exist("selectedGameMode") then --previous selection available local selIndex = menuPrevSelect:get("custom"):get("selectedGameMode"):getInt() changeGameMode("", selIndex) else --no previous selection available changeGameMode("", 1) end mainPanel:setVisible(false) end init() -- -- -- function self.isVisible() MapInformation.init() end function self.getVisible() return mainPanel:getVisible() end function self.setVisible(set,set2) if type(set)=="boolean" then print("mainPanel:setVisible("..tostring(set)..")\n") mainPanel:setVisible(set) else print("mainPanel:setVisible("..tostring(set2)..")\n") mainPanel:setVisible(set2) end end return self end
local a="all" local m="men" local f="female" local page = "c" local msg = "" local missionTimer = {} local sellingTimer = {} local MainTable = { } local sold = false local mission = false local item = "" local progress = false local rx, ry = guiGetScreenSize() local nX, nY = 1366, 768 local sX, sY = guiGetScreenSize() local count = 3*6000 local blip = exports.customblips:createCustomBlip ( -2242.83,145.71, 20, 20, "radar_tshirt.png", 100 ) exports.customblips:setCustomBlipRadarScale(blip,1.1) local global = { {1,a,"images/Winter-Boots.png","Winter Boot",100}, {2,a,"images/Watch.png","Watch",120}, {3,a,"images/Umbrella.png","Umbrella",80}, {4,a,"images/T-Shirt.png","T-Shirt",300}, {5,a,"images/Trousers.png","Trousers",400}, {6,a,"images/Sun-Glasses.png","Sun Glasses",150}, {7,a,"images/Glasses.png","Glasses",350}, {8,a,"images/Socks.png","Socks",50}, {9,a,"images/Shoe-Brush.png","Shoe-Brush",50}, {10,a,"images/Shirt.png","Shirt",300}, {11,a,"images/Scarf.png","Scarf",150}, {12,a,"images/Pilot-hat.png","Pilot hat",250}, {13,a,"images/Necklace.png","Necklace",500}, {14,a,"images/Motorbike-Helmet.png","Bike helmet",600}, {15,a,"images/Jumper.png","Sport Shirt",900}, {16,a,"images/Jacket.png","Jacket",1500}, {17,a,"images/Helmet.png","Helmet",200}, {18,a,"images/Hanger.png","Hanger",200}, {19,a,"images/Shorts.png","Short",300}, {20,a,"images/Coat.png","Coat",1600}, {21,a,"images/Chef-Hat.png","Chef hat",100}, {22,a,"images/Boots.png","Black Boot",130}, {23,a,"images/Baseball-cap.png","Cap",100}, } local men = { {1,m,"images/Trainers.png","Sport Boot",120}, {2,m,"images/Tie.png","Tie",25}, {3,m,"images/mShoe.png","Men Shoe",260}, {4,m,"images/Men-Underwear.png","Underwear",100}, {5,m,"images/Wizard.png","Wizard hat",200}, {6,m,"images/Bowler-Hat.png","Bowler Hat",200}, {7,m,"images/Beanie.png","Theif Hat",100}, {8,m,"images/Kimono.png","Kung Fu suit",1000}, {9,m,"images/Fireman-Coat.png","Fireman Coat",2000}, {10,m,"images/Fireman-Boots.png","Fireman Boot",500}, {11,m,"images/Bulletproof-Vest.png","Armor Vest",3000}, } local female = { {1,f,"images/wShoe.png","Women Shoe",170}, {2,f,"images/Women-Underwear.png","Underwear",300}, {3,f,"images/Witch.png","Witch Hat",200}, {4,f,"images/Wedding-Dress.png","Dress",1500}, {5,f,"images/Skirt.png","Skirt",1000}, {6,f,"images/Romper.png","Romper",800}, {7,f,"images/Bracelet.png","Bracelet1",300}, {8,f,"images/Bra.png","Bra",700}, {9,f,"images/Bow-Tie.png","Bow-Tie",100}, {10,f,"images/Fan.png","Fan",100}, {11,f,"images/Christmas-Mitten.png","Gloves",200}, } local greeting = { "Hello", "Greeting", "Hi", "Wow nice store, Hi..", } local asking = { "I'm looking for", "I was wondering do you have", "I wanna buy", "Please Gimme", } local waste = { "You wasted my time!", "Good bye", "I don't want it anymore :|", } local skins = { [1]= 190, [2]= 192, [3]= 193, [4]= 194, [5]= 195, [6]= 302, [7]= 303, [8]= 269, [9]= 305, [10]= 306, } Store = { tab = {}, scrollpane = {}, tabpanel = {}, label = {}, button = {}, window = {}, staticimage = {} } GlobalStore = { label = {}, staticimage = {} } MenStore = { label = {}, staticimage = {} } FemaleStore = { label = {}, staticimage = {} } local access = false local col = createColCircle(207.04,-127.81,2) local col2 = createColCircle(207.04,-127.81,2) local marker = createMarker(206.98602294922,-127.30908203125,1001,"cylinder",1,255,255,0,100) setElementInterior(marker,3) setElementInterior(col,3) setElementInterior(col2,3) addEventHandler("onClientResourceStart",resourceRoot,function() Store.window[1] = guiCreateWindow(40,50, 706, 506, "Clothes Store", false) centerWindows(Store.window[1]) guiWindowSetSizable(Store.window[1], false) guiSetVisible(Store.window[1],false) guiSetAlpha(Store.window[1], 1.00) Store.tabpanel[1] = guiCreateTabPanel(10, 26, 683, 405, false, Store.window[1]) Store.tab[1] = guiCreateTab("General", Store.tabpanel[1]) Store.scrollpane[1] = guiCreateScrollPane(7, 8, 666, 362, false, Store.tab[1]) Store.tab[2] = guiCreateTab("Men Clothes", Store.tabpanel[1]) Store.scrollpane[2] = guiCreateScrollPane(7, 8, 666, 362, false, Store.tab[2]) Store.tab[3] = guiCreateTab("Women Clothes", Store.tabpanel[1]) Store.scrollpane[3] = guiCreateScrollPane(7, 8, 666, 362, false, Store.tab[3]) Store.button[1] = guiCreateButton(20, 460, 124, 28, "Close", false, Store.window[1]) Store.button[2] = guiCreateButton(569, 459, 124, 28, "Open Store", false, Store.window[1]) end) function centerWindows ( theWindow ) local screenW,screenH=guiGetScreenSize() local windowW,windowH=guiGetSize(theWindow,false) local x,y = (screenW-windowW)/2,(screenH-windowH)/2 guiSetPosition(theWindow,x,y,false) end function BuyItem() if getElementData(source,"data") then if progress == true then local element,id,name = unpack(getElementData(source,"data")) if item == name then sold = true exports.NGCdxmsg:createNewDxMessage("You have sold "..name.." nice work :)",0,255,0) end else exports.NGCdxmsg:createNewDxMessage("There is no customer wants to buy anything !",255,0,0) end end if source == Store.button[2] then createMission() end if source == Store.button[1] then guiSetVisible(Store.window[1],false) showCursor(false) removePanel() toggleAllControls(true,true,true) --setElementPosition(localPlayer,204.47,-131.15,1003.5) --setPedRotation(localPlayer,181) page = "c" end if source == Store.tabpanel[1] then if (guiGetSelectedTab(Store.tabpanel[1])==Store.tab[1]) then createGlobal("a") elseif (guiGetSelectedTab(Store.tabpanel[1])==Store.tab[2]) then createGlobal("m") elseif (guiGetSelectedTab(Store.tabpanel[1])==Store.tab[3]) then createGlobal("f") end end end addEventHandler("onClientGUIClick",resourceRoot,BuyItem) addEventHandler("onClientMouseEnter",root,function() if getElementData(source,"data") then guiSetAlpha(source,0.5) end end) addEventHandler("onClientMouseLeave",root,function() if getElementData(source,"data") then guiSetAlpha(source,1) end end) function openPanel() if access == true then guiSetVisible(Store.window[1],true) showCursor(true) guiSetSelectedTab(Store.tabpanel[1],Store.tab[1]) createGlobal("a") end end function createGlobal(p) if p == "a" then if page == p then return false end page = p removePanel() for k,v in ipairs(global) do iter = v[1] local x,y = -25,14 if iter > 0 and iter <= 8 then x = x+(iter*83) y = 14 elseif iter > 8 and iter <= 16 then x = x-670+(iter*83) y = y+(2*55) elseif iter > 16 and iter <= 24 then x = x-1330+(iter*83) y = y+(2*105) else return end GlobalStore.staticimage[iter] = guiCreateStaticImage(x+8,y, 52, 42, v[3], false, Store.scrollpane[1]) GlobalStore.label[iter] = guiCreateLabel(x,y+50, 75, 35, v[4].."\n$"..v[5], false, Store.scrollpane[1]) guiSetFont(GlobalStore.label[iter], "default-bold-small") guiLabelSetHorizontalAlign(GlobalStore.label[iter], "center", false) setElementData(GlobalStore.staticimage[iter],"data",{GlobalStore.staticimage[iter],v[1],v[4]}) end elseif p == "m" then if page == p then return false end removePanel() page = p for k,v in ipairs(men) do iter = v[1] local x,y = -25,14 if iter > 0 and iter <= 8 then x = x+(iter*83) y = 14 elseif iter > 8 and iter <= 16 then x = x-670+(iter*83) y = y+(2*55) elseif iter > 16 and iter <= 24 then x = x-1330+(iter*83) y = y+(2*105) else return end MenStore.staticimage[iter] = guiCreateStaticImage(x+8,y, 52, 42, v[3], false, Store.scrollpane[2]) MenStore.label[iter] = guiCreateLabel(x,y+50, 75, 35, v[4].."\n$"..v[5], false, Store.scrollpane[2]) guiSetFont(MenStore.label[iter], "default-bold-small") guiLabelSetHorizontalAlign(MenStore.label[iter], "center", false) setElementData(MenStore.staticimage[iter],"data",{MenStore.staticimage[iter],v[1],v[4]}) end elseif p == "f" then if page == p then return false end removePanel() page = p for k,v in ipairs(female) do iter = v[1] local x,y = -25,14 if iter > 0 and iter <= 8 then x = x+(iter*83) y = 14 elseif iter > 8 and iter <= 16 then x = x-670+(iter*83) y = y+(2*55) elseif iter > 16 and iter <= 24 then x = x-1330+(iter*83) y = y+(2*105) else return end FemaleStore.staticimage[iter] = guiCreateStaticImage(x+8,y, 52, 42, v[3], false, Store.scrollpane[3]) FemaleStore.label[iter] = guiCreateLabel(x,y+50, 75, 35, v[4].."\n$"..v[5], false, Store.scrollpane[3]) guiSetFont(FemaleStore.label[iter], "default-bold-small") guiLabelSetHorizontalAlign(FemaleStore.label[iter], "center", false) setElementData(FemaleStore.staticimage[iter],"data",{FemaleStore.staticimage[iter],v[1],v[4]}) end end end function removePanel() for i=1,23 do if isElement(GlobalStore.staticimage[i]) then destroyElement(GlobalStore.staticimage[i]) end if isElement(GlobalStore.label[i]) then destroyElement(GlobalStore.label[i]) end end for i=1,11 do if isElement(MenStore.staticimage[i]) then destroyElement(MenStore.staticimage[i]) end if isElement(MenStore.label[i]) then destroyElement(MenStore.label[i]) end end for i=1,11 do if isElement(FemaleStore.staticimage[i]) then destroyElement(FemaleStore.staticimage[i]) end if isElement(FemaleStore.label[i]) then destroyElement(FemaleStore.label[i]) end end end function isElementWithinCol( element ) if ( not isElement( element ) ) then access = false return false end if getElementInterior( element ) ~= 3 then access = false return false end if isElementWithinColShape( element, col ) then return true end return false end addEventHandler("onClientColShapeHit",col2,function(h,d) if not d then return false end if h and getElementType(h) == "player" then if not isPedInVehicle(h) then if h == localPlayer then if getElementData(h,"Occupation") == "Clothes Seller" and getTeamName(getPlayerTeam(h)) == "Civilian Workers" then exports.NGCdxmsg:createNewDxMessage("Press Space bar to open your store inventory",255,255,0) access = true end end end end end) addEventHandler("onClientColShapeHit",col,function(h,d) if not d then return false end if h and getElementType(h) == "player" then if not isPedInVehicle(h) then if h == localPlayer then --toggleAllControls(false,true,true) --setElementPosition(h,207.09,-127.78,1003.5) --setPedRotation(h,181) if getElementData(h,"Occupation") == "Clothes Seller" and getTeamName(getPlayerTeam(h)) == "Civilian Workers" then exports.NGCdxmsg:createNewDxMessage("Press Space bar to open your store inventory",255,255,0) access = true end end end elseif getElementType(h) == "ped" then -- here start mission if progress == true then return false end progress = true MainTable = nil local ask = math.random(#asking) local msg = asking[ask] local g = getElementModel(h) if g == 190 or g == 192 or g == 193 or g == 194 or g == 195 then local co = math.random(0,1) if co == 0 then local sd = math.random(#global) item = global[sd][4] myMoney = global[sd][5] else local sd = math.random(#female) item = female[sd][4] myMoney = female[sd][5] end elseif g == 302 or g == 303 or g == 269 or g == 305 or g == 306 then local co = math.random(0,1) if co == 0 then local sd = math.random(#global) item = global[sd][4] myMoney = global[sd][5] else local sd = math.random(#men) item = men[sd][4] myMoney = men[sd][5] end end MainTable = { h, msg.." "..item } exports.NGCdxmsg:createNewDxMessage("Store customer : "..msg.." "..item,255,255,0) sellingTimer = setTimer(function(ped) if sold == true then MainTable = nil MainTable = { ped, "Thank you very much :)" } triggerServerEvent("setPedTask",localPlayer) sold = false item = "" progress = false mission = false triggerServerEvent("payPedTask",localPlayer,myMoney) createGame() else MainTable = nil addWasteMsg(ped) triggerServerEvent("setPedTask",localPlayer) item = "" sold = false progress = false mission = false createGame() end end,15000,1,h) end end) function addWasteMsg(p) local ask = math.random(#waste) local msg = waste[ask] MainTable = { p, msg } setTimer(function() MainTable = nil end,5000,1) end addEventHandler("onClientColShapeLeave",col,function(h) if h and getElementType(h) == "player" then if h ~= localPlayer then return false end if getElementDimension(source) ~= getElementDimension(h) then triggerServerEvent("leaveStoreInterior",localPlayer) return false end if not isPedInVehicle(h) then endJob() end end end) function onCalculateBanktime(theTime) if (theTime >= 60000) then local plural = "" if (math.floor((theTime/1000)/60) >= 2) then plural = "s" end return tostring(math.floor((theTime/1000)/60) .. " minute" .. plural) else local plural = "" if (math.floor((theTime/1000)) >= 2) then plural = "s" end return tostring(math.floor((theTime/1000)) .. " second" .. plural) end end local afkKeys = { "mouse1", "mouse2", "mouse3", "mouse4", "mouse5", "mouse_wheel_up", "mouse_wheel_down", "arrow_l", "arrow_u", "arrow_r", "arrow_d", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "num_0", "num_1", "num_2", "num_3", "num_4", "num_5", "num_6", "num_7", "num_8", "num_9", "num_mul", "num_add", "num_sep", "num_sub", "num_div", "num_dec", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "backspace", "tab", "lalt", "ralt", "enter", "space", "pgup", "pgdn", "end", "home", "insert", "delete", "lshift", "rshift", "lctrl", "rctrl", "[", "]", "pause", "capslock", "scroll", ";", ",", "-", ".", "/", "#", "\\", "="} local afkTime = getTickCount() local client = getLocalPlayer() local minutes = 4 local afk = false function resetAFkTime() afkTime = getTickCount() afk = false end for k, v in ipairs(afkKeys) do bindKey(v,"both",resetAFkTime) end setTimer( function () if getTickCount()-afkTime > minutes*60000 then afk = true else afk = false end end,minutes*60000,0) addEventHandler("onClientRender",root,function() if isElementWithinCol(localPlayer) then if getElementData(localPlayer,"Occupation") == "Clothes Seller" and getTeamName(getPlayerTeam(localPlayer)) == "Civilian Workers" then access = true if (isTimer(sellingTimer)) then a, b, c = getTimerDetails(sellingTimer) timeLeftt = a/1000 timeLeft = math.floor(timeLeftt) dxDrawText( "Time Until Customer Leave:"..onCalculateBanktime(math.floor(a)), ( 695 / nX ) * sX, ( 680 / nY ) * sY, ( 647 / nX ) * sX, ( 591 / nY ) * sY, tocolor( 255, 255, 255, 255 ), 1.5, "default-bold", "center", "center",true,true,true,true ) end end else access = false count = 3*6000 if progress == true then endJob() end end if isElementWithinCol(localPlayer) then if getElementData(localPlayer,"Occupation") == "Clothes Seller" and getTeamName(getPlayerTeam(localPlayer)) == "Civilian Workers" then if afk == false then if count > 0 then count = count - 1 dxDrawText( "Worker Payment: "..math.floor((count)/60).." sec|5 minutes", ( 1195 / nX ) * sX, ( 680 / nY ) * sY, ( 947 / nX ) * sX, ( 591 / nY ) * sY, tocolor( 0, 205, 0, 255 ), 1, "default-bold", "center", "center",true,true,true,true ) end if count == 0 then local mon = math.random(3000,6000) dxDrawText( "Worker Payment: $"..mon, ( 1195 / nX ) * sX, ( 680 / nY ) * sY, ( 947 / nX ) * sX, ( 591 / nY ) * sY, tocolor( 0, 205, 0, 255 ), 1, "default-bold", "center", "center",true,true,true,true ) triggerServerEvent("payBonusTask",localPlayer,mon) count = 3*6000 end else dxDrawText( "[Store Boss]: You are AFK , I wont give you any payment!!", ( 1195 / nX ) * sX, ( 680 / nY ) * sY, ( 947 / nX ) * sX, ( 591 / nY ) * sY, tocolor( 0, 205, 0, 255 ), 1, "default-bold", "center", "center",true,true,true,true ) end end end end) function createMission() if isElementWithinCol(localPlayer) then if getElementData(localPlayer,"Occupation") == "Clothes Seller" and getTeamName(getPlayerTeam(localPlayer)) == "Civilian Workers" then if mission == true then exports.NGCdxmsg:createNewDxMessage("You already opened your store, please wait the customers!",255,0,0) return else createGame() end triggerServerEvent("setStoreDim",localPlayer) setElementDimension(col,exports.server:getPlayerAccountID(localPlayer)) end else exports.NGCdxmsg:createNewDxMessage("You can't sell clothes from here!!",255,0,0) end end function createGame() if isTimer(missionTimer) then return false end exports.NGCdxmsg:createNewDxMessage("Please wait the customers :)",255,255,0) missionTimer = setTimer(function() if isElementWithinCol(localPlayer) then mission = true local skin = skins[math.random(#skins)] triggerServerEvent("setStorePedTask",localPlayer,skin) end end,15000,1) end addEvent("togglePedGreeting",true) addEventHandler("togglePedGreeting",root,function(p) local greet = math.random(#greeting) local msg = greeting[greet] MainTable = { p, msg } end) addEventHandler ( "onClientPedDamage", root, function () if ( getElementData( source, "showModelPed" ) ) then cancelEvent() end end ) function drawText (ped, text) --- local chat for ped if ( isElement( ped ) ) then local camPosXl, camPosYl, camPosZl = getPedBonePosition (ped, 6) local camPosXr, camPosYr, camPosZr = getPedBonePosition (ped, 7) local x,y,z = (camPosXl + camPosXr) / 2, (camPosYl + camPosYr) / 2, (camPosZl + camPosZr) / 2 local cx,cy,cz = getCameraMatrix() local px,py,pz = getElementPosition(ped) local distance = getDistanceBetweenPoints3D(cx,cy,cz,px,py,pz) local posx,posy = getScreenFromWorldPosition(x,y,z+0.020*distance+0.10) local elementtoignore1 = getPedOccupiedVehicle(localPlayer) or localPlayer local elementtoignore2 = getPedOccupiedVehicle(ped) or ped if posx and distance <= 20 then --and ( isLineOfSightClear(cx,cy,cz,px,py,pz,true,true,false,true,false,true,true,elementtoignore1) or isLineOfSightClear(cx,cy,cz,px,py,pz,true,true,false,true,false,true,true,elementtoignore2) ) then -- change this when multiple ignored elements can be specified local width = dxGetTextWidth(text,1,"default-bold") dxDrawRectangle(posx - (3 + (0.5 * width)),posy - (2 + (0 * 20)),width + 5,19,tocolor(0,0,0,180)) dxDrawRectangle(posx - (6 + (0.5 * width)),posy - (2 + (0 * 20)),width + 11,19,tocolor(0,0,0,0)) dxDrawRectangle(posx - (8 + (0.5 * width)),posy - (1 + (0 * 20)),width + 15,17,tocolor(0,0,0,180)) dxDrawRectangle(posx - (10 + (0.5 * width)),posy - (1 + (0 * 20)),width + 19,17,tocolor(0,0,0,0)) dxDrawRectangle(posx - (10 + (0.5 * width)),posy - (0 * 20) + 1,width + 19,13,tocolor(0,0,0,180)) dxDrawRectangle(posx - (12 + (0.5 * width)),posy - (0 * 20) + 1,width + 23,13,tocolor(0,0,0,0)) dxDrawRectangle(posx - (12 + (0.5 * width)),posy - (0 * 20) + 4,width + 23,7,tocolor(0,0,0,180)) local r,g,b = 255, 255, 255 dxDrawText(text,posx - (0.5 * width),posy - (0 * 20),posx - (0.5 * width),posy - (0 * 20),tocolor(r,g,b,255),1,"default","left","top",false,false,false) end end end function drawTextBubble () if MainTable then for i=1,#MainTable do drawText (MainTable[1], MainTable[2] ) end end end addEventHandler( "onClientRender", root, drawTextBubble ) function onElementDataChange( dataName, oldValue ) if dataName == "Occupation" and getElementData(localPlayer,dataName) == "Clothes Seller" then initJob() elseif dataName == "Occupation" then stopJob() end end addEventHandler ( "onClientElementDataChange", localPlayer, onElementDataChange, false ) function onJobTeamChange ( oldTeam, newTeam ) if getElementData ( localPlayer, "Occupation" ) == "Clothes Seller" and source == localPlayer then setTimer ( function () if getPlayerTeam( localPlayer ) then local newTeam = getTeamName ( getPlayerTeam( localPlayer ) ) if newTeam == "Off-Duty Workers" then stopJob() elseif getElementData ( localPlayer, "Occupation" ) == "Clothes Seller" and newTeam == "Civilian Workers" then initJob() end end end, 200, 1 ) end end addEventHandler( "onClientPlayerTeamChange", localPlayer, onJobTeamChange, false ) function onResourceStart() setTimer ( function () if getPlayerTeam( localPlayer ) then local team = getTeamName ( getPlayerTeam( localPlayer ) ) if getElementData ( localPlayer, "Occupation" ) == "Clothes Seller" and team == "Civilian Workers" then initJob() end end end, 2500, 1 ) end addEventHandler ( "onClientResourceStart", getResourceRootElement(getThisResource()), onResourceStart ) addEvent( "onClientPlayerTeamChange" ) function initJob() if not job then job = true count = 3*6000 bindKey("space","down",openPanel) end end function stopJob() if job then job = false MainTable = nil progress = false mission = false msg = "" item = "" sold = false access = false unbindKey("space","down",openPanel) triggerServerEvent("endStorePed",localPlayer) if isTimer(missionTimer) then killTimer(missionTimer) end if isTimer(sellingTimer) then killTimer(sellingTimer) end triggerServerEvent("leaveStoreInterior",localPlayer) end end function endJob() MainTable = nil progress = false mission = false msg = "" item = "" sold = false triggerServerEvent("endStorePed",localPlayer) triggerServerEvent("leaveStoreInterior",localPlayer) if isTimer(missionTimer) then killTimer(missionTimer) end if isTimer(sellingTimer) then killTimer(sellingTimer) end end
--- Check if path is a file -- @name isFile -- @param filename string -- @return boolean if ok return function (f) local f=io.open(f,"r") if f~=nil then io.close(f) return true else return false end end
object_tangible_storyteller_prop_pr_all_lair_webweaver = object_tangible_storyteller_prop_shared_pr_all_lair_webweaver:new { } ObjectTemplates:addTemplate(object_tangible_storyteller_prop_pr_all_lair_webweaver, "object/tangible/storyteller/prop/pr_all_lair_webweaver.iff")
local MAXSLOTS = 1000 local Inventory = Class(function(self, inst) self.inst = inst self.itemslots = {} self.maxslots = MAXSLOTS self.recipes = {} self.recipe_count = 0 self.acceptsstacks = true self.ignorescangoincontainer = false self.opencontainers = {} end) function Inventory:NumItems() local num = 0 for k,v in pairs(self.itemslots) do num = num + 1 end return num end function Inventory:GuaranteeItems(items) self.inst:DoTaskInTime(0,function() for k,v in pairs(items) do local item = v if self:Has(item, 1) then for k,v in pairs(Ents) do if v.prefab == item and v.components.inventoryitem:GetGrandOwner() ~= GetPlayer() then v:Remove() end end else for k,v in pairs(Ents) do if v.prefab == item then item = nil break end end if item then self:GiveItem(SpawnPrefab(item)) end end end end) end function Inventory:CanTakeItemInSlot(item, slot) if not (item and item.components.inventoryitem and (item.components.inventoryitem.cangoincontainer or self.ignorescangoincontainer) ) then return false end return item and item.components.inventoryitem ~= nil end function Inventory:GetNumSlots() return self.maxslots end function Inventory:GetItemSlot(item) for k,v in pairs(self.itemslots) do if item == v then return k end end end function Inventory:FindItem(fn) for k,v in pairs(self.itemslots) do if fn(v) then return v end end if self.overflow then return self.overflow.components.container:FindItem(fn) end end function Inventory:FindItems(fn) local items = {} for k,v in pairs(self.itemslots) do if fn(v) then table.insert(items, v) end end local overflow_items = {} if self.overflow then overflow_items = self.overflow.components.container:FindItems(fn) end if #overflow_items > 0 then for k,v in pairs(overflow_items) do table.insert(items, v) end end return items end function Inventory:RemoveItemBySlot(slot) if slot and self.itemslots[slot] then local item = self.itemslots[slot] self:RemoveItem(item, true) return item end end function Inventory:DropItem(item, wholestack, randomdir, pos) if not item or not item.components.inventoryitem then return end local dropped = item.components.inventoryitem:RemoveFromOwner(wholestack) or item if dropped then pos = pos or Vector3(self.inst.Transform:GetWorldPosition()) --print("Inventory:DropItem", item, pos) dropped.Transform:SetPosition(pos:Get()) if dropped.components.inventoryitem then dropped.components.inventoryitem:OnDropped(randomdir) end self.inst:PushEvent("dropitem", {item = dropped}) end return dropped end function Inventory:GetItemInSlot(slot) return self.itemslots[slot] end function Inventory:IsFull() for k = 1, self.maxslots do if not self.itemslots[k] then return false end end return true end ---Returns the slot, and the container where the slot is (self.itemslots, self.equipslots or self.overflow) function Inventory:GetNextAvailableSlot(item) local prefabname = nil if item.components.stackable ~= nil then prefabname = item.prefab --check for stacks that aren't full for k,v in pairs(self.itemslots) do if v.prefab == prefabname and v.components.stackable and not v.components.stackable:IsFull() then return k, self.itemslots end end if self.overflow and self.overflow.components.container then for k,v in pairs(self.overflow.components.container.slots) do if v.prefab == prefabname and v.components.stackable and not v.components.stackable:IsFull() then return k, self.overflow end end end end --check for empty space in the container local empty = nil for k = 1, self.maxslots do if self:CanTakeItemInSlot(item, k) and not self.itemslots[k] then if prefabname ~= nil then if empty == nil then empty = k end else return k, self.itemslots end end end return empty, self.itemslots end function Inventory:GiveItem( inst, slot, screen_src_pos ) --print("Inventory:GiveItem", inst, slot, screen_src_pos) if not inst.components.inventoryitem or not inst:IsValid() then return end if inst.components.inventoryitem.owner and inst.components.inventoryitem.owner ~= self.inst then inst.components.inventoryitem:RemoveFromOwner(true) end local objectDestroyed = inst.components.inventoryitem:OnPickup(self.inst) if objectDestroyed then return end local can_use_suggested_slot = false if not slot and inst.prevslot and not inst.prevcontainer then slot = inst.prevslot end if not slot and inst.prevslot and inst.prevcontainer and inst.prevcontainer.components then if inst.prevcontainer.components.inventoryitem and inst.prevcontainer.components.inventoryitem.owner == self.inst and inst.prevcontainer:IsOpen() and inst.prevcontainer:GetItemInSlot(inst.prevslot) == nil then inst.prevcontainer:GiveItem(inst, inst.prevslot) --self:RemoveItem(inst) return end end if slot then local olditem = self:GetItemInSlot(slot) can_use_suggested_slot = slot ~= nil and slot <= self.maxslots and ( olditem == nil or (olditem and olditem.components.stackable and olditem.prefab == inst.prefab)) and self:CanTakeItemInSlot(inst,slot) end local container = self.itemslots if not can_use_suggested_slot then slot,container = self:GetNextAvailableSlot(inst) end if slot then local leftovers = nil if container == self.overflow and self.overflow and self.overflow.components.container then local itemInSlot = self.overflow.components.container:GetItemInSlot(slot) if itemInSlot then leftovers = itemInSlot.components.stackable:Put(inst, screen_src_pos) end else if self.itemslots[slot] ~= nil then leftovers = self.itemslots[slot].components.stackable:Put(inst, screen_src_pos) else inst.components.inventoryitem:OnPutInInventory(self.inst) self.itemslots[slot] = inst self.inst:PushEvent("itemget", {item=inst, slot = slot, src_pos = screen_src_pos}) end end if leftovers then self:GiveItem(leftovers) end return slot elseif self.overflow and self.overflow.components.container then if self.overflow.components.container:GiveItem(inst, nil, screen_src_pos) then return true end end --self.inst:PushEvent("inventoryfull", {item=inst}) --self:DropItem(inst, true, true) end function Inventory:RemoveItem(item, wholestack) local dec_stack = not wholestack and item and item.components.stackable and item.components.stackable:IsStack() and item.components.stackable:StackSize() > 1 if dec_stack then local dec = item.components.stackable:Get() return dec else for k,v in pairs(self.itemslots) do if v == item then self.itemslots[k] = nil self.inst:PushEvent("itemlose", {slot = k}) if item.components.inventoryitem then item.components.inventoryitem:OnRemoved() end return item end end local ret = nil if ret then if ret.components.inventoryitem and ret.components.inventoryitem.OnRemoved then ret.components.inventoryitem:OnRemoved() return ret end else if self.overflow then return self.overflow.components.container:RemoveItem(item, wholestack) end end end return item end function Inventory:Has(item, amount) local num_found = 0 for k,v in pairs(self.itemslots) do if v and v.prefab == item then if v.components.stackable ~= nil then num_found = num_found + v.components.stackable:StackSize() else num_found = num_found + 1 end end end if self.overflow then local overflow_enough, overflow_found = self.overflow.components.container:Has(item, amount) num_found = num_found + overflow_found end return num_found >= amount, num_found end function Inventory:ConsumeByName(item, amount) local total_num_found = 0 local function tryconsume(v) local num_found = 0 if v and v.prefab == item then local num_left_to_find = amount - total_num_found if v.components.stackable then if v.components.stackable.stacksize > num_left_to_find then v.components.stackable:SetStackSize(v.components.stackable.stacksize - num_left_to_find) num_found = amount else num_found = num_found + v.components.stackable.stacksize self:RemoveItem(v, true):Remove() end else num_found = num_found + 1 self:RemoveItem(v):Remove() end end return num_found end for k = 1,self.maxslots do local v = self.itemslots[k] total_num_found = total_num_found + tryconsume(v) if total_num_found >= amount then break end end if self.overflow and total_num_found < amount then self.overflow.components.container:ConsumeByName(item, (amount - total_num_found)) end end function Inventory:DropEverything(ondeath, keepequip) -- for k = 1,self.maxslots do -- local v = self.itemslots[k] -- if v then -- self:DropItem(v, true, true) -- end -- end end function Inventory:BurnNonpotatableInContainer(container) for j = 1,container.numslots do if container.slots[j] and container.slots[j]:HasTag("nonpotatable") then local olditem = container:RemoveItem(container.slots[j], true) local itemash = SpawnPrefab("ash") itemash.components.named:SetName( olditem.name ) container:GiveItem(itemash,j) olditem:Remove() end end end return Inventory
-- Weltraumprogrammiernacht Config file, for dynamically controllable parameters of the -- simulation. -- Maximum amount of cycles a ship may use per lua function call lua_max_cycles = 10000 -- If we didn't have an complete map in $n cycles send one map_interval = 500 -- Minimum time of one "tick", in microseconds -- (this is 1000000/framerate) frametime = 200000 -- Name of the initial lua code file that will be executed before any player- -- specific code, in a new ship computer. ship_init_code_file = "init.lua" -- Estimated maximum amount of ships and bases. These do not have to be really realistic, -- and are just a hint for memory allocation max_ship_size = 1 -- Do not change, or everything will be blown into pieces (this is the radius btw) max_ship_estimation = 8192 max_base_estimation = 32 -- Map configuration maximum_cluster_size = 500; minimum_planet_size = 30; maximum_planet_size = 50; planets = 100; asteroids = 250; minimum_asteroids = 5; maximum_asteroids = 5; average_grid_size = 500; map_size_x = 170000.; map_size_y = 96250.; -- Range Limits: weapon_range = 500 docking_range = 100 colonize_range = 100 scanner_range = 5000 -- Durations for a number of actions (measured in ticks) docking_duration = 3 undocking_duration = 3 transfer_duration = 3 mining_duration = 20 manufacture_duration = 20 build_ship_duration = 50 colonize_duration = 50 upgrade_base_duration = 50 -- This better be a multiple of 24, so a large ship can fire every x timesteps laser_recharge_duration = 24 -- Hit probabilities when shooting at stuff ship_hit_probability = 0.3 base_hit_probability = 0.3 asteroid_hit_probability = 0.3 -- Tunables of the physics engine dt = 0.5 vmax = 250 m0_small = 1 -- Leergewicht eines kleinen Schiffs (3 slots) m0_medium = 2 -- Leergewicht eines mittleren Schiffs (6 slots) m0_large = 4 -- Leergewicht eines grossen Schiffs (12 slots) m0_huge = 8 -- Leergewicht eines riesigen Schiffs (24 slots) m0_klotz = 1 -- Gewicht eines Klotzes (thruster, resource, laser) F_thruster = 20 -- Schub eines thrusters epsilon = 1e-10 -- // Missmatches im Kurs durch Rundungsfehler ab denen die Physiksengine sich beklagen soll asteroid_radius_to_slots_ratio = 1 planet_size = 50 -- Stuff in astroids upon creation in percent -- First drives are filled, then weapons, then ore. -- Once the astroid is full we stop putting stuff in. -- Remaining slots are filled with "empty". initial_asteroid_drive = 2 initial_asteroid_weapon = 2 initial_asteroid_ore = 86 -- When building a new ship, offset it from the building bases' position by this -- amount. (This should always be larger than the collision distance) build_offset_x = -50 build_offset_y = 50 -- A new player starts with a base of this size initial_base_size = 12
-- See LICENSE for terms local table_remove = table.remove local RemoveFromRules = RemoveFromRules local StopSound = StopSound local PlayFX = PlayFX local ToggleWorking = ChoGGi.ComFuncs.ToggleWorking local mod_SensorSensorTowerBeeping local mod_RCCommanderDronesDeployed local mod_MirrorSphereCrackling local mod_NurseryChild local mod_SpacebarMusic local mod_BioroboticsWorkshop local mod_RareMetalsExtractor local mod_SelectBuildingSound local mod_ResearchComplete local mod_ColdWaveCrackling local DisableSounds -- fired when settings are changed/init local function ModOptions() local options = CurrentModOptions mod_SensorSensorTowerBeeping = options:GetProperty("SensorSensorTowerBeeping") mod_RCCommanderDronesDeployed = options:GetProperty("RCCommanderDronesDeployed") mod_MirrorSphereCrackling = options:GetProperty("MirrorSphereCrackling") mod_NurseryChild = options:GetProperty("NurseryChild") mod_SpacebarMusic = options:GetProperty("SpacebarMusic") mod_BioroboticsWorkshop = options:GetProperty("BioroboticsWorkshop") mod_RareMetalsExtractor = options:GetProperty("RareMetalsExtractor") mod_SelectBuildingSound = options:GetProperty("SelectBuildingSound") mod_ResearchComplete = options:GetProperty("ResearchComplete") mod_ColdWaveCrackling = options:GetProperty("ColdWaveCrackling") if UICity then DisableSounds() end end -- load default/saved settings OnMsg.ModsReloaded = ModOptions -- fired when option is changed function OnMsg.ApplyModOptions(id) if id == CurrentModId then ModOptions() end end local function BldToggleWorking(label) local objs = UICity.labels[label] or "" for i = 1, #objs do ToggleWorking(objs[i]) end end local function BldToggleSounds(label, snd) local objs = UICity.labels[label] or "" for i = 1, #objs do local obj = objs[i] PlayFX(snd, "end", obj) PlayFX(snd, "start", obj) end end DisableSounds = function() local FXRules = FXRules if mod_SensorSensorTowerBeeping then table_remove(FXRules.Working.start.SensorTower.any, 3) RemoveFromRules("Object SensorTower Loop") BldToggleWorking("SensorTower") end if mod_RCCommanderDronesDeployed then local rules = FXRules.RoverDeploy.start for id, list in pairs(rules) do --~ local list = FXRules.RoverDeploy.start.RCRover.any list = rules[id].any for i = #list, 1, -1 do local sound = list[i].Sound if sound == "Unit Rover DeployAntennaON" or sound == "Unit Rover DeployLoop" then table_remove(list, i) end end RemoveFromRules("Unit Rover DeployLoop") RemoveFromRules("Unit Rover DeployAntennaON") BldToggleSounds(id, "RoverDeploy") end end if mod_MirrorSphereCrackling then table_remove(FXRules.Freeze.start.MirrorSphere.any, 2) FXRules.Freeze.start.any = nil RemoveFromRules("Mystery Sphere Freeze") BldToggleSounds("MirrorSpheres", "Freeze") end if mod_NurseryChild then table_remove(FXRules.Working.start.Nursery.any, 1) RemoveFromRules("Building Nurcery LoopEmpty") BldToggleWorking("Nursery") end if mod_SpacebarMusic then table_remove(FXRules.Working.start.Spacebar.any, 1) table_remove(FXRules.Working.start.Spacebar_Small.any, 1) RemoveFromRules("Building Spacebar Loop") RemoveFromRules("Building SpacebarSmall Loop") -- Includes reg and small BldToggleWorking("Spacebar") end if mod_BioroboticsWorkshop then table_remove(FXRules.Working.start.BioroboticsWorkshop.any, 1) RemoveFromRules("Building WorkshopBiorobotics Loop") BldToggleWorking("BioroboticsWorkshop") end if mod_RareMetalsExtractor then table_remove(FXRules.Working.start.PreciousMetalsExtractor.any, 1) RemoveFromRules("Object PreciousExtractor Loop") BldToggleWorking("PreciousMetalsExtractor") end if mod_SelectBuildingSound then RemoveFromRules("UI SelectBuilding") local rules = FXRules.SelectObj.start for id, list in pairs(rules) do list = rules[id].any for i = #list, 1, -1 do local sound = list[i].Sound if sound == "UI SelectBuilding" or sound:sub(-6) == "Select" then RemoveFromRules("list[i].Sound") table_remove(list, i) end end end end if mod_ColdWaveCrackling then local list = FXRules.ColdWave.start.any.any for i = #list, 1, -1 do local sound = list[i].Sound if sound == "Ambience Disaster ColdwaveWave" or sound == "Ambience Disaster ColdwaveCracks" then StopSound(sound.handle) table_remove(list, i) end end RemoveFromRules("Ambience Disaster ColdwaveWave") RemoveFromRules("Ambience Disaster ColdwaveCracks") end end OnMsg.CityStart = DisableSounds OnMsg.LoadGame = DisableSounds -- disable voiced text local complete = T(7058, "Research complete") local orig_Voice_Play = Voice.Play function Voice:Play(text, ...) if mod_ResearchComplete and text == complete then return end return orig_Voice_Play(self, text, ...) end if not ChoGGi.testing then return end --~ -- Data\SoundPreset.lua, and Lua\Config\__SoundTypes.lua --~ -- test sounds: function TestSound(snd) StopSound(ChoGGi.Temp.Sound) ChoGGi.Temp.Sound = PlaySound(snd, "UI") end --~ TestSound("Ambience Disaster ColdwaveWave") --~ TestSound("Ambience Disaster ColdwaveCracks") --~ TestSound("Building Spacebar Loop")
-- Copyright (c) 2020 Trevor Redfern -- -- This software is released under the MIT License. -- https://opensource.org/licenses/MIT local quest = {} function quest:constructor(props) self.title = props.title self.description = props.description self.image = props.image self.prerequisites = props.prerequisites self.progress = { turn_counter = 0 } self.goals = props.goals self.rewards = props.rewards self.turn_counter = 0 self.source = props.source end function quest:assign(hero) self.assigned_hero = hero end function quest:check_prerequisites(game_state) if self.prerequisites then return self.prerequisites(game_state) end end function quest:clone() return quest:new{ title = self.title, description = self.description, image = self.image, prerequisites = self.prerequisites, source = self, goals = self.goals, rewards = self.rewards, } end local prereqs = { turn_counter = function(min) return function(gs) return gs:get_turn_counter() >= min end end } quest.prerequisites = prereqs return moonpie.class(quest)
object_tangible_item_beast_converted_tanray_decoration = object_tangible_item_beast_shared_converted_tanray_decoration:new { } ObjectTemplates:addTemplate(object_tangible_item_beast_converted_tanray_decoration, "object/tangible/item/beast/converted_tanray_decoration.iff")
object_tangible_destructible_destructable_crate_02 = object_tangible_destructible_shared_destructable_crate_02:new { } ObjectTemplates:addTemplate(object_tangible_destructible_destructable_crate_02, "object/tangible/destructible/destructable_crate_02.iff")
minetest.after(0, function() if not armor.def then minetest.after(2,minetest.chat_send_all,"#Better HUD: Please update your version of 3darmor") HUD_SHOW_ARMOR = false end end) function hbarmor.get_armor(player) if not player or not armor.def then return false end local name = player:get_player_name() local def = armor.def[name] or nil if def and def.state and def.count then hbarmor.set_armor(name, def.state, def.count) else return false end return true end function hbarmor.set_armor(player_name, ges_state, items) local max_items = 4 if items == 5 then max_items = items end local max = max_items * 65535 local lvl = max - ges_state lvl = lvl/max if ges_state == 0 and items == 0 then lvl = 0 end hbarmor.armor[player_name] = lvl* (items * (100 / max_items)) end
-- Init Global local MaxSpeed = 300 local font = renderer.setup_font("C:/windows/fonts/arial.ttf", 25, 0) local vVelocity_Offset = se.get_netvar("DT_BasePlayer", "m_vecVelocity[0]") local fFlags_Offset = se.get_netvar("DT_BasePlayer", "m_fFlags") local size = engine.get_screen_size() local x,y = size.x, size.y local TicksShow = 0 -- Graph local Mnoj = 5 local SpeedArray = { } local SpeedArraySize = 300 for i = 1, SpeedArraySize do SpeedArray[i] = MaxSpeed / Mnoj end -- Customize Pos local SpeedPos = vec3_t.new(x / 2 - 330, y - y / 2 - 400, 0) local GraphPos = vec3_t.new(x / 2 - SpeedArraySize / 2 - 500, y - y / 2 - 430, 0) -- Func client.register_callback("paint", function() local LocalPlayer = entitylist.get_local_player() -- Show Speed local r = 0 local g = 255 local b = 0 local fSpeed = LocalPlayer:get_prop_vector(vVelocity_Offset):length() local iSpeed = math.floor(fSpeed) local Raz = (MaxSpeed - fSpeed) if Raz > 49 then r = r + (Raz / 1.18) g = (g - (Raz / 1.18)) / 1.25 elseif Raz > 0 and Raz < 49 then r = r + (Raz / 1.18) g = (g - (Raz / 1.18)) end renderer.text(tostring(iSpeed), font, vec2_t.new(SpeedPos.x, SpeedPos.y), 25, color_t.new(r, g, b, 255)) -- Show Grapth for i = 2, SpeedArraySize do SpeedArray[i - 1] = SpeedArray[i] end SpeedArray[SpeedArraySize] = MaxSpeed / Mnoj - iSpeed / Mnoj for i = 2, SpeedArraySize do if (SpeedArray[i]) then renderer.line(vec2_t.new(GraphPos.x + i - 1, GraphPos.y + SpeedArray[i - 1]), vec2_t.new(GraphPos.x + i, GraphPos.y + SpeedArray[i]), color_t.new(255,255,255,255)) else break end end SpeedArrayStep = SpeedArrayStep + 1 if (SpeedArrayStep >= SpeedArraySize) then SpeedArrayStep = 0 end end)
-- Rings application for WSAPI local rings = require "rings" local _M = {} local init = [==[ local loadstring = loadstring or load local app_name, bootstrap_code, is_file = ... if bootstrap_code then local bootstrap, err if string.match(bootstrap_code, "%w%.lua$") then bootstrap, err = loadfile(bootstrap_code) else bootstrap, err = loadstring(bootstrap_code) end if bootstrap then bootstrap() else error("could not load " .. bootstrap_code .. ": " .. err) end else _, package.path = remotedostring("return package.path") _, package.cpath = remotedostring("return package.cpath") end local common = require"wsapi.common" local wsapi_error = { write = function (self, err) remotedostring("env.error:write(...)", err) end } local wsapi_input = { read = function (self, n) return coroutine.yield("RECEIVE", n) end } local wsapi_meta = { __index = function (tab, k) if k == "headers" then local headers local _, all_headers = remotedostring([[ if env.headers then local out = {} for k, v in pairs(env.headers) do table.insert(out, "[" .. string.format("%q", k) .. "]=" .. string.format("%q", v)) end return "return {" .. table.concat(out, ",") .. "}" end ]]) if all_headers then local v = loadstring(all_headers)() rawset(tab, k, v) return v end else local _, v = remotedostring("return env[(...)]", k) rawset(tab, k, v) return v end end, __newindex = function (tab, k, v) rawset(tab, k, v) remotedostring("local k, v = ...; env[k] = v", k, v) end } local app = common.normalize_app(app_name, is_file) main_func = function () local wsapi_env = { error = wsapi_error, input = wsapi_input } setmetatable(wsapi_env, wsapi_meta) local ok, status, headers, res = common.run_app(app, wsapi_env) if not ok then local msg = status headers = { ["Content-Type"] = "text/html" } if wsapi_env.STATUS ~= "" then status = wsapi_env.STATUS res = coroutine.wrap(function () coroutine.yield(msg) end) else status = 500 res = coroutine.wrap(function () coroutine.yield(common.error_html(msg)) end) end end remotedostring("status = ...", status) for k, v in pairs(headers) do if type(v) == "table" then remotedostring("headers[(...)] = {}", k) for _, val in ipairs(v) do remotedostring("local k, v = ...; table.insert(headers[k], v)", k, val) end else remotedostring("local k, v = ...; headers[k] = v", k, v) end end local s, v = res() while s do if s == "RECEIVE" and v then s, v = res(coroutine.yield(s, v)) else coroutine.yield("SEND", s) end s, v = res() end return "SEND", nil end ]==] -- Returns a WSAPI application that runs the provided WSAPI application -- in an isolated Lua environment function _M.new(app_name, bootstrap, is_file) local data = { created_at = os.time() } setmetatable(data, { __index = _G }) local state = rings.new(data) assert(state:dostring(init, app_name, bootstrap, is_file)) local error = function (msg) data.status, data.headers, data.env = nil error(msg) end return function (wsapi_env) if state and wsapi_env == "close" then state:close() state = nil end if not state then return nil end if rawget(data, "status") then error("this state is already in use") end data.status = 500 data.headers = {} data.env = wsapi_env local ok, flag, s = state:dostring([[ main_coro = coroutine.wrap(main_func) return main_coro(...) ]]) repeat if not ok then error(flag) end if flag == "RECEIVE" then ok, flag, s = state:dostring("return main_coro(...)", wsapi_env.input:read(s)) elseif flag == "SEND" then break else error("Invalid command: " .. tostring(flag)) end until flag == "SEND" local res if not s then res = function () return nil end else res = function () if s then local res = s s = nil return res end local ok, flag, s = state:dostring("return main_coro()") while ok and flag and s do if flag == "RECEIVE" then ok, flag, s = state:dostring("return main_coro(...)", wsapi_env.input:read(s)) elseif flag == "SEND" then return s else error("Invalid command: " .. tostring(flag)) end end data.status, data.headers, data.env = nil if data.cleanup then state:close() state = nil end if not ok then error(flag) end end end return data.status, data.headers, res end, data end return _M
return function(id,props) return { type = script.Name, id = id, props = props, } end
nuclear.debug.log("--item") -- U-235 local u235 = data.raw["item"]["uranium-235"] u235.subgroup = "elements" u235.order = "92[uranium-235]" -- U-238 local u238 = data.raw["item"]["uranium-238"] u238.subgroup = "elements" u238.order = "92[uranium-238]" -- Steam turbine data.raw.item["steam-turbine"].stack_size = 50
local tl = require("tl") local fd = io.open(arg[1], "r") local input = fd:read("*a") local tokens = tl.lex(input) local errs = {} local i, program = tl.parse_program(tokens, errs) if #errs > 0 then for _, err in ipairs(errs) do io.stderr:write(arg[1]..":"..err.y..":"..err.x..": "..err.msg.."\n") end os.exit(1) end print(tl.pretty_print_ast(program)) --local tokens2 = tl.lex(tl.pretty_print_ast(program)) --print(tl.pretty_print_tokens(tokens2))
--[[********************************** * * Multi Theft Auto - Admin Panel * * server/admin_bans.lua * * Original File by lil_Toady * **************************************]] local aBans = { List = {} } addEventHandler( "onResourceStart", resourceRoot, function() for i, ban in ipairs(getBans()) do aBans.List[aBans.GenerateID(ban)] = ban end end ) addEventHandler( "onBan", root, function(ban) local id = aBans.GenerateID(ban) aBans.List[id] = ban data = { type = "a", id = id, ban = getBanData(ban) } aSyncData(nil, "ban", root, data, "command.listbans") end ) addEventHandler( "onPlayerBan", root, function(ban) local id = aBans.GenerateID(ban) aBans.List[id] = ban data = { type = "a", id = id, ban = getBanData(ban) } aSyncData(nil, "ban", root, data, "command.listbans") end ) addEventHandler( "onUnban", root, function(ban) for id, b in pairs(aBans.List) do if (b == ban) then data = { type = "d", id = id } aSyncData(nil, "ban", root, data, "command.listbans") aBans.List[id] = nil end end end ) function aBans.GenerateID(ban) local id = getBanTime(ban) if (not id or id == 0) then id = math.random(1, 1000000) end while (aBans.List[id]) do id = id + 1 end return tostring(id) end function getBansList() return aBans.List end function getBanData(ban) t = {} t.nick = getBanNick(ban) or nil t.ip = getBanIP(ban) or nil t.serial = getBanSerial(ban) or nil t.username = getBanUsername(ban) or nil t.banner = getBanAdmin(ban) or nil t.reason = getBanReason(ban) or nil t.time = getBanTime(ban) or nil t.unban = getUnbanTime(ban) or nil if (not t.unban or not t.time or t.unban <= t.time) then t.unban = nil end return t end
--[[ Copyright 2014 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] -- Extracted from https://github.com/luvit/luvi/blob/master/src/lua/init.lua local isWindows if jit and jit.os then -- Luajit provides explicit platform detection isWindows = jit.os == "Windows" else -- Normal lua will only have \ for path separator on windows. isWindows = package.config:find("\\") and true or false end local uv = require('luv') local getPrefix, splitPath, joinParts if isWindows then -- Windows aware path utilities function getPrefix(path) return path:match("^%a:\\") or path:match("^/") or path:match("^\\+") end function splitPath(path) local parts = {} for part in string.gmatch(path, '([^/\\]+)') do table.insert(parts, part) end return parts end function joinParts(prefix, parts, i, j) if not prefix then return table.concat(parts, '/', i, j) elseif prefix ~= '/' then return prefix .. table.concat(parts, '\\', i, j) else return prefix .. table.concat(parts, '/', i, j) end end else -- Simple optimized versions for UNIX systems function getPrefix(path) return path:match("^/") end function splitPath(path) local parts = {} for part in string.gmatch(path, '([^/]+)') do table.insert(parts, part) end return parts end function joinParts(prefix, parts, i, j) if prefix then return prefix .. table.concat(parts, '/', i, j) end return table.concat(parts, '/', i, j) end end local function pathJoin(...) local inputs = {...} local l = #inputs -- Find the last segment that is an absolute path -- Or if all are relative, prefix will be nil local i = l local prefix while true do prefix = getPrefix(inputs[i]) if prefix or i <= 1 then break end i = i - 1 end -- If there was one, remove its prefix from its segment if prefix then inputs[i] = inputs[i]:sub(#prefix) end -- Split all the paths segments into one large list local parts = {} while i <= l do local sub = splitPath(inputs[i]) for j = 1, #sub do parts[#parts + 1] = sub[j] end i = i + 1 end -- Evaluate special segments in reverse order. local skip = 0 local reversed = {} for idx = #parts, 1, -1 do local part = parts[idx] if part == '.' then -- Ignore elseif part == '..' then skip = skip + 1 elseif skip > 0 then skip = skip - 1 else reversed[#reversed + 1] = part end end -- Reverse the list again to get the correct order parts = reversed for idx = 1, #parts / 2 do local j = #parts - idx + 1 parts[idx], parts[j] = parts[j], parts[idx] end local path = joinParts(prefix, parts) return path end return { isWindows = isWindows, join = pathJoin, getPrefix = getPrefix, splitPath = splitPath, joinparts = joinParts, }
ITEM.name = "Deploy Base" ITEM.model = Model("models/props_junk/cardboard_box001a.mdl") ITEM.category = "Deployables" ITEM.entityName = "npc_turret_floor" ITEM.description = "Deploy It" ITEM.width = 2 ITEM.height = 2 ITEM.noBusiness = true ITEM.price = 50 ITEM.functions.Deploy = { OnRun = function(item) if item.entityName then local pos = item.entity:GetPos() pos:Add(Vector(0, 0, 50)) --prevention for stuck ents inside world local spawned = ents.Create(item.entityName) spawned:SetAngles(item.player:GetAngles()) spawned:SetPos(pos) spawned:Spawn() return true end end, OnCanRun = function(item) return IsValid(item.entity) end }
-- luacheck: globals describe it return function() describe("multiple it blocks with the same description", function() it("should raise an error", function() end) it("should raise an error", function() end) end) end