commit
stringlengths
40
40
old_file
stringlengths
6
181
new_file
stringlengths
6
181
old_contents
stringlengths
448
7.17k
new_contents
stringlengths
449
7.17k
subject
stringlengths
0
450
message
stringlengths
6
4.92k
lang
stringclasses
1 value
license
stringclasses
12 values
repos
stringlengths
9
33.9k
4002346c2a0f9754c485c54452f92939068d7386
lua/include/histogram.lua
lua/include/histogram.lua
local histogram = {} histogram.__index = histogram function histogram.create() local histo = {} setmetatable(histo, histogram) histo.histo = {} histo.dirty = true return histo end function histogram:update(k) self.histo[k] = (self.histo[k] or 0) +1 self.dirty = true end function histogram:calc() self.sortedHisto = {} self.sum = 0 self.numSamples = 0 for k, v in pairs(self.histo) do table.insert(self.sortedHisto, {k = k, v = v}) self.numSamples = self.numSamples + v self.sum = self.sum + k * v end self.avg = self.sum / self.numSamples table.sort(self.sortedHisto, function(e1, e2) return e1.k < e2.k end) local quartSamples = self.numSamples / 4 self.lowerQuart = nil self.median = nil self.upperQuart = nil local idx = 0 for _, p in ipairs(self.sortedHisto) do if not self.lowerQuart and idx >= quartSamples then self.lowerQuart = p.k elseif not self.median and idx >= quartSamples * 2 then self.median = p.k elseif not self.upperQuart and idx >= quartSamples * 3 then self.upperQuart = p.k break end idx = idx + p.v end self.dirty = false end function histogram:totals() if self.dirty then self:calc() end return self.numSamples, self.sum, self.avg end function histogram:quartiles() if self.dirty then self:calc() end return self.lowerQuart, self.median, self.upperQuart end function histogram:samples() local i = 0 if self.dirty then self:calc() end local n = #self.sortedHisto return function() if not self.dirty then i = i + 1 if i <= n then return self.sortedHisto[i] end end end end return histogram
local histogram = {} histogram.__index = histogram function histogram.create() local histo = setmetatable({}, histogram) histo.histo = {} histo.dirty = true return histo end setmetatable(histogram, { __call = histogram.create }) function histogram:update(k) self.histo[k] = (self.histo[k] or 0) +1 self.dirty = true end function histogram:calc() self.sortedHisto = {} self.sum = 0 self.numSamples = 0 for k, v in pairs(self.histo) do table.insert(self.sortedHisto, { k = k, v = v }) self.numSamples = self.numSamples + v self.sum = self.sum + k * v end self.avg = self.sum / self.numSamples local stdDevSum = 0 for k, v in pairs(self.histo) do stdDevSum = stdDevSum + v * (k - self.avg)^2 end self.stdDev = (stdDevSum / (self.numSamples - 1)) ^ 0.5 table.sort(self.sortedHisto, function(e1, e2) return e1.k < e2.k end) -- TODO: this is obviously not entirely correct for numbers not divisible by 4 -- however, it doesn't really matter for the number of samples we usually use local quartSamples = self.numSamples / 4 self.lowerQuart = nil self.median = nil self.upperQuart = nil local idx = 0 for _, p in ipairs(self.sortedHisto) do -- TODO: inefficient for _ = 1, p.v do if not self.lowerQuart and idx >= quartSamples then self.lowerQuart = p.k elseif not self.median and idx >= quartSamples * 2 then self.median = p.k elseif not self.upperQuart and idx >= quartSamples * 3 then self.upperQuart = p.k break end idx = idx + 1 end end self.dirty = false end function histogram:totals() if self.dirty then self:calc() end return self.numSamples, self.sum, self.avg end function histogram:avg() if self.dirty then self:calc() end return self.avg end function histogram:standardDeviation() if self.dirty then self:calc() end return self.stdDev end function histogram:quartiles() if self.dirty then self:calc() end return self.lowerQuart, self.median, self.upperQuart end function histogram:samples() local i = 0 if self.dirty then self:calc() end local n = #self.sortedHisto return function() if not self.dirty then i = i + 1 if i <= n then return self.sortedHisto[i] end end end end return histogram
fix histograms with few bins
fix histograms with few bins
Lua
mit
schoenb/MoonGen,atheurer/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,pavel-odintsov/MoonGen,dschoeffm/MoonGen,NetronomeMoongen/MoonGen,kidaa/MoonGen,wenhuizhang/MoonGen,duk3luk3/MoonGen,atheurer/MoonGen,werpat/MoonGen,emmericp/MoonGen,wenhuizhang/MoonGen,duk3luk3/MoonGen,atheurer/MoonGen,schoenb/MoonGen,dschoeffm/MoonGen,slyon/MoonGen,NetronomeMoongen/MoonGen,bmichalo/MoonGen,gallenmu/MoonGen,kidaa/MoonGen,bmichalo/MoonGen,slyon/MoonGen,pavel-odintsov/MoonGen,kidaa/MoonGen,bmichalo/MoonGen,werpat/MoonGen,scholzd/MoonGen,duk3luk3/MoonGen,gallenmu/MoonGen,slyon/MoonGen,dschoeffm/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,wenhuizhang/MoonGen,schoenb/MoonGen,scholzd/MoonGen,slyon/MoonGen,gallenmu/MoonGen,werpat/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,bmichalo/MoonGen,NetronomeMoongen/MoonGen,pavel-odintsov/MoonGen
73d293c84f8a906ade8d058d8dfad5b0ccca1930
lua/mediaplayer/utils.lua
lua/mediaplayer/utils.lua
if SERVER then AddCSLuaFile() end local file = file local math = math local urllib = url local ceil = math.ceil local floor = math.floor local Round = math.Round local log = math.log local pow = math.pow local format = string.format local tostring = tostring local IsValid = IsValid local utils = {} --- -- Ceil the given number to the largest power of two. -- function utils.CeilPower2(n) return pow(2, ceil(log(n) / log(2))) end --- -- Method for easily grabbing a value from a table without checking that each -- fragment exists. -- -- @param tbl Table -- @param key e.g. "json.key.fragments" -- function utils.TableLookup( tbl, key ) local fragments = string.Split(key, '.') local value = tbl for _, fragment in ipairs(fragments) do value = value[fragment] if not value then return nil end end return value end --- -- Formats the number of seconds to a string. -- e.g. 3612 => 24:12 -- function utils.FormatSeconds(sec) sec = Round(sec) local hours = floor(sec / 3600) local minutes = floor((sec % 3600) / 60) local seconds = sec % 60 if minutes < 10 then minutes = "0" .. tostring(minutes) end if seconds < 10 then seconds = "0" .. tostring(seconds) end if hours > 0 then return format("%s:%s:%s", hours, minutes, seconds) else return format("%s:%s", minutes, seconds) end end -- https://github.com/xfbs/PiL3/blob/master/18MathLibrary/shuffle.lua function utils.Shuffle(list) -- make and fill array of indices local indices = {} for i = 1, #list do indices[#indices+1] = i end -- create shuffled list local shuffled = {} for i = 1, #list do -- get a random index local index = math.random(#indices) -- get the value local value = list[indices[index]] -- remove it from the list so it won't be used again table.remove(indices, index) -- insert into shuffled array shuffled[#shuffled+1] = value end return shuffled end function utils.Retry( func, success, error, maxAttempts ) maxAttempts = maxAttempts or 3 local attempts = 1 local function callback( value ) if value then success( value ) elseif attempts < maxAttempts then attempts = attempts + 1 func( callback ) else error() end end func( callback ) end local function setTimeout( func, wait ) local timerID = tostring( func ) timer.Create( timerID, wait, 1, func ) timer.Start( timerID ) return timerID end local function clearTimeout( timerID ) if timer.Exists( timerID ) then timer.Destroy( timerID ) end end -- based on underscore.js' _.throttle function function utils.Throttle( func, wait, options ) wait = wait or 1 options = options or {} local timeout, args, result local previous local function later() previous = (options.leading == false) and 0 or RealTime() timeout = nil result = func( unpack(args) ) if not timeout then args = nil end end local function throttled(...) local now = RealTime() if not previous then previous = now end local remaining = wait - (now - previous) args = {...} if remaining <= 0 or remaining > wait then if timeout then clearTimeout(timeout) timeout = nil end previous = now result = func( unpack(args) ) if not timeout then args = nil end elseif not timeout and options.trailing ~= false then timeout = setTimeout(later, remaining) end return result end return throttled end if CLIENT then local CeilPower2 = utils.CeilPower2 local SetDrawColor = surface.SetDrawColor local SetMaterial = surface.SetMaterial local DrawTexturedRect = surface.DrawTexturedRect local color_white = color_white function utils.DrawHTMLPanel( panel, w, h ) if not (IsValid( panel ) and w and h) then return end panel:UpdateHTMLTexture() local pw, ph = panel:GetSize() -- Convert to scalar w = w / pw h = h / ph -- Fix for non-power-of-two html panel size pw = CeilPower2(pw) ph = CeilPower2(ph) SetDrawColor( color_white ) SetMaterial( panel:GetHTMLMaterial() ) DrawTexturedRect( 0, 0, w * pw, h * ph ) end function utils.ParseHHMMSS( time ) local tbl = {} -- insert fragments in reverse for fragment, _ in string.gmatch(time, ":?(%d+)") do table.insert(tbl, 1, tonumber(fragment) or 0) end if #tbl == 0 then return nil end local seconds = 0 for i = 1, #tbl do seconds = seconds + tbl[i] * math.max(60 ^ (i-1), 1) end return seconds end --- -- Attempts to play uri from stream or local file and returns channel in -- callback. -- function utils.LoadStreamChannel( uri, options, callback ) local isLocalFile = false -- Play uri from a local file if: -- 1. Windows OS and path contains drive letter -- 2. Linux or OS X and path starts with a single '/' -- -- We can't check this using file.Exists since GMod only allows checking -- within the GMod directory. However, sound.PlayFile will still load -- a file from any directory. if ( system.IsWindows() and uri:find("^%w:/") ) or ( not system.IsWindows() and uri:find("^/[^/]") ) then isLocalFile = true local success, decoded = pcall(urllib.unescape, uri) if success then uri = decoded end end local playFunc = isLocalFile and sound.PlayFile or sound.PlayURL playFunc( uri, options or "noplay", function( channel ) if IsValid( channel ) then callback( channel ) else callback( nil ) end end ) end end _G.MediaPlayerUtils = utils
if SERVER then AddCSLuaFile() end local file = file local math = math local urllib = url local ceil = math.ceil local floor = math.floor local Round = math.Round local log = math.log local pow = math.pow local format = string.format local tostring = tostring local IsValid = IsValid local utils = {} --- -- Ceil the given number to the largest power of two. -- function utils.CeilPower2(n) return pow(2, ceil(log(n) / log(2))) end --- -- Method for easily grabbing a value from a table without checking that each -- fragment exists. -- -- @param tbl Table -- @param key e.g. "json.key.fragments" -- function utils.TableLookup( tbl, key ) local fragments = string.Split(key, '.') local value = tbl for _, fragment in ipairs(fragments) do value = value[fragment] if not value then return nil end end return value end --- -- Formats the number of seconds to a string. -- e.g. 3612 => 24:12 -- function utils.FormatSeconds(sec) sec = Round(sec) local hours = floor(sec / 3600) local minutes = floor((sec % 3600) / 60) local seconds = sec % 60 if minutes < 10 then minutes = "0" .. tostring(minutes) end if seconds < 10 then seconds = "0" .. tostring(seconds) end if hours > 0 then return format("%s:%s:%s", hours, minutes, seconds) else return format("%s:%s", minutes, seconds) end end -- https://github.com/xfbs/PiL3/blob/master/18MathLibrary/shuffle.lua function utils.Shuffle(list) -- make and fill array of indices local indices = {} for i = 1, #list do indices[#indices+1] = i end -- create shuffled list local shuffled = {} for i = 1, #list do -- get a random index local index = math.random(#indices) -- get the value local value = list[indices[index]] -- remove it from the list so it won't be used again table.remove(indices, index) -- insert into shuffled array shuffled[#shuffled+1] = value end return shuffled end function utils.Retry( func, success, error, maxAttempts ) maxAttempts = maxAttempts or 3 local attempts = 1 local function callback( value ) if value then success( value ) elseif attempts < maxAttempts then attempts = attempts + 1 func( callback ) else error() end end func( callback ) end local function setTimeout( func, wait ) local timerID = tostring( func ) timer.Create( timerID, wait, 1, func ) timer.Start( timerID ) return timerID end local function clearTimeout( timerID ) if timer.Exists( timerID ) then timer.Destroy( timerID ) end end -- based on underscore.js' _.throttle function function utils.Throttle( func, wait, options ) wait = wait or 1 options = options or {} local timeout, args, result local previous local function later() previous = (options.leading == false) and 0 or RealTime() timeout = nil result = func( unpack(args) ) if not timeout then args = nil end end local function throttled(...) local now = RealTime() if not previous then previous = now end local remaining = wait - (now - previous) args = {...} if remaining <= 0 or remaining > wait then if timeout then clearTimeout(timeout) timeout = nil end previous = now result = func( unpack(args) ) if not timeout then args = nil end elseif not timeout and options.trailing ~= false then timeout = setTimeout(later, remaining) end return result end return throttled end if CLIENT then local CeilPower2 = utils.CeilPower2 local SetDrawColor = surface.SetDrawColor local SetMaterial = surface.SetMaterial local DrawTexturedRect = surface.DrawTexturedRect local DrawRect = surface.DrawRect local color_white = color_white function utils.DrawHTMLPanel( panel, w, h ) if not (IsValid( panel ) and w and h) then return end panel:UpdateHTMLTexture() local pw, ph = panel:GetSize() -- Convert to scalar w = w / pw h = h / ph -- Fix for non-power-of-two html panel size pw = CeilPower2(pw) ph = CeilPower2(ph) SetDrawColor( color_white ) local mat = panel:GetHTMLMaterial() if mat then SetMaterial( mat ) DrawTexturedRect( 0, 0, w * pw, h * ph ) else DrawRect( 0, 0, w * pw, h * ph ) end end function utils.ParseHHMMSS( time ) local tbl = {} -- insert fragments in reverse for fragment, _ in string.gmatch(time, ":?(%d+)") do table.insert(tbl, 1, tonumber(fragment) or 0) end if #tbl == 0 then return nil end local seconds = 0 for i = 1, #tbl do seconds = seconds + tbl[i] * math.max(60 ^ (i-1), 1) end return seconds end --- -- Attempts to play uri from stream or local file and returns channel in -- callback. -- function utils.LoadStreamChannel( uri, options, callback ) local isLocalFile = false -- Play uri from a local file if: -- 1. Windows OS and path contains drive letter -- 2. Linux or OS X and path starts with a single '/' -- -- We can't check this using file.Exists since GMod only allows checking -- within the GMod directory. However, sound.PlayFile will still load -- a file from any directory. if ( system.IsWindows() and uri:find("^%w:/") ) or ( not system.IsWindows() and uri:find("^/[^/]") ) then isLocalFile = true local success, decoded = pcall(urllib.unescape, uri) if success then uri = decoded end end local playFunc = isLocalFile and sound.PlayFile or sound.PlayURL playFunc( uri, options or "noplay", function( channel ) if IsValid( channel ) then callback( channel ) else callback( nil ) end end ) end end _G.MediaPlayerUtils = utils
Fix DrawHTMLPanel erroring when Chromium material is nil
Fix DrawHTMLPanel erroring when Chromium material is nil
Lua
mit
pixeltailgames/gm-mediaplayer,pixeltailgames/gm-mediaplayer
8ade3ba1aa005badc9178256c113217fe66ff490
src/scanner.lua
src/scanner.lua
--[[ @file scanner.lua @license The MIT License (MIT) @author Alex <alex@maximum.guru> @copyright 2016 Alex --]] --- @module scanner local scanner = {} local config = require("config") local rpc = require("rpc") local threadman = require("threadman") local db = require("db") local network = require("network") local support = require("support") local socket = require("socket") function scanner.processPorts(ip, net, scanId) local module = require("networks."..net.module) local ip, err = network.canonicalizeIp(ip) if err then threadman.notify({type = "error", module = "scanner", error = err}) return end local myip, err = module.getMyIp() if err then threadman.notify({type = "error", module = "scanner", error = "Failed to get own IP: "..err}) return end local myip, err = network.canonicalizeIp(myip) if err then threadman.notify({type = "error", module = "scanner", error = err}) return end -- ignore self if ip == myip then return end ports = {} for port in string.gmatch(config.daemon.scanports, "%d+") do local port = tonumber(port) local proxy = rpc.getProxy(ip, port) local info, err = proxy.nodeInfo() if err then threadman.notify({type = "nodeInfoFailed", ["ip"] = ip, ["port"] = port, ["network"] = net, ["scanId"] = scanId, ["error"] = err}) else if info.name then db.registerNode(info.name, ip, port) threadman.notify({type = "nodeFound", ["ip"] = ip, ["port"] = port, ["network"] = net, ["scanId"] = scanId}) if info.suites then for id, suite in pairs(info.suites) do -- register suites if suite.id then db.registerGateway(info.name, ip, port, suite.id) threadman.notify({type = "gatewayFound", ["ip"] = ip, ["port"] = port, ["suite"] = suite.id, ["network"] = net, ["scanId"] = scanId}) end end end end end end end function scanner.processLinks(ip, net, scanId) local module = require("networks."..net.module) local links, err = module.getLinks(ip) if err then threadman.notify({type = "error", module = "scanner", error = "Failed to links for host: "..err}) return end for k,newIp in pairs(links) do if newIp ~= ip then local result, err = db.addNetworkHost(net.module, newIp, scanId) if err then threadman.notify({type = "error", module = "scanner", error = "Failed to add network host: "..err}) end local result, err = db.addNetworkLink(net.module, ip, newIp, scanId) if err then threadman.notify({type = "error", module = "scanner", error = "Failed to add network link: "..err}) end end end end function scanner.processHost(ip, net, scanId) threadman.notify({type = "info", ["module"] = "scanner", info = "Processing "..ip}) scanner.processLinks(ip, net, scanId) scanner.processPorts(ip, net, scanId) local result, err = db.visitNetworkHost(net.module, ip, scanId) if err then threadman.notify({type = "error", ["module"] = "scanner", error = "Failed to mark host visited: "..err}) end socket.sleep(tonumber(config.daemon.scanDelay)) end function scanner.run() local networks = support.getNetworks() local listener = threadman.registerListener("scanner", {"exit"}) local numhosts = 0 local exit = false; while not exit do numhosts = 0 for netmod,net in pairs(networks) do local msg = ""; while msg ~= nil do msg = listener:listen(true) if msg ~= nil then if msg["type"] == "exit" then exit = true; end end end if exit then break end local scanId, err = db.getLastScanId(netmod) if err then threadman.notify({type = "error", ["module"] = "scanner", error = "Failed to get scan id: "..err}) end if scanId then local host, err = db.getNextNetworkHost(netmod, scanId) if err then threadman.notify({type = "error", ["module"] = "scanner", error = "Failed to get next host: "..err}) break end if host then scanner.processHost(host.ip, net, scanId) numhosts = numhosts + 1 end else -- start scan if none were done scanner.startScan() end end -- sleep if there are no more hosts to scan if numhosts < #networks then socket.sleep(1) end end threadman.unregisterListener(listener) end function scanner.startScan() for netmod,net in pairs(support.getNetworks()) do local module = require("networks."..net.module) local scanId = 1 local lastScanId, err = db.getLastScanId(netmod) if err then threadman.notify({type = "error", ["module"] = "scanner", ["netmod"] = netmod, error = err}) break end local isComplete = true if lastScanId then isComplete, err = db.isScanComplete(netmod, lastScanId) if err then threadman.notify({type = "error", ["module"] = "scanner", ["netmod"] = netmod, error = err}) break end end if isComplete then if lastScanId then scanId = lastScanId + 1 end local myip, err = module.getMyIp() if err then threadman.notify({type = "error", ["module"] = "scanner", ["netmod"] = netmod, ["error"] = "Failed to get own IP: "..err}) break end local result, err = db.addNetworkHost(netmod, myip, scanId) if err then threadman.notify({type = "error", ["module"] = "scanner", ["netmod"] = netmod, ["error"] = "Failed to add host: "..err}) break end end end return true, nil end function scanner.stopScan() for netmod,net in pairs(support.getNetworks()) do local lastScanId, err = db.getLastScanId(netmod) if err then return nil, err end if lastScanId then local isComplete, err = db.isScanComplete(netmod, lastScanId) if err then return nil, err end if not isComplete then -- start another fake scan and complete it so the current scan will be abandoned local result, err = db.addNetworkHost(netmod, "0.0.0.0", lastScanId+1) if err then return nil, err end local result, err = db.visitNetworkHost(netmod, "0.0.0.0", lastScanId+1) if err then return nil, err end local result, err = db.visitAllNetworkHosts(netmod, lastScanId) if err then return nil, err end end end end return true, nil end return scanner
--[[ @file scanner.lua @license The MIT License (MIT) @author Alex <alex@maximum.guru> @copyright 2016 Alex --]] --- @module scanner local scanner = {} local config = require("config") local rpc = require("rpc") local threadman = require("threadman") local db = require("db") local network = require("network") local support = require("support") local socket = require("socket") function scanner.processPorts(ip, net, scanId) local module = require("networks."..net.module) local ip, err = network.canonicalizeIp(ip) if err then threadman.notify({type = "error", module = "scanner", error = err}) return end local myip, err = module.getMyIp() if err then threadman.notify({type = "error", module = "scanner", error = "Failed to get own IP: "..err}) return end local myip, err = network.canonicalizeIp(myip) if err then threadman.notify({type = "error", module = "scanner", error = err}) return end -- ignore self if ip == myip then return end ports = {} for port in string.gmatch(config.daemon.scanports, "%d+") do local port = tonumber(port) local proxy = rpc.getProxy(ip, port) local info, err = proxy.nodeInfo() if err then threadman.notify({type = "nodeInfoFailed", ["ip"] = ip, ["port"] = port, ["network"] = net, ["scanId"] = scanId, ["error"] = err}) else if info.name then db.registerNode(info.name, ip, port) threadman.notify({type = "nodeFound", ["ip"] = ip, ["port"] = port, ["network"] = net, ["scanId"] = scanId}) if info.suites then for id, suite in pairs(info.suites) do -- register suites if suite.id then db.registerGateway(info.name, ip, port, suite.id) threadman.notify({type = "gatewayFound", ["ip"] = ip, ["port"] = port, ["suite"] = suite.id, ["network"] = net, ["scanId"] = scanId}) end end end end end end end function scanner.processLinks(ip, net, scanId) local module = require("networks."..net.module) local links, err = module.getLinks(ip) if err then threadman.notify({type = "error", module = "scanner", error = "Failed to links for host: "..err}) return end for k,newIp in pairs(links) do if newIp ~= ip then local result, err = db.addNetworkHost(net.module, newIp, scanId) if err then threadman.notify({type = "error", module = "scanner", error = "Failed to add network host: "..err}) end local result, err = db.addNetworkLink(net.module, ip, newIp, scanId) if err then threadman.notify({type = "error", module = "scanner", error = "Failed to add network link: "..err}) end end end end function scanner.processHost(ip, net, scanId) threadman.notify({type = "info", ["module"] = "scanner", info = "Processing "..ip}) scanner.processLinks(ip, net, scanId) scanner.processPorts(ip, net, scanId) local result, err = db.visitNetworkHost(net.module, ip, scanId) if err then threadman.notify({type = "error", ["module"] = "scanner", error = "Failed to mark host visited: "..err}) end socket.sleep(tonumber(config.daemon.scanDelay)) end function scanner.run() local listener = threadman.registerListener("scanner", {"exit"}) local exit = false; while not exit do local numhosts = 0 local networks = support.getNetworks() for netmod,net in pairs(networks) do local msg = ""; while msg ~= nil do msg = listener:listen(true) if msg ~= nil then if msg["type"] == "exit" then exit = true; end end end if exit then break end local scanId, err = db.getLastScanId(netmod) if err then threadman.notify({type = "error", ["module"] = "scanner", error = "Failed to get scan id: "..err}) end if scanId then local host, err = db.getNextNetworkHost(netmod, scanId) if err then threadman.notify({type = "error", ["module"] = "scanner", error = "Failed to get next host: "..err}) break end if host then scanner.processHost(host.ip, net, scanId) numhosts = numhosts + 1 end else -- start scan if none were done scanner.startScan() end end -- sleep if there are no more hosts to scan if numhosts == 0 then socket.sleep(1) end end threadman.unregisterListener(listener) end function scanner.startScan() for netmod,net in pairs(support.getNetworks()) do local module = require("networks."..net.module) local scanId = 1 local lastScanId, err = db.getLastScanId(netmod) if err then threadman.notify({type = "error", ["module"] = "scanner", ["netmod"] = netmod, error = err}) break end local isComplete = true if lastScanId then isComplete, err = db.isScanComplete(netmod, lastScanId) if err then threadman.notify({type = "error", ["module"] = "scanner", ["netmod"] = netmod, error = err}) break end end if isComplete then if lastScanId then scanId = lastScanId + 1 end local myip, err = module.getMyIp() if err then threadman.notify({type = "error", ["module"] = "scanner", ["netmod"] = netmod, ["error"] = "Failed to get own IP: "..err}) break end local result, err = db.addNetworkHost(netmod, myip, scanId) if err then threadman.notify({type = "error", ["module"] = "scanner", ["netmod"] = netmod, ["error"] = "Failed to add host: "..err}) break end end end return true, nil end function scanner.stopScan() for netmod,net in pairs(support.getNetworks()) do local lastScanId, err = db.getLastScanId(netmod) if err then return nil, err end if lastScanId then local isComplete, err = db.isScanComplete(netmod, lastScanId) if err then return nil, err end if not isComplete then -- start another fake scan and complete it so the current scan will be abandoned local result, err = db.addNetworkHost(netmod, "0.0.0.0", lastScanId+1) if err then return nil, err end local result, err = db.visitNetworkHost(netmod, "0.0.0.0", lastScanId+1) if err then return nil, err end local result, err = db.visitAllNetworkHosts(netmod, lastScanId) if err then return nil, err end end end end return true, nil end return scanner
Bug fix
Bug fix
Lua
mit
pdxmeshnet/mnigs,transitd/transitd,transitd/transitd,intermesh-networks/transitd,pdxmeshnet/mnigs,intermesh-networks/transitd,transitd/transitd
6a1102f026998871500157ddef3b003434aab91d
BCECriterion.lua
BCECriterion.lua
local BCECriterion, parent = torch.class('nn.BCECriterion', 'nn.Criterion') function BCECriterion:__init() parent.__init(self) self.sizeAverage = true end function BCECriterion:updateOutput(input, target) -- log(input) * target + log(1 - input) * (1 - target) self.term1 = self.term1 or input.new() self.term2 = self.term2 or input.new() self.term3 = self.term3 or input.new() self.term1:resizeAs(input) self.term2:resizeAs(input) self.term3:resizeAs(input) self.term1:fill(1):add(-1,target) self.term2:fill(1):add(-1,input):log():cmul(self.term1) self.term3:copy(input):log():cmul(target) self.term3:add(self.term2) if self.sizeAverage then self.term3:div(target:size(1)) end return self.term3:sum() end function BCECriterion:updateGradInput(input, target) -- target / input - (1 - target) / (1 - input) self.term1 = self.term1 or input.new() self.term2 = self.term2 or input.new() self.term1:resizeAs(input) self.term2:resizeAs(input) self.term1:fill(1):add(-1,target) self.term2:fill(1):add(-1,input) self.term1:cdiv(self.term2) self.gradInput:resizeAs(input) self.gradInput:copy(target):cdiv(input) self.gradInput:add(-1,self.term1) if self.sizeAverage then self.gradInput:div(target:size(1)) end return self.gradInput end
local BCECriterion, parent = torch.class('nn.BCECriterion', 'nn.Criterion') local eps = 1e-12 function BCECriterion:__init() parent.__init(self) self.sizeAverage = true end function BCECriterion:updateOutput(input, target) -- log(input) * target + log(1 - input) * (1 - target) self.term1 = self.term1 or input.new() self.term2 = self.term2 or input.new() self.term3 = self.term3 or input.new() self.term1:resizeAs(input) self.term2:resizeAs(input) self.term3:resizeAs(input) self.term1:fill(1):add(-1,target) self.term2:fill(1):add(-1,input):add(eps):log():cmul(self.term1) self.term3:copy(input):add(eps):log():cmul(target) self.term3:add(self.term2) if self.sizeAverage then self.term3:div(target:nElement()) end self.output = - self.term3:sum() return self.output end function BCECriterion:updateGradInput(input, target) -- target / input - (1 - target) / (1 - input) self.term1 = self.term1 or input.new() self.term2 = self.term2 or input.new() self.term3 = self.term3 or input.new() self.term1:resizeAs(input) self.term2:resizeAs(input) self.term3:resizeAs(input) self.term1:fill(1):add(-1,target) self.term2:fill(1):add(-1,input) self.term2:add(eps) self.term1:cdiv(self.term2) self.term3:copy(input):add(eps) self.gradInput:resizeAs(input) self.gradInput:copy(target):cdiv(self.term3) self.gradInput:add(-1,self.term1) if self.sizeAverage then self.gradInput:div(target:nElement()) end self.gradInput:mul(-1) return self.gradInput end
BCECriterion was incorrect.
BCECriterion was incorrect. Fixed: * forward/backward: inverted sign to produce neg ll (not pos) * averaging over all elements in target, to properly support batches * added epsilon to protect against 0s (divs and logs)
Lua
bsd-3-clause
zhangxiangxiao/nn,eriche2016/nn,zchengquan/nn,PierrotLC/nn,andreaskoepf/nn,Jeffyrao/nn,Aysegul/nn,nicholas-leonard/nn,karpathy/nn,mys007/nn,bartvm/nn,ivendrov/nn,Djabbz/nn,colesbury/nn,apaszke/nn,douwekiela/nn,GregSatre/nn,joeyhng/nn,kmul00/nn,sagarwaghmare69/nn,diz-vara/nn,boknilev/nn,szagoruyko/nn,mlosch/nn,aaiijmrtt/nn,lukasc-ch/nn,hery/nn,PraveerSINGH/nn,jhjin/nn,xianjiec/nn,forty-2/nn,abeschneider/nn,clementfarabet/nn,rotmanmi/nn,jonathantompson/nn,hughperkins/nn,ominux/nn,lvdmaaten/nn,soumith/nn,elbamos/nn,jzbontar/nn,noa/nn,rickyHong/nn_lib_torch,fmassa/nn,Moodstocks/nn,EnjoyHacking/nn,davidBelanger/nn,LinusU/nn,sbodenstein/nn,caldweln/nn,witgo/nn,vgire/nn,adamlerer/nn,eulerreich/nn
9ec0708bc3eae36ff361bda1290b56fb141dabe5
roles/neovim/config/lua/irubataru/options.lua
roles/neovim/config/lua/irubataru/options.lua
local opt = vim.opt -- Treat both system clipboards as the same opt.clipboard = "unnamedplus" opt.backupdir = vim.fn.expand "~/.tmp" -- Start diff-mode in vertical split, ignore all whitespace opt.diffopt = "filler,vertical,iwhiteall" --Command line file completion opt.wildmode = "longest,list,full" -- bash-like filename autocompletion opt.wildmenu = true -- zsh-like filename list chooser -- Use treesitter to fold opt.foldmethod = "expr" opt.foldexpr = "nvim_treesitter#foldexpr()" -- Make it so I can switch buffers even if they have changed opt.hidden = true -- Highlight the current cursorline opt.cursorline = true -- Timeoutlen is used for e.g. the which-key plugin (default value 1000 ms) opt.timeoutlen = 500 -- Splits should be to the right and below opt.splitbelow = true opt.splitright = true -- Remove line numbering in new terminals vim.cmd [[autocmd TermOpen term://* set nonumber]] vim.cmd [[autocmd TermOpen term://* set norelativenumber]] -- Backup if necessary vim.cmd([[ if has("vms") set nobackup " do not keep a backup file, use versions instead else set backup " keep a backup file endif ]]) -- Colors and styling --{{{ -- Additional colours support opt.termguicolors = true vim.cmd [[set t_Co=256]] vim.cmd [[set t_ut=]] --Fix for bg colour issues in tmux http://sunaku.github.io/vim-256color-bce.html opt.conceallevel = 1 --Use vims new conceal feature opt.concealcursor = "" --}}} -- Settings related to text behaviour and margins --{{{ opt.scrolloff = 10 -- number of lines to keep above and below cursor opt.number = true -- show linenumbers opt.relativenumber = true opt.wrap = true -- wrap text opt.linebreak = true -- break lines when wrapping text opt.list = false opt.cinoptions = "N-s" -- namespaces doesn't count towards indentation opt.textwidth = 80 opt.wrapmargin = 0 opt.formatoptions:append('l') --}}} --- Tabs are defined as 2 spaces ---{{{ opt.tabstop = 2 opt.expandtab = true opt.shiftwidth = 2 ---}}} --- Other settings ---{{{ opt.inccommand = "nosplit" opt.laststatus = 2 opt.showmode = false vim.g.tex_flavor = "--latex" ---}}}
local opt = vim.opt -- Treat both system clipboards as the same opt.clipboard = "unnamedplus" opt.backupdir = vim.fn.expand "~/.tmp" -- Start diff-mode in vertical split, ignore all whitespace opt.diffopt = "filler,vertical,iwhiteall" --Command line file completion opt.wildmode = "longest,list,full" -- bash-like filename autocompletion opt.wildmenu = true -- zsh-like filename list chooser -- Use treesitter to fold opt.foldmethod = "expr" opt.foldexpr = "nvim_treesitter#foldexpr()" -- Make it so I can switch buffers even if they have changed opt.hidden = true -- Highlight the current cursorline opt.cursorline = true -- Disable mouse integration opt.mouse = nil -- Timeoutlen is used for e.g. the which-key plugin (default value 1000 ms) opt.timeoutlen = 500 -- Splits should be to the right and below opt.splitbelow = true opt.splitright = true -- Remove line numbering in new terminals vim.cmd [[autocmd TermOpen term://* set nonumber]] vim.cmd [[autocmd TermOpen term://* set norelativenumber]] -- Backup if necessary vim.cmd([[ if has("vms") set nobackup " do not keep a backup file, use versions instead else set backup " keep a backup file endif ]]) -- Colors and styling --{{{ -- Additional colours support opt.termguicolors = true vim.cmd [[set t_Co=256]] vim.cmd [[set t_ut=]] --Fix for bg colour issues in tmux http://sunaku.github.io/vim-256color-bce.html opt.conceallevel = 1 --Use vims new conceal feature opt.concealcursor = "" --}}} -- Settings related to text behaviour and margins --{{{ opt.scrolloff = 10 -- number of lines to keep above and below cursor opt.number = true -- show linenumbers opt.relativenumber = true opt.wrap = true -- wrap text opt.linebreak = true -- break lines when wrapping text opt.list = false opt.cinoptions = "N-s" -- namespaces doesn't count towards indentation opt.textwidth = 80 opt.wrapmargin = 0 opt.formatoptions:append('l') --}}} --- Tabs are defined as 2 spaces ---{{{ opt.tabstop = 2 opt.expandtab = true opt.shiftwidth = 2 ---}}} --- Other settings ---{{{ opt.inccommand = "nosplit" opt.laststatus = 2 opt.showmode = false vim.g.tex_flavor = "--latex" ---}}}
fix(nvim): disable mouse support
fix(nvim): disable mouse support
Lua
mit
Irubataru/dotfiles,Irubataru/dotfiles,Irubataru/dotfiles
9c5f0c687dd30eb1f6299e3e7dda35728e6208a7
examples/perf2/runner.lua
examples/perf2/runner.lua
local DIR_SEP = package.config:sub(1,1) local msg_size local msg_count local N local function exec(cmd) local f, err = io.popen(cmd, "r") if not f then return err end local data, err = f:read("*all") f:close() return data, err end local function parse_thr(result) local msgps = assert( tonumber((result:match("mean throughput: (%S+) %[msg/s%]"))) , result) local mbps = assert( tonumber((result:match("mean throughput: (%S+) %[Mb/s%]"))) , result) return msgps, mbps end local function parse_lat(result) return assert( tonumber((result:match("average latency: (%S+) %[us%]"))) , result) end local function exec_thr(cmd) local msg = assert(exec(cmd)) return parse_thr(msg) end local function exec_lat(cmd) local msg = assert(exec(cmd)) return parse_lat(msg) end local function field(wdt, fmt, value) local str = string.format(fmt, value) if wdt > #str then str = str .. (' '):rep(wdt - #str) end return str end local function print_row(row) print('|' .. table.concat(row, '|') .. '|') end function luajit_thr(result, dir, ffi) local cmd = "cd " .. dir .. " && " .. "luajit ." .. DIR_SEP .."inproc_thr.lua " .. msg_size .. " " .. msg_count .. " " .. ffi .. " && cd .." for i = 1, N do table.insert(result, {exec_thr(cmd)}) end end function bin_thr(result, dir) local cmd = "cd " .. dir .. " && " .. "." .. DIR_SEP .."inproc_thr " .. msg_size .. " " .. msg_count .. " && cd .." for i = 1, N do table.insert(result, {exec_thr(cmd)}) end end function luajit_lat(result, dir, ffi) local cmd = "cd " .. dir .. " && " .. "luajit ." .. DIR_SEP .."inproc_lat.lua " .. msg_size .. " " .. msg_count .. " " .. ffi .. " && cd .." for i = 1, N do table.insert(result, {exec_lat(cmd)}) end end function bin_lat(result, dir) local cmd = "cd " .. dir .. " && " .. "." .. DIR_SEP .."inproc_lat " .. msg_size .. " " .. msg_count .. " && cd .." for i = 1, N do table.insert(result, {exec_lat(cmd)}) end end msg_size = 30 msg_count = 10000 N = 10 local libzmq_thr = {} local nomsg_thr = {} local nomsg_thr_ffi = {} local msg_thr = {} local msg_thr_ffi = {} bin_thr(libzmq_thr, "libzmq") luajit_thr(nomsg_thr, "thr_nomsg", "" ) luajit_thr(nomsg_thr_ffi, "thr_nomsg", "ffi" ) luajit_thr(msg_thr, "thr", "" ) luajit_thr(msg_thr_ffi, "thr", "ffi" ) msg_size = 1 msg_count = 10000 N = 10 print("\n----") print("###Inproc Throughput Test:\n") print(string.format("message size: %d [B]<br/>", msg_size )) print(string.format("message count: %d<br/>", msg_count )) print(string.format("mean throughput [Mb/s]:<br/>\n" )) print_row{ field(3, " # "); field(12, " libzmq"); field(12, " str"); field(12, " str(ffi)"); field(12, " msg"); field(12, " msg(ffi)"); } print_row{ ("-"):rep(3); ("-"):rep(12); ("-"):rep(12); ("-"):rep(12); ("-"):rep(12); ("-"):rep(12); } for i = 1, N do print_row{ field(3, " %d", i); field(12,"%.3f", libzmq_thr [i][2]); field(12,"%.3f", nomsg_thr [i][2]); field(12,"%.3f", nomsg_thr_ffi [i][2]); field(12,"%.3f", msg_thr [i][2]); field(12,"%.3f", msg_thr_ffi [i][2]); } end local libzmq_lat = {} local nomsg_lat = {} local nomsg_lat_ffi = {} local msg_lat = {} local msg_lat_ffi = {} bin_lat(libzmq_lat, "libzmq") luajit_lat(nomsg_lat, "lat_nomsg", "" ) luajit_lat(nomsg_lat_ffi, "lat_nomsg", "ffi" ) luajit_lat(msg_lat, "lat", "" ) luajit_lat(msg_lat_ffi, "lat", "ffi" ) print("\n----") print("###Inproc Latency Test:\n") print(string.format("message size: %d [B]<br/>", msg_size )) print(string.format("message count: %d<br/>", msg_count )) print(string.format("average latency [us]:<br/>\n" )) print_row{ field(3, " # "); field(12, " libzmq"); field(12, " str"); field(12, " str(ffi)"); field(12, " msg"); field(12, " msg(ffi)"); } print_row{ ("-"):rep(3); ("-"):rep(12); ("-"):rep(12); ("-"):rep(12); ("-"):rep(12); ("-"):rep(12); } for i = 1, N do print_row{ field(3, " %d", i); field(12,"%.3f", libzmq_lat [i][1]); field(12,"%.3f", nomsg_lat [i][1]); field(12,"%.3f", nomsg_lat_ffi [i][1]); field(12,"%.3f", msg_lat [i][1]); field(12,"%.3f", msg_lat_ffi [i][1]); } end
local DIR_SEP = package.config:sub(1,1) local msg_size local msg_count local N local function exec(cmd) local f, err = io.popen(cmd, "r") if not f then return err end local data, err = f:read("*all") f:close() return data, err end local function parse_thr(result) local msgps = assert( tonumber((result:match("mean throughput: (%S+) %[msg/s%]"))) , result) local mbps = assert( tonumber((result:match("mean throughput: (%S+) %[Mb/s%]"))) , result) return msgps, mbps end local function parse_lat(result) return assert( tonumber((result:match("average latency: (%S+) %[us%]"))) , result) end local function exec_thr(cmd) local msg = assert(exec(cmd)) return parse_thr(msg) end local function exec_lat(cmd) local msg = assert(exec(cmd)) return parse_lat(msg) end local function field(wdt, fmt, value) local str = string.format(fmt, value) if wdt > #str then str = str .. (' '):rep(wdt - #str) end return str end local function print_row(row) print('|' .. table.concat(row, '|') .. '|') end function luajit_thr(result, dir, ffi) local cmd = "cd " .. dir .. " && " .. "luajit ." .. DIR_SEP .."inproc_thr.lua " .. msg_size .. " " .. msg_count .. " " .. ffi .. " && cd .." for i = 1, N do table.insert(result, {exec_thr(cmd)}) end end function bin_thr(result, dir) local cmd = "cd " .. dir .. " && " .. "." .. DIR_SEP .."inproc_thr " .. msg_size .. " " .. msg_count .. " && cd .." for i = 1, N do table.insert(result, {exec_thr(cmd)}) end end function luajit_lat(result, dir, ffi) local cmd = "cd " .. dir .. " && " .. "luajit ." .. DIR_SEP .."inproc_lat.lua " .. msg_size .. " " .. msg_count .. " " .. ffi .. " && cd .." for i = 1, N do table.insert(result, {exec_lat(cmd)}) end end function bin_lat(result, dir) local cmd = "cd " .. dir .. " && " .. "." .. DIR_SEP .."inproc_lat " .. msg_size .. " " .. msg_count .. " && cd .." for i = 1, N do table.insert(result, {exec_lat(cmd)}) end end msg_size = 30 msg_count = 10000 N = 10 local libzmq_thr = {} local nomsg_thr = {} local nomsg_thr_ffi = {} local msg_thr = {} local msg_thr_ffi = {} bin_thr(libzmq_thr, "libzmq") luajit_thr(nomsg_thr, "thr_nomsg", "" ) luajit_thr(nomsg_thr_ffi, "thr_nomsg", "ffi" ) luajit_thr(msg_thr, "thr", "" ) luajit_thr(msg_thr_ffi, "thr", "ffi" ) print("\n----") print("###Inproc Throughput Test:\n") print(string.format("message size: %d [B]<br/>", msg_size )) print(string.format("message count: %d<br/>", msg_count )) print(string.format("mean throughput [Mb/s]:<br/>\n" )) print_row{ field(3, " # "); field(12, " libzmq"); field(12, " str"); field(12, " str(ffi)"); field(12, " msg"); field(12, " msg(ffi)"); } print_row{ ("-"):rep(3); ("-"):rep(12); ("-"):rep(12); ("-"):rep(12); ("-"):rep(12); ("-"):rep(12); } for i = 1, N do print_row{ field(3, " %d", i); field(12,"%.3f", libzmq_thr [i][2]); field(12,"%.3f", nomsg_thr [i][2]); field(12,"%.3f", nomsg_thr_ffi [i][2]); field(12,"%.3f", msg_thr [i][2]); field(12,"%.3f", msg_thr_ffi [i][2]); } end msg_size = 1 msg_count = 10000 N = 10 local libzmq_lat = {} local nomsg_lat = {} local nomsg_lat_ffi = {} local msg_lat = {} local msg_lat_ffi = {} bin_lat(libzmq_lat, "libzmq") luajit_lat(nomsg_lat, "lat_nomsg", "" ) luajit_lat(nomsg_lat_ffi, "lat_nomsg", "ffi" ) luajit_lat(msg_lat, "lat", "" ) luajit_lat(msg_lat_ffi, "lat", "ffi" ) print("\n----") print("###Inproc Latency Test:\n") print(string.format("message size: %d [B]<br/>", msg_size )) print(string.format("message count: %d<br/>", msg_count )) print(string.format("average latency [us]:<br/>\n" )) print_row{ field(3, " # "); field(12, " libzmq"); field(12, " str"); field(12, " str(ffi)"); field(12, " msg"); field(12, " msg(ffi)"); } print_row{ ("-"):rep(3); ("-"):rep(12); ("-"):rep(12); ("-"):rep(12); ("-"):rep(12); ("-"):rep(12); } for i = 1, N do print_row{ field(3, " %d", i); field(12,"%.3f", libzmq_lat [i][1]); field(12,"%.3f", nomsg_lat [i][1]); field(12,"%.3f", nomsg_lat_ffi [i][1]); field(12,"%.3f", msg_lat [i][1]); field(12,"%.3f", msg_lat_ffi [i][1]); } end
Fix. runner.lua display wrong values for message size [ci-skip]
Fix. runner.lua display wrong values for message size [ci-skip]
Lua
mit
moteus/lzmq,moteus/lzmq,zeromq/lzmq,zeromq/lzmq,zeromq/lzmq,LuaDist/lzmq-ffi,LuaDist/lzmq-ffi,moteus/lzmq,bsn069/lzmq,LuaDist/lzmq,LuaDist/lzmq,bsn069/lzmq
23558157f3f3b4a043d0f7a4399d162095e4a5ec
mod_adhoc_cmd_modules/mod_adhoc_cmd_modules.lua
mod_adhoc_cmd_modules/mod_adhoc_cmd_modules.lua
-- Copyright (C) 2009-2010 Florian Zeitz -- -- This file is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local _G = _G; local prosody = _G.prosody; local hosts = prosody.hosts; require "util.iterators"; local dataforms_new = require "util.dataforms".new; local array = require "util.array"; local modulemanager = require "modulemanager"; local adhoc_new = module:require "adhoc".new; function list_modules_handler(self, data, state) local result = dataforms_new { title = "List of loaded modules"; { name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#list" }; { name = "modules", type = "text-multi", label = "The following modules are loaded:" }; }; local modules = array.collect(keys(hosts[data.to].modules)):sort():concat("\n"); return { status = "completed", result = { layout = result; data = { modules = modules } } }; end function load_module_handler(self, data, state) local layout = dataforms_new { title = "Load module"; instructions = "Specify the module to be loaded"; { name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#load" }; { name = "module", type = "text-single", required = true, label = "Module to be loaded:"}; }; if state then if data.action == "cancel" then return { status = "canceled" }; end local fields = layout:data(data.form); if (not fields.module) or (fields.module == "") then return { status = "completed", error = { message = "Please specify a module. (This means your client misbehaved, as this field is required)" } }; end if modulemanager.is_loaded(data.to, fields.module) then return { status = "completed", info = "Module already loaded" }; end local ok, err = modulemanager.load(data.to, fields.module); if ok then return { status = "completed", info = 'Module "'..fields.module..'" successfully loaded on host "'..data.to..'".' }; else return { status = "completed", error = { message = 'Failed to load module "'..fields.module..'" on host "'..data.to.. '". Error was: "'..tostring(err or "<unspecified>")..'"' } }; end else local modules = array.collect(keys(hosts[data.to].modules)):sort(); return { status = "executing", form = layout }, "executing"; end end -- TODO: Allow reloading multiple modules (depends on list-multi) function reload_modules_handler(self, data, state) local layout = dataforms_new { title = "Reload module"; instructions = "Select the module to be reloaded"; { name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#reload" }; { name = "module", type = "list-single", required = true, label = "Module to be reloaded:"}; }; if state then if data.action == "cancel" then return { status = "canceled" }; end local fields = layout:data(data.form); if (not fields.module) or (fields.module == "") then return { status = "completed", error = { message = "Please specify a module. (This means your client misbehaved, as this field is required)" } }; end local ok, err = modulemanager.reload(data.to, fields.module); if ok then return { status = "completed", info = 'Module "'..fields.module..'" successfully reloaded on host "'..data.to..'".' }; else return { status = "completed", error = { message = 'Failed to reload module "'..fields.module..'" on host "'..data.to.. '". Error was: "'..tostring(err)..'"' } }; end else local modules = array.collect(keys(hosts[data.to].modules)):sort(); return { status = "executing", form = { layout = layout; data = { module = modules } } }, "executing"; end end -- TODO: Allow unloading multiple modules (depends on list-multi) function unload_modules_handler(self, data, state) local layout = dataforms_new { title = "Unload module"; instructions = "Select the module to be unloaded"; { name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#unload" }; { name = "module", type = "list-single", required = true, label = "Module to be unloaded:"}; }; if state then if data.action == "cancel" then return { status = "canceled" }; end local fields = layout:data(data.form); if (not fields.module) or (fields.module == "") then return { status = "completed", error = { message = "Please specify a module. (This means your client misbehaved, as this field is required)" } }; end local ok, err = modulemanager.unload(data.to, fields.module); if ok then return { status = "completed", info = 'Module "'..fields.module..'" successfully unloaded on host "'..data.to..'".' }; else return { status = "completed", error = { message = 'Failed to unload module "'..fields.module..'" on host "'..data.to.. '". Error was: "'..tostring(err)..'"' } }; end else local modules = array.collect(keys(hosts[data.to].modules)):sort(); return { status = "executing", form = { layout = layout; data = { module = modules } } }, "executing"; end end local list_modules_desc = adhoc_new("List loaded modules", "http://prosody.im/protocol/modules#list", list_modules_handler, "admin"); local load_module_desc = adhoc_new("Load module", "http://prosody.im/protocol/modules#load", load_module_handler, "admin"); local reload_modules_desc = adhoc_new("Reload module", "http://prosody.im/protocol/modules#reload", reload_modules_handler, "admin"); local unload_modules_desc = adhoc_new("Unload module", "http://prosody.im/protocol/modules#unload", unload_modules_handler, "admin"); module:add_item("adhoc", list_modules_desc); module:add_item("adhoc", load_module_desc); module:add_item("adhoc", reload_modules_desc); module:add_item("adhoc", unload_modules_desc);
-- Copyright (C) 2009-2010 Florian Zeitz -- -- This file is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local _G = _G; local prosody = _G.prosody; local hosts = prosody.hosts; require "util.iterators"; local dataforms_new = require "util.dataforms".new; local array = require "util.array"; local modulemanager = require "modulemanager"; local adhoc_new = module:require "adhoc".new; function list_modules_handler(self, data, state) local result = dataforms_new { title = "List of loaded modules"; { name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#list" }; { name = "modules", type = "text-multi", label = "The following modules are loaded:" }; }; local modules = array.collect(keys(hosts[data.to].modules)):sort():concat("\n"); return { status = "completed", result = { layout = result; data = { modules = modules } } }; end function load_module_handler(self, data, state) local layout = dataforms_new { title = "Load module"; instructions = "Specify the module to be loaded"; { name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#load" }; { name = "module", type = "text-single", required = true, label = "Module to be loaded:"}; }; if state then if data.action == "cancel" then return { status = "canceled" }; end local fields = layout:data(data.form); if (not fields.module) or (fields.module == "") then return { status = "completed", error = { message = "Please specify a module." } }; end if modulemanager.is_loaded(data.to, fields.module) then return { status = "completed", info = "Module already loaded" }; end local ok, err = modulemanager.load(data.to, fields.module); if ok then return { status = "completed", info = 'Module "'..fields.module..'" successfully loaded on host "'..data.to..'".' }; else return { status = "completed", error = { message = 'Failed to load module "'..fields.module..'" on host "'..data.to.. '". Error was: "'..tostring(err or "<unspecified>")..'"' } }; end else local modules = array.collect(keys(hosts[data.to].modules)):sort(); return { status = "executing", form = layout }, "executing"; end end -- TODO: Allow reloading multiple modules (depends on list-multi) function reload_modules_handler(self, data, state) local layout = dataforms_new { title = "Reload module"; instructions = "Select the module to be reloaded"; { name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#reload" }; { name = "module", type = "list-single", required = true, label = "Module to be reloaded:"}; }; if state then if data.action == "cancel" then return { status = "canceled" }; end local fields = layout:data(data.form); if (not fields.module) or (fields.module == "") then return { status = "completed", error = { message = "Please specify a module. (This means your client misbehaved, as this field is required)" } }; end local ok, err = modulemanager.reload(data.to, fields.module); if ok then return { status = "completed", info = 'Module "'..fields.module..'" successfully reloaded on host "'..data.to..'".' }; else return { status = "completed", error = { message = 'Failed to reload module "'..fields.module..'" on host "'..data.to.. '". Error was: "'..tostring(err)..'"' } }; end else local modules = array.collect(keys(hosts[data.to].modules)):sort(); return { status = "executing", form = { layout = layout; data = { module = modules } } }, "executing"; end end -- TODO: Allow unloading multiple modules (depends on list-multi) function unload_modules_handler(self, data, state) local layout = dataforms_new { title = "Unload module"; instructions = "Select the module to be unloaded"; { name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/modules#unload" }; { name = "module", type = "list-single", required = true, label = "Module to be unloaded:"}; }; if state then if data.action == "cancel" then return { status = "canceled" }; end local fields = layout:data(data.form); if (not fields.module) or (fields.module == "") then return { status = "completed", error = { message = "Please specify a module. (This means your client misbehaved, as this field is required)" } }; end local ok, err = modulemanager.unload(data.to, fields.module); if ok then return { status = "completed", info = 'Module "'..fields.module..'" successfully unloaded on host "'..data.to..'".' }; else return { status = "completed", error = { message = 'Failed to unload module "'..fields.module..'" on host "'..data.to.. '". Error was: "'..tostring(err)..'"' } }; end else local modules = array.collect(keys(hosts[data.to].modules)):sort(); return { status = "executing", form = { layout = layout; data = { module = modules } } }, "executing"; end end local list_modules_desc = adhoc_new("List loaded modules", "http://prosody.im/protocol/modules#list", list_modules_handler, "admin"); local load_module_desc = adhoc_new("Load module", "http://prosody.im/protocol/modules#load", load_module_handler, "admin"); local reload_modules_desc = adhoc_new("Reload module", "http://prosody.im/protocol/modules#reload", reload_modules_handler, "admin"); local unload_modules_desc = adhoc_new("Unload module", "http://prosody.im/protocol/modules#unload", unload_modules_handler, "admin"); module:add_item("adhoc", list_modules_desc); module:add_item("adhoc", load_module_desc); module:add_item("adhoc", reload_modules_desc); module:add_item("adhoc", unload_modules_desc);
mod_adhoc_cmd_modules: Fix error message
mod_adhoc_cmd_modules: Fix error message
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
68d9d973e53720610260707aecadc8fc19e89351
share/luaplaylist/youtube.lua
share/luaplaylist/youtube.lua
--[[ $Id$ Copyright © 2007 the VideoLAN team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Helper function to get a parameter's value in a URL function get_url_param( url, name ) return string.gsub( url, "^.*[&?]"..name.."=([^&]*).*$", "%1" ) end function get_arturl( path, video_id ) if string.match( vlc.path, "iurl=" ) then return vlc.decode_uri( get_url_param( vlc.path, "iurl" ) ) end if not arturl then return "http://img.youtube.com/vi/"..video_id.."/default.jpg" end end -- Probe function. function probe() if vlc.access ~= "http" then return false end youtube_site = string.match( string.sub( vlc.path, 1, 8 ), "youtube" ) if not youtube_site then -- FIXME we should be using a builtin list of known youtube websites -- like "fr.youtube.com", "uk.youtube.com" etc.. youtube_site = string.find( vlc.path, ".youtube.com" ) if youtube_site == nil then return false end end return ( string.match( vlc.path, "watch%?v=" ) -- the html page or string.match( vlc.path, "watch_fullscreen%?video_id=" ) -- the fullscreen page or string.match( vlc.path, "p.swf" ) -- the (old?) player url or string.match( vlc.path, "jp.swf" ) -- the (new?) player url (as of 24/08/2007) or string.match( vlc.path, "player2.swf" ) ) -- another player url end -- Parse function. function parse() if string.match( vlc.path, "watch%?v=" ) then -- This is the HTML page's URL while true do -- Try to find the video's title line = vlc.readline() if not line then break end if string.match( line, "<meta name=\"title\"" ) then name = string.gsub( line, "^.*content=\"([^\"]*).*$", "%1" ) end if string.match( line, "<meta name=\"description\"" ) then description = string.gsub( line, "^.*content=\"([^\"]*).*$", "%1" ) end if string.match( line, "subscribe_to_user=" ) then artist = string.gsub( line, ".*subscribe_to_user=([^&]*).*", "%1" ) end -- var swfArgs = {hl:'en',BASE_YT_URL:'http://youtube.com/',video_id:'XPJ7d8dq0t8',l:'292',t:'OEgsToPDskLFdOYrrlDm3FQPoQBYaCP1',sk:'0gnr-AE6QZJEZmCMd3lq_AC'}; if string.match( line, "swfArgs" ) and string.match( line, "video_id" ) then if string.match( line, "BASE_YT_URL" ) then base_yt_url = string.gsub( line, ".*BASE_YT_URL:'([^']*)'.*", "%1" ) end t = string.gsub( line, ".*t:'([^']*)'.*", "%1" ) -- vlc.msg_err( t ) -- video_id = string.gsub( line, ".*&video_id:'([^']*)'.*", "%1" ) end if name and description and artist --[[and video_id]] then break end end if not video_id then video_id = get_url_param( vlc.path, "v" ) end if not base_yt_url then base_yt_url = "http://youtube.com/" end arturl = get_arturl( vlc.path, video_id ) if t then return { { path = base_yt_url .. "get_video?video_id="..video_id.."&t="..t; name = name; description = description; artist = artist; arturl = arturl } } else -- This shouldn't happen ... but keep it as a backup. return { { path = "http://www.youtube.com/v/"..video_id; name = name; description = description; artist = artist; arturl = arturl } } end else -- This is the flash player's URL if string.match( vlc.path, "title=" ) then name = get_url_param( vlc.path, "title" ) end video_id = get_url_param( vlc.path, "video_id" ) arturl = get_arturl( vlc.path, video_id ) if not string.match( vlc.path, "t=" ) then -- This sucks, we're missing "t" which is now mandatory. Let's -- try using another url return { { path = "http://www.youtube.com/v/"..video_id; name = name; arturl = arturl } } end return { { path = "http://www.youtube.com/get_video.php?video_id="..video_id.."&t="..get_url_param( vlc.path, "t" ); name = name; arturl = arturl } } end end
--[[ $Id$ Copyright © 2007 the VideoLAN team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Helper function to get a parameter's value in a URL function get_url_param( url, name ) return string.gsub( url, "^.*[&?]"..name.."=([^&]*).*$", "%1" ) end function get_arturl( path, video_id ) if string.match( vlc.path, "iurl=" ) then return vlc.decode_uri( get_url_param( vlc.path, "iurl" ) ) end if not arturl then return "http://img.youtube.com/vi/"..video_id.."/default.jpg" end end -- Probe function. function probe() if vlc.access ~= "http" then return false end youtube_site = string.match( string.sub( vlc.path, 1, 8 ), "youtube" ) if not youtube_site then -- FIXME we should be using a builtin list of known youtube websites -- like "fr.youtube.com", "uk.youtube.com" etc.. youtube_site = string.find( vlc.path, ".youtube.com" ) if youtube_site == nil then return false end end return ( string.match( vlc.path, "watch%?v=" ) -- the html page or string.match( vlc.path, "watch_fullscreen%?video_id=" ) -- the fullscreen page or string.match( vlc.path, "p.swf" ) -- the (old?) player url or string.match( vlc.path, "jp.swf" ) -- the (new?) player url (as of 24/08/2007) or string.match( vlc.path, "player2.swf" ) ) -- another player url end -- Parse function. function parse() if string.match( vlc.path, "watch%?v=" ) then -- This is the HTML page's URL while true do -- Try to find the video's title line = vlc.readline() if not line then break end if string.match( line, "<meta name=\"title\"" ) then name = string.gsub( line, "^.*content=\"([^\"]*).*$", "%1" ) end if string.match( line, "<meta name=\"description\"" ) then description = string.gsub( line, "^.*content=\"([^\"]*).*$", "%1" ) end if string.match( line, "subscribe_to_user=" ) then artist = string.gsub( line, ".*subscribe_to_user=([^&]*).*", "%1" ) end -- OLD: var swfArgs = {hl:'en',BASE_YT_URL:'http://youtube.com/',video_id:'XPJ7d8dq0t8',l:'292',t:'OEgsToPDskLFdOYrrlDm3FQPoQBYaCP1',sk:'0gnr-AE6QZJEZmCMd3lq_AC'}; -- NEW: var swfArgs = {"video_id": "OHVvVmUNBFc", "l": 88, "sk": "WswKuJzDBsdD6oG3IakCXgC", "t": "OEgsToPDskK3zO44y0QN8Fr5ZSAZwCQp", "plid": "AARGnwWMrmGkbpOxAAAA4AT4IAA", "tk": "mEL4E7PqHeaZp5OG19NQThHt9mXJU4PbRTOw6lz9osHi4Hixp7RE1w=="}; if string.match( line, "swfArgs" ) and string.match( line, "video_id" ) then if string.match( line, "BASE_YT_URL" ) then base_yt_url = string.gsub( line, ".*BASE_YT_URL:'([^']*)'.*", "%1" ) end t = string.gsub( line, ".*\"t\": \"([^\"]*).*", "%1" ) -- vlc.msg_err( t ) -- video_id = string.gsub( line, ".*&video_id:'([^']*)'.*", "%1" ) end if name and description and artist --[[and video_id]] then break end end if not video_id then video_id = get_url_param( vlc.path, "v" ) end if not base_yt_url then base_yt_url = "http://youtube.com/" end arturl = get_arturl( vlc.path, video_id ) if t then return { { path = base_yt_url .. "get_video?video_id="..video_id.."&t="..t; name = name; description = description; artist = artist; arturl = arturl } } else -- This shouldn't happen ... but keep it as a backup. return { { path = "http://www.youtube.com/v/"..video_id; name = name; description = description; artist = artist; arturl = arturl } } end else -- This is the flash player's URL if string.match( vlc.path, "title=" ) then name = get_url_param( vlc.path, "title" ) end video_id = get_url_param( vlc.path, "video_id" ) arturl = get_arturl( vlc.path, video_id ) if not string.match( vlc.path, "t=" ) then -- This sucks, we're missing "t" which is now mandatory. Let's -- try using another url return { { path = "http://www.youtube.com/v/"..video_id; name = name; arturl = arturl } } end return { { path = "http://www.youtube.com/get_video.php?video_id="..video_id.."&t="..get_url_param( vlc.path, "t" ); name = name; arturl = arturl } } end end
fix youtube parsing
fix youtube parsing
Lua
lgpl-2.1
shyamalschandra/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,xkfz007/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc,shyamalschandra/vlc,shyamalschandra/vlc,vlc-mirror/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,xkfz007/vlc,vlc-mirror/vlc,vlc-mirror/vlc,krichter722/vlc,shyamalschandra/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,shyamalschandra/vlc,krichter722/vlc,xkfz007/vlc,vlc-mirror/vlc,krichter722/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,krichter722/vlc,shyamalschandra/vlc,xkfz007/vlc
b511b792ba70f1f9bb21c94767e00bf778d3aea9
himan-scripts/CB-TCU-cloud.lua
himan-scripts/CB-TCU-cloud.lua
--Round to natural number function round(n) return n % 1 >= 0.5 and math.ceil(n) or math.floor(n) end --Main program -- local MU = level(HPLevelType.kMaximumThetaE,0) local HL = level(HPLevelType.kHeightLayer,500,0) local HG = level(HPLevelType.kHeight,0) EL500 = luatool:FetchWithType(current_time, HL, param("EL-HPA"), current_forecast_type) LCL500 = luatool:FetchWithType(current_time, HL, param("LCL-HPA"), current_forecast_type) LFC500 = luatool:FetchWithType(current_time, HL, param("LFC-HPA"), current_forecast_type) CAPE500 = luatool:FetchWithType(current_time, HL, param("CAPE-JKG"), current_forecast_type) CIN500 = luatool:FetchWithType(current_time, HL, param("CIN-JKG"), current_forecast_type) LCLmu = luatool:FetchWithType(current_time, MU, param("LCL-HPA"), current_forecast_type) LFCmu = luatool:FetchWithType(current_time, MU, param("LFC-HPA"), current_forecast_type) LFCmu_metric = luatool:FetchWithType(current_time, MU, param("LFC-M"), current_forecast_type) ELmu = luatool:FetchWithType(current_time, MU, param("EL-HPA"), current_forecast_type) CINmu = luatool:FetchWithType(current_time, MU, param("CIN-JKG"), current_forecast_type) CAPEmu = luatool:FetchWithType(current_time, MU, param("CAPE-JKG"), current_forecast_type) Ttop = luatool:FetchWithType(current_time, HL, param("EL-K"), current_forecast_type) Tbase = luatool:FetchWithType(current_time, HL, param("LCL-K"), current_forecast_type) TtopMU = luatool:FetchWithType(current_time, MU, param("EL-K"), current_forecast_type) --LFC probably better than LCL for elev conv. base TbaseMU = luatool:FetchWithType(current_time, MU, param("LFC-K"), current_forecast_type) NL = luatool:FetchWithType(current_time, HG, param("NL-PRCNT"), current_forecast_type) NM = luatool:FetchWithType(current_time, HG, param("NM-PRCNT"), current_forecast_type) if not NL then NL = luatool:FetchWithType(current_time, HG, param("NL-0TO1"), current_forecast_type) end if not NM then NM = luatool:FetchWithType(current_time, HG, param("NM-0TO1"), current_forecast_type) end RR = luatool:FetchWithType(current_time, HG, param("RRR-KGM2"), current_forecast_type) CBlimit = 9 --required vertical thickness [degrees C] to consider a CB (tweak this..!) TCUlimit = 6 --required vertical thickness [degrees C] to consider a TCU (tweak this..!) CBtopLim = 263.15 --required top T [K] to consider a CB (tweakable!) --Max height [FL] to check for top TopLim = 650 --Denominator to calculate overshooting top based on CAPE, +1000ft/350J/kg (tweak this!) overshoot = 35 local i = 0 local res = {} local Missing = missing for i=1, #EL500 do res[i] = Missing --TCU if ((Tbase[i]-Ttop[i]>TCUlimit) and (NL[i]>0) and (CIN500[i]>-1)) then res[i] = FlightLevel_(EL500[i]*100) --Limit top value if (res[i] <= TopLim) then --Add for overshooting top based on CAPE, +1000ft/350J/kg (tweak this!) res[i] = -(res[i] + CAPE500[i]/overshoot) else --Add for overshooting top based on CAPE, +1000ft/350J/kg (tweak this!) res[i] = Missing end end --CB if ((Ttop[i]<CBtopLim) and (Tbase[i]-Ttop[i]>CBlimit) and (RR[i]>0)) then res[i] = FlightLevel_(EL500[i]*100) --Limit top value if (res[i] <= TopLim) then --Add for overshooting top based on CAPE, +1000ft/350J/kg (tweak this!) res[i] = res[i] + CAPE500[i]/overshoot else res[i] = Missing end end --If no TOP from above, check also with MU values, for elev. conv. only from blw 3,5km if (not res[i]==res[i] and (LFCmu[i]>LCL500[i]) and (LFCmu_metric[i]>650)) then -- TCU if ((TbaseMU[i]-TtopMU[i]>TCUlimit) and ((NL[i]>0) or (NM[i]>0)) and (CINmu[i]>-1)) then res[i] = FlightLevel_(ELmu[i]*100) --Limit top value if (res[i] <= TopLim) then --Add for overshooting top based on CAPE, +1000ft/350J/kg (tweak this!) res[i] = -(res[i] + CAPEmu[i]/overshoot) else res[i] = Missing end end --CB if ((TtopMU[i]<CBtopLim) and (TbaseMU[i]-TtopMU[i]>CBlimit) and (RR[i]>0)) then res[i] = FlightLevel_(ELmu[i]*100) --Limit top value if (res[i] <= TopLim) then --Add for overshooting top based on CAPE, +1000ft/350J/kg (tweak this!) res[i] = res[i] + CAPEmu[i]/overshoot else res[i] = Missing end end end res[i] = round(res[i]/10)*10; end p = param("CBTCU-FL") result:SetValues(res) result:SetParam(p) luatool:WriteToFile(result)
--Round to natural number function round(n) return n % 1 >= 0.5 and math.ceil(n) or math.floor(n) end --Main program -- local MU = level(HPLevelType.kMaximumThetaE,0) local HL = level(HPLevelType.kHeightLayer,500,0) local HG = level(HPLevelType.kHeight,0) EL500 = luatool:FetchWithType(current_time, HL, param("EL-HPA"), current_forecast_type) LCL500 = luatool:FetchWithType(current_time, HL, param("LCL-HPA"), current_forecast_type) LFC500 = luatool:FetchWithType(current_time, HL, param("LFC-HPA"), current_forecast_type) CAPE500 = luatool:FetchWithType(current_time, HL, param("CAPE-JKG"), current_forecast_type) CIN500 = luatool:FetchWithType(current_time, HL, param("CIN-JKG"), current_forecast_type) LCLmu = luatool:FetchWithType(current_time, MU, param("LCL-HPA"), current_forecast_type) LFCmu = luatool:FetchWithType(current_time, MU, param("LFC-HPA"), current_forecast_type) ELmu = luatool:FetchWithType(current_time, MU, param("EL-HPA"), current_forecast_type) CINmu = luatool:FetchWithType(current_time, MU, param("CIN-JKG"), current_forecast_type) CAPEmu = luatool:FetchWithType(current_time, MU, param("CAPE-JKG"), current_forecast_type) Ttop = luatool:FetchWithType(current_time, HL, param("EL-K"), current_forecast_type) Tbase = luatool:FetchWithType(current_time, HL, param("LCL-K"), current_forecast_type) TtopMU = luatool:FetchWithType(current_time, MU, param("EL-K"), current_forecast_type) --LFC probably better than LCL for elev conv. base TbaseMU = luatool:FetchWithType(current_time, MU, param("LFC-K"), current_forecast_type) NL = luatool:FetchWithType(current_time, HG, param("NL-PRCNT"), current_forecast_type) NM = luatool:FetchWithType(current_time, HG, param("NM-PRCNT"), current_forecast_type) if not NL then NL = luatool:FetchWithType(current_time, HG, param("NL-0TO1"), current_forecast_type) end if not NM then NM = luatool:FetchWithType(current_time, HG, param("NM-0TO1"), current_forecast_type) end RR = luatool:FetchWithType(current_time, HG, param("RRR-KGM2"), current_forecast_type) CBlimit = 9 --required vertical thickness [degrees C] to consider a CB (tweak this..!) TCUlimit = 6 --required vertical thickness [degrees C] to consider a TCU (tweak this..!) CBtopLim = 263.15 --required top T [K] to consider a CB (tweakable!) --Max height [FL] to check for top TopLim = 650 --Denominator to calculate overshooting top based on CAPE, +1000ft/350J/kg (tweak this!) overshoot = 35 local i = 0 local res = {} local Missing = missing for i=1, #EL500 do res[i] = Missing --TCU if ((Tbase[i]-Ttop[i]>TCUlimit) and (NL[i]>0) and (CIN500[i]>-1)) then res[i] = FlightLevel_(EL500[i]*100) --Limit top value if (res[i] <= TopLim) then --Add for overshooting top based on CAPE, +1000ft/350J/kg (tweak this!) res[i] = -(res[i] + CAPE500[i]/overshoot) else --Add for overshooting top based on CAPE, +1000ft/350J/kg (tweak this!) res[i] = Missing end end --CB if ((Ttop[i]<CBtopLim) and (Tbase[i]-Ttop[i]>CBlimit) and (RR[i]>0)) then res[i] = FlightLevel_(EL500[i]*100) --Limit top value if (res[i] <= TopLim) then --Add for overshooting top based on CAPE, +1000ft/350J/kg (tweak this!) res[i] = res[i] + CAPE500[i]/overshoot else res[i] = Missing end end --If no TOP from above, check also with MU values, for elev. conv. only from blw 3,5km if ( IsMissing(res[i]) and (LFCmu[i]<LCL500[i]) and (LFCmu[i]>650)) then -- TCU if ((TbaseMU[i]-TtopMU[i]>TCUlimit) and ((NL[i]>0) or (NM[i]>0)) and (CINmu[i]>-1)) then res[i] = FlightLevel_(ELmu[i]*100) --Limit top value if (res[i] <= TopLim) then --Add for overshooting top based on CAPE, +1000ft/350J/kg (tweak this!) res[i] = -(res[i] + CAPEmu[i]/overshoot) else res[i] = Missing end end --CB if ((TtopMU[i]<CBtopLim) and (TbaseMU[i]-TtopMU[i]>CBlimit) and (RR[i]>0)) then res[i] = FlightLevel_(ELmu[i]*100) --Limit top value if (res[i] <= TopLim) then --Add for overshooting top based on CAPE, +1000ft/350J/kg (tweak this!) res[i] = res[i] + CAPEmu[i]/overshoot else res[i] = Missing end end end res[i] = round(res[i]/10)*10; end p = param("CBTCU-FL") result:SetValues(res) result:SetParam(p) luatool:WriteToFile(result)
fix missing value check
fix missing value check
Lua
mit
fmidev/himan,fmidev/himan,fmidev/himan
9ba0860c701850a04154b4f9799f391f9d388fa3
lualib/skynet/cluster.lua
lualib/skynet/cluster.lua
local skynet = require "skynet" local clusterd local cluster = {} local sender = {} local function get_sender(t, node) local c = skynet.call(clusterd, "lua", "sender", node) t[node] = c return c end setmetatable(sender, { __index = get_sender } ) function cluster.call(node, address, ...) -- skynet.pack(...) will free by cluster.core.packrequest return skynet.call(sender[node], "lua", "req", address, skynet.pack(...)) end function cluster.send(node, address, ...) -- push is the same with req, but no response skynet.send(sender[node], "lua", "push", address, skynet.pack(...)) end function cluster.open(port) if type(port) == "string" then skynet.call(clusterd, "lua", "listen", port) else skynet.call(clusterd, "lua", "listen", "0.0.0.0", port) end end function cluster.reload(config) skynet.call(clusterd, "lua", "reload", config) end function cluster.proxy(node, name) return skynet.call(clusterd, "lua", "proxy", node, name) end function cluster.snax(node, name, address) local snax = require "skynet.snax" if not address then address = cluster.call(node, ".service", "QUERY", "snaxd" , name) end local handle = skynet.call(clusterd, "lua", "proxy", node, address) return snax.bind(handle, name) end function cluster.register(name, addr) assert(type(name) == "string") assert(addr == nil or type(addr) == "number") return skynet.call(clusterd, "lua", "register", name, addr) end function cluster.query(node, name) return skynet.call(sender[node], "lua", "req", 0, skynet.pack(name)) end skynet.init(function() clusterd = skynet.uniqueservice("clusterd") end) return cluster
local skynet = require "skynet" local clusterd local cluster = {} local sender = {} local inquery_name = {} local function get_sender(t, node) local waitco = inquery_name[node] if waitco then local co=coroutine.running() table.insert(waitco, co) skynet.wait(co) return rawget(t, node) else waitco = {} inquery_name[node] = waitco local c = skynet.call(clusterd, "lua", "sender", node) inquery_name[node] = nil t[node] = c for _, co in ipairs(waitco) do skynet.wakeup(co) end return c end end setmetatable(sender, { __index = get_sender } ) function cluster.call(node, address, ...) -- skynet.pack(...) will free by cluster.core.packrequest return skynet.call(sender[node], "lua", "req", address, skynet.pack(...)) end function cluster.send(node, address, ...) -- push is the same with req, but no response skynet.send(sender[node], "lua", "push", address, skynet.pack(...)) end function cluster.open(port) if type(port) == "string" then skynet.call(clusterd, "lua", "listen", port) else skynet.call(clusterd, "lua", "listen", "0.0.0.0", port) end end function cluster.reload(config) skynet.call(clusterd, "lua", "reload", config) end function cluster.proxy(node, name) return skynet.call(clusterd, "lua", "proxy", node, name) end function cluster.snax(node, name, address) local snax = require "skynet.snax" if not address then address = cluster.call(node, ".service", "QUERY", "snaxd" , name) end local handle = skynet.call(clusterd, "lua", "proxy", node, address) return snax.bind(handle, name) end function cluster.register(name, addr) assert(type(name) == "string") assert(addr == nil or type(addr) == "number") return skynet.call(clusterd, "lua", "register", name, addr) end function cluster.query(node, name) return skynet.call(sender[node], "lua", "req", 0, skynet.pack(name)) end skynet.init(function() clusterd = skynet.uniqueservice("clusterd") end) return cluster
bugfix:cluster初始化节点的时候有可能导致消息乱序
bugfix:cluster初始化节点的时候有可能导致消息乱序
Lua
mit
bigrpg/skynet,sanikoyes/skynet,JiessieDawn/skynet,xcjmine/skynet,jxlczjp77/skynet,korialuo/skynet,wangyi0226/skynet,cloudwu/skynet,wangyi0226/skynet,icetoggle/skynet,xjdrew/skynet,sanikoyes/skynet,bigrpg/skynet,pigparadise/skynet,ag6ag/skynet,icetoggle/skynet,xcjmine/skynet,xjdrew/skynet,xjdrew/skynet,jxlczjp77/skynet,korialuo/skynet,hongling0/skynet,xcjmine/skynet,wangyi0226/skynet,cloudwu/skynet,JiessieDawn/skynet,ag6ag/skynet,korialuo/skynet,pigparadise/skynet,JiessieDawn/skynet,hongling0/skynet,cloudwu/skynet,hongling0/skynet,bigrpg/skynet,icetoggle/skynet,jxlczjp77/skynet,pigparadise/skynet,ag6ag/skynet,sanikoyes/skynet
1c7179431af1e160f6f9fab069074b6847733ec9
ram-widget/ram-widget.lua
ram-widget/ram-widget.lua
local awful = require("awful") local watch = require("awful.widget.watch") local wibox = require("wibox") local ramgraph_widget = {} local function worker(args) local args = args or {} local timeout = args.timeout or 1 --- Main ram widget shown on wibar ramgraph_widget = wibox.widget { border_width = 0, colors = { '#74aeab', '#26403f' }, display_labels = false, forced_width = 25, widget = wibox.widget.piechart } --- Widget which is shown when user clicks on the ram widget local w = wibox { height = 200, width = 400, ontop = true, expand = true, bg = '#1e252c', max_widget_size = 500 } w:setup { border_width = 0, colors = { '#5ea19d', '#55918e', '#4b817e', }, display_labels = false, forced_width = 25, id = 'pie', widget = wibox.widget.piechart } local total, used, free, shared, buff_cache, available, total_swap, used_swap, free_swap local function getPercentage(value) return math.floor(value / (total+total_swap) * 100 + 0.5) .. '%' end watch('bash -c "LANGUAGE=en_US.UTF-8 free | grep -z Mem.*Swap.*"', timeout, function(widget, stdout, stderr, exitreason, exitcode) total, used, free, shared, buff_cache, available, total_swap, used_swap, free_swap = stdout:match('(%d+)%s*(%d+)%s*(%d+)%s*(%d+)%s*(%d+)%s*(%d+)%s*Swap:%s*(%d+)%s*(%d+)%s*(%d+)') widget.data = { used, total-used } widget.data = { used, total-used } if w.visible then w.pie.data_list = { {'used ' .. getPercentage(used + used_swap), used + used_swap}, {'free ' .. getPercentage(free + free_swap), free + free_swap}, {'buff_cache ' .. getPercentage(buff_cache), buff_cache} } end end, ramgraph_widget ) ramgraph_widget:buttons( awful.util.table.join( awful.button({}, 1, function() awful.placement.top_right(w, { margins = {top = 25, right = 10}, parent = awful.screen.focused() }) w.pie.data_list = { {'used ' .. getPercentage(used + used_swap), used + used_swap}, {'free ' .. getPercentage(free + free_swap), free + free_swap}, {'buff_cache ' .. getPercentage(buff_cache), buff_cache} } w.pie.display_labels = true w.visible = not w.visible end) ) ) return ramgraph_widget end return setmetatable(ramgraph_widget, { __call = function(_, ...) return worker(...) end })
local awful = require("awful") local beautiful = require("beautiful") local gears = require("gears") local watch = require("awful.widget.watch") local wibox = require("wibox") local ramgraph_widget = {} local function worker(args) local args = args or {} local timeout = args.timeout or 1 --- Main ram widget shown on wibar ramgraph_widget = wibox.widget { border_width = 0, colors = { beautiful.bg_urgent, -- used beautiful.fg_normal -- free }, display_labels = false, forced_width = 25, widget = wibox.widget.piechart } --- Widget which is shown when user clicks on the ram widget local popup = awful.popup{ visible = false, widget = { widget = wibox.widget.piechart, forced_height = 200, forced_width = 400, colors = { beautiful.bg_urgent, -- used beautiful.fg_normal, -- free beautiful.border_color_active, -- buf_cache }, }, shape = gears.shape.rounded_rect, border_color = beautiful.border_color_active, border_width = 1, offset = { y = 5 }, } local total, used, free, shared, buff_cache, available, total_swap, used_swap, free_swap local function getPercentage(value) return math.floor(value / (total+total_swap) * 100 + 0.5) .. '%' end watch('bash -c "LANGUAGE=en_US.UTF-8 free | grep -z Mem.*Swap.*"', timeout, function(widget, stdout, stderr, exitreason, exitcode) total, used, free, shared, buff_cache, available, total_swap, used_swap, free_swap = stdout:match('(%d+)%s*(%d+)%s*(%d+)%s*(%d+)%s*(%d+)%s*(%d+)%s*Swap:%s*(%d+)%s*(%d+)%s*(%d+)') widget.data = { used, total-used } if popup.visible then popup:get_widget().data_list = { {'used ' .. getPercentage(used + used_swap), used + used_swap}, {'free ' .. getPercentage(free + free_swap), free + free_swap}, {'buff_cache ' .. getPercentage(buff_cache), buff_cache} } end end, ramgraph_widget ) ramgraph_widget:buttons( awful.util.table.join( awful.button({}, 1, function() popup:get_widget().data_list = { {'used ' .. getPercentage(used + used_swap), used + used_swap}, {'free ' .. getPercentage(free + free_swap), free + free_swap}, {'buff_cache ' .. getPercentage(buff_cache), buff_cache} } if popup.visible then popup.visible = not popup.visible else popup:move_next_to(mouse.current_widget_geometry) end end) ) ) return ramgraph_widget end return setmetatable(ramgraph_widget, { __call = function(_, ...) return worker(...) end })
Use popup widget and theme colors for ram-widget.
Use popup widget and theme colors for ram-widget. ram-widget now uses an awful.popup widget. This gives a more consistent appearance with the other widget and displays the popup next to the wibar widget, instead of always top right. Instead of fixed colors, I selected appropriate symbolic colors from beautiful themes. Therefore, the widget now reacts to theming. Naturally, The selection of colors are a matter of taste. Fixes #201.
Lua
mit
streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets
442b13531a187b653a7c4b9d181d7095f4320b6d
src/websocket/client_ev.lua
src/websocket/client_ev.lua
local socket = require'socket' local tools = require'websocket.tools' local frame = require'websocket.frame' local handshake = require'websocket.handshake' local debug = require'debug' local tconcat = table.concat local tinsert = table.insert local ev = function(ws) ws = ws or {} local ev = require'ev' local sock local loop = ws.loop or ev.Loop.default local fd local message_io local handshake_io local async_send local self = {} self.state = 'CLOSED' local close_timer local user_on_message local user_on_close local user_on_open local user_on_error local on_error = function(s,err) if user_on_error then user_on_error(s,err) else print('Error',err) end end local on_close = function(was_clean,code,reason) if close_timer then close_timer:stop(loop) close_timer = nil end if message_io then message_io:stop(loop) end self.state = 'CLOSED' if user_on_close then user_on_close(self,was_clean,code,reason or '') end sock:shutdown() sock:close() end local on_open = function() self.state = 'OPEN' if user_on_open then user_on_open(self) end end local handle_socket_err = function(err) if err == 'closed' then if self.state ~= 'CLOSED' then on_close(false,1006,'') end else on_error(err) end end local on_message = function(message,opcode) if opcode == frame.TEXT or opcode == frame.BINARY then if user_on_message then user_on_message(self,message,opcode) end elseif opcode == frame.CLOSE then if self.state ~= 'CLOSING' then self.state = 'CLOSING' local code,reason = frame.decode_close(message) local encoded = frame.encode_close(code) encoded = frame.encode(encoded,frame.CLOSE,true) async_send(encoded, function() on_close(true,code or 1005,reason) end,handle_socket_err) else on_close(true,code or 1005,reason) end end end self.send = function(_,message,opcode) local encoded = frame.encode(message,opcode or frame.TEXT,true) async_send(encoded, nil, handle_socket_error) end local connect = function(_,params) if self.state ~= 'CLOSED' then on_error(self,'wrong state') return end self.state = 'CONNECTING' local protocol,host,port,uri = tools.parse_url(params.url) if protocol ~= 'ws' then error('Protocol not supported:'..protocol) end assert(not sock) sock = socket.tcp() fd = sock:getfd() assert(fd > -1) -- set non blocking sock:settimeout(0) sock:setoption('tcp-nodelay',true) async_send = require'websocket.ev_common'.async_send(sock,loop) user_on_open = params.on_open or user_on_open ev.IO.new( function(loop,connect_io) connect_io:stop(loop) local key = tools.generate_key() local req = handshake.upgrade_request { key = key, host = host, port = port, protocols = {params.protocol or ''}, origin = ws.origin, uri = uri } async_send( req, function() local resp = {} local last assert(sock:getfd() > -1) handshake_io = ev.IO.new( function(loop,read_io) repeat local line,err,part = sock:receive('*l') if line then if last then line = last..line last = nil end resp[#resp+1] = line elseif err ~= 'timeout' then read_io:stop(loop) handle_socket_err(err) return else last = part return end until line == '' read_io:stop(loop) handshake_io = nil local response = table.concat(resp,'\r\n') local headers = handshake.http_headers(response) local expected_accept = handshake.sec_websocket_accept(key) if headers['sec-websocket-accept'] ~= expected_accept then local msg = 'Websocket Handshake failed: Invalid Sec-Websocket-Accept (expected %s got %s)' msg = msg:format(expected_accept,headers['sec-websocket-accept'] or 'nil') on_error(self,msg) return end message_io = require'websocket.ev_common'.message_io( sock,loop, on_message, handle_socket_err) on_open(self) end,fd,ev.READ) handshake_io:start(loop)-- handshake end, handle_socket_err) end,fd,ev.WRITE):start(loop)-- connect local _,err = sock:connect(host,port) assert(_ == nil) if err ~= 'timeout' then error('Websocket could not connect to '..ws.url) end end self.on_close = function(_,on_close_arg) user_on_close = on_close_arg end self.on_error = function(_,on_error_arg) user_on_error = on_error_arg end self.on_open = function(_,on_open_arg) user_on_open = on_open_arg end self.on_message = function(_,on_message_arg) user_on_message = on_message_arg end self.close = function(_,code,reason,timeout) if self.state == 'CONNECTING' then self.state = 'CLOSING' assert(handshake_io) assert(not message_io) handshake_io:stop(loop) handshake_io = nil on_close(false,1006,'not open') return elseif self.state == 'OPEN' then assert(not handshake_io) assert(message_io) self.state = 'CLOSING' timeout = timeout or 3 local encoded = frame.encode_close(code or 1000,reason) encoded = frame.encode(encoded,frame.CLOSE,true) -- this should let the other peer confirm the CLOSE message -- by 'echoing' the message. async_send(encoded) close_timer = ev.Timer.new(function() close_timer = nil on_close(false,1006,'timeout') end,timeout) close_timer:start(loop) end end self.connect = connect return self end return ev
local socket = require'socket' local tools = require'websocket.tools' local frame = require'websocket.frame' local handshake = require'websocket.handshake' local debug = require'debug' local tconcat = table.concat local tinsert = table.insert local ev = function(ws) ws = ws or {} local ev = require'ev' local sock local loop = ws.loop or ev.Loop.default local fd local message_io local handshake_io local async_send local self = {} self.state = 'CLOSED' local close_timer local user_on_message local user_on_close local user_on_open local user_on_error local on_close = function(was_clean,code,reason) if close_timer then close_timer:stop(loop) close_timer = nil end if handshake_io then handshake_io:clear_pending(loop) handshake_io:stop(loop) handshake_io = nil end if message_io then message_io:clear_pending(loop) message_io:stop(loop) message_io = nil end self.state = 'CLOSED' if sock then sock:shutdown() sock:close() sock = nil end if user_on_close then user_on_close(self,was_clean,code,reason or '') end end local on_error = function(err) if user_on_error then user_on_error(self,err) else print('Error',err) end end local on_open = function() self.state = 'OPEN' if user_on_open then user_on_open(self) end end local handle_socket_err = function(err) if err == 'closed' then if self.state == 'OPEN' then on_close(false,1006,'') end else on_error(err) end end local on_message = function(message,opcode) if opcode == frame.TEXT or opcode == frame.BINARY then if user_on_message then user_on_message(self,message,opcode) end elseif opcode == frame.CLOSE then if self.state ~= 'CLOSING' then self.state = 'CLOSING' local code,reason = frame.decode_close(message) local encoded = frame.encode_close(code) encoded = frame.encode(encoded,frame.CLOSE,true) async_send(encoded, function() on_close(true,code or 1005,reason) end,handle_socket_err) else on_close(true,code or 1005,reason) end end end self.send = function(_,message,opcode) local encoded = frame.encode(message,opcode or frame.TEXT,true) async_send(encoded, nil, handle_socket_error) end local connect = function(_,params) if self.state ~= 'CLOSED' then on_error('wrong state') return end local protocol,host,port,uri = tools.parse_url(params.url) if protocol ~= 'ws' then on_error('bad protocol') return end self.state = 'CONNECTING' assert(not sock) sock = socket.tcp() fd = sock:getfd() assert(fd > -1) -- set non blocking sock:settimeout(0) sock:setoption('tcp-nodelay',true) async_send = require'websocket.ev_common'.async_send(sock,loop) user_on_open = params.on_open or user_on_open ev.IO.new( function(loop,connect_io) connect_io:stop(loop) local key = tools.generate_key() local req = handshake.upgrade_request { key = key, host = host, port = port, protocols = {params.protocol or ''}, origin = ws.origin, uri = uri } async_send( req, function() local resp = {} local last assert(sock:getfd() > -1) handshake_io = ev.IO.new( function(loop,read_io) repeat local line,err,part = sock:receive('*l') if line then if last then line = last..line last = nil end resp[#resp+1] = line elseif err ~= 'timeout' then read_io:stop(loop) handle_socket_err(err) return else last = part return end until line == '' read_io:stop(loop) handshake_io = nil local response = table.concat(resp,'\r\n') local headers = handshake.http_headers(response) local expected_accept = handshake.sec_websocket_accept(key) if headers['sec-websocket-accept'] ~= expected_accept then on_error('accept failed') return end message_io = require'websocket.ev_common'.message_io( sock,loop, on_message, handle_socket_err) on_open(self) end,fd,ev.READ) handshake_io:start(loop)-- handshake end, handle_socket_err) end,fd,ev.WRITE):start(loop)-- connect local _,err = sock:connect(host,port) assert(_ == nil) if err ~= 'timeout' then error('Websocket could not connect to '..ws.url) end end self.on_close = function(_,on_close_arg) user_on_close = on_close_arg end self.on_error = function(_,on_error_arg) user_on_error = on_error_arg end self.on_open = function(_,on_open_arg) user_on_open = on_open_arg end self.on_message = function(_,on_message_arg) user_on_message = on_message_arg end self.close = function(_,code,reason,timeout) if self.state == 'CONNECTING' then self.state = 'CLOSING' on_close(false,1006,'') return elseif self.state == 'OPEN' then self.state = 'CLOSING' timeout = timeout or 3 local encoded = frame.encode_close(code or 1000,reason) encoded = frame.encode(encoded,frame.CLOSE,true) -- this should let the other peer confirm the CLOSE message -- by 'echoing' the message. async_send(encoded) close_timer = ev.Timer.new(function() close_timer = nil on_close(false,1006,'timeout') end,timeout) close_timer:start(loop) end end self.connect = connect return self end return ev
fix error handling and reconnect
fix error handling and reconnect
Lua
mit
lipp/lua-websockets,KSDaemon/lua-websockets,enginix/lua-websockets,lipp/lua-websockets,OptimusLime/lua-websockets,KSDaemon/lua-websockets,OptimusLime/lua-websockets,lipp/lua-websockets,enginix/lua-websockets,OptimusLime/lua-websockets,enginix/lua-websockets,KSDaemon/lua-websockets
08d2c18d4374092197def0bb500d09bfd14b0255
src/game/StarterPlayer/StarterPlayerScripts/CameraScript.lua
src/game/StarterPlayer/StarterPlayerScripts/CameraScript.lua
-- ClassName: LocalScript local OFFSET = Vector3.new(-45, 45, 45) local FIELD_OF_VIEW = 25 local player = game.Players.LocalPlayer local camera = workspace.CurrentCamera local run = game:GetService("RunService") camera.FieldOfView = FIELD_OF_VIEW local function lookAt(pos) local cameraPos = pos + OFFSET camera.CoordinateFrame = CFrame.new(cameraPos, pos) end local function onRenderStep() local character = player.Character local primaryPart = character.PrimaryPart if character and primaryPart then lookAt(primaryPart.Position) end end run:BindToRenderStep("Camera", Enum.RenderPriority.Camera.Value, onRenderStep)
-- ClassName: LocalScript local OFFSET = Vector3.new(-45, 45, 45) local FIELD_OF_VIEW = 25 local player = game.Players.LocalPlayer local camera = workspace.CurrentCamera local run = game:GetService("RunService") camera.FieldOfView = FIELD_OF_VIEW local function lookAt(pos) local cameraPos = pos + OFFSET camera.CoordinateFrame = CFrame.new(cameraPos, pos) end local function onRenderStep() local character = player.Character local rootPart = character:FindFirstChild("HumanoidRootPart") if character and rootPart then lookAt(rootPart.Position) end end run:BindToRenderStep("Camera", Enum.RenderPriority.Camera.Value, onRenderStep)
Fix the camera slightly bobbing along to the character
Fix the camera slightly bobbing along to the character The character's PrimaryPart (its head) is animated, along with the rest of the body, making the camera bob up and down slightly when the "breathing" animation is playing. It's hardly noticable, but definitly needs to be fixed. We're locking the camera onto the HumanoidRootPart to fix this problem, as it remains static.
Lua
mit
VoxelDavid/echo-ridge
090f0468ec4664d444899b3f9309da3ad8e2732b
spec/helpers/perf/git.lua
spec/helpers/perf/git.lua
local perf local logger = require("spec.helpers.perf.logger") local utils = require("spec.helpers.perf.utils") local my_logger = logger.new_logger("[git]") local git_temp_repo = "/tmp/perf-temp-repo" local function is_git_repo() -- reload the perf module, for circular dependency issue perf = require("spec.helpers.perf") local _, err = perf.execute("git rev-parse HEAD") return err == nil end -- is this test based on git versions: e.g. have we git checkout versions? local function is_git_based() return package.path:find(git_temp_repo) end local function git_checkout(version) -- reload the perf module, for circular dependency issue perf = require("spec.helpers.perf") local _, err = perf.execute("which git") if err then error("git binary not found") end if not is_git_repo() then error("not in a git repo") end for _, cmd in ipairs({ "rm -rf " .. git_temp_repo, "git clone . " .. git_temp_repo, "cp -r .git/refs/ " .. git_temp_repo .. "/.git/.", -- version is sometimes a hash so we can't always use -b "cd " .. git_temp_repo .. " && git checkout " ..version }) do local _, err = perf.execute(cmd, { logger = my_logger.log_exec }) if err then error("error preparing temporary repo: " .. err) end end utils.add_lua_package_paths(git_temp_repo) return git_temp_repo end local function git_restore() return utils.restore_lua_package_paths() end local function get_kong_version(raw) -- unload the module if it's previously loaded package.loaded["kong.meta"] = nil local ok, meta, _ = pcall(require, "kong.meta") if ok then return meta._VERSION end error("can't read Kong version from kong.meta: " .. (meta or "nil")) end return { is_git_repo = is_git_repo, is_git_based = is_git_based, git_checkout = git_checkout, git_restore = git_restore, get_kong_version = get_kong_version, }
local perf local logger = require("spec.helpers.perf.logger") local utils = require("spec.helpers.perf.utils") local my_logger = logger.new_logger("[git]") local git_temp_repo = "/tmp/perf-temp-repo" local function is_git_repo() -- reload the perf module, for circular dependency issue perf = require("spec.helpers.perf") local _, err = perf.execute("git rev-parse HEAD") return err == nil end -- is this test based on git versions: e.g. have we git checkout versions? local function is_git_based() return package.path:find(git_temp_repo) end local function git_checkout(version) -- reload the perf module, for circular dependency issue perf = require("spec.helpers.perf") local _, err = perf.execute("which git") if err then error("git binary not found") end if not is_git_repo() then error("not in a git repo") end for _, cmd in ipairs({ "rm -rf " .. git_temp_repo, "git clone . " .. git_temp_repo, "cp -r .git/refs/ " .. git_temp_repo .. "/.git/.", -- version is sometimes a hash so we can't always use -b "cd " .. git_temp_repo .. " && git checkout " ..version }) do local _, err = perf.execute(cmd, { logger = my_logger.log_exec }) if err then error("error preparing temporary repo: " .. err) end end utils.add_lua_package_paths(git_temp_repo) return git_temp_repo end local function git_restore() return utils.restore_lua_package_paths() end local version_map_table = { -- temporary hack, we usually bump version when released, but it's -- true for master currently ["3.0.0"] = "2.8.1", } local function get_kong_version(raw) -- unload the module if it's previously loaded package.loaded["kong.meta"] = nil local ok, meta, _ = pcall(require, "kong.meta") local v = meta._VERSION if not raw and version_map_table[v] then return version_map_table[v] end if ok then return v end error("can't read Kong version from kong.meta: " .. (meta or "nil")) end return { is_git_repo = is_git_repo, is_git_based = is_git_based, git_checkout = git_checkout, git_restore = git_restore, get_kong_version = get_kong_version, }
tests(perf) fix version mapping
tests(perf) fix version mapping
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
4bb9c3424d89a932e1f1bee1411baea52ad435ab
onion2web.lua
onion2web.lua
local socks5 = require 'socks5' local ngx = require 'ngx' local onion2web = {} local hidden_base = "(" .. string.rep("%w", 16) .. ")" local hidden_onion = hidden_base .. '%.onion' local show_confirmation_form = function() local host = ngx.req.get_headers()['Host'] local onion = host:match(hidden_base) .. '.onion' if ngx.req.get_method() == 'POST' and ngx.var.uri:match('^/confirm') then ngx.header['Set-Cookie'] = 'onion2web_confirmed=true;' return ngx.redirect("/") end ngx.say(([[<html> <head> <title>Onion2web</title> <body> <h1>Onion2web</h1> <br/><br/> <b>%s does not host this content</b>; the service is simply a proxy connecting Internet users to content hosted inside the <a href="https://www.torproject.org/docs/hidden-services.html.en"> Tor network.</a> Please be aware that when you access this site through a Onion2web proxy you are not anonymous. To obtain anonymity, you are strongly advised to <a href="https://www.torproject.org/download/"> download the Tor Browser Bundle</a> and access this content over Tor. <br> By accessing this site you acknowledge that you have understood: <ul> <li>What Tor Hidden Services are and how they works;</li> <li>What Onion2web is and how it works;</li> <li>That Onion2web operator running cannot block this site in any way;</li> <li>The content of the %s website is responsibility of it's editor.</li> </ul> <br/> <div>By the way, just to be clear:</div> <br/><br/> <center><b>THIS SERVER IS A PROXY AND IT'S NOT HOSTING THE TOR HIDDEN SERVICE SITE %s</b> <br/><br/> <form method="post" action="/confirm"> <input type="submit" value="I agree with the terms, let me access the content"/> </form> </center> <a href="https://github.com/starius/onion2web"> <img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub" > </a> </body> </html> ]]):format(host, onion, onion)) end onion2web.handle_onion2web = function(onion_replacement, torhost, torport, confirmation) if not torhost then torhost = '127.0.0.1' end if not torport then torport = 9050 end if confirmation == nil then confirmation = true end local repl = hidden_base .. onion_replacement local host = ngx.req.get_headers()['Host'] if not host:match('^' .. repl .. '$') then ngx.say('Bad domain: ' .. host) return end local cookies = ngx.req.get_headers()['Cookie'] if confirmation and (not cookies or not cookies:match('onion2web_confirmed=true')) then show_confirmation_form() return end socks5.handle_request(torhost, torport, function(clheader) return clheader :gsub("HTTP/1.1(%c+)", "HTTP/1.0%1") :gsub(repl, "%1.onion") :gsub("Connection: keep%-alive", "Connection: close") :gsub("Accept%-Encoding: [%w%p ]+%c+", "") end, function(soheader) return soheader :gsub(hidden_onion, "%1" .. onion_replacement) end) end return onion2web
local socks5 = require 'socks5' local ngx = require 'ngx' local onion2web = {} local hidden_base = "(" .. string.rep("%w", 16) .. ")" local hidden_onion = hidden_base .. '%.onion' local show_confirmation_form = function() local host = ngx.req.get_headers()['Host'] local onion = host:match(hidden_base) .. '.onion' if ngx.req.get_method() == 'POST' and ngx.var.uri:match('^/confirm') then ngx.header['Set-Cookie'] = 'onion2web_confirmed=true;' return ngx.redirect("/") end ngx.say(([[<html> <head> <title>Onion2web</title> <body> <h1>Onion2web</h1> <br/><br/> <b>%s does not host this content</b>; the service is simply a proxy connecting Internet users to content hosted inside the <a href="https://www.torproject.org/docs/hidden-services.html.en"> Tor network.</a> Please be aware that when you access this site through a Onion2web proxy you are not anonymous. To obtain anonymity, you are strongly advised to <a href="https://www.torproject.org/download/"> download the Tor Browser Bundle</a> and access this content over Tor. <br> By accessing this site you acknowledge that you have understood: <ul> <li>What Tor Hidden Services are and how they works;</li> <li>What Onion2web is and how it works;</li> <li>That Onion2web operator running cannot block this site in any way;</li> <li>The content of the %s website is responsibility of it's editor.</li> </ul> <br/> <div>By the way, just to be clear:</div> <br/><br/> <center><b>THIS SERVER IS A PROXY AND IT'S NOT HOSTING THE TOR HIDDEN SERVICE SITE %s</b> <br/><br/> <form method="post" action="/confirm"> <input type="submit" value="I agree with the terms, let me access the content"/> </form> </center> <a href="https://github.com/starius/onion2web"> <img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub" > </a> </body> </html> ]]):format(host, onion, onion)) end onion2web.handle_onion2web = function(onion_replacement, torhost, torport, confirmation) if not torhost then torhost = '127.0.0.1' end if not torport then torport = 9050 end if confirmation == nil then confirmation = true end local repl = hidden_base .. onion_replacement local host = ngx.req.get_headers()['Host'] if not host:match('^' .. repl .. '$') and not host:match('%.' .. repl .. '$') then ngx.say('Bad domain: ' .. host) return end local cookies = ngx.req.get_headers()['Cookie'] if confirmation and (not cookies or not cookies:match('onion2web_confirmed=true')) then show_confirmation_form() return end socks5.handle_request(torhost, torport, function(clheader) return clheader :gsub("HTTP/1.1(%c+)", "HTTP/1.0%1") :gsub(repl, "%1.onion") :gsub("Connection: keep%-alive", "Connection: close") :gsub("Accept%-Encoding: [%w%p ]+%c+", "") end, function(soheader) return soheader :gsub(hidden_onion, "%1" .. onion_replacement) end) end return onion2web
allow subdomains of hidden services
allow subdomains of hidden services fix #5
Lua
mit
starius/onion2web
642d1179a840a6651484b95e2168646c6c4b2116
scripts/chem_notepad.lua
scripts/chem_notepad.lua
dofile("common.inc"); function doit() local tree = loadNotes("scripts/chem-cheap.txt"); browseMenu(tree); end function browseMenu(tree) local done = false; local tags = {}; local nextIndex = 1; while not done do local y = 0; for i=1,#tags do y = y + 30; lsPrint(40, y, 0, 0.9, 0.9, 0xd0d0d0ff, tags[i]); end local nextTags = lookupData(tree, tags); if not nextTags then lsPrint(10, y, 0, 0.7, 0.7, 0xffd0d0ff, "No note found"); y = y + 30; elseif type(nextTags) == "table" then table.sort(nextTags); for i=1,#nextTags do local x = 40; if i % 2 == 0 then x = 160; else y = y + 30; end if lsButtonText(x, y, 0, 100, 0xd0ffd0ff, nextTags[i]) then table.insert(tags, nextTags[i]); end end y = y + 30; -- if nextTags[1] ~= "" then -- table.insert(nextTags, 1, ""); -- end -- nextIndex = lsDropdown("NoteIndex", 40, y, 0, 250, nextIndex, nextTags); -- if nextIndex ~= 1 then -- table.insert(tags, nextTags[nextIndex]); -- nextIndex = 1; -- end else y = y + 30; lsPrintWrapped(10, y, 0, lsScreenX - 20, 0.7, 0.7, 0xffffffff, nextTags); end if lsButtonText(10, lsScreenY - 30, 0, 100, 0xffffffff, "Restart") then if #tags > 0 then -- table.remove(tags); tags = {}; nextIndex = 1; else -- done = true; end end if lsButtonText(lsScreenX - 110, lsScreenY - 30, 0, 100, 0xffffffff, "End Script") then error(quit_message); end checkBreak(); lsSleep(tick_delay); lsDoFrame(); end end function setLine(tree, line) --local sections = csplit(line, "|"); local sections = explode("|",line); if #sections ~= 2 then error("Cannot parse line: " .. line); end --local tags = csplit(sections[1], ","); -- local tags = csplit(",",sections[1]); local tags = explode(",",sections[1]); local data = sections[2]; setData(tree, tags, data); end function setData(tree, tags, data, index) if not index then index = 1; end if #tags == index then tree[tags[index]] = data; else local current = tags[index]; if type(tree[current]) ~= "table" then tree[current] = {}; end setData(tree[current], tags, data, index + 1); end end function lookupData(tree, tags, index) if not index then index = 1; end local result = {}; if tree == nil then result = nil; elseif type(tree) ~= "table" then result = tree; elseif #tags < index then for key,value in pairs(tree) do table.insert(result, key); end else local current = tags[index]; result = lookupData(tree[current], tags, index + 1); end return result; end function dataToLine(prefix, value) local result = ""; for i=1,#prefix do result = result .. prefix; if i ~= #prefix then result = result .. ","; end end result = result .. "|" .. value; return result; end function lookupAllData(prefix, tree, result) for key,value in pairs(tree) do table.insert(prefix, key); if type(value) == "table" then lookupAllData(prefix, value, result); else table.insert(result, dataToLine(prefix, value)); end table.remove(prefix); end end function loadNotes(filename) local result = {}; local file = io.open(filename, "a+"); io.close(file); for line in io.lines(filename) do setLine(result, line); end return result; end function saveNotes(filename, tree) local file = io.open(filename, "w+"); local lines = {}; lookupAllData({}, tree, lines); for line in lines do file:write(line .. "\n"); end io.close(file); end -- Added in an explode function (delimiter, string) to deal with broken csplit. function explode(d,p) local t, ll t={} ll=0 if(#p == 1) then return {p} end while true do l = string.find(p, d, ll, true) -- find the next d in the string if l ~= nil then -- if "not not" found then.. table.insert(t, string.sub(p,ll,l-1)) -- Save it in our array. ll = l + 1 -- save just after where we found it for searching next time. else table.insert(t, string.sub(p,ll)) -- Save what's left in our array. break -- Break at end, as it should be, according to the lua manual. end end return t end
dofile("common.inc"); function doit() local tree = loadNotes("scripts/chem-cheap.txt"); browseMenu(tree); end function browseMenu(tree) local done = false; local tags = {}; local nextIndex = 1; while not done do local y = 0; for i=1,#tags do y = y + 30; lsPrint(40, y, 0, 0.9, 0.9, 0xd0d0d0ff, tags[i]); end local nextTags = lookupData(tree, tags); if not nextTags then lsPrint(10, y, 0, 0.7, 0.7, 0xffd0d0ff, "No note found"); y = y + 30; elseif type(nextTags) == "table" then table.sort(nextTags); for i=1,#nextTags do local x = 40; if i % 2 == 0 then x = 160; else y = y + 30; end if lsButtonText(x, y, 0, 100, 0xd0ffd0ff, nextTags[i]) then table.insert(tags, nextTags[i]); end end y = y + 30; -- if nextTags[1] ~= "" then -- table.insert(nextTags, 1, ""); -- end -- nextIndex = lsDropdown("NoteIndex", 40, y, 0, 250, nextIndex, nextTags); -- if nextIndex ~= 1 then -- table.insert(tags, nextTags[nextIndex]); -- nextIndex = 1; -- end else y = y + 30; lsPrintWrapped(10, y, 0, lsScreenX - 20, 0.7, 0.7, 0xffffffff, nextTags); end if lsButtonText(10, lsScreenY - 30, 0, 100, 0xffffffff, "Restart") then if #tags > 0 then -- table.remove(tags); tags = {}; nextIndex = 1; else -- done = true; end end if lsButtonText(lsScreenX - 110, lsScreenY - 30, 0, 100, 0xffffffff, "End Script") then error(quit_message); end checkBreak(); lsSleep(tick_delay); lsDoFrame(); end end function setLine(tree, line) --local sections = csplit(line, "|"); local sections = explode("|",line); if #sections ~= 2 then error("Cannot parse line: " .. line); end --local tags = csplit(sections[1], ","); local tags = csplit(",",sections[1]); local data = sections[2]; setData(tree, tags, data); end function setData(tree, tags, data, index) if not index then index = 1; end if #tags == index then tree[tags[index]] = data; else local current = tags[index]; if type(tree[current]) ~= "table" then tree[current] = {}; end setData(tree[current], tags, data, index + 1); end end function lookupData(tree, tags, index) if not index then index = 1; end local result = {}; if tree == nil then result = nil; elseif type(tree) ~= "table" then result = tree; elseif #tags < index then for key,value in pairs(tree) do table.insert(result, key); end else local current = tags[index]; result = lookupData(tree[current], tags, index + 1); end return result; end function dataToLine(prefix, value) local result = ""; for i=1,#prefix do result = result .. prefix; if i ~= #prefix then result = result .. ","; end end result = result .. "|" .. value; return result; end function lookupAllData(prefix, tree, result) for key,value in pairs(tree) do table.insert(prefix, key); if type(value) == "table" then lookupAllData(prefix, value, result); else table.insert(result, dataToLine(prefix, value)); end table.remove(prefix); end end function loadNotes(filename) local result = {}; local file = io.open(filename, "a+"); io.close(file); for line in io.lines(filename) do setLine(result, line); end return result; end function saveNotes(filename, tree) local file = io.open(filename, "w+"); local lines = {}; lookupAllData({}, tree, lines); for line in lines do file:write(line .. "\n"); end io.close(file); end -- Added in an explode function (delimiter, string) to deal with broken csplit. function explode(d,p) local t, ll t={} ll=0 if(#p == 1) then return {p} end while true do l = string.find(p, d, ll, true) -- find the next d in the string if l ~= nil then -- if "not not" found then.. table.insert(t, string.sub(p,ll,l-1)) -- Save it in our array. ll = l + 1 -- save just after where we found it for searching next time. else table.insert(t, string.sub(p,ll)) -- Save what's left in our array. break -- Break at end, as it should be, according to the lua manual. end end return t end
Revert "chem_notepad.lua - Fix missing text on buttons (missing explode function)"
Revert "chem_notepad.lua - Fix missing text on buttons (missing explode function)" This reverts commit b4b67b1f75be5e4014240bb5c5103da6579666a1.
Lua
mit
DashingStrike/Automato-ATITD,DashingStrike/Automato-ATITD
3fa0288a8ab47c4b38f5c6b82371261c7e28716c
shared/iguana/channel.lua
shared/iguana/channel.lua
iguana.channel = {} require 'file' function iguana.channel.getTranslators(ChannelConfig) local Info = {} local C = ChannelConfig.channel; if C.to_mapper then Info.to = C.to_mapper.guid:nodeValue() end if C.from_mapper then Info.from = C.from_mapper.guid:nodeValue() end if C.use_message_filter:nodeValue() == 'true' and C.message_filter and C.message_filter.use_translator_filter and C.message_filter.translator_guid then Info.filter = C.message_filter.translator_guid:nodeValue() end if C.from_llp_listener and C.from_llp_listener.ack_script then Info.ack = C.from_llp_listener.ack_script:nodeValue() end if C.from_http and C.from_http.guid then Info.http = C.from_http.guid:nodeValue() end return Info end local function ChannelDefinition(Dir, Name) local FullFileName = Dir..'/'..Name..'.xml' trace(FullFileName) local Content = os.fs.readFile(FullFileName) return xml.parse{data=Content} end local function ProjectFile(MainDir) local D = os.fs.readFile(MainDir.."/project.prj") return json.parse{data=D} end local function AddFile(Dir, File, Content) local Parts = File:split('/') local SubDir = Dir for i = 1, #Parts-1 do if #Parts[i] > 0 then if not SubDir[Parts[i]] then SubDir[Parts[i]] = {} end SubDir = SubDir[Parts[i]] end end SubDir[Parts[#Parts]] = Content end local function BuildTransZip(RepoDir, ProjectDir, TargetGuid, ScratchDir) local Dir = {} local MainDir = RepoDir..'/'..ProjectDir..'/' for K,V in os.fs.glob(MainDir..'*') do local Content = os.fs.readFile(K) AddFile(Dir,TargetGuid..'/'..K:sub(#MainDir), Content) end trace(Dir) local P = ProjectFile(MainDir) for i = 1, #P.OtherDependencies do local Content = os.fs.readFile(RepoDir..'/other/'..P.OtherDependencies[i]) AddFile(Dir, '/other/'..P.OtherDependencies[i], Content) end for i = 1, #P.LuaDependencies do local Content = os.fs.readFile(RepoDir..'/shared/'..P.LuaDependencies[i]:gsub("%.", '/')..'.lua') AddFile(Dir, '/shared/'..P.LuaDependencies[i]:gsub("%.", "/")..'.lua', Content) end trace(Dir) os.ts.time() local ZipData2 = filter.zip.deflate(Dir) os.ts.time() return filter.base64.enc(ZipData2) end function iguana.channel.add(T) local RepoDir = T.dir local Definition = T.definition local Api = T.api local ScratchDir = T.scratch os.ts.time() local ChanDef = ChannelDefinition(RepoDir, Definition) if T.name then ChanDef.channel.name = T.name end os.ts.time() local NewChanDef = Api:addChannel{config=ChanDef, live=true} os.ts.time() local TranList = iguana.channel.getTranslators(NewChanDef) os.ts.time() for TransType,Guid in pairs(TranList) do local Start = os.ts.time() local ZipData = BuildTransZip(RepoDir, Definition..'_'..TransType, Guid, ScratchDir) local EndTime = os.ts.time() trace(EndTime-Start) os.ts.time() Api:importProject{project=ZipData, guid=Guid, sample_data='replace', live=true} os.ts.time() Api:saveProjectMilestone{guid=Guid, milestone_name='Channel Manager '..os.date(), live=true} os.ts.time() end os.ts.time() return NewChanDef end local function MergeTree(From, To) for k,v in pairs(From) do if type(v) == 'table' then if not To[k] then To[k] = {} end MergeTree(v, To[k]) end if type(v) == 'string' and not k:find("::") then -- Metadata To[k] = v end end end local function ExpandTranslatorZip(Result, Guid, Name, ZipContent) local D = filter.base64.dec(ZipContent) local T = filter.zip.inflate(D) trace(T) Result[Name] = {} MergeTree(T[Guid], Result[Name]) if (T.other) then if not Result.other then Result.other ={} end MergeTree(T.other, Result.other) end if (T.shared) then if not Result.shared then Result.shared = {} end MergeTree(T.shared, Result.shared) end end function iguana.channel.export(T) local Result = {} local Api = T.api local ChannelName = T.name local ChanDef = Api:getChannelConfig{name=ChannelName, live=true} Result[ChannelName..'.xml'] = tostring(ChanDef) local TranList = iguana.channel.getTranslators(ChanDef) for TranType,GUID in pairs(TranList) do local ZipContent = Api:exportProject{guid=GUID, live=true} ExpandTranslatorZip(Result, GUID, ChannelName.."_"..TranType, ZipContent) end return Result end function iguana.channel.exists(Name) local X = xml.parse{data=iguana.status()} for i = 1, X.IguanaStatus:childCount("Channel") do local C = X.IguanaStatus:child("Channel", i) if tostring(C.Name) == Name then return true; end end return false end
iguana.channel = {} require 'file' function iguana.channel.getTranslators(ChannelConfig) local Info = {} local C = ChannelConfig.channel; if C.to_mapper then Info.to = C.to_mapper.guid:nodeValue() end if C.from_mapper then Info.from = C.from_mapper.guid:nodeValue() end if C.use_message_filter:nodeValue() == 'true' and C.message_filter and C.message_filter.use_translator_filter and C.message_filter.translator_guid then Info.filter = C.message_filter.translator_guid:nodeValue() end if C.from_llp_listener and C.from_llp_listener.ack_script then Info.ack = C.from_llp_listener.ack_script:nodeValue() end if C.from_http and C.from_http.guid then Info.http = C.from_http.guid:nodeValue() end return Info end local function ChannelDefinition(Dir, Name) local FullFileName = Dir..'/'..Name..'.xml' trace(FullFileName) local Content = os.fs.readFile(FullFileName) return xml.parse{data=Content} end local function ProjectFile(MainDir) local D = os.fs.readFile(MainDir.."/project.prj") return json.parse{data=D} end local function AddFile(Dir, File, Content) local Parts = File:split('/') local SubDir = Dir for i = 1, #Parts-1 do if #Parts[i] > 0 then if not SubDir[Parts[i]] then SubDir[Parts[i]] = {} end SubDir = SubDir[Parts[i]] end end SubDir[Parts[#Parts]] = Content end local function BuildTransZip(RepoDir, ProjectDir, TargetGuid, ScratchDir) local Dir = {} local MainDir = RepoDir..'/'..ProjectDir..'/' MainDir = os.fs.abspath(MainDir) for K,V in os.fs.glob(MainDir..'*') do local Content = os.fs.readFile(K) AddFile(Dir,TargetGuid..'/'..K:sub(#MainDir), Content) end trace(Dir) local P = ProjectFile(MainDir) for i = 1, #P.OtherDependencies do local Content = os.fs.readFile(RepoDir..'/other/'..P.OtherDependencies[i]) AddFile(Dir, '/other/'..P.OtherDependencies[i], Content) end for i = 1, #P.LuaDependencies do local Content = os.fs.readFile(RepoDir..'/shared/'..P.LuaDependencies[i]:gsub("%.", '/')..'.lua') AddFile(Dir, '/shared/'..P.LuaDependencies[i]:gsub("%.", "/")..'.lua', Content) end trace(Dir) os.ts.time() local ZipData2 = filter.zip.deflate(Dir) os.ts.time() return filter.base64.enc(ZipData2) end function iguana.channel.add(T) local RepoDir = T.dir local Definition = T.definition local Api = T.api local ScratchDir = T.scratch os.ts.time() local ChanDef = ChannelDefinition(RepoDir, Definition) if T.name then ChanDef.channel.name = T.name end os.ts.time() local NewChanDef = Api:addChannel{config=ChanDef, live=true} os.ts.time() local TranList = iguana.channel.getTranslators(NewChanDef) os.ts.time() for TransType,Guid in pairs(TranList) do local Start = os.ts.time() local ZipData = BuildTransZip(RepoDir, Definition..'_'..TransType, Guid, ScratchDir) local EndTime = os.ts.time() trace(EndTime-Start) os.ts.time() Api:importProject{project=ZipData, guid=Guid, sample_data='replace', live=true} os.ts.time() Api:saveProjectMilestone{guid=Guid, milestone_name='Channel Manager '..os.date(), live=true} os.ts.time() end os.ts.time() return NewChanDef end local function MergeTree(From, To) for k,v in pairs(From) do if type(v) == 'table' then if not To[k] then To[k] = {} end MergeTree(v, To[k]) end if type(v) == 'string' and not k:find("::") then -- Metadata To[k] = v end end end local function ExpandTranslatorZip(Result, Guid, Name, ZipContent) local D = filter.base64.dec(ZipContent) local T = filter.zip.inflate(D) trace(T) Result[Name] = {} MergeTree(T[Guid], Result[Name]) if (T.other) then if not Result.other then Result.other ={} end MergeTree(T.other, Result.other) end if (T.shared) then if not Result.shared then Result.shared = {} end MergeTree(T.shared, Result.shared) end end function iguana.channel.export(T) local Result = {} local Api = T.api local ChannelName = T.name local ChanDef = Api:getChannelConfig{name=ChannelName, live=true} Result[ChannelName..'.xml'] = tostring(ChanDef) local TranList = iguana.channel.getTranslators(ChanDef) for TranType,GUID in pairs(TranList) do local ZipContent = Api:exportProject{guid=GUID, live=true} ExpandTranslatorZip(Result, GUID, ChannelName.."_"..TranType, ZipContent) end return Result end function iguana.channel.exists(Name) local X = xml.parse{data=iguana.status()} for i = 1, X.IguanaStatus:childCount("Channel") do local C = X.IguanaStatus:child("Channel", i) if tostring(C.Name) == Name then return true; end end return false end
Corrected bug for OS X - we need to resolve that
Corrected bug for OS X - we need to resolve that path to a fully qualified path to use it from truncation.
Lua
mit
interfaceware/iguana-web-apps,interfaceware/iguana-web-apps
537b5463d1720a751b9641174b55bee107b1f1bf
Quadtastic/Label.lua
Quadtastic/Label.lua
local Rectangle = require("Rectangle") local renderutils = require("Renderutils") local Label = {} unpack = unpack or table.unpack local margin_x = 4 Label.min_width = function(state, text) local textwidth = state.style.font and state.style.font:getWidth(text) return math.max(32, 2*margin_x + (textwidth or 32)) end -- Displays the passed in label. Returns, in this order, whether the label -- is active (i.e. getting clicked on), and whether the mouse is over this -- label. Label.draw = function(state, x, y, w, h, label, options) x = x or state.layout.next_x y = y or state.layout.next_y local textwidth = Label.min_width(state, label) w = w or textwidth h = h or 18 if options then -- center alignment if options.alignment == ":" then x = x + w/2 - textwidth /2 - margin_x -- right alignment elseif options.alignment == ">" then x = x + w - textwidth - 2 * margin_x end end state.layout.adv_x = w state.layout.adv_y = h -- Print label local fontcolor = options and options.font_color or {32, 63, 73, 255} love.graphics.setColor(unpack(fontcolor)) local margin_y = (h - 16) / 2 love.graphics.print(label or "", x + margin_x, y + margin_y) local active, hover = false, false -- Highlight if mouse is over button if state and state.mouse and Rectangle(x, y, w, h):contains(state.transform.unproject(state.mouse.x, state.mouse.y)) then hover = true if state.mouse.buttons[1] and state.mouse.buttons[1].pressed then active = true end end return active, hover end return Label
local Rectangle = require("Rectangle") local renderutils = require("Renderutils") local Label = {} unpack = unpack or table.unpack local margin_x = 4 Label.min_width = function(state, text) return state.style.font and state.style.font:getWidth(text) end -- Displays the passed in label. Returns, in this order, whether the label -- is active (i.e. getting clicked on), and whether the mouse is over this -- label. Label.draw = function(state, x, y, w, h, label, options) x = x or state.layout.next_x y = y or state.layout.next_y local textwidth = Label.min_width(state, label) w = w or textwidth h = h or 18 if options then -- center alignment if options.alignment == ":" then x = x + w/2 - textwidth /2 - margin_x -- right alignment elseif options.alignment == ">" then x = x + w - textwidth - 2 * margin_x end end state.layout.adv_x = w state.layout.adv_y = h -- Print label local fontcolor = options and options.font_color or {32, 63, 73, 255} love.graphics.setColor(unpack(fontcolor)) local margin_y = (h - 16) / 2 love.graphics.print(label or "", x + margin_x, y + margin_y) local active, hover = false, false -- Highlight if mouse is over button if state and state.mouse and Rectangle(x, y, w, h):contains(state.transform.unproject(state.mouse.x, state.mouse.y)) then hover = true if state.mouse.buttons[1] and state.mouse.buttons[1].pressed then active = true end end return active, hover end return Label
Fix margin shenanigans in text size calculation
Fix margin shenanigans in text size calculation
Lua
mit
25A0/Quadtastic,25A0/Quadtastic
5eb79f91c5c24d911ea0a44f049338ca98ac67d8
src/luacheck/profiler.lua
src/luacheck/profiler.lua
local socket = require "socket" local profiler = {} local metrics = { {name = "Wall", get = socket.gettime}, {name = "CPU", get = os.clock}, {name = "Memory", get = function() return collectgarbage("count") end} } local functions = { {name = "load", module = "cache"}, {name = "update", module = "cache"}, {name = "decode", module = "decoder"}, {name = "get_events", module = "inline_options"}, {name = "get_issues_and_affecting_options", module = "inline_options"}, {name = "parse", module = "parser"}, {name = "run", module = "stages.unwrap_parens"}, {name = "run", module = "stages.linearize"}, {name = "run", module = "stages.name_functions"}, {name = "run", module = "stages.resolve_locals"}, {name = "run", module = "stages.detect_bad_whitespace"}, {name = "run", module = "stages.detect_cyclomatic_complexity"}, {name = "run", module = "stages.detect_empty_blocks"}, {name = "run", module = "stages.detect_empty_statements"}, {name = "run", module = "stages.detect_globals"}, {name = "run", module = "stages.detect_reversed_fornum_loops"}, {name = "run", module = "stages.detect_unbalanced_assignments"}, {name = "run", module = "stages.detect_uninit_accesses"}, {name = "run", module = "stages.detect_unreachable_code"}, {name = "run", module = "stages.detect_unused_fields"}, {name = "run", module = "stages.detect_unused_locals"}, {name = "filter", module = "filter"}, {name = "normalize", module = "options"} } local stats = {} local start_values = {} local function start_phase(name) for _, metric in ipairs(metrics) do start_values[metric][name] = metric.get() end end local function stop_phase(name) for _, metric in ipairs(metrics) do local increment = metric.get() - start_values[metric][name] stats[metric][name] = (stats[metric][name] or 0) + increment end end local phase_stack = {} local function push_phase(name) local prev_name = phase_stack[#phase_stack] if prev_name then stop_phase(prev_name) end table.insert(phase_stack, name) start_phase(name) end local function pop_phase(name) assert(name == table.remove(phase_stack)) stop_phase(name) local prev_name = phase_stack[#phase_stack] if prev_name then start_phase(prev_name) end end local function continue_wrapper(name, ...) pop_phase(name) return ... end local function wrap(fn, name) return function(...) push_phase(name) return continue_wrapper(name, fn(...)) end end local function patch(fn) local mod = require("luacheck." .. fn.module) local orig = mod[fn.name] local new = wrap(orig, fn.module .. "." .. fn.name) mod[fn.name] = new end function profiler.init() collectgarbage("stop") for _, metric in ipairs(metrics) do stats[metric] = {} start_values[metric] = {} end for _, fn in ipairs(functions) do patch(fn) end push_phase("other") end function profiler.report() pop_phase("other") for _, metric in ipairs(metrics) do local names = {} local total = 0 for name, value in pairs(stats[metric]) do table.insert(names, name) total = total + value end table.sort(names, function(name1, name2) local stats1 = stats[metric][name1] local stats2 = stats[metric][name2] if stats1 ~= stats2 then return stats1 > stats2 else return name1 < name2 end end) print(metric.name) print() for _, name in ipairs(names) do print(("%s - %f (%f%%)"):format(name, stats[metric][name], stats[metric][name] / total * 100)) end print(("Total - %f"):format(total)) print() end end return profiler
-- Require luasocket only when needed. local socket local profiler = {} local metrics = { {name = "Wall", get = function() return socket.gettime() end}, {name = "CPU", get = os.clock}, {name = "Memory", get = function() return collectgarbage("count") end} } local functions = { {name = "load", module = "cache"}, {name = "update", module = "cache"}, {name = "decode", module = "decoder"}, {name = "get_events", module = "inline_options"}, {name = "get_issues_and_affecting_options", module = "inline_options"}, {name = "parse", module = "parser"}, {name = "run", module = "stages.unwrap_parens"}, {name = "run", module = "stages.linearize"}, {name = "run", module = "stages.name_functions"}, {name = "run", module = "stages.resolve_locals"}, {name = "run", module = "stages.detect_bad_whitespace"}, {name = "run", module = "stages.detect_cyclomatic_complexity"}, {name = "run", module = "stages.detect_empty_blocks"}, {name = "run", module = "stages.detect_empty_statements"}, {name = "run", module = "stages.detect_globals"}, {name = "run", module = "stages.detect_reversed_fornum_loops"}, {name = "run", module = "stages.detect_unbalanced_assignments"}, {name = "run", module = "stages.detect_uninit_accesses"}, {name = "run", module = "stages.detect_unreachable_code"}, {name = "run", module = "stages.detect_unused_fields"}, {name = "run", module = "stages.detect_unused_locals"}, {name = "filter", module = "filter"}, {name = "normalize", module = "options"} } local stats = {} local start_values = {} local function start_phase(name) for _, metric in ipairs(metrics) do start_values[metric][name] = metric.get() end end local function stop_phase(name) for _, metric in ipairs(metrics) do local increment = metric.get() - start_values[metric][name] stats[metric][name] = (stats[metric][name] or 0) + increment end end local phase_stack = {} local function push_phase(name) local prev_name = phase_stack[#phase_stack] if prev_name then stop_phase(prev_name) end table.insert(phase_stack, name) start_phase(name) end local function pop_phase(name) assert(name == table.remove(phase_stack)) stop_phase(name) local prev_name = phase_stack[#phase_stack] if prev_name then start_phase(prev_name) end end local function continue_wrapper(name, ...) pop_phase(name) return ... end local function wrap(fn, name) return function(...) push_phase(name) return continue_wrapper(name, fn(...)) end end local function patch(fn) local mod = require("luacheck." .. fn.module) local orig = mod[fn.name] local new = wrap(orig, fn.module .. "." .. fn.name) mod[fn.name] = new end function profiler.init() socket = require "socket" collectgarbage("stop") for _, metric in ipairs(metrics) do stats[metric] = {} start_values[metric] = {} end for _, fn in ipairs(functions) do patch(fn) end push_phase("other") end function profiler.report() pop_phase("other") for _, metric in ipairs(metrics) do local names = {} local total = 0 for name, value in pairs(stats[metric]) do table.insert(names, name) total = total + value end table.sort(names, function(name1, name2) local stats1 = stats[metric][name1] local stats2 = stats[metric][name2] if stats1 ~= stats2 then return stats1 > stats2 else return name1 < name2 end end) print(metric.name) print() for _, name in ipairs(names) do print(("%s - %f (%f%%)"):format(name, stats[metric][name], stats[metric][name] / total * 100)) end print(("Total - %f"):format(total)) print() end end return profiler
Fix profiler unconditionally requiring luasocket
Fix profiler unconditionally requiring luasocket
Lua
mit
mpeterv/luacheck,xpol/luacheck,mpeterv/luacheck,xpol/luacheck,mpeterv/luacheck,xpol/luacheck
37fc8f7a934044dca58efeb1bdb180db027aed33
Interface/AddOns/RayUI/modules/skins/blizzard/blackmarket.lua
Interface/AddOns/RayUI/modules/skins/blizzard/blackmarket.lua
local R, L, P, G = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, GlobalDB local S = R:GetModule("Skins") local function LoadSkin() BlackMarketFrame:DisableDrawLayer("BACKGROUND") BlackMarketFrame:DisableDrawLayer("BORDER") BlackMarketFrame:DisableDrawLayer("OVERLAY") BlackMarketFrame.Inset:DisableDrawLayer("BORDER") select(9, BlackMarketFrame.Inset:GetRegions()):Hide() BlackMarketFrame.MoneyFrameBorder:Hide() BlackMarketFrame.HotDeal.Left:Hide() BlackMarketFrame.HotDeal.Right:Hide() select(4, BlackMarketFrame.HotDeal:GetRegions()):Hide() S:CreateBG(BlackMarketFrame.HotDeal.Item) BlackMarketFrame.HotDeal.Item.IconTexture:SetTexCoord(.08, .92, .08, .92) local headers = {"ColumnName", "ColumnLevel", "ColumnType", "ColumnDuration", "ColumnHighBidder", "ColumnCurrentBid"} for _, header in pairs(headers) do local header = BlackMarketFrame[header] header.Left:Hide() header.Middle:Hide() header.Right:Hide() local bg = CreateFrame("Frame", nil, header) bg:Point("TOPLEFT", 2, 0) bg:Point("BOTTOMRIGHT", -1, 0) bg:SetFrameLevel(header:GetFrameLevel()-1) S:CreateBD(bg, .25) end S:SetBD(BlackMarketFrame) S:CreateBD(BlackMarketFrame.HotDeal, .25) S:Reskin(BlackMarketFrame.BidButton) S:Reskin(BlackMarketFrame.HotDeal.BidButton) S:ReskinClose(BlackMarketFrame.CloseButton) S:ReskinInput(BlackMarketBidPriceGold) S:ReskinInput(BlackMarketHotItemBidPriceGold) S:ReskinScroll(BlackMarketScrollFrameScrollBar) local function UpdateBlackMarketList() local scrollFrame = BlackMarketScrollFrame local offset = HybridScrollFrame_GetOffset(scrollFrame) local buttons = scrollFrame.buttons local numButtons = #buttons for i = 1, numButtons do local index = i + offset local bu = buttons[i] bu.Item.IconTexture:SetTexCoord(.08, .92, .08, .92) if not bu.reskinned then bu.Left:Hide() bu.Right:Hide() select(3, bu:GetRegions()):Hide() bu.Item:SetNormalTexture("") S:CreateBG(bu.Item) local bg = CreateFrame("Frame", nil, bu) bg:SetPoint("TOPLEFT") bg:SetPoint("BOTTOMRIGHT", 0, 5) bg:SetFrameLevel(bu:GetFrameLevel()-1) S:CreateBD(bg, 0) local tex = bu:CreateTexture(nil, "BACKGROUND") tex:SetPoint("TOPLEFT") tex:SetPoint("BOTTOMRIGHT", 0, 5) tex:SetColorTexture(0, 0, 0, .25) bu:SetHighlightTexture(R["media"].gloss) local hl = bu:GetHighlightTexture() hl:SetVertexColor(r, g, b, .2) hl.SetAlpha = R.dummy hl:ClearAllPoints() hl:Point("TOPLEFT", 0, -1) hl:Point("BOTTOMRIGHT", -1, 6) bu.Item:StyleButton(true) bu.reskinned = true end local link = select(15, C_BlackMarket.GetItemInfoByIndex(index)) if link then local _, _, quality = GetItemInfo(link) local r, g, b = GetItemQualityColor(quality) bu.Name:SetTextColor(r, g, b) end end end hooksecurefunc(BlackMarketScrollFrame, "update", UpdateBlackMarketList) hooksecurefunc("BlackMarketScrollFrame_Update", UpdateBlackMarketList) hooksecurefunc("BlackMarketFrame_UpdateHotItem", function() local link = select(15, C_BlackMarket.GetHotItem()) if link then local _, _, quality = GetItemInfo(link) local r, g, b = GetItemQualityColor(quality) BlackMarketFrame.HotDeal.Name:SetTextColor(r, g, b) end end) end S:AddCallbackForAddon("Blizzard_BlackMarketUI", "BlackMarket", LoadSkin)
local R, L, P, G = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, GlobalDB local S = R:GetModule("Skins") local function LoadSkin() BlackMarketFrame:StripTextures() BlackMarketFrame.Inset:StripTextures() BlackMarketFrame.MoneyFrameBorder:StripTextures() BlackMarketFrame.HotDeal:StripTextures() BlackMarketFrame.HotDeal.Item.IconBorder:Kill() BlackMarketFrame.HotDeal.Item.IconTexture:SetTexCoord(.08, .92, .08, .92) BlackMarketFrame.HotDeal.Item:StyleButton(true) S:CreateBG(BlackMarketFrame.HotDeal.Item) local headers = {"ColumnName", "ColumnLevel", "ColumnType", "ColumnDuration", "ColumnHighBidder", "ColumnCurrentBid"} for _, header in pairs(headers) do local header = BlackMarketFrame[header] header.Left:Hide() header.Middle:Hide() header.Right:Hide() local bg = CreateFrame("Frame", nil, header) bg:Point("TOPLEFT", 2, 0) bg:Point("BOTTOMRIGHT", -1, 0) bg:SetFrameLevel(header:GetFrameLevel()-1) S:CreateBD(bg, .25) end S:SetBD(BlackMarketFrame) S:CreateBD(BlackMarketFrame.HotDeal, .25) S:Reskin(BlackMarketFrame.BidButton) S:ReskinClose(BlackMarketFrame.CloseButton) S:ReskinInput(BlackMarketBidPriceGold) S:ReskinScroll(BlackMarketScrollFrameScrollBar) local function UpdateBlackMarketList() local scrollFrame = BlackMarketScrollFrame local offset = HybridScrollFrame_GetOffset(scrollFrame) local buttons = scrollFrame.buttons local numButtons = #buttons for i = 1, numButtons do local index = i + offset local bu = buttons[i] bu.Item.IconTexture:SetTexCoord(.08, .92, .08, .92) if not bu.reskinned then bu.Item.IconBorder:Kill() bu.Left:Hide() bu.Right:Hide() select(3, bu:GetRegions()):Hide() bu.Item:SetNormalTexture("") S:CreateBG(bu.Item) local bg = CreateFrame("Frame", nil, bu) bg:SetPoint("TOPLEFT") bg:SetPoint("BOTTOMRIGHT", 0, 5) bg:SetFrameLevel(bu:GetFrameLevel()-1) S:CreateBD(bg, 0) local tex = bu:CreateTexture(nil, "BACKGROUND") tex:SetPoint("TOPLEFT") tex:SetPoint("BOTTOMRIGHT", 0, 5) tex:SetColorTexture(0, 0, 0, .25) bu:SetHighlightTexture(R["media"].gloss) local hl = bu:GetHighlightTexture() hl:SetVertexColor(r, g, b, .2) hl.SetAlpha = R.dummy hl:ClearAllPoints() hl:Point("TOPLEFT", 0, -1) hl:Point("BOTTOMRIGHT", -1, 6) bu.Item:StyleButton(true) bu.reskinned = true end local link = select(15, C_BlackMarket.GetItemInfoByIndex(index)) if link then local _, _, quality = GetItemInfo(link) local r, g, b = GetItemQualityColor(quality) bu.Name:SetTextColor(r, g, b) end end end hooksecurefunc(BlackMarketScrollFrame, "update", UpdateBlackMarketList) hooksecurefunc("BlackMarketScrollFrame_Update", UpdateBlackMarketList) hooksecurefunc("BlackMarketFrame_UpdateHotItem", function() local link = select(15, C_BlackMarket.GetHotItem()) if link then local _, _, quality = GetItemInfo(link) local r, g, b = GetItemQualityColor(quality) BlackMarketFrame.HotDeal.Name:SetTextColor(r, g, b) end end) end S:AddCallbackForAddon("Blizzard_BlackMarketUI", "BlackMarket", LoadSkin)
fix #37
fix #37
Lua
mit
fgprodigal/RayUI
22b717704a8b6158df1dd58065662f473b9f25b8
tools/bundler.lua
tools/bundler.lua
--[[ Copyright 2012 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local FS = require('fs') local Path = require('path') local Table = require('table') local ChildProcess = require('childprocess') local function map(array, fn) local new_array = {} for i,v in ipairs(array) do new_array[i] = fn(v, i, array) end return new_array end local function mapcat(array, fn, join) return Table.concat(map(array, fn), join or "") end local libdir = Path.join(Path.dirname(process.execPath), Path.join("..", "lib", "luvit")) local files = FS.readdirSync(libdir) local names = map(files, function (file) return file:match("^([^.]*)") end) Table.sort(names) local exports_c = [[ /* This file is generated by bundler.lua */ #include <string.h> #include "luvit.h" const void *luvit_ugly_hack = NULL; ]] .. mapcat(names, function (name) return "extern const char *luaJIT_BC_" .. name .. "[];\n" end) .. [[ const void *luvit__suck_in_symbols(void) { luvit_ugly_hack = (const char*) ]] .. mapcat(names, function (name) return " (size_t)(const char *)luaJIT_BC_" .. name end, " +\n") .. [[; return luvit_ugly_hack; } ]] local exports_h = [[ /* This file is generated by bundler.lua */ #ifndef LUV_EXPORTS #define LUV_EXPORTS const void *luvit__suck_in_symbols(void); #endif ]] FS.mkdir("bundle", "0755", function (err) if err then if not (err.code == "EEXIST") then error(err) end end local left = 0 local function pend() left = left + 1 return function (err) if err then error(err) end left = left - 1 if left == 0 then -- print("Done!") end end end FS.writeFile(Path.join("src", "luvit_exports.c"), exports_c, pend()) FS.writeFile(Path.join("src", "luvit_exports.h"), exports_h, pend()) for i, file in ipairs(files) do ChildProcess.execFile(Path.join("deps", "luajit", "src", "luajit"), {"-bg", Path.join("lib", "luvit", file), Path.join("bundle", names[i] .. ".c")}, {}, pend()) end end);
--[[ Copyright 2012 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local FS = require('fs') local Path = require('path') local Table = require('table') local ChildProcess = require('childprocess') local function map(array, fn) local new_array = {} for i,v in ipairs(array) do new_array[i] = fn(v, i, array) end return new_array end local function mapcat(array, fn, join) return Table.concat(map(array, fn), join or "") end local libdir = Path.join(Path.dirname(process.execPath), Path.join("..", "lib", "luvit")) local files = FS.readdirSync(libdir) local names = map(files, function (file) return file:match("^([^.]*)") end) Table.sort(names) local exports_c = [[ /* This file is generated by bundler.lua */ #include <string.h> #include "luvit.h" const void *luvit_ugly_hack = NULL; ]] .. mapcat(names, function (name) return "extern const char *luaJIT_BC_" .. name .. "[];\n" end) .. [[ const void *luvit__suck_in_symbols(void) { const char **luvit_ugly_hack[] = { ]] .. mapcat(names, function (name) return " luaJIT_BC_" .. name end, ",\n") .. [[ 0 }; return (const void *)&luvit_ugly_hack[0]; } ]] local exports_h = [[ /* This file is generated by bundler.lua */ #ifndef LUV_EXPORTS #define LUV_EXPORTS const void *luvit__suck_in_symbols(void); #endif ]] FS.mkdir("bundle", "0755", function (err) if err then if not (err.code == "EEXIST") then error(err) end end local left = 0 local function pend() left = left + 1 return function (err) if err then error(err) end left = left - 1 if left == 0 then -- print("Done!") end end end FS.writeFile(Path.join("src", "luvit_exports.c"), exports_c, pend()) FS.writeFile(Path.join("src", "luvit_exports.h"), exports_h, pend()) for i, file in ipairs(files) do ChildProcess.execFile(Path.join("deps", "luajit", "src", "luajit"), {"-bg", Path.join("lib", "luvit", file), Path.join("bundle", names[i] .. ".c")}, {}, pend()) end end);
fixed generated code to compile with MSVC
fixed generated code to compile with MSVC
Lua
apache-2.0
bsn069/luvit,rjeli/luvit,kaustavha/luvit,rjeli/luvit,sousoux/luvit,zhaozg/luvit,GabrielNicolasAvellaneda/luvit-upstream,zhaozg/luvit,boundary/luvit,rjeli/luvit,boundary/luvit,DBarney/luvit,luvit/luvit,boundary/luvit,GabrielNicolasAvellaneda/luvit-upstream,DBarney/luvit,boundary/luvit,kaustavha/luvit,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream,DBarney/luvit,sousoux/luvit,sousoux/luvit,kaustavha/luvit,bsn069/luvit,bsn069/luvit,luvit/luvit,boundary/luvit,sousoux/luvit,boundary/luvit,sousoux/luvit,sousoux/luvit,DBarney/luvit,rjeli/luvit
7588fbd153136bc4e607ec42a04596b66010e647
init.lua
init.lua
---------------------------------------------------------------------- -- sys - a package that provides simple system (unix) tools ---------------------------------------------------------------------- local os = require 'os' local io = require 'io' local paths = require 'paths' sys = {} -------------------------------------------------------------------------------- -- load all functions from lib -------------------------------------------------------------------------------- local _lib = require 'libsys' for k,v in pairs(_lib) do sys[k] = v end -------------------------------------------------------------------------------- -- tic/toc (matlab-like) timers -------------------------------------------------------------------------------- local __t__ function sys.tic() __t__ = sys.clock() end function sys.toc(verbose) local __dt__ = sys.clock() - __t__ if verbose then print(__dt__) end return __dt__ end -------------------------------------------------------------------------------- -- execute an OS command, but retrieves the result in a string -------------------------------------------------------------------------------- local function execute(cmd) local cmd = cmd .. ' 2>&1' local f = io.popen(cmd) local s = f:read('*all') f:close() s = s:gsub('^%s*',''):gsub('%s*$','') return s end sys.execute = execute -------------------------------------------------------------------------------- -- execute an OS command, but retrieves the result in a string -- side effect: file in /tmp -- this call is typically more robust than the one above (on some systems) -------------------------------------------------------------------------------- function sys.fexecute(cmd, readwhat) readwhat = readwhat or '*all' local tmpfile = os.tmpname() local cmd = cmd .. ' 1>'.. tmpfile..' 2>' .. tmpfile os.execute(cmd) local file = _G.assert(io.open(tmpfile)) local s= file:read(readwhat) file:close() s = s:gsub('^%s*',''):gsub('%s*$','') os.execute('rm ' .. tmpfile) return s end -------------------------------------------------------------------------------- -- returns the name of the OS in use -- warning, this method is extremely dumb, and should be replaced by something -- more reliable -------------------------------------------------------------------------------- function sys.uname() if paths.dirp('C:\\') then return 'windows' else local ffi = require 'ffi' local os = ffi.os if os:find('Linux') then return 'linux' elseif os:find('OSX') then return 'macos' else return '?' end end end sys.OS = sys.uname() -------------------------------------------------------------------------------- -- ls (list dir) -------------------------------------------------------------------------------- sys.ls = function(d) d = d or ' ' return execute('ls ' ..d) end sys.ll = function(d) d = d or ' ' return execute('ls -l ' ..d) end sys.la = function(d) d = d or ' ' return execute('ls -a ' ..d) end sys.lla = function(d) d = d or ' ' return execute('ls -la '..d) end -------------------------------------------------------------------------------- -- prefix -------------------------------------------------------------------------------- sys.prefix = execute('which lua'):gsub('//','/'):gsub('/bin/lua\n','') -------------------------------------------------------------------------------- -- always returns the path of the file running -------------------------------------------------------------------------------- sys.fpath = require 'sys.fpath' -------------------------------------------------------------------------------- -- split string based on pattern pat -------------------------------------------------------------------------------- function sys.split(str, pat) local t = {} -- NOTE: use {n = 0} in Lua-5.0 local fpat = "(.-)" .. pat local last_end = 1 local s, e, cap = str:find(fpat, last_end) while s do if s ~= 1 or cap ~= "" then _G.table.insert(t,cap) end last_end = e+1 s, e, cap = str:find(fpat, last_end) end if last_end <= #str then cap = str:sub(last_end) _G.table.insert(t, cap) end return t end -------------------------------------------------------------------------------- -- check if a number is NaN -------------------------------------------------------------------------------- function sys.isNaN(number) -- We rely on the property that NaN is the only value that doesn't equal itself. return (number ~= number) end -------------------------------------------------------------------------------- -- sleep -------------------------------------------------------------------------------- function sys.sleep(seconds) sys.usleep(seconds*1000000) end -------------------------------------------------------------------------------- -- colors, can be used to print things in color -------------------------------------------------------------------------------- sys.COLORS = require 'sys.colors' -------------------------------------------------------------------------------- -- backward compat -------------------------------------------------------------------------------- sys.dirname = paths.dirname sys.concat = paths.concat return sys
---------------------------------------------------------------------- -- sys - a package that provides simple system (unix) tools ---------------------------------------------------------------------- local os = require 'os' local io = require 'io' local paths = require 'paths' sys = {} -------------------------------------------------------------------------------- -- load all functions from lib -------------------------------------------------------------------------------- local _lib = require 'libsys' for k,v in pairs(_lib) do sys[k] = v end -------------------------------------------------------------------------------- -- tic/toc (matlab-like) timers -------------------------------------------------------------------------------- local __t__ function sys.tic() __t__ = sys.clock() end function sys.toc(verbose) local __dt__ = sys.clock() - __t__ if verbose then print(__dt__) end return __dt__ end -------------------------------------------------------------------------------- -- execute an OS command, but retrieves the result in a string -------------------------------------------------------------------------------- local function execute(cmd) local cmd = cmd .. ' 2>&1' local f = io.popen(cmd) local s = f:read('*all') f:close() s = s:gsub('^%s*',''):gsub('%s*$','') return s end sys.execute = execute -------------------------------------------------------------------------------- -- execute an OS command, but retrieves the result in a string -- side effect: file in /tmp -- this call is typically more robust than the one above (on some systems) -------------------------------------------------------------------------------- function sys.fexecute(cmd, readwhat) readwhat = readwhat or '*all' local tmpfile = os.tmpname() local cmd = cmd .. ' 1>'.. tmpfile..' 2>' .. tmpfile os.execute(cmd) local file = _G.assert(io.open(tmpfile)) local s= file:read(readwhat) file:close() s = s:gsub('^%s*',''):gsub('%s*$','') os.execute('rm ' .. tmpfile) return s end -------------------------------------------------------------------------------- -- returns the name of the OS in use -- warning, this method is extremely dumb, and should be replaced by something -- more reliable -------------------------------------------------------------------------------- function sys.uname() if paths.dirp('C:\\') then return 'windows' else local ffi = require 'ffi' local os = ffi.os if os:find('Linux') then return 'linux' elseif os:find('OSX') then return 'macos' else return '?' end end end sys.OS = sys.uname() -------------------------------------------------------------------------------- -- ls (list dir) -------------------------------------------------------------------------------- sys.ls = function(d) d = d or ' ' return execute('ls ' ..d) end sys.ll = function(d) d = d or ' ' return execute('ls -l ' ..d) end sys.la = function(d) d = d or ' ' return execute('ls -a ' ..d) end sys.lla = function(d) d = d or ' ' return execute('ls -la '..d) end -------------------------------------------------------------------------------- -- prefix -------------------------------------------------------------------------------- local function find_prefix() if arg then for i, v in pairs(arg) do if i <= 0 then local lua_path = paths.basename(v) if lua_path == "luajit" or lua_path == "lua" then local bin_dir = paths.dirname(v) if paths.basename(bin_dir) == "bin" then return paths.dirname(bin_dir) else return bin_dir end end end end end return "" end sys.prefix = find_prefix() -------------------------------------------------------------------------------- -- always returns the path of the file running -------------------------------------------------------------------------------- sys.fpath = require 'sys.fpath' -------------------------------------------------------------------------------- -- split string based on pattern pat -------------------------------------------------------------------------------- function sys.split(str, pat) local t = {} -- NOTE: use {n = 0} in Lua-5.0 local fpat = "(.-)" .. pat local last_end = 1 local s, e, cap = str:find(fpat, last_end) while s do if s ~= 1 or cap ~= "" then _G.table.insert(t,cap) end last_end = e+1 s, e, cap = str:find(fpat, last_end) end if last_end <= #str then cap = str:sub(last_end) _G.table.insert(t, cap) end return t end -------------------------------------------------------------------------------- -- check if a number is NaN -------------------------------------------------------------------------------- function sys.isNaN(number) -- We rely on the property that NaN is the only value that doesn't equal itself. return (number ~= number) end -------------------------------------------------------------------------------- -- sleep -------------------------------------------------------------------------------- function sys.sleep(seconds) sys.usleep(seconds*1000000) end -------------------------------------------------------------------------------- -- colors, can be used to print things in color -------------------------------------------------------------------------------- sys.COLORS = require 'sys.colors' -------------------------------------------------------------------------------- -- backward compat -------------------------------------------------------------------------------- sys.dirname = paths.dirname sys.concat = paths.concat return sys
fixing sys to not fork
fixing sys to not fork
Lua
bsd-3-clause
torch/sys
7efc701be416bcf5d22a5f017ee6cd39b019ebab
test_scripts/Polices/build_options/ATF_PolicyManager_changes_status_to_UPDATING_PROPRIETARY.lua
test_scripts/Polices/build_options/ATF_PolicyManager_changes_status_to_UPDATING_PROPRIETARY.lua
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [PolicyTableUpdate] PoliciesManager changes status to "UPDATING" -- [HMI API] OnStatusUpdate -- -- Description: -- SDL is built with "-DEXTENDED_POLICY: PROPRIETARY" flag -- PoliciesManager must change the status to "UPDATING" and notify HMI with OnStatusUpdate("UPDATING") -- right after SnapshotPT is sent out to to mobile app via OnSystemRequest() RPC. -- -- Steps: -- 1. Register new app -- 2. Trigger PTU -- 3. SDL->HMI: Verify step of SDL.OnStatusUpdate(UPDATING) notification in PTU sequence -- -- Expected result: -- SDL.OnStatusUpdate(UPDATING) notification is send right after SDL->MOB: OnSystemRequest --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonFunctions = require("user_modules/shared_testcases/commonFunctions") local commonSteps = require("user_modules/shared_testcases/commonSteps") local testCasesForPolicyTable = require("user_modules/shared_testcases/testCasesForPolicyTable") --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() testCasesForPolicyTable.Delete_Policy_table_snapshot() --[[ General Settings for configuration ]] Test = require("connecttest") require("user_modules/AppTypes") --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Precondition") --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_CheckMessagesSequence() local is_test_fail = false local message_number = 1 local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(RequestId_GetUrls) :Do(function(_,_) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", fileName = "PolicyTableUpdate"}) if(message_number ~= 1) then commonFunctions:printError("Error: SDL.GetURLS reponse is not received as message 1 after SDL.GetURLS request. Real: "..message_number) is_test_fail = true else print("SDL.GetURLS is received as message "..message_number.." after SDL.GetURLS request") end message_number = message_number + 1 end) EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "PROPRIETARY"}) :Do(function(_,_) if( (message_number ~= 2) and (message_number ~= 3)) then commonFunctions:printError("Error: SDL.OnStatusUpdate reponse is not received as message 2/3 after SDL.GetURLS request. Real: "..message_number) is_test_fail = true else print("OnSystemRequest is received as message "..message_number.." after SDL.GetURLS request") end message_number = message_number + 1 end) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate",{status = "UPDATING"}) :Do(function(_,data) if( (message_number ~= 2) and (message_number ~= 3)) then commonFunctions:printError("Error: SDL.OnStatusUpdate reponse is not received as message 2/3 after SDL.GetURLS request. Real: "..message_number) is_test_fail = true else print("SDL.OnStatusUpdate("..data.params.status..") is received as message "..message_number.." after SDL.GetURLS request") end message_number = message_number + 1 end) if(is_test_fail == true) then self:FailTestCase("Test is FAILED. See prints.") end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_StopSDL() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [PolicyTableUpdate] PoliciesManager changes status to "UPDATING" -- [HMI API] OnStatusUpdate -- -- Description: -- SDL is built with "-DEXTENDED_POLICY: PROPRIETARY" flag -- PoliciesManager must change the status to "UPDATING" and notify HMI with OnStatusUpdate("UPDATING") -- right after SnapshotPT is sent out to to mobile app via OnSystemRequest() RPC. -- -- Steps: -- 1. Register new app -- 2. Trigger PTU -- 3. SDL->HMI: Verify step of SDL.OnStatusUpdate(UPDATING) notification in PTU sequence -- -- Expected result: -- SDL.OnStatusUpdate(UPDATING) notification is send right after SDL->MOB: OnSystemRequest --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonFunctions = require("user_modules/shared_testcases/commonFunctions") local commonSteps = require("user_modules/shared_testcases/commonSteps") local testCasesForPolicyTable = require("user_modules/shared_testcases/testCasesForPolicyTable") --[[ Local Variables ]] local r_actual = { } --[[ Local Functions ]] local function get_id_by_val(t, v) for i = 1, #t do if (t[i] == v) then return i end end return nil end --[[ General Precondition before ATF start ]] commonFunctions:SDLForceStop() commonSteps:DeleteLogsFileAndPolicyTable() testCasesForPolicyTable.Delete_Policy_table_snapshot() --[[ General Settings for configuration ]] Test = require("connecttest") require("user_modules/AppTypes") -- [[ Notifications ]] EXPECT_HMICALL("BasicCommunication.PolicyUpdate") :Do(function() table.insert(r_actual, "BC.PolicyUpdate") end) :Times(AnyNumber()) :Pin() EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate",{ status = "UPDATING" }) :Do(function(_, d) table.insert(r_actual, "SDL.OnStatusUpdate: " .. d.params.status) end) :Times(AnyNumber()) :Pin() --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_CheckMessagesSequence() local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) table.insert(r_actual, "SDL.GetURLS: request") EXPECT_HMIRESPONSE(RequestId_GetUrls) :Do(function() table.insert(r_actual, "SDL.GetURLS: response") EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY" }) :Do(function() table.insert(r_actual, "OnSystemRequest") end) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", fileName = "PolicyTableUpdate"}) table.insert(r_actual, "BC.OnSystemRequest") end) end function Test:ValidateResult() commonFunctions:printTable(r_actual) local onSystemRequestId = get_id_by_val(r_actual, "OnSystemRequest") local onStatusUpdate = get_id_by_val(r_actual, "SDL.OnStatusUpdate: UPDATING") print("Id of 'OnSystemRequest': " .. onSystemRequestId) print("Id of 'SDL.OnStatusUpdate: UPDATING': " .. onStatusUpdate) if onStatusUpdate < onSystemRequestId then self:FailTestCase("Unexpected 'SDL.OnStatusUpdate: UPDATING' before 'OnSystemRequest'") end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_StopSDL() StopSDL() end return Test
Fix issues in script
Fix issues in script
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
f6d8baab44e50164ae1d68dd9ccdf11408b2c7bf
.config/nvim/lua/config/coc.lua
.config/nvim/lua/config/coc.lua
vim.g.coc_node_args = { "--max-old-space-size=4096" } vim.g.coc_global_extensions = { "coc-lists", "coc-snippets", "coc-solargraph", "coc-go", "coc-java", "coc-tsserver", "coc-eslint", "coc-prettier", "coc-sumneko-lua", "coc-stylua", "coc-markdownlint", "coc-html", "coc-css", "coc-json", "coc-yaml", "coc-toml", "coc-tailwindcss", "coc-swagger", "coc-sh", "coc-fish", "coc-markmap", "coc-vimlsp", } vim.cmd([[ " Use tab for trigger completion with characters ahead and navigate. inoremap <silent><expr> <TAB> \ coc#pum#visible() ? coc#_select_confirm() : \ coc#expandableOrJumpable() ? "\<C-r>=coc#rpc#request('doKeymap', ['snippets-expand-jump',''])\<CR>" : \ CheckBackSpace() ? "\<TAB>" : \ coc#refresh() inoremap <expr> <S-TAB> coc#pum#visible() ? coc#pum#prev(1) : "\<C-h>" inoremap <silent><expr> <C-n> coc#pum#visible() ? coc#pum#next(1) : "\<Down>" inoremap <silent><expr> <C-p> coc#pum#visible() ? coc#pum#prev(1) : "\<Up>" inoremap <silent><expr> <C-e> coc#pum#visible() ? coc#pum#cancel() : "\<Esc>A" inoremap <silent><expr> <C-j> coc#pum#visible() ? coc#pum#confirm() : "\<C-j>" function! CheckBackSpace() abort let col = col('.') - 1 return !col || getline('.')[col - 1] =~# '\s' endfunction inoremap <silent><expr> <c-space> coc#refresh() " Make <CR> to accept selected completion item or notify coc.nvim to format " <C-g>u breaks current undo, please make your own choice. inoremap <silent><expr> <CR> coc#pum#visible() ? coc#pum#confirm() \: "\<C-g>u\<CR>" " Use `[d` and `]d` to navigate diagnostics " Use `:CocDiagnostics` to get all diagnostics of current buffer in location list. nmap <silent> [d <Plug>(coc-diagnostic-prev) nmap <silent> ]d <Plug>(coc-diagnostic-next) " Use K to show documentation in preview window. nnoremap <silent> K :call ShowDocumentation()<CR> function! ShowDocumentation() if CocAction('hasProvider', 'hover') call CocActionAsync('doHover') else call feedkeys('K', 'in') endif endfunction " Highlight the symbol and its references when holding the cursor. autocmd CursorHold * silent call CocActionAsync('highlight') " Symbol renaming. nmap <leader>rn <Plug>(coc-rename) " Remap keys for applying codeAction to the current buffer. nmap <leader>ca <Plug>(coc-codeaction) " Run the Code Lens action on the current line. nmap <leader>cl <Plug>(coc-codelens-action) nnoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? coc#float#scroll(1) : "\<C-f>" nnoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? coc#float#scroll(0) : "\<C-b>" inoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? "\<c-r>=coc#float#scroll(1)\<cr>" : "\<Right>" inoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? "\<c-r>=coc#float#scroll(0)\<cr>" : "\<Left>" vnoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? coc#float#scroll(1) : "\<C-f>" vnoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? coc#float#scroll(0) : "\<C-b>" " coc-yank nnoremap <silent> <Leader>y :<C-u>CocList -A --normal yank<CR> " coc-markmap " Create markmap from the whole file command! Markmap CocCommand markmap.create -w ]]) local autocmd = vim.api.nvim_create_autocmd autocmd({ "VimEnter", "ColorScheme" }, { group = "_", pattern = "*", command = "highlight CocMenuSel gui=underline guibg=#282c34", }) autocmd({ "FileType" }, { group = "_", pattern = "*", -- Setup formatexpr command = "setlocal formatexpr=CocAction('formatSelected')", }) -- For go autocmd({ "BufWritePre" }, { pattern = "*.go", command = "CocCommand editor.action.organizeImport", })
vim.g.coc_node_args = { "--max-old-space-size=4096" } vim.g.coc_global_extensions = { "coc-lists", "coc-snippets", "coc-solargraph", "coc-go", "coc-java", "coc-tsserver", "coc-eslint", "coc-prettier", "coc-sumneko-lua", "coc-stylua", "coc-markdownlint", "coc-html", "coc-css", "coc-json", "coc-yaml", "coc-toml", "coc-tailwindcss", "coc-swagger", "coc-sh", "coc-fish", "coc-markmap", "coc-vimlsp", } vim.cmd([[ " Use tab for trigger completion with characters ahead and navigate. inoremap <silent><expr> <TAB> \ coc#pum#visible() ? coc#_select_confirm() : \ coc#expandableOrJumpable() ? "\<C-r>=coc#rpc#request('doKeymap', ['snippets-expand-jump',''])\<CR>" : \ CheckBackSpace() ? "\<TAB>" : \ coc#refresh() inoremap <expr> <S-TAB> coc#pum#visible() ? coc#pum#prev(1) : "\<C-h>" inoremap <silent><expr> <C-n> coc#pum#visible() ? coc#pum#next(1) : "\<Down>" inoremap <silent><expr> <C-p> coc#pum#visible() ? coc#pum#prev(1) : "\<Up>" inoremap <silent><expr> <C-e> coc#pum#visible() ? coc#pum#cancel() : "\<Esc>A" inoremap <silent><expr> <C-j> coc#pum#visible() ? coc#pum#confirm() : "\<C-j>" function! CheckBackSpace() abort let col = col('.') - 1 return !col || getline('.')[col - 1] =~# '\s' endfunction inoremap <silent><expr> <c-space> coc#refresh() " Make <CR> to accept selected completion item or notify coc.nvim to format " <C-g>u breaks current undo, please make your own choice. inoremap <silent><expr> <CR> coc#pum#visible() ? coc#pum#confirm() \: "\<C-g>u\<CR>" " Use `[d` and `]d` to navigate diagnostics " Use `:CocDiagnostics` to get all diagnostics of current buffer in location list. nmap <silent> [d <Plug>(coc-diagnostic-prev) nmap <silent> ]d <Plug>(coc-diagnostic-next) " Use K to show documentation in preview window. nnoremap <silent> K :call ShowDocumentation()<CR> function! ShowDocumentation() if CocAction('hasProvider', 'hover') call CocActionAsync('doHover') else call feedkeys('K', 'in') endif endfunction " Highlight the symbol and its references when holding the cursor. autocmd CursorHold * silent call CocActionAsync('highlight') " Symbol renaming. nmap <leader>rn <Plug>(coc-rename) " Remap keys for applying codeAction to the current buffer. nmap <leader>ca <Plug>(coc-codeaction) " Run the Code Lens action on the current line. nmap <leader>cl <Plug>(coc-codelens-action) nnoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? coc#float#scroll(1) : "\<C-f>" nnoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? coc#float#scroll(0) : "\<C-b>" inoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? "\<c-r>=coc#float#scroll(1)\<cr>" : "\<Right>" inoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? "\<c-r>=coc#float#scroll(0)\<cr>" : "\<Left>" vnoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? coc#float#scroll(1) : "\<C-f>" vnoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? coc#float#scroll(0) : "\<C-b>" " coc-yank nnoremap <silent> <Leader>y :<C-u>CocList -A --normal yank<CR> " coc-markmap " Create markmap from the whole file command! Markmap CocCommand markmap.create -w ]]) local autocmd = vim.api.nvim_create_autocmd autocmd({ "VimEnter", "ColorScheme" }, { group = "_", pattern = "*", command = "highlight CocMenuSel gui=underline guibg=#282c34", }) autocmd({ "FileType" }, { group = "_", pattern = "*", -- Setup formatexpr command = "setlocal formatexpr=CocAction('formatSelected')", }) -- For go autocmd({ "BufWritePre" }, { pattern = "*.go", command = "CocCommand editor.action.organizeImport", }) autocmd({ "BufWritePre" }, { pattern = "*.ts", command = "CocCommand tsserver.organizeImports", })
[nvim] Fix ts config
[nvim] Fix ts config
Lua
mit
masa0x80/dotfiles,masa0x80/dotfiles,masa0x80/dotfiles,masa0x80/dotfiles
6d73752e59048cfc627ad556e1d303973be9811e
Hydra/repl.lua
Hydra/repl.lua
api.repl = {} api.doc.repl.open = {"api.repl.open() -> textgrid", "Opens a REPL that has full access to Hydra's API"} function api.repl.open() local win = api.textgrid.open() win:livelong() local fg = "00FF00" local bg = "222222" win:settitle("Hydra REPL") local stdout = "" local stdin = "" local function printstr(x, y, str) local size = win:getsize() local w = size.w local h = size.h for i = 1, #str do if x == w + 1 then x = 1 y = y + 1 end if y == h + 1 then break end local c = str:sub(i,i):byte() if c == string.byte("\n") then x = 1 y = y + 1 else win:set(c, x, y, fg, bg) x = x + 1 end end end local function clearbottom() local size = win:getsize() local w = size.w local h = size.h for x = 1, w do win:set(string.byte(" "), x, h, fg, bg) end end local function printcursor(x, y) win:set(string.byte(" "), x, y, bg, fg) end local function redraw() local size = win:getsize() local w = size.w local h = size.h win:clear(bg) printstr(1, 1, stdout) clearbottom() printstr(1, h, "> " .. stdin) printcursor(3 + string.len(stdin), h) end win:resized(redraw) local function receivedlog(str) stdout = stdout .. str .. "\n" redraw() end local loghandler = api.log.addhandler(receivedlog) win:closed(function() api.log.removehandler(loghandler) end) win:keydown(function(t) if t.key == "return" then local command = stdin stdin = "" local fn = load(command) local success, result = pcall(fn) result = tostring(result) if not success then result = "error: " .. result end stdout = stdout .. "> " .. command .. "\n" .. result .. "\n" elseif t.key == "delete" then -- i.e. backspace stdin = stdin:sub(0, -2) else stdin = stdin .. t.key end redraw() end) redraw() win:focus() return win end
api.repl = {} api.doc.repl = {__doc = "Read-Eval-Print-Loop"} api.doc.repl.open = {"api.repl.open() -> textgrid", "Opens a (primitive) REPL that has full access to Hydra's API"} function api.repl.open() local win = api.textgrid.open() win:livelong() local fg = "00FF00" local bg = "222222" win:settitle("Hydra REPL") local stdout = "" local stdin = "" local function printstr(x, y, str) local size = win:getsize() local w = size.w local h = size.h for i = 1, #str do if x == w + 1 then x = 1 y = y + 1 end if y == h + 1 then break end local c = str:sub(i,i):byte() if c == string.byte("\n") then x = 1 y = y + 1 else win:set(c, x, y, fg, bg) x = x + 1 end end end local function clearbottom() local size = win:getsize() local w = size.w local h = size.h for x = 1, w do win:set(string.byte(" "), x, h, fg, bg) end end local function printcursor(x, y) win:set(string.byte(" "), x, y, bg, fg) end local function redraw() local size = win:getsize() local w = size.w local h = size.h win:clear(bg) printstr(1, 1, stdout) clearbottom() printstr(1, h, "> " .. stdin) printcursor(3 + string.len(stdin), h) end win:resized(redraw) local function receivedlog(str) stdout = stdout .. str .. "\n" redraw() end local loghandler = api.log.addhandler(receivedlog) win:closed(function() api.log.removehandler(loghandler) end) win:keydown(function(t) if t.key == "return" then local command = stdin stdin = "" local fn = load(command) local success, result = pcall(fn) result = tostring(result) if not success then result = "error: " .. result end stdout = stdout .. "> " .. command .. "\n" .. result .. "\n" elseif t.key == "delete" then -- i.e. backspace stdin = stdin:sub(0, -2) else stdin = stdin .. t.key end redraw() end) redraw() win:focus() return win end
Fixes bug caused by REPL documentation.
Fixes bug caused by REPL documentation.
Lua
mit
knl/hammerspoon,asmagill/hammerspoon,dopcn/hammerspoon,peterhajas/hammerspoon,heptal/hammerspoon,lowne/hammerspoon,peterhajas/hammerspoon,Stimim/hammerspoon,wsmith323/hammerspoon,wsmith323/hammerspoon,zzamboni/hammerspoon,bradparks/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,Hammerspoon/hammerspoon,chrisjbray/hammerspoon,cmsj/hammerspoon,nkgm/hammerspoon,kkamdooong/hammerspoon,TimVonsee/hammerspoon,wvierber/hammerspoon,Stimim/hammerspoon,hypebeast/hammerspoon,zzamboni/hammerspoon,tmandry/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,zzamboni/hammerspoon,knl/hammerspoon,knu/hammerspoon,wvierber/hammerspoon,Stimim/hammerspoon,asmagill/hammerspoon,Habbie/hammerspoon,knl/hammerspoon,heptal/hammerspoon,ocurr/hammerspoon,ocurr/hammerspoon,lowne/hammerspoon,dopcn/hammerspoon,chrisjbray/hammerspoon,cmsj/hammerspoon,nkgm/hammerspoon,dopcn/hammerspoon,knu/hammerspoon,CommandPost/CommandPost-App,trishume/hammerspoon,junkblocker/hammerspoon,nkgm/hammerspoon,dopcn/hammerspoon,wsmith323/hammerspoon,tmandry/hammerspoon,knu/hammerspoon,junkblocker/hammerspoon,knu/hammerspoon,Hammerspoon/hammerspoon,emoses/hammerspoon,latenitefilms/hammerspoon,hypebeast/hammerspoon,joehanchoi/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,Stimim/hammerspoon,Stimim/hammerspoon,TimVonsee/hammerspoon,nkgm/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,asmagill/hammerspoon,lowne/hammerspoon,joehanchoi/hammerspoon,junkblocker/hammerspoon,knl/hammerspoon,ocurr/hammerspoon,CommandPost/CommandPost-App,CommandPost/CommandPost-App,TimVonsee/hammerspoon,tmandry/hammerspoon,latenitefilms/hammerspoon,dopcn/hammerspoon,CommandPost/CommandPost-App,chrisjbray/hammerspoon,zzamboni/hammerspoon,heptal/hammerspoon,bradparks/hammerspoon,latenitefilms/hammerspoon,peterhajas/hammerspoon,wvierber/hammerspoon,asmagill/hammerspoon,kkamdooong/hammerspoon,chrisjbray/hammerspoon,joehanchoi/hammerspoon,hypebeast/hammerspoon,Habbie/hammerspoon,Habbie/hammerspoon,zzamboni/hammerspoon,heptal/hammerspoon,Habbie/hammerspoon,hypebeast/hammerspoon,trishume/hammerspoon,cmsj/hammerspoon,trishume/hammerspoon,Hammerspoon/hammerspoon,TimVonsee/hammerspoon,junkblocker/hammerspoon,ocurr/hammerspoon,Habbie/hammerspoon,wsmith323/hammerspoon,wsmith323/hammerspoon,emoses/hammerspoon,chrisjbray/hammerspoon,TimVonsee/hammerspoon,peterhajas/hammerspoon,latenitefilms/hammerspoon,bradparks/hammerspoon,emoses/hammerspoon,ocurr/hammerspoon,kkamdooong/hammerspoon,kkamdooong/hammerspoon,latenitefilms/hammerspoon,wvierber/hammerspoon,emoses/hammerspoon,chrisjbray/hammerspoon,peterhajas/hammerspoon,wvierber/hammerspoon,lowne/hammerspoon,knu/hammerspoon,bradparks/hammerspoon,lowne/hammerspoon,bradparks/hammerspoon,zzamboni/hammerspoon,knl/hammerspoon,knu/hammerspoon,kkamdooong/hammerspoon,latenitefilms/hammerspoon,heptal/hammerspoon,nkgm/hammerspoon,junkblocker/hammerspoon,emoses/hammerspoon,joehanchoi/hammerspoon,joehanchoi/hammerspoon,hypebeast/hammerspoon
5558df9ed0ab53abd1985079fb905f992e5434e7
hammerspoon/init.lua
hammerspoon/init.lua
-- TODO -- 1) Use Spectacle's keyboard shortcuts -- 2) Add shortcuts for play, pause, step for iTunes -- Set up hotkey combinations local ctril_opt_shift = {"ctrl", "alt", "shift"} local opt_cmd_ctril = { "alt", "cmd", "ctrl"} local cmd_opt_shift = {"cmd", "alt", "shift"} -- Set grid size. hs.grid.GRIDWIDTH = 12 hs.grid.GRIDHEIGHT = 12 hs.grid.MARGINX = 0 hs.grid.MARGINY = 0 -- Set window animation off. It's much smoother. hs.window.animationDuration = 0 -- Set volume increments local volumeIncrement = 5 function toggle_muted() local output_device = hs.audiodevice.defaultOutputDevice() local is_muted = output_device:muted() output_device:setMuted(not is_muted) is_muted = output_device:muted() hs.alert.show("is_muted: " .. tostring(is_muted), 1) end function set_volume(vol_delta) local output_device = hs.audiodevice.defaultOutputDevice() local current_volume = hs.audiodevice.current().volume output_device:setVolume(current_volume + vol_delta) hs.alert.show("Volume: " .. output_device:volume(), 1) end function start_iterm() local iterm = hs.appfinder.appFromName("iTerm") iterm:selectMenuItem({"Shell", "New Window"}) return iterm end function get_focused_window() if hs.window.focusedWindow() then return hs.window.focusedWindow() end end function win_full_screen(win) win:toggleFullScreen() end function win_toggle_maximize(win) win:maximize() end function move_focused_window(fn) print(fn) window = get_focused_window() if window == nil then hs.alert.show("No active window") else fn(window) end end hs.hotkey.bind(opt_cmd_ctril, 'return', function () start_iterm() end) -- hs.hotkey.bind(ctril_opt_shift, ';', function() hs.grid.snap(hs.window.focusedWindow()) end) -- hs.hotkey.bind(ctril_opt_shift, "'", function() hs.fnutils.map(hs.window.visibleWindows(), hs.grid.snap) end) -- hs.hotkey.bind(opt_cmd_ctril, '=', function() hs.grid.adjustWidth(1) end) -- hs.hotkey.bind(opt_cmd_ctril, '-', function() hs.grid.adjustWidth(-1) end) -- hs.hotkey.bind(cmd_opt_shift, '=', function() hs.grid.adjustHeight(1) end) -- hs.hotkey.bind(cmd_opt_shift, '-', function() hs.grid.adjustHeight(-1) end) -- hs.hotkey.bind(cmd_opt_shift, 'left', function() hs.window.focusedWindow():focusWindowWest() end) -- hs.hotkey.bind(cmd_opt_shift, 'right', function() hs.window.focusedWindow():focusWindowEast() end) -- hs.hotkey.bind(cmd_opt_shift, 'up', function() hs.window.focusedWindow():focusWindowNorth() end) -- hs.hotkey.bind(cmd_opt_shift, 'down', function() hs.window.focusedWindow():focusWindowSouth() end) hs.hotkey.bind(opt_cmd_ctril, 'M', hs.grid.maximizeWindow) -- move window to next screen hs.hotkey.bind(opt_cmd_ctril, 'N', hs.grid.pushWindowNextScreen) -- move window to prev screen hs.hotkey.bind(opt_cmd_ctril, 'P', hs.grid.pushWindowPrevScreen) -- move window left -- hs.hotkey.bind(opt_cmd_ctril, 'J', hs.grid.pushWindowLeft) -- move window down -- hs.hotkey.bind(opt_cmd_ctril, 'K', hs.grid.pushWindowDown) -- move window up -- hs.hotkey.bind(opt_cmd_ctril, 'L', hs.grid.pushWindowUp) -- move window right -- hs.hotkey.bind(opt_cmd_ctril, ';', hs.grid.pushWindowRight) hs.hotkey.bind(opt_cmd_ctril, 'U', hs.grid.resizeWindowTaller) hs.hotkey.bind(opt_cmd_ctril, 'O', hs.grid.resizeWindowWider) hs.hotkey.bind(opt_cmd_ctril, 'I', hs.grid.resizeWindowThinner) hs.hotkey.bind(opt_cmd_ctril, 'Y', hs.grid.resizeWindowShorter) hs.hotkey.bind(ctril_opt_shift, 'space', hs.itunes.displayCurrentTrack) hs.hotkey.bind(ctril_opt_shift, 'P', hs.itunes.play) hs.hotkey.bind(ctril_opt_shift, 'O', hs.itunes.pause) hs.hotkey.bind(ctril_opt_shift, 'N', hs.itunes.next) hs.hotkey.bind(ctril_opt_shift, 'I', hs.itunes.previous) hs.hotkey.bind(cmd_opt_shift, ']', function() set_volume( volumeIncrement ) end) hs.hotkey.bind(cmd_opt_shift, '[', function() set_volume( -1 * volumeIncrement ) end) hs.hotkey.bind(cmd_opt_shift, '\\', function() toggle_muted() end) -- hs.hotkey.bind(cmd_opt_shift, 'j', function() move_focused_window(hs.window.focusWindowWest) end) -- hs.hotkey.bind(cmd_opt_shift, 'k', function() move_focused_window(hs.window.focusWindowEast) end) -- hs.hotkey.bind(cmd_opt_shift, 'l', function() move_focused_window(hs.window.focusWindowSouth) end) -- hs.hotkey.bind(cmd_opt_shift, ';', function() move_focused_window(hs.window.focusWindowNorth) end) function _move_window_left(f, max) f.x = max.x + (max.w / 2) f.y = max.y f.w = max.w / 2 f.h = max.h return f end function _move_window_right(f, max) f.x = max.x f.y = max.y f.w = max.w / 2 f.h = max.h return f end function _move_window_up(f, max) f.x = max.x + (max.w / 2) f.y = max.y f.w = max.w / 2 f.h = max.h / 2 return f end function _move_window_down(f, max) f.x = max.x + (max.w / 2) f.y = max.y + (max.h / 2) f.w = max.w / 2 f.h = max.h / 2 return f end function move_window_on_screen(new_frame_fn) if hs.window.focusedWindow() then local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() win:setFrame(new_frame_fn(f, max)) else hs.alert.show("No active window") end end hs.hotkey.bind(opt_cmd_ctril, 'j', function() move_window_on_screen(_move_window_left) end) hs.hotkey.bind(opt_cmd_ctril, 'k', function() move_window_on_screen(_move_window_down) end) hs.hotkey.bind(opt_cmd_ctril, 'l', function() move_window_on_screen(_move_window_up) end) hs.hotkey.bind(opt_cmd_ctril, ';', function() move_window_on_screen(_move_window_right) end) function reload_config(files) hs.reload() hs.alert.show("Config loaded") end hs.pathwatcher.new(os.getenv("HOME") .. "/.hammerspoon/", reload_config):start() hs.alert.show("Hammerspoon, at your service.", 3)
-- TODO -- 1) Use Spectacle's keyboard shortcuts -- 2) Add shortcuts for play, pause, step for iTunes -- Set up hotkey combinations local ctril_opt_shift = {"ctrl", "alt", "shift"} local opt_cmd_ctril = { "alt", "cmd", "ctrl"} local cmd_opt_shift = {"cmd", "alt", "shift"} -- Set grid size. hs.grid.GRIDWIDTH = 12 hs.grid.GRIDHEIGHT = 12 hs.grid.MARGINX = 0 hs.grid.MARGINY = 0 -- Set window animation off. It's much smoother. hs.window.animationDuration = 0 -- Set volume increments local volumeIncrement = 5 function toggle_muted() local output_device = hs.audiodevice.defaultOutputDevice() local is_muted = output_device:muted() output_device:setMuted(not is_muted) is_muted = output_device:muted() hs.alert.show("is_muted: " .. tostring(is_muted), 1) end function set_volume(vol_delta) local output_device = hs.audiodevice.defaultOutputDevice() local current_volume = hs.audiodevice.current().volume output_device:setVolume(current_volume + vol_delta) hs.alert.show("Volume: " .. output_device:volume(), 1) end function start_iterm() local iterm = hs.appfinder.appFromName("iTerm") iterm:selectMenuItem({"Shell", "New Window"}) return iterm end function get_focused_window() if hs.window.focusedWindow() then return hs.window.focusedWindow() end end function win_full_screen(win) win:toggleFullScreen() end function win_toggle_maximize(win) win:maximize() end function move_focused_window(fn) print(fn) window = get_focused_window() if window == nil then hs.alert.show("No active window") else fn(window) end end hs.hotkey.bind(opt_cmd_ctril, 'return', function () start_iterm() end) -- hs.hotkey.bind(ctril_opt_shift, ';', function() hs.grid.snap(hs.window.focusedWindow()) end) -- hs.hotkey.bind(ctril_opt_shift, "'", function() hs.fnutils.map(hs.window.visibleWindows(), hs.grid.snap) end) -- hs.hotkey.bind(opt_cmd_ctril, '=', function() hs.grid.adjustWidth(1) end) -- hs.hotkey.bind(opt_cmd_ctril, '-', function() hs.grid.adjustWidth(-1) end) -- hs.hotkey.bind(cmd_opt_shift, '=', function() hs.grid.adjustHeight(1) end) -- hs.hotkey.bind(cmd_opt_shift, '-', function() hs.grid.adjustHeight(-1) end) -- hs.hotkey.bind(cmd_opt_shift, 'left', function() hs.window.focusedWindow():focusWindowWest() end) -- hs.hotkey.bind(cmd_opt_shift, 'right', function() hs.window.focusedWindow():focusWindowEast() end) -- hs.hotkey.bind(cmd_opt_shift, 'up', function() hs.window.focusedWindow():focusWindowNorth() end) -- hs.hotkey.bind(cmd_opt_shift, 'down', function() hs.window.focusedWindow():focusWindowSouth() end) hs.hotkey.bind(opt_cmd_ctril, 'M', hs.grid.maximizeWindow) -- move window to next screen hs.hotkey.bind(opt_cmd_ctril, 'N', hs.grid.pushWindowNextScreen) -- move window to prev screen hs.hotkey.bind(opt_cmd_ctril, 'P', hs.grid.pushWindowPrevScreen) -- move window left -- hs.hotkey.bind(opt_cmd_ctril, 'J', hs.grid.pushWindowLeft) -- move window down -- hs.hotkey.bind(opt_cmd_ctril, 'K', hs.grid.pushWindowDown) -- move window up -- hs.hotkey.bind(opt_cmd_ctril, 'L', hs.grid.pushWindowUp) -- move window right -- hs.hotkey.bind(opt_cmd_ctril, ';', hs.grid.pushWindowRight) hs.hotkey.bind(opt_cmd_ctril, 'U', hs.grid.resizeWindowTaller) hs.hotkey.bind(opt_cmd_ctril, 'O', hs.grid.resizeWindowWider) hs.hotkey.bind(opt_cmd_ctril, 'I', hs.grid.resizeWindowThinner) hs.hotkey.bind(opt_cmd_ctril, 'Y', hs.grid.resizeWindowShorter) hs.hotkey.bind(ctril_opt_shift, 'space', hs.itunes.displayCurrentTrack) hs.hotkey.bind(ctril_opt_shift, 'P', hs.itunes.play) hs.hotkey.bind(ctril_opt_shift, 'O', hs.itunes.pause) hs.hotkey.bind(ctril_opt_shift, 'N', hs.itunes.next) hs.hotkey.bind(ctril_opt_shift, 'I', hs.itunes.previous) hs.hotkey.bind(cmd_opt_shift, ']', function() set_volume( volumeIncrement ) end) hs.hotkey.bind(cmd_opt_shift, '[', function() set_volume( -1 * volumeIncrement ) end) hs.hotkey.bind(cmd_opt_shift, '\\', function() toggle_muted() end) -- hs.hotkey.bind(cmd_opt_shift, 'j', function() move_focused_window(hs.window.focusWindowWest) end) -- hs.hotkey.bind(cmd_opt_shift, 'k', function() move_focused_window(hs.window.focusWindowEast) end) -- hs.hotkey.bind(cmd_opt_shift, 'l', function() move_focused_window(hs.window.focusWindowSouth) end) -- hs.hotkey.bind(cmd_opt_shift, ';', function() move_focused_window(hs.window.focusWindowNorth) end) function _move_window_left(f, max) f.x = max.x + (max.w / 2) f.y = max.y f.w = max.w / 2 f.h = max.h return f end function _move_window_right(f, max) f.x = max.x f.y = max.y f.w = max.w / 2 f.h = max.h return f end function _move_window_up(f, max) f.x = max.x f.y = max.y f.w = max.w f.h = max.h / 2 return f end function _move_window_down(f, max) f.x = max.x f.y = max.y + (max.h / 2) f.w = max.w f.h = max.h / 2 return f end function move_window_on_screen(new_frame_fn) if hs.window.focusedWindow() then local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() win:setFrame(new_frame_fn(f, max)) else hs.alert.show("No active window") end end hs.hotkey.bind(opt_cmd_ctril, 'j', function() move_window_on_screen(_move_window_left) end) hs.hotkey.bind(opt_cmd_ctril, 'k', function() move_window_on_screen(_move_window_down) end) hs.hotkey.bind(opt_cmd_ctril, 'l', function() move_window_on_screen(_move_window_up) end) hs.hotkey.bind(opt_cmd_ctril, ';', function() move_window_on_screen(_move_window_right) end) function reload_config(files) hs.reload() hs.alert.show("Config loaded") end hs.pathwatcher.new(os.getenv("HOME") .. "/.hammerspoon/", reload_config):start() hs.alert.show("Hammerspoon, at your service.", 3)
Correct logic bugs in _move_window_[up,down].
Correct logic bugs in _move_window_[up,down].
Lua
mit
skk/dotfiles,skk/dotfiles
079592ad831cd7a5fdddd91e05d4ca64fb9a643a
otouto/plugins/wikipedia.lua
otouto/plugins/wikipedia.lua
local wikipedia = {} wikipedia.command = 'wiki <Begriff>' function wikipedia:init(config) wikipedia.triggers = { "^/[Ww]iki(%w+) (search) (.+)$", "^/[Ww]iki (search) ?(.*)$", "^/[Ww]iki(%w+) (.+)$", "^/[Ww]iki ?(.*)$", "(%w+).wikipedia.org/wiki/(.+)" } wikipedia.inline_triggers = { "^wiki(%w+) (.+)", "^wiki (.+)" } wikipedia.doc = [[* ]]..config.cmd_pat..[[wiki* _<Begriff>_: Gibt Wikipedia-Artikel aus Alias: ]]..config.cmd_pat..[[wikipedia]] end local decodetext do local char, gsub, tonumber = string.char, string.gsub, tonumber local function _(hex) return char(tonumber(hex, 16)) end function decodetext(s) s = gsub(s, '%%(%x%x)', _) return s end end local server = { -- http://meta.wikimedia.org/wiki/List_of_Wikipedias wiki_server = "https://%s.wikipedia.org", wiki_path = "/w/api.php", wiki_load_params = { action = "query", prop = "extracts", format = "json", exchars = 350, exsectionformat = "plain", explaintext = "", redirects = "" }, wiki_search_params = { action = "query", list = "search", srlimit = 20, format = "json", }, default_lang = "de", } function wikipedia:getWikiServer(lang) return string.format(server.wiki_server, lang or server.default_lang) end --[[ -- return decoded JSON table from Wikipedia --]] function wikipedia:loadPage(text, lang, intro, plain, is_search) local request, sink = {}, {} local query = "" local parsed if is_search then for k,v in pairs(server.wiki_search_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(wikipedia:getWikiServer(lang)) parsed.path = server.wiki_path parsed.query = query .. "srsearch=" .. URL.escape(text) else server.wiki_load_params.explaintext = plain and "" or nil for k,v in pairs(server.wiki_load_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(wikipedia:getWikiServer(lang)) parsed.path = server.wiki_path parsed.query = query .. "titles=" .. URL.escape(text) end -- HTTP request request['url'] = URL.build(parsed) request['method'] = 'GET' request['sink'] = ltn12.sink.table(sink) local httpRequest = parsed.scheme == 'http' and http.request or https.request local code, headers, status = socket.skip(1, httpRequest(request)) if not headers or not sink then return nil end local content = table.concat(sink) if content ~= "" then local ok, result = pcall(json.decode, content) if ok and result then return result else return nil end else return nil end end -- extract intro passage in wiki page function wikipedia:wikintro(text, lang, is_inline) local text = decodetext(text) local result = self:loadPage(text, lang, true, true) if result and result.query then local query = result.query if query and query.normalized then text = query.normalized[1].to or text end local page = query.pages[next(query.pages)] if page and page.extract then local lang = lang or "de" local title = page.title local title_enc = URL.escape(title) if is_inline then local result = '<b>'..title..'</b>:\n'..page.extract local result = result:gsub('\n', '\\n') local result = result:gsub('"', '\\"') return title, result, '{"inline_keyboard":[[{"text":"Wikipedia aufrufen","url":"https://'..lang..'.wikipedia.org/wiki/'..title_enc..'"}]]}' else return '*'..title..'*:\n'..utilities.md_escape(page.extract), '{"inline_keyboard":[[{"text":"Artikel aufrufen","url":"https://'..lang..'.wikipedia.org/wiki/'..title_enc..'"}]]}' end else if is_inline then return nil else local text = text.." nicht gefunden" return text end end else if is_inline then return nil else return "Ein Fehler ist aufgetreten." end end end -- search for term in wiki function wikipedia:wikisearch(text, lang) local result = wiki:loadPage(text, lang, true, true, true) if result and result.query then local titles = "" for i,item in pairs(result.query.search) do titles = titles .. "\n" .. item["title"] end titles = titles ~= "" and titles or "Keine Ergebnisse gefunden" return titles else return "Ein Fehler ist aufgetreten." end end function wikipedia:snip_snippet(snippet) local snippet = snippet:gsub("<span class%=\"searchmatch\">", "") local snippet = snippet:gsub("</span>", "") return snippet end function wikipedia:inline_callback(inline_query, config, matches) if matches[2] then lang = matches[1] query = matches[2] else lang = 'de' query = matches[1] end local search_url = 'https://'..lang..'.wikipedia.org/w/api.php?action=query&list=search&srsearch='..URL.escape(query)..'&format=json&prop=extracts&srprop=snippet&&srlimit=5' local res, code = https.request(search_url) if code ~= 200 then abort_inline_query(inline_query) return end local data = json.decode(res).query local results = '[' local id = 700 for num in pairs(data.search) do local title, result, keyboard = wikipedia:wikintro(data.search[num].title, lang, true) if not title or not result or not keyboard then abort_inline_query(inline_query) return end results = results..'{"type":"article","id":"'..id..'","title":"'..title..'","description":"'..wikipedia:snip_snippet(data.search[num].snippet)..'","url":"https://'..lang..'.wikipedia.org/wiki/'..URL.escape(title)..'","hide_url":true,"thumb_url":"https://anditest.perseus.uberspace.de/inlineQuerys/wiki/logo.jpg","thumb_width":95,"thumb_height":86,"reply_markup":'..keyboard..',"input_message_content":{"message_text":"'..result..'","parse_mode":"HTML"}}' id = id+1 if num < #data.search then results = results..',' end end local results = results..']' utilities.answer_inline_query(inline_query, results, 3600) end function wikipedia:action(msg, config, matches) local search, term, lang if matches[1] == "search" then search = true term = matches[2] lang = nil elseif matches[2] == "search" then search = true term = matches[3] lang = matches[1] else term = matches[2] lang = matches[1] end if not term then term = lang lang = nil end if term == "" then utilities.send_reply(msg, wikipedia.doc, true) return end local result if search then result = wikipedia:wikisearch(term, lang) else result, keyboard = wikipedia:wikintro(term, lang) end utilities.send_reply(msg, result, true, keyboard) end return wikipedia
local wikipedia = {} wikipedia.command = 'wiki <Begriff>' function wikipedia:init(config) wikipedia.triggers = { "^/[Ww]iki(%w+) (search) (.+)$", "^/[Ww]iki (search) ?(.*)$", "^/[Ww]iki(%w+) (.+)$", "^/[Ww]iki ?(.*)$", "(%w+).m.wikipedia.org/wiki/(.+)", "(%w+).wikipedia.org/wiki/(.+)" } wikipedia.inline_triggers = { "^wiki(%w+) (.+)", "^wiki (.+)" } wikipedia.doc = [[* ]]..config.cmd_pat..[[wiki* _<Begriff>_: Gibt Wikipedia-Artikel aus Alias: ]]..config.cmd_pat..[[wikipedia]] end local decodetext do local char, gsub, tonumber = string.char, string.gsub, tonumber local function _(hex) return char(tonumber(hex, 16)) end function decodetext(s) s = gsub(s, '%%(%x%x)', _) return s end end local server = { -- http://meta.wikimedia.org/wiki/List_of_Wikipedias wiki_server = "https://%s.wikipedia.org", wiki_path = "/w/api.php", wiki_load_params = { action = "query", prop = "extracts", format = "json", exchars = 350, exsectionformat = "plain", explaintext = "", redirects = "" }, wiki_search_params = { action = "query", list = "search", srlimit = 20, format = "json", }, default_lang = "de", } function wikipedia:getWikiServer(lang) return string.format(server.wiki_server, lang or server.default_lang) end --[[ -- return decoded JSON table from Wikipedia --]] function wikipedia:loadPage(text, lang, intro, plain, is_search) local request, sink = {}, {} local query = "" local parsed if is_search then for k,v in pairs(server.wiki_search_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(wikipedia:getWikiServer(lang)) parsed.path = server.wiki_path parsed.query = query .. "srsearch=" .. URL.escape(text) else server.wiki_load_params.explaintext = plain and "" or nil for k,v in pairs(server.wiki_load_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(wikipedia:getWikiServer(lang)) parsed.path = server.wiki_path parsed.query = query .. "titles=" .. URL.escape(text) end -- HTTP request request['url'] = URL.build(parsed) request['method'] = 'GET' request['sink'] = ltn12.sink.table(sink) local httpRequest = parsed.scheme == 'http' and http.request or https.request local code, headers, status = socket.skip(1, httpRequest(request)) if not headers or not sink then return nil end local content = table.concat(sink) if content ~= "" then local ok, result = pcall(json.decode, content) if ok and result then return result else return nil end else return nil end end -- extract intro passage in wiki page function wikipedia:wikintro(text, lang, is_inline) local text = decodetext(text) local result = self:loadPage(text, lang, true, true) if result and result.query then local query = result.query if query and query.normalized then text = query.normalized[1].to or text end local page = query.pages[next(query.pages)] if page and page.extract then local lang = lang or "de" local title = page.title local title_enc = URL.escape(title) if is_inline then local result = '<b>'..title..'</b>:\n'..page.extract local result = result:gsub('\n', '\\n') local result = result:gsub('"', '\\"') return title, result, '{"inline_keyboard":[[{"text":"Wikipedia aufrufen","url":"https://'..lang..'.wikipedia.org/wiki/'..title_enc..'"}]]}' else return '*'..title..'*:\n'..utilities.md_escape(page.extract), '{"inline_keyboard":[[{"text":"Artikel aufrufen","url":"https://'..lang..'.wikipedia.org/wiki/'..title_enc..'"}]]}' end else if is_inline then return nil else local text = text.." nicht gefunden" return text end end else if is_inline then return nil else return "Ein Fehler ist aufgetreten." end end end -- search for term in wiki function wikipedia:wikisearch(text, lang) local result = wiki:loadPage(text, lang, true, true, true) if result and result.query then local titles = "" for i,item in pairs(result.query.search) do titles = titles .. "\n" .. item["title"] end titles = titles ~= "" and titles or "Keine Ergebnisse gefunden" return titles else return "Ein Fehler ist aufgetreten." end end function wikipedia:snip_snippet(snippet) local snippet = snippet:gsub("<span class%=\"searchmatch\">", "") local snippet = snippet:gsub("</span>", "") return snippet end function wikipedia:inline_callback(inline_query, config, matches) if matches[2] then lang = matches[1] query = matches[2] else lang = 'de' query = matches[1] end local search_url = 'https://'..lang..'.wikipedia.org/w/api.php?action=query&list=search&srsearch='..URL.escape(query)..'&format=json&prop=extracts&srprop=snippet&&srlimit=5' local res, code = https.request(search_url) if code ~= 200 then abort_inline_query(inline_query) return end local data = json.decode(res).query local results = '[' local id = 700 for num in pairs(data.search) do local title, result, keyboard = wikipedia:wikintro(data.search[num].title, lang, true) if not title or not result or not keyboard then abort_inline_query(inline_query) return end results = results..'{"type":"article","id":"'..id..'","title":"'..title..'","description":"'..wikipedia:snip_snippet(data.search[num].snippet)..'","url":"https://'..lang..'.wikipedia.org/wiki/'..URL.escape(title)..'","hide_url":true,"thumb_url":"https://anditest.perseus.uberspace.de/inlineQuerys/wiki/logo.jpg","thumb_width":95,"thumb_height":86,"reply_markup":'..keyboard..',"input_message_content":{"message_text":"'..result..'","parse_mode":"HTML"}}' id = id+1 if num < #data.search then results = results..',' end end local results = results..']' utilities.answer_inline_query(inline_query, results, 3600) end function wikipedia:action(msg, config, matches) local search, term, lang if matches[1] == "search" then search = true term = matches[2] lang = nil elseif matches[2] == "search" then search = true term = matches[3] lang = matches[1] else term = matches[2] lang = matches[1] end if not term then term = lang lang = nil end if term == "" then utilities.send_reply(msg, wikipedia.doc, true) return end local result if search then result = wikipedia:wikisearch(term, lang) else result, keyboard = wikipedia:wikintro(term, lang) end utilities.send_reply(msg, result, true, keyboard) end return wikipedia
Fixe Wikipedia-Mobile-Links
Fixe Wikipedia-Mobile-Links
Lua
agpl-3.0
Brawl345/Brawlbot-v2
5b7c483906f97d31b8c74e6bc1ee8fd50f63040c
lua/mediaplayer/players/entity/shared.lua
lua/mediaplayer/players/entity/shared.lua
include "sh_meta.lua" DEFINE_BASECLASS( "mp_base" ) --[[--------------------------------------------------------- Entity Media Player -----------------------------------------------------------]] local MEDIAPLAYER = MEDIAPLAYER MEDIAPLAYER.Name = "entity" function MEDIAPLAYER:IsValid() return self.Entity and IsValid(self.Entity) end function MEDIAPLAYER:Init(...) BaseClass.Init(self, ...) if SERVER then -- Manually manage listeners by default self._TransmitState = TRANSMIT_NEVER end end function MEDIAPLAYER:SetEntity(ent) self.Entity = ent if SERVER then local creator = ent:GetCreator() if IsValid(creator) and creator:IsPlayer() then self:SetOwner(creator) end else -- Setup hooks for drawing the screen onto the entity hook.Add( "HUDPaint", self, self.DrawFullscreen ) hook.Add( "PostDrawOpaqueRenderables", self, self.Draw ) end end function MEDIAPLAYER:GetEntity() -- Clients may wait for the entity to become valid if CLIENT and self._EntIndex then local ent = Entity(self._EntIndex) if IsValid(ent) and ent ~= NULL then ent:InstallMediaPlayer(self) self._EntIndex = nil else return nil end end return self.Entity end function MEDIAPLAYER:GetPos() return IsValid(self.Entity) and self.Entity:GetPos() or Vector(0,0,0) end function MEDIAPLAYER:GetLocation() if IsValid(self.Entity) and self.Entity.Location then return self.Entity:Location() end return self._Location end function MEDIAPLAYER:Think() BaseClass.Think(self) local ent = self:GetEntity() if IsValid(ent) then -- Lua refresh fix if ent._mp ~= self then self:Remove() end elseif SERVER then -- Only remove on the server since the client may still be connecting -- and the entity will be created when they finish. self:Remove() end end function MEDIAPLAYER:Remove() -- remove draw hooks if CLIENT then hook.Remove( "HUDPaint", self ) hook.Remove( "PostDrawOpaqueRenderables", self ) end -- remove reference to media player installed on entity if self.Entity then self.Entity._mp = nil end BaseClass.Remove(self) end
include "sh_meta.lua" DEFINE_BASECLASS( "mp_base" ) --[[--------------------------------------------------------- Entity Media Player -----------------------------------------------------------]] local MEDIAPLAYER = MEDIAPLAYER MEDIAPLAYER.Name = "entity" function MEDIAPLAYER:IsValid() local ent = self.Entity if ent then return IsValid(ent) end -- Client may still be waiting on the entity to be created by the network; -- let's just say it's valid until the entity is setup return true end function MEDIAPLAYER:Init(...) BaseClass.Init(self, ...) if SERVER then -- Manually manage listeners by default self._TransmitState = TRANSMIT_NEVER end end function MEDIAPLAYER:SetEntity(ent) self.Entity = ent if SERVER then local creator = ent:GetCreator() if IsValid(creator) and creator:IsPlayer() then self:SetOwner(creator) end else -- Setup hooks for drawing the screen onto the entity hook.Add( "HUDPaint", self, self.DrawFullscreen ) hook.Add( "PostDrawOpaqueRenderables", self, self.Draw ) end end function MEDIAPLAYER:GetEntity() -- Clients may wait for the entity to become valid if CLIENT and self._EntIndex then local ent = Entity(self._EntIndex) if IsValid(ent) and ent ~= NULL then ent:InstallMediaPlayer(self) self._EntIndex = nil else return nil end end return self.Entity end function MEDIAPLAYER:GetPos() return IsValid(self.Entity) and self.Entity:GetPos() or Vector(0,0,0) end function MEDIAPLAYER:GetLocation() if IsValid(self.Entity) and self.Entity.Location then return self.Entity:Location() end return self._Location end function MEDIAPLAYER:Think() BaseClass.Think(self) local ent = self:GetEntity() if IsValid(ent) then -- Lua refresh fix if ent._mp ~= self then self:Remove() end elseif SERVER then -- Only remove on the server since the client may still be connecting -- and the entity will be created when they finish. self:Remove() end end function MEDIAPLAYER:Remove() -- remove draw hooks if CLIENT then hook.Remove( "HUDPaint", self ) hook.Remove( "PostDrawOpaqueRenderables", self ) end -- remove reference to media player installed on entity if self.Entity then self.Entity._mp = nil end BaseClass.Remove(self) end
Fixed media players getting removed on the client if it takes too long for the entity to be created by the network.
Fixed media players getting removed on the client if it takes too long for the entity to be created by the network.
Lua
mit
pixeltailgames/gm-mediaplayer,pixeltailgames/gm-mediaplayer
3c85fc482b8f98e8843182cabf661ec2af6194ca
.config/nvim/lua/config/jaq.lua
.config/nvim/lua/config/jaq.lua
local status_ok, p = pcall(require, "jaq-nvim") if not status_ok then return end p.setup({ cmds = { default = "toggleterm", external = { typescript = "node %", javascript = "node %", markdown = "glow %", python = "python3 %", rust = "rustc % && ./$fileBase && rm $fileBase", cpp = "g++ % -o $fileBase && ./$fileBase", go = "go run %", sh = "sh %", ruby = "ruby %", rspec = "rspec %", }, }, ui = { toggleterm = { position = "float", }, }, }) local opts = { noremap = true, silent = true } local keymap = vim.api.nvim_set_keymap keymap("n", "<Leader>x", "<Cmd>Jaq<CR>", opts)
local status_ok, p = pcall(require, "jaq-nvim") if not status_ok then return end p.setup({ cmds = { external = { typescript = "node %", javascript = "node %", markdown = "glow %", python = "python3 %", rust = "rustc % && ./$fileBase && rm $fileBase", cpp = "g++ % -o $fileBase && ./$fileBase", go = "go run %", sh = "sh %", ruby = "ruby %", rspec = "rspec %", }, }, behavior = { default = "terminal", }, ui = { terminal = { position = "bot", size = 10, line_no = false, }, }, }) local opts = { noremap = true, silent = true } local keymap = vim.api.nvim_set_keymap keymap("n", "<Leader>x", "<Cmd>Jaq<CR><C-w>k", opts)
[nvim] Fix jaq config
[nvim] Fix jaq config
Lua
mit
masa0x80/dotfiles,masa0x80/dotfiles,masa0x80/dotfiles,masa0x80/dotfiles
f3d1f9a93ec148ff04f95f58f8a88d824101746a
src/extensions/cp/ui/RadioGroup.lua
src/extensions/cp/ui/RadioGroup.lua
--- === cp.ui.RadioGroup === --- --- Represents an `AXRadioGroup`, providing utility methods. -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- local require = require -------------------------------------------------------------------------------- -- Logger: -------------------------------------------------------------------------------- --local log = require("hs.logger").new("radioGroup") -------------------------------------------------------------------------------- -- Hammerspoon Extensions: -------------------------------------------------------------------------------- --local inspect = require("hs.inspect") -------------------------------------------------------------------------------- -- CommandPost Extensions: -------------------------------------------------------------------------------- local Element = require("cp.ui.Element") local go = require("cp.rx.go") local If, Throw, WaitUntil = go.If, go.Throw, go.WaitUntil -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local RadioGroup = Element:subclass("RadioGroup") --- cp.ui.RadioGroup.matches(element) -> boolean --- Function --- Checks if the provided `axuielement` is a RadioGroup. --- --- Parameters: --- * element - The element to check. --- --- Returns: --- * `true` if the element is a RadioGroup. function RadioGroup.static.matches(element) return Element.matches(element) and element:attributeValue("AXRole") == "AXRadioGroup" end --- cp.ui.RadioGroup:new(parent, finderFn[, cached]) -> cp.ui.RadioGroup --- Constructor --- Creates a new RadioGroup. --- --- Parameters: --- * parent - The parent table. --- * finderFn - The function which will find the `axuielement` representing the RadioGroup. --- --- Returns: --- * The new `RadioGroup` instance. function RadioGroup:initialize(parent, finderFn) Element.initialize(self, parent, finderFn) end --- cp.ui.RadioGroup.optionCount <cp.prop: number; read-only> --- Field --- The number of options in the group. function RadioGroup.lazy.prop:optionCount() return self.UI:mutate( function(original) local ui = original() return ui and #ui or 0 end ) end --- cp.ui.RadioGroup.selectedOption <cp.prop: number> --- Field --- The currently selected option number. function RadioGroup.lazy.prop:selectedOption() return self.UI:mutate( function(original) local ui = original() if ui then for i,item in ipairs(ui:children()) do if item:attributeValue("AXValue") == 1 then return i end end end return nil end, function(index, original) local ui = original() if ui then if index >= 1 and index <= #ui then local item = ui[index] if item and item:attributeValue("AXValue") ~= 1 then item:doPress() return index end end end return nil end ) end --- cp.ui.RadioGroup:doSelectOption(index) -> cp.rx.go.Statement<boolean> --- Method --- A [Statement](cp.rx.go.Statement.md) which will attempt to select the option at the specified `index`. --- --- Parameters: --- * index - The index to select. Must be between 1 and [optionCount](#optionCount). --- --- Returns: --- * The `Statement`, which will resolve to `true` if successful or send an error if not. function RadioGroup:doSelectOption(index) return If(self.isEnabled) :Then(function() local count = self:optionCount() if index < 1 or index > count then return Throw("Selected index must be between 1 and %d, but was %d", count, index) end self:selectedOption(index) return WaitUntil(self.selectedOption):Is(index) :TimeoutAfter(1000, Throw("Failed to select item %d", index)) end) :Otherwise(Throw("The radio group is unavailable.")) :Label("RadioGroup:doSelectOption") end --- cp.ui.RadioGroup:nextOption() -> self --- Method --- Selects the next option in the group. Cycles from the last to the first option. --- --- Parameters: --- * None --- --- Returns: --- * The `RadioGroup`. function RadioGroup:nextOption() local selected = self:selectedOption() local count = self:optionCount() selected = selected >= count and 1 or selected + 1 self:selectedOption(selected) return self end --- cp.ui.RadioGroup:doNextOption() -> cp.rx.go.Statement<boolean> --- Method --- A [Statement](cp.rx.go.Statement.md) that selects the next option in the group. --- Cycles from the last to the first option. --- --- Parameters: --- * None --- --- Returns: --- * The `Statement`, that resolves to `true` if successful or sends an error if not. function RadioGroup.lazy.method:doNextOption() return If(self.isEnabled) :Then(function() local selected = self:selectedOption() local count = self:optionCount() selected = selected >= count and 1 or selected + 1 return self:doSelectOption(selected) end) :Otherwise(Throw("The radio group is unavailable.")) :Label("RadioGroup:doNextOption") end --- cp.ui.RadioGroup:previousOption() -> self --- Method --- Selects the previous option in the group. Cycles from the first to the last item. --- --- Parameters: --- * None --- --- Returns: --- * The `RadioGroup`. function RadioGroup:previousOption() local selected = self:selectedOption() local count = self:optionCount() selected = selected <= 1 and count or selected - 1 self:selectedOption(selected) return self end --- cp.ui.RadioGroup:doPreviousOption() -> cp.rx.go.Statement<boolean> --- Method --- A [Statement](cp.rx.go.Statement.md) that selects the previous option in the group. --- Cycles from the first to the last item. --- --- Parameters: --- * None --- --- Returns: --- * The `Statement`, which resolves to `true` if successful or sends an error if not.. function RadioGroup.lazy.method:doPreviousOption() return If(self.isEnabled) :Then(function() local selected = self:selectedOption() local count = self:optionCount() selected = selected <= 1 and count or selected - 1 return self:doSelectOption(selected) end) :Otherwise(Throw("The radio group is unavailable.")) :Label("RadioGroup:doNextOption") end function RadioGroup.__tostring() return "cp.ui.RadioGroup" end return RadioGroup
--- === cp.ui.RadioGroup === --- --- Represents an `AXRadioGroup`, providing utility methods. -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- local require = require -------------------------------------------------------------------------------- -- Logger: -------------------------------------------------------------------------------- --local log = require("hs.logger").new("radioGroup") -------------------------------------------------------------------------------- -- Hammerspoon Extensions: -------------------------------------------------------------------------------- --local inspect = require("hs.inspect") -------------------------------------------------------------------------------- -- CommandPost Extensions: -------------------------------------------------------------------------------- local Element = require("cp.ui.Element") local go = require("cp.rx.go") local If, Throw, WaitUntil = go.If, go.Throw, go.WaitUntil -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local RadioGroup = Element:subclass("RadioGroup") --- cp.ui.RadioGroup.matches(element) -> boolean --- Function --- Checks if the provided `axuielement` is a RadioGroup. --- --- Parameters: --- * element - The element to check. --- --- Returns: --- * `true` if the element is a RadioGroup. function RadioGroup.static.matches(element) return Element.matches(element) and element:attributeValue("AXRole") == "AXRadioGroup" end --- cp.ui.RadioGroup:new(parent, finderFn[, cached]) -> cp.ui.RadioGroup --- Constructor --- Creates a new RadioGroup. --- --- Parameters: --- * parent - The parent table. --- * finderFn - The function which will find the `axuielement` representing the RadioGroup. --- --- Returns: --- * The new `RadioGroup` instance. function RadioGroup:initialize(parent, finderFn) Element.initialize(self, parent, finderFn) end --- cp.ui.RadioGroup.optionCount <cp.prop: number; read-only> --- Field --- The number of options in the group. function RadioGroup.lazy.prop:optionCount() return self.UI:mutate( function(original) local ui = original() return ui and #ui or 0 end ) end --- cp.ui.RadioGroup.selectedOption <cp.prop: number> --- Field --- The currently selected option number. function RadioGroup.lazy.prop:selectedOption() return self.UI:mutate( function(original) local ui = original() if ui then for i,item in ipairs(ui:children()) do if item:attributeValue("AXValue") == 1 then return i end end end return nil end, function(index, original) local ui = original() if ui then if index >= 1 and index <= #ui then local item = ui[index] if item and item:attributeValue("AXValue") ~= 1 then item:doPress() return index end end end return nil end ) end --- cp.ui.RadioGroup:doSelectOption(index) -> cp.rx.go.Statement<boolean> --- Method --- A [Statement](cp.rx.go.Statement.md) which will attempt to select the option at the specified `index`. --- --- Parameters: --- * index - The index to select. Must be between 1 and [optionCount](#optionCount). --- --- Returns: --- * The `Statement`, which will resolve to `true` if successful or send an error if not. function RadioGroup:doSelectOption(index) return If(self.isEnabled) :Then(function() local count = self:optionCount() if index < 1 or index > count then return Throw("Selected index must be between 1 and %d, but was %d", count, index) end self:selectedOption(index) return WaitUntil(self.selectedOption):Is(index) :TimeoutAfter(1000, Throw("Failed to select item %d", index)) end) :Otherwise(Throw("The radio group is unavailable.")) :Label("RadioGroup:doSelectOption") end --- cp.ui.RadioGroup:nextOption() -> self --- Method --- Selects the next option in the group. Cycles from the last to the first option. --- --- Parameters: --- * None --- --- Returns: --- * The `RadioGroup`. function RadioGroup:nextOption() local selected = self:selectedOption() local count = self:optionCount() if selected and count then selected = selected >= count and 1 or selected + 1 self:selectedOption(selected) end return self end --- cp.ui.RadioGroup:doNextOption() -> cp.rx.go.Statement<boolean> --- Method --- A [Statement](cp.rx.go.Statement.md) that selects the next option in the group. --- Cycles from the last to the first option. --- --- Parameters: --- * None --- --- Returns: --- * The `Statement`, that resolves to `true` if successful or sends an error if not. function RadioGroup.lazy.method:doNextOption() return If(self.isEnabled) :Then(function() local selected = self:selectedOption() local count = self:optionCount() selected = selected >= count and 1 or selected + 1 return self:doSelectOption(selected) end) :Otherwise(Throw("The radio group is unavailable.")) :Label("RadioGroup:doNextOption") end --- cp.ui.RadioGroup:previousOption() -> self --- Method --- Selects the previous option in the group. Cycles from the first to the last item. --- --- Parameters: --- * None --- --- Returns: --- * The `RadioGroup`. function RadioGroup:previousOption() local selected = self:selectedOption() local count = self:optionCount() if selected and count then selected = selected <= 1 and count or selected - 1 self:selectedOption(selected) end return self end --- cp.ui.RadioGroup:doPreviousOption() -> cp.rx.go.Statement<boolean> --- Method --- A [Statement](cp.rx.go.Statement.md) that selects the previous option in the group. --- Cycles from the first to the last item. --- --- Parameters: --- * None --- --- Returns: --- * The `Statement`, which resolves to `true` if successful or sends an error if not.. function RadioGroup.lazy.method:doPreviousOption() return If(self.isEnabled) :Then(function() local selected = self:selectedOption() local count = self:optionCount() selected = selected <= 1 and count or selected - 1 return self:doSelectOption(selected) end) :Otherwise(Throw("The radio group is unavailable.")) :Label("RadioGroup:doNextOption") end function RadioGroup.__tostring() return "cp.ui.RadioGroup" end return RadioGroup
#1475
#1475 - Bug fix in `cp.ui.RadioGroup`
Lua
mit
fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks
221ce985260f90b00daf522225d4db00b9eccb56
packages/grid.lua
packages/grid.lua
local gridSpacing -- Should be a setting local makeUp = function () local toadd = gridSpacing - (SILE.typesetter.frame.state.totals.gridCursor % gridSpacing) SILE.typesetter.frame.state.totals.gridCursor = SILE.typesetter.frame.state.totals.gridCursor + toadd return SILE.nodefactory.newVglue({ height = SILE.length.new({ length = toadd }) }) end local leadingFor = function(this, vbox, previous) if not this.frame.state.totals.gridCursor then this.frame.state.totals.gridCursor = SILE.typesetter.frame.state.cursorY end this.frame.state.totals.gridCursor = this.frame.state.totals.gridCursor + previous.height.length + previous.depth.length return makeUp() end local pushVglue = function(this, spec) if not this.frame.state.totals.gridCursor then this.frame.state.totals.gridCursor = SILE.typesetter.frame.state.cursorY end this.frame.state.totals.gridCursor = this.frame.state.totals.gridCursor + spec.height.length SILE.defaultTypesetter.pushVglue(this, spec); SILE.defaultTypesetter.pushVglue(this, makeUp()) end local newBoxup = function (this) local b = SILE.defaultTypesetter.boxUpNodes(this) if #b > 1 then this.frame.state.totals.gridCursor = this.frame.state.totals.gridCursor + b[#b].height.length + b[#b].depth.length end return b end local debugGrid = function() local t = SILE.typesetter if not t.frame.state.totals.gridCursor then t.frame.state.totals.gridCursor = SILE.typesetter.frame.state.cursorY end local g = t.frame.state.totals.gridCursor while g < t.frame:bottom() do SILE.outputter.rule(t.frame:left(), g, t.frame:width(), 0.1) g = g + gridSpacing end end SILE.registerCommand("grid", function(options, content) SU.required(options, "spacing", "grid package") gridSpacing = SILE.parseComplexFrameDimension(options.spacing,"h"); SILE.typesetter:chuck() SILE.typesetter.leadingFor = leadingFor SILE.typesetter.pushVglue = pushVglue SILE.typesetter.boxUpNodes = newBoxup SILE.typesetter.setVerticalGlue = function () end SILE.typesetter.frame.state.totals.gridCursor = SILE.typesetter.frame.state.cursorY -- add some now SILE.defaultTypesetter.pushVglue(SILE.typesetter, makeUp()) end, "Begins typesetting on a grid spaced at <spacing> intervals.") SILE.registerCommand("no-grid", function (options, content) SILE.typesetter.leadingFor = SILE.defaultTypesetter.leadingFor SILE.typesetter.pushVglue = SILE.defaultTypesetter.pushVglue SILE.typesetter.setVerticalGlue = SILE.defaultTypesetter.setVerticalGlue -- SILE.typesetter.state = t.state end, "Stops grid typesetting.")
local gridSpacing -- Should be a setting local makeUp = function () local toadd = gridSpacing - (SILE.typesetter.frame.state.totals.gridCursor % gridSpacing) SILE.typesetter.frame.state.totals.gridCursor = SILE.typesetter.frame.state.totals.gridCursor + toadd return SILE.nodefactory.newVglue({ height = SILE.length.new({ length = toadd }) }) end local leadingFor = function(this, vbox, previous) if not this.frame.state.totals.gridCursor then this.frame.state.totals.gridCursor = SILE.typesetter.frame.state.cursorY end this.frame.state.totals.gridCursor = this.frame.state.totals.gridCursor + previous.height.length + previous.depth.length return makeUp() end local pushVglue = function(this, spec) if not this.frame.state.totals.gridCursor then this.frame.state.totals.gridCursor = SILE.typesetter.frame.state.cursorY end this.frame.state.totals.gridCursor = this.frame.state.totals.gridCursor + spec.height.length SILE.defaultTypesetter.pushVglue(this, spec); SILE.defaultTypesetter.pushVglue(this, makeUp()) end local newBoxup = function (this) local b = SILE.defaultTypesetter.boxUpNodes(this) if not this.frame.state.totals.gridCursor then this.frame.state.totals.gridCursor = SILE.typesetter.frame.state.cursorY end if #b > 1 then this.frame.state.totals.gridCursor = this.frame.state.totals.gridCursor + b[#b].height.length + b[#b].depth.length end return b end local debugGrid = function() local t = SILE.typesetter if not t.frame.state.totals.gridCursor then t.frame.state.totals.gridCursor = SILE.typesetter.frame.state.cursorY end local g = t.frame.state.totals.gridCursor while g < t.frame:bottom() do SILE.outputter.rule(t.frame:left(), g, t.frame:width(), 0.1) g = g + gridSpacing end end SILE.registerCommand("grid:debug", debugGrid) SILE.registerCommand("grid", function(options, content) SU.required(options, "spacing", "grid package") gridSpacing = SILE.parseComplexFrameDimension(options.spacing,"h"); SILE.typesetter:chuck() SILE.typesetter.leadingFor = leadingFor SILE.typesetter.pushVglue = pushVglue SILE.typesetter.boxUpNodes = newBoxup SILE.typesetter.setVerticalGlue = function () end SILE.typesetter.frame.state.totals.gridCursor = SILE.typesetter.frame.state.cursorY -- add some now SILE.defaultTypesetter.pushVglue(SILE.typesetter, makeUp()) end, "Begins typesetting on a grid spaced at <spacing> intervals.") SILE.registerCommand("no-grid", function (options, content) SILE.typesetter.leadingFor = SILE.defaultTypesetter.leadingFor SILE.typesetter.pushVglue = SILE.defaultTypesetter.pushVglue SILE.typesetter.setVerticalGlue = SILE.defaultTypesetter.setVerticalGlue -- SILE.typesetter.state = t.state end, "Stops grid typesetting.")
More fixes.
More fixes.
Lua
mit
neofob/sile,WAKAMAZU/sile_fe,anthrotype/sile,Nathan22Miles/sile,neofob/sile,alerque/sile,alerque/sile,WAKAMAZU/sile_fe,simoncozens/sile,shirat74/sile,anthrotype/sile,shirat74/sile,Nathan22Miles/sile,anthrotype/sile,shirat74/sile,simoncozens/sile,neofob/sile,alerque/sile,simoncozens/sile,WAKAMAZU/sile_fe,Nathan22Miles/sile,alerque/sile,Nathan22Miles/sile,Nathan22Miles/sile,WAKAMAZU/sile_fe,simoncozens/sile,anthrotype/sile,shirat74/sile,neofob/sile
1df53234825cadab5b93561dfd06e875c6fe2fab
mods/areas/api.lua
mods/areas/api.lua
-- Returns a list of areas that include the provided position function areas:getAreasAtPos(pos) local a = {} local px, py, pz = pos.x, pos.y, pos.z for id, area in pairs(self.areas) do local ap1, ap2 = area.pos1, area.pos2 if px >= ap1.x and px <= ap2.x and py >= ap1.y and py <= ap2.y and pz >= ap1.z and pz <= ap2.z then a[id] = area end end return a end -- Checks if the area is unprotected or owned by you function areas:canInteract(pos, name) if minetest.check_player_privs(name, self.adminPrivs) then return true end local owned = false if pos == nil then return not owned end -- pour éviter crash avec nénuphar for _, area in pairs(self:getAreasAtPos(pos)) do if area.owner == name or area.open then return true elseif area.openfarming then -- if area is openfarming and node is in group plant, action is authorized local node = minetest.get_node(pos).name if minetest.registered_nodes[node] and minetest.get_item_group(node, "plant") == 1 then return true end return false else owned = true end end return not owned end -- Returns a table (list) of all players that own an area function areas:getNodeOwners(pos) local owners = {} for _, area in pairs(self:getAreasAtPos(pos)) do table.insert(owners, area.owner) end return owners end --- Checks if the area intersects with an area that the player can't interact in. -- Note that this fails and returns false when the specified area is fully -- owned by the player, but with multiple protection zones, none of which -- cover the entire checked area. -- @param name (optional) player name. If not specified checks for any intersecting areas. -- @param allow_open Whether open areas should be counted as is they didn't exist. -- @return Boolean indicating whether the player can interact in that area. -- @return Un-owned intersecting area id, if found. function areas:canInteractInArea(pos1, pos2, name, allow_open) if name and minetest.check_player_privs(name, self.adminPrivs) then return true end areas:sortPos(pos1, pos2) -- First check for a fully enclosing owned area. if name then for id, area in pairs(self.areas) do -- A little optimization: isAreaOwner isn't necessary -- here since we're iterating through all areas. if area.owner == name and self:isSubarea(pos1, pos2, id) then return true end end end -- Then check for intersecting (non-owned) areas. for id, area in pairs(self.areas) do local p1, p2 = area.pos1, area.pos2 if (p1.x <= pos2.x and p2.x >= pos1.x) and (p1.y <= pos2.y and p2.y >= pos1.y) and (p1.z <= pos2.z and p2.z >= pos1.z) then -- Found an intersecting area. -- Return if the area is closed or open areas aren't -- allowed, and the area isn't owned. if (not allow_open or not area.open) and (not name or not areas:isAreaOwner(id, name)) then return false, id end end end return true end
--plants to place in openfarming local plants = { ["farming:blueberries"]=1, ["farming:muffin_blueberry"]=1, ["farming:carrot"]=1, ["farming:carrot_gold"]=1, ["farming:cocoa_beans"]=1, ["farming:cookie"]=1, ["farming:chocolate_dark"]=1, ["farming:coffee_beans"]=1, ["farming:corn"]=1, ["farming:corn_cob"]=1, ["farming:bottle_ethanol"]=1, ["farming:cotton"]=1, ["farming:cucumber"]=1, ["farming:donut"]=1, ["farming:donut_chocolate"]=1, ["farming:donut_apple"]=1, ["farming:melon_slice"]=1, ["farming:potato"]=1, ["farming:baked_potato"]=1, ["farming:pumpkin_slice"]=1, ["farming:pumpkin_bread"]=1, ["farming:pumpkin_dough"]=1, ["farming:raspberries"]=1, ["farming:smoothie_raspberry"]=1, ["farming:rhubarb"]=1, ["farming:rhubarb_pie"]=1, ["farming:sugar"]=1, ["farming:tomato"]=1, ["farming:wheat"]=1, ["farming:seed_cotton"]=1, ["farming:seed_wheat"]=1, ["default:papyrus"]=1 } --tools to dig in openfarming local in_hand = { ["hand"]=1, ["vines:shears"]=1, ["multitest:shears"]=1 , ["multitest:wood_shears"]=1,["multitest:stone_shears"]=1 } -- Returns a list of areas that include the provided position function areas:getAreasAtPos(pos) local a = {} local px, py, pz = pos.x, pos.y, pos.z for id, area in pairs(self.areas) do local ap1, ap2 = area.pos1, area.pos2 if px >= ap1.x and px <= ap2.x and py >= ap1.y and py <= ap2.y and pz >= ap1.z and pz <= ap2.z then a[id] = area end end return a end -- Checks if the area is unprotected or owned by you function areas:canInteract(pos, name) if minetest.check_player_privs(name, self.adminPrivs) then return true end local owned = false if pos == nil then return not owned end -- pour éviter crash avec nénuphar for _, area in pairs(self:getAreasAtPos(pos)) do if area.owner == name or area.open then return true elseif area.openfarming then -- if area is openfarming local node = minetest.get_node(pos).name if not minetest.registered_nodes[node] then return false end local player = minetest.get_player_by_name(name) if not player then return false end local wstack = player:get_wielded_item():get_name() if wstack == "" then wstack = "hand" end --on_place if node == "air" and plants[wstack] ~= nil then return true end --on_dig if minetest.get_item_group(node, "plant") == 1 and in_hand[wstack] ~= nil then return true end owned = true else owned = true end end return not owned end -- Returns a table (list) of all players that own an area function areas:getNodeOwners(pos) local owners = {} for _, area in pairs(self:getAreasAtPos(pos)) do table.insert(owners, area.owner) end return owners end --- Checks if the area intersects with an area that the player can't interact in. -- Note that this fails and returns false when the specified area is fully -- owned by the player, but with multiple protection zones, none of which -- cover the entire checked area. -- @param name (optional) player name. If not specified checks for any intersecting areas. -- @param allow_open Whether open areas should be counted as is they didn't exist. -- @return Boolean indicating whether the player can interact in that area. -- @return Un-owned intersecting area id, if found. function areas:canInteractInArea(pos1, pos2, name, allow_open) if name and minetest.check_player_privs(name, self.adminPrivs) then return true end areas:sortPos(pos1, pos2) -- First check for a fully enclosing owned area. if name then for id, area in pairs(self.areas) do -- A little optimization: isAreaOwner isn't necessary -- here since we're iterating through all areas. if area.owner == name and self:isSubarea(pos1, pos2, id) then return true end end end -- Then check for intersecting (non-owned) areas. for id, area in pairs(self.areas) do local p1, p2 = area.pos1, area.pos2 if (p1.x <= pos2.x and p2.x >= pos1.x) and (p1.y <= pos2.y and p2.y >= pos1.y) and (p1.z <= pos2.z and p2.z >= pos1.z) then -- Found an intersecting area. -- Return if the area is closed or open areas aren't -- allowed, and the area isn't owned. if (not allow_open or not area.open) and (not name or not areas:isAreaOwner(id, name)) then return false, id end end end return true end
fix bug in openfarming fix usebug in openfarming, when node is plant any node can be placed fix bug due to news protection in farming mod V1.12 add default:papyrus can be placed, no dig
fix bug in openfarming fix usebug in openfarming, when node is plant any node can be placed fix bug due to news protection in farming mod V1.12 add default:papyrus can be placed, no dig
Lua
unlicense
Coethium/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,paly2/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Ombridride/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun,sys4-fr/server-minetestforfun
1c6251dbd04c745d98fd7e6a3b816d263a361da5
cwtest.lua
cwtest.lua
require "pl.strict" -- enforced, on purpose ;) local tablex = require "pl.tablex" local pretty = require "pl.pretty" local printf = function(p,...) io.stdout:write(string.format(p,...)); io.stdout:flush() end local pass_assertion = function(self) printf(".") local info = debug.getinfo(3) self.successes[#self.successes+1] = string.format( "\n[OK] %s line %d (assertion)\n", info.short_src, info.currentline ) return true end local fail_assertion = function(self) printf("x") local info = debug.getinfo(3) self.failures[#self.failures+1] = string.format( "\n[KO] %s line %d (assertion)\n", info.short_src, info.currentline ) return false end local pass_eq = function(self,x,y) printf(".") local info = debug.getinfo(3) self.successes[#self.successes+1] = string.format( "\n[OK] %s line %d\n expected: %s\n got: %s\n", info.short_src, info.currentline, pretty.write(y,""), pretty.write(x,"") ) return true end local fail_eq = function(self,x,y) printf("x") local info = debug.getinfo(3) self.failures[#self.failures+1] = string.format( "\n[KO] %s line %d\n expected: %s\n got: %s\n", info.short_src, info.currentline, pretty.write(y,""), pretty.write(x,"") ) return false end local start = function(self,s) assert((not (self.failures or self.successes)),"test already started") self.failures,self.successes = {},{} printf("%s ",s) end local done = function(self) local f,s = self.failures,self.successes assert((f and s),"call start before done") if #f > 0 then print(" FAILED") for i=1,#f do io.stderr:write(f[i]) end print() else print(" OK") end if self.verbose and (#s > 0) then for i=1,#s do io.stderr:write(s[i]) end print() end self.failures,self.successes = nil,nil end local eq = function(self,x,y) local ok = (x == y) or tablex.deepcompare(x,y) return (ok and pass_eq or fail_eq)(self,x,y) end local seq = function(self,x,y) -- list-sets local ok = tablex.compare_no_order(x,y) return (ok and pass_eq or fail_eq)(self,x,y) end local is_true = function(self,x) return (x and pass_assertion or fail_assertion)(self) end local is_false = function(self,x) return (x and fail_assertion or pass_assertion)(self) end local methods = { start = start, done = done, eq = eq, seq = seq, yes = is_true, no = is_false, -- below: only to build custom tests pass_eq = pass_eq, fail_eq = fail_eq, pass_assertion = pass_assertion, fail_assertion = fail_assertion, } local new = function(verbose) return setmetatable({verbose = verbose or false},{__index = methods}) end return { new = new }
require "pl.strict" -- enforced, on purpose ;) local tablex = require "pl.tablex" local pretty = require "pl.pretty" local printf = function(p,...) io.stdout:write(string.format(p,...)); io.stdout:flush() end local pass_assertion = function(self) printf(".") local info = debug.getinfo(3) self.successes[#self.successes+1] = string.format( "\n[OK] %s line %d (assertion)\n", info.short_src, info.currentline ) return true end local fail_assertion = function(self) printf("x") local info = debug.getinfo(3) self.failures[#self.failures+1] = string.format( "\n[KO] %s line %d (assertion)\n", info.short_src, info.currentline ) return false end local pass_eq = function(self,x,y) printf(".") local info = debug.getinfo(3) self.successes[#self.successes+1] = string.format( "\n[OK] %s line %d\n expected: %s\n got: %s\n", info.short_src, info.currentline, pretty.write(y,""), pretty.write(x,"") ) return true end local fail_eq = function(self,x,y) printf("x") local info = debug.getinfo(3) self.failures[#self.failures+1] = string.format( "\n[KO] %s line %d\n expected: %s\n got: %s\n", info.short_src, info.currentline, pretty.write(y,""), pretty.write(x,"") ) return false end local start = function(self,s) assert((not (self.failures or self.successes)),"test already started") self.failures,self.successes = {},{} printf("%s ",s) end local done = function(self) local f,s = self.failures,self.successes assert((f and s),"call start before done") if #f > 0 then print(" FAILED") for i=1,#f do io.stderr:write(f[i]) end print() else print(" OK") end if self.verbose and (#s > 0) then for i=1,#s do io.stderr:write(s[i]) end print() end self.failures,self.successes = nil,nil end local eq = function(self,x,y) local ok = (x == y) or tablex.deepcompare(x,y) local r = (ok and pass_eq or fail_eq)(self,x,y) return r end local seq = function(self,x,y) -- list-sets local ok = tablex.compare_no_order(x,y) local r = (ok and pass_eq or fail_eq)(self,x,y) return r end local is_true = function(self,x) local r = (x and pass_assertion or fail_assertion)(self) return r end local is_false = function(self,x) local r = (x and fail_assertion or pass_assertion)(self) return r end local methods = { start = start, done = done, eq = eq, seq = seq, yes = is_true, no = is_false, -- below: only to build custom tests pass_eq = pass_eq, fail_eq = fail_eq, pass_assertion = pass_assertion, fail_assertion = fail_assertion, } local new = function(verbose) return setmetatable({verbose = verbose or false},{__index = methods}) end return { new = new }
fix tail call issue
fix tail call issue We must *avoid* the TCO here, otherwise we lose debug information.
Lua
mit
tst2005/cwtest,catwell/cwtest
d1047c9120d43f39435e1c73f462f00cad2c8408
extensions/base64/init.lua
extensions/base64/init.lua
--- === hs.base64 === --- --- Base64 encoding and decoding --- --- Portions sourced from (https://gist.github.com/shpakovski/1902994). local module = require("hs.base64.internal") -- private variables and methods ----------------------------------------- -- Public interface ------------------------------------------------------ --- hs.base64.encode(val[,width]) -> str --- Function --- Encodes a given string to base64 --- --- Parameters: --- * val - A string to encode as base64 --- * width - Optional line width to split the string into (usually 64 or 76) --- --- Returns: --- * A string containing the base64 representation of the input string module.encode = function(data, width) local _data = module._encode(data) if width then local _hold, i, j = _data, 1, width _data = "" repeat _data = _data.._hold:sub(i,j).."\n" i = i + width j = j + width until i > #_hold end return _data:sub(1,#_data - 1) end --- hs.base64.decode(str) -> val --- Function --- Decodes a given base64 string --- --- Parameters: --- * str - A base64 encoded string --- --- Returns: --- * A string containing the decoded data module.decode = function(data) return module._decode(data:gsub("[\r\n]+","")) end -- Return Module Object -------------------------------------------------- return module
--- === hs.base64 === --- --- Base64 encoding and decoding --- --- Portions sourced from (https://gist.github.com/shpakovski/1902994). local module = require("hs.base64.internal") -- private variables and methods ----------------------------------------- -- Public interface ------------------------------------------------------ --- hs.base64.encode(val[,width]) -> str --- Function --- Encodes a given string to base64 --- --- Parameters: --- * val - A string to encode as base64 --- * width - Optional line width to split the string into (usually 64 or 76) --- --- Returns: --- * A string containing the base64 representation of the input string module.encode = function(data, width) local _data = module._encode(data) if width then local _hold, i, j = _data, 1, width _data = "" repeat _data = _data.._hold:sub(i,j).."\n" i = i + width j = j + width until i > #_hold return _data:sub(1,#_data - 1) else return _data end end --- hs.base64.decode(str) -> val --- Function --- Decodes a given base64 string --- --- Parameters: --- * str - A base64 encoded string --- --- Returns: --- * A string containing the decoded data module.decode = function(data) return module._decode(data:gsub("[\r\n]+","")) end -- Return Module Object -------------------------------------------------- return module
hs.base64.encode without width lost last char
hs.base64.encode without width lost last char fixed
Lua
mit
nkgm/hammerspoon,nkgm/hammerspoon,zzamboni/hammerspoon,latenitefilms/hammerspoon,lowne/hammerspoon,knl/hammerspoon,TimVonsee/hammerspoon,wvierber/hammerspoon,emoses/hammerspoon,knu/hammerspoon,zzamboni/hammerspoon,ocurr/hammerspoon,knl/hammerspoon,joehanchoi/hammerspoon,knu/hammerspoon,latenitefilms/hammerspoon,wsmith323/hammerspoon,ocurr/hammerspoon,Stimim/hammerspoon,Hammerspoon/hammerspoon,peterhajas/hammerspoon,ocurr/hammerspoon,latenitefilms/hammerspoon,wvierber/hammerspoon,knl/hammerspoon,kkamdooong/hammerspoon,joehanchoi/hammerspoon,knu/hammerspoon,wsmith323/hammerspoon,dopcn/hammerspoon,heptal/hammerspoon,wvierber/hammerspoon,dopcn/hammerspoon,lowne/hammerspoon,cmsj/hammerspoon,heptal/hammerspoon,cmsj/hammerspoon,cmsj/hammerspoon,knl/hammerspoon,latenitefilms/hammerspoon,asmagill/hammerspoon,ocurr/hammerspoon,chrisjbray/hammerspoon,wvierber/hammerspoon,peterhajas/hammerspoon,Habbie/hammerspoon,dopcn/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,dopcn/hammerspoon,asmagill/hammerspoon,ocurr/hammerspoon,Hammerspoon/hammerspoon,wsmith323/hammerspoon,knl/hammerspoon,knu/hammerspoon,cmsj/hammerspoon,junkblocker/hammerspoon,lowne/hammerspoon,TimVonsee/hammerspoon,Hammerspoon/hammerspoon,nkgm/hammerspoon,junkblocker/hammerspoon,asmagill/hammerspoon,Habbie/hammerspoon,joehanchoi/hammerspoon,kkamdooong/hammerspoon,latenitefilms/hammerspoon,bradparks/hammerspoon,heptal/hammerspoon,joehanchoi/hammerspoon,zzamboni/hammerspoon,junkblocker/hammerspoon,Hammerspoon/hammerspoon,nkgm/hammerspoon,peterhajas/hammerspoon,chrisjbray/hammerspoon,emoses/hammerspoon,chrisjbray/hammerspoon,zzamboni/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon,zzamboni/hammerspoon,chrisjbray/hammerspoon,junkblocker/hammerspoon,wvierber/hammerspoon,cmsj/hammerspoon,chrisjbray/hammerspoon,kkamdooong/hammerspoon,emoses/hammerspoon,emoses/hammerspoon,wsmith323/hammerspoon,kkamdooong/hammerspoon,knu/hammerspoon,CommandPost/CommandPost-App,peterhajas/hammerspoon,peterhajas/hammerspoon,lowne/hammerspoon,junkblocker/hammerspoon,TimVonsee/hammerspoon,Stimim/hammerspoon,bradparks/hammerspoon,asmagill/hammerspoon,Stimim/hammerspoon,chrisjbray/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,knu/hammerspoon,heptal/hammerspoon,bradparks/hammerspoon,bradparks/hammerspoon,kkamdooong/hammerspoon,TimVonsee/hammerspoon,CommandPost/CommandPost-App,CommandPost/CommandPost-App,TimVonsee/hammerspoon,cmsj/hammerspoon,Stimim/hammerspoon,bradparks/hammerspoon,CommandPost/CommandPost-App,dopcn/hammerspoon,Stimim/hammerspoon,lowne/hammerspoon,nkgm/hammerspoon,Habbie/hammerspoon,joehanchoi/hammerspoon,heptal/hammerspoon,wsmith323/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,zzamboni/hammerspoon,asmagill/hammerspoon,CommandPost/CommandPost-App,emoses/hammerspoon
3f95d81c9d8ae9294f8fa4b94411c08ec881a01c
xmake/core/sandbox/modules/find_packages.lua
xmake/core/sandbox/modules/find_packages.lua
--!A cross-platform build utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file find_package.lua -- -- return module return function (...) -- get find_package local find_package = require("sandbox/modules/import/lib/detect/find_package").main -- get packages and options local pkgs = {...} local opts = pkgs[#pkgs] if type(opts) == "table" then pkgs = table.slice(pkgs, 1, #pkgs - 1) else opts = {} end -- find all packages local packages = {} for _, pkgname in ipairs(pkgs) do local pkg = find_package(pkgname, opts) if pkg then table.insert(packages, pkg) end end return packages end
--!A cross-platform build utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file find_package.lua -- -- return module return function (...) -- get find_package local find_package = require("sandbox/modules/import/core/sandbox/module").import("lib.detect.find_package", {anonymous = true}) -- get packages and options local pkgs = {...} local opts = pkgs[#pkgs] if type(opts) == "table" then pkgs = table.slice(pkgs, 1, #pkgs - 1) else opts = {} end -- find all packages local packages = {} for _, pkgname in ipairs(pkgs) do local pkg = find_package(pkgname, opts) if pkg then table.insert(packages, pkg) end end return packages end
fix find_packages
fix find_packages
Lua
apache-2.0
tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake
a867c1487ee7fed586a31429e033f79fbbcd208e
wrappers/Lua/example.lua
wrappers/Lua/example.lua
local cp = require "coolprop" print[[ Information Examples ==================== ]] print("Version", cp.version()) print("gitrevision", cp.gitrevision()) print("FluidsList", cp.FluidsList()) print("Debug Level", cp.get_debug_level()) print() print[[ Usage Examples ============== ]] print(cp.Props1SI("Water", "Phase")) print(cp.PropsSI("C", "P", 101325, "T", 300, "Water")) print(cp.PropsSI("d(Hmass)/d(T)|P", "P", 101325, "T", 300, "Water")) print(cp.PropsSI("D", "P", 101325, "T", 300, "Air.mix")) print(cp.PhaseSI("P", 101325, "Q", 0, "Water")) print(cp.get_global_param_string("predefined_mixtures")) print(cp.get_param_index("T")) print(cp.HAPropsSI('H','T',298.15,'P',101325,'R',0.5)) print(10, "Fahrenheits is", cp.F2K(10) , "Kelvins") print(cp.F2K(10), "Kelvins is", cp.K2F(cp.F2K(10)), "Fahrenheits") print() print[[ Error Examples ============== ]] print(cp.Props1SI("Error", "Phase")) print(cp.PropsSI("Error", "T", 298.15, "P", 101325, "Nitrogen")) print(cp.PhaseSI("Error", 101325, "Q", 0, "Water")) print(cp.get_parameter_information_string("Error")) -- What are the correct inputs for this? print(cp.saturation_ancillary("Water", "C", 10, "Error", 300)) -- What are the correct inputs for this? print(cp.HAPropsSI('Error','T',298.15,'P',101325,'R',0.5)) print(cp.get_param_index("Error")) print()
local cp = require "coolprop" print[[ Information Examples ==================== ]] print("Version", cp.version()) print("gitrevision", cp.gitrevision()) print("FluidsList", cp.FluidsList()) print("Debug Level", cp.get_debug_level()) print() print[[ Usage Examples ============== ]] print(cp.Props1SI("Water", "Phase")) print(cp.PropsSI("C", "P", 101325, "T", 300, "Water")) print(cp.PropsSI("d(Hmass)/d(T)|P", "P", 101325, "T", 300, "Water")) print(cp.PropsSI("D", "P", 101325, "T", 300, "Air.mix")) print(cp.PhaseSI("P", 101325, "Q", 0, "Water")) print(cp.get_global_param_string("predefined_mixtures")) print(cp.get_fluid_param_string("Water", "aliases")) print(cp.get_param_index("T")) print(cp.HAPropsSI('H','T',298.15,'P',101325,'R',0.5)) print(10, "Fahrenheits is", cp.F2K(10) , "Kelvins") print(cp.F2K(10), "Kelvins is", cp.K2F(cp.F2K(10)), "Fahrenheits") print() print[[ Error Examples ============== ]] print(cp.Props1SI("Error", "Phase")) print(cp.PropsSI("Error", "T", 298.15, "P", 101325, "Nitrogen")) print(cp.PhaseSI("Error", 101325, "Q", 0, "Water")) print(cp.get_parameter_information_string("Error")) -- What are the correct inputs for this? print(cp.saturation_ancillary("Water", "C", 10, "Error", 300)) -- What are the correct inputs for this? print(cp.HAPropsSI('Error','T',298.15,'P',101325,'R',0.5)) print(cp.get_param_index("Error")) print(cp.get_fluid_param_string("Water", "wrong")) print()
Add test to example.lua demonstrating fix.
Add test to example.lua demonstrating fix.
Lua
mit
henningjp/CoolProp,JonWel/CoolProp,henningjp/CoolProp,henningjp/CoolProp,henningjp/CoolProp,henningjp/CoolProp,CoolProp/CoolProp,DANA-Laboratory/CoolProp,DANA-Laboratory/CoolProp,DANA-Laboratory/CoolProp,CoolProp/CoolProp,henningjp/CoolProp,CoolProp/CoolProp,DANA-Laboratory/CoolProp,CoolProp/CoolProp,CoolProp/CoolProp,dcprojects/CoolProp,DANA-Laboratory/CoolProp,dcprojects/CoolProp,JonWel/CoolProp,henningjp/CoolProp,CoolProp/CoolProp,dcprojects/CoolProp,JonWel/CoolProp,DANA-Laboratory/CoolProp,JonWel/CoolProp,dcprojects/CoolProp,CoolProp/CoolProp,JonWel/CoolProp,dcprojects/CoolProp,JonWel/CoolProp,CoolProp/CoolProp,JonWel/CoolProp,henningjp/CoolProp,dcprojects/CoolProp,DANA-Laboratory/CoolProp,dcprojects/CoolProp
b05bcfaba7ad606fba3e424609050cf6e3ca6a95
mods/mobs/kitten.lua
mods/mobs/kitten.lua
local kitten_nodes = { "wool:black", "wool:blue", "wool:brown", "wool:cyan", "wool:dark_green", "wool:dark_grey", "wool:green", "wool:grey", "wool:magenta", "wool:orange", "wool:pink", "wool:red", "wool:violet", "wool:white", "wool:yellow", "carpet:black", "carpet:blue", "carpet:brown", "carpet:cyan", "carpet:dark_green", "carpet:dark_grey", "carpet:green", "carpet:grey", "carpet:magenta", "carpet:orange", "carpet:pink", "carpet:red", "carpet:violet", "carpet:white", "carpet:yellow", "deco:furnace_active", "beds:bed_bottom", "beds:bed_top", "beds:bed_top_red", "beds:bed_top_orange", "beds:bed_top_yellow", "beds:bed_top_green", "beds:bed_top_blue", "beds:bed_top_violet", "beds:bed_top_black", "beds:bed_top_grey", "beds:bed_top_white", "beds:bed_bottom_red", "beds:bed_bottom_orange", "beds:bed_bottom_yellow", "beds:bed_bottom_green", "beds:bed_bottom_blue", "beds:bed_bottom_violet", "beds:bed_bottom_black", "beds:bed_bottom_grey", "beds:bed_bottom_white", } local function register_kitten(image, name) mobs:register_spawn("mobs:kitten_"..name, {"default:dirt_with_grass"}, 15, 0, 9000, 10, 31000) mobs:register_mob("mobs:kitten_"..name, { type = "animal", hp_min = 5, hp_max = 10, collisionbox = {-0.3, -0.3, -0.3, 0.3, 0.1, 0.3}, visual = "mesh", visual_size = {x=0.5, y=0.5}, mesh = "mobs_kitten.b3d", textures = {image}, makes_footstep_sound = false, view_range = 16, walk_velocity = 0.6, drops = { {name = "maptools:copper_coin", chance = 10, min = 1, max = 1,}, }, water_damage = 1, lava_damage = 5, on_rightclick = nil, armor = 200, sounds = { random = "mobs_kitten", }, animation = { stand_start = 97, stand_end = 192, walk_start = 0, walk_end = 96, speed_normal = 42, }, follow = "fishing:fish_raw", view_range = 8, -- jump = true, -- step = 0.5, passive = true, blood_texture = "mobs_blood.png", on_rightclick = function(self, clicker) local item = clicker:get_wielded_item() if item:get_name() == "fishing:fish_raw" then if not minetest.setting_getbool("creative_mode") then item:take_item() clicker:set_wielded_item(item) end self.food = (self.food or 0) + 1 if self.food >= 4 then self.food = 0 self.tamed = true minetest.sound_play("mobs_kitten", {object = self.object,gain = 1.0,max_hear_distance = 32,loop = false,}) end return end end }) register_kitten("mobs_kitten_striped.png", "striped") register_kitten("mobs_kitten_splotchy.png", "splotchy") register_kitten("mobs_kitten_ginger.png", "ginger") register_kitten("mobs_kitten_sandy.png", "sandy") end
local kitten_nodes = { "wool:black", "wool:blue", "wool:brown", "wool:cyan", "wool:dark_green", "wool:dark_grey", "wool:green", "wool:grey", "wool:magenta", "wool:orange", "wool:pink", "wool:red", "wool:violet", "wool:white", "wool:yellow", "carpet:black", "carpet:blue", "carpet:brown", "carpet:cyan", "carpet:dark_green", "carpet:dark_grey", "carpet:green", "carpet:grey", "carpet:magenta", "carpet:orange", "carpet:pink", "carpet:red", "carpet:violet", "carpet:white", "carpet:yellow", "deco:furnace_active", "beds:bed_bottom", "beds:bed_top", "beds:bed_top_red", "beds:bed_top_orange", "beds:bed_top_yellow", "beds:bed_top_green", "beds:bed_top_blue", "beds:bed_top_violet", "beds:bed_top_black", "beds:bed_top_grey", "beds:bed_top_white", "beds:bed_bottom_red", "beds:bed_bottom_orange", "beds:bed_bottom_yellow", "beds:bed_bottom_green", "beds:bed_bottom_blue", "beds:bed_bottom_violet", "beds:bed_bottom_black", "beds:bed_bottom_grey", "beds:bed_bottom_white", } mobs:register_spawn("mobs:kitten", {"default:dirt_with_grass"}, 15, 0, 2750, 10, 31000) mobs:register_mob("mobs:kitten", { type = "animal", hp_min = 5, hp_max = 10, collisionbox = {-0.3, -0.3, -0.3, 0.3, 0.1, 0.3}, visual = "mesh", visual_size = {x=0.5, y=0.5}, mesh = "mobs_kitten.b3d", available_textures = { total = 4, texture_1 = {"mobs_kitten_striped.png"}, texture_2 = {"mobs_kitten_splotchy.png"}, texture_3 = {"mobs_kitten_ginger.png"}, texture_4 = {"mobs_kitten_sandy.png"}, }, makes_footstep_sound = false, view_range = 16, walk_velocity = 0.6, drops = { {name = "maptools:copper_coin", chance = 10, min = 1, max = 1,}, }, water_damage = 1, lava_damage = 5, on_rightclick = nil, armor = 200, sounds = { random = "mobs_kitten", }, animation = { stand_start = 97, stand_end = 192, walk_start = 0, walk_end = 96, speed_normal = 42, }, follow = "fishing:fish_raw", view_range = 8, -- jump = true, -- step = 0.5, passive = true, blood_texture = "mobs_blood.png", on_rightclick = function(self, clicker) local item = clicker:get_wielded_item() if item:get_name() == "fishing:fish_raw" then if not minetest.setting_getbool("creative_mode") then item:take_item() clicker:set_wielded_item(item) end self.food = (self.food or 0) + 1 if self.food >= 4 then self.food = 0 self.tamed = true minetest.sound_play("mobs_kitten", {object = self.object,gain = 1.0,max_hear_distance = 32,loop = false,}) end return end end })
Fixed some problems about kittens
Fixed some problems about kittens
Lua
unlicense
MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun,sys4-fr/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,paly2/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/server-minetestforfun,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,crabman77/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Coethium/server-minetestforfun,sys4-fr/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server
e75ed26182d3ef47806715e47efda09fd5643056
kong/plugins/azure-functions/handler.lua
kong/plugins/azure-functions/handler.lua
local BasePlugin = require "kong.plugins.base_plugin" local constants = require "kong.constants" local meta = require "kong.meta" local http = require "resty.http" local pairs = pairs local server_header = meta._SERVER_TOKENS local conf_cache = setmetatable({}, { __mode = "k" }) local function send(status, content, headers) if kong.configuration.enabled_headers[constants.HEADERS.VIA] then headers = kong.table.merge(headers) -- create a copy of headers headers[constants.HEADERS.VIA] = server_header end return kong.response.exit(status, content, headers) end local azure = BasePlugin:extend() azure.PRIORITY = 749 azure.VERSION = "0.1.1" function azure:new() azure.super.new(self, "azure-functions") end function azure:access(config) azure.super.access(self) -- prepare and store updated config in cache local conf = conf_cache[config] if not conf then conf = {} for k,v in pairs(config) do conf[k] = v end conf.host = config.appname .. "." .. config.hostdomain conf.port = config.https and 443 or 80 local f = (config.functionname or ""):match("^/*(.-)/*$") -- drop pre/postfix slashes local p = (config.routeprefix or ""):match("^/*(.-)/*$") -- drop pre/postfix slashes if p ~= "" then p = "/" .. p end conf.path = p .. "/" .. f conf_cache[config] = conf end config = conf local client = http.new() local request_method = get_method() read_body() local request_body = get_body_data() local request_headers = get_headers() local request_args = get_uri_args() client:set_timeout(config.timeout) local ok, err = client:connect(config.host, config.port) if not ok then kong.log.err("could not connect to Azure service: ", err) return kong.response.exit(500, { message = "An unexpected error ocurred" }) end if config.https then local ok, err = client:ssl_handshake(false, config.host, config.https_verify) if not ok then kong.log.err("could not perform SSL handshake : ", err) return kong.response.exit(500, { message = "An unexpected error ocurred" }) end end local upstream_uri = var.upstream_uri local path = conf.path local end1 = path:sub(-1, -1) local start2 = upstream_uri:sub(1, 1) if end1 == "/" then if start2 == "/" then path = path .. upstream_uri:sub(2,-1) else path = path .. upstream_uri end else if start2 == "/" then path = path .. upstream_uri else if upstream_uri ~= "" then path = path .. "/" .. upstream_uri end end end local res res, err = client:request { method = request_method, path = path, body = request_body, query = request_args, headers = { ["Content-Length"] = #(request_body or ""), ["Content-Type"] = request_headers["Content-Type"], ["x-functions-key"] = config.apikey, ["x-functions-clientid"] = config.clientid, } } if not res then kong.log.err(err) return kong.response.exit(500, { message = "An unexpected error occurred" }) end local response_headers = res.headers local response_status = res.status local response_content = res:read_body() ok, err = client:set_keepalive(config.keepalive) if not ok then kong.log.err("could not keepalive connection: ", err) end return send(response_status, response_content, response_headers) end return azure
local BasePlugin = require "kong.plugins.base_plugin" local constants = require "kong.constants" local meta = require "kong.meta" local http = require "resty.http" local pairs = pairs local server_header = meta._SERVER_TOKENS local conf_cache = setmetatable({}, { __mode = "k" }) local function send(status, content, headers) if kong.configuration.enabled_headers[constants.HEADERS.VIA] then headers = kong.table.merge(headers) -- create a copy of headers headers[constants.HEADERS.VIA] = server_header end return kong.response.exit(status, content, headers) end local azure = BasePlugin:extend() azure.PRIORITY = 749 azure.VERSION = "0.1.1" function azure:new() azure.super.new(self, "azure-functions") end function azure:access(config) azure.super.access(self) -- prepare and store updated config in cache local conf = conf_cache[config] if not conf then conf = {} for k,v in pairs(config) do conf[k] = v end conf.host = config.appname .. "." .. config.hostdomain conf.port = config.https and 443 or 80 local f = (config.functionname or ""):match("^/*(.-)/*$") -- drop pre/postfix slashes local p = (config.routeprefix or ""):match("^/*(.-)/*$") -- drop pre/postfix slashes if p ~= "" then p = "/" .. p end conf.path = p .. "/" .. f conf_cache[config] = conf end config = conf local client = http.new() local request_method = kong.request.get_method() local request_body = kong.request.get_raw_body() local request_headers = kong.request.get_headers() local request_args = kong.request.get_query() client:set_timeout(config.timeout) local ok, err = client:connect(config.host, config.port) if not ok then kong.log.err("could not connect to Azure service: ", err) return kong.response.exit(500, { message = "An unexpected error ocurred" }) end if config.https then local ok2, err2 = client:ssl_handshake(false, config.host, config.https_verify) if not ok2 then kong.log.err("could not perform SSL handshake : ", err2) return kong.response.exit(500, { message = "An unexpected error ocurred" }) end end local upstream_uri = ngx.var.upstream_uri local path = conf.path local end1 = path:sub(-1, -1) local start2 = upstream_uri:sub(1, 1) if end1 == "/" then if start2 == "/" then path = path .. upstream_uri:sub(2,-1) else path = path .. upstream_uri end else if start2 == "/" then path = path .. upstream_uri else if upstream_uri ~= "" then path = path .. "/" .. upstream_uri end end end local res res, err = client:request { method = request_method, path = path, body = request_body, query = request_args, headers = { ["Content-Length"] = #(request_body or ""), ["Content-Type"] = request_headers["Content-Type"], ["x-functions-key"] = config.apikey, ["x-functions-clientid"] = config.clientid, } } if not res then kong.log.err(err) return kong.response.exit(500, { message = "An unexpected error occurred" }) end local response_headers = res.headers local response_status = res.status local response_content = res:read_body() ok, err = client:set_keepalive(config.keepalive) if not ok then kong.log.err("could not keepalive connection: ", err) end return send(response_status, response_content, response_headers) end return azure
hotfix(azure-functions) replace several undefined vars with pdk/ngx methods
hotfix(azure-functions) replace several undefined vars with pdk/ngx methods From #6
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
d7c21eb82892ffddcd2f7dafe233748fc0ba1cab
core/pagebuilder.lua
core/pagebuilder.lua
local awful_bad = 1073741823 local inf_bad = 10000 local eject_penalty = -inf_bad local deplorable = 100000 SILE.pagebuilder = { collateVboxes = function(vboxlist) local i local output = SILE.nodefactory.newVbox({nodes = {} }) output:append(vboxlist) return output end, badness = function (t,s) local bad = 100 * (t/s)^3 bad = math.floor(bad) -- TeX uses integer math for this stuff, so for compatibility... if bad > inf_bad then return inf_bad else return bad end end, findBestBreak = function(options) local vboxlist = SU.required(options, "vboxlist", "in findBestBreak") local target = SU.required(options, "target", "in findBestBreak") local restart = options.restart or false local force = options.force or false local i = 0 local totalHeight = SILE.length.new() local bestBreak = nil local started = false if restart and restart.target == target then totalHeight = restart.totalHeight i = restart.i started = restart.started end local leastC = inf_bad SU.debug("pagebuilder", "Page builder for frame "..SILE.typesetter.frame.id.." called with "..#vboxlist.." nodes, "..target) if SU.debugging("vboxes") then for j = 1,#vboxlist do SU.debug("vboxes", (j==i and " -> " or " ")..j..": "..vboxlist[j]) end end while i < #vboxlist do i = i + 1 local vbox = vboxlist[i] SU.debug("pagebuilder", "Dealing with VBox " .. vbox) while not started and vbox:isVglue() do table.remove(vboxlist, i) if i >= #vboxlist then break end vbox = vboxlist[i] end if (vbox:isVbox()) then if not started then started = true end totalHeight = totalHeight + vbox.height + vbox.depth; elseif vbox:isVglue() then totalHeight = totalHeight + vbox.height elseif vbox.type == "insertionVbox" then target = SILE.insertions.processInsertion(vboxlist, i, totalHeight, target) vbox = vboxlist[i] end local left = target - totalHeight.length SU.debug("pagebuilder", "I have " .. tostring(left) .. "pts left"); -- if (left < -20) then SU.error("\nCatastrophic page breaking failure!"); end local pi = 0 if vbox:isPenalty() then pi = vbox.penalty -- print("PI "..pi) end if vbox:isPenalty() and vbox.penalty < inf_bad or (vbox:isVglue() and i > 1 and not vboxlist[i-1]:isDiscardable()) then local badness SU.debug("pagebuilder", "totalHeight " .. totalHeight .. " with target " .. target); if totalHeight.length < target then -- TeX #1039 -- Account for infinite stretch? badness = SILE.pagebuilder.badness(left, totalHeight.stretch) -- print("Height == "..totalHeight.length, "target=="..target, "stretch=="..totalHeight.stretch) elseif left < totalHeight.shrink then badness = awful_bad else badness = SILE.pagebuilder.badness(-left, totalHeight.shrink) end local c if badness < awful_bad then if pi <= eject_penalty then c = pi elseif badness < inf_bad then c = badness + pi -- plus insert else c = deplorable end else c = badness end if c < leastC then leastC = c bestBreak = i else restart = { totalHeight = totalHeight, i = i, started = started, target = target} end -- print("Badness "..badness .." c = "..c) SU.debug("pagebuilder", "Badness: "..c); if c == awful_bad or pi <= eject_penalty then SU.debug("pagebuilder", "outputting"); local onepage = {} if not bestBreak then bestBreak = i end for j=1,bestBreak do onepage[j] = table.remove(vboxlist,1) end while(#onepage > 1 and onepage[#onepage]:isVDiscardable()) do onepage[#onepage] = nil end return onepage, pi end end end SU.debug("pagebuilder", "No page break here") if force and bestBreak then local onepage = {} for j=1,bestBreak do onepage[j] = table.remove(vboxlist,1) end return onepage, pi end return false, restart end, }
local awful_bad = 1073741823 local inf_bad = 10000 local eject_penalty = -inf_bad local deplorable = 100000 SILE.pagebuilder = { collateVboxes = function(vboxlist) local i local output = SILE.nodefactory.newVbox({nodes = {} }) output:append(vboxlist) return output end, badness = function (t,s) local bad = 100 * (t/s)^3 bad = math.floor(bad) -- TeX uses integer math for this stuff, so for compatibility... if bad > inf_bad then return inf_bad else return bad end end, findBestBreak = function(options) local vboxlist = SU.required(options, "vboxlist", "in findBestBreak") local target = SU.required(options, "target", "in findBestBreak") local restart = options.restart or false local force = options.force or false local i = 0 local totalHeight = SILE.length.new() local bestBreak = nil local started = false if restart and restart.target == target then totalHeight = restart.totalHeight i = restart.i started = restart.started end local leastC = inf_bad SU.debug("pagebuilder", "Page builder for frame "..SILE.typesetter.frame.id.." called with "..#vboxlist.." nodes, "..target) if SU.debugging("vboxes") then for j = 1,#vboxlist do SU.debug("vboxes", (j==i and " -> " or " ")..j..": "..vboxlist[j]) end end while not started and i < #vboxlist do i = i + 1 if not vboxlist[i]:isVglue() then started = true i = i - 1 break end end while i < #vboxlist do i = i + 1 local vbox = vboxlist[i] SU.debug("pagebuilder", "Dealing with VBox " .. vbox) if (vbox:isVbox()) then totalHeight = totalHeight + vbox.height + vbox.depth; elseif vbox:isVglue() then totalHeight = totalHeight + vbox.height elseif vbox.type == "insertionVbox" then target = SILE.insertions.processInsertion(vboxlist, i, totalHeight, target) vbox = vboxlist[i] end local left = target - totalHeight.length SU.debug("pagebuilder", "I have " .. tostring(left) .. "pts left"); -- if (left < -20) then SU.error("\nCatastrophic page breaking failure!"); end local pi = 0 if vbox:isPenalty() then pi = vbox.penalty -- print("PI "..pi) end if vbox:isPenalty() and vbox.penalty < inf_bad or (vbox:isVglue() and i > 1 and not vboxlist[i-1]:isDiscardable()) then local badness SU.debug("pagebuilder", "totalHeight " .. totalHeight .. " with target " .. target); if totalHeight.length < target then -- TeX #1039 -- Account for infinite stretch? badness = SILE.pagebuilder.badness(left, totalHeight.stretch) -- print("Height == "..totalHeight.length, "target=="..target, "stretch=="..totalHeight.stretch) elseif left < totalHeight.shrink then badness = awful_bad else badness = SILE.pagebuilder.badness(-left, totalHeight.shrink) end local c if badness < awful_bad then if pi <= eject_penalty then c = pi elseif badness < inf_bad then c = badness + pi -- plus insert else c = deplorable end else c = badness end if c < leastC then leastC = c bestBreak = i else restart = { totalHeight = totalHeight, i = i, started = started, target = target} end -- print("Badness "..badness .." c = "..c) SU.debug("pagebuilder", "Badness: "..c); if c == awful_bad or pi <= eject_penalty then SU.debug("pagebuilder", "outputting"); local onepage = {} if not bestBreak then bestBreak = i end for j=1,bestBreak do onepage[j] = table.remove(vboxlist,1) end while(#onepage > 1 and onepage[#onepage]:isVDiscardable()) do onepage[#onepage] = nil end return onepage, pi end end end SU.debug("pagebuilder", "No page break here") if force and bestBreak then local onepage = {} for j=1,bestBreak do onepage[j] = table.remove(vboxlist,1) end return onepage, pi end return false, restart end, }
Fix to pagebuilder fix. (masters regression test was failing. How about now?)
Fix to pagebuilder fix. (masters regression test was failing. How about now?)
Lua
mit
neofob/sile,simoncozens/sile,alerque/sile,simoncozens/sile,alerque/sile,neofob/sile,simoncozens/sile,simoncozens/sile,neofob/sile,alerque/sile,alerque/sile,neofob/sile
930a1250e0e1bf7fc1a824004e99d86ce0ab252f
lua/starfall/libs_sh/timer.lua
lua/starfall/libs_sh/timer.lua
------------------------------------------------------------------------------- -- Time library ------------------------------------------------------------------------------- local timer = timer --- Deals with time and timers. -- @shared local timer_library, _ = SF.Libraries.Register("timer") -- ------------------------- Time ------------------------- -- --- Same as GLua's CurTime() function timer_library.curtime() return CurTime() end --- Same as GLua's RealTime() function timer_library.realtime() return RealTime() end --- Same as GLua's SysTime() function timer_library.systime() return SysTime() end --- Returns time between frames on client and ticks on server. Same thing as G.FrameTime in GLua function timer_library.frametime() return FrameTime() end -- ------------------------- Timers ------------------------- -- local function mangle_timer_name(instance, name) return string.format("sftimer_%s_%s",tostring(instance),name) end --- Creates (and starts) a timer -- @param name The timer name -- @param delay The time, in seconds, to set the timer to. -- @param reps The repititions of the tiemr. 0 = infinte, nil = 1 -- @param func The function to call when the tiemr is fired function timer_library.create(name, delay, reps, func) SF.CheckType(name,"string") SF.CheckType(delay,"number") reps = SF.CheckType(reps,"number",0,1) SF.CheckType(func,"function") local instance = SF.instance local timername = mangle_timer_name(instance,name) local function timercb() local ok, tbl = instance:runFunction(func) if not ok and instance.runOnError then instance:runOnError( tbl[1] ) timer.Remove( timername ) end end timer.Create(timername, delay, reps, timercb ) instance.data.timers[name] = true end --- Removes a timer -- @param name The timer name function timer_library.remove(name) SF.CheckType(name,"string") local instance = SF.instance timer.Stop(mangle_timer_name(instance,name)) instance.data.timers[name] = nil end --- Stops a timer -- @param name The timer name function timer_library.stop(name) SF.CheckType(name,"string") timer.Stop(mangle_timer_name(instance,name)) end --- Starts a timer -- @param name The timer name function timer_library.start(name) SF.CheckType(name,"string") timer.Start(mangle_timer_name(instance,name)) end --- Adjusts a timer -- @param name The timer name function timer_library.adjust(name) SF.CheckType(name,"string") timer.Adjust(mangle_timer_name(instance,name)) end --- Pauses a timer -- @param name The timer name function timer_library.pause(name) SF.CheckType(name,"string") timer.Pause(mangle_timer_name(instance,name)) end --- Unpauses a timer -- @param name The timer name function timer_library.unpause(name) SF.CheckType(name,"string") timer.UnPause(mangle_timer_name(instance,name)) end --- Creates a simple timer, has no name, can't be stopped, paused, or destroyed. -- @param delay the time, in second, to set the timer to -- @param func the function to call when the timer is fired function timer_library.simple(delay, func) SF.CheckType( delay, "number" ) SF.CheckType( func, "function" ) local instance = SF.instance timer.Simple(delay, function() if not instance.error then instance:runFunction(func) elseif instance.runOnError then instance:runOnError( "timer error" ) end end) end SF.Libraries.AddHook("initialize",function(instance) instance.data.timers = {} end) SF.Libraries.AddHook("deinitialize",function(instance) if instance.data.timers ~= nil then for name,_ in pairs(instance.data.timers) do local realname = mangle_timer_name(instance,name) timer.Remove(realname) end end instance.data.timers = nil end)
------------------------------------------------------------------------------- -- Time library ------------------------------------------------------------------------------- local timer = timer --- Deals with time and timers. -- @shared local timer_library, _ = SF.Libraries.Register("timer") -- ------------------------- Time ------------------------- -- --- Same as GLua's CurTime() function timer_library.curtime() return CurTime() end --- Same as GLua's RealTime() function timer_library.realtime() return RealTime() end --- Same as GLua's SysTime() function timer_library.systime() return SysTime() end --- Returns time between frames on client and ticks on server. Same thing as G.FrameTime in GLua function timer_library.frametime() return FrameTime() end -- ------------------------- Timers ------------------------- -- local function mangle_timer_name(instance, name) return string.format("sftimer_%s_%s",tostring(instance),name) end --- Creates (and starts) a timer -- @param name The timer name -- @param delay The time, in seconds, to set the timer to. -- @param reps The repititions of the tiemr. 0 = infinte, nil = 1 -- @param func The function to call when the tiemr is fired function timer_library.create(name, delay, reps, func) SF.CheckType(name,"string") SF.CheckType(delay,"number") reps = SF.CheckType(reps,"number",0,1) SF.CheckType(func,"function") local instance = SF.instance local timername = mangle_timer_name(instance,name) local function timercb() local ok, tbl = instance:runFunction(func) if not ok and instance.runOnError then instance:runOnError( tbl[1] ) timer.Remove( timername ) end end timer.Create(timername, delay, reps, timercb ) instance.data.timers[name] = true end --- Removes a timer -- @param name The timer name function timer_library.remove(name) SF.CheckType(name,"string") local instance = SF.instance timer.Stop(mangle_timer_name(instance,name)) instance.data.timers[name] = nil end --- Stops a timer -- @param name The timer name function timer_library.stop(name) SF.CheckType(name,"string") timer.Stop(mangle_timer_name(instance,name)) end --- Starts a timer -- @param name The timer name function timer_library.start(name) SF.CheckType(name,"string") timer.Start(mangle_timer_name(instance,name)) end --- Adjusts a timer -- @param name The timer name function timer_library.adjust(name) SF.CheckType(name,"string") timer.Adjust(mangle_timer_name(instance,name)) end --- Pauses a timer -- @param name The timer name function timer_library.pause(name) SF.CheckType(name,"string") timer.Pause(mangle_timer_name(instance,name)) end --- Unpauses a timer -- @param name The timer name function timer_library.unpause(name) SF.CheckType(name,"string") timer.UnPause(mangle_timer_name(instance,name)) end --- Creates a simple timer, has no name, can't be stopped, paused, or destroyed. -- @param delay the time, in second, to set the timer to -- @param func the function to call when the timer is fired function timer_library.simple(delay, func) SF.CheckType( delay, "number" ) SF.CheckType( func, "function" ) local instance = SF.instance timer.Simple(delay, function() if instance.data.entity ~= NULL then if not instance.error then instance:runFunction(func) elseif instance.runOnError then instance:runOnError( "timer error" ) end end end) end SF.Libraries.AddHook("initialize",function(instance) instance.data.timers = {} end) SF.Libraries.AddHook("deinitialize",function(instance) if instance.data.timers ~= nil then for name,_ in pairs(instance.data.timers) do local realname = mangle_timer_name(instance,name) timer.Remove(realname) end end instance.data.timers = nil end)
[Fix] in timer library
[Fix] in timer library timer.simple was throwing an error if the entity got removed while the timer was running Fixes #53
Lua
bsd-3-clause
Ingenious-Gaming/Starfall,INPStarfall/Starfall,Jazzelhawk/Starfall,Jazzelhawk/Starfall,Xandaros/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall,INPStarfall/Starfall
e73a856fa2c820bb07a4c9941f94db408eed7e7e
src/lua/rule.lua
src/lua/rule.lua
local __dissectors = {} local __rule_groups = {} function haka.dissector(d) if d.name == nil or d.dissect == nil then if haka.app.currentThread() == 0 then haka.log.error("core", "registering invalid dissector: '%s'", d.name) end else if not __dissectors[d.name] then __dissectors[d.name] = d if haka.app.currentThread() == 0 then haka.log.info("core", "registering new dissector: '%s'", d.name) end end end end function haka.rule_group(group) group.rule = function (g, r) for _, h in pairs(r.hooks) do if not g.__hooks[h] then g.__hooks[h] = {} end table.insert(g.__hooks[h], r) end end group.__hooks = {} __rule_groups[group.name] = group return group end local __default_rule_group = haka.rule_group { name = "default" } function haka.rule(r) return __default_rule_group:rule(r) end local function _rule_group_eval(hook, group, pkt) local rules = group.__hooks[hook] if rules then if group.init then group:init(pkt) end for _, r in pairs(rules) do local ret = r.eval(nil, pkt) if group.continue then if not group:continue(ret) then return true end end if not pkt:valid() then return false end end if group.fini then group:fini(pkt) end end return true end function haka.rule_summary() local total = 0 local rule_count = {} for _, group in pairs(__rule_groups) do for hook, rules in pairs(group.__hooks) do if not rule_count[hook] then rule_count[hook] = 0 end rule_count[hook] = rule_count[hook] + #rules total = total + #rules end end if total == 0 then haka.log.warning("core", "no registered rule\n") else for hook, count in pairs(rule_count) do haka.log.info("core", "%d rule(s) on hook '%s'", count, hook) end haka.log.info("core", "%d rule(s) registered\n", total) end end local function eval_rules(hook, pkt) for _, group in pairs(__rule_groups) do if not _rule_group_eval(hook, group, pkt) then return false end end return true end local function filter_down(pkt) if pkt.dissector then eval_rules(pkt.dissector .. '-down', pkt) end while true do local pktdown = pkt:forge() if pktdown then filter_down(pktdown) else break end end end local function get_dissector(name) return __dissectors[name] end function haka.rule_hook(name, pkt) eval_rules(name, pkt) return not pkt:valid() end function haka.filter(pkt) local dissect = get_dissector(pkt.nextDissector) while dissect do local nextpkt = dissect.dissect(pkt) if not nextpkt then break end if not nextpkt:valid() then break end pkt = nextpkt eval_rules(dissect.name .. '-up', pkt) dissect = nil if not pkt:valid() then break end if pkt.nextDissector then dissect = get_dissector(pkt.nextDissector) if not dissect then haka.log.error("core", "cannot create dissector '%s': not registered", pkt.nextDissector) pkt:drop() end end end filter_down(pkt) end
local __dissectors = {} local __rule_groups = {} function haka.dissector(d) if d.name == nil or d.dissect == nil then if haka.app.currentThread() == 0 then haka.log.error("core", "registering invalid dissector: '%s'", d.name) end else if not __dissectors[d.name] then __dissectors[d.name] = d if haka.app.currentThread() == 0 then haka.log.info("core", "registering new dissector: '%s'", d.name) end end end end function haka.rule_group(group) group.rule = function (g, r) for _, h in pairs(r.hooks) do if not g.__hooks[h] then g.__hooks[h] = {} end table.insert(g.__hooks[h], r) end end group.__hooks = {} __rule_groups[group.name] = group return group end local __default_rule_group = haka.rule_group { name = "default" } function haka.rule(r) return __default_rule_group:rule(r) end local function _rule_group_eval(hook, group, pkt) local rules = group.__hooks[hook] if rules then if group.init then group:init(pkt) end for _, r in pairs(rules) do local ret = r.eval(nil, pkt) if group.continue then if not group:continue(ret) then return true end end if not pkt:valid() then return false end end if group.fini then group:fini(pkt) end end return true end function haka.rule_summary() local total = 0 local rule_count = {} for _, group in pairs(__rule_groups) do for hook, rules in pairs(group.__hooks) do if not rule_count[hook] then rule_count[hook] = 0 end rule_count[hook] = rule_count[hook] + #rules total = total + #rules end end if total == 0 then haka.log.warning("core", "no registered rule\n") else for hook, count in pairs(rule_count) do haka.log.info("core", "%d rule(s) on hook '%s'", count, hook) end haka.log.info("core", "%d rule(s) registered\n", total) end end local function eval_rules(hook, pkt) for _, group in pairs(__rule_groups) do if not _rule_group_eval(hook, group, pkt) then return false end end return true end local function filter_down(pkt) if pkt.dissector then eval_rules(pkt.dissector .. '-down', pkt) end while true do local pktdown = pkt:forge() if pktdown then filter_down(pktdown) else break end end end local function get_dissector(name) return __dissectors[name] end function haka.rule_hook(name, pkt) eval_rules(name, pkt) return not pkt:valid() end function haka.filter(pkt) local guard = {pkt} -- TODO: to be removed (need to avoid Lua to destroy some object still used) local dissect = get_dissector(pkt.nextDissector) while dissect do local nextpkt = dissect.dissect(pkt) if not nextpkt then break end if not nextpkt:valid() then break end pkt = nextpkt table.insert(guard, pkt) eval_rules(dissect.name .. '-up', pkt) dissect = nil if not pkt:valid() then break end if pkt.nextDissector then dissect = get_dissector(pkt.nextDissector) if not dissect then haka.log.error("core", "cannot create dissector '%s': not registered", pkt.nextDissector) pkt:drop() end end end filter_down(pkt) end
Fix memory corruption
Fix memory corruption Quick fix that should be improved in the future.
Lua
mpl-2.0
LubyRuffy/haka,lcheylus/haka,Wingless-Archangel/haka,lcheylus/haka,lcheylus/haka,nabilbendafi/haka,Wingless-Archangel/haka,LubyRuffy/haka,haka-security/haka,nabilbendafi/haka,haka-security/haka,nabilbendafi/haka,haka-security/haka
63295d72ca08236c055486e8b9a14a413ee82869
src/program/snabbnfv/traffic/traffic.lua
src/program/snabbnfv/traffic/traffic.lua
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local lib = require("core.lib") local nfvconfig = require("program.snabbnfv.nfvconfig") local usage = require("program.snabbnfv.traffic.README_inc") local ffi = require("ffi") local C = ffi.C local timer = require("core.timer") local pci = require("lib.hardware.pci") local ingress_drop_monitor = require("lib.timers.ingress_drop_monitor") local counter = require("core.counter") local long_opts = { benchmark = "B", help = "h", ["link-report-interval"] = "k", ["load-report-interval"] = "l", ["debug-report-interval"] = "D", ["busy"] = "b", ["long-help"] = "H" } function run (args) local opt = {} local benchpackets local linkreportinterval = 0 local loadreportinterval = 1 local debugreportinterval = 0 function opt.B (arg) benchpackets = tonumber(arg) end function opt.h (arg) print(short_usage()) main.exit(1) end function opt.H (arg) print(long_usage()) main.exit(1) end function opt.k (arg) linkreportinterval = tonumber(arg) end function opt.l (arg) loadreportinterval = tonumber(arg) end function opt.D (arg) debugreportinterval = tonumber(arg) end function opt.b (arg) engine.busywait = true end args = lib.dogetopt(args, opt, "hHB:k:l:D:b", long_opts) if #args == 3 then local pciaddr, confpath, sockpath = unpack(args) if pciaddr == "soft" then pciaddr = nil end if pciaddr then local ok, info = pcall(pci.device_info, pciaddr) if not ok then print("Error: device not found " .. pciaddr) os.exit(1) end if not info.driver then print("Error: no driver for device " .. pciaddr) os.exit(1) end end if loadreportinterval > 0 then local t = timer.new("nfvloadreport", engine.report_load, loadreportinterval*1e9, 'repeating') timer.activate(t) end if linkreportinterval > 0 then local t = timer.new("nfvlinkreport", engine.report_links, linkreportinterval*1e9, 'repeating') timer.activate(t) end if debugreportinterval > 0 then local t = timer.new("nfvdebugreport", engine.report_apps, debugreportinterval*1e9, 'repeating') timer.activate(t) end if benchpackets then print("snabbnfv traffic starting (benchmark mode)") bench(pciaddr, confpath, sockpath, benchpackets) else print("snabbnfv traffic starting") traffic(pciaddr, confpath, sockpath) end else print("Wrong number of arguments: " .. tonumber(#args)) print() print(short_usage()) main.exit(1) end end function short_usage () return (usage:gsub("%s*CONFIG FILE FORMAT:.*", "")) end function long_usage () return usage end -- Run in real traffic mode. function traffic (pciaddr, confpath, sockpath) engine.log = true local mtime = 0 local needs_reconfigure = true function check_for_reconfigure() needs_reconfigure = C.stat_mtime(confpath) ~= mtime end timer.activate(timer.new("reconf", check_for_reconfigure, 1e9, 'repeating')) -- Flush logs every second. timer.activate(timer.new("flush", io.flush, 1e9, 'repeating')) timer.activate(ingress_drop_monitor.new({action='warn'}):timer()) while true do needs_reconfigure = false print("Loading " .. confpath) mtime = C.stat_mtime(confpath) if mtime == 0 then print(("WARNING: File '%s' does not exist."):format(confpath)) end engine.configure(nfvconfig.load(confpath, pciaddr, sockpath)) engine.main({done=function() return needs_reconfigure end}) end end -- Run in benchmark mode. function bench (pciaddr, confpath, sockpath, npackets) npackets = tonumber(npackets) local ports = dofile(confpath) local nic, bench if pciaddr then nic = (nfvconfig.port_name(ports[1])).."_NIC" else nic = "BenchSink" bench = { src="52:54:00:00:00:02", dst="52:54:00:00:00:01", sizes = {60}} end engine.log = true engine.Hz = false print("Loading " .. confpath) engine.configure(nfvconfig.load(confpath, pciaddr, sockpath, bench)) -- From designs/nfv local start, packets, bytes = 0, 0, 0 local done = function () local inputs = link.stats(engine.app_table[nic].input) local _, input = next(inputs) if start == 0 and input.rxpackets > 0 then -- started receiving, record time and packet count packets = input.rxpackets bytes = input.rxbytes start = C.get_monotonic_time() if os.getenv("NFV_PROF") then require("jit.p").start(os.getenv("NFV_PROF"), os.getenv("NFV_PROF_FILE")) else print("No LuaJIT profiling enabled ($NFV_PROF unset).") end if os.getenv("NFV_DUMP") then require("jit.dump").start(os.getenv("NFV_DUMP"), os.getenv("NFV_DUMP_FILE")) main.dumping = true else print("No LuaJIT dump enabled ($NFV_DUMP unset).") end end return input.rxpackets - packets >= npackets end engine.main({done = done, no_report = true}) local finish = C.get_monotonic_time() local runtime = finish - start local breaths = tonumber(counter.read(engine.breaths)) local inputs = link.stats(engine.app_table[nic].input) local _, input = next(inputs) packets = input.rxpackets - packets bytes = input.rxbytes - bytes engine.report() print() print(("Processed %.1f million packets in %.2f seconds (%d bytes; %.2f Gbps)"):format(packets / 1e6, runtime, bytes, bytes * 8.0 / 1e9 / runtime)) print(("Made %s breaths: %.2f packets per breath; %.2fus per breath"):format(lib.comma_value(breaths), packets / breaths, runtime / breaths * 1e6)) print(("Rate(Mpps):\t%.3f"):format(packets / runtime / 1e6)) require("jit.p").stop() end
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local lib = require("core.lib") local nfvconfig = require("program.snabbnfv.nfvconfig") local usage = require("program.snabbnfv.traffic.README_inc") local ffi = require("ffi") local C = ffi.C local timer = require("core.timer") local pci = require("lib.hardware.pci") local ingress_drop_monitor = require("lib.timers.ingress_drop_monitor") local counter = require("core.counter") local long_opts = { benchmark = "B", help = "h", ["link-report-interval"] = "k", ["load-report-interval"] = "l", ["debug-report-interval"] = "D", ["busy"] = "b", ["long-help"] = "H" } function run (args) local opt = {} local benchpackets local linkreportinterval = 0 local loadreportinterval = 1 local debugreportinterval = 0 function opt.B (arg) benchpackets = tonumber(arg) end function opt.h (arg) print(short_usage()) main.exit(1) end function opt.H (arg) print(long_usage()) main.exit(1) end function opt.k (arg) linkreportinterval = tonumber(arg) end function opt.l (arg) loadreportinterval = tonumber(arg) end function opt.D (arg) debugreportinterval = tonumber(arg) end function opt.b (arg) engine.busywait = true end args = lib.dogetopt(args, opt, "hHB:k:l:D:b", long_opts) if #args == 3 then local pciaddr, confpath, sockpath = unpack(args) if pciaddr == "soft" then pciaddr = nil end if pciaddr then local ok, info = pcall(pci.device_info, pciaddr) if not ok then print("Error: device not found " .. pciaddr) os.exit(1) end if not info.driver then print("Error: no driver for device " .. pciaddr) os.exit(1) end end if loadreportinterval > 0 then local t = timer.new("nfvloadreport", engine.report_load, loadreportinterval*1e9, 'repeating') timer.activate(t) end if linkreportinterval > 0 then local t = timer.new("nfvlinkreport", engine.report_links, linkreportinterval*1e9, 'repeating') timer.activate(t) end if debugreportinterval > 0 then local t = timer.new("nfvdebugreport", engine.report_apps, debugreportinterval*1e9, 'repeating') timer.activate(t) end if benchpackets then print("snabbnfv traffic starting (benchmark mode)") bench(pciaddr, confpath, sockpath, benchpackets) else print("snabbnfv traffic starting") traffic(pciaddr, confpath, sockpath) end else print("Wrong number of arguments: " .. tonumber(#args)) print() print(short_usage()) main.exit(1) end end function short_usage () return (usage:gsub("%s*CONFIG FILE FORMAT:.*", "")) end function long_usage () return usage end -- Run in real traffic mode. function traffic (pciaddr, confpath, sockpath) engine.log = true local mtime = 0 local needs_reconfigure = true function check_for_reconfigure() needs_reconfigure = C.stat_mtime(confpath) ~= mtime end timer.activate(timer.new("reconf", check_for_reconfigure, 1e9, 'repeating')) -- Flush logs every second. timer.activate(timer.new("flush", io.flush, 1e9, 'repeating')) timer.activate(ingress_drop_monitor.new({action='warn'}):timer()) while true do needs_reconfigure = false print("Loading " .. confpath) mtime = C.stat_mtime(confpath) if mtime == 0 then print(("WARNING: File '%s' does not exist."):format(confpath)) end engine.configure(nfvconfig.load(confpath, pciaddr, sockpath)) engine.main({done=function() return needs_reconfigure end}) end end -- Run in benchmark mode. function bench (pciaddr, confpath, sockpath, npackets) npackets = tonumber(npackets) local ports = dofile(confpath) local nic, bench if pciaddr then nic = (nfvconfig.port_name(ports[1])).."_NIC" else nic = "BenchSink" bench = { src="52:54:00:00:00:02", dst="52:54:00:00:00:01", sizes = {60}} end engine.log = true engine.Hz = false print("Loading " .. confpath) engine.configure(nfvconfig.load(confpath, pciaddr, sockpath, bench)) -- From designs/nfv local start, packets, bytes = 0, 0, 0 local done = function () local _, rx = next(engine.app_table[nic].input) local input = link.stats(rx) if start == 0 and input.rxpackets > 0 then -- started receiving, record time and packet count packets = input.rxpackets bytes = input.rxbytes start = C.get_monotonic_time() if os.getenv("NFV_PROF") then require("jit.p").start(os.getenv("NFV_PROF"), os.getenv("NFV_PROF_FILE")) else print("No LuaJIT profiling enabled ($NFV_PROF unset).") end if os.getenv("NFV_DUMP") then require("jit.dump").start(os.getenv("NFV_DUMP"), os.getenv("NFV_DUMP_FILE")) main.dumping = true else print("No LuaJIT dump enabled ($NFV_DUMP unset).") end end return input.rxpackets - packets >= npackets end engine.main({done = done, no_report = true}) local finish = C.get_monotonic_time() local runtime = finish - start local breaths = tonumber(counter.read(engine.breaths)) local _, rx = next(engine.app_table[nic].input) local input = link.stats(rx) packets = input.rxpackets - packets bytes = input.rxbytes - bytes engine.report() print() print(("Processed %.1f million packets in %.2f seconds (%d bytes; %.2f Gbps)"):format(packets / 1e6, runtime, bytes, bytes * 8.0 / 1e9 / runtime)) print(("Made %s breaths: %.2f packets per breath; %.2fus per breath"):format(lib.comma_value(breaths), packets / breaths, runtime / breaths * 1e6)) print(("Rate(Mpps):\t%.3f"):format(packets / runtime / 1e6)) require("jit.p").stop() end
Fix adaptation of "snabb snabbnfv traffic" to be driver-agnostic
Fix adaptation of "snabb snabbnfv traffic" to be driver-agnostic Fix borked code introduced in 3f5d3efbb84a9033b8b7f1021ef47570f4ecce9c.
Lua
apache-2.0
dpino/snabbswitch,SnabbCo/snabbswitch,alexandergall/snabbswitch,alexandergall/snabbswitch,eugeneia/snabbswitch,snabbco/snabb,snabbco/snabb,dpino/snabb,alexandergall/snabbswitch,dpino/snabb,eugeneia/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,Igalia/snabb,dpino/snabb,Igalia/snabb,snabbco/snabb,Igalia/snabbswitch,alexandergall/snabbswitch,SnabbCo/snabbswitch,SnabbCo/snabbswitch,snabbco/snabb,eugeneia/snabb,Igalia/snabbswitch,dpino/snabb,alexandergall/snabbswitch,Igalia/snabbswitch,snabbco/snabb,dpino/snabb,eugeneia/snabb,eugeneia/snabb,eugeneia/snabb,Igalia/snabb,SnabbCo/snabbswitch,Igalia/snabbswitch,eugeneia/snabbswitch,snabbco/snabb,dpino/snabbswitch,Igalia/snabbswitch,eugeneia/snabb,dpino/snabbswitch,dpino/snabb,Igalia/snabb,eugeneia/snabb,Igalia/snabb,eugeneia/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,eugeneia/snabb,eugeneia/snabb,dpino/snabbswitch,dpino/snabb,snabbco/snabb,Igalia/snabb,Igalia/snabb
592e0ee5e2d46840559d2b9f6952bff0701082d0
mod_muc_restrict_rooms/mod_muc_restrict_rooms.lua
mod_muc_restrict_rooms/mod_muc_restrict_rooms.lua
local st = require "util.stanza"; local nodeprep = require "util.encodings".stringprep.nodeprep; local rooms = module:shared "muc/rooms"; if not rooms then module:log("error", "This module only works on MUC components!"); return; end local admins = module:get_option_set("admins", {}); local restrict_patterns = module:get_option("muc_restrict_matching", {}); local restrict_excepts = module:get_option_set("muc_restrict_exceptions", {}); local restrict_allow_admins = module:get_option_set("muc_restrict_allow_admins", false); local function is_restricted(room, who) -- If admins can join prohibited rooms, we allow them to if (restrict_allow_admins == true) and (admins:contains(who)) then module:log("debug", "Admins are allowed to enter restricted rooms (%s on %s)", who, room) return false; end -- Don't evaluate exceptions if restrict_excepts:contains(room:lower()) then module:log("debug", "Room %s is amongst restriction exceptions", room:lower()) return false; end -- Evaluate regexps of restricted patterns for pattern,reason in pairs(restrict_patterns) do if room:match(pattern) then module:log("debug", "Room %s is restricted by pattern %s, user %s is not allowed to join (%s)", room, pattern, who, reason) return reason; end end return nil end module:hook("presence/full", function(event) local stanza = event.stanza; if stanza.name == "presence" and stanza.attr.type == "unavailable" then -- Leaving events get discarded return; end -- Get the room local room = stanza.attr.from:match("([^@]+)@[^@]+") if not room then return; end -- Get who has tried to join it local who = stanza.attr.to:match("([^\/]+)\/[^\/]+") -- Checking whether room is restricted local check_restricted = is_restricted(room, who) if check_restricted ~= nil then event.allowed = false; event.stanza.attr.type = 'error'; return event.origin.send(st.error_reply(event.stanza, "cancel", "forbidden", "You're not allowed to enter this room: " .. check_restricted)); end end, 10);
local st = require "util.stanza"; local jid = require "util.jid"; local nodeprep = require "util.encodings".stringprep.nodeprep; local rooms = module:shared "muc/rooms"; if not rooms then module:log("error", "This module only works on MUC components!"); return; end local restrict_patterns = module:get_option("muc_restrict_matching", {}); local restrict_excepts = module:get_option_set("muc_restrict_exceptions", {}); local restrict_allow_admins = module:get_option_boolean("muc_restrict_allow_admins", false); local function is_restricted(room, who) -- If admins can join prohibited rooms, we allow them to if restrict_allow_admins and usermanager.is_admin(who, module.host) then module:log("debug", "Admins are allowed to enter restricted rooms (%s on %s)", who, room) return nil; end -- Don't evaluate exceptions if restrict_excepts:contains(room) then module:log("debug", "Room %s is amongst restriction exceptions", room()) return nil; end -- Evaluate regexps of restricted patterns for pattern,reason in pairs(restrict_patterns) do if room:match(pattern) then module:log("debug", "Room %s is restricted by pattern %s, user %s is not allowed to join (%s)", room, pattern, who, reason) return reason; end end return nil end module:hook("presence/full", function(event) local stanza = event.stanza; if stanza.name == "presence" and stanza.attr.type == "unavailable" then -- Leaving events get discarded return; end -- Get the room local room = jid.split(stanza.attr.from); if not room then return; end -- Get who has tried to join it local who = jid.bare(stanza.attr.to) -- Checking whether room is restricted local check_restricted = is_restricted(room, who) if check_restricted ~= nil then event.allowed = false; event.stanza.attr.type = 'error'; return event.origin.send(st.error_reply(event.stanza, "cancel", "forbidden", "You're not allowed to enter this room: " .. check_restricted)); end end, 10);
mod_muc_restrict_rooms: Some fixes based on Matthew's comments + a few more
mod_muc_restrict_rooms: Some fixes based on Matthew's comments + a few more
Lua
mit
joewalker/prosody-modules,stephen322/prosody-modules,dhotson/prosody-modules,vince06fr/prosody-modules,cryptotoad/prosody-modules,joewalker/prosody-modules,amenophis1er/prosody-modules,amenophis1er/prosody-modules,NSAKEY/prosody-modules,softer/prosody-modules,jkprg/prosody-modules,dhotson/prosody-modules,either1/prosody-modules,prosody-modules/import,BurmistrovJ/prosody-modules,iamliqiang/prosody-modules,guilhem/prosody-modules,olax/prosody-modules,vince06fr/prosody-modules,prosody-modules/import,mmusial/prosody-modules,heysion/prosody-modules,dhotson/prosody-modules,LanceJenkinZA/prosody-modules,either1/prosody-modules,mardraze/prosody-modules,mmusial/prosody-modules,stephen322/prosody-modules,syntafin/prosody-modules,drdownload/prosody-modules,syntafin/prosody-modules,apung/prosody-modules,asdofindia/prosody-modules,drdownload/prosody-modules,mmusial/prosody-modules,1st8/prosody-modules,NSAKEY/prosody-modules,heysion/prosody-modules,iamliqiang/prosody-modules,amenophis1er/prosody-modules,vfedoroff/prosody-modules,LanceJenkinZA/prosody-modules,obelisk21/prosody-modules,amenophis1er/prosody-modules,LanceJenkinZA/prosody-modules,jkprg/prosody-modules,Craige/prosody-modules,iamliqiang/prosody-modules,asdofindia/prosody-modules,softer/prosody-modules,cryptotoad/prosody-modules,NSAKEY/prosody-modules,crunchuser/prosody-modules,softer/prosody-modules,amenophis1er/prosody-modules,vfedoroff/prosody-modules,either1/prosody-modules,prosody-modules/import,either1/prosody-modules,obelisk21/prosody-modules,BurmistrovJ/prosody-modules,olax/prosody-modules,drdownload/prosody-modules,Craige/prosody-modules,1st8/prosody-modules,joewalker/prosody-modules,1st8/prosody-modules,jkprg/prosody-modules,iamliqiang/prosody-modules,apung/prosody-modules,BurmistrovJ/prosody-modules,brahmi2/prosody-modules,NSAKEY/prosody-modules,apung/prosody-modules,Craige/prosody-modules,cryptotoad/prosody-modules,BurmistrovJ/prosody-modules,jkprg/prosody-modules,guilhem/prosody-modules,heysion/prosody-modules,brahmi2/prosody-modules,jkprg/prosody-modules,olax/prosody-modules,NSAKEY/prosody-modules,vfedoroff/prosody-modules,crunchuser/prosody-modules,apung/prosody-modules,cryptotoad/prosody-modules,asdofindia/prosody-modules,mardraze/prosody-modules,Craige/prosody-modules,asdofindia/prosody-modules,drdownload/prosody-modules,crunchuser/prosody-modules,softer/prosody-modules,BurmistrovJ/prosody-modules,crunchuser/prosody-modules,stephen322/prosody-modules,mmusial/prosody-modules,obelisk21/prosody-modules,asdofindia/prosody-modules,LanceJenkinZA/prosody-modules,brahmi2/prosody-modules,LanceJenkinZA/prosody-modules,stephen322/prosody-modules,heysion/prosody-modules,obelisk21/prosody-modules,guilhem/prosody-modules,vfedoroff/prosody-modules,Craige/prosody-modules,1st8/prosody-modules,prosody-modules/import,mardraze/prosody-modules,prosody-modules/import,drdownload/prosody-modules,vince06fr/prosody-modules,apung/prosody-modules,mardraze/prosody-modules,vince06fr/prosody-modules,softer/prosody-modules,guilhem/prosody-modules,olax/prosody-modules,stephen322/prosody-modules,mmusial/prosody-modules,heysion/prosody-modules,brahmi2/prosody-modules,joewalker/prosody-modules,brahmi2/prosody-modules,vfedoroff/prosody-modules,syntafin/prosody-modules,crunchuser/prosody-modules,iamliqiang/prosody-modules,syntafin/prosody-modules,joewalker/prosody-modules,cryptotoad/prosody-modules,guilhem/prosody-modules,obelisk21/prosody-modules,1st8/prosody-modules,either1/prosody-modules,vince06fr/prosody-modules,olax/prosody-modules,dhotson/prosody-modules,mardraze/prosody-modules,dhotson/prosody-modules,syntafin/prosody-modules
baf1202a522cc769e33faa2e14b3c03140fc3309
action.lua
action.lua
function on_msg_receive (msg) if msg.out then return end if (msg.text=='ping') then send_msg (msg.from.print_name, 'pong', ok_cb, false) end if (msg.text=='bos') then send_msg (msg.from.print_name, 'yes bos?', ok_cb, false) end if (msg.text=='photo') then os.execute('/home/pi/camera/camera.sh') send_photo (msg.from.print_name, '/home/pi/camera/image2.jpg', ok_cb, false) end if (msg.text=='on') then os.execute('python /home/pi/tg/led.py') send_msg (msg.from.print_name, 'LED sudah dinyalakan boss!', ok_cb, false) end if (msg.text=='off') then os.execute('python /home/pi/tg/led_off.py') send_msg (msg.from.print_name, 'LED sudah dimatikan boss!', ok_cb, false) end end function on_our_id (id) end function on_secret_chat_created (peer) end function on_user_update (user) end function on_chat_update (user) end function on_get_difference_end () end function on_binlog_replay_end () end
function on_msg_receive (msg) if msg.out then return end if (msg.text=='ping') then send_msg (msg.from.print_name, 'pong', ok_cb, false) end if (msg.text=='bos') then send_msg (msg.from.print_name, 'yes bos?', ok_cb, false) end if (msg.text=='photo') then os.execute('/home/pi/camera/camera.sh') send_photo (msg.from.print_name, '/home/pi/camera/image2.jpg', ok_cb, false) end if (msg.text=='on') then os.execute('python /home/pi/tg/led.py') send_msg (msg.from.print_name, 'LED sudah dinyalakan boss!', ok_cb, false) end if (msg.text=='off') then os.execute('python /home/pi/tg/led_off.py') send_msg (msg.from.print_name, 'LED sudah dimatikan boss!', ok_cb, false) end end function on_our_id (id) end function on_secret_chat_created (peer) end function on_user_update (user) end function on_chat_update (user) end function on_get_difference_end () end function on_binlog_replay_end () end
Fixes indentation
Fixes indentation
Lua
mit
aryulianto/Gempi_Bot,aryulianto/Gempi_Bot,aryulianto/Telegram_Bot,aryulianto/Telegram_Bot
5dce5148e762a6e2256249a541c0356135b23534
lua/framework/graphics/font.lua
lua/framework/graphics/font.lua
--=========== Copyright © 2018, Planimeter, All rights reserved. =============-- -- -- Purpose: -- --============================================================================-- require( "class" ) local FT = require( "freetype" ) local ffi = require( "ffi" ) local GL = require( "opengl" ) local ft = ffi.new( "FT_Library[1]" ) FT.FT_Init_FreeType( ft ) class( "framework.graphics.font" ) local font = framework.graphics.font function font:font( filename, size ) size = size or 16 self.face = ffi.new( "FT_Face[1]" ) self.buffer, self.length = framework.filesystem.read( filename ) if ( self.buffer == nil ) then FT.FT_Done_Face( self.face ) error( self.length, 3 ) end FT.FT_New_Memory_Face( ft[0], self.buffer, self.length, 0, self.face ) self.size = size size = size * framework.window.getPixelScale() FT.FT_Set_Pixel_Sizes( self.face[0], 0, size ) self.texture = ffi.new( "GLuint[1]" ) GL.glGenTextures( 1, self.texture ) GL.glBindTexture( GL.GL_TEXTURE_2D, self.texture[0] ) GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_BASE_LEVEL, 0 ) GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAX_LEVEL, 0 ) local o = GL.GL_ONE local r = GL.GL_RED local mask = ffi.new( "GLint[4]", o, o, o, r ) GL.glTexParameteriv( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_SWIZZLE_RGBA, mask ) local s = self.face[0].size.metrics; self.advance = bit.rshift( tonumber( s.max_advance ), 6 ) self.ascent = bit.rshift( tonumber( s.ascender ), 6 ) self.descent = bit.rshift( tonumber( s.descender ), 6 ) self.height = bit.rshift( tonumber( s.height ), 6 ) setproxy( self ) end function font:getWidth( text ) local width = 0 local face = self.face[0] for i = 1, #text do local char = string.sub( text, i, i ) if ( FT.FT_Load_Char( face, string.byte( char ), 4 ) == 0 ) then local g = face.glyph local bw = g.bitmap.width width = width + bw else error( "Could not load character '" .. char .. "'", 3 ) end end return tonumber( width ) end function font:getHeight() return math.floor( self.height / framework.window.getPixelScale() + 0.5 ) end function font:getWrap() -- TODO: Implement me. return 0, {} end function font:print( text, x, y, r, sx, sy, ox, oy, kx, ky ) local defaultVBO = framework.graphics._defaultVBO local shader = framework.graphics.getShader() local position = GL.glGetAttribLocation( shader, "position" ) local stride = 4 * ffi.sizeof( "GLfloat" ) local texcoord = GL.glGetAttribLocation( shader, "texcoord" ) local pointer = ffi.cast( "GLvoid *", 2 * ffi.sizeof( "GLfloat" ) ) GL.glBindBuffer( GL.GL_ARRAY_BUFFER, defaultVBO[0] ) GL.glVertexAttribPointer( position, 2, GL.GL_FLOAT, 0, stride, nil ) GL.glEnableVertexAttribArray( texcoord ) GL.glVertexAttribPointer( texcoord, 2, GL.GL_FLOAT, 0, stride, pointer ) framework.graphics.updateTransformations() GL.glBindTexture( GL.GL_TEXTURE_2D, self.texture[0] ) GL.glPixelStorei( GL.GL_UNPACK_ALIGNMENT, 1 ) local face = self.face[0] for i = 1, #text do local char = string.sub( text, i, i ) if ( FT.FT_Load_Char( face, string.byte( char ), 4 ) == 0 ) then local g = face.glyph local gx = x + g.bitmap_left local gy = y + face.size.metrics.ascender / 64 - g.bitmap_top local width = g.bitmap.width local height = g.bitmap.rows local vertices = { -- vertex -- texcoord gx, gy + height, 0.0, 1.0, gx + width, gy + height, 1.0, 1.0, gx, gy, 0.0, 0.0, gx + width, gy + height, 1.0, 1.0, gx + width, gy, 1.0, 0.0, gx, gy, 0.0, 0.0 } local pVertices = ffi.new( "GLfloat[?]", #vertices, vertices ) local size = ffi.sizeof( pVertices ) GL.glBufferData( GL.GL_ARRAY_BUFFER, size, pVertices, GL.GL_STREAM_DRAW ) GL.glTexImage2D( GL.GL_TEXTURE_2D, 0, GL.GL_RED, g.bitmap.width, g.bitmap.rows, 0, GL.GL_RED, GL.GL_UNSIGNED_BYTE, g.bitmap.buffer ) framework.graphics.drawArrays( GL.GL_TRIANGLES, 0, #vertices / 4 ) x = x + ( g.advance.x / 64 ) y = y + ( g.advance.y / 64 ) else error( "Could not load character '" .. char .. "'", 3 ) end end GL.glPixelStorei( GL.GL_UNPACK_ALIGNMENT, 4 ) end function font:__gc() GL.glDeleteTextures( 1, self.texture ) FT.FT_Done_Face( self.face[0] ) end
--=========== Copyright © 2018, Planimeter, All rights reserved. =============-- -- -- Purpose: -- --============================================================================-- require( "class" ) local FT = require( "freetype" ) local ffi = require( "ffi" ) local GL = require( "opengl" ) local ft = ffi.new( "FT_Library[1]" ) FT.FT_Init_FreeType( ft ) class( "framework.graphics.font" ) local font = framework.graphics.font function font:font( filename, size ) size = size or 16 self.face = ffi.new( "FT_Face[1]" ) self.buffer, self.length = framework.filesystem.read( filename ) if ( self.buffer == nil ) then FT.FT_Done_Face( self.face ) error( self.length, 3 ) end FT.FT_New_Memory_Face( ft[0], self.buffer, self.length, 0, self.face ) self.size = size size = size * framework.window.getPixelScale() FT.FT_Set_Pixel_Sizes( self.face[0], 0, size ) self.texture = ffi.new( "GLuint[1]" ) GL.glGenTextures( 1, self.texture ) GL.glBindTexture( GL.GL_TEXTURE_2D, self.texture[0] ) GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_BASE_LEVEL, 0 ) GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAX_LEVEL, 0 ) local o = GL.GL_ONE local r = GL.GL_RED local mask = ffi.new( "GLint[4]", o, o, o, r ) GL.glTexParameteriv( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_SWIZZLE_RGBA, mask ) local s = self.face[0].size.metrics; self.advance = bit.rshift( tonumber( s.max_advance ), 6 ) self.ascent = bit.rshift( tonumber( s.ascender ), 6 ) self.descent = bit.rshift( tonumber( s.descender ), 6 ) self.height = bit.rshift( tonumber( s.height ), 6 ) setproxy( self ) end function font:getWidth( text ) local width = 0 local face = self.face[0] for i = 1, #text do local char = string.sub( text, i, i ) if ( FT.FT_Load_Char( face, string.byte( char ), 4 ) == 0 ) then local g = face.glyph local bw = g.bitmap.width width = width + bw else error( "Could not load character '" .. char .. "'", 3 ) end end return tonumber( width ) end function font:getHeight() return math.floor( self.height / framework.window.getPixelScale() + 0.5 ) end function font:getWrap() -- TODO: Implement me. return 0, {} end function font:print( text, x, y, r, sx, sy, ox, oy, kx, ky ) local defaultVBO = framework.graphics._defaultVBO local shader = framework.graphics.getShader() local position = GL.glGetAttribLocation( shader, "position" ) local stride = 4 * ffi.sizeof( "GLfloat" ) local texcoord = GL.glGetAttribLocation( shader, "texcoord" ) local pointer = ffi.cast( "GLvoid *", 2 * ffi.sizeof( "GLfloat" ) ) GL.glBindBuffer( GL.GL_ARRAY_BUFFER, defaultVBO[0] ) GL.glVertexAttribPointer( position, 2, GL.GL_FLOAT, 0, stride, nil ) GL.glEnableVertexAttribArray( texcoord ) GL.glVertexAttribPointer( texcoord, 2, GL.GL_FLOAT, 0, stride, pointer ) framework.graphics.updateTransformations() GL.glBindTexture( GL.GL_TEXTURE_2D, self.texture[0] ) GL.glPixelStorei( GL.GL_UNPACK_ALIGNMENT, 1 ) local face = self.face[0] local _x = x for i = 1, #text do local char = string.sub( text, i, i ) if ( FT.FT_Load_Char( face, string.byte( char ), 4 ) == 0 ) then if ( char == "\n" ) then x = _x y = y + self:getHeight() else local g = face.glyph local gx = x + g.bitmap_left local gy = y + face.size.metrics.ascender / 64 - g.bitmap_top local width = g.bitmap.width local height = g.bitmap.rows local vertices = { -- vertex -- texcoord gx, gy + height, 0.0, 1.0, gx + width, gy + height, 1.0, 1.0, gx, gy, 0.0, 0.0, gx + width, gy + height, 1.0, 1.0, gx + width, gy, 1.0, 0.0, gx, gy, 0.0, 0.0 } local pVertices = ffi.new( "GLfloat[?]", #vertices, vertices ) local size = ffi.sizeof( pVertices ) GL.glBufferData( GL.GL_ARRAY_BUFFER, size, pVertices, GL.GL_STREAM_DRAW ) GL.glTexImage2D( GL.GL_TEXTURE_2D, 0, GL.GL_RED, g.bitmap.width, g.bitmap.rows, 0, GL.GL_RED, GL.GL_UNSIGNED_BYTE, g.bitmap.buffer ) framework.graphics.drawArrays( GL.GL_TRIANGLES, 0, #vertices / 4 ) x = x + ( g.advance.x / 64 ) y = y + ( g.advance.y / 64 ) end else error( "Could not load character '" .. char .. "'", 3 ) end end GL.glPixelStorei( GL.GL_UNPACK_ALIGNMENT, 4 ) end function font:__gc() GL.glDeleteTextures( 1, self.texture ) FT.FT_Done_Face( self.face[0] ) end
Fix rendering newlines
Fix rendering newlines
Lua
mit
Planimeter/lgameframework,Planimeter/lgameframework,Planimeter/lgameframework
81c9493e0e0746c5befea32d0cbf222a6fb44c7a
src/base/detoken.lua
src/base/detoken.lua
-- -- detoken.lua -- -- Expands tokens. -- -- Copyright (c) 2011-2013 Jason Perkins and the Premake project -- premake.detoken = {} local detoken = premake.detoken -- -- Expand tokens in a value. -- -- @param value -- The value containing the tokens to be expanded. -- @param environ -- An execution environment for any token expansion. This is a list of key- -- value pairs that will be inserted as global variables into the token -- expansion runtime environment. -- @param ispath -- If true, the value treated as a file system path, and checks will be made -- for nested absolute paths from expanded tokens. -- @param basedir -- If provided, path tokens encountered in non-path fields (where the ispath -- parameter is set to false) will be made relative to this location. -- @return -- The value with any contained tokens expanded. -- function detoken.expand(value, environ, ispath, basedir) if type(value) ~= "string" then return value end -- enable access to the global environment setmetatable(environ, {__index = _G}) function expandtoken(token, environ) -- convert the token into a function to execute local func, err = loadstring("return " .. token) if not func then return nil, err end -- give the function access to the project objects setfenv(func, environ) -- run it and return the result local result = func() or "" -- If the result is an absolute path, and it is being inserted into -- a path value, place a special marker at the start of it. After -- all results have been processed, I can look for these markers to -- find the last absolute path expanded. -- -- Example: the value "/home/user/myprj/%{cfg.objdir}" expands to: -- "/home/user/myprj//home/user/myprj/obj/Debug". -- -- By inserting a marker this becomes: -- "/home/user/myprj/[\0]/home/user/myprj/obj/Debug". -- -- I can now trim everything before the marker to get the right -- result, which should always be the last absolute path specified: -- "/home/user/myprj/obj/Debug" local isAbs = path.isabsolute(result) if isAbs and ispath then result = "\0" .. result end -- If the result is an absolute path, and it is being inserted into -- a NON-path value, I need to make it relative to the project that -- will contain it. Otherwise I ended up with an absolute path in -- the generated project, and it can no longer be moved around. if isAbs and not ispath and basedir then result = path.getrelative(basedir, result) end return result end function expandvalue(value) local count repeat value, count = value:gsub("%%{(.-)}", function(token) local result, err = expandtoken(token, environ) if not result then error(err, 0) end return result end) until count == 0 -- if a path, look for a split out embedded absolute paths if ispath then local i, j repeat i, j = value:find("\0") if i then value = value:sub(i + 1) end until not i end return value end function recurse(value) if type(value) == "table" then for k, v in pairs(value) do value[k] = recurse(v) end return value else return expandvalue(value) end end return recurse(value) end
-- -- detoken.lua -- -- Expands tokens. -- -- Copyright (c) 2011-2013 Jason Perkins and the Premake project -- premake.detoken = {} local detoken = premake.detoken -- -- Expand tokens in a value. -- -- @param value -- The value containing the tokens to be expanded. -- @param environ -- An execution environment for any token expansion. This is a list of key- -- value pairs that will be inserted as global variables into the token -- expansion runtime environment. -- @param ispath -- If true, the value treated as a file system path, and checks will be made -- for nested absolute paths from expanded tokens. -- @param basedir -- If provided, path tokens encountered in non-path fields (where the ispath -- parameter is set to false) will be made relative to this location. -- @return -- The value with any contained tokens expanded. -- function detoken.expand(value, environ, ispath, basedir) -- enable access to the global environment setmetatable(environ, {__index = _G}) function expandtoken(token, environ) -- convert the token into a function to execute local func, err = loadstring("return " .. token) if not func then return nil, err end -- give the function access to the project objects setfenv(func, environ) -- run it and return the result local result = func() or "" -- If the result is an absolute path, and it is being inserted into -- a path value, place a special marker at the start of it. After -- all results have been processed, I can look for these markers to -- find the last absolute path expanded. -- -- Example: the value "/home/user/myprj/%{cfg.objdir}" expands to: -- "/home/user/myprj//home/user/myprj/obj/Debug". -- -- By inserting a marker this becomes: -- "/home/user/myprj/[\0]/home/user/myprj/obj/Debug". -- -- I can now trim everything before the marker to get the right -- result, which should always be the last absolute path specified: -- "/home/user/myprj/obj/Debug" local isAbs = path.isabsolute(result) if isAbs and ispath then result = "\0" .. result end -- If the result is an absolute path, and it is being inserted into -- a NON-path value, I need to make it relative to the project that -- will contain it. Otherwise I ended up with an absolute path in -- the generated project, and it can no longer be moved around. if isAbs and not ispath and basedir then result = path.getrelative(basedir, result) end return result end function expandvalue(value) if type(value) ~= "string" then return end local count repeat value, count = value:gsub("%%{(.-)}", function(token) local result, err = expandtoken(token, environ) if not result then error(err, 0) end return result end) until count == 0 -- if a path, look for a split out embedded absolute paths if ispath then local i, j repeat i, j = value:find("\0") if i then value = value:sub(i + 1) end until not i end return value end function recurse(value) if type(value) == "table" then for k, v in pairs(value) do value[k] = recurse(v) end return value else return expandvalue(value) end end return recurse(value) end
Fix detoken of table values, broken by previous commit
Fix detoken of table values, broken by previous commit
Lua
bsd-3-clause
dcourtois/premake-core,bravnsgaard/premake-core,LORgames/premake-core,dcourtois/premake-core,CodeAnxiety/premake-core,xriss/premake-core,grbd/premake-core,noresources/premake-core,premake/premake-core,jstewart-amd/premake-core,prapin/premake-core,CodeAnxiety/premake-core,grbd/premake-core,jstewart-amd/premake-core,Yhgenomics/premake-core,resetnow/premake-core,aleksijuvani/premake-core,mendsley/premake-core,Zefiros-Software/premake-core,mandersan/premake-core,soundsrc/premake-core,tritao/premake-core,aleksijuvani/premake-core,noresources/premake-core,jsfdez/premake-core,dcourtois/premake-core,sleepingwit/premake-core,martin-traverse/premake-core,starkos/premake-core,kankaristo/premake-core,dcourtois/premake-core,tritao/premake-core,starkos/premake-core,akaStiX/premake-core,premake/premake-core,xriss/premake-core,LORgames/premake-core,tvandijck/premake-core,mandersan/premake-core,Zefiros-Software/premake-core,bravnsgaard/premake-core,sleepingwit/premake-core,martin-traverse/premake-core,tvandijck/premake-core,Tiger66639/premake-core,Tiger66639/premake-core,LORgames/premake-core,Blizzard/premake-core,premake/premake-core,resetnow/premake-core,CodeAnxiety/premake-core,lizh06/premake-core,sleepingwit/premake-core,starkos/premake-core,prapin/premake-core,Tiger66639/premake-core,Blizzard/premake-core,mendsley/premake-core,Meoo/premake-core,TurkeyMan/premake-core,akaStiX/premake-core,Zefiros-Software/premake-core,alarouche/premake-core,prapin/premake-core,Yhgenomics/premake-core,jsfdez/premake-core,aleksijuvani/premake-core,saberhawk/premake-core,sleepingwit/premake-core,noresources/premake-core,noresources/premake-core,akaStiX/premake-core,mandersan/premake-core,alarouche/premake-core,aleksijuvani/premake-core,Blizzard/premake-core,kankaristo/premake-core,prapin/premake-core,jstewart-amd/premake-core,noresources/premake-core,premake/premake-core,starkos/premake-core,xriss/premake-core,soundsrc/premake-core,sleepingwit/premake-core,xriss/premake-core,soundsrc/premake-core,akaStiX/premake-core,starkos/premake-core,Blizzard/premake-core,lizh06/premake-core,lizh06/premake-core,noresources/premake-core,xriss/premake-core,kankaristo/premake-core,tvandijck/premake-core,soundsrc/premake-core,Zefiros-Software/premake-core,jsfdez/premake-core,resetnow/premake-core,PlexChat/premake-core,grbd/premake-core,tritao/premake-core,PlexChat/premake-core,PlexChat/premake-core,bravnsgaard/premake-core,mendsley/premake-core,Yhgenomics/premake-core,martin-traverse/premake-core,Meoo/premake-core,Blizzard/premake-core,martin-traverse/premake-core,grbd/premake-core,LORgames/premake-core,tritao/premake-core,Tiger66639/premake-core,Blizzard/premake-core,alarouche/premake-core,felipeprov/premake-core,starkos/premake-core,jstewart-amd/premake-core,premake/premake-core,mendsley/premake-core,Meoo/premake-core,saberhawk/premake-core,mandersan/premake-core,alarouche/premake-core,mandersan/premake-core,Yhgenomics/premake-core,soundsrc/premake-core,TurkeyMan/premake-core,felipeprov/premake-core,resetnow/premake-core,CodeAnxiety/premake-core,CodeAnxiety/premake-core,noresources/premake-core,dcourtois/premake-core,Meoo/premake-core,premake/premake-core,saberhawk/premake-core,LORgames/premake-core,PlexChat/premake-core,TurkeyMan/premake-core,aleksijuvani/premake-core,Zefiros-Software/premake-core,tvandijck/premake-core,dcourtois/premake-core,jsfdez/premake-core,bravnsgaard/premake-core,kankaristo/premake-core,felipeprov/premake-core,tvandijck/premake-core,bravnsgaard/premake-core,jstewart-amd/premake-core,lizh06/premake-core,dcourtois/premake-core,TurkeyMan/premake-core,starkos/premake-core,mendsley/premake-core,premake/premake-core,felipeprov/premake-core,resetnow/premake-core,saberhawk/premake-core,TurkeyMan/premake-core
a5a6cf818a2a5741c6fae7b3081e1e20f3ec0a1b
mod_auth_ldap/mod_auth_ldap.lua
mod_auth_ldap/mod_auth_ldap.lua
-- mod_auth_ldap local new_sasl = require "util.sasl".new; local lualdap = require "lualdap"; local function ldap_filter_escape(s) return (s:gsub("[\\*\\(\\)\\\\%z]", function(c) return ("\\%02x"):format(c:byte()) end)); end -- Config options local ldap_server = module:get_option_string("ldap_server", "localhost"); local ldap_rootdn = module:get_option_string("ldap_rootdn", ""); local ldap_password = module:get_option_string("ldap_password", ""); local ldap_tls = module:get_option_boolean("ldap_tls"); local ldap_scope = module:get_option_string("ldap_scope", "onelevel"); local ldap_filter = module:get_option_string("ldap_filter", "(uid=$user)"):gsub("%%s", "$user", 1); local ldap_base = assert(module:get_option_string("ldap_base"), "ldap_base is a required option for ldap"); local ldap_mode = module:get_option_string("ldap_mode", "getpasswd"); local host = ldap_filter_escape(module:get_option_string("realm", module.host)); -- Initiate connection local ld = assert(lualdap.open_simple(ldap_server, ldap_rootdn, ldap_password, ldap_tls)); module.unload = function() ld:close(); end local function get_user(username) module:log("debug", "get_user(%q)", username); return ld:search({ base = ldap_base; scope = ldap_scope; filter = ldap_filter:gsub("%$(%a+)", { user = ldap_filter_escape(username); host = host; }); })(); end local provider = {}; function provider.create_user(username, password) return nil, "Account creation not available with LDAP."; end function provider.user_exists(username) return not not get_user(username); end function provider.set_password(username, password) local dn, attr = get_user(username); if not dn then return nil, attr end if attr.userPassword == password then return true end return ld:modify(dn, { '=', userPassword = password })(); end if ldap_mode == "getpasswd" then function provider.get_password(username) local dn, attr = get_user(username); if dn and attr then return attr.userPassword; end end function provider.test_password(username, password) return provider.get_password(username) == password; end function provider.get_sasl_handler() return new_sasl(module.host, { plain = function(sasl, username) local password = provider.get_password(username); if not password then return "", nil; end return password, true; end }); end elseif ldap_mode == "bind" then local function test_password(userdn, password) return not not lualdap.open_simple(ldap_server, userdn, password, ldap_tls); end function provider.test_password(username, password) local dn = get_user(username); if not dn then return end return test_password(dn, password) end function provider.get_sasl_handler() return new_sasl(module.host, { plain_test = function(sasl, username, password) return provider.test_password(username, password), true; end }); end else module:log("error", "Unsupported ldap_mode %s", tostring(ldap_mode)); end module:provides("auth", provider);
-- mod_auth_ldap local new_sasl = require "util.sasl".new; local lualdap = require "lualdap"; local function ldap_filter_escape(s) return (s:gsub("[\\*\\(\\)\\\\%z]", function(c) return ("\\%02x"):format(c:byte()) end)); end -- Config options local ldap_server = module:get_option_string("ldap_server", "localhost"); local ldap_rootdn = module:get_option_string("ldap_rootdn", ""); local ldap_password = module:get_option_string("ldap_password", ""); local ldap_tls = module:get_option_boolean("ldap_tls"); local ldap_scope = module:get_option_string("ldap_scope", "onelevel"); local ldap_filter = module:get_option_string("ldap_filter", "(uid=$user)"):gsub("%%s", "$user", 1); local ldap_base = assert(module:get_option_string("ldap_base"), "ldap_base is a required option for ldap"); local ldap_mode = module:get_option_string("ldap_mode", "getpasswd"); local host = ldap_filter_escape(module:get_option_string("realm", module.host)); -- Initiate connection local ld = assert(lualdap.open_simple(ldap_server, ldap_rootdn, ldap_password, ldap_tls)); module.unload = function() ld:close(); end local function get_user(username) module:log("debug", "get_user(%q)", username); for dn, attr in ld:search({ base = ldap_base; scope = ldap_scope; filter = ldap_filter:gsub("%$(%a+)", { user = ldap_filter_escape(username); host = host; }); }) do return dn, attr; end end local provider = {}; function provider.create_user(username, password) return nil, "Account creation not available with LDAP."; end function provider.user_exists(username) return not not get_user(username); end function provider.set_password(username, password) local dn, attr = get_user(username); if not dn then return nil, attr end if attr.userPassword == password then return true end return ld:modify(dn, { '=', userPassword = password })(); end if ldap_mode == "getpasswd" then function provider.get_password(username) local dn, attr = get_user(username); if dn and attr then return attr.userPassword; end end function provider.test_password(username, password) return provider.get_password(username) == password; end function provider.get_sasl_handler() return new_sasl(module.host, { plain = function(sasl, username) local password = provider.get_password(username); if not password then return "", nil; end return password, true; end }); end elseif ldap_mode == "bind" then local function test_password(userdn, password) return not not lualdap.open_simple(ldap_server, userdn, password, ldap_tls); end function provider.test_password(username, password) local dn = get_user(username); if not dn then return end return test_password(dn, password) end function provider.get_sasl_handler() return new_sasl(module.host, { plain_test = function(sasl, username, password) return provider.test_password(username, password), true; end }); end else module:log("error", "Unsupported ldap_mode %s", tostring(ldap_mode)); end module:provides("auth", provider);
mod_auth_ldap: Fix issue with some versions of LuaLDAP
mod_auth_ldap: Fix issue with some versions of LuaLDAP
Lua
mit
vince06fr/prosody-modules,jkprg/prosody-modules,olax/prosody-modules,mmusial/prosody-modules,Craige/prosody-modules,stephen322/prosody-modules,syntafin/prosody-modules,BurmistrovJ/prosody-modules,prosody-modules/import,mmusial/prosody-modules,heysion/prosody-modules,Craige/prosody-modules,olax/prosody-modules,vfedoroff/prosody-modules,stephen322/prosody-modules,stephen322/prosody-modules,NSAKEY/prosody-modules,cryptotoad/prosody-modules,prosody-modules/import,softer/prosody-modules,drdownload/prosody-modules,olax/prosody-modules,softer/prosody-modules,guilhem/prosody-modules,guilhem/prosody-modules,dhotson/prosody-modules,asdofindia/prosody-modules,1st8/prosody-modules,heysion/prosody-modules,heysion/prosody-modules,vfedoroff/prosody-modules,NSAKEY/prosody-modules,obelisk21/prosody-modules,asdofindia/prosody-modules,1st8/prosody-modules,apung/prosody-modules,mardraze/prosody-modules,dhotson/prosody-modules,drdownload/prosody-modules,dhotson/prosody-modules,jkprg/prosody-modules,vfedoroff/prosody-modules,NSAKEY/prosody-modules,asdofindia/prosody-modules,cryptotoad/prosody-modules,prosody-modules/import,BurmistrovJ/prosody-modules,vince06fr/prosody-modules,olax/prosody-modules,amenophis1er/prosody-modules,guilhem/prosody-modules,LanceJenkinZA/prosody-modules,guilhem/prosody-modules,syntafin/prosody-modules,mardraze/prosody-modules,Craige/prosody-modules,mardraze/prosody-modules,heysion/prosody-modules,1st8/prosody-modules,joewalker/prosody-modules,iamliqiang/prosody-modules,Craige/prosody-modules,cryptotoad/prosody-modules,either1/prosody-modules,dhotson/prosody-modules,brahmi2/prosody-modules,crunchuser/prosody-modules,prosody-modules/import,amenophis1er/prosody-modules,brahmi2/prosody-modules,crunchuser/prosody-modules,prosody-modules/import,iamliqiang/prosody-modules,syntafin/prosody-modules,jkprg/prosody-modules,drdownload/prosody-modules,crunchuser/prosody-modules,obelisk21/prosody-modules,obelisk21/prosody-modules,LanceJenkinZA/prosody-modules,softer/prosody-modules,mmusial/prosody-modules,apung/prosody-modules,iamliqiang/prosody-modules,cryptotoad/prosody-modules,vince06fr/prosody-modules,joewalker/prosody-modules,mardraze/prosody-modules,iamliqiang/prosody-modules,mmusial/prosody-modules,either1/prosody-modules,LanceJenkinZA/prosody-modules,apung/prosody-modules,vfedoroff/prosody-modules,vfedoroff/prosody-modules,mmusial/prosody-modules,amenophis1er/prosody-modules,either1/prosody-modules,mardraze/prosody-modules,obelisk21/prosody-modules,cryptotoad/prosody-modules,drdownload/prosody-modules,crunchuser/prosody-modules,heysion/prosody-modules,stephen322/prosody-modules,guilhem/prosody-modules,softer/prosody-modules,joewalker/prosody-modules,amenophis1er/prosody-modules,NSAKEY/prosody-modules,vince06fr/prosody-modules,jkprg/prosody-modules,syntafin/prosody-modules,crunchuser/prosody-modules,either1/prosody-modules,asdofindia/prosody-modules,BurmistrovJ/prosody-modules,stephen322/prosody-modules,asdofindia/prosody-modules,softer/prosody-modules,BurmistrovJ/prosody-modules,Craige/prosody-modules,brahmi2/prosody-modules,jkprg/prosody-modules,olax/prosody-modules,apung/prosody-modules,1st8/prosody-modules,drdownload/prosody-modules,BurmistrovJ/prosody-modules,syntafin/prosody-modules,joewalker/prosody-modules,brahmi2/prosody-modules,dhotson/prosody-modules,iamliqiang/prosody-modules,LanceJenkinZA/prosody-modules,LanceJenkinZA/prosody-modules,obelisk21/prosody-modules,vince06fr/prosody-modules,amenophis1er/prosody-modules,either1/prosody-modules,NSAKEY/prosody-modules,brahmi2/prosody-modules,1st8/prosody-modules,joewalker/prosody-modules,apung/prosody-modules
38181e259ca4ee907014595d2c3921d6f987d67b
modules/xcode/xcode_project.lua
modules/xcode/xcode_project.lua
--- -- xcode/xcode4_project.lua -- Generate an Xcode project file. -- Author Jason Perkins -- Modified by Mihai Sebea -- Copyright (c) 2009-2015 Jason Perkins and the Premake project --- local p = premake local m = p.modules.xcode local xcode = p.modules.xcode local project = p.project local config = p.config local fileconfig = p.fileconfig local tree = p.tree -- -- Create a tree corresponding to what is shown in the Xcode project browser -- pane, with nodes for files and folders, resources, frameworks, and products. -- -- @param prj -- The project being generated. -- @returns -- A tree, loaded with metadata, which mirrors Xcode's view of the project. -- function xcode.buildprjtree(prj) local tr = project.getsourcetree(prj, nil , false) tr.project = prj -- create a list of build configurations and assign IDs tr.configs = {} for cfg in project.eachconfig(prj) do cfg.xcode = {} cfg.xcode.targetid = xcode.newid(prj.xcode.projectnode.name, cfg.buildcfg, "target") cfg.xcode.projectid = xcode.newid(tr.name, cfg.buildcfg) table.insert(tr.configs, cfg) end -- convert localized resources from their filesystem layout (English.lproj/MainMenu.xib) -- to Xcode's display layout (MainMenu.xib/English). tree.traverse(tr, { onbranch = function(node) if path.getextension(node.name) == ".lproj" then local lang = path.getbasename(node.name) -- "English", "French", etc. -- create a new language group for each file it contains for _, filenode in ipairs(node.children) do local grpnode = node.parent.children[filenode.name] if not grpnode then grpnode = tree.insert(node.parent, tree.new(filenode.name)) grpnode.kind = "vgroup" end -- convert the file node to a language node and add to the group filenode.name = path.getbasename(lang) tree.insert(grpnode, filenode) end -- remove this directory from the tree tree.remove(node) end end }) -- the special folder "Frameworks" lists all linked frameworks tr.frameworks = tree.new("Frameworks") for cfg in project.eachconfig(prj) do for _, link in ipairs(config.getlinks(cfg, "system", "fullpath")) do local name = path.getname(link) if xcode.isframework(name) and not tr.frameworks.children[name] then node = tree.insert(tr.frameworks, tree.new(name)) node.path = link end end end -- only add it to the tree if there are frameworks to link if #tr.frameworks.children > 0 then tree.insert(tr, tr.frameworks) end -- the special folder "Products" holds the target produced by the project; this -- is populated below tr.products = tree.insert(tr, tree.new("Products")) -- the special folder "Projects" lists sibling project dependencies tr.projects = tree.new("Projects") for _, dep in ipairs(project.getdependencies(prj, "sibling", "object")) do -- create a child node for the dependency's xcodeproj local xcpath = xcode.getxcodeprojname(dep) local xcnode = tree.insert(tr.projects, tree.new(path.getname(xcpath))) xcnode.path = xcpath xcnode.project = dep xcnode.productgroupid = xcode.newid(xcnode.name, "prodgrp") xcnode.productproxyid = xcode.newid(xcnode.name, "prodprox") xcnode.targetproxyid = xcode.newid(xcnode.name, "targprox") xcnode.targetdependid = xcode.newid(xcnode.name, "targdep") -- create a grandchild node for the dependency's link target local lprj = premake.workspace.findproject(prj.workspace, dep.name) local cfg = project.findClosestMatch(lprj, prj.configurations[1]) node = tree.insert(xcnode, tree.new(cfg.linktarget.name)) node.path = cfg.linktarget.fullpath node.cfg = cfg end if #tr.projects.children > 0 then tree.insert(tr, tr.projects) end -- Final setup tree.traverse(tr, { onnode = function(node) -- assign IDs to every node in the tree node.id = xcode.newid(node.name, nil, node.path) node.isResource = xcode.isItemResource(prj, node) -- assign build IDs to buildable files if xcode.getbuildcategory(node) then node.buildid = xcode.newid(node.name, "build", node.path) end -- remember key files that are needed elsewhere if string.endswith(node.name, "Info.plist") then tr.infoplist = node end end }, true) -- Plug in the product node into the Products folder in the tree. The node -- was built in xcode.prepareWorkspace() in xcode_common.lua; it contains IDs -- that are necessary for inter-project dependencies node = tree.insert(tr.products, prj.xcode.projectnode) node.kind = "product" node.path = node.cfg.buildtarget.fullpath node.cfgsection = xcode.newid(node.name, "cfg") node.resstageid = xcode.newid(node.name, "rez") node.sourcesid = xcode.newid(node.name, "src") node.fxstageid = xcode.newid(node.name, "fxs") return tr end --- -- Generate an Xcode .xcodeproj for a Premake project. --- m.elements.project = function(prj) return { m.header, } end function m.generateProject(prj) local tr = xcode.buildprjtree(prj) p.callArray(m.elements.project, prj) xcode.PBXBuildFile(tr) xcode.PBXContainerItemProxy(tr) xcode.PBXFileReference(tr) xcode.PBXFrameworksBuildPhase(tr) xcode.PBXGroup(tr) xcode.PBXNativeTarget(tr) xcode.PBXProject(tr) xcode.PBXReferenceProxy(tr) xcode.PBXResourcesBuildPhase(tr) xcode.PBXShellScriptBuildPhase(tr) xcode.PBXSourcesBuildPhase(tr) xcode.PBXTargetDependency(tr) xcode.PBXVariantGroup(tr) xcode.XCBuildConfiguration(tr) xcode.XCBuildConfigurationList(tr) xcode.footer(prj) end function m.header(prj) p.w('// !$*UTF8*$!') p.push('{') p.w('archiveVersion = 1;') p.w('classes = {') p.w('};') p.w('objectVersion = 46;') p.push('objects = {') p.w() end function xcode.footer(prj) p.pop('};') p.w('rootObject = 08FB7793FE84155DC02AAC07 /* Project object */;') p.pop('}') end
--- -- xcode/xcode4_project.lua -- Generate an Xcode project file. -- Author Jason Perkins -- Modified by Mihai Sebea -- Copyright (c) 2009-2015 Jason Perkins and the Premake project --- local p = premake local m = p.modules.xcode local xcode = p.modules.xcode local project = p.project local config = p.config local fileconfig = p.fileconfig local tree = p.tree -- -- Create a tree corresponding to what is shown in the Xcode project browser -- pane, with nodes for files and folders, resources, frameworks, and products. -- -- @param prj -- The project being generated. -- @returns -- A tree, loaded with metadata, which mirrors Xcode's view of the project. -- function xcode.buildprjtree(prj) local tr = project.getsourcetree(prj, nil , false) tr.project = prj -- create a list of build configurations and assign IDs tr.configs = {} for cfg in project.eachconfig(prj) do cfg.xcode = {} cfg.xcode.targetid = xcode.newid(prj.xcode.projectnode.name, cfg.buildcfg, "target") cfg.xcode.projectid = xcode.newid(tr.name, cfg.buildcfg) table.insert(tr.configs, cfg) end -- convert localized resources from their filesystem layout (English.lproj/MainMenu.xib) -- to Xcode's display layout (MainMenu.xib/English). tree.traverse(tr, { onbranch = function(node) if path.getextension(node.name) == ".lproj" then local lang = path.getbasename(node.name) -- "English", "French", etc. -- create a new language group for each file it contains for _, filenode in ipairs(node.children) do local grpnode = node.parent.children[filenode.name] if not grpnode then grpnode = tree.insert(node.parent, tree.new(filenode.name)) grpnode.kind = "vgroup" end -- convert the file node to a language node and add to the group filenode.name = path.getbasename(lang) tree.insert(grpnode, filenode) end -- remove this directory from the tree tree.remove(node) end end }) -- the special folder "Frameworks" lists all linked frameworks tr.frameworks = tree.new("Frameworks") for cfg in project.eachconfig(prj) do for _, link in ipairs(config.getlinks(cfg, "system", "fullpath")) do local name = path.getname(link) if xcode.isframework(name) and not tr.frameworks.children[name] then node = tree.insert(tr.frameworks, tree.new(name)) node.path = link end end end -- only add it to the tree if there are frameworks to link if #tr.frameworks.children > 0 then tree.insert(tr, tr.frameworks) end -- the special folder "Products" holds the target produced by the project; this -- is populated below tr.products = tree.insert(tr, tree.new("Products")) -- the special folder "Projects" lists sibling project dependencies tr.projects = tree.new("Projects") for _, dep in ipairs(project.getdependencies(prj)) do -- create a child node for the dependency's xcodeproj local xcpath = xcode.getxcodeprojname(dep) local xcnode = tree.insert(tr.projects, tree.new(path.getname(xcpath))) xcnode.path = xcpath xcnode.project = dep xcnode.productgroupid = xcode.newid(xcnode.name, "prodgrp") xcnode.productproxyid = xcode.newid(xcnode.name, "prodprox") xcnode.targetproxyid = xcode.newid(xcnode.name, "targprox") xcnode.targetdependid = xcode.newid(xcnode.name, "targdep") -- create a grandchild node for the dependency's link target local lprj = premake.workspace.findproject(prj.workspace, dep.name) local cfg = project.findClosestMatch(lprj, prj.configurations[1]) node = tree.insert(xcnode, tree.new(cfg.linktarget.name)) node.path = cfg.linktarget.fullpath node.cfg = cfg -- don't link the dependency if it's a dependency only for _, deponly in ipairs(project.getdependencies(prj, "dependOnly")) do if dep == deponly then node.nobuild = true break end end end if #tr.projects.children > 0 then tree.insert(tr, tr.projects) end -- Final setup tree.traverse(tr, { onnode = function(node) -- assign IDs to every node in the tree node.id = xcode.newid(node.name, nil, node.path) node.isResource = xcode.isItemResource(prj, node) -- assign build IDs to buildable files if xcode.getbuildcategory(node) and not node.nobuild then node.buildid = xcode.newid(node.name, "build", node.path) end -- remember key files that are needed elsewhere if string.endswith(node.name, "Info.plist") then tr.infoplist = node end end }, true) -- Plug in the product node into the Products folder in the tree. The node -- was built in xcode.prepareWorkspace() in xcode_common.lua; it contains IDs -- that are necessary for inter-project dependencies node = tree.insert(tr.products, prj.xcode.projectnode) node.kind = "product" node.path = node.cfg.buildtarget.fullpath node.cfgsection = xcode.newid(node.name, "cfg") node.resstageid = xcode.newid(node.name, "rez") node.sourcesid = xcode.newid(node.name, "src") node.fxstageid = xcode.newid(node.name, "fxs") return tr end --- -- Generate an Xcode .xcodeproj for a Premake project. --- m.elements.project = function(prj) return { m.header, } end function m.generateProject(prj) local tr = xcode.buildprjtree(prj) p.callArray(m.elements.project, prj) xcode.PBXBuildFile(tr) xcode.PBXContainerItemProxy(tr) xcode.PBXFileReference(tr) xcode.PBXFrameworksBuildPhase(tr) xcode.PBXGroup(tr) xcode.PBXNativeTarget(tr) xcode.PBXProject(tr) xcode.PBXReferenceProxy(tr) xcode.PBXResourcesBuildPhase(tr) xcode.PBXShellScriptBuildPhase(tr) xcode.PBXSourcesBuildPhase(tr) xcode.PBXTargetDependency(tr) xcode.PBXVariantGroup(tr) xcode.XCBuildConfiguration(tr) xcode.XCBuildConfigurationList(tr) xcode.footer(prj) end function m.header(prj) p.w('// !$*UTF8*$!') p.push('{') p.w('archiveVersion = 1;') p.w('classes = {') p.w('};') p.w('objectVersion = 46;') p.push('objects = {') p.w() end function xcode.footer(prj) p.pop('};') p.w('rootObject = 08FB7793FE84155DC02AAC07 /* Project object */;') p.pop('}') end
Fixed an issue where libraries listed under "dependson" would be linked into the executable in Xcode.
Fixed an issue where libraries listed under "dependson" would be linked into the executable in Xcode.
Lua
bsd-3-clause
mendsley/premake-core,sleepingwit/premake-core,TurkeyMan/premake-core,bravnsgaard/premake-core,mendsley/premake-core,noresources/premake-core,aleksijuvani/premake-core,noresources/premake-core,Blizzard/premake-core,LORgames/premake-core,soundsrc/premake-core,Zefiros-Software/premake-core,jstewart-amd/premake-core,soundsrc/premake-core,premake/premake-core,soundsrc/premake-core,starkos/premake-core,jstewart-amd/premake-core,noresources/premake-core,noresources/premake-core,Blizzard/premake-core,dcourtois/premake-core,starkos/premake-core,bravnsgaard/premake-core,aleksijuvani/premake-core,mendsley/premake-core,Blizzard/premake-core,sleepingwit/premake-core,premake/premake-core,premake/premake-core,tvandijck/premake-core,mandersan/premake-core,noresources/premake-core,resetnow/premake-core,sleepingwit/premake-core,LORgames/premake-core,soundsrc/premake-core,Blizzard/premake-core,resetnow/premake-core,dcourtois/premake-core,resetnow/premake-core,premake/premake-core,LORgames/premake-core,tvandijck/premake-core,aleksijuvani/premake-core,starkos/premake-core,Blizzard/premake-core,mandersan/premake-core,dcourtois/premake-core,premake/premake-core,premake/premake-core,mandersan/premake-core,starkos/premake-core,TurkeyMan/premake-core,mendsley/premake-core,tvandijck/premake-core,aleksijuvani/premake-core,soundsrc/premake-core,mandersan/premake-core,mendsley/premake-core,tvandijck/premake-core,resetnow/premake-core,Zefiros-Software/premake-core,dcourtois/premake-core,bravnsgaard/premake-core,Zefiros-Software/premake-core,starkos/premake-core,dcourtois/premake-core,Zefiros-Software/premake-core,jstewart-amd/premake-core,tvandijck/premake-core,jstewart-amd/premake-core,jstewart-amd/premake-core,mandersan/premake-core,noresources/premake-core,premake/premake-core,sleepingwit/premake-core,LORgames/premake-core,LORgames/premake-core,dcourtois/premake-core,resetnow/premake-core,Zefiros-Software/premake-core,noresources/premake-core,TurkeyMan/premake-core,starkos/premake-core,dcourtois/premake-core,starkos/premake-core,Blizzard/premake-core,TurkeyMan/premake-core,bravnsgaard/premake-core,bravnsgaard/premake-core,sleepingwit/premake-core,aleksijuvani/premake-core,TurkeyMan/premake-core
799401c0374a69671c3f2285704bd0c28e51d804
utils/speech.lua
utils/speech.lua
-- -- fn - l -- toggle listener -- -- hold down fn, even when on, or command is ignored (minimizes false positives in noisy -- environments.) -- local module, placeholder = {}, {} local speech = require("hs.speech") local listener = speech.listener local fnutils = require("hs.fnutils") local log = require("hs.logger").new("mySpeech","warning") local settings = require("hs.settings") local eventtap = require("hs.eventtap") local hotkey = require("hs.hotkey") local commands = {} local title = "Hammerspoon" local listenerCallback = function(listenerObj, text) if eventtap.checkKeyboardModifiers().fn then if commands[text] then commands[text]() else log.wf("Unrecognized command '%s' received", text) end else log.vf("FN not depressed -- ignoring command '%s'", text) end end local updateCommands = function() if module.recognizer then local cmdList = {} for k,v in fnutils.sortByKeys(commands) do table.insert(cmdList, k) end module.recognizer:commands(cmdList) end end module.log = log module.commands = commands module.add = function(text, func) assert(type(text) == "string", "command must be a string") assert(type(func) == "function", "action must be a function") if commands[text] then error("Command '"..text.."' is already registered", 2) end commands[text] = func updateCommands() return placeholder end module.remove = function(text) assert(type(text) == "string", "command must be a string") if commands[text] then commands[text] = nil else error("Command '"..text.."' is not registered", 2) end updateCommands() return placeholder end module.start = function() updateCommands() -- should be current, but just in case module.recognizer:title(title):start() settings.set("_asm.listener", true) return placeholder end module.stop = function() module.recognizer:title("Disabled: "..title):stop() return placeholder end module.isListening = function() if module.recognizer then return module.recognizer:isListening() else return nil end end module.disableCompletely = function() if module.recognizer then module.recognizer:delete() end module.recognizer = nil setmetatable(placeholder, nil) module.hotkey:disable() module.listenLabel = module.listenLabel:delete() settings.set("_asm.listener", false) end module.init = function() if module.recognizer then error("Listener already initialized", 2) end module.recognizer = listener.new(title):setCallback(listenerCallback) :foregroundOnly(false) :blocksOtherRecognizers(false) module.hotkey = hotkey.bind({}, "l", function() if eventtap.checkKeyboardModifiers().fn then if module.isListening() then module.listenLabel = module.listenLabel:delete() module.stop() else local screen = require("hs.screen").primaryScreen():fullFrame() module.listenLabel = require("hs.drawing").text({ x = screen.x + 5, y = screen.y + screen.h - 21, h = 14, w = 150 }, require("hs.styledtext").new("Hammerspoon Listening...", { font = { name = "Menlo-Italic", size = 10 }, color = { list = "Crayons", name = "Sky" }, paragraphStyle = { lineBreak = "clip" } })):setBehaviorByLabels{"canJoinAllSpaces"} :setLevel("popUpMenu") :show() module.start() end else module.hotkey:disable() eventtap.keyStroke({}, "l") module.hotkey:enable() end end) return setmetatable(placeholder, { __index = function(_, k) if module[k] then if type(module[k]) ~= "function" then return module[k] end return function(_, ...) return module[k](...) end else return nil end end, __tostring = function(_) return module.recognizer:title() end, __pairs = function(_) return pairs(module) end, -- __gc = module.disableCompletely }) end placeholder.init = function() return module.init() end module.add("Open Hammerspoon Console", hs.openConsole) module.add("Open System Console", function() require("hs.application").launchOrFocus("Console") end) module.add("Open Editor", function() require("hs.application").launchOrFocus("BBEdit") end) module.add("Open Browser", function() require("hs.application").launchOrFocus("Safari") end) module.add("Open SmartGit", function() require("hs.application").launchOrFocus("SmartGit") end) module.add("Open Mail", function() require("hs.application").launchOrFocus("Mail") end) module.add("Open Terminal Application", function() require("hs.application").launchOrFocus("Terminal") end) module.add("Re-Load Hammerspoon", hs.reload) module.add("Re-Launch Hammerspoon", _asm.relaunch) -- module.add("Stop Listening", module.stop) module.add("Go away for a while", module.disableCompletely) -- list doesn't appear until its started at least once; since we want to minimize false -- positives, start disabled, but fill list in case Dictation Commands window is open. if settings.get("_asm.listener") then placeholder.init():start():stop() end return placeholder
-- -- fn - l -- toggle listener -- -- hold down fn, even when on, or command is ignored (minimizes false positives in noisy -- environments.) -- local module, placeholder = {}, {} local speech = require("hs.speech") local listener = speech.listener local fnutils = require("hs.fnutils") local log = require("hs.logger").new("mySpeech","warning") local settings = require("hs.settings") local eventtap = require("hs.eventtap") local hotkey = require("hs.hotkey") local commands = {} local title = "Hammerspoon" local listenerCallback = function(listenerObj, text) if eventtap.checkKeyboardModifiers().fn then if commands[text] then commands[text]() else log.wf("Unrecognized command '%s' received", text) end else log.vf("FN not depressed -- ignoring command '%s'", text) end end local updateCommands = function() if module.recognizer then local cmdList = {} for k,v in fnutils.sortByKeys(commands) do table.insert(cmdList, k) end module.recognizer:commands(cmdList) end end module.log = log module.commands = commands module.add = function(text, func) assert(type(text) == "string", "command must be a string") assert(type(func) == "function", "action must be a function") if commands[text] then error("Command '"..text.."' is already registered", 2) end commands[text] = func updateCommands() return placeholder end module.remove = function(text) assert(type(text) == "string", "command must be a string") if commands[text] then commands[text] = nil else error("Command '"..text.."' is not registered", 2) end updateCommands() return placeholder end module.start = function() updateCommands() -- should be current, but just in case module.recognizer:title(title):start() settings.set("_asm.listener", true) return placeholder end module.stop = function() module.recognizer:title("Disabled: "..title):stop() return placeholder end module.isListening = function() if module.recognizer then return module.recognizer:isListening() else return nil end end module.disableCompletely = function() if module.recognizer then module.recognizer:delete() end module.recognizer = nil setmetatable(placeholder, nil) module.hotkey:disable() if (module.listenLabel) then module.listenLabel = module.listenLabel:delete() end settings.set("_asm.listener", false) end module.init = function() if module.recognizer then error("Listener already initialized", 2) end module.recognizer = listener.new(title):setCallback(listenerCallback) :foregroundOnly(false) :blocksOtherRecognizers(false) module.hotkey = hotkey.bind({}, "l", function() if eventtap.checkKeyboardModifiers().fn then if module.isListening() then module.listenLabel = module.listenLabel:delete() module.stop() else local screen = require("hs.screen").primaryScreen():fullFrame() module.listenLabel = require("hs.drawing").text({ x = screen.x + 5, y = screen.y + screen.h - 21, h = 14, w = 150 }, require("hs.styledtext").new("Hammerspoon Listening...", { font = { name = "Menlo-Italic", size = 10 }, color = { list = "Crayons", name = "Sky" }, paragraphStyle = { lineBreak = "clip" } })):setBehaviorByLabels{"canJoinAllSpaces"} :setLevel("popUpMenu") :show() module.start() end else module.hotkey:disable() eventtap.keyStroke({}, "l") module.hotkey:enable() end end) return setmetatable(placeholder, { __index = function(_, k) if module[k] then if type(module[k]) ~= "function" then return module[k] end return function(_, ...) return module[k](...) end else return nil end end, __tostring = function(_) return module.recognizer:title() end, __pairs = function(_) return pairs(module) end, -- __gc = module.disableCompletely }) end placeholder.init = function() return module.init() end module.add("Open Hammerspoon Console", hs.openConsole) module.add("Open System Console", function() require("hs.application").launchOrFocus("Console") end) module.add("Open Editor", function() require("hs.application").launchOrFocus("BBEdit") end) module.add("Open Browser", function() require("hs.application").launchOrFocus("Safari") end) module.add("Open SmartGit", function() require("hs.application").launchOrFocus("SmartGit") end) module.add("Open Mail", function() require("hs.application").launchOrFocus("Mail") end) module.add("Open Terminal Application", function() require("hs.application").launchOrFocus("Terminal") end) module.add("Re-Load Hammerspoon", hs.reload) module.add("Re-Launch Hammerspoon", _asm.relaunch) -- module.add("Stop Listening", module.stop) module.add("Go away for a while", module.disableCompletely) -- list doesn't appear until its started at least once; since we want to minimize false -- positives, start disabled, but fill list in case Dictation Commands window is open. if settings.get("_asm.listener") then placeholder.init():start():stop() end return placeholder
bug fix
bug fix
Lua
mit
asmagill/hammerspoon-config,asmagill/hammerspoon-config,asmagill/hammerspoon-config
ca51ab16c9c42565da6d4f7d18d1f06d7663df18
xmake.lua
xmake.lua
local modules = { Audio = { Deps = {"NazaraCore"}, Packages = {"dr_wav", "libsndfile", "minimp3"} }, Core = {}, Graphics = { Deps = {"NazaraRenderer"} }, Network = { Deps = {"NazaraCore"}, Custom = function() if is_plat("windows") then add_syslinks("ws2_32") end if is_plat("linux") then del_files("src/Nazara/Network/Posix/SocketPollerImpl.hpp") del_files("src/Nazara/Network/Posix/SocketPollerImpl.cpp") end end }, OpenGLRenderer = { Deps = {"NazaraRenderer"}, Custom = function() if is_plat("windows") then add_syslinks("gdi32", "user32") else del_files("src/Nazara/OpenGLRenderer/Wrapper/Win32/**.cpp") del_files("src/Nazara/OpenGLRenderer/Wrapper/WGL/**.cpp") end if not is_plat("linux") then del_files("src/Nazara/OpenGLRenderer/Wrapper/Linux/**.cpp") end end }, Physics2D = { Deps = {"NazaraUtility"}, Packages = {"chipmunk2d"} }, Physics3D = { Deps = {"NazaraUtility"}, Packages = {"newtondynamics"} }, Platform = { Deps = {"NazaraUtility"}, Packages = {"libsdl"}, Custom = function() if is_plat("windows") then add_defines("SDL_VIDEO_DRIVER_WINDOWS=1") elseif is_plat("linux") then add_defines("SDL_VIDEO_DRIVER_X11=1") add_defines("SDL_VIDEO_DRIVER_WAYLAND=1") elseif is_plat("macosx") then add_defines("SDL_VIDEO_DRIVER_COCOA=1") end end }, Renderer = { Deps = {"NazaraPlatform", "NazaraShader"} }, Shader = { Deps = {"NazaraUtility"} }, Utility = { Deps = {"NazaraCore"}, Packages = {"freetype", "stb"} }, VulkanRenderer = { Deps = {"NazaraRenderer"}, Custom = function() add_defines("VK_NO_PROTOTYPES") if is_plat("windows") then add_defines("VK_USE_PLATFORM_WIN32_KHR") add_syslinks("user32") elseif is_plat("linux") then add_defines("VK_USE_PLATFORM_XLIB_KHR") add_defines("VK_USE_PLATFORM_WAYLAND_KHR") elseif is_plat("macosx") then add_defines("VK_USE_PLATFORM_MACOS_MVK") end end } } add_repositories("local-repo xmake-repo") add_requires("chipmunk2d", "dr_wav", "freetype", "libsndfile", "libsdl", "minimp3", "stb") add_requires("newtondynamics", { debug = is_plat("windows") and is_mode("debug") }) -- Newton doesn't like compiling in Debug on Linux set_project("NazaraEngine") add_rules("mode.debug", "mode.releasedbg") add_rules("plugin.vsxmake.autoupdate") add_rules("build_rendererplugins") if is_mode("debug") then add_rules("debug_suffix") end add_includedirs("include") add_sysincludedirs("thirdparty/include") set_languages("c89", "cxx17") set_rundir("./bin/$(os)_$(arch)_$(mode)") set_symbols("debug", "hidden") set_targetdir("./bin/$(os)_$(arch)_$(mode)") set_warnings("allextra") if is_mode("releasedbg") then set_fpmodels("fast") add_vectorexts("sse", "sse2", "sse3", "ssse3") end if is_plat("windows") then set_runtimes(is_mode("debug") and "MDd" or "MD") add_defines("_CRT_SECURE_NO_WARNINGS") add_cxxflags("/bigobj", "/permissive-", "/Zc:__cplusplus", "/Zc:referenceBinding", "/Zc:throwingNew") add_cxxflags("/FC") add_cxflags("/w44062") -- Enable warning: switch case not handled add_cxflags("/wd4251") -- Disable warning: class needs to have dll-interface to be used by clients of class blah blah blah end for name, module in pairs(modules) do target("Nazara" .. name) set_kind("shared") set_group("Modules") add_rules("embed_resources") if module.Deps then add_deps(module.Deps) end if module.Packages then add_packages(module.Packages) end add_defines("NAZARA_BUILD") add_defines("NAZARA_" .. name:upper() .. "_BUILD") if is_mode("debug") then add_defines("NAZARA_DEBUG") add_defines("NAZARA_" .. name:upper() .. "_DEBUG") end add_headerfiles("include/Nazara/" .. name .. "/**.hpp") add_headerfiles("include/Nazara/" .. name .. "/**.inl") add_headerfiles("src/Nazara/" .. name .. "/**.hpp") add_headerfiles("src/Nazara/" .. name .. "/**.inl") add_files("src/Nazara/" .. name .. "/**.cpp") add_includedirs("src") for _, filepath in pairs(os.files("src/Nazara/" .. name .. "/Resources/**|**.h")) do add_files(filepath, {rule="embed_resources"}) end if is_plat("windows") then del_files("src/Nazara/" .. name .. "/Posix/**.cpp") else del_files("src/Nazara/" .. name .. "/Win32/**.cpp") end if not is_plat("linux") then del_files("src/Nazara/" .. name .. "/Linux/**.cpp") end if module.Custom then module.Custom() end end includes("xmake/actions/*.lua") includes("tools/xmake.lua") includes("tests/xmake.lua") includes("plugins/*/xmake.lua") includes("examples/*/xmake.lua") -- Adds -d as a debug suffix rule("debug_suffix") on_load(function (target) if target:kind() ~= "binary" then target:set("basename", target:basename() .. "-d") end end) -- Builds renderer plugins if linked to NazaraRenderer rule("build_rendererplugins") after_load(function (target) if target:kind() == "binary" and target:dep("NazaraRenderer") then for name, _ in pairs(modules) do local depName = "Nazara" .. name if name:match("^.+Renderer$") and target:dep(depName) == nil then -- don't overwrite dependency target:add("deps", depName, {inherit = false}) end end end end) -- Turns resources into includables headers rule("embed_resources") before_build(function (target, opt) import("core.base.option") import("private.utils.progress") local function GenerateEmbedHeader(filepath, targetpath) local bufferSize = 1024 * 1024 progress.show(opt.progress, "${color.build.object}embedding %s", filepath) local resource = assert(io.open(filepath, "rb")) local targetFile = assert(io.open(targetpath, "w+")) local resourceSize = resource:size() local remainingSize = resourceSize local headerSize = 0 while remainingSize > 0 do local readSize = math.min(remainingSize, bufferSize) local data = resource:read(readSize) remainingSize = remainingSize - readSize local headerContentTable = {} for i = 1, #data do table.insert(headerContentTable, string.format("%d,", data:byte(i))) end local content = table.concat(headerContentTable) headerSize = headerSize + #content targetFile:write(content) end resource:close() targetFile:close() end for _, sourcebatch in pairs(target:sourcebatches()) do if sourcebatch.rulename == "embed_resources" then for _, sourcefile in ipairs(sourcebatch.sourcefiles) do local targetpath = sourcefile .. ".h" if option.get("rebuild") or os.mtime(sourcefile) >= os.mtime(targetpath) then GenerateEmbedHeader(sourcefile, targetpath) end end end end end)
local modules = { Audio = { Deps = {"NazaraCore"}, Packages = {"dr_wav", "libsndfile", "minimp3"} }, Core = { Custom = function () if is_plat("linux") then add_syslinks("dl", "pthread") end end }, Graphics = { Deps = {"NazaraRenderer"} }, Network = { Deps = {"NazaraCore"}, Custom = function() if is_plat("windows") then add_syslinks("ws2_32") end if is_plat("linux") then del_files("src/Nazara/Network/Posix/SocketPollerImpl.hpp") del_files("src/Nazara/Network/Posix/SocketPollerImpl.cpp") end end }, OpenGLRenderer = { Deps = {"NazaraRenderer"}, Custom = function() if is_plat("windows") then add_syslinks("gdi32", "user32") else del_files("src/Nazara/OpenGLRenderer/Wrapper/Win32/**.cpp") del_files("src/Nazara/OpenGLRenderer/Wrapper/WGL/**.cpp") end if not is_plat("linux") then del_files("src/Nazara/OpenGLRenderer/Wrapper/Linux/**.cpp") end end }, Physics2D = { Deps = {"NazaraUtility"}, Packages = {"chipmunk2d"} }, Physics3D = { Deps = {"NazaraUtility"}, Packages = {"newtondynamics"} }, Platform = { Deps = {"NazaraUtility"}, Packages = {"libsdl"}, Custom = function() if is_plat("windows") then add_defines("SDL_VIDEO_DRIVER_WINDOWS=1") elseif is_plat("linux") then add_defines("SDL_VIDEO_DRIVER_X11=1") add_defines("SDL_VIDEO_DRIVER_WAYLAND=1") elseif is_plat("macosx") then add_defines("SDL_VIDEO_DRIVER_COCOA=1") end end }, Renderer = { Deps = {"NazaraPlatform", "NazaraShader"} }, Shader = { Deps = {"NazaraUtility"} }, Utility = { Deps = {"NazaraCore"}, Packages = {"freetype", "stb"} }, VulkanRenderer = { Deps = {"NazaraRenderer"}, Custom = function() add_defines("VK_NO_PROTOTYPES") if is_plat("windows") then add_defines("VK_USE_PLATFORM_WIN32_KHR") add_syslinks("user32") elseif is_plat("linux") then add_defines("VK_USE_PLATFORM_XLIB_KHR") add_defines("VK_USE_PLATFORM_WAYLAND_KHR") elseif is_plat("macosx") then add_defines("VK_USE_PLATFORM_MACOS_MVK") end end } } add_repositories("local-repo xmake-repo") add_requires("chipmunk2d", "dr_wav", "freetype", "libsndfile", "libsdl", "minimp3", "stb") add_requires("newtondynamics", { debug = is_plat("windows") and is_mode("debug") }) -- Newton doesn't like compiling in Debug on Linux set_project("NazaraEngine") add_rules("mode.debug", "mode.releasedbg") add_rules("plugin.vsxmake.autoupdate") add_rules("build_rendererplugins") if is_mode("debug") then add_rules("debug_suffix") end add_includedirs("include") add_sysincludedirs("thirdparty/include") set_languages("c89", "cxx17") set_rundir("./bin/$(os)_$(arch)_$(mode)") set_symbols("debug", "hidden") set_targetdir("./bin/$(os)_$(arch)_$(mode)") set_warnings("allextra") if is_mode("releasedbg") then set_fpmodels("fast") add_vectorexts("sse", "sse2", "sse3", "ssse3") end if is_plat("windows") then set_runtimes(is_mode("debug") and "MDd" or "MD") add_defines("_CRT_SECURE_NO_WARNINGS") add_cxxflags("/bigobj", "/permissive-", "/Zc:__cplusplus", "/Zc:referenceBinding", "/Zc:throwingNew") add_cxxflags("/FC") add_cxflags("/w44062") -- Enable warning: switch case not handled add_cxflags("/wd4251") -- Disable warning: class needs to have dll-interface to be used by clients of class blah blah blah end for name, module in pairs(modules) do target("Nazara" .. name) set_kind("shared") set_group("Modules") add_rules("embed_resources") if module.Deps then add_deps(module.Deps) end if module.Packages then add_packages(module.Packages) end add_defines("NAZARA_BUILD") add_defines("NAZARA_" .. name:upper() .. "_BUILD") if is_mode("debug") then add_defines("NAZARA_DEBUG") add_defines("NAZARA_" .. name:upper() .. "_DEBUG") end add_headerfiles("include/Nazara/" .. name .. "/**.hpp") add_headerfiles("include/Nazara/" .. name .. "/**.inl") add_headerfiles("src/Nazara/" .. name .. "/**.hpp") add_headerfiles("src/Nazara/" .. name .. "/**.inl") add_files("src/Nazara/" .. name .. "/**.cpp") add_includedirs("src") for _, filepath in pairs(os.files("src/Nazara/" .. name .. "/Resources/**|**.h")) do add_files(filepath, {rule="embed_resources"}) end if is_plat("windows") then del_files("src/Nazara/" .. name .. "/Posix/**.cpp") else del_files("src/Nazara/" .. name .. "/Win32/**.cpp") end if not is_plat("linux") then del_files("src/Nazara/" .. name .. "/Linux/**.cpp") end if module.Custom then module.Custom() end end includes("xmake/actions/*.lua") includes("tools/xmake.lua") includes("tests/xmake.lua") includes("plugins/*/xmake.lua") includes("examples/*/xmake.lua") -- Adds -d as a debug suffix rule("debug_suffix") on_load(function (target) if target:kind() ~= "binary" then target:set("basename", target:basename() .. "-d") end end) -- Builds renderer plugins if linked to NazaraRenderer rule("build_rendererplugins") after_load(function (target) if target:kind() == "binary" and target:dep("NazaraRenderer") then for name, _ in pairs(modules) do local depName = "Nazara" .. name if name:match("^.+Renderer$") and target:dep(depName) == nil then -- don't overwrite dependency target:add("deps", depName, {inherit = false}) end end end end) -- Turns resources into includables headers rule("embed_resources") before_build(function (target, opt) import("core.base.option") import("private.utils.progress") local function GenerateEmbedHeader(filepath, targetpath) local bufferSize = 1024 * 1024 progress.show(opt.progress, "${color.build.object}embedding %s", filepath) local resource = assert(io.open(filepath, "rb")) local targetFile = assert(io.open(targetpath, "w+")) local resourceSize = resource:size() local remainingSize = resourceSize local headerSize = 0 while remainingSize > 0 do local readSize = math.min(remainingSize, bufferSize) local data = resource:read(readSize) remainingSize = remainingSize - readSize local headerContentTable = {} for i = 1, #data do table.insert(headerContentTable, string.format("%d,", data:byte(i))) end local content = table.concat(headerContentTable) headerSize = headerSize + #content targetFile:write(content) end resource:close() targetFile:close() end for _, sourcebatch in pairs(target:sourcebatches()) do if sourcebatch.rulename == "embed_resources" then for _, sourcefile in ipairs(sourcebatch.sourcefiles) do local targetpath = sourcefile .. ".h" if option.get("rebuild") or os.mtime(sourcefile) >= os.mtime(targetpath) then GenerateEmbedHeader(sourcefile, targetpath) end end end end end)
XMake: Add dl and pthread links (fixes Linux compilation)
XMake: Add dl and pthread links (fixes Linux compilation)
Lua
mit
DigitalPulseSoftware/NazaraEngine
eb62689620a93025483343dffd53c858fae31774
kernel/turtle/ttl2flr.lua
kernel/turtle/ttl2flr.lua
-- convert turtle ontologies to F-Logic/Flora-2 local ttl2flr = {} local turtleparse = require("turtleparse") local __dump = require("pl.pretty").dump local function __printPrefix(p) print(string.format(":- iriprefix{%s='%s'}.", p.name, p.uri)) end -- convert a resource (UriRef, Qname) string value for Flora-2 local function __rsrc2str(r) if r.type == "UriRef" then return string.format("\"%s\"^^\\iri", r.uri) elseif r.type == "Qname" then local n = r.name -- dcterms has "dcterms:ISO639-2" if n:find("-") then -- TODO make this more robustly handle forbidden chars in F-atoms n = "'" .. n .. "'" end return string.format("%s#%s", r.prefix, n) else __dump(r) error("Unknown resource") end end -- convert an object (resource or literal (TypedString)) to a string -- value for Flora-2 local function __obj2str(o) -- TODO need proper string processing if type(o) == "string" then return '"' .. o:sub('"', '\\"') .. '"' elseif r.type == "TypedString" then local t if r.datatype.type == "UriRef" then t = r.datatype.uri:gsub("http://www.w3.org/2001/XMLSchema", "xsd") elseif r.datatype.type == "Qname" then t = string.format("%s#%s", r.datatype.prefix, r.datatype.name) else __dump(r) error("Unknown datatype type") end return string.format("\"%s\"^^%s", r.value, t) else return __rsrc2str(o) end end if true then -- run script --local f = io.open("/home/jbalint/Dropbox/important/org/rdf/other/rdf.ttl", "r") local f = io.open("/home/jbalint/Dropbox/important/org/rdf/other/vcard.ttl", "r") local content = f:read("*all") f:close() local s = turtleparse.parse(content) __dump(s) for idx, el in ipairs(s) do if el.type == "Prefix" then __printPrefix(el) elseif el.subject then -- a statement print("") local sub = __rsrc2str(el.subject) for idx2, pred in ipairs(el.preds) do local verb = pred.verb for idx3, obj in ipairs(pred.objects) do if pred.verb == "a" then print(string.format("%s:%s.", sub, __rsrc2str(obj))) else print(string.format("%s[%s -> %s].", sub, __rsrc2str(verb), __obj2str(obj))) end end if pred.objects.preds then error("NESTED OBJECTS") end end end end end return ttl2flr
-- convert turtle ontologies to F-Logic/Flora-2 local ttl2flr = {} local turtleparse = require("turtleparse") local __dump = require("pl.pretty").dump -- no default prefix support in Flora-2, so we save it here and -- substitute it upon encountering it local __DEFAULT_PREFIX_URI local function __printPrefix(p) if p.name == "" then __DEFAULT_PREFIX_URI = p.uri else print(string.format(":- iriprefix{%s='%s'}.", p.name, p.uri)) end end -- convert a resource (UriRef, Qname) string value for Flora-2 local function __rsrc2str(r) if r.type == "UriRef" then return string.format("\"%s\"^^\\iri", r.uri) elseif r.type == "Qname" then local n = r.name -- dcterms has "dcterms:ISO639-2" if n:find("-") then -- TODO make this more robustly handle forbidden chars in F-atoms n = "'" .. n .. "'" end if r.prefix == "" then assert(__DEFAULT_PREFIX_URI, "Default prefix encountered, but none defined") return string.format("\"%s%s\"^^\\iri", __DEFAULT_PREFIX_URI, n) end return string.format("%s#%s", r.prefix, n) else __dump(r) error("Unknown resource") end end -- convert an object (resource or literal (TypedString)) to a string -- value for Flora-2 local function __obj2str(o) -- TODO need proper string processing if type(o) == "string" then return '"' .. o:gsub('"', '\\"') .. '"' elseif o.type == "TypedString" then local t if o.datatype.type == "UriRef" then t = o.datatype.uri:gsub("http://www.w3.org/2001/XMLSchema", "xsd") elseif o.datatype.type == "Qname" then t = string.format("%s#%s", o.datatype.prefix, o.datatype.name) else __dump(o) error("Unknown datatype type") end return string.format("\"%s\"^^%s", o.value, t) elseif o.type == "Collection" then local strval = "{" for idx, v in ipairs(o.values) do local strv = __obj2str(v) if strval == "{" then strval = strval .. strv else strval = strval .. ", " .. strv end end return strval .. "}" else return __rsrc2str(o) end end if true then -- run script --local f = io.open("/home/jbalint/Dropbox/important/org/rdf/other/rdf.ttl", "r") local f = io.open("/home/jbalint/Dropbox/important/org/rdf/nepomuk/nie.ttl", "r") local content = f:read("*all") f:close() local s = turtleparse.parse(content) __dump(s) for idx, el in ipairs(s) do if el.type == "Prefix" then __printPrefix(el) elseif el.subject then -- a statement print("") local sub = __rsrc2str(el.subject) for idx2, pred in ipairs(el.preds) do local verb = pred.verb for idx3, obj in ipairs(pred.objects) do if verb == "a" then print(string.format("%s:%s.", sub, __rsrc2str(obj))) else print(string.format("%s[%s -> %s].", sub, __rsrc2str(verb), __obj2str(obj))) end end if pred.objects.preds then -- A bit more complicated to represent nested objects -- as we can't reference the skolem symbol from several -- statements local nested = "\\#" local preds = "[" for idx3, pred2 in ipairs(pred.objects.preds) do for idx4, obj in ipairs(pred2.objects) do if pred2.verb == "a" then nested = nested .. ":" .. __rsrc2str(obj) else local newpred = string.format("%s -> %s", __rsrc2str(pred2.verb), __obj2str(obj)) if preds == "[" then preds = preds .. newpred else preds = preds .. ", " .. newpred end end end end print(string.format("%s[%s -> %s%s].", sub, __rsrc2str(verb), nested, preds .. "]")) end end end end end return ttl2flr
turtle to flora: add default prefix expansion add support for nested objects via skolems and collections tested with 10+ popular ontologies
turtle to flora: add default prefix expansion add support for nested objects via skolems and collections tested with 10+ popular ontologies
Lua
mit
jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico,jbalint/banshee-sympatico
db666ed6a5589f50a8a80a9230fe09f06f8c4032
src/premake5.lua
src/premake5.lua
function setupReleaseConfiguration() buildoptions { "/GL", "/sdl-", "/Ot", "/GS-", "/arch:AVX2" } linkoptions { "/LTCG:incremental" } optimize "Speed" inlining "Auto" end function setupDebugConfiguration() buildoptions { "/sdl", "/arch:AVX2" } optimize "Off" inlining "Disabled" end function setupX64Platform() architecture "x86_64" defines "FD_PLATFORM_X64" callingconvention "FastCall" end vk_path = os.getenv("VULKAN_SDK"); if (vk_path == nil) then vk_path = os.getenv("VK_SDK_PATH") end if (vk_path == nil) then print("No vulkan sdk path. Set environment variable VULKAN_SDK or VK_SDK_PATH to the vulkan sdk directory") os.exit() end workspace("Frodo") location "../solution/" startproject "Sandbox" configurations { "Release-VK", "Debug-VK" } platforms { "x64" } defines "FD_LINUX" floatingpoint "Fast" intrinsics "on" if _TARGET_OS == "windows" then removedefines "FD_LINUX" defines { "FD_WINDOWS", "_CRT_NON_CONFORMING_SWPRINTFS", "_CRT_SECURE_NO_WARNINGS" } configurations { "Release-DX", "Debug-DX", } buildoptions { "/wd4251" } filter("configurations:Release-DX") defines {"FD_RELEASE", "FD_DX" } setupReleaseConfiguration() filter("configurations:Debug-DX") defines {"FD_DEBUG", "FD_DX" } setupDebugConfiguration() end filter("configurations:Release-VK") defines {"FD_RELEASE", "FD_VK" } setupReleaseConfiguration() filter("configurations:Debug-VK") defines {"FD_DEBUG", "FD_VK" } setupDebugConfiguration() filter("platforms:x64") setupX64Platform() project("Frodo-core") kind("StaticLib") location "../solution/Frodo-core/" files { "Frodo-core/**.cpp", "Frodo-core/**.h", "Frodo-core/**.c" } targetdir "../bin/$(Configuration)/$(Platform)/" objdir "../bin/intermediates" includedirs { "Frodo-core/", } filter("Release-VK or Debug-VK") includedirs { vk_path .. "/include/vulkan" } libdirs { vk_path .. "/Lib" } filter {"Release-VK or Debug-VK", "files:Frodo-core/**DX*.cpp"} flags "ExcludeFromBuild" filter("Release-VK or Debug-VK") excludes "Frodo-core/**dx*.*" filter {"Release-DX or Debug-DX", "files:Frodo-core/**VK*.cpp"} flags "ExcludeFromBuild" if _TARGET_OS == "linux" then removefiles { "Frodo-core/platforms/windows/**.*", "Frodo-core/**dx*.*" } elseif _TARGET_OS == "windows" then filter {"system:windows"} removefiles "Frodo-core/platforms/linux/**.*" end project("Sandbox") kind("ConsoleApp") location "../solution/Sandbox" dependson "Frodo-core" files { "Sandbox/**.cpp", "Sandbox/**.h" } filter("Release-VK or Debug-VK") libdirs { vk_path .. "/Lib" } includedirs { vk_path .. "/include/vulkan" } filter {} includedirs {"Frodo-core/", "Sandbox/"} links {"Frodo-core"} if _TARGET_OS == "windows" then postbuildcommands { "call \"$(SolutionDir)../src/post.bat\" \"$(SolutionDir)../src/Sandbox/res\"" } filter("configurations:Release-DX") links { "D3D11", "DXGI" } filter("configurations:Debug-DX") links { "D3D11", "DXGI" } end filter("configurations:Release-VK") links { "vulkan-1" } filter("configurations:Debug-VK") links { "vulkan-1" }
function setupReleaseConfiguration() buildoptions { "/GL", "/sdl-", "/Ot", "/GS-", "/arch:AVX2" } linkoptions { "/LTCG:incremental" } optimize "Speed" inlining "Auto" end function setupDebugConfiguration() buildoptions { "/sdl", "/arch:AVX2" } optimize "Off" inlining "Disabled" end function setupX64Platform() architecture "x86_64" defines "FD_PLATFORM_X64" callingconvention "FastCall" end vk_path = os.getenv("VULKAN_SDK"); if (vk_path == nil) then vk_path = os.getenv("VK_SDK_PATH") end if (vk_path == nil) then print("No vulkan sdk path. Set environment variable VULKAN_SDK or VK_SDK_PATH to the vulkan sdk directory") os.exit() end workspace("Frodo") location "../solution/" startproject "Sandbox" configurations { "Release-VK", "Debug-VK" } platforms { "x64" } defines "FD_LINUX" floatingpoint "Fast" intrinsics "on" if _TARGET_OS == "windows" then removedefines "FD_LINUX" defines { "FD_WINDOWS", "_CRT_NON_CONFORMING_SWPRINTFS", "_CRT_SECURE_NO_WARNINGS" } configurations { "Release-DX", "Debug-DX", } buildoptions { "/wd4251" } filter("configurations:Release-DX") defines {"FD_RELEASE", "FD_DX" } setupReleaseConfiguration() filter("configurations:Debug-DX") defines {"FD_DEBUG", "FD_DX" } setupDebugConfiguration() end filter("configurations:Release-VK") defines {"FD_RELEASE", "FD_VK" } setupReleaseConfiguration() filter("configurations:Debug-VK") defines {"FD_DEBUG", "FD_VK" } setupDebugConfiguration() filter("platforms:x64") setupX64Platform() project("Frodo-core") kind("StaticLib") location "../solution/Frodo-core/" files { "Frodo-core/**.cpp", "Frodo-core/**.h", "Frodo-core/**.c" } targetdir "../bin/$(Configuration)/$(Platform)/" objdir "../bin/intermediates" includedirs { "Frodo-core/", } filter("Release-VK or Debug-VK") includedirs { vk_path .. "/include/vulkan" } libdirs { vk_path .. "/Lib" } targetprefix "VK-" filter("Release-DX or Debug-DX") targetprefix "VK-" filter {"Release-VK or Debug-VK", "files:Frodo-core/**DX*.cpp"} flags "ExcludeFromBuild" filter {"Release-DX or Debug-DX", "files:Frodo-core/**VK*.cpp"} flags "ExcludeFromBuild" if _TARGET_OS == "linux" then removefiles { "Frodo-core/platforms/windows/**.*", "Frodo-core/**dx*.*" } elseif _TARGET_OS == "windows" then filter {"system:windows"} removefiles "Frodo-core/platforms/linux/**.*" end project("Sandbox") kind("ConsoleApp") location "../solution/Sandbox" dependson "Frodo-core" targetdir "../bin/$(Configuration)/$(Platform)/" objdir "../bin/intermediates" files { "Sandbox/**.cpp", "Sandbox/**.h" } filter("Release-VK or Debug-VK") libdirs { vk_path .. "/Lib" } includedirs { vk_path .. "/include/vulkan" } filter {} includedirs {"Frodo-core/", "Sandbox/"} links {"Frodo-core"} if _TARGET_OS == "windows" then postbuildcommands { "call \"$(SolutionDir)../src/post.bat\" \"$(SolutionDir)../src/Sandbox/res\"" } filter("configurations:Release-DX") links { "D3D11", "DXGI" } filter("configurations:Debug-DX") links { "D3D11", "DXGI" } end filter("configurations:Release-VK") links { "vulkan-1" } filter("configurations:Debug-VK") links { "vulkan-1" }
Fixed some shit in premake script
Fixed some shit in premake script
Lua
mit
JeppeSRC/Frodo,JeppeSRC/Frodo,JeppeSRC/Frodo
2fa080c83ce21dc94efe66d698299f18de34a140
HexChat/twitch.lua
HexChat/twitch.lua
hexchat.register('Twitch', '1', 'Better integration with twitch.tv') local function is_twitch () if hexchat.nickcmp(hexchat.get_info('network'), 'Twitch') == 0 then return true elseif hexchat.get_info('server'):find('twitch.tv$') then return true else return false end end -- Commands from http://help.twitch.tv/customer/portal/articles/659095-chat-moderation-commands -- /ban may conflict with other scripts nothing we can do about that -- /clear is an existing command, just override it for _, command in pairs({ 'timeout', 'slow', 'slowoff', 'subscribers', 'subscribersoff', 'mod', 'unmod', 'mods', 'clear', 'ban', 'unban', 'commercial', 'r9kbeta', 'r9kbetaoff', 'color', 'host', }) do hexchat.hook_command(command, function (word, word_eol) if not is_twitch() then return end hexchat.command('say .' .. word_eol[1]) return hexchat.EAT_ALL end) end for command, alias in pairs({['op'] = 'mod', ['deop'] = 'unmod'}) do hexchat.hook_command(command, function (word, word_eol) if not is_twitch() then return end if word[2] then hexchat.command(string.format('say .%s %s', alias, word_eol[2])) else hexchat.command('say .' .. alias) end return hexchat.EAT_ALL end) end hexchat.hook_server('PRIVMSG', function (word, word_eol) if not is_twitch() then return end -- Move jtv messages to the server tab if word[1]:find('^:jtv!') and word[3]:sub(1, 1) ~= '#' then local id = hexchat.prefs['id'] for chan in hexchat.iterate('channels') do if chan.type == 1 and chan.id == id then chan.context:emit_print('Server Text', word_eol[4]:sub(2)) return hexchat.EAT_ALL end end end end) hexchat.hook_server('421', function (word, word_eol) if not is_twitch() then return end -- Ignore unknown command errors if word[4] == 'WHO' or word[4] == 'WHOIS' then return hexchat.EAT_ALL end end) hexchat.hook_print('Your Message', function (args) if not is_twitch() then return end -- Eat any message starting with a '.', twitch eats all of them too if args[2]:sub(1, 1) == '.' then return hexchat.EAT_ALL end end) hexchat.hook_print('Channel Message', function (args) if not is_twitch() then return end -- Format messages from twitchnotify if args[1] == 'twitchnotify' then print('\00314*\t' .. args[2]) return hexchat.EAT_HEXCHAT end end, hexchat.PRI_LOW)
hexchat.register('Twitch', '1', 'Better integration with twitch.tv') local function is_twitch () local server = hexchat.get_info('server') if hexchat.nickcmp(hexchat.get_info('network'), 'Twitch') == 0 then return true elseif server and server:find('twitch.tv$') then return true else return false end end -- Commands from http://help.twitch.tv/customer/portal/articles/659095-chat-moderation-commands -- /ban may conflict with other scripts nothing we can do about that -- /clear is an existing command, just override it for _, command in pairs({ 'timeout', 'slow', 'slowoff', 'subscribers', 'subscribersoff', 'mod', 'unmod', 'mods', 'clear', 'ban', 'unban', 'commercial', 'r9kbeta', 'r9kbetaoff', 'color', 'host', }) do hexchat.hook_command(command, function (word, word_eol) if not is_twitch() then return end hexchat.command('say .' .. word_eol[1]) return hexchat.EAT_ALL end) end for command, alias in pairs({['op'] = 'mod', ['deop'] = 'unmod'}) do hexchat.hook_command(command, function (word, word_eol) if not is_twitch() then return end if word[2] then hexchat.command(string.format('say .%s %s', alias, word_eol[2])) else hexchat.command('say .' .. alias) end return hexchat.EAT_ALL end) end hexchat.hook_server('PRIVMSG', function (word, word_eol) if not is_twitch() then return end -- Move jtv messages to the server tab if word[1]:find('^:jtv!') and word[3]:sub(1, 1) ~= '#' then local id = hexchat.prefs['id'] for chan in hexchat.iterate('channels') do if chan.type == 1 and chan.id == id then chan.context:emit_print('Server Text', word_eol[4]:sub(2)) return hexchat.EAT_ALL end end end end) hexchat.hook_server('421', function (word, word_eol) if not is_twitch() then return end -- Ignore unknown command errors if word[4] == 'WHO' or word[4] == 'WHOIS' then return hexchat.EAT_ALL end end) hexchat.hook_print('Your Message', function (args) if not is_twitch() then return end -- Eat any message starting with a '.', twitch eats all of them too if args[2]:sub(1, 1) == '.' then return hexchat.EAT_ALL end end) hexchat.hook_print('Channel Message', function (args) if not is_twitch() then return end -- Format messages from twitchnotify if args[1] == 'twitchnotify' then print('\00314*\t' .. args[2]) return hexchat.EAT_HEXCHAT end end, hexchat.PRI_LOW)
twitch: Fix possible error
twitch: Fix possible error
Lua
mit
TingPing/plugins,TingPing/plugins
a7e84b7d185abeebc2967853a444d312675eaf58
lua/mediaplayer/sh_metadata.lua
lua/mediaplayer/sh_metadata.lua
--[[--------------------------------------------------------- Media Player Metadata All media metadata is cached in an SQLite table for quick lookup and to prevent unnecessary network requests. -----------------------------------------------------------]] MediaPlayer.Metadata = {} --- -- Default metadata table name -- @type String -- local TableName = "mediaplayer_metadata" --- -- SQLite table struct -- @type String -- local TableStruct = string.format([[ CREATE TABLE %s ( id VARCHAR(48) PRIMARY KEY, title VARCHAR(128), duration INTEGER NOT NULL DEFAULT 0, thumbnail VARCHAR(512), extra VARCHAR(2048), request_count INTEGER NOT NULL DEFAULT 1, last_request INTEGER NOT NULL DEFAULT 0, last_updated INTEGER NOT NULL DEFAULT 0, expired BOOLEAN NOT NULL DEFAULT 0 )]], TableName) --- -- Maximum cache age before it expires; currently one week in seconds. -- @type Number -- local MaxCacheAge = 604800 --- -- Query the metadata table for the given media object's metadata. -- If the metadata is older than one week, it is ignored and replaced upon -- saving. -- -- @param media Media service object. -- @return table Cached metadata results. -- function MediaPlayer.Metadata:Query( media ) local id = media:UniqueID() if not id then return end local query = ("SELECT * FROM `%s` WHERE id='%s'"):format(TableName, id) if MediaPlayer.DEBUG then print("MediaPlayer.Metadata.Query") print(query) end local results = sql.QueryRow(query) if results then local expired = ( tonumber(results.expired) == 1 ) -- Media metadata has been marked as out-of-date if expired then return nil end local lastupdated = tonumber( results.last_updated ) local timediff = RealTime() - lastupdated if timediff > MaxCacheAge then -- Set metadata entry as expired query = "UPDATE `%s` SET expired=1 WHERE id='%s'" query = query:format( TableName, id ) if MediaPlayer.DEBUG then print("MediaPlayer.Metadata.Query: Setting entry as expired") print(query) end sql.Query( query ) return nil else return results end elseif results == false then ErrorNoHalt("MediaPlayer.Metadata.Query: There was an error executing the SQL query\n") print(query) end return nil end --- -- Save or update the given media object into the metadata table. -- -- @param media Media service object. -- @return table SQL query results. -- function MediaPlayer.Metadata:Save( media ) local id = media:UniqueID() if not id then return end local query = ("SELECT expired FROM `%s` WHERE id='%s'"):format(TableName, id) local results = sql.Query(query) if istable(results) then -- update if MediaPlayer.DEBUG then print("MediaPlayer.Metadata.Save Results:") PrintTable(results) end results = results[1] local expired = ( tonumber(results.expired) == 1 ) if expired then -- Update possible new metadata query = "UPDATE `%s` SET request_count=request_count+1, title=%s, duration=%s, thumbnail=%s, extra=%s, last_request=%s, last_updated=%s, expired=0 WHERE id='%s'" query = query:format( TableName, sql.SQLStr( media:Title() ), media:Duration(), sql.SQLStr( media:Thumbnail() ), sql.SQLStr( util.TableToJSON(media._metadata.extra) ), RealTime(), RealTime(), id ) else query = "UPDATE `%s` SET request_count=request_count+1, last_request=%s WHERE id='%s'" query = query:format( TableName, RealTime(), id ) end else -- insert query = string.format( "INSERT INTO `%s` ", TableName ) .. "(id,title,duration,thumbnail,extra,last_request,last_updated) VALUES (" .. string.format( "'%s',", id ) .. string.format( "%s,", sql.SQLStr( media:Title() ) ) .. string.format( "%s,", media:Duration() ) .. string.format( "%s,", sql.SQLStr( media:Thumbnail() ) ) .. string.format( "%s,", sql.SQLStr( util.TableToJSON(media._metadata.extra) ) ) .. string.format( "%d,", RealTime() ) .. string.format( "%d)", RealTime() ) end if MediaPlayer.DEBUG then print("MediaPlayer.Metadata.Save") print(query) end results = sql.Query(query) if results == false then ErrorNoHalt("MediaPlayer.Metadata.Save: There was an error executing the SQL query\n") print(query) end return results end -- Create the SQLite table if it doesn't exist if not sql.TableExists(TableName) then Msg("MediaPlayer.Metadata: Creating `" .. TableName .. "` table...\n") sql.Query(TableStruct) end
--[[--------------------------------------------------------- Media Player Metadata All media metadata is cached in an SQLite table for quick lookup and to prevent unnecessary network requests. -----------------------------------------------------------]] MediaPlayer.Metadata = {} --- -- Default metadata table name -- @type String -- local TableName = "mediaplayer_metadata" --- -- SQLite table struct -- @type String -- local TableStruct = string.format([[ CREATE TABLE %s ( id VARCHAR(48) PRIMARY KEY, title VARCHAR(128), duration INTEGER NOT NULL DEFAULT 0, thumbnail VARCHAR(512), extra VARCHAR(2048), request_count INTEGER NOT NULL DEFAULT 1, last_request INTEGER NOT NULL DEFAULT 0, last_updated INTEGER NOT NULL DEFAULT 0, expired BOOLEAN NOT NULL DEFAULT 0 )]], TableName) --- -- Maximum cache age before it expires; currently one week in seconds. -- @type Number -- local MaxCacheAge = 604800 --- -- Query the metadata table for the given media object's metadata. -- If the metadata is older than one week, it is ignored and replaced upon -- saving. -- -- @param media Media service object. -- @return table Cached metadata results. -- function MediaPlayer.Metadata:Query( media ) local id = media:UniqueID() if not id then return end local query = ("SELECT * FROM `%s` WHERE id='%s'"):format(TableName, id) if MediaPlayer.DEBUG then print("MediaPlayer.Metadata.Query") print(query) end local results = sql.QueryRow(query) if results then local expired = ( tonumber(results.expired) == 1 ) -- Media metadata has been marked as out-of-date if expired then return nil end local lastupdated = tonumber( results.last_updated ) local timediff = os.time() - lastupdated if timediff > MaxCacheAge then -- Set metadata entry as expired query = "UPDATE `%s` SET expired=1 WHERE id='%s'" query = query:format( TableName, id ) if MediaPlayer.DEBUG then print("MediaPlayer.Metadata.Query: Setting entry as expired") print(query) end sql.Query( query ) return nil else return results end elseif results == false then ErrorNoHalt("MediaPlayer.Metadata.Query: There was an error executing the SQL query\n") print(query) end return nil end --- -- Save or update the given media object into the metadata table. -- -- @param media Media service object. -- @return table SQL query results. -- function MediaPlayer.Metadata:Save( media ) local id = media:UniqueID() if not id then return end local query = ("SELECT expired FROM `%s` WHERE id='%s'"):format(TableName, id) local results = sql.Query(query) if istable(results) then -- update if MediaPlayer.DEBUG then print("MediaPlayer.Metadata.Save Results:") PrintTable(results) end results = results[1] local expired = ( tonumber(results.expired) == 1 ) if expired then -- Update possible new metadata query = "UPDATE `%s` SET request_count=request_count+1, title=%s, duration=%s, thumbnail=%s, extra=%s, last_request=%s, last_updated=%s, expired=0 WHERE id='%s'" query = query:format( TableName, sql.SQLStr( media:Title() ), media:Duration(), sql.SQLStr( media:Thumbnail() ), sql.SQLStr( util.TableToJSON(media._metadata.extra) ), os.time(), os.time(), id ) else query = "UPDATE `%s` SET request_count=request_count+1, last_request=%s WHERE id='%s'" query = query:format( TableName, os.time(), id ) end else -- insert query = string.format( "INSERT INTO `%s` ", TableName ) .. "(id,title,duration,thumbnail,extra,last_request,last_updated) VALUES (" .. string.format( "'%s',", id ) .. string.format( "%s,", sql.SQLStr( media:Title() ) ) .. string.format( "%s,", media:Duration() ) .. string.format( "%s,", sql.SQLStr( media:Thumbnail() ) ) .. string.format( "%s,", sql.SQLStr( util.TableToJSON(media._metadata.extra) ) ) .. string.format( "%d,", os.time() ) .. string.format( "%d)", os.time() ) end if MediaPlayer.DEBUG then print("MediaPlayer.Metadata.Save") print(query) end results = sql.Query(query) if results == false then ErrorNoHalt("MediaPlayer.Metadata.Save: There was an error executing the SQL query\n") print(query) end return results end -- Create the SQLite table if it doesn't exist if not sql.TableExists(TableName) then Msg("MediaPlayer.Metadata: Creating `" .. TableName .. "` table...\n") sql.Query(TableStruct) end
Fixed metadata module accidently not using the unix epoch :(
Fixed metadata module accidently not using the unix epoch :(
Lua
mit
pixeltailgames/gm-mediaplayer,pixeltailgames/gm-mediaplayer
7c0ec6ee7d98d0dc7fd01c91ac343a2fd8384d58
logout-popup-widget/logout-popup.lua
logout-popup-widget/logout-popup.lua
------------------------------------------------- -- Logout widget for Awesome Window Manager -- More details could be found here: -- https://github.com/streetturtle/awesome-wm-widgets/tree/master/logout-widget -- @author Pavel Makhov -- @copyright 2020 Pavel Makhov ------------------------------------------------- local awful = require("awful") local capi = {keygrabber = keygrabber } local wibox = require("wibox") local gears = require("gears") local beautiful = require("beautiful") local awesomebuttons = require("awesome-buttons.awesome-buttons") local HOME_DIR = os.getenv("HOME") local WIDGET_DIR = HOME_DIR .. '/.config/awesome/awesome-wm-widgets/logout-popup-widget' local w = wibox { bg = beautiful.fg_normal, max_widget_size = 500, ontop = true, height = 200, width = 400, shape = function(cr, width, height) gears.shape.rounded_rect(cr, width, height, 8) end } local action = wibox.widget { text = ' ', widget = wibox.widget.textbox } local phrase_widget = wibox.widget{ align = 'center', widget = wibox.widget.textbox } local function create_button(icon_name, action_name, accent_color, label_color, onclick, icon_size, icon_margin) local button = awesomebuttons.with_icon { type = 'basic', icon = icon_name, color = accent_color, icon_size = icon_size, icon_margin = icon_margin, onclick = function() onclick() w.visible = false capi.keygrabber.stop() end } button:connect_signal("mouse::enter", function() action:set_markup('<span color="' .. label_color .. '">' .. action_name .. '</span>') end) button:connect_signal("mouse::leave", function() action:set_markup('<span> </span>') end) return button end local function launch(args) args = args or {} local bg_color = args.bg_color or beautiful.bg_normal local accent_color = args.accent_color or beautiful.bg_focus local text_color = args.text_color or beautiful.fg_normal local label_color = args.label_color or beautiful.fg_focus local phrases = args.phrases or {'Goodbye!'} local icon_size = args.icon_size or 40 local icon_margin = args.icon_margin or 16 local onlogout = args.onlogout or function () awesome.quit() end local onlock = args.onlock or function() awful.spawn.with_shell("i3lock") end local onreboot = args.onreboot or function() awful.spawn.with_shell("reboot") end local onsuspend = args.onsuspend or function() awful.spawn.with_shell("systemctl suspend") end local onpoweroff = args.onpoweroff or function() awful.spawn.with_shell("shutdown now") end w:set_bg(bg_color) if #phrases > 0 then phrase_widget:set_markup( '<span color="'.. text_color .. '" size="20000">' .. phrases[ math.random( #phrases ) ] .. '</span>') end w:setup { { phrase_widget, { { create_button('log-out', 'Log Out (l)', accent_color, label_color, onlogout, icon_size, icon_margin), create_button('lock', 'Lock (k)', accent_color, label_color, onlock, icon_size, icon_margin), create_button('refresh-cw', 'Reboot (r)', accent_color, label_color, onreboot, icon_size, icon_margin), create_button('moon', 'Suspend (u)', accent_color, label_color, onsuspend, icon_size, icon_margin), create_button('power', 'Power Off (s)', accent_color, label_color, onpoweroff, icon_size, icon_margin), id = 'buttons', spacing = 8, layout = wibox.layout.fixed.horizontal }, valigh = 'center', layout = wibox.container.place }, { action, haligh = 'center', layout = wibox.container.place }, spacing = 32, layout = wibox.layout.fixed.vertical }, id = 'a', shape_border_width = 1, valigh = 'center', layout = wibox.container.place } w.screen = mouse.screen w.visible = true awful.placement.centered(w) capi.keygrabber.run(function(_, key, event) if event == "release" then return end if key then if key == 'Escape' then phrase_widget:set_text('') capi.keygrabber.stop() w.visible = false elseif key == 's' then onpoweroff() elseif key == 'r' then onreboot() elseif key == 'u' then onsuspend() elseif key == 'k' then onlock() elseif key == 'l' then onlogout() end if key == 'Escape' or string.match("srukl", key) then phrase_widget:set_text('') capi.keygrabber.stop() w.visible = false end end end) end local function widget(args) local icon = args.icon or WIDGET_DIR .. '/power.svg' local res = wibox.widget { { { image = icon, widget = wibox.widget.imagebox }, margins = 4, layout = wibox.container.margin }, layout = wibox.layout.fixed.horizontal, } res:buttons( awful.util.table.join( awful.button({}, 1, function() if w.visible then phrase_widget:set_text('') capi.keygrabber.stop() w.visible = false else launch(args) end end) )) return res end return { launch = launch, widget = widget }
------------------------------------------------- -- Logout widget for Awesome Window Manager -- More details could be found here: -- https://github.com/streetturtle/awesome-wm-widgets/tree/master/logout-widget -- @author Pavel Makhov -- @copyright 2020 Pavel Makhov ------------------------------------------------- local awful = require("awful") local capi = {keygrabber = keygrabber } local wibox = require("wibox") local gears = require("gears") local beautiful = require("beautiful") local awesomebuttons = require("awesome-buttons.awesome-buttons") local HOME_DIR = os.getenv("HOME") local WIDGET_DIR = HOME_DIR .. '/.config/awesome/awesome-wm-widgets/logout-popup-widget' local w = wibox { bg = beautiful.fg_normal, max_widget_size = 500, ontop = true, height = 200, width = 400, shape = function(cr, width, height) gears.shape.rounded_rect(cr, width, height, 8) end } local action = wibox.widget { text = ' ', widget = wibox.widget.textbox } local phrase_widget = wibox.widget{ align = 'center', widget = wibox.widget.textbox } local function create_button(icon_name, action_name, accent_color, label_color, onclick, icon_size, icon_margin) local button = awesomebuttons.with_icon { type = 'basic', icon = icon_name, color = accent_color, icon_size = icon_size, icon_margin = icon_margin, onclick = function() onclick() w.visible = false capi.keygrabber.stop() end } button:connect_signal("mouse::enter", function() action:set_markup('<span color="' .. label_color .. '">' .. action_name .. '</span>') end) button:connect_signal("mouse::leave", function() action:set_markup('<span> </span>') end) return button end local function launch(args) args = args or {} local bg_color = args.bg_color or beautiful.bg_normal local accent_color = args.accent_color or beautiful.bg_focus local text_color = args.text_color or beautiful.fg_normal local label_color = args.label_color or beautiful.fg_focus local phrases = args.phrases or {'Goodbye!'} local icon_size = args.icon_size or 40 local icon_margin = args.icon_margin or 16 local onlogout = args.onlogout or function () awesome.quit() end local onlock = args.onlock or function() awful.spawn.with_shell("i3lock") end local onreboot = args.onreboot or function() awful.spawn.with_shell("reboot") end local onsuspend = args.onsuspend or function() awful.spawn.with_shell("systemctl suspend") end local onpoweroff = args.onpoweroff or function() awful.spawn.with_shell("shutdown now") end w:set_bg(bg_color) if #phrases > 0 then phrase_widget:set_markup( '<span color="'.. text_color .. '" size="20000">' .. phrases[ math.random( #phrases ) ] .. '</span>') end w:setup { { phrase_widget, { { create_button('log-out', 'Log Out (l)', accent_color, label_color, onlogout, icon_size, icon_margin), create_button('lock', 'Lock (k)', accent_color, label_color, onlock, icon_size, icon_margin), create_button('refresh-cw', 'Reboot (r)', accent_color, label_color, onreboot, icon_size, icon_margin), create_button('moon', 'Suspend (u)', accent_color, label_color, onsuspend, icon_size, icon_margin), create_button('power', 'Power Off (s)', accent_color, label_color, onpoweroff, icon_size, icon_margin), id = 'buttons', spacing = 8, layout = wibox.layout.fixed.horizontal }, valigh = 'center', layout = wibox.container.place }, { action, haligh = 'center', layout = wibox.container.place }, spacing = 32, layout = wibox.layout.fixed.vertical }, id = 'a', shape_border_width = 1, valigh = 'center', layout = wibox.container.place } w.screen = mouse.screen w.visible = true awful.placement.centered(w) capi.keygrabber.run(function(_, key, event) if event == "release" then return end if key then if key == 'Escape' then phrase_widget:set_text('') capi.keygrabber.stop() w.visible = false elseif key == 's' then onpoweroff() elseif key == 'r' then onreboot() elseif key == 'u' then onsuspend() elseif key == 'k' then onlock() elseif key == 'l' then onlogout() end if key == 'Escape' or string.match("srukl", key) then phrase_widget:set_text('') capi.keygrabber.stop() w.visible = false end end end) end local function widget(args) local icon = args.icon or WIDGET_DIR .. '/power.svg' local res = wibox.widget { { { image = icon, widget = wibox.widget.imagebox }, margins = 4, layout = wibox.container.margin }, layout = wibox.layout.fixed.horizontal, } res:buttons( awful.util.table.join( awful.button({}, 1, function() if w.visible then phrase_widget:set_text('') capi.keygrabber.stop() w.visible = false else launch(args) end end) )) return res end return { launch = launch, widget = widget }
fix lua check
fix lua check
Lua
mit
streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets
db283fa6724a656b7835b1ef5153b7811a428c5c
nvim/.config/nvim/lua/gb/plugins.lua
nvim/.config/nvim/lua/gb/plugins.lua
vim.cmd "autocmd BufWritePost plugins.lua PackerCompile" -- Auto compile when there are changes in plugins.lua require("packer").startup( function(use) -- Packer can manage itself use "wbthomason/packer.nvim" use { "rmehri01/onenord.nvim", config = function() require("onenord").setup({ fade_nc = true }) end } use "lukas-reineke/indent-blankline.nvim" -- Statusline use { "feline-nvim/feline.nvim" } use "windwp/windline.nvim" -- File tree use {"kyazdani42/nvim-web-devicons", config = function() require "gb.icons" end} use "kyazdani42/nvim-tree.lua" -- Highlight hex colors use "norcalli/nvim-colorizer.lua" -- Autoformater use "lukas-reineke/lsp-format.nvim" use "averms/black-nvim" -- Highlight other uses of the current word under the cursor use "RRethy/vim-illuminate" -- Lua scratchpad use "rafcamlet/nvim-luapad" -- Toggle floating terminal inside nvim use "voldikss/vim-floaterm" -- Treesitter Plugins {{{ use { "nvim-treesitter/nvim-treesitter", run = ":TSUpdate" } use "nvim-treesitter/playground" -- }}} -- LSP Plugins {{{ use "nvim-lua/lsp-status.nvim" use "neovim/nvim-lspconfig" use { "hrsh7th/nvim-cmp", requires = { "hrsh7th/cmp-buffer", "hrsh7th/cmp-nvim-lua", "hrsh7th/cmp-nvim-lsp", "hrsh7th/cmp-path", "hrsh7th/cmp-vsnip", "hrsh7th/cmp-nvim-lsp-signature-help" } } use "nvim-lua/lsp_extensions.nvim" use "onsails/lspkind-nvim" -- }}} -- Tmux Plugins {{{ use "tmux-plugins/vim-tmux-focus-events" -- Allows navigation between vim and tmux use "christoomey/vim-tmux-navigator" -- }}} -- Comment helper use { "numToStr/Comment.nvim", requires = { "JoosepAlviste/nvim-ts-context-commentstring" } } use { "kevinhwang91/nvim-bqf", requires = { { "junegunn/fzf", run = function() vim.fn["fzf#install"]() end } } } -- Run tests inside nvim use "David-Kunz/jester" use "vim-test/vim-test" -- Live Markdown previews use { "iamcco/markdown-preview.nvim", run = "cd app && yarn install" } -- Additional search highlighting use "kevinhwang91/nvim-hlslens" -- Telescope Plugins {{{ use "nvim-lua/popup.nvim" use "nvim-lua/plenary.nvim" use "nvim-telescope/telescope.nvim" use "nvim-telescope/telescope-fzf-writer.nvim" use { "nvim-telescope/telescope-fzf-native.nvim", run = "make" } use 'nvim-telescope/telescope-ui-select.nvim' -- }}} -- Git status integration use { "lewis6991/gitsigns.nvim", requires = { "nvim-lua/plenary.nvim" } } use { "TimUntersberger/neogit", requires = { "nvim-lua/plenary.nvim", "sindrets/diffview.nvim" } } -- Documentation generator use { "kkoomen/vim-doge", run = function() vim.fn["doge#install"]() end } -- Git UI use { "tpope/vim-fugitive", requires = { "tpope/vim-rhubarb" } } -- Adds commands to easliy change surrounding quotes, brackets, etc. use "tpope/vim-surround" -- Test startup time use "tweekmonster/startuptime.vim" -- Swap file handling use "gioele/vim-autoswap" -- Maximize buffers use "szw/vim-maximizer" -- Adds debugger to nvim -- use "puremourning/vimspector" use "mfussenegger/nvim-dap" use "rcarriga/nvim-dap-ui" use "nvim-telescope/telescope-dap.nvim" use "theHamsta/nvim-dap-virtual-text" use { "folke/lsp-trouble.nvim", requires = "kyazdani42/nvim-web-devicons", config = function() require("trouble").setup {} end } -- Snippets use "hrsh7th/vim-vsnip" use "hrsh7th/vim-vsnip-integ" use "rafamadriz/friendly-snippets" -- -- Uncomment when I want to explain regex, no way to override default mappings -- use { 'bennypowers/nvim-regexplainer', -- config = function() require'regexplainer'.setup() end, -- requires = { -- 'nvim-treesitter/nvim-treesitter', -- 'MunifTanjim/nui.nvim', -- } -- } use { "vuki656/package-info.nvim", requires = "MunifTanjim/nui.nvim", config = function() require("package-info").setup() end } use "ggandor/lightspeed.nvim" use { "ThePrimeagen/harpoon", requires = "nvim-lua/plenary.nvim" } end ) require("indent_blankline").setup { -- for example, context is off by default, use this to turn it on show_current_context = true, show_trailing_blankline_indent = false } -- load plugin configs require("gb.autoswap") require("gb.colorizer") require("gb.commenter") require("gb.debugger") require("gb.file-explorer") require("gb.finder") require("gb.format") require("gb.git") require("gb.harpoon") require("gb.hlslens") require("gb.lsp") require("gb.lsp-trouble") require("gb.maximizer") require("gb.remaps") require("gb.statusline") require("gb.term") require("gb.test") require("gb.tmux-navigator") require("gb.treesitter")
vim.cmd "autocmd BufWritePost plugins.lua PackerCompile" -- Auto compile when there are changes in plugins.lua require("packer").startup( function(use) -- Packer can manage itself use "wbthomason/packer.nvim" use { "rmehri01/onenord.nvim", config = function() require("onenord").setup({ fade_nc = true }) end } use "lukas-reineke/indent-blankline.nvim" -- Statusline use { "feline-nvim/feline.nvim" } use "windwp/windline.nvim" -- File tree use "kyazdani42/nvim-web-devicons" use "kyazdani42/nvim-tree.lua" -- Highlight hex colors use "norcalli/nvim-colorizer.lua" -- Autoformater use "lukas-reineke/lsp-format.nvim" use "averms/black-nvim" -- Highlight other uses of the current word under the cursor use "RRethy/vim-illuminate" -- Lua scratchpad use "rafcamlet/nvim-luapad" -- Toggle floating terminal inside nvim use "voldikss/vim-floaterm" -- Treesitter Plugins {{{ use { "nvim-treesitter/nvim-treesitter", run = ":TSUpdate" } use "nvim-treesitter/playground" -- }}} -- LSP Plugins {{{ use "nvim-lua/lsp-status.nvim" use "neovim/nvim-lspconfig" use { "hrsh7th/nvim-cmp", requires = { "hrsh7th/cmp-buffer", "hrsh7th/cmp-nvim-lua", "hrsh7th/cmp-nvim-lsp", "hrsh7th/cmp-path", "hrsh7th/cmp-vsnip", "hrsh7th/cmp-nvim-lsp-signature-help" } } use "nvim-lua/lsp_extensions.nvim" use "onsails/lspkind-nvim" -- }}} -- Tmux Plugins {{{ use "tmux-plugins/vim-tmux-focus-events" -- Allows navigation between vim and tmux use "christoomey/vim-tmux-navigator" -- }}} -- Comment helper use { "numToStr/Comment.nvim", requires = { "JoosepAlviste/nvim-ts-context-commentstring" } } use { "kevinhwang91/nvim-bqf", requires = { { "junegunn/fzf", run = function() vim.fn["fzf#install"]() end } } } -- Run tests inside nvim use "David-Kunz/jester" use "vim-test/vim-test" -- Live Markdown previews use { "iamcco/markdown-preview.nvim", run = "cd app && yarn install" } -- Additional search highlighting use "kevinhwang91/nvim-hlslens" -- Telescope Plugins {{{ use "nvim-lua/popup.nvim" use "nvim-lua/plenary.nvim" use "nvim-telescope/telescope.nvim" use "nvim-telescope/telescope-fzf-writer.nvim" use { "nvim-telescope/telescope-fzf-native.nvim", run = "make" } use 'nvim-telescope/telescope-ui-select.nvim' -- }}} -- Git status integration use { "lewis6991/gitsigns.nvim", requires = { "nvim-lua/plenary.nvim" } } use { "TimUntersberger/neogit", requires = { "nvim-lua/plenary.nvim", "sindrets/diffview.nvim" } } -- Documentation generator use { "kkoomen/vim-doge", run = function() vim.fn["doge#install"]() end } -- Git UI use { "tpope/vim-fugitive", requires = { "tpope/vim-rhubarb" } } -- Adds commands to easliy change surrounding quotes, brackets, etc. use "tpope/vim-surround" -- Test startup time use "tweekmonster/startuptime.vim" -- Swap file handling use "gioele/vim-autoswap" -- Maximize buffers use "szw/vim-maximizer" -- Adds debugger to nvim -- use "puremourning/vimspector" use "mfussenegger/nvim-dap" use "rcarriga/nvim-dap-ui" use "nvim-telescope/telescope-dap.nvim" use "theHamsta/nvim-dap-virtual-text" use { "folke/lsp-trouble.nvim", requires = "kyazdani42/nvim-web-devicons", config = function() require("trouble").setup {} end } -- Snippets use "hrsh7th/vim-vsnip" use "hrsh7th/vim-vsnip-integ" use "rafamadriz/friendly-snippets" -- -- Uncomment when I want to explain regex, no way to override default mappings -- use { 'bennypowers/nvim-regexplainer', -- config = function() require'regexplainer'.setup() end, -- requires = { -- 'nvim-treesitter/nvim-treesitter', -- 'MunifTanjim/nui.nvim', -- } -- } use { "vuki656/package-info.nvim", requires = "MunifTanjim/nui.nvim", config = function() require("package-info").setup() end } use "ggandor/lightspeed.nvim" use { "ThePrimeagen/harpoon", requires = "nvim-lua/plenary.nvim" } end ) require("indent_blankline").setup { -- for example, context is off by default, use this to turn it on show_current_context = true, show_trailing_blankline_indent = false } -- load plugin configs require("gb.icons") require("gb.autoswap") require("gb.colorizer") require("gb.commenter") require("gb.debugger") require("gb.file-explorer") require("gb.finder") require("gb.format") require("gb.git") require("gb.harpoon") require("gb.hlslens") require("gb.lsp") require("gb.lsp-trouble") require("gb.maximizer") require("gb.remaps") require("gb.statusline") require("gb.term") require("gb.test") require("gb.tmux-navigator") require("gb.treesitter")
Fixup test icons showing up
Fixup test icons showing up
Lua
mit
gblock0/dotfiles
103523490801ea75d7287eb5e6c0e928aab1b116
mod_s2s_auth_dane/mod_s2s_auth_dane.lua
mod_s2s_auth_dane/mod_s2s_auth_dane.lua
-- mod_s2s_auth_dane -- Copyright (C) 2013-2014 Kim Alvefur -- -- This file is MIT/X11 licensed. -- -- In your DNS, put -- _xmpp-server.example.com. IN TLSA 3 0 1 <sha256 hash of certificate> -- -- Known issues: -- Race condition -- Could be done much cleaner if mod_s2s was using util.async -- -- TODO Things to test/handle: -- Negative or bogus answers -- No encryption offered -- Different hostname before and after STARTTLS - mod_s2s should complain -- Interaction with Dialback module:set_global(); local type = type; local t_insert = table.insert; local set = require"util.set"; local dns_lookup = require"net.adns".lookup; local hashes = require"util.hashes"; local base64 = require"util.encodings".base64; local idna_to_ascii = require "util.encodings".idna.to_ascii; if not dns_lookup.types or not dns_lookup.types.TLSA then module:log("error", "No TLSA support available, DANE will not be supported"); return end local s2sout = module:depends"s2s".route_to_new_session.s2sout; local pat = "%-%-%-%-%-BEGIN ([A-Z ]+)%-%-%-%-%-\r?\n".. "([0-9A-Za-z=+/\r\n]*)\r?\n%-%-%-%-%-END %1%-%-%-%-%-"; local function pem2der(pem) local typ, data = pem:match(pat); if typ and data then return base64.decode(data), typ; end end local use_map = { ["DANE-EE"] = 3; ["DANE-TA"] = 2; ["PKIX-EE"] = 1; ["PKIX-CA"] = 0 } local implemented_uses = set.new { "DANE-EE", "PKIX-EE" }; local configured_uses = module:get_option_set("dane_uses", { "DANE-EE" }); local enabled_uses = set.intersection(implemented_uses, configured_uses) / function(use) return use_map[use] end; local function dane_lookup(host_session, cb, a,b,c,e) if host_session.dane ~= nil then return end if host_session.direction == "incoming" then local name = host_session.from_host and idna_to_ascii(host_session.from_host); if not name then return end host_session.dane = dns_lookup(function (answer) if not answer.secure then if cb then return cb(a,b,c,e); end return; end local n = #answer if n == 0 then if cb then return cb(a,b,c,e); end return end if n == 1 and answer[1].srv.target == '.' then return end local srv_hosts = { answer = answer }; local dane = {}; host_session.dane = dane; host_session.srv_hosts = srv_hosts; for _, record in ipairs(answer) do t_insert(srv_hosts, record.srv); dns_lookup(function(dane_answer) n = n - 1; if dane_answer.bogus then t_insert(dane, { bogus = dane_answer.bogus }); elseif dane_answer.secure then for _, record in ipairs(dane_answer) do t_insert(dane, record); end end if n == 0 and cb then return cb(a,b,c,e); end end, ("_%d._tcp.%s."):format(record.srv.port, record.srv.target), "TLSA"); end end, "_xmpp-server._tcp."..name..".", "SRV"); return true; elseif host_session.direction == "outgoing" then local srv_hosts = host_session.srv_hosts; if not ( srv_hosts and srv_hosts.answer and srv_hosts.answer.secure ) then return end local srv_choice = srv_hosts[host_session.srv_choice]; host_session.dane = dns_lookup(function(answer) if answer and (answer.secure and #answer > 0) or answer.bogus then srv_choice.dane = answer; else srv_choice.dane = false; end host_session.dane = srv_choice.dane; if cb then return cb(a,b,c,e); end end, ("_%d._tcp.%s."):format(srv_choice.port, srv_choice.target), "TLSA"); return true; end end local _try_connect = s2sout.try_connect; function s2sout.try_connect(host_session, connect_host, connect_port, err) if not err and dane_lookup(host_session, _try_connect, host_session, connect_host, connect_port, err) then return true; end return _try_connect(host_session, connect_host, connect_port, err); end function module.add_host(module) module:hook("s2s-stream-features", function(event) -- dane_lookup(origin, origin.from_host); dane_lookup(event.origin); end, 1); module:hook("s2s-authenticated", function(event) local session = event.session; if session.dane and not session.secure then -- TLSA record but no TLS, not ok. -- TODO Optional? -- Bogus replies should trigger this path -- How does this interact with Dialback? session:close({ condition = "policy-violation", text = "Encrypted server-to-server communication is required but was not " ..((session.direction == "outgoing" and "offered") or "used") }); return false; end end); end module:hook("s2s-check-certificate", function(event) local session, cert = event.session, event.cert; local dane = session.dane; if type(dane) == "table" then local use, select, match, tlsa, certdata, match_found, supported_found; for i = 1, #dane do tlsa = dane[i].tlsa; module:log("debug", "TLSA %s %s %s %d bytes of data", tlsa:getUsage(), tlsa:getSelector(), tlsa:getMatchType(), #tlsa.data); use, select, match, certdata = tlsa.use, tlsa.select, tlsa.match; if enabled_uses:contains(use) then -- PKIX-EE or DANE-EE if use == 1 or use == 3 then supported_found = true if select == 0 then certdata = pem2der(cert:pem()); elseif select == 1 and cert.pubkey then certdata = pem2der(cert:pubkey()); -- Not supported in stock LuaSec else module:log("warn", "DANE selector %s is unsupported", tlsa:getSelector() or select); end if match == 1 then certdata = certdata and hashes.sha256(certdata); elseif match == 2 then certdata = certdata and hashes.sha512(certdata); elseif match ~= 0 then module:log("warn", "DANE match rule %s is unsupported", tlsa:getMatchType() or match); certdata = nil; end -- Should we check if the cert subject matches? if certdata and certdata == tlsa.data then (session.log or module._log)("info", "DANE validation successful"); session.cert_identity_status = "valid"; if use == 3 then -- DANE-EE, chain status equals DNSSEC chain status session.cert_chain_status = "valid"; -- for usage 1, PKIX-EE, the chain has to be valid already end match_found = true; break; end end end end if supported_found and not match_found or dane.bogus then -- No TLSA matched or response was bogus (session.log or module._log)("warn", "DANE validation failed"); session.cert_identity_status = "invalid"; session.cert_chain_status = "invalid"; end end end); function module.unload() -- Restore the original try_connect function s2sout.try_connect = _try_connect; end
-- mod_s2s_auth_dane -- Copyright (C) 2013-2014 Kim Alvefur -- -- This file is MIT/X11 licensed. -- -- In your DNS, put -- _xmpp-server.example.com. IN TLSA 3 0 1 <sha256 hash of certificate> -- -- Known issues: -- Race condition -- Could be done much cleaner if mod_s2s was using util.async -- -- TODO Things to test/handle: -- Negative or bogus answers -- No encryption offered -- Different hostname before and after STARTTLS - mod_s2s should complain -- Interaction with Dialback module:set_global(); local type = type; local t_insert = table.insert; local set = require"util.set"; local dns_lookup = require"net.adns".lookup; local hashes = require"util.hashes"; local base64 = require"util.encodings".base64; local idna_to_ascii = require "util.encodings".idna.to_ascii; if not dns_lookup.types or not dns_lookup.types.TLSA then module:log("error", "No TLSA support available, DANE will not be supported"); return end local s2sout = module:depends"s2s".route_to_new_session.s2sout; local pat = "%-%-%-%-%-BEGIN ([A-Z ]+)%-%-%-%-%-\r?\n".. "([0-9A-Za-z=+/\r\n]*)\r?\n%-%-%-%-%-END %1%-%-%-%-%-"; local function pem2der(pem) local typ, data = pem:match(pat); if typ and data then return base64.decode(data), typ; end end local use_map = { ["DANE-EE"] = 3; ["DANE-TA"] = 2; ["PKIX-EE"] = 1; ["PKIX-CA"] = 0 } local implemented_uses = set.new { "DANE-EE", "PKIX-EE" }; local configured_uses = module:get_option_set("dane_uses", { "DANE-EE" }); local enabled_uses = set.intersection(implemented_uses, configured_uses) / function(use) return use_map[use] end; local function dane_lookup(host_session, cb, a,b,c,e) if host_session.dane ~= nil then return end if host_session.direction == "incoming" then local name = host_session.from_host and idna_to_ascii(host_session.from_host); if not name then return end host_session.dane = dns_lookup(function (answer) if not answer.secure then if cb then return cb(a,b,c,e); end return; end local n = #answer if n == 0 then if cb then return cb(a,b,c,e); end return end if n == 1 and answer[1].srv.target == '.' then return end local srv_hosts = { answer = answer }; local dane = {}; host_session.dane = dane; host_session.srv_hosts = srv_hosts; for _, record in ipairs(answer) do t_insert(srv_hosts, record.srv); dns_lookup(function(dane_answer) n = n - 1; if dane_answer.bogus then t_insert(dane, { bogus = dane_answer.bogus }); elseif dane_answer.secure then for _, record in ipairs(dane_answer) do t_insert(dane, record); end end if n == 0 and cb then return cb(a,b,c,e); end end, ("_%d._tcp.%s."):format(record.srv.port, record.srv.target), "TLSA"); end end, "_xmpp-server._tcp."..name..".", "SRV"); return true; elseif host_session.direction == "outgoing" then local srv_hosts = host_session.srv_hosts; if not ( srv_hosts and srv_hosts.answer and srv_hosts.answer.secure ) then return end local srv_choice = srv_hosts[host_session.srv_choice]; host_session.dane = dns_lookup(function(answer) if answer and (answer.secure and #answer > 0) or answer.bogus then srv_choice.dane = answer; else srv_choice.dane = false; end host_session.dane = srv_choice.dane; if cb then return cb(a,b,c,e); end end, ("_%d._tcp.%s."):format(srv_choice.port, srv_choice.target), "TLSA"); return true; end end local _try_connect = s2sout.try_connect; function s2sout.try_connect(host_session, connect_host, connect_port, err) if not err and dane_lookup(host_session, _try_connect, host_session, connect_host, connect_port, err) then return true; end return _try_connect(host_session, connect_host, connect_port, err); end function module.add_host(module) module:hook("s2s-stream-features", function(event) -- dane_lookup(origin, origin.from_host); local host_session = event.origin; host_session.log("debug", "Pausing connection until DANE lookup is completed"); host_session.conn:pause() local function resume() module:log("eebug", "Resuming connection"); host_session.conn:resume() end if not dane_lookup(host_session, resume) then resume(); end end, 10); module:hook("s2s-authenticated", function(event) local session = event.session; if session.dane and not session.secure then -- TLSA record but no TLS, not ok. -- TODO Optional? -- Bogus replies should trigger this path -- How does this interact with Dialback? session:close({ condition = "policy-violation", text = "Encrypted server-to-server communication is required but was not " ..((session.direction == "outgoing" and "offered") or "used") }); return false; end end); end module:hook("s2s-check-certificate", function(event) local session, cert = event.session, event.cert; local dane = session.dane; if type(dane) == "table" then local use, select, match, tlsa, certdata, match_found, supported_found; for i = 1, #dane do tlsa = dane[i].tlsa; module:log("debug", "TLSA %s %s %s %d bytes of data", tlsa:getUsage(), tlsa:getSelector(), tlsa:getMatchType(), #tlsa.data); use, select, match, certdata = tlsa.use, tlsa.select, tlsa.match; if enabled_uses:contains(use) then -- PKIX-EE or DANE-EE if use == 1 or use == 3 then supported_found = true if select == 0 then certdata = pem2der(cert:pem()); elseif select == 1 and cert.pubkey then certdata = pem2der(cert:pubkey()); -- Not supported in stock LuaSec else module:log("warn", "DANE selector %s is unsupported", tlsa:getSelector() or select); end if match == 1 then certdata = certdata and hashes.sha256(certdata); elseif match == 2 then certdata = certdata and hashes.sha512(certdata); elseif match ~= 0 then module:log("warn", "DANE match rule %s is unsupported", tlsa:getMatchType() or match); certdata = nil; end -- Should we check if the cert subject matches? if certdata and certdata == tlsa.data then (session.log or module._log)("info", "DANE validation successful"); session.cert_identity_status = "valid"; if use == 3 then -- DANE-EE, chain status equals DNSSEC chain status session.cert_chain_status = "valid"; -- for usage 1, PKIX-EE, the chain has to be valid already end match_found = true; break; end end end end if supported_found and not match_found or dane.bogus then -- No TLSA matched or response was bogus (session.log or module._log)("warn", "DANE validation failed"); session.cert_identity_status = "invalid"; session.cert_chain_status = "invalid"; end end end); function module.unload() -- Restore the original try_connect function s2sout.try_connect = _try_connect; end
mod_s2s_auth_dane: Pause s2sin while doing SRV and TLSA lookups, fixes race condition (Can haz util.async plz)
mod_s2s_auth_dane: Pause s2sin while doing SRV and TLSA lookups, fixes race condition (Can haz util.async plz)
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
8744adbbd2967b50409dd72f23e47f60be81d541
applications/luci-initmgr/luasrc/controller/init.lua
applications/luci-initmgr/luasrc/controller/init.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.init", package.seeall) function index() if not luci.fs.isfile("/etc/rc.common") then return end local page = entry({"admin", "system", "init"}, form("init/init"), luci.i18n.translate("initmgr", "Init Scripts")) page.i18n = "initmgr" page.dependent = true end
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.init", package.seeall) function index() if not luci.fs.isfile("/etc/rc.common") then return end require("luci.i18n") luci.i18n.loadc("initmgr") entry( {"admin", "system", "init"}, form("init/init"), luci.i18n.translate("initmgr", "Init Scripts") ).i18n = "initmgr" end
* luci/app/initmgr: fix translation issue in menu entry
* luci/app/initmgr: fix translation issue in menu entry git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@3516 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
8devices/carambola2-luci,saraedum/luci-packages-old,projectbismark/luci-bismark,ThingMesh/openwrt-luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,jschmidlapp/luci,freifunk-gluon/luci,saraedum/luci-packages-old,projectbismark/luci-bismark,Canaan-Creative/luci,freifunk-gluon/luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,vhpham80/luci,Canaan-Creative/luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,vhpham80/luci,stephank/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,8devices/carambola2-luci,yeewang/openwrt-luci,ch3n2k/luci,yeewang/openwrt-luci,ch3n2k/luci,projectbismark/luci-bismark,gwlim/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,jschmidlapp/luci,8devices/carambola2-luci,alxhh/piratenluci,8devices/carambola2-luci,zwhfly/openwrt-luci,vhpham80/luci,8devices/carambola2-luci,alxhh/piratenluci,ch3n2k/luci,yeewang/openwrt-luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3,8devices/carambola2-luci,Flexibity/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,phi-psi/luci,phi-psi/luci,zwhfly/openwrt-luci,gwlim/luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,ch3n2k/luci,zwhfly/openwrt-luci,ch3n2k/luci,phi-psi/luci,alxhh/piratenluci,Canaan-Creative/luci,gwlim/luci,stephank/luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,Flexibity/luci,Flexibity/luci,yeewang/openwrt-luci,alxhh/piratenluci,Canaan-Creative/luci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,gwlim/luci,vhpham80/luci,Flexibity/luci,phi-psi/luci,jschmidlapp/luci,freifunk-gluon/luci,saraedum/luci-packages-old,yeewang/openwrt-luci,yeewang/openwrt-luci,alxhh/piratenluci,jschmidlapp/luci,freifunk-gluon/luci,alxhh/piratenluci,projectbismark/luci-bismark,jschmidlapp/luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,vhpham80/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,freifunk-gluon/luci,jschmidlapp/luci,stephank/luci,alxhh/piratenluci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,freifunk-gluon/luci,stephank/luci,jschmidlapp/luci,projectbismark/luci-bismark,stephank/luci,jschmidlapp/luci,Flexibity/luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,vhpham80/luci,freifunk-gluon/luci,Flexibity/luci,phi-psi/luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,gwlim/luci,saraedum/luci-packages-old,8devices/carambola2-luci,gwlim/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,zwhfly/openwrt-luci,Canaan-Creative/luci,phi-psi/luci
d7ca046b0b3d597b1a78516cd283d338ecb3cbc1
util/filters.lua
util/filters.lua
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local t_insert, t_remove = table.insert, table.remove; module "filters" local new_filter_hooks = {}; function initialize(session) if not session.filters then local filters = {}; session.filters = filters; function session.filter(type, data) local filter_list = filters[type]; if filter_list then for i = 1, #filter_list do data = filter_list[i](data, session); if data == nil then break; end end end return data; end end for i=1,#new_filter_hooks do new_filter_hooks[i](session); end return session.filter; end function add_filter(session, type, callback, priority) if not session.filters then initialize(session); end local filter_list = session.filters[type]; if not filter_list then filter_list = {}; session.filters[type] = filter_list; end priority = priority or 0; local i = 0; repeat i = i + 1; until not filter_list[i] or filter_list[filter_list[i]] < priority; t_insert(filter_list, i, callback); filter_list[callback] = priority; end function remove_filter(session, type, callback) if not session.filters then return; end local filter_list = session.filters[type]; if filter_list and filter_list[callback] then for i=1, #filter_list do if filter_list[i] == callback then t_remove(filter_list, i); filter_list[callback] = nil; return true; end end end end function add_filter_hook(callback) t_insert(new_filter_hooks, callback); end function remove_filter_hook(callback) for i=1,#new_filter_hooks do if new_filter_hooks[i] == callback then t_remove(new_filter_hooks, i); end end end return _M;
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local t_insert, t_remove = table.insert, table.remove; module "filters" local new_filter_hooks = {}; function initialize(session) if not session.filters then local filters = {}; session.filters = filters; function session.filter(type, data) local filter_list = filters[type]; if filter_list then for i = 1, #filter_list do data = filter_list[i](data, session); if data == nil then break; end end end return data; end end for i=1,#new_filter_hooks do new_filter_hooks[i](session); end return session.filter; end function add_filter(session, type, callback, priority) if not session.filters then initialize(session); end local filter_list = session.filters[type]; if not filter_list then filter_list = {}; session.filters[type] = filter_list; elseif filter_list[callback] then return; -- Filter already added end priority = priority or 0; local i = 0; repeat i = i + 1; until not filter_list[i] or filter_list[filter_list[i]] < priority; t_insert(filter_list, i, callback); filter_list[callback] = priority; end function remove_filter(session, type, callback) if not session.filters then return; end local filter_list = session.filters[type]; if filter_list and filter_list[callback] then for i=1, #filter_list do if filter_list[i] == callback then t_remove(filter_list, i); filter_list[callback] = nil; return true; end end end end function add_filter_hook(callback) t_insert(new_filter_hooks, callback); end function remove_filter_hook(callback) for i=1,#new_filter_hooks do if new_filter_hooks[i] == callback then t_remove(new_filter_hooks, i); end end end return _M;
util.filters: Ignore filters being added twice (fixes issues on removal)
util.filters: Ignore filters being added twice (fixes issues on removal)
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
e56c8b618ac0784e0ca70e4145d30a610f6a704d
init.lua
init.lua
local json = require('json') local framework = require('framework.lua') framework.table() framework.util() framework.functional() local stringutil = framework.string local Plugin = framework.Plugin local NetDataSource = framework.NetDataSource local net = require('net') local items = {} local params = framework.boundary.param params.name = 'Boundary Disk Use Summary' params.version = '2.0' items = params.items or items local meterDataSource = NetDataSource:new('127.0.0.1', '9192') function meterDataSource:onFetch(socket) socket:write('{"jsonrpc":"2.0","method":"query_metric","id":1,"params":{"match":"system.fs.use_percent*"}}\n') end local meterPlugin = Plugin:new(params, meterDataSource) function meterPlugin:onParseValues(data) local result = {} local parsed = json.parse(data) if table.getn(parsed.result.query_metric) > 0 then for i = 1, table.getn(parsed.result.query_metric), 3 do if parsed.result.query_metric[i] ~= 'system.fs.use_percent.total' then local dirname = stringutil.urldecode(string.sub(parsed.result.query_metric[i], string.find(parsed.result.query_metric[i], "dir=")+4, string.find(parsed.result.query_metric[i], "&")-1)) local devname = stringutil.urldecode(string.sub(parsed.result.query_metric[i], string.find(parsed.result.query_metric[i], "dev=")+4, -1)) local sourcename=meterPlugin.source.."." local metric = {} local capture_metric = 0 for _, item in ipairs(items) do if item.dir then if (item.dir == dirname) then if item.device then if (item.device == devname) then capture_metric = 1 sourcename = sourcename..(item.diskname or dirname.."."..devname) end else capture_metric = 1 sourcename = sourcename..(item.diskname or dirname.."."..devname) end end elseif item.device and (item.device == devname) then capture_metric = 1 sourcename = sourcename..(item.diskname or dirname.."."..devname) end end if capture_metric == 1 then local metric = "PERCENT_DISKUSE" local value = {} value['source'] = '"'..sourcename..'"' value['value'] = parsed.result.query_metric[i+1] result[metric] = value end end end end return result end meterPlugin:run()
local json = require('json') local framework = require('framework.lua') framework.table() framework.util() framework.functional() local stringutil = framework.string local Plugin = framework.Plugin local NetDataSource = framework.NetDataSource local net = require('net') local items = {} local params = framework.boundary.param params.name = 'Boundary Disk Use Summary' params.version = '2.0' items = params.items or items local meterDataSource = NetDataSource:new('127.0.0.1', '9192') function meterDataSource:onFetch(socket) socket:write('{"jsonrpc":"2.0","method":"query_metric","id":1,"params":{"match":"system.fs.use_percent*"}}\n') end local meterPlugin = Plugin:new(params, meterDataSource) function meterPlugin:onParseValues(data) local result = {} local parsed = json.parse(data) if table.getn(parsed.result.query_metric) > 0 then for i = 1, table.getn(parsed.result.query_metric), 3 do if parsed.result.query_metric[i] ~= 'system.fs.use_percent.total' then local dirname = stringutil.urldecode(string.sub(parsed.result.query_metric[i], string.find(parsed.result.query_metric[i], "dir=")+4, string.find(parsed.result.query_metric[i], "&")-1)) local devname = stringutil.urldecode(string.sub(parsed.result.query_metric[i], string.find(parsed.result.query_metric[i], "dev=")+4, -1)) local sourcename=meterPlugin.source .. "." local metric = {} local capture_metric = 0 for _, item in ipairs(items) do if item.dir then if string.find(dirname, item.dir) then if item.device then if string.find(devname, item.device) then capture_metric = 1 sourcename = sourcename .. (item.diskname or (dirname .. "." .. devname)) end else capture_metric = 1 sourcename = sourcename .. (item.diskname or (dirname .. "." .. devname)) end end elseif item.device and string.find(devname, item.device) then capture_metric = 1 sourcename = sourcename .. (item.diskname or (dirname .. "." .. devname)) end end if capture_metric == 1 then local metric = "DISKUSE_SUMMARY" local value = {} value['source'] = '"'..sourcename..'"' value['value'] = parsed.result.query_metric[i+1] result[metric] = value end end end end return result end meterPlugin:run()
Fixed issue with not matching a partial
Fixed issue with not matching a partial
Lua
apache-2.0
boundary/boundary-plugin-diskuse-summary,graphdat/plugin-diskuse_summary,GabrielNicolasAvellaneda/boundary-plugin-diskuse-summary
bdac80e60fdded42694bb6844ccb4c4a72d8d559
init.lua
init.lua
-- Copyright 2007 Mitchell mitchell<att>caladbolg.net. See LICENSE. require 'ext/pm' require 'ext/find' require 'ext/mime_types' require 'ext/keys' local mpath = _HOME..'modules/?.lua;'.._HOME..'/modules/?/init.lua' package.path = package.path..';'..mpath -- modules to load on startup require 'textadept' -- end modules require 'ext/key_commands' -- process command line arguments local textadept = textadept if #arg == 0 then textadept.io.load_session() else local base_dir = arg[0]:match('^.+/') or '' for _, filename in ipairs(arg) do textadept.io.open(base_dir..filename) end textadept.pm.entry_text = 'buffers' textadept.pm.activate() end
-- Copyright 2007 Mitchell mitchell<att>caladbolg.net. See LICENSE. require 'ext/pm' require 'ext/find' require 'ext/mime_types' require 'ext/keys' local mpath = _HOME..'modules/?.lua;'.._HOME..'/modules/?/init.lua' package.path = package.path..';'..mpath -- modules to load on startup require 'textadept' -- end modules require 'ext/key_commands' -- process command line arguments local textadept = textadept if #arg == 0 then textadept.io.load_session() else local base_dir = arg[0]:match('^.+/') or '' local filepath for _, filename in ipairs(arg) do if not filename:match('^~?/') then textadept.io.open(base_dir..filename) else textadept.io.open(filename) end end textadept.pm.entry_text = 'buffers' textadept.pm.activate() end
Fixed command line parameters bug; init.lua When files are passed by the command line, they are assumed to be relative to Textadept's path. Instead, check if the file has a leading '~/' or '/' indicating an absolute path. If so, do not treat it that way. Otherwise treat it as relative.
Fixed command line parameters bug; init.lua When files are passed by the command line, they are assumed to be relative to Textadept's path. Instead, check if the file has a leading '~/' or '/' indicating an absolute path. If so, do not treat it that way. Otherwise treat it as relative.
Lua
mit
rgieseke/textadept,rgieseke/textadept
7545294df284f425bcb68f37b6f7c60dfda8cd43
webui/src/WebUIManager.lua
webui/src/WebUIManager.lua
-- **************************************************************************** -- * -- * PROJECT: MTA:SA CEF utilities (https://github.com/Jusonex/mtasa_cef_tools) -- * FILE: webui/src/WebUIManager.lua -- * PURPOSE: WebUIManager class definition -- * -- **************************************************************************** WebUIManager = { new = function(self, ...) local o=setmetatable({},{__index=self}) o:constructor(...) WebUIManager.Instance = o return o end; getInstance = function() assert(WebUIManager.Instance, "WebUIManager has not been initialised yet") return WebUIManager.Instance end; Settings = { ScrollSpeed = 50; TitleBarHeight = 25; }; } -- -- WebUIManager's constructor -- Returns: The WebUIManager instance -- function WebUIManager:constructor() self.m_Stack = {} addEventHandler("onClientRender", root, function() -- Draw from bottom to top for k, ui in ipairs(self.m_Stack) do ui:draw() end end ) addEventHandler("onClientCursorMove", root, function(relX, relY, absX, absY) for k, ui in pairs(self.m_Stack) do local browser = ui:getUnderlyingBrowser() local pos = ui:getPosition() browser:injectMouseMove(absX - pos.x, absY - pos.y) end end ) local function onMouseWheel(key, state, direction) local browser = WebUIManager.getFocusedBrowser() if browser then browser:injectMouseWheel(direction*WebUIManager.Settings.ScrollSpeed, 0) end end bindKey("mouse_wheel_up", "down", onMouseWheel, 1) bindKey("mouse_wheel_down", "down", onMouseWheel, -1) addEventHandler("onClientClick", root, function(button, state, absX, absY) local topIndex = #self.m_Stack -- Process from top to bottom for i = topIndex, 1, -1 do local ui = self.m_Stack[i] local pos, size = ui:getPosition(), ui:getSize() local browser = ui:getUnderlyingBrowser() if state == "up" and ui.movefunc then removeEventHandler("onClientCursorMove", root, ui.movefunc) ui.movefunc = nil end -- Are we within the browser rect? if absX >= pos.x and absY >= pos.y and absX < pos.x + size.x and absY < pos.y + size.y then if ui:getType() == WebWindow.WindowType.Frame and state == "down" then local diff = Vector2(absX-pos.x, absY-pos.y) ui.movefunc = function(relX, relY, absX, absY) ui:setPosition(Vector2(absX, absY) - diff) end if diff.y <= WebUIManager.Settings.TitleBarHeight then addEventHandler("onClientCursorMove", root, ui.movefunc) break end end if state == "down" then browser:injectMouseDown(button) else browser:injectMouseUp(button) end -- Move to front if the current browser isn't the currently focused one if i ~= topIndex then self:moveWindowToFrontByIndex(i) end browser:focus() -- Stop here (the click has been processed!) break end end end ) end -- -- Registers a window at the manager -- Parameters: -- window: The web UI window (WebWindow) -- function WebUIManager:registerWindow(window) table.insert(self.m_Stack, window) end -- -- Unlinks a window from the manager -- Parameters: -- window: The web UI window (WebWindow) -- function WebUIManager:unregisterWindow(window) for k, v in pairs(self.m_Stack) do if v == window then table.remove(self.m_Stack, k) return true end end return false end -- -- Moves the specified window to the front (by WebWindow instance) -- Parameters: -- window: The web UI window you want to move to the front (WebWindow) -- function WebUIManager:moveWindowToFront(window) -- TODO end -- -- Moves a window to the front by index (fast internal use) -- Parameters: -- index: The index the window has on the drawing stack -- function WebUIManager:moveWindowToFrontByIndex(index) -- Make a backup of the window at the specified index local ui = self.m_Stack[index] -- Remove it from the list temporally table.remove(self.m_Stack, index) -- Append it to the end table.insert(self.m_Stack, ui) end -- -- Static function that returns the currently focussed browser -- Returns: The focussed browser element -- function WebUIManager.getFocusedBrowser() for k, browser in pairs(getElementsByType("webbrowser")) do if browser:isFocused() then return browser end end return false end
-- **************************************************************************** -- * -- * PROJECT: MTA:SA CEF utilities (https://github.com/Jusonex/mtasa_cef_tools) -- * FILE: webui/src/WebUIManager.lua -- * PURPOSE: WebUIManager class definition -- * -- **************************************************************************** WebUIManager = { new = function(self, ...) local o=setmetatable({},{__index=self}) o:constructor(...) WebUIManager.Instance = o return o end; getInstance = function() assert(WebUIManager.Instance, "WebUIManager has not been initialised yet") return WebUIManager.Instance end; Settings = { ScrollSpeed = 50; TitleBarHeight = 25; }; } -- -- WebUIManager's constructor -- Returns: The WebUIManager instance -- function WebUIManager:constructor() self.m_Stack = {} addEventHandler("onClientRender", root, function() -- Draw from bottom to top for k, ui in ipairs(self.m_Stack) do ui:draw() end end ) addEventHandler("onClientCursorMove", root, function(relX, relY, absX, absY) for k, ui in pairs(self.m_Stack) do local browser = ui:getUnderlyingBrowser() local pos = ui:getPosition() browser:injectMouseMove(absX - pos.x, absY - pos.y) end end ) local function onMouseWheel(key, state, direction) local browser = WebUIManager.getFocusedBrowser() if browser then browser:injectMouseWheel(direction*WebUIManager.Settings.ScrollSpeed, 0) end end bindKey("mouse_wheel_up", "down", onMouseWheel, 1) bindKey("mouse_wheel_down", "down", onMouseWheel, -1) addEventHandler("onClientClick", root, function(button, state, absX, absY) local topIndex = #self.m_Stack -- Process from top to bottom for i = topIndex, 1, -1 do local ui = self.m_Stack[i] local pos, size = ui:getPosition(), ui:getSize() local browser = ui:getUnderlyingBrowser() if state == "up" and ui.movefunc then removeEventHandler("onClientCursorMove", root, ui.movefunc) ui.movefunc = nil end -- Are we within the browser rect? if absX >= pos.x and absY >= pos.y and absX < pos.x + size.x and absY < pos.y + size.y then if ui:getType() == WebWindow.WindowType.Frame and state == "down" then local diff = Vector2(absX-pos.x, absY-pos.y) ui.movefunc = function(relX, relY, absX, absY) ui:setPosition(Vector2(absX, absY) - diff) end if diff.y <= WebUIManager.Settings.TitleBarHeight then addEventHandler("onClientCursorMove", root, ui.movefunc) break end end if state == "down" then browser:injectMouseDown(button) else browser:injectMouseUp(button) end -- Move to front if the current browser isn't the currently focused one if i ~= topIndex then self:moveWindowToFrontByIndex(i) end browser:focus() -- Enable input mode guiSetInputEnabled(true) -- Stop here (the click has been processed!) return end end -- Unfocus and disable input mode Browser.focus(nil) guiSetInputEnabled(false) end ) end -- -- Registers a window at the manager -- Parameters: -- window: The web UI window (WebWindow) -- function WebUIManager:registerWindow(window) table.insert(self.m_Stack, window) end -- -- Unlinks a window from the manager -- Parameters: -- window: The web UI window (WebWindow) -- function WebUIManager:unregisterWindow(window) for k, v in pairs(self.m_Stack) do if v == window then table.remove(self.m_Stack, k) return true end end return false end -- -- Moves the specified window to the front (by WebWindow instance) -- Parameters: -- window: The web UI window you want to move to the front (WebWindow) -- function WebUIManager:moveWindowToFront(window) -- TODO end -- -- Moves a window to the front by index (fast internal use) -- Parameters: -- index: The index the window has on the drawing stack -- function WebUIManager:moveWindowToFrontByIndex(index) -- Make a backup of the window at the specified index local ui = self.m_Stack[index] -- Remove it from the list temporally table.remove(self.m_Stack, index) -- Append it to the end table.insert(self.m_Stack, ui) end -- -- Static function that returns the currently focussed browser -- Returns: The focussed browser element -- function WebUIManager.getFocusedBrowser() for k, browser in pairs(getElementsByType("webbrowser")) do if browser:isFocused() then return browser end end return false end
Fixed key binds being triggered if browser is focused
Fixed key binds being triggered if browser is focused
Lua
unlicense
Jusonex/mtasa_cef_tools,FL1K3R/mtasa_cef_tools,FL1K3R/mtasa_cef_tools,Jusonex/mtasa_cef_tools
e8af37c32549f54059f6e7635064c623b80c039c
xmake/rules/winsdk/mfc/mfc.lua
xmake/rules/winsdk/mfc/mfc.lua
--!A cross-platform build utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2018, TBOOX Open Source Group. -- -- @author xigal -- @file xmake.lua -- -- remove exists md or mt function _mfc_remove_mt_md_flags(target, flagsname) local flags = table.wrap(target:get(flagsname)) for key, flag in pairs(flags) do flag = flag:lower():trim() if flag:find("^[/%-]?mt[d]?$") or flag:find("^[/%-]?md[d]?$") then flags[key] = nil end end target:set(flagsname, flags) end -- remove exists settings function _mfc_remove_flags(target) local ldflags = table.wrap(target:get("ldflags")) for key, ldflag in pairs(ldflags) do ldflag = ldflag:lower():trim() if ldflag:find("[/%-]subsystem:") then ldflags[key] = nil break end end target:set("ldflags", ldflags) -- remove defines MT MTd MD MDd local defines = table.wrap(target:get("defines")) for key, define in pairs(defines) do define = define:lower():trim() if define:find("^[/%-]?mt[d]?$") or define:find("^[/%-]?md[d]?$") then defines[key] = nil end end target:set("defines", defines) -- remove c /MD,/MT _mfc_remove_mt_md_flags(target, "cflags") -- remove c,cpp /MD,/MT _mfc_remove_mt_md_flags(target, "cxflags") -- remove cpp /MD,/MT _mfc_remove_mt_md_flags(target, "cxxflags") end -- get application entry function mfc_application_entry(target) local defines = target:get("defines") for key, define in pairs(defines) do define = define:lower():trim() if define:find("^[_]?unicode$") then return "-entry:wWinMainCRTStartup" end end return "-entry:WinMainCRTStartup" end -- apply shared mfc settings function mfc_shared(target) -- remove some exists flags _mfc_remove_flags(target) -- add flags target:add("ldflags", "-subsystem:windows", {force = true}) -- set runtimelibrary target:add("cxflags", ifelse(is_mode("debug"), "-MDd", "-MD")) target:add("defines", "AFX", "_AFXDLL") end -- apply static mfc settings function mfc_static(target) -- remove some exists flags _mfc_remove_flags(target) -- add flags target:add("ldflags", "-subsystem:windows", {force = true}) target:add("ldflags", "-force", {force = true}) -- set runtimelibrary target:add("cxflags", ifelse(is_mode("debug"), "-MTd", "-MT")) end
--!A cross-platform build utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2018, TBOOX Open Source Group. -- -- @author xigal -- @file xmake.lua -- -- remove exists md or mt function _mfc_remove_mt_md_flags(target, flagsname) local flags = table.wrap(target:get(flagsname)) for i = #flags, 1, -1 do flag = flags[i]:lower():trim() if flag:find("^[/%-]?mt[d]?$") or flag:find("^[/%-]?md[d]?$") then table.remove(flags, i) end end target:set(flagsname, flags) end -- remove exists settings function _mfc_remove_flags(target) local ldflags = table.wrap(target:get("ldflags")) for i = #ldflags, 1, -1 do ldflag = ldflags[i]:lower():trim() if ldflag:find("[/%-]subsystem:") then table.remove(ldflags, i) break end end target:set("ldflags", ldflags) -- remove defines MT MTd MD MDd local defines = table.wrap(target:get("defines")) for i = #defines, 1, -1 do define = defines[i]:lower():trim() if define:find("^[/%-]?mt[d]?$") or define:find("^[/%-]?md[d]?$") then table.remove(defines, i) end end target:set("defines", defines) -- remove c /MD,/MT _mfc_remove_mt_md_flags(target, "cflags") -- remove c,cpp /MD,/MT _mfc_remove_mt_md_flags(target, "cxflags") -- remove cpp /MD,/MT _mfc_remove_mt_md_flags(target, "cxxflags") end -- get application entry function mfc_application_entry(target) local defines = target:get("defines") for key, define in pairs(defines) do define = define:lower():trim() if define:find("^[_]?unicode$") then return "-entry:wWinMainCRTStartup" end end return "-entry:WinMainCRTStartup" end -- apply shared mfc settings function mfc_shared(target) -- remove some exists flags _mfc_remove_flags(target) -- add flags target:add("ldflags", "-subsystem:windows", {force = true}) -- set runtimelibrary target:add("cxflags", ifelse(is_mode("debug"), "-MDd", "-MD")) target:add("defines", "AFX", "_AFXDLL") end -- apply static mfc settings function mfc_static(target) -- remove some exists flags _mfc_remove_flags(target) -- add flags target:add("ldflags", "-subsystem:windows", {force = true}) target:add("ldflags", "-force", {force = true}) -- set runtimelibrary target:add("cxflags", ifelse(is_mode("debug"), "-MTd", "-MT")) end
fix bug: remove item from table
fix bug: remove item from table
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake
38b22206e6e356a3ccfb08de89acb23a9967a7a3
contrib/package/olsrd-luci/files/lib/config/olsr.lua
contrib/package/olsrd-luci/files/lib/config/olsr.lua
#!/usr/bin/lua --[[ OLSRd configuration generator (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.fs") require("luci.util") require("luci.model.uci") local conf = luci.model.uci.get_all("olsr") local function _value(val) if val:match("^[0-9%. \t]+$") or val == "yes" or val == "no" then return val else return string.format( '"%s"', val ) end end local function _section(sect,sval,parstr) local rv = "" local pad = "" if sval then rv = string.format( '%s "%s"\n{\n', conf[sect][".type"], conf[sect][sval] ) pad = "\t" end for k, v in luci.util.spairs(conf[sect]) do if k:sub(1,1) ~= '.' and k ~= sval then if parstr then rv = rv .. string.format( '%s%s "%s"\t"%s"\n', pad, parstr, k:gsub( "_", "-" ), -- XXX: find a better solution for this v ) else rv = rv .. string.format( '%s%s\t%s\n', pad, k, _value(v) ) end end end if sval then rv = rv .. "}\n" end return rv end local function _hna(sval) local rv = string.format( "%s\n{\n", sval ) for k, v in luci.util.spairs(conf) do if conf[k][".type"] == sval and conf[k].NetAddr and conf[k].Prefix then rv = rv .. string.format( "\t%s\t%s\n", conf[k].NetAddr, conf[k].Prefix ) end end return rv .. "}\n" end local function _ipc(sval) local rv = string.format( "%s\n{\n", sval ) for k, v in luci.util.spairs(conf[sval]) do if k:sub(1,1) ~= "." then local vals = luci.util.split(v, "%s+", nil, true) if k == "Net" then for i = 1,#vals,2 do rv = rv .. string.format( "\tNet\t%s\t%s\n", vals[i], vals[i+1] ) end elseif k == "Host" then for i, v in ipairs(vals) do rv = rv .. string.format( "\t%s\t%s\n", k, vals[i] ) end else rv = rv .. string.format( "\t%s\t%s\n", k, v ) end end end return rv .. "}\n" end -- general config section print( _section("general") ) -- plugin config sections for k, v in luci.util.spairs(conf) do if conf[k][".type"] == "LoadPlugin" then if v.Library and luci.fs.access("/usr/lib/"..v.Library) then print( _section( k, "Library", "PlParam" ) ) end end end -- interface config sections for k, v in luci.util.spairs(conf) do if conf[k][".type"] == "Interface" then print( _section( k, "Interface" ) ) end end -- write Hna4, Hna6 sections print( _hna("Hna4") ) print( _hna("Hna6") ) -- write IpcConnect section print( _ipc("IpcConnect") )
#!/usr/bin/lua --[[ OLSRd configuration generator (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.fs") require("luci.util") require("luci.model.uci") local uci = luci.model.uci.cursor() local conf = uci:get_all("olsr") local function _value(val) if val:match("^[0-9%. \t]+$") or val == "yes" or val == "no" then return val else return string.format( '"%s"', val ) end end local function _section(sect,sval,parstr) local rv = "" local pad = "" if sval then if sval == "Interface" then rv = string.format( 'Interface "%s"\n{\n', uci:get("network",conf[sect][sval],"ifname") ) else rv = string.format( '%s "%s"\n{\n', conf[sect][".type"], conf[sect][sval] ) end pad = "\t" end for k, v in luci.util.spairs(conf[sect]) do if k:sub(1,1) ~= '.' and k ~= sval then if parstr then rv = rv .. string.format( '%s%s "%s"\t"%s"\n', pad, parstr, k:gsub( "_", "-" ), -- XXX: find a better solution for this v ) else rv = rv .. string.format( '%s%s\t%s\n', pad, k, _value(v) ) end end end if sval then rv = rv .. "}\n" end return rv end local function _hna(sval) local rv = string.format( "%s\n{\n", sval ) for k, v in luci.util.spairs(conf) do if conf[k][".type"] == sval and conf[k].NetAddr and conf[k].Prefix then rv = rv .. string.format( "\t%s\t%s\n", conf[k].NetAddr, conf[k].Prefix ) end end return rv .. "}\n" end local function _ipc(sval) local rv = string.format( "%s\n{\n", sval ) for k, v in luci.util.spairs(conf[sval]) do if k:sub(1,1) ~= "." then local vals = luci.util.split(v, "%s+", nil, true) if k == "Net" then for i = 1,#vals,2 do rv = rv .. string.format( "\tNet\t%s\t%s\n", vals[i], vals[i+1] ) end elseif k == "Host" then for i, v in ipairs(vals) do rv = rv .. string.format( "\t%s\t%s\n", k, vals[i] ) end else rv = rv .. string.format( "\t%s\t%s\n", k, v ) end end end return rv .. "}\n" end -- general config section print( _section("general") ) -- plugin config sections for k, v in luci.util.spairs(conf) do if conf[k][".type"] == "LoadPlugin" then if v.Library and luci.fs.access("/usr/lib/"..v.Library) then print( _section( k, "Library", "PlParam" ) ) end end end -- interface config sections for k, v in luci.util.spairs(conf) do if conf[k][".type"] == "Interface" then print( _section( k, "Interface" ) ) end end -- write Hna4, Hna6 sections print( _hna("Hna4") ) print( _hna("Hna6") ) -- write IpcConnect section print( _ipc("IpcConnect") )
* luci/contrib/olsrd-luci: adept config generator to new uci api and fix ifname in interface sections
* luci/contrib/olsrd-luci: adept config generator to new uci api and fix ifname in interface sections git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@3078 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,phi-psi/luci,jschmidlapp/luci,8devices/carambola2-luci,vhpham80/luci,gwlim/luci,projectbismark/luci-bismark,ch3n2k/luci,saraedum/luci-packages-old,phi-psi/luci,projectbismark/luci-bismark,gwlim/luci,zwhfly/openwrt-luci,freifunk-gluon/luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,Flexibity/luci,jschmidlapp/luci,stephank/luci,projectbismark/luci-bismark,stephank/luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,eugenesan/openwrt-luci,stephank/luci,yeewang/openwrt-luci,alxhh/piratenluci,saraedum/luci-packages-old,freifunk-gluon/luci,Flexibity/luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,freifunk-gluon/luci,yeewang/openwrt-luci,alxhh/piratenluci,zwhfly/openwrt-luci,Canaan-Creative/luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,Canaan-Creative/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,stephank/luci,alxhh/piratenluci,phi-psi/luci,jschmidlapp/luci,Canaan-Creative/luci,alxhh/piratenluci,ch3n2k/luci,yeewang/openwrt-luci,Flexibity/luci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,Flexibity/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,projectbismark/luci-bismark,stephank/luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,ch3n2k/luci,gwlim/luci,8devices/carambola2-luci,vhpham80/luci,yeewang/openwrt-luci,vhpham80/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,freifunk-gluon/luci,8devices/carambola2-luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,alxhh/piratenluci,alxhh/piratenluci,phi-psi/luci,jschmidlapp/luci,eugenesan/openwrt-luci,vhpham80/luci,phi-psi/luci,projectbismark/luci-bismark,gwlim/luci,freifunk-gluon/luci,projectbismark/luci-bismark,8devices/carambola2-luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,gwlim/luci,ch3n2k/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,alxhh/piratenluci,Canaan-Creative/luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,dtaht/cerowrt-luci-3.3,8devices/carambola2-luci,8devices/carambola2-luci,saraedum/luci-packages-old,Canaan-Creative/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,jschmidlapp/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,gwlim/luci,gwlim/luci,ThingMesh/openwrt-luci,vhpham80/luci,jschmidlapp/luci,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,freifunk-gluon/luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,ch3n2k/luci,freifunk-gluon/luci,Flexibity/luci,projectbismark/luci-bismark,yeewang/openwrt-luci,ch3n2k/luci,stephank/luci,ThingMesh/openwrt-luci
9fe62f7a283ded890fbfa22befd1f7d7e09771ff
applications/luci-firewall/luasrc/model/cbi/firewall/zone-details.lua
applications/luci-firewall/luasrc/model/cbi/firewall/zone-details.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local nw = require "luci.model.network" local fw = require "luci.model.firewall" local ds = require "luci.dispatcher" local ut = require "luci.util" local m, p, i, v local s, name, net, family, msrc, mdest, log, lim local s2, out, inp m = Map("firewall", translate("Firewall - Zone Settings")) m.redirect = luci.dispatcher.build_url("admin/network/firewall/zones") fw.init(m.uci) nw.init(m.uci) local zone = fw:get_zone(arg[1]) if not zone then luci.http.redirect(dsp.build_url("admin/network/firewall/zones")) return else m.title = "%s - %s" %{ translate("Firewall - Zone Settings"), translatef("Zone %q", zone:name() or "?") } end s = m:section(NamedSection, zone.sid, "zone", translatef("Zone %q", zone:name()), translatef("This section defines common properties of %q. \ The <em>input</em> and <em>output</em> options set the default \ policies for traffic entering and leaving this zone while the \ <em>forward</em> option describes the policy for forwarded traffic \ between different networks within the zone. \ <em>Covered networks</em> specifies which available networks are \ member of this zone.", zone:name())) s.anonymous = true s.addremove = false m.on_commit = function(map) local zone = fw:get_zone(arg[1]) if zone then s.section = zone.sid s2.section = zone.sid end end s:tab("general", translate("General Settings")) s:tab("advanced", translate("Advanced Settings")) name = s:taboption("general", Value, "name", translate("Name")) name.optional = false name.forcewrite = true name.datatype = "uciname" function name.write(self, section, value) if zone:name() ~= value then fw:rename_zone(zone:name(), value) out.exclude = value inp.exclude = value end m.redirect = ds.build_url("admin/network/firewall/zones", value) m.title = "%s - %s" %{ translate("Firewall - Zone Settings"), translatef("Zone %q", value or "?") } end p = { s:taboption("general", ListValue, "input", translate("Input")), s:taboption("general", ListValue, "output", translate("Output")), s:taboption("general", ListValue, "forward", translate("Forward")) } for i, v in ipairs(p) do v:value("REJECT", translate("reject")) v:value("DROP", translate("drop")) v:value("ACCEPT", translate("accept")) end s:taboption("general", Flag, "masq", translate("Masquerading")) s:taboption("general", Flag, "mtu_fix", translate("MSS clamping")) net = s:taboption("general", Value, "network", translate("Covered networks")) net.template = "cbi/network_netlist" net.widget = "checkbox" net.cast = "string" function net.formvalue(self, section) return Value.formvalue(self, section) or "-" end function net.cfgvalue(self, section) return Value.cfgvalue(self, section) or name:cfgvalue(section) end function net.write(self, section, value) zone:clear_networks() local n for n in ut.imatch(value) do zone:add_network(n) end end family = s:taboption("advanced", ListValue, "family", translate("Restrict to address family")) family.rmempty = true family:value("", translate("IPv4 and IPv6")) family:value("ipv4", translate("IPv4 only")) family:value("ipv6", translate("IPv6 only")) msrc = s:taboption("advanced", DynamicList, "masq_src", translate("Restrict Masquerading to given source subnets")) msrc.optional = true msrc.datatype = "neg_network_ip4addr" msrc.placeholder = "0.0.0.0/0" msrc:depends("family", "") msrc:depends("family", "ipv4") mdest = s:taboption("advanced", DynamicList, "masq_dest", translate("Restrict Masquerading to given destination subnets")) mdest.optional = true mdest.datatype = "neg_network_ip4addr" mdest.placeholder = "0.0.0.0/0" mdest:depends("family", "") mdest:depends("family", "ipv4") s:taboption("advanced", Flag, "conntrack", translate("Force connection tracking")) log = s:taboption("advanced", Flag, "log", translate("Enable logging on this zone")) log.rmempty = true log.enabled = "1" lim = s:taboption("advanced", Value, "log_limit", translate("Limit log messages")) lim.placeholder = "10/minute" lim:depends("log", "1") s2 = m:section(NamedSection, zone.sid, "fwd_out", translate("Inter-Zone Forwarding"), translatef("The options below control the forwarding policies between \ this zone (%s) and other zones. <em>Destination zones</em> cover \ forwarded traffic <strong>originating from %q</strong>. \ <em>Source zones</em> match forwarded traffic from other zones \ <strong>targeted at %q</strong>. The forwarding rule is \ <em>unidirectional</em>, e.g. a forward from lan to wan does \ <em>not</em> imply a permission to forward from wan to lan as well.", zone:name(), zone:name(), zone:name() )) out = s2:option(Value, "out", translate("Allow forward to <em>destination zones</em>:")) out.nocreate = true out.widget = "checkbox" out.exclude = zone:name() out.template = "cbi/firewall_zonelist" inp = s2:option(Value, "in", translate("Allow forward from <em>source zones</em>:")) inp.nocreate = true inp.widget = "checkbox" inp.exclude = zone:name() inp.template = "cbi/firewall_zonelist" function out.cfgvalue(self, section) local v = { } local f for _, f in ipairs(zone:get_forwardings_by("src")) do v[#v+1] = f:dest() end return table.concat(v, " ") end function inp.cfgvalue(self, section) local v = { } local f for _, f in ipairs(zone:get_forwardings_by("dest")) do v[#v+1] = f:src() end return v end function out.formvalue(self, section) return Value.formvalue(self, section) or "-" end function inp.formvalue(self, section) return Value.formvalue(self, section) or "-" end function out.write(self, section, value) zone:del_forwardings_by("src") local f for f in ut.imatch(value) do zone:add_forwarding_to(f) end end function inp.write(self, section, value) zone:del_forwardings_by("dest") local f for f in ut.imatch(value) do zone:add_forwarding_from(f) end end return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2010-2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local nw = require "luci.model.network" local fw = require "luci.model.firewall" local ds = require "luci.dispatcher" local ut = require "luci.util" local m, p, i, v local s, name, net, family, msrc, mdest, log, lim local s2, out, inp m = Map("firewall", translate("Firewall - Zone Settings")) m.redirect = luci.dispatcher.build_url("admin/network/firewall/zones") fw.init(m.uci) nw.init(m.uci) local zone = fw:get_zone(arg[1]) if not zone then luci.http.redirect(dsp.build_url("admin/network/firewall/zones")) return else m.title = "%s - %s" %{ translate("Firewall - Zone Settings"), translatef("Zone %q", zone:name() or "?") } end s = m:section(NamedSection, zone.sid, "zone", translatef("Zone %q", zone:name()), translatef("This section defines common properties of %q. \ The <em>input</em> and <em>output</em> options set the default \ policies for traffic entering and leaving this zone while the \ <em>forward</em> option describes the policy for forwarded traffic \ between different networks within the zone. \ <em>Covered networks</em> specifies which available networks are \ member of this zone.", zone:name())) s.anonymous = true s.addremove = false m.on_commit = function(map) local zone = fw:get_zone(arg[1]) if zone then s.section = zone.sid s2.section = zone.sid end end s:tab("general", translate("General Settings")) s:tab("advanced", translate("Advanced Settings")) name = s:taboption("general", Value, "name", translate("Name")) name.optional = false name.forcewrite = true name.datatype = "uciname" function name.write(self, section, value) if zone:name() ~= value then fw:rename_zone(zone:name(), value) out.exclude = value inp.exclude = value end m.redirect = ds.build_url("admin/network/firewall/zones", value) m.title = "%s - %s" %{ translate("Firewall - Zone Settings"), translatef("Zone %q", value or "?") } end p = { s:taboption("general", ListValue, "input", translate("Input")), s:taboption("general", ListValue, "output", translate("Output")), s:taboption("general", ListValue, "forward", translate("Forward")) } for i, v in ipairs(p) do v:value("REJECT", translate("reject")) v:value("DROP", translate("drop")) v:value("ACCEPT", translate("accept")) end s:taboption("general", Flag, "masq", translate("Masquerading")) s:taboption("general", Flag, "mtu_fix", translate("MSS clamping")) net = s:taboption("general", Value, "network", translate("Covered networks")) net.template = "cbi/network_netlist" net.widget = "checkbox" net.cast = "string" function net.formvalue(self, section) return Value.formvalue(self, section) or "-" end function net.cfgvalue(self, section) return Value.cfgvalue(self, section) or name:cfgvalue(section) end function net.write(self, section, value) zone:clear_networks() local n for n in ut.imatch(value) do zone:add_network(n) end end family = s:taboption("advanced", ListValue, "family", translate("Restrict to address family")) family.rmempty = true family:value("", translate("IPv4 and IPv6")) family:value("ipv4", translate("IPv4 only")) family:value("ipv6", translate("IPv6 only")) msrc = s:taboption("advanced", DynamicList, "masq_src", translate("Restrict Masquerading to given source subnets")) msrc.optional = true msrc.datatype = "list(neg,network)" msrc.placeholder = "0.0.0.0/0" msrc:depends("family", "") msrc:depends("family", "ipv4") mdest = s:taboption("advanced", DynamicList, "masq_dest", translate("Restrict Masquerading to given destination subnets")) mdest.optional = true mdest.datatype = "list(neg,network)" mdest.placeholder = "0.0.0.0/0" mdest:depends("family", "") mdest:depends("family", "ipv4") s:taboption("advanced", Flag, "conntrack", translate("Force connection tracking")) log = s:taboption("advanced", Flag, "log", translate("Enable logging on this zone")) log.rmempty = true log.enabled = "1" lim = s:taboption("advanced", Value, "log_limit", translate("Limit log messages")) lim.placeholder = "10/minute" lim:depends("log", "1") s2 = m:section(NamedSection, zone.sid, "fwd_out", translate("Inter-Zone Forwarding"), translatef("The options below control the forwarding policies between \ this zone (%s) and other zones. <em>Destination zones</em> cover \ forwarded traffic <strong>originating from %q</strong>. \ <em>Source zones</em> match forwarded traffic from other zones \ <strong>targeted at %q</strong>. The forwarding rule is \ <em>unidirectional</em>, e.g. a forward from lan to wan does \ <em>not</em> imply a permission to forward from wan to lan as well.", zone:name(), zone:name(), zone:name() )) out = s2:option(Value, "out", translate("Allow forward to <em>destination zones</em>:")) out.nocreate = true out.widget = "checkbox" out.exclude = zone:name() out.template = "cbi/firewall_zonelist" inp = s2:option(Value, "in", translate("Allow forward from <em>source zones</em>:")) inp.nocreate = true inp.widget = "checkbox" inp.exclude = zone:name() inp.template = "cbi/firewall_zonelist" function out.cfgvalue(self, section) local v = { } local f for _, f in ipairs(zone:get_forwardings_by("src")) do v[#v+1] = f:dest() end return table.concat(v, " ") end function inp.cfgvalue(self, section) local v = { } local f for _, f in ipairs(zone:get_forwardings_by("dest")) do v[#v+1] = f:src() end return v end function out.formvalue(self, section) return Value.formvalue(self, section) or "-" end function inp.formvalue(self, section) return Value.formvalue(self, section) or "-" end function out.write(self, section, value) zone:del_forwardings_by("src") local f for f in ut.imatch(value) do zone:add_forwarding_to(f) end end function inp.write(self, section, value) zone:del_forwardings_by("dest") local f for f in ut.imatch(value) do zone:add_forwarding_from(f) end end return m
applications/luci-firewall: fix datatype validation for masq src/dest; allow list of negated ucinames, hostnames, ip-ranges or -addresses
applications/luci-firewall: fix datatype validation for masq src/dest; allow list of negated ucinames, hostnames, ip-ranges or -addresses git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@8154 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
freifunk-gluon/luci,gwlim/luci,phi-psi/luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,yeewang/openwrt-luci,eugenesan/openwrt-luci,8devices/carambola2-luci,Canaan-Creative/luci,freifunk-gluon/luci,jschmidlapp/luci,eugenesan/openwrt-luci,jschmidlapp/luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,vhpham80/luci,Canaan-Creative/luci,ch3n2k/luci,phi-psi/luci,stephank/luci,jschmidlapp/luci,ch3n2k/luci,Flexibity/luci,jschmidlapp/luci,Flexibity/luci,8devices/carambola2-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,dtaht/cerowrt-luci-3.3,gwlim/luci,stephank/luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,gwlim/luci,ch3n2k/luci,yeewang/openwrt-luci,freifunk-gluon/luci,stephank/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,freifunk-gluon/luci,saraedum/luci-packages-old,Flexibity/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,vhpham80/luci,Canaan-Creative/luci,yeewang/openwrt-luci,ch3n2k/luci,Flexibity/luci,phi-psi/luci,ch3n2k/luci,gwlim/luci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,Flexibity/luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,freifunk-gluon/luci,stephank/luci,Canaan-Creative/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,phi-psi/luci,freifunk-gluon/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,gwlim/luci,Canaan-Creative/luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,phi-psi/luci,stephank/luci,zwhfly/openwrt-luci,gwlim/luci,zwhfly/openwrt-luci,vhpham80/luci,dtaht/cerowrt-luci-3.3,8devices/carambola2-luci,ch3n2k/luci,vhpham80/luci,Canaan-Creative/luci,gwlim/luci,phi-psi/luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,jschmidlapp/luci,phi-psi/luci,saraedum/luci-packages-old,stephank/luci,vhpham80/luci,jschmidlapp/luci,Flexibity/luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,yeewang/openwrt-luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,Flexibity/luci
11420f909bc6c161d9df49843de94ea1d982a379
spec/random_tree_spec.lua
spec/random_tree_spec.lua
-- tree.lua, Lua representation of trees with edge lengths -- Copyright (C) 2015 Boris Nagaev -- See the LICENSE file for terms of use. describe("random tree", function() it("creates a random tree", function() local Tree = require 'tree.Tree' local children_of = {} local nodes = {} for i = 1, 10000 do local node = {name='node'..i} children_of[node] = {} if #nodes > 0 then -- select random parent local parent = nodes[math.random(1, #nodes)] children_of[parent][node] = {length=math.random(0, 100)} end table.insert(nodes, node) end local t = Tree(children_of) -- local toNewick = require 'tree.toNewick' local fromNewick = require 'tree.fromNewick' local t2 = fromNewick(toNewick(t)) assert.equal(#t:nodes(), #t2:nodes()) end) end)
-- tree.lua, Lua representation of trees with edge lengths -- Copyright (C) 2015 Boris Nagaev -- See the LICENSE file for terms of use. describe("random tree", function() it("creates a random tree", function() local Tree = require 'tree.Tree' local children_of = {} local nodes = {} for i = 1, 10000 do local node = {name='node'..i} children_of[node] = {} if #nodes > 0 then -- select random parent local parent = nodes[math.random(1, #nodes)] children_of[parent][node] = {length=math.random(0, 100)} end table.insert(nodes, node) end local t = Tree(children_of) -- local lpeg = require 'lpeg' lpeg.setmaxstack(100000) local toNewick = require 'tree.toNewick' local fromNewick = require 'tree.fromNewick' local t2 = fromNewick(toNewick(t)) assert.equal(#t:nodes(), #t2:nodes()) end) end)
fix failed test: increase lpeg stack size
fix failed test: increase lpeg stack size
Lua
mit
starius/tree.lua
39bd3ee0696eba648f7f10919ba7e832abc0093e
src/jet/daemon/value_matcher.lua
src/jet/daemon/value_matcher.lua
local jutils = require'jet.utils' local tinsert = table.insert local less_than = function(other) return function(x) return x < other end end local greater_than = function(other) return function(x) return x > other end end local equals = function(other) return function(x) return x == other end end local equals_not = function(other) return function(x) return x ~= other end end local is_type = function(typ) return function(x) return type(x) == typ end end local generators = { lessThan = less_than, greaterThan = greater_than, equals = equals, equalsNot = equals_not, isType = is_type, } local access_field = jutils.access_field local is_table = function(tab) return type(tab) == 'table' end -- given the fetcher options table, creates a function which matches an element (state) value -- against some defined rule. local create_value_matcher = function(options) -- sorting by value implicit defines value matcher rule against expected type. if options.sort then if options.sort.byValue then options.value = options.value or {} options.value.isType = options.sort.byValue end if options.sort.byValueField then local tmp = options.sort.byValueField local fieldname,typ = pairs(tmp)(tmp) options.valueField = options.valueField or {} options.valueField[fieldname] = options.valueField[fieldname] or {} options.valueField[fieldname].isType = typ end end if not options.value and not options.valueField then return nil end local predicates = {} if options.value then for op,comp in pairs(options.value) do local gen = generators[op] if gen then tinsert(predicates,gen(comp)) end end elseif options.valueField then for field_str,conf in pairs(options.valueField) do local accessor = access_field(field_str) local field_predicates = {} for op,comp in pairs(conf) do local gen = generators[op] if gen then tinsert(field_predicates,gen(comp)) end end local field_pred = function(value) if not is_table(value) then return false end local ok,field = pcall(accessor,value) if not ok or not field then return false end for _,pred in ipairs(field_predicates) do if not pred(field) then return false end end return true end tinsert(predicates,field_pred) end end return function(value) for _,pred in ipairs(predicates) do local ok,match = pcall(pred,value) if not ok or not match then return false end end return true end end return { new = create_value_matcher, _generators = generators, _access_field = access_field, }
local jutils = require'jet.utils' local tinsert = table.insert local less_than = function(other) return function(x) return x < other end end local greater_than = function(other) return function(x) return x > other end end local equals = function(other) return function(x) return x == other end end local equals_not = function(other) return function(x) return x ~= other end end local is_type = function(typ) local lua_type if typ == 'object' then lua_type = 'table' else lua_type = typ end return function(x) return type(x) == lua_type end end local generators = { lessThan = less_than, greaterThan = greater_than, equals = equals, equalsNot = equals_not, isType = is_type, } local access_field = jutils.access_field local is_table = function(tab) return type(tab) == 'table' end -- given the fetcher options table, creates a function which matches an element (state) value -- against some defined rule. local create_value_matcher = function(options) -- sorting by value implicit defines value matcher rule against expected type. if options.sort then if options.sort.byValue then options.value = options.value or {} options.value.isType = options.sort.byValue end if options.sort.byValueField then local tmp = options.sort.byValueField local fieldname,typ = pairs(tmp)(tmp) options.valueField = options.valueField or {} options.valueField[fieldname] = options.valueField[fieldname] or {} options.valueField[fieldname].isType = typ end end if not options.value and not options.valueField then return nil end local predicates = {} if options.value then for op,comp in pairs(options.value) do local gen = generators[op] if gen then tinsert(predicates,gen(comp)) end end elseif options.valueField then for field_str,conf in pairs(options.valueField) do local accessor = access_field(field_str) local field_predicates = {} for op,comp in pairs(conf) do local gen = generators[op] if gen then tinsert(field_predicates,gen(comp)) end end local field_pred = function(value) if not is_table(value) then return false end local ok,field = pcall(accessor,value) if not ok or not field then return false end for _,pred in ipairs(field_predicates) do if not pred(field) then return false end end return true end tinsert(predicates,field_pred) end end return function(value) for _,pred in ipairs(predicates) do local ok,match = pcall(pred,value) if not ok or not match then return false end end return true end end return { new = create_value_matcher, _generators = generators, _access_field = access_field, }
fix isType predicate for objects (not tables as in lua)
fix isType predicate for objects (not tables as in lua)
Lua
mit
lipp/lua-jet
7b8f494b707f5b2d680f6ce8b526458ae426eafc
src/cosy/configuration.lua
src/cosy/configuration.lua
local Platform = require "cosy.platform" local Repository = require "cosy.repository" local repository = Repository.new () Repository.options (repository).create = function () end Repository.options (repository).import = function () end repository.internal = {} repository.default = require "cosy.configuration.default" local loaded = { repository.internal, repository.default, nil, -- required for 100% code coverage :-( } for _, path in ipairs (Platform.configuration.paths) do local filename = path .. "/cosy.conf" local content = Platform.configuration.read (filename) if content then if pcall (function () content = Platform.value.decode (content) repository [filename] = t loaded [#loaded+1] = repository [filename] end) then Platform.logger.debug { _ = "configuration:using", path = path, } else Platform.logger.warn { _ = "configuration:skipping", path = path, reason = t, } end end end repository.whole = { [Repository.depends] = loaded, } return repository.whole
local Platform = require "cosy.platform" local Repository = require "cosy.repository" local repository = Repository.new () Repository.options (repository).create = function () end Repository.options (repository).import = function () end repository.internal = {} repository.default = require "cosy.configuration.default" local loaded = { repository.internal, repository.default, nil, -- required for 100% code coverage :-( } for _, path in ipairs (Platform.configuration.paths) do local filename = path .. "/cosy.conf" local content = Platform.configuration.read (filename) if content then local ok, err = pcall (function () content = Platform.value.decode (content) repository [filename] = content loaded [#loaded+1] = repository [filename] end) if ok then Platform.logger.debug { _ = "configuration:using", path = path, } else Platform.logger.warn { _ = "configuration:skipping", path = path, reason = err, } end end end repository.whole = { [Repository.depends] = loaded, } return repository.whole
Fix configuration loading.
Fix configuration loading.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
b3f8bfe46adf71dfe21459d4c491d96a91170105
test/test-getaddrinfo.lua
test/test-getaddrinfo.lua
local uv = require 'couv' local SockAddr = uv.SockAddr local exports = {} exports['getaddrinfo.basic'] = function(test) coroutine.wrap(function() local name = 'localhost' local addresses = uv.getaddrinfo(name, nil, nil) test.ok(type(addresses), 'table') test.ok(#addresses > 0) for i, address in ipairs(addresses) do test.ok(type(address), 'table') test.ok(address.family == SockAddr.AF_INET or address.family == SockAddr.AF_INET6) test.ok(address.socktype == SockAddr.SOCK_DGRAM or address.socktype == SockAddr.SOCK_STREAM or address.socktype == SockAddr.SOCK_DGRAM + SockAddr.SOCK_STREAM) test.ok(address.protocol == 0 or address.protocol == SockAddr.IPPROTO_TCP or address.protocol == SockAddr.IPPROTO_UDP) test.ok(SockAddr.isSockAddr(address.addr)) end end)() uv.run() test.done() end exports['getaddrinfo.basic2'] = function(test) coroutine.wrap(function() local name = 'localhost' local hints = { family = SockAddr.AF_UNSPEC, socktype = SockAddr.SOCK_STREAM, protocol = SockAddr.IPPROTO_TCP } local addresses = uv.getaddrinfo(name, nil, hints) test.ok(type(addresses), 'table') test.ok(#addresses > 0) for i, address in ipairs(addresses) do test.ok(type(address), 'table') test.ok(address.family == SockAddr.AF_INET or address.family == SockAddr.AF_INET6) test.ok(address.socktype == SockAddr.SOCK_STREAM) test.ok(address.protocol == SockAddr.IPPROTO_TCP) test.ok(SockAddr.isSockAddr(address.addr)) end end)() uv.run() test.done() end exports['getaddrinfo.concurrent'] = function(test) local CONCURRENT_COUNT = 10 for i = 1, CONCURRENT_COUNT do coroutine.wrap(function() local name = 'localhost' local addresses = uv.getaddrinfo(name, nil, nil) test.ok(type(addresses), 'table') test.ok(#addresses > 0) for i, address in ipairs(addresses) do test.ok(type(address), 'table') test.ok(address.family == SockAddr.AF_INET or address.family == SockAddr.AF_INET6) test.ok(address.socktype == SockAddr.SOCK_DGRAM or address.socktype == SockAddr.SOCK_STREAM or address.socktype == SockAddr.SOCK_DGRAM + SockAddr.SOCK_STREAM) test.ok(address.protocol == 0 or address.protocol == SockAddr.IPPROTO_TCP or address.protocol == SockAddr.IPPROTO_UDP) test.ok(SockAddr.isSockAddr(address.addr)) end end)() end uv.run() test.done() end return exports
local uv = require 'couv' local SockAddr = uv.SockAddr local exports = {} exports['getaddrinfo.basic'] = function(test) coroutine.wrap(function() local name = 'localhost' local addresses = uv.getaddrinfo(name, nil, nil) test.ok(type(addresses), 'table') test.ok(#addresses > 0) for i, address in ipairs(addresses) do test.ok(type(address), 'table') test.ok(address.family == SockAddr.AF_INET or address.family == SockAddr.AF_INET6) test.ok(address.socktype == 0 or address.socktype == SockAddr.SOCK_DGRAM or address.socktype == SockAddr.SOCK_STREAM or address.socktype == SockAddr.SOCK_DGRAM + SockAddr.SOCK_STREAM) test.ok(address.protocol == 0 or address.protocol == SockAddr.IPPROTO_TCP or address.protocol == SockAddr.IPPROTO_UDP) test.ok(SockAddr.isSockAddr(address.addr)) end end)() uv.run() test.done() end exports['getaddrinfo.basic2'] = function(test) coroutine.wrap(function() local name = 'localhost' local hints = { family = SockAddr.AF_UNSPEC, socktype = SockAddr.SOCK_STREAM, protocol = SockAddr.IPPROTO_TCP } local addresses = uv.getaddrinfo(name, nil, hints) test.ok(type(addresses), 'table') test.ok(#addresses > 0) for i, address in ipairs(addresses) do test.ok(type(address), 'table') test.ok(address.family == SockAddr.AF_INET or address.family == SockAddr.AF_INET6) test.ok(address.socktype == SockAddr.SOCK_STREAM) test.ok(address.protocol == SockAddr.IPPROTO_TCP) test.ok(SockAddr.isSockAddr(address.addr)) end end)() uv.run() test.done() end exports['getaddrinfo.concurrent'] = function(test) local CONCURRENT_COUNT = 10 for i = 1, CONCURRENT_COUNT do coroutine.wrap(function() local name = 'localhost' local addresses = uv.getaddrinfo(name, nil, nil) test.ok(type(addresses), 'table') test.ok(#addresses > 0) for i, address in ipairs(addresses) do test.ok(type(address), 'table') test.ok(address.family == SockAddr.AF_INET or address.family == SockAddr.AF_INET6) test.ok(address.socktype == 0 or address.socktype == SockAddr.SOCK_DGRAM or address.socktype == SockAddr.SOCK_STREAM or address.socktype == SockAddr.SOCK_DGRAM + SockAddr.SOCK_STREAM) test.ok(address.protocol == 0 or address.protocol == SockAddr.IPPROTO_TCP or address.protocol == SockAddr.IPPROTO_UDP) test.ok(SockAddr.isSockAddr(address.addr)) end end)() end uv.run() test.done() end return exports
Fix test-getaddinfo to pass on Windows
Fix test-getaddinfo to pass on Windows
Lua
mit
hnakamur/couv,hnakamur/couv
7ece4be76fd8af14f9853fbffcd951f5e92e602c
triggerfield/homeland.lua
triggerfield/homeland.lua
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- INSERT INTO triggerfields VALUES (216,647,0,'triggerfield.homeland'); -- INSERT INTO triggerfields VALUES (216,648,0,'triggerfield.homeland'); -- INSERT INTO triggerfields VALUES (478,249,0,'triggerfield.homeland'); -- INSERT INTO triggerfields VALUES (478,250,0,'triggerfield.homeland'); -- INSERT INTO triggerfields VALUES (888,646,0,'triggerfield.homeland'); -- INSERT INTO triggerfields VALUES (889,646,0,'triggerfield.homeland'); require("base.common") module("triggerfield.homeland", package.seeall) function MoveToField(Character) questvalue={}; questvalue[1] = 166; --Cadomyr questvalue[2] = 167; --Galmair questvalue[3] = 168; --Runewick location={} location[1]=position(216,647,0); --Cadomyr location[2]=position(216,648,0); --Cadomyr location[3]=position(478,249,0); --Galmair location[4]=position(478,250,0); --Galmair location[5]=position(888,646,0); --Runewick location[6]=position(889,646,0); --Runewick if (Character:getQuestProgress(questvalue[1]) == 0) and (Character:getFaceTo() == 1 or Character:getFaceTo() == 2 or Character:getFaceTo() == 3) then --Didn't visit the triggerfield yet Character:setQuestProgress(questvalue[1],1); --player was here factionString="Cadomyr"; elseif (Character:getQuestProgress(questvalue[2]) == 0) and (Character:getFaceTo() == 1 or Character:getFaceTo() == 2 or Character:getFaceTo() == 3) then --Didn't visit the triggerfield yet Character:setQuestProgress(questvalue[2],1); --player was here factionString="Galmair"; elseif (Character:getQuestProgress(questvalue[3]) == 0) and (Character:getFaceTo() == 7 or Character:getFaceTo() == 0 or Character:getFaceTo() == 1) then --Didn't visit the triggerfield yet Character:setQuestProgress(questvalue[3],1); --player was here factionString="Runewick"; else return; --bailing out end local callbackHomeland = function(dialogHomeland) end; --empty callback if Character:getPlayerLanguage() == 0 then dialogHomeland = MessageDialog("Heimatland","Du verlsst nun das vergleichsweise sichere Heimatland von "..factionString..". Hinter diesem Punkt wirst du wahrscheinlich feindseligen Monstern begegnen. Sei auf der Hut!", callbackHomeland) else dialogHomeland = MessageDialog("Homeland", "You are leaving the comparable safe homeland of "..factionString..". Beyond this point, you will most likely encounter hostile monsters. Be on your guard!", callbackHomeland) end Character:requestMessageDialog(dialogHomeland) end
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- INSERT INTO triggerfields VALUES (216,647,0,'triggerfield.homeland'); -- INSERT INTO triggerfields VALUES (216,648,0,'triggerfield.homeland'); -- INSERT INTO triggerfields VALUES (478,249,0,'triggerfield.homeland'); -- INSERT INTO triggerfields VALUES (478,250,0,'triggerfield.homeland'); -- INSERT INTO triggerfields VALUES (888,646,0,'triggerfield.homeland'); -- INSERT INTO triggerfields VALUES (889,646,0,'triggerfield.homeland'); require("base.common") module("triggerfield.homeland", package.seeall) function MoveToField(Character) questvalue={}; questvalue[1] = 166; --Cadomyr questvalue[2] = 167; --Galmair questvalue[3] = 168; --Runewick location={} location[1]=position(216,647,0); --Cadomyr location[2]=position(216,648,0); --Cadomyr location[3]=position(478,249,0); --Galmair location[4]=position(478,250,0); --Galmair location[5]=position(888,646,0); --Runewick location[6]=position(889,646,0); --Runewick if (Character:getQuestProgress(questvalue[1]) == 0) and (Character:getFaceTo() == 1 or Character:getFaceTo() == 2 or Character:getFaceTo() == 3) and (Character.pos == location[1] or Character.pos == location[2]) then --Didn't visit the triggerfield yet Character:setQuestProgress(questvalue[1],1); --player was here factionString="Cadomyr"; elseif (Character:getQuestProgress(questvalue[2]) == 0) and (Character:getFaceTo() == 1 or Character:getFaceTo() == 2 or Character:getFaceTo() == 3) and (Character.pos == location[3] or Character.pos == location[4]) then --Didn't visit the triggerfield yet Character:setQuestProgress(questvalue[2],1); --player was here factionString="Galmair"; elseif (Character:getQuestProgress(questvalue[3]) == 0) and (Character:getFaceTo() == 7 or Character:getFaceTo() == 0 or Character:getFaceTo() == 1) and (Character.pos == location[5] or Character.pos == location[6]) then --Didn't visit the triggerfield yet Character:setQuestProgress(questvalue[3],1); --player was here factionString="Runewick"; else return; --bailing out end local callbackHomeland = function(dialogHomeland) end; --empty callback if Character:getPlayerLanguage() == 0 then dialogHomeland = MessageDialog("Heimatland","Du verlsst nun das vergleichsweise sichere Heimatland von "..factionString..". Hinter diesem Punkt wirst du wahrscheinlich feindseligen Monstern begegnen. Sei auf der Hut!", callbackHomeland) else dialogHomeland = MessageDialog("Homeland", "You are leaving the comparable safe homeland of "..factionString..". Beyond this point, you will most likely encounter hostile monsters. Be on your guard!", callbackHomeland) end Character:requestMessageDialog(dialogHomeland) end
Fix for homeland messages
Fix for homeland messages
Lua
agpl-3.0
Illarion-eV/Illarion-Content,vilarion/Illarion-Content,Baylamon/Illarion-Content,LaFamiglia/Illarion-Content,KayMD/Illarion-Content
8babe571063a11ba9a8f5f1fdc32e405ae178e7b
frontend/apps/reader/modules/readergoto.lua
frontend/apps/reader/modules/readergoto.lua
local InputContainer = require("ui/widget/container/inputcontainer") local InputDialog = require("ui/widget/inputdialog") local UIManager = require("ui/uimanager") local Event = require("ui/event") local SkimToWidget = require("apps/reader/skimtowidget") local _ = require("gettext") local ReaderGoto = InputContainer:new{ goto_menu_title = _("Go to"), skim_menu_title = _("Skim to"), } function ReaderGoto:init() self.ui.menu:registerToMainMenu(self) end function ReaderGoto:addToMainMenu(menu_items) -- insert goto command to main reader menu menu_items.go_to = { text = self.goto_menu_title, callback = function() self:onShowGotoDialog() end, } menu_items.skim_to = { text = self.skim_menu_title, callback = function() self:onShowSkimtoDialog() end, } end function ReaderGoto:onShowGotoDialog() local dialog_title, goto_btn, curr_page if self.document.info.has_pages then dialog_title = _("Go to Page") goto_btn = { is_enter_default = true, text = _("Page"), callback = function() self:gotoPage() end, } curr_page = self.ui.paging.current_page else dialog_title = _("Go to Location") goto_btn = { is_enter_default = true, text = _("Location"), callback = function() self:gotoPage() end, } -- only CreDocument has this method curr_page = self.document:getCurrentPage() end self.goto_dialog = InputDialog:new{ title = dialog_title, input_hint = "@"..curr_page.." (1 - "..self.document:getPageCount()..")", buttons = { { { text = _("Cancel"), enabled = true, callback = function() self:close() end, }, goto_btn, { text = _("Skim mode"), enabled = true, callback = function() self:close() self.skimto = SkimToWidget:new{ document = self.document, ui = self.ui, callback_switch_to_goto = function() UIManager:close(self.skimto) self:onShowGotoDialog() end, } UIManager:show(self.skimto) end, }, }, }, input_type = "number", } self.goto_dialog:onShowKeyboard() UIManager:show(self.goto_dialog) end function ReaderGoto:onShowSkimtoDialog() self.skimto = SkimToWidget:new{ document = self.document, ui = self.ui, callback_switch_to_goto = function() UIManager:close(self.skimto) self:onShowGotoDialog() end, } UIManager:show(self.skimto) end function ReaderGoto:close() UIManager:close(self.goto_dialog) end function ReaderGoto:gotoPage() local page_number = self.goto_dialog:getInputText() local relative_sign = page_number:sub(1, 1) local number = tonumber(page_number) if number then if relative_sign == "+" or relative_sign == "-" then self.ui:handleEvent(Event:new("GotoRelativePage", number)) else self.ui:handleEvent(Event:new("GotoPage", number)) end self:close() end end return ReaderGoto
local Event = require("ui/event") local InputContainer = require("ui/widget/container/inputcontainer") local InputDialog = require("ui/widget/inputdialog") local SkimToWidget = require("apps/reader/skimtowidget") local UIManager = require("ui/uimanager") local _ = require("gettext") local ReaderGoto = InputContainer:new{ goto_menu_title = _("Go to"), skim_menu_title = _("Skim to"), } function ReaderGoto:init() self.ui.menu:registerToMainMenu(self) end function ReaderGoto:addToMainMenu(menu_items) -- insert goto command to main reader menu menu_items.go_to = { text = self.goto_menu_title, callback = function() self:onShowGotoDialog() end, } menu_items.skim_to = { text = self.skim_menu_title, callback = function() self:onShowSkimtoDialog() end, } end function ReaderGoto:onShowGotoDialog() local dialog_title, goto_btn, curr_page if self.document.info.has_pages then dialog_title = _("Go to Page") goto_btn = { is_enter_default = true, text = _("Page"), callback = function() self:gotoPage() end, } curr_page = self.ui.paging.current_page else dialog_title = _("Go to Location") goto_btn = { is_enter_default = true, text = _("Location"), callback = function() self:gotoPage() end, } -- only CreDocument has this method curr_page = self.document:getCurrentPage() end self.goto_dialog = InputDialog:new{ title = dialog_title, input_hint = "@"..curr_page.." (1 - "..self.document:getPageCount()..")", buttons = { { { text = _("Cancel"), enabled = true, callback = function() self:close() end, }, { text = _("Skim mode"), enabled = true, callback = function() self:close() self.skimto = SkimToWidget:new{ document = self.document, ui = self.ui, callback_switch_to_goto = function() UIManager:close(self.skimto) self:onShowGotoDialog() end, } UIManager:show(self.skimto) end, }, goto_btn, }, }, input_type = "number", } self.goto_dialog:onShowKeyboard() UIManager:show(self.goto_dialog) end function ReaderGoto:onShowSkimtoDialog() self.skimto = SkimToWidget:new{ document = self.document, ui = self.ui, callback_switch_to_goto = function() UIManager:close(self.skimto) self:onShowGotoDialog() end, } UIManager:show(self.skimto) end function ReaderGoto:close() UIManager:close(self.goto_dialog) end function ReaderGoto:gotoPage() local page_number = self.goto_dialog:getInputText() local relative_sign = page_number:sub(1, 1) local number = tonumber(page_number) if number then if relative_sign == "+" or relative_sign == "-" then self.ui:handleEvent(Event:new("GotoRelativePage", number)) else self.ui:handleEvent(Event:new("GotoPage", number)) end self:close() end end return ReaderGoto
[fix] ReaderGoto button order
[fix] ReaderGoto button order
Lua
agpl-3.0
Frenzie/koreader,poire-z/koreader,NiLuJe/koreader,lgeek/koreader,Hzj-jie/koreader,Markismus/koreader,koreader/koreader,houqp/koreader,Frenzie/koreader,koreader/koreader,apletnev/koreader,mwoz123/koreader,poire-z/koreader,mihailim/koreader,NiLuJe/koreader,pazos/koreader
395cfe82acb1bd774a753a1cdb4504554a568ebc
lua/test/simple_template_container_test.lua
lua/test/simple_template_container_test.lua
local template_container = require("./lua/answer/simple_template_container") local str_starts_with = template_container.str_starts_with local function str_starts_with_test() local from, to = str_starts_with("abc", "abc") assert(from == 1 and to == 3) from, to = str_starts_with("abc", "ab") assert(from == 1 and to == 2) from, to = str_starts_with("", "abc") assert(from == 0 and to == 0) from, to = str_starts_with("2.71828", "") assert(from == 0 and to == 0) from, to = str_starts_with(nil, "abc") assert(from == 0 and to == 0) from, to = str_starts_with("3.14159", nil) assert(from == 0 and to == 0) -- position test from, to = str_starts_with("aaaa", "a") assert(from == 1 and to == 1) from, to = str_starts_with("aaaa", "a", 1) assert(from == 1 and to == 1) from, to = str_starts_with("aaaa", "a", 2) assert(from == 2 and to == 2) from, to = str_starts_with("aaaa", "aa", 2) assert(from == 2 and to == 3) -- UTF-8 test from, to = str_starts_with("丧尸暴龙兽", "丧") assert(from == 1 and to == 3) from, to = str_starts_with("丧尸暴龙兽", "暴龙", 7) assert(from == 7 and to == 12) ngx.say("str_starts_with_test success (12/12)") end local str_starts_with_re = template_container.str_starts_with_re local function str_starts_with_re_test() local from, to = str_starts_with_re("abc", "abc") assert(from == 1 and to == 3) from, to = str_starts_with_re(nil, "abc") assert(from == 0 and to == 0) from, to = str_starts_with_re("abc", nil) assert(from == 0 and to == 0) from, to = str_starts_with_re("", "") assert(from == 0 and to == 0) from, to = str_starts_with_re("abc", "bc", 1) assert(from == 0 and to == 0) from, to = str_starts_with_re("abc", "bc", 2) assert(from == 2 and to == 3) -- UTF-8 test from, to = str_starts_with_re("你为什么这么熟练啊", "为什么", 4) assert(from == 4 and to == 12) from, to = str_starts_with_re("你为什么这么熟练啊", "为什么", 1) assert(from == 0 and to == 0) ngx.say("str_starts_with_re_test success (8/8)") end local test_func = function() str_starts_with_test() str_starts_with_re_test() end return test_func
local template_container = require("./lua/answer/simple_template_container") local str_starts_with = template_container.str_starts_with local function str_starts_with_test() local from, to = str_starts_with("abc", "abc") assert(from == 1 and to == 3) from, to = str_starts_with("abc", "ab") assert(from == 1 and to == 2) from, to = str_starts_with("", "abc") assert(not from and not to) from, to = str_starts_with("2.71828", "") assert(not from and not to) from, to = str_starts_with(nil, "abc") assert(not from and not to) from, to = str_starts_with("3.14159", nil) assert(not from and not to) -- position test from, to = str_starts_with("aaaa", "a") assert(from == 1 and to == 1) from, to = str_starts_with("aaaa", "a", 1) assert(from == 1 and to == 1) from, to = str_starts_with("aaaa", "a", 2) assert(from == 2 and to == 2) from, to = str_starts_with("aaaa", "aa", 2) assert(from == 2 and to == 3) -- UTF-8 test from, to = str_starts_with("丧尸暴龙兽", "丧") assert(from == 1 and to == 3) from, to = str_starts_with("丧尸暴龙兽", "暴龙", 7) assert(from == 7 and to == 12) ngx.say("str_starts_with_test success (12/12)") end local str_starts_with_re = template_container.str_starts_with_re local function str_starts_with_re_test() local from, to = str_starts_with_re("abc", "abc") assert(from == 1 and to == 3) from, to = str_starts_with_re(nil, "abc") assert(not from and not to) from, to = str_starts_with_re("abc", nil) assert(not from and not to) from, to = str_starts_with_re("", "") assert(not from and not to) from, to = str_starts_with_re("abc", "bc", 1) assert(not from and not to) from, to = str_starts_with_re("abc", "bc", 2) assert(from == 2 and to == 3) -- UTF-8 test from, to = str_starts_with_re("你为什么这么熟练啊", "为什么", 4) assert(from == 4 and to == 12) from, to = str_starts_with_re("你为什么这么熟练啊", "为什么", 1) assert(not from and not to) ngx.say("str_starts_with_re_test success (8/8)") end local test_func = function() str_starts_with_test() str_starts_with_re_test() end return test_func
fix the template unit test to validate on nil
fix the template unit test to validate on nil
Lua
apache-2.0
zxteloiv/docomo-qa,zxteloiv/docomo-qa,zxteloiv/docomo-qa
83f0f1bed8481c5461a4609eb5ed7b3d9e7dcfac
Modules/Client/CoreGuiEnabler.lua
Modules/Client/CoreGuiEnabler.lua
--- Key based CoreGuiEnabler, singleton -- Use this class to load/unload CoreGuis / other GUIs, by disabling based upon keys -- Keys are additive, so if you have more than 1 disabled, it's ok. -- @module CoreGuiEnabler local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local Players = game:GetService("Players") local StarterGui = game:GetService("StarterGui") local UserInputService = game:GetService("UserInputService") local CharacterUtils = require("CharacterUtils") local CoreGuiEnabler = {} CoreGuiEnabler.__index = CoreGuiEnabler CoreGuiEnabler.ClassName = "CoreGuiEnabler" function CoreGuiEnabler.new() local self = setmetatable({}, CoreGuiEnabler) self._states = {} self:AddState(Enum.CoreGuiType.Backpack, function(isEnabled) StarterGui:SetCoreGuiEnabled(Enum.CoreGuiType.Backpack, isEnabled) CharacterUtils.unequipTools(Players.LocalPlayer) end) for _, coreGuiType in pairs(Enum.CoreGuiType:GetEnumItems()) do if not self._states[coreGuiType] then self:AddState(coreGuiType, function(isEnabled) StarterGui:SetCoreGuiEnabled(coreGuiType, isEnabled) end) end end self:_addStarterGuiState("TopbarEnabled") self:_addStarterGuiState("BadgesNotificationsActive") self:_addStarterGuiState("PointsNotificationsActive") self:AddState("ModalEnabled", function(isEnabled) UserInputService.ModalEnabled = not isEnabled end) self:AddState("MouseIconEnabled", function(isEnabled) UserInputService.MouseIconEnabled = isEnabled end) return self end function CoreGuiEnabler:_addStarterGuiState(stateName) local boolValueName = stateName .. "State" self[boolValueName] = Instance.new("BoolValue") self[boolValueName].Value = false self:AddState(stateName, function(isEnabled) self[boolValueName].Value = isEnabled local success, err = pcall(function() StarterGui:SetCore(stateName, isEnabled) end) if not success then warn("Failed to set core", err) end end) end function CoreGuiEnabler:AddState(key, coreGuiStateChangeFunc) assert(type(coreGuiStateChangeFunc) == "function", "must have coreGuiStateChangeFunc as function") assert(self._states[key] == nil, "state already exists") local realState = {} local lastState = true local function isEnabled() return next(realState) == nil end self._states[key] = setmetatable({}, { __newindex = function(_, index, value) rawset(realState, index, value) local newState = isEnabled() if lastState ~= newState then lastState = newState coreGuiStateChangeFunc(newState) end end; }) end function CoreGuiEnabler:Disable(key, coreGuiState) if not self._states[coreGuiState] then error(("[CoreGuiEnabler] - State '%s' does not exist."):format(tostring(coreGuiState))) end self._states[coreGuiState][key] = true return function() self:Enable(key, coreGuiState) end end function CoreGuiEnabler:Enable(key, coreGuiState) if not self._states[coreGuiState] then error(("[CoreGuiEnabler] - State '%s' does not exist."):format(tostring(coreGuiState))) end self._states[coreGuiState][key] = nil end return CoreGuiEnabler.new()
--- Key based CoreGuiEnabler, singleton -- Use this class to load/unload CoreGuis / other GUIs, by disabling based upon keys -- Keys are additive, so if you have more than 1 disabled, it's ok. -- @module CoreGuiEnabler local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local Players = game:GetService("Players") local StarterGui = game:GetService("StarterGui") local UserInputService = game:GetService("UserInputService") local CharacterUtils = require("CharacterUtils") local Maid = require("Maid") local CoreGuiEnabler = {} CoreGuiEnabler.__index = CoreGuiEnabler CoreGuiEnabler.ClassName = "CoreGuiEnabler" function CoreGuiEnabler.new() local self = setmetatable({}, CoreGuiEnabler) self._maid = Maid.new() self._states = {} self:AddState(Enum.CoreGuiType.Backpack, function(isEnabled) StarterGui:SetCoreGuiEnabled(Enum.CoreGuiType.Backpack, isEnabled) CharacterUtils.unequipTools(Players.LocalPlayer) end) for _, coreGuiType in pairs(Enum.CoreGuiType:GetEnumItems()) do if not self._states[coreGuiType] then self:AddState(coreGuiType, function(isEnabled) StarterGui:SetCoreGuiEnabled(coreGuiType, isEnabled) end) end end self:_addStarterGuiState("TopbarEnabled") self:_addStarterGuiState("BadgesNotificationsActive") self:_addStarterGuiState("PointsNotificationsActive") self:AddState("ModalEnabled", function(isEnabled) UserInputService.ModalEnabled = not isEnabled end) self:AddState("MouseIconEnabled", function(isEnabled) if isEnabled then UserInputService.MouseIconEnabled = isEnabled else UserInputService.MouseIconEnabled = false self._maid:GiveTask(UserInputService:GetPropertyChangedSignal("MouseIconEnabled"):Connect(function() UserInputService.MouseIconEnabled = false end)) end end) return self end function CoreGuiEnabler:_addStarterGuiState(stateName) local boolValueName = stateName .. "State" self[boolValueName] = Instance.new("BoolValue") self[boolValueName].Value = false self:AddState(stateName, function(isEnabled) self[boolValueName].Value = isEnabled local success, err = pcall(function() StarterGui:SetCore(stateName, isEnabled) end) if not success then warn("Failed to set core", err) end end) end function CoreGuiEnabler:AddState(key, coreGuiStateChangeFunc) assert(type(coreGuiStateChangeFunc) == "function", "must have coreGuiStateChangeFunc as function") assert(self._states[key] == nil, "state already exists") local realState = {} local lastState = true local function isEnabled() return next(realState) == nil end self._states[key] = setmetatable({}, { __newindex = function(_, index, value) rawset(realState, index, value) local newState = isEnabled() if lastState ~= newState then lastState = newState coreGuiStateChangeFunc(newState) end end; }) end function CoreGuiEnabler:Disable(key, coreGuiState) if not self._states[coreGuiState] then error(("[CoreGuiEnabler] - State '%s' does not exist."):format(tostring(coreGuiState))) end self._states[coreGuiState][key] = true return function() self:Enable(key, coreGuiState) end end function CoreGuiEnabler:Enable(key, coreGuiState) if not self._states[coreGuiState] then error(("[CoreGuiEnabler] - State '%s' does not exist."):format(tostring(coreGuiState))) end self._states[coreGuiState][key] = nil end return CoreGuiEnabler.new()
Fix Roblox messing with mouse icon enabled properties
Fix Roblox messing with mouse icon enabled properties
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
ac54464ff0b6b2a265a68ddaf07108b874704352
icesl-gallery/superquadrics.lua
icesl-gallery/superquadrics.lua
--[[ The MIT License (MIT) Copyright (c) 2015 Loïc Fejoz 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. ]] -- Directly applied from http://graphics.cs.illinois.edu/sites/default/files/zeno.pdf -- See IceSL's forum for the trick to multiply distance by 0.1. function superquadrics(radius, p) glsl = [[ //float minDistanceSphereTracing=0.001; float sum3(vec3 p) { return p.x + p.y + p.z; } // This might not be need but abs(vec3) does not work on my card. vec3 abs3(vec3 p) { return vec3(abs(p.x), abs(p.y), abs(p.z)); } float quadricsDistance(vec3 pt, float p) { vec3 v1 = pow(abs(pt), vec3(p)); float v2 = sum3(v1); return pow(v2, 1 / p); } float distanceEstimator(vec3 pt) { return 0.1 * (quadricsDistance(pt, <CST_P>) - <CST_RADIUS>); } ]] glsl = string.gsub(glsl, "<CST_P>", "" .. p) glsl = string.gsub(glsl, "<CST_RADIUS>", "" .. radius) return implicit(v(-radius, -radius, -radius), v(radius, radius, radius), glsl) end function samples() ps = {0.1, 0.2, 0.3, 0.5, 0.8, 1.0, 1.5, 1.8, 2.0, 5.0, 10.0} for k, p in pairs(ps) do emit(translate(20 * k, 0, 0) * scale(10) * superquadrics(1.0, p)) end end -- If used as main script then display samples -- see http://stackoverflow.com/questions/4521085/main-function-in-lua if not pcall(getfenv, 4) then samples() end
--[[ The MIT License (MIT) Copyright (c) 2015 Loïc Fejoz 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. ]] -- Directly applied from http://graphics.cs.illinois.edu/sites/default/files/zeno.pdf -- See IceSL's forum for the trick to multiply distance by 0.1. function superquadrics(radius, p) glsl = [[ uniform float uradius; uniform float up; float sum3(vec3 p) { return p.x + p.y + p.z; } // This might not be need but abs(vec3) does not work on my card. vec3 abs3(vec3 p) { return vec3(abs(p.x), abs(p.y), abs(p.z)); } float quadricsDistance(vec3 pt, float p) { vec3 v1 = pow(abs(pt), vec3(p)); float v2 = sum3(v1); return pow(v2, 1 / p); } float distanceEstimator(vec3 pt) { return 0.01 * (quadricsDistance(pt, up) - uradius); } ]] obj = implicit(v(-radius, -radius, -radius), v(radius, radius, radius), glsl) set_uniform_scalar(obj, "up", p) set_uniform_scalar(obj, "uradius", radius) return obj end function samples() ps = {0.1, 0.2, 0.3, 0.5, 0.8, 1.0, 1.5, 1.8, 2.0, 5.0, 10.0} for k, p in pairs(ps) do emit(translate(20 * k, 0, 0) * scale(10) * superquadrics(1.0, p)) end end -- If used as main script then display samples -- see http://stackoverflow.com/questions/4521085/main-function-in-lua if not pcall(getfenv, 4) then samples() end
fix(superquadrics): upgrade to latest version
fix(superquadrics): upgrade to latest version
Lua
mit
loic-fejoz/loic-fejoz-fabmoments,loic-fejoz/loic-fejoz-fabmoments,loic-fejoz/loic-fejoz-fabmoments
288db9c78a4b68d31bc3a647b2938b6238446b6a
src/patch/ui/hooks/frontend/modsmenu/lobby_skip.lua
src/patch/ui/hooks/frontend/modsmenu/lobby_skip.lua
-- Copyright (c) 2015-2017 Lymia Alusyia <lymia@lymiahugs.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. if _mpPatch and _mpPatch.loaded and ContextPtr:LookUpControl(".."):GetID() == "ModMultiplayerSelectScreen" then ContextPtr:SetShowHideHandler(function(bIsHide, _) if not bIsHide then HostButtonClick() UIManager:DequeuePopup(ContextPtr) end end) end
-- Copyright (c) 2015-2017 Lymia Alusyia <lymia@lymiahugs.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. if _mpPatch and _mpPatch.loaded and ContextPtr:LookUpControl(".."):GetID() == "ModMultiplayerSelectScreen" then _mpPatch.replaceGlobalFunction("ShowHideHandler", function(bIsHide, _) if not bIsHide then HostButtonClick() UIManager:DequeuePopup(ContextPtr) end end) end
Fix lobby.
Fix lobby.
Lua
mit
Lymia/MultiverseModManager,Lymia/MPPatch,Lymia/CivV_Mod2DLC,Lymia/MPPatch,Lymia/MPPatch,Lymia/MultiverseModManager,Lymia/MPPatch
53fb1d6222c2e7987a573b86ee8794278d481ee4
state/initialize.lua
state/initialize.lua
--[[-- INITIALIZE STATE ---- Initialize resources needed for the game. --]]-- local st = RunState.new() local mt = {__tostring = function() return 'RunState.initialize' end} setmetatable(st, mt) local World = getClass 'wyx.map.World' function st:init() -- entity databases HeroDB = getClass('wyx.entity.HeroEntityDB')() EnemyDB = getClass('wyx.entity.EnemyEntityDB')() ItemDB = getClass('wyx.entity.ItemEntityDB')() -- create systems RenderSystem = getClass('wyx.system.RenderSystem')() TimeSystem = getClass('wyx.system.TimeSystem')() CollisionSystem = getClass('wyx.system.CollisionSystem')() -- instantiate world self._world = World() end function st:enter(prevState, nextState) if Console then Console:show() end self._nextState = nextState self._loadStep = 0 self._doLoadStep = true end function st:leave() self._doLoadStep = nil self._loadStep = nil end function st:destroy() self._world:destroy() EntityRegistry = nil -- destroy systems RenderSystem:destroy() TimeSystem:destroy() CollisionSystem:destroy() RenderSystem = nil TimeSystem = nil CollisionSystem = nil -- destroy entity databases HeroDB:destroy() EnemyDB:destroy() ItemDB:destroy() HeroDB = nil EnemyDB = nil ItemDB = nil end function st:_makeEntityRegistry() -- TODO: make this not global EntityRegistry = self._world:getEntityRegistry() end -- make a ridiculous seed for the PRNG function st:_makeGameSeed() local time = os.time() local ltime = math.floor(love.timer.getTime() * 10000000) local mtime = math.floor(love.timer.getMicroTime() * 1000) local mx = love.mouse.getX() local my = love.mouse.getY() GAMESEED = (time - ltime) + mtime + mx + my math.randomseed(GAMESEED) math.random() math.random() math.random() local rand = math.floor(math.random() * 10000000) GAMESEED = GAMESEED + rand -- create the real global PRNG instance with this ridiculous seed Random = random.new(GAMESEED) end function st:_nextLoadStep() if nil ~= self._doLoadStep then self._doLoadStep = true end if nil ~= self._loadStep then self._loadStep = self._loadStep + 1 end end function st:_load() self._doLoadStep = false -- load entities switch(self._loadStep) { [1] = function() self:_makeGameSeed() end, [2] = function() self:_makeEntityRegistry() end, [3] = function() HeroDB:load() end, [4] = function() EnemyDB:load() end, [5] = function() ItemDB:load() end, [6] = function() RunState.switch(State[self._nextState], self._world) end, default = function() end, } cron.after(LOAD_DELAY, self._nextLoadStep, self) end function st:update(dt) if self._doLoadStep then self:_load() end end function st:draw() if Console then Console:draw() end end function st:keypressed(key, unicode) end return st
--[[-- INITIALIZE STATE ---- Initialize resources needed for the game. --]]-- local st = RunState.new() local mt = {__tostring = function() return 'RunState.initialize' end} setmetatable(st, mt) local World = getClass 'wyx.map.World' function st:init() -- entity databases HeroDB = getClass('wyx.entity.HeroEntityDB')() EnemyDB = getClass('wyx.entity.EnemyEntityDB')() ItemDB = getClass('wyx.entity.ItemEntityDB')() -- create systems RenderSystem = getClass('wyx.system.RenderSystem')() TimeSystem = getClass('wyx.system.TimeSystem')() CollisionSystem = getClass('wyx.system.CollisionSystem')() -- instantiate world self._world = World() end function st:enter(prevState, nextState) if Console then Console:show() end self._nextState = nextState self._loadStep = 0 self._doLoadStep = true end function st:leave() self._doLoadStep = nil self._loadStep = nil end function st:destroy() self._world:destroy() EntityRegistry = nil -- destroy systems RenderSystem:destroy() TimeSystem:destroy() CollisionSystem:destroy() RenderSystem = nil TimeSystem = nil CollisionSystem = nil -- destroy entity databases HeroDB:destroy() EnemyDB:destroy() ItemDB:destroy() HeroDB = nil EnemyDB = nil ItemDB = nil end function st:_makeEntityRegistry() -- TODO: make this not global EntityRegistry = self._world:getEntityRegistry() end -- make a ridiculous seed for the PRNG function st:_makeGameSeed() local time = os.time() local ltime = math.floor(love.timer.getTime() * 10000000) local mtime = math.floor(love.timer.getMicroTime() * 1000) local mx = love.mouse.getX() local my = love.mouse.getY() if time < ltime then time, ltime = ltime, time end GAMESEED = (time - ltime) + mtime + mx + my math.randomseed(GAMESEED) math.random() math.random() math.random() local rand = math.floor(math.random() * 10000000) GAMESEED = GAMESEED + rand -- create the real global PRNG instance with this ridiculous seed Random = random.new(GAMESEED) end function st:_nextLoadStep() if nil ~= self._doLoadStep then self._doLoadStep = true end if nil ~= self._loadStep then self._loadStep = self._loadStep + 1 end end function st:_load() self._doLoadStep = false -- load entities switch(self._loadStep) { [1] = function() self:_makeGameSeed() end, [2] = function() self:_makeEntityRegistry() end, [3] = function() HeroDB:load() end, [4] = function() EnemyDB:load() end, [5] = function() ItemDB:load() end, [6] = function() RunState.switch(State[self._nextState], self._world) end, default = function() end, } cron.after(LOAD_DELAY, self._nextLoadStep, self) end function st:update(dt) if self._doLoadStep then self:_load() end end function st:draw() if Console then Console:draw() end end function st:keypressed(key, unicode) end return st
fix negative game seeds
fix negative game seeds
Lua
mit
scottcs/wyx
d40e33b66e647b6eaba2cf23bac5b172c7575dfe
modules/data/prop.lua
modules/data/prop.lua
sptbl["prop"] = { files = { module = "prop.c", header = "prop.h", example = "ex_prop.c", }, func = { create = "sp_prop_create", destroy = "sp_prop_destroy", init = "sp_prop_init", compute = "sp_prop_compute", other = { sp_prop_reset = { description = "Resets prop back to starting position.", } } }, params = { mandatory = { { name = "str", type = "const char *", description = "Prop string to be parsed.", default = "N/A" }, }, optional = { { name = "bpm", type = "SPFLOAT", description = "Beats per minute of the prop string.", default = 60 }, } }, modtype = "module", description = [[Simple rhythmic notation gate generator Creates a gate using a simple rhythmic notation system called prop. When it reaches the end of the prop string, it will loop back to the beginning. Prop has a few basic rules: 1. A '+' denotes a on. A '-' denotes an off (rest). They each have an equal duration of a quarter note. 2. On and off values can be strung together to create equally spaced gates: +-+-- 3. When notes are enclosed in parantheses '()' following a positive integer N, their duration is reduced N times: ++2(+-) 4. When notes are enclosed in brackets '[]' following a positive integer N, their duration is scaled by a factor of N: ++2[++] 5. Parenthesis and brackets can be nested: +- 2[3(+2(++)+)]2(++) ]], ninputs = 0, noutputs = 1, inputs = { { name = "dummy", description = "This is doesn't do anything." }, }, outputs = { { name = "out", description = "Gate output." }, } }
sptbl["prop"] = { files = { module = "prop.c", header = "prop.h", example = "ex_prop.c", }, func = { create = "sp_prop_create", destroy = "sp_prop_destroy", init = "sp_prop_init", compute = "sp_prop_compute", other = { sp_prop_reset = { description = "Resets prop back to starting position.", args = { } } } }, params = { mandatory = { { name = "str", type = "const char *", description = "Prop string to be parsed.", default = "N/A" }, }, optional = { { name = "bpm", type = "SPFLOAT", description = "Beats per minute of the prop string.", default = 60 }, } }, modtype = "module", description = [[Simple rhythmic notation gate generator Creates a gate using a simple rhythmic notation system called prop. When it reaches the end of the prop string, it will loop back to the beginning. Prop has a few basic rules: 1. A '+' denotes a on. A '-' denotes an off (rest). They each have an equal duration of a quarter note. 2. On and off values can be strung together to create equally spaced gates: +-+-- 3. When notes are enclosed in parantheses '()' following a positive integer N, their duration is reduced N times: ++2(+-) 4. When notes are enclosed in brackets '[]' following a positive integer N, their duration is scaled by a factor of N: ++2[++] 5. Parenthesis and brackets can be nested: +- 2[3(+2(++)+)]2(++) ]], ninputs = 0, noutputs = 1, inputs = { { name = "dummy", description = "This is doesn't do anything." }, }, outputs = { { name = "out", description = "Gate output." }, } }
prop: doc fix
prop: doc fix
Lua
mit
aure/Soundpipe,narner/Soundpipe,narner/Soundpipe,narner/Soundpipe,narner/Soundpipe,aure/Soundpipe,aure/Soundpipe,aure/Soundpipe
5353fc66cadec019c8f893c9328ad35b7ebae4f0
game/scripts/vscripts/data/abilities.lua
game/scripts/vscripts/data/abilities.lua
LINKED_ABILITIES = { shredder_chakram_2 = {"shredder_return_chakram_2"}, shredder_chakram = {"shredder_return_chakram"}, kunkka_x_marks_the_spot = {"kunkka_return"}, life_stealer_infest = {"life_stealer_control", "life_stealer_consume"}, rubick_telekinesis = {"rubick_telekinesis_land"}, bane_nightmare = {"bane_nightmare_end"}, phoenix_icarus_dive = {"phoenix_icarus_dive_stop"}, phoenix_fire_spirits = {"phoenix_launch_fire_spirit"}, ancient_apparition_ice_blast = {"ancient_apparition_ice_blast_release"}, wisp_tether_aghanims = {"wisp_tether_break_aghanims"}, alchemist_unstable_concoction = {"alchemist_unstable_concoction_throw"}, monkey_king_mischief = {"monkey_king_untransform"}, monkey_king_primal_spring = {"monkey_king_primal_spring_early"}, } NOT_MULTICASTABLE_ABILITIES = { "ogre_magi_bloodlust", "ogre_magi_fireblast", "ogre_magi_ignite", "ogre_magi_unrefined_fireblast", "ogre_magi_multicast_arena", "invoker_quas", "invoker_wex", "invoker_exort", "invoker_invoke", "shredder_chakram", "alchemist_unstable_concoction", "alchemist_unstable_concoction_throw", "riki_pocket_riki", "elder_titan_ancestral_spirit", "elder_titan_return_spirit", "ember_spirit_sleight_of_fist", } REFRESH_LIST_IGNORE_REFRESHER = { item_refresher_arena = true, item_aegis_arena = true, item_refresher_core = true, omniknight_select_allies = true, omniknight_select_enemies = true, } REFRESH_LIST_IGNORE_OMNIKNIGHT_SELECT = { item_refresher_arena = true, item_aegis_arena = true, item_refresher_core = true, item_titanium_bar = true, item_coffee_bean = true, omniknight_select_allies = true, omniknight_select_enemies = true, } REFRESH_LIST_IGNORE_BODY_RECONSTRUCTION = { item_refresher_arena = true, item_aegis_arena = true, item_refresher_core = true, item_titanium_bar = true, item_black_king_bar_arena = true, item_black_king_bar_2 = true, item_black_king_bar_3 = true, item_black_king_bar_4 = true, item_black_king_bar_5 = true, item_black_king_bar_6 = true, item_coffee_bean = true, destroyer_body_reconstruction = true, } REFRESH_LIST_IGNORE_REARM = { tinker_rearm_arena = true, item_refresher_arena = true, item_aegis_arena = true, item_refresher_core = true, item_titanium_bar = true, item_guardian_greaves_arena = true, item_demon_king_bar = true, item_pipe = true, item_arcane_boots = true, item_helm_of_the_dominator = true, item_sphere = true, item_necronomicon = true, item_hand_of_midas_arena = true, item_hand_of_midas_2_arena = true, item_hand_of_midas_3_arena = true, item_mekansm_arena = true, item_mekansm_2 = true, item_black_king_bar_arena = true, item_black_king_bar_2 = true, item_black_king_bar_3 = true, item_black_king_bar_4 = true, item_black_king_bar_5 = true, item_black_king_bar_6 = true, omniknight_select_allies = true, omniknight_select_enemies = true, destroyer_body_reconstruction = true, stargazer_cosmic_countdown = true, } COFFEE_BEAN_NOT_REFRESHABLE = { zuus_cloud = true, monkey_king_boundless_strike = true, dazzle_shallow_grave = true, } BOSS_BANNED_ABILITIES = { item_heart_cyclone = true, item_blink_staff = true, item_urn_of_demons = true, razor_static_link = true, tusk_walrus_kick = true, death_prophet_spirit_siphon = true, item_force_staff = true, item_hurricane_pike = true, rubick_telekinesis = true, item_demon_king_bar = true, } -- "CalculateSpellDamageTooltip" "0" SPELL_AMPLIFY_NOT_SCALABLE_MODIFIERS = { zuus_static_field = true, enigma_midnight_pulse = true, morphling_adaptive_strike_agi = true, nyx_assassin_mana_burn = true, elder_titan_earth_splitter = true, necrolyte_reapers_scythe = true, doom_bringer_infernal_blade = true, phoenix_sun_ray = true, silencer_glaives_of_wisdom = true, winter_wyvern_arctic_burn = true, obsidian_destroyer_sanity_eclipse = true, centaur_stampede = true, obsidian_destroyer_arcane_orb = true, spectre_dispersion = true, skywrath_mage_arcane_bolt = true, centaur_return = true, huskar_life_break = true, } OCTARINE_NOT_LIFESTALABLE_ABILITIES = { ["freya_pain_reflection"] = true, ["spectre_dispersion"] = true, } ARENA_NOT_CASTABLE_ABILITIES = { ["techies_land_mines"] = GetAbilitySpecial("techies_land_mines", "radius"), ["techies_stasis_trap"] = GetAbilitySpecial("techies_stasis_trap", "activation_radius"), ["techies_remote_mines"] = GetAbilitySpecial("techies_land_mines", "radius"), ["invoker_chaos_meteor"] = 1100, ["disruptor_thunder_strike"] = GetAbilitySpecial("disruptor_thunder_strike", "radius"), ["pugna_nether_blast"] = GetAbilitySpecial("pugna_nether_blast", "radius"), ["enigma_midnight_pulse"] = GetAbilitySpecial("enigma_midnight_pulse", "radius"), ["abyssal_underlord_firestorm"] = GetAbilitySpecial("abyssal_underlord_firestorm", "radius"), ["skywrath_mage_mystic_flare"] = GetAbilitySpecial("skywrath_mage_mystic_flare", "radius"), ["warlock_upheaval_arena"] = GetAbilitySpecial("warlock_upheaval_arena", "aoe"), } PERCENT_DAMAGE_MODIFIERS = { } DISABLE_HELP_ABILITIES = { wisp_tether_aghanims = true, keeper_of_the_light_recall = true, chen_test_of_faith_teleport = true, oracle_purifying_flames = true, kunkka_x_marks_the_spot = true, bloodseeker_bloodrage = true, bane_nightmare = true, winter_wyvern_cold_embrace = true, }
LINKED_ABILITIES = { shredder_chakram_2 = {"shredder_return_chakram_2"}, shredder_chakram = {"shredder_return_chakram"}, kunkka_x_marks_the_spot = {"kunkka_return"}, life_stealer_infest = {"life_stealer_control", "life_stealer_consume"}, rubick_telekinesis = {"rubick_telekinesis_land"}, bane_nightmare = {"bane_nightmare_end"}, phoenix_icarus_dive = {"phoenix_icarus_dive_stop"}, phoenix_fire_spirits = {"phoenix_launch_fire_spirit"}, ancient_apparition_ice_blast = {"ancient_apparition_ice_blast_release"}, wisp_tether_aghanims = {"wisp_tether_break_aghanims"}, alchemist_unstable_concoction = {"alchemist_unstable_concoction_throw"}, monkey_king_mischief = {"monkey_king_untransform"}, monkey_king_primal_spring = {"monkey_king_primal_spring_early"}, } NOT_MULTICASTABLE_ABILITIES = { "ogre_magi_bloodlust", "ogre_magi_fireblast", "ogre_magi_ignite", "ogre_magi_unrefined_fireblast", "ogre_magi_multicast_arena", "invoker_quas", "invoker_wex", "invoker_exort", "invoker_invoke", "shredder_chakram", "alchemist_unstable_concoction", "alchemist_unstable_concoction_throw", "riki_pocket_riki", "elder_titan_ancestral_spirit", "elder_titan_return_spirit", "ember_spirit_sleight_of_fist", } REFRESH_LIST_IGNORE_REFRESHER = { item_refresher_arena = true, item_aegis_arena = true, item_refresher_core = true, omniknight_select_allies = true, omniknight_select_enemies = true, } REFRESH_LIST_IGNORE_OMNIKNIGHT_SELECT = { item_refresher_arena = true, item_aegis_arena = true, item_refresher_core = true, item_titanium_bar = true, item_coffee_bean = true, omniknight_select_allies = true, omniknight_select_enemies = true, } REFRESH_LIST_IGNORE_BODY_RECONSTRUCTION = { item_refresher_arena = true, item_aegis_arena = true, item_refresher_core = true, item_titanium_bar = true, item_black_king_bar_arena = true, item_black_king_bar_2 = true, item_black_king_bar_3 = true, item_black_king_bar_4 = true, item_black_king_bar_5 = true, item_black_king_bar_6 = true, item_coffee_bean = true, destroyer_body_reconstruction = true, } REFRESH_LIST_IGNORE_REARM = { tinker_rearm_arena = true, item_refresher_arena = true, item_aegis_arena = true, item_refresher_core = true, item_titanium_bar = true, item_guardian_greaves_arena = true, item_demon_king_bar = true, item_pipe = true, item_arcane_boots = true, item_helm_of_the_dominator = true, item_sphere = true, item_necronomicon = true, item_hand_of_midas_arena = true, item_hand_of_midas_2_arena = true, item_hand_of_midas_3_arena = true, item_mekansm_arena = true, item_mekansm_2 = true, item_black_king_bar_arena = true, item_black_king_bar_2 = true, item_black_king_bar_3 = true, item_black_king_bar_4 = true, item_black_king_bar_5 = true, item_black_king_bar_6 = true, omniknight_select_allies = true, omniknight_select_enemies = true, destroyer_body_reconstruction = true, stargazer_cosmic_countdown = true, } COFFEE_BEAN_NOT_REFRESHABLE = { zuus_cloud = true, monkey_king_boundless_strike = true, dazzle_shallow_grave = true, } BOSS_BANNED_ABILITIES = { item_heart_cyclone = true, item_blink_staff = true, item_urn_of_demons = true, razor_static_link = true, tusk_walrus_kick = true, death_prophet_spirit_siphon = true, item_force_staff = true, item_hurricane_pike = true, rubick_telekinesis = true, item_demon_king_bar = true, morphling_adaptive_strike_str = true, } -- "CalculateSpellDamageTooltip" "0" SPELL_AMPLIFY_NOT_SCALABLE_MODIFIERS = { zuus_static_field = true, enigma_midnight_pulse = true, morphling_adaptive_strike_agi = true, nyx_assassin_mana_burn = true, elder_titan_earth_splitter = true, necrolyte_reapers_scythe = true, doom_bringer_infernal_blade = true, phoenix_sun_ray = true, silencer_glaives_of_wisdom = true, winter_wyvern_arctic_burn = true, obsidian_destroyer_sanity_eclipse = true, centaur_stampede = true, obsidian_destroyer_arcane_orb = true, spectre_dispersion = true, skywrath_mage_arcane_bolt = true, centaur_return = true, huskar_life_break = true, } OCTARINE_NOT_LIFESTALABLE_ABILITIES = { ["freya_pain_reflection"] = true, ["spectre_dispersion"] = true, } ARENA_NOT_CASTABLE_ABILITIES = { ["techies_land_mines"] = GetAbilitySpecial("techies_land_mines", "radius"), ["techies_stasis_trap"] = GetAbilitySpecial("techies_stasis_trap", "activation_radius"), ["techies_remote_mines"] = GetAbilitySpecial("techies_land_mines", "radius"), ["invoker_chaos_meteor"] = 1100, ["disruptor_thunder_strike"] = GetAbilitySpecial("disruptor_thunder_strike", "radius"), ["pugna_nether_blast"] = GetAbilitySpecial("pugna_nether_blast", "radius"), ["enigma_midnight_pulse"] = GetAbilitySpecial("enigma_midnight_pulse", "radius"), ["abyssal_underlord_firestorm"] = GetAbilitySpecial("abyssal_underlord_firestorm", "radius"), ["skywrath_mage_mystic_flare"] = GetAbilitySpecial("skywrath_mage_mystic_flare", "radius"), ["warlock_upheaval_arena"] = GetAbilitySpecial("warlock_upheaval_arena", "aoe"), } PERCENT_DAMAGE_MODIFIERS = { } DISABLE_HELP_ABILITIES = { wisp_tether_aghanims = true, keeper_of_the_light_recall = true, chen_test_of_faith_teleport = true, oracle_purifying_flames = true, kunkka_x_marks_the_spot = true, bloodseeker_bloodrage = true, bane_nightmare = true, winter_wyvern_cold_embrace = true, }
fix(abilities): Morphling - Adaptive Strike (strength) pushes bosses
fix(abilities): Morphling - Adaptive Strike (strength) pushes bosses Fixes #37
Lua
mit
ark120202/aabs
c5db70b03b6ca83fefad0939881e760614897106
mod_auth_joomla/mod_auth_joomla.lua
mod_auth_joomla/mod_auth_joomla.lua
-- Joomla authentication backend for Prosody -- -- Copyright (C) 2011 Waqas Hussain -- local new_sasl = require "util.sasl".new; local nodeprep = require "util.encodings".stringprep.nodeprep; local saslprep = require "util.encodings".stringprep.saslprep; local DBI = require "DBI" local md5 = require "util.hashes".md5; local uuid_gen = require "util.uuid".generate; local connection; local params = module:get_option("sql"); local resolve_relative_path = require "core.configmanager".resolve_relative_path; local function test_connection() if not connection then return nil; end if connection:ping() then return true; else module:log("debug", "Database connection closed"); connection = nil; end end local function connect() if not test_connection() then prosody.unlock_globals(); local dbh, err = DBI.Connect( params.driver, params.database, params.username, params.password, params.host, params.port ); prosody.lock_globals(); if not dbh then module:log("debug", "Database connection failed: %s", tostring(err)); return nil, err; end module:log("debug", "Successfully connected to database"); dbh:autocommit(true); -- don't run in transaction connection = dbh; return connection; end end do -- process options to get a db connection params = params or { driver = "SQLite3" }; if params.driver == "SQLite3" then params.database = resolve_relative_path(prosody.paths.data or ".", params.database or "prosody.sqlite"); end assert(params.driver and params.database, "Both the SQL driver and the database need to be specified"); assert(connect()); end local function getsql(sql, ...) if params.driver == "PostgreSQL" then sql = sql:gsub("`", "\""); end if not test_connection() then connect(); end -- do prepared statement stuff local stmt, err = connection:prepare(sql); if not stmt and not test_connection() then error("connection failed"); end if not stmt then module:log("error", "QUERY FAILED: %s %s", err, debug.traceback()); return nil, err; end -- run query local ok, err = stmt:execute(...); if not ok and not test_connection() then error("connection failed"); end if not ok then return nil, err; end return stmt; end local function setsql(sql, ...) local stmt, err = getsql(sql, ...); if not stmt then return stmt, err; end return stmt:affected(); end local function get_password(username) local stmt, err = getsql("SELECT `password` FROM `jos_users` WHERE `username`=?", username); if stmt then for row in stmt:rows(true) do return row.password; end end end local function getCryptedPassword(plaintext, salt) local salted = plaintext..salt; return md5(salted, true); end local function joomlaCheckHash(password, hash) local crypt, salt = hash:match("^([^:]*):(.*)$"); return (crypt or hash) == getCryptedPassword(password, salt or ''); end local function joomlaCreateHash(password) local salt = uuid_gen():gsub("%-", ""); local crypt = getCryptedPassword(password, salt); return crypt..':'..salt; end provider = { name = "joomla" }; function provider.test_password(username, password) local hash = get_password(username); return hash and joomlaCheckHash(password, hash); end function provider.user_exists(username) module:log("debug", "test user %s existence", username); return get_password(username) and true; end function provider.get_password(username) return nil, "Getting password is not supported."; end function provider.set_password(username, password) local hash = joomlaCreateHash(password); local stmt, err = setsql("UPDATE `jos_users` SET `password`=? WHERE `username`=?", hash, username); return stmt and true, err; end function provider.create_user(username, password) return nil, "Account creation/modification not supported."; end local escapes = { [" "] = "\\20"; ['"'] = "\\22"; ["&"] = "\\26"; ["'"] = "\\27"; ["/"] = "\\2f"; [":"] = "\\3a"; ["<"] = "\\3c"; [">"] = "\\3e"; ["@"] = "\\40"; ["\\"] = "\\5c"; }; local unescapes = {}; for k,v in pairs(escapes) do unescapes[v] = k; end local function jid_escape(s) return s and (s:gsub(".", escapes)); end local function jid_unescape(s) return s and (s:gsub("\\%x%x", unescapes)); end function provider.get_sasl_handler() local sasl = {}; function sasl:clean_clone() return provider.get_sasl_handler(); end function sasl:mechanisms() return { PLAIN = true; }; end function sasl:select(mechanism) if not self.selected and mechanism == "PLAIN" then self.selected = mechanism; return true; end end function sasl:process(message) if not message then return "failure", "malformed-request"; end local authorization, authentication, password = message:match("^([^%z]*)%z([^%z]+)%z([^%z]+)"); if not authorization then return "failure", "malformed-request"; end authentication = saslprep(authentication); password = saslprep(password); if (not password) or (password == "") or (not authentication) or (authentication == "") then return "failure", "malformed-request", "Invalid username or password."; end local function test(authentication) local prepped = nodeprep(authentication); local normalized = jid_unescape(prepped); return normalized and provider.test_password(normalized, password) and prepped; end local username = test(authentication) or test(jid_escape(authentication)); if username then self.username = username; return "success"; end return "failure", "not-authorized", "Unable to authorize you with the authentication credentials you've sent."; end return sasl; end module:add_item("auth-provider", provider);
-- Joomla authentication backend for Prosody -- -- Copyright (C) 2011 Waqas Hussain -- local new_sasl = require "util.sasl".new; local nodeprep = require "util.encodings".stringprep.nodeprep; local saslprep = require "util.encodings".stringprep.saslprep; local DBI = require "DBI" local md5 = require "util.hashes".md5; local uuid_gen = require "util.uuid".generate; local connection; local params = module:get_option("sql"); local prefix = params and params.prefix or "jos_"; local resolve_relative_path = require "core.configmanager".resolve_relative_path; local function test_connection() if not connection then return nil; end if connection:ping() then return true; else module:log("debug", "Database connection closed"); connection = nil; end end local function connect() if not test_connection() then prosody.unlock_globals(); local dbh, err = DBI.Connect( params.driver, params.database, params.username, params.password, params.host, params.port ); prosody.lock_globals(); if not dbh then module:log("debug", "Database connection failed: %s", tostring(err)); return nil, err; end module:log("debug", "Successfully connected to database"); dbh:autocommit(true); -- don't run in transaction connection = dbh; return connection; end end do -- process options to get a db connection params = params or { driver = "SQLite3" }; if params.driver == "SQLite3" then params.database = resolve_relative_path(prosody.paths.data or ".", params.database or "prosody.sqlite"); end assert(params.driver and params.database, "Both the SQL driver and the database need to be specified"); assert(connect()); end local function getsql(sql, ...) if params.driver == "PostgreSQL" then sql = sql:gsub("`", "\""); end if not test_connection() then connect(); end -- do prepared statement stuff local stmt, err = connection:prepare(sql); if not stmt and not test_connection() then error("connection failed"); end if not stmt then module:log("error", "QUERY FAILED: %s %s", err, debug.traceback()); return nil, err; end -- run query local ok, err = stmt:execute(...); if not ok and not test_connection() then error("connection failed"); end if not ok then return nil, err; end return stmt; end local function setsql(sql, ...) local stmt, err = getsql(sql, ...); if not stmt then return stmt, err; end return stmt:affected(); end local function get_password(username) local stmt, err = getsql("SELECT `password` FROM `"..prefix.."users` WHERE `username`=?", username); if stmt then for row in stmt:rows(true) do return row.password; end end end local function getCryptedPassword(plaintext, salt) local salted = plaintext..salt; return md5(salted, true); end local function joomlaCheckHash(password, hash) local crypt, salt = hash:match("^([^:]*):(.*)$"); return (crypt or hash) == getCryptedPassword(password, salt or ''); end local function joomlaCreateHash(password) local salt = uuid_gen():gsub("%-", ""); local crypt = getCryptedPassword(password, salt); return crypt..':'..salt; end provider = { name = "joomla" }; function provider.test_password(username, password) local hash = get_password(username); return hash and joomlaCheckHash(password, hash); end function provider.user_exists(username) module:log("debug", "test user %s existence", username); return get_password(username) and true; end function provider.get_password(username) return nil, "Getting password is not supported."; end function provider.set_password(username, password) local hash = joomlaCreateHash(password); local stmt, err = setsql("UPDATE `"..prefix.."users` SET `password`=? WHERE `username`=?", hash, username); return stmt and true, err; end function provider.create_user(username, password) return nil, "Account creation/modification not supported."; end local escapes = { [" "] = "\\20"; ['"'] = "\\22"; ["&"] = "\\26"; ["'"] = "\\27"; ["/"] = "\\2f"; [":"] = "\\3a"; ["<"] = "\\3c"; [">"] = "\\3e"; ["@"] = "\\40"; ["\\"] = "\\5c"; }; local unescapes = {}; for k,v in pairs(escapes) do unescapes[v] = k; end local function jid_escape(s) return s and (s:gsub(".", escapes)); end local function jid_unescape(s) return s and (s:gsub("\\%x%x", unescapes)); end function provider.get_sasl_handler() local sasl = {}; function sasl:clean_clone() return provider.get_sasl_handler(); end function sasl:mechanisms() return { PLAIN = true; }; end function sasl:select(mechanism) if not self.selected and mechanism == "PLAIN" then self.selected = mechanism; return true; end end function sasl:process(message) if not message then return "failure", "malformed-request"; end local authorization, authentication, password = message:match("^([^%z]*)%z([^%z]+)%z([^%z]+)"); if not authorization then return "failure", "malformed-request"; end authentication = saslprep(authentication); password = saslprep(password); if (not password) or (password == "") or (not authentication) or (authentication == "") then return "failure", "malformed-request", "Invalid username or password."; end local function test(authentication) local prepped = nodeprep(authentication); local normalized = jid_unescape(prepped); return normalized and provider.test_password(normalized, password) and prepped; end local username = test(authentication) or test(jid_escape(authentication)); if username then self.username = username; return "success"; end return "failure", "not-authorized", "Unable to authorize you with the authentication credentials you've sent."; end return sasl; end module:add_item("auth-provider", provider);
mod_auth_joomla: Added config option sql.prefix (default = "jos_").
mod_auth_joomla: Added config option sql.prefix (default = "jos_").
Lua
mit
NSAKEY/prosody-modules,olax/prosody-modules,vince06fr/prosody-modules,obelisk21/prosody-modules,crunchuser/prosody-modules,stephen322/prosody-modules,softer/prosody-modules,stephen322/prosody-modules,vince06fr/prosody-modules,iamliqiang/prosody-modules,joewalker/prosody-modules,Craige/prosody-modules,syntafin/prosody-modules,vfedoroff/prosody-modules,1st8/prosody-modules,mmusial/prosody-modules,mardraze/prosody-modules,obelisk21/prosody-modules,softer/prosody-modules,dhotson/prosody-modules,dhotson/prosody-modules,obelisk21/prosody-modules,jkprg/prosody-modules,Craige/prosody-modules,BurmistrovJ/prosody-modules,mardraze/prosody-modules,olax/prosody-modules,syntafin/prosody-modules,vfedoroff/prosody-modules,either1/prosody-modules,asdofindia/prosody-modules,joewalker/prosody-modules,LanceJenkinZA/prosody-modules,vfedoroff/prosody-modules,apung/prosody-modules,asdofindia/prosody-modules,amenophis1er/prosody-modules,stephen322/prosody-modules,obelisk21/prosody-modules,cryptotoad/prosody-modules,joewalker/prosody-modules,olax/prosody-modules,stephen322/prosody-modules,crunchuser/prosody-modules,heysion/prosody-modules,prosody-modules/import,jkprg/prosody-modules,amenophis1er/prosody-modules,cryptotoad/prosody-modules,asdofindia/prosody-modules,Craige/prosody-modules,crunchuser/prosody-modules,1st8/prosody-modules,BurmistrovJ/prosody-modules,softer/prosody-modules,brahmi2/prosody-modules,vince06fr/prosody-modules,vfedoroff/prosody-modules,asdofindia/prosody-modules,1st8/prosody-modules,iamliqiang/prosody-modules,guilhem/prosody-modules,crunchuser/prosody-modules,apung/prosody-modules,heysion/prosody-modules,syntafin/prosody-modules,prosody-modules/import,obelisk21/prosody-modules,stephen322/prosody-modules,BurmistrovJ/prosody-modules,mardraze/prosody-modules,softer/prosody-modules,amenophis1er/prosody-modules,LanceJenkinZA/prosody-modules,LanceJenkinZA/prosody-modules,amenophis1er/prosody-modules,drdownload/prosody-modules,cryptotoad/prosody-modules,iamliqiang/prosody-modules,drdownload/prosody-modules,vfedoroff/prosody-modules,BurmistrovJ/prosody-modules,guilhem/prosody-modules,apung/prosody-modules,Craige/prosody-modules,prosody-modules/import,heysion/prosody-modules,NSAKEY/prosody-modules,brahmi2/prosody-modules,apung/prosody-modules,syntafin/prosody-modules,softer/prosody-modules,heysion/prosody-modules,1st8/prosody-modules,cryptotoad/prosody-modules,either1/prosody-modules,LanceJenkinZA/prosody-modules,mmusial/prosody-modules,Craige/prosody-modules,joewalker/prosody-modules,guilhem/prosody-modules,joewalker/prosody-modules,NSAKEY/prosody-modules,drdownload/prosody-modules,asdofindia/prosody-modules,crunchuser/prosody-modules,cryptotoad/prosody-modules,drdownload/prosody-modules,either1/prosody-modules,jkprg/prosody-modules,olax/prosody-modules,jkprg/prosody-modules,dhotson/prosody-modules,amenophis1er/prosody-modules,olax/prosody-modules,mmusial/prosody-modules,prosody-modules/import,mmusial/prosody-modules,iamliqiang/prosody-modules,mardraze/prosody-modules,brahmi2/prosody-modules,heysion/prosody-modules,BurmistrovJ/prosody-modules,guilhem/prosody-modules,dhotson/prosody-modules,brahmi2/prosody-modules,vince06fr/prosody-modules,vince06fr/prosody-modules,jkprg/prosody-modules,1st8/prosody-modules,mardraze/prosody-modules,either1/prosody-modules,NSAKEY/prosody-modules,prosody-modules/import,either1/prosody-modules,mmusial/prosody-modules,syntafin/prosody-modules,dhotson/prosody-modules,apung/prosody-modules,iamliqiang/prosody-modules,LanceJenkinZA/prosody-modules,drdownload/prosody-modules,brahmi2/prosody-modules,NSAKEY/prosody-modules,guilhem/prosody-modules
0c6a332b7b780ac3e11513b3ecc286a27f23f540
lib/redis_hook.lua
lib/redis_hook.lua
-- Helper Methods function emptyGif() ngx.exec('/_.gif') end function logErrorAndExit(err) ngx.log(ngx.ERR, err) emptyGif() end function initRedis() local redis = require "resty.redis" local red = redis:new() red:set_timeout(3000) -- 3 sec local ok, err = red:connect("127.0.0.1", 6379) if not ok then logErrorAndExit("Error connecting to redis: ".. err) end return red end --------------------- ngx.header["Cache-Control"] = "no-cache" local args = ngx.req.get_uri_args() args["action"] = ngx.var.action args["day"] = os.date("%d", ngx.req.start_time()) args["week"] = os.date("%W",ngx.req.start_time()) args["month"] = os.date("%m", ngx.req.start_time()) args["year"] = os.date("%Y",ngx.req.start_time()) local cjson = require "cjson" local args_json = cjson.encode(args) red = initRedis() ok, err = red:evalsha(ngx.var.redis_counter_hash, 2, "args", "config", args_json, ngx.var.config) if not ok then logErrorAndExit("Error evaluating redis script: ".. err) end ok, err = red:set_keepalive(10000, 100) if not ok then ngx.log(ngx.ERR, "Error setting redis keep alive ".. err) end emptyGif()
-- Helper Methods function emptyGif() ngx.exec('/_.gif') end function logErrorAndExit(err) ngx.log(ngx.ERR, err) emptyGif() end function initRedis() local redis = require "resty.redis" local red = redis:new() red:set_timeout(3000) -- 3 sec local ok, err = red:connect("127.0.0.1", 6379) if not ok then logErrorAndExit("Error connecting to redis: ".. err) end return red end --------------------- ngx.header["Cache-Control"] = "no-cache" local args = ngx.req.get_uri_args() args["action"] = ngx.var.action args["day"] = os.date("%d", ngx.req.start_time()) week = os.date("%W",ngx.req.start_time()) if week == "00" then week = "52" end args["week"] = week args["month"] = os.date("%m", ngx.req.start_time()) args["year"] = os.date("%Y",ngx.req.start_time()) local cjson = require "cjson" local args_json = cjson.encode(args) red = initRedis() ok, err = red:evalsha(ngx.var.redis_counter_hash, 2, "args", "config", args_json, ngx.var.config) if not ok then logErrorAndExit("Error evaluating redis script: ".. err) end ok, err = red:set_keepalive(10000, 100) if not ok then ngx.log(ngx.ERR, "Error setting redis keep alive ".. err) end emptyGif()
fixed last week of the year edge case
fixed last week of the year edge case
Lua
mit
FTBpro/count-von-count,FTBpro/count-von-count
88a53372c1db03271a5ff09c51c87592c738b020
mods/colored_steel/init.lua
mods/colored_steel/init.lua
colored_steel = {} function colored_steel.register_steel(color) minetest.register_node("colored_steel:block_"..color, { description = color .. " Steel Block", tiles = {"default_steel_block.png^[colorize:"..color..":100"}, is_ground_content = false, groups = {cracky=1,level=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("colored_steel:glowing_block_"..color, { description = color .. " Steel Block (GLOWING)", tiles = {"default_steel_block.png^[colorize:"..color..":100^colored_steel_glowing.png"}, is_ground_content = false, light_source = 14, groups = {cracky=1,level=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_craftitem("colored_steel:steel_ingot_"..color, { description = color.." Steel Ingot", inventory_image = "default_steel_ingot.png^[colorize:"..color..":100", }) minetest.register_craft({ output = "colored_steel:block_"..color, recipe = { {"colored_steel:steel_ingot_"..color, "colored_steel:steel_ingot_"..color, "colored_steel:steel_ingot_"..color}, {"colored_steel:steel_ingot_"..color, "colored_steel:steel_ingot_"..color, "colored_steel:steel_ingot_"..color}, {"colored_steel:steel_ingot_"..color, "colored_steel:steel_ingot_"..color, "colored_steel:steel_ingot_"..color}, } }) minetest.register_craft({ output = "colored_steel:steel_ingot_"..color.." 9", recipe = { {"colored_steel:block_"..color}, } }) minetest.register_craft({ output = "colored_steel:steel_ingot_"..color.." 2", recipe = { {"default:steel_ingot", "dye:" .. color}, } }) minetest.register_craft({ output = "colored_steel:glowing_block_"..color.." 9", recipe = { {"colored_steel:block_"..color, "default:mese"}, } }) end colored_steel.register_steel("green") colored_steel.register_steel("cyan") colored_steel.register_steel("red") colored_steel.register_steel("black") colored_steel.register_steel("yellow") colored_steel.register_steel("blue") colored_steel.register_steel("magenta") colored_steel.register_steel("lime")
colored_steel = {} function colored_steel.register_steel(color) minetest.register_node("colored_steel:block_"..color, { description = color .. " Steel Block", tiles = {"default_steel_block.png^[colorize:"..color..":100"}, is_ground_content = false, groups = {cracky=1,level=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("colored_steel:glowing_block_"..color, { description = color .. " Steel Block (GLOWING)", tiles = {"default_steel_block.png^[colorize:"..color..":100^colored_steel_glowing.png"}, is_ground_content = false, light_source = 14, groups = {cracky=1,level=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("colored_steel:trap_block_"..color, { description = color .. " Steel Block (Trap)", tiles = {"default_steel_block.png^[colorize:"..color..":100"}, is_ground_content = false, walkable = false, groups = {cracky=1,level=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_craftitem("colored_steel:steel_ingot_"..color, { description = color.." Steel Ingot", inventory_image = "default_steel_ingot.png^[colorize:"..color..":100", }) minetest.register_craft({ output = "colored_steel:block_"..color, recipe = { {"colored_steel:steel_ingot_"..color, "colored_steel:steel_ingot_"..color, "colored_steel:steel_ingot_"..color}, {"colored_steel:steel_ingot_"..color, "colored_steel:steel_ingot_"..color, "colored_steel:steel_ingot_"..color}, {"colored_steel:steel_ingot_"..color, "colored_steel:steel_ingot_"..color, "colored_steel:steel_ingot_"..color}, } }) minetest.register_craft({ output = "colored_steel:steel_ingot_"..color.." 9", recipe = { {"colored_steel:block_"..color}, } }) minetest.register_craft({ output = "colored_steel:steel_ingot_"..color.." 2", recipe = { {"default:steel_ingot", "dye:" .. color}, } }) minetest.register_craft({ output = "colored_steel:glowing_block_"..color.." 9", recipe = { {"colored_steel:block_"..color, "default:mese"}, } }) minetest.register_craft({ output = "colored_steel:trap_block_"..color.." 9", recipe = { {"colored_steel:block_"..color, "default:grass_1"}, } }) end colored_steel.register_steel("green") colored_steel.register_steel("cyan") colored_steel.register_steel("red") colored_steel.register_steel("black") colored_steel.register_steel("yellow") colored_steel.register_steel("blue") colored_steel.register_steel("magenta") colored_steel.register_steel("lime")
[colored_steel] Update - Fix #40
[colored_steel] Update - Fix #40
Lua
unlicense
MinetestForFun/server-minetestforfun-creative,MinetestForFun/server-minetestforfun-creative,MinetestForFun/server-minetestforfun-creative
5b7db483728cfdd735e3bb8819d1320671836762
mods/fire/init.lua
mods/fire/init.lua
-- minetest/fire/init.lua minetest.register_node("fire:basic_flame", { description = "Fire", drawtype = "firelike", tiles = {{ name="fire_basic_flame_animated.png", animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=1}, }}, inventory_image = "fire_basic_flame.png", light_source = 14, groups = {igniter=2,dig_immediate=3,hot=3}, drop = '', walkable = false, buildable_to = true, damage_per_second = 4, after_place_node = function(pos, placer) fire.on_flame_add_at(pos) end, after_dig_node = function(pos, oldnode, oldmetadata, digger) fire.on_flame_remove_at(pos) end, }) fire = {} fire.D = 6 -- key: position hash of low corner of area -- value: {handle=sound handle, name=sound name} fire.sounds = {} function fire.get_area_p0p1(pos) local p0 = { x=math.floor(pos.x/fire.D)*fire.D, y=math.floor(pos.y/fire.D)*fire.D, z=math.floor(pos.z/fire.D)*fire.D, } local p1 = { x=p0.x+fire.D-1, y=p0.y+fire.D-1, z=p0.z+fire.D-1 } return p0, p1 end function fire.update_sounds_around(pos) local p0, p1 = fire.get_area_p0p1(pos) local cp = {x=(p0.x+p1.x)/2, y=(p0.y+p1.y)/2, z=(p0.z+p1.z)/2} local flames_p = minetest.find_nodes_in_area(p0, p1, {"fire:basic_flame"}) --print("number of flames at "..minetest.pos_to_string(p0).."/" -- ..minetest.pos_to_string(p1)..": "..#flames_p) local should_have_sound = (#flames_p > 0) local wanted_sound = nil if #flames_p >= 9 then wanted_sound = {name="fire_large", gain=1.5} elseif #flames_p > 0 then wanted_sound = {name="fire_small", gain=1.5} end local p0_hash = minetest.hash_node_position(p0) local sound = fire.sounds[p0_hash] if not sound then if should_have_sound then fire.sounds[p0_hash] = { handle = minetest.sound_play(wanted_sound, {pos=cp, loop=true}), name = wanted_sound.name, } end else if not wanted_sound then minetest.sound_stop(sound.handle) fire.sounds[p0_hash] = nil elseif sound.name ~= wanted_sound.name then minetest.sound_stop(sound.handle) fire.sounds[p0_hash] = { handle = minetest.sound_play(wanted_sound, {pos=cp, loop=true}), name = wanted_sound.name, } end end end function fire.on_flame_add_at(pos) --print("flame added at "..minetest.pos_to_string(pos)) fire.update_sounds_around(pos) end function fire.on_flame_remove_at(pos) --print("flame removed at "..minetest.pos_to_string(pos)) fire.update_sounds_around(pos) end function fire.find_pos_for_flame_around(pos) return minetest.find_node_near(pos, 1, {"air"}) end function fire.flame_should_extinguish(pos) if minetest.setting_getbool("disable_fire") then return true end --return minetest.find_node_near(pos, 1, {"group:puts_out_fire"}) local p0 = {x=pos.x-2, y=pos.y, z=pos.z-2} local p1 = {x=pos.x+2, y=pos.y, z=pos.z+2} local ps = minetest.find_nodes_in_area(p0, p1, {"group:puts_out_fire"}) return (#ps ~= 0) end -- Ignite neighboring nodes minetest.register_abm({ nodenames = {"group:flammable"}, neighbors = {"group:igniter"}, interval = 1, chance = 2, action = function(p0, node, _, _) -- If there is water or stuff like that around flame, don't ignite if fire.flame_should_extinguish(p0) then return end local p = fire.find_pos_for_flame_around(p0) if p then minetest.set_node(p, {name="fire:basic_flame"}) fire.on_flame_add_at(p) end end, }) -- Rarely ignite things from far minetest.register_abm({ nodenames = {"group:igniter"}, neighbors = {"air"}, interval = 2, chance = 10, action = function(p0, node, _, _) local reg = minetest.registered_nodes[node.name] if not reg or not reg.groups.igniter or reg.groups.igniter < 2 then return end local d = reg.groups.igniter local p = minetest.find_node_near(p0, d, {"group:flammable"}) if p then -- If there is water or stuff like that around flame, don't ignite if fire.flame_should_extinguish(p) then return end local p2 = fire.find_pos_for_flame_around(p) if p2 then minetest.set_node(p2, {name="fire:basic_flame"}) fire.on_flame_add_at(p2) end end end, }) -- Remove flammable nodes and flame minetest.register_abm({ nodenames = {"fire:basic_flame"}, interval = 1, chance = 2, action = function(p0, node, _, _) -- If there is water or stuff like that around flame, remove flame if fire.flame_should_extinguish(p0) then minetest.remove_node(p0) fire.on_flame_remove_at(p0) return end -- Make the following things rarer if math.random(1,3) == 1 then return end -- If there are no flammable nodes around flame, remove flame if not minetest.find_node_near(p0, 1, {"group:flammable"}) then minetest.remove_node(p0) fire.on_flame_remove_at(p0) return end if math.random(1,4) == 1 then -- remove a flammable node around flame local p = minetest.find_node_near(p0, 1, {"group:flammable"}) if p then -- If there is water or stuff like that around flame, don't remove if fire.flame_should_extinguish(p0) then return end minetest.remove_node(p) nodeupdate(p) end else -- remove flame minetest.remove_node(p0) fire.on_flame_remove_at(p0) end end, })
-- minetest/fire/init.lua fire = {} minetest.register_node("fire:basic_flame", { description = "Fire", drawtype = "firelike", tiles = {{ name="fire_basic_flame_animated.png", animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=1}, }}, inventory_image = "fire_basic_flame.png", light_source = 14, groups = {igniter=2,dig_immediate=3,hot=3}, drop = '', walkable = false, buildable_to = true, damage_per_second = 4, on_construct = function(pos) minetest.after(0, fire.on_flame_add_at, pos) end, on_destruct = function(pos) minetest.after(0, fire.on_flame_remove_at, pos) end, }) fire.D = 6 -- key: position hash of low corner of area -- value: {handle=sound handle, name=sound name} fire.sounds = {} function fire.get_area_p0p1(pos) local p0 = { x=math.floor(pos.x/fire.D)*fire.D, y=math.floor(pos.y/fire.D)*fire.D, z=math.floor(pos.z/fire.D)*fire.D, } local p1 = { x=p0.x+fire.D-1, y=p0.y+fire.D-1, z=p0.z+fire.D-1 } return p0, p1 end function fire.update_sounds_around(pos) local p0, p1 = fire.get_area_p0p1(pos) local cp = {x=(p0.x+p1.x)/2, y=(p0.y+p1.y)/2, z=(p0.z+p1.z)/2} local flames_p = minetest.find_nodes_in_area(p0, p1, {"fire:basic_flame"}) --print("number of flames at "..minetest.pos_to_string(p0).."/" -- ..minetest.pos_to_string(p1)..": "..#flames_p) local should_have_sound = (#flames_p > 0) local wanted_sound = nil if #flames_p >= 9 then wanted_sound = {name="fire_large", gain=1.5} elseif #flames_p > 0 then wanted_sound = {name="fire_small", gain=1.5} end local p0_hash = minetest.hash_node_position(p0) local sound = fire.sounds[p0_hash] if not sound then if should_have_sound then fire.sounds[p0_hash] = { handle = minetest.sound_play(wanted_sound, {pos=cp, loop=true}), name = wanted_sound.name, } end else if not wanted_sound then minetest.sound_stop(sound.handle) fire.sounds[p0_hash] = nil elseif sound.name ~= wanted_sound.name then minetest.sound_stop(sound.handle) fire.sounds[p0_hash] = { handle = minetest.sound_play(wanted_sound, {pos=cp, loop=true}), name = wanted_sound.name, } end end end function fire.on_flame_add_at(pos) fire.update_sounds_around(pos) end function fire.on_flame_remove_at(pos) fire.update_sounds_around(pos) end function fire.find_pos_for_flame_around(pos) return minetest.find_node_near(pos, 1, {"air"}) end function fire.flame_should_extinguish(pos) if minetest.setting_getbool("disable_fire") then return true end --return minetest.find_node_near(pos, 1, {"group:puts_out_fire"}) local p0 = {x=pos.x-2, y=pos.y, z=pos.z-2} local p1 = {x=pos.x+2, y=pos.y, z=pos.z+2} local ps = minetest.find_nodes_in_area(p0, p1, {"group:puts_out_fire"}) return (#ps ~= 0) end -- Ignite neighboring nodes minetest.register_abm({ nodenames = {"group:flammable"}, neighbors = {"group:igniter"}, interval = 1, chance = 2, action = function(p0, node, _, _) -- If there is water or stuff like that around flame, don't ignite if fire.flame_should_extinguish(p0) then return end local p = fire.find_pos_for_flame_around(p0) if p then minetest.set_node(p, {name="fire:basic_flame"}) end end, }) -- Rarely ignite things from far minetest.register_abm({ nodenames = {"group:igniter"}, neighbors = {"air"}, interval = 2, chance = 10, action = function(p0, node, _, _) local reg = minetest.registered_nodes[node.name] if not reg or not reg.groups.igniter or reg.groups.igniter < 2 then return end local d = reg.groups.igniter local p = minetest.find_node_near(p0, d, {"group:flammable"}) if p then -- If there is water or stuff like that around flame, don't ignite if fire.flame_should_extinguish(p) then return end local p2 = fire.find_pos_for_flame_around(p) if p2 then minetest.set_node(p2, {name="fire:basic_flame"}) end end end, }) -- Remove flammable nodes and flame minetest.register_abm({ nodenames = {"fire:basic_flame"}, interval = 1, chance = 2, action = function(p0, node, _, _) -- If there is water or stuff like that around flame, remove flame if fire.flame_should_extinguish(p0) then minetest.remove_node(p0) return end -- Make the following things rarer if math.random(1,3) == 1 then return end -- If there are no flammable nodes around flame, remove flame if not minetest.find_node_near(p0, 1, {"group:flammable"}) then minetest.remove_node(p0) return end if math.random(1,4) == 1 then -- remove a flammable node around flame local p = minetest.find_node_near(p0, 1, {"group:flammable"}) if p then -- If there is water or stuff like that around flame, don't remove if fire.flame_should_extinguish(p0) then return end minetest.remove_node(p) nodeupdate(p) end else -- remove flame minetest.remove_node(p0) end end, })
Fix various fire sound bugs
Fix various fire sound bugs
Lua
lgpl-2.1
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
44ed5515ea64f6625aab52ca9a075b8b47f1bccc
roles/dotfiles/files/.hammerspoon/init.lua
roles/dotfiles/files/.hammerspoon/init.lua
hs.grid.setGrid('12x12') -- allows us to place on quarters, thirds and halves hs.window.animationDuration = 0 -- disable animations local lastSeenChain = nil local lastSeenWindow = nil function chain(movements) local chainResetInterval = 2000 local cycleLength = #movements local sequenceNumber = 1 return function() local win = hs.window.frontmostWindow() local id = win:id() local now = hs.timer.secondsSinceEpoch() if lastSeenChain ~= movements or lastSeenAt < now - chainResetInterval or lastSeenWindow ~= id then sequenceNumber = 1 lastSeenChain = movements -- elseif (sequenceNumber == cycleLength) then -- TODO: at end of chain, restart chain on next screen end lastSeenAt = now lastSeenWindow = id hs.grid.set(win, movements[sequenceNumber]) sequenceNumber = sequenceNumber % cycleLength + 1 end end hs.hotkey.bind({'ctrl', 'alt'}, 'up', chain({ '0,0 12x6', -- top half '0,0 12x4', -- top third '0,0 12x8', -- top two thirds })) hs.hotkey.bind({'ctrl', 'alt'}, 'right', chain({ '6,0 6x12', -- right half '8,0 4x12', -- right third '4,0 8x12', -- right two thirds })) hs.hotkey.bind({'ctrl', 'alt'}, 'down', chain({ '0,6 12x6', -- bottom half '0,8 12x4', -- bottom third '0,4 12x8', -- bottom two thirds })) hs.hotkey.bind({'ctrl', 'alt'}, 'left', chain({ '0,0 6x12', -- left half '0,0 4x12', -- left third '0,0 8x12', -- left two thirds })) hs.hotkey.bind({'ctrl', 'alt', 'cmd'}, 'up', chain({ '0,0 6x6', -- top-left corner '6,0 6x6', -- top-right corner '6,6 6x6', -- bottom-right corner '0,6 6x6', -- bottom-left corner })) hs.hotkey.bind({'ctrl', 'alt', 'cmd'}, 'down', chain({ '0,0 12x12', -- full screen '3,3 6x6', -- centered, big '4,4 4x4', -- centered, small }))
hs.grid.setGrid('12x12') -- allows us to place on quarters, thirds and halves hs.window.animationDuration = 0 -- disable animations local lastSeenChain = nil local lastSeenWindow = nil -- chain the specified movement commands function chain(movements) local chainResetInterval = 2 -- seconds local cycleLength = #movements local sequenceNumber = 1 return function() local win = hs.window.frontmostWindow() local id = win:id() local now = hs.timer.secondsSinceEpoch() if lastSeenChain ~= movements or lastSeenAt < now - chainResetInterval or lastSeenWindow ~= id then sequenceNumber = 1 lastSeenChain = movements -- elseif (sequenceNumber == cycleLength) then -- TODO: at end of chain, restart chain on next screen end lastSeenAt = now lastSeenWindow = id hs.grid.set(win, movements[sequenceNumber]) sequenceNumber = sequenceNumber % cycleLength + 1 end end hs.hotkey.bind({'ctrl', 'alt'}, 'up', chain({ '0,0 12x6', -- top half '0,0 12x4', -- top third '0,0 12x8', -- top two thirds })) hs.hotkey.bind({'ctrl', 'alt'}, 'right', chain({ '6,0 6x12', -- right half '8,0 4x12', -- right third '4,0 8x12', -- right two thirds })) hs.hotkey.bind({'ctrl', 'alt'}, 'down', chain({ '0,6 12x6', -- bottom half '0,8 12x4', -- bottom third '0,4 12x8', -- bottom two thirds })) hs.hotkey.bind({'ctrl', 'alt'}, 'left', chain({ '0,0 6x12', -- left half '0,0 4x12', -- left third '0,0 8x12', -- left two thirds })) hs.hotkey.bind({'ctrl', 'alt', 'cmd'}, 'up', chain({ '0,0 6x6', -- top-left corner '6,0 6x6', -- top-right corner '6,6 6x6', -- bottom-right corner '0,6 6x6', -- bottom-left corner })) hs.hotkey.bind({'ctrl', 'alt', 'cmd'}, 'down', chain({ '0,0 12x12', -- full screen '3,3 6x6', -- centered, big '4,4 4x4', -- centered, small }))
git ci -m 'hammerspoon: fix chain reset interval [master●●●] ~/code/wincent
git ci -m 'hammerspoon: fix chain reset interval [master●●●] ~/code/wincent `secondsSinceEpoch` returns seconds, not milliseconds (but note: it's a double-precision float, so the resolution is still better than whole seconds).
Lua
unlicense
wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent
5ba0c6aeb201dfdb889f01b4d4558f0f3ea6112e
testserver/item/id_361_altar.lua
testserver/item/id_361_altar.lua
-- UPDATE common SET com_script='item.id_361_altar' WHERE com_itemid IN (361); require("base.common") require("content.gods") module("item.id_361_altar", package.seeall, package.seeall(content.gods)) function LookAtItem(User, Item) if Item.data ==100 then --used for THE LIBRARY quest if (User:getPlayerLanguage() ==0) then User:inform("Dir fallen die Buchstaben CRG am Altar auf") else User:inform("You notice the letters CRG on the altar") end end if Item.data > 0 then if User:getPlayerLanguage() == 0 then ret = "Altar "..GOD_DE[Item.data]; else ret = "Altar "..GOD_EN[Item.data]; end; if User:getRace() == 5 then ret = string.gsub( ret, "Tanora", "Zshhel-pheey-arrr" ); end; else ret = User:getPlayerLanguage() == 0 and "Ungeweihter Altar" or "Undedicated altar"; end; world:itemInform( User, Item, ret ); end function UseItem(User, SourceItem, TargetItem, Counter, param) if (SourceItem.data == 100) then --used for THE LIBRARY quest local items = User:getItemList(79); for i, item in pairs(items) do if (item.data == 705) or (item.data==707) then --teleport if has complete amulet world:makeSound(5,position(385,552,0)) User:warp(position(382,560,-3)) if (User:getPlayerLanguage() ==0) then User:inform("Du legst das Amulett auf den Altar - Es blitzt auf und du bist an einem anderen Ort"); else User:inform("You place the amulet on the altar - there is a flash and you are somewhere else"); end break; end; end; end; end;
-- UPDATE common SET com_script='item.id_361_altar' WHERE com_itemid IN (361); require("base.common") require("content.gods") module("item.id_361_altar", package.seeall, package.seeall(content.gods)) function LookAtItem(User, Item) if tonumber(Item:getData("libraryQuest")) ==100 then --used for THE LIBRARY quest if (User:getPlayerLanguage() ==0) then User:inform("Dir fallen die Buchstaben CRG am Altar auf") else User:inform("You notice the letters CRG on the altar") end end if tonumber(Item:getData("god")) > 0 then if User:getPlayerLanguage() == 0 then retDE = "Altar "..GOD_DE[tonumber(Item:getData("god"))]; else retEN = "Altar "..GOD_EN[tonumber(Item:getData("god"))]; end; if User:getRace() == 5 then retDE = string.gsub( retDE, "Tanora", "Zshhel-pheey-arrr" ); retEN = string.gsub( retEN, "Tanora", "Zshhel-pheey-arrr" ); end; else retDE = "Ungeweihter Altar"; retEN = "Undedicated altar"; end; base.lookat.SetSpecialName(Item, retDE, retEN) world:itemInform(User,Item,base.lookat.GenerateLookAt(User, Item, base.lookat.NONE)); end function UseItem(User, SourceItem, TargetItem, Counter, param) if (tonumber(SourceItem:getData("libraryQuest")) == 100) then --used for THE LIBRARY quest local items = User:getItemList(79); for i, item in pairs(items) do if (tonumber(item:getData("libraryQuest")) == 705) or (tonumber(item:getData("libraryQuest"))==707) then --teleport if has complete amulet world:makeSound(5,position(385,552,0)) User:warp(position(382,560,-3)) if (User:getPlayerLanguage() ==0) then User:inform("Du legst das Amulett auf den Altar - Es blitzt auf und du bist an einem anderen Ort"); else User:inform("You place the amulet on the altar - there is a flash and you are somewhere else"); end break; end; end; end; end;
replaced old data and fixed lookat
replaced old data and fixed lookat
Lua
agpl-3.0
Baylamon/Illarion-Content,LaFamiglia/Illarion-Content,Illarion-eV/Illarion-Content,KayMD/Illarion-Content,vilarion/Illarion-Content
a638096ce3be7e591a9ca64cdab74cf42651ba22
minetestforfun_game/mods/bucket/init.lua
minetestforfun_game/mods/bucket/init.lua
-- Minetest 0.4 mod: bucket -- See README.txt for licensing and other information. minetest.register_alias("bucket", "bucket:bucket_empty") minetest.register_alias("bucket_water", "bucket:bucket_water") minetest.register_alias("bucket_acid", "bucket:bucket_acid") minetest.register_alias("bucket_lava", "bucket:bucket_lava") minetest.register_craft({ output = "bucket:bucket_empty 1", recipe = { {"group:ingot", "", "group:ingot"}, {"", "group:ingot", ""}, } }) bucket = {} bucket.liquids = {} local function check_protection(pos, name, text) if minetest.is_protected(pos, name) then minetest.log("action", (name ~= "" and name or "A mod") .. " tried to " .. text .. " at protected position " .. minetest.pos_to_string(pos) .. " with a bucket.") minetest.record_protection_violation(pos, name) return true end return false end -- Register a new liquid -- source = name of the source node -- flowing = name of the flowing node -- itemname = name of the new bucket item (or nil if liquid is not takeable) -- inventory_image = texture of the new bucket item (ignored if itemname == nil) -- This function can be called from any mod (that depends on bucket). function bucket.register_liquid(source, flowing, itemname, inventory_image, name) bucket.liquids[source] = { source = source, flowing = flowing, itemname = itemname, } bucket.liquids[flowing] = bucket.liquids[source] if itemname ~= nil then minetest.register_craftitem(itemname, { description = name, inventory_image = inventory_image, stack_max = 1, liquids_pointable = true, groups = {not_in_creative_inventory=1}, on_place = function(itemstack, user, pointed_thing) -- Must be pointing to node if pointed_thing.type ~= "node" then return end local node = minetest.get_node_or_nil(pointed_thing.under) local ndef if node then ndef = minetest.registered_nodes[node.name] end -- Call on_rightclick if the pointed node defines it if ndef and ndef.on_rightclick and user and not user:get_player_control().sneak then return ndef.on_rightclick( pointed_thing.under, node, user, itemstack) or itemstack end local place_liquid = function(pos, node, source, flowing) if check_protection(pos, user and user:get_player_name() or "", "place "..source) then return end minetest.add_node(pos, {name=source}) end -- Check if pointing to a buildable node if ndef and ndef.buildable_to then -- buildable; replace the node place_liquid(pointed_thing.under, node, source, flowing) else -- not buildable to; place the liquid above -- check if the node above can be replaced local node = minetest.get_node_or_nil(pointed_thing.above) if node and minetest.registered_nodes[node.name].buildable_to then place_liquid(pointed_thing.above, node, source, flowing) else -- do not remove the bucket with the liquid return end end return {name="bucket:bucket_empty"} end }) end end -- Empty Bucket code by Casimir. minetest.register_craftitem(":bucket:bucket_empty", { description = "Empty Bucket", inventory_image = "bucket.png", liquids_pointable = true, on_use = function(itemstack, user, pointed_thing) -- Must be pointing to a node. if pointed_thing.type ~= "node" then return end -- Check if pointing to a liquid source. local node = minetest.get_node(pointed_thing.under) local liquiddef = bucket.liquids[node.name] if liquiddef ~= nil and liquiddef.itemname ~= nil and node.name == liquiddef.source then if check_protection(pointed_thing.under, user:get_player_name(), "take ".. node.name) then return end -- Only one bucket: replace. local count = itemstack:get_count() if count == 1 then minetest.add_node(pointed_thing.under, {name="air"}) return ItemStack({name = liquiddef.itemname, metadata = tostring(node.param2)}) end -- Stacked buckets: add a filled bucket, replace stack. local inv = user:get_inventory() if inv:room_for_item("main", liquiddef.itemname) then minetest.add_node(pointed_thing.under, {name="air"}) --count = count - 1 --itemstack:set_count(count) return ItemStack(liquiddef.itemname) --inv:add_item("main", bucket_liquid) else minetest.chat_send_player(user:get_player_name(), "Your inventory is full.") end end end, }) bucket.register_liquid( "default:water_source", "default:water_flowing", "bucket:bucket_water", "bucket_water.png", "Water Bucket" ) bucket.register_liquid( "default:lava_source", "default:lava_flowing", "bucket:bucket_lava", "bucket_lava.png", "Lava Bucket" ) bucket.register_liquid( "default:acid_source", "default:acid_flowing", "bucket:bucket_acid", "bucket_acid.png", "Acid Bucket" ) minetest.register_craft({ type = "fuel", recipe = "bucket:bucket_lava", burntime = 60, replacements = {{"bucket:bucket_lava", "bucket:bucket_empty"}}, }) if minetest.setting_getbool("log_mods") then minetest.log("action", "Carbone: [bucket] loaded.") end
-- Minetest 0.4 mod: bucket -- See README.txt for licensing and other information. minetest.register_alias("bucket", "bucket:bucket_empty") minetest.register_alias("bucket_water", "bucket:bucket_water") minetest.register_alias("bucket_acid", "bucket:bucket_acid") minetest.register_alias("bucket_lava", "bucket:bucket_lava") minetest.register_craft({ output = "bucket:bucket_empty 1", recipe = { {"group:ingot", "", "group:ingot"}, {"", "group:ingot", ""}, } }) bucket = {} bucket.liquids = {} local function check_protection(pos, name, text) if minetest.is_protected(pos, name) then minetest.log("action", (name ~= "" and name or "A mod") .. " tried to " .. text .. " at protected position " .. minetest.pos_to_string(pos) .. " with a bucket.") minetest.record_protection_violation(pos, name) return true end return false end -- Register a new liquid -- source = name of the source node -- flowing = name of the flowing node -- itemname = name of the new bucket item (or nil if liquid is not takeable) -- inventory_image = texture of the new bucket item (ignored if itemname == nil) -- This function can be called from any mod (that depends on bucket). function bucket.register_liquid(source, flowing, itemname, inventory_image, name) bucket.liquids[source] = { source = source, flowing = flowing, itemname = itemname, } bucket.liquids[flowing] = bucket.liquids[source] if itemname ~= nil then minetest.register_craftitem(itemname, { description = name, inventory_image = inventory_image, stack_max = 1, liquids_pointable = true, groups = {not_in_creative_inventory=1}, on_place = function(itemstack, user, pointed_thing) -- Must be pointing to node if pointed_thing.type ~= "node" then return end local node = minetest.get_node_or_nil(pointed_thing.under) local ndef if node then ndef = minetest.registered_nodes[node.name] end -- Call on_rightclick if the pointed node defines it if ndef and ndef.on_rightclick and user and not user:get_player_control().sneak then return ndef.on_rightclick( pointed_thing.under, node, user, itemstack) or itemstack end local place_liquid = function(pos, node, source, flowing) if check_protection(pos, user and user:get_player_name() or "", "place "..source) then return end minetest.add_node(pos, {name=source}) end -- Check if pointing to a buildable node if ndef and ndef.buildable_to then -- buildable; replace the node place_liquid(pointed_thing.under, node, source, flowing) else -- not buildable to; place the liquid above -- check if the node above can be replaced local node = minetest.get_node_or_nil(pointed_thing.above) if node and minetest.registered_nodes[node.name].buildable_to then place_liquid(pointed_thing.above, node, source, flowing) else -- do not remove the bucket with the liquid return end end return {name="bucket:bucket_empty"} end }) end end -- Empty Bucket code by Casimir. minetest.register_craftitem(":bucket:bucket_empty", { description = "Empty Bucket", inventory_image = "bucket.png", liquids_pointable = true, on_use = function(itemstack, user, pointed_thing) -- Must be pointing to a node. if pointed_thing.type ~= "node" then return end -- Check if pointing to a liquid source. local node = minetest.get_node(pointed_thing.under) local liquiddef = bucket.liquids[node.name] if liquiddef ~= nil and liquiddef.itemname ~= nil and node.name == liquiddef.source then if check_protection(pointed_thing.under, user:get_player_name(), "take ".. node.name) then return end -- Only one bucket: replace. local count = itemstack:get_count() if count == 1 then minetest.add_node(pointed_thing.under, {name="air"}) return ItemStack({name = liquiddef.itemname, metadata = tostring(node.param2)}) end -- Stacked buckets: add a filled bucket, replace stack. local inv = user:get_inventory() if inv:room_for_item("main", liquiddef.itemname) then count = count - 1 itemstack:set_count(count) inv:add_item("main", liquiddef.itemname) return ItemStack(itemstack) else minetest.chat_send_player(user:get_player_name(), "Your inventory is full.") end end end, }) bucket.register_liquid( "default:water_source", "default:water_flowing", "bucket:bucket_water", "bucket_water.png", "Water Bucket" ) bucket.register_liquid( "default:lava_source", "default:lava_flowing", "bucket:bucket_lava", "bucket_lava.png", "Lava Bucket" ) bucket.register_liquid( "default:acid_source", "default:acid_flowing", "bucket:bucket_acid", "bucket_acid.png", "Acid Bucket" ) minetest.register_craft({ type = "fuel", recipe = "bucket:bucket_lava", burntime = 60, replacements = {{"bucket:bucket_lava", "bucket:bucket_empty"}}, }) if minetest.setting_getbool("log_mods") then minetest.log("action", "Carbone: [bucket] loaded.") end
Implementation of multiple buckets handler - Uncommented and changed a bit the lines of Casimir's redefinition of bucket:bucket_empty in ./minetestforfun_game/mods/bucket/init.lua to implement multiple buckets handle system, commented in an old commit (it was buggy, or something). The system has been modified a bit to prevent bugs from incompatibility between carbone's api (which the definition has been copied from) and minetestforfun_game's one.
Implementation of multiple buckets handler - Uncommented and changed a bit the lines of Casimir's redefinition of bucket:bucket_empty in ./minetestforfun_game/mods/bucket/init.lua to implement multiple buckets handle system, commented in an old commit (it was buggy, or something). The system has been modified a bit to prevent bugs from incompatibility between carbone's api (which the definition has been copied from) and minetestforfun_game's one.
Lua
unlicense
Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Coethium/server-minetestforfun,paly2/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,sys4-fr/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server
de2d6185e9daf91f389121778fb1b53ef0ec87f8
orange/plugins/kafka/handler.lua
orange/plugins/kafka/handler.lua
local BasePlugin = require("orange.plugins.base_handler") local cjson = require "cjson" local producer = require "resty.kafka.producer" local KafkaHandler = BasePlugin:extend() KafkaHandler.PRIORITY = 2000 function KafkaHandler:new(store) KafkaHandler.super.new(self, "key_auth-plugin") self.store = store end local function errlog(...) ngx.log(ngx.ERR,'[Kafka]',...) end local do_log = function(log_table) -- 定义kafka broker地址,ip需要和kafka的host.name配置一致 local broker_list = context.config.plugin_config.kafka.broker_list local kafka_topic = context.config.plugin_config.kafka.topic local producer_config = context.config.plugin_config.kafka.producer_config -- 定义json便于日志数据整理收集 -- 转换json为字符串 local message = cjson.encode(log_table); -- 定义kafka异步生产者 local bp = producer:new(broker_list, producer_config) -- 发送日志消息,send第二个参数key,用于kafka路由控制: -- key为nill(空)时,一段时间向同一partition写入数据 -- 指定key,按照key的hash写入到对应的partition local ok, err = bp:send(kafka_topic, nil, message) if not ok then ngx.log(ngx.ERR, "kafka send err:", err) return end end local function log(premature,log_table) if premature then errlog("timer premature") return end local ok,err = pcall(do_log,log_table) if not ok then errlog("failed to record log by kafka",err) local ok,err = ngx.timer.at(0,log,log_table) if not ok then errlog ("faild to create timer",err) end end end -- log_format main '$remote_addr - $remote_user [$time_local] "$request" ' -- '$status $body_bytes_sent "$http_referer" ' -- '"$http_user_agent" "$request_time" "$ssl_protocol" "$ssl_cipher" "$http_x_forwarded_for"' -- '"$upstream_addr" "$upstream_status" "$upstream_response_length" "$upstream_response_time"'; function KafkaHandler:log() local log_json = {} log_json["remote_addr"] = ngx.var.remote_addr and ngx.var.remote_addr or '-' log_json["remote_user"] = ngx.var.remote_user and ngx.var.remote_user or '-' log_json["time_local"] = ngx.var.time_local and ngx.var.time_local or '-' log_json['request'] = ngx.var.request and ngx.var.request or '-' log_json["status"] = ngx.var.status and ngx.var.status or '-' log_json["body_bytes_sent"] = ngx.var.body_bytes_sent and ngx.var.body_bytes_sent or '-' log_json["http_referer"] = ngx.var.http_referer and ngx.var.http_referer or '-' log_json["http_user_agent"] = ngx.var.http_user_agent and ngx.var.http_user_agent or '-' log_json["request_time"] = ngx.var.request_time and ngx.var.request_time or '-' log_json["uri"]=ngx.var.uri and ngx.var.uri or '-' log_json["args"]=ngx.var.args and ngx.var.args or '-' log_json["host"]=ngx.var.host and ngx.var.host or '-' log_json["request_body"]=ngx.var.request_body and ngx.var.request_body or '-' log_json['ssl_protocol'] = ngx.var.ssl_protocol and ngx.var.ssl_protocol or ' -' log_json['ssl_cipher'] = ngx.var.ssl_cipher and ngx.var.ssl_cipher or ' -' log_json['upstream_addr'] = ngx.var.upstream_addr and ngx.var.upstream_addr or ' -' log_json['upstream_status'] = ngx.var.upstream_status and ngx.var.upstream_status or ' -' log_json['upstream_response_length'] = ngx.var.upstream_response_length and ngx.var.upstream_response_length or ' -' log_json["http_x_forwarded_for"] = ngx.var.http_x_forwarded_for and ngx.var.http_x_forwarded_for or '-' log_json["upstream_response_time"] = ngx.var.upstream_response_time and ngx.var.upstream_response_time or '-' log_json["upstream_url"] = "http://" .. ngx.var.upstream_url; log_json["request_headers"] = ngx.req.get_headers(); log_json["response_headers"] = ngx.resp.get_headers(); local ok,err = ngx.timer.at(0,log,log_json) if not ok then errlog ("faild to create timer",err) end end return KafkaHandler
local BasePlugin = require("orange.plugins.base_handler") local cjson = require "cjson" local producer = require "resty.kafka.producer" local KafkaHandler = BasePlugin:extend() KafkaHandler.PRIORITY = 2000 function KafkaHandler:new(store) KafkaHandler.super.new(self, "kafka-plugin") self.store = store end local function errlog(...) ngx.log(ngx.ERR,'[Kafka]',...) end local do_log = function(log_table) -- 定义kafka broker地址,ip需要和kafka的host.name配置一致 local broker_list = context.config.plugin_config.kafka.broker_list local kafka_topic = context.config.plugin_config.kafka.topic local producer_config = context.config.plugin_config.kafka.producer_config -- 定义json便于日志数据整理收集 -- 转换json为字符串 local message = cjson.encode(log_table); -- 定义kafka异步生产者 local bp = producer:new(broker_list, producer_config) -- 发送日志消息,send第二个参数key,用于kafka路由控制: -- key为nill(空)时,一段时间向同一partition写入数据 -- 指定key,按照key的hash写入到对应的partition local ok, err = bp:send(kafka_topic, nil, message) if not ok then errlog("kafka send err:", err) return end end local function log(premature,log_table) if premature then errlog("timer premature") return end local ok,err = pcall(do_log,log_table) if not ok then errlog("failed to record log by kafka",err) local ok,err = ngx.timer.at(0,log,log_table) if not ok then errlog ("faild to create timer",err) end end end -- log_format main '$remote_addr - $remote_user [$time_local] "$request" ' -- '$status $body_bytes_sent "$http_referer" ' -- '"$http_user_agent" "$request_time" "$ssl_protocol" "$ssl_cipher" "$http_x_forwarded_for"' -- '"$upstream_addr" "$upstream_status" "$upstream_response_length" "$upstream_response_time"'; function KafkaHandler:log() local log_json = {} log_json["remote_addr"] = ngx.var.remote_addr and ngx.var.remote_addr or '-' log_json["remote_user"] = ngx.var.remote_user and ngx.var.remote_user or '-' log_json["time_local"] = ngx.var.time_local and ngx.var.time_local or '-' log_json['request'] = ngx.var.request and ngx.var.request or '-' log_json["status"] = ngx.var.status and ngx.var.status or '-' log_json["body_bytes_sent"] = ngx.var.body_bytes_sent and ngx.var.body_bytes_sent or '-' log_json["http_referer"] = ngx.var.http_referer and ngx.var.http_referer or '-' log_json["http_user_agent"] = ngx.var.http_user_agent and ngx.var.http_user_agent or '-' log_json["request_time"] = ngx.var.request_time and ngx.var.request_time or '-' log_json["uri"]=ngx.var.uri and ngx.var.uri or '-' log_json["args"]=ngx.var.args and ngx.var.args or '-' log_json["host"]=ngx.var.host and ngx.var.host or '-' log_json["request_body"]=ngx.var.request_body and ngx.var.request_body or '-' log_json['ssl_protocol'] = ngx.var.ssl_protocol and ngx.var.ssl_protocol or ' -' log_json['ssl_cipher'] = ngx.var.ssl_cipher and ngx.var.ssl_cipher or ' -' log_json['upstream_addr'] = ngx.var.upstream_addr and ngx.var.upstream_addr or ' -' log_json['upstream_status'] = ngx.var.upstream_status and ngx.var.upstream_status or ' -' log_json['upstream_response_length'] = ngx.var.upstream_response_length and ngx.var.upstream_response_length or ' -' log_json["http_x_forwarded_for"] = ngx.var.http_x_forwarded_for and ngx.var.http_x_forwarded_for or '-' log_json["upstream_response_time"] = ngx.var.upstream_response_time and ngx.var.upstream_response_time or '-' log_json["upstream_url"] = "http://" .. ngx.var.upstream_url .. ngx.var.upstream_request_uri or ''; log_json["request_headers"] = ngx.req.get_headers(); log_json["response_headers"] = ngx.resp.get_headers(); local ok,err = ngx.timer.at(0,log,log_json) if not ok then errlog ("faild to create timer",err) end end return KafkaHandler
1. fix: name error. 2: compliant with plug dynamic_upstream 3:refact: replace ngx.log with local fun errlog
1. fix: name error. 2: compliant with plug dynamic_upstream 3:refact: replace ngx.log with local fun errlog
Lua
mit
thisverygoodhhhh/orange,thisverygoodhhhh/orange,thisverygoodhhhh/orange,sumory/orange,sumory/orange,sumory/orange
e9d1f0245cf4f9788736d4120d02a8c490e146a4
protocols/ppp/luasrc/model/network/proto_ppp.lua
protocols/ppp/luasrc/model/network/proto_ppp.lua
--[[ LuCI - Network model - 3G, PPP, PPtP, PPPoE and PPPoA protocol extension Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local netmod = luci.model.network local _, p for _, p in ipairs({"ppp", "pptp", "pppoe", "pppoa", "3g", "l2tp"}) do local proto = netmod:register_protocol(p) function proto.get_i18n(self) if p == "ppp" then return luci.i18n.translate("PPP") elseif p == "pptp" then return luci.i18n.translate("PPtP") elseif p == "3g" then return luci.i18n.translate("UMTS/GPRS/EV-DO") elseif p == "pppoe" then return luci.i18n.translate("PPPoE") elseif p == "pppoa" then return luci.i18n.translate("PPPoATM") elseif p == "l2tp" then return luci.i18n.translate("L2TP") end end function proto.ifname(self) return p .. "-" .. self.sid end function proto.opkg_package(self) if p == "ppp" then return p elseif p == "3g" then return "comgt" elseif p == "pptp" then return "ppp-mod-pptp" elseif p == "pppoe" then return "ppp-mod-pppoe" elseif p == "pppoa" then return "ppp-mod-pppoa" elseif p == "l2tp" then return "xl2tpd" end end function proto.is_installed(self) if p == "pppoa" then return (nixio.fs.glob("/usr/lib/pppd/*/pppoatm.so")() ~= nil) elseif p == "pppoe" then return (nixio.fs.glob("/usr/lib/pppd/*/rp-pppoe.so")() ~= nil) elseif p == "pptp" then return (nixio.fs.glob("/usr/lib/pppd/*/pptp.so")() ~= nil) elseif p == "3g" then return nixio.fs.access("/lib/netifd/proto/3g.sh") else return nixio.fs.access("/lib/netifd/proto/ppp.sh") end end function proto.is_floating(self) return (p ~= "pppoe") end function proto.is_virtual(self) return true end function proto.get_interfaces(self) if self:is_floating() then return nil else return netmod.protocol.get_interfaces(self) end end function proto.contains_interface(self, ifc) if self:is_floating() then return (netmod:ifnameof(ifc) == self:ifname()) else return netmod.protocol.contains_interface(self, ifc) end end netmod:register_pattern_virtual("^%s-%%w" % p) end
--[[ LuCI - Network model - 3G, PPP, PPtP, PPPoE and PPPoA protocol extension Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local netmod = luci.model.network local _, p for _, p in ipairs({"ppp", "pptp", "pppoe", "pppoa", "3g", "l2tp"}) do local proto = netmod:register_protocol(p) function proto.get_i18n(self) if p == "ppp" then return luci.i18n.translate("PPP") elseif p == "pptp" then return luci.i18n.translate("PPtP") elseif p == "3g" then return luci.i18n.translate("UMTS/GPRS/EV-DO") elseif p == "pppoe" then return luci.i18n.translate("PPPoE") elseif p == "pppoa" then return luci.i18n.translate("PPPoATM") elseif p == "l2tp" then return luci.i18n.translate("L2TP") end end function proto.ifname(self) return p .. "-" .. self.sid end function proto.opkg_package(self) if p == "ppp" then return p elseif p == "3g" then return "comgt" elseif p == "pptp" then return "ppp-mod-pptp" elseif p == "pppoe" then return "ppp-mod-pppoe" elseif p == "pppoa" then return "ppp-mod-pppoa" elseif p == "l2tp" then return "xl2tpd" end end function proto.is_installed(self) if p == "pppoa" then return (nixio.fs.glob("/usr/lib/pppd/*/pppoatm.so")() ~= nil) elseif p == "pppoe" then return (nixio.fs.glob("/usr/lib/pppd/*/rp-pppoe.so")() ~= nil) elseif p == "pptp" then return (nixio.fs.glob("/usr/lib/pppd/*/pptp.so")() ~= nil) elseif p == "3g" then return nixio.fs.access("/lib/netifd/proto/3g.sh") elseif p == "l2tp" then return nixio.fs.access("/lib/netifd/proto/l2tp.sh") else return nixio.fs.access("/lib/netifd/proto/ppp.sh") end end function proto.is_floating(self) return (p ~= "pppoe") end function proto.is_virtual(self) return true end function proto.get_interfaces(self) if self:is_floating() then return nil else return netmod.protocol.get_interfaces(self) end end function proto.contains_interface(self, ifc) if self:is_floating() then return (netmod:ifnameof(ifc) == self:ifname()) else return netmod.protocol.contains_interface(self, ifc) end end netmod:register_pattern_virtual("^%s-%%w" % p) end
fix is_installed() check for l2tp
fix is_installed() check for l2tp Signed-off-by: David Woodhouse <David.Woodhouse@intel.com> git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@9541 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
0e48785e0e3df7c042ef047801876584a3d6c72d
reader.lua
reader.lua
#!./kpdfview --[[ KindlePDFViewer: a reader implementation Copyright (C) 2011 Hans-Werner Hilse <hilse@web.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]]-- require "alt_getopt" require "pdfreader" require "djvureader" require "filechooser" require "settings" -- option parsing: longopts = { password = "p", goto = "g", gamma = "G", device = "d", help = "h" } function openFile(filename) local file_type = string.lower(string.match(filename, ".+%.(.+)")) if file_type == "djvu" then if DJVUReader:open(filename) then page_num = DJVUReader.settings:readsetting("last_page") or 1 DJVUReader:goto(tonumber(page_num)) reader_settings:savesetting("lastfile", filename) return DJVUReader:inputloop() end elseif file_type == "pdf" then if PDFReader:open(filename,"") then -- TODO: query for password page_num = PDFReader.settings:readsetting("last_page") or 1 PDFReader:goto(tonumber(page_num)) reader_settings:savesetting("lastfile", filename) return PDFReader:inputloop() end end end function showusage() print("usage: ./reader.lua [OPTION] ... path") print("Read PDFs and DJVUs on your E-Ink reader") print("") print("-p, --password=PASSWORD set password for reading PDF document") print("-g, --goto=page start reading on page") print("-G, --gamma=GAMMA set gamma correction") print(" (floating point notation, e.g. \"1.5\")") print("-d, --device=DEVICE set device specific configuration,") print(" currently one of \"kdxg\" (default), \"k3\"") print(" \"emu\" (DXG emulation)") print("-h, --help show this usage help") print("") print("If you give the name of a directory instead of a file path, a file") print("chooser will show up and let you select a PDF|DJVU file") print("") print("If you don't pass any path, the last viewed document will be opened") print("") print("This software is licensed under the GPLv3.") print("See http://github.com/hwhw/kindlepdfviewer for more info.") return end optarg, optind = alt_getopt.get_opts(ARGV, "p:G:hg:d:", longopts) if optarg["h"] then return showusage() end if optarg["d"] == "k3" then -- for now, the only difference is the additional input device input.open("/dev/input/event0") input.open("/dev/input/event1") input.open("/dev/input/event2") set_k3_keycodes() elseif optarg["d"] == "emu" then input.open("") -- SDL key codes set_emu_keycodes() else input.open("/dev/input/event0") input.open("/dev/input/event1") -- check if we are running on Kindle 3 (additional volume input) local f=lfs.attributes("/dev/input/event2") print(f) if f then print("Auto-detected Kindle 3") input.open("/dev/input/event2") set_k3_keycodes() end end if optarg["G"] ~= nil then globalgamma = optarg["G"] end fb = einkfb.open("/dev/fb0") width, height = fb:getSize() -- set up reader's setting: font reader_settings = DocSettings:open(".reader") r_cfont = reader_settings:readsetting("cfont") if r_cfont ~=nil then FontChooser.cfont = r_cfont end -- initialize specific readers PDFReader:init() DJVUReader:init() -- display directory or open file local patharg = reader_settings:readsetting("lastfile") if ARGV[optind] and lfs.attributes(ARGV[optind], "mode") == "directory" then local running = true FileChooser:setPath(ARGV[optind]) while running do local file = FileChooser:choose(0,height) if file ~= nil then running = openFile(file) else running = false end end elseif patharg and lfs.attributes(patharg, "mode") == "file" then openFile(patharg, optarg["p"]) else return showusage() end -- save reader settings reader_settings:savesetting("cfont", FontChooser.cfont) reader_settings:close() input.closeAll() --os.execute('test -e /proc/keypad && echo "send '..KEY_HOME..'" > /proc/keypad ') if optarg["d"] ~= "emu" then os.execute('echo "send '..KEY_MENU..'" > /proc/keypad;echo "send '..KEY_MENU..'" > /proc/keypad') end
#!./kpdfview --[[ KindlePDFViewer: a reader implementation Copyright (C) 2011 Hans-Werner Hilse <hilse@web.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]]-- require "alt_getopt" require "pdfreader" require "djvureader" require "filechooser" require "settings" -- option parsing: longopts = { password = "p", goto = "g", gamma = "G", device = "d", help = "h" } function openFile(filename) local file_type = string.lower(string.match(filename, ".+%.(.+)")) if file_type == "djvu" then if DJVUReader:open(filename) then page_num = DJVUReader.settings:readsetting("last_page") or 1 DJVUReader:goto(tonumber(page_num)) reader_settings:savesetting("lastfile", filename) return DJVUReader:inputloop() end elseif file_type == "pdf" then if PDFReader:open(filename,"") then -- TODO: query for password page_num = PDFReader.settings:readsetting("last_page") or 1 PDFReader:goto(tonumber(page_num)) reader_settings:savesetting("lastfile", filename) return PDFReader:inputloop() end end end function showusage() print("usage: ./reader.lua [OPTION] ... path") print("Read PDFs and DJVUs on your E-Ink reader") print("") print("-p, --password=PASSWORD set password for reading PDF document") print("-g, --goto=page start reading on page") print("-G, --gamma=GAMMA set gamma correction") print(" (floating point notation, e.g. \"1.5\")") print("-d, --device=DEVICE set device specific configuration,") print(" currently one of \"kdxg\" (default), \"k3\"") print(" \"emu\" (DXG emulation)") print("-h, --help show this usage help") print("") print("If you give the name of a directory instead of a file path, a file") print("chooser will show up and let you select a PDF|DJVU file") print("") print("If you don't pass any path, the last viewed document will be opened") print("") print("This software is licensed under the GPLv3.") print("See http://github.com/hwhw/kindlepdfviewer for more info.") return end optarg, optind = alt_getopt.get_opts(ARGV, "p:G:hg:d:", longopts) if optarg["h"] then return showusage() end if optarg["d"] == "k3" then -- for now, the only difference is the additional input device input.open("/dev/input/event0") input.open("/dev/input/event1") input.open("/dev/input/event2") set_k3_keycodes() elseif optarg["d"] == "emu" then input.open("") -- SDL key codes set_emu_keycodes() else input.open("/dev/input/event0") input.open("/dev/input/event1") -- check if we are running on Kindle 3 (additional volume input) local f=lfs.attributes("/dev/input/event2") print(f) if f then print("Auto-detected Kindle 3") input.open("/dev/input/event2") set_k3_keycodes() end end if optarg["G"] ~= nil then globalgamma = optarg["G"] end fb = einkfb.open("/dev/fb0") width, height = fb:getSize() -- set up reader's setting: font reader_settings = DocSettings:open(".reader") r_cfont = reader_settings:readsetting("cfont") if r_cfont ~=nil then FontChooser.cfont = r_cfont end -- initialize specific readers PDFReader:init() DJVUReader:init() -- display directory or open file local patharg = reader_settings:readsetting("lastfile") if ARGV[optind] and lfs.attributes(ARGV[optind], "mode") == "directory" then local running = true FileChooser:setPath(ARGV[optind]) while running do local file = FileChooser:choose(0,height) if file ~= nil then running = openFile(file) else running = false end end elseif ARGV[optind] and lfs.attributes(ARGV[optind], "mode") == "file" then openFile(ARGV[optind], optarg["p"]) elseif patharg and lfs.attributes(patharg, "mode") == "file" then openFile(patharg, optarg["p"]) else return showusage() end -- save reader settings reader_settings:savesetting("cfont", FontChooser.cfont) reader_settings:close() input.closeAll() --os.execute('test -e /proc/keypad && echo "send '..KEY_HOME..'" > /proc/keypad ') if optarg["d"] ~= "emu" then os.execute('echo "send '..KEY_MENU..'" > /proc/keypad;echo "send '..KEY_MENU..'" > /proc/keypad') end
fix #36: enable file path back
fix #36: enable file path back
Lua
agpl-3.0
apletnev/koreader-base,NiLuJe/koreader-base,chrox/koreader,pazos/koreader,ashang/koreader,Frenzie/koreader-base,poire-z/koreader,Hzj-jie/koreader,Markismus/koreader,frankyifei/koreader,Frenzie/koreader,Hzj-jie/koreader-base,NickSavage/koreader,koreader/koreader-base,Frenzie/koreader-base,NiLuJe/koreader,chihyang/koreader,NiLuJe/koreader-base,koreader/koreader-base,mihailim/koreader,koreader/koreader-base,NiLuJe/koreader-base,Frenzie/koreader,poire-z/koreader,ashhher3/koreader,frankyifei/koreader-base,Frenzie/koreader-base,koreader/koreader,houqp/koreader-base,lgeek/koreader,noname007/koreader,NiLuJe/koreader,frankyifei/koreader-base,houqp/koreader-base,houqp/koreader,apletnev/koreader-base,apletnev/koreader-base,mwoz123/koreader,houqp/koreader-base,koreader/koreader-base,Hzj-jie/koreader-base,frankyifei/koreader-base,Hzj-jie/koreader-base,Hzj-jie/koreader-base,apletnev/koreader-base,frankyifei/koreader-base,NiLuJe/koreader-base,koreader/koreader,Frenzie/koreader-base,robert00s/koreader,apletnev/koreader,houqp/koreader-base
0c223c87b3bd8fe7fdf921545ba50854aa9f2ad9
mods/irc/init.lua
mods/irc/init.lua
-- This file is licensed under the terms of the BSD 2-clause license. -- See LICENSE.txt for details. local modpath = minetest.get_modpath(minetest.get_current_modname()) package.path = -- To find LuaIRC's init.lua modpath.."/?/init.lua;" -- For LuaIRC to find its files ..modpath.."/?.lua;" ..package.path -- The build of Lua that Minetest comes with only looks for libraries under -- /usr/local/share and /usr/local/lib but LuaSocket is often installed under -- /usr/share and /usr/lib. if not rawget(_G,"jit") and package.config:sub(1, 1) == "/" then package.path = package.path.. ";/usr/share/lua/5.1/?.lua".. ";/usr/share/lua/5.1/?/init.lua" package.cpath = package.cpath.. ";/usr/lib/lua/5.1/?.so" end irc = { version = "0.2.0", connected = false, cur_time = 0, message_buffer = {}, recent_message_count = 0, joined_players = {}, modpath = modpath, lib = require("irc"), } -- Compatibility mt_irc = irc dofile(modpath.."/config.lua") dofile(modpath.."/messages.lua") dofile(modpath.."/hooks.lua") dofile(modpath.."/callback.lua") dofile(modpath.."/chatcmds.lua") dofile(modpath.."/botcmds.lua") if irc.config.enable_player_part then dofile(modpath.."/player_part.lua") else setmetatable(irc.joined_players, {__index = function(index) return true end}) end minetest.register_privilege("irc_admin", { description = "Allow IRC administrative tasks to be performed.", give_to_singleplayer = true }) local stepnum = 0 minetest.register_globalstep(function(dtime) return irc:step(dtime) end) function irc:step(dtime) if stepnum == 3 then if self.config.auto_connect then self:connect() end end stepnum = stepnum + 1 if not self.connected then return end -- Hooks will manage incoming messages and errors local good, err = xpcall(function() self.conn:think() end, debug.traceback) if not good then print(err) return end end function irc:connect() if self.connected then minetest.log("error", "IRC: Ignoring attempt to connect when already connected.") return end self.conn = irc.lib.new({ nick = self.config.nick, username = "Minetest", realname = "Minetest", }) self:doHook(self.conn) local good, message = pcall(function() self.conn:connect({ host = self.config.server, port = self.config.port, password = self.config.password, timeout = self.config.timeout, secure = self.config.secure }) end) if not good then minetest.log("error", ("IRC: Connection error: %s: %s -- Reconnecting in ten minutes...") :format(self.config.server, message)) minetest.after(600, function() self:connect() end) return end print("== This is a debug line, please check for it ==") print(self.config.NSPass) print("=== DEBUG FINISHED ===") if self.config.NSPass then self:say("NickServ", "IDENTIFY "..self.config.NSPass) end self.conn:join(self.config.channel, self.config.key) self.connected = true minetest.log("action", "IRC: Connected!") minetest.chat_send_all("IRC: Connected!") end function irc:disconnect(message) if self.connected then --The OnDisconnect hook will clear self.connected and print a disconnect message self.conn:disconnect(message) end end function irc:say(to, message) if not message then message = to to = self.config.channel end to = to or self.config.channel self:queue(irc.msgs.privmsg(to, message)) end function irc:reply(message) if not self.last_from then return end message = message:gsub("[\r\n%z]", " \\n ") self:say(self.last_from, message) end function irc:send(msg) if not self.connected then return end self.conn:send(msg) end function irc:queue(msg) if not self.connected then return end self.conn:queue(msg) end
-- This file is licensed under the terms of the BSD 2-clause license. -- See LICENSE.txt for details. local modpath = minetest.get_modpath(minetest.get_current_modname()) package.path = -- To find LuaIRC's init.lua modpath.."/?/init.lua;" -- For LuaIRC to find its files ..modpath.."/?.lua;" ..package.path -- The build of Lua that Minetest comes with only looks for libraries under -- /usr/local/share and /usr/local/lib but LuaSocket is often installed under -- /usr/share and /usr/lib. if not rawget(_G,"jit") and package.config:sub(1, 1) == "/" then package.path = package.path.. ";/usr/share/lua/5.1/?.lua".. ";/usr/share/lua/5.1/?/init.lua" package.cpath = package.cpath.. -- ";/usr/lib/lua/5.1/?.so" ";/usr/lib/x86_64-linux-gnu/lua/5.1/?.so" end irc = { version = "0.2.0", connected = false, cur_time = 0, message_buffer = {}, recent_message_count = 0, joined_players = {}, modpath = modpath, lib = require("irc"), } -- Compatibility mt_irc = irc dofile(modpath.."/config.lua") dofile(modpath.."/messages.lua") dofile(modpath.."/hooks.lua") dofile(modpath.."/callback.lua") dofile(modpath.."/chatcmds.lua") dofile(modpath.."/botcmds.lua") if irc.config.enable_player_part then dofile(modpath.."/player_part.lua") else setmetatable(irc.joined_players, {__index = function(index) return true end}) end minetest.register_privilege("irc_admin", { description = "Allow IRC administrative tasks to be performed.", give_to_singleplayer = true }) local stepnum = 0 minetest.register_globalstep(function(dtime) return irc:step(dtime) end) function irc:step(dtime) if stepnum == 3 then if self.config.auto_connect then self:connect() end end stepnum = stepnum + 1 if not self.connected then return end -- Hooks will manage incoming messages and errors local good, err = xpcall(function() self.conn:think() end, debug.traceback) if not good then print(err) return end end function irc:connect() if self.connected then minetest.log("error", "IRC: Ignoring attempt to connect when already connected.") return end self.conn = irc.lib.new({ nick = self.config.nick, username = "Minetest", realname = "Minetest", }) self:doHook(self.conn) local good, message = pcall(function() self.conn:connect({ host = self.config.server, port = self.config.port, password = self.config.password, timeout = self.config.timeout, secure = self.config.secure }) end) if not good then minetest.log("error", ("IRC: Connection error: %s: %s -- Reconnecting in ten minutes...") :format(self.config.server, message)) minetest.after(600, function() self:connect() end) return end print("== This is a debug line, please check for it ==") print(self.config.NSPass) print("=== DEBUG FINISHED ===") if self.config.NSPass then self:say("NickServ", "IDENTIFY "..self.config.NSPass) end self.conn:join(self.config.channel, self.config.key) self.connected = true minetest.log("action", "IRC: Connected!") minetest.chat_send_all("IRC: Connected!") end function irc:disconnect(message) if self.connected then --The OnDisconnect hook will clear self.connected and print a disconnect message self.conn:disconnect(message) end end function irc:say(to, message) if not message then message = to to = self.config.channel end to = to or self.config.channel self:queue(irc.msgs.privmsg(to, message)) end function irc:reply(message) if not self.last_from then return end message = message:gsub("[\r\n%z]", " \\n ") self:say(self.last_from, message) end function irc:send(msg) if not self.connected then return end self.conn:send(msg) end function irc:queue(msg) if not self.connected then return end self.conn:queue(msg) end
IRC's bugfix #1 after update
IRC's bugfix #1 after update
Lua
unlicense
LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Ombridride/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Ombridride/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun
ecbfe541f8ab26261494821d1f0942a4b11cb834
module/admin-core/src/model/cbi/admin_index/luci.lua
module/admin-core/src/model/cbi/admin_index/luci.lua
-- ToDo: Translate, Add descriptions and help texts m = Map("luci", "FFLuCI") c = m:section(NamedSection, "main", "core", "Allgemein") c:option(Value, "lang", "Sprache") c:option(Value, "mediaurlbase", "Mediaverzeichnis") f = m:section(NamedSection, "flash", "extern", "Firmwareupgrade") f:option(Value, "keep", "Übernehme Dateien").size = 64 p = m:section(NamedSection, "category_privileges", "core", "Kategorieprivilegien") p.dynamic = true u = m:section(NamedSection, "uci_oncommit", "event", "UCI-Befehle beim Anwenden") u.dynamic = true return m
-- ToDo: Translate, Add descriptions and help texts m = Map("luci", "FFLuCI") c = m:section(NamedSection, "main", "core", "Allgemein") c:option(Value, "lang", "Sprache") c:option(Value, "mediaurlbase", "Mediaverzeichnis") f = m:section(NamedSection, "flash_keep", "extern", "Zu übernehmende Dateien bei Firmwareupgrade") f.dynamic = true p = m:section(NamedSection, "category_privileges", "core", "Kategorieprivilegien") p.dynamic = true u = m:section(NamedSection, "uci_oncommit", "event", "UCI-Befehle beim Anwenden") u.dynamic = true return m
* Fixed changed layout of flash_keep in admin > index
* Fixed changed layout of flash_keep in admin > index
Lua
apache-2.0
deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci
d2b76b191deb5198ccf75017600d67705c24ea22
objects/internal/menuoption.lua
objects/internal/menuoption.lua
--[[------------------------------------------------ -- Love Frames - A GUI library for LOVE -- -- Copyright (c) 2013 Kenny Shields -- --]]------------------------------------------------ -- menuoption object local newobject = loveframes.NewObject("menuoption", "loveframes_object_menuoption", true) --[[--------------------------------------------------------- - func: initialize() - desc: initializes the object --]]--------------------------------------------------------- function newobject:initialize(parent, option_type, menu) self.type = "menuoption" self.text = "Option" self.width = 100 self.height = 25 self.contentwidth = 0 self.contentheight = 0 self.parent = parent self.option_type = option_type or "option" self.menu = menu self.activated = false self.internal = true self.icon = false self.func = nil end --[[--------------------------------------------------------- - func: update(deltatime) - desc: updates the object --]]--------------------------------------------------------- function newobject:update(dt) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible local alwaysupdate = self.alwaysupdate if not visible then if not alwaysupdate then return end end self:CheckHover() local hover = self.hover local parent = self.parent local option_type = self.option_type local base = loveframes.base local update = self.Update if option_type == "submenu_activator" then local activated = self.activated if hover and not activated then self.menu:SetVisible(true) self.menu:SetPos(self:GetX() + self:GetWidth(), self:GetY()) self.activated = true elseif not hover and activated then local hoverobject = loveframes.hoverobject if hoverobject and hoverobject:GetBaseParent() == self.parent then self.menu:SetVisible(false) self.activated = false end end end -- move to parent if there is a parent if parent ~= base then self.x = self.parent.x + self.staticx self.y = self.parent.y + self.staticy end if update then update(self, dt) end end --[[--------------------------------------------------------- - func: draw() - desc: draws the object --]]--------------------------------------------------------- function newobject:draw() local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible if not visible then return end local skins = loveframes.skins.available local skinindex = loveframes.config["ACTIVESKIN"] local defaultskin = loveframes.config["DEFAULTSKIN"] local selfskin = self.skin local skin = skins[selfskin] or skins[skinindex] local drawfunc = skin.DrawMenuOption or skins[defaultskin].DrawMenuOption local draw = self.Draw local drawcount = loveframes.drawcount -- set the object's draw order self:SetDrawOrder() if draw then draw(self) else drawfunc(self) end end --[[--------------------------------------------------------- - func: mousepressed(x, y, button) - desc: called when the player presses a mouse button --]]--------------------------------------------------------- function newobject:mousepressed(x, y, button) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible if not visible then return end end --[[--------------------------------------------------------- - func: mousereleased(x, y, button) - desc: called when the player releases a mouse button --]]--------------------------------------------------------- function newobject:mousereleased(x, y, button) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible if not visible then return end local hover = self.hover local option_type = self.option_type if hover and option_type ~= "divider" and button == "l" then local func = self.func if func then local text = self.text func(self, text) end local basemenu = self.parent:GetBaseMenu() basemenu:SetVisible(false) end end --[[--------------------------------------------------------- - func: SetText(text) - desc: sets the object's text --]]--------------------------------------------------------- function newobject:SetText(text) self.text = text end --[[--------------------------------------------------------- - func: GetText() - desc: gets the object's text --]]--------------------------------------------------------- function newobject:GetText() return self.text end --[[--------------------------------------------------------- - func: SetIcon(icon) - desc: sets the object's icon --]]--------------------------------------------------------- function newobject:SetIcon(icon) if type(icon) == "string" then self.icon = love.graphics.newImage(icon) elseif type(icon) == "userdata" then self.icon = icon end end --[[--------------------------------------------------------- - func: GetIcon() - desc: gets the object's icon --]]--------------------------------------------------------- function newobject:GetIcon() return self.icon end --[[--------------------------------------------------------- - func: SetFunction(func) - desc: sets the object's function --]]--------------------------------------------------------- function newobject:SetFunction(func) self.func = func end
--[[------------------------------------------------ -- Love Frames - A GUI library for LOVE -- -- Copyright (c) 2013 Kenny Shields -- --]]------------------------------------------------ -- menuoption object local newobject = loveframes.NewObject("menuoption", "loveframes_object_menuoption", true) --[[--------------------------------------------------------- - func: initialize() - desc: initializes the object --]]--------------------------------------------------------- function newobject:initialize(parent, option_type, menu) self.type = "menuoption" self.text = "Option" self.width = 100 self.height = 25 self.contentwidth = 0 self.contentheight = 0 self.parent = parent self.option_type = option_type or "option" self.menu = menu self.activated = false self.internal = true self.icon = false self.func = nil end --[[--------------------------------------------------------- - func: update(deltatime) - desc: updates the object --]]--------------------------------------------------------- function newobject:update(dt) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible local alwaysupdate = self.alwaysupdate if not visible then if not alwaysupdate then return end end self:CheckHover() local hover = self.hover local parent = self.parent local option_type = self.option_type local activated = self.activated local base = loveframes.base local update = self.Update if option_type == "submenu_activator" then if hover and not activated then self.menu:SetVisible(true) self.menu:MoveToTop() self.activated = true elseif not hover and activated then local hoverobject = loveframes.hoverobject if hoverobject and hoverobject:GetBaseParent() == self.parent then self.menu:SetVisible(false) self.activated = false end elseif activated then local screen_width = love.graphics.getWidth() local screen_height = love.graphics.getHeight() local sx = self.x local sy = self.y local width = self.width local height = self.height local x1 = sx + width if x1 + self.menu.width <= screen_width then self.menu.x = x1 else self.menu.x = sx - self.menu.width end if sy + self.menu.height <= screen_height then self.menu.y = sy else self.menu.y = (sy + height) - self.menu.height end end end -- move to parent if there is a parent if parent ~= base then self.x = self.parent.x + self.staticx self.y = self.parent.y + self.staticy end if update then update(self, dt) end end --[[--------------------------------------------------------- - func: draw() - desc: draws the object --]]--------------------------------------------------------- function newobject:draw() local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible if not visible then return end local skins = loveframes.skins.available local skinindex = loveframes.config["ACTIVESKIN"] local defaultskin = loveframes.config["DEFAULTSKIN"] local selfskin = self.skin local skin = skins[selfskin] or skins[skinindex] local drawfunc = skin.DrawMenuOption or skins[defaultskin].DrawMenuOption local draw = self.Draw local drawcount = loveframes.drawcount -- set the object's draw order self:SetDrawOrder() if draw then draw(self) else drawfunc(self) end end --[[--------------------------------------------------------- - func: mousepressed(x, y, button) - desc: called when the player presses a mouse button --]]--------------------------------------------------------- function newobject:mousepressed(x, y, button) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible if not visible then return end end --[[--------------------------------------------------------- - func: mousereleased(x, y, button) - desc: called when the player releases a mouse button --]]--------------------------------------------------------- function newobject:mousereleased(x, y, button) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible if not visible then return end local hover = self.hover local option_type = self.option_type if hover and option_type ~= "divider" and button == "l" then local func = self.func if func then local text = self.text func(self, text) end local basemenu = self.parent:GetBaseMenu() basemenu:SetVisible(false) end end --[[--------------------------------------------------------- - func: SetText(text) - desc: sets the object's text --]]--------------------------------------------------------- function newobject:SetText(text) self.text = text end --[[--------------------------------------------------------- - func: GetText() - desc: gets the object's text --]]--------------------------------------------------------- function newobject:GetText() return self.text end --[[--------------------------------------------------------- - func: SetIcon(icon) - desc: sets the object's icon --]]--------------------------------------------------------- function newobject:SetIcon(icon) if type(icon) == "string" then self.icon = love.graphics.newImage(icon) elseif type(icon) == "userdata" then self.icon = icon end end --[[--------------------------------------------------------- - func: GetIcon() - desc: gets the object's icon --]]--------------------------------------------------------- function newobject:GetIcon() return self.icon end --[[--------------------------------------------------------- - func: SetFunction(func) - desc: sets the object's function --]]--------------------------------------------------------- function newobject:SetFunction(func) self.func = func end
Fix submenu positioning
Fix submenu positioning
Lua
mit
SimLeek/the-Open-Source-Pony-Game
94cdc74e851b9eeb4d6bd64d8f853ae3be67fc27
npc/base/talk.lua
npc/base/talk.lua
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] --- Base NPC script for talking NPCs -- -- This script offers all functions needed to get NPCs to talk. -- -- Author: Martin Karing local common = require("base.common") local messages = require("base.messages") local class = require("base.class") local baseNPC = require("npc.base.basic") local processorList = require("npc.base.responses") local tools = require("npc.base.tools") local consequence = require("npc.base.consequence.consequence") local condition = require("npc.base.condition.condition") local talkNPC = class(function(self, rootNPC) if rootNPC == nil or not rootNPC:is_a(baseNPC) then return end self["_parent"] = rootNPC self["_entry"] = nil self["_cycleText"] = nil self["_state"] = 0 self["_saidNumber"] = nil self["_nextCycleText"] = -1 end) local talkNPCEntry = class(function(self) self["_trigger"] = {} self["_conditions"] = {} self["_responses"] = {} self["_responseProcessors"] = {} self["_responsesCount"] = 0 self["_consequences"] = {} self["_parent"] = nil end) function talkNPC:addCycleText(germanText, englishText) if (self._cycleText == nil) then self._cycleText = messages.Messages() self._parent:addCycle(self) end self._cycleText:addMessage(germanText, englishText) end function talkNPC:addTalkingEntry(newEntry) if (newEntry == nil or not newEntry:is_a(talkNPCEntry)) then return end if (self._entry == nil) then self._parent:addRecvText(self) self._entry = {} end newEntry:setParent(self) table.insert(self._entry, newEntry) end function talkNPC:receiveText(npcChar, texttype, player, text) local result = false for _, entry in pairs(self._entry) do if entry:checkEntry(npcChar, texttype, player, text) then entry:execute(npcChar, player) result = true return true end end return result end function talkNPC:nextCycle(npcChar, counter) if (counter >= self._nextCycleText) then self._nextCycleText = math.random(6000, 9000) --10 to 15 minutes local german, english = self._cycleText:getRandomMessage() local textTypeDe, textDe = tools.get_text_and_talktype(german) local textTypeEn, textEn = tools.get_text_and_talktype(english) npcChar:talk(textTypeDe, textDe, textEn) else self._nextCycleText = self._nextCycleText - counter end return self._nextCycleText end function talkNPCEntry:addTrigger(text) if text == nil or type(text) ~= "string" then return end text = string.lower(text) text = string.gsub(text,'([ ]+)',' .*') -- replace all spaces by " .*" table.insert(self._trigger, text) end function talkNPCEntry:setParent(npc) for _, value in pairs(self._conditions) do value:setNPC(npc) end for _, value in pairs(self._consequences) do value:setNPC(npc) end self._parent = npc end function talkNPCEntry:addCondition(c) if c == nil or not c:is_a(condition) then return end table.insert(self._conditions, c) if (self._parent ~= nil) then c:setNPC(self._parent) end end function talkNPCEntry:addResponse(text) if text == nil or type(text) ~= "string" then return end table.insert(self._responses, text) self._responsesCount = self._responsesCount + 1 for _, processor in pairs(processorList) do if processor:check(text) then if (self._responseProcessors[self._responsesCount] == nil) then self._responseProcessors[self._responsesCount] = {} end table.insert(self._responseProcessors[self._responsesCount], processor) end end end function talkNPCEntry:addConsequence(c) if c == nil or not c:is_a(consequence) then return end table.insert(self._consequences, c) if (self._parent ~= nil) then c:setNPC(self._parent) end end function talkNPCEntry:checkEntry(npcChar, texttype, player, text) for _1, pattern in pairs(self._trigger) do local a, _2, number = string.find(text, pattern) self._saidNumber = number if a ~= nil then local conditionsResult = true for _3, condition in pairs(self._conditions) do if not condition:check(npcChar, texttype, player) then conditionsResult = false break end end if conditionsResult then return true end end end end function talkNPCEntry:execute(npcChar, player) if (self._responsesCount > 0) then local selectedResponse = math.random(1, self._responsesCount) local responseText = self._responses[selectedResponse] local responseProcessors = self._responseProcessors[selectedResponse] if (responseProcessors ~= nil) then for _, processor in pairs(responseProcessors) do responseText = processor:process(player, self._parent, npcChar, responseText) end end local textType, text = tools.get_text_and_talktype(responseText) npcChar:talk(textType, text) end for _, consequence in pairs(self._consequences) do if consequence then consequence:perform(npcChar, player) end end end talkNPC["talkNPCEntry"] = talkNPCEntry return talkNPC
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] --- Base NPC script for talking NPCs -- -- This script offers all functions needed to get NPCs to talk. -- -- Author: Martin Karing local common = require("base.common") local messages = require("base.messages") local class = require("base.class") local baseNPC = require("npc.base.basic") local processorList = require("npc.base.responses") local tools = require("npc.base.tools") local consequence = require("npc.base.consequence.consequence") local condition = require("npc.base.condition.condition") local talkNPC = class(function(self, rootNPC) if rootNPC == nil or not rootNPC:is_a(baseNPC) then return end self["_parent"] = rootNPC self["_entry"] = nil self["_cycleText"] = nil self["_state"] = 0 self["_saidNumber"] = nil self["_nextCycleText"] = -1 end) local talkNPCEntry = class(function(self) self["_trigger"] = {} self["_conditions"] = {} self["_responses"] = {} self["_responseProcessors"] = {} self["_responsesCount"] = 0 self["_consequences"] = {} self["_parent"] = nil end) function talkNPC:addCycleText(germanText, englishText) if (self._cycleText == nil) then self._cycleText = messages.Messages() self._parent:addCycle(self) end self._cycleText:addMessage(germanText, englishText) end function talkNPC:addTalkingEntry(newEntry) if (newEntry == nil or not newEntry:is_a(talkNPCEntry)) then return end if (self._entry == nil) then self._parent:addRecvText(self) self._entry = {} end newEntry:setParent(self) table.insert(self._entry, newEntry) end function talkNPC:receiveText(npcChar, texttype, player, text) local result = false for _, entry in pairs(self._entry) do if entry:checkEntry(npcChar, texttype, player, text) then entry:execute(npcChar, player) result = true return true end end return result end function talkNPC:nextCycle(npcChar, counter) seenNPCs = world:getNPCSInRangeOf(npcChar.pos,15) seenPlayers = world:getPlayersInRangeOf(npcChar.pos,15) if (counter >= self._nextCycleText) then self._nextCycleText = math.random(3000, 6000) * math.max(1, (#seenNPCs)/2 + #seenPlayers -1) --5 to 10 minutes times NPCs+players around local german, english = self._cycleText:getRandomMessage() local textTypeDe, textDe = tools.get_text_and_talktype(german) local textTypeEn, textEn = tools.get_text_and_talktype(english) npcChar:talk(textTypeDe, textDe, textEn) else self._nextCycleText = self._nextCycleText - counter end return self._nextCycleText end function talkNPCEntry:addTrigger(text) if text == nil or type(text) ~= "string" then return end text = string.lower(text) text = string.gsub(text,'([ ]+)',' .*') -- replace all spaces by " .*" table.insert(self._trigger, text) end function talkNPCEntry:setParent(npc) for _, value in pairs(self._conditions) do value:setNPC(npc) end for _, value in pairs(self._consequences) do value:setNPC(npc) end self._parent = npc end function talkNPCEntry:addCondition(c) if c == nil or not c:is_a(condition) then return end table.insert(self._conditions, c) if (self._parent ~= nil) then c:setNPC(self._parent) end end function talkNPCEntry:addResponse(text) if text == nil or type(text) ~= "string" then return end table.insert(self._responses, text) self._responsesCount = self._responsesCount + 1 for _, processor in pairs(processorList) do if processor:check(text) then if (self._responseProcessors[self._responsesCount] == nil) then self._responseProcessors[self._responsesCount] = {} end table.insert(self._responseProcessors[self._responsesCount], processor) end end end function talkNPCEntry:addConsequence(c) if c == nil or not c:is_a(consequence) then return end table.insert(self._consequences, c) if (self._parent ~= nil) then c:setNPC(self._parent) end end function talkNPCEntry:checkEntry(npcChar, texttype, player, text) for _1, pattern in pairs(self._trigger) do local a, _2, number = string.find(text, pattern) self._saidNumber = number if a ~= nil then local conditionsResult = true for _3, condition in pairs(self._conditions) do if not condition:check(npcChar, texttype, player) then conditionsResult = false break end end if conditionsResult then return true end end end end function talkNPCEntry:execute(npcChar, player) if (self._responsesCount > 0) then local selectedResponse = math.random(1, self._responsesCount) local responseText = self._responses[selectedResponse] local responseProcessors = self._responseProcessors[selectedResponse] if (responseProcessors ~= nil) then for _, processor in pairs(responseProcessors) do responseText = processor:process(player, self._parent, npcChar, responseText) end end local textType, text = tools.get_text_and_talktype(responseText) npcChar:talk(textType, text) end for _, consequence in pairs(self._consequences) do if consequence then consequence:perform(npcChar, player) end end end talkNPC["talkNPCEntry"] = talkNPCEntry return talkNPC
Fix #107
Fix #107
Lua
agpl-3.0
Illarion-eV/Illarion-Content,vilarion/Illarion-Content,KayMD/Illarion-Content
6e93078cf12179a6884c3fa3fe85c3b72b52619b
item/id_2207_well.lua
item/id_2207_well.lua
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- UPDATE items SET itm_script='item.id_2207_well' WHERE itm_id IN (2207); local common = require("base.common") local lookat = require("base.lookat") local climbing = require("content.climbing") local M = {} local wellPosition1 = position(528, 555, 0) -- maze local wellPosition2 = position(105, 600, 0) -- Cadomyr local wellPosition3 = position(357, 272, 0) -- Galmair local wellPosition4 = position(849, 841, 0) -- Runewick function M.UseItem(User, SourceItem, ltstate) if (SourceItem:getData("modifier") == "wishing well") then common.InformNLS(User, "Vielleicht kann sich einer deiner Wnsche erfllen, wenn du etwas hineinwirfst?", "Maybe one of your wishes come true, if you pitch something in?") -- TODO: select dialog for coins return end local climbable = false if SourceItem.pos == wellPosition1 then climbable = true elseif SourceItem.pos == wellPosition2 then climbable = true elseif SourceItem.pos == wellPosition3 then climbable = true elseif SourceItem.pos == wellPosition4 then climbable = true end if climbable then common.HighInformNLS(User, "Du brauchst ein Seil um hier hinab zu klettern.", "You need a rope to climb down here.") if content.climbing.hasRope(User) then content.climbing.climbDown(User) end end -- TODO: select diaolg water scooping + climbing end function M.LookAtItem(User, Item) local lookAt = lookat.GenerateLookAt(User, Item) if ( Item:getData("modifier") == "wishing well" ) then lookAt.name = common.GetNLS(User, "Wunschbrunnen", "wishing well") elseif Item.pos == wellPosition1 then lookAt.name = common.GetNLS(User, "Ausgetrockneter Brunnen", "Dry well") elseif Item.pos == wellPosition2 then lookAt.name = common.GetNLS(User, "Zisterne von Cadomyr", "Cadomyr Cavern") elseif Item.pos == wellPosition3 then lookAt.name = common.GetNLS(User, "Zisterne von Galmair", "Galmair Cavern") elseif Item.pos == wellPosition4 then lookAt.name = common.GetNLS(User, "Zisterne von Runewick", "Runewick Cavern") end return lookAt end return M
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- UPDATE items SET itm_script='item.id_2207_well' WHERE itm_id IN (2207); local common = require("base.common") local lookat = require("base.lookat") local climbing = require("content.climbing") local M = {} local wellPosition1 = position(528, 555, 0) -- maze local wellPosition2 = position(105, 600, 0) -- Cadomyr local wellPosition3 = position(357, 272, 0) -- Galmair local wellPosition4 = position(849, 841, 0) -- Runewick function M.UseItem(User, SourceItem, ltstate) if (SourceItem:getData("modifier") == "wishing well") then common.InformNLS(User, "Vielleicht kann sich einer deiner Wnsche erfllen, wenn du etwas hineinwirfst?", "Maybe one of your wishes come true, if you pitch something in?") -- TODO: select dialog for coins return end local climbable = false if SourceItem.pos == wellPosition1 then climbable = true elseif SourceItem.pos == wellPosition2 then climbable = true elseif SourceItem.pos == wellPosition3 then climbable = true elseif SourceItem.pos == wellPosition4 then climbable = true end if climbable then common.HighInformNLS(User, "Du brauchst ein Seil um hier hinab zu klettern.", "You need a rope to climb down here.") if climbing.hasRope(User) then climbing.climbDown(User) end return end -- TODO: select diaolg water scooping + climbing end function M.LookAtItem(User, Item) local lookAt = lookat.GenerateLookAt(User, Item) if ( Item:getData("modifier") == "wishing well" ) then lookAt.name = common.GetNLS(User, "Wunschbrunnen", "wishing well") elseif Item.pos == wellPosition1 then lookAt.name = common.GetNLS(User, "Ausgetrockneter Brunnen", "Dry well") elseif Item.pos == wellPosition2 then lookAt.name = common.GetNLS(User, "Zisterne von Cadomyr", "Cadomyr Cavern") elseif Item.pos == wellPosition3 then lookAt.name = common.GetNLS(User, "Zisterne von Galmair", "Galmair Cavern") elseif Item.pos == wellPosition4 then lookAt.name = common.GetNLS(User, "Zisterne von Runewick", "Runewick Cavern") end return lookAt end return M
fix my climbing errors again
fix my climbing errors again
Lua
agpl-3.0
LaFamiglia/Illarion-Content,Baylamon/Illarion-Content,vilarion/Illarion-Content,Illarion-eV/Illarion-Content,KayMD/Illarion-Content
bf0d07d6982011f256a3759eb3455e8a96faf798
src/nodes/rock.lua
src/nodes/rock.lua
local Rock = {} Rock.__index = Rock Rock.rock = true local RockImage = love.graphics.newImage('images/rock.png') local RockItem = require('items/rockItem') --- -- Creates a new rock object -- @return the rock object created function Rock.new(node, collider) local rock = {} setmetatable(rock, Rock) rock.image = RockImage rock.foreground = node.properties.foreground rock.bb = collider:addRectangle(node.x, node.y, node.width, node.height) rock.bb.node = rock rock.collider = collider rock.position = {x = node.x, y = node.y} rock.width = node.width rock.height = node.height rock.touchedPlayer = nil rock.exists = true return rock end --- -- Draws the rock to the screen -- @return nil function Rock:draw() if not self.exists then return end love.graphics.drawq(self.image, love.graphics.newQuad(0,0, self.width,self.height,self.width,self.height), self.position.x, self.position.y) end --- -- Called when the rock begins colliding with another node -- @return nil function Rock:collide(node, dt, mtv_x, mtv_y) if node and node.character then self.touchedPlayer = node end end --- -- Called when the rock finishes colliding with another node -- @return nil function Rock:collide_end(node, dt) if node and node.character then self.touchedPlayer = nil end end --- -- Updates the rock and allows the player to pick it up. function Rock:update(dt, player) if not self.exists then return end if love.keyboard.isDown('lshift') or love.keyboard.isDown('rshift') then local item = RockItem.new() if player.inventory:addItem(item) then self.exists = false end end end return Rock
local Rock = {} Rock.__index = Rock Rock.rock = true local RockImage = love.graphics.newImage('images/rock.png') local RockItem = require('items/rockItem') --- -- Creates a new rock object -- @return the rock object created function Rock.new(node, collider) local rock = {} setmetatable(rock, Rock) rock.image = RockImage rock.foreground = node.properties.foreground rock.bb = collider:addRectangle(node.x, node.y, node.width, node.height) rock.bb.node = rock rock.collider = collider rock.position = {x = node.x, y = node.y} rock.width = node.width rock.height = node.height rock.touchedPlayer = nil rock.exists = true return rock end --- -- Draws the rock to the screen -- @return nil function Rock:draw() if not self.exists then return end love.graphics.drawq(self.image, love.graphics.newQuad(0,0, self.width,self.height,self.width,self.height), self.position.x, self.position.y) end --- -- Called when the rock begins colliding with another node -- @return nil function Rock:collide(node, dt, mtv_x, mtv_y) if node and node.character then self.touchedPlayer = node end end --- -- Called when the rock finishes colliding with another node -- @return nil function Rock:collide_end(node, dt) if node and node.character then self.touchedPlayer = nil end end --- -- Updates the rock and allows the player to pick it up. function Rock:update() if not self.exists then return end if (love.keyboard.isDown('lshift') or love.keyboard.isDown('rshift')) and self.touchedPlayer then local item = RockItem.new() if self.touchedPlayer.inventory:addItem(item) then self.exists = false end end end return Rock
Fixed bug where player could pick up rock if they were anywhere in the level
Fixed bug where player could pick up rock if they were anywhere in the level
Lua
mit
hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua
d3316568e18e06efc84b5864e82e9c2580597f75
kong/plugins/jwt/schema.lua
kong/plugins/jwt/schema.lua
local typedefs = require "kong.db.schema.typedefs" return { name = "jwt", fields = { { protocols = typedefs.protocols_http }, { config = { type = "record", fields = { { uri_param_names = { type = "set", elements = { type = "string" }, default = { "jwt" }, }, }, { cookie_names = { type = "set", elements = { type = "string" }, default = {} }, }, { key_claim_name = { type = "string", default = "iss" }, }, { secret_is_base64 = { type = "boolean", default = false }, }, { claims_to_verify = { type = "set", elements = { type = "string", one_of = { "exp", "nbf" }, }, }, }, { anonymous = { type = "string" }, }, { run_on_preflight = { type = "boolean", default = true }, }, { maximum_expiration = { type = "number", default = 0, between = { 0, 31536000 }, }, }, { header_names = { type = "set", elements = { type = "string" }, default = { "authorization" }, }, }, }, }, }, }, entity_checks = { { conditional = { if_field = "config.maximum_expiration", if_match = { gt = 0 }, then_field = "config.claims_to_verify", then_match = { contains = "exp" }, }, }, }, }
local typedefs = require "kong.db.schema.typedefs" return { name = "jwt", fields = { { consumer = typedefs.no_consumer }, { protocols = typedefs.protocols_http }, { config = { type = "record", fields = { { uri_param_names = { type = "set", elements = { type = "string" }, default = { "jwt" }, }, }, { cookie_names = { type = "set", elements = { type = "string" }, default = {} }, }, { key_claim_name = { type = "string", default = "iss" }, }, { secret_is_base64 = { type = "boolean", default = false }, }, { claims_to_verify = { type = "set", elements = { type = "string", one_of = { "exp", "nbf" }, }, }, }, { anonymous = { type = "string" }, }, { run_on_preflight = { type = "boolean", default = true }, }, { maximum_expiration = { type = "number", default = 0, between = { 0, 31536000 }, }, }, { header_names = { type = "set", elements = { type = "string" }, default = { "authorization" }, }, }, }, }, }, }, entity_checks = { { conditional = { if_field = "config.maximum_expiration", if_match = { gt = 0 }, then_field = "config.claims_to_verify", then_match = { contains = "exp" }, }, }, }, }
fix(JWT) do not allow on consumer (#6777)
fix(JWT) do not allow on consumer (#6777)
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
4712a8ebb14be99341734b5657a35ec2f882ca5c
tests/test-dns.lua
tests/test-dns.lua
return require('lib/tap')(function (test) local isWindows = require('lib/utils').isWindows local function errorAllowed(err) -- allowed errors from gnulib's test-getaddrinfo.c return err == "EAI_AGAIN" -- offline/no network connection or err == "EAI_NONAME" -- IRIX returns this for "https" or err == "EAI_SERVICE" -- Solaris returns this for "http"/"https" or err == "EAI_NODATA" -- AIX returns this for "https" end test("Get all local http addresses", function (print, p, expect, uv) assert(uv.getaddrinfo(nil, "http", nil, expect(function (err, res) if errorAllowed(err) then print(err, "skipping") return end assert(not err, err) p(res, #res) assert(res[1].port == 80) end))) end) test("Get all local http addresses sync", function (print, p, expect, uv) local res, errstr, err = uv.getaddrinfo(nil, "http") if errorAllowed(err) then print(err, "skipping") return end assert(res, errstr) p(res, #res) assert(res[1].port == 80) end) test("Get only ipv4 tcp adresses for luvit.io", function (print, p, expect, uv) assert(uv.getaddrinfo("luvit.io", nil, { socktype = "stream", family = "inet", }, expect(function (err, res) if errorAllowed(err) then print(err, "skipping") return end assert(not err, err) p(res, #res) assert(#res > 0) end))) end) -- FIXME: this test always fails on AppVeyor for some reason if isWindows and not os.getenv'APPVEYOR' then test("Get only ipv6 tcp adresses for luvit.io", function (print, p, expect, uv) assert(uv.getaddrinfo("luvit.io", nil, { socktype = "stream", family = "inet6", }, expect(function (err, res) if errorAllowed(err) then print(err, "skipping") return end assert(not err, err) p(res, #res) assert(#res == 1) end))) end) end test("Get ipv4 and ipv6 tcp adresses for luvit.io", function (print, p, expect, uv) assert(uv.getaddrinfo("luvit.io", nil, { socktype = "stream", }, expect(function (err, res) if errorAllowed(err) then print(err, "skipping") return end assert(not err, err) p(res, #res) assert(#res > 0) end))) end) test("Get all adresses for luvit.io", function (print, p, expect, uv) assert(uv.getaddrinfo("luvit.io", nil, nil, expect(function (err, res) if errorAllowed(err) then print(err, "skipping") return end assert(not err, err) p(res, #res) assert(#res > 0) end))) end) test("Lookup local ipv4 address", function (print, p, expect, uv) assert(uv.getnameinfo({ family = "inet", }, expect(function (err, hostname, service) if errorAllowed(err) then print(err, "skipping") return end p{err=err,hostname=hostname,service=service} assert(not err, err) assert(hostname) assert(service) end))) end) test("Lookup local ipv4 address sync", function (print, p, expect, uv) local hostname, service, err = uv.getnameinfo({ family = "inet", }) if errorAllowed(err) then print(err, "skipping") return end p{hostname=hostname,service=service} assert(hostname) assert(service) end) test("Lookup local 127.0.0.1 ipv4 address", function (print, p, expect, uv) assert(uv.getnameinfo({ ip = "127.0.0.1", }, expect(function (err, hostname, service) p{err=err,hostname=hostname,service=service} assert(not err, err) assert(hostname) assert(service) end))) end) test("Lookup local ipv6 address", function (print, p, expect, uv) assert(uv.getnameinfo({ family = "inet6", }, expect(function (err, hostname, service) p{err=err,hostname=hostname,service=service} assert(not err, err) assert(hostname) assert(service) end))) end) test("Lookup local ::1 ipv6 address", function (print, p, expect, uv) assert(uv.getnameinfo({ ip = "::1", }, expect(function (err, hostname, service) p{err=err,hostname=hostname,service=service} assert(not err, err) assert(hostname) assert(service) end))) end) test("Lookup local port 80 service", function (print, p, expect, uv) assert(uv.getnameinfo({ port = 80, family = "inet6", }, expect(function (err, hostname, service) p{err=err,hostname=hostname,service=service} assert(not err, err) assert(hostname) assert(service == "http") end))) end) end)
return require('lib/tap')(function (test) local isWindows = require('lib/utils').isWindows local function errorAllowed(err) -- allowed errors from gnulib's test-getaddrinfo.c return err == "EAI_AGAIN" -- offline/no network connection or err == "EAI_NONAME" -- IRIX returns this for "https" or err == "EAI_SERVICE" -- Solaris returns this for "http"/"https" or err == "EAI_NODATA" -- AIX returns this for "https" end test("Get all local http addresses", function (print, p, expect, uv) assert(uv.getaddrinfo(nil, "http", nil, expect(function (err, res) if errorAllowed(err) then print(err, "skipping") return end assert(not err, err) p(res, #res) assert(res[1].port == 80) end))) end) test("Get all local http addresses sync", function (print, p, expect, uv) local version = 0x10000 + 3*0x100 + 0 if uv.version() < version then print("skipped, requires libuv >= 1.3.0") return end local res, errstr, err = uv.getaddrinfo(nil, "http") if errorAllowed(err) then print(err, "skipping") return end assert(res, errstr) p(res, #res) assert(res[1].port == 80) end) test("Get only ipv4 tcp adresses for luvit.io", function (print, p, expect, uv) assert(uv.getaddrinfo("luvit.io", nil, { socktype = "stream", family = "inet", }, expect(function (err, res) if errorAllowed(err) then print(err, "skipping") return end assert(not err, err) p(res, #res) assert(#res > 0) end))) end) -- FIXME: this test always fails on AppVeyor for some reason if isWindows and not os.getenv'APPVEYOR' then test("Get only ipv6 tcp adresses for luvit.io", function (print, p, expect, uv) assert(uv.getaddrinfo("luvit.io", nil, { socktype = "stream", family = "inet6", }, expect(function (err, res) if errorAllowed(err) then print(err, "skipping") return end assert(not err, err) p(res, #res) assert(#res == 1) end))) end) end test("Get ipv4 and ipv6 tcp adresses for luvit.io", function (print, p, expect, uv) assert(uv.getaddrinfo("luvit.io", nil, { socktype = "stream", }, expect(function (err, res) if errorAllowed(err) then print(err, "skipping") return end assert(not err, err) p(res, #res) assert(#res > 0) end))) end) test("Get all adresses for luvit.io", function (print, p, expect, uv) assert(uv.getaddrinfo("luvit.io", nil, nil, expect(function (err, res) if errorAllowed(err) then print(err, "skipping") return end assert(not err, err) p(res, #res) assert(#res > 0) end))) end) test("Lookup local ipv4 address", function (print, p, expect, uv) assert(uv.getnameinfo({ family = "inet", }, expect(function (err, hostname, service) if errorAllowed(err) then print(err, "skipping") return end p{err=err,hostname=hostname,service=service} assert(not err, err) assert(hostname) assert(service) end))) end) test("Lookup local ipv4 address sync", function (print, p, expect, uv) local hostname, service, err = uv.getnameinfo({ family = "inet", }) if errorAllowed(err) then print(err, "skipping") return end p{hostname=hostname,service=service} assert(hostname) assert(service) end) test("Lookup local 127.0.0.1 ipv4 address", function (print, p, expect, uv) assert(uv.getnameinfo({ ip = "127.0.0.1", }, expect(function (err, hostname, service) p{err=err,hostname=hostname,service=service} assert(not err, err) assert(hostname) assert(service) end))) end) test("Lookup local ipv6 address", function (print, p, expect, uv) assert(uv.getnameinfo({ family = "inet6", }, expect(function (err, hostname, service) p{err=err,hostname=hostname,service=service} assert(not err, err) assert(hostname) assert(service) end))) end) test("Lookup local ::1 ipv6 address", function (print, p, expect, uv) assert(uv.getnameinfo({ ip = "::1", }, expect(function (err, hostname, service) p{err=err,hostname=hostname,service=service} assert(not err, err) assert(hostname) assert(service) end))) end) test("Lookup local port 80 service", function (print, p, expect, uv) assert(uv.getnameinfo({ port = 80, family = "inet6", }, expect(function (err, hostname, service) p{err=err,hostname=hostname,service=service} assert(not err, err) assert(hostname) assert(service == "http") end))) end) end)
Fix test-dns's sync getaddrinfo test when using libuv < 1.3.0
Fix test-dns's sync getaddrinfo test when using libuv < 1.3.0
Lua
apache-2.0
zhaozg/luv,luvit/luv,luvit/luv,zhaozg/luv
3fefaaf27210732c8378e27397991a38258c8a04
.config/awesome/widgets/mail.lua
.config/awesome/widgets/mail.lua
local wibox = require("wibox") local awful = require("awful") local gears = require("gears") local mail = {} --- Email local path_to_icons = "/usr/share/icons/Arc/actions/22/" local mail_icon = wibox.widget.imagebox() mail_icon:set_image(path_to_icons .. "/mail-mark-unread.png") -- mail_icon:set_image(awful.util.getdir("config") .. "/email-closed.png") --mail_widget_container = wibox.widget local mail_textbox = wibox.widget{ align = 'center', valign = 'center', widget = wibox.widget.textbox } --wibox.widget.textbox() mail_textbox:set_font("Iosevka Bold 8") local mail_widget = wibox.widget { mail_icon, mail_textbox , layout = wibox.layout.align.horizontal, } local function mail_update(widget) local fd = io.popen("ls ~/Maildir/INBOX/new | wc -w | tr -d '\n'") local mail_new = fd:read("*all") fd:close() return mail_new end local current_status = 0 local function update_mail_status() local mail_new = mail_update() mail_textbox:set_text("(" .. mail_new .. ")") -- .. mail_new) if tonumber(mail_new) == 0 then mail_icon:set_image(path_to_icons .. "/mail-mark-read.png") else mail_icon:set_image(path_to_icons .. "/mail-mark-unread.png") end end local mail_widget_timer = gears.timer({timeout = 1}) mail_widget_timer:connect_signal("timeout", update_mail_status) update_mail_status() return mail_widget
local wibox = require("wibox") local awful = require("awful") local gears = require("gears") local mail = {} --- Email local path_to_icons = "/usr/share/icons/Arc/actions/22/" local mail_icon = wibox.widget.imagebox() mail_icon:set_image(path_to_icons .. "/mail-mark-unread.png") -- mail_icon:set_image(awful.util.getdir("config") .. "/email-closed.png") --mail_widget_container = wibox.widget local mail_textbox = wibox.widget{ align = 'center', valign = 'center', widget = wibox.widget.textbox } --wibox.widget.textbox() mail_textbox:set_font("Iosevka Bold 8") local mail_widget = wibox.widget { mail_icon, mail_textbox , layout = wibox.layout.align.horizontal, } local function mail_update(widget) local fd = io.popen("ls ~/Maildir/INBOX/new | wc -w | tr -d '\n'") local mail_new = fd:read("*all") fd:close() return mail_new end local current_status = 0 local function update_mail_status() local mail_new = mail_update() mail_textbox:set_text("[" .. mail_new .. "]") -- .. mail_new) if tonumber(mail_new) == 0 then mail_icon:set_image(path_to_icons .. "/mail-mark-read.png") else mail_icon:set_image(path_to_icons .. "/mail-mark-unread.png") end return true end local mail_widget_timer = gears.timer.start_new(1, update_mail_status) -- mail_widget_timer:connect_signal("timeout", update_mail_status) update_mail_status() return mail_widget
AwesomeWM: Fix mail widget timer
AwesomeWM: Fix mail widget timer
Lua
mit
hershsingh/dotfiles,hershsingh/dotfiles
4df1c3340d44e27a35af825473b1c4e091f8db09
upcache/common.lua
upcache/common.lua
local module = {} local mp = require 'MessagePack' local log = ngx.log local ERR = ngx.ERR local INFO = ngx.INFO local json = require 'cjson.safe' module.console = {} function module.console.info(...) return log(INFO, ...) end function module.console.error(...) return log(ERR, ...) end function module.console.encode(...) return json.encode(...) end module.prefixHeader = "X-Upcache" function module.get_variants(key, what) local pac = ngx.shared.upcacheVariants:get(key) if pac == nil then return nil end return mp.unpack(pac)[what] end function module.set_variants(key, what, data) local vars = module.get_variants(key) if vars == nil then vars = {} end vars[what] = data ngx.shared.upcacheVariants:set(key, mp.pack(vars)) return vars end return module
local module = {} local mp = require 'MessagePack' local log = ngx.log local ERR = ngx.ERR local INFO = ngx.INFO local json = require 'cjson.safe' module.console = {} function module.console.info(...) return log(INFO, ...) end function module.console.error(...) return log(ERR, ...) end function module.console.encode(...) return json.encode(...) end module.prefixHeader = "X-Upcache" function module.get_variants(key, what) local pac = ngx.shared.upcacheVariants:get(key) if pac == nil then return nil end local unpac = mp.unpack(pac) if what ~= nil then unpac = unpac[what] end return unpac end function module.set_variants(key, what, data) local vars = module.get_variants(key) if vars == nil then vars = {} end vars[what] = data ngx.shared.upcacheVariants:set(key, mp.pack(vars)) return vars end return module
Fix error in getting restrictions
Fix error in getting restrictions
Lua
mit
kapouer/upcache,kapouer/cache-protocols
58459619733b04f1d7e8c15fd4ba09d5ba47da08
genie.lua
genie.lua
newoption { trigger = "UWP", description = "Generates Universal Windows Platform application type", } newoption { trigger = "DX12", description = "Generates a sample for DirectX12", } if not _ACTION then _ACTION="vs2017" end outFolderRoot = "Bin/" .. _ACTION .. "/"; isVisualStudio = false isUWP = false if _ACTION == "vs2010" or _ACTION == "vs2012" or _ACTION == "vs2015" or _ACTION == "vs2017" then isVisualStudio = true end if _OPTIONS["UWP"] then isUWP = true end if isUWP then premake.vstudio.toolset = "v140" premake.vstudio.storeapp = "10.0" end outputFolder = "Build/" .. _ACTION if isUWP then outputFolder = outputFolder .. "_UWP" end solution "Brofiler" language "C++" if _ACTION == "vs2017" then windowstargetplatformversion "10.0.17134.0" end startproject "ConsoleApp" location ( outputFolder ) flags { "NoManifest", "ExtraWarnings", "Unicode" } optimization_flags = { "OptimizeSpeed" } if isVisualStudio then debugdir (outFolderRoot) buildoptions { "/wd4127", -- Conditional expression is constant "/wd4091" -- 'typedef ': ignored on left of '' when no variable is declared } end if isUWP then defines { "BRO_UWP=1" } end defines { "USE_BROFILER=1"} defines { "BRO_FIBERS=1"} local config_list = { "Release", "Debug", } local platform_list = { "x32", "x64", "Native", } configurations(config_list) platforms(platform_list) -- CONFIGURATIONS if _ACTION == "vs2010" then defines { "_DISABLE_DEPRECATE_STATIC_CPPLIB", "_STATIC_CPPLIB"} end configuration "Release" targetdir(outFolderRoot .. "/Native/Release") defines { "NDEBUG", "MT_INSTRUMENTED_BUILD" } flags { "Symbols", optimization_flags } configuration "Debug" targetdir(outFolderRoot .. "/Native/Debug") defines { "_DEBUG", "_CRTDBG_MAP_ALLOC", "MT_INSTRUMENTED_BUILD" } flags { "Symbols" } -- give each configuration/platform a unique output directory for _, config in ipairs(config_list) do for _, plat in ipairs(platform_list) do configuration { config, plat } objdir ( outputFolder .. "/Temp/" ) tgtDir = outFolderRoot .. plat .. "/" .. config targetdir (tgtDir) end end os.mkdir("./" .. outFolderRoot) -- SUBPROJECTS project "BrofilerCore" uuid "830934D9-6F6C-C37D-18F2-FB3304348F00" defines { "_CRT_SECURE_NO_WARNINGS", "BROFILER_LIB=1" } -- if _OPTIONS['platform'] ~= "orbis" then -- kind "SharedLib" -- defines { "BROFILER_EXPORTS" } -- else kind "StaticLib" -- end includedirs { "BrofilerCore" } files { "BrofilerCore/**.cpp", "BrofilerCore/**.h", } vpaths { ["API"] = { "BrofilerCore/Brofiler.h", }, ["Core"] = { "BrofilerCore/Core.h", "BrofilerCore/Core.cpp", "BrofilerCore/ETW.h", "BrofilerCore/Event.h", "BrofilerCore/Event.cpp", "BrofilerCore/EventDescription.h", "BrofilerCore/EventDescription.cpp", "BrofilerCore/EventDescriptionBoard.h", "BrofilerCore/EventDescriptionBoard.cpp", "BrofilerCore/Sampler.h", "BrofilerCore/Sampler.cpp", "BrofilerCore/SymEngine.h", "BrofilerCore/SymEngine.cpp", }, ["Network"] = { "BrofilerCore/Message.h", "BrofilerCore/Message.cpp", "BrofilerCore/ProfilerServer.h", "BrofilerCore/ProfilerServer.cpp", "BrofilerCore/Socket.h", "BrofilerCore/Serialization.h", "BrofilerCore/Serialization.cpp", }, ["System"] = { "BrofilerCore/Common.h", "BrofilerCore/Concurrency.h", "BrofilerCore/CityHash.h", "BrofilerCore/CityHash.cpp", "BrofilerCore/HPTimer.h", "BrofilerCore/HPTimer.cpp", "BrofilerCore/Memory.h", "BrofilerCore/Memory.cpp", "BrofilerCore/MemoryPool.h", "BrofilerCore/StringHash.h", "BrofilerCore/Platform.h", "BrofilerCore/Timer.h", "BrofilerCore/ThreadID.h", "BrofilerCore/Types.h", }, } group "Samples" project "TaskScheduler" excludes { "ThirdParty/TaskScheduler/Scheduler/Source/MTDefaultAppInterop.cpp", } kind "StaticLib" flags {"NoPCH"} defines {"USE_BROFILER=1"} files { "ThirdParty/TaskScheduler/Scheduler/**.*", } includedirs { "ThirdParty/TaskScheduler/Scheduler/Include", "BrofilerCore" } excludes { "Src/Platform/Posix/**.*" } links { "BrofilerCore", } if isUWP then -- Genie can't generate proper UWP application -- It's a dummy project to match existing project file project "DurangoUWP" location( "Samples/DurangoUWP" ) kind "WindowedApp" uuid "5CA6AF66-C2CB-412E-B335-B34357F2FBB6" files { "Samples/DurangoUWP/**.*", } else project "ConsoleApp" flags {"NoPCH"} kind "ConsoleApp" uuid "C50A1240-316C-EF4D-BAD9-3500263A260D" files { "Samples/ConsoleApp/**.*", "Samples/Common/TestEngine/**.*", "ThirdParty/TaskScheduler/Scheduler/Source/MTDefaultAppInterop.cpp", } includedirs { "BrofilerCore", "Samples/Common/TestEngine", "ThirdParty/TaskScheduler/Scheduler/Include" } links { "BrofilerCore", "TaskScheduler" } vpaths { ["*"] = "Samples/ConsoleApp" } end if _OPTIONS["DX12"] then project "WindowsD3D12" flags {"NoPCH", "WinMain"} kind "WindowedApp" uuid "D055326C-F1F3-4695-B7E2-A683077BE4DF" buildoptions { "/wd4324", -- structure was padded due to alignment specifier "/wd4238" -- nonstandard extension used: class rvalue used as lvalue } links { "d3d12", "dxgi", "d3dcompiler" } files { "Samples/WindowsD3D12/**.*", } includedirs { "BrofilerCore", } links { "BrofilerCore", } vpaths { ["*"] = "Samples/WindowsD3D12" } end
newoption { trigger = "UWP", description = "Generates Universal Windows Platform application type", } newoption { trigger = "DX12", description = "Generates a sample for DirectX12", } if not _ACTION then _ACTION="vs2017" end outFolderRoot = "Bin/" .. _ACTION .. "/"; isVisualStudio = false isUWP = false isDX12 = false isVulkan = false if _ACTION == "vs2010" or _ACTION == "vs2012" or _ACTION == "vs2015" or _ACTION == "vs2017" then isVisualStudio = true end if _OPTIONS["UWP"] then isUWP = true end if _OPTIONS["DX12"] then isDX12 = true end if _OPTIONS["Vulkan"] then isVulkan = true end if isUWP then premake.vstudio.toolset = "v140" premake.vstudio.storeapp = "10.0" end outputFolder = "Build/" .. _ACTION if isUWP then outputFolder = outputFolder .. "_UWP" end solution "Brofiler" language "C++" if _ACTION == "vs2017" then windowstargetplatformversion "10.0.17134.0" end startproject "ConsoleApp" location ( outputFolder ) flags { "NoManifest", "ExtraWarnings", "Unicode" } optimization_flags = { "OptimizeSpeed" } if isVisualStudio then debugdir (outFolderRoot) buildoptions { "/wd4127", -- Conditional expression is constant "/wd4091" -- 'typedef ': ignored on left of '' when no variable is declared } end if isUWP then defines { "BRO_UWP=1" } end defines { "USE_BROFILER=1"} defines { "BRO_FIBERS=1"} local config_list = { "Release", "Debug", } local platform_list = { "x32", "x64", "Native", } configurations(config_list) platforms(platform_list) -- CONFIGURATIONS if _ACTION == "vs2010" then defines { "_DISABLE_DEPRECATE_STATIC_CPPLIB", "_STATIC_CPPLIB"} end configuration "Release" targetdir(outFolderRoot .. "/Native/Release") defines { "NDEBUG", "MT_INSTRUMENTED_BUILD" } flags { "Symbols", optimization_flags } configuration "Debug" targetdir(outFolderRoot .. "/Native/Debug") defines { "_DEBUG", "_CRTDBG_MAP_ALLOC", "MT_INSTRUMENTED_BUILD" } flags { "Symbols" } -- give each configuration/platform a unique output directory for _, config in ipairs(config_list) do for _, plat in ipairs(platform_list) do configuration { config, plat } objdir ( outputFolder .. "/Temp/" ) tgtDir = outFolderRoot .. plat .. "/" .. config targetdir (tgtDir) end end os.mkdir("./" .. outFolderRoot) -- SUBPROJECTS project "BrofilerCore" uuid "830934D9-6F6C-C37D-18F2-FB3304348F00" defines { "_CRT_SECURE_NO_WARNINGS", "BROFILER_LIB=1" } -- if _OPTIONS['platform'] ~= "orbis" then -- kind "SharedLib" -- defines { "BROFILER_EXPORTS" } -- else kind "StaticLib" -- end includedirs { "BrofilerCore" } if isDX12 then -- includedirs -- { -- "$(DXSDK_DIR)Include", -- } -- links { -- "d3d12", -- "dxgi", -- } else defines { "BRO_ENABLE_GPU_D3D12=0" } end if isVulkan then includedirs { "$(VULKAN_SDK)Include", } else defines { "BRO_ENABLE_GPU_VULKAN=0" } end files { "BrofilerCore/**.cpp", "BrofilerCore/**.h", } vpaths { ["API"] = { "BrofilerCore/Brofiler.h", }, ["Core"] = { "BrofilerCore/Core.h", "BrofilerCore/Core.cpp", "BrofilerCore/ETW.h", "BrofilerCore/Event.h", "BrofilerCore/Event.cpp", "BrofilerCore/EventDescription.h", "BrofilerCore/EventDescription.cpp", "BrofilerCore/EventDescriptionBoard.h", "BrofilerCore/EventDescriptionBoard.cpp", "BrofilerCore/Sampler.h", "BrofilerCore/Sampler.cpp", "BrofilerCore/SymEngine.h", "BrofilerCore/SymEngine.cpp", }, ["Network"] = { "BrofilerCore/Message.h", "BrofilerCore/Message.cpp", "BrofilerCore/ProfilerServer.h", "BrofilerCore/ProfilerServer.cpp", "BrofilerCore/Socket.h", "BrofilerCore/Serialization.h", "BrofilerCore/Serialization.cpp", }, ["System"] = { "BrofilerCore/Common.h", "BrofilerCore/Concurrency.h", "BrofilerCore/CityHash.h", "BrofilerCore/CityHash.cpp", "BrofilerCore/HPTimer.h", "BrofilerCore/HPTimer.cpp", "BrofilerCore/Memory.h", "BrofilerCore/Memory.cpp", "BrofilerCore/MemoryPool.h", "BrofilerCore/StringHash.h", "BrofilerCore/Platform.h", "BrofilerCore/Timer.h", "BrofilerCore/ThreadID.h", "BrofilerCore/Types.h", }, } group "Samples" project "TaskScheduler" excludes { "ThirdParty/TaskScheduler/Scheduler/Source/MTDefaultAppInterop.cpp", } kind "StaticLib" flags {"NoPCH"} defines {"USE_BROFILER=1"} files { "ThirdParty/TaskScheduler/Scheduler/**.*", } includedirs { "ThirdParty/TaskScheduler/Scheduler/Include", "BrofilerCore" } excludes { "Src/Platform/Posix/**.*" } links { "BrofilerCore", } if isUWP then -- Genie can't generate proper UWP application -- It's a dummy project to match existing project file project "DurangoUWP" location( "Samples/DurangoUWP" ) kind "WindowedApp" uuid "5CA6AF66-C2CB-412E-B335-B34357F2FBB6" files { "Samples/DurangoUWP/**.*", } else project "ConsoleApp" flags {"NoPCH"} kind "ConsoleApp" uuid "C50A1240-316C-EF4D-BAD9-3500263A260D" files { "Samples/ConsoleApp/**.*", "Samples/Common/TestEngine/**.*", "ThirdParty/TaskScheduler/Scheduler/Source/MTDefaultAppInterop.cpp", } includedirs { "BrofilerCore", "Samples/Common/TestEngine", "ThirdParty/TaskScheduler/Scheduler/Include" } links { "BrofilerCore", "TaskScheduler" } vpaths { ["*"] = "Samples/ConsoleApp" } end if isDX12 then project "WindowsD3D12" flags {"NoPCH", "WinMain"} kind "WindowedApp" uuid "D055326C-F1F3-4695-B7E2-A683077BE4DF" buildoptions { "/wd4324", -- structure was padded due to alignment specifier "/wd4238" -- nonstandard extension used: class rvalue used as lvalue } links { "d3d12", "dxgi", "d3dcompiler" } files { "Samples/WindowsD3D12/**.*", } includedirs { "BrofilerCore", } links { "BrofilerCore", } vpaths { ["*"] = "Samples/WindowsD3D12" } end
Fixing appveyor compilation.
Fixing appveyor compilation.
Lua
mit
bombomby/brofiler,bombomby/brofiler,bombomby/brofiler
03c28d829fb4a880cd7530548f23286169408c2c
Game/data/scripts/Config.lua
Game/data/scripts/Config.lua
Config = { camera = { distance = 5.0, -- initial distance of camera distanceDelta = 3, -- delta of distance change distanceMin = 2.0, distanceMax = 3000.0, hightFactor = 0.5, -- 0..1 factor for hight of camera initLook = Vec2(0.0, 20.0), rotationSpeedFactor = 50, rotationSpeedFactorGamePad = 200, --zoomfactorgamepad = 1.65 zoomfactorgamepad = 5.65 }, player = { maxLinearVelocity = 300.0, maxAngularVelocity = 100.0, spawnPosition = Vec3(0.0, 0.0, 3.0), torqueMulScalar = 2000, lastTransformator = Vec3(0.0,0.0,3.0) }, materials = { sphere = { wood = { mass = 200.0, friction = 20.0, angularDamping = 4.0, linearDamping = 0.0, restitution = 0.0, radius = 0.5 }, stone = { mass = 1370.0, friction = 30.0, angularDamping = 0.3, linearDamping = 0.0, restitution = 0.0, radius = 0.5 }, paper = { mass = 30.09, friction = 30.0, angularDamping = 10.0, linearDamping = 3.0, restitution = 0.0, radius = 0.5 } }, track = { wood = { friction = 20.0, restitution = 0.75, }, ice = { friction = 0.01, restitution = 0.0 } } }, keys = { keyboard = { forward = Key.W, backward = Key.S, left = Key.A, right = Key.D, pause = Key.P, restart = Key.F3, zoomout = Key.Oem_Minus, zoomin = Key.Oem_Plus, lastTransformator = Key.F4 }, gamepad = { restart = Button.Back, pause = Button.Start, lastTransformator = Button.LeftShoulder } }, world = { gravity = Vec3(0,0,-9.81), worldSize = 4000 }, fans = { forces = { woodonly = Vec3(0.0,0.0,3123.0), stoneonly = Vec3(4123.0,0.0,0.0), paperonly = Vec3(0.0,0.0,513.0) }, fan1 = { position = Vec3(-170,-70,-30), size = Vec3(20,5,5), name = "fan1", active = true }, fan2 = { position = Vec3(-185,-150,-25), size = Vec3(5,5,7), name = "fan2", --active = false active = true }, fan3 = { position = Vec3(51,-150,-13), size = Vec3(27.5,5,20), name = "fan3", --active = false active = true }, }, transformators = { transformatorsize = Vec3(0.7,0.7,0.7), transformator1 = { name = "transformator1", position = Vec3(-69.9,-77.2,1), transformTo = "playerInstanceStone" }, transformator2 = { name = "transformator2", position = Vec3(-177.3,-135,-30), transformTo = "playerInstancePaper" }, transformator3 = { name = "transformator3", position = Vec3(22.3,-163,0.8), transformTo = "playerInstance" }, transformator4 = { name = "transformator4", position = Vec3(12,-118,0.8), transformTo = "playerInstanceStone" }, }, triggers = { triggersize = Vec3(0.7,0.7,0.7), trigger1 = { position = Vec3(0,0,0), name = "trigger1" }, trigger2 = { position = Vec3(0,0,0), name = "trigger2" }, endtrigger = { position = Vec3(100,0,-20), name = "endtrigger" } } }
Config = { camera = { distance = 5.0, -- initial distance of camera distanceDelta = 3, -- delta of distance change distanceMin = 2.0, distanceMax = 3000.0, hightFactor = 0.5, -- 0..1 factor for hight of camera initLook = Vec2(0.0, 20.0), rotationSpeedFactor = 50, rotationSpeedFactorGamePad = 200, --zoomfactorgamepad = 1.65 zoomfactorgamepad = 5.65 }, player = { maxLinearVelocity = 300.0, maxAngularVelocity = 100.0, spawnPosition = Vec3(0.0, 0.0, 3.0), torqueMulScalar = 2000, linearVelocityScalar = 100, lastTransformator = Vec3(0.0,0.0,3.0) }, materials = { sphere = { wood = { mass = 200.0, friction = 20.0, angularDamping = 4.0, linearDamping = 0.0, restitution = 0.0, radius = 0.5 }, stone = { mass = 1370.0, friction = 30.0, angularDamping = 0.3, linearDamping = 0.0, restitution = 0.0, radius = 0.5 }, paper = { mass = 30.09, friction = 30.0, angularDamping = 10.0, linearDamping = 3.0, restitution = 0.0, radius = 0.5 } }, track = { wood = { friction = 20.0, restitution = 0.75, }, ice = { friction = 0.01, restitution = 0.0 } } }, keys = { keyboard = { forward = Key.W, backward = Key.S, left = Key.A, right = Key.D, pause = Key.P, restart = Key.F3, zoomout = Key.Oem_Minus, zoomin = Key.Oem_Plus, lastTransformator = Key.F4 }, gamepad = { restart = Button.Back, pause = Button.Start, lastTransformator = Button.LeftShoulder } }, world = { gravity = Vec3(0,0,-9.81), worldSize = 4000 }, fans = { forces = { woodonly = Vec3(0.0,0.0,3123.0), stoneonly = Vec3(4123.0,0.0,0.0), paperonly = Vec3(0.0,0.0,513.0) }, fan1 = { position = Vec3(-170,-70,-30), size = Vec3(20,5,5), name = "fan1", active = true }, fan2 = { position = Vec3(-185,-150,-25), size = Vec3(5,5,7), name = "fan2", --active = false active = true }, fan3 = { position = Vec3(51,-150,-13), size = Vec3(27.5,5,20), name = "fan3", --active = false active = true }, }, transformators = { transformatorsize = Vec3(0.7,0.7,0.7), transformator1 = { name = "transformator1", position = Vec3(-69.9,-77.2,1), transformTo = "playerInstanceStone" }, transformator2 = { name = "transformator2", position = Vec3(-177.3,-135,-30), transformTo = "playerInstancePaper" }, transformator3 = { name = "transformator3", position = Vec3(22.3,-163,0.8), transformTo = "playerInstance" }, transformator4 = { name = "transformator4", position = Vec3(12,-118,0.8), transformTo = "playerInstanceStone" }, }, triggers = { triggersize = Vec3(0.7,0.7,0.7), trigger1 = { position = Vec3(0,0,0), name = "trigger1" }, trigger2 = { position = Vec3(0,0,0), name = "trigger2" }, endtrigger = { position = Vec3(100,0,-20), name = "endtrigger" } } }
fixed bug.
fixed bug.
Lua
mit
pampersrocker/risky-epsilon,pampersrocker/risky-epsilon,pampersrocker/risky-epsilon