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
bb595a1cbe8d4a4fe7e09e3884fe0fc9734a7d12
util/stanza.lua
util/stanza.lua
local t_insert = table.insert; local t_remove = table.remove; local s_format = string.format; local tostring = tostring; local setmetatable = setmetatable; local pairs = pairs; local ipairs = ipairs; local type = type; local unpack = unpack; local s_gsub = string.gsub; module "stanza" stanza_mt = {}; stanza_mt.__index = stanza_mt; function stanza(name, attr) local stanza = { name = name, attr = attr or {}, tags = {}, last_add = {}}; return setmetatable(stanza, stanza_mt); end function stanza_mt:query(xmlns) return self:tag("query", { xmlns = xmlns }); end function stanza_mt:tag(name, attrs) local s = stanza(name, attrs); (self.last_add[#self.last_add] or self):add_child(s); t_insert(self.last_add, s); return self; end function stanza_mt:text(text) (self.last_add[#self.last_add] or self):add_child(text); return self; end function stanza_mt:up() t_remove(self.last_add); return self; end function stanza_mt:add_child(child) if type(child) == "table" then t_insert(self.tags, child); end t_insert(self, child); end function stanza_mt:child_with_name(name) for _, child in ipairs(self) do if child.name == name then return child; end end end function stanza_mt:children() local i = 0; return function (a) i = i + 1 local v = a[i] if v then return v; end end, self, i; end function stanza_mt:childtags() local i = 0; return function (a) i = i + 1 local v = self.tags[i] if v then return v; end end, self.tags[1], i; end do local xml_entities = { ["'"] = "&apos;", ["\""] = "&quot;", ["<"] = "&lt;", [">"] = "&gt;", ["&"] = "&amp;" }; function xml_escape(s) return s_gsub(s, "['&<>\"]", xml_entities); end end local xml_escape = xml_escape; function stanza_mt.__tostring(t) local children_text = ""; for n, child in ipairs(t) do if type(child) == "string" then children_text = children_text .. xml_escape(child); else children_text = children_text .. tostring(child); end end local attr_string = ""; if t.attr then for k, v in pairs(t.attr) do if type(k) == "string" then attr_string = attr_string .. s_format(" %s='%s'", k, tostring(v)); end end end return s_format("<%s%s>%s</%s>", t.name, attr_string, children_text, t.name); end function stanza_mt.__add(s1, s2) return s1:add_child(s2); end do local id = 0; function new_id() id = id + 1; return "lx"..id; end end function preserialize(stanza) local s = { name = stanza.name, attr = stanza.attr }; for _, child in ipairs(stanza) do if type(child) == "table" then t_insert(s, preserialize(child)); else t_insert(s, child); end end return s; end function deserialize(stanza) -- Set metatable setmetatable(stanza, stanza_mt); for _, child in ipairs(stanza) do if type(child) == "table" then deserialize(child); end end if not stanza.tags then -- Rebuild tags local tags = {}; for _, child in ipairs(stanza) do if type(child) == "table" then t_insert(tags, child); end end stanza.tags = tags; end return stanza; end function message(attr, body) if not body then return stanza("message", attr); else return stanza("message", attr):tag("body"):text(body); end end function iq(attr) if attr and not attr.id then attr.id = new_id(); end return stanza("iq", attr or { id = new_id() }); end function reply(orig) return stanza(orig.name, orig.attr and { to = orig.attr.from, from = orig.attr.to, id = orig.attr.id, type = ((orig.name == "iq" and "result") or nil) }); end function error_reply(orig, type, condition, message, clone) local t = reply(orig); t.attr.type = "error"; -- TODO use clone t:tag("error", {type = type}) :tag(condition, {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}):up(); if (message) then t:tag("text"):text(message):up(); end return t; -- stanza ready for adding app-specific errors end function presence(attr) return stanza("presence", attr); end return _M;
local t_insert = table.insert; local t_remove = table.remove; local s_format = string.format; local tostring = tostring; local setmetatable = setmetatable; local pairs = pairs; local ipairs = ipairs; local type = type; local unpack = unpack; local s_gsub = string.gsub; module "stanza" stanza_mt = {}; stanza_mt.__index = stanza_mt; function stanza(name, attr) local stanza = { name = name, attr = attr or {}, tags = {}, last_add = {}}; return setmetatable(stanza, stanza_mt); end function stanza_mt:query(xmlns) return self:tag("query", { xmlns = xmlns }); end function stanza_mt:tag(name, attrs) local s = stanza(name, attrs); (self.last_add[#self.last_add] or self):add_child(s); t_insert(self.last_add, s); return self; end function stanza_mt:text(text) (self.last_add[#self.last_add] or self):add_child(text); return self; end function stanza_mt:up() t_remove(self.last_add); return self; end function stanza_mt:add_child(child) if type(child) == "table" then t_insert(self.tags, child); end t_insert(self, child); end function stanza_mt:child_with_name(name) for _, child in ipairs(self) do if child.name == name then return child; end end end function stanza_mt:children() local i = 0; return function (a) i = i + 1 local v = a[i] if v then return v; end end, self, i; end function stanza_mt:childtags() local i = 0; return function (a) i = i + 1 local v = self.tags[i] if v then return v; end end, self.tags[1], i; end do local xml_entities = { ["'"] = "&apos;", ["\""] = "&quot;", ["<"] = "&lt;", [">"] = "&gt;", ["&"] = "&amp;" }; function xml_escape(s) return s_gsub(s, "['&<>\"]", xml_entities); end end local xml_escape = xml_escape; function stanza_mt.__tostring(t) local children_text = ""; for n, child in ipairs(t) do if type(child) == "string" then children_text = children_text .. xml_escape(child); else children_text = children_text .. tostring(child); end end local attr_string = ""; if t.attr then for k, v in pairs(t.attr) do if type(k) == "string" then attr_string = attr_string .. s_format(" %s='%s'", k, tostring(v)); end end end return s_format("<%s%s>%s</%s>", t.name, attr_string, children_text, t.name); end function stanza_mt.__add(s1, s2) return s1:add_child(s2); end do local id = 0; function new_id() id = id + 1; return "lx"..id; end end function preserialize(stanza) local s = { name = stanza.name, attr = stanza.attr }; for _, child in ipairs(stanza) do if type(child) == "table" then t_insert(s, preserialize(child)); else t_insert(s, child); end end return s; end function deserialize(stanza) -- Set metatable if stanza then setmetatable(stanza, stanza_mt); for _, child in ipairs(stanza) do if type(child) == "table" then deserialize(child); end end if not stanza.tags then -- Rebuild tags local tags = {}; for _, child in ipairs(stanza) do if type(child) == "table" then t_insert(tags, child); end end stanza.tags = tags; end end return stanza; end function message(attr, body) if not body then return stanza("message", attr); else return stanza("message", attr):tag("body"):text(body); end end function iq(attr) if attr and not attr.id then attr.id = new_id(); end return stanza("iq", attr or { id = new_id() }); end function reply(orig) return stanza(orig.name, orig.attr and { to = orig.attr.from, from = orig.attr.to, id = orig.attr.id, type = ((orig.name == "iq" and "result") or nil) }); end function error_reply(orig, type, condition, message, clone) local t = reply(orig); t.attr.type = "error"; -- TODO use clone t:tag("error", {type = type}) :tag(condition, {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}):up(); if (message) then t:tag("text"):text(message):up(); end return t; -- stanza ready for adding app-specific errors end function presence(attr) return stanza("presence", attr); end return _M;
Fixed: util.stanza.deserialize now handles nil stanzas
Fixed: util.stanza.deserialize now handles nil stanzas
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
28414516c931d2e87ee268a4a0444ef7765bcf45
resources/stdlibrary/stdfuncs.lua
resources/stdlibrary/stdfuncs.lua
function assert(v, message) end function collectgarbage(opt, arg) end function dofile(filename) end function error(message, level) end function getfenv(f) end function getmetatable(object) end function ipairs (t) end function load(func, optChunkname) end function loadfile (filename) end function loadstring (string, chunkname) end function next(table, index) end function pairs(t) end function pcall (f, arg1, ...) end function print (...) end function rawequal (v1, v2) end function rawget (table, index) end function rawset (table, index, value) end function select (index, ...) end function setfenv (f, table) end function setmetatable (table, metatable) end function tonumber (e, base) end function tostring (e) end function type (v) end function unpack (list , i , j) end function xpcall (f, err) end function module (name, ...) end function require (modname) end _VERSION = "string" _G = {} coroutine = {} debug = {} io = {} math = {} os = {} package = {} string = {} table = {} --file = {} function coroutine.create() end function coroutine.resume() end function coroutine.running() end function coroutine.status() end function coroutine.wrap() end function coroutine.yield() end function debug.debug() end function debug.getfenv() end function debug.gethook() end function debug.getinfo() end function debug.getlocal() end function debug.getmetatable() end function debug.getregistry() end function debug.getupvalue() end function debug.setfenv() end function debug.sethook() end function debug.setlocal() end function debug.setmetatable() end function debug.setupvalue() end function debug.traceback() end function io.close() end function io.flush() end function io.input() end function io.lines() end function io.open() end function io.output() end function io.popen() end function io.read() end function io.tmpfile() end function io.type() end function io.write() end function math.abs() end function math.acos() end function math.asin() end function math.atan() end function math.atan() end function math.ceil() end function math.cos() end function math.cosh() end function math.deg() end function math.exp() end function math.floor() end function math.fmod() end function math.frexp() end function math.huge() end function math.ldexp() end function math.log() end function math.log() end function math.max() end function math.min() end function math.modf() end math.pi = 3.1415 function math.pow() end function math.rad() end function math.random() end function math.randomseed() end function math.sin() end function math.sinh() end function math.sqrt() end function math.tan() end function math.tanh() end function os.clock() end function os.date() end function os.difftime() end function os.execute() end function os.exit() end function os.getenv() end function os.remove() end function os.rename() end function os.setlocale() end function os.time() end function os.tmpname() end -- Resolving these requires the "Enable Additional Completions" option in Settings|Lua function file:close() end function file:flush() end function file:lines() end function file:read() end function file:seek() end function file:setvbuf() end function file:write() end function package.cpath() end function package.loaded() end function package.loaders() end function package.loadlib() end function package.path() end function package.preload() end function package.seeall() end function string.byte() end function string.char() end function string.dump() end function string.find() end function string.format() end function string.gmatch() end function string.gsub() end function string.len() end function string.lower() end function string.match() end function string.rep() end function string.reverse() end function string.sub() end function string.upper() end function table.concat() end function table.insert() end function table.maxn() end function table.remove() end function table.sort() end
function assert(v, message) end function collectgarbage(opt, arg) end function dofile(filename) end function error(message, level) end function getfenv(f) end function getmetatable(object) end function ipairs (t) end function load(func, optChunkname) end function loadfile (filename) end function loadstring (string, chunkname) end function next(table, index) end function pairs(t) end function pcall (f, arg1, ...) end function print (...) end function rawequal (v1, v2) end function rawget (table, index) end function rawset (table, index, value) end function select (index, ...) end function setfenv (f, table) end function setmetatable (table, metatable) end function tonumber (e, base) end function tostring (e) end function type (v) end function unpack (list , i , j) end function xpcall (f, err) end function module (name, ...) end function require (modname) end _VERSION = "string" _G = {} coroutine = {} debug = {} io = {} math = {} os = {} package = {} string = {} table = {} --file = {} function coroutine.create() end function coroutine.resume() end function coroutine.running() end function coroutine.status() end function coroutine.wrap() end function coroutine.yield() end function debug.debug() end function debug.getfenv() end function debug.gethook() end function debug.getinfo() end function debug.getlocal() end function debug.getmetatable() end function debug.getregistry() end function debug.getupvalue() end function debug.setfenv() end function debug.sethook() end function debug.setlocal() end function debug.setmetatable() end function debug.setupvalue() end function debug.traceback() end function io.close() end function io.flush() end function io.input() end function io.lines() end function io.open() end function io.output() end function io.popen() end function io.read() end function io.tmpfile() end function io.type() end function io.write() end io.stdin = true io.stdout= true function math.abs() end function math.acos() end function math.asin() end function math.atan() end function math.atan() end function math.ceil() end function math.cos() end function math.cosh() end function math.deg() end function math.exp() end function math.floor() end function math.fmod() end function math.frexp() end function math.huge() end function math.ldexp() end function math.log() end function math.log() end function math.max() end function math.min() end function math.modf() end math.pi = 3.1415 function math.pow() end function math.rad() end function math.random() end function math.randomseed() end function math.sin() end function math.sinh() end function math.sqrt() end function math.tan() end function math.tanh() end function os.clock() end function os.date() end function os.difftime() end function os.execute() end function os.exit() end function os.getenv() end function os.remove() end function os.rename() end function os.setlocale() end function os.time() end function os.tmpname() end -- Resolving these requires the "Enable Additional Completions" option in Settings|Lua function file:close() end function file:flush() end function file:lines() end function file:read() end function file:seek() end function file:setvbuf() end function file:write() end function package.cpath() end function package.loaded() end function package.loaders() end function package.loadlib() end function package.path() end function package.preload() end function package.seeall() end function string.byte() end function string.char() end function string.dump() end function string.find() end function string.format() end function string.gmatch() end function string.gsub() end function string.len() end function string.lower() end function string.match() end function string.rep() end function string.reverse() end function string.sub() end function string.upper() end function table.concat() end function table.insert() end function table.maxn() end function table.remove() end function table.sort() end
add io.stdin/io.stdout to stdfuncs (fix #64)
add io.stdin/io.stdout to stdfuncs (fix #64)
Lua
apache-2.0
internetisalie/lua-for-idea,internetisalie/lua-for-idea,internetisalie/lua-for-idea,internetisalie/lua-for-idea
2740edee75c63f485e213dc0280ec52af4898b82
pud/entity/EntityRegistry.lua
pud/entity/EntityRegistry.lua
local Class = require 'lib.hump.class' -- EntityRegistry -- local EntityRegistry = Class{name='EntityRegistry', function(self) self._registry = {} self._byname = {} self._bytype = {} end } -- destructor function EntityRegistry:destroy() for k in pairs(self._registry) do self._registry[k]:destroy() self._registry[k] = nil end self._registry = nil for k,v in pairs(self._byname) do for j in pairs(v) do v[j] = nil end self._byname[k] = nil end self._byname = nil for k,v in pairs(self._bytype) do for j in pairs(v) do v[j] = nil end self._bytype[k] = nil end self._bytype = nil end function EntityRegistry:register(entity) verifyClass('pud.entity.Entity', entity) local id = entity:getID() local name = entity:getName() local etype = entity:getEntityType() verify('number', id) verify('string', name, etype) if nil ~= self._registry[id] then warning('Entity registration overwitten: %s (%d)', name, id) end self._registry[id] = entity self._byname[name] = self._byname[name] or {} local num = #(self._byname[name]) self._byname[name][num+1] = id self._bytype[etype] = self._bytype[etype] or {} num = #(self._bytype[etype]) self._bytype[etype][num+1] = id end local _removeID = function(id, t) local found = false for k,v in pairs(t) do local num = #v local new = {} local newCount = 1 for i=1,num do if v[i] == id then found = true else new[newCount] = v[i] newCount = newCount + 1 end v[i] = nil end if #new == 0 then t[k] = nil else t[k] = new end if found then break end end end function EntityRegistry:unregister(id) local entity = self._registry[id] assert(entity, 'No such entity to unregister: %d', id) self._registry[id] = nil _removeID(id, self._byname) _removeID(id, self._bytype) return entity end function EntityRegistry:exists(id) return self._registry[id] ~= nil end function EntityRegistry:get(id) return self._registry[id] end function EntityRegistry:getIDsByName(name) return self._byname[name] end function EntityRegistry:getIDsByType(etype) return self._bytype[etype] end local _byElevel = function(a, b) if nil == a then return false end if nil == b then return true end local al = a:getELevel() local bl = b:getELevel() if nil == al then return false end if nil == bl then return true end return al < bl end -- debug function to print all entities to console by elevel function EntityRegistry:dumpEntities() local ents = setmetatable({}, {__mode='kv'}) local hero = self._bytype['hero'] local enemy = self._bytype['enemy'] local item = self._bytype['item'] local num, count = 0, 0 num = #hero for i=1,num do local id = hero[i] count = count + 1 ents[count] = self:get(id) end num = #enemy for i=1,num do local id = enemy[i] count = count + 1 ents[count] = self:get(id) end num = #item for i=1,num do local id = item[i] count = count + 1 ents[count] = self:get(id) end if count > 0 then table.sort(ents, _byElevel) Console:print('Registered Entities:') Console:print(' %-11s %4s %s', 'ID', 'ELVL', 'NAME') for i=1,count do local e = ents[i] local id = e:getID() or -1 local elevel = e:getELevel() or -1 local name = e:getName() or '?' Console:print(' {%08d} %4d %s', id, elevel, name) end else Console:print('RED', 'No entities to dump!') end end -- the class return EntityRegistry
local Class = require 'lib.hump.class' -- EntityRegistry -- local EntityRegistry = Class{name='EntityRegistry', function(self) self._registry = {} self._byname = {} self._bytype = {} end } -- destructor function EntityRegistry:destroy() for k in pairs(self._registry) do self._registry[k]:destroy() self._registry[k] = nil end self._registry = nil for k,v in pairs(self._byname) do for j in pairs(v) do v[j] = nil end self._byname[k] = nil end self._byname = nil for k,v in pairs(self._bytype) do for j in pairs(v) do v[j] = nil end self._bytype[k] = nil end self._bytype = nil end function EntityRegistry:register(entity) verifyClass('pud.entity.Entity', entity) local id = entity:getID() local name = entity:getName() local etype = entity:getEntityType() verify('number', id) verify('string', name, etype) if nil ~= self._registry[id] then warning('Entity registration overwitten: %s (%d)', name, id) end self._registry[id] = entity self._byname[name] = self._byname[name] or {} local num = #(self._byname[name]) self._byname[name][num+1] = id self._bytype[etype] = self._bytype[etype] or {} num = #(self._bytype[etype]) self._bytype[etype][num+1] = id end local _removeID = function(id, t) local found = false for k,v in pairs(t) do local num = #v local new = {} local newCount = 1 for i=1,num do if v[i] == id then found = true else new[newCount] = v[i] newCount = newCount + 1 end v[i] = nil end if #new == 0 then t[k] = nil else t[k] = new end if found then break end end end function EntityRegistry:unregister(id) local entity = self._registry[id] assert(entity, 'No such entity to unregister: %d', id) self._registry[id] = nil _removeID(id, self._byname) _removeID(id, self._bytype) return entity end function EntityRegistry:exists(id) return self._registry[id] ~= nil end function EntityRegistry:get(id) return self._registry[id] end function EntityRegistry:getIDsByName(name) return self._byname[name] end function EntityRegistry:getIDsByType(etype) return self._bytype[etype] end local _byElevel = function(a, b) if nil == a then return false end if nil == b then return true end local al = a:getELevel() local bl = b:getELevel() if nil == al then return false end if nil == bl then return true end return al < bl end -- debug function to print all entities to console by elevel function EntityRegistry:dumpEntities() local ents = setmetatable({}, {__mode='kv'}) local hero = self._bytype['hero'] local enemy = self._bytype['enemy'] local item = self._bytype['item'] local num, count = 0, 0 if hero then num = #hero for i=1,num do local id = hero[i] count = count + 1 ents[count] = self:get(id) end end if enemy then num = #enemy for i=1,num do local id = enemy[i] count = count + 1 ents[count] = self:get(id) end end if item then num = #item for i=1,num do local id = item[i] count = count + 1 ents[count] = self:get(id) end end if count > 0 then table.sort(ents, _byElevel) Console:print('Registered Entities:') Console:print(' %-11s %4s %s', 'ID', 'ELVL', 'NAME') for i=1,count do local e = ents[i] local id = e:getID() or -1 local elevel = e:getELevel() or -1 local name = e:getName() or '?' Console:print(' {%08d} %4d %s', id, elevel, name) end else Console:print('RED', 'No entities to dump!') end end -- the class return EntityRegistry
fix dumpEntities when entities don't exist
fix dumpEntities when entities don't exist
Lua
mit
scottcs/wyx
1c5d07414e8455b8ef1df6e86b0e3cc71d5865a6
src/main/resources/moe/lymia/mppatch/data/patch/hooks/before_stagingroom.lua
src/main/resources/moe/lymia/mppatch/data/patch/hooks/before_stagingroom.lua
if _mpPatch and _mpPatch.enabled then Modding = _mpPatch.hookTable(Modding, {ActivateAllowedDLC = function(...) _mpPatch.overrideModsFromPreGame() return Modding._super.ActivateAllowedDLC(...) end}) Matchmaking = _mpPatch.hookTable(Matchmaking, {LaunchMultiplayerGame = function(...) _mpPatch.overrideModsFromPreGame() return Matchmaking._super.LaunchMultiplayerGame(...) end}) if _mpPatch.isModding then _mpPatch.setBIsModding() end local MultiplayerGameLaunchedHook_added = true local MultiplayerGameLaunchedHook_remove local function MultiplayerGameLaunchedHook() if not Matchmaking.IsHost() then _mpPatch.overrideModsFromPreGame() end MultiplayerGameLaunchedHook_remove() end MultiplayerGameLaunchedHook_remove = function() if MultiplayerGameLaunchedHook_added then Events.MultiplayerGameLaunched.Remove(MultiplayerGameLaunchedHook) MultiplayerGameLaunchedHook_added = false end end Events.MultiplayerGameLaunched.Add(MultiplayerGameLaunchedHook) _mpPatch.patch.globals.rawset(UIManager, "DequeuePopup", function(this, ...) local context = ... if context == ContextPtr then MultiplayerGameLaunchedHook_remove() end return UIManager._super.DequeuePopup(UIManager._super, ...) end) end
if _mpPatch and _mpPatch.enabled then Modding = _mpPatch.hookTable(Modding, {ActivateAllowedDLC = function(...) _mpPatch.overrideModsFromPreGame() return Modding._super.ActivateAllowedDLC(...) end}) Matchmaking = _mpPatch.hookTable(Matchmaking, {LaunchMultiplayerGame = function(...) _mpPatch.overrideModsFromPreGame() return Matchmaking._super.LaunchMultiplayerGame(...) end}) if _mpPatch.isModding then _mpPatch.setBIsModding() end local MultiplayerGameLaunchedHook_added = true local MultiplayerGameLaunchedHook_remove local function MultiplayerGameLaunchedHook() if not Matchmaking.IsHost() then _mpPatch.overrideModsFromPreGame() end MultiplayerGameLaunchedHook_remove() end MultiplayerGameLaunchedHook_remove = function() if MultiplayerGameLaunchedHook_added then Events.MultiplayerGameLaunched.Remove(MultiplayerGameLaunchedHook) MultiplayerGameLaunchedHook_added = false end end Events.MultiplayerGameLaunched.Add(MultiplayerGameLaunchedHook) local DequeuePopup = UIManager.DequeuePopup _mpPatch.patch.globals.rawset(UIManager, "DequeuePopup", function(this, ...) local context = ... if context == ContextPtr then MultiplayerGameLaunchedHook_remove() end return DequeuePopup(UIManager, ...) end) end
... more patch fixing.
... more patch fixing.
Lua
mit
Lymia/MPPatch,Lymia/MultiverseModManager,Lymia/MPPatch,Lymia/MPPatch,Lymia/MPPatch,Lymia/CivV_Mod2DLC,Lymia/MultiverseModManager
22a20e104e3d8d9e800f452398d33e18cfadcb9d
lua/entities/gmod_wire_expression2/core/cl_hologram.lua
lua/entities/gmod_wire_expression2/core/cl_hologram.lua
-- Replicated from serverside, same function as the one below except this takes precedence local holoDisplayCVar = GetConVar("wire_holograms_display_owners_maxdist") local holoDisplayCVarCL = CreateClientConVar( "wire_holograms_display_owners_maxdist_cl" , "-1", true, false, "The maximum distance that wire_holograms_display_owners will allow names to be seen. -1 for original function.", -1, 32768) local function WireHologramsShowOwners() local eye = EyePos() local entList = ents.FindByClass( "gmod_wire_hologram" ) local finalEntList = {} local finalCVar = 0 -- Both cvars, server-replicated and clientside local cva = holoDisplayCVar:GetInt() local cvb = holoDisplayCVarCL:GetInt() if cva == -1 then -- Server allows mapwide visibility for display, default to the client's setting finalCVar = cvb else if cvb >= 0 then -- Use whichever value is lower, as long as the client isn't trying to get mapwide visibility of names while the server prevents it finalCVar = math.min( cva, cvb) else -- If all else fails, settle with what the server is using finalCVar = cva end end local holoDisplayDist = finalCVar ^ 2 if finalCVar > 0 then -- Can't check for -1 from the above variable since it is squared, and it needs to be squared for performance reasons comparing distances for _,ent in pairs( entList ) do local distToEye = eye:DistToSqr( ent:GetPos() ) if distToEye < holoDisplayDist then finalEntList[ #finalEntList + 1 ] = ent end end else -- Default to the original function of showing ALL holograms -- if, in the end, both are 0, why even bother trying to do it at all (and why is this running?) if finalCVar == -1 then finalEntList = entList end end for _,ent in pairs( finalEntList ) do local id = ent:GetNWInt( "ownerid" ) for _,ply in pairs( player.GetAll() ) do if ply:UserID() == id then local vec = ent:GetPos():ToScreen() draw.DrawText( ply:Name() .. "\n" .. ply:SteamID(), "DermaDefault", vec.x, vec.y, Color(255,0,0,255), 1 ) break end end end end local display_owners = false concommand.Add( "wire_holograms_display_owners", function() display_owners = !display_owners if display_owners then hook.Add( "HUDPaint", "wire_holograms_showowners", WireHologramsShowOwners) else hook.Remove("HUDPaint", "wire_holograms_showowners") end end )
-- Replicated from serverside, same function as the one below except this takes precedence local holoDisplayCVar = CreateConVar("wire_holograms_display_owners_maxdist", "-1", {FCVAR_REPLICATED}) local holoDisplayCVarCL = CreateClientConVar( "wire_holograms_display_owners_maxdist_cl" , "-1", true, false, "The maximum distance that wire_holograms_display_owners will allow names to be seen. -1 for original function.", -1, 32768) local function WireHologramsShowOwners() local eye = EyePos() local entList = ents.FindByClass( "gmod_wire_hologram" ) local finalEntList = {} local finalCVar = 0 -- Both cvars, server-replicated and clientside local cva = holoDisplayCVar:GetInt() local cvb = holoDisplayCVarCL:GetInt() if cva == -1 then -- Server allows mapwide visibility for display, default to the client's setting finalCVar = cvb else if cvb >= 0 then -- Use whichever value is lower, as long as the client isn't trying to get mapwide visibility of names while the server prevents it finalCVar = math.min( cva, cvb) else -- If all else fails, settle with what the server is using finalCVar = cva end end local holoDisplayDist = finalCVar ^ 2 if finalCVar > 0 then -- Can't check for -1 from the above variable since it is squared, and it needs to be squared for performance reasons comparing distances for _,ent in pairs( entList ) do local distToEye = eye:DistToSqr( ent:GetPos() ) if distToEye < holoDisplayDist then finalEntList[ #finalEntList + 1 ] = ent end end else -- Default to the original function of showing ALL holograms -- if, in the end, both are 0, why even bother trying to do it at all (and why is this running?) if finalCVar == -1 then finalEntList = entList end end for _,ent in pairs( finalEntList ) do local id = ent:GetNWInt( "ownerid" ) for _,ply in pairs( player.GetAll() ) do if ply:UserID() == id then local vec = ent:GetPos():ToScreen() draw.DrawText( ply:Name() .. "\n" .. ply:SteamID(), "DermaDefault", vec.x, vec.y, Color(255,0,0,255), 1 ) break end end end end local display_owners = false concommand.Add( "wire_holograms_display_owners", function() display_owners = !display_owners if display_owners then hook.Add( "HUDPaint", "wire_holograms_showowners", WireHologramsShowOwners) else hook.Remove("HUDPaint", "wire_holograms_showowners") end end )
Fix for cvar not replicating (#2274)
Fix for cvar not replicating (#2274) Made the required cvar actually get created on the clientside so it has something to replicate to
Lua
apache-2.0
Grocel/wire,wiremod/wire,dvdvideo1234/wire
3f1ce3b2a9034d1045047a4ed13380ab7a4c1ca8
docker/notelauncher.lua
docker/notelauncher.lua
-- -- Module for managing notebook container instances running with the docker module -- -- author: Steve Chan sychan@lbl.gov -- -- Copyright 2013 The Regents of the University of California, -- Lawrence Berkeley National Laboratory -- United States Department of Energy -- The DOE Systems Biology Knowledgebase (KBase) -- Made available under the KBase Open Source License -- local M = {} local docker = require('docker') local json = require('json') local p = require('pl.pretty') local lfs = require('lfs') -- This is the repository name, can be set by whoever instantiates a notelauncher M.repository_image = 'kbase/narrative' -- This is the tag to use, defaults to latest M.repository_version = 'latest' -- This is the port that should be exposed from the container, the service in the container -- should have a listener on here configured M.private_port = 8888 -- This is the path to the syslog Unix socket listener in the host environment -- it is imported into the container via a Volumes argument M.syslog_src = '/dev/log' -- -- Query the docker container for a list of containers and -- return a list of the container names that have listeners on -- port 8888. Keyed on container name, value is IP:Port that can -- be fed into an nginx proxy target local function get_notebooks() local ok, res = pcall(docker.client.containers,docker.client) local portmap = {} ngx.log( ngx.DEBUG, string.format("list containers result: %s",p.write(res.body))) if ok then for index,container in pairs(res.body) do -- we only care about containers matching repository_image and listening on the proper port first,last = string.find(container.Image,M.repository_image) if first == 1 then name = string.sub(container.Names[1],2,-1) portmap[name]={} for i, v in pairs(container.Ports) do if v.PrivatePort == M.private_port then portmap[name] = string.format("127.0.0.1:%u", v.PublicPort) end end end end return portmap else local msg = string.format("Failed to fetch list of containers: %s",p.write(res.body)) ngx.log(ngx.ERR,msg) error(msg) end end -- -- Actually launch a new docker container. -- local function launch_notebook( name ) -- don't wrap this in a pcall, if it fails let it propagate to -- the caller portmap = get_notebooks() assert(portmap[name] == nil, "Notebook by this name already exists: " .. name) local conf = docker.config() local bind_syslog = nil conf.Image = string.format("%s:%s",M.repository_image,M.repository_version) conf.Cmd={name} conf.PortSpecs = {tostring(M.private_port)} ngx.log(ngx.INFO,string.format("Spinning up instance of %s on port %d",conf.Image, M.private_port)) -- we wrap the next call in pcall because we want to trap the case where we get an -- error and try deleting the old container and creating a new one again local ok,res = pcall(docker.client.create_container, docker.client, { payload = conf, name = name}) if not ok and res.response.status >= 409 then -- conflict, try to delete it and then create it again ngx.log(ngx.ERR,string.format("conflicting notebook, removing notebook named: %s",name)) ok, res = pcall( docker.client.remove_container, docker.client, { id = name }) ngx.log(ngx.ERR,string.format("response from remove_container: %s", p.write(res.response))) -- ignore the response and retry the create, and if it still errors, let that propagate ok, res = pcall(docker.client.create_container, docker.client, { payload = conf, name = name}) end if ok then assert(res.status == 201, "Failed to create container: " .. json.encode(res.body)) local id = res.body.Id if M.syslog_src then -- Make sure it exists and is writeable local stat = lfs.attributes(M.syslog_src) if stat ~= nil and stat.mode == 'socket' then bind_syslog = { string.format("%s:%s",M.syslog_src,"/dev/log") } --ngx.log(ngx.ERR,string.format("Binding %s in container %s", bind_syslog[1], name)) else --ngx.log(ngx.ERR,string.format("%s is not writeable, not mounting in container %s",M.syslog_src, name)) end end if bind_syslog ~= nil then res = docker.client:start_container{ id = id, payload = { PublishAllPorts = true, Binds = bind_syslog }} else res = docker.client:start_container{ id = id, payload = { PublishAllPorts = true }} end assert(res.status == 204, "Failed to start container " .. id .. " : " .. json.encode(res.body)) -- get back the container info to pull out the port mapping res = docker.client:inspect_container{ id=id} --p.dump(res) assert(res.status == 200, "Could not inspect new container: " .. id) local ports = res.body.NetworkSettings.Ports local ThePort = string.format("%d/tcp", M.private_port) assert( ports[ThePort] ~= nil, string.format("Port binding for port %s not found!",ThePort)) return(string.format("%s:%d","127.0.0.1", ports[ThePort][1].HostPort)) else local msg = "Failed to create container: " .. p.write(res) ngx.log(ngx.ERR,msg) error(msg) end end -- -- Kill and remove an existing docker container. -- local function remove_notebook( name ) local portmap = get_notebooks() assert(portmap[name], "Notebook by this name does not exist: " .. name) local id = string.format('/%s',name) --ngx.log(ngx.INFO,string.format("removing notebook named: %s",id)) local res = docker.client:stop_container{ id = id } --ngx.log(ngx.INFO,string.format("response from stop_container: %d : %s",res.status,res.body)) assert(res.status == 204, "Failed to stop container: " .. json.encode(res.body)) res = docker.client:remove_container{ id = id} --ngx.log(ngx.INFO,string.format("response from remove_container: %d : %s",res.status,res.body)) assert(res.status == 204, "Failed to remove container " .. id .. " : " .. json.encode(res.body)) return true end M.docker = docker M.get_notebooks = get_notebooks M.launch_notebook = launch_notebook M.remove_notebook = remove_notebook return M
-- -- Module for managing notebook container instances running with the docker module -- -- author: Steve Chan sychan@lbl.gov -- -- Copyright 2013 The Regents of the University of California, -- Lawrence Berkeley National Laboratory -- United States Department of Energy -- The DOE Systems Biology Knowledgebase (KBase) -- Made available under the KBase Open Source License -- local M = {} local docker = require('docker') local json = require('json') local p = require('pl.pretty') local lfs = require('lfs') -- This is the repository name, can be set by whoever instantiates a notelauncher M.repository_image = 'kbase/narrative' -- This is the tag to use, defaults to latest M.repository_version = 'latest' -- This is the port that should be exposed from the container, the service in the container -- should have a listener on here configured M.private_port = 8888 -- This is the path to the syslog Unix socket listener in the host environment -- it is imported into the container via a Volumes argument M.syslog_src = '/dev/log' -- -- Query the docker container for a list of containers and -- return a list of the container names that have listeners on -- port 8888. Keyed on container name, value is IP:Port that can -- be fed into an nginx proxy target local function get_notebooks() local ok, res = pcall(docker.client.containers,docker.client) local portmap = {} ngx.log( ngx.DEBUG, string.format("list containers result: %s",p.write(res.body))) if ok then for index,container in pairs(res.body) do -- we only care about containers matching repository_image and listening on the proper port first,last = string.find(container.Image,M.repository_image) if first == 1 then name = string.sub(container.Names[1],2,-1) portmap[name]={} for i, v in pairs(container.Ports) do if v.PrivatePort == M.private_port then portmap[name] = string.format("127.0.0.1:%u", v.PublicPort) end end end end return portmap else local msg = string.format("Failed to fetch list of containers: %s",p.write(res.body)) ngx.log(ngx.ERR,msg) error(msg) end end -- -- Actually launch a new docker container. -- local function launch_notebook( name ) -- don't wrap this in a pcall, if it fails let it propagate to -- the caller portmap = get_notebooks() assert(portmap[name] == nil, "Notebook by this name already exists: " .. name) local conf = docker.config() local bind_syslog = nil conf.Image = string.format("%s:%s",M.repository_image,M.repository_version) conf.Cmd={name} conf.PortSpecs = {tostring(M.private_port)} ngx.log(ngx.INFO,string.format("Spinning up instance of %s on port %d",conf.Image, M.private_port)) -- we wrap the next call in pcall because we want to trap the case where we get an -- error and try deleting the old container and creating a new one again local ok,res = pcall(docker.client.create_container, docker.client, { payload = conf, name = name}) if not ok and res.response.status >= 409 then -- conflict, try to delete it and then create it again ngx.log(ngx.ERR,string.format("conflicting notebook, removing notebook named: %s",name)) ok, res = pcall( docker.client.remove_container, docker.client, { id = name }) ngx.log(ngx.ERR,string.format("response from remove_container: %s", p.write(res.response))) -- ignore the response and retry the create, and if it still errors, let that propagate ok, res = pcall(docker.client.create_container, docker.client, { payload = conf, name = name}) end if ok then assert(res.status == 201, "Failed to create container: " .. json.encode(res.body)) local id = res.body.Id if M.syslog_src then -- Make sure it exists and is writeable local stat = lfs.attributes(M.syslog_src) if stat ~= nil and stat.mode == 'socket' then bind_syslog = { string.format("%s:%s",M.syslog_src,"/dev/log") } --ngx.log(ngx.ERR,string.format("Binding %s in container %s", bind_syslog[1], name)) else --ngx.log(ngx.ERR,string.format("%s is not writeable, not mounting in container %s",M.syslog_src, name)) end end if bind_syslog ~= nil then res = docker.client:start_container{ id = id, payload = { PublishAllPorts = true, Binds = bind_syslog }} else res = docker.client:start_container{ id = id, payload = { PublishAllPorts = true }} end assert(res.status == 204, "Failed to start container " .. id .. " : " .. json.encode(res.body)) -- get back the container info to pull out the port mapping res = docker.client:inspect_container{ id=id} --p.dump(res) assert(res.status == 200, "Could not inspect new container: " .. id) local ports = res.body.NetworkSettings.Ports local ThePort = string.format("%d/tcp", M.private_port) local log, occ = string.gsub(res.body.HostsPath,"hosts","root/tmp/kbase-narrative.log") local ct=5 local ready=0 while (ct and not ready) do local f=io.open(name,"r") if f ~= nil then io.close(f) ready = 1 end ct = ct - 1 ngx.sleep(2) end if not ready then local msg = "Time out starting container: " .. id ngx.log(ngx.ERR,msg) error(msg) end assert(ports[ThePort] ~= nil, string.format("Port binding for port %s not found!",ThePort)) return(string.format("%s:%d","127.0.0.1", ports[ThePort][1].HostPort)) else local msg = "Failed to create container: " .. p.write(res) ngx.log(ngx.ERR,msg) error(msg) end end -- -- Kill and remove an existing docker container. -- local function remove_notebook( name ) local portmap = get_notebooks() assert(portmap[name], "Notebook by this name does not exist: " .. name) local id = string.format('/%s',name) --ngx.log(ngx.INFO,string.format("removing notebook named: %s",id)) local res = docker.client:stop_container{ id = id } --ngx.log(ngx.INFO,string.format("response from stop_container: %d : %s",res.status,res.body)) assert(res.status == 204, "Failed to stop container: " .. json.encode(res.body)) res = docker.client:remove_container{ id = id} --ngx.log(ngx.INFO,string.format("response from remove_container: %d : %s",res.status,res.body)) assert(res.status == 204, "Failed to remove container " .. id .. " : " .. json.encode(res.body)) return true end M.docker = docker M.get_notebooks = get_notebooks M.launch_notebook = launch_notebook M.remove_notebook = remove_notebook return M
Added Shane's possible fix to notelauncher
Added Shane's possible fix to notelauncher
Lua
mit
psnovichkov/narrative,briehl/narrative,pranjan77/narrative,rsutormin/narrative,jmchandonia/narrative,jmchandonia/narrative,pranjan77/narrative,nlharris/narrative,aekazakov/narrative,jmchandonia/narrative,msneddon/narrative,jmchandonia/narrative,psnovichkov/narrative,kbase/narrative,pranjan77/narrative,pranjan77/narrative,nlharris/narrative,jmchandonia/narrative,scanon/narrative,msneddon/narrative,kbase/narrative,msneddon/narrative,aekazakov/narrative,jmchandonia/narrative,psnovichkov/narrative,nlharris/narrative,mlhenderson/narrative,mlhenderson/narrative,msneddon/narrative,briehl/narrative,pranjan77/narrative,psnovichkov/narrative,rsutormin/narrative,scanon/narrative,rsutormin/narrative,briehl/narrative,briehl/narrative,msneddon/narrative,rsutormin/narrative,kbase/narrative,scanon/narrative,psnovichkov/narrative,rsutormin/narrative,kbase/narrative,nlharris/narrative,msneddon/narrative,pranjan77/narrative,mlhenderson/narrative,nlharris/narrative,briehl/narrative,psnovichkov/narrative,kbase/narrative,msneddon/narrative,aekazakov/narrative,aekazakov/narrative,kbase/narrative,mlhenderson/narrative,scanon/narrative,briehl/narrative,rsutormin/narrative,mlhenderson/narrative,scanon/narrative,mlhenderson/narrative,briehl/narrative,jmchandonia/narrative,aekazakov/narrative,scanon/narrative,psnovichkov/narrative,aekazakov/narrative,nlharris/narrative,nlharris/narrative,pranjan77/narrative
f3cc92434ae14b4630aec4bc7b995e74ecd1ebe1
src/lua-factory/sources/grl-acoustid.lua
src/lua-factory/sources/grl-acoustid.lua
--[[ * Copyright (C) 2016 Grilo Project * * Contact: Victor Toso <me@victortoso.com> * * This library 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; version 2.1 of * the License, or (at your option) any later version. * * This library 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-acoustid", name = "Acoustid", description = "a source that provides audio identification", supported_keys = { "title", "album", "artist", "mb-recording-id", "mb-album-id", "mb-artist-id", "mb-release-group-id", "mb-release-id", "album-disc-number", "publication-date", "track-number", "creation-date" }, supported_media = { 'audio' }, config_keys = { required = { "api-key" }, }, resolve_keys = { ["type"] = "audio", required = { "duration", "chromaprint" } }, tags = { 'music', 'net:internet' }, } netopts = { user_agent = "Grilo Source AcoustID/0.3.0", } ------------------ -- Source utils -- ------------------ acoustid = {} -- https://acoustid.org/webservice#lookup ACOUSTID_LOOKUP = "https://api.acoustid.org/v2/lookup?client=%s&meta=compress+recordings+releasegroups+releases+sources+tracks&duration=%d&fingerprint=%s" --------------------------------- -- Handlers of Grilo functions -- --------------------------------- function grl_source_init (configs) acoustid.api_key = configs.api_key return true end function grl_source_resolve (media, options, callback) local url local media = grl.get_media_keys() if not media or not media.duration or not media.chromaprint or #media.chromaprint == 0 then grl.callback () return end url = string.format (ACOUSTID_LOOKUP, acoustid.api_key, media.duration, media.chromaprint) grl.fetch (url, netopts, lookup_cb) end --------------- -- Utilities -- --------------- function lookup_cb (feed) if not feed then grl.callback() return end local json = grl.lua.json.string_to_table (feed) if not json or json.status ~= "ok" then grl.callback() end media = build_media (json.results) grl.callback (media) end function build_media(results) local media = grl.get_media_keys () local keys = grl.get_requested_keys () local record, album, artist local release_group_id local sources = 0 local creation_date = nil if results and #results > 0 and results[1].recordings and #results[1].recordings > 0 then for _, recording in ipairs(results[1].recordings) do if recording.sources > sources then sources = recording.sources record = recording end end media.title = keys.title and record.title or nil media.mb_recording_id = keys.mb_recording_id and record.id or nil end if record and record.releasegroups and #record.releasegroups > 0 then album = record.releasegroups[1] media.album = keys.album and album.title or nil release_group_id = keys.mb_album_id and album.id or nil media.mb_album_id = release_group_id media.mb_release_group_id = release_group_id end -- FIXME: related-keys on lua sources are in the TODO list -- https://bugzilla.gnome.org/show_bug.cgi?id=756203 -- and for that reason we are only returning first of all metadata if record and record.artists and #record.artists > 0 then artist = record.artists[1] media.artist = keys.artist and artist.name or nil media.mb_artist_id = keys.mb_artist_id and artist.id or nil end if album and album.releases and #album.releases > 0 then if keys.creation_date then for _, release in ipairs(album.releases) do if release.date then local month = release.date.month or 1 local day = release.date.day or 1 local year= release.date.year if not creation_date or year < creation_date.year or (year == creation_date.year and month < creation_date.month) or (year == creation_date.year and month == creation_date.month and day < creation_date.day) then creation_date = {day=day, month=month, year=year} end end end if creation_date then media.creation_date = string.format('%04d-%02d-%02d', creation_date.year, creation_date.month, creation_date.day) end end release = album.releases[1] media.mb_release_id = keys.mb_album_id and release.id or nil if release.date then local date = release.date local month = date.month or 1 local day = date.day or 1 date = string.format('%04d-%02d-%02d', date.year, month, day) media.publication_date = keys.publication_date and date or nil end if release.mediums and #release.mediums > 0 then medium = release.mediums[1] media.album_disc_number = keys.album_disc_number and medium.position or nil if medium.tracks and #medium.tracks > 0 then media.track_number = keys.track_number and medium.tracks[1].position or nil end end end return media end
--[[ * Copyright (C) 2016 Grilo Project * * Contact: Victor Toso <me@victortoso.com> * * This library 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; version 2.1 of * the License, or (at your option) any later version. * * This library 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-acoustid", name = "Acoustid", description = "a source that provides audio identification", supported_keys = { "title", "album", "artist", "mb-recording-id", "mb-album-id", "mb-artist-id", "mb-release-group-id", "mb-release-id", "album-disc-number", "publication-date", "track-number", "creation-date" }, supported_media = { 'audio' }, config_keys = { required = { "api-key" }, }, resolve_keys = { ["type"] = "audio", required = { "duration", "chromaprint" } }, tags = { 'music', 'net:internet' }, } netopts = { user_agent = "Grilo Source AcoustID/0.3.0", } ------------------ -- Source utils -- ------------------ acoustid = {} -- https://acoustid.org/webservice#lookup ACOUSTID_LOOKUP = "https://api.acoustid.org/v2/lookup?client=%s&meta=compress+recordings+releasegroups+releases+sources+tracks&duration=%d&fingerprint=%s" --------------------------------- -- Handlers of Grilo functions -- --------------------------------- function grl_source_init (configs) acoustid.api_key = configs.api_key return true end function grl_source_resolve (media, options, callback) local url local media = grl.get_media_keys() if not media or not media.duration or not media.chromaprint or #media.chromaprint == 0 then grl.callback () return end url = string.format (ACOUSTID_LOOKUP, acoustid.api_key, media.duration, media.chromaprint) grl.fetch (url, netopts, lookup_cb) end --------------- -- Utilities -- --------------- function lookup_cb (feed) if not feed then grl.callback() return end local json = grl.lua.json.string_to_table (feed) if not json or json.status ~= "ok" then grl.callback() end media = build_media (json.results) grl.callback (media) end function build_media(results) local media = grl.get_media_keys () local keys = grl.get_requested_keys () local record, album, artist local release_group_id local sources = 0 local creation_date = nil if results and #results > 0 and results[1].recordings and #results[1].recordings > 0 then for _, recording in ipairs(results[1].recordings) do if recording.sources > sources then sources = recording.sources record = recording end end media.title = keys.title and record.title or nil media.mb_recording_id = keys.mb_recording_id and record.id or nil end if record and record.releasegroups and #record.releasegroups > 0 then album = record.releasegroups[1] media.album = keys.album and album.title or nil release_group_id = keys.mb_album_id and album.id or nil media.mb_album_id = release_group_id media.mb_release_group_id = release_group_id end -- FIXME: related-keys on lua sources are in the TODO list -- https://bugzilla.gnome.org/show_bug.cgi?id=756203 -- and for that reason we are only returning first of all metadata if record and record.artists and #record.artists > 0 then artist = record.artists[1] media.artist = keys.artist and artist.name or nil media.mb_artist_id = keys.mb_artist_id and artist.id or nil end if album and album.releases and #album.releases > 0 then if keys.creation_date then for _, release in ipairs(album.releases) do if release.date then local month = release.date.month or 1 local day = release.date.day or 1 local year= release.date.year if not creation_date or year < creation_date.year or (year == creation_date.year and month < creation_date.month) or (year == creation_date.year and month == creation_date.month and day < creation_date.day) then creation_date = {day=day, month=month, year=year} end end end if creation_date then media.creation_date = string.format('%04d-%02d-%02d', creation_date.year, creation_date.month, creation_date.day) end end release = album.releases[1] media.mb_release_id = keys.mb_album_id and release.id or nil if release.date then local date = release.date local month = date.month or 1 local day = date.day or 1 date = string.format('%04d-%02d-%02d', date.year, month, day) media.publication_date = keys.publication_date and date or nil end if release.mediums and #release.mediums > 0 then medium = release.mediums[1] media.album_disc_number = keys.album_disc_number and medium.position or nil if medium.tracks and #medium.tracks > 0 then media.track_number = keys.track_number and medium.tracks[1].position or nil end end end return media end
grl-acoustid: Fix indentation
grl-acoustid: Fix indentation
Lua
lgpl-2.1
jasuarez/grilo-plugins,jasuarez/grilo-plugins,GNOME/grilo-plugins,grilofw/grilo-plugins,grilofw/grilo-plugins,GNOME/grilo-plugins
69d2b6824ee18b672132661e9e162e88af6f8c6b
SpatialBatchNormalization.lua
SpatialBatchNormalization.lua
local SpatialBatchNormalization, parent = torch.class('cudnn.SpatialBatchNormalization', 'nn.SpatialBatchNormalization') local ffi = require 'ffi' local errcheck = cudnn.errcheck function SpatialBatchNormalization:__init(nFeature, eps, momentum, affine) parent.__init(self, nFeature, eps, momentum, affine) self.mode = 'CUDNN_BATCHNORM_SPATIAL' self.nFeature = nFeature self.save_mean = torch.Tensor(nFeature) self.save_std = torch.Tensor(nFeature) end function SpatialBatchNormalization:createIODescriptors(input) assert(input:dim() == 4) assert(torch.typename(self.weight) == 'torch.CudaTensor' and torch.typename(self.bias) == 'torch.CudaTensor', 'Only CUDA tensors are supported for cudnn.SpatialBatchNormalization!') if not self.iDesc or not self.oDesc or input:size(1) ~= self.iSize[1] or input:size(2) ~= self.iSize[2] or input:size(3) ~= self.iSize[3] or input:size(4) ~= self.iSize[4] then self.iSize = input:size() self.output:resizeAs(input) self.gradInput:resizeAs(input) self.iDesc = cudnn.toDescriptor(input) self.oDesc = cudnn.toDescriptor(self.output) self.sDesc = cudnn.toDescriptor(self.bias:view(1, self.nFeature, 1, 1)) end end local one = torch.FloatTensor({1}); local zero = torch.FloatTensor({0}); function SpatialBatchNormalization:updateOutput(input) self:createIODescriptors(input) if self.train then errcheck('cudnnBatchNormalizationForwardTraining', cudnn.getHandle(), self.mode, one:data(), zero:data(), self.iDesc[0], input:data(), self.oDesc[0], self.output:data(), self.sDesc[0], self.weight:data(), self.bias:data(), self.momentum, self.running_mean:data(), self.running_std:data(), self.eps, self.save_mean:data(), self.save_std:data()); else errcheck('cudnnBatchNormalizationForwardInference', cudnn.getHandle(), self.mode, one:data(), zero:data(), self.iDesc[0], input:data(), self.oDesc[0], self.output:data(), self.sDesc[0], self.weight:data(), self.bias:data(), self.running_mean:data(), self.running_std:data(), self.eps); end return self.output end function SpatialBatchNormalization:updateGradInput(input, gradOutput) assert(gradOutput:isContiguous()); self:createIODescriptors(input) errcheck('cudnnBatchNormalizationBackward', cudnn.getHandle(), self.mode, one:data(), zero:data(), self.iDesc[0], input:data(), self.iDesc[0], gradOutput:data(), self.iDesc[0], self.gradInput:data(), -- input is bottom, gradOutput is topDiff, self.gradInput is resultBottomDiff self.sDesc[0], self.weight:data(), self.gradWeight:data(), self.gradBias:data(), self.eps, self.save_mean:data(), self.save_std:data()); return self.gradInput end function SpatialBatchNormalization:accGradParameters(input, gradOutput, scale) end function SpatialBatchNormalization:write(f) self.iDesc = nil self.oDesc = nil self.sDesc = nil local var = {} for k,v in pairs(self) do var[k] = v end f:writeObject(var) end
local SpatialBatchNormalization, parent = torch.class('cudnn.SpatialBatchNormalization', 'nn.Module') local ffi = require 'ffi' local errcheck = cudnn.errcheck function SpatialBatchNormalization:__init(nFeature, eps, momentum, affine) parent.__init(self) assert(nFeature and type(nFeature) == 'number', 'Missing argument #1: Number of feature planes. ') assert(nFeature ~= 0, 'To set affine=false call BatchNormalization' .. '(nFeature, eps, momentum, false) ') assert(affine == nil or affine == true, 'only affine supported') self.mode = 'CUDNN_BATCHNORM_SPATIAL' self.nFeature = nFeature self.eps = eps or 1e-5 self.train = true self.momentum = momentum or 0.1 self.save_mean = torch.Tensor(nFeature) self.save_std = torch.Tensor(nFeature) self.running_mean = torch.zeros(nFeature) self.running_std = torch.ones(nFeature) self.weight = torch.Tensor(nFeature) self.bias = torch.Tensor(nFeature) self.gradWeight = torch.Tensor(nFeature) self.gradBias = torch.Tensor(nFeature) self:reset() end function SpatialBatchNormalization:createIODescriptors(input) assert(input:dim() == 4) assert(torch.typename(self.weight) == 'torch.CudaTensor' and torch.typename(self.bias) == 'torch.CudaTensor', 'Only CUDA tensors are supported for cudnn.SpatialBatchNormalization!') if not self.iDesc or not self.oDesc or input:size(1) ~= self.iSize[1] or input:size(2) ~= self.iSize[2] or input:size(3) ~= self.iSize[3] or input:size(4) ~= self.iSize[4] then self.iSize = input:size() self.output:resizeAs(input) self.gradInput:resizeAs(input) self.iDesc = cudnn.toDescriptor(input) self.oDesc = cudnn.toDescriptor(self.output) self.sDesc = cudnn.toDescriptor(self.bias:view(1, self.nFeature, 1, 1)) end end local one = torch.FloatTensor({1}); local zero = torch.FloatTensor({0}); function SpatialBatchNormalization:reset() self.weight:uniform() self.bias:zero() end function SpatialBatchNormalization:updateOutput(input) self:createIODescriptors(input) if self.train then errcheck('cudnnBatchNormalizationForwardTraining', cudnn.getHandle(), self.mode, one:data(), zero:data(), self.iDesc[0], input:data(), self.oDesc[0], self.output:data(), self.sDesc[0], self.weight:data(), self.bias:data(), self.momentum, self.running_mean:data(), self.running_std:data(), self.eps, self.save_mean:data(), self.save_std:data()); else errcheck('cudnnBatchNormalizationForwardInference', cudnn.getHandle(), self.mode, one:data(), zero:data(), self.iDesc[0], input:data(), self.oDesc[0], self.output:data(), self.sDesc[0], self.weight:data(), self.bias:data(), self.running_mean:data(), self.running_std:data(), self.eps); end return self.output end function SpatialBatchNormalization:updateGradInput(input, gradOutput) assert(gradOutput:isContiguous()); self:createIODescriptors(input) errcheck('cudnnBatchNormalizationBackward', cudnn.getHandle(), self.mode, one:data(), zero:data(), self.iDesc[0], input:data(), self.iDesc[0], gradOutput:data(), self.iDesc[0], self.gradInput:data(), -- input is bottom, gradOutput is topDiff, self.gradInput is resultBottomDiff self.sDesc[0], self.weight:data(), self.gradWeight:data(), self.gradBias:data(), self.eps, self.save_mean:data(), self.save_std:data()); return self.gradInput end function SpatialBatchNormalization:accGradParameters(input, gradOutput, scale) end function SpatialBatchNormalization:write(f) self.iDesc = nil self.oDesc = nil self.sDesc = nil local var = {} for k,v in pairs(self) do var[k] = v end f:writeObject(var) end
Fix cudnn.SpatialBatchNormalization after nn change
Fix cudnn.SpatialBatchNormalization after nn change
Lua
bsd-3-clause
phunghx/phnn.torch,phunghx/phnn.torch,phunghx/phnn.torch
70005feff95d55de2e4ec31aee80ef788f86fe24
core/utilities.lua
core/utilities.lua
local utilities = { } function utilities.required(t, name, context) if not t[name] then utilities.error(context.." needs a "..name.." parameter") end return t[name] end function utilities.error(message) print("\n! "..message) os.exit(1) end function utilities.debugging(category) return SILE.debugFlags[category] end function utilities.gtoke(string, pattern) string = string and tostring(string) or '' pattern = pattern and tostring(pattern) or "%s+" return coroutine.wrap(function() local index= 1 repeat local first, last = string:find(pattern, index) if first and last then if index < first then coroutine.yield({ string = string:sub(index, first -1) }) end coroutine.yield({ separator = string:sub(first, last) }) index = last + 1 else if index <= #string then coroutine.yield({ string = string:sub(index) }) end break end until index > #string end) end function utilities.debug(category, messages) if utilities.debugging(category) then print(messages) end end function utilities.concat(s,c) local t = { } for k,v in ipairs(s) do t[#t+1] = tostring(v) end return table.concat(t,c) end function utilities.inherit (orig, spec) local new = std.tree.clone(orig) if spec then for k,v in pairs(spec) do new[k] = v end end if new.init then new:init() end return new end function utilities.map(func, array) local new_array = {} for i,v in ipairs(array) do new_array[i] = func(v) end return new_array end function utilities.splice(array, start, stop, replacement) if replacement then local n = stop - start + 1 while n > 0 do table.remove(array, start) n = n - 1 end for i,v in ipairs(replacement) do table.insert(array, start+i-1, v) end return array else local res = {} for i = start,stop do table.insert(res, array[i]) end return res end end function utilities.sum(array) local t = 0 for i,v in ipairs(array) do t = t + v end return t end return utilities
local utilities = { } function utilities.required(t, name, context) if not t[name] then utilities.error(context.." needs a "..name.." parameter") end return t[name] end function utilities.error(message) print("\n! "..message) os.exit(1) end function utilities.warn(message) print("\n! "..message) print(debug.traceback()) os.exit(1) end function utilities.debugging(category) return SILE.debugFlags[category] end function utilities.gtoke(string, pattern) string = string and tostring(string) or '' pattern = pattern and tostring(pattern) or "%s+" return coroutine.wrap(function() local index= 1 repeat local first, last = string:find(pattern, index) if first and last then if index < first then coroutine.yield({ string = string:sub(index, first -1) }) end coroutine.yield({ separator = string:sub(first, last) }) index = last + 1 else if index <= #string then coroutine.yield({ string = string:sub(index) }) end break end until index > #string end) end function utilities.debug(category, messages) if utilities.debugging(category) then print(messages) end end function utilities.concat(s,c) local t = { } for k,v in ipairs(s) do t[#t+1] = tostring(v) end return table.concat(t,c) end function utilities.inherit (orig, spec) local new = std.tree.clone(orig) if spec then for k,v in pairs(spec) do new[k] = v end end if new.init then new:init() end return new end function utilities.map(func, array) local new_array = {} for i,v in ipairs(array) do new_array[i] = func(v) end return new_array end function utilities.splice(array, start, stop, replacement) if replacement then local n = stop - start + 1 while n > 0 do table.remove(array, start) n = n - 1 end for i,v in ipairs(replacement) do table.insert(array, start+i-1, v) end return array else local res = {} for i = start,stop do table.insert(res, array[i]) end return res end end function utilities.sum(array) local t = 0 for i,v in ipairs(array) do t = t + v end return t end return utilities
Warning function for internal bugs.
Warning function for internal bugs.
Lua
mit
shirat74/sile,Nathan22Miles/sile,WAKAMAZU/sile_fe,Nathan22Miles/sile,WAKAMAZU/sile_fe,Nathan22Miles/sile,simoncozens/sile,anthrotype/sile,anthrotype/sile,Nathan22Miles/sile,Nathan22Miles/sile,alerque/sile,anthrotype/sile,WAKAMAZU/sile_fe,neofob/sile,simoncozens/sile,neofob/sile,simoncozens/sile,neofob/sile,shirat74/sile,alerque/sile,shirat74/sile,simoncozens/sile,alerque/sile,alerque/sile,shirat74/sile,neofob/sile,WAKAMAZU/sile_fe,anthrotype/sile
83abc7b0701e5f0e5f58eadbb830e6d771c153ca
alchemy/lte/id_59_attribs.lua
alchemy/lte/id_59_attribs.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/>. ]] -- LTE fr das Druidensystem -- by Falk local common = require("base.common") local M = {} -- INSERT INTO longtimeeffects VALUES (59, 'alchemy_attribs', 'alchemy.lte.id_59_attribs'); local attribList ={"strength","willpower","perception","intelligence","constitution","agility","dexterity","essence"}; local bottomBorder = 1; function M.addEffect(Effect, User) end function M.callEffect(Effect,User) -- callEffect is only called once; we just need to return false local find_i,sight = Effect:findValue("sightpotion") if find then common.InformNLS( User, "Deine Augen fhlen sich wieder normal an.", "Your eyes feel normal again.") else common.InformNLS( User, "Du fhlst, dass der Strkungstrank seine Wirkung verliert.", "You feel that the strengthening potion looses its effect.") end return false end function M.removeEffect(Effect,User) -- restore the attributes local find_i,sight = Effect:findValue("sightpotion") if not find then local find_i, attrib_i, attribValue for i=1,8 do find_i,attrib_i = Effect:findValue(""..attribList[i]) if find_i then attribValue = attrib_i - 5 User:increaseAttrib(attribList[i],-attribValue); end end end end function M.loadEffect(Effect,User) -- login, we have to change the attributes again local find_i,sight = Effect:findValue("sightpotion") if not find then local find_i, attrib_i for i=1,8 do find_i,attrib_i = Effect:findValue(""..attribList[i]) if find_i then User:increaseAttrib(attribList[i],attrib_i - 5) end end 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/>. ]] -- LTE fr das Druidensystem -- by Falk local common = require("base.common") local M = {} -- INSERT INTO longtimeeffects VALUES (59, 'alchemy_attribs', 'alchemy.lte.id_59_attribs'); local attribList ={"strength","willpower","perception","intelligence","constitution","agility","dexterity","essence"} function M.addEffect(Effect, User) end function M.callEffect(Effect,User) -- callEffect is only called once; we just need to return false local find = Effect:findValue("sightpotion") if find then common.InformNLS( User, "Deine Augen fhlen sich wieder normal an.", "Your eyes feel normal again.") else common.InformNLS( User, "Du fhlst, dass der Strkungstrank seine Wirkung verliert.", "You feel that the strengthening potion looses its effect.") end return false end function M.removeEffect(Effect,User) -- restore the attributes local find = Effect:findValue("sightpotion") if not find then local find_i, attrib_i, attribValue for i=1,8 do find_i,attrib_i = Effect:findValue(""..attribList[i]) if find_i then attribValue = attrib_i - 5 User:increaseAttrib(attribList[i],-attribValue) end end end end function M.loadEffect(Effect,User) -- login, we have to change the attributes again local find = Effect:findValue("sightpotion") if not find then local find_i, attrib_i for i=1,8 do find_i,attrib_i = Effect:findValue(""..attribList[i]) if find_i then User:increaseAttrib(attribList[i],attrib_i - 5) end end end end return M
fix variables usage
fix variables usage
Lua
agpl-3.0
KayMD/Illarion-Content,Illarion-eV/Illarion-Content,vilarion/Illarion-Content,Baylamon/Illarion-Content
a7fd6596da16774ab93939f8ba59cb0fbd48cd27
scripts/before_install.lua
scripts/before_install.lua
import("core.platform.platform") import("core.base.option") function main(target) if target:isphony() then return end local targetname = target:name() if "_hikyuu" ~= targetname then return end local installdir = option.get("installdir") or os.getenv("INSTALLDIR") or os.getenv("DESTDIR") or platform.get("installdir") if is_plat("windows") then os.exec("xcopy /S /Q /Y /I hikyuu " .. installdir) end if is_plat("linux") then os.exec("cp -f -r -T hikyuu " .. installdir) end if is_plat("macosx") then os.exec("cp -f -r hikyuu/* " .. installdir) end end
import("core.platform.platform") import("core.base.option") function main(target) if target:isphony() then return end local targetname = target:name() if "_hikyuu" ~= targetname then return end local installdir = option.get("installdir") or os.getenv("INSTALLDIR") or os.getenv("DESTDIR") or platform.get("installdir") if is_plat("windows") then os.exec("xcopy /S /Q /Y /I hikyuu %s", os.args(installdir)) end if is_plat("linux") then os.exec("cp -f -r -T hikyuu %s" ,os.args(installdir)) end if is_plat("macosx") then os.exec("cp -f -r hikyuu/* %s", os.args(installdir)) end end
fixed #IVH02 安装目标路径如果带有空格导致安装失败
fixed #IVH02 安装目标路径如果带有空格导致安装失败
Lua
mit
fasiondog/hikyuu
df4534d8591750aef1c053143d0ffa47e5855b82
mod/mpi/config/scripts/image_statusbar.lua
mod/mpi/config/scripts/image_statusbar.lua
local on = mp.get_opt('images-statusbar') == 'yes' -- lua-filesize, generate a human readable string describing the file size -- Copyright (c) 2016 Boris Nagaev -- See the LICENSE file for terms of use. local si = {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} local function isNan(num) -- http://lua-users.org/wiki/InfAndNanComparisons -- NaN is the only value that doesn't equal itself return num ~= num end local function roundNumber(num, digits) local fmt = "%." .. digits .. "f" return tonumber(fmt:format(num)) end local function get_file_size(size) if size == 0 then return "0" .. si[1] end local exponent = math.floor(math.log(size) / math.log(1024)) if exponent > 8 then exponent = 8 end local value = roundNumber( size / math.pow(2, exponent * 10), exponent > 0 and 1 or 0) local suffix = si[exponent + 1] return tostring(value):gsub('%.0$', '') .. suffix end function get_property_number_or_nil(name) if mp.get_property(name) == nil then return nil end return mp.get_property_number(name) end function force_redraw() mp.osd_message('') end function update_statusbar() if on == true then local playlist_pos = mp.get_property_number('playlist-pos') + 1 local playlist_count = mp.get_property_number('playlist-count') local width = get_property_number_or_nil('width') local height = get_property_number_or_nil('height') local size = get_file_size(mp.get_property_number('file-size')) local path = mp.get_property('filename') mp.set_property( 'options/osd-msg1', string.format( '%s %sx%s %s (%d/%d)', path, width or '?', height or '?', size, playlist_pos, playlist_count)) mp.set_property('options/osd-msg3', string.format('%s', path)) force_redraw() end end function toggle_statusbar() if on == false then on = true update_statusbar() else on = false mp.set_property('options/osd-msg1', '') force_redraw() end mp.resume_all() end mp.register_event('file-loaded', update_statusbar) mp.register_script_message('toggle-statusbar', toggle_statusbar)
local on = mp.get_opt('images-statusbar') == 'yes' -- lua-filesize, generate a human readable string describing the file size -- Copyright (c) 2016 Boris Nagaev -- See the LICENSE file for terms of use. local si = {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} local function isNan(num) -- http://lua-users.org/wiki/InfAndNanComparisons -- NaN is the only value that doesn't equal itself return num ~= num end local function roundNumber(num, digits) local fmt = "%." .. digits .. "f" return tonumber(fmt:format(num)) end local function get_file_size(size) if size == 0 then return "0" .. si[1] end local exponent = math.floor(math.log(size) / math.log(1024)) if exponent > 8 then exponent = 8 end local value = roundNumber( size / math.pow(2, exponent * 10), exponent > 0 and 1 or 0) local suffix = si[exponent + 1] return tostring(value):gsub('%.0$', '') .. suffix end function get_property_number_or_nil(name) if mp.get_property(name) == nil then return nil end return mp.get_property_number(name) end function update_statusbar() if on == true then local playlist_pos = mp.get_property_number('playlist-pos') + 1 local playlist_count = mp.get_property_number('playlist-count') local width = get_property_number_or_nil('width') local height = get_property_number_or_nil('height') local size = get_file_size(mp.get_property_number('file-size')) local path = mp.get_property('filename') mp.set_property( 'options/osd-msg1', string.format( '%s %sx%s %s (%d/%d)', path, width or '?', height or '?', size, playlist_pos, playlist_count)) else mp.set_property('options/osd-msg1', '') end end function toggle_statusbar() on = not on update_statusbar() mp.osd_message('', 0) end mp.register_event('file-loaded', update_statusbar) mp.register_script_message('toggle-statusbar', toggle_statusbar)
mod/mpi: fix statusbar showing/hiding
mod/mpi: fix statusbar showing/hiding The force_redraw() trick, every time a file was loaded, discarded all messages that were shown at that time. This behavior, for example, was the cause behind "Slide show started" message (which is provided by the slideshow script) disappearing as soon as the file has been loaded rather than the normal timeout.
Lua
mit
rr-/dotfiles,rr-/dotfiles,rr-/dotfiles
0b68b2aec676e737930743e7136e21c97f0ff292
worldedit_commands/cuboid.lua
worldedit_commands/cuboid.lua
dofile(minetest.get_modpath("worldedit_commands") .. "/cuboidapi.lua") minetest.register_chatcommand("/outset", { params = "[h|v] <amount>", description = "outset the selection", privs = {worldedit=true}, func = function(name, param) local find, _, dir, amount = param:find("(%a*)%s*([+-]?%d+)") if find == nil then return false, "invalid usage: " .. param end local pos1 = worldedit.pos1[name] local pos2 = worldedit.pos2[name] if pos1 == nil or pos2 == nil then return false, "Undefined region. Region must be defined beforehand." end local hv_test = dir:find("[^hv]+") if hv_test ~= nil then return false, "Invalid direction." end if dir == "" or dir == "hv" or dir == "vh" then assert(worldedit.cuboid_volumetric_expand(name, amount)) elseif dir == "h" then assert(worldedit.cuboid_linear_expand(name, 'x', 1, amount)) assert(worldedit.cuboid_linear_expand(name, 'x', -1, amount)) assert(worldedit.cuboid_linear_expand(name, 'z', 1, amount)) assert(worldedit.cuboid_linear_expand(name, 'z', -1, amount)) elseif dir == "v" then assert(worldedit.cuboid_linear_expand(name, 'y', 1, amount)) assert(worldedit.cuboid_linear_expand(name, 'y', -1, amount)) else return false, "Invalid number of arguments" end worldedit.marker_update(name) return true, "Region outset by " .. amount .. " blocks" end, } ) minetest.register_chatcommand("/inset", { params = "[h|v] <amount>", description = "inset the selection", privs = {worldedit=true}, func = function(name, param) local find, _, dir, amount = param:find("(%a*)%s*([+-]?%d+)") if find == nil then return false, "invalid usage: " .. param end local pos1 = worldedit.pos1[name] local pos2 = worldedit.pos2[name] if pos1 == nil or pos2 == nil then return false, "Undefined region. Region must be defined beforehand." end local hv_test = dir:find("[^hv]+") if hv_test ~= nil then return false, "Invalid direction." end if dir == "" or dir == "vh" or dir == "hv" then assert(worldedit.cuboid_volumetric_expand(name, -amount)) elseif dir == "h" then assert(worldedit.cuboid_linear_expand(name, 'x', 1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'x', -1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'z', 1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'z', -1, -amount)) elseif dir == "v" then assert(worldedit.cuboid_linear_expand(name, 'y', 1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'y', -1, -amount)) else return false, "Invalid number of arguments" end worldedit.marker_update(name) return true, "Region inset by " .. amount .. " blocks" end, } ) minetest.register_chatcommand("/shift", { params = "[x|y|z|?|up|down|left|right|front|back] [+|-]<amount>", description = "Moves the selection region. Does not move contents.", privs = {worldedit=true}, func = function(name, param) local pos1 = worldedit.pos1[name] local pos2 = worldedit.pos2[name] local find, _, direction, amount = param:find("([%?%l]+)%s*([+-]?%d+)") if find == nil then worldedit.player_notify(name, "invalid usage: " .. param) return end if pos1 == nil or pos2 == nil then worldedit.player_notify(name, "Undefined region. Region must be defined beforehand.") return end local axis, dir if direction ~= "?" then axis, dir = worldedit.translate_direction(name, direction) else axis, dir = worldedit.player_axis(name) end if axis == nil or dir == nil then return false, "Invalid if looking straight up or down" end assert(worldedit.cuboid_shift(name, axis, amount * dir)) worldedit.marker_update(name) return true, "region shifted by " .. amount .. " nodes" end, } ) minetest.register_chatcommand("/expand", { params = "[+|-]<x|y|z|?|up|down|left|right|front|back> <amount> [reverse-amount]", description = "expand the selection in one or two directions at once", privs = {worldedit=true}, func = function(name, param) local find, _, sign, direction, amount, rev_amount = param:find("([+-]?)([%?%l]+)%s*(%d+)%s*(%d*)") if find == nil then worldedit.player_notify(name, "invalid use: " .. param) return end if worldedit.pos1[name] == nil or worldedit.pos2[name] == nil then worldedit.player_notify(name, "Undefined region. Region must be defined beforehand.") return end local absolute = direction:find("[xyz?]") local dir, axis if rev_amount == "" then rev_amount = 0 end if absolute == nil then axis, dir = worldedit.translate_direction(name, direction) if axis == nil or dir == nil then return false, "Invalid if looking straight up or down" end else if direction == "?" then axis, dir = worldedit.player_axis(name) else axis = direction dir = 1 end end if sign == "-" then dir = -dir end worldedit.cuboid_linear_expand(name, axis, dir, amount) worldedit.cuboid_linear_expand(name, axis, -dir, rev_amount) worldedit.marker_update(name) end, } ) minetest.register_chatcommand("/contract", { params = "[+|-]<x|y|z|?|up|down|left|right|front|back> <amount> [reverse-amount]", description = "contract the selection in one or two directions at once", privs = {worldedit=true}, func = function(name, param) local find, _, sign, direction, amount, rev_amount = param:find("([+-]?)([%?%l]+)%s*(%d+)%s*(%d*)") if find == nil then worldedit.player_notify(name, "invalid use: " .. param) return end if worldedit.pos1[name] == nil or worldedit.pos2[name] == nil then worldedit.player_notify(name, "Undefined region. Region must be defined beforehand.") return end local absolute = direction:find("[xyz?]") local dir, axis if rev_amount == "" then rev_amount = 0 end if absolute == nil then axis, dir = worldedit.translate_direction(name, direction) if axis == nil or dir == nil then return false, "Invalid if looking straight up or down" end else if direction == "?" then axis, dir = worldedit.player_axis(name) else axis = direction dir = 1 end end if sign == "-" then dir = -dir end worldedit.cuboid_linear_expand(name, axis, dir, -amount) worldedit.cuboid_linear_expand(name, axis, -dir, -rev_amount) worldedit.marker_update(name) end, } )
dofile(minetest.get_modpath("worldedit_commands") .. "/cuboidapi.lua") minetest.register_chatcommand("/outset", { params = "[h|v] <amount>", description = "outset the selection", privs = {worldedit=true}, func = function(name, param) local find, _, dir, amount = param:find("(%a*)%s*([+-]?%d+)") if find == nil then return false, "invalid usage: " .. param end local pos1 = worldedit.pos1[name] local pos2 = worldedit.pos2[name] if pos1 == nil or pos2 == nil then return false, "Undefined region. Region must be defined beforehand." end local hv_test = dir:find("[^hv]+") if hv_test ~= nil then return false, "Invalid direction." end if dir == "" or dir == "hv" or dir == "vh" then assert(worldedit.cuboid_volumetric_expand(name, amount)) elseif dir == "h" then assert(worldedit.cuboid_linear_expand(name, 'x', 1, amount)) assert(worldedit.cuboid_linear_expand(name, 'x', -1, amount)) assert(worldedit.cuboid_linear_expand(name, 'z', 1, amount)) assert(worldedit.cuboid_linear_expand(name, 'z', -1, amount)) elseif dir == "v" then assert(worldedit.cuboid_linear_expand(name, 'y', 1, amount)) assert(worldedit.cuboid_linear_expand(name, 'y', -1, amount)) else return false, "Invalid number of arguments" end worldedit.marker_update(name) return true, "Region outset by " .. amount .. " blocks" end, } ) minetest.register_chatcommand("/inset", { params = "[h|v] <amount>", description = "inset the selection", privs = {worldedit=true}, func = function(name, param) local find, _, dir, amount = param:find("(%a*)%s*([+-]?%d+)") if find == nil then return false, "invalid usage: " .. param end local pos1 = worldedit.pos1[name] local pos2 = worldedit.pos2[name] if pos1 == nil or pos2 == nil then return false, "Undefined region. Region must be defined beforehand." end local hv_test = dir:find("[^hv]+") if hv_test ~= nil then return false, "Invalid direction." end if dir == "" or dir == "vh" or dir == "hv" then assert(worldedit.cuboid_volumetric_expand(name, -amount)) elseif dir == "h" then assert(worldedit.cuboid_linear_expand(name, 'x', 1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'x', -1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'z', 1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'z', -1, -amount)) elseif dir == "v" then assert(worldedit.cuboid_linear_expand(name, 'y', 1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'y', -1, -amount)) else return false, "Invalid number of arguments" end worldedit.marker_update(name) return true, "Region inset by " .. amount .. " blocks" end, } ) minetest.register_chatcommand("/shift", { params = "[x|y|z|?|up|down|left|right|front|back] [+|-]<amount>", description = "Moves the selection region. Does not move contents.", privs = {worldedit=true}, func = function(name, param) local pos1 = worldedit.pos1[name] local pos2 = worldedit.pos2[name] local find, _, direction, amount = param:find("([%?%l]+)%s*([+-]?%d+)") if find == nil then worldedit.player_notify(name, "invalid usage: " .. param) return end if pos1 == nil or pos2 == nil then worldedit.player_notify(name, "Undefined region. Region must be defined beforehand.") return end local axis, dir if direction == "x" or direction == "y" or direction == "z" then axis, dir = direction, 1 elseif direction == "?" then axis, dir = worldedit.player_axis(name) else axis, dir = worldedit.translate_direction(name, direction) end if axis == nil or dir == nil then return false, "Invalid if looking straight up or down" end assert(worldedit.cuboid_shift(name, axis, amount * dir)) worldedit.marker_update(name) return true, "region shifted by " .. amount .. " nodes" end, } ) minetest.register_chatcommand("/expand", { params = "[+|-]<x|y|z|?|up|down|left|right|front|back> <amount> [reverse-amount]", description = "expand the selection in one or two directions at once", privs = {worldedit=true}, func = function(name, param) local find, _, sign, direction, amount, rev_amount = param:find("([+-]?)([%?%l]+)%s*(%d+)%s*(%d*)") if find == nil then worldedit.player_notify(name, "invalid use: " .. param) return end if worldedit.pos1[name] == nil or worldedit.pos2[name] == nil then worldedit.player_notify(name, "Undefined region. Region must be defined beforehand.") return end local absolute = direction:find("[xyz?]") local dir, axis if rev_amount == "" then rev_amount = 0 end if absolute == nil then axis, dir = worldedit.translate_direction(name, direction) if axis == nil or dir == nil then return false, "Invalid if looking straight up or down" end else if direction == "?" then axis, dir = worldedit.player_axis(name) else axis = direction dir = 1 end end if sign == "-" then dir = -dir end worldedit.cuboid_linear_expand(name, axis, dir, amount) worldedit.cuboid_linear_expand(name, axis, -dir, rev_amount) worldedit.marker_update(name) end, } ) minetest.register_chatcommand("/contract", { params = "[+|-]<x|y|z|?|up|down|left|right|front|back> <amount> [reverse-amount]", description = "contract the selection in one or two directions at once", privs = {worldedit=true}, func = function(name, param) local find, _, sign, direction, amount, rev_amount = param:find("([+-]?)([%?%l]+)%s*(%d+)%s*(%d*)") if find == nil then worldedit.player_notify(name, "invalid use: " .. param) return end if worldedit.pos1[name] == nil or worldedit.pos2[name] == nil then worldedit.player_notify(name, "Undefined region. Region must be defined beforehand.") return end local absolute = direction:find("[xyz?]") local dir, axis if rev_amount == "" then rev_amount = 0 end if absolute == nil then axis, dir = worldedit.translate_direction(name, direction) if axis == nil or dir == nil then return false, "Invalid if looking straight up or down" end else if direction == "?" then axis, dir = worldedit.player_axis(name) else axis = direction dir = 1 end end if sign == "-" then dir = -dir end worldedit.cuboid_linear_expand(name, axis, dir, -amount) worldedit.cuboid_linear_expand(name, axis, -dir, -rev_amount) worldedit.marker_update(name) end, } )
Fix //shift with absolute axis (x/y/z)
Fix //shift with absolute axis (x/y/z)
Lua
agpl-3.0
Uberi/Minetest-WorldEdit
a492fa546117bf76d5ec9d3e484920551e106948
testserver/item/signpost.lua
testserver/item/signpost.lua
-- Wegweiserskript -- Nitram require("base.common") require("content.signpost") module("item.signpost", package.seeall) -- UPDATE common SET com_script='item.signpost' WHERE com_itemid IN (1817,1809,1808,1807,308,1804,586,3084,3081,3082,3083,519,520,521,337,1914,1915,2046,2069,512,2924,2925,2926,2927); function LookAtItemIdent(User,Item) local test = "no value"; if (first==nil) then content.signpost.InitWegweiser() first=1; end -- fetching local references local signTextDe = content.signpost.signTextDe; local signTextEn = content.signpost.signTextEn; local signCoo = content.signpost.signCoo; local signItemId = content.signpost.signItemId; local signPerception = content.signpost.signPerception; found = false; UserPer = User:increaseAttrib("perception",0); tablePosition = Item.pos.x .. Item.pos.y .. Item.pos.z; if signCoo ~= nil then if (signCoo[tablePosition] ~= nil) then for i, signpos in pairs(signCoo[tablePosition]) do if (Item.pos == signpos) then if (UserPer >= signPerception[tablePosition][i]) then found = true; world:itemInform(User,Item,base.common.GetNLS(User,string.gsub(signTextDe[tablePosition][i],"currentChar",User.name),string.gsub(signTextEn[tablePosition][i],"currentChar",User.name))); test = signTextDe[tablePosition][i]; end end end end end local outText = checkNoobiaSigns(User,Item.pos); if outText and not found then world:itemInform(User,Item,outText); found = true; end if not found then world:itemInform(User,Item,world:getItemName(Item.id,User:getPlayerLanguage())); end end --[[ LookAtItemIdent identity of LookAtItem ]] LookAtItem = LookAtItemIdent;
-- Wegweiserskript -- Nitram require("base.common") require("content.signpost") module("item.signpost", package.seeall) -- UPDATE common SET com_script='item.signpost' WHERE com_itemid IN (1817,1809,1808,1807,308,1804,586,3084,3081,3082,3083,519,520,521,337,1914,1915,2046,2069,512,2924,2925,2926,2927); function LookAtItemIdent(User,Item) if (first==nil) then content.signpost.InitWegweiser() first=1; end -- fetching local references local signTextDe = content.signpost.signTextDe; local signTextEn = content.signpost.signTextEn; local signCoo = content.signpost.signCoo; local signItemId = content.signpost.signItemId; local signPerception = content.signpost.signPerception; local lookAt = base.lookat.GenerateLookAt(User, Item) UserPer = User:increaseAttrib("perception",0); tablePosition = Item.pos.x .. Item.pos.y .. Item.pos.z; if signCoo ~= nil then if (signCoo[tablePosition] ~= nil) then for i, signpos in pairs(signCoo[tablePosition]) do if (Item.pos == signpos) then if (UserPer >= signPerception[tablePosition][i]) then lookAt.description = base.common.GetNLS(User,string.gsub(signTextDe[tablePosition][i],"currentChar",User.name),string.gsub(signTextEn[tablePosition][i],"currentChar",User.name)) end end end end end world:itemInform(User, Item, lookAt) end --[[ LookAtItemIdent identity of LookAtItem ]] LookAtItem = LookAtItemIdent;
Fix signpost lookat
Fix signpost lookat
Lua
agpl-3.0
Baylamon/Illarion-Content,KayMD/Illarion-Content,Illarion-eV/Illarion-Content,vilarion/Illarion-Content,LaFamiglia/Illarion-Content
1b07c4d6e5deb6af713572460abdada6c35792ec
modules/textadept/run.lua
modules/textadept/run.lua
-- Copyright 2007-2010 Mitchell mitchell<att>caladbolg.net. See LICENSE. local L = _G.locale.localize --- -- Module for running/executing source files. -- Typically, language-specific modules populate the 'compile_command', -- 'run_command', and 'error_detail' tables for a particular language's file -- extension. module('_m.textadept.run', package.seeall) --- -- Executes the command line parameter and prints the output to Textadept. -- @param command The command line string. -- It can have the following macros: -- * %(filepath) The full path of the current file. -- * %(filedir) The current file's directory path. -- * %(filename) The name of the file including extension. -- * %(filename_noext) The name of the file excluding extension. function execute(command) local filepath = buffer.filename:iconv(_CHARSET, 'UTF-8') local filedir, filename if filepath:find('[/\\]') then filedir, filename = filepath:match('^(.+[/\\])([^/\\]+)$') else filedir, filename = '', filepath end local filename_noext = filename:match('^(.+)%.') command = command:gsub('%%%b()', { ['%(filepath)'] = filepath, ['%(filedir)'] = filedir, ['%(filename)'] = filename, ['%(filename_noext)'] = filename_noext, }) local current_dir = lfs.currentdir() lfs.chdir(filedir) local p = io.popen(command..' 2>&1') local out = p:read('*all') p:close() lfs.chdir(current_dir) gui.print(('> '..command..'\n'..out):iconv('UTF-8', _CHARSET)) buffer:goto_pos(buffer.length) end --- -- File extensions and their associated 'compile' actions. -- Each key is a file extension whose value is a either a command line string to -- execute or a function returning one. -- This table is typically populated by language-specific modules. -- @class table -- @name compile_command compile_command = {} --- -- Compiles the file as specified by its extension in the compile_command -- table. -- @see compile_command function compile() if not buffer.filename then return end buffer:save() local action = compile_command[buffer.filename:match('[^.]+$')] if action then execute(type(action) == 'function' and action() or action) end end --- -- File extensions and their associated 'go' actions. -- Each key is a file extension whose value is either a command line string to -- execute or a function returning one. -- This table is typically populated by language-specific modules. -- @class table -- @name run_command run_command = {} --- -- Runs/executes the file as specified by its extension in the run_command -- table. -- @see run_command function run() if not buffer.filename then return end buffer:save() local action = run_command[buffer.filename:match('[^.]+$')] if action then execute(type(action) == 'function' and action() or action) end end --- -- A table of error string details. -- Each entry is a table with the following fields: -- pattern: the Lua pattern that matches a specific error string. -- filename: the index of the Lua capture that contains the filename the error -- occured in. -- line: the index of the Lua capture that contains the line number the error -- occured on. -- message: [Optional] the index of the Lua capture that contains the error's -- message. A call tip will be displayed if a message was captured. -- When an error message is double-clicked, the user is taken to the point of -- error. -- This table is usually populated by language-specific modules. -- @class table -- @name error_detail error_detail = {} --- -- When the user double-clicks an error message, go to the line in the file -- the error occured at and display a calltip with the error message. -- @param pos The position of the caret. -- @param line_num The line double-clicked. -- @see error_detail function goto_error(pos, line_num) local type = buffer._type if type == L('[Message Buffer]') or type == L('[Error Buffer]') then line = buffer:get_line(line_num) for _, error_detail in pairs(error_detail) do local captures = { line:match(error_detail.pattern) } if #captures > 0 then local lfs = require 'lfs' local utf8_filename = captures[error_detail.filename] local filename = utf8_filename:iconv(_CHARSET, 'UTF-8') if lfs.attributes(filename) then io.open_file(utf8_filename) _m.textadept.editing.goto_line(captures[error_detail.line]) local msg = captures[error_detail.message] if msg then buffer:call_tip_show(buffer.current_pos, msg) end else error(string.format('"%s" %s', L('does not exist'), utf8_filename)) end break end end end end events.connect('double_click', goto_error)
-- Copyright 2007-2010 Mitchell mitchell<att>caladbolg.net. See LICENSE. local L = _G.locale.localize --- -- Module for running/executing source files. -- Typically, language-specific modules populate the 'compile_command', -- 'run_command', and 'error_detail' tables for a particular language's file -- extension. module('_m.textadept.run', package.seeall) --- -- Executes the command line parameter and prints the output to Textadept. -- @param command The command line string. -- It can have the following macros: -- * %(filepath) The full path of the current file. -- * %(filedir) The current file's directory path. -- * %(filename) The name of the file including extension. -- * %(filename_noext) The name of the file excluding extension. function execute(command) local filepath = buffer.filename:iconv(_CHARSET, 'UTF-8') local filedir, filename if filepath:find('[/\\]') then filedir, filename = filepath:match('^(.+[/\\])([^/\\]+)$') else filedir, filename = '', filepath end local filename_noext = filename:match('^(.+)%.') command = command:gsub('%%%b()', { ['%(filepath)'] = filepath, ['%(filedir)'] = filedir, ['%(filename)'] = filename, ['%(filename_noext)'] = filename_noext, }) local current_dir = lfs.currentdir() lfs.chdir(filedir) local p = io.popen(command..' 2>&1') local out = p:read('*all') p:close() lfs.chdir(current_dir) gui.print(('> '..command..'\n'..out):iconv('UTF-8', _CHARSET)) buffer:goto_pos(buffer.length) end --- -- File extensions and their associated 'compile' actions. -- Each key is a file extension whose value is a either a command line string to -- execute or a function returning one. -- This table is typically populated by language-specific modules. -- @class table -- @name compile_command compile_command = {} --- -- Compiles the file as specified by its extension in the compile_command -- table. -- @see compile_command function compile() if not buffer.filename then return end buffer:save() local action = compile_command[buffer.filename:match('[^.]+$')] if action then execute(type(action) == 'function' and action() or action) end end --- -- File extensions and their associated 'go' actions. -- Each key is a file extension whose value is either a command line string to -- execute or a function returning one. -- This table is typically populated by language-specific modules. -- @class table -- @name run_command run_command = {} --- -- Runs/executes the file as specified by its extension in the run_command -- table. -- @see run_command function run() if not buffer.filename then return end buffer:save() local action = run_command[buffer.filename:match('[^.]+$')] if action then execute(type(action) == 'function' and action() or action) end end --- -- A table of error string details. -- Each entry is a table with the following fields: -- pattern: the Lua pattern that matches a specific error string. -- filename: the index of the Lua capture that contains the filename the error -- occured in. -- line: the index of the Lua capture that contains the line number the error -- occured on. -- message: [Optional] the index of the Lua capture that contains the error's -- message. A call tip will be displayed if a message was captured. -- When an error message is double-clicked, the user is taken to the point of -- error. -- This table is usually populated by language-specific modules. -- @class table -- @name error_detail error_detail = {} --- -- When the user double-clicks an error message, go to the line in the file -- the error occured at and display a calltip with the error message. -- @param pos The position of the caret. -- @param line_num The line double-clicked. -- @see error_detail function goto_error(pos, line_num) local type = buffer._type if type == L('[Message Buffer]') or type == L('[Error Buffer]') then line = buffer:get_line(line_num) for _, error_detail in pairs(error_detail) do local captures = { line:match(error_detail.pattern) } if #captures > 0 then local lfs = require 'lfs' local utf8_filename = captures[error_detail.filename] local filename = utf8_filename:iconv(_CHARSET, 'UTF-8') if lfs.attributes(filename) then io.open_file(utf8_filename) _m.textadept.editing.goto_line(captures[error_detail.line]) local msg = captures[error_detail.message] if msg then buffer:call_tip_show(buffer.current_pos, msg) end else error(string.format('"%s" %s', utf8_filename, L('does not exist')) end break end end end end events.connect('double_click', goto_error)
Fixed bug in modules/textadept/run.lua from localization changes.
Fixed bug in modules/textadept/run.lua from localization changes.
Lua
mit
rgieseke/textadept,rgieseke/textadept
17196beda6029808f36294a126d9c2547c5329ee
mod_s2s_reload_newcomponent/mod_s2s_reload_newcomponent.lua
mod_s2s_reload_newcomponent/mod_s2s_reload_newcomponent.lua
local modulemanager = require "core.modulemanager"; local config = require "core.configmanager"; module.host = "*"; local function reload_components() module:log ("debug", "reload_components"); local defined_hosts = config.getconfig(); for host in pairs(defined_hosts) do module:log ("debug", "found host %s", host); if (not hosts[host] and host ~= "*") then module:log ("debug", "found new host %s", host); modulemanager.load(host, configmanager.get(host, "core", "component_module")); end end; return; end module:hook("config-reloaded", reload_components);
local modulemanager = require "core.modulemanager"; local config = require "core.configmanager"; module.host = "*"; local function reload_components() local defined_hosts = config.getconfig(); for host in pairs(defined_hosts) do if (not hosts[host] and host ~= "*") then module:log ("debug", "loading new component %s", host); modulemanager.load(host, configmanager.get(host, "core", "component_module")); end end; return; end module:hook("config-reloaded", reload_components);
mod_s2s_reload_newcomponent: fix debug logs
mod_s2s_reload_newcomponent: fix debug logs
Lua
mit
mardraze/prosody-modules,softer/prosody-modules,crunchuser/prosody-modules,stephen322/prosody-modules,obelisk21/prosody-modules,brahmi2/prosody-modules,dhotson/prosody-modules,NSAKEY/prosody-modules,heysion/prosody-modules,LanceJenkinZA/prosody-modules,iamliqiang/prosody-modules,jkprg/prosody-modules,LanceJenkinZA/prosody-modules,iamliqiang/prosody-modules,vfedoroff/prosody-modules,NSAKEY/prosody-modules,drdownload/prosody-modules,cryptotoad/prosody-modules,dhotson/prosody-modules,olax/prosody-modules,obelisk21/prosody-modules,crunchuser/prosody-modules,apung/prosody-modules,olax/prosody-modules,mmusial/prosody-modules,mmusial/prosody-modules,heysion/prosody-modules,cryptotoad/prosody-modules,Craige/prosody-modules,1st8/prosody-modules,drdownload/prosody-modules,jkprg/prosody-modules,dhotson/prosody-modules,LanceJenkinZA/prosody-modules,BurmistrovJ/prosody-modules,Craige/prosody-modules,prosody-modules/import,vince06fr/prosody-modules,crunchuser/prosody-modules,LanceJenkinZA/prosody-modules,vfedoroff/prosody-modules,apung/prosody-modules,syntafin/prosody-modules,vince06fr/prosody-modules,heysion/prosody-modules,joewalker/prosody-modules,drdownload/prosody-modules,guilhem/prosody-modules,amenophis1er/prosody-modules,1st8/prosody-modules,mardraze/prosody-modules,guilhem/prosody-modules,BurmistrovJ/prosody-modules,crunchuser/prosody-modules,iamliqiang/prosody-modules,asdofindia/prosody-modules,brahmi2/prosody-modules,either1/prosody-modules,stephen322/prosody-modules,apung/prosody-modules,brahmi2/prosody-modules,amenophis1er/prosody-modules,vfedoroff/prosody-modules,NSAKEY/prosody-modules,obelisk21/prosody-modules,stephen322/prosody-modules,prosody-modules/import,syntafin/prosody-modules,BurmistrovJ/prosody-modules,dhotson/prosody-modules,syntafin/prosody-modules,Craige/prosody-modules,mardraze/prosody-modules,softer/prosody-modules,amenophis1er/prosody-modules,drdownload/prosody-modules,olax/prosody-modules,joewalker/prosody-modules,cryptotoad/prosody-modules,vfedoroff/prosody-modules,jkprg/prosody-modules,either1/prosody-modules,either1/prosody-modules,joewalker/prosody-modules,asdofindia/prosody-modules,cryptotoad/prosody-modules,olax/prosody-modules,syntafin/prosody-modules,cryptotoad/prosody-modules,LanceJenkinZA/prosody-modules,amenophis1er/prosody-modules,stephen322/prosody-modules,obelisk21/prosody-modules,prosody-modules/import,obelisk21/prosody-modules,mmusial/prosody-modules,vince06fr/prosody-modules,either1/prosody-modules,Craige/prosody-modules,guilhem/prosody-modules,mmusial/prosody-modules,brahmi2/prosody-modules,crunchuser/prosody-modules,joewalker/prosody-modules,apung/prosody-modules,stephen322/prosody-modules,asdofindia/prosody-modules,softer/prosody-modules,brahmi2/prosody-modules,dhotson/prosody-modules,softer/prosody-modules,1st8/prosody-modules,1st8/prosody-modules,either1/prosody-modules,jkprg/prosody-modules,joewalker/prosody-modules,olax/prosody-modules,1st8/prosody-modules,drdownload/prosody-modules,vince06fr/prosody-modules,iamliqiang/prosody-modules,mardraze/prosody-modules,heysion/prosody-modules,heysion/prosody-modules,Craige/prosody-modules,NSAKEY/prosody-modules,NSAKEY/prosody-modules,BurmistrovJ/prosody-modules,syntafin/prosody-modules,asdofindia/prosody-modules,guilhem/prosody-modules,vfedoroff/prosody-modules,jkprg/prosody-modules,prosody-modules/import,mardraze/prosody-modules,amenophis1er/prosody-modules,asdofindia/prosody-modules,mmusial/prosody-modules,softer/prosody-modules,vince06fr/prosody-modules,apung/prosody-modules,iamliqiang/prosody-modules,prosody-modules/import,guilhem/prosody-modules,BurmistrovJ/prosody-modules
9a06498dbdf5f5878d2ce86a4b9ac8abc9173bdc
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/memory.lua
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/memory.lua
--[[ (c) 2011 Manuel Munz <freifunk at somakoma dot de> 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 ]]-- module("luci.statistics.rrdtool.definitions.memory",package.seeall) function rrdargs( graph, plugin, plugin_instance, dtype ) return { title = "%H: Memory usage", vlabel = "MB", number_format = "%5.1lf%s", data = { instances = { memory = { "free", "buffered", "cached", "used" } }, options = { memory_buffered = { color = "0000ff", title = "Buffered" }, memory_cached = { color = "ff00ff", title = "Cached" }, memory_used = { color = "ff0000", title = "Used" }, memory_free = { color = "00ff00", title = "Free" } } } } end
--[[ (c) 2011 Manuel Munz <freifunk at somakoma dot de> 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 ]]-- module("luci.statistics.rrdtool.definitions.memory",package.seeall) function rrdargs( graph, plugin, plugin_instance, dtype ) return { title = "%H: Memory usage", vlabel = "MB", number_format = "%5.1lf%s", y_min = "0", alt_autoscale_max = true, data = { instances = { memory = { "free", "buffered", "cached", "used" } }, options = { memory_buffered = { color = "0000ff", title = "Buffered" }, memory_cached = { color = "ff00ff", title = "Cached" }, memory_used = { color = "ff0000", title = "Used" }, memory_free = { color = "00ff00", title = "Free" } } } } end
statistics: memory plugin - improve graph by better scaling of y-axis
statistics: memory plugin - improve graph by better scaling of y-axis Utilise alt_autoscale_max to make the memory chart y-axis to scale better for devices with e.g. 128 MB RAM. Also fix the axis min value to 0. Signed-off-by: Hannu Nyman <ab53a3387de93e31696058c104e6f769cd83fd1b@iki.fi>
Lua
apache-2.0
forward619/luci,oyido/luci,openwrt/luci,zhaoxx063/luci,oyido/luci,chris5560/openwrt-luci,dwmw2/luci,kuoruan/luci,jorgifumi/luci,cshore-firmware/openwrt-luci,daofeng2015/luci,thesabbir/luci,bright-things/ionic-luci,teslamint/luci,taiha/luci,bittorf/luci,rogerpueyo/luci,aa65535/luci,openwrt/luci,lbthomsen/openwrt-luci,bright-things/ionic-luci,urueedi/luci,cappiewu/luci,oneru/luci,dwmw2/luci,cshore/luci,rogerpueyo/luci,schidler/ionic-luci,aa65535/luci,cappiewu/luci,NeoRaider/luci,bright-things/ionic-luci,tobiaswaldvogel/luci,chris5560/openwrt-luci,obsy/luci,oyido/luci,zhaoxx063/luci,marcel-sch/luci,hnyman/luci,thess/OpenWrt-luci,bittorf/luci,Noltari/luci,mumuqz/luci,nmav/luci,taiha/luci,jlopenwrtluci/luci,kuoruan/luci,shangjiyu/luci-with-extra,kuoruan/luci,shangjiyu/luci-with-extra,chris5560/openwrt-luci,zhaoxx063/luci,remakeelectric/luci,remakeelectric/luci,teslamint/luci,nmav/luci,MinFu/luci,shangjiyu/luci-with-extra,nmav/luci,tobiaswaldvogel/luci,kuoruan/lede-luci,urueedi/luci,marcel-sch/luci,chris5560/openwrt-luci,jorgifumi/luci,nmav/luci,981213/luci-1,taiha/luci,wongsyrone/luci-1,zhaoxx063/luci,Hostle/luci,ollie27/openwrt_luci,981213/luci-1,taiha/luci,oneru/luci,teslamint/luci,cshore/luci,rogerpueyo/luci,tobiaswaldvogel/luci,981213/luci-1,nmav/luci,daofeng2015/luci,jlopenwrtluci/luci,joaofvieira/luci,981213/luci-1,marcel-sch/luci,jlopenwrtluci/luci,jchuang1977/luci-1,LuttyYang/luci,tobiaswaldvogel/luci,dwmw2/luci,thess/OpenWrt-luci,tobiaswaldvogel/luci,wongsyrone/luci-1,daofeng2015/luci,bittorf/luci,wongsyrone/luci-1,cshore-firmware/openwrt-luci,NeoRaider/luci,Hostle/luci,schidler/ionic-luci,jchuang1977/luci-1,Wedmer/luci,jlopenwrtluci/luci,cshore-firmware/openwrt-luci,openwrt/luci,artynet/luci,dwmw2/luci,cappiewu/luci,aa65535/luci,MinFu/luci,joaofvieira/luci,obsy/luci,zhaoxx063/luci,artynet/luci,jorgifumi/luci,Hostle/luci,cshore/luci,ollie27/openwrt_luci,dwmw2/luci,oneru/luci,Wedmer/luci,obsy/luci,thesabbir/luci,chris5560/openwrt-luci,Noltari/luci,jorgifumi/luci,bright-things/ionic-luci,aa65535/luci,981213/luci-1,cappiewu/luci,NeoRaider/luci,urueedi/luci,openwrt-es/openwrt-luci,artynet/luci,aa65535/luci,cshore-firmware/openwrt-luci,aa65535/luci,ollie27/openwrt_luci,shangjiyu/luci-with-extra,daofeng2015/luci,Hostle/luci,schidler/ionic-luci,maxrio/luci981213,kuoruan/luci,chris5560/openwrt-luci,LuttyYang/luci,Noltari/luci,tobiaswaldvogel/luci,dwmw2/luci,oyido/luci,LuttyYang/luci,thesabbir/luci,chris5560/openwrt-luci,hnyman/luci,NeoRaider/luci,joaofvieira/luci,cshore/luci,daofeng2015/luci,artynet/luci,981213/luci-1,bittorf/luci,dwmw2/luci,cappiewu/luci,maxrio/luci981213,NeoRaider/luci,mumuqz/luci,bittorf/luci,maxrio/luci981213,kuoruan/luci,maxrio/luci981213,zhaoxx063/luci,Wedmer/luci,NeoRaider/luci,zhaoxx063/luci,teslamint/luci,Noltari/luci,LuttyYang/luci,oneru/luci,urueedi/luci,aa65535/luci,teslamint/luci,artynet/luci,aa65535/luci,joaofvieira/luci,remakeelectric/luci,Hostle/luci,MinFu/luci,kuoruan/lede-luci,jlopenwrtluci/luci,lbthomsen/openwrt-luci,openwrt/luci,jorgifumi/luci,mumuqz/luci,teslamint/luci,cshore/luci,Noltari/luci,Hostle/luci,kuoruan/luci,marcel-sch/luci,jchuang1977/luci-1,mumuqz/luci,cshore-firmware/openwrt-luci,thess/OpenWrt-luci,marcel-sch/luci,remakeelectric/luci,oneru/luci,openwrt-es/openwrt-luci,remakeelectric/luci,bittorf/luci,Noltari/luci,urueedi/luci,nmav/luci,cshore-firmware/openwrt-luci,kuoruan/lede-luci,thess/OpenWrt-luci,artynet/luci,ollie27/openwrt_luci,thess/OpenWrt-luci,forward619/luci,MinFu/luci,jchuang1977/luci-1,remakeelectric/luci,kuoruan/lede-luci,daofeng2015/luci,daofeng2015/luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,dwmw2/luci,oyido/luci,kuoruan/luci,openwrt-es/openwrt-luci,tobiaswaldvogel/luci,obsy/luci,Noltari/luci,thess/OpenWrt-luci,nmav/luci,zhaoxx063/luci,mumuqz/luci,chris5560/openwrt-luci,jorgifumi/luci,artynet/luci,mumuqz/luci,lbthomsen/openwrt-luci,teslamint/luci,kuoruan/lede-luci,openwrt/luci,Noltari/luci,forward619/luci,rogerpueyo/luci,oyido/luci,shangjiyu/luci-with-extra,shangjiyu/luci-with-extra,thesabbir/luci,NeoRaider/luci,openwrt/luci,hnyman/luci,Wedmer/luci,bittorf/luci,jchuang1977/luci-1,artynet/luci,Wedmer/luci,MinFu/luci,rogerpueyo/luci,cshore/luci,jorgifumi/luci,Wedmer/luci,schidler/ionic-luci,rogerpueyo/luci,maxrio/luci981213,forward619/luci,openwrt-es/openwrt-luci,ollie27/openwrt_luci,schidler/ionic-luci,cappiewu/luci,jchuang1977/luci-1,schidler/ionic-luci,oyido/luci,marcel-sch/luci,nmav/luci,cshore/luci,wongsyrone/luci-1,openwrt-es/openwrt-luci,jchuang1977/luci-1,openwrt/luci,NeoRaider/luci,thesabbir/luci,thess/OpenWrt-luci,ollie27/openwrt_luci,remakeelectric/luci,forward619/luci,wongsyrone/luci-1,hnyman/luci,LuttyYang/luci,cappiewu/luci,maxrio/luci981213,kuoruan/lede-luci,kuoruan/lede-luci,schidler/ionic-luci,rogerpueyo/luci,remakeelectric/luci,oneru/luci,cshore-firmware/openwrt-luci,shangjiyu/luci-with-extra,openwrt-es/openwrt-luci,obsy/luci,Wedmer/luci,mumuqz/luci,lbthomsen/openwrt-luci,bright-things/ionic-luci,maxrio/luci981213,lbthomsen/openwrt-luci,nmav/luci,oneru/luci,artynet/luci,hnyman/luci,openwrt/luci,wongsyrone/luci-1,cshore/luci,hnyman/luci,cshore-firmware/openwrt-luci,marcel-sch/luci,ollie27/openwrt_luci,hnyman/luci,thess/OpenWrt-luci,bright-things/ionic-luci,lbthomsen/openwrt-luci,marcel-sch/luci,obsy/luci,981213/luci-1,Hostle/luci,obsy/luci,bright-things/ionic-luci,urueedi/luci,jorgifumi/luci,maxrio/luci981213,rogerpueyo/luci,taiha/luci,joaofvieira/luci,thesabbir/luci,joaofvieira/luci,wongsyrone/luci-1,oyido/luci,hnyman/luci,jlopenwrtluci/luci,jlopenwrtluci/luci,obsy/luci,MinFu/luci,LuttyYang/luci,Hostle/luci,LuttyYang/luci,cappiewu/luci,Wedmer/luci,joaofvieira/luci,shangjiyu/luci-with-extra,jlopenwrtluci/luci,schidler/ionic-luci,urueedi/luci,urueedi/luci,daofeng2015/luci,thesabbir/luci,oneru/luci,taiha/luci,kuoruan/luci,teslamint/luci,jchuang1977/luci-1,bittorf/luci,thesabbir/luci,Noltari/luci,taiha/luci,openwrt-es/openwrt-luci,ollie27/openwrt_luci,mumuqz/luci,forward619/luci,MinFu/luci,kuoruan/lede-luci,tobiaswaldvogel/luci,forward619/luci,forward619/luci,wongsyrone/luci-1,bright-things/ionic-luci,lbthomsen/openwrt-luci,taiha/luci,LuttyYang/luci,joaofvieira/luci,MinFu/luci
7fa9b042017afb0af17e3db15c99d46c7619624b
lib/drivers/abbott/tools/fslibre_usb_dissector.lua
lib/drivers/abbott/tools/fslibre_usb_dissector.lua
-- -- Wireshark plugin to dissect the USB HID packets of the Abbott FreeStyle Libre -- -- TODO: does not yet handle AAP frame reassembly local fslibre_usb = Proto("fslibre_usb", "Abbott FreeStyle Libre USB Protocol") local fslibre_dump = ProtoField.new("FSLibre Dump", "fslibre_usb.dump", ftypes.BYTES) local command = ProtoField.new("Command", "fslibre_usb.command", ftypes.UINT8, nil, base.HEX) local data_length = ProtoField.new("Data Length", "fslibre_usb.data_length", ftypes.UINT8) local text = ProtoField.new("Text", "fslibre_usb.text", ftypes.STRING) local atp_frame = ProtoField.new("ATP Frame", "fslibre_usb.atp", ftypes.NONE) local atp_data = ProtoField.new("ATP Data", "fslibre_usb.atp.data", ftypes.BYTES) local atp_sequence_received = ProtoField.new("ATP Seq Rx", "fslibre_usb.atp.sequence_received", ftypes.UINT8) local atp_sequence_sent = ProtoField.new("ATP Seq Tx", "fslibre_usb.atp.sequence_sent", ftypes.UINT8) local atp_crc32 = ProtoField.new("ATP CRC32", "fslibre_usb.atp.crc32", ftypes.UINT32, nil, base.HEX) local aap_frame = ProtoField.new("AAP Frame", "fslibre_usb.aap", ftypes.NONE) local aap_data_length = ProtoField.new("AAP Data Length", "fslibre_usb.aap.data_length", ftypes.UINT32) local aap_op_code = ProtoField.new("AAP OP Code", "fslibre_usb.aap.op_code", ftypes.UINT8, nil, base.HEX) local aap_data = ProtoField.new("AAP Data", "fslibre_usb.aap.data", ftypes.BYTES) fslibre_usb.fields = { fslibre_dump, command, text, atp_frame, data_length, atp_data, atp_sequence_received, atp_sequence_sent, atp_crc32, aap_frame, aap_data_length, aap_op_code, aap_data } local hid_report_length = 64 local function dissect_aap(atp_payload_buf, pktinfo, atp_tree) local aap_frame_offset = 0 repeat local aap_data_length_num_bytes = 0 local aap_data_length_value = 0 -- the first 0 to 3 bytes describe the aap frame length in their lower 7 bits for i = 0, 2 do local byte_value = atp_payload_buf:range(aap_frame_offset + i, 1):uint() -- if highest bit is not set, this is already the command byte if not bit32.btest(byte_value, 0x80) then break end -- highest bit was set, add lower 7 bits to length value aap_data_length_value = bit32.lshift(aap_data_length_value, 7) aap_data_length_value = bit32.bor(aap_data_length_value, bit32.band(byte_value, 0x7f)) aap_data_length_num_bytes = aap_data_length_num_bytes + 1 end -- check that opcode does not have the highest bit set, otherwise cancel parsing due to faulty data local aap_op_code_value = atp_payload_buf:range(aap_frame_offset + aap_data_length_num_bytes, 1):uint() if bit32.btest(aap_op_code_value, 0x80) then break end local aap_data_offset = aap_frame_offset + aap_data_length_num_bytes + 1 local aap_data_length_in_this_frame = math.min(atp_payload_buf:len() - aap_data_offset, aap_data_length_value) -- add new aap sub-tree local aap_tree = atp_tree:add(aap_frame, atp_payload_buf:range(aap_frame_offset, aap_data_length_num_bytes + 1 + aap_data_length_in_this_frame)) -- mark the aap data length bytes at the aap frame start aap_tree:add(aap_data_length, atp_payload_buf:range(aap_frame_offset, aap_data_length_num_bytes), aap_data_length_value) -- aap op code is the first byte after the aap length aap_tree:add(aap_op_code, atp_payload_buf:range(aap_frame_offset + aap_data_length_num_bytes, 1)) if aap_data_length_value > 0 then -- aap data bytes start after the op code aap_tree:add(aap_data, atp_payload_buf:range(aap_data_offset, aap_data_length_in_this_frame)) end aap_frame_offset = aap_data_offset + aap_data_length_value until aap_frame_offset >= atp_payload_buf:len() end function fslibre_usb.dissector(tvbuf, pktinfo, root) pktinfo.cols.protocol:set("fslibre_usb") local pktlen = tvbuf:reported_length_remaining() local hid_report_buf if pktlen < hid_report_length then return pktlen elseif pktlen == hid_report_length then hid_report_buf = tvbuf elseif pktlen > hid_report_length then hid_report_buf = tvbuf:range(pktlen - hid_report_length, hid_report_length):tvb() end pktinfo.cols.protocol = fslibre_usb.name local command_value = hid_report_buf:range(0, 1):uint() local data_length_value = hid_report_buf:range(1, 1):uint() local tree = root:add(fslibre_usb, hid_report_buf:range(0, 2 + data_length_value)) -- add hidden field that can be used in custom column to show whole packet data tree:add(fslibre_dump, hid_report_buf:range(0, 2 + data_length_value)):set_hidden() -- actually the command is only in the lower 6 bits of the first byte, -- but the 2 high bits are currently always 0 anyhow tree:add(command, hid_report_buf:range(0, 1)) tree:add(data_length, hid_report_buf:range(1, 1)) if data_length_value > 0 then local data_offset = 2 if command_value == 0x60 or command_value == 0x21 or command_value == 0x06 or command_value == 0x35 then tree:add(text, hid_report_buf:range(data_offset, data_length_value)) else local atp_tree = tree:add(atp_frame, hid_report_buf:range(data_offset, data_length_value)) local atp_data_buf = hid_report_buf:range(data_offset, data_length_value):tvb() atp_tree:add(atp_data, atp_data_buf:range()):set_hidden() if data_length_value > 4 then atp_tree:add(atp_sequence_received, atp_data_buf:range(0, 1)) atp_tree:add(atp_sequence_sent, atp_data_buf:range(1, 1)) atp_tree:add(atp_crc32, atp_data_buf:range(2, 4)) if data_length_value > 6 then dissect_aap(atp_data_buf:range(6):tvb(), pktinfo, atp_tree) end end end end return pktlen end function fslibre_usb.init() -- register this disector for USB vendor:product 1a61:3650 DissectorTable.get("usb.product"):add(0x1a613650, fslibre_usb) end
-- -- Wireshark plugin to dissect the USB HID packets of the Abbott FreeStyle Libre -- -- TODO: does not yet handle AAP frame reassembly local fslibre_usb = Proto("fslibre_usb", "Abbott FreeStyle Libre USB Protocol") local fslibre_dump = ProtoField.new("FSLibre Dump", "fslibre_usb.dump", ftypes.BYTES) local command = ProtoField.new("Command", "fslibre_usb.command", ftypes.UINT8, nil, base.HEX) local data_length = ProtoField.new("Data Length", "fslibre_usb.data_length", ftypes.UINT8) local text = ProtoField.new("Text", "fslibre_usb.text", ftypes.STRING) local atp_frame = ProtoField.new("ATP Frame", "fslibre_usb.atp", ftypes.NONE) local atp_data = ProtoField.new("ATP Data", "fslibre_usb.atp.data", ftypes.BYTES) local atp_sequence_received = ProtoField.new("ATP Seq Rx", "fslibre_usb.atp.sequence_received", ftypes.UINT8) local atp_sequence_sent = ProtoField.new("ATP Seq Tx", "fslibre_usb.atp.sequence_sent", ftypes.UINT8) local atp_crc32 = ProtoField.new("ATP CRC32", "fslibre_usb.atp.crc32", ftypes.UINT32, nil, base.HEX) local atp_unknown = ProtoField.new("ATP UNKNOWN", "fslibre_usb.atp.unknown", ftypes.UINT16, nil, base.HEX) local aap_frame = ProtoField.new("AAP Frame", "fslibre_usb.aap", ftypes.NONE) local aap_data_length = ProtoField.new("AAP Data Length", "fslibre_usb.aap.data_length", ftypes.UINT32) local aap_op_code = ProtoField.new("AAP OP Code", "fslibre_usb.aap.op_code", ftypes.UINT8, nil, base.HEX) local aap_data = ProtoField.new("AAP Data", "fslibre_usb.aap.data", ftypes.BYTES) fslibre_usb.fields = { fslibre_dump, command, text, atp_frame, data_length, atp_data, atp_sequence_received, atp_sequence_sent, atp_crc32, atp_unknown, aap_frame, aap_data_length, aap_op_code, aap_data } local hid_report_length = 64 local function dissect_aap(atp_payload_buf, pktinfo, atp_tree) local aap_frame_offset = 0 repeat local aap_data_length_num_bytes = 0 local aap_data_length_value = 0 -- the first 0 to 3 bytes describe the aap frame length in their lower 7 bits for i = 0, 2 do local byte_value = atp_payload_buf:range(aap_frame_offset + i, 1):uint() -- if highest bit is not set, this is already the command byte if not bit32.btest(byte_value, 0x80) then break end -- highest bit was set, add lower 7 bits to length value aap_data_length_value = bit32.lshift(aap_data_length_value, 7) aap_data_length_value = bit32.bor(aap_data_length_value, bit32.band(byte_value, 0x7f)) aap_data_length_num_bytes = aap_data_length_num_bytes + 1 end -- check that opcode does not have the highest bit set, otherwise cancel parsing due to faulty data local aap_op_code_value = atp_payload_buf:range(aap_frame_offset + aap_data_length_num_bytes, 1):uint() if bit32.btest(aap_op_code_value, 0x80) then break end local aap_data_offset = aap_frame_offset + aap_data_length_num_bytes + 1 local aap_data_length_in_this_frame = math.min(atp_payload_buf:len() - aap_data_offset, aap_data_length_value) -- add new aap sub-tree local aap_tree = atp_tree:add(aap_frame, atp_payload_buf:range(aap_frame_offset, aap_data_length_num_bytes + 1 + aap_data_length_in_this_frame)) -- mark the aap data length bytes at the aap frame start aap_tree:add(aap_data_length, atp_payload_buf:range(aap_frame_offset, aap_data_length_num_bytes), aap_data_length_value) -- aap op code is the first byte after the aap length aap_tree:add(aap_op_code, atp_payload_buf:range(aap_frame_offset + aap_data_length_num_bytes, 1)) if aap_data_length_value > 0 then -- aap data bytes start after the op code aap_tree:add(aap_data, atp_payload_buf:range(aap_data_offset, aap_data_length_in_this_frame)) end aap_frame_offset = aap_data_offset + aap_data_length_value until aap_frame_offset >= atp_payload_buf:len() end function fslibre_usb.dissector(tvbuf, pktinfo, root) pktinfo.cols.protocol:set("fslibre_usb") local pktlen = tvbuf:reported_length_remaining() local hid_report_buf if pktlen < hid_report_length then return pktlen elseif pktlen == hid_report_length then hid_report_buf = tvbuf elseif pktlen > hid_report_length then hid_report_buf = tvbuf:range(pktlen - hid_report_length, hid_report_length):tvb() end pktinfo.cols.protocol = fslibre_usb.name local command_value = hid_report_buf:range(0, 1):uint() local data_length_value = hid_report_buf:range(1, 1):uint() local tree = root:add(fslibre_usb, hid_report_buf:range(0, 2 + data_length_value)) -- add hidden field that can be used in custom column to show whole packet data tree:add(fslibre_dump, hid_report_buf:range(0, 2 + data_length_value)):set_hidden() -- actually the command is only in the lower 6 bits of the first byte, -- but the 2 high bits are currently always 0 anyhow tree:add(command, hid_report_buf:range(0, 1)) tree:add(data_length, hid_report_buf:range(1, 1)) if data_length_value > 0 then local data_offset = 2 if command_value == 0x60 or command_value == 0x21 or command_value == 0x06 or command_value == 0x35 then tree:add(text, hid_report_buf:range(data_offset, data_length_value)) else local atp_tree = tree:add(atp_frame, hid_report_buf:range(data_offset, data_length_value)) local atp_data_buf = hid_report_buf:range(data_offset, data_length_value):tvb() atp_tree:add(atp_data, atp_data_buf:range()):set_hidden() if data_length_value >= 2 then atp_tree:add(atp_sequence_received, atp_data_buf:range(0, 1)) atp_tree:add(atp_sequence_sent, atp_data_buf:range(1, 1)) if data_length_value >= 6 then atp_tree:add(atp_crc32, atp_data_buf:range(2, 4)) if data_length_value > 6 then dissect_aap(atp_data_buf:range(6):tvb(), pktinfo, atp_tree) end elseif data_length_value == 4 then atp_tree:add(atp_unknown, atp_data_buf:range(2, 2)) end end end end return pktlen end function fslibre_usb.init() -- register this disector for USB vendor:product 1a61:3650 DissectorTable.get("usb.product"):add(0x1a613650, fslibre_usb) end
small fixes to wireshark protocol dissector
small fixes to wireshark protocol dissector
Lua
bsd-2-clause
tidepool-org/chrome-uploader,tidepool-org/chrome-uploader,tidepool-org/chrome-uploader
9ffa7f1ca4417fb1835fcd942d7c950058dcfc5e
src/rspamadm/stat_convert.lua
src/rspamadm/stat_convert.lua
local sqlite3 = require "rspamd_sqlite3" local redis = require "rspamd_redis" local _ = require "fun" local function send_redis(server, symbol, tokens) local ret = true local args = {} _.each(function(t) if not args[t[3]] then args[t[3]] = {symbol .. t[3]} end table.insert(args[t[3]], t[1]) table.insert(args[t[3]], t[2]) end, tokens) _.each(function(k, argv) if not redis.make_request_sync({ host = server, cmd = 'HMSET', args = argv }) then ret = false end end, args) return ret end return function (args, res) local db = sqlite3.open(res['source_db']) local tokens = {} local num = 0 local lim = 100 -- Update each 100 tokens local users_map = {} local learns = {} if not db then print('Cannot open source db: ' .. res['source_db']) return end db:sql('BEGIN;') -- Fill users mapping for row in db:rows('SELECT * FROM users;') do users_map[row.id] = row.name learns[row.id] = row.learned end -- Fill tokens, sending data to redis each `lim` records for row in db:rows('SELECT token,value,user FROM tokens;') do local user = '' if row.user ~= 0 and users_map[row.user] then user = users_map[row.user] end table.insert(tokens, {row.token, row.value, user}) num = num + 1 if num > lim then if not send_redis(res['redis_host'], res['symbol'], tokens, users_map) then print('Cannot send tokens to the redis server') return end num = 0 tokens = {} end end db:sql('COMMIT;') end
local sqlite3 = require "rspamd_sqlite3" local redis = require "rspamd_redis" local _ = require "fun" local function send_redis(server, symbol, tokens) local ret = true local args = {} _.each(function(t) if not args[t[3]] then args[t[3]] = {symbol .. t[3]} end table.insert(args[t[3]], t[1]) table.insert(args[t[3]], t[2]) end, tokens) _.each(function(k, argv) if not redis.make_request_sync({ host = server, cmd = 'HMSET', args = argv }) then ret = false end end, args) return ret end return function (args, res) local db = sqlite3.open(res['source_db']) local tokens = {} local num = 0 local total = 0 local nusers = 0 local lim = 1000 -- Update each 1000 tokens local users_map = {} local learns = {} if not db then print('Cannot open source db: ' .. res['source_db']) return end db:sql('BEGIN;') -- Fill users mapping for row in db:rows('SELECT * FROM users;') do if row.id == '0' then users_map[row.id] = '' else users_map[row.id] = row.name end learns[row.id] = row.learned nusers = nusers + 1 end -- Fill tokens, sending data to redis each `lim` records for row in db:rows('SELECT token,value,user FROM tokens;') do local user = '' if row.user ~= 0 and users_map[row.user] then user = users_map[row.user] end table.insert(tokens, {row.token, row.value, user}) num = num + 1 total = total + 1 if num > lim then if not send_redis(res['redis_host'], res['symbol'], tokens, users_map) then print('Cannot send tokens to the redis server') return end num = 0 tokens = {} end end if #tokens > 0 and not send_redis(res['redis_host'], res['symbol'], tokens, users_map) then print('Cannot send tokens to the redis server') return end -- Now update all users _.each(function(id, learned) local user = users_map[id] if not redis.make_request_sync({ host = server, cmd = 'HSET', args = {symbol .. user, 'learns', learned} }) then print('Cannot update learns for user: ' .. user) end end, learns) db:sql('COMMIT;') print(string.format('Migrated %d tokens for %d users for symbol %s', total, nusers, res['symbol'])) end
Fix stat migration script
Fix stat migration script
Lua
bsd-2-clause
AlexeySa/rspamd,AlexeySa/rspamd,minaevmike/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,minaevmike/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,minaevmike/rspamd,minaevmike/rspamd,minaevmike/rspamd,minaevmike/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,minaevmike/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,andrejzverev/rspamd
de71b820558479920842537ad6a0f914e80fabb5
kong/plugins/filelog/log.lua
kong/plugins/filelog/log.lua
-- Copyright (C) Mashape, Inc. local ffi = require "ffi" local bit = require "bit" local cjson = require "cjson" local fd_util = require "kong.plugins.filelog.fd_util" local basic_serializer = require "kong.plugins.log_serializers.basic" ffi.cdef[[ int open(char * filename, int flags, int mode); int write(int fd, void * ptr, int numbytes); ]] local O_CREAT = 0x0200 local O_APPEND = 0x0008 local O_WRONLY = 0x0001 local S_IWUSR = 0000200 local S_IRUSR = 0000400 local S_IROTH = 0000004 local function string_to_char(str) return ffi.cast("uint8_t*", str) end -- Log to a file -- @param `premature` -- @param `conf` Configuration table, holds http endpoint details -- @param `message` Message to be logged local function log(premature, conf, message) message = cjson.encode(message).."\n" local fd = fd_util.get_fd(conf.path) if not fd then fd = ffi.C.open(string_to_char(conf.path), bit.bor(O_CREAT, O_APPEND, O_WRONLY), bit.bor(S_IWUSR, S_IRUSR, S_IROTH)) fd_util.set_fd(conf.path, fd) end ffi.C.write(fd, string_to_char(message), string.len(message)) end local _M = {} function _M.execute(conf) local message = basic_serializer.serialize(ngx) local ok, err = ngx.timer.at(0, log, conf, message) if not ok then ngx.log(ngx.ERR, "[filelog] failed to create timer: ", err) end end return _M
-- Copyright (C) Mashape, Inc. local ffi = require "ffi" local bit = require "bit" local cjson = require "cjson" local fd_util = require "kong.plugins.filelog.fd_util" local basic_serializer = require "kong.plugins.log_serializers.basic" ffi.cdef[[ int open(char * filename, int flags, int mode); int write(int fd, void * ptr, int numbytes); ]] local octal = function(n) return tonumber(n, 8) end local O_CREAT = octal('0100') local O_APPEND = octal('02000') local O_WRONLY = octal('0001') local S_IWUSR = octal('00200') local S_IRUSR = octal('00400') local S_IXUSR = octal('00100') local function string_to_char(str) return ffi.cast("uint8_t*", str) end -- Log to a file -- @param `premature` -- @param `conf` Configuration table, holds http endpoint details -- @param `message` Message to be logged local function log(premature, conf, message) message = cjson.encode(message).."\n" local fd = fd_util.get_fd(conf.path) if not fd then fd = ffi.C.open(string_to_char(conf.path), bit.bor(O_CREAT, O_APPEND, O_WRONLY), bit.bor(S_IWUSR, S_IRUSR, S_IXUSR)) fd_util.set_fd(conf.path, fd) end ffi.C.write(fd, string_to_char(message), string.len(message)) end local _M = {} function _M.execute(conf) local message = basic_serializer.serialize(ngx) local ok, err = ngx.timer.at(0, log, conf, message) if not ok then ngx.log(ngx.ERR, "[filelog] failed to create timer: ", err) end end return _M
Fixing file permissions, closes #461
Fixing file permissions, closes #461 Former-commit-id: 47692e9b4f9c72e331df3a164eeb6b247b2fe83c
Lua
apache-2.0
jebenexer/kong,akh00/kong,ind9/kong,vzaramel/kong,icyxp/kong,vzaramel/kong,kyroskoh/kong,rafael/kong,ajayk/kong,kyroskoh/kong,Kong/kong,Vermeille/kong,shiprabehera/kong,ind9/kong,beauli/kong,li-wl/kong,isdom/kong,ccyphers/kong,ejoncas/kong,smanolache/kong,Mashape/kong,jerizm/kong,xvaara/kong,Kong/kong,Kong/kong,ejoncas/kong,isdom/kong,rafael/kong,streamdataio/kong,salazar/kong,streamdataio/kong
4a83d3a188e22728bafa2c428212ff95efc1929e
plugins/weather.lua
plugins/weather.lua
do local BASE_URL = "http://api.openweathermap.org/data/2.5/weather" local function get_weather(location) print("Finding weather in ", location) local url = BASE_URL url = url.."?q="..location url = url.."&units=metric" url = url.."&appid=61cc78f1feb326ba7f3d3948ad690671" print(url) local b, c, h = http.request(url) if c ~= 200 then return nil end local weather = json:decode(b) local city = weather.name local country = weather.sys.country local temp = 'The temperature in '..city ..' (' ..country..')' ..' is '..weather.main.temp..'°C' local conditions = 'Current conditions are: ' .. weather.weather[1].description if weather.weather[1].main == 'Clear' then conditions = conditions .. ' ☀' elseif weather.weather[1].main == 'Clouds' then conditions = conditions .. ' ☁☁' elseif weather.weather[1].main == 'Rain' then conditions = conditions .. ' ☔' elseif weather.weather[1].main == 'Thunderstorm' then conditions = conditions .. ' ☔☔☔☔' end return temp .. '\n' .. conditions end local function run(msg, matches) local city = 'Venezia' if matches[1] ~= '!weather' then city = matches[1] end local text = get_weather(city) if not text then text = 'Can\'t get weather from that city.' end return text end return { description = "weather in that city (Venezia is default)", usage = "!weather (city)", patterns = { "^!weather$", "^!weather (.*)$" }, run = run } end
do local BASE_URL = "http://api.openweathermap.org/data/2.5/weather" local API_KEY = "" local function get_weather(location) print("Finding weather in ", location) local url = BASE_URL url = url.."?q="..location url = url.."&units=metric" url = url.."&appid="..API_KEY print(url) local b, c, h = http.request(url) if c ~= 200 then return nil end local weather = json:decode(b) local city = weather.name local country = weather.sys.country local temp = 'The temperature in '..city ..' (' ..country..')' ..' is '..weather.main.temp..'°C' local conditions = 'Current conditions are: ' .. weather.weather[1].description if weather.weather[1].main == 'Clear' then conditions = conditions .. ' ☀' elseif weather.weather[1].main == 'Clouds' then conditions = conditions .. ' ☁☁' elseif weather.weather[1].main == 'Rain' then conditions = conditions .. ' ☔' elseif weather.weather[1].main == 'Thunderstorm' then conditions = conditions .. ' ☔☔☔☔' end return temp .. '\n' .. conditions end local function run(msg, matches) local city = 'Venezia' if matches[1] ~= '!weather' then city = matches[1] end local text = get_weather(city) if not text then text = 'Can\'t get weather from that city.' end return text end return { description = "weather in that city (Venezia is default)", usage = "!weather (city)", patterns = { "^!weather$", "^!weather (.*)$" }, run = run } end
Bug fix
Bug fix
Lua
mit
KevinGuarnati/controllore,KevinGuarnati/controllore
39c68c3d90c7c7ddaff4fd37f3f81e503670d19e
testserver/npc/base/talk.lua
testserver/npc/base/talk.lua
--- Base NPC script for talking NPCs -- -- This script offers all functions needed to get NPCs to talk. -- -- Author: Martin Karing require("base.common") require("base.messages") require("base.class") require("npc.base.basic") require("npc.base.responses") module("npc.base.talk", package.seeall) talkNPC = base.class.class(function(self, rootNPC) if (rootNPC == nil or not rootNPC:is_a(npc.base.basic.baseNPC)) then return; end; self["_parent"] = rootNPC; self["_entry"] = nil; self["_cycleText"] = nil; self["_state"] = 0; self["_saidNumber"] = nil; self["_nextCycleText"] = -1; end); function talkNPC:addCycleText(germanText, englishText) if (self._cycleText == nil) then self._cycleText = base.messages.Messages(); self._parent:addCycle(self); end; self._cycleText:addMessage(germanText, englishText); end; function talkNPC:addTalkingEntry(newEntry) if (newEntry == nil or not newEntry:is_a(talkNPCEntry)) then return; end; if (self._entry == nil) then self._parent:addRecvText(self); self._entry = {}; end; newEntry:setParent(self); table.insert(self._entry, newEntry); end; function talkNPC:receiveText(npcChar, player, text) local result = false; table.foreach(self._entry, function(_, entry) if entry:checkEntry(npcChar, player, text) then entry:execute(npcChar, player); result = true; return true; end; end); return result; end; function talkNPC:nextCycle(npcChar, counter) if (counter >= self._nextCycleText) then self._nextCycleText = math.random(1200, 3600); --2 to 6 minutes local german, english = self._cycleText:getRandomMessage(); npcChar:talkLanguage(Character.say, Player.german, german); npcChar:talkLanguage(Character.say, Player.english, english); else self._nextCycleText = self._nextCycleText - counter; end; return self._nextCycleText; end; talkNPCEntry = base.class.class(function(self) self["_trigger"] = {}; self["_conditions"] = {}; self["_responses"] = {}; self["_responseProcessors"] = {}; self["_responsesCount"] = 0; self["_consequences"] = {}; self["_parent"] = nil; end); function talkNPCEntry:addTrigger(text) if (text == nil or type(text) ~= "string") then return; end; text = string.lower(text); text = string.gsub(text,'([ ]+)',' .*'); -- replace all spaces by " .*" table.insert(self._trigger, text); end; function talkNPCEntry:setParent(npc) local updateFkt = function(_, value) value:setNPC(npc); end; table.foreach(self._conditions, updateFkt); table.foreach(self._consequences, updateFkt); self._parent = npc; end; function talkNPCEntry:addCondition(condition) if (condition == nil or not condition:is_a(npc.base.condition.condition.condition)) then return; end; table.insert(self._conditions, condition); if (self._parent ~= nil) then condition:setNPC(self._parent); end; end; function talkNPCEntry:addResponse(text) if (text == nil or type(text) ~= "string") then return; end; table.insert(self._responses, text); self._responsesCount = self._responsesCount + 1; for _, processor in pairs(npc.base.responses.processorList) do if processor:check(text) then if (self._responseProcessors[self._responsesCount] == nil) then self._responseProcessors[self._responsesCount] = {}; end; table.insert(self._responseProcessors[self._responsesCount], processor) end; end; end; function talkNPCEntry:addConsequence(consequence) if (consequence == nil or not consequence:is_a(npc.base.consequence.consequence.consequence)) then return; end; table.insert(self._consequences, consequence); if (self._parent ~= nil) then consequence:setNPC(self._parent); end; end; function talkNPCEntry:checkEntry(npcChar, player, text) for _1, pattern in pairs(self._trigger) do local a, _2, number = string.find(text, pattern); self._saidNumber = number; if (a ~= nil) then local conditionsResult = true; for _3, condition in pairs(self._conditions) do if not condition:check(npcChar, player) then conditionsResult = false; break; end; end; if conditionsResult then return true; end; end; end; end; function talkNPCEntry:execute(npcChar, player) if (self._responsesCount > 0) then local selectedResponse = math.random(1, self._responsesCount); local responseText = self._responses[selectedResponse]; local responseProcessors = self._responseProcessors[selectedResponse]; if (responseProcessors ~= nil) then for _, processor in pairs(responseProcessors) do responseText = processor:process(player, self._parent, npcChar, responseText); end; end; npcChar:talk(Character.say, responseText); end; table.foreach(self._consequences, function(_, consequence) if consequence then consequence:perform(npcChar, player); end; end); end; function _set_value(value) if (type(value) == "function") then return value, 2; elseif (value == "%NUMBER") then return nil, 1; else return tonumber(value), 0; end; end; function _get_value(npc, value, type) if (type == 2) then return value(npc._saidNumber); elseif (type == 1) then return npc._saidNumber; elseif (type == 0) then return value; else return 0; end; end;
--- Base NPC script for talking NPCs -- -- This script offers all functions needed to get NPCs to talk. -- -- Author: Martin Karing require("base.common") require("base.messages") require("base.class") require("npc.base.basic") require("npc.base.responses") module("npc.base.talk", package.seeall) talkNPC = base.class.class(function(self, rootNPC) if (rootNPC == nil or not rootNPC:is_a(npc.base.basic.baseNPC)) then return; end; self["_parent"] = rootNPC; self["_entry"] = nil; self["_cycleText"] = nil; self["_state"] = 0; self["_saidNumber"] = nil; self["_nextCycleText"] = -1; end); function talkNPC:addCycleText(germanText, englishText) if (self._cycleText == nil) then self._cycleText = base.messages.Messages(); self._parent:addCycle(self); end; self._cycleText:addMessage(germanText, englishText); end; function talkNPC:addTalkingEntry(newEntry) if (newEntry == nil or not newEntry:is_a(talkNPCEntry)) then return; end; if (self._entry == nil) then self._parent:addRecvText(self); self._entry = {}; end; newEntry:setParent(self); table.insert(self._entry, newEntry); end; function talkNPC:receiveText(npcChar, player, text) local result = false; table.foreach(self._entry, function(_, entry) if entry:checkEntry(npcChar, player, text) then entry:execute(npcChar, player); result = true; return true; end; end); return result; end; function talkNPC:nextCycle(npcChar, counter) if (counter >= self._nextCycleText) then self._nextCycleText = math.random(1200, 3600); --2 to 6 minutes local german, english = self._cycleText:getRandomMessage(); npcChar:talkLanguage(Character.say, Player.german, german); npcChar:talkLanguage(Character.say, Player.english, english); else self._nextCycleText = self._nextCycleText - counter; end; return self._nextCycleText; end; talkNPCEntry = base.class.class(function(self) self["_trigger"] = {}; self["_conditions"] = {}; self["_responses"] = {}; self["_responseProcessors"] = {}; self["_responsesCount"] = 0; self["_consequences"] = {}; self["_parent"] = nil; end); function talkNPCEntry:addTrigger(text) if (text == nil or type(text) ~= "string") then return; end; text = string.lower(text); text = string.gsub(text,'([ ]+)',' .*'); -- replace all spaces by " .*" table.insert(self._trigger, text); end; function talkNPCEntry:setParent(npc) local updateFkt = function(_, value) value:setNPC(npc); end; table.foreach(self._conditions, updateFkt); table.foreach(self._consequences, updateFkt); self._parent = npc; end; function talkNPCEntry:addCondition(condition) if (condition == nil or not condition:is_a(npc.base.condition.condition.condition)) then return; end; table.insert(self._conditions, condition); if (self._parent ~= nil) then condition:setNPC(self._parent); end; end; function talkNPCEntry:addResponse(text) if (text == nil or type(text) ~= "string") then return; end; table.insert(self._responses, text); self._responsesCount = self._responsesCount + 1; for _, processor in pairs(npc.base.responses.processorList) do if processor:check(text) then if (self._responseProcessors[self._responsesCount] == nil) then self._responseProcessors[self._responsesCount] = {}; end; table.insert(self._responseProcessors[self._responsesCount], processor) end; end; end; function talkNPCEntry:addConsequence(consequence) if (consequence == nil or not consequence:is_a(npc.base.consequence.consequence.consequence)) then return; end; table.insert(self._consequences, consequence); if (self._parent ~= nil) then consequence:setNPC(self._parent); end; end; function talkNPCEntry:checkEntry(npcChar, player, text) for _1, pattern in pairs(self._trigger) do local a, _2, number = string.find(text, pattern); self._saidNumber = number; if (a ~= nil) then local conditionsResult = true; for _3, condition in pairs(self._conditions) do if not condition:check(npcChar, player) then conditionsResult = false; break; end; end; if conditionsResult then return true; end; end; end; end; function talkNPCEntry:execute(npcChar, player) if (self._responsesCount > 0) then local selectedResponse = math.random(1, self._responsesCount); local responseText = self._responses[selectedResponse]; local responseProcessors = self._responseProcessors[selectedResponse]; if (responseProcessors ~= nil) then for _, processor in pairs(responseProcessors) do responseText = processor:process(player, self._parent, npcChar, responseText); end; end; if (string.find(responseText, "[#/]w") == 1) then npcChar:talk(Character.whisper, string.gsub(responseText, "[#/]w%s*", "", 1)); elseif (string.find(responseText, "[#/]s") == 1) then npcChar:talk(Character.shout, string.gsub(responseText, "[#/]s%s*", "", 1)); elseif (string.find(responseText, "[#/]o") == 1) then npcChar:talk(Character.whisper, responseText); else npcChar:talk(Character.say, responseText); end; end; table.foreach(self._consequences, function(_, consequence) if consequence then consequence:perform(npcChar, player); end; end); end; function _set_value(value) if (type(value) == "function") then return value, 2; elseif (value == "%NUMBER") then return nil, 1; else return tonumber(value), 0; end; end; function _get_value(npc, value, type) if (type == 2) then return value(npc._saidNumber); elseif (type == 1) then return npc._saidNumber; elseif (type == 0) then return value; else return 0; end; end;
Added talking mode support to easyNPC
Added talking mode support to easyNPC EasyNPCs now support whispered, shouted and ooc text properly by using the same prefix tags like the players in the game.
Lua
agpl-3.0
vilarion/Illarion-Content,Illarion-eV/Illarion-Content,LaFamiglia/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content
89c738d1b366bd112e89a10d283788497635d3fa
monster/base/behaviour/hostileWildlife.lua
monster/base/behaviour/hostileWildlife.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/>. ]] -- This is the behaviour script for hostile wildlife. -- This script utilizes the aggro manager and feeds it with some default values. local common = require("base.common") local character = require("base.character") local ag = require("monster.base.behaviour.aggroManager") local M = {} local aggroManager = ag.buildAggroManager{ addAggroForTarget = function(monster, target) if character.IsPlayer(target) then local distance = monster:distanceMetric(target) if distance > 4 then return -15 else return math.pow(6 - distance, 3) end end return 0 end, addAggroForAttack = function(monster, attacker) local monsterHP = character.GetHP(monster) local attackerHP = character.GetHP(attacker) return 500 - (attackerHP / 10) + (monsterHP / 10) end, aggroReduction = 5, maxAggro = 500, minAggro = -200 } local function doRandomMove(monster) if Random.uniform() < 0.15 then monster:move(Random.uniform(0, 7), true) else character.ChangeMovepoints(monster, -30) end end function M.addCallbacks(t) t = aggroManager.addCallbacks(t) local function reactOnAggro(monster, enemy) local enemyAggro = aggroManager.getAggro(monster, enemy) local absAggro = math.abs(enemyAggro) if absAggro < 20 then -- low aggro on the target. Ignore the target. doRandomMove(monster) return true elseif absAggro < 100 then -- critical aggro, observe the target. common.TurnTo(monster, enemy.pos) enemy:inform("Monster " .. monster.name .. " is watching you.") character.ChangeMovepoints(monster, -10) return true else -- aggro is high. Act on it. if enemyAggro > 0 then -- positive aggro. Engage! return false else -- negative aggro. Lets run for the hills. local enemyDir = common.GetDirection(enemy.pos, monster.pos) local vX, vY = common.GetDirectionVector(enemyDir) local d = math.min(1, 8 - monster:distanceMetric(enemy)) local runAwayTarget = position(monster.pos.x + vX * d, monster.pos.y + vY * d, monster.pos.z) local runAwayFreePositions = common.GetFreePositions(runAwayTarget, d, true, true) local runAwayFreePosition local runAwayFreePositionDist = math.huge; for freePosition in runAwayFreePositions do local dX = runAwayTarget.x - freePosition.x local dY = runAwayTarget.y - freePosition.y local dist = math.sqrt(dX * dX + dY * dY) if dist < runAwayFreePositionDist then runAwayFreePositionDist = dist runAwayFreePosition = freePosition end end if runAwayFreePosition == nil then -- No way to escape! local distance = monster:distanceMetric(enemy) if distance > 4 then doRandomMove(monster) return true else local aggroToAdd = math.min(0, math.pow(6 - distance, 4)) aggroManager.addAggro(monster, enemy, aggroToAdd) common.TurnTo(monster, enemy.pos) character.ChangeMovepoints(monster, -5) return true end else monster:talk(Character.say, "Running away!", "Running away!") monster.waypoints:clear() monster.waypoints:addWaypoint(runAwayFreePosition) monster:setOnRoute(true) return false end end end end local oldEnemyOnSight = t.enemyOnSight t.enemyOnSight = function(monster, enemy) if oldEnemyOnSight ~= nil and oldEnemyOnSight(monster, enemy) then return true end if reactOnAggro(monster, enemy) then return true end if Random.uniform() < 0.03 then character.ChangeMovepoints(monster, -20) return true end return false end local oldEnemyNear = t.enemyNear t.enemyNear = function(monster, enemy) local enemyAggro = aggroManager.getAggro(monster, enemy) if enemyAggro == 0 then return false end if oldEnemyNear ~= nil and oldEnemyNear(monster, enemy) then return true end return reactOnAggro(monster, enemy) end return t 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/>. ]] -- This is the behaviour script for hostile wildlife. -- This script utilizes the aggro manager and feeds it with some default values. local common = require("base.common") local character = require("base.character") local ag = require("monster.base.behaviour.aggroManager") local M = {} local aggroManager = ag.buildAggroManager{ addAggroForTarget = function(monster, target) if character.IsPlayer(target) then local distance = monster:distanceMetric(target) if distance > 4 then return -15 else return math.pow(6 - distance, 3) end end return 0 end, addAggroForAttack = function(monster, attacker) local monsterHP = character.GetHP(monster) local attackerHP = character.GetHP(attacker) return 500 - (attackerHP / 10) + (monsterHP / 10) end, aggroReduction = 5, maxAggro = 500, minAggro = -200 } local function doRandomMove(monster) if Random.uniform() < 0.15 then monster:move(Random.uniform(0, 7), true) else character.ChangeMovepoints(monster, -30) end end function M.addCallbacks(t) t = aggroManager.addCallbacks(t) local function reactOnAggro(monster, enemy) local enemyAggro = aggroManager.getAggro(monster, enemy) local absAggro = math.abs(enemyAggro) if absAggro < 20 then -- low aggro on the target. Ignore the target. doRandomMove(monster) return true elseif absAggro < 100 then -- critical aggro, observe the target. common.TurnTo(monster, enemy.pos) enemy:inform("Monster " .. monster.name .. " is watching you.") character.ChangeMovepoints(monster, -10) return true else -- aggro is high. Act on it. if enemyAggro > 0 then -- positive aggro. Engage! return false else -- negative aggro. Lets run for the hills. local enemyDir = common.GetDirection(enemy.pos, monster.pos) local runAwayDirection = -1 for _, runDir in pairs({enemyDir, enemyDir - 1, enemyDir + 1}) do local vX, vY = common.GetDirectionVector((runDir + 8) % 8) local runAwayTarget = position(monster.pos.x + vX, monster.pos.y + vY, monster.pos.z) local runAwayField = world:getField(runAwayTarget) if runAwayField ~= nil and runAwayField:isPassable() then runAwayDirection = runDir break end end if runAwayDirection == -1 then -- No way to escape! local distance = monster:distanceMetric(enemy) if distance > 4 then doRandomMove(monster) return true else local aggroToAdd = math.min(0, math.pow(6 - distance, 4)) aggroManager.addAggro(monster, enemy, aggroToAdd) common.TurnTo(monster, enemy.pos) character.ChangeMovepoints(monster, -5) return true end else monster:talk(Character.say, "Running away!", "Running away!") monster:move(runAwayDirection, true) return true end end end end local oldEnemyOnSight = t.enemyOnSight t.enemyOnSight = function(monster, enemy) if oldEnemyOnSight ~= nil and oldEnemyOnSight(monster, enemy) then return true end if reactOnAggro(monster, enemy) then return true end if Random.uniform() < 0.03 then character.ChangeMovepoints(monster, -20) return true end return false end local oldEnemyNear = t.enemyNear t.enemyNear = function(monster, enemy) local enemyAggro = aggroManager.getAggro(monster, enemy) if enemyAggro == 0 then return false end if oldEnemyNear ~= nil and oldEnemyNear(monster, enemy) then return true end return reactOnAggro(monster, enemy) end return t end return M
Fixing running away for monsters
Fixing running away for monsters
Lua
agpl-3.0
Baylamon/Illarion-Content,vilarion/Illarion-Content,KayMD/Illarion-Content,Illarion-eV/Illarion-Content
3327bb7f82e0fed1d90e18e4fe49464a59e03c85
lualib/socket.lua
lualib/socket.lua
local driver = require "socketdriver" local skynet = require "skynet" local assert = assert local socket = {} -- api local buffer_pool = {} -- store all message buffer object local socket_pool = setmetatable( -- store all socket object {}, { __gc = function(p) for id,v in pairs(p) do driver.close(id) -- don't need clear v.buffer, because buffer pool will be free at the end p[id] = nil end end } ) local socket_message = {} local function wakeup(s) local co = s.co if co then s.co = nil skynet.wakeup(co) end end local function suspend(s) assert(not s.co) s.co = coroutine.running() skynet.wait() end -- read skynet_socket.h for these macro -- SKYNET_SOCKET_TYPE_DATA = 1 socket_message[1] = function(id, size, data) local s = socket_pool[id] if s == nil then print("socket: drop package from " .. id) driver.drop(data) return end local sz = driver.push(s.buffer, buffer_pool, data, size) local rr = s.read_required local rrt = type(rr) if rrt == "number" then -- read size if sz >= rr then s.read_required = nil wakeup(s) end elseif rrt == "string" then -- read line if driver.readline(s.buffer,nil,rr) then s.read_required = nil wakeup(s) end end end -- SKYNET_SOCKET_TYPE_CONNECT = 2 socket_message[2] = function(id, _ , addr) local s = socket_pool[id] if s == nil then return end -- log remote addr s.connected = true wakeup(s) end -- SKYNET_SOCKET_TYPE_CLOSE = 3 socket_message[3] = function(id) local s = socket_pool[id] if s == nil then return end s.connected = false wakeup(s) end -- SKYNET_SOCKET_TYPE_ACCEPT = 4 socket_message[4] = function(id, newid, addr) local s = socket_pool[id] if s == nil then driver.close(newid) return end s.callback(newid, addr) end -- SKYNET_SOCKET_TYPE_ERROR = 5 socket_message[5] = function(id) print("error on ", id) local s = socket_pool[id] if s == nil then return end s.connected = false wakeup(s) end skynet.register_protocol { name = "socket", id = 6, -- PTYPE_SOCKET unpack = driver.unpack, dispatch = function (_, _, t, n1, n2, data) socket_message[t](n1,n2,data) end } local function connect(id, func) local newbuffer if func == nil then newbuffer = driver.buffer() end local s = { id = id, buffer = newbuffer, connected = false, read_require = false, co = false, callback = func, } socket_pool[id] = s suspend(s) if s.connected then return id end end function socket.open(addr, port) local id = driver.connect(addr,port) return connect(id) end function socket.stdin() local id = driver.bind(1) return connect(id) end function socket.start(id, func) driver.start(id) return connect(id, func) end function socket.close(fd) local s = socket_pool[id] if s == nil then return end if s.connected then driver.close(s.id) suspend(s) end if s.buffer then driver.clear(s.buffer,buffer_pool) end assert(s.lock_set == nil or next(s.lock_set) == nil) socket_pool[id] = nil end function socket.read(id, sz) local s = socket_pool[id] assert(s) local ret = driver.pop(s.buffer, buffer_pool, sz) if ret then return ret end if not s.connected then return false, driver.readall(s.buffer, buffer_pool) end assert(not s.read_required) s.read_required = sz suspend(s) ret = driver.pop(s.buffer, buffer_pool, sz) if ret then return ret else return false, driver.readall(s.buffer, buffer_pool) end end function socket.readall(id) local s = socket_pool[id] assert(s) if not s.connected then return driver.readall(s.buffer, buffer_pool) end assert(not s.read_required) s.read_required = true suspend(s) assert(s.connected == false) return driver.readall(s.buffer, buffer_pool) end function socket.readline(id, sep) sep = sep or "\n" local s = socket_pool[id] assert(s) local ret = driver.readline(s.buffer, buffer_pool, sep) if ret then return ret end if not s.connected then return false, driver.readall(s.buffer, buffer_pool) end assert(not s.read_required) s.read_required = sep suspend(s) if s.connected then return driver.readline(s.buffer, buffer_pool, sep) else return false, driver.readall(s.buffer, buffer_pool) end end socket.write = assert(driver.send) function socket.invalid(id) return socket_pool[id] == nil end socket.listen = assert(driver.listen) function socket.lock(id) local s = socket_pool[id] assert(s) local lock_set = s.lock local co = coroutine.running() if not lock_set then lock_set = {} s.lock = lock_set lock_set[co] = true elseif next(lock_set) == nil then lock_set[co] = true else assert(lock_set[co] == nil) lock_set[co] = true skynet.wait() end end function socket.unlock(id) local s = socket_pool[id] assert(s) local lock_set = s.lock assert(lock_set) local co = coroutine.running() assert(lock_set[co]) lock_set[co] = nil while true do co = next(lock_set) if co == nil then break end if skynet.wakeup(co) then break else lock_set[co] = nil end end end -- abandon use to forward socket id to other service -- you must call socket.accept(id) later in other service function socket.abandon(id) local s = socket_pool[id] if s and s.buffer then driver.clear(s.buffer,buffer_pool) end socket_pool[id] = nil end return socket
local driver = require "socketdriver" local skynet = require "skynet" local assert = assert local socket = {} -- api local buffer_pool = {} -- store all message buffer object local socket_pool = setmetatable( -- store all socket object {}, { __gc = function(p) for id,v in pairs(p) do driver.close(id) -- don't need clear v.buffer, because buffer pool will be free at the end p[id] = nil end end } ) local socket_message = {} local function wakeup(s) local co = s.co if co then s.co = nil skynet.wakeup(co) end end local function suspend(s) assert(not s.co) s.co = coroutine.running() skynet.wait() end -- read skynet_socket.h for these macro -- SKYNET_SOCKET_TYPE_DATA = 1 socket_message[1] = function(id, size, data) local s = socket_pool[id] if s == nil then print("socket: drop package from " .. id) driver.drop(data) return end local sz = driver.push(s.buffer, buffer_pool, data, size) local rr = s.read_required local rrt = type(rr) if rrt == "number" then -- read size if sz >= rr then s.read_required = nil wakeup(s) end elseif rrt == "string" then -- read line if driver.readline(s.buffer,nil,rr) then s.read_required = nil wakeup(s) end end end -- SKYNET_SOCKET_TYPE_CONNECT = 2 socket_message[2] = function(id, _ , addr) local s = socket_pool[id] if s == nil then return end -- log remote addr s.connected = true wakeup(s) end -- SKYNET_SOCKET_TYPE_CLOSE = 3 socket_message[3] = function(id) local s = socket_pool[id] if s == nil then return end s.connected = false wakeup(s) end -- SKYNET_SOCKET_TYPE_ACCEPT = 4 socket_message[4] = function(id, newid, addr) local s = socket_pool[id] if s == nil then driver.close(newid) return end s.callback(newid, addr) end -- SKYNET_SOCKET_TYPE_ERROR = 5 socket_message[5] = function(id) print("error on ", id) local s = socket_pool[id] if s == nil then return end s.connected = false wakeup(s) end skynet.register_protocol { name = "socket", id = 6, -- PTYPE_SOCKET unpack = driver.unpack, dispatch = function (_, _, t, n1, n2, data) socket_message[t](n1,n2,data) end } local function connect(id, func) local newbuffer if func == nil then newbuffer = driver.buffer() end local s = { id = id, buffer = newbuffer, connected = false, read_require = false, co = false, callback = func, } socket_pool[id] = s suspend(s) if s.connected then return id end end function socket.open(addr, port) local id = driver.connect(addr,port) return connect(id) end function socket.stdin() local id = driver.bind(1) return connect(id) end function socket.start(id, func) driver.start(id) return connect(id, func) end function socket.close(fd) local s = socket_pool[id] if s == nil then return end if s.connected then driver.close(s.id) suspend(s) end if s.buffer then driver.clear(s.buffer,buffer_pool) end assert(s.lock_set == nil or next(s.lock_set) == nil) socket_pool[id] = nil end function socket.read(id, sz) local s = socket_pool[id] assert(s) local ret = driver.pop(s.buffer, buffer_pool, sz) if ret then return ret end if not s.connected then return false, driver.readall(s.buffer, buffer_pool) end assert(not s.read_required) s.read_required = sz suspend(s) ret = driver.pop(s.buffer, buffer_pool, sz) if ret then return ret else return false, driver.readall(s.buffer, buffer_pool) end end function socket.readall(id) local s = socket_pool[id] assert(s) if not s.connected then return driver.readall(s.buffer, buffer_pool) end assert(not s.read_required) s.read_required = true suspend(s) assert(s.connected == false) return driver.readall(s.buffer, buffer_pool) end function socket.readline(id, sep) sep = sep or "\n" local s = socket_pool[id] assert(s) local ret = driver.readline(s.buffer, buffer_pool, sep) if ret then return ret end if not s.connected then return false, driver.readall(s.buffer, buffer_pool) end assert(not s.read_required) s.read_required = sep suspend(s) if s.connected then return driver.readline(s.buffer, buffer_pool, sep) else return false, driver.readall(s.buffer, buffer_pool) end end socket.write = assert(driver.send) function socket.invalid(id) return socket_pool[id] == nil end socket.listen = assert(driver.listen) function socket.lock(id) local s = socket_pool[id] assert(s) local lock_set = s.lock if not lock_set then lock_set = {} s.lock = lock_set end local co = coroutine.running() if #lock_set == 0 then lock_set[1] = co else table.insert(lock_set, co) skynet.wait() end end function socket.unlock(id) local s = socket_pool[id] assert(s) local lock_set = s.lock assert(lock_set) local co = coroutine.running() assert(lock_set[1] == co) table.remove(lock_set,1) co = lock_set[1] if co then skynet.wakeup(co) end end -- abandon use to forward socket id to other service -- you must call socket.accept(id) later in other service function socket.abandon(id) local s = socket_pool[id] if s and s.buffer then driver.clear(s.buffer,buffer_pool) end socket_pool[id] = nil end return socket
queue lock request in socket, fix issue #51
queue lock request in socket, fix issue #51
Lua
mit
great90/skynet,liuxuezhan/skynet,sanikoyes/skynet,zhangshiqian1214/skynet,puXiaoyi/skynet,KittyCookie/skynet,czlc/skynet,your-gatsby/skynet,wangyi0226/skynet,MRunFoss/skynet,peimin/skynet,plsytj/skynet,lawnight/skynet,cmingjian/skynet,zzh442856860/skynet,firedtoad/skynet,sundream/skynet,sundream/skynet,qyli/test,microcai/skynet,jxlczjp77/skynet,enulex/skynet,Zirpon/skynet,qyli/test,harryzeng/skynet,hongling0/skynet,boyuegame/skynet,MoZhonghua/skynet,togolwb/skynet,chenjiansnail/skynet,zhaijialong/skynet,bingo235/skynet,yunGit/skynet,chuenlungwang/skynet,xubigshu/skynet,chenjiansnail/skynet,ludi1991/skynet,firedtoad/skynet,longmian/skynet,MoZhonghua/skynet,rainfiel/skynet,fztcjjl/skynet,ilylia/skynet,great90/skynet,ag6ag/skynet,codingabc/skynet,samael65535/skynet,liuxuezhan/skynet,nightcj/mmo,yunGit/skynet,boyuegame/skynet,asanosoyokaze/skynet,xjdrew/skynet,Markal128/skynet,lawnight/skynet,togolwb/skynet,jxlczjp77/skynet,zhaijialong/skynet,boyuegame/skynet,cuit-zhaxin/skynet,javachengwc/skynet,gitfancode/skynet,harryzeng/skynet,ruleless/skynet,sanikoyes/skynet,pigparadise/skynet,pichina/skynet,ilylia/skynet,yinjun322/skynet,cmingjian/skynet,hongling0/skynet,LuffyPan/skynet,lynx-seu/skynet,iskygame/skynet,enulex/skynet,lynx-seu/skynet,vizewang/skynet,u20024804/skynet,KAndQ/skynet,cuit-zhaxin/skynet,QuiQiJingFeng/skynet,bigrpg/skynet,ag6ag/skynet,zzh442856860/skynet,KittyCookie/skynet,chfg007/skynet,xcjmine/skynet,MoZhonghua/skynet,helling34/skynet,fhaoquan/skynet,zhoukk/skynet,bttscut/skynet,gitfancode/skynet,javachengwc/skynet,korialuo/skynet,matinJ/skynet,zhouxiaoxiaoxujian/skynet,Ding8222/skynet,harryzeng/skynet,ilylia/skynet,zzh442856860/skynet-Note,ludi1991/skynet,firedtoad/skynet,leezhongshan/skynet,helling34/skynet,lawnight/skynet,chuenlungwang/skynet,puXiaoyi/skynet,wangjunwei01/skynet,vizewang/skynet,LuffyPan/skynet,matinJ/skynet,javachengwc/skynet,codingabc/skynet,xjdrew/skynet,fztcjjl/skynet,xinmingyao/skynet,Markal128/skynet,wangyi0226/skynet,dymx101/skynet,microcai/skynet,zhangshiqian1214/skynet,kebo/skynet,pigparadise/skynet,bingo235/skynet,kebo/skynet,zhouxiaoxiaoxujian/skynet,MetSystem/skynet,ypengju/skynet_comment,lynx-seu/skynet,zhouxiaoxiaoxujian/skynet,ruleless/skynet,your-gatsby/skynet,enulex/skynet,LiangMa/skynet,gitfancode/skynet,cloudwu/skynet,sdgdsffdsfff/skynet,iskygame/skynet,xinjuncoding/skynet,fhaoquan/skynet,bigrpg/skynet,jiuaiwo1314/skynet,matinJ/skynet,wangyi0226/skynet,bigrpg/skynet,codingabc/skynet,bttscut/skynet,zzh442856860/skynet-Note,xubigshu/skynet,liuxuezhan/skynet,winglsh/skynet,zzh442856860/skynet,felixdae/skynet,iskygame/skynet,letmefly/skynet,ruleless/skynet,MRunFoss/skynet,catinred2/skynet,zhangshiqian1214/skynet,MetSystem/skynet,JiessieDawn/skynet,your-gatsby/skynet,JiessieDawn/skynet,sdgdsffdsfff/skynet,bingo235/skynet,fhaoquan/skynet,helling34/skynet,wangjunwei01/skynet,lc412/skynet,ag6ag/skynet,qyli/test,czlc/skynet,cpascal/skynet,rainfiel/skynet,felixdae/skynet,yunGit/skynet,yinjun322/skynet,u20024804/skynet,jiuaiwo1314/skynet,liuxuezhan/skynet,leezhongshan/skynet,xinjuncoding/skynet,kyle-wang/skynet,peimin/skynet_v0.1_with_notes,ludi1991/skynet,kyle-wang/skynet,KAndQ/skynet,MRunFoss/skynet,great90/skynet,cpascal/skynet,lc412/skynet,Zirpon/skynet,Zirpon/skynet,catinred2/skynet,qyli/test,ludi1991/skynet,rainfiel/skynet,plsytj/skynet,xinjuncoding/skynet,zhangshiqian1214/skynet,asanosoyokaze/skynet,letmefly/skynet,bttscut/skynet,cdd990/skynet,cdd990/skynet,letmefly/skynet,zhangshiqian1214/skynet,cpascal/skynet,chfg007/skynet,chuenlungwang/skynet,sdgdsffdsfff/skynet,kyle-wang/skynet,czlc/skynet,zzh442856860/skynet-Note,puXiaoyi/skynet,LiangMa/skynet,plsytj/skynet,LuffyPan/skynet,cloudwu/skynet,jxlczjp77/skynet,cuit-zhaxin/skynet,Markal128/skynet,zhoukk/skynet,KAndQ/skynet,cmingjian/skynet,chfg007/skynet,jiuaiwo1314/skynet,chenjiansnail/skynet,zhoukk/skynet,lawnight/skynet,pichina/skynet,peimin/skynet,felixdae/skynet,dymx101/skynet,catinred2/skynet,zhaijialong/skynet,zhangshiqian1214/skynet,vizewang/skynet,QuiQiJingFeng/skynet,QuiQiJingFeng/skynet,dymx101/skynet,letmefly/skynet,u20024804/skynet,yinjun322/skynet,sundream/skynet,korialuo/skynet,fztcjjl/skynet,pichina/skynet,icetoggle/skynet,sanikoyes/skynet,longmian/skynet,icetoggle/skynet,ypengju/skynet_comment,cdd990/skynet,microcai/skynet,pigparadise/skynet,korialuo/skynet,samael65535/skynet,winglsh/skynet,LiangMa/skynet,xcjmine/skynet,togolwb/skynet,ypengju/skynet_comment,xinmingyao/skynet,lc412/skynet,wangjunwei01/skynet,nightcj/mmo,nightcj/mmo,cloudwu/skynet,icetoggle/skynet,hongling0/skynet,winglsh/skynet,xjdrew/skynet,peimin/skynet_v0.1_with_notes,Ding8222/skynet,longmian/skynet,zzh442856860/skynet-Note,xcjmine/skynet,asanosoyokaze/skynet,JiessieDawn/skynet,kebo/skynet,KittyCookie/skynet,leezhongshan/skynet,Ding8222/skynet,MetSystem/skynet,samael65535/skynet
fb298aaf2c1ca7c64cbcc3078141334f9850c8fe
lualib/socket.lua
lualib/socket.lua
local buffer = require "socketbuffer" local skynet = require "skynet" local table = table local next = next local assert = assert local coroutine = coroutine local type = type local READBUF = {} -- fd:buffer local READREQUEST = {} -- fd:request_size local READSESSION = {} -- fd:session local READLOCK = {} -- fd:queue(session) local READTHREAD= {} -- fd:thread local selfaddr = skynet.self() local function response(session) skynet.redirect(selfaddr , 0, "response", session, "") end skynet.register_protocol { name = "client", id = 3, -- PTYPE_CLIENT pack = buffer.pack, unpack = buffer.unpack, dispatch = function (_, _, fd, msg, sz) local qsz = READREQUEST[fd] local buf = READBUF[fd] local bsz if sz == 0 or buf == true then buf,bsz = true, qsz else buf,bsz = buffer.push(buf, msg, sz) end READBUF[fd] = buf local session = READSESSION[fd] if qsz == nil or session == nil then return end if type(qsz) == "number" then if qsz > bsz then return end else -- request readline if buffer.readline(buf, qsz, true) == nil then return end end response(session) READSESSION[fd] = nil end } skynet.register_protocol { name = "system", id = 4, -- PTYPE_SYSTEM pack = skynet.pack, unpack = function (...) return ... end, dispatch = function (session, addr, msg, sz) fd, t, sz = skynet.unpack(msg,sz) assert(addr == selfaddr, "PTYPE_SYSTEM message must send by self") if t == 0 then -- lock fd if READTHREAD[fd] == nil then skynet.ret() return end local q = READLOCK[fd] if q == nil then READLOCK[fd] = { session } else table.insert(q, session) end else -- request bytes or readline local buf = READBUF[fd] if buf == true then skynet.ret() return end local _,bsz = buffer.push(buf) if t == 1 then -- sz is size if bsz >= sz then skynet.ret() return end else -- sz is sep if buffer.readline(buf, sz, true) then -- don't real read skynet.ret() return end end READSESSION[fd] = session end end } local socket = {} function socket.open(addr, port) local cmd = "open" .. " " .. (port and (addr..":"..port) or addr) local r = skynet.call(".socket", "text", cmd) if r == "" then error(cmd .. " failed") end return tonumber(r) end function socket.stdin() local r = skynet.call(".socket", "text", "bind 1") if r == "" then error("stdin bind failed") end return tonumber(r) end function socket.close(fd) socket.lock(fd) skynet.call(".socket", "text", "close", fd) READBUF[fd] = true READLOCK[fd] = nil end function socket.read(fd, sz) assert(coroutine.running() == READTHREAD[fd], "call socket.lock first") local str = buffer.pop(READBUF[fd],sz) if str then return str end READREQUEST[fd] = sz skynet.call(selfaddr, "system",fd,1,sz) -- singal size 1 READREQUEST[fd] = nil str = buffer.pop(READBUF[fd],sz) return str end function socket.readline(fd, sep) assert(coroutine.running() == READTHREAD[fd], "call socket.lock first") local str = buffer.readline(READBUF[fd],sep) if str then return str end READREQUEST[fd] = sep skynet.call(selfaddr, "system",fd,2,sep) -- singal sep 2 READREQUEST[fd] = nil str = buffer.readline(READBUF[fd],sep) return str end function socket.write(fd, msg, sz) skynet.send(".socket", "client", fd, msg, sz) end function socket.lock(fd) local lt = READTHREAD[fd] local ct = coroutine.running() if lt then assert(lt ~= ct, "already lock") skynet.call(selfaddr, "system",fd,0) end READTHREAD[fd] = ct end function socket.unlock(fd) READTHREAD[fd] = nil local q = READLOCK[fd] if q then if q[1] then response(q[1]) end table.remove(q,1) if q[1] == nil then READLOCK[fd] = nil end end end return socket
local buffer = require "socketbuffer" local skynet = require "skynet" local table = table local next = next local assert = assert local coroutine = coroutine local type = type local READBUF = {} -- fd:buffer local READREQUEST = {} -- fd:request_size local READSESSION = {} -- fd:session local READLOCK = {} -- fd:queue(session) local READTHREAD= {} -- fd:thread local selfaddr = skynet.self() local function response(session) skynet.redirect(selfaddr , 0, "response", session, "") end skynet.register_protocol { name = "client", id = 3, -- PTYPE_CLIENT pack = buffer.pack, unpack = buffer.unpack, dispatch = function (_, _, fd, msg, sz) local qsz = READREQUEST[fd] local buf = READBUF[fd] local bsz if sz == 0 or buf == true then buf,bsz = true, qsz else buf,bsz = buffer.push(buf, msg, sz) end READBUF[fd] = buf local session = READSESSION[fd] if qsz == nil or session == nil then return end if type(qsz) == "number" then if qsz > bsz then return end else -- request readline if buffer.readline(buf, qsz, true) == nil then return end end response(session) READSESSION[fd] = nil end } skynet.register_protocol { name = "system", id = 4, -- PTYPE_SYSTEM pack = skynet.pack, unpack = function (...) return ... end, dispatch = function (session, addr, msg, sz) fd, t, sz = skynet.unpack(msg,sz) assert(addr == selfaddr, "PTYPE_SYSTEM message must send by self") if t > 0 then -- lock request when t == 0 -- request bytes or readline local buf = READBUF[fd] if buf == true then skynet.ret() return end local _,bsz = buffer.push(buf) if t == 1 then -- sz is size if bsz >= sz then skynet.ret() return end else -- sz is sep if buffer.readline(buf, sz, true) then -- don't real read skynet.ret() return end end READSESSION[fd] = session end end } local socket = {} function socket.open(addr, port) local cmd = "open" .. " " .. (port and (addr..":"..port) or addr) local r = skynet.call(".socket", "text", cmd) if r == "" then error(cmd .. " failed") end return tonumber(r) end function socket.stdin() local r = skynet.call(".socket", "text", "bind 1") if r == "" then error("stdin bind failed") end return tonumber(r) end function socket.close(fd) socket.lock(fd) skynet.call(".socket", "text", "close", fd) READBUF[fd] = true READLOCK[fd] = nil end function socket.read(fd, sz) local str = buffer.pop(READBUF[fd],sz) if str then return str end READREQUEST[fd] = sz skynet.call(selfaddr, "system",fd,1,sz) -- singal size 1 READREQUEST[fd] = nil str = buffer.pop(READBUF[fd],sz) return str end function socket.readline(fd, sep) local str = buffer.readline(READBUF[fd],sep) if str then return str end READREQUEST[fd] = sep skynet.call(selfaddr, "system",fd,2,sep) -- singal sep 2 READREQUEST[fd] = nil str = buffer.readline(READBUF[fd],sep) return str end function socket.write(fd, msg, sz) skynet.send(".socket", "client", fd, msg, sz) end function socket.lock(fd) local locked = READTHREAD[fd] if locked then -- lock fd local session = skynet.genid() local q = READLOCK[fd] if q == nil then READLOCK[fd] = { session } else table.insert(q, session) end skynet.redirect(selfaddr , 0, "system", session, skynet.pack(fd,0)) coroutine.yield("CALL",session) else READTHREAD[fd] = true end end function socket.unlock(fd) READTHREAD[fd] = nil local q = READLOCK[fd] if q then if q[1] then READTHREAD[fd] = true response(q[1]) table.remove(q,1) else READLOCK[fd] = nil end end end return socket
bugfix: socket read lock/unlock
bugfix: socket read lock/unlock
Lua
mit
icetoggle/skynet,LiangMa/skynet,zhangshiqian1214/skynet,Markal128/skynet,zhangshiqian1214/skynet,bttscut/skynet,jxlczjp77/skynet,wangyi0226/skynet,boyuegame/skynet,MRunFoss/skynet,cuit-zhaxin/skynet,pichina/skynet,fztcjjl/skynet,togolwb/skynet,chfg007/skynet,kyle-wang/skynet,winglsh/skynet,QuiQiJingFeng/skynet,kyle-wang/skynet,wangjunwei01/skynet,bingo235/skynet,korialuo/skynet,letmefly/skynet,lawnight/skynet,yinjun322/skynet,cuit-zhaxin/skynet,firedtoad/skynet,liuxuezhan/skynet,ruleless/skynet,JiessieDawn/skynet,ilylia/skynet,microcai/skynet,ludi1991/skynet,lawnight/skynet,korialuo/skynet,ag6ag/skynet,Zirpon/skynet,sdgdsffdsfff/skynet,pigparadise/skynet,MoZhonghua/skynet,rainfiel/skynet,dymx101/skynet,hongling0/skynet,qyli/test,sundream/skynet,KittyCookie/skynet,your-gatsby/skynet,catinred2/skynet,winglsh/skynet,KittyCookie/skynet,catinred2/skynet,xinmingyao/skynet,fztcjjl/skynet,yunGit/skynet,xjdrew/skynet,letmefly/skynet,xinjuncoding/skynet,fhaoquan/skynet,chenjiansnail/skynet,Markal128/skynet,codingabc/skynet,pichina/skynet,kebo/skynet,KAndQ/skynet,chenjiansnail/skynet,sdgdsffdsfff/skynet,ag6ag/skynet,zhoukk/skynet,ypengju/skynet_comment,winglsh/skynet,puXiaoyi/skynet,wangjunwei01/skynet,dymx101/skynet,ludi1991/skynet,cloudwu/skynet,ludi1991/skynet,bigrpg/skynet,hongling0/skynet,kebo/skynet,fhaoquan/skynet,QuiQiJingFeng/skynet,gitfancode/skynet,samael65535/skynet,cpascal/skynet,javachengwc/skynet,qyli/test,zhangshiqian1214/skynet,qyli/test,ludi1991/skynet,great90/skynet,LuffyPan/skynet,KAndQ/skynet,zhangshiqian1214/skynet,chuenlungwang/skynet,xjdrew/skynet,czlc/skynet,lc412/skynet,lawnight/skynet,xinmingyao/skynet,cdd990/skynet,lawnight/skynet,xcjmine/skynet,kebo/skynet,leezhongshan/skynet,zhouxiaoxiaoxujian/skynet,helling34/skynet,puXiaoyi/skynet,ypengju/skynet_comment,harryzeng/skynet,bigrpg/skynet,iskygame/skynet,iskygame/skynet,jiuaiwo1314/skynet,JiessieDawn/skynet,czlc/skynet,matinJ/skynet,cloudwu/skynet,zhangshiqian1214/skynet,longmian/skynet,xinjuncoding/skynet,enulex/skynet,togolwb/skynet,pigparadise/skynet,zzh442856860/skynet-Note,helling34/skynet,peimin/skynet_v0.1_with_notes,wangjunwei01/skynet,MetSystem/skynet,u20024804/skynet,pichina/skynet,peimin/skynet_v0.1_with_notes,LiangMa/skynet,letmefly/skynet,icetoggle/skynet,peimin/skynet,xcjmine/skynet,leezhongshan/skynet,samael65535/skynet,zhoukk/skynet,jiuaiwo1314/skynet,your-gatsby/skynet,catinred2/skynet,cpascal/skynet,chuenlungwang/skynet,MRunFoss/skynet,ag6ag/skynet,zhaijialong/skynet,zzh442856860/skynet,yinjun322/skynet,wangyi0226/skynet,MetSystem/skynet,Ding8222/skynet,bttscut/skynet,javachengwc/skynet,felixdae/skynet,MoZhonghua/skynet,xinjuncoding/skynet,wangyi0226/skynet,jxlczjp77/skynet,helling34/skynet,liuxuezhan/skynet,microcai/skynet,ruleless/skynet,vizewang/skynet,zhangshiqian1214/skynet,QuiQiJingFeng/skynet,togolwb/skynet,sanikoyes/skynet,pigparadise/skynet,yinjun322/skynet,u20024804/skynet,bingo235/skynet,JiessieDawn/skynet,gitfancode/skynet,codingabc/skynet,firedtoad/skynet,sanikoyes/skynet,ypengju/skynet_comment,nightcj/mmo,great90/skynet,matinJ/skynet,bigrpg/skynet,zhaijialong/skynet,yunGit/skynet,your-gatsby/skynet,rainfiel/skynet,icetoggle/skynet,Markal128/skynet,xubigshu/skynet,fztcjjl/skynet,xcjmine/skynet,vizewang/skynet,zzh442856860/skynet,chuenlungwang/skynet,hongling0/skynet,nightcj/mmo,boyuegame/skynet,jiuaiwo1314/skynet,rainfiel/skynet,KittyCookie/skynet,MRunFoss/skynet,felixdae/skynet,Ding8222/skynet,sdgdsffdsfff/skynet,LuffyPan/skynet,xubigshu/skynet,felixdae/skynet,chenjiansnail/skynet,MetSystem/skynet,cpascal/skynet,plsytj/skynet,vizewang/skynet,ilylia/skynet,plsytj/skynet,zzh442856860/skynet-Note,great90/skynet,zhouxiaoxiaoxujian/skynet,MoZhonghua/skynet,cdd990/skynet,puXiaoyi/skynet,plsytj/skynet,nightcj/mmo,lynx-seu/skynet,iskygame/skynet,zhoukk/skynet,xjdrew/skynet,lc412/skynet,zhaijialong/skynet,chfg007/skynet,cmingjian/skynet,fhaoquan/skynet,ruleless/skynet,LuffyPan/skynet,peimin/skynet,cloudwu/skynet,microcai/skynet,chfg007/skynet,leezhongshan/skynet,samael65535/skynet,bttscut/skynet,matinJ/skynet,harryzeng/skynet,enulex/skynet,jxlczjp77/skynet,qyli/test,ilylia/skynet,longmian/skynet,zhouxiaoxiaoxujian/skynet,Zirpon/skynet,liuxuezhan/skynet,lynx-seu/skynet,longmian/skynet,firedtoad/skynet,letmefly/skynet,javachengwc/skynet,enulex/skynet,liuxuezhan/skynet,boyuegame/skynet,Ding8222/skynet,harryzeng/skynet,LiangMa/skynet,zzh442856860/skynet-Note,czlc/skynet,asanosoyokaze/skynet,zzh442856860/skynet-Note,zzh442856860/skynet,yunGit/skynet,Zirpon/skynet,codingabc/skynet,cuit-zhaxin/skynet,cmingjian/skynet,sanikoyes/skynet,cmingjian/skynet,dymx101/skynet,korialuo/skynet,sundream/skynet,lc412/skynet,bingo235/skynet,gitfancode/skynet,asanosoyokaze/skynet,KAndQ/skynet,cdd990/skynet,asanosoyokaze/skynet,lynx-seu/skynet,u20024804/skynet,kyle-wang/skynet,sundream/skynet
f572340e58ee910973ded0d72df9dcb69e00d851
src_trunk/resources/job-system/c_job_framework.lua
src_trunk/resources/job-system/c_job_framework.lua
job = 0 localPlayer = getLocalPlayer() function playerSpawn() local logged = getElementData(source, "loggedin") if (logged==1) then job = tonumber(getElementData(source, "job")) outputDebugString(tostring(job)) if (job==1) then -- TRUCKER resetTruckerJob() setTimer(displayTruckerJob, 1000, 1) elseif (job==2) then -- TAXI resetTaxiJob() setTimer(displayTaxiJob, 1000, 1) elseif (job==3) then -- BUS resetBusJob() setTimer(displayBusJob, 1000, 1) end end end addEventHandler("onClientPlayerSpawn", localPlayer, playerSpawn) function quitJob() local logged = getElementData(localPlayer, "loggedin") if (logged==1) then job = getElementData(localPlayer, "job") if (job==0) then outputChatBox("You are currently unemployed.", 255, 0, 0) elseif (job==1) then -- TRUCKER JOB resetTruckerJob() setElementData(localPlayer, "job", true, 0) outputChatBox("You have now quit your job as a delivery driver.", 0, 255, 0) elseif (job==2) then -- TAXI JOB resetTaxiJob() setElementData(localPlayer, "job", true, 0) outputChatBox("You have now quit your job as a taxi driver.", 0, 255, 0) elseif (job==3) then -- BUS JOB resetBusJob() setElementData(localPlayer, "job", true, 0) outputChatBox("You have now quit your job as a bus driver.", 0, 255, 0) elseif (job==4) then -- CITY MAINTENANCE outputChatBox("You have now quit your job as a city maintenance worker.", 0, 255, 0) setElementData(localPlayer, "tag", true, 1) setElementData(localPlayer, "job", true, 0) triggerServerEvent("cancelCityMaintenance", localPlayer) end end end addCommandHandler("endjob", quitJob, false, false) addCommandHandler("quitjob", quitJob, false, false)
job = 0 localPlayer = getLocalPlayer() function playerSpawn() local logged = getElementData(source, "loggedin") if (logged==1) then job = tonumber(getElementData(source, "job")) if (job==1) then -- TRUCKER resetTruckerJob() setTimer(displayTruckerJob, 1000, 1) elseif (job==2) then -- TAXI resetTaxiJob() setTimer(displayTaxiJob, 1000, 1) elseif (job==3) then -- BUS resetBusJob() setTimer(displayBusJob, 1000, 1) end end end addEventHandler("onClientPlayerSpawn", localPlayer, playerSpawn) function quitJob() local logged = getElementData(localPlayer, "loggedin") if (logged==1) then job = getElementData(localPlayer, "job") if (job==0) then outputChatBox("You are currently unemployed.", 255, 0, 0) elseif (job==1) then -- TRUCKER JOB resetTruckerJob() setElementData(localPlayer, "job", true, 0) outputChatBox("You have now quit your job as a delivery driver.", 0, 255, 0) elseif (job==2) then -- TAXI JOB resetTaxiJob() setElementData(localPlayer, "job", true, 0) outputChatBox("You have now quit your job as a taxi driver.", 0, 255, 0) elseif (job==3) then -- BUS JOB resetBusJob() setElementData(localPlayer, "job", true, 0) outputChatBox("You have now quit your job as a bus driver.", 0, 255, 0) elseif (job==4) then -- CITY MAINTENANCE outputChatBox("You have now quit your job as a city maintenance worker.", 0, 255, 0) setElementData(localPlayer, "tag", true, 1) setElementData(localPlayer, "job", true, 0) triggerServerEvent("cancelCityMaintenance", localPlayer) end end end addCommandHandler("endjob", quitJob, false, false) addCommandHandler("quitjob", quitJob, false, false)
Few tiny bug fixes
Few tiny bug fixes git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@598 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
d61847e7b1206298a440311cffca15db7d2dcc0e
premake5.lua
premake5.lua
workspace("qor") targetdir("bin") configurations {"Debug", "Release"} defines { "GLM_FORCE_RADIANS" } -- Debug Config configuration "Debug" defines { "DEBUG" } symbols "On" linkoptions { } configuration "linux" links { "z", "bfd", "iberty" } -- Release Config configuration "Release" defines { "NDEBUG" } optimize "speed" targetname("qor_dist") -- gmake Config configuration "gmake" buildoptions { "-std=c++11" } -- buildoptions { "-std=c++11", "-pedantic", "-Wall", "-Wextra", '-v', '-fsyntax-only'} links { "pthread", "SDL2_ttf", "SDL2", "GLEW", "assimp", "freeimage", "openal", "alut", "ogg", "vorbis", "vorbisfile", "boost_system", "boost_filesystem", "boost_coroutine", "boost_python", "boost_regex", "jsoncpp", "RakNetDLL", --"BulletSoftBody", "BulletDynamics", "BulletCollision", "LinearMath", } includedirs { "lib/qor/", "lib/qor/lib/kit", "/usr/local/include/", "/usr/include/bullet/", "/usr/include/raknet/DependentExtensions" } libdirs { "/usr/local/lib" } buildoptions { "`python2-config --includes`", "`pkg-config --cflags cairomm-1.0 pangomm-1.4`" } linkoptions { "`python2-config --libs`", "`pkg-config --libs cairomm-1.0 pangomm-1.4`" } configuration "macosx" links { "boost_thread-mt", } buildoptions { "-framework OpenGL" } linkoptions { "-framework OpenGL" } --buildoptions { "-U__STRICT_ANSI__", "-stdlib=libc++" } --linkoptions { "-stdlib=libc++" } configuration "linux" links { "GL", "boost_thread", } configuration "windows" toolset "v140" flags { "MultiProcessorCompile" } links { "ws2_32", "glibmm.dll", "cairomm.dll", "pangomm.dll", "SDL2main", "OpenGL32", "GLU32", "SDL2", "SDL2_ttf", "GLEW32", "assimp", "freeimage", "alut", "libogg", "libvorbis", "libvorbisfile", "boost_system-vc141-mt-1_64", "boost_filesystem-vc141-mt-1_64", "boost_thread-vc141-mt-1_64", "python27", "boost_python-vc141-mt-1_64", "boost_coroutine-vc141-mt-1_64", "boost_regex-vc141-mt-1_64", "lib_json", } includedirs { "c:/Python27/include", "c:/gtkmm/lib/pangomm/include", "c:/gtkmm/lib/sigc++/include", "c:/gtkmm/lib/cairomm/include", "c:/gtkmm/include/pango", "c:/gtkmm/include/pangomm", "c:/gtkmm/include/sigc++", "c:/gtkmm/include", "c:/gtkmm/include/cairo", "c:/gtkmm/lib/glib/include", "c:/gtkmm/include/glib", "c:/gtkmm/lib/glibmm/include", "c:/gtkmm/include/glibmm", "c:/gtkmm/include/cairomm", "c:/gtkmm/include", "c:/local/boost_1_64_0", "c:/Program Files (x86)/OpenAL 1.1 SDK/include", "c:/msvc/include", } configuration { "windows", "Debug" } libdirs { "c:/msvc/lib32/debug" } configuration { "windows" } includedirs { "C:/Python27/include", } libdirs { "c:/Program Files (x86)/OpenAL 1.1 SDK/libs/Win32", "c:/msvc/lib32", "c:/gtkmm/lib", "c:/local/boost_1_64_0/lib32-msvc-14.1", "C:/Python27/libs", } -- buildoptions { -- "/MP", -- "/Gm-", -- } configuration { "windows", "Debug" } links { --"libboost_filesystem-vc140-mt-gd-1_64", "RakNet_VS2008_LibStatic_Debug_Win32", --"BulletSoftBody_vs2010", "BulletDynamics_vs2010_debug", "BulletCollision_vs2010_debug", "LinearMath_vs2010_debug", } configuration {} configuration { "windows", "Release" } links { --"libboost_filesystem-vc140-mt-1_64", "RakNet_VS2008_LibStatic_Release_Win32", --"BulletSoftBody_vs2010", "BulletDynamics_vs2010", "BulletCollision_vs2010", "LinearMath_vs2010", } project "qor" kind "WindowedApp" language "C++" -- Project Files files { "Qor/**.h", "Qor/**.cpp", "lib/kit/**.h", "lib/kit/**.cpp" } -- Exluding Files excludes { "Qor/tests/**", "Qor/scripts/**", "Qor/addons/**", "lib/kit/tests/**", "lib/kit/toys/**" } includedirs { "lib/kit", "/usr/local/include/", "/usr/include/bullet/", "/usr/include/raknet/DependentExtensions" }
workspace("qor") targetdir("bin") configurations {"Debug", "Release"} defines { "GLM_FORCE_RADIANS" } -- Debug Config configuration "Debug" defines { "DEBUG" } symbols "On" linkoptions { } configuration "linux" links { "z", "bfd", "iberty" } -- Release Config configuration "Release" defines { "NDEBUG" } optimize "speed" targetname("qor_dist") -- gmake Config configuration "gmake" buildoptions { "-std=c++11" } -- buildoptions { "-std=c++11", "-pedantic", "-Wall", "-Wextra", '-v', '-fsyntax-only'} links { "pthread", "SDL2_ttf", "SDL2", "GLEW", "assimp", "freeimage", "openal", "alut", "ogg", "vorbis", "vorbisfile", "boost_system", "boost_filesystem", "boost_coroutine", "boost_python", "boost_regex", "jsoncpp", "RakNetDLL", --"BulletSoftBody", "BulletDynamics", "BulletCollision", "LinearMath", } includedirs { "lib/qor/", "lib/qor/lib/kit", "/usr/local/include/", "/usr/include/bullet/", "/usr/include/raknet/DependentExtensions" } libdirs { "/usr/local/lib" } buildoptions { "`python2-config --includes`", "`pkg-config --cflags cairomm-1.0 pangomm-1.4`" } linkoptions { "`python2-config --libs`", "`pkg-config --libs cairomm-1.0 pangomm-1.4`" } configuration "macosx" links { "boost_thread-mt", } buildoptions { "-framework OpenGL" } linkoptions { "-framework OpenGL" } --buildoptions { "-U__STRICT_ANSI__", "-stdlib=libc++" } --linkoptions { "-stdlib=libc++" } configuration "linux" links { "GL", "boost_thread", } configuration "windows" toolset "v141" flags { "MultiProcessorCompile" } links { "ws2_32", "glibmm.dll.lib", "cairomm.dll.lib", "pangomm.dll.lib", "SDL2main", "OpenGL32", "GLU32", "SDL2", "SDL2_ttf", "GLEW32", "assimp", "freeimage", "OpenAL32", "alut", "libogg", "libvorbis", "libvorbisfile", "boost_system-vc141-mt-1_64", "boost_filesystem-vc141-mt-1_64", "boost_thread-vc141-mt-1_64", "python27", "boost_python-vc141-mt-1_64", "boost_coroutine-vc141-mt-1_64", "boost_regex-vc141-mt-1_64", "lib_json", } includedirs { "c:/Python27/include", "c:/gtkmm/lib/pangomm/include", "c:/gtkmm/lib/sigc++/include", "c:/gtkmm/lib/cairomm/include", "c:/gtkmm/include/pango", "c:/gtkmm/include/pangomm", "c:/gtkmm/include/sigc++", "c:/gtkmm/include", "c:/gtkmm/include/cairo", "c:/gtkmm/lib/glib/include", "c:/gtkmm/include/glib", "c:/gtkmm/lib/glibmm/include", "c:/gtkmm/include/glibmm", "c:/gtkmm/include/cairomm", "c:/gtkmm/include", "c:/local/boost_1_64_0", "c:/Program Files (x86)/OpenAL 1.1 SDK/include", "c:/msvc/include", } configuration { "windows", "Debug" } libdirs { "c:/msvc/lib32/debug" } configuration "windows" includedirs { "C:/Python27/include", } libdirs { "c:/Program Files (x86)/OpenAL 1.1 SDK/libs/Win32", "c:/msvc/lib32", "c:/gtkmm/lib", "C:/local/boost_1_64_0/lib32-msvc-14.1", "C:/Python27/libs", } -- buildoptions { -- "/MP", -- "/Gm-", -- } configuration { "windows", "Debug" } links { "RakNet_VS2008_LibStatic_Debug_Win32", --"BulletSoftBody_vs2010", "BulletDynamics_vs2010_debug", "BulletCollision_vs2010_debug", "LinearMath_vs2010_debug", } configuration {} configuration { "windows", "Release" } links { "RakNet_VS2008_LibStatic_Release_Win32", --"BulletSoftBody_vs2010", "BulletDynamics_vs2010", "BulletCollision_vs2010", "LinearMath_vs2010", } project "qor" kind "WindowedApp" language "C++" -- Project Files files { "Qor/**.h", "Qor/**.cpp", "lib/kit/**.h", "lib/kit/**.cpp" } -- Exluding Files excludes { "Qor/tests/**", "Qor/scripts/**", "Qor/addons/**", "lib/kit/tests/**", "lib/kit/toys/**" } includedirs { "lib/kit", "/usr/local/include/", "/usr/include/bullet/", "/usr/include/raknet/DependentExtensions" }
windows compilation fixes
windows compilation fixes
Lua
mit
flipcoder/qor,flipcoder/qor,flipcoder/qor,flipcoder/qor
806ca4d8f19c3613eba56b1e6b0d07e81bdac51e
plugins/mod_version.lua
plugins/mod_version.lua
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local prosody = prosody; local st = require "util.stanza"; local xmlns_version = "jabber:iq:version" module:add_feature(xmlns_version); local version = "the best operating system ever!"; if not module:get_option("hide_os_type") then if os.getenv("WINDIR") then version = "Windows"; else local uname = io.popen("uname"); if uname then version = uname:read("*a"); else version = "an OS"; end end end version = version:match("^%s*(.-)%s*$") or version; module:add_iq_handler({"c2s", "s2sin"}, xmlns_version, function(session, stanza) if stanza.attr.type == "get" then session.send(st.reply(stanza):query(xmlns_version) :tag("name"):text("Prosody"):up() :tag("version"):text(prosody.version):up() :tag("os"):text(version)); end end);
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st = require "util.stanza"; module:add_feature("jabber:iq:version"); local version = "the best operating system ever!"; if not module:get_option("hide_os_type") then if os.getenv("WINDIR") then version = "Windows"; else local uname = io.popen("uname"); if uname then version = uname:read("*a"); else version = "an OS"; end end end version = version:match("^%s*(.-)%s*$") or version; local query = st.stanza("query", {xmlns = "jabber:iq:version"}) :tag("name"):text("Prosody"):up() :tag("version"):text(prosody.version):up() :tag("os"):text(version); module:hook("iq/host/jabber:iq:version:query", function(event) local stanza = event.stanza; if stanza.attr.type == "get" and stanza.attr.to == module.host then event.origin.send(st.reply(stanza):add_child(query)); return true; end end);
mod_version: Rewritten to use new API. Added reply caching, and fixed some issues.
mod_version: Rewritten to use new API. Added reply caching, and fixed some issues.
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
dabadc7b229419989b2f36d6a4019354404c20ca
attack-on-deadline/RoomSelect.lua
attack-on-deadline/RoomSelect.lua
--[[ ルーム選択画面 概要: ・サーバから取得したルーム一覧を表示 ・新規にルーム作成もできる ・既存ルーム選択、新規ルーム作成をサーバに要求する ・サーバから正常な結果が返ってきたら、ルーム確認画面に遷移する ]] function setup() if not rootTbl then rootTbl = {} end local x = 0 local y = 0 local pForm = UI_Form(nil, -- arg[1]: 親となるUIタスクのポインタ 7000, -- arg[2]: 基準表示プライオリティ x, y, -- arg[3,4]: 表示位置 "asset://roomSelect.json", -- arg[5]: composit jsonのパス false -- arg[6]: 排他フラグ ) --[[ arg[6]:排他フラグ は、省略可能です。 省略した場合は false と同じ挙動になります。 ]] serverResult = nil -- ここにサーバから返ってきた bodyPayload が入る status = 0 -- まだサーバに何もリクエストしてないよ shinchoku.api.fetchRooms(callbackFetchRooms) status = 1 -- サーバへのリクエスト送ったよ TASK_StageOnly(pSceneForm) end function execute(deltaT) if status == 1 or status == 0 then -- TODO: あんまり通信中状態が長かったらキャンセルする処理も入れた方がいいかも return end if status == -1 then networkError() -- TODO: 前画面かトップ画面に戻る処理を入れる return end -- ここには通信成功 (status == 2)でしかこないはず status = 0 -- 通信終わってるはずだから元に戻しておくよ -- TODO: ルーム一覧表示を更新する end function leave() TASK_StageClear() end -- サーバとの通信処理のコールバック function callbackFetchRooms(connectionID, message, status, bodyPayload) if message ~= NETAPIMSG_REQUEST_SUCCESS or status ~= 200 then status = -1 -- 通信エラーだよ return end status = 2 -- サーバとの処理成功したよ serverResult = bodyPayload end -- TODO: エラー処理を書く function networkError() end
--[[ ルーム選択画面 概要: ・サーバから取得したルーム一覧を表示 ・新規にルーム作成もできる ・既存ルーム選択、新規ルーム作成をサーバに要求する ・サーバから正常な結果が返ってきたら、ルーム確認画面に遷移する ]] function setup() if not rootTbl then rootTbl = {} end local x = 0 local y = 0 local pForm = UI_Form(nil, -- arg[1]: 親となるUIタスクのポインタ 7000, -- arg[2]: 基準表示プライオリティ x, y, -- arg[3,4]: 表示位置 "asset://roomSelect.json", -- arg[5]: composit jsonのパス false -- arg[6]: 排他フラグ ) --[[ arg[6]:排他フラグ は、省略可能です。 省略した場合は false と同じ挙動になります。 ]] serverResult = nil -- ここにサーバから返ってきた bodyPayload が入る status = 0 -- まだサーバに何もリクエストしてないよ shinchoku.api.fetchRooms(callbackFetchRooms) status = 1 -- サーバへのリクエスト送ったよ TASK_StageOnly(pForm) end function execute(deltaT) if status == 1 or status == 0 then -- TODO: あんまり通信中状態が長かったらキャンセルする処理も入れた方がいいかも return end if status == -1 then networkError() -- TODO: 前画面かトップ画面に戻る処理を入れる return end -- ここには通信成功 (status == 2)でしかこないはず status = 0 -- 通信終わってるはずだから元に戻しておくよ -- TODO: ルーム一覧表示を更新する if serverResult == nil then return end end function leave() TASK_StageClear() end -- サーバとの通信処理のコールバック function callbackFetchRooms(connectionID, message, status, bodyPayload) if message ~= NETAPIMSG_REQUEST_SUCCESS or status ~= 200 then status = -1 -- 通信エラーだよ return end status = 2 -- サーバとの処理成功したよ serverResult = bodyPayload end -- TODO: エラー処理を書く function networkError() end
fix typo
fix typo
Lua
apache-2.0
mhidaka/playgroundthon,mhidaka/playgroundthon,mhidaka/playgroundthon,mhidaka/playgroundthon,mhidaka/playgroundthon,mhidaka/playgroundthon,mhidaka/playgroundthon
5344b9c1af64b1d16539f8844e1e890587c84d44
OS/DiskOS/APIS/RamUtils.lua
OS/DiskOS/APIS/RamUtils.lua
--RAM Utilities. --Variabes. local sw,sh = screenSize() --Localized Lua Library local unpack = unpack local floor, ceil, min = math.floor, math.ceil, math.min local strChar, strByte = string.char, string.byte local lshift, rshift, bor, band = bit.lshift, bit,rshift, bit.bor, bit.band --The API local RamUtils = {} RamUtils.VRAM = 0 --The start address of the VRAM RamUtils.LIMG = RamUtils.VRAM + (sw/2)*sh --The start address of the LabelImage. RamUtils.FRAM = RamUtils.LIMG + (sw/2)*sh --The start address of the Floppy RAM. RamUtils.Null = strChar(0) --The null character --==Images==-- --Encode an image into binary. function RamUtils.imgToBin(img,getTable) if image:typeOf("GPU.image") then image = image:data() end --Convert the image to imagedata. local bin = {} local imgW, imgH = img:size() local flag = true img:map(function(x,y,c) x = x + y*imgW + 1 local byte = bin[floor(x/2)] or 0 if flag then byte = byte + lshift(c,4) else byte = byte + c end bin[floor(x/2)] = byte flag = not flag end) if getTable then return bin end return strChar(unpack(bin)) end --Load an image from binary. function RamUtils.binToImage(img,bin) local colors, cid = {}, 1 for i=1,bin:len() do local byte = strByte(bin,i) local left = band(byte,0xF0) colors[cid] = rshift(left,4) colors[cid+1] = band(byte,0x0F) cid = cid + 2 end cid = 1 imgdata:map(function(x,y,c) local c = colors[cid] or 0 cid = cid + 1 return c end) end --==Maps==-- --Encode a map into binary. function RamUtils.mapToBin(map,getTable) local bin = {} local tid = 1 map:map(function(x,y,tile) bin[tid] = min(tile,255) tid = tid + 1 end) if getTable then return bin end return strChar(unpack(bin)) end --Load a map from binary. function RamUtils.binToMap(map,bin) local len, id = bin:len(), 0 map:map(function(x,y,tile) id = id + 1 return (id <= len and strByte(bin,id) or 0) end) end --==Code==-- --Encode code into binary. function RamUtils.codeToBin(code) return math.compress(code,"gzip",9) end --Load code from binary. function RamUtils.binToCode(bin) return math.decompress(bin,"gzip",9) end --==Extra==-- --Encode a number into binary function RamUtils.numToBin(num,length,getTable) local bytes,bnum = {}, 1 while num > 0 do bytes[bnum] = band(num,255) num = rshift(num,8) bnum = bnum + 1 end for i=bnum+1, length do bytes[i] = 0 end if getTable then return bytes end return strChar(unpack(bytes)) end --Load a number from binar function RamUtils.binToNum(bin) local number = 0 for i=1,bin:len() do number = number + strByte(bin,i) number = lshift(number,8) end return rshift(number,8) end --Make the ramutils a global _G["RamUtils"] = RamUtils
--RAM Utilities. --Variabes. local sw,sh = screenSize() --Localized Lua Library local unpack = unpack local floor, ceil, min = math.floor, math.ceil, math.min local strChar, strByte = string.char, string.byte local lshift, rshift, bor, band = bit.lshift, bit.rshift, bit.bor, bit.band --The API local RamUtils = {} RamUtils.VRAM = 0 --The start address of the VRAM RamUtils.LIMG = RamUtils.VRAM + (sw/2)*sh --The start address of the LabelImage. RamUtils.FRAM = RamUtils.LIMG + (sw/2)*sh --The start address of the Floppy RAM. RamUtils.Null = strChar(0) --The null character --==Images==-- --Encode an image into binary. function RamUtils.imgToBin(img,getTable) if image:typeOf("GPU.image") then image = image:data() end --Convert the image to imagedata. local bin = {} local imgW, imgH = img:size() local flag = true img:map(function(x,y,c) x = x + y*imgW + 1 local byte = bin[floor(x/2)] or 0 if flag then byte = byte + lshift(c,4) else byte = byte + c end bin[floor(x/2)] = byte flag = not flag end) if getTable then return bin end return strChar(unpack(bin)) end --Load an image from binary. function RamUtils.binToImage(img,bin) local colors, cid = {}, 1 for i=1,bin:len() do local byte = strByte(bin,i) local left = band(byte,0xF0) colors[cid] = rshift(left,4) colors[cid+1] = band(byte,0x0F) cid = cid + 2 end cid = 1 imgdata:map(function(x,y,c) local c = colors[cid] or 0 cid = cid + 1 return c end) end --==Maps==-- --Encode a map into binary. function RamUtils.mapToBin(map,getTable) local bin = {} local tid = 1 map:map(function(x,y,tile) bin[tid] = min(tile,255) tid = tid + 1 end) if getTable then return bin end return strChar(unpack(bin)) end --Load a map from binary. function RamUtils.binToMap(map,bin) local len, id = bin:len(), 0 map:map(function(x,y,tile) id = id + 1 return (id <= len and strByte(bin,id) or 0) end) end --==Code==-- --Encode code into binary. function RamUtils.codeToBin(code) return math.compress(code,"gzip",9) end --Load code from binary. function RamUtils.binToCode(bin) return math.decompress(bin,"gzip",9) end --==Extra==-- --Encode a number into binary function RamUtils.numToBin(num,length,getTable) local bytes = {} for bnum=1,length do bytes[bnum] = band(num,255) num = rshift(num,8) end if getTable then return bytes end return strChar(unpack(bytes)) end --Load a number from binar function RamUtils.binToNum(bin) local number = 0 for i=1,bin:len() do local byte = strByte(bin,i) byte = lshift(byte,(i-1)*8) number = bor(number,strByte(bin,i)) end return number end --Make the ramutils a global _G["RamUtils"] = RamUtils
Trying to fix (bin <-> num) functions
Trying to fix (bin <-> num) functions
Lua
mit
RamiLego4Game/LIKO-12
e2b9137420b3444766d28ca8b773bfee7e978c68
spec/resty/concurrent/timer_task_spec.lua
spec/resty/concurrent/timer_task_spec.lua
local TimerTask = require('resty.concurrent.timer_task') local ngx_timer = ngx.timer describe('TimerTask', function() local test_task = function() end before_each(function() TimerTask.active_tasks = {} end) describe('.register_task', function() it('adds an ID to the list of active tasks', function() local id = '1' TimerTask.register_task(id) assert.is_true(TimerTask.task_is_active(id)) end) end) describe('.unregister_task', function() local id = '1' setup(function() TimerTask.register_task(id) end) it('removes an ID to the list of active tasks', function() TimerTask.unregister_task(id) assert.is_false(TimerTask.task_is_active(id)) end) end) describe(':new', function() it('adds the task to the list of active tasks', function() local task = TimerTask.new(test_task) assert.is_true(TimerTask.task_is_active(task.id)) end) it('sets a default interval of 60s when not specified', function() local task = TimerTask.new(test_task) assert.equals(60, task.interval) end) it('allows to set a running interval', function() local interval = 10 local task = TimerTask.new(test_task, { interval = interval }) assert.equals(interval, task.interval) end) it('allows to set arguments for the task', function() local args = { '1', '2' } local task = TimerTask.new(test_task, { args = args }) assert.same(args, task.args) end) end) describe(':cancel', function() it('removes the task from the list of active tasks', function() local task = TimerTask.new(test_task) task:cancel() assert.is_false(TimerTask.task_is_active(task.id)) end) end) describe(':execute', function() local func = test_task local ngx_timer_stub local args = { '1', '2', '3' } local interval = 10 before_each(function() ngx_timer_stub = stub(ngx_timer, 'at') end) describe('when the task is active', function() it('runs the task', function() local timer_task = TimerTask.new(func, { args = args, interval = interval }) local func_spy = spy.on(timer_task, 'task') timer_task:execute(true) assert.spy(func_spy).was_called_with(unpack(args)) end) it('schedules the next one', function() local timer_task = TimerTask.new(func, { args = args, interval = interval }) timer_task:execute(true) assert.stub(ngx_timer_stub).was_called() end) end) describe('when the task is not active', function() it('does not run the task', function() local timer_task = TimerTask.new(func, { args = args, interval = interval }) local func_spy = spy.on(timer_task, 'task') timer_task:cancel() timer_task:execute(true) assert.spy(func_spy).was_not_called() end) it('does not schedule another task', function() local timer_task = TimerTask.new(func, { args = args, interval = interval }) timer_task:cancel() timer_task:execute(true) assert.stub(ngx_timer_stub).was_not_called() end) end) describe('when the option to wait an interval instead of running now is passed', function() it('does not run the task inmediately', function() local timer_task = TimerTask.new(func, { args = args, interval = interval }) local func_spy = spy.on(timer_task, 'task') timer_task:execute(false) -- It will be called in 'interval' seconds, but not now assert.spy(func_spy).was_not_called() end) it('schedules the next one', function() local timer_task = TimerTask.new(func, { args = args, interval = interval }) timer_task:execute(false) assert.stub(ngx_timer_stub).was_called() end) end) end) it('cancels itself when it is garbage collected', function() local timer_task = TimerTask.new(test_task) local id = timer_task.id timer_task = nil collectgarbage() assert.is_false(TimerTask.task_is_active(id)) end) end)
local TimerTask = require('resty.concurrent.timer_task') local ngx_timer = ngx.timer describe('TimerTask', function() local test_task = function() end before_each(function() TimerTask.active_tasks = {} end) after_each(function() -- We need to trigger a GC cycle after each test. -- Instances of TimerTask mark themselves as inactive by removing their ID -- from TimerTask.active_tasks, which is shared between tests. -- The sequence of random numbers generated by resty.jit-uuid starts from -- the beginning on each nested describe clause. That means that IDs are -- reused from different tests. -- That means that the following situation might happen: -- A test with some ID runs, a second test that reuses the same ID runs an -- assumes that during the test the ID will be marked as active. However, -- in the middle of the test a garbage collector cycle is triggered and -- runs the __gc method of an instance from the first test. Now the ID is -- marked as inactive and the second test fails. collectgarbage() end) describe('.register_task', function() it('adds an ID to the list of active tasks', function() local id = '1' TimerTask.register_task(id) assert.is_true(TimerTask.task_is_active(id)) end) end) describe('.unregister_task', function() local id = '1' setup(function() TimerTask.register_task(id) end) it('removes an ID to the list of active tasks', function() TimerTask.unregister_task(id) assert.is_false(TimerTask.task_is_active(id)) end) end) describe(':new', function() it('adds the task to the list of active tasks', function() local task = TimerTask.new(test_task) assert.is_true(TimerTask.task_is_active(task.id)) end) it('sets a default interval of 60s when not specified', function() local task = TimerTask.new(test_task) assert.equals(60, task.interval) end) it('allows to set a running interval', function() local interval = 10 local task = TimerTask.new(test_task, { interval = interval }) assert.equals(interval, task.interval) end) it('allows to set arguments for the task', function() local args = { '1', '2' } local task = TimerTask.new(test_task, { args = args }) assert.same(args, task.args) end) end) describe(':cancel', function() it('removes the task from the list of active tasks', function() local task = TimerTask.new(test_task) task:cancel() assert.is_false(TimerTask.task_is_active(task.id)) end) end) describe(':execute', function() local func = test_task local ngx_timer_stub local args = { '1', '2', '3' } local interval = 10 before_each(function() ngx_timer_stub = stub(ngx_timer, 'at') end) describe('when the task is active', function() it('runs the task', function() local timer_task = TimerTask.new(func, { args = args, interval = interval }) local func_spy = spy.on(timer_task, 'task') timer_task:execute(true) assert.spy(func_spy).was_called_with(unpack(args)) end) it('schedules the next one', function() local timer_task = TimerTask.new(func, { args = args, interval = interval }) timer_task:execute(true) assert.stub(ngx_timer_stub).was_called() end) end) describe('when the task is not active', function() it('does not run the task', function() local timer_task = TimerTask.new(func, { args = args, interval = interval }) local func_spy = spy.on(timer_task, 'task') timer_task:cancel() timer_task:execute(true) assert.spy(func_spy).was_not_called() end) it('does not schedule another task', function() local timer_task = TimerTask.new(func, { args = args, interval = interval }) timer_task:cancel() timer_task:execute(true) assert.stub(ngx_timer_stub).was_not_called() end) end) describe('when the option to wait an interval instead of running now is passed', function() it('does not run the task inmediately', function() local timer_task = TimerTask.new(func, { args = args, interval = interval }) local func_spy = spy.on(timer_task, 'task') timer_task:execute(false) -- It will be called in 'interval' seconds, but not now assert.spy(func_spy).was_not_called() end) it('schedules the next one', function() local timer_task = TimerTask.new(func, { args = args, interval = interval }) timer_task:execute(false) assert.stub(ngx_timer_stub).was_called() end) end) end) it('cancels itself when it is garbage collected', function() local timer_task = TimerTask.new(test_task) local id = timer_task.id timer_task = nil collectgarbage() assert.is_false(TimerTask.task_is_active(id)) end) end)
spec/resty/concurrent/timer_task: run the GC after each test
spec/resty/concurrent/timer_task: run the GC after each test This fixes a flaky test.
Lua
mit
3scale/docker-gateway,3scale/apicast,3scale/apicast,3scale/apicast,3scale/docker-gateway,3scale/apicast
e34b843e61c14e8526b3b18a958a81d53994a5ff
gwen/Projects/premake4.lua
gwen/Projects/premake4.lua
dofile( "inc/include.lua" ) solution "GWEN" language "C++" location ( os.get() .. "/" .. _ACTION ) flags { "Unicode", "Symbols", "NoEditAndContinue", "NoPCH", "No64BitChecks", "StaticRuntime", "EnableSSE" } -- "NoRTTI" targetdir ( "../lib/" .. os.get() .. "/" .. _ACTION ) libdirs { "../lib/", "../lib/" .. os.get() } configurations { "Release", "Debug" } if ( _ACTION == "vs2010" or _ACTION=="vs2008" ) then buildoptions { "/MP" } end configuration "Release" defines { "NDEBUG" } flags{ "Optimize", "FloatFast" } includedirs { "../include/" } configuration "Debug" defines { "_DEBUG" } includedirs { "../include/" } targetsuffix( "d" ) project "GWEN-DLL" defines { "GWEN_COMPILE_DLL" } files { "../src/**.*", "../include/Gwen/**.*" } kind "SharedLib" targetname( "gwen" ) project "GWEN-Static" defines { "GWEN_COMPILE_STATIC" } files { "../src/**.*", "../include/Gwen/**.*" } flags { "Symbols" } kind "StaticLib" targetname( "gwen_static" ) project "UnitTest" files { "../UnitTest/**.*" } flags { "Symbols" } kind "StaticLib" targetname( "unittest" ) -- -- Renderers -- DefineRenderer( "OpenGL", {"../Renderers/OpenGL/OpenGL.cpp"} ) DefineRenderer( "OpenGL_DebugFont", { "../Renderers/OpenGL/OpenGL.cpp", "../Renderers/OpenGL/DebugFont/OpenGL_DebugFont.cpp" } ) DefineRenderer( "SFML", { "../Renderers/SFML/SFML.cpp" }, SFML_DEFINES ) DefineRenderer( "SFML2", { "../Renderers/SFML2/SFML2.cpp" }, SFML2_DEFINES ) DefineRenderer( "Allegro", { "../Renderers/Allegro/Allegro.cpp" } ) if ( os.get() == "windows" ) then DefineRenderer( "DirectX9", { "../Renderers/DirectX9/DirectX9.cpp" } ) includedirs { "$(DXSDK_DIR)/Include" } libdirs { "$(DXSDK_DIR)/lib/x86" } DefineRenderer( "Direct2D", { "../Renderers/Direct2D/Direct2D.cpp" } ) includedirs { "$(DXSDK_DIR)/Include" } libdirs { "$(DXSDK_DIR)/lib/x86" } DefineRenderer( "GDI", { "../Renderers/GDIPlus/GDIPlus.cpp", "../Renderers/GDIPlus/GDIPlusBuffered.cpp" } ) end -- -- Samples -- DefineSample( "CrossPlatform", { "../Samples/CrossPlatform/CrossPlatform.cpp" }, CROSS_LIBS, nil, { "USE_DEBUG_FONT" } ) DefineSample( "SFML", { "../Samples/SFML/SFML.cpp" }, SFML_LIBS, SFML_LIBS_D, SFML_DEFINES ) DefineSample( "SFML2", { "../Samples/SFML2/SFML2.cpp" }, SFML2_LIBS, SFML2_LIBS_D, SFML2_DEFINES ) DefineSample( "Allegro", { "../Samples/Allegro/AllegroSample.cpp" }, ALLEGRO_LIBS, ALLEGRO_LIBS_D ) if ( os.get() == "windows" ) then DefineSample( "Direct2D", { "../Samples/Direct2D/Direct2DSample.cpp" }, { "UnitTest", "Renderer-Direct2D", "GWEN-Static", "d2d1", "dwrite", "windowscodecs" } ) includedirs { "$(DXSDK_DIR)/Include" } libdirs { "$(DXSDK_DIR)/lib/x86" } DefineSample( "DirectX9", { "../Samples/Direct3D/Direct3DSample.cpp" }, { "UnitTest", "Renderer-DirectX9", "GWEN-Static" } ) includedirs { "$(DXSDK_DIR)/Include" } libdirs { "$(DXSDK_DIR)/lib/x86" } DefineSample( "WindowsGDI", { "../Samples/WindowsGDI/WindowsGDI.cpp" }, { "UnitTest", "Renderer-GDI", "GWEN-Static" } ) DefineSample( "OpenGL", { "../Samples/OpenGL/OpenGLSample.cpp" }, { "UnitTest", "Renderer-OpenGL", "GWEN-Static", "FreeImage", "opengl32" } ) DefineSample( "OpenGL_DebugFont", { "../Samples/OpenGL/OpenGLSample.cpp" }, { "UnitTest", "Renderer-OpenGL_DebugFont", "GWEN-Static", "FreeImage", "opengl32" }, nil, { "USE_DEBUG_FONT" } ) end project "ControlFactory" files { "../Util/ControlFactory/**.*" } kind "StaticLib" targetname( "controlfactory" ) project "ImportExport" files { "../Util/ImportExport/**.*" } kind "StaticLib" targetname( "importexport" )
dofile( "inc/include.lua" ) solution "GWEN" language "C++" location ( os.get() .. "/" .. _ACTION ) flags { "Unicode", "Symbols", "NoEditAndContinue", "NoPCH", "No64BitChecks", "StaticRuntime", "EnableSSE" } -- "NoRTTI" targetdir ( "../lib/" .. os.get() .. "/" .. _ACTION ) libdirs { "../lib/", "../lib/" .. os.get() } configurations { "Release", "Debug" } if ( _ACTION == "vs2010" or _ACTION=="vs2008" ) then -- Enable multiprocessor compilation (requires Minimal Rebuild to be disabled) buildoptions { "/MP" } flags { "NoMinimalRebuild" } end configuration "Release" defines { "NDEBUG" } flags{ "Optimize", "FloatFast" } includedirs { "../include/" } configuration "Debug" defines { "_DEBUG" } includedirs { "../include/" } targetsuffix( "d" ) project "GWEN-DLL" defines { "GWEN_COMPILE_DLL" } files { "../src/**.*", "../include/Gwen/**.*" } kind "SharedLib" targetname( "gwen" ) project "GWEN-Static" defines { "GWEN_COMPILE_STATIC" } files { "../src/**.*", "../include/Gwen/**.*" } flags { "Symbols" } kind "StaticLib" targetname( "gwen_static" ) project "UnitTest" files { "../UnitTest/**.*" } flags { "Symbols" } kind "StaticLib" targetname( "unittest" ) -- -- Renderers -- DefineRenderer( "OpenGL", {"../Renderers/OpenGL/OpenGL.cpp"} ) DefineRenderer( "OpenGL_DebugFont", { "../Renderers/OpenGL/OpenGL.cpp", "../Renderers/OpenGL/DebugFont/OpenGL_DebugFont.cpp" } ) DefineRenderer( "SFML", { "../Renderers/SFML/SFML.cpp" }, SFML_DEFINES ) DefineRenderer( "SFML2", { "../Renderers/SFML2/SFML2.cpp" }, SFML2_DEFINES ) DefineRenderer( "Allegro", { "../Renderers/Allegro/Allegro.cpp" } ) if ( os.get() == "windows" ) then DefineRenderer( "DirectX9", { "../Renderers/DirectX9/DirectX9.cpp" } ) includedirs { "$(DXSDK_DIR)/Include" } libdirs { "$(DXSDK_DIR)/lib/x86" } DefineRenderer( "Direct2D", { "../Renderers/Direct2D/Direct2D.cpp" } ) includedirs { "$(DXSDK_DIR)/Include" } libdirs { "$(DXSDK_DIR)/lib/x86" } DefineRenderer( "GDI", { "../Renderers/GDIPlus/GDIPlus.cpp", "../Renderers/GDIPlus/GDIPlusBuffered.cpp" } ) end -- -- Samples -- DefineSample( "CrossPlatform", { "../Samples/CrossPlatform/CrossPlatform.cpp" }, CROSS_LIBS, nil, { "USE_DEBUG_FONT" } ) DefineSample( "SFML", { "../Samples/SFML/SFML.cpp" }, SFML_LIBS, SFML_LIBS_D, SFML_DEFINES ) DefineSample( "SFML2", { "../Samples/SFML2/SFML2.cpp" }, SFML2_LIBS, SFML2_LIBS_D, SFML2_DEFINES ) DefineSample( "Allegro", { "../Samples/Allegro/AllegroSample.cpp" }, ALLEGRO_LIBS, ALLEGRO_LIBS_D ) if ( os.get() == "windows" ) then DefineSample( "Direct2D", { "../Samples/Direct2D/Direct2DSample.cpp" }, { "UnitTest", "Renderer-Direct2D", "GWEN-Static", "d2d1", "dwrite", "windowscodecs" } ) includedirs { "$(DXSDK_DIR)/Include" } libdirs { "$(DXSDK_DIR)/lib/x86" } DefineSample( "DirectX9", { "../Samples/Direct3D/Direct3DSample.cpp" }, { "UnitTest", "Renderer-DirectX9", "GWEN-Static" } ) includedirs { "$(DXSDK_DIR)/Include" } libdirs { "$(DXSDK_DIR)/lib/x86" } DefineSample( "WindowsGDI", { "../Samples/WindowsGDI/WindowsGDI.cpp" }, { "UnitTest", "Renderer-GDI", "GWEN-Static" } ) DefineSample( "OpenGL", { "../Samples/OpenGL/OpenGLSample.cpp" }, { "UnitTest", "Renderer-OpenGL", "GWEN-Static", "FreeImage", "opengl32" } ) DefineSample( "OpenGL_DebugFont", { "../Samples/OpenGL/OpenGLSample.cpp" }, { "UnitTest", "Renderer-OpenGL_DebugFont", "GWEN-Static", "FreeImage", "opengl32" }, nil, { "USE_DEBUG_FONT" } ) end project "ControlFactory" files { "../Util/ControlFactory/**.*" } kind "StaticLib" targetname( "controlfactory" ) project "ImportExport" files { "../Util/ImportExport/**.*" } kind "StaticLib" targetname( "importexport" )
Visual Studio multi-processor compilation fix
Visual Studio multi-processor compilation fix - Fixed premake script to disable Minimal Rebuild (/Gm) in order to build with multi-processor compilation
Lua
mit
garrynewman/GWEN,garrynewman/GWEN,garrynewman/GWEN
fe14180a6b5ba8ef1caa61c50dba11be848ff011
Modules/Events/TimeSyncManager.lua
Modules/Events/TimeSyncManager.lua
local MasterClock = {} MasterClock.__index = MasterClock MasterClock.ClassName = "MasterClock" -- MasterClock sends time to client. function MasterClock.new(SyncEvent, DelayedRequestFunction) local self = {} setmetatable(self, MasterClock) self.SyncEvent = SyncEvent self.DelayedRequestFunction = DelayedRequestFunction -- Define function calls and events. function self.DelayedRequestFunction.OnServerInvoke(Player, TimeThree) -- @return SlaveMasterDifference return self:HandleDelayRequest(TimeThree) end self.SyncEvent.OnServerEvent:connect(function(Player) self.SyncEvent:FireClient(Player, self:GetTime()) end) -- Create thread.... forever! Yeah! That's right! spawn(function() while true do wait(5) self:Sync() end end) return self end function MasterClock:GetTime() return workspace.DistributedGameTime end function MasterClock:Sync() --- Starts the sync process with all slave clocks. local TimeOne = self:GetTime() --print("[MasterClock] - Syncing all clients, TimeOne = ", TimeOne) self.SyncEvent:FireAllClients(TimeOne) end function MasterClock:HandleDelayRequest(TimeThree) --- Client sends back message to get the SM_Difference. -- @return SlaveMasterDifference local TimeFour = self:GetTime() return TimeFour - TimeThree -- -Offset + SM Delay end local SlaveClock = {} SlaveClock.__index = SlaveClock SlaveClock.ClassName = "SlaveClock" function SlaveClock.new(SyncEvent, DelayedRequestFunction) local self = {} setmetatable(self, SlaveClock) self.SyncEvent = SyncEvent self.DelayedRequestFunction = DelayedRequestFunction self.Offset = -1 -- Uncalculated. -- Connect self.SyncEvent.OnClientEvent:connect(function(TimeOne) self:HandleSyncEvent(TimeOne) end) -- Request sync. self.SyncEvent:FireServer() return self end function SlaveClock:GetLocalTime() return workspace.DistributedGameTime end function SlaveClock:HandleSyncEvent(TimeOne) -- http://www.nist.gov/el/isd/ieee/upload/tutorial-basic.pdf -- We can't actually get hardware stuff, so we'll send T1 immediately. local TimeTwo = self:GetLocalTime() local MasterSlaveDifference = TimeTwo - TimeOne -- We have Offst + MS Delay -- wait(1) local TimeThree = self:GetLocalTime() local SlaveMasterDifference = self:SendDelayRequest(TimeThree) --[[ From explination link. The result is that we have the following two equations: MS_difference = offset + MS delay SM_difference = ?offset + SM delay With two measured quantities: MS_difference = 90 minutes SM_difference = ?20 minutes And three unknowns: offset , MS delay, and SM delay Rearrange the equations according to the tutorial. -- Assuming this: MS delay = SM delay = one_way_delay one_way_delay = (MSDelay + SMDelay) / 2 ]] local Offset = (MasterSlaveDifference - SlaveMasterDifference)/2 local OneWayDelay = (MasterSlaveDifference + SlaveMasterDifference)/2 --print("[SlaveClock] - Synced time at ", self.Offset, "change of ", Offset - self.Offset, ". self:GetTime() = ", self:GetTime(), "OneWayDelay time @ ", OneWayDelay) self.Offset = Offset -- Estimated difference between server/client self.OneWayDelay = OneWayDelay -- Estimated time for network events to send. (MSDelay/SMDelay) end function SlaveClock:SendDelayRequest(TimeThree) return self.DelayedRequestFunction:InvokeServer(TimeThree) end function SlaveClock:GetTime() if self.Offset == -1 then warn("[SlaveClock] - Offset is -1, may be unsynced clock!") end return self:GetLocalTime() - self.Offset end --- Actual Construction -- -- Determine what class to send back here: Singleton. -- Usually I wouldn't do something as... badly designed... as this, but in this case -- I'm pretty sure these sync calls are expensive, so it's best that we do it here. local Players = game:GetService("Players") local ReplicatedStorage = game:GetService("ReplicatedStorage") local NevermoreEngine = require(ReplicatedStorage:WaitForChild("NevermoreEngine")) local SyncEvent = NevermoreEngine.GetRemoteEvent("TimeSyncEvent") local DelayedRequestFunction = NevermoreEngine.GetRemoteFunction("DelayedRequestEvent") local Manager if game:FindService("NetworkServer") == nil and game:FindService("NetworkClient") == nil then -- Solo test mode Manager = MasterClock.new(SyncEvent, DelayedRequestFunction) print("[TimeSyncManager] - SoloTestMode enabled. MasterClock constructed.") elseif Players.LocalPlayer then -- Client Manager = SlaveClock.new(SyncEvent, DelayedRequestFunction) print("[TimeSyncManager] - Client mode enabled. SlaveClock constructed.") else -- Server Manager = MasterClock.new(SyncEvent, DelayedRequestFunction) print("[TimeSyncManager] - Server mode enabled. MasterClock constructed.") end return Manager
local MasterClock = {} MasterClock.__index = MasterClock MasterClock.ClassName = "MasterClock" -- MasterClock sends time to client. function MasterClock.new(SyncEvent, DelayedRequestFunction) local self = {} setmetatable(self, MasterClock) self.SyncEvent = SyncEvent self.DelayedRequestFunction = DelayedRequestFunction -- Define function calls and events. function self.DelayedRequestFunction.OnServerInvoke(Player, TimeThree) -- @return SlaveMasterDifference return self:HandleDelayRequest(TimeThree) end self.SyncEvent.OnServerEvent:connect(function(Player) self.SyncEvent:FireClient(Player, self:GetTime()) end) -- Create thread.... forever! Yeah! That's right! spawn(function() while true do wait(5) self:Sync() end end) return self end function MasterClock:GetTime() return workspace.DistributedGameTime end function MasterClock:Sync() --- Starts the sync process with all slave clocks. local TimeOne = self:GetTime() --print("[MasterClock] - Syncing all clients, TimeOne = ", TimeOne) self.SyncEvent:FireAllClients(TimeOne) end function MasterClock:HandleDelayRequest(TimeThree) --- Client sends back message to get the SM_Difference. -- @return SlaveMasterDifference local TimeFour = self:GetTime() return TimeFour - TimeThree -- -Offset + SM Delay end local SlaveClock = {} SlaveClock.__index = SlaveClock SlaveClock.ClassName = "SlaveClock" function SlaveClock.new(SyncEvent, DelayedRequestFunction) local self = {} setmetatable(self, SlaveClock) self.SyncEvent = SyncEvent self.DelayedRequestFunction = DelayedRequestFunction self.Offset = -1 -- Uncalculated. -- Connect self.SyncEvent.OnClientEvent:connect(function(TimeOne) self:HandleSyncEvent(TimeOne) end) -- Request sync. self.SyncEvent:FireServer() return self end function SlaveClock:GetLocalTime() return workspace.DistributedGameTime end function SlaveClock:HandleSyncEvent(TimeOne) -- http://www.nist.gov/el/isd/ieee/upload/tutorial-basic.pdf -- We can't actually get hardware stuff, so we'll send T1 immediately. local TimeTwo = self:GetLocalTime() local MasterSlaveDifference = TimeTwo - TimeOne -- We have Offst + MS Delay -- wait(1) local TimeThree = self:GetLocalTime() local SlaveMasterDifference = self:SendDelayRequest(TimeThree) --[[ From explination link. The result is that we have the following two equations: MS_difference = offset + MS delay SM_difference = ?offset + SM delay With two measured quantities: MS_difference = 90 minutes SM_difference = ?20 minutes And three unknowns: offset , MS delay, and SM delay Rearrange the equations according to the tutorial. -- Assuming this: MS delay = SM delay = one_way_delay one_way_delay = (MSDelay + SMDelay) / 2 ]] local Offset = (MasterSlaveDifference - SlaveMasterDifference)/2 local OneWayDelay = (MasterSlaveDifference + SlaveMasterDifference)/2 --print("[SlaveClock] - Synced time at ", self.Offset, "change of ", Offset - self.Offset, ". self:GetTime() = ", self:GetTime(), "OneWayDelay time @ ", OneWayDelay) self.Offset = Offset -- Estimated difference between server/client self.OneWayDelay = OneWayDelay -- Estimated time for network events to send. (MSDelay/SMDelay) end function SlaveClock:SendDelayRequest(TimeThree) return self.DelayedRequestFunction:InvokeServer(TimeThree) end function SlaveClock:GetTime() if self.Offset == -1 then warn("[SlaveClock] - Offset is -1, may be unsynced clock!") end return self:GetLocalTime() - self.Offset end --- Actual Construction -- -- Determine what class to send back here: Singleton. -- Usually I wouldn't do something as... badly designed... as this, but in this case -- I'm pretty sure these sync calls are expensive, so it's best that we do it here. local Players = game:GetService("Players") local ReplicatedStorage = game:GetService("ReplicatedStorage") local NevermoreEngine = require(ReplicatedStorage:WaitForChild("NevermoreEngine")) local SyncEvent = NevermoreEngine.GetRemoteEvent("TimeSyncEvent") local DelayedRequestFunction = NevermoreEngine.GetRemoteFunction("DelayedRequestEvent") local Manager if game:FindService("NetworkServer") == nil and game:FindService("NetworkClient") == nil then -- Solo test mode Manager = MasterClock.new(SyncEvent, DelayedRequestFunction) --> Edge case issue: --> Remote event invocation queue exhausted for ReplicatedStorage.NevermoreResources.EventStreamContainer.TimeSyncEvent; did you forget to implement OnClientEvent? -- Occurs because there is no OnClientEvent invoked for the sync thing. Will do so now. SyncEvent.OnClientEvent:connect(function() end) print("[TimeSyncManager] - SoloTestMode enabled. MasterClock constructed.") elseif Players.LocalPlayer then -- Client Manager = SlaveClock.new(SyncEvent, DelayedRequestFunction) print("[TimeSyncManager] - Client mode enabled. SlaveClock constructed.") else -- Server Manager = MasterClock.new(SyncEvent, DelayedRequestFunction) print("[TimeSyncManager] - Server mode enabled. MasterClock constructed.") end return Manager
Edge case fix
Edge case fix
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
85811b2b3f03914a7183f967c6b476e0a722caee
src/rules.lua
src/rules.lua
require 'Target' local system = require 'system' local mkpath = system.mkpath local P = {} local Rule = { init_stages = { 'unpack', 'patch' } } Rule.__index = Rule local function import_paths(filename) local o = {} table.insert(o, mkpath(jagen.dir, 'lib', filename)) for _, overlay in ipairs(string.split(jagen.overlays, ' ')) do table.insert(o, mkpath(jagen.dir, 'overlay', overlay, filename)) end table.insert(o, mkpath(jagen.root, filename)) return o end local function loadsingle(filename) local o, env = {}, {} function env.package(rule) o = rule end local chunk = loadfile(filename) if chunk then setfenv(chunk, env) chunk() end return o end local function loadall(filename) local o, env = {}, { table = table, jagen = jagen } function env.package(rule, template) table.insert(o, Rule:new(rule, template)) end local chunk = loadfile(filename) if chunk then setfenv(chunk, env) chunk() end return o end local function add_package(rule, list) local key = tostring(rule) local pkg = list[key] if not pkg then pkg = Rule:new_package { rule.name } table.merge(pkg, rule) if pkg.build and pkg.config then pkg:add_build_stages(list) end pkg:add_stages(pkg, list) if pkg.source and pkg.source.type == 'repo' then local unpack = { { 'unpack', requires = { { 'repo', 'host' } } } } pkg:add_stages(unpack, list) end list[key] = pkg else table.merge(pkg, rule) end pkg:add_stages(rule, list) end function Rule:__tostring() return string.format('%s__%s', self.name or '', self.config or '') end function Rule:parse(rule) if type(rule[1]) == 'string' then rule.name = rule[1] table.remove(rule, 1) end if type(rule[1]) == 'string' then rule.config = rule[1] table.remove(rule, 1) end if type(rule.source) == 'string' then rule.source = { type = 'dist', location = rule.source } end return rule end function Rule:new(rule, template) rule = Rule:parse(rule) local new if template then new = Rule:parse(copy(template)) table.merge(new, rule) new.template = template else new = rule end setmetatable(new, self) return new end function Rule:new_package(rule) local pkg = Rule:new(rule) local name = pkg.name pkg.stages = pkg.stages or {} for stage in each(self.init_stages) do pkg:add_target(Target:new(name, stage)) end for filename in each(import_paths('pkg/'..name..'.lua')) do table.merge(pkg, Rule:new(loadsingle(filename))) end return pkg end function Rule:add_stages(rule, list) local template = rule.template or {} local config = self.config or template.config for _, stage in ipairs(rule) do local tc = not stage.shared and self.config local target = Target:parse(stage, self.name, tc) for _, item in ipairs(stage.requires or {}) do local config, name = config if type(item) == 'string' then name = item else name = item[1] config = item[2] or config end target:append(Target:required(name, config)) add_package(Rule:new({ name = name, config = config }, template), list) end self:add_target(target) end end function Rule:add_target(target) local name = target.stage local config = target.config local shared = { unpack = true, patch = true, } local function add_to(pkg) if not pkg.stages then pkg.stages = {} end local stages = pkg.stages if stages[name] then stages[name]:add_inputs(target) else table.insert(stages, target) stages[name] = target end end if not config or shared[name] then add_to(self) else if not self.configs then self.configs = {} end if not self.configs[config] then self.configs[config] = {} end add_to(self.configs[config]) end return self end function Rule:add_build_stages(list) local build = self.build if self.requires then table.insert(self, { 'configure', requires = self.requires }) end if build.type == 'GNU' then if build.generate or build.autoreconf then local autoreconf = { { 'autoreconf', shared = true, requires = { { 'libtool', 'host' } } } } self:add_stages(autoreconf, list) end end if build.type then local build_rules = { { 'configure', requires = { 'toolchain' } }, { 'compile' }, { 'install' } } self:add_stages(build_rules, list) end end function Rule:add_ordering_dependencies() local prev, common for s in self:each() do if prev then s.inputs = s.inputs or {} if common and s.config ~= prev.config then append(s.inputs, common) else append(s.inputs, prev) end end prev = s if not s.config then common = s end end end function Rule:each() return coroutine.wrap(function () for _, t in ipairs(self.stages) do coroutine.yield(t) end for k, c in pairs(self.configs or {}) do for _, t in ipairs(c.stages or {}) do coroutine.yield(t) end end end) end function P.load() local packages = {} local Source = require 'Source' for filename in each(import_paths('rules.lua')) do for rule in each(loadall(filename)) do add_package(rule, packages) end end for _, pkg in pairs(packages) do pkg.source = Source:create(pkg.source, pkg.name) end return packages end function P.merge(rules) local packages = {} for _, rule in pairs(rules) do local name = assert(rule.name) local pkg = packages[name] if pkg then for target in rule:each() do pkg:add_target(target) end -- FIXME: really need to sanitize rule handling to get rid of merge -- step if pkg.source and rule.source then table.merge(pkg.source, rule.source) end else packages[name] = rule end end return packages end return P
require 'Target' local system = require 'system' local mkpath = system.mkpath local P = {} local Rule = { init_stages = { 'unpack', 'patch' } } Rule.__index = Rule local function import_paths(filename) local o = {} table.insert(o, mkpath(jagen.dir, 'lib', filename)) for _, overlay in ipairs(string.split(jagen.overlays, ' ')) do table.insert(o, mkpath(jagen.dir, 'overlay', overlay, filename)) end table.insert(o, mkpath(jagen.root, filename)) return o end local function loadsingle(filename) local o, env = {}, {} function env.package(rule) o = rule end local chunk = loadfile(filename) if chunk then setfenv(chunk, env) chunk() end return o end local function loadall(filename) local o, env = {}, { table = table, jagen = jagen } function env.package(rule, template) table.insert(o, Rule:new(rule, template)) end local chunk = loadfile(filename) if chunk then setfenv(chunk, env) chunk() end return o end local function add_package(rule, list) local key = tostring(rule) local pkg = list[key] if not pkg then pkg = Rule:new_package { rule.name } table.merge(pkg, rule) if pkg.build and pkg.config then pkg:add_build_stages(list) end pkg:add_stages(pkg, list) if pkg.source and pkg.source.type == 'repo' then local unpack = { { 'unpack', requires = { { 'repo', 'host' } } } } pkg:add_stages(unpack, list) end list[key] = pkg else table.merge(pkg, rule) if pkg.build and pkg.config then pkg:add_build_stages(list) pkg:add_stages(pkg, list) end end pkg:add_stages(rule, list) end function Rule:__tostring() return string.format('%s__%s', self.name or '', self.config or '') end function Rule:parse(rule) if type(rule[1]) == 'string' then rule.name = rule[1] table.remove(rule, 1) end if type(rule[1]) == 'string' then rule.config = rule[1] table.remove(rule, 1) end if type(rule.source) == 'string' then rule.source = { type = 'dist', location = rule.source } end return rule end function Rule:new(rule, template) rule = Rule:parse(rule) local new if template then new = Rule:parse(copy(template)) table.merge(new, rule) new.template = template else new = rule end setmetatable(new, self) return new end function Rule:new_package(rule) local pkg = Rule:new(rule) local name = pkg.name pkg.stages = pkg.stages or {} for stage in each(self.init_stages) do pkg:add_target(Target:new(name, stage)) end for filename in each(import_paths('pkg/'..name..'.lua')) do table.merge(pkg, Rule:new(loadsingle(filename))) end return pkg end function Rule:add_stages(rule, list) local template = rule.template or {} local config = self.config or template.config for i, stage in ipairs(rule) do local tc = not stage.shared and self.config local target = Target:parse(stage, self.name, tc) for _, item in ipairs(stage.requires or {}) do local config, name = config if type(item) == 'string' then name = item else name = item[1] config = item[2] or config end target:append(Target:required(name, config)) add_package(Rule:new({ name = name, config = config }, template), list) end self:add_target(target) rule[i] = nil end end function Rule:add_target(target) local name = target.stage local config = target.config local shared = { unpack = true, patch = true, } local function add_to(pkg) if not pkg.stages then pkg.stages = {} end local stages = pkg.stages if stages[name] then stages[name]:add_inputs(target) else table.insert(stages, target) stages[name] = target end end if not config or shared[name] then add_to(self) else if not self.configs then self.configs = {} end if not self.configs[config] then self.configs[config] = {} end add_to(self.configs[config]) end return self end function Rule:add_build_stages(list) local build = self.build if self.requires then table.insert(self, { 'configure', requires = self.requires }) end if build.type == 'GNU' then if build.generate or build.autoreconf then local autoreconf = { { 'autoreconf', shared = true, requires = { { 'libtool', 'host' } } } } self:add_stages(autoreconf, list) end end if build.type then local build_rules = { { 'configure', requires = { 'toolchain' } }, { 'compile' }, { 'install' } } self:add_stages(build_rules, list) end end function Rule:add_ordering_dependencies() local prev, common for s in self:each() do if prev then s.inputs = s.inputs or {} if common and s.config ~= prev.config then append(s.inputs, common) else append(s.inputs, prev) end end prev = s if not s.config then common = s end end end function Rule:each() return coroutine.wrap(function () for _, t in ipairs(self.stages) do coroutine.yield(t) end for k, c in pairs(self.configs or {}) do for _, t in ipairs(c.stages or {}) do coroutine.yield(t) end end end) end function P.load() local packages = {} local Source = require 'Source' for filename in each(import_paths('rules.lua')) do for rule in each(loadall(filename)) do add_package(rule, packages) end end for _, pkg in pairs(packages) do pkg.source = Source:create(pkg.source, pkg.name) end return packages end function P.merge(rules) local packages = {} for _, rule in pairs(rules) do local name = assert(rule.name) local pkg = packages[name] if pkg then for target in rule:each() do pkg:add_target(target) end -- FIXME: really need to sanitize rule handling to get rid of merge -- step if pkg.source and rule.source then table.merge(pkg.source, rule.source) end else packages[name] = rule end end return packages end return P
Fix adding stages for all configs
Fix adding stages for all configs
Lua
mit
bazurbat/jagen
fdd2c13b91bd1df68ee2f5150de4e0fdcd402ebc
packages/ruby.lua
packages/ruby.lua
SILE.registerCommand("ruby", function (o,c) local reading = SU.required(o, "reading", "\\ruby") SILE.call("hbox", {}, function() SILE.settings.temporarily(function () SILE.call("noindent") SILE.call("font", {size = "0.5zw"}) SILE.typesetter:typeset(reading) end) end) local rubybox = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] rubybox.outputYourself = function (self, typesetter, line) local ox = typesetter.frame.state.cursorX typesetter.frame.state.cursorX = typesetter.frame.state.cursorX + rubybox.width.length / 2 typesetter.frame:advancePageDirection(-SILE.toPoints("1zw")) SILE.outputter.moveTo(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY) for i = 1, #(self.value) do local node = self.value[i] node:outputYourself(typesetter, line) end typesetter.frame.state.cursorX = ox typesetter.frame:advancePageDirection(SILE.toPoints("1zw")) end -- measure the content SILE.call("hbox", {}, c) cbox = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] if cbox.width > rubybox.width then rubybox.width = cbox.width - rubybox.width else local to_insert = SILE.length.new({length = (rubybox.width - cbox.width).length / 2, }) cbox.width = rubybox.width rubybox.width = SILE.length.zero -- add spaces at beginning and end table.insert(cbox.value, 1, SILE.nodefactory.newGlue({ width = to_insert })) table.insert(cbox.value, SILE.nodefactory.newGlue({ width = to_insert })) end end)
SILE.registerCommand("ruby", function (o,c) local reading = SU.required(o, "reading", "\\ruby") SILE.call("hbox", {}, function() SILE.settings.temporarily(function () SILE.call("noindent") SILE.call("font", {size = "0.6zw", weight = 800 }) SILE.typesetter:typeset(reading) end) end) local rubybox = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] rubybox.outputYourself = function (self, typesetter, line) local ox = typesetter.frame.state.cursorX typesetter.frame.state.cursorX = typesetter.frame.state.cursorX + rubybox.width.length / 2 typesetter.frame:advancePageDirection(-SILE.toPoints("0.8zw")) SILE.outputter.moveTo(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY) for i = 1, #(self.value) do local node = self.value[i] node:outputYourself(typesetter, line) end typesetter.frame.state.cursorX = ox typesetter.frame:advancePageDirection(SILE.toPoints("0.8zw")) end -- measure the content SILE.call("hbox", {}, c) cbox = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] local measure if SILE.typesetter.frame:writingDirection() == "LTR" then measure = "width" else measure = "height" end if cbox[measure] > rubybox[measure] then rubybox[measure] = cbox[measure] - rubybox[measure] else local diff = rubybox[measure] - cbox[measure] if type(diff) == "table" then diff = diff.length end local to_insert = SILE.length.new({length = diff / 2, }) cbox[measure] = rubybox[measure] rubybox.width = SILE.length.zero -- add spaces at beginning and end table.insert(cbox.value, 1, SILE.nodefactory.newGlue({ width = to_insert })) table.insert(cbox.value, SILE.nodefactory.newGlue({ width = to_insert })) end end)
Ruby fixes.
Ruby fixes.
Lua
mit
simoncozens/sile,neofob/sile,simoncozens/sile,alerque/sile,neofob/sile,alerque/sile,alerque/sile,simoncozens/sile,neofob/sile,alerque/sile,simoncozens/sile,neofob/sile
df7f03853317cc954ecb9765c823fa32e59851f8
tests/test-http-post-1mb.lua
tests/test-http-post-1mb.lua
--[[ Copyright 2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local http = require('http') local string = require('string') local HOST = "127.0.0.1" local PORT = process.env.PORT or 10080 local server = nil local client = nil local a = string.rep('a', 1024) local data = string.rep(a, 1024) local MB = data:len() require('tap')(function(test) test('http-post-1mb', function(expect) server = http.createServer(function(request, response) p('server:onConnection') local postBuffer = '' assert(request.method == "POST") assert(request.url == "/foo") assert(request.headers.bar == "cats") request:on('data', function(chunk) postBuffer = postBuffer .. chunk end) request:on('end', expect(function() p('server:onEnd') assert(postBuffer == data) response:write(data) response:finish() end)) end) server:listen(PORT, HOST, function() local headers = { {'bar', 'cats'}, {'Content-Length', MB}, {'Transfer-Encoding', 'chunked'} } local req = http.request({ host = HOST, port = PORT, method = 'POST', path = "/foo", headers = headers }, function(response) assert(response.statusCode == 200) assert(response.httpVersion == '1.1') response:on('data', expect(function(data) assert(data:len() == MB) p('All data received') end)) response:on('end', expect(function(data) p('Response ended') server:close() end)) end) req:write(data) req:done() end) end) end)
--[[ Copyright 2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local http = require('http') local string = require('string') local HOST = "127.0.0.1" local PORT = process.env.PORT or 10080 local server = nil local client = nil local a = string.rep('a', 1024) local data = string.rep(a, 1024) local MB = data:len() require('tap')(function(test) test('http-post-1mb', function(expect) server = http.createServer(function(request, response) p('server:onConnection') local postBuffer = '' assert(request.method == "POST") assert(request.url == "/foo") assert(request.headers.bar == "cats") request:on('data', function(chunk) postBuffer = postBuffer .. chunk end) request:on('end', expect(function() p('server:onEnd') assert(postBuffer == data) response:write(data) response:finish() end)) end) server:listen(PORT, HOST, function() local headers = { {'bar', 'cats'}, {'Content-Length', MB}, {'Transfer-Encoding', 'chunked'} } local body = {} local req = http.request({ host = HOST, port = PORT, method = 'POST', path = "/foo", headers = headers }, function(response) assert(response.statusCode == 200) assert(response.httpVersion == '1.1') response:on('data', expect(function(data) body[#body+1] = data p('chunk received',data:len()) end)) response:on('end', expect(function(data) data = table.concat(body) assert(data:len() == MB) p('Response ended') server:close() end)) end) req:write(data) req:done() end) end) end)
fix tests/test-http-post-1mb.lua to pass
fix tests/test-http-post-1mb.lua to pass
Lua
apache-2.0
bsn069/luvit,kaustavha/luvit,zhaozg/luvit,luvit/luvit,kaustavha/luvit,luvit/luvit,kaustavha/luvit,bsn069/luvit,bsn069/luvit,zhaozg/luvit
120f7b02529f25491e97ae3b849a9fdbab6f6872
frontend/ui/reader/readerview.lua
frontend/ui/reader/readerview.lua
ReaderView = WidgetContainer:new{ document = nil, state = { page = 0, pos = 0, zoom = 1.0, rotation = 0, offset = {}, bbox = nil, }, outer_page_color = 7, -- DjVu page rendering mode (used in djvu.c:drawPage()) render_mode = 0, -- default to COLOR -- Crengine view mode view_mode = "page", -- default to page mode -- visible area within current viewing page visible_area = Geom:new{x = 0, y = 0}, -- dimen for current viewing page page_area = Geom:new{}, -- dimen for area to dim dim_area = Geom:new{w = 0, h = 0}, } function ReaderView:paintTo(bb, x, y) DEBUG("painting", self.visible_area, "to", x, y) local inner_offset = Geom:new{x = 0, y = 0} -- draw surrounding space, if any if self.ui.dimen.h > self.visible_area.h then inner_offset.y = (self.ui.dimen.h - self.visible_area.h) / 2 bb:paintRect(x, y, self.ui.dimen.w, inner_offset.y, self.outer_page_color) bb:paintRect(x, y + self.ui.dimen.h - inner_offset.y - 1, self.ui.dimen.w, inner_offset.y + 1, self.outer_page_color) end if self.ui.dimen.w > self.visible_area.w then inner_offset.x = (self.ui.dimen.w - self.visible_area.w) / 2 bb:paintRect(x, y, inner_offset.x, self.ui.dimen.h, self.outer_page_color) bb:paintRect(x + self.ui.dimen.w - inner_offset.x - 1, y, inner_offset.x + 1, self.ui.dimen.h, self.outer_page_color) end -- draw content if self.ui.document.info.has_pages then self.ui.document:drawPage( bb, x + inner_offset.x, y + inner_offset.y, self.visible_area, self.state.page, self.state.zoom, self.state.rotation, self.render_mode) else if self.view_mode == "page" then self.ui.document:drawCurrentViewByPage( bb, x + inner_offset.x, y + inner_offset.y, self.visible_area, self.state.page) else self.ui.document:drawCurrentViewByPos( bb, x + inner_offset.x, y + inner_offset.y, self.visible_area, self.state.pos) end end -- dim last read area if self.document.view_mode ~= "page" and self.dim_area.w ~= 0 and self.dim_area.h ~= 0 then bb:dimRect( self.dim_area.x, self.dim_area.y, self.dim_area.w, self.dim_area.h ) end end --[[ This method is supposed to be only used by ReaderPaging --]] function ReaderView:recalculate() local page_size = nil if self.ui.document.info.has_pages then if not self.bbox then self.page_area = self.ui.document:getPageDimensions( self.state.page, self.state.zoom, self.state.rotation) else self.page_area = self.ui.document:getUsedBBoxDimensions( self.state.page, self.state.zoom, self.state.rotation) end -- starts from left top of page_area self.visible_area.x = self.page_area.x self.visible_area.y = self.page_area.y -- reset our size self.visible_area:setSizeTo(self.dimen) -- and recalculate it according to page size self.visible_area:offsetWithin(self.page_area, 0, 0) -- clear dim area self.dim_area.w = 0 self.dim_area.h = 0 self.ui:handleEvent( Event:new("ViewRecalculate", self.visible_area, self.page_area)) else self.visible_area:setSizeTo(self.dimen) end -- flag a repaint so self:paintTo will be called UIManager:setDirty(self.dialog) end function ReaderView:PanningUpdate(dx, dy) DEBUG("pan by", dx, dy) local old = self.visible_area:copy() self.visible_area:offsetWithin(self.page_area, dx, dy) if self.visible_area ~= old then -- flag a repaint UIManager:setDirty(self.dialog) DEBUG("on pan: page_area", self.page_area) DEBUG("on pan: visible_area", self.visible_area) end return true end function ReaderView:onSetDimensions(dimensions) self.dimen = dimensions -- recalculate view self:recalculate() end function ReaderView:onReadSettings(config) self.render_mode = config:readSetting("render_mode") or 0 end function ReaderView:onPageUpdate(new_page_no) self.state.page = new_page_no self:recalculate() end function ReaderView:onPosUpdate(new_pos) self.state.pos = new_pos self:recalculate() end function ReaderView:onZoomUpdate(zoom) self.state.zoom = zoom self:recalculate() end function ReaderView:onBBoxUpdate(bbox) self.bbox = bbox end function ReaderView:onRotationUpdate(rotation) self.state.rotation = rotation self:recalculate() end function ReaderView:onCloseDocument() self.ui.doc_settings:saveSetting("render_mode", self.render_mode) end
ReaderView = WidgetContainer:new{ document = nil, state = { page = 0, pos = 0, zoom = 1.0, rotation = 0, offset = {}, bbox = nil, }, outer_page_color = 7, -- DjVu page rendering mode (used in djvu.c:drawPage()) render_mode = 0, -- default to COLOR -- Crengine view mode view_mode = "page", -- default to page mode -- visible area within current viewing page visible_area = Geom:new{x = 0, y = 0}, -- dimen for current viewing page page_area = Geom:new{}, -- dimen for area to dim dim_area = Geom:new{w = 0, h = 0}, } function ReaderView:paintTo(bb, x, y) DEBUG("painting", self.visible_area, "to", x, y) local inner_offset = Geom:new{x = 0, y = 0} -- draw surrounding space, if any if self.ui.dimen.h > self.visible_area.h then inner_offset.y = (self.ui.dimen.h - self.visible_area.h) / 2 bb:paintRect(x, y, self.ui.dimen.w, inner_offset.y, self.outer_page_color) bb:paintRect(x, y + self.ui.dimen.h - inner_offset.y - 1, self.ui.dimen.w, inner_offset.y + 1, self.outer_page_color) end if self.ui.dimen.w > self.visible_area.w then inner_offset.x = (self.ui.dimen.w - self.visible_area.w) / 2 bb:paintRect(x, y, inner_offset.x, self.ui.dimen.h, self.outer_page_color) bb:paintRect(x + self.ui.dimen.w - inner_offset.x - 1, y, inner_offset.x + 1, self.ui.dimen.h, self.outer_page_color) end -- draw content if self.ui.document.info.has_pages then self.ui.document:drawPage( bb, x + inner_offset.x, y + inner_offset.y, self.visible_area, self.state.page, self.state.zoom, self.state.rotation, self.render_mode) else if self.view_mode == "page" then self.ui.document:drawCurrentViewByPage( bb, x + inner_offset.x, y + inner_offset.y, self.visible_area, self.state.page) else self.ui.document:drawCurrentViewByPos( bb, x + inner_offset.x, y + inner_offset.y, self.visible_area, self.state.pos) end end -- dim last read area if self.document.view_mode ~= "page" and self.dim_area.w ~= 0 and self.dim_area.h ~= 0 then bb:dimRect( self.dim_area.x, self.dim_area.y, self.dim_area.w, self.dim_area.h ) end end --[[ This method is supposed to be only used by ReaderPaging --]] function ReaderView:recalculate() local page_size = nil if self.ui.document.info.has_pages then if not self.bbox then self.page_area = self.ui.document:getPageDimensions( self.state.page, self.state.zoom, self.state.rotation) else self.page_area = self.ui.document:getUsedBBoxDimensions( self.state.page, self.state.zoom, self.state.rotation) end -- starts from left top of page_area self.visible_area.x = self.page_area.x self.visible_area.y = self.page_area.y -- reset our size self.visible_area:setSizeTo(self.dimen) -- and recalculate it according to page size self.visible_area:offsetWithin(self.page_area, 0, 0) -- clear dim area self.dim_area.w = 0 self.dim_area.h = 0 self.ui:handleEvent( Event:new("ViewRecalculate", self.visible_area, self.page_area)) else self.visible_area:setSizeTo(self.dimen) end -- flag a repaint so self:paintTo will be called UIManager:setDirty(self.dialog) end function ReaderView:PanningUpdate(dx, dy) DEBUG("pan by", dx, dy) local old = self.visible_area:copy() self.visible_area:offsetWithin(self.page_area, dx, dy) if self.visible_area ~= old then -- flag a repaint UIManager:setDirty(self.dialog) DEBUG("on pan: page_area", self.page_area) DEBUG("on pan: visible_area", self.visible_area) self.ui:handleEvent( Event:new("ViewRecalculate", self.visible_area, self.page_area)) end return true end function ReaderView:onSetDimensions(dimensions) self.dimen = dimensions -- recalculate view self:recalculate() end function ReaderView:onReadSettings(config) self.render_mode = config:readSetting("render_mode") or 0 end function ReaderView:onPageUpdate(new_page_no) self.state.page = new_page_no self:recalculate() end function ReaderView:onPosUpdate(new_pos) self.state.pos = new_pos self:recalculate() end function ReaderView:onZoomUpdate(zoom) self.state.zoom = zoom self:recalculate() end function ReaderView:onBBoxUpdate(bbox) self.bbox = bbox end function ReaderView:onRotationUpdate(rotation) self.state.rotation = rotation self:recalculate() end function ReaderView:onCloseDocument() self.ui.doc_settings:saveSetting("render_mode", self.render_mode) end
bug fix: signal ViewRecalculate event after panning
bug fix: signal ViewRecalculate event after panning This make sure ReaderPaging get correct visible_area when turnning to previous page.
Lua
agpl-3.0
apletnev/koreader-base,ashang/koreader,NiLuJe/koreader-base,frankyifei/koreader,houqp/koreader-base,noname007/koreader,Hzj-jie/koreader-base,Hzj-jie/koreader-base,Frenzie/koreader,apletnev/koreader-base,frankyifei/koreader-base,koreader/koreader-base,chihyang/koreader,apletnev/koreader-base,NiLuJe/koreader-base,NickSavage/koreader,Frenzie/koreader-base,Frenzie/koreader,NiLuJe/koreader,Hzj-jie/koreader-base,koreader/koreader-base,pazos/koreader,Hzj-jie/koreader-base,poire-z/koreader,frankyifei/koreader-base,houqp/koreader-base,mwoz123/koreader,houqp/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base,houqp/koreader-base,ashhher3/koreader,frankyifei/koreader-base,koreader/koreader,Hzj-jie/koreader,NiLuJe/koreader,robert00s/koreader,lgeek/koreader,houqp/koreader,apletnev/koreader,koreader/koreader-base,Markismus/koreader,koreader/koreader,chrox/koreader,mihailim/koreader,NiLuJe/koreader-base,Frenzie/koreader-base,koreader/koreader-base,frankyifei/koreader-base,poire-z/koreader,Frenzie/koreader-base,apletnev/koreader-base
a37ddb1b49896cb6d1ba7865b808a8bb6e977f3c
modules/title/sites/komplett.lua
modules/title/sites/komplett.lua
local simplehttp = require'simplehttp' local html2unicode = require'html' local trim = function(s) if(not s) then return end return (string.gsub(s, "^%s*(.-)%s*$", "%1")) end local handler = function(queue, info) local query = info.query local path = info.path if((query and query:match('sku=%d+')) or (path and path:match('/[^/]+/%d+'))) then simplehttp( info.url, function(data, url, response) local ins = function(out, fmt, ...) for i=1, select('#', ...) do local val = select(i, ...) if(type(val) == 'nil' or val == -1) then return end end table.insert( out, string.format(fmt, ...) ) end local out = {} local name = data:match('<h1 class="main%-header" itemprop="name">([^<]+)</h1>') local desc = data:match('<h3 class="secondary%-header" itemprop="description">([^<]+)</h3>') local price = data:match('<span itemprop="price"[^>]+>([^<]+)</span>') local storage = data:match('<span class="stock%-details">(.-)</span>') local bomb = data:match('<div class="bomb">.-<div class="value">([^<]+)</div>') ins(out, '\002%s\002: ', html2unicode(name)) if(desc) then ins(out, '%s ,', html2unicode(desc)) end if(price) then ins(out, '\002%s\002 ', trim(price)) end local extra = {} if(bomb) then bomb = trim(bomb) if(bomb:sub(1, 1) == '-') then bomb = bomb:sub(2) end ins(extra, '%s off', bomb) end if(storage) then storage = html2unicode(storage) storage = trim(storage:gsub('<%/?[%w:]+.-%/?>', '')) if(storage:sub(-1) == '.') then storage = storage:sub(1, -2) end ins(extra, '%s', storage) end if(#extra > 0) then ins(out, '(%s)', table.concat(extra, ', ')) end queue:done(table.concat(out, '')) end ) return true end end customHosts['komplett%.no'] = handler customHosts['komplett%.dk'] = handler customHosts['komplett%.se'] = handler customHosts['inwarehouse%.se'] = handler customHosts['mpx%.no'] = handler
local simplehttp = require'simplehttp' local html2unicode = require'html' local trim = function(s) if(not s) then return end return (string.gsub(s, "^%s*(.-)%s*$", "%1")) end local handler = function(queue, info) local query = info.query local path = info.path if((query and query:match('sku=%d+')) or (path and path:match('/[^/]+/%d+'))) then simplehttp( info.url, function(data, url, response) local ins = function(out, fmt, ...) for i=1, select('#', ...) do local val = select(i, ...) if(type(val) == 'nil' or val == -1) then return end end table.insert( out, string.format(fmt, ...) ) end local out = {} local name = data:match('<h1 class="product%-main%-info%-webtext1" itemprop="name">([^<]+)</h1>') local desc = data:match('<h2 class="product%-main%-info%-webtext2" itemprop="description">([^<]+)</h2>') local price = data:match('<span class="product%-price%-now" itemprop=price content=.->([^<]+)</span>') local storage = data:match('<span class="stockstatus%-stock%-details">([^<]+)</span>') local bomb = data:match('<span.-class="prodpage-discount-label".->([^<]+)</span>') ins(out, '\002%s\002: ', html2unicode(trim(name))) if(desc) then ins(out, '%s ,', html2unicode(trim(desc))) end if(price) then ins(out, '\002%s\002 ', trim(price)) end local extra = {} if(bomb) then bomb = trim(bomb) if(bomb:sub(1, 1) == '-') then bomb = bomb:sub(2) end ins(extra, '%s off', bomb) end if(storage) then storage = html2unicode(storage) storage = trim(storage:gsub('<%/?[%w:]+.-%/?>', '')) if(storage:sub(-1) == '.') then storage = storage:sub(1, -2) end ins(extra, '%s', storage) end if(#extra > 0) then ins(out, '(%s)', table.concat(extra, ', ')) end queue:done(table.concat(out, '')) end ) return true end end customHosts['komplett%.no'] = handler customHosts['komplett%.dk'] = handler customHosts['komplett%.se'] = handler customHosts['inwarehouse%.se'] = handler customHosts['mpx%.no'] = handler
title/komplett: fix site plugin
title/komplett: fix site plugin
Lua
mit
torhve/ivar2,torhve/ivar2,torhve/ivar2,haste/ivar2
115c0f92e26e67e8fb6054bc109a050cee527707
src/lua-factory/sources/grl-guardianvideos.lua
src/lua-factory/sources/grl-guardianvideos.lua
--[[ * Copyright (C) 2014 Bastien Nocera * * Contact: Bastien Nocera <hadess@hadess.net> * * This library 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; version 2.1 of * the License, or (at your option) any later version. * * This library 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] GUARDIANVIDEOS_URL = 'http://content.guardianapis.com/search?tag=video&page=%s&page-size=%s&show-fields=all' --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-guardianvideos-lua", name = "The Guardian Videos", description = "A source for browsing videos from the Guardian", supported_keys = { "id", "thumbnail", "title", "url" }, supported_media = 'video', auto_split_threshold = 50, tags = { 'news' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) local count = grl.get_options("count") local skip = grl.get_options("skip") local urls = {} local page = skip / count + 1 if page > math.floor(page) then local url = string.format(GUARDIANVIDEOS_URL, math.floor(page), count) grl.debug ("Fetching URL #1: " .. url .. " (count: " .. count .. " skip: " .. skip .. ")") table.insert(urls, url) url = string.format(GUARDIANVIDEOS_URL, math.floor(page) + 1, count) grl.debug ("Fetching URL #2: " .. url .. " (count: " .. count .. " skip: " .. skip .. ")") table.insert(urls, url) else local url = string.format(GUARDIANVIDEOS_URL, page, count) grl.debug ("Fetching URL: " .. url .. " (count: " .. count .. " skip: " .. skip .. ")") table.insert(urls, url) end grl.fetch(urls, "guardianvideos_fetch_cb") end ------------------------ -- Callback functions -- ------------------------ -- return all the media found function guardianvideos_fetch_cb(results) local count = grl.get_options("count") for i, result in ipairs(results) do local json = {} json = grl.lua.json.string_to_table(result) if not json or json.stat == "fail" or not json.response or not json.response.results then grl.callback() return end for index, item in pairs(json.response.results) do local media = create_media(item) count = count - 1 grl.callback(media, count) end -- Bail out if we've given enough items if count == 0 then return end end end ------------- -- Helpers -- ------------- function create_media(item) local media = {} media.type = "video" media.id = item.id media.url = item.webUrl media.title = item.webTitle media.thumbnail = item.fields.thumbnail return media end
--[[ * Copyright (C) 2014 Bastien Nocera * * Contact: Bastien Nocera <hadess@hadess.net> * * This library 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; version 2.1 of * the License, or (at your option) any later version. * * This library 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] -- Test the API at: -- http://explorer.content.guardianapis.com/search?api-key=rppwmmu3mfqj6gkbs8kcjg23&show-fields=all&page-size=50&tag=type/video API_KEY = 'rppwmmu3mfqj6gkbs8kcjg23' GUARDIANVIDEOS_URL = 'http://content.guardianapis.com/search?tag=type/video&page=%s&page-size=%s&show-fields=all&api-key=%s' --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-guardianvideos-lua", name = "The Guardian Videos", description = "A source for browsing videos from the Guardian", supported_keys = { "id", "thumbnail", "title", "url" }, supported_media = 'video', auto_split_threshold = 50, tags = { 'news' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) local count = grl.get_options("count") local skip = grl.get_options("skip") local urls = {} local page = skip / count + 1 if page > math.floor(page) then local url = string.format(GUARDIANVIDEOS_URL, math.floor(page), count, API_KEY) grl.debug ("Fetching URL #1: " .. url .. " (count: " .. count .. " skip: " .. skip .. ")") table.insert(urls, url) url = string.format(GUARDIANVIDEOS_URL, math.floor(page) + 1, count, API_KEY) grl.debug ("Fetching URL #2: " .. url .. " (count: " .. count .. " skip: " .. skip .. ")") table.insert(urls, url) else local url = string.format(GUARDIANVIDEOS_URL, page, count, API_KEY) grl.debug ("Fetching URL: " .. url .. " (count: " .. count .. " skip: " .. skip .. ")") table.insert(urls, url) end grl.fetch(urls, "guardianvideos_fetch_cb") end ------------------------ -- Callback functions -- ------------------------ -- return all the media found function guardianvideos_fetch_cb(results) local count = grl.get_options("count") for i, result in ipairs(results) do local json = {} json = grl.lua.json.string_to_table(result) if not json or json.stat == "fail" or not json.response or not json.response.results then grl.callback() return end for index, item in pairs(json.response.results) do local media = create_media(item) count = count - 1 grl.callback(media, count) end -- Bail out if we've given enough items if count == 0 then return end end end ------------- -- Helpers -- ------------- function create_media(item) local media = {} media.type = "video" media.id = item.id media.url = item.webUrl media.title = item.webTitle media.thumbnail = item.fields.thumbnail return media end
guardianvideos: Update for new API
guardianvideos: Update for new API https://bugzilla.gnome.org/show_bug.cgi?id=737176
Lua
lgpl-2.1
MikePetullo/grilo-plugins,grilofw/grilo-plugins,GNOME/grilo-plugins,MikePetullo/grilo-plugins,jasuarez/grilo-plugins,jasuarez/grilo-plugins,GNOME/grilo-plugins,MathieuDuponchelle/grilo-plugins,grilofw/grilo-plugins,MikePetullo/grilo-plugins,MathieuDuponchelle/grilo-plugins,MathieuDuponchelle/grilo-plugins,MathieuDuponchelle/grilo-plugins
f7ecd723e64db34f59b627f6bf7e108046ec4f6f
mods/BeardLib-Editor/Classes/Map/Elements/lootbagelement.lua
mods/BeardLib-Editor/Classes/Map/Elements/lootbagelement.lua
EditorLootBag = EditorLootBag or class(MissionScriptEditor) EditorLootBag.USES_POINT_ORIENTATION = true function EditorLootBag:create_element() self.super.create_element(self) self._element.class = "ElementLootBag" self._element.values.spawn_dir = Vector3(0, 0, 1) self._element.values.push_multiplier = 0 self._element.values.carry_id = "none" self._element.values.from_respawn = false end function EditorLootBag:update(d, dt) local kb = Input:keyboard() local speed = 60 * dt if kb:down(Idstring("left")) then self._element.values.spawn_dir = self._element.values.spawn_dir:rotate_with(Rotation(speed, 0, 0)) end if kb:down(Idstring("right")) then self._element.values.spawn_dir = self._element.values.spawn_dir:rotate_with(Rotation(-speed, 0, 0)) end if kb:down(Idstring("up")) then self._element.values.spawn_dir = self._element.values.spawn_dir:rotate_with(Rotation(0, 0, speed)) end if kb:down(Idstring("down")) then self._element.values.spawn_dir = self._element.values.spawn_dir:rotate_with(Rotation(0, 0, -speed)) end local from = self._element.values.position local to = from + self._element.values.spawn_dir * 100000 local ray = World:raycast("ray", from, to) if ray and ray.unit then Application:draw_sphere(ray.position, 25, 1, 0, 0) Application:draw_arrow(self._element.values.position, self._element.values.position + self._element.values.spawn_dir * 50, 0.75, 0.75, 0.75, 0.1) end EditorLootBag.super.update(self, t, dt) end function EditorLootBag:_build_panel() self:_create_panel() self:NumberCtrl("push_multiplier", {floats = 1, min = 0, help = "Use this to add a velocity to a physic push on the spawned unit"}) self:ComboCtrl("carry_id", table.list_add({"none"}, tweak_data.carry:get_carry_ids()), {help = "Select a carry_id to be created."}) self:BooleanCtrl("from_respawn") self:Text("This element can spawn loot bags, control the spawn direction using your arrow keys") end EditorLootBagTrigger = EditorLootBagTrigger or class(MissionScriptEditor) function EditorLootBagTrigger:create_element() self.super.create_element(self) self._element.class = "ElementLootBagTrigger" self._element.values.elements = {} self._element.values.trigger_type = "load" end function EditorLootBagTrigger:_build_panel() self:_create_panel() self:BuildElementsManage("elements", nil, {"ElementLootBag"}) self:ComboCtrl("trigger_type", {"load", "spawn"}, {help = "Select a trigger type for the selected elements"}) self:Text("This element is a trigger to point_loot_bag element.") end
EditorLootBag = EditorLootBag or class(MissionScriptEditor) EditorLootBag.USES_POINT_ORIENTATION = true function EditorLootBag:create_element() self.super.create_element(self) self._element.class = "ElementLootBag" self._element.values.spawn_dir = Vector3(0, 0, 1) self._element.values.push_multiplier = 0 self._element.values.carry_id = "none" self._element.values.from_respawn = false end function EditorLootBag:update(d, dt) local kb = Input:keyboard() local speed = 60 * dt self._element.values.spawn_dir = self._element.values.spawn_dir or Vector3() if kb:down(Idstring("left")) then self._element.values.spawn_dir = self._element.values.spawn_dir:rotate_with(Rotation(speed, 0, 0)) end if kb:down(Idstring("right")) then self._element.values.spawn_dir = self._element.values.spawn_dir:rotate_with(Rotation(-speed, 0, 0)) end if kb:down(Idstring("up")) then self._element.values.spawn_dir = self._element.values.spawn_dir:rotate_with(Rotation(0, 0, speed)) end if kb:down(Idstring("down")) then self._element.values.spawn_dir = self._element.values.spawn_dir:rotate_with(Rotation(0, 0, -speed)) end local from = self._element.values.position local to = from + self._element.values.spawn_dir * 100000 local ray = World:raycast("ray", from, to) if ray and ray.unit then Application:draw_sphere(ray.position, 25, 1, 0, 0) Application:draw_arrow(self._element.values.position, self._element.values.position + self._element.values.spawn_dir * 50, 0.75, 0.75, 0.75, 0.1) end EditorLootBag.super.update(self, t, dt) end function EditorLootBag:_build_panel() self:_create_panel() self:NumberCtrl("push_multiplier", {floats = 1, min = 0, help = "Use this to add a velocity to a physic push on the spawned unit"}) self:ComboCtrl("carry_id", table.list_add({"none"}, tweak_data.carry:get_carry_ids()), {help = "Select a carry_id to be created."}) self:BooleanCtrl("from_respawn") self:Text("This element can spawn loot bags, control the spawn direction using your arrow keys") end EditorLootBagTrigger = EditorLootBagTrigger or class(MissionScriptEditor) function EditorLootBagTrigger:create_element() self.super.create_element(self) self._element.class = "ElementLootBagTrigger" self._element.values.elements = {} self._element.values.trigger_type = "load" end function EditorLootBagTrigger:_build_panel() self:_create_panel() self:BuildElementsManage("elements", nil, {"ElementLootBag"}) self:ComboCtrl("trigger_type", {"load", "spawn"}, {help = "Select a trigger type for the selected elements"}) self:Text("This element is a trigger to point_loot_bag element.") end
Fixed #206
Fixed #206
Lua
mit
simon-wh/PAYDAY-2-BeardLib-Editor
7a17e716f8776231c3e19f86e041366819cf8471
openwrt/package/linkmeter/luasrc/controller/linkmeter/lm.lua
openwrt/package/linkmeter/luasrc/controller/linkmeter/lm.lua
module("luci.controller.linkmeter.lm", package.seeall) function index() local root = node() root.target = call("rootredirect") local page = node("lm") page.target = template("linkmeter/index") page.order = 10 page.sysauth = { "anon", "root" } page.sysauth_authenticator = require "luci.controller.linkmeter.lm".lmauth local page = node("lm", "json") page.target = call("json") page.order = 20 local page = node("lm", "set") page.target = call("set") page.order = 30 page.sysauth = "root" local page = node("lm", "login") page.target = call("rootredirect") page.order = 20 page.sysauth = "root" end function lmauth(validator, accs, default) local user = "anon" local sess = luci.http.getcookie("sysauth") sess = sess and sess:match("^[a-f0-9]*$") local sdat = luci.sauth.read(sess) if sdat then sdat = loadstring(sdat) setfenv(sdat, {}) sdat = sdat() user = sdat.user end -- If the page requested does not allow anon acces and we're using the -- anon token, reutrn no session to get luci to prompt the user to escalate local needsRoot = not luci.util.contains(accs, "anon") if needsRoot and user == "anon" then return luci.dispatcher.authenticator.htmlauth(validator, accs, default) else return user, sess end end function rootredirect() luci.http.redirect(luci.dispatcher.build_url("lm/")) end function json() luci.http.prepare_content("text/plain") local f = io.open("/tmp/json", "rb") luci.ltn12.pump.all(luci.ltn12.source.file(f), luci.http.write) f:close() end function set() local dsp = require "luci.dispatcher" local http = require "luci.http" -- Make sure the user passed some values to set local vals = http.formvalue() local cnt = 0 for _ in pairs(vals) do cnt = cnt + 1 end if cnt == 0 then return dsp.error500("No values specified") end local uci = luci.model.uci.cursor() local device = uci:get("linkmeter", "daemon", "serial_device") local f = nixio.open(device, "w") if f == nil then return dsp.error500("Can not open serial device "..device) end 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 http.write("%s to %s\n" % {k,v}) f:write("/set?%s=%s\n" % {k,v}) end http.write("Done!") f:close() end
module("luci.controller.linkmeter.lm", package.seeall) function index() local root = node() root.target = call("rootredirect") local page = node("lm") page.target = template("linkmeter/index") page.order = 10 page.sysauth = { "anon", "root" } page.sysauth_authenticator = require "luci.controller.linkmeter.lm".lmauth local page = node("lm", "json") page.target = call("json") page.order = 20 local page = node("lm", "set") page.target = call("set") page.order = 30 page.sysauth = "root" local page = node("lm", "login") page.target = call("rootredirect") page.order = 20 page.sysauth = "root" end function lmauth(validator, accs, default) local user = "anon" local sess = luci.http.getcookie("sysauth") sess = sess and sess:match("^[a-f0-9]*$") local sdat = luci.sauth.read(sess) if sdat then sdat = loadstring(sdat) setfenv(sdat, {}) sdat = sdat() if sdat.token == luci.dispatcher.context.urltoken then user = sdat.user end end -- If the page requested does not allow anon acces and we're using the -- anon token, reutrn no session to get luci to prompt the user to escalate local needsRoot = not luci.util.contains(accs, "anon") if needsRoot and user == "anon" then return luci.dispatcher.authenticator.htmlauth(validator, accs, default) else return user, sess end end function rootredirect() luci.http.redirect(luci.dispatcher.build_url("lm/")) end function json() -- luci.http.prepare_content("application/json") luci.http.prepare_content("text/plain") local f = io.open("/tmp/json", "rb") luci.ltn12.pump.all(luci.ltn12.source.file(f), luci.http.write) f:close() end function set() local dsp = require "luci.dispatcher" local http = require "luci.http" -- Make sure the user passed some values to set local vals = http.formvalue() local cnt = 0 for _ in pairs(vals) do cnt = cnt + 1 end if cnt == 0 then return dsp.error500("No values specified") end local uci = luci.model.uci.cursor() local device = uci:get("linkmeter", "daemon", "serial_device") local f = nixio.open(device, "w") if f == nil then return dsp.error500("Can not open serial device "..device) end 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 http.write("%s to %s\n" % {k,v}) f:write("/set?%s=%s\n" % {k,v}) end http.write("Done!") f:close() end
[lm] Fix cross-site request forgery by using the url token
[lm] Fix cross-site request forgery by using the url token
Lua
mit
CapnBry/HeaterMeter,CapnBry/HeaterMeter,dwright134/HeaterMeter,dwright134/HeaterMeter,shmick/HeaterMeter,kdakers80/HeaterMeter,dwright134/HeaterMeter,shmick/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter,kdakers80/HeaterMeter,CapnBry/HeaterMeter,dwright134/HeaterMeter,dwright134/HeaterMeter,shmick/HeaterMeter,kdakers80/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,kdakers80/HeaterMeter,CapnBry/HeaterMeter,kdakers80/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,kdakers80/HeaterMeter
00e548062a89cc34da37470b3ebde46601abc181
src/game/StarterPlayer/StarterPlayerScripts/CameraScript.lua
src/game/StarterPlayer/StarterPlayerScripts/CameraScript.lua
-- ClassName: LocalScript local OFFSET = Vector3.new(-45, 45, 45) local FIELD_OF_VIEW = 25 local player = game.Players.LocalPlayer local camera = workspace.CurrentCamera local run = game:GetService("RunService") camera.FieldOfView = FIELD_OF_VIEW local function onRenderStep() local playerPosition = player.Character.Torso.Position local cameraPosition = playerPosition + OFFSET camera.CoordinateFrame = CFrame.new(cameraPosition, playerPosition) end run:BindToRenderStep("Camera", Enum.RenderPriority.Camera.Value, onRenderStep)
-- ClassName: LocalScript local OFFSET = Vector3.new(-45, 45, 45) local FIELD_OF_VIEW = 25 local player = game.Players.LocalPlayer local camera = workspace.CurrentCamera local run = game:GetService("RunService") camera.FieldOfView = FIELD_OF_VIEW local function lookAt(pos) local cameraPos = pos + OFFSET camera.CoordinateFrame = CFrame.new(cameraPos, pos) end local function onRenderStep() local character = player.Character local primaryPart = character.PrimaryPart if character and primaryPart then lookAt(primaryPart.Position) end end run:BindToRenderStep("Camera", Enum.RenderPriority.Camera.Value, onRenderStep)
Fix camera errors when the player dies
Fix camera errors when the player dies We didn't check to make sure that the character actually exists before continuing, so when the player drops into the void and their character is deleted, we got constant errors from RenderStepped. This fixes that.
Lua
mit
VoxelDavid/echo-ridge
1e68f15550c448f4c546b04ffd9deaeecdf6715d
mod_extauth/mod_extauth.lua
mod_extauth/mod_extauth.lua
local nodeprep = require "util.encodings".stringprep.nodeprep; local process = require "process"; local script_type = module:get_option("extauth_type"); assert(script_type == "ejabberd"); local command = module:get_option("extauth_command"); assert(type(command) == "string"); local host = module.host; assert(not host:find(":")); local proc; local function send_query(text) if not proc then proc = process.popen(command); end proc:write(text); proc:flush(); return proc:read(4); -- FIXME do properly end function do_query(kind, username, password) if not username then return nil, "not-acceptable"; end username = nodeprep(username); if not username then return nil, "jid-malformed"; end local query = (password and "%s:%s:%s:%s" or "%s:%s:%s"):format(kind, username, host, password); local len = #query if len > 1000 then return nil, "policy-violation"; end local lo = len % 256; local hi = (len - lo) / 256; query = string.char(hi, lo)..query; local response = send_query(query); if response == "\0\2\0\0" then return nil, "not-authorized"; elseif response == "\0\2\0\1" then return true; else proc = nil; -- TODO kill proc return nil, "internal-server-error"; end end local provider = { name = "extauth" }; function provider.test_password(username, password) return do_query("auth", username, password); end function provider.set_password(username, password) return do_query("setpass", username, password); end function provider.user_exists(username) return do_query("isuser", username); end function provider.get_password() return nil, "Passwords not available."; end function provider.create_user(username, password) return nil, "Account creation/modification not available."; end function provider.get_supported_methods() return {["PLAIN"] = true}; end local config = require "core.configmanager"; local usermanager = require "core.usermanager"; local jid_bare = require "util.jid".bare; function provider.is_admin(jid) local admins = config.get(host, "core", "admins"); if admins ~= config.get("*", "core", "admins") then if type(admins) == "table" then jid = jid_bare(jid); for _,admin in ipairs(admins) do if admin == jid then return true; end end elseif admins then log("error", "Option 'admins' for host '%s' is not a table", host); end end return usermanager.is_admin(jid); -- Test whether it's a global admin instead end module:add_item("auth-provider", provider);
-- -- NOTE: currently this uses lpc; when waqas fixes process, it can go back to that -- -- Prosody IM -- Copyright (C) 2010 Waqas Hussain -- Copyright (C) 2010 Jeff Mitchell -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local nodeprep = require "util.encodings".stringprep.nodeprep; --local process = require "process"; local lpc = require "lpc"; local config = require "core.configmanager"; local log = require "util.logger".init("usermanager"); local host = module.host; local script_type = config.get(host, "core", "extauth_type") or "generic"; assert(script_type == "ejabberd" or script_type == "generic"); local command = config.get(host, "core", "extauth_command") or ""; assert(type(command) == "string"); assert(not host:find(":")); local usermanager = require "core.usermanager"; local jid_bare = require "util.jid".bare; --local proc; local pid; local readfile; local writefile; local function send_query(text) -- if not proc then if not pid then log("debug", "EXTAUTH: Opening process"); -- proc = process.popen(command); pid, writefile, readfile = lpc.run(command); end -- if not proc then if not pid then log("debug", "EXTAUTH: Process failed to open"); return nil; end -- proc:write(text); -- proc:flush(); writefile:write(text); writefile:flush(); if script_type == "ejabberd" then -- return proc:read(4); -- FIXME do properly return readfile:read(4); -- FIXME do properly elseif script_type == "generic" then -- return proc:read(1); return readfile:read(); end end function do_query(kind, username, password) if not username then return nil, "not-acceptable"; end username = nodeprep(username); if not username then return nil, "jid-malformed"; end local query = (password and "%s:%s:%s:%s" or "%s:%s:%s"):format(kind, username, host, password); local len = #query if len > 1000 then return nil, "policy-violation"; end if script_type == "ejabberd" then local lo = len % 256; local hi = (len - lo) / 256; query = string.char(hi, lo)..query; end if script_type == "generic" then query = query..'\n'; end local response = send_query(query); if (script_type == "ejabberd" and response == "\0\2\0\0") or (script_type == "generic" and response == "0") then return nil, "not-authorized"; elseif (script_type == "ejabberd" and response == "\0\2\0\1") or (script_type == "generic" and response == "1") then return true; else log("debug", "EXTAUTH: Nonsense back"); --proc:close(); --proc = nil; return nil, "internal-server-error"; end end function new_extauth_provider(host) local provider = { name = "extauth" }; function provider.test_password(username, password) return do_query("auth", username, password); end function provider.set_password(username, password) return do_query("setpass", username, password); end function provider.user_exists(username) return do_query("isuser", username); end function provider.create_user(username, password) return nil, "Account creation/modification not available."; end function provider.get_supported_methods() return {["PLAIN"] = true}; end function provider.is_admin(jid) local admins = config.get(host, "core", "admins"); if admins ~= config.get("*", "core", "admins") then if type(admins) == "table" then jid = jid_bare(jid); for _,admin in ipairs(admins) do if admin == jid then return true; end end elseif admins then log("error", "Option 'admins' for host '%s' is not a table", host); end end return usermanager.is_admin(jid); -- Test whether it's a global admin instead end return provider; end module:add_item("auth-provider", new_extauth_provider(module.host));
Add "generic" script support to mod_extauth, as well as lpc support until waqas fixes process
Add "generic" script support to mod_extauth, as well as lpc support until waqas fixes process
Lua
mit
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
f025436a162776c2fbf04bdbd9c41ab310d388b6
Quadtastic/Exporters.lua
Quadtastic/Exporters.lua
local current_folder = ... and (...):match '(.-%.?)[^%.]+$' or '' local common = require(current_folder .. ".common") local exporters = {} -- Creates the empty exporters directory and copies the Readme file to it. function exporters.init(dirname) if not love.filesystem.exists(dirname) then love.filesystem.createDirectory(dirname) end -- Copy the template to the exporters directory local template_content = love.filesystem.read("res/exporter-template.lua") assert(template_content) local success = love.filesystem.write(dirname .. "/exporter-template.lua", template_content) assert(success) end -- Checks whether the given module conforms to the requirements of an exporter. -- That is, the module needs to define the mandatory functions and fields. function exporters.is_exporter(module) if not module.name then return false, "Module misses name attribute." elseif not module.ext then return false, "Module misses extension attribute." elseif not module.export then return false, "Module misses export function." else return true end end -- Scans through the files in the exporters directory and returns a list with -- the found exporters. function exporters.list(dirname) local found_exporters = {} local num_found = 0 if love.filesystem.exists(dirname) then local files = love.filesystem.getDirectoryItems(dirname) for _, file in ipairs(files) do local filename, extension = common.split_extension(file) if extension == "lua" then -- try to load the exporter local load_success, more = pcall(love.filesystem.load, dirname .. "/" .. file) if load_success then -- try to run the loaded chunk local run_success, result = pcall(more) if run_success then local is_exporter, reason = exporters.is_exporter(result) if is_exporter then -- Check for naming conflicts if found_exporters[result.name] then print(string.format("Exporter in %s declares a name (%s) that already exists.", file, result.name)) else --if has no name conflict found_exporters[result.name] = result num_found = num_found + 1 end else print(string.format("Module in file %s is not an exporter: %s", file, reason)) end -- if is exporter else print("Exporter could not be executed: " .. result) end -- if can run else print("Could not load exporter in file " .. file ..": " .. more) end -- if can load end -- if has .lua extension end -- for file in dir end -- if is dir return found_exporters, num_found end return exporters
local current_folder = ... and (...):match '(.-%.?)[^%.]+$' or '' local common = require(current_folder .. ".common") local exporters = {} -- Creates the empty exporters directory and copies the Readme file to it. function exporters.init(dirname) if not love.filesystem.exists(dirname) then love.filesystem.createDirectory(dirname) end -- Copy the template to the exporters directory local template_content = love.filesystem.read("res/exporter-template.lua") assert(template_content) local success = love.filesystem.write(dirname .. "/exporter-template.lua", template_content) assert(success) end -- Checks whether the given module conforms to the requirements of an exporter. -- That is, the module needs to define the mandatory functions and fields. function exporters.is_exporter(module) if not module or type(module) ~= "table" then return false, "No module returned." elseif not module.name then return false, "Module misses name attribute." elseif not module.ext then return false, "Module misses extension attribute." elseif not module.export then return false, "Module misses export function." else return true end end -- Scans through the files in the exporters directory and returns a list with -- the found exporters. function exporters.list(dirname) local found_exporters = {} local num_found = 0 if love.filesystem.exists(dirname) then local files = love.filesystem.getDirectoryItems(dirname) for _, file in ipairs(files) do local filename, extension = common.split_extension(file) if extension == "lua" then -- try to load the exporter local load_success, more = pcall(love.filesystem.load, dirname .. "/" .. file) if load_success then -- try to run the loaded chunk local run_success, result = pcall(more) if run_success then local is_exporter, reason = exporters.is_exporter(result) if is_exporter then -- Check for naming conflicts if found_exporters[result.name] then print(string.format("Exporter in %s declares a name (%s) that already exists.", file, result.name)) else --if has no name conflict found_exporters[result.name] = result num_found = num_found + 1 end else print(string.format("Module in file %s is not an exporter: %s", file, reason)) end -- if is exporter else print("Exporter could not be executed: " .. result) end -- if can run else print("Could not load exporter in file " .. file ..": " .. more) end -- if can load end -- if has .lua extension end -- for file in dir end -- if is dir return found_exporters, num_found end return exporters
Fix error that would fail to handle lua files that return nothing
Fix error that would fail to handle lua files that return nothing
Lua
mit
25A0/Quadtastic,25A0/Quadtastic
c01c33bfb1d850188f6d90cd63372202cb0c7c54
Modules/Events/Promise.lua
Modules/Events/Promise.lua
--- Promises, but without error handling as this screws with stack traces, using Roblox signals -- @classmod Promise -- See: https://promisesaplus.com/ local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local Maid = require("Maid") local function _isSignal(value) if typeof(value) == "RBXScriptSignal" then return true elseif type(value) == "table" and type(value.Connect) == "function" then return true end return false end local function isPromise(value) if type(value) == "table" and value.ClassName == "Promise" then return true end return false end local Promise = {} Promise.ClassName = "Promise" Promise.__index = Promise Promise.CatchErrors = false -- A+ compliance if true Promise.IsPromise = isPromise --- Construct a new promise -- @constructor Promise.new() -- @param value, default nil -- @treturn Promise function Promise.new(value) local self = setmetatable({}, Promise) self._pendingMaid = Maid.new() self:_promisify(value) return self end function Promise.resolved(...) return Promise.new():Resolve(...) end function Promise.rejected(...) return Promise.new():Reject(...) end --- Returns whether or not the promise is pending -- @treturn bool True if pending, false otherwise function Promise:IsPending() return self._pendingMaid ~= nil end function Promise:IsFulfilled() return self._fulfilled ~= nil end function Promise:IsRejected() return self._rejected ~= nil end --- Yield until the promise is complete function Promise:Wait() if self._fulfilled then return unpack(self._fulfilled) elseif self._rejected then return unpack(self._rejected) else local result local bindable = Instance.new("BindableEvent") self._pendingMaid:GiveTask(bindable) self:Then(function(...) result = {...} bindable:Fire(true) end, function(...) result = {...} bindable:Fire(false) end) local ok = bindable.Event:Wait() bindable:Destroy() if not ok then error(tostring(result[1]), 2) end return unpack(result) end end --- -- Resolves a promise -- @return self function Promise:Resolve(...) local valueLength = select("#", ...) -- Treat tuples as an array under A+ compliance if valueLength > 1 then self:Fulfill(...) return self end local value = ... if self == value then self:Reject("TypeError: Resolved to self") return self end if isPromise(value) then value:Then(function(...) self:Fulfill(...) end, function(...) self:Reject(...) end) return self end -- Thenable like objects if type(value) == "table" and type(value.Then) == "function" then value:Then(self:_getResolveReject()) return self end self:Fulfill(value) return self end --- Fulfills the promise with the value -- @param ... Params to fulfill with -- @return self function Promise:Fulfill(...) if not self:IsPending() then return end self._fulfilled = {...} self:_endPending() return self end --- Rejects the promise with the value given -- @param ... Params to reject with -- @return self function Promise:Reject(...) if not self:IsPending() then return end self._rejected = {...} self:_endPending() return self end --- Handlers when promise is fulfilled/rejected. It takes up to two arguments, callback functions -- for the success and failure cases of the Promise -- @tparam[opt=nil] function onFulfilled Called when fulfilled with parameters -- @tparam[opt=nil] function onRejected Called when rejected with parameters -- @treturn Promise function Promise:Then(onFulfilled, onRejected) local returnPromise = Promise.new() if self._pendingMaid then self._pendingMaid:GiveTask(function() self:_executeThen(returnPromise, onFulfilled, onRejected) end) else self:_executeThen(returnPromise, onFulfilled, onRejected) end return returnPromise end function Promise:Finally(func) return self:Then(func, func) end --- Catch errors from the promise -- @treturn Promise function Promise:Catch(func) return self:Then(nil, func) end --- Rejects the current promise. -- Utility left for Maid task -- @treturn nil function Promise:Destroy() self:Reject() end --- Modifies values into promises -- @local function Promise:_promisify(value) if type(value) == "function" then self:_promisfyYieldingFunction(value) elseif _isSignal(value) then self:_promisfySignal(value) end end function Promise:_promisfySignal(signal) if not self._pendingMaid then return end self._pendingMaid:GiveTask(signal:Connect(function(...) self:Fulfill(...) end)) return end function Promise:_promisfyYieldingFunction(yieldingFunction) if not self._pendingMaid then return end local maid = Maid.new() -- Hack to spawn new thread fast local bindable = Instance.new("BindableEvent") maid:GiveTask(bindable) maid:GiveTask(bindable.Event:Connect(function() maid:DoCleaning() if self.CatchErrors then local resultList = self:_executeFunc(self, yieldingFunction, {self:_getResolveReject()}) if self:IsPending() then self:Resolve(unpack(resultList)) end else self:Resolve(yieldingFunction(self:_getResolveReject())) end end)) self._pendingMaid:GiveTask(maid) bindable:Fire() end function Promise:_getResolveReject() local called = false local function resolvePromise(...) if called then return end called = true self:Resolve(...) end local function rejectPromise(...) if called then return end called = true self:Reject(...) end return resolvePromise, rejectPromise end function Promise:_executeFunc(returnPromise, func, args) if not self.CatchErrors then return {func(unpack(args))} end local resultList local success, err = pcall(function() resultList = {func(unpack())} end) if not success then returnPromise:Reject(err) end return resultList end function Promise:_executeThen(returnPromise, onFulfilled, onRejected) local resultList if self._fulfilled then if type(onFulfilled) ~= "function" then return returnPromise:Fulfill(unpack(self._fulfilled)) end resultList = self:_executeFunc(returnPromise, onFulfilled, self._fulfilled) elseif self._rejected then if type(onRejected) ~= "function" then return returnPromise:Reject(unpack(self._rejected)) end resultList = self:_executeFunc(returnPromise, onRejected, self._rejected) else error("Internal error, cannot execute while pending") end if resultList and #resultList > 0 then returnPromise:Resolve(unpack(resultList)) end end function Promise:_endPending() local maid = self._pendingMaid self._pendingMaid = nil maid:DoCleaning() end return Promise
--- Promises, but without error handling as this screws with stack traces, using Roblox signals -- @classmod Promise -- See: https://promisesaplus.com/ local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local Maid = require("Maid") local function _isSignal(value) if typeof(value) == "RBXScriptSignal" then return true elseif type(value) == "table" and type(value.Connect) == "function" then return true end return false end local function isPromise(value) if type(value) == "table" and value.ClassName == "Promise" then return true end return false end local Promise = {} Promise.ClassName = "Promise" Promise.__index = Promise Promise.CatchErrors = false -- A+ compliance if true Promise.IsPromise = isPromise --- Construct a new promise -- @constructor Promise.new() -- @param value, default nil -- @treturn Promise function Promise.new(value) local self = setmetatable({}, Promise) self._pendingMaid = Maid.new() self:_promisify(value) return self end function Promise.resolved(...) return Promise.new():Resolve(...) end function Promise.rejected(...) return Promise.new():Reject(...) end --- Returns whether or not the promise is pending -- @treturn bool True if pending, false otherwise function Promise:IsPending() return self._pendingMaid ~= nil end function Promise:IsFulfilled() return self._fulfilled ~= nil end function Promise:IsRejected() return self._rejected ~= nil end --- Yield until the promise is complete function Promise:Wait() if self._fulfilled then return unpack(self._fulfilled) elseif self._rejected then return unpack(self._rejected) else local result local bindable = Instance.new("BindableEvent") self:Then(function(...) result = {...} bindable:Fire(true) end, function(...) result = {...} bindable:Fire(false) end) local ok = bindable.Event:Wait() bindable:Destroy() if not ok then error(tostring(result[1]), 2) end return unpack(result) end end --- -- Resolves a promise -- @return self function Promise:Resolve(...) local valueLength = select("#", ...) -- Treat tuples as an array under A+ compliance if valueLength > 1 then self:Fulfill(...) return self end local value = ... if self == value then self:Reject("TypeError: Resolved to self") return self end if isPromise(value) then value:Then(function(...) self:Fulfill(...) end, function(...) self:Reject(...) end) return self end -- Thenable like objects if type(value) == "table" and type(value.Then) == "function" then value:Then(self:_getResolveReject()) return self end self:Fulfill(value) return self end --- Fulfills the promise with the value -- @param ... Params to fulfill with -- @return self function Promise:Fulfill(...) if not self:IsPending() then return end self._fulfilled = {...} self:_endPending() return self end --- Rejects the promise with the value given -- @param ... Params to reject with -- @return self function Promise:Reject(...) if not self:IsPending() then return end self._rejected = {...} self:_endPending() return self end --- Handlers when promise is fulfilled/rejected. It takes up to two arguments, callback functions -- for the success and failure cases of the Promise -- @tparam[opt=nil] function onFulfilled Called when fulfilled with parameters -- @tparam[opt=nil] function onRejected Called when rejected with parameters -- @treturn Promise function Promise:Then(onFulfilled, onRejected) local returnPromise = Promise.new() if self._pendingMaid then self._pendingMaid:GiveTask(function() self:_executeThen(returnPromise, onFulfilled, onRejected) end) else self:_executeThen(returnPromise, onFulfilled, onRejected) end return returnPromise end function Promise:Finally(func) return self:Then(func, func) end --- Catch errors from the promise -- @treturn Promise function Promise:Catch(func) return self:Then(nil, func) end --- Rejects the current promise. -- Utility left for Maid task -- @treturn nil function Promise:Destroy() self:Reject() end --- Modifies values into promises -- @local function Promise:_promisify(value) if type(value) == "function" then self:_promisfyYieldingFunction(value) elseif _isSignal(value) then self:_promisfySignal(value) end end function Promise:_promisfySignal(signal) if not self._pendingMaid then return end self._pendingMaid:GiveTask(signal:Connect(function(...) self:Fulfill(...) end)) return end function Promise:_promisfyYieldingFunction(yieldingFunction) if not self._pendingMaid then return end local maid = Maid.new() -- Hack to spawn new thread fast local bindable = Instance.new("BindableEvent") maid:GiveTask(bindable) maid:GiveTask(bindable.Event:Connect(function() maid:DoCleaning() if self.CatchErrors then local resultList = self:_executeFunc(self, yieldingFunction, {self:_getResolveReject()}) if self:IsPending() then self:Resolve(unpack(resultList)) end else self:Resolve(yieldingFunction(self:_getResolveReject())) end end)) self._pendingMaid:GiveTask(maid) bindable:Fire() end function Promise:_getResolveReject() local called = false local function resolvePromise(...) if called then return end called = true self:Resolve(...) end local function rejectPromise(...) if called then return end called = true self:Reject(...) end return resolvePromise, rejectPromise end function Promise:_executeFunc(returnPromise, func, args) if not self.CatchErrors then return {func(unpack(args))} end local resultList local success, err = pcall(function() resultList = {func(unpack())} end) if not success then returnPromise:Reject(err) end return resultList end function Promise:_executeThen(returnPromise, onFulfilled, onRejected) local resultList if self._fulfilled then if type(onFulfilled) ~= "function" then return returnPromise:Fulfill(unpack(self._fulfilled)) end resultList = self:_executeFunc(returnPromise, onFulfilled, self._fulfilled) elseif self._rejected then if type(onRejected) ~= "function" then return returnPromise:Reject(unpack(self._rejected)) end resultList = self:_executeFunc(returnPromise, onRejected, self._rejected) else error("Internal error, cannot execute while pending") end if resultList and #resultList > 0 then returnPromise:Resolve(unpack(resultList)) end end function Promise:_endPending() local maid = self._pendingMaid self._pendingMaid = nil maid:DoCleaning() end return Promise
Fix promise:Wait() dropping threads
Fix promise:Wait() dropping threads
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
38018c1347bef0ec6bff1b59ea1054eb27a012f5
src/plugins/lua/rbl.lua
src/plugins/lua/rbl.lua
-- Configuration: -- rbl { -- default_ipv4 = true; -- default_ipv6 = false; -- default_received = true; -- default_from = false; -- rbls { -- xbl { -- rbl = "xbl.spamhaus.org"; -- symbol = "RBL_SPAMHAUSXBL"; -- ipv4 = true; -- ipv6 = false; -- } -- } -- } local rbls = {} function revipv6(ip) local c = 0 local i = 1 local t = {} for o in string.gmatch(ip, "%p-%x+%p-") do o = string.gsub(o, ":", "") while(#o < 4) do o = "0" .. o end t[i] = o i = i+1 end if #t < 8 then for i=1,8 do if(t[i] == nil) then c = c+1 end end for i=(8-c),#t do t[i+c] = t[i] t[i] = "0000" end for i=1,8 do if(t[i] == nil) then t[i] = "0000" end end end x=table.concat(t,"") x=string.reverse(x) rbl_str = "" for i in string.gmatch(x, "%x") do rbl_str = rbl_str .. i .. "." end return rbl_str end function dns_cb(task, to_resolve, results, err, sym) if results then task:insert_result(sym, 1) end end function rbl_cb (task) local rip = task:get_from_ip() if(rip ~= nil) then if not string.match(rip, ":") then local _,_,o1,o2,o3,o4 = string.find(rip, '^(%d+)%.(%d+)%.(%d+)%.(%d+)$') for _,rbl in pairs(rbls) do if(rbl['ipv4'] and rbl['from']) then rbl_str = o4 .. '.' .. o3 .. '.' .. o2 .. '.' .. o1 .. '.' .. rbl['rbl'] task:resolve_dns_a(rbl_str, 'dns_cb', rbl['symbol']) end end else for _,rbl in pairs(rbls) do if(rbl['ipv6'] and rbl['from']) then rbl_str = revipv6(rip) .. rbl['rbl'] task:resolve_dns_a(rbl_str, 'dns_cb', rbl['symbol']) end end end end local recvh = task:get_received_headers() for _,rh in ipairs(recvh) do if rh['real_ip'] then if not string.match(rh['real_ip'], ":") then local _,_,o1,o2,o3,o4 = string.find(rh['real_ip'], '^(%d+)%.(%d+)%.(%d+)%.(%d+)$') if o1 and o2 and o3 and o4 then for _,rbl in pairs(rbls) do if(rbl['ipv4'] and rbl['received']) then rbl_str = o4 .. '.' .. o3 .. '.' .. o2 .. '.' .. o1 .. '.' .. rbl['rbl'] task:resolve_dns_a(rbl_str, 'dns_cb', rbl['symbol']) end end end else for _,rbl in pairs(rbls) do if(rbl['ipv6'] and rbl['received']) then rbl_str = revipv6(rh['real_ip']) .. rbl['rbl'] task:resolve_dns_a(rbl_str, 'dns_cb', rbl['symbol']) end end end end end end -- Registration if type(rspamd_config.get_api_version) ~= 'nil' then if rspamd_config:get_api_version() >= 1 then rspamd_config:register_module_option('rbl', 'rbls', 'map') rspamd_config:register_module_option('rbl', 'default_ipv4', 'string') rspamd_config:register_module_option('rbl', 'default_ipv6', 'string') rspamd_config:register_module_option('rbl', 'default_received', 'string') rspamd_config:register_module_option('rbl', 'default_from', 'string') end end -- Configuration local opts = rspamd_config:get_all_opt('rbl') if(opts == nil) then return end if(opts['default_ipv4'] == nil) then opts['default_ipv4'] = true end if(opts['default_ipv6'] == nil) then opts['default_ipv6'] = false end if(opts['default_received'] == nil) then opts['default_received'] = true end if(opts['default_from'] == nil) then opts['default_from'] = false end for _,rbl in pairs(opts['rbls']) do local o = { "ipv4", "ipv6", "from", "received" } for i=1,#o do if(rbl[o[i]] == nil) then rbl[o[i]] = opts['default_' .. o[i]] end end if type(rspamd_config.get_api_version) ~= 'nil' then rspamd_config:register_virtual_symbol(rbl['symbol'], 1) end table.insert(rbls, {symbol = rbl['symbol'], rbl = rbl['rbl'], ipv6 = rbl['ipv6'], ipv4 = rbl['ipv4'], received = rbl['received'], from = rbl['from']}) rspamd_config:register_symbol(rbl['symbol'], 1.0, 'rbl_cb') end
-- Configuration: -- rbl { -- default_ipv4 = true; -- default_ipv6 = false; -- default_received = true; -- default_from = false; -- rbls { -- xbl { -- rbl = "xbl.spamhaus.org"; -- symbol = "RBL_SPAMHAUSXBL"; -- ipv4 = true; -- ipv6 = false; -- } -- } -- } local rbls = {} local function ip_to_rbl(ip, rbl) octets = ip:inversed_str_octets() local str = '' for _,o in ipairs(octets) do str = str .. o .. '.' end str = str .. rbl return str end local function rbl_dns_cb(task, to_resolve, results, err, sym) if results then task:insert_result(sym, 1) end end local function rbl_cb (task) local rip = task:get_from_ip() if(rip ~= nil) then for _,rbl in pairs(rbls) do task:resolve_dns_a(ip_to_rbl(rip, rbl['rbl']), rbl_dns_cb, rbl['symbol']) end end local recvh = task:get_received_headers() for _,rh in ipairs(recvh) do if rh['real_ip'] then for _,rbl in pairs(rbls) do task:resolve_dns_a(ip_to_rbl(rip, rbl['rbl']), rbl_dns_cb, rbl['symbol']) end end end end -- Registration if type(rspamd_config.get_api_version) ~= 'nil' then if rspamd_config:get_api_version() >= 1 then rspamd_config:register_module_option('rbl', 'rbls', 'map') rspamd_config:register_module_option('rbl', 'default_ipv4', 'string') rspamd_config:register_module_option('rbl', 'default_ipv6', 'string') rspamd_config:register_module_option('rbl', 'default_received', 'string') rspamd_config:register_module_option('rbl', 'default_from', 'string') end end -- Configuration local opts = rspamd_config:get_all_opt('rbl') if not opts or type(opts) ~= 'table' then return end if(opts['default_ipv4'] == nil) then opts['default_ipv4'] = true end if(opts['default_ipv6'] == nil) then opts['default_ipv6'] = false end if(opts['default_received'] == nil) then opts['default_received'] = true end if(opts['default_from'] == nil) then opts['default_from'] = false end for key,rbl in pairs(opts['rbls']) do local o = { "ipv4", "ipv6", "from", "received" } for i=1,table.maxn(o) do if(rbl[o[i]] == nil) then rbl[o[i]] = opts['default_' .. o[i]] end end if not rbl['symbol'] then rbl['symbol'] = key end if type(rspamd_config.get_api_version) ~= 'nil' then rspamd_config:register_virtual_symbol(rbl['symbol'], 1) end table.insert(rbls, {symbol = rbl['symbol'], rbl = rbl['rbl'], ipv6 = rbl['ipv6'], ipv4 = rbl['ipv4'], received = rbl['received'], from = rbl['from']}) rspamd_config:register_symbol(rbl['symbol'], 1.0, rbl_cb) end
Fix rbl plugin.
Fix rbl plugin.
Lua
apache-2.0
minaevmike/rspamd,amohanta/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,awhitesong/rspamd,dark-al/rspamd,amohanta/rspamd,amohanta/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,dark-al/rspamd,andrejzverev/rspamd,minaevmike/rspamd,AlexeySa/rspamd,amohanta/rspamd,minaevmike/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,dark-al/rspamd,awhitesong/rspamd,awhitesong/rspamd,minaevmike/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,minaevmike/rspamd,minaevmike/rspamd,amohanta/rspamd,minaevmike/rspamd,minaevmike/rspamd,awhitesong/rspamd,AlexeySa/rspamd,minaevmike/rspamd,dark-al/rspamd,dark-al/rspamd,AlexeySa/rspamd,andrejzverev/rspamd
cc747f4988f409a601366881817eba7cb5bcc83f
SVUI_Skins/components/blizzard/orderhall.lua
SVUI_Skins/components/blizzard/orderhall.lua
--[[ ############################################################################## S V U I By: Failcoder ############################################################################## --]] --[[ GLOBALS ]]-- local _G = _G; local unpack = _G.unpack; local select = _G.select; local tinsert = _G.tinsert; --[[ ADDON ]]-- local SV = _G['SVUI']; local L = SV.L; local MOD = SV.Skins; local Schema = MOD.Schema; --[[ ########################################################## HELPERS ########################################################## ]]-- local function OrderHallCommandBar_OnShow() SV:AdjustTopDockBar(18) end local function OrderHallCommandBar_OnHide() SV:AdjustTopDockBar(0) end --[[ ########################################################## STYLE ########################################################## ]]-- local function OrderHallStyle() --print('test OrderHallStyle') if SV.db.Skins.blizzard.enable ~= true or SV.db.Skins.blizzard.orderhall ~= true then return end --print('begin OrderHallStyle') --OrderHallCommandBar:RemoveTextures() --OrderHallCommandBar:SetStyle("Inset") --OrderHallCommandBar:DisableDrawLayer("BACKGROUND") OrderHallCommandBar:SetStyle("!_Frame", "") SV.API:Set("IconButton", OrderHallCommandBar.WorldMapButton, [[Interface\ICONS\INV_Misc_Map02]]) OrderHallCommandBar:HookScript("OnShow", OrderHallCommandBar_OnShow) OrderHallCommandBar:HookScript("OnHide", OrderHallCommandBar_OnHide) SV:AdjustTopDockBar(18) end --[[ ########################################################## MOD LOADING ########################################################## ]]-- MOD:SaveBlizzardStyle("Blizzard_OrderHallUI", OrderHallStyle)
--[[ ############################################################################## S V U I By: Failcoder ############################################################################## --]] --[[ GLOBALS ]]-- local _G = _G; local unpack = _G.unpack; local select = _G.select; local tinsert = _G.tinsert; --[[ ADDON ]]-- local SV = _G['SVUI']; local L = SV.L; local MOD = SV.Skins; local Schema = MOD.Schema; --[[ ########################################################## HELPERS ########################################################## ]]-- local function OrderHallCommandBar_OnShow() SV:AdjustTopDockBar(18); end local function OrderHallCommandBar_OnHide() SV:AdjustTopDockBar(); end --[[ ########################################################## STYLE ########################################################## ]]-- local function OrderHallStyle() if SV.db.Skins.blizzard.enable ~= true or SV.db.Skins.blizzard.orderhall ~= true then return end local frame = OrderHallTalentFrame; -- Set API SV.API:Set("Window", frame, true); SV.API:Set("Button", frame.BackButton, nil, true); --Reposition the back button slightly (if there is one) --This should only occur inside the Chromie scenario frame.BackButton:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -15, 10); OrderHallCommandBar:SetStyle("!_Frame", "") SV.API:Set("IconButton", OrderHallCommandBar.WorldMapButton, [[Interface\ICONS\INV_Misc_Map02]]) local inOrderHall = C_Garrison.IsPlayerInGarrison(LE_GARRISON_TYPE_7_0); if (inOrderHall) then OrderHallCommandBar:HookScript("OnShow", OrderHallCommandBar_OnShow); frame.currencyButton = CreateFrame("Frame", nil, frame); frame.currencyButton:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -85, -35); frame.currencyButton:SetHeight(20); frame.currencyButton:SetWidth(20); frame.currencyButton:CreateTexture("resources"); resources:SetAllPoints(); resources:SetTexture("Interface\\ICONS\\INV_Garrison_Resource"); end OrderHallCommandBar:HookScript("OnHide", OrderHallCommandBar_OnHide) -- Movable Talent Window frame:SetMovable(true); frame:EnableMouse(true); frame:RegisterForDrag("LeftButton"); frame:SetScript("OnDragStart", frame.StartMoving); frame:SetScript("OnDragStop", frame.StopMovingOrSizing); end --[[ ########################################################## MOD LOADING ########################################################## ]]-- MOD:SaveBlizzardStyle("Blizzard_OrderHallUI", OrderHallStyle)
Multiple fixes: #3 and #108
Multiple fixes: #3 and #108
Lua
mit
FailcoderAddons/supervillain-ui,finalsliver/supervillain-ui
692c21ee76d982f0ce2ae64b721a4b82e8290cc3
MMOCoreORB/bin/scripts/object/weapon/melee/sword/crafted_saber/sword_lightsaber_one_handed_gen1.lua
MMOCoreORB/bin/scripts/object/weapon/melee/sword/crafted_saber/sword_lightsaber_one_handed_gen1.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_weapon_melee_sword_crafted_saber_sword_lightsaber_one_handed_gen1 = object_weapon_melee_sword_crafted_saber_shared_sword_lightsaber_one_handed_gen1:new { playerRaces = { "object/creature/player/bothan_male.iff", "object/creature/player/bothan_female.iff", "object/creature/player/human_male.iff", "object/creature/player/human_female.iff", "object/creature/player/ithorian_male.iff", "object/creature/player/ithorian_female.iff", "object/creature/player/moncal_male.iff", "object/creature/player/moncal_female.iff", "object/creature/player/rodian_male.iff", "object/creature/player/rodian_female.iff", "object/creature/player/sullustan_male.iff", "object/creature/player/sullustan_female.iff", "object/creature/player/trandoshan_male.iff", "object/creature/player/trandoshan_female.iff", "object/creature/player/twilek_male.iff", "object/creature/player/twilek_female.iff", "object/creature/player/wookiee_male.iff", "object/creature/player/wookiee_female.iff", "object/creature/player/zabrak_male.iff", "object/creature/player/zabrak_female.iff" }, -- RANGEDATTACK, MELEEATTACK, FORCEATTACK, TRAPATTACK, GRENADEATTACK, HEAVYACIDBEAMATTACK, -- HEAVYLIGHTNINGBEAMATTACK, HEAVYPARTICLEBEAMATTACK, HEAVYROCKETLAUNCHERATTACK, HEAVYLAUNCHERATTACK attackType = MELEEATTACK, -- ENERGY, KINETIC, ELECTRICITY, STUN, BLAST, HEAT, COLD, ACID, FORCE, LIGHTSABER damageType = LIGHTSABER, -- NONE, LIGHT, MEDIUM, HEAVY armorPiercing = MEDIUM, -- combat_rangedspecialize_bactarifle, combat_rangedspecialize_rifle, combat_rangedspecialize_pistol, combat_rangedspecialize_heavy, combat_rangedspecialize_carbine -- combat_meleespecialize_unarmed, combat_meleespecialize_twohand, combat_meleespecialize_polearm, combat_meleespecialize_onehand, combat_general, -- combat_meleespecialize_twohandlightsaber, combat_meleespecialize_polearmlightsaber, combat_meleespecialize_onehandlightsaber xpType = "combat_meleespecialize_onehandlightsaber", -- See http://www.ocdsoft.com/files/certifications.xls certificationsRequired = { "cert_onehandlightsaber_gen1" }, -- See http://www.ocdsoft.com/files/accuracy.xls creatureAccuracyModifiers = { "onehandlightsaber_accuracy" }, -- See http://www.ocdsoft.com/files/defense.xls defenderDefenseModifiers = { "melee_defense" }, -- Leave as "dodge" for now, may have additions later defenderSecondaryDefenseModifiers = { "saber_block" }, -- See http://www.ocdsoft.com/files/speed.xls speedModifiers = { "onehandlightsaber_speed" }, -- Leave blank for now damageModifiers = { }, -- The values below are the default values. To be used for blue frog objects primarily healthAttackCost = 20, actionAttackCost = 35, mindAttackCost = 40, forceCost = 12, pointBlankAccuracy = 0, pointBlankRange = 0, idealRange = 0, idealAccuracy = 0, maxRange = 0, maxRangeAccuracy = 0, minDamage = 70, maxDamage = 160, attackSpeed = 4.5, numberExperimentalProperties = {1, 1, 2, 2, 2, 2, 2, 1, 1, 1}, experimentalProperties = {"XX", "XX", "CD", "OQ", "CD", "OQ", "CD", "OQ", "SR", "UT", "CD", "OQ", "OQ", "OQ", "OQ"}, experimentalWeights = {1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1}, experimentalGroupTitles = {"null", "null", "expDamage", "expDamage", "expDamage", "expDamage", "expEffeciency", "expEffeciency", "expEffeciency", "expEffeciency"}, experimentalSubGroupTitles = {"null", "null", "mindamage", "maxdamage", "attackspeed", "woundchance", "forcecost", "attackhealthcost", "attackactioncost", "attackmindcost"}, experimentalMin = {0, 0, 70, 160, 4.5, 10, 15, 20, 35, 40}, experimentalMax = {0, 0, 90, 200, 4.2, 20, 12, 15, 25, 25}, experimentalPrecision = {0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, } ObjectTemplates:addTemplate(object_weapon_melee_sword_crafted_saber_sword_lightsaber_one_handed_gen1, "object/weapon/melee/sword/crafted_saber/sword_lightsaber_one_handed_gen1.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_weapon_melee_sword_crafted_saber_sword_lightsaber_one_handed_gen1 = object_weapon_melee_sword_crafted_saber_shared_sword_lightsaber_one_handed_gen1:new { playerRaces = { "object/creature/player/bothan_male.iff", "object/creature/player/bothan_female.iff", "object/creature/player/human_male.iff", "object/creature/player/human_female.iff", "object/creature/player/ithorian_male.iff", "object/creature/player/ithorian_female.iff", "object/creature/player/moncal_male.iff", "object/creature/player/moncal_female.iff", "object/creature/player/rodian_male.iff", "object/creature/player/rodian_female.iff", "object/creature/player/sullustan_male.iff", "object/creature/player/sullustan_female.iff", "object/creature/player/trandoshan_male.iff", "object/creature/player/trandoshan_female.iff", "object/creature/player/twilek_male.iff", "object/creature/player/twilek_female.iff", "object/creature/player/wookiee_male.iff", "object/creature/player/wookiee_female.iff", "object/creature/player/zabrak_male.iff", "object/creature/player/zabrak_female.iff" }, -- RANGEDATTACK, MELEEATTACK, FORCEATTACK, TRAPATTACK, GRENADEATTACK, HEAVYACIDBEAMATTACK, -- HEAVYLIGHTNINGBEAMATTACK, HEAVYPARTICLEBEAMATTACK, HEAVYROCKETLAUNCHERATTACK, HEAVYLAUNCHERATTACK attackType = MELEEATTACK, -- ENERGY, KINETIC, ELECTRICITY, STUN, BLAST, HEAT, COLD, ACID, FORCE, LIGHTSABER damageType = LIGHTSABER, -- NONE, LIGHT, MEDIUM, HEAVY armorPiercing = MEDIUM, -- combat_rangedspecialize_bactarifle, combat_rangedspecialize_rifle, combat_rangedspecialize_pistol, combat_rangedspecialize_heavy, combat_rangedspecialize_carbine -- combat_meleespecialize_unarmed, combat_meleespecialize_twohand, combat_meleespecialize_polearm, combat_meleespecialize_onehand, combat_general, -- combat_meleespecialize_twohandlightsaber, combat_meleespecialize_polearmlightsaber, combat_meleespecialize_onehandlightsaber xpType = "combat_meleespecialize_onehandlightsaber", -- See http://www.ocdsoft.com/files/certifications.xls certificationsRequired = { "cert_onehandlightsaber_gen1" }, -- See http://www.ocdsoft.com/files/accuracy.xls creatureAccuracyModifiers = { "onehandlightsaber_accuracy" }, -- See http://www.ocdsoft.com/files/defense.xls defenderDefenseModifiers = { "melee_defense" }, -- Leave as "dodge" for now, may have additions later defenderSecondaryDefenseModifiers = { "saber_block" }, -- See http://www.ocdsoft.com/files/speed.xls speedModifiers = { "onehandlightsaber_speed" }, -- Leave blank for now damageModifiers = { }, -- The values below are the default values. To be used for blue frog objects primarily healthAttackCost = 20, actionAttackCost = 35, mindAttackCost = 40, forceCost = 12, pointBlankAccuracy = 0, pointBlankRange = 0, idealRange = 0, idealAccuracy = 0, maxRange = 0, maxRangeAccuracy = 0, minDamage = 70, maxDamage = 160, attackSpeed = 4.5, saberInventory = "object/tangible/inventory/lightsaber_inventory_1.iff", numberExperimentalProperties = {1, 1, 2, 2, 2, 2, 2, 1, 1, 1}, experimentalProperties = {"XX", "XX", "CD", "OQ", "CD", "OQ", "CD", "OQ", "SR", "UT", "CD", "OQ", "OQ", "OQ", "OQ"}, experimentalWeights = {1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1}, experimentalGroupTitles = {"null", "null", "expDamage", "expDamage", "expDamage", "expDamage", "expEffeciency", "expEffeciency", "expEffeciency", "expEffeciency"}, experimentalSubGroupTitles = {"null", "null", "mindamage", "maxdamage", "attackspeed", "woundchance", "forcecost", "attackhealthcost", "attackactioncost", "attackmindcost"}, experimentalMin = {0, 0, 70, 160, 4.5, 10, 15, 20, 35, 40}, experimentalMax = {0, 0, 90, 200, 4.2, 20, 12, 15, 25, 25}, experimentalPrecision = {0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, } ObjectTemplates:addTemplate(object_weapon_melee_sword_crafted_saber_sword_lightsaber_one_handed_gen1, "object/weapon/melee/sword/crafted_saber/sword_lightsaber_one_handed_gen1.iff")
[Fixed] 1h generation 1 saber inventory.
[Fixed] 1h generation 1 saber inventory. git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@4580 c3d1530f-68f5-4bd0-87dc-8ef779617e40
Lua
agpl-3.0
Tatwi/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,lasko2112/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,Tatwi/legend-of-hondo
1c41fb0a9c674f1a4dcb18d9c27b45a181ffb040
scripts/tcp-connect.lua
scripts/tcp-connect.lua
local syn_table = {} print(string.format("\n Time IP:Port Retries Conenct Cost(s)")) print(string.format("-------------------------- ---------------------------------------------- -------------- ---------------------")) function process(packet) if packet.size ~= 0 then return -- // skip the packet with payload end if packet.request and packet.flags == 2 then -- syn packet local key = packet.sip..":"..packet.sport.." => "..packet.dip..":"..packet.dport if not syn_table[key] then syn_table[key] = { seq = packet.seq, count = 0, tv_sec = packet.tv_sec, tv_usec = packet.tv_usec } return end if syn_table[key].seq == packet.seq then -- duplicate syn syn_table[key].count = syn_table[key].count + 1 end return end if (not packet.request and packet.flags == 18) -- syn + ack or (bit32.band(packet.flags, 4) ~= 0) then -- rst local key = packet.dip..":"..packet.dport.." => "..packet.sip..":"..packet.sport local first_syn_packet = syn_table[key] -- only print the connection with retransmit syn packet if first_syn_packet and first_syn_packet.count > 0 then local time_str = os.date('%Y-%m-%d %H:%M:%S', packet.tv_sec).."."..packet.tv_usec print(string.format("%26s %47s %6d %12d.%06d", time_str, key, syn_table[key].count, packet.tv_sec-first_syn_packet.tv_sec, packet.tv_usec-first_syn_packet.tv_usec )) end syn_table[key] = nil return end end
local syn_table = {} print(string.format("\n Time IP:Port Retries Conenct Cost(s)")) print(string.format("-------------------------- ---------------------------------------------- -------------- ---------------------")) function process(packet) if packet.size ~= 0 then return -- // skip the packet with payload end if packet.request and packet.flags == 2 then -- syn packet local key = packet.sip..":"..packet.sport.." => "..packet.dip..":"..packet.dport if not syn_table[key] then syn_table[key] = { seq = packet.seq, count = 0, tv_sec = packet.tv_sec, tv_usec = packet.tv_usec } return end if syn_table[key].seq == packet.seq then -- duplicate syn syn_table[key].count = syn_table[key].count + 1 end return end if (not packet.request and packet.flags == 18) -- syn + ack or (bit32.band(packet.flags, 4) ~= 0) then -- rst local key = packet.dip..":"..packet.dport.." => "..packet.sip..":"..packet.sport local first_syn_packet = syn_table[key] -- only print the connection with retransmit syn packet if first_syn_packet and first_syn_packet.count > 0 then local time_str = os.date('%Y-%m-%d %H:%M:%S', packet.tv_sec).."."..packet.tv_usec if packet.tv_usec < first_syn_packet.tv_usec then packet.tv_sec = packet.tv_sec - 1 packet.tv_usec = packet.tv_usec + 1000000 end print(string.format("%26s %47s %6d %12d.%06d", time_str, key, syn_table[key].count, packet.tv_sec-first_syn_packet.tv_sec, packet.tv_usec-first_syn_packet.tv_usec )) end syn_table[key] = nil return end end
FIX: tcp connect script usec maybe negative number
FIX: tcp connect script usec maybe negative number
Lua
mit
git-hulk/tcpkit,git-hulk/tcpkit
bb1c4e9db6b920b1b0c99e4da0f6bb06784f3646
scripts/tundra/util.lua
scripts/tundra/util.lua
-- Copyright 2010 Andreas Fredriksson -- -- This file is part of Tundra. -- -- Tundra is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- Tundra is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with Tundra. If not, see <http://www.gnu.org/licenses/>. local _tostring = tostring module(..., package.seeall) function tostring(value) local str = '' if (type(value) ~= 'table') then if (type(value) == 'string') then str = string.format("%q", value) else str = _tostring(value) end else local auxTable = {} for k, v in pairs(value) do auxTable[#auxTable + 1] = k end table.sort(auxTable, function (a, b) return _tostring(a) < _tostring(b) end) str = str..'{' local separator = "" local entry = "" for index, fieldName in ipairs(auxTable) do if ((tonumber(fieldName)) and (tonumber(fieldName) > 0)) then entry = tostring(value[tonumber(fieldName)]) else entry = tostring(fieldName) .. " = " .. tostring(rawget(value, fieldName)) end str = str..separator..entry separator = ", " end str = str..'}' end return str end function map(t, fn) local result = {} for idx = 1, #t do result[idx] = fn(t[idx]) end return result end function mapnil(table, fn) if not table then return nil else return map(table, fn) end end function get_named_arg(tab, name, context) local v = tab[name] if v then return v else if context then error(context .. ": argument " .. name .. " must be specified", 3) else error("argument " .. name .. " must be specified", 3) end end end function parse_cmdline(args, blueprint) local index, max = 2, #args local options, targets = {}, {} local lookup = {} for _, opt in ipairs(blueprint) do if opt.Short then lookup[opt.Short] = opt end if opt.Long then lookup[opt.Long] = opt end end while index <= max do local s = args[index] local key, val if s:sub(1, 2) == '--' then key = s:sub(3) elseif s:sub(1, 1) == '-' then key = s:sub(2,2) if s:len() > 2 then val = s:sub(3) printf("val for %s is %s", key, val) end else table.insert(targets, s) end if key then local opt = lookup[key] if not opt then return nil, nil, "Unknown option " .. s end if opt.HasValue then if not val then index = index + 1 val = args[index+1] end if val then options[opt.Name] = val else return nil, nil, "Missing value for option "..s end else local v = options[opt.Name] or 0 options[opt.Name] = v + 1 end end index = index + 1 end return options, targets end function clone_table(t) if t then local r = {} for k, v in pairs(t) do r[k] = v end return r else return nil end end function clone_array(t) local r = {} for k, v in ipairs(t) do r[k] = v end return r end function merge_arrays(...) local result = {} local count = select('#', ...) for i = 1, count do local tab = select(i, ...) if tab then for _, v in ipairs(tab) do result[#result + 1] = v end end end return result end function merge_arrays_2(a, b) if a and b then return merge_arrays(a, b) elseif a then return a elseif b then return b else return {} end end function matches_any(str, patterns) for _, pattern in ipairs(patterns) do if str:match(pattern) then return true end end return false end function return_nil() end function nil_pairs(t) if t then return next, t else return return_nil end end function nil_ipairs(t) if t then return ipairs(t) else return return_nil end end function clear_table(tab) local key, val = next(tab) while key do tab[key] = nil key, val = next(tab, key) end return tab end function filter_in_place(tab, predicate) local i, limit = 1, #tab while i <= limit do if not predicate(tab[i]) then table.remove(tab, i) limit = limit - 1 else i = i + 1 end end return tab end function append_table(result, items) local offset = #result for i = 1, #items do result[offset + i] = items[i] end return result end function flatten(array) local function iter(item, accum) if type(item) == 'table' then for _, sub_item in ipairs(item) do iter(sub_item, accum) end else accum[#accum + 1] = item end end local accum = {} iter(array, accum) return accum end function memoize(closure) local result = nil return function(...) if not result then result = assert(closure(...)) end return result end end function uniq(array) local seen = {} local result = {} for _, val in ipairs(array) do if not seen[val] then seen[val] = true result[#result + 1] = val end end return result end function make_lookup_table(array) local result = {} for _, item in nil_ipairs(array) do result[item] = true end return result end
-- Copyright 2010 Andreas Fredriksson -- -- This file is part of Tundra. -- -- Tundra is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- Tundra is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with Tundra. If not, see <http://www.gnu.org/licenses/>. local _tostring = tostring module(..., package.seeall) function tostring(value) local str = '' if (type(value) ~= 'table') then if (type(value) == 'string') then str = string.format("%q", value) else str = _tostring(value) end else local auxTable = {} for k, v in pairs(value) do auxTable[#auxTable + 1] = k end table.sort(auxTable, function (a, b) return _tostring(a) < _tostring(b) end) str = str..'{' local separator = "" local entry = "" for index, fieldName in ipairs(auxTable) do if ((tonumber(fieldName)) and (tonumber(fieldName) > 0)) then entry = tostring(value[tonumber(fieldName)]) else entry = tostring(fieldName) .. " = " .. tostring(rawget(value, fieldName)) end str = str..separator..entry separator = ", " end str = str..'}' end return str end function map(t, fn) local result = {} for idx = 1, #t do result[idx] = fn(t[idx]) end return result end function mapnil(table, fn) if not table then return nil else return map(table, fn) end end function get_named_arg(tab, name, context) local v = tab[name] if v then return v else if context then error(context .. ": argument " .. name .. " must be specified", 3) else error("argument " .. name .. " must be specified", 3) end end end function parse_cmdline(args, blueprint) local index, max = 2, #args local options, targets = {}, {} local lookup = {} for _, opt in ipairs(blueprint) do if opt.Short then lookup[opt.Short] = opt end if opt.Long then lookup[opt.Long] = opt end end while index <= max do local s = args[index] local key, val if s:sub(1, 2) == '--' then key = s:sub(3) elseif s:sub(1, 1) == '-' then key = s:sub(2,2) if s:len() > 2 then val = s:sub(3) end else table.insert(targets, s) end if key then local opt = lookup[key] if not opt then return nil, nil, "Unknown option " .. s end if opt.HasValue then if not val then index = index + 1 val = args[index] end if val then options[opt.Name] = val else return nil, nil, "Missing value for option "..s end else local v = options[opt.Name] or 0 options[opt.Name] = v + 1 end end index = index + 1 end return options, targets end function clone_table(t) if t then local r = {} for k, v in pairs(t) do r[k] = v end return r else return nil end end function clone_array(t) local r = {} for k, v in ipairs(t) do r[k] = v end return r end function merge_arrays(...) local result = {} local count = select('#', ...) for i = 1, count do local tab = select(i, ...) if tab then for _, v in ipairs(tab) do result[#result + 1] = v end end end return result end function merge_arrays_2(a, b) if a and b then return merge_arrays(a, b) elseif a then return a elseif b then return b else return {} end end function matches_any(str, patterns) for _, pattern in ipairs(patterns) do if str:match(pattern) then return true end end return false end function return_nil() end function nil_pairs(t) if t then return next, t else return return_nil end end function nil_ipairs(t) if t then return ipairs(t) else return return_nil end end function clear_table(tab) local key, val = next(tab) while key do tab[key] = nil key, val = next(tab, key) end return tab end function filter_in_place(tab, predicate) local i, limit = 1, #tab while i <= limit do if not predicate(tab[i]) then table.remove(tab, i) limit = limit - 1 else i = i + 1 end end return tab end function append_table(result, items) local offset = #result for i = 1, #items do result[offset + i] = items[i] end return result end function flatten(array) local function iter(item, accum) if type(item) == 'table' then for _, sub_item in ipairs(item) do iter(sub_item, accum) end else accum[#accum + 1] = item end end local accum = {} iter(array, accum) return accum end function memoize(closure) local result = nil return function(...) if not result then result = assert(closure(...)) end return result end end function uniq(array) local seen = {} local result = {} for _, val in ipairs(array) do if not seen[val] then seen[val] = true result[#result + 1] = val end end return result end function make_lookup_table(array) local result = {} for _, item in nil_ipairs(array) do result[item] = true end return result end
Fixed bug with value options.
Fixed bug with value options.
Lua
mit
bmharper/tundra,deplinenoise/tundra,bmharper/tundra,bmharper/tundra,deplinenoise/tundra,bmharper/tundra,deplinenoise/tundra
eaa5d5be5dae28896f1624eee09ccb75552fe1e9
agents/monitoring/tests/check/filesystem.lua
agents/monitoring/tests/check/filesystem.lua
local math = require('math') local os = require('os') local FileSystemCheck = require('monitoring/default/check').FileSystemCheck local exports = {} exports['test_filesystem_check'] = function(test, asserts) if os.type() == "win32" then fs_target = 'C:\\' else fs_target = '/' end local check = FileSystemCheck:new({id='foo', period=30, details={target=fs_target}}) asserts.ok(check._lastResult == nil) check:run(function(result) local util = require('utils') local metrics = result:getMetrics()['none'] asserts.not_nil(metrics['total']['v']) asserts.not_nil(metrics['free']['v']) asserts.not_nil(metrics['used']['v']) asserts.not_nil(metrics['avail']['v']) asserts.not_nil(metrics['files']['v']) asserts.not_nil(metrics['free_files']['v']) asserts.equal(metrics['total']['t'], 'int64') asserts.equal(metrics['free']['t'], 'int64') asserts.equal(metrics['used']['t'], 'int64') asserts.equal(metrics['avail']['t'], 'int64') asserts.ok(tonumber(metrics['free']['v']) <= tonumber(metrics['total']['v'])) asserts.equal(tonumber(metrics['free']['v']) + tonumber(metrics['used']['v']), tonumber(metrics['total']['v'])) -- These metrics are unavailalbe on Win32, see: -- http://www.hyperic.com/support/docs/sigar/org/hyperic/sigar/FileSystemUsage.html#getFiles() if os.type() ~= "win32" then asserts.equal(metrics['files']['t'], 'int64') asserts.equal(metrics['free_files']['t'], 'int64') asserts.ok(tonumber(metrics['free_files']['v']) <= tonumber(metrics['files']['v'])) else asserts.is_nil(metrics['files']) asserts.is_nil(metrics['free_files']) end test.done() end) end exports['test_filesystem_check_nonexistent_mount_point'] = function(test, asserts) local check = FileSystemCheck:new({id='foo', period=30, details={target='does-not-exist'}}) check:run(function(result) asserts.equal(result:getState(), 'unavailable') asserts.equal(result:getStatus(), 'No filesystem mounted at does-not-exist') test.done() end) end exports['test_filesystem_check_no_mount_point'] = function(test, asserts) local check = FileSystemCheck:new({id='foo', period=30}) check:run(function(result) asserts.equal(result:getState(), 'unavailable') asserts.equal(result:getStatus(), 'Missing target parameter') test.done() end) end return exports
local math = require('math') local os = require('os') local FileSystemCheck = require('monitoring/default/check').FileSystemCheck local exports = {} exports['test_filesystem_check'] = function(test, asserts) if os.type() == "win32" then fs_target = 'C:\\' else fs_target = '/' end local check = FileSystemCheck:new({id='foo', period=30, details={target=fs_target}}) asserts.ok(check._lastResult == nil) check:run(function(result) local util = require('utils') local metrics = result:getMetrics()['none'] asserts.not_nil(metrics['total']['v']) asserts.not_nil(metrics['free']['v']) asserts.not_nil(metrics['used']['v']) asserts.not_nil(metrics['avail']['v']) asserts.equal(metrics['total']['t'], 'int64') asserts.equal(metrics['free']['t'], 'int64') asserts.equal(metrics['used']['t'], 'int64') asserts.equal(metrics['avail']['t'], 'int64') asserts.ok(tonumber(metrics['free']['v']) <= tonumber(metrics['total']['v'])) asserts.equal(tonumber(metrics['free']['v']) + tonumber(metrics['used']['v']), tonumber(metrics['total']['v'])) -- These metrics are unavailalbe on Win32, see: -- http://www.hyperic.com/support/docs/sigar/org/hyperic/sigar/FileSystemUsage.html#getFiles() if os.type() ~= "win32" then asserts.not_nil(metrics['files']['v']) asserts.not_nil(metrics['free_files']['v']) asserts.equal(metrics['files']['t'], 'int64') asserts.equal(metrics['free_files']['t'], 'int64') asserts.ok(tonumber(metrics['free_files']['v']) <= tonumber(metrics['files']['v'])) else asserts.is_nil(metrics['files']) asserts.is_nil(metrics['free_files']) end test.done() end) end exports['test_filesystem_check_nonexistent_mount_point'] = function(test, asserts) local check = FileSystemCheck:new({id='foo', period=30, details={target='does-not-exist'}}) check:run(function(result) asserts.equal(result:getState(), 'unavailable') asserts.equal(result:getStatus(), 'No filesystem mounted at does-not-exist') test.done() end) end exports['test_filesystem_check_no_mount_point'] = function(test, asserts) local check = FileSystemCheck:new({id='foo', period=30}) check:run(function(result) asserts.equal(result:getState(), 'unavailable') asserts.equal(result:getStatus(), 'Missing target parameter') test.done() end) end return exports
fixes(windows): filesystem test
fixes(windows): filesystem test
Lua
apache-2.0
AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent
4163c9b01f6c0f9b5e46833582ddcc338e6628b9
kong/api/routes/upstreams.lua
kong/api/routes/upstreams.lua
local endpoints = require "kong.api.endpoints" local utils = require "kong.tools.utils" local kong = kong local escape_uri = ngx.escape_uri local unescape_uri = ngx.unescape_uri local null = ngx.null local fmt = string.format local function post_health(self, db, is_healthy) local upstream, _, err_t = endpoints.select_entity(self, db, db.upstreams.schema) if err_t then return endpoints.handle_error(err_t) end if not upstream then return kong.response.exit(404, { message = "Not found" }) end local target if utils.is_valid_uuid(unescape_uri(self.params.targets)) then target, _, err_t = endpoints.select_entity(self, db, db.targets.schema) else local opts = endpoints.extract_options(self.args.uri, db.targets.schema, "select") local upstream_pk = db.upstreams.schema:extract_pk_values(upstream) local filter = { target = unescape_uri(self.params.targets) } target, _, err_t = db.targets:select_by_upstream_filter(upstream_pk, filter, opts) end if err_t then return endpoints.handle_error(err_t) end if not target or target.upstream.id ~= upstream.id then return kong.response.exit(404, { message = "Not found" }) end local ok, err = db.targets:post_health(upstream, target, self.params.address, is_healthy) if not ok then return kong.response.exit(400, { message = err }) end return kong.response.exit(204) end return { ["/upstreams/:upstreams/health"] = { GET = function(self, db) local upstream, _, err_t = endpoints.select_entity(self, db, db.upstreams.schema) if err_t then return endpoints.handle_error(err_t) end if not upstream then return kong.response.exit(404, { message = "Not found" }) end local node_id, err = kong.node.get_id() if err then kong.log.err("failed to get node id: ", err) end if tostring(self.params.balancer_health) == "1" then local upstream_pk = db.upstreams.schema:extract_pk_values(upstream) local balancer_health = db.targets:get_balancer_health(upstream_pk) return kong.response.exit(200, { data = balancer_health, next = null, node_id = node_id, }) end self.params.targets = db.upstreams.schema:extract_pk_values(upstream) local targets_with_health, _, err_t, offset = endpoints.page_collection(self, db, db.targets.schema, "page_for_upstream_with_health") if err_t then return endpoints.handle_error(err_t) end local next_page = offset and fmt("/upstreams/%s/health?offset=%s", self.params.upstreams, escape_uri(offset)) or null return kong.response.exit(200, { data = targets_with_health, offset = offset, next = next_page, node_id = node_id, }) end }, ["/upstreams/:upstreams/targets"] = { GET = endpoints.get_collection_endpoint(kong.db.targets.schema, kong.db.upstreams.schema, "upstream", "page_for_upstream"), }, ["/upstreams/:upstreams/targets/all"] = { GET = endpoints.get_collection_endpoint(kong.db.targets.schema, kong.db.upstreams.schema, "upstream", "page_for_upstream_raw") }, ["/upstreams/:upstreams/targets/:targets/healthy"] = { POST = function(self, db) return post_health(self, db, true) end, }, ["/upstreams/:upstreams/targets/:targets/unhealthy"] = { POST = function(self, db) return post_health(self, db, false) end, }, ["/upstreams/:upstreams/targets/:targets/:address/healthy"] = { POST = function(self, db) return post_health(self, db, true) end, }, ["/upstreams/:upstreams/targets/:targets/:address/unhealthy"] = { POST = function(self, db) return post_health(self, db, false) end, }, ["/upstreams/:upstreams/targets/:targets"] = { DELETE = function(self, db) local upstream, _, err_t = endpoints.select_entity(self, db, db.upstreams.schema) if err_t then return endpoints.handle_error(err_t) end if not upstream then return kong.response.exit(404, { message = "Not found" }) end local target if utils.is_valid_uuid(unescape_uri(self.params.targets)) then target, _, err_t = endpoints.select_entity(self, db, db.targets.schema) else local opts = endpoints.extract_options(self.args.uri, db.targets.schema, "select") local upstream_pk = db.upstreams.schema:extract_pk_values(upstream) local filter = { target = unescape_uri(self.params.targets) } target, _, err_t = db.targets:select_by_upstream_filter(upstream_pk, filter, opts) end if err_t then return endpoints.handle_error(err_t) end if not target or target.upstream.id ~= upstream.id then return kong.response.exit(404, { message = "Not found" }) end self.params.targets = db.upstreams.schema:extract_pk_values(target) _, _, err_t = endpoints.delete_entity(self, db, db.targets.schema) if err_t then return endpoints.handle_error(err_t) end return kong.response.exit(204) -- no content end }, }
local endpoints = require "kong.api.endpoints" local utils = require "kong.tools.utils" local kong = kong local escape_uri = ngx.escape_uri local unescape_uri = ngx.unescape_uri local null = ngx.null local tostring = tostring local fmt = string.format local function post_health(self, db, is_healthy) local upstream, _, err_t = endpoints.select_entity(self, db, db.upstreams.schema) if err_t then return endpoints.handle_error(err_t) end if not upstream then return kong.response.exit(404, { message = "Not found" }) end local target if utils.is_valid_uuid(unescape_uri(self.params.targets)) then target, _, err_t = endpoints.select_entity(self, db, db.targets.schema) else local opts = endpoints.extract_options(self.args.uri, db.targets.schema, "select") local upstream_pk = db.upstreams.schema:extract_pk_values(upstream) local filter = { target = unescape_uri(self.params.targets) } target, _, err_t = db.targets:select_by_upstream_filter(upstream_pk, filter, opts) end if err_t then return endpoints.handle_error(err_t) end if not target or target.upstream.id ~= upstream.id then return kong.response.exit(404, { message = "Not found" }) end local ok, err = db.targets:post_health(upstream, target, self.params.address, is_healthy) if not ok then return kong.response.exit(400, { message = err }) end return kong.response.exit(204) end local function select_target_cb(self, db, upstream, target) if target and target.weight ~= 0 then return kong.response.exit(200, target) end return kong.response.exit(404, { message = "Not found" }) end local function update_target_cb(self, db, upstream, target) return kong.response.exit(405, { message = "Method not allowed" }) end local function delete_target_cb(self, db, upstream, target) self.params.targets = db.targets.schema:extract_pk_values(target) local _, _, err_t = endpoints.delete_entity(self, db, db.targets.schema) if err_t then return endpoints.handle_error(err_t) end return kong.response.exit(204) -- no content end local function target_endpoint(self, db, callback) local upstream, _, err_t = endpoints.select_entity(self, db, db.upstreams.schema) if err_t then return endpoints.handle_error(err_t) end if not upstream then return kong.response.exit(404, { message = "Not found" }) end local target if utils.is_valid_uuid(unescape_uri(self.params.targets)) then target, _, err_t = endpoints.select_entity(self, db, db.targets.schema) else local opts = endpoints.extract_options(self.args.uri, db.targets.schema, "select") local upstream_pk = db.upstreams.schema:extract_pk_values(upstream) local filter = { target = unescape_uri(self.params.targets) } target, _, err_t = db.targets:select_by_upstream_filter(upstream_pk, filter, opts) end if err_t then return endpoints.handle_error(err_t) end if not target or target.upstream.id ~= upstream.id then return kong.response.exit(404, { message = "Not found" }) end return callback(self, db, upstream, target) end return { ["/upstreams/:upstreams/health"] = { GET = function(self, db) local upstream, _, err_t = endpoints.select_entity(self, db, db.upstreams.schema) if err_t then return endpoints.handle_error(err_t) end if not upstream then return kong.response.exit(404, { message = "Not found" }) end local node_id, err = kong.node.get_id() if err then kong.log.err("failed to get node id: ", err) end if tostring(self.params.balancer_health) == "1" then local upstream_pk = db.upstreams.schema:extract_pk_values(upstream) local balancer_health = db.targets:get_balancer_health(upstream_pk) return kong.response.exit(200, { data = balancer_health, next = null, node_id = node_id, }) end self.params.targets = db.upstreams.schema:extract_pk_values(upstream) local targets_with_health, _, err_t, offset = endpoints.page_collection(self, db, db.targets.schema, "page_for_upstream_with_health") if err_t then return endpoints.handle_error(err_t) end local next_page = offset and fmt("/upstreams/%s/health?offset=%s", self.params.upstreams, escape_uri(offset)) or null return kong.response.exit(200, { data = targets_with_health, offset = offset, next = next_page, node_id = node_id, }) end }, ["/upstreams/:upstreams/targets"] = { GET = endpoints.get_collection_endpoint(kong.db.targets.schema, kong.db.upstreams.schema, "upstream", "page_for_upstream"), }, ["/upstreams/:upstreams/targets/all"] = { GET = endpoints.get_collection_endpoint(kong.db.targets.schema, kong.db.upstreams.schema, "upstream", "page_for_upstream_raw") }, ["/upstreams/:upstreams/targets/:targets/healthy"] = { POST = function(self, db) return post_health(self, db, true) end, }, ["/upstreams/:upstreams/targets/:targets/unhealthy"] = { POST = function(self, db) return post_health(self, db, false) end, }, ["/upstreams/:upstreams/targets/:targets/:address/healthy"] = { POST = function(self, db) return post_health(self, db, true) end, }, ["/upstreams/:upstreams/targets/:targets/:address/unhealthy"] = { POST = function(self, db) return post_health(self, db, false) end, }, ["/upstreams/:upstreams/targets/:targets"] = { DELETE = function(self, db) return target_endpoint(self, db, delete_target_cb) end, GET = function(self, db) return target_endpoint(self, db, select_target_cb) end, PATCH = function(self, db) return target_endpoint(self, db, update_target_cb) end, }, }
fix(api) upstream targets endpoints fixes
fix(api) upstream targets endpoints fixes ### Summary 1. disallow (405) PATCH on /upstreams/:upstreams/targets/:targets 2. make GET to do proper pre-checks on /upstreams/:upstreams/targets/:targets 3. make PUT to do proper pre-checks on /upstreams/:upstreams/targets/:targets
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
2e0d1c87812865434e5c549b2c1824b5b8bf500d
src/lua-factory/sources/grl-radiofrance.lua
src/lua-factory/sources/grl-radiofrance.lua
--[[ * Copyright (C) 2014 Bastien Nocera * * Contact: Bastien Nocera <hadess@hadess.net> * * This library 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; version 2.1 of * the License, or (at your option) any later version. * * This library 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] local stations = { 'franceinter', 'franceinfo', 'franceculture', 'francemusique', 'fipradio', 'lemouv' } --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-radiofrance-lua", name = "Radio France", description = "A source for browsing Radio France radio stations", supported_keys = { "id", "thumbnail", "title", "url", "mime-type" }, icon = 'resource:///org/gnome/grilo/plugins/radiofrance/radiofrance.png', supported_media = 'audio', tags = { 'radio', 'country:fr', 'net:internet', 'net:plaintext' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media, options, callback) if options.skip > 0 then callback() else local urls = {} for index, item in pairs(stations) do local url = 'http://www.' .. item .. '.fr/player' table.insert(urls, url) end grl.fetch(urls, radiofrance_now_fetch_cb, callback) end end ------------------------ -- Callback functions -- ------------------------ -- return all the media found function radiofrance_now_fetch_cb(results, callback) for index, result in pairs(results) do local media = create_media(stations[index], result) callback(media, -1) end callback() end ------------- -- Helpers -- ------------- function get_thumbnail(id) local images = {} images['franceinter'] = 'http://www.franceinter.fr/sites/all/themes/franceinter/logo.png' images['franceinfo'] = 'http://www.franceinfo.fr/sites/all/themes/custom/france_info/logo.png' images['franceculture'] = 'http://www.franceculture.fr/sites/all/themes/franceculture/images/logo.png' images['francemusique'] = 'http://www.francemusique.fr/sites/all/themes/custom/france_musique/logo.png' images['fipradio'] = 'http://www.fipradio.fr/sites/all/themes/custom/fip/logo.png' images['lemouv'] = 'http://www.lemouv.fr/sites/all/themes/mouv/images/logo_119x119.png' return images[id] end function get_title(id) local names = {} names['franceinter'] = 'France Inter' names['franceinfo'] = 'France Info' names['franceculture'] = 'France Culture' names['francemusique'] = 'France Musique' names['fipradio'] = 'Fip Radio' names['lemouv'] = "Le Mouv'" return names[id] end function create_media(id, result) local media = {} media.type = "audio" media.mime_type = "audio/mpeg" media.id = id if media.id == 'fipradio' then media.id = 'fip' end media.url = result:match("liveUrl: '(.-)',") if not media.url then media.url = result:match('"player" href="(http.-%.mp3)') end media.title = get_title(id) media.thumbnail = get_thumbnail(id) -- FIXME Add metadata about the currently playing tracks -- Available in 'http://www.' .. item .. '.fr/api/now&full=true' return media end
--[[ * Copyright (C) 2014 Bastien Nocera * * Contact: Bastien Nocera <hadess@hadess.net> * * This library 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; version 2.1 of * the License, or (at your option) any later version. * * This library 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] local stations = { 'franceinter', 'franceinfo', 'franceculture', 'francemusique', 'fipradio', 'lemouv' } --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-radiofrance-lua", name = "Radio France", description = "A source for browsing Radio France radio stations", supported_keys = { "id", "thumbnail", "title", "url", "mime-type" }, icon = 'resource:///org/gnome/grilo/plugins/radiofrance/radiofrance.png', supported_media = 'audio', tags = { 'radio', 'country:fr', 'net:internet', 'net:plaintext' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) if grl.get_options("skip") > 0 then grl.callback() else local urls = {} for index, item in pairs(stations) do local url = 'http://www.' .. item .. '.fr/player' table.insert(urls, url) end grl.fetch(urls, radiofrance_now_fetch_cb) end end ------------------------ -- Callback functions -- ------------------------ -- return all the media found function radiofrance_now_fetch_cb(results) for index, result in pairs(results) do local media = create_media(stations[index], result) grl.callback(media, -1) end grl.callback() end ------------- -- Helpers -- ------------- function get_thumbnail(id) local images = {} images['franceinter'] = 'http://www.franceinter.fr/sites/all/themes/franceinter/logo.png' images['franceinfo'] = 'http://www.franceinfo.fr/sites/all/themes/custom/france_info/logo.png' images['franceculture'] = 'http://www.franceculture.fr/sites/all/themes/franceculture/images/logo.png' images['francemusique'] = 'http://www.francemusique.fr/sites/all/themes/custom/france_musique/logo.png' images['fipradio'] = 'http://www.fipradio.fr/sites/all/themes/custom/fip/logo.png' images['lemouv'] = 'http://www.lemouv.fr/sites/all/themes/mouv/images/logo_119x119.png' return images[id] end function get_title(id) local names = {} names['franceinter'] = 'France Inter' names['franceinfo'] = 'France Info' names['franceculture'] = 'France Culture' names['francemusique'] = 'France Musique' names['fipradio'] = 'Fip Radio' names['lemouv'] = "Le Mouv'" return names[id] end function create_media(id, result) local media = {} media.type = "audio" media.mime_type = "audio/mpeg" media.id = id if media.id == 'fipradio' then media.id = 'fip' end media.url = result:match("liveUrl: '(.-)',") if not media.url then media.url = result:match('"player" href="(http.-%.mp3)') end media.title = get_title(id) media.thumbnail = get_thumbnail(id) -- FIXME Add metadata about the currently playing tracks -- Available in 'http://www.' .. item .. '.fr/api/now&full=true' return media end
Revert "lua-factory: port grl-radiofrance.lua to the new lua system"
Revert "lua-factory: port grl-radiofrance.lua to the new lua system" This reverts commit 93547ac94797cdea6670b0d458e838bcdb578f77. But keeps grl.fetch callback as function instead of string https://bugzilla.gnome.org/show_bug.cgi?id=763046
Lua
lgpl-2.1
GNOME/grilo-plugins,GNOME/grilo-plugins,MikePetullo/grilo-plugins,MikePetullo/grilo-plugins,MikePetullo/grilo-plugins,grilofw/grilo-plugins,jasuarez/grilo-plugins,jasuarez/grilo-plugins,grilofw/grilo-plugins
a7e7c31f8c659b55c1adb0863a8f2f66d3452d2b
applications/luci-siitwizard/luasrc/model/cbi/siitwizard.lua
applications/luci-siitwizard/luasrc/model/cbi/siitwizard.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local uci = require "luci.model.uci".cursor() local tools = require "luci.tools.ffwizard" local util = require "luci.util" local io = require "io" -------------------- View -------------------- f = SimpleForm("siitwizward", "4over6-Assistent", "Dieser Assistent unterstüzt bei der Einrichtung von IPv4-over-IPv6 Translation.") mode = f:field(ListValue, "mode", "Betriebsmodus") mode:value("gateway", "Gateway") mode:value("client", "Client") dev = f:field(ListValue, "device", "WLAN-Gerät") uci:foreach("network", "interface", function(section) if section[".name"] ~= "siit0" then dev:value(section[".name"]) end end) -------------------- Control -------------------- LL_PREFIX = luci.ip.IPv6("fe80::/16") -- -- find link-local address -- function find_ll(dev) for _, r in ipairs(luci.sys.net.routes6()) do if r.device == dev and LL_PREFIX:contains(r.dest) then return r.dest:sub(LL_PREFIX) end end return luci.ip.IPv6("::") end function f.handle(self, state, data) if state == FORM_VALID then luci.http.redirect(luci.dispatcher.build_url("admin", "uci", "changes")) return false elseif state == FORM_INVALID then self.errmessage = "Ungültige Eingabe: Bitte die Formularfelder auf Fehler prüfen." end return true end function mode.write(self, section, value) -- -- Determine defaults -- local ula_prefix = uci:get("siit", "defaults", "ula_prefix") or "fd00::" local ula_global = uci:get("siit", "defaults", "ula_global") or "00ca:ffee:babe::" -- = Freifunk local ula_subnet = uci:get("siit", "defaults", "ula_subnet") or "0000:0000:0000:4223::" -- = Berlin local siit_prefix = uci:get("siit", "defaults", "siit_prefix") or "::ffff:ffff:0000:0000" local siit_route = luci.ip.IPv6(siit_prefix .. "/96") -- Find wifi interface local device = dev:formvalue(section) -- -- Generate ULA -- local ula = luci.ip.IPv6("::") for _, prefix in ipairs({ ula_prefix, ula_global, ula_subnet }) do ula = ula:add(luci.ip.IPv6(prefix)) end ula = ula:add(find_ll(uci:get("network", device, "ifname") or device)) -- -- Gateway mode -- -- * wan port is dhcp, lan port is 172.23.1.1/24 -- * siit0 gets a dummy address: 169.254.42.42 -- * wl0 gets an ipv6 address, in this case the fdca:ffee:babe::1:1/64 -- * we do a ::ffff:ffff:0/96 route into siit0, so everything from 6mesh goes into translation. -- * an HNA6 of ::ffff:ffff:0:0/96 announces the mapped 0.0.0.0/0 ipv4 space. -- * MTU on WAN, LAN down to 1400, ipv6 headers are slighly larger. if value == "gateway" then uci:set("network", "wan", "mtu", 1400) -- -- Client mode -- -- * 172.23.2.1/24 on its lan, fdca:ffee:babe::1:2 on wl0 and the usual dummy address on siit0. -- * we do a ::ffff:ffff:172.13.2.0/120 to siit0, because in this case, only traffic directed to clients needs to go into translation. -- * same route as HNA6 announcement to catch the traffic out of the mesh. -- * Also, MTU on LAN reduced to 1400. else local lan_ip = luci.ip.IPv4( uci:get("network", "lan", "ipaddr"), uci:get("network", "lan", "netmask") ) siit_route = luci.ip.IPv6( siit_prefix .. "/" .. (96 + lan_ip:prefix()) ):add(lan_ip[2]) end -- siit0 interface uci:delete_all("network", "interface", function(s) return ( s.ifname == "siit0" ) end) uci:section("network", "interface", "siit0", { ifname = "siit0", proto = "static", ipaddr = "169.254.42.42", netmask = "255.255.255.0" }) -- siit0 route uci:delete_all("network", "route6", function(s) return siit_route:contains(luci.ip.IPv6(s.target)) end) uci:section("network", "route6", nil, { interface = device, target = siit_route:string() }) -- interface uci:set("network", device, "ip6addr", ula:string()) uci:set("network", "lan", "mtu", 1400) uci:set("olsrd", "general", "IpVersion", 6) uci:foreach("olsrd", "Interface", function(s) if s.interface == device then uci:set("olsrd", s[".name"], "Ip6AddrType", "global") end uci:delete("olsrd", s[".name"], "Ip4Boradcast") end) -- hna6 uci:delete_all("olsrd", "Hna6", function(s) if s.netaddr and s.prefix then return siit_route:contains(luci.ip.IPv6(s.netaddr.."/"..s.prefix)) end end) uci:section("olsrd", "Hna6", nil, { netaddr = siit_route:host():string(), prefix = siit_route:prefix() }) uci:save("network") uci:save("olsrd") end return f
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local uci = require "luci.model.uci".cursor() local tools = require "luci.tools.ffwizard" local util = require "luci.util" local io = require "io" -------------------- View -------------------- f = SimpleForm("siitwizward", "4over6-Assistent", "Dieser Assistent unterstüzt bei der Einrichtung von IPv4-over-IPv6 Translation.") mode = f:field(ListValue, "mode", "Betriebsmodus") mode:value("gateway", "Gateway") mode:value("client", "Client") dev = f:field(ListValue, "device", "WLAN-Gerät") uci:foreach("network", "interface", function(section) if section[".name"] ~= "siit0" then dev:value(section[".name"]) end end) -------------------- Control -------------------- LL_PREFIX = luci.ip.IPv6("fe80::/16") -- -- find link-local address -- function find_ll(dev) for _, r in ipairs(luci.sys.net.routes6()) do if r.device == dev and LL_PREFIX:contains(r.dest) then return r.dest:sub(LL_PREFIX) end end return luci.ip.IPv6("::") end function f.handle(self, state, data) if state == FORM_VALID then luci.http.redirect(luci.dispatcher.build_url("admin", "uci", "changes")) return false elseif state == FORM_INVALID then self.errmessage = "Ungültige Eingabe: Bitte die Formularfelder auf Fehler prüfen." end return true end function mode.write(self, section, value) -- -- Determine defaults -- local ula_prefix = uci:get("siit", "defaults", "ula_prefix") or "fd00::" local ula_global = uci:get("siit", "defaults", "ula_global") or "00ca:ffee:babe::" -- = Freifunk local ula_subnet = uci:get("siit", "defaults", "ula_subnet") or "0000:0000:0000:4223::" -- = Berlin local siit_prefix = uci:get("siit", "defaults", "siit_prefix") or "::ffff:ffff:0000:0000" local siit_route = luci.ip.IPv6(siit_prefix .. "/96") -- Find wifi interface local device = dev:formvalue(section) -- -- Generate ULA -- local ula = luci.ip.IPv6("::") for _, prefix in ipairs({ ula_prefix, ula_global, ula_subnet }) do ula = ula:add(luci.ip.IPv6(prefix)) end ula = ula:add(find_ll(uci:get("network", device, "ifname") or device)) -- -- Gateway mode -- -- * wan port is dhcp, lan port is 172.23.1.1/24 -- * siit0 gets a dummy address: 169.254.42.42 -- * wl0 gets an ipv6 address, in this case the fdca:ffee:babe::1:1/64 -- * we do a ::ffff:ffff:0/96 route into siit0, so everything from 6mesh goes into translation. -- * an HNA6 of ::ffff:ffff:0:0/96 announces the mapped 0.0.0.0/0 ipv4 space. -- * MTU on WAN, LAN down to 1400, ipv6 headers are slighly larger. if value == "gateway" then uci:set("network", "wan", "mtu", 1400) -- -- Client mode -- -- * 172.23.2.1/24 on its lan, fdca:ffee:babe::1:2 on wl0 and the usual dummy address on siit0. -- * we do a ::ffff:ffff:172.13.2.0/120 to siit0, because in this case, only traffic directed to clients needs to go into translation. -- * same route as HNA6 announcement to catch the traffic out of the mesh. -- * Also, MTU on LAN reduced to 1400. else local lan_ip = luci.ip.IPv4( uci:get("network", "lan", "ipaddr"), uci:get("network", "lan", "netmask") ) siit_route = luci.ip.IPv6( siit_prefix .. "/" .. (96 + lan_ip:prefix()) ):add(lan_ip[2]) end -- siit0 interface uci:delete_all("network", "interface", function(s) return ( s.ifname == "siit0" ) end) uci:section("network", "interface", "siit0", { ifname = "siit0", proto = "static", ipaddr = "169.254.42.42", netmask = "255.255.255.0" }) -- siit0 route uci:delete_all("network", "route6", function(s) return siit_route:contains(luci.ip.IPv6(s.target)) end) uci:section("network", "route6", nil, { interface = device, target = siit_route:string() }) -- interface uci:set("network", device, "ip6addr", ula:string()) uci:set("network", "lan", "mtu", 1400) uci:set("olsrd", "general", "IpVersion", 6) uci:foreach("olsrd", "Interface", function(s) if s.interface == device then uci:set("olsrd", s[".name"], "Ip6AddrType", "global") end uci:delete("olsrd", s[".name"], "Ip4Broadcast") end) -- hna6 uci:delete_all("olsrd", "Hna6", function(s) if s.netaddr and s.prefix then return siit_route:contains(luci.ip.IPv6(s.netaddr.."/"..s.prefix)) end end) uci:section("olsrd", "Hna6", nil, { netaddr = siit_route:host():string(), prefix = siit_route:prefix() }) uci:save("network") uci:save("olsrd") end return f
applications/siitwizard: whitespace and typo fixes, svn property fixup
applications/siitwizard: whitespace and typo fixes, svn property fixup
Lua
apache-2.0
lcf258/openwrtcn,palmettos/cnLuCI,obsy/luci,deepak78/new-luci,oyido/luci,teslamint/luci,harveyhu2012/luci,jlopenwrtluci/luci,db260179/openwrt-bpi-r1-luci,ReclaimYourPrivacy/cloak-luci,chris5560/openwrt-luci,ReclaimYourPrivacy/cloak-luci,NeoRaider/luci,zhaoxx063/luci,nwf/openwrt-luci,deepak78/new-luci,joaofvieira/luci,kuoruan/lede-luci,Kyklas/luci-proto-hso,opentechinstitute/luci,zhaoxx063/luci,MinFu/luci,lbthomsen/openwrt-luci,mumuqz/luci,obsy/luci,nmav/luci,cshore/luci,remakeelectric/luci,Hostle/luci,oyido/luci,thesabbir/luci,schidler/ionic-luci,daofeng2015/luci,dwmw2/luci,ollie27/openwrt_luci,tcatm/luci,dismantl/luci-0.12,rogerpueyo/luci,oyido/luci,daofeng2015/luci,obsy/luci,palmettos/cnLuCI,kuoruan/luci,ff94315/luci-1,lbthomsen/openwrt-luci,nmav/luci,lbthomsen/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,lbthomsen/openwrt-luci,marcel-sch/luci,Sakura-Winkey/LuCI,thesabbir/luci,cshore/luci,bittorf/luci,oyido/luci,forward619/luci,hnyman/luci,sujeet14108/luci,kuoruan/lede-luci,chris5560/openwrt-luci,ff94315/luci-1,hnyman/luci,981213/luci-1,schidler/ionic-luci,981213/luci-1,taiha/luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,thess/OpenWrt-luci,bright-things/ionic-luci,MinFu/luci,kuoruan/lede-luci,openwrt/luci,wongsyrone/luci-1,keyidadi/luci,deepak78/new-luci,lcf258/openwrtcn,lcf258/openwrtcn,sujeet14108/luci,LuttyYang/luci,jorgifumi/luci,ff94315/luci-1,cshore/luci,cshore/luci,harveyhu2012/luci,Sakura-Winkey/LuCI,wongsyrone/luci-1,slayerrensky/luci,tcatm/luci,shangjiyu/luci-with-extra,lbthomsen/openwrt-luci,jlopenwrtluci/luci,LazyZhu/openwrt-luci-trunk-mod,aircross/OpenWrt-Firefly-LuCI,dismantl/luci-0.12,cappiewu/luci,ff94315/luci-1,nmav/luci,kuoruan/lede-luci,chris5560/openwrt-luci,palmettos/cnLuCI,opentechinstitute/luci,bittorf/luci,aa65535/luci,LazyZhu/openwrt-luci-trunk-mod,shangjiyu/luci-with-extra,remakeelectric/luci,wongsyrone/luci-1,thess/OpenWrt-luci,cshore-firmware/openwrt-luci,jchuang1977/luci-1,cappiewu/luci,aircross/OpenWrt-Firefly-LuCI,openwrt-es/openwrt-luci,tobiaswaldvogel/luci,jchuang1977/luci-1,tcatm/luci,openwrt-es/openwrt-luci,deepak78/new-luci,Sakura-Winkey/LuCI,jorgifumi/luci,Wedmer/luci,nwf/openwrt-luci,slayerrensky/luci,jchuang1977/luci-1,RuiChen1113/luci,bright-things/ionic-luci,lcf258/openwrtcn,ff94315/luci-1,db260179/openwrt-bpi-r1-luci,Noltari/luci,lcf258/openwrtcn,Hostle/luci,daofeng2015/luci,openwrt-es/openwrt-luci,NeoRaider/luci,Kyklas/luci-proto-hso,bright-things/ionic-luci,palmettos/cnLuCI,LazyZhu/openwrt-luci-trunk-mod,thesabbir/luci,Hostle/luci,LazyZhu/openwrt-luci-trunk-mod,db260179/openwrt-bpi-r1-luci,urueedi/luci,kuoruan/lede-luci,david-xiao/luci,david-xiao/luci,tcatm/luci,dismantl/luci-0.12,aa65535/luci,RuiChen1113/luci,artynet/luci,shangjiyu/luci-with-extra,schidler/ionic-luci,dismantl/luci-0.12,Hostle/luci,cappiewu/luci,lcf258/openwrtcn,joaofvieira/luci,mumuqz/luci,artynet/luci,artynet/luci,RedSnake64/openwrt-luci-packages,forward619/luci,schidler/ionic-luci,zhaoxx063/luci,aircross/OpenWrt-Firefly-LuCI,LuttyYang/luci,zhaoxx063/luci,taiha/luci,Kyklas/luci-proto-hso,oneru/luci,hnyman/luci,schidler/ionic-luci,remakeelectric/luci,cshore-firmware/openwrt-luci,fkooman/luci,bright-things/ionic-luci,ollie27/openwrt_luci,ollie27/openwrt_luci,aircross/OpenWrt-Firefly-LuCI,forward619/luci,mumuqz/luci,florian-shellfire/luci,ollie27/openwrt_luci,lbthomsen/openwrt-luci,taiha/luci,forward619/luci,opentechinstitute/luci,ollie27/openwrt_luci,keyidadi/luci,teslamint/luci,LazyZhu/openwrt-luci-trunk-mod,nwf/openwrt-luci,Hostle/openwrt-luci-multi-user,ReclaimYourPrivacy/cloak-luci,RedSnake64/openwrt-luci-packages,Wedmer/luci,artynet/luci,openwrt/luci,fkooman/luci,oneru/luci,hnyman/luci,db260179/openwrt-bpi-r1-luci,daofeng2015/luci,taiha/luci,forward619/luci,ReclaimYourPrivacy/cloak-luci,opentechinstitute/luci,slayerrensky/luci,ReclaimYourPrivacy/cloak-luci,981213/luci-1,oyido/luci,thess/OpenWrt-luci,urueedi/luci,thesabbir/luci,palmettos/test,florian-shellfire/luci,lcf258/openwrtcn,obsy/luci,bright-things/ionic-luci,sujeet14108/luci,male-puppies/luci,artynet/luci,lcf258/openwrtcn,Hostle/openwrt-luci-multi-user,oneru/luci,david-xiao/luci,rogerpueyo/luci,jlopenwrtluci/luci,teslamint/luci,dwmw2/luci,NeoRaider/luci,jlopenwrtluci/luci,cshore/luci,palmettos/cnLuCI,jorgifumi/luci,Kyklas/luci-proto-hso,jchuang1977/luci-1,cappiewu/luci,teslamint/luci,jchuang1977/luci-1,Noltari/luci,taiha/luci,joaofvieira/luci,db260179/openwrt-bpi-r1-luci,mumuqz/luci,hnyman/luci,marcel-sch/luci,schidler/ionic-luci,LazyZhu/openwrt-luci-trunk-mod,Wedmer/luci,openwrt-es/openwrt-luci,thesabbir/luci,marcel-sch/luci,keyidadi/luci,cshore-firmware/openwrt-luci,Hostle/openwrt-luci-multi-user,keyidadi/luci,palmettos/test,opentechinstitute/luci,kuoruan/luci,hnyman/luci,tobiaswaldvogel/luci,slayerrensky/luci,david-xiao/luci,cappiewu/luci,Noltari/luci,deepak78/new-luci,openwrt/luci,fkooman/luci,remakeelectric/luci,NeoRaider/luci,jorgifumi/luci,dwmw2/luci,teslamint/luci,RuiChen1113/luci,marcel-sch/luci,david-xiao/luci,RuiChen1113/luci,bittorf/luci,sujeet14108/luci,remakeelectric/luci,981213/luci-1,david-xiao/luci,bittorf/luci,nwf/openwrt-luci,Hostle/openwrt-luci-multi-user,joaofvieira/luci,thess/OpenWrt-luci,maxrio/luci981213,opentechinstitute/luci,bittorf/luci,maxrio/luci981213,male-puppies/luci,palmettos/test,db260179/openwrt-bpi-r1-luci,oyido/luci,taiha/luci,joaofvieira/luci,artynet/luci,981213/luci-1,opentechinstitute/luci,mumuqz/luci,tobiaswaldvogel/luci,bittorf/luci,maxrio/luci981213,nmav/luci,MinFu/luci,joaofvieira/luci,Wedmer/luci,sujeet14108/luci,shangjiyu/luci-with-extra,slayerrensky/luci,wongsyrone/luci-1,schidler/ionic-luci,RedSnake64/openwrt-luci-packages,Noltari/luci,ollie27/openwrt_luci,RuiChen1113/luci,maxrio/luci981213,florian-shellfire/luci,RedSnake64/openwrt-luci-packages,NeoRaider/luci,jorgifumi/luci,obsy/luci,teslamint/luci,deepak78/new-luci,florian-shellfire/luci,nwf/openwrt-luci,Hostle/luci,jorgifumi/luci,Hostle/openwrt-luci-multi-user,daofeng2015/luci,Sakura-Winkey/LuCI,NeoRaider/luci,aa65535/luci,oneru/luci,fkooman/luci,fkooman/luci,kuoruan/lede-luci,jorgifumi/luci,RedSnake64/openwrt-luci-packages,keyidadi/luci,jlopenwrtluci/luci,marcel-sch/luci,sujeet14108/luci,obsy/luci,cshore-firmware/openwrt-luci,ReclaimYourPrivacy/cloak-luci,Hostle/luci,981213/luci-1,oyido/luci,nmav/luci,MinFu/luci,MinFu/luci,ff94315/luci-1,openwrt/luci,slayerrensky/luci,thesabbir/luci,harveyhu2012/luci,aa65535/luci,taiha/luci,MinFu/luci,bright-things/ionic-luci,rogerpueyo/luci,kuoruan/lede-luci,harveyhu2012/luci,chris5560/openwrt-luci,shangjiyu/luci-with-extra,cshore/luci,nmav/luci,wongsyrone/luci-1,obsy/luci,maxrio/luci981213,forward619/luci,Noltari/luci,nwf/openwrt-luci,schidler/ionic-luci,dismantl/luci-0.12,Hostle/luci,LazyZhu/openwrt-luci-trunk-mod,shangjiyu/luci-with-extra,wongsyrone/luci-1,Sakura-Winkey/LuCI,artynet/luci,aircross/OpenWrt-Firefly-LuCI,forward619/luci,bittorf/luci,marcel-sch/luci,maxrio/luci981213,bittorf/luci,Wedmer/luci,zhaoxx063/luci,urueedi/luci,harveyhu2012/luci,forward619/luci,cshore-firmware/openwrt-luci,kuoruan/luci,Noltari/luci,florian-shellfire/luci,urueedi/luci,LuttyYang/luci,oneru/luci,zhaoxx063/luci,mumuqz/luci,Noltari/luci,nwf/openwrt-luci,LuttyYang/luci,Hostle/openwrt-luci-multi-user,joaofvieira/luci,kuoruan/lede-luci,RedSnake64/openwrt-luci-packages,shangjiyu/luci-with-extra,bright-things/ionic-luci,chris5560/openwrt-luci,jlopenwrtluci/luci,remakeelectric/luci,nmav/luci,cappiewu/luci,florian-shellfire/luci,cappiewu/luci,rogerpueyo/luci,aa65535/luci,deepak78/new-luci,rogerpueyo/luci,openwrt/luci,sujeet14108/luci,tobiaswaldvogel/luci,male-puppies/luci,harveyhu2012/luci,dismantl/luci-0.12,zhaoxx063/luci,openwrt/luci,mumuqz/luci,Sakura-Winkey/LuCI,aa65535/luci,thesabbir/luci,RuiChen1113/luci,thesabbir/luci,maxrio/luci981213,rogerpueyo/luci,kuoruan/luci,jchuang1977/luci-1,Wedmer/luci,NeoRaider/luci,florian-shellfire/luci,keyidadi/luci,kuoruan/luci,LuttyYang/luci,nmav/luci,dwmw2/luci,LuttyYang/luci,cshore-firmware/openwrt-luci,remakeelectric/luci,fkooman/luci,opentechinstitute/luci,thess/OpenWrt-luci,hnyman/luci,taiha/luci,Sakura-Winkey/LuCI,ff94315/luci-1,chris5560/openwrt-luci,Hostle/openwrt-luci-multi-user,db260179/openwrt-bpi-r1-luci,jchuang1977/luci-1,hnyman/luci,palmettos/test,jlopenwrtluci/luci,shangjiyu/luci-with-extra,MinFu/luci,tobiaswaldvogel/luci,kuoruan/luci,kuoruan/luci,daofeng2015/luci,nmav/luci,aa65535/luci,slayerrensky/luci,joaofvieira/luci,dismantl/luci-0.12,openwrt/luci,artynet/luci,zhaoxx063/luci,palmettos/cnLuCI,male-puppies/luci,Kyklas/luci-proto-hso,tcatm/luci,openwrt-es/openwrt-luci,wongsyrone/luci-1,chris5560/openwrt-luci,male-puppies/luci,cshore-firmware/openwrt-luci,oneru/luci,david-xiao/luci,daofeng2015/luci,dwmw2/luci,remakeelectric/luci,lbthomsen/openwrt-luci,Noltari/luci,male-puppies/luci,ReclaimYourPrivacy/cloak-luci,981213/luci-1,sujeet14108/luci,urueedi/luci,Kyklas/luci-proto-hso,slayerrensky/luci,Hostle/openwrt-luci-multi-user,wongsyrone/luci-1,rogerpueyo/luci,keyidadi/luci,db260179/openwrt-bpi-r1-luci,thess/OpenWrt-luci,dwmw2/luci,Noltari/luci,tcatm/luci,palmettos/test,lbthomsen/openwrt-luci,palmettos/cnLuCI,tcatm/luci,nwf/openwrt-luci,openwrt/luci,LazyZhu/openwrt-luci-trunk-mod,openwrt-es/openwrt-luci,dwmw2/luci,jorgifumi/luci,Hostle/luci,marcel-sch/luci,marcel-sch/luci,lcf258/openwrtcn,oyido/luci,maxrio/luci981213,ReclaimYourPrivacy/cloak-luci,ollie27/openwrt_luci,aa65535/luci,male-puppies/luci,cshore-firmware/openwrt-luci,daofeng2015/luci,fkooman/luci,Wedmer/luci,urueedi/luci,chris5560/openwrt-luci,cshore/luci,oneru/luci,fkooman/luci,dwmw2/luci,jchuang1977/luci-1,RedSnake64/openwrt-luci-packages,palmettos/test,openwrt-es/openwrt-luci,artynet/luci,RuiChen1113/luci,deepak78/new-luci,teslamint/luci,RuiChen1113/luci,Sakura-Winkey/LuCI,palmettos/cnLuCI,palmettos/test,obsy/luci,teslamint/luci,tcatm/luci,urueedi/luci,ollie27/openwrt_luci,urueedi/luci,tobiaswaldvogel/luci,florian-shellfire/luci,Kyklas/luci-proto-hso,rogerpueyo/luci,oneru/luci,palmettos/test,aircross/OpenWrt-Firefly-LuCI,jlopenwrtluci/luci,MinFu/luci,keyidadi/luci,thess/OpenWrt-luci,LuttyYang/luci,cshore/luci,ff94315/luci-1,kuoruan/luci,david-xiao/luci,bright-things/ionic-luci,lcf258/openwrtcn,cappiewu/luci,NeoRaider/luci,harveyhu2012/luci,Wedmer/luci,thess/OpenWrt-luci,tobiaswaldvogel/luci,LuttyYang/luci,male-puppies/luci,mumuqz/luci
70f455a2d61d343da1376619579400e98700130d
src/plugins/core/commands/commandaction.lua
src/plugins/core/commands/commandaction.lua
--- A `action` which will execute a command with matching group/id values. --------------------------------------------------------------------------------- -- -- THE PLUGIN: -- -------------------------------------------------------------------------------- registers itself with the `cp.plugins.actions.actionmanager`. -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- local commands = require("cp.commands") local choices = require("cp.choices") local config = require("cp.config") -------------------------------------------------------------------------------- -- -- THE MODULE: -- --------------------------------------------------------------------------------s local mod = {} local ID = "command" function mod.init(actionmanager) mod._manager = actionmanager mod._manager.addAction(mod) end function mod.id() return ID end function mod.setEnabled(value) config.set("commandActionEnabled", value) mod._manager.refresh() end function mod.isEnabled() return config.get("commandActionEnabled", true) end function mod.toggleEnabled() mod.setEnabled(not mod.isEnabled()) end --- cp.plugins.actions.commandaction.choices() -> table --- Function --- Returns an array of available choices function mod.choices() -- Cache the choices, since commands don't change while the app is running. if not mod._choices then mod._choices = choices.new(ID) for _,id in pairs(commands.groupIds()) do local group = commands.group(id) for _,cmd in pairs(group:getAll()) do local title = cmd:getTitle() if title then local subText = cmd:getSubtitle() if not subText and cmd:getGroup() then subText = i18n(cmd:getGroup() .. "_group") end local params = { group = group:id(), id = cmd:id(), } mod._choices:add(title) :subText(subText) :params(params) :id(mod.getId(params)) end end end end return mod._choices end function mod.getId(params) return ID .. ":" .. string.format("%s:%s", params.group, params.id) end --- cp.plugins.actions.commandaction.execute(params) -> boolean --- Function --- Executes the action with the provided parameters. --- --- Parameters: --- * `params` - A table of parameters, matching the following: --- * `group` - The Command Group ID --- * `id` - The specific Command ID within the group. --- --- * `true` if the action was executed successfully. function mod.execute(params) local group = commands.group(params.group) if group then local cmdId = params.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 function mod.reset() mod._choices = nil end -------------------------------------------------------------------------------- -- -- THE PLUGIN: -- -------------------------------------------------------------------------------- local plugin = { id = "core.commands.commandaction", group = "core", dependencies = { ["core.action.manager"] = "actionmanager", } } function plugin.init(deps) mod.init(deps.actionmanager) return mod end return plugin
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- C O M M A N D A C T I O N -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --- === core.commands.commandaction === --- --- 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 commands = require("cp.commands") local config = require("cp.config") local dialog = require("cp.dialog") -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local mod = {} local ID = "command" function mod.init(actionmanager) mod._manager = actionmanager mod._manager.addAction(mod) end function mod.id() return ID end function mod.setEnabled(value) config.set("commandActionEnabled", value) mod._manager.refresh() end function mod.isEnabled() return config.get("commandActionEnabled", true) end function mod.toggleEnabled() mod.setEnabled(not mod.isEnabled()) end --- core.commands.commandaction.choices() -> table --- Function --- Returns an array of available choices function mod.choices() -- Cache the choices, since commands don't change while the app is running. if not mod._choices then mod._choices = choices.new(ID) for _,id in pairs(commands.groupIds()) do local group = commands.group(id) for _,cmd in pairs(group:getAll()) do local title = cmd:getTitle() if title then local subText = cmd:getSubtitle() if not subText and cmd:getGroup() then subText = i18n(cmd:getGroup() .. "_group") end local params = { group = group:id(), id = cmd:id(), } mod._choices:add(title) :subText(subText) :params(params) :id(mod.getId(params)) end end end end return mod._choices end function mod.getId(params) return ID .. ":" .. string.format("%s:%s", params.group, params.id) end --- core.commands.commandaction.execute(params) -> boolean --- Function --- Executes the action with the provided parameters. --- --- Parameters: --- * `params` - A table of parameters, matching the following: --- * `group` - The Command Group ID --- * `id` - The specific Command ID within the group. --- --- * `true` if the action was executed successfully. function mod.execute(params) local group = commands.group(params.group) if group then local cmdId = params.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 function mod.reset() mod._choices = nil end -------------------------------------------------------------------------------- -- -- THE PLUGIN: -- -------------------------------------------------------------------------------- local plugin = { id = "core.commands.commandaction", group = "core", dependencies = { ["core.action.manager"] = "actionmanager", } } function plugin.init(deps) mod.init(deps.actionmanager) return mod end return plugin
Bug Fix
Bug Fix - Fixed missing cp.dialog in commandaction
Lua
mit
cailyoung/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,fcpxhacks/fcpxhacks,CommandPost/CommandPost,cailyoung/CommandPost,cailyoung/CommandPost,CommandPost/CommandPost
2e73111a50846a6d15b7e22659dd842fd149115f
src_trunk/resources/boatshop-system/s_boatshop_system.lua
src_trunk/resources/boatshop-system/s_boatshop_system.lua
-- //////////////////////////////////// -- // MYSQL // -- //////////////////////////////////// sqlUsername = exports.mysql:getMySQLUsername() sqlPassword = exports.mysql:getMySQLPassword() sqlDB = exports.mysql:getMySQLDBName() sqlHost = exports.mysql:getMySQLHost() sqlPort = exports.mysql:getMySQLPort() handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) function checkMySQL() if not (mysql_ping(handler)) then handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) end end setTimer(checkMySQL, 300000, 0) function closeMySQL() if (handler) then mysql_close(handler) end end addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL) -- //////////////////////////////////// -- // MYSQL END // -- //////////////////////////////////// carshopPickup = createPickup(-2433.3547363281, 2313.8015136719, 4.984375, 3, 1239) exports.pool.allocatePickup(carshopPickup) blip = createBlip(-2433.3547363281, 2313.8015136719, 4.984375, 9) exports.pool:allocateElement(blip) function pickupUse(thePlayer) triggerClientEvent(thePlayer, "showBoatshopUI", thePlayer) end addEventHandler("onPickupHit", carshopPickup, pickupUse) function buyCar(car, cost, id, col1, col2) outputChatBox("You bought a " .. car .. " for " .. cost .. "$. Enjoy!", source, 255, 194, 14) outputChatBox("You can set this boats spawn position by parking it and typing /vehpos", source, 255, 194, 14) outputChatBox("Press I and use your car key to unlock this boat.", source, 255, 194, 14) makeCar(source, car, cost, id, col1, col2) end addEvent("buyBoat", true) addEventHandler("buyBoat", getRootElement(), buyCar) function makeCar(thePlayer, car, cost, id, col1, col2) local rx = 0 local ry = 0 local rz = 270 local x, y, z = -2414.4711914063, 2304.0166015625, -0.55000001192093 setElementPosition(thePlayer, -2416.708984375, 2310.5837402344, 1.5305557250977) setPedRotation(thePlayer, 188) local username = getPlayerName(thePlayer) local dbid = getElementData(thePlayer, "dbid") exports.global:takePlayerSafeMoney(thePlayer, tonumber(cost)) local letter1 = exports.global:randChar() local letter2 = exports.global:randChar() local plate = letter1 .. letter2 .. math.random(0, 9) .. " " .. math.random(1000, 9999) local veh = createVehicle(id, x, y, z, 0, 0, rz, plate) exports.pool:allocateElement(veh) setElementData(veh, "fuel", 100) setVehicleRespawnPosition(veh, x, y, z, 0, 0, rz) setVehicleLocked(veh, false) local locked = 0 setVehicleColor(veh, col1, col2, col1, col2) setVehicleOverrideLights(veh, 1) setVehicleEngineState(veh, false) setVehicleFuelTankExplodable(veh, false) local query = mysql_query(handler, "INSERT INTO vehicles SET model='" .. id .. "', x='" .. x .. "', y='" .. y .. "', z='" .. z .. "', rotx='" .. rx .. "', roty='" .. ry .. "', rotz='" .. rz .. "', color1='" .. col1 .. "', color2='" .. col2 .. "', faction='-1', owner='" .. dbid .. "', plate='" .. plate .. "', currx='" .. x .. "', curry='" .. y .. "', currz='" .. z .. "', currrx='0', currry='0', currrz='" .. rz .. "', locked='" .. locked .. "'") if (query) then mysql_free_result(query) local id = mysql_insert_id(handler) exports.global:givePlayerItem(thePlayer, 3, tonumber(id)) setElementData(veh, "dbid", tonumber(id), false) setElementData(veh, "fuel", 100) setElementData(veh, "engine", 0, false) setElementData(veh, "oldx", x, false) setElementData(veh, "oldy", y, false) setElementData(veh, "oldz", z, false) setElementData(veh, "faction", -1, false) setElementData(veh, "owner", dbid, false) setElementData(veh, "job", 0, false) setElementData(veh, "locked", locked, false) triggerEvent("onVehicleSpawn", veh) exports.global:givePlayerAchievement(thePlayer, 27) -- boat trip end end
-- //////////////////////////////////// -- // MYSQL // -- //////////////////////////////////// sqlUsername = exports.mysql:getMySQLUsername() sqlPassword = exports.mysql:getMySQLPassword() sqlDB = exports.mysql:getMySQLDBName() sqlHost = exports.mysql:getMySQLHost() sqlPort = exports.mysql:getMySQLPort() handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) function checkMySQL() if not (mysql_ping(handler)) then handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) end end setTimer(checkMySQL, 300000, 0) function closeMySQL() if (handler) then mysql_close(handler) end end addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL) -- //////////////////////////////////// -- // MYSQL END // -- //////////////////////////////////// carshopPickup = createPickup(-2433.3547363281, 2313.8015136719, 4.984375, 3, 1239) exports.pool.allocatePickup(carshopPickup) blip = createBlip(-2433.3547363281, 2313.8015136719, 4.984375, 9) exports.pool:allocateElement(blip) function pickupUse(thePlayer) triggerClientEvent(thePlayer, "showBoatshopUI", thePlayer) end addEventHandler("onPickupHit", carshopPickup, pickupUse) function buyCar(car, cost, id, col1, col2) outputChatBox("You bought a " .. car .. " for " .. cost .. "$. Enjoy!", source, 255, 194, 14) outputChatBox("You can set this boats spawn position by parking it and typing /vehpos", source, 255, 194, 14) outputChatBox("Press I and use your car key to unlock this boat.", source, 255, 194, 14) makeCar(source, car, cost, id, col1, col2) end addEvent("buyBoat", true) addEventHandler("buyBoat", getRootElement(), buyCar) function SmallestVehicleID( ) -- Loop which finds the smallest ID in the SQL instead of the biggest one. UsedID = {} local id = 0 local answer = 2 -- 0 = ID = 1 . 1 =Suitable ID found. 2= Still searching for ID. local highest = 0 local result = mysql_query(handler, "SELECT id FROM vehicles") if(result) then for result, row in mysql_rows(result) do UsedID[tonumber(row[1])] = 1 if (tonumber(row[1]) > highest) then highest = tonumber(row[1]) end end end if(highest > 0) then for i = 1, highest do if(UsedID[i] ~= 1) then answer = 1 id = i break end end else answer = 0 id = 1 end if(answer == 2) then answer = 1 id = highest + 1 end if(answer ~= 2) then return id else return false end end function makeCar(thePlayer, car, cost, id, col1, col2) local rx = 0 local ry = 0 local rz = 270 local x, y, z = -2414.4711914063, 2304.0166015625, -0.55000001192093 setElementPosition(thePlayer, -2416.708984375, 2310.5837402344, 1.5305557250977) setPedRotation(thePlayer, 188) local username = getPlayerName(thePlayer) local dbid = getElementData(thePlayer, "dbid") exports.global:takePlayerSafeMoney(thePlayer, tonumber(cost)) local letter1 = exports.global:randChar() local letter2 = exports.global:randChar() local plate = letter1 .. letter2 .. math.random(0, 9) .. " " .. math.random(1000, 9999) local veh = createVehicle(id, x, y, z, 0, 0, rz, plate) exports.pool:allocateElement(veh) setElementData(veh, "fuel", 100) setVehicleRespawnPosition(veh, x, y, z, 0, 0, rz) setVehicleLocked(veh, false) local locked = 0 setVehicleColor(veh, col1, col2, col1, col2) setVehicleOverrideLights(veh, 1) setVehicleEngineState(veh, false) setVehicleFuelTankExplodable(veh, false) local insertid = SmallestVehicleID() local query = mysql_query(handler, "INSERT INTO vehicles SET id='" .. insertid .. "', model='" .. id .. "', x='" .. x .. "', y='" .. y .. "', z='" .. z .. "', rotx='" .. rx .. "', roty='" .. ry .. "', rotz='" .. rz .. "', color1='" .. col1 .. "', color2='" .. col2 .. "', faction='-1', owner='" .. dbid .. "', plate='" .. plate .. "', currx='" .. x .. "', curry='" .. y .. "', currz='" .. z .. "', currrx='0', currry='0', currrz='" .. rz .. "', locked='" .. locked .. "'") if (query) then mysql_free_result(query) exports.global:givePlayerItem(thePlayer, 3, tonumber(id)) setElementData(veh, "dbid", tonumber(insertid), false) setElementData(veh, "fuel", 100) setElementData(veh, "engine", 0, false) setElementData(veh, "oldx", x, false) setElementData(veh, "oldy", y, false) setElementData(veh, "oldz", z, false) setElementData(veh, "faction", -1, false) setElementData(veh, "owner", dbid, false) setElementData(veh, "job", 0, false) setElementData(veh, "locked", locked, false) triggerEvent("onVehicleSpawn", veh) exports.global:givePlayerAchievement(thePlayer, 27) -- boat trip end end
Boat shop fix
Boat shop fix git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@734 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
712a2b44f09baeb6a70c5dbf83ed68ea9d5d1aee
module/admin-core/src/controller/admin/index.lua
module/admin-core/src/controller/admin/index.lua
module("ffluci.controller.admin.index", package.seeall) function action_wizard() if ffluci.http.formvalue("ip") then return configure_freifunk() end local ifaces = {} local wldevs = ffluci.model.uci.show("wireless") if wldevs then for k, v in pairs(wldevs.wireless) do if v[".type"] == "wifi-device" then table.insert(ifaces, k) end end end ffluci.template.render("admin_index/wizard", {ifaces=ifaces}) end function configure_freifunk() local ip = ffluci.http.formvalue("ip") local uci = ffluci.model.uci.Session() -- Configure FF-Interface uci:del("network", "ff") uci:del("network", "ffdhcp") uci:set("network", "ff", nil, "interface") uci:set("network", "ff", "type", "bridge") uci:set("network", "ff", "proto", "static") uci:set("network", "ff", "ipaddr", ip) uci:set("network", "ff", "netmask", uci:get("freifunk", "community", "mask")) uci:set("network", "ff", "dns", uci:get("freifunk", "community", "dns")) -- Enable internal routing uci:set("freifunk", "routing", "internal", "1") -- Enable internet routing if ffluci.http.formvalue("shareinet") then uci:set("freifunk", "routing", "internet", "1") else uci:set("freifunk", "routing", "internet", "0") end -- Configure DHCP if ffluci.http.formvalue("dhcp") then local dhcpnet = uci:get("freifunk", "community", "dhcp"):match("^([0-9]+)") local dhcpip = ip:gsub("^[0-9]+", dhcpnet) uci:set("network", "ffdhcp", nil, "interface") uci:set("network", "ffdhcp", "proto", "static") uci:set("network", "ffdhcp", "ifname", "br-ff:dhcp") uci:set("network", "ffdhcp", "ipaddr", dhcpip) uci:set("network", "ffdhcp", "netmask", uci:get("freifunk", "community", "dhcpmask")) end -- Configure OLSR if ffluci.http.formvalue("olsr") and uci:show("olsr") then for k, v in pairs(uci:show("olsr").olsr) do if v[".type"] == "Interface" or v[".type"] == "LoadPlugin" then uci:del("olsr", "k") end end if ffluci.http.formvalue("shareinet") then uci:set("olsr", "dyn_gw", nil, "LoadPlugin") uci:set("olsr", "dyn_gw", "Library", "olsrd_dyn_gw.so.0.4") end uci:set("olsr", "nameservice", nil, "LoadPlugin") uci:set("olsr", "nameservice", "Library", "olsrd_nameservice.so.0.3") uci:set("olsr", "nameservice", "name", ip:gsub("%.", "-")) uci:set("olsr", "nameservice", "hosts_file", "/var/etc/hosts") uci:set("olsr", "nameservice", "suffix", ".olsr") uci:set("olsr", "nameservice", "latlon_infile", "/tmp/latlon.txt") uci:set("olsr", "txtinfo", nil, "LoadPlugin") uci:set("olsr", "txtinfo", "Library", "olsrd_txtinfo.so.0.1") uci:set("olsr", "txtinfo", "Accept", "127.0.0.1") local oif = uci:add("olsr", "Interface") uci:set("olsr", oif, "Interface", "ff") uci:set("olsr", oif, "HelloInterval", "6.0") uci:set("olsr", oif, "HelloValidityTime", "108.0") uci:set("olsr", oif, "TcInterval", "4.0") uci:set("olsr", oif, "TcValidityTime", "324.0") uci:set("olsr", oif, "MidInterval", "18.0") uci:set("olsr", oif, "MidValidityTime", "324.0") uci:set("olsr", oif, "HnaInterval", "18.0") uci:set("olsr", oif, "HnaValidityTime", "108.0") end -- Configure Wifi local wifi = ffluci.http.formvalue("wifi") local wcfg = uci:show("wireless") if type(wifi) == "table" and wcfg then for iface, v in pairs(wifi) do if wcfg[iface] then -- Cleanup for k, v in pairs(wcfg.wireless) do if v[".type"] == "wifi-iface" and v.device == iface then uci:del("wireless", k) end end uci:set("wireless", iface, "disabled", "0") uci:set("wireless", iface, "mode", "11g") uci:set("wireless", iface, "txantenna", 1) uci:set("wireless", iface, "rxantenna", 1) uci:set("wireless", iface, "channel", uci:get("freifunk", "community", "channel")) local wif = uci:add("wireless", "wifi-iface") uci:set("wireless", wif, "device", iface) uci:set("wireless", wif, "network", "ff") uci:set("wireless", wif, "mode", "adhoc") uci:set("wireless", wif, "ssid", uci:get("freifunk", "community", "essid")) uci:set("wireless", wif, "bssid", uci:get("freifunk", "community", "bssid")) uci:set("wireless", wif, "txpower", 13) end end end ffluci.http.request_redirect("admin", "uci", "changes") end
module("ffluci.controller.admin.index", package.seeall) function action_wizard() if ffluci.http.formvalue("ip") then return configure_freifunk() end local ifaces = {} local wldevs = ffluci.model.uci.show("wireless") if wldevs then for k, v in pairs(wldevs.wireless) do if v[".type"] == "wifi-device" then table.insert(ifaces, k) end end end ffluci.template.render("admin_index/wizard", {ifaces=ifaces}) end function configure_freifunk() local ip = ffluci.http.formvalue("ip") local uci = ffluci.model.uci.Session() -- Configure FF-Interface uci:del("network", "ff") uci:del("network", "ffdhcp") uci:set("network", "ff", nil, "interface") uci:set("network", "ff", "type", "bridge") uci:set("network", "ff", "proto", "static") uci:set("network", "ff", "ipaddr", ip) uci:set("network", "ff", "netmask", uci:get("freifunk", "community", "mask")) uci:set("network", "ff", "dns", uci:get("freifunk", "community", "dns")) -- Enable internal routing uci:set("freifunk", "routing", "internal", "1") -- Enable internet routing if ffluci.http.formvalue("shareinet") then uci:set("freifunk", "routing", "internet", "1") else uci:set("freifunk", "routing", "internet", "0") end -- Configure DHCP if ffluci.http.formvalue("dhcp") then local dhcpnet = uci:get("freifunk", "community", "dhcp"):match("^([0-9]+)") local dhcpip = ip:gsub("^[0-9]+", dhcpnet) uci:set("network", "ffdhcp", nil, "interface") uci:set("network", "ffdhcp", "proto", "static") uci:set("network", "ffdhcp", "ifname", "br-ff:dhcp") uci:set("network", "ffdhcp", "ipaddr", dhcpip) uci:set("network", "ffdhcp", "netmask", uci:get("freifunk", "community", "dhcpmask")) local splash = uci:show("luci_splash") if splash then for k, v in pairs(splash.luci_splash) do if v[".type"] == "iface" then uci:del("luci_splash", k) end end local sk = uci:add("luci_splash", "iface") uci:set("luci_splash", sk, "network", "ffdhcp") end end -- Configure OLSR if ffluci.http.formvalue("olsr") and uci:show("olsr") then for k, v in pairs(uci:show("olsr").olsr) do if v[".type"] == "Interface" or v[".type"] == "LoadPlugin" then uci:del("olsr", k) end end if ffluci.http.formvalue("shareinet") then uci:set("olsr", "dyn_gw", nil, "LoadPlugin") uci:set("olsr", "dyn_gw", "Library", "olsrd_dyn_gw.so.0.4") end uci:set("olsr", "nameservice", nil, "LoadPlugin") uci:set("olsr", "nameservice", "Library", "olsrd_nameservice.so.0.3") uci:set("olsr", "nameservice", "name", ip:gsub("%.", "-")) uci:set("olsr", "nameservice", "hosts_file", "/var/etc/hosts") uci:set("olsr", "nameservice", "suffix", ".olsr") uci:set("olsr", "nameservice", "latlon_infile", "/tmp/latlon.txt") uci:set("olsr", "txtinfo", nil, "LoadPlugin") uci:set("olsr", "txtinfo", "Library", "olsrd_txtinfo.so.0.1") uci:set("olsr", "txtinfo", "Accept", "127.0.0.1") local oif = uci:add("olsr", "Interface") uci:set("olsr", oif, "Interface", "ff") uci:set("olsr", oif, "HelloInterval", "6.0") uci:set("olsr", oif, "HelloValidityTime", "108.0") uci:set("olsr", oif, "TcInterval", "4.0") uci:set("olsr", oif, "TcValidityTime", "324.0") uci:set("olsr", oif, "MidInterval", "18.0") uci:set("olsr", oif, "MidValidityTime", "324.0") uci:set("olsr", oif, "HnaInterval", "18.0") uci:set("olsr", oif, "HnaValidityTime", "108.0") end -- Configure Wifi local wifi = ffluci.http.formvalue("wifi") local wcfg = uci:show("wireless") if type(wifi) == "table" and wcfg then for iface, v in pairs(wifi) do if wcfg[iface] then -- Cleanup for k, v in pairs(wcfg.wireless) do if v[".type"] == "wifi-iface" and v.device == iface then uci:del("wireless", k) end end uci:set("wireless", iface, "disabled", "0") uci:set("wireless", iface, "mode", "11g") uci:set("wireless", iface, "txantenna", 1) uci:set("wireless", iface, "rxantenna", 1) uci:set("wireless", iface, "channel", uci:get("freifunk", "community", "channel")) local wif = uci:add("wireless", "wifi-iface") uci:set("wireless", wif, "device", iface) uci:set("wireless", wif, "network", "ff") uci:set("wireless", wif, "mode", "adhoc") uci:set("wireless", wif, "ssid", uci:get("freifunk", "community", "essid")) uci:set("wireless", wif, "bssid", uci:get("freifunk", "community", "bssid")) uci:set("wireless", wif, "txpower", 13) end end end ffluci.http.request_redirect("admin", "uci", "changes") end
* Fixed Freifunk wizard
* Fixed Freifunk wizard git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@1959 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
ThingMesh/openwrt-luci,freifunk-gluon/luci,gwlim/luci,alxhh/piratenluci,stephank/luci,Canaan-Creative/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,jschmidlapp/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,Flexibity/luci,8devices/carambola2-luci,Flexibity/luci,projectbismark/luci-bismark,ch3n2k/luci,eugenesan/openwrt-luci,jschmidlapp/luci,zwhfly/openwrt-luci,freifunk-gluon/luci,gwlim/luci,freifunk-gluon/luci,projectbismark/luci-bismark,phi-psi/luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,vhpham80/luci,alxhh/piratenluci,jschmidlapp/luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,projectbismark/luci-bismark,Canaan-Creative/luci,freifunk-gluon/luci,eugenesan/openwrt-luci,gwlim/luci,vhpham80/luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,alxhh/piratenluci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,alxhh/piratenluci,saraedum/luci-packages-old,alxhh/piratenluci,saraedum/luci-packages-old,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,jschmidlapp/luci,vhpham80/luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,yeewang/openwrt-luci,saraedum/luci-packages-old,phi-psi/luci,phi-psi/luci,8devices/carambola2-luci,phi-psi/luci,8devices/carambola2-luci,phi-psi/luci,phi-psi/luci,freifunk-gluon/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,yeewang/openwrt-luci,Canaan-Creative/luci,freifunk-gluon/luci,yeewang/openwrt-luci,jschmidlapp/luci,Flexibity/luci,zwhfly/openwrt-luci,freifunk-gluon/luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,projectbismark/luci-bismark,projectbismark/luci-bismark,jschmidlapp/luci,yeewang/openwrt-luci,vhpham80/luci,gwlim/luci,phi-psi/luci,jschmidlapp/luci,stephank/luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,yeewang/openwrt-luci,zwhfly/openwrt-luci,projectbismark/luci-bismark,Canaan-Creative/luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,ch3n2k/luci,jschmidlapp/luci,Canaan-Creative/luci,gwlim/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,gwlim/luci,ch3n2k/luci,zwhfly/openwrt-luci,alxhh/piratenluci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,Flexibity/luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,eugenesan/openwrt-luci,Flexibity/luci,stephank/luci,zwhfly/openwrt-luci,alxhh/piratenluci,8devices/carambola2-luci,ch3n2k/luci,yeewang/openwrt-luci,stephank/luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,dtaht/cerowrt-luci-3.3,stephank/luci,8devices/carambola2-luci,Flexibity/luci,eugenesan/openwrt-luci,ch3n2k/luci
bfb5a3dd96bf505cd16745566a9f5c2d33a24a0d
vim/lua/madx-config.lua
vim/lua/madx-config.lua
-------------------------------------------------------------------------------- -- Utils local buf_map = function(bufnr, mode, lhs, rhs, opts) vim.api.nvim_buf_set_keymap(bufnr, mode, lhs, rhs, opts or { silent = true, }) end local has_words_before = function() local line, col = unpack(vim.api.nvim_win_get_cursor(0)) return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match("%s") == nil end -------------------------------------------------------------------------------- -- Trouble require("trouble").setup { icons = false, fold_open = "v", fold_closed = ">", indent_lines = false, signs = { error = "error", warning = "warn", hint = "hint", information = "info" }, use_diagnostic_signs = false } -------------------------------------------------------------------------------- -- Automatic LSP server installs local lspconfig = require("lspconfig") require("nvim-lsp-installer").setup { automatic_installation = true } -------------------------------------------------------------------------------- -- Treesitter require('nvim-treesitter.configs').setup { ensure_installed = { "javascript", "typescript", "html", "markdown", "html", "css" }, highlight = { enable = true, additional_vim_regex_highlighting = false, }, indent = { enable = true, }, autotag = { enable = true, }, context_commentstring = { enable = true, }, } -------------------------------------------------------------------------------- -- nvim-cmp vim.api.nvim_set_option("completeopt", "menu,menuone,noselect") local cmp = require("cmp") cmp.setup({ mapping = cmp.mapping.preset.insert({ ['<C-b>'] = cmp.mapping.scroll_docs(-4), ['<C-f>'] = cmp.mapping.scroll_docs(4), ['<C-Space>'] = cmp.mapping.complete(), ['<C-e>'] = cmp.mapping.abort(), ['<CR>'] = cmp.mapping(function(fallback) if cmp.visible() then cmp.confirm({ select = false }) else fallback() end end), ["<Tab>"] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_next_item() elseif has_words_before() then cmp.complete() else fallback() end end, { "i", "s" }), ["<S-Tab>"] = cmp.mapping(function() if cmp.visible() then cmp.select_prev_item() end end, { "i", "s" }), }), sources = cmp.config.sources({ { name = 'nvim_lsp' }, { name = 'buffer' }, { name = 'luasnip' }, { name = 'path' }, -- { name = 'cmdline' }, }), snippet = { expand = function(args) require('luasnip').lsp_expand(args.body) end, } }) local capabilities = require("cmp_nvim_lsp").update_capabilities(vim.lsp.protocol.make_client_capabilities()) -------------------------------------------------------------------------------- -- LSP servers configurations local on_attach = function(client, bufnr) vim.cmd("command! LspDef lua vim.lsp.buf.definition()") vim.cmd("command! LspFormatting lua vim.lsp.buf.formatting()") vim.cmd("command! LspCodeAction lua vim.lsp.buf.code_action()") vim.cmd("command! LspHover lua vim.lsp.buf.hover()") vim.cmd("command! LspRename lua vim.lsp.buf.rename()") vim.cmd("command! LspRefs lua vim.lsp.buf.references()") vim.cmd("command! LspTypeDef lua vim.lsp.buf.type_definition()") vim.cmd("command! LspImplementation lua vim.lsp.buf.implementation()") vim.cmd("command! LspDiagPrev lua vim.diagnostic.goto_prev()") vim.cmd("command! LspDiagNext lua vim.diagnostic.goto_next()") vim.cmd("command! LspDiagLine lua vim.diagnostic.open_float()") vim.cmd("command! LspSignatureHelp lua vim.lsp.buf.signature_help()") buf_map(bufnr, "n", "<Leader>gd", ":LspDef<CR>") buf_map(bufnr, "n", "<Leader>gr", ":LspRename<CR>") buf_map(bufnr, "n", "<Leader>gt", ":LspTypeDef<CR>") buf_map(bufnr, "n", "<Leader>gg", ":LspHover<CR>") buf_map(bufnr, "n", "<Leader>gn", ":LspDiagPrev<CR>") buf_map(bufnr, "n", "<Leader>gp", ":LspDiagNext<CR>") buf_map(bufnr, "n", "<Leader>g<space>", ":LspCodeAction<CR>") buf_map(bufnr, "n", "<Leader>gl", ":LspDiagLine<CR>") buf_map(bufnr, "i", "<C-x><C-x>", "<cmd> LspSignatureHelp<CR>") end for _, lspserver in ipairs({ "intelephense", "tailwindcss", "vimls", "cssls" }) do lspconfig[lspserver].setup { capabilities = capabilities, on_attach = on_attach, } end lspconfig.tsserver.setup({ capabilities = capabilities, on_attach = function(client, bufnr) client.server_capabilities.documentFormattingProvider = false client.server_capabilities.documentRangeFormattingProvider = false local ts_utils = require("nvim-lsp-ts-utils") ts_utils.setup({}) ts_utils.setup_client(client) on_attach(client, bufnr) end }) lspconfig.sumneko_lua.setup({ capabilities = capabilities, on_attach = on_attach, settings = { Lua = { diagnostics = { globals = { "vim" }, }, }, }, }) -------------------------------------------------------------------------------- -- null-ls local null_ls = require("null-ls") null_ls.setup({ sources = { null_ls.builtins.diagnostics.eslint_d, null_ls.builtins.code_actions.eslint_d, -- null_ls.builtins.formatting.eslint_d, null_ls.builtins.formatting.prettierd, }, on_attach = function() vim.cmd("autocmd BufWritePre <buffer> lua vim.lsp.buf.format()") end }) -------------------------------------------------------------------------------- -- pears require("pears").setup() -------------------------------------------------------------------------------- -- gitsigns require("gitsigns").setup({ current_line_blame = true, current_line_blame_opts = { virt_text = true, virt_text_pos = 'eol', delay = 200, ignore_whitespace = false, }, current_line_blame_formatter = '-- <author> - <author_time:%Y-%m-%d> - <summary>', }) -------------------------------------------------------------------------------- -- nvim-treesitter-context require('treesitter-context').setup({ enable = true, max_lines = 0, trim_scope = 'outer' })
-------------------------------------------------------------------------------- -- Utils local buf_map = function(bufnr, mode, lhs, rhs, opts) vim.api.nvim_buf_set_keymap(bufnr, mode, lhs, rhs, opts or { silent = true, }) end local has_words_before = function() local line, col = unpack(vim.api.nvim_win_get_cursor(0)) return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match("%s") == nil end -------------------------------------------------------------------------------- -- Trouble require("trouble").setup { icons = false, fold_open = "v", fold_closed = ">", indent_lines = false, signs = { error = "error", warning = "warn", hint = "hint", information = "info" }, use_diagnostic_signs = false } -------------------------------------------------------------------------------- -- Automatic LSP server installs local lspconfig = require("lspconfig") require("nvim-lsp-installer").setup { automatic_installation = true } -------------------------------------------------------------------------------- -- Treesitter require('nvim-treesitter.configs').setup { ensure_installed = { "javascript", "typescript", "html", "markdown", "html", "css" }, highlight = { enable = true, additional_vim_regex_highlighting = false, }, indent = { enable = true, }, autotag = { enable = true, }, context_commentstring = { enable = true, }, } -------------------------------------------------------------------------------- -- nvim-cmp vim.api.nvim_set_option("completeopt", "menu,menuone,noselect") local cmp = require("cmp") cmp.setup({ mapping = cmp.mapping.preset.insert({ ['<C-b>'] = cmp.mapping.scroll_docs(-4), ['<C-f>'] = cmp.mapping.scroll_docs(4), ['<C-Space>'] = cmp.mapping.complete(), ['<C-e>'] = cmp.mapping.abort(), ['<CR>'] = cmp.mapping(function(fallback) if cmp.visible() then cmp.confirm({ select = false }) else fallback() end end), ["<Tab>"] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_next_item() elseif has_words_before() then cmp.complete() else fallback() end end, { "i", "s" }), ["<S-Tab>"] = cmp.mapping(function() if cmp.visible() then cmp.select_prev_item() end end, { "i", "s" }), }), sources = cmp.config.sources({ { name = 'nvim_lsp' }, { name = 'buffer' }, { name = 'luasnip' }, { name = 'path' }, -- { name = 'cmdline' }, }), snippet = { expand = function(args) require('luasnip').lsp_expand(args.body) end, } }) local capabilities = require("cmp_nvim_lsp").default_capabilities() -------------------------------------------------------------------------------- -- LSP servers configurations local on_attach = function(client, bufnr) vim.cmd("command! LspDef lua vim.lsp.buf.definition()") vim.cmd("command! LspFormatting lua vim.lsp.buf.formatting()") vim.cmd("command! LspCodeAction lua vim.lsp.buf.code_action()") vim.cmd("command! LspHover lua vim.lsp.buf.hover()") vim.cmd("command! LspRename lua vim.lsp.buf.rename()") vim.cmd("command! LspRefs lua vim.lsp.buf.references()") vim.cmd("command! LspTypeDef lua vim.lsp.buf.type_definition()") vim.cmd("command! LspImplementation lua vim.lsp.buf.implementation()") vim.cmd("command! LspDiagPrev lua vim.diagnostic.goto_prev()") vim.cmd("command! LspDiagNext lua vim.diagnostic.goto_next()") vim.cmd("command! LspDiagLine lua vim.diagnostic.open_float()") vim.cmd("command! LspSignatureHelp lua vim.lsp.buf.signature_help()") buf_map(bufnr, "n", "<Leader>gd", ":LspDef<CR>") buf_map(bufnr, "n", "<Leader>gr", ":LspRename<CR>") buf_map(bufnr, "n", "<Leader>gt", ":LspTypeDef<CR>") buf_map(bufnr, "n", "<Leader>gg", ":LspHover<CR>") buf_map(bufnr, "n", "<Leader>gn", ":LspDiagPrev<CR>") buf_map(bufnr, "n", "<Leader>gp", ":LspDiagNext<CR>") buf_map(bufnr, "n", "<Leader>g<space>", ":LspCodeAction<CR>") buf_map(bufnr, "n", "<Leader>gl", ":LspDiagLine<CR>") buf_map(bufnr, "i", "<C-x><C-x>", "<cmd> LspSignatureHelp<CR>") end for _, lspserver in ipairs({ "intelephense", "tailwindcss", "vimls", "cssls" }) do lspconfig[lspserver].setup { capabilities = capabilities, on_attach = on_attach, } end lspconfig.tsserver.setup({ capabilities = capabilities, on_attach = function(client, bufnr) client.server_capabilities.documentFormattingProvider = false client.server_capabilities.documentRangeFormattingProvider = false local ts_utils = require("nvim-lsp-ts-utils") ts_utils.setup({}) ts_utils.setup_client(client) on_attach(client, bufnr) end }) lspconfig.sumneko_lua.setup({ capabilities = capabilities, on_attach = on_attach, settings = { Lua = { diagnostics = { globals = { "vim" }, }, }, }, }) -------------------------------------------------------------------------------- -- null-ls local null_ls = require("null-ls") null_ls.setup({ sources = { null_ls.builtins.diagnostics.eslint_d, null_ls.builtins.code_actions.eslint_d, -- null_ls.builtins.formatting.eslint_d, null_ls.builtins.formatting.prettierd, }, on_attach = function() vim.cmd("autocmd BufWritePre <buffer> lua vim.lsp.buf.format()") end }) -------------------------------------------------------------------------------- -- pears require("pears").setup() -------------------------------------------------------------------------------- -- gitsigns require("gitsigns").setup({ current_line_blame = true, current_line_blame_opts = { virt_text = true, virt_text_pos = 'eol', delay = 200, ignore_whitespace = false, }, current_line_blame_formatter = '-- <author> - <author_time:%Y-%m-%d> - <summary>', }) -------------------------------------------------------------------------------- -- nvim-treesitter-context require('treesitter-context').setup({ enable = true, max_lines = 0, trim_scope = 'outer' })
fix(vim): Update deprecacted cmp-nvim-lsp config
fix(vim): Update deprecacted cmp-nvim-lsp config
Lua
mit
madx/propane
1ef19f7b56c665a38b64b518789e89a93030f383
onmt/translate/DecoderAdvancer.lua
onmt/translate/DecoderAdvancer.lua
--[[ DecoderAdvancer is an implementation of the interface Advancer for specifyinghow to advance one step in decoder. --]] local DecoderAdvancer = torch.class('DecoderAdvancer', 'Advancer') --[[ Constructor. Parameters: * `decoder` - an `onmt.Decoder` object. * `batch` - an `onmt.data.Batch` object. * `context` - encoder output (batch x n x rnnSize). * `max_sent_length` - optional, maximum output sentence length. * `max_num_unks` - optional, maximum number of UNKs. * `decStates` - optional, initial decoder states. * `dicts` - optional, dictionary for additional features. * `updateSeqLengthFunc` - optional, sequence length adaptation function after encoder --]] function DecoderAdvancer:__init(decoder, batch, context, max_sent_length, max_num_unks, decStates, dicts, length_norm, coverage_norm, eos_norm, updateSeqLengthFunc) self.decoder = decoder self.batch = batch self.context = context self.max_sent_length = max_sent_length or math.huge self.max_num_unks = max_num_unks or math.huge self.length_norm = length_norm or 0.0 self.coverage_norm = coverage_norm or 0.0 self.eos_norm = eos_norm or 0.0 self.decStates = decStates or onmt.utils.Tensor.initTensorTable( decoder.args.numEffectiveLayers, onmt.utils.Cuda.convert(torch.Tensor()), { self.batch.size, decoder.args.rnnSize }) self.dicts = dicts self.updateSeqLengthFunc = updateSeqLengthFunc end --[[Returns an initial beam. Returns: * `beam` - an `onmt.translate.Beam` object. --]] function DecoderAdvancer:initBeam() local tokens = onmt.utils.Cuda.convert(torch.IntTensor(self.batch.size)):fill(onmt.Constants.BOS) local features = {} if self.dicts then for j = 1, #self.dicts.tgt.features do features[j] = torch.IntTensor(self.batch.size):fill(onmt.Constants.EOS) end end local sourceSizes = onmt.utils.Cuda.convert(self.batch.sourceSize) local attnProba = torch.FloatTensor(self.batch.size, self.context:size(2)):fill(0.0001) -- Mask padding for i = 1,self.batch.size do local pad_size = self.context:size(2) - sourceSizes[i] if (pad_size ~= 0) then attnProba[{ i, {1,pad_size} }] = 1.0 end end -- Define state to be { decoder states, decoder output, context, -- attentions, features, sourceSizes, step, cumulated attention probablities }. local state = { self.decStates, nil, self.context, nil, features, sourceSizes, 1, attnProba } local params = {} params.length_norm = self.length_norm params.coverage_norm = self.coverage_norm params.eos_norm = self.eos_norm return onmt.translate.Beam.new(tokens, state, params) end --[[Updates beam states given new tokens. Parameters: * `beam` - beam with updated token list. ]] function DecoderAdvancer:update(beam) local state = beam:getState() local decStates, decOut, context, _, features, sourceSizes, t, cumAttnProba = table.unpack(state, 1, 8) local tokens = beam:getTokens() local token = tokens[#tokens] local inputs if #features == 0 then inputs = token elseif #features == 1 then inputs = { token, features[1] } else inputs = { token } table.insert(inputs, features) end local contextSizes, contextLength = sourceSizes, self.batch.sourceLength if self.updateSeqLengthFunc then contextSizes, contextLength = self.updateSeqLengthFunc(contextSizes, contextLength) end self.decoder:maskPadding(contextSizes, contextLength) decOut, decStates = self.decoder:forwardOne(inputs, decStates, context, decOut) t = t + 1 local softmaxOut if self.decoder.softmaxAttn then softmaxOut = self.decoder.softmaxAttn.output cumAttnProba = cumAttnProba:typeAs(softmaxOut):add(softmaxOut) end local nextState = {decStates, decOut, context, softmaxOut, nil, sourceSizes, t, cumAttnProba} beam:setState(nextState) end --[[Expand function. Expands beam by all possible tokens and returns the scores. Parameters: * `beam` - an `onmt.translate.Beam` object. Returns: * `scores` - a 2D tensor of size `(batchSize * beamSize, numTokens)`. ]] function DecoderAdvancer:expand(beam) local state = beam:getState() local decOut = state[2] local out = self.decoder.generator:forward(decOut) local features = {} for j = 2, #out do local _, best = out[j]:max(2) features[j - 1] = best:view(-1) end state[5] = features local scores = out[1] return scores end --[[Checks which hypotheses in the beam are already finished. A hypothesis is complete if i) an onmt.Constants.EOS is encountered, or ii) the length of the sequence is greater than or equal to `max_sent_length`. Parameters: * `beam` - an `onmt.translate.Beam` object. Returns: a binary flat tensor of size `(batchSize * beamSize)`, indicating which hypotheses are finished. ]] function DecoderAdvancer:isComplete(beam) local tokens = beam:getTokens() local seqLength = #tokens - 1 local complete = tokens[#tokens]:eq(onmt.Constants.EOS) if seqLength > self.max_sent_length then complete:fill(1) end return complete end --[[Checks which hypotheses in the beam shall be pruned. We disallow empty predictions, as well as predictions with more UNKs than `max_num_unks`. Parameters: * `beam` - an `onmt.translate.Beam` object. Returns: a binary flat tensor of size `(batchSize * beamSize)`, indicating which beams shall be pruned. ]] function DecoderAdvancer:filter(beam) local tokens = beam:getTokens() local numUnks = onmt.utils.Cuda.convert(torch.zeros(tokens[1]:size(1))) for t = 1, #tokens do local token = tokens[t] numUnks:add(onmt.utils.Cuda.convert(token:eq(onmt.Constants.UNK):double())) end -- Disallow too many UNKs local pruned = numUnks:gt(self.max_num_unks) -- Disallow empty hypotheses if #tokens == 2 then pruned:add(tokens[2]:eq(onmt.Constants.EOS)) end return pruned:ge(1) end return DecoderAdvancer
--[[ DecoderAdvancer is an implementation of the interface Advancer for specifyinghow to advance one step in decoder. --]] local DecoderAdvancer = torch.class('DecoderAdvancer', 'Advancer') --[[ Constructor. Parameters: * `decoder` - an `onmt.Decoder` object. * `batch` - an `onmt.data.Batch` object. * `context` - encoder output (batch x n x rnnSize). * `max_sent_length` - optional, maximum output sentence length. * `max_num_unks` - optional, maximum number of UNKs. * `decStates` - optional, initial decoder states. * `dicts` - optional, dictionary for additional features. * `updateSeqLengthFunc` - optional, sequence length adaptation function after encoder --]] function DecoderAdvancer:__init(decoder, batch, context, max_sent_length, max_num_unks, decStates, dicts, length_norm, coverage_norm, eos_norm, updateSeqLengthFunc) self.decoder = decoder self.batch = batch self.context = context self.max_sent_length = max_sent_length or math.huge self.max_num_unks = max_num_unks or math.huge self.length_norm = length_norm or 0.0 self.coverage_norm = coverage_norm or 0.0 self.eos_norm = eos_norm or 0.0 self.decStates = decStates or onmt.utils.Tensor.initTensorTable( decoder.args.numEffectiveLayers, onmt.utils.Cuda.convert(torch.Tensor()), { self.batch.size, decoder.args.rnnSize }) self.dicts = dicts self.updateSeqLengthFunc = updateSeqLengthFunc end --[[Returns an initial beam. Returns: * `beam` - an `onmt.translate.Beam` object. --]] function DecoderAdvancer:initBeam() local tokens = onmt.utils.Cuda.convert(torch.IntTensor(self.batch.size)):fill(onmt.Constants.BOS) local features = {} if self.dicts then for j = 1, #self.dicts.tgt.features do features[j] = torch.IntTensor(self.batch.size):fill(onmt.Constants.EOS) end end local sourceSizes = onmt.utils.Cuda.convert(self.batch.sourceSize) local attnProba = torch.FloatTensor(self.batch.size, self.context:size(2)) :fill(0.0001) :typeAs(self.context) -- Mask padding for i = 1,self.batch.size do local pad_size = self.context:size(2) - sourceSizes[i] if (pad_size ~= 0) then attnProba[{ i, {1,pad_size} }] = 1.0 end end -- Define state to be { decoder states, decoder output, context, -- attentions, features, sourceSizes, step, cumulated attention probablities }. local state = { self.decStates, nil, self.context, nil, features, sourceSizes, 1, attnProba } local params = {} params.length_norm = self.length_norm params.coverage_norm = self.coverage_norm params.eos_norm = self.eos_norm return onmt.translate.Beam.new(tokens, state, params) end --[[Updates beam states given new tokens. Parameters: * `beam` - beam with updated token list. ]] function DecoderAdvancer:update(beam) local state = beam:getState() local decStates, decOut, context, _, features, sourceSizes, t, cumAttnProba = table.unpack(state, 1, 8) local tokens = beam:getTokens() local token = tokens[#tokens] local inputs if #features == 0 then inputs = token elseif #features == 1 then inputs = { token, features[1] } else inputs = { token } table.insert(inputs, features) end local contextSizes, contextLength = sourceSizes, self.batch.sourceLength if self.updateSeqLengthFunc then contextSizes, contextLength = self.updateSeqLengthFunc(contextSizes, contextLength) end self.decoder:maskPadding(contextSizes, contextLength) decOut, decStates = self.decoder:forwardOne(inputs, decStates, context, decOut) t = t + 1 local softmaxOut if self.decoder.softmaxAttn then softmaxOut = self.decoder.softmaxAttn.output cumAttnProba = cumAttnProba:add(softmaxOut) end local nextState = {decStates, decOut, context, softmaxOut, nil, sourceSizes, t, cumAttnProba} beam:setState(nextState) end --[[Expand function. Expands beam by all possible tokens and returns the scores. Parameters: * `beam` - an `onmt.translate.Beam` object. Returns: * `scores` - a 2D tensor of size `(batchSize * beamSize, numTokens)`. ]] function DecoderAdvancer:expand(beam) local state = beam:getState() local decOut = state[2] local out = self.decoder.generator:forward(decOut) local features = {} for j = 2, #out do local _, best = out[j]:max(2) features[j - 1] = best:view(-1) end state[5] = features local scores = out[1] return scores end --[[Checks which hypotheses in the beam are already finished. A hypothesis is complete if i) an onmt.Constants.EOS is encountered, or ii) the length of the sequence is greater than or equal to `max_sent_length`. Parameters: * `beam` - an `onmt.translate.Beam` object. Returns: a binary flat tensor of size `(batchSize * beamSize)`, indicating which hypotheses are finished. ]] function DecoderAdvancer:isComplete(beam) local tokens = beam:getTokens() local seqLength = #tokens - 1 local complete = tokens[#tokens]:eq(onmt.Constants.EOS) if seqLength > self.max_sent_length then complete:fill(1) end return complete end --[[Checks which hypotheses in the beam shall be pruned. We disallow empty predictions, as well as predictions with more UNKs than `max_num_unks`. Parameters: * `beam` - an `onmt.translate.Beam` object. Returns: a binary flat tensor of size `(batchSize * beamSize)`, indicating which beams shall be pruned. ]] function DecoderAdvancer:filter(beam) local tokens = beam:getTokens() local numUnks = onmt.utils.Cuda.convert(torch.zeros(tokens[1]:size(1))) for t = 1, #tokens do local token = tokens[t] numUnks:add(onmt.utils.Cuda.convert(token:eq(onmt.Constants.UNK):double())) end -- Disallow too many UNKs local pruned = numUnks:gt(self.max_num_unks) -- Disallow empty hypotheses if #tokens == 2 then pruned:add(tokens[2]:eq(onmt.Constants.EOS)) end return pruned:ge(1) end return DecoderAdvancer
Fix tensor type mismatch when attention is not used
Fix tensor type mismatch when attention is not used Fixes #229.
Lua
mit
jsenellart/OpenNMT,monsieurzhang/OpenNMT,da03/OpenNMT,da03/OpenNMT,da03/OpenNMT,jungikim/OpenNMT,jungikim/OpenNMT,jsenellart/OpenNMT,monsieurzhang/OpenNMT,jsenellart-systran/OpenNMT,OpenNMT/OpenNMT,jungikim/OpenNMT,jsenellart-systran/OpenNMT,jsenellart-systran/OpenNMT,jsenellart/OpenNMT,monsieurzhang/OpenNMT,OpenNMT/OpenNMT,OpenNMT/OpenNMT
a2d8bbab46b3db0124cab8e1fc8dcbf9406a5845
check/network.lua
check/network.lua
--[[ Copyright 2015 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 BaseCheck = require('./base').BaseCheck local CheckResult = require('./base').CheckResult local fs = require('fs') local los = require('los') local misc = require('virgo/util/misc') local sigar = require('sigar') local table = require('table') local units = { rx_bytes = 'bytes', rx_dropped = 'packets', rx_errors = 'errors', rx_frame = 'frames', rx_overruns = 'overruns', rx_packets = 'packets', tx_bytes = 'bytes', tx_carrier = 'errors', tx_collisions = 'collisions', tx_dropped = 'packets', tx_errors = 'errors', tx_overruns = 'overruns', tx_packets = 'packets', link_state = 'link_state' } local NetworkCheck = BaseCheck:extend() function NetworkCheck:initialize(params) BaseCheck.initialize(self, params) self.interface_name = params.details and params.details.target end function NetworkCheck:getType() return 'agent.network' end function NetworkCheck:getTargets(callback) local s = sigar:new() local netifs = s:netifs() local targets = {} for i=1, #netifs do local info = netifs[i]:info() table.insert(targets, info.name) end callback(nil, targets) end -- Dimension is is the interface name, e.g. eth0, lo0, etc function NetworkCheck:run(callback) -- Perform Check local s = sigar:new() local netifs = s:netifs() local checkResult = CheckResult:new(self, {}) if not self.interface_name then checkResult:setError('Missing target parameter; give me an interface.') return callback(checkResult) end local interface = nil for i=1, #netifs do local name = netifs[i]:info().name if name == self.interface_name then interface = netifs[i] break end end if not interface then checkResult:setError('No such interface: ' .. self.interface_name) else local usage = interface:usage() for key, value in pairs(usage) do checkResult:addMetric(key, nil, 'gauge', value, units[key]) end end -- Get link state self:getLinkState(function(linkState) checkResult:addMetric('link_state', nil, 'string', linkState, units['link_state']) -- Return Result self._lastResult = checkResult callback(checkResult) end) end function NetworkCheck:getLinkState(callback) local linkState = 'unknown' local cfname = '/sys/class/net/' .. self.interface_name .. '/carrier' -- Linux if los.type() == 'linux' then fs.readFile(cfname, function(err, cstate) if not err then local tcstate = misc.trim(cstate) if tcstate == '1' then linkState = 'up' elseif tcstate == '0' then linkState = 'down' end end callback(linkState) end) -- Other OSes (for now) else callback(linkState) end end exports.NetworkCheck = NetworkCheck
--[[ Copyright 2015 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 BaseCheck = require('./base').BaseCheck local CheckResult = require('./base').CheckResult local fs = require('fs') local los = require('los') local misc = require('virgo/util/misc') local sigar = require('sigar') local table = require('table') local units = { rx_bytes = 'bytes', rx_dropped = 'packets', rx_errors = 'errors', rx_frame = 'frames', rx_overruns = 'overruns', rx_packets = 'packets', tx_bytes = 'bytes', tx_carrier = 'errors', tx_collisions = 'collisions', tx_dropped = 'packets', tx_errors = 'errors', tx_overruns = 'overruns', tx_packets = 'packets', link_state = 'link_state' } local NetworkCheck = BaseCheck:extend() function NetworkCheck:initialize(params) BaseCheck.initialize(self, params) self.interface_name = params.details and params.details.target end function NetworkCheck:getType() return 'agent.network' end function NetworkCheck:getTargets(callback) local s = sigar:new() local netifs = s:netifs() local targets = {} for i=1, #netifs do local info = netifs[i]:info() table.insert(targets, info.name) end callback(nil, targets) end -- Dimension is is the interface name, e.g. eth0, lo0, etc function NetworkCheck:run(callback) -- Perform Check local s = sigar:new() local netifs = s:netifs() local checkResult = CheckResult:new(self, {}) if not self.interface_name then checkResult:setError('Missing target parameter; give me an interface.') return callback(checkResult) end local interface = nil for i=1, #netifs do local name = netifs[i]:info().name if name == self.interface_name then interface = netifs[i] break end end if not interface then checkResult:setError('No such interface: ' .. self.interface_name) else local usage = interface:usage() if usage then for key, value in pairs(usage) do checkResult:addMetric(key, nil, 'gauge', value, units[key]) end end end -- Get link state self:getLinkState(function(linkState) checkResult:addMetric('link_state', nil, 'string', linkState, units['link_state']) -- Return Result self._lastResult = checkResult callback(checkResult) end) end function NetworkCheck:getLinkState(callback) local linkState = 'unknown' local cfname = '/sys/class/net/' .. self.interface_name .. '/carrier' -- Linux if los.type() == 'linux' then fs.readFile(cfname, function(err, cstate) if not err then local tcstate = misc.trim(cstate) if tcstate == '1' then linkState = 'up' elseif tcstate == '0' then linkState = 'down' end end callback(linkState) end) -- Other OSes (for now) else callback(linkState) end end exports.NetworkCheck = NetworkCheck
add a nil check within the network check (#954)
add a nil check within the network check (#954) fixes #937
Lua
apache-2.0
virgo-agent-toolkit/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent
60a109909b177ca3db2d0b2f4867932090920ff6
SafeLuaAPI/generator.lua
SafeLuaAPI/generator.lua
--- -- ## SafeLuaAPI compiler, generate the C code needed for the library -- -- @author Demi Marie Obenour -- @copyright 2016 -- @license MIT/X11 -- @module generator local generator = {} local require = require local concat = table.concat local assert = assert local sub, find, match = string.sub, string.find, string.match local format = string.format local stdout, stderr = io.stdout, io.stderr local pairs, ipairs, next = pairs, ipairs, next local tostring = tostring local io = io local type, tonumber, tostring = type, tonumber, tostring local string = string local os = os local pcall, xpcall = pcall, xpcall local print, error = print, error local getmetatable, setmetatable = getmetatable, setmetatable require 'pl/strict' local strict, err = pcall(require, 'pl/strict') local err, pretty = pcall(require, 'pl/pretty') pretty = err and pretty local finally = require 'SafeLuaAPI/finally' local parse_prototype = require 'SafeLuaAPI/parse_prototype' local parse_prototypes = parse_prototype.extract_args if pretty then pretty.dump { parse_prototypes('int main(int argc, char **argv)') } end local metatable = { __index = generator, __metatable = nil } local function check_metatable(table_) return getmetatable(table_) == metatable or error('Incorrect type passed to binder API', 2) end function generator:emit_struct(name, arguments) check_metatable(self) local handle = self.handle handle:write 'STRUCT_STATIC struct Struct_' handle:write(name) handle:write ' {\n' for i = 2, #arguments do handle:write(arguments[i]) handle:write ';\n' end handle:write '};\n' end local function emit_arglist(arguments) local len = #arguments if len == 0 then return '', '', 'L' end local y, z = {}, {'L'} for i, j in ipairs(arguments) do if i ~= 1 then -- print('[ARGUMENT] '..j) local argname = match(j, '[_%w]+%s*$') -- print('[ARGNAME] '..argname) y[i-1] = argname z[i] = 'args->'..argname end end return concat(arguments, ', '), concat(y, ', '), concat(z, ', ') end function generator.check_ident(ident) return find(ident, '^[_%a][_%w]*$') or error(('String %q is not an identifier'):format(ident)) end function generator.check_type(ty) if not (find(ty, '^[%s_%w%b()%*]*$') and find(ty, '^[%s_%w%(%)%*]*$')) then error(('String %q is not a valid C type'):format(ty)) end end local check_ident, check_type = generator.check_ident, generator.check_type function generator:emit_function_prototype(name, prototype) check_metatable(self) local c_source_text = '#ifndef '..name..'\n'..prototype..';\n#endif\n' self.handle:write(c_source_text) end --- Generates a wrapper for API function `name`. -- @tparam string name The function name. -- @tparam string popped The number of arguments popped from the Lua stack. -- @tparam string pushed The number of arguments pushed onto the Lua stack. -- @tparam {string,...} stack_in A list of arguments that name stack slots -- used by the function. -- @tparam string prototype The function prototype for the function. -- @treturn string The wrapper C code for the function function generator:emit_wrapper(popped, pushed, stack_in, prototype) check_metatable(self) local return_type, name, arguments = parse_prototype.extract_args(prototype) assert(#arguments > 0, 'No Lua API function takes no arguments') -- Consistency checks on the arguments check_type(return_type) check_ident(name) tonumber(popped) tonumber(pushed) self:emit_function_prototype(name, prototype) -- Get the various lists local prototype_args, initializers, call_string = emit_arglist(arguments) -- C needs different handling of `void` than of other types. Boo. local trampoline_type, retcast_type = 'TRAMPOLINE(', ', RETCAST_VALUE, ' if return_type == 'void' then trampoline_type, retcast_type = 'VOID_TRAMPOLINE(', ', RETCAST_VOID, ' end -- C does not allow empty structs or initializers. Boo. local local_struct = ', DUMMY_LOCAL_STRUCT' if #arguments ~= 1 then -- Actually emit the struct self:emit_struct(name, arguments) -- Use a different macro for the local struct (one that actually -- assigns to thread-local storage) local_struct = ', LOCAL_STRUCT' end -- local args = concat({name, argcount}, ', ') self.handle:write(concat { trampoline_type, return_type, ', ', name, ', ', pushed, ', ', call_string,')\ #define ARGLIST ', prototype_args:gsub('\n', ' '), '\ EMIT_WRAPPER(', return_type, ', ', name, ', ', popped, local_struct, retcast_type, initializers, ')\n#undef ARGLIST\n\n' }) end function generator:generate(table_) --pretty.dump(table_) check_metatable(self) for i, j in pairs(table_) do assert(type(i) == 'string') -- print(argument_list) self:emit_wrapper(j.popped, j.pushed, j.stack_in, i) end end function generator.new(handle) return setmetatable({ handle = handle }, metatable) end local generate = generator.generate --- Generate C code to a given filename -- @tparam string filename The name of the file to write the C code to. -- @tparam {} table_ The table containing function descriptions function generator.generate_to_file(filename, table_) return finally.with_file(filename, 'w', generate) end return generator
--- -- ## SafeLuaAPI compiler, generate the C code needed for the library -- -- @author Demi Marie Obenour -- @copyright 2016 -- @license MIT/X11 -- @module generator local generator = {} local require = require local concat = table.concat local assert = assert local sub, find, match = string.sub, string.find, string.match local format = string.format local stdout, stderr = io.stdout, io.stderr local pairs, ipairs, next = pairs, ipairs, next local tostring = tostring local io = io local type, tonumber, tostring = type, tonumber, tostring local string = string local os = os local pcall, xpcall = pcall, xpcall local print, error = print, error local getmetatable, setmetatable = getmetatable, setmetatable require 'pl/strict' local strict, err = pcall(require, 'pl/strict') local err, pretty = pcall(require, 'pl/pretty') pretty = err and pretty local finally = require 'SafeLuaAPI/finally' local parse_prototype = require 'SafeLuaAPI/parse_prototype' local parse_prototypes = parse_prototype.extract_args if pretty then pretty.dump { parse_prototypes('int main(int argc, char **argv)') } end local metatable = { __index = generator, __metatable = nil } local function check_metatable(table_) return getmetatable(table_) == metatable or error('Incorrect type passed to binder API', 2) end function generator:emit(...) local handle = self.handle for _, j in ipairs({...}) do handle:write(j) end end function generator:emit_struct(name, arguments, indexes) local handle = self.handle self:emit 'STRUCT_STATIC struct Struct_' self:emit(name) self:emit ' {\n' for i = 2, #arguments do local arg = arguments[i] if not indexes[arg] then self:emit(arguments[i]) self:emit';\n' end end handle:write '};\n' end local function emit_arglist(arguments, indexes) local len = #arguments if len == 0 then return '', '', 'L' end local y, z = {}, {'L'} for i, j in ipairs(arguments) do if i ~= 1 then -- print('[ARGUMENT] '..j) local argname = match(j, '[_%w]+%s*$') -- print('[ARGNAME] '..argname) y[i-1] = argname z[i] = indexes[argname] or 'args->'..argname end end return concat(arguments, ', '), concat(y, ', '), concat(z, ', ') end function generator.check_ident(ident) return find(ident, '^[_%a][_%w]*$') or error(('String %q is not an identifier'):format(ident)) end function generator.check_type(ty) if not (find(ty, '^[%s_%w%b()%*]*$') and find(ty, '^[%s_%w%(%)%*]*$')) then error(('String %q is not a valid C type'):format(ty)) end end function generator:emit_function_prototype(name, prototype) local c_source_text = '#ifndef '..name..'\n'..prototype..';\n#endif\n' self.handle:write(c_source_text) end --- Generates a wrapper for API function `name`. -- @tparam string name The function name. -- @tparam string popped The number of arguments popped from the Lua stack. -- @tparam string pushed The number of arguments pushed onto the Lua stack. -- @tparam {string,...} stack_in A list of arguments that name stack slots -- used by the function. -- @tparam string prototype The function prototype for the function. -- @treturn string The wrapper C code for the function function generator:emit_wrapper(popped, pushed, stack_in, prototype) check_metatable(self) local return_type, name, arguments = parse_prototype.extract_args(prototype) assert(#arguments > 0, 'No Lua API function takes no arguments') -- Consistency checks on the arguments self.check_type(return_type) self.check_ident(name) tonumber(popped) tonumber(pushed) -- Generate indexes table. Map from argument names to stack indexes. local indexes = {} for i, j in ipairs(stack_in) do indexes[j] = i + popped end self:emit_function_prototype(name, prototype) -- Get the various lists local prototype_args, initializers, call_string = emit_arglist(arguments, indexes) -- C needs different handling of `void` than of other types. Boo. local trampoline_type, retcast_type = 'TRAMPOLINE(', ', RETCAST_VALUE, ' if return_type == 'void' then trampoline_type, retcast_type = 'VOID_TRAMPOLINE(', ', RETCAST_VOID, ' end -- Initial newline self:emit '\n' -- C does not allow empty structs or initializers. Boo. local local_struct = ', DUMMY_LOCAL_STRUCT' if #arguments ~= 1 then -- Actually emit the struct self:emit_struct(name, arguments, indexes) -- Use a different macro for the local struct (one that actually -- assigns to thread-local storage) local_struct = ', LOCAL_STRUCT' end -- local args = concat({name, argcount}, ', ') -- -- Emit trampoline code. self:emit(trampoline_type, return_type, ', ', name, ', ', pushed, ', ', call_string,')\n') -- Emit main function self:emit(return_type, ' safe_', name, '(int *success, ', prototype_args,') {\n') do local num_stack_inputs = #stack_in if num_stack_inputs ~= 0 then for i = num_stack_inputs, 1, -1 do self:emit(' lua_pushvalue(L, ', stack_in[i], ');\n') if popped ~= 0 then self:emit(' lua_insert(L, ', -i - popped, ');\n') end end end end self:emit(' EMIT_WRAPPER(', return_type, ', ', name, ',\ ', popped, local_struct, retcast_type, initializers, ');\n}\n') end function generator:generate(table_) --pretty.dump(table_) check_metatable(self) for i, j in pairs(table_) do assert(type(i) == 'string') -- print(argument_list) self:emit_wrapper(j.popped, j.pushed, j.stack_in, i) end end function generator.new(handle) return setmetatable({ handle = handle }, metatable) end local generate = generator.generate --- Generate C code to a given filename -- @tparam string filename The name of the file to write the C code to. -- @tparam {} table_ The table containing function descriptions function generator.generate_to_file(filename, table_) return finally.with_file(filename, 'w', generate) end return generator
Push stack arguments passed to the function
Push stack arguments passed to the function before calling the function. Fixes #1.
Lua
apache-2.0
drbo/safer-lua-api,drbo/safer-lua-api
45a646bf3c00d86594bfbde1fdb19f5763a2beeb
src/lua/redis.lua
src/lua/redis.lua
package.path = package.path .. ";lua/?.lua;../?.lua" print ("Script Init Begin") local pool = require("pool") function parse(body) local lines = body:strip():split("\n") table.remove(lines, 1) local configs = {} -- parse for i,line in ipairs(lines) do local xs = line:split(" ") local addr = xs[4]:split(":") ip, port = addr[1], addr[2] local role = "master" if string.find(xs[5], "master") == nil then role = "slave" end local loc = xs[2]:split(":") local c = { id = xs[3], addr = xs[4], ip = ip, port = tonumber(port), role = role, master_id = xs[6], status = xs[10], readable = false, writable = false, region = loc[1], zone = loc[2], room = loc[3], } if string.find(xs[1], "r") then c.readable = true end if string.find(xs[1], "w") then c.writable = true end if role == "master" then local ranges = {} for i = 11, #xs do -- skip importing/migrating info if string.sub(xs[i],1,1) == "[" then break end local range = {} local pair = xs[i]:split("-") range.left = tonumber(pair[1]) range.right = tonumber(pair[2]) table.insert(ranges, range) end c.ranges = ranges end table.insert(configs, c) end return configs end function update_cluster_nodes(msg) if string.sub(msg,1,3) == "+OK" or string.sub(msg,1,3) == "$-1" then return end -- parse message returned by 'cluster nodes' local configs = parse(msg) -- reconstruct servers, fix adds and drops pool:set_servers(configs) -- rebuild replica sets pool:build_replica_sets() -- bind replica sets to slots pool:bind_slots() end print ("Script Init Done")
package.path = package.path .. ";lua/?.lua;../?.lua" print ("Script Init Begin") local pool = require("pool") function parse(body) local lines = body:strip():split("\n") table.remove(lines, 1) local configs = {} -- parse for i,line in ipairs(lines) do local xs = line:split(" ") local addr = xs[4]:split(":") ip, port = addr[1], addr[2] local role = "master" if string.find(xs[5], "master") == nil then role = "slave" end local loc = xs[2]:split(":") local c = { id = xs[3], addr = xs[4], ip = ip, port = tonumber(port), role = role, master_id = xs[6], status = xs[10], readable = false, writable = false, region = loc[1], zone = loc[2], room = loc[3], } if string.find(xs[1], "r") then c.readable = true end if string.find(xs[1], "w") then c.writable = true end if role == "master" then local ranges = {} for i = 11, #xs do -- skip importing/migrating info if string.sub(xs[i],1,1) == "[" then break end local range = {} local pair = xs[i]:split("-") if #pair == 2 then range.left = tonumber(pair[1]) range.right = tonumber(pair[2]) else range.left = tonumber(xs[i]) range.right = tonumber(xs[i]) end table.insert(ranges, range) end c.ranges = ranges end table.insert(configs, c) end return configs end function update_cluster_nodes(msg) if string.sub(msg,1,3) == "+OK" or string.sub(msg,1,3) == "$-1" then return end -- parse message returned by 'cluster nodes' local configs = parse(msg) -- reconstruct servers, fix adds and drops pool:set_servers(configs) -- rebuild replica sets pool:build_replica_sets() -- bind replica sets to slots pool:bind_slots() end print ("Script Init Done")
fix range parsing
fix range parsing
Lua
apache-2.0
jxwr/r3proxy,jxwr/r3proxy,jxwr/r3proxy
3a24152e3d999bd6b0ba16ffacee1ce8c3b95904
src/single-dir.lua
src/single-dir.lua
-- lua-round-up, Gather all dependencies of Lua module together -- Copyright (C) 2015 Boris Nagaev -- See the LICENSE file for terms of use. local function fileExists(name) local f = io.open(name, "r") if f ~= nil then io.close(f) return true else return false end end local function dirExists(name) local renamed = os.rename(name, name) return renamed end local function mkDir(dir) local parts = {} for part in dir:gmatch('([^/]+)') do table.insert(parts, part) local path = table.concat(parts, '/') if not dirExists(path) then os.execute("mkdir " .. path) end end end local function copyFile(old_path, new_path) local new_dir = new_path:match('.*/') mkDir(new_dir) local f = assert(io.open(old_path, "r")) local data = f:read('*all') f:close() local f = assert(io.open(new_path, "w")) f:write(data) f:close() end local function searchModule(name, path) name = name:gsub('%.', '/') for p in path:gmatch("([^;]+)") do local fname = p:gsub('%?', name) if fileExists(fname) then return fname, p end end end local function makeNewName(name, fname, pattern) local suffix = pattern:match('%?(.*)') return 'modules/' .. name:gsub('%.', '/') .. suffix end local function copyModule(name, path) local fname, pattern = searchModule(name, path) assert(fname, "Can't find module " .. name) local new_path = makeNewName(name, fname, pattern) copyFile(fname, new_path) end local function myLoader(original_loader, path, all_in_one) return function(name) local f = original_loader(name) if type(f) == "function" then if all_in_one then name = name:match('^([^.]+)') end copyModule(name, path) end return f end end -- change package loaders local lua_loader = package.loaders[2] local c_loader = package.loaders[3] local aio_loader = package.loaders[4] package.loaders[2] = myLoader(lua_loader, package.path) package.loaders[3] = myLoader(c_loader, package.cpath) package.loaders[4] = myLoader(aio_loader, package.cpath, true)
-- lua-round-up, Gather all dependencies of Lua module together -- Copyright (C) 2015 Boris Nagaev -- See the LICENSE file for terms of use. local function fileExists(name) local f = io.open(name, "r") if f ~= nil then io.close(f) return true else return false end end local function dirExists(name) local renamed = os.rename(name, name) return renamed end local function mkDir(dir) local parts = {} for part in dir:gmatch('([^/]+)') do table.insert(parts, part) local path = table.concat(parts, '/') if not dirExists(path) then os.execute("mkdir " .. path) end end end local function copyFile(old_path, new_path) local new_dir = new_path:match('.*/') mkDir(new_dir) local f = assert(io.open(old_path, "r")) local data = f:read('*all') f:close() local f = assert(io.open(new_path, "w")) f:write(data) f:close() end local function searchModule(name, path) name = name:gsub('%.', '/') for p in path:gmatch("([^;]+)") do local fname = p:gsub('%?', name) if fileExists(fname) then return fname, p end end end local function makeNewName(name, fname, pattern) local suffix = pattern:match('%?(.*)') return 'modules/' .. name:gsub('%.', '/') .. suffix end local function copyModule(name, path) local fname, pattern = searchModule(name, path) assert(fname, "Can't find module " .. name) local new_path = makeNewName(name, fname, pattern) copyFile(fname, new_path) end local function myLoader(original_loader, path, all_in_one) return function(name) local f = original_loader(name) if type(f) == "function" then if all_in_one then name = name:match('^([^.]+)') end copyModule(name, path) end return f end end -- package.loaders (Lua 5.1), package.searchers (Lua >= 5.2) local searchers = package.searchers or package.loaders local lua_searcher = searchers[2] local c_searcher = searchers[3] local allinone_searcher = searchers[4] searchers[2] = myLoader(lua_searcher, package.path) searchers[3] = myLoader(c_searcher, package.cpath) searchers[4] = myLoader(allinone_searcher, package.cpath, true)
fix for lua >= 5.2
fix for lua >= 5.2 The table package.loaders was renamed package.searchers.
Lua
mit
starius/single-dir.lua
a074c91995d1920495c5365a0c442cadf19e3865
Ndex.lua
Ndex.lua
--[[ This module prints an entry in a list of Pokémon. The interface allow for printing from WikiCode, and expose the class for other modules to use it. Example call from WikiCode: {{#invoke: ndex | list | 396 397 398 487 487O 422E | color = alola }} Takes a list of space separated ndexes and print the relative entries. The color argument specify the color of the background (a name from modulo colore). The other interface prints only the header, with the color specified: {{#invoke: ndex | header | sinnoh }} --]] local n = {} local txt = require('Wikilib-strings') -- luacheck: no unused local tab = require('Wikilib-tables') -- luacheck: no unused local form = require('Wikilib-forms') local oop = require('Wikilib-oop') local lists = require('Wikilib-lists') local multigen = require('Wikilib-multigen') local box = require('Box') local ms = require('MiniSprite') local css = require('Css') local pokes = require('Poké-data') -- Loads also useless forms because there can be entries for useless forms form.loadUseless(true) local alts = form.allFormsData() --[[ This class holds data about name, ndex, types and form of a Pokémon. It also support useless forms. --]] n.Entry = oop.makeClass(lists.PokeLabelledEntry) n.Entry.strings = { ENTRY = string.gsub([=[ <div class="inline-block width-xl-33 width-md-50 width-sm-100" style="padding: 0.2em 0.3em;"> <div class="roundy white-bg height-100 vert-middle" style="padding-right: 0.2em; padding-top: 0.1em;"><!-- --><div class="width-xl-15" style="padding: 0.3ex;">#${ndex}</div><!-- --><div class="width-xl-15" style="padding: 0.3ex;">${ms}</div><!-- --><div class="text-center width-xl-40" style="padding: 0.3ex;">[[${name}]]${form}</div><!-- --><div class="width-xl-30" style="padding: 0.3ex;">${types}</div> </div></div>]=], "<!%-%-\n%-%->", ""), HEADER = [=[ <div class="roundy pull-center text-center flex-row-stretch-around flex-wrap width-xl-80 width-lg-100" style="${bg}">]=], } n.Entry.new = function(pokedata, name) local this = n.Entry.super.new(name, pokedata.ndex) local baseName, abbr = form.getNameAbbr(name) if alts[baseName] then -- Table.copy because alts is mw.loadData, so mw.clone doesn't work this.formsData = table.copy(alts[baseName]) this.formAbbr = abbr end if this.labels[1] == "" then this.labels[1] = nil end return setmetatable(table.merge(this, pokedata), n.Entry) end -- WikiCode for an entry: card layout with all the informations on one line. n.Entry.__tostring = function(this) local formtag = "" if this.labels[1] then formtag = this.labels[1] == 'Tutte le forme' and '<div class="small-text">Tutte le forme</div>' or this.formsData.links[this.formAbbr] end local type1 = multigen.getGenValue(this.type1) local type2 = multigen.getGenValue(this.type2) local types = type2 == type1 and { type1 } or { type1, type2 } return string.interp(n.Entry.strings.ENTRY, { ndex = this.ndex and string.tf(this.ndex) or '???', ms = ms.staticLua(string.tf(this.ndex or 0) .. form.toEmptyAbbr(this.formAbbr or '')), name = this.name, form = formtag, types = box.listTipoLua(table.concat(types, ", "), "thin", "width-xl-100", "margin: 0 0.2ex 0.2ex 0;"), }) end -- ================================== Header ================================== n.headerLua = function(color) return string.interp(n.Entry.strings.HEADER, { bg = css.horizGradLua{type = color or 'pcwiki'}, }) end n.header = function(frame) return n.headerLua(string.trim(frame.args[1])) end --[[ WikiCode interface, to print a list of entries. --]] n.list = function(frame) local ndexlist = frame.args[1] local res = { n.headerLua(string.trim(frame.args.color)) } for ndex in ndexlist:gmatch("[^ ]+") do local baseName, _ = form.getNameAbbr(ndex) table.insert(res, tostring(n.Entry.new(pokes[ndex] or pokes[baseName], ndex))) end table.insert(res, "</div>") return table.concat(res) end n.List = n.list return n
--[[ This module prints an entry in a list of Pokémon. The interface allow for printing from WikiCode, and expose the class for other modules to use it. Example call from WikiCode: {{#invoke: ndex | list | 396 397 398 487 487O 422E | color = alola }} Takes a list of space separated ndexes and print the relative entries. The color argument specify the color of the background (a name from modulo colore). The other interface prints only the header, with the color specified: {{#invoke: ndex | header | sinnoh }} --]] local n = {} local txt = require('Wikilib-strings') -- luacheck: no unused local tab = require('Wikilib-tables') -- luacheck: no unused local form = require('Wikilib-forms') local oop = require('Wikilib-oop') local lists = require('Wikilib-lists') local multigen = require('Wikilib-multigen') local box = require('Box') local ms = require('MiniSprite') local css = require('Css') local pokes = require('Poké-data') -- Loads also useless forms because there can be entries for useless forms form.loadUseless(true) local alts = form.allFormsData() --[[ This class holds data about name, ndex, types and form of a Pokémon. It also support useless forms. --]] n.Entry = oop.makeClass(lists.PokeLabelledEntry) n.Entry.strings = { ENTRY = string.gsub([=[ <div class="inline-block width-xl-33 width-md-50 width-sm-100" style="padding: 0.2em 0.3em;"> <div class="roundy white-bg height-100 vert-middle" style="padding-right: 0.2em; padding-top: 0.1em;"><!-- --><div class="width-xl-15" style="padding: 0.3ex;">#${ndex}</div><!-- --><div class="width-xl-20" style="padding: 0.3ex;">${ms}</div><!-- --><div class="text-center width-xl-35" style="padding: 0.3ex;">[[${name}]]${form}</div><!-- --><div class="width-xl-30" style="padding: 0.3ex;">${types}</div> </div></div>]=], "<!%-%-\n%-%->", ""), HEADER = [=[ <div class="roundy pull-center text-center flex-row-stretch-around flex-wrap width-xl-80 width-lg-100" style="${bg}">]=], } n.Entry.new = function(pokedata, name) local this = n.Entry.super.new(name, pokedata.ndex) local baseName, abbr = form.getNameAbbr(name) if alts[baseName] then -- Table.copy because alts is mw.loadData, so mw.clone doesn't work this.formsData = table.copy(alts[baseName]) this.formAbbr = abbr end if this.labels[1] == "" then this.labels[1] = nil end return setmetatable(table.merge(this, pokedata), n.Entry) end -- WikiCode for an entry: card layout with all the informations on one line. n.Entry.__tostring = function(this) local formtag = "" if this.labels[1] then formtag = this.labels[1] == 'Tutte le forme' and '<div class="small-text">Tutte le forme</div>' or this.formsData.links[this.formAbbr] end local type1 = multigen.getGenValue(this.type1) local type2 = multigen.getGenValue(this.type2) local types = type2 == type1 and { type1 } or { type1, type2 } return string.interp(n.Entry.strings.ENTRY, { ndex = this.ndex and string.tf(this.ndex) or '???', ms = ms.staticLua(string.tf(this.ndex or 0) .. form.toEmptyAbbr(this.formAbbr or '')), name = this.name, form = formtag, types = box.listTipoLua(table.concat(types, ", "), "thin", "width-xl-100", "margin: 0 0.2ex 0.2ex 0;"), }) end -- ================================== Header ================================== n.headerLua = function(color) return string.interp(n.Entry.strings.HEADER, { bg = css.horizGradLua{type = color or 'pcwiki'}, }) end n.header = function(frame) return n.headerLua(string.trim(frame.args[1])) end --[[ WikiCode interface, to print a list of entries. --]] n.list = function(frame) local ndexlist = frame.args[1] local res = { n.headerLua(string.trim(frame.args.color)) } for ndex in ndexlist:gmatch("[^ ]+") do local baseName, _ = form.getNameAbbr(ndex) table.insert(res, tostring(n.Entry.new(pokes[ndex] or pokes[baseName], ndex))) end table.insert(res, "</div>") return table.concat(res) end n.List = n.list return n
Fixing problems in ndex with MS increased size
Fixing problems in ndex with MS increased size
Lua
cc0-1.0
pokemoncentral/wiki-lua-modules
0392d4429b939d15a95341aed850d91041ad7d3d
Engine/sandbox.lua
Engine/sandbox.lua
--A function that creates new sandboxed global environment. local basexx = require("Engine.basexx") local bit = require("bit") local _LuaBCHeader = string.char(0x1B).."LJ" return function(parent) local GLOB = { assert=assert, error=error, ipairs=ipairs, pairs=pairs, next=next, pcall=pcall, select=select, tonumber=tonumber, tostring=tostring, type=type, unpack=unpack, _VERSION=_VERSION, xpcall=xpcall, setmetatable=setmetatable, getmetatable=getmetatable, rawget = rawget, rawset = rawset, rawequal = rawequal, string={ byte=string.byte, char=string.char, find=string.find, format=string.format, gmatch=string.gmatch, gsub=string.gsub, len=string.len, lower=string.lower, match=string.match, rep=string.rep, reverse=string.reverse, sub=string.sub, upper=string.upper }, table={ insert=table.insert, maxn=table.maxn, remove=table.remove, sort=table.sort, concat=table.concat }, math={ abs=math.abs, acos=math.acos, asin=math.asin, atan=math.atan, atan2=math.atan2, ceil=math.ceil, cos=math.cos, cosh=math.cosh, deg=math.deg, exp=math.exp, floor=math.floor, fmod=math.fmod, frexp=math.frexp, huge=math.huge, ldexp=math.ldexp, log=math.log, log10=math.log10, max=math.max, min=math.min, modf=math.modf, pi=math.pi, pow=math.pow, rad=math.rad, random=love.math.random, --Replaced with love.math versions randomseed=love.math.setRandomSeed, sin=math.sin, sinh=math.sinh, sqrt=math.sqrt, tan=math.tan, tanh=math.tanh, noise = love.math.noise, --LOVE releated apis b64enc = basexx.to_base64, --Will be replaced by love.math ones in love 0.11 b64dec = basexx.from_base64, hexenc = basexx.to_hex, hexdec = basexx.from_hex, compress = function(...) return love.math.compress(...):getString() end, decompress = love.math.decompress, isConvex = love.math.isConvex, triangulate = love.math.triangulate, noise = love.math.noise, randomNormal = love.math.randomNormal }, coroutine={ create = coroutine.create, resume = coroutine.resume, yield = coroutine.yield, status = coroutine.status }, os={ time=os.time, clock=os.clock, date=os.date }, bit={ cast=bit.cast, bnot=bit.bnot, band=bit.band, bor=bit.bor, bxor=bit.bxor, lshift=bit.lshift, rshift=bit.rshift, arshift=bit.arshift, tobit=bit.tobit, tohex=bit.tohex, rol=bit.rol, ror=bit.ror, bswap=bit.swap } } GLOB.getfenv = function(f) if type(f) ~= "function" then return error("bad argument #1 to 'getfenv' (function expected, got "..type(f)) end local ok, env = pcall(getfenv,f) if not ok then return error(env) end if env.love == love then env = {} end --Protection return env end GLOB.setfenv = function(f,env) if type(f) ~= "function" then return error("bad argument #1 to 'setfenv' (function expected, got "..type(f)) end if type(env) ~= "table" then return error("bad argument #2 to 'setfenv' (table expected, got "..type(env)) end local oldenv = getfenv(f) if oldenv.love == love then return end --Trying to make a crash ! evil. local ok, err = pcall(setfenv,f,env) if not ok then return error(err) end end GLOB.loadstring = function(data) if data:sub(1,3) == _LuaBCHeader then return error("LOADING BYTECODE IS NOT ALLOWED, YOU HACKER !") end local chunk, err = loadstring(data) if not chunk then return nil, err end setfenv(chunk,GLOB) return chunk end GLOB.coroutine.sethook = function(co,...) if type(co) ~= "thread" then return error("bad argument #1 (thread expected, got "..type(co)..")") end local ok, err = pcall(debug.sethook,co,...) if not ok then return error(err) end return err end GLOB.coroutine.running = function() local curco = coroutine.running() if parent and parent.co and curco == parent.co then return end return curco end GLOB._G=GLOB --Mirror Mirror return GLOB end
--A function that creates new sandboxed global environment. local basexx = require("Engine.basexx") local bit = require("bit") local _LuaBCHeader = string.char(0x1B).."LJ" return function(parent) local GLOB = { assert=assert, error=error, ipairs=ipairs, pairs=pairs, next=next, pcall=pcall, select=select, tonumber=tonumber, tostring=tostring, type=type, unpack=unpack, _VERSION=_VERSION, xpcall=xpcall, setmetatable=setmetatable, getmetatable=getmetatable, rawget = rawget, rawset = rawset, rawequal = rawequal, string={ byte=string.byte, char=string.char, find=string.find, format=string.format, gmatch=string.gmatch, gsub=string.gsub, len=string.len, lower=string.lower, match=string.match, rep=string.rep, reverse=string.reverse, sub=string.sub, upper=string.upper }, table={ insert=table.insert, maxn=table.maxn, remove=table.remove, sort=table.sort, concat=table.concat }, math={ abs=math.abs, acos=math.acos, asin=math.asin, atan=math.atan, atan2=math.atan2, ceil=math.ceil, cos=math.cos, cosh=math.cosh, deg=math.deg, exp=math.exp, floor=math.floor, fmod=math.fmod, frexp=math.frexp, huge=math.huge, ldexp=math.ldexp, log=math.log, log10=math.log10, max=math.max, min=math.min, modf=math.modf, pi=math.pi, pow=math.pow, rad=math.rad, random=love.math.random, --Replaced with love.math versions randomseed=love.math.setRandomSeed, sin=math.sin, sinh=math.sinh, sqrt=math.sqrt, tan=math.tan, tanh=math.tanh, noise = love.math.noise, --LOVE releated apis b64enc = basexx.to_base64, --Will be replaced by love.math ones in love 0.11 b64dec = basexx.from_base64, hexenc = basexx.to_hex, hexdec = basexx.from_hex, compress = function(...) return love.math.compress(...):getString() end, decompress = love.math.decompress, isConvex = love.math.isConvex, triangulate = love.math.triangulate, randomNormal = love.math.randomNormal }, coroutine={ create = coroutine.create, resume = coroutine.resume, yield = coroutine.yield, status = coroutine.status }, os={ time=os.time, clock=os.clock, date=os.date }, bit={ cast=bit.cast, bnot=bit.bnot, band=bit.band, bor=bit.bor, bxor=bit.bxor, lshift=bit.lshift, rshift=bit.rshift, arshift=bit.arshift, tobit=bit.tobit, tohex=bit.tohex, rol=bit.rol, ror=bit.ror, bswap=bit.swap } } GLOB.getfenv = function(f) if type(f) ~= "function" then return error("bad argument #1 to 'getfenv' (function expected, got "..type(f)) end local ok, env = pcall(getfenv,f) if not ok then return error(env) end if env.love == love then env = {} end --Protection return env end GLOB.setfenv = function(f,env) if type(f) ~= "function" then return error("bad argument #1 to 'setfenv' (function expected, got "..type(f)) end if type(env) ~= "table" then return error("bad argument #2 to 'setfenv' (table expected, got "..type(env)) end local oldenv = getfenv(f) if oldenv.love == love then return end --Trying to make a crash ! evil. local ok, err = pcall(setfenv,f,env) if not ok then return error(err) end end GLOB.loadstring = function(data) if data:sub(1,3) == _LuaBCHeader then return error("LOADING BYTECODE IS NOT ALLOWED, YOU HACKER !") end local chunk, err = loadstring(data) if not chunk then return nil, err end setfenv(chunk,GLOB) return chunk end GLOB.coroutine.sethook = function(co,...) if type(co) ~= "thread" then return error("bad argument #1 (thread expected, got "..type(co)..")") end local ok, err = pcall(debug.sethook,co,...) if not ok then return error(err) end return err end GLOB.coroutine.running = function() local curco = coroutine.running() if parent and parent.co and curco == parent.co then return end return curco end GLOB._G=GLOB --Mirror Mirror return GLOB end
Typofix (Repeated math.noise)
Typofix (Repeated math.noise) Former-commit-id: b41be74ac3884efdcc0066d5c3c7e404815ee0df
Lua
mit
RamiLego4Game/LIKO-12
8cf6f2364ef5c31f71b1e1366d91120a56cec0f2
test_scripts/Polices/build_options/ATF_PolicyManager_changes_status_to_UPDATING_PROPRIETARY.lua
test_scripts/Polices/build_options/ATF_PolicyManager_changes_status_to_UPDATING_PROPRIETARY.lua
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [PolicyTableUpdate] PoliciesManager changes status to "UPDATING" -- [HMI API] OnStatusUpdate -- -- Description: -- SDL is built with "-DEXTENDED_POLICY: PROPRIETARY" flag -- PoliciesManager must change the status to "UPDATING" and notify HMI with OnStatusUpdate("UPDATING") -- right after SnapshotPT is sent out to to mobile app via OnSystemRequest() RPC. -- -- Steps: -- 1. Register new app -- 2. Trigger PTU -- 3. SDL->HMI: Verify step of SDL.OnStatusUpdate(UPDATING) notification in PTU sequence -- -- Expected result: -- SDL.OnStatusUpdate(UPDATING) notification is send right after SDL->MOB: OnSystemRequest --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonFunctions = require("user_modules/shared_testcases/commonFunctions") local commonSteps = require("user_modules/shared_testcases/commonSteps") local testCasesForPolicyTable = require("user_modules/shared_testcases/testCasesForPolicyTable") --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() testCasesForPolicyTable.Delete_Policy_table_snapshot() --[[ General Settings for configuration ]] Test = require("connecttest") require("user_modules/AppTypes") --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Precondition") function Test:Precondition_trigger_getting_device_consent() testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_CheckMessagesSequence() local is_test_fail = false local message_number = 1 local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(RequestId_GetUrls) :Do(function(_,_) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", fileName = "PolicyTableUpdate"}) if(message_number ~= 1) then commonFunctions:printError("Error: SDL.GetURLS reponse is not received as message 1 after SDL.GetURLS request. Real: "..message_number) is_test_fail = true else print("SDL.GetURLS is received as message "..message_number.." after SDL.GetURLS request") end message_number = message_number + 1 end) EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "PROPRIETARY"}) :Do(function(_,_) if( (message_number ~= 2) and (message_number ~= 3)) then commonFunctions:printError("Error: SDL.OnStatusUpdate reponse is not received as message 2/3 after SDL.GetURLS request. Real: "..message_number) is_test_fail = true else print("OnSystemRequest is received as message "..message_number.." after SDL.GetURLS request") end message_number = message_number + 1 end) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate",{status = "UPDATING"}) :Do(function(_,data) if( (message_number ~= 2) and (message_number ~= 3)) then commonFunctions:printError("Error: SDL.OnStatusUpdate reponse is not received as message 2/3 after SDL.GetURLS request. Real: "..message_number) is_test_fail = true else print("SDL.OnStatusUpdate("..data.params.status..") is received as message "..message_number.." after SDL.GetURLS request") end message_number = message_number + 1 end) if(is_test_fail == true) then self:FailTestCase("Test is FAILED. See prints.") end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_StopSDL() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [PolicyTableUpdate] PoliciesManager changes status to "UPDATING" -- [HMI API] OnStatusUpdate -- -- Description: -- SDL is built with "-DEXTENDED_POLICY: PROPRIETARY" flag -- PoliciesManager must change the status to "UPDATING" and notify HMI with OnStatusUpdate("UPDATING") -- right after SnapshotPT is sent out to to mobile app via OnSystemRequest() RPC. -- -- Steps: -- 1. Register new app -- 2. Trigger PTU -- 3. SDL->HMI: Verify step of SDL.OnStatusUpdate(UPDATING) notification in PTU sequence -- -- Expected result: -- SDL.OnStatusUpdate(UPDATING) notification is send right after SDL->MOB: OnSystemRequest --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonFunctions = require("user_modules/shared_testcases/commonFunctions") local commonSteps = require("user_modules/shared_testcases/commonSteps") local testCasesForPolicyTable = require("user_modules/shared_testcases/testCasesForPolicyTable") --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() testCasesForPolicyTable.Delete_Policy_table_snapshot() --[[ General Settings for configuration ]] Test = require("connecttest") require("user_modules/AppTypes") --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Precondition") --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_CheckMessagesSequence() local is_test_fail = false local message_number = 1 local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(RequestId_GetUrls) :Do(function(_,_) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", fileName = "PolicyTableUpdate"}) if(message_number ~= 1) then commonFunctions:printError("Error: SDL.GetURLS reponse is not received as message 1 after SDL.GetURLS request. Real: "..message_number) is_test_fail = true else print("SDL.GetURLS is received as message "..message_number.." after SDL.GetURLS request") end message_number = message_number + 1 end) EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "PROPRIETARY"}) :Do(function(_,_) if( (message_number ~= 2) and (message_number ~= 3)) then commonFunctions:printError("Error: SDL.OnStatusUpdate reponse is not received as message 2/3 after SDL.GetURLS request. Real: "..message_number) is_test_fail = true else print("OnSystemRequest is received as message "..message_number.." after SDL.GetURLS request") end message_number = message_number + 1 end) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate",{status = "UPDATING"}) :Do(function(_,data) if( (message_number ~= 2) and (message_number ~= 3)) then commonFunctions:printError("Error: SDL.OnStatusUpdate reponse is not received as message 2/3 after SDL.GetURLS request. Real: "..message_number) is_test_fail = true else print("SDL.OnStatusUpdate("..data.params.status..") is received as message "..message_number.." after SDL.GetURLS request") end message_number = message_number + 1 end) if(is_test_fail == true) then self:FailTestCase("Test is FAILED. See prints.") end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_StopSDL() StopSDL() end return Test
Fix issues
Fix issues
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
b405f1d083b9d2355138780ad4fcf768b4f565e7
src/lib/configure/lang/c/compiler/msvc.lua
src/lib/configure/lang/c/compiler/msvc.lua
--- MSVC compiler implementation -- @classmod configure.lang.c.compiler.msvc local Super = require('configure.lang.c.compiler.base') local tools = require('configure.tools') local Compiler = table.update({}, Super) Compiler.name = 'msvc' Compiler.binary_names = {'cl.exe', } Compiler.lang = 'c' Compiler._language_flag = '-TC' Compiler.optional_args = table.update( table.update({}, Super.optional_args), { shared_library_directory = Super.optional_args.executable_directory } ) function Compiler:new(args) local o = Super.new(self, args) o.link_path = o:find_tool("LINK", "Link program", "link.exe") o.lib_path = o:find_tool("LIB", "Lib program", "lib.exe") return o end Compiler._optimization_flags = { no = {"-Od", }, yes = {"-Ox", }, size = {"-O1", }, harder = {"-O2", }, fastest = {"-O2", }, } function Compiler:_add_optimization_flag(cmd, args) table.extend(cmd, self._optimization_flags[args.optimization]) end function Compiler:_build_object(args) local command = { self.binary_path, '-nologo', self._language_flag } self:_add_optimization_flag(command, args) if args.exception == true then table.append(command, '-EHsc') end if args.debug then table.append(command, '-Z7') end if args.warnings then table.append(command, '-W3') end local defines = table.extend({}, args.defines) if args.runtime == 'static' then if args.threading then table.append(command, '-MT') else table.append(command, '-ML') end else -- dynamic runtime if args.threading then table.append(command, '-MD') else table.append(command, '-ML') -- Single threaded app defines.append({'_DLL'}) -- XXX is it enough for dynamic runtime ? end end for _, dir in ipairs(args.include_directories) do table.extend(command, {'-I', dir}) end local define_args = {} for _, define in ipairs(defines) do if define[2] == nil then table.insert(define_args, '-D' .. define[1]) else table.insert(define_args, '-D' .. define[1] .. '=' .. tostring(define[2])) end end table.extend(command, tools.unique(define_args)) for _, file in ipairs(args.include_files) do table.extend(command, {'-FI', file}) end table.extend(command, {"-c", args.source, '-Fo' .. tostring(args.target:path())}) self.build:add_rule( Rule:new() :add_source(args.source) :add_sources(args.install_nodes) :add_target(args.target) :add_shell_command(ShellCommand:new(table.unpack(command))) ) return args.target end function Compiler:_link_executable(args) local command = {self.link_path, '-nologo',} if args.debug then table.append(command, '-DEBUG') end if args.coverage then table.append(command, '-Profile') end for _, dir in ipairs(args.library_directories) do table.append(command, '-LIBPATH:' .. tostring(dir:path())) end local library_sources = {} for _, lib in ipairs(args.libraries) do if lib.system then if lib.kind == 'static' then table.append(command, lib.name .. '.lib') elseif lib.kind == 'shared' then table.append(command, lib.name .. '.lib') end else for _, file in ipairs(lib.files) do local path = file if getmetatable(file) == Node then table.append(library_sources, file) path = file:path() end table.append(command, '-LIBPATH:' .. tostring(path:parent_path())) table.append(command, path:filename()) end end end table.extend(command, args.objects) table.append(command, "-OUT:" .. tostring(args.target:path())) self.build:add_rule( Rule:new() :add_sources(args.objects) :add_sources(library_sources) :add_target(args.target) :add_shell_command(ShellCommand:new(table.unpack(command))) ) return args.target end function Compiler:_link_library(args) local command = {} local linker_lib = nil local rule = Rule:new():add_sources(args.objects):add_target(args.target) if args.kind == 'shared' then linker_lib = self.build:target_node( args.import_library_directory / (args.target:path():stem() + ".lib") ) rule:add_target(linker_lib) table.extend(command, {self.link_path, '-DLL', '-IMPLIB:' .. tostring(linker_lib:path())}) if args.debug then table.append(command, '-DEBUG') end if args.coverage then table.append(command, '-Profile') end else table.extend(command, {self.lib_path}) linker_lib = args.target end table.extend(command, { '-nologo', '-OUT:' .. tostring(args.target:path()) }) table.extend(command, args.objects) self.build:add_rule( rule:add_shell_command(ShellCommand:new(table.unpack(command))) ) return linker_lib end function Compiler:_library_extension(kind, ext) if ext then return ext end if kind == 'shared' then return ".dll" else return ".lib" end end function Compiler:_object_extension(ext) return ext or ".obj" end local os = require('os') function Compiler:_system_include_directories() local res = {} table.extend(res, os.getenv('INCLUDE'):split(';')) local dirs = {} for _, dir in ipairs(res) do local p = Path:new(dir) if p:is_directory() then self.build:debug('Found system include dir', p) table.append(dirs, p) end end return dirs end function Compiler:_system_library_directories() local res = {} table.extend(res, os.getenv('LIB'):split(';')) table.extend(res, os.getenv('LIBPATH'):split(';')) local dirs = {} for _, dir in ipairs(res) do local p = Path:new(dir) if p:is_directory() then self.build:debug('Found system library dir', p) table.append(dirs, p) else self.build:debug('ignore system library dir', p) end end return dirs end return Compiler
--- MSVC compiler implementation -- @classmod configure.lang.c.compiler.msvc local Super = require('configure.lang.c.compiler.base') local tools = require('configure.tools') local Compiler = table.update({}, Super) Compiler.name = 'msvc' Compiler.binary_names = {'cl.exe', } Compiler.lang = 'c' Compiler._language_flag = '-TC' Compiler.optional_args = table.update( table.update({}, Super.optional_args), { shared_library_directory = Super.optional_args.executable_directory } ) function Compiler:new(args) local o = Super.new(self, args) o.link_path = o:find_tool("LINK", "Link program", "link.exe") o.lib_path = o:find_tool("LIB", "Lib program", "lib.exe") return o end Compiler._optimization_flags = { no = {"-Od", }, yes = {"-Ox", }, size = {"-O1", }, harder = {"-O2", }, fastest = {"-O2", }, } function Compiler:_add_optimization_flag(cmd, args) table.extend(cmd, self._optimization_flags[args.optimization]) end function Compiler:_build_object(args) local command = { self.binary_path, '-nologo', self._language_flag } self:_add_optimization_flag(command, args) if args.exception == true then table.append(command, '-EHsc') end if args.debug then table.append(command, '-Z7') end if args.warnings then table.append(command, '-W3') end local defines = table.extend({}, args.defines) if args.runtime == 'static' then if args.threading then table.append(command, '-MT') else table.append(command, '-ML') end else -- dynamic runtime if args.threading then table.append(command, '-MD') else table.append(command, '-ML') -- Single threaded app defines.append({'_DLL'}) -- XXX is it enough for dynamic runtime ? end end for _, dir in ipairs(args.include_directories) do table.extend(command, {'-I', dir}) end local define_args = {} for _, define in ipairs(defines) do if define[2] == nil then table.insert(define_args, '-D' .. define[1]) else table.insert(define_args, '-D' .. define[1] .. '=' .. tostring(define[2])) end end table.extend(command, tools.unique(define_args)) for _, file in ipairs(args.include_files) do table.extend(command, {'-FI', file}) end table.extend(command, {"-c", args.source, '-Fo' .. tostring(args.target:path())}) self.build:add_rule( Rule:new() :add_source(args.source) :add_sources(args.install_nodes) :add_target(args.target) :add_shell_command(ShellCommand:new(table.unpack(command))) ) return args.target end function Compiler:_add_linker_library_flags(command, args, sources) for _, dir in ipairs(args.library_directories) do table.append(command, '-LIBPATH:' .. tostring(dir:path())) end for _, lib in ipairs(args.libraries) do if lib.system then if lib.kind == 'static' then table.append(command, lib.name .. '.lib') elseif lib.kind == 'shared' then table.append(command, lib.name .. '.lib') end else for _, file in ipairs(lib.files) do local path = file if getmetatable(file) == Node then table.append(sources, file) path = file:path() end table.append(command, '-LIBPATH:' .. tostring(path:parent_path())) table.append(command, path:filename()) end end end end function Compiler:_link_executable(args) local command = {self.link_path, '-nologo',} if args.debug then table.append(command, '-DEBUG') end if args.coverage then table.append(command, '-Profile') end local library_sources = {} self:_add_linker_library_flags(command, args, library_sources) table.extend(command, args.objects) table.append(command, "-OUT:" .. tostring(args.target:path())) self.build:add_rule( Rule:new() :add_sources(args.objects) :add_sources(library_sources) :add_target(args.target) :add_shell_command(ShellCommand:new(table.unpack(command))) ) return args.target end function Compiler:_link_library(args) local command = {} local linker_lib = nil local rule = Rule:new() if args.kind == 'shared' then linker_lib = self.build:target_node( args.import_library_directory / (args.target:path():stem() + ".lib") ) rule:add_target(linker_lib) table.extend(command, {self.link_path, '-DLL', '-IMPLIB:' .. tostring(linker_lib:path())}) if args.debug then table.append(command, '-DEBUG') end if args.coverage then table.append(command, '-Profile') end else table.extend(command, {self.lib_path}) linker_lib = args.target end table.extend(command, { '-nologo', '-OUT:' .. tostring(args.target:path()) }) local library_sources = {} self:_add_linker_library_flags(command, args, library_sources) table.extend(command, args.objects) self.build:add_rule( rule :add_sources(args.objects) :add_sources(library_sources) :add_target(args.target) :add_shell_command(ShellCommand:new(table.unpack(command))) ) return linker_lib end function Compiler:_library_extension(kind, ext) if ext then return ext end if kind == 'shared' then return ".dll" else return ".lib" end end function Compiler:_object_extension(ext) return ext or ".obj" end local os = require('os') function Compiler:_system_include_directories() local res = {} table.extend(res, os.getenv('INCLUDE'):split(';')) local dirs = {} for _, dir in ipairs(res) do local p = Path:new(dir) if p:is_directory() then self.build:debug('Found system include dir', p) table.append(dirs, p) end end return dirs end function Compiler:_system_library_directories() local res = {} table.extend(res, os.getenv('LIB'):split(';')) table.extend(res, os.getenv('LIBPATH'):split(';')) local dirs = {} for _, dir in ipairs(res) do local p = Path:new(dir) if p:is_directory() then self.build:debug('Found system library dir', p) table.append(dirs, p) else self.build:debug('ignore system library dir', p) end end return dirs end return Compiler
lang.c.compiler.msvc: Fix link flags when linking a library.
lang.c.compiler.msvc: Fix link flags when linking a library.
Lua
bsd-3-clause
hotgloupi/configure,hotgloupi/configure,hotgloupi/configure,hotgloupi/configure,hotgloupi/configure
f3612a683217537c81566051bb78977b63ebbe96
Render.lua
Render.lua
--[[ Modulo per ridurre le chiamate a lua in caso di molti entry This module is used when there's the need to invoke the same module function many times in a row (for instance when each call is an entry of a list). The goal of this module is to squash all calls in a single #invoke in order to make it much more lightweight. The syntax is as follows {{#invoke: render | newrender | <module> | <function> | <separator> | <parameters of the first entry> | <separator> | <parameters of the second entry> | <separator> ... }} The separator should be a (nonempty) sequence of "-" of any length enclosed between "/". For instance "/-/" or "/--/". Also "//" is fine. Unnamed parameters for a single entry are put as you would in a normal invocation, so values separated by |. For named parameter you have to use a slightly different syntax: <param name> <- <value> again separated by a | So for instance a pair of invocations like {{#invoke: somemodule | somefunction | arg11 | arg12 | arg13 | key1 = val11 | key2 = val12 }} {{#invoke: somemodule | somefunction | arg21 | arg22 | arg23 | key1 = val21 }} becomes {{#invoke: render | render | somemodule | somefunction | // | arg11 | arg12 | arg13 | key1 <- val11 | key2 <- val12 | // | arg21 | arg22 | arg23 | key1 <- val21 | // }} (note: the last separator // is optional, but my suggestion is to add it) --]] local r = {} local mw = require('mw') local w = require('Wikilib') local tab = require('Wikilib-tables') -- luacheck: no unused r.entry = function(frame) local p = w.trimAll(mw.clone(frame.args)) local modu = require('' .. p[1]:match('^(.+)%.')) local func = p[1]:match('%.([%a%d]+)$') table.remove(p, 1) return w.mapAndConcat(p, '\n', function(value) local prepared = value:gsub('%[%[(.*)%]%]', '%1') :gsub('|', '£€') local mockFrame = {args={}} for param in prepared:gmatch('€(.-)£') do local k, v = param:match('^(.+)=(.+)$') if k and v then mockFrame.args[k] = v else table.insert(mockFrame.args, param) end end return modu[func](mockFrame) end) end --[[ New render function. The previous function was based on a hack of MediaWiki, so we decided it is better to have a nicer syntax. Also because the current implementation has problems if you want to put a link/template within the entry. For the syntax check the doc at the top of the file. --]] r.render = function(frame) local p = w.trimAll(mw.clone(frame.args), false) local modulename = p[1] local modulefunc = require(modulename)[p[2]] local separator = p[3] -- Check if separator matches the standard if not separator:match("^/%-*/$") then error("Ill formatted separator") end -- The last separator is optional. If not given, adds it if p[#p] ~= separator then table.insert(p, separator) end local mockArgs = {} local res = {} for i = 4, #p do local param = p[i] if not param then print(i, "'" .. param .. "'") return end if param == separator then -- print(require("static.dumper")(mockArgs)) table.insert(res, modulefunc{args = mockArgs}) -- Prepare for the next call mockArgs = {} else local beg = param:find("<%-") if beg then local key = param:sub(1, beg - 1):trim() mockArgs[key] = param:sub(beg + 2):trim() else table.insert(mockArgs, p[i]) end end end return table.concat(res, "\n") end return r
--[[ Modulo per ridurre le chiamate a lua in caso di molti entry This module is used when there's the need to invoke the same module function many times in a row (for instance when each call is an entry of a list). The goal of this module is to squash all calls in a single #invoke in order to make it much more lightweight. The syntax is as follows {{#invoke: render | render | <module> | <function> | <separator> | <parameters of the first entry> | <separator> | <parameters of the second entry> | <separator> ... }} The separator should be a (possibly empty) sequence of "-" enclosed between "/". For instance "/-/" or "/--/"; also "//" is fine. Unnamed parameters for a single entry are put as you would in a normal invocation, so values separated by |. For named parameter you have to use a slightly different syntax: <param name> <- <value> again separated by a | So for instance a pair of invocations like {{#invoke: somemodule | somefunction | arg11 | arg12 | arg13 | key1 = val11 | key2 = val12 }} {{#invoke: somemodule | somefunction | arg21 | arg22 | arg23 | key1 = val21 }} becomes {{#invoke: render | render | somemodule | somefunction | // | arg11 | arg12 | arg13 | key1 <- val11 | key2 <- val12 | // | arg21 | arg22 | arg23 | key1 <- val21 | // }} (note: the last separator // is optional, but my suggestion is to add it) --]] local r = {} local mw = require('mw') local w = require('Wikilib') local tab = require('Wikilib-tables') -- luacheck: no unused r.entry = function(frame) local p = w.trimAll(mw.clone(frame.args)) local modu = require('' .. p[1]:match('^(.+)%.')) local func = p[1]:match('%.([%a%d]+)$') table.remove(p, 1) return w.mapAndConcat(p, '\n', function(value) local prepared = value:gsub('%[%[(.*)%]%]', '%1') :gsub('|', '£€') local mockFrame = {args={}} for param in prepared:gmatch('€(.-)£') do local k, v = param:match('^(.+)=(.+)$') if k and v then mockFrame.args[k] = v else table.insert(mockFrame.args, param) end end return modu[func](mockFrame) end) end --[[ New render function. The previous function was based on a hack of MediaWiki, so we decided it is better to have a nicer syntax. Also because the current implementation has problems if you want to put a link/template within the entry. For the syntax check the doc at the top of the file. --]] r.render = function(frame) local p = w.trimAll(mw.clone(frame.args), false) local modulename = p[1] local modulefunc = require(modulename)[p[2]] local separator = p[3] -- Check if separator matches the standard if not separator:match("^/%-*/$") then error("Ill formatted separator") end -- The last separator is optional. If not given, adds it if p[#p] ~= separator then table.insert(p, separator) end local mockArgs = {} local res = {} for i = 4, #p do local param = p[i] if not param then print(i, "'" .. param .. "'") return end if param == separator then table.insert(res, modulefunc{args = mockArgs}) -- Prepare for the next call mockArgs = {} else local beg = param:find("<%-") if beg then local key = string.trim(param:sub(1, beg - 1)) mockArgs[key] = string.trim(param:sub(beg + 2)) else table.insert(mockArgs, p[i]) end end end return table.concat(res, "\n") end return r
Fixed trim call in render (can't be called as object method on MW)
Fixed trim call in render (can't be called as object method on MW)
Lua
cc0-1.0
pokemoncentral/wiki-lua-modules
8ae7c792b6c6b1eda268d8953fa8737a9ad7dc91
item/id_1206_claypit.lua
item/id_1206_claypit.lua
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- UPDATE items SET itm_script='item.id_1206_claypit' WHERE itm_id=1206; local common = require("base.common") local lookat = require("base.lookat") local climbing = require("content.climbing") local claydigging = require("craft.gathering.claydigging") local M = {} local holePosition = { position(854, 414, 0), position(659, 255, 0) } function M.UseItem(User, SourceItem, ltstate) for i = 1, #holePosition do if (SourceItem.pos == holePosition[i]) then common.HighInformNLS(User, "Du brauchst ein Seil um hier hinab zu klettern.", "You need a rope to climb down here.") if climbing.hasRope(User) then climbing.climbDown(User) end return end end claydigging.StartGathering(User, SourceItem, ltstate) end function M.LookAtItem(User, Item) local lookAt = lookat.GenerateLookAt(User, Item) if Item.pos == holePosition then lookAt.name = common.GetNLS(User, "Ein tiefes Loch.", "A deep hole.") lookAt.description = common.GetNLS(User, "Dieses Loch scheint bodenlos.", "This hole looks bottomless.") end return lookAt end return M
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- UPDATE items SET itm_script='item.id_1206_claypit' WHERE itm_id=1206; local common = require("base.common") local lookat = require("base.lookat") local climbing = require("content.climbing") local claydigging = require("craft.gathering.claydigging") local M = {} local holePosition = { position(854, 414, 0), position(659, 255, 0) } function M.UseItem(User, SourceItem, ltstate) for i = 1, #holePosition do if (SourceItem.pos == holePosition[i]) then if climbing.hasRope(User) then climbing.climbDown(User) else common.HighInformNLS(User, "Du brauchst ein Seil um hier hinab zu klettern.", "You need a rope to climb down here.") end return end end claydigging.StartGathering(User, SourceItem, ltstate) end function M.LookAtItem(User, Item) local lookAt = lookat.GenerateLookAt(User, Item) local foundClimbableClaypit = false for index=1,#(holePosition),1 do if(holePosition[index] == Item.pos) then foundClimbableClaypit = true break end end if foundClimbableClaypit then lookAt.name = common.GetNLS(User, "Ein tiefes Loch.", "A deep hole.") lookAt.description = common.GetNLS(User, "Dieses Loch scheint bodenlos.", "This hole looks bottomless.") end return lookAt end return M
Fix custom lookAt for claypits
Fix custom lookAt for claypits
Lua
agpl-3.0
Illarion-eV/Illarion-Content
bbc6057f9602787119d3654c58b3d62ca54c9852
tests/projects/static_library_go/xmake.lua
tests/projects/static_library_go/xmake.lua
-- the debug mode if is_mode("debug") then -- enable the debug symbols set_symbols("debug") -- disable optimization set_optimize("none") end -- the release mode if is_mode("release") then -- set the symbols visibility: hidden set_symbols("hidden") -- enable fastest optimization set_optimize("fastest") -- strip all symbols set_strip("all") end -- add target target("module") -- set kind set_kind("static") -- add files add_files("src/test/*.go") -- add target target("test") -- set kind set_kind("binary") -- add deps add_deps("module") -- add files add_files("src/*.go") -- add link directory add_linkdirs("$(buildir)") -- add include directory add_includedirs("$(buildir)")
-- the debug mode if is_mode("debug") then -- enable the debug symbols set_symbols("debug") -- disable optimization set_optimize("none") end -- the release mode if is_mode("release") then -- set the symbols visibility: hidden set_symbols("hidden") -- enable fastest optimization set_optimize("fastest") -- strip all symbols set_strip("all") end -- add target target("module") -- set kind set_kind("static") -- add files add_files("src/test/*.go") -- add target target("test") -- set kind set_kind("binary") -- add deps add_deps("module") -- add files add_files("src/*.go") -- add link directory add_linkdirs("$(buildir)/$(mode)/$(arch)") -- add include directory add_includedirs("$(buildir)/$(mode)/$(arch)")
fix go test
fix go test
Lua
apache-2.0
tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake
a6562b56fc7b7a9dc3a643fc234ec98236b5d126
stdlib/event/surface.lua
stdlib/event/surface.lua
--- Surface global creation. -- <p>All surfaces will be added to the `global.forces` table. -- <p>This modules events should be registered after any other Init functions but before any scripts needing `global.surfaces`. -- <p>This modules can register the following events: -- @module Event.Surface -- @usage -- local surface = require('__stdlib__/stdlib/event/surface').register_events() local Event = require('__stdlib__/stdlib/event/event') local Surface = { _module = 'Surface', _new_surface_data = {} } setmetatable(Surface, require('__stdlib__/stdlib/core')) local Is = require('__stdlib__/stdlib/utils/is') -- local Game = require('__stdlib__/stdlib/game') -- local table = require('__stdlib__/stdlib/utils/table') local merge_additional_data = require('__stdlib__/stdlib/event/modules/merge_data') local function new(index) local surface = game.surfaces[index] local sdata = { index = surface.index, name = surface.name, } merge_additional_data(Surface._new_surface_data, sdata) return sdata end function Surface.additional_data(...) for _, func_or_table in pairs({...}) do Is.Assert(Is.Table(func_or_table) or Is.Function(func_or_table), 'Must be table or function') Surface._new_surface_data[#Surface._new_surface_data + 1] = func_or_table end return Surface end --- Remove data for a player when they are deleted. -- @tparam table event event table containing the `player_index` function Surface.remove(event) global.surfaces[event.surface_index] = nil end function Surface.rename(event) global.surfaces[event.surface_index].name = event.new_name end function Surface.import(event) new(event.surface_index) end -- function Surface.cleared(event) -- end --- Init or re-init a player or players. -- Passing a `nil` event will iterate all existing players. -- @tparam[opt] number|table|string|LuaPlayer event -- @tparam[opt=false] boolean overwrite the player data function Surface.init(event, overwrite) -- Create the global.players table if it doesn't exisit global.surfaces = global.surfaces or {} --get a valid player object or nil local surface = game.surfaces[event.surface_index] if surface then if not global.surfaces[surface.index] or (global.surfaces[surface.index] and overwrite) then global.surfaces[surface.index] = new(surface.index) return global.surfaces[surface.index] end else --Check all surfaces for index in pairs(game.surfaces) do if not global.surfaces[index] or (global.surfaces[index] and overwrite) then global.surfaces[index] = new(index) end end end return Surface end function Surface.dump_data() game.write_file(Surface.get_file_path('Surface/surface_data.lua'), inspect(Surface._new_surface_data, {longkeys = true, arraykeys = true})) game.write_file(Surface.get_file_path('Surface/global.lua'), inspect(global.surfaces or nil, {longkeys = true, arraykeys = true})) end function Surface.register_init() Event.register(Event.core_events.init, Surface.init) return Surface end function Surface.register_events(do_on_init) Event.register(defines.events.on_surface_created, Surface.init) Event.register(defines.events.on_surface_deleted, Surface.remove) Event.register(defines.events.on_surface_imported, Surface.import) Event.register(defines.events.on_surface_renamed, Surface.rename) --Event.register(defines.events.on_surface_cleared, Surface.func) if do_on_init then Surface.register_init() end return Surface end return Surface
--- Surface global creation. -- <p>All surfaces will be added to the `global.surfaces` table. -- <p>This modules events should be registered after any other Init functions but before any scripts needing `global.surfaces`. -- <p>This modules can register the following events: -- @module Event.Surface -- @usage -- local surface = require('__stdlib__/stdlib/event/surface').register_events() local Event = require('__stdlib__/stdlib/event/event') local Surface = { _module = 'Surface', _new_surface_data = {} } setmetatable(Surface, require('__stdlib__/stdlib/core')) local Is = require('__stdlib__/stdlib/utils/is') -- local Game = require('__stdlib__/stdlib/game') -- local table = require('__stdlib__/stdlib/utils/table') local merge_additional_data = require('__stdlib__/stdlib/event/modules/merge_data') local function new(index) local surface = game.surfaces[index] local sdata = { index = surface.index, name = surface.name, } merge_additional_data(Surface._new_surface_data, sdata) return sdata end function Surface.additional_data(...) for _, func_or_table in pairs({...}) do Is.Assert(Is.Table(func_or_table) or Is.Function(func_or_table), 'Must be table or function') Surface._new_surface_data[#Surface._new_surface_data + 1] = func_or_table end return Surface end --- Remove data for a surface when it is deleted. -- @tparam table event event table containing the surface index function Surface.remove(event) global.surfaces[event.surface_index] = nil end function Surface.rename(event) global.surfaces[event.surface_index].name = event.new_name end function Surface.import(event) new(event.surface_index) end -- function Surface.cleared(event) -- end --- Init or re-init the surfaces. -- Passing a `nil` event will iterate all existing surfaces. -- @tparam[opt] number|table|string|LuaSurface event -- @tparam[opt=false] boolean overwrite the surface data function Surface.init(event, overwrite) -- Create the global.surfaces table if it doesn't exisit global.surfaces = global.surfaces or {} --get a valid surface object or nil local surface = game.surfaces[event.surface_index] if surface then if not global.surfaces[surface.index] or (global.surfaces[surface.index] and overwrite) then global.surfaces[surface.index] = new(surface.index) return global.surfaces[surface.index] end else --Check all surfaces for index in pairs(game.surfaces) do if not global.surfaces[index] or (global.surfaces[index] and overwrite) then global.surfaces[index] = new(index) end end end return Surface end function Surface.dump_data() game.write_file(Surface.get_file_path('Surface/surface_data.lua'), inspect(Surface._new_surface_data, {longkeys = true, arraykeys = true})) game.write_file(Surface.get_file_path('Surface/global.lua'), inspect(global.surfaces or nil, {longkeys = true, arraykeys = true})) end function Surface.register_init() Event.register(Event.core_events.init, Surface.init) return Surface end function Surface.register_events(do_on_init) Event.register(defines.events.on_surface_created, Surface.init) Event.register(defines.events.on_surface_deleted, Surface.remove) Event.register(defines.events.on_surface_imported, Surface.import) Event.register(defines.events.on_surface_renamed, Surface.rename) --Event.register(defines.events.on_surface_cleared, Surface.func) if do_on_init then Surface.register_init() end return Surface end return Surface
Doc Copypasta fix
Doc Copypasta fix
Lua
isc
Afforess/Factorio-Stdlib
aa254e28354ded1a09916905eeb0ede2bf76450d
mods/default/craftitems.lua
mods/default/craftitems.lua
-- mods/default/craftitems.lua minetest.register_craftitem("default:stick", { description = "Stick", inventory_image = "default_stick.png", groups = {stick=1}, }) minetest.register_craftitem("default:paper", { description = "Paper", inventory_image = "default_paper.png", }) local function book_on_use(itemstack, user, pointed_thing) local player_name = user:get_player_name() local data = minetest.deserialize(itemstack:get_metadata()) local title, text, owner = "", "", player_name if data then title, text, owner = data.title, data.text, data.owner end local formspec if owner == player_name then formspec = "size[8,8]"..default.gui_bg.. default.gui_bg_img.. "field[0.5,1;7.5,0;title;Title:;".. minetest.formspec_escape(title).."]".. "textarea[0.5,1.5;7.5,7;text;Contents:;".. minetest.formspec_escape(text).."]".. "button_exit[2.5,7.5;3,1;save;Save]" else formspec = "size[8,8]"..default.gui_bg.. default.gui_bg_img.. "label[0.5,0.5;by "..owner.."]".. "label[0.5,0;"..minetest.formspec_escape(title).."]".. "tableoptions[background=#00000000;highlight=#00000000;border=false]".. "table[0.5,1.5;7.5,7;;"..minetest.formspec_escape(text):gsub("\n", ",")..";1]" end minetest.show_formspec(user:get_player_name(), "default:book", formspec) end minetest.register_on_player_receive_fields(function(player, form_name, fields) if form_name ~= "default:book" or not fields.save or fields.title == "" or fields.text == "" then return end local inv = player:get_inventory() local stack = player:get_wielded_item() local new_stack, data if stack:get_name() ~= "default:book_written" then local count = stack:get_count() if count == 1 then stack:set_name("default:book_written") else stack:set_count(count - 1) new_stack = ItemStack("default:book_written") end else data = minetest.deserialize(stack:get_metadata()) end if not data then data = {} end data.title = fields.title data.text = fields.text data.owner = player:get_player_name() local data_str = minetest.serialize(data) if new_stack then new_stack:set_metadata(data_str) if inv:room_for_item("main", new_stack) then inv:add_item("main", new_stack) else minetest.add_item(player:getpos(), new_stack) end else stack:set_metadata(data_str) end player:set_wielded_item(stack) end) minetest.register_craftitem("default:book", { description = "Book", inventory_image = "default_book.png", groups = {book=1}, on_use = book_on_use, }) minetest.register_craftitem("default:book_written", { description = "Book With Text", inventory_image = "default_book_written.png", groups = {book=1, not_in_creative_inventory=1}, stack_max = 1, on_use = book_on_use, }) minetest.register_craft({ type = "shapeless", output = "default:book_written", recipe = { "default:book", "default:book_written" } }) minetest.register_on_craft(function(itemstack, player, old_craft_grid, craft_inv) if itemstack:get_name() ~= "default:book_written" then return end local copy = ItemStack("default:book_written") local original local index for i = 1, player:get_inventory():get_size("craft") do if old_craft_grid[i]:get_name() == "default:book_written" then original = old_craft_grid[i] index = i end end if not original then return end local copymeta = original:get_metadata() -- copy of the book held by player's mouse cursor itemstack:set_metadata(copymeta) -- put the book with metadata back in the craft grid craft_inv:set_stack("craft", index, original) end) minetest.register_craftitem("default:coal_lump", { description = "Coal Lump", inventory_image = "default_coal_lump.png", groups = {coal = 1} }) minetest.register_craftitem("default:iron_lump", { description = "Iron Lump", inventory_image = "default_iron_lump.png", }) minetest.register_craftitem("default:copper_lump", { description = "Copper Lump", inventory_image = "default_copper_lump.png", }) minetest.register_craftitem("default:mese_crystal", { description = "Mese Crystal", inventory_image = "default_mese_crystal.png", }) minetest.register_craftitem("default:gold_lump", { description = "Gold Lump", inventory_image = "default_gold_lump.png", }) minetest.register_craftitem("default:diamond", { description = "Diamond", inventory_image = "default_diamond.png", }) minetest.register_craftitem("default:clay_lump", { description = "Clay Lump", inventory_image = "default_clay_lump.png", }) minetest.register_craftitem("default:steel_ingot", { description = "Steel Ingot", inventory_image = "default_steel_ingot.png", }) minetest.register_craftitem("default:copper_ingot", { description = "Copper Ingot", inventory_image = "default_copper_ingot.png", }) minetest.register_craftitem("default:bronze_ingot", { description = "Bronze Ingot", inventory_image = "default_bronze_ingot.png", }) minetest.register_craftitem("default:gold_ingot", { description = "Gold Ingot", inventory_image = "default_gold_ingot.png" }) minetest.register_craftitem("default:mese_crystal_fragment", { description = "Mese Crystal Fragment", inventory_image = "default_mese_crystal_fragment.png", }) minetest.register_craftitem("default:clay_brick", { description = "Clay Brick", inventory_image = "default_clay_brick.png", }) minetest.register_craftitem("default:obsidian_shard", { description = "Obsidian Shard", inventory_image = "default_obsidian_shard.png", })
-- mods/default/craftitems.lua minetest.register_craftitem("default:stick", { description = "Stick", inventory_image = "default_stick.png", groups = {stick=1}, }) minetest.register_craftitem("default:paper", { description = "Paper", inventory_image = "default_paper.png", }) local function book_on_use(itemstack, user, pointed_thing) local player_name = user:get_player_name() local data = minetest.deserialize(itemstack:get_metadata()) local title, text, owner = "", "", player_name if data then title, text, owner = data.title, data.text, data.owner end local formspec if owner == player_name then formspec = "size[8,8]"..default.gui_bg.. default.gui_bg_img.. "field[0.5,1;7.5,0;title;Title:;".. minetest.formspec_escape(title).."]".. "textarea[0.5,1.5;7.5,7;text;Contents:;".. minetest.formspec_escape(text).."]".. "button_exit[2.5,7.5;3,1;save;Save]" else formspec = "size[8,8]"..default.gui_bg.. default.gui_bg_img.. "label[0.5,0.5;by "..owner.."]".. "label[0.5,0;"..minetest.formspec_escape(title).."]".. "textarea[0.5,1.5;7.5,7;text;;".. minetest.formspec_escape(text).."]" end minetest.show_formspec(user:get_player_name(), "default:book", formspec) end minetest.register_on_player_receive_fields(function(player, form_name, fields) if form_name ~= "default:book" or not fields.save or fields.title == "" or fields.text == "" then return end local inv = player:get_inventory() local stack = player:get_wielded_item() local new_stack, data if stack:get_name() ~= "default:book_written" then local count = stack:get_count() if count == 1 then stack:set_name("default:book_written") else stack:set_count(count - 1) new_stack = ItemStack("default:book_written") end else data = minetest.deserialize(stack:get_metadata()) end if not data then data = {} end data.title = fields.title data.text = fields.text data.owner = player:get_player_name() local data_str = minetest.serialize(data) if new_stack then new_stack:set_metadata(data_str) if inv:room_for_item("main", new_stack) then inv:add_item("main", new_stack) else minetest.add_item(player:getpos(), new_stack) end else stack:set_metadata(data_str) end player:set_wielded_item(stack) end) minetest.register_craftitem("default:book", { description = "Book", inventory_image = "default_book.png", groups = {book=1}, on_use = book_on_use, }) minetest.register_craftitem("default:book_written", { description = "Book With Text", inventory_image = "default_book_written.png", groups = {book=1, not_in_creative_inventory=1}, stack_max = 1, on_use = book_on_use, }) minetest.register_craft({ type = "shapeless", output = "default:book_written", recipe = { "default:book", "default:book_written" } }) minetest.register_on_craft(function(itemstack, player, old_craft_grid, craft_inv) if itemstack:get_name() ~= "default:book_written" then return end local copy = ItemStack("default:book_written") local original local index for i = 1, player:get_inventory():get_size("craft") do if old_craft_grid[i]:get_name() == "default:book_written" then original = old_craft_grid[i] index = i end end if not original then return end local copymeta = original:get_metadata() -- copy of the book held by player's mouse cursor itemstack:set_metadata(copymeta) -- put the book with metadata back in the craft grid craft_inv:set_stack("craft", index, original) end) minetest.register_craftitem("default:coal_lump", { description = "Coal Lump", inventory_image = "default_coal_lump.png", groups = {coal = 1} }) minetest.register_craftitem("default:iron_lump", { description = "Iron Lump", inventory_image = "default_iron_lump.png", }) minetest.register_craftitem("default:copper_lump", { description = "Copper Lump", inventory_image = "default_copper_lump.png", }) minetest.register_craftitem("default:mese_crystal", { description = "Mese Crystal", inventory_image = "default_mese_crystal.png", }) minetest.register_craftitem("default:gold_lump", { description = "Gold Lump", inventory_image = "default_gold_lump.png", }) minetest.register_craftitem("default:diamond", { description = "Diamond", inventory_image = "default_diamond.png", }) minetest.register_craftitem("default:clay_lump", { description = "Clay Lump", inventory_image = "default_clay_lump.png", }) minetest.register_craftitem("default:steel_ingot", { description = "Steel Ingot", inventory_image = "default_steel_ingot.png", }) minetest.register_craftitem("default:copper_ingot", { description = "Copper Ingot", inventory_image = "default_copper_ingot.png", }) minetest.register_craftitem("default:bronze_ingot", { description = "Bronze Ingot", inventory_image = "default_bronze_ingot.png", }) minetest.register_craftitem("default:gold_ingot", { description = "Gold Ingot", inventory_image = "default_gold_ingot.png" }) minetest.register_craftitem("default:mese_crystal_fragment", { description = "Mese Crystal Fragment", inventory_image = "default_mese_crystal_fragment.png", }) minetest.register_craftitem("default:clay_brick", { description = "Clay Brick", inventory_image = "default_clay_brick.png", }) minetest.register_craftitem("default:obsidian_shard", { description = "Obsidian Shard", inventory_image = "default_obsidian_shard.png", })
Fix book formspec to word-wrap lines
Fix book formspec to word-wrap lines Books still don't wrap long lines of text properly so until this has been sorted out I suggest reverting back to a previous working formspec which lets players read books properly until a fix is found (and maybe scrollbars added to texarea's). Also adding a recipe to blank written books.
Lua
lgpl-2.1
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
ab06f654a77137f9fa063937d4a2707252dc2557
src/premake/PGTA.lua
src/premake/PGTA.lua
-- Procedurally Generated Transitional Audio Build -- if (os.get() ~= "windows") then include "compilationunit.lua" end function run_include(script, rel_dir) local external_dir = path.getabsolute("../external") local repo_dir = path.join(external_dir, rel_dir) local script_full = external_dir.."/build-tools/premake_scripts/"..script local output_dir = path.getabsolute("../premake/".._ACTION) assert(loadfile(script_full))(repo_dir, output_dir) end solution "PGTA" location(_ACTION) targetdir(_ACTION) startproject "EngineTest" language "C++" platforms { "x64", "x32" } configurations { "Debug", "Release" } flags { "Symbols", "StaticRuntime", "NoMinimalRebuild", "NoEditAndContinue", "MultiProcessorCompile" } filter "action:vs*" defines { "_CRT_SECURE_NO_WARNINGS", "_SCL_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_DEPRECATE" } filter { "action:not vs*" } buildoptions "-fPIC" compilationunitdir(_ACTION.."/%{prj.name}Dir") filter { "action:not vs*", "language:C++" } buildoptions "-std=c++1y" filter { "action:not vs*", "language:C" } buildoptions "-std=c11" filter "Debug" defines { "DEBUG", "_DEBUG" } filter "Release" flags "LinkTimeOptimization" defines "NDEBUG" optimize "Full" filter {} group "Externals" run_include("flatbuffers.lua", "flatbuffers") group "Externals" run_include("flatc.lua", "flatbuffers") group "Externals" run_include("sdl2.lua", "SDL2") group "PGTA" dofile "AudioMixer.lua" group "PGTA" dofile "PGTALib.lua" group "BuildTools" dofile "SchemaCompiler.lua" group "Tests" assert(loadfile("Test.lua"))("AudioMixerTest") group "Tests" assert(loadfile("Test.lua"))("EngineTest") group "Tests" assert(loadfile("TestC.lua"))("CInterfaceTest") group ""
-- Procedurally Generated Transitional Audio Build -- include "compilationunit.lua" function run_include(script, rel_dir) local external_dir = path.getabsolute("../external") local repo_dir = path.join(external_dir, rel_dir) local script_full = external_dir.."/build-tools/premake_scripts/"..script local output_dir = path.getabsolute("../premake/".._ACTION) assert(loadfile(script_full))(repo_dir, output_dir) end solution "PGTA" location(_ACTION) targetdir(_ACTION) startproject "EngineTest" language "C++" platforms { "x64", "x32" } configurations { "Debug", "Release" } flags { "Symbols", "StaticRuntime", "NoMinimalRebuild", "NoEditAndContinue", "MultiProcessorCompile" } filter "action:vs*" defines { "_CRT_SECURE_NO_WARNINGS", "_SCL_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_DEPRECATE" } filter { "action:not vs*" } buildoptions "-fPIC" compilationunitdir(_ACTION.."/%{prj.name}Dir") filter { "action:not vs*", "language:C++" } buildoptions "-std=c++1y" filter { "action:not vs*", "language:C" } buildoptions "-std=c11" filter "Debug" defines { "DEBUG", "_DEBUG" } filter "Release" flags "LinkTimeOptimization" defines "NDEBUG" optimize "Full" filter {} group "Externals" run_include("flatbuffers.lua", "flatbuffers") group "Externals" run_include("flatc.lua", "flatbuffers") group "Externals" run_include("sdl2.lua", "SDL2") group "PGTA" dofile "AudioMixer.lua" group "PGTA" dofile "PGTALib.lua" group "BuildTools" dofile "SchemaCompiler.lua" group "Tests" assert(loadfile("Test.lua"))("AudioMixerTest") group "Tests" assert(loadfile("Test.lua"))("EngineTest") group "Tests" assert(loadfile("TestC.lua"))("CInterfaceTest") group ""
Fixed windows premake generation error
Fixed windows premake generation error
Lua
mit
PGTA/PGTA,PGTA/PGTA,PGTA/PGTA
4f19f3b5664c1bb9e12a21966459590b97488c28
build/premake4.lua
build/premake4.lua
-- This is the starting point of the build scripts for the project. -- It defines the common build settings that all the projects share -- and calls the build scripts of all the sub-projects. config = {} dofile "Helpers.lua" dofile "Tests.lua" -- Setup the LLVM dependency dofile "LLVM.lua" newoption { trigger = "parser", description = "Controls which version of the parser is enabled.", value = "version", allowed = { { "cpp", "Cross-platform C++ parser."}, { "cli", "VS-only C++/CLI parser."}, } } function SetupParser() local c = configuration "vs*" defines { "OLD_PARSER" } links { "CppSharp.Parser" } configuration(c) end solution "CppSharp" configurations { "Debug", "Release" } platforms { "x32", "x64" } flags { common_flags } location (builddir) objdir (builddir .. "/obj/") targetdir (libdir) libdirs { libdir } debugdir (bindir) -- startproject "Generator" configuration "vs2013" framework "4.0" configuration "vs2012" framework "4.0" configuration "windows" defines { "WINDOWS" } configuration {} group "Examples" IncludeExamples() group "Tests" IncludeTests() group "Libraries" include (srcdir .. "/Core") include (srcdir .. "/AST/AST.lua") include (srcdir .. "/Generator/Generator.lua") include (srcdir .. "/Generator.Tests/Generator.Tests.lua") include (srcdir .. "/Runtime/Runtime.lua") include (srcdir .. "/CppParser") if string.starts(action, "vs") then include (srcdir .. "/Parser/Parser.lua") end
-- This is the starting point of the build scripts for the project. -- It defines the common build settings that all the projects share -- and calls the build scripts of all the sub-projects. config = {} dofile "Helpers.lua" dofile "Tests.lua" -- Setup the LLVM dependency dofile "LLVM.lua" newoption { trigger = "parser", description = "Controls which version of the parser is enabled.", value = "version", allowed = { { "cpp", "Cross-platform C++ parser."}, { "cli", "VS-only C++/CLI parser."}, } } function SetupCLIParser() local parser = _OPTIONS["parser"] if not parser or parser == "cli" then defines { "OLD_PARSER" } links { "CppSharp.Parser" } else links { "CppSharp.Parser.CLI" } end end function SetupCSharpParser() links { "CppSharp.Parser.CSharp" } end function SetupParser() if string.match(action, "vs*") then SetupCLIParser() else SetupCSharpParser() end end solution "CppSharp" configurations { "Debug", "Release" } platforms { "x32", "x64" } flags { common_flags } location (builddir) objdir (builddir .. "/obj/") targetdir (libdir) libdirs { libdir } debugdir (bindir) -- startproject "Generator" configuration "vs2013" framework "4.0" configuration "vs2012" framework "4.0" configuration "windows" defines { "WINDOWS" } configuration {} group "Examples" IncludeExamples() group "Tests" IncludeTests() group "Libraries" include (srcdir .. "/Core") include (srcdir .. "/AST/AST.lua") include (srcdir .. "/Generator/Generator.lua") include (srcdir .. "/Generator.Tests/Generator.Tests.lua") include (srcdir .. "/Runtime/Runtime.lua") include (srcdir .. "/CppParser") if string.starts(action, "vs") then include (srcdir .. "/Parser/Parser.lua") end
Fixed the parser build setup code to work with the new options.
Fixed the parser build setup code to work with the new options.
Lua
mit
u255436/CppSharp,ktopouzi/CppSharp,zillemarco/CppSharp,txdv/CppSharp,KonajuGames/CppSharp,mohtamohit/CppSharp,mono/CppSharp,SonyaSa/CppSharp,mohtamohit/CppSharp,ddobrev/CppSharp,imazen/CppSharp,mohtamohit/CppSharp,KonajuGames/CppSharp,nalkaro/CppSharp,nalkaro/CppSharp,genuinelucifer/CppSharp,txdv/CppSharp,u255436/CppSharp,Samana/CppSharp,SonyaSa/CppSharp,KonajuGames/CppSharp,genuinelucifer/CppSharp,inordertotest/CppSharp,KonajuGames/CppSharp,nalkaro/CppSharp,zillemarco/CppSharp,mono/CppSharp,mohtamohit/CppSharp,inordertotest/CppSharp,u255436/CppSharp,nalkaro/CppSharp,Samana/CppSharp,mydogisbox/CppSharp,ktopouzi/CppSharp,u255436/CppSharp,xistoso/CppSharp,ddobrev/CppSharp,SonyaSa/CppSharp,mono/CppSharp,xistoso/CppSharp,ktopouzi/CppSharp,u255436/CppSharp,nalkaro/CppSharp,Samana/CppSharp,ddobrev/CppSharp,mydogisbox/CppSharp,zillemarco/CppSharp,mono/CppSharp,xistoso/CppSharp,Samana/CppSharp,genuinelucifer/CppSharp,mohtamohit/CppSharp,SonyaSa/CppSharp,inordertotest/CppSharp,txdv/CppSharp,ddobrev/CppSharp,mydogisbox/CppSharp,KonajuGames/CppSharp,imazen/CppSharp,zillemarco/CppSharp,ktopouzi/CppSharp,imazen/CppSharp,xistoso/CppSharp,ddobrev/CppSharp,ktopouzi/CppSharp,inordertotest/CppSharp,xistoso/CppSharp,mono/CppSharp,txdv/CppSharp,genuinelucifer/CppSharp,mono/CppSharp,imazen/CppSharp,txdv/CppSharp,imazen/CppSharp,mydogisbox/CppSharp,SonyaSa/CppSharp,inordertotest/CppSharp,zillemarco/CppSharp,Samana/CppSharp,genuinelucifer/CppSharp,mydogisbox/CppSharp
ec717c42631c3af49ba20116a53a1e460e4ef63c
xmake/rules/utils/inherit_links/inherit_links.lua
xmake/rules/utils/inherit_links/inherit_links.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 inherit_links.lua -- -- get values from target function _get_values_from_target(target, name) local values = table.wrap(target:get(name)) table.join2(values, target:get_from_opts(name)) table.join2(values, target:get_from_pkgs(name)) return values end -- main entry function main(target) -- disable inherit.links for `add_deps()`? if target:data("inherit.links") == false then return end -- export links and linkdirs local targetkind = target:targetkind() if targetkind == "shared" or targetkind == "static" then local targetfile = target:targetfile() target:add("links", target:basename(), {interface = true}) target:add("linkdirs", path.directory(targetfile), {interface = true}) for _, name in ipairs({"frameworkdirs", "frameworks", "linkdirs", "links", "syslinks"}) do local values = _get_values_from_target(target, name) if values and #values > 0 then target:add(name, values, {public = true}) end end end -- export rpathdirs for all shared library if targetkind == "binary" then local targetdir = target:targetdir() for _, dep in ipairs(target:orderdeps()) do if dep:targetkind() == "shared" then local rpathdir = "@loader_path" local subdir = path.relative(path.directory(dep:targetfile()), targetdir) if subdir and subdir ~= '.' then rpathdir = path.join(rpathdir, subdir) end target:add("rpathdirs", rpathdir) end end end 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 inherit_links.lua -- -- get values from target function _get_values_from_target(target, name) local values = table.wrap(target:get(name)) table.join2(values, target:get_from_opts(name)) table.join2(values, target:get_from_pkgs(name)) return values end -- main entry function main(target) -- disable inherit.links for `add_deps()`? if target:data("inherit.links") == false then return end -- export links and linkdirs local targetkind = target:targetkind() if targetkind == "shared" or targetkind == "static" then local targetfile = target:targetfile() target:add("links", target:basename(), {interface = true}) target:add("linkdirs", path.directory(targetfile), {interface = true}) for _, name in ipairs({"frameworkdirs", "frameworks", "linkdirs", "links", "syslinks"}) do local values = _get_values_from_target(target, name) if values and #values > 0 then target:add(name, values, {public = true}) end end end -- export rpathdirs for all shared library if targetkind == "binary" then local targetdir = target:targetdir() for _, dep in ipairs(target:orderdeps()) do local depinherit = target:extraconf("deps", dep:name(), "inherit") if dep:targetkind() == "shared" and depinherit == nil or depinherit then local rpathdir = "@loader_path" local subdir = path.relative(path.directory(dep:targetfile()), targetdir) if subdir and subdir ~= '.' then rpathdir = path.join(rpathdir, subdir) end target:add("rpathdirs", rpathdir) end end end end
fix inherit links
fix inherit links
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
0c7957113b53be2485cd0b8b3200f11cd371b7fd
core/init.lua
core/init.lua
-- Copyright 2007-2013 Mitchell mitchell.att.foicica.com. See LICENSE. _RELEASE = "Textadept 7.0 beta 3" package.path = _HOME..'/core/?.lua;'..package.path _SCINTILLA = require('iface') _L = require('locale') events = require('events') args = require('args') require('file_io') require('lfs_ext') require('ui') keys = require('keys') _M = {} -- language modules table -- LuaJIT compatibility. if jit then module, package.searchers, bit32 = nil, package.loaders, bit end --[[ This comment is for LuaDoc. --- -- Extends Lua's _G table to provide extra functions and fields for Textadept. -- @field _HOME (string) -- The path to the directory containing Textadept. -- @field _RELEASE (string) -- The Textadept release version string. -- @field _USERHOME (string) -- The path to the user's *~/.textadept/* directory, where all preferences and -- user-data is stored. -- On Windows machines *~/* is the value of the "USERHOME" environment -- variable, typically *C:\Users\username\\* or -- *C:\Documents and Settings\username\\*. On Linux, BSD, and Mac OSX -- machines *~/* is the value of "$HOME", typically */home/username/* and -- */Users/username/* respectively. -- @field _CHARSET (string) -- The character set encoding of the filesystem. -- This is used when [working with files](io.html). -- @field WIN32 (bool) -- If Textadept is running on Windows, this flag is `true`. -- @field OSX (bool) -- If Textadept is running on Mac OSX, this flag is `true`. -- @field CURSES (bool) -- If Textadept is running in the terminal, this flag is `true`. -- Curses feature incompatibilities are listed in the [Appendix][]. -- -- [Appendix]: ../14_Appendix.html#Curses.Compatibility module('_G')]] --[[ The tables below were defined in C. --- -- Table of command line parameters passed to Textadept. -- @class table -- @see _G.args -- @name arg local arg --- -- Table of all open buffers in Textadept. -- Numeric keys have buffer values and buffer keys have their associated numeric -- keys. -- @class table -- @usage _BUFFERS[n] --> buffer at index n -- @usage _BUFFERS[buffer] --> index of buffer in _BUFFERS -- @see _G.buffer -- @name _BUFFERS local _BUFFERS --- -- Table of all views in Textadept. -- Numeric keys have view values and view keys have their associated numeric -- keys. -- @class table -- @usage _VIEWS[n] --> view at index n -- @usage _VIEWS[view] --> index of view in _VIEWS -- @see _G.view -- @name _VIEWS local _VIEWS --- -- The current [buffer](buffer.html) in the current [view](#view). -- @class table -- @name buffer local buffer --- -- The currently focused [view](view.html). -- @class table -- @name view local view -- The functions below are Lua C functions. --- -- Emits a `QUIT` event, and unless any handler returns `false`, quits -- Textadept. -- @see events.QUIT -- @class function -- @name quit local quit --- -- Resets the Lua state by reloading all initialization scripts. -- Language modules for opened files are NOT reloaded. Re-opening the files that -- use them will reload those modules instead. -- This function is useful for modifying user scripts (such as -- *~/.textadept/init.lua* and *~/.textadept/modules/textadept/keys.lua*) on -- the fly without having to restart Textadept. `arg` is set to `nil` when -- reinitializing the Lua State. Any scripts that need to differentiate between -- startup and reset can test `arg`. -- @class function -- @name reset local reset --- -- Calls function *f* with the given arguments after *interval* seconds and then -- repeatedly while *f* returns `true`. A `nil` or `false` return value stops -- repetition. -- @param interval The interval in seconds to call *f* after. -- @param f The function to call. -- @param ... Additional arguments to pass to *f*. -- @class function -- @name timeout local timeout ]]
-- Copyright 2007-2013 Mitchell mitchell.att.foicica.com. See LICENSE. _RELEASE = "Textadept 7.0 beta 3" package.path = _HOME..'/core/?.lua;'..package.path _SCINTILLA = require('iface') events = require('events') args = require('args') _L = require('locale') require('file_io') require('lfs_ext') require('ui') keys = require('keys') _M = {} -- language modules table -- LuaJIT compatibility. if jit then module, package.searchers, bit32 = nil, package.loaders, bit end --[[ This comment is for LuaDoc. --- -- Extends Lua's _G table to provide extra functions and fields for Textadept. -- @field _HOME (string) -- The path to the directory containing Textadept. -- @field _RELEASE (string) -- The Textadept release version string. -- @field _USERHOME (string) -- The path to the user's *~/.textadept/* directory, where all preferences and -- user-data is stored. -- On Windows machines *~/* is the value of the "USERHOME" environment -- variable, typically *C:\Users\username\\* or -- *C:\Documents and Settings\username\\*. On Linux, BSD, and Mac OSX -- machines *~/* is the value of "$HOME", typically */home/username/* and -- */Users/username/* respectively. -- @field _CHARSET (string) -- The character set encoding of the filesystem. -- This is used when [working with files](io.html). -- @field WIN32 (bool) -- If Textadept is running on Windows, this flag is `true`. -- @field OSX (bool) -- If Textadept is running on Mac OSX, this flag is `true`. -- @field CURSES (bool) -- If Textadept is running in the terminal, this flag is `true`. -- Curses feature incompatibilities are listed in the [Appendix][]. -- -- [Appendix]: ../14_Appendix.html#Curses.Compatibility module('_G')]] --[[ The tables below were defined in C. --- -- Table of command line parameters passed to Textadept. -- @class table -- @see _G.args -- @name arg local arg --- -- Table of all open buffers in Textadept. -- Numeric keys have buffer values and buffer keys have their associated numeric -- keys. -- @class table -- @usage _BUFFERS[n] --> buffer at index n -- @usage _BUFFERS[buffer] --> index of buffer in _BUFFERS -- @see _G.buffer -- @name _BUFFERS local _BUFFERS --- -- Table of all views in Textadept. -- Numeric keys have view values and view keys have their associated numeric -- keys. -- @class table -- @usage _VIEWS[n] --> view at index n -- @usage _VIEWS[view] --> index of view in _VIEWS -- @see _G.view -- @name _VIEWS local _VIEWS --- -- The current [buffer](buffer.html) in the current [view](#view). -- @class table -- @name buffer local buffer --- -- The currently focused [view](view.html). -- @class table -- @name view local view -- The functions below are Lua C functions. --- -- Emits a `QUIT` event, and unless any handler returns `false`, quits -- Textadept. -- @see events.QUIT -- @class function -- @name quit local quit --- -- Resets the Lua state by reloading all initialization scripts. -- Language modules for opened files are NOT reloaded. Re-opening the files that -- use them will reload those modules instead. -- This function is useful for modifying user scripts (such as -- *~/.textadept/init.lua* and *~/.textadept/modules/textadept/keys.lua*) on -- the fly without having to restart Textadept. `arg` is set to `nil` when -- reinitializing the Lua State. Any scripts that need to differentiate between -- startup and reset can test `arg`. -- @class function -- @name reset local reset --- -- Calls function *f* with the given arguments after *interval* seconds and then -- repeatedly while *f* returns `true`. A `nil` or `false` return value stops -- repetition. -- @param interval The interval in seconds to call *f* after. -- @param f The function to call. -- @param ... Additional arguments to pass to *f*. -- @class function -- @name timeout local timeout ]]
Fixed bug with previous commit.
Fixed bug with previous commit.
Lua
mit
rgieseke/textadept,rgieseke/textadept
0e43a7f6721d9e0c9c66d08f0b041791daded9e0
game/main.lua
game/main.lua
-- The screen size isn't communicated between Lua and C yet SCREEN_WIDTH = 640 SCREEN_HEIGHT = 480 NUM_ENTITIES = 2048 function rect_t(x, y, w, h) local temp = {x=x, y=y, w=w, h=h,__type="__RECT__"} return temp end function animation_t() local temp = {delays={}, rects={}, cur_frame=1,cur_delay=0,cur_rect=nil, __type="__ANIMATION__"} function temp:add_frame(rect, delay) table.insert(self.rects, rect) table.insert(self.delays, delay) if self.cur_rect == nil then self.cur_rect = self.rects[1] end end function temp:remove_frame(i) table.remove(self.rects, i) table.remove(self.delays, i) end function temp:update(delta) self.cur_delay = self.cur_delay + delta if self.cur_delay >= self.delays[self.cur_frame] then self.cur_delay = 0 self.cur_frame = self.cur_frame + 1 -- TODO: Add support for animation play types if self.cur_frame > #self.rects then self.cur_frame = 1 end self.cur_rect = self.rects[self.cur_frame] end end return temp end function sprite_t(img) if type(img) == "string" then img = zull.graphics.load_texture(img) end local temp = {img=img, animations={}, x=0, y=0, cur_anim=""} function temp:add_anim(name, anim) self.animations[name] = anim end function temp:play_anim(name) self.cur_anim = name end function temp:stop_anim() self.cur_anim = "" end function temp:get_anim() if self.cur_anim == "" then return nil end return self.animations[self.cur_anim] end function temp:update(delta, fn) if cur_anim ~= "" then self.animations[self.cur_anim]:update(delta) end if fn ~= nil then fn(delta) end end function temp:draw() zull.graphics.draw_sprite_ex(self.img, self.x, self.y, self.img.width, self.img.height, self:get_anim().cur_rect.x, self:get_anim().cur_rect.y, self:get_anim().cur_rect.w, self:get_anim().cur_rect.h) end return temp end test_image = zull.graphics.load_texture("game/test.png") test_animation = animation_t() test_animation:add_frame(rect_t(0, 0, 16, 16), 1) test_animation:add_frame(rect_t(16, 16, 16, 16), 1) test_animation:add_frame(rect_t(0, 0, 32, 32), 1) test_sprite = sprite_t(test_image) test_sprite:add_anim("test", test_animation) test_sprite:play_anim("test") entities = {} function create_entity() local entity = {} entity.x = math.random(0, SCREEN_WIDTH - 32) entity.y = math.random(0, SCREEN_HEIGHT - 32) if math.random(100) <= 50 then entity.vel_x = 50.0 else entity.vel_x = -50.0 end if math.random(100) <= 50 then entity.vel_y = 50.0 else entity.vel_y = -50.0 end return entity end function zull.init() math.randomseed(os.time()) for i = 1, NUM_ENTITIES do entities[i] = create_entity() end end function zull.shutdown() end function zull.update(delta_time) test_sprite:update(delta_time) for i = 1, NUM_ENTITIES do entities[i].x = entities[i].x + entities[i].vel_x * delta_time entities[i].y = entities[i].y + entities[i].vel_y * delta_time if entities[i].x <= 0.0 or entities[i].x + 32.0 >= SCREEN_WIDTH then entities[i].vel_x = -entities[i].vel_x end if entities[i].y <= 0.0 or entities[i].y + 32.0 >= SCREEN_HEIGHT then entities[i].vel_y = -entities[i].vel_y end end end function zull.draw() test_sprite:draw() for i = 1, NUM_ENTITIES do --zull.graphics.draw_sprite_ex(test_image, entities[i].x, entities[i].y, 32, 32, -- test_animation.cur_rect.x, test_animation.cur_rect.y, test_animation.cur_rect.w, test_animation.cur_rect.h) end end
-- The screen size isn't communicated between Lua and C yet SCREEN_WIDTH = 640 SCREEN_HEIGHT = 480 NUM_ENTITIES = 2048 function rect_t(x, y, w, h) local temp = {x=x, y=y, w=w, h=h,__type="__RECT__"} return temp end function animation_t() local temp = {delays={}, rects={}, cur_frame=1,cur_delay=0,cur_rect=nil, __type="__ANIMATION__"} function temp:add_frame(rect, delay) table.insert(self.rects, rect) table.insert(self.delays, delay) if self.cur_rect == nil then self.cur_rect = self.rects[1] end end function temp:remove_frame(i) table.remove(self.rects, i) table.remove(self.delays, i) end function temp:update(delta) self.cur_delay = self.cur_delay + delta if self.cur_delay >= self.delays[self.cur_frame] then self.cur_delay = 0 self.cur_frame = self.cur_frame + 1 -- TODO: Add support for animation play types if self.cur_frame > #self.rects then self.cur_frame = 1 end self.cur_rect = self.rects[self.cur_frame] end end return temp end function sprite_t(img) if type(img) == "string" then img = zull.graphics.load_texture(img) end local temp = {img=img, animations={}, x=0, y=0, cur_anim=""} function temp:add_anim(name, anim) self.animations[name] = anim end function temp:play_anim(name) self.cur_anim = name end function temp:stop_anim() self.cur_anim = "" end function temp:get_anim() if self.cur_anim == "" then return nil end return self.animations[self.cur_anim] end function temp:update(delta, fn) if self.cur_anim ~= "" then self.animations[self.cur_anim]:update(delta) end if fn ~= nil then fn(delta) end end function temp:draw() if self.cur_anim == "" then zull.graphics.draw_sprite(self.img, self.x, self.y) else zull.graphics.draw_sprite_ex(self.img, self.x, self.y, self.img.width, self.img.height, self:get_anim().cur_rect.x, self:get_anim().cur_rect.y, self:get_anim().cur_rect.w, self:get_anim().cur_rect.h) end end return temp end test_image = zull.graphics.load_texture("game/test.png") test_animation = animation_t() test_animation:add_frame(rect_t(0, 0, 16, 16), 1) test_animation:add_frame(rect_t(16, 16, 16, 16), 1) test_animation:add_frame(rect_t(0, 0, 32, 32), 1) test_sprite = sprite_t(test_image) test_sprite:add_anim("test", test_animation) test_sprite:play_anim("test") entities = {} function create_entity() local entity = {} entity.x = math.random(0, SCREEN_WIDTH - 32) entity.y = math.random(0, SCREEN_HEIGHT - 32) if math.random(100) <= 50 then entity.vel_x = 50.0 else entity.vel_x = -50.0 end if math.random(100) <= 50 then entity.vel_y = 50.0 else entity.vel_y = -50.0 end return entity end function zull.init() math.randomseed(os.time()) for i = 1, NUM_ENTITIES do entities[i] = create_entity() end end function zull.shutdown() end function zull.update(delta_time) test_sprite:update(delta_time) for i = 1, NUM_ENTITIES do entities[i].x = entities[i].x + entities[i].vel_x * delta_time entities[i].y = entities[i].y + entities[i].vel_y * delta_time if entities[i].x <= 0.0 or entities[i].x + 32.0 >= SCREEN_WIDTH then entities[i].vel_x = -entities[i].vel_x end if entities[i].y <= 0.0 or entities[i].y + 32.0 >= SCREEN_HEIGHT then entities[i].vel_y = -entities[i].vel_y end end end function zull.draw() test_sprite:draw() for i = 1, NUM_ENTITIES do --zull.graphics.draw_sprite_ex(test_image, entities[i].x, entities[i].y, 32, 32, -- test_animation.cur_rect.x, test_animation.cur_rect.y, test_animation.cur_rect.w, test_animation.cur_rect.h) end end
Added support for non-animated sprites Fixed problem in sprite_t:update
Added support for non-animated sprites Fixed problem in sprite_t:update
Lua
mit
ZedZull/zull_engine
318017e4c676dc2586af50a403a6b9cb9d84db31
modules/urbandict.lua
modules/urbandict.lua
local simplehttp = require'simplehttp' local json = require'json' local trim = function(s) return (string.gsub(s, "^%s*(.-)%s*$", "%1")) end local urlEncode = function(str) return str:gsub( '([^%w ])', function (c) return string.format ("%%%02X", string.byte(c)) end ):gsub(' ', '+') end local parseJSON = function(data) data = json.decode(data) if(#data.list > 0) then return data.list[1].definition:gsub('\r\n', ' ') end end local handler = function(self, source, destination, input) input = trim(input) simplehttp( APIBase:format(urlEncode(input)), function(data) local result = parseJSON(data) if(result) then local msgLimit = (512 - 16 - 65 - 10) - #self.config.nick - #destination if(#result > msgLimit) then result = result:sub(1, msgLimit - 3) .. '...' end self:Msg('privmsg', destination, source, string.format('%s: %s', source.nick, result)) else self:Msg('privmsg', destination, source, string.format("%s: %s is bad and you should feel bad.", source.nick, input)) end end ) end local APIBase = 'http://api.urbandictionary.com/v0/define?term=%s' return { PRIVMSG = { ['^!ud (.+)$'] = handler, ['^!urb (.+)$'] = handler, }, }
local simplehttp = require'simplehttp' local json = require'json' local trim = function(s) return (string.gsub(s, "^%s*(.-)%s*$", "%1")) end local urlEncode = function(str) return str:gsub( '([^%w ])', function (c) return string.format ("%%%02X", string.byte(c)) end ):gsub(' ', '+') end local parseJSON = function(data) data = json.decode(data) if(#data.list > 0) then return data.list[1].definition:gsub('\r\n', ' ') end end local APIBase = 'http://api.urbandictionary.com/v0/define?term=%s' local handler = function(self, source, destination, input) input = trim(input) simplehttp( APIBase:format(urlEncode(input)), function(data) local result = parseJSON(data) if(result) then local msgLimit = (512 - 16 - 65 - 10) - #self.config.nick - #destination if(#result > msgLimit) then result = result:sub(1, msgLimit - 3) .. '...' end self:Msg('privmsg', destination, source, string.format('%s: %s', source.nick, result)) else self:Msg('privmsg', destination, source, string.format("%s: %s is bad and you should feel bad.", source.nick, input)) end end ) end return { PRIVMSG = { ['^!ud (.+)$'] = handler, ['^!urb (.+)$'] = handler, }, }
urbandict: Fix fail. :-(
urbandict: Fix fail. :-(
Lua
mit
haste/ivar2,torhve/ivar2,torhve/ivar2,torhve/ivar2
67b7ccc94639adb9216aa2053c4fa450ebefc066
SVUI_!Core/system/_reports/reputation_new.lua
SVUI_!Core/system/_reports/reputation_new.lua
--[[ ############################################################################## S V U I By: Munglunch ############################################################################## ########################################################## LOCALIZED LUA FUNCTIONS ########################################################## ]]-- --[[ GLOBALS ]]-- local _G = _G; local select = _G.select; local table = _G.table; local twipe = table.wipe; local tsort = table.sort; --[[ STRING METHODS ]]-- local format, gsub = string.format, string.gsub; --[[ ########################################################## GET ADDON DATA ########################################################## ]]-- local SV = select(2, ...) local L = SV.L; local Reports = SV.Reports; local LRD = LibStub("LibReputationData-1.0"); --[[ ########################################################## REPUTATION STATS ########################################################## ]]-- local HEX_COLOR = "22FFFF"; local TEXT_PATTERN = "|cff22EF5F%s|r|cff888888 - [|r%d%%|cff888888]|r"; local FACTION_BAR_COLORS = _G.FACTION_BAR_COLORS; local sort_menu_fn = function(a,b) if (a ~= nil and b ~= nil) then if (a.text ~= nil and b.text ~= nil) then return a.text < b.text end end return false end; local function CacheRepData(data) local count = 1 local factions = LRD:GetAllActiveFactionsInfo(); if not factions then return end twipe(data) for i=1, #factions do if(factions[i].isActive and (not factions[i].isHeader)) then local factionIndex = tonumber(factions[i].factionIndex) local fn = function() local active = LRD:GetWatchedFactionIndex() if factionIndex ~= active then LRD:SetWatchedFaction(factionIndex) end end tinsert(data,{text = factions[i].name, func = fn}); count=count+1; end end if #data > 0 then tsort(data, sort_menu_fn); end end local function DoTooltip(self) Reports:SetDataTip(self) local factionIndex, faction = LRD:GetReputationInfo() if not factionIndex then Reports.ToolTip:AddLine("No Watched Factions") else Reports.ToolTip:AddLine(faction.name) Reports.ToolTip:AddLine(' ') Reports.ToolTip:AddDoubleLine(STANDING..':', faction.standing, 1, 1, 1) Reports.ToolTip:AddDoubleLine(REPUTATION..':', format('%d / %d (%d%%)', faction.value - faction.min, faction.max - faction.min, (faction.value - faction.min) / (faction.max - faction.min) * 100), 1, 1, 1) end Reports.ToolTip:AddLine(" ", 1, 1, 1) Reports.ToolTip:AddDoubleLine("[Click]", "Change Watched Faction", 0,1,0, 0.5,1,0.5) Reports:ShowDataTip(true) end --[[ ########################################################## STANDARD TYPE ########################################################## ]]-- local REPORT_NAME = "Reputation"; local Report = Reports:NewReport(REPORT_NAME, { type = "data source", text = REPORT_NAME .. " Info", icon = [[Interface\Addons\SVUI_!Core\assets\icons\SVUI]] }); Report.Populate = function(self) if self.barframe:IsShown()then self.text:SetAllPoints(self) self.text:SetJustifyH("CENTER") self.barframe:Hide() self.text:SetAlpha(1) self.text:SetShadowOffset(2, -4) end local factionIndex, faction = LRD:GetReputationInfo() if not factionIndex then self.text:SetText("No watched factions") else self.text:SetFormattedText(TEXT_PATTERN , faction.standing, ((faction.value - faction.min) / (faction.max - faction.min) * 100)) end end Report.OnClick = function(self, button) SV.Dropdown:Open(self, self.InnerData, "Select Faction") end Report.OnEnter = function(self) DoTooltip(self) end Report.OnInit = function(self) LRD.RegisterCallback(self,"FACTIONS_LOADED", function () if(not self.InnerData) then self.InnerData = {} end CacheRepData(self.InnerData) Report.Populate(self) if Reports.Tooltip.IsShown() then DoTooltip(self) end end) LRD.RegisterCallback(self, "REPUTATION_CHANGED", function() Report.Populate(self) end) end --[[ ########################################################## BAR TYPE ########################################################## ]]-- local BAR_NAME = "Reputation Bar"; local ReportBar = Reports:NewReport(BAR_NAME, { type = "data source", text = BAR_NAME, icon = [[Interface\Addons\SVUI_!Core\assets\icons\SVUI]] }); ReportBar.Populate = function(self) if not self.barframe:IsShown()then self.barframe:Show() self.barframe.icon.texture:SetTexture(SV.media.dock.reputationLabel) self.text:SetAlpha(1) self.text:SetShadowOffset(1, -2) end local bar = self.barframe.bar; local factionIndex, faction = LRD:GetReputationInfo() if not factionIndex then bar:SetStatusBarColor(0,0,0) bar:SetMinMaxValues(0,1) bar:SetValue(0) self.text:SetText("No Faction") else local color = FACTION_BAR_COLORS[faction.standingID] bar:SetStatusBarColor(color.r, color.g, color.b) bar:SetMinMaxValues(faction.min, faction.max) bar:SetValue(faction.value) self.text:SetText(faction.standing) end end ReportBar.OnClick = function(self, button) SV.Dropdown:Open(self, self.InnerData, "Select Faction") end ReportBar.OnEnter = function(self) DoTooltip(self) end ReportBar.OnInit = function(self) LRD.RegisterCallback(self,"FACTIONS_LOADED", function () if(not self.InnerData) then self.InnerData = {} end CacheRepData(self.InnerData) ReportBar.Populate(self) end) LRD.RegisterCallback(self, "REPUTATION_CHANGED", function() ReportBar.Populate(self) end) end
--[[ ############################################################################## S V U I By: Munglunch ############################################################################## ########################################################## LOCALIZED LUA FUNCTIONS ########################################################## ]]-- --[[ GLOBALS ]]-- local _G = _G; local select = _G.select; local table = _G.table; local twipe = table.wipe; local tsort = table.sort; --[[ STRING METHODS ]]-- local format, gsub = string.format, string.gsub; --[[ ########################################################## GET ADDON DATA ########################################################## ]]-- local SV = select(2, ...) local L = SV.L; local Reports = SV.Reports; local LRD = LibStub("LibReputationData-1.0"); --[[ ########################################################## REPUTATION STATS ########################################################## ]]-- local HEX_COLOR = "22FFFF"; local TEXT_PATTERN = "|cff22EF5F%s|r|cff888888 - [|r%d%%|cff888888]|r"; local FACTION_BAR_COLORS = _G.FACTION_BAR_COLORS; local sort_menu_fn = function(a,b) if (a ~= nil and b ~= nil) then if (a.text ~= nil and b.text ~= nil) then return a.text < b.text end end return false end; local function CacheRepData(data) local count = 1 local factions = LRD:GetAllActiveFactionsInfo(); if not factions then return end twipe(data) for i=1, #factions do if(factions[i].isActive and (not factions[i].isHeader)) then local factionIndex = tonumber(factions[i].factionIndex) local fn = function() local active = LRD:GetWatchedFactionIndex() if factionIndex ~= active then LRD:SetWatchedFaction(factionIndex) end end tinsert(data,{text = factions[i].name, func = fn}); count=count+1; end end if #data > 0 then tsort(data, sort_menu_fn); end end local function DoTooltip(self) Reports:SetDataTip(self) local factionIndex, faction = LRD:GetReputationInfo() if not factionIndex then Reports.ToolTip:AddLine("No Watched Factions") else Reports.ToolTip:AddLine(faction.name) Reports.ToolTip:AddLine(' ') Reports.ToolTip:AddDoubleLine(STANDING..':', faction.standing, 1, 1, 1) Reports.ToolTip:AddDoubleLine(REPUTATION..':', format('%d / %d (%d%%)', faction.value - faction.min, faction.max - faction.min, (faction.value - faction.min) / (faction.max - faction.min) * 100), 1, 1, 1) end Reports.ToolTip:AddLine(" ", 1, 1, 1) Reports.ToolTip:AddDoubleLine("[Click]", "Change Watched Faction", 0,1,0, 0.5,1,0.5) Reports:ShowDataTip(true) end --[[ ########################################################## STANDARD TYPE ########################################################## ]]-- local REPORT_NAME = "Reputation"; local Report = Reports:NewReport(REPORT_NAME, { type = "data source", text = REPORT_NAME .. " Info", icon = [[Interface\Addons\SVUI_!Core\assets\icons\SVUI]] }); Report.Populate = function(self) if self.barframe:IsShown()then self.text:SetAllPoints(self) self.text:SetJustifyH("CENTER") self.barframe:Hide() self.text:SetAlpha(1) self.text:SetShadowOffset(2, -4) end local factionIndex, faction = LRD:GetReputationInfo() if not factionIndex then self.text:SetText("No watched factions") else self.text:SetFormattedText(TEXT_PATTERN , faction.standing, ((faction.value - faction.min) / (faction.max - faction.min) * 100)) end end Report.OnClick = function(self, button) SV.Dropdown:Open(self, self.InnerData, "Select Faction") end Report.OnEnter = function(self) DoTooltip(self) end Report.OnInit = function(self) LRD.RegisterCallback(self,"FACTIONS_LOADED", function () if(not self.InnerData) then self.InnerData = {} end CacheRepData(self.InnerData) Report.Populate(self) end) LRD.RegisterCallback(self, "REPUTATION_CHANGED", function() Report.Populate(self) end) LRD:ForceUpdate() end --[[ ########################################################## BAR TYPE ########################################################## ]]-- local BAR_NAME = "Reputation Bar"; local ReportBar = Reports:NewReport(BAR_NAME, { type = "data source", text = BAR_NAME, icon = [[Interface\Addons\SVUI_!Core\assets\icons\SVUI]] }); ReportBar.Populate = function(self) if not self.barframe:IsShown()then self.barframe:Show() self.barframe.icon.texture:SetTexture(SV.media.dock.reputationLabel) self.text:SetAlpha(1) self.text:SetShadowOffset(1, -2) end local bar = self.barframe.bar; local factionIndex, faction = LRD:GetReputationInfo() if not factionIndex then bar:SetStatusBarColor(0,0,0) bar:SetMinMaxValues(0,1) bar:SetValue(0) self.text:SetText("No Faction") else local color = FACTION_BAR_COLORS[faction.standingID] bar:SetStatusBarColor(color.r, color.g, color.b) bar:SetMinMaxValues(faction.min, faction.max) bar:SetValue(faction.value) self.text:SetText(faction.standing) end end ReportBar.OnClick = function(self, button) SV.Dropdown:Open(self, self.InnerData, "Select Faction") end ReportBar.OnEnter = function(self) DoTooltip(self) end ReportBar.OnInit = function(self) LRD.RegisterCallback(self,"FACTIONS_LOADED", function () if(not self.InnerData) then self.InnerData = {} end CacheRepData(self.InnerData) ReportBar.Populate(self) end) LRD.RegisterCallback(self, "REPUTATION_CHANGED", function() ReportBar.Populate(self) end) LRD:ForceUpdate() end
Fix #45 and re-initialisation post SVUI_Config changes
Fix #45 and re-initialisation post SVUI_Config changes Needed to call a LibReputationData:ForceUpdate() as the old bar/panel essentially went away but new one couldn't get a cache of the factions as the FACTIONS_LOADED had already fired in the session and wouldn't again unless there was a faction update.
Lua
mit
joev/SVUI-Temp
f4dd177e5e70d16d2ab7687e6fb39f980d299119
UCDchat/instantMessaging_c.lua
UCDchat/instantMessaging_c.lua
-- People will use /sms addCommandHandler("sms", function (plr) exports.UCDdx:new(plr, "This function is depracated. Use /im <player> <message> instead.", 255, 174, 0) end ) local antiSpam = {} local antiSpamTimer = 1000 -- This is the function we use to send the IM function instantMessage(_, target, ...) -- Actual messaging function if (not target) then exports.UCDdx:new("You must specify a player", 255, 0, 0) return end local recipient = exports.UCDutil:getPlayerFromPartialName(target) -- If we found a recipient if recipient then local msg = table.concat({...}, " ") if (msg == "" or msg == " " or msg:gsub(" ", "") == "") then return end if (msg:find("ucd")) then msg = msg:gsub("ucd", "UCD") end if (recipient.name == localPlayer.name) then exports.UCDdx:new(localPlayer, "You cannot send an IM to yourself", 255, 0, 0) return end outputChatBox("[IM to "..recipient.name.."] "..msg, 255, 174, 0, true) -- source = player who got the msg, plr = player who sent it, msg = the message sent triggerEvent("onPlayerReceiveIM", recipient, localPlayer, msg) triggerEvent("UCDphone.appendMessage", localPlayer, false, recipient.name, msg) triggerServerEvent("UCDchat.instantMessage", localPlayer, recipient, msg) --exports.UCDlogging:new(plr, "IM", msg, ) else exports.UCDdx:new(plr, "There is no player named "..target.." online", 255, 0, 0) end end addCommandHandler("im", instantMessage, false, false) addCommandHandler("instantmessage", instantMessage, false, false) addCommandHandler("imsg", instantMessage, false, false) addCommandHandler("imessage", instantMessage, false, false) addCommandHandler("instantmsg", instantMessage, false, false) addEvent("UCDchat.onSendIMFromPhone", true) addEventHandler("UCDchat.onSendIMFromPhone", root, function (plrName, message) instantMessage(nil, plrName, message) end ) function cacheLastSender(name) lastMsg = name end addEvent("UCDchat.cacheLastSender", true) addEventHandler("UCDchat.cacheLastSender", root, cacheLastSender) function quickReply(_, ...) if (lastMsg) then local recipient = Player(lastMsg) if (not recipient) then exports.UCDdx:new("The last person to IM you is offline", 255, 0, 0) return end local msg = table.concat({...}, " ") if (msg == "" or msg == " " or msg:gsub(" ", "") == "") then return end if (msg:find("UCD")) then msg = msg:gsub("ucd", "UCD") end instantMessage(nil, lastMsg, msg) else exports.UCDdx:new("The last person to IM you is offline", 255, 0, 0) end end addCommandHandler("re", quickReply, false, false) addCommandHandler("r", quickReply, false, false)
-- People will use /sms addCommandHandler("sms", function () exports.UCDdx:new("Syntax is: /im <player> <message>", 255, 174, 0) end ) local antiSpam = {} local antiSpamTimer = 1000 -- This is the function we use to send the IM function instantMessage(_, target, ...) -- Actual messaging function if (not target) then exports.UCDdx:new("You must specify a player", 255, 0, 0) return end local recipient = exports.UCDutil:getPlayerFromPartialName(target) -- If we found a recipient if recipient then local msg = table.concat({...}, " ") if (msg == "" or msg == " " or msg:gsub(" ", "") == "") then return end if (msg:find("ucd")) then msg = msg:gsub("ucd", "UCD") end if (recipient.name == localPlayer.name) then exports.UCDdx:new("You cannot send an IM to yourself", 255, 0, 0) return end outputChatBox("[IM to "..recipient.name.."] "..msg, 255, 174, 0, true) -- source = player who got the msg, plr = player who sent it, msg = the message sent triggerEvent("onPlayerReceiveIM", recipient, localPlayer, msg) triggerEvent("UCDphone.appendMessage", localPlayer, false, recipient.name, msg) triggerServerEvent("UCDchat.instantMessage", localPlayer, recipient, msg) --exports.UCDlogging:new(plr, "IM", msg, ) else exports.UCDdx:new(plr, "There is no player named "..target.." online", 255, 0, 0) end end addCommandHandler("im", instantMessage, false, false) addCommandHandler("instantmessage", instantMessage, false, false) addCommandHandler("imsg", instantMessage, false, false) addCommandHandler("imessage", instantMessage, false, false) addCommandHandler("instantmsg", instantMessage, false, false) addEvent("UCDchat.onSendIMFromPhone", true) addEventHandler("UCDchat.onSendIMFromPhone", root, function (plrName, message) instantMessage(nil, plrName, message) end ) function cacheLastSender(name) lastMsg = name end addEvent("UCDchat.cacheLastSender", true) addEventHandler("UCDchat.cacheLastSender", root, cacheLastSender) function quickReply(_, ...) if (lastMsg) then local recipient = Player(lastMsg) if (not recipient) then exports.UCDdx:new("The last person to IM you is offline", 255, 0, 0) return end local msg = table.concat({...}, " ") if (msg == "" or msg == " " or msg:gsub(" ", "") == "") then return end if (msg:find("UCD")) then msg = msg:gsub("ucd", "UCD") end instantMessage(nil, lastMsg, msg) else exports.UCDdx:new("The last person to IM you is offline", 255, 0, 0) end end addCommandHandler("re", quickReply, false, false) addCommandHandler("r", quickReply, false, false)
UCDchat
UCDchat - Fixed some misc bugs.
Lua
mit
nokizorque/ucd,nokizorque/ucd
eac0c654f84fecbf32d6797d85e75588c9ea7853
tests/test_gmake_cpp.lua
tests/test_gmake_cpp.lua
-- -- tests/test_gmake_cpp.lua -- Automated test suite for GNU Make C/C++ project generation. -- Copyright (c) 2009 Jason Perkins and the Premake project -- T.gmake_cpp = { } -- -- Configure a solution for testing -- local sln, prj function T.gmake_cpp.setup() _ACTION = "gmake" _OPTIONS.os = "linux" sln = solution "MySolution" configurations { "Debug", "Release" } platforms { "native" } prj = project "MyProject" language "C++" kind "ConsoleApp" end local function prepare() io.capture() premake.buildconfigs() end -- -- Test the header -- function T.gmake_cpp.BasicHeader() prepare() premake.gmake_cpp_header(prj, premake.gcc, sln.platforms) test.capture [[ # GNU Make project makefile autogenerated by Premake ifndef config config=debug endif ifndef verbose SILENT = @ endif ifndef CC CC = gcc endif ifndef CXX CXX = g++ endif ifndef AR AR = ar endif ]] end -- -- Test configuration blocks -- function T.gmake_cpp.BasicCfgBlock() prepare() local cfg = premake.getconfig(prj, "Debug") premake.gmake_cpp_config(cfg, premake.gcc) test.capture [[ ifeq ($(config),debug) OBJDIR = obj/Debug TARGETDIR = . TARGET = $(TARGETDIR)/MyProject DEFINES += INCLUDES += CPPFLAGS += -MMD $(DEFINES) $(INCLUDES) CFLAGS += $(CPPFLAGS) $(ARCH) CXXFLAGS += $(CFLAGS) LDFLAGS += -s LIBS += RESFLAGS += $(DEFINES) $(INCLUDES) LDDEPS += LINKCMD = $(CXX) -o $(TARGET) $(LDFLAGS) $(OBJECTS) $(RESOURCES) $(ARCH) $(LIBS) define PREBUILDCMDS endef define PRELINKCMDS endef define POSTBUILDCMDS endef endif ]] end function T.gmake_cpp.BasicCfgBlockWithPlatformCc() platforms { "ps3" } prepare() local cfg = premake.getconfig(prj, "Debug", "PS3") premake.gmake_cpp_config(cfg, premake.gcc) test.capture [[ ifeq ($(config),debugps3) CC = ppu-lv2-g++ CXX = ppu-lv2-g++ AR = ppu-lv2-ar OBJDIR = obj/PS3/Debug TARGETDIR = . TARGET = $(TARGETDIR)/MyProject.elf DEFINES += INCLUDES += CPPFLAGS += -MMD $(DEFINES) $(INCLUDES) CFLAGS += $(CPPFLAGS) $(ARCH) CXXFLAGS += $(CFLAGS) LDFLAGS += -s LIBS += RESFLAGS += $(DEFINES) $(INCLUDES) LDDEPS += LINKCMD = $(CXX) -o $(TARGET) $(LDFLAGS) $(OBJECTS) $(RESOURCES) $(ARCH) $(LIBS) define PREBUILDCMDS endef define PRELINKCMDS endef define POSTBUILDCMDS endef endif ]] end function T.gmake_cpp.PlatformSpecificBlock() platforms { "x64" } prepare() local cfg = premake.getconfig(prj, "Debug", "x64") premake.gmake_cpp_config(cfg, premake.gcc) test.capture [[ ifeq ($(config),debug64) OBJDIR = obj/x64/Debug TARGETDIR = . TARGET = $(TARGETDIR)/MyProject DEFINES += INCLUDES += CPPFLAGS += -MMD $(DEFINES) $(INCLUDES) CFLAGS += $(CPPFLAGS) $(ARCH) -m64 CXXFLAGS += $(CFLAGS) LDFLAGS += -s -m64 -L/usr/lib64 LIBS += RESFLAGS += $(DEFINES) $(INCLUDES) LDDEPS += LINKCMD = $(CXX) -o $(TARGET) $(LDFLAGS) $(OBJECTS) $(RESOURCES) $(ARCH) $(LIBS) define PREBUILDCMDS endef define PRELINKCMDS endef define POSTBUILDCMDS endef endif ]] end function T.gmake_cpp.UniversalStaticLibBlock() kind "StaticLib" platforms { "universal32" } prepare() local cfg = premake.getconfig(prj, "Debug", "Universal32") premake.gmake_cpp_config(cfg, premake.gcc) test.capture [[ ifeq ($(config),debuguniv32) OBJDIR = obj/Universal32/Debug TARGETDIR = . TARGET = $(TARGETDIR)/libMyProject.a DEFINES += INCLUDES += CPPFLAGS += $(DEFINES) $(INCLUDES) CFLAGS += $(CPPFLAGS) $(ARCH) -arch i386 -arch ppc CXXFLAGS += $(CFLAGS) LDFLAGS += -s -arch i386 -arch ppc LIBS += RESFLAGS += $(DEFINES) $(INCLUDES) LDDEPS += LINKCMD = libtool -o $(TARGET) $(OBJECTS) define PREBUILDCMDS endef define PRELINKCMDS endef define POSTBUILDCMDS endef endif ]] end
-- -- tests/test_gmake_cpp.lua -- Automated test suite for GNU Make C/C++ project generation. -- Copyright (c) 2009 Jason Perkins and the Premake project -- T.gmake_cpp = { } -- -- Configure a solution for testing -- local sln, prj function T.gmake_cpp.setup() _ACTION = "gmake" _OPTIONS.os = "linux" sln = solution "MySolution" configurations { "Debug", "Release" } platforms { "native" } prj = project "MyProject" language "C++" kind "ConsoleApp" end local function prepare() io.capture() premake.buildconfigs() end -- -- Test the header -- function T.gmake_cpp.BasicHeader() prepare() premake.gmake_cpp_header(prj, premake.gcc, sln.platforms) test.capture [[ # GNU Make project makefile autogenerated by Premake ifndef config config=debug endif ifndef verbose SILENT = @ endif ifndef CC CC = gcc endif ifndef CXX CXX = g++ endif ifndef AR AR = ar endif ]] end -- -- Test configuration blocks -- function T.gmake_cpp.BasicCfgBlock() prepare() local cfg = premake.getconfig(prj, "Debug") premake.gmake_cpp_config(cfg, premake.gcc) test.capture [[ ifeq ($(config),debug) OBJDIR = obj/Debug TARGETDIR = . TARGET = $(TARGETDIR)/MyProject DEFINES += INCLUDES += CPPFLAGS += -MMD $(DEFINES) $(INCLUDES) CFLAGS += $(CPPFLAGS) $(ARCH) CXXFLAGS += $(CFLAGS) LDFLAGS += -s LIBS += RESFLAGS += $(DEFINES) $(INCLUDES) LDDEPS += LINKCMD = $(CXX) -o $(TARGET) $(OBJECTS) $(LDFLAGS) $(RESOURCES) $(ARCH) $(LIBS) define PREBUILDCMDS endef define PRELINKCMDS endef define POSTBUILDCMDS endef endif ]] end function T.gmake_cpp.BasicCfgBlockWithPlatformCc() platforms { "ps3" } prepare() local cfg = premake.getconfig(prj, "Debug", "PS3") premake.gmake_cpp_config(cfg, premake.gcc) test.capture [[ ifeq ($(config),debugps3) CC = ppu-lv2-g++ CXX = ppu-lv2-g++ AR = ppu-lv2-ar OBJDIR = obj/PS3/Debug TARGETDIR = . TARGET = $(TARGETDIR)/MyProject.elf DEFINES += INCLUDES += CPPFLAGS += -MMD $(DEFINES) $(INCLUDES) CFLAGS += $(CPPFLAGS) $(ARCH) CXXFLAGS += $(CFLAGS) LDFLAGS += -s LIBS += RESFLAGS += $(DEFINES) $(INCLUDES) LDDEPS += LINKCMD = $(CXX) -o $(TARGET) $(OBJECTS) $(LDFLAGS) $(RESOURCES) $(ARCH) $(LIBS) define PREBUILDCMDS endef define PRELINKCMDS endef define POSTBUILDCMDS endef endif ]] end function T.gmake_cpp.PlatformSpecificBlock() platforms { "x64" } prepare() local cfg = premake.getconfig(prj, "Debug", "x64") premake.gmake_cpp_config(cfg, premake.gcc) test.capture [[ ifeq ($(config),debug64) OBJDIR = obj/x64/Debug TARGETDIR = . TARGET = $(TARGETDIR)/MyProject DEFINES += INCLUDES += CPPFLAGS += -MMD $(DEFINES) $(INCLUDES) CFLAGS += $(CPPFLAGS) $(ARCH) -m64 CXXFLAGS += $(CFLAGS) LDFLAGS += -s -m64 -L/usr/lib64 LIBS += RESFLAGS += $(DEFINES) $(INCLUDES) LDDEPS += LINKCMD = $(CXX) -o $(TARGET) $(OBJECTS) $(LDFLAGS) $(RESOURCES) $(ARCH) $(LIBS) define PREBUILDCMDS endef define PRELINKCMDS endef define POSTBUILDCMDS endef endif ]] end function T.gmake_cpp.UniversalStaticLibBlock() kind "StaticLib" platforms { "universal32" } prepare() local cfg = premake.getconfig(prj, "Debug", "Universal32") premake.gmake_cpp_config(cfg, premake.gcc) test.capture [[ ifeq ($(config),debuguniv32) OBJDIR = obj/Universal32/Debug TARGETDIR = . TARGET = $(TARGETDIR)/libMyProject.a DEFINES += INCLUDES += CPPFLAGS += $(DEFINES) $(INCLUDES) CFLAGS += $(CPPFLAGS) $(ARCH) -arch i386 -arch ppc CXXFLAGS += $(CFLAGS) LDFLAGS += -s -arch i386 -arch ppc LIBS += RESFLAGS += $(DEFINES) $(INCLUDES) LDDEPS += LINKCMD = libtool -o $(TARGET) $(OBJECTS) define PREBUILDCMDS endef define PRELINKCMDS endef define POSTBUILDCMDS endef endif ]] end
Fixed failing GMake C++ tests
Fixed failing GMake C++ tests
Lua
bsd-3-clause
starkos/premake-core,bravnsgaard/premake-core,Meoo/premake-core,sleepingwit/premake-core,lizh06/premake-core,resetnow/premake-core,sleepingwit/premake-core,alarouche/premake-core,tritao/premake-core,kankaristo/premake-core,LORgames/premake-core,saberhawk/premake-core,felipeprov/premake-core,jstewart-amd/premake-core,lizh06/premake-4.x,martin-traverse/premake-core,jstewart-amd/premake-core,aleksijuvani/premake-core,prapin/premake-core,lizh06/premake-core,starkos/premake-core,bravnsgaard/premake-core,premake/premake-4.x,mendsley/premake-core,TurkeyMan/premake-core,noresources/premake-core,noresources/premake-core,mandersan/premake-core,Zefiros-Software/premake-core,Blizzard/premake-core,aleksijuvani/premake-core,Tiger66639/premake-core,premake/premake-4.x,kankaristo/premake-core,Yhgenomics/premake-core,aleksijuvani/premake-core,lizh06/premake-4.x,kankaristo/premake-core,akaStiX/premake-core,soundsrc/premake-core,aleksijuvani/premake-core,jsfdez/premake-core,xriss/premake-core,grbd/premake-core,mandersan/premake-core,felipeprov/premake-core,sleepingwit/premake-core,prapin/premake-core,felipeprov/premake-core,lizh06/premake-4.x,jstewart-amd/premake-core,TurkeyMan/premake-core,jsfdez/premake-core,tvandijck/premake-core,premake/premake-core,PlexChat/premake-core,Meoo/premake-core,TurkeyMan/premake-core,tritao/premake-core,saberhawk/premake-core,soundsrc/premake-core,starkos/premake-core,mendsley/premake-core,akaStiX/premake-core,premake/premake-core,grbd/premake-core,jsfdez/premake-core,premake/premake-core,noresources/premake-core,resetnow/premake-core,soundsrc/premake-core,ryanjmulder/premake-4.x,mandersan/premake-core,Tiger66639/premake-core,dcourtois/premake-core,CodeAnxiety/premake-core,Blizzard/premake-core,Meoo/premake-core,xriss/premake-core,mandersan/premake-core,PlexChat/premake-core,mendsley/premake-core,Meoo/premake-core,noresources/premake-core,starkos/premake-core,soundsrc/premake-stable,Yhgenomics/premake-core,CodeAnxiety/premake-core,Zefiros-Software/premake-core,PlexChat/premake-core,alarouche/premake-core,prapin/premake-core,noresources/premake-core,noresources/premake-core,starkos/premake-core,resetnow/premake-core,lizh06/premake-core,CodeAnxiety/premake-core,lizh06/premake-core,sleepingwit/premake-core,alarouche/premake-core,martin-traverse/premake-core,lizh06/premake-4.x,sleepingwit/premake-core,premake/premake-core,Tiger66639/premake-core,dcourtois/premake-core,jstewart-amd/premake-core,starkos/premake-core,premake/premake-core,Yhgenomics/premake-core,ryanjmulder/premake-4.x,ryanjmulder/premake-4.x,ryanjmulder/premake-4.x,LORgames/premake-core,martin-traverse/premake-core,PlexChat/premake-core,bravnsgaard/premake-core,Blizzard/premake-core,LORgames/premake-core,noresources/premake-core,grbd/premake-core,jsfdez/premake-core,TurkeyMan/premake-core,tritao/premake-core,Zefiros-Software/premake-core,soundsrc/premake-stable,grbd/premake-core,tritao/premake-core,dcourtois/premake-core,xriss/premake-core,LORgames/premake-core,soundsrc/premake-core,soundsrc/premake-core,tvandijck/premake-core,dcourtois/premake-core,Tiger66639/premake-core,TurkeyMan/premake-core,prapin/premake-core,premake/premake-4.x,Blizzard/premake-core,akaStiX/premake-core,alarouche/premake-core,aleksijuvani/premake-core,Yhgenomics/premake-core,jstewart-amd/premake-core,xriss/premake-core,saberhawk/premake-core,tvandijck/premake-core,soundsrc/premake-stable,mendsley/premake-core,premake/premake-core,tvandijck/premake-core,martin-traverse/premake-core,Zefiros-Software/premake-core,CodeAnxiety/premake-core,bravnsgaard/premake-core,kankaristo/premake-core,bravnsgaard/premake-core,tvandijck/premake-core,xriss/premake-core,Blizzard/premake-core,resetnow/premake-core,akaStiX/premake-core,Zefiros-Software/premake-core,dcourtois/premake-core,felipeprov/premake-core,mendsley/premake-core,Blizzard/premake-core,dcourtois/premake-core,dcourtois/premake-core,mandersan/premake-core,premake/premake-4.x,starkos/premake-core,premake/premake-core,saberhawk/premake-core,CodeAnxiety/premake-core,LORgames/premake-core,soundsrc/premake-stable,resetnow/premake-core
364ad53c0cda4baf6e1d508e0a46b679bce80c45
share/media/funnyordie.lua
share/media/funnyordie.lua
-- libquvi-scripts -- Copyright (C) 2011,2013 Toni Gundogdu <legatvs@gmail.com> -- Copyright (C) 2010 quvi project -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- 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/>. -- local FunnyOrDie = {} -- Utility functions unique to this script -- Identify the media script. function ident(qargs) return { can_parse_url = FunnyOrDie.can_parse_url(qargs), domains = table.concat({'funnyordie.com'}, ',') } end -- Parse media properties. function parse(qargs) local p = quvi.http.fetch(qargs.input_url).data qargs.thumb_url = p:match('"og:image" content="(.-)"') or '' qargs.title = p:match('"og:title" content="(.-)">') or '' qargs.id = p:match('key:%s+"(.-)"') or '' qargs.streams = FunnyOrDie.iter_streams(p) return qargs end -- -- Utility functions -- function FunnyOrDie.can_parse_url(qargs) local U = require 'socket.url' local t = U.parse(qargs.input_url) if t and t.scheme and t.scheme:lower():match('^http$') and t.host and t.host:lower():match('funnyordie%.com$') and t.path and t.path:lower():match('^/videos/%w+') then return true else return false end end function FunnyOrDie.iter_streams(p) local t = {} for u in p:gmatch('type: "video/mp4", src: "(.-)"') do table.insert(t, u) end if #t ==0 then error('no match: media stream URL') end local S = require 'quvi/stream' local r = {} -- nostd is a dictionary used by this script only. libquvi ignores it. for _,u in pairs(t) do local q,c = u:match('/(%w+)%.(%w+)$') local s = S.stream_new(u) s.nostd = {quality=q} s.container = c s.id = FunnyOrDie.to_id(s) table.insert(r,s) end if #r >1 then FunnyOrDie.ch_best(r) end return r end function FunnyOrDie.ch_best(t) t[1].flags.best = true end function FunnyOrDie.to_id(t) return string.format("%s_%s", t.nostd.quality, t.container) end -- vim: set ts=2 sw=2 tw=72 expandtab:
-- libquvi-scripts -- Copyright (C) 2011,2013 Toni Gundogdu <legatvs@gmail.com> -- Copyright (C) 2010 quvi project -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- 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/>. -- local FunnyOrDie = {} -- Utility functions unique to this script -- Identify the media script. function ident(qargs) return { can_parse_url = FunnyOrDie.can_parse_url(qargs), domains = table.concat({'funnyordie.com'}, ',') } end -- Parse media properties. function parse(qargs) local p = quvi.http.fetch(qargs.input_url).data qargs.thumb_url = p:match('"og:image" content="(.-)"') or '' qargs.title = p:match('"og:title" content="(.-)">') or '' qargs.id = p:match('key:%s+"(.-)"') or '' qargs.streams = FunnyOrDie.iter_streams(p) return qargs end -- -- Utility functions -- function FunnyOrDie.can_parse_url(qargs) local U = require 'socket.url' local t = U.parse(qargs.input_url) if t and t.scheme and t.scheme:lower():match('^http$') and t.host and t.host:lower():match('funnyordie%.com$') and t.path and t.path:lower():match('^/videos/%w+') then return true else return false end end function FunnyOrDie.iter_streams(p) local t = {} -- 41a7516647: added the pattern in the next line, and removed... for u in p:gmatch('type: "video/mp4", src: "(.-)"') do table.insert(t,u) end for u in p:gmatch('source src="(.-)"') do table.insert(t,u) end -- ... This. -- Keep both of them. if #t ==0 then error('no match: media stream URL') end local S = require 'quvi/stream' local r = {} -- nostd is a dictionary used by this script only. libquvi ignores it. for _,u in pairs(t) do local q,c = u:match('/(%w+)%.(%w+)$') if q and c then local s = S.stream_new(u) s.nostd = {quality=q} s.container = c s.id = FunnyOrDie.to_id(s) table.insert(r,s) end end if #r >1 then FunnyOrDie.ch_best(r) end return r end function FunnyOrDie.ch_best(t) t[1].flags.best = true end function FunnyOrDie.to_id(t) return string.format("%s_%s", t.nostd.quality, t.container) end -- vim: set ts=2 sw=2 tw=72 expandtab:
FIX: media/funnyordie.lua: Media stream URL pattern
FIX: media/funnyordie.lua: Media stream URL pattern This was fixed by 41a7516647, which removed the pattern that appears to work again. Keep both patterns. Other changes: * Insert only those media URLs that match the quality-container pattern Signed-off-by: Toni Gundogdu <eac2284b3c43676907b96f08de9d3d52d5df0361@gmail.com>
Lua
agpl-3.0
alech/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts,legatvs/libquvi-scripts
6addb504e4c956dbbb22fb9e3ed1ed1e87972986
lualib/snax/loginserver.lua
lualib/snax/loginserver.lua
local skynet = require "skynet" require "skynet.manager" local socket = require "skynet.socket" local crypt = require "skynet.crypt" local table = table local string = string local assert = assert --[[ Protocol: line (\n) based text protocol 1. Server->Client : base64(8bytes random challenge) 2. Client->Server : base64(8bytes handshake client key) 3. Server: Gen a 8bytes handshake server key 4. Server->Client : base64(DH-Exchange(server key)) 5. Server/Client secret := DH-Secret(client key/server key) 6. Client->Server : base64(HMAC(challenge, secret)) 7. Client->Server : DES(secret, base64(token)) 8. Server : call auth_handler(token) -> server, uid (A user defined method) 9. Server : call login_handler(server, uid, secret) ->subid (A user defined method) 10. Server->Client : 200 base64(subid) Error Code: 400 Bad Request . challenge failed 401 Unauthorized . unauthorized by auth_handler 403 Forbidden . login_handler failed 406 Not Acceptable . already in login (disallow multi login) Success: 200 base64(subid) ]] local socket_error = {} local function assert_socket(service, v, fd) if v then return v else skynet.error(string.format("%s failed: socket (fd = %d) closed", service, fd)) error(socket_error) end end local function write(service, fd, text) assert_socket(service, socket.write(fd, text), fd) end local function launch_slave(auth_handler) local function auth(fd, addr) -- set socket buffer limit (8K) -- If the attacker send large package, close the socket socket.limit(fd, 8192) local challenge = crypt.randomkey() write("auth", fd, crypt.base64encode(challenge).."\n") local handshake = assert_socket("auth", socket.readline(fd), fd) local clientkey = crypt.base64decode(handshake) if #clientkey ~= 8 then error "Invalid client key" end local serverkey = crypt.randomkey() write("auth", fd, crypt.base64encode(crypt.dhexchange(serverkey)).."\n") local secret = crypt.dhsecret(clientkey, serverkey) local response = assert_socket("auth", socket.readline(fd), fd) local hmac = crypt.hmac64(challenge, secret) if hmac ~= crypt.base64decode(response) then write("auth", fd, "400 Bad Request\n") error "challenge failed" end local etoken = assert_socket("auth", socket.readline(fd),fd) local token = crypt.desdecode(secret, crypt.base64decode(etoken)) local ok, server, uid = pcall(auth_handler,token) return ok, server, uid, secret end local function ret_pack(ok, err, ...) if ok then return skynet.pack(err, ...) else if err == socket_error then return skynet.pack(nil, "socket error") else return skynet.pack(false, err) end end end local function auth_fd(fd, addr) skynet.error(string.format("connect from %s (fd = %d)", addr, fd)) socket.start(fd) -- may raise error here local msg, len = ret_pack(pcall(auth, fd, addr)) socket.abandon(fd) -- never raise error here return msg, len end skynet.dispatch("lua", function(_,_,...) local ok, msg, len = pcall(auth_fd, ...) if ok then skynet.ret(msg,len) else skynet.ret(skynet.pack(false, msg)) end end) end local user_login = {} local function accept(conf, s, fd, addr) -- call slave auth local ok, server, uid, secret = skynet.call(s, "lua", fd, addr) -- slave will accept(start) fd, so we can write to fd later if not ok then if ok ~= nil then write("response 401", fd, "401 Unauthorized\n") end error(server) end if not conf.multilogin then if user_login[uid] then write("response 406", fd, "406 Not Acceptable\n") error(string.format("User %s is already login", uid)) end user_login[uid] = true end local ok, err = pcall(conf.login_handler, server, uid, secret) -- unlock login user_login[uid] = nil if ok then err = err or "" write("response 200",fd, "200 "..crypt.base64encode(err).."\n") else write("response 403",fd, "403 Forbidden\n") error(err) end end local function launch_master(conf) local instance = conf.instance or 8 assert(instance > 0) local host = conf.host or "0.0.0.0" local port = assert(tonumber(conf.port)) local slave = {} local balance = 1 skynet.dispatch("lua", function(_,source,command, ...) skynet.ret(skynet.pack(conf.command_handler(command, ...))) end) for i=1,instance do table.insert(slave, skynet.newservice(SERVICE_NAME)) end skynet.error(string.format("login server listen at : %s %d", host, port)) local id = socket.listen(host, port) socket.start(id , function(fd, addr) local s = slave[balance] balance = balance + 1 if balance > #slave then balance = 1 end local ok, err = pcall(accept, conf, s, fd, addr) if not ok then if err ~= socket_error then skynet.error(string.format("invalid client (fd = %d) error = %s", fd, err)) end end socket.close_fd(fd) -- We haven't call socket.start, so use socket.close_fd rather than socket.close. end) end local function login(conf) local name = "." .. (conf.name or "login") skynet.start(function() local loginmaster = skynet.localname(name) if loginmaster then local auth_handler = assert(conf.auth_handler) launch_master = nil conf = nil launch_slave(auth_handler) else launch_slave = nil conf.auth_handler = nil assert(conf.login_handler) assert(conf.command_handler) skynet.register(name) launch_master(conf) end end) end return login
local skynet = require "skynet" require "skynet.manager" local socket = require "skynet.socket" local crypt = require "skynet.crypt" local table = table local string = string local assert = assert --[[ Protocol: line (\n) based text protocol 1. Server->Client : base64(8bytes random challenge) 2. Client->Server : base64(8bytes handshake client key) 3. Server: Gen a 8bytes handshake server key 4. Server->Client : base64(DH-Exchange(server key)) 5. Server/Client secret := DH-Secret(client key/server key) 6. Client->Server : base64(HMAC(challenge, secret)) 7. Client->Server : DES(secret, base64(token)) 8. Server : call auth_handler(token) -> server, uid (A user defined method) 9. Server : call login_handler(server, uid, secret) ->subid (A user defined method) 10. Server->Client : 200 base64(subid) Error Code: 401 Unauthorized . unauthorized by auth_handler 403 Forbidden . login_handler failed 406 Not Acceptable . already in login (disallow multi login) Success: 200 base64(subid) ]] local socket_error = {} local function assert_socket(service, v, fd) if v then return v else skynet.error(string.format("%s failed: socket (fd = %d) closed", service, fd)) error(socket_error) end end local function write(service, fd, text) assert_socket(service, socket.write(fd, text), fd) end local function launch_slave(auth_handler) local function auth(fd, addr) -- set socket buffer limit (8K) -- If the attacker send large package, close the socket socket.limit(fd, 8192) local challenge = crypt.randomkey() write("auth", fd, crypt.base64encode(challenge).."\n") local handshake = assert_socket("auth", socket.readline(fd), fd) local clientkey = crypt.base64decode(handshake) if #clientkey ~= 8 then error "Invalid client key" end local serverkey = crypt.randomkey() write("auth", fd, crypt.base64encode(crypt.dhexchange(serverkey)).."\n") local secret = crypt.dhsecret(clientkey, serverkey) local response = assert_socket("auth", socket.readline(fd), fd) local hmac = crypt.hmac64(challenge, secret) if hmac ~= crypt.base64decode(response) then error "challenge failed" end local etoken = assert_socket("auth", socket.readline(fd),fd) local token = crypt.desdecode(secret, crypt.base64decode(etoken)) local ok, server, uid = pcall(auth_handler,token) return ok, server, uid, secret end local function ret_pack(ok, err, ...) if ok then return skynet.pack(err, ...) else if err == socket_error then return skynet.pack(nil, "socket error") else return skynet.pack(false, err) end end end local function auth_fd(fd, addr) skynet.error(string.format("connect from %s (fd = %d)", addr, fd)) socket.start(fd) -- may raise error here local msg, len = ret_pack(pcall(auth, fd, addr)) socket.abandon(fd) -- never raise error here return msg, len end skynet.dispatch("lua", function(_,_,...) local ok, msg, len = pcall(auth_fd, ...) if ok then skynet.ret(msg,len) else skynet.ret(skynet.pack(false, msg)) end end) end local user_login = {} local function accept(conf, s, fd, addr) -- call slave auth local ok, server, uid, secret = skynet.call(s, "lua", fd, addr) -- slave will accept(start) fd, so we can write to fd later if not ok then if ok ~= nil then write("response 401", fd, "401 Unauthorized\n") end error(server) end if not conf.multilogin then if user_login[uid] then write("response 406", fd, "406 Not Acceptable\n") error(string.format("User %s is already login", uid)) end user_login[uid] = true end local ok, err = pcall(conf.login_handler, server, uid, secret) -- unlock login user_login[uid] = nil if ok then err = err or "" write("response 200",fd, "200 "..crypt.base64encode(err).."\n") else write("response 403",fd, "403 Forbidden\n") error(err) end end local function launch_master(conf) local instance = conf.instance or 8 assert(instance > 0) local host = conf.host or "0.0.0.0" local port = assert(tonumber(conf.port)) local slave = {} local balance = 1 skynet.dispatch("lua", function(_,source,command, ...) skynet.ret(skynet.pack(conf.command_handler(command, ...))) end) for i=1,instance do table.insert(slave, skynet.newservice(SERVICE_NAME)) end skynet.error(string.format("login server listen at : %s %d", host, port)) local id = socket.listen(host, port) socket.start(id , function(fd, addr) local s = slave[balance] balance = balance + 1 if balance > #slave then balance = 1 end local ok, err = pcall(accept, conf, s, fd, addr) if not ok then if err ~= socket_error then skynet.error(string.format("invalid client (fd = %d) error = %s", fd, err)) end end socket.close_fd(fd) -- We haven't call socket.start, so use socket.close_fd rather than socket.close. end) end local function login(conf) local name = "." .. (conf.name or "login") skynet.start(function() local loginmaster = skynet.localname(name) if loginmaster then local auth_handler = assert(conf.auth_handler) launch_master = nil conf = nil launch_slave(auth_handler) else launch_slave = nil conf.auth_handler = nil assert(conf.login_handler) assert(conf.command_handler) skynet.register(name) launch_master(conf) end end) end return login
fix #1012
fix #1012
Lua
mit
ag6ag/skynet,korialuo/skynet,cloudwu/skynet,hongling0/skynet,xcjmine/skynet,jxlczjp77/skynet,sanikoyes/skynet,cloudwu/skynet,icetoggle/skynet,hongling0/skynet,xjdrew/skynet,xjdrew/skynet,bigrpg/skynet,hongling0/skynet,pigparadise/skynet,korialuo/skynet,cloudwu/skynet,xcjmine/skynet,bigrpg/skynet,ag6ag/skynet,icetoggle/skynet,bigrpg/skynet,wangyi0226/skynet,wangyi0226/skynet,jxlczjp77/skynet,pigparadise/skynet,wangyi0226/skynet,sanikoyes/skynet,JiessieDawn/skynet,pigparadise/skynet,sanikoyes/skynet,JiessieDawn/skynet,xcjmine/skynet,korialuo/skynet,icetoggle/skynet,JiessieDawn/skynet,xjdrew/skynet,jxlczjp77/skynet,ag6ag/skynet
46cf04efdd73e3a7df274c77731ff031838abccb
asset/src/framework/system.lua
asset/src/framework/system.lua
--[[ Description: Internal objects extensions Author: M.Wan Date: 04/26/2014 ]] -- Copy k-v from source table to the target table. function table.shallowCopy(targetTable, sourceTable) if type(targetTable) == "table" and type(sourceTable) == "table" then for k, v in pairs(sourceTable) do targetTable[k] = v end end end -- Deep copy function table.deepCopy(targetTable, sourceTable) if type(targetTable) == "table" and type(sourceTable) == "table" then for k, v in pairs(sourceTable) do if type(v) == "table" then if type(targetTable[k]) ~= "table" then targetTable[k] = {} end table.deepCopy(targetTable[k], v) else targetTable[k] = v end end end end -- get k-v count function table.count(t, selector, ...) if type(t) ~= "table" then return -1 end local count = 0 for k, v in pairs(t) do if selector == nil or selector(v, k, ...) then count = count + 1 end end return count end -- concat strings with the specified character function table.join(t, c) if type(t) ~= "table" or type(c) ~= "string" then return end local str = "" for i, v in ipairs(t) do str = str .. tostring(v) if i ~= #t then str = str .. c end end return str end -- do action for each element in table function table.forEach(t, action, ...) if type(t) ~= "table" or type(action) ~= "function" then return end for i, v in ipairs(t) do action(v, i, ...) end end -- select new table for the specified behaviors function table.select(t, selector, ...) if type(t) ~= "table" or type(selector) ~= "function" then return nil end local ret = {} for i, v in ipairs(t) do if selector(v, i, ...) then table.insert(ret, v) end end return ret end -- cast every item of table to the specified item function table.cast(t, caster, ...) if type(t) ~= "table" or type(caster) ~= "function" then return nil end local ret = {} for i, v in ipairs(table) do local item = caster(v, i, ...) table.insert(ret, item) end return ret end -- whether the table contains the object which satisfies the condition function table.contains(t, selector, ...) if type(t) ~= "table" then return false end for i, v in ipairs(t) do if selector(v, i, ...) then return true end end return false end -- remove the first object which satisfied the condition function table.erase(t, selector, ...) if type(t) ~= "table" then return false end for i, v in ipairs(t) do if selector(v, i, ...) then table.remove(table, i) return true end end return false end -- reverse the table function table.reverse(t) for i = 1, math.floor(#t / 2) do t[i], t[#t - i + 1] = t[#t - i + 1], t[i] end end -- shuffle the array function table.shuffle(t) if type(t) ~= "table" then return end local rd = nil for i = 1, #t - 1 do rd = math.random(1, #t - i - 1) t[i], t[rd] = t[rd], t[i] end end -- log table function table.dump(table) if type(table) ~= "table" then return false end local function dump(data, prefix) prefix = prefix or "" local str = tostring(data) local prefix_next = prefix .. "\t" str = str .. "\n" .. prefix .. "{" for k, v in pairs(data) do str = str .. "\n" .. prefix_next .. k .. " = " if type(v) == "table" then str = str .. dump(v, prefix_next) else str = str .. tostring(v) end end str = str .. "\n" .. prefix .. "}" return str end local traceback = string.split(debug.traceback("", 2), "\n") print("dump from: " .. string.trim(traceback[3])) print(dump(table)) end -- serialze table function table.serialize(t, filter, ...) if type(t) ~= "table" then return false end if filter == nil or type(filter) ~= "function" then filter = function() return true end end local mark = {} local assign = {} local function serialize_table(t, parent, filter, ...) mark[t] = parent local tmp = {} for k, v in pairs(t) do if (type(v) == "number" or type(v) == "string" or type(v) == "table" or type(v) == "boolean") and filter(v, k, ...) then local key = type(k) == "number" and "[" .. k .. "]" or k if type(v) == "table" then local dotKey = parent .. (type(k) == "number" and key or "." .. key) if mark[v] then table.insert(assign, dotKey .. "=" .. mark[v]) else table.insert(tmp, key .. "=" .. serialize_table(v, dotKey)) end else table.insert(tmp, key .. "=" .. (type(v) == "string" and ("\"" .. v .. "\"") or tostring(v))) end end end return "{" .. table.concat(tmp, ",") .. "}" end return "do local ret = " .. serialize_table(t, "ret", filter, ...) .. table.concat(assign, " ") .. " return ret end" end -- split string from the specified character function string.split(s, delimiter) s = tostring(s) delimiter = tostring(delimiter) if (delimiter == "") then return nil end local pos, arr = 0, {} -- for each divider found for st, sp in function() return string.find(s, delimiter, pos, true) end do table.insert(arr, string.sub(s, pos, st - 1)) pos = sp + 1 end table.insert(arr, string.sub(s, pos)) return arr end function string.ltrim(str) return string.gsub(str, "^[ \t\n\r]+", "") end function string.rtrim(str) return string.gsub(str, "[ \t\n\r]+$", "") end function string.trim(str) str = string.gsub(str, "^[ \t\n\r]+", "") return string.gsub(str, "[ \t\n\r]+$", "") end -- get utf-8 char array function string.charArray(s) local function getBytesOfChar(idx) local byte = string.byte(s, idx) if bit.rshift(byte, 7) == 0x0 then return 1 elseif bit.rshift(byte, 5) == 0x6 then return 2 elseif bit.rshift(byte, 4) == 0xE then return 3 elseif bit.rshift(byte, 3) == 0x1E then return 4 elseif bit.rshift(byte, 2) == 0x3E then return 5 elseif bit.rshift(byte, 1) == 0x7E then return 6 end return 1 end local ary = {} local start = 1 local idx = 1 while idx <= #str do idx = idx + getBytesOfChar(idx) local substr = string.sub(str, start, idx - 1) start = idx table.insert(ary, substr) end return ary end
--[[ Description: Internal objects extensions Author: M.Wan Date: 04/26/2014 ]] -- Copy k-v from source table to the target table. function table.shallowCopy(targetTable, sourceTable) if type(targetTable) == "table" and type(sourceTable) == "table" then for k, v in pairs(sourceTable) do targetTable[k] = v end end end -- Deep copy function table.deepCopy(targetTable, sourceTable) if type(targetTable) == "table" and type(sourceTable) == "table" then for k, v in pairs(sourceTable) do if type(v) == "table" then if type(targetTable[k]) ~= "table" then targetTable[k] = {} end table.deepCopy(targetTable[k], v) else targetTable[k] = v end end end end -- get k-v count function table.count(t, selector, ...) if type(t) ~= "table" then return -1 end local count = 0 for k, v in pairs(t) do if selector == nil or selector(v, k, ...) then count = count + 1 end end return count end -- concat strings with the specified character function table.join(t, c) if type(t) ~= "table" or type(c) ~= "string" then return end local str = "" for i, v in ipairs(t) do str = str .. tostring(v) if i ~= #t then str = str .. c end end return str end -- do action for each element in table function table.forEach(t, action, ...) if type(t) ~= "table" or type(action) ~= "function" then return end for i, v in ipairs(t) do action(v, ...) end end -- select new table for the specified behaviors function table.select(t, selector, ...) if type(t) ~= "table" or type(selector) ~= "function" then return nil end local ret = {} for i, v in ipairs(t) do ret[i] = selector(v, ...) end return ret end -- find elements which satisfy the selector function table.filter(t, filter, ...) if type(t) ~= "table" or type(filter) ~= "function" then return nil end local ret = {} for i, v in ipairs(t) do if filter(v, ...) then table.insert(ret, v) end end return ret end -- whether the table contains the object which satisfies the condition function table.contains(t, selector, ...) if type(t) ~= "table" then return false end for i, v in ipairs(t) do if selector(v, ...) then return true end end return false end -- remove the first object which satisfied the condition function table.erase(t, selector, ...) if type(t) ~= "table" then return false end for i, v in ipairs(t) do if selector(v, ...) then table.remove(table, i) return true end end return false end -- reverse the table function table.reverse(t) for i = 1, math.floor(#t / 2) do t[i], t[#t - i + 1] = t[#t - i + 1], t[i] end end -- shuffle the array function table.shuffle(t) if type(t) ~= "table" then return end local rd = nil for i = 1, #t - 1 do rd = math.random(1, #t - i - 1) t[i], t[rd] = t[rd], t[i] end end -- log table function table.dump(table) if type(table) ~= "table" then return false end local function dump(data, prefix) prefix = prefix or "" local str = tostring(data) local prefix_next = prefix .. "\t" str = str .. "\n" .. prefix .. "{" for k, v in pairs(data) do str = str .. "\n" .. prefix_next .. k .. " = " if type(v) == "table" then str = str .. dump(v, prefix_next) else str = str .. tostring(v) end end str = str .. "\n" .. prefix .. "}" return str end local traceback = string.split(debug.traceback("", 2), "\n") print("dump from: " .. string.trim(traceback[3])) print(dump(table)) end -- serialze table function table.serialize(t, filter, ...) if type(t) ~= "table" then return false end if filter == nil or type(filter) ~= "function" then filter = function() return true end end local mark = {} local assign = {} local function serialize_table(t, parent, filter, ...) mark[t] = parent local tmp = {} for k, v in pairs(t) do if (type(v) == "number" or type(v) == "string" or type(v) == "table" or type(v) == "boolean") and filter(v, k, ...) then local key = type(k) == "number" and "[" .. k .. "]" or k if type(v) == "table" then local dotKey = parent .. (type(k) == "number" and key or "." .. key) if mark[v] then table.insert(assign, dotKey .. "=" .. mark[v]) else table.insert(tmp, key .. "=" .. serialize_table(v, dotKey)) end else table.insert(tmp, key .. "=" .. (type(v) == "string" and ("\"" .. v .. "\"") or tostring(v))) end end end return "{" .. table.concat(tmp, ",") .. "}" end return "do local ret = " .. serialize_table(t, "ret", filter, ...) .. table.concat(assign, " ") .. " return ret end" end -- split string from the specified character function string.split(s, delimiter) s = tostring(s) delimiter = tostring(delimiter) if (delimiter == "") then return nil end local pos, arr = 0, {} -- for each divider found for st, sp in function() return string.find(s, delimiter, pos, true) end do table.insert(arr, string.sub(s, pos, st - 1)) pos = sp + 1 end table.insert(arr, string.sub(s, pos)) return arr end function string.ltrim(str) return string.gsub(str, "^[ \t\n\r]+", "") end function string.rtrim(str) return string.gsub(str, "[ \t\n\r]+$", "") end function string.trim(str) str = string.gsub(str, "^[ \t\n\r]+", "") return string.gsub(str, "[ \t\n\r]+$", "") end -- get utf-8 char array function string.charArray(s) local function getBytesOfChar(idx) local byte = string.byte(s, idx) if bit.rshift(byte, 7) == 0x0 then return 1 elseif bit.rshift(byte, 5) == 0x6 then return 2 elseif bit.rshift(byte, 4) == 0xE then return 3 elseif bit.rshift(byte, 3) == 0x1E then return 4 elseif bit.rshift(byte, 2) == 0x3E then return 5 elseif bit.rshift(byte, 1) == 0x7E then return 6 end return 1 end local ary = {} local start = 1 local idx = 1 while idx <= #str do idx = idx + getBytesOfChar(idx) local substr = string.sub(str, start, idx - 1) start = idx table.insert(ary, substr) end return ary end
fix some system apis
fix some system apis
Lua
apache-2.0
wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua,wanmaple/MWFrameworkForCocosLua
03509bb551e7b5491a8ed08f9fc7241d39beb215
xmake/plugins/project/clang/compile_commands.lua
xmake/plugins/project/clang/compile_commands.lua
--!The Make-like Build Utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2017, TBOOX Open Source Group. -- -- @author ruki -- @file compile_commands.lua -- -- imports import("core.tool.compiler") import("core.project.project") import("core.language.language") -- make the object function _make_object(jsonfile, target, sourcefile, objectfile) -- get the source file kind local sourcekind = language.sourcekind_of(sourcefile) -- make the object for the *.o/obj? ignore it directly if sourcekind == "obj" or sourcekind == "lib" then return end -- get compile arguments local arguments = table.join(compiler.compargv(sourcefile, objectfile, {target = target, sourcekind = sourcekind})) -- make body jsonfile:printf( [[%s{ "directory": "%s", "arguments": ["%s"], "file": "%s" }]], ifelse(_g.firstline, "", ",\n"), os.projectdir(), table.concat(arguments, "\", \""), sourcefile) -- clear first line marks _g.firstline = false end -- make each objects function _make_each_objects(jsonfile, target, sourcekind, sourcebatch) for index, objectfile in ipairs(sourcebatch.objectfiles) do _make_object(jsonfile, target, sourcebatch.sourcefiles[index], objectfile) end end -- make single object function _make_single_object(jsonfile, target, sourcekind, sourcebatch) -- not supported now, ignore it directly for _, sourcefile in ipairs(table.wrap(sourcebatch.sourcefiles)) do cprint("${bright yellow}warning: ${default yellow}ignore[%s]: %s", target:name(), sourcefile) end end -- make target function _make_target(jsonfile, target) -- build source batches for sourcekind, sourcebatch in pairs(target:sourcebatches()) do if type(sourcebatch.objectfiles) == "string" then _make_single_object(jsonfile, target, sourcekind, sourcebatch) else _make_each_objects(jsonfile, target, sourcekind, sourcebatch) end end end -- make all function _make_all(jsonfile) -- make header jsonfile:print("[") -- make commands _g.firstline = true for _, target in pairs(project.targets()) do local isdefault = target:get("default") if not target:isphony() and (isdefault == nil or isdefault == true) then _make_target(jsonfile, target) end end -- make tailer jsonfile:print("]") end -- generate compilation databases for clang-based tools(compile_commands.json) -- -- references: -- - https://clang.llvm.org/docs/JSONCompilationDatabase.html -- - https://sarcasm.github.io/notes/dev/compilation-database.html -- - http://eli.thegreenplace.net/2014/05/21/compilation-databases-for-clang-based-tools -- function make(outputdir) -- enter project directory local oldir = os.cd(os.projectdir()) -- open the jsonfile local jsonfile = io.open(path.join(outputdir, "compile_commands.json"), "w") -- make all _make_all(jsonfile) -- close the jsonfile jsonfile:close() -- leave project directory os.cd(oldir) end
--!The Make-like Build Utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2017, TBOOX Open Source Group. -- -- @author ruki -- @file compile_commands.lua -- -- imports import("core.tool.compiler") import("core.project.project") import("core.language.language") -- make the object function _make_object(jsonfile, target, sourcefile, objectfile) -- get the source file kind local sourcekind = language.sourcekind_of(sourcefile) -- make the object for the *.o/obj? ignore it directly if sourcekind == "obj" or sourcekind == "lib" then return end -- get compile arguments local arguments = table.join(compiler.compargv(sourcefile, objectfile, {target = target, sourcekind = sourcekind})) -- escape '"', '\' local arguments_escape = {} for _, arg in ipairs(arguments) do table.insert(arguments_escape, (arg:gsub("[\"\\]", "\\%1"))) end -- make body jsonfile:printf( [[%s{ "directory": "%s", "arguments": ["%s"], "file": "%s" }]], ifelse(_g.firstline, "", ",\n"), os.projectdir(), table.concat(arguments_escape, "\", \""), sourcefile) -- clear first line marks _g.firstline = false end -- make each objects function _make_each_objects(jsonfile, target, sourcekind, sourcebatch) for index, objectfile in ipairs(sourcebatch.objectfiles) do _make_object(jsonfile, target, sourcebatch.sourcefiles[index], objectfile) end end -- make single object function _make_single_object(jsonfile, target, sourcekind, sourcebatch) -- not supported now, ignore it directly for _, sourcefile in ipairs(table.wrap(sourcebatch.sourcefiles)) do cprint("${bright yellow}warning: ${default yellow}ignore[%s]: %s", target:name(), sourcefile) end end -- make target function _make_target(jsonfile, target) -- build source batches for sourcekind, sourcebatch in pairs(target:sourcebatches()) do if type(sourcebatch.objectfiles) == "string" then _make_single_object(jsonfile, target, sourcekind, sourcebatch) else _make_each_objects(jsonfile, target, sourcekind, sourcebatch) end end end -- make all function _make_all(jsonfile) -- make header jsonfile:print("[") -- make commands _g.firstline = true for _, target in pairs(project.targets()) do local isdefault = target:get("default") if not target:isphony() and (isdefault == nil or isdefault == true) then _make_target(jsonfile, target) end end -- make tailer jsonfile:print("]") end -- generate compilation databases for clang-based tools(compile_commands.json) -- -- references: -- - https://clang.llvm.org/docs/JSONCompilationDatabase.html -- - https://sarcasm.github.io/notes/dev/compilation-database.html -- - http://eli.thegreenplace.net/2014/05/21/compilation-databases-for-clang-based-tools -- function make(outputdir) -- enter project directory local oldir = os.cd(os.projectdir()) -- open the jsonfile local jsonfile = io.open(path.join(outputdir, "compile_commands.json"), "w") -- make all _make_all(jsonfile) -- close the jsonfile jsonfile:close() -- leave project directory os.cd(oldir) end
fix arguments escape for compile_commands
fix arguments escape for compile_commands
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake
18af9307886479cb0095a6095ccfd71d1cedb369
bin/batchTomo.lua
bin/batchTomo.lua
#!/usr/bin/env lua --[[===========================================================================# # This is a program to run tomoAuto in batch to align and reconstruct a large # # number of raw image stacks. # #------------------------------------------------------------------------------# # Author: Dustin Morado # # Written: March 24th 2014 # # Contact: dustin.morado@uth.tmc.edu # #------------------------------------------------------------------------------# # Arguments: arg[1] = fiducial size in nm <integer> # #===========================================================================--]] package.path = package.path .. ';' .. os.getenv('TOMOAUTOROOT') .. '/bin/?.lua' local lfs = assert(require 'lfs') local tomoAuto = assert(require 'tomoAuto') local tomoOpt = assert(require 'tomoOpt') shortOptsString = 'cd_hn_p_' longOptsString = 'CTF, defocus, help, max, parallel' arg, Opts = tomoOpt.get(arg, shortOptsString, longOptsString) local fileTable = {} local i = 1 for file in lfs.dir('.') do if file:find('%w+%.st$') then fileTable[i] = file i = i + 1 end end local total = i - 1 local procs = Opts.n_ or 1 local thread = coroutine.create(function () for i = 1, total do runString = 'tomoAuto.lua ' if Opts.c then runString = runString .. '-c' end if Opts.d_ then runString = runString .. ' -d ' .. Opts.d_ end if Opts.p_ then runString = runString .. ' -p ' .. Opts.p_ end runString = runString .. ' ' .. fileTable .. ' ' .. arg[1] success, exit, signal = os.execute(runString) if (i % n == 0) then coroutine.yield() end end end) while coroutine.resume(thread) do print('Running on block ' .. i) end
#!/usr/bin/env lua --[[===========================================================================# # This is a program to run tomoAuto in batch to align and reconstruct a large # # number of raw image stacks. # #------------------------------------------------------------------------------# # Author: Dustin Morado # # Written: March 24th 2014 # # Contact: dustin.morado@uth.tmc.edu # #------------------------------------------------------------------------------# # Arguments: arg[1] = fiducial size in nm <integer> # #===========================================================================--]] package.path = package.path .. ';' .. os.getenv('TOMOAUTOROOT') .. '/lib/?.lua' package.path = package.path .. ';' .. os.getenv('TOMOAUTOROOT') .. '/bin/?.lua' local lfs = assert(require 'lfs') local tomoAuto = assert(require 'tomoAuto') local tomoOpt = assert(require 'tomoOpt') local shortOptsString = 'cd_hn_p_' local longOptsString = 'CTF, defocus, help, max, parallel' local arg, Opts = tomoOpt.get(arg, shortOptsString, longOptsString) local fileTable = {} local i = 1 for file in lfs.dir('.') do if file:find('%w+%.st$') then fileTable[i] = file i = i + 1 end end local total = i - 1 local procs = Opts.n_ or 1 local thread = coroutine.create(function () for i = 1, total do runString = 'tomoAuto.lua ' if Opts.c then runString = runString .. '-c' end if Opts.d_ then runString = runString .. ' -d ' .. Opts.d_ end if Opts.p_ then runString = runString .. ' -p ' .. Opts.p_ end runString = runString .. ' ' .. fileTable .. ' ' .. arg[1] success, exit, signal = os.execute(runString) if (i % n == 0) then coroutine.yield() end end end) while coroutine.resume(thread) do print('Running on block ' .. i) end
fix package path some more
fix package path some more
Lua
mit
DustinMorado/tomoauto
6ab0139532fa359c3536097b4d5d1ad336cbe1ea
userspace/falco/lua/output.lua
userspace/falco/lua/output.lua
local mod = {} levels = {"Emergency", "Alert", "Critical", "Error", "Warning", "Notice", "Informational", "Debug"} mod.levels = levels local outputs = {} function mod.stdout(level, msg) print (msg) end function mod.file_validate(options) if (not type(options.filename) == 'string') then error("File output needs to be configured with a valid filename") end file, err = io.open(options.filename, "a+") if file == nil then error("Error with file output: "..err) end file:close() end function mod.file(level, msg) file = io.open(options.filename, "a+") file:write(msg, "\n") file:close() end function mod.syslog(level, msg) falco.syslog(level, msg) end function mod.program(level, msg) -- XXX Ideally we'd check that the program ran -- successfully. However, the luajit we're using returns true even -- when the shell can't run the program. file = io.popen(options.program, "w") file:write(msg, "\n") file:close() end local function level_of(s) s = string.lower(s) for i,v in ipairs(levels) do if (string.find(string.lower(v), "^"..s)) then return i - 1 -- (syslog levels start at 0, lua indices start at 1) end end error("Invalid severity level: "..s) end function output_event(event, rule, priority, format) local level = level_of(priority) format = "*%evt.time: "..levels[level+1].." "..format formatter = falco.formatter(format) msg = falco.format_event(event, rule, levels[level+1], formatter) for index,o in ipairs(outputs) do o.output(level, msg) end falco.free_formatter(formatter) end function add_output(output_name, config) if not (type(mod[output_name]) == 'function') then error("rule_loader.add_output(): invalid output_name: "..output_name) end -- outputs can optionally define a validation function so that we don't -- find out at runtime (when an event finally matches a rule!) that the config is invalid if (type(mod[output_name.."_validate"]) == 'function') then mod[output_name.."_validate"](config) end table.insert(outputs, {output = mod[output_name], config=config}) end return mod
local mod = {} levels = {"Emergency", "Alert", "Critical", "Error", "Warning", "Notice", "Informational", "Debug"} mod.levels = levels local outputs = {} function mod.stdout(level, msg) print (msg) end function mod.file_validate(options) if (not type(options.filename) == 'string') then error("File output needs to be configured with a valid filename") end file, err = io.open(options.filename, "a+") if file == nil then error("Error with file output: "..err) end file:close() end function mod.file(level, msg, options) file = io.open(options.filename, "a+") file:write(msg, "\n") file:close() end function mod.syslog(level, msg, options) falco.syslog(level, msg) end function mod.program(level, msg, options) -- XXX Ideally we'd check that the program ran -- successfully. However, the luajit we're using returns true even -- when the shell can't run the program. file = io.popen(options.program, "w") file:write(msg, "\n") file:close() end local function level_of(s) s = string.lower(s) for i,v in ipairs(levels) do if (string.find(string.lower(v), "^"..s)) then return i - 1 -- (syslog levels start at 0, lua indices start at 1) end end error("Invalid severity level: "..s) end function output_event(event, rule, priority, format) local level = level_of(priority) format = "*%evt.time: "..levels[level+1].." "..format formatter = falco.formatter(format) msg = falco.format_event(event, rule, levels[level+1], formatter) for index,o in ipairs(outputs) do o.output(level, msg, o.config) end falco.free_formatter(formatter) end function add_output(output_name, config) if not (type(mod[output_name]) == 'function') then error("rule_loader.add_output(): invalid output_name: "..output_name) end -- outputs can optionally define a validation function so that we don't -- find out at runtime (when an event finally matches a rule!) that the config is invalid if (type(mod[output_name.."_validate"]) == 'function') then mod[output_name.."_validate"](config) end table.insert(outputs, {output = mod[output_name], config=config}) end return mod
Fix output methods that take configurations.
Fix output methods that take configurations. The falco engine changes broke the output methods that take configuration (like the filename for file output, or the program for program output). Fix that by properly passing the options argument to each method's output function.
Lua
apache-2.0
draios/falco,draios/falco,draios/falco,draios/falco,draios/falco,draios/falco,draios/falco,draios/falco
a7ff576f2c7f5a835ca2d2e2de8c3b16b7f8fb44
contrib/statusd/statusd_inetaddr2/statusd_inetaddr2.lua
contrib/statusd/statusd_inetaddr2/statusd_inetaddr2.lua
-- Authors: Guillermo Bonvehí <gbonvehi@gmail.com> -- License: Public domain -- -- statusd_inetaddr2.lua -- show IP address for Notion's statusbar -- Shows assigned IP address for each configured interface. -- Uses `ip addr show` or `ifconfig` to fetch current iface's data -- Configuration: -- `template' string controls how the output will be formated. It may -- contain the following keywords: -- PLACEHOLDER DESCRIPTION EXAMPLE -- ----------- ----------- ------- -- iface interface eth0 -- ipv4 IPv4 address 192.168.1.1 -- ipv6 IPv6 address fe80::208:54ff:fe68:7e2c -- `interfaces' table contains the interfaces to be monitored. -- `separator' is placed between the entries in the output. -- `interval' is the refresh timer (in milliseconds). -- `mode` use `ip` for `ip addr show` or `ifconfig` for `ifconfig` -- This software is in the public domain. -------------------------------------------------------------------------------- local defaults = { template = "[%iface %ipv4 %ipv6]", interfaces = { "eth0", "wlan0" }, separator = " ", interval = 10*1000, mode = "ip", mode_path_check = true, } local settings = table.join(statusd.get_config("inetaddr2"), defaults) local inetaddr2_timer = statusd.create_timer() local mode_path = "" local function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end local function get_tool_output(command) local f = io.popen(command) if not f then return nil end lines = f:read("a") f:close() return lines end local function get_ip_address_using__ifconfig(iface, lines) local r_table = {} local inet4_match = "inet " local inet6_match = "inet6 " local inet4_addr = "none" local inet6_addr = "none" lines = lines or get_tool_output("LC_ALL=C " .. mode_path .. " " .. iface .. " 2>/dev/null") for line in lines:gmatch("([^\n]*)\n?") do if (string.match(line, inet4_match)) then inet4_addr = line:match("inet (%d+%.%d+%.%d+%.%d+)") or "none" elseif (string.match(line, inet6_match)) then inet6_addr = line:match("inet6 ([a-fA-F0-9%:]+) ") or "none" end end r_table["iface"] = iface r_table["ipv4"] = inet4_addr r_table["ipv6"] = inet6_addr return r_table end local function get_ip_address_using__ip_addr(iface, lines) local r_table = {} local inet4_match = "inet " local inet6_match = "inet6 " local inet4_addr = "none" local inet6_addr = "none" lines = lines or get_tool_output("LC_ALL=C " .. mode_path .. " addr show " .. iface .. " 2>/dev/null") for line in lines:gmatch("([^\n]*)\n?") do if (string.match(line, inet4_match)) then inet4_addr = line:match("inet (%d+%.%d+%.%d+%.%d+)") or "none" elseif (string.match(line, inet6_match)) then inet6_addr = line:match("inet6 ([a-fA-F0-9%:]+)/") or "none" end end r_table["iface"] = iface r_table["ipv4"] = inet4_addr r_table["ipv6"] = inet6_addr return r_table end local function get_inetaddr_ifcfg(mode, iface) if mode == "ifconfig" then return get_ip_address_using__ifconfig(iface) elseif mode == "ip" then return get_ip_address_using__ip_addr(iface) end end local function update_inetaddr() local ifaces_info = {} for i=1, #settings.interfaces do local iface = settings.interfaces[i] local parsed_ifcfg = get_inetaddr_ifcfg(settings.mode, iface) if (parsed_ifcfg == nil) then else local s = string.gsub(settings.template, "%%(%w+)", function (arg) if (parsed_ifcfg[arg] ~= nil) then return parsed_ifcfg[arg] end return nil end) ifaces_info[i] = s end end statusd.inform("inetaddr2", table.concat(ifaces_info, settings.separator)) inetaddr2_timer:set(settings.interval, update_inetaddr) end inetaddr2_timer:set(100, update_inetaddr) if settings.mode == "ip" then ip_paths = {"/sbin/ip", "/usr/sbin/ip", "/bin/ip", "/usr/bin/ip"} elseif settings.mode == "ifconfig" then ip_paths = {"/sbin/ifconfig", "/usr/sbin/ifconfig", "/bin/ifconfig", "/usr/bin/ifconfig"} end for i = 1, #ip_paths do if file_exists(ip_paths[i]) then mode_path = ip_paths[i] break end end if (settings.mode_path_check == true) then assert(mode_path ~= "", "Could not find a suitable binary for " .. settings.mode) end statusd_inetaddr2_export = { get_ip_address_using__ifconfig = get_ip_address_using__ifconfig, get_ip_address_using__ip_addr = get_ip_address_using__ip_addr, }
-- Authors: Guillermo Bonvehí <gbonvehi@gmail.com> -- License: Public domain -- -- statusd_inetaddr2.lua -- show IP address for Notion's statusbar -- Shows assigned IP address for each configured interface. -- Uses `ip addr show` or `ifconfig` to fetch current iface's data -- Configuration: -- `template' string controls how the output will be formated. It may -- contain the following keywords: -- PLACEHOLDER DESCRIPTION EXAMPLE -- ----------- ----------- ------- -- iface interface eth0 -- ipv4 IPv4 address 192.168.1.1 -- ipv6 IPv6 address fe80::208:54ff:fe68:7e2c -- `interfaces' table contains the interfaces to be monitored. -- `separator' is placed between the entries in the output. -- `interval' is the refresh timer (in milliseconds). -- `mode` use `ip` for `ip addr show` or `ifconfig` for `ifconfig` -- This software is in the public domain. -------------------------------------------------------------------------------- local defaults = { template = "[%iface %ipv4 %ipv6]", interfaces = { "eth0", "wlan0" }, separator = " ", interval = 10*1000, mode = "ip", mode_path_check = true, } local settings = table.join(statusd.get_config("inetaddr2"), defaults) local inetaddr2_timer = statusd.create_timer() local mode_path = "" local function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end local function get_tool_output(command) local f = io.popen(command) if not f then return nil end lines = f:read("*a") f:close() return lines end local function get_ip_address_using__ifconfig(iface, lines) local r_table = {} local inet4_match = "inet " local inet6_match = "inet6 " local inet4_addr = "none" local inet6_addr = "none" lines = lines or get_tool_output("LC_ALL=C " .. mode_path .. " " .. iface .. " 2>/dev/null") for line in lines:gmatch("([^\n]*)\n?") do if (string.match(line, inet4_match)) then inet4_addr = line:match("inet (%d+%.%d+%.%d+%.%d+)") or "none" elseif (string.match(line, inet6_match)) then inet6_addr = line:match("inet6 ([a-fA-F0-9%:]+) ") or "none" end end r_table["iface"] = iface r_table["ipv4"] = inet4_addr r_table["ipv6"] = inet6_addr return r_table end local function get_ip_address_using__ip_addr(iface, lines) local r_table = {} local inet4_match = "inet " local inet6_match = "inet6 " local inet4_addr = "none" local inet6_addr = "none" lines = lines or get_tool_output("LC_ALL=C " .. mode_path .. " addr show " .. iface .. " 2>/dev/null") for line in lines:gmatch("([^\n]*)\n?") do if (string.match(line, inet4_match)) then inet4_addr = line:match("inet (%d+%.%d+%.%d+%.%d+)") or "none" elseif (string.match(line, inet6_match)) then inet6_addr = line:match("inet6 ([a-fA-F0-9%:]+)/") or "none" end end r_table["iface"] = iface r_table["ipv4"] = inet4_addr r_table["ipv6"] = inet6_addr return r_table end local function get_inetaddr_ifcfg(mode, iface) if mode == "ifconfig" then return get_ip_address_using__ifconfig(iface) elseif mode == "ip" then return get_ip_address_using__ip_addr(iface) end end local function update_inetaddr() local ifaces_info = {} for i=1, #settings.interfaces do local iface = settings.interfaces[i] local parsed_ifcfg = get_inetaddr_ifcfg(settings.mode, iface) if (parsed_ifcfg == nil) then else local s = string.gsub(settings.template, "%%(%w+)", function (arg) if (parsed_ifcfg[arg] ~= nil) then return parsed_ifcfg[arg] end return nil end) ifaces_info[i] = s end end statusd.inform("inetaddr2", table.concat(ifaces_info, settings.separator)) inetaddr2_timer:set(settings.interval, update_inetaddr) end if settings.mode == "ip" then ip_paths = {"/sbin/ip", "/usr/sbin/ip", "/bin/ip", "/usr/bin/ip"} elseif settings.mode == "ifconfig" then ip_paths = {"/sbin/ifconfig", "/usr/sbin/ifconfig", "/bin/ifconfig", "/usr/bin/ifconfig"} end for i = 1, #ip_paths do if file_exists(ip_paths[i]) then mode_path = ip_paths[i] break end end if (settings.mode_path_check == true) then assert(mode_path ~= "", "Could not find a suitable binary for " .. settings.mode) end inetaddr2_timer:set(100, update_inetaddr) statusd_inetaddr2_export = { get_ip_address_using__ifconfig = get_ip_address_using__ifconfig, get_ip_address_using__ip_addr = get_ip_address_using__ip_addr, }
Fixed reading using get_output_tool
Fixed reading using get_output_tool I guess I tested an old version before uploading latest change, sorry about that.
Lua
lgpl-2.1
raboof/notion,knixeur/notion,raboof/notion,raboof/notion,knixeur/notion,knixeur/notion,knixeur/notion,knixeur/notion,raboof/notion
1e2f690aa2b8f265c1aab5a6d4acd6a2593f52c7
mod_auth_ldap/mod_auth_ldap.lua
mod_auth_ldap/mod_auth_ldap.lua
-- mod_auth_ldap local new_sasl = require "util.sasl".new; local lualdap = require "lualdap"; local function ldap_filter_escape(s) return (s:gsub("[*()\\%z]", function(c) return ("\\%02x"):format(c:byte()) end)); end -- Config options local ldap_server = module:get_option_string("ldap_server", "localhost"); local ldap_rootdn = module:get_option_string("ldap_rootdn", ""); local ldap_password = module:get_option_string("ldap_password", ""); local ldap_tls = module:get_option_boolean("ldap_tls"); local ldap_scope = module:get_option_string("ldap_scope", "onelevel"); local ldap_filter = module:get_option_string("ldap_filter", "(uid=$user)"):gsub("%%s", "$user", 1); local ldap_base = assert(module:get_option_string("ldap_base"), "ldap_base is a required option for ldap"); local ldap_mode = module:get_option_string("ldap_mode", "bind"); local host = ldap_filter_escape(module:get_option_string("realm", module.host)); -- Initiate connection local ld = nil; module.unload = function() if ld then pcall(ld, ld.close); end end function ldap_search_once(args) if ld == nil then local err; ld, err = lualdap.open_simple(ldap_server, ldap_rootdn, ldap_password, ldap_tls); if not ld then return nil, err, "reconnect"; end end local success, iterator, invariant, initial = pcall(ld.search, ld, args); if not success then ld = nil; return nil, iterator, "search"; end local success, dn, attr = pcall(iterator, invariant, initial); if not success then ld = nil; return success, dn, "iter"; end return dn, attr, "return"; end function ldap_search(args, retry_count) local dn, attr, where; for i=1,1+retry_count do dn, attr, where = ldap_search_once(args); if dn or not(attr) then break; end -- nothing or something found module:log("warn", "LDAP: %s %s (in %s)", tostring(dn), tostring(attr), where); -- otherwise retry end if not dn and attr then module:log("error", "LDAP: %s", tostring(attr)); end return dn, attr; end local function get_user(username) module:log("debug", "get_user(%q)", username); for dn, attr in ldap_search({ base = ldap_base; scope = ldap_scope; sizelimit = 1; filter = ldap_filter:gsub("%$(%a+)", { user = ldap_filter_escape(username); host = host; }); }, 3) do return dn, attr; end end local provider = {}; function provider.create_user(username, password) return nil, "Account creation not available with LDAP."; end function provider.user_exists(username) return not not get_user(username); end function provider.set_password(username, password) local dn, attr = get_user(username); if not dn then return nil, attr end if attr.userPassword == password then return true end return ld:modify(dn, { '=', userPassword = password })(); end if ldap_mode == "getpasswd" then function provider.get_password(username) local dn, attr = get_user(username); if dn and attr then return attr.userPassword; end end function provider.test_password(username, password) return provider.get_password(username) == password; end function provider.get_sasl_handler() return new_sasl(module.host, { plain = function(sasl, username) local password = provider.get_password(username); if not password then return "", nil; end return password, true; end }); end elseif ldap_mode == "bind" then local function test_password(userdn, password) return not not lualdap.open_simple(ldap_server, userdn, password, ldap_tls); end function provider.test_password(username, password) local dn = get_user(username); if not dn then return end return test_password(dn, password) end function provider.get_sasl_handler() return new_sasl(module.host, { plain_test = function(sasl, username, password) return provider.test_password(username, password), true; end }); end else module:log("error", "Unsupported ldap_mode %s", tostring(ldap_mode)); end module:provides("auth", provider);
-- mod_auth_ldap local new_sasl = require "util.sasl".new; local lualdap = require "lualdap"; local function ldap_filter_escape(s) return (s:gsub("[*()\\%z]", function(c) return ("\\%02x"):format(c:byte()) end)); end -- Config options local ldap_server = module:get_option_string("ldap_server", "localhost"); local ldap_rootdn = module:get_option_string("ldap_rootdn", ""); local ldap_password = module:get_option_string("ldap_password", ""); local ldap_tls = module:get_option_boolean("ldap_tls"); local ldap_scope = module:get_option_string("ldap_scope", "onelevel"); local ldap_filter = module:get_option_string("ldap_filter", "(uid=$user)"):gsub("%%s", "$user", 1); local ldap_base = assert(module:get_option_string("ldap_base"), "ldap_base is a required option for ldap"); local ldap_mode = module:get_option_string("ldap_mode", "bind"); local host = ldap_filter_escape(module:get_option_string("realm", module.host)); -- Initiate connection local ld = nil; module.unload = function() if ld then pcall(ld, ld.close); end end function ldap_do_once(method, ...) if ld == nil then local err; ld, err = lualdap.open_simple(ldap_server, ldap_rootdn, ldap_password, ldap_tls); if not ld then return nil, err, "reconnect"; end end local success, iterator, invariant, initial = pcall(ld[method], ld, ...); if not success then ld = nil; return nil, iterator, "search"; end local success, dn, attr = pcall(iterator, invariant, initial); if not success then ld = nil; return success, dn, "iter"; end return dn, attr, "return"; end function ldap_do(method, retry_count, ...) local dn, attr, where; for i=1,1+retry_count do dn, attr, where = ldap_do_once(method, ...); if dn or not(attr) then break; end -- nothing or something found module:log("warn", "LDAP: %s %s (in %s)", tostring(dn), tostring(attr), where); -- otherwise retry end if not dn and attr then module:log("error", "LDAP: %s", tostring(attr)); end return dn, attr; end local function get_user(username) module:log("debug", "get_user(%q)", username); return ldap_do("search", 2, { base = ldap_base; scope = ldap_scope; sizelimit = 1; filter = ldap_filter:gsub("%$(%a+)", { user = ldap_filter_escape(username); host = host; }); }); end local provider = {}; function provider.create_user(username, password) return nil, "Account creation not available with LDAP."; end function provider.user_exists(username) return not not get_user(username); end function provider.set_password(username, password) local dn, attr = get_user(username); if not dn then return nil, attr end if attr.userPassword == password then return true end return ldap_do("modify", 2, dn, { '=', userPassword = password }); end if ldap_mode == "getpasswd" then function provider.get_password(username) local dn, attr = get_user(username); if dn and attr then return attr.userPassword; end end function provider.test_password(username, password) return provider.get_password(username) == password; end function provider.get_sasl_handler() return new_sasl(module.host, { plain = function(sasl, username) local password = provider.get_password(username); if not password then return "", nil; end return password, true; end }); end elseif ldap_mode == "bind" then local function test_password(userdn, password) return not not lualdap.open_simple(ldap_server, userdn, password, ldap_tls); end function provider.test_password(username, password) local dn = get_user(username); if not dn then return end return test_password(dn, password) end function provider.get_sasl_handler() return new_sasl(module.host, { plain_test = function(sasl, username, password) return provider.test_password(username, password), true; end }); end else module:log("error", "Unsupported ldap_mode %s", tostring(ldap_mode)); end module:provides("auth", provider);
mod_auth_ldap: Fix use of ldap_search, and generalize it to support password modification as well.
mod_auth_ldap: Fix use of ldap_search, and generalize it to support password modification as well.
Lua
mit
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
2a81d75ae02c2c5ad8b52dc9b6f57b749aac88e2
hostinfo/init.lua
hostinfo/init.lua
--[[ Copyright 2014 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 Object = require('core').Object local JSON = require('json') local fs = require('fs') local misc = require('/base/util/misc') local os = require('os') local asserts = require('bourbon').asserts local classes = require('./all') local function create_map() local map = {} for x, klass in pairs(classes) do asserts.ok(klass.getType and klass.getType(), "HostInfo getType() undefined or returning nil: " .. tostring(x)) map[klass.getType()] = klass end return map end local HOST_INFO_MAP = create_map() --[[ Factory ]]-- local function create(infoType) local klass = HOST_INFO_MAP[infoType] if klass then return klass:new() end return NilInfo:new() end -- Dump all the info objects to a file local function debugInfo(fileName, callback) local data = '' for k, v in pairs(HOST_INFO_MAP) do local info = create(v) local obj = info:serialize().metrics data = data .. '-- ' .. v .. '.' .. os.type() .. ' --\n\n' data = data .. misc.toString(obj) data = data .. '\n' end fs.writeFile(fileName, data, callback) end --[[ Exports ]]-- local exports = {} exports.create = create exports.debugInfo = debugInfo exports.classes = classes return exports
--[[ Copyright 2014 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 Object = require('core').Object local JSON = require('json') local fs = require('fs') local misc = require('/base/util/misc') local os = require('os') local asserts = require('bourbon').asserts local HostInfo = require('./base').HostInfo local classes = require('./all') local function create_map() local map = {} for x, klass in pairs(classes) do asserts.ok(klass.getType and klass.getType(), "HostInfo getType() undefined or returning nil: " .. tostring(x)) map[klass.getType()] = klass end return map end local HOST_INFO_MAP = create_map() --[[ NilInfo ]]-- local NilInfo = HostInfo:extend() --[[ Factory ]]-- local function create(infoType) local klass = HOST_INFO_MAP[infoType] if klass then return klass:new() end return NilInfo:new() end -- Dump all the info objects to a file local function debugInfo(fileName, callback) local data = '' for k, v in pairs(HOST_INFO_MAP) do local info = create(v) local obj = info:serialize().metrics data = data .. '-- ' .. v .. '.' .. os.type() .. ' --\n\n' data = data .. misc.toString(obj) data = data .. '\n' end fs.writeFile(fileName, data, callback) end --[[ Exports ]]-- local exports = {} exports.create = create exports.debugInfo = debugInfo exports.classes = classes return exports
fix: NilInfo was missing from the host_info refactor
fix: NilInfo was missing from the host_info refactor
Lua
apache-2.0
AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent
4a7a63dd8b7b35f8a52b7fd15f4be91542cd5e69
src/plugins/finalcutpro/browser/insertvertical.lua
src/plugins/finalcutpro/browser/insertvertical.lua
--- === plugins.finalcutpro.browser.insertvertical === --- --- Insert Clips Vertically from Browser to Timeline. local require = require local log = require "hs.logger".new "addnote" local fcp = require "cp.apple.finalcutpro" local dialog = require "cp.dialog" local i18n = require "cp.i18n" local go = require "cp.rx.go" local Do = go.Do local If = go.If local Throw = go.Throw local Given = go.Given local List = go.List local Retry = go.Retry local plugin = { id = "finalcutpro.browser.insertvertical", group = "finalcutpro", dependencies = { ["finalcutpro.commands"] = "fcpxCmds", } } function plugin.init(deps) local timeline = fcp:timeline() local libraries = fcp:browser():libraries() deps.fcpxCmds :add("insertClipsVerticallyFromBrowserToTimeline") :whenActivated( Do(libraries:doShow()) :Then( If(function() local clips = libraries:selectedClips() return clips and #clips >= 2 end):Then( Given(List(function() return libraries:selectedClips() end)) :Then(function(child) log.df("Selecting clip: %s", child) libraries:selectClip(child) return true end) :Then(function() log.df("Connecting to primary storyline") return true end) :Then(fcp:doSelectMenu({"Edit", "Connect to Primary Storyline"})) :Then(function() log.df("Focussing on timeline.") return true end) :Then(timeline:doFocus()) :Then( Retry(function() if timeline.isFocused() then return true else return Throw("Failed to make the timeline focused.") end end):UpTo(10):DelayedBy(100) ) :Then(function() log.df("Go to previous edit.") return true end) :Then(fcp:doSelectMenu({"Mark", "Previous", "Edit"})) :Then(function() log.df("End of block") return true end) ):Otherwise( Throw("No clips selected in the Browser.") ) ) :Catch(function(message) log.ef("Error in insertClipsVerticallyFromBrowserToTimeline: %s", message) dialog.displayMessage(message) end) ) :titled(i18n("insertClipsVerticallyFromBrowserToTimeline")) end return plugin
--- === plugins.finalcutpro.browser.insertvertical === --- --- Insert Clips Vertically from Browser to Timeline. local require = require local log = require "hs.logger".new "addnote" local fcp = require "cp.apple.finalcutpro" local dialog = require "cp.dialog" local i18n = require "cp.i18n" local go = require "cp.rx.go" local displayMessage = dialog.displayMessage local Do = go.Do local If = go.If local Throw = go.Throw local Given = go.Given local List = go.List local Retry = go.Retry local plugin = { id = "finalcutpro.browser.insertvertical", group = "finalcutpro", dependencies = { ["finalcutpro.commands"] = "fcpxCmds", } } function plugin.init(deps) local timeline = fcp:timeline() local libraries = fcp:browser():libraries() deps.fcpxCmds :add("insertClipsVerticallyFromBrowserToTimeline") :whenActivated( Do(libraries:doShow()) :Then( If(function() local clips = libraries:selectedClips() return clips and #clips >= 2 end):Then( Given(List(function() return libraries:selectedClips() end)) :Then(function(child) return Do(function() if not libraries:selectClip(child) then return Throw("Failed to select clip.") end if not fcp:selectMenu({"Edit", "Connect to Primary Storyline"}) then return Throw("Failed to Connect to Primary Storyline.") end if not fcp:selectMenu({"Window", "Go To", "Timeline"}) then return Throw("Failed to go to timeline.") end if not fcp:selectMenu({"Mark", "Previous", "Edit"}) then return Throw("Failed to go to previous edit.") end return true end) end) ):Otherwise( Throw("No clips selected in the Browser.") ) ) :Catch(function(message) log.ef("Error in insertClipsVerticallyFromBrowserToTimeline: %s", message) displayMessage(message) end) ) :titled(i18n("insertClipsVerticallyFromBrowserToTimeline")) end return plugin
#1671
#1671 - Fixed bugs in “Insert Clips Vertically from Browser to Timeline”. Closes #1671
Lua
mit
fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost
ccab7c1176f6bf743818f0794a82cb138fe8678d
src/lua-factory/sources/grl-radiofrance.lua
src/lua-factory/sources/grl-radiofrance.lua
--[[ * Copyright (C) 2014 Bastien Nocera * * Contact: Bastien Nocera <hadess@hadess.net> * * This library 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; version 2.1 of * the License, or (at your option) any later version. * * This library 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] RADIOFRANCE_URL = 'http://app2.radiofrance.fr/rfdirect/config/Radio.js' FRANCEBLEU_URL = 'http://app2.radiofrance.fr/rfdirect/config/FranceBleu.js' --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-radiofrance-lua", name = "Radio France", description = "A source for browsing Radio France radio stations", supported_keys = { "id", "thumbnail", "title", "url", "mime-type" }, icon = 'http://www.radiofrance.fr/sites/all/themes/custom/rftheme/logo.png', supported_media = 'audio', tags = { 'radio', 'country:fr' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) if grl.get_options("skip") > 0 then grl.callback() else grl.fetch(RADIOFRANCE_URL, "radiofrance_fetch_cb") end end ------------------------ -- Callback functions -- ------------------------ -- return all the media found function radiofrance_fetch_cb(playlist) if parse_playlist(playlist, false) then grl.fetch(FRANCEBLEU_URL, "francebleu_fetch_cb") end end function francebleu_fetch_cb(playlist) parse_playlist(playlist, true) end ------------- -- Helpers -- ------------- function parse_playlist(playlist, francebleu) local match1_prefix, match2 if francebleu then match1_prefix = '_frequence' match2 = '{(.-logo_region.-)}' else match1_prefix = '_radio' match2 = '{(.-#rfdirect.-)}' end if not playlist then grl.callback() return false end local items = playlist:match('Flux = {.-' .. match1_prefix .. ' : {(.*)}.-}') if not items then grl.callback() return false end for item in items:gmatch(match2) do local media = create_media(item, francebleu) if media then grl.callback(media, -1) end end if francebleu then grl.callback() end return true end function get_thumbnail(id) local images = {} images['FranceInter'] = 'http://www.franceinter.fr/sites/all/themes/franceinter/logo.png' images['FranceInfo'] = 'http://www.franceinfo.fr/sites/all/themes/franceinfo/logo.png' images['FranceCulture'] = 'http://www.franceculture.fr/sites/all/themes/franceculture/images/logo.png' images['FranceMusique'] = 'http://www.francemusique.fr/sites/all/themes/custom/france_musique/logo.png' images['Fip'] = 'http://www.fipradio.fr/sites/all/themes/fip2/images/logo_121x121.png' images['LeMouv'] = 'http://www.lemouv.fr/sites/all/themes/mouv/images/logo_119x119.png' images['FranceBleu'] = 'http://www.francebleu.fr/sites/all/themes/francebleu/logo.png' return images[id] end function create_media(item, francebleu) local media = {} if francebleu then media.url = item:match("mp3_direct : '(http://.-)'") else media.url = item:match("hifi :'(.-)'") end if not media.url or media.url == '' then return nil end media.type = "audio" media.mime_type = "audio/mpeg" media.id = item:match("id : '(.-)',") media.title = item:match("nom : '(.-)',") media.title = media.title:gsub("\\'", "'") if francebleu then media.thumbnail = get_thumbnail('FranceBleu') else media.thumbnail = get_thumbnail(media.id) end return media end
--[[ * Copyright (C) 2014 Bastien Nocera * * Contact: Bastien Nocera <hadess@hadess.net> * * This library 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; version 2.1 of * the License, or (at your option) any later version. * * This library 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] RADIOFRANCE_URL = 'http://app2.radiofrance.fr/rfdirect/config/Radio.js' FRANCEBLEU_URL = 'http://app2.radiofrance.fr/rfdirect/config/FranceBleu.js' local stations = { 'franceinter', 'franceinfo', 'franceculture', 'francemusique', 'fipradio', 'lemouv' } --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-radiofrance-lua", name = "Radio France", description = "A source for browsing Radio France radio stations", supported_keys = { "id", "thumbnail", "title", "url", "mime-type" }, icon = 'http://www.radiofrance.fr/sites/all/themes/custom/rftheme/logo.png', supported_media = 'audio', tags = { 'radio', 'country:fr' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) if grl.get_options("skip") > 0 then grl.callback() else local urls = {} for index, item in pairs(stations) do local url = 'http://www.' .. item .. '.fr/api/now&full=true' table.insert(urls, url) end grl.fetch(urls, "radiofrance_now_fetch_cb") end end ------------------------ -- Callback functions -- ------------------------ -- return all the media found function radiofrance_now_fetch_cb(results) for index, result in pairs(results) do local json = {} json = grl.lua.json.string_to_table(result) if not json or json.stat == "fail" or not json.stations then local url = 'http://www.' .. stations[index] .. '.fr/api/now&full=true' grl.warning ('Could not fetch ' .. url .. ' failed') grl.callback() return end local media = create_media(stations[index], json.stations[1]) grl.callback(media, -1) end grl.callback() end ------------- -- Helpers -- ------------- function get_thumbnail(id) local images = {} images['franceinter'] = 'http://www.franceinter.fr/sites/all/themes/franceinter/logo.png' images['franceinfo'] = 'http://www.franceinfo.fr/sites/all/themes/custom/france_info/logo.png' images['franceculture'] = 'http://www.franceculture.fr/sites/all/themes/franceculture/images/logo.png' images['francemusique'] = 'http://www.francemusique.fr/sites/all/themes/custom/france_musique/logo.png' images['fipradio'] = 'http://www.fipradio.fr/sites/all/themes/custom/fip/logo.png' images['lemouv'] = 'http://www.lemouv.fr/sites/all/themes/mouv/images/logo_119x119.png' return images[id] end function get_title(id) local names = {} names['franceinter'] = 'France Inter' names['franceinfo'] = 'France Info' names['franceculture'] = 'France Culture' names['francemusique'] = 'France Musique' names['fipradio'] = 'Fip Radio' names['lemouv'] = "Le Mouv'" return names[id] end function create_media(id, station) local media = {} media.type = "audio" media.mime_type = "audio/mpeg" media.id = id if media.id == 'fipradio' then media.id = 'fip' end media.url = 'http://mp3lg.tdf-cdn.com/' .. media.id .. '/all/' .. media.id .. 'hautdebit.mp3' media.title = get_title(id) media.thumbnail = get_thumbnail(id) -- FIXME Add metadata about the currently playing tracks return media end
radiofrance: Fix for backend changes
radiofrance: Fix for backend changes The old Radio France APIs stopped working when they deployed a new iOS application, so move over to the new URLs. We're losing France Bleu support for now. https://bugzilla.gnome.org/show_bug.cgi?id=734234
Lua
lgpl-2.1
grilofw/grilo-plugins,jasuarez/grilo-plugins,GNOME/grilo-plugins,MikePetullo/grilo-plugins,GNOME/grilo-plugins,MathieuDuponchelle/grilo-plugins,jasuarez/grilo-plugins,grilofw/grilo-plugins,MikePetullo/grilo-plugins,MathieuDuponchelle/grilo-plugins,MikePetullo/grilo-plugins,MathieuDuponchelle/grilo-plugins,MathieuDuponchelle/grilo-plugins
52283b80d349dc404ce9b3cff2bf58407bd733d1
plugins/mod_http.lua
plugins/mod_http.lua
-- Prosody IM -- Copyright (C) 2008-2012 Matthew Wild -- Copyright (C) 2008-2012 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- module:set_global(); module:depends("http_errors"); local portmanager = require "core.portmanager"; local moduleapi = require "core.moduleapi"; local url_parse = require "socket.url".parse; local url_build = require "socket.url".build; local server = require "net.http.server"; server.set_default_host(module:get_option_string("http_default_host")); local function normalize_path(path) if path:sub(-1,-1) == "/" then path = path:sub(1, -2); end if path:sub(1,1) ~= "/" then path = "/"..path; end return path; end local function get_http_event(host, app_path, key) local method, path = key:match("^(%S+)%s+(.+)$"); if not method then -- No path specified, default to "" (base path) method, path = key, ""; end if method:sub(1,1) == "/" then return nil; end if app_path == "/" and path:sub(1,1) == "/" then app_path = ""; end return method:upper().." "..host..app_path..path; end local function get_base_path(host_module, app_name, default_app_path) return (normalize_path(host_module:get_option("http_paths", {})[app_name] -- Host or module:get_option("http_paths", {})[app_name] -- Global or default_app_path)) -- Default :gsub("%$(%w+)", { host = host_module.host }); end local ports_by_scheme = { http = 80, https = 443, }; -- Helper to deduce a module's external URL function moduleapi.http_url(module, app_name, default_path) app_name = app_name or (module.name:gsub("^http_", "")); local external_url = url_parse(module:get_option_string("http_external_url")) or {}; local services = portmanager.get_active_services(); local http_services = services:get("https") or services:get("http") or {}; for interface, ports in pairs(http_services) do for port, services in pairs(ports) do local url = { scheme = (external_url.scheme or services[1].service.name); host = (external_url.host or module:get_option_string("http_host", module.host)); port = tonumber(external_url.port) or port or 80; path = normalize_path(external_url.path or "/").. (get_base_path(module, app_name, default_path or "/"..app_name):sub(2)); } if ports_by_scheme[url.scheme] == url.port then url.port = nil end return url_build(url); end end end function module.add_host(module) local host = module:get_option_string("http_host", module.host); local apps = {}; module.environment.apps = apps; local function http_app_added(event) local app_name = event.item.name; local default_app_path = event.item.default_path or "/"..app_name; local app_path = get_base_path(module, app_name, default_app_path); if not app_name then -- TODO: Link to docs module:log("error", "HTTP app has no 'name', add one or use module:provides('http', app)"); return; end apps[app_name] = apps[app_name] or {}; local app_handlers = apps[app_name]; for key, handler in pairs(event.item.route or {}) do local event_name = get_http_event(host, app_path, key); if event_name then if type(handler) ~= "function" then local data = handler; handler = function () return data; end elseif event_name:sub(-2, -1) == "/*" then local base_path_len = #event_name:match("/.+$"); local _handler = handler; handler = function (event) local path = event.request.path:sub(base_path_len); return _handler(event, path); end; end if not app_handlers[event_name] then app_handlers[event_name] = handler; module:hook_object_event(server, event_name, handler); else module:log("warn", "App %s added handler twice for '%s', ignoring", app_name, event_name); end else module:log("error", "Invalid route in %s, %q. See http://prosody.im/doc/developers/http#routes", app_name, key); end end end local function http_app_removed(event) local app_handlers = apps[event.item.name]; apps[event.item.name] = nil; for event, handler in pairs(app_handlers) do module:unhook_object_event(server, event, handler); end end module:handle_items("http-provider", http_app_added, http_app_removed); server.add_host(host); function module.unload() server.remove_host(host); end end module:provides("net", { name = "http"; listener = server.listener; default_port = 5280; multiplex = { pattern = "^[A-Z]"; }; }); module:provides("net", { name = "https"; listener = server.listener; default_port = 5281; encryption = "ssl"; ssl_config = { verify = "none" }; multiplex = { pattern = "^[A-Z]"; }; });
-- Prosody IM -- Copyright (C) 2008-2012 Matthew Wild -- Copyright (C) 2008-2012 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- module:set_global(); module:depends("http_errors"); local portmanager = require "core.portmanager"; local moduleapi = require "core.moduleapi"; local url_parse = require "socket.url".parse; local url_build = require "socket.url".build; local server = require "net.http.server"; server.set_default_host(module:get_option_string("http_default_host")); local function normalize_path(path) if path:sub(-1,-1) == "/" then path = path:sub(1, -2); end if path:sub(1,1) ~= "/" then path = "/"..path; end return path; end local function get_http_event(host, app_path, key) local method, path = key:match("^(%S+)%s+(.+)$"); if not method then -- No path specified, default to "" (base path) method, path = key, ""; end if method:sub(1,1) == "/" then return nil; end if app_path == "/" and path:sub(1,1) == "/" then app_path = ""; end return method:upper().." "..host..app_path..path; end local function get_base_path(host_module, app_name, default_app_path) return (normalize_path(host_module:get_option("http_paths", {})[app_name] -- Host or module:get_option("http_paths", {})[app_name] -- Global or default_app_path)) -- Default :gsub("%$(%w+)", { host = host_module.host }); end local ports_by_scheme = { http = 80, https = 443, }; -- Helper to deduce a module's external URL function moduleapi.http_url(module, app_name, default_path) app_name = app_name or (module.name:gsub("^http_", "")); local external_url = url_parse(module:get_option_string("http_external_url")) or {}; if external_url.scheme and external_url.port == nil then external_url.port = ports_by_scheme[external_url.scheme]; end local services = portmanager.get_active_services(); local http_services = services:get("https") or services:get("http") or {}; for interface, ports in pairs(http_services) do for port, services in pairs(ports) do local url = { scheme = (external_url.scheme or services[1].service.name); host = (external_url.host or module:get_option_string("http_host", module.host)); port = tonumber(external_url.port) or port or 80; path = normalize_path(external_url.path or "/").. (get_base_path(module, app_name, default_path or "/"..app_name):sub(2)); } if ports_by_scheme[url.scheme] == url.port then url.port = nil end return url_build(url); end end end function module.add_host(module) local host = module:get_option_string("http_host", module.host); local apps = {}; module.environment.apps = apps; local function http_app_added(event) local app_name = event.item.name; local default_app_path = event.item.default_path or "/"..app_name; local app_path = get_base_path(module, app_name, default_app_path); if not app_name then -- TODO: Link to docs module:log("error", "HTTP app has no 'name', add one or use module:provides('http', app)"); return; end apps[app_name] = apps[app_name] or {}; local app_handlers = apps[app_name]; for key, handler in pairs(event.item.route or {}) do local event_name = get_http_event(host, app_path, key); if event_name then if type(handler) ~= "function" then local data = handler; handler = function () return data; end elseif event_name:sub(-2, -1) == "/*" then local base_path_len = #event_name:match("/.+$"); local _handler = handler; handler = function (event) local path = event.request.path:sub(base_path_len); return _handler(event, path); end; end if not app_handlers[event_name] then app_handlers[event_name] = handler; module:hook_object_event(server, event_name, handler); else module:log("warn", "App %s added handler twice for '%s', ignoring", app_name, event_name); end else module:log("error", "Invalid route in %s, %q. See http://prosody.im/doc/developers/http#routes", app_name, key); end end end local function http_app_removed(event) local app_handlers = apps[event.item.name]; apps[event.item.name] = nil; for event, handler in pairs(app_handlers) do module:unhook_object_event(server, event, handler); end end module:handle_items("http-provider", http_app_added, http_app_removed); server.add_host(host); function module.unload() server.remove_host(host); end end module:provides("net", { name = "http"; listener = server.listener; default_port = 5280; multiplex = { pattern = "^[A-Z]"; }; }); module:provides("net", { name = "https"; listener = server.listener; default_port = 5281; encryption = "ssl"; ssl_config = { verify = "none" }; multiplex = { pattern = "^[A-Z]"; }; });
mod_http: Fix http_external_url setting without an explicit port
mod_http: Fix http_external_url setting without an explicit port
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
9c33bbb697f16833c184a687d255144484e73b91
lib/table.lua
lib/table.lua
do -- table.show, table.print --[[ Author: Julio Manuel Fernandez-Diaz Date: January 12, 2007 (For Lua 5.1) Modified slightly by RiciLake to avoid the unnecessary table traversal in tablecount() Formats tables with cycles recursively to any depth. The output is returned as a string. References to other tables are shown as values. Self references are indicated. The string returned is "Lua code", which can be procesed (in the case in which indent is composed by spaces or "--"). Userdata and function keys and values are shown as strings, which logically are exactly not equivalent to the original code. This routine can serve for pretty formating tables with proper indentations, apart from printing them: print(table.show(t, "t")) -- a typical use Heavily based on "Saving tables with cycles", PIL2, p. 113. Arguments: t is the table. name is the name of the table (optional) indent is a first indentation (optional). --]] function table.show(t, name, indent) local cart -- a container local autoref -- for self references --[[ counts the number of elements in a table local function tablecount(t) local n = 0 for _, _ in pairs(t) do n = n+1 end return n end ]] -- (RiciLake) returns true if the table is empty local function isemptytable(t) return next(t) == nil end local function basicSerialize (o) local so = tostring(o) if type(o) == "function" then local info = debug.getinfo(o, "S") -- info.name is nil because o is not a calling level if info.what == "C" then return string.format("%q", so .. ", C function") else -- the information is defined through lines return string.format("%q", so .. ", defined in (" .. info.linedefined .. "-" .. info.lastlinedefined .. ")" .. info.source) end elseif type(o) == "number" or type(o) == "boolean" then return so else return string.format("%q", so) end end local function addtocart (value, name, indent, saved, field) indent = indent or "" saved = saved or {} field = field or name cart = cart .. indent .. field if type(value) ~= "table" then cart = cart .. " = " .. basicSerialize(value) .. ";\n" else if saved[value] then cart = cart .. " = {}; -- " .. saved[value] .. " (self reference)\n" autoref = autoref .. name .. " = " .. saved[value] .. ";\n" else saved[value] = name --if tablecount(value) == 0 then if isemptytable(value) then cart = cart .. " = {};\n" else cart = cart .. " = {\n" for k, v in pairs(value) do k = basicSerialize(k) local fname = string.format("%s[%s]", name, k) field = string.format("[%s]", k) -- three spaces between levels addtocart(v, fname, indent .. " ", saved, field) end cart = cart .. indent .. "};\n" end end end end name = name or "__unnamed__" if type(t) ~= "table" then return name .. " = " .. basicSerialize(t) end cart, autoref = "", "" addtocart(t, name, indent) return cart .. autoref end function table.print(tbl, name, indent) print(table.show(tbl, name, indent)) end end
do -- table.show, table.print --[[ Author: Julio Manuel Fernandez-Diaz Date: January 12, 2007 (For Lua 5.1) Modified slightly by RiciLake to avoid the unnecessary table traversal in tablecount() Formats tables with cycles recursively to any depth. The output is returned as a string. References to other tables are shown as values. Self references are indicated. The string returned is "Lua code", which can be procesed (in the case in which indent is composed by spaces or "--"). Userdata and function keys and values are shown as strings, which logically are exactly not equivalent to the original code. This routine can serve for pretty formating tables with proper indentations, apart from printing them: print(table.show(t, "t")) -- a typical use Heavily based on "Saving tables with cycles", PIL2, p. 113. Arguments: t is the table. name is the name of the table (optional) indent is a first indentation (optional). --]] function table.show(t, name, indent) local cart -- a container local autoref -- for self references --[[ counts the number of elements in a table local function tablecount(t) local n = 0 for _, _ in pairs(t) do n = n+1 end return n end ]] -- (RiciLake) returns true if the table is empty local function isemptytable(t) return next(t) == nil end local function basicSerialize (o) if type(o) == "function" then local so = tostring(o) local info = debug.getinfo(o, "S") -- info.name is nil because o is not a calling level if info.what == "C" then return string.format("%q", so .. ", C function") else -- the information is defined through lines return string.format("%q", so .. ", defined in (" .. info.linedefined .. "-" .. info.lastlinedefined .. ")" .. info.source) end elseif type(o) == "number" or type(o) == "boolean" then return tostring(o) elseif type(o) == "userdata" then local suc, ret = pcall(tostring, o) if suc then return ret else return '"userdata"' end else return string.format("%q", tostring(o)) end end local function addtocart (value, name, indent, saved, field) indent = indent or "" saved = saved or {} field = field or name cart = cart .. indent .. field if type(value) ~= "table" then cart = cart .. " = " .. basicSerialize(value) .. ";\n" else if saved[value] then cart = cart .. " = {}; -- " .. saved[value] .. " (self reference)\n" autoref = autoref .. name .. " = " .. saved[value] .. ";\n" else saved[value] = name --if tablecount(value) == 0 then if isemptytable(value) then cart = cart .. " = {};\n" else cart = cart .. " = {\n" for k, v in pairs(value) do k = basicSerialize(k) local fname = string.format("%s[%s]", name, k) field = string.format("[%s]", k) -- three spaces between levels addtocart(v, fname, indent .. " ", saved, field) end cart = cart .. indent .. "};\n" end end end end name = name or "__unnamed__" if type(t) ~= "table" then return name .. " = " .. basicSerialize(t) end cart, autoref = "", "" addtocart(t, name, indent) return cart .. autoref end function table.print(tbl, name, indent) print(table.show(tbl, name, indent)) end end
Fixed table.show/table.print with userdata
Fixed table.show/table.print with userdata
Lua
mit
Quit/jelly
6cb0220ba03ea1494fdde006d8c7deaf862e7544
MMOCoreORB/bin/scripts/screenplays/themepark/imperial/emperors_retreat.lua
MMOCoreORB/bin/scripts/screenplays/themepark/imperial/emperors_retreat.lua
local ObjectManager = require("managers.object.object_manager") EmperorsRetreatScreenPlay = ScreenPlay:new { numberOfActs = 1, screenplayName = "EmperorsRetreatScreenPlay", } registerScreenPlay("EmperorsRetreatScreenPlay", true) function EmperorsRetreatScreenPlay:start() if (isZoneEnabled("naboo")) then self:spawnMobiles() self:spawnSceneObjects() end end function EmperorsRetreatScreenPlay:spawnSceneObjects() local elevatorUp = spawnSceneObject("naboo", "object/tangible/terminal/terminal_elevator_up.iff", 13, 1, -36, 1418877, 1, 0, 0, 0) spawnSceneObject("naboo", "object/tangible/terminal/terminal_elevator_down.iff", 13, 20.5, -36, 1418877, 1, 0, 0, 0) if (elevatorUp ~= nil) then local terminal = LuaSceneObject(elevatorUp) terminal:setObjectMenuComponent("EmperorElevatorMenuComponent") end end EmperorElevatorMenuComponent = {} function EmperorElevatorMenuComponent:fillObjectMenuResponse(pSceneObject, pMenuResponse, pPlayer) local menuResponse = LuaObjectMenuResponse(pMenuResponse) menuResponse:addRadialMenuItem(198, 3, "@elevator_text:up") end function EmperorElevatorMenuComponent:handleObjectMenuSelect(pSceneObject, pPlayer, selectedID) local creature = LuaCreatureObject(pPlayer) if (selectedID ~= 198) or (not creature:hasScreenPlayState("imperial_theme_park", 32)) then creature:sendSystemMessage("@theme_park_imperial/warning:emperor") return end local obj = LuaSceneObject(pSceneObject) if (creature:getParent() ~= obj:getParent()) then return end local z = obj:getPositionZ() + 20 local x = creature:getPositionX() local y = creature:getPositionY() creature:playEffect("clienteffect", "elevator_ascend.cef") creature:teleport(x, z, y, obj:getParentID()) end function EmperorsRetreatScreenPlay:setMoodString(pNpc, mood) ObjectManager.withCreatureObject(pNpc, function(npc) npc:setMoodString(mood) end) end function EmperorsRetreatScreenPlay:spawnMobiles() -- Inside spawnMobile("naboo", "royal_imperial_guard", 120, 11.2, 0.2, -31.5, 0, 1418874) spawnMobile("naboo", "royal_imperial_guard", 120, 14.8, 0.2, -31.5, 0, 1418874) spawnMobile("naboo", "royal_imperial_guard", 120, 10.8, 20, -27.2, 180, 1418886) spawnMobile("naboo", "royal_imperial_guard", 120, 15.3, 20, -27.2, -13, 1418886) spawnMobile("naboo", "ra7_bug_droid", 120, 4.0, 0.2, -45.7, 4, 1418876) spawnMobile("naboo", "mouse_droid", 120, -8.6, 0.2, -14.2, -15, 1418879) spawnMobile("naboo", "mouse_droid", 120, -39.9, 0.2, -12.4, -25, 1418879) local pNpc = spawnMobile("naboo", "stormtrooper", 120, -0.5, 0.2, -23.6, 76, 1418874) EmperorsRetreatScreenPlay:setMoodString(pNpc, "conversation") local pNpc2 = spawnMobile("naboo", "stormtrooper", 120, 0.7, 0.2, -23.5, -20, 1418874) EmperorsRetreatScreenPlay:setMoodString(pNpc2, "conversation") --Guard Towers spawnMobile("naboo", "stormtrooper", 450, 2536.8, 296, -3881.4, -90, 0) spawnMobile("naboo", "stormtrooper", 450, 2536.8, 296, -3885.5, -90, 0) spawnMobile("naboo", "stormtrooper", 450, 2551, 352, -3647, -125, 0) spawnMobile("naboo", "stormtrooper", 450, 2553.2, 352, -3650.7, -125, 0) spawnMobile("naboo", "stormtrooper", 450, 2342, 392, -3561.1, 145, 0) spawnMobile("naboo", "stormtrooper", 450, 2345.3, 392, -3559, 145, 0) spawnMobile("naboo", "stormtrooper", 450, 2175.6, 362, -3698, 133, 0) spawnMobile("naboo", "stormtrooper", 450, 2178, 362, -3695.1, 133, 0) spawnMobile("naboo", "stormtrooper", 450, 1711.5, 385, -3676, 130, 0) spawnMobile("naboo", "stormtrooper", 450, 1714.6, 385, -3673.6, 130, 0) spawnMobile("naboo", "stormtrooper", 450, 1909, 395, -4020.8, 20, 0) spawnMobile("naboo", "stormtrooper", 450, 1905.3, 395, -4018.9, 20, 0) spawnMobile("naboo", "stormtrooper", 450, 2122.8, 294, -4180.9, -15, 0) spawnMobile("naboo", "stormtrooper", 450, 2118.9, 294, -4181.4, -15, 0) spawnMobile("naboo", "stormtrooper", 450, 2371.8, 325, -4095.5, 0, 0) spawnMobile("naboo", "stormtrooper", 450, 2367.7, 325, -4095.5, 0, 0) --By the emperors retreat spawnMobile("naboo", "at_st", 900, 2436.4, 292, -3912.1, 167, 0) spawnMobile("naboo", "at_st", 900, 2429.9, 292, -3913.1, 167, 0) spawnMobile("naboo", "stormtrooper", 450, 2433.3, 292, -3968.4, 4, 0) spawnMobile("naboo", "stormtrooper", 450, 2435.3, 292, -3968.4, 4, 0) spawnMobile("naboo", "imperial_corporal", 450, 2434.4, 292, -3967.1, 4, 0) spawnMobile("naboo", "stormtrooper", 450, 2452, 292, -3912.8, -170, 0) spawnMobile("naboo", "stormtrooper", 450, 2454, 292, -3912.8, -170, 0) spawnMobile("naboo", "imperial_corporal", 450, 2452.9, 292, -3914.1, -170, 0) end
local ObjectManager = require("managers.object.object_manager") EmperorsRetreatScreenPlay = ScreenPlay:new { numberOfActs = 1, screenplayName = "EmperorsRetreatScreenPlay", } registerScreenPlay("EmperorsRetreatScreenPlay", true) function EmperorsRetreatScreenPlay:start() if (isZoneEnabled("naboo")) then self:spawnMobiles() self:spawnSceneObjects() end end function EmperorsRetreatScreenPlay:spawnSceneObjects() local elevatorUp = spawnSceneObject("naboo", "object/tangible/terminal/terminal_elevator_up.iff", 13, 1, -36, 1418877, 1, 0, 0, 0) spawnSceneObject("naboo", "object/tangible/terminal/terminal_elevator_down.iff", 13, 20.5, -36, 1418877, 1, 0, 0, 0) if (elevatorUp ~= nil) then local terminal = LuaSceneObject(elevatorUp) terminal:setObjectMenuComponent("EmperorElevatorMenuComponent") end end EmperorElevatorMenuComponent = {} function EmperorElevatorMenuComponent:fillObjectMenuResponse(pSceneObject, pMenuResponse, pPlayer) local menuResponse = LuaObjectMenuResponse(pMenuResponse) menuResponse:addRadialMenuItem(198, 3, "@elevator_text:up") end function EmperorElevatorMenuComponent:handleObjectMenuSelect(pSceneObject, pPlayer, selectedID) local creature = LuaCreatureObject(pPlayer) if (selectedID ~= 198) or (not creature:hasScreenPlayState("imperial_theme_park", 32)) then creature:sendSystemMessage("@theme_park_imperial/warning:emperor") return end local obj = LuaSceneObject(pSceneObject) if (creature:getParent() ~= obj:getParent()) then return end local z = obj:getPositionZ() + 20 local x = creature:getPositionX() local y = creature:getPositionY() creature:playEffect("clienteffect", "elevator_ascend.cef") creature:teleport(x, z, y, obj:getParentID()) end function EmperorsRetreatScreenPlay:setMoodString(pNpc, mood) ObjectManager.withCreatureObject(pNpc, function(npc) npc:setMoodString(mood) end) end function EmperorsRetreatScreenPlay:spawnMobiles() -- Inside local pNpc = spawnMobile("naboo", "royal_imperial_guard", 120, 11.2, 0.2, -31.5, 0, 1418874) EmperorsRetreatScreenPlay:setMoodString(pNpc, "npc_imperial") pNpc = spawnMobile("naboo", "royal_imperial_guard", 120, 14.8, 0.2, -31.5, 0, 1418874) EmperorsRetreatScreenPlay:setMoodString(pNpc, "npc_imperial") pNpc = spawnMobile("naboo", "royal_imperial_guard", 120, 10.8, 20, -27.2, 180, 1418886) EmperorsRetreatScreenPlay:setMoodString(pNpc, "npc_imperial") pNpc = spawnMobile("naboo", "royal_imperial_guard", 120, 15.3, 20, -27.2, 180, 1418886) EmperorsRetreatScreenPlay:setMoodString(pNpc, "npc_imperial") spawnMobile("naboo", "ra7_bug_droid", 120, 4.0, 0.2, -45.7, 4, 1418876) spawnMobile("naboo", "mouse_droid", 120, -8.6, 0.2, -14.2, -15, 1418879) spawnMobile("naboo", "mouse_droid", 120, -39.9, 0.2, -12.4, -25, 1418879) pNpc = spawnMobile("naboo", "stormtrooper", 120, -0.5, 0.2, -23.6, 76, 1418874) EmperorsRetreatScreenPlay:setMoodString(pNpc, "conversation") pNpc = spawnMobile("naboo", "stormtrooper", 120, 0.7, 0.2, -23.5, -20, 1418874) EmperorsRetreatScreenPlay:setMoodString(pNpc, "conversation") --Guard Towers spawnMobile("naboo", "stormtrooper", 450, 2536.8, 296, -3881.4, -90, 0) spawnMobile("naboo", "stormtrooper", 450, 2536.8, 296, -3885.5, -90, 0) spawnMobile("naboo", "stormtrooper", 450, 2551, 352, -3647, -125, 0) spawnMobile("naboo", "stormtrooper", 450, 2553.2, 352, -3650.7, -125, 0) spawnMobile("naboo", "stormtrooper", 450, 2342, 392, -3561.1, 145, 0) spawnMobile("naboo", "stormtrooper", 450, 2345.3, 392, -3559, 145, 0) spawnMobile("naboo", "stormtrooper", 450, 2175.6, 362, -3698, 133, 0) spawnMobile("naboo", "stormtrooper", 450, 2178, 362, -3695.1, 133, 0) spawnMobile("naboo", "stormtrooper", 450, 1711.5, 385, -3676, 130, 0) spawnMobile("naboo", "stormtrooper", 450, 1714.6, 385, -3673.6, 130, 0) spawnMobile("naboo", "stormtrooper", 450, 1909, 395, -4020.8, 20, 0) spawnMobile("naboo", "stormtrooper", 450, 1905.3, 395, -4018.9, 20, 0) spawnMobile("naboo", "stormtrooper", 450, 2122.8, 294, -4180.9, -15, 0) spawnMobile("naboo", "stormtrooper", 450, 2118.9, 294, -4181.4, -15, 0) spawnMobile("naboo", "stormtrooper", 450, 2371.8, 325, -4095.5, 0, 0) spawnMobile("naboo", "stormtrooper", 450, 2367.7, 325, -4095.5, 0, 0) --By the emperors retreat spawnMobile("naboo", "at_st", 900, 2436.4, 292, -3912.1, 167, 0) spawnMobile("naboo", "at_st", 900, 2429.9, 292, -3913.1, 167, 0) spawnMobile("naboo", "stormtrooper", 450, 2433.3, 292, -3968.4, 4, 0) spawnMobile("naboo", "stormtrooper", 450, 2435.3, 292, -3968.4, 4, 0) spawnMobile("naboo", "imperial_corporal", 450, 2434.4, 292, -3967.1, 4, 0) spawnMobile("naboo", "stormtrooper", 450, 2452, 292, -3912.8, -170, 0) spawnMobile("naboo", "stormtrooper", 450, 2454, 292, -3912.8, -170, 0) spawnMobile("naboo", "imperial_corporal", 450, 2452.9, 292, -3914.1, -170, 0) end
[fixed] Tweaked some Emperor's Retreat spawns
[fixed] Tweaked some Emperor's Retreat spawns Change-Id: I9881582c7f02b20384c86b8f0253f62b8088e704
Lua
agpl-3.0
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,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
e5d4d4e8e88667e9f8741865d242b7087c17cb2b
testserver/item/id_2874_mirror.lua
testserver/item/id_2874_mirror.lua
require("base.common") require("content.chardescription") module("item.id_2874_mirror", package.seeall) -- belongs also to item id 2873 -- UPDATE common SET com_script='item.id_2874_mirror' WHERE com_itemid = 2874; function init() lpos = position(-32,193,-8); mpos = position(-28,193,-8); end function LookAtItem( User, Item ) -- Mirror of Death -- if (Item.pos == position(892,390,0)) and (User:getFaceTo() == 2) and (User.pos == position(890,390,0)) then MirrorOfDeath(User) return end -- end of mirror of death if (first==nil) then init(); first=1; end lang=User:getPlayerLanguage(); if ( (Item.pos == mpos) and (User:getFaceTo() == 2) and (User.pos == position(-29,193,-8)) ) then if lang==0 then world:itemInform(User, Item, "Hinter deinem Rcken erkennst du deutlich eine Leiter im Spiegel."); else world:itemInform(User, Item, "Behind your back you can clearly see a ladder in the mirror."); end if ( not base.common.isItemIdInFieldStack( 35, lpos ) ) then world:createItemFromId( 35, 1, lpos, true, 999 ,nil); end; else if lang==0 then world:itemInform(User, Item, "Spiegel"); else world:itemInform(User, Item, "mirror"); end end; -- User:inform("in LookAtItem of spiegel"); LookAtItemIdent(User,Item); end function UseItem(User,SourceItem,TargetItem,Counter,Param) local output = ""; local lang = User:getPlayerLanguage(); local qual,dura = getClothesFactor(User); local ft = getFigureText(User:increaseAttrib("body_height",0),User:increaseAttrib("weight",0),User:increaseAttrib("strength",0), lang); if(lang == 0) then output = "Du bist "; output = output..getAgeText(User:getRace(), User:increaseAttrib("age", 0), lang); if(ft ~= nil) then output = output..", "..ft; end output = output.." und "..getHPText(User:increaseAttrib("hitpoints",0), lang)..". "; output = output.."Deine Kleidung wirkt "..getClothesQualText(qual, lang).." und "..getClothesDuraText(dura, lang).."."; else output = "You are "; output = output..getAgeText(User:getRace(), User:increaseAttrib("age", 0), lang); if(ft ~= nil) then output = output..", "..getFigureText(User:increaseAttrib("body_height",0),User:increaseAttrib("weight",0),User:increaseAttrib("strength",0), lang); end output = output.." and "..getHPText(User:increaseAttrib("hitpoints",0), lang)..". "; output = output.."Your clothes look "..getClothesQualText(qual, lang).." and "..getClothesDuraText(dura, lang).."."; end User:sendCharDescription(User.id, output); end function MirrorOfDeath(User) -- shows the a picture of him after his death -- can be reducned by donations, see coin scripts MoveItemAfterMove getProgress = User:getQuestProgress(666) if getProgress == 0 then getProgress = 10000 end charSex = User:increaseAttrib("sex",0) charRace = User:getRace() deathCounter = getProgress-((math.floor(getProgress/10))*10) if deathCounter == 0 then base.common.InformNLS(User, "Im Spiegel siehst du ein Bild deiner selbst - jedoch in den besten deiner Jahre, bei voller Gesundheit.", "You see yourself in the mirror - but in your prime time and fit as a fiddle.") else if charSex == 0 then base.common.InformNLS(User, DeathTextMaleDE[charRace][deathCounter], DeathTextMaleEN[charRace][deathCounter]) else base.common.InformNLS(User, DeathTextFemaleDE[charRace][deathCounter], DeathTextFemaleEN[charRace][deathCounter]) end end end DeathTextMaleDE = {} DeathTextMaleEN = {} -- human DeathTextMaleDE[0] = {"de1","de2","de3","de4","de5"} DeathTextMaleEN[0] = {"en1","en2","en3","en4","en5"} -- dwarf DeathTextMaleDE[1] = {"de1","de2","de3","de4","de5"} DeathTextMaleEN[1] = {"en1","en2","en3","en4","en5"} -- halfling DeathTextMaleDE[2] = {"de1","de2","de3","de4","de5"} DeathTextMaleEN[2] = {"en1","en2","en3","en4","en5"} -- elf DeathTextMaleDE[3] = {"de1","de2","de3","de4","de5"} DeathTextMaleEN[3] = {"en1","en2","en3","en4","en5"} -- orc DeathTextMaleDE[4] = {"de1","de2","de3","de4","de5"} DeathTextMaleEN[4] = {"en1","en2","en3","en4","en5"} -- lizard DeathTextMaleDE[5] = {"de1","de2","de3","de4","de5"} DeathTextMaleEN[5] = {"en1","en2","en3","en4","en5"} DeathTextFemaleDE = {} DeathTextFemaleEN = {} -- human DeathTextFemaleDE[0] = {"de1","de2","de3","de4","de5"} DeathTextFemaleEN[0] = {"en1","en2","en3","en4","en5"} -- dwarf DeathTextFemaleDE[1] = {"de1","de2","de3","de4","de5"} DeathTextFemaleEN[1] = {"en1","en2","en3","en4","en5"} -- halfling DeathTextFemaleDE[2] = {"de1","de2","de3","de4","de5"} DeathTextFemaleEN[2] = {"en1","en2","en3","en4","en5"} -- elf DeathTextFemaleDE[3] = {"de1","de2","de3","de4","de5"} DeathTextFemaleEN[3] = {"en1","en2","en3","en4","en5"} -- orc DeathTextFemaleDE[4] = {"de1","de2","de3","de4","de5"} DeathTextFemaleEN[4] = {"en1","en2","en3","en4","en5"} -- lizard DeathTextFemaleDE[5] = {"de1","de2","de3","de4","de5"} DeathTextFemaleEN[5] = {"en1","en2","en3","en4","en5"}
require("base.common") require("content.chardescription") module("item.id_2874_mirror", package.seeall) -- belongs also to item id 2873 -- UPDATE common SET com_script='item.id_2874_mirror' WHERE com_itemid = 2874; ladderPosition = position(-32,193,-8) mirrorPosition = position(-28,193,-8) function LookAtItem(User, Item) -- Mirror of Death -- if (Item.pos == position(892,390,0)) and (User:getFaceTo() == 2) and (User.pos == position(890,390,0)) then MirrorOfDeath(User) return end -- end of mirror of death local lookAt = base.lookat.GenerateLookAt(User, Item) if Item.pos == mirrorPosition and User:getFaceTo() == Character.dir_east and User.pos == position(-29, 193, -8) then lookAt.description = base.common.GetNLS("Hinter deinem Rcken erkennst du deutlich eine Leiter im Spiegel.", "Behind your back you can clearly see a ladder in the mirror.") if ( not base.common.isItemIdInFieldStack(35, ladderPosition)) then world:createItemFromId(35, 1, ladderPosition, true, 999, nil) end end world:itemInform(User, Item, lookAt) end function UseItem(User,SourceItem,TargetItem,Counter,Param) local output = ""; local lang = User:getPlayerLanguage(); local qual,dura = getClothesFactor(User); local ft = getFigureText(User:increaseAttrib("body_height",0),User:increaseAttrib("weight",0),User:increaseAttrib("strength",0), lang); if(lang == 0) then output = "Du bist "; output = output..getAgeText(User:getRace(), User:increaseAttrib("age", 0), lang); if(ft ~= nil) then output = output..", "..ft; end output = output.." und "..getHPText(User:increaseAttrib("hitpoints",0), lang)..". "; output = output.."Deine Kleidung wirkt "..getClothesQualText(qual, lang).." und "..getClothesDuraText(dura, lang).."."; else output = "You are "; output = output..getAgeText(User:getRace(), User:increaseAttrib("age", 0), lang); if(ft ~= nil) then output = output..", "..getFigureText(User:increaseAttrib("body_height",0),User:increaseAttrib("weight",0),User:increaseAttrib("strength",0), lang); end output = output.." and "..getHPText(User:increaseAttrib("hitpoints",0), lang)..". "; output = output.."Your clothes look "..getClothesQualText(qual, lang).." and "..getClothesDuraText(dura, lang).."."; end User:sendCharDescription(User.id, output); end function MirrorOfDeath(User) -- shows the a picture of him after his death -- can be reducned by donations, see coin scripts MoveItemAfterMove getProgress = User:getQuestProgress(666) if getProgress == 0 then getProgress = 10000 end charSex = User:increaseAttrib("sex",0) charRace = User:getRace() deathCounter = getProgress-((math.floor(getProgress/10))*10) if deathCounter == 0 then base.common.InformNLS(User, "Im Spiegel siehst du ein Bild deiner selbst - jedoch in den besten deiner Jahre, bei voller Gesundheit.", "You see yourself in the mirror - but in your prime time and fit as a fiddle.") else if charSex == 0 then base.common.InformNLS(User, DeathTextMaleDE[charRace][deathCounter], DeathTextMaleEN[charRace][deathCounter]) else base.common.InformNLS(User, DeathTextFemaleDE[charRace][deathCounter], DeathTextFemaleEN[charRace][deathCounter]) end end end DeathTextMaleDE = {} DeathTextMaleEN = {} -- human DeathTextMaleDE[0] = {"de1","de2","de3","de4","de5"} DeathTextMaleEN[0] = {"en1","en2","en3","en4","en5"} -- dwarf DeathTextMaleDE[1] = {"de1","de2","de3","de4","de5"} DeathTextMaleEN[1] = {"en1","en2","en3","en4","en5"} -- halfling DeathTextMaleDE[2] = {"de1","de2","de3","de4","de5"} DeathTextMaleEN[2] = {"en1","en2","en3","en4","en5"} -- elf DeathTextMaleDE[3] = {"de1","de2","de3","de4","de5"} DeathTextMaleEN[3] = {"en1","en2","en3","en4","en5"} -- orc DeathTextMaleDE[4] = {"de1","de2","de3","de4","de5"} DeathTextMaleEN[4] = {"en1","en2","en3","en4","en5"} -- lizard DeathTextMaleDE[5] = {"de1","de2","de3","de4","de5"} DeathTextMaleEN[5] = {"en1","en2","en3","en4","en5"} DeathTextFemaleDE = {} DeathTextFemaleEN = {} -- human DeathTextFemaleDE[0] = {"de1","de2","de3","de4","de5"} DeathTextFemaleEN[0] = {"en1","en2","en3","en4","en5"} -- dwarf DeathTextFemaleDE[1] = {"de1","de2","de3","de4","de5"} DeathTextFemaleEN[1] = {"en1","en2","en3","en4","en5"} -- halfling DeathTextFemaleDE[2] = {"de1","de2","de3","de4","de5"} DeathTextFemaleEN[2] = {"en1","en2","en3","en4","en5"} -- elf DeathTextFemaleDE[3] = {"de1","de2","de3","de4","de5"} DeathTextFemaleEN[3] = {"en1","en2","en3","en4","en5"} -- orc DeathTextFemaleDE[4] = {"de1","de2","de3","de4","de5"} DeathTextFemaleEN[4] = {"en1","en2","en3","en4","en5"} -- lizard DeathTextFemaleDE[5] = {"de1","de2","de3","de4","de5"} DeathTextFemaleEN[5] = {"en1","en2","en3","en4","en5"}
Fix mirror lookat
Fix mirror lookat
Lua
agpl-3.0
Baylamon/Illarion-Content,LaFamiglia/Illarion-Content,vilarion/Illarion-Content,Illarion-eV/Illarion-Content,KayMD/Illarion-Content
ec59a23bea13d21030cb5a985ff332cdda994b63
worker.lua
worker.lua
#!/usr/bin/luajit local io = require("io") local os = require("os") local string = require("string") local http = require("socket.http") local json = require("dkjson") local memcache = require("memcached") local nonblock = require("nonblock") -- check effective uid if io.popen("whoami"):read("*l") ~= "root" then print("Need to be root.") os.exit(1) end -- retrieve url from environment local meeci_host = os.getenv("MEECI_HOST") if not meeci_host then print("MEECI_HOST is not defined.") os.exit(2) end local meeci_http = "http://" .. meeci_host local meeci_ftp = "ftp://" .. meeci_host .. "/meeci" local mc = memcache.connect(meeci_host, 11211) --< function definitions function fwrite(fmt, ...) return io.write(string.format(fmt, ...)) end function sleep(n) os.execute("sleep " .. tonumber(n)) end -- luajit os.execute returns only the exit status function execute(cmd) print(cmd) if _G.jit then return os.execute(cmd) == 0 else return os.execute(cmd) end end -- return content of a file function cat(file) local stream = io.popen("cat " .. file) local result = stream:read("*a") stream:close() return result end -- receive a task from meeci-web function receive() local body, code = http.request(meeci_http .. "/task") if code == 200 then return json.decode(body) end end function log(task) fwrite("[%s] %s %d: ", os.date(), task.type, task.id) if task.type == "build" then io.write(task.url .. '\n') else io.write(task.container .. '\n') end end -- download files in /meeci/container function wget(file) local cmd = "wget -N " .. meeci_ftp .. "/containers/" .. file return execute(cmd) end -- extract a container into 'container' directory -- [args] container: container name with suffix .bz2 function tarx(container) execute("rm -rf container") return execute("tar xf " .. container) end -- download a shallow repository and its build script function gitclone(task) local dir = "container/opt/" .. task.repository if not execute("mkdir -p " .. dir) then return false end local cmd = "git clone --depth 30 -b %s %s %s" cmd = string.format(cmd, task.branch, task.url, dir) if not execute(cmd) then return false end cmd = "cd " .. dir .. "; git checkout " .. task.commit if not execute(cmd) then return false end local url = meeci_http .. "/scripts/" .. task.id cmd = "wget -O " .. dir .. "/meeci_build.sh " .. url return execute(cmd) end -- inform meeci-web the result function report(task, start, stop, code) local cmd = string.format( "wput /var/lib/meeci/worker/logs/%s/%d.log " .. meeci_ftp .. "/logs/%s/%d.log", task.type, task.id, task.type, task.id ) execute(cmd); local str = json.encode({ user = task.user, type = task.type, id = task.id, start = start, stop = stop, exit = code, container = task.container }) mc:set(string.sub(task.type, 1, 1) .. ":" .. task.id, str) local path = string.format( "/finish/%s/%d", task.type, task.id ) http.request(meeci_http .. path, tostring(code)) print("POST " .. meeci_http .. path) end -- compress and upload a new container -- [args] container: container name with suffix .bz2 function upload(container) execute("rm -f container/meeci_exit_status") -- TODO: file changed as we read it execute("tar jcf container.bz2 container") local url = meeci_ftp .. "/containers/" .. container if execute("wput container.bz2 " .. url) then os.remove("container.bz2") return true end end -- run a build task or create a container function build(task) local dir, script if task.type == "build" then dir = "/opt/" .. task.repository script = "meeci_build.sh" else dir = "/root" script = task.container .. ".sh" end local cmd = "cd %s; bash %s; echo -n $? > /meeci_exit_status" cmd = string.format(cmd, dir, script) cmd = string.format("systemd-nspawn -D ./container bash -c '%s'", cmd) -- file log local logdir = "/var/lib/meeci/worker/logs" local log = string.format("%s/%s/%d.log", logdir, task.type, task.id) log = io.open(log, 'a') -- memcache log local key = string.sub(task.type, 1, 1) .. "#" .. tostring(task.id) mc:set(key, "") local start = os.time() local stream, fd = nonblock:popen(cmd) while true do local n, line = nonblock:read(fd) if n == 0 then break end log:write(line) mc:append(key, line) if n < 1000 then sleep(1) end -- TODO: 10min and 60min limit end log:close() nonblock:pclose(stream) local stop = os.time() local code = tonumber(cat("container/meeci_exit_status")) if task.type == "build" then report(task, start, stop, code) return true else if (not upload(task.user .. "/" .. task.container .. ".bz2")) then code = 21 end report(task, start, stop, code) return code == 0 end end --> local test = os.getenv("TEST") and true or false if not test and not wget("meeci-minbase.bz2") then print("Cannot wget meeci-minbase.bz2") os.exit(3) end -- main loop -- local failure, idle = 0, os.time() while not test do local done = false local task = receive() if task then log(task) if task.type == "build" then if not wget(task.user .. "/" .. task.container .. ".bz2") then goto END_TASK end if not tarx(task.container .. ".bz2") then goto END_TASK end os.remove(task.container .. ".bz2") if not gitclone(task) then goto END_TASK end else if not tarx("meeci-minbase.bz2") then goto END_TASK end local script = task.container .. ".sh" if not wget(task.user .. "/" .. script) then goto END_TASK end os.rename(script, "container/root/" .. script) end done = build(task) ::END_TASK:: execute("rm -rf container") if done then fwrite("[%s] SUCCESS\n", os.date()) if failure > 0 then failure = failure - 1 end else fwrite("[%s] ERROR\n", os.date()) failure = failure + 1 if failure == 10 then fwrite("Worker stopped because of too many failures.\n") os.exit(10) end end idle = os.time() end -- TODO: sleep(1) sleep(10) if (os.time() - idle) % 600 == 0 then local m = math.floor((os.time() - idle) / 60) fwrite("[%s] idle for %d min\n", os.date(), m) end end
#!/usr/bin/luajit local io = require("io") local os = require("os") local string = require("string") local http = require("socket.http") local json = require("dkjson") local memcache = require("memcached") local nonblock = require("nonblock") -- check effective uid if io.popen("whoami"):read("*l") ~= "root" then print("Need to be root.") os.exit(1) end -- retrieve url from environment local meeci_host = os.getenv("MEECI_HOST") if not meeci_host then print("MEECI_HOST is not defined.") os.exit(2) end local meeci_http = "http://" .. meeci_host .. ":3780" local meeci_ftp = "ftp://" .. meeci_host .. "/meeci" local mc = memcache.connect(meeci_host, 11211) --< function definitions function fwrite(fmt, ...) return io.write(string.format(fmt, ...)) end function sleep(n) os.execute("sleep " .. tonumber(n)) end -- luajit os.execute returns only the exit status function execute(cmd) print(cmd) if _G.jit then return os.execute(cmd) == 0 else return os.execute(cmd) end end -- return content of a file function cat(file) local stream = io.popen("cat " .. file) local result = stream:read("*a") stream:close() return result end -- receive a task from meeci-web function receive() local body, code = http.request(meeci_http .. "/task") if code == 200 then return json.decode(body) end end function log(task) fwrite("[%s] %s %s: ", os.date(), task.type, task.strid) if task.type == "build" then io.write(task.url .. '\n') else io.write(task.container .. '\n') end end -- download files in /meeci/container function wget(file) local cmd = "wget -N " .. meeci_ftp .. "/containers/" .. file return execute(cmd) end -- extract a container into 'container' directory -- [args] container: container name with suffix .bz2 function tarx(container) execute("rm -rf container") return execute("tar xf " .. container) end -- download a shallow repository and its build script function gitclone(task) local dir = "container/opt/" .. task.repository if not execute("mkdir -p " .. dir) then return false end local cmd = "git clone --depth 30 -b %s %s %s" cmd = string.format(cmd, task.branch, task.url, dir) if not execute(cmd) then return false end cmd = "cd " .. dir .. "; git checkout " .. task.commit if not execute(cmd) then return false end local url = meeci_http .. string.format( "/scripts/%s/%s/%s/%d", task.user, task.repository, task.owner, task.host ) cmd = "wget -O " .. dir .. "/meeci_build.sh " .. url return execute(cmd) end -- inform meeci-web the result function report(task, start, stop, code) local cmd = string.format( "wput /var/lib/meeci/worker/logs/%s/%s.log " .. meeci_ftp .. "/logs/%s/%s.log", task.type, task.strid, task.type, task.strid ) execute(cmd); local str = json.encode({ user = task.user, start = start, stop = stop, exit = code, container = task.container }) mc:set(string.sub(task.type, 1, 1) .. ":" .. task.strid, str) local path = string.format( "/finish/%s/%s", task.type, task.strid ) http.request(meeci_http .. path, tostring(code)) print("POST " .. meeci_http .. path) end -- compress and upload a new container -- [args] container: container name with suffix .bz2 function upload(container) execute("rm -f container/meeci_exit_status") -- TODO: file changed as we read it execute("tar jcf container.bz2 container") local url = meeci_ftp .. "/containers/" .. container if execute("wput container.bz2 " .. url) then os.remove("container.bz2") return true end end -- run a build task or create a container function build(task) local dir, script if task.type == "build" then dir = "/opt/" .. task.repository script = "meeci_build.sh" else dir = "/root" script = task.container .. ".sh" end local cmd = "cd %s; bash %s; echo -n $? > /meeci_exit_status" cmd = string.format(cmd, dir, script) cmd = string.format("systemd-nspawn -D ./container bash -c '%s'", cmd) -- file log local logdir = "/var/lib/meeci/worker/logs" local log = string.format("%s/%s/%s.log", logdir, task.type, task.strid) log = io.open(log, 'a') -- memcache log local key = string.sub(task.type, 1, 1) .. "#" .. tostring(task.strid) mc:set(key, "") local start = os.time() local stream, fd = nonblock:popen(cmd) while true do local n, line = nonblock:read(fd) if n == 0 then break end log:write(line) mc:append(key, line) if n < 1000 then sleep(1) end -- TODO: 10min and 60min limit end log:close() nonblock:pclose(stream) local stop = os.time() local code = tonumber(cat("container/meeci_exit_status")) if task.type == "build" then report(task, start, stop, code) return true else if (not upload(task.user .. "/" .. task.container .. ".bz2")) then code = 21 end report(task, start, stop, code) return code == 0 end end --> local test = os.getenv("TEST") and true or false if not test and not wget("meeci-minbase.bz2") then print("Cannot wget meeci-minbase.bz2") os.exit(3) end -- main loop -- local failure, idle = 0, os.time() while not test do local done = false local task = receive() if task then log(task) if task.type == "build" then if not wget(task.user .. "/" .. task.container .. ".bz2") then goto END_TASK end if not tarx(task.container .. ".bz2") then goto END_TASK end os.remove(task.container .. ".bz2") if not gitclone(task) then goto END_TASK end else if not tarx("meeci-minbase.bz2") then goto END_TASK end local script = task.container .. ".sh" if not wget(task.user .. "/" .. script) then goto END_TASK end os.rename(script, "container/root/" .. script) end done = build(task) ::END_TASK:: execute("rm -rf container") if done then fwrite("[%s] SUCCESS\n", os.date()) if failure > 0 then failure = failure - 1 end else fwrite("[%s] ERROR\n", os.date()) failure = failure + 1 if failure == 10 then fwrite("Worker stopped because of too many failures.\n") os.exit(10) end end idle = os.time() end -- TODO: sleep(1) sleep(10) if (os.time() - idle) % 600 == 0 then local m = math.floor((os.time() - idle) / 60) fwrite("[%s] idle for %d min\n", os.date(), m) end end
fix task.id precision problem
fix task.id precision problem
Lua
mit
wizawu/meeci-worker
03f90b74b8724c3f1a373bbfa58233e01dc1cbc4
lua/starfall/libs_sh/color.lua
lua/starfall/libs_sh/color.lua
SF.Color = {} --- Color type --@shared local color_methods, color_metatable = SF.Typedef( "Color" ) local wrap, unwrap = SF.CreateWrapper( color_metatable, true, false, debug.getregistry().Color ) SF.Color.Methods = color_methods SF.Color.Metatable = color_metatable SF.Color.Wrap = wrap SF.Color.Unwrap = unwrap --- Same as the Gmod Color type -- @name SF.DefaultEnvironment.Color -- @class function -- @param r - Red -- @param g - Green -- @param b - Blue -- @param a - Alpha -- @return New color SF.DefaultEnvironment.Color = function ( ... ) return wrap( Color( ... ) ) end --- __newindex metamethod function color_metatable.__newindex ( t, k, v ) rawset( t, k, v ) end local _p = color_metatable.__index --- __index metamethod function color_metatable.__index ( t, k ) if k == "r" or k == "g" or k == "b" or k == "a" then return unwrap( t )[ k ] end return _p[ k ] end --- __tostring metamethod function color_metatable:__tostring () return unwrap( self ):__tostring() end --- __concat metamethod function color_metatable.__concat ( ... ) local t = { ... } return tostring( t[ 1 ] ) .. tostring( t[ 2 ] ) end --- __eq metamethod function color_metatable:__eq ( c ) SF.CheckType( self, color_metatable ) SF.CheckType( c, color_metatable ) return unwrap( self ):__eq( unwrap( c ) ) end --- Converts the color from RGB to HSV. --@shared --@return A triplet of numbers representing HSV. function color_methods:toHSV () return ColorToHSV( unwrap( self ) ) end
SF.Color = {} --- Color type --@shared local color_methods, color_metatable = SF.Typedef( "Color" ) local wrap, unwrap = SF.CreateWrapper( color_metatable, true, false, debug.getregistry().Color ) SF.Color.Methods = color_methods SF.Color.Metatable = color_metatable SF.Color.Wrap = wrap SF.Color.Unwrap = unwrap --- Same as the Gmod Color type -- @name SF.DefaultEnvironment.Color -- @class function -- @param r - Red -- @param g - Green -- @param b - Blue -- @param a - Alpha -- @return New color SF.DefaultEnvironment.Color = function ( ... ) return wrap( Color( ... ) ) end -- Lookup table. -- Index 1->4 have associative rgba for use in __index. Saves lots of checks -- String based indexing returns string, just a pass through. -- Think of rgb as a template for members of Color that are expected. local rgb = { [ 1 ] = "r", [ 2 ] = "g", [ 3 ] = "b", [ 4 ] = "a", r = "r", g = "g", b = "b", a = "a" } --- __newindex metamethod function color_metatable.__newindex ( t, k, v ) if rgb[ k ] then rawset( SF.UnwrapObject( t ), rgb[ k ], v ) else rawset( t, k, v ) end end --- __index metamethod function color_metatable.__index ( t, k ) if rgb[ k ] then return rawget( SF.UnwrapObject( t ), rgb[ k ] ) else return rawget( t, k ) end end --- __tostring metamethod function color_metatable:__tostring () return unwrap( self ):__tostring() end --- __concat metamethod function color_metatable.__concat ( ... ) local t = { ... } return tostring( t[ 1 ] ) .. tostring( t[ 2 ] ) end --- __eq metamethod function color_metatable:__eq ( c ) SF.CheckType( self, color_metatable ) SF.CheckType( c, color_metatable ) return unwrap( self ):__eq( unwrap( c ) ) end --- Converts the color from RGB to HSV. --@shared --@return A triplet of numbers representing HSV. function color_methods:toHSV () return ColorToHSV( unwrap( self ) ) end
Fixed Color type __index & __newindex metamethods.
Fixed Color type __index & __newindex metamethods. Fixes #282
Lua
bsd-3-clause
Ingenious-Gaming/Starfall,Jazzelhawk/Starfall,INPStarfall/Starfall,Xandaros/Starfall,Jazzelhawk/Starfall,Xandaros/Starfall,INPStarfall/Starfall,Ingenious-Gaming/Starfall
9f0610eedce8eb1c344b5ff0b522cf15cf670cf5
tests/insteadose5/main3.lua
tests/insteadose5/main3.lua
--$Name: Инстедоз 5$ --$Version: 0.23$ --$Author: http://instead.syscall.ru$ --$Info: Сборник коротких игр$ require 'fmt' require 'snd' require 'timer' local old_timer = timer.callback std.timer = function() _'@mplayer':timer() return old_timer(timer) end obj { nam = '@mplayer'; { tracks = {}; }; pos = 1; timer = function(s) if snd.music_playing() then return end s:next() end; rand = function(s) s.pos = rnd(#s.tracks) end; next = function(s) s.pos = s.pos + 1 if s.pos > #s.tracks then s.pos = 1 end print("Next track: ", s.tracks[s.pos]) snd.music('mus/'..s.tracks[s.pos], 1) end; load = function(s) if rawget(_G, 'js') then s.tracks = { 'RoccoW_-_01_-_Welcome.ogg', 'RoccoW_-_02_-_Echiptian_Swaggah.ogg', 'RoccoW_-_08_-_Sweet_Self_Satisfaction.ogg', } else for f in std.readdir 'mus' do if f:find('%.ogg$') then table.insert(s.tracks, f) print("Adding track: ", f) end end end table.sort(s.tracks) return s end; start = function(s) if #s.tracks == 0 then return end snd.music('mus/'..s.tracks[s.pos], 1) timer:set(1000) end; }:load():start() obj { nam = '@game'; act = function(s, w) gamefile('games/'..w..'/main3.lua', true) if w ~= 'spring' then _'@mplayer':rand() _'@mplayer':start() end if _'game'.pic == nil then _'game' 'pic'('gfx/fractal.gif'); end end; } obj { nam = '@restart'; act = function(s, w) instead.restart() end; } room { nam = 'main'; title = 'ИНСТЕДОЗ 5'; pic = 'gfx/fractal.gif'; decor = function() pn (fmt.c(fmt.b[[ЖУРНАЛ (СОВЕРШЕННО СЕКРЕТНО)]])) pn () pn (fmt.c [[{@game prolog|ПРОЛОГ}]]); pn (fmt.c [[{@game photohunt|ФОТООХОТА}]]); pn (fmt.c [[{@game walkout|НОЧНАЯ ПРОГУЛКА}]]); pn (fmt.c [[{@game spring|ВЕСНА}]]); pn (fmt.c [[{@game i_came_to_myself|Я ОЧНУЛСЯ}]]); end; }
--$Name: Инстедоз 5$ --$Version: 0.23$ --$Author: http://instead.syscall.ru$ --$Info: Сборник коротких игр$ require 'fmt' require 'snd' require 'timer' local old_timer = timer.callback std.timer = function() _'@mplayer':timer() return old_timer(timer) end obj { nam = '@mplayer'; { tracks = {}; }; pos = 1; timer = function(s) if snd.music_playing() then return end s:next() end; rand = function(s) s.pos = rnd(#s.tracks) end; next = function(s) s.pos = s.pos + 1 if s.pos > #s.tracks then s.pos = 1 end print("Next track: ", s.tracks[s.pos]) snd.music('mus/'..s.tracks[s.pos], 1) end; load = function(s) s.tracks = { 'RoccoW_-_01_-_Welcome.ogg', 'RoccoW_-_02_-_Echiptian_Swaggah.ogg', 'RoccoW_-_08_-_Sweet_Self_Satisfaction.ogg', } table.sort(s.tracks) return s end; start = function(s) if #s.tracks == 0 then return end snd.music('mus/'..s.tracks[s.pos], 1) timer:set(1000) end; }:load():start() obj { nam = '@game'; act = function(s, w) gamefile('games/'..w..'/main3.lua', true) if w ~= 'spring' then _'@mplayer':rand() _'@mplayer':start() end if _'game'.pic == nil then _'game' 'pic'('gfx/fractal.gif'); end end; } obj { nam = '@restart'; act = function(s, w) instead.restart() end; } room { nam = 'main'; title = 'ИНСТЕДОЗ 5'; pic = 'gfx/fractal.gif'; decor = function() pn (fmt.c(fmt.b[[ЖУРНАЛ (СОВЕРШЕННО СЕКРЕТНО)]])) pn () pn (fmt.c [[{@game prolog|ПРОЛОГ}]]); pn (fmt.c [[{@game photohunt|ФОТООХОТА}]]); pn (fmt.c [[{@game walkout|НОЧНАЯ ПРОГУЛКА}]]); pn (fmt.c [[{@game spring|ВЕСНА}]]); pn (fmt.c [[{@game i_came_to_myself|Я ОЧНУЛСЯ}]]); end; }
tracks fix
tracks fix
Lua
mit
gl00my/stead3
186b41ebeba7170499d061c226a1c2a763cc98b6
share/lua/website/gaskrank.lua
share/lua/website/gaskrank.lua
-- libquvi-scripts -- Copyright (C) 2010 Toni Gundogdu <legatvs@gmail.com> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library 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.1 of the License, or (at your option) any later version. -- -- This library 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 library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "gaskrank%.tv" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/tv/"}) return r end -- Query available formats. function query_formats(self) self.formats = 'default' return self end -- Parse media URL. function parse(self) self.host_id = "gaskrank" local p = quvi.fetch(self.page_url) self.title = p:match('"og:title" content="(.-)"') or error("no match: media title") self.title = self.title:gsub('Video', '') self.id = self.page_url:match("%-(%d+)%.h") or error("no match: media ID") self.url = {p:match('file:%s+"(.-)"') or error("no match: media stream URL")} return self end -- vim: set ts=4 sw=4 tw=72 expandtab:
-- libquvi-scripts -- Copyright (C) 2010,2012 Toni Gundogdu <legatvs@gmail.com> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library 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.1 of the License, or (at your option) any later version. -- -- This library 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 library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "gaskrank%.tv" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/tv/"}) return r end -- Query available formats. function query_formats(self) self.formats = 'default' return self end -- Parse media URL. function parse(self) self.host_id = "gaskrank" local p = quvi.fetch(self.page_url) self.title = p:match('"og:title" content="(.-)"') or error('no match: media title') local u = p:match("(http://movies.-%.flv)") or error("no match: media stream URL") self.id = u:match("/%d+/(%d+)%.%w+") or error("no match: media ID") self.url = {u} return self end -- vim: set ts=4 sw=4 tw=72 expandtab:
FIX: media/gaskrank.lua: Media ID, stream URL patterns
FIX: media/gaskrank.lua: Media ID, stream URL patterns Update the media stream URL pattern. Parse media ID from the media stream URL, instead. Croak if media title was not found.
Lua
agpl-3.0
legatvs/libquvi-scripts,DangerCove/libquvi-scripts,alech/libquvi-scripts,alech/libquvi-scripts,DangerCove/libquvi-scripts,legatvs/libquvi-scripts