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
082962a8d80b7cb362388209c926538b50526842
core/libtexpdf-output.lua
core/libtexpdf-output.lua
local pdf = require("justenoughlibtexpdf") if (not SILE.outputters) then SILE.outputters = {} end local cursorX = 0 local cursorY = 0 local font = 0 local started = false local function ensureInit () if not started then pdf.init(SILE.outputFilename, SILE.documentState.paperSize[1],SILE.documentState.paperSize[2]) pdf.beginpage() started = true end end SILE.outputters.libtexpdf = { init = function() -- We don't do anything yet because this commits us to a page size. end, _init = ensureInit, newPage = function() ensureInit() pdf.endpage() pdf.beginpage() end, finish = function() if not started then return end pdf.endpage() pdf.finish() end, setColor = function(self, color) ensureInit() pdf.setcolor(color.r, color.g, color.b) end, pushColor = function (self, color) ensureInit() pdf.colorpush(color.r, color.g, color.b) end, popColor = function (self) ensureInit() pdf.colorpop() end, cursor = function(self) return cursorX, cursorY end, outputHbox = function (value,w) ensureInit() if not value.glyphString then return end -- Nodes which require kerning or have offsets to the glyph -- position should be output a glyph at a time. We pass the -- glyph advance from the htmx table, so that libtexpdf knows -- how wide each glyph is. It uses this to then compute the -- relative position between the pen after the glyph has been -- painted (cursorX + glyphAdvance) and the next painting -- position (cursorX + width - remember that the box's "width" -- is actually the shaped x_advance). if value.complex then for i=1,#(value.items) do local glyph = value.items[i].gid local buf = string.char(math.floor(glyph % 2^32 / 2^8)) .. string.char(glyph % 0x100) pdf.setstring(cursorX + (value.items[i].x_offset or 0), cursorY + (value.items[i].y_offset or 0), buf, string.len(buf), font, value.items[i].glyphAdvance) cursorX = cursorX + value.items[i].width end return end local buf = {} for i=1,#(value.glyphString) do glyph = value.glyphString[i] buf[#buf+1] = string.char(math.floor(glyph % 2^32 / 2^8)) buf[#buf+1] = string.char(glyph % 0x100) end buf = table.concat(buf, "") pdf.setstring(cursorX, cursorY, buf, string.len(buf), font, w) end, setFont = function (options) ensureInit() if SILE.font._key(options) == lastkey then return end lastkey = SILE.font._key(options) font = SILE.font.cache(options, SILE.shaper.getFace) if options.direction == "TTB" then font.layout_dir = 1 end if SILE.typesetter.frame and SILE.typesetter.frame:writingDirection() == "TTB" then pdf.setdirmode(1) else pdf.setdirmode(0) end f = pdf.loadfont(font) if f< 0 then SU.error("Font loading error for "..options) end font = f end, drawImage = function (src, x,y,w,h) ensureInit() pdf.drawimage(src, x, y, w, h) end, imageSize = function (src) ensureInit() -- in case it's a PDF file local llx, lly, urx, ury = pdf.imagebbox(src) return (urx-llx), (ury-lly) end, moveTo = function (x,y) cursorX = x cursorY = SILE.documentState.paperSize[2] - y end, rule = function (x,y,w,d) ensureInit() pdf.setrule(x,SILE.documentState.paperSize[2] -y-d,w,d) end, debugFrame = function (self,f) ensureInit() pdf.colorpush(0.8,0,0) self.rule(f:left(), f:top(), f:width(), 0.5) self.rule(f:left(), f:top(), 0.5, f:height()) self.rule(f:right(), f:top(), 0.5, f:height()) self.rule(f:left(), f:bottom(), f:width(), 0.5) --self.rule(f:left() + f:width()/2 - 5, (f:top() + f:bottom())/2+5, 10, 10) local oldfont = font SILE.outputter.setFont(SILE.font.loadDefaults({})) local stuff = SILE.shaper:createNnodes(f.id, SILE.font.loadDefaults({})) stuff = stuff[1].nodes[1].value.glyphString -- Horrible hack local buf = {} for i=1,#stuff do glyph = stuff[i] buf[#buf+1] = string.char(math.floor(glyph % 2^32 / 2^8)) buf[#buf+1] = string.char(glyph % 0x100) end buf = table.concat(buf, "") pdf.setstring(f:left(), SILE.documentState.paperSize[2] -f:top(), buf, string.len(buf), font, 0) pdf.colorpop() font = oldfont end, debugHbox = function(typesetter, hbox, scaledWidth) end } SILE.outputter = SILE.outputters.libtexpdf
local pdf = require("justenoughlibtexpdf") if (not SILE.outputters) then SILE.outputters = {} end local cursorX = 0 local cursorY = 0 local font = 0 local started = false local function ensureInit () if not started then pdf.init(SILE.outputFilename, SILE.documentState.paperSize[1],SILE.documentState.paperSize[2]) pdf.beginpage() started = true end end SILE.outputters.libtexpdf = { init = function() -- We don't do anything yet because this commits us to a page size. end, _init = ensureInit, newPage = function() ensureInit() pdf.endpage() pdf.beginpage() end, finish = function() if not started then return end pdf.endpage() pdf.finish() end, setColor = function(self, color) ensureInit() pdf.setcolor(color.r, color.g, color.b) end, pushColor = function (self, color) ensureInit() pdf.colorpush(color.r, color.g, color.b) end, popColor = function (self) ensureInit() pdf.colorpop() end, cursor = function(self) return cursorX, cursorY end, outputHbox = function (value,w) ensureInit() if not value.glyphString then return end -- Nodes which require kerning or have offsets to the glyph -- position should be output a glyph at a time. We pass the -- glyph advance from the htmx table, so that libtexpdf knows -- how wide each glyph is. It uses this to then compute the -- relative position between the pen after the glyph has been -- painted (cursorX + glyphAdvance) and the next painting -- position (cursorX + width - remember that the box's "width" -- is actually the shaped x_advance). if value.complex then for i=1,#(value.items) do local glyph = value.items[i].gid local buf = string.char(math.floor(glyph % 2^32 / 2^8)) .. string.char(glyph % 0x100) pdf.setstring(cursorX + (value.items[i].x_offset or 0), cursorY + (value.items[i].y_offset or 0), buf, string.len(buf), font, value.items[i].glyphAdvance) cursorX = cursorX + value.items[i].width end return end local buf = {} for i=1,#(value.glyphString) do glyph = value.glyphString[i] buf[#buf+1] = string.char(math.floor(glyph % 2^32 / 2^8)) buf[#buf+1] = string.char(glyph % 0x100) end buf = table.concat(buf, "") pdf.setstring(cursorX, cursorY, buf, string.len(buf), font, w) end, setFont = function (options) ensureInit() if SILE.font._key(options) == lastkey then return end lastkey = SILE.font._key(options) font = SILE.font.cache(options, SILE.shaper.getFace) if options.direction == "TTB" then font.layout_dir = 1 end if SILE.typesetter.frame and SILE.typesetter.frame:writingDirection() == "TTB" then pdf.setdirmode(1) else pdf.setdirmode(0) end f = pdf.loadfont(font) if f< 0 then SU.error("Font loading error for "..options) end font = f end, drawImage = function (src, x,y,w,h) ensureInit() pdf.drawimage(src, x, y, w, h) end, imageSize = function (src) ensureInit() -- in case it's a PDF file local llx, lly, urx, ury = pdf.imagebbox(src) return (urx-llx), (ury-lly) end, moveTo = function (x,y) cursorX = x cursorY = SILE.documentState.paperSize[2] - y end, rule = function (x,y,w,d) ensureInit() pdf.setrule(x,SILE.documentState.paperSize[2] -y-d,w,d) end, debugFrame = function (self,f) ensureInit() pdf.colorpush(0.8,0,0) self.rule(f:left(), f:top(), f:width(), 0.5) self.rule(f:left(), f:top(), 0.5, f:height()) self.rule(f:right(), f:top(), 0.5, f:height()) self.rule(f:left(), f:bottom(), f:width(), 0.5) --self.rule(f:left() + f:width()/2 - 5, (f:top() + f:bottom())/2+5, 10, 10) local stuff = SILE.shaper:createNnodes(f.id, SILE.font.loadDefaults({})) stuff = stuff[1].nodes[1].value.glyphString -- Horrible hack local buf = {} for i=1,#stuff do glyph = stuff[i] buf[#buf+1] = string.char(math.floor(glyph % 2^32 / 2^8)) buf[#buf+1] = string.char(glyph % 0x100) end buf = table.concat(buf, "") if font == 0 then SILE.outputter.setFont(SILE.font.loadDefaults({})) end pdf.setstring(f:left(), SILE.documentState.paperSize[2] -f:top(), buf, string.len(buf), font, 0) pdf.colorpop() end, debugHbox = function(typesetter, hbox, scaledWidth) end } SILE.outputter = SILE.outputters.libtexpdf
Revert "Possible fix for #384". It didn't fix it, and it messes other stuff up.
Revert "Possible fix for #384". It didn't fix it, and it messes other stuff up. This reverts commit 4295e9ca1a6738bdb4bbaa52010724d585140c6a.
Lua
mit
neofob/sile,simoncozens/sile,simoncozens/sile,simoncozens/sile,neofob/sile,alerque/sile,alerque/sile,neofob/sile,simoncozens/sile,alerque/sile,alerque/sile,neofob/sile
ac164fdbd3f461844107840be09c26cb31f57460
src/binder/src/Shared/BinderGroupProvider.lua
src/binder/src/Shared/BinderGroupProvider.lua
--- Provides a basis for binderGroups that can be retrieved anywhere -- @classmod BinderGroupProvider local require = require(script.Parent.loader).load(script) local Promise = require("Promise") local BinderGroupProvider = {} BinderGroupProvider.ClassName = "BinderGroupProvider" BinderGroupProvider.__index = BinderGroupProvider function BinderGroupProvider.new(initMethod) local self = setmetatable({}, BinderGroupProvider) self._initMethod = initMethod or error("No initMethod") self._groupsAddedPromise = Promise.new() self._init = false self._binderGroups = {} return self end function BinderGroupProvider:PromiseGroupsAdded() return self._groupsAddedPromise end function BinderGroupProvider:Init(...) self._initMethod(self, ...) self._init = true self._groupsAddedPromise:Resolve() end function BinderGroupProvider:__index(index) if BinderGroupProvider[index] then return BinderGroupProvider[index] end error(("%q Not a valid index"):format(tostring(index))) end function BinderGroupProvider:Get(tagName) assert(type(tagName) == "string", "tagName must be a string") return rawget(self, tagName) end function BinderGroupProvider:Add(groupName, binderGroup) assert(type(groupName) == "string", "Bad groupName") assert(type(binderGroup) == "table", "Bad binderGroup") assert(not self._init, "Already initialized") assert(not self:Get(groupName), "Duplicate groupName") table.insert(self._binderGroups, binderGroup) self[groupName] = binderGroup end return BinderGroupProvider
--- Provides a basis for binderGroups that can be retrieved anywhere -- @classmod BinderGroupProvider local require = require(script.Parent.loader).load(script) local Promise = require("Promise") local BinderGroupProvider = {} BinderGroupProvider.ClassName = "BinderGroupProvider" BinderGroupProvider.__index = BinderGroupProvider function BinderGroupProvider.new(initMethod) local self = setmetatable({}, BinderGroupProvider) self._initMethod = initMethod or error("No initMethod") self._groupsAddedPromise = Promise.new() self._init = false self._binderGroups = {} return self end function BinderGroupProvider:PromiseGroupsAdded() return self._groupsAddedPromise end function BinderGroupProvider:Init(...) assert(not self._init, "Already initialized") self._initMethod(self, ...) self._init = true self._groupsAddedPromise:Resolve() end function BinderGroupProvider:Start() -- Do nothing end function BinderGroupProvider:__index(index) if BinderGroupProvider[index] then return BinderGroupProvider[index] end error(("%q Not a valid index"):format(tostring(index))) end function BinderGroupProvider:Get(tagName) assert(type(tagName) == "string", "tagName must be a string") return rawget(self, tagName) end function BinderGroupProvider:Add(groupName, binderGroup) assert(type(groupName) == "string", "Bad groupName") assert(type(binderGroup) == "table", "Bad binderGroup") assert(not self._init, "Already initialized") assert(not self:Get(groupName), "Duplicate groupName") table.insert(self._binderGroups, binderGroup) self[groupName] = binderGroup end return BinderGroupProvider
fix: Allow BinderGroup to be initialized by the service bag
fix: Allow BinderGroup to be initialized by the service bag
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
a7a90083bfeb4239a8a8ea2d9a803e4d894fc99c
mqtt-client.lua
mqtt-client.lua
local module = {} local client = nil local options = nil function module.connect(options, connected) client:connect(options.host, options.port, options.secure, connected, 1, function(c, reason) print("failed reason: "..reason) end) end function module.setup(opts, connected) options = opts client = mqtt.Client(options.id, 120, options.user, options.password) client:on("connect", connected) module.connect(options, connected) return module end function module.client() return client end function module.message(topic, message, retain) client:publish(options.endpoint .. topic, message, 0, retain) end function module.read_topic(topic, callback) topic = options.endpoint .. topic print("subscribing to " .. topic) client:on('message', function(c, t, message) if t == topic then client:unsubscribe(topic) callback(t, message) end end) client:subscribe(topic, 0) end return module
local module = {} local client = nil local options = nil function module.connect(options, connected) client:connect(options.host, options.port, options.secure, connected, 1, function(c, reason) print("failed reason: "..reason) end) end function module.setup(opts, connected) module.options = opts client = mqtt.Client(module.options.id, 120, module.options.user, module.options.password) client:on("connect", connected) module.connect(module.options, connected) return module end function module.client() return client end function module.message(topic, message, retain) client:publish(module.options.endpoint .. topic, message, 0, retain) end function module.read_topic(topic, callback) local topic = module.options.endpoint .. topic print("subscribing to " .. topic) client:on('message', function(c, t, message) if t == topic then client:unsubscribe(topic, function() print("unsubscribed " .. topic) end) callback(t, message) end end) client:subscribe(topic, 0) end return module
No global options in mqtt-client, last fixes
No global options in mqtt-client, last fixes
Lua
mit
DevLoL/super-mario-count
3a47d1000d1cb9517cc23d6769b937a2055ba280
nyagos.d/su.lua
nyagos.d/su.lua
nyagos.alias.sudo = function(args) if #args <= 0 then nyagos.shellexecute("runas",nyagos.exe) return end local prog = args[1] table.remove(args,1) local cwd = nyagos.netdrivetounc(nyagos.getwd()) assert(nyagos.shellexecute("runas",prog,table.concat(args," "),cwd)) end share._clone = function(action) local cwd = nyagos.netdrivetounc(nyagos.getwd()) print(cwd) local status,err = nyagos.shellexecute(action,nyagos.exe,"",cwd) if not status and string.match(err,"^Error%(5%)") then status,err = nyagos.shellexecute(action,nyagos.getenv("COMSPEC"),'/c "'..nyagos.exe,"",cwd) end return status,err end nyagos.alias.su = function() assert(share._clone("runas")) end nyagos.alias.clone = function() assert(share._clone("open")) end
nyagos.alias.sudo = function(args) if #args <= 0 then nyagos.shellexecute("runas",nyagos.exe) return end local prog = args[1] table.remove(args,1) local cwd = nyagos.netdrivetounc(nyagos.getwd()) assert(nyagos.shellexecute("runas",prog,table.concat(args," "),cwd)) end share._clone = function(action) local cwd = nyagos.netdrivetounc(nyagos.getwd()) print(cwd) local status,err = nyagos.shellexecute(action,nyagos.exe,"",cwd) if status then return status,err end if string.match(err,"^Error%(5%)") or string.match(err,"winapi error") then status,err = nyagos.shellexecute(action,nyagos.getenv("COMSPEC"),'/c "'..nyagos.exe,"",cwd) end return status,err end nyagos.alias.su = function() assert(share._clone("runas")) end nyagos.alias.clone = function() assert(share._clone("open")) end
Fix: su & clone's retrying by cmd.exe did not work on winapi error
Fix: su & clone's retrying by cmd.exe did not work on winapi error
Lua
bsd-3-clause
tsuyoshicho/nyagos,tyochiai/nyagos,zetamatta/nyagos,nocd5/nyagos
ddec2816e8290b8c636007158b7ab766384b02dd
applications/luci-statistics/luasrc/controller/luci_statistics/luci_statistics.lua
applications/luci-statistics/luasrc/controller/luci_statistics/luci_statistics.lua
--[[ Luci statistics - statistics controller module (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <[email protected]> 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.luci_statistics.luci_statistics", package.seeall) function index() require("luci.fs") require("luci.util") require("luci.i18n") require("luci.statistics.datatree") -- load language files luci.i18n.loadc("rrdtool") luci.i18n.loadc("statistics") -- get rrd data tree local tree = luci.statistics.datatree.Instance() -- override entry(): check for existance <plugin>.so where <plugin> is derived from the called path function _entry( path, ... ) local file = path[5] or path[4] if luci.fs.isfile( "/usr/lib/collectd/" .. file .. ".so" ) then entry( path, ... ) end end -- override i18n(): try to translate stat_<str> or fall back to <str> function _i18n( str ) return luci.i18n.translate( "stat_" .. str, str ) end -- our collectd menu local collectd_menu = { output = { "rrdtool", "network", "unixsock", "csv" }, system = { "exec", "email", "cpu", "df", "disk", "irq", "processes", "load" }, network = { "interface", "netlink", "iptables", "tcpconns", "ping", "dns", "wireless" } } -- create toplevel menu nodes entry({"admin", "statistics"}, call("statistics_index"), _i18n("statistics"), 80).i18n = "statistics" entry({"admin", "statistics", "collectd"}, cbi("luci_statistics/collectd"), _i18n("collectd"), 10) -- populate collectd plugin menu local index = 1 for section, plugins in luci.util.kspairs( collectd_menu ) do entry( { "admin", "statistics", "collectd", section }, call( "statistics_" .. section .. "plugins" ), _i18n( section .. "plugins" ), index * 10 ) for j, plugin in luci.util.vspairs( plugins ) do _entry( { "admin", "statistics", "collectd", section, plugin }, cbi("luci_statistics/" .. plugin ), _i18n( plugin ), j * 10 ) end index = index + 1 end -- output views local page = entry( { "admin", "statistics", "graph" }, call("statistics_index"), _i18n("graphs"), 80) page.i18n = "statistics" page.setuser = "nobody" page.setgroup = "nogroup" local vars = luci.http.formvalue(nil, true) local span = vars.timespan or nil for i, plugin in luci.util.vspairs( tree:plugins() ) do -- get plugin instances local instances = tree:plugin_instances( plugin ) -- plugin menu entry entry( { "admin", "statistics", "graph", plugin }, call("statistics_render"), _i18n( plugin ), i ).query = { timespan = span } -- if more then one instance is found then generate submenu if #instances > 1 then for j, inst in luci.util.vspairs(instances) do -- instance menu entry entry( { "admin", "statistics", "graph", plugin, inst }, call("statistics_render"), inst, j ).query = { timespan = span } end end end end function statistics_index() luci.template.render("admin_statistics/index") end function statistics_outputplugins() local plugins = { } for i, p in ipairs({ "rrdtool", "network", "unixsock", "csv" }) do plugins[p] = luci.i18n.translate( "stat_" .. p, p ) end luci.template.render("admin_statistics/outputplugins", {plugins=plugins}) end function statistics_systemplugins() local plugins = { } for i, p in ipairs({ "exec", "email", "df", "disk", "irq", "processes", "cpu" }) do plugins[p] = luci.i18n.translate( "stat_" .. p, p ) end luci.template.render("admin_statistics/systemplugins", {plugins=plugins}) end function statistics_networkplugins() local plugins = { } for i, p in ipairs({ "interface", "netlink", "iptables", "tcpconns", "ping", "dns", "wireless" }) do plugins[p] = luci.i18n.translate( "stat_" .. p, p ) end luci.template.render("admin_statistics/networkplugins", {plugins=plugins}) end function statistics_render() require("luci.statistics.rrdtool") require("luci.template") require("luci.model.uci") local vars = luci.http.formvalue() local req = luci.dispatcher.context.request local path = luci.dispatcher.context.dispatched.path local uci = luci.model.uci.cursor() local spans = luci.util.split( uci:get( "luci_statistics", "collectd_rrdtool", "RRATimespans" ), "%s+", nil, true ) local span = vars.timespan or uci:get( "luci_statistics", "rrdtool", "default_timespan" ) or spans[1] local graph = luci.statistics.rrdtool.Graph( luci.util.parse_units( span ) ) local plugin, instances local images = { } -- find requested plugin and instance for i, p in ipairs( luci.dispatcher.context.dispatched.path ) do if luci.dispatcher.context.dispatched.path[i] == "graph" then plugin = luci.dispatcher.context.dispatched.path[i+1] instances = { luci.dispatcher.context.dispatched.path[i+2] } end end -- no instance requested, find all instances if #instances == 0 then instances = { graph.tree:plugin_instances( plugin )[1] } -- index instance requested elseif instances[1] == "-" then instances[1] = "" end -- render graphs for i, inst in ipairs( instances ) do for i, img in ipairs( graph:render( plugin, inst ) ) do table.insert( images, graph:strippngpath( img ) ) end end luci.template.render( "public_statistics/graph", { images = images, plugin = plugin, timespans = spans, current_timespan = span } ) end
--[[ Luci statistics - statistics controller module (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <[email protected]> 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.luci_statistics.luci_statistics", package.seeall) function index() require("luci.fs") require("luci.util") require("luci.i18n") require("luci.statistics.datatree") -- load language files luci.i18n.loadc("rrdtool") luci.i18n.loadc("statistics") -- get rrd data tree local tree = luci.statistics.datatree.Instance() -- override entry(): check for existance <plugin>.so where <plugin> is derived from the called path function _entry( path, ... ) local file = path[5] or path[4] if luci.fs.isfile( "/usr/lib/collectd/" .. file .. ".so" ) then entry( path, ... ) end end -- override i18n(): try to translate stat_<str> or fall back to <str> function _i18n( str ) return luci.i18n.translate( "stat_" .. str, str ) end -- our collectd menu local collectd_menu = { output = { "rrdtool", "network", "unixsock", "csv" }, system = { "exec", "email", "cpu", "df", "disk", "irq", "processes", "load" }, network = { "interface", "netlink", "iptables", "tcpconns", "ping", "dns", "wireless" } } -- create toplevel menu nodes entry({"admin", "statistics"}, call("statistics_index"), _i18n("statistics"), 80).i18n = "statistics" entry({"admin", "statistics", "collectd"}, cbi("luci_statistics/collectd"), _i18n("collectd"), 10) -- populate collectd plugin menu local index = 1 for section, plugins in luci.util.kspairs( collectd_menu ) do entry( { "admin", "statistics", "collectd", section }, call( "statistics_" .. section .. "plugins" ), _i18n( section .. "plugins" ), index * 10 ) for j, plugin in luci.util.vspairs( plugins ) do _entry( { "admin", "statistics", "collectd", section, plugin }, cbi("luci_statistics/" .. plugin ), _i18n( plugin ), j * 10 ) end index = index + 1 end -- output views local page = entry( { "admin", "statistics", "graph" }, call("statistics_index"), _i18n("graphs"), 80) page.i18n = "statistics" page.setuser = "nobody" page.setgroup = "nogroup" local vars = luci.http.formvalue(nil, true) local span = vars.timespan or nil for i, plugin in luci.util.vspairs( tree:plugins() ) do -- get plugin instances local instances = tree:plugin_instances( plugin ) -- plugin menu entry entry( { "admin", "statistics", "graph", plugin }, call("statistics_render"), _i18n( plugin ), i ).query = { timespan = span } -- if more then one instance is found then generate submenu if #instances > 1 then for j, inst in luci.util.vspairs(instances) do -- instance menu entry entry( { "admin", "statistics", "graph", plugin, inst }, call("statistics_render"), inst, j ).query = { timespan = span } end end end end function statistics_index() luci.template.render("admin_statistics/index") end function statistics_outputplugins() local plugins = { } for i, p in ipairs({ "rrdtool", "network", "unixsock", "csv" }) do plugins[p] = luci.i18n.translate( "stat_" .. p, p ) end luci.template.render("admin_statistics/outputplugins", {plugins=plugins}) end function statistics_systemplugins() local plugins = { } for i, p in ipairs({ "exec", "email", "df", "disk", "irq", "processes", "cpu" }) do plugins[p] = luci.i18n.translate( "stat_" .. p, p ) end luci.template.render("admin_statistics/systemplugins", {plugins=plugins}) end function statistics_networkplugins() local plugins = { } for i, p in ipairs({ "interface", "netlink", "iptables", "tcpconns", "ping", "dns", "wireless" }) do plugins[p] = luci.i18n.translate( "stat_" .. p, p ) end luci.template.render("admin_statistics/networkplugins", {plugins=plugins}) end function statistics_render() require("luci.statistics.rrdtool") require("luci.template") require("luci.model.uci") local vars = luci.http.formvalue() local req = luci.dispatcher.context.request local path = luci.dispatcher.context.path local uci = luci.model.uci.cursor() local spans = luci.util.split( uci:get( "luci_statistics", "collectd_rrdtool", "RRATimespans" ), "%s+", nil, true ) local span = vars.timespan or uci:get( "luci_statistics", "rrdtool", "default_timespan" ) or spans[1] local graph = luci.statistics.rrdtool.Graph( luci.util.parse_units( span ) ) local plugin, instances local images = { } -- find requested plugin and instance for i, p in ipairs( luci.dispatcher.context.path ) do if luci.dispatcher.context.path[i] == "graph" then plugin = luci.dispatcher.context.path[i+1] instances = { luci.dispatcher.context.path[i+2] } end end -- no instance requested, find all instances if #instances == 0 then instances = { graph.tree:plugin_instances( plugin )[1] } -- index instance requested elseif instances[1] == "-" then instances[1] = "" end -- render graphs for i, inst in ipairs( instances ) do for i, img in ipairs( graph:render( plugin, inst ) ) do table.insert( images, graph:strippngpath( img ) ) end end luci.template.render( "public_statistics/graph", { images = images, plugin = plugin, timespans = spans, current_timespan = span } ) end
Fixed statistics
Fixed statistics git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@3321 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,ch3n2k/luci,8devices/carambola2-luci,vhpham80/luci,jschmidlapp/luci,Canaan-Creative/luci,eugenesan/openwrt-luci,phi-psi/luci,freifunk-gluon/luci,Canaan-Creative/luci,ch3n2k/luci,saraedum/luci-packages-old,Canaan-Creative/luci,stephank/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,saraedum/luci-packages-old,jschmidlapp/luci,phi-psi/luci,gwlim/luci,freifunk-gluon/luci,jschmidlapp/luci,stephank/luci,8devices/carambola2-luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,vhpham80/luci,saraedum/luci-packages-old,alxhh/piratenluci,ThingMesh/openwrt-luci,stephank/luci,vhpham80/luci,8devices/carambola2-luci,gwlim/luci,freifunk-gluon/luci,8devices/carambola2-luci,ch3n2k/luci,ThingMesh/openwrt-luci,jschmidlapp/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,8devices/carambola2-luci,yeewang/openwrt-luci,saraedum/luci-packages-old,freifunk-gluon/luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,dtaht/cerowrt-luci-3.3,alxhh/piratenluci,saraedum/luci-packages-old,saraedum/luci-packages-old,Canaan-Creative/luci,projectbismark/luci-bismark,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,zwhfly/openwrt-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,alxhh/piratenluci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,ThingMesh/openwrt-luci,Flexibity/luci,zwhfly/openwrt-luci,alxhh/piratenluci,zwhfly/openwrt-luci,jschmidlapp/luci,vhpham80/luci,jschmidlapp/luci,projectbismark/luci-bismark,stephank/luci,Flexibity/luci,ch3n2k/luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,Flexibity/luci,stephank/luci,zwhfly/openwrt-luci,Flexibity/luci,freifunk-gluon/luci,freifunk-gluon/luci,gwlim/luci,projectbismark/luci-bismark,ch3n2k/luci,dtaht/cerowrt-luci-3.3,alxhh/piratenluci,8devices/carambola2-luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,Flexibity/luci,Flexibity/luci,alxhh/piratenluci,alxhh/piratenluci,yeewang/openwrt-luci,projectbismark/luci-bismark,gwlim/luci,jschmidlapp/luci,Canaan-Creative/luci,Canaan-Creative/luci,gwlim/luci,phi-psi/luci,yeewang/openwrt-luci,yeewang/openwrt-luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,projectbismark/luci-bismark,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,vhpham80/luci,freifunk-gluon/luci,stephank/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,gwlim/luci,phi-psi/luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,yeewang/openwrt-luci,phi-psi/luci,eugenesan/openwrt-luci,Canaan-Creative/luci
a4562060af840f00883819753bca2993f55d9bfe
mod_ircd/mod_ircd.lua
mod_ircd/mod_ircd.lua
local irc_listener = { default_port = 6667, default_mode = "*l" }; local sessions = {}; local commands = {}; local nicks = {}; local st = require "util.stanza"; local conference_server = module:get_option("conference_server") or "conference.jabber.org"; local function irc_close_session(session) session.conn:close(); end function irc_listener.onincoming(conn, data) local session = sessions[conn]; if not session then session = { conn = conn, host = module.host, reset_stream = function () end, close = irc_close_session, log = logger.init("irc"..(conn.id or "1")), roster = {} }; sessions[conn] = session; function session.data(data) module:log("debug", "Received: %s", data); local command, args = data:match("^%s*([^ ]+) *(.*)%s*$"); if not command then module:log("warn", "Invalid command: %s", data); return; end command = command:upper(); module:log("debug", "Received command: %s", command); if commands[command] then local ret = commands[command](session, args); if ret then session.send(ret.."\r\n"); end end end function session.send(data) module:log("debug", "sending: %s", data); return conn:write(data.."\r\n"); end end if data then session.data(data); end end function irc_listener.ondisconnect(conn, error) module:log("debug", "Client disconnected"); sessions[conn] = nil; end function commands.NICK(session, nick) nick = nick:match("^[%w_]+"); if nicks[nick] then session.send(":"..session.host.." 433 * The nickname "..nick.." is already in use"); return; end nicks[nick] = session; session.nick = nick; session.full_jid = nick.."@"..module.host.."/ircd"; session.type = "c2s"; module:log("debug", "Client bound to %s", session.full_jid); session.send(":"..session.host.." 001 "..session.nick.." :Welcome to XMPP via the "..session.host.." gateway "..session.nick); end local joined_mucs = {}; function commands.JOIN(session, channel) if not joined_mucs[channel] then joined_mucs[channel] = { occupants = {}, sessions = {} }; end joined_mucs[channel].sessions[session] = true; local join_stanza = st.presence({ from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }); core_process_stanza(session, join_stanza); session.send(":"..session.nick.." JOIN :"..channel); session.send(":"..session.host.." 332 "..session.nick.." "..channel.." :Connection in progress..."); session.send(":"..session.host.." 353 "..session.nick.." = "..channel.." :"..session.nick); session.send(":"..session.host.." 366 "..session.nick.." "..channel.." :End of /NAMES list."); end function commands.PART(session, channel) local channel, part_message = channel:match("^([^:]+):?(.*)$"); channel = channel:match("^([%S]*)"); core_process_stanza(session, st.presence{ type = "unavailable", from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }:tag("status"):text(part_message)); session.send(":"..session.nick.." PART :"..channel); end function commands.PRIVMSG(session, message) local who, message = message:match("^(%S+) :(.+)$"); if joined_mucs[who] then core_process_stanza(session, st.message{to=who:gsub("^#", "").."@"..conference_server, type="groupchat"}:tag("body"):text(message)); end end function commands.PING(session, server) session.send(":"..session.host..": PONG "..server); end function commands.WHO(session, channel) if joined_mucs[channel] then for nick in pairs(joined_mucs[channel].occupants) do --n=MattJ 91.85.191.50 irc.freenode.net MattJ H :0 Matthew Wild session.send(":"..session.host.." 352 "..session.nick.." "..channel.." "..nick.." "..nick.." "..session.host.." "..nick.." H :0 "..nick); end session.send(":"..session.host.." 315 "..session.nick.." "..channel.. " :End of /WHO list"); end end function commands.MODE(session, channel) session.send(":"..session.host.." 324 "..session.nick.." "..channel.." +J"); end --- Component (handle stanzas from the server for IRC clients) function irc_component(origin, stanza) local from, from_bare = stanza.attr.from, jid.bare(stanza.attr.from); local from_node = "#"..jid.split(stanza.attr.from); if joined_mucs[from_node] and from_bare == from then -- From room itself local joined_muc = joined_mucs[from_node]; if stanza.name == "message" then local subject = stanza:get_child("subject"); if subject then local subject_text = subject:get_text(); for session in pairs(joined_muc.sessions) do session.send(":"..session.host.." 332 "..session.nick.." "..from_node.." :"..subject_text); end end end elseif joined_mucs[from_node] then -- From room occupant local joined_muc = joined_mucs[from_node]; local nick = select(3, jid.split(from)):gsub(" ", "_"); if stanza.name == "presence" then local what; if not stanza.attr.type then if joined_muc.occupants[nick] then return; end joined_muc.occupants[nick] = true; what = "JOIN"; else joined_muc.occupants[nick] = nil; what = "PART"; end for session in pairs(joined_muc.sessions) do if nick ~= session.nick then session.send(":"..nick.."!"..nick.." "..what.." :"..from_node); end end elseif stanza.name == "message" then local body = stanza:get_child("body"); body = body and body:get_text() or ""; local hasdelay = stanza:get_child("delay", "urn:xmpp:delay"); if body ~= "" then for session in pairs(joined_muc.sessions) do if nick ~= session.nick or hasdelay then session.send(":"..nick.." PRIVMSG "..from_node.." :"..body); end end end end end end require "core.componentmanager".register_component(module.host, irc_component); prosody.events.add_handler("server-stopping", function (shutdown) module:log("debug", "Closing IRC connections prior to shutdown"); for channel, joined_muc in pairs(joined_mucs) do for session in pairs(joined_muc.sessions) do core_process_stanza(session, st.presence{ type = "unavailable", from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick } :tag("status") :text("Connection closed: Server is shutting down"..(shutdown.reason and (": "..shutdown.reason) or ""))); session:close(); end end end); require "net.connlisteners".register("irc", irc_listener); require "net.connlisteners".start("irc", { port = module:get_option("port") });
local irc_listener = { default_port = 6667, default_mode = "*l" }; local sessions = {}; local commands = {}; local nicks = {}; local st = require "util.stanza"; local conference_server = module:get_option("conference_server") or "conference.jabber.org"; local function irc_close_session(session) session.conn:close(); end function irc_listener.onincoming(conn, data) local session = sessions[conn]; if not session then session = { conn = conn, host = module.host, reset_stream = function () end, close = irc_close_session, log = logger.init("irc"..(conn.id or "1")), roster = {} }; sessions[conn] = session; function session.data(data) module:log("debug", "Received: %s", data); local command, args = data:match("^%s*([^ ]+) *(.*)%s*$"); if not command then module:log("warn", "Invalid command: %s", data); return; end command = command:upper(); module:log("debug", "Received command: %s", command); if commands[command] then local ret = commands[command](session, args); if ret then session.send(ret.."\r\n"); end end end function session.send(data) module:log("debug", "sending: %s", data); return conn:write(data.."\r\n"); end end if data then session.data(data); end end function irc_listener.ondisconnect(conn, error) module:log("debug", "Client disconnected"); sessions[conn] = nil; end function commands.NICK(session, nick) nick = nick:match("^[%w_]+"); if nicks[nick] then session.send(":"..session.host.." 433 * The nickname "..nick.." is already in use"); return; end nicks[nick] = session; session.nick = nick; session.full_jid = nick.."@"..module.host.."/ircd"; session.type = "c2s"; module:log("debug", "Client bound to %s", session.full_jid); session.send(":"..session.host.." 001 "..session.nick.." :Welcome to XMPP via the "..session.host.." gateway "..session.nick); end local joined_mucs = {}; function commands.JOIN(session, channel) if not joined_mucs[channel] then joined_mucs[channel] = { occupants = {}, sessions = {} }; end joined_mucs[channel].sessions[session] = true; local join_stanza = st.presence({ from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }); core_process_stanza(session, join_stanza); session.send(":"..session.nick.." JOIN :"..channel); session.send(":"..session.host.." 332 "..session.nick.." "..channel.." :Connection in progress..."); session.send(":"..session.host.." 353 "..session.nick.." = "..channel.." :"..session.nick); session.send(":"..session.host.." 366 "..session.nick.." "..channel.." :End of /NAMES list."); end function commands.PART(session, channel) local channel, part_message = channel:match("^([^:]+):?(.*)$"); channel = channel:match("^([%S]*)"); core_process_stanza(session, st.presence{ type = "unavailable", from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }:tag("status"):text(part_message)); session.send(":"..session.nick.." PART :"..channel); end function commands.PRIVMSG(session, message) local who, message = message:match("^(%S+) :(.+)$"); if joined_mucs[who] then core_process_stanza(session, st.message{to=who:gsub("^#", "").."@"..conference_server, type="groupchat"}:tag("body"):text(message)); end end function commands.PING(session, server) session.send(":"..session.host..": PONG "..server); end function commands.WHO(session, channel) if joined_mucs[channel] then for nick in pairs(joined_mucs[channel].occupants) do --n=MattJ 91.85.191.50 irc.freenode.net MattJ H :0 Matthew Wild session.send(":"..session.host.." 352 "..session.nick.." "..channel.." "..nick.." "..nick.." "..session.host.." "..nick.." H :0 "..nick); end session.send(":"..session.host.." 315 "..session.nick.." "..channel.. " :End of /WHO list"); end end function commands.MODE(session, channel) session.send(":"..session.host.." 324 "..session.nick.." "..channel.." +J"); end --- Component (handle stanzas from the server for IRC clients) function irc_component(origin, stanza) local from, from_bare = stanza.attr.from, jid.bare(stanza.attr.from); local from_node = "#"..jid.split(stanza.attr.from); if joined_mucs[from_node] and from_bare == from then -- From room itself local joined_muc = joined_mucs[from_node]; if stanza.name == "message" then local subject = stanza:get_child("subject"); subject = subject and (subject:get_text() or ""); if subject then for session in pairs(joined_muc.sessions) do session.send(":"..session.host.." 332 "..session.nick.." "..from_node.." :"..subject); end end end elseif joined_mucs[from_node] then -- From room occupant local joined_muc = joined_mucs[from_node]; local nick = select(3, jid.split(from)):gsub(" ", "_"); if stanza.name == "presence" then local what; if not stanza.attr.type then if joined_muc.occupants[nick] then return; end joined_muc.occupants[nick] = true; what = "JOIN"; else joined_muc.occupants[nick] = nil; what = "PART"; end for session in pairs(joined_muc.sessions) do if nick ~= session.nick then session.send(":"..nick.."!"..nick.." "..what.." :"..from_node); end end elseif stanza.name == "message" then local body = stanza:get_child("body"); body = body and body:get_text() or ""; local hasdelay = stanza:get_child("delay", "urn:xmpp:delay"); if body ~= "" then for session in pairs(joined_muc.sessions) do if nick ~= session.nick or hasdelay then session.send(":"..nick.." PRIVMSG "..from_node.." :"..body); end end end end end end require "core.componentmanager".register_component(module.host, irc_component); prosody.events.add_handler("server-stopping", function (shutdown) module:log("debug", "Closing IRC connections prior to shutdown"); for channel, joined_muc in pairs(joined_mucs) do for session in pairs(joined_muc.sessions) do core_process_stanza(session, st.presence{ type = "unavailable", from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick } :tag("status") :text("Connection closed: Server is shutting down"..(shutdown.reason and (": "..shutdown.reason) or ""))); session:close(); end end end); require "net.connlisteners".register("irc", irc_listener); require "net.connlisteners".start("irc", { port = module:get_option("port") });
mod_ircd: Fixed handling of empty <subject/> elements.
mod_ircd: Fixed handling of empty <subject/> elements.
Lua
mit
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
c2be4bdcb39b7b0f746bae9def5564dedee4bba8
src/characters/leonard.lua
src/characters/leonard.lua
local anim8 = require 'vendor/anim8' local plyr = {} plyr.name = 'leonard' plyr.offset = 9 plyr.ow = 13 plyr.costumes = { {name='Leonard Rodriguez', sheet='base'}, } local beam = love.graphics.newImage('images/characters/' .. plyr.name .. '/beam.png') function plyr.new(sheet) local new_plyr = {} new_plyr.sheet = sheet new_plyr.sheet:setFilter('nearest', 'nearest') local g = anim8.newGrid(48, 48, new_plyr.sheet:getWidth(), new_plyr.sheet:getHeight()) local warp = anim8.newGrid(36, 300, beam:getWidth(), beam:getHeight()) new_plyr.hand_offset = 10 new_plyr.beam = beam new_plyr.animations = { dead = { right = anim8.newAnimation('once', g('6,2'), 1), left = anim8.newAnimation('once', g('6,1'), 1) }, hold = { right = anim8.newAnimation('once', g(1,8), 1), left = anim8.newAnimation('once', g(1,9), 1), }, holdwalk = { right = anim8.newAnimation('loop', g('1-2,10'), 0.16), left = anim8.newAnimation('loop', g('1-2,11'), 0.16), }, crouch = { right = anim8.newAnimation('once', g('4,4'), 1), left = anim8.newAnimation('once', g('4,5'), 1) }, crouchwalk = { --state for walking towards the camera left = anim8.newAnimation('loop', g('2-3,4'), 0.16), right = anim8.newAnimation('loop', g('2-3,4'), 0.16), }, gaze = { right = anim8.newAnimation('once', g(7,2), 1), left = anim8.newAnimation('once', g(7,1), 1), }, gazewalk = { --state for walking away from the camera left = anim8.newAnimation('loop', g('2-3,5'), 0.16), right = anim8.newAnimation('loop', g('2-3,5'), 0.16), }, attack = { left = anim8.newAnimation('loop', g('1-2,7'), 0.16), right = anim8.newAnimation('loop', g('1-2,6'), 0.16), }, attackjump = { left = anim8.newAnimation('loop', g('3-4,7'), 0.16), right = anim8.newAnimation('loop', g('3-4,6'), 0.16), }, attackwalk = { left = anim8.newAnimation('loop', g('1,8','5,8','3,8','5,8'), 0.16), right = anim8.newAnimation( 'loop', g('1,7','5,7','3,7','5,7'), 0.16), }, jump = { right = anim8.newAnimation('once', g('9,4'), 1), left = anim8.newAnimation('once', g('9,5'), 1) }, walk = { right = anim8.newAnimation('loop', g('2-5,2'), 0.16), left = anim8.newAnimation('loop', g('2-5,1'), 0.16), }, idle = { right = anim8.newAnimation('once', g(1,2), 1), left = anim8.newAnimation('once', g(1,1), 1), }, warp = anim8.newAnimation('once', warp('1-4,1'), 0.08), } return new_plyr end return plyr
local anim8 = require 'vendor/anim8' local plyr = {} plyr.name = 'leonard' plyr.offset = 9 plyr.ow = 13 plyr.costumes = { {name='Leonard Rodriguez', sheet='base'}, } local beam = love.graphics.newImage('images/characters/' .. plyr.name .. '/beam.png') function plyr.new(sheet) local new_plyr = {} new_plyr.sheet = sheet new_plyr.sheet:setFilter('nearest', 'nearest') local g = anim8.newGrid(48, 48, new_plyr.sheet:getWidth(), new_plyr.sheet:getHeight()) local warp = anim8.newGrid(36, 300, beam:getWidth(), beam:getHeight()) new_plyr.hand_offset = 10 new_plyr.beam = beam new_plyr.animations = { dead = { right = anim8.newAnimation('once', g('6,2'), 1), left = anim8.newAnimation('once', g('6,1'), 1) }, hold = { right = anim8.newAnimation('once', g(1,8), 1), left = anim8.newAnimation('once', g(1,9), 1), }, holdwalk = { right = anim8.newAnimation('loop', g('1-2,10'), 0.16), left = anim8.newAnimation('loop', g('1-2,11'), 0.16), }, crouch = { right = anim8.newAnimation('once', g('4,4'), 1), left = anim8.newAnimation('once', g('4,5'), 1) }, crouchwalk = { --state for walking towards the camera left = anim8.newAnimation('loop', g('2-3,4'), 0.16), right = anim8.newAnimation('loop', g('2-3,4'), 0.16), }, gaze = { right = anim8.newAnimation('once', g(7,2), 1), left = anim8.newAnimation('once', g(7,1), 1), }, gazewalk = { --state for walking away from the camera left = anim8.newAnimation('loop', g('2-3,5'), 0.16), right = anim8.newAnimation('loop', g('2-3,5'), 0.16), }, attack = { left = anim8.newAnimation('loop', g('1-2,7'), 0.16), right = anim8.newAnimation('loop', g('1-2,6'), 0.16), }, attackjump = { left = anim8.newAnimation('loop', g('3-4,7'), 0.16), right = anim8.newAnimation('loop', g('3-4,6'), 0.16), }, attackwalk = { left = anim8.newAnimation('loop', g('1,8','5,8','3,8','5,8'), 0.16), right = anim8.newAnimation( 'loop', g('1,7','5,7','3,7','5,7'), 0.16), }, jump = { right = anim8.newAnimation('once', g('9,4'), 1), left = anim8.newAnimation('once', g('9,5'), 1) }, walk = { right = anim8.newAnimation('loop', g('2-5,2'), 0.16), left = anim8.newAnimation('loop', g('2-5,1'), 0.16), }, idle = { right = anim8.newAnimation('once', g(1,2), 1), left = anim8.newAnimation('once', g(1,1), 1), }, warp = anim8.newAnimation('once', warp('1-4,1'), 0.08), } return new_plyr end return plyr
Fixes line ending weirdness with leonard.lua
Fixes line ending weirdness with leonard.lua
Lua
mit
hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-client-lua
fdd9ab471486162d83273d400f6d33cb97ffebd1
scen_edit/command/set_sun_parameters_command.lua
scen_edit/command/set_sun_parameters_command.lua
SetSunParametersCommand = UndoableCommand:extends{} SetSunParametersCommand.className = "SetSunParametersCommand" function SetSunParametersCommand:init(opts) self.className = "SetSunParametersCommand" self.opts = opts end function SetSunParametersCommand:execute() local cmd = WidgetSetSunParametersCommand(self.opts) SCEN_EDIT.commandManager:execute(cmd, true) end function SetSunParametersCommand:unexecute() -- FIXME: widget command undo isn't implemented correctly yet end WidgetSetSunParametersCommand = UndoableCommand:extends{} WidgetSetSunParametersCommand.className = "WidgetSetSunParametersCommand" function WidgetSetSunParametersCommand:init(opts) self.opts = opts end function WidgetSetSunParametersCommand:execute() self.old = { -- manuallyControlled = Spring.IsSunManuallyControlled(), -- params = {Spring.GetSunParameters()}, params = {gl.GetSun()}, } Spring.SetSunManualControl(true) if self.opts.startAngle then Spring.SetSunParameters(self.opts.dirX, self.opts.dirY, self.opts.dirZ, self.opts.distance, self.opts.startAngle, self.opts.orbitTime) else Spring.SetSunDirection(self.opts.dirX, self.opts.dirY, self.opts.dirZ) end end function WidgetSetSunParametersCommand:unexecute() -- Spring.SetSunManualControl(self.old.manuallyControlled) if #self.old.params >= 4 then Spring.SetSunParameters(self.old.params[1], self.old.params[2], self.old.params[3], self.old.params[4], self.old.params[5], self.old.params[6]) else Spring.SetSunDirection(self.old.params[1], self.old.params[2], self.old.params[3]) end end
SetSunParametersCommand = UndoableCommand:extends{} SetSunParametersCommand.className = "SetSunParametersCommand" function SetSunParametersCommand:init(opts) self.className = "SetSunParametersCommand" self.opts = opts end function SetSunParametersCommand:execute() local cmd = WidgetSetSunParametersCommand(self.opts) SCEN_EDIT.commandManager:execute(cmd, true) end function SetSunParametersCommand:unexecute() -- FIXME: widget command undo isn't implemented correctly yet end WidgetSetSunParametersCommand = UndoableCommand:extends{} WidgetSetSunParametersCommand.className = "WidgetSetSunParametersCommand" function WidgetSetSunParametersCommand:init(opts) self.opts = opts end function WidgetSetSunParametersCommand:execute() self.old = { -- params = {Spring.GetSunParameters()}, params = {gl.GetSun()}, } if self.opts.startAngle then Spring.SetSunParameters(self.opts.dirX, self.opts.dirY, self.opts.dirZ, self.opts.distance, self.opts.startAngle, self.opts.orbitTime) else Spring.SetSunDirection(self.opts.dirX, self.opts.dirY, self.opts.dirZ) end end function WidgetSetSunParametersCommand:unexecute() if #self.old.params >= 4 then Spring.SetSunParameters(self.old.params[1], self.old.params[2], self.old.params[3], self.old.params[4], self.old.params[5], self.old.params[6]) else Spring.SetSunDirection(self.old.params[1], self.old.params[2], self.old.params[3]) end end
fix sun direction control
fix sun direction control
Lua
mit
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
9d3a74896dd3747c8a005115695e484052ec3b0b
roles/dotfiles/files/.imapfilter/work.lua
roles/dotfiles/files/.imapfilter/work.lua
dofile(os.getenv('HOME') .. '/.imapfilter/util.lua') local me = '[email protected]' local password = get_pass(me, 'outlook.office365.com') local phabricator_user = '<PHID-USER-dfiqtsjr7q4b4fu336uy>' local phabricator_team = '<PHID-PROJ-vgzmhfup375n4lfv4xka>' function connect() return IMAP { server = 'outlook.office365.com', port = 993, username = me, password = password, ssl = 'auto', } end function print_status(messages, description) label = #messages == 1 and 'message' or 'messages' print(description .. ': applied to ' .. #messages .. ' ' .. label) end function run() print "work: run" work = connect() phabricator = work.INBOX:match_field('X-Phabricator-Sent-This-Message', '.') differential = phabricator:contain_subject('[Differential]') reviewer = differential:contain_field('X-Differential-Reviewer', phabricator_user) commented = differential:contain_field('X-Phabricator-Mail-Tags', '<differential-comment>') uncommented = differential - commented messages = phabricator:contain_from(me) print_status(messages, 'My [Phabricator] actions -> archive & mark read') messages:mark_seen() messages:move_messages(work.Archive) closed = differential:contain_subject('[Closed]') messages = closed:contain_field('X-Phabricator-Mail-Tags', '<differential-committed>') print_status(messages, '[Closed] -> archive') messages:move_messages(work.Archive) accepted_and_shipped = differential:contain_subject('[Accepted and Shipped]') messages = accepted_and_shipped * uncommented print_status(messages, '[Accepted and Shipped] without comments -> archive') messages:move_messages(work.Archive) -- Metadata changes (not "[Updated, N line(s)]") without comments. updated = differential:contain_subject('[Updated]') messages = updated - commented print_status(messages, '[Updated] without comments -> archive') messages:move_messages(work.Archive) planned = differential:contain_subject('[Planned Changes To]') messages = planned - commented print_status(messages, '[Planned Changes To] without comments -> archive') messages:move_messages(work.Archive) -- If I'm not direct reviewer, I can probably ignore these. messages = planned - reviewer print_status(messages, '[Planned Changes To] not direct reviewer -> archive') messages:move_messages(work.Archive) -- 'Ch1rpBot' matches from, but 'Ch1rpBot <[email protected]>' does not. chirp_bot = work.INBOX:contain_from('Ch1rpBot') messages = chirp_bot:contain_subject('[land] [success]') print_status(messages, '[land] [success] -> archive') messages:move_messages(work.Archive) requests = differential: contain_field('X-Phabricator-Mail-Tags', '<differential-review-request') self = requests:contain_field('X-Differential-Reviewer', phabricator_user) team = requests:contain_field('X-Differential-Reviewer', phabricator_team) messages = requests * (self + team) print_status(messages, '[Request] (direct) -> Important') messages:mark_flagged() -- Archive abandoned and related emails as well. abandoned = differential:contain_subject('[Abandoned]'): contain_field('X-Differential-Status', 'Abandoned') for _, message in ipairs(abandoned) do mbox, uid = table.unpack(message) rev_key = string.gsub(mbox[uid]:fetch_field('In-Reply-To'), 'In%-Reply%-To: ', '') related = differential:contain_field('In-Reply-To', rev_key) + differential:contain_field('Message-ID', rev_key) abandoned = abandoned + related end print_status(abandoned, '[Abandoned] + related -> archive') abandoned:move_messages(work.Archive) end if os.getenv('DEBUG') then print 'DEBUG is set: running once.' run() else print 'Looping, to run once set DEBUG.' forever(run, 60) end
dofile(os.getenv('HOME') .. '/.imapfilter/util.lua') local me = '[email protected]' local password = get_pass(me, 'outlook.office365.com') local phabricator_user = '<PHID-USER-dfiqtsjr7q4b4fu336uy>' local phabricator_team = '<PHID-PROJ-vgzmhfup375n4lfv4xka>' function connect() return IMAP { server = 'outlook.office365.com', port = 993, username = me, password = password, ssl = 'auto', } end function print_status(messages, description) label = #messages == 1 and 'message' or 'messages' print(description .. ': applied to ' .. #messages .. ' ' .. label) end function run() print "work: run" work = connect() -- NOTE: Beware the use of contain_field when talking to an MS server; it is -- totally unreliable, so must use the slower match_field method. See: -- -- - https://github.com/lefcha/imapfilter/issues/14 -- - https://github.com/lefcha/imapfilter/issues/33 phabricator = work.INBOX:match_field('X-Phabricator-Sent-This-Message', '.') differential = phabricator:contain_subject('[Differential]') reviewer = differential:match_field('X-Differential-Reviewer', phabricator_user) commented = differential:match_field('X-Phabricator-Mail-Tags', '<differential-comment>') uncommented = differential - commented mine = differential:match_field('X-Differential-Author', phabricator_user) messages = phabricator:contain_from(me) print_status(messages, 'My [Phabricator] actions -> archive & mark read') messages:mark_seen() messages:move_messages(work.Archive) closed = differential:contain_subject('[Closed]') messages = closed:match_field('X-Phabricator-Mail-Tags', '<differential-committed>') print_status(messages, '[Closed] -> archive') messages:move_messages(work.Archive) accepted_and_shipped = differential:contain_subject('[Accepted and Shipped]') messages = accepted_and_shipped * uncommented print_status(messages, '[Accepted and Shipped] without comments -> archive') messages:move_messages(work.Archive) accepted = differential:contain_subject('[Accepted]') interim = accepted * uncommented messages = (accepted * uncommented) - mine print_status(messages, "[Accepted] without comments (others' diffs) -> archive") messages:move_messages(work.Archive) -- Metadata changes (not "[Updated, N line(s)]") without comments. updated = differential:contain_subject('[Updated]') messages = updated - commented print_status(messages, '[Updated] without comments -> archive') messages:move_messages(work.Archive) planned = differential:contain_subject('[Planned Changes To]') messages = planned - commented print_status(messages, '[Planned Changes To] without comments -> archive') messages:move_messages(work.Archive) -- If I'm not direct reviewer, I can probably ignore these. messages = planned - reviewer print_status(messages, '[Planned Changes To] not direct reviewer -> archive') messages:move_messages(work.Archive) -- 'Ch1rpBot' matches from, but 'Ch1rpBot <[email protected]>' does not. chirp_bot = work.INBOX:contain_from('Ch1rpBot') messages = chirp_bot:contain_subject('[land] [success]') print_status(messages, '[land] [success] -> archive') messages:move_messages(work.Archive) requests = differential: match_field('X-Phabricator-Mail-Tags', '<differential-review-request') self = requests:match_field('X-Differential-Reviewer', phabricator_user) team = requests:match_field('X-Differential-Reviewer', phabricator_team) messages = requests * (self + team) print_status(messages, '[Request] (direct) -> Important') messages:mark_flagged() -- Archive abandoned and related emails as well. abandoned = differential:contain_subject('[Abandoned]'): match_field('X-Differential-Status', 'Abandoned') for _, message in ipairs(abandoned) do mbox, uid = table.unpack(message) rev_key = string.gsub(mbox[uid]:fetch_field('In-Reply-To'), 'In%-Reply%-To: ', '') related = differential:match_field('In-Reply-To', rev_key) + differential:match_field('Message-ID', rev_key) abandoned = abandoned + related end print_status(abandoned, '[Abandoned] + related -> archive') abandoned:move_messages(work.Archive) end if os.getenv('DEBUG') then print 'DEBUG is set: running once.' run() else print 'Looping, to run once set DEBUG.' forever(run, 60) end
mutt: add more filters, fixing issues with Exchange and contain_field
mutt: add more filters, fixing issues with Exchange and contain_field While adding new fields noticed in testing that one of my `contain_field` calls was returning the wrong messages: `foo:contain_field('X-Differential-Author', 'some-id')` was matching all messages with the field, regardless of its contents. Other, similar `contain_field` usages (eg. for 'X-Differential-Mail-Tags' and such), *seemed* to be working. Screw it: rather than play guessing games about what will and won't work, use `match_field` instead. This is much slower because it downloads the headers and does the match locally, but it does mean we can use regular expressions if we want and, more importantly, we can actually filter the darn mail. I had similar issues with `content_from` before. `content_subject` *seems* to be OK, but I may well have to switch that as well if I want this to be truly robust, which I obviously do.
Lua
unlicense
wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent
297a5d27a4e29621044de03b50a9757e3a7de689
tests/metaparser/main3.lua
tests/metaparser/main3.lua
--$Name:Хейди$ game.dsc = [[^Пример простой игры на Inform. ^Авторы: Роджер Фирт (Roger Firth) и Соня Кессерих (Sonja Kesserich). ^Перевод Юрия Салтыкова a.k.a. G.A. Garinson^ ^Перевод на МЕТАПАРСЕР 3 выполнил Петр Косых. ^ ]] require "mp-ru" require "fmt" room { nam = "before_cottage"; title = "Перед домом"; dsc = "Ты стоишь около избушки, на восток от которой раскинулся лес."; e_to = 'forest'; in_to = function() p "Такой славный денек... Он слишком хорош, чтобы прятаться внутри."; end; cant_go = "Единственный путь ведет на восток."; obj = { 'cottage' }; } obj { -"домик,дом|избушка|терем|коттедж|хата|строение"; nam = "cottage"; dsc = "Домик мал и неказист, но ты очень счастлива, живя здесь."; before_Enter = [[Такой славный денек... Он слишком хорош, чтобы прятаться внутри.]]; } room { -"чаща|лес"; nam = "forest"; title = "В лесной чаще"; dsc = [[На западе, сквозь густую листву, можно разглядеть небольшое строение.^ Тропинка ведет на северо-восток.]]; w_to = 'before_cottage'; ne_to = 'clearing'; obj = { 'bird' }; } obj { -"птенчик,птенец,птица,птичка,детёныш"; nam = "bird"; description = "Слишком мал, чтобы летать, птенец беспомощно попискивает."; before_Listen = "Жалобный писк испуганной птички разрывает тебе сердце.^Надо помочь!"; }: attr '~animate' room { -"полянка,поляна"; nam = "clearing"; title = "Полянка"; dsc = [[Посреди полянки стоит высокий платан. Тропинка вьется меж деревьев, уводя на юго-запад.]]; sw_to = 'forest'; u_to = 'top_of_tree'; obj = { 'nest', 'tree' }; } obj { -"гнездо|мох|прутики,прутья"; nam = "nest"; description = function(s) p "Гнездо сплетено из прутиков и аккуратно устлано мхом."; mp:content(s) end; }: attr 'container,open' obj { -"платан|дерево|ствол"; nam = 'tree'; description = [[Величавое дерево стоит посреди поляны. Кажется, по его стволу будет несложно влезть наверх.]]; before_Climb = function(s) move(me(), 'top_of_tree'); end } : attr 'scenery' room { -"верхушка"; nam = 'top_of_tree'; title = "На верхушке дерева"; dsc = "На этой высоте цепляться за ствол уже не так удобно."; d_to = 'clearing'; after_Drop = function(s, w) move(w, 'clearing') return false end; obj = { 'branch' }; } obj { -"сук|ветка"; nam = 'branch'; description = "Сук достаточно ровный и крепкий, чтобы на нем надежно держалось что-то не очень большое."; each_turn = function(s) if _'bird':inside'nest' and _'nest':inside'branch' then walk 'happyend' end end }:attr 'supporter' room { nam = 'happyend'; title = "Конец"; dsc = [[Поздравляем! Вы прошли игру.]]; } pl.word = -"ты/жр,2л" pl.room = 'before_cottage' function start() for _, v in pairs((_'branch':gram(2))) do print(_, v) end end
--$Name:Хейди$ game.dsc = [[^Пример простой игры на Inform. ^Авторы: Роджер Фирт (Roger Firth) и Соня Кессерих (Sonja Kesserich). ^Перевод Юрия Салтыкова a.k.a. G.A. Garinson^ ^Перевод на МЕТАПАРСЕР 3 выполнил Петр Косых. ^ ]] require "mp-ru" require "fmt" room { nam = "before_cottage"; title = "Перед домом"; dsc = "Ты стоишь около избушки, на восток от которой раскинулся лес."; e_to = 'forest'; in_to = function() p "Такой славный денек... Он слишком хорош, чтобы прятаться внутри."; end; cant_go = "Единственный путь ведет на восток."; obj = { 'cottage' }; } obj { -"домик,дом|избушка|терем|коттедж|хата|строение"; nam = "cottage"; dsc = "Домик мал и неказист, но ты очень счастлива, живя здесь."; before_Enter = [[Такой славный денек... Он слишком хорош, чтобы прятаться внутри.]]; } room { -"чаща|лес"; nam = "forest"; title = "В лесной чаще"; dsc = [[На западе, сквозь густую листву, можно разглядеть небольшое строение.^ Тропинка ведет на северо-восток.]]; w_to = 'before_cottage'; ne_to = 'clearing'; obj = { 'bird' }; } obj { -"птенчик,птенец,птица,птичка,детёныш"; nam = "bird"; description = "Слишком мал, чтобы летать, птенец беспомощно попискивает."; before_Listen = "Жалобный писк испуганной птички разрывает тебе сердце.^Надо помочь!"; }: attr '~animate' room { -"полянка,поляна"; nam = "clearing"; title = "Полянка"; dsc = [[Посреди полянки стоит высокий платан. Тропинка вьется меж деревьев, уводя на юго-запад.]]; sw_to = 'forest'; u_to = 'top_of_tree'; obj = { 'nest', 'tree' }; } obj { -"гнездо|мох|прутики,прутья"; nam = "nest"; description = function(s) p "Гнездо сплетено из прутиков и аккуратно устлано мхом."; mp:content(s) end; }: attr 'container,open' obj { -"платан|дерево|ствол"; nam = 'tree'; description = [[Величавое дерево стоит посреди поляны. Кажется, по его стволу будет несложно влезть наверх.]]; before_Climb = function(s) move(me(), 'top_of_tree'); end } : attr 'scenery' room { -"верхушка"; nam = 'top_of_tree'; title = "На верхушке дерева"; dsc = "На этой высоте цепляться за ствол уже не так удобно."; d_to = 'clearing'; after_Drop = function(s, w) move(w, 'clearing') return false end; obj = { 'branch' }; } obj { -"сук|ветка"; nam = 'branch'; description = "Сук достаточно ровный и крепкий, чтобы на нем надежно держалось что-то не очень большое."; each_turn = function(s) if _'bird':inside'nest' and _'nest':inside'branch' then walk 'happyend' end end }:attr 'supporter' room { nam = 'happyend'; title = "Конец"; dsc = [[Поздравляем! Вы прошли игру.]]; } function init() pl.word = -"ты/жр,2л" pl.room = 'before_cottage' end
heidi fix
heidi fix
Lua
mit
gl00my/stead3
e25d114b78d825f4132d433c58b19f778f7ca800
lib/switchboard_modules/lua_script_debugger/premade_scripts/i2c/accelerometer-adxl345.lua
lib/switchboard_modules/lua_script_debugger/premade_scripts/i2c/accelerometer-adxl345.lua
--[[ Name: accelerometer-adxl345.lua Desc: This is an example that uses the ADXL345 Accelerometer on the I2C Bus on EIO4(SCL) and EIO5(SDA) --]] --Outputs data to Registers: --X accel = 46000 --Y accel = 46002 --Z accel = 46004 ------------------------------------------------------------------------------- -- Desc: Returns a number adjusted using the conversion factor -- Use 1 if not desired ------------------------------------------------------------------------------- local function convert_16_bit(msb, lsb, conv) res = 0 if msb >= 128 then res = (-0x7FFF+((msb-128)*256+lsb))/conv else res = (msb*256+lsb)/conv end return res end local SLAVE_ADDRESS = 0x53 I2C.config(13, 12, 65516, 0, SLAVE_ADDRESS, 0)--configure the I2C Bus local addrs = I2C.search(0, 127) local addrslen = table.getn(addrs) local found = 0 -- Make sure the device slave address is found for i=1, addrslen do if addrs[i] == SLAVE_ADDRESS then print("I2C Slave Detected") found = 1 break end end if found == 0 then print("No I2C Slave detected, program stopping") MB.writeName("LUA_RUN", 0) end -- Set for +-4g (use 0x08 for 2g) in full resolution mode I2C.write({0x31, 0x09}) -- Disable power saving I2C.write({0x2D, 0x08}) -- Used to control program progress local stage = 0 -- Configure a 500ms interval local interval = 500 LJ.IntervalConfig(0, interval) while true do -- If an interval is done if LJ.CheckInterval(0) then if stage == 0 then -- Begin the stream of 6 bytes I2C.write({0x32}) -- Set an interval of 100ms to give the range finder some processing time LJ.IntervalConfig(0, 100) stage = 1 elseif stage == 1 then -- Read the raw data local raw = I2C.read(6) local data = {} -- Process the raw data for i=0, 2 do table.insert(data, convert_16_bit(raw[(2*i)+2], raw[(2*i)+1], 233)) end -- Add X value, in Gs, to the user_ram register MB.writeName("USER_RAM0_F32", data[1]) -- Add Y MB.writeName("USER_RAM1_F32", data[2]) -- Add Z MB.writeName("USER_RAM2_F32", data[3]) print("X", data[1]) print("Y", data[2]) print("Z", data[3]) print("-----------") -- Set the interval back to the original duration LJ.IntervalConfig(0, interval) stage = 0 end end end
--[[ Name: accelerometer-adxl345.lua Desc: This is an example that uses the ADXL345 Accelerometer on the I2C Bus on EIO4(SCL) and EIO5(SDA) --]] --Outputs data to Registers: --X accel = 46000 --Y accel = 46002 --Z accel = 46004 ------------------------------------------------------------------------------- -- Desc: Returns a number adjusted using the conversion factor -- Use 1 if not desired ------------------------------------------------------------------------------- local function convert_16_bit(msb, lsb, conv) res = 0 if msb >= 128 then res = (-0x7FFF+((msb-128)*256+lsb))/conv else res = (msb*256+lsb)/conv end return res end local SLAVE_ADDRESS = 0x53 -- Use EIO3 for power MB.writeName("EIO3", 1) -- Use EIO2 to pull up CS MB.writeName("EIO2", 1) -- Use EOI5(DIO13) for SDA and EIO4(DIO12) for SCL I2C.config(13, 12, 65516, 0, SLAVE_ADDRESS, 0) local addrs = I2C.search(0, 127) local addrslen = table.getn(addrs) local found = 0 -- Make sure the device slave address is found for i=1, addrslen do if addrs[i] == SLAVE_ADDRESS then print("I2C Slave Detected") found = 1 break end end if found == 0 then print("No I2C Slave detected, program stopping") MB.writeName("LUA_RUN", 0) end -- Set for +-4g (use 0x08 for 2g) in full resolution mode I2C.write({0x31, 0x09}) -- Disable power saving I2C.write({0x2D, 0x08}) -- Used to control program progress local stage = 0 -- Configure a 500ms interval local interval = 500 LJ.IntervalConfig(0, interval) while true do -- If an interval is done if LJ.CheckInterval(0) then if stage == 0 then -- Begin the stream of 6 bytes I2C.write({0x32}) -- Set an interval of 100ms to give the range finder some processing time LJ.IntervalConfig(0, 100) stage = 1 elseif stage == 1 then -- Read the raw data local raw = I2C.read(6) local data = {} -- Process the raw data for i=0, 2 do table.insert(data, convert_16_bit(raw[(2*i)+2], raw[(2*i)+1], 233)) end -- Add X value, in Gs, to the user_ram register MB.writeName("USER_RAM0_F32", data[1]) -- Add Y MB.writeName("USER_RAM1_F32", data[2]) -- Add Z MB.writeName("USER_RAM2_F32", data[3]) print("X", data[1]) print("Y", data[2]) print("Z", data[3]) print("-----------") -- Set the interval back to the original duration LJ.IntervalConfig(0, interval) stage = 0 end end end
Fixed up the adxl345 example
Fixed up the adxl345 example
Lua
mit
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
d4c01b0ab321edd290ea0262a67119026c78c5d3
config/nvim/lua/plugin/rc/catppuccin.lua
config/nvim/lua/plugin/rc/catppuccin.lua
local M = {} local catppuccin = require("catppuccin") local colors = require("catppuccin.api.colors").get_colors() function M.config() catppuccin.setup({}) catppuccin.remap({ HighlightedCursorLineNr = { fg = colors.red }, HighlightedLineNr = { fg = colors.white }, HighlightedLineNr1 = { fg = colors.maroon }, HighlightedLineNr2 = { fg = colors.peach }, HighlightedLineNr3 = { fg = colors.yellow }, HighlightedLineNr4 = { fg = colors.green }, HighlightedLineNr5 = { fg = colors.blue }, DimLineNr = { fg = colors.black4 }, ActiveWindow = { bg = colors.black2 }, InactiveWindow = { bg = colors.black0 }, WinBarContent = { fg = colors.black2, bg = colors.sky }, WinBarSeparator = { fg = colors.sky }, ColorColumn = { bg = colors.black1 } }) vim.opt.winhighlight = "Normal:ActiveWindow,NormalNC:InactiveWindow,CursorLineNr:HighlightedCursorLineNr" vim.api.nvim_cmd({ cmd = "colorscheme", args = { "catppuccin" }, }, {}) end return M
local M = {} local catppuccin = require("catppuccin") local colors = require("catppuccin.api.colors").get_colors() function M.config() catppuccin.setup({}) catppuccin.remap({ HighlightedCursorLineNr = { fg = colors.red }, HighlightedLineNr = { fg = colors.text }, HighlightedLineNr1 = { fg = colors.maroon }, HighlightedLineNr2 = { fg = colors.peach }, HighlightedLineNr3 = { fg = colors.yellow }, HighlightedLineNr4 = { fg = colors.green }, HighlightedLineNr5 = { fg = colors.teal }, DimLineNr = { fg = colors.surface1 }, ActiveWindow = { bg = colors.base }, InactiveWindow = { bg = colors.mantle }, WinBarContent = { fg = colors.base, bg = colors.sapphire }, WinBarSeparator = { fg = colors.sapphire }, ColorColumn = { bg = colors.mantle } }) vim.opt.winhighlight = "Normal:ActiveWindow,NormalNC:InactiveWindow,CursorLineNr:HighlightedCursorLineNr" vim.api.nvim_cmd({ cmd = "colorscheme", args = { "catppuccin" }, }, {}) end return M
fix: Update color palette for recently catppuccin update.
fix: Update color palette for recently catppuccin update.
Lua
mit
IMOKURI/dotfiles,IMOKURI/dotfiles
6fe2c8bbc8a5208c33d4e32d222d82b3ee505849
Framework/LuaTools/info.lua
Framework/LuaTools/info.lua
function get_info(cmd, default) local f = io.popen (cmd, "r"); local rev = f:read("*a") f:close (); if rev ~= nil then return rev end return default end REVISION = get_info("git rev-parse HEAD", -1) USER_NAME = get_info("git config user.name", "-") BRANCH_PATH = get_info("git branch -a", -1) REVISION = string.gsub(REVISION,"\n", "") USER_NAME = string.gsub(USER_NAME,"\n", "") print("INFO: repository info") print(" REVISION = " .. REVISION) print(" USER_NAME = " .. USER_NAME) print(" BRANCH_PATH = " .. BRANCH_PATH) print()
function get_info(cmd, default) local f = io.popen (cmd, "r"); local rev = f:read("*a") f:close (); if rev ~= nil then return rev end return default end REVISION = get_info("git rev-parse HEAD", -1) USER_NAME = get_info("git config user.name", -1) BRANCH_PATH = get_info("git branch -a", -1) REVISION = string.gsub(REVISION,"\n", "") USER_NAME = string.gsub(USER_NAME,"\n", "") BRANCH_PATH = "(* indicates active branch in following list)\n [\n " .. string.gsub(BRANCH_PATH,"\n", "\n ") .."]" print("INFO: repository info") print(" REVISION = " .. REVISION) print(" USER_NAME = " .. USER_NAME) print(" BRANCH_PATH = " .. BRANCH_PATH) print() BRANCH_PATH = "todo"
buxfix: broken branch path corrected
buxfix: broken branch path corrected
Lua
apache-2.0
BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH
91c1285b7e51b4da6c202d367b8af9a37a7a0a93
ffi/framebuffer_pocketbook.lua
ffi/framebuffer_pocketbook.lua
local ffi = require("ffi") local BB = require("ffi/blitbuffer") local inkview = ffi.load("inkview") require("ffi/inkview_h") require("ffi/linux_fb_h") local framebuffer = { } function framebuffer:init() self._finfo = ffi.new("struct fb_fix_screeninfo") self._vinfo = ffi.new("struct fb_var_screeninfo") local finfo = self._finfo local vinfo = self._vinfo self.debug("Initialize inkview screen") inkview.OpenScreen() local pb_fb = inkview.GetTaskFramebuffer(inkview.GetCurrentTask()) self._finfo.line_length = pb_fb.scanline self._vinfo.xres = pb_fb.width self._vinfo.yres = pb_fb.height self.fb_size = self._finfo.line_length * self._vinfo.yres self._vinfo.width = pb_fb.width self._vinfo.height = pb_fb.height local bpp = pb_fb.depth self.data = pb_fb.addr self.bb = BB.new(pb_fb.width, pb_fb.height, BB["TYPE_BB"..bpp] or BB["TYPE_BBRGB"..bpp], self.data, pb_fb.scanline, pb_fb.width) self.blitbuffer_rotation_mode = self.bb:getRotation() self.screen_size = self:getRawSize() self.native_rotation_mode = self.forced_rotation and self.forced_rotation.default or self.ORIENTATION_PORTRAIT self.cur_rotation_mode = self.native_rotation_mode self.debug("FB info (post fixup)", { fb_size = self.fb_size, xres = vinfo.xres, yres = vinfo.yres, xoffset = vinfo.xoffset, yoffset = vinfo.yoffset, bpp = bpp, xres_virtual = vinfo.xres, yres_virtual = vinfo.yres, line_length = finfo.line_length, stride_pixels = finfo.line_length, smem_len = finfo.smem_len, type = finfo.type, mmio_len = finfo.mmio_len, rotate = vinfo.rotate, width_mm = vinfo.width, height_mm = vinfo.height, }) end function framebuffer:close(reinit) if self.bb ~= nil then self.bb:free() self.bb = nil end end --[[ framebuffer API ]]-- function framebuffer:refreshPartialImp(x, y, w, h, dither) self.debug("refresh: inkview partial", x, y, w, h) inkview.PartialUpdate(x, y, w, h) end function framebuffer:refreshFlashPartialImp(x, y, w, h, dither) self.debug("refresh: inkview partial", x, y, w, h) inkview.PartialUpdate(x, y, w, h) end function framebuffer:refreshUIImp(x, y, w, h, dither) self.debug("refresh: inkview partial", x, y, w, h) inkview.PartialUpdate(x, y, w, h) end function framebuffer:refreshFlashUIImp(x, y, w, h, dither) self.debug("refresh: inkview partial", x, y, w, h) inkview.PartialUpdate(x, y, w, h) end function framebuffer:refreshFullImp(x, y, w, h, dither) self.debug("refresh: inkview partial", x, y, w, h) inkview.FullUpdate() end function framebuffer:refreshFastImp(x, y, w, h, dither) self.debug("refresh: inkview dynamic", x, y, w, h) inkview.DynamicUpdate(x, y, w, h) end function framebuffer:refreshWaitForLastImp() if self.mech_wait_update_complete and self.dont_wait_for_marker ~= self.marker then self.debug("refresh: inkview waiting for previous update", self.marker) -- self:mech_wait_update_complete(self.marker) inkview.WaitForUpdateComplete() self.dont_wait_for_marker = self.marker end end return require("ffi/framebuffer_linux"):extend(framebuffer)
local ffi = require("ffi") local BB = require("ffi/blitbuffer") local inkview = ffi.load("inkview") require("ffi/inkview_h") require("ffi/linux_fb_h") local framebuffer = { } local function _getPhysicalRect(fb, x, y, w, h) local bb = fb.full_bb or fb.bb w, x = BB.checkBounds(w or bb:getWidth(), x or 0, 0, bb:getWidth(), 0xFFFF) h, y = BB.checkBounds(h or bb:getHeight(), y or 0, 0, bb:getHeight(), 0xFFFF) return bb:getPhysicalRect(x, y, w, h) end local function _updatePartial(fb, x, y, w, h) x, y, w, h = _getPhysicalRect(fb, x, y, w, h) fb.debug("refresh: inkview partial", x, y, w, h) inkview.PartialUpdate(x, y, w, h) end local function _updateFull(fb, x, y, w, h) fb.debug("refresh: inkview full", x, y, w, h) inkview.FullUpdate() end local function _updateFast(fb, x, y, w, h) x, y, w, h = _getPhysicalRect(fb, x, y, w, h) fb.debug("refresh: inkview fast", x, y, w, h) inkview.DynamicUpdate(x, y, w, h) end function framebuffer:init() self._finfo = ffi.new("struct fb_fix_screeninfo") self._vinfo = ffi.new("struct fb_var_screeninfo") local finfo = self._finfo local vinfo = self._vinfo self.debug("Initialize inkview screen") inkview.OpenScreen() local pb_fb = inkview.GetTaskFramebuffer(inkview.GetCurrentTask()) self._finfo.line_length = pb_fb.scanline self._vinfo.xres = pb_fb.width self._vinfo.yres = pb_fb.height self.fb_size = self._finfo.line_length * self._vinfo.yres self._vinfo.width = pb_fb.width self._vinfo.height = pb_fb.height local bpp = pb_fb.depth self.data = pb_fb.addr self.bb = BB.new(pb_fb.width, pb_fb.height, BB["TYPE_BB"..bpp] or BB["TYPE_BBRGB"..bpp], self.data, pb_fb.scanline, pb_fb.width) self.blitbuffer_rotation_mode = self.bb:getRotation() self.screen_size = self:getRawSize() self.native_rotation_mode = self.forced_rotation and self.forced_rotation.default or self.ORIENTATION_PORTRAIT self.cur_rotation_mode = self.native_rotation_mode self.debug("FB info (post fixup)", { fb_size = self.fb_size, xres = vinfo.xres, yres = vinfo.yres, xoffset = vinfo.xoffset, yoffset = vinfo.yoffset, bpp = bpp, xres_virtual = vinfo.xres, yres_virtual = vinfo.yres, line_length = finfo.line_length, stride_pixels = finfo.line_length, smem_len = finfo.smem_len, type = finfo.type, mmio_len = finfo.mmio_len, rotate = vinfo.rotate, width_mm = vinfo.width, height_mm = vinfo.height, }) end function framebuffer:close(reinit) if self.bb ~= nil then self.bb:free() self.bb = nil end end --[[ framebuffer API ]]-- function framebuffer:refreshPartialImp(x, y, w, h, dither) _updatePartial(self, x, y, w, h) end function framebuffer:refreshFlashPartialImp(x, y, w, h, dither) _updatePartial(self, x, y, w, h) end function framebuffer:refreshUIImp(x, y, w, h, dither) _updatePartial(self, x, y, w, h) end function framebuffer:refreshFlashUIImp(x, y, w, h, dither) _updatePartial(self, x, y, w, h) end function framebuffer:refreshFullImp(x, y, w, h, dither) _updateFull(self, x, y, w, h) end function framebuffer:refreshFastImp(x, y, w, h, dither) _updateFast(self, x, y, w, h) end function framebuffer:refreshWaitForLastImp() if self.mech_wait_update_complete and self.dont_wait_for_marker ~= self.marker then self.debug("refresh: inkview waiting for previous update", self.marker) -- self:mech_wait_update_complete(self.marker) inkview.WaitForUpdateComplete() self.dont_wait_for_marker = self.marker end end return require("ffi/framebuffer_linux"):extend(framebuffer)
Fix screen being partially refreshed when screen was rotated 90deg. (#1454)
Fix screen being partially refreshed when screen was rotated 90deg. (#1454) Fixes: https://github.com/koreader/koreader/issues/8773 When the screen was rotated 90deg. The screen was only updated partially.
Lua
agpl-3.0
NiLuJe/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,koreader/koreader-base,Frenzie/koreader-base,Frenzie/koreader-base,koreader/koreader-base
1884237120fbbb3c9b29032d995c132af381f16b
src/sounds/src/Shared/SoundUtils.lua
src/sounds/src/Shared/SoundUtils.lua
--[=[ Helps plays back sounds in the Roblox engine. ```lua SoundUtils.playFromId("rbxassetid://4255432837") -- Plays a wooshing sound ``` @class SoundUtils ]=] local SoundService = game:GetService("SoundService") local SoundUtils = {} --[=[ Plays back a template given asset id. ```lua SoundUtils.playFromId("rbxassetid://4255432837") -- Plays a wooshing sound ``` :::tip The sound will be automatically cleaned up after the sound is played. ::: @param id string | number @return Sound ]=] function SoundUtils.playFromId(id) local soundId = SoundUtils.toRbxAssetId(id) assert(type(soundId) == "string", "Bad id") local sound = Instance.new("Sound") sound.Name = ("Sound_%s"):format(soundId) sound.SoundId = soundId sound.Volume = 0.25 sound.Archivable = false SoundService:PlayLocalSound(sound) task.delay(sound.TimeLength + 0.05, function() sound:Destroy() end) return sound end --[=[ Plays back a template given the templateName. :::tip The sound will be automatically cleaned up after the sound is played. ::: @param templates TemplateProvider @param templateName string @return Sound ]=] function SoundUtils.playTemplate(templates, templateName) assert(type(templates) == "table", "Bad templates") assert(type(templateName) == "string", "Bad templateName") local sound = templates:Clone(templateName) sound.Archivable = false SoundService:PlayLocalSound(sound) task.delay(sound.TimeLength + 0.05, function() sound:Destroy() end) return sound end --[=[ Converts a string or number to a string for playback. @param id string | number @return string ]=] function SoundUtils.toRbxAssetId(id) if type(id) == "number" then return ("rbxassetid://%d"):format(id) else return id end end --[=[ Plays back a sound template in a specific parent. :::tip The sound will be automatically cleaned up after the sound is played. ::: @param templates TemplateProvider @param templateName string @param parent Instance @return Sound ]=] function SoundUtils.playTemplateInParent(templates, templateName, parent) local sound = templates:Clone(templateName) sound.Archivable = false sound.Parent = parent sound:Play() task.delay(sound.TimeLength + 0.05, function() sound:Destroy() end) return sound end return SoundUtils
--[=[ Helps plays back sounds in the Roblox engine. ```lua SoundUtils.playFromId("rbxassetid://4255432837") -- Plays a wooshing sound ``` @class SoundUtils ]=] local SoundService = game:GetService("SoundService") local RunService = game:GetService("RunService") local SoundUtils = {} --[=[ Plays back a template given asset id. ```lua SoundUtils.playFromId("rbxassetid://4255432837") -- Plays a wooshing sound ``` :::tip The sound will be automatically cleaned up after the sound is played. ::: @param id string | number @return Sound ]=] function SoundUtils.playFromId(id) local soundId = SoundUtils.toRbxAssetId(id) assert(type(soundId) == "string", "Bad id") local sound = Instance.new("Sound") sound.Name = ("Sound_%s"):format(soundId) sound.SoundId = soundId sound.Volume = 0.25 sound.Archivable = false if RunService:IsClient() then SoundService:PlayLocalSound(sound) else sound:Play() end task.delay(sound.TimeLength + 0.05, function() sound:Destroy() end) return sound end --[=[ Plays back a template given the templateName. :::tip The sound will be automatically cleaned up after the sound is played. ::: @param templates TemplateProvider @param templateName string @return Sound ]=] function SoundUtils.playTemplate(templates, templateName) assert(type(templates) == "table", "Bad templates") assert(type(templateName) == "string", "Bad templateName") local sound = templates:Clone(templateName) sound.Archivable = false SoundService:PlayLocalSound(sound) task.delay(sound.TimeLength + 0.05, function() sound:Destroy() end) return sound end --[=[ Converts a string or number to a string for playback. @param id string | number @return string ]=] function SoundUtils.toRbxAssetId(id) if type(id) == "number" then return ("rbxassetid://%d"):format(id) else return id end end --[=[ Plays back a sound template in a specific parent. :::tip The sound will be automatically cleaned up after the sound is played. ::: @param templates TemplateProvider @param templateName string @param parent Instance @return Sound ]=] function SoundUtils.playTemplateInParent(templates, templateName, parent) local sound = templates:Clone(templateName) sound.Archivable = false sound.Parent = parent sound:Play() task.delay(sound.TimeLength + 0.05, function() sound:Destroy() end) return sound end return SoundUtils
fix: Support sound playback for non-local situations. On the server this will require the sound to be parented.
fix: Support sound playback for non-local situations. On the server this will require the sound to be parented.
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
adcf0164338067237fcbb36f42684fa76bfa7b5d
Source/Urho3D/LuaScript/pkgs/ToCppHook.lua
Source/Urho3D/LuaScript/pkgs/ToCppHook.lua
-- -- Copyright (c) 2008-2015 the Urho3D project. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- local toWrite = {} local currentString = '' local out local WRITE, OUTPUT = write, output function output(s) out = _OUTPUT output = OUTPUT -- restore output(s) end function write(a) if out == _OUTPUT then currentString = currentString .. a if string.sub(currentString,-1) == '\n' then toWrite[#toWrite+1] = currentString currentString = '' end else WRITE(a) end end function post_output_hook(package) local result = table.concat(toWrite) local function replace(pattern, replacement) local k = 0 local nxt, currentString = 1, '' repeat local s, e = string.find(result, pattern, nxt, true) if e then currentString = currentString .. string.sub(result, nxt, s-1) .. replacement nxt = e + 1 k = k + 1 end until not e result = currentString..string.sub(result, nxt) --if k == 0 then print('Pattern not replaced', pattern) end end replace("\t", " ") replace([[#ifndef __cplusplus #include "stdlib.h" #endif #include "string.h" #include "tolua++.h"]], [[// // Copyright (c) 2008-2015 the Urho3D project. // // 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. // #include <toluapp/tolua++.h> #include <Urho3D/LuaScript/ToluaUtils.h> #if __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-function" #endif]]) if _extra_parameters["Urho3D"] then replace([[<Urho3D/LuaScript/ToluaUtils.h>]], [["LuaScript/ToluaUtils.h"]]) end WRITE(result) WRITE([[ #if __clang__ #pragma clang diagnostic pop #endif]]) end _push_functions['Component'] = "ToluaPushObject" _push_functions['Resource'] = "ToluaPushObject" _push_functions['UIElement'] = "ToluaPushObject" -- Is Urho3D Vector type. function urho3d_is_vector(t) return t:find("Vector<") ~= nil end -- Is Urho3D PODVector type. function urho3d_is_podvector(t) return t:find("PODVector<") ~= nil end local old_get_push_function = get_push_function local old_get_to_function = get_to_function local old_get_is_function = get_is_function function get_push_function(t) if not urho3d_is_vector(t) then return old_get_push_function(t) end if not urho3d_is_podvector(t) then return "ToluaPushVector" .. t:match("<.*>") else return "ToluaPushPODVector" .. t:match("<.*>") end end function get_to_function(t) if not urho3d_is_vector(t) then return old_get_to_function(t) end if not urho3d_is_podvector(t) then return "ToluaToVector" .. t:match("<.*>") else return "ToluaToPODVector" .. t:match("<.*>") end end function get_is_function(t) if not urho3d_is_vector(t) then return old_get_is_function(t) end if not urho3d_is_podvector(t) then return "ToluaIsVector" .. t:match("<.*>") else return "ToluaIsPODVector" .. t:match("<.*>") end end function get_property_methods_hook(ptype, name) if ptype == "get_set" then local Name = string.upper(string.sub(name, 1, 1))..string.sub(name, 2) return "Get"..Name, "Set"..Name end if ptype == "is_set" then local Name = string.upper(string.sub(name, 1, 1))..string.sub(name, 2) return "Is"..Name, "Set"..Name end if ptype == "has_set" then local Name = string.upper(string.sub(name, 1, 1))..string.sub(name, 2) return "Has"..Name, "Set"..Name end if ptype == "no_prefix" then local Name = string.upper(string.sub(name, 1, 1))..string.sub(name, 2) return Name, "Set"..Name end end
-- -- Copyright (c) 2008-2015 the Urho3D project. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- local toWrite = {} local currentString = '' local out local WRITE, OUTPUT = write, output function output(s) out = _OUTPUT output = OUTPUT -- restore output(s) end function write(a) if out == _OUTPUT then currentString = currentString .. a if string.sub(currentString,-1) == '\n' then toWrite[#toWrite+1] = currentString currentString = '' end else WRITE(a) end end function post_output_hook(package) local result = table.concat(toWrite) local function replace(pattern, replacement) local k = 0 local nxt, currentString = 1, '' repeat local s, e = string.find(result, pattern, nxt, true) if e then currentString = currentString .. string.sub(result, nxt, s-1) .. replacement nxt = e + 1 k = k + 1 end until not e result = currentString..string.sub(result, nxt) --if k == 0 then print('Pattern not replaced', pattern) end end replace("\t", " ") replace([[#ifndef __cplusplus #include "stdlib.h" #endif #include "string.h" #include "tolua++.h"]], [[// // Copyright (c) 2008-2015 the Urho3D project. // // 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. // #include <toluapp/tolua++.h> #include "LuaScript/ToluaUtils.h" #if __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-function" #endif]]) if not _extra_parameters["Urho3D"] then replace([[#include "LuaScript/ToluaUtils.h"]], [[#include <Urho3D/Urho3D.h> #include <Urho3D/LuaScript/ToluaUtils.h>]]) end WRITE(result) WRITE([[ #if __clang__ #pragma clang diagnostic pop #endif]]) end _push_functions['Component'] = "ToluaPushObject" _push_functions['Resource'] = "ToluaPushObject" _push_functions['UIElement'] = "ToluaPushObject" -- Is Urho3D Vector type. function urho3d_is_vector(t) return t:find("Vector<") ~= nil end -- Is Urho3D PODVector type. function urho3d_is_podvector(t) return t:find("PODVector<") ~= nil end local old_get_push_function = get_push_function local old_get_to_function = get_to_function local old_get_is_function = get_is_function function get_push_function(t) if not urho3d_is_vector(t) then return old_get_push_function(t) end if not urho3d_is_podvector(t) then return "ToluaPushVector" .. t:match("<.*>") else return "ToluaPushPODVector" .. t:match("<.*>") end end function get_to_function(t) if not urho3d_is_vector(t) then return old_get_to_function(t) end if not urho3d_is_podvector(t) then return "ToluaToVector" .. t:match("<.*>") else return "ToluaToPODVector" .. t:match("<.*>") end end function get_is_function(t) if not urho3d_is_vector(t) then return old_get_is_function(t) end if not urho3d_is_podvector(t) then return "ToluaIsVector" .. t:match("<.*>") else return "ToluaIsPODVector" .. t:match("<.*>") end end function get_property_methods_hook(ptype, name) if ptype == "get_set" then local Name = string.upper(string.sub(name, 1, 1))..string.sub(name, 2) return "Get"..Name, "Set"..Name end if ptype == "is_set" then local Name = string.upper(string.sub(name, 1, 1))..string.sub(name, 2) return "Is"..Name, "Set"..Name end if ptype == "has_set" then local Name = string.upper(string.sub(name, 1, 1))..string.sub(name, 2) return "Has"..Name, "Set"..Name end if ptype == "no_prefix" then local Name = string.upper(string.sub(name, 1, 1))..string.sub(name, 2) return Name, "Set"..Name end end
Fix ToCpHook.lua when it is being used in external project.
Fix ToCpHook.lua when it is being used in external project.
Lua
mit
SuperWangKai/Urho3D,luveti/Urho3D,henu/Urho3D,bacsmar/Urho3D,299299/Urho3D,luveti/Urho3D,tommy3/Urho3D,rokups/Urho3D,codedash64/Urho3D,MonkeyFirst/Urho3D,c4augustus/Urho3D,orefkov/Urho3D,bacsmar/Urho3D,kostik1337/Urho3D,codedash64/Urho3D,kostik1337/Urho3D,bacsmar/Urho3D,kostik1337/Urho3D,weitjong/Urho3D,rokups/Urho3D,rokups/Urho3D,c4augustus/Urho3D,cosmy1/Urho3D,xiliu98/Urho3D,victorholt/Urho3D,xiliu98/Urho3D,SirNate0/Urho3D,iainmerrick/Urho3D,rokups/Urho3D,henu/Urho3D,helingping/Urho3D,helingping/Urho3D,luveti/Urho3D,eugeneko/Urho3D,eugeneko/Urho3D,MeshGeometry/Urho3D,abdllhbyrktr/Urho3D,helingping/Urho3D,weitjong/Urho3D,PredatorMF/Urho3D,cosmy1/Urho3D,weitjong/Urho3D,carnalis/Urho3D,abdllhbyrktr/Urho3D,fire/Urho3D-1,c4augustus/Urho3D,codedash64/Urho3D,SirNate0/Urho3D,MonkeyFirst/Urho3D,carnalis/Urho3D,tommy3/Urho3D,luveti/Urho3D,SuperWangKai/Urho3D,c4augustus/Urho3D,codemon66/Urho3D,kostik1337/Urho3D,299299/Urho3D,299299/Urho3D,orefkov/Urho3D,eugeneko/Urho3D,SuperWangKai/Urho3D,PredatorMF/Urho3D,urho3d/Urho3D,SirNate0/Urho3D,weitjong/Urho3D,codedash64/Urho3D,fire/Urho3D-1,tommy3/Urho3D,urho3d/Urho3D,carnalis/Urho3D,helingping/Urho3D,PredatorMF/Urho3D,xiliu98/Urho3D,abdllhbyrktr/Urho3D,urho3d/Urho3D,weitjong/Urho3D,orefkov/Urho3D,xiliu98/Urho3D,MeshGeometry/Urho3D,luveti/Urho3D,iainmerrick/Urho3D,victorholt/Urho3D,fire/Urho3D-1,SirNate0/Urho3D,tommy3/Urho3D,victorholt/Urho3D,MonkeyFirst/Urho3D,c4augustus/Urho3D,cosmy1/Urho3D,MonkeyFirst/Urho3D,victorholt/Urho3D,MeshGeometry/Urho3D,carnalis/Urho3D,henu/Urho3D,carnalis/Urho3D,codemon66/Urho3D,299299/Urho3D,cosmy1/Urho3D,cosmy1/Urho3D,codemon66/Urho3D,bacsmar/Urho3D,codemon66/Urho3D,fire/Urho3D-1,abdllhbyrktr/Urho3D,rokups/Urho3D,abdllhbyrktr/Urho3D,xiliu98/Urho3D,iainmerrick/Urho3D,codemon66/Urho3D,MeshGeometry/Urho3D,iainmerrick/Urho3D,henu/Urho3D,codedash64/Urho3D,fire/Urho3D-1,299299/Urho3D,orefkov/Urho3D,tommy3/Urho3D,MeshGeometry/Urho3D,MonkeyFirst/Urho3D,kostik1337/Urho3D,PredatorMF/Urho3D,victorholt/Urho3D,SuperWangKai/Urho3D,rokups/Urho3D,SirNate0/Urho3D,eugeneko/Urho3D,SuperWangKai/Urho3D,henu/Urho3D,helingping/Urho3D,iainmerrick/Urho3D,urho3d/Urho3D,299299/Urho3D
4139bb28eeb7d37258b8e77ed3f485a1d23152e1
test/rpc-handler_call_procedure-SET_COLOR.lua
test/rpc-handler_call_procedure-SET_COLOR.lua
package.path = "../?.lua;" .. package.path require 'busted.runner'() local match = require("luassert.match") describe("impl.rpc-handler", function() local qlua = require("qlua.api") local sut = require("impl.rpc-handler") describe("WHEN given a request of type ProcedureType.SET_COLOR", function() local request setup(function() request = {} request.type = qlua.RPC.ProcedureType.SET_COLOR end) teardown(function() request = nil end) insulate("WITH arguments", function() local request_args local proc_result setup(function() request_args = qlua.SetColor.Request() request_args.t_id = 42 request_args.row = 5 request_args.col = 7 request_args.b_color = 175 request_args.f_color = 201 request_args.sel_b_color = 40232 request_args.sel_f_color = 25999 request.args = request_args:SerializeToString() proc_result = true _G.SetColor = spy.new(function(red, green, blue) return proc_result end) end) teardown(function() request_args = nil proc_result = nil end) it("SHOULD call the global 'SetColor' function once, passing the procedure arguments to it", function() local response = sut.call_procedure(request.type, request.args) assert.spy(_G.SetColor).was.called_with(request_args.t_id, request_args.row, request_args.col, request_args.b_color, request_args.f_color, request_args.sel_b_color, request_args.sel_f_color) end) it("SHOULD return a qlua.SetColor.Result instance", function() local actual_result = sut.call_procedure(request.type, request) local expected_result = qlua.SetColor.Result() local actual_meta = getmetatable(actual_result) local expected_meta = getmetatable(expected_result) assert.are.equal(expected_meta, actual_meta) end) it("SHOULD return a protobuf object which string-serialized form equals to that of the expected result", function() local actual_result = sut.call_procedure(request.type, request) local expected_result = qlua.SetColor.Result() expected_result.result = proc_result assert.are.equal(expected_result:SerializeToString(), actual_result:SerializeToString()) end) end) describe("WITHOUT arguments", function() it("SHOULD raise an error", function() assert.has_error(function() sut.call_procedure(request.type) end, "The request has no arguments.") end) end) end) end)
package.path = "../?.lua;" .. package.path require 'busted.runner'() local match = require("luassert.match") describe("impl.rpc-handler", function() local qlua = require("qlua.api") local sut = require("impl.rpc-handler") describe("WHEN given a request of type ProcedureType.SET_COLOR", function() local request setup(function() request = {} request.type = qlua.RPC.ProcedureType.SET_COLOR end) teardown(function() request = nil end) insulate("WITH arguments", function() local request_args local proc_result setup(function() request_args = qlua.SetColor.Request() request_args.t_id = 42 request_args.row = 5 request_args.col = 7 request_args.b_color = 175 request_args.f_color = 201 request_args.sel_b_color = 40232 request_args.sel_f_color = 25999 request.args = request_args:SerializeToString() proc_result = true _G.SetColor = spy.new(function(t_id, row, col, b_color, f_color, sel_b_color, sel_f_color) return proc_result end) end) teardown(function() request_args = nil proc_result = nil end) it("SHOULD call the global 'SetColor' function once, passing the procedure arguments to it", function() local response = sut.call_procedure(request.type, request.args) assert.spy(_G.SetColor).was.called_with(request_args.t_id, request_args.row, request_args.col, request_args.b_color, request_args.f_color, request_args.sel_b_color, request_args.sel_f_color) end) it("SHOULD return a qlua.SetColor.Result instance", function() local actual_result = sut.call_procedure(request.type, request) local expected_result = qlua.SetColor.Result() local actual_meta = getmetatable(actual_result) local expected_meta = getmetatable(expected_result) assert.are.equal(expected_meta, actual_meta) end) it("SHOULD return a protobuf object which string-serialized form equals to that of the expected result", function() local actual_result = sut.call_procedure(request.type, request) local expected_result = qlua.SetColor.Result() expected_result.result = proc_result assert.are.equal(expected_result:SerializeToString(), actual_result:SerializeToString()) end) end) describe("WITHOUT arguments", function() it("SHOULD raise an error", function() assert.has_error(function() sut.call_procedure(request.type) end, "The request has no arguments.") end) end) end) end)
* fixed the target function's definition.
* fixed the target function's definition.
Lua
apache-2.0
Enfernuz/quik-lua-rpc,Enfernuz/quik-lua-rpc
ccff187723296ba9b1f694044b9fee227091126f
src/romdisk/samples/cairo/test/clip_image.lua
src/romdisk/samples/cairo/test/clip_image.lua
local M = {} function M.test() local cairo = require "org.xboot.cairo" local M_PI = math.pi local cs = cairo.image_surface_create(cairo.FORMAT_ARGB32, 400, 400) local cr = cairo.create(cs) cr:save() cr:set_source_rgb(0.9, 0.9, 0.9) cr:paint() cr:restore() cr:arc(128.0, 128.0, 76.8, 0, 2*M_PI); cr:clip(); cr:new_path(); local image = cairo.image_surface_create_from_png("/romdisk/system/media/image/battery/battery_8.png"); local w = image:get_width(); local h = image:get_height(); cr:scale(256.0/w, 256.0/h); -- cr:set_source_surface(image, 0, 0); --BUG(crash when sencond running), PLEASE FIXME cr:paint(); cs:show() collectgarbage("collect") collectgarbage("step") end return M
local M = {} function M.test() local cairo = require "org.xboot.cairo" local M_PI = math.pi local cs = cairo.image_surface_create(cairo.FORMAT_ARGB32, 400, 400) local cr = cairo.create(cs) local image = cairo.image_surface_create_from_png("/romdisk/system/media/image/battery/battery_8.png") local w = image:get_width() local h = image:get_height() cr:save() cr:set_source_rgb(0.9, 0.9, 0.9) cr:paint() cr:restore() cr:arc(128.0, 128.0, 76.8, 0, 2*M_PI) cr:clip() cr:new_path() cr:scale(100.0 / w, 100.0 / h) cr:set_source_surface(image, 100, 100); cr:paint(); cs:show() collectgarbage("collect") collectgarbage("step") end return M
fix clip_image.lua
fix clip_image.lua
Lua
mit
xboot/xboot,xboot/xboot
bdd23c7a44b8467e5d29a3ad1bdb476851d881ab
lua_modules/bourbon/lib/run.lua
lua_modules/bourbon/lib/run.lua
--[[ Copyright 2012 Rackspace 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 async = require 'async' local table = require 'table' local string = require 'string' local math = require 'math' local fmt = string.format local context = require './context' function is_test_key(k) return type(k) == "string" and k:match("_*test.*") end local function is_control_function(name) return name == 'setup' or name == 'teardown' or name == 'ssetup' or name == 'steardown' end local function get_tests(mod) local ts = {} if not mod then return ts end for k,v in pairs(mod) do if is_test_key(k) and type(v) == "function" then ts[k] = v end end ts.setup = rawget(mod, "setup") ts.teardown = rawget(mod, "teardown") ts.ssetup = rawget(mod, "suite_setup") ts.steardown = rawget(mod, "suite_teardown") return ts end local TestBaton = {} TestBaton.prototype = {} function TestBaton.new(runner, stats, callback) local tb = {} tb._callback = callback tb._stats = stats tb._runner = runner tb.done = function() stats:add_stats(runner.context) callback() end setmetatable(tb, {__index=TestBaton.prototype}) return tb end local run_test = function(runner, stats, callback) process.stdout:write(fmt("Running %s", runner.name)) local test_baton = TestBaton.new(runner, stats, function(err) process.stdout:write(" DONE\n") runner.context:dump_errors(function(line) process.stdout:write(line) end) callback(err) end) runner.context:run(runner.func, test_baton) end local run = function(options, mods, callback) if not mods then return end local runners = {} local ops = {} local stats = context:new() options = options or { print_summary = true, verbose = true } for k, v in pairs(get_tests(mods)) do if not is_control_function(k) then table.insert(runners, 1, { name = k, func = v, context = context:new() }) end end local function setup(callback) local test_baton = TestBaton.new({context = context:new()}, stats, callback) mods.setup(test_baton) end local function teardown(callback) local test_baton = TestBaton.new({context = context:new()}, stats, callback) mods.teardown(test_baton) end local function run_tests(callback) async.forEachSeries(runners, function(runner, callback) run_test(runner, stats, callback) end, callback) end if mods.setup then table.insert(ops, setup) end table.insert(ops, run_tests) if mods.teardown then table.insert(ops, teardown) end async.forEachSeries(ops, function(fun, callback) fun(callback) end, function(err) if err then process.stdout:write(err .. '\n') return end if options.print_summary then process.stdout:write('\nTotals' .. '\n') stats:print_summary() end if callback then callback(nil, stats) end end) end return run
--[[ Copyright 2012 Rackspace 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 async = require 'async' local table = require 'table' local string = require 'string' local math = require 'math' local Object = require 'object' local fmt = string.format local context = require './context' function is_test_key(k) return type(k) == "string" and k:match("_*test.*") end local function is_control_function(name) return name == 'setup' or name == 'teardown' or name == 'ssetup' or name == 'steardown' end local function get_tests(mod) local ts = {} if not mod then return ts end for k,v in pairs(mod) do if is_test_key(k) and type(v) == "function" then ts[k] = v end end ts.setup = rawget(mod, "setup") ts.teardown = rawget(mod, "teardown") ts.ssetup = rawget(mod, "suite_setup") ts.steardown = rawget(mod, "suite_teardown") return ts end local TestBaton = Object:extend() function TestBaton.prototype:initialize(runner, stats, callback) self._callback = callback self._stats = stats self._runner = runner self.done = function() stats:add_stats(runner.context) callback() end end local run_test = function(runner, stats, callback) process.stdout:write(fmt("Running %s", runner.name)) local test_baton = TestBaton:new(runner, stats, function(err) process.stdout:write(" DONE\n") runner.context:dump_errors(function(line) process.stdout:write(line) end) callback(err) end) runner.context:run(runner.func, test_baton) end local run = function(options, mods, callback) if not mods then return end local runners = {} local ops = {} local stats = context:new() options = options or { print_summary = true, verbose = true } for k, v in pairs(get_tests(mods)) do if not is_control_function(k) then table.insert(runners, 1, { name = k, func = v, context = context:new() }) end end local function setup(callback) local test_baton = TestBaton:new({context = context:new()}, stats, callback) mods.setup(test_baton) end local function teardown(callback) local test_baton = TestBaton:new({context = context:new()}, stats, callback) mods.teardown(test_baton) end local function run_tests(callback) async.forEachSeries(runners, function(runner, callback) run_test(runner, stats, callback) end, callback) end if mods.setup then table.insert(ops, setup) end table.insert(ops, run_tests) if mods.teardown then table.insert(ops, teardown) end async.forEachSeries(ops, function(fun, callback) fun(callback) end, function(err) if err then process.stdout:write(err .. '\n') return end if options.print_summary then process.stdout:write('\nTotals' .. '\n') stats:print_summary() end if callback then callback(nil, stats) end end) end return run
test fixes
test fixes
Lua
apache-2.0
kans/birgo,kans/birgo,kans/birgo,kans/birgo,kans/birgo
c81b98b33cf26f01fb1963daa974d0922ebdd2f9
empty-drills_0.0.1/styles/main.lua
empty-drills_0.0.1/styles/main.lua
--- Location view gui data.raw["gui-style"].default["lv_location_view"] = { type = "button_style", parent = "button_style", width = 100, height = 100, top_padding = 65, right_padding = 0, bottom_padding = 0, left_padding = 0, font = "font-mb", default_font_color = {r=0.98, g=0.66, b=0.22}, default_graphical_set = { type = "monolith", monolith_image = { filename = "location.png", priority = "extra-high-no-scale", width = 100, height = 100, x = 0 } }, hovered_graphical_set = { type = "monolith", monolith_image = { filename = "location-hover.png", priority = "extra-high-no-scale", width = 100, height = 100, x = 0 } }, clicked_graphical_set = { type = "monolith", monolith_image = { filename = "location-hover.png", width = 100, height = 100, x = 0 } } }
--- Location view gui data.raw["gui-style"].default["lv_location_view"] = { type = "button_style", parent = "button_style", width = 100, height = 100, top_padding = 65, right_padding = 0, bottom_padding = 0, left_padding = 0, font = "font-mb", default_font_color = {r=0.98, g=0.66, b=0.22}, default_graphical_set = { type = "monolith", monolith_image = { filename = "__empty-drills__/styles/location.png", priority = "extra-high-no-scale", width = 100, height = 100, x = 0 } }, hovered_graphical_set = { type = "monolith", monolith_image = { filename = "__empty-drills__/styles/location-hover.png", priority = "extra-high-no-scale", width = 100, height = 100, x = 0 } }, clicked_graphical_set = { type = "monolith", monolith_image = { filename = "__empty-drills__/styles/location-hover.png", width = 100, height = 100, x = 0 } } }
Fix empty drills bug because of moved resource location
Fix empty drills bug because of moved resource location
Lua
mit
Zomis/FactorioMods
613b35fc8d36918745868bde173e34bf78288b2b
src/patch/ui/hooks/joiningroom_enablemods.lua
src/patch/ui/hooks/joiningroom_enablemods.lua
if _mpPatch and _mpPatch.loaded then Modding = _mpPatch.hookTable(Modding, {ActivateAllowedDLC = function(...) _mpPatch.overrideModsFromPreGame() return Modding._super.ActivateAllowedDLC(...) end}) local function enterLobby() UIManager:QueuePopup(Controls.StagingRoomScreen, PopupPriority.StagingScreen) UIManager:DequeuePopup(ContextPtr) end local function joinFailed(message) Events.FrontEndPopup.CallImmediate(message) g_joinFailed = true Matchmaking.LeaveMultiplayerGame() UIManager:DequeuePopup(ContextPtr) end function OnConnectionCompete() if not Matchmaking.IsHost() then if _mpPatch.isModding then local missingModList = {} _mpPatch.debugPrint("Enabled mods for room:") for _, mod in ipairs(_mpPatch.decodeModsList()) do local missingText = "" if not Modding.IsModInstalled(mod.ID, mod.Version) then table.insert(missingModList, mod.Name) missingText = " (is missing)" end _mpPatch.debugPrint("- "..mod.Name..missingText) end -- TODO: Check for DLCs/mod compatibility if #missingModList > 0 then local messageTable = {Locale.Lookup("TXT_KEY_MPPATCH_MOD_MISSING")} for _, name in ipairs(missingModList) do table.insert(messageTable, "[ICON_BULLET]"..v.Name:gsub("%[", "("):gsub("%]", ")")) end joinFailed(table.concat(messageTable, "[NEWLINE]")) return end _mpPatch.debugPrint("Activating mods and DLC...") Modding.ActivateAllowedDLC() end enterLobby() end end end
if _mpPatch and _mpPatch.loaded then Modding = _mpPatch.hookTable(Modding, {ActivateAllowedDLC = function(...) _mpPatch.overrideModsFromPreGame() return Modding._super.ActivateAllowedDLC(...) end}) local function enterLobby() UIManager:QueuePopup(Controls.StagingRoomScreen, PopupPriority.StagingScreen) UIManager:DequeuePopup(ContextPtr) end local function joinFailed(message) Events.FrontEndPopup.CallImmediate(message) g_joinFailed = true Matchmaking.LeaveMultiplayerGame() UIManager:DequeuePopup(ContextPtr) end function OnConnectionCompete() if not Matchmaking.IsHost() then if _mpPatch.isModding then local missingModList = {} _mpPatch.debugPrint("Enabled mods for room:") for _, mod in ipairs(_mpPatch.decodeModsList()) do local missingText = "" if not Modding.IsModInstalled(mod.ID, mod.Version) then table.insert(missingModList, mod.Name) missingText = " (is missing)" end _mpPatch.debugPrint("==DEBUG==", mod.ID, mod.Version, mod.Name) _mpPatch.debugPrint("- "..mod.Name..missingText) end -- TODO: Check for DLCs/mod compatibility if #missingModList > 0 then local messageTable = {Locale.Lookup("TXT_KEY_MPPATCH_MOD_MISSING")} for _, name in ipairs(missingModList) do table.insert(messageTable, "[ICON_BULLET]"..name:gsub("%[", "("):gsub("%]", ")")) end joinFailed(table.concat(messageTable, "[NEWLINE]")) return end _mpPatch.debugPrint("Activating mods and DLC...") Modding.ActivateAllowedDLC() end enterLobby() end end end
Fix more joiningroom issues.
Fix more joiningroom issues.
Lua
mit
Lymia/MPPatch,Lymia/MPPatch,Lymia/MultiverseModManager,Lymia/MPPatch,Lymia/MPPatch,Lymia/MultiverseModManager,Lymia/CivV_Mod2DLC
da870ca15cdd2c48bf4ef1af21fae16b96a862ce
dialog.lua
dialog.lua
require "widget" require "font" InfoMessage = { face = Font:getFace("infofont", 25) } function InfoMessage:show(text,refresh_mode) print("# InfoMessage ", text, refresh_mode) local dialog = CenterContainer:new({ dimen = { w = G_width, h = G_height }, FrameContainer:new({ margin = 2, background = 0, HorizontalGroup:new({ align = "center", ImageWidget:new({ file = "resources/info-i.png" }), Widget:new({ dimen = { w = 10, h = 0 } }), TextWidget:new({ text = text, face = Font:getFace("cfont", 30) }) }) }) }) dialog:paintTo(fb.bb, 0, 0) dialog:free() if refresh_mode ~= nil then fb:refresh(refresh_mode) end end function showInfoMsgWithDelay(text, msec, refresh_mode) if not refresh_mode then refresh_mode = 0 end Screen:saveCurrentBB() InfoMessage:show(text) fb:refresh(refresh_mode) -- util.usleep(msec*1000) input.waitForEvent(msec*1000) Screen:restoreFromSavedBB() fb:refresh(refresh_mode) end
require "widget" require "font" InfoMessage = { face = Font:getFace("infofont", 25) } function InfoMessage:show(text,refresh_mode) print("# InfoMessage ", text, refresh_mode) local dialog = CenterContainer:new({ dimen = { w = G_width, h = G_height }, FrameContainer:new({ margin = 2, background = 0, HorizontalGroup:new({ align = "center", ImageWidget:new({ file = "resources/info-i.png" }), Widget:new({ dimen = { w = 10, h = 0 } }), TextWidget:new({ text = text, face = Font:getFace("cfont", 30) }) }) }) }) dialog:paintTo(fb.bb, 0, 0) dialog:free() if refresh_mode ~= nil then fb:refresh(refresh_mode) end end function showInfoMsgWithDelay(text, msec, refresh_mode) if not refresh_mode then refresh_mode = 0 end Screen:saveCurrentBB() InfoMessage:show(text) fb:refresh(refresh_mode) -- util.usleep(msec*1000) -- eat the first key release event local ev = input.waitForEvent() adjustKeyEvents(ev) repeat ok = pcall( function() ev = input.waitForEvent(msec*1000) adjustKeyEvents(ev) end) print(is_not_timeout) until not ok or ev.value == EVENT_VALUE_KEY_PRESS Screen:restoreFromSavedBB() fb:refresh(refresh_mode) end
fix bug in showInfoMsgWithDelay()
fix bug in showInfoMsgWithDelay() The release key event will cause the dialog disappear immediately after show up. Also the timeout error is handled with pcall.
Lua
agpl-3.0
houqp/koreader,chihyang/koreader,Frenzie/koreader-base,apletnev/koreader-base,NiLuJe/koreader-base,noname007/koreader,chrox/koreader,houqp/koreader-base,koreader/koreader-base,frankyifei/koreader,frankyifei/koreader-base,koreader/koreader-base,Hzj-jie/koreader,NickSavage/koreader,NiLuJe/koreader,pazos/koreader,apletnev/koreader,koreader/koreader-base,houqp/koreader-base,Hzj-jie/koreader-base,Frenzie/koreader,NiLuJe/koreader-base,mihailim/koreader,koreader/koreader,ashhher3/koreader,NiLuJe/koreader-base,ashang/koreader,Hzj-jie/koreader-base,Hzj-jie/koreader-base,Frenzie/koreader-base,poire-z/koreader,frankyifei/koreader-base,NiLuJe/koreader-base,houqp/koreader-base,Hzj-jie/koreader-base,robert00s/koreader,apletnev/koreader-base,Frenzie/koreader-base,mwoz123/koreader,koreader/koreader-base,apletnev/koreader-base,Markismus/koreader,apletnev/koreader-base,frankyifei/koreader-base,frankyifei/koreader-base,NiLuJe/koreader,Frenzie/koreader,lgeek/koreader,koreader/koreader,houqp/koreader-base,Frenzie/koreader-base,poire-z/koreader
905d16e64baa1883b7def5ce659667689897e766
neovim/lua/plugins/nvim-lspconfig/init.lua
neovim/lua/plugins/nvim-lspconfig/init.lua
local is_present_lsp_config, lsp_config = pcall(require, "lspconfig") local is_present_lsp_inst, lsp_install = pcall(require, "lspinstall") local is_present_coq, coq = pcall(require, "coq") if not (is_present_lsp_config or is_present_lsp_inst or is_present_coq) then error("Error loading " .. "\n\n" .. lsp_config .. lsp_install .. coq) return end -- Use an on_attach function to only map the following keys -- after the language server attaches to the current buffer local on_attach = function(client, bufnr) -- setup illuminate require("illuminate").on_attach(client) local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end -- Enable completion triggered by <c-x><c-o> buf_set_option("omnifunc", "v:lua.vim.lsp.omnifunc") -- Mappings. local opts = { noremap = true, silent = true } -- See `:help vim.lsp.*` for documentation on any of the below functions buf_set_keymap("n", "gD", "<cmd>lua vim.lsp.buf.declaration()<CR>", opts) buf_set_keymap("n", "gd", "<cmd>lua vim.lsp.buf.definition()<CR>", opts) buf_set_keymap("n", "K", "<cmd>lua vim.lsp.buf.hover()<CR>", opts) buf_set_keymap("n", "gi", "<cmd>lua vim.lsp.buf.implementation()<CR>", opts) buf_set_keymap("n", "<C-k>", "<cmd>lua vim.lsp.buf.signature_help()<CR>", opts) buf_set_keymap("n", "<space>wa", "<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>", opts) buf_set_keymap("n", "<space>wr", "<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>", opts) buf_set_keymap("n", "<space>wl", "<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>", opts) buf_set_keymap("n", "<space>D", "<cmd>lua vim.lsp.buf.type_definition()<CR>", opts) buf_set_keymap("n", "<space>rn", "<cmd>lua vim.lsp.buf.rename()<CR>", opts) buf_set_keymap("n", "<space>ca", "<cmd>lua vim.lsp.buf.code_action()<CR>", opts) buf_set_keymap("n", "gr", "<cmd>lua vim.lsp.buf.references()<CR>", opts) buf_set_keymap("n", "<space>e", "<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>", opts) buf_set_keymap("n", "[d", "<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>", opts) buf_set_keymap("n", "]d", "<cmd>lua vim.lsp.diagnostic.goto_next()<CR>", opts) buf_set_keymap("n", "<space>q", "<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>", opts) buf_set_keymap("n", "<space>f", "<cmd>lua vim.lsp.buf.formatting()<CR>", opts) if client.resolved_capabilities.document_formatting then vim.cmd("autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()") end end -- Use a loop to conveniently call 'setup' on multiple servers and -- map buffer local keybindings when the language server attaches local function setup_servers() lsp_install.setup() local servers = lsp_install.installed_servers() for _, lsp in ipairs(servers) do lsp_config[lsp].setup({ coq.lsp_ensure_capabilities({ on_attach = on_attach, flags = { debounce_text_changes = 150, }, }), }) end end local pyright_config = require("lspinstall/util").extract_config("pyright") pyright_config.default_config.cmd = { "/Users/lucas.rondenet/.nvm/versions/node/v12.18.4/bin/node", "/Users/lucas.rondenet/.local/share/nvim/lspinstall/python/./node_modules/.bin/pyright-langserver", "--stdio", } require("lspinstall/servers").python = vim.tbl_extend("error", pyright_config, {}) local bash_config = require("lspinstall/util").extract_config("bashls") bash_config.default_config.cmd = { "/Users/lucas.rondenet/.nvm/versions/node/v12.18.4/bin/node", "/Users/lucas.rondenet/.local/share/nvim/lspinstall/bash/node_modules/./.bin/bash-language-server", "start", } require("lspinstall/servers").bash = vim.tbl_extend("error", bash_config, {}) setup_servers() -- Automatically reload after `:LspInstall <server>` so we don't have to restart neovim lsp_install.post_install_hook = function() setup_servers() -- reload installed servers vim.cmd("bufdo e") -- this triggers the FileType autocmd that starts the server end require("plugins/null-ls").setup(on_attach)
local is_present_lsp_config, lsp_config = pcall(require, "lspconfig") local is_present_lsp_inst, lsp_install = pcall(require, "lspinstall") local is_present_coq, coq = pcall(require, "coq") if not (is_present_lsp_config or is_present_lsp_inst or is_present_coq) then error("Error loading " .. "\n\n" .. lsp_config .. lsp_install .. coq) return end -- Use an on_attach function to only map the following keys -- after the language server attaches to the current buffer local on_attach = function(client, bufnr) -- setup illuminate require("illuminate").on_attach(client) local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end -- Enable completion triggered by <c-x><c-o> buf_set_option("omnifunc", "v:lua.vim.lsp.omnifunc") -- Mappings. local opts = { noremap = true, silent = true } -- See `:help vim.lsp.*` for documentation on any of the below functions buf_set_keymap("n", "gD", "<cmd>lua vim.lsp.buf.declaration()<CR>", opts) buf_set_keymap("n", "gd", "<cmd>lua vim.lsp.buf.definition()<CR>", opts) buf_set_keymap("n", "K", "<cmd>lua vim.lsp.buf.hover()<CR>", opts) buf_set_keymap("n", "gi", "<cmd>lua vim.lsp.buf.implementation()<CR>", opts) --buf_set_keymap("n", "<C-k>", "<cmd>lua vim.lsp.buf.signature_help()<CR>", opts) buf_set_keymap("n", "<space>wa", "<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>", opts) buf_set_keymap("n", "<space>wr", "<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>", opts) buf_set_keymap("n", "<space>wl", "<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>", opts) buf_set_keymap("n", "<space>D", "<cmd>lua vim.lsp.buf.type_definition()<CR>", opts) buf_set_keymap("n", "<space>rn", "<cmd>lua vim.lsp.buf.rename()<CR>", opts) buf_set_keymap("n", "<space>ca", "<cmd>lua vim.lsp.buf.code_action()<CR>", opts) buf_set_keymap("n", "gr", "<cmd>lua vim.lsp.buf.references()<CR>", opts) buf_set_keymap("n", "<space>e", "<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>", opts) buf_set_keymap("n", "[d", "<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>", opts) buf_set_keymap("n", "]d", "<cmd>lua vim.lsp.diagnostic.goto_next()<CR>", opts) buf_set_keymap("n", "<space>q", "<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>", opts) buf_set_keymap("n", "<space>f", "<cmd>lua vim.lsp.buf.formatting()<CR>", opts) --if client.resolved_capabilities.document_formatting then -- vim.cmd("autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()") --end end -- Use a loop to conveniently call 'setup' on multiple servers and -- map buffer local keybindings when the language server attaches local function setup_servers() lsp_install.setup() local servers = lsp_install.installed_servers() for _, lsp in ipairs(servers) do lsp_config[lsp].setup({ coq.lsp_ensure_capabilities({ on_attach = on_attach, flags = { debounce_text_changes = 150, }, }), }) end end local pyright_config = require("lspinstall/util").extract_config("pyright") pyright_config.default_config.cmd = { "/Users/lucas.rondenet/.nvm/versions/node/v12.18.4/bin/node", "/Users/lucas.rondenet/.local/share/nvim/lspinstall/python/./node_modules/.bin/pyright-langserver", "--stdio", } require("lspinstall/servers").python = vim.tbl_extend("error", pyright_config, {}) local bash_config = require("lspinstall/util").extract_config("bashls") bash_config.default_config.cmd = { "/Users/lucas.rondenet/.nvm/versions/node/v12.18.4/bin/node", "/Users/lucas.rondenet/.local/share/nvim/lspinstall/bash/node_modules/./.bin/bash-language-server", "start", } require("lspinstall/servers").bash = vim.tbl_extend("error", bash_config, {}) local lua_config = require("lspinstall/util").extract_config("sumneko_lua") local lua_settings = { Lua = { runtime = { -- LuaJIT in the case of Neovim version = 'LuaJIT', path = vim.split(package.path, ';'), }, diagnostics = { -- Get the language server to recognize the `vim` global globals = {'vim'}, }, workspace = { -- Make the server aware of Neovim runtime files library = { [vim.fn.expand('$VIMRUNTIME/lua')] = true, [vim.fn.expand('$VIMRUNTIME/lua/vim/lsp')] = true, }, }, } } lua_config.default_config.settings = lua_settings lua_config.default_config.cmd = { "./sumneko-lua-language-server" } require("lspinstall/servers").lua = vim.tbl_extend("error", lua_config, {}) setup_servers() -- Automatically reload after `:LspInstall <server>` so we don't have to restart neovim lsp_install.post_install_hook = function() setup_servers() -- reload installed servers vim.cmd("bufdo e") -- this triggers the FileType autocmd that starts the server end require("plugins/null-ls").setup(on_attach)
remove autoformat, fix lsp lua vim global
remove autoformat, fix lsp lua vim global
Lua
mit
rucas/derpfiles,rucas/derpfiles,rucas/derpfiles
af8bc6d307756bf376b7059f50ccf92732f15c2a
packages/dok/search.lua
packages/dok/search.lua
-------------------------------------------------------------------------------- -- search in help -- that file defines all the tools and goodies to allow search -------------------------------------------------------------------------------- local entries = {} paths.install_dok = paths.concat(paths.install_html, '..', 'dok') paths.install_dokmedia = paths.concat(paths.install_html, '..', 'dokmedia') local function html2entries(html, package, file) local next = html:gfind('<div.->\n<h%d><a.->%s+(.-)%s+</a></h%d><a.-></a>\n<a name="(.-)"></a>\n(.-)</div>') for title,link,body in next do link = package .. '/' .. file:gsub('.txt','.html') .. '#' .. link body = body:gsub('<img.->','') entries.global = entries.global or {} table.insert(entries.global, {title, link, body}) entries[package] = entries[package] or {} table.insert(entries[package], {title, '../' .. link, body}) end return entries end local function install(entries, dir) local vars = {} for i,entry in ipairs(entries) do table.insert(vars, 's[' .. (i-1) .. '] = "' .. table.concat(entry, '^'):gsub('"','\\"'):gsub('\n',' ') .. '";') end local array = table.concat(vars, '\n') local f = paths.concat(paths.install_html, paths.basename(dir), 'jse_form.js') if paths.filep(f) then local js = io.open(f):read('*all') js = js:gsub('// SEARCH_ARRAY //', array) local w = io.open(f,'w') w:write(js) w:close() end end function dok.installsearch() for package in paths.files(paths.install_dok) do if package ~= '.' and package ~= '..' then local dir = paths.concat(paths.install_dok, package) for file in paths.files(dir) do if file ~= '.' and file ~= '..' then local path = paths.concat(dir, file) local f = io.open(path) if f then local content = f:read('*all') local html = dok.dok2html(content) local entries = html2entries(html, package, file) end end end end end for package,entries in pairs(entries) do print('installing search for package: ' .. package) if package == 'global' then package = '.' end install(entries, package) end end
-------------------------------------------------------------------------------- -- search in help -- that file defines all the tools and goodies to allow search -------------------------------------------------------------------------------- local entries = {} paths.install_dok = paths.concat(paths.install_html, '..', 'dok') paths.install_dokmedia = paths.concat(paths.install_html, '..', 'dokmedia') local function html2entries(html, package, file) local dnext = html:gfind('<div.->(.-)</div>') for div in dnext do local next = div:gfind('<h%d><a.->%s+(.-)%s+</a></h%d><a.-></a>\n<a name="(.-)"></a>\n(.-)$') for title,link,body in next do link = package .. '/' .. file:gsub('.txt','.html') .. '#' .. link body = body:gsub('<img.->','') entries.global = entries.global or {} table.insert(entries.global, {title, link, body}) entries[package] = entries[package] or {} table.insert(entries[package], {title, '../' .. link, body}) end end return entries end local function install(entries, dir) local vars = {} for i,entry in ipairs(entries) do table.insert(vars, 's[' .. (i-1) .. '] = "' .. table.concat(entry, '^'):gsub('"','\\"'):gsub('\n',' ') .. '";') end local array = table.concat(vars, '\n') local f = paths.concat(paths.install_html, paths.basename(dir), 'jse_form.js') if paths.filep(f) then local js = io.open(f):read('*all') js = js:gsub('// SEARCH_ARRAY //', array) local w = io.open(f,'w') w:write(js) w:close() end end function dok.installsearch() print('-- parsing dok files to build search index') for package in paths.files(paths.install_dok) do if package ~= '.' and package ~= '..' then local dir = paths.concat(paths.install_dok, package) for file in paths.files(dir) do if file ~= '.' and file ~= '..' then print('-+ parsing file: ' .. paths.concat(dir,file)) local path = paths.concat(dir, file) local f = io.open(path) if f then local content = f:read('*all') local html = dok.dok2html(content) local entries = html2entries(html, package, file) end end end end end for package,entries in pairs(entries) do print('-+ installing search for package: ' .. package) if package == 'global' then package = '.' end install(entries, package) end end
Fixed painful help parser.
Fixed painful help parser.
Lua
bsd-3-clause
soumith/TH,soumith/TH,soumith/TH,soumith/TH
b1a1f1dd6c0d3781097736c07107262722dbeffe
durden/menus/target/clipboard.lua
durden/menus/target/clipboard.lua
local function pastefun(wnd, msg) local dst = wnd.clipboard_out; if (not dst) then local dst = alloc_surface(1, 1); -- this approach triggers an interesting bug that may be worthwhile to explore -- wnd.clipboard_out = define_recordtarget(alloc_surface(1, 1), -- wnd.external, "", {null_surface(1,1)}, {}, -- RENDERTARGET_DETACH, RENDERTARGET_NOSCALE, 0, function() -- end); wnd.clipboard_out = define_nulltarget(wnd.external, "clipboard", function(source, status) if (status.kind == "terminated") then delete_image(source); wnd.clipboard_out = nil; end end); link_image(wnd.clipboard_out, wnd.anchor); end msg = wnd.pastefilter ~= nil and wnd.pastefilter(msg) or msg; if (msg and string.len(msg) > 0) then target_input(wnd.clipboard_out, msg); end end local function clipboard_paste() local wnd = active_display().selected; pastefun(wnd, CLIPBOARD.globals[1]); end local function clipboard_paste_local() local wnd = active_display().selected; pastefun(wnd, CLIPBOARD:list_local(wnd.clipboard)[1]); end local function clipboard_histgen(wnd, lst, promote) local res = {}; for k, v in ipairs(lst) do local short = string.shorten(v, 20); table.insert(res, { name = "hist_" .. tostring(k), description = v, label = string.format("%d:%s", k, short), kind = "action", format = suppl_strcol_fmt(short, false), select_format = suppl_strcol_fmt(short, true), handler = function() if (promote) then CLIPBOARD:set_global(v); else local m1, m2 = dispatch_meta(); pastefun(wnd, v); end end }); end return res; end local function clipboard_local_history() local wnd = active_display().selected; return clipboard_histgen(wnd, CLIPBOARD:list_local(wnd.clipboard)); end local function clipboard_history() return clipboard_histgen(active_display().selected, CLIPBOARD.globals); end local function clipboard_urls() local res = {}; for k,v in ipairs(CLIPBOARD.urls) do table.insert(res, { name = "url_" .. tostring(k), label = string.shorten(url, 20), description = url, fmt = suppl_strcol_fmt(short, false), select_fmt = suppl_strcol_fmt(short, true), kind = "action", handler = function() local m1, m2 = dispatch_meta(); pastefun(active_display().selected, v); end }); end return res; end return { { name = "paste", label = "Paste", kind = "action", description = "Paste the current entry from the global clipboard", eval = function() return valid_vid( active_display().selected.external, TYPE_FRAMESERVER); end, handler = clipboard_paste }, { name = "lpaste", label = "Paste-Local", kind = "action", description = "Paste the current entry from the local clipboard", eval = function() return valid_vid( active_display().selected.external, TYPE_FRAMESERVER); end, handler = clipboard_paste_local }, { name = "lhist", label = "History-Local", kind = "action", description = "Enumerate the local clipboard history", eval = function() local wnd = active_display().selected; return wnd.clipboard ~= nil and #CLIPBOARD:list_local(wnd.clipboard) > 0; end, submenu = true, handler = function() local wnd = active_display().selected; return clipboard_histgen(wnd, CLIPBOARD:list_local(wnd.clipboard)); end }, { name = "lhistprom", label = "Promote", kind = "action", description = "Promote an entry from the local clipboard to the global shared one", eval = function() local wnd = active_display().selected; return wnd.clipboard ~= nil and #CLIPBOARD:list_local(wnd.clipboard) > 0; end, submenu = true, handler = function() local wnd = active_display().selected; return clipboard_histgen(wnd, CLIPBOARD:list_local(wnd.clipboard), true); end }, { name = "hist", label = "History", description = "Select an entry from the global history", kind = "action", submenu = true, eval = function() return valid_vid( active_display().selected.external, TYPE_FRAMESERVER); end, handler = clipboard_history }, { name = "url", label = "URLs", kind = "action", description = "Select an entry from the URL catcher", submenu = true, eval = function() return valid_vid( active_display().selected.external, TYPE_FRAMESERVER) and #CLIPBOARD.urls > 0; end, handler = clipboard_urls }, { name = "mode", label = "Mode", kind = "value", description = "Change the preprocess filter that will be applied before pasting", initial = function() local wnd = active_display().selected; return wnd.pastemode and wnd.pastemode or ""; end, set = CLIPBOARD:pastemodes(), handler = function(ctx, val) local wnd = active_display().selected; local f, l = CLIPBOARD:pastemodes(val); wnd.pastemode = l; wnd.pastefilter = f; end } }
local function pastefun(wnd, msg) local dst = wnd.clipboard_out; if (not dst) then local dst = alloc_surface(1, 1); -- this approach triggers an interesting bug that may be worthwhile to explore -- wnd.clipboard_out = define_recordtarget(alloc_surface(1, 1), -- wnd.external, "", {null_surface(1,1)}, {}, -- RENDERTARGET_DETACH, RENDERTARGET_NOSCALE, 0, function() -- end); wnd.clipboard_out = define_nulltarget(wnd.external, "clipboard", function(source, status) if (status.kind == "terminated") then delete_image(source); wnd.clipboard_out = nil; end end); link_image(wnd.clipboard_out, wnd.anchor); end msg = wnd.pastefilter ~= nil and wnd.pastefilter(msg) or msg; if (msg and string.len(msg) > 0) then target_input(wnd.clipboard_out, msg); end end local function clipboard_paste() local wnd = active_display().selected; pastefun(wnd, CLIPBOARD.globals[1]); end local function clipboard_paste_local() local wnd = active_display().selected; pastefun(wnd, CLIPBOARD:list_local(wnd.clipboard)[1]); end local function clipboard_histgen(wnd, lst, promote) local res = {}; for k, v in ipairs(lst) do local short = string.shorten(v, 20); table.insert(res, { name = "hist_" .. tostring(k), description = v, label = string.format("%d:%s", k, short), kind = "action", format = suppl_strcol_fmt(short, false), select_format = suppl_strcol_fmt(short, true), handler = function() if (promote) then CLIPBOARD:set_global(v); else local m1, m2 = dispatch_meta(); pastefun(wnd, v); end end }); end return res; end local function clipboard_local_history() local wnd = active_display().selected; return clipboard_histgen(wnd, CLIPBOARD:list_local(wnd.clipboard)); end local function clipboard_history() return clipboard_histgen(active_display().selected, CLIPBOARD.globals); end local function clipboard_urls() local res = {}; for k,v in ipairs(CLIPBOARD.urls) do local short = string.shorten(v, 20); table.insert(res, { name = "url_" .. tostring(k), label = short, description = v, fmt = suppl_strcol_fmt(short, false), select_fmt = suppl_strcol_fmt(short, true), kind = "action", handler = function() local m1, m2 = dispatch_meta(); pastefun(active_display().selected, v); end }); end return res; end return { { name = "paste", label = "Paste", kind = "action", description = "Paste the current entry from the global clipboard", eval = function() return valid_vid( active_display().selected.external, TYPE_FRAMESERVER); end, handler = clipboard_paste }, { name = "lpaste", label = "Paste-Local", kind = "action", description = "Paste the current entry from the local clipboard", eval = function() return valid_vid( active_display().selected.external, TYPE_FRAMESERVER); end, handler = clipboard_paste_local }, { name = "lhist", label = "History-Local", kind = "action", description = "Enumerate the local clipboard history", eval = function() local wnd = active_display().selected; return wnd.clipboard ~= nil and #CLIPBOARD:list_local(wnd.clipboard) > 0; end, submenu = true, handler = function() local wnd = active_display().selected; return clipboard_histgen(wnd, CLIPBOARD:list_local(wnd.clipboard)); end }, { name = "lhistprom", label = "Promote", kind = "action", description = "Promote an entry from the local clipboard to the global shared one", eval = function() local wnd = active_display().selected; return wnd.clipboard ~= nil and #CLIPBOARD:list_local(wnd.clipboard) > 0; end, submenu = true, handler = function() local wnd = active_display().selected; return clipboard_histgen(wnd, CLIPBOARD:list_local(wnd.clipboard), true); end }, { name = "hist", label = "History", description = "Select an entry from the global history", kind = "action", submenu = true, eval = function() return valid_vid( active_display().selected.external, TYPE_FRAMESERVER); end, handler = clipboard_history }, { name = "url", label = "URLs", kind = "action", description = "Select an entry from the URL catcher", submenu = true, eval = function() return valid_vid( active_display().selected.external, TYPE_FRAMESERVER) and #CLIPBOARD.urls > 0; end, handler = clipboard_urls }, { name = "mode", label = "Mode", kind = "value", description = "Change the preprocess filter that will be applied before pasting", initial = function() local wnd = active_display().selected; return wnd.pastemode and wnd.pastemode or ""; end, set = CLIPBOARD:pastemodes(), handler = function(ctx, val) local wnd = active_display().selected; local f, l = CLIPBOARD:pastemodes(val); wnd.pastemode = l; wnd.pastefilter = f; end } }
clipboard - target/url fix
clipboard - target/url fix fields were wrong/broken after refactoring a while back.
Lua
bsd-3-clause
letoram/durden
677e5ee08e5549df8732b64eaa2462b64a111693
MMOCoreORB/bin/scripts/crafting/objects/draftschematics/artisan/noviceArtisan/survivalKnife.lua
MMOCoreORB/bin/scripts/crafting/objects/draftschematics/artisan/noviceArtisan/survivalKnife.lua
--Copyright (C) 2009 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --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 Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. survivalKnife = Object:new { objectName = "Survival Knife", stfName = "knife_survival", objectCRC = 1433859593, groupName = "craftArtisanNewbieGroupA", -- Group schematic is awarded in (See skills table) craftingToolTab = 1, -- (See DraftSchemticImplementation.h) complexity = 3, size = 1, xpType = "crafting_general", xp = 28, assemblySkill = "general_assembly", experimentingSkill = "general_experimentation", ingredientTemplateNames = "craft_weapon_ingredients_n, craft_weapon_ingredients_n, craft_weapon_ingredients_n, craft_weapon_ingredients_n", ingredientTitleNames = "knife_shaft, cutting_edge, grip_cap, grip", ingredientSlotType = "0, 0, 0, 0", resourceTypes = "metal, metal, metal, mineral", resourceQuantities = "6, 4, 2, 2", combineTypes = "0, 0, 0, 0", contribution = "100, 100, 100, 100", numberExperimentalProperties = "1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1", experimentalProperties = "XX, XX, SR, SR, SR, SR, SR, SR, SR, XX, SR, XX, SR, SR, SR", experimentalWeights = "1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1", experimentalGroupTitles = "null, null, expDamage, expDamage, expDamage, expDamage, exp_durability, expRange, expRange, null, expRange, null, expEffeciency, expEffeciency, expEffeciency", experimentalSubGroupTitles = "null, null, mindamage, maxdamage, attackspeed, woundchance, hitpoints, zerorangemod, maxrangemod, midrange, midrangemod, maxrange, attackhealthcost, attackactioncost, attackmindcost", experimentalMin = "0, 0, 14, 28, 4.2, 5, 750, 21, 21, 3, 21, 4, 9, 29, 7", experimentalMax = "0, 0, 26, 52, 2.9, 11, 1500, 39, 39, 3, 39, 1482184792, 5, 15, 4", experimentalPrecision = "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0", tanoAttributes = "objecttype=131073:objectcrc=530531036:objecttemp=knife_survival:templatetype=weapon_name:itemmask=65535::", customizationOptions = "", customizationDefaults = "", customizationSkill = "clothing_customization" } DraftSchematics:addDraftSchematic(survivalKnife, 1433859593)--- Add to global DraftSchematics table
--Copyright (C) 2009 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --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 Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. survivalKnife = Object:new { objectName = "Survival Knife", stfName = "knife_survival", objectCRC = 1433859593, groupName = "craftArtisanNewbieGroupA", -- Group schematic is awarded in (See skills table) craftingToolTab = 1, -- (See DraftSchemticImplementation.h) complexity = 3, size = 1, xpType = "crafting_general", xp = 28, assemblySkill = "general_assembly", experimentingSkill = "general_experimentation", ingredientTemplateNames = "craft_weapon_ingredients_n, craft_weapon_ingredients_n, craft_weapon_ingredients_n, craft_weapon_ingredients_n", ingredientTitleNames = "knife_shaft, cutting_edge, grip_cap, grip", ingredientSlotType = "0, 0, 0, 0", resourceTypes = "metal, metal, metal, mineral", resourceQuantities = "6, 4, 2, 2", combineTypes = "0, 0, 0, 0", contribution = "100, 100, 100, 100", numberExperimentalProperties = "1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1", experimentalProperties = "XX, XX, SR, SR, SR, SR, SR, SR, SR, XX, SR, XX, SR, SR, SR", experimentalWeights = "1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1", experimentalGroupTitles = "null, null, expDamage, expDamage, expDamage, expDamage, exp_durability, expRange, expRange, null, expRange, null, expEffeciency, expEffeciency, expEffeciency", experimentalSubGroupTitles = "null, null, mindamage, maxdamage, attackspeed, woundchance, hitpoints, zerorangemod, maxrangemod, midrange, midrangemod, maxrange, attackhealthcost, attackactioncost, attackmindcost", experimentalMin = "0, 0, 14, 28, 4.2, 5, 750, 21, 21, 3, 21, 4, 9, 29, 7", experimentalMax = "0, 0, 26, 52, 2.9, 11, 1500, 39, 39, 3, 39, 4, 5, 15, 4", experimentalPrecision = "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0", tanoAttributes = "objecttype=131073:objectcrc=530531036:objecttemp=knife_survival:templatetype=weapon_name:itemmask=65535:customattributes=damagetype=1;:", customizationOptions = "", customizationDefaults = "", customizationSkill = "clothing_customization" } DraftSchematics:addDraftSchematic(survivalKnife, 1433859593)--- Add to global DraftSchematics table
[fixed] messed up schematic
[fixed] messed up schematic git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@1255 c3d1530f-68f5-4bd0-87dc-8ef779617e40
Lua
agpl-3.0
lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
00ece41b2e89d197d1ed6169cdb668c92d088d36
extensions/window/test_window.lua
extensions/window/test_window.lua
require("hs.timer") function testAllWindows() hs.openConsole() hs.openPreferences() local allWindows = hs.window.allWindows() assertIsEqual("table", type(allWindows)) assertGreaterThan(1, #allWindows) -- Enable this when hs.window objects have a proper __type metatable entry -- assertIsUserdataOfType(allWindows[1], "hs.window") hs.closePreferences() hs.closeConsole() return success() end function testDesktop() local desktop = hs.window.desktop() assertIsNotNil(desktop) assertIsEqual("AXScrollArea", desktop:role()) return success() end function testOrderedWindows() hs.openConsole() -- Make sure we have at least one window hs.openPreferences() local orderedWindows = hs.window.orderedWindows() assertIsEqual("table", type(orderedWindows)) assertGreaterThan(1, #orderedWindows) return success() end function testFocusedWindow() hs.openConsole() local win = hs.window.focusedWindow() assertIsUserdataOfType("hs.window", win) return success() end function testSnapshots() hs.openConsole() local win = hs.window.focusedWindow() local id = win:id() assertIsNumber(id) assertGreaterThan(0, id) assertIsUserdataOfType("hs.image", hs.window.snapshotForID(id)) assertIsUserdataOfType("hs.image", win:snapshot()) return success() end function testTitle() hs.openConsole() local win = hs.window.focusedWindow() local title = win:title() assertIsString(title) assertIsEqual("Hammerspoon Console", win:title()) assertIsString(tostring(win)) return success() end function testRoles() hs.openConsole() local win = hs.window.focusedWindow() assertIsEqual("AXWindow", win:role()) assertIsEqual("AXStandardWindow", win:subrole()) assertTrue(win:isStandard()) return success() end function testTopLeft() hs.openConsole() local win = hs.window.focusedWindow() local topLeftOrig = win:topLeft() assertIsTable(topLeftOrig) local topLeftNew = hs.geometry.point(topLeftOrig.x + 1, topLeftOrig.y + 1) win:setTopLeft(topLeftNew) topLeftNew = win:topLeft() assertIsEqual(topLeftNew.x, topLeftOrig.x + 1) assertIsEqual(topLeftNew.y, topLeftOrig.y + 1) return success() end function testSize() hs.openConsole() local win = hs.window.focusedWindow() win:setSize(hs.geometry.size(500, 600)) local sizeOrig = win:size() assertIsTable(sizeOrig) assertIsEqual(500, sizeOrig.w) assertIsEqual(600, sizeOrig.h) local sizeNew = hs.geometry.size(sizeOrig.w + 5, sizeOrig.h + 5) win:setSize(sizeNew) sizeNew = win:size() assertIsEqual(sizeNew.w, sizeOrig.w + 5) assertIsEqual(sizeNew.h, sizeOrig.h + 5) return success() end function testMinimize() hs.openConsole() local win = hs.window.focusedWindow() local isMinimizedOrig = win:isMinimized() assertIsBoolean(isMinimizedOrig) win:minimize() assertFalse(isMinimizedOrig == win:isMinimized()) win:unminimize() assertTrue(isMinimizedOrig == win:isMinimized()) return success() end function testPID() hs.openConsole() local win = hs.window.focusedWindow() assertIsEqual(win:pid(), hs.processInfo["processID"]) return success() end function testApplication() hs.openConsole() local win = hs.window.focusedWindow() local app = win:application() assertIsUserdataOfType("hs.application", app) -- This will fail right now, because hs.application doesn't have a __type metatable entry return success() end function testTabs() -- First test tabs on a window that doesn't have tabs hs.openConsole() local win = hs.window.focusedWindow() assertIsNil(win:tabCount()) -- Now test an app with tabs local safari = hs.application.open("Safari", 5, true) -- Ensure we have at least two tabs hs.urlevent.openURLWithBundle("http://www.apple.com", "com.apple.Safari") hs.urlevent.openURLWithBundle("http://developer.apple.com", "com.apple.Safari") local safariWin = safari:mainWindow() local tabCount = safariWin:tabCount() assertGreaterThan(1, tabCount) safariWin:focusTab(tabCount - 1) return success() end function testBecomeMain() -- This will fail end function testClose() hs.openConsole() local win = hs.window.focusedWindow() assertTrue(win:close()) -- It would be nice to do something more here, to verify it's gone return success() end function testFullscreen() hs.openConsole() local win = hs.window.focusedWindow() assertIsUserdata(win) local fullscreenState = win:isFullScreen() assertIsBoolean(fullscreenState) assertFalse(fullscreenState) win:setFullScreen(false) return success() end function testFullscreenOneSetup() hs.openConsole() local win = hs.window.get("Hammerspoon Console") assertIsEqual(win:title(), "Hammerspoon Console") assertFalse(win:isFullScreen()) win:setFullScreen(true) --return success() end function testFullscreenOneResult() local win = hs.window.get("Hammerspoon Console") assertIsEqual(win:title(), "Hammerspoon Console") assertTrue(win:isFullScreen()) win:setFullScreen(false) return success() end function testFullscreenTwoSetup() hs.openConsole() local win = hs.window.get("Hammerspoon Console") win:toggleZoom() return success() end function testFullscreenTwoResult() local win = hs.window.get("Hammerspoon Console") assertTrue(win:isFullScreen()) win:setFullScreen(false) return success() end
require("hs.timer") function testAllWindows() hs.openConsole() hs.openPreferences() local allWindows = hs.window.allWindows() assertIsEqual("table", type(allWindows)) assertGreaterThan(1, #allWindows) -- Enable this when hs.window objects have a proper __type metatable entry -- assertIsUserdataOfType(allWindows[1], "hs.window") hs.closePreferences() hs.closeConsole() return success() end function testDesktop() local desktop = hs.window.desktop() assertIsNotNil(desktop) assertIsEqual("AXScrollArea", desktop:role()) return success() end function testOrderedWindows() hs.openConsole() -- Make sure we have at least one window hs.openPreferences() hs.application.launchOrFocus("Activity Monitor.app") local orderedWindows = hs.window.orderedWindows() assertIsEqual("table", type(orderedWindows)) --assertIsEqual(hs.inspect(orderedWindows) .. " :: " .. hs.inspect(hs.window.visibleWindows()) .. " :: " .. hs.inspect(hs.window._orderedwinids()), "lol") hs.timer.usleep(500000) hs.application.find("Activity Monitor"):kill() assertGreaterThan(1, #orderedWindows) return success() end function testFocusedWindow() hs.openConsole() local win = hs.window.focusedWindow() assertIsUserdataOfType("hs.window", win) return success() end function testSnapshots() hs.openConsole() local win = hs.window.focusedWindow() local id = win:id() assertIsNumber(id) assertGreaterThan(0, id) assertIsUserdataOfType("hs.image", hs.window.snapshotForID(id)) assertIsUserdataOfType("hs.image", win:snapshot()) return success() end function testTitle() hs.openConsole() local win = hs.window.focusedWindow() local title = win:title() assertIsString(title) assertIsEqual("Hammerspoon Console", win:title()) assertIsString(tostring(win)) return success() end function testRoles() hs.openConsole() local win = hs.window.focusedWindow() assertIsEqual("AXWindow", win:role()) assertIsEqual("AXStandardWindow", win:subrole()) assertTrue(win:isStandard()) return success() end function testTopLeft() hs.openConsole() local win = hs.window.focusedWindow() local topLeftOrig = win:topLeft() assertIsTable(topLeftOrig) local topLeftNew = hs.geometry.point(topLeftOrig.x + 1, topLeftOrig.y + 1) win:setTopLeft(topLeftNew) topLeftNew = win:topLeft() assertIsEqual(topLeftNew.x, topLeftOrig.x + 1) assertIsEqual(topLeftNew.y, topLeftOrig.y + 1) return success() end function testSize() hs.openConsole() local win = hs.window.focusedWindow() win:setSize(hs.geometry.size(500, 600)) local sizeOrig = win:size() assertIsTable(sizeOrig) assertIsEqual(500, sizeOrig.w) assertIsEqual(600, sizeOrig.h) local sizeNew = hs.geometry.size(sizeOrig.w + 5, sizeOrig.h + 5) win:setSize(sizeNew) sizeNew = win:size() assertIsEqual(sizeNew.w, sizeOrig.w + 5) assertIsEqual(sizeNew.h, sizeOrig.h + 5) return success() end function testMinimize() hs.openConsole() local win = hs.window.focusedWindow() local isMinimizedOrig = win:isMinimized() assertIsBoolean(isMinimizedOrig) win:minimize() assertFalse(isMinimizedOrig == win:isMinimized()) win:unminimize() assertTrue(isMinimizedOrig == win:isMinimized()) return success() end function testPID() hs.openConsole() local win = hs.window.focusedWindow() assertIsEqual(win:pid(), hs.processInfo["processID"]) return success() end function testApplication() hs.openConsole() local win = hs.window.focusedWindow() local app = win:application() assertIsUserdataOfType("hs.application", app) -- This will fail right now, because hs.application doesn't have a __type metatable entry return success() end function testTabs() -- First test tabs on a window that doesn't have tabs hs.openConsole() local win = hs.window.focusedWindow() assertIsNil(win:tabCount()) -- Now test an app with tabs local safari = hs.application.open("Safari", 5, true) -- Ensure we have at least two tabs hs.urlevent.openURLWithBundle("http://www.apple.com", "com.apple.Safari") hs.urlevent.openURLWithBundle("http://developer.apple.com", "com.apple.Safari") local safariWin = safari:mainWindow() local tabCount = safariWin:tabCount() assertGreaterThan(1, tabCount) safariWin:focusTab(tabCount - 1) return success() end function testBecomeMain() -- This will fail end function testClose() hs.openConsole() local win = hs.window.focusedWindow() assertTrue(win:close()) -- It would be nice to do something more here, to verify it's gone return success() end function testFullscreen() hs.openConsole() local win = hs.window.focusedWindow() assertIsUserdata(win) local fullscreenState = win:isFullScreen() assertIsBoolean(fullscreenState) assertFalse(fullscreenState) win:setFullScreen(false) return success() end function testFullscreenOneSetup() hs.openConsole() local win = hs.window.get("Hammerspoon Console") assertIsEqual(win:title(), "Hammerspoon Console") assertFalse(win:isFullScreen()) win:setFullScreen(true) --return success() end function testFullscreenOneResult() local win = hs.window.get("Hammerspoon Console") assertIsEqual(win:title(), "Hammerspoon Console") assertTrue(win:isFullScreen()) win:setFullScreen(false) return success() end function testFullscreenTwoSetup() hs.openConsole() local win = hs.window.get("Hammerspoon Console") win:toggleZoom() return success() end function testFullscreenTwoResult() local win = hs.window.get("Hammerspoon Console") assertTrue(win:isFullScreen()) win:setFullScreen(false) return success() end
Attempt to debug hs.window.orderedWindows() failure
Attempt to debug hs.window.orderedWindows() failure Attempt to fix hs.window.orderedWindows() test Attempt to fix hs.window.orderedWindows() test
Lua
mit
Hammerspoon/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,asmagill/hammerspoon,Habbie/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,cmsj/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,asmagill/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,latenitefilms/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,cmsj/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,Habbie/hammerspoon,cmsj/hammerspoon,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,cmsj/hammerspoon,Hammerspoon/hammerspoon
5a8b2cb4ca2623961ed9ddf783fc5ce7659920c0
libs/httpd/luasrc/httpd.lua
libs/httpd/luasrc/httpd.lua
--[[ HTTP server implementation for LuCI - core (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <[email protected]> (c) 2008 Steven Barth <[email protected]> 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.httpd", package.seeall) require("socket") THREAD_IDLEWAIT = 0.01 THREAD_TIMEOUT = 90 THREAD_LIMIT = nil local reading = {} local clhandler = {} local erhandler = {} local threadc = 0 local threads = {} local threadm = {} local threadi = {} local _meta = {__mode = "k"} setmetatable(threads, _meta) setmetatable(threadm, _meta) setmetatable(threadi, _meta) function Socket(ip, port) local sock, err = socket.bind( ip, port ) if sock then sock:settimeout( 0, "t" ) end return sock, err end function corecv(socket, ...) threadi[socket] = true while true do local chunk, err, part = socket:receive(...) if err ~= "timeout" then threadi[socket] = false return chunk, err, part end coroutine.yield() end end function cosend(socket, chunk, i, ...) threadi[socket] = true i = i or 1 while true do local stat, err, sent = socket:send(chunk, i, ...) if err ~= "timeout" then threadi[socket] = false return stat, err, sent else i = sent and (sent + 1) or i end coroutine.yield() end end function register(socket, s_clhandler, s_errhandler) table.insert(reading, socket) clhandler[socket] = s_clhandler erhandler[socket] = s_errhandler end function run() while true do step() end end function step() print(collectgarbage("count")) local idle = true if not THREAD_LIMIT or threadc < THREAD_LIMIT then local now = os.time() for i, server in ipairs(reading) do local client = server:accept() if client then threadm[client] = now threadc = threadc + 1 threads[client] = coroutine.create(clhandler[server]) end end end for client, thread in pairs(threads) do coroutine.resume(thread, client) local now = os.time() if coroutine.status(thread) == "dead" then threadc = threadc - 1 elseif threadm[client] and threadm[client] + THREAD_TIMEOUT < now then threads[client] = nil threadc = threadc - 1 client:close() elseif not threadi[client] then threadm[client] = now idle = false end end if idle then socket.sleep(THREAD_IDLEWAIT) end end
--[[ HTTP server implementation for LuCI - core (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <[email protected]> (c) 2008 Steven Barth <[email protected]> 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.httpd", package.seeall) require("socket") THREAD_IDLEWAIT = 0.01 THREAD_TIMEOUT = 90 THREAD_LIMIT = nil local reading = {} local clhandler = {} local erhandler = {} local threadc = 0 local threads = {} local threadm = {} local threadi = {} local _meta = {__mode = "k"} setmetatable(threads, _meta) setmetatable(threadm, _meta) setmetatable(threadi, _meta) function Socket(ip, port) local sock, err = socket.bind( ip, port ) if sock then sock:settimeout( 0, "t" ) end return sock, err end function corecv(socket, ...) threadi[socket] = true while true do local chunk, err, part = socket:receive(...) if err ~= "timeout" then threadi[socket] = false return chunk, err, part end coroutine.yield() end end function cosend(socket, chunk, i, ...) threadi[socket] = true i = i or 1 while true do local stat, err, sent = socket:send(chunk, i, ...) if err ~= "timeout" then threadi[socket] = false return stat, err, sent else i = sent and (sent + 1) or i end coroutine.yield() end end function register(socket, s_clhandler, s_errhandler) table.insert(reading, socket) clhandler[socket] = s_clhandler erhandler[socket] = s_errhandler end function run() while true do step() end end function step() local idle = true if not THREAD_LIMIT or threadc < THREAD_LIMIT then local now = os.time() for i, server in ipairs(reading) do local client = server:accept() if client then threadm[client] = now threadc = threadc + 1 threads[client] = coroutine.create(clhandler[server]) end end end for client, thread in pairs(threads) do coroutine.resume(thread, client) local now = os.time() if coroutine.status(thread) == "dead" then threadc = threadc - 1 elseif threadm[client] and threadm[client] + THREAD_TIMEOUT < now then threads[client] = nil threadc = threadc - 1 client:close() elseif not threadi[client] then threadm[client] = now idle = false end end if idle then socket.sleep(THREAD_IDLEWAIT) end end
* libs/httpd: Fixed last commit
* libs/httpd: Fixed last commit
Lua
apache-2.0
8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci
ae8d7eec19d57e04dfc0280c95df32d6ce316d47
macos/.config/nvim/lua/dk/lsp.lua
macos/.config/nvim/lua/dk/lsp.lua
local nvim_lsp = require('lspconfig') local on_attach = function(client, bufnr) local function set(mode, lhs, rhs, opts) vim.keymap.set(mode,lhs,rhs,opts) end vim.api.nvim_buf_set_option(bufnr, 'omnifunc', 'v:lua.vim.lsp.omnifunc') -- Mappings. local opts = { buffer=bufnr} -- See `:help vim.lsp.*` for documentation on any of the below functions set('n', 'gd', vim.lsp.buf.definition, opts) set('n', 'K', vim.lsp.buf.hover, opts) set('n', 'gi', vim.lsp.buf.implementation, opts) set('n', 'gs', vim.lsp.buf.signature_help, opts) set('n', 'gt', vim.lsp.buf.type_definition, opts) set('n', '<leader>rn', vim.lsp.buf.rename, opts) set('n', '<leader>ca', vim.lsp.buf.code_action, opts) set('n', 'gr', vim.lsp.buf.references, opts) set('n', '<leader>e', vim.lsp.diagnostic.show_line_diagnostics, opts) set('n', '<leader>[', vim.diagnostic.goto_prev, opts) set('n', '<leader>]', vim.diagnostic.goto_next, opts) set('n', '<leader>ll', vim.diagnostic.setloclist, opts) end nvim_lsp.gopls.setup { settings = { gopls = { analyses = { fieldalignment = true, nilness = true, shadow = true, unusedparams = true, unusedwrite = true, }, staticcheck = true, linksInHover = false, }, }, on_attach = on_attach, } function goimports(timeout_ms) local context = { only = { "source.organizeImports" } } vim.validate { context = { context, "t", true } } local params = vim.lsp.util.make_range_params() params.context = context -- See the implementation of the textDocument/codeAction callback -- (lua/vim/lsp/handler.lua) for how to do this properly. local result = vim.lsp.buf_request_sync(0, "textDocument/codeAction", params, timeout_ms) if not result or next(result) == nil then return end local actions = result[1].result if not actions then return end local action = actions[1] -- textDocument/codeAction can return either Command[] or CodeAction[]. If it -- is a CodeAction, it can have either an edit, a command or both. Edits -- should be executed first. if action.edit or type(action.command) == "table" then if action.edit then vim.lsp.util.apply_workspace_edit(action.edit) end if type(action.command) == "table" then vim.lsp.buf.execute_command(action.command) end else vim.lsp.buf.execute_command(action) end end vim.cmd([[autocmd BufWritePre *.go lua vim.lsp.buf.formatting()]]) vim.cmd([[autocmd BufWritePre *.go lua goimports(1000)]])
local nvim_lsp = require('lspconfig') local on_attach = function(client, bufnr) local function set(mode, lhs, rhs, opts) vim.keymap.set(mode,lhs,rhs,opts) end vim.api.nvim_buf_set_option(bufnr, 'omnifunc', 'v:lua.vim.lsp.omnifunc') -- Mappings. local opts = { buffer=bufnr} -- See `:help vim.lsp.*` for documentation on any of the below functions set('n', 'gd', vim.lsp.buf.definition, opts) set('n', 'K', vim.lsp.buf.hover, opts) set('n', 'gi', vim.lsp.buf.implementation, opts) set('n', 'gs', vim.lsp.buf.signature_help, opts) set('n', 'gt', vim.lsp.buf.type_definition, opts) set('n', '<leader>rn', vim.lsp.buf.rename, opts) set('n', '<leader>ca', vim.lsp.buf.code_action, opts) set('n', 'gr', vim.lsp.buf.references, opts) set('n', '<leader>e', vim.lsp.diagnostic.show_line_diagnostics, opts) set('n', '<leader>[', vim.diagnostic.goto_prev, opts) set('n', '<leader>]', vim.diagnostic.goto_next, opts) set('n', '<leader>ll', vim.diagnostic.setloclist, opts) end nvim_lsp.gopls.setup { settings = { gopls = { analyses = { fieldalignment = true, nilness = true, shadow = true, unusedparams = true, unusedwrite = true, }, staticcheck = true, linksInHover = false, }, }, on_attach = on_attach, } function go_org_imports(wait_ms) local params = vim.lsp.util.make_range_params() params.context = {only = {"source.organizeImports"}} local result = vim.lsp.buf_request_sync(0, "textDocument/codeAction", params, wait_ms) for cid, res in pairs(result or {}) do for _, r in pairs(res.result or {}) do if r.edit then local enc = (vim.lsp.get_client_by_id(cid) or {}).offset_encoding or "utf-16" vim.lsp.util.apply_workspace_edit(r.edit, enc) end end end end local goGroup = vim.api.nvim_create_augroup("GoGroup", { clear = true }) vim.api.nvim_create_autocmd("BufWritePre", { group = goGroup, pattern = '*.go', callback = function() go_org_imports() vim.lsp.buf.formatting() end, })
nvim: fix lsp import on save
nvim: fix lsp import on save
Lua
mit
dvrkps/dotfiles
20a5d684dba6803090393f0fcd69919199029c43
Sidebar.lua
Sidebar.lua
-- Sidebar Sidebar = Tile:extend { width = 1, height = 1, visible = false, frame = false, buttonExists = {}, buttonTable = {}, onNew = function (self) the.app.view.layers.ui:add(self) self.frame = loveframes.Create("frame") self.frame:SetSize(256 / inputScale, 1024 / inputScale) self.frame:SetPos(1024 / inputScale, 0 / inputScale, false) self.frame:SetDraggable(false) self.frame:SetScreenLocked(false) self.frame:ShowCloseButton(false) end, onUpdate = function (self, elapsed) local i = 0 for k, v in pairs(the.characters) do if not self.buttonExists[k] and k.clan == the.clan.name then self["button" .. i] = loveframes.Create("button", self.frame) self["button" .. i]:SetSize(256 / inputScale, 32 / inputScale) self["button" .. i]:SetText(k.name .. " (" .. k.ressourcesCarried .. ")") self["button" .. i].OnClick = function(object) object_manager.get(k.oid):clicked() end self.buttonExists[k] = true self.buttonTable[k] = self["button" .. i] i = i + 1 end end local j = 0 for k, v in pairs(the.characters) do self["button" .. j]:SetText(k.name .. " (" .. k.ressourcesCarried .. ")") j = j + 1 end local counter = 0 for k,v in pairs(self.buttonTable) do v:SetPos(0 / inputScale, 32 / inputScale + counter * 32 / inputScale) counter = counter + 1 if not k.active then v:Remove() self.buttonTable[k] = nil end end self.frame:SetName("Clan " .. the.clan.name) end, onDie = function (self) frame:Remove() the.app.view.layers.ui:remove(self) end, }
-- Sidebar Sidebar = Tile:extend { width = 1, height = 1, visible = false, frame = false, buttonExists = {}, buttonTable = {}, onNew = function (self) the.app.view.layers.ui:add(self) self.frame = loveframes.Create("frame") self.frame:SetSize(256 / inputScale, 1024 / inputScale) self.frame:SetPos(1024 / inputScale, 0 / inputScale, false) self.frame:SetDraggable(false) self.frame:SetScreenLocked(false) self.frame:ShowCloseButton(false) end, onUpdate = function (self, elapsed) local i = 0 for k, v in pairs(the.characters) do if not self.buttonExists[k] and k.clan == the.clan.name then self["button" .. i] = loveframes.Create("button", self.frame) self["button" .. i]:SetSize(256 / inputScale, 32 / inputScale) self["button" .. i]:SetText(k.name .. " (" .. k.ressourcesCarried .. ")") self["button" .. i].OnClick = function(object) object_manager.get(k.oid):clicked() end self.buttonExists[k] = true self.buttonTable[k] = self["button" .. i] i = i + 1 end end local j = 0 for k, v in pairs(the.characters) do if self["button" .. j] then self["button" .. j]:SetText(k.name .. " (" .. k.ressourcesCarried .. ")") j = j + 1 end end local counter = 0 for k,v in pairs(self.buttonTable) do v:SetPos(0 / inputScale, 32 / inputScale + counter * 32 / inputScale) counter = counter + 1 if not k.active then v:Remove() self.buttonTable[k] = nil end end self.frame:SetName("Clan " .. the.clan.name) end, onDie = function (self) frame:Remove() the.app.view.layers.ui:remove(self) end, }
sidebar fix
sidebar fix
Lua
mit
dbltnk/macro-prototype,dbltnk/macro-prototype,dbltnk/macro-prototype,dbltnk/macro-prototype
b410003e30960416e0d46c5fc876a4396872b123
xmake/modules/package/manager/find_package.lua
xmake/modules/package/manager/find_package.lua
--!A cross-platform build utility based on Lua -- -- 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. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file find_package.lua -- -- imports import("core.base.semver") import("core.base.option") import("core.project.config") -- find package with the builtin rule -- -- opt.system: -- nil: find local or system packages -- true: only find system package -- false: only find local packages -- function _find_package_with_builtin_rule(package_name, opt) -- we cannot find it from xmake repo and package directories if only find system packages local managers = {} if opt.system ~= true then table.insert(managers, "xmake") end -- find system package if be not disabled if opt.system ~= false then -- find it from homebrew if not is_host("windows") then table.insert(managers, "brew") end -- find it from vcpkg (support multi-platforms/architectures) table.insert(managers, "vcpkg") -- find it from conan (support multi-platforms/architectures) table.insert(managers, "conan") -- only support the current host platform and architecture if opt.plat == os.host() and opt.arch == os.arch() then -- find it from pkg-config table.insert(managers, "pkg_config") -- find it from system table.insert(managers, "system") end end -- find package from the given package manager local result = nil for _, manager_name in ipairs(managers) do dprint("finding %s from %s ..", package_name, manager_name) result = import("package.manager." .. manager_name .. ".find_package", {anonymous = true})(package_name, opt) if result then break end end return result end -- find package function _find_package(manager_name, package_name, opt) -- find package from the given package manager local result = nil if manager_name then -- trace dprint("finding %s from %s ..", package_name, manager_name) -- find it result = import("package.manager." .. manager_name .. ".find_package", {anonymous = true})(package_name, opt) else -- find package from the given custom "detect.packages.find_xxx" script local builtin = false local find_package = import("detect.packages.find_" .. package_name, {anonymous = true, try = true}) if find_package then -- trace dprint("finding %s from find_%s ..", package_name, package_name) -- find it result = find_package(table.join(opt, { find_package = function (...) builtin = true return _find_package_with_builtin_rule(...) end})) end -- find package with the builtin rule if not result and not builtin then result = _find_package_with_builtin_rule(package_name, opt) end end -- found? if result then -- remove repeat result.linkdirs = table.unique(result.linkdirs) result.includedirs = table.unique(result.includedirs) end -- ok? return result end -- find package using the package manager -- -- @param name the package name -- e.g. zlib 1.12.x (try all), xmake::zlib 1.12.x, brew::zlib, brew::pcre/libpcre16, vcpkg::zlib, conan::OpenSSL/1.0.2n@conan/stable -- @param opt the options -- e.g. { verbose = false, force = false, plat = "iphoneos", arch = "arm64", mode = "debug", version = "1.0.x", -- linkdirs = {"/usr/lib"}, includedirs = "/usr/include", links = {"ssl"}, includes = {"ssl.h"} -- packagedirs = {"/tmp/packages"}, system = true} -- -- @return {links = {"ssl", "crypto", "z"}, linkdirs = {"/usr/local/lib"}, includedirs = {"/usr/local/include"}} -- -- @code -- -- local package = find_package("openssl") -- local package = find_package("openssl", {version = "1.0.*"}) -- local package = find_package("openssl", {plat = "iphoneos"}) -- local package = find_package("openssl", {linkdirs = {"/usr/lib", "/usr/local/lib"}, includedirs = "/usr/local/include", version = "1.0.1"}) -- local package = find_package("openssl", {linkdirs = {"/usr/lib", "/usr/local/lib", links = {"ssl", "crypto"}, includes = {"ssl.h"}}) -- -- @endcode -- function main(name, opt) -- get the copied options opt = table.copy(opt) opt.plat = opt.plat or config.get("plat") or os.host() opt.arch = opt.arch or config.get("arch") or os.arch() opt.mode = opt.mode or config.mode() or "release" -- get package manager name local manager_name, package_name = unpack(name:split("::", {plain = true, strict = true})) if package_name == nil then package_name = manager_name manager_name = nil else manager_name = manager_name:lower():trim() end -- get package name and require version local require_version = nil package_name, require_version = unpack(package_name:trim():split("%s")) opt.version = require_version or opt.version -- find package result = _find_package(manager_name, package_name, opt) -- match version? if opt.version and result then if not (result.version and (result.version == opt.version or semver.satisfies(result.version, opt.version))) then result = nil end end -- ok? return result end
--!A cross-platform build utility based on Lua -- -- 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. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file find_package.lua -- -- imports import("core.base.semver") import("core.base.option") import("core.project.config") -- find package with the builtin rule -- -- opt.system: -- nil: find local or system packages -- true: only find system package -- false: only find local packages -- function _find_package_with_builtin_rule(package_name, opt) -- we cannot find it from xmake repo and package directories if only find system packages local managers = {} if opt.system ~= true then table.insert(managers, "xmake") end -- find system package if be not disabled if opt.system ~= false then -- find it from homebrew if not is_host("windows") then table.insert(managers, "brew") end -- find it from vcpkg (support multi-platforms/architectures) table.insert(managers, "vcpkg") -- find it from conan (support multi-platforms/architectures) table.insert(managers, "conan") -- only support the current host platform and architecture if opt.plat == os.host() and opt.arch == os.arch() then -- find it from pkg-config table.insert(managers, "pkg_config") -- find it from system table.insert(managers, "system") end end -- find package from the given package manager local result = nil for _, manager_name in ipairs(managers) do dprint("finding %s from %s ..", package_name, manager_name) result = import("package.manager." .. manager_name .. ".find_package", {anonymous = true})(package_name, opt) if result then break end end return result end -- find package function _find_package(manager_name, package_name, opt) -- find package from the given package manager local result = nil if manager_name then -- trace dprint("finding %s from %s ..", package_name, manager_name) -- find it result = import("package.manager." .. manager_name .. ".find_package", {anonymous = true})(package_name, opt) else -- find package from the given custom "detect.packages.find_xxx" script local builtin = false local find_package = import("detect.packages.find_" .. package_name, {anonymous = true, try = true}) if find_package then -- trace dprint("finding %s from find_%s ..", package_name, package_name) -- find it result = find_package(table.join(opt, { find_package = function (...) builtin = true return _find_package_with_builtin_rule(...) end})) end -- find package with the builtin rule if not result and not builtin then result = _find_package_with_builtin_rule(package_name, opt) end end -- found? if result then -- remove repeat result.linkdirs = table.unique(result.linkdirs) result.includedirs = table.unique(result.includedirs) end -- ok? return result end -- find package using the package manager -- -- @param name the package name -- e.g. zlib 1.12.x (try all), xmake::zlib 1.12.x, brew::zlib, brew::pcre/libpcre16, vcpkg::zlib, conan::OpenSSL/1.0.2n@conan/stable -- @param opt the options -- e.g. { verbose = false, force = false, plat = "iphoneos", arch = "arm64", mode = "debug", version = "1.0.x", -- linkdirs = {"/usr/lib"}, includedirs = "/usr/include", links = {"ssl"}, includes = {"ssl.h"} -- packagedirs = {"/tmp/packages"}, system = true} -- -- @return {links = {"ssl", "crypto", "z"}, linkdirs = {"/usr/local/lib"}, includedirs = {"/usr/local/include"}} -- -- @code -- -- local package = find_package("openssl") -- local package = find_package("openssl", {version = "1.0.*"}) -- local package = find_package("openssl", {plat = "iphoneos"}) -- local package = find_package("openssl", {linkdirs = {"/usr/lib", "/usr/local/lib"}, includedirs = "/usr/local/include", version = "1.0.1"}) -- local package = find_package("openssl", {linkdirs = {"/usr/lib", "/usr/local/lib", links = {"ssl", "crypto"}, includes = {"ssl.h"}}) -- -- @endcode -- function main(name, opt) -- get the copied options opt = table.copy(opt) opt.plat = opt.plat or config.get("plat") or os.host() opt.arch = opt.arch or config.get("arch") or os.arch() opt.mode = opt.mode or config.mode() or "release" -- get package manager name local manager_name, package_name = unpack(name:split("::", {plain = true, strict = true})) if package_name == nil then package_name = manager_name manager_name = nil else manager_name = manager_name:lower():trim() end -- get package name and require version local require_version = nil package_name, require_version = unpack(package_name:trim():split("%s")) opt.version = require_version or opt.version -- find package result = _find_package(manager_name, package_name, opt) -- match version? if opt.version and opt.version:find('.', {plain = true}) and result then if not (result.version and (result.version == opt.version or semver.satisfies(result.version, opt.version))) then result = nil end end -- ok? return result end
fix find_package
fix find_package
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
f0054790aa89e1fa8b011031c0f1504d6c888eb2
lua/akamaiFunctions.lua
lua/akamaiFunctions.lua
-- vars for reference in criteria and behaviours local aka_request_host = ngx.var.host local aka_request_path = ngx.var.document_uri local aka_request_qs = ngx.var.query_string if aka_request_qs == nil then aka_request_qs = "" else aka_request_qs = "?" .. aka_request_qs end -- table to contain manage headers sent to origin local aka_upstream_headers = ngx.req.get_headers() -- supporting functions function string.starts(String,Start) return string.sub(String,1,string.len(Start))==Start end function string.ends(String,End) return End=='' or string.sub(String,-string.len(End))==End end function globtopattern(g) -- Some useful references: -- - apr_fnmatch in Apache APR. For example, -- http://apr.apache.org/docs/apr/1.3/group__apr__fnmatch.html -- which cites POSIX 1003.2-1992, section B.6. local p = "^" -- pattern being built local i = 0 -- index in g local c -- char at index i in g. -- unescape glob char local function unescape() if c == '\\' then i = i + 1; c = g:sub(i,i) if c == '' then p = '[^]' return false end end return true end -- escape pattern char local function escape(c) return c:match("^%w$") and c or '%' .. c end -- Convert tokens at end of charset. local function charset_end() while 1 do if c == '' then p = '[^]' return false elseif c == ']' then p = p .. ']' break else if not unescape() then break end local c1 = c i = i + 1; c = g:sub(i,i) if c == '' then p = '[^]' return false elseif c == '-' then i = i + 1; c = g:sub(i,i) if c == '' then p = '[^]' return false elseif c == ']' then p = p .. escape(c1) .. '%-]' break else if not unescape() then break end p = p .. escape(c1) .. '-' .. escape(c) end elseif c == ']' then p = p .. escape(c1) .. ']' break else p = p .. escape(c1) i = i - 1 -- put back end end i = i + 1; c = g:sub(i,i) end return true end -- Convert tokens in charset. local function charset() i = i + 1; c = g:sub(i,i) if c == '' or c == ']' then p = '[^]' return false elseif c == '^' or c == '!' then i = i + 1; c = g:sub(i,i) if c == ']' then -- ignored else p = p .. '[^' if not charset_end() then return false end end else p = p .. '[' if not charset_end() then return false end end return true end -- Convert tokens. while 1 do i = i + 1; c = g:sub(i,i) if c == '' then p = p .. '$' break elseif c == '?' then p = p .. '.' elseif c == '*' then p = p .. '.*' elseif c == '[' then if not charset() then break end elseif c == '\\' then i = i + 1; c = g:sub(i,i) if c == '' then p = p .. '\\$' break end p = p .. escape(c) else p = p .. escape(c) end end return p end function matches(value, glob) local pattern = globtopattern(glob) return (value):match(pattern) end -- executed after all criteria and behavior are evaluated to apply final actions function finalActions() -- deal with an calculated access controls if ngx.var.aka_deny_reason ~= nil and ngx.var.aka_deny_reason ~= "" then ngx.var.aka_origin_host = '' ngx.header.content_type = 'text/plain'; ngx.status = ngx.HTTP_UNAUTHORIZED ngx.say("access denied: " .. ngx.var.aka_deny_reason) ngx.exit(ngx.HTTP_OK) end -- if redirect calculated, do it if ngx.var.aka_redirect_location ~= nil and ngx.var.aka_redirect_location ~= "" then ngx.redirect(ngx.var.aka_redirect_location, ngx.var.aka_redirect_code) end -- set upstream headers modified by behaviors for key,value in pairs(aka_upstream_headers) do ngx.req.set_header(key, value) end -- if we have not manipulated the path or qs, pass through to origin as is. if aka_origin_url == nill or aka_origin_url == "" then ngx.var.aka_origin_url = aka_request_path .. aka_request_qs end end
-- vars for reference in criteria and behaviours local aka_request_scheme = ngx.var.scheme local aka_request_host = ngx.var.host local aka_request_path = ngx.var.document_uri local aka_request_qs = ngx.var.query_string local aka_origin_url = nil if aka_request_qs == nil then aka_request_qs = "" else aka_request_qs = "?" .. aka_request_qs end -- table to contain manage headers sent to origin local aka_upstream_headers = ngx.req.get_headers() function globtopattern(g) -- Some useful references: -- - apr_fnmatch in Apache APR. For example, -- http://apr.apache.org/docs/apr/1.3/group__apr__fnmatch.html -- which cites POSIX 1003.2-1992, section B.6. local p = "^" -- pattern being built local i = 0 -- index in g local c -- char at index i in g. -- unescape glob char local function unescape() if c == '\\' then i = i + 1; c = g:sub(i,i) if c == '' then p = '[^]' return false end end return true end -- escape pattern char local function escape(c) return c:match("^%w$") and c or '%' .. c end -- Convert tokens at end of charset. local function charset_end() while 1 do if c == '' then p = '[^]' return false elseif c == ']' then p = p .. ']' break else if not unescape() then break end local c1 = c i = i + 1; c = g:sub(i,i) if c == '' then p = '[^]' return false elseif c == '-' then i = i + 1; c = g:sub(i,i) if c == '' then p = '[^]' return false elseif c == ']' then p = p .. escape(c1) .. '%-]' break else if not unescape() then break end p = p .. escape(c1) .. '-' .. escape(c) end elseif c == ']' then p = p .. escape(c1) .. ']' break else p = p .. escape(c1) i = i - 1 -- put back end end i = i + 1; c = g:sub(i,i) end return true end -- Convert tokens in charset. local function charset() i = i + 1; c = g:sub(i,i) if c == '' or c == ']' then p = '[^]' return false elseif c == '^' or c == '!' then i = i + 1; c = g:sub(i,i) if c == ']' then -- ignored else p = p .. '[^' if not charset_end() then return false end end else p = p .. '[' if not charset_end() then return false end end return true end -- Convert tokens. while 1 do i = i + 1; c = g:sub(i,i) if c == '' then p = p .. '$' break elseif c == '?' then p = p .. '.' elseif c == '*' then p = p .. '.*' elseif c == '[' then if not charset() then break end elseif c == '\\' then i = i + 1; c = g:sub(i,i) if c == '' then p = p .. '\\$' break end p = p .. escape(c) else p = p .. escape(c) end end return p end function matches(value, glob) local glob = glob .. "*" local pattern = globtopattern(glob) return (value):match(pattern) end -- executed after all criteria and behavior are evaluated to apply final actions function finalActions() -- deal with an calculated access controls if ngx.var.aka_deny_reason ~= nil and ngx.var.aka_deny_reason ~= "" then ngx.var.aka_origin_host = "" ngx.header.content_type = "text/plain"; ngx.status = ngx.HTTP_UNAUTHORIZED ngx.log(ngx.ERR, "access denied: " .. ngx.var.aka_deny_reason) ngx.say("access denied: " .. ngx.var.aka_deny_reason) ngx.exit(ngx.HTTP_OK) end -- if redirect calculated, do it if ngx.var.aka_redirect_location ~= nil and ngx.var.aka_redirect_location ~= "" then ngx.log(ngx.ERR, "redirecting to: " .. ngx.var.aka_redirect_location .. " as " .. ngx.var.aka_redirect_code) ngx.redirect(ngx.var.aka_redirect_location, ngx.var.aka_redirect_code) end -- set upstream headers modified by behaviors for key,value in pairs(aka_upstream_headers) do ngx.req.set_header(key, value) end -- if we have not manipulated the path or qs, pass through to origin as is. if aka_origin_url == nil or aka_origin_url == "" then aka_origin_url = aka_request_path .. aka_request_qs end ngx.var.aka_origin_url = aka_origin_url ngx.var.aka_origin_scheme = aka_request_scheme ngx.log(ngx.ERR, "origin request: " .. ngx.var.aka_origin_scheme .. "://" .. ngx.var.aka_origin_host .. ngx.var.aka_origin_url) end
origin uri fixes and tidy
origin uri fixes and tidy
Lua
mit
wyvern8/akamai-nginx,wyvern8/akamai-nginx
fb42c59664c34c1b817a24442b3c5c9b0d244fe4
packages/verseindex.lua
packages/verseindex.lua
SILE.scratch.tableofverses = {} local orig_href = SILE.Commands["href"] local loadstring = loadstring or load local writeTov = function (self) local contents = "return " .. std.string.pickle(SILE.scratch.tableofverses) local tovfile, err = io.open(SILE.masterFilename .. '.tov', "w") if not tovfile then return SU.error(err) end tovfile:write(contents) end local moveNodes = function (self) local node = SILE.scratch.info.thispage.tov if node then for i = 1, #node do node[i].pageno = SILE.formatCounter(SILE.scratch.counters.folio) SILE.scratch.tableofverses[#(SILE.scratch.tableofverses)+1] = node[i] end end end local init = function (self) self:loadPackage("infonode") self:loadPackage("leaders") local inpair = nil local defaultparskip = SILE.settings.get("typesetter.parfillskip") local continuepair = function (args) if not args then return end if inpair and (args.frame.id == "content") then SILE.typesetter:pushState() SILE.call("tableofverses:book", { }, { inpair }) SILE.typesetter:popState() end end local pushBack = SILE.typesetter.pushBack SILE.typesetter.pushBack = function(self) continuepair(self) pushBack(self) end local startpair = function (pair) SILE.call("makecolumns", { gutter = "4%pw" }) SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue) inpair = pair end local endpair = function (seq) inpair = nil if seq > 2 and seq % 2 == 0 then SILE.typesetter:typeset(" ") SILE.call("par") end SILE.call("mergecolumns") SILE.settings.set("typesetter.parfillskip", defaultparskip) end SILE.registerCommand("href", function (options, content) SILE.call("markverse", options, content) return orig_href(options, content) end) SILE.registerCommand("tableofverses:book", function (options, content) SILE.call("requireSpace", { height = "4em" }) SILE.settings.set("typesetter.parfillskip", defaultparskip) SILE.call("hbox") SILE.call("skip", { height = "1ex" }) SILE.call("section", { numbering = false, skiptoc = true }, content) SILE.call("breakframevertical") startpair(content[1]) end) SILE.registerCommand("tableofverses:reference", function (options, content) if #options.pages < 1 then SU.warn("Verse in index doesn't have page marker") SU.debug("casile", content) pages = { "0" } end SILE.process(content) SILE.call("noindent") SILE.call("font", { size = ".5em" }, function () SILE.call("dotfill") end) local first = true for _, pageno in pairs(options.pages) do if not first then SILE.typesetter:typeset(", ") end SILE.typesetter:typeset(pageno) first = false end SILE.call("par") end) SILE.registerCommand("markverse", function (options, content) SILE.call("info", { category = "tov", value = { label = content } }) end) SILE.registerCommand("tableofverses", function (options, content) SILE.call("chapter", { numbering = false, appendix = true }, { "Ayet Referans İndeksi" }) SILE.call("cabook:seriffont", { size = "0.95em" }) local origmethod = SILE.settings.get("linespacing.method") local origleader = SILE.settings.get("linespacing.fixed.baselinedistance") local origparskip = SILE.settings.get("document.parskip") SILE.settings.set("linespacing.method", "fixed") SILE.settings.set("linespacing.fixed.baselinedistance", SILE.length.parse("1.1em")) SILE.settings.set("document.parskip", SILE.nodefactory.newVglue({})) local refshash = {} local lastbook = nil local seq = 1 for i, ref in pairs(CASILE.verses) do if not refshash[ref.osis] then refshash[ref.osis] = true if not(lastbook == ref.b) then if inpair then endpair(seq) end SILE.call("tableofverses:book", { }, { ref.b }) seq = 1 lastbook = inpair end local label = ref.reformat:match(".* (.*)") local pages = {} local pageshash = {} local bk = ref.b == "Mezmurlar" and "Mezmur" or ref.b for _, link in pairs(SILE.scratch.tableofverses) do if link.label[1] == bk .. " " .. label then local pageno = link.pageno if not pageshash[pageno] then pages[#pages+1] = pageno pageshash[pageno] = true end end end SILE.call("tableofverses:reference", { pages = pages }, { label }) seq = seq + 1 end end if inpair then endpair(seq) end inpair = nil SILE.settings.set("linespacing.fixed.baselinedistance", origleader) SILE.settings.set("linespacing.method", origmethod) SILE.settings.set("document.parskip", origparskip) end) end return { exports = { writeTov = writeTov, moveTovNodes = moveNodes }, init = init }
SILE.scratch.tableofverses = {} local orig_href = SILE.Commands["href"] local loadstring = loadstring or load local writeTov = function (self) local contents = "return " .. std.string.pickle(SILE.scratch.tableofverses) local tovfile, err = io.open(SILE.masterFilename .. '.tov', "w") if not tovfile then return SU.error(err) end tovfile:write(contents) end local moveNodes = function (self) local node = SILE.scratch.info.thispage.tov if node then for i = 1, #node do node[i].pageno = SILE.formatCounter(SILE.scratch.counters.folio) SILE.scratch.tableofverses[#(SILE.scratch.tableofverses)+1] = node[i] end end end local init = function (self) self:loadPackage("infonode") self:loadPackage("leaders") local inpair = nil local defaultparskip = SILE.settings.get("typesetter.parfillskip") local continuepair = function (args) if not args then return end if inpair and (args.frame.id == "content") then SILE.typesetter:pushState() SILE.call("tableofverses:book", { }, { inpair }) SILE.typesetter:popState() end end local pushBack = SILE.typesetter.pushBack SILE.typesetter.pushBack = function(self) continuepair(self) pushBack(self) end local startpair = function (pair) SILE.call("makecolumns", { gutter = "4%pw" }) SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue) inpair = pair end local endpair = function (seq) inpair = nil SILE.call("mergecolumns") SILE.settings.set("typesetter.parfillskip", defaultparskip) end SILE.registerCommand("href", function (options, content) SILE.call("markverse", options, content) return orig_href(options, content) end) SILE.registerCommand("tableofverses:book", function (options, content) SILE.call("requireSpace", { height = "4em" }) SILE.settings.set("typesetter.parfillskip", defaultparskip) SILE.call("hbox") SILE.call("skip", { height = "1ex" }) SILE.call("section", { numbering = false, skiptoc = true }, content) SILE.call("breakframevertical") startpair(content[1]) end) SILE.registerCommand("tableofverses:reference", function (options, content) if #options.pages < 1 then SU.warn("Verse in index doesn't have page marker") SU.debug("casile", content) pages = { "0" } end SILE.process(content) SILE.call("noindent") SILE.call("font", { size = ".5em" }, function () SILE.call("dotfill") end) local first = true for _, pageno in pairs(options.pages) do if not first then SILE.typesetter:typeset(", ") end SILE.typesetter:typeset(pageno) first = false end SILE.call("par") end) SILE.registerCommand("markverse", function (options, content) SILE.call("info", { category = "tov", value = { label = content } }) end) SILE.registerCommand("tableofverses", function (options, content) SILE.call("chapter", { numbering = false, appendix = true }, { "Ayet Referans İndeksi" }) SILE.call("cabook:seriffont", { size = "0.95em" }) local origmethod = SILE.settings.get("linespacing.method") local origleader = SILE.settings.get("linespacing.fixed.baselinedistance") local origparskip = SILE.settings.get("document.parskip") SILE.settings.set("linespacing.method", "fixed") SILE.settings.set("linespacing.fixed.baselinedistance", SILE.length.parse("1.1em")) SILE.settings.set("document.parskip", SILE.nodefactory.newVglue({})) local refshash = {} local lastbook = nil local seq = 1 for i, ref in pairs(CASILE.verses) do if not refshash[ref.osis] then refshash[ref.osis] = true if not(lastbook == ref.b) then if inpair then endpair(seq) end SILE.call("tableofverses:book", { }, { ref.b }) seq = 1 lastbook = inpair end local label = ref.reformat:match(".* (.*)") local pages = {} local pageshash = {} local bk = ref.b == "Mezmurlar" and "Mezmur" or ref.b for _, link in pairs(SILE.scratch.tableofverses) do if link.label[1] == bk .. " " .. label then local pageno = link.pageno if not pageshash[pageno] then pages[#pages+1] = pageno pageshash[pageno] = true end end end SILE.call("tableofverses:reference", { pages = pages }, { label }) seq = seq + 1 end end if inpair then endpair(seq) end inpair = nil SILE.settings.set("linespacing.fixed.baselinedistance", origleader) SILE.settings.set("linespacing.method", origmethod) SILE.settings.set("document.parskip", origparskip) end) end return { exports = { writeTov = writeTov, moveTovNodes = moveNodes }, init = init }
Remove colomn balancing hack obsoleted by using fixed leading
Remove colomn balancing hack obsoleted by using fixed leading
Lua
agpl-3.0
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
33d63b5446868a06bd69e6da7c1403a382690452
lualib/skynet/cluster.lua
lualib/skynet/cluster.lua
local skynet = require "skynet" local clusterd local cluster = {} local sender = {} local task_queue = {} local function request_sender(q, node) local ok, c = pcall(skynet.call, clusterd, "lua", "sender", node) if not ok then skynet.error(c) c = nil end -- run tasks in queue local confirm = coroutine.running() q.confirm = confirm q.sender = c for _, task in ipairs(q) do if type(task) == "table" then if c then skynet.send(c, "lua", "push", task[1], skynet.pack(table.unpack(task,2,task.n))) end else skynet.wakeup(task) skynet.wait(confirm) end end task_queue[node] = nil sender[node] = c end local function get_queue(t, node) local q = {} t[node] = q skynet.fork(request_sender, q, node) return q end setmetatable(task_queue, { __index = get_queue } ) local function get_sender(node) local s = sender[node] if not s then local q = task_queue[node] local task = coroutine.running() table.insert(q, task) skynet.wait(task) skynet.wakeup(q.confirm) return q.sender end return s end function cluster.call(node, address, ...) -- skynet.pack(...) will free by cluster.core.packrequest return skynet.call(get_sender(node), "lua", "req", address, skynet.pack(...)) end function cluster.send(node, address, ...) -- push is the same with req, but no response local s = sender[node] if not s then table.insert(task_queue[node], table.pack(address, ...)) else skynet.send(sender[node], "lua", "push", address, skynet.pack(...)) end 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(get_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 task_queue = {} local function repack(address, ...) return address, skynet.pack(...) end local function request_sender(q, node) local ok, c = pcall(skynet.call, clusterd, "lua", "sender", node) if not ok then skynet.error(c) c = nil end -- run tasks in queue local confirm = coroutine.running() q.confirm = confirm q.sender = c for _, task in ipairs(q) do if type(task) == "string" then if c then skynet.send(c, "lua", "push", repack(skynet.unpack(task))) end else skynet.wakeup(task) skynet.wait(confirm) end end task_queue[node] = nil sender[node] = c end local function get_queue(t, node) local q = {} t[node] = q skynet.fork(request_sender, q, node) return q end setmetatable(task_queue, { __index = get_queue } ) local function get_sender(node) local s = sender[node] if not s then local q = task_queue[node] local task = coroutine.running() table.insert(q, task) skynet.wait(task) skynet.wakeup(q.confirm) return q.sender end return s end function cluster.call(node, address, ...) -- skynet.pack(...) will free by cluster.core.packrequest local s = sender[node] if not s then local task = skynet.packstring(address, ...) return skynet.call(get_sender(node), "lua", "req", repack(skynet.unpack(task))) end return skynet.call(s, "lua", "req", address, skynet.pack(...)) end function cluster.send(node, address, ...) -- push is the same with req, but no response local s = sender[node] if not s then table.insert(task_queue[node], skynet.packstring(address, ...)) else skynet.send(sender[node], "lua", "push", address, skynet.pack(...)) end 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(get_sender(node), "lua", "req", 0, skynet.pack(name)) end skynet.init(function() clusterd = skynet.uniqueservice("clusterd") end) return cluster
bugfix:params changed when cluster sender is connecting
bugfix:params changed when cluster sender is connecting
Lua
mit
pigparadise/skynet,pigparadise/skynet,pigparadise/skynet
12f01b5416afc79e957cf5c1c22411dc5787fb35
wyx/ui/TooltipFactory.lua
wyx/ui/TooltipFactory.lua
local Class = require 'lib.hump.class' local Tooltip = getClass 'wyx.ui.Tooltip' local Text = getClass 'wyx.ui.Text' local Bar = getClass 'wyx.ui.Bar' local Frame = getClass 'wyx.ui.Frame' local Style = getClass 'wyx.ui.Style' local property = require 'wyx.component.property' local math_ceil = math.ceil local colors = colors -- some constants local MARGIN = 16 local MINWIDTH = 300 -- Common styles for tooltips local tooltipStyle = Style({ bgcolor = colors.BLACK_A85, bordersize = 4, borderinset = 4, bordercolor = colors.GREY30, }) local header1Style = Style({ font = GameFont.small, fontcolor = colors.WHITE, }) local textStyle = Style({ font = GameFont.verysmall, fontcolor = colors.GREY70, }) local iconStyle = Style({ bordersize = 4, bordercolor = colors.GREY70, bgcolor = colors.GREY10, fgcolor = colors.WHITE, }) local healthBarStyle = Style({ fgcolor = colors.RED, bgcolor = colors.DARKRED, }) -- TooltipFactory -- local TooltipFactory = Class{name='TooltipFactory', function(self) end } -- destructor function TooltipFactory:destroy() end -- make a tooltip for an entity function TooltipFactory:makeEntityTooltip(id) local entity = type(id) == 'string' and EntityRegistry:get(id) or id verifyClass('wyx.entity.Entity', entity) local name = entity:getName() local family = entity:getFamily() local kind = entity:getKind() local description = entity:getDescription() local headerW = 0 -- make the icon local icon local tileset = entity:query(property('TileSet')) if tileset then local image = Image[tileset] local allcoords = entity:query(property('TileCoords')) local coords local coords = allcoords.item or allcoords.front or allcoords.right or allcoords.left if not coords then for k in pairs(allcoords) do coords = allcoords[k]; break end end if coords then local size = entity:query(property('TileSize')) if size then local x, y = (coords[1]-1) * size, (coords[2]-1) * size icon = self:_makeIcon(image, x, y, size, size) else warning('makeEntityTooltip: bad TileSize property in entity %q', name) end else warning('makeEntityTooltip: bad TileCoords property in entity %q', name) end else warning('makeEntityTooltip: bad TileSet property in entity %q', name) end -- make the first header local header1 if name then header1 = self:_makeHeader1(name) headerW = header1:getWidth() else warning('makeEntityTooltip: bad Name for entity %q', tostring(entity)) end headerW = icon and headerW + icon:getWidth() + MARGIN or headerW local width = headerW > MINWIDTH and headerW or MINWIDTH -- make the health bar local pHealth = property('Health') local pHealthB = property('HealthBonus') local pMaxHealth = property('MaxHealth') local pMaxHealthB = property('MaxHealthBonus') local health = entity:query(pHealth) local maxHealth = entity:query(pMaxHealth) local healthBar if health and maxHealth then healthBar = Bar(0, 0, width, 9) healthBar:setNormalStyle(healthBarStyle) local func = function() local h = entity:query(pHealth) + entity:query(pHealthB) local max = entity:query(pMaxHealth) + entity:query(pMaxHealthB) return h, 0, max end healthBar:watch(func) end -- make the family and kind line local famLine if family and kind then local string = family..' ('..kind..')' famLine = self:_makeText(string) local width = famLine:getWidth() else warning('makeEntityTooltip: missing family or kind for entity %q', name) end -- make the stats frames -- TODO -- make the description local body if description then body = self:_makeText(description, width) else warning('makeEntityTooltip: missing description for entity %q', name) end -- make the tooltip local tooltip = Tooltip() tooltip:setNormalStyle(tooltipStyle) tooltip:setMargin(MARGIN) if icon then tooltip:setIcon(icon) end if header1 then tooltip:setHeader1(header1) end if healthBar then tooltip:addBar(healthBar) tooltip:addSpace() end if famLine then tooltip:addText(famLine) end if stats then for i=1,numStats do local stat = stats[i] tooltip:addText(stat) end end if body then if stats then tooltip:addSpace() end tooltip:addText(body) end return tooltip end -- make a simple generic tooltip with text function TooltipFactory:makeVerySimpleTooltip(text) verifyAny(text, 'string', 'function') local body = self:_makeText(text) local tooltip = Tooltip() tooltip:setNormalStyle(tooltipStyle) tooltip:setMargin(MARGIN) if body then tooltip:addText(body) end return tooltip end -- make a simple generic tooltip with a header and text function TooltipFactory:makeSimpleTooltip(header, text) verify('string', header) verifyAny(text, 'string', 'function') local header1 = self:_makeHeader1(header) local headerW = header1:getWidth() local width = headerW > MINWIDTH and headerW or MINWIDTH local body = self:_makeText(text, width) local tooltip = Tooltip() tooltip:setNormalStyle(tooltipStyle) tooltip:setMargin(MARGIN) if header1 then tooltip:setHeader1(header1) end if body then tooltip:addText(body) end return tooltip end -- make an icon frame function TooltipFactory:_makeIcon(image, x, y, w, h) local style = iconStyle:clone({fgimage = image}) style:setFGQuad(x, y, w, h) local icon = Frame(0, 0, w, h) icon:setNormalStyle(style, true) return icon end -- make a header1 Text frame function TooltipFactory:_makeHeader1(text) local font = header1Style:getFont() local fontH = font:getHeight() local width = font:getWidth(text) local header1 = Text(0, 0, width, fontH) header1:setNormalStyle(header1Style) header1:setText(text) return header1 end -- make a header2 Text frame function TooltipFactory:_makeHeader2(text) local font = header2Style:getFont() local fontH = font:getHeight() local width = font:getWidth(text) local header2 = Text(0, 0, width, fontH) header2:setNormalStyle(header2Style) header2:setText(text) return header2 end -- make a generic Text frame function TooltipFactory:_makeText(text, width) local isString = type(text) == 'string' local font = textStyle:getFont() local fontH = font:getHeight() local fontW = isString and font:getWidth(text) or font:getWidth(text())*2 width = width or fontW local numLines = math_ceil(fontW / width) local line = Text(0, 0, width, numLines * fontH) line:setMaxLines(numLines) if numLines == 1 then line:setJustifyCenter() end line:setNormalStyle(textStyle) if isString then line:setText(text) else line:watch(text) end return line end -- the class return TooltipFactory
local Class = require 'lib.hump.class' local Tooltip = getClass 'wyx.ui.Tooltip' local Text = getClass 'wyx.ui.Text' local Bar = getClass 'wyx.ui.Bar' local Frame = getClass 'wyx.ui.Frame' local Style = getClass 'wyx.ui.Style' local property = require 'wyx.component.property' local math_ceil = math.ceil local colors = colors -- some constants local MARGIN = 16 local MINWIDTH = 300 -- Common styles for tooltips local tooltipStyle = Style({ bgcolor = colors.BLACK_A85, bordersize = 4, borderinset = 4, bordercolor = colors.GREY30, }) local header1Style = Style({ font = GameFont.small, fontcolor = colors.WHITE, }) local textStyle = Style({ font = GameFont.verysmall, fontcolor = colors.GREY70, }) local iconStyle = Style({ bordersize = 4, bordercolor = colors.GREY70, bgcolor = colors.GREY10, fgcolor = colors.WHITE, }) local healthBarStyle = Style({ fgcolor = colors.RED, bgcolor = colors.DARKRED, }) -- TooltipFactory -- local TooltipFactory = Class{name='TooltipFactory', function(self) end } -- destructor function TooltipFactory:destroy() end -- make a tooltip for an entity function TooltipFactory:makeEntityTooltip(id) local entity = type(id) == 'string' and EntityRegistry:get(id) or id verifyClass('wyx.entity.Entity', entity) local name = entity:getName() local family = entity:getFamily() local kind = entity:getKind() local description = entity:getDescription() local headerW = 0 -- make the icon local icon local tileset = entity:query(property('TileSet')) if tileset then local image = Image[tileset] local allcoords = entity:query(property('TileCoords')) local coords local coords = allcoords.item or allcoords.front or allcoords.right or allcoords.left if not coords then for k in pairs(allcoords) do coords = allcoords[k]; break end end if coords then local size = entity:query(property('TileSize')) if size then local x, y = (coords[1]-1) * size, (coords[2]-1) * size icon = self:_makeIcon(image, x, y, size, size, size+8, size+8) else warning('makeEntityTooltip: bad TileSize property in entity %q', name) end else warning('makeEntityTooltip: bad TileCoords property in entity %q', name) end else warning('makeEntityTooltip: bad TileSet property in entity %q', name) end -- make the first header local header1 if name then header1 = self:_makeHeader1(name) headerW = header1:getWidth() else warning('makeEntityTooltip: bad Name for entity %q', tostring(entity)) end headerW = icon and headerW + icon:getWidth() + MARGIN or headerW local width = headerW > MINWIDTH and headerW or MINWIDTH -- make the health bar local pHealth = property('Health') local pHealthB = property('HealthBonus') local pMaxHealth = property('MaxHealth') local pMaxHealthB = property('MaxHealthBonus') local health = entity:query(pHealth) local maxHealth = entity:query(pMaxHealth) local healthBar if health and maxHealth then healthBar = Bar(0, 0, width, 9) healthBar:setNormalStyle(healthBarStyle) local func = function() local h = entity:query(pHealth) + entity:query(pHealthB) local max = entity:query(pMaxHealth) + entity:query(pMaxHealthB) return h, 0, max end healthBar:watch(func) end -- make the family and kind line local famLine if family and kind then local string = family..' ('..kind..')' famLine = self:_makeText(string) local width = famLine:getWidth() else warning('makeEntityTooltip: missing family or kind for entity %q', name) end -- make the stats frames -- TODO -- make the description local body if description then body = self:_makeText(description, width) else warning('makeEntityTooltip: missing description for entity %q', name) end -- make the tooltip local tooltip = Tooltip() tooltip:setNormalStyle(tooltipStyle) tooltip:setMargin(MARGIN) if icon then tooltip:setIcon(icon) end if header1 then tooltip:setHeader1(header1) end if healthBar then tooltip:addBar(healthBar) tooltip:addSpace() end if famLine then tooltip:addText(famLine) end if stats then for i=1,numStats do local stat = stats[i] tooltip:addText(stat) end end if body then if stats then tooltip:addSpace() end tooltip:addText(body) end return tooltip end -- make a simple generic tooltip with text function TooltipFactory:makeVerySimpleTooltip(text) verifyAny(text, 'string', 'function') local body = self:_makeText(text) local tooltip = Tooltip() tooltip:setNormalStyle(tooltipStyle) tooltip:setMargin(MARGIN) if body then tooltip:addText(body) end return tooltip end -- make a simple generic tooltip with a header and text function TooltipFactory:makeSimpleTooltip(header, text) verify('string', header) verifyAny(text, 'string', 'function') local header1 = self:_makeHeader1(header) local headerW = header1:getWidth() local width = headerW > MINWIDTH and headerW or MINWIDTH local body = self:_makeText(text, width) local tooltip = Tooltip() tooltip:setNormalStyle(tooltipStyle) tooltip:setMargin(MARGIN) if header1 then tooltip:setHeader1(header1) end if body then tooltip:addText(body) end return tooltip end -- make an icon frame function TooltipFactory:_makeIcon(image, x, y, w, h, fw, fh) local style = iconStyle:clone({fgimage = image}) style:setFGQuad(x, y, w, h) fw = fw or w fh = fh or h local icon = Frame(0, 0, fw, fh) icon:setNormalStyle(style, true) return icon end -- make a header1 Text frame function TooltipFactory:_makeHeader1(text) local font = header1Style:getFont() local fontH = font:getHeight() local width = font:getWidth(text) local header1 = Text(0, 0, width, fontH) header1:setNormalStyle(header1Style) header1:setText(text) return header1 end -- make a header2 Text frame function TooltipFactory:_makeHeader2(text) local font = header2Style:getFont() local fontH = font:getHeight() local width = font:getWidth(text) local header2 = Text(0, 0, width, fontH) header2:setNormalStyle(header2Style) header2:setText(text) return header2 end -- make a generic Text frame function TooltipFactory:_makeText(text, width) local isString = type(text) == 'string' local font = textStyle:getFont() local fontH = font:getHeight() local fontW = isString and font:getWidth(text) or font:getWidth(text())*2 width = width or fontW local numLines = math_ceil(fontW / width) local line = Text(0, 0, width, numLines * fontH) line:setMaxLines(numLines) if numLines == 1 then line:setJustifyCenter() end line:setNormalStyle(textStyle) if isString then line:setText(text) else line:watch(text) end return line end -- the class return TooltipFactory
fix entity icon border in tooltip
fix entity icon border in tooltip
Lua
mit
scottcs/wyx
a36d59711c098896b5f7c3c256df0a9d86f30595
agents/monitoring/tests/agent-protocol/init.lua
agents/monitoring/tests/agent-protocol/init.lua
local fs = require('fs') local JSON = require('json') local AgentProtocol = require('monitoring/lib/protocol/protocol') local AgentProtocolConnection = require('monitoring/lib/protocol/connection') local exports = {} exports['test_handshake_hello'] = function(test, asserts) fs.readFile('./options.gypi', function(err, data) if (err) then p(err) asserts.is_nil(err) return end local data = fs.readFileSync("./agents/monitoring/tests/agent-protocol/handshake.hello.request.json") local hello = { } hello.data = JSON.parse(data) hello.write = function(_, res) hello.res = res end local agent = AgentProtocol:new(hello.data, hello) agent:request(hello.data) response = JSON.parse(hello.res) -- TODO: asserts.object_equals in bourbon asserts.equals(response.v, 1) asserts.equals(response.id, 1) asserts.equals(response.source, "endpoint") asserts.equals(response.target, "X") asserts.equals(response.result, nil) test.done() end) end return exports
local fs = require('fs') local JSON = require('json') local AgentProtocol = require('monitoring/lib/protocol/protocol') local AgentProtocolConnection = require('monitoring/lib/protocol/connection') local exports = {} exports['test_handshake_hello'] = function(test, asserts) fs.readFile('./agents/monitoring/tests/agent-protocol/handshake.hello.request.json', function(err, data) if (err) then p(err) asserts.is_nil(err) return end local hello = { } hello.data = JSON.parse(data) hello.write = function(_, res) hello.res = res end local agent = AgentProtocol:new(hello.data, hello) agent:request(hello.data) response = JSON.parse(hello.res) -- TODO: asserts.object_equals in bourbon asserts.equals(response.v, 1) asserts.equals(response.id, 1) asserts.equals(response.source, "endpoint") asserts.equals(response.target, "X") asserts.equals(response.result, nil) test.done() end) end return exports
fix filename
fix filename
Lua
apache-2.0
kaustavha/rackspace-monitoring-agent,cp16net/virgo-base,AlphaStaxLLC/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base
6707844c34b10b2cbb7844838c886e9aa315f415
xmake/rules/cuda/xmake.lua
xmake/rules/cuda/xmake.lua
--!A cross-platform build utility based on Lua -- -- 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. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file xmake.lua -- -- define rule: cuda.build rule("cuda.build") set_sourcekinds("cu") add_deps("cuda.build.devlink") on_build_files("private.action.build.object", {batch = true}) -- define rule: cuda rule("cuda") add_deps("cuda.build", "cuda.gencodes")
--!A cross-platform build utility based on Lua -- -- 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. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file xmake.lua -- -- define rule: cuda.build rule("cuda.build") set_sourcekinds("cu") add_deps("cuda.build.devlink") on_build_files("private.action.build.object", {batch = true}) -- define rule: cuda rule("cuda") -- add build rules add_deps("cuda.build", "cuda.gencodes") -- inherit links and linkdirs of all dependent targets by default add_deps("utils.inherit.links") -- check targets add_deps("utils.check.targets")
fix cuda rules
fix cuda rules
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
f6553722b30b723c5027251bfa72c9d7ea7b8c2e
openwrt/package/linkmeter/luasrc/controller/linkmeter/lmadmin.lua
openwrt/package/linkmeter/luasrc/controller/linkmeter/lmadmin.lua
module("luci.controller.linkmeter.lmadmin", package.seeall) function index() local node = entry({"admin", "lm"}, alias("admin", "lm", "conf"), "LinkMeter",60) node.index = true entry({"admin", "lm", "home"}, template("linkmeter/index"), "Home", 10) entry({"admin", "lm", "conf"}, template("linkmeter/conf"), "Configuration", 20) entry({"admin", "lm", "archive"}, template("linkmeter/archive"), "Archive", 40) entry({"admin", "lm", "fw"}, call("action_fw"), "AVR Firmware", 50) entry({"admin", "lm", "credits"}, template("linkmeter/credits"), "Credits", 60) entry({"admin", "lm", "stashdb"}, call("action_stashdb")) entry({"admin", "lm", "reboot"}, call("action_reboot")) entry({"admin", "lm", "set"}, call("action_set")) if node.inreq and nixio.fs.access("/usr/share/linkmeter/alarm") then entry({"admin", "lm", "alarms"}, form("linkmeter/alarms"), "Alarm Scripts", 30) end end function action_fw() local hex = "/tmp/hm.hex" local file luci.http.setfilehandler( function(meta, chunk, eof) if not file and chunk and #chunk > 0 then file = io.open(hex, "w") end if file and chunk then file:write(chunk) end if file and eof then file:close() end end ) local step = tonumber(luci.http.formvalue("step") or 1) local has_upload = luci.http.formvalue("hexfile") local hexpath = luci.http.formvalue("hexpath") local web_update = hexpath and hexpath:find("^http://") if step == 1 then if has_upload and nixio.fs.access(hex) then step = 2 elseif hexpath and (web_update or nixio.fs.access(hexpath)) then step = 2 hex = hexpath else nixio.fs.unlink(hex) end return luci.template.render("linkmeter/fw", {step=step, hex=hex}) end if step == 3 then luci.http.prepare_content("text/plain") local pipe = require "luci.controller.admin.system".ltn12_popen( "/usr/bin/avrupdate %q" % luci.http.formvalue("hex")) return luci.ltn12.pump.all(pipe, luci.http.write) end end function action_stashdb() local http = require "luci.http" local uci = luci.model.uci.cursor() local RRD_FILE = uci:get("lucid", "linkmeter", "rrd_file") local STASH_PATH = uci:get("lucid", "linkmeter", "stashpath") or "/root" local restoring = http.formvalue("restore") local backup = http.formvalue("backup") local resetting = http.formvalue("reset") local deleting = http.formvalue("delete") local stashfile = http.formvalue("rrd") or "hm.rrd" -- directory traversal if stashfile:find("[/\\]+") then http.status(400, "Bad Request") http.prepare_content("text/plain") return http.write("Invalid stashfile specified: "..stashfile) end -- the stashfile should start with a slash if stashfile:sub(1,1) ~= "/" then stashfile = "/"..stashfile end -- and end with .rrd if stashfile:sub(-4) ~= ".rrd" then stashfile = stashfile..".rrd" end stashfile = STASH_PATH..stashfile if backup == "1" then local backup_cmd = "cd %q && tar cz *.rrd" % STASH_PATH local reader = require "luci.controller.admin.system".ltn12_popen(backup_cmd) http.header("Content-Disposition", 'attachment; filename="lmstash-%s-%s.tar.gz"' % { luci.sys.hostname(), os.date("%Y-%m-%d")}) http.prepare_content("application/x-targz") return luci.ltn12.pump.all(reader, luci.http.write) end local result http.prepare_content("text/plain") if deleting == "1" then result = nixio.fs.unlink(stashfile) http.write("Deleting "..stashfile) stashfile = stashfile:gsub("\.rrd$", ".txt") if nixio.fs.access(stashfile) then nixio.fs.unlink(stashfile) http.write("\nDeleting "..stashfile) end elseif restoring == "1" or resetting == "1" then require "lmclient" local lm = LmClient() lm:query("$LMDC,0", true) -- stop serial process if resetting == "1" then result = nixio.fs.unlink(RRD_FILE) http.write("Resetting "..RRD_FILE) else result = nixio.fs.copy(stashfile, RRD_FILE) http.write("Restoring "..stashfile.." to "..RRD_FILE) end lm:query("$LMDC,1") -- start serial process and close connection else if not nixio.fs.stat(STASH_PATH) then nixio.fs.mkdir(STASH_PATH) end result = nixio.fs.copy(RRD_FILE, stashfile) http.write("Stashing "..RRD_FILE.." to "..stashfile) end if result then http.write("\nOK") else http.write("\nERR") end end function action_reboot() local http = require "luci.http" http.prepare_content("text/plain") http.write("Rebooting AVR... ") require "lmclient" http.write(LmClient():query("$LMRB") or "FAILED") end function action_set() local dsp = require "luci.dispatcher" local http = require "luci.http" local vals = http.formvalue() -- If there's a rawset, explode the rawset into individual items local rawset = vals.rawset if rawset then -- remove /set? or set? if supplied rawset = rawset:gsub("^/?set%?","") vals = {} for pair in rawset:gmatch( "[^&;]+" ) do local key = pair:match("^([^=]+)") local val = pair:match("^[^=]+=(.+)$") if key and val then vals[key] = val end end end -- Make sure the user passed some values to set local cnt = 0 -- Can't use #vals because the table is actually a metatable with an indexer for _ in pairs(vals) do cnt = cnt + 1 end if cnt == 0 then return dsp.error500("No values specified") end require("lmclient") local lm = LmClient() http.prepare_content("text/plain") http.write("User %s setting %d values...\n" % {dsp.context.authuser, cnt}) local firstTime = true for k,v in pairs(vals) do -- Pause 100ms between commands to allow HeaterMeter to work if firstTime then firstTime = nil else nixio.nanosleep(0, 100000000) end local result, err = lm:query("$LMST,%s,%s" % {k,v}, true) http.write("%s to %s = %s\n" % {k,v, result or err}) if err then break end end lm:close() http.write("Done!") end
module("luci.controller.linkmeter.lmadmin", package.seeall) function index() local node = entry({"admin", "lm"}, alias("admin", "lm", "conf"), "LinkMeter",60) node.index = true entry({"admin", "lm", "home"}, template("linkmeter/index"), "Home", 10) entry({"admin", "lm", "conf"}, template("linkmeter/conf"), "Configuration", 20) entry({"admin", "lm", "archive"}, template("linkmeter/archive"), "Archive", 40) entry({"admin", "lm", "fw"}, call("action_fw"), "AVR Firmware", 50) entry({"admin", "lm", "credits"}, template("linkmeter/credits"), "Credits", 60) entry({"admin", "lm", "stashdb"}, call("action_stashdb")) entry({"admin", "lm", "reboot"}, call("action_reboot")) entry({"admin", "lm", "set"}, call("action_set")) if node.inreq and nixio.fs.access("/usr/share/linkmeter/alarm") then entry({"admin", "lm", "alarms"}, form("linkmeter/alarms"), "Alarm Scripts", 30) end end function action_fw() local hex = "/tmp/hm.hex" local file luci.http.setfilehandler( function(meta, chunk, eof) if not file and chunk and #chunk > 0 then file = io.open(hex, "w") end if file and chunk then file:write(chunk) end if file and eof then file:close() end end ) local step = tonumber(luci.http.formvalue("step") or 1) local has_upload = luci.http.formvalue("hexfile") local hexpath = luci.http.formvalue("hexpath") local web_update = hexpath and hexpath:find("^http://") if step == 1 then if has_upload and nixio.fs.access(hex) then step = 2 elseif hexpath and (web_update or nixio.fs.access(hexpath)) then step = 2 hex = hexpath else nixio.fs.unlink(hex) end return luci.template.render("linkmeter/fw", {step=step, hex=hex}) end if step == 3 then luci.http.prepare_content("text/plain") local pipe = require "luci.controller.admin.system".ltn12_popen( "/usr/bin/avrupdate %q" % luci.http.formvalue("hex")) return luci.ltn12.pump.all(pipe, luci.http.write) end end function action_stashdb() local http = require "luci.http" local uci = luci.model.uci.cursor() local RRD_FILE = uci:get("lucid", "linkmeter", "rrd_file") local STASH_PATH = uci:get("lucid", "linkmeter", "stashpath") or "/root" local restoring = http.formvalue("restore") local backup = http.formvalue("backup") local resetting = http.formvalue("reset") local deleting = http.formvalue("delete") local stashfile = http.formvalue("rrd") or "hm.rrd" -- directory traversal if stashfile:find("[/\\]+") then http.status(400, "Bad Request") http.prepare_content("text/plain") return http.write("Invalid stashfile specified: "..stashfile) end -- the stashfile should start with a slash if stashfile:sub(1,1) ~= "/" then stashfile = "/"..stashfile end -- and end with .rrd if stashfile:sub(-4) ~= ".rrd" then stashfile = stashfile..".rrd" end stashfile = STASH_PATH..stashfile if backup == "1" then local backup_cmd = "cd %q && tar cz *.rrd" % STASH_PATH local reader = require "luci.controller.admin.system".ltn12_popen(backup_cmd) http.header("Content-Disposition", 'attachment; filename="lmstash-%s-%s.tar.gz"' % { luci.sys.hostname(), os.date("%Y-%m-%d")}) http.prepare_content("application/x-targz") return luci.ltn12.pump.all(reader, luci.http.write) end local result http.prepare_content("text/plain") if deleting == "1" then result = nixio.fs.unlink(stashfile) http.write("Deleting "..stashfile) stashfile = stashfile:gsub("\.rrd$", ".txt") if nixio.fs.access(stashfile) then nixio.fs.unlink(stashfile) http.write("\nDeleting "..stashfile) end elseif restoring == "1" or resetting == "1" then require "lmclient" local lm = LmClient() lm:query("$LMDC,0", true) -- stop serial process if resetting == "1" then nixio.fs.unlink("/root/autobackup.rrd") result = nixio.fs.unlink(RRD_FILE) http.write("Removing autobackup\nResetting "..RRD_FILE) else result = nixio.fs.copy(stashfile, RRD_FILE) http.write("Restoring "..stashfile.." to "..RRD_FILE) end lm:query("$LMDC,1") -- start serial process and close connection else if not nixio.fs.stat(STASH_PATH) then nixio.fs.mkdir(STASH_PATH) end result = nixio.fs.copy(RRD_FILE, stashfile) http.write("Stashing "..RRD_FILE.." to "..stashfile) end if result then http.write("\nOK") else http.write("\nERR") end end function action_reboot() local http = require "luci.http" http.prepare_content("text/plain") http.write("Rebooting AVR... ") require "lmclient" http.write(LmClient():query("$LMRB") or "FAILED") end function action_set() local dsp = require "luci.dispatcher" local http = require "luci.http" local vals = http.formvalue() -- If there's a rawset, explode the rawset into individual items local rawset = vals.rawset if rawset then -- remove /set? or set? if supplied rawset = rawset:gsub("^/?set%?","") vals = {} for pair in rawset:gmatch( "[^&;]+" ) do local key = pair:match("^([^=]+)") local val = pair:match("^[^=]+=(.+)$") if key and val then vals[key] = val end end end -- Make sure the user passed some values to set local cnt = 0 -- Can't use #vals because the table is actually a metatable with an indexer for _ in pairs(vals) do cnt = cnt + 1 end if cnt == 0 then return dsp.error500("No values specified") end require("lmclient") local lm = LmClient() http.prepare_content("text/plain") http.write("User %s setting %d values...\n" % {dsp.context.authuser, cnt}) local firstTime = true for k,v in pairs(vals) do -- Pause 100ms between commands to allow HeaterMeter to work if firstTime then firstTime = nil else nixio.nanosleep(0, 100000000) end local result, err = lm:query("$LMST,%s,%s" % {k,v}, true) http.write("%s to %s = %s\n" % {k,v, result or err}) if err then break end end lm:close() http.write("Done!") end
[lm] Fix 'reset database' restoring autobackup
[lm] Fix 'reset database' restoring autobackup
Lua
mit
dwright134/HeaterMeter,kdakers80/HeaterMeter,kdakers80/HeaterMeter,dwright134/HeaterMeter,dwright134/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,kdakers80/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,kdakers80/HeaterMeter,kdakers80/HeaterMeter,kdakers80/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter,dwright134/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,shmick/HeaterMeter
b79ec9be7c6587a342b595de1ab385909fb1671b
MMOCoreORB/bin/scripts/screenplays/screenplay.lua
MMOCoreORB/bin/scripts/screenplays/screenplay.lua
local ObjectManager = require("managers.object.object_manager") function printf(...) io.write(string.format(unpack(arg))) end function writeData(key, data) writeSharedMemory(string.format(key), data) end function writeStringData(key, data) writeStringSharedMemory(string.format(key), string.format(data)) end function deleteData(key) deleteSharedMemory(string.format(key)) end function deleteStringData(key) deleteStringSharedMemory(string.format(key)) end function readData(key) return readSharedMemory(string.format(key)) end function readStringData(key) return readStringSharedMemory(string.format(key)) end ScreenPlay = Object:new { screenplayName = "", numerOfActs = 0, startingEvent = nil, lootContainers = {}, lootLevel = 0, lootGroups = {}, lootContainerRespawn = 1800 -- 30 minutes } function ScreenPlay:initializeLootContainers() for k,v in pairs(self.lootContainers) do local pContainer = getSceneObject(v) if (pContainer ~= nil) then createObserver(OPENCONTAINER, self.screenplayName, "spawnContainerLoot", pContainer) self:spawnContainerLoot(pContainer) local container = LuaSceneObject(pContainer) container:setContainerDefaultAllowPermission(MOVEOUT + OPEN) container:setContainerComponent("PlaceableLootContainerComponent") end end end function ScreenPlay:spawnContainerLoot(pContainer) local container = LuaSceneObject(pContainer) local time = getTimestamp() if (readData(container:getObjectID()) > time) then return end --If it has loot already, then exit. if (container:getContainerObjectsSize() > 0) then return end createLootFromCollection(pContainer, self.lootGroups, self.lootLevel) writeData(container:getObjectID(), time + self.lootContainerRespawn) end Act = Object:new { } return ScreenPlay
local ObjectManager = require("managers.object.object_manager") function printf(...) io.write(string.format(unpack(arg))) end function writeData(key, data) writeSharedMemory(string.format(key), data) end function writeStringData(key, data) writeStringSharedMemory(string.format(key), string.format(data)) end function deleteData(key) deleteSharedMemory(string.format(key)) end function deleteStringData(key) deleteStringSharedMemory(string.format(key)) end function readData(key) return readSharedMemory(string.format(key)) end function readStringData(key) return readStringSharedMemory(string.format(key)) end ScreenPlay = Object:new { screenplayName = "", numerOfActs = 0, startingEvent = nil, lootContainers = {}, lootLevel = 0, lootGroups = {}, lootContainerRespawn = 1800 -- 30 minutes } function ScreenPlay:initializeLootContainers() for k,v in pairs(self.lootContainers) do local pContainer = getSceneObject(v) if (pContainer ~= nil) then createObserver(OPENCONTAINER, self.screenplayName, "spawnContainerLoot", pContainer) self:spawnContainerLoot(pContainer) local container = LuaSceneObject(pContainer) container:setContainerDefaultAllowPermission(MOVEOUT + OPEN) container:setContainerComponent("PlaceableLootContainerComponent") end end end function ScreenPlay:spawnContainerLoot(pContainer) local container = LuaSceneObject(pContainer) local time = getTimestamp() if (readData(container:getObjectID()) > time) then return end writeData(container:getObjectID(), time + self.lootContainerRespawn) --If it has loot already, then exit. if (container:getContainerObjectsSize() > 0) then return end createLootFromCollection(pContainer, self.lootGroups, self.lootLevel) end Act = Object:new { } return ScreenPlay
[Fixed] magseals to no longer double spawn loot
[Fixed] magseals to no longer double spawn loot Change-Id: I4c1b9c2eabac981c3c58c3c965594e0ae997a2b8
Lua
agpl-3.0
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo
01f0dd3826a356aed9bf3ffd5b2200dc1f4fc5e7
modules/vim/installed-config/plugin/cmp.lua
modules/vim/installed-config/plugin/cmp.lua
local cmp = require('cmp') local t = function(str) return vim.api.nvim_replace_termcodes(str, true, true, true) end local kind_icons = { text = "", method = "", ['function'] = "", constructor = "", field = "", variable = "", class = "ﴯ", interface = "", module = "", property = "ﰠ", unit = "", value = "", enum = "", keyword = "", snippet = "", color = "", file = "", reference = "", folder = "", enumMember = "", constant = "", struct = "", event = "", operator = "", typeParameter = "" } cmp.setup({ snippet = { -- REQUIRED - you must specify a snippet engine expand = function(args) vim.fn["vsnip#anonymous"](args.body) end, }, mapping = { ['<C-b>'] = cmp.mapping(cmp.mapping.scroll_docs(-4), { 'i', 'c' }), ['<C-f>'] = cmp.mapping(cmp.mapping.scroll_docs(4), { 'i', 'c' }), ['<C-Space>'] = cmp.mapping(cmp.mapping.complete(), { 'i', 'c' }), ['<C-y>'] = cmp.config.disable, -- Specify `cmp.config.disable` if you want to remove the default `<C-y>` mapping. ['<C-e>'] = cmp.mapping({ i = cmp.mapping.abort(), c = cmp.mapping.close(), }), ['<CR>'] = cmp.mapping.confirm({ select = false }), -- Accept currently selected item. Set `select` to `false` to only confirm explicitly selected items. ['<C-n>'] = cmp.mapping({ c = function() if cmp.visible() then cmp.select_next_item({ behavior = cmp.SelectBehavior.Select }) else vim.api.nvim_feedkeys(t('<Down>'), 'n', true) end end, i = function(fallback) if cmp.visible() then cmp.select_next_item({ behavior = cmp.SelectBehavior.Select }) else fallback() end end }), ['<C-p>'] = cmp.mapping({ c = function() if cmp.visible() then cmp.select_prev_item({ behavior = cmp.SelectBehavior.Select }) else vim.api.nvim_feedkeys(t('<Up>'), 'n', true) end end, i = function(fallback) if cmp.visible() then cmp.select_prev_item({ behavior = cmp.SelectBehavior.Select }) else fallback() end end }), }, sources = cmp.config.sources({ { name = 'nvim_lsp' }, { name = 'vsnip' }, { name = 'treesitter' }, { name = 'rg' }, }, { { name = 'buffer' }, }), window = { completion = cmp.config.window.bordered(), documentation = cmp.config.window.bordered() }, formatting = { format = function(entry, vim_item) vim_item.kind = string.format('%s %s', kind_icons[string.lower(vim_item.kind)], vim_item.kind) return vim_item end } }) cmp.setup.cmdline(':', { sources = { { name = 'cmdline' }, { name = 'buffer' } } }) cmp.setup.cmdline('/', { sources = { { name = 'buffer' } } })
local cmp = require('cmp') local t = function(str) return vim.api.nvim_replace_termcodes(str, true, true, true) end local kind_icons = { text = "", method = "", ['function'] = "", constructor = "", field = "", variable = "", class = "ﴯ", interface = "", module = "", property = "ﰠ", unit = "", value = "", enum = "", keyword = "", snippet = "", color = "", file = "", reference = "", folder = "", enumMember = "", constant = "", struct = "", event = "", operator = "", typeParameter = "" } cmp.setup({ snippet = { -- REQUIRED - you must specify a snippet engine expand = function(args) require('luasnip').lsp_expand(args.body) end, }, mapping = { ['<C-b>'] = cmp.mapping(cmp.mapping.scroll_docs(-4), { 'i', 'c' }), ['<C-f>'] = cmp.mapping(cmp.mapping.scroll_docs(4), { 'i', 'c' }), ['<C-Space>'] = cmp.mapping(cmp.mapping.complete(), { 'i', 'c' }), ['<C-y>'] = cmp.config.disable, -- Specify `cmp.config.disable` if you want to remove the default `<C-y>` mapping. ['<C-e>'] = cmp.mapping({ i = cmp.mapping.abort(), c = cmp.mapping.close(), }), ['<CR>'] = cmp.mapping({ -- Accept currently selected item. -- Set `select` to `false` to only confirm explicitly selected items. i = cmp.mapping.confirm({ select = false }), c = function(fallback) if cmp.visible() then if not cmp.confirm({ select = false }) then fallback() end else fallback() end end }), ['<C-n>'] = cmp.mapping({ c = function() if cmp.visible() then cmp.select_next_item({ behavior = cmp.SelectBehavior.Select }) else vim.api.nvim_feedkeys(t('<Down>'), 'n', true) end end, i = function(fallback) if cmp.visible() then cmp.select_next_item({ behavior = cmp.SelectBehavior.Select }) else fallback() end end }), ['<C-p>'] = cmp.mapping({ c = function() if cmp.visible() then cmp.select_prev_item({ behavior = cmp.SelectBehavior.Select }) else vim.api.nvim_feedkeys(t('<Up>'), 'n', true) end end, i = function(fallback) if cmp.visible() then cmp.select_prev_item({ behavior = cmp.SelectBehavior.Select }) else fallback() end end }), }, sources = cmp.config.sources({ { name = 'nvim_lsp' }, { name = 'luasnip' }, { name = 'treesitter' }, { name = 'rg' }, }, { { name = 'buffer' }, }), window = { completion = cmp.config.window.bordered(), documentation = cmp.config.window.bordered() }, formatting = { format = function(entry, vim_item) vim_item.kind = string.format('%s %s', kind_icons[string.lower(vim_item.kind)], vim_item.kind) return vim_item end } }) cmp.setup.cmdline(':', { sources = { { name = 'cmdline' }, { name = 'buffer' } } }) cmp.setup.cmdline('/', { sources = { { name = 'buffer' } } })
Fix cmp mappings for command line
Fix cmp mappings for command line
Lua
mit
justinhoward/dotfiles,justinhoward/dotfiles
69c6fe6f4ecefc65b6dd7cd601bf3ac33aa61c86
agents/monitoring/tests/fixtures/protocol/server.lua
agents/monitoring/tests/fixtures/protocol/server.lua
local net = require('net') local JSON = require('json') local fixtures = require('./') local LineEmitter = require('line-emitter').LineEmitter local table = require('table') local tls = require('tls') local timer = require('timer') local string = require('string') local math = require('math') local table = require('table') local http = require("http") local url = require('url') local lineEmitter = LineEmitter:new() local ports = {50041, 50051, 50061} local opts = {} local function set_option(options, name, default) options[name] = process.env[string.upper(name)] or default end set_option(opts, "send_schedule_changed_initial", 2000) set_option(opts, "send_schedule_changed_interval", 60000) set_option(opts, "destroy_connection_jitter", 60000) set_option(opts, "destroy_connection_base", 60000) set_option(opts, "listen_ip", '127.0.0.1') set_option(opts, "perform_client_disconnect", 'true') set_option(opts, "rate_limit", 3000) set_option(opts, "rate_limit_reset", 86400) -- Reset limit in 24 hours local keyPem = [[ -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre 535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0 kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9 2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR 9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd 0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei -----END RSA PRIVATE KEY----- ]] local certPem = [[ -----BEGIN CERTIFICATE----- MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG 9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN -----END CERTIFICATE----- ]] local options = { cert = certPem, key = keyPem } local respond = function(log, client, payload) local destroy = false -- skip responses to requests if payload.method == nil then return end local response_method = payload.method .. '.response' local response = JSON.parse(fixtures[response_method]) local response_out = nil -- Handle rate limit logic client.rate_limit = client.rate_limit - 1 if client.rate_limit <= 0 then response = JSON.parse(fixtures['rate-limiting']['rate-limit-error']) destroy = true end response.target = payload.source response.source = payload.target response.id = payload.id log("Sending response:") response_out = JSON.stringify(response) response_out:gsub("\n", " ") client:write(response_out .. '\n') if destroy == true then client:destroy() end return destroy end local send_schedule_changed = function(log, client) local request = fixtures['check_schedule.changed.request'] log("Sending request:") p(JSON.parse(request)) client:write(request .. '\n') end local function clear_timers(timer_ids) for k, v in pairs(timer_ids) do if v._closed ~= true then timer.clearTimer(v) end end end local function start_fixture_server(options, port) local log = function(...) print(port .. ": " .. ...) end local server = tls.createServer(options, function (client) local destroyed = false local timers = {} client.rate_limit = opts.rate_limit client:pipe(lineEmitter) lineEmitter:on('data', function(line) local payload = JSON.parse(line) log("Got payload:") p(payload) destroyed = respond(log, client, payload) if destroyed == true then clear_timers(timers) end end) -- Reset rate limit counter timer.setTimeout(opts.rate_limit_reset, function() client.rate_limit = opts.rate_limit end) timer.setTimeout(opts.send_schedule_changed_initial, function() send_schedule_changed(log, client) end) table.insert(timers, timer.setInterval(opts.send_schedule_changed_interval, function() send_schedule_changed(log, client) end) ) -- Disconnect the agent after some random number of seconds -- to exercise reconnect logic if opts.perform_client_disconnect == 'true' then local disconnect_time = opts.destroy_connection_base + math.floor(math.random() * opts.destroy_connection_jitter) timer.setTimeout(disconnect_time, function() log("Destroying connection after " .. disconnect_time .. "ms connected") client:destroy() end) end end):listen(port, opts.listen_ip) return server end -- There is no cleanup code for the server here as the process for exiting is -- to just ctrl+c the runner or kill the process. for k, v in pairs(ports) do start_fixture_server(options, v) print("TCP echo server listening on port " .. v) end
local net = require('net') local JSON = require('json') local fixtures = require('./') local LineEmitter = require('line-emitter').LineEmitter local table = require('table') local tls = require('tls') local timer = require('timer') local string = require('string') local math = require('math') local table = require('table') local http = require("http") local url = require('url') local ports = {50041, 50051, 50061} local opts = {} local function set_option(options, name, default) options[name] = process.env[string.upper(name)] or default end set_option(opts, "send_schedule_changed_initial", 2000) set_option(opts, "send_schedule_changed_interval", 60000) set_option(opts, "destroy_connection_jitter", 60000) set_option(opts, "destroy_connection_base", 60000) set_option(opts, "listen_ip", '127.0.0.1') set_option(opts, "perform_client_disconnect", 'true') set_option(opts, "rate_limit", 3000) set_option(opts, "rate_limit_reset", 86400) -- Reset limit in 24 hours local keyPem = [[ -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre 535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0 kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9 2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR 9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd 0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei -----END RSA PRIVATE KEY----- ]] local certPem = [[ -----BEGIN CERTIFICATE----- MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG 9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN -----END CERTIFICATE----- ]] local options = { cert = certPem, key = keyPem } local respond = function(log, client, payload) local destroy = false -- skip responses to requests if payload.method == nil then return end local response_method = payload.method .. '.response' local response = JSON.parse(fixtures[response_method]) local response_out = nil -- Handle rate limit logic client.rate_limit = client.rate_limit - 1 if client.rate_limit <= 0 then response = JSON.parse(fixtures['rate-limiting']['rate-limit-error']) destroy = true end response.target = payload.source response.source = payload.target response.id = payload.id log("Sending response:") response_out = JSON.stringify(response) response_out:gsub("\n", " ") client:write(response_out .. '\n') if destroy == true then client:destroy() end return destroy end local send_schedule_changed = function(log, client) local request = fixtures['check_schedule.changed.request'] log("Sending request:") p(JSON.parse(request)) client:write(request .. '\n') end local function clear_timers(timer_ids) for k, v in pairs(timer_ids) do if v._closed ~= true then timer.clearTimer(v) end end end local function start_fixture_server(options, port) local log = function(...) print(port .. ": " .. ...) end local server = tls.createServer(options, function (client) local lineEmitter = LineEmitter:new() local destroyed = false local timers = {} client.rate_limit = opts.rate_limit client:pipe(lineEmitter) lineEmitter:on('data', function(line) local payload = JSON.parse(line) log("Got payload:") p(payload) destroyed = respond(log, client, payload) if destroyed == true then clear_timers(timers) end end) -- Reset rate limit counter timer.setTimeout(opts.rate_limit_reset, function() client.rate_limit = opts.rate_limit end) timer.setTimeout(opts.send_schedule_changed_initial, function() send_schedule_changed(log, client) end) table.insert(timers, timer.setInterval(opts.send_schedule_changed_interval, function() send_schedule_changed(log, client) end) ) -- Disconnect the agent after some random number of seconds -- to exercise reconnect logic if opts.perform_client_disconnect == 'true' then local disconnect_time = opts.destroy_connection_base + math.floor(math.random() * opts.destroy_connection_jitter) timer.setTimeout(disconnect_time, function() log("Destroying connection after " .. disconnect_time .. "ms connected") client:destroy() end) end end):listen(port, opts.listen_ip) return server end -- There is no cleanup code for the server here as the process for exiting is -- to just ctrl+c the runner or kill the process. for k, v in pairs(ports) do start_fixture_server(options, v) print("TCP echo server listening on port " .. v) end
monitoring: fixtures: server: lineEmitter per connection
monitoring: fixtures: server: lineEmitter per connection make the lineEmitter per connection so that we don't end up sending responses to all three connections.
Lua
apache-2.0
kans/zirgo,kans/zirgo,kans/zirgo
57e364eb0dde6e5ede7ba59f22c5d2edd14bfd04
libs/httpd/luasrc/httpd/handler/luci.lua
libs/httpd/luasrc/httpd/handler/luci.lua
--[[ HTTP server implementation for LuCI - luci handler (c) 2008 Steven Barth <[email protected]> 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.httpd.handler.luci", package.seeall) require("luci.dispatcher") require("luci.http") require("luci.http.protocol.date") local ltn12 = require("luci.ltn12") Luci = luci.util.class(luci.httpd.module.Handler) Response = luci.httpd.module.Response function Luci.__init__(self, limit) luci.httpd.module.Handler.__init__(self) self.limit = limit or 5 self.running = {} setmetatable(self.running, {__mode = "v"}) end function Luci.handle_head(self, ...) local response, sourceout = self:handle_get(...) return response end function Luci.handle_post(self, ...) return self:handle_get(...) end function Luci.handle_get(self, request, sourcein, sinkerr) if self.limit and #self.running >= self.limit then return self:failure(503, "Overload") end table.insert(self.running, coroutine.running()) local r = luci.http.Request( request.env, sourcein, sinkerr ) local res, id, data1, data2 = true, 0, nil, nil local headers = {} local status = 200 local active = true local x = coroutine.create(luci.dispatcher.httpdispatch) while not id or id < 3 do coroutine.yield() res, id, data1, data2 = coroutine.resume(x, r) if not res then status = 500 headers["Content-Type"] = "text/plain" local err = {id} return Response( status, headers ), function() return table.remove(err) end end if id == 1 then status = data1 elseif id == 2 then headers[data1] = data2 end end local function iter() local res, id, data = coroutine.resume(x) if not res then return nil, id elseif not id or not active then return true elseif id == 5 then active = false return nil elseif id == 4 then return data end if coroutine.status(x) == "dead" then return nil end end return Response(status, headers), iter end
--[[ HTTP server implementation for LuCI - luci handler (c) 2008 Steven Barth <[email protected]> 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.httpd.handler.luci", package.seeall) require("luci.dispatcher") require("luci.http") require("luci.http.protocol.date") local ltn12 = require("luci.ltn12") Luci = luci.util.class(luci.httpd.module.Handler) Response = luci.httpd.module.Response function Luci.__init__(self, limit) luci.httpd.module.Handler.__init__(self) self.limit = limit or 5 self.running = {} setmetatable(self.running, {__mode = "v"}) end function Luci.handle_head(self, ...) local response, sourceout = self:handle_get(...) return response end function Luci.handle_post(self, ...) return self:handle_get(...) end function Luci.handle_get(self, request, sourcein, sinkerr) if self.limit and #self.running >= self.limit then for k, v in ipairs(self.running) do if coroutine.status(v) == "dead" then collectgarbage() break end end if #self.running >= self.limit then return self:failure(503, "Overload") end end table.insert(self.running, coroutine.running()) local r = luci.http.Request( request.env, sourcein, sinkerr ) local res, id, data1, data2 = true, 0, nil, nil local headers = {} local status = 200 local active = true local x = coroutine.create(luci.dispatcher.httpdispatch) while not id or id < 3 do coroutine.yield() res, id, data1, data2 = coroutine.resume(x, r) if not res then status = 500 headers["Content-Type"] = "text/plain" local err = {id} return Response( status, headers ), function() return table.remove(err) end end if id == 1 then status = data1 elseif id == 2 then headers[data1] = data2 end end local function iter() local res, id, data = coroutine.resume(x) if not res then return nil, id elseif not id or not active then return true elseif id == 5 then active = false while (coroutine.resume(x)) do end return nil elseif id == 4 then return data end if coroutine.status(x) == "dead" then return nil end end return Response(status, headers), iter end
Fixed occasionally occuring "Overload"-problems with luci-httpd
Fixed occasionally occuring "Overload"-problems with luci-httpd git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@3073 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
gwlim/luci,eugenesan/openwrt-luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,gwlim/luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,projectbismark/luci-bismark,eugenesan/openwrt-luci,phi-psi/luci,saraedum/luci-packages-old,yeewang/openwrt-luci,stephank/luci,phi-psi/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,zwhfly/openwrt-luci,alxhh/piratenluci,dtaht/cerowrt-luci-3.3,phi-psi/luci,vhpham80/luci,ThingMesh/openwrt-luci,ch3n2k/luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,saraedum/luci-packages-old,Flexibity/luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,ch3n2k/luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,vhpham80/luci,8devices/carambola2-luci,freifunk-gluon/luci,zwhfly/openwrt-luci,alxhh/piratenluci,jschmidlapp/luci,zwhfly/openwrt-luci,freifunk-gluon/luci,Canaan-Creative/luci,yeewang/openwrt-luci,ch3n2k/luci,freifunk-gluon/luci,zwhfly/openwrt-luci,phi-psi/luci,vhpham80/luci,gwlim/luci,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,eugenesan/openwrt-luci,Flexibity/luci,saraedum/luci-packages-old,8devices/carambola2-luci,gwlim/luci,alxhh/piratenluci,stephank/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,projectbismark/luci-bismark,Canaan-Creative/luci,zwhfly/openwrt-luci,gwlim/luci,projectbismark/luci-bismark,projectbismark/luci-bismark,ch3n2k/luci,yeewang/openwrt-luci,ch3n2k/luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,alxhh/piratenluci,Canaan-Creative/luci,jschmidlapp/luci,stephank/luci,vhpham80/luci,gwlim/luci,ThingMesh/openwrt-luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,Flexibity/luci,phi-psi/luci,stephank/luci,vhpham80/luci,vhpham80/luci,Flexibity/luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,jschmidlapp/luci,jschmidlapp/luci,stephank/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,eugenesan/openwrt-luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,alxhh/piratenluci,Flexibity/luci,8devices/carambola2-luci,8devices/carambola2-luci,alxhh/piratenluci,yeewang/openwrt-luci,yeewang/openwrt-luci,jschmidlapp/luci,freifunk-gluon/luci,alxhh/piratenluci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,phi-psi/luci,jschmidlapp/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,jschmidlapp/luci,Canaan-Creative/luci,stephank/luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,ch3n2k/luci,Flexibity/luci,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,eugenesan/openwrt-luci,zwhfly/openwrt-luci,gwlim/luci,Flexibity/luci,projectbismark/luci-bismark,freifunk-gluon/luci,jschmidlapp/luci
7e9242cae92cb6c21819013c86bd2b5ec3fffa70
bam.lua
bam.lua
-- important paths sourcePath = "src/" objectPath = "obj/" testPath = "src/test/" testObjectPath = "obj/test/" -- set up compiler settings settings = NewSettings() -- full warning level, treat warnings as errors settings.cc.flags:Add("-Wall -Wextra -Werror") -- use fPIC for making a shared object settings.cc.flags:Add("-fPIC") -- output objects to obj directory settings.cc.Output = function(settings, input) return objectPath .. PathFilename(PathBase(input)) end -- collect sources and compile source = Collect(sourcePath .. "*.c") objects = Compile(settings, source) -- make shared objects libpotency = SharedLibrary(settings, "libpotency", objects) -- build test binary settings = NewSettings() -- full warning level, treat warnings as errors settings.cc.flags:Add("-Wall -Wextra -Werror") -- use fPIC for making a shared object settings.cc.flags:Add("-fPIC") settings.cc.includes:Add(sourcePath) settings.link.libpath:Add(".") settings.link.libs:Add("potency") -- output objects to obj directory settings.cc.Output = function(settings, input) return testObjectPath .. PathFilename(PathBase(input)) end -- compile test_potency test suite source = Collect(testPath .. "*.c") objects = Compile(settings, source) exe = Link(settings, "test_potency", objects)
-- important paths sourcePath = "src/" objectPath = "obj/" testPath = "src/test/" testObjectPath = "obj/test/" -- set up compiler settings settings = NewSettings() -- full warning level, treat warnings as errors settings.cc.flags:Add("-Wall -Wextra -Werror") -- use fPIC for making a shared object settings.cc.flags:Add("-fPIC") -- output objects to obj directory settings.cc.Output = function(settings, input) return objectPath .. PathFilename(PathBase(input)) end -- collect sources and compile source = Collect(sourcePath .. "*.c") objects = Compile(settings, source) -- make shared objects libpotency = SharedLibrary(settings, "libpotency", objects) -- build test binary settings = NewSettings() -- full warning level, treat warnings as errors settings.cc.flags:Add("-Wall -Wextra -Werror") -- use fPIC for making a shared object settings.cc.flags:Add("-fPIC") settings.cc.includes:Add(sourcePath) -- output objects to obj directory settings.cc.Output = function(settings, input) return testObjectPath .. PathFilename(PathBase(input)) end -- compile test_potency test suite source = Collect(testPath .. "*.c") objects = Compile(settings, source) exe = Link(settings, "test_potency", objects, libpotency)
fix multithreaded compilation race condition
fix multithreaded compilation race condition
Lua
isc
Potent-Code/potency,Potent-Code/potency,Potent-Code/potency
2c1e83677cb799b00b08f7270443399648e70419
Modules/ROBLOXAnimations/AnimationPlayer.lua
Modules/ROBLOXAnimations/AnimationPlayer.lua
local ReplicatedStorage = game:GetService("ReplicatedStorage") local NevermoreEngine = require(ReplicatedStorage:WaitForChild("NevermoreEngine")) local LoadCustomLibrary = NevermoreEngine.LoadLibrary local Signal = LoadCustomLibrary("Signal") local AnimationPlayer = {} AnimationPlayer.__index = AnimationPlayer AnimationPlayer.ClassName = "AnimationPlayer" -- Intent: Makes playing and loading tracks into a humanoid easy. -- @author Quenty function AnimationPlayer.new(Humanoid) local self = setmetatable({}, AnimationPlayer) self.Humanoid = Humanoid or error("No Humanoid") self.Tracks = {} self.FadeTime = 0.4 -- Default self.TrackPlayed = Signal.new() return self end function AnimationPlayer:WithAnimation(Animation) self.Tracks[Animation.Name] = self.Humanoid:LoadAnimation(Animation) return self end function AnimationPlayer:AddAnimation(Name, AnimationID) local Animation = Instance.new("Animation") Animation.AnimationId = "http://www.roblox.com/Asset?ID=" .. tonumber(AnimationID) or error("No AnimationID") Animation.Name = Name or error("No name") return self:WithAnimation(Animation) end function AnimationPlayer:GetTrack(TrackName) return self.Tracks[TrackName] or error("Track does not exist") end function AnimationPlayer:PlayTrack(TrackName, FadeTime, Weight, Speed, StopFadeTime) -- @param FadeTime How much time it will take to transition into the animation. -- @param Weight Acts as a multiplier for the offsets and rotations of the playing animation -- This parameter is extremely unstable. -- Any parameter higher than 1.5 will result in very shaky motion, and any parameter higher ' -- than 2 will almost always result in NAN errors. Use with caution. -- @param Speed The time scale of the animation. -- Setting this to 2 will make the animation 2x faster, and setting it to 0.5 will make it -- run 2x slower. FadeTime = FadeTime or self.FadeTime local Track = self:GetTrack(TrackName) if not Track.IsPlaying then self.TrackPlayed:fire(TrackName, FadeTime, Weight, Speed, StopFadeTime) self:StopAllTracks(StopFadeTime or FadeTime) Track:Play(FadeTime, Weight, Speed) end return Track end function AnimationPlayer:StopTrack(TrackName, FadeTime) FadeTime = FadeTime or self.FadeTime local Track = self:GetTrack(TrackName) Track:Stop(FadeTime) return Track end function AnimationPlayer:StopAllTracks(FadeTime) for TrackName, _ in pairs(self.Tracks) do self:StopTrack(TrackName, FadeTime) end end function AnimationPlayer:Destroy() self:StopAllTracks() setmetatable(self, nil) end return AnimationPlayer
local ReplicatedStorage = game:GetService("ReplicatedStorage") local NevermoreEngine = require(ReplicatedStorage:WaitForChild("NevermoreEngine")) local LoadCustomLibrary = NevermoreEngine.LoadLibrary local Signal = LoadCustomLibrary("Signal") local AnimationPlayer = {} AnimationPlayer.__index = AnimationPlayer AnimationPlayer.ClassName = "AnimationPlayer" -- Intent: Makes playing and loading tracks into a humanoid easy. -- @author Quenty function AnimationPlayer.new(Humanoid) local self = setmetatable({}, AnimationPlayer) self.Humanoid = Humanoid or error("No Humanoid") self.Tracks = {} self.FadeTime = 0.4 -- Default self.TrackPlayed = Signal.new() return self end function AnimationPlayer:WithAnimation(Animation) self.Tracks[Animation.Name] = self.Humanoid:LoadAnimation(Animation) return self end function AnimationPlayer:AddAnimation(Name, AnimationId) local Animation = Instance.new("Animation") if tonumber(AnimationId) then Animation.AnimationId = "http://www.roblox.com/Asset?ID=" .. tonumber(AnimationId) or error("No AnimationId") else Animation.AnimationId = AnimationId end Animation.Name = Name or error("No name") return self:WithAnimation(Animation) end function AnimationPlayer:GetTrack(TrackName) return self.Tracks[TrackName] or error("Track does not exist") end function AnimationPlayer:PlayTrack(TrackName, FadeTime, Weight, Speed, StopFadeTime) -- @param FadeTime How much time it will take to transition into the animation. -- @param Weight Acts as a multiplier for the offsets and rotations of the playing animation -- This parameter is extremely unstable. -- Any parameter higher than 1.5 will result in very shaky motion, and any parameter higher ' -- than 2 will almost always result in NAN errors. Use with caution. -- @param Speed The time scale of the animation. -- Setting this to 2 will make the animation 2x faster, and setting it to 0.5 will make it -- run 2x slower. FadeTime = FadeTime or self.FadeTime local Track = self:GetTrack(TrackName) if not Track.IsPlaying then self.TrackPlayed:fire(TrackName, FadeTime, Weight, Speed, StopFadeTime) self:StopAllTracks(StopFadeTime or FadeTime) Track:Play(FadeTime, Weight, Speed) end return Track end function AnimationPlayer:StopTrack(TrackName, FadeTime) FadeTime = FadeTime or self.FadeTime local Track = self:GetTrack(TrackName) Track:Stop(FadeTime) return Track end function AnimationPlayer:StopAllTracks(FadeTime) for TrackName, _ in pairs(self.Tracks) do self:StopTrack(TrackName, FadeTime) end end function AnimationPlayer:Destroy() self:StopAllTracks() setmetatable(self, nil) end return AnimationPlayer
Fixed animation player
Fixed animation player
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
4134bbf5ba5a7bd393b11a43d878b3e5c72f4713
src/attributeutils/src/Shared/RxAttributeUtils.lua
src/attributeutils/src/Shared/RxAttributeUtils.lua
--- -- @module RxAttributeUtils -- @author Quenty local require = require(script.Parent.loader).load(script) local Observable = require("Observable") local Maid = require("Maid") local RxAttributeUtils = {} function RxAttributeUtils.observeAttribute(instance, attributeName) assert(typeof(instance) == "Instance", "Bad instance") assert(type(attributeName) == "string", "Bad attributeName") return Observable.new(function(sub) local maid = Maid.new() maid:GiveTask(instance:GetAttributeChangedSignal(attributeName):Connect(function() sub:Fire(instance:GetAttribute(attributeName)) end)) sub:Fire(instance:GetAttribute(attributeName)) return maid end) end return RxAttributeUtils
--- -- @module RxAttributeUtils -- @author Quenty local require = require(script.Parent.loader).load(script) local Observable = require("Observable") local Maid = require("Maid") local RxAttributeUtils = {} function RxAttributeUtils.observeAttribute(instance, attributeName, defaultValue) assert(typeof(instance) == "Instance", "Bad instance") assert(type(attributeName) == "string", "Bad attributeName") return Observable.new(function(sub) local maid = Maid.new() local function update() local value = instance:GetAttribute(attributeName) if value == nil then sub:Fire(defaultValue) else sub:Fire(value) end end maid:GiveTask(instance:GetAttributeChangedSignal(attributeName):Connect(update)) update() return maid end) end return RxAttributeUtils
fix: Add default attribute utils
fix: Add default attribute utils
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
881d2acf6f4d1524c998cd59386138589293895f
item/id_164_emptybottle.lua
item/id_164_emptybottle.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/>. ]] -- Merung 2011: fill stock or potion into bottle -- UPDATE items SET itm_script='item.id_164_emptybottle' WHERE itm_id IN (164); local common = require("base.common") local alchemy = require("alchemy.base.alchemy") local licence = require("base.licence") local granorsHut = require("content.granorsHut") local M = {} function M.UseItem(User, SourceItem, ltstate) -- alchemy -- infront of a cauldron? local cauldron = alchemy.GetCauldronInfront(User) if cauldron then if cauldron:getData("granorsHut") ~= "" then granorsHut.fillingFromCauldron(User, ltstate) return end if licence.licence(User) then --checks if user is citizen or has a licence return -- avoids crafting if user is neither citizen nor has a licence end if not CheckWaterEmpty(User, SourceItem, cauldron) then return end if not alchemy.checkFood(User) then return end if ( ltstate == Action.abort ) then common.InformNLS(User, "Du brichst deine Arbeit ab.", "You abort your work.") return end if (ltstate == Action.none) then User:startAction(20,21,5,15,25); return end M.FillIntoBottle(User, SourceItem, cauldron) alchemy.lowerFood(User) end -- The Glutinous Tree local frontItem = common.GetFrontItem(User) if frontItem and frontItem.id == 589 and frontItem.pos == position(376,288,0) then GetSlimeFromTree(User, SourceItem, ltstate) end end function CheckWaterEmpty(User, SourceItem, cauldron) if (cauldron:getData("filledWith") == "water") then -- water belongs into a bucket, not a potion bottle! common.InformNLS( User, "Es ist zu viel Wasser im Kessel, als dass es in die Flaschen passen wrde. Ein Eimer wre hilfreicher.", "There is too much water in the cauldron to bottle it. Better use a bucket.") return nil ; -- no stock, no potion, not essence brew -> nothing we could fil into the bottle elseif cauldron:getData("filledWith") == "" then common.InformNLS( User, "Es befindet sich nichts zum Abfllen im Kessel.", "There is nothing to be bottled in the cauldron.") return nil; end return true end function M.FillIntoBottle(User, SourceItem, cauldron) -- stock, essence brew or potion; fill it up if (cauldron:getData("filledWith") == "stock") or (cauldron:getData("filledWith") == "essenceBrew") or (cauldron:getData("filledWith") == "potion") then local reGem, reGemdust, reCauldron, reBottle = alchemy.GemDustBottleCauldron(nil, nil, cauldron.id, nil, User) if SourceItem.number > 1 then -- stack! if cauldron:getData("filledWith") == "stock" then local data = {} data.AdrazinConcentration=cauldron:getData("AdrazinConcentration") data.IllidriumConcentration=cauldron:getData("IllidriumConcentration") data.CaprazinConcentration=cauldron:getData("CaprazinConcentration") data.HyperboreliumConcentration=cauldron:getData("HyperboreliumConcentration") data.EcholonConcentration=cauldron:getData("EcholonConcentration") data.DracolinConcentration=cauldron:getData("DracolinConcentration") data.OrcanolConcentration=cauldron:getData("OrcanolConcentration") data.FenolinConcentration=cauldron:getData("FenolinConcentration") data.filledWith="stock" User:createItem(reBottle, 1, 0, data) elseif cauldron:getData("filledWith") == "essenceBrew" then local data = {} data.essenceHerb1=cauldron:getData("essenceHerb1") data.essenceHerb2=cauldron:getData("essenceHerb2") data.essenceHerb3=cauldron:getData("essenceHerb3") data.essenceHerb4=cauldron:getData("essenceHerb4") data.essenceHerb5=cauldron:getData("essenceHerb5") data.essenceHerb6=cauldron:getData("essenceHerb6") data.essenceHerb7=cauldron:getData("essenceHerb7") data.essenceHerb8=cauldron:getData("essenceHerb8") data.filledWith="essenceBrew" User:createItem(reBottle, 1, 0, data) elseif cauldron:getData("filledWith") == "potion" then local data = {} data.potionEffectId=cauldron:getData("potionEffectId") data.filledWith="potion" User:createItem(reBottle, 1, tonumber(cauldron:getData("potionQuality")), data) end world:erase(SourceItem,1) else SourceItem.id = reBottle alchemy.FillFromTo(cauldron,SourceItem) world:changeItem(SourceItem) end alchemy.RemoveAll(cauldron) end world:changeItem(cauldron) world:makeSound(10,cauldron.pos) end function GetSlimeFromTree(User, SourceItem, ltstate) if ( ltstate == Action.abort ) then return end if (ltstate == Action.none) then User:startAction(50,21,5,0,0); return end if SourceItem.number > 1 then local data = {} data.filledWith="meraldilised slime" User:createItem(327, 1, 0, data) else SourceItem.id = 327 SourceItem:setData("filledWith","meraldilised slime") world:changeItem(SourceItem) end 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/>. ]] -- Merung 2011: fill stock or potion into bottle -- UPDATE items SET itm_script='item.id_164_emptybottle' WHERE itm_id IN (164); local common = require("base.common") local alchemy = require("alchemy.base.alchemy") local licence = require("base.licence") local granorsHut = require("content.granorsHut") local M = {} function M.UseItem(User, SourceItem, ltstate) -- alchemy -- infront of a cauldron? local cauldron = alchemy.GetCauldronInfront(User) if cauldron then if cauldron:getData("granorsHut") ~= "" then granorsHut.fillingFromCauldron(User, ltstate) return end if licence.licence(User) then --checks if user is citizen or has a licence return -- avoids crafting if user is neither citizen nor has a licence end if not CheckWaterEmpty(User, SourceItem, cauldron) then return end if not alchemy.checkFood(User) then return end if ( ltstate == Action.abort ) then common.InformNLS(User, "Du brichst deine Arbeit ab.", "You abort your work.") return end if (ltstate == Action.none) then User:startAction(20,21,5,15,25); return end M.FillIntoBottle(User, SourceItem, cauldron) alchemy.lowerFood(User) end -- The Glutinous Tree local frontItem = common.GetFrontItem(User) if frontItem and frontItem.id == 589 and frontItem.pos == position(376,288,0) then GetSlimeFromTree(User, SourceItem, ltstate) end end function CheckWaterEmpty(User, SourceItem, cauldron) if (cauldron:getData("filledWith") == "water") then -- water belongs into a bucket, not a potion bottle! common.InformNLS( User, "Es ist zu viel Wasser im Kessel, als dass es in die Flaschen passen wrde. Ein Eimer wre hilfreicher.", "There is too much water in the cauldron to bottle it. Better use a bucket.") return nil ; -- no stock, no potion, not essence brew -> nothing we could fil into the bottle elseif cauldron:getData("filledWith") == "" then common.InformNLS( User, "Es befindet sich nichts zum Abfllen im Kessel.", "There is nothing to be bottled in the cauldron.") return nil; end return true end function M.FillIntoBottle(User, SourceItem, cauldron) -- stock, essence brew or potion; fill it up if (cauldron:getData("filledWith") == "stock") or (cauldron:getData("filledWith") == "essenceBrew") or (cauldron:getData("filledWith") == "potion") then local reGem, reGemdust, reCauldron, reBottle = alchemy.GemDustBottleCauldron(nil, nil, cauldron.id, nil, User) if SourceItem.number > 1 then -- stack! if cauldron:getData("filledWith") == "stock" then local data = {} data.AdrazinConcentration=cauldron:getData("AdrazinConcentration") data.IllidriumConcentration=cauldron:getData("IllidriumConcentration") data.CaprazinConcentration=cauldron:getData("CaprazinConcentration") data.HyperboreliumConcentration=cauldron:getData("HyperboreliumConcentration") data.EcholonConcentration=cauldron:getData("EcholonConcentration") data.DracolinConcentration=cauldron:getData("DracolinConcentration") data.OrcanolConcentration=cauldron:getData("OrcanolConcentration") data.FenolinConcentration=cauldron:getData("FenolinConcentration") data.filledWith="stock" common.CreateItem(User, reBottle, 1, 0, data) elseif cauldron:getData("filledWith") == "essenceBrew" then local data = {} data.essenceHerb1=cauldron:getData("essenceHerb1") data.essenceHerb2=cauldron:getData("essenceHerb2") data.essenceHerb3=cauldron:getData("essenceHerb3") data.essenceHerb4=cauldron:getData("essenceHerb4") data.essenceHerb5=cauldron:getData("essenceHerb5") data.essenceHerb6=cauldron:getData("essenceHerb6") data.essenceHerb7=cauldron:getData("essenceHerb7") data.essenceHerb8=cauldron:getData("essenceHerb8") data.filledWith="essenceBrew" common.CreateItem(User, reBottle, 1, 0, data) elseif cauldron:getData("filledWith") == "potion" then local data = {} data.potionEffectId=cauldron:getData("potionEffectId") data.filledWith="potion" common.CreateItem(User, reBottle, 1, tonumber(cauldron:getData("potionQuality")), data) end world:erase(SourceItem,1) else SourceItem.id = reBottle alchemy.FillFromTo(cauldron,SourceItem) world:changeItem(SourceItem) end alchemy.RemoveAll(cauldron) end world:changeItem(cauldron) world:makeSound(10,cauldron.pos) end function GetSlimeFromTree(User, SourceItem, ltstate) if ( ltstate == Action.abort ) then return end if (ltstate == Action.none) then User:startAction(50,21,5,0,0); return end if SourceItem.number > 1 then local data = {} data.filledWith="meraldilised slime" common.CreateItem(User, 327, 1, 0, data) else SourceItem.id = 327 SourceItem:setData("filledWith","meraldilised slime") world:changeItem(SourceItem) end end return M
fix #0011309 Potions not created
fix #0011309 Potions not created use a common function to safely create the item
Lua
agpl-3.0
vilarion/Illarion-Content,KayMD/Illarion-Content,Illarion-eV/Illarion-Content,Baylamon/Illarion-Content
f58a5346dad4a3d7af9e3ed2e61b532df31ec01c
hammerspoon/Mute.lua
hammerspoon/Mute.lua
local M = {} M.device = hs.audiodevice.defaultInputDevice() M.micVolume = 0.0 M.muteSound = hs.sound.getByName("Mute"): volume(0.35) M.unmuteSound = hs.sound.getByName("Unmute"):volume(0.35) M.muteIcon = hs.image.imageFromPath( "~/Dropbox/config/OSX/Hammerspoon/Images/muted.png" ):setSize({h=18, w=18}, false) M.unmuteIcon = hs.image.imageFromPath( "~/Dropbox/config/OSX/Hammerspoon/Images/unmuted.png" ):setSize({h=18, w=18}, false) M.menubar = hs.menubar.new():setIcon(M.unmuteIcon) function M.toggle() inputVolume = M.device:inputVolume() if inputVolume > 0.0 then M.micVolume = inputVolume M.device:setInputVolume(0.0) M.muteSound:play() M.menubar:setIcon(M.muteIcon) else M.device:setInputVolume(M.micVolume) M.unmuteSound:play() M.menubar:setIcon(M.unmuteIcon) end end M.menubar:setClickCallback(M.toggle) return M
local M = {} M.device = hs.audiodevice.defaultInputDevice() M.micVolume = 75 M.muteSound = hs.sound.getByName("Mute"): volume(0.35) M.unmuteSound = hs.sound.getByName("Unmute"):volume(0.35) M.muteIcon = hs.image.imageFromPath( "~/Dropbox/config/OSX/Hammerspoon/Images/muted.png" ):setSize({h=18, w=18}, false) M.unmuteIcon = hs.image.imageFromPath( "~/Dropbox/config/OSX/Hammerspoon/Images/unmuted.png" ):setSize({h=18, w=18}, false) function M.toggle() inputVolume = M.device:inputVolume() if inputVolume > 0.0 then M.micVolume = inputVolume M.device:setInputVolume(0.0) M.muteSound:play() M.menubar:setIcon(M.muteIcon) else M.device:setInputVolume(M.micVolume) M.unmuteSound:play() M.menubar:setIcon(M.unmuteIcon) end end M.menubar = hs.menubar.new():setIcon(M.unmuteIcon):setClickCallback(M.toggle) return M
fewer lines, bug fixes
fewer lines, bug fixes
Lua
mit
rahulsalvi/dotfiles,rahulsalvi/dotfiles,rahulsalvi/dotfiles
af33824527bb99678ea39e5781adddcbe343a1d0
includes/path.lua
includes/path.lua
if not ophal.aliases.source then ophal.aliases.source = {} end if not ophal.aliases.alias then ophal.aliases.alias = {} end local explode = seawolf.text.explode local aliases = ophal.aliases function path_register_alias(path, alias) aliases.source[path] = alias aliases.alias[alias] = path end do local arguments function arg(index) local alias, result index = index + 1 if arguments == nil then q = request_path() arguments = explode('/', q ~= '' and q or settings.site.frontpage) end result = arguments[index] if result ~= nil then alias = aliases.alias[result] return alias and alias or result end end end local slash = settings.slash do local path_tree, path function init_path() local alias if path_tree == nil and path == nil then path_tree, path = {} -- build path tree for i = 1,8 do a = arg(i - 1) if a == nil or a == '' then break else path = (path or '') .. (path and slash or '') .. (a or '') table.insert(path_tree, path) end end if not #path_tree then error 'Menu system error!' end end return path_tree, path end end function url(path, options) if options == nil then options = {} end if path == nil then path = '' end if not (options.alias or options.external) then alias = aliases.source[path] if alias then path = alias end end if options.external then return path end return (options.absolute and base_root or '') .. base_path .. path end function l(text, path, options) if options == nil then options = {} end local attributes = options.attributes or {} options.attributes = nil return theme{'a', text = text, path = url(path, options), attributes = attributes, } end
if not ophal.aliases.source then ophal.aliases.source = {} end if not ophal.aliases.alias then ophal.aliases.alias = {} end local explode = seawolf.text.explode local aliases = ophal.aliases function path_register_alias(path, alias) aliases.source[path] = alias aliases.alias[alias] = path end do local arguments function arg(index) local source, rp index = index + 1 if arguments == nil then rp = request_path() source = aliases.alias[rp] if source then rp = source end arguments = explode('/', rp ~= '' and rp or settings.site.frontpage) end return arguments[index] end end local slash = settings.slash do local path_tree, path function init_path() local alias if path_tree == nil and path == nil then path_tree, path = {} -- build path tree for i = 1,8 do a = arg(i - 1) if a == nil or a == '' then break else path = (path or '') .. (path and slash or '') .. (a or '') table.insert(path_tree, path) end end if not #path_tree then error 'Menu system error!' end end return path_tree, path end end function url(path, options) if options == nil then options = {} end if path == nil then path = '' end if not (options.alias or options.external) then alias = aliases.source[path] if alias then path = alias end end if options.external then return path end return (options.absolute and base_root or '') .. base_path .. path end function l(text, path, options) if options == nil then options = {} end local attributes = options.attributes or {} options.attributes = nil return theme{'a', text = text, path = url(path, options), attributes = attributes, } end
Bug fix: path aliases mixed with source paths.
Bug fix: path aliases mixed with source paths.
Lua
agpl-3.0
ophal/core,coinzen/coinage,coinzen/coinage,ophal/core,ophal/core,coinzen/coinage
acc7755b9ea4edef3aca57aa90a417c098325a81
SVUI_!Core/system/_reports/artifact.lua
SVUI_!Core/system/_reports/artifact.lua
--[[ ############################################################################## S V U I By: Failcoder ############################################################################## ########################################################## LOCALIZED LUA FUNCTIONS ########################################################## ]]-- --[[ GLOBALS ]]-- local _G = _G; local select = _G.select; local pairs = _G.pairs; local ipairs = _G.ipairs; local type = _G.type; local error = _G.error; local pcall = _G.pcall; local assert = _G.assert; local tostring = _G.tostring; local tonumber = _G.tonumber; local string = _G.string; local math = _G.math; local table = _G.table; --[[ STRING METHODS ]]-- local lower, upper = string.lower, string.upper; local find, format, len, split = string.find, string.format, string.len, string.split; local match, sub, join = string.match, string.sub, string.join; local gmatch, gsub = string.gmatch, string.gsub; --[[ MATH METHODS ]]-- local abs, ceil, floor, round = math.abs, math.ceil, math.floor, math.round; -- Basic --[[ TABLE METHODS ]]-- local twipe, tsort = table.wipe, table.sort; --[[ ########################################################## GET ADDON DATA ########################################################## ]]-- local SV = select(2, ...) local L = SV.L local Reports = SV.Reports; local LAD = LibStub("LibArtifactData-1.0"); --[[ ########################################################## UTILITIES ########################################################## ]]-- local function GetArtifactData() local artID = LAD:GetActiveArtifactID() if not artID then return false end local data = nil artID, data = LAD:GetArtifactInfo(artID) if not artID then return false end return true, data.numRanksPurchased, data.power, data.maxPower , data.numRanksPurchasable end local function SetTooltipText(report) Reports:SetDataTip(report) local isEquipped, rank, currentPower,powerToNextLevel,pointsToSpend = GetArtifactData() Reports.ToolTip:AddLine(L["Artifact Power"]) Reports.ToolTip:AddLine(" ") if isEquipped then local calc1 = (currentPower / powerToNextLevel) * 100; Reports.ToolTip:AddDoubleLine(L["Rank:"], (" %d "):format(rank), 1, 1, 1) Reports.ToolTip:AddDoubleLine(L["Current Artifact Power:"], (" %d / %d (%d%%)"):format(currentPower, powerToNextLevel, calc1), 1, 1, 1) Reports.ToolTip:AddDoubleLine(L["Remaining:"], (" %d "):format(powerToNextLevel - currentPower), 1, 1, 1) Reports.ToolTip:AddDoubleLine(L["Points to Spend:"], format(" %d ", pointsToSpend), 1, 1, 1) else Reports.ToolTip:AddDoubleLine(L["No Artifact"]) end end local function FormatPower(rank, currentPower, powerForNextPoint, pointsToSpend) local currentText = ("%d(+%d) %d/%d"):format(rank, pointsToSpend, currentPower, powerForNextPoint); return currentText end --[[ ########################################################## REPORT TEMPLATE ########################################################## ]]-- local REPORT_NAME = "Artifact"; local HEX_COLOR = "22FFFF"; --SV.media.color.green --SV.media.color.normal --r, g, b = 0.8, 0.8, 0.8 --local c = SV.media.color.green --r, g, b = c[1], c[2], c[3] local Report = Reports:NewReport(REPORT_NAME, { type = "data source", text = REPORT_NAME .. " Info", icon = [[Interface\Addons\SVUI_!Core\assets\icons\SVUI]] }); Report.events = {"PLAYER_ENTERING_WORLD"}; Report.OnEvent = function(self, event, ...) Report.Populate(self) end Report.Populate = function(self) if self.barframe:IsShown() then self.text:SetAllPoints(self) self.text:SetJustifyH("CENTER") self.barframe:Hide() end local isEquipped,rank,currentPower,powerToNextLevel,pointsToSpend = GetArtifactData() if isEquipped then local text = FormatPower(rank, currentPower,powerToNextLevel,pointsToSpend); self.text:SetText(text) else self.text:SetText(L["No Artifact"]) end end Report.OnEnter = function(self) SetTooltipText(self) Reports:ShowDataTip() end Report.OnInit = function(self) LAD.RegisterCallback(self,"ARTIFACT_ADDED", function () Report.Populate(self) end) LAD.RegisterCallback(self,"ARTIFACT_ACTIVE_CHANGED", function () Report.Populate(self) end) LAD.RegisterCallback(self,"ARTIFACT_POWER_CHANGED", function () Report.Populate(self) end) end --[[ ########################################################## BAR TYPE ########################################################## ]]-- local BAR_NAME = "Artifact Bar"; local ReportBar = Reports:NewReport(BAR_NAME, { type = "data source", text = BAR_NAME, icon = [[Interface\Addons\SVUI_!Core\assets\icons\SVUI]] }); ReportBar.events = {"PLAYER_ENTERING_WORLD"}; ReportBar.OnEvent = function(self, event, ...) ReportBar.Populate(self) end ReportBar.Populate = function(self) if (not self.barframe:IsShown())then self.barframe:Show() self.barframe.icon.texture:SetTexture(SV.media.dock.artifactLabel) end local bar = self.barframe.bar; local isEquipped, rank, currentPower, powerToNextLevel, pointsToSpend = GetArtifactData() if isEquipped then bar:SetMinMaxValues(0, powerToNextLevel) bar:SetValue(currentPower) bar:SetStatusBarColor(0.9, 0.64, 0.37) local toSpend = "" if pointsToSpend>0 then toSpend = " (+"..pointsToSpend..")" end self.text:SetText(rank..toSpend) else bar:SetMinMaxValues(0, 1) bar:SetValue(0) self.text:SetText(L["No Artifact"]) end end ReportBar.OnEnter = function(self) SetTooltipText(self) Reports:ShowDataTip() end ReportBar.OnInit = function(self) LAD.RegisterCallback(self,"ARTIFACT_ADDED", function () ReportBar.Populate(self) end) LAD.RegisterCallback(self,"ARTIFACT_ACTIVE_CHANGED", function () ReportBar.Populate(self) end) LAD.RegisterCallback(self,"ARTIFACT_POWER_CHANGED", function () ReportBar.Populate(self) end) end
--[[ ############################################################################## S V U I By: Failcoder ############################################################################## ########################################################## LOCALIZED LUA FUNCTIONS ########################################################## ]]-- --[[ GLOBALS ]]-- local _G = _G; local select = _G.select; local pairs = _G.pairs; local ipairs = _G.ipairs; local type = _G.type; local error = _G.error; local pcall = _G.pcall; local assert = _G.assert; local tostring = _G.tostring; local tonumber = _G.tonumber; local string = _G.string; local math = _G.math; local table = _G.table; --[[ STRING METHODS ]]-- local lower, upper = string.lower, string.upper; local find, format, len, split = string.find, string.format, string.len, string.split; local match, sub, join = string.match, string.sub, string.join; local gmatch, gsub = string.gmatch, string.gsub; --[[ MATH METHODS ]]-- local abs, ceil, floor, round = math.abs, math.ceil, math.floor, math.round; -- Basic --[[ TABLE METHODS ]]-- local twipe, tsort = table.wipe, table.sort; --[[ ########################################################## GET ADDON DATA ########################################################## ]]-- local SV = select(2, ...) local L = SV.L local Reports = SV.Reports; local LAD = LibStub("LibArtifactData-1.0"); --[[ ########################################################## UTILITIES ########################################################## ]]-- local function GetArtifactData() local artID = LAD:GetActiveArtifactID() if not artID then return false end local data = nil artID, data = LAD:GetArtifactInfo(artID) if not artID then return false end return true, data.numRanksPurchased, data.power, data.maxPower , data.numRanksPurchasable end local function SetTooltipText(report) Reports:SetDataTip(report) local isEquipped, rank, currentPower,powerToNextLevel,pointsToSpend = GetArtifactData() Reports.ToolTip:AddLine(L["Artifact Power"]) Reports.ToolTip:AddLine(" ") if isEquipped then local calc1 = (currentPower / powerToNextLevel) * 100; Reports.ToolTip:AddDoubleLine(L["Rank:"], (" %d "):format(rank), 1, 1, 1) Reports.ToolTip:AddDoubleLine(L["Current Artifact Power:"], (" %d / %d (%d%%)"):format(currentPower, powerToNextLevel, calc1), 1, 1, 1) Reports.ToolTip:AddDoubleLine(L["Remaining:"], (" %d "):format(powerToNextLevel - currentPower), 1, 1, 1) Reports.ToolTip:AddDoubleLine(L["Points to Spend:"], format(" %d ", pointsToSpend), 1, 1, 1) else Reports.ToolTip:AddDoubleLine(L["No Artifact"]) end end local function FormatPower(rank, currentPower, powerForNextPoint, pointsToSpend) local currentText = ("%d(+%d) %d/%d"):format(rank, pointsToSpend, currentPower, powerForNextPoint); return currentText end --[[ ########################################################## REPORT TEMPLATE ########################################################## ]]-- local REPORT_NAME = "Artifact"; local HEX_COLOR = "22FFFF"; --SV.media.color.green --SV.media.color.normal --r, g, b = 0.8, 0.8, 0.8 --local c = SV.media.color.green --r, g, b = c[1], c[2], c[3] local Report = Reports:NewReport(REPORT_NAME, { type = "data source", text = REPORT_NAME .. " Info", icon = [[Interface\Addons\SVUI_!Core\assets\icons\SVUI]] }); Report.events = {"PLAYER_ENTERING_WORLD"}; Report.OnEvent = function(self, event, ...) LAD.RegisterCallback(self,"ARTIFACT_ADDED", function () Report.Populate(self) end) LAD.RegisterCallback(self,"ARTIFACT_ACTIVE_CHANGED", function () Report.Populate(self) end) LAD.RegisterCallback(self,"ARTIFACT_POWER_CHANGED", function () Report.Populate(self) end) end Report.Populate = function(self) if self.barframe:IsShown() then self.text:SetAllPoints(self) self.text:SetJustifyH("CENTER") self.barframe:Hide() end local isEquipped,rank,currentPower,powerToNextLevel,pointsToSpend = GetArtifactData() if isEquipped then local text = FormatPower(rank, currentPower,powerToNextLevel,pointsToSpend); self.text:SetText(text) else self.text:SetText(L["No Artifact"]) end end Report.OnEnter = function(self) SetTooltipText(self) Reports:ShowDataTip() end Report.OnInit = function(self) end --[[ ########################################################## BAR TYPE ########################################################## ]]-- local BAR_NAME = "Artifact Bar"; local ReportBar = Reports:NewReport(BAR_NAME, { type = "data source", text = BAR_NAME, icon = [[Interface\Addons\SVUI_!Core\assets\icons\SVUI]] }); ReportBar.events = {"PLAYER_ENTERING_WORLD"}; ReportBar.OnEvent = function(self, event, ...) LAD.RegisterCallback(self,"ARTIFACT_ADDED", function () ReportBar.Populate(self) end) LAD.RegisterCallback(self,"ARTIFACT_ACTIVE_CHANGED", function () ReportBar.Populate(self) end) LAD.RegisterCallback(self,"ARTIFACT_POWER_CHANGED", function () ReportBar.Populate(self) end) end ReportBar.Populate = function(self) if (not self.barframe:IsShown())then self.barframe:Show() self.barframe.icon.texture:SetTexture(SV.media.dock.artifactLabel) end local bar = self.barframe.bar; local isEquipped, rank, currentPower, powerToNextLevel, pointsToSpend = GetArtifactData() if isEquipped then bar:SetMinMaxValues(0, powerToNextLevel) bar:SetValue(currentPower) bar:SetStatusBarColor(0.9, 0.64, 0.37) local toSpend = "" if pointsToSpend>0 then toSpend = " (+"..pointsToSpend..")" end self.text:SetText(rank..toSpend) else bar:SetMinMaxValues(0, 1) bar:SetValue(0) self.text:SetText(L["No Artifact"]) end end ReportBar.OnEnter = function(self) SetTooltipText(self) Reports:ShowDataTip() end ReportBar.OnInit = function(self) end
Attempted fix for artifact weirdness
Attempted fix for artifact weirdness change artifact to only populate after PLAYER_ENTERING_WORLD
Lua
mit
FailcoderAddons/supervillain-ui,finalsliver/supervillain-ui
c801638a2dbd750ff0793bc2b4da2cb8ad41cb3c
MMOCoreORB/bin/scripts/object/draft_schematic/furniture/city/furniture_fountain.lua
MMOCoreORB/bin/scripts/object/draft_schematic/furniture/city/furniture_fountain.lua
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --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 Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_draft_schematic_furniture_city_furniture_fountain = object_draft_schematic_furniture_city_shared_furniture_fountain:new { templateType = DRAFTSCHEMATIC, customObjectName = "Fountain", craftingToolTab = 512, -- (See DraftSchemticImplementation.h) complexity = 21, size = 2, xpType = "crafting_structure_general", xp = 3300, assemblySkill = "structure_assembly", experimentingSkill = "structure_experimentation", customizationSkill = "structure_customization", customizationOptions = {}, customizationStringNames = {}, customizationDefaults = {}, ingredientTemplateNames = {"craft_furniture_ingredients_n", "craft_furniture_ingredients_n", "craft_furniture_ingredients_n"}, ingredientTitleNames = {"fountain", "water_pump", "water"}, ingredientSlotType = {0, 0, 0}, resourceTypes = {"ore", "metal", "water"}, resourceQuantities = {1000, 300, 500}, contribution = {100, 100, 100}, targetTemplate = "object/tangible/furniture/city/fountain_generic.iff", additionalTemplates = { "object/tangible/furniture/city/shared_fountain_brazier_round.iff", "object/tangible/furniture/city/shared_fountain_brazier_square.iff", "object/tangible/furniture/city/shared_fountain_circle.iff", "object/tangible/furniture/city/shared_fountain_contemplate.iff", "object/tangible/furniture/city/shared_fountain_heroic.iff", "object/tangible/furniture/city/shared_shared_fountain_rectangle.iff", } } ObjectTemplates:addTemplate(object_draft_schematic_furniture_city_furniture_fountain, "object/draft_schematic/furniture/city/furniture_fountain.iff")
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --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 Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_draft_schematic_furniture_city_furniture_fountain = object_draft_schematic_furniture_city_shared_furniture_fountain:new { templateType = DRAFTSCHEMATIC, customObjectName = "Fountain", craftingToolTab = 512, -- (See DraftSchemticImplementation.h) complexity = 21, size = 2, xpType = "crafting_structure_general", xp = 3300, assemblySkill = "structure_assembly", experimentingSkill = "structure_experimentation", customizationSkill = "structure_customization", customizationOptions = {}, customizationStringNames = {}, customizationDefaults = {}, ingredientTemplateNames = {"craft_furniture_ingredients_n", "craft_furniture_ingredients_n", "craft_furniture_ingredients_n"}, ingredientTitleNames = {"fountain", "water_pump", "water"}, ingredientSlotType = {0, 0, 0}, resourceTypes = {"ore", "metal", "water"}, resourceQuantities = {1000, 300, 500}, contribution = {100, 100, 100}, targetTemplate = "object/tangible/furniture/city/fountain_generic.iff", additionalTemplates = { "object/tangible/furniture/city/shared_fountain_brazier_round.iff", "object/tangible/furniture/city/shared_fountain_brazier_square.iff", "object/tangible/furniture/city/shared_fountain_circle.iff", "object/tangible/furniture/city/shared_fountain_contemplate.iff", "object/tangible/furniture/city/shared_fountain_heroic.iff", "object/tangible/furniture/city/shared_fountain_rectangle.iff", } } ObjectTemplates:addTemplate(object_draft_schematic_furniture_city_furniture_fountain, "object/draft_schematic/furniture/city/furniture_fountain.iff")
[Fixed] Typo in fountain schematic
[Fixed] Typo in fountain schematic Change-Id: I5798545f20f9bb9fdb045f9edf32506bb668791a
Lua
agpl-3.0
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo
b5365b9af7280a1f0810226559c88ec84bcb8395
spec/write_rockspec_spec.lua
spec/write_rockspec_spec.lua
local test_env = require("test/test_environment") local lfs = require("lfs") local run = test_env.run test_env.unload_luarocks() describe("LuaRocks write_rockspec tests #blackbox #b_write_rockspec", function() before_each(function() test_env.setup_specs() end) describe("LuaRocks write_rockspec basic tests", function() it("LuaRocks write_rockspec with no flags/arguments", function() assert.is_true(run.luarocks_bool("write_rockspec")) os.remove("luarocks-scm-1.rockspec") end) it("LuaRocks write_rockspec with invalid argument", function() assert.is_false(run.luarocks_bool("write_rockspec invalid")) end) it("LuaRocks write_rockspec invalid zip", function() assert.is_false(run.luarocks_bool("write_rockspec http://example.com/invalid.zip")) end) end) describe("LuaRocks write_rockspec more complex tests", function() it("LuaRocks write_rockspec git luarocks", function() assert.is_true(run.luarocks_bool("write_rockspec git://github.com/keplerproject/luarocks")) assert.is.truthy(lfs.attributes("luarocks-scm-1.rockspec")) assert.is_true(os.remove("luarocks-scm-1.rockspec")) end) it("LuaRocks write_rockspec git luarocks --tag=v2.3.0", function() assert.is_true(run.luarocks_bool("write_rockspec git://github.com/keplerproject/luarocks --tag=v2.3.0")) assert.is.truthy(lfs.attributes("luarocks-2.3.0-1.rockspec")) assert.is_true(os.remove("luarocks-2.3.0-1.rockspec")) end) it("LuaRocks write_rockspec git luarocks with format flag", function() assert.is_true(run.luarocks_bool("write_rockspec git://github.com/mbalmer/luarocks --rockspec-format=1.1 --lua-version=5.1,5.2")) assert.is.truthy(lfs.attributes("luarocks-scm-1.rockspec")) assert.is_true(os.remove("luarocks-scm-1.rockspec")) end) it("LuaRocks write_rockspec git luarocks with full flags", function() assert.is_true(run.luarocks_bool("write_rockspec git://github.com/mbalmer/luarocks --lua-version=5.1,5.2 --license=\"MIT/X11\" " .. " --homepage=\"http://www.luarocks.org\" --summary=\"A package manager for Lua modules\" ")) assert.is.truthy(lfs.attributes("luarocks-scm-1.rockspec")) assert.is_true(os.remove("luarocks-scm-1.rockspec")) end) it("LuaRocks write_rockspec rockspec via http", function() assert.is_true(run.luarocks_bool("write_rockspec http://luarocks.org/releases/luarocks-2.1.0.tar.gz --lua-version=5.1")) assert.is.truthy(lfs.attributes("luarocks-2.1.0-1.rockspec")) assert.is_true(os.remove("luarocks-2.1.0-1.rockspec")) end) it("LuaRocks write_rockspec base dir, luassert.tar.gz via https", function() assert.is_true(run.luarocks_bool("write_rockspec https://github.com/downloads/Olivine-Labs/luassert/luassert-1.2.tar.gz --lua-version=5.1")) assert.is.truthy(lfs.attributes("luassert-1.2-1.rockspec")) assert.is_true(os.remove("luassert-1.2-1.rockspec")) end) it("LuaRocks write_rockspec git luafcgi with many flags", function() assert.is_true(run.luarocks_bool("write_rockspec git://github.com/mbalmer/luafcgi --lib=fcgi --license=\"3-clause BSD\" " .. "--lua-version=5.1,5.2")) assert.is.truthy(lfs.attributes("luafcgi-scm-1.rockspec")) -- TODO maybe read it content and find arguments from flags? assert.is_true(os.remove("luafcgi-scm-1.rockspec")) end) end) end)
local test_env = require("test/test_environment") local lfs = require("lfs") local run = test_env.run test_env.unload_luarocks() describe("LuaRocks write_rockspec tests #blackbox #b_write_rockspec", function() before_each(function() test_env.setup_specs() end) describe("LuaRocks write_rockspec basic tests", function() it("LuaRocks write_rockspec with no flags/arguments", function() assert.is_true(run.luarocks_bool("write_rockspec")) os.remove("luarocks-dev-1.rockspec") end) it("LuaRocks write_rockspec with invalid argument", function() assert.is_false(run.luarocks_bool("write_rockspec invalid")) end) it("LuaRocks write_rockspec invalid zip", function() assert.is_false(run.luarocks_bool("write_rockspec http://example.com/invalid.zip")) end) end) describe("LuaRocks write_rockspec more complex tests", function() it("LuaRocks write_rockspec git luarocks", function() assert.is_true(run.luarocks_bool("write_rockspec git://github.com/keplerproject/luarocks")) assert.is.truthy(lfs.attributes("luarocks-dev-1.rockspec")) assert.is_true(os.remove("luarocks-dev-1.rockspec")) end) it("LuaRocks write_rockspec git luarocks --tag=v2.3.0", function() assert.is_true(run.luarocks_bool("write_rockspec git://github.com/keplerproject/luarocks --tag=v2.3.0")) assert.is.truthy(lfs.attributes("luarocks-2.3.0-1.rockspec")) assert.is_true(os.remove("luarocks-2.3.0-1.rockspec")) end) it("LuaRocks write_rockspec git luarocks with format flag", function() assert.is_true(run.luarocks_bool("write_rockspec git://github.com/luarocks/luarocks --rockspec-format=1.1 --lua-version=5.1,5.2")) assert.is.truthy(lfs.attributes("luarocks-dev-1.rockspec")) assert.is_true(os.remove("luarocks-dev-1.rockspec")) end) it("LuaRocks write_rockspec git luarocks with full flags", function() assert.is_true(run.luarocks_bool("write_rockspec git://github.com/luarocks/luarocks --lua-version=5.1,5.2 --license=\"MIT/X11\" " .. " --homepage=\"http://www.luarocks.org\" --summary=\"A package manager for Lua modules\" ")) assert.is.truthy(lfs.attributes("luarocks-dev-1.rockspec")) assert.is_true(os.remove("luarocks-dev-1.rockspec")) end) it("LuaRocks write_rockspec rockspec via http", function() assert.is_true(run.luarocks_bool("write_rockspec http://luarocks.org/releases/luarocks-2.1.0.tar.gz --lua-version=5.1")) assert.is.truthy(lfs.attributes("luarocks-2.1.0-1.rockspec")) assert.is_true(os.remove("luarocks-2.1.0-1.rockspec")) end) it("LuaRocks write_rockspec base dir, luassert.tar.gz via https", function() assert.is_true(run.luarocks_bool("write_rockspec https://github.com/downloads/Olivine-Labs/luassert/luassert-1.2.tar.gz --lua-version=5.1")) assert.is.truthy(lfs.attributes("luassert-1.2-1.rockspec")) assert.is_true(os.remove("luassert-1.2-1.rockspec")) end) it("LuaRocks write_rockspec git luafcgi with many flags", function() assert.is_true(run.luarocks_bool("write_rockspec git://github.com/mbalmer/luafcgi --lib=fcgi --license=\"3-clause BSD\" " .. "--lua-version=5.1,5.2")) assert.is.truthy(lfs.attributes("luafcgi-dev-1.rockspec")) -- TODO maybe read it content and find arguments from flags? assert.is_true(os.remove("luafcgi-dev-1.rockspec")) end) end) end)
Tests: fix write_rockspec tests wrt scm -> dev
Tests: fix write_rockspec tests wrt scm -> dev
Lua
mit
keplerproject/luarocks,tarantool/luarocks,tarantool/luarocks,keplerproject/luarocks,luarocks/luarocks,luarocks/luarocks,luarocks/luarocks,tarantool/luarocks,keplerproject/luarocks,keplerproject/luarocks
8b09b5134262bbe766c79c8e123d79726229eb5e
src/latclient/starlight.lua
src/latclient/starlight.lua
-- This file is part of the Lua@Client project -- Copyright (c) 2015 Etiene Dalcol -- License: MIT local M = { js_served = false, modules_served = {} } local common = require "latclient.common" function M.get_header(s) if M.js_served == false then M.js_served = true local header = [[ <script src="{url}/starlight/starlight.min.js"></script> <script src="{url}/starlight/parser.min.js"></script> <script src="{url}/starlight/babel.min.js"></script> <script src="{url}/starlight/DOMAPI.min.js"></script> <script src="{url}/starlight/latclient.js"></script> ]] header = string.gsub(header, "{url}", M.js_url) s = header..s end return s end function M.get_client_js(s) local modules = M.get_modules(s) s = common.js_string_escape(s) s = '<script>'..modules..'(starlight.parser.parse('..s..'))();</script>' return M.get_header(s) end function M.get_modules(s) local modules = "" for name in string.gfind(s, "require%s*%(?[\"'](.-)[\"']%)?") do if not M.modules_served[name] then local module_file = common.search_module_path(name) if module_file then local file = io.open(module_file,'r') local file_str = file:read("*a") file:close() local lua_code = "rawset(package.preload, '" .. name.. [[', function(...) ]] .. file_str .. [[ end)]] lua_code = common.js_string_escape(lua_code) modules = modules .. '(starlight.parser.parse('..lua_code..'))(); ' M.modules_served[name] = true end end end return modules end return M
-- This file is part of the Lua@Client project -- v0.2 -- Copyright (c) 2015 Etiene Dalcol -- License: MIT local M = { js_served = false, modules_served = {} } local common = require "latclient.common" function M.get_header(s) if M.js_served == false then M.js_served = true local header = [[ <!-- While target browsers don't support ES6 natively, include Babel parser --> <script src="{url}/starlight/browser.5.8.34.min.js"></script> <script src="{url}/starlight/starlight.js" data-run-script-tags></script> <!-- Starlight! --> ]] header = string.gsub(header, "{url}", M.js_url) s = s..header end return s end function M.get_client_js(s) local modules = M.get_modules(s) s = modules..M.wrap_code(s) return M.get_header(s) end function M.wrap_code(s,module_name) local mod = module_name and table.concat{'data-modname="',module_name,'"'} or '' return table.concat({ '<script type="application/x-lua"', mod, '>', s, '</script>' }, '\n') end function M.get_modules(s) local modules = "" for name in string.gfind(s, "require%s*%(?[\"'](.-)[\"']%)?") do if not M.modules_served[name] then local module_file = common.search_module_path(name) if module_file then local file = io.open(module_file,'r') local file_str = file:read("*a") file:close() modules = modules..M.wrap_code(file_str,name) M.modules_served[name] = true end end end return modules end return M
fix(starlight) Adds new starlight latclient module
fix(starlight) Adds new starlight latclient module
Lua
mit
mpeterv/sailor,Etiene/sailor,Etiene/sailor,sailorproject/sailor,mpeterv/sailor
c24498a9197231eccd8e6aa0b6b17ca4b7718d90
src/program/packetblaster/replay/replay.lua
src/program/packetblaster/replay/replay.lua
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local engine = require("core.app") local config = require("core.config") local timer = require("core.timer") local pci = require("lib.hardware.pci") local intel10g = require("apps.intel.intel10g") local basic_apps = require("apps.basic.basic_apps") local main = require("core.main") local PcapReader= require("apps.pcap.pcap").PcapReader local LoadGen = require("apps.intel.loadgen").LoadGen local lib = require("core.lib") local ffi = require("ffi") local usage = require("program.packetblaster.replay.README_inc") local long_opts = { duration = "D", help = "h" } function run (args) local opt = {} local mode = table.remove(args, 1) local duration local c = config.new() function opt.D (arg) duration = assert(tonumber(arg), "duration is not a number!") end function opt.h (arg) print(usage) main.exit(1) end args = lib.dogetopt(args, opt, "hD:", long_opts) local filename = table.remove(args, 1) config.app(c, "pcap", PcapReader, filename) config.app(c, "loop", basic_apps.Repeater) config.app(c, "source", basic_apps.Tee) config.link(c, "pcap.output -> loop.input") config.link(c, "loop.output -> source.input") local patterns = args local nics = 0 pci.scan_devices() for _,device in ipairs(pci.devices) do if is_device_suitable(device, patterns) then nics = nics + 1 local name = "nic"..nics config.app(c, name, LoadGen, device.pciaddress) config.link(c, "source."..tostring(nics).."->"..name..".input") end end assert(nics > 0, "<PCI> matches no suitable devices.") engine.busywait = true intel10g.num_descriptors = 32*1024 engine.configure(c) local fn = function () print("Transmissions (last 1 sec):") engine.report_apps() end local t = timer.new("report", fn, 1e9, 'repeating') timer.activate(t) if duration then engine.main({duration=duration}) else engine.main() end end function is_device_suitable (pcidev, patterns) if not pcidev.usable or pcidev.driver ~= 'apps.intel.intel_app' then return false end if #patterns == 0 then return true end for _, pattern in ipairs(patterns) do if pci.qualified(pcidev.pciaddress):gmatch(pattern)() then return true end end end
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local engine = require("core.app") local config = require("core.config") local timer = require("core.timer") local pci = require("lib.hardware.pci") local intel10g = require("apps.intel.intel10g") local basic_apps = require("apps.basic.basic_apps") local main = require("core.main") local PcapReader= require("apps.pcap.pcap").PcapReader local LoadGen = require("apps.intel.loadgen").LoadGen local lib = require("core.lib") local ffi = require("ffi") local usage = require("program.packetblaster.replay.README_inc") local long_opts = { duration = "D", help = "h" } function run (args) local opt = {} local duration local c = config.new() function opt.D (arg) duration = assert(tonumber(arg), "duration is not a number!") end function opt.h (arg) print(usage) main.exit(1) end args = lib.dogetopt(args, opt, "hD:", long_opts) local filename = table.remove(args, 1) print (string.format("filename=%s", filename)) config.app(c, "pcap", PcapReader, filename) config.app(c, "loop", basic_apps.Repeater) config.app(c, "source", basic_apps.Tee) config.link(c, "pcap.output -> loop.input") config.link(c, "loop.output -> source.input") local patterns = args local nics = 0 pci.scan_devices() for _,device in ipairs(pci.devices) do if is_device_suitable(device, patterns) then nics = nics + 1 local name = "nic"..nics config.app(c, name, LoadGen, device.pciaddress) config.link(c, "source."..tostring(nics).."->"..name..".input") end end assert(nics > 0, "<PCI> matches no suitable devices.") engine.busywait = true intel10g.num_descriptors = 32*1024 engine.configure(c) local fn = function () print("Transmissions (last 1 sec):") engine.report_apps() end local t = timer.new("report", fn, 1e9, 'repeating') timer.activate(t) if duration then engine.main({duration=duration}) else engine.main() end end function is_device_suitable (pcidev, patterns) if not pcidev.usable or pcidev.driver ~= 'apps.intel.intel_app' then return false end if #patterns == 0 then return true end for _, pattern in ipairs(patterns) do if pci.qualified(pcidev.pciaddress):gmatch(pattern)() then return true end end end
fix argument pcap file for packetblaster replay
fix argument pcap file for packetblaster replay
Lua
apache-2.0
Igalia/snabb,wingo/snabbswitch,heryii/snabb,SnabbCo/snabbswitch,wingo/snabbswitch,kbara/snabb,eugeneia/snabb,eugeneia/snabb,alexandergall/snabbswitch,dpino/snabb,Igalia/snabbswitch,dpino/snabb,Igalia/snabbswitch,Igalia/snabbswitch,Igalia/snabb,mixflowtech/logsensor,Igalia/snabb,mixflowtech/logsensor,eugeneia/snabbswitch,kbara/snabb,snabbco/snabb,snabbco/snabb,wingo/snabb,wingo/snabb,eugeneia/snabb,wingo/snabb,Igalia/snabb,wingo/snabbswitch,eugeneia/snabbswitch,dpino/snabbswitch,mixflowtech/logsensor,eugeneia/snabb,dpino/snabb,mixflowtech/logsensor,wingo/snabb,heryii/snabb,eugeneia/snabbswitch,alexandergall/snabbswitch,heryii/snabb,SnabbCo/snabbswitch,alexandergall/snabbswitch,dpino/snabbswitch,alexandergall/snabbswitch,kbara/snabb,eugeneia/snabb,mixflowtech/logsensor,eugeneia/snabb,wingo/snabbswitch,kbara/snabb,dpino/snabb,Igalia/snabbswitch,Igalia/snabb,snabbco/snabb,heryii/snabb,eugeneia/snabb,kbara/snabb,Igalia/snabb,SnabbCo/snabbswitch,dpino/snabb,kbara/snabb,dpino/snabb,wingo/snabb,alexandergall/snabbswitch,heryii/snabb,snabbco/snabb,eugeneia/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,dpino/snabb,Igalia/snabb,snabbco/snabb,alexandergall/snabbswitch,eugeneia/snabb,snabbco/snabb,SnabbCo/snabbswitch,dpino/snabbswitch,snabbco/snabb,Igalia/snabbswitch,dpino/snabbswitch,snabbco/snabb,wingo/snabb,heryii/snabb,alexandergall/snabbswitch
224daefd0f692f8601497a7f5680451f9db1243a
src/base/os.lua
src/base/os.lua
-- -- os.lua -- Additions to the OS namespace. -- Copyright (c) 2002-2011 Jason Perkins and the Premake project -- -- -- Same as os.execute(), but accepts string formatting arguments. -- function os.executef(cmd, ...) cmd = string.format(cmd, unpack(arg)) return os.execute(cmd) end -- -- Scan the well-known system locations for a particular library. -- function os.findlib(libname) local path, formats -- assemble a search path, depending on the platform if os.is("windows") then formats = { "%s.dll", "%s" } path = os.getenv("PATH") elseif os.is("haiku") then formats = { "lib%s.so", "%s.so" } path = os.getenv("LIBRARY_PATH") else if os.is("macosx") then formats = { "lib%s.dylib", "%s.dylib" } path = os.getenv("DYLD_LIBRARY_PATH") else formats = { "lib%s.so", "%s.so" } path = os.getenv("LD_LIBRARY_PATH") or "" io.input("/etc/ld.so.conf") if io.input() then for line in io.lines() do path = path .. ":" .. line end io.input():close() end end table.insert(formats, "%s") path = path or "" if os.is64bit() then path = path .. ":/lib64:/usr/lib64/:usr/local/lib64" end path = path .. ":/lib:/usr/lib:/usr/local/lib" end for _, fmt in ipairs(formats) do local name = string.format(fmt, libname) local result = os.pathsearch(name, path) if result then return result end end end -- -- Retrieve the current operating system ID string. -- function os.get() return _OPTIONS.os or _OS end -- -- Check the current operating system; may be set with the /os command line flag. -- function os.is(id) return (os.get():lower() == id:lower()) end -- -- Determine if the current system is running a 64-bit architecture -- local _64BitHostTypes = { "x86_64", "ia64", "amd64", "ppc64", "powerpc64", "sparc64" } function os.is64bit() -- Call the native code implementation. If this returns true then -- we're 64-bit, otherwise do more checking locally if (os._is64bit()) then return true end -- Identify the system local arch if _OS == "windows" then arch = os.getenv("PROCESSOR_ARCHITECTURE") elseif _OS == "macosx" then arch = os.outputof("echo $HOSTTYPE") else arch = os.outputof("uname -m") end -- Check our known 64-bit identifiers arch = arch:lower() for _, hosttype in ipairs(_64BitHostTypes) do if arch:find(hosttype) then return true end end return false end -- -- The os.matchdirs() and os.matchfiles() functions -- local function domatch(result, mask, wantfiles) -- need to remove extraneous path info from the mask to ensure a match -- against the paths returned by the OS. Haven't come up with a good -- way to do it yet, so will handle cases as they come up if mask:startswith("./") then mask = mask:sub(3) end -- strip off any leading directory information to find out -- where the search should take place local basedir = mask local starpos = mask:find("%*") if starpos then basedir = basedir:sub(1, starpos - 1) end basedir = path.getdirectory(basedir) if (basedir == ".") then basedir = "" end -- recurse into subdirectories? local recurse = mask:find("**", nil, true) -- convert mask to a Lua pattern mask = path.wildcards(mask) local function matchwalker(basedir) local wildcard = path.join(basedir, "*") -- retrieve files from OS and test against mask local m = os.matchstart(wildcard) while (os.matchnext(m)) do local isfile = os.matchisfile(m) if ((wantfiles and isfile) or (not wantfiles and not isfile)) then local fname = path.join(basedir, os.matchname(m)) if fname:match(mask) == fname then table.insert(result, fname) end end end os.matchdone(m) -- check subdirectories if recurse then m = os.matchstart(wildcard) while (os.matchnext(m)) do if not os.matchisfile(m) then local dirname = os.matchname(m) matchwalker(path.join(basedir, dirname)) end end os.matchdone(m) end end matchwalker(basedir) end function os.matchdirs(...) local result = { } for _, mask in ipairs(arg) do domatch(result, mask, false) end return result end function os.matchfiles(...) local result = { } for _, mask in ipairs(arg) do domatch(result, mask, true) end return result end -- -- An overload of the os.mkdir() function, which will create any missing -- subdirectories along the path. -- local builtin_mkdir = os.mkdir function os.mkdir(p) local dir = iif(p:startswith("/"), "/", "") for part in p:gmatch("[^/]+") do dir = dir .. part if (part ~= "" and not path.isabsolute(part) and not os.isdir(dir)) then local ok, err = builtin_mkdir(dir) if (not ok) then return nil, err end end dir = dir .. "/" end return true end -- -- Run a shell command and return the output. -- function os.outputof(cmd) local pipe = io.popen(cmd) local result = pipe:read('*a') pipe:close() return result end -- -- Remove a directory, along with any contained files or subdirectories. -- local builtin_rmdir = os.rmdir function os.rmdir(p) -- recursively remove subdirectories local dirs = os.matchdirs(p .. "/*") for _, dname in ipairs(dirs) do os.rmdir(dname) end -- remove any files local files = os.matchfiles(p .. "/*") for _, fname in ipairs(files) do os.remove(fname) end -- remove this directory builtin_rmdir(p) end
-- -- os.lua -- Additions to the OS namespace. -- Copyright (c) 2002-2011 Jason Perkins and the Premake project -- -- -- Same as os.execute(), but accepts string formatting arguments. -- function os.executef(cmd, ...) cmd = string.format(cmd, unpack(arg)) return os.execute(cmd) end -- -- Scan the well-known system locations for a particular library. -- local function parse_ld_so_conf(conf_file) -- Linux ldconfig file parser to find system library locations local first, last local dirs = { } for line in io.lines(conf_file) do -- ignore comments first = line:find("#", 1, true) if first ~= nil then line = line:sub(1, first - 1) end if line ~= "" then -- check for include files first, last = line:find("include%s+") if first ~= nil then -- found include glob local include_glob = line:sub(last + 1) local includes = os.matchfiles(include_glob) for _, v in ipairs(includes) do dirs = table.join(dirs, parse_ld_so_conf(v)) end else -- found an actual ld path entry table.insert(dirs, line) end end end return dirs end function os.findlib(libname) local path, formats -- assemble a search path, depending on the platform if os.is("windows") then formats = { "%s.dll", "%s" } path = os.getenv("PATH") elseif os.is("haiku") then formats = { "lib%s.so", "%s.so" } path = os.getenv("LIBRARY_PATH") else if os.is("macosx") then formats = { "lib%s.dylib", "%s.dylib" } path = os.getenv("DYLD_LIBRARY_PATH") else formats = { "lib%s.so", "%s.so" } path = os.getenv("LD_LIBRARY_PATH") or "" for _, v in ipairs(parse_ld_so_conf("/etc/ld.so.conf")) do path = path .. ":" .. v end end table.insert(formats, "%s") path = path or "" if os.is64bit() then path = path .. ":/lib64:/usr/lib64/:usr/local/lib64" end path = path .. ":/lib:/usr/lib:/usr/local/lib" end for _, fmt in ipairs(formats) do local name = string.format(fmt, libname) local result = os.pathsearch(name, path) if result then return result end end end -- -- Retrieve the current operating system ID string. -- function os.get() return _OPTIONS.os or _OS end -- -- Check the current operating system; may be set with the /os command line flag. -- function os.is(id) return (os.get():lower() == id:lower()) end -- -- Determine if the current system is running a 64-bit architecture -- local _64BitHostTypes = { "x86_64", "ia64", "amd64", "ppc64", "powerpc64", "sparc64" } function os.is64bit() -- Call the native code implementation. If this returns true then -- we're 64-bit, otherwise do more checking locally if (os._is64bit()) then return true end -- Identify the system local arch if _OS == "windows" then arch = os.getenv("PROCESSOR_ARCHITECTURE") elseif _OS == "macosx" then arch = os.outputof("echo $HOSTTYPE") else arch = os.outputof("uname -m") end -- Check our known 64-bit identifiers arch = arch:lower() for _, hosttype in ipairs(_64BitHostTypes) do if arch:find(hosttype) then return true end end return false end -- -- The os.matchdirs() and os.matchfiles() functions -- local function domatch(result, mask, wantfiles) -- need to remove extraneous path info from the mask to ensure a match -- against the paths returned by the OS. Haven't come up with a good -- way to do it yet, so will handle cases as they come up if mask:startswith("./") then mask = mask:sub(3) end -- strip off any leading directory information to find out -- where the search should take place local basedir = mask local starpos = mask:find("%*") if starpos then basedir = basedir:sub(1, starpos - 1) end basedir = path.getdirectory(basedir) if (basedir == ".") then basedir = "" end -- recurse into subdirectories? local recurse = mask:find("**", nil, true) -- convert mask to a Lua pattern mask = path.wildcards(mask) local function matchwalker(basedir) local wildcard = path.join(basedir, "*") -- retrieve files from OS and test against mask local m = os.matchstart(wildcard) while (os.matchnext(m)) do local isfile = os.matchisfile(m) if ((wantfiles and isfile) or (not wantfiles and not isfile)) then local fname = path.join(basedir, os.matchname(m)) if fname:match(mask) == fname then table.insert(result, fname) end end end os.matchdone(m) -- check subdirectories if recurse then m = os.matchstart(wildcard) while (os.matchnext(m)) do if not os.matchisfile(m) then local dirname = os.matchname(m) matchwalker(path.join(basedir, dirname)) end end os.matchdone(m) end end matchwalker(basedir) end function os.matchdirs(...) local result = { } for _, mask in ipairs(arg) do domatch(result, mask, false) end return result end function os.matchfiles(...) local result = { } for _, mask in ipairs(arg) do domatch(result, mask, true) end return result end -- -- An overload of the os.mkdir() function, which will create any missing -- subdirectories along the path. -- local builtin_mkdir = os.mkdir function os.mkdir(p) local dir = iif(p:startswith("/"), "/", "") for part in p:gmatch("[^/]+") do dir = dir .. part if (part ~= "" and not path.isabsolute(part) and not os.isdir(dir)) then local ok, err = builtin_mkdir(dir) if (not ok) then return nil, err end end dir = dir .. "/" end return true end -- -- Run a shell command and return the output. -- function os.outputof(cmd) local pipe = io.popen(cmd) local result = pipe:read('*a') pipe:close() return result end -- -- Remove a directory, along with any contained files or subdirectories. -- local builtin_rmdir = os.rmdir function os.rmdir(p) -- recursively remove subdirectories local dirs = os.matchdirs(p .. "/*") for _, dname in ipairs(dirs) do os.rmdir(dname) end -- remove any files local files = os.matchfiles(p .. "/*") for _, fname in ipairs(files) do os.remove(fname) end -- remove this directory builtin_rmdir(p) end
Process ld.so.conf for includes, fixes os.findlib in Linux.
Process ld.so.conf for includes, fixes os.findlib in Linux.
Lua
bsd-3-clause
premake/premake-4.x,lizh06/premake-4.x,soundsrc/premake-stable,lizh06/premake-4.x,ryanjmulder/premake-4.x,lizh06/premake-4.x,premake/premake-4.x,ryanjmulder/premake-4.x,premake/premake-4.x,soundsrc/premake-stable,soundsrc/premake-stable,premake/premake-4.x,soundsrc/premake-stable,ryanjmulder/premake-4.x,ryanjmulder/premake-4.x,lizh06/premake-4.x
cbe6085f1aaeaca6fb36d1640c64dea52c36298d
orange/plugins/signature_auth/handler.lua
orange/plugins/signature_auth/handler.lua
local ipairs = ipairs local type = type local encode_base64 = ngx.encode_base64 local string_format = string.format local string_gsub = string.gsub local tabel_insert = table.insert local utils = require("orange.utils.utils") local orange_db = require("orange.store.orange_db") local judge_util = require("orange.utils.judge") local handle_util = require("orange.utils.handle") local BasePlugin = require("orange.plugins.base_handler") local extractor_util = require("orange.utils.extractor") local function is_authorized(signature_name, secretKey,extractor) if not signature_name or not secretKey then return false,'sig or secret key config error' end if extractor == nil or next(extractor) == nil then return false,'extractor empty' end local check_sig = function(extractions,secretKey) local param = {} local req_val = {} for i, extraction in ipairs(extractions) do local name = extraction.name tabel_insert(param,name) local temp= extractor_util.extract_variable(extraction) if temp then req_val[name] = temp else return false ,name.." is empty" end end local signature = req_val[signature_name] req_val[signature_name]=nil local md5 = require("resty.md5") local md5 = md5:new() if not md5 then ngx.log(ngx.ERR,'server error exec md5:new faild') return false end for _, v in ipairs(param) do if req_val[v] then local ok = md5:update(req_val[v]) if not ok then ngx.log(ngx.ERR,'server error exec md5:update faild') return false end end end local ok = md5:update(secretKey) if not ok then ngx.log(ngx.ERR,'server error exec md5:update faild') return false end local str = require "resty.string" local calc_sig = str.to_hex(md5:final()) return calc_sig == signature end return check_sig(extractor.extractions,secretKey) end local function filter_rules(sid, plugin, ngx_var_uri) local rules = orange_db.get_json(plugin .. ".selector." .. sid .. ".rules") if not rules or type(rules) ~= "table" or #rules <= 0 then return false end for i, rule in ipairs(rules) do if rule.enable == true then -- judge阶段 local pass = judge_util.judge_rule(rule, plugin) -- handle阶段 local handle = rule.handle or {} if pass then if handle.credentials then if handle.log == true then ngx.log(ngx.INFO, "[SignatureAuth-Pass-Rule] ", rule.name, " uri:", ngx_var_uri) end local credentials = handle.credentials local authorized = is_authorized(credentials.signame,credentials.secretkey,rule.extractor) if authorized then return true else ngx.exit(tonumber(handle.code) or 401) return true end else if handle.log == true then ngx.log(ngx.INFO, "[SignatureAuth-Forbidden-Rule] ", rule.name, " uri:", ngx_var_uri) end ngx.exit(tonumber(handle.code) or 401) return true end end end end return false end local BasicAuthHandler = BasePlugin:extend() BasicAuthHandler.PRIORITY = 2000 function BasicAuthHandler:new(store) BasicAuthHandler.super.new(self, "signature_auth-plugin") self.store = store end function BasicAuthHandler:access(conf) BasicAuthHandler.super.access(self) local enable = orange_db.get("signature_auth.enable") local meta = orange_db.get_json("signature_auth.meta") local selectors = orange_db.get_json("signature_auth.selectors") local ordered_selectors = meta and meta.selectors if not enable or enable ~= true or not meta or not ordered_selectors or not selectors then return end local ngx_var_uri = ngx.var.uri for i, sid in ipairs(ordered_selectors) do ngx.log(ngx.INFO, "==[SignatureAuth][PASS THROUGH SELECTOR:", sid, "]") local selector = selectors[sid] if selector and selector.enable == true then local selector_pass if selector.type == 0 then -- 全流量选择器 selector_pass = true else selector_pass = judge_util.judge_selector(selector, "signature_auth")-- selector judge end if selector_pass then if selector.handle and selector.handle.log == true then ngx.log(ngx.INFO, "[SignatureAuth][PASS-SELECTOR:", sid, "] ", ngx_var_uri) end local stop = filter_rules(sid, "signature_auth", ngx_var_uri) if stop then -- 不再执行此插件其他逻辑 return end else if selector.handle and selector.handle.log == true then ngx.log(ngx.INFO, "[SignatureAuth][NOT-PASS-SELECTOR:", sid, "] ", ngx_var_uri) end end -- if continue or break the loop if selector.handle and selector.handle.continue == true then -- continue next selector else break end end end end return BasicAuthHandler
local ipairs = ipairs local type = type local encode_base64 = ngx.encode_base64 local string_format = string.format local string_gsub = string.gsub local tabel_insert = table.insert local utils = require("orange.utils.utils") local orange_db = require("orange.store.orange_db") local judge_util = require("orange.utils.judge") local handle_util = require("orange.utils.handle") local BasePlugin = require("orange.plugins.base_handler") local extractor_util = require("orange.utils.extractor") local function is_authorized(signature_name, secretKey,extractor) if not signature_name or not secretKey then return false,'sig or secret key config error' end if extractor == nil or next(extractor) == nil then return false,'extractor empty' end local check_sig = function(extractions,secretKey) local param = {} local req_val = {} for i, extraction in ipairs(extractions) do local name = extraction.name tabel_insert(param,name) local temp= extractor_util.extract_variable(extraction) if temp then req_val[name] = temp else return false ,name.." is empty" end end local signature = req_val[signature_name] req_val[signature_name]=nil local md5 = require("resty.md5") local md5 = md5:new() if not md5 then ngx.log(ngx.ERR,'server error exec md5:new faild') return false end for _, v in ipairs(param) do if req_val[v] then local ok = md5:update(req_val[v]) if not ok then ngx.log(ngx.ERR,'server error exec md5:update faild') return false end end end local ok = md5:update(secretKey) if not ok then ngx.log(ngx.ERR,'server error exec md5:update faild') return false end local str = require "resty.string" local calc_sig = str.to_hex(md5:final()) return calc_sig == signature end return check_sig(extractor.extractions,secretKey) end local function filter_rules(sid, plugin, ngx_var_uri) local rules = orange_db.get_json(plugin .. ".selector." .. sid .. ".rules") if not rules or type(rules) ~= "table" or #rules <= 0 then return false end for i, rule in ipairs(rules) do if rule.enable == true then -- judge阶段 local pass = judge_util.judge_rule(rule, plugin) -- handle阶段 local handle = rule.handle or {} if pass then if handle.credentials then if handle.log == true then ngx.log(ngx.INFO, "[SignatureAuth-Pass-Rule] ", rule.name, " uri:", ngx_var_uri) end local credentials = handle.credentials local authorized = is_authorized(credentials.signame,credentials.secretkey,rule.extractor) if authorized then return true else ngx.exit(tonumber(handle.code) or 401) return true end else if handle.log == true then ngx.log(ngx.INFO, "[SignatureAuth-Forbidden-Rule] ", rule.name, " uri:", ngx_var_uri) end ngx.exit(tonumber(handle.code) or 401) return true end end end end return false end local SignatureAuthHandler = BasePlugin:extend() SignatureAuthHandler.PRIORITY = 2000 function SignatureAuthHandler:new(store) SignatureAuthHandler.super.new(self, "signature_auth-plugin") self.store = store end function SignatureAuthHandler:access(conf) SignatureAuthHandler.super.access(self) local enable = orange_db.get("signature_auth.enable") local meta = orange_db.get_json("signature_auth.meta") local selectors = orange_db.get_json("signature_auth.selectors") local ordered_selectors = meta and meta.selectors if not enable or enable ~= true or not meta or not ordered_selectors or not selectors then return end local ngx_var_uri = ngx.var.uri for i, sid in ipairs(ordered_selectors) do ngx.log(ngx.INFO, "==[SignatureAuth][PASS THROUGH SELECTOR:", sid, "]") local selector = selectors[sid] if selector and selector.enable == true then local selector_pass if selector.type == 0 then -- 全流量选择器 selector_pass = true else selector_pass = judge_util.judge_selector(selector, "signature_auth")-- selector judge end if selector_pass then if selector.handle and selector.handle.log == true then ngx.log(ngx.INFO, "[SignatureAuth][PASS-SELECTOR:", sid, "] ", ngx_var_uri) end local stop = filter_rules(sid, "signature_auth", ngx_var_uri) if stop then -- 不再执行此插件其他逻辑 return end else if selector.handle and selector.handle.log == true then ngx.log(ngx.INFO, "[SignatureAuth][NOT-PASS-SELECTOR:", sid, "] ", ngx_var_uri) end end -- if continue or break the loop if selector.handle and selector.handle.continue == true then -- continue next selector else break end end end end return SignatureAuthHandler
fix: corrrect the plugins name
fix: corrrect the plugins name
Lua
mit
jxskiss/orange,thisverygoodhhhh/orange,sumory/orange,wuhuatianbao007/orange,sumory/orange,wuhuatianbao007/orange,wuhuatianbao007/orange,thisverygoodhhhh/orange,thisverygoodhhhh/orange,jxskiss/orange,jxskiss/orange,sumory/orange
f0d3e731adeaa4a15c62a82592aa1b8262a7cd3b
build/Helpers.lua
build/Helpers.lua
-- This module checks for the all the project dependencies. newoption { trigger = "arch", description = "Choose a particular architecture / bitness", allowed = { { "x86", "x86 32-bits" }, { "x64", "x64 64-bits" }, } } newoption { trigger = "no-cxx11-abi", description = "disable cxx11 abi on gcc 4.9+" } explicit_target_architecture = _OPTIONS["arch"] function is_64_bits_mono_runtime() result, errorcode = os.outputof("mono --version") local arch = string.match(result, "Architecture:%s*([%w]+)") return arch == "amd64" end function target_architecture() -- Default to 32-bit on Windows and Mono architecture otherwise. if explicit_target_architecture ~= nil then return explicit_target_architecture end if os.ishost("windows") then return "x86" end return is_64_bits_mono_runtime() and "x64" or "x86" end if not _OPTIONS["arch"] then _OPTIONS["arch"] = target_architecture() end action = _ACTION or "" basedir = path.getdirectory(_PREMAKE_COMMAND) depsdir = path.getabsolute("../deps"); srcdir = path.getabsolute("../src"); incdir = path.getabsolute("../include"); bindir = path.getabsolute("../bin"); examplesdir = path.getabsolute("../examples"); testsdir = path.getabsolute("../tests"); builddir = path.getabsolute("./" .. action); if _ARGS[1] then builddir = path.getabsolute("./" .. _ARGS[1]); end objsdir = path.join(builddir, "obj", "%{cfg.buildcfg}_%{cfg.platform}"); libdir = path.join(builddir, "lib", "%{cfg.buildcfg}_%{cfg.platform}"); gendir = path.join(builddir, "gen"); msvc_buildflags = { "/wd4267" } msvc_cpp_defines = { } generate_build_config = true function string.starts(str, start) return string.sub(str, 1, string.len(start)) == start end function SafePath(path) return "\"" .. path .. "\"" end function SetupNativeProject() location ("%{wks.location}/projects") filter { "configurations:Debug" } defines { "DEBUG" } filter { "configurations:Release" } defines { "NDEBUG" } optimize "On" -- Compiler-specific options filter { "action:vs*" } buildoptions { msvc_buildflags } defines { msvc_cpp_defines } filter { "system:linux" } buildoptions { gcc_buildflags } links { "stdc++" } filter { "system:macosx", "language:C++" } buildoptions { gcc_buildflags, "-stdlib=libc++" } links { "c++" } filter { "system:not windows", "language:C++" } buildoptions { "-fpermissive -std=c++11" } -- OS-specific options filter { "system:windows" } defines { "WIN32", "_WINDOWS" } filter {} if os.istarget("linux") then if not UseCxx11ABI() then defines { "_GLIBCXX_USE_CXX11_ABI=0" } end end end function SetupManagedProject() language "C#" location ("%{wks.location}/projects") buildoptions {"/platform:".._OPTIONS["arch"]} dotnetframework "4.6" if not os.istarget("macosx") then filter { "action:vs*" } location "." filter {} end filter { "action:vs2013" } dotnetframework "4.5" filter { "action:vs2012" } dotnetframework "4.5" filter {} end function IncludeDir(dir) local deps = os.matchdirs(dir .. "/*") for i,dep in ipairs(deps) do local fp = path.join(dep, "premake5.lua") fp = path.join(os.getcwd(), fp) if os.isfile(fp) then include(dep) return end fp = path.join(dep, "premake4.lua") fp = path.join(os.getcwd(), fp) if os.isfile(fp) then --print(string.format(" including %s", dep)) include(dep) end end end function StaticLinksOpt(libnames) local path = table.concat(cc.configset.libdirs, ";") local formats if os.is("windows") then formats = { "%s.lib" } else formats = { "lib%s.a" } end table.insert(formats, "%s"); local existing_libnames = {} for _, libname in ipairs(libnames) do for _, fmt in ipairs(formats) do local name = string.format(fmt, libname) if os.pathsearch(name, path) then table.insert(existing_libnames, libname) end end end links(existing_libnames) end function GccVersion() local compiler = os.getenv("CXX") if compiler == nil then compiler = "gcc" end local out = os.outputof(compiler.." -v") local version = string.match(out, "gcc version [0-9\\.]+") return string.sub(version, 13) end function UseCxx11ABI() if os.istarget("linux") and GccVersion() >= '4.9.0' and _OPTIONS["no-cxx11-abi"] == nil then return true end return false end
-- This module checks for the all the project dependencies. newoption { trigger = "arch", description = "Choose a particular architecture / bitness", allowed = { { "x86", "x86 32-bits" }, { "x64", "x64 64-bits" }, } } newoption { trigger = "no-cxx11-abi", description = "disable cxx11 abi on gcc 4.9+" } explicit_target_architecture = _OPTIONS["arch"] function is_64_bits_mono_runtime() result, errorcode = os.outputof("mono --version") local arch = string.match(result, "Architecture:%s*([%w]+)") return arch == "amd64" end function target_architecture() -- Default to 32-bit on Windows and Mono architecture otherwise. if explicit_target_architecture ~= nil then return explicit_target_architecture end if os.ishost("windows") then return "x86" end return is_64_bits_mono_runtime() and "x64" or "x86" end if not _OPTIONS["arch"] then _OPTIONS["arch"] = target_architecture() end action = _ACTION or "" basedir = path.getdirectory(_PREMAKE_COMMAND) depsdir = path.getabsolute("../deps"); srcdir = path.getabsolute("../src"); incdir = path.getabsolute("../include"); bindir = path.getabsolute("../bin"); examplesdir = path.getabsolute("../examples"); testsdir = path.getabsolute("../tests"); builddir = path.getabsolute("./" .. action); if _ARGS[1] then builddir = path.getabsolute("./" .. _ARGS[1]); end objsdir = path.join(builddir, "obj", "%{cfg.buildcfg}_%{cfg.platform}"); libdir = path.join(builddir, "lib", "%{cfg.buildcfg}_%{cfg.platform}"); gendir = path.join(builddir, "gen"); msvc_buildflags = { "/wd4267" } msvc_cpp_defines = { } generate_build_config = true function string.starts(str, start) return string.sub(str, 1, string.len(start)) == start end function SafePath(path) return "\"" .. path .. "\"" end function SetupNativeProject() location ("%{wks.location}/projects") filter { "configurations:Debug" } defines { "DEBUG" } filter { "configurations:Release" } defines { "NDEBUG" } optimize "On" -- Compiler-specific options filter { "action:vs*" } buildoptions { msvc_buildflags } defines { msvc_cpp_defines } filter { "system:linux" } buildoptions { gcc_buildflags } links { "stdc++" } filter { "system:macosx", "language:C++" } buildoptions { gcc_buildflags, "-stdlib=libc++" } links { "c++" } filter { "system:not windows", "language:C++" } buildoptions { "-fpermissive -std=c++11" } -- OS-specific options filter { "system:windows" } defines { "WIN32", "_WINDOWS" } -- For context: https://github.com/premake/premake-core/issues/935 filter {"system:windows", "action:vs*"} systemversion("latest") filter {} if os.istarget("linux") then if not UseCxx11ABI() then defines { "_GLIBCXX_USE_CXX11_ABI=0" } end end end function SetupManagedProject() language "C#" location ("%{wks.location}/projects") buildoptions {"/platform:".._OPTIONS["arch"]} dotnetframework "4.6" if not os.istarget("macosx") then filter { "action:vs*" } location "." filter {} end filter { "action:vs2013" } dotnetframework "4.5" filter { "action:vs2012" } dotnetframework "4.5" filter {} end function IncludeDir(dir) local deps = os.matchdirs(dir .. "/*") for i,dep in ipairs(deps) do local fp = path.join(dep, "premake5.lua") fp = path.join(os.getcwd(), fp) if os.isfile(fp) then include(dep) return end fp = path.join(dep, "premake4.lua") fp = path.join(os.getcwd(), fp) if os.isfile(fp) then --print(string.format(" including %s", dep)) include(dep) end end end function StaticLinksOpt(libnames) local path = table.concat(cc.configset.libdirs, ";") local formats if os.is("windows") then formats = { "%s.lib" } else formats = { "lib%s.a" } end table.insert(formats, "%s"); local existing_libnames = {} for _, libname in ipairs(libnames) do for _, fmt in ipairs(formats) do local name = string.format(fmt, libname) if os.pathsearch(name, path) then table.insert(existing_libnames, libname) end end end links(existing_libnames) end function GccVersion() local compiler = os.getenv("CXX") if compiler == nil then compiler = "gcc" end local out = os.outputof(compiler.." -v") local version = string.match(out, "gcc version [0-9\\.]+") return string.sub(version, 13) end function UseCxx11ABI() if os.istarget("linux") and GccVersion() >= '4.9.0' and _OPTIONS["no-cxx11-abi"] == nil then return true end return false end
Fixed Windows SDK version detection in build scripts.
Fixed Windows SDK version detection in build scripts.
Lua
mit
ddobrev/CppSharp,zillemarco/CppSharp,zillemarco/CppSharp,ddobrev/CppSharp,mono/CppSharp,mono/CppSharp,zillemarco/CppSharp,zillemarco/CppSharp,mono/CppSharp,zillemarco/CppSharp,mono/CppSharp,ddobrev/CppSharp,ddobrev/CppSharp,ddobrev/CppSharp,mono/CppSharp,mono/CppSharp
6a52788b4632b71944881eaa17d28b2879d889cf
test/autobahn_client_test.lua
test/autobahn_client_test.lua
local uv = require "lluv" local websocket = require "lluv.websocket" local URI = "ws://127.0.0.1:9001" local agent = "lluv-websocket" local caseCount = 0 local currentCaseId = 0 function isWSEOF(err) return err:name() == 'EOF' and err.cat and err:cat() == 'WEBSOCKET' end function getCaseCount(cont) websocket.new():connect(URI .. "/getCaseCount", "echo", function(cli, err) if err then print("Client connect error:", err) return cli:close() end cli:start_read(function(self, err, message, opcode) if err then print("Client read error:", err) return cli:close() end caseCount = tonumber(message) cli:close(function() cont() end) end) end) end function runtTestCase(no, cb) local ws_uri = URI .. "/runCase?case=" .. no .. "&agent=" .. agent websocket.new():connect(ws_uri, "echo", function(cli, err) if err then print("Client connect error:", err) return cli:close() end print("Executing test case " .. no .. "/" .. caseCount) cli:start_read(function(self, err, message, opcode) if err then if isWSEOF(err) then return cli:close(cb) end print("Client read error:", err) return cli:close() end cli:write(message, opcode) end) end) end function runNextCase() runtTestCase(currentCaseId, function(_, err, code, reason) if code ~= 1000 then print("Test fail : ", reason) end currentCaseId = currentCaseId + 1 if currentCaseId <= caseCount then runNextCase() else print("All test cases executed.") updateReports() end end) end function updateReports() local ws_uri = URI .. "/updateReports?agent=" .. agent websocket.new():connect(ws_uri, "echo", function(cli, err) if err then print("Client connect error:", err) return cli:close() end print("Updating reports ..."); cli:start_read(function(self, err, message, opcode) if err then if not isWSEOF(err) then print("Client read error:", err) end return cli:close(function() print("Reports updated."); print("Test suite finished!"); end) end end) end) end function runAll() currentCaseId = 1 getCaseCount(runNextCase) uv.run() updateReports() end runAll() -- runtTestCase(21, print) uv.run()
local uv = require "lluv" local websocket = require "lluv.websocket" local URI = "ws://127.0.0.1:9001" local agent = "lluv-websocket" local caseCount = 0 local currentCaseId = 0 function isWSEOF(err) return err:name() == 'EOF' and err.cat and err:cat() == 'WEBSOCKET' end function getCaseCount(cont) websocket.new():connect(URI .. "/getCaseCount", "echo", function(cli, err) if err then print("Client connect error:", err) return cli:close() end cli:start_read(function(self, err, message, opcode) if err then print("Client read error:", err) return cli:close() end caseCount = tonumber(message) cli:close(function() cont() end) end) end) end function runtTestCase(no, cb) local ws_uri = URI .. "/runCase?case=" .. no .. "&agent=" .. agent websocket.new():connect(ws_uri, "echo", function(cli, err) if err then print("Client connect error:", err) return cli:close() end print("Executing test case " .. no .. "/" .. caseCount) cli:start_read(function(self, err, message, opcode) if err then if not isWSEOF(err) then print("Client read error:", err) end return cli:close(cb) end if opcode == websocket.TEXT or opcode == websocket.BINARY then cli:write(message, opcode) end end) end) end function runNextCase() runtTestCase(currentCaseId, function(_, err, code, reason) if code ~= 1000 then print("Test fail : ", reason) end currentCaseId = currentCaseId + 1 if currentCaseId <= caseCount then runNextCase() else print("All test cases executed.") updateReports() end end) end function updateReports() local ws_uri = URI .. "/updateReports?agent=" .. agent websocket.new():connect(ws_uri, "echo", function(cli, err) if err then print("Client connect error:", err) return cli:close() end print("Updating reports ..."); cli:start_read(function(self, err, message, opcode) if err then if not isWSEOF(err) then print("Client read error:", err) end return cli:close(function() print("Reports updated."); print("Test suite finished!"); end) end end) end) end function runAll() currentCaseId = 1 getCaseCount(runNextCase) uv.run() updateReports() end runAll() -- runtTestCase(1, print) uv.run()
Fix. Test does not echo PONGs
Fix. Test does not echo PONGs
Lua
mit
moteus/lua-lluv-websocket,moteus/lua-lluv-websocket,moteus/lua-lluv-websocket
6c8197adb32328afb70bb9ef46f83df661e5946c
spec/02-integration/03-db/11-postgres-ro_spec.lua
spec/02-integration/03-db/11-postgres-ro_spec.lua
local helpers = require "spec.helpers" local cjson = require "cjson.safe" for _, strategy in helpers.each_strategy() do local postgres_only = strategy == "postgres" and describe or pending postgres_only("postgres readonly connection", function() local proxy_client, admin_client lazy_setup(function() helpers.get_db_utils(strategy, { "routes", "services", }) -- runs migrations assert(helpers.start_kong({ database = strategy, pg_ro_host = helpers.test_conf.pg_host, nginx_conf = "spec/fixtures/custom_nginx.template", })) admin_client = helpers.admin_client() proxy_client = helpers.proxy_client() end) lazy_teardown(function() if admin_client then admin_client:close() end if proxy_client then proxy_client:close() end helpers.stop_kong() end) describe("proxy and admin API works", function() local route_id it("can change and retrieve config using Admin API", function() local res = assert(admin_client:post("/services", { body = { name = "mock-service", url = "https://127.0.0.1:15556/request", }, headers = {["Content-Type"] = "application/json"} })) assert.res_status(201, res) res = assert(admin_client:get("/services/mock-service")) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.equals(json.path, "/request") res = assert(admin_client:post("/services/mock-service/routes", { body = { paths = { "/" }, }, headers = {["Content-Type"] = "application/json"} })) body = assert.res_status(201, res) json = cjson.decode(body) route_id = json.id helpers.wait_until(function() res = assert(proxy_client:send({ method = "GET", path = "/", })) return pcall(function() assert.res_status(200, res) end) end, 10) end) it("cache invalidation works on config change", function() local res = assert(admin_client:send({ method = "DELETE", path = "/routes/" .. route_id, })) assert.res_status(204, res) helpers.wait_until(function() res = assert(proxy_client:send({ method = "GET", path = "/", })) return pcall(function() assert.res_status(404, res) end) end, 10) end) end) end) postgres_only("postgres bad readonly connection", function() local proxy_client, admin_client lazy_setup(function() helpers.get_db_utils(strategy, { "routes", "services", }) -- runs migrations assert(helpers.start_kong({ database = strategy, pg_ro_host = helpers.test_conf.pg_host, pg_ro_port = 9090, -- connection refused })) admin_client = helpers.admin_client() proxy_client = helpers.proxy_client() end) lazy_teardown(function() if admin_client then admin_client:close() end if proxy_client then proxy_client:close() end helpers.stop_kong() end) describe("read only operation breaks and read write operation works", function() it("admin API bypasses readonly connection but proxy doesn't", function() local res = assert(admin_client:post("/services", { body = { name = "mock-service", url = "https://127.0.0.1:15556/request", }, headers = {["Content-Type"] = "application/json"} })) assert.res_status(201, res) res = assert(admin_client:get("/services/mock-service")) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.equals(json.path, "/request") res = assert(admin_client:post("/services/mock-service/routes", { body = { paths = { "/" }, }, headers = {["Content-Type"] = "application/json"} })) assert.res_status(201, res) helpers.wait_until(function() res = assert(proxy_client:send({ method = "GET", path = "/", })) return pcall(function() assert.res_status(404, res) end) end, 10) helpers.wait_until(function () return pcall(function () assert.logfile().has.line("could not rebuild router.*: could not load routes.*" .. "postgres.*connection refused", false) end) -- pcall end, 20) -- helpers.wait_until end) end) end) end
local helpers = require "spec.helpers" local cjson = require "cjson.safe" for _, strategy in helpers.each_strategy() do local postgres_only = strategy == "postgres" and describe or pending postgres_only("postgres readonly connection", function() local proxy_client, admin_client lazy_setup(function() helpers.get_db_utils(strategy, { "routes", "services", }) -- runs migrations assert(helpers.start_kong({ database = strategy, pg_ro_host = helpers.test_conf.pg_host, nginx_conf = "spec/fixtures/custom_nginx.template", })) admin_client = helpers.admin_client() proxy_client = helpers.proxy_client() end) lazy_teardown(function() if admin_client then admin_client:close() end if proxy_client then proxy_client:close() end helpers.stop_kong() end) describe("proxy and admin API works", function() local route_id it("can change and retrieve config using Admin API", function() local res = assert(admin_client:post("/services", { body = { name = "mock-service", url = "https://127.0.0.1:15556/request", }, headers = {["Content-Type"] = "application/json"} })) assert.res_status(201, res) res = assert(admin_client:get("/services/mock-service")) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.equals(json.path, "/request") res = assert(admin_client:post("/services/mock-service/routes", { body = { paths = { "/" }, }, headers = {["Content-Type"] = "application/json"} })) body = assert.res_status(201, res) json = cjson.decode(body) route_id = json.id helpers.wait_until(function() res = assert(proxy_client:send({ method = "GET", path = "/", })) return pcall(function() assert.res_status(200, res) end) end, 10) end) it("cache invalidation works on config change", function() local res = assert(admin_client:send({ method = "DELETE", path = "/routes/" .. route_id, })) assert.res_status(204, res) helpers.wait_until(function() res = assert(proxy_client:send({ method = "GET", path = "/", })) return pcall(function() assert.res_status(404, res) end) end, 10) end) end) end) postgres_only("postgres bad readonly connection", function() local proxy_client, admin_client lazy_setup(function() helpers.get_db_utils(strategy, { "routes", "services", }) -- runs migrations assert(helpers.start_kong({ worker_consistency = "strict", database = strategy, pg_ro_host = helpers.test_conf.pg_host, pg_ro_port = 9090, -- connection refused })) admin_client = helpers.admin_client() proxy_client = helpers.proxy_client() end) lazy_teardown(function() if admin_client then admin_client:close() end if proxy_client then proxy_client:close() end helpers.stop_kong() end) describe("read only operation breaks and read write operation works", function() it("admin API bypasses readonly connection but proxy doesn't", function() local res = assert(admin_client:post("/services", { body = { name = "mock-service", url = "https://127.0.0.1:15556/request", }, headers = {["Content-Type"] = "application/json"} })) assert.res_status(201, res) res = assert(admin_client:get("/services/mock-service")) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.equals(json.path, "/request") res = assert(admin_client:post("/services/mock-service/routes", { body = { paths = { "/" }, }, headers = {["Content-Type"] = "application/json"} })) assert.res_status(201, res) helpers.wait_until(function() res = assert(proxy_client:send({ method = "GET", path = "/", })) return pcall(function() assert.res_status(404, res) assert.logfile().has.line("get_updated_router(): could not rebuild router: " .. "could not load routes: [postgres] connection " .. "refused (stale router will be used)", true) end) end, 10) end) end) end) end
fix(tests) more request to wait for router update (#9113)
fix(tests) more request to wait for router update (#9113) This test is flaky because we may send the request before the router takes effect. We need to wait not only for log emitting but also for the router update to take effect.
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
607b93c8fae24ff157e3ff36df7c34fee372e890
aspects/vim/files/.vim/lua/wincent/lsp.lua
aspects/vim/files/.vim/lua/wincent/lsp.lua
local lsp = {} local nnoremap = function (lhs, rhs) vim.api.nvim_buf_set_keymap(0, 'n', lhs, rhs, {noremap = true, silent = true}) end local on_attach = function () local mappings = { ['<Leader>ld'] = '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>', ['<c-]>'] = '<cmd>lua vim.lsp.buf.definition()<CR>', ['K'] = '<cmd>lua vim.lsp.buf.hover()<CR>', ['gd'] = '<cmd>lua vim.lsp.buf.declaration()<CR>', } for lhs, rhs in pairs(mappings) do nnoremap(lhs, rhs) end vim.api.nvim_win_set_option(0, 'signcolumn', 'yes') end lsp.bind = function () pcall(function () if vim.api.nvim_win_get_var(0, 'textDocument/hover') then nnoremap('K', ':call nvim_win_close(0, v:true)<CR>') nnoremap('<Esc>', ':call nvim_win_close(0, v:true)<CR>') vim.api.nvim_win_set_option(0, 'cursorline', false) -- I believe this is supposed to happen automatically because I can see -- this in lsp/util.lua: -- -- api.nvim_buf_set_option(floating_bufnr, 'modifiable', false) -- -- but it doesn't seem to be working. vim.api.nvim_buf_set_option(0, 'modifiable', false) end end) end lsp.init = function () require'lspconfig'.clangd.setup{ cmd = {'clangd', '--background-index'}, on_attach = on_attach, } -- If you're feeling brave after reading: -- -- https://github.com/neovim/nvim-lspconfig/issues/319 -- -- Install: -- -- :LspInstall sumneko_lua -- -- After marvelling at the horror that is the installation script: -- -- https://github.com/neovim/nvim-lspconfig/blob/master/lua/lspconfig/sumneko_lua.lua -- -- To see path: -- -- :LspInstallInfo sumneko_lua -- -- See: https://github.com/neovim/nvim-lspconfig#sumneko_lua -- -- Failing that; you can install by hand: -- -- https://github.com/sumneko/lua-language-server/wiki/Build-and-Run-(Standalone) -- local cmd = vim.fn.expand( '~/code/lua-language-server/bin/macOS/lua-language-server' ) local main = vim.fn.expand('~/code/lua-language-server/main.lua') if vim.fn.executable(cmd) == 1 then require'lspconfig'.sumneko_lua.setup{ cmd = {cmd, '-E', main}, on_attach = on_attach, settings = { Lua = { diagnostics = { enable = true, globals = {'vim'}, }, filetypes = {'lua'}, runtime = { path = vim.split(package.path, ';'), version = 'LuaJIT', }, } }, } end require'lspconfig'.ocamlls.setup{ on_attach = on_attach, } require'lspconfig'.tsserver.setup{ -- cmd = { -- "typescript-language-server", -- "--stdio", -- "--tsserver-log-file", -- "tslog" -- }, on_attach = on_attach, } require'lspconfig'.vimls.setup{ on_attach = on_attach, } -- Override hover winhighlight. local method = 'textDocument/hover' local hover = vim.lsp.handlers[method] vim.lsp.handlers[method] = function (_, method, result) hover(_, method, result) for _, winnr in ipairs(vim.api.nvim_tabpage_list_wins(0)) do if pcall(function () vim.api.nvim_win_get_var(winnr, 'textDocument/hover') end) then vim.api.nvim_win_set_option(winnr, 'winhighlight', 'Normal:Visual,NormalNC:Visual') break else -- Not a hover window. end end end end lsp.set_up_highlights = function () local pinnacle = require'wincent.pinnacle' vim.cmd('highlight LspDiagnosticsDefaultError ' .. pinnacle.decorate('italic,underline', 'ModeMsg')) vim.cmd('highlight LspDiagnosticsDefaultHint ' .. pinnacle.decorate('bold,italic,underline', 'Type')) vim.cmd('highlight LspDiagnosticsSignHint ' .. pinnacle.highlight({ bg = pinnacle.extract_bg('ColorColumn'), fg = pinnacle.extract_fg('Type'), })) vim.cmd('highlight LspDiagnosticsSignError ' .. pinnacle.highlight({ bg = pinnacle.extract_bg('ColorColumn'), fg = pinnacle.extract_fg('ErrorMsg'), })) end return lsp
local lsp = {} local nnoremap = function (lhs, rhs) vim.api.nvim_buf_set_keymap(0, 'n', lhs, rhs, {noremap = true, silent = true}) end local on_attach = function () local mappings = { ['<Leader>ld'] = '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>', ['<c-]>'] = '<cmd>lua vim.lsp.buf.definition()<CR>', ['K'] = '<cmd>lua vim.lsp.buf.hover()<CR>', ['gd'] = '<cmd>lua vim.lsp.buf.declaration()<CR>', } for lhs, rhs in pairs(mappings) do nnoremap(lhs, rhs) end vim.api.nvim_win_set_option(0, 'signcolumn', 'yes') end lsp.bind = function () pcall(function () if vim.api.nvim_win_get_var(0, 'textDocument/hover') then nnoremap('K', ':call nvim_win_close(0, v:true)<CR>') nnoremap('<Esc>', ':call nvim_win_close(0, v:true)<CR>') vim.api.nvim_win_set_option(0, 'cursorline', false) -- I believe this is supposed to happen automatically because I can see -- this in lsp/util.lua: -- -- api.nvim_buf_set_option(floating_bufnr, 'modifiable', false) -- -- but it doesn't seem to be working. vim.api.nvim_buf_set_option(0, 'modifiable', false) end end) end lsp.init = function () require'lspconfig'.clangd.setup{ cmd = {'clangd', '--background-index'}, on_attach = on_attach, } -- If you're feeling brave after reading: -- -- https://github.com/neovim/nvim-lspconfig/issues/319 -- -- Install: -- -- :LspInstall sumneko_lua -- -- After marvelling at the horror that is the installation script: -- -- https://github.com/neovim/nvim-lspconfig/blob/master/lua/lspconfig/sumneko_lua.lua -- -- To see path: -- -- :LspInstallInfo sumneko_lua -- -- See: https://github.com/neovim/nvim-lspconfig#sumneko_lua -- -- Failing that; you can install by hand: -- -- https://github.com/sumneko/lua-language-server/wiki/Build-and-Run-(Standalone) -- local cmd = vim.fn.expand( '~/code/lua-language-server/bin/macOS/lua-language-server' ) local main = vim.fn.expand('~/code/lua-language-server/main.lua') if vim.fn.executable(cmd) == 1 then require'lspconfig'.sumneko_lua.setup{ cmd = {cmd, '-E', main}, on_attach = on_attach, settings = { Lua = { diagnostics = { enable = true, globals = {'vim'}, }, filetypes = {'lua'}, runtime = { path = vim.split(package.path, ';'), version = 'LuaJIT', }, } }, } end require'lspconfig'.ocamlls.setup{ on_attach = on_attach, } require'lspconfig'.tsserver.setup{ -- cmd = { -- "typescript-language-server", -- "--stdio", -- "--tsserver-log-file", -- "tslog" -- }, on_attach = on_attach, } require'lspconfig'.vimls.setup{ on_attach = on_attach, } -- Override hover winhighlight. local method = 'textDocument/hover' local hover = vim.lsp.handlers[method] vim.lsp.handlers[method] = function (_, method, result) hover(_, method, result) for _, winnr in ipairs(vim.api.nvim_tabpage_list_wins(0)) do if pcall(function () vim.api.nvim_win_get_var(winnr, 'textDocument/hover') end) then vim.api.nvim_win_set_option(winnr, 'winhighlight', 'Normal:Visual,NormalNC:Visual') break else -- Not a hover window. end end end end lsp.set_up_highlights = function () local pinnacle = require'wincent.pinnacle' vim.cmd('highlight LspDiagnosticsDefaultError ' .. pinnacle.decorate('italic,underline', 'ModeMsg')) vim.cmd('highlight LspDiagnosticsDefaultHint ' .. pinnacle.decorate('bold,italic,underline', 'Type')) vim.cmd('highlight LspDiagnosticsSignHint ' .. pinnacle.highlight({ bg = pinnacle.extract_bg('ColorColumn'), fg = pinnacle.extract_fg('Type'), })) vim.cmd('highlight LspDiagnosticsSignError ' .. pinnacle.highlight({ bg = pinnacle.extract_bg('ColorColumn'), fg = pinnacle.extract_fg('ErrorMsg'), })) vim.cmd('highlight LspDiagnosticsSignInformation ' .. pinnacle.highlight({ bg = pinnacle.extract_bg('ColorColumn'), fg = pinnacle.extract_fg('LspDiagnosticsDefaultHint'), })) vim.cmd('highlight LspDiagnosticsSignWarning ' .. pinnacle.highlight({ bg = pinnacle.extract_bg('ColorColumn'), fg = pinnacle.extract_fg('LspDiagnosticsDefaultHint'), })) end return lsp
fix(vim): provide missing highlighting for two LspDiagnostics groups
fix(vim): provide missing highlighting for two LspDiagnostics groups These were linking to two cleared groups: LspDiagnosticsDefaultWarning xxx cleared LspDiagnosticsDefaultInformation xxx cleared so showed up as white text on black background, which is a bit ugly... I don't know if this is the best approach, but the least we can do is give it a decent `ColorColumn` background to match the other stuff in the gutter.
Lua
unlicense
wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent
f365550b7dac594bc275cb4c8e67bf327613bfba
matlab/simple_solids/vrep_cuboid_script_drop_exp.lua
matlab/simple_solids/vrep_cuboid_script_drop_exp.lua
-- DO NOT WRITE CODE OUTSIDE OF THE if-then-end SECTIONS BELOW!! (unless the code is a function definition) if (sim_call_type==sim_childscriptcall_initialization) then handle=simGetObjectHandle('Cuboid') init_pose=io.open("/home/ratnesh/projects/riss/windows_riss_code/bingham/matlab/simple_solids/data/vrep_cube_0.35/1/init_pose.csv", "w"); final_pose=io.open("/home/ratnesh/projects/riss/windows_riss_code/bingham/matlab/simple_solids/data/vrep_cube_0.35/1/final_pose.csv", "w"); init_pose_euler=io.open("/home/ratnesh/projects/riss/windows_riss_code/bingham/matlab/simple_solids/data/vrep_cube_0.35/1/init_pose_euler.csv", "w"); final_pose_euler=io.open("/home/ratnesh/projects/riss/windows_riss_code/bingham/matlab/simple_solids/data/vrep_cube_0.35/1/final_pose_euler.csv", "w"); count=0; -- debug=0; no_of_trials = 6000; threshold = 100*(no_of_trials+1); threshold_final_pose = 100*no_of_trials; r2a = 180/math.pi; end if (sim_call_type==sim_childscriptcall_actuation) then if count < threshold then local position=simGetObjectPosition(handle,-1) local quaternion=simGetObjectQuaternion(handle,-1) local orientation=simGetObjectOrientation(handle, -1) if (count%100==0) then if count ~= 0 then -- no final pose written at the beginning of the simulation final_pose:write(count/100,",", position[1], ",", position[2], ",", position[3], ",", quaternion[1], "," , quaternion[2], ",", quaternion[3], ",", quaternion[4], "\n") final_pose_euler:write(position[1], ",", position[2], ",", position[3], ",", r2a*orientation[1], "," , r2a*orientation[2], ",", r2a*orientation[3], "\n") end position[1] = math.random(); position[2] = math.random(); position[3] = 2.5+math.random(); --because setting random orientation via euler angles is easier than setting it via random quaternions orientation[1] = math.random(-180,180)*math.pi/180.0; orientation[2] = math.random(-180,180)*math.pi/180.0; orientation[3] = math.random(-180,180)*math.pi/180.0; simSetObjectPosition(handle,-1,position); simSetObjectOrientation(handle,-1,orientation) quat_test = simGetObjectQuaternion(handle, -1) -- euler_test = simGetObjectOrientation(handle, -1) --last value is garbage if count < threshold_final_pose then init_pose:write(count/100, ",",position[1], ",", position[2], ",", position[3], ",", quat_test[1], "," , quat_test[2], ",", quat_test[3], ",", quat_test[4], "\n") init_pose_euler:write(position[1], ",", position[2], ",", position[3], ",", r2a*orientation[1], "," , r2a*orientation[2], ",", r2a*orientation[3], "\n") end end count = count+1; end end if (sim_call_type==sim_childscriptcall_sensing) then -- Put your main SENSING code here end if (sim_call_type==sim_childscriptcall_cleanup) then erlFile:close() -- Put some restoration code here end
-- DO NOT WRITE CODE OUTSIDE OF THE if-then-end SECTIONS BELOW!! (unless the code is a function definition) if (sim_call_type==sim_childscriptcall_initialization) then handle=simGetObjectHandle('Cuboid') init_pose=io.open("/home/ratnesh/projects/riss/windows_riss_code/bingham/matlab/simple_solids/data/vrep_exp_cube_0.35/4_small_drop/init_pose.csv", "w"); final_pose=io.open("/home/ratnesh/projects/riss/windows_riss_code/bingham/matlab/simple_solids/data/vrep_exp_cube_0.35/4_small_drop/final_pose.csv", "w"); init_pose_euler=io.open("/home/ratnesh/projects/riss/windows_riss_code/bingham/matlab/simple_solids/data/vrep_cube_0.35/4_small_drop/init_pose_euler.csv", "w"); final_pose_euler=io.open("/home/ratnesh/projects/riss/windows_riss_code/bingham/matlab/simple_solids/data/vrep_cube_0.35/4_small_drop/final_pose_euler.csv", "w"); count=0; -- debug=0; no_of_trials = 6000; threshold = 100*(no_of_trials+1); threshold_final_pose = 100*no_of_trials; r2a = 180/math.pi; end if (sim_call_type==sim_childscriptcall_actuation) then if count < threshold then local position=simGetObjectPosition(handle,-1) local quaternion=simGetObjectQuaternion(handle,-1) local orientation=simGetObjectOrientation(handle, -1) if (count%100==0) then if count ~= 0 then -- no final pose written at the beginning of the simulation final_pose:write(count/100,",", quaternion[4], "," , quaternion[1], ",", quaternion[2], ",", quaternion[3], "\n") end position[1] = math.random(); position[2] = math.random(); position[3] = 0.4+math.random(); --because setting random orientation via euler angles is easier than setting it via random quaternions orientation[1] = math.random(-180,180)*math.pi/180.0; orientation[2] = math.random(-180,180)*math.pi/180.0; orientation[3] = math.random(-180,180)*math.pi/180.0; simSetObjectPosition(handle,-1,position); simSetObjectOrientation(handle,-1,orientation); quat_get = simGetObjectQuaternion(handle, -1); -- euler_test = simGetObjectOrientation(handle, -1) --last value is garbage if count < threshold_final_pose then init_pose:write(count/100,",", quat_get[4], ",", quat_get[1], ",", quat_get[2], ",", quat_get[3], "\n") end end count = count+1; end end if (sim_call_type==sim_childscriptcall_sensing) then -- Put your main SENSING code here end if (sim_call_type==sim_childscriptcall_cleanup) then -- Put some restoration code here end
vrep: fixes/changes drop exp child script
vrep: fixes/changes drop exp child script
Lua
bsd-3-clause
madratman/riss_bingham,madratman/riss_bingham,madratman/riss_bingham,madratman/riss_bingham,madratman/riss_bingham,madratman/riss_bingham,madratman/riss_bingham,madratman/riss_bingham
552a7b4d1b81fb764da58408ae8f775ed5fa93da
util/sasl.lua
util/sasl.lua
local md5 = require "util.hashes".md5; local log = require "util.logger".init("sasl"); local tostring = tostring; local st = require "util.stanza"; local generate_uuid = require "util.uuid".generate; local s_match = string.match; local gmatch = string.gmatch local string = string local math = require "math" local type = type local error = error local print = print module "sasl" local function new_plain(realm, password_handler) local object = { mechanism = "PLAIN", realm = realm, password_handler = password_handler} function object.feed(self, message) if message == "" or message == nil then return "failure", "malformed-request" end local response = message local authorization = s_match(response, "([^&%z]+)") local authentication = s_match(response, "%z([^&%z]+)%z") local password = s_match(response, "%z[^&%z]+%z([^&%z]+)") if authentication == nil or password == nil then return "failure", "malformed-request" end local password_encoding, correct_password = self.password_handler(authentication, self.realm, "PLAIN") if correct_password == nil then return "failure", "not-authorized" elseif correct_password == false then return "failure", "account-disabled" end local claimed_password = "" if password_encoding == nil then claimed_password = password else claimed_password = password_encoding(password) end self.username = authentication if claimed_password == correct_password then return "success" else return "failure", "not-authorized" end end return object end local function new_digest_md5(realm, password_handler) --TODO maybe support for authzid local function serialize(message) local data = "" if type(message) ~= "table" then error("serialize needs an argument of type table.") end -- testing all possible values if message["nonce"] then data = data..[[nonce="]]..message.nonce..[[",]] end if message["qop"] then data = data..[[qop="]]..message.qop..[[",]] end if message["charset"] then data = data..[[charset=]]..message.charset.."," end if message["algorithm"] then data = data..[[algorithm=]]..message.algorithm.."," end if message["realm"] then data = data..[[realm="]]..message.realm..[[",]] end if message["rspauth"] then data = data..[[rspauth=]]..message.rspauth.."," end data = data:gsub(",$", "") return data end local function parse(data) message = {} for k, v in gmatch(data, [[([%w%-]+)="?([^",]*)"?,?]]) do message[k] = v end return message end local object = { mechanism = "DIGEST-MD5", realm = realm, password_handler = password_handler} --TODO: something better than math.random would be nice, maybe OpenSSL's random number generator object.nonce = generate_uuid() object.step = 0 object.nonce_count = {} function object.feed(self, message) self.step = self.step + 1 if (self.step == 1) then local challenge = serialize({ nonce = object.nonce, qop = "auth", charset = "utf-8", algorithm = "md5-sess", realm = self.realm}); return "challenge", challenge elseif (self.step == 2) then local response = parse(message) -- check for replay attack if response["nc"] then if self.nonce_count[response["nc"]] then return "failure", "not-authorized" end end -- check for username, it's REQUIRED by RFC 2831 if not response["username"] then return "failure", "malformed-request" end self["username"] = response["username"] -- check for nonce, ... if not response["nonce"] then return "failure", "malformed-request" else -- check if it's the right nonce if response["nonce"] ~= tostring(self.nonce) then return "failure", "malformed-request" end end if not response["cnonce"] then return "failure", "malformed-request", "Missing entry for cnonce in SASL message." end if not response["qop"] then response["qop"] = "auth" end if response["realm"] == nil then response["realm"] = "" end local domain = "" local protocol = "" if response["digest-uri"] then protocol, domain = response["digest-uri"]:match("(%w+)/(.*)$") if protocol == nil or domain == nil then return "failure", "malformed-request" end else return "failure", "malformed-request", "Missing entry for digest-uri in SASL message." end --TODO maybe realm support self.username = response["username"] local password_encoding, Y = self.password_handler(response["username"], response["realm"], "DIGEST-MD5") if Y == nil then return "failure", "not-authorized" elseif Y == false then return "failure", "account-disabled" end local A1 = Y..":"..response["nonce"]..":"..response["cnonce"]--:authzid local A2 = "AUTHENTICATE:"..protocol.."/"..domain local HA1 = md5(A1, true) local HA2 = md5(A2, true) local KD = HA1..":"..response["nonce"]..":"..response["nc"]..":"..response["cnonce"]..":"..response["qop"]..":"..HA2 local response_value = md5(KD, true) if response_value == response["response"] then -- calculate rspauth A2 = ":"..protocol.."/"..domain HA1 = md5(A1, true) HA2 = md5(A2, true) KD = HA1..":"..response["nonce"]..":"..response["nc"]..":"..response["cnonce"]..":"..response["qop"]..":"..HA2 local rspauth = md5(KD, true) self.authenticated = true return "challenge", serialize({rspauth = rspauth}) else return "failure", "not-authorized", "The response provided by the client doesn't match the one we calculated." end elseif self.step == 3 then if self.authenticated ~= nil then return "success" else return "failure", "malformed-request" end end end return object end function new(mechanism, realm, password_handler) local object if mechanism == "PLAIN" then object = new_plain(realm, password_handler) elseif mechanism == "DIGEST-MD5" then object = new_digest_md5(realm, password_handler) else log("debug", "Unsupported SASL mechanism: "..tostring(mechanism)); return nil end return object end return _M;
local md5 = require "util.hashes".md5; local log = require "util.logger".init("sasl"); local tostring = tostring; local st = require "util.stanza"; local generate_uuid = require "util.uuid".generate; local s_match = string.match; local gmatch = string.gmatch local string = string local math = require "math" local type = type local error = error local print = print module "sasl" local function new_plain(realm, password_handler) local object = { mechanism = "PLAIN", realm = realm, password_handler = password_handler} function object.feed(self, message) if message == "" or message == nil then return "failure", "malformed-request" end local response = message local authorization = s_match(response, "([^&%z]+)") local authentication = s_match(response, "%z([^&%z]+)%z") local password = s_match(response, "%z[^&%z]+%z([^&%z]+)") if authentication == nil or password == nil then return "failure", "malformed-request" end local password_encoding, correct_password = self.password_handler(authentication, self.realm, "PLAIN") if correct_password == nil then return "failure", "not-authorized" elseif correct_password == false then return "failure", "account-disabled" end local claimed_password = "" if password_encoding == nil then claimed_password = password else claimed_password = password_encoding(password) end self.username = authentication if claimed_password == correct_password then return "success" else return "failure", "not-authorized" end end return object end local function new_digest_md5(realm, password_handler) --TODO maybe support for authzid local function serialize(message) local data = "" if type(message) ~= "table" then error("serialize needs an argument of type table.") end -- testing all possible values if message["nonce"] then data = data..[[nonce="]]..message.nonce..[[",]] end if message["qop"] then data = data..[[qop="]]..message.qop..[[",]] end if message["charset"] then data = data..[[charset=]]..message.charset.."," end if message["algorithm"] then data = data..[[algorithm=]]..message.algorithm.."," end if message["realm"] then data = data..[[realm="]]..message.realm..[[",]] end if message["rspauth"] then data = data..[[rspauth=]]..message.rspauth.."," end data = data:gsub(",$", "") return data end local function parse(data) message = {} for k, v in gmatch(data, [[([%w%-]+)="?([^",]*)"?,?]]) do -- FIXME The hacky regex makes me shudder message[k] = v end return message end local object = { mechanism = "DIGEST-MD5", realm = realm, password_handler = password_handler} --TODO: something better than math.random would be nice, maybe OpenSSL's random number generator object.nonce = generate_uuid() object.step = 0 object.nonce_count = {} function object.feed(self, message) self.step = self.step + 1 if (self.step == 1) then local challenge = serialize({ nonce = object.nonce, qop = "auth", charset = "utf-8", algorithm = "md5-sess", realm = self.realm}); return "challenge", challenge elseif (self.step == 2) then local response = parse(message) -- check for replay attack if response["nc"] then if self.nonce_count[response["nc"]] then return "failure", "not-authorized" end end -- check for username, it's REQUIRED by RFC 2831 if not response["username"] then return "failure", "malformed-request" end self["username"] = response["username"] -- check for nonce, ... if not response["nonce"] then return "failure", "malformed-request" else -- check if it's the right nonce if response["nonce"] ~= tostring(self.nonce) then return "failure", "malformed-request" end end if not response["cnonce"] then return "failure", "malformed-request", "Missing entry for cnonce in SASL message." end if not response["qop"] then response["qop"] = "auth" end if response["realm"] == nil then response["realm"] = "" end local domain = "" local protocol = "" if response["digest-uri"] then protocol, domain = response["digest-uri"]:match("(%w+)/(.*)$") if protocol == nil or domain == nil then return "failure", "malformed-request" end else return "failure", "malformed-request", "Missing entry for digest-uri in SASL message." end --TODO maybe realm support self.username = response["username"] local password_encoding, Y = self.password_handler(response["username"], response["realm"], "DIGEST-MD5") if Y == nil then return "failure", "not-authorized" elseif Y == false then return "failure", "account-disabled" end local A1 = Y..":"..response["nonce"]..":"..response["cnonce"]--:authzid local A2 = "AUTHENTICATE:"..protocol.."/"..domain local HA1 = md5(A1, true) local HA2 = md5(A2, true) local KD = HA1..":"..response["nonce"]..":"..response["nc"]..":"..response["cnonce"]..":"..response["qop"]..":"..HA2 local response_value = md5(KD, true) if response_value == response["response"] then -- calculate rspauth A2 = ":"..protocol.."/"..domain HA1 = md5(A1, true) HA2 = md5(A2, true) KD = HA1..":"..response["nonce"]..":"..response["nc"]..":"..response["cnonce"]..":"..response["qop"]..":"..HA2 local rspauth = md5(KD, true) self.authenticated = true return "challenge", serialize({rspauth = rspauth}) else return "failure", "not-authorized", "The response provided by the client doesn't match the one we calculated." end elseif self.step == 3 then if self.authenticated ~= nil then return "success" else return "failure", "malformed-request" end end end return object end function new(mechanism, realm, password_handler) local object if mechanism == "PLAIN" then object = new_plain(realm, password_handler) elseif mechanism == "DIGEST-MD5" then object = new_digest_md5(realm, password_handler) else log("debug", "Unsupported SASL mechanism: "..tostring(mechanism)); return nil end return object end return _M;
Added a FIXME
Added a FIXME
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
61d0a3777fe9f575fdcbf704b6a007329646db1a
lib/switchboard_modules/lua_script_debugger/premade_scripts/t4/t4_basic_io.lua
lib/switchboard_modules/lua_script_debugger/premade_scripts/t4/t4_basic_io.lua
print("T4 Basic I/O Example") -- This is a basic lua script example that interacts with analog and digital I/O -- on the T4 once per second. During initialization, all of the flexible I/O -- lines get configured as digital I/O. Once running, once per second, an -- analog value is read from AIN0 and written to DAC0. FIO4 is read and its -- state is written to FIO5. -- If we are not running on a T4, stop the script. devType = MB.R(60000, 3) if devType ~= 4 then print("Device is not a T4") MB.W(6000, 1, 0); end -- Configure flexible I/O lines as digital inputs and outputs. print('Val:', 0x0F0) MB.W(2880, 1, 0x000) -- Write to the DIO_ANALOG_ENABLE register: https://labjack.com/support/datasheets/t-series/digital-io/flexible-io -- to configure all flexible I/O lines (FIO4->FIO7 and EIO0->EIO3) -- Set up a 1 second timer LJ.IntervalConfig(0, 1000) -- define used variables. ainVal = 0 dacVal = 0 dioState = 0 -- Enter a permanent while loop while true do if LJ.CheckInterval(0) then -- Interval completed. -- Read AIN0 ainVal = MB.R(0, 3) -- Make sure the AIN0 value is between 0V and 5V dacVal = ainVal if(ainVal > 5) then dacVal = 5 end if(ainVal < 0) then dacVal = 0 end -- Write the AIN0 value to DAC0. MB.W(1000, 3, dacVal) -- Read FIO4 and write to FIO5 dioState = MB.R(2004, 0) MB.W(2005, 0, dioState) print('Set DAC0 to:', dacVal) print('Set FIO5 to:', dioState) print('') -- Print a new-line end end
--[[ Name: t4_basic_io.lua Desc: This is a basic lua script example that interacts with analog and digital I/O on the T4. During initialization, all of the flexible I/O lines get configured as digital I/O. Once running, once per second, an analog value is read from AIN0 and written to DAC0. FIO4 is read and its state is written to FIO5. Note: See our website for more information on flexible I/O: https://labjack.com/support/datasheets/t-series/digital-io/flexible-io --]] print("T4 Basic I/O Example") -- Get the device type by reading the PRODUCT_ID register local devtype = MB.R(60000, 3) -- If the user is not using a T4 exit the script if devtype ~= 4 then print("Device is not a T4") -- Write 0 to LUA_RUN to stop the script MB.W(6000, 1, 0); end -- Write 0 to the DIO_ANALOG_ENABLE register to configure all FIO lines as -- digital I/O MB.W(2880, 1, 0x000) -- Set up a 1 second interval LJ.IntervalConfig(0, 1000) -- Run the program in an infinite loop while true do -- If the interval is done if LJ.CheckInterval(0) then -- Read AIN0 local ainval = MB.R(0, 3) -- Ensure the AIN0 value is between 0V and 5V local dacval = ainval if(ainval > 5) then dacval = 5 end if(ainval < 0) then dacval = 0 end -- Write the AIN0 value to DAC0. MB.W(1000, 3, dacval) -- Read FIO4 and write its value to FIO5 local fioval = MB.R(2004, 0) MB.W(2005, 0, fioval) print('Set DAC0 to:', dacval) print('Set FIO5 to:', fioval) print('') -- Print a new-line end end
Fixed up the formatting of the T4 basic I/O example
Fixed up the formatting of the T4 basic I/O example
Lua
mit
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
44c41e57d077a7b03380358f90d0c366ab4bf056
applications/luci-app-travelmate/luasrc/model/cbi/travelmate/setup_tab.lua
applications/luci-app-travelmate/luasrc/model/cbi/travelmate/setup_tab.lua
-- Copyright 2017 Dirk Brenken ([email protected]) -- This is free software, licensed under the Apache License, Version 2.0 local nw = require("luci.model.network").init() local fw = require("luci.model.firewall").init() local util = require("luci.util") local uci = require("luci.model.uci").cursor() m = SimpleForm("network", translate("Interface Setup"), translate("Automatically create a new wireless wan interface, configure it to use dhcp and " .. "add it to the wan zone of the firewall. This step has only to be done once.")) m.reset = false iface = m:field(Value, "netname", translate("Name of the new wireless wan interface"), translate("The allowed characters are: <code>A-Z</code>, <code>a-z</code>, " .. "<code>0-9</code> and <code>_</code> (3-15 characters).")) iface.default = "wwan" iface.datatype = "and(uciname,minlength(3),maxlength(15))" function iface.validate(self, value, section) local value = iface:formvalue(section) local name = uci.get("network", value) if name then iface:add_error(section, translate("The given network interface name already exist")) else iface.datatype = false iface.default = iface.disabled f = m:field(DummyValue, "textfield", "&nbsp;", translate("Direct Link: " .. [[<a href="]] .. luci.dispatcher.build_url("admin/network/wireless") .. [[">]] .. "Wireless Setup" .. [[</a>]])) f.default = translate("Network Interface '" .. value .. "' created successfully." .. " Feel free to scan & add new stations via standard wireless setup.") f.disabled = true end return value end function iface.write(self, section, value) local name = iface:formvalue(section) if name then local net = nw:add_network(name, { proto = "dhcp" }) if net then nw:save("network") nw:commit("network") local zone = fw:get_zone_by_network("wan") if zone then zone:add_network(name) fw:save("firewall") fw:commit("firewall") end end end end return m
-- Copyright 2017 Dirk Brenken ([email protected]) -- This is free software, licensed under the Apache License, Version 2.0 local nw = require("luci.model.network").init() local fw = require("luci.model.firewall").init() local util = require("luci.util") local uci = require("luci.model.uci").cursor() m = SimpleForm("network", translate("Interface Setup"), translate("Automatically create a new wireless wan interface, configure it to use dhcp and " .. "add it to the wan zone of the firewall. This step has only to be done once.")) m.reset = false iface = m:field(Value, "netname", translate("Name of the new wireless wan interface"), translate("The allowed characters are: <code>A-Z</code>, <code>a-z</code>, " .. "<code>0-9</code> and <code>_</code> (3-15 characters).")) iface.default = "wwan" iface.datatype = "and(uciname,minlength(3),maxlength(15))" function iface.validate(self, value, section) local value = iface:formvalue(section) local name = uci.get("network", value) if name then iface:add_error(section, translate("The given network interface name already exist")) else iface.datatype = false iface.default = iface.disabled f = m:field(DummyValue, "textfield", "&nbsp;", translatef("Direct Link: " .. "<a href=\"%s\">" .. "Wireless Setup</a>", luci.dispatcher.build_url("admin/network/wireless"))) f.default = translatef("Network Interface '%s' created successfully." .. " Feel free to scan & add new stations via standard wireless setup.", value) f.disabled = true end return value end function iface.write(self, section, value) local name = iface:formvalue(section) if name then local net = nw:add_network(name, { proto = "dhcp" }) if net then nw:save("network") nw:commit("network") local zone = fw:get_zone_by_network("wan") if zone then zone:add_network(name) fw:save("firewall") fw:commit("firewall") end end end end return m
luci-app-travelmate: Fix detection issues of i18n tools
luci-app-travelmate: Fix detection issues of i18n tools Fixed detection issues of i18n tools for translation target. 'translate()' -> 'translatef()' And fixed the format within that function. Signed-off-by: INAGAKI Hiroshi <[email protected]>
Lua
apache-2.0
kuoruan/lede-luci,Wedmer/luci,aa65535/luci,oneru/luci,artynet/luci,981213/luci-1,rogerpueyo/luci,remakeelectric/luci,nmav/luci,remakeelectric/luci,oneru/luci,981213/luci-1,openwrt/luci,LuttyYang/luci,openwrt/luci,taiha/luci,artynet/luci,rogerpueyo/luci,wongsyrone/luci-1,lbthomsen/openwrt-luci,oneru/luci,wongsyrone/luci-1,openwrt/luci,taiha/luci,chris5560/openwrt-luci,oneru/luci,LuttyYang/luci,wongsyrone/luci-1,Noltari/luci,aa65535/luci,nmav/luci,chris5560/openwrt-luci,artynet/luci,hnyman/luci,hnyman/luci,Noltari/luci,artynet/luci,openwrt-es/openwrt-luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,aa65535/luci,aa65535/luci,openwrt-es/openwrt-luci,oneru/luci,chris5560/openwrt-luci,Wedmer/luci,hnyman/luci,taiha/luci,LuttyYang/luci,openwrt/luci,wongsyrone/luci-1,artynet/luci,Noltari/luci,nmav/luci,taiha/luci,tobiaswaldvogel/luci,Noltari/luci,openwrt/luci,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,oneru/luci,kuoruan/luci,Noltari/luci,rogerpueyo/luci,981213/luci-1,lbthomsen/openwrt-luci,oneru/luci,hnyman/luci,oneru/luci,kuoruan/lede-luci,lbthomsen/openwrt-luci,kuoruan/lede-luci,Wedmer/luci,kuoruan/luci,kuoruan/luci,Wedmer/luci,tobiaswaldvogel/luci,kuoruan/luci,wongsyrone/luci-1,chris5560/openwrt-luci,kuoruan/lede-luci,remakeelectric/luci,lbthomsen/openwrt-luci,taiha/luci,Wedmer/luci,aa65535/luci,aa65535/luci,wongsyrone/luci-1,LuttyYang/luci,kuoruan/luci,aa65535/luci,taiha/luci,chris5560/openwrt-luci,taiha/luci,wongsyrone/luci-1,tobiaswaldvogel/luci,hnyman/luci,kuoruan/lede-luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci,Noltari/luci,Noltari/luci,nmav/luci,taiha/luci,kuoruan/luci,tobiaswaldvogel/luci,kuoruan/lede-luci,hnyman/luci,kuoruan/luci,rogerpueyo/luci,nmav/luci,kuoruan/lede-luci,lbthomsen/openwrt-luci,rogerpueyo/luci,Noltari/luci,hnyman/luci,remakeelectric/luci,Noltari/luci,Wedmer/luci,nmav/luci,artynet/luci,rogerpueyo/luci,hnyman/luci,wongsyrone/luci-1,openwrt-es/openwrt-luci,remakeelectric/luci,tobiaswaldvogel/luci,981213/luci-1,LuttyYang/luci,tobiaswaldvogel/luci,openwrt/luci,LuttyYang/luci,Wedmer/luci,tobiaswaldvogel/luci,remakeelectric/luci,981213/luci-1,lbthomsen/openwrt-luci,rogerpueyo/luci,artynet/luci,981213/luci-1,remakeelectric/luci,openwrt/luci,openwrt-es/openwrt-luci,nmav/luci,rogerpueyo/luci,LuttyYang/luci,aa65535/luci,kuoruan/lede-luci,artynet/luci,chris5560/openwrt-luci,chris5560/openwrt-luci,remakeelectric/luci,LuttyYang/luci,nmav/luci,openwrt/luci,lbthomsen/openwrt-luci,Wedmer/luci,981213/luci-1,openwrt-es/openwrt-luci,kuoruan/luci,nmav/luci,artynet/luci
4de6b495156fe8dbd74ec4b581a95af2c60564e0
src/extensions/cp/apple/finalcutpro/content/Clip.lua
src/extensions/cp/apple/finalcutpro/content/Clip.lua
--- === cp.apple.finalcutpro.content.Clip === --- --- Represents a clip of media inside FCP. local require = require --local log = require "hs.logger".new "Clip" local axutils = require "cp.ui.axutils" local Table = require "cp.ui.Table" local childWithRole = axutils.childWithRole local Clip = {} Clip.mt = {} Clip.type = {} --- cp.apple.finalcutpro.content.Clip.type.filmstrip --- Constant --- A constant for clips which are represented by a filmstrip. Clip.type.filmstrip = "filmstrip" --- cp.apple.finalcutpro.content.Clip.type.row --- Constant --- A constant for clips which are represented by a table row. Clip.type.row = "row" --- cp.apple.finalcutpro.content.Clip:UI() -> axuielement --- Method --- Returns the `axuielement` for the clip. --- --- Parameters: --- * None --- --- Returns: --- * The `axuielement` for the clip. function Clip.mt:UI() return self._element end --- cp.apple.finalcutpro.content.Clip:getType() -> Clip.type --- Method --- Returns the type of clip (one of the `Clip.type` values) --- --- Parameters: --- * None --- --- Returns: --- * The `Clip.type` value (e.g. `Clip.type.row` or Clip.type.filmstrip`) function Clip.mt:getType() return self._type end --- cp.apple.finalcutpro.content.Clip:getTitle() -> String --- Method --- Returns the title of the clip. --- --- Parameters: --- * None --- --- Returns: --- * The clip title. function Clip.mt:getTitle() if self:getType() == Clip.type.row then local colIndex = self._options.columnIndex local cell = self._element[colIndex] return Table.cellTextValue(cell) else return self._element:attributeValue("AXDescription") end end --- cp.apple.finalcutpro.content.Clip:setTitle(title) -> none --- Method --- Sets the title of a clip. --- --- Parameters: --- * None --- --- Returns: --- * None function Clip.mt:setTitle(title) if self:getType() == Clip.type.row then local colIndex = self._options.columnIndex local cell = self._element[colIndex] local textfield = cell and childWithRole(cell, "AXTextField") if textfield then textfield:setAttributeValue("AXValue", title) end else local textfield = self._element and childWithRole(self._element, "AXTextField") if textfield then textfield:setAttributeValue("AXValue", title) end end end --- cp.apple.finalcutpro.content.Clip.new(element[, options]) -> Clip --- Constructor --- Creates a new `Clip` pointing at the specified element, with the specified options. --- --- Parameters: --- * `element` - The `axuielement` the clip represents. --- * `options` - A table containing the options for the clip. --- --- Returns: --- * The new `Clip`. --- --- Notes: --- * The options may be: --- ** `columnIndex` - A number which will be used to specify the column number to find the title in, if relevant. function Clip.new(element, options) local o = { _element = element, _options = options or {}, _type = element:attributeValue("AXRole") == "AXRow" and Clip.type.row or Clip.type.filmstrip, } return setmetatable(o, {__index = Clip.mt}) end --- cp.apple.finalcutpro.content.Clip.is(thing) -> boolean --- Function --- Checks if the specified `thing` is a `Clip` instance. --- --- Parameters: --- * `thing` - The thing to check. --- --- Returns: --- * `true` if the `thing` is a `Clip`, otherwise returns `false`. function Clip.is(thing) return thing and getmetatable(thing) == Clip.mt end return Clip
--- === cp.apple.finalcutpro.content.Clip === --- --- Represents a clip of media inside FCP. local require = require --local log = require "hs.logger".new "Clip" local axutils = require "cp.ui.axutils" local Table = require "cp.ui.Table" local childWithRole = axutils.childWithRole local Clip = {} Clip.mt = {} Clip.type = {} --- cp.apple.finalcutpro.content.Clip.type.filmstrip --- Constant --- A constant for clips which are represented by a filmstrip. Clip.type.filmstrip = "filmstrip" --- cp.apple.finalcutpro.content.Clip.type.row --- Constant --- A constant for clips which are represented by a table row. Clip.type.row = "row" --- cp.apple.finalcutpro.content.Clip:UI() -> axuielement --- Method --- Returns the `axuielement` for the clip. --- --- Parameters: --- * None --- --- Returns: --- * The `axuielement` for the clip. function Clip.mt:UI() return self._element end --- cp.apple.finalcutpro.content.Clip:getType() -> Clip.type --- Method --- Returns the type of clip (one of the `Clip.type` values) --- --- Parameters: --- * None --- --- Returns: --- * The `Clip.type` value (e.g. `Clip.type.row` or Clip.type.filmstrip`) function Clip.mt:getType() return self._type end --- cp.apple.finalcutpro.content.Clip:getTitle() -> String --- Method --- Returns the title of the clip. --- --- Parameters: --- * None --- --- Returns: --- * The clip title. function Clip.mt:getTitle() if self:getType() == Clip.type.row then local colIndex = self._options.columnIndex local cell = self._element[colIndex] return Table.cellTextValue(cell) else return self._element:attributeValue("AXDescription") end end --- cp.apple.finalcutpro.content.Clip:setTitle(title) -> none --- Method --- Sets the title of a clip. --- --- Parameters: --- * None --- --- Returns: --- * None function Clip.mt:setTitle(title) if self:getType() == Clip.type.row then local colIndex = self._options.columnIndex local cell = self._element[colIndex] local textfield = cell and childWithRole(cell, "AXTextField") if textfield then textfield:setAttributeValue("AXFocused", true) textfield:setAttributeValue("AXValue", title) textfield:performAction("AXConfirm") end else local textfield = self._element and childWithRole(self._element, "AXTextField") if textfield then textfield:setAttributeValue("AXFocused", true) textfield:setAttributeValue("AXValue", title) textfield:performAction("AXConfirm") end end end --- cp.apple.finalcutpro.content.Clip.new(element[, options]) -> Clip --- Constructor --- Creates a new `Clip` pointing at the specified element, with the specified options. --- --- Parameters: --- * `element` - The `axuielement` the clip represents. --- * `options` - A table containing the options for the clip. --- --- Returns: --- * The new `Clip`. --- --- Notes: --- * The options may be: --- ** `columnIndex` - A number which will be used to specify the column number to find the title in, if relevant. function Clip.new(element, options) local o = { _element = element, _options = options or {}, _type = element:attributeValue("AXRole") == "AXRow" and Clip.type.row or Clip.type.filmstrip, } return setmetatable(o, {__index = Clip.mt}) end --- cp.apple.finalcutpro.content.Clip.is(thing) -> boolean --- Function --- Checks if the specified `thing` is a `Clip` instance. --- --- Parameters: --- * `thing` - The thing to check. --- --- Returns: --- * `true` if the `thing` is a `Clip`, otherwise returns `false`. function Clip.is(thing) return thing and getmetatable(thing) == Clip.mt end return Clip
Fixed a bug in Clip:setTitle()
Fixed a bug in Clip:setTitle() - Fixed a bug which was causing the HUD Batch Rename tool to fail - Closes #2211
Lua
mit
fcpxhacks/fcpxhacks,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost
ae5ccb4af05450bb384de9e7cc1dd2d0d2d94af9
Interface/AddOns/RayUI/modules/skins/blizzard/quest.lua
Interface/AddOns/RayUI/modules/skins/blizzard/quest.lua
local R, L, P = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, local local S = R:GetModule("Skins") local function LoadSkin() local r, g, b = S["media"].classcolours[R.myclass].r, S["media"].classcolours[R.myclass].g, S["media"].classcolours[R.myclass].b S:ReskinPortraitFrame(QuestFrame, true) QuestFont:SetTextColor(1, 1, 1) QuestFrameDetailPanel:DisableDrawLayer("BACKGROUND") QuestFrameProgressPanel:DisableDrawLayer("BACKGROUND") QuestFrameRewardPanel:DisableDrawLayer("BACKGROUND") QuestFrameGreetingPanel:DisableDrawLayer("BACKGROUND") QuestFrameDetailPanel:DisableDrawLayer("BORDER") QuestFrameRewardPanel:DisableDrawLayer("BORDER") QuestDetailScrollFrameTop:Hide() QuestDetailScrollFrameBottom:Hide() QuestDetailScrollFrameMiddle:Hide() QuestProgressScrollFrameTop:Hide() QuestProgressScrollFrameBottom:Hide() QuestProgressScrollFrameMiddle:Hide() QuestRewardScrollFrameTop:Hide() QuestRewardScrollFrameBottom:Hide() QuestRewardScrollFrameMiddle:Hide() QuestGreetingScrollFrameTop:Hide() QuestGreetingScrollFrameBottom:Hide() QuestGreetingScrollFrameMiddle:Hide() QuestFrameProgressPanelMaterialTopLeft:SetAlpha(0) QuestFrameProgressPanelMaterialTopRight:SetAlpha(0) QuestFrameProgressPanelMaterialBotLeft:SetAlpha(0) QuestFrameProgressPanelMaterialBotRight:SetAlpha(0) local line = QuestFrameGreetingPanel:CreateTexture() line:SetTexture(1, 1, 1, .2) line:SetSize(256, 1) line:SetPoint("CENTER", QuestGreetingFrameHorizontalBreak) QuestGreetingFrameHorizontalBreak:SetTexture("") QuestFrameGreetingPanel:HookScript("OnShow", function() line:SetShown(QuestGreetingFrameHorizontalBreak:IsShown()) end) for i = 1, MAX_REQUIRED_ITEMS do local bu = _G["QuestProgressItem"..i] local ic = _G["QuestProgressItem"..i.."IconTexture"] local na = _G["QuestProgressItem"..i.."NameFrame"] local co = _G["QuestProgressItem"..i.."Count"] ic:SetSize(40, 40) ic:SetTexCoord(.08, .92, .08, .92) ic:SetDrawLayer("OVERLAY") S:CreateBD(bu, .25) na:Hide() co:SetDrawLayer("OVERLAY") local line = CreateFrame("Frame", nil, bu) line:SetSize(1, 40) line:SetPoint("RIGHT", ic, 1, 0) S:CreateBD(line) end QuestDetailScrollFrame:SetWidth(302) -- else these buttons get cut off hooksecurefunc(QuestProgressRequiredMoneyText, "SetTextColor", function(self, r, g, b) if r == 0 then self:SetTextColor(.8, .8, .8) elseif r == .2 then self:SetTextColor(1, 1, 1) end end) for _, questButton in pairs({"QuestFrameAcceptButton", "QuestFrameDeclineButton", "QuestFrameCompleteQuestButton", "QuestFrameCompleteButton", "QuestFrameGoodbyeButton", "QuestFrameGreetingGoodbyeButton"}) do S:Reskin(_G[questButton]) end S:ReskinScroll(QuestProgressScrollFrameScrollBar) S:ReskinScroll(QuestRewardScrollFrameScrollBar) S:ReskinScroll(QuestDetailScrollFrameScrollBar) S:ReskinScroll(QuestGreetingScrollFrameScrollBar) -- Text colour stuff QuestProgressRequiredItemsText:SetTextColor(1, 1, 1) QuestProgressRequiredItemsText:SetShadowColor(0, 0, 0) QuestProgressTitleText:SetTextColor(1, 1, 1) QuestProgressTitleText:SetShadowColor(0, 0, 0) QuestProgressTitleText.SetTextColor = R.dummy QuestProgressText:SetTextColor(1, 1, 1) QuestProgressText.SetTextColor = R.dummy GreetingText:SetTextColor(1, 1, 1) GreetingText.SetTextColor = R.dummy AvailableQuestsText:SetTextColor(1, 1, 1) AvailableQuestsText.SetTextColor = R.dummy AvailableQuestsText:SetShadowColor(0, 0, 0) CurrentQuestsText:SetTextColor(1, 1, 1) CurrentQuestsText.SetTextColor = R.dummy CurrentQuestsText:SetShadowColor(0, 0, 0) -- [[ Quest NPC model ]] QuestNPCModelShadowOverlay:Hide() QuestNPCModelBg:Hide() QuestNPCModel:DisableDrawLayer("OVERLAY") QuestNPCModelNameText:SetDrawLayer("ARTWORK") QuestNPCModelTextFrameBg:Hide() QuestNPCModelTextFrame:DisableDrawLayer("OVERLAY") local npcbd = CreateFrame("Frame", nil, QuestNPCModel) npcbd:SetPoint("TOPLEFT", -1, 1) npcbd:SetPoint("RIGHT", 2, 0) npcbd:SetPoint("BOTTOM", QuestNPCModelTextScrollFrame) npcbd:SetFrameLevel(0) S:CreateBD(npcbd) local npcLine = CreateFrame("Frame", nil, QuestNPCModel) npcLine:SetPoint("BOTTOMLEFT", 0, -1) npcLine:SetPoint("BOTTOMRIGHT", 1, -1) npcLine:SetHeight(1) npcLine:SetFrameLevel(0) S:CreateBD(npcLine, 0) hooksecurefunc("QuestFrame_ShowQuestPortrait", function(parentFrame, _, _, _, x, y) if parentFrame == QuestLogPopupDetailFrame or parentFrame == QuestFrame then x = x + 3 end QuestNPCModel:SetPoint("TOPLEFT", parentFrame, "TOPRIGHT", x, y) end) S:ReskinScroll(QuestNPCModelTextScrollFrameScrollBar) end S:RegisterSkin("RayUI", LoadSkin)
local R, L, P = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, local local S = R:GetModule("Skins") local function LoadSkin() local r, g, b = S["media"].classcolours[R.myclass].r, S["media"].classcolours[R.myclass].g, S["media"].classcolours[R.myclass].b S:ReskinPortraitFrame(QuestFrame, true) QuestTitleFont:SetTextColor(1, 1, 1) QuestTitleFont:SetShadowColor(0, 0, 0) QuestFont:SetTextColor(1, 1, 1) QuestFrameDetailPanel:DisableDrawLayer("BACKGROUND") QuestFrameProgressPanel:DisableDrawLayer("BACKGROUND") QuestFrameRewardPanel:DisableDrawLayer("BACKGROUND") QuestFrameGreetingPanel:DisableDrawLayer("BACKGROUND") QuestFrameDetailPanel:DisableDrawLayer("BORDER") QuestFrameRewardPanel:DisableDrawLayer("BORDER") QuestDetailScrollFrameTop:Hide() QuestDetailScrollFrameBottom:Hide() QuestDetailScrollFrameMiddle:Hide() QuestProgressScrollFrameTop:Hide() QuestProgressScrollFrameBottom:Hide() QuestProgressScrollFrameMiddle:Hide() QuestRewardScrollFrameTop:Hide() QuestRewardScrollFrameBottom:Hide() QuestRewardScrollFrameMiddle:Hide() QuestGreetingScrollFrameTop:Hide() QuestGreetingScrollFrameBottom:Hide() QuestGreetingScrollFrameMiddle:Hide() QuestFrameProgressPanelMaterialTopLeft:SetAlpha(0) QuestFrameProgressPanelMaterialTopRight:SetAlpha(0) QuestFrameProgressPanelMaterialBotLeft:SetAlpha(0) QuestFrameProgressPanelMaterialBotRight:SetAlpha(0) local line = QuestFrameGreetingPanel:CreateTexture() line:SetTexture(1, 1, 1, .2) line:SetSize(256, 1) line:SetPoint("CENTER", QuestGreetingFrameHorizontalBreak) QuestGreetingFrameHorizontalBreak:SetTexture("") QuestFrameGreetingPanel:HookScript("OnShow", function() line:SetShown(QuestGreetingFrameHorizontalBreak:IsShown()) end) for i = 1, MAX_REQUIRED_ITEMS do local bu = _G["QuestProgressItem"..i] local ic = _G["QuestProgressItem"..i.."IconTexture"] local na = _G["QuestProgressItem"..i.."NameFrame"] local co = _G["QuestProgressItem"..i.."Count"] ic:SetSize(40, 40) ic:SetTexCoord(.08, .92, .08, .92) ic:SetDrawLayer("OVERLAY") S:CreateBD(bu, .25) na:Hide() co:SetDrawLayer("OVERLAY") local line = CreateFrame("Frame", nil, bu) line:SetSize(1, 40) line:SetPoint("RIGHT", ic, 1, 0) S:CreateBD(line) end QuestDetailScrollFrame:SetWidth(302) -- else these buttons get cut off hooksecurefunc(QuestProgressRequiredMoneyText, "SetTextColor", function(self, r, g, b) if r == 0 then self:SetTextColor(.8, .8, .8) elseif r == .2 then self:SetTextColor(1, 1, 1) end end) for _, questButton in pairs({"QuestFrameAcceptButton", "QuestFrameDeclineButton", "QuestFrameCompleteQuestButton", "QuestFrameCompleteButton", "QuestFrameGoodbyeButton", "QuestFrameGreetingGoodbyeButton"}) do S:Reskin(_G[questButton]) end S:ReskinScroll(QuestProgressScrollFrameScrollBar) S:ReskinScroll(QuestRewardScrollFrameScrollBar) S:ReskinScroll(QuestDetailScrollFrameScrollBar) S:ReskinScroll(QuestGreetingScrollFrameScrollBar) -- Text colour stuff QuestProgressRequiredItemsText:SetTextColor(1, 1, 1) QuestProgressRequiredItemsText:SetShadowColor(0, 0, 0) QuestProgressText.SetTextColor = R.dummy GreetingText:SetTextColor(1, 1, 1) GreetingText.SetTextColor = R.dummy AvailableQuestsText:SetTextColor(1, 1, 1) AvailableQuestsText.SetTextColor = R.dummy AvailableQuestsText:SetShadowColor(0, 0, 0) CurrentQuestsText:SetTextColor(1, 1, 1) CurrentQuestsText.SetTextColor = R.dummy CurrentQuestsText:SetShadowColor(0, 0, 0) -- [[ Quest NPC model ]] QuestNPCModelShadowOverlay:Hide() QuestNPCModelBg:Hide() QuestNPCModel:DisableDrawLayer("OVERLAY") QuestNPCModelNameText:SetDrawLayer("ARTWORK") QuestNPCModelTextFrameBg:Hide() QuestNPCModelTextFrame:DisableDrawLayer("OVERLAY") local npcbd = CreateFrame("Frame", nil, QuestNPCModel) npcbd:SetPoint("TOPLEFT", -1, 1) npcbd:SetPoint("RIGHT", 2, 0) npcbd:SetPoint("BOTTOM", QuestNPCModelTextScrollFrame) npcbd:SetFrameLevel(0) S:CreateBD(npcbd) local npcLine = CreateFrame("Frame", nil, QuestNPCModel) npcLine:SetPoint("BOTTOMLEFT", 0, -1) npcLine:SetPoint("BOTTOMRIGHT", 1, -1) npcLine:SetHeight(1) npcLine:SetFrameLevel(0) S:CreateBD(npcLine, 0) hooksecurefunc("QuestFrame_ShowQuestPortrait", function(parentFrame, _, _, _, x, y) if parentFrame == QuestLogPopupDetailFrame or parentFrame == QuestFrame then x = x + 3 end QuestNPCModel:SetPoint("TOPLEFT", parentFrame, "TOPRIGHT", x, y) end) S:ReskinScroll(QuestNPCModelTextScrollFrameScrollBar) end S:RegisterSkin("RayUI", LoadSkin)
fix QuestTitleFont color
fix QuestTitleFont color
Lua
mit
fgprodigal/RayUI
036fc0cfd428f853d479c48e493cd7b051f42e63
pages/shop/checkout/post.lua
pages/shop/checkout/post.lua
function post() if not app.Shop.Enabled then http:redirect("/") return end if not session:isLogged() then http:redirect("/subtopic/login") return end local cart = session:get("shop-cart") if cart == nil then http:redirect("/") return end local cartdata = {} local totalprice = 0 for name, count in pairs(cart) do cartdata[name] = {} cartdata[name].offer = db:singleQuery("SELECT name, price FROM castro_shop_offers WHERE name = ?", name) if cartdata[name].offer == nil then http:redirect("/") return end totalprice = tonumber(cartdata[name].offer.price) * count cartdata[name].count = count end if http.postValues.discount ~= nil then local discount = db:singleQuery("SELECT valid_till, discount, uses, unlimited FROM castro_shop_discounts WHERE code = ?", http.postValues.discount) if discount ~= nil then if os.time() < tonumber(discount.valid_till) then if discount.unlimited or (not discount.unlimited and discount.uses > 0) then totalprice = totalprice - ((tonumber(discount.discount) * totalprice) / 100) end end end end local account = session:loggedAccount() if account.castro.Points < totalprice then session:setFlash("error", "You need more points") http:redirect("/subtopic/shop/view") return end db:execute("UPDATE castro_accounts SET points = points - ? WHERE account_id = ?", totalprice, account.Id) session:setFlash("success", "You paid " .. totalprice .. " for all your cart items") http:redirect("/subtopic/shop/view") end
function post() if not app.Shop.Enabled then http:redirect("/") return end if not session:isLogged() then http:redirect("/subtopic/login") return end local cart = session:get("shop-cart") if cart == nil then http:redirect("/") return end local cartdata = {} local totalprice = 0 for name, count in pairs(cart) do cartdata[name] = {} cartdata[name].offer = db:singleQuery("SELECT name, price FROM castro_shop_offers WHERE name = ?", name) if cartdata[name].offer == nil then http:redirect("/") return end totalprice = tonumber(cartdata[name].offer.price) * count cartdata[name].count = count end local discount = db:singleQuery("SELECT id, valid_till, discount, uses, unlimited FROM castro_shop_discounts WHERE code = ?", http.postValues.discount) if discount ~= nil then if os.time() < tonumber(discount.valid_till) then if discount.unlimited or tonumber(discount.uses) > 0 then totalprice = totalprice - ((tonumber(discount.discount) * totalprice) / 100) db:execute("UPDATE castro_shop_discounts SET uses = uses - 1 WHERE id = ?", discount.id) end end end local account = session:loggedAccount() if account.castro.Points < totalprice then session:setFlash("error", "You need more points") http:redirect("/subtopic/shop/view") return end db:execute("UPDATE castro_accounts SET points = points - ? WHERE account_id = ?", totalprice, account.Id) session:setFlash("success", "You paid " .. totalprice .. " for all your cart items") http:redirect("/subtopic/shop/view") end
Fix shop discount usage
Fix shop discount usage
Lua
mit
Raggaer/castro,Raggaer/castro,Raggaer/castro
aff6d4b36dc6154973ab334b9fdbdbfd4a02e6d8
resources/prosody-plugins/mod_muc_max_occupants.lua
resources/prosody-plugins/mod_muc_max_occupants.lua
-- MUC Max Occupants -- Configuring muc_max_occupants will set a limit of the maximum number -- of participants that will be able to join in a room. -- Participants in muc_access_whitelist will not be counted for the -- max occupants value (values are jids like [email protected]). -- This module is configured under the muc component that is used for jitsi-meet local split_jid = require "util.jid".split; local st = require "util.stanza"; local it = require "util.iterators"; local whitelist = module:get_option_set("muc_access_whitelist"); local MAX_OCCUPANTS = module:get_option_number("muc_max_occupants", -1); local function count_keys(t) return it.count(it.keys(t)); end local function check_for_max_occupants(event) local room, origin, stanza = event.room, event.origin, event.stanza; local actor = stanza.attr.from; local user, domain, res = split_jid(stanza.attr.from); --no user object means no way to check for max occupants if user == nil then return end -- If we're a whitelisted user joining the room, don't bother checking the max -- occupants. if whitelist and whitelist:contains(domain) or whitelist:contains(user..'@'..domain) then return; end if room and not room._jid_nick[stanza.attr.from] then local count = count_keys(room._occupants); local slots = MAX_OCCUPANTS; -- If there is no whitelist, just check the count. if not whitelist and count >= MAX_OCCUPANTS then module:log("info", "Attempt to enter a maxed out MUC"); origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return true; end -- TODO: Are Prosody hooks atomic, or is this a race condition? -- For each person in the room that's not on the whitelist, subtract one -- from the count. for _, occupant in room:each_occupant() do if not whitelist:contains(domain) and not whitelist:contains(user..'@'..domain) then slots = slots - 1 end end -- If the room is full (<0 slots left), error out. if slots <= 0 then module:log("info", "Attempt to enter a maxed out MUC"); origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return true; end end end if MAX_OCCUPANTS > 0 then module:hook("muc-occupant-pre-join", check_for_max_occupants, 10); end
-- MUC Max Occupants -- Configuring muc_max_occupants will set a limit of the maximum number -- of participants that will be able to join in a room. -- Participants in muc_access_whitelist will not be counted for the -- max occupants value (values are jids like [email protected]). -- This module is configured under the muc component that is used for jitsi-meet local split_jid = require "util.jid".split; local st = require "util.stanza"; local it = require "util.iterators"; local whitelist = module:get_option_set("muc_access_whitelist"); local MAX_OCCUPANTS = module:get_option_number("muc_max_occupants", -1); local function count_keys(t) return it.count(it.keys(t)); end local function check_for_max_occupants(event) local room, origin, stanza = event.room, event.origin, event.stanza; local actor = stanza.attr.from; local user, domain, res = split_jid(stanza.attr.from); --no user object means no way to check for max occupants if user == nil then return end -- If we're a whitelisted user joining the room, don't bother checking the max -- occupants. if whitelist and whitelist:contains(domain) or whitelist:contains(user..'@'..domain) then return; end if room and not room._jid_nick[stanza.attr.from] then local count = count_keys(room._occupants); local slots = MAX_OCCUPANTS; -- If there is no whitelist, just check the count. if not whitelist and count >= MAX_OCCUPANTS then module:log("info", "Attempt to enter a maxed out MUC"); origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return true; end -- TODO: Are Prosody hooks atomic, or is this a race condition? -- For each person in the room that's not on the whitelist, subtract one -- from the count. for _, occupant in room:each_occupant() do user, domain, res = split_jid(occupant.bare_jid); if not whitelist:contains(domain) and not whitelist:contains(user..'@'..domain) then slots = slots - 1 end end -- If the room is full (<0 slots left), error out. if slots <= 0 then module:log("info", "Attempt to enter a maxed out MUC"); origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return true; end end end if MAX_OCCUPANTS > 0 then module:hook("muc-occupant-pre-join", check_for_max_occupants, 10); end
Fix mod_muc_max_occupants to properly ignore whitelisted users
Fix mod_muc_max_occupants to properly ignore whitelisted users In a typical Jitsi Meet setup, this plugin can be used to limit the number of occupants in a meeting room, while ignoring "utility" users. Such a configuration could be: muc_max_occupants = 2 muc_access_whitelist = { "[email protected]"; } It would be expected that this configuration allows two users to attend the meeting room, but in practice only one is allowed, because the whitelist is not honoured. This commit fixes it by actually updating the `user` and `domain` variables being checked. After this change, the scenario above works just fine.
Lua
apache-2.0
gpolitis/jitsi-meet,bgrozev/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,bgrozev/jitsi-meet,bgrozev/jitsi-meet,gpolitis/jitsi-meet,bgrozev/jitsi-meet,jitsi/jitsi-meet,bgrozev/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,bgrozev/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet
6d2163eb622a6f4da43b6ecc8379a1fc891b5b0b
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/df.lua
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/df.lua
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <[email protected]> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.df", package.seeall) function rrdargs( graph, plugin, plugin_instance, dtype ) return { title = "%H: Disk space usage on %di", vlabel = "Bytes", per_instance = true, number_format = "%5.1lf%sB", data = { sources = { df = { "free", "used" } }, options = { df__free = { color = "00ff00", overlay = false, title = "free" }, df__used = { color = "ff0000", overlay = false, title = "used" } } } } end
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <[email protected]> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.df", package.seeall) function rrdargs( graph, plugin, plugin_instance, dtype ) return { title = "%H: Disk space usage on %di", vlabel = "Bytes", per_instance = true, number_format = "%5.1lf%sB", data = { instances = { df_complex = { "free", "used", "reserved" } }, options = { df_complex_free = { color = "00ff00", overlay = false, title = "free" }, df_complex_used = { color = "ff0000", overlay = false, title = "used" }, df_complex_reserved = { color = "0000ff", overlay = false, title = "reserved" } } } } end
luci-app-statistics: Fix disk usage graphing
luci-app-statistics: Fix disk usage graphing Disk usage graphing was broken. This fixes it. Signed-off-by: Daniel Dickinson <[email protected]>
Lua
apache-2.0
taiha/luci,tobiaswaldvogel/luci,Noltari/luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,shangjiyu/luci-with-extra,bright-things/ionic-luci,kuoruan/lede-luci,Noltari/luci,981213/luci-1,aa65535/luci,bright-things/ionic-luci,wongsyrone/luci-1,Wedmer/luci,artynet/luci,rogerpueyo/luci,shangjiyu/luci-with-extra,openwrt-es/openwrt-luci,LuttyYang/luci,openwrt/luci,tobiaswaldvogel/luci,mumuqz/luci,taiha/luci,oneru/luci,remakeelectric/luci,mumuqz/luci,hnyman/luci,kuoruan/luci,kuoruan/lede-luci,daofeng2015/luci,openwrt/luci,hnyman/luci,remakeelectric/luci,remakeelectric/luci,oneru/luci,wongsyrone/luci-1,Noltari/luci,nmav/luci,cshore/luci,bittorf/luci,bittorf/luci,kuoruan/luci,taiha/luci,981213/luci-1,shangjiyu/luci-with-extra,kuoruan/lede-luci,oneru/luci,kuoruan/luci,openwrt-es/openwrt-luci,mumuqz/luci,artynet/luci,cappiewu/luci,hnyman/luci,Noltari/luci,bright-things/ionic-luci,shangjiyu/luci-with-extra,nmav/luci,teslamint/luci,ollie27/openwrt_luci,Wedmer/luci,ollie27/openwrt_luci,artynet/luci,cshore/luci,openwrt-es/openwrt-luci,LuttyYang/luci,teslamint/luci,cshore/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,jlopenwrtluci/luci,aa65535/luci,cshore-firmware/openwrt-luci,nmav/luci,ollie27/openwrt_luci,openwrt/luci,Wedmer/luci,daofeng2015/luci,oneru/luci,daofeng2015/luci,kuoruan/luci,Wedmer/luci,hnyman/luci,bittorf/luci,chris5560/openwrt-luci,LuttyYang/luci,cshore/luci,openwrt/luci,nmav/luci,kuoruan/lede-luci,nmav/luci,bright-things/ionic-luci,daofeng2015/luci,cshore/luci,kuoruan/luci,mumuqz/luci,mumuqz/luci,bright-things/ionic-luci,remakeelectric/luci,wongsyrone/luci-1,daofeng2015/luci,wongsyrone/luci-1,daofeng2015/luci,bittorf/luci,teslamint/luci,aa65535/luci,openwrt-es/openwrt-luci,nmav/luci,Wedmer/luci,cshore/luci,tobiaswaldvogel/luci,cappiewu/luci,bittorf/luci,cshore-firmware/openwrt-luci,taiha/luci,tobiaswaldvogel/luci,shangjiyu/luci-with-extra,chris5560/openwrt-luci,openwrt/luci,chris5560/openwrt-luci,Wedmer/luci,LuttyYang/luci,shangjiyu/luci-with-extra,981213/luci-1,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,cappiewu/luci,kuoruan/luci,openwrt/luci,981213/luci-1,rogerpueyo/luci,cappiewu/luci,cshore/luci,lbthomsen/openwrt-luci,cshore-firmware/openwrt-luci,wongsyrone/luci-1,aa65535/luci,LuttyYang/luci,bright-things/ionic-luci,tobiaswaldvogel/luci,bright-things/ionic-luci,kuoruan/luci,Noltari/luci,ollie27/openwrt_luci,hnyman/luci,artynet/luci,cappiewu/luci,mumuqz/luci,artynet/luci,981213/luci-1,cshore-firmware/openwrt-luci,wongsyrone/luci-1,chris5560/openwrt-luci,teslamint/luci,981213/luci-1,nmav/luci,openwrt/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,ollie27/openwrt_luci,mumuqz/luci,ollie27/openwrt_luci,cshore-firmware/openwrt-luci,lbthomsen/openwrt-luci,Noltari/luci,nmav/luci,taiha/luci,kuoruan/lede-luci,bright-things/ionic-luci,oneru/luci,bittorf/luci,rogerpueyo/luci,mumuqz/luci,jlopenwrtluci/luci,jlopenwrtluci/luci,oneru/luci,chris5560/openwrt-luci,tobiaswaldvogel/luci,remakeelectric/luci,aa65535/luci,tobiaswaldvogel/luci,shangjiyu/luci-with-extra,artynet/luci,LuttyYang/luci,jlopenwrtluci/luci,teslamint/luci,hnyman/luci,artynet/luci,lbthomsen/openwrt-luci,hnyman/luci,teslamint/luci,jlopenwrtluci/luci,kuoruan/luci,rogerpueyo/luci,openwrt/luci,aa65535/luci,remakeelectric/luci,chris5560/openwrt-luci,wongsyrone/luci-1,teslamint/luci,hnyman/luci,Noltari/luci,taiha/luci,kuoruan/lede-luci,kuoruan/lede-luci,aa65535/luci,teslamint/luci,ollie27/openwrt_luci,bittorf/luci,Wedmer/luci,cappiewu/luci,aa65535/luci,cshore-firmware/openwrt-luci,lbthomsen/openwrt-luci,jlopenwrtluci/luci,oneru/luci,rogerpueyo/luci,oneru/luci,Wedmer/luci,wongsyrone/luci-1,artynet/luci,kuoruan/lede-luci,shangjiyu/luci-with-extra,Noltari/luci,Noltari/luci,chris5560/openwrt-luci,rogerpueyo/luci,openwrt-es/openwrt-luci,jlopenwrtluci/luci,cappiewu/luci,artynet/luci,daofeng2015/luci,cshore-firmware/openwrt-luci,taiha/luci,taiha/luci,jlopenwrtluci/luci,LuttyYang/luci,nmav/luci,rogerpueyo/luci,LuttyYang/luci,remakeelectric/luci,981213/luci-1,bittorf/luci,daofeng2015/luci,cshore/luci,ollie27/openwrt_luci,openwrt-es/openwrt-luci,cshore-firmware/openwrt-luci,remakeelectric/luci,cappiewu/luci
8f11781cd41f7bbd1906ae672ff10c8d62c56ada
Modules/Shared/Assembly/setAssemblyCFrame.lua
Modules/Shared/Assembly/setAssemblyCFrame.lua
--- Gets the full assembly of a part -- @module setAssemblyCFrame local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local getFullAssembly = require("getFullAssembly") return function(primaryPart, cframe) assert(typeof(primaryPart) == "Instance") assert(typeof(cframe) == "CFrame") local primaryPartCFrame = primaryPart.CFrame for _, part in pairs(getFullAssembly(primaryPart)) do part.CFrame = cframe:toWorldSpace(primaryPartCFrame:toObjectSpace(part.CFrame)) end end
--- Gets the full assembly of a part -- @module setAssemblyCFrame local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local getFullAssembly = require("getFullAssembly") return function(primaryPart, cframe) assert(typeof(primaryPart) == "Instance") assert(typeof(cframe) == "CFrame") local primaryPartCFrame = primaryPart.CFrame local roots = {} for _, part in pairs(getFullAssembly(primaryPart)) do local rootPart = part:GetRootPart() if not roots[rootPart] then roots[rootPart] = primaryPartCFrame:toObjectSpace(part.CFrame) end end for root, relCFrame in pairs(roots) do root.CFrame = cframe:toWorldSpace(relCFrame) end end
Fix setting assembly CFrame
Fix setting assembly CFrame
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
32aa7dba943feca755e9b3f80e8de8cdb36e53ac
MMOCoreORB/bin/scripts/mobile/weapon/serverobjects.lua
MMOCoreORB/bin/scripts/mobile/weapon/serverobjects.lua
-- weapon group templates -- creature default attack includeFile("weapon/creature_default_weapon.lua") -- creature spit attacks includeFile("weapon/creature_spit_heavy_flame.lua") includeFile("weapon/creature_spit_large_green.lua") includeFile("weapon/creature_spit_large_red.lua") includeFile("weapon/creature_spit_large_toxicgreen.lua") includeFile("weapon/creature_spit_large_yellow.lua") includeFile("weapon/creature_spit_lightning_ball.lua") includeFile("weapon/creature_spit_particle_beam.lua") includeFile("weapon/creature_spit_small_green.lua") includeFile("weapon/creature_spit_small_red.lua") includeFile("weapon/creature_spit_small_toxicgreen.lua") includeFile("weapon/creature_spit_small_yellow.lua") includeFile("weapon/creature_spit_spray_green.lua") includeFile("weapon/creature_spit_spray_red.lua") includeFile("weapon/creature_spit_spray_toxicgreen.lua") includeFile("weapon/creature_spit_spray_yellow.lua") -- npc weapons includeFile("weapon/groups/dark_trooper_weapons.lua") includeFile("weapon/groups/darth_vader_weapons.lua") includeFile("weapon/groups/blood_razer_weapons.lua") includeFile("weapon/groups/canyon_corsair_weapons.lua") includeFile("weapon/groups/death_watch_commander_weapons.lua") includeFile("weapon/groups/donkuwah_weapons.lua") includeFile("weapon/groups/gamorrean_weapons.lua") includeFile("weapon/groups/imperial_weapons_light.lua") includeFile("weapon/groups/imperial_weapons_medium.lua") includeFile("weapon/groups/jawa_warlord_weapons.lua") includeFile("weapon/groups/mixed_force_weapons.lua") includeFile("weapon/groups/nyax_weapons.lua") includeFile("weapon/groups/pirate_weapons_light.lua") includeFile("weapon/groups/pirate_weapons_heavy.lua") includeFile("weapon/groups/primitive_weapons.lua") includeFile("weapon/groups/ranged_weapons.lua") includeFile("weapon/groups/rebel_weapons_light.lua") includeFile("weapon/groups/janta_weapons.lua") includeFile("weapon/groups/dantari_weapons.lua") includeFile("weapon/groups/stormtrooper_weapons.lua") includeFile("weapon/groups/sandtrooper_weapons.lua") includeFile("weapon/groups/unarmed_weapons.lua") includeFile("weapon/groups/novice_weapons.lua") includeFile("weapon/groups/corsec_police_weapons.lua") includeFile("weapon/groups/geonosian_mercenary_weapons.lua") -- Groups gotten from swgemu includeFile("weapon/groups/battle_droid_weapons.lua") includeFile("weapon/groups/boba_fett_weapons.lua") includeFile("weapon/groups/captain_hassk_weapons.lua") includeFile("weapon/groups/cas_vankoo_weapons.lua") includeFile("weapon/groups/chewbacca_weapons.lua") includeFile("weapon/groups/dark_jedi_weapons_gen2.lua") includeFile("weapon/groups/dark_jedi_weapons_gen3.lua") includeFile("weapon/groups/dark_jedi_weapons_gen4.lua") includeFile("weapon/groups/ewok_weapons.lua") includeFile("weapon/groups/geonosian_weapons.lua") includeFile("weapon/groups/han_solo_weapons.lua") includeFile("weapon/groups/light_jedi_weapons.lua") includeFile("weapon/groups/lt_heb_nee_weapons.lua") includeFile("weapon/groups/lt_ori_weapons.lua") includeFile("weapon/groups/luke_skywalker_weapons.lua") includeFile("weapon/groups/melee_weapons.lua") includeFile("weapon/groups/mordran_weapons.lua") includeFile("weapon/groups/pirate_weapons_medium.lua") includeFile("weapon/groups/rebel_weapons_heavy.lua") includeFile("weapon/groups/rebel_weapons_medium.lua") includeFile("weapon/groups/sif_weapons.lua") includeFile("weapon/groups/st_assault_weapons.lua") includeFile("weapon/groups/st_bombardier_weapons.lua") includeFile("weapon/groups/st_rifleman_weapons.lua") includeFile("weapon/groups/st_sniper_weapons.lua") includeFile("weapon/groups/stormtrooper_weapons.lua") includeFile("weapon/groups/tusken_weapons.lua") -- tutorial includeFile("weapon/groups/tutorial_bandit.lua")
-- weapon group templates -- creature default attack includeFile("weapon/creature_default_weapon.lua") -- creature spit attacks includeFile("weapon/creature_spit_heavy_flame.lua") includeFile("weapon/creature_spit_large_green.lua") includeFile("weapon/creature_spit_large_red.lua") includeFile("weapon/creature_spit_large_toxicgreen.lua") includeFile("weapon/creature_spit_large_yellow.lua") includeFile("weapon/creature_spit_lightning_ball.lua") includeFile("weapon/creature_spit_particle_beam.lua") includeFile("weapon/creature_spit_small_green.lua") includeFile("weapon/creature_spit_small_red.lua") includeFile("weapon/creature_spit_small_toxicgreen.lua") includeFile("weapon/creature_spit_small_yellow.lua") includeFile("weapon/creature_spit_spray_green.lua") includeFile("weapon/creature_spit_spray_red.lua") includeFile("weapon/creature_spit_spray_toxicgreen.lua") includeFile("weapon/creature_spit_spray_yellow.lua") -- npc weapons includeFile("weapon/groups/dark_trooper_weapons.lua") includeFile("weapon/groups/darth_vader_weapons.lua") includeFile("weapon/groups/blood_razer_weapons.lua") includeFile("weapon/groups/canyon_corsair_weapons.lua") includeFile("weapon/groups/death_watch_commander_weapons.lua") includeFile("weapon/groups/donkuwah_weapons.lua") includeFile("weapon/groups/gamorrean_weapons.lua") includeFile("weapon/groups/imperial_weapons_heavy.lua") includeFile("weapon/groups/imperial_weapons_light.lua") includeFile("weapon/groups/imperial_weapons_medium.lua") includeFile("weapon/groups/jawa_warlord_weapons.lua") includeFile("weapon/groups/mixed_force_weapons.lua") includeFile("weapon/groups/nyax_weapons.lua") includeFile("weapon/groups/pirate_weapons_light.lua") includeFile("weapon/groups/pirate_weapons_heavy.lua") includeFile("weapon/groups/primitive_weapons.lua") includeFile("weapon/groups/ranged_weapons.lua") includeFile("weapon/groups/rebel_weapons_light.lua") includeFile("weapon/groups/janta_weapons.lua") includeFile("weapon/groups/dantari_weapons.lua") includeFile("weapon/groups/stormtrooper_weapons.lua") includeFile("weapon/groups/sandtrooper_weapons.lua") includeFile("weapon/groups/unarmed_weapons.lua") includeFile("weapon/groups/novice_weapons.lua") includeFile("weapon/groups/corsec_police_weapons.lua") includeFile("weapon/groups/geonosian_mercenary_weapons.lua") -- Groups gotten from swgemu includeFile("weapon/groups/battle_droid_weapons.lua") includeFile("weapon/groups/boba_fett_weapons.lua") includeFile("weapon/groups/captain_hassk_weapons.lua") includeFile("weapon/groups/cas_vankoo_weapons.lua") includeFile("weapon/groups/chewbacca_weapons.lua") includeFile("weapon/groups/dark_jedi_weapons_gen2.lua") includeFile("weapon/groups/dark_jedi_weapons_gen3.lua") includeFile("weapon/groups/dark_jedi_weapons_gen4.lua") includeFile("weapon/groups/ewok_weapons.lua") includeFile("weapon/groups/geonosian_weapons.lua") includeFile("weapon/groups/han_solo_weapons.lua") includeFile("weapon/groups/light_jedi_weapons.lua") includeFile("weapon/groups/lt_heb_nee_weapons.lua") includeFile("weapon/groups/lt_ori_weapons.lua") includeFile("weapon/groups/luke_skywalker_weapons.lua") includeFile("weapon/groups/melee_weapons.lua") includeFile("weapon/groups/mordran_weapons.lua") includeFile("weapon/groups/pirate_weapons_medium.lua") includeFile("weapon/groups/rebel_weapons_heavy.lua") includeFile("weapon/groups/rebel_weapons_medium.lua") includeFile("weapon/groups/sif_weapons.lua") includeFile("weapon/groups/st_assault_weapons.lua") includeFile("weapon/groups/st_bombardier_weapons.lua") includeFile("weapon/groups/st_rifleman_weapons.lua") includeFile("weapon/groups/st_sniper_weapons.lua") includeFile("weapon/groups/stormtrooper_weapons.lua") includeFile("weapon/groups/tusken_weapons.lua") -- tutorial includeFile("weapon/groups/tutorial_bandit.lua")
[Fixed] imperial_weapons_heavy weapon group not loading
[Fixed] imperial_weapons_heavy weapon group not loading Change-Id: Ib31bd902abd924615479bec017d4496a3058e822
Lua
agpl-3.0
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
364f59d7dd75af81305df9d78752ae18e4460974
libs/chiliui/luaui/chili/chili/controls/combobox.lua
libs/chiliui/luaui/chili/chili/controls/combobox.lua
--//============================================================================= --- ComboBox module --- ComboBox fields. -- Inherits from Control. -- @see control.Control -- @table ComboBox -- @tparam {"item1","item2",...} items table of items in the ComboBox, (default {"items"}) -- @int[opt=1] selected id of the selected item -- @tparam {func1,func2,...} OnSelect listener functions for selected item changes, (default {}) ComboBox = Button:Inherit{ classname = "combobox", caption = 'combobox', defaultWidth = 70, defaultHeight = 20, items = { "items" }, itemHeight = 20, selected = 1, OnOpen = {}, OnClose = {}, OnSelect = {}, OnSelectName = {}, selectionOffsetX = 0, selectionOffsetY = 0, maxDropDownHeight = 200, minDropDownHeight = 50, maxDropDownWidth = 500, minDropDownWidth = 50, } local ComboBoxWindow = Window:Inherit{classname = "combobox_window", resizable = false, draggable = false, } local ComboBoxScrollPanel = ScrollPanel:Inherit{classname = "combobox_scrollpanel", horizontalScrollbar = false, } local ComboBoxStackPanel = StackPanel:Inherit{classname = "combobox_stackpanel", autosize = true, resizeItems = false, borderThickness = 0, padding = {0,0,0,0}, itemPadding = {0,0,0,0}, itemMargin = {0,0,0,0}, } local ComboBoxItem = Button:Inherit{classname = "combobox_item"} local this = ComboBox local inherited = this.inherited function ComboBox:New(obj) obj = inherited.New(self,obj) obj:Select(obj.selected or 1) return obj end --- Selects an item by id -- @int itemIdx id of the item to be selected function ComboBox:Select(itemIdx) if (type(itemIdx)=="number") then local item = self.items[itemIdx] if not item then return end self.selected = itemIdx if type(item) == "string" and not self.ignoreItemCaption then self.caption = "" self.caption = item end self:CallListeners(self.OnSelect, itemIdx, true) self:Invalidate() elseif (type(itemIdx)=="string") then self:CallListeners(self.OnSelectName, itemIdx, true) for i = 1, #self.items do if self.items[i] == itemIdx then self:Select(i) end end end end function ComboBox:_CloseWindow() if self._dropDownWindow then self:CallListeners(self.OnClose) self._dropDownWindow:Dispose() self._dropDownWindow = nil end if (self.state.pressed) then self.state.pressed = false self:Invalidate() return self end end function ComboBox:FocusUpdate() if not self.state.focused then self:_CloseWindow() end end function ComboBox:MouseDown(x, y) self.state.pressed = true if not self._dropDownWindow then local sx,sy = self:LocalToScreen(0,0) local selectByName = self.selectByName local labels = {} local width = math.max(self.width, self.minDropDownWidth) local height = 7 for i = 1, #self.items do local item = self.items[i] if type(item) == "string" then local newBtn = ComboBoxItem:New { caption = item, width = '100%', height = self.itemHeight, fontsize = self.itemFontSize, state = {focused = (i == self.selected), selected = (i == self.selected)}, OnMouseUp = { function() if selectByName then self:Select(item) else self:Select(i) end self:_CloseWindow() end } } labels[#labels+1] = newBtn height = height + self.itemHeight width = math.max(width, self.font:GetTextWidth(item)) else labels[#labels+1] = item item.OnMouseUp = { function() self:Select(i) self:_CloseWindow() end } width = math.max(width, item.width + 5) height = height + item.height -- FIXME: what if this height is relative? end end height = math.max(self.minDropDownHeight, height) height = math.min(self.maxDropDownHeight, height) width = math.min(self.maxDropDownWidth, width) local screen = self:FindParent("screen") local y = sy + self.height if y + height > screen.height then y = sy - height end self._dropDownWindow = ComboBoxWindow:New{ parent = screen, width = width, height = height, minHeight = self.minDropDownHeight, x = math.max(sx, math.min(sx + self.width - width, (sx + x - width/2))) + self.selectionOffsetX, y = y + self.selectionOffsetY, children = { ComboBoxScrollPanel:New{ width = "100%", height = "100%", children = { ComboBoxStackPanel:New{ width = '100%', children = labels, }, }, } } } self:CallListeners(self.OnOpen) else self:_CloseWindow() end self:Invalidate() return self end function ComboBox:MouseUp(...) self:Invalidate() return self -- this exists to override Button:MouseUp so it doesn't modify .state.pressed end
--//============================================================================= --- ComboBox module --- ComboBox fields. -- Inherits from Control. -- @see control.Control -- @table ComboBox -- @tparam {"item1","item2",...} items table of items in the ComboBox, (default {"items"}) -- @int[opt=1] selected id of the selected item -- @tparam {func1,func2,...} OnSelect listener functions for selected item changes, (default {}) ComboBox = Button:Inherit{ classname = "combobox", caption = 'combobox', defaultWidth = 70, defaultHeight = 20, items = { "items" }, itemHeight = 20, selected = 1, OnOpen = {}, OnClose = {}, OnSelect = {}, OnSelectName = {}, selectionOffsetX = 0, selectionOffsetY = 0, maxDropDownHeight = 200, minDropDownHeight = 50, maxDropDownWidth = 500, minDropDownWidth = 50, } local ComboBoxWindow = Window:Inherit{classname = "combobox_window", resizable = false, draggable = false, } local ComboBoxScrollPanel = ScrollPanel:Inherit{classname = "combobox_scrollpanel", horizontalScrollbar = false, } local ComboBoxStackPanel = StackPanel:Inherit{classname = "combobox_stackpanel", autosize = true, resizeItems = false, borderThickness = 0, padding = {0,0,0,0}, itemPadding = {0,0,0,0}, itemMargin = {0,0,0,0}, } local ComboBoxItem = Button:Inherit{classname = "combobox_item"} local this = ComboBox local inherited = this.inherited function ComboBox:New(obj) obj = inherited.New(self,obj) obj:Select(obj.selected or 1) return obj end --- Selects an item by id -- @int itemIdx id of the item to be selected function ComboBox:Select(itemIdx) if (type(itemIdx)=="number") then local item = self.items[itemIdx] if not item then return end self.selected = itemIdx if type(item) == "string" and not self.ignoreItemCaption then self.caption = "" self.caption = item end self:CallListeners(self.OnSelect, itemIdx, true) self:Invalidate() elseif (type(itemIdx)=="string") then self:CallListeners(self.OnSelectName, itemIdx, true) for i = 1, #self.items do if self.items[i] == itemIdx then self:Select(i) end end end end function ComboBox:_CloseWindow() if self._dropDownWindow then self:CallListeners(self.OnClose) self._dropDownWindow:Dispose() self._dropDownWindow = nil end if (self.state.pressed) then self.state.pressed = false self:Invalidate() return self end end function ComboBox:FocusUpdate() self:RequestUpdate() end function ComboBox:Update(...) -- obj:RequestUpdate() inherited.Update(self, ...) if self._dropDownWindow then if self.state.focused or self._scrollPanelCtrl.state.focused then self:RequestUpdate() else self:_CloseWindow() end end end function ComboBox:MouseDown(x, y) self.state.pressed = true if not self._dropDownWindow then local sx,sy = self:LocalToScreen(0,0) local selectByName = self.selectByName local labels = {} local width = math.max(self.width, self.minDropDownWidth) local height = 7 for i = 1, #self.items do local item = self.items[i] if type(item) == "string" then local newBtn = ComboBoxItem:New { caption = item, width = '100%', height = self.itemHeight, fontsize = self.itemFontSize, state = {focused = (i == self.selected), selected = (i == self.selected)}, OnMouseUp = { function() if selectByName then self:Select(item) else self:Select(i) end self:_CloseWindow() end } } labels[#labels+1] = newBtn height = height + self.itemHeight width = math.max(width, self.font:GetTextWidth(item)) else labels[#labels+1] = item item.OnMouseUp = { function() self:Select(i) self:_CloseWindow() end } width = math.max(width, item.width + 5) height = height + item.height -- FIXME: what if this height is relative? end end height = math.max(self.minDropDownHeight, height) height = math.min(self.maxDropDownHeight, height) width = math.min(self.maxDropDownWidth, width) local screen = self:FindParent("screen") local y = sy + self.height if y + height > screen.height then y = sy - height end self._dropDownWindow = ComboBoxWindow:New{ parent = screen, width = width, height = height, minHeight = self.minDropDownHeight, x = math.max(sx, math.min(sx + self.width - width, (sx + x - width/2))) + self.selectionOffsetX, y = y + self.selectionOffsetY, children = { ComboBoxScrollPanel:New{ width = "100%", height = "100%", children = { ComboBoxStackPanel:New{ width = '100%', children = labels, }, }, } } } self._scrollPanelCtrl = self._dropDownWindow.children[1] self:CallListeners(self.OnOpen) else self:_CloseWindow() end self:Invalidate() return self end function ComboBox:MouseUp(...) self:Invalidate() return self -- this exists to override Button:MouseUp so it doesn't modify .state.pressed end
fix clicking on combobox scrollbar dismissing the combobox; close #306
fix clicking on combobox scrollbar dismissing the combobox; close #306
Lua
mit
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
2e308d67d88d0c80275610ed8bfe22bc2058db25
resources/prosody-plugins/mod_muc_allowners.lua
resources/prosody-plugins/mod_muc_allowners.lua
local filters = require 'util.filters'; local jid = require "util.jid"; local jid_bare = require "util.jid".bare; local um_is_admin = require "core.usermanager".is_admin; local util = module:require "util"; local is_healthcheck_room = util.is_healthcheck_room; local extract_subdomain = util.extract_subdomain; local presence_check_status = util.presence_check_status; local MUC_NS = 'http://jabber.org/protocol/muc'; local moderated_subdomains; local moderated_rooms; local function load_config() moderated_subdomains = module:get_option_set("allowners_moderated_subdomains", {}) moderated_rooms = module:get_option_set("allowners_moderated_rooms", {}) end load_config(); local function is_admin(jid) return um_is_admin(jid, module.host); end -- List of the bare_jids of all occupants that are currently joining (went through pre-join) and will be promoted -- as moderators. As pre-join (where added) and joined event (where removed) happen one after another this list should -- have length of 1 local joining_moderator_participants = {}; -- Checks whether the jid is moderated, the room name is in moderated_rooms -- or if the subdomain is in the moderated_subdomains -- @return returns on of the: -- -> false -- -> true, room_name, subdomain -- -> true, room_name, nil (if no subdomain is used for the room) local function is_moderated(room_jid) if moderated_subdomains:empty() and moderated_rooms:empty() then return false; end local room_node = jid.node(room_jid); -- parses bare room address, for multidomain expected format is: -- [subdomain][email protected] local target_subdomain, target_room_name = extract_subdomain(room_node); if target_subdomain then if moderated_subdomains:contains(target_subdomain) then return true, target_room_name, target_subdomain; end elseif moderated_rooms:contains(room_node) then return true, room_node, nil; end return false; end module:hook("muc-occupant-pre-join", function (event) local room, occupant = event.room, event.occupant; if is_healthcheck_room(room.jid) or is_admin(occupant.bare_jid) then return; end local moderated, room_name, subdomain = is_moderated(room.jid); if moderated then local session = event.origin; local token = session.auth_token; if not token then module:log('debug', 'skip allowners for non-auth user subdomain:%s room_name:%s', subdomain, room_name); return; end if not (room_name == session.jitsi_meet_room or session.jitsi_meet_room == '*') then module:log('debug', 'skip allowners for auth user and non matching room name: %s, jwt room name: %s', room_name, session.jitsi_meet_room); return; end if not (subdomain == session.jitsi_meet_context_group) then module:log('debug', 'skip allowners for auth user and non matching room subdomain: %s, jwt subdomain: %s', subdomain, session.jitsi_meet_context_group); return; end end -- mark this participant that it will be promoted and is currently joining joining_moderator_participants[occupant.bare_jid] = true; end, 2); module:hook("muc-occupant-joined", function (event) local room, occupant = event.room, event.occupant; local promote_to_moderator = joining_moderator_participants[occupant.bare_jid]; -- clear it joining_moderator_participants[occupant.bare_jid] = nil; if promote_to_moderator ~= nil then room:set_affiliation(true, occupant.bare_jid, "owner"); end end, 2); module:hook("muc-occupant-left", function (event) local room, occupant = event.room, event.occupant; if is_healthcheck_room(room.jid) then return; end room:set_affiliation(true, occupant.bare_jid, nil); end, 2); module:hook_global('config-reloaded', load_config); -- Filters self-presences to a jid that exist in joining_participants array -- We want to filter those presences where we send first `participant` and just after it `moderator` function filter_stanza(stanza) if not stanza.attr or not stanza.attr.to or stanza.name ~= "presence" then return stanza; end -- Allow self-presence (code=110) local bare_to = jid_bare(stanza.attr.to); if joining_moderator_participants[bare_to] then if presence_check_status(stanza:get_child('x', MUC_NS..'#user'), '110') then return nil; end end return stanza; end function filter_session(session) -- domain mapper is filtering on default priority 0, and we need it after that filters.add_filter(session, 'stanzas/out', filter_stanza, -1); end -- enable filtering presences filters.add_filter_hook(filter_session);
local filters = require 'util.filters'; local jid = require "util.jid"; local jid_bare = require "util.jid".bare; local um_is_admin = require "core.usermanager".is_admin; local util = module:require "util"; local is_healthcheck_room = util.is_healthcheck_room; local extract_subdomain = util.extract_subdomain; local presence_check_status = util.presence_check_status; local MUC_NS = 'http://jabber.org/protocol/muc'; local moderated_subdomains; local moderated_rooms; local function load_config() moderated_subdomains = module:get_option_set("allowners_moderated_subdomains", {}) moderated_rooms = module:get_option_set("allowners_moderated_rooms", {}) end load_config(); local function is_admin(jid) return um_is_admin(jid, module.host); end -- List of the bare_jids of all occupants that are currently joining (went through pre-join) and will be promoted -- as moderators. As pre-join (where added) and joined event (where removed) happen one after another this list should -- have length of 1 local joining_moderator_participants = {}; -- Checks whether the jid is moderated, the room name is in moderated_rooms -- or if the subdomain is in the moderated_subdomains -- @return returns on of the: -- -> false -- -> true, room_name, subdomain -- -> true, room_name, nil (if no subdomain is used for the room) local function is_moderated(room_jid) if moderated_subdomains:empty() and moderated_rooms:empty() then return false; end local room_node = jid.node(room_jid); -- parses bare room address, for multidomain expected format is: -- [subdomain][email protected] local target_subdomain, target_room_name = extract_subdomain(room_node); if target_subdomain then if moderated_subdomains:contains(target_subdomain) then return true, target_room_name, target_subdomain; end elseif moderated_rooms:contains(room_node) then return true, room_node, nil; end return false; end module:hook("muc-occupant-pre-join", function (event) local room, occupant = event.room, event.occupant; if is_healthcheck_room(room.jid) or is_admin(occupant.bare_jid) then return; end local moderated, room_name, subdomain = is_moderated(room.jid); if moderated then local session = event.origin; local token = session.auth_token; if not token then module:log('debug', 'skip allowners for non-auth user subdomain:%s room_name:%s', subdomain, room_name); return; end if not (room_name == session.jitsi_meet_room or session.jitsi_meet_room == '*') then module:log('debug', 'skip allowners for auth user and non matching room name: %s, jwt room name: %s', room_name, session.jitsi_meet_room); return; end if not (subdomain == session.jitsi_meet_context_group) then module:log('debug', 'skip allowners for auth user and non matching room subdomain: %s, jwt subdomain: %s', subdomain, session.jitsi_meet_context_group); return; end end -- mark this participant that it will be promoted and is currently joining joining_moderator_participants[occupant.bare_jid] = true; end, 2); module:hook("muc-occupant-joined", function (event) local room, occupant = event.room, event.occupant; local promote_to_moderator = joining_moderator_participants[occupant.bare_jid]; -- clear it joining_moderator_participants[occupant.bare_jid] = nil; if promote_to_moderator ~= nil then room:set_affiliation(true, occupant.bare_jid, "owner"); end end, 2); module:hook("muc-occupant-left", function (event) local room, occupant = event.room, event.occupant; if is_healthcheck_room(room.jid) then return; end room:set_affiliation(true, occupant.bare_jid, nil); end, 2); module:hook_global('config-reloaded', load_config); -- Filters self-presences to a jid that exist in joining_participants array -- We want to filter those presences where we send first `participant` and just after it `moderator` function filter_stanza(stanza) -- when joining_moderator_participants is empty there is nothing to filter if next(joining_moderator_participants) == nil or not stanza.attr or not stanza.attr.to or stanza.name ~= "presence" then return stanza; end local muc_x = stanza:get_child('x', MUC_NS..'#user'); if not muc_x then return stanza; end local bare_to = jid_bare(stanza.attr.to); if joining_moderator_participants[bare_to] and presence_check_status(muc_x, '110') then -- skip the local presence for participant return nil; end -- skip sending the 'participant' presences to all other people in the room for item in muc_x:childtags('item') do if joining_moderator_participants[jid_bare(item.attr.jid)] then return nil; end end return stanza; end function filter_session(session) -- domain mapper is filtering on default priority 0, and we need it after that filters.add_filter(session, 'stanzas/out', filter_stanza, -1); end -- enable filtering presences filters.add_filter_hook(filter_session);
feat: Fixes filtering not needed presences.
feat: Fixes filtering not needed presences. We were filtering only self presences, no it filters and the presences to the other participants.
Lua
apache-2.0
gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet
a5d99f0619bb58309313ece1ba320a5e465681a2
packages/rules.lua
packages/rules.lua
SILE.baseClass:loadPackage("raiselower") SILE.baseClass:loadPackage("rebox") SILE.registerCommand("hrule", function (options, _) local width = SU.cast("length", options.width) local height = SU.cast("length", options.height) local depth = SU.cast("length", options.depth) SILE.typesetter:pushHbox({ width = width:absolute(), height = height:absolute(), depth = depth:absolute(), value = options.src, outputYourself= function (self, typesetter, line) local outputWidth = SU.rationWidth(self.width, self.width, line.ratio) typesetter.frame:advancePageDirection(-self.height) local oldx = typesetter.frame.state.cursorX local oldy = typesetter.frame.state.cursorY typesetter.frame:advanceWritingDirection(outputWidth) typesetter.frame:advancePageDirection(self.height + self.depth) local newx = typesetter.frame.state.cursorX local newy = typesetter.frame.state.cursorY SILE.outputter:drawRule(oldx, oldy, newx - oldx, newy - oldy) end }) end, "Creates a line of width <width> and height <height>") SILE.registerCommand("fullrule", function (options, _) SILE.call("raise", { height = options.raise or "0.5em" }, function () SILE.call("hrule", { height = options.height or "0.2pt", width = options.width or "100%lw" }) end) end, "Draw a full width hrule centered on the current line") SILE.registerCommand("underline", function (_, content) local ot = SILE.require("core/opentype-parser") local fontoptions = SILE.font.loadDefaults({}) local face = SILE.font.cache(fontoptions, SILE.shaper.getFace) local font = ot.parseFont(face) local upem = font.head.unitsPerEm local underlinePosition = -font.post.underlinePosition / upem * fontoptions.size local underlineThickness = font.post.underlineThickness / upem * fontoptions.size local hbox = SILE.call("hbox", {}, content) local gl = SILE.length() - hbox.width SILE.call("lower", {height = SU.cast("measurement", underlinePosition)}, function() SILE.call("hrule", {width = gl.length, height = underlineThickness}) end) SILE.typesetter:pushGlue({width = hbox.width}) end, "Underlines some content") SILE.registerCommand("boxaround", function (_, content) local hbox = SILE.call("hbox", {}, content) local gl = SILE.length() - hbox.width SILE.call("rebox", {width = 0}, function() SILE.call("hrule", {width = gl.length-1, height = "0.5pt"}) end) SILE.call("raise", {height = hbox.height}, function () SILE.call("hrule", {width = gl.length-1, height = "0.5pt"}) end) SILE.call("hrule", { height = hbox.height, width = "0.5pt"}) SILE.typesetter:pushGlue({width = hbox.width}) SILE.call("hrule", { height = hbox.height, width = "0.5pt"}) end, "Draws a box around some content") return { documentation = [[\begin{document} The \code{rules} package draws lines. It provides three commands. The first command is \code{\\hrule}, which draws a line of a given length and thickness, although it calls these \code{width} and \code{height}. (A box is just a square line.) Lines are treated just like other text to be output, and so can appear in the middle of a paragraph, like this: \hrule[width=20pt, height=0.5pt] (that one was generated with \code{\\hrule[width=20pt, height=0.5pt]}.) Like images, rules are placed along the baseline of a line of text. The second command provided by \code{rules} is \code{\\underline}, which underlines its contents. \note{ Underlining is horrible typographic practice, and you should \underline{never} do it.} (That was produced with \code{\\underline\{never\}}.) Finally, \code{fullrule} draws a thin line across the width of the current frame. \end{document}]] }
SILE.baseClass:loadPackage("raiselower") SILE.baseClass:loadPackage("rebox") SILE.registerCommand("hrule", function (options, _) local width = SU.cast("length", options.width) local height = SU.cast("length", options.height) local depth = SU.cast("length", options.depth) SILE.typesetter:pushHbox({ width = width:absolute(), height = height:absolute(), depth = depth:absolute(), value = options.src, outputYourself= function (self, typesetter, line) local outputWidth = SU.rationWidth(self.width, self.width, line.ratio) typesetter.frame:advancePageDirection(-self.height) local oldx = typesetter.frame.state.cursorX local oldy = typesetter.frame.state.cursorY typesetter.frame:advanceWritingDirection(outputWidth) typesetter.frame:advancePageDirection(self.height + self.depth) local newx = typesetter.frame.state.cursorX local newy = typesetter.frame.state.cursorY SILE.outputter:drawRule(oldx, oldy, newx - oldx, newy - oldy) end }) end, "Creates a line of width <width> and height <height>") SILE.registerCommand("fullrule", function (options, _) SILE.call("raise", { height = options.raise or "0.5em" }, function () SILE.call("hrule", { height = options.height or "0.2pt", width = options.width or "100%lw" }) end) end, "Draw a full width hrule centered on the current line") SILE.registerCommand("underline", function (_, content) local ot = SILE.require("core/opentype-parser") local fontoptions = SILE.font.loadDefaults({}) local face = SILE.font.cache(fontoptions, SILE.shaper.getFace) local font = ot.parseFont(face) local upem = font.head.unitsPerEm local underlinePosition = -font.post.underlinePosition / upem * fontoptions.size local underlineThickness = font.post.underlineThickness / upem * fontoptions.size local hbox = SILE.call("hbox", {}, content) table.remove(SILE.typesetter.state.nodes) -- steal it back... -- Re-wrap the hbox in another hbox responsible for boxing it at output -- time, when we will know the line contribution and can compute the scaled width -- of the box, taking into account possible stretching and shrinking. SILE.typesetter:pushHbox({ inner = hbox, width = hbox.width, height = hbox.height, depth = hbox.depth, outputYourself = function(self, typesetter, line) local oldX = typesetter.frame.state.cursorX local Y = typesetter.frame.state.cursorY -- Build the original hbox. -- Cursor will be moved by the actual definitive size. self.inner:outputYourself(SILE.typesetter, line) local newX = typesetter.frame.state.cursorX -- Output a line. -- NOTE: According to the OpenType specs, underlinePosition is "the suggested distance of -- the top of the underline from the baseline" so it seems implied that the thickness -- should expand downwards SILE.outputter:drawRule(oldX, Y + underlinePosition, newX - oldX, underlineThickness) end }) end, "Underlines some content") SILE.registerCommand("boxaround", function (_, content) local hbox = SILE.call("hbox", {}, content) local gl = SILE.length() - hbox.width SILE.call("rebox", {width = 0}, function() SILE.call("hrule", {width = gl.length-1, height = "0.5pt"}) end) SILE.call("raise", {height = hbox.height}, function () SILE.call("hrule", {width = gl.length-1, height = "0.5pt"}) end) SILE.call("hrule", { height = hbox.height, width = "0.5pt"}) SILE.typesetter:pushGlue({width = hbox.width}) SILE.call("hrule", { height = hbox.height, width = "0.5pt"}) end, "Draws a box around some content") return { documentation = [[\begin{document} The \code{rules} package draws lines. It provides three commands. The first command is \code{\\hrule}, which draws a line of a given length and thickness, although it calls these \code{width} and \code{height}. (A box is just a square line.) Lines are treated just like other text to be output, and so can appear in the middle of a paragraph, like this: \hrule[width=20pt, height=0.5pt] (that one was generated with \code{\\hrule[width=20pt, height=0.5pt]}.) Like images, rules are placed along the baseline of a line of text. The second command provided by \code{rules} is \code{\\underline}, which underlines its contents. \note{ Underlining is horrible typographic practice, and you should \underline{never} do it.} (That was produced with \code{\\underline\{never\}}.) Finally, \code{fullrule} draws a thin line across the width of the current frame. \end{document}]] }
fix(packages): Make underline respect shrink/strech (rules package)
fix(packages): Make underline respect shrink/strech (rules package)
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
51ea28488129d28cd346d04e605494afa30e16ea
MMOCoreORB/bin/scripts/commands/multiTargetShot.lua
MMOCoreORB/bin/scripts/commands/multiTargetShot.lua
--Copyright (C) 2007 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --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 Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. --true = 1, false = 0 MultiTargetShotCommand = { name = "multitargetshot", } AddCommand(MultiTargetShotCommand)
--Copyright (C) 2007 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --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 Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. --true = 1, false = 0 MultiTargetShotCommand = { name = "multitargetshot", combatSpam = "multishot", range = -1 } AddCommand(MultiTargetShotCommand)
[fixed] one of the grammar data bugs
[fixed] one of the grammar data bugs git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@3767 c3d1530f-68f5-4bd0-87dc-8ef779617e40
Lua
agpl-3.0
lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
e9fbae995f5153b5e80883e0639cccd20f313316
test_scripts/Polices/user_consent_of_Policies/101_ATF_Device_treated_as_consented.lua
test_scripts/Polices/user_consent_of_Policies/101_ATF_Device_treated_as_consented.lua
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [Policies] Treating the device as consented -- -- Description: -- Condition for device to be consented -- 1. Used preconditions: -- Close current connection -- Overwrite preloaded policy table to have group both listed in 'device' and 'preconsented_groups' sub-sections of 'app_policies' section -- Connect device for the first time -- Register app running on this device -- 2. Performed steps -- Activate app: HMI->SDL: SDL.ActivateApp => Policies Manager treats the device as consented => no consent popup appears => SDL->HMI: SDL.ActivateApp(isSDLAllowed: true, params) -- -- Expected result: -- Policies Manager must treat the device as consented If "device" sub-section of "app_policies" has its group listed in "preconsented_groups". --------------------------------------------------------------------------------------------- --[[ 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 testCasesForPolicyTableSnapshot = require('user_modules/shared_testcases/testCasesForPolicyTableSnapshot') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') --[[ Local variables ]] local ServerAddress = commonFunctions:read_parameter_from_smart_device_link_ini("ServerAddress") --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() testCasesForPolicyTable:Precondition_updatePolicy_By_overwriting_preloaded_pt("files/DeviceGroupInPreconsented_preloadedPT.json") --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_TreatDeviceAsConsented() local is_test_fail = false local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications[config.application1.registerAppInterfaceParams.appName]}) EXPECT_HMIRESPONSE(RequestId, { isSDLAllowed = true } ) :Do(function(_,data) if(data.result.isSDLAllowed == false) then local RequestId1 = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}}) EXPECT_HMIRESPONSE( RequestId1, {result = {code = 0, method = "SDL.GetUserFriendlyMessage"}}) :Do(function(_,_) self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", {allowed = true, source = "GUI", device = {id = config.deviceMAC, name = ServerAddress, isSDLAllowed = true}}) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"}) EXPECT_HMICALL("BasicCommunication.PolicyUpdate",{}) :Do(function(_,_data1) self.hmiConnection:SendResponse(_data1.id, _data1.method, "SUCCESS", {}) testCasesForPolicyTableSnapshot:extract_pts({self.applications[config.application1.registerAppInterfaceParams.appName]}) local device_consent_groups = testCasesForPolicyTableSnapshot:get_data_from_PTS("app_policies.device.groups.1") local device_preconsented_groups = testCasesForPolicyTableSnapshot:get_data_from_PTS("app_policies.device.preconsented_groups.1") if(device_consent_groups ~= "DataConsent-2") then commonFunctions:printError("Error: app_policies.device.groups should be DataConsent-2") is_test_fail = true end if(device_preconsented_groups ~= "DataConsent-2") then commonFunctions:printError("Error: app_policies.device.preconsented_groups should be DataConsent-2") is_test_fail = true end if(is_test_fail == true) then self:FailTestCase("Test is FAILED. See prints.") end end) end) else local RequestIdUpdateSDL = self.hmiConnection:SendRequest("SDL.UpdateSDL") EXPECT_HMIRESPONSE(RequestIdUpdateSDL,{result = {code = 0, method = "SDL.UpdateSDL", result = "UPDATE_NEEDED" }}) :Do(function(_,_data1) self.hmiConnection:SendResponse(_data1.id, _data1.method, "SUCCESS", {}) testCasesForPolicyTableSnapshot:extract_pts({self.applications[config.application1.registerAppInterfaceParams.appName]}) local device_consent_groups = testCasesForPolicyTableSnapshot:get_data_from_PTS("app_policies.device.groups.1") local device_preconsented_groups = testCasesForPolicyTableSnapshot:get_data_from_PTS("app_policies.device.preconsented_groups.1") if(device_consent_groups ~= "DataConsent-2") then commonFunctions:printError("Error: app_policies.device.groups should be DataConsent-2") is_test_fail = true end if(device_preconsented_groups ~= "DataConsent-2") then commonFunctions:printError("Error: app_policies.device.preconsented_groups should be DataConsent-2") is_test_fail = true end if(is_test_fail == true) then self:FailTestCase("Test is FAILED. See prints.") end end) end end) EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"}) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") testCasesForPolicyTable:Restore_preloaded_pt() function Test.Postcondition_StopSDL() StopSDL() end
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [Policies] Treating the device as consented -- -- Description: -- Condition for device to be consented -- 1. Used preconditions: -- Close current connection -- Overwrite preloaded policy table to have group both listed in 'device' and 'preconsented_groups' sub-sections of 'app_policies' section -- Connect device for the first time -- Register app running on this device -- 2. Performed steps -- Activate app: HMI->SDL: SDL.ActivateApp => Policies Manager treats the device as consented => no consent popup appears => SDL->HMI: SDL.ActivateApp(isSDLAllowed: true, params) -- -- Expected result: -- Policies Manager must treat the device as consented If "device" sub-section of "app_policies" has its group listed in "preconsented_groups". --------------------------------------------------------------------------------------------- --[[ 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:Precondition_updatePolicy_By_overwriting_preloaded_pt("files/DeviceGroupInPreconsented_preloadedPT.json") --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_TreatDeviceAsConsented() local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications[config.application1.registerAppInterfaceParams.appName] }) EXPECT_HMIRESPONSE(RequestId, { isSDLAllowed = true } ) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") testCasesForPolicyTable:Restore_preloaded_pt() function Test.Postcondition_StopSDL() StopSDL() end
Fix issues
Fix issues
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
18d2631f4dcf8e099230583d0b707fd681da2a72
src/program/config/listen/listen.lua
src/program/config/listen/listen.lua
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local S = require("syscall") local ffi = require("ffi") local fiber = require("lib.fibers.fiber") local queue = require("lib.fibers.queue") local mem = require("lib.stream.mem") local file = require("lib.stream.file") local rpc = require("lib.yang.rpc") local data = require("lib.yang.data") local path_lib = require("lib.yang.path") local json_lib = require("lib.ptree.json") local common = require("program.config.common") local function open_socket(file) S.signal('pipe', 'ign') local socket = assert(S.socket("unix", "stream")) S.unlink(file) local sa = S.t.sockaddr_un(file) assert(socket:bind(sa)) assert(socket:listen()) return socket end local function validate_config(schema_name, revision_date, path, value_str) local parser = common.config_parser(schema_name, path) local value = parser(mem.open_input_string(value_str)) return common.serialize_config(value, schema_name, path) end local request_handlers = {} function request_handlers.get(schema_name, revision_date, path) return {method='get-config', args={schema=schema_name, revision=revision_date, path=path}} end function request_handlers.get_state(schema_name, revision_date, path) return {method='get-state', args={schema=schema_name, revision=revision_date, path=path}} end function request_handlers.set(schema_name, revision_date, path, value) assert(value ~= nil) local config = validate_config(schema_name, revision_date, path, value) return {method='set-config', args={schema=schema_name, revision=revision_date, path=path, config=config}} end function request_handlers.add(schema_name, revision_date, path, value) assert(value ~= nil) local config = validate_config(schema_name, revision_date, path, value) return {method='add-config', args={schema=schema_name, revision=revision_date, path=path, config=config}} end function request_handlers.remove(schema_name, revision_date, path) return {method='remove-config', args={schema=schema_name, revision=revision_date, path=path}} end local function read_request(client, schema_name, revision_date) local json = json_lib.read_json(client) if json == nil then -- The input pipe is closed. FIXME: there could still be buffered -- responses; we should exit only once we've received them. io.stderr:write('Input pipe closed.\n') os.exit(0) end local id, verb, path = assert(json.id), assert(json.verb), json.path or '/' path = path_lib.normalize_path(path) if json.schema then schema_name = json.schema end if json.revision then revision_date = json.revision end local handler = assert(request_handlers[data.normalize_id(verb)]) local req = handler(schema_name, revision_date, path, json.value) local function print_reply(reply, output) local value if verb == 'get' then value = reply.config elseif verb == 'get-state' then value = reply.state end json_lib.write_json(output, {id=id, status='ok', value=value}) output:flush() end return req, print_reply end local function attach_listener(leader, caller, schema_name, revision_date) local msg, parse_reply = rpc.prepare_call( caller, 'attach-listener', {schema=schema_name, revision=revision_date}) common.send_message(leader, msg) return parse_reply(mem.open_input_string(common.recv_message(leader))) end function run(args) args = common.parse_command_line(args, { command='listen' }) if args.error then common.print_and_exit(args) end local caller = rpc.prepare_caller('snabb-config-leader-v1') local leader = common.open_socket_or_die(args.instance_id) attach_listener(leader, caller, args.schema_name, args.revision_date) local handler = require('lib.fibers.file').new_poll_io_handler() file.set_blocking_handler(handler) fiber.current_scheduler:add_task_source(handler) -- Leader was blocking in call to attach_listener. leader:nonblock() -- Check if there is a socket path specified, if so use that as method -- to communicate, otherwise use stdin and stdout. local client_rx, client_tx = nil if args.socket then local sockfd = open_socket(args.socket) local addr = S.t.sockaddr_un() -- Wait for a connection print("Listening for clients on socket: "..args.socket) client_rx = file.fdopen(assert(sockfd:accept(addr))) client_tx = client_rx else client_rx = file.fdopen(S.stdin) client_tx = file.fdopen(S.stdout) end local pending_replies = queue.new() local function exit_when_finished(f) return function() local success, res = pcall(f) if not success then io.stderr:write('error: '..tostring(res)..'\n') end os.exit(success and 0 or 1) end end local function handle_requests() while true do -- FIXME: Better error message on read-from-client failures. local request, print_reply = read_request(client_rx, args.schema_name, args.revision_date) local msg, parse_reply = rpc.prepare_call( caller, request.method, request.args) local function have_reply(msg) msg = mem.open_input_string(msg) return print_reply(parse_reply(msg), client_tx) end pending_replies:put(have_reply) -- FIXME: Better error message on write-to-leader failures. common.send_message(leader, msg) end end local function handle_replies() while true do local handle_reply = pending_replies:get() -- FIXME: Better error message on read-from-leader failures. -- FIXME: Better error message on write-to-client failures. handle_reply(common.recv_message(leader)) end end fiber.spawn(exit_when_finished(handle_requests)) fiber.spawn(exit_when_finished(handle_replies)) fiber.main() end
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local S = require("syscall") local ffi = require("ffi") local fiber = require("lib.fibers.fiber") local queue = require("lib.fibers.queue") local mem = require("lib.stream.mem") local file = require("lib.stream.file") local rpc = require("lib.yang.rpc") local data = require("lib.yang.data") local path_lib = require("lib.yang.path") local json_lib = require("lib.ptree.json") local common = require("program.config.common") local function open_socket(file) S.signal('pipe', 'ign') local socket = assert(S.socket("unix", "stream")) S.unlink(file) local sa = S.t.sockaddr_un(file) assert(socket:bind(sa)) assert(socket:listen()) return socket end local function validate_config(schema_name, revision_date, path, value_str) local parser = common.config_parser(schema_name, path) local value = parser(mem.open_input_string(value_str)) return common.serialize_config(value, schema_name, path) end local request_handlers = {} function request_handlers.get(schema_name, revision_date, path) return {method='get-config', args={schema=schema_name, revision=revision_date, path=path}} end function request_handlers.get_state(schema_name, revision_date, path) return {method='get-state', args={schema=schema_name, revision=revision_date, path=path}} end function request_handlers.set(schema_name, revision_date, path, value) assert(value ~= nil) local config = validate_config(schema_name, revision_date, path, value) return {method='set-config', args={schema=schema_name, revision=revision_date, path=path, config=config}} end function request_handlers.add(schema_name, revision_date, path, value) assert(value ~= nil) local config = validate_config(schema_name, revision_date, path, value) return {method='add-config', args={schema=schema_name, revision=revision_date, path=path, config=config}} end function request_handlers.remove(schema_name, revision_date, path) return {method='remove-config', args={schema=schema_name, revision=revision_date, path=path}} end local function read_request(client, schema_name, revision_date) local json = json_lib.read_json(client) if json == nil then -- The input pipe is closed. FIXME: there could still be buffered -- responses; we should exit only once we've received them. io.stderr:write('Input pipe closed.\n') os.exit(0) end local id, verb, path = assert(json.id), assert(json.verb), json.path or '/' path = path_lib.normalize_path(path) if json.schema then schema_name = json.schema end if json.revision then revision_date = json.revision end local handler = assert(request_handlers[data.normalize_id(verb)]) local req = handler(schema_name, revision_date, path, json.value) local function print_reply(reply, output) local value if verb == 'get' then value = reply.config elseif verb == 'get-state' then value = reply.state end json_lib.write_json(output, {id=id, status='ok', value=value}) output:flush() end return req, print_reply end local function attach_listener(leader, caller, schema_name, revision_date) local msg, parse_reply = rpc.prepare_call( caller, 'attach-listener', {schema=schema_name, revision=revision_date}) common.send_message(leader, msg) return parse_reply(mem.open_input_string(common.recv_message(leader))) end function run(args) args = common.parse_command_line(args, { command='listen' }) if args.error then common.print_and_exit(args) end local caller = rpc.prepare_caller('snabb-config-leader-v1') local leader = common.open_socket(args.instance_id) if not leader then io.stderr:write( ("Could not connect to config leader socket on Snabb instance %q\n") :format(args.instance_id) ) main.exit(1) end attach_listener(leader, caller, args.schema_name, args.revision_date) local handler = require('lib.fibers.file').new_poll_io_handler() file.set_blocking_handler(handler) fiber.current_scheduler:add_task_source(handler) -- Leader was blocking in call to attach_listener. leader:nonblock() -- Check if there is a socket path specified, if so use that as method -- to communicate, otherwise use stdin and stdout. local client_rx, client_tx = nil if args.socket then local sockfd = open_socket(args.socket) local addr = S.t.sockaddr_un() -- Wait for a connection print("Listening for clients on socket: "..args.socket) client_rx = file.fdopen(assert(sockfd:accept(addr))) client_tx = client_rx else client_rx = file.fdopen(S.stdin) client_tx = file.fdopen(S.stdout) end local pending_replies = queue.new() local function exit_when_finished(f) return function() local success, res = pcall(f) if not success then io.stderr:write('error: '..tostring(res)..'\n') end os.exit(success and 0 or 1) end end local function handle_requests() while true do -- FIXME: Better error message on read-from-client failures. local request, print_reply = read_request(client_rx, args.schema_name, args.revision_date) local msg, parse_reply = rpc.prepare_call( caller, request.method, request.args) local function have_reply(msg) msg = mem.open_input_string(msg) return print_reply(parse_reply(msg), client_tx) end pending_replies:put(have_reply) -- FIXME: Better error message on write-to-leader failures. common.send_message(leader, msg) end end local function handle_replies() while true do local handle_reply = pending_replies:get() -- FIXME: Better error message on read-from-leader failures. -- FIXME: Better error message on write-to-client failures. handle_reply(common.recv_message(leader)) end end fiber.spawn(exit_when_finished(handle_requests)) fiber.spawn(exit_when_finished(handle_replies)) fiber.main() end
snabb config listen: fix bug introduced in bfa68ba1bd4ccf7afe973ed21cafac9a0dcb72b5
snabb config listen: fix bug introduced in bfa68ba1bd4ccf7afe973ed21cafac9a0dcb72b5
Lua
apache-2.0
eugeneia/snabb,eugeneia/snabb,eugeneia/snabb,snabbco/snabb,snabbco/snabb,snabbco/snabb,eugeneia/snabb,snabbco/snabb,snabbco/snabb,snabbco/snabb,snabbco/snabb,snabbco/snabb,eugeneia/snabb,eugeneia/snabb,eugeneia/snabb,eugeneia/snabb
da050a5630709c509174624a50d8b284526f67d6
modules/corelib/ui/uipopupmenu.lua
modules/corelib/ui/uipopupmenu.lua
-- @docclass UIPopupMenu = extends(UIWidget) local currentMenu function UIPopupMenu.create() local menu = UIPopupMenu.internalCreate() local layout = UIVerticalLayout.create(menu) layout:setFitChildren(true) menu:setLayout(layout) return menu end function UIPopupMenu:display(pos) -- don't display if not options was added if self:getChildCount() == 0 then self:destroy() return end if g_ui.isMouseGrabbed() then self:destroy() return end if currentMenu then currentMenu:destroy() end if pos == nil then pos = g_window.getMousePosition() end rootWidget:addChild(self) self:setPosition(pos) self:grabMouse() --self:grabKeyboard() currentMenu = self end function UIPopupMenu:onGeometryChange(oldRect, newRect) local parent = self:getParent() if not parent then return end local ymax = parent:getY() + parent:getHeight() local xmax = parent:getX() + parent:getWidth() if newRect.y + newRect.height > ymax then local newy = newRect.y - newRect.height if newy > 0 and newy + newRect.height < ymax then self:setY(newy) end end if newRect.x + newRect.width > xmax then local newx = newRect.x - newRect.width if newx > 0 and newx + newRect.width < xmax then self:setX(newx) end end self:bindRectToParent() end function UIPopupMenu:addOption(optionName, optionCallback, shortcut) local optionWidget = g_ui.createWidget(self:getStyleName() .. 'Button', self) local lastOptionWidget = self:getLastChild() optionWidget.onClick = function(self) optionCallback() self:getParent():destroy() end optionWidget:setText(optionName) local width = optionWidget:getTextSize().width + optionWidget:getMarginLeft() + optionWidget:getMarginRight() + 15 if shortcut then local shortcutLabel = g_ui.createWidget(self:getStyleName() .. 'ShortcutLabel', optionWidget) shortcutLabel:setText(shortcut) width = width + shortcutLabel:getTextSize().width + shortcutLabel:getMarginLeft() + shortcutLabel:getMarginRight() end self:setWidth(math.max(self:getWidth(), width)) end function UIPopupMenu:addSeparator() g_ui.createWidget(self:getStyleName() .. 'Separator', self) end function UIPopupMenu:onDestroy() if currentMenu == self then currentMenu = nil end end function UIPopupMenu:onMousePress(mousePos, mouseButton) -- clicks outside menu area destroys the menu if not self:containsPoint(mousePos) then self:destroy() end return true end function UIPopupMenu:onKeyPress(keyCode, keyboardModifiers) if keyCode == KeyEscape then self:destroy() return true end return false end -- close all menus when the window is resized local function onRootGeometryUpdate() if currentMenu then currentMenu:destroy() end end connect(rootWidget, { onGeometryChange = onRootGeometryUpdate} )
-- @docclass UIPopupMenu = extends(UIWidget) local currentMenu function UIPopupMenu.create() local menu = UIPopupMenu.internalCreate() local layout = UIVerticalLayout.create(menu) layout:setFitChildren(true) menu:setLayout(layout) return menu end function UIPopupMenu:display(pos) -- don't display if not options was added if self:getChildCount() == 0 then self:destroy() return end if g_ui.isMouseGrabbed() then self:destroy() return end if currentMenu then currentMenu:destroy() end if pos == nil then pos = g_window.getMousePosition() end rootWidget:addChild(self) self:setPosition(pos) self:grabMouse() --self:grabKeyboard() currentMenu = self end function UIPopupMenu:onGeometryChange(oldRect, newRect) local parent = self:getParent() if not parent then return end local ymax = parent:getY() + parent:getHeight() local xmax = parent:getX() + parent:getWidth() if newRect.y + newRect.height > ymax then local newy = newRect.y - newRect.height if newy > 0 and newy + newRect.height < ymax then self:setY(newy) end end if newRect.x + newRect.width > xmax then local newx = newRect.x - newRect.width if newx > 0 and newx + newRect.width < xmax then self:setX(newx) end end self:bindRectToParent() end function UIPopupMenu:addOption(optionName, optionCallback, shortcut) local optionWidget = g_ui.createWidget(self:getStyleName() .. 'Button', self) local lastOptionWidget = self:getLastChild() optionWidget.onClick = function(self) self:getParent():destroy() optionCallback() end optionWidget:setText(optionName) local width = optionWidget:getTextSize().width + optionWidget:getMarginLeft() + optionWidget:getMarginRight() + 15 if shortcut then local shortcutLabel = g_ui.createWidget(self:getStyleName() .. 'ShortcutLabel', optionWidget) shortcutLabel:setText(shortcut) width = width + shortcutLabel:getTextSize().width + shortcutLabel:getMarginLeft() + shortcutLabel:getMarginRight() end self:setWidth(math.max(self:getWidth(), width)) end function UIPopupMenu:addSeparator() g_ui.createWidget(self:getStyleName() .. 'Separator', self) end function UIPopupMenu:onDestroy() if currentMenu == self then currentMenu = nil end self:ungrabMouse() end function UIPopupMenu:onMousePress(mousePos, mouseButton) -- clicks outside menu area destroys the menu if not self:containsPoint(mousePos) then self:destroy() end return true end function UIPopupMenu:onKeyPress(keyCode, keyboardModifiers) if keyCode == KeyEscape then self:destroy() return true end return false end -- close all menus when the window is resized local function onRootGeometryUpdate() if currentMenu then currentMenu:destroy() end end connect(rootWidget, { onGeometryChange = onRootGeometryUpdate} )
Fix trade/use bug from previous commit
Fix trade/use bug from previous commit
Lua
mit
dreamsxin/otclient,Cavitt/otclient_mapgen,kwketh/otclient,Radseq/otclient,EvilHero90/otclient,Cavitt/otclient_mapgen,EvilHero90/otclient,dreamsxin/otclient,kwketh/otclient,gpedro/otclient,Radseq/otclient,gpedro/otclient,gpedro/otclient,dreamsxin/otclient
64179619daa402a98bb05839f6085a45bcd3a6bd
spec/fixtures/mocks/lua-resty-dns/resty/dns/resolver.lua
spec/fixtures/mocks/lua-resty-dns/resty/dns/resolver.lua
-- Mock for the underlying 'resty.dns.resolver' library -- (so NOT the Kong dns client) -- this file should be in the Kong working directory (prefix) local MOCK_RECORD_FILENAME = "dns_mock_records.json" local LOG_PREFIX = "[mock_dns_resolver] " local cjson = require "cjson.safe" -- first thing is to get the original (non-mock) resolver local resolver do local function get_source_path() -- find script path remember to strip off the starting @ -- should be like: 'spec/fixtures/mocks/lua-resty-dns/resty/dns/resolver.lua' return debug.getinfo(2, "S").source:sub(2) --only works in a function, hence the wrapper end local path = get_source_path() -- module part is like: 'resty.dns.resolver' local module_part = select(1,...) -- create the packagepath part, like: 'spec/fixtures/mocks/lua-resty-dns/?.lua' path = path:gsub(module_part:gsub("%.", "/"), "?") .. ";" -- prefix path, so semi-colon at end -- grab current paths local old_paths = package.path -- drop the element that picked this mock from the path local s, e = old_paths:find(path, 1, true) package.path = old_paths:sub(1, s-1) .. old_paths:sub(e + 1, -1) -- With the mock out of the path, require the module again to get the original. -- Problem is that package.loaded contains a userdata now, because we're in -- the middle of loading that same module name. So swap it. local swap swap, package.loaded[module_part] = package.loaded[module_part], nil resolver = require(module_part) package.loaded[module_part] = swap -- restore the package path package.path = old_paths end -- load and cache the mock-records local get_mock_records do local mock_records get_mock_records = function() if mock_records then return mock_records end local is_file = require("pl.path").isfile local prefix = ((kong or {}).configuration or {}).prefix if not prefix then -- we might be invoked before the Kong config was loaded, so exit early -- and do not set _mock_records yet. return {} end local filename = prefix .. "/" .. MOCK_RECORD_FILENAME mock_records = {} if not is_file(filename) then -- no mock records set up, return empty default ngx.log(ngx.DEBUG, LOG_PREFIX, "bypassing mock, no mock records found") return mock_records end -- there is a file with mock records available, go load it local f = assert(io.open(filename)) local json_file = assert(f:read("*a")) f:close() mock_records = assert(cjson.decode(json_file)) return mock_records end end -- patch the actual query method local old_query = resolver.query resolver.query = function(self, name, options, tries) local mock_records = get_mock_records() local qtype = (options or {}).qtype or resolver.TYPE_A local answer = (mock_records[qtype] or {})[name] if answer then -- we actually have a mock answer, return it ngx.log(ngx.DEBUG, LOG_PREFIX, "serving '", name, "' from mocks") return answer, nil, tries end -- no mock, so invoke original resolver return old_query(self, name, options, tries) end return resolver
-- Mock for the underlying 'resty.dns.resolver' library -- (so NOT the Kong dns client) -- this file should be in the Kong working directory (prefix) local MOCK_RECORD_FILENAME = "dns_mock_records.json" local LOG_PREFIX = "[mock_dns_resolver] " local cjson = require "cjson.safe" -- first thing is to get the original (non-mock) resolver local resolver do local function get_source_path() -- find script path remember to strip off the starting @ -- should be like: 'spec/fixtures/mocks/lua-resty-dns/resty/dns/resolver.lua' return debug.getinfo(2, "S").source:sub(2) --only works in a function, hence the wrapper end local path = get_source_path() -- module part is like: 'resty.dns.resolver' local module_part = select(1,...) -- create the packagepath part, like: 'spec/fixtures/mocks/lua-resty-dns/?.lua' path = path:gsub(module_part:gsub("%.", "/"), "?") .. ";" -- prefix path, so semi-colon at end -- grab current paths local old_paths = package.path -- drop the element that picked this mock from the path local s, e = old_paths:find(path, 1, true) package.path = old_paths:sub(1, s-1) .. old_paths:sub(e + 1, -1) -- With the mock out of the path, require the module again to get the original. -- Problem is that package.loaded contains a userdata now, because we're in -- the middle of loading that same module name. So swap it. local swap swap, package.loaded[module_part] = package.loaded[module_part], nil resolver = require(module_part) package.loaded[module_part] = swap -- restore the package path package.path = old_paths end -- load and cache the mock-records local get_mock_records do local mock_records get_mock_records = function() if mock_records then return mock_records end local is_file = require("pl.path").isfile local prefix = ((kong or {}).configuration or {}).prefix if not prefix then -- we might be invoked before the Kong config was loaded, so exit early -- and do not set _mock_records yet. return {} end local filename = prefix .. "/" .. MOCK_RECORD_FILENAME mock_records = {} if not is_file(filename) then -- no mock records set up, return empty default ngx.log(ngx.DEBUG, LOG_PREFIX, "bypassing mock, no mock records found") return mock_records end -- there is a file with mock records available, go load it local f = assert(io.open(filename)) local json_file = assert(f:read("*a")) f:close() mock_records = assert(cjson.decode(json_file)) return mock_records end end -- patch the actual query method local old_query = resolver.query resolver.query = function(self, name, options, tries) local mock_records = get_mock_records() local qtype = (options or {}).qtype or resolver.TYPE_A local answer = (mock_records[qtype] or {})[name] if answer then -- we actually have a mock answer, return it ngx.log(ngx.DEBUG, LOG_PREFIX, "serving '", name, "' from mocks") ngx.timer.at(0.05, function() ngx.log(ngx.INFO, "tick") end) -- FIXME: remove after OpenResty semaphore bug is fixed return answer, nil, tries end -- no mock, so invoke original resolver local a, b, c = old_query(self, name, options, tries) ngx.timer.at(0.05, function() ngx.log(ngx.INFO, "tick") end) -- FIXME: remove after OpenResty semaphore bug is fixed return a, b, c end return resolver
tests(fixtures) use dummy timer to ensure Nginx event loop continues after resolver returns
tests(fixtures) use dummy timer to ensure Nginx event loop continues after resolver returns It is determined that the semaphore module of OpenResty contains a bug that when `:post()` is called right before a timer terminates, the thread waiting on `:wait()` will not be triggered immediately. This is a temporary workaround by @javierguerragiraldez until this bug is fixed inside OpenResty. See: https://gist.github.com/dndx/8539137ddbdc804a31c1b667158c7efe for a minimum reproducible example of this issue.
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
3efd162049d60b68a299d4ac1e09b3965bc04db8
Alpha_Beta_Pruning/Lua/Yonaba/alpha_beta_pruning.lua
Alpha_Beta_Pruning/Lua/Yonaba/alpha_beta_pruning.lua
local function alphabeta(handler, node, depth, alpha, beta, maximize) if depth == 0 then return handler.heuristic(node) end local successors = handler.getNeighbors(node) if maximize then for i, successor in ipairs(successors) do alpha = math.max(alpha, alphabeta(handler, successor, depth - 1, alpha, beta, false)) if beta <= alpha then break end return alpha end else for i, successor in ipairs(successors) do beta = math.min(alpha, alphabeta(handler, successor, depth - 1, alpha, beta, true)) if beta <= alpha then break end return beta end end end function AlphaBeta(node, depth, handler) return alphabeta(handler, node, depth, -math.huge, math.huge, true) end return AlphaBeta
local function alphabeta(tree, node, depth, alpha, beta, maximize) if depth == 0 or tree:isLeaf(node) then return tree:heuristic(node) end local children = tree:children(node) if maximize then for i, child in ipairs(children) do alpha = math.max(alpha, alphabeta(tree, child, depth - 1, alpha, beta, false)) if beta <= alpha then break end end return alpha else for i, child in ipairs(children) do beta = math.min(beta, alphabeta(tree, child, depth - 1, alpha, beta, true)) if beta <= alpha then break end end return beta end end return AlphaBeta(node, tree, depth) return alphabeta(tree, node, depth, -math.huge, math.huge, true) end
Fixed initial implementation
Fixed initial implementation
Lua
mit
sugiartocokrowibowo/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,kennyledet/Algorithm-Implementations,movb/Algorithm-Implementations,Etiene/Algorithm-Implementations,isalnikov/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,imanmafi/Algorithm-Implementations,kidaa/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,kidaa/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,isalnikov/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,imanmafi/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,isalnikov/Algorithm-Implementations,Etiene/Algorithm-Implementations,vikas17a/Algorithm-Implementations,pravsingh/Algorithm-Implementations,girishramnani/Algorithm-Implementations,kidaa/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,Yonaba/Algorithm-Implementations,movb/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,vikas17a/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,warreee/Algorithm-Implementations,girishramnani/Algorithm-Implementations,jiang42/Algorithm-Implementations,Etiene/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,girishramnani/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,Endika/Algorithm-Implementations,kidaa/Algorithm-Implementations,jb1717/Algorithm-Implementations,rohanp/Algorithm-Implementations,isalnikov/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,kennyledet/Algorithm-Implementations,pravsingh/Algorithm-Implementations,jiang42/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,kidaa/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,jb1717/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,movb/Algorithm-Implementations,Endika/Algorithm-Implementations,jb1717/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,kidaa/Algorithm-Implementations,mishin/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,jiang42/Algorithm-Implementations,Yonaba/Algorithm-Implementations,jb1717/Algorithm-Implementations,rohanp/Algorithm-Implementations,jb1717/Algorithm-Implementations,movb/Algorithm-Implementations,isalnikov/Algorithm-Implementations,joshimoo/Algorithm-Implementations,Yonaba/Algorithm-Implementations,kennyledet/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,Yonaba/Algorithm-Implementations,jb1717/Algorithm-Implementations,Etiene/Algorithm-Implementations,rohanp/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,jb1717/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,imanmafi/Algorithm-Implementations,vikas17a/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,kennyledet/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,vikas17a/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,kidaa/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,imanmafi/Algorithm-Implementations,joshimoo/Algorithm-Implementations,Yonaba/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,jb1717/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,Etiene/Algorithm-Implementations,movb/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,Endika/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,movb/Algorithm-Implementations,pravsingh/Algorithm-Implementations,jiang42/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,kennyledet/Algorithm-Implementations,movb/Algorithm-Implementations,Yonaba/Algorithm-Implementations,movb/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,movb/Algorithm-Implementations,mishin/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,kennyledet/Algorithm-Implementations,jb1717/Algorithm-Implementations,mishin/Algorithm-Implementations,imanmafi/Algorithm-Implementations,pravsingh/Algorithm-Implementations,Endika/Algorithm-Implementations,movb/Algorithm-Implementations,pravsingh/Algorithm-Implementations,Etiene/Algorithm-Implementations,warreee/Algorithm-Implementations,Endika/Algorithm-Implementations,vikas17a/Algorithm-Implementations,jiang42/Algorithm-Implementations,Yonaba/Algorithm-Implementations,vikas17a/Algorithm-Implementations,rohanp/Algorithm-Implementations,joshimoo/Algorithm-Implementations,pravsingh/Algorithm-Implementations,imanmafi/Algorithm-Implementations,kennyledet/Algorithm-Implementations,Yonaba/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,vikas17a/Algorithm-Implementations,rohanp/Algorithm-Implementations,Etiene/Algorithm-Implementations,kennyledet/Algorithm-Implementations,girishramnani/Algorithm-Implementations,rohanp/Algorithm-Implementations,warreee/Algorithm-Implementations,Endika/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,isalnikov/Algorithm-Implementations,Yonaba/Algorithm-Implementations,warreee/Algorithm-Implementations,joshimoo/Algorithm-Implementations,imanmafi/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,rohanp/Algorithm-Implementations,vikas17a/Algorithm-Implementations,Yonaba/Algorithm-Implementations,Etiene/Algorithm-Implementations,kidaa/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,kidaa/Algorithm-Implementations,warreee/Algorithm-Implementations,pravsingh/Algorithm-Implementations,Etiene/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,isalnikov/Algorithm-Implementations,kennyledet/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,movb/Algorithm-Implementations,imanmafi/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,isalnikov/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,mishin/Algorithm-Implementations,mishin/Algorithm-Implementations,Endika/Algorithm-Implementations,warreee/Algorithm-Implementations,Etiene/Algorithm-Implementations,joshimoo/Algorithm-Implementations,Etiene/Algorithm-Implementations,Yonaba/Algorithm-Implementations,joshimoo/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,mishin/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,girishramnani/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,girishramnani/Algorithm-Implementations,isalnikov/Algorithm-Implementations,joshimoo/Algorithm-Implementations,vikas17a/Algorithm-Implementations,jb1717/Algorithm-Implementations,joshimoo/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,isalnikov/Algorithm-Implementations,jiang42/Algorithm-Implementations,jb1717/Algorithm-Implementations,Endika/Algorithm-Implementations,movb/Algorithm-Implementations,kidaa/Algorithm-Implementations,imanmafi/Algorithm-Implementations,jb1717/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,kennyledet/Algorithm-Implementations,isalnikov/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,rohanp/Algorithm-Implementations,jb1717/Algorithm-Implementations,movb/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,kidaa/Algorithm-Implementations,Endika/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,mishin/Algorithm-Implementations,jiang42/Algorithm-Implementations,rohanp/Algorithm-Implementations,imanmafi/Algorithm-Implementations,imanmafi/Algorithm-Implementations,Yonaba/Algorithm-Implementations,girishramnani/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,rohanp/Algorithm-Implementations,kennyledet/Algorithm-Implementations,kidaa/Algorithm-Implementations,rohanp/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,warreee/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,imanmafi/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,jiang42/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,Yonaba/Algorithm-Implementations,mishin/Algorithm-Implementations,rohanp/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,pravsingh/Algorithm-Implementations,joshimoo/Algorithm-Implementations,imanmafi/Algorithm-Implementations,mishin/Algorithm-Implementations,warreee/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,Endika/Algorithm-Implementations,joshimoo/Algorithm-Implementations,jiang42/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,warreee/Algorithm-Implementations,Endika/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,vikas17a/Algorithm-Implementations,kennyledet/Algorithm-Implementations,kennyledet/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,Etiene/Algorithm-Implementations,movb/Algorithm-Implementations,Etiene/Algorithm-Implementations,vikas17a/Algorithm-Implementations,rohanp/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,warreee/Algorithm-Implementations,jiang42/Algorithm-Implementations,isalnikov/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,Yonaba/Algorithm-Implementations,warreee/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,jiang42/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,rohanp/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,pravsingh/Algorithm-Implementations,warreee/Algorithm-Implementations,kidaa/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,girishramnani/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,imanmafi/Algorithm-Implementations,isalnikov/Algorithm-Implementations,girishramnani/Algorithm-Implementations,Endika/Algorithm-Implementations,imanmafi/Algorithm-Implementations,pravsingh/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,movb/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,girishramnani/Algorithm-Implementations,warreee/Algorithm-Implementations,Endika/Algorithm-Implementations,joshimoo/Algorithm-Implementations,kennyledet/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,pravsingh/Algorithm-Implementations,warreee/Algorithm-Implementations,pravsingh/Algorithm-Implementations,mishin/Algorithm-Implementations,joshimoo/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,vikas17a/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,pravsingh/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,isalnikov/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,girishramnani/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,jiang42/Algorithm-Implementations,warreee/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,kidaa/Algorithm-Implementations,kennyledet/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,Yonaba/Algorithm-Implementations,jb1717/Algorithm-Implementations,Endika/Algorithm-Implementations,jiang42/Algorithm-Implementations,vikas17a/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,vikas17a/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,jb1717/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,kidaa/Algorithm-Implementations,jiang42/Algorithm-Implementations,mishin/Algorithm-Implementations,mishin/Algorithm-Implementations,Endika/Algorithm-Implementations,girishramnani/Algorithm-Implementations,mishin/Algorithm-Implementations,rohanp/Algorithm-Implementations,warreee/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,jiang42/Algorithm-Implementations,joshimoo/Algorithm-Implementations,pravsingh/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,mishin/Algorithm-Implementations,vikas17a/Algorithm-Implementations,mishin/Algorithm-Implementations,Etiene/Algorithm-Implementations,pravsingh/Algorithm-Implementations,joshimoo/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,isalnikov/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,joshimoo/Algorithm-Implementations,varunparkhe/Algorithm-Implementations
5f227efdb0cd945a4293a2b851aeb10a021212c6
modules/admin-full/luasrc/model/cbi/admin_system/system.lua
modules/admin-full/luasrc/model/cbi/admin_system/system.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2011 Jo-Philipp Wich <[email protected]> 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.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") require("luci.fs") require("luci.config") local m, s, o local has_ntpd = luci.fs.access("/usr/sbin/ntpd") m = Map("system", translate("System"), translate("Here you can configure the basic aspects of your device like its hostname or the timezone.")) m:chain("luci") s = m:section(TypedSection, "system", translate("System Properties")) s.anonymous = true s.addremove = false s:tab("general", translate("General Settings")) s:tab("logging", translate("Logging")) s:tab("language", translate("Language and Style")) -- -- System Properties -- o = s:taboption("general", DummyValue, "_systime", translate("Local Time")) o.template = "admin_system/clock_status" o = s:taboption("general", Value, "hostname", translate("Hostname")) o.datatype = "hostname" function o.write(self, section, value) Value.write(self, section, value) luci.sys.hostname(value) end o = s:taboption("general", ListValue, "zonename", translate("Timezone")) o:value("UTC") for i, zone in ipairs(luci.sys.zoneinfo.TZ) do o:value(zone[1]) end function o.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(luci.sys.zoneinfo.TZ) do if zone[1] == title then return zone[2] end end end AbstractValue.write(self, section, value) local timezone = lookup_zone(value) or "GMT0" self.map.uci:set("system", section, "timezone", timezone) luci.fs.writefile("/etc/TZ", timezone .. "\n") end -- -- Logging -- o = s:taboption("logging", Value, "log_size", translate("System log buffer size"), "kiB") o.optional = true o.placeholder = 16 o.datatype = "uinteger" o = s:taboption("logging", Value, "log_ip", translate("External system log server")) o.optional = true o.placeholder = "0.0.0.0" o.datatype = "ip4addr" o = s:taboption("logging", Value, "log_port", translate("External system log server port")) o.optional = true o.placeholder = 514 o.datatype = "port" o = s:taboption("logging", ListValue, "conloglevel", translate("Log output level")) o:value(8, translate("Debug")) o:value(7, translate("Info")) o:value(6, translate("Notice")) o:value(5, translate("Warning")) o:value(4, translate("Error")) o:value(3, translate("Critical")) o:value(2, translate("Alert")) o:value(1, translate("Emergency")) o = s:taboption("logging", ListValue, "cronloglevel", translate("Cron Log Level")) o.default = 8 o:value(5, translate("Debug")) o:value(8, translate("Normal")) o:value(9, translate("Warning")) -- -- Langauge & Style -- o = s:taboption("language", ListValue, "_lang", translate("Language")) o:value("auto") local i18ndir = luci.i18n.i18ndir .. "base." for k, v in luci.util.kspairs(luci.config.languages) do local file = i18ndir .. k:gsub("_", "-") if k:sub(1, 1) ~= "." and luci.fs.access(file .. ".lmo") then o:value(k, v) end end function o.cfgvalue(...) return m.uci:get("luci", "main", "lang") end function o.write(self, section, value) m.uci:set("luci", "main", "lang", value) end o = s:taboption("language", ListValue, "_mediaurlbase", translate("Design")) for k, v in pairs(luci.config.themes) do if k:sub(1, 1) ~= "." then o:value(v, k) end end function o.cfgvalue(...) return m.uci:get("luci", "main", "mediaurlbase") end function o.write(self, section, value) m.uci:set("luci", "main", "mediaurlbase", value) end -- -- NTP -- if has_ntpd then s = m:section(TypedSection, "timeserver", translate("Time Synchronization")) s.anonymous = true s.addremove = false function m.on_parse() local has_section = false m.uci:foreach("system", "timeserver", function(s) has_section = true return false end) if not has_section then m.uci:section("system", "timeserver", "ntp") end end o = s:option(Flag, "enable", translate("Enable builtin NTP server")) o.rmempty = false function o.cfgvalue(self) return luci.sys.init.enabled("sysntpd") and self.enabled or self.disabled end function o.write(self, section, value) if value == self.enabled then luci.sys.init.enable("sysntpd") luci.sys.call("env -i /etc/init.d/sysntpd start >/dev/null") else luci.sys.call("env -i /etc/init.d/sysntpd stop >/dev/null") luci.sys.init.disable("sysntpd") end end o = s:option(DynamicList, "server", translate("NTP server candidates")) o.datatype = "host" o:depends("enable", "1") -- retain server list even if disabled function o.remove() end end return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2011 Jo-Philipp Wich <[email protected]> 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.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") require("luci.fs") require("luci.config") local m, s, o local has_ntpd = luci.fs.access("/usr/sbin/ntpd") m = Map("system", translate("System"), translate("Here you can configure the basic aspects of your device like its hostname or the timezone.")) m:chain("luci") s = m:section(TypedSection, "system", translate("System Properties")) s.anonymous = true s.addremove = false s:tab("general", translate("General Settings")) s:tab("logging", translate("Logging")) s:tab("language", translate("Language and Style")) -- -- System Properties -- o = s:taboption("general", DummyValue, "_systime", translate("Local Time")) o.template = "admin_system/clock_status" o = s:taboption("general", Value, "hostname", translate("Hostname")) o.datatype = "hostname" function o.write(self, section, value) Value.write(self, section, value) luci.sys.hostname(value) end o = s:taboption("general", ListValue, "zonename", translate("Timezone")) o:value("UTC") for i, zone in ipairs(luci.sys.zoneinfo.TZ) do o:value(zone[1]) end function o.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(luci.sys.zoneinfo.TZ) do if zone[1] == title then return zone[2] end end end AbstractValue.write(self, section, value) local timezone = lookup_zone(value) or "GMT0" self.map.uci:set("system", section, "timezone", timezone) luci.fs.writefile("/etc/TZ", timezone .. "\n") end -- -- Logging -- o = s:taboption("logging", Value, "log_size", translate("System log buffer size"), "kiB") o.optional = true o.placeholder = 16 o.datatype = "uinteger" o = s:taboption("logging", Value, "log_ip", translate("External system log server")) o.optional = true o.placeholder = "0.0.0.0" o.datatype = "ip4addr" o = s:taboption("logging", Value, "log_port", translate("External system log server port")) o.optional = true o.placeholder = 514 o.datatype = "port" o = s:taboption("logging", ListValue, "conloglevel", translate("Log output level")) o:value(8, translate("Debug")) o:value(7, translate("Info")) o:value(6, translate("Notice")) o:value(5, translate("Warning")) o:value(4, translate("Error")) o:value(3, translate("Critical")) o:value(2, translate("Alert")) o:value(1, translate("Emergency")) o = s:taboption("logging", ListValue, "cronloglevel", translate("Cron Log Level")) o.default = 8 o:value(5, translate("Debug")) o:value(8, translate("Normal")) o:value(9, translate("Warning")) -- -- Langauge & Style -- o = s:taboption("language", ListValue, "_lang", translate("Language")) o:value("auto") local i18ndir = luci.i18n.i18ndir .. "base." for k, v in luci.util.kspairs(luci.config.languages) do local file = i18ndir .. k:gsub("_", "-") if k:sub(1, 1) ~= "." and luci.fs.access(file .. ".lmo") then o:value(k, v) end end function o.cfgvalue(...) return m.uci:get("luci", "main", "lang") end function o.write(self, section, value) m.uci:set("luci", "main", "lang", value) end o = s:taboption("language", ListValue, "_mediaurlbase", translate("Design")) for k, v in pairs(luci.config.themes) do if k:sub(1, 1) ~= "." then o:value(v, k) end end function o.cfgvalue(...) return m.uci:get("luci", "main", "mediaurlbase") end function o.write(self, section, value) m.uci:set("luci", "main", "mediaurlbase", value) end -- -- NTP -- if has_ntpd then -- timeserver setup was requested, create section and reload page if m:formvalue("cbid.system._timeserver._enable") then m.uci:section("system", "timeserver", "ntp") m.uci:save("system") luci.http.redirect(luci.dispatcher.build_url("admin/system", arg[1])) return end local has_section = false m.uci:foreach("system", "timeserver", function(s) has_section = true return false end) if not has_section then s = m:section(TypedSection, "timeserver", translate("Time Synchronization")) s.anonymous = true s.cfgsections = function() return { "_timeserver" } end x = s:option(Button, "_enable") x.title = translate("Time Synchronization is not configured yet.") x.inputtitle = translate("Setup Time Synchronization") x.inputstyle = "apply" else s = m:section(TypedSection, "timeserver", translate("Time Synchronization")) s.anonymous = true s.addremove = false o = s:option(Flag, "enable", translate("Enable builtin NTP server")) o.rmempty = false function o.cfgvalue(self) return luci.sys.init.enabled("sysntpd") and self.enabled or self.disabled end function o.write(self, section, value) if value == self.enabled then luci.sys.init.enable("sysntpd") luci.sys.call("env -i /etc/init.d/sysntpd start >/dev/null") else luci.sys.call("env -i /etc/init.d/sysntpd stop >/dev/null") luci.sys.init.disable("sysntpd") end end o = s:option(DynamicList, "server", translate("NTP server candidates")) o.datatype = "host" o:depends("enable", "1") -- retain server list even if disabled function o.remove() end end end return m
admin-full: Better fix for the last change (timeserver setup), add button to add the missing section
admin-full: Better fix for the last change (timeserver setup), add button to add the missing section git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@7915 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
3eb0e48042ad064927afa3fa65a1a1d6c8f9b7d7
kong/plugins/acl/migrations/001_14_to_15.lua
kong/plugins/acl/migrations/001_14_to_15.lua
return { postgres = { up = [[ DO $$ BEGIN ALTER TABLE IF EXISTS ONLY "acls" ADD "cache_key" TEXT UNIQUE; EXCEPTION WHEN DUPLICATE_COLUMN THEN -- Do nothing, accept existing state END; $$; DO $$ BEGIN ALTER TABLE IF EXISTS ONLY "acls" ALTER "created_at" TYPE TIMESTAMP WITH TIME ZONE USING "created_at" AT TIME ZONE 'UTC', ALTER "created_at" SET DEFAULT CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC'; EXCEPTION WHEN UNDEFINED_COLUMN THEN -- Do nothing, accept existing state END$$; DO $$ BEGIN ALTER INDEX IF EXISTS "acls_consumer_id" RENAME TO "acls_consumer_id_idx"; EXCEPTION WHEN DUPLICATE_TABLE THEN -- Do nothing, accept existing state END; $$; DO $$ BEGIN ALTER INDEX IF EXISTS "acls_group" RENAME TO "acls_group_idx"; EXCEPTION WHEN DUPLICATE_TABLE THEN -- Do nothing, accept existing state END; $$; ]], teardown = function(connector, helpers) assert(connector:connect_migrations()) for rows, err in connector:iterate('SELECT * FROM "acls" ORDER BY "created_at";') do if err then return nil, err end for i = 1, #rows do local row = rows[i] local cache_key = string.format("%s:%s:%s:::", "acls", row.consumer_id or "", row.group or "") local sql = string.format([[ UPDATE "acls" SET "cache_key" = '%s' WHERE "id" = '%s'; ]], cache_key, row.id) assert(connector:query(sql)) end end end, }, cassandra = { up = [[ ALTER TABLE acls ADD cache_key text; CREATE INDEX IF NOT EXISTS acls_cache_key_idx ON acls(cache_key); ]], teardown = function(connector, helpers) local cassandra = require "cassandra" local coordinator = assert(connector:connect_migrations()) for rows, err in coordinator:iterate("SELECT * FROM acls") do if err then return nil, err end for i = 1, #rows do local row = rows[i] local cache_key = string.format("%s:%s:%s:::", "acls", row.consumer_id or "", row.group or "") assert(connector:query("UPDATE acls SET cache_key = ? WHERE id = ?", { cache_key, cassandra.uuid(row.id), })) end end end, }, }
return { postgres = { up = [[ DO $$ BEGIN ALTER TABLE IF EXISTS ONLY "acls" ADD "cache_key" TEXT UNIQUE; EXCEPTION WHEN DUPLICATE_COLUMN THEN -- Do nothing, accept existing state END; $$; DO $$ BEGIN ALTER TABLE IF EXISTS ONLY "acls" ALTER "created_at" TYPE TIMESTAMP WITH TIME ZONE USING "created_at" AT TIME ZONE 'UTC', ALTER "created_at" SET DEFAULT CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC'; EXCEPTION WHEN UNDEFINED_COLUMN THEN -- Do nothing, accept existing state END$$; DO $$ BEGIN ALTER INDEX IF EXISTS "acls_consumer_id" RENAME TO "acls_consumer_id_idx"; EXCEPTION WHEN DUPLICATE_TABLE THEN -- Do nothing, accept existing state END; $$; DO $$ BEGIN ALTER INDEX IF EXISTS "acls_group" RENAME TO "acls_group_idx"; EXCEPTION WHEN DUPLICATE_TABLE THEN -- Do nothing, accept existing state END; $$; ]], teardown = function(connector, helpers) assert(connector:connect_migrations()) for row, err in connector:iterate('SELECT * FROM "acls" ORDER BY "created_at";') do if err then return nil, err end local cache_key = string.format("%s:%s:%s:::", "acls", row.consumer_id or "", row.group or "") local sql = string.format([[ UPDATE "acls" SET "cache_key" = '%s' WHERE "id" = '%s'; ]], cache_key, row.id) assert(connector:query(sql)) end end, }, cassandra = { up = [[ ALTER TABLE acls ADD cache_key text; CREATE INDEX IF NOT EXISTS acls_cache_key_idx ON acls(cache_key); ]], teardown = function(connector, helpers) local cassandra = require "cassandra" local coordinator = assert(connector:connect_migrations()) for rows, err in coordinator:iterate("SELECT * FROM acls") do if err then return nil, err end for i = 1, #rows do local row = rows[i] local cache_key = string.format("%s:%s:%s:::", "acls", row.consumer_id or "", row.group or "") assert(connector:query("UPDATE acls SET cache_key = ? WHERE id = ?", { cache_key, cassandra.uuid(row.id), })) end end end, }, }
fix(acl) fix migration of acls on postgres
fix(acl) fix migration of acls on postgres
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
1f91b8fe8f5da833016abe6b204cbc3d8233ba2b
MMOCoreORB/bin/scripts/loot/items/krayt_dragon_scales.lua
MMOCoreORB/bin/scripts/loot/items/krayt_dragon_scales.lua
--Automatically generated by SWGEmu Spawn Tool v0.12 loot editor. krayt_dragon_scales = { minimumLevel = 0, maximumLevel = -1, customObjectName = "", directObjectTemplate = "object/tangible/component/armor/armor_segment_enhancement_krayt.iff", craftingValues = { {"armor_special_type",0,0,0}, {"acideffectiveness",2,8,10}, {"heateffectiveness",2,8,10}, {"energyeffectiveness",2,8,10}, {"kineticeffectiveness",2,8,10}, {"coldeffectiveness",2,8,10}, {"blasteffectiveness",2,8,10}, {"electricaleffectiveness",0,0,0,0}, {"stuneffectiveness",0,0,0,0}, {"armor_health_encumbrance",0,0,0,0}, {"armor_action_encumbrance",0,0,0,0}, {"armor_mind_encumbrance",0,0,0,0}, {"useCount",1,10,0}, }, customizationStringNames = {}, customizationValues = {} } addLootItemTemplate("krayt_dragon_scales", krayt_dragon_scales)
--Automatically generated by SWGEmu Spawn Tool v0.12 loot editor. krayt_dragon_scales = { minimumLevel = 0, maximumLevel = -1, customObjectName = "", directObjectTemplate = "object/tangible/component/armor/armor_segment_enhancement_krayt.iff", craftingValues = { {"armor_special_type",0,0,0}, {"acideffectiveness",2,8,10}, {"heateffectiveness",2,8,10}, {"energyeffectiveness",2,8,10}, {"kineticeffectiveness",2,8,10}, {"coldeffectiveness",2,8,10}, {"blasteffectiveness",2,8,10}, {"useCount",1,10,0}, }, customizationStringNames = {}, customizationValues = {} } addLootItemTemplate("krayt_dragon_scales", krayt_dragon_scales)
(Unstable) [Fixed] Krayt Scales
(Unstable) [Fixed] Krayt Scales git-svn-id: e4cf3396f21da4a5d638eecf7e3b4dd52b27f938@5123 c3d1530f-68f5-4bd0-87dc-8ef779617e40
Lua
agpl-3.0
lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo
4d7950ff490cf0ab9eb688f8640d764b2ffdf90f
bot.lua
bot.lua
Class = require("hump.class") require("entity") require("bullet") Polygon = require("HC.polygon") require("mixins.collidable") require("mixins.health") local lg = love.graphics local lk = love.keyboard local font_14 = love.graphics.newFont("assets/fonts/Hack-Regular.ttf", 14) local font_16 = love.graphics.newFont("assets/fonts/Hack-Regular.ttf", 16) local AngCor = -90 Bot = Class{ name = "Bot"; __includes = {Entity, Health, Collidable, shapes.ConvexPolygonShape}; init = function (self, x, y, ang, r, g, b, a) Entity.init(self) Health.init(self, 100) self.m_x = x self.m_y = y self.m_ang_deg = ang self.m_ang_rad = self.m_ang_deg * math.pi / 180 self.m_turnAngSlow = 3 self.m_turnAngFast = 7 self.m_dragCoef = 0.97 self.m_r = r self.m_g = g self.m_b = b self.m_a = a self.m_xVel = 0 self.m_yVel = 0 self.m_maxVel = 5 self.m_maxAccel = 5 self.m_size = 32; --self.m_scale = 0.25 self.m_scale = 0.25 self.m_mainThrusterForce_US = 1 self.m_strafeThrusterForce_US = 0.5 self.m_reverseThrusterForce_US = 0.25 self.m_mainThrusterForce = self.m_mainThrusterForce_US * self.m_scale self.m_strafeThrusterForce = self.m_strafeThrusterForce_US * self.m_scale self.m_reverseThrusterForce = self.m_strafeThrusterForce_US * self.m_scale --self.m_geom = {32,0, 64,64, 0,64, 32,0} -- Making bot smaller, 64 is a bit to big --self.m_geom = {32/2,0, 64/2,64/2, 0,64/2, 32/2,0} --self.m_geom = {0,-16, 16,16, -16,16, 0,-16} shapes.ConvexPolygonShape.init(self, Polygon(-self.m_size*self.m_scale, self.m_size*self.m_scale,self.m_size*self.m_scale, -self.m_size*self.m_scale,self.m_size*self.m_scale, 0,-self.m_size*self.m_scale)) HC.register(self) self.ammo = { Bullet(self.m_x, self.m_y, self.m_ang_deg, 255, 50, 50, 255) } self.clipSize = 10; end; updatePosition = function (self, dt) self.m_xVel = self.m_xVel * self.m_dragCoef self.m_yVel = self.m_yVel * self.m_dragCoef self.m_x = self.m_x + self.m_xVel self.m_y = self.m_y + self.m_yVel if self.m_x > 1280 then self.m_x = 1 elseif self.m_x < 0 then self.m_x = 1279 end if self.m_y > 720 then self.m_y = 1 elseif self.m_y < 0 then self.m_y = 719 end self:moveTo(self.m_x, self.m_y) self:setRotation(self.m_ang_rad) end; applyMainThruster = function (self) --self.m_XVel = 1 * math.cos(self.m_ang_rad) --self.m_yVel = 1* math.sin(self.m_ang_rad) --if self.m_xVel < self.m_maxVel then -- if self.m_yVel < self.m_maxVel then self.m_xVel = self.m_xVel + self.m_mainThrusterForce * math.cos((AngCor+self.m_ang_deg) * math.pi / 180) self.m_yVel = self.m_yVel + self.m_mainThrusterForce * math.sin((AngCor+self.m_ang_deg) * math.pi / 180) -- end --end end; applyReverseThruster = function (self) --self.m_XVel = 1 * math.cos(self.m_ang_rad) --self.m_yVel = 1* math.sin(self.m_ang_rad) self.m_xVel = self.m_xVel + self.m_reverseThrusterForce * math.cos((AngCor+self.m_ang_deg+180) * math.pi / 180) self.m_yVel = self.m_yVel + self.m_reverseThrusterForce * math.sin((AngCor+self.m_ang_deg+180) * math.pi / 180) end; applyStrafeLeftThruster = function (self) self.m_xVel = self.m_xVel + self.m_strafeThrusterForce * math.cos((AngCor+self.m_ang_deg-90) * math.pi / 180) self.m_yVel = self.m_yVel + self.m_strafeThrusterForce * math.sin((AngCor+self.m_ang_deg-90) * math.pi / 180) end; applyStrafeRightThruster = function (self) self.m_xVel = self.m_xVel + self.m_strafeThrusterForce * math.cos((AngCor+self.m_ang_deg+90) * math.pi / 180) self.m_yVel = self.m_yVel + self.m_strafeThrusterForce * math.sin((AngCor+self.m_ang_deg+90) * math.pi / 180) end; turnLeftSlow = function (self) self.m_ang_deg = self.m_ang_deg - self.m_turnAngSlow self.m_ang_rad = self.m_ang_deg * math.pi / 180 end; turnRightSlow = function (self) self.m_ang_deg = self.m_ang_deg + self.m_turnAngSlow self.m_ang_rad = self.m_ang_deg * math.pi / 180 end; turnLeftFast = function (self) self.m_ang_deg = self.m_ang_deg - self.m_turnAngFast self.m_ang_rad = self.m_ang_deg * math.pi / 180 end; turnRightFast = function (self) self.m_ang_deg = self.m_ang_deg + self.m_turnAngFast self.m_ang_rad = self.m_ang_deg * math.pi / 180 end; update = function (self, dt) self:updatePosition(dt) end; fire = function (self) Bullet(self.m_x, self.m_y, self.m_ang_deg, 255, 50, 50, 255) end; draw = function (self, dt) -- Attemppting to draw to framebuffer for shell. Its not called framebuffer -- anymore, but rather "canvas" -- Changing framebuffers. This means any drawing commands will be drawing on the fb, duh. ;git add - --lg.setCanvas(self.m_fb) --lg.clear( ) lg.push() lg.setColor(self.m_r, self.m_g, self.m_b, self.m_a) --lg.translate( self.m_x, self.m_y ) --lg.rotate( self.m_ang_rad ) love.graphics.polygon('line', self._polygon:unpack()) lg.pop() end; keyPressed = function (self, key, scancode, isrepeat ) end; } Bot.collision_handler["Bullet"] = function(self, other, sep_v, dt) self.take_damage(other.damage) end Bot.collision_handler["*"] = function(self, other, sep_v, dt) print("collided with " .. tostring(other)) end
Class = require("hump.class") require("entity") require("bullet") Polygon = require("HC.polygon") require("mixins.collidable") require("mixins.health") local lg = love.graphics local lk = love.keyboard local font_14 = love.graphics.newFont("assets/fonts/Hack-Regular.ttf", 14) local font_16 = love.graphics.newFont("assets/fonts/Hack-Regular.ttf", 16) local AngCor = -90 Bot = Class{ name = "Bot"; __includes = {Entity, Health, Collidable, shapes.ConvexPolygonShape}; init = function (self, x, y, ang, r, g, b, a) Entity.init(self) Health.init(self, 100) self.m_x = x self.m_y = y self.m_ang_deg = ang self.m_ang_rad = self.m_ang_deg * math.pi / 180 self.m_turnAngSlow = 3 self.m_turnAngFast = 7 self.m_dragCoef = 0.97 self.m_r = r self.m_g = g self.m_b = b self.m_a = a self.m_xVel = 0 self.m_yVel = 0 self.m_maxVel = 5 self.m_maxAccel = 5 self.m_size = 32; self.m_scale = 0.25 self.m_mainThrusterForce_US = 1 self.m_strafeThrusterForce_US = 0.5 self.m_reverseThrusterForce_US = 0.25 self.m_mainThrusterForce = self.m_mainThrusterForce_US * self.m_scale self.m_strafeThrusterForce = self.m_strafeThrusterForce_US * self.m_scale self.m_reverseThrusterForce = self.m_strafeThrusterForce_US * self.m_scale shapes.ConvexPolygonShape.init(self, Polygon(self.m_size*self.m_scale, self.m_size*self.m_scale,0,-self.m_size*self.m_scale, -self.m_size*self.m_scale, self.m_size*self.m_scale)) HC.register(self) self.ammo = { Bullet(self.m_x, self.m_y, self.m_ang_deg, 255, 50, 50, 255) } self.clipSize = 10; end; updatePosition = function (self, dt) self.m_xVel = self.m_xVel * self.m_dragCoef self.m_yVel = self.m_yVel * self.m_dragCoef self.m_x = self.m_x + self.m_xVel self.m_y = self.m_y + self.m_yVel if self.m_x > 1280 then self.m_x = 1 elseif self.m_x < 0 then self.m_x = 1279 end if self.m_y > 720 then self.m_y = 1 elseif self.m_y < 0 then self.m_y = 719 end self:moveTo(self.m_x, self.m_y) self:setRotation(self.m_ang_rad) end; applyMainThruster = function (self) self.m_xVel = self.m_xVel + self.m_mainThrusterForce * math.cos((AngCor+self.m_ang_deg) * math.pi / 180) self.m_yVel = self.m_yVel + self.m_mainThrusterForce * math.sin((AngCor+self.m_ang_deg) * math.pi / 180) end; applyReverseThruster = function (self) self.m_xVel = self.m_xVel + self.m_reverseThrusterForce * math.cos((AngCor+self.m_ang_deg+180) * math.pi / 180) self.m_yVel = self.m_yVel + self.m_reverseThrusterForce * math.sin((AngCor+self.m_ang_deg+180) * math.pi / 180) end; applyStrafeLeftThruster = function (self) self.m_xVel = self.m_xVel + self.m_strafeThrusterForce * math.cos((AngCor+self.m_ang_deg-90) * math.pi / 180) self.m_yVel = self.m_yVel + self.m_strafeThrusterForce * math.sin((AngCor+self.m_ang_deg-90) * math.pi / 180) end; applyStrafeRightThruster = function (self) self.m_xVel = self.m_xVel + self.m_strafeThrusterForce * math.cos((AngCor+self.m_ang_deg+90) * math.pi / 180) self.m_yVel = self.m_yVel + self.m_strafeThrusterForce * math.sin((AngCor+self.m_ang_deg+90) * math.pi / 180) end; turnLeftSlow = function (self) self.m_ang_deg = self.m_ang_deg - self.m_turnAngSlow self.m_ang_rad = self.m_ang_deg * math.pi / 180 end; turnRightSlow = function (self) self.m_ang_deg = self.m_ang_deg + self.m_turnAngSlow self.m_ang_rad = self.m_ang_deg * math.pi / 180 end; turnLeftFast = function (self) self.m_ang_deg = self.m_ang_deg - self.m_turnAngFast self.m_ang_rad = self.m_ang_deg * math.pi / 180 end; turnRightFast = function (self) self.m_ang_deg = self.m_ang_deg + self.m_turnAngFast self.m_ang_rad = self.m_ang_deg * math.pi / 180 end; update = function (self, dt) self:updatePosition(dt) end; fire = function (self) Bullet(self.m_x, self.m_y, self.m_ang_deg, 255, 50, 50, 255) end; draw = function (self, dt) lg.push() lg.setColor(self.m_r, self.m_g, self.m_b, self.m_a) love.graphics.polygon('line', self._polygon:unpack()) lg.pop() end; keyPressed = function (self, key, scancode, isrepeat ) end; } Bot.collision_handler["Bullet"] = function(self, other, sep_v, dt) self.take_damage(other.damage) end Bot.collision_handler["*"] = function(self, other, sep_v, dt) print("collided with " .. tostring(other)) end
Fixed bot polygon
Fixed bot polygon
Lua
mit
aswyk/botrot
a303db78405b7a186c41acfadb1f7d29a0c37553
redir_scripts/preload/default/00_default.lua
redir_scripts/preload/default/00_default.lua
-- Copyright (C) 2006,2007 Lauri Leukkunen <[email protected]> -- Licensed under so called MIT license. default_bin = { func_name = ".*", path = "^/bin", map_to = nil } default_usrbin = { func_name = ".*", path = "^/usr/bin", map_to = nil } default_usrlocalbin = { func_name = ".*", path = "^/usr/local/bin", map_to = nil } default_sbin = { func_name = ".*", path = "^/sbin", map_to = nil } default_usrsbin = { func_name = ".*", path = "^/usr/sbin", map_to = nil } default_home = { func_name = ".*", path = "^/home", map_to = nil } default_proc = { func_name = ".*", path = "^/proc", map_to = nil } default_tmp = { func_name = ".*", path = "^/tmp", map_to = nil } default_etc = { func_name = ".*", path = "^/etc", map_to = nil } default_scratchbox = { func_name = ".*", path = "^/scratchbox", map_to = nil } default_dev = { func_name = ".*", path = "^/dev", map_to = nil } default_opt = { func_name = ".*", path = "^/opt", map_to = nil } autoconf = { func_name = ".*", path = "^/usr/share/autoconf.*", map_to = nil } autoconf_misc = { func_name = ".*", path = "^/usr/share/misc/config.*", map_to = nil } automake = { func_name = ".*", path = "^/usr/share/automake.*", map_to = nil } aclocal = { func_name = ".*", path = "^/usr/share/aclocal.*", map_to = nil } intltool = { func_name = ".*", path = "^/usr/share/intltool.*", map_to = nil } hostgcc = { func_name = ".*", path = "^/host_usr", map_to = "=" } -- pkgconfig pkgconfig = { func_name = ".*", path = "^/usr/lib/pkgconfig.*", map_to = "=" } -- don't map anything else from TARGETDIR targetdir = { func_name = ".*", path = "^" .. target_root .. ".*", map_to = nil } -- don't map "/" path actual_root = { func_name = ".*", path = "^/$", map_to = nil } -- catch all rule to map everything else to TARGETDIR/ default_rootdir = { func_name = ".*", path = "^/", map_to = "=" } -- the actual chain, this is not actually exported -- it's only defined in this file which gets loaded -- first by main.lua so that default_chain is available -- for the actual entry chains defined in the other -- lua files default_chain = { next_chain = nil, noentry = 1, -- never use this chain directly to start mapping binary = nil, rules = { autoconf, autoconf_misc, automake, aclocal, intltool, default_bin, default_usrbin, default_usrlocalbin, default_sbin, default_usrsbin, default_scratchbox, default_dev, default_opt, default_home, default_proc, default_tmp, default_etc, hostgcc, pkgconfig, targetdir, actual_root, default_rootdir } } export_chains = { default_chain }
-- Copyright (C) 2006,2007 Lauri Leukkunen <[email protected]> -- Licensed under so called MIT license. default_bin = { func_name = ".*", path = "^/bin", map_to = nil } default_usrbin = { func_name = ".*", path = "^/usr/bin", map_to = nil } default_usrlocalbin = { func_name = ".*", path = "^/usr/local/bin", map_to = nil } default_sbin = { func_name = ".*", path = "^/sbin", map_to = nil } default_usrsbin = { func_name = ".*", path = "^/usr/sbin", map_to = nil } default_home = { func_name = ".*", path = "^/home", map_to = nil } default_proc = { func_name = ".*", path = "^/proc", map_to = nil } default_tmp = { func_name = ".*", path = "^/tmp", map_to = nil } default_etc = { func_name = ".*", path = "^/etc", map_to = nil } default_scratchbox = { func_name = ".*", path = "^/scratchbox", map_to = nil } default_dev = { func_name = ".*", path = "^/dev", map_to = nil } default_opt = { func_name = ".*", path = "^/opt", map_to = nil } autoconf = { func_name = ".*", path = "^/usr/share/autoconf.*", map_to = nil } autoconf_misc = { func_name = ".*", path = "^/usr/share/misc/config.*", map_to = nil } automake = { func_name = ".*", path = "^/usr/share/automake.*", map_to = nil } aclocal = { func_name = ".*", path = "^/usr/share/aclocal.*", map_to = nil } intltool = { func_name = ".*", path = "^/usr/share/intltool.*", map_to = nil } debhelper = { func_name = ".*", path = "^/usr/share/debhelper.*", map_to = nil } hostgcc = { func_name = ".*", path = "^/host_usr", map_to = "=" } -- pkgconfig pkgconfig = { func_name = ".*", path = "^/usr/lib/pkgconfig.*", map_to = "=" } -- don't map anything else from TARGETDIR targetdir = { func_name = ".*", path = "^" .. target_root .. ".*", map_to = nil } -- don't map "/" path actual_root = { func_name = ".*", path = "^/$", map_to = nil } -- catch all rule to map everything else to TARGETDIR/ default_rootdir = { func_name = ".*", path = "^/", map_to = "=" } -- the actual chain, this is not actually exported -- it's only defined in this file which gets loaded -- first by main.lua so that default_chain is available -- for the actual entry chains defined in the other -- lua files default_chain = { next_chain = nil, noentry = 1, -- never use this chain directly to start mapping binary = nil, rules = { autoconf, autoconf_misc, automake, aclocal, intltool, debhelper, default_bin, default_usrbin, default_usrlocalbin, default_sbin, default_usrsbin, default_scratchbox, default_dev, default_opt, default_home, default_proc, default_tmp, default_etc, hostgcc, pkgconfig, targetdir, actual_root, default_rootdir } } export_chains = { default_chain }
Fix debhelper mappings
Fix debhelper mappings Signed-off-by: Lauri Leukkunen <[email protected]>
Lua
lgpl-2.1
neeraj9/sbox2,OlegGirko/ldbox,loganchien/scratchbox2,h113331pp/scratchbox2,h113331pp/scratchbox2,neeraj9/sbox2,lbt/scratchbox2,madscientist42/scratchbox2,ldbox/ldbox,neeraj9/sbox2,ldbox/ldbox,OlegGirko/ldbox,h113331pp/scratchbox2,loganchien/scratchbox2,h113331pp/scratchbox2,OlegGirko/ldbox,h113331pp/scratchbox2,lbt/scratchbox2,neeraj9/sbox2,freedesktop-unofficial-mirror/sbox2,lbt/scratchbox2,BinChengfei/scratchbox2,BinChengfei/scratchbox2,BinChengfei/scratchbox2,freedesktop-unofficial-mirror/sbox2,neeraj9/sbox2,freedesktop-unofficial-mirror/sbox2,OlegGirko/ldbox,ldbox/ldbox,ldbox/ldbox,loganchien/scratchbox2,OlegGirko/ldbox,loganchien/scratchbox2,madscientist42/scratchbox2,madscientist42/scratchbox2,lbt/scratchbox2,BinChengfei/scratchbox2,loganchien/scratchbox2,BinChengfei/scratchbox2,madscientist42/scratchbox2,freedesktop-unofficial-mirror/sbox2,lbt/scratchbox2,OlegGirko/ldbox,loganchien/scratchbox2,freedesktop-unofficial-mirror/sbox2,neeraj9/sbox2,ldbox/ldbox,h113331pp/scratchbox2,madscientist42/scratchbox2,madscientist42/scratchbox2,freedesktop-unofficial-mirror/sbox2,ldbox/ldbox,BinChengfei/scratchbox2
792a36d5b60faf3922641f742a7898d15f405a36
mod_compat_vcard/mod_compat_vcard.lua
mod_compat_vcard/mod_compat_vcard.lua
-- Compatibility with clients and servers (i.e. ejabberd) that send vcard -- requests to the full JID -- -- https://support.process-one.net/browse/EJAB-1045 local jid_bare = require "util.jid".bare; local st = require "util.stanza"; local core_process_stanza = prosody.core_process_stanza; module:hook("iq/full", function(event) local stanza = event.stanza; local payload = stanza.tags[1]; if payload.name == "vCard" and stanza.attr.type == "get" and payload.attr.xmlns == "vcard-temp" then local fixed_stanza = st.clone(event.stanza); fixed_stanza.attr.to = jid_bare(stanza.attr.to); core_process_stanza(event.origin, fixed_stanza); return true; end end, 1);
-- Compatibility with clients and servers (i.e. ejabberd) that send vcard -- requests to the full JID -- -- https://support.process-one.net/browse/EJAB-1045 local jid_bare = require "util.jid".bare; local st = require "util.stanza"; local core_process_stanza = prosody.core_process_stanza; module:hook("iq/full", function(event) local stanza = event.stanza; local payload = stanza.tags[1]; if payload and stanza.attr.type == "get" and payload.name == "vCard" and payload.attr.xmlns == "vcard-temp" then local fixed_stanza = st.clone(event.stanza); fixed_stanza.attr.to = jid_bare(stanza.attr.to); core_process_stanza(event.origin, fixed_stanza); return true; end end, 1);
mod_compat_vcard: Fix traceback from probably empty stanzas (Thanks Biszkopcik)
mod_compat_vcard: Fix traceback from probably empty stanzas (Thanks Biszkopcik)
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
2a23b24d2d756c441827fd36cd6a869dc1dc5906
modules/admin-full/luasrc/model/cbi/admin_network/routes.lua
modules/admin-full/luasrc/model/cbi/admin_network/routes.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> 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.tools.webadmin") m = Map("network", translate("Routes"), translate("a_n_routes1")) local routes6 = luci.sys.net.routes6() local bit = require "bit" s = m:section(TypedSection, "route", translate("Static IPv4 Routes")) s.addremove = true s.anonymous = true s.template = "cbi/tblsection" iface = s:option(ListValue, "interface", translate("Interface")) luci.tools.webadmin.cbi_add_networks(iface) s:option(Value, "target", translate("Target"), translate("Host-<abbr title=\"Internet Protocol Address\">IP</abbr> or Network")) s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"), translate("if target is a network")).rmemepty = true s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Gateway")) if routes6 then s = m:section(TypedSection, "route6", translate("Static IPv6 Routes")) s.addremove = true s.anonymous = true s.template = "cbi/tblsection" iface = s:option(ListValue, "interface", translate("Interface")) luci.tools.webadmin.cbi_add_networks(iface) s:option(Value, "target", translate("Target"), translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Address or Network (CIDR)")) s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Gateway")).rmempty = true end return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> 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.tools.webadmin") m = Map("network", translate("Routes"), translate("Routes specify over which interface and gateway a certain host or network " .. "can be reached.")) local routes6 = luci.sys.net.routes6() local bit = require "bit" s = m:section(TypedSection, "route", translate("Static IPv4 Routes")) s.addremove = true s.anonymous = true s.template = "cbi/tblsection" iface = s:option(ListValue, "interface", translate("Interface")) luci.tools.webadmin.cbi_add_networks(iface) s:option(Value, "target", translate("Target"), translate("Host-<abbr title=\"Internet Protocol Address\">IP</abbr> or Network")) s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"), translate("if target is a network")).rmemepty = true s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Gateway")) if routes6 then s = m:section(TypedSection, "route6", translate("Static IPv6 Routes")) s.addremove = true s.anonymous = true s.template = "cbi/tblsection" iface = s:option(ListValue, "interface", translate("Interface")) luci.tools.webadmin.cbi_add_networks(iface) s:option(Value, "target", translate("Target"), translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Address or Network (CIDR)")) s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Gateway")).rmempty = true end return m
modules/admin-full: fix static routes page
modules/admin-full: fix static routes page git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5467 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
ed0356d6d920229467797729a5b21b390b310c11
src_trunk/resources/realism-system/water.lua
src_trunk/resources/realism-system/water.lua
-- waves function setInitialWaves(res) if (res==getThisResource()) then local hour, mins = getTime() createSewerFlood() if (hour%2==0) then -- even hour setWaveHeight(1) else setWaveHeight(0) end end end addEventHandler("onClientResourceStart", getRootElement(), setInitialWaves) function updateWaves() local hour, mins = getTime() if (hour%2==0) then -- even hour setWaveHeight(1) else setWaveHeight(0) end end addEvent("updateWaves", false) addEventHandler("updateWaves", getRootElement(), updateWaves) function createSewerFlood() -- Dams createObject(16339, 1573.72265625, -1751.748046875, 1.3512325286865, 0, 0, 180) createObject(16339, 1524.205078125, -1740.673828125, 1.3512325286865, 0, 0, 0) createObject(16339, 2017.158203125, -1906.9755859375, 1.3512325286865, 0, 0, 315) createObject(16339, 2127.3828125, -2015.9189453125, 1.3512325286865, 0, 0, 135) createObject(16339, 2581.9560546875, -2110.491210937, 0, 0, 0, 270) -- Water #1 local x1, y1, z1 = 1349, -1725, 12 -- SW local x2, y2, z2 = 1382, -1726, 12 -- SE local x3, y3, z3 = 1405, -1300, 12 -- NW local x4, y4, z4 = 1420, -1300, 12 -- NE local water = createWater(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) -- Water #2 local x1, y1, z1 = 1377.1025390625, -1722.6787109375, 12 -- SW local x2, y2, z2 = 1425.798828125, -1721.890625, 12 -- SE local x3, y3, z3 = 1381.0849609375, -1706.6318359375, 12 -- NW local x4, y4, z4 = 1426.0390625, -1710.375, 12 -- NE local water = createWater(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) -- Water #3 local x1, y1, z1 = 1357.7431640625, -1868.1962890625, 8 -- SW local x2, y2, z2 = 1527.5556640625, -1873.0205078125, 8 -- SE local x3, y3, z3 = 1349.453125, -1701.9990234375, 8 -- NW local x4, y4, z4 = 1527.1181640625, -1709.41015625, 8 -- NE local water = createWater(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) -- Water #4 local x1, y1, z1 = 1574.828125, -1877.42578125, 8 -- SW local x2, y2, z2 = 2534.6591796875, -1917.185546875, 8 -- SE local x3, y3, z3 = 1576.982421875, -1729.087890625, 8 -- NW local x4, y4, z4 = 2537.37890625, -1775.4609375, 8 -- NE local water = createWater(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) -- Water #5 local x1, y1, z1 = 2527.25, -2207.4765625, 8 -- SW local x2, y2, z2 = 2628.8037109375, -2207.7392578125, 8 -- SE local x3, y3, z3 = 2523.50390625, -1468.19140625, 8 -- NW local x4, y4, z4 = 2623.529296875, -1452.0751953125, 8 -- NE local water = createWater(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) -- Water #6 local x1, y1, z1 = 1613.341796875, -1750.46289062, 8 -- SW local x2, y2, z2 = 1630.85546875, -1750.1044921875, 8 -- SE local x3, y3, z3 = 1609.0078125, -1670.2392578125, 8 -- NW local x4, y4, z4 = 1628.3701171875, -1672.7763671875, 8 -- NE local water = createWater(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) -- Water #7 local x1, y1, z1 = 1966.9541015625, -1942.3779296875, 8 -- SW local x2, y2, z2 = 2076.99609375, -1927.4052734375, 8 -- SE local x3, y3, z3 = 1960.7197265625, -1872.1435546875, 8 -- NW local x4, y4, z4 = 2075.8251953125, -1866.0732421875, 8 -- NE local water = createWater(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) outputDebugString(tostring(water)) end
-- waves function setInitialWaves(res) if (res==getThisResource()) then local hour, mins = getTime() createSewerFlood() if (hour%2==0) then -- even hour setWaveHeight(1) else setWaveHeight(0) end end end addEventHandler("onClientResourceStart", getRootElement(), setInitialWaves) function updateWaves() local hour, mins = getTime() if (hour%2==0) then -- even hour setWaveHeight(1) else setWaveHeight(0) end end addEvent("updateWaves", false) addEventHandler("updateWaves", getRootElement(), updateWaves) function createSewerFlood() -- Dams createObject(16339, 1579.72265625, -1751.748046875, 1.3512325286865, 0, 0, 180) createObject(16339, 1410.2568359375, -1714.7568359375, 1.3512325286865, 0, 0, 355) createObject(16339, 2017.158203125, -1906.9755859375, 1.3512325286865, 0, 0, 315) createObject(16339, 2127.3828125, -2015.9189453125, 1.3512325286865, 0, 0, 135) createObject(16339, 2581.9560546875, -2110.491210937, 0, 0, 0, 270) createObject(16339, 2581.673828125, -2120.3525390625, 0, 0, 0, 90) -- Water #1 local x1, y1, z1 = 1329.0009765625, -1733.38671875, 11.8 -- SW local x2, y2, z2 = 1466.4970703125, -1729.9609375, 11.8 -- SE local x3, y3, z3 = 1403.7509765625, -1298.647460937, 11.8 -- NW local x4, y4, z4 = 1420.6875, -1296.216796875, 11.8 -- NE local water = createWater(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) -- Water #2 local x1, y1, z1 = 1349, -1725, 11.8 -- SW local x2, y2, z2 = 1382, -1726, 11.8-- SE local x3, y3, z3 = 1405, -1300, 11.8 -- NW local x4, y4, z4 = 1420, -1300, 11.8 -- NE local water = createWater(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) -- Water #3 local x1, y1, z1 = 1377.1025390625, -1722.6787109375, 11.8 -- SW local x2, y2, z2 = 1425.798828125, -1721.890625, 11.8 -- SE local x3, y3, z3 = 1381.0849609375, -1706.6318359375, 11.8 -- NW local x4, y4, z4 = 1426.0390625, -1710.375, 11.8 -- NE local water = createWater(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) -- Water #4 local x1, y1, z1 = 1357.7431640625, -1868.1962890625, 7 -- SW local x2, y2, z2 = 1527.5556640625, -1873.0205078125, 7 -- SE local x3, y3, z3 = 1349.453125, -1701.9990234375, 7 -- NW local x4, y4, z4 = 1527.1181640625, -1709.41015625, 7 -- NE local water = createWater(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) -- Water #5 local x1, y1, z1 = 1574.828125, -1877.42578125, 7 -- SW local x2, y2, z2 = 2534.6591796875, -1917.185546875, 7 -- SE local x3, y3, z3 = 1576.982421875, -1729.087890625, 7 -- NW local x4, y4, z4 = 2537.37890625, -1775.4609375, 7 -- NE local water = createWater(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) -- Water #6 local x1, y1, z1 = 2527.25, -2115.4765625, 7 -- SW local x2, y2, z2 = 2628.8037109375, -2207.7392578125, 7 -- SE local x3, y3, z3 = 2523.50390625, -1468.19140625, 7 -- NW local x4, y4, z4 = 2623.529296875, -1452.0751953125, 7 -- NE local water = createWater(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) -- Water #7 local x1, y1, z1 = 1613.341796875, -1750.46289062, 7 -- SW local x2, y2, z2 = 1630.85546875, -1750.1044921875, 7 -- SE local x3, y3, z3 = 1609.0078125, -1670.2392578125, 7 -- NW local x4, y4, z4 = 1628.3701171875, -1672.7763671875, 7 -- NE local water = createWater(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) -- Water #8 local x1, y1, z1 = 1966.9541015625, -1942.3779296875, 7 -- SW local x2, y2, z2 = 2076.99609375, -1927.4052734375, 7 -- SE local x3, y3, z3 = 1960.7197265625, -1872.1435546875, 7 -- NW local x4, y4, z4 = 2075.8251953125, -1866.0732421875, 7 -- NE local water = createWater(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) end
Many water fixes
Many water fixes git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@937 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
efcb9b7aa97a0dbfec4cb78762c1bbe7b196768a
Code/Tools/BuildScripts/publish.lua
Code/Tools/BuildScripts/publish.lua
------------------------------------------------------------------------------ -- Copyright (C) 2008-2012, Shane Liesegang -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the copyright holder nor the names of any -- contributors may be used to endorse or promote products derived from -- this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ if (package.path == nil) then package.path = "" end local mydir = debug.getinfo(1,"S").source:match[[^@?(.*[\/])[^\/]-$]] if (mydir == nil) then mydir = "." end package.path = mydir .. "?.lua;" .. package.path package.path = package.path .. ";" .. mydir .. "lua-lib/penlight-0.8/lua/?/init.lua" package.path = package.path .. ";" .. mydir .. "lua-lib/penlight-0.8/lua/?.lua" require "angel_build" require "lfs" require "pl.path" require "pl.lapp" local args = pl.lapp [[ Packages a game for easy distribution. -i,--input_directory (string) Project directory -o,--output_directory (string) Where the packaged game should go -v,--vcpath (string) Where Visual Studio is installed -g,--gamename (default ClientGame.exe) Name of the final game ]] lfs.chdir(args.input_directory) local config = {} if (pl.path.exists("build.lua")) then loadFileIn("build.lua", config) end if (config.game_info == nil) then config.game_info = {} end if (config.game_info.name == nil) then config.game_info.name = pl.path.splitext(args.gamename) end local bits_path = pl.path.join(args.output_directory, "bits") if (not pl.path.exists(bits_path)) then makedirs(bits_path) end conf_path = fulljoin(args.input_directory, "..", "Angel", "AngelConfig.h") t = io.open(conf_path, "r") tr = t:read("*all") t:close() disable_fmod = tonumber(tr:match("\n%s*#define%s+ANGEL_DISABLE_FMOD%s+([0-9]+)")) disable_devil = tonumber(tr:match("\n%s*#define%s+ANGEL_DISABLE_DEVIL%s+([0-9]+)")) local files_ex = {} local files_base = {"GameInfo.txt", "Attributions.txt"} local directories = {"Resources", "Config", "Logs"} if (disable_fmod == 1) then table.insert(files_ex, "OpenAL32.dll") else table.insert(files_ex, "fmodex.dll") end if (disable_devil ~= 1) then table.insert(files_ex, "DevIL.dll") table.insert(files_ex, "ILU.dll") table.insert(files_ex, "ILUT.dll") end for _, file_ex in pairs(files_ex) do copyfile(pl.path.join(args.input_directory, file_ex), pl.path.join(bits_path, file_ex)) end for _, file_base in pairs(files_base) do copyfile(fulljoin(args.input_directory, "Documentation", file_base), pl.path.join(args.output_directory, file_base)) end for _, directory in pairs(directories) do recursive_copy(pl.path.join(args.input_directory, directory), pl.path.join(bits_path, directory)) end att_path = fulljoin(args.input_directory, "..", "Tools", "BuildScripts", "Attributions") correct_attributions(pl.path.join(args.output_directory, "Attributions.txt"), att_path, disable_devil, disable_fmod) copyfile(fulljoin(args.input_directory, "Release", args.gamename), pl.path.join(bits_path, config.game_info.name .. ".exe")) local kicker_exe = fulljoin(args.output_directory, config.game_info.name .. ".exe") local kicker_dir = fulljoin(args.input_directory, "..", "Angel", "Win", "WindowsAngelKicker") local kicker_source_fname = "WindowsAngelKicker.cpp" local kicker_config = "Release" local kicker_built = fulljoin(kicker_dir, kicker_config, "WindowsAngelKicker.exe") local rebuild_needed = false if (pl.path.exists(kicker_exe) ~= true) then rebuild_needed = true end local kicker_files = {"angel.ico", "angel_small.ico"} for _, kicker_file in pairs(kicker_files) do local src = fulljoin(args.input_directory, "platforms", "win", kicker_file) local dst = fulljoin(kicker_dir, kicker_file) if ( (pl.path.exists(dst) ~= true) or (lfs.attributes(dst, "modification") < lfs.attributes(src, "modification") ) ) then rebuild_needed = true copyfile(src, dst) end end lfs.chdir(kicker_dir) if (pl.path.exists(kicker_source_fname) ~= true) then rebuild_needed = true copyfile("WindowsAngelKicker.cpp.orig", kicker_source_fname) end local build_file = fulljoin(args.input_directory, "build.lua") if (lfs.attributes(kicker_source_fname, "modification") < lfs.attributes(build_file, "modification")) then rebuild_needed = true local kicker_file = io.open(kicker_source_fname, "r") local kicker_source = kicker_file:read("*all") kicker_file:close() local newstring = string.format("\n#define ANGEL_EXE_NAME \"%s.exe\"", config.game_info.name) kicker_source = kicker_source:gsub("\n#define%s+ANGEL_EXE_NAME%s+[^\n]+", newstring) kicker_file = io.open(kicker_source_fname, "w") kicker_file:write(kicker_source) kicker_file:close() end if (rebuild_needed) then print("Rebuilding kicker...") local exec_string = string.format("echo off & \"%sbin\\vcvars32.bat\" > nul & msbuild WindowsAngelKicker.sln /p:Configuration=%s /nologo /noconsolelogger /v:quiet > nul", args.vcpath, kicker_config) os.execute(exec_string) end copyfile(kicker_built, kicker_exe)
------------------------------------------------------------------------------ -- Copyright (C) 2008-2012, Shane Liesegang -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the copyright holder nor the names of any -- contributors may be used to endorse or promote products derived from -- this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ if (package.path == nil) then package.path = "" end local mydir = debug.getinfo(1,"S").source:match[[^@?(.*[\/])[^\/]-$]] if (mydir == nil) then mydir = "." end package.path = mydir .. "?.lua;" .. package.path package.path = package.path .. ";" .. mydir .. "lua-lib/penlight-0.8/lua/?/init.lua" package.path = package.path .. ";" .. mydir .. "lua-lib/penlight-0.8/lua/?.lua" require "angel_build" require "lfs" require "pl.path" require "pl.lapp" local args = pl.lapp [[ Packages a game for easy distribution. -i,--input_directory (string) Project directory -o,--output_directory (string) Where the packaged game should go -v,--vcpath (string) Where Visual Studio is installed -g,--gamename (default ClientGame.exe) Name of the final game ]] lfs.chdir(args.input_directory) local config = {} if (pl.path.exists("build.lua")) then loadFileIn("build.lua", config) end if (config.game_info == nil) then config.game_info = {} end if (config.game_info.name == nil) then config.game_info.name = pl.path.splitext(args.gamename) end local bits_path = pl.path.join(args.output_directory, "bits") if (not pl.path.exists(bits_path)) then makedirs(bits_path) end conf_path = fulljoin(args.input_directory, "..", "Angel", "AngelConfig.h") t = io.open(conf_path, "r") tr = t:read("*all") t:close() disable_fmod = tonumber(tr:match("\n%s*#define%s+ANGEL_DISABLE_FMOD%s+([0-9]+)")) disable_devil = tonumber(tr:match("\n%s*#define%s+ANGEL_DISABLE_DEVIL%s+([0-9]+)")) local files_ex = {} local files_base = {"GameInfo.txt", "Attributions.txt"} local directories = {"Resources", "Config", "Logs"} if (disable_fmod == 1) then table.insert(files_ex, "OpenAL32.dll") else table.insert(files_ex, "fmodex.dll") end if (disable_devil ~= 1) then table.insert(files_ex, "DevIL.dll") table.insert(files_ex, "ILU.dll") table.insert(files_ex, "ILUT.dll") end for _, file_ex in pairs(files_ex) do copyfile(pl.path.join(args.input_directory, file_ex), pl.path.join(bits_path, file_ex)) end for _, file_base in pairs(files_base) do copyfile(fulljoin(args.input_directory, "Documentation", file_base), pl.path.join(args.output_directory, file_base)) end for _, directory in pairs(directories) do recursive_copy(pl.path.join(args.input_directory, directory), pl.path.join(bits_path, directory)) end att_path = fulljoin(args.input_directory, "..", "Tools", "BuildScripts", "Attributions") correct_attributions(pl.path.join(args.output_directory, "Attributions.txt"), att_path, disable_devil, disable_fmod) copyfile(fulljoin(args.input_directory, "Release", args.gamename), pl.path.join(bits_path, config.game_info.name .. ".exe")) local kicker_exe = fulljoin(args.output_directory, config.game_info.name .. ".exe") local kicker_dir = fulljoin(args.input_directory, "..", "Angel", "Win", "WindowsAngelKicker") local kicker_source_fname = "WindowsAngelKicker.cpp" local kicker_config = "Release" local kicker_built = fulljoin(kicker_dir, kicker_config, "WindowsAngelKicker.exe") local rebuild_needed = false if (pl.path.exists(kicker_exe) ~= true) then rebuild_needed = true end local kicker_files = {"angel.ico", "angel_small.ico"} for _, kicker_file in pairs(kicker_files) do local src = fulljoin(args.input_directory, "platforms", "win", kicker_file) local dst = fulljoin(kicker_dir, kicker_file) if ( (pl.path.exists(dst) ~= true) or (lfs.attributes(dst, "modification") < lfs.attributes(src, "modification") ) ) then rebuild_needed = true copyfile(src, dst) end end lfs.chdir(kicker_dir) local build_file = fulljoin(args.input_directory, "build.lua") if (pl.path.exists(kicker_source_fname) ~= true) then rebuild_needed = true copyfile("WindowsAngelKicker.cpp.orig", kicker_source_fname) end if ((pl.path.exists(build_file) ~= true) or (lfs.attributes(kicker_source_fname, "modification") < lfs.attributes(build_file, "modification"))) then rebuild_needed = true local kicker_file = io.open(kicker_source_fname, "r") local kicker_source = kicker_file:read("*all") kicker_file:close() local newstring = string.format("\n#define ANGEL_EXE_NAME \"%s.exe\"", config.game_info.name) kicker_source = kicker_source:gsub("\n#define%s+ANGEL_EXE_NAME%s+[^\n]+", newstring) kicker_file = io.open(kicker_source_fname, "w") kicker_file:write(kicker_source) kicker_file:close() end if (rebuild_needed) then print("Rebuilding kicker...") local exec_string = string.format("echo off & \"%sbin\\vcvars32.bat\" > nul & msbuild WindowsAngelKicker.sln /p:Configuration=%s /nologo /noconsolelogger /v:quiet > nul", args.vcpath, kicker_config) os.execute(exec_string) end copyfile(kicker_built, kicker_exe)
Fixing publish script to work for IntroGame.
Fixing publish script to work for IntroGame. --HG-- extra : convert_revision : svn%3A18234216-3d68-4496-97ee-3aadfc93d375/trunk%40733
Lua
bsd-3-clause
angel2d/angel2d,tks2103/angel-test,angel2d/angel2d,tks2103/angel-test,angel2d/angel2d,angel2d/angel2d,tks2103/angel-test,tks2103/angel-test,angel2d/angel2d,angel2d/angel2d,tks2103/angel-test,tks2103/angel-test,angel2d/angel2d,tks2103/angel-test,tks2103/angel-test
48e98af0713c7ebb4fca73a763460834d98129f3
pud/component/ControllerComponent.lua
pud/component/ControllerComponent.lua
local Class = require 'lib.hump.class' local Component = getClass 'pud.component.Component' local CommandEvent = getClass 'pud.event.CommandEvent' local ConsoleEvent = getClass 'pud.event.ConsoleEvent' local DisplayPopupMessageEvent = getClass 'pud.event.DisplayPopupMessageEvent' local WaitCommand = getClass 'pud.command.WaitCommand' local MoveCommand = getClass 'pud.command.MoveCommand' local AttackCommand = getClass 'pud.command.AttackCommand' local OpenDoorCommand = getClass 'pud.command.OpenDoorCommand' local PickupCommand = getClass 'pud.command.PickupCommand' local DropCommand = getClass 'pud.command.DropCommand' local AttachCommand = getClass 'pud.command.AttachCommand' local DetachCommand = getClass 'pud.command.DetachCommand' local DoorMapType = getClass 'pud.map.DoorMapType' local message = require 'pud.component.message' local property = require 'pud.component.property' local CommandEvents = CommandEvents local vec2_equal = vec2.equal -- ControllerComponent -- local ControllerComponent = Class{name='ControllerComponent', inherits=Component, function(self, newProperties) Component._addRequiredProperties(self, {'CanOpenDoors'}) Component.construct(self, newProperties) self:_addMessages( 'COLLIDE_NONE', 'COLLIDE_BLOCKED', 'COLLIDE_ITEM', 'COLLIDE_ENEMY', 'COLLIDE_HERO') end } -- destructor function ControllerComponent:destroy() Component.destroy(self) end function ControllerComponent:_setProperty(prop, data) prop = property(prop) if nil == data then data = property.default(prop) end if prop == property('CanOpenDoors') then verify('boolean', data) end Component._setProperty(self, prop, data) end -- check for collisions at the given coordinates function ControllerComponent:_attemptMove(x, y) local pos = self._mediator:query(property('Position')) local newX, newY = pos[1] + x, pos[2] + y CollisionSystem:check(self._mediator, newX, newY) end function ControllerComponent:_wait() self:_sendCommand(WaitCommand(self._mediator)) end function ControllerComponent:_move(x, y) local canMove = self._mediator:query(property('CanMove')) if canMove then self:_sendCommand(MoveCommand(self._mediator, x, y)) else self:_wait() end end function ControllerComponent:_tryToManipulateMap(node) local wait = true if node then local mapType = node:getMapType() if mapType:isType(DoorMapType('shut')) then if self._mediator:query(property('CanOpenDoors')) then self:_sendCommand(OpenDoorCommand(self._mediator, node)) wait = false end end end if wait then self:_wait() end end function ControllerComponent:_attack(isHero, target) local etype = self._mediator:getEntityType() if isHero or 'hero' == etype then self:_sendCommand( AttackCommand(self._mediator, EntityRegistry:get(target))) else self:_wait() end end function ControllerComponent:_tryToPickup() local items = EntityRegistry:getIDsByType('item') local count = 0 local pIsContained = property('IsContained') local pPosition = property('Position') if items then local num = #items for i=1,num do local id = items[i] local item = EntityRegistry:get(id) if not item:query(pIsContained) then local ipos = item:query(pPosition) local mpos = self._mediator:query(pPosition) if vec2_equal(ipos[1], ipos[2], mpos[1], mpos[2]) then self:_sendCommand(PickupCommand(self._mediator, id)) count = count + 1 end end end end if count == 0 then GameEvents:push(DisplayPopupMessageEvent('Nothing to pick up!')) end end function ControllerComponent:_tryToDrop(id) local contained = self._mediator:query(property('ContainedEntities')) if contained then local found = false local num = #contained for i=1,num do if contained[i] == id then found = true break end end if found then local item = EntityRegistry:get(id) self:_sendCommand(DropCommand(self._mediator, id)) else GameEvents:push(DisplayPopupMessageEvent('You can\'t drop that!')) end else GameEvents:push(DisplayPopupMessageEvent('Nothing to drop!')) end end function ControllerComponent:_tryToAttach(id) local contained = self._mediator:query(property('ContainedEntities')) local attached = false if contained then local num = #contained local found = false for i=1,num do if contained[i] == id then found = true break end end if found then local item = EntityRegistry:get(id) if not item:query(property('IsAttached')) then self:_sendCommand(AttachCommand(self._mediator, id)) attached = true end else GameEvents:push(DisplayPopupMessageEvent('You can\'t equip that!')) end end if not attached then print('not attached') GameEvents:push(DisplayPopupMessageEvent('Nothing to equip!')) end end function ControllerComponent:_tryToDetach(id) local attached = self._mediator:query(property('AttachedEntities')) if attached then local found = false local num = #attached for i=1,num do if attached[i] == id then found = true break end end if found then local item = EntityRegistry:get(id) self:_sendCommand(DetachCommand(self._mediator, id)) else GameEvents:push( DisplayPopupMessageEvent('You don\'t have that equipped!')) end else GameEvents:push(DisplayPopupMessageEvent('Nothing to unequip!')) end end function ControllerComponent:_sendCommand(command) CommandEvents:notify(CommandEvent(command)) end function ControllerComponent:receive(msg, ...) if msg == message('COLLIDE_NONE') then self:_move(...) elseif msg == message('COLLIDE_BLOCKED') then self:_tryToManipulateMap(...) elseif msg == message('COLLIDE_ENEMY') then self:_attack(false, ...) elseif msg == message('COLLIDE_HERO') then self:_attack(true, ...) elseif msg == message('COLLIDE_ITEM') then if self._mediator:getEntityType() == 'hero' then local id = select(1, ...) if id then local item = EntityRegistry:get(id) local name = item:getName() local elevel = item:getELevel() GameEvents:push(ConsoleEvent('Item found: %s (%d)', name, elevel)) end end else Component.receive(self, msg, ...) end end -- the class return ControllerComponent
local Class = require 'lib.hump.class' local Component = getClass 'pud.component.Component' local CommandEvent = getClass 'pud.event.CommandEvent' local ConsoleEvent = getClass 'pud.event.ConsoleEvent' local DisplayPopupMessageEvent = getClass 'pud.event.DisplayPopupMessageEvent' local WaitCommand = getClass 'pud.command.WaitCommand' local MoveCommand = getClass 'pud.command.MoveCommand' local AttackCommand = getClass 'pud.command.AttackCommand' local OpenDoorCommand = getClass 'pud.command.OpenDoorCommand' local PickupCommand = getClass 'pud.command.PickupCommand' local DropCommand = getClass 'pud.command.DropCommand' local AttachCommand = getClass 'pud.command.AttachCommand' local DetachCommand = getClass 'pud.command.DetachCommand' local DoorMapType = getClass 'pud.map.DoorMapType' local message = require 'pud.component.message' local property = require 'pud.component.property' local CommandEvents = CommandEvents local vec2_equal = vec2.equal -- ControllerComponent -- local ControllerComponent = Class{name='ControllerComponent', inherits=Component, function(self, newProperties) Component._addRequiredProperties(self, {'CanOpenDoors'}) Component.construct(self, newProperties) self:_addMessages( 'COLLIDE_NONE', 'COLLIDE_BLOCKED', 'COLLIDE_ITEM', 'COLLIDE_ENEMY', 'COLLIDE_HERO') end } -- destructor function ControllerComponent:destroy() Component.destroy(self) end function ControllerComponent:_setProperty(prop, data) prop = property(prop) if nil == data then data = property.default(prop) end if prop == property('CanOpenDoors') then verify('boolean', data) end Component._setProperty(self, prop, data) end -- check for collisions at the given coordinates function ControllerComponent:_attemptMove(x, y) local pos = self._mediator:query(property('Position')) local newX, newY = pos[1] + x, pos[2] + y CollisionSystem:check(self._mediator, newX, newY) end function ControllerComponent:_wait() self:_sendCommand(WaitCommand(self._mediator)) end function ControllerComponent:_move(x, y) local canMove = self._mediator:query(property('CanMove')) if canMove then self:_sendCommand(MoveCommand(self._mediator, x, y)) else self:_wait() end end function ControllerComponent:_tryToManipulateMap(node) local wait = true if node then local mapType = node:getMapType() if mapType:isType(DoorMapType('shut')) then if self._mediator:query(property('CanOpenDoors')) then self:_sendCommand(OpenDoorCommand(self._mediator, node)) wait = false end end end if wait then self:_wait() end end function ControllerComponent:_attack(isHero, target) local etype = self._mediator:getEntityType() if isHero or 'hero' == etype then self:_sendCommand( AttackCommand(self._mediator, EntityRegistry:get(target))) else self:_wait() end end function ControllerComponent:_tryToPickup() local items = EntityRegistry:getIDsByType('item') local count = 0 local pIsContained = property('IsContained') local pPosition = property('Position') if items then local num = #items for i=1,num do local id = items[i] local item = EntityRegistry:get(id) if not item:query(pIsContained) then local ipos = item:query(pPosition) local mpos = self._mediator:query(pPosition) if vec2_equal(ipos[1], ipos[2], mpos[1], mpos[2]) then self:_sendCommand(PickupCommand(self._mediator, id)) count = count + 1 end end end end if count == 0 then GameEvents:push(DisplayPopupMessageEvent('Nothing to pick up!')) end end function ControllerComponent:_tryToDrop(id) local contained = self._mediator:query(property('ContainedEntities')) if contained then local found = false local num = #contained for i=1,num do if contained[i] == id then found = true break end end if found then local item = EntityRegistry:get(id) self:_sendCommand(DropCommand(self._mediator, id)) else GameEvents:push(DisplayPopupMessageEvent('You can\'t drop that!')) end else GameEvents:push(DisplayPopupMessageEvent('Nothing to drop!')) end end function ControllerComponent:_tryToAttach(id) local contained = self._mediator:query(property('ContainedEntities')) local found = false if contained then local num = #contained for i=1,num do if contained[i] == id then found = true break end end if found then local item = EntityRegistry:get(id) if not item:query(property('IsAttached')) then self:_sendCommand(AttachCommand(self._mediator, id)) end else GameEvents:push(DisplayPopupMessageEvent('You can\'t equip that!')) end end if not found then GameEvents:push(DisplayPopupMessageEvent('Nothing to equip!')) end end function ControllerComponent:_tryToDetach(id) local attached = self._mediator:query(property('AttachedEntities')) if attached then local found = false local num = #attached for i=1,num do if attached[i] == id then found = true break end end if found then local item = EntityRegistry:get(id) self:_sendCommand(DetachCommand(self._mediator, id)) else GameEvents:push( DisplayPopupMessageEvent('You don\'t have that equipped!')) end else GameEvents:push(DisplayPopupMessageEvent('Nothing to unequip!')) end end function ControllerComponent:_sendCommand(command) CommandEvents:notify(CommandEvent(command)) end function ControllerComponent:receive(msg, ...) if msg == message('COLLIDE_NONE') then self:_move(...) elseif msg == message('COLLIDE_BLOCKED') then self:_tryToManipulateMap(...) elseif msg == message('COLLIDE_ENEMY') then self:_attack(false, ...) elseif msg == message('COLLIDE_HERO') then self:_attack(true, ...) elseif msg == message('COLLIDE_ITEM') then if self._mediator:getEntityType() == 'hero' then local id = select(1, ...) if id then local item = EntityRegistry:get(id) local name = item:getName() local elevel = item:getELevel() GameEvents:push(ConsoleEvent('Item found: %s (%d)', name, elevel)) end end else Component.receive(self, msg, ...) end end -- the class return ControllerComponent
fix "Nothing to equip!" spam
fix "Nothing to equip!" spam
Lua
mit
scottcs/wyx
674c8fc07f82a3f9757400de0fa3efa737ff1ef7
[resources]/GTWaccounts/c_intro.lua
[resources]/GTWaccounts/c_intro.lua
--[[ ******************************************************************************** Project owner: RageQuit community Project name: GTW-RPG Developers: Mr_Moose Source code: https://github.com/GTWCode/GTW-RPG/ Bugtracker: https://forum.404rq.com/bug-reports/ Suggestions: https://forum.404rq.com/mta-servers-development/ Version: Open source License: BSD 2-Clause Status: Stable release ******************************************************************************** ]]-- -- Initialize tables for data storage settings = { } settings.timer = { } settings.frames = { } -- Setup introduction for new players settings.intro = { -- LookAtX, LookAtY, LookAtZ, PosX, PosY, PosZ, Message [1]={ 1804.1455078125, -1932.4345703125, 13.386493682861, 1793.5693359375, -1924.181640625, 17.390524864197, "This is a rental shop from where you can get a car" }, [2]={ 1940.4599609375, -1772.3994140625, 13.390598297119, 1970.6015625, -1742.7529296875, 17.546875, "All vehicles need fuel, you can buy fuel at any gas station" }, [3]={ 2245.490234375, -1663.033203125, 15.469003677368, 2263.44140625, -1650.8525390625, 19.432439804077, "This is a skin shop, walk inside to buy a new skin" }, [4]={ 2227.2275390625, -1721.541015625, 13.554790496826, 2223.6796875, -1756.4375, 16.5625, "Visit the gym to improve your stamina or muscles" }, [5]={ 2396.2890625, -1911.6201171875, 16.460195541382, 2360.251953125, -1880.6142578125, 22.553737640381, "You can regain your health by eating, literally anything" }, [6]={ 2495.810546875, -1666.443359375, 13.34375, 2456.9892578125, -1697.0546875, 22.953369140625, "Create/join a gang by pressing F6 to open your gang/goup/clan panel" }, [7]={ 2495.810546875, -1666.443359375, 13.34375, 2456.9892578125, -1697.0546875, 22.953369140625, "When you're in a gang you can capture turfs to gain money and respect" }, [8]={ 1808.2685546875, -1897.8447265625, 13.578125, 1797.71484375, -1897.3994140625, 20.402294158936, "This is a work place, you can get a job here to make money" }, } settings.timer.limit = 360 settings.timer.current = settings.timer.limit - 30 settings.frames.current = 0 settings.message = "Initializing..." sx,sy = guiGetScreenSize() --[[ Reset and clean up ]]-- function reset_data() settings.timer.limit = 360 settings.timer.current = settings.timer.limit - 30 settings.frames.current = 0 settings.message = "Initializing..." -- Kill event handler and reset view removeEventHandler("onClientRender", root, view_gtw_intro) if not isClientLoggedIn() then local x = getElementData(client, "GTWaccounts.login.coordinates.x") local y = getElementData(client, "GTWaccounts.login.coordinates.y") local z = getElementData(client, "GTWaccounts.login.coordinates.z") local x2 = getElementData(client, "GTWaccounts.login.coordinates.x2") local y2 = getElementData(client, "GTWaccounts.login.coordinates.y2") local z2 = getElementData(client, "GTWaccounts.login.coordinates.z2") setCameraMatrix(x,y,z, x2,y2,z2, 0, 80) guiSetVisible(window, true) else setCameraTarget(localPlayer) showChat(true) end -- Show radar again showPlayerHudComponent("radar", true) -- Reset temporary view coordinates setElementData(client, "GTWaccounts.login.coordinates.x", nil) setElementData(client, "GTWaccounts.login.coordinates.y", nil) setElementData(client, "GTWaccounts.login.coordinates.z", nil) setElementData(client, "GTWaccounts.login.coordinates.x2", nil) setElementData(client, "GTWaccounts.login.coordinates.y2", nil) setElementData(client, "GTWaccounts.login.coordinates.z2", nil) end --[[ Update 3D text message and picture ]]-- function view_gtw_intro( ) dxDrawText(settings.message, sx+1,0, 0,sy-70, tocolor(0,0,0,255), 1, "bankgothic", "center", "bottom", false, true) dxDrawText(settings.message, sx,0, 0,sy-69, tocolor(255,100,0,255), 1, "bankgothic", "center", "bottom", false, true) -- Update text and screen position if settings.timer.current == settings.timer.limit then settings.frames.current = settings.frames.current + 1 setCameraMatrix(settings.intro[settings.frames.current][4], settings.intro[settings.frames.current][5], settings.intro[settings.frames.current][6], settings.intro[settings.frames.current][1], settings.intro[settings.frames.current][2], settings.intro[settings.frames.current][3], 0, 80) settings.message = settings.intro[settings.frames.current][7] settings.timer.current = 0 fadeCamera(true, 2, 0,0,0) playSoundFrontEnd(11) -- Hise radar and chat showPlayerHudComponent("radar", false) showChat(false) end -- Stop if finished if settings.frames.current >= #settings.intro then -- Stop the intro reset_data() end -- Update timer settings.timer.current = settings.timer.current + 1 end --[[ Start the introduction ]]-- function start_intro() addEventHandler("onClientRender", root, view_gtw_intro) guiSetVisible(window, false) end addCommandHandler("intro", start_intro) --[[ Function to stop the intro and reset ]]-- function stop_intro() -- Stop the intro reset_data() showPlayerHudComponent("radar", true) unbindKey("space", "down", stop_intro) end addCommandHandler("stopintro", toggle_intro) bindKey("space", "down", stop_intro)
--[[ ******************************************************************************** Project owner: RageQuit community Project name: GTW-RPG Developers: Mr_Moose Source code: https://github.com/GTWCode/GTW-RPG/ Bugtracker: https://forum.404rq.com/bug-reports/ Suggestions: https://forum.404rq.com/mta-servers-development/ Version: Open source License: BSD 2-Clause Status: Stable release ******************************************************************************** ]]-- -- Initialize tables for data storage settings = { } settings.timer = { } settings.frames = { } -- Setup introduction for new players settings.intro = { -- LookAtX, LookAtY, LookAtZ, PosX, PosY, PosZ, Message [1]={ 1804.1455078125, -1932.4345703125, 13.386493682861, 1793.5693359375, -1924.181640625, 17.390524864197, "This is a rental shop from where you can get a car" }, [2]={ 1940.4599609375, -1772.3994140625, 13.390598297119, 1970.6015625, -1742.7529296875, 17.546875, "All vehicles need fuel, you can buy fuel at any gas station" }, [3]={ 2245.490234375, -1663.033203125, 15.469003677368, 2263.44140625, -1650.8525390625, 19.432439804077, "This is a skin shop, walk inside to buy a new skin" }, [4]={ 2227.2275390625, -1721.541015625, 13.554790496826, 2223.6796875, -1756.4375, 16.5625, "Visit the gym to improve your stamina or muscles" }, [5]={ 2396.2890625, -1911.6201171875, 16.460195541382, 2360.251953125, -1880.6142578125, 22.553737640381, "You can regain your health by eating, literally anything" }, [6]={ 2495.810546875, -1666.443359375, 13.34375, 2456.9892578125, -1697.0546875, 22.953369140625, "Create/join a gang by pressing F6 to open your gang/goup/clan panel" }, [7]={ 2495.810546875, -1666.443359375, 13.34375, 2456.9892578125, -1697.0546875, 22.953369140625, "When you're in a gang you can capture turfs to gain money and respect" }, [8]={ 1808.2685546875, -1897.8447265625, 13.578125, 1797.71484375, -1897.3994140625, 20.402294158936, "This is a work place, you can get a job here to make money" }, } settings.timer.limit = 360 settings.timer.current = settings.timer.limit - 30 settings.frames.current = 0 settings.message = "Initializing..." sx,sy = guiGetScreenSize() --[[ Reset and clean up ]]-- function reset_data() settings.timer.limit = 360 settings.timer.current = settings.timer.limit - 30 settings.frames.current = 0 settings.message = "Initializing..." -- Kill event handler and reset view removeEventHandler("onClientRender", root, view_gtw_intro) if not isClientLoggedIn() then local x = getElementData(localPlayer, "GTWaccounts.login.coordinates.x") local y = getElementData(localPlayer, "GTWaccounts.login.coordinates.y") local z = getElementData(localPlayer, "GTWaccounts.login.coordinates.z") local x2 = getElementData(localPlayer, "GTWaccounts.login.coordinates.x2") local y2 = getElementData(localPlayer, "GTWaccounts.login.coordinates.y2") local z2 = getElementData(localPlayer, "GTWaccounts.login.coordinates.z2") setCameraMatrix(x,y,z, x2,y2,z2, 0, 80) guiSetVisible(window, true) else setCameraTarget(localPlayer) showChat(true) end -- Show radar again showPlayerHudComponent("radar", true) -- Reset temporary view coordinates setElementData(localPlayer, "GTWaccounts.login.coordinates.x", nil) setElementData(localPlayer, "GTWaccounts.login.coordinates.y", nil) setElementData(localPlayer, "GTWaccounts.login.coordinates.z", nil) setElementData(localPlayer, "GTWaccounts.login.coordinates.x2", nil) setElementData(localPlayer, "GTWaccounts.login.coordinates.y2", nil) setElementData(localPlayer, "GTWaccounts.login.coordinates.z2", nil) end --[[ Update 3D text message and picture ]]-- function view_gtw_intro( ) dxDrawText(settings.message, sx+1,0, 0,sy-70, tocolor(0,0,0,255), 1, "bankgothic", "center", "bottom", false, true) dxDrawText(settings.message, sx,0, 0,sy-69, tocolor(255,100,0,255), 1, "bankgothic", "center", "bottom", false, true) -- Update text and screen position if settings.timer.current == settings.timer.limit then settings.frames.current = settings.frames.current + 1 setCameraMatrix(settings.intro[settings.frames.current][4], settings.intro[settings.frames.current][5], settings.intro[settings.frames.current][6], settings.intro[settings.frames.current][1], settings.intro[settings.frames.current][2], settings.intro[settings.frames.current][3], 0, 80) settings.message = settings.intro[settings.frames.current][7] settings.timer.current = 0 fadeCamera(true, 2, 0,0,0) playSoundFrontEnd(11) -- Hise radar and chat showPlayerHudComponent("radar", false) showChat(false) end -- Stop if finished if settings.frames.current >= #settings.intro then -- Stop the intro reset_data() end -- Update timer settings.timer.current = settings.timer.current + 1 end --[[ Start the introduction ]]-- function start_intro() addEventHandler("onClientRender", root, view_gtw_intro) guiSetVisible(window, false) end addCommandHandler("intro", start_intro) --[[ Function to stop the intro and reset ]]-- function stop_intro() -- Stop the intro reset_data() showPlayerHudComponent("radar", true) unbindKey("space", "down", stop_intro) end addCommandHandler("stopintro", stop_intro) bindKey("space", "down", stop_intro)
[Patch] Fixed the non working stop command
[Patch] Fixed the non working stop command
Lua
bsd-2-clause
404rq/GTW-RPG,GTWCode/GTW-RPG,GTWCode/GTW-RPG,404rq/GTW-RPG,404rq/GTW-RPG,GTWCode/GTW-RPG
e525fa7b90a4bf26515b395b2bc361c7d95f7bac
lib/switchboard_modules/lua_script_debugger/premade_scripts/3_set_dac_based_on_voltage.lua
lib/switchboard_modules/lua_script_debugger/premade_scripts/3_set_dac_based_on_voltage.lua
print("Read AIN3 input voltage and set DAC0 output voltage. Update at 10Hz") local InputVoltage = 0 local ThresholdVoltage = 2.5 --threshold is 2.5V local OutputVoltageA = 4.5 local OutputVoltageB = 0 LJ.IntervalConfig(0, 100) --set interval to 100 for 100ms local checkInterval=LJ.CheckInterval local mbRead=MB.R --local functions for faster processing local mbWrite=MB.W while true do if LJ.CheckInterval(0) then --interval completed InputVoltage = mbRead(6, 3) --read AIN3. Address is 6, type is 3 print("AIN3: ", InputVoltage, "V") if InputVoltage > ThresholdVoltage then --if the input voltage exceeds 2.5V mbWrite(1000, 3, OutputVoltageA) --Set DAC0 to 4.5V. Address is 1000, type is 3 print ("DAC0: ", OutputVoltageA) else mbWrite(1000, 3, OutputVoltageB) --Set DAC0 to 0V. print ("DAC0: ", OutputVoltageB) end end end
--[[ Name: 3_set_dac_based_on_voltage.lua Desc: This example shows how to set a DAC according to an input voltage Note: This example requires firmware 1.0282 (T7) or 1.0023 (T4) --]] print("Read AIN3 input voltage and set DAC0 output voltage. Update at 10Hz") local threshold = 2.5 local vout0 = 4.5 local vout1 = 0 -- Configure a 100ms interval LJ.IntervalConfig(0, 100) -- Run the program in an infinite loop while true do -- If an interval is done if LJ.CheckInterval(0) then -- Get an input voltage by reading AIN3 local vin = MB.readName("AIN3") print("AIN3: ", vin, "V") -- If vin exceeds the threshold (2.5V) if vin > threshold then -- Set DAC0 to 4.5V MB.writeName("DAC0", vout0) print ("DAC0: ", vout0) else -- Set DAC0 to 0V MB.writeName("DAC0", vout1) print ("DAC0: ", vout1) end end end
Fixed up the formatting of the set dac based on voltage example
Fixed up the formatting of the set dac based on voltage example
Lua
mit
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
a9fd135de39d85d3aca131e8b80284ce6995aa5c
applications/luci-firewall/luasrc/model/cbi/luci_fw/rrule.lua
applications/luci-firewall/luasrc/model/cbi/luci_fw/rrule.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2010 Jo-Philipp Wich <[email protected]> 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 sys = require "luci.sys" local dsp = require "luci.dispatcher" arg[1] = arg[1] or "" m = Map("firewall", translate("Traffic Redirection"), translate("Traffic redirection allows you to change the " .. "destination address of forwarded packets.")) m.redirect = dsp.build_url("admin", "network", "firewall") if not m.uci:get(arg[1]) == "redirect" then luci.http.redirect(m.redirect) return end local has_v2 = nixio.fs.access("/lib/firewall/fw.sh") local wan_zone = nil m.uci:foreach("firewall", "zone", function(s) local n = s.network or s.name if n then local i for i in n:gmatch("%S+") do if i == "wan" then wan_zone = s.name return false end end end end) s = m:section(NamedSection, arg[1], "redirect", "") s.anonymous = true s.addremove = false s:tab("general", translate("General Settings")) s:tab("advanced", translate("Advanced Settings")) name = s:taboption("general", Value, "_name", translate("Name")) name.rmempty = true name.size = 10 src = s:taboption("general", Value, "src", translate("Source zone")) src.nocreate = true src.default = "wan" src.template = "cbi/firewall_zonelist" proto = s:taboption("general", Value, "proto", translate("Protocol")) proto.optional = true proto:value("tcpudp", "TCP+UDP") proto:value("tcp", "TCP") proto:value("udp", "UDP") dport = s:taboption("general", Value, "src_dport", translate("External port"), translate("Match incoming traffic directed at the given " .. "destination port or port range on this host")) dport.datatype = "portrange" dport:depends("proto", "tcp") dport:depends("proto", "udp") dport:depends("proto", "tcpudp") to = s:taboption("general", Value, "dest_ip", translate("Internal IP address"), translate("Redirect matched incoming traffic to the specified " .. "internal host")) to.datatype = "ip4addr" for i, dataset in ipairs(luci.sys.net.arptable()) do to:value(dataset["IP address"]) end toport = s:taboption("general", Value, "dest_port", translate("Internal port (optional)"), translate("Redirect matched incoming traffic to the given port on " .. "the internal host")) toport.optional = true toport.placeholder = "0-65535" toport.datatype = "portrange" toport:depends("proto", "tcp") toport:depends("proto", "udp") toport:depends("proto", "tcpudp") target = s:taboption("advanced", ListValue, "target", translate("Redirection type")) target:value("DNAT") target:value("SNAT") dest = s:taboption("advanced", Value, "dest", translate("Destination zone")) dest.nocreate = true dest.default = "lan" dest.template = "cbi/firewall_zonelist" src_dip = s:taboption("advanced", Value, "src_dip", translate("Intended destination address"), translate( "For DNAT, match incoming traffic directed at the given destination ".. "ip address. For SNAT rewrite the source address to the given address." )) src_dip.optional = true src_dip.datatype = "ip4addr" src_dip.placeholder = translate("any") src_mac = s:taboption("advanced", Value, "src_mac", translate("Source MAC address")) src_mac.optional = true src_mac.datatype = "macaddr" src_mac.placeholder = translate("any") src_ip = s:taboption("advanced", Value, "src_ip", translate("Source IP address")) src_ip.optional = true src_ip.datatype = "neg_ip4addr" src_ip.placeholder = translate("any") sport = s:taboption("advanced", Value, "src_port", translate("Source port"), translate("Match incoming traffic originating from the given " .. "source port or port range on the client host")) sport.optional = true sport.datatype = "portrange" sport.placeholder = "0-65536" sport:depends("proto", "tcp") sport:depends("proto", "udp") sport:depends("proto", "tcpudp") reflection = s:taboption("advanced", Flag, "reflection", translate("Enable NAT Loopback")) reflection.rmempty = true reflection:depends({ target = "DNAT", src = wan_zone }) reflection.cfgvalue = function(...) return Flag.cfgvalue(...) or "1" end return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2010 Jo-Philipp Wich <[email protected]> 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 sys = require "luci.sys" local dsp = require "luci.dispatcher" arg[1] = arg[1] or "" m = Map("firewall", translate("Traffic Redirection"), translate("Traffic redirection allows you to change the " .. "destination address of forwarded packets.")) m.redirect = dsp.build_url("admin", "network", "firewall") if not m.uci:get(arg[1]) == "redirect" then luci.http.redirect(m.redirect) return end local has_v2 = nixio.fs.access("/lib/firewall/fw.sh") local wan_zone = nil m.uci:foreach("firewall", "zone", function(s) local n = s.network or s.name if n then local i for i in n:gmatch("%S+") do if i == "wan" then wan_zone = s.name return false end end end end) s = m:section(NamedSection, arg[1], "redirect", "") s.anonymous = true s.addremove = false s:tab("general", translate("General Settings")) s:tab("advanced", translate("Advanced Settings")) name = s:taboption("general", Value, "_name", translate("Name")) name.rmempty = true name.size = 10 src = s:taboption("general", Value, "src", translate("Source zone")) src.nocreate = true src.default = "wan" src.template = "cbi/firewall_zonelist" proto = s:taboption("general", Value, "proto", translate("Protocol")) proto.optional = true proto:value("tcpudp", "TCP+UDP") proto:value("tcp", "TCP") proto:value("udp", "UDP") dport = s:taboption("general", Value, "src_dport", translate("External port"), translate("Match incoming traffic directed at the given " .. "destination port or port range on this host")) dport.datatype = "portrange" dport:depends("proto", "tcp") dport:depends("proto", "udp") dport:depends("proto", "tcpudp") to = s:taboption("general", Value, "dest_ip", translate("Internal IP address"), translate("Redirect matched incoming traffic to the specified " .. "internal host")) to.datatype = "ip4addr" for i, dataset in ipairs(luci.sys.net.arptable()) do to:value(dataset["IP address"]) end toport = s:taboption("general", Value, "dest_port", translate("Internal port (optional)"), translate("Redirect matched incoming traffic to the given port on " .. "the internal host")) toport.optional = true toport.placeholder = "0-65535" toport.datatype = "portrange" toport:depends("proto", "tcp") toport:depends("proto", "udp") toport:depends("proto", "tcpudp") target = s:taboption("advanced", ListValue, "target", translate("Redirection type")) target:value("DNAT") target:value("SNAT") dest = s:taboption("advanced", Value, "dest", translate("Destination zone")) dest.nocreate = true dest.default = "lan" dest.template = "cbi/firewall_zonelist" src_dip = s:taboption("advanced", Value, "src_dip", translate("Intended destination address"), translate( "For DNAT, match incoming traffic directed at the given destination ".. "ip address. For SNAT rewrite the source address to the given address." )) src_dip.optional = true src_dip.datatype = "ip4addr" src_dip.placeholder = translate("any") src_mac = s:taboption("advanced", Value, "src_mac", translate("Source MAC address")) src_mac.optional = true src_mac.datatype = "macaddr" src_mac.placeholder = translate("any") src_ip = s:taboption("advanced", Value, "src_ip", translate("Source IP address")) src_ip.optional = true src_ip.datatype = "neg_ip4addr" src_ip.placeholder = translate("any") sport = s:taboption("advanced", Value, "src_port", translate("Source port"), translate("Match incoming traffic originating from the given " .. "source port or port range on the client host")) sport.optional = true sport.datatype = "portrange" sport.placeholder = "0-65536" sport:depends("proto", "tcp") sport:depends("proto", "udp") sport:depends("proto", "tcpudp") reflection = s:taboption("advanced", Flag, "reflection", translate("Enable NAT Loopback")) reflection.rmempty = true reflection.default = reflection.enabled reflection:depends({ target = "DNAT", src = wan_zone }) reflection.cfgvalue = function(...) return Flag.cfgvalue(...) or "1" end return m
applications/luci-firewall: fix turning off nat reflection
applications/luci-firewall: fix turning off nat reflection
Lua
apache-2.0
8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci
4b0b94264c29273a65e87ff50ce9629e27fb381b
Crop.lua
Crop.lua
local Crop, Parent = torch.class('nn.Crop', 'nn.Module') ---- forward: two paras, work with nnGraph. need redefine forward function Crop:__init() Parent.__init(self) self.mask = torch.Tensor() end function Crop:updateOutput(input_data,input) -- input_data: bottom data -- input: the current layer's input, format:nBatch x nChanel x H x W or nChannel x H x W --self.output:resizeAs(input_data) --:copy(input_data) if input_data:dim() == 3 then -- one image self.output:resize(input:size(1),input_data:size(2),input_data:size(3)) --:copy(input_data) self.mask = torch.Tensor(1,4) -- pad_l, pad_r,pad_t,pad_b self.mask[{1,1}]=math.floor((input:size(2) - input_data:size(2))/2) self.mask[{1,2}]=(input:size(2)-input_data:size(2)) - self.mask[{1,1}] self.mask[{1,3}]=math.floor((input:size(3) - input_data:size(3))/2) self.mask[{1,4}]=(input:size(3) - input_data:size(3)) - self.mask[{1,3}] -- update: crop input self.output:copy(input[{{},{self.mask[{1,1}]+1,self.mask[{1,1}]+input_data:size(2)},{self.mask[{1,3}]+1,self.mask[{1,3}]+input_data:size(3)}}]) elseif input_data:dim() == 4 then -- batch self.output:resize(input:size(1),input:size(2),input_data:size(3),input_data:size(4)) --:copy(input_data) --self.mask = torch.Tensor(input_data:size(1),4) self.mask = torch.Tensor(1,4) -- pad_l, pad_r,pad_t,pad_b self.mask[{1,1}]=math.floor((input:size(3) - input_data:size(3))/2) self.mask[{1,2}]=(input:size(3)-input_data:size(3)) - self.mask[{1,1}] self.mask[{1,3}]=math.floor((input:size(4) - input_data:size(4))/2) self.mask[{1,4}]=(input:size(4) - input_data:size(4)) - self.mask[{1,3}] -- update: crop input self.output:copy(input[{{},{},{self.mask[{1,1}]+1,self.mask[{1,1}]+input_data:size(3)},{self.mask[{1,3}]+1,self.mask[{1,3}]+input_data:size(4)}}]) else error('<Crop updateOutput> illegal input, must be 3 D or 4 D') end -- updateOutput return self.output end function Crop:updateGradInput(input,gradOutput) --self.gradInput = torch.Tensor() if gradOutput:dim() == 3 then self.gradInput:resize(gradOutput:size(1),gradOutput:size(2)+self.mask[{1,1}]+self.mask[{1,2}],gradOutput:size(3)+self.mask[{1,3}]+self.mask[{1,4}]) self.gradInput:fill(0) self.gradInput[{{},{self.mask[{1,1}]+1,self.mask[{1,1}]+gradOutput:size(2)},{self.mask[{1,3}]+1,self.mask[{1,3}]+gradOutput:size(3)}}]:copy(gradOutput) elseif gradOutput:dim() == 4 then self.gradInput:resize(gradOutput:size(1),gradOutput:size(2),gradOutput:size(3)+self.mask[{1,1}]+self.mask[{1,2}],gradOutput:size(4)+self.mask[{1,3}]+self.mask[{1,4}]) self.gradInput:fill(0) self.gradInput[{{},{},{self.mask[{1,1}]+1,self.mask[{1,1}]+gradOutput:size(3)},{self.mask[{1,3}]+1,self.mask[{1,3}]+gradOutput:size(4)}}]:copy(gradOutput) else error('<crop updateGradInput> illegal gradOutput, must be 3 D or 4 D') end return self.gradInput end function Crop:forward(input_data, input) -- rewrite forward, need be fixed given the input data format return self:updateOutput(input_data,input) end
local Crop, Parent = torch.class('nn.Crop', 'nn.Module') function Crop:__init() Parent.__init(self) self.mask = torch.Tensor() end function Crop:updateOutput(_input) -- input_data: bottom data -- input: current laye's input, format:nBatch x nChanel x H x W or nChannel x H x W, just one scale for per training time local input_data = _input[1]; local input = _input[2]; if input_data:dim() == 3 then -- one image self.output:resize(input:size(1),input_data:size(2),input_data:size(3)) --:copy(input_data) self.mask = torch.Tensor(1,4) -- pad_l, pad_r,pad_t,pad_b self.mask[{1,1}]=math.floor((input:size(2) - input_data:size(2))/2) self.mask[{1,2}]=(input:size(2)-input_data:size(2)) - self.mask[{1,1}] self.mask[{1,3}]=math.floor((input:size(3) - input_data:size(3))/2) self.mask[{1,4}]=(input:size(3) - input_data:size(3)) - self.mask[{1,3}] -- update: crop input self.output:copy(input[{{},{self.mask[{1,1}]+1,self.mask[{1,1}]+input_data:size(2)},{self.mask[{1,3}]+1,self.mask[{1,3}]+input_data:size(3)}}]); elseif input_data:dim() == 4 then -- batch self.output:resize(input:size(1),input:size(2),input_data:size(3),input_data:size(4)) --:copy(input_data) --self.mask = torch.Tensor(input_data:size(1),4) self.mask = torch.Tensor(1,4) -- pad_l, pad_r,pad_t,pad_b self.mask[{1,1}]=math.floor((input:size(3) - input_data:size(3))/2) self.mask[{1,2}]=(input:size(3)-input_data:size(3)) - self.mask[{1,1}] self.mask[{1,3}]=math.floor((input:size(4) - input_data:size(4))/2) self.mask[{1,4}]=(input:size(4) - input_data:size(4)) - self.mask[{1,3}] -- update: crop input self.output:copy(input[{{},{},{self.mask[{1,1}]+1,self.mask[{1,1}]+input_data:size(3)},{self.mask[{1,3}]+1,self.mask[{1,3}]+input_data:size(4)}}]) else error('<Crop updateOutput> illegal input, must be 3 D or 4 D') end -- update crop input return self.output end function Crop:updateGradInput(_input,gradOutput) --self.gradInput = torch.Tensor() if gradOutput:dim() == 3 then self.gradInput:resize(gradOutput:size(1),gradOutput:size(2)+self.mask[{1,1}]+self.mask[{1,2}],gradOutput:size(3)+self.mask[{1,3}]+self.mask[{1,4}]) self.gradInput:fill(0) self.gradInput[{{},{self.mask[{1,1}]+1,self.mask[{1,1}]+gradOutput:size(2)},{self.mask[{1,3}]+1,self.mask[{1,3}]+gradOutput:size(3)}}]:copy(gradOutput) elseif gradOutput:dim() == 4 then self.gradInput:resize(gradOutput:size(1),gradOutput:size(2),gradOutput:size(3)+self.mask[{1,1}]+self.mask[{1,2}],gradOutput:size(4)+self.mask[{1,3}]+self.mask[{1,4}]) self.gradInput:fill(0) self.gradInput[{{},{},{self.mask[{1,1}]+1,self.mask[{1,1}]+gradOutput:size(3)},{self.mask[{1,3}]+1,self.mask[{1,3}]+gradOutput:size(4)}}]:copy(gradOutput) else error('<crop updateGradInput> illegal gradOutput, must be 3 D or 4 D') end return {nil,self.gradInput} end function Crop:accGradParameters(_input, gradOutput, scale) end function Crop:forward(_input) -- rewrite forward return self:updateOutput(_input) end function Crop:backward(_input, gradOutput, scale) scale = scale or 1 self:updateGradInput(_input, gradOutput) self:accGradParameters(_input, gradOutput, scale) return self.gradInput end
fixe some bug
fixe some bug the crop layer foraward input:{input_data,input}, thus the updateGradInput: {nil,gradInput}
Lua
bsd-3-clause
zchengquan/nn
7678ab70bdfa4421eedf92b2d299069d74bf4d88
applications/luci-firewall/luasrc/model/cbi/luci_fw/rrule.lua
applications/luci-firewall/luasrc/model/cbi/luci_fw/rrule.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2010 Jo-Philipp Wich <[email protected]> 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 sys = require "luci.sys" local dsp = require "luci.dispatcher" arg[1] = arg[1] or "" m = Map("firewall", translate("Traffic Redirection"), translate("Traffic redirection allows you to change the " .. "destination address of forwarded packets.")) m.redirect = dsp.build_url("admin", "network", "firewall") if not m.uci:get(arg[1]) == "redirect" then luci.http.redirect(m.redirect) return end local has_v2 = nixio.fs.access("/lib/firewall/fw.sh") local wan_zone = nil m.uci:foreach("firewall", "zone", function(s) local n = s.network or s.name if n then local i for i in n:gmatch("%S+") do if i == "wan" then wan_zone = s.name return false end end end end) s = m:section(NamedSection, arg[1], "redirect", "") s.anonymous = true s.addremove = false s:tab("general", translate("General Settings")) s:tab("advanced", translate("Advanced Settings")) back = s:taboption("general", DummyValue, "_overview", translate("Overview")) back.value = "" back.titleref = luci.dispatcher.build_url("admin", "network", "firewall", "redirect") name = s:taboption("general", Value, "_name", translate("Name")) name.rmempty = true name.size = 10 src = s:taboption("general", Value, "src", translate("Source zone")) src.nocreate = true src.default = "wan" src.template = "cbi/firewall_zonelist" proto = s:taboption("general", ListValue, "proto", translate("Protocol")) proto.optional = true proto:value("tcpudp", "TCP+UDP") proto:value("tcp", "TCP") proto:value("udp", "UDP") dport = s:taboption("general", Value, "src_dport", translate("External port"), translate("Match incoming traffic directed at the given " .. "destination port or port range on this host")) dport.datatype = "portrange" dport:depends("proto", "tcp") dport:depends("proto", "udp") dport:depends("proto", "tcpudp") to = s:taboption("general", Value, "dest_ip", translate("Internal IP address"), translate("Redirect matched incoming traffic to the specified " .. "internal host")) to.datatype = "ip4addr" for i, dataset in ipairs(luci.sys.net.arptable()) do to:value(dataset["IP address"]) end toport = s:taboption("general", Value, "dest_port", translate("Internal port (optional)"), translate("Redirect matched incoming traffic to the given port on " .. "the internal host")) toport.optional = true toport.placeholder = "0-65535" target = s:taboption("advanced", ListValue, "target", translate("Redirection type")) target:value("DNAT") target:value("SNAT") dest = s:taboption("advanced", Value, "dest", translate("Destination zone")) dest.nocreate = true dest.default = "lan" dest.template = "cbi/firewall_zonelist" src_dip = s:taboption("advanced", Value, "src_dip", translate("Intended destination address"), translate( "For DNAT, match incoming traffic directed at the given destination ".. "ip address. For SNAT rewrite the source address to the given address." )) src_dip.optional = true src_dip.datatype = "ip4addr" src_dip.placeholder = translate("any") src_mac = s:taboption("advanced", Value, "src_mac", translate("Source MAC address")) src_mac.optional = true src_mac.datatype = "macaddr" src_mac.placeholder = translate("any") src_ip = s:taboption("advanced", Value, "src_ip", translate("Source IP address")) src_ip.optional = true src_ip.datatype = "ip4addr" src_ip.placeholder = translate("any") sport = s:taboption("advanced", Value, "src_port", translate("Source port"), translate("Match incoming traffic originating from the given " .. "source port or port range on the client host")) sport.optional = true sport.datatype = "portrange" sport.placeholder = "0-65536" sport:depends("proto", "tcp") sport:depends("proto", "udp") sport:depends("proto", "tcpudp") reflection = s:taboption("advanced", Flag, "reflection", translate("Enable NAT Loopback")) reflection.rmempty = true reflection:depends({ target = "DNAT", src = wan_zone }) reflection.cfgvalue = function(...) return Flag.cfgvalue(...) or "1" end return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2010 Jo-Philipp Wich <[email protected]> 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 sys = require "luci.sys" local dsp = require "luci.dispatcher" arg[1] = arg[1] or "" m = Map("firewall", translate("Traffic Redirection"), translate("Traffic redirection allows you to change the " .. "destination address of forwarded packets.")) m.redirect = dsp.build_url("admin", "network", "firewall") if not m.uci:get(arg[1]) == "redirect" then luci.http.redirect(m.redirect) return end local has_v2 = nixio.fs.access("/lib/firewall/fw.sh") local wan_zone = nil m.uci:foreach("firewall", "zone", function(s) local n = s.network or s.name if n then local i for i in n:gmatch("%S+") do if i == "wan" then wan_zone = s.name return false end end end end) s = m:section(NamedSection, arg[1], "redirect", "") s.anonymous = true s.addremove = false s:tab("general", translate("General Settings")) s:tab("advanced", translate("Advanced Settings")) back = s:taboption("general", DummyValue, "_overview", translate("Overview")) back.value = "" back.titleref = luci.dispatcher.build_url("admin", "network", "firewall", "redirect") name = s:taboption("general", Value, "_name", translate("Name")) name.rmempty = true name.size = 10 src = s:taboption("general", Value, "src", translate("Source zone")) src.nocreate = true src.default = "wan" src.template = "cbi/firewall_zonelist" proto = s:taboption("general", Value, "proto", translate("Protocol")) proto.optional = true proto:value("tcpudp", "TCP+UDP") proto:value("tcp", "TCP") proto:value("udp", "UDP") dport = s:taboption("general", Value, "src_dport", translate("External port"), translate("Match incoming traffic directed at the given " .. "destination port or port range on this host")) dport.datatype = "portrange" dport:depends("proto", "tcp") dport:depends("proto", "udp") dport:depends("proto", "tcpudp") to = s:taboption("general", Value, "dest_ip", translate("Internal IP address"), translate("Redirect matched incoming traffic to the specified " .. "internal host")) to.datatype = "ip4addr" for i, dataset in ipairs(luci.sys.net.arptable()) do to:value(dataset["IP address"]) end toport = s:taboption("general", Value, "dest_port", translate("Internal port (optional)"), translate("Redirect matched incoming traffic to the given port on " .. "the internal host")) toport.optional = true toport.placeholder = "0-65535" toport.datatype = "portrange" toport:depends("proto", "tcp") toport:depends("proto", "udp") toport:depends("proto", "tcpudp") target = s:taboption("advanced", ListValue, "target", translate("Redirection type")) target:value("DNAT") target:value("SNAT") dest = s:taboption("advanced", Value, "dest", translate("Destination zone")) dest.nocreate = true dest.default = "lan" dest.template = "cbi/firewall_zonelist" src_dip = s:taboption("advanced", Value, "src_dip", translate("Intended destination address"), translate( "For DNAT, match incoming traffic directed at the given destination ".. "ip address. For SNAT rewrite the source address to the given address." )) src_dip.optional = true src_dip.datatype = "ip4addr" src_dip.placeholder = translate("any") src_mac = s:taboption("advanced", Value, "src_mac", translate("Source MAC address")) src_mac.optional = true src_mac.datatype = "macaddr" src_mac.placeholder = translate("any") src_ip = s:taboption("advanced", Value, "src_ip", translate("Source IP address")) src_ip.optional = true src_ip.datatype = "ip4addr" src_ip.placeholder = translate("any") sport = s:taboption("advanced", Value, "src_port", translate("Source port"), translate("Match incoming traffic originating from the given " .. "source port or port range on the client host")) sport.optional = true sport.datatype = "portrange" sport.placeholder = "0-65536" sport:depends("proto", "tcp") sport:depends("proto", "udp") sport:depends("proto", "tcpudp") reflection = s:taboption("advanced", Flag, "reflection", translate("Enable NAT Loopback")) reflection.rmempty = true reflection:depends({ target = "DNAT", src = wan_zone }) reflection.cfgvalue = function(...) return Flag.cfgvalue(...) or "1" end return m
applications/luci-firewall: some fixes on redirection page
applications/luci-firewall: some fixes on redirection page git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@6514 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI
afa590000fcf6a6d33a26ee527fe5b3760ddee80
src/plugins/core/commands/actions.lua
src/plugins/core/commands/actions.lua
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- C O M M A N D A C T I O N -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --- === plugins.core.commands.actions === --- --- An `action` which will execute a command with matching group/id values. --- Registers itself with the `core.action.manager`. -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- local choices = require("cp.choices") local config = require("cp.config") local dialog = require("cp.dialog") local prop = require("cp.prop") local format = string.format -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local mod = {} local ID = "cmds" local GROUP = "global" -- TODO: Add documentation function mod.init(actionmanager, cmds) mod._cmds = cmds mod._manager = actionmanager mod._handler = actionmanager.addHandler(GROUP .. "_" .. ID, GROUP) :onChoices(mod.onChoices) :onExecute(mod.onExecute) :onActionId(mod.getId) end --- plugins.core.commands.actions.onChoices(choices) -> nothing --- Function --- Adds available choices to the selection. --- --- Parameters: --- * `choices` - The `cp.choices` to add choices to. --- --- Returns: --- * Nothing function mod.onChoices(choices) for _,cmd in pairs(mod._cmds:getAll()) do local title = cmd:getTitle() if title then local group = cmd:getSubtitle() if not group and cmd:getGroup() then group = i18n(cmd:getGroup().."_group") end group = group or "" local action = { id = cmd:id(), } choices:add(title) :subText(i18n("commandChoiceSubText", {group = group})) :params(action) :id(mod.getId(action)) end end end -- TODO: Add documentation function mod.getId(action) return format("%s:%s", ID, action.id) end --- plugins.core.commands.actions.execute(action) -> boolean --- Function --- Executes the action with the provided parameters. --- --- Parameters: --- * `action` - A table representing the action, matching the following: --- * `id` - The specific Command ID within the group. --- --- * `true` if the action was executed successfully. function mod.onExecute(action) local group = mod._cmds if group then local cmdId = action.id if cmdId == nil or cmdId == "" then -- No command ID provided! dialog.displayMessage(i18n("cmdIdMissingError")) return false end local cmd = group:get(cmdId) if cmd == nil then -- No matching command! dialog.displayMessage(i18n("cmdDoesNotExistError"), {id = cmdId}) return false end -- Ensure the command group is active group:activate( function() cmd:activated() end, function() dialog.displayMessage(i18n("cmdGroupNotActivated"), {id = group.id}) end ) return true end return false end --- plugins.core.commands.actions.reset() -> nothing --- Function --- Resets the set of choices. --- --- Parameters: --- * None --- --- Returns: --- * Nothing function mod.reset() mod._handler:reset() end -------------------------------------------------------------------------------- -- -- THE PLUGIN: -- -------------------------------------------------------------------------------- local plugin = { id = "core.commands.actions", group = "core", dependencies = { ["core.action.manager"] = "actionmanager", ["core.commands.global"] = "cmds", } } function plugin.init(deps) mod.init(deps.actionmanager, deps.cmds) return mod end return plugin
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- C O M M A N D A C T I O N -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --- === plugins.core.commands.actions === --- --- An `action` which will execute a command with matching group/id values. --- Registers itself with the `core.action.manager`. -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- local choices = require("cp.choices") local config = require("cp.config") local dialog = require("cp.dialog") local prop = require("cp.prop") local format = string.format -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local mod = {} local ID = "cmds" local GROUP = "global" -- TODO: Add documentation function mod.init(actionmanager, cmds) mod._cmds = cmds mod._manager = actionmanager mod._handler = actionmanager.addHandler(GROUP .. "_" .. ID, GROUP) :onChoices(mod.onChoices) :onExecute(mod.onExecute) :onActionId(mod.getId) end --- plugins.core.commands.actions.onChoices(choices) -> nothing --- Function --- Adds available choices to the selection. --- --- Parameters: --- * `choices` - The `cp.choices` to add choices to. --- --- Returns: --- * Nothing function mod.onChoices(choices) for _,cmd in pairs(mod._cmds:getAll()) do local title = cmd:getTitle() if title then local group = cmd:getSubtitle() if not group and cmd:getGroup() then group = i18n(cmd:getGroup().."_group") end group = group or "" local action = { id = cmd:id(), } choices:add(title) :subText(i18n("commandChoiceSubText", {group = group})) :params(action) :id(mod.getId(action)) end end end -- TODO: Add documentation function mod.getId(action) return format("%s:%s", ID, action.id) end --- plugins.core.commands.actions.execute(action) -> boolean --- Function --- Executes the action with the provided parameters. --- --- Parameters: --- * `action` - A table representing the action, matching the following: --- * `id` - The specific Command ID within the group. --- --- * `true` if the action was executed successfully. function mod.onExecute(action) local group = mod._cmds if group then local cmdId = action.id if cmdId == nil or cmdId == "" then -- No command ID provided! dialog.displayMessage(i18n("cmdIdMissingError")) return false end local cmd = group:get(cmdId) if cmd == nil then -- No matching command! dialog.displayMessage(i18n("cmdDoesNotExistError"), {id = cmdId}) return false end -- Ensure the command group is active group:activate( function() cmd:activated() end, function() dialog.displayMessage(i18n("cmdGroupNotActivated"), {id = group.id}) end ) return true end return false end --- plugins.core.commands.actions.reset() -> nothing --- Function --- Resets the set of choices. --- --- Parameters: --- * None --- --- Returns: --- * Nothing function mod.reset() mod._handler:reset() end -------------------------------------------------------------------------------- -- -- THE PLUGIN: -- -------------------------------------------------------------------------------- local plugin = { id = "core.commands.actions", group = "core", dependencies = { ["core.action.manager"] = "actionmanager", ["core.commands.global"] = "cmds", } } function plugin.init(deps) return mod end function plugin.postInit(deps) -- -- TO-DO: Moving `mod.init()` from `plugin.init()` to `plugin.postInit()` is just a temporary fix -- until David comes up with a better fix in issue #897 -- mod.init(deps.actionmanager, deps.cmds) return mod end return plugin
Temporary Fix for Global Items in Console
Temporary Fix for Global Items in Console
Lua
mit
fcpxhacks/fcpxhacks,fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,cailyoung/CommandPost,CommandPost/CommandPost,cailyoung/CommandPost,cailyoung/CommandPost
df40aaa6a64a7edad6983933f615982aba698d67
lua/entities/gmod_wire_friendslist.lua
lua/entities/gmod_wire_friendslist.lua
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Friends List" ENT.WireDebugName = "Friends List" if CLIENT then return end -- No more client function ENT:Initialize() self.BaseClass.Initialize( self ) WireLib.CreateInputs( self, {"CheckEntity [ENTITY]", "CheckSteamID [STRING]", "CheckEntityID"} ) WireLib.CreateOutputs( self, {"Checked", "Friends [ARRAY]", "AmountConnected", "AmountTotal"} ) self.friends = {} self.friends_lookup = {} self.steamids = {} self.steamids_lookup = {} self.save_on_entity = false self:UpdateOutputs() end function ENT:Setup( save_on_entity, friends_steamids ) self.save_on_entity = false self:UpdateFriendslist( friends_steamids ) self.save_on_entity = save_on_entity or false self:UpdateOutputs() end function ENT:UpdateFriendslist( friends_steamids ) if self.save_on_entity then return end self.friends = {} self.friends_lookup = {} self.steamids = table.Copy(friends_steamids) self.steamids_lookup = {} for i=1,#friends_steamids do self.steamids_lookup[friends_steamids[i]] = true end local plys = player.GetHumans() for i=1,#plys do self:Connected( plys[i] ) end self:UpdateOutputs() end function ENT:Connected( ply ) local steamid = ply:SteamID() -- already added if self.friends_lookup[ply] then return end if self.steamids_lookup[ply:SteamID()] then self.friends[#self.friends+1] = ply self.friends_lookup[ply] = #self.friends self:UpdateOutputs() end end function ENT:Disconnected( ply ) local steamid = ply:SteamID() -- not already added if not self.friends_lookup[ply] then return end if self.steamids_lookup[ply:SteamID()] then local idx = self.friends_lookup[ply] table.remove( self.friends, idx ) self.friends_lookup[ply] = nil self:UpdateOutputs() end end hook.Add( "PlayerInitialSpawn", "wire_friendslist_connect", function( ply ) local friendslists = ents.FindByClass( "gmod_wire_friendslist" ) for i=1,#friendslists do friendslists[i]:Connected( ply ) end end) hook.Add( "PlayerDisconnected", "wire_friendslist_disconnect", function( ply ) local friendslists = ents.FindByClass( "gmod_wire_friendslist" ) for i=1,#friendslists do friendslists[i]:Disconnected( ply ) end end) function ENT:TriggerInput( name, value ) local ply if name == "CheckEntity" then ply = value elseif name == "CheckSteamID" then ply = player.GetBySteamID( value ) elseif name == "CheckEntityID" then ply = Entity(value) end if not IsValid( ply ) then return end if self.friends_lookup[ply] then WireLib.TriggerOutput( self, "Checked", 1 ) else WireLib.TriggerOutput( self, "Checked", -1 ) end timer.Remove( "wire_friendslist_" .. self:EntIndex() ) timer.Create( "wire_friendslist_" .. self:EntIndex(), 0.1, 1, function() if IsValid( self ) then WireLib.TriggerOutput( self, "Checked", 0 ) end end) end function ENT:UpdateOutputs() local str = {} str[#str+1] = "Saved on entity: " .. (self.save_on_entity and "Yes" or "No") .. "\n" str[#str+1] = #self.friends .. " connected friends" str[#str+1] = "\nConnected:" local not_connected = {} for i=1, #self.steamids do local steamid = self.steamids[i] local ply = player.GetBySteamID( steamid ) if IsValid( ply ) then str[#str+1] = ply:Nick() .. " (" .. steamid .. ")" else not_connected[#not_connected+1] = steamid end end table.insert( str, 2, #self.steamids .. " total friends" ) WireLib.TriggerOutput( self, "Friends", self.friends ) WireLib.TriggerOutput( self, "AmountConnected", #self.friends ) WireLib.TriggerOutput( self, "AmountTotal", #self.steamids ) local str = table.concat( str, "\n" ) if #not_connected > 0 then str = str .. "\n\nNot connected:\n" .. table.concat( not_connected, "\n" ) end self:SetOverlayText( str ) end duplicator.RegisterEntityClass("gmod_wire_friendslist", WireLib.MakeWireEnt, "Data", "save_on_entity", "steamids")
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Friends List" ENT.WireDebugName = "Friends List" if CLIENT then return end -- No more client function ENT:Initialize() self.BaseClass.Initialize( self ) WireLib.CreateInputs( self, {"CheckEntity [ENTITY]", "CheckSteamID [STRING]", "CheckEntityID"} ) WireLib.CreateOutputs( self, {"Checked", "Friends [ARRAY]", "AmountConnected", "AmountTotal"} ) self.friends_lookup = {} self.steamids = {} self.steamids_lookup = {} self.save_on_entity = false self:UpdateOutputs() end function ENT:Setup( save_on_entity, friends_steamids ) self.save_on_entity = false self:UpdateFriendslist( friends_steamids ) self.save_on_entity = save_on_entity or false self:UpdateOutputs() end function ENT:UpdateFriendslist( friends_steamids ) if self.save_on_entity then return end self.friends_lookup = {} self.steamids = table.Copy(friends_steamids) self.steamids_lookup = {} for i=1,#friends_steamids do self.steamids_lookup[friends_steamids[i]] = true end local plys = player.GetHumans() for i=1,#plys do self:Connected( plys[i] ) end self:UpdateOutputs() end function ENT:Connected( ply ) local steamid = ply:SteamID() -- already added if self.friends_lookup[ply] then return end if self.steamids_lookup[ply:SteamID()] then self.friends_lookup[ply] = true self:UpdateOutputs() end end function ENT:Disconnected( ply ) local steamid = ply:SteamID() -- not already added if not self.friends_lookup[ply] then return end if self.steamids_lookup[ply:SteamID()] then self.friends_lookup[ply] = nil self:UpdateOutputs() end end hook.Add( "PlayerInitialSpawn", "wire_friendslist_connect", function( ply ) local friendslists = ents.FindByClass( "gmod_wire_friendslist" ) for i=1,#friendslists do friendslists[i]:Connected( ply ) end end) hook.Add( "PlayerDisconnected", "wire_friendslist_disconnect", function( ply ) local friendslists = ents.FindByClass( "gmod_wire_friendslist" ) for i=1,#friendslists do friendslists[i]:Disconnected( ply ) end end) function ENT:TriggerInput( name, value ) local ply if name == "CheckEntity" then ply = value elseif name == "CheckSteamID" then ply = player.GetBySteamID( value ) elseif name == "CheckEntityID" then ply = Entity(value) end if not IsValid( ply ) then return end if self.friends_lookup[ply] then WireLib.TriggerOutput( self, "Checked", 1 ) else WireLib.TriggerOutput( self, "Checked", -1 ) end timer.Remove( "wire_friendslist_" .. self:EntIndex() ) timer.Create( "wire_friendslist_" .. self:EntIndex(), 0.1, 1, function() if IsValid( self ) then WireLib.TriggerOutput( self, "Checked", 0 ) end end) end function ENT:UpdateOutputs() local str = {} str[#str+1] = "Saved on entity: " .. (self.save_on_entity and "Yes" or "No") .. "\n" str[#str+1] = #self.steamids .. " total friends" str[#str+1] = "\nConnected:" local not_connected = {} local connected = {} for i=1, #self.steamids do local steamid = self.steamids[i] local ply = player.GetBySteamID( steamid ) if IsValid( ply ) then str[#str+1] = ply:Nick() .. " (" .. steamid .. ")" connected[#connected+1] = ply else not_connected[#not_connected+1] = steamid end end table.insert( str, 2, #connected .. " connected friends" ) WireLib.TriggerOutput( self, "Friends", connected ) WireLib.TriggerOutput( self, "AmountConnected", #connected ) WireLib.TriggerOutput( self, "AmountTotal", #self.steamids ) local str = table.concat( str, "\n" ) if #not_connected > 0 then str = str .. "\n\nNot connected:\n" .. table.concat( not_connected, "\n" ) end self:SetOverlayText( str ) end duplicator.RegisterEntityClass("gmod_wire_friendslist", WireLib.MakeWireEnt, "Data", "save_on_entity", "steamids")
Fixed friendslist issue
Fixed friendslist issue Fixed an issue that would happen if someone disconnected from the server a few times
Lua
apache-2.0
bigdogmat/wire,NezzKryptic/Wire,thegrb93/wire,dvdvideo1234/wire,sammyt291/wire,Grocel/wire,wiremod/wire,garrysmodlua/wire
d048ccab03144f9e6cd93079d02d3a207aafe345
test_scripts/Polices/Policy_Table_Update/011_ATF_P_TC_HMI_sends_GetURLs_no_app_registered.lua
test_scripts/Polices/Policy_Table_Update/011_ATF_P_TC_HMI_sends_GetURLs_no_app_registered.lua
--------------------------------------------------------------------------------------------- -- Requirements summary: -- In case HMI sends GetURLs and no apps registered SDL must return only default url -- [HMI API] GetURLs request/response -- -- Description: -- SDL should request PTU in case user requests PTU -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: EXTERNAL_PROPRIETARY" flag -- Application is registered. AppID is listed in PTS -- No PTU is requested. -- 2. Performed steps -- Unregister application. -- User press button on HMI to request PTU. -- HMI->SDL: SDL.GetURLs(service=0x07) -- -- Expected result: -- PTU is requested. PTS is created. -- SDL.GetURLs({urls[] = default}) --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') local testCasesForPolicyTableSnapshot = require('user_modules/shared_testcases/testCasesForPolicyTableSnapshot') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() testCasesForPolicyTable.Delete_Policy_table_snapshot() testCasesForPolicyTable:Precondition_updatePolicy_By_overwriting_preloaded_pt("files/jsons/Policies/Policy_Table_Update/endpoints_appId.json") --ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_trigger_getting_device_consent() testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC) end function Test:Precondition_flow_PTU_SUCCEESS_EXTERNAL_PROPRIETARY() local SystemFilesPath = "/tmp/fs/mp/images/ivsu_cache/" local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(RequestId_GetUrls,{result = {code = 0, method = "SDL.GetURLS"} } ) :Do(function(_,_) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", fileName = "PolicyTableUpdate"}) EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "PROPRIETARY"}) :Do(function(_,_) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATING"}, {status = "UP_TO_DATE"}):Times(2) local CorIdSystemRequest = self.mobileSession:SendRPC("SystemRequest", {requestType = "PROPRIETARY", fileName = "PolicyTableUpdate", appID = config.application1.registerAppInterfaceParams.appID}, "files/ptu.json") EXPECT_HMICALL("BasicCommunication.SystemRequest",{ requestType = "PROPRIETARY", fileName = SystemFilesPath.."PolicyTableUpdate" }) :Do(function(_,_data1) self.hmiConnection:SendResponse(_data1.id,"BasicCommunication.SystemRequest", "SUCCESS", {}) self.hmiConnection:SendNotification("SDL.OnReceivedPolicyUpdate", { policyfile = SystemFilesPath.."PolicyTableUpdate"}) end) EXPECT_RESPONSE(CorIdSystemRequest, { success = true, resultCode = "SUCCESS"}) end) end) end function Test:Precondition_UnregisterApp() self.mobileSession:SendRPC("UnregisterAppInterface", {}) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered", {appID = self.applications[config.application1.registerAppInterfaceParams.appName], unexpectedDisconnect = false}) EXPECT_RESPONSE("UnregisterAppInterface", {success = true , resultCode = "SUCCESS"}) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_PTU_GetURLs_NoAppRegistered() local endpoints = {} testCasesForPolicyTableSnapshot:extract_pts() for i = 1, #testCasesForPolicyTableSnapshot.pts_endpoints do if (testCasesForPolicyTableSnapshot.pts_endpoints[i].service == "0x07") then endpoints[#endpoints + 1] = { url = testCasesForPolicyTableSnapshot.pts_endpoints[i].value, appID = testCasesForPolicyTableSnapshot.pts_endpoints[i].appID} end end local RequestId = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(RequestId,{result = {code = 0, method = "SDL.GetURLS"} } ) :Do(function(_,data) local is_correct = {} for i = 1, #data.result.urls do is_correct[i] = false for j = 1, #endpoints do if ( data.result.urls[i].url == endpoints[j].url ) then is_correct[i] = true end end end if(#data.result.urls ~= #endpoints ) then self:FailTestCase("Number of urls is not as expected: "..#endpoints..". Real: "..#data.result.urls) end for i = 1, #is_correct do if(is_correct[i] == false) then self:FailTestCase("url: "..data.result.urls[i].url.." is not correct. Expected: "..endpoints[i].url) end end end) end function Test:TestStep_PTU_DB_GetURLs_NoAppRegistered() local is_test_fail = false local policy_endpoints = {} local sevices_table = commonFunctions:get_data_policy_sql(config.pathToSDL.."/storage/policy.sqlite", "select service from endpoint") for _, value in pairs(sevices_table) do policy_endpoints[#policy_endpoints + 1] = { found = false, service = value } --TODO(istoimenova): Should be updated when policy defect is fixed if ( value == "4" or value == "7") then policy_endpoints[#policy_endpoints].found = true end end for i = 1, #policy_endpoints do if(policy_endpoints[i].found == false) then commonFunctions:printError("endpoints for service "..policy_endpoints[i].service .. " should not be observed." ) is_test_fail = true end end if(is_test_fail == true) then self:FailTestCase("Test is FAILED. See prints.") end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") testCasesForPolicyTable:Restore_preloaded_pt() function Test.Postcondition_Stop() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- Requirements summary: -- In case HMI sends GetURLs and no apps registered SDL must return only default url -- [HMI API] GetURLs request/response -- -- Description: -- SDL should request PTU in case user requests PTU -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: EXTERNAL_PROPRIETARY" flag -- Application is registered. AppID is listed in PTS -- No PTU is requested. -- 2. Performed steps -- Unregister application. -- User press button on HMI to request PTU. -- HMI->SDL: SDL.GetURLs(service=0x07) -- -- Expected result: -- PTU is requested. PTS is created. -- SDL.GetURLs({urls[] = default}) --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') local testCasesForPolicyTableSnapshot = require('user_modules/shared_testcases/testCasesForPolicyTableSnapshot') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() testCasesForPolicyTable.Delete_Policy_table_snapshot() testCasesForPolicyTable:Precondition_updatePolicy_By_overwriting_preloaded_pt("files/jsons/Policies/Policy_Table_Update/endpoints_appId.json") --ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_trigger_getting_device_consent() testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC) end function Test:Precondition_flow_PTU_SUCCEESS_EXTERNAL_PROPRIETARY() local SystemFilesPath = "/tmp/fs/mp/images/ivsu_cache/" local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(RequestId_GetUrls,{result = {code = 0, method = "SDL.GetURLS"} } ) :Do(function(_,_) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", fileName = "PolicyTableUpdate"}) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATING"}, {status = "UP_TO_DATE"}):Times(2) EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "PROPRIETARY"}) :Do(function(_,_) local CorIdSystemRequest = self.mobileSession:SendRPC("SystemRequest", {requestType = "PROPRIETARY", fileName = "PolicyTableUpdate", appID = config.application1.registerAppInterfaceParams.appID}, "files/ptu.json") EXPECT_HMICALL("BasicCommunication.SystemRequest",{ requestType = "PROPRIETARY", fileName = SystemFilesPath.."PolicyTableUpdate" }) :Do(function(_,_data1) self.hmiConnection:SendResponse(_data1.id,"BasicCommunication.SystemRequest", "SUCCESS", {}) self.hmiConnection:SendNotification("SDL.OnReceivedPolicyUpdate", { policyfile = SystemFilesPath.."PolicyTableUpdate"}) end) EXPECT_RESPONSE(CorIdSystemRequest, { success = true, resultCode = "SUCCESS"}) end) end) end function Test:Precondition_UnregisterApp() self.mobileSession:SendRPC("UnregisterAppInterface", {}) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered", {appID = self.applications[config.application1.registerAppInterfaceParams.appName], unexpectedDisconnect = false}) EXPECT_RESPONSE("UnregisterAppInterface", {success = true , resultCode = "SUCCESS"}) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_PTU_GetURLs_NoAppRegistered() local endpoints = {} testCasesForPolicyTableSnapshot:extract_pts() for i = 1, #testCasesForPolicyTableSnapshot.pts_endpoints do if (testCasesForPolicyTableSnapshot.pts_endpoints[i].service == "0x07") then endpoints[#endpoints + 1] = { url = testCasesForPolicyTableSnapshot.pts_endpoints[i].value, appID = testCasesForPolicyTableSnapshot.pts_endpoints[i].appID} end end local RequestId = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(RequestId,{result = {code = 0, method = "SDL.GetURLS"} } ) :Do(function(_,data) local is_correct = {} for i = 1, #data.result.urls do is_correct[i] = false for j = 1, #endpoints do if ( data.result.urls[i].url == endpoints[j].url ) then is_correct[i] = true end end end if(#data.result.urls ~= #endpoints ) then self:FailTestCase("Number of urls is not as expected: "..#endpoints..". Real: "..#data.result.urls) end for i = 1, #is_correct do if(is_correct[i] == false) then self:FailTestCase("url: "..data.result.urls[i].url.." is not correct. Expected: "..endpoints[i].url) end end end) end function Test:TestStep_PTU_DB_GetURLs_NoAppRegistered() local is_test_fail = false local policy_endpoints = {} local sevices_table = commonFunctions:get_data_policy_sql(config.pathToSDL.."/storage/policy.sqlite", "select service from endpoint") for _, value in pairs(sevices_table) do policy_endpoints[#policy_endpoints + 1] = { found = false, service = value } --TODO(istoimenova): Should be updated when policy defect is fixed if ( value == "4" or value == "7") then policy_endpoints[#policy_endpoints].found = true end end for i = 1, #policy_endpoints do if(policy_endpoints[i].found == false) then commonFunctions:printError("endpoints for service "..policy_endpoints[i].service .. " should not be observed." ) is_test_fail = true end end if(is_test_fail == true) then self:FailTestCase("Test is FAILED. See prints.") end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") testCasesForPolicyTable:Restore_preloaded_pt() function Test.Postcondition_Stop() 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
84d56b2a4755a499def7fa25ca62e2323727cdd0
modules/admin-full/luasrc/model/cbi/admin_system/system.lua
modules/admin-full/luasrc/model/cbi/admin_system/system.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> 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.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") m = Map("system", translate("system"), translate("a_s_desc")) s = m:section(TypedSection, "system", "") s.anonymous = true local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo() local uptime = luci.sys.uptime() s:option(DummyValue, "_system", translate("system")).value = system s:option(DummyValue, "_cpu", translate("m_i_processor")).value = model local load1, load5, load15 = luci.sys.loadavg() s:option(DummyValue, "_la", translate("load")).value = string.format("%.2f, %.2f, %.2f", load1, load5, load15) s:option(DummyValue, "_memtotal", translate("m_i_memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)", tonumber(memtotal) / 1024, 100 * memcached / memtotal, translate("mem_cached") or "", 100 * membuffers / memtotal, translate("mem_buffered") or "", 100 * memfree / memtotal, translate("mem_free") or "") s:option(DummyValue, "_systime", translate("m_i_systemtime")).value = os.date("%c") s:option(DummyValue, "_uptime", translate("m_i_uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) hn = s:option(Value, "hostname", translate("hostname")) function hn.write(self, section, value) Value.write(self, section, value) luci.sys.hostname(value) end tz = s:option(ListValue, "zonename", translate("timezone")) tz:value("UTC") for i, zone in ipairs(luci.sys.zoneinfo.TZ) do tz:value(zone[1]) end function tz.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(luci.sys.zoneinfo.TZ) do if zone[1] == title then return zone[2] end end end AbstractValue.write(self, section, value) self.map.uci:set("system", section, "timezone", lookup_zone(value) or "GMT0") end s:option(Value, "log_size", nil, "kiB").optional = true s:option(Value, "log_ip").optional = true s:option(Value, "conloglevel").optional = true s:option(Value, "cronloglevel").optional = true return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> 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.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") m = Map("system", translate("system"), translate("a_s_desc")) s = m:section(TypedSection, "system", "") s.anonymous = true local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo() local uptime = luci.sys.uptime() s:option(DummyValue, "_system", translate("system")).value = system s:option(DummyValue, "_cpu", translate("m_i_processor")).value = model local load1, load5, load15 = luci.sys.loadavg() s:option(DummyValue, "_la", translate("load")).value = string.format("%.2f, %.2f, %.2f", load1, load5, load15) s:option(DummyValue, "_memtotal", translate("m_i_memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)", tonumber(memtotal) / 1024, 100 * memcached / memtotal, tostring(translate("mem_cached", "")), 100 * membuffers / memtotal, tostring(translate("mem_buffered", "")), 100 * memfree / memtotal, tostring(translate("mem_free", "")) s:option(DummyValue, "_systime", translate("m_i_systemtime")).value = os.date("%c") s:option(DummyValue, "_uptime", translate("m_i_uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) hn = s:option(Value, "hostname", translate("hostname")) function hn.write(self, section, value) Value.write(self, section, value) luci.sys.hostname(value) end tz = s:option(ListValue, "zonename", translate("timezone")) tz:value("UTC") for i, zone in ipairs(luci.sys.zoneinfo.TZ) do tz:value(zone[1]) end function tz.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(luci.sys.zoneinfo.TZ) do if zone[1] == title then return zone[2] end end end AbstractValue.write(self, section, value) self.map.uci:set("system", section, "timezone", lookup_zone(value) or "GMT0") end s:option(Value, "log_size", nil, "kiB").optional = true s:option(Value, "log_ip").optional = true s:option(Value, "conloglevel").optional = true s:option(Value, "cronloglevel").optional = true return m
modules/admin-full: fix udata vs. string in system.lua model
modules/admin-full: fix udata vs. string in system.lua model
Lua
apache-2.0
8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci
c892d0b4609be7f83831b6faa13889c8efe975ef
openwrt/package/linkmeter/luasrc/model/cbi/linkmeter/alarm.lua
openwrt/package/linkmeter/luasrc/model/cbi/linkmeter/alarm.lua
require "lmclient" local json = require("luci.json") local lmcf = json.decode(LmClient():query("$LMCF")) local m, s, v m = Map("linkmeter", "Alarm Settings", [[Alarm trigger points and alert options. Enable an alarm by setting its threshold to a positive value, or checking the box beside it. Select the types of notifications to receive when the alarm is trigged. Inputting a 'Setpoint' will adjust the Pit setpoint.]]) -- -- Alarm Values -- s = m:section(TypedSection, "_hmconfig") s.template = "linkmeter/alarm-section" s.cfgsections = function(a,b,c) local retVal = {} for probe = 1,4 do retVal[probe] = tostring(probe-1) end return retVal end s.field = function(self, name) for k,v in pairs(self.fields) do if k == name then return v end end end -- probe_lm_* values that are stored in HeaterMeter local probe_lm_alvals = {} local function probe_lm_value(self, section) -- self.option will be the "palh" section will be 0,1,2,3 return tostring(lmcf[self.option .. section]) end local function probe_lm_write(self, section, value) -- Alarm high/low if self.option:sub(1,3) == "pal" then local idx = self.option:sub(-1) == "l" and 1 or 2 idx = idx + 2 * tonumber(section) while #probe_lm_alvals < idx do probe_lm_alvals[#probe_lm_alvals+1] = "" end probe_lm_alvals[idx] = value end lmcf[self.option .. section] = value end local PROBE_LM = { "pn", "pcurr", "pall", "palh" } for _,kv in ipairs(PROBE_LM) do v = s:option(Value, kv, kv) v.value = probe_lm_value v.cfgvalue = probe_lm_value v.write = probe_lm_write end local function saveProbeLm() if #probe_lm_alvals > 0 then local alvals = "$LMST,al," .. table.concat(probe_lm_alvals, ",") LmClient():query(alvals) end end -- probe_conf_* values that are stored in uci local function probe_conf_value(self, section) return m:get("alarms", self.option .. section) end local function probe_conf_write(self, section, value) return m:set("alarms", self.option .. section, value) end local PROBE_CONF = { "emaill", "smsl", "spl", "emailh", "smsh", "sph" } for _,kv in ipairs(PROBE_CONF) do v = s:option(Value, kv, kv) v.cfgvalue = probe_conf_value v.write = probe_conf_write end -- -- Email Notifications -- s = m:section(NamedSection, "alarms", "email", "Email Notifications", [[Email notifications only work if <a href="]] .. luci.dispatcher.build_url("admin/services/msmtp") .. [[">SMTP Client</a> is configured.]]) v = s:option(Value, "emailtoname", "Recipient name (optional)") v = s:option(Value, "emailtoaddress", "To email address") v = s:option(Value, "emailsubject", "Subject") local msg = s:option(TextValue, "_msg", "Message") msg.wrap = "off" msg.rows = 5 msg.rmempty = false local MSG_TEMPLATE = "/usr/share/linkmeter/email.txt" function msg.cfgvalue() return nixio.fs.readfile(MSG_TEMPLATE) or "" end function msg.write(self, section, value) if value then value = value:gsub("\r\n", "\n") if value ~= msg.cfgvalue() then nixio.fs.writefile(MSG_TEMPLATE, value) end end end -- -- SMS Notifications -- s = m:section(NamedSection, "alarms", "sms", "SMS Notifications", [[SMS notifications only work if <a href="]] .. luci.dispatcher.build_url("admin/services/msmtp") .. [[">SMTP Client</a> is configured.]]) local PROVIDERS = { { "AT&T", "txt.att.net", "ATT" }, { "Nextel", "messaging.nextel.com" }, { "Sprint", "messaging.sprintpcs.com" }, { "T-Mobile", "tmomail.net" }, { "Verizon", "vtext.com" }, { "Virgin Mobile", "vmobl.com" }, } local smsto = m:get("alarms", "smstoaddress") local smsphone, smsprovider = smsto:match("^(%d+)@(.+)$") v = s:option(Value, "_phone", "Phone number") v.cfgvalue = function() return smsphone end v.datatype = "phonedigit" v = s:option(ListValue, "_provider", "Provider") for i,p in ipairs(PROVIDERS) do local key = p[3] or p[1] v:value(key, p[1]) -- convert the @addr to the provider name if p[2] == smsprovider then v.cfgvalue = function () return key end end end v = s:option(Value, "smsmessage", "Message") -- -- Map Functions -- m.on_save = function (self) saveProbeLm() end return m
require "lmclient" local json = require("luci.json") local lmcf = json.decode(LmClient():query("$LMCF")) local m, s, v m = Map("linkmeter", "Alarm Settings", [[Alarm trigger points and alert options. Enable an alarm by setting its threshold to a positive value, or checking the box beside it. Select the types of notifications to receive when the alarm is trigged. Inputting a 'Setpoint' will adjust the Pit setpoint.]]) local ESCAPE_HELP = "All special characters (e.g. parens) must be escaped" -- -- Alarm Values -- s = m:section(TypedSection, "_hmconfig") s.template = "linkmeter/alarm-section" s.cfgsections = function(a,b,c) local retVal = {} for probe = 1,4 do retVal[probe] = tostring(probe-1) end return retVal end s.field = function(self, name) for k,v in pairs(self.fields) do if k == name then return v end end end -- probe_lm_* values that are stored in HeaterMeter local probe_lm_alvals = {} local function probe_lm_value(self, section) -- self.option will be the "palh" section will be 0,1,2,3 return tostring(lmcf[self.option .. section]) end local function probe_lm_write(self, section, value) -- Alarm high/low if self.option:sub(1,3) == "pal" then local idx = self.option:sub(-1) == "l" and 1 or 2 idx = idx + 2 * tonumber(section) while #probe_lm_alvals < idx do probe_lm_alvals[#probe_lm_alvals+1] = "" end probe_lm_alvals[idx] = value end lmcf[self.option .. section] = value end local PROBE_LM = { "pn", "pcurr", "pall", "palh" } for _,kv in ipairs(PROBE_LM) do v = s:option(Value, kv, kv) v.value = probe_lm_value v.cfgvalue = probe_lm_value v.write = probe_lm_write end local function saveProbeLm() if #probe_lm_alvals > 0 then local alvals = "$LMST,al," .. table.concat(probe_lm_alvals, ",") LmClient():query(alvals) end end -- probe_conf_* values that are stored in uci local function probe_conf_value(self, section) return m:get("alarms", self.option .. section) end local function probe_conf_write(self, section, value) return m:set("alarms", self.option .. section, value) end local function probe_conf_remove(self, section) return m:del("alarms", self.option .. section) end local PROBE_CONF = { "emaill", "smsl", "spl", "emailh", "smsh", "sph" } for _,kv in ipairs(PROBE_CONF) do v = s:option(Value, kv, kv) v.cfgvalue = probe_conf_value v.write = probe_conf_write v.remove = probe_conf_remove end -- -- Email Notifications -- s = m:section(NamedSection, "alarms", "email", "Email Notifications", [[Email notifications only work if <a href="]] .. luci.dispatcher.build_url("admin/services/msmtp") .. [[">SMTP Client</a> is configured.]]) v = s:option(Value, "emailtoname", "Recipient name (optional)") v = s:option(Value, "emailtoaddress", "To email address") v = s:option(Value, "emailsubject", "Subject") local msg = s:option(TextValue, "_msg", "Message") msg.wrap = "off" msg.rows = 5 msg.rmempty = false msg.description = ESCAPE_HELP local MSG_TEMPLATE = "/usr/share/linkmeter/email.txt" function msg.cfgvalue() return nixio.fs.readfile(MSG_TEMPLATE) or "" end function msg.write(self, section, value) if value then value = value:gsub("\r\n", "\n") if value ~= msg.cfgvalue() then nixio.fs.writefile(MSG_TEMPLATE, value) end end end -- -- SMS Notifications -- s = m:section(NamedSection, "alarms", "sms", "SMS Notifications", [[SMS notifications only work if <a href="]] .. luci.dispatcher.build_url("admin/services/msmtp") .. [[">SMTP Client</a> is configured.]]) local PROVIDERS = { { "AT&T", "txt.att.net", "ATT" }, { "Nextel", "messaging.nextel.com" }, { "Sprint", "messaging.sprintpcs.com" }, { "T-Mobile", "tmomail.net" }, { "Verizon", "vtext.com" }, { "Virgin Mobile", "vmobl.com" }, } local smsto = m:get("alarms", "smstoaddress") local smsphone, smsprovider = smsto:match("^(%d+)@(.+)$") v = s:option(Value, "_phone", "Phone number") v.cfgvalue = function() return smsphone end v.datatype = "phonedigit" v = s:option(ListValue, "_provider", "Provider") for i,p in ipairs(PROVIDERS) do local key = p[3] or p[1] v:value(key, p[1]) -- convert the @addr to the provider name if p[2] == smsprovider then v.cfgvalue = function () return key end end end v = s:option(Value, "smsmessage", "Message") v.description = ESCAPE_HELP -- -- Map Functions -- m.on_save = function (self) saveProbeLm() end return m
[lm] Fix not being able to disable alert actions
[lm] Fix not being able to disable alert actions Also add help text about special shell characters, which blows up the alarm script.
Lua
mit
kdakers80/HeaterMeter,dwright134/HeaterMeter,CapnBry/HeaterMeter,kdakers80/HeaterMeter,dwright134/HeaterMeter,kdakers80/HeaterMeter,kdakers80/HeaterMeter,CapnBry/HeaterMeter,dwright134/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,kdakers80/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,dwright134/HeaterMeter,kdakers80/HeaterMeter,dwright134/HeaterMeter,shmick/HeaterMeter,shmick/HeaterMeter,shmick/HeaterMeter
c269ec9f53a789877fc3254496f38395760dd9e3
lua/entities/gmod_wire_starfall_processor/init.lua
lua/entities/gmod_wire_starfall_processor/init.lua
AddCSLuaFile('cl_init.lua') AddCSLuaFile('shared.lua') include('shared.lua') include("starfall/SFLib.lua") assert(SF, "Starfall didn't load correctly!") ENT.WireDebugName = "Starfall Processor" ENT.OverlayDelay = 0 local context = SF.CreateContext() local name = nil function ENT:UpdateState(state) if name then self:SetOverlayText("Starfall Processor\n"..name.."\n"..state) else self:SetOverlayText("Starfall Processor\n"..state) end end function ENT:Initialize() self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) self.Inputs = WireLib.CreateInputs(self, {}) self.Outputs = WireLib.CreateOutputs(self, {}) self:UpdateState("Inactive (No code)") local r,g,b,a = self:GetColor() self:SetColor(255, 0, 0, a) end function ENT:Compile(codetbl, mainfile) if self.instance then self.instance:deinitialize() end local ok, instance = SF.Compiler.Compile(codetbl,context,mainfile,self.owner) if not ok then self:Error(instance) return end self.instance = instance instance.data.entity = self local ok, msg = instance:initialize() if not ok then self:Error(msg) return end if self.instance.ppdata.scriptnames and self.instance.mainfile and self.instance.ppdata.scriptnames[self.instance.mainfile] then name = tostring(self.instance.ppdata.scriptnames[self.instance.mainfile]) end if not name or string.len(name) <= 0 then name = "generic" end self:UpdateState("(None)") local r,g,b,a = self:GetColor() self:SetColor(255, 255, 255, a) end function ENT:Error(msg, traceback) ErrorNoHalt("Processor of "..self.owner:Nick().." errored: "..msg.."\n") if traceback then print(traceback) end WireLib.ClientError(msg, self.owner) if self.instance then self.instance:deinitialize() self.instance = nil end self:UpdateState("Inactive (Error)") local r,g,b,a = self:GetColor() self:SetColor(255, 0, 0, a) end function ENT:Think() self.BaseClass.Think(self) if self.instance and not self.instance.error then self:UpdateState(tostring(self.instance.ops).." ops, "..tostring(math.floor(self.instance.ops / self.instance.context.ops * 100)).."%") self.instance:resetOps() self:RunScriptHook("think") end self:NextThink(CurTime()) return true end function ENT:OnRemove() if not self.instance then return end self.instance:deinitialize() self.instance = nil end function ENT:TriggerInput(key, value) self:RunScriptHook("input",key, SF.Wire.InputConverters[self.Inputs[key].Type](value)) end function ENT:ReadCell(address) return tonumber(self:RunScriptHookForResult("readcell",address)) or 0 end function ENT:WriteCell(address, data) self:RunScriptHook("writecell",address,data) end function ENT:RunScriptHook(hook, ...) if self.instance and not self.instance.error and self.instance.hooks[hook:lower()] then local ok, rt = self.instance:runScriptHook(hook, ...) if not ok then self:Error(rt) end end end function ENT:RunScriptHookForResult(hook,...) if self.instance and not self.instance.error and self.instance.hooks[hook:lower()] then local ok, rt = self.instance:runScriptHookForResult(hook, ...) if not ok then self:Error(rt) else return rt end end end function ENT:OnRestore() end function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} if self.instance then info.starfall = SF.SerializeCode(self.instance.source, self.instance.mainfile) end return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) self.owner = ply if info.starfall then local code, main = SF.DeserializeCode(info.starfall) self:Compile(code, main) end end
AddCSLuaFile('cl_init.lua') AddCSLuaFile('shared.lua') include('shared.lua') include("starfall/SFLib.lua") assert(SF, "Starfall didn't load correctly!") ENT.WireDebugName = "Starfall Processor" ENT.OverlayDelay = 0 local context = SF.CreateContext() local name = nil function ENT:UpdateState(state) if name then self:SetOverlayText("Starfall Processor\n"..name.."\n"..state) else self:SetOverlayText("Starfall Processor\n"..state) end end function ENT:Initialize() self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) self.Inputs = WireLib.CreateInputs(self, {}) self.Outputs = WireLib.CreateOutputs(self, {}) self:UpdateState("Inactive (No code)") local clr = self:GetColor() self:SetColor(Color(255, 0, 0, clr.a)) end function ENT:Compile(codetbl, mainfile) if self.instance then self.instance:deinitialize() end local ok, instance = SF.Compiler.Compile(codetbl,context,mainfile,self.owner) if not ok then self:Error(instance) return end self.instance = instance instance.data.entity = self local ok, msg = instance:initialize() if not ok then self:Error(msg) return end if self.instance.ppdata.scriptnames and self.instance.mainfile and self.instance.ppdata.scriptnames[self.instance.mainfile] then name = tostring(self.instance.ppdata.scriptnames[self.instance.mainfile]) end if not name or string.len(name) <= 0 then name = "generic" end self:UpdateState("(None)") local clr = self:GetColor() self:SetColor(Color(255, 255, 255, clr.a)) end function ENT:Error(msg, traceback) ErrorNoHalt("Processor of "..self.owner:Nick().." errored: "..msg.."\n") if traceback then print(traceback) end WireLib.ClientError(msg, self.owner) if self.instance then self.instance:deinitialize() self.instance = nil end self:UpdateState("Inactive (Error)") local clr = self:GetColor() self:SetColor(Color(255, 0, 0, clr.a)) end function ENT:Think() self.BaseClass.Think(self) if self.instance and not self.instance.error then self:UpdateState(tostring(self.instance.ops).." ops, "..tostring(math.floor(self.instance.ops / self.instance.context.ops * 100)).."%") self.instance:resetOps() self:RunScriptHook("think") end self:NextThink(CurTime()) return true end function ENT:OnRemove() if not self.instance then return end self.instance:deinitialize() self.instance = nil end function ENT:TriggerInput(key, value) self:RunScriptHook("input",key, SF.Wire.InputConverters[self.Inputs[key].Type](value)) end function ENT:ReadCell(address) return tonumber(self:RunScriptHookForResult("readcell",address)) or 0 end function ENT:WriteCell(address, data) self:RunScriptHook("writecell",address,data) end function ENT:RunScriptHook(hook, ...) if self.instance and not self.instance.error and self.instance.hooks[hook:lower()] then local ok, rt = self.instance:runScriptHook(hook, ...) if not ok then self:Error(rt) end end end function ENT:RunScriptHookForResult(hook,...) if self.instance and not self.instance.error and self.instance.hooks[hook:lower()] then local ok, rt = self.instance:runScriptHookForResult(hook, ...) if not ok then self:Error(rt) else return rt end end end function ENT:OnRestore() end function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} if self.instance then info.starfall = SF.SerializeCode(self.instance.source, self.instance.mainfile) end return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) self.owner = ply if info.starfall then local code, main = SF.DeserializeCode(info.starfall) self:Compile(code, main) end end
fixed it being purple
fixed it being purple Fixes #1
Lua
bsd-3-clause
Ingenious-Gaming/Starfall,INPStarfall/Starfall,Xandaros/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall,Jazzelhawk/Starfall,Jazzelhawk/Starfall,INPStarfall/Starfall