content
stringlengths
5
1.05M
-- -- Project: Loowy -- User: kostik -- Date: 09.02.17 -- package.path = "../src/?.lua;" .. package.path local config = {} local wsServer for line in io.lines('config.ini') do local key, value = line:match("^(%w+)%s*=%s*(.+)$") if key and value then if tonumber(value) then value = tonumber(value) end if value == "true" then value = true end if value == "false" then value = false end if key == 'wsServer' then wsServer = value else config[key] = value end end end local printdump = require("loowy.vardump").printdump local ev = require 'ev' local loowy = require 'loowy.client' local client1, client2 print('Connecting clients to WAMP Server: ' .. wsServer) client1 = loowy.new(wsServer, { realm = config.realm, maxRetries = config.maxRetries, transportEncoding = config.transportEncoding, debug = config.debug, onConnect = function() print('Got to WAMP Client instance 1 onConnect callback') print('Subscribing to topic.test1') client1:subscribe('topic.test1', { onSuccess = function() print('Got to topic topic.test1 instance 1 subscribe onSuccess') end, onError = function(err) print('Got to topic topic.test1 instance 1 subscribe onError: ' .. err.error) end, onEvent = function(evt) print('Got to topic topic.test1 instance 1 subscribe onEvent') print('Event payload: ') printdump(evt) end }) local publishTimer publishTimer = ev.Timer.new(function() publishTimer:stop(ev.Loop.default) print('Publishing to topic.test1 instance 1 without payload') client1:publish('topic.test1', nil, { onSuccess = function() print('Got to publish to topic topic.test1 instance 1 onSuccess') end, onError = function(err) print('Got to publish to topic topic.test1 instance 1 onError: ' .. err.error) end }) end, 10) publishTimer:start(ev.Loop.default) local unsubscribeTimer unsubscribeTimer = ev.Timer.new(function() unsubscribeTimer:stop(ev.Loop.default) print('Unsubscribing from topic.test1 instance 1') client1:unsubscribe('topic.test1', { onSuccess = function() print('Got to unsubscribe from topic topic.test1 instance 1 onSuccess') end, onError = function(err) print('Got to unsubscribe from topic topic.test1 instance 1 onError: ' .. err.error) end }) end, 10) unsubscribeTimer:start(ev.Loop.default) print('Registering new RPC rpc.test1 instance 1') client1:register('rpc.test1', { rpc = function(data) print('Invoked rpc.test1 instance 1') print('RPC payload') printdump(data) return { argsList = data.argsList, argsDict = data.argsDict } end, onSuccess = function() print('Got to register rpc rpc.test1 instance 1 onSuccess') end, onError = function(err) print('Got to register rpc rpc.test1 instance 1 onError: ' .. err.error) end }) local callTimer callTimer = ev.Timer.new(function() callTimer:stop(ev.Loop.default) print('Calling rpc rpc.test2 from instance 1 with payload: string "string payload"') client1:call('rpc.test2', "string payload", { onSuccess = function(data) print('Got to rpc call rpc.test2 onSuccess') print('Call result') printdump(data) end, onError = function(err) print('Got to rpc call rpc.test2 instance 1 onError: ' .. err.error) end }) end, 10) callTimer:start(ev.Loop.default) local disconnectTimer disconnectTimer = ev.Timer.new(function() disconnectTimer:stop(ev.Loop.default) print('Disconnecting from WAMP Server instance 1') client1:disconnect() end, 30) disconnectTimer:start(ev.Loop.default) end, onClose = function() print('Got to WAMP Client instance 1 onClose callback') end, onError = function(err) print('Got to WAMP Client instance 1 onError callback: ' .. err.error) end, onReconnect = function() print('Got to WAMP Client instance 1 onReconnect callback') end }) client2 = loowy.new(wsServer, { transportEncoding = 'json', realm = config.realm, maxRetries = config.maxRetries, transportEncoding = config.transportEncoding, debug = config.debug, onConnect = function() print('Got to WAMP Client instance 2 onConnect callback') print('Subscribing to topic.test1') client2:subscribe('topic.test1', { onSuccess = function() print('Got to topic topic.test1 instance 2 subscribe onSuccess') end, onError = function(err) print('Got to topic topic.test1 instance 2 subscribe onError: ' .. err.error) end, onEvent = function(evt) print('Got to topic topic.test1 instance 2 subscribe onEvent') print('Event payload: ') printdump(evt) end }) local publishTimer publishTimer = ev.Timer.new(function() publishTimer:stop(ev.Loop.default) print('Publishing to topic.test1 instance 2 without payload') client2:publish('topic.test1', nil, { onSuccess = function() print('Got to publish to topic topic.test1 instance 2 onSuccess') end, onError = function(err) print('Got to publish to topic topic.test1 instance 2 onError: ' .. err.error) end }) end, 10) publishTimer:start(ev.Loop.default) local unsubscribeTimer unsubscribeTimer = ev.Timer.new(function() unsubscribeTimer:stop(ev.Loop.default) print('Unsubscribing from topic.test1 instance 2') client2:unsubscribe('topic.test1', { onSuccess = function() print('Got to unsubscribe from topic topic.test1 instance 2 onSuccess') end, onError = function(err) print('Got to unsubscribe from topic topic.test1 instance 2 onError: ' .. err.error) end }) end, 20) unsubscribeTimer:start(ev.Loop.default) print('Registering new RPC rpc.test2 instance 2') client2:register('rpc.test2', { rpc = function(data) print('Invoked rpc.test2 instance 2') print('RPC payload') printdump(data) return { argsList = data.argsList, argsDict = data.argsDict } end, onSuccess = function() print('Got to register rpc rpc.test2 instance 2 onSuccess') end, onError = function(err) print('Got to register rpc rpc.test2 instance 2 onError: ' .. err.error) end }) local callTimer callTimer = ev.Timer.new(function() callTimer:stop(ev.Loop.default) print('Calling rpc rpc.test1 from instance 2 with payload: string "string payload"') client2:call('rpc.test1', "string payload", { onSuccess = function(data) print('Got to rpc call rpc.test1 onSuccess') print('Call result') printdump(data) end, onError = function(err) print('Got to rpc call rpc.test1 instance 2 onError: ' .. err.error) end }) end, 10) callTimer:start(ev.Loop.default) local disconnectTimer disconnectTimer = ev.Timer.new(function() disconnectTimer:stop(ev.Loop.default) print('Disconnecting from WAMP Server instance 2') client2:disconnect() end, 30) disconnectTimer:start(ev.Loop.default) end, onClose = function() print('Got to WAMP Client instance 2 onClose callback') end, onError = function(err) printdump(err) print('Got to WAMP Client instance 2 onError callback: ' .. err.error) end, onReconnect = function() print('Got to WAMP Client instance 2 onReconnect callback') end }) ev.Loop.default:loop()
-- Used to provide cooldown time for teleport. RecallCooldownDataProvider = Up_DataProvider:new { Cooldown = 0 -- Actual cooldown time. } -- Overriden method Up_DataProvider:initialize(). function RecallCooldownDataProvider:initialize() self.Cooldown = GetRecallCooldown() local function updateCooldownTime() self.Cooldown = GetRecallCooldown() end EVENT_MANAGER:RegisterForUpdate("RecallCooldownDataProvider", 1000, updateCooldownTime) -- 1 second is enough. end -- Overriden method Up_DataProvider:getText(addon). function RecallCooldownDataProvider:getText(addon) if self.Cooldown == 0 then return nil -- return nothing to avoid displaying with zero time. end -- TODO settings attributes for all parameters local textureString = zo_iconFormat("esoui\\art\\icons\\poi\\poi_wayshrine_complete.dds", 32, 32) local timeString = ZO_FormatTimeMilliseconds(self.Cooldown, TIME_FORMAT_STYLE_SHOW_LARGEST_UNIT) return string.format("%s %s", textureString, timeString) end
local module = {} local pin_scl = 5 --yellow local pin_sda = 4 --green local mqtt_id = 6666 local mqtt_topic_co2 = "/your_mqtt_topic/co2" local mqtt_topic_temp = "/your_mqtt_topic/temp" local mqtt_topic_rh = "/your_mqtt_topic/rh" -- CO2 measurement callback local function callback_co2(co2,temp,rh) --print("CO2 "..co2.." temp "..temp.." RH "..rh.." mem "..node.heap()) mod_mqtt.send(mqtt_topic_co2, co2) mod_mqtt.send(mqtt_topic_temp, temp) mod_mqtt.send(mqtt_topic_rh, rh) end -- callback when MQTT is connected local function callback_mqtt() end -- callback on INITIAL wifi connect local function callback_connect() end function module.start() _G.APP_Version = "2.1" _G.APP_Name = "TEST" mod_wifi.init(callback_connect) mod_mqtt.init(mqtt_id, callback_mqtt) mod_scd4x.init(5000,pin_scl,pin_sda,callback_co2) -- measure every 5 seconds end return module
--[[-- @package MoonZaphire @filename window.lua @version 1.0 @author Díaz Urbaneja Víctor Eduardo Diex <victor.vector008@gmail.com> @date 05.02.2021 01:10:40 -04 ]] --- I create the AuthHost subclass of MoonZaphire MoonZaphire:class('AuthHost', Gtk.Box) --- At the beginning of the class function MoonZaphire.AuthHost:_class_init(klass) --- I load the template klass:set_template_from_resource( '/com/github/diazvictor/MoonZaphire/data/ui/login/auth_host.ui' ) --- I add the desired elements to the template klass:bind_template_child_full('hostname', true, 0) klass:bind_template_child_full('channel', true, 0) klass:bind_template_child_full('revealer', true, 0) klass:bind_template_child_full('port', true, 0) klass:bind_template_child_full('btn_back', true, 0) klass:bind_template_child_full('btn_login', true, 0) end --- When building the class function MoonZaphire.AuthHost:_init() -- Start template self:init_template() -- I load the template objects local hostname = self:get_template_child(MoonZaphire.AuthHost, 'hostname') local channel = self:get_template_child(MoonZaphire.AuthHost, 'channel') local port = self:get_template_child(MoonZaphire.AuthHost, 'port') local revealer = self:get_template_child(MoonZaphire.AuthHost, 'revealer') local btn_login = self:get_template_child(MoonZaphire.AuthHost, 'btn_login') local btn_back = self:get_template_child(MoonZaphire.AuthHost, 'btn_back') -- Hidden revealer revealer:set_reveal_child(false) -- By pressing the btn_back.on_clicked = function () content_login:set_visible_child_name('auth_user') end -- By pressing the btn_login.on_clicked = function () content:set_visible_child_name('chat') end end
-- --The MIT License (MIT) --Copyright (c) 2014 CoolDark -- --See LICENSE file -- addEventHandler ("onPlayerLogin", root, function ( ) fadeCamera( source, true ) setCameraTarget( source, source ) iRandom = math.random ( #g_Positions ) spawnPlayer ( source, g_Positions[iRandom][1],g_Positions[iRandom][2],g_Positions[iRandom][3] ) end ) addEventHandler ( "onPlayerLogout", root, function ( ) fadeCamera( source, false ) end ) addEventHandler ( "onPlayerSpawn", root, function ( ) setElementModel ( source, getAccountData (getPlayerAccount (source), "ClassicDM.PlayerSkin") ) giveWeapon ( source, 22, 100 ) end )
local identifiers = {} function ShowInfo(text) SetNotificationTextEntry("STRING") AddTextComponentSubstringPlayerName(text) DrawNotification(false, false) end Citizen.CreateThread(function() local myIdss = getIdentifiers() print(myIdss) while true do Citizen.Wait(10000) TriggerServerEvent('primerp_vehwl:reloadwl') TriggerServerEvent('primerp_vehwl:Server:Check') end end) function getConfig() return LoadResourceFile(GetCurrentResourceName(), "whitelist.json") end AddEventHandler("playerSpawned", function() TriggerServerEvent("primerp_vehwl:reloadwl") end) function getIdentifiers() return identifiers end RegisterNetEvent('primerp_vehwl:RunCode:Client') AddEventHandler('primerp_vehwl:RunCode:Client', function(cfg) -- local ped = GetPlayerPed(-1) local inVeh = IsPedInAnyVehicle(ped, false) local veh = GetVehiclePedIsUsing(ped) local driver = GetPedInVehicleSeat(veh, -1) local spawncode = GetEntityModel(veh) local allowed = false local exists = false local myIds = {} myIds = getIdentifiers() if (inVeh) and (driver == ped) then for pair,_ in pairs(cfg) do -- Pair for _,vehic in ipairs(cfg[pair]) do --print("Checking if exists with vehic.spawncode == " .. string.upper(vehic.spawncode) .. " and spawncode == " --.. string.upper(spawncode)) if (GetHashKey(vehic.spawncode) == spawncode) then exists = true end end if (pair == myIds[1]) then for _,v in ipairs(cfg[pair]) do --print(v.allowed) --print("The vehicle is " .. v.spawncode .. " and allowed = " .. tostring(v.allowed) .. " with ID as " .. tostring(pair)) if (spawncode == GetHashKey(v.spawncode)) and (v.allowed) then allowed = true print("Allowed was set to true with vehicle == " .. v.spawncode) end end end end end --print("Value of exists == " .. tostring(exists) .. " and value of allowed == " .. tostring(allowed)) if (exists and not allowed) then --print("It should delete the vehicle for " .. GetPlayerName(source)) DeleteEntity(veh) ClearPedTasksImmediately(ped) TriggerEvent('primerp_vehwl:RunCode:Success', source) end end) RegisterNetEvent('primerp_vehwl:RunCode:Success') AddEventHandler('primerp_vehwl:RunCode:Success', function() ShowInfo('~r~ERROR: You do not have access to this personal vehicle') end) RegisterNetEvent("primerp_vehwl:loadIdentifiers") AddEventHandler("primerp_vehwl:loadIdentifiers", function(id) identifiers = id end) RegisterCommand("reloadwl", function(source) TriggerServerEvent("primerp_vehwl:reloadwl") end) --[[ Commands: /setOwner <id> <spawncode> /trust <id> <spawncode> /untrust <id> <spawncode> /vehicle list --]]--
--------------------------------------------------------------------------------------------------- -- User story: https://github.com/smartdevicelink/sdl_requirements/issues/10 -- Use case: https://github.com/smartdevicelink/sdl_requirements/blob/master/detailed_docs/resource_allocation.md -- Item: Use Case 3: Excpetion 2.1 -- -- Requirement summary: -- [SDL_RC] Resource allocation based on access mode -- -- Description: -- In case: -- Any trigger of Policy Table Update happened and in received PTU RC_app_1 is revoked -- -- SDL must: -- 1) SDL releases module_1 from RC_app_1 control --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local commonRC = require('test_scripts/RC/commonRC') --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false --[[ Local Functions ]] local function PTUfunc(tbl) tbl.policy_table.app_policies[config.application1.registerAppInterfaceParams.fullAppID] = commonRC.json.null tbl.policy_table.app_policies[config.application2.registerAppInterfaceParams.fullAppID] = commonRC.getRCAppConfig() end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", commonRC.preconditions, { true, 1 }) runner.Step("Update SDL config", commonRC.setSDLIniParameter, { "ApplicationListUpdateTimeout", 5000 }) runner.Step("Start SDL, HMI, connect Mobile, start Session", commonRC.start) runner.Step("RAI1", commonRC.registerAppWOPTU) runner.Title("Test") runner.Step("Enable RC from HMI with AUTO_DENY access mode", commonRC.defineRAMode, { true, "AUTO_DENY"}) runner.Step("Activate App1", commonRC.activateApp) -- App1: FULL runner.Step("Module RADIO App1 ButtonPress allowed", commonRC.rpcAllowed, { "RADIO", 1, "ButtonPress" }) runner.Step("Subscribe App1 to RADIO", commonRC.subscribeToModule, { "RADIO", 1 }) runner.Step("Send notification OnInteriorVehicleData RADIO. App1 is subscribed", commonRC.isSubscribed, { "RADIO", 1 }) runner.Step("RAI2", commonRC.registerApp, { 2 }) runner.Step("PTU App1 permissions revoked", commonRC.policyTableUpdate, { PTUfunc }) runner.Step("Module RADIO App1 SetInteriorVehicleData disallowed", commonRC.rpcDenied, { "RADIO", 1, "SetInteriorVehicleData", "DISALLOWED"}) runner.Step("Module CLIMATE App1 SetInteriorVehicleData disallowed", commonRC.rpcDenied, { "CLIMATE", 1, "SetInteriorVehicleData", "DISALLOWED"}) runner.Step("Activate App2", commonRC.activateApp, { 2 }) -- App1: BACKGROUND, App2: FULL runner.Step("Send notification OnInteriorVehicleData RADIO. App1 is unsubscribed", commonRC.isUnsubscribed, { "RADIO", 1 }) runner.Step("Module RADIO App2 SetInteriorVehicleData allowed", commonRC.rpcAllowed, { "RADIO", 2, "SetInteriorVehicleData"}) runner.Title("Postconditions") runner.Step("Stop SDL", commonRC.postconditions)
require 'nn'; require 'nngraph'; local nBatch = 2 local nCh = 3 local nHt = 4 local nWd = 5 xx = torch.Tensor(nBatch,nCh, nHt, nWd) --========== First batch xx[{1,1,{},{}}] = 1*torch.ones(nHt, nWd) -- bluCh xx[{1,2,{},{}}] = 2*torch.ones(nHt, nWd) -- grnCh xx[{1,3,{},{}}] = 3*torch.ones(nHt, nWd) -- redCh --========== Second batch xx[{2,1,{},{}}] = 0.5*torch.ones(nHt, nWd) -- bluCh xx[{2,2,{},{}}] = 0.2*torch.ones(nHt, nWd) -- grnCh xx[{2,3,{},{}}] = 0.3*torch.ones(nHt, nWd) -- redCh local augNetInitBlock = nn.ConcatTable() local allCh = nn.Identity() local sepCh = nn.ConcatTable() local bluCh = nn.Sequential():add(nn.Narrow(2, 1, 1)):add(nn.MulConstant(0.114, false)) local grnCh = nn.Sequential():add(nn.Narrow(2, 2, 1)):add(nn.MulConstant(0.587, false)) local redCh = nn.Sequential():add(nn.Narrow(2, 3, 1)):add(nn.MulConstant(0.299, false)) sepCh:add(bluCh) sepCh:add(grnCh) sepCh:add(redCh) local gryCh = nn.Sequential() gryCh:add(sepCh):add(nn.CAddTable()) augNetInitBlock:add(allCh) augNetInitBlock:add(gryCh) local augNet = nn.Sequential() augNet:add(augNetInitBlock):add(nn.JoinTable(2)) yy = augNet:forward(xx) print(yy:size()) print(yy)
--[[ Data Preparation functions. ]] local function vecToTensor(vec) local t = torch.Tensor(#vec) for i = 1, #vec do t[i] = vec[i] end return t end local Preprocessor = torch.class('Preprocessor') local paths = require 'paths' local tokenizer = require('tools.utils.tokenizer') local tds local threads local preprocess_batchsize = 10000 local commonOptions = { { '-features_vocabs_prefix', '', [[Path prefix to existing features vocabularies.]] }, { '-time_shift_feature', true, [[Time shift features on the decoder side.]] }, { '-keep_frequency', false, [[Keep frequency of words in dictionary.]] }, { '-gsample', 0, [[If not zero, extract a new sample from the corpus. In training mode, file sampling is done at each epoch. Values between 0 and 1 indicate ratio, values higher than 1 indicate data size]], { valid = onmt.utils.ExtendedCmdLine.isFloat(0) } }, { '-gsample_dist', '', [[Configuration file with data class distribution to use for sampling training corpus. If not set, sampling is uniform.]], { valid = onmt.utils.ExtendedCmdLine.fileNullOrExists, depends = function(opt) return opt.gsample_dist == '' or opt.gsample > 0, "option `gsample_dist` requires `gsample`" end } }, { '-sort', true, [[If set, sort the sequences by size to build batches without source padding.]] }, { '-shuffle', true, [[If set, shuffle the data (prior sorting).]] }, { '-idx_files', false, [[If set, source and target files are 'key value' with key match between source and target.]] }, { '-report_progress_every', 100000, [[Report status every this many sentences.]], { valid = onmt.utils.ExtendedCmdLine.isInt(1) } }, { '-preprocess_pthreads', 4, [[Number of parallel threads for preprocessing.]], { valid = onmt.utils.ExtendedCmdLine.isInt(1) } } } function Preprocessor.getDataList(dataType) local datalist if dataType == 'bitext' or dataType == 'seq2seq' then datalist = { {name="source",short="src",hasVocab=true,suffix=".src"} , {name="target",short="tgt",hasVocab=true,suffix=".tgt"} } elseif dataType == 'monotext' then datalist = { {hasVocab=true,suffix=".tok"} } else datalist = { {name="source",short="src",hasVocab=false,suffix=".src"} , {name="target",short="tgt",hasVocab=true,suffix=".tgt"} } end return datalist end -- utility functions local function prefix(data) if data.short then return data.short.."_" end return "" end local function suffix(data) if data.short then return "_"..data.short end return "" end local function nameWithSpace(data) if data.name then return " "..data.name end return "" end --[[ Generic function to generate options for the different dataTypes ]] local function declareDataOptions(dataType) local datalist = Preprocessor.getDataList(dataType) local options = {} table.insert(options, { '-train_dir', '', [[Path to training files directory.]], { valid = onmt.utils.ExtendedCmdLine.fileNullOrExists } }) for i = 1, #datalist do table.insert(options, { '-train'..suffix(datalist[i]), '', "Path to the training"..nameWithSpace(datalist[i]).." data.", { valid=onmt.utils.ExtendedCmdLine.fileNullOrExists } }) end for i = 1, #datalist do table.insert(options, { '-valid'..suffix(datalist[i]), '', "Path to the validation"..nameWithSpace(datalist[i]).." data.", { valid=onmt.utils.ExtendedCmdLine.fileNullOrExists } }) end for i = 1, #datalist do if datalist[i].hasVocab then table.insert(options, { '-'..prefix(datalist[i])..'vocab', '', "Path to an existing"..nameWithSpace(datalist[i]).." vocabulary.", { valid=onmt.utils.ExtendedCmdLine.fileNullOrExists } }) table.insert(options, { '-'..prefix(datalist[i])..'suffix', datalist[i].suffix, "Suffix for"..nameWithSpace(datalist[i]).." files in train/valid directories." }) table.insert(options, { '-'..prefix(datalist[i])..'vocab_size', { 50000 }, "List of"..nameWithSpace(datalist[i])..[[ vocabularies size: `word[ feat1[ feat2[ ...] ] ]`. If = 0, vocabularies are not pruned.]] }) table.insert(options, { '-'..prefix(datalist[i])..'words_min_frequency', { 0 }, "List of"..nameWithSpace(datalist[i])..[[ words min frequency: `word[ feat1[ feat2[ ...] ] ]`. If = 0, vocabularies are pruned by size.]] }) end end for i = 1, #datalist do table.insert(options, { '-'..prefix(datalist[i])..'seq_length', 50, "Maximum"..nameWithSpace(datalist[i])..[[ sequence length.]], { valid = onmt.utils.ExtendedCmdLine.isInt(1) } }) end if dataType ~= 'monotext' then table.insert(options, { '-check_plength', false, [[Check source and target have same length (for seq tagging).]] }) end return options end function Preprocessor.declareOpts(cmd, dataType) dataType = dataType or 'bitext' local options = declareDataOptions(dataType) for _, v in ipairs(commonOptions) do table.insert(options, v) end cmd:setCmdLineOptions(options, 'Data') -- prepare tokenization option local topts = tokenizer.getOpts() for i, v in ipairs(topts) do if v[1] == '-mode' then topts[i] = { '-mode', 'space', [[Define how aggressive should the tokenization be. `space` is space-tokenization.]], { enum = {'conservative', 'aggressive', 'space'} } } end end cmd:setCmdLineOptions(topts, "Tokenizer") end function Preprocessor.expandOpts(cmd, dataType) local torenameOpts = {}; local current_block; local pref = "{src,tgt}_" if dataType == "monotext" then pref = "" end if dataType == "feattext" then pref = "tgt_" end for i, v in ipairs(cmd.helplines) do if type(v) == "string" then local p = v:find(" options") if p then current_block = v:sub(1,p-1); if current_block == "MPreprocessing" or current_block == "Tokenizer" then cmd.helplines[i] = cmd.helplines[i] end end else if current_block == "MPreprocessing" or current_block == "Tokenizer" then torenameOpts[v.key] = current_block:sub(1,3):lower() v.key="-"..current_block:sub(1,3):lower().."_"..pref..v.key:sub(2) end end end local newOpts = {} for k, v in pairs(cmd.options) do if torenameOpts[k] then cmd.options[k] = nil if dataType == 'monotext' then local ksrc = '-'..torenameOpts[k]..'_'..k:sub(2) newOpts[ksrc] = onmt.utils.Table.deepCopy(v) elseif dataType == 'bitext' then local ksrc = '-'..torenameOpts[k]..'_src_'..k:sub(2) newOpts[ksrc] = onmt.utils.Table.deepCopy(v) end if dataType ~= 'monotext' then local ktgt = '-'..torenameOpts[k]..'_tgt_'..k:sub(2) newOpts[ktgt] = onmt.utils.Table.deepCopy(v) end end end for k, v in pairs(newOpts) do cmd.options[k] = v end end local function ruleMatch(s, rule) if rule == '*' then return true end local pat = onmt.utils.String.split(rule, ",") for _, r in ipairs(pat) do if string.match(s, r) then return true end end end function Preprocessor:parseDirectory(args, datalist, dist_rules, keep_rules, type) local dir = args[type.."_dir"] assert(dir ~= '', 'missing \''..type..'_dir\' parameter') _G.logger:info('Parsing '..type..' data from directory \''..dir..'\':') local firstSuffix = args[prefix(datalist[1])..'suffix'] local totalCount = 0 local totalError = 0 local list_files = {} for candf in paths.iterfiles(dir) do if firstSuffix == '' or candf:sub(-firstSuffix:len()) == firstSuffix then self:poolAddJob( function(f) local flist = {} local errors = {} local fprefix = f:sub(1, -firstSuffix:len()-1) table.insert(flist, _G.paths.concat(dir,f)) local error = 0 local countLines = onmt.utils.FileReader.countLines(flist[1], args.idx_files) for i = 2, #datalist do local tfile = _G.paths.concat(dir,fprefix..args[prefix(datalist[i])..'suffix']) table.insert(flist, tfile) if not _G.path.exists(tfile) or onmt.utils.FileReader.countLines(tfile, args.idx_files) ~= countLines then table.insert(errors, '* ['.._G.__threadid..'] invalid file - '..tfile..' - not aligned with '..f) error = error + 1 end end if error == 0 then local fdesc = { countLines, flist } fdesc.fname = fprefix fdesc.weight = 0 fdesc.options = {} return _G.__threadid, 0, fdesc else return _G.__threadid, error, errors end end, function(threadid, error, fdesc) if error > 0 then totalError = totalError + error for _, m in ipairs(fdesc) do _G.logger:error(m) end else _G.logger:info(' * ['..threadid..'] Reading files \''..fdesc.fname..'\' - '..fdesc[1]..' sentences') table.insert(list_files, fdesc) totalCount = totalCount + fdesc[1] end end, candf) end end self:poolSynchronize() if totalError > 0 then _G.logger:error('Errors in training directory - fix them first') os.exit(0) end if totalCount == 0 then _G.logger:error('No '..type..' data found in directory \''..dir..'\'') os.exit(0) end _G.logger:info(totalCount..' sentences, in '..#list_files..' files, in '..type..' directory') _G.logger:info('') local keepCount = 0 if #keep_rules > 0 then _G.logger:info('Matching files with keep rules:') for i = 1, #list_files do if list_files[i].weight == 0 then for rule_idx = 1, #keep_rules do if ruleMatch(list_files[i].fname, keep_rules[rule_idx][1]) then keepCount = keepCount + list_files[i][1] list_files[i].rule_idx = rule_idx list_files[i].weight = math.huge list_files[i].options = keep_rules[rule_idx][3] _G.logger:info(" * file '%s' is covered by the keep rule %d", list_files[i].fname, list_files[i].rule_idx or 0) break end end end end _G.logger:info('') -- Files matched with keep rules are not part of the global sampling. totalCount = totalCount - keepCount end if #dist_rules > 0 then _G.logger:info('Matching files with sample rules:') local weight_norm = 0 local weight_rule = {} for i = 1, #list_files do if list_files[i].weight == 0 then for rule_idx = 1, #dist_rules do if ruleMatch(list_files[i].fname, dist_rules[rule_idx][1]) then list_files[i].rule_idx = rule_idx if not weight_rule[rule_idx] then weight_norm = weight_norm + dist_rules[rule_idx][2] weight_rule[rule_idx] = 0 end weight_rule[rule_idx] = weight_rule[rule_idx] + list_files[i][1] break end end end end local sum_weight = 0 for i = 1, #list_files do if list_files[i].rule_idx and list_files[i].weight ~= math.huge then local rule_idx = list_files[i].rule_idx list_files[i].weight = dist_rules[rule_idx][2] / weight_norm * list_files[i][1] / weight_rule[rule_idx] sum_weight = sum_weight + list_files[i].weight list_files[i].options = dist_rules[rule_idx][3] end end for i = 1, #list_files do if list_files[i].weight ~= math.huge then list_files[i].weight = list_files[i].weight / sum_weight if list_files[i].weight > 0 then _G.logger:info(" * file '%s' is covered by the sampling rule %d - uniform weight: %.4f, distribution weight: %.4f", list_files[i].fname, list_files[i].rule_idx or 0, 100 * list_files[i][1] / totalCount, 100 * list_files[i].weight) end end end _G.logger:info('') else for i = 1, #list_files do list_files[i].weight = list_files[i][1] / totalCount end end for i = 1, #list_files do if list_files[i].weight == 0 then _G.logger:warning(" * file '%s' is not covered by any rules and will not be used", list_files[i].fname) end end return totalCount, keepCount, list_files end -- helper functions for threading function Preprocessor:poolAddJob(f, r, ...) if self.pool then self.pool:addjob(f, r, ...) else _G.__threadid = '-' _G.tds = tds r(f(...)) end end function Preprocessor:poolSynchronize() if self.pool then self.pool:synchronize() end end -- initialization of threads and optTok local function init_thread(id, args, optTok, optMPr) _G.paths = require 'paths' _G.path = require 'pl.path' _G.onmt = require 'onmt.init' _G.tds = require 'tds' -- if on-the-fly tokenization _G.separators = require('tools.utils.separators') _G.tokenizer = require('tools.utils.tokenizer') _G.BPE = require ('tools.utils.BPE') _G.bpes = {} _G.optTok = optTok _G.optMPr = optMPr _G.hookManager = onmt.utils.HookManager.new(args, id) _G.args = args for i, v in ipairs(optTok) do if v and v["bpe_model"] and v["bpe_model"] ~= '' then _G.bpes[i] = _G.BPE.new(v) end end end -- parse k=v options from distribution file, and build real key-value based on args local function parseTextOptions(args, optList) local foptions = {} for _, o in ipairs(optList) do local kv = onmt.utils.String.split(o, "=") onmt.utils.Error.assert(#kv==1 or #kv==2, "incorrect option in distribution rules: "..o) -- boolean option if #kv == 1 then table.insert(kv, true) end onmt.utils.Error.assert(args[kv[1]] ~= nil, "option not defined in distribution rules: "..o) if type(args[kv[1]]) == "number" then kv[2]=tonumber(kv[2]) end if type(args[kv[1]]) == "boolean" then kv[2]=kv[2]~="" and kv[2]~="false" end foptions[kv[1]]=kv[2] end foptions.textOpt = table.concat(optList,";"); return foptions end function Preprocessor:__init(args, dataType) tds = require('tds') self.dataType = dataType or 'bitext' self.args = onmt.utils.ExtendedCmdLine.getModuleOpts(args, commonOptions) local options = declareDataOptions(self.dataType) for _, v in ipairs(commonOptions) do table.insert(options, v) end self.args = args local function isempty(t) local count = 0 for _, v in ipairs(t) do if self.args[v] == '' then count = count + 1 end end return count end -- tokenization and preprocessing options local optTok = { {}, {} } local optMPr = { {}, {} } for k, v in pairs(args) do if k:sub(1,4) == 'tok_' then local idx = 1 if k:sub(5, 8) == 'tgt_' then idx = 2 k = k:sub(9) elseif k:sub(5,8) == 'src_' then k = k:sub(9) else k = k:sub(5) end optTok[idx][k] = v end if k:sub(1,4) == 'mpr_' then local idx = 1 if k:sub(5, 8) == 'tgt_' then idx = 2 k = k:sub(9) elseif k:sub(5,8) == 'src_' then k = k:sub(9) else k = k:sub(5) end optMPr[idx][k] = v end end for i = 1, 2 do _G.logger:info("Using on-the-fly '%s' tokenization for input "..i, optTok[i]["mode"]) end if args.preprocess_pthreads > 1 and args.train_dir ~= '' then local globalLogger = _G.logger -- try to load threads if available threads = require('threads') threads.Threads.serialization('threads.sharedserialize') self.pool = threads.Threads( args.preprocess_pthreads, function(id) init_thread(id, args, optTok, optMPr) end, function() _G.logger = globalLogger end ) else init_thread("-", args, optTok, optMPr) end -- sanity check on options: train_dir is exclusive all direct file settings -- and for train_dir, we do need pre-build vocabulary if dataType == 'monotext' then self.trains = { 'train' } self.valids = { 'valid' } self.vocabs = { 'vocab' } else self.trains = { 'train_src', 'train_tgt' } self.valids = { 'valid_src', 'valid_tgt' } self.vocabs = { 'src_vocab', 'tgt_vocab' } end self.dist_rules = {} self.keep_rules = {} if args.gsample_dist ~= '' then local f = io.input(args.gsample_dist) while true do local dist_rule = f:read() if not dist_rule then break end local trule = onmt.utils.String.split(dist_rule, " ") local pattern = trule[1] local weight = trule[2] table.remove(trule,1) table.remove(trule,1) trule = { pattern, weight, parseTextOptions(args, trule) } if trule[2] == "*" then table.insert(self.keep_rules, trule) else table.insert(self.dist_rules, trule) end end end -- list and check training files if args.train_dir ~= '' then onmt.utils.Error.assert(isempty(self.trains) == #self.trains, 'For directory mode, file mode options (training) should not be set') if not args.dry_run then onmt.utils.Error.assert(isempty(self.vocabs) == 0, 'For directory mode, vocabs should be predefined') end self.totalCount, self.keepCount, self.list_train = self:parseDirectory(self.args, Preprocessor.getDataList(self.dataType), self.dist_rules, self.keep_rules, 'train') else onmt.utils.Error.assert(isempty(self.trains) == 0) self.totalCount = onmt.utils.FileReader.countLines(self.args[self.trains[1]], args.idx_files) self.keepCount = 0 local list_files = { self.args[self.trains[1]] } for i = 2, #self.trains do table.insert(list_files, args[self.trains[i]]) if not args.idx_files then onmt.utils.Error.assert(onmt.utils.FileReader.countLines(args[self.trains[i]], args.idx_files) == self.totalCount, "line count in "..args[self.trains[i]].." do not match "..args[self.trains[1]]) end end self.list_train = { { self.totalCount, list_files } } self.list_train[1].fname = self.args[self.trains[1]] self.list_train[1].weight = 1 self.list_train[1].options = {} end if args[self.valids[1]] ~= '' then self.list_valid = { {onmt.utils.FileReader.countLines(args[self.valids[1]], args.idx_files), {args[self.valids[1]]}}} for i = 2, #self.valids do if not args.idx_files then onmt.utils.Error.assert(onmt.utils.FileReader.countLines(args[self.valids[i]], args.idx_files) == self.list_valid[1][1], "line count in "..args[self.valids[i]].." do not match "..args[self.valids[1]]) end table.insert(self.list_valid[1][2], args[self.valids[i]]) end self.list_valid[1].fname = self.args[self.valids[1]] self.list_valid[1].weight = 1 self.list_valid[1].options = {} end end --[[ Process on given tokenized sentence - check for validity and prepare structure ]] local function processSentence(n, idx, tokens, parallelCheck, isValid, isInputVector, dicts, constants, prunedRatio, generateFeatures, time_shift_feature, sentenceDists, vectors, features, avgLength, sizes, src_seq_length, tgt_seq_length) local ignored = 0 for i = 1, n do local length = (type(tokens[i])=='table' and #tokens[i]) or (tokens[i]:dim()==0 and 0) or tokens[i]:size(1) local idxRange = math.floor(length/10)+1 if idxRange > #sentenceDists[i] then idxRange = #sentenceDists[i] end sentenceDists[i][idxRange] = sentenceDists[i][idxRange]+1 end local valid = true if parallelCheck then valid = parallelCheck(idx, isInputVector, dicts, tokens) end if valid and isValid(tokens, src_seq_length, tgt_seq_length) then for i = 1, n do local length = (type(tokens[i])=='table' and #tokens[i]) or (tokens[i]:dim()==0 and 0) or tokens[i]:size(1) avgLength[i] = avgLength[i] * (#vectors[i] / (#vectors[i] + 1)) + length / (#vectors[i] + 1) if isInputVector[i] then vectors[i]:insert(tokens[i]) else local words, feats = onmt.utils.Features.extract(tokens[i]) local vocabs = onmt.utils.Placeholders.norm(words) local vec = dicts[i].words:convertToIdx(vocabs, table.unpack(constants[i])) local pruned = vec:eq(onmt.Constants.UNK):sum() / vec:size(1) prunedRatio[i] = prunedRatio[i] * (#vectors[i] / (#vectors[i] + 1)) + pruned / (#vectors[i] + 1) vectors[i]:insert(vec) if not(isInputVector[i]) and #dicts[i].features > 0 then features[i]:insert(generateFeatures[i](dicts[i].features, feats, true, time_shift_feature)) end end if i == 1 then sizes:insert(length) end end else ignored = 1 end return ignored end --[[ Generic data preparation function on multiples source * `files`: table of data source name * `isInputVector`: table of boolean indicating if corresponding source is an vector * `dicts`: table of dictionary data corresponding to source * `nameSources`: table of name of each source - for logging purpose * `constants`: constant to add to the vocabulary for each source * `isValid`: validation function taking prepared table of tokens from each source * `generateFeatures`: table of feature extraction fucnction for each source * `parallelCheck`: function to check parallely source/target(s) * `sample_file`: possible torch mapping vector ]] function Preprocessor:makeGenericData(files, isInputVector, dicts, nameSources, constants, isValid, generateFeatures, parallelCheck, sample_file) local verbose = _G.logger.level == 'DEBUG' sample_file = sample_file or {} local n = #files[1][2] local gSentenceDists = {} local gVectors = {} local gFeatures = {} local gAvgLength = {} local gSizes = tds.Vec() local gCount = 0 local gIgnored = 0 local gEmptyCount = 0 for _ = 1, n do table.insert(gSentenceDists, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}) table.insert(gVectors, tds.Vec()) table.insert(gFeatures, tds.Vec()) table.insert(gAvgLength, 0) end -- iterate on each file for _m, _df in ipairs(files) do self:poolAddJob( function(df, idx_files, time_shift_feature, src_seq_length, tgt_seq_length, sampling) local count = 0 local ignored = 0 local emptyCount = 0 local sentenceDists = {} local vectors = {} local features = {} local avgLength = {} local sizes = _G.tds.Vec() for _ = 1, n do table.insert(sentenceDists, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}) table.insert(vectors, _G.tds.Vec()) table.insert(features, _G.tds.Vec()) table.insert(avgLength, 0) end -- if there is a sampling for this file local readers = {} local prunedRatio = {} for i = 1, n do table.insert(readers, onmt.utils.FileReader.new(df[2][i], idx_files, isInputVector[i])) table.insert(prunedRatio, 0) end if idx_files then local maps = {} for i = 1, n do table.insert(maps, {}) while true do local tokens, idx = readers[i]:next() if not tokens then break end if maps[i][idx] then return _G.__threadid, 1, string.format('duplicate idx in %s file: '..idx, nameSources[i]) end if i > 1 and not maps[1][idx] then return _G.__threadid, 1, string.format('%s Idx not defined in %s: '..idx, nameSources[i], nameSources[1]) end if isInputVector[i] then maps[i][idx] = torch.Tensor(tokens) else maps[i][idx] = tokens end end end for k,_ in pairs(maps[1]) do local tokens = {} local hasNil = false for i = 1, n do hasNil = hasNil or maps[i][k] == nil table.insert(tokens, maps[i][k]) end if not hasNil then ignored = ignored + processSentence(n, k, tokens, parallelCheck, isValid, isInputVector, dicts, constants, prunedRatio, generateFeatures, time_shift_feature, sentenceDists, vectors, features, avgLength, sizes, src_seq_length, tgt_seq_length) count = count + 1 else emptyCount = emptyCount + 1 end end else local idx = 1 local sampling_idx = 1 local hasNil = false -- read all the available sentences or as long as we have not reached sampling size -- sampling table is an ordered sentence of sentences id to keep while not hasNil and (not sampling or sampling_idx <= #sampling) do -- keep in sentences the different sentences and number of times it repeats local sentences = { {} } for _ = 1, n do table.insert(sentences, {}) end -- keep maximum a batch of 10000 sentences while not hasNil and (not sampling or sampling_idx <= #sampling) and #sentences[1] < preprocess_batchsize do local allNil = true local keepSentence = not sampling or sampling[sampling_idx] == idx for i = 1, n do local sentence = readers[i]:next(false) hasNil = hasNil or sentence == nil allNil = allNil and sentence == nil if sentence and keepSentence then table.insert(sentences[i+1], sentence) end end if hasNil then if not allNil then return _G.__threadid, 1, string.format('all data sources do not have the same number of sentences') end break end local repeatSentence = 1 if sampling then while sampling_idx+repeatSentence <= #sampling and sampling[sampling_idx+repeatSentence] == idx do repeatSentence = repeatSentence + 1 end end if keepSentence then if sampling then sampling_idx = sampling_idx + repeatSentence end table.insert(sentences[1], repeatSentence) end idx = idx + 1 end if #sentences[1] > 0 then -- preprocess and tokenize for i = 1, n do -- adapt local options local savOpt = {} for k, v in pairs(df.options or {}) do savOpt[k] = _G.optMPr[i][k] _G.optMPr[i][k] = v end local psentences = _G.hookManager:call("mpreprocess", _G.optMPr[i], sentences[i+1]) if psentences then sentences[i+1] = psentences end -- restore options for k, _ in pairs(df.options or {}) do _G.optMPr[i][k] = savOpt[k] end end if n == 2 then local asentences = { sentences[2], sentences[3] } -- adapt local options local savOpt = {} for k, v in pairs(df.options or {}) do savOpt[k] = _G.args[k] _G.args[k] = v end local psentences = _G.hookManager:call("bpreprocess", _G.args, asentences) if psentences then if verbose then _G.logger:info("bpreprocess results: %d remaining out of %d", #psentences[1], #sentences[2]) end sentences[2] = psentences[1] sentences[3] = psentences[2] end -- restore options for k, _ in pairs(df.options or {}) do _G.args[k] = savOpt[k] end end for i = 1, n do for j = 1, #sentences[i+1] do sentences[i+1][j] = _G.tokenizer.tokenize(_G.optTok[i], sentences[i+1][j], _G.bpes[i]) end end for j = 1, #sentences[2] do local tokens = {} for i = 1, n do table.insert(tokens, sentences[i+1][j]) if verbose then _G.logger:debug("[%d:%d] %s", j, i, table.concat(tokens[i], " ")) end end for _ = 1, sentences[1][j] do ignored = ignored + processSentence(n, idx, tokens, parallelCheck, isValid, isInputVector, dicts, constants, prunedRatio, generateFeatures, time_shift_feature, sentenceDists, vectors, features, avgLength, sizes, src_seq_length, tgt_seq_length) count = count + 1 end end end end end for i = 1, n do readers[i]:close() end return _G.__threadid, false, sentenceDists, vectors, features, avgLength, sizes, prunedRatio, count, ignored, emptyCount, sampling and #sampling or _df[1] end, -- aggregate the results together function(__threadid, error, sentenceDists, vectors, features, avgLength, sizes, prunedRatio, count, ignored, emptyCount, kept) if error then _G.logger:error(sentenceDists) os.exit(1) end for i = 1, n do for j=1, #gSentenceDists[i] do gSentenceDists[i][j] = gSentenceDists[i][j] + sentenceDists[i][j] end for j=1, #vectors[i] do gVectors[i]:insert(vectors[i][j]) end for j=1, #features[i] do gFeatures[i]:insert(features[i][j]) end gAvgLength[i] = (gAvgLength[i] * (#gVectors[i]-#vectors[i]) + avgLength[i] * #vectors[i])/#gVectors[i] end for j=1, #sizes do gSizes:insert(sizes[j]) end local msgPrune = '' for i = 1, n do msgPrune = msgPrune .. (i==1 and '' or ', ') msgPrune = msgPrune .. nameSources[i] .. ' = '..string.format("%.1f%%", prunedRatio[i] * 100) end _G.logger:info(' * ['..__threadid..'] file \'%s\' (%s): %d total, %d drawn, %d kept - unknown words: %s', _df.fname or "n/a", (_df.options and _df.options.textOpt) or '', _df[1], kept, #vectors[1], msgPrune) gCount = gCount + count gIgnored = gIgnored + ignored gEmptyCount = gEmptyCount + emptyCount end, _df, self.args.idx_files, self.args.time_shift_feature, self.args.src_seq_length or self.args.seq_length, self.args.tgt_seq_length, sample_file[_m]) end self:poolSynchronize() for i = 1, n do for j=1, #gSentenceDists[i] do gSentenceDists[i][j] = gSentenceDists[i][j] / gCount end end local function reorderData(perm) for i = 1, n do gVectors[i] = onmt.utils.Table.reorder(gVectors[i], perm, true, isInputVector and isInputVector[i]) if not(isInputVector[i]) and #dicts[i].features > 0 then gFeatures[i] = onmt.utils.Table.reorder(gFeatures[i], perm, true) end end end onmt.utils.Error.assert(#gVectors[1] > 0, "empty dataset") if self.args.shuffle then _G.logger:info('... shuffling sentences') local perm = torch.randperm(#gVectors[1]) gSizes = onmt.utils.Table.reorder(gSizes, perm, true) reorderData(perm) end if self.args.sort then _G.logger:info('... sorting sentences by size') local _, perm = torch.sort(vecToTensor(gSizes)) reorderData(perm) end _G.logger:info('Prepared %d sentences:', #gVectors[1]) _G.logger:info(' * %d sequences not validated (length, other)', gIgnored) local msgLength = '' for i = 1, n do msgLength = msgLength .. (i==1 and '' or ', ') msgLength = msgLength .. nameSources[i] .. ' = '..string.format("%.1f", gAvgLength[i]) end _G.logger:info(' * average sequence length: '..msgLength) local data = {} for i = 1, n do local dist='[ ' for j = 1, #gSentenceDists[1] do if j>1 then dist = dist..' ; ' end dist = dist..math.floor(gSentenceDists[i][j]*100)..'%%' end dist = dist..' ]' _G.logger:info(' * %s sentence length (range of 10): '..dist, nameSources[i]) if isInputVector[i] then table.insert(data, { vectors = gVectors[i], features = gFeatures[i] }) else table.insert(data, { words = gVectors[i], features = gFeatures[i] }) end end return data end --[[ Check data validity ]] local function isValid(seq, maxSeqLength) if torch.isTensor(seq) then return seq:size(1) > 0 and seq:size(1) <= maxSeqLength end return #seq > 0 and #seq <= maxSeqLength end local function validBilingual(tokens, src_seq_length, tgt_seq_length) return #tokens[1] > 0 and isValid(tokens[1], src_seq_length) and #tokens[2] > 0 and isValid(tokens[2], tgt_seq_length) end function Preprocessor:makeBilingualData(files, srcDicts, tgtDicts, sample_file) local data = self:makeGenericData( files, { false, false }, { srcDicts, tgtDicts }, { 'source', 'target' }, { { onmt.Constants.UNK_WORD }, { onmt.Constants.UNK_WORD, onmt.Constants.BOS_WORD, onmt.Constants.EOS_WORD } }, validBilingual, { onmt.utils.Features.generateSource, onmt.utils.Features.generateTarget }, self.args.check_plength and self.parallelCheck, sample_file) return data[1], data[2] end local function validFeat(tokens, src_seq_length, tgt_seq_length) return tokens[1]:dim() > 0 and isValid(tokens[1], src_seq_length) and #tokens[2] > 0 and isValid(tokens[2], tgt_seq_length) end function Preprocessor:makeFeatTextData(files, tgtDicts, sample_file) local data = self:makeGenericData( files, { true, false }, { {}, tgtDicts }, { 'source', 'target' }, { false, { onmt.Constants.UNK_WORD, onmt.Constants.BOS_WORD, onmt.Constants.EOS_WORD } }, validFeat, { false, onmt.utils.Features.generateTarget }, self.args.check_plength and self.parallelCheck, sample_file) return data[1], data[2] end local function ValidMono(tokens, seq_length) return #tokens[1] > 0 and isValid(tokens[1], seq_length) end function Preprocessor:makeMonolingualData(files, dicts, sample_file) local data = self:makeGenericData( files, { false }, { dicts }, { 'source' }, { { onmt.Constants.UNK_WORD, onmt.Constants.BOS_WORD, onmt.Constants.EOS_WORD } }, ValidMono, { onmt.utils.Features.generateTarget }, nil, sample_file) return data[1] end function Preprocessor.parallelCheck(idx, _, _, tokens) local length1 = (type(tokens[1])=='table' and #tokens[1]) or (tokens[1]:dim()==0 and 0) or tokens[1]:size(1) local length2 = (type(tokens[2])=='table' and #tokens[2]) or (tokens[2]:dim()==0 and 0) or tokens[2]:size(1) if length1~=length2 then _G.logger:warning('SENT %s: source/target not aligned (%d/%d)', tostring(idx), length1, length2) return false end return true end function Preprocessor:getVocabulary() local dicts = {} -- use the first source file to count source features local src_file = self.list_train[1][2][1] if self.dataType ~= 'feattext' then dicts.src = onmt.data.Vocabulary.init('source', src_file, self.args.src_vocab or self.args.vocab, self.args.src_vocab_size or self.args.vocab_size, self.args.src_words_min_frequency or self.args.words_min_frequency, self.args.features_vocabs_prefix, function(s) return isValid(s, self.args.src_seq_length or self.args.seq_length) end, self.args.keep_frequency, self.args.idx_files, self.args.tok_src_case_feature) end if self.dataType ~= 'monotext' then -- use the first target file to count target features local tgt_file = self.list_train[1][2][2] dicts.tgt = onmt.data.Vocabulary.init('target', tgt_file, self.args.tgt_vocab, self.args.tgt_vocab_size, self.args.tgt_words_min_frequency, self.args.features_vocabs_prefix, function(s) return isValid(s, self.args.tgt_seq_length) end, self.args.keep_frequency, self.args.idx_files, self.args.tok_tgt_case_feature) end return dicts end function Preprocessor:makeData(dataset, dicts) if dataset ~= 'valid' or (self.args.valid and self.args.valid ~= '') or (self.args.valid_src and self.args.valid_src ~= '') or (self.args.valid_tgt and self.args.valid_tgt ~= '') then _G.logger:info("--- Preparing "..dataset.." sample") local sample_file = {} if dataset == 'train' and self.args.gsample ~= 0 then -- sample data using sample and sample_dict local sampledCount = self.args.gsample if sampledCount < 1 then sampledCount = sampledCount * self.totalCount else sampledCount = sampledCount - self.keepCount end if self.totalCount == 0 and self.keepCount < self.args.gsample then _G.logger:warning('You requested a sample of %d sentences but no files matched any sampling rules and only %d sentences are selected by keep rules. There could be issues with your distribution rules.', self.args.gsample, self.keepCount) end if sampledCount < 0 then _G.logger:error('You requested a sample of %d sentences but %d are already reserved by keep rules. You should configure a larger sample or keep less sentences.', self.args.gsample, self.keepCount) os.exit(1) end -- check how many sentences per file for _, f in ipairs(self.list_train) do if f.weight == math.huge then table.insert(sample_file, tds.Vec(torch.range(1, f[1]):totable())) else local n = math.ceil(sampledCount * f.weight) local t = torch.LongTensor(n) if n > 0 then for i = 1, n do t[i] = torch.random(1, f[1]) end t = torch.sort(t) end table.insert(sample_file, tds.Vec(t:totable())) end end end local data = {} if self.dataType == 'monotext' then data.src = self:makeMonolingualData(self["list_"..dataset], dicts.src, sample_file) elseif self.dataType == 'feattext' then data.src, data.tgt = self:makeFeatTextData(self["list_"..dataset], dicts.tgt, sample_file) if not dicts.srcInputSize then dicts.srcInputSize = data.src.vectors[1]:size(2) else onmt.utils.Error.assert(dicts.srcInputSize==data.src.vectors[1]:size(2), "feature size is not matching in all files") end else data.src, data.tgt = self:makeBilingualData(self["list_"..dataset], dicts.src, dicts.tgt, sample_file) end _G.logger:info("") return data else _G.logger:warning('No validation data') end end return Preprocessor
data = '{"entity_id": "switch.macbook_power"}' headers = {} headers["x-ha-access"] = "your_password" local sleepWatcher = hs.caffeinate.watcher.new(function (eventType) if (eventType == hs.caffeinate.watcher.systemDidWake) then hs.notify.show("Wake sequence initiated!", "", "") hs.http.post("http://192.168.0.100:8123/api/services/switch/turn_on", data, headers) elseif (eventType == hs.caffeinate.watcher.systemWillSleep) then hs.notify.show("Bye!", "", "") hs.http.post("http://192.168.0.100:8123/api/services/switch/turn_off", data, headers) end end) sleepWatcher:start()
--[[ Name: "sv_hooks.lua". Product: "HL2 RP". --]] local MOUNT = MOUNT; -- Called just after a player spawns. function MOUNT:PostPlayerSpawn(player, lightSpawn, changeVocation, firstSpawn) if (!lightSpawn) then self:MakePlayerExitStance(player, true); end; end; -- Called when a player spawns lightly. function MOUNT:PostPlayerLightSpawn(player, weapons, ammo, special) self:MakePlayerExitStance(player); end; -- Called when a player has been ragdolled. function MOUNT:PlayerRagdolled(player, state, ragdoll) self:MakePlayerExitStance(player, true); end; -- Called at an interval while a player is connected. function MOUNT:PlayerThink(player, curTime, infoTable) local forcedAnimation = player:GetForcedAnimation(); -- Check if a statement is true. if ( forcedAnimation and self.stances[forcedAnimation.animation] ) then if (player._StanceLocation) then if (player:GetPos():Distance(player._StanceLocation) > 16) then player._StanceLocation = nil; player._StancePosition = nil; -- Set some information. player:SetForcedAnimation(false); player:SetSharedVar("ks_Stance", false); player:Freeze(false); end; end; -- Set some information. return true; elseif ( player:GetSharedVar("ks_Stance") ) then player:SetSharedVar("ks_Stance", false); end; end; -- Called when a player starts to move. function MOUNT:Move(player, moveData) local forcedAnimation = player:GetForcedAnimation(); -- Check if a statement is true. if ( forcedAnimation and self.stances[forcedAnimation.animation] ) then player:DrawViewModel(false); -- Return true to break the function. return true; end; end; -- Called when the player attempts to be ragdolled. function MOUNT:PlayerCanRagdoll(player, state, delay, decay, ragdoll) local forcedAnimation = player:GetForcedAnimation(); -- Check if a statement is true. if ( forcedAnimation and self.stances[forcedAnimation.animation] ) then if ( player:Alive() ) then return false; end; end; end; -- Called when a player attempts to NoClip. function MOUNT:PlayerNoClip(player) local forcedAnimation = player:GetForcedAnimation(); -- Check if a statement is true. if ( forcedAnimation and self.stances[forcedAnimation.animation] ) then return false; end; end;
depends_on("Non_existant")
function onCreate() setProperty('health', getProperty('health') + 1); debugPrint("Welcome to hell") end function opponentNoteHit() cameraShake(game, 0.05, 0.1); end
local _={} _.name="BirchTree" _.new=function(options) local result=BaseEntity.new() Entity.setSprite(result,"birch_tree_1") result.isDrawable=true result.growPhase=1 result.isActive=false result.originX=8 result.originY=15 Taggable.addTag(result,"tree") Entity.afterCreated(result,_,options) return result end _.draw=BaseEntity.draw _.getSpriteForGrowPhase=function(phase) if phase==1 then return "birch_tree_1" end if phase==2 then return "birch_tree_2" end if phase==3 then return "birch_tree_3" end if phase==4 then return "birch_tree_4" end if phase==5 then return "birch_tree_5" end return nil end if Session.isServer then _.slowUpdate=function(entity) -- log("birch tree slow update") -- можно попробовать на активации на сервере вешаться на какой либо медленный таймер local rnd=Lume.random() if rnd>0.9 then GrowableBehaviour.grow(entity) end end end return _
local data = [[ compat/( accessx basic caps complete iso9995 japan ledcaps ledcompose lednum ledscroll level5 misc mousekeys olpc pc pc98 xfree86 xtest README ) geometry/( digital_vndr/(lk pc unix) sgi_vndr/(indigo indy O2) amiga ataritt chicony dell everex fujitsu hhk hp keytronic kinesis macintosh microsoft nec nokia northgate pc sanwa sony thinkpad sun teck steelseries typematrix winbook README ) keycodes/( digital_vndr/(lk pc) sgi_vndr/(indigo indy iris) aliases amiga ataritt empty evdev fujitsu hp ibm jolla macintosh olpc sony sun xfree86 xfree98 README ) rules/( xfree98 xkb.dtd README ) symbols/( digital_vndr/(lk pc us vt) fujitsu_vndr/(jp us) hp_vndr/(us) jolla_vndr/(sbj) macintosh_vndr/( apple ch de dk fi fr gb is it jp latam nl no pt se us ) nec_vndr/(jp) nokia_vndr/(rx-44 rx-51 su-8w) sgi_vndr/(jp) sharp_vndr/(sl-c3x00 ws003sh ws007sh ws011sh ws020sh) sony_vndr/(us) sun_vndr/( ara be br ca ch cz de dk ee es fi fr gb gr it jp kr lt lv nl no pl pt ro ru se sk solaris tr tw ua us ) xfree68_vndr/(amiga ataritt) af al am apl ara at au az ba bd be bg br brai bt bw by ca cd ch cm cn cz de dk dz ee eg es et epo eu fi fo fr gb ge gh gn gr hr hu id ie il in iq ir is it jp jv ke kg kh kr kz la latam latin lk lt lv ma mao md me mk ml mm mn mt mv my ng nl no np parens pc ph pk pl pt ro rs ru se si sk sn sy th terminate tg tj tm tr trans tw tz ua us uz vn za altwin capslock compose ctrl empty eurosign rupeesign group inet keypad kpdl level2 level3 level5 nbsp olpc shift srvr_ctrl typo ) types/( basic cancel caps complete default extra iso9995 level5 mousekeys nokia numpad pc README ) ]] for f in iterpaths(data) do file('share/xkb/'..f, '644', '$srcdir/'..f) end local function parts(ruleset) return expand{'$srcdir/rules/', { '0000-hdr.part', '0001-lists.part', '0002-'..ruleset..'.lists.part', '0004-'..ruleset..'.m_k.part', '0005-l1_k.part', '0006-l_k.part', '0007-o_k.part', '0008-ml_g.part', '0009-m_g.part', '0011-mlv_s.part', '0013-ml_s.part', '0015-ml1_s.part', '0018-ml2_s.part ', '0020-ml3_s.part ', '0022-ml4_s.part ', '0026-'..ruleset..'.m_s.part', '0027-'..ruleset..'.ml_s1.part', '0033-ml_c.part', '0034-ml1_c.part', '0035-m_t.part', '0036-lo_s.part', '0037-l1o_s.part', '0038-l2o_s.part', '0039-l3o_s.part', '0040-l4o_s.part', '0042-o_s.part', '0043-o_c.part', '0044-o_t.part', }} end build('cat', '$outdir/base', parts('base')) file('share/xkb/rules/base', '644', '$outdir/base') build('cat', '$outdir/evdev', parts('evdev')) file('share/xkb/rules/evdev', '644', '$outdir/evdev') fetch 'git'
function leye (N) local C = torch.zeros(1,N) for i=1,N do C[{1,i}]=i end return newlm(C,N) end
luaarrys = {} function luaarrys.solve(arr) if #arr < 3 then return 0 end local tops = { arr[1], arr[2] } -- array to hold the largest 2 elements table.sort(tops) for i = 3,#arr do local it = arr[i] if it > tops[2] then tops[1] = tops[2] tops[2] = it elseif it > tops[1] then tops[1] = it end end -- count the number of elements less than the 2-largest element local count = 0 for i = 1, #arr do if arr[i] < tops[1] then count = count + 1 end end return count end return luaarrys
object_building_mustafar_structures_must_uplink_bunker_entrance_door = object_building_mustafar_structures_shared_must_uplink_bunker_entrance_door:new { } ObjectTemplates:addTemplate(object_building_mustafar_structures_must_uplink_bunker_entrance_door, "object/building/mustafar/structures/must_uplink_bunker_entrance_door.iff")
_G.requireInjector() local Config = require('config') local Event = require('event') local itemDB = require('itemDB') local Socket = require('socket') local Terminal = require('terminal') local UI = require('ui') local Util = require('util') local colors = _G.colors local fs = _G.fs local multishell = _ENV.multishell local network = _G.network local os = _G.os local shell = _ENV.shell local term = _G.term UI.Button.defaults.focusIndicator = ' ' UI:configure('Turtles', ...) local config = { } Config.load('Turtles', config) local options = { turtle = { arg = 'i', type = 'number', value = config.id or -1, desc = 'Turtle ID' }, tab = { arg = 's', type = 'string', value = config.tab or 'Sel', desc = 'Selected tab to display' }, help = { arg = 'h', type = 'flag', value = false, desc = 'Displays the options' }, } local SCRIPTS_PATH = 'packages/core/etc/scripts' local nullTerm = Terminal.getNullTerm(term.current()) local socket local page = UI.Page { coords = UI.Window { backgroundColor = colors.black, height = 4, }, tabs = UI.Tabs { x = 1, y = 5, ey = -2, scripts = UI.ScrollingGrid { tabTitle = 'Run', backgroundColor = UI.TabBar.defaults.selectedBackgroundColor, columns = { { heading = '', key = 'label' }, }, disableHeader = true, sortColumn = 'label', autospace = true, }, turtles = UI.ScrollingGrid { tabTitle = 'Select', backgroundColor = UI.TabBar.defaults.selectedBackgroundColor, columns = { { heading = 'label', key = 'label' }, { heading = 'Dist', key = 'distance' }, { heading = 'Status', key = 'status' }, { heading = 'Fuel', key = 'fuel' }, }, disableHeader = true, sortColumn = 'label', autospace = true, }, inventory = UI.ScrollingGrid { backgroundColor = UI.TabBar.defaults.selectedBackgroundColor, tabTitle = 'Inv', columns = { { heading = '', key = 'index', width = 2 }, { heading = '', key = 'qty', width = 2 }, { heading = 'Inventory', key = 'id', width = UI.term.width - 7 }, }, disableHeader = true, sortColumn = 'index', }, --[[ policy = UI.ScrollingGrid { tabTitle = 'Mod', backgroundColor = UI.TabBar.defaults.selectedBackgroundColor, columns = { { heading = 'label', key = 'label' }, }, values = policies, disableHeader = true, sortColumn = 'label', autospace = true, }, ]] action = UI.Window { tabTitle = 'Action', backgroundColor = UI.TabBar.defaults.selectedBackgroundColor, moveUp = UI.Button { x = 5, y = 2, text = 'up', fn = 'turtle.up', }, moveDown = UI.Button { x = 5, y = 4, text = 'dn', fn = 'turtle.down', }, moveForward = UI.Button { x = 9, y = 3, text = 'f', fn = 'turtle.forward', }, moveBack = UI.Button { x = 2, y = 3, text = 'b', fn = 'turtle.back', }, turnLeft = UI.Button { x = 2, y = 6, text = 'lt', fn = 'turtle.turnLeft', }, turnRight = UI.Button { x = 8, y = 6, text = 'rt', fn = 'turtle.turnRight', }, info = UI.TextArea { x = 2, y = 9, inactive = true, } }, }, statusBar = UI.StatusBar(), notification = UI.Notification(), accelerators = { q = 'quit', }, } function page:enable(turtle) self.turtle = turtle UI.Page.enable(self) end function page:runFunction(script, nowrap) for _ = 1, 2 do if not socket then socket = Socket.connect(self.turtle.id, 161) end if socket then if not nowrap then script = 'turtle.run(' .. script .. ')' end if socket:write({ type = 'scriptEx', args = script }) then local t = socket:read(3) if t then return table.unpack(t) end return false, 'Socket timeout' end end socket = nil end self.notification:error('Unable to connect') end function page:runScript(scriptName) if self.turtle then self.notification:info('Connecting') self:sync() local cmd = string.format('Script %d %s', self.turtle.id, scriptName) local ot = term.redirect(nullTerm) pcall(function() shell.run(cmd) end) term.redirect(ot) self.notification:success('Sent') end end function page.coords:draw() local t = self.parent.turtle self:clear() if t then self:setCursorPos(2, 2) local ind = 'GPS' if not t.point.gps then ind = 'REL' end self:print(string.format('%s : %d,%d,%d\n Fuel: %s\n', ind, t.point.x, t.point.y, t.point.z, Util.toBytes(t.fuel))) end end --[[ Inventory Tab ]]-- function page.tabs.inventory:getRowTextColor(row, selected) if page.turtle and row.selected then return colors.yellow end return UI.ScrollingGrid.getRowTextColor(self, row, selected) end function page.tabs.inventory:draw() local t = page.turtle Util.clear(self.values) if t then for _,v in ipairs(t.inventory) do if v.qty > 0 then table.insert(self.values, v) if v.index == t.slotIndex then v.selected = true end if v.id then v.id = itemDB:getName(v) end end end end self:adjustWidth() self:update() UI.ScrollingGrid.draw(self) end function page.tabs.inventory:eventHandler(event) if event.type == 'grid_select' then local fn = string.format('turtle.select(%d)', event.selected.index) page:runFunction(fn) else return UI.ScrollingGrid.eventHandler(self, event) end return true end function page.tabs.scripts:draw() Util.clear(self.values) local files = fs.list(SCRIPTS_PATH) for _,path in pairs(files) do table.insert(self.values, { label = path, path = fs.combine(SCRIPTS_PATH, path) }) end self:update() UI.ScrollingGrid.draw(self) end function page.tabs.scripts:eventHandler(event) if event.type == 'grid_select' then page:runScript(event.selected.label) else return UI.ScrollingGrid.eventHandler(self, event) end return true end function page.tabs.turtles:getDisplayValues(row) row = Util.shallowCopy(row) if row.fuel then row.fuel = Util.toBytes(row.fuel) end if row.distance then row.distance = Util.round(row.distance, 1) end return row end function page.tabs.turtles:draw() Util.clear(self.values) for _,v in pairs(network) do if v.fuel then table.insert(self.values, v) end end self:update() UI.ScrollingGrid.draw(self) end function page.tabs.turtles:eventHandler(event) if event.type == 'grid_select' then page.turtle = event.selected config.id = event.selected.id Config.update('Turtles', config) multishell.setTitle(multishell.getCurrent(), page.turtle.label) if socket then socket:close() socket = nil end else return UI.ScrollingGrid.eventHandler(self, event) end return true end function page.statusBar:draw() local t = self.parent.turtle if t then local status = string.format('%s [ %s ]', t.status, Util.round(t.distance, 2)) self:setStatus(status, true) end UI.StatusBar.draw(self) end function page:showBlocks() local script = [[ local function inspect(direction) local s,b = turtle['inspect' .. (direction or '')]() if not s then return 'minecraft:air:0' end return string.format('%s:%d', b.name, b.metadata) end local bu, bf, bd = inspect('Up'), inspect(), inspect('Down') return string.format('%s\n%s\n%s', bu, bf, bd) ]] local s, m = self:runFunction(script, true) self.tabs.action.info:setText(s or m) end function page:eventHandler(event) if event.type == 'quit' then UI:exitPullEvents() elseif event.type == 'tab_select' then config.tab = event.button.text Config.update('Turtles', config) elseif event.type == 'button_press' then if event.button.fn then self:runFunction(event.button.fn, event.button.nowrap) self:showBlocks() elseif event.button.script then self:runScript(event.button.script) end else return UI.Page.eventHandler(self, event) end return true end function page:enable() UI.Page.enable(self) -- self.tabs:activateTab(page.tabs.turtles) end if not Util.getOptions(options, { ... }, true) then return end if options.turtle.value >= 0 then for _ = 1, 10 do page.turtle = _G.network[options.turtle.value] if page.turtle then break end os.sleep(1) end end Event.onInterval(1, function() if page.turtle then local t = _G.network[page.turtle.id] page.turtle = t page:draw() page:sync() end end) if config.tab then page.tabs.tabBar:selectTab(config.tab) end UI:setPage(page) UI:pullEvents()
TetrisConf = { Left = 0, Right = 36, Top = 36, Interval = 3, Buffer = 3, Direction = Vector3(0, 0, -1), MovementRate = 1, SpawnDelay = 20, Blocks = { "Objects/CornerRoomBlock.xml", "Objects/CornerRoomBlock2.xml", "Objects/CornerRoomBlock3.xml", "Objects/CornerRoomBlock4.xml", "Objects/CornerRoomBlock5.xml", "Objects/CornerRoomBlock6.xml", "Objects/CornerRoomBlock7.xml", "Objects/CornerRoomBlock8.xml", "Objects/CornerRoomBlock9.xml", "Objects/CornerRoomBlock10.xml", "Objects/LineRoomBlock.xml", "Objects/LineRoomBlock2.xml", "Objects/LineRoomBlock3.xml", "Objects/LineRoomBlock4.xml", "Objects/SquareRoomBlock.xml", "Objects/SquareRoomBlock2.xml" }, SpawnNewRoom = function (scene) log:Write("Spawning new room") local count = 0 for k, v in pairs(TetrisConf.Blocks) do count = count + 1 end local roomIndex = RandomInt(1, count + 1) scene:InstantiateXML( cache:GetResourceFileName(TetrisConf.Blocks[roomIndex]), Vector3(-TetrisConf.Right, 0, -TetrisConf.Right), Quaternion() ) end }
{["rednet"]=true,["userAuth"]="125}_/%22222222222",["user"]="Carg",["version"]="v0.1",}
local config = { [10001] = { id = 10001, name = "内网服务器", desc = "测试用", }, [10002] = { id = 10002, name = "外网服务器", desc = "测试用", }, [10003] = { id = 10003, name = "测试服务器1", desc = "测试用", }, [10004] = { id = 10004, name = "测试服务器2", desc = "测试用", }, [10005] = { id = 10005, name = "测试服务器3", desc = "测试用", }, [10006] = { id = 10006, name = "测试服务器4", desc = "测试用", }, [10007] = { id = 10007, name = "测试服务器5", desc = "测试用", }, [10008] = { id = 10008, name = "测试服务器6", desc = "测试用", }, [10009] = { id = 10009, name = "测试服务器7", desc = "测试用", }, [10010] = { id = 10010, name = "测试服务器8", desc = "测试用", }, [10011] = { id = 10011, name = "测试服务器9", desc = "测试用", }, [10012] = { id = 10012, name = "测试服务器10", desc = "测试用", }, [10013] = { id = 10013, name = "测试服务器11", desc = "测试用", }, [10014] = { id = 10014, name = "测试服务器12", desc = "测试用", }, [10015] = { id = 10015, name = "测试服务器13", desc = "测试用", }, [10016] = { id = 10016, name = "测试服务器14", desc = "测试用", }, [10017] = { id = 10017, name = "测试服务器15", desc = "测试用", }, [10018] = { id = 10018, name = "测试服务器16", desc = "测试用", }, [10019] = { id = 10019, name = "测试服务器17", desc = "测试用", }, [10020] = { id = 10020, name = "测试服务器18", desc = "测试用", }, [10021] = { id = 10021, name = "测试服务器19", desc = "测试用", }, [10022] = { id = 10022, name = "测试服务器20", desc = "测试用", }, [10023] = { id = 10023, name = "测试服务器21", desc = "测试用", }, [10024] = { id = 10024, name = "测试服务器22", desc = "测试用", }, [10025] = { id = 10025, name = "测试服务器23", desc = "测试用", }, [10026] = { id = 10026, name = "测试服务器24", desc = "测试用", }, [10027] = { id = 10027, name = "测试服务器25", desc = "测试用", }, [10028] = { id = 10028, name = "测试服务器26", desc = "测试用", }, [10029] = { id = 10029, name = "测试服务器27", desc = "测试用", }, [10030] = { id = 10030, name = "测试服务器28", desc = "测试用", }, [10031] = { id = 10031, name = "测试服务器29", desc = "测试用", }, [10032] = { id = 10032, name = "测试服务器30", desc = "测试用", }, [10033] = { id = 10033, name = "测试服务器31", desc = "测试用", }, [10034] = { id = 10034, name = "测试服务器32", desc = "测试用", }, [10035] = { id = 10035, name = "测试服务器33", desc = "测试用", }, } return config
CcsScrollView = class("CcsScrollView", function () return ccui.Layout:create() end) CcsScrollView.SCROLL_V = 1 CcsScrollView.SCROLL_H = 2 CcsScrollView.SCROLL_BOTH = 3 CcsScrollView.CAN_ALL_SCROLL = true CcsScrollView.isScreenOrientationRotated = false DISTANCE_2_TRIGGER_MOVE_H = 3 DISTANCE_2_TRIGGER_MOVE_V = 5 CcsScrollView.ctor = function (slot0, slot1) slot0:setAnchorPoint(cc.p(0, 0)) createSetterGetter(slot0, "innerContainer", ccui.Layout:create(), false, true) createSetterGetter(slot0, "innerContainerSize", cc.size(0, 0), false, true) createSetterGetter(slot0, "vScrollBar", nil, false, true) createSetterGetter(slot0, "vScrollBarTrack", nil, false, true) createSetterGetter(slot0, "vUpdateNode", nil, false, true) createSetterGetter(slot0, "canScrollBottom2Load", false, false, false, false, false, handler(slot0, slot0.oncanScrollBottom2LoadChanged)) createSetterGetter(slot0, "isLoadingMore", false, false, false, false, false, handler(slot0, slot0.onIsLoadingMoreChanged)) createSetterGetter(slot0, "scrollAreaNode", nil, false, true) createSetterGetter(slot0, "scrollPolicy", CcsScrollView.SCROLL_V) createSetterGetter(slot0, "isScrollable", true, false) createSetterGetter(slot0, "isItemClickable", true, false) createSetterGetter(slot0, "bottomMargin", 0, false, true) createSetterGetter(slot0, "leftMargin", 0, false, true) createSetterGetter(slot0, "rightMargin", 0, false, false, false, false, false, handler(slot0, slot0.updateMarginInfos)) createSetterGetter(slot0, "topMargin", 0, false, true) createSetterGetter(slot0, "isCenterWhileNeed", false) createSetterGetter(slot0, "isScrollableOnlyInNeed", false) createSetterGetter(slot0, "canLongClick", false, false, true) createSetterGetter(slot0, "longClickIntervalMs", 250, false, true) createSetterGetter(slot0, "loadMoreSignal", SignalAs3.new(), false, true) createSetterGetter(slot0, "itemClickSignal", SignalAs3.new(), false, true) createSetterGetter(slot0, "viewTouchSignal", SignalAs3.new(), false, true) createSetterGetter(slot0, "viewClickSignal", SignalAs3.new(), false, true) createSetterGetter(slot0, "viewPushSignal", SignalAs3.new(), false, true) createSetterGetter(slot0, "onPosChangedSignal", SignalAs3.new(), false, true) createSetterGetter(slot0, "isScrollViewNotRotated", false) createSetterGetter(slot0, "isScrollViewForceRotated", false) createSetterGetter(slot0, "canScrollAlways", false) createSetterGetter(slot0, "maxPosBounceOffset", 100) createSetterGetter(slot0, "minPosBounceOffset", 100) createSetterGetter(slot0, "canMaxDrag", true) createSetterGetter(slot0, "isPauseBounce", false, nil, nil, nil, nil, handler(slot0, slot0.onIsPauseBouceChanged)) slot0._vUpdateNodeGap = 5 slot0._longClickTimer = nil slot0._loadMoreBottomMarginOffset = 0 slot0._vScrollBarMinHeight = 70 slot0._innerContainerSizeWithMargin = cc.size(0, 0) slot0._leftX = 0 slot0._rightX = 0 slot0._topY = 0 slot0._bottomY = 0 slot0._tempTouchPos = nil slot0._easingFactor = 0.08 slot0._bounceDuration = 0.6 slot0._curVx = 0 slot0._curVy = 0 slot0._defaultA = 3 slot0._aX = slot0._defaultA slot0._aY = slot0._defaultA slot0._isAutoCheckItemVisible = true slot0._scrollItems = {} slot0._innerContainer:setAnchorPoint(cc.p(0, 0)) slot0._innerContainer:setTouchEnabled(false) slot0:addChild(slot0._innerContainer) slot0:setClippingEnabled(true) ClassUtil.extends(slot0, TickBase) slot0:setTouchEnabled(false) slot0:setScrollAreaNode(slot1 or slot0) slot0._pushDownNotMove = false slot0._curPushingDownItem = nil slot0._isTouching = false slot0._preBtn = nil slot0._nextBtn = nil slot0._btnsInHandle = {} slot0._btnsDicInHandle = {} end CcsScrollView.onIsPauseBouceChanged = function (slot0) if slot0._isPauseBounce then TweenLite.killTweensOf(slot0._innerContainer) else slot0:jumpTo(0, 0, 0.2) end end CcsScrollView.removeBtnInHandleTouchOperate = function (slot0, slot1) table.removebyvalue(slot0._btnsInHandle, slot1) slot0._btnsDicInHandle[slot1] = nil end CcsScrollView.addBtn2HandleTouchOperate = function (slot0, slot1) if slot1 and not slot0._btnsDicInHandle[slot1] then slot0._btnsDicInHandle[slot1] = {} table.insert(slot0._btnsInHandle, slot1) slot1:setInteractiveTouchEnable(false) end end CcsScrollView.checkBtnsTouchEvent = function (slot0, slot1, slot2) if slot1 == ccs.TOUCH_EVENT_MOVED then if slot0._tempTouchPos and slot0:checkDistance2TriggerMove(slot2) then slot1 = ccs.TOUCH_EVENT_CANCELED else return end end function slot3(slot0, slot1) if slot1.touchWorldPos then slot1.touchWorldPos = nil slot0:onTouchOperation(slot0, ccs.TOUCH_EVENT_CANCELED) end end slot4 = nil for slot8 = #slot0._btnsInHandle, 1, -1 do slot10 = slot0._btnsDicInHandle[slot0._btnsInHandle[slot8]] if slot1 ~= ccs.TOUCH_EVENT_CANCELED and DisplayUtil.isInDisplayList(slot9) and slot9:getInteractiveObj():hitTest(slot2, nil, nil) then if slot1 == ccs.TOUCH_EVENT_BEGAN then if not slot4 then slot4 = slot9 slot10.touchWorldPos = slot2 slot9:onTouchOperation(slot9, slot1) end elseif slot1 == ccs.TOUCH_EVENT_ENDED and slot10.touchWorldPos then slot10.touchWorldPos = nil slot9:onTouchOperation(slot9, slot1) end else slot3(slot9, slot10) end end end CcsScrollView.onIsLoadingMoreChanged = function (slot0) if slot0._isLoadingMore then slot0._loadMoreSignal:emit() elseif slot0._loadMoreBottomMarginOffset > 0 then slot0:setBottomMargin(slot0._bottomMargin - slot0._loadMoreBottomMarginOffset, nil, 0.3) end end CcsScrollView.oncanScrollBottom2LoadChanged = function (slot0) if not slot0._canScrollBottom2Load and slot0._vUpdateNode then slot0._vUpdateNode:setVisible(false) end end CcsScrollView.tick = function (slot0, slot1, slot2) if slot0._scrollPolicy == CcsScrollView.SCROLL_V then if math.abs(slot0._curVy) <= slot0._aY then slot0:stopSpeedDown() else slot0:speedDown() end elseif slot0._scrollPolicy == CcsScrollView.SCROLL_H then if math.abs(slot0._curVx) <= slot0._aX then slot0:stopSpeedDown() else slot0:speedDown() end end end CcsScrollView.setTopMargin = function (slot0, slot1) if slot0._topMargin ~= slot1 then slot0._topMargin = slot1 slot0:updateMarginInfos() slot0._innerContainer:setPositionY(slot0._innerContainer:getPositionY() - (slot1 - slot0._topMargin)) end end CcsScrollView.setBottomMargin = function (slot0, slot1, slot2, slot3) if slot0._bottomMargin ~= slot1 then slot4 = slot0._bottomMargin slot0._bottomMargin = slot1 slot0:updateMarginInfos() if not slot2 then if slot0._bottomY < slot0._innerContainer:getPositionY() + slot1 - slot4 then slot6 = slot0._bottomY end slot0:resetScrollState() if slot3 then TweenLite.to(slot0._innerContainer, slot3, { y = slot6 }) else slot0._innerContainer:setPositionY(slot6) end end end end CcsScrollView.setLeftMargin = function (slot0, slot1) if slot0._leftMargin ~= slot1 then slot0._leftMargin = slot1 slot0:updateMarginInfos() slot0._innerContainer:setPositionX(slot0._innerContainer:getPositionX() + slot1 - slot0._leftMargin) end end CcsScrollView.speedDown = function (slot0) slot1 = cc.p(slot0._innerContainer:getPosition()) if slot0._scrollPolicy == CcsScrollView.SCROLL_V then slot0._curVx = 0 if slot0._curVy < 0 then slot0._curVy = slot0._curVy + slot0._aY else slot0._curVy = slot0._curVy - slot0._aY end elseif slot0._scrollPolicy == CcsScrollView.SCROLL_H then slot0._curVy = 0 if slot0._curVx < 0 then slot0._curVx = slot0._curVx + slot0._aX else slot0._curVx = slot0._curVx - slot0._aX end end slot0:scrollView2(slot1.x + slot0._curVx, slot1.y + slot0._curVy, nil, false, true) end CcsScrollView.stopSpeedDown = function (slot0) slot0._curVy = 0 slot0._curVx = 0 slot0:stopTick() slot0:checkScrollCancel(false) end CcsScrollView.checkDistance2TriggerMove = function (slot0, slot1) slot2 = false if slot0._scrollPolicy == CcsScrollView.SCROLL_H then slot3 = nil slot2 = DISTANCE_2_TRIGGER_MOVE_H < (((not slot0._isScrollViewForceRotated and (slot0._isScrollViewNotRotated or not CcsScrollView.isScreenOrientationRotated)) or math.abs(slot1.y - slot0._tempTouchPos.y)) and math.abs(slot1.x - slot0._tempTouchPos.x)) else slot3 = nil return DISTANCE_2_TRIGGER_MOVE_V < (((not slot0._isScrollViewForceRotated and (slot0._isScrollViewNotRotated or not CcsScrollView.isScreenOrientationRotated)) or math.abs(slot1.x - slot0._tempTouchPos.x)) and math.abs(slot1.y - slot0._tempTouchPos.y)) end end CcsScrollView.rotationPos = function (slot0, slot1) return cc.p(slot1.y, slot1.x) end CcsScrollView.onTouchOperation = function (slot0, slot1, slot2) slot3 = nil if slot2 == ccs.TOUCH_EVENT_BEGAN then slot0._isTouching = true slot3 = DisplayUtil.ccpCopy(slot0:getScrollAreaNode():getTouchBeganPosition()) if not slot0._pushDownNotMove then slot0._pushDownNotMove = true slot0._viewPushSignal:emit(slot0._pushDownNotMove, slot3, slot2) end slot0:resetScrollState() slot0._tempTouchPos = DisplayUtil.ccpCopy(slot3) if slot0:checkScrollItemsPushDown(slot0._tempTouchPos) and slot0._longClickTimer then slot0._longClickTimer:reset() slot0._longClickTimer:start() end slot0:setBarVisible(true) slot0._viewTouchSignal:emit(slot3, slot2) slot0:checkBtnsTouchEvent(slot2, slot3) elseif slot2 == ccs.TOUCH_EVENT_MOVED then if CcsScrollView.CAN_ALL_SCROLL or slot0._canScrollAlways then slot0:checkBtnsTouchEvent(slot2, DisplayUtil.ccpCopy(slot0:getScrollAreaNode():getTouchMovePosition())) if not slot0._pushDownNotMove or slot0:checkDistance2TriggerMove(slot3) then if slot0._pushDownNotMove then slot0._pushDownNotMove = false slot0._viewPushSignal:emit(slot0._pushDownNotMove, slot3, slot2) end if slot0:canScroll() then slot0:checkScrollMove() slot0:checkScrollItemsMove() end end if slot0._longClickTimer then slot0._longClickTimer:reset() end slot0._viewTouchSignal:emit(slot3, slot2) end elseif slot2 == ccs.TOUCH_EVENT_CANCELED or slot2 == ccs.TOUCH_EVENT_ENDED then slot0._isTouching = false slot3 = DisplayUtil.ccpCopy(slot0:getScrollAreaNode():getTouchEndPosition()) if slot0:canScroll() then slot0:checkScrollBottom2Load() end slot0:checkScrollCancel(true) slot0:checkScrollItemsRelease(slot3) if slot0._longClickTimer then slot0._longClickTimer:reset() end if slot0._pushDownNotMove then if slot2 == ccs.TOUCH_EVENT_ENDED then slot0._viewClickSignal:emit(slot3, slot2) end slot0._pushDownNotMove = false slot0._viewPushSignal:emit(slot0._pushDownNotMove, slot3, slot2) end slot0._viewTouchSignal:emit(slot3, slot2) slot0:checkBtnsTouchEvent(slot2, slot3) end slot0:checkItemTouchEvent(slot2, slot3) end CcsScrollView.checkItemTouchEvent = function (slot0, slot1, slot2) if slot0._curPushingDownItem then slot0._curPushingDownItem:onTouchEvent(slot1, slot2) if slot1 == ccs.TOUCH_EVENT_CANCELED or slot1 == ccs.TOUCH_EVENT_ENDED then slot0._curPushingDownItem = nil end end end CcsScrollView.canScroll = function (slot0) if not slot0._isScrollable then return false elseif slot0._isScrollableOnlyInNeed then if slot0._scrollPolicy == CcsScrollView.SCROLL_V then return slot0:getContentSize().height < slot0._innerContainerSizeWithMargin.height else return slot0:getContentSize().width < slot0._innerContainerSizeWithMargin.width end else return true end end CcsScrollView.checkScrollBottom2Load = function (slot0, slot1) if slot0:canShowBottomUpdateNode() and not slot0._isLoadingMore then slot2, slot3 = slot0._innerContainer:getPosition() if slot3 > 0 + 10 + math.abs(slot0._vUpdateNode:getPositionY()) + slot0._vUpdateNode:getContentSize().height * slot0._vUpdateNode:getAnchorPoint().y then slot0._loadMoreBottomMarginOffset = slot5 slot0:setBottomMargin(slot6, true) slot0:setIsLoadingMore(true) end end end CcsScrollView.setBarVisible = function (slot0, slot1) if slot1 and slot0:isShowScroller() then if slot0._vScrollBar then TweenLite.killTweensOf(slot0._vScrollBar) TweenLite.to(slot0._vScrollBar, 0.5, { autoAlpha = 1 }) end if slot0._vScrollBarTrack then TweenLite.killTweensOf(slot0._vScrollBarTrack) TweenLite.to(slot0._vScrollBarTrack, 0.5, { autoAlpha = 1 }) end else if slot0._vScrollBar then TweenLite.killTweensOf(slot0._vScrollBar) TweenLite.to(slot0._vScrollBar, 0.5, { autoAlpha = 0, delay = 0.3 }) end if slot0._vScrollBarTrack then TweenLite.killTweensOf(slot0._vScrollBarTrack) TweenLite.to(slot0._vScrollBarTrack, 0.5, { autoAlpha = 0, delay = 0.3 }) end end end CcsScrollView.checkScrollItemsPushDown = function (slot0, slot1) slot2 = false if slot0._isItemClickable then for slot6, slot7 in ipairs(slot0._scrollItems) do if slot2 then slot7:setIsTouchPushDown(false, slot1) else slot7:setIsTouchPushDown(slot7:checkTouchInMe(slot1), slot1) if slot7.checkTouchInMe(slot1) then slot0._curPushingDownItem = slot7 end end end end return slot2 end CcsScrollView.setAllItemsNotPushDown = function (slot0) for slot4, slot5 in ipairs(slot0._scrollItems) do slot5:setIsTouchPushDown(false) end end CcsScrollView.checkScrollItemsMove = function (slot0) slot0:setAllItemsNotPushDown() end CcsScrollView.checkScrollItemsRelease = function (slot0, slot1) slot2 = nil for slot6, slot7 in ipairs(slot0._scrollItems) do if slot7:getIsTouchPushDown() then if slot7:checkTouchInMe(slot1) then slot2 = slot7 end slot7:setIsTouchPushDown(false, slot1) break end end if slot2 then if slot2:canPlayClickSound(slot1) then slot2:playClickSoundEffect() end slot0._itemClickSignal:emit(slot2) slot2:onClick(slot1) end end CcsScrollView.resetScrollState = function (slot0) slot0._curVy = 0 slot0._curVx = 0 slot0._tempTouchPos = nil slot0:stopTick() TweenLite.killTweensOf(slot0._innerContainer) end CcsScrollView.checkScrollCancel = function (slot0, slot1) slot2 = cc.p(slot0._innerContainer:getPosition()) if slot0._scrollPolicy == CcsScrollView.SCROLL_V then if slot2.y < slot0._topY then slot0:scrollView2(nil, slot0._topY, slot0._bounceDuration, true, true) elseif slot0._bottomY < slot2.y then slot0:scrollView2(nil, slot0._bottomY, slot0._bounceDuration, true, true) elseif slot1 then if slot0._tempTouchPos then slot6 = 0 if math.pow(slot0._curVy, 2) / (2 * slot0._defaultA) > ((slot0._curVy > 0 and math.abs(slot0._bottomY - slot2.y) + slot0._maxPosBounceOffset) or math.abs(slot0._topY - slot2.y) + slot0._minPosBounceOffset) then slot3 = slot4 / (2 * slot6) end slot0._aY = slot3 slot0:startTick() end else slot0:setBarVisible(false) end elseif slot0._scrollPolicy == CcsScrollView.SCROLL_H then if slot2.x < slot0._rightX then slot0:scrollView2(slot0._rightX, nil, slot0._bounceDuration, true, true) elseif slot0._leftX < slot2.x then slot0:scrollView2(slot0._leftX, nil, slot0._bounceDuration, true, true) elseif slot1 then if slot0._tempTouchPos then slot6 = 0 if math.pow(slot0._curVx, 2) / (2 * slot0._defaultA) > ((slot0._curVx > 0 and math.abs(slot0._leftX - slot2.x) + slot0._maxPosBounceOffset) or math.abs(slot0._rightX - slot2.x) + slot0._minPosBounceOffset) then slot3 = slot4 / (2 * slot6) end slot0._aX = slot3 slot0:startTick() end else slot0:setBarVisible(false) end end slot0._tempTouchPos = nil end CcsScrollView.checkIgnoreMove = function (slot0, slot1, slot2) if slot1 * slot2 > 0 then return math.abs(slot1) > math.abs(slot2) + 30 end return false end CcsScrollView.checkScrollMove = function (slot0) slot1 = DisplayUtil.ccpCopy(slot0:getScrollAreaNode():getTouchMovePosition()) if slot0._tempTouchPos then slot2 = slot1.x - slot0._tempTouchPos.x slot3 = slot1.y - slot0._tempTouchPos.y if slot0._isScrollViewForceRotated or (not slot0._isScrollViewNotRotated and CcsScrollView.isScreenOrientationRotated) then slot2 = slot3 slot3 = -slot2 if isAndroid then slot2 = -slot2 slot3 = -slot3 end end if slot0._scrollPolicy == CcsScrollView.SCROLL_V then if slot0:checkIgnoreMove(slot0._curVy, slot3) then return end elseif slot0._scrollPolicy == CcsScrollView.SCROLL_H and slot0:checkIgnoreMove(slot0._curVx, slot2) then return end slot0._curVx = slot2 slot0._curVy = slot3 slot5 = slot0:checkScrollMoveOffset(slot0._curVx, cc.p(slot0._innerContainer:getPosition()).x, slot0._leftX, slot0._rightX) slot6 = slot0:checkScrollMoveOffset(slot0._curVy, cc.p(slot0._innerContainer.getPosition()).y, slot0._bottomY, slot0._topY) if slot0._scrollPolicy == CcsScrollView.SCROLL_V then slot5 = 0 elseif slot0._scrollPolicy == CcsScrollView.SCROLL_H then slot6 = 0 end slot0:scrollView2(slot4.x + slot5, slot4.y + slot6, nil, false, true) end slot0._tempTouchPos = slot1 end CcsScrollView.checkScrollMoveOffset = function (slot0, slot1, slot2, slot3, slot4) slot6 = nil if slot2 + slot1 < slot4 and slot1 < 0 then slot6 = (slot2 + (slot4 - slot0._minPosBounceOffset - slot2) * slot0._easingFactor) - slot2 elseif slot3 < slot5 and slot1 > 0 then slot7 = slot0._maxPosBounceOffset if not slot0._canMaxDrag and slot0._isTouching then slot7 = 0 end slot6 = (slot2 + ((slot3 + slot7) - slot2) * slot0._easingFactor) - slot2 end if slot6 then if math.abs(slot1) < math.abs(slot6) then return slot1 else return slot6 end else return slot1 end end CcsScrollView.scrollView2 = function (slot0, slot1, slot2, slot3, slot4, slot5) TweenLite.killTweensOf(slot0._innerContainer) if not slot5 then slot1 = slot1 and MathUtil.getValueBetween(slot1, slot0._leftX, slot0._rightX) slot2 = slot2 and MathUtil.getValueBetween(slot2, slot0._topY, slot0._bottomY) end if slot3 then slot6 = nil if slot4 then slot6 = Back.easeOut end if not slot0._isPauseBounce or not slot4 then TweenLite.to(slot0._innerContainer, slot3, { x = slot1, y = slot2, ease = slot6, onUpdate = handler(slot0, slot0.onPositionChanged), onComplete = handler(slot0, slot0.setBarVisible), onCompleteParams = { false } }) end else slot0._innerContainer:setPosition(cc.p(slot1 or slot0._innerContainer:getPositionX(), slot2 or slot0._innerContainer:getPositionY())) slot0:onPositionChanged() end end CcsScrollView.deployBtns = function (slot0, slot1, slot2) if slot0._preBtn then slot0._preBtn:getClickSignal():remove(slot0.onBtnClick, slot0) slot0._nextBtn:getClickSignal():remove(slot0.onBtnClick, slot0) end slot0._preBtn = slot1 slot0._nextBtn = slot2 if slot0._preBtn then slot0._preBtn:getClickSignal():add(slot0.onBtnClick, slot0) slot0._nextBtn:getClickSignal():add(slot0.onBtnClick, slot0) end end CcsScrollView.onBtnClick = function (slot0, slot1) if slot1 == slot0._preBtn then slot0:jumpPage(true) elseif slot1 == slot0._nextBtn then slot0:jumpPage(false) end end CcsScrollView.jumpPage = function (slot0, slot1) slot2, slot3 = nil if slot0._scrollPolicy == CcsScrollView.SCROLL_H then if slot1 then slot2 = slot0._innerContainer:getPositionX() + slot0:getContentSize().width else slot2 = slot0._innerContainer:getPositionX() - slot0:getContentSize().width end else slot0:jumpTo(slot2, (slot1 and slot0._innerContainer:getPositionY() + slot0:getContentSize().height) or slot0._innerContainer:getPositionY() - slot0:getContentSize().height, 0.3) return end end CcsScrollView.checkBtnsCanShow = function (slot0) if slot0._preBtn then if slot0._scrollPolicy == CcsScrollView.SCROLL_H then slot0._preBtn:setVisible(slot0._innerContainer:getPositionX() < slot0._leftX - 5) slot0._nextBtn:setVisible(slot0._innerContainer:getPositionX() > slot0._rightX + 5) else slot0._preBtn:setVisible(slot0._topY < slot0._innerContainer:getPositionY()) slot0._nextBtn:setVisible(slot0._innerContainer:getPositionY() < slot0._bottomY) end end end CcsScrollView.onPositionChanged = function (slot0) slot0:checkBtnsCanShow() slot0:checkItemsVisible() slot0:updateScrollBarPosition() slot0._onPosChangedSignal:emit() end CcsScrollView.checkItemsVisible = function (slot0) if slot0._isAutoCheckItemVisible then if slot0._scrollPolicy == CcsScrollView.SCROLL_V then slot1 = -slot0._innerContainer:getPositionY() slot2 = -slot0._innerContainer:getPositionY() + slot0:getContentSize().height for slot6, slot7 in ipairs(slot0._scrollItems) do if slot7:getParent() == slot0._innerContainer then slot11 = slot7:getPositionY() - slot7:getAnchorPoint().y * slot7:getContentSize().height - slot7:getEndGap() < slot2 and (slot1 < slot9 or slot1 < slot7.getPositionY() - slot7.getAnchorPoint().y * slot7.getContentSize().height - slot7.getEndGap() + slot7:getItemSize().height + slot7:getBeginGap() + slot7:getEndGap()) if slot7:isVisible() ~= slot11 then slot7:setVisible(slot11) end end end elseif slot0._scrollPolicy == CcsScrollView.SCROLL_H then end end end CcsScrollView.updateUpdateNodePosition = function (slot0) if slot0._vUpdateNode then slot0._vUpdateNode:setPositionY(0 - slot0._vUpdateNode:getContentSize().height * (1 - slot0._vUpdateNode:getAnchorPoint().y) - slot0._vUpdateNodeGap) slot0._vUpdateNode:setVisible(slot0:canShowBottomUpdateNode()) end end CcsScrollView.canShowBottomUpdateNode = function (slot0) return slot0._scrollPolicy == CcsScrollView.SCROLL_V and slot0._canScrollBottom2Load and slot0:getContentSize().height < slot0._innerContainerSizeWithMargin.height end CcsScrollView.updateScrollBarSize = function (slot0) if slot0._vScrollBar then slot0._vScrollBar:setContentSize(cc.size(slot0._vScrollBar:getContentSize().width, math.max(slot0._vScrollBarMinHeight, slot0:getContentSize().height * slot0.getContentSize().height / slot0._innerContainerSizeWithMargin.height))) end end CcsScrollView.isShowScroller = function (slot0) return slot0._bottomY - slot0._topY > slot0._topMargin + slot0._bottomMargin end CcsScrollView.updateScrollBarPosition = function (slot0) if slot0._vScrollBar and slot0:isShowScroller() then slot0._vScrollBar:setPosition(cc.p(slot0._vScrollBar:getPositionX(), (slot0:getContentSize().height - slot0._vScrollBar:getContentSize().height * slot0._vScrollBar:getScaleY()) * (slot0._innerContainer:getPositionY() - slot0._bottomY) / (slot0._topY - slot0._bottomY))) end end CcsScrollView.updateMarginInfos = function (slot0) slot0._innerContainerSizeWithMargin.height = math.max(slot0:getContentSize().height, slot0._innerContainerSize.height + slot0._bottomMargin + slot0._topMargin) slot0._innerContainerSizeWithMargin.width = math.max(slot0.getContentSize().width, slot0._innerContainerSize.width + slot0._leftMargin + slot0._rightMargin) if slot0._scrollPolicy == CcsScrollView.SCROLL_V then if slot1.height < slot0._innerContainerSizeWithMargin.height then slot0._bottomY = slot0._bottomMargin else slot0._bottomY = -slot0._topMargin end end slot0._topY = slot1.height - slot0._innerContainerSizeWithMargin.height + slot0._bottomMargin slot0._leftX = slot0._leftMargin slot0._rightX = slot1.width - slot0._innerContainerSizeWithMargin.width + slot0._leftMargin end CcsScrollView.setInnerContainerSize = function (slot0, slot1) slot1.height = math.max(slot0:getContentSize().height, slot1.height) slot1.width = math.max(slot0.getContentSize().width, slot1.width) if slot0._innerContainerSize.width == slot1.width and slot0._innerContainerSize.height == slot1.height then return false end slot3 = slot0._innerContainer:getPositionX() slot4 = slot0._innerContainer:getPositionY() slot5 = 0 slot6 = slot0._innerContainerSize.height == 0 if not slot6 then slot5 = math.max(0, slot0._innerContainerSizeWithMargin.height - slot2.height - (slot0._bottomMargin - slot4)) end slot0._innerContainerSize.width = slot1.width slot0._innerContainerSize.height = slot1.height slot0._innerContainer:setContentSize(slot1) slot0:updateMarginInfos() slot0:updateScrollBarSize() slot0:updateUpdateNodePosition() slot0:scrollView2(slot3, (slot0._scrollPolicy == CcsScrollView.SCROLL_V and slot0._bottomMargin - (slot0._innerContainerSizeWithMargin.height - slot0:getContentSize().height - slot5)) or slot0._bottomMargin) return true end CcsScrollView.removeContentChild = function (slot0, slot1) table.removebyvalue(slot0._scrollItems, slot1) if slot1:getParent() == slot0._innerContainer then slot1:removeFromParent() end end CcsScrollView.removeAllChildren = function (slot0, slot1) slot2 = #slot0._scrollItems while slot2 > 0 do slot3 = slot0._scrollItems[1] if not slot1 and ClassUtil.is(slot3, CcsScrollViewItem) then slot3:destroy() else slot0:removeContentChild(slot3) end slot2 = slot2 - 1 end slot0._scrollItems = {} end CcsScrollView.setContentChild = function (slot0, slot1) if slot1:getContentSize().height < slot0:getContentSize().height then slot1:setPositionY(slot3.height - slot2.height) end slot0:addContentChild(slot1) end CcsScrollView.addContentChild = function (slot0, slot1) if slot1:getParent() ~= slot0._innerContainer then DisplayUtil.setAddOrRemoveChild(slot1, slot0._innerContainer, true) if ClassUtil.is(slot1, CcsScrollViewItem) then TableUtil.push(slot0._scrollItems, slot1) slot1:setScrollViewParent(slot0) slot1:handleScrollBtns(slot0) end end end CcsScrollView.jumpTo = function (slot0, slot1, slot2, slot3) slot0:scrollView2(slot1, slot2, slot3) end CcsScrollView.jumpToPercent = function (slot0, slot1, slot2, slot3) slot4, slot5 = nil if slot1 then slot4 = -MathUtil.getValueBetweenByPercent(slot1, slot0._leftX, -slot0._rightX) end if slot2 then slot5 = MathUtil.getValueBetweenByPercent(slot2, slot0._topY, slot0._bottomY) end slot0:jumpTo(slot4, slot5, slot3) end CcsScrollView.setScrollAreaNode = function (slot0, slot1) if slot0._scrollAreaNode ~= (slot1 or slot0) then if slot0:getScrollAreaNode() then slot0:getScrollAreaNode():setTouchEnabled(false) end slot0._scrollAreaNode = slot1 slot0._scrollAreaNode:setTouchEnabled(true) slot0:getScrollAreaNode():addTouchEventListener(handler(slot0, slot0.onTouchOperation)) end end CcsScrollView.setLongClickIntervalMs = function (slot0, slot1) if slot0._longClickIntervalMs ~= slot1 then slot0._longClickIntervalMs = slot1 if slot0._longClickTimer then slot0._longClickTimer.delayInMs = slot1 end end end CcsScrollView.setCanLongClick = function (slot0, slot1) slot0._canLongClick = slot1 if slot1 then if not slot0._longClickTimer then slot0._longClickTimer = TimerBase.new(handler(slot0, slot0.onLongClickTimer), slot0._longClickIntervalMs, nil, "CcsScrollView:_longClickTimer") slot0._longClickTimer:setAutoDispose(false) end slot0._longClickTimer:reset() elseif slot0._longClickTimer then slot0._longClickTimer:destroy() slot0._longClickTimer = nil end end CcsScrollView.onLongClickTimer = function (slot0) for slot4, slot5 in ipairs(slot0._scrollItems) do if slot5:getIsTouchPushDown() then slot5:onLongClick(slot6) slot5:setIsTouchPushDown(false, DisplayUtil.ccpCopy(slot0:getScrollAreaNode():getTouchBeganPosition())) break end end end CcsScrollView.setVScrollBarTrack = function (slot0, slot1) if slot0._vScrollBarTrack ~= slot1 then if slot0._vScrollBarTrack then slot0._vScrollBarTrack:removeFromParent() end slot0._vScrollBarTrack = slot1 slot1:setLocalZOrder(slot0._innerContainer:getLocalZOrder() + 1) DisplayUtil.insertChild2(slot1, slot0) DisplayUtil.setVisible(slot1, false) end end CcsScrollView.setVUpdateNode = function (slot0, slot1) if slot0._vUpdateNode ~= slot1 then if slot0._vUpdateNode then slot0._vUpdateNode:removeFromParent() end slot0._vUpdateNode = slot1 slot0:setCanScrollBottom2Load(slot1 ~= nil) if slot1 then slot1:setLocalZOrder(slot0._innerContainer:getLocalZOrder() + 1) DisplayUtil.insertChild2(slot1, slot0._innerContainer) DisplayUtil.setVisible(slot1, true) slot0:updateUpdateNodePosition() end end end CcsScrollView.setVScrollBar = function (slot0, slot1) if slot0._vScrollBar ~= slot1 then if slot0._vScrollBar then slot0._vScrollBar:removeFromParent() end slot0._vScrollBar = slot1 slot1:setAnchorPoint(cc.p(0.5, 0)) slot1:setLocalZOrder(slot0._innerContainer:getLocalZOrder() + 2) DisplayUtil.insertChild2(slot1, slot0) DisplayUtil.setVisible(slot1, false) slot0:updateScrollBarSize() end end CcsScrollView.destroy = function (slot0) TweenLite.killTweensOf(slot0._innerContainer) slot0:resetScrollState() for slot5, slot6 in ipairs(slot1) do slot6:destroy() end TickBase.destroy(slot0) slot0:removeFromParent() if slot0._longClickTimer then slot0._longClickTimer:destroy() slot0._longClickTimer = nil end if slot0._viewPushSignal then slot0._viewPushSignal:removeAll() slot0._viewPushSignal = nil end if slot0._viewTouchSignal then slot0._viewTouchSignal:removeAll() slot0._viewTouchSignal = nil end if slot0._itemClickSignal then slot0._itemClickSignal:removeAll() slot0._itemClickSignal = nil end if slot0._viewClickSignal then slot0._viewClickSignal:removeAll() slot0._viewClickSignal = nil end if slot0._onPosChangedSignal then slot0._onPosChangedSignal:removeAll() slot0._onPosChangedSignal = nil end if slot0._loadMoreSignal then slot0._loadMoreSignal:removeAll() slot0._loadMoreSignal = nil end if slot0._preBtn then slot0._preBtn:getClickSignal():remove(slot0.onBtnClick, slot0) slot0._nextBtn:getClickSignal():remove(slot0.onBtnClick, slot0) slot0._preBtn = nil slot0._nextBtn = nil end slot0._btnsInHandle = nil slot0._btnsDicInHandle = nil slot0._scrollItems = nil end return
-- file encode must be UTF8 -- qq号码登录监视脚本(不支持手机号码登录,不支持webqq,只在pc上用qq2015测试通过) -- 2015.9.14 require "base64" require "tcp_ip" function init() trace("plugin init: ".._VERSION.."\n") trace("package path: "..package.path.."\n") trace("package path: "..package.cpath.."\n") --for k,v in pairs(_G) do -- trace(string.format("%s,%s\n", k, v)) --end end -- protocol: 字符串如tcp,udp,icmp -- data: 二进制数据 -- len_total: 总共数据长度 -- len_data: 有效数据长度(去除各种头之后的数据) function handle_data(protocol,data,len_total,len_data) if 54 == len_total then return "delete" -- remove handshake end src_port = tcp_ip_get_src_port(data) dst_port = tcp_ip_get_dst_port(data) -- if 8000 != src_port && 8000 != dst_port then if (8000 ~= dst_port) or (len_data < 100) then return "delete" end if 2 ~= data:byte(43) then -- 0x2是qq udp协议magic number return "delete" end if 8 ~= data:byte(46) then -- 8和37是 0x8和0x25是协议类型,表示登录 return "delete" end if 37 ~= data:byte(47) then return "delete" end -- 50, 51, 52, 53字节是qq号(lua index从1开始而不是0) qq_number = data:byte(50) * 256 * 256 * 256 + data:byte(51) * 256 * 256 + data:byte(52) * 256 + data:byte(53) plugin_summary("qq_number is: " .. qq_number) end function handle_click(protocol,data,len_total,len_data) if 54 == len_total then return end src_port = tcp_ip_get_src_port(data) dst_port = tcp_ip_get_dst_port(data) -- if 8000 != src_port && 8000 != dst_port then if (8000 ~= dst_port) or (len_data < 100) then return end if 2 ~= data:byte(43) then -- 0x2是qq udp协议magic number return end if 8 ~= data:byte(46) then -- 8和37是 0x8和0x25是协议类型,表示登录 return end if 37 ~= data:byte(47) then return end -- 50, 51, 52, 53字节是qq号(lua index从1开始而不是0) qq_number = data:byte(50) * 256 * 256 * 256 + data:byte(51) * 256 * 256 + data:byte(52) * 256 + data:byte(53) plugin_output_clear() plugin_output("qq_number is: " .. qq_number.."\n") end function handle_double(protocol,data,len_total,len_data) handle_data(protocol,data,len_total,len_data) end
local helper = require 'app.conf.helper' return helper
-- Created by Elfansoer --[[ Ability checklist (erase if done/checked): - Scepter Upgrade - Break behavior - Linken/Reflect behavior - Spell Immune/Invulnerable/Invisible behavior - Illusion behavior - Stolen behavior ]] -------------------------------------------------------------------------------- modifier_timbersaw_chakram_lua_thinker = class({}) local MODE_LAUNCH = 0 local MODE_STAY = 1 local MODE_RETURN = 2 -------------------------------------------------------------------------------- -- Classifications function modifier_timbersaw_chakram_lua_thinker:IsHidden() return true end function modifier_timbersaw_chakram_lua_thinker:IsPurgable() return false end -------------------------------------------------------------------------------- -- Initializations function modifier_timbersaw_chakram_lua_thinker:OnCreated( kv ) if not IsServer() then return end self.parent = self:GetParent() self.caster = self:GetCaster() -- references self.damage_pass = self:GetAbility():GetSpecialValueFor( "pass_damage" ) self.damage_stay = self:GetAbility():GetSpecialValueFor( "damage_per_second" ) self.radius = self:GetAbility():GetSpecialValueFor( "radius" ) self.speed = self:GetAbility():GetSpecialValueFor( "speed" ) self.duration = self:GetAbility():GetSpecialValueFor( "pass_slow_duration" ) self.manacost = self:GetAbility():GetSpecialValueFor( "mana_per_second" ) self.max_range = self:GetAbility():GetSpecialValueFor( "break_distance" ) self.interval = self:GetAbility():GetSpecialValueFor( "damage_interval" ) -- kv references self.point = Vector( kv.target_x, kv.target_y, kv.target_z ) self.scepter = kv.scepter==1 -- init vars self.mode = MODE_LAUNCH self.move_interval = FrameTime() self.proximity = 50 self.caught_enemies = {} self.damageTable = { -- victim = target, attacker = self.caster, -- damage = damage, damage_type = self:GetAbility():GetAbilityDamageType(), ability = self:GetAbility(), --Optional. } -- ApplyDamage(damageTable) -- give vision to thinker self.parent:SetDayTimeVisionRange( 500 ) self.parent:SetNightTimeVisionRange( 500 ) -- add disarm to caster self.disarm = self.caster:AddNewModifier( self.caster, -- player source self:GetAbility(), -- ability source "modifier_timbersaw_chakram_lua_disarm", -- modifier name {} -- kv ) -- Init mode self.damageTable.damage = self.damage_pass self:StartIntervalThink( self.move_interval ) -- play effects self:PlayEffects1() end function modifier_timbersaw_chakram_lua_thinker:OnRemoved() end function modifier_timbersaw_chakram_lua_thinker:OnDestroy() if not IsServer() then return end -- remove disarm if not self.disarm:IsNull() then self.disarm:Destroy() end -- swap ability back, then remove sub local main = self:GetAbility() if main and (not main:IsNull()) and (not self.sub:IsNull()) then -- check if main is hidden (due to scepter or stolen) local active = main:IsActivated() self.caster:SwapAbilities( main:GetAbilityName(), self.sub:GetAbilityName(), active, false ) end self.caster:RemoveAbilityByHandle( self.sub ) -- stop effects self:StopEffects() -- remove UTIL_Remove( self.parent ) end -------------------------------------------------------------------------------- -- Interval Effects function modifier_timbersaw_chakram_lua_thinker:OnIntervalThink() -- check mode if self.mode==MODE_LAUNCH then self:LaunchThink() elseif self.mode==MODE_STAY then self:StayThink() elseif self.mode==MODE_RETURN then self:ReturnThink() end end function modifier_timbersaw_chakram_lua_thinker:LaunchThink() local origin = self.parent:GetOrigin() -- pass logic self:PassLogic( origin ) -- move logic local close = self:MoveLogic( origin ) -- if close, switch to stay mode if close then self.mode = MODE_STAY self.damageTable.damage = self.damage_stay*self.interval self:StartIntervalThink( self.interval ) self:OnIntervalThink() -- play effects self:PlayEffects2() end end function modifier_timbersaw_chakram_lua_thinker:StayThink() local origin = self.parent:GetOrigin() -- check if died, too far or not enough manacost local mana = self.caster:GetMana() if (self.caster:GetOrigin()-origin):Length2D()>self.max_range or mana<self.manacost*self.interval or (not self.caster:IsAlive()) then self:ReturnChakram() return end -- spend mana self.caster:SpendMana( self.manacost*self.interval, self:GetAbility() ) -- find enemies local enemies = FindUnitsInRadius( self.caster:GetTeamNumber(), -- int, your team number origin, -- point, center point nil, -- handle, cacheUnit. (not known) self.radius, -- float, radius. or use FIND_UNITS_EVERYWHERE DOTA_UNIT_TARGET_TEAM_ENEMY, -- int, team filter DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, -- int, type filter 0, -- int, flag filter 0, -- int, order filter false -- bool, can grow cache ) for _,enemy in pairs(enemies) do -- damage self.damageTable.victim = enemy ApplyDamage( self.damageTable ) -- -- add debuff -- enemy:AddNewModifier( -- self.caster, -- player source -- self:GetAbility(), -- ability source -- "modifier_timbersaw_chakram_lua", -- modifier name -- { duration = self.duration } -- kv -- ) end -- destroy trees local sound_tree = "Hero_Shredder.Chakram.Tree" local trees = GridNav:GetAllTreesAroundPoint( origin, self.radius, true ) for _,tree in pairs(trees) do EmitSoundOnLocationWithCaster( tree:GetOrigin(), sound_tree, self.parent ) end GridNav:DestroyTreesAroundPoint( origin, self.radius, true ) end function modifier_timbersaw_chakram_lua_thinker:ReturnThink() local origin = self.parent:GetOrigin() -- pass logic self:PassLogic( origin ) -- move logic self.point = self.caster:GetOrigin( ) local close = self:MoveLogic( origin ) -- if close, destroy if close then self:Destroy() end end function modifier_timbersaw_chakram_lua_thinker:PassLogic( origin ) -- find enemies local enemies = FindUnitsInRadius( self.caster:GetTeamNumber(), -- int, your team number origin, -- point, center point nil, -- handle, cacheUnit. (not known) self.radius, -- float, radius. or use FIND_UNITS_EVERYWHERE DOTA_UNIT_TARGET_TEAM_ENEMY, -- int, team filter DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, -- int, type filter 0, -- int, flag filter 0, -- int, order filter false -- bool, can grow cache ) for _,enemy in pairs(enemies) do -- check if already hit if not self.caught_enemies[enemy] then self.caught_enemies[enemy] = true -- damage self.damageTable.victim = enemy ApplyDamage( self.damageTable ) -- add debuff enemy:AddNewModifier( self.caster, -- player source self:GetAbility(), -- ability source "modifier_timbersaw_chakram_lua", -- modifier name { duration = self.duration } -- kv ) -- play effects local sound_target = "Hero_Shredder.Chakram.Target" EmitSoundOn( sound_target, enemy ) end end -- destroy trees local sound_tree = "Hero_Shredder.Chakram.Tree" local trees = GridNav:GetAllTreesAroundPoint( origin, self.radius, true ) for _,tree in pairs(trees) do EmitSoundOnLocationWithCaster( tree:GetOrigin(), sound_tree, self.parent ) end GridNav:DestroyTreesAroundPoint( origin, self.radius, true ) end function modifier_timbersaw_chakram_lua_thinker:MoveLogic( origin ) -- move position local direction = (self.point-origin):Normalized() local target = origin + direction * self.speed * self.move_interval -- target.z = GetGroundHeight( target, self.parent ) + 50 self.parent:SetOrigin( target ) -- return true if close to target return (target-self.point):Length2D()<self.proximity end function modifier_timbersaw_chakram_lua_thinker:ReturnChakram() -- if already returning, do nothing if self.mode == MODE_RETURN then return end -- switch mode self.mode = MODE_RETURN self.caught_enemies = {} self.damageTable.damage = self.damage_pass self:StartIntervalThink( self.move_interval ) -- play effects self:PlayEffects3() end -------------------------------------------------------------------------------- -- Aura Effects function modifier_timbersaw_chakram_lua_thinker:IsAura() return self.mode==MODE_STAY end function modifier_timbersaw_chakram_lua_thinker:GetModifierAura() return "modifier_timbersaw_chakram_lua" end function modifier_timbersaw_chakram_lua_thinker:GetAuraRadius() return self.radius end function modifier_timbersaw_chakram_lua_thinker:GetAuraDuration() return 0.3 end function modifier_timbersaw_chakram_lua_thinker:GetAuraSearchTeam() return DOTA_UNIT_TARGET_TEAM_ENEMY end function modifier_timbersaw_chakram_lua_thinker:GetAuraSearchType() return DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC end function modifier_timbersaw_chakram_lua_thinker:GetAuraSearchFlags() return DOTA_UNIT_TARGET_FLAG_NONE end -------------------------------------------------------------------------------- -- Graphics & Animations function modifier_timbersaw_chakram_lua_thinker:PlayEffects1() -- Get Resources local particle_cast = "particles/units/heroes/hero_shredder/shredder_chakram.vpcf" local sound_cast = "Hero_Shredder.Chakram" -- get data local direction = self.point-self.parent:GetOrigin() direction.z = 0 direction = direction:Normalized() -- Create Particle -- self.effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_ABSORIGIN_FOLLOW, self.parent ) self.effect_cast = assert(loadfile("lua_abilities/rubick_spell_steal_lua/rubick_spell_steal_lua_arcana"))(self, particle_cast, PATTACH_ABSORIGIN_FOLLOW, self.parent ) ParticleManager:SetParticleControl( self.effect_cast, 0, self:GetParent():GetOrigin() ) ParticleManager:SetParticleControl( self.effect_cast, 1, direction * self.speed ) ParticleManager:SetParticleControl( self.effect_cast, 16, Vector( 0, 0, 0 ) ) if self.scepter then -- set color to blue ParticleManager:SetParticleControl( self.effect_cast, 15, Vector( 0, 0, 255 ) ) ParticleManager:SetParticleControl( self.effect_cast, 16, Vector( 1, 0, 0 ) ) end -- Create Sound EmitSoundOn( sound_cast, self.parent ) end function modifier_timbersaw_chakram_lua_thinker:PlayEffects2() -- destroy previous particle ParticleManager:DestroyParticle( self.effect_cast, false ) ParticleManager:ReleaseParticleIndex( self.effect_cast ) -- Get Resources local particle_cast = "particles/units/heroes/hero_shredder/shredder_chakram_stay.vpcf" -- Create Particle -- self.effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_WORLDORIGIN, nil ) self.effect_cast = assert(loadfile("lua_abilities/rubick_spell_steal_lua/rubick_spell_steal_lua_arcana"))(self, particle_cast, PATTACH_WORLDORIGIN, nil ) ParticleManager:SetParticleControl( self.effect_cast, 0, self.parent:GetOrigin() ) ParticleManager:SetParticleControl( self.effect_cast, 16, Vector( 0, 0, 0 ) ) if self.scepter then -- set color to blue ParticleManager:SetParticleControl( self.effect_cast, 15, Vector( 0, 0, 255 ) ) ParticleManager:SetParticleControl( self.effect_cast, 16, Vector( 1, 0, 0 ) ) end end function modifier_timbersaw_chakram_lua_thinker:PlayEffects3() -- destroy previous particle ParticleManager:DestroyParticle( self.effect_cast, false ) ParticleManager:ReleaseParticleIndex( self.effect_cast ) -- Get Resources local particle_cast = "particles/units/heroes/hero_shredder/shredder_chakram_return.vpcf" local sound_cast = "Hero_Shredder.Chakram.Return" -- Create Particle -- self.effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_ABSORIGIN_FOLLOW, self.parent ) self.effect_cast = assert(loadfile("lua_abilities/rubick_spell_steal_lua/rubick_spell_steal_lua_arcana"))(self, particle_cast, PATTACH_ABSORIGIN_FOLLOW, self.parent ) ParticleManager:SetParticleControl( self.effect_cast, 0, self:GetParent():GetOrigin() ) ParticleManager:SetParticleControlEnt( self.effect_cast, 1, self.caster, PATTACH_ABSORIGIN_FOLLOW, nil, self.caster:GetOrigin(), -- unknown true -- unknown, true ) ParticleManager:SetParticleControl( self.effect_cast, 2, Vector( self.speed, 0, 0 ) ) ParticleManager:SetParticleControl( self.effect_cast, 16, Vector( 0, 0, 0 ) ) if self.scepter then -- set color to blue ParticleManager:SetParticleControl( self.effect_cast, 15, Vector( 0, 0, 255 ) ) ParticleManager:SetParticleControl( self.effect_cast, 16, Vector( 1, 0, 0 ) ) end -- Create Sound EmitSoundOn( sound_cast, self.parent ) end function modifier_timbersaw_chakram_lua_thinker:StopEffects() -- destroy previous particle ParticleManager:DestroyParticle( self.effect_cast, false ) ParticleManager:ReleaseParticleIndex( self.effect_cast ) -- stop sound local sound_cast = "Hero_Shredder.Chakram" StopSoundOn( sound_cast, self.parent ) end -- function modifier_timbersaw_chakram_lua_thinker:PlayEffects() -- -- Get Resources -- local particle_cast = "particles/units/heroes/hero_shredder/shredder_chakram_spin.vpcf" -- local sound_cast = "Hero_Shredder.Chakram" -- -- Create Particle -- local effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_CENTER_FOLLOW, self.parent ) -- ParticleManager:SetParticleControlEnt( -- effect_cast, -- 3, -- self.parent, -- PATTACH_CENTER_FOLLOW, -- nil, -- Vector( 0,0,0 ), -- unknown -- true -- unknown, true -- ) -- if self.scepter then -- -- set color to blue -- ParticleManager:SetParticleControl( effect_cast, 15, Vector( 0, 0, 255 ) ) -- ParticleManager:SetParticleControl( effect_cast, 16, Vector( 1, 0, 0 ) ) -- end -- -- buff particle -- self:AddParticle( -- effect_cast, -- false, -- bDestroyImmediately -- false, -- bStatusEffect -- -1, -- iPriority -- false, -- bHeroEffect -- false -- bOverheadEffect -- ) -- -- Create Sound -- EmitSoundOn( sound_cast, self.parent ) -- end
-- Format taken from y0ast: https://github.com/y0ast/VAE-Torch.git require 'hdf5' require 'torch' function loadmnist() -- This loads an hdf5 version of the MNIST dataset used here: -- http://deeplearning.net/tutorial/gettingstarted.html -- Direct link: http://deeplearning.net/data/mnist/mnist.pkl.gz local f = hdf5.open('datasets/mnist.hdf5', 'r') data = {} data.train = f:read('x_train'):all():double() data.test = f:read('x_test'):all():double() f:close() return data end function loadflipshift() -- This loads a data of a picture of an object in various positions local f = hdf5.open('datasets/flipshift.hdf5', 'r') data = {} data.train = f:read('dataset'):all():double() f:close() return data end function loadghost() local f = hdf5.open('animate/ghost.h5', 'r') data = {} data.train = f:read('dataset'):all():double() f:close() return data end function loadupdown() -- This loads a data of a picture of an object in various positions data = {} data.train = torch.load('datasets/updown.t7') return data end
Simulation { name = 'D1', description = 'Three-point Bending - D1 specimen - Omar et al. (2009)' } dofile('$SIMULATIONDIR/$SIMULATIONNAME_model.lua') dofile('$SIMULATIONDIR/$SIMULATIONNAME_solution.lua')
function Ability_Uber(player) local playersChar = player:GetControlledCharacter() if playersChar ~= nil then playersChar:SetInvulnerable(true) playersChar:SetDefaultMaterial(MaterialType.Masked) playersChar:SetMaterialColorParameter("Tint", Color(0, 0, 1)) Timer.SetTimeout(function(chara) if (chara:IsValid()) then chara:SetInvulnerable(false) chara:SetDefaultMaterial(MaterialType.None) end return false end, 6000, playersChar) end end Package.Export("Ability_Uber", Ability_Uber)
-- -- simplified version of the menu system used in durden: -- -- table of tables with: -- handler = function called on menu selection, -- label = static string or function returning dynamic string -- name = binding path keybindings -- hidden = don't show in UI menus -- local system = { { label = "Exit", name = "exit", handler = function() shutdown(); end }, { label = "Reset", name = "reset", handler = function() system_collapse(); end }, { label = "Screenshot", name = "screenshot", eval = function() return false; end, handler = function() prioactions.save_screenshot(); end }, { label = "Record", name = "record", -- eval = function() return false; end, handler = function() prioactions.record(); end } }; local function gen_show_menu() local res = {}; for k,v in ipairs(priohidden) do table.insert(res, { label = string.format("%d%s", k, (":") .. (v.ident and v.ident() or "")), name = "show_" .. tonumber(k), handler = function() v:show(); end }); end return res; end local global = { { label = "New", name = "new", handler = function() prio_input = prio_region_input; end }, { label = function() local cnt = 0; for k,v in pairs(priowindows) do cnt = cnt + 1; end return cnt > 0 and "Delete" or nil; end, name = "delete", handler = function() mouse_switch_cursor("destroy"); priostate = function(wnd) priostate = nil; mouse_switch_cursor(); if (wnd and not wnd.delete_protect) then wnd:destroy(); return true; end end end }, { label = function() local cnt = 0; for k,v in pairs(priowindows) do cnt = cnt + 1; end cnt = cnt - #priohidden; return cnt > 0 and "Hide" or nil; end, name = "hide", handler = function() mouse_switch_cursor("hide"); priostate = function(wnd) priostate = nil; mouse_switch_cursor(); if (wnd and not wnd.delete_protect) then wnd:hide(); return true; end end end }, { label = function() return #priohidden > 0 and "Show" or nil; end, name = "show", handler = function() local mx, my = mouse_xy(); prio_menu_spawn(gen_show_menu(), mx, my); end }, { label = "System", name = "system", handler = function() local mx, my = mouse_xy(); prio_menu_spawn(system, mx, my); end } }; local context = { { name = "paste", label = function(ctx) return "Paste(" .. string.sub(CLIPBOARD_MESSAGE, 1, 10) .. ")"; end, eval = function(ctx) return string.len(CLIPBOARD_MESSAGE) > 0; end, handler = function(ctx) ctx[1]:paste(CLIPBOARD_MESSAGE); end }, { label = function(ctx) local props = image_storage_properties(ctx[2].source); return (props.width ~= ctx[1].width or props.height ~= ctx[1].height) and "Set Source Size" or nil; end, name = "source_size", handler = function(ctx) local props = image_storage_properties(ctx[2].source); ctx[1]:resize(props.width, props.height); ctx[1]:synch_tab_sizes(); end }, { name = "toggle_force_size", label = function(ctx) return ctx[1].force_size and "Dynamic Size" or "Force Size" end, handler = function(ctx) ctx[1].force_size = not ctx[1].force_size; ctx[1]:resize(ctx[1].width, ctx[1].height); end }, { name = "toggle_mute", label = function(ctx) if (ctx[1].aid == nil or ctx[1].aid == BADID) then return; end return (ctx[1].mute and "Unmute" or "Mute"); end, handler = function(ctx) end }, { name = "close_tab", label = "Close", handler = function(ctx) ctx[1].lost(ctx[1], ctx[2].source); end }, { name = "save_img", label = "Output Image", eval = function() return false; end, handler = function(ctx) save_screenshot("prio_imgss.png", FORMAT_PNG, ctx[2].source); end }, }; function tab_menu(wnd, tab) local mx, my = mouse_xy(); prio_menu_spawn(context, mx, my, {wnd, tab}); end function cancel_menu() if (priomenu) then priomenu:destroy(); end mouse_switch_cursor(); end function prio_menu() local mx, my = mouse_xy(); mouse_switch_cursor(); prio_menu_spawn(global, mx, my); end
--[[ LUA MODULE complex v$(_VERSION) - complex numbers implemented as Lua tables SYNOPSIS local complex = require 'complex' local cx1 = complex "2+3i" -- or complex.new(2, 3) local cx2 = complex "3+2i" assert( complex.add(cx1,cx2) == complex "5+5i" ) assert( tostring(cx1) == "2+3i" ) DESCRIPTION 'complex' provides common tasks with complex numbers function complex.to( arg ); complex( arg ) returns a complex number on success, nil on failure arg := number or { number,number } or ( "(-)<number>" and/or "(+/-)<number>i" ) e.g. 5; {2,3}; "2", "2+i", "-2i", "2^2*3+1/3i" note: 'i' is always in the numerator, spaces are not allowed A complex number is defined as Cartesian complex number complex number := { real_part, imaginary_part } . This gives fast access to both parts of the number for calculation. The access is faster than in a hash table The metatable is just an add on. When it comes to speed, one is faster using a direct function call. API See code and test_complex.lua. DEPENDENCIES None (other than Lua 5.1 or 5.2). HOME PAGE http://luamatrix.luaforge.net http://lua-users.org/wiki/LuaMatrix DOWNLOAD/INSTALL ./util.mk cd tmp/* luarocks make Licensed under the same terms as Lua itself. Developers: Michael Lutz (chillcode) David Manura http://lua-users.org/wiki/DavidManura (maintainer) --]] --/////////////-- --// complex //-- --/////////////-- -- link to complex table local complex = {_TYPE = "module", _NAME = "complex", _VERSION = "0.3.3.20111212"} -- link to complex metatable local complex_meta = {} -- helper functions for parsing complex number strings. local function parse_scalar(s, pos0) local x, n, pos = s:match("^([+-]?[%d%.]+)(.?)()", pos0) if not x then return end if n == "e" or n == "E" then local x2, n2, pos2 = s:match("^([+-]?%d+)(.?)()", pos) if not x2 then error "number format error" end x = tonumber(x .. n .. x2) if not x then error "number format error" end return x, n2, pos2 else x = tonumber(x) if not x then error "number format error" end return x, n, pos end end local function parse_component(s, pos0) local x, n, pos = parse_scalar(s, pos0) if not x then local x2, n2, pos2 = s:match("^([+-]?)(i)()$", pos0) if not x2 then error "number format error" end return (x2 == "-" and -1 or 1), n2, pos2 end if n == "/" then local x2, n2, pos2 = parse_scalar(s, pos) x = x / x2 return x, n2, pos2 end return x, n, pos end local function parse_complex(s) local x, n, pos = parse_component(s, 1) if n == "+" or n == "-" then local x2, n2, pos2 = parse_component(s, pos) if n2 ~= "i" or pos2 ~= #s + 1 then error "number format error" end if n == "-" then x2 = -x2 end return x, x2 elseif n == "" then return x, 0 elseif n == "i" then if pos ~= #s + 1 then error "number format error" end return 0, x else error "number format error" end end -- complex.to( arg ) -- return a complex number on success -- return nil on failure function complex.to(num) -- check for table type if type(num) == "table" then -- check for a complex number if getmetatable(num) == complex_meta then return num end local real, imag = tonumber(num[1]), tonumber(num[2]) if real and imag then return setmetatable({real, imag}, complex_meta) end return end -- check for number local isnum = tonumber(num) if isnum then return setmetatable({isnum, 0}, complex_meta) end if type(num) == "string" then local real, imag = parse_complex(num) return setmetatable({real, imag}, complex_meta) end end -- complex( arg ) -- same as complex.to( arg ) -- set __call behaviour of complex setmetatable( complex, {__call = function(_, num) return complex.to(num) end} ) -- complex.new( real, complex ) -- fast function to get a complex number, not invoking any checks function complex.new(...) return setmetatable({...}, complex_meta) end -- complex.type( arg ) -- is argument of type complex function complex.type(arg) if getmetatable(arg) == complex_meta then return "complex" end end -- complex.convpolar( r, phi ) -- convert polar coordinates ( r*e^(i*phi) ) to carthesic complex number -- r (radius) is a number -- phi (angle) must be in radians; e.g. [0 - 2pi] function complex.convpolar(radius, phi) return setmetatable({radius * math.cos(phi), radius * math.sin(phi)}, complex_meta) end -- complex.convpolardeg( r, phi ) -- convert polar coordinates ( r*e^(i*phi) ) to carthesic complex number -- r (radius) is a number -- phi must be in degrees; e.g. [0 - 360 deg] function complex.convpolardeg(radius, phi) phi = phi / 180 * math.pi return setmetatable({radius * math.cos(phi), radius * math.sin(phi)}, complex_meta) end --// complex number functions only -- complex.tostring( cx [, formatstr] ) -- to string or real number -- takes a complex number and returns its string value or real number value function complex.tostring(cx, formatstr) local real, imag = cx[1], cx[2] if formatstr then if imag == 0 then return string.format(formatstr, real) elseif real == 0 then return string.format(formatstr, imag) .. "i" elseif imag > 0 then return string.format(formatstr, real) .. "+" .. string.format(formatstr, imag) .. "i" end return string.format(formatstr, real) .. string.format(formatstr, imag) .. "i" end if imag == 0 then return real elseif real == 0 then return ((imag == 1 and "") or (imag == -1 and "-") or imag) .. "i" elseif imag > 0 then return real .. "+" .. (imag == 1 and "" or imag) .. "i" end return real .. (imag == -1 and "-" or imag) .. "i" end -- complex.print( cx [, formatstr] ) -- print a complex number function complex.print(...) print(complex.tostring(...)) end -- complex.polar( cx ) -- from complex number to polar coordinates -- output in radians; [-pi,+pi] -- returns r (radius), phi (angle) function complex.polar(cx) return math.sqrt(cx[1] ^ 2 + cx[2] ^ 2), math.atan2(cx[2], cx[1]) end -- complex.polardeg( cx ) -- from complex number to polar coordinates -- output in degrees; [-180, 180 deg] -- returns r (radius), phi (angle) function complex.polardeg(cx) return math.sqrt(cx[1] ^ 2 + cx[2] ^ 2), math.atan2(cx[2], cx[1]) / math.pi * 180 end -- complex.norm2( cx ) -- multiply with conjugate, function returning a scalar number -- norm2(x + i*y) returns x^2 + y^2 function complex.norm2(cx) return cx[1] ^ 2 + cx[2] ^ 2 end -- complex.abs( cx ) -- get the absolute value of a complex number function complex.abs(cx) return math.sqrt(cx[1] ^ 2 + cx[2] ^ 2) end -- complex.get( cx ) -- returns real_part, imaginary_part function complex.get(cx) return cx[1], cx[2] end -- complex.set( cx, real, imag ) -- sets real_part = real and imaginary_part = imag function complex.set(cx, real, imag) cx[1], cx[2] = real, imag end -- complex.is( cx, real, imag ) -- returns true if, real_part = real and imaginary_part = imag -- else returns false function complex.is(cx, real, imag) if cx[1] == real and cx[2] == imag then return true end return false end --// functions returning a new complex number -- complex.copy( cx ) -- copy complex number function complex.copy(cx) return setmetatable({cx[1], cx[2]}, complex_meta) end -- complex.add( cx1, cx2 ) -- add two numbers; cx1 + cx2 function complex.add(cx1, cx2) return setmetatable({cx1[1] + cx2[1], cx1[2] + cx2[2]}, complex_meta) end -- complex.sub( cx1, cx2 ) -- subtract two numbers; cx1 - cx2 function complex.sub(cx1, cx2) return setmetatable({cx1[1] - cx2[1], cx1[2] - cx2[2]}, complex_meta) end -- complex.mul( cx1, cx2 ) -- multiply two numbers; cx1 * cx2 function complex.mul(cx1, cx2) return setmetatable({cx1[1] * cx2[1] - cx1[2] * cx2[2], cx1[1] * cx2[2] + cx1[2] * cx2[1]}, complex_meta) end -- complex.mulnum( cx, num ) -- multiply complex with number; cx1 * num function complex.mulnum(cx, num) return setmetatable({cx[1] * num, cx[2] * num}, complex_meta) end -- complex.div( cx1, cx2 ) -- divide 2 numbers; cx1 / cx2 function complex.div(cx1, cx2) -- get complex value local val = cx2[1] ^ 2 + cx2[2] ^ 2 -- multiply cx1 with conjugate complex of cx2 and divide through val return setmetatable( {(cx1[1] * cx2[1] + cx1[2] * cx2[2]) / val, (cx1[2] * cx2[1] - cx1[1] * cx2[2]) / val}, complex_meta ) end -- complex.divnum( cx, num ) -- divide through a number function complex.divnum(cx, num) return setmetatable({cx[1] / num, cx[2] / num}, complex_meta) end -- complex.pow( cx, num ) -- get the power of a complex number function complex.pow(cx, num) if math.floor(num) == num then if num < 0 then local val = cx[1] ^ 2 + cx[2] ^ 2 cx = {cx[1] / val, -cx[2] / val} num = -num end local real, imag = cx[1], cx[2] for i = 2, num do real, imag = real * cx[1] - imag * cx[2], real * cx[2] + imag * cx[1] end return setmetatable({real, imag}, complex_meta) end -- we calculate the polar complex number now -- since then we have the versatility to calc any potenz of the complex number -- then we convert it back to a carthesic complex number, we loose precision here local length, phi = math.sqrt(cx[1] ^ 2 + cx[2] ^ 2) ^ num, math.atan2(cx[2], cx[1]) * num return setmetatable({length * math.cos(phi), length * math.sin(phi)}, complex_meta) end -- complex.sqrt( cx ) -- get the first squareroot of a complex number, more accurate than cx^.5 function complex.sqrt(cx) local len = math.sqrt(cx[1] ^ 2 + cx[2] ^ 2) local sign = (cx[2] < 0 and -1) or 1 return setmetatable({math.sqrt((cx[1] + len) / 2), sign * math.sqrt((len - cx[1]) / 2)}, complex_meta) end -- complex.ln( cx ) -- natural logarithm of cx function complex.ln(cx) return setmetatable( { math.log(math.sqrt(cx[1] ^ 2 + cx[2] ^ 2)), math.atan2(cx[2], cx[1]) }, complex_meta ) end -- complex.exp( cx ) -- exponent of cx (e^cx) function complex.exp(cx) local expreal = math.exp(cx[1]) return setmetatable({expreal * math.cos(cx[2]), expreal * math.sin(cx[2])}, complex_meta) end -- complex.conjugate( cx ) -- get conjugate complex of number function complex.conjugate(cx) return setmetatable({cx[1], -cx[2]}, complex_meta) end -- complex.round( cx [,idp] ) -- round complex numbers, by default to 0 decimal points function complex.round(cx, idp) local mult = 10 ^ (idp or 0) return setmetatable( { math.floor(cx[1] * mult + 0.5) / mult, math.floor(cx[2] * mult + 0.5) / mult }, complex_meta ) end --// variables complex.zero = complex.new(0, 0) complex.one = complex.new(1, 0) --// metatable functions complex_meta.__add = function(cx1, cx2) local cx1, cx2 = complex.to(cx1), complex.to(cx2) return complex.add(cx1, cx2) end complex_meta.__sub = function(cx1, cx2) local cx1, cx2 = complex.to(cx1), complex.to(cx2) return complex.sub(cx1, cx2) end complex_meta.__mul = function(cx1, cx2) local cx1, cx2 = complex.to(cx1), complex.to(cx2) return complex.mul(cx1, cx2) end complex_meta.__div = function(cx1, cx2) local cx1, cx2 = complex.to(cx1), complex.to(cx2) return complex.div(cx1, cx2) end complex_meta.__pow = function(cx, num) if num == "*" then return complex.conjugate(cx) end return complex.pow(cx, num) end complex_meta.__unm = function(cx) return setmetatable({-cx[1], -cx[2]}, complex_meta) end complex_meta.__eq = function(cx1, cx2) if cx1[1] == cx2[1] and cx1[2] == cx2[2] then return true end return false end complex_meta.__tostring = function(cx) return tostring(complex.tostring(cx)) end complex_meta.__concat = function(cx, cx2) return tostring(cx) .. tostring(cx2) end -- cx( cx, formatstr ) complex_meta.__call = function(...) print(complex.tostring(...)) end complex_meta.__index = {} for k, v in pairs(complex) do complex_meta.__index[k] = v end return complex --///////////////-- --// chillcode //-- --///////////////--
return { name="Fill Basins With Water", description="Fill basins on heightmap with water", options= { {name="Max delta", type="value", value=0.0005}, {name="Offset Water Surface", type="value", value=0.002}, {name="Use Mask 0?", type="flag", value=false}, {name="Invert Mask 0?", type="flag", value=false}, {name="Use Mask 1?", type="flag", value=false}, {name="Invert Mask 1?", type="flag", value=false}, {name="Use Mask 2?", type="flag", value=false}, {name="Invert Mask 2?", type="flag", value=false}, }, execute=function(self) local ops=GetOptions(self.options) local E=ops["Max delta"] local off=ops["Offset Water Surface"] local arr=CArray2Dd() TerrainState:GetHeightMap(arr) FillBasins(arr,E) local ter=CArray2Dd() TerrainState:GetHeightMap(ter) arr:subtractArray(ter) local buf=CArray2Dd(arr:width(), arr:height()) local x,y local neighborIsNonZero=function(x,y) local i,j for i=-1,1,1 do for j=-1,1,1 do local nx=x+i local ny=y+j if nx>=0 and ny>=0 and nx<buf:width() and ny<buf:height() and nx~=x and ny~=y then if buf:get(nx,ny)>0 then return true end end end end return false end for x=0,arr:width()-1,1 do for y=0,arr:height()-1,1 do local msk=arr:get(x,y) if msk>0 then msk=1 end buf:set(x,y,msk) end end local buf2=CArray2Dd(arr:width(), arr:height()) for x=0,arr:width()-1,1 do for y=0,arr:height()-1,1 do local msk=buf:get(x,y) if neighborIsNonZero(x,y) then msk=1 end buf2:set(x,y,msk) end end --buf2:blur(0.005,false) for x=0,arr:width()-1,1 do for y=0,arr:height()-1,1 do local msk=buf2:get(x,y) arr:set(x,y,arr:get(x,y)+msk*ter:get(x,y)-off) end end local ms=MaskSettings(ops["Use Mask 0?"], ops["Invert Mask 0?"], ops["Use Mask 1?"], ops["Invert Mask 1?"], ops["Use Mask 2?"], ops["Invert Mask 2?"]) TerrainState:SetWaterBuffer(arr,ms,0) end }
local ESX = nil local lastJob = nil local lastGrade = nil local spawnedVeh = {} local lastarmor = 0 local lastskin = nil local pos_before_assist,assisting,assist_target,last_assist = nil, false, nil, nil RegisterNetEvent('esx_adminmode:onCommand') AddEventHandler('esx_adminmode:onCommand', function() local xPlayer = ESX.GetPlayerData() ESX.TriggerServerCallback("esx_adminmode:checkGroup",function(authed) if authed then if isOnDuty() then offDuty() else onDuty() end else --[[ Insert Ban Statement here if you would like to ban the player for cheating. The only way they would get to this line is if they manually called the event, which would signify cheating. --]] end end) end) function DeleteSpawnedVehicles() while #spawnedVeh > 0 do local vehicle = spawnedVeh[1] ESX.Game.DeleteVehicle(vehicle) table.remove(spawnedVeh, 1) end end function onDuty() local xPlayer = ESX.GetPlayerData() lastJob = xPlayer.job.name lastGrade = xPlayer.job.grade lastarmor = GetPedArmour(PlayerPedId()) local info = {} ESX.TriggerServerCallback('esx_adminmode:checkGroup', function(group) for k, v in ipairs(Config.Groups) do print(v.group) if group == v.group then info = v break end end TriggerServerEvent('esx_adminmode:setJob', info.job, info.grade) ESX.Streaming.RequestModel(info.ped, function() SetPlayerModel(PlayerId(), info.ped) SetModelAsNoLongerNeeded(info.ped) SetPedDefaultComponentVariation(PlayerPedId()) for k,v in ipairs(info.pedvari) do SetPedComponentVariation(GetPlayerPed(-1), v.component, v.texture-1, v.color-1, 0) end for k,v in ipairs(info.pedprop) do if v.texture == 0 then ClearPedProp(ped, v.component) else SetPedPropIndex(GetPlayerPed(-1), v.component, v.texture-1, v.color-1, v.attach) end end TriggerEvent('esx:restoreLoadout') if info.god then SetEntityInvincible(GetPlayerPed(-1), true) SetPlayerInvincible(PlayerId(), true) SetEntityOnlyDamagedByPlayer(GetPlayerPed(-1), false) SetEntityCanBeDamaged(GetPlayerPed(-1), false) SetEntityProofs(GetPlayerPed(-1), true, true, true, true, true, true, true, true) end if info.heal then SetPedCanRagdoll(GetPlayerPed(-1), false) ClearPedBloodDamage(GetPlayerPed(-1)) ResetPedVisibleDamage(GetPlayerPed(-1)) ClearPedLastWeaponDamage(GetPlayerPed(-1)) if Config.ESXStatus then TriggerEvent('esx_status:set', 'hunger', 1000000) TriggerEvent('esx_status:set', 'thirst', 1000000) TriggerEvent('esx_status:set', 'drunk', 0) TriggerEvent('esx_status:set', 'drug', 0) end if IsPedMale(PlayerPedId()) then SetEntityHealth(PlayerPedId(), 200) else SetEntityHealth(PlayerPedId(), 100) end end TriggerEvent("chat:addMessage",{color={0,255,0},multiline=false,args={"Admin Mode","Enabled!"}}) TriggerEvent('esx:restoreLoadout') if #spawnedVeh == 0 then ESX.Game.SpawnVehicle(info.car, GetEntityCoords(PlayerPedId()), GetEntityHeading(PlayerPedId()), function(callback_vehicle) Citizen.Wait(10) table.insert(spawnedVeh, callback_vehicle) for extra,enabled in ipairs(ESX.Game.GetVehicleProperties(callback_vehicle).extras) do enabled = false for _,eID in ipairs(info.extras) do if extra == eID then enabled = true end end end SetVehRadioStation(callback_vehicle, "OFF") SetVehicleFixed(callback_vehicle) SetVehicleDeformationFixed(callback_vehicle) SetVehicleUndriveable(callback_vehicle, 0) SetVehicleCanBeVisiblyDamaged(callback_vehicle, 0) SetEntityCanBeDamaged(callback_vehicle, 0) SetVehicleExclusiveDriver(callback_vehicle, PlayerPedId(), 0) SetVehicleExclusiveDriver_2(callback_vehicle, PlayerPedId(), 1) SetVehicleEngineOn(callback_vehicle, true, true, false) SetEntityProofs(callback_vehicle, 1, 1, 1, 1, 1, 1, 1, 1) SetVehicleStrong(callback_vehicle, true) SetVehicleLivery(callback_vehicle,info.vehlivery) TaskWarpPedIntoVehicle(GetPlayerPed(-1), callback_vehicle, -1) end) end end) end) end function offDuty() DeleteSpawnedVehicles() TriggerServerEvent('esx_adminmode:setJob', lastJob, lastGrade) lastJob = nil lastGrade = nil -- Ped Change ESX.TriggerServerCallback('esx_skin:getPlayerSkin', function(skin, jobSkin) local isMale = skin.sex == 0 TriggerEvent('skinchanger:loadDefaultModel', isMale, function() ESX.TriggerServerCallback('esx_skin:getPlayerSkin', function(skin) TriggerEvent('skinchanger:loadSkin', skin) TriggerEvent('esx:restoreLoadout') SetPedArmour(PlayerPedId(), lastarmor) SetEntityInvincible(GetPlayerPed(-1), false) SetPlayerInvincible(PlayerId(), false) SetPedCanRagdoll(GetPlayerPed(-1), true) ClearPedLastWeaponDamage(GetPlayerPed(-1)) SetEntityProofs(GetPlayerPed(-1), false, false, false, false, false, false, false, false) SetEntityOnlyDamagedByPlayer(GetPlayerPed(-1), true) SetEntityCanBeDamaged(GetPlayerPed(-1), true) TriggerEvent("chat:addMessage",{color={255,0,0},multiline=false,args={"Admin Mode","Disabled!"}}) end) end) end) end function isOnDuty() for k, v in ipairs(Config.Groups) do if ESX.GetPlayerData().job.name == v.job then return true end end return false end RegisterCommand("adminmode", function() local xPlayer = ESX.GetPlayerData() ESX.TriggerServerCallback("esx_adminmode:checkGroup",function(authed) if authed then TriggerEvent('esx_adminmode:onCommand') else TriggerEvent("chat:addMessage",{color={255,0,0},multiline=false,args={"Admin Mode","You do not have permission to use this command!"}}) end end) end) Citizen.CreateThread(function() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Citizen.Wait(0) end SetNuiFocus(false, false) if Config.assist_keys then Citizen.CreateThread(function() while true do Citizen.Wait(0) if IsControlJustPressed(0, Config.assist_keys.accept) then if not last_assist then ESX.ShowNotification("~r~Noone requested assistance yet") elseif not NetworkIsPlayerActive(GetPlayerFromServerId(last_assist)) then ESX.ShowNotification("~r~The player that requested assistance is not online anymore") last_assist=nil else TriggerServerEvent("esx_adminmode:acceptAssistKey",last_assist) end end if IsControlJustPressed(0, Config.assist_keys.decline) then TriggerEvent("esx_adminmode:hideAssistPopup") end end end) end end) function GetIndexedPlayerList() local players = {} for k,v in ipairs(GetActivePlayers()) do players[tostring(GetPlayerServerId(v))]=GetPlayerName(v)..(v==PlayerId() and " (self)" or "") end return json.encode(players) end RegisterNUICallback("ban", function(data,cb) if not data.target or not data.reason then return end ESX.TriggerServerCallback("esx_adminmode:ban",function(success,reason) if success then ESX.ShowNotification("~g~Successfully banned player") else ESX.ShowNotification(reason) end -- dont ask why i did it this way, im a bit retarded end, data.target, data.reason, data.length, data.offline) end) RegisterNUICallback("warn", function(data,cb) print('warn callback') if not data.target or not data.message then return end ESX.TriggerServerCallback("esx_adminmode:warn",function(success) if success then ESX.ShowNotification("~g~Successfully warned player") else ESX.ShowNotification("~r~Something went wrong") end end, data.target, data.message, data.anon) end) RegisterNUICallback("kick", function(data,cb) if not data.target or not data.message then return end ESX.TriggerServerCallback("esx_adminmode:kick",function(success) if success then ESX.ShowNotification("~g~Successfully kicked player") else ESX.ShowNotification("~r~Something went wrong") end end, data.target, data.message, data.anon) end) RegisterNUICallback("unban", function(data,cb) if not data.id then return end ESX.TriggerServerCallback("esx_adminmode:unban",function(success) if success then ESX.ShowNotification("~g~Successfully unbanned player") else ESX.ShowNotification("~r~Something went wrong") end end, data.id) end) RegisterNUICallback("getListData", function(data,cb) if not data.list or not data.page then cb(nil); return end ESX.TriggerServerCallback("esx_adminmode:getListData",function(data) cb(data) end, data.list, data.page) end) RegisterNUICallback("hidecursor", function(data,cb) SetNuiFocus(false, false) end) RegisterNetEvent("esx_adminmode:gotBanned") AddEventHandler("esx_adminmode:gotBanned",function(rsn) Citizen.CreateThread(function() local scaleform = RequestScaleformMovie("mp_big_message_freemode") while not HasScaleformMovieLoaded(scaleform) do Citizen.Wait(0) end BeginScaleformMovieMethod(scaleform, "SHOW_SHARD_WASTED_MP_MESSAGE") PushScaleformMovieMethodParameterString("~r~BANNED") PushScaleformMovieMethodParameterString(rsn) PushScaleformMovieMethodParameterInt(5) EndScaleformMovieMethod() PlaySoundFrontend(-1, "LOSER", "HUD_AWARDS") ClearDrawOrigin() ESX.UI.HUD.SetDisplay(0) while true do Citizen.Wait(0) DisableAllControlActions(0) DisableFrontendThisFrame() local ped = GetPlayerPed(-1) ESX.UI.Menu.CloseAll() SetEntityCoords(ped, 0, 0, 0, 0, 0, 0, false) FreezeEntityPosition(ped, true) DrawRect(0.0,0.0,2.0,2.0,0,0,0,255) DrawScaleformMovieFullscreen(scaleform, 255, 255, 255, 255) end SetScaleformMovieAsNoLongerNeeded(scaleform) end) end) RegisterNetEvent("esx_adminmode:receiveWarn") AddEventHandler("esx_adminmode:receiveWarn",function(sender,message) TriggerEvent("chat:addMessage",{color={255,255,0},multiline=true,args={"Admin Mode","You received a warning"..(sender~="" and " from "..sender or "").."!\n-> "..message}}) Citizen.CreateThread(function() local scaleform = RequestScaleformMovie("mp_big_message_freemode") while not HasScaleformMovieLoaded(scaleform) do Citizen.Wait(0) end BeginScaleformMovieMethod(scaleform, "SHOW_SHARD_WASTED_MP_MESSAGE") PushScaleformMovieMethodParameterString("~y~WARNING") PushScaleformMovieMethodParameterString(message) PushScaleformMovieMethodParameterInt(5) EndScaleformMovieMethod() PlaySoundFrontend(-1, "LOSER", "HUD_AWARDS") local drawing = true Citizen.SetTimeout(Config.warning_screentime,function() drawing = false end) while drawing do Citizen.Wait(0) DrawScaleformMovieFullscreen(scaleform, 255, 255, 255, 255) end SetScaleformMovieAsNoLongerNeeded(scaleform) end) end) RegisterNetEvent("esx_adminmode:requestedAssist") AddEventHandler("esx_adminmode:requestedAssist",function(t) SendNUIMessage({show=true,window="assistreq",data=Config.popassistformat:format(GetPlayerName(GetPlayerFromServerId(t)),t)}) last_assist=t end) RegisterNetEvent("esx_adminmode:acceptedAssist") AddEventHandler("esx_adminmode:acceptedAssist",function(t) if assisting then return end local target = GetPlayerFromServerId(t) if target then local ped = GetPlayerPed(-1) pos_before_assist = GetEntityCoords(ped) assisting = true assist_target = t ESX.Game.Teleport(ped,GetEntityCoords(GetPlayerPed(target))+vector3(0,0.5,0)) end end) RegisterNetEvent("esx_adminmode:assistDone") AddEventHandler("esx_adminmode:assistDone",function() if assisting then assisting = false if pos_before_assist~=nil then ESX.Game.Teleport(GetPlayerPed(-1),pos_before_assist+vector3(0,0.5,0)); pos_before_assist = nil end assist_target = nil end end) RegisterNetEvent("esx_adminmode:hideAssistPopup") AddEventHandler("esx_adminmode:hideAssistPopup",function(t) SendNUIMessage({hide=true}) last_assist=nil end) RegisterNetEvent("esx_adminmode:showWindow") AddEventHandler("esx_adminmode:showWindow",function(win) if win=="ban" or win=="warn" or win=="kick" then SendNUIMessage({show=true,window=win,players=GetIndexedPlayerList()}) elseif win=="banlist" or win=="warnlist" then SendNUIMessage({loading=true,window=win}) ESX.TriggerServerCallback(win=="banlist" and "esx_adminmode:getBanList" or "esx_adminmode:getWarnList",function(list,pages) SendNUIMessage({show=true,window=win,list=list,pages=pages}) end) end SetNuiFocus(true, true) end) RegisterCommand("decassist",function(a,b,c) TriggerEvent("esx_adminmode:hideAssistPopup") end, false)
local settings = require "settings" local unit = settings.gridwidth --todo make Grid inherit from Array2d --Singleton --the interface table --singleton class local Grid = {} --the value table local grid = {} function Grid:reset() grid = {} end function Grid:set(x, y) if grid[x] == nil then grid[x] = {} end grid[x][y] = true end function Grid:get(x, y) if grid[x] == nil then return false else if grid[x][y] == true then return true else return false end end end function Grid:delete(x, y) if grid[x] ~= nil then grid[x][y] = nil end end function Grid:deleteColumn(x) grid[x] = nil end function Grid:deleteRow(y) for k, v in pairs(grid) do if grid[k][y] ~= nil then grid[k][y] = nil end end end function Grid:draw() for kx, vx in pairs(grid) do for ky, vy in pairs(vx) do local x = kx * unit local y = ky * unit love.graphics.setColor(150 / 255, 150 / 255, 255 / 255, 127 / 255) love.graphics.rectangle("fill", x, y, unit, unit) love.graphics.setColor(1, 1, 1, 1) local coords = "(" .. kx .. ", " .. ky .. ")" --love.graphics.print(coords, x + halfunit - 40, y + halfunit - 40) end end end function Grid:print() for kx, vx in pairs(grid) do for ky, vy in pairs(vx) do print(kx, ky, vy) end end end function Grid:getGridCoords(x, y) local gridx, gridy = 0, 0 if x >= 0 then while x >= unit do gridx = gridx + 1 x = x - unit end else while x < 0 do gridx = gridx - 1 x = x + unit end end if y >= 0 then while y >= unit do gridy = gridy + 1 y = y - unit end else while y < 0 do gridy = gridy - 1 y = y + unit end end return gridx, gridy end return Grid
JOBID = { JT_NOVICE = 0, JT_SWORDMAN = 1, JT_MAGICIAN = 2, JT_ARCHER = 3, JT_ACOLYTE = 4, JT_MERCHANT = 5, JT_THIEF = 6, JT_KNIGHT = 7, JT_PRIEST = 8, JT_WIZARD = 9, JT_BLACKSMITH = 10, JT_HUNTER = 11, JT_ASSASSIN = 12, JT_CHICKEN = 13, JT_CRUSADER = 14, JT_MONK = 15, JT_SAGE = 16, JT_ROGUE = 17, JT_ALCHEMIST = 18, JT_BARD = 19, JT_DANCER = 20, JT_CHICKEN2 = 21, JT_MARRIED = 22, JT_SUPERNOVICE = 23, JT_GUNSLINGER = 24, JT_NINJA = 25, JT_SANTA = 26, JT_SUMMER = 27, JT_HANBOK = 28, JT_OKTOBERFEST = 29, JT_SUMMER2 = 30, JT_NOVICE_H = 4001, JT_SWORDMAN_H = 4002, JT_MAGICIAN_H = 4003, JT_ARCHER_H = 4004, JT_ACOLYTE_H = 4005, JT_MERCHANT_H = 4006, JT_THIEF_H = 4007, JT_KNIGHT_H = 4008, JT_PRIEST_H = 4009, JT_WIZARD_H = 4010, JT_BLACKSMITH_H = 4011, JT_HUNTER_H = 4012, JT_ASSASSIN_H = 4013, JT_CHICKEN_H = 4014, JT_CRUSADER_H = 4015, JT_MONK_H = 4016, JT_SAGE_H = 4017, JT_ROGUE_H = 4018, JT_ALCHEMIST_H = 4019, JT_BARD_H = 4020, JT_DANCER_H = 4021, JT_CHICKEN2_H = 4022, JT_NOVICE_B = 4023, JT_SWORDMAN_B = 4024, JT_MAGICIAN_B = 4025, JT_ARCHER_B = 4026, JT_ACOLYTE_B = 4027, JT_MERCHANT_B = 4028, JT_THIEF_B = 4029, JT_KNIGHT_B = 4030, JT_PRIEST_B = 4031, JT_WIZARD_B = 4032, JT_BLACKSMITH_B = 4033, JT_HUNTER_B = 4034, JT_ASSASSIN_B = 4035, JT_CHICKEN_B = 4036, JT_CRUSADER_B = 4037, JT_MONK_B = 4038, JT_SAGE_B = 4039, JT_ROGUE_B = 4040, JT_ALCHEMIST_B = 4041, JT_BARD_B = 4042, JT_DANCER_B = 4043, JT_CHICKEN2_B = 4044, JT_SUPERNOVICE_B = 4045, JT_TAEKWON = 4046, JT_STAR = 4047, JT_STAR2 = 4048, JT_LINKER = 4049, JT_GANGSI = 4050, JT_DEATHKNIGHT = 4051, JT_COLLECTOR = 4052, JT_THIRDJOB_BEGIN = 4053, JT_RUNE_KNIGHT = 4054, JT_WARLOCK = 4055, JT_RANGER = 4056, JT_ARCHBISHOP = 4057, JT_MECHANIC = 4058, JT_GUILLOTINE_CROSS = 4059, JT_RUNE_KNIGHT_H = 4060, JT_WARLOCK_H = 4061, JT_RANGER_H = 4062, JT_ARCHBISHOP_H = 4063, JT_MECHANIC_H = 4064, JT_GUILLOTINE_CROSS_H = 4065, JT_ROYAL_GUARD = 4066, JT_SORCERER = 4067, JT_MINSTREL = 4068, JT_WANDERER = 4069, JT_SURA = 4070, JT_GENETIC = 4071, JT_SHADOW_CHASER = 4072, JT_ROYAL_GUARD_H = 4073, JT_SORCERER_H = 4074, JT_MINSTREL_H = 4075, JT_WANDERER_H = 4076, JT_SURA_H = 4077, JT_GENETIC_H = 4078, JT_SHADOW_CHASER_H = 4079, JT_RUNE_CHICKEN = 4080, JT_RUNE_CHICKEN_H = 4081, JT_ROYAL_CHICKEN = 4082, JT_ROYAL_CHICKEN_H = 4083, JT_WOLF_RANGER = 4084, JT_WOLF_RANGER_H = 4085, JT_MADOGEAR = 4086, JT_MADOGEAR_H = 4087, JT_RUNE_CHICKEN2 = 4088, JT_RUNE_CHICKEN2_H = 4089, JT_RUNE_CHICKEN3 = 4090, JT_RUNE_CHICKEN3_H = 4091, JT_RUNE_CHICKEN4 = 4092, JT_RUNE_CHICKEN4_H = 4093, JT_RUNE_CHICKEN5 = 4094, JT_RUNE_CHICKEN5_H = 4095, JT_RUNE_KNIGHT_B = 4096, JT_WARLOCK_B = 4097, JT_RANGER_B = 4098, JT_ARCHBISHOP_B = 4099, JT_MECHANIC_B = 4100, JT_GUILLOTINE_CROSS_B = 4101, JT_ROYAL_GUARD_B = 4102, JT_SORCERER_B = 4103, JT_MINSTREL_B = 4104, JT_WANDERER_B = 4105, JT_SURA_B = 4106, JT_GENETIC_B = 4107, JT_SHADOW_CHASER_B = 4108, JT_RUNE_CHICKEN_B = 4109, JT_ROYAL_CHICKEN_B = 4110, JT_WOLF_RANGER_B = 4111, JT_MADOGEAR_B = 4112, JT_THIRDJOB_END = 4113, JT_FROG_NINJA = 4114, JT_PECO_GUNNER = 4115, JT_PECO_SWORD = 4116, JT_FROG_LINKER = 4117, JT_PIG_WHITESMITH = 4118, JT_PIG_MERCHANT = 4119, JT_PIG_GENETIC = 4120, JT_PIG_CREATOR = 4121, JT_OSTRICH_ARCHER = 4122, JT_PORING_STAR = 4123, JT_PORING_NOVICE = 4124, JT_SHEEP_MONK = 4125, JT_SHEEP_ACO = 4126, JT_SHEEP_SURA = 4127, JT_PORING_SNOVICE = 4128, JT_SHEEP_ARCB = 4129, JT_FOX_MAGICIAN = 4130, JT_FOX_SAGE = 4131, JT_FOX_SORCERER = 4132, JT_FOX_WARLOCK = 4133, JT_FOX_WIZ = 4134, JT_FOX_PROF = 4135, JT_FOX_HWIZ = 4136, JT_PIG_ALCHE = 4137, JT_PIG_BLACKSMITH = 4138, JT_SHEEP_CHAMP = 4139, JT_DOG_G_CROSS = 4140, JT_DOG_THIEF = 4141, JT_DOG_ROGUE = 4142, JT_DOG_CHASER = 4143, JT_DOG_STALKER = 4144, JT_DOG_ASSASSIN = 4145, JT_DOG_ASSA_X = 4146, JT_OSTRICH_DANCER = 4147, JT_OSTRICH_MINSTREL = 4148, JT_OSTRICH_BARD = 4149, JT_OSTRICH_SNIPER = 4150, JT_OSTRICH_WANDER = 4151, JT_OSTRICH_ZIPSI = 4152, JT_OSTRICH_CROWN = 4153, JT_OSTRICH_HUNTER = 4154, JT_PORING_TAEKWON = 4155, JT_SHEEP_PRIEST = 4156, JT_SHEEP_HPRIEST = 4157, JT_PORING_NOVICE_B = 4158, JT_PECO_SWORD_B = 4159, JT_FOX_MAGICIAN_B = 4160, JT_OSTRICH_ARCHER_B = 4161, JT_SHEEP_ACO_B = 4162, JT_PIG_MERCHANT_B = 4163, JT_OSTRICH_HUNTER_B = 4164, JT_DOG_ASSASSIN_B = 4165, JT_SHEEP_MONK_B = 4166, JT_FOX_SAGE_B = 4167, JT_DOG_ROGUE_B = 4168, JT_PIG_ALCHE_B = 4169, JT_OSTRICH_BARD_B = 4170, JT_OSTRICH_DANCER_B = 4171, JT_PORING_SNOVICE_B = 4172, JT_FOX_WARLOCK_B = 4173, JT_SHEEP_ARCB_B = 4174, JT_DOG_G_CROSS_B = 4175, JT_FOX_SORCERER_B = 7176, JT_OSTRICH_MINSTREL_B = 4177, JT_OSTRICH_WANDER_B = 4178, JT_SHEEP_SURA_B = 4179, JT_PIG_GENETIC_B = 4180, JT_DOG_THIEF_B = 4181, JT_DOG_CHASER_B = 4182, JT_PORING_NOVICE_H = 4183, JT_PECO_SWORD_H = 4184, JT_FOX_MAGICIAN_H = 4185, JT_OSTRICH_ARCHER_H = 4186, JT_SHEEP_ACO_H = 4187, JT_PIG_MERCHANT_H = 4188, JT_DOG_THIEF_H = 4189, JT_SUPERNOVICE2 = 4190, JT_SUPERNOVICE2_B = 4191, JT_PORING_SNOVICE2 = 4192, JT_PORING_SNOVICE2_B = 4193, JT_SHEEP_PRIEST_B = 4194, JT_FOX_WIZ_B = 4195, JT_PIG_BLACKSMITH_B = 4196, JT_PIG_MECHANIC = 4197, JT_OSTRICH_RANGER = 4198, JT_LION_KNIGHT = 4199, JT_LION_KNIGHT_H = 4200, JT_LION_ROYAL_GUARD = 4201, JT_LION_RUNE_KNIGHT = 4202, JT_LION_CRUSADER = 4203, JT_LION_CRUSADER_H = 4204, JT_PIG_MECHANIC_B = 4205, JT_OSTRICH_RANGER_B = 4206, JT_LION_KNIGHT_B = 4207, JT_LION_ROYAL_GUARD_B = 4208, JT_LION_RUNE_KNIGHT_B = 4209, JT_LION_CRUSADER_B = 4210, JT_KAGEROU = 4211, JT_OBORO = 4212, JT_FROG_KAGEROU = 4213, JT_FROG_OBORO = 4214, JT_REBELLION = 4215, JT_PECO_REBELLION = 4216, JT_2004_JOB_LAST = 4217, JT_DO_SUMMONER = 4218, JT_DO_SUMMONER_B = 4220, JT_NINJA_B = 4222, JT_KAGEROU_B = 4223, JT_OBORO_B = 4224, JT_TAEKWON_B = 4225, JT_STAR_B = 4226, JT_LINKER_B = 4227, JT_GUNSLINGER_B = 4228, JT_REBELLION_B = 4229 } JOB_INHERIT_LIST = { [JOBID.JT_SWORDMAN] = JOBID.JT_NOVICE, [JOBID.JT_MAGICIAN] = JOBID.JT_NOVICE, [JOBID.JT_ARCHER] = JOBID.JT_NOVICE, [JOBID.JT_ACOLYTE] = JOBID.JT_NOVICE, [JOBID.JT_MERCHANT] = JOBID.JT_NOVICE, [JOBID.JT_THIEF] = JOBID.JT_NOVICE, [JOBID.JT_KNIGHT] = JOBID.JT_SWORDMAN, [JOBID.JT_PRIEST] = JOBID.JT_ACOLYTE, [JOBID.JT_WIZARD] = JOBID.JT_MAGICIAN, [JOBID.JT_BLACKSMITH] = JOBID.JT_MERCHANT, [JOBID.JT_HUNTER] = JOBID.JT_ARCHER, [JOBID.JT_ASSASSIN] = JOBID.JT_THIEF, [JOBID.JT_CRUSADER] = JOBID.JT_SWORDMAN, [JOBID.JT_MONK] = JOBID.JT_ACOLYTE, [JOBID.JT_SAGE] = JOBID.JT_MAGICIAN, [JOBID.JT_ROGUE] = JOBID.JT_THIEF, [JOBID.JT_ALCHEMIST] = JOBID.JT_MERCHANT, [JOBID.JT_BARD] = JOBID.JT_ARCHER, [JOBID.JT_DANCER] = JOBID.JT_ARCHER, [JOBID.JT_SUPERNOVICE] = JOBID.JT_NOVICE, [JOBID.JT_GUNSLINGER] = JOBID.JT_NOVICE, [JOBID.JT_NINJA] = JOBID.JT_NOVICE, [JOBID.JT_NOVICE_H] = JOBID.JT_NOVICE, [JOBID.JT_SWORDMAN_H] = JOBID.JT_SWORDMAN, [JOBID.JT_MAGICIAN_H] = JOBID.JT_MAGICIAN, [JOBID.JT_ARCHER_H] = JOBID.JT_ARCHER, [JOBID.JT_ACOLYTE_H] = JOBID.JT_ACOLYTE, [JOBID.JT_MERCHANT_H] = JOBID.JT_MERCHANT, [JOBID.JT_THIEF_H] = JOBID.JT_THIEF, [JOBID.JT_KNIGHT_H] = JOBID.JT_KNIGHT, [JOBID.JT_PRIEST_H] = JOBID.JT_PRIEST, [JOBID.JT_WIZARD_H] = JOBID.JT_WIZARD, [JOBID.JT_BLACKSMITH_H] = JOBID.JT_BLACKSMITH, [JOBID.JT_HUNTER_H] = JOBID.JT_HUNTER, [JOBID.JT_ASSASSIN_H] = JOBID.JT_ASSASSIN, [JOBID.JT_CRUSADER_H] = JOBID.JT_CRUSADER, [JOBID.JT_MONK_H] = JOBID.JT_MONK, [JOBID.JT_SAGE_H] = JOBID.JT_SAGE, [JOBID.JT_ROGUE_H] = JOBID.JT_ROGUE, [JOBID.JT_ALCHEMIST_H] = JOBID.JT_ALCHEMIST, [JOBID.JT_BARD_H] = JOBID.JT_BARD, [JOBID.JT_DANCER_H] = JOBID.JT_DANCER, [JOBID.JT_NOVICE_B] = JOBID.JT_NOVICE, [JOBID.JT_SWORDMAN_B] = JOBID.JT_SWORDMAN, [JOBID.JT_MAGICIAN_B] = JOBID.JT_MAGICIAN, [JOBID.JT_ARCHER_B] = JOBID.JT_ARCHER, [JOBID.JT_ACOLYTE_B] = JOBID.JT_ACOLYTE, [JOBID.JT_MERCHANT_B] = JOBID.JT_MERCHANT, [JOBID.JT_THIEF_B] = JOBID.JT_THIEF, [JOBID.JT_KNIGHT_B] = JOBID.JT_KNIGHT, [JOBID.JT_PRIEST_B] = JOBID.JT_PRIEST, [JOBID.JT_WIZARD_B] = JOBID.JT_WIZARD, [JOBID.JT_BLACKSMITH_B] = JOBID.JT_BLACKSMITH, [JOBID.JT_HUNTER_B] = JOBID.JT_HUNTER, [JOBID.JT_ASSASSIN_B] = JOBID.JT_ASSASSIN, [JOBID.JT_CRUSADER_B] = JOBID.JT_CRUSADER, [JOBID.JT_MONK_B] = JOBID.JT_MONK, [JOBID.JT_SAGE_B] = JOBID.JT_SAGE, [JOBID.JT_ROGUE_B] = JOBID.JT_ROGUE, [JOBID.JT_ALCHEMIST_B] = JOBID.JT_ALCHEMIST, [JOBID.JT_BARD_B] = JOBID.JT_BARD, [JOBID.JT_DANCER_B] = JOBID.JT_DANCER, [JOBID.JT_SUPERNOVICE_B] = JOBID.JT_SUPERNOVICE, [JOBID.JT_TAEKWON] = JOBID.JT_NOVICE, [JOBID.JT_STAR] = JOBID.JT_TAEKWON, [JOBID.JT_LINKER] = JOBID.JT_TAEKWON, [JOBID.JT_RUNE_KNIGHT] = JOBID.JT_KNIGHT, [JOBID.JT_WARLOCK] = JOBID.JT_WIZARD, [JOBID.JT_RANGER] = JOBID.JT_HUNTER, [JOBID.JT_ARCHBISHOP] = JOBID.JT_PRIEST, [JOBID.JT_MECHANIC] = JOBID.JT_BLACKSMITH, [JOBID.JT_GUILLOTINE_CROSS] = JOBID.JT_ASSASSIN, [JOBID.JT_RUNE_KNIGHT_H] = JOBID.JT_KNIGHT_H, [JOBID.JT_WARLOCK_H] = JOBID.JT_WIZARD_H, [JOBID.JT_RANGER_H] = JOBID.JT_HUNTER_H, [JOBID.JT_ARCHBISHOP_H] = JOBID.JT_PRIEST_H, [JOBID.JT_MECHANIC_H] = JOBID.JT_BLACKSMITH_H, [JOBID.JT_GUILLOTINE_CROSS_H] = JOBID.JT_ASSASSIN_H, [JOBID.JT_ROYAL_GUARD] = JOBID.JT_CRUSADER, [JOBID.JT_SORCERER] = JOBID.JT_SAGE, [JOBID.JT_MINSTREL] = JOBID.JT_BARD, [JOBID.JT_WANDERER] = JOBID.JT_DANCER, [JOBID.JT_SURA] = JOBID.JT_MONK, [JOBID.JT_GENETIC] = JOBID.JT_ALCHEMIST, [JOBID.JT_SHADOW_CHASER] = JOBID.JT_ROGUE, [JOBID.JT_ROYAL_GUARD_H] = JOBID.JT_CRUSADER_H, [JOBID.JT_SORCERER_H] = JOBID.JT_SAGE_H, [JOBID.JT_MINSTREL_H] = JOBID.JT_BARD_H, [JOBID.JT_WANDERER_H] = JOBID.JT_DANCER_H, [JOBID.JT_SURA_H] = JOBID.JT_MONK_H, [JOBID.JT_GENETIC_H] = JOBID.JT_ALCHEMIST_H, [JOBID.JT_SHADOW_CHASER_H] = JOBID.JT_ROGUE_H, [JOBID.JT_RUNE_KNIGHT_B] = JOBID.JT_RUNE_KNIGHT, [JOBID.JT_WARLOCK_B] = JOBID.JT_WARLOCK, [JOBID.JT_RANGER_B] = JOBID.JT_RANGER, [JOBID.JT_ARCHBISHOP_B] = JOBID.JT_ARCHBISHOP, [JOBID.JT_MECHANIC_B] = JOBID.JT_MECHANIC, [JOBID.JT_GUILLOTINE_CROSS_B] = JOBID.JT_GUILLOTINE_CROSS, [JOBID.JT_ROYAL_GUARD_B] = JOBID.JT_ROYAL_GUARD, [JOBID.JT_SORCERER_B] = JOBID.JT_SORCERER, [JOBID.JT_MINSTREL_B] = JOBID.JT_MINSTREL, [JOBID.JT_WANDERER_B] = JOBID.JT_WANDERER, [JOBID.JT_SURA_B] = JOBID.JT_SURA, [JOBID.JT_GENETIC_B] = JOBID.JT_GENETIC, [JOBID.JT_SHADOW_CHASER_B] = JOBID.JT_SHADOW_CHASER, [JOBID.JT_SUPERNOVICE2] = JOBID.JT_SUPERNOVICE, [JOBID.JT_SUPERNOVICE2_B] = JOBID.JT_SUPERNOVICE2, [JOBID.JT_KAGEROU] = JOBID.JT_NINJA, [JOBID.JT_OBORO] = JOBID.JT_NINJA, [JOBID.JT_REBELLION] = JOBID.JT_GUNSLINGER, [JOBID.JT_KAGEROU_B] = JOBID.JT_KAGEROU, [JOBID.JT_OBORO_B] = JOBID.JT_OBORO, [JOBID.JT_REBELLION_B] = JOBID.JT_REBELLION, [JOBID.JT_NINJA_B] = JOBID.JT_NINJA, [JOBID.JT_GUNSLINGER_B] = JOBID.JT_GUNSLINGER, [JOBID.JT_TAEKWON_B] = JOBID.JT_TAEKWON, [JOBID.JT_LINKER_B] = JOBID.JT_LINKER, [JOBID.JT_STAR_B] = JOBID.JT_STAR, __newindex = function() error("unknown state") end } setmetatable(JOB_INHERIT_LIST, JOB_INHERIT_LIST) JOB_INHERIT_LIST2 = { [JOBID.JT_RUNE_KNIGHT_H] = JOBID.JT_RUNE_KNIGHT, [JOBID.JT_WARLOCK_H] = JOBID.JT_WARLOCK, [JOBID.JT_RANGER_H] = JOBID.JT_RANGER, [JOBID.JT_ARCHBISHOP_H] = JOBID.JT_ARCHBISHOP, [JOBID.JT_MECHANIC_H] = JOBID.JT_MECHANIC, [JOBID.JT_GUILLOTINE_CROSS_H] = JOBID.JT_GUILLOTINE_CROSS, [JOBID.JT_ROYAL_GUARD_H] = JOBID.JT_ROYAL_GUARD, [JOBID.JT_SORCERER_H] = JOBID.JT_SORCERER, [JOBID.JT_MINSTREL_H] = JOBID.JT_MINSTREL, [JOBID.JT_WANDERER_H] = JOBID.JT_WANDERER, [JOBID.JT_SURA_H] = JOBID.JT_SURA, [JOBID.JT_GENETIC_H] = JOBID.JT_GENETIC, [JOBID.JT_SHADOW_CHASER_H] = JOBID.JT_SHADOW_CHASER, __newindex = function() error("unknown state") end } setmetatable(JOB_INHERIT_LIST2, JOB_INHERIT_LIST2)
--[[ Simple paint program to demonstrate display & touch on ILI9341 based displays Author: LoBo, loboris@gmail.com (https://github.com/loboris) To load the program execute 'dofile("paint.lua")' or 'require("paint")' To run the program: set the display orientation (optional), 'paint.orient=tft.LANDSCAPE_FLIP' execute 'paint.run()' to start the program Program can also be run in the thread: set the display orientation (optional), 'paint.orient=tft.LANDSCAPE_FLIP' 'paint_th = thread.start(paint.run)' ]]-- paint = { orient = tft.PORTRAIT_FLIP, running = false } -- ------------------------ -- Wait for touch event -- ------------------------ function paint.wait(tpwait) local touch while true do touch, _, _ = tft.gettouch() if ((touch > 0) and (tpwait == 1)) or ((touch == 0) and (tpwait == 0)) then break end tmr.sleepms(10) end end -- ------------------------------------ -- Display selection bars and some info -- ------------------------------------ function paint.paint_info() local dispx, dispy, dx, dy, dw, dh, fp, i tft.setorient(paint.orient) tft.setfont(tft.FONT_DEFAULT) tft.setrot(0) tft.setfixed(0) tft.clear(tft.BLACK) dispx, dispy = tft.getscreensize() dx = dispx // 8 dw,dh = tft.getfontsize() dy = dispy - dh - 5 fp = math.ceil((dx // 2) - (dw // 2)) -- draw color bar, orange selected tft.rect(dx*0,0,dx-2,18,tft.BLACK,tft.BLACK) tft.rect(dx*1,0,dx-2,18,tft.WHITE,tft.WHITE) tft.rect(dx*2,0,dx-2,18,tft.RED,tft.RED) tft.rect(dx*3,0,dx-2,18,tft.GREEN,tft.GREEN) tft.rect(dx*4,0,dx-2,18,tft.BLUE,tft.BLUE) tft.rect(dx*5,0,dx-2,18,tft.YELLOW,tft.YELLOW) tft.rect(dx*6,0,dx-2,18,tft.CYAN,tft.CYAN) tft.rect(dx*7,0,dx-2,18,tft.ORANGE,tft.ORANGE) tft.rect(dx*7+2,2,dx-6,14,tft.WHITE, tft.ORANGE) tft.rect(dx*7+3,3,dx-8,12,tft.BLACK, tft.ORANGE) for i=1,7,1 do tft.line(dx*i-1,0,dx*i-1,18,tft.LIGHTGREY) tft.line(dx*i-2,0,dx*i-2,18,tft.LIGHTGREY) end tft.line(0,18,dispx,18,tft.LIGHTGREY) -- draw functions bar, size 2 selected tft.rect(dx*0,dy,dx-2,dispy-dy,tft.LIGHTGREY) tft.rect(dx*1,dy,dx-2,dispy-dy,tft.YELLOW) tft.rect(dx*2,dy,dx-2,dispy-dy,tft.LIGHTGREY) tft.rect(dx*3,dy,dx-2,dispy-dy,tft.LIGHTGREY) tft.rect(dx*4,dy,dx-2,dispy-dy,tft.LIGHTGREY) tft.rect(dx*5,dy,dx-2,dispy-dy,tft.LIGHTGREY) tft.rect(dx*6,dy,dx-2,dispy-dy,tft.LIGHTGREY) tft.rect(dx*7,dy,dx-2,dispy-dy,tft.LIGHTGREY) -- write info tft.setcolor(tft.CYAN) tft.write(dx*0+fp,dy+3,"2") tft.write(dx*1+fp,dy+3,"4") tft.write(dx*2+fp,dy+3,"6") tft.write(dx*3+fp,dy+3,"8") tft.write(dx*4+fp-3,dy+3,"10") --tft.write(dx*5+fp,dy+3,"S") tft.circle(dx*5+((dx-2) // 2), dy+((dispy-dy) // 2), (dispy-dy) // 2 - 2, tft.LIGHTGREY, tft.LIGHTGREY) tft.write(dx*6+fp,dy+3,"C") tft.write(dx*7+fp,dy+3,"R") tft.setcolor(tft.YELLOW) tft.write(60,40,"S") tft.setcolor(tft.CYAN) tft.write(tft.LASTX,tft.LASTY," change shape") tft.circle(60+(dw // 2), 40+(dh // 2), dh // 2 + 1, tft.LIGHTGREY, tft.LIGHTGREY) tft.setcolor(tft.YELLOW) tft.write(60,dh*2+40,"C") tft.setcolor(tft.CYAN) tft.write(tft.LASTX,tft.LASTY," Clear screen") tft.setcolor(tft.YELLOW) tft.write(60,dh*4+40,"R") tft.setcolor(tft.CYAN) tft.write(tft.LASTX,tft.LASTY," Return, exit program") tft.setcolor(tft.YELLOW) tft.write(60,dh*6+40,"2,4,6,8") tft.setcolor(tft.CYAN) tft.write(tft.LASTX,tft.LASTY," draw size") tft.setcolor(tft.ORANGE) tft.setfont(tft.FONT_UBUNTU16) tft.write(tft.CENTER,dh*10+40,"Touch screen to start") tft.setfont(tft.FONT_DEFAULT) paint.wait(0) paint.wait(1) paint.wait(0) tft.rect(0,20,dispx,dy-20,tft.BLACK,tft.BLACK) return dx, dy end -- ----------------- -- Paint main loop -- ----------------- function paint.run() if paint.running then print("Already running") return end if tft.gettype() ~= 1 then print("LCD not initialized or wrong type") return end local dispx, dispy, dx, dy, x, y, touch, lx, lx, first, drw, dodrw, color, lastc, lastr paint.running = true dx, dy = paint.paint_info() dispx, dispy = tft.getscreensize() first = true drw = 1 color = tft.ORANGE lastc = dx*7 r = 4 lastr = dx while true do tmr.sleepms(10) -- get touch status and coordinates touch, x, y = tft.gettouch() if touch > 0 then if first and ((y < 20) or (y > dy)) then -- color or functions bar touched -- check if after 100 ms we are on the same position lx = x ly = y tmr.sleepms(100) paint.wait(1) if (math.abs(x-lx) < 4) and (math.abs(y-ly) < 4) then if (y < 20) then -- === first touch, upper bar touched: color select === tft.rect(lastc,0,dx-2,18,color,color) if x > (dx*7) then color = tft.ORANGE lastc = dx*7 elseif x > (dx*6) then color = tft.CYAN lastc = dx*6 elseif x > (dx*5) then color = tft.YELLOW lastc = dx*5 elseif x > (dx*4) then color = tft.BLUE lastc = dx*4 elseif x > (dx*3) then color = tft.GREEN lastc = dx*3 elseif x > (dx*2) then color = tft.RED lastc = dx*2 elseif x > dx then color = tft.WHITE lastc = dx elseif x > 1 then color = tft.BLACK lastc = 0 end tft.rect(lastc+2,2,dx-6,14,tft.WHITE,color) tft.rect(lastc+3,3,dx-8,12,tft.BLACK,color) -- wait for touch release paint.wait(0) first = true elseif (y > dy) then -- === first touch, lower bar touched: change size, r, erase, shape select, return === if x < (dx*5) then tft.rect(lastr,dy,dx-2,dispy-dy,tft.LIGHTGREY) end if x > (dx*7) then break elseif x > (dx*6) then -- clear drawing area tft.rect(0,20,dispx,dy-20,tft.BLACK,tft.BLACK) elseif x > (dx*5) then -- change drawing shape drw = drw + 1 if drw > 4 then drw = 1 end tft.rect(dx*5,dy,dx-2,dispy-dy,tft.LIGHTGREY, tft.BLACK) if drw == 1 then tft.circle(dx*5+((dx-2) // 2), dy+((dispy-dy) // 2), (dispy-dy) // 2 - 2, tft.LIGHTGREY, tft.LIGHTGREY) elseif drw == 3 then tft.rect(dx*5+6, dy+2, dx-14, dispy-dy-4, tft.LIGHTGREY, tft.LIGHTGREY) elseif drw == 2 then tft.circle(dx*5+((dx-2) // 2), dy+((dispy-dy) // 2), (dispy-dy) // 2 - 2, tft.YELLOW, tft.DARKGREY) elseif drw == 4 then tft.rect(dx*5+6, dy+2, dx-14, dispy-dy-4, tft.YELLOW, tft.DARKGREY) end -- drawing size elseif x > (dx*4) then r = 10 lastr = dx*4 elseif x > (dx*3) then r = 8 lastr = dx*3 elseif x > (dx*2) then r = 6 lastr = dx*2 elseif x > dx then r = 4 lastr = dx elseif x > 0 then r = 2 lastr = 0 end if x < (dx*5) then tft.rect(lastr,dy,dx-2,dispy-dy,tft.YELLOW) end -- wait for touch release paint.wait(0) first = true end end elseif (x > r) and (y > (r+20)) and (y < (dy-r)) then -- === touch on drawing area, draw shape === dodrw = true if first == false then -- it is NOT first touch, draw only if coordinates changed, but no more than 5 pixels if ((x == lx) and (y == ly)) or (math.abs(x-lx) > 5) or (math.abs(y-ly) > 5) then dodrw = false end end if dodrw == true then -- draw with active shape if drw == 1 then tft.circle(x, y, r, color, color) elseif drw == 3 then tft.rect(x-r, y-r, r*2, r*2, color, color) elseif drw == 2 then tft.circle(x, y, r, color, tft.DARKGREY) elseif drw == 4 then tft.rect(x-r, y-r, r*2, r*2, color, tft.DARKGREY) end end -- save touched coordinates lx = x ly = y first = false end else -- not touched first = true paint.wait(1) end end tft.rect(0,dy,dispx,dispy-dy,tft.YELLOW,tft.BLACK) tft.setcolor(tft.CYAN) tft.write(tft.CENTER, dy+3, "FINISHED") paint.running = false end
require "luaClass.init" _ENV=namespace "test" using_namespace "luaClass" class ("PublicTest"){ public{ FUNCTION.PublicTest(function(self) --thorw error --self.FIRST=996; self.SECOND=997; end); CONST.FIRST(3333); CONST.SECOND(); STATIC.myStatic(996); }; } local p=PublicTest() print(p.FIRST) print(p.SECOND) print(p) print(p.myStatic) p.myStatic=966 local p2=PublicTest() print(p.myStatic,p2.myStatic)
local setup = require('plugins.setup') setup(function(import) -- Surround text. import('tpope/vim-surround') -- comment/uncomment binding import('tpope/vim-commentary') -- Treesitter ast / higlighting import('nvim-treesitter/nvim-treesitter', { 'nvim-treesitter/nvim-treesitter-textobjects', { ['do'] = ':TSUpdate' }, }).then_configure(require('plugins.treesitter')) end)
-- @description Find and Replace in Marker Region Names -- @author Aaron Cendan -- @version 1.2 -- @changelog -- Added field for toggling search case-sensitivity. -- Fixed replacement with /blank; only affects part of matching name(s). -- Added replacement with /clear; erases entire name of matching markers/regions. -- @metapackage -- @provides -- [main] . > acendan_Find and Replace in Region Names.lua -- [main] . > acendan_Find and Replace in Marker Names.lua -- @link https://aaroncendan.me -- @about -- # Find and Replace in Marker/Region Names -- By Aaron Cendan - May 2020 -- -- ### General Info -- * Prompts user to replace part of a marker or region's name with new text if that marker/region name contains search criteria. -- * Uses file name to detect search type. -- -- ### Search Parameters -- * Accepts "/blank" as search criteria for finding and replacing blank marker/region names. -- * Accepts "/clear" as replacement criteria for erasing name of matching markers/regions. -- * Case-sensitive and case-insensitive searching. function findReplace() reaper.Undo_BeginBlock() -- Identify region/marker mode based on script name local script_name = ({reaper.get_action_context()})[2]:match("([^/\\_]+)%.lua$") local region_mode = script_name:match('Region') local mode_name = region_mode and 'Region' or 'Marker' local retval, num_markers, num_regions = reaper.CountProjectMarkers( 0 ) local num_total = num_markers + num_regions if mode_name == "Region" then num_items = num_regions elseif mode_name == "Marker" then num_items = num_markers end if num_items > 0 then ret, search_string, replace_string, search_field, case_sens = getSearchInfo(mode_name) if not ret then return end -- Confirm is valid search, search info not blank if search_string and replace_string and search_field and case_sens then if case_sens == "/c" or case_sens == "/i" then if search_field == "/p" then searchFullProject(num_total, search_string, replace_string, mode_name, case_sens) elseif search_field == "/t" then searchTimeSelection(num_total, search_string, replace_string, mode_name, case_sens) --Ideally it would be possible to find/replace in render matrix, see function below: --elseif search_field == "/m" then --searchSelectedMarkersRegions(num_total, search_string, replace_string, mode_name) else reaper.ShowMessageBox("Search field must be exactly /p or /t","Find/Replace", 0) findReplace() end else reaper.ShowMessageBox("Case sensitivity must be exactly /c or /i","Find/Replace", 0) findReplace() end else reaper.ShowMessageBox("Search fields cannot be empty!" .. "\n" .. "\n" .. "To Find blank names or Replace part of names with blanks, then use:" .. "\n" .. "/blank".. "\n" .. "\n" .. "To clear the entire name of a matching marker/region, then Replace with:" .. "\n" .. "/clear","Find/Replace", 0) findReplace() end else reaper.ShowMessageBox(string.format("Project has no %s" .. "s!", mode_name),"Find/Replace", 0) end reaper.Undo_EndBlock("Find and Replace", -1) end function getSearchInfo(mode_name) -- Check for previous search field local ret, prev_field = reaper.GetProjExtState(0, "FindReplaceStorage", "PrevSearchField") -- Check for previous search sensitivity local ret2, prev_sens = reaper.GetProjExtState(0, "FindReplaceStorage", "PrevCaseSens") if ret == 1 and prev_field == "/p" or prev_field == "/t" then --or prev_field == "/m" then -- If valid search field used previously, use as default if ret2 == 1 and prev_sens == "/c" or prev_sens == "/i" then -- Store user input for search and replace strings ret,user_input = reaper.GetUserInputs(string.format("Find & Replace in %s Names", mode_name), 4, "Find: Text to Search For,Replace: Text to Replace With,Project /p or Time Selection /t,Case-Sensitive /c or Insensitive /i,extrawidth=100",",,"..prev_field..","..prev_sens) search_string, replace_string, search_field, case_sens = user_input:match("([^,]+),([^,]+),([^,]+),([^,]+)") -- Save new search field if search_field then reaper.SetProjExtState(0, "FindReplaceStorage", "PrevSearchField",search_field) end -- Save new case sensitivity if case_sens then reaper.SetProjExtState(0, "FindReplaceStorage", "PrevCaseSens",case_sens) end else -- Store user input for search and replace strings ret,user_input = reaper.GetUserInputs(string.format("Find & Replace in %s Names", mode_name), 4, "Find: Text to Search For,Replace: Text to Replace With,Project /p or Time Selection /t,Case-Sensitive /c or Insensitive /i,extrawidth=100",",,"..prev_field..",/c") search_string, replace_string, search_field, case_sens = user_input:match("([^,]+),([^,]+),([^,]+),([^,]+)") -- Save new search field if search_field then reaper.SetProjExtState(0, "FindReplaceStorage", "PrevSearchField",search_field) end -- Save new case sensitivity if case_sens then reaper.SetProjExtState(0, "FindReplaceStorage", "PrevCaseSens",case_sens) end end else -- Search not used yet in this project, use Project (/p) field as default if ret2 == 1 and prev_sens == "/c" or prev_sens == "/i" then -- Store user input for search and replace strings ret,user_input = reaper.GetUserInputs(string.format("Find & Replace in %s Names", mode_name), 4, "Find: Text to Search For,Replace: Text to Replace With,Project /p or Time Selection /t,Case-Sensitive /c or Insensitive /i,extrawidth=100",",,/p,"..prev_sens) search_string, replace_string, search_field, case_sens = user_input:match("([^,]+),([^,]+),([^,]+),([^,]+)") -- Save new search field if search_field then reaper.SetProjExtState(0, "FindReplaceStorage", "PrevSearchField",search_field) end -- Save new case sensitivity if case_sens then reaper.SetProjExtState(0, "FindReplaceStorage", "PrevCaseSens",case_sens) end else -- Store user input for search and replace strings ret,user_input = reaper.GetUserInputs(string.format("Find & Replace in %s Names", mode_name), 4, "Find: Text to Search For,Replace: Text to Replace With,Project /p or Time Selection /t,Case-Sensitive /c or Insensitive /i,extrawidth=100",",,/p,/c") search_string, replace_string, search_field, case_sens = user_input:match("([^,]+),([^,]+),([^,]+),([^,]+)") -- Save new search field if search_field then reaper.SetProjExtState(0, "FindReplaceStorage", "PrevSearchField",search_field) end -- Save new case sensitivity if case_sens then reaper.SetProjExtState(0, "FindReplaceStorage", "PrevCaseSens",case_sens) end end end return ret, search_string, replace_string, search_field, case_sens end function analyzeMarkerRegion(search_string, replace_string, case_sens, i, isrgn, pos, rgnend, name, markrgnindexnumber, color) if search_string ~= "/blank" and search_string ~= "/clear" then if case_sens == "/c" then if string.find(name, search_string) then if replace_string ~= "/blank" and replace_string ~= "/clear" then local new_name = string.gsub( name, search_string, replace_string) reaper.SetProjectMarkerByIndex( 0, i, isrgn, pos, rgnend, markrgnindexnumber, new_name, color ) elseif replace_string == "/blank" then local new_name = string.gsub( name, search_string, "") reaper.SetProjectMarkerByIndex( 0, i, isrgn, pos, rgnend, markrgnindexnumber, new_name, color ) elseif replace_string == "/clear" then reaper.DeleteProjectMarker( 0, markrgnindexnumber, isrgn ) reaper.AddProjectMarker2( 0, isrgn, pos, rgnend, '', markrgnindexnumber, color ) end end elseif case_sens == "/i" then local lower_name = string.lower(name) local lower_search_string = string.lower(search_string) local j, k = string.find(lower_name, lower_search_string) if j and k then if replace_string ~= "/blank" and replace_string ~= "/clear" then local new_name = string.sub(name,1,j-1) .. replace_string .. string.sub(name,k+1,string.len(name)) reaper.SetProjectMarkerByIndex( 0, i, isrgn, pos, rgnend, markrgnindexnumber, new_name, color ) elseif replace_string == "/blank" then local new_name = string.sub(name,1,j-1) .. string.sub(name,k+1,string.len(name)) reaper.SetProjectMarkerByIndex( 0, i, isrgn, pos, rgnend, markrgnindexnumber, new_name, color ) elseif replace_string == "/clear" then reaper.DeleteProjectMarker( 0, markrgnindexnumber, isrgn ) reaper.AddProjectMarker2( 0, isrgn, pos, rgnend, '', markrgnindexnumber, color ) end end end else if name == "" then if replace_string ~= "/blank" and replace_string ~= "/clear" then local new_name = replace_string reaper.SetProjectMarkerByIndex( 0, i, isrgn, pos, rgnend, markrgnindexnumber, new_name, color ) end end end end function searchFullProject(num_total, search_string, replace_string, mode_name, case_sens) -- Loop through all markers/regions in project if mode_name == "Region" then local i = 0 while i < num_total do local retval, isrgn, pos, rgnend, name, markrgnindexnumber, color = reaper.EnumProjectMarkers3( 0, i ) if isrgn then analyzeMarkerRegion(search_string, replace_string, case_sens, i, isrgn, pos, rgnend, name, markrgnindexnumber, color) end i = i + 1 end elseif mode_name == "Marker" then local i = 0 while i < num_total do local retval, isrgn, pos, rgnend, name, markrgnindexnumber, color = reaper.EnumProjectMarkers3( 0, i ) if not isrgn then analyzeMarkerRegion(search_string, replace_string, case_sens, i, isrgn, pos, rgnend, name, markrgnindexnumber, color) end i = i + 1 end end end function searchTimeSelection(num_total, search_string, replace_string, mode_name, case_sens) -- Loop through all markers/regions in time selection StartTimeSel, EndTimeSel = reaper.GetSet_LoopTimeRange(0,0,0,0,0); -- Confirm valid time selection if StartTimeSel ~= EndTimeSel then if mode_name == "Region" then local i = 0 while i < num_total do local retval, isrgn, pos, rgnend, name, markrgnindexnumber, color = reaper.EnumProjectMarkers3( 0, i ) if isrgn then if pos >= StartTimeSel and rgnend <= EndTimeSel then analyzeMarkerRegion(search_string, replace_string, case_sens, i, isrgn, pos, rgnend, name, markrgnindexnumber, color) end end i = i + 1 end elseif mode_name == "Marker" then local i = 0 while i < num_total do local retval, isrgn, pos, rgnend, name, markrgnindexnumber, color = reaper.EnumProjectMarkers3( 0, i ) if not isrgn then if pos >= StartTimeSel and pos <= EndTimeSel then analyzeMarkerRegion(search_string, replace_string, case_sens, i, isrgn, pos, rgnend, name, markrgnindexnumber, color) end end i = i + 1 end end else reaper.ShowMessageBox("To Find & Replace within a time selection, you are going to need a time selection!","Find/Replace", 0) end end function searchSelectedMarkersRegions(num_total, search_string, replace_string, mode_name) -- Ideally, it would be possible to run this Find/Replace functionality on regions -- that are selected in the Region Render Matrix, but unfortunately, that info is not -- exposed via the API as of Reaper v6.10. end reaper.PreventUIRefresh(1) findReplace() reaper.PreventUIRefresh(-1) reaper.UpdateArrange()
object_tangible_loot_creature_loot_collections_statuette_piece_002 = object_tangible_loot_creature_loot_collections_shared_statuette_piece_002:new { } ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_collections_statuette_piece_002, "object/tangible/loot/creature/loot/collections/statuette_piece_002.iff")
q3d = require "quinta" local renderer = nil local mill = nil local mill_wheel = nil local tetrahedron = nil local tetrahedron_copies = {} local use_mouse = true love.window.setMode(640,480,{resizable=true}) love.window.setTitle('Quinta 3D - The World Worst 3D Engine!!!') function love.load() renderer = q3d.Renderer() -- You can load a model using only the path -- if not texture is given, we use the vertex colors -- the engine supports iqm and obj models local old_one = q3d.Object3D('assets/cthulhu.iqm') -- If needed you can add some texture local hare = q3d.Object3D('assets/hare.obj',"assets/textures/hare.png") mill_wheel = q3d.Object3D('assets/mill_wheel.obj',"assets/textures/wood.png") -- You can have objects that use multiple materials. mill = q3d.Object3D( "assets/mill3.obj", { "assets/textures/window.png", "assets/textures/stone_walls.png", "assets/textures/land.png", q3d.Material3D("assets/textures/water.png",nil,"assets/textures/distortion.png") } ) --You can create geometry from code, just add vertex list of the faces --Order is important to determine the face orientation. --Any face not oriented to the camera will not be rendered. --the colors of the vertex will have an effect on the texture used --The format is x,y,z,u,v,r,g,b, --in this example, we used placeholder uv cords --the default color is white. local pyramidVerts = {} pyramidVerts[ 1] = {-1,1,1, 0,0, 0.1,0.2,1.0} pyramidVerts[ 2] = {1,1,-1, 0,1, 0.2,1.0,0.1} pyramidVerts[ 3] = {1,-1,1, 1,1} pyramidVerts[ 4] = {-1,1,1, 0,0, 0.1,0.2,1.0} pyramidVerts[ 5] = {-1,-1,-1, 0,1, 1.0,0.2,0.1} pyramidVerts[ 6] = {1,1,-1, 1,1, 0.2,1.0,0.1} pyramidVerts[ 7] = {1,-1,1, 0,0} pyramidVerts[ 8] = {1,1,-1, 0,1, 0.2,1.0,0.1} pyramidVerts[ 9] = {-1,-1,-1, 1,1, 1.0,0.2,0.1} pyramidVerts[10] = {-1,-1,-1, 0,0, 1.0,0.2,0.1} pyramidVerts[11] = {-1,1,1, 0,1, 0.1,0.2,1.0} pyramidVerts[12] = {1,-1,1, 1,1} --send the vertex to create a new object, also put a texture tetrahedron = q3d.Object3D(pyramidVerts,'assets/textures/distortion_b.png') --Change position, rotation, and scale of the objects --mill.setPos(0,0,0) --0,0,0 is default position hare.setPos(3,1.5,0.2) hare.setRot(nil,nil,math.rad(-45)) old_one.setRot(nil,nil,math.rad(-90)) mill_wheel.setPos(0.1,2.7,1.45) mill_wheel.setRot(math.rad(90),0,0) tetrahedron.setScale(0.25,0.25,0.25) tetrahedron.setPos(2,2,3) -- Important, the objects need to be added to the renderer renderer.addObject(mill) renderer.addObject(mill_wheel) renderer.addObject(hare) renderer.addObject(tetrahedron) renderer.addObject(old_one) -- Create a set of instances of the tetrahedron. -- instances are independent objects that shared the same mesh data and materials -- we are gonna set their positions on the update bellow... local i = 0 local scale = 0.35 while i < 7 do local new_t4 = tetrahedron.newInstance() new_t4.setScale(scale,scale,scale) --add to the render... renderer.addObject(new_t4) --add to this list, so we can later modify they. table.insert(tetrahedron_copies, new_t4) scale = scale+0.25 i=i+1 end renderer.bgcolor = {0.0,0.1,0.2} renderer.setCameraPos(12,4,4) -- Set the camera to look on start to the tetrahedron. renderer.setCameraLookAt(tetrahedron) end function love.draw() renderer.render() local info_text = [[ Press SPACE to change between FPS control and set the camera to look at the tetrahedron. On FPS control, use the WASD keys to move plus Q and E to go up and down. Use ESC to close at any time. ]] local cam_pos_x = 'x: '..tostring(math.floor(renderer.camera.pos.x)) local cam_pos_y = ' y: '..tostring(math.floor(renderer.camera.pos.y)) local cam_pos_z = ' z: '..tostring(math.floor(renderer.camera.pos.z)) info_text = info_text..' '..cam_pos_x..cam_pos_y..cam_pos_z love.graphics.setColor(0,0,0) love.graphics.print(info_text,-1,0) love.graphics.print(info_text,0,1) love.graphics.print(info_text,-1,1) love.graphics.print(info_text,0,-1) love.graphics.setColor(1,1,1) love.graphics.print(info_text,0,0) end local timer = 0 local rotation = 0 function love.update(dt) -- simple first-person camera movement love.mouse.setRelativeMode(use_mouse) if use_mouse then local mx,my,mz = 0,0,0 local speed = 0.15 if love.keyboard.isDown("w") then my = my + 1 end if love.keyboard.isDown("a") then mx = mx + 1 end if love.keyboard.isDown("s") then my = my - 1 end if love.keyboard.isDown("d") then mx = mx - 1 end if love.keyboard.isDown("e") then mz = mz - dt/speed end if love.keyboard.isDown("q") then mz = mz + dt/speed end if mx ~= 0 or my ~= 0 then local angle = math.atan2(mx,my) renderer.camera.pos.x = renderer.camera.pos.x + math.sin(renderer.camera.rot.z + angle)*speed*dt*60 renderer.camera.pos.y = renderer.camera.pos.y - math.cos(renderer.camera.rot.z + angle)*speed*dt*60 end renderer.camera.pos.z = renderer.camera.pos.z + mz else renderer.setCameraLookAt(tetrahedron) end -- Make the tetrahedron and the copies spin. timer = timer + dt/8 local angle = timer*3+math.pi*0.5 local npos = {math.cos(angle)*5,math.sin(angle)*5,3} tetrahedron.setPos(unpack(npos)) tetrahedron.setRot(unpack(npos)) local i = 1 while tetrahedron_copies[i] do local angle1 = math.rad((i/7)*360)-angle local x = math.sin(-angle1)*(8) local y = math.cos(-angle1)*(8) tetrahedron_copies[i].setPos(x,y,math.cos(angle1*3)) tetrahedron_copies[i].setRot(angle1,-angle1*2,angle1*3) i=i+1 end -- Here is defined the animation of the mill wheel. rotation = rotation + dt*10 if rotation > 360 then rotation = 0 end mill_wheel.setRot(nil,nil,math.rad(-rotation)) -- The animation of the texture of the mill water texture local mesh_list = mill.getMeshByMaterial('water') for _,mesh in pairs(mesh_list) do local current_vertex = mesh.first local last_vertex = mesh.last while current_vertex < last_vertex do -- 1 is position cords, 2 is uv cords, anything after that is format dependent. -- for details of the format, see model_name.model.mesh:getVertexFormat( ) -- and the love Mesh:getVertexFormat( ) API local u,v = mill.getVertexAttributes(current_vertex,2) u = u-dt*0.05 --original_uv[first][1]+0.25*(frame_list[frame]-1) v = v-dt*0.05 mill.setVertexAttribute(current_vertex,2,{u,v}) current_vertex = current_vertex+1 end end -- The animation on the texture of the tetrahedron. -- Alter the mesh, also changes all their instances... mesh_list = tetrahedron.getMeshByMaterial('Material_0') for _,mesh in pairs(mesh_list) do local current_vertex = mesh.first local last_vertex = mesh.last while current_vertex < last_vertex do local u,v = tetrahedron.getVertexAttributes(current_vertex,2) u = u-dt --original_uv[first][1]+0.25*(frame_list[frame]-1) v = v+dt tetrahedron.setVertexAttribute(current_vertex,2,{u,v}) current_vertex = current_vertex+1 end end end function love.mousemoved(x,y, dx,dy) if use_mouse then local z_rot = renderer.camera.rot.z - math.rad(dx * 0.5) local x_rot = math.max(math.min(renderer.camera.rot.x - math.rad(dy * 0.5), math.rad(170)), math.rad(20)) renderer.setCameraRot(x_rot,nil,z_rot) end end function love.keypressed(a, id) if id == 'escape' then love.event.quit() end if id == 'space' then use_mouse = not use_mouse end end
local Players = game:GetService("Players") local Lighting = game:GetService("Lighting") local RunService = game:GetService("RunService") local ReplicatedStorage = game:GetService("ReplicatedStorage") local ViewportWindow = require(ReplicatedStorage:WaitForChild("ViewportWindow")) local Maid = require(ReplicatedStorage.ViewportWindow:WaitForChild("Maid")) local Mirror = workspace.Mirror local MirrorVPW = ViewportWindow.FromPart(Mirror, Enum.NormalId.Front) local MirrorCF = MirrorVPW:GetSurface() local function reflectCFrame(cf, surfaceCF) local c = {surfaceCF:ToObjectSpace(cf):GetComponents()} local trueReflect = surfaceCF * CFrame.new( c[1], c[2], -c[3], c[4], c[5], c[6], c[7], c[8], c[9], -c[10], -c[11], -c[12] ) return CFrame.fromMatrix(trueReflect.Position, -trueReflect.XVector, trueReflect.YVector, trueReflect.ZVector) end local function addCharacterToMirror(player) local character = player.Character local humanoid = character:WaitForChild("Humanoid") local matches = MirrorVPW:CloneHierarchyToWorld({character}, {}) local function update() for child, match in pairs(matches) do if child:IsA("BasePart") then match.CFrame = reflectCFrame(child.CFrame, MirrorCF) end end end local maid = Maid.new() maid:Mark(RunService.RenderStepped:Connect(update)) maid:Mark(matches[character]) maid:Mark(player.CharacterRemoving:Connect(function() maid:Sweep() end)) update() matches[humanoid].DisplayDistanceType = Enum.HumanoidDisplayDistanceType.None return maid end local function addWorldToMirror() local children = {} for _, child in pairs(workspace:GetChildren()) do if not Players:GetPlayerFromCharacter(child) then table.insert(children, child) end end local world = MirrorVPW:CloneHierarchyToWorld(children, { [Mirror] = true, }) for child, match in pairs(world) do if child:IsA("BasePart") then match.CFrame = reflectCFrame(child.CFrame, MirrorCF) end end end for _, player in pairs(Players:GetPlayers()) do if player.Character then addCharacterToMirror(player) end player.CharacterAdded:Connect(function(character) wait(1) addCharacterToMirror(player) end) end Players.PlayerAdded:Connect(function(player) player.CharacterAdded:Connect(function(character) addCharacterToMirror(player) end) end) MirrorVPW.Maid:Mark(RunService.RenderStepped:Connect(function(dt) MirrorVPW:Render() end)) addWorldToMirror() MirrorVPW:AddSkybox(Lighting.Sky) print("Running!")
local noremap = wincent.vim.noremap noremap('{', ':keeppatterns ?^\\d<CR>', {buffer = true, silent = true}) noremap('}', ':keeppatterns /^\\d<CR>', {buffer = true, silent = true})
------------------------------------------------------ -- template.lua -- -- Match results to names in template. -- -- Possible options: -- safe - Do not die if key in template not found in db. -- syntax - { start = x, end = y } -- execute - Disable / enable execution within template ------------------------------------------------------ local payload -- String holding the payload. local query -- Table holding either database query or standard table. local file -- Reference to a file. local do_exec = false -- Run execution or not. local safe = false -- Decide whether or not to die if db or table keys are not found. local syntax = { -- Define some alternate syntax. start = "", finish = "" } ------------------------------------------------------ -- local how_deep() -- -- Get the max depth of a table? -- *integer ------------------------------------------------------ local function how_deep(t) -- Get max depth. end ------------------------------------------------------ -- local render (file) -- -- Render a particular file. -- *table ------------------------------------------------------ local function render ( file ) ----------------------------------------------- -- Load the template file into memory. -- -- IE has some strange quirks here if newlines -- are omitted, and if the payload is under -- 512 bytes. ----------------------------------------------- payload = table.concat(F.totable( file ),"\n") ----------------------------------------------- -- Check for each word. -- Store each key ( <word> ) --> keys ----------------------------------------------- if safe then -- safe checking option is on -- Store local keys = {} for w in string.gmatch( payload, "%{[%c%s%w_]+%}" ) do table.insert(keys, ({string.gsub(w,"[%{%}%c%s]","")})[1]) end -- Check for __,my_key in ipairs(keys) do local status = false if is.value( my_key, table.keys( query[1] )) then -- out.add( my_key .. "<br />") -- out.add( table.concat( table.keys( query[1] )) .. "<br />") status = true -- stop running and move to next result... end -- This is going to be slow, I cannot remember -- how to simulate a continue right now. if not status then die.with(500, { msg = _.div("error", { "Cannot find key: " .. my_key, "In database: " .. _.i( pg.dbname ), "Please check the template file supplied: " .. _.i( file ), }) }) end end end ----------------------------------------------- -- Store each block ( { <word> } ) --> blocks ----------------------------------------------- local blocks = {} for w in string.gmatch( payload, "%{[%c%s%w_]+%}" ) do table.insert(blocks, w) end ----------------------------------------------- -- Then do matching per each term that's in -- the above. ----------------------------------------------- local final_block = {} for __, db_stream in ipairs(query) do local minp = payload for __, keycorr in ipairs( blocks ) do -- Create a simple keyname, since we can't -- access both {keys} and {blocks} this way. keyname = ({string.gsub(keycorr,"[%{%}%c%s]","")})[1] -- Simple find-and-replace of [ { <word> } ] with [ database result ]. -- Possible that these just don't work. minp = string.gsub( minp, keycorr, db_stream[keyname]) end -- Insert it. table.insert( final_block, minp ) end return final_block end ------------------------------------------------------ -- local execute(str) -- -- Using the execute key terms "[" & "]", render -- a file. ------------------------------------------------------ local function execute( t ) ----------------------------------------------- -- Now store each execution block. ----------------------------------------------- -- for w in string.gmatch( table.concat(t), "%[[%c%s%w_%p]+%]" ) -- do local payload = table.concat(t) for w in string.gmatch( payload, "%[[%c%s%w_\"'%.%(%)%/%=%{%}]+%]" ) do -- See the block before execution. -- response.abort({200}, w ) a = string.sub(w, 2, string.len(w) - 1) a = loadstring(a) -- See the results of the execution. -- response.abort({200}, a() ) if type(a) == 'function' then -- Should it be a fatal error if your function returns nothing? local result = a() if result then payload = string.gsub( payload, "%[[%c%s%w_\"'%.%(%)%/%=%{%}]+%]", a(), 1 ) end else -- Need a way to extract which line failed and at what position. response.abort({200}, "Execution of lines in template: " .. file .. " failed.") end end ----------------------------------------------- -- Return content stream. ----------------------------------------------- return payload --table.concat(final_block) end return { ------------------------------------------------------ -- .exec() -- -- Set execution to on or off. -- *nil ------------------------------------------------------ exec = function (b) do_exec = true end, ------------------------------------------------------ -- .safe -- -- Set safe to true. -- *nil ------------------------------------------------------ safe = function () safe = true end, ------------------------------------------------------ -- .string(t, str) -- -- Render a template string [str]. -- *string ------------------------------------------------------ -- string = function (t, str) -- end, ------------------------------------------------------ -- .db(t, f) -- -- Render a database dump. ------------------------------------------------------ db = function (t, file) end, ------------------------------------------------------ -- .file(t, f) -- -- Render a properly syntaxed file [f]. -- *string ------------------------------------------------------ file = function (t, file) ----------------------------------------------- -- Check if a template file exists. ----------------------------------------------- if file and type(file) == 'string' then -- Search private assets only. F.asset("private") local fname = "templates/" .. file .. ".tpl" -- Check for a .tpl extension. local f = F.exists( fname ) if not f.status then die.with(500, "File '" .. fname .. "' not found") end ------------------------------------------------------ -- Clean / peek into this. ------------------------------------------------------ query = t ------------------------------------------------------ -- Render the file, evaluating whether or not we -- wanted execution. ------------------------------------------------------ if not do_exec then return table.concat(render( f.handle )) else return execute( render(f.handle) ) end end end, }
local chain = require"luaossl.x509.chain" return chain
gameNpcs.removeTextAreas = function(id, player) local ID = -89000+(id*6) for i = 0, 5 do removeTextArea(ID+i, player) end end
--====================================================================-- -- Example: Trajectory Direction -- -- Shows example of how to setup dmc_trajectory with objects -- that face either left or right. -- -- by David McCuskey -- -- Sample code is MIT licensed, the same license which covers Lua itself -- http://en.wikipedia.org/wiki/MIT_License -- -- Copyright (C) 2012-2014 David McCuskey. All Rights Reserved. --====================================================================-- print("---------------------------------------------------") --========================================================= -- Imports --========================================================= local Trajectory = require( "dmc_library.dmc_trajectory" ) --====================================================================-- -- Setup, Constants --====================================================================-- display.setStatusBar( display.HiddenStatusBar ) math.randomseed( os.time() ) -- coordinate points for each test location -- local POINTS = { { 80, 120 }, { 240, 120 }, { 80, 240 }, { 240, 240 }, { 80, 360 }, { 240, 360 } } local CENTER_POINT = { 160, 240 } -- tables of values, used for random choices -- local HEIGHTS = { 5, 25, 45, 65 } local TIMES = { 750, 1500, 3000 } local grid = display.newGroup() --====================================================================-- -- Support Functions --====================================================================-- -- drawGrid() -- create and position the grid points - locations for trajectory tests -- local function drawGrid() local o for i=1, #POINTS do o = display.newCircle( POINTS[i][1], POINTS[i][2], 3 ) grid:insert( o ) end -- center point o = display.newCircle( CENTER_POINT[1], CENTER_POINT[2], 1 ) grid:insert( o ) end --== Projectile Creation functions ==-- -- local createLeftProjectile = function() local o = display.newImageRect( "assets/projectile_left.png", 12, 12 ) local p = { rotate=true, direction="left" } return o, p end local createRightProjectile = function() local o = display.newImageRect( "assets/projectile_right.png", 13, 7 ) local p = { rotate=true, direction="right" } return o, p end -- createRandomProjectile() -- returns a random projectile -- local function createRandomProjectile() if math.random( 2 ) == 1 then return createLeftProjectile() else return createRightProjectile() end end -- doTest() -- local function doTest() local oB, oE, oP -- refs to objects Begin, End, Projectile local height, time -- random height and time for transition local pB, pE -- begin and end points for transition local prms, params -- params for transition call pB = CENTER_POINT -- get random items for transition pE = POINTS[ math.random( #POINTS ) ] height = HEIGHTS[ math.random( #HEIGHTS ) ] time = TIMES[ math.random( #TIMES ) ] -- begin point - green oB = display.newCircle( pB[1], pB[2], 1 ) oB:setFillColor( 0, 1, 0 ) -- end point -- red oE = display.newCircle( pE[1], pE[2], 5 ) oE:setFillColor( 1, 0, 0 ) -- projectile oP, prms = createRandomProjectile() oP.x, oP.y = pB[1], pB[2] -- onComplete function, called after trajectory transition is finished local onCompleteCallback = function() -- clean up test items oB:removeSelf() oE:removeSelf() oP:removeSelf() -- start a new test doTest() end -- setup params for our trajectory calls params = { time=time, pBegin=pB, pEnd=pE, height=height, rotate=prms.rotate, direction=prms.direction, onComplete=onCompleteCallback } -- get calculated angle for intiial setup prms = Trajectory.calculate( params ) oP.rotation = prms.angle -- pause a bit so we can see setup timer.performWithDelay( 500, function() -- Do the transition Trajectory.move( oP, params ) end) end --== Main Function local main = function() drawGrid() doTest() end -- let's get this party started ! -- main()
AddCSLuaFile() -- The following is for the server's eyes only local GravityDuplicator if ( SERVER ) then function GravityDuplicator( ply, ent, data ) if ( !data || !data.enabled ) then duplicator.ClearEntityModifier( ent, "gravity_property" ) return end -- Simply restore the value whenever we are duplicated -- We don't need to reapply EnableGravity because duplicator already does it for us ent:SetNWBool( "gravity_disabled", data.enabled ) duplicator.StoreEntityModifier( ent, "gravity_property", data ) end duplicator.RegisterEntityModifier( "gravity_property", GravityDuplicator ) end properties.Add( "gravity", { MenuLabel = "#gravity", Type = "toggle", Order = 1001, Filter = function( self, ent, ply ) if ( !IsValid( ent ) ) then return false end if ( !gamemode.Call( "CanProperty", ply, "gravity", ent ) ) then return false end if ( ent:GetClass() == "prop_physics" ) then return true end if ( ent:GetClass() == "prop_ragdoll" ) then return true end return false end, Checked = function( self, ent, ply ) return ent:GetNWBool( "gravity_disabled" ) == false end, Action = function( self, ent ) self:MsgStart() net.WriteEntity( ent ) self:MsgEnd() end, Receive = function( self, length, ply ) local ent = net.ReadEntity() if ( !properties.CanBeTargeted( ent, ply ) ) then return end if ( !self:Filter( ent, ply ) ) then return end local bones = ent:GetPhysicsObjectCount() local b = ent:GetNWBool( "gravity_disabled" ) for i = 0, bones - 1 do local phys = ent:GetPhysicsObjectNum( i ) if ( IsValid( phys ) ) then phys:EnableGravity( b ) phys:Wake() end end ent:SetNWBool( "gravity_disabled", b == false ) GravityDuplicator( ply, ent, { enabled = ent:GetNWBool( "gravity_disabled" ) } ) end } )
sampleInfo = { CodeName="Regular", ShortName="Regular", LongName="Regular Sampling", Description="Uniformly spaced samples", Functions= { { name = "Regular", progressive = false, randomized = false, cache = false }, { name = "RegularCentered", progressive = false, randomized = false, cache = false }, { name = "RegularCenteredOffset", progressive = false, randomized = false, cache = false }, { name = "RegularJittered", progressive = false, randomized = true, cache = false }, }, }
--[[ This file contains the ArenaState class. The ArenaState manages everything that happens in an arena. ]] local g_ArenaStates = {} function cArenaState(a_ArenaName, a_WorldName) local m_ArenaName = a_ArenaName local m_World = a_WorldName local m_HasStarted = false local m_CountDownLeft = Config.CountDownTime local m_NoDamageTimeLeft = Config.NoDamageTime local m_SpawnPoints = {} local m_Players = {} local m_Inventories = {} local m_LobbyCoordinates = Vector3d() local m_LobbyWorld = m_World local m_BoundingBox = cCuboid() local m_DestroyedBlocks = {} local m_TicksUntilStart = Config.ArenaStartCountdown -- Create the object. local self = {} self.ArenaName = m_ArenaName -- Loops through each player in the arena and calls the given callback. function self:ForEachPlayer(a_Callback) local World = cRoot:Get():GetWorld(m_World) local ShouldStop = false for PlayerName, _ in pairs(m_Players) do if (ShouldStop) then return end World:DoWithPlayer(PlayerName, function(a_Player) if (a_Callback(a_Player)) then ShouldStop = true end end ) end end -- Sends a message to all the players who joined the arena. function self:BroadcastChat(a_Message) self:ForEachPlayer( function(a_Player) a_Player:SendMessage(a_Message) end ) end do -- Lobby related functions -- Returns the coordinates for the lobby function self:GetLobbyCoordinates() return m_LobbyCoordinates end -- Sets the coordinates for the lobby function self:SetLobbyCoordinates(a_LobbyCoordinates) m_LobbyCoordinates:Set(a_LobbyCoordinates.x, a_LobbyCoordinates.y, a_LobbyCoordinates.z) end -- Returns true if the lobby coordinates are set. function self:AreLobbyCoordinateSet() return (m_LobbyCoordinates:Length() ~= 0) end -- sets the world where the lobby is. function self:SetLobbyWorld(a_WorldName) assert(type(a_WorldName) == 'string') m_LobbyWorld = a_WorldName end -- Get the world where the lobby is. function self:GetLobbyWorld() return m_LobbyWorld end end do -- All the ArenaSize functions function self:SetArenaSizeP1(a_Point) assert((tolua.type(a_Point) == "Vector3<int>") or (tolua.type(a_Point) == "const Vector3<int>")) m_BoundingBox.p1:Set(a_Point.x, a_Point.y, a_Point.z) m_BoundingBox:Sort() end function self:SetArenaSizeP2(a_Point) assert((tolua.type(a_Point) == "Vector3<int>") or (tolua.type(a_Point) == "const Vector3<int>")) m_BoundingBox.p2:Set(a_Point.x, a_Point.y, a_Point.z) m_BoundingBox:Sort() end function self:SetArenaSize(a_Vector, a_Point) a_Point = tostring(a_Point) if (a_Point == '1') then self:SetArenaSizeP1(a_Vector) return true elseif (a_Point == '2') then self:SetArenaSizeP2(a_Vector) return true else return false, "Invalid point \"" .. a_Point .. "\"" end end function self:IsInside(a_Point) assert((tolua.type(a_Point) == "Vector3<double>") or (tolua.type(a_Point) == "const Vector3<double>")) return m_BoundingBox:IsInside(a_Point) end end -- Returns true if the arena has started function self:HasStarted() return m_HasStarted end -- Returns the world where the arena is in function self:GetWorldName() return m_World end -- Returns the name of the arena. function self:GetName() return m_ArenaName end -- Returns the amount of players who joined. function self:GetNumPlayers() local Count = 0 for PlayerName, _ in pairs(m_Players) do Count = Count + 1 end return Count end -- Returns the amount of playing players function self:GetNumPlayingPlayers() local Count = 0 for PlayerName, Info in pairs(m_Players) do if (Info.IsPlaying) then Count = Count + 1 end end return Count end -- Returns the players who are still in the game function self:GetPlayingPlayers() local res = {} for PlayerName, Info in pairs(m_Players) do if (Info.IsPlaying) then table.insert(res, PlayerName) end end return res end do -- Manages the players joining and leaving. -- Adds a player to the arena. Returns true if succes and returns false if: the arena is full or the arena already started. function self:AddPlayer(a_Player) if (m_HasStarted) then return false, "The arena already started." end if (#m_SpawnPoints == self:GetNumPlayers()) then return false, "The arena is full." end m_Players[a_Player:GetName()] = { IsPlaying = false, SpawnPoint = nil, } if (a_Player:GetWorld():GetName() ~= m_World) then a_Player:MoveToWorld(m_World) end a_Player:TeleportToCoords(m_LobbyCoordinates.x, m_LobbyCoordinates.y, m_LobbyCoordinates.z) if (self:GetNumPlayers() == #m_SpawnPoints) then self:StartArena() end end -- Removes the player from the arena function self:RemovePlayer(a_Player) if (a_Player:GetWorld():GetName() ~= m_LobbyWorld) then a_Player:MoveToWorld(m_LobbyWorld) end a_Player:TeleportToCoords(m_LobbyCoordinates.x, m_LobbyCoordinates.y, m_LobbyCoordinates.z) m_Players[a_Player:GetName()] = nil if (not m_HasStarted) then return end -- Give the player his items back. local Inventory = a_Player:GetInventory() Inventory:Clear() Inventory:AddItems(m_Inventories[PlayerName] or cItems(), true) if (self:GetNumPlayingPlayers() == 1) then self:StopArena() end end end -- Adds a block to the table with destroyed blocks. They get replaced once the match is over. function self:AddDestroyedBlock(a_Pos, a_BlockType, a_BlockMeta) table.insert(m_DestroyedBlocks, {Pos = a_Pos, BlockType = a_BlockType, BlockMeta = a_BlockMeta}) end do -- Adds a spawnpoint. function self:AddSpawnPoint(a_SpawnPoint) assert((tolua.type(a_SpawnPoint) == "Vector3<double>") or (tolua.type(a_SpawnPoint) == "const Vector3<double>")) table.insert(m_SpawnPoints, {Coordinates = Vector3d(a_SpawnPoint), IsTaken = false}) end -- Returns the amount of spawnpoints function self:GetNumSpawnPoints() return #m_SpawnPoints end end -- Refills all the chests that are in the arena. function self:RefillChestsInArena() local MinChunkX = math.floor(m_BoundingBox.p1.x / 16) local MinChunkZ = math.floor(m_BoundingBox.p1.z / 16) local MaxChunkX = math.floor(m_BoundingBox.p2.x / 16) local MaxChunkZ = math.floor(m_BoundingBox.p2.z / 16) local ChunkCoords = {} for X = MinChunkX, MaxChunkX do for Z = MinChunkZ, MaxChunkZ do table.insert(ChunkCoords, {X, Z}) end end local World = cRoot:Get():GetWorld(m_World) World:ChunkStay(ChunkCoords, function(a_ChunkX, a_ChunkZ) World:ForEachChestInChunk(a_ChunkX, a_ChunkZ, function(a_ChestEntity) if (m_BoundingBox:IsInside(a_ChestEntity:GetPosX(), a_ChestEntity:GetPosY(), a_ChestEntity:GetPosZ())) then for X = 1, 3 do for Y = 1, 9 do a_ChestEntity:SetSlot(X * Y - 1, GetRandomItem()) end end end end ) end, function() end ) end -- Starts the arena. function self:StartArena() if (self:GetNumPlayers() < 2) then return false; end -- Refill all the chests inside the arena. self:RefillChestsInArena() local SpawnPoint = 1 self:ForEachPlayer( function(a_Player) local PlayerName = a_Player:GetName() -- Save the inventory local InventoryContent = cItems() local Inventory = a_Player:GetInventory() Inventory:CopyToItems(InventoryContent) m_Inventories[PlayerName] = InventoryContent Inventory:Clear() -- Teleport the player to one of the spawnpoint coordinates. local Coordinates = m_SpawnPoints[SpawnPoint].Coordinates a_Player:TeleportToCoords(Coordinates.x, Coordinates.y, Coordinates.z) -- Set the gamemode to survival a_Player:SetGameMode(eGameMode_Survival) -- Mark the player as IsPlaying and save his spawnpoint coordinates. m_Players[PlayerName].IsPlaying = true m_Players[PlayerName].SpawnPoint = Coordinates -- Heal the player completely a_Player:Heal(20) a_Player:Feed(20, 20) SpawnPoint = SpawnPoint + 1 end ) m_HasStarted = true end -- Stops the arena function self:StopArena(a_IsForceStop) if (a_IsForceStop) then self:BroadcastChat("The match is over.") else local Winner = self:GetPlayingPlayers() self:BroadcastChat(Winner[1] .. " has won the game") end self:ForEachPlayer( function(a_Player) local PlayerName = a_Player:GetName() local PlayerState = GetPlayerState(PlayerName) -- Teleport the player to the lobby. a_Player:TeleportToCoords(m_LobbyCoordinates.x, m_LobbyCoordinates.y, m_LobbyCoordinates.z) -- Remove the player self:RemovePlayer(a_Player) PlayerState:LeaveArena() end ) -- Delete all the inventories wich were saved. m_Inventories = {} -- Reset the counters m_CountDownLeft = Config.CountDownTime m_NoDamageTimeLeft = Config.NoDamageTime -- Replace all the destroyed grass and leave blocks. local World = cRoot:Get():GetWorld(m_World) for Idx, BlockInfo in ipairs(m_DestroyedBlocks) do World:SetBlock(BlockInfo.Pos.x, BlockInfo.Pos.y, BlockInfo.Pos.z, BlockInfo.BlockType, BlockInfo.BlockMeta) end -- Reset the table wich contains all the destroyed blocks. m_DestroyedBlocks = {} -- Mark as "Not started" m_HasStarted = false -- Reset the countdown m_TicksUntilStart = Config.ArenaStartCountdown end -- Gets called each tick. It's used to teleport the players to their spawn point if the arena didn't start yet. function self:Tick() if (not m_HasStarted) then m_TicksUntilStart = m_TicksUntilStart - 1 if (m_TicksUntilStart == 0) then if (not self:StartArena()) then m_TicksUntilStart = Config.ArenaStartCountdown end end return end if (m_NoDamageTimeLeft ~= 0) then m_NoDamageTimeLeft = m_NoDamageTimeLeft - 1 end if (m_CountDownLeft == 0) then return end m_CountDownLeft = m_CountDownLeft - 1 if (m_CountDownLeft == 5 * 20) then self:BroadcastChat("5 seconds left") elseif (m_CountDownLeft == 4 * 20) then self:BroadcastChat("4") elseif (m_CountDownLeft == 3 * 20) then self:BroadcastChat("3") elseif (m_CountDownLeft == 2 * 20) then self:BroadcastChat("2") elseif (m_CountDownLeft == 1 * 20) then self:BroadcastChat("1") elseif (m_CountDownLeft == 0) then self:BroadcastChat("The match has started!") end self:ForEachPlayer( function(a_Player) local PlayerName = a_Player:GetName() local Coords = m_Players[PlayerName].SpawnPoint a_Player:TeleportToCoords(Coords.x, Coords.y, Coords.z) end ) end do function self:GetCountDownTime() return m_CountDownLeft end function self:GetNoDamageTime() return m_NoDamageTimeLeft end end -- Saves all the info about the arena in an IniFile object. function self:SaveToIniFile(a_IniFile) local SpawnPoints = "" for I, Coordinates in pairs(m_SpawnPoints) do SpawnPoints = SpawnPoints .. Coordinates.Coordinates.x .. "," .. Coordinates.Coordinates.y .. "," .. Coordinates.Coordinates.z .. ";" end a_IniFile:SetValue(m_ArenaName, "SpawnPoints", SpawnPoints) a_IniFile:SetValue(m_ArenaName, "World", m_World) a_IniFile:SetValue(m_ArenaName, "LobbyCoordinates", m_LobbyCoordinates.x .. "," .. m_LobbyCoordinates.y .. "," .. m_LobbyCoordinates.z .. "," .. m_LobbyWorld) a_IniFile:SetValue(m_ArenaName, "BoundingBox", m_BoundingBox.p1.x .. "," .. m_BoundingBox.p1.y .. "," .. m_BoundingBox.p1.z .. ";" .. m_BoundingBox.p2.x .. "," .. m_BoundingBox.p2.y .. "," .. m_BoundingBox.p2.z .. "," ) end -- Loads all the info from an IniFile object. function self:LoadFromIniFile(a_IniFile) local SpawnPoints = StringSplit(a_IniFile:GetValue(m_ArenaName, "SpawnPoints"), ";") for Idx = 1, #SpawnPoints do local Coords = StringSplit(SpawnPoints[Idx], ",") self:AddSpawnPoint(Vector3d(Coords[1], Coords[2], Coords[3])) end local BoundingBox = StringSplit(a_IniFile:GetValue(m_ArenaName, "BoundingBox"), ";") do local Coords = StringSplit(BoundingBox[1], ",") m_BoundingBox.p1:Set(Coords[1], Coords[2], Coords[3]) local Coords = StringSplit(BoundingBox[2], ",") m_BoundingBox.p2:Set(Coords[1], Coords[2], Coords[3]) end local LobbyCoords = StringSplit(a_IniFile:GetValue(m_ArenaName, "LobbyCoordinates"), ",") self:SetLobbyCoordinates(Vector3d(LobbyCoords[1], LobbyCoords[2], LobbyCoords[3])) self:SetLobbyWorld(LobbyCoords[4] or m_World) end return self end function GetArenaState(a_ArenaStateName) if (g_ArenaStates[a_ArenaStateName]) then return g_ArenaStates[a_ArenaStateName] end return false end function CreateArenaState(a_ArenaName, a_WorldName) assert(type(a_ArenaName) == "string") assert(type(a_WorldName) == "string") if (g_ArenaStates[a_ArenaName]) then return false, "The arena already exists." end local ArenaState = cArenaState(a_ArenaName, a_WorldName) g_ArenaStates[a_ArenaName] = ArenaState return ArenaState end function ArenaExist(a_ArenaName) return (g_ArenaStates[a_ArenaName] ~= nil) end function ForEachArena(a_Callback) for ArenaName, ArenaState in pairs(g_ArenaStates) do a_Callback(ArenaState) end end function InsertArenaState(a_ArenaName, a_ArenaState) if (g_ArenaStates[a_ArenaName]) then return false end g_ArenaStates[a_ArenaName] = a_ArenaState return true end function DoWithArena(a_ArenaName, a_Callback) assert(type(a_Callback) == 'function') if (not g_ArenaStates[a_ArenaName]) then return false end a_Callback(g_ArenaStates[a_ArenaName]) end
function model.enableSimulatedCamera() --[[ local data={} data.id=model.handle data.imageProcessingParameters=imgProcessingParams simBWF.query('ragnarVision_connectSimulated',data)--]] end function model.disableSimulatedCamera() --[[ local data={} data.id=model.handle simBWF.query('ragnarVision_disconnectSimulated',data)--]] end function model.enableRealCamera() --[[ if not realCamera_initialCameraTransform then realCamera_initialCameraTransform=sim.getObjectMatrix(model.handles.sensor,model.handle) local data={} data.id=model.handle data.imageProcessingParameters=imgProcessingParams simBWF.query('ragnarVision_connectReal',data) end --]] end function model.disableRealCamera() --[[ if realCamera_initialCameraTransform then local data={} data.id=model.handle simBWF.query('ragnarVision_disconnectReal',data) sim.setObjectMatrix(model.handles.sensor,model.handle,realCamera_initialCameraTransform) realCamera_initialCameraTransform=nil end --]] end function sysCall_init() model.codeVersion=1 model.sensorInitialMatrix=sim.getObjectMatrix(model.handles.sensor,-1) model.allDesiredModelPoses={} model.online=simBWF.isSystemOnline() model.simOrRealIndex=1 model.lastImgUpdateTimeInMs=-1000 if model.online then model.simOrRealIndex=2 model.lastImgUpdateTimeInMs=sim.getSystemTimeInMs(-1)-1000 end local data=model.readInfo() model.sensorResolution=data.resolution model.imgToDisplay=data.imgToDisplay[model.simOrRealIndex] model.imgSizeToDisplay=data.imgSizeToDisplay[model.simOrRealIndex] model.lastImgToDisplay=-1 model.lastImgSizeToDisplay=model.imgSizeToDisplay-- -1 if model.online then model.enableRealCamera() else model.enableSimulatedCamera() end end function sysCall_sensing() local data=model.readInfo() model.imgToDisplay=data.imgToDisplay[model.simOrRealIndex] model.imgSizeToDisplay=data.imgSizeToDisplay[model.simOrRealIndex] local delaysInMs={50,200,1000} model.imgUpdateFrequMs=delaysInMs[data.imgUpdateFrequ[model.simOrRealIndex]+1] if model.online then if model.lastImgToDisplay~=model.imgToDisplay or model.lastImgSizeToDisplay~=model.imgSizeToDisplay then model.realCamDisp.removeDisplay() if model.lastImgSizeToDisplay~=model.imgSizeToDisplay then simBWF.writeSessionPersistentObjectData(model.handle,"visionImgDlgPosReal",nil) end if model.realCamDisp.createDisplay() then model.lastImgToDisplay=model.imgToDisplay model.lastImgSizeToDisplay=model.imgSizeToDisplay end end model.realCamDisp.updateDisplay() else sim.handleVisionSensor(model.handles.sensor) if model.lastImgToDisplay~=model.imgToDisplay or model.lastImgSizeToDisplay~=model.imgSizeToDisplay then model.simCamDisp.removeDisplay() if model.lastImgSizeToDisplay~=model.imgSizeToDisplay then simBWF.writeSessionPersistentObjectData(model.handle,"visionImgDlgPosSim",nil) end if model.simCamDisp.createDisplay() then model.lastImgToDisplay=model.imgToDisplay model.lastImgSizeToDisplay=model.imgSizeToDisplay end end model.simCamDisp.updateDisplay() end end function sysCall_cleanup() if model.online then model.realCamDisp.removeDisplay() model.disableRealCamera() else model.simCamDisp.removeDisplay() model.disableSimulatedCamera() end sim.setObjectMatrix(model.handles.sensor,-1,model.sensorInitialMatrix) end
object_tangible_loot_npc_loot_spice_yarrock_generic = object_tangible_loot_npc_loot_shared_spice_yarrock_generic:new { } ObjectTemplates:addTemplate(object_tangible_loot_npc_loot_spice_yarrock_generic, "object/tangible/loot/npc/loot/spice_yarrock_generic.iff")
--[[ Project TkJson-Lua Author T1nKeR File TkBench.lua Decription A benchmark library. --]] local TkBench = {} TkBench.LibraryQueue = {} function TkBench.Reset() TkBench.LibraryQueue = {} end function TkBench.RegisterLibrary(library_name, decoder, encoder) local library = {} library.name = library_name library.decode = decoder library.encode = encoder table.insert(TkBench.LibraryQueue, library) end function TkBench.TestDecode(library, filename) local json_file = assert(io.open(filename, 'r')) local json_string = json_file:read('a') local test_time = 0.0 local test_count = 10 for i = 1, test_count do local start_clock = os.clock() local value = library.decode(json_string) local stop_clock = os.clock() test_time = test_time + (stop_clock - start_clock) end test_time = test_time / test_count print( string.format( "> Pressure Test - JSON Decoder: %s, Filename: %s, Elapsed Time: %fs", library.name, filename, test_time ) ) return test_time end function TkBench.TestEncode(library, filename) local json_file = assert(io.open(filename, 'r')) local json_string = json_file:read('a') local json_value = library.decode(json_string) local test_time = 0.0 local test_count = 10 for i = 1, test_count do local start_clock = os.clock() local value = library.encode(json_value) local stop_clock = os.clock() test_time = test_time + (stop_clock - start_clock) end test_time = test_time / test_count print( string.format( "> Pressure Test - JSON Encoder: %s, Filename: %s, Elapsed Time: %fs", library.name, filename, test_time ) ) return test_time end function TkBench.DecodeBenchmark(filename) for key, library in ipairs(TkBench.LibraryQueue) do TkBench.TestDecode(library, filename) end print('--------------------------------------------------------------') end function TkBench.EncodeBenchmark(filename) for key, library in ipairs(TkBench.LibraryQueue) do TkBench.TestEncode(library, filename) end print('--------------------------------------------------------------') end return TkBench
-- utility functions and variables -- dump object, see https://stackoverflow.com/a/27028488/707516 function dump_object(o) if type(o) == "table" then local s = "{ " for k, v in pairs(o) do if type(k) ~= "number" then k = '"' .. k .. '"' end s = s .. "[" .. k .. "] = " .. dump_object(v) .. "," end return s .. "} " else return tostring(o) end end local function split(str, sep) local result = {} local regex = ("([^%s]+)"):format(sep) for each in str:gmatch(regex) do table.insert(result, each) end return result end -- enumerate network interfaces, see https://superuser.com/a/1173532/95569 function enum_ifaces_full() local _in_docker = in_docker() local ifaces = {} for i, device in ipairs(sys_call("bash ./script/netlist.sh")) do local lines = split(device, ":") table.insert(ifaces, lines) end return ifaces end function enum_ifaces() local _in_docker = in_docker() local ifaces = {} for i, l in ipairs(sys_call("basename -a /sys/class/net/*")) do local p = sys_call("realpath /sys/class/net/" .. l, true) -- for regular host, skip virtual interfaces (including lo) -- in container, return all interfaces except lo if not p:match("^/sys/devices/virtual/") or (_in_docker and l ~= "lo") then table.insert(ifaces, l) end end return ifaces end -- enumerate mounted disks -- NOTE: only list most relevant mounts, e.g. boot partitions are ignored function enum_disks() local fs_types = "fuseblk,ext2,ext3,ext4,ecryptfs,vfat" if in_docker() then fs_types = fs_types .. ",overlay" end local cmd = "findmnt -bPUno TARGET,FSTYPE,SIZE,USED,LABEL,SOURCE,AVAIL -t " .. fs_types local entry_pattern = '^TARGET="(.+)"%s+FSTYPE="(.+)"%s+SIZE="(.+)"%s+USED="(.+)"%s+LABEL="(.+)"%s+SOURCE="(.+)"%s+AVAIL="(.+)"$' local mnt_fs = sys_call(cmd) local mnts = {} for i, l in ipairs(mnt_fs) do local mnt, fstype, size, used, label, source, avail = l:match(entry_pattern) if mnt and is_dir(mnt) and is_readable(mnt) and not mnt:match("^/boot/") and not mnt:match("^/run/live/") then table.insert( mnts, { mnt = mnt, type = fstype, size = tonumber(size), used = tonumber(used), avail = tonumber(avail), label = label, source = source } ) end end return mnts end -- some environment variables local env = {} for i, k in ipairs({"HOME", "USER"}) do env[k] = os.getenv(k) end -- human friendly file size local _filesize = require "filesize" function filesize(size) return _filesize(size, {round = 0, spacer = "", base = 2}) end -- call at interval, similar to Conky's `execi` but for functions local _interval_call_cache = {} function interval_call(interv, func, ...) if _interval_call_cache[func] == nil then _interval_call_cache[func] = {} end local cache = _interval_call_cache[func] local now = os.time() if cache.last == nil or (now - cache.last) >= interv then cache.result = func(...) cache.last = now end return cache.result end -- pad string to `max_len`, `align` mode can be 'left', 'right' or 'center' function padding(str, max_len, align, char) if not max_len then return str end local n = max_len - utf8_len(str) if n <= 0 then return str end if not align then align = "left" end if not char then char = " " end assert(utf8_len(char) == 1, "padding `char` must be a single character.") local srep = string.rep if align == "center" then local m = math.floor(n / 2) return srep(char, m) .. str .. srep(char, n - m) elseif align == "left" then return str .. srep(char, n) elseif align == "right" then return srep(char, n) .. str end end -- strip surrounding whitespaces function trim(str) return str:match("^%s*(.-)%s*$") end -- strip surrounding braces function unbrace(str) if not str then return str end while true do local u = str:match("^{(.-)}$") if u then str = u else return str end end end -- count characters in a utf-8 encoded string function utf8_len(str) local _, count = string.gsub(str, "[^\128-\193]", "") return count end -- calculate ratio as percentage function percent_ratio(x, y) return math.floor(100.0 * tonumber(x) / tonumber(y)) end -- run system command and return stdout as lines or a string function sys_call(cmd, as_string) local pipe = io.popen(cmd) local lines = {} for l in pipe:lines() do table.insert(lines, l) end pipe:close() if as_string then return table.concat(lines, "\n") else return lines end end -- eval string as system call and check if result is true function is_true(expr) local s = sys_call(expr .. ' && echo "true"', true) return (#s > 3) end -- is dir or file function is_dir(p) return is_true('[ -d "' .. p .. '" ]') end -- is path readable function is_readable(p) return is_true('[ -r "' .. p .. '" ]') end -- is running in a docker container function in_docker() return is_true('[ -f /.dockerenv ] || grep -Eq "(lxc|docker)" /proc/1/cgroup') end return { dump_object = dump_object, enum_ifaces_full = enum_ifaces_full, enum_ifaces = enum_ifaces, enum_disks = enum_disks, env = env, filesize = filesize, interval_call = interval_call, padding = padding, percent_ratio = percent_ratio, sys_call = sys_call, trim = trim, unbrace = unbrace }
function sendChatMessage(templateID, arguments) TriggerEvent('chat:addMessage', { templateId = templateID, multiline = true, args = arguments } ) end --[[ drawNotification(message) Displayes a message above the map @message - The message to display ]] function drawNotification(message) SetNotificationTextEntry("STRING") AddTextComponentString(message) DrawNotification(false, false) end --[[ isPedRealAndAlive(playerPed) Checks to make sure a player exists and is not dead @playerPed - The player ped of the entity to test (See GetPlayerPed()) @returns - boolean ]] function isPedRealAndAlive(playerPed) if DoesEntityExist(playerPed) and not IsEntityDead(playerPed) then return true else return false end end --[[ isVehicleLocked(vehicle) Checks to see if a vehicle is locked @vehicle - The vehicle to check @returns - boolean @nilReturns The function will return nil when the vehicle doesn't exist ]] function isVehicleLocked(vehicle) if not DoesEntityExist(vehicle) then return nil end -- Make sure the vehicle is real local lockState = GetVehicleDoorLockStatus(vehicle) if lockState == 0 or lockState == 1 then return false else return true end end --[[ doesVehicleHaveDoor(vehicle, doorIndex) Checks if a vehicle has a specific door Vehicle Door Indexes: 0 = Front Driver 1 = Rear Driver 2 = Front Passenger 3 = Rear Passenger 4 = Hood 5 = Trunk @vehicle - The vehicle to check @doorIndex - The index of the door to check @returns - boolean @nilReturns The function will return nil when either the vehicle doesn't exist or the doorIndex is out of value ]] function doesVehicleHaveDoor(vehicle, doorIndex) if not isDoorIndexValid(doorIndex) then return nil end -- Make sure the doorIndex is valid if not DoesEntityExist(vehicle) then return nil end -- Make sure the vehicle is real local value = GetIsDoorValid(vehicle, doorIndex) return value end --[[ doesVehicleHaveWindow(vehicle, windowIndex) Checks if a vehicle has a specific window Vehicle Window Indexes: 0 = Front Driver 1 = Front Passenger 2 = Rear Driver 3 = Rear Passenger @vehicle - The vehicle to check @windowIndex - The index of the window to check @returns - boolean @nilReturns The function will return nil when either the vehicle doesn't exist or the windowIndex is out of value ]] function doesVehicleHaveWindow(vehicle, windowIndex) if not isWindowIndexValid(windowIndex) then return nil end -- Make sure the windowIndex is valid if not DoesEntityExist(vehicle) then return nil end -- Make sure the vehicle is real doorIndex = windowIndexToDoorIndex(windowIndex) local value = GetIsDoorValid(vehicle, doorIndex) return value end --[[ isVehicleDoorOpen(vehicle, doorIndex) Checks if a vehicle's door is open or not Vehicle Door Indexes: 0 = Front Driver 1 = Rear Driver 2 = Front Passenger 3 = Rear Passenger 4 = Hood 5 = Trunk @vehicle - The vehicle to check @doorIndex - The index of the door to check @returns - boolean @nilReturns The function will return nil when either the vehicle doesn't exist the doorIndex is out of value the vehicle doesn't have the requested door ]] function isVehicleDoorOpen(vehicle, doorIndex) if not isDoorIndexValid(doorIndex) then return nil end -- Make sure the doorIndex is valid if not DoesEntityExist(vehicle) then return nil end -- Make sure the vehicle is real if not doesVehicleHaveDoor(vehicle, doorIndex) then return nil end -- Make sure the vehicle has the door if GetVehicleDoorAngleRatio(vehicle, doorIndex) > 0 then return true else return false end end --[[ isVehicleWindowOpen(vehicle, windowIndex) Checks if a vehicle's window is open or not Vehicle Window Indexes: 0 = Front Driver 1 = Front Passenger 2 = Rear Driver 3 = Rear Passenger @vehicle - The vehicle to check @windowIndex - The index of the window to check @returns - boolean @nilReturns The function will return nil when either the vehicle doesn't exist the windowIndex is out of value the vehicle doesn't have the requested windowwindowIndex ]] function isVehicleWindowOpen(vehicle, windowIndex) key = getKeyFromWindowIndex(windowIndex) if key == nil then return nil end if not isWindowIndexValid(windowIndex) then return nil end -- Make sure the windowIndex is valid if not DoesEntityExist(vehicle) then return nil end -- Make sure the vehicle is real if not doesVehicleHaveWindow(vehicle, windowIndex) then return nil end -- Make sure the vehicle has the window TriggerServerEvent("Jay:Basics:syncVehicleData") Citizen.Wait(100) if Vehicles[vehicle] == nil then return true else if Vehicles[vehicle]["windows"][key] then return true elseif not Vehicles[vehicle]["windows"][key] then return false end end end --[[ isDoorIndexValid(doorIndex) Checks if a value is allowed as a doorIndex Vehicle Door Indexes: 0 = Front Driver 1 = Rear Driver 2 = Front Passenger 3 = Rear Passenger 4 = Hood 5 = Trunk @doorIndex - The index of the door to check @returns - boolean ]] function isDoorIndexValid(doorIndex) if doorIndex >= 0 and doorIndex <= 5 then return true else return false end end --[[ isWindowIndexValid(windowIndex) Checks if a value is allowed as a windowIndex Vehicle Window Indexes: 0 = Front Driver 1 = Front Passenger 2 = Rear Driver 3 = Rear Passenger @windowIndex - The index of the window to check @returns - boolean ]] function isWindowIndexValid(windowIndex) if windowIndex >= 0 and windowIndex <= 3 then return true else return false end end --[[ windowIndexToDoorIndex(windowIndex) Gets the door index for a window index Vehicle Window Indexes: 0 = Front Driver 1 = Front Passenger 2 = Rear Driver 3 = Rear Passenger Vehicle Door Indexes: 0 = Front Driver 1 = Rear Driver 2 = Front Passenger 3 = Rear Passenger @windowIndex - The index of the window to check @returns - number ]] function windowIndexToDoorIndex(windowIndex) if windowIndex == 0 then return 0 elseif windowIndex == 1 then return 1 elseif windowIndex == 2 then return 2 elseif windowIndex == 3 then return 3 else return nil end end --[[ translateDoorIndex(doorIndex) Coverts a doorIndex int to a string Vehicle Door Indexes: 0 = Front Driver 1 = Rear Driver 2 = Front Passenger 3 = Rear Passenger 4 = Hood 5 = Trunk @doorIndex - The index of the door @returns - String @nilReturns The function will return nil when the doorIndex is out of value ]] function translateDoorIndex(doorIndex) if not isDoorIndexValid(doorIndex) then return nil end -- Make sure the doorIndex is valid if doorIndex == 0 then return _U("frontDriver") elseif doorIndex == 1 then return _U("frontPassenger") elseif doorIndex == 2 then return _U("rearDriver") elseif doorIndex == 3 then return _U("rearPassenger") elseif doorIndex == 4 then return _U("hood") elseif doorIndex == 5 then return _U("trunk") end end --[[ translateWindowIndex(windowIndex) Coverts a windowIndex int to a string Vehicle Window Indexes: 0 = Front Driver 1 = Front Passenger 2 = Rear Driver 3 = Rear Passenger @windowIndex - The index of the window @returns - String @nilReturns The function will return nil when the windowIndex is out of value ]] function translateWindowIndex(windowIndex) if not isWindowIndexValid(windowIndex) then return nil end -- Make sure the windowIndex is valid if windowIndex == 0 then return _U("frontDriver") elseif windowIndex == 1 then return _U("frontPassenger") elseif windowIndex == 2 then return _U("rearDriver") elseif windowIndex == 3 then return _U("rearPassenger") end end --[[ isPedInSeatForDoorIndex(playerPed, vehicle, doorIndex) Checks if the player is in an appropriate seat to access a sepcific door. @playerPed - The player to check @vehicle - The vehicle to check @doorIndex - The index of the door to check @returns - boolean @nilReturns The function will return nil when either the player doesn't exist the vehicle doesn't exist the doorIndex is out of value the vehicle doesn't have the requested door ]] function isPedInSeatForDoorIndex(playerPed, vehicle, doorIndex) if not isPedRealAndAlive(playerPed) then return nil end -- Make sure the playerPed is real if not DoesEntityExist(vehicle) then return nil end -- Make sure the vehicle is real if not isDoorIndexValid(doorIndex) then return nil end -- Make sure the doorIndex is valid if not doesVehicleHaveDoor(vehicle, doorIndex) then return nil end -- Make sure the vehicle has that door if doorIndex == 0 or doorIndex == 4 or doorIndex == 5 then -- check for front driver if GetPedInVehicleSeat(vehicle, -1) == playerPed then return true else return false end elseif doorIndex == 2 then -- check for front passenger if GetPedInVehicleSeat(vehicle, 0) == playerPed then return true else return false end elseif doorIndex == 1 then -- check for rear driver if GetPedInVehicleSeat(vehicle, 1) == playerPed then return true else return false end elseif doorIndex == 3 then -- check for rear passenger if GetPedInVehicleSeat(vehicle, 2) == playerPed then return true else return false end end end --[[ isPedInSeatForWindowIndex(playerPed, vehicle, windowIndex) Checks if the player is in an appropriate seat to access a sepcific door. Vehicle Window Indexes: 0 = Front Driver 1 = Front Passenger 2 = Rear Driver 3 = Rear Passenger @playerPed - The player to check @vehicle - The vehicle to check @windowIndex - The index of the window to check @returns - boolean @nilReturns The function will return nil when either the player doesn't exist the vehicle doesn't exist the windowIndex is out of value the vehicle doesn't have the requested window ]] function isPedInSeatForWindowIndex(playerPed, vehicle, windowIndex) if not isPedRealAndAlive(playerPed) then return nil end -- Make sure the playerPed is real if not DoesEntityExist(vehicle) then return nil end -- Make sure the vehicle is real if not isWindowIndexValid(windowIndex) then return nil end -- Make sure the windowIndex is valid if not doesVehicleHaveWindow(vehicle, windowIndex) then return nil end -- Make sure the vehicle has that window if windowIndex == 0 then -- check for front driver if GetPedInVehicleSeat(vehicle, -1) == playerPed then return true else return false end elseif windowIndex == 1 then -- check for front passenger if GetPedInVehicleSeat(vehicle, 0) == playerPed or GetPedInVehicleSeat(vehicle, -1) == playerPed then return true else return false end elseif windowIndex == 2 then -- check for rear driver if GetPedInVehicleSeat(vehicle, 1) == playerPed or GetPedInVehicleSeat(vehicle, -1) == playerPed then return true else return false end elseif windowIndex == 3 then -- check for rear passenger if GetPedInVehicleSeat(vehicle, 2) == playerPed or GetPedInVehicleSeat(vehicle, -1) == playerPed then return true else return false end end end --[[ DO NOT USE, OLD METHOD ]] function getKeyFromWindowIndex(windowIndex) if windowIndex == 0 then return "fd" elseif windowIndex == 1 then return "fp" elseif windowIndex == 2 then return"rd" elseif windowIndex == 3 then return "rp" else return nil end end function setWindowData(vehicle, windowIndex) key = getKeyFromWindowIndex(windowIndex) if key == nil then return nil end if Vehicles[vehicle] == nil then Vehicles[vehicle] = { locked = false, key = nil, windows = { fd = true, fp = true, rd = true, rp = true } } end Vehicles[vehicle]["windows"][key] = not Vehicles[vehicle]["windows"][key] TriggerServerEvent("Jay:Basics:setVehicleData", vehicle, Vehicles[vehicle]) TriggerServerEvent("Jay:Basics:syncVehicleData") end function getVehicleInDirection(coordFrom, coordTo) local rayHandle = CastRayPointToPoint(coordFrom.x, coordFrom.y, coordFrom.z, coordTo.x, coordTo.y, coordTo.z, 10, GetPlayerPed(-1), 0) local a, b, c, d, vehicle = GetRaycastResult(rayHandle) return vehicle end --[[ Shoutout to Flatracer on the forums for this one https://forum.cfx.re/t/use-displayonscreenkeyboard-properly/51143/2 -- TextEntry --> The Text above the typing field in the black square -- ExampleText --> An Example Text, what it should say in the typing field -- MaxStringLenght --> Maximum String Lenght ]] function getUserTextInput(TextEntry, ExampleText, MaxStringLenght) AddTextEntry('FMMC_KEY_TIP1', TextEntry) --Sets the Text above the typing field in the black square DisplayOnscreenKeyboard(1, "FMMC_KEY_TIP1", "", ExampleText, "", "", "", MaxStringLenght) --Actually calls the Keyboard Input blockinput = true --Blocks new input while typing if **blockinput** is used while UpdateOnscreenKeyboard() ~= 1 and UpdateOnscreenKeyboard() ~= 2 do --While typing is not aborted and not finished, this loop waits Citizen.Wait(0) end if UpdateOnscreenKeyboard() ~= 2 then local result = GetOnscreenKeyboardResult() --Gets the result of the typing Citizen.Wait(500) --Little Time Delay, so the Keyboard won't open again if you press enter to finish the typing blockinput = false --This unblocks new Input when typing is done return result --Returns the result else Citizen.Wait(500) --Little Time Delay, so the Keyboard won't open again if you press enter to finish the typing blockinput = false --This unblocks new Input when typing is done return nil --Returns nil if the typing got aborted end end
--[[ Static class to display menu at start of game, or after lives lost ]] local Shared = require "shared" local Menu = {} function Menu.update(keyboard) --[[ love.keypressed(key) in main.lua takes priority, so not required in Menu.lua ]] end function Menu.draw(gameTitle) --[[ show start menu screen ]] -- drawText(text, size, x, y, align, colour) -- drawText("Hello", "size24", 10, 10, "centre", WHITE) Shared.drawText(gameTitle, "size64", 0, Shared.HEIGHT * 0.25, 'centre', Shared.YELLOW) Shared.drawText("Arrow keys move, space to fire", "size22", 0, Shared.HEIGHT * 0.5, 'centre', Shared.WHITE) Shared.drawText("Press Enter to begin", "size30", 0, Shared.HEIGHT * 0.65, 'centre', Shared.WHITE) Shared.drawText("Escape to quit at any time", "size18", 0, Shared.HEIGHT * 0.85, 'centre', Shared.WHITE) Shared.drawText("Press B to toggle background music", "size16", 0, Shared.HEIGHT * 0.9, 'centre', Shared.GREEN) end return Menu
-- Load Extensions local application = require "mjolnir.application" local window = require "mjolnir.window" local hotkey = require "mjolnir.hotkey" local keycodes = require "mjolnir.keycodes" local fnutils = require "mjolnir.fnutils" local alert = require "mjolnir.alert" local screen = require "mjolnir.screen" -- User packages local grid = require "mjolnir.bg.grid" local appfinder = require "mjolnir.cmsj.appfinder" function init() alert.show("Mjolnir, at your service.") end -- Set grid size. grid.GRIDWIDTH = 10 grid.GRIDHEIGHT = 8 grid.MARGINX = 0 grid.MARGINY = 0 local width = grid.GRIDWIDTH local height = grid.GRIDHEIGHT local oneScreen = { { name = "Google Chrome", location = { x = 1.5, y = 0, w = 7, h = 8 } }, { name = "Wunderlist", location = { x = (width/2)-1, y = (height/2)-.75, w = (width/2)+1, h = height/2 } }, { name = "LimeChat", location = { x = (width/2)+1, y = 0, w = 4, h = 3 } }, { name = "Slack", location = { x = 0, y = 0, w = width/2, h = height/2 } } } fnutils.each(oneScreen, function(app) local found = application.launchorfocus(app.name) if found then local win = window.focusedwindow() grid.set(win, app.location, win:screen()) end end) init()
--- This file is generated by ava-x2l.exe, --- Don't change it manaully. --- @copyright Lilith Games, Project Da Vinci(Avatar Team) --- @see Official Website: https://www.projectdavinci.com/ --- @see Dev Framework: https://github.com/lilith-avatar/avatar-ava --- @see X2L Tool: https://github.com/lilith-avatar/avatar-ava-xls2lua --- source file: ./Xls/Scenes.xls local SkyXls = { [1001] = { SceneId = 1001, Des = '核弹小镇', Mode = 2, Front = 'evening_cloud_outfront', Back = 'evening_cloud_outback', Left = 'evening_cloud_outleft', Right = 'evening_cloud_outright', Up = 'evening_cloud_outup', Down = 'evening_cloud_outdown', Style = 0, Brightness = 0.2, Latitude = 40.0, ShowSun = false, SunAngular = 20.0, ShadowDistance = 70.0, ShadowIntensity = 1.0, LightType = 1, Ambient = Color(255, 255, 255, 255), SunColor = Color(255, 238, 203, 255), EquatorColor = Color(195, 184, 189, 255), GroundColor = Color(69, 52, 84, 255), SunIntensity = 1.0, SkyboxIntensity = 1.0, TimeScale = 0.0, ClockTime = 12.0, FogStart = 20.0, FogEnd = 300.0, FogColor = Color(242, 211, 178, 255), FogHeightFadeStart = 4000.0, FogHeightFadeEnd = 0.0 }, [1002] = { SceneId = 1002, Des = 'Flash', Mode = 2, Front = 'SKY_1', Back = 'SKY_2', Left = 'SKY_3', Right = 'SKY_4', Up = 'SKY_5', Down = 'SKY_6', Style = 3, Brightness = 0.1199, Latitude = 21.5, ShowSun = false, SunAngular = 21.0, ShadowDistance = 50.0, ShadowIntensity = 1.0, LightType = 0, Ambient = nil, SunColor = nil, EquatorColor = nil, GroundColor = nil, SunIntensity = nil, SkyboxIntensity = nil, TimeScale = 0.0, ClockTime = 12.0, FogStart = 50.0, FogEnd = 300.0, FogColor = Color(125, 112, 93, 0), FogHeightFadeStart = -20000.0, FogHeightFadeEnd = -20000.0 }, [1003] = { SceneId = 1003, Des = '爆破模式', Mode = 2, Front = 'SKY_1', Back = 'SKY_2', Left = 'SKY_3', Right = 'SKY_4', Up = 'SKY_5', Down = 'SKY_6', Style = 3, Brightness = 0.1199, Latitude = 21.5, ShowSun = false, SunAngular = 21.0, ShadowDistance = 50.0, ShadowIntensity = 1.0, LightType = 0, Ambient = nil, SunColor = nil, EquatorColor = nil, GroundColor = nil, SunIntensity = nil, SkyboxIntensity = nil, TimeScale = 0.0, ClockTime = 12.0, FogStart = 50.0, FogEnd = 300.0, FogColor = Color(125, 112, 93, 0), FogHeightFadeStart = -20000.0, FogHeightFadeEnd = -20000.0 }, [1004] = { SceneId = 1004, Des = 'Tojimap1', Mode = 2, Front = 'evening_cloud_outfront', Back = 'evening_cloud_outback', Left = 'evening_cloud_outleft', Right = 'evening_cloud_outright', Up = 'evening_cloud_outup', Down = 'evening_cloud_outdown', Style = 0, Brightness = 0.2, Latitude = 40.0, ShowSun = false, SunAngular = 40.0, ShadowDistance = 50.0, ShadowIntensity = 1.0, LightType = 1, Ambient = Color(255, 255, 255, 255), SunColor = Color(217, 144, 59, 255), EquatorColor = Color(160, 156, 164, 255), GroundColor = Color(64, 56, 83, 255), SunIntensity = 1.0, SkyboxIntensity = 1.0, TimeScale = 0.0, ClockTime = 16.0, FogStart = 60.0, FogEnd = 300.0, FogColor = Color(191, 184, 171, 255), FogHeightFadeStart = -1000.0, FogHeightFadeEnd = -1000.0 }, [1005] = { SceneId = 1005, Des = 'Tojimap2', Mode = 2, Front = 'SKY_1', Back = 'SKY_2', Left = 'SKY_3', Right = 'SKY_4', Up = 'SKY_5', Down = 'SKY_6', Style = 3, Brightness = 0.1199, Latitude = 21.5, ShowSun = false, SunAngular = 21.0, ShadowDistance = 50.0, ShadowIntensity = 1.0, LightType = 0, Ambient = nil, SunColor = nil, EquatorColor = nil, GroundColor = nil, SunIntensity = nil, SkyboxIntensity = nil, TimeScale = 0.0, ClockTime = 12.0, FogStart = 50.0, FogEnd = 300.0, FogColor = Color(125, 112, 93, 0), FogHeightFadeStart = -20000.0, FogHeightFadeEnd = -20000.0 }, [1006] = { SceneId = 1006, Des = 'Deathmatch', Mode = 2, Front = 'evening_cloud_outfront', Back = 'evening_cloud_outback', Left = 'evening_cloud_outleft', Right = 'evening_cloud_outright', Up = 'evening_cloud_outup', Down = 'evening_cloud_outdown', Style = 0, Brightness = 0.2, Latitude = 40.0, ShowSun = false, SunAngular = 20.0, ShadowDistance = 70.0, ShadowIntensity = 1.0, LightType = 1, Ambient = Color(255, 255, 255, 255), SunColor = Color(255, 237, 203, 255), EquatorColor = Color(195, 183, 188, 255), GroundColor = Color(69, 52, 84, 255), SunIntensity = 1.0, SkyboxIntensity = 1.0, TimeScale = 0.0, ClockTime = 12.0, FogStart = 20.0, FogEnd = 300.0, FogColor = Color(242, 210, 177, 255), FogHeightFadeStart = 4000.0, FogHeightFadeEnd = 0.0 }, [1007] = { SceneId = 1007, Des = 'Yard', Mode = 2, Front = 'skybox_new_front', Back = 'skybox_new_back', Left = 'skybox_new_left', Right = 'skybox_new_right', Up = 'skybox_new_up', Down = 'skybox_new_down', Style = nil, Brightness = nil, Latitude = nil, ShowSun = nil, SunAngular = 21.0, ShadowDistance = 50.0, ShadowIntensity = 1.0, LightType = nil, Ambient = Color(212, 193, 145, 255), SunColor = Color(240, 234, 215, 255), EquatorColor = Color(235, 235, 235, 255), GroundColor = Color(133, 115, 98, 255), SunIntensity = nil, SkyboxIntensity = nil, TimeScale = 0.0, ClockTime = nil, FogStart = 50.0, FogEnd = 300.0, FogColor = Color(222, 192, 163, 255), FogHeightFadeStart = nil, FogHeightFadeEnd = nil }, [1008] = { SceneId = 1008, Des = 'Factory', Mode = 2, Front = 'skybox_new_front', Back = 'skybox_new_back', Left = 'skybox_new_left', Right = 'skybox_new_right', Up = 'skybox_new_up', Down = 'skybox_new_down', Style = 0, Brightness = 0.2, Latitude = 45.0, ShowSun = true, SunAngular = 21.0, ShadowDistance = 50.0, ShadowIntensity = 0.8, LightType = 1, Ambient = Color(255, 255, 255, 255), SunColor = Color(243, 221, 181, 255), EquatorColor = Color(187, 187, 187, 255), GroundColor = Color(102, 88, 116, 255), SunIntensity = 1.0, SkyboxIntensity = 1.0, TimeScale = 0.0, ClockTime = 14.0, FogStart = 50.0, FogEnd = 200.0, FogColor = Color(193, 175, 134, 255), FogHeightFadeStart = -1000.0, FogHeightFadeEnd = -1000.0 }, [1009] = { SceneId = 1009, Des = 'Base', Mode = 2, Front = 'SKY_1', Back = 'SKY_2', Left = 'SKY_3', Right = 'SKY_4', Up = 'SKY_5', Down = 'SKY_6', Style = 3, Brightness = 0.1199, Latitude = 21.5, ShowSun = false, SunAngular = 21.0, ShadowDistance = 50.0, ShadowIntensity = 1.0, LightType = 0, Ambient = nil, SunColor = nil, EquatorColor = nil, GroundColor = nil, SunIntensity = nil, SkyboxIntensity = nil, TimeScale = 0.0, ClockTime = 12.0, FogStart = 50.0, FogEnd = 300.0, FogColor = Color(125, 112, 93, 0), FogHeightFadeStart = -20000.0, FogHeightFadeEnd = -20000.0 }, [1010] = { SceneId = 1010, Des = 'Garden', Mode = 2, Front = 'skybox_new_front', Back = 'skybox_new_back', Left = 'skybox_new_left', Right = 'skybox_new_right', Up = 'skybox_new_up', Down = 'skybox_new_down', Style = nil, Brightness = nil, Latitude = nil, ShowSun = nil, SunAngular = 21.0, ShadowDistance = 50.0, ShadowIntensity = 1.0, LightType = nil, Ambient = Color(212, 193, 145, 255), SunColor = Color(240, 234, 215, 255), EquatorColor = Color(235, 235, 235, 255), GroundColor = Color(133, 115, 98, 255), SunIntensity = nil, SkyboxIntensity = nil, TimeScale = 0.0, ClockTime = nil, FogStart = nil, FogEnd = 300.0, FogColor = Color(222, 210, 182, 255), FogHeightFadeStart = nil, FogHeightFadeEnd = nil }, [1011] = { SceneId = 1011, Des = 'Hall', Mode = 2, Front = 'evening_cloud_outfront', Back = 'evening_cloud_outback', Left = 'evening_cloud_outleft', Right = 'evening_cloud_outright', Up = 'evening_cloud_outup', Down = 'evening_cloud_outdown', Style = 0, Brightness = 0.1598, Latitude = 40.0, ShowSun = true, SunAngular = 45.0, ShadowDistance = 60.0, ShadowIntensity = 0.8, LightType = 1, Ambient = Color(156, 132, 119, 255), SunColor = Color(188, 188, 188, 255), EquatorColor = Color(100, 67, 121, 255), GroundColor = Color(75, 69, 69, 255), SunIntensity = 1.0, SkyboxIntensity = 1.0, TimeScale = 0.0, ClockTime = 17.0, FogStart = 60.0, FogEnd = 250.0, FogColor = Color(213, 180, 130, 255), FogHeightFadeStart = -20000.0, FogHeightFadeEnd = -20000.0 } } return SkyXls
AddCSLuaFile(); CreateClientConVar("discord_show_icons", 1, true, false, "Should show the mute/deafen icons."); local imgSize = 64 local imgSpace = imgSize / 8; local img1 = { x = imgSpace, y = imgSpace, w = imgSize, h = imgSize }; local img2 = { x = (imgSpace * 2) + imgSize, y = imgSpace, w = imgSize, h = imgSize }; resource.AddFile("materials/icon" .. imgSize .. "/mute.png"); resource.AddFile("materials/icon" .. imgSize .. "/deafen.png"); local muteIconAsset = Material("materials/icon" .. imgSize .. "/mute.png", "smooth mips"); local deafenIconAsset = Material("materials/icon" .. imgSize .. "/deafen.png", "smooth mips"); local shouldDrawMuteIcon = false; net.Receive("drawMuteIcon", function() shouldDrawMuteIcon = net.ReadBool(); end); local shouldDrawDeafenIcon = false; net.Receive("drawDeafenIcon", function() shouldDrawDeafenIcon = net.ReadBool(); end); hook.Add("HUDPaint", "Discord_HUDPaint", function() if (not GetConVar("discord_show_icons"):GetBool()) then return; end; surface.SetDrawColor(176, 40, 40, 255 * 0.8); local muteIcon = surface; if (shouldDrawMuteIcon) then muteIcon.SetMaterial(muteIconAsset); muteIcon.DrawTexturedRect(img1.x, img1.y, img1.w, img1.h); end local deafenIcon = surface; if (shouldDrawDeafenIcon) then deafenIcon.SetMaterial(deafenIconAsset); if (not shouldDrawMuteIcon) then deafenIcon.DrawTexturedRect(img1.x, img1.y, img1.w, img1.h); else deafenIcon.DrawTexturedRect(img2.x, img2.y, img2.w, img2.h); end end end);
--[[ Copyright (c) 2020 Martin Hassman 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 addonName, NS = ...; local dataobj; local cYellow = "\124cFFFFFF00"; local cWhite = "\124cFFFFFFFF"; local cRed = "\124cFFFF0000"; local cLightBlue = "\124cFFadd8e6"; local cGreen1 = "\124cFF38FFBE"; -- updateBrokerText: must work correctly even when there is no broker library loaded function NS.updateBrokerText(text) if dataobj == nil then return; end dataobj.text = text; end if LibStub == nil then print(addonName, "ERROR: LibStub not found."); return; end local ldb = LibStub:GetLibrary("LibDataBroker-1.1", true); if ldb == nil then print(addonName, "ERROR: LibDataBroker not found."); return; end -- LibDataBroker documentation: https://github.com/tekkub/libdatabroker-1-1/wiki/How-to-provide-a-dataobject -- List of WOW UI icons: https://github.com/Gethe/wow-ui-textures/tree/live/ICONS dataobj = ldb:NewDataObject(addonName, { type = "data source", text = "", icon = "Interface\\Icons\\Trade_Engineering", }); function dataobj:OnTooltipShow() self:AddLine(addonName.." v"..GetAddOnMetadata(addonName, "version")); self:AddLine(cWhite.."Craftable:"); self:AddLine(" "); local creatableItems = NS.whatCanPlayerCreateNow(NS.data.knownRecipes); for skillName, creatableItemsList in pairs(creatableItems) do self:AddLine(cGreen1..skillName); for i, item in pairs(creatableItemsList) do local color = NS.skillTypes[item.skillType]; self:AddDoubleLine(item.recipeName, item.count, color.r,color.g,color.b,0,1,0); end self:AddLine(" "); end end
include("shared.lua") function ENT:Draw() self:DrawModel() if self.alpha == nil then self.alpha = 0 end if LocalPlayer():GetPos():Distance(self:GetPos()) < 100 then self.alpha = Lerp(10 * FrameTime() , self.alpha , 255) else self.alpha = Lerp(10 * FrameTime() , self.alpha , 0) end local ang = self:GetAngles() ang:RotateAroundAxis(self:GetAngles():Forward(),90) cam.Start3D2D(self:GetPos() + (ang:Up() *22.2) + (ang:Right() * -38.75), ang , 0.0175) draw.SimpleText("Pressed 'E' to get an unpressed plate, Then take it to the press","TABLE_PRESS",0,60, Color(255,255,255,self.alpha),1,1) cam.End3D2D() local ang = self:GetAngles() ang:RotateAroundAxis(self:GetAngles():Right(),90) ang:RotateAroundAxis(self:GetAngles():Forward(),90) cam.Start3D2D(self:GetPos() + (ang:Up() *22.2) + (ang:Right() * -38.75), ang , 0.0175) draw.SimpleText("Pressed 'E' to get an unpressed plate, Then take it to the press","TABLE_PRESS",0,60, Color(255,255,255,self.alpha),1,1) cam.End3D2D() local ang = self:GetAngles() ang:RotateAroundAxis(self:GetAngles():Right(),180) ang:RotateAroundAxis(self:GetAngles():Forward(),90) cam.Start3D2D(self:GetPos() + (ang:Up() *22.2) + (ang:Right() * -38.75), ang , 0.0175) draw.SimpleText("Pressed 'E' to get an unpressed plate, Then take it to the press","TABLE_PRESS",0,60, Color(255,255,255,self.alpha),1,1) cam.End3D2D() local ang = self:GetAngles() ang:RotateAroundAxis(self:GetAngles():Right(),180+90) ang:RotateAroundAxis(self:GetAngles():Forward(),90) cam.Start3D2D(self:GetPos() + (ang:Up() *22.2) + (ang:Right() * -38.75), ang , 0.0175) draw.SimpleText("Pressed 'E' to get an unpressed plate, Then take it to the press","TABLE_PRESS",0,60, Color(255,255,255,self.alpha),1,1) cam.End3D2D() end function ENT:Initialize() local csm = {} local offset = self:GetPos() + Vector(0,0,39) + (self:GetAngles():Forward() * -15) + (self:GetAngles():Right() * -9) for i =0 , 3 do for y = 0 , 1 do local xOffset = 0 local stack = math.random(1,10) for a = 1 , stack do local t = ClientsideModel("models/press-plates/plate.mdl") local r = math.random(1,2) if r == 2 then t:SetAngles(self:GetAngles()) else local ang = self:GetAngles() ang:RotateAroundAxis(self:GetAngles():Up(),180) t:SetAngles(ang) end t:SetSubMaterial(1,"press-plates/plate_body") t:SetPos(offset + (self:GetAngles():Forward() * (i * 10)) + (self:GetAngles():Right() * (y * 19)) + (self:GetAngles():Up() * xOffset)) t:Spawn() t:SetParent(self) table.insert(csm , t) xOffset = xOffset + 0.37 end end end self.csm = csm end function ENT:OnRemove() for k ,v in pairs(self.csm) do v:Remove() end end
require "Server" require "Binary" require "ai" love = {} love.timer = {} function love.timer.getDelta() return 0.02 end server:Init(8118) server:setPing(true, 2, "PING!") server:setHandshake("Hi! I want to play pong!") server:setCallback(updatedata) ai:init() while true do server:update() end
local module = {} function module.init(Modules) local network = Modules.network local events = Modules.events network:connect("fireEvent", "OnClientEvent", function(...) events:fireEventLocal(...) end) end return module
local add_command = require("nebula.helpers.nvim").add_user_command add_command("ReloadPlugins", Nebula.load_plugins)
function create_table_element(filename) --[[ Reads in the file given by the path filename and outputs a new pandoc table element filename: string new_section: pandoc.Table or nil ]] local f = io.open(filename, "r") if f ~= nil then local csv = f:read("*all") f:close() local new_section = pandoc.read(csv, "csv") return new_section end return nil end function CodeBlock(e) --[[ turns a CodeBlock element into a table e: CodeBlock element ]] local caption = e.text local filename = e.attr.classes[1] if filename == nil then return e end if string.match(filename, "csv") then local new_section = create_table_element(filename) if new_section ~= nil then local ast_table = new_section.blocks[1] ast_table.caption.short = { pandoc.Str(caption) } return ast_table end else return e end end function Div(e) -- turns a Div element into a table local caption = e.content[1].content[1] local filename = e.attr.classes[1] if filename == nil then return e end if string.match(filename, "csv") then local new_section = create_table_element(filename) if new_section ~= nil then local ast_table = new_section.blocks[1] ast_table.caption.short = { pandoc.Str(caption) } return ast_table end else return e end end
local function getLayoutTable() local t = {}; for k, v in pairs(sArenaMixin.layouts) do t[k] = sArenaMixin.layouts[k].name and sArenaMixin.layouts[k].name or k; end return t; end local function validateCombat() if ( InCombatLockdown() ) then return "Must leave combat first."; end return true; end local growthOptions = { "Down", "Up", "Right", "Left" }; local drCategories = { ["Stun"] = "Stuns", ["Incapacitate"] = "Incapacitates", ["Disorient"] = "Disorients", ["Silence"] = "Silences", ["Root"] = "Roots", }; sArenaMixin.optionsTable = { type = "group", childGroups = "tab", validate = validateCombat, args = { setLayout = { order = 1, name = "Layout", type = "select", style = "dropdown", get = function(info) return info.handler.db.profile.currentLayout end, set = "SetLayout", values = getLayoutTable, }, test = { order = 2, name = "Test", type = "execute", func = "Test", width = "half", }, hide = { order = 3, name = "Hide", type = "execute", func = function(info) for i = 1, 3 do info.handler["arena"..i]:OnEvent("PLAYER_ENTERING_WORLD"); end end, width = "half", }, globalSettingsGroup = { order = 4, name = "Global Settings", type = "group", childGroups = "tree", args = { framesGroup = { order = 1, name = "Arena Frames", type = "group", args = { scale = { order = 1, name = "Scale", type = "range", min = 0.1, max = 5.0, softMin = 0.5, softMax = 3.0, step = 0.01, bigStep = 0.1, isPercent = true, get = function(info) return info.handler.db.profile.scale end, set = function(info, val) info.handler.db.profile.scale = val; info.handler:SetScale(val); end, }, framePositioning = { order = 2, name = "Positioning", type = "group", inline = true, args = { horizontal = { order = 1, name = "Horizontal", type = "range", min = -1000, max = 1000, step = 0.1, bigStep = 1, get = function(info) return info.handler.db.profile.posX; end, set = function(info, val) info.handler.db.profile.posX = val; info.handler:UpdatePositioning(); end, }, vertical = { order = 1, name = "Vertical", type = "range", min = -1000, max = 1000, step = 0.1, bigStep = 1, get = function(info) return info.handler.db.profile.posY; end, set = function(info, val) info.handler.db.profile.posY = val; info.handler:UpdatePositioning(); end, }, }, }, frameGrowth = { order = 3, name = "Growth", type = "group", inline = true, args = { growthDirection = { order = 1, name = "Direction", type = "select", style = "dropdown", get = function(info) return info.handler.db.profile.frameGrowthDirection end, set = function(info, val) info.handler.db.profile.frameGrowthDirection = val; info.handler:UpdatePositioning(); end, values = growthOptions, }, frameSpacing = { order = 2, name = "Spacing", desc = "Spacing between each arena frame", type = "range", min = 0, max = 100, step = 1, get = function(info) return info.handler.db.profile.frameSpacing end, set = function(info, val) info.handler.db.profile.frameSpacing = val; info.handler:UpdatePositioning(); end, }, }, }, classColors = { order = 4, name = "Use Class Colors", desc = "When disabled, health bars will be green", type = "toggle", get = function(info) return info.handler.db.profile.classColors end, set = function(info, val) info.handler.db.profile.classColors = val; end, }, }, }, drGroup = { order = 2, name = "Diminishing Returns", type = "group", args = { categories = { order = 1, name = "Categories", type = "multiselect", get = function(info, key) return info.handler.db.profile.dr.categories[key]; end, set = function(info, key, val) info.handler.db.profile.dr.categories[key] = val; end, values = drCategories, }, size = { order = 2, name = "Size", type = "group", inline = true, args = { size = { order = 1, name = "Size", type = "range", min = 2, max = 128, softMin = 8, softMax = 64, step = 1, get = function(info) return info.handler.db.profile.dr.size; end, set = function(info, val) for i = 1, 3 do info.handler["arena"..i]:SetDRSize(val); end end, }, borderSize = { order = 2, name = "Border Size", type = "range", min = 0, max = 24, softMin = 1, softMax = 16, step = 0.1, bigStep = 1, get = function(info) return info.handler.db.profile.dr.borderSize; end, set = function(info, val) for i = 1, 3 do info.handler["arena"..i]:SetDRBorderSize(val); end end, }, }, }, positioning = { order = 3, name = "Positioning", type = "group", inline = true, args = { horizontal = { order = 1, name = "Horizontal", type = "range", min = -500, max = 500, softMin = -200, softMax = 200, step = 0.1, bigStep = 1, get = function(info) return info.handler.db.profile.dr.posX; end, set = function(info, val) info.handler.db.profile.dr.posX = val; for i = 1, 3 do info.handler["arena"..i]:UpdateDRPositions(); end end, }, vertical = { order = 2, name = "Vertical", type = "range", min = -500, max = 500, softMin = -200, softMax = 200, step = 0.1, bigStep = 1, get = function(info) return info.handler.db.profile.dr.posY; end, set = function(info, val) info.handler.db.profile.dr.posY = val; for i = 1, 3 do info.handler["arena"..i]:UpdateDRPositions(); end end, }, }, }, growth = { order = 4, name = "Growth", type = "group", inline = true, args = { growthDirection = { order = 1, name = "Direction", type = "select", style = "dropdown", get = function(info) return info.handler.db.profile.dr.growthDirection end, set = function(info, val) info.handler.db.profile.dr.growthDirection = val; for i = 1, 3 do info.handler["arena"..i]:UpdateDRPositions(); end end, values = growthOptions, }, spacing = { order = 2, name = "Spacing", type = "range", min = 0, max = 32, softMin = 0, softMax = 32, step = 1, get = function(info) return info.handler.db.profile.dr.spacing; end, set = function(info, val) info.handler.db.profile.dr.spacing = val; for i = 1, 3 do info.handler["arena"..i]:UpdateDRPositions(); end end, }, }, }, }, }, }, }, layoutSettingsGroup = { order = 5, name = "Layout Settings", type = "group", args = {}, }, }, };
-- level3.lua Lvl3 = Gamestate.new() -- LV. 03 (first "bigger" Lv with two ways of choice) function Lvl3:init() atlMap = atl.Loader.load('level3.tmx') player = entity.new(150,675,55,79,atlMap,select(2,next(atlMap.layers))) -- coins and enemies -> all in groups on map coin1 = createNewCoin(845 ,165 , width, height); coin2 = createNewCoin(2300 , 105 , width, height) coin3 = createNewCoin(2300 ,145 , width, height);coin4 = createNewCoin(2300 , 185, width, height) coin5 = createNewCoin(1250 ,1075 , width, height);coin6 = createNewCoin(1250 ,1115 , width, height) coin7 = createNewCoin(1250 ,1155 , width, height);coin8 = createNewCoin(1290 ,1155 , width, height) coin9 = createNewCoin(2080 ,1225, width, height);coin10 = createNewCoin(2120 ,1225, width, height) coin11 = createNewCoin(2160 ,1225 , width, height);coin12 = createNewCoin(2200 ,1225, width, height) coin13 = createNewCoin(2240, 1225, width, height);coin14 = createNewCoin(2700 ,750 , width, height) coin15 = createNewCoin(2800 ,750 , width, height) -- and because it's a star ... coin15_2 = createNewCoin(2752.5 ,800 , width, height);coin16 = createNewCoin(2700 ,834 , width, height) coin17 = createNewCoin(2800, 834, width, height) EasyEnemy1 = createNewEasyEnemy(2125, 165, vxEnem );EasyEnemy2 = createNewEasyEnemy(2125, 834, vxEnem ) EasyEnemy3 = createNewEasyEnemy(1475, 834, vxEnem );EasyEnemy4 = createNewEasyEnemy(2455, 1220, vxEnem ) playerCollide() end function Lvl3:update(dt) if not ingameMenuOpen then playerCollide_generalUpdate(dt) enem_update(dt) player_update(dt) coin_update(dt) bullet_update(dt) end end function Lvl3:draw() camera:set() atlMap:draw() enem_draw() player_draw() coin_draw() bullet_draw() ingameMenu_draw() camera:unset() playerCollide_drawStatBar() end function Lvl3:keypressed(key) ingameMenu_keypressed(key) end local releaseX, releaseY = 150, 675 function Lvl3:keyreleased(k) if k == 'r' then player.x, player.y = releaseX, releaseY end end
local header = [[ /* auto generated by structs_vk.lua */ /* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA CORPORATION nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ ////////////////////////////////////////////////////////////////////////// /** # function nvvk::make, nvvk::clear Contains templated `nvvk::make<T>` and `nvvk::clear<T>` functions that are auto-generated by `structs.lua`. The functions provide default structs for the Vulkan C api by initializing the `VkStructureType sType` field (also for nested structs) and clearing the rest to zero. ``` c++ auto compCreateInfo = nvvk::make<VkComputePipelineCreateInfo>; ``` */ #pragma once ]] -- HOW TO USE -- -- 1. Setup environment variable NVVK_VULKAN_XML pointing to vk.xml -- or use VULKAN_SDK >= 1.2.135.0 -- -- 2. Modify the extension subset (allowlist) -- -- 3. Check out this and the other structs_vk files for write access -- -- 4. Run with a lua5.1 compatible lua runtime and the lua2xml project -- https://github.com/manoelcampos/xml2lua -- (shared_internal has all the files). -- -- lua structs_vk.lua -- -- within this directory. local VULKAN_XML = os.getenv("NVVK_VULKAN_XML") or os.getenv("VULKAN_SDK").."/share/vulkan/registry/vk.xml" local extensionSubset = [[ VK_KHR_acceleration_structure VK_KHR_ray_query VK_KHR_ray_tracing_pipeline VK_KHR_push_descriptor VK_KHR_8bit_storage VK_KHR_create_renderpass2 VK_KHR_depth_stencil_resolve VK_KHR_draw_indirect_count VK_KHR_driver_properties VK_KHR_pipeline_executable_properties VK_NV_compute_shader_derivatives VK_NV_cooperative_matrix VK_NV_corner_sampled_image VK_NV_coverage_reduction_mode VK_NV_dedicated_allocation_image_aliasing VK_NV_mesh_shader VK_NV_ray_tracing VK_NV_representative_fragment_test VK_NV_shading_rate_image VK_NV_viewport_array2 VK_NV_viewport_swizzle VK_NV_scissor_exclusive VK_NV_device_generated_commands VK_EXT_buffer_device_address VK_EXT_debug_marker VK_EXT_calibrated_timestamps VK_EXT_conservative_rasterization VK_EXT_descriptor_indexing VK_EXT_depth_clip_enable VK_EXT_memory_budget VK_EXT_memory_priority VK_EXT_pci_bus_info VK_EXT_sample_locations VK_EXT_sampler_filter_minmax VK_EXT_texel_buffer_alignment VK_EXT_debug_utils VK_EXT_host_query_reset VK_KHR_external_memory_win32 VK_KHR_external_semaphore_win32 VK_KHR_external_fence_win32 VK_KHR_external_memory_fd VK_KHR_external_semaphore_fd VK_EXT_validation_features VK_KHR_swapchain ]] local function generate(outfilename, header, whitelist) local override = { VkRayTracingShaderGroupCreateInfoNV = [[ template<> inline VkRayTracingShaderGroupCreateInfoNV make<VkRayTracingShaderGroupCreateInfoNV>(){ VkRayTracingShaderGroupCreateInfoNV ret = {VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_NV}; ret.generalShader = VK_SHADER_UNUSED_NV; ret.closestHitShader = VK_SHADER_UNUSED_NV; ret.anyHitShader = VK_SHADER_UNUSED_NV; ret.intersectionShader = VK_SHADER_UNUSED_NV; return ret; } ]], VkRayTracingShaderGroupCreateInfoKHR = [[ template<> inline VkRayTracingShaderGroupCreateInfoKHR make<VkRayTracingShaderGroupCreateInfoKHR>(){ VkRayTracingShaderGroupCreateInfoKHR ret = {VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR}; ret.generalShader = VK_SHADER_UNUSED_KHR; ret.closestHitShader = VK_SHADER_UNUSED_KHR; ret.anyHitShader = VK_SHADER_UNUSED_KHR; ret.intersectionShader = VK_SHADER_UNUSED_KHR; return ret; } ]], } local function toTab(str) local tab = {} for name in str:gmatch("[%w_]+") do tab[name] = true end return tab end local whitelist = whitelist and toTab(whitelist) local xml2lua = require("xml2lua") local handler = require("xmlhandler.tree") local filename = VULKAN_XML local f = io.open(filename,"rt") assert(f, filename.." not found") local xml = f:read("*a") f:close() -- Bug workaround https://github.com/manoelcampos/xml2lua/issues/35 xml = xml:gsub("(<member>)(<type>[%w_]+</type>)%* ", function(p,typ) -- add _ dummy symbol return "<member>_"..typ.."* " end) local parser = xml2lua.parser(handler) parser:parse(xml) local version = xml:match("VK_HEADER_VERSION</name> (%d+)") assert(version) local structenums = {} local structextensions = {} local function enumID(name) name = name:lower() name = name:gsub("_","") return name end for name in xml:gmatch('"VK_STRUCTURE_TYPE_([%w_]-)"') do structenums[enumID(name)] = "VK_STRUCTURE_TYPE_"..name end xml = nil local types = handler.root.registry.types local commands = handler.root.registry.commands local extensions = handler.root.registry.extensions.extension -- debugging if (false) then local serpent = require "serpent" local f = io.open(filename..".types.lua", "wt") f:write(serpent.block(types)) local f = io.open(filename..".exts.lua", "wt") f:write(serpent.block(extensions)) end -- build list struct types with structure type init local lktypes = {} local lkall = {} local lkcore = {} for _,v in ipairs(types.type) do if (v._attr.category == "struct") then local alias = v._attr.alias local name = v._attr.name if (alias) then lktypes[name] = lktypes[alias] else local members = type(v.member[1]) == "table" and v.member or {v.member} local tab = {name=name, members=members} if (members[1].type == "VkStructureType") then lktypes[name] = tab lkcore[name] = true end lkall[name] = tab end end end local platforms = { ggp = "VK_USE_PLATFORM_GGP", win32 = "VK_USE_PLATFORM_WIN32_KHR", vi = "VK_USE_PLATFORM_VI_NN", ios = "VK_USE_PLATFORM_IOS_MVK", macos = "VK_USE_PLATFORM_MACOS_MVK", android = "VK_USE_PLATFORM_ANDROID_KHR", fuchsia = "VK_USE_PLATFORM_FUCHSIA", metal = "VK_USE_PLATFORM_METAL_EXT", xlib = "VK_USE_PLATFORM_XLIB_KHR", xcb = "VK_USE_PLATFORM_XCB_KHR", wayland = "VK_USE_PLATFORM_WAYLAND_KHR", xlib_xrandr = "VK_USE_PLATFORM_XLIB_XRANDR_EXT", } -- fill extension list local extLists = {} for _,v in ipairs(extensions) do if (v.require) then local reqs = v.require[1] and v.require or {v.require} local list = {} local valid = false for _,r in ipairs(reqs) do if (r.type) then local types = r.type[1] and r.type or {r.type} for _,t in ipairs(types) do local tname = t._attr.name if (lktypes[tname]) then lkcore[tname] = false table.insert(list, tname) valid = true end end end end if (valid and ((whitelist and whitelist[v._attr.name]) or not whitelist)) then table.insert(extLists, {list=list, ext=v._attr.name, platform=platforms[v._attr.platform or "_"] }) end end end -- fill core list local coreList = {} for _,v in ipairs(types.type) do if (v._attr.category == "struct" and lkcore[v._attr.name]) then table.insert(coreList, v._attr.name) end end local out = "" out = out.." template <class T> T make(){ return T(); }\n" out = out.." template <class T> void clear(T& ref){ ref = make<T>(); }\n" local function process(t) local ext = nil for _,sname in ipairs(t.list) do local enum = structenums[enumID(sname:match("Vk(.*)"))] local struct = lktypes[sname] if (enum and struct and not struct.exported) then if ((not ext) and t.ext) then out = out.."#if "..t.ext.."\n" ext = t.ext end local complex = "" local function addComplex(prefix, members) for _,m in ipairs(members) do local mvar = m.name local mtype = m.type local mstruct = lkall[mtype] -- skip pointers if (mstruct and not m[1]) then local mexp = mstruct.exported local mmembers = mstruct.members if (mexp == true) then complex = complex..prefix..mvar.." = make<"..mtype..">();\n" elseif (mexp) then complex = complex..prefix..mvar.." = {"..mexp.."};\n" elseif (mmembers) then addComplex(prefix..mvar..".", mmembers) end end end end addComplex(" ret.", struct.members) if (override[sname]) then out = out..override[sname] print("override", sname) struct.exported = true elseif (complex ~= "") then out = out.." template<> inline "..sname.." make<"..sname..">(){\n "..sname.." ret = {"..enum.."};\n"..complex.." return ret;\n }\n" print("complex", sname) struct.exported = true else out = out.." template<> inline "..sname.." make<"..sname..">(){\n return "..sname.."{"..enum.."};\n }\n" struct.exported = enum end end end if (ext) then out = out.."#endif\n" end end -- process core process({list=coreList}) -- process whitelisted extensions for _,ext in ipairs(extLists) do process(ext) end local outfile = io.open(outfilename, "wt") assert(outfile, "could not open "..outfilename.." for writing") outfile:write("/* based on VK_HEADER_VERSION "..version.." */\n") outfile:write(header) outfile:write("namespace nvvk {\n") outfile:write(out) outfile:write("}\n") outfile:flush() outfile:close() end generate("structs_vk.hpp", header, extensionSubset)
--深海姫プリマドーナ --Scripted by nekrozar function c101012042.initial_effect(c) --synchro summon aux.AddSynchroProcedure(c,nil,aux.NonTuner(nil),1) c:EnableReviveLimit() --to hand local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(101012042,0)) e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH+CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1,101012042) e1:SetTarget(c101012042.thtg) e1:SetOperation(c101012042.thop) c:RegisterEffect(e1) --cannot be target local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e2:SetCode(EVENT_BE_MATERIAL) e2:SetCondition(c101012042.tgcon) e2:SetOperation(c101012042.tgop) c:RegisterEffect(e2) --to deck local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(101012042,1)) e3:SetCategory(CATEGORY_TODECK) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY) e3:SetCode(EVENT_TO_GRAVE) e3:SetCountLimit(1,101012142) e3:SetTarget(c101012042.tdtg) e3:SetOperation(c101012042.tdop) c:RegisterEffect(e3) end function c101012042.thfilter(c,e,tp,ft) return c:IsAttribute(ATTRIBUTE_WATER) and c:IsLevelBelow(4) and (c:IsAbleToHand() or (ft>0 and c:IsCanBeSpecialSummoned(e,0,tp,false,false))) end function c101012042.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) local ft=Duel.GetLocationCount(tp,LOCATION_MZONE) if chkc then return chkc:IsLocation(LOCATION_REMOVED) and chkc:IsControler(1-tp) and chkc:IsAbleToHand() end if chk==0 then return Duel.IsExistingTarget(Card.IsAbleToHand,tp,0,LOCATION_REMOVED,1,nil) and Duel.IsExistingMatchingCard(c101012042.thfilter,tp,LOCATION_DECK,0,1,nil,e,tp,ft) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectTarget(tp,Card.IsAbleToHand,tp,0,LOCATION_REMOVED,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,0,tp,LOCATION_DECK) end function c101012042.thop(e,tp,eg,ep,ev,re,r,rp) local ft=Duel.GetLocationCount(tp,LOCATION_MZONE) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c101012042.thfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp,ft) if g:GetCount()>0 then local sc=g:GetFirst() if sc then local res=0 if ft>0 and sc:IsCanBeSpecialSummoned(e,0,tp,false,false) and (not sc:IsAbleToHand() or Duel.SelectOption(tp,1190,1152)==1) then res=Duel.SpecialSummon(sc,0,tp,tp,false,false,POS_FACEUP) else res=Duel.SendtoHand(sc,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,sc) end local tc=Duel.GetFirstTarget() if res~=0 and tc:IsRelateToEffect(e) then Duel.SendtoHand(tc,nil,REASON_EFFECT) end end end end function c101012042.tgcon(e,tp,eg,ep,ev,re,r,rp) return r==REASON_SYNCHRO end function c101012042.tgop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local rc=c:GetReasonCard() local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(101012042,2)) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CLIENT_HINT) e1:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET) e1:SetValue(c101012042.tgval) e1:SetOwnerPlayer(ep) e1:SetReset(RESET_EVENT+RESETS_STANDARD) rc:RegisterEffect(e1,true) end function c101012042.tgval(e,re,rp) return rp==1-e:GetOwnerPlayer() and re:IsActiveType(TYPE_MONSTER) end function c101012042.tdtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_REMOVED) and chkc:IsAbleToDeck() end if chk==0 then return Duel.IsExistingTarget(Card.IsAbleToDeck,tp,LOCATION_REMOVED,LOCATION_REMOVED,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK) local g=Duel.SelectTarget(tp,Card.IsAbleToDeck,tp,LOCATION_REMOVED,LOCATION_REMOVED,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_TODECK,g,1,0,0) end function c101012042.tdop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SendtoDeck(tc,nil,2,REASON_EFFECT) end end
-- Should be in cl_player_menu.lua but i decided to split the files function FriendsListUI(Online_friends, friends, friends_settings, friends_requests) local ScreenX, ScreenY = GetScreenSize() local dialogPosition = UICSS() dialogPosition.top = math.floor((ScreenY - 325) / 2) .. "px" dialogPosition.left = math.floor((ScreenX - 600) / 2) .. "px !important" dialogPosition.width = "600px" local dialog = UIDialog() dialog.setTitle("Friends Menu") dialog.appendTo(UIFramework) dialog.setCSS(dialogPosition) dialog.onClickClose(function(obj) obj.destroy() LeavePlayerMenuUI() end) local FriendsList = UIOptionList() for i, v in ipairs(friends) do FriendsList.appendOption(i-1, "Friend " .. v.name .. ", SteamId : " .. tostring(v.steamid)) end local selected = nil FriendsList.onChange(function(obj) selected = obj.getValue()[1] + 1 end) FriendsList.appendTo(dialog) local RemoveFromFriendListButton = UIButton() RemoveFromFriendListButton.setTitle("Remove Friend") RemoveFromFriendListButton.onClick(function(obj) if selected then CallRemoteEvent("RemoveFriend", friends[selected].steamid) dialog.destroy() PlayerMenuUI() end end) RemoveFromFriendListButton.appendTo(dialog) local BackButton = UIButton() BackButton.setTitle("Back") BackButton.onClick(function(obj) dialog.destroy() FriendsUI(Online_friends, friends, friends_settings, friends_requests) end) BackButton.appendTo(dialog) end function FriendsOnlineUI(Online_friends, friends, friends_settings, friends_requests) local ScreenX, ScreenY = GetScreenSize() local dialogPosition = UICSS() dialogPosition.top = math.floor((ScreenY - 500) / 2) .. "px" dialogPosition.left = math.floor((ScreenX - 600) / 2) .. "px !important" dialogPosition.width = "600px" local dialog = UIDialog() dialog.setTitle("Friends Menu") dialog.appendTo(UIFramework) dialog.setCSS(dialogPosition) dialog.onClickClose(function(obj) obj.destroy() LeavePlayerMenuUI() end) local comboContainer = UIContainer() comboContainer.setSizes({100,300}) comboContainer.setDirection("horizontal") comboContainer.appendTo(dialog) local FriendsName = UIText() FriendsName.setContent("Name <br> ") FriendsName.appendTo(comboContainer) local FriendsSteamId = UIText() FriendsSteamId.setContent("SteamId <br> ") FriendsSteamId.appendTo(comboContainer) for i, v in ipairs(Online_friends) do FriendsName.setContent(FriendsName.getContent() .. tostring(v.name) .. " <br> ") FriendsSteamId.setContent(FriendsSteamId.getContent() .. tostring(v.steamid) .. " <br> ") end local BackButton = UIButton() BackButton.setTitle("Back") BackButton.onClick(function(obj) dialog.destroy() FriendsUI(Online_friends, friends, friends_settings, friends_requests) end) BackButton.appendTo(dialog) end function FriendsSettingsUI(Online_friends, friends, friends_settings, friends_requests) local ScreenX, ScreenY = GetScreenSize() local dialogPosition = UICSS() dialogPosition.top = math.floor((ScreenY - 325) / 2) .. "px" dialogPosition.left = math.floor((ScreenX - 600) / 2) .. "px !important" dialogPosition.width = "600px" local dialog = UIDialog() dialog.setTitle("Friends Menu") dialog.appendTo(UIFramework) dialog.setCSS(dialogPosition) dialog.onClickClose(function(obj) obj.destroy() LeavePlayerMenuUI() end) for i, v in ipairs(friends_settings) do local nextsetting = v.setting + 1 if nextsetting > table_count(Friend_Settings[v.settingid][2]) then nextsetting = 1 end local SettingText = UIText() SettingText.setContent("Setting : " .. Friend_Settings[v.settingid][1]) SettingText.appendTo(dialog) local SettingStateText = UIText() SettingStateText.setContent("State : " .. Friend_Settings[v.settingid][2][v.setting]) SettingStateText.appendTo(dialog) local ChangeSettingButton = UIButton() ChangeSettingButton.setTitle("Change setting state to : " .. Friend_Settings[v.settingid][2][nextsetting]) ChangeSettingButton.onClick(function(obj) CallRemoteEvent("ChangeFriendSetting", v.settingid, nextsetting) dialog.destroy() PlayerMenuUI() end) ChangeSettingButton.appendTo(dialog) end local BackButton = UIButton() BackButton.setTitle("Back") BackButton.onClick(function(obj) dialog.destroy() FriendsUI(Online_friends, friends, friends_settings, friends_requests) end) BackButton.appendTo(dialog) end function FriendsRequestsUI(Online_friends, friends, friends_settings, friends_requests) local ScreenX, ScreenY = GetScreenSize() local dialogPosition = UICSS() dialogPosition.top = math.floor((ScreenY - 325) / 2) .. "px" dialogPosition.left = math.floor((ScreenX - 600) / 2) .. "px !important" dialogPosition.width = "600px" local dialog = UIDialog() dialog.setTitle("Friends Menu") dialog.appendTo(UIFramework) dialog.setCSS(dialogPosition) dialog.onClickClose(function(obj) obj.destroy() LeavePlayerMenuUI() end) local FriendsRequestsList = UIOptionList() for i, v in ipairs(friends_requests) do FriendsRequestsList.appendOption(i-1, "Name " .. v.name .. ", SteamId : " .. tostring(v.steamid)) end local selected = nil FriendsRequestsList.onChange(function(obj) selected = obj.getValue()[1] + 1 end) FriendsRequestsList.appendTo(dialog) local DenyFriendRequestButton = UIButton() DenyFriendRequestButton.setTitle("Deny Friend Request") DenyFriendRequestButton.onClick(function(obj) if selected then CallRemoteEvent("DenyFriendRequest", friends_requests[selected].steamid) dialog.destroy() PlayerMenuUI() end end) DenyFriendRequestButton.appendTo(dialog) local AcceptFriendRequestButton = UIButton() AcceptFriendRequestButton.setTitle("Accept Friend Request (the other player need to be connected on the player)") AcceptFriendRequestButton.onClick(function(obj) if selected then CallRemoteEvent("AcceptFriendRequest", friends_requests[selected].steamid) dialog.destroy() PlayerMenuUI() end end) AcceptFriendRequestButton.appendTo(dialog) local BackButton = UIButton() BackButton.setTitle("Back") BackButton.onClick(function(obj) dialog.destroy() FriendsUI(Online_friends, friends, friends_settings, friends_requests) end) BackButton.appendTo(dialog) end function FriendsUI(Online_friends, friends, friends_settings, friends_requests) local ScreenX, ScreenY = GetScreenSize() local dialogPosition = UICSS() dialogPosition.top = math.floor((ScreenY - 325) / 2) .. "px" dialogPosition.left = math.floor((ScreenX - 600) / 2) .. "px !important" dialogPosition.width = "600px" local dialog = UIDialog() dialog.setTitle("Friends Menu") dialog.appendTo(UIFramework) dialog.setCSS(dialogPosition) dialog.onClickClose(function(obj) obj.destroy() LeavePlayerMenuUI() end) local friendscount = table_count(friends) local FriendsOnFriendsMax = UIText() FriendsOnFriendsMax.setContent(tostring(friendscount) .. " / " .. tostring(max_friends) .. " friends.") FriendsOnFriendsMax.appendTo(dialog) if friendscount > 0 then local FriendsListButton = UIButton() FriendsListButton.setTitle("Friends List") FriendsListButton.onClick(function(obj) dialog.destroy() FriendsListUI(Online_friends, friends, friends_settings, friends_requests) end) FriendsListButton.appendTo(dialog) if table_count(Online_friends) > 0 then local FriendsOnlineButton = UIButton() FriendsOnlineButton.setTitle("Friends Online") FriendsOnlineButton.onClick(function(obj) dialog.destroy() FriendsOnlineUI(Online_friends, friends, friends_settings, friends_requests) end) FriendsOnlineButton.appendTo(dialog) else local NoOnlineFriendsText = UIText() NoOnlineFriendsText.setContent("No friends are online") NoOnlineFriendsText.appendTo(dialog) end else local NoFriendsText = UIText() NoFriendsText.setContent("No friends, you can add friends by pressing " .. OnlineKeys.ACTION_KEY .. " on them.") NoFriendsText.appendTo(dialog) end local FriendsSettingsButton = UIButton() FriendsSettingsButton.setTitle("Friends Settings") FriendsSettingsButton.onClick(function(obj) dialog.destroy() FriendsSettingsUI(Online_friends, friends, friends_settings, friends_requests) end) FriendsSettingsButton.appendTo(dialog) if table_count(friends_requests) > 0 then if friendscount < max_friends then local FriendsRequestsButton = UIButton() FriendsRequestsButton.setTitle("Friends Requests") FriendsRequestsButton.onClick(function(obj) dialog.destroy() FriendsRequestsUI(Online_friends, friends, friends_settings, friends_requests) end) FriendsRequestsButton.appendTo(dialog) end else local NoFriendsRequestsText = UIText() NoFriendsRequestsText.setContent("No friends requests") NoFriendsRequestsText.appendTo(dialog) end local BackButton = UIButton() BackButton.setTitle("Back") BackButton.onClick(function(obj) dialog.destroy() PlayerMenuUI() end) BackButton.appendTo(dialog) end
--[[ Awesome WM configuration by phantom (Tyler Oalman) --]] -- {{{ Libraries --luacheck: push ignore local awesome, client, mouse, screen, tag = awesome, client, mouse, screen, tag local pairs, ipairs, string, os, table, math, tostring, tonumber, type = pairs, ipairs, string, os, table, math, tostring, tonumber, type -- If LuaRocks is installed, make sure that packages installed through it are -- found (e.g. lgi). If LuaRocks is not installed, do nothing. pcall(require, "luarocks.loader") -- Global (for awesome-client) awful = require("awful") beautiful = require("beautiful") gears = require("gears") gtable = require("gears.table") gdebug = require("gears.debug") naughty = require("naughty") config = require("config") -- yaawl libs (for awesome-client) inspect = require("yaawl.util").inspect json = require("yaawl.util").json -- Local local awful = awful local beautiful = beautiful local gears = gears local naughty = naughty local config = config require("awful.autofocus") require("awful.remote") --luacheck: pop -- }}} -- Localization os.setlocale(os.getenv("LANG")) -- {{{ Initialize context config.context.init { theme = "blackout", keys = { modkey = "Mod4", altkey = "Mod1", ctrlkey = "Control", shiftkey = "Shift", leftkey = "h", rightkey = "l", upkey = "k", downkey = "j", leftkey_alt = "Left", rightkey_alt = "Right", upkey_alt = "Up", downkey_alt = "Down", }, vars = { merge_tags = false, sloppy_focus = false, start_as_slave = false, terminal = "kitty ", browser = "firefox ", net_iface = "wlp3s0", ping_ip = "8.8.8.8", cores = 4, batteries = { "BAT0" }, ac = "AC", checkupdate = "checkupdates | sed 's/->/→/' | sort | column -t -c 70 -T 2,4", -- checkupdate = "checkupdates | sed -E 's/->/→/;s/\\.g[^.-]+-/-/g' | sort | column -t -c 70 -T 2,4", scripts_dir = os.getenv("HOME") .. "/.bin", secrets_dir = os.getenv("HOME") .. "/.secrets", } } -- }}} -- {{{ Error handling if awesome.startup_errors then naughty.notify { preset = naughty.config.presets.critical, title = "Oops, there were errors during startup!", text = awesome.startup_errors, } end do local in_error = false awesome.connect_signal("debug::error", function(err) if in_error then return end in_error = true naughty.notify { preset = naughty.config.presets.critical, title = "Oops, an error happened!", text = tostring(err), } in_error = false end) end -- }}} -- -- {{{ Notifications -- naughty.connect_signal("request::display", function(n) -- naughty.layout.box { -- notification = n, -- } -- end) -- -- }}} -- {{{ Deprecation warnings awesome.connect_signal("debug::deprecation", function(hint, see, args) --luacheck: no unused naughty.notify { preset = naughty.config.presets.warn, title = "Deprecation", text = hint, } end) -- }}} -- {{{ Debug hints awesome.connect_signal("debug::index::miss", function(c, k) --luacheck: no unused naughty.notify { preset = naughty.config.presets.warn, title = "Debug: Index miss", text = c .. "." .. k, } end) awesome.connect_signal("debug::newindex::miss", function(c, k, v) --luacheck: no unused naughty.notify { preset = naughty.config.presets.warn, title = "Debug: New index miss", text = c .. "." .. k .. " = " .. v, } end) -- }}} -- {{{ Auto DPI -- awful.screen.set_auto_dpi_enabled(true) -- }}} -- {{{ Utils config.brokers.init() config.tags.init() config.util.init() config.util_theme.init() -- }}} -- {{{ Bindings config.keys.init() config.bindings_global.init() config.bindings_client.init() config.bindings_command.init() config.bindings_taglist.init() config.bindings_tasklist.init() -- }}} -- {{{ Theme local theme_path = string.format("%s/.config/awesome/themes/%s/theme.lua", os.getenv("HOME"), config.context.theme) beautiful.init(theme_path) -- }}} -- {{{ Parts config.menu.init() config.popups.init() config.sidebar.init() -- }}} -- {{{ Configs config.wallpaper.init() config.rules.init() config.signals.init() config.screens.init() -- }}} -- {{{ Spawn -- awful.spawn { -- config.context.vars.scripts_dir .. "/autolock" -- } -- util.spawn_once { -- command = "kitty --class='kitty-main'", -- class = "kitty-main", -- tag = awful.screen.focused().tags[2], -- callback = function(c) -- c.maximized = true -- end, -- } -- util.spawn_once("subl", "Sublime_text", tags[1][2]) -- util.spawn_once("chromium", "Chromium", tags[1][3]) -- util.spawn_once("thunar", "Thunar", tags[1][4]) -- util.spawn_once("xchat", "Xchat", tags[1][5]) -- util.spawn_once("kitty", "kitty", awful.tag.find_by_name(awful.screen.focused(), "2")) -- }}} -- naughty.dbus.config.mapping = { -- {{urgency = "\1"}, naughty.config.presets.low}, -- {{urgency = "\2"}, naughty.config.presets.normal}, -- {{urgency = "\3"}, naughty.config.presets.critical} -- } -- {{{ Update brokers config.brokers:update() -- }}}
--Paint Program-- if false then color(8) print("Work in progress ....") return end local args = {...} if #args < 1 or args[1] == "-?" then printUsage("paint <filename>", "Creates or edits an existing image.") return end local tar = table.concat(args," ") --The path may include whitespaces if tar:sub(-5,-1) ~= ".lk12" then tar = tar..".lk12" end local term = require("terminal") tar = term.resolve(tar) if fs.exists(tar) and fs.isDirectory(tar) then color(8) print("Can't edit directories !") return end local img, imgdata if not fs.exists(tar) then --Create a new image color(9) print("Input image size:") color(11) print("Width: ",false) color(7) local width = input() if not width or width:len() == 0 then print("") return end local w = tonumber(width) if not w then color(8) print("\nInvalid Width: "..width..", width must be a number !") return end color(11) print(", Height: ",false) color(7) local height = input() if not height or height:len() == 0 then print("") return end local h = tonumber(height) if not h then color(8) print("\nInvalid Height: "..height..", height must be a number !") return end print("") imgdata = imagedata(w,h) img = imgdata:image() else --Load the image local data = fs.read(tar) local ok, err = pcall(image,data) if not ok then color(8) print(err) return end img = err imgdata = img:data() end local eapi = require("Editors") local edit = {} edit.editorsheet = eapi.editorsheet edit.flavor = eapi.flavor edit.flavorBack = eapi.flavorBack edit.background = 0 local swidth, sheight = screenSize() local bgsprite = eapi.editorsheet:extract(59):image() local bgquad = bgsprite:quad(0,0,swidth,sheight-8*2) local sid --Selected option id function edit:drawBottomBar() rect(0,sheight-8,swidth,8,false,self.flavor) end local controlID = 11 local controlNum = 3 --The number of the control buttons at the top right corner of the editor. local controlGrid = {swidth-8*controlNum,0, 8*controlNum,8, controlNum,1} function edit:drawTopBar() palt(0,true) rect(0,0,swidth,8,false,self.flavor) SpriteGroup(55, 0,0, 4,1, 1,1, false, self.editorsheet) --The LIKO12 Logo SpriteGroup(controlID, controlGrid[1],controlGrid[2], controlGrid[5],controlGrid[6], 1,1, false, self.editorsheet) if sid then SpriteGroup(controlID+24+sid, controlGrid[1]+sid*8,controlGrid[2], 1,1, 1,1, false, self.editorsheet) end palt(0,false) end function edit:drawBackground() rect(0,8,swidth,sheight-8*2,false,0) bgsprite:draw(0,8,0,1,1,bgquad) end function edit:drawUI() self:drawBackground() self:drawTopBar() --Draw the top bar self:drawBottomBar() --Draw the bottom bar end local screen = screenshot() local px,py,pc = printCursor() local ok, painteditor = assert(pcall(assert(fs.load("C:/Editors/paint.lua")),edit,img,imgdata)) cursor("normal") painteditor:entered() local eflag = false local hflag = false --hover flag local controls = { function() --Reload painteditor:leaved() if fs.exists(tar) then local data = fs.read(tar) local ok, err = pcall(image,data) if not ok then color(8) print(err) return end img = err imgdata = img:data() painteditor:import(img,imgdata) end painteditor:entered() end, function() --Save local data = painteditor:export() fs.write(tar,data) end, function() --Exit painteditor:leaved() return true end } for event, a,b,c,d,e,f in pullEvent do if event == "keypressed" then if a == "escape" then eflag = not eflag if eflag then cursor("none") sid = 1 else cursor("normal") sid = false end pushMatrix() cam() edit:drawTopBar() popMatrix() elseif eflag then if a == "left" then sid = sid - 1 if sid < 0 then sid = 2 end pushMatrix() cam() edit:drawTopBar() popMatrix() elseif a == "right" then sid = sid + 1 if sid > 2 then sid = 0 end pushMatrix() cam() edit:drawTopBar() popMatrix() elseif a == "return" then if controls[sid+1]() then break end sid, eflag = false, false pushMatrix() cam() edit:drawTopBar() popMatrix() end else local key, sc = a, b if(isKDown("lalt", "ralt")) then key = "alt-" .. key sc = "alt-" .. sc end if(isKDown("lctrl", "rctrl", "capslock")) then key = "ctrl-" .. key sc = "ctrl-" .. sc end if(isKDown("lshift", "rshift")) then key = "shift-" .. key sc = "shift-" .. sc end if painteditor.keymap and painteditor.keymap[key] then painteditor.keymap[key](painteditor,c) elseif painteditor.keymap and painteditor.keymap[sc] then painteditor.keymap[sc](painteditor,c) end if painteditor[event] then painteditor[event](painteditor,a,b,c,d,e,f) end end elseif event == "mousepressed" and not eflag then if painteditor[event] then painteditor[event](painteditor,a,b,c,d,e,f) end local cx, cy = whereInGrid(a,b,controlGrid) if cx then cursor("handpress") hflag = "d" sid = cx-1 pushMatrix() cam() edit:drawTopBar() popMatrix() end elseif event == "mousemoved" and not eflag then if painteditor[event] then painteditor[event](painteditor,a,b,c,d,e,f) end local cx, cy = whereInGrid(a,b,controlGrid) if cx then if hflag and hflag == "h" then cursor("handrelease") end if hflag and hflag == "d" then sid = cx-1 pushMatrix() cam() edit:drawTopBar() popMatrix() elseif not hflag then cursor("handrelease") hflag = "h" end else if hflag and hflag == "h" then hflag = false cursor("normal") end end elseif event == "mousereleased" and not eflag then if painteditor[event] then painteditor[event](painteditor,a,b,c,d,e,f) end local cx, cy = whereInGrid(a,b,controlGrid) if cx then if hflag and hflag == "d" then cursor("handrelease") if controls[sid+1]() then break end sid, hflag = false, false pushMatrix() cam() edit:drawTopBar() popMatrix() elseif not hflag then hflag = "h" cursor("handrelease") end else if hflag then if hflag == "d" then sid = false pushMatrix() cam() edit:drawTopBar() popMatrix() end cursor("normal") hflag = nil end end elseif eflag then if event == "touchpressed" then textinput(true) end else if painteditor[event] then painteditor[event](painteditor,a,b,c,d,e,f) end end end clear() screen:image():draw(0,0) printCursor(px,py,pc)
local fun = require 'fun' local lfs = require 'lfs' local skooma = require 'skooma' local warn = require 'warn.compatible' local yaml = require 'lyaml' local env = setmetatable({}, {__index=function(self, key) return _G[key] or skooma.env[key] end}) local function foreachfile(fn, pattern, dir) for name in lfs.dir(dir) do if not name:find("^%.") then local file = dir .. '/' .. name local attr = lfs.attributes(name) if attr.mode == "directory" then foreachfile(fn, pattern, file) elseif file:find(pattern) then fn(name, file) end end end end local function files(dir, pattern) local pattern = pattern or ".*" return coroutine.wrap(function() foreachfile(coroutine.yield, pattern, dir) end), true, true end local function read_header(path) local file = io.open(path) if file:read()=="/*" then local buffer = {} for line in file:lines() do if line ~= "*/" then table.insert(buffer, line) else local text = table.concat(buffer, '\n'):gsub("\t", " ") local ok, data = pcall(yaml.load, text) if ok then return data else warn(data) end end end end end local css = [[ @import url('core.css'); @import url('box.css'); :root { --box-stripe-color: salmon; background-color: #f4f4f4; padding: 1em 2em; } body :not(:first-child) { margin-top: .4em; } ul.nested { list-style: none; } ul.nested ul.nested { padding: .2em .7em; margin-left: .1em; border-left: .2em solid var(--color); } .nested code { color: var(--color) } .property { --color: #006 } code.property::before { content: '--' } .class { --color: #060 } code.class::before { content: '.' } .element { --color: #600 } code.element::before { content: '' } .attribute { --color: #440 } code.attribute::before { content: '[' } code.attribute::after { content: ']' } ]] local page do local _ENV=env local function stylesheets() return fun.iter(files(".", "%.css$")) end local singular = { attributes = "attribute"; elements="element"; classes="class"; properties = "property"; } local types = {"attributes", "elements", "classes", "properties"} local function definitions(info) return ul(fun.iter(types):map(function(category) local info = info[category] if info then return { class = "nested", fun.iter(info):map(function(item) return { class = singular[category]; p(code{item.name, class=singular[category]}, ' ', item.description); definitions(item); } end) :map(li) :totable() } end end):totable()) end local function stylesheed(path) local data = read_header(path) local name = path:gsub(".-([^/]+)%.css$", "%1") return div( div({class="box"}, h2(name), data.description and h3(data.description), definitions(data) ) ) end local project_title = "DarkWiiPlayer/CSS" page = html(head( style(css), title(project_title) ), body( h1(project_title), stylesheets() :map(stylesheed) :totable() )) end local outfile <close> = io.open("doc.html", "w") for i, line in ipairs(skooma.serialize.html(page)) do outfile:write(line) end
local M = {} local fn = vim.fn local api = vim.api local cmd = vim.cmd local utils = require('hlslens.utils') local config = require('hlslens.config') local winhl = require('hlslens.render.winhl') local extmark = require('hlslens.render.extmark') local floatwin = require('hlslens.render.floatwin') local virt_priority local nearest_only local nearest_float_when local float_shadow_blend local float_virt_id local gutter_size local function init() virt_priority = config.virt_priority nearest_only = config.nearest_only nearest_float_when = config.nearest_float_when float_shadow_blend = config.float_shadow_blend cmd([[ hi default link HlSearchNear IncSearch hi default link HlSearchLens WildMenu hi default link HlSearchLensNear IncSearch hi default link HlSearchFloat IncSearch ]]) if vim.o.termguicolors then local tbl_hi_cmd = {'hi HlSearchFloat', 'blend=0'} for k, v in pairs(utils.hl_attrs('HlSearchFloat')) do table.insert(tbl_hi_cmd, ('%s=%s'):format(k, type(v) == 'table' and table.concat(v, ',') or v)) end cmd(table.concat(tbl_hi_cmd, ' ')) end end local function enough_size4virt(winid, lnum, line_wid, t_len) local end_vcol = utils.vcol(winid, {lnum, '$'}) - 1 local re_vcol if vim.wo[winid].wrap then re_vcol = line_wid - (end_vcol - 1) % line_wid - 1 else re_vcol = math.max(0, line_wid - end_vcol) end return re_vcol > t_len end local function update_floatwin(winid, pos, line_wid, g_size, text) local width, height = api.nvim_win_get_width(winid), api.nvim_win_get_height(winid) local f_col = utils.vcol(winid, pos) % line_wid + g_size - 1 text = vim.trim(text) if vim.o.termguicolors then local f_win, f_buf = floatwin.update(height, 0, width) vim.wo[f_win].winbl = float_shadow_blend local padding = (' '):rep(math.min(f_col, width - #text) - 1) local chunks = {{padding, 'Ignore'}, {text, 'HlSearchFloat'}} float_virt_id = extmark.set_virt_eol(f_buf, 0, chunks, virt_priority, float_virt_id) else local f_win, f_buf = floatwin.update(height, f_col, #text) vim.wo[f_win].winhl = 'Normal:HlSearchFloat' api.nvim_buf_set_lines(f_buf, 0, 1, true, {text}) end end -- Add lens template, can be overrided by `override_lens` -- @param bufnr (number) buffer number -- @param plist (table) (1,1)-indexed position list -- @param nearest (boolean) whether nearest lens -- @param idx (number) nearest index in the plist -- @param r_idx (number) relative index, negative means before current position, positive means after function M.add_lens(bufnr, plist, nearest, idx, r_idx) if type(config.override_lens) == 'function' then -- export render module for hacking :) return config.override_lens(M, plist, nearest, idx, r_idx) end local sfw = vim.v.searchforward == 1 local indicator, text, chunks local abs_r_idx = math.abs(r_idx) if abs_r_idx > 1 then indicator = ('%d%s'):format(abs_r_idx, sfw ~= (r_idx > 1) and 'N' or 'n') elseif abs_r_idx == 1 then indicator = sfw ~= (r_idx == 1) and 'N' or 'n' else indicator = '' end local lnum, col = unpack(plist[idx], 1, 2) if nearest then local cnt = #plist if indicator ~= '' then text = ('[%s %d/%d]'):format(indicator, idx, cnt) else text = ('[%d/%d]'):format(idx, cnt) end chunks = {{' ', 'Ignore'}, {text, 'HlSearchLensNear'}} else text = ('[%s %d]'):format(indicator, idx) chunks = {{' ', 'Ignore'}, {text, 'HlSearchLens'}} end M.set_virt(bufnr, lnum - 1, col - 1, chunks, nearest) end function M.set_virt(bufnr, lnum, col, chunks, nearest) local ex_lnum, ex_col = lnum + 1, col + 1 local text = '' for _, chunk in ipairs(chunks) do text = text .. chunk[1] end if nearest and (nearest_float_when == 'auto' or nearest_float_when == 'always') then local g_size = gutter_size or utils.gutter_size(0) local per_line_wid = api.nvim_win_get_width(0) - g_size if nearest_float_when == 'always' then update_floatwin(0, {ex_lnum, ex_col}, per_line_wid, g_size, text) else if enough_size4virt(0, ex_lnum, per_line_wid, #text) then extmark.set_virt_eol(bufnr, lnum, chunks, virt_priority) floatwin.close() else update_floatwin(0, {ex_lnum, ex_col}, per_line_wid, g_size, text) end end else extmark.set_virt_eol(bufnr, lnum, chunks, virt_priority) end end function M.add_win_hl(winid, start_p, end_p) winhl.add_hl(winid, start_p, end_p, 'HlSearchNear') end function M.do_lens(plist, nearest, idx, r_idx) local pos_len = #plist local idx_lnum = plist[idx][1] local tbl_render = {} if not nearest_only and not nearest then local t0, b0 local p_pos, n_pos = plist[math.max(1, idx - 1)], plist[math.min(pos_len, idx + 1)] -- TODO just relieve foldclosed behavior, can't solve the issue perfectly if vim.wo.foldenable then t0, b0 = math.min(p_pos[1], fn.line('w0')), math.max(n_pos[1], fn.line('w$')) else t0, b0 = p_pos[1], n_pos[1] end local w_hei = api.nvim_win_get_height(0) local top_limit = math.max(0, t0 - w_hei + 1) local bot_limit = math.min(api.nvim_buf_line_count(0), b0 + w_hei - 1) local i_lnum, rel_idx local last_hl_lnum = 0 local top_r_idx = math.min(r_idx, 0) for i = math.max(idx - 1, 0), 1, -1 do i_lnum = plist[i][1] if i_lnum < top_limit then break end if last_hl_lnum == i_lnum then goto continue end last_hl_lnum = i_lnum rel_idx = i - idx + top_r_idx tbl_render[i_lnum] = {i, rel_idx} ::continue:: end last_hl_lnum = idx_lnum local bot_r_idx = math.max(r_idx, 0) local last_i for i = idx + 1, pos_len do last_i = i i_lnum = plist[i][1] if last_hl_lnum == i_lnum then goto continue end last_hl_lnum = i_lnum rel_idx = i - 1 - idx + bot_r_idx tbl_render[plist[i - 1][1]] = {i - 1, rel_idx} if i_lnum > bot_limit then break end ::continue:: end if last_i and i_lnum <= bot_limit then rel_idx = last_i - idx + bot_r_idx tbl_render[i_lnum] = {last_i, rel_idx} end tbl_render[idx_lnum] = nil end local bufnr = api.nvim_get_current_buf() gutter_size = utils.gutter_size(0) extmark.clear_buf(bufnr) M.add_lens(bufnr, plist, true, idx, r_idx) for _, idxs in pairs(tbl_render) do M.add_lens(bufnr, plist, false, idxs[1], idxs[2]) end gutter_size = false end function M.clear(hl, bufnr, floated) if hl then winhl.clear_hl() end if bufnr then extmark.clear_buf(bufnr) end if floated then floatwin.close() end end function M.clear_all() floatwin.close() winhl.clear_hl() extmark.clear_all_buf() end init() return M
#!/usr/bin/env lua -- https://www.lua.org/pil/16.1.html Coords3 = {} function Coords3:new(x, y, z) cx = { x = x, y = y, z = z, } setmetatable(cx, self) self.__index = self return cx end function Coords3:energy() return math.abs(self.x) + math.abs(self.y) + math.abs(self.z) end Moon = {} function Moon:new(x, y, z) m = { position = Coords3:new(x, y, z), velocity = Coords3:new(0, 0, 0), } setmetatable(m, self) self.__index = self return m end function Moon:apply_velocity() -- +=, anyone? self.position.x = self.position.x + self.velocity.x self.position.y = self.position.y + self.velocity.y self.position.z = self.position.z + self.velocity.z end AXES = {"x", "y", "z"} function Moon:apply_gravity(moon) -- ipairs(self) doesn't work here, I don't know why for _, axis in ipairs(AXES) do mine = self.position[axis] theirs = moon.position[axis] if mine < theirs then self.velocity[axis] = self.velocity[axis] + 1 else if mine > theirs then self.velocity[axis] = self.velocity[axis] - 1 end end end end function Moon:potential_energy() return self.position:energy() end function Moon:kinetic_energy() return self.velocity:energy() end function Moon:total_energy() return self:potential_energy() * self:kinetic_energy() end function apply_gravity(moons) for i, moon1 in ipairs(moons) do for j, moon2 in ipairs(moons) do if i ~= j then moon1:apply_gravity(moon2) end end end end function apply_velocity(moons) for _, moon in pairs(moons) do moon:apply_velocity() end end function next_step(moons) apply_gravity(moons) apply_velocity(moons) end function total_energy(moons) local energy = 0 for _, moon in pairs(moons) do energy = energy + moon:total_energy() end return energy end -- Return a string describing the situation of all moons on a given axis function get_situation(moons, axis) local situation = {} for i, moon in ipairs(moons) do situation[i*2 - 1] = moon.position[axis] situation[i*2] = moon.velocity[axis] end return table.concat(situation, "#") end function problem1(moons) local steps = 1000 for _=1, steps do next_step(moons) end print(total_energy(moons)) end function gcd(a, b) while b ~= 0 do local q = a a = b b = q % b end return a end function lcm(a, b) -- https://en.wikipedia.org/wiki/Least_common_multiple#Calculation return math.abs(a*b) / gcd(a, b) end function problem2(moons) --[[ Intuitions: * we can't bruteforce, it'd be too long * axes are independent: what happens on y, z doesn’t affect x, and vice-versa. Of course _all_ axes must go back a previous state. * changes in velocity are a zero-sum game: at any step, the sum of the changes in velocity is zero. * all moons are equal: they all follow the same movement rules, for any position and any velocity, all moons would behave the exact same way. On one axis: * a one-moon situation never changes state * a two-moon situation continuously loop between both original states: moon A goes from init_A to init_B while moon B goes from init_B to init_A, and again and again One thing that would be great but I'm not sure is true is: If any situation goes back to a previous one after some period of time, then this is true for each axis, and the revolution of one axis is at most that period. Each axis has 3 times fewer variables than the situation as a whole so we MAY think one axis' revolution period should be significantly shorter than a 3-axis one. That period may be different for each axis. The solution is then to find the least common multiple of all periods. (spoiler from my future me: this intuition was true) --]] local situations = { x = {}, y = {}, z = {}, } local current_steps = { x = 0, y = 0, z = 0, } local steps = {} while not (steps.x and steps.y and steps.z) do for _, axis in ipairs(AXES) do -- already matched if steps[axis] then goto continue end local situation = get_situation(moons, axis) local situation_steps = situations[axis][situation] if situations[axis][situation] then -- match! steps[axis] = current_steps[axis] - situation_steps -- cleanup to save memory(?) situations[axis] = nil print(axis, situation, current_steps[axis], situation_steps) goto continue end -- otherwise mark the situation as seen situations[axis][situation] = current_steps[axis] current_steps[axis] = current_steps[axis] + 1 ::continue:: end next_step(moons) end print("x", steps.x, "y", steps.y, "z", steps.z) local total_steps = lcm(lcm(steps.x, steps.y), steps.z) print(string.format("%.f", total_steps)) end function main() if #arg ~= 2 then print("I need a problem number (1 or 2) and an input.txt!") os.exit(1) end local moons = {} local f = io.open(arg[2]) for line in f:lines() do x, y, z = string.match(line, "<x=(-?%d+), y=(-?%d+), z=(-?%d+)>") m = Moon:new(tonumber(x), tonumber(y), tonumber(z)) table.insert(moons, m) end f:close() if arg[1] == "1" then problem1(moons) else if arg[1] == "2" then problem2(moons) else print("Invalid problem number!") os.exit(2) end end end main()
local config = require "config" local vector = require "lib.vector" local sensor = require "lib.sensor" local _entity_ = {} ; _entity_.__index = _entity_ function _entity_.create (env, args) -- initialize entity local instance = setmetatable({ position = assert(args.position, 'missing position') }, _entity_) return env.world:create(instance) end function _entity_:update (dt, env) -- update entity end function _entity_:draw (env) -- draw entity end return _entity_
data:extend({ -- Ghost tint { type = "double-setting", name = "blue-ghosts-r", setting_type = "startup", minimum_value = 0, maximum_value = 1, default_value = 0.0, order = "a" }, { type = "double-setting", name = "blue-ghosts-g", setting_type = "startup", minimum_value = 0, maximum_value = 1, default_value = 0.0, order = "b" }, { type = "double-setting", name = "blue-ghosts-b", setting_type = "startup", minimum_value = 0, maximum_value = 1, default_value = 0.8, order = "c" }, { type = "double-setting", name = "blue-ghosts-alpha", setting_type = "startup", minimum_value = 0, maximum_value = 1, default_value = 0.3, order = "d" }, -- Mining Drill Area { type = "double-setting", name = "blue-ghosts-drill-area-r", setting_type = "startup", minimum_value = 0, maximum_value = 1, default_value = 0.0, order = "e" }, { type = "double-setting", name = "blue-ghosts-drill-area-g", setting_type = "startup", minimum_value = 0, maximum_value = 1, default_value = 0.0, order = "f" }, { type = "double-setting", name = "blue-ghosts-drill-area-b", setting_type = "startup", minimum_value = 0, maximum_value = 1, default_value = 0.8, order = "g" }, { type = "double-setting", name = "blue-ghosts-drill-area-alpha", setting_type = "startup", minimum_value = 0, maximum_value = 1, default_value = 0.3, order = "h" }, })
local error_handling = require("gimpy/error_handling") error_handling.handle_awesome_errors() local initialize = require("gimpy/initialize") initialize.initialize() -- vim: ft=lua sts=2 sw=2
AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "shared.lua" ) include( 'shared.lua' ) function ENT:Initialize() self.Entity:SetMoveType( MOVETYPE_NONE ) self.Entity:SetSolid( SOLID_OBB ) self.BuildingSound = CreateSound( self.Entity, "ambient/levels/citadel/portal_beam_loop1.wav" ) self.BuildingSound:Play() self.Entity:SetCollisionGroup( COLLISION_GROUP_BREAKABLE_GLASS ) self.Entity:SetTrigger( true ) self.Entity:SetNotSolid( true ) self.Entity:DrawShadow( false ) self.Entity:Activate() local length = 750 local width = 750 local height = 750 self.Radius = math.sqrt( length^2 + width^2 ) self.LifeSpan = CurTime() + 3.5 local maxref = Vector( length/2, width/2, height/2 ) local minref = Vector( length/-2, width/-2, height/-2 ) self.Entity:SetCollisionBounds( minref, maxref ) end function ENT:Think() -- THIS ONE IS GOOD ParticleEffect("hpw_protego_main", self.Entity:GetPos(), Angle(90, 0, 0)) -- GOES WITH ABOVE ParticleEffect("hpw_protego_impact", self.Entity:GetPos(), Angle(90, 0, 0)) if !self.Owner then self:Remove() return end if !self.Owner:Alive() then self:Remove() return end if self.LifeSpan < CurTime() then self.Entity:Remove() end self.Owner:SetMoveType( MOVETYPE_NONE ) local effectdata = EffectData() effectdata:SetEntity(self.Owner) effectdata:SetRadius( self.Radius ) effectdata:SetMagnitude(5) effectdata:SetScale(20) util.Effect("TeslaHitBoxes", effectdata) local pos = self.Owner:GetPos() + Vector( 0, 0, 25 ) local effect = EffectData() effect:SetStart( pos ) effect:SetOrigin( pos ) effect:SetScale( 100 ) util.Effect("cball_explode", effect, true, true) end function ENT:Touch( ent ) local interval = self.LifeSpan - CurTime() interval = math.Round( ( interval%0.5 )*10 ) if interval > 0 then return end if ent == self:GetOwner() then return end if !ent:IsPlayer() and !ent:IsNPC() and !ent:IsNextBot() then return end local ed = EffectData() ed:SetOrigin( self.Owner:GetActiveWeapon():GetSaberPosAng() ) ed:SetEntity( ent ) util.Effect( "wos_tesla_coil_lightning", ed, true, true ) local dmginfo = DamageInfo() dmginfo:SetAttacker( self.Owner ) dmginfo:SetInflictor( self.Owner:GetActiveWeapon() ) dmginfo:SetDamage( 30 ) dmginfo:SetDamageType( DMG_SHOCK ) ent:TakeDamageInfo( dmginfo ) local chance = math.random( 100 ) if chance < 10 then local effectdata = EffectData() effectdata:SetEntity(ent) effectdata:SetRadius(3) effectdata:SetMagnitude(2) effectdata:SetScale(1) util.Effect("TeslaHitBoxes", effectdata) local n = math.random(11) ent:EmitSound("ambient/energy/newspark"..(n<10 and "0" or "")..n..".wav") end end function ENT:OnRemove() if self.BuildingSound then self.BuildingSound:Stop() self.BuildingSound = nil end if !self.Owner then return end if !self.Owner:Alive() then return end self.Owner:SetSequenceOverride() self.Owner:SetMoveType( MOVETYPE_WALK ) end
function SaveDataToFile(fileName, data) local file = io.open(fileName, "a") file:write(data) file:close() end function err(msg) MsgBox(msg) end function IsFullPath(filePath) local ret = string.match(filePath, "(%a):.*") if ret and ret ~= "" then return true else return false end end function ReadFile(filePath, readMode) -- if not IsFullPath(filePath) then -- filePath = __document.."\\..\\"..filePath -- end -- print("ReadFile filePath: "..tostring(filePath)) local file, err = io.open(filePath,'r') if not file then print("ReadFile error: "..tostring(err)) return nil, err end readMode = readMode or "*all" local data = file:read(readMode) file:close() return data end function WriteFile(filePath, data, openMode) -- if not IsFullPath(filePath) then -- filePath = __document.."\\..\\"..filePath -- end -- print("WriteFile filePath: "..tostring(filePath)) openMode = openMode or "a" local file, err = io.open(filePath, openMode) if not file then print("WriteFile error: "..tostring(err)) return nil, err end file:write(data) file:close() end function MakeTableFromFile(path) local file = io.open(path, "r+"); if not file then print("ReadFile error: "..tostring(err)) return nil, err end local t = {} for line in file:lines() do table.insert(t, line) end return t end local arrFolder = {} function GetNewFileName(path) -- 匹配出jpg所在的文件夹 local fileExtPosBegin, fileExtPosEnd = string.find(path, "(%.%w+)", string.len(path) - 5) if not fileExtPosBegin or not fileExtPosEnd then return end local fileExt = string.sub(path, fileExtPosBegin, fileExtPosEnd) local folderPosBegin, folderPosEnd = string.find(path, "\\") while (folderPosBegin) do if string.find(path, "\\", folderPosBegin + 1) then folderPosEnd = folderPosBegin folderPosBegin = string.find(path, "\\", folderPosBegin + 1) else break end end local folderName = string.sub(path, folderPosEnd+1, folderPosBegin-1) local tmpPath = string.sub(path, 1, folderPosBegin) if not tmpPath then return end if not arrFolder[tmpPath] then arrFolder[tmpPath] = 0 end arrFolder[tmpPath] = arrFolder[tmpPath] + 1 local newName = nil if arrFolder[tmpPath] < 10 then newName = "00"..tostring(arrFolder[tmpPath]) elseif arrFolder[tmpPath] < 100 then newName = "0"..tostring(arrFolder[tmpPath]) else newName = tostring(arrFolder[tmpPath]) end local newFullPath = tmpPath..newName..fileExt return newFullPath, newName end -- local status,_= pcall(os.execute("REN "..folderTable[i].." "..newName.." 2>null"))--重命名 --重命名当前文件夹里的所有子文件夹,不递归 --该方法只适合用于那些有规律的文件夹,如Beay No.201 function RenameCurRegularFolders() local function GetNewFolderNum(name) if not name or "" == name then return end local num = string.match(name, "(No%.%d+)") if not num then num = string.match(name, "%d+") if num then num = "No."..tostring(num) end end return num end os.execute("del /F /Q folder.txt") os.execute("dir /ad/b > folder.txt")--列出当前文件夹下的子文件夹,不递归 local folderTable = MakeTableFromFile("folder.txt") for i=1, #folderTable do local newName = GetNewFolderNum(folderTable[i]) if newName then local status,_= pcall(os.rename(folderTable[i], newName))--重命名 local info = newName .." ==> ".. folderTable[i].."\r\n" WriteFile("rename_info.txt", info) end end -- 删掉folder.txt os.execute("del /F /Q folder.txt") end function FormatIndex(index) local newIndex = nil if index < 10 then newIndex = "00"..tostring(index) elseif index < 100 then newIndex = "0"..tostring(index) else newIndex = tostring(index) end return newIndex end function RenameCurMessyFolders() os.execute("del /F /Q messyfolder.txt") os.execute("dir /ad/b > messyfolder.txt")--列出当前文件夹下的子文件夹,不递归 local folderTable = MakeTableFromFile("messyfolder.txt") local index = 0 for i=1, #folderTable do index = index + 1 local newName = FormatIndex(index) if newName then newName = "No."..newName local status,_= pcall(os.rename(folderTable[i], newName))--重命名 local info = newName .." ==> ".. folderTable[i].."\r\n" WriteFile("rename_info.txt", info) end end os.execute("del /F /Q messyfolder.txt") end --将当前目录下的所有名字不规则的文件(递归),重命名 function RenameAllMessyFiles() --递归列出当前文件夹下的所有文件 os.execute("del /F /Q allfiles.txt") os.execute(" for /r %i in (*.jpg, *.png, *.jpeg, *.gif, *.bmp) do (echo %i >> allfiles.txt)") local fileTable = MakeTableFromFile("allfiles.txt") for i=1, #fileTable do local newFullPath, newName = GetNewFileName(fileTable[i]) if newFullPath then local status,_= pcall(os.rename(fileTable[i], newFullPath))--重命名 end end --删掉allfiles.txt os.execute("del /F /Q allfiles.txt") end function RenameAllRegularFiles() end --[[--]] function CopyFilesOut() local function GetCurFolderPath() local obj=io.popen("cd") --如果不在交互模式下,前面可以添加local local path=obj:read("*all"):sub(1,-2) return path.."\\" end os.execute("del /F /Q folder.txt") os.execute("dir /ad/b > folder.txt")--列出当前文件夹下的子文件夹,不递归 local folderTable = MakeTableFromFile("folder.txt") local curPath = GetCurFolderPath() for i=1, #folderTable do local tarPath = curPath..folderTable[i] os.execute("xcopy /e /r /y "..tarPath.." "..curPath) os.execute(" rd /s /q "..tarPath) end os.execute("del /F /Q folder.txt") end function OnLoadLuaFile(a, b) -- RenameAllMessyFiles() RenameCurMessyFolders() end
-------------------------------- -- @module Helper -------------------------------- -- @function [parent=#Helper] seekWidgetByTag -- @param self -- @param #ccui.Widget widget -- @param #int int -- @return Widget#Widget ret (return value: ccui.Widget) -------------------------------- -- @function [parent=#Helper] seekActionWidgetByActionTag -- @param self -- @param #ccui.Widget widget -- @param #int int -- @return Widget#Widget ret (return value: ccui.Widget) -------------------------------- -- @function [parent=#Helper] seekWidgetByName -- @param self -- @param #ccui.Widget widget -- @param #char char -- @return Widget#Widget ret (return value: ccui.Widget) return nil
local utils = require('metrics.utils') local collectors_list = {} local function update() if not utils.box_is_configured() then return end local vinyl_stat = box.stat.vinyl() collectors_list.vinyl_disk_data_size = utils.set_gauge('vinyl_disk_data_size', 'Amount of data stored in files', vinyl_stat.disk.data) collectors_list.vinyl_disk_index_size = utils.set_gauge('vinyl_disk_index_size', 'Amount of index stored in files', vinyl_stat.disk.index) collectors_list.vinyl_regulator_dump_bandwidth = utils.set_gauge('vinyl_regulator_dump_bandwidth', 'Estimated average rate at which dumps are done', vinyl_stat.regulator.dump_bandwidth) collectors_list.vinyl_regulator_write_rate = utils.set_gauge('vinyl_regulator_write_rate', 'Average rate at which recent writes to disk are done', vinyl_stat.regulator.write_rate) collectors_list.vinyl_regulator_rate_limit = utils.set_gauge('vinyl_regulator_rate_limit', 'Write rate limit', vinyl_stat.regulator.rate_limit) collectors_list.vinyl_regulator_dump_watermark = utils.set_gauge('vinyl_regulator_dump_watermark', 'Point when dumping must occur', vinyl_stat.regulator.dump_watermark) collectors_list.vinyl_tx_conflict = utils.set_gauge('vinyl_tx_conflict', 'Count of transaction conflicts', vinyl_stat.tx.conflict) collectors_list.vinyl_tx_commit = utils.set_gauge('vinyl_tx_commit', 'Count of commits', vinyl_stat.tx.commit) collectors_list.vinyl_tx_rollback = utils.set_gauge('vinyl_tx_rollback', 'Count of rollbacks', vinyl_stat.tx.rollback) collectors_list.vinyl_tx_read_views = utils.set_gauge('vinyl_tx_read_views', 'Count of open read views', vinyl_stat.tx.read_views) collectors_list.vinyl_memory_tuple_cache = utils.set_gauge('vinyl_memory_tuple_cache', 'Number of bytes that are being used for tuple', vinyl_stat.memory.tuple_cache) collectors_list.vinyl_memory_level0 = utils.set_gauge('vinyl_memory_level0', 'Size of in-memory storage of an LSM tree', vinyl_stat.memory.level0) collectors_list.vinyl_memory_page_index = utils.set_gauge('vinyl_memory_page_index', 'Size of page indexes', vinyl_stat.memory.page_index) collectors_list.vinyl_memory_bloom_filter = utils.set_gauge('vinyl_memory_bloom_filter', 'Size of bloom filter', vinyl_stat.memory.bloom_filter) collectors_list.vinyl_scheduler_tasks = utils.set_gauge('vinyl_scheduler_tasks', 'Vinyl tasks count', vinyl_stat.scheduler.tasks_inprogress, {status = 'inprogress'}) collectors_list.vinyl_scheduler_tasks = utils.set_gauge('vinyl_scheduler_tasks', 'Vinyl tasks count', vinyl_stat.scheduler.tasks_completed, {status = 'completed'}) collectors_list.vinyl_scheduler_tasks = utils.set_gauge('vinyl_scheduler_tasks', 'Vinyl tasks count', vinyl_stat.scheduler.tasks_failed, {status = 'failed'}) collectors_list.vinyl_scheduler_dump_time = utils.set_gauge('vinyl_scheduler_dump_time', 'Total time spent by all worker threads performing dump', vinyl_stat.scheduler.dump_time) collectors_list.vinyl_scheduler_dump_count = utils.set_gauge('vinyl_scheduler_dump_count', 'The count of completed dumps', vinyl_stat.scheduler.dump_count) end return { update = update, list = collectors_list, }
-- Copyright (c) 2016 John Schember <john@nachtimwald.com> -- -- 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 os = require("os") local debug = require("debug") local M = {} local M_mt = { __metatable = {}, __index = M } local function timer_start(timer) timer.running = true timer.last = os.clock() end local function timer_stop(timer) timer.running = false timer.time = timer.time + os.clock() - timer.last timer.last = 0 end function M:new() if self ~= M then return nil, "First argument must be self" end local o = setmetatable({}, M_mt) -- Number of times a function has been called o._count = {} -- Time a function takes to run. -- value: { -- running: Function running -- time: Total time function took to run -- last: Last time the function started running -- } o._time = {} -- function name and table of functions it calls. o._calls = {} -- List of parent functions above the current function. o._parent = {} return o end setmetatable(M, { __call = M.new }) function M:start() -- Wrapper function used to pass the object -- into the debug hook function. local function wrapper(e) M.trace(self, e) end debug.sethook(wrapper, "cr") end function M:stop() local info local name debug.sethook() -- Remove the stop call from what we're tracking. info = debug.getinfo(1, "nSlt") name = info.source .. ":" .. info.linedefined .. ":" .. (info.name or "") self._count[name] = nil self._time[name] = nil self._calls[name] = nil self._parent = {} for _,v in ipairs(self._time) do v.running = false v.last = 0 end end function M:trace(e) local info local parent local name e = e:lower() info = debug.getinfo(3, "nSlt") if info.what:lower() ~= "lua" then return end if e ~= "call" and e ~= "tail call" and e ~= "return" then return end -- "call" and "tail call" should have set the call as parent so there -- should always be a parent. If there isn't then we're returning to -- functions that were called before the profiler was started. -- -- This can cause "holes" because there could be a few returns then -- the next call will start recording. if e == "return" and #self._parent == 0 then return end -- We use all data to generate the name because it's valid for function's -- passed as an argument to have the same function name between functions. -- Also multiple files can have the same function names if they're local. -- It's also possible for a function not to have a name. name = info.source .. ":" .. info.linedefined .. ":" .. (info.name or "") if e == "call" or e == "tail call" then -- increment the count self._count[name] = (self._count[name] or 0) + 1 -- If this function has never been seen setup the time table. if not self._time[name] then self._time[name] = { running = false, time = 0, last = 0 } end -- If there is a parent we need to record a bit of info. if #self._parent ~= 0 then parent = self._parent[#self._parent] -- The parent called this function so record that this is -- a call path. if not self._calls[parent] then self._calls[parent] = {} end self._calls[parent][name] = true -- We need to stop the parent's time because we've now gone into -- a different function. We're trying to record the execution time -- of the function not the funciton plus all functions it calls. -- -- It's possible the function is calling itself but we still want -- to stop the timer. We'll start it again later. timer_stop(self._time[parent]) end -- This function is now the parent so if it calls something we know -- what called it, even if it called itself. self._parent[#self._parent+1] = name timer_start(self._time[name]) elseif e == "return" then -- Stop the timer because the function has finished running. timer_stop(self._time[name]) -- Remove the parent from the table because it's this function. table.remove(self._parent, #self._parent) -- Restart the function's parent's timer. if #self._parent ~= 0 then parent = self._parent[#self._parent] timer_start(self._time[parent]) end end end function M:gen_csv() local stats = {} local line local p stats[#stats+1] = "id, file, line, name, count, average time, total time" for k,v in pairs(self._count) do line = {} line[1] = k line[2] = k:gsub(":.*$", "") p = k:gsub("^[^:]*:", "") line[3] = p:gsub(":.*$", "") line[4] = p:gsub("^[^:]*:", "") line[5] = v p = self._time[k] if p ~= nil then line[6] = string.format("%f", p.time/v) line[7] = string.format("%f", p.time) end stats[#stats+1] = table.concat(line, ", ") end return table.concat(stats, "\n") end function M:gen_dot() local dot = {} dot[#dot+1] = "digraph graphname {" for k,v in pairs(self._calls) do for n,_ in pairs(v) do dot[#dot+1] = "\"" .. k .. "\" -> \"" .. n .. "\";" end end dot[#dot+1] = "}" return table.concat(dot, "\n") end function M:gen_total_time() local total = 0 for _,v in pairs(self._time) do total = total + v.time end return total end return M
-- Creating Early Variables. local Player = game.Players.LocalPlayer local Character = Player.Character local PlayerName = Player.Name local Physics = settings().Physics local Head = Character:FindFirstChild("Head") local Torso = Character:FindFirstChild("Torso") local HumanoidRootPart = Character:FindFirstChild("HumanoidRootPart") local Humanoid = Character:FindFirstChild("Humanoid") local LeftArm = Character:FindFirstChild("Left Arm") local LeftLeg = Character:FindFirstChild("Left Leg") local RightArm = Character:FindFirstChild("Right Arm") local RightLeg = Character:FindFirstChild("Right Leg") local Reanimated = true -- R15 Check if Humanoid.RigType == Enum.HumanoidRigType.R15 then game.StarterGui:SetCore("SendNotification",{ Title = "Kom Reanimation", Text = "Reanimation supports only R6.", Duration = 10 }) end if game.Players.LocalPlayer.Character:FindFirstChild("KomReanimation") or workspace:FindFirstChild("KomReanimation") then game.StarterGui:SetCore("ChatMakeSystemMessage", { Text = "[Kom Hub V2] You are already reanimated! Please reset to unreanimate.", Color = Color3.fromRGB(255, 10, 70), TextSize = 18, Font = Enum.Font.Ubuntu }); else Physics.AllowSleep = false Physics.ThrottleAdjustTime = -9e9 Player.ReplicationFocus = workspace Character.Archivable = true -- Checks if player died so it doesnt run again. game:WaitForChild("Run Service").RenderStepped:Connect(function() if Character:FindFirstChild("Humanoid").Health == 0 then Reanimated = false wait(9e9^30) end end) -- Start reanimation game:WaitForChild("Run Service").Heartbeat:Connect(function() if Reanimated == true then if Character.KomReanimation then Character.Torso.CFrame=Character.KomReanimation.Torso.CFrame end sethiddenproperty(game.Players.LocalPlayer, "MaximumSimulationRadius", 1000) sethiddenproperty(game.Players.LocalPlayer, "SimulationRadius", 1000) RightArm.Velocity = Vector3.new(-28.05,1,1) RightLeg.Velocity = Vector3.new(-28.05,1,1) LeftArm.Velocity = Vector3.new(-28.05,1,1) LeftLeg.Velocity = Vector3.new(-28.05,1,1) Torso.Velocity = Vector3.new(12000,12000,12000) HumanoidRootPart.Velocity = Vector3.new(-28.05,1,1) for _, Accessories in pairs(Character:GetDescendants()) do if Accessories:IsA("Accessory") then Accessories.Handle.Velocity = Vector3.new(-28.05,1,1) end end end end) local CopyCharacter = Character:Clone() CopyCharacter.Parent = Character CopyCharacter.Name = "KomReanimation" for k,l in pairs(Character.KomReanimation:GetDescendants()) do if l:IsA("Part") or l:IsA("Decal") then l.Transparency=1 end end Character.Torso["Left Shoulder"]:Destroy() Character.Torso["Right Shoulder"]:Destroy() Character.Torso["Left Hip"]:Destroy() Character.Torso["Right Hip"]:Destroy() HumanoidRootPart.RootJoint:Destroy() -- Using Mizt's align local CountSCIFIMOVIELOL = 1 function AlignCharacter(Part0,Part1,Position,Angle) local AlignPos = Instance.new('AlignPosition', Part1); AlignPos.Name = "AliP_"..CountSCIFIMOVIELOL AlignPos.ApplyAtCenterOfMass = true; AlignPos.MaxForce = 5772000--67752; AlignPos.MaxVelocity = math.huge/9e110; AlignPos.ReactionForceEnabled = false; AlignPos.Responsiveness = 200; AlignPos.RigidityEnabled = false; local AlignOri = Instance.new('AlignOrientation', Part1); AlignOri.Name = "AliO_"..CountSCIFIMOVIELOL AlignOri.MaxAngularVelocity = math.huge/9e110; AlignOri.MaxTorque = 5772000 AlignOri.PrimaryAxisOnly = false; AlignOri.ReactionTorqueEnabled = false; AlignOri.Responsiveness = 200; AlignOri.RigidityEnabled = false; local AttachmentA=Instance.new('Attachment',Part1); AttachmentA.Name = "AthP_"..CountSCIFIMOVIELOL local AttachmentB=Instance.new('Attachment',Part0); AttachmentB.Name = "AthP_"..CountSCIFIMOVIELOL local AttachmentC=Instance.new('Attachment',Part1); AttachmentC.Name = "AthO_"..CountSCIFIMOVIELOL local AttachmentD=Instance.new('Attachment',Part0); AttachmentD.Name = "AthO_"..CountSCIFIMOVIELOL AttachmentC.Orientation = Angle AttachmentA.Position = Position AlignPos.Attachment1 = AttachmentA; AlignPos.Attachment0 = AttachmentB; AlignOri.Attachment1 = AttachmentC; AlignOri.Attachment0 = AttachmentD; CountSCIFIMOVIELOL = CountSCIFIMOVIELOL + 1 end AlignCharacter(Torso,CopyCharacter["Torso"],Vector3.new(0,0,0),Vector3.new(0,0,0)) AlignCharacter(HumanoidRootPart,CopyCharacter["HumanoidRootPart"],Vector3.new(0,0,0),Vector3.new(0,0,0)) AlignCharacter(LeftArm,CopyCharacter["Left Arm"],Vector3.new(0,0,0),Vector3.new(0,0,0)) AlignCharacter(RightArm,CopyCharacter["Right Arm"],Vector3.new(0,0,0),Vector3.new(0,0,0)) AlignCharacter(LeftLeg,CopyCharacter["Left Leg"],Vector3.new(0,0,0),Vector3.new(0,0,0)) AlignCharacter(RightLeg,CopyCharacter["Right Leg"],Vector3.new(0,0,0),Vector3.new(0,0,0)) CopyCharacter:FindFirstChild("HumanoidRootPart").Anchored = false spawn(function() while true do wait() if Character:FindFirstChild("Humanoid").Health == 0 then Character:BreakJoints() CopyCharacter:BreakJoints() end end end) function nocol(t) for k,l in pairs(Character:GetDescendants()) do if l:IsA("BasePart")then HILOL=Instance.new("NoCollisionConstraint",l) HILOL.Part0=l HILOL.Part1=t end end end for k,l in pairs(CopyCharacter:GetDescendants()) do if l:IsA("BasePart")then nocol(l) end end Torso.Anchored = true LeftArm.Anchored = true RightArm.Anchored = true LeftLeg.Anchored = true RightLeg.Anchored = true Head.Anchored = true for k=0,30 do wait() CopyCharacter.HumanoidRootPart.RotVelocity = Vector3.new(0,0,0) CopyCharacter.HumanoidRootPart.Velocity = Vector3.new(0,0,0) end Character.Animate.Disabled = true game:GetService("UserInputService").JumpRequest:connect(function(t) if CopyCharacter.Humanoid.FloorMaterial~=Enum.Material.Air then CopyCharacter.Humanoid:ChangeState(Enum.HumanoidStateType.Jumping) game.Players.LocalPlayer.Character.KomReanimation:FindFirstChildOfClass('Humanoid').Sit=false end end) game.RunService.RenderStepped:Connect(function() CopyCharacter.Humanoid:Move(Character.Humanoid.MoveDirection,false) local animtracks = Humanoid:GetPlayingAnimationTracks() for n,l in pairs(animtracks) do l:Stop() end end) Torso.Anchored = false LeftArm.Anchored = false RightArm.Anchored = false LeftLeg.Anchored = false RightLeg.Anchored = false Head.Anchored = false local something = true while true do if something == true then for n,l in pairs(Character:children()) do pcall(function() if l.className=="Part" then l.CanCollide=false elseif l.ClassName=="Model" then l.Head.CanCollide=false end end) end end game:service("RunService").Stepped:wait() end end
--- -- @author wesen -- @copyright 2020 wesen <wesen-ac@web.de> -- @release 0.1 -- @license MIT -- local BaseInjector = require "ArgumentListWrapper.Injector.BaseInjector" local ValueAtPositionInjector = BaseInjector:extend() ValueAtPositionInjector.appendValues = nil function ValueAtPositionInjector:new(_injectValues, _nilInjectPositions) self.appendValues = _appendValues end function ValueAtPositionInjector:injectValues(_arguments) local numberOfInjectedValues = 0 for position, value in pairs(self.injectValues) do table.insert(_arguments, position, value) end tablex.insertvalues(_arguments, self.appendValues) end return ValueAtPositionInjector
local lpeg = require("lpeg") local R = lpeg.R local S = lpeg.S local P = lpeg.P local C = lpeg.C -- local V = lpeg.V local Cg = lpeg.Cg local Ct = lpeg.Ct local number = {} local digit = R("09") number.integer = (S("+-") ^ -1) * (digit ^ 1) number.fractional = (P(".") ) * (digit ^ 1) number.decimal = (number.integer * -- Integer (number.fractional ^ -1)) + -- Fractional (S("+-")^-1 * number.fractional) -- Completely fractional number number.scientific = number.decimal * -- Decimal number S("Ee") * -- E or e number.integer -- Exponent -- Matches all of the above number.number = C(number.decimal + number.scientific) / function (n) return tonumber(n) end local whitespace = S('\r\n\f\t ')^0 local units = lpeg.Cmt(C(R("az", "%%")^-5), function (_, _, p) for k, _ in pairs(SILE.units) do if p == k then return true end end return false end) local zero = P("0") / function () return 0 end local dimensioned_string = ( C(number.number) * whitespace * C(units) ) / function (_, n, u) return SILE.toMeasurement(n, u) end SILE.parserBits = { number = number, digit = digit, letter = lpeg.R( "az", "AZ" ) + lpeg.P"_", identifier = (R("AZ") + R("az") + P("_") + R("09"))^1, units = units, zero = zero, whitespace = whitespace, dimensioned_string = dimensioned_string, length = Ct(Cg(dimensioned_string + zero, "length") * whitespace * (P("plus") * whitespace * Cg(dimensioned_string + zero, "stretch"))^-1 * whitespace * (P("minus") * whitespace * Cg(dimensioned_string + zero, "shrink"))^-1) }
local dbConn addEventHandler('onResourceStart', resourceRoot, function() dbConn = dbConnect('sqlite', ':/global.db') end) getConn = function() return dbConn end
local rdebug = require 'remotedebug.visitor' local fs = require 'backend.worker.filesystem' local source = require 'backend.worker.source' local evaluate = require 'backend.worker.evaluate' local ev = require 'common.event' local hookmgr = require 'remotedebug.hookmgr' local breakpoints = {} local waitverify = {} local info = {} local m = {} local enable = false local function nextActiveLine(si, line) local defines = si.definelines if line > #defines then return end local actives = si.activelines local fn = defines[line] while actives[line] ~= true do if fn ~= defines[line] then return end line = line + 1 end return line end local function updateHook() if enable then if next(breakpoints) == nil and next(waitverify) == nil then enable = false hookmgr.break_close() end else if next(breakpoints) ~= nil or next(waitverify) ~= nil then enable = true hookmgr.break_open() end end end local function hasActiveBreakpoint(bps, activeline) for line in pairs(bps) do if activeline[line] then return true end end return false end local function updateBreakpoint(key, src, bps) if next(bps) == nil then breakpoints[key] = nil for proto in pairs(src.protos) do hookmgr.break_del(proto) end else breakpoints[key] = bps for proto, activeline in pairs(src.protos) do if hasActiveBreakpoint(bps, activeline) then activeline.bp = true hookmgr.break_add(proto) else activeline.bp = false hookmgr.break_del(proto) end end end updateHook() end local function bpKey(src) if src.sourceReference then return src.sourceReference end return fs.narive_normalize_clientpath(src.path) end local function verifyBreakpoint(src, bps) local key = bpKey(src) local oldBP = breakpoints[key] local hits = {} if oldBP then for _, bp in ipairs(oldBP) do hits[bp.realLine] = bp.statHit end end local res = {} for _, bp in ipairs(bps) do local activeline = nextActiveLine(src.si, bp.line) if activeline then bp.source = src bp.realLine = bp.line bp.line = activeline res[bp.line] = bp bp.statHit = hits[bp.realLine] or 0 if bp.logMessage then local n = 0 bp.statLog = {} bp.statLog[1] = bp.logMessage:gsub('%b{}', function(str) n = n + 1 local key = ('{%d}'):format(n) bp.statLog[key] = str:sub(2,-2) return key end) bp.statLog[1] = bp.statLog[1] .. '\n' end ev.emit('breakpoint', 'changed', { id = bp.id, line = bp.line, message = bp.message, verified = true, }) end end updateBreakpoint(key, src, res) end function m.find(src, currentline) local currentBP = breakpoints[bpKey(src)] if not currentBP then hookmgr.break_closeline() return end return currentBP[currentline] end function m.update(clientsrc, si, bps) if not clientsrc.sourceReference then if not si then return end local src = source.c2s(clientsrc) if src then src.si = si verifyBreakpoint(src, bps) return end for _, bp in ipairs(bps) do bp.source = clientsrc end waitverify[bpKey(clientsrc)] = { bps, si } updateHook() else local src = source.c2s(clientsrc) if src then verifyBreakpoint(src, bps) return end for _, bp in ipairs(bps) do bp.source = clientsrc end waitverify[bpKey(clientsrc)] = { bps, si } updateHook() end end function m.exec(bp) if bp.condition then local ok, res = evaluate.eval(bp.condition) if ok and type(res) == 'boolean' and res == false then return false end end bp.statHit = bp.statHit + 1 if bp.hitCondition then local ok, res = evaluate.eval(bp.statHit .. ' ' .. bp.hitCondition) if ok and type(res) == 'boolean' and res == false then return false end end if bp.statLog then local res = bp.statLog[1]:gsub('{%d+}', function(key) local info = bp.statLog[key] if not info then return key end local ok, r = evaluate.eval(info) if not ok then return info end return tostring(r) end) local s = rdebug.getinfo(1, info) local src = source.create(s.source) if source.valid(src) then ev.emit('output', 'stdout', res, src, s.currentline) else ev.emit('output', 'stdout', res) end return false end return true end local function sourceUpdateBreakpoint(src) local key = bpKey(src) local bpssi = waitverify[key] if bpssi then waitverify[key] = nil if not src.sourceReference then src.si = bpssi[2] end verifyBreakpoint(src, bpssi[1]) return end local bps = breakpoints[key] if bps then updateBreakpoint(key, src, bps) return end end function m.newproto(proto, src, activeline) src.protos[proto] = activeline sourceUpdateBreakpoint(src) return activeline.bp end ev.on('terminated', function() breakpoints = {} waitverify = {} info = {} m = {} enable = false hookmgr.break_close() end) return m
local Config = require("AdituV.DetectTrap.Config"); local Utility = require("AdituV.DetectTrap.Utility"); -- Proxy for tes3.mobileplayer with extended functionality local MobilePlayer = { -- (Float) the additional chance (from 0 to 1) applied to trap detection. -- Intended to be modified by a spell/enchantment, etc. trapDetectionBonus = 0, }; setmetatable(MobilePlayer, MobilePlayer); MobilePlayer.__index = function (self, key) return tes3.mobilePlayer[key]; end function MobilePlayer.getEffectiveSecurityLevel() local security = MobilePlayer.security.current; local intelligence = MobilePlayer.intelligence.current; local luck = MobilePlayer.luck.current; return security + (intelligence / 5) + (luck / 10); end function MobilePlayer.getFatigueTerm() local fFatigueMult = tes3.findGMST(tes3.gmst.fFatigueMult).value; local fFatigueBase = tes3.findGMST(tes3.gmst.fFatigueBase).value; return fFatigueMult*MobilePlayer.fatigue.normalized + fFatigueBase; end function MobilePlayer.getTrapDetectProbability() local effectiveSecurity = MobilePlayer.getEffectiveSecurityLevel(); local fatigueTerm = MobilePlayer.getFatigueTerm(); local effectiveLevel = fatigueTerm * effectiveSecurity; local smoother = Utility.mkLogistic(0,1, Config.trapDifficulty.steepness, Config.trapDifficulty.midpoint); return smoother(effectiveLevel) + MobilePlayer.trapDetectionBonus; end return MobilePlayer;
require("games/common2/match/module/matchLayerBase"); local MatchReviveLayer = class(MatchLayerBase); MatchReviveLayer.parseViewConfig = function(self) local viewConfig = { ["onlooker"] = {}; }; return viewConfig; end -- 初始化layer的配置 MatchReviveLayer.initViewConfig = function(self) self.m_viewConfig = GameMatchConfig.matchRevive; if not self.m_viewConfig then self.m_viewConfig = { [1] = { path = "games/common2/match/module/matchRevive/matchReviveView2"; pos = {}; viewLayer = "view/kScreen_1280_800/games/common2/match/match_revive_layout_2"; viewConfig = "match_revive_layout_2"; }; }; end end return MatchReviveLayer; --[[ 复活提示 监听动作: MatchMechineConfig.ACTION_GET_REVIVE_NOTIFY --收到复活赛通知 ]]
--[[ This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:26' using the latest game version. NOTE: This file should only be used as IDE support; it should NOT be distributed with addons! **************************************************************************** CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC. **************************************************************************** ]] ZO_SmithingExtraction = ZO_SharedSmithingExtraction:Subclass() function ZO_SmithingExtraction:New(...) return ZO_SharedSmithingExtraction.New(self, ...) end function ZO_SmithingExtraction:Initialize(control, owner, isRefinementOnly) local slotContainer = control:GetNamedChild("SlotContainer") self.control = control ZO_SharedSmithingExtraction.Initialize(self, slotContainer:GetNamedChild("ExtractionSlot"), slotContainer:GetNamedChild("ExtractLabel"), owner, isRefinementOnly) self.inventory = ZO_SmithingExtractionInventory:New(self, self.control:GetNamedChild("Inventory"), isRefinementOnly) self:InitExtractionSlot("smithing") if not isRefinementOnly then self.includeBankedItemsCheckbox = self.inventory.control:GetNamedChild("IncludeBanked") self:InitializeFilters() local function OnAddOnLoaded(event, name) if name == "ZO_Ingame" then self:SetupSavedVars() self.control:UnregisterForEvent(EVENT_ADD_ON_LOADED) end end self.control:RegisterForEvent(EVENT_ADD_ON_LOADED, OnAddOnLoaded) end end function ZO_SmithingExtraction:InitializeFilters() local function OnFilterChanged() self:OnFilterChanged(ZO_CheckButton_IsChecked(self.includeBankedItemsCheckbox)) end ZO_CheckButton_SetToggleFunction(self.includeBankedItemsCheckbox, OnFilterChanged) ZO_CheckButton_SetLabelText(self.includeBankedItemsCheckbox, GetString(SI_CRAFTING_INCLUDE_BANKED)) CALLBACK_MANAGER:RegisterCallback("CraftingAnimationsStarted", function() ZO_CheckButton_SetCheckState(self.includeBankedItemsCheckbox, self.savedVars.includeBankedItemsChecked) end) --This needs to happen AFTER the above CraftingAnimationsStarted callback is registered, so the disabled state doesn't get clobbered by setting the check state for the button ZO_CraftingUtils_ConnectCheckBoxToCraftingProcess(self.includeBankedItemsCheckbox) end function ZO_SmithingExtraction:SetupSavedVars() local defaults = { includeBankedItemsChecked = true, } self.savedVars = ZO_SavedVars:New("ZO_Ingame_SavedVariables", 1, "SmithingExtraction", defaults) ZO_CheckButton_SetCheckState(self.includeBankedItemsCheckbox, self.savedVars.includeBankedItemsChecked) end function ZO_SmithingExtraction_IncludeBankedItemsOnMouseEnter(control) InitializeTooltip(InformationTooltip, control, BOTTOM, 0, -10) SetTooltipText(InformationTooltip, GetString(SI_CRAFTING_INCLUDE_BANKED_TOOLTIP)) end function ZO_SmithingExtraction_FilterOnMouseExit(control) ClearTooltip(InformationTooltip) end function ZO_SmithingExtraction:SetCraftingType(craftingType, oldCraftingType, isCraftingTypeDifferent) self:ClearSelections() if isCraftingTypeDifferent then self.inventory:SetActiveFilterByDescriptor(nil) end self.inventory:HandleDirtyEvent() end function ZO_SmithingExtraction:SetHidden(hidden) self.control:SetHidden(hidden) self.inventory:HandleDirtyEvent() end function ZO_SmithingExtraction:OnFilterChanged() ZO_SharedSmithingExtraction.OnFilterChanged(self) local filterType = self:GetFilterType() if filterType then self.extractionSlot:SetEmptyTexture(ZO_CraftingUtils_GetItemSlotTextureFromSmithingFilter(filterType)) end local deconstructionType = self:GetDeconstructionType() if deconstructionType then self.extractionSlot:SetMultipleItemsTexture(ZO_CraftingUtils_GetMultipleItemsTextureFromSmithingDeconstructionType(deconstructionType)) end if not self:IsInRefineMode() then local includeBankedItemsChecked = ZO_CheckButton_IsChecked(self.includeBankedItemsCheckbox) if self.savedVars.includeBankedItemsChecked ~= includeBankedItemsChecked then self.savedVars.includeBankedItemsChecked = includeBankedItemsChecked self.inventory:PerformFullRefresh() end end end ZO_SmithingRefinement = ZO_SmithingExtraction:Subclass() function ZO_SmithingRefinement:New(...) return ZO_SmithingExtraction.New(self, ...) end function ZO_SmithingRefinement:Initialize(control, owner) local REFINEMENT_ONLY = true ZO_SmithingExtraction.Initialize(self, control, owner, REFINEMENT_ONLY) self.multiRefineSpinner = ZO_MultiCraftSpinner:New(control:GetNamedChild("SlotContainerSpinner")) -- connect refine spinner to crafting process local function UpdateMultiRefineSpinner() if not self.control:IsHidden() then self:UpdateMultiRefine() end end CALLBACK_MANAGER:RegisterCallback("CraftingAnimationsStarted", UpdateMultiRefineSpinner) CALLBACK_MANAGER:RegisterCallback("CraftingAnimationsStopped", UpdateMultiRefineSpinner) end function ZO_SmithingRefinement:ConfirmRefine() if self:IsMultiExtract() then self:ConfirmExtractAll() else local iterations = self.multiRefineSpinner:GetValue() self:ExtractPartialStack(iterations * GetRequiredSmithingRefinementStackSize()) end end function ZO_SmithingRefinement:UpdateMultiRefine() local shouldEnableSpinner = true local NO_OVERRIDE = nil if self.extractionSlot:HasOneItem() then local bagId, slotIndex = self.extractionSlot:GetItemBagAndSlot(1) local refineSize = GetRequiredSmithingRefinementStackSize() local maxIterations = zo_min(zo_floor(self.inventory:GetStackCount(bagId, slotIndex) / refineSize), MAX_ITERATIONS_PER_DECONSTRUCTION) self.multiRefineSpinner:SetDisplayTextOverride(NO_OVERRIDE) self.multiRefineSpinner:SetMinMax(1, maxIterations) elseif self.extractionSlot:HasMultipleItems() then self.multiRefineSpinner:SetDisplayTextOverride(GetString(SI_CRAFTING_QUANTITY_ALL)) shouldEnableSpinner = false else self.multiRefineSpinner:SetDisplayTextOverride(NO_OVERRIDE) self.multiRefineSpinner:SetMinMax(0, 0) end if ZO_CraftingUtils_IsPerformingCraftProcess() then shouldEnableSpinner = false end self.multiRefineSpinner:SetEnabled(shouldEnableSpinner) self.multiRefineSpinner:UpdateButtons() end function ZO_SmithingRefinement:SetRefineIterationsToMax() if self.extractionSlot:HasOneItem() then self.multiRefineSpinner:SetValue(self.multiRefineSpinner:GetMax()) end end function ZO_SmithingRefinement:OnSlotChanged() ZO_SmithingExtraction.OnSlotChanged(self) self:UpdateMultiRefine() self:SetRefineIterationsToMax() end function ZO_SmithingRefinement:OnInventoryUpdate(validItems, filterType) ZO_SmithingExtraction.OnInventoryUpdate(self, validItems, filterType) self:UpdateMultiRefine() end ZO_SmithingExtractionInventory = ZO_CraftingInventory:Subclass() function ZO_SmithingExtractionInventory:New(...) return ZO_CraftingInventory.New(self, ...) end function ZO_SmithingExtractionInventory:Initialize(owner, control, isRefinementOnly, ...) ZO_CraftingInventory.Initialize(self, control, ...) self.owner = owner if isRefinementOnly then self:SetFilters{ self:CreateNewTabFilterData(SMITHING_FILTER_TYPE_RAW_MATERIALS, GetString("SI_SMITHINGFILTERTYPE", SMITHING_FILTER_TYPE_RAW_MATERIALS), "EsoUI/Art/Inventory/inventory_tabIcon_crafting_up.dds", "EsoUI/Art/Inventory/inventory_tabIcon_crafting_down.dds", "EsoUI/Art/Inventory/inventory_tabIcon_crafting_over.dds", "EsoUI/Art/Inventory/inventory_tabIcon_crafting_disabled.dds"), } self:SetSortColumnHidden({ statusSortOrder = true, traitInformationSortOrder = true, sellInformationSortOrder = true }, true) self.sortOrder = ZO_SORT_ORDER_UP self.sortKey = "name" else self:SetFilters{ self:CreateNewTabFilterData(SMITHING_FILTER_TYPE_JEWELRY, GetString("SI_SMITHINGFILTERTYPE", SMITHING_FILTER_TYPE_JEWELRY), "EsoUI/Art/Crafting/jewelry_tabIcon_icon_up.dds", "EsoUI/Art/Crafting/jewelry_tabIcon_down.dds", "EsoUI/Art/Crafting/jewelry_tabIcon_icon_over.dds", "EsoUI/Art/Inventory/inventory_tabIcon_jewelry_disabled.dds", CanSmithingJewelryPatternsBeCraftedHere), self:CreateNewTabFilterData(SMITHING_FILTER_TYPE_ARMOR, GetString("SI_SMITHINGFILTERTYPE", SMITHING_FILTER_TYPE_ARMOR), "EsoUI/Art/Inventory/inventory_tabIcon_armor_up.dds", "EsoUI/Art/Inventory/inventory_tabIcon_armor_down.dds", "EsoUI/Art/Inventory/inventory_tabIcon_armor_over.dds", "EsoUI/Art/Inventory/inventory_tabIcon_armor_disabled.dds", CanSmithingApparelPatternsBeCraftedHere), self:CreateNewTabFilterData(SMITHING_FILTER_TYPE_WEAPONS, GetString("SI_SMITHINGFILTERTYPE", SMITHING_FILTER_TYPE_WEAPONS), "EsoUI/Art/Inventory/inventory_tabIcon_weapons_up.dds", "EsoUI/Art/Inventory/inventory_tabIcon_weapons_down.dds", "EsoUI/Art/Inventory/inventory_tabIcon_weapons_over.dds", "EsoUI/Art/Inventory/inventory_tabIcon_weapons_disabled.dds", CanSmithingWeaponPatternsBeCraftedHere), } self:SetSortColumnHidden({ sellInformationSortOrder = true }, true) self.sortOrder = ZO_SORT_ORDER_UP self.sortKey = "traitInformationSortOrder" end self.sortHeaders:SelectHeaderByKey(self.sortKey, ZO_SortHeaderGroup.SUPPRESS_CALLBACKS, not ZO_SortHeaderGroup.FORCE_RESELECT, self.sortOrder) end function ZO_SmithingExtractionInventory:AddListDataTypes() local defaultSetup = self:GetDefaultTemplateSetupFunction() local function RowSetup(rowControl, data) local inventorySlot = rowControl:GetNamedChild("Button") local questPin = rowControl:GetNamedChild("QuestPin") ZO_ItemSlot_SetAlwaysShowStackCount(inventorySlot, false, self.filterType == SMITHING_FILTER_TYPE_RAW_MATERIALS and GetRequiredSmithingRefinementStackSize()) defaultSetup(rowControl, data) if self.filterType == SMITHING_FILTER_TYPE_RAW_MATERIALS then local isQuestItem = self.owner:CanRefineToQuestItem(data.bagId, data.slotIndex) questPin:SetHidden(not isQuestItem) ZO_ItemSlot_SetupUsableAndLockedColor(inventorySlot, data.stackCount >= GetRequiredSmithingRefinementStackSize()) else questPin:SetHidden(true) end end ZO_ScrollList_AddDataType(self.list, self:GetScrollDataType(), "ZO_CraftingInventoryComponentRow", 52, RowSetup, nil, nil, ZO_InventorySlot_OnPoolReset) end function ZO_SmithingExtractionInventory:IsLocked(bagId, slotIndex) return ZO_CraftingInventory.IsLocked(self, bagId, slotIndex) or self.owner:IsSlotted(bagId, slotIndex) or IsItemPlayerLocked(bagId, slotIndex) end function ZO_SmithingExtractionInventory:ChangeFilter(filterData) ZO_CraftingInventory.ChangeFilter(self, filterData) self.filterType = filterData.descriptor self:SetNoItemLabelText(GetString("SI_SMITHINGFILTERTYPE_EXTRACTNONE", self.filterType)) self.owner:OnFilterChanged() self:HandleDirtyEvent() end function ZO_SmithingExtractionInventory:GetCurrentFilterType() return self.filterType end function ZO_SmithingExtractionInventory:Refresh(data) local validItems if self.filterType == SMITHING_FILTER_TYPE_RAW_MATERIALS then validItems = self:EnumerateInventorySlotsAndAddToScrollData(ZO_SharedSmithingExtraction_IsRefinableItem, ZO_SharedSmithingExtraction_DoesItemPassFilter, self.filterType, data) else local DONT_USE_WORN_BAG = false local excludeBanked = not self.owner.savedVars.includeBankedItemsChecked validItems = self:GetIndividualInventorySlotsAndAddToScrollData(ZO_SharedSmithingExtraction_IsExtractableItem, ZO_SharedSmithingExtraction_DoesItemPassFilter, self.filterType, data, DONT_USE_WORN_BAG, excludeBanked) end self.owner:OnInventoryUpdate(validItems, self.filterType) self:SetNoItemLabelHidden(#data > 0) end function ZO_SmithingExtractionInventory:ShowAppropriateSlotDropCallouts(bagId, slotIndex) self.owner:ShowAppropriateSlotDropCallouts() end function ZO_SmithingExtractionInventory:HideAllSlotDropCallouts() self.owner:HideAllSlotDropCallouts() end
--[==[ luawinapi - winapi wrapper for Lua Copyright (C) 2011 Klaus Oberhofer. See copyright notice in LICENSE file Simple test application for luawinapi --]==] winapi = require("luawinapi") -- control IDs ID_EDIT = 1 ID_BUTTON = 2 -- start print("-----------------GetModuleHandleW") hInstance = winapi.GetModuleHandleW(nil) clsname = toUCS2Z("GettingStarted") handlers = { [WM_PAINT] = function(hwnd, wParam, lParam) ps = winapi.PAINTSTRUCT:new() hdc = winapi.BeginPaint(hwnd, ps); pen = winapi.CreatePen(PS_SOLID, 1, RGB(0xFF,0,0)); oldPen = winapi.SelectObject(hdc, pen); winapi.SelectObject(hdc, pen); -- winapi.SelectObject(hdc, winapi.GetStockObject(BLACK_BRUSH)) winapi.MoveToEx(hdc, 0, 0, nil) winapi.LineTo(hdc, 200, 100) winapi.MoveToEx(hdc, 0, 100, nil) winapi.LineTo(hdc, 200, 0) winapi.MoveToEx(hdc, 100, 100, nil) winapi.Ellipse(hdc, 50, 50, 0, 100) winapi.EndPaint(hwnd, ps); return 0; end, [WM_NCHITTEST] = function(hwnd, wParam, lParam) print("WM_NCHITTEST") local hit = winapi.DefWindowProcW(hwnd, WM_NCHITTEST, wParam, lParam); if (hit == HTCLIENT) then hit = HTCAPTION; end return hit end, [WM_CREATE] = function(hwnd, wParam, lParam) local icon = winapi.LoadImageW(NULL, _T("logo.ico"), IMAGE_ICON, 0, 0, LR_LOADFROMFILE) winapi.setIcon(hwnd, ICON_SMALL, icon) winapi.setIcon(hwnd, ICON_LARGE, icon) return 0 end, [WM_DESTROY] = function(hwnd, wParam, lParam) winapi.PostQuitMessage(0) return 0 end } function WndProc(hwnd, msg, wParam, lParam) print(hwnd, MSG_CONSTANTS[msg] or msg, wParam, lParam) local handler = handlers[msg] if (handler) then return handler(hwnd, wParam, lParam) else return winapi.DefWindowProcW(hwnd, msg, wParam, lParam) end end print("-----------------CreateWndProcThunk") WndProc_callback = winapi.WndProc.new(nil, WndProc) wndClass = winapi.WNDCLASSW:new() wndClass.style = CS_HREDRAW + CS_VREDRAW; wndClass.lpfnWndProc = WndProc_callback.entrypoint wndClass.cbClsExtra = 0 wndClass.cbWndExtra = 0 wndClass.hInstance = hInstance wndClass.hIcon = 0 -- winapi.LoadIcon(NULL, IDI_APPLICATION); wndClass.hCursor = winapi.LoadCursorW(NULL, IDC_ARROW); wndClass.hbrBackground = winapi.GetStockObject(WHITE_BRUSH); wndClass.lpszMenuName = 0 wndClass.lpszClassName = clsname print("-----------------RegisterClassW") atom = winapi.RegisterClassW(wndClass); print("-----------------atom", atom) if (not atom) then error(WinError()) end print("---------------CreateMenu-------------------------") --[==[ -- alternative code local hmenu = winapi.CreateMenu(); local hSubMenu = winapi.CreateMenu(); winapi.AppendMenuW(hSubMenu, MF_STRING, 1, _T("Item 1")); winapi.AppendMenuW(hSubMenu, MF_STRING, 1, _T("Item 2")); winapi.AppendMenuW(hSubMenu, MF_STRING, 1, _T("Item 3")); winapi.AppendMenuW(hmenu, MF_POPUP, hSubMenu, _T("TopItem")); --]==] local hmenu = winapi.CreateMenu() local hSubMenu = winapi.CreateMenu() local mii = winapi.MENUITEMINFOW:new() mii.cbSize = #mii mii.fMask = MIIM_ID + MIIM_STRING + MIIM_DATA; mii.fType = MFT_STRING; mii.dwTypeData = _T("Item 1"); winapi.InsertMenuItemW(hSubMenu, winapi.GetMenuItemCount(hSubMenu), TRUE, mii); mii.dwTypeData = _T("Item 2"); winapi.InsertMenuItemW(hSubMenu, winapi.GetMenuItemCount(hSubMenu), TRUE, mii); mii.dwTypeData = _T("Item 3"); winapi.InsertMenuItemW(hSubMenu, winapi.GetMenuItemCount(hSubMenu), TRUE, mii); mii.fMask = MIIM_STRING + MIIM_DATA + MIIM_SUBMENU; mii.fType = MFT_STRING; mii.hSubMenu = hSubMenu; mii.dwTypeData = _T("TopItem"); winapi.InsertMenuItemW(hmenu, winapi.GetMenuItemCount(hmenu), TRUE, mii); print("---------------CreateWindowExW -------------------") hWnd = winapi.CreateWindowExW( 0, clsname, -- window class name toUCS2Z("Getting Started"), -- window caption WS_OVERLAPPEDWINDOW + WS_VISIBLE, -- window style CW_USEDEFAULT, -- initial x position CW_USEDEFAULT, -- initial y position CW_USEDEFAULT, -- initial x size CW_USEDEFAULT, -- initial y size 0, -- parent window handle hmenu, -- window menu handle hInstance, -- program instance handle 0) -- creation parameters hEdit = winapi.CreateWindowExW( 0, toUCS2Z("EDIT"), -- window class name toUCS2Z("Getting Started"), -- window caption WS_VISIBLE + WS_CHILD, -- window style CW_USEDEFAULT, -- initial x position CW_USEDEFAULT, -- initial y position CW_USEDEFAULT, -- initial x size CW_USEDEFAULT, -- initial y size hWnd, -- parent window handle 0, -- window menu handle hInstance, -- program instance handle 0) -- creation parameters hLabel = winapi.CreateWindowExW( 0, toUCS2Z("static"), -- window class name toUCS2Z("Getting Started"), -- window caption WS_VISIBLE + WS_CHILD, -- window style 200, -- initial x position 200, -- initial y position 100, -- initial x size 100, -- initial y size hWnd, -- parent window handle 0, -- window menu handle hInstance, -- program instance handle 0) -- creation parameters hBtn = winapi.CreateWindowExW( 0, toUCS2Z("BUTTON"), -- window class name toUCS2Z("mein button"), -- window caption WS_VISIBLE + WS_CHILD, -- window style 20, -- initial x position 320, -- initial y position 100, -- initial x size 20, -- initial y size hWnd, -- parent window handle 0, -- window menu handle hInstance, -- program instance handle 0) -- creation parameters print("----------- hwnd ", hWnd) if (0 == hWnd) then error(WinError()) end print("---------------ShowWindow -------------------") hWnd:ShowWindow(SW_SHOW) -- alternative: -- winapi.ShowWindow(hWnd, SW_SHOW) print("---------------UpdateWindow -------------------") hWnd:UpdateWindow() print("---------------ProcessMessages -------------------") return winapi.ProcessMessages() -- print("---------------end -------------------") --[[ -- this is possible, too msg = winapi.MSG:new() while (GetMessage(msg.__ptr, NULL, 0, 0)) do TranslateMessage(msg.__ptr); DispatchMessage(msg.__ptr); end return msg.wParam ]]
local inspect = require("inspect") local pp = {} function pp.p(root, options) print(pp.format(root, options)) end function pp.format(root, options) return inspect.inspect(root, options) end function pp.traceback(prefix, offset) print(prefix .. "Traceback") if not offset then offset = 2 end local deep_level = offset while true do local info = debug.getinfo(deep_level, "Sl") if not info then break end print(string.format("%s%d: %s:%d", prefix, deep_level - offset + 1, info.short_src, info.currentline)) deep_level = deep_level + 1 end end return pp
local redis = { protocol = require'redis-client.protocol', response = require'redis-client.response', } describe('redis-client.protocol sending commands', function() it('rejects a missing argument array', function() assert(redis.protocol.send_command(true) == nil) end) it('rejects an empty argument array', function() assert(redis.protocol.send_command(true, {}) == nil) end) it('correctly encodes the argument array', function() local command redis.protocol.send_command({ write = function(self, data) command = data; return true end, flush = function() return true end, }, { 'PING', }) assert.equal(command, '*1\r\n$4\r\nPING\r\n') end) it('captures write errors', function() redis.protocol.send_command({ write = function() return nil, 110 end, flush = function() return nil, 110 end, }, { 'PING', }) end) it('captures flush errors', function() redis.protocol.send_command({ write = function() return true end, flush = function() return nil, 110 end, }, { 'PING', }) end) end) describe('redis-client.protocol reading responses', function() local script = { '+OK\n', '+OK\r\n', '-ERR Error\r\n', ':-1\r\n', ':NotANumber\r\n', '$-1\r\n', '$0\r\n', '\r\n', '$5\r\n', 'Hello\r\n', '$NotANumber\r\n', '$1\r\n', 'Hello\r\n', '$10\r\n', 'Hello\r\n', '*-1\r\n', '*0\r\n', '*NotANumber\r\n', '*1\r\n', '$5\r\n', 'Hello\r\n', '*1\r\n', '$1\r\n', 'Hello\r\n', '#100\r\n', } local file = { read = function(self, format) local line = table.remove(script, 1) if type(format) == 'number' then line = line:sub(1, format) if format ~= #line then line = nil end end return line end } it('rejects malformed responses', function() assert.is_nil(redis.protocol.read_response(file)) end) it('decodes STATUS responses', function() assert.same(redis.protocol.read_response(file), { type = redis.response.STATUS, data = 'OK', }) end) it('decodes ERROR responses', function() assert.same(redis.protocol.read_response(file), { type = redis.response.ERROR, data = 'ERR Error', }) end) it('decodes INT responses', function() assert.same(redis.protocol.read_response(file), { type = redis.response.INT, data = -1, }) end) it('rejects malformed INT responses', function() assert.is_nil(redis.protocol.read_response(file)) end) it('decodes nil STRING responses', function() assert.same(redis.protocol.read_response(file), { type = redis.response.STRING, data = nil, }) end) it('decodes empty STRING responses', function() assert.same(redis.protocol.read_response(file), { type = redis.response.STRING, data = '', }) end) it('decodes STRING responses', function() assert.same(redis.protocol.read_response(file), { type = redis.response.STRING, data = 'Hello', }) end) it('rejects malformed STRING responses', function() assert.is_nil(redis.protocol.read_response(file)) end) it('rejects short STRING responses', function() assert.is_nil(redis.protocol.read_response(file)) end) it('handles EOF during STRING responses', function() assert.is_nil(redis.protocol.read_response(file)) end) it('decodes nil ARRAY responses', function() assert.same(redis.protocol.read_response(file), { type = redis.response.ARRAY, data = nil, }) end) it('decodes empty ARRAY responses', function() assert.same(redis.protocol.read_response(file), { type = redis.response.ARRAY, data = {}, }) end) it('rejects malformed ARRAY responses', function() assert.is_nil(redis.protocol.read_response(file)) end) it('decodes ARRAY responses', function() assert.same(redis.protocol.read_response(file), { type = redis.response.ARRAY, data = { { type = redis.response.STRING, data = 'Hello', } }, }) end) it('rejects malformed ARRAY content', function() assert.is_nil(redis.protocol.read_response(file)) end) it('rejects unknown responses', function() assert.is_nil(redis.protocol.read_response(file)) end) it('handles EOF while waiting for response', function() assert.is_nil(redis.protocol.read_response(file)) end) end)
require 'nn' require 'image' require 'xlua' local DataSet = torch.class 'DataSet' function DataSet:__init(full) local source = '/home/caoqingxing/crawler/cloth_test/female_images/female_formatted_attributes_part_random_index.txt' local impath = {} local attri = {} local sampleCount = 0 local attriCount = -1 -- load image path text file io.input(source) for line in io.lines() do xlua.progress(sampleCount,253983) sampleCount = sampleCount+1 attriCount = -1 attri[sampleCount] = {} for word in string.gmatch(line,'[^\t]+') do attriCount = attriCount+1 if attriCount == 0 then impath[sampleCount] = word else attri[sampleCount][attriCount] = tonumber(word) end end end -- load dataset self.trainData = { data = {}, impath_rootFolder = '/home/caoqingxing/crawler/cloth_test/female_images/', labels = torch.Tensor(attri), imPath = impath, size = function() return sampleCount end } self.indices = torch.randperm(sampleCount) local trainData = self.trainData local indices = self.indices -- Mean Std Normalise if paths.filep('cache/meanfile.t7') then meanStdv = torch.load('cache/meanfile.t7') trainData.mean = meanStdv[1] trainData.std = meanStdv[2] print('Loaded Mean and Std') else print('Normalising') mean = {} -- store the mean, to normalize the test set in the future stdv = {} -- store the standard-deviation for the future data = torch.Tensor(10000, 3, 256, 256) for i = 1,10000 do data[i] = image.load(trainData.impath_rootFolder..trainData.imPath[indices[i]]) end for i=1,3 do -- over each image channel mean[i] = data[{ {}, {i}, {}, {} }]:mean() -- mean estimation stdv[i] = data[{ {}, {i}, {}, {} }]:std() -- std estimation end trainData.mean = mean trainData.std = stdv paths.mkdir('cache') torch.save('cache/meanfile.t7',{mean,stdv}) end collectgarbage() end function DataSet:initLoad() local trainData = self.trainData local indices = self.indices if dataNorm == '01' then setmetatable(trainData.data, {__index = function(self, index) im = image.load(trainData.impath_rootFolder..trainData.imPath[index]) --if torch.max(im) <= 1.5 then im:div(255) end return im end}) else setmetatable(trainData.data, {__index = function(self, index) im = image.load(trainData.impath_rootFolder..trainData.imPath[index]) for channel=1,3 do im[{ {channel}, {}, {} }]:add(-trainData.mean[channel]) im[{ {channel}, {}, {} }]:div(trainData.std[channel]) end return im end}) end end function DataSet:shuffle() self.indices = torch.randperm(self.trainData.size()) end
DefineClass.OverviewMapCurtains = { __parents = { "XDialog" }, curtains_width = -1, curtains_height = -1, ZOrder = -1000, FadeInTime = const.InterfaceAnimDuration, FadeOutTime = const.InterfaceAnimDuration, } function OverviewMapCurtains:Open() XDialog.Open(self) self:SetOverviewCurtains() end function OverviewMapCurtains:Close() XWindow.Close(self) end function OverviewMapCurtains:ForceDelete() --delete the dialog during fade out interpolation local modifier = self:FindModifier("fade") if modifier then modifier.on_complete = function() end end self:delete() end function OverviewMapCurtains:OnDesktopSize() XDialog.OnDesktopSize(self) local pos, lookat = CalcOverviewCameraPos() local width, height = CalcOverviewCurtainsSize(pos, lookat, self.parent.box:sizex(), self.parent.box:sizey()) self:SetOverviewCurtains(Max(width, self.curtains_width), Max(height, self.curtains_height)) self:DeleteThread("OverviewCurtains") if width < self.curtains_width or height < self.curtains_height then self:CreateThread("OverviewCurtains", function(self) WaitNextFrame(2) self:SetOverviewCurtains() end, self) end end function OverviewMapCurtains:SetOverviewCurtains(width, height) local screen_w = self.parent.box:sizex() local screen_h = self.parent.box:sizey() if not width or not height then local pos, lookat = CalcOverviewCameraPos() width, height = CalcOverviewCurtainsSize(pos, lookat, screen_w, screen_h) end local twidth = 80 local sizex = (width+twidth-1)/twidth*twidth + 2*twidth local left = width + twidth - sizex local right = screen_w - width - twidth local top_sizex = (screen_w - left + 2 * twidth) / twidth * twidth if self.idLeft then self.idLeft:SetBox(left, 0, sizex, screen_h) self.idLeft:SetVisible(width > 0, true) end if self.idRight then self.idRight:SetBox(right, 0, sizex, screen_h) self.idRight:SetVisible(width > 0, true) end if self.idTop then self.idTop:SetBox(left, 0, top_sizex, height) self.idTop:SetVisible(height > 0, true) end if self.idBottom then self.idBottom:SetBox(left, screen_h - height, top_sizex, height) self.idBottom:SetVisible(height > 0, true) end self.curtains_width = width self.curtains_height = height end function ShowOverviewMapCurtains(bShow, forceClose) local dlg = GetXDialog("OverviewMapCurtains") if bShow then if not dlg or dlg and dlg.window_state == "closing" then if dlg then dlg:ForceDelete() end OpenXDialog("OverviewMapCurtains") end elseif dlg then if forceClose then dlg:SetFadeOutTime(0) end CloseXDialog("OverviewMapCurtains") end end function HideOverviewMapCurtains(bHide) local dlg = GetXDialog("OverviewMapCurtains") if dlg then dlg:SetVisible(not bHide, "instant") end end
----------------------------------- -- Area: Newton Movalpolos -- NPC: Moblin Showman - Bugbear Matman -- !pos 124.544 19.988 -60.670 12 ----------------------------------- local ID = require("scripts/zones/Newton_Movalpolos/IDs") require("scripts/globals/npc_util") ----------------------------------- function onTrade(player, npc, trade) if npcUtil.tradeHas(trade, 1878) and npcUtil.popFromQM(player, npc, ID.mob.BUGBEAR_MATMAN) then -- Air tank player:showText(npc, ID.text.SHOWMAN_ACCEPT) player:confirmTrade() else player:showText(npc, ID.text.SHOWMAN_DECLINE) end end function onTrigger(player, npc) player:showText(npc, ID.text.SHOWMAN_TRIGGER) end
local completion = {} local conf = require('modules.completion.config') -- Plug 'neovim/nvim-lspconfig' -- opt true completion['neovim/nvim-lspconfig'] = { -- event trigger what? event = 'BufReadPre', config = conf.nvim_lsp, } -- ? -- -- opt true completion['tami5/lspsaga.nvim'] = { -- branch = 'main', -- branch = 'nvim6.0', cmd = 'Lspsaga', } -- -- opt true, but who load it? -- Plug 'hrsh7th/cmp-nvim-lsp' completion['hrsh7th/cmp-nvim-lsp'] = { -- opt = true, } -- Plug 'hrsh7th/cmp-buffer' -- Plug 'hrsh7th/cmp-path' -- Plug 'hrsh7th/cmp-cmdline' -- opt true, but who load it? completion['hrsh7th/cmp-buffer'] = { -- opt = true, } -- opt true, but who load it? completion['hrsh7th/cmp-path'] = { -- opt = true, } -- opt true, but who load it? completion['hrsh7th/cmp-cmdline'] = { -- opt = true, } -- opt true -- Plug 'hrsh7th/nvim-cmp' completion['hrsh7th/nvim-cmp'] = { -- event = 'InsertEnter', --event = 'TextChanged', config = conf.nvim_cmp, } -- completion['hrsh7th/nvim-compe'] = { -- event = 'InsertEnter', -- config = conf.nvim_compe, -- } -- " For vsnip users. -- Plug 'hrsh7th/cmp-vsnip' -- Plug 'hrsh7th/vim-vsnip' -- -- opt true, but who load it? -- start/cmp-vsnip depend cmp completion['hrsh7th/cmp-vsnip'] = { -- opt = true, -- event = 'InsertCharPre', -- config = conf.vim_vsnip } -- opt true completion['hrsh7th/vim-vsnip'] = { -- event = 'InsertCharPre', config = conf.vim_vsnip } -- " For luasnip users. -- " Plug 'L3MON4D3/LuaSnip' -- " Plug 'saadparwaiz1/cmp_luasnip' -- -- " For ultisnips users. -- " Plug 'SirVer/ultisnips' -- " Plug 'quangnguyen30192/cmp-nvim-ultisnips' -- -- " For snippy users. -- " Plug 'dcampos/nvim-snippy' -- " Plug 'dcampos/cmp-snippy' -- opt true -- Adds extra functionality over rust analyzer -- Plug 'simrat39/rust-tools.nvim' completion['simrat39/rust-tools.nvim'] = { --opt = true, -- ft = 'rust', } -- opt true completion['nvim-telescope/telescope.nvim'] = { cmd = 'Telescope', config = conf.telescope, requires = { {'nvim-lua/popup.nvim', opt = true}, {'nvim-lua/plenary.nvim',opt = true}, {'nvim-telescope/telescope-fzy-native.nvim',opt = true}, } } completion['glepnir/smartinput.nvim'] = { ft = 'go', config = conf.smart_input } completion['mattn/vim-sonictemplate'] = { cmd = 'Template', ft = {'go','typescript','lua','javascript','vim','rust','markdown'}, config = conf.vim_sonictemplate, } completion['mattn/emmet-vim'] = { event = 'InsertEnter', ft = {'html','css','javascript','javascriptreact','vue','typescript','typescriptreact'}, config = conf.emmet, } return completion
Apartments = {} Apartments.SpawnOffset = 30 Apartments.Locations = { ["apartment1"] = { name = "apartment1", label = "South Rockford Drive", coords = { enter = vector4(-667.372, -1106.034, 14.629, 65.033), doorbell = vector4(-667.372, -1106.034, 15, 65.033), } }, ["apartment2"] = { name = "apartment2", label = "Morningwood Blvd", coords = { enter = vector4(-1288.046, -430.126, 35.077, 305.348), doorbell = vector4(-1288.046, -430.126, 35.5, 305.348), } }, ["apartment3"] = { name = "apartment3", label = "Integrity Way", coords = { enter = vector4(269.075, -640.672, 42.02, 70.01), doorbell = vector4(269.075, -640.672, 42.5, 70.01), } }, ["apartment4"] = { name = "apartment4", label = "Tinsel Towers", coords = { enter = vector4(-621.016, 46.677, 43.591, 179.36), doorbell = vector4(-621.016, 46.677, 44, 179.36), } }, ["apartment5"] = { name = "apartment5", label = "Fantastic Plaza", coords = { enter = vector4(291.517, -1078.674, 29.405, 270.75), doorbell = vector4(291.517, -1078.674, 29.90, 270.75), } }, }
function onUpdate(elapsed) if boyfriendName == 'bf' then --replace the name for your character name for i=0,4,1 do setPropertyFromGroup('playerStrums', i, 'texture', 'NOTE_assets') end for i = 0, getProperty('unspawnNotes.length')-1 do if getPropertyFromGroup('unspawnNotes', i, 'mustPress') then setPropertyFromGroup('unspawnNotes', i, 'texture', 'GRAVE_assets'); --Change texture end end end end