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
|
|---|---|---|---|---|---|---|---|---|---|
7e07ea5a1f85c072e0283783db200231168667dd
|
commands.lua
|
commands.lua
|
require "keys"
Keydef = {
keycode = nil,
modifier = nil,
descr = nil
}
function Keydef:_new(obj)
-- obj definition
obj = obj or {}
setmetatable(obj, self)
self.__index = self
self.__tostring=Keydef.tostring
return obj
end
function Keydef:new(keycode,modifier,descr)
obj = Keydef:_new()
obj.keycode = keycode
obj.modifier = modifier
obj.descr = descr
return obj
end
function Keydef:display()
return ((self.modifier and self.modifier.."+") or "")..(self.descr or "")
end
function Keydef:tostring()
return ((self.modifier and self.modifier.."+") or "").."["..(self.keycode or "").."]"..(self.descr or "")
end
Command = {
keydef = nil,
keygroup = nil,
func = nil,
help = nil,
order = nil
}
function Command:_new(obj)
-- obj definition
obj = obj or {}
setmetatable(obj, self)
self.__index = self
self.__tostring=Command.tostring
return obj
end
function Command:new(keydef, func, help, keygroup, order)
obj = Command:_new()
obj.keydef = keydef
obj.func = func
obj.help = help
obj.keygroup = keygroup
obj.order = order
--print("creating command: ["..tostring(keydef).."] keygroup:["..(keygroup or "").."] help:"..help)
return obj
end
function Command:tostring()
return tostring(self.keydef)..": "..(self.help or "<no help defined>")
end
Commands = {
map = {},
size = 0
}
function Commands:add(keycode,modifier,keydescr,help,func)
if type(keycode) == "table" then
for i=1,#keycode,1 do
local keydef = Keydef:new(keycode[i],modifier,keydescr)
self:_addImpl(keydef,help,func)
end
else
local keydef = Keydef:new(keycode,modifier,keydescr)
self:_addImpl(keydef,help,func)
end
end
function Commands:addGroup(keygroup,keys,help,func)
for _k,keydef in pairs(keys) do
self:_addImpl(keydef,help,func,keygroup)
end
end
function Commands:_addImpl(keydef,help,func,keygroup)
if keydef.modifier==MOD_ANY then
self:addGroup(keygroup or keydef.descr,{Keydef:new(keydef.keycode,nil), Keydef:new(keydef.keycode,MOD_SHIFT), Keydef:new(keydef.keycode,MOD_ALT)},help,func)
elseif keydef.modifier==MOD_SHIFT_OR_ALT then
self:addGroup(keygroup or (MOD_SHIFT.."|"..MOD_ALT.."+"..(keydef.descr or "")),{Keydef:new(keydef.keycode,MOD_SHIFT), Keydef:new(keydef.keycode,MOD_ALT)},help,func)
else
local command = self.map[keydef]
if command == nil then
self.size = self.size + 1
command = Command:new(keydef,func,help,keygroup,self.size)
self.map[keydef] = command
else
command.func = func
command.help = help
command.keygroup = keygroup
end
end
end
function Commands:get(keycode,modifier)
return self.map[Keydef:new(keycode, modifier)]
end
function Commands:getByKeydef(keydef)
return self.map[keydef]
end
function Commands:new(obj)
-- payload
local mt = {}
setmetatable(self.map,mt)
mt.__index=function (table, key)
return rawget(table,(key.modifier or "").."@#@"..(key.keycode or ""))
end
mt.__newindex=function (table, key, value)
return rawset(table,(key.modifier or "").."@#@"..(key.keycode or ""),value)
end
-- obj definition
obj = obj or {}
setmetatable(obj, self)
self.__index = self
return obj
end
|
require "keys"
Keydef = {
keycode = nil,
modifier = nil,
descr = nil
}
function Keydef:_new(obj)
-- obj definition
obj = obj or {}
setmetatable(obj, self)
self.__index = self
self.__tostring=Keydef.tostring
return obj
end
function Keydef:new(keycode,modifier,descr)
obj = Keydef:_new()
obj.keycode = keycode
obj.modifier = modifier
obj.descr = descr
return obj
end
function Keydef:display()
return ((self.modifier and self.modifier.."+") or "")..(self.descr or "")
end
function Keydef:tostring()
return ((self.modifier and self.modifier.."+") or "").."["..(self.keycode or "").."]"..(self.descr or "")
end
Command = {
keydef = nil,
keygroup = nil,
func = nil,
help = nil,
order = nil
}
function Command:_new(obj)
-- obj definition
obj = obj or {}
setmetatable(obj, self)
self.__index = self
self.__tostring=Command.tostring
return obj
end
function Command:new(keydef, func, help, keygroup, order)
obj = Command:_new()
obj.keydef = keydef
obj.func = func
obj.help = help
obj.keygroup = keygroup
obj.order = order
--print("creating command: ["..tostring(keydef).."] keygroup:["..(keygroup or "").."] help:"..help)
return obj
end
function Command:tostring()
return tostring(self.keydef)..": "..(self.help or "<no help defined>")
end
Commands = {
map = {},
size = 0
}
function Commands:add(keycode,modifier,keydescr,help,func)
if type(keycode) == "table" then
for i=1,#keycode,1 do
local keydef = Keydef:new(keycode[i],modifier,keydescr)
self:_addImpl(keydef,help,func)
end
else
local keydef = Keydef:new(keycode,modifier,keydescr)
self:_addImpl(keydef,help,func)
end
end
function Commands:addGroup(keygroup,keys,help,func)
for _k,keydef in pairs(keys) do
self:_addImpl(keydef,help,func,keygroup)
end
end
function Commands:_addImpl(keydef,help,func,keygroup)
if keydef.modifier==MOD_ANY then
self:addGroup(keygroup or keydef.descr,{Keydef:new(keydef.keycode,nil), Keydef:new(keydef.keycode,MOD_SHIFT), Keydef:new(keydef.keycode,MOD_ALT)},help,func)
elseif keydef.modifier==MOD_SHIFT_OR_ALT then
self:addGroup(keygroup or (MOD_SHIFT.."|"..MOD_ALT.."+"..(keydef.descr or "")),{Keydef:new(keydef.keycode,MOD_SHIFT), Keydef:new(keydef.keycode,MOD_ALT)},help,func)
else
local command = self.map[keydef]
if command == nil then
self.size = self.size + 1
command = Command:new(keydef,func,help,keygroup,self.size)
self.map[keydef] = command
else
command.func = func
command.help = help
command.keygroup = keygroup
end
end
end
function Commands:get(keycode,modifier)
return self.map[Keydef:new(keycode, modifier)]
end
function Commands:getByKeydef(keydef)
return self.map[keydef]
end
function Commands:new(obj)
-- obj definition
obj = obj or {}
obj.map = {}
obj.size = 0
setmetatable(obj, self)
self.__index = self
-- payload
local mt = {}
mt.__index = function(table, key)
return rawget(table,(key.modifier or "").."@#@"..(key.keycode or ""))
end
mt.__newindex = function(table, key, value)
return rawset(table,(key.modifier or "").."@#@"..(key.keycode or ""),value)
end
setmetatable(obj.map, mt)
return obj
end
|
fix: bug in Commands:new()
|
fix: bug in Commands:new()
assign a new map to every created object
|
Lua
|
agpl-3.0
|
houqp/koreader-base,noname007/koreader,frankyifei/koreader-base,Frenzie/koreader,apletnev/koreader-base,pazos/koreader,ashang/koreader,Hzj-jie/koreader-base,frankyifei/koreader-base,mwoz123/koreader,NiLuJe/koreader-base,koreader/koreader-base,NiLuJe/koreader,chrox/koreader,Hzj-jie/koreader,frankyifei/koreader,Frenzie/koreader-base,koreader/koreader-base,Hzj-jie/koreader-base,apletnev/koreader,Frenzie/koreader-base,poire-z/koreader,NickSavage/koreader,NiLuJe/koreader-base,ashhher3/koreader,frankyifei/koreader-base,poire-z/koreader,chihyang/koreader,houqp/koreader-base,Frenzie/koreader,Frenzie/koreader-base,NiLuJe/koreader,koreader/koreader-base,Hzj-jie/koreader-base,robert00s/koreader,NiLuJe/koreader-base,frankyifei/koreader-base,Hzj-jie/koreader-base,apletnev/koreader-base,koreader/koreader-base,koreader/koreader,lgeek/koreader,houqp/koreader-base,Markismus/koreader,Frenzie/koreader-base,houqp/koreader-base,mihailim/koreader,koreader/koreader,apletnev/koreader-base,houqp/koreader,apletnev/koreader-base,NiLuJe/koreader-base
|
e050b58a48fba493920024625933ff6a40422bb4
|
kong/vaults/env/init.lua
|
kong/vaults/env/init.lua
|
local type = type
local upper = string.upper
local kong = kong
local ENV = {}
local function init()
local ffi = require "ffi"
ffi.cdef("extern char **environ;")
local e = ffi.C.environ
if not e then
kong.log.warn("could not access environment variables")
end
local find = string.find
local sub = string.sub
local str = ffi.string
local i = 0
while e[i] ~= nil do
local var = str(e[i])
local p = find(var, "=", nil, true)
if p then
ENV[sub(var, 1, p - 1)] = sub(var, p + 1)
end
i = i + 1
end
end
local function get(conf, resource, version)
local prefix = conf.prefix
if type(prefix) == "string" then
resource = prefix .. resource
end
if version == 2 then
resource = resource .. "_PREVIOUS"
end
return ENV[upper(resource)]
end
return {
VERSION = "1.0.0",
init = init,
get = get,
}
|
local type = type
local gsub = string.gsub
local upper = string.upper
local kong = kong
local ENV = {}
local function init()
local ffi = require "ffi"
ffi.cdef("extern char **environ;")
local e = ffi.C.environ
if not e then
kong.log.warn("could not access environment variables")
end
local find = string.find
local sub = string.sub
local str = ffi.string
local i = 0
while e[i] ~= nil do
local var = str(e[i])
local p = find(var, "=", nil, true)
if p then
ENV[sub(var, 1, p - 1)] = sub(var, p + 1)
end
i = i + 1
end
end
local function get(conf, resource, version)
local prefix = conf.prefix
resource = gsub(resource, "-", "_")
if type(prefix) == "string" then
resource = prefix .. resource
end
resource = upper(resource)
if version == 2 then
resource = resource .. "_PREVIOUS"
end
return ENV[resource]
end
return {
VERSION = "1.0.0",
init = init,
get = get,
}
|
fix(pdk) env vault to replace "-" in resource with "_"
|
fix(pdk) env vault to replace "-" in resource with "_"
### Summary
This will just convert possible `-` in resource name with `_` when looking
up for an environment variable.
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
518cfd360c935f1a074cbf8920daec23d9950a3e
|
src/cosy/loader/lua.lua
|
src/cosy/loader/lua.lua
|
if #setmetatable ({}, { __len = function () return 1 end }) ~= 1
then
error "Cosy requires Lua >= 5.2 to run."
end
return function (t)
t = t or {}
local loader = {}
for k, v in pairs (t) do
loader [k] = v
end
loader.home = os.getenv "HOME" .. "/.cosy/" .. (loader.alias or "default")
local modules = setmetatable ({}, { __mode = "kv" })
loader.hotswap = t.hotswap
or require "hotswap".new {}
loader.require = loader.hotswap.require
loader.load = function (name)
if modules [name] then
return modules [name]
end
local module = loader.require (name) (loader) or true
modules [name] = module
return module
end
loader.logto = t.logto
loader.scheduler = t.scheduler
if not loader.scheduler then
local ok, s = pcall (loader.require, "copas.ev")
if ok then
loader.scheduler = s
else
loader.scheduler = loader.require "copas"
loader.scheduler.autoclose = false
end
end
loader.hotswap.loaded.copas = loader.scheduler
package.loaded.copas = loader.scheduler
loader.coroutine = t.coroutine
or loader.scheduler._coroutine
or loader.require "coroutine.make" ()
_G.coroutine = loader.coroutine
loader.request = t.request
or loader.require "copas.http".request
loader.load "cosy.string"
loader.hotswap.preload ["websocket.bit" ] = function ()
return loader.require "cosy.loader.patches.bit"
end
loader.hotswap.preload ["websocket.server_copas"] = function ()
return loader.require "cosy.loader.patches.server_copas"
end
local path = package.searchpath ("cosy.loader.lua", package.path)
local parts = {}
for part in path:gmatch "[^/]+" do
parts [#parts+1] = part
end
for i = #parts, #parts-5, -1 do
parts [i] = nil
end
loader.prefix = (path:find "^/" and "/" or "") .. table.concat (parts, "/")
os.execute ([[ mkdir -p {{{home}}} ]] % {
home = loader.home,
})
return loader
end
|
if #setmetatable ({}, { __len = function () return 1 end }) ~= 1
then
error "Cosy requires Lua >= 5.2 to run."
end
return function (t)
t = t or {}
local loader = {}
for k, v in pairs (t) do
loader [k] = v
end
loader.home = os.getenv "HOME" .. "/.cosy/" .. (loader.alias or "default")
local modules = setmetatable ({}, { __mode = "kv" })
loader.hotswap = t.hotswap
or require "hotswap".new {}
loader.require = loader.hotswap.require
loader.load = function (name)
if modules [name] then
return modules [name]
end
local module = loader.require (name) (loader) or true
modules [name] = module
return module
end
loader.logto = t.logto
loader.scheduler = t.scheduler
if not loader.scheduler then
local ok, s = pcall (loader.require, "copas.ev")
if ok then
loader.scheduler = s
else
loader.scheduler = loader.require "copas"
loader.scheduler.autoclose = false
end
end
loader.hotswap.loaded.copas = loader.scheduler
package.loaded.copas = loader.scheduler
loader.coroutine = t.coroutine
or loader.scheduler._coroutine
or loader.require "coroutine.make" ()
_G.coroutine = loader.coroutine
loader.request = t.request
or loader.require "copas.http".request
loader.load "cosy.string"
loader.hotswap.preload ["websocket.bit" ] = function ()
return loader.require "cosy.loader.patches.bit"
end
loader.hotswap.preload ["websocket.server_copas"] = function ()
return loader.require "cosy.loader.patches.server_copas"
end
local path = package.searchpath ("cosy.loader.lua", package.path)
local parts = {}
for part in path:gmatch "[^/]+" do
parts [#parts+1] = part
end
parts [#parts] = nil
parts [#parts] = nil
loader.source = (path:find "^/" and "/" or "") .. table.concat (parts, "/")
parts [#parts] = nil
parts [#parts] = nil
parts [#parts] = nil
loader.prefix = (path:find "^/" and "/" or "") .. table.concat (parts, "/")
os.execute ([[ mkdir -p {{{home}}} ]] % {
home = loader.home,
})
return loader
end
|
Loader defines source in addition to prefix.
|
Loader defines source in addition to prefix.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
257a28232be5db0d09e573e80b1471e5d83594c3
|
Hydra/API/repl.lua
|
Hydra/API/repl.lua
|
--- === repl ===
---
--- The REPL (Read-Eval-Print-Loop) is excellent for exploring and experiment with Hydra's API.
---
--- It has all of the familiar readline-like keybindings, including C-b, C-f, M-b, M-f, etc; use C-p and C-n to browse command history.
---
--- Type `help` in the REPL for info on how to use the documentation system.
repl = {}
--- repl.open()
--- Opens a new REPL.
--- In beta versions of Hydra, the REPL was a textgrid; in Hydra 1.0, this function now opens hydra-cli; see https://github.com/sdegutis/hydra-cli
--- When hydra-cli is installed, this function opens it in a new terminal window; see repl.path.
--- When it's not installed, this function opens the github page for hydra-cli which includes installation instructions, as a convenience to the user.
function repl.open()
if not os.execute('open "' .. repl.path .. '"') then
hydra.alert('To use the REPL, install hydra-cli; see the opened website for installation instructions.', 10)
os.execute('open https://github.com/sdegutis/hydra-cli')
end
end
--- repl.path -> string
--- The path to the hydra-cli binary; defaults to "/usr/local/bin/hydra"
repl.path = "/usr/local/bin/hydra"
|
--- === repl ===
---
--- The REPL (Read-Eval-Print-Loop) is excellent for exploring and experiment with Hydra's API.
---
--- It has all of the familiar readline-like keybindings, including C-b, C-f, M-b, M-f, etc; use C-p and C-n to browse command history.
---
--- Type `help` in the REPL for info on how to use the documentation system.
repl = {}
--- repl.open()
--- Opens a new REPL.
--- In beta versions of Hydra, the REPL was a textgrid; in Hydra 1.0, this function now opens hydra-cli; see https://github.com/sdegutis/hydra-cli
--- When hydra-cli is installed, this function opens it in a new terminal window; see repl.path.
--- When it's not installed, this function opens the github page for hydra-cli which includes installation instructions, as a convenience to the user.
--- NOTE: This seems to not work when you're using Bash version 4. In this case, you can use something like this intead:
--- os.execute([[osascript -e 'tell application "Terminal" to do script "/usr/local/bin/hydra" in do script ""']])
function repl.open()
if not os.execute('open "' .. repl.path .. '"') then
hydra.alert('To use the REPL, install hydra-cli; see the opened website for installation instructions.', 10)
os.execute('open https://github.com/sdegutis/hydra-cli')
end
end
--- repl.path -> string
--- The path to the hydra-cli binary; defaults to "/usr/local/bin/hydra"
repl.path = "/usr/local/bin/hydra"
|
Took note of repl.open() bug; fixes #280.
|
Took note of repl.open() bug; fixes #280.
|
Lua
|
mit
|
ocurr/hammerspoon,lowne/hammerspoon,bradparks/hammerspoon,tmandry/hammerspoon,Habbie/hammerspoon,kkamdooong/hammerspoon,CommandPost/CommandPost-App,TimVonsee/hammerspoon,ocurr/hammerspoon,cmsj/hammerspoon,trishume/hammerspoon,joehanchoi/hammerspoon,Hammerspoon/hammerspoon,peterhajas/hammerspoon,nkgm/hammerspoon,heptal/hammerspoon,chrisjbray/hammerspoon,hypebeast/hammerspoon,wvierber/hammerspoon,dopcn/hammerspoon,wsmith323/hammerspoon,hypebeast/hammerspoon,zzamboni/hammerspoon,Stimim/hammerspoon,wsmith323/hammerspoon,junkblocker/hammerspoon,asmagill/hammerspoon,wsmith323/hammerspoon,Stimim/hammerspoon,joehanchoi/hammerspoon,asmagill/hammerspoon,trishume/hammerspoon,Habbie/hammerspoon,TimVonsee/hammerspoon,zzamboni/hammerspoon,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,zzamboni/hammerspoon,hypebeast/hammerspoon,nkgm/hammerspoon,cmsj/hammerspoon,emoses/hammerspoon,joehanchoi/hammerspoon,cmsj/hammerspoon,knl/hammerspoon,Habbie/hammerspoon,kkamdooong/hammerspoon,chrisjbray/hammerspoon,zzamboni/hammerspoon,junkblocker/hammerspoon,Habbie/hammerspoon,lowne/hammerspoon,heptal/hammerspoon,knl/hammerspoon,dopcn/hammerspoon,junkblocker/hammerspoon,peterhajas/hammerspoon,Hammerspoon/hammerspoon,nkgm/hammerspoon,Stimim/hammerspoon,asmagill/hammerspoon,asmagill/hammerspoon,knu/hammerspoon,nkgm/hammerspoon,Hammerspoon/hammerspoon,chrisjbray/hammerspoon,joehanchoi/hammerspoon,knl/hammerspoon,emoses/hammerspoon,junkblocker/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,kkamdooong/hammerspoon,chrisjbray/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,dopcn/hammerspoon,ocurr/hammerspoon,knu/hammerspoon,joehanchoi/hammerspoon,kkamdooong/hammerspoon,latenitefilms/hammerspoon,heptal/hammerspoon,TimVonsee/hammerspoon,chrisjbray/hammerspoon,Habbie/hammerspoon,knu/hammerspoon,TimVonsee/hammerspoon,wvierber/hammerspoon,CommandPost/CommandPost-App,tmandry/hammerspoon,cmsj/hammerspoon,bradparks/hammerspoon,zzamboni/hammerspoon,Stimim/hammerspoon,bradparks/hammerspoon,wvierber/hammerspoon,Stimim/hammerspoon,asmagill/hammerspoon,CommandPost/CommandPost-App,lowne/hammerspoon,bradparks/hammerspoon,Habbie/hammerspoon,junkblocker/hammerspoon,trishume/hammerspoon,wvierber/hammerspoon,chrisjbray/hammerspoon,lowne/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,emoses/hammerspoon,bradparks/hammerspoon,TimVonsee/hammerspoon,wsmith323/hammerspoon,ocurr/hammerspoon,CommandPost/CommandPost-App,lowne/hammerspoon,wsmith323/hammerspoon,kkamdooong/hammerspoon,wvierber/hammerspoon,hypebeast/hammerspoon,cmsj/hammerspoon,hypebeast/hammerspoon,peterhajas/hammerspoon,knu/hammerspoon,heptal/hammerspoon,knl/hammerspoon,heptal/hammerspoon,knu/hammerspoon,peterhajas/hammerspoon,dopcn/hammerspoon,knu/hammerspoon,dopcn/hammerspoon,ocurr/hammerspoon,CommandPost/CommandPost-App,nkgm/hammerspoon,emoses/hammerspoon,zzamboni/hammerspoon,Hammerspoon/hammerspoon,asmagill/hammerspoon,emoses/hammerspoon,latenitefilms/hammerspoon,peterhajas/hammerspoon,knl/hammerspoon,tmandry/hammerspoon
|
8858c4796a5862107e60aec95a936dbbdd12b195
|
whisper.lua
|
whisper.lua
|
local mod = EPGP:NewModule("whisper", "AceEvent-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
local senderMap = {}
function mod:CHAT_MSG_WHISPER(event_name, msg, sender)
if not UnitInRaid("player") then return end
if not EPGP.db.profile.auto_standby_whispers then return end
if not msg:match("epgp standby") then return end
local member = msg:match("epgp standby ([^ ]+)")
if member then
member = member:sub(1,1):upper()..member:sub(2):lower()
else
member = sender
end
senderMap[member] = sender
if not EPGP:GetEPGP(member) then
SendChatMessage(L["%s is not eligible for EP awards"]:format(member),
"WHISPER", nil, sender)
elseif EPGP:IsMemberInAwardList(member) then
SendChatMessage(L["%s is already in the award list"]:format(member),
"WHISPER", nil, sender)
else
EPGP:SelectMember(member)
SendChatMessage(L["%s is added to the award list"]:format(member),
"WHISPER", nil, sender)
end
end
local function SendNotifiesAndClearExtras(event_name, names, reason, amount)
for member, sender in pairs(senderMap) do
if EPGP:IsMemberInExtrasList(member) then
SendChatMessage(L["%+d EP (%s) to %s"]:format(amount, reason, member),
"WHISPER", nil, sender)
-- If whispers are enabled clear the standby list so that people
-- can re-add themselves.
if EPGP.db.profile.auto_standby_whispers then
SendChatMessage(
L["%s is now removed from the award list"]:format(member),
"WHISPER", nil, sender)
EPGP:DeSelectMember(member)
end
end
senderMap[member] = nil
end
end
function mod:OnEnable()
self:RegisterEvent("CHAT_MSG_WHISPER")
EPGP.RegisterCallback(self, "MassEPAward", SendNotifiesAndClearExtras)
end
|
local mod = EPGP:NewModule("whisper", "AceEvent-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
local senderMap = {}
function mod:CHAT_MSG_WHISPER(event_name, msg, sender)
if not UnitInRaid("player") then return end
if not msg:match("epgp standby") then return end
local member = msg:match("epgp standby ([^ ]+)")
if member then
member = member:sub(1,1):upper()..member:sub(2):lower()
else
member = sender
end
senderMap[member] = sender
if not EPGP:GetEPGP(member) then
SendChatMessage(L["%s is not eligible for EP awards"]:format(member),
"WHISPER", nil, sender)
elseif EPGP:IsMemberInAwardList(member) then
SendChatMessage(L["%s is already in the award list"]:format(member),
"WHISPER", nil, sender)
else
EPGP:SelectMember(member)
SendChatMessage(L["%s is added to the award list"]:format(member),
"WHISPER", nil, sender)
end
end
local function SendNotifiesAndClearExtras(event_name, names, reason, amount)
for member, sender in pairs(senderMap) do
if EPGP:IsMemberInExtrasList(member) then
SendChatMessage(L["%+d EP (%s) to %s"]:format(amount, reason, member),
"WHISPER", nil, sender)
SendChatMessage(
L["%s is now removed from the award list"]:format(member),
"WHISPER", nil, sender)
EPGP:DeSelectMember(member)
end
senderMap[member] = nil
end
end
function mod:OnEnable()
self:RegisterEvent("CHAT_MSG_WHISPER")
EPGP.RegisterCallback(self, "MassEPAward", SendNotifiesAndClearExtras)
end
|
Fix standby awards. This fixes issue 330.
|
Fix standby awards. This fixes issue 330.
|
Lua
|
bsd-3-clause
|
sheldon/epgp,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,hayword/tfatf_epgp,sheldon/epgp
|
b0f4ed812f9667586541c36ee15f26afe409a009
|
projects/game003/scripts/app/controllers/Communication.lua
|
projects/game003/scripts/app/controllers/Communication.lua
|
local Communication = class("Communication")
local url = "http://168.168.8.105:8765"
function Communication:ctor()
end
function Communication:onRequestFinished( event )
local request = event.request
if event.name == "complete" then
local code = request:getResponseStatusCode()
if code ~= 200 then
printf("Response not complete, Code : %d",code)
return
end
local response = request:getResponseString()
printf("Server Return Success : %s",response)
else
printf("Request failed, Code:%d, Message:%s", request:getErrorCode(), request:getErrorMessage())
end
end
function Communication:doRequest(params)
local request = network.createHTTPRequest(self.onRequestFinished, url, "POST")
request:addPOSTValue("param",params)
request:start()
end
return Communication
|
local Communication = class("Communication")
local url = "http://168.168.8.105:8765"
function Communication:ctor()
end
function onRequestFinished( event )
local request = event.request
if event.name == "completed" then
local code = request:getResponseStatusCode()
if code ~= 200 then
printf("Response not complete, Code : %d",code)
return
end
local response = request:getResponseString()
printf("Server Return Success : %s",response)
else
printf("Request failed, type:%s Code:%d, Message:%s", event.name, request:getErrorCode(), request:getErrorMessage())
end
end
function Communication:doRequest(params)
local request = network.createHTTPRequest(onRequestFinished, url, "POST")
request:addPOSTValue("param",params)
request:start()
end
return Communication
|
bug修复
|
bug修复
|
Lua
|
mit
|
AdoBeatTheWorld/waytomobile,AdoBeatTheWorld/waytomobile,AdoBeatTheWorld/waytomobile,AdoBeatTheWorld/waytomobile,AdoBeatTheWorld/waytomobile,AdoBeatTheWorld/waytomobile,AdoBeatTheWorld/waytomobile
|
bb0c01757def3163471bf2a94aa081d90fbf3390
|
frontend/fontlist.lua
|
frontend/fontlist.lua
|
local CanvasContext = require("document/canvascontext")
local FontList = {
fontdir = "./fonts",
fontlist = {},
}
--[[
These non-LGC Kindle system fonts fail CRe's moronic header check.
--]]
local kindle_fonts_blacklist = {
["DiwanMuna-Bold.ttf"] = true,
["DiwanMuna-Regular.ttf"] = true,
["HYGothicBold.ttf"] = true,
["HYGothicMedium.ttf"] = true,
["HYMyeongJoBold.ttf"] = true,
["HYMyeongJoMedium.ttf"] = true,
["KindleBlackboxBoldItalic.ttf"] = true,
["KindleBlackboxBold.ttf"] = true,
["KindleBlackboxItalic.ttf"] = true,
["KindleBlackboxRegular.ttf"] = true,
["Kindle_MonospacedSymbol.ttf"] = true,
["Kindle_Symbol.ttf"] = true,
["MTChineseSurrogates.ttf"] = true,
["MYingHeiTBold.ttf"] = true,
["MYingHeiTMedium.ttf"] = true,
["NotoNaskhArabicUI-Bold.ttf"] = true,
["NotoNaskhArabicUI-Regular.ttf"] = true,
["NotoNaskh-Bold.ttf"] = true,
["NotoNaskh-Regular.ttf"] = true,
["NotoSansBengali-Regular.ttf"] = true,
["NotoSansDevanagari-Regular.ttf"] = true,
["NotoSansGujarati-Regular.ttf"] = true,
["NotoSansKannada-Regular.ttf"] = true,
["NotoSansMalayalam-Regular.ttf"] = true,
["NotoSansTamil-Regular.ttf"] = true,
["NotoSansTelugu-Regular.ttf"] = true,
["SakkalKitab-Bold.ttf"] = true,
["SakkalKitab-Regular.ttf"] = true,
["SongTBold.ttf"] = true,
["SongTMedium.ttf"] = true,
["STHeitiBold.ttf"] = true,
["STHeitiMedium.ttf"] = true,
["STSongBold.ttf"] = true,
["STSongMedium.ttf"] = true,
["TBGothicBold_213.ttf"] = true,
["TBGothicMed_213.ttf"] = true,
["TBMinchoBold_213.ttf"] = true,
["TBMinchoMedium_213.ttf"] = true,
["STKaiMedium.ttf"] = true,
["Caecilia_LT_67_Cond_Medium.ttf"] = true,
["Caecilia_LT_68_Cond_Medium_Italic.ttf"] = true,
["Caecilia_LT_77_Cond_Bold.ttf"] = true,
["Caecilia_LT_78_Cond_Bold_Italic.ttf"] = true,
["Helvetica_LT_65_Medium.ttf"] = true,
["Helvetica_LT_66_Medium_Italic.ttf"] = true,
["Helvetica_LT_75_Bold.ttf"] = true,
["Helvetica_LT_76_Bold_Italic.ttf"] = true,
}
local function isInFontsBlacklist(f)
-- write test for this
return CanvasContext.isKindle() and kindle_fonts_blacklist[f]
end
local function getExternalFontDir()
if CanvasContext.isAndroid() or CanvasContext.isDesktop() then
return require("frontend/ui/elements/font_settings"):getPath()
else
return os.getenv("EXT_FONT_DIR")
end
end
local function _readList(target, dir)
-- lfs.dir non-existent directory will give an error, weird!
local ok, iter, dir_obj = pcall(lfs.dir, dir)
if not ok then return end
for f in iter, dir_obj do
local mode = lfs.attributes(dir.."/"..f, "mode")
if mode == "directory" and f ~= "." and f ~= ".." then
_readList(target, dir.."/"..f)
elseif mode == "file" or mode == "link" then
if string.sub(f, 1, 1) ~= "." then
local file_type = string.lower(string.match(f, ".+%.([^.]+)") or "")
if file_type == "ttf" or file_type == "ttc"
or file_type == "cff" or file_type == "otf" then
if not isInFontsBlacklist(f) then
table.insert(target, dir.."/"..f)
end
end
end
end
end
end
function FontList:getFontList()
if #self.fontlist > 0 then return self.fontlist end
_readList(self.fontlist, self.fontdir)
-- multiple paths should be joined with semicolon
for dir in string.gmatch(getExternalFontDir() or "", "([^;]+)") do
_readList(self.fontlist, dir)
end
table.sort(self.fontlist)
return self.fontlist
end
return FontList
|
local CanvasContext = require("document/canvascontext")
local FontList = {
fontdir = "./fonts",
fontlist = {},
}
--[[
These non-LGC Kindle system fonts fail CRe's moronic header check.
Also applies to a number of LGC fonts that have different family names for different styles...
(Those are actually "fixed" via FontConfig in the stock system).
--]]
local kindle_fonts_blacklist = {
["DiwanMuna-Bold.ttf"] = true,
["DiwanMuna-Regular.ttf"] = true,
["HYGothicBold.ttf"] = true,
["HYGothicMedium.ttf"] = true,
["HYMyeongJoBold.ttf"] = true,
["HYMyeongJoMedium.ttf"] = true,
["KindleBlackboxBoldItalic.ttf"] = true,
["KindleBlackboxBold.ttf"] = true,
["KindleBlackboxItalic.ttf"] = true,
["KindleBlackboxRegular.ttf"] = true,
["Kindle_MonospacedSymbol.ttf"] = true,
["Kindle_Symbol.ttf"] = true,
["MTChineseSurrogates.ttf"] = true,
["MYingHeiTBold.ttf"] = true,
["MYingHeiTMedium.ttf"] = true,
["NotoNaskhArabicUI-Bold.ttf"] = true,
["NotoNaskhArabicUI-Regular.ttf"] = true,
["NotoNaskh-Bold.ttf"] = true,
["NotoNaskh-Regular.ttf"] = true,
["NotoSansBengali-Regular.ttf"] = true,
["NotoSansDevanagari-Regular.ttf"] = true,
["NotoSansGujarati-Regular.ttf"] = true,
["NotoSansKannada-Regular.ttf"] = true,
["NotoSansMalayalam-Regular.ttf"] = true,
["NotoSansTamil-Regular.ttf"] = true,
["NotoSansTelugu-Regular.ttf"] = true,
["SakkalKitab-Bold.ttf"] = true,
["SakkalKitab-Regular.ttf"] = true,
["SongTBold.ttf"] = true,
["SongTMedium.ttf"] = true,
["STHeitiBold.ttf"] = true,
["STHeitiMedium.ttf"] = true,
["STSongBold.ttf"] = true,
["STSongMedium.ttf"] = true,
["TBGothicBold_213.ttf"] = true,
["TBGothicMed_213.ttf"] = true,
["TBMinchoBold_213.ttf"] = true,
["TBMinchoMedium_213.ttf"] = true,
["STKaiMedium.ttf"] = true,
["Amazon-Ember-Bold.ttf"] = false,
["Amazon-Ember-BoldItalic.ttf"] = false,
["Amazon-Ember-Heavy.ttf"] = true,
["Amazon-Ember-HeavyItalic.ttf"] = true,
["Amazon-Ember-Medium.ttf"] = true,
["Amazon-Ember-MediumItalic.ttf"] = true,
["Amazon-Ember-Regular.ttf"] = false,
["Amazon-Ember-RegularItalic.ttf"] = false,
["AmazonEmberBold-Bold.ttf"] = true,
["AmazonEmberBold-BoldItalic.ttf"] = true,
["AmazonEmberBold-Italic.ttf"] = true,
["AmazonEmberBold-Regular.ttf"] = true,
["Caecilia_LT_65_Medium.ttf"] = false,
["Caecilia_LT_66_Medium_Italic.ttf"] = false,
["Caecilia_LT_75_Bold.ttf"] = false,
["Caecilia_LT_76_Bold_Italic.ttf"] = false,
["Caecilia_LT_67_Cond_Medium.ttf"] = true,
["Caecilia_LT_68_Cond_Medium_Italic.ttf"] = true,
["Caecilia_LT_77_Cond_Bold.ttf"] = true,
["Caecilia_LT_78_Cond_Bold_Italic.ttf"] = true,
["Futura-Bold.ttf"] = true,
["Futura-BoldOblique.ttf"] = true,
["Helvetica_LT_65_Medium.ttf"] = true,
["Helvetica_LT_66_Medium_Italic.ttf"] = true,
["Helvetica_LT_75_Bold.ttf"] = true,
["Helvetica_LT_76_Bold_Italic.ttf"] = true,
}
local function isInFontsBlacklist(f)
-- write test for this
return CanvasContext.isKindle() and kindle_fonts_blacklist[f]
end
local function getExternalFontDir()
if CanvasContext.isAndroid() or CanvasContext.isDesktop() then
return require("frontend/ui/elements/font_settings"):getPath()
else
return os.getenv("EXT_FONT_DIR")
end
end
local function _readList(target, dir)
-- lfs.dir non-existent directory will give an error, weird!
local ok, iter, dir_obj = pcall(lfs.dir, dir)
if not ok then return end
for f in iter, dir_obj do
local mode = lfs.attributes(dir.."/"..f, "mode")
if mode == "directory" and f ~= "." and f ~= ".." then
_readList(target, dir.."/"..f)
elseif mode == "file" or mode == "link" then
if string.sub(f, 1, 1) ~= "." then
local file_type = string.lower(string.match(f, ".+%.([^.]+)") or "")
if file_type == "ttf" or file_type == "ttc"
or file_type == "cff" or file_type == "otf" then
if not isInFontsBlacklist(f) then
table.insert(target, dir.."/"..f)
end
end
end
end
end
end
function FontList:getFontList()
if #self.fontlist > 0 then return self.fontlist end
_readList(self.fontlist, self.fontdir)
-- multiple paths should be joined with semicolon
for dir in string.gmatch(getExternalFontDir() or "", "([^;]+)") do
_readList(self.fontlist, dir)
end
table.sort(self.fontlist)
return self.fontlist
end
return FontList
|
Blacklist a few Amazon Ember styles to get the main ones to behave. (#5951)
|
Blacklist a few Amazon Ember styles to get the main ones to behave. (#5951)
Fix #5950
|
Lua
|
agpl-3.0
|
mwoz123/koreader,NiLuJe/koreader,Frenzie/koreader,Markismus/koreader,pazos/koreader,mihailim/koreader,poire-z/koreader,Frenzie/koreader,NiLuJe/koreader,poire-z/koreader,koreader/koreader,Hzj-jie/koreader,koreader/koreader
|
a6acf0db4e8aad8c6a6f78d2e5b060a416aa17e1
|
src/bot/bin_game_bot.lua
|
src/bot/bin_game_bot.lua
|
--[[
Global variables:
* int size
* state[0-col][0-row] = value of cell
Functions called from C++:
* int getDeskSize()
* int getWinNumber()
* int getTimeNumber()
* 0-int, 0-int, 0-int, 0-int getIndex()
returns coordinates of joined cells
* output(model)
provides current state of game
model has the following methods:
* int getDeskNumber(point)
returns value of cell
Point has the following fields:
* 0-int col
* 0-int row
Points has the following fields:
* Point p1
* Point p2
type points_table:
is array of instances of Points
Utility lua-functions (not called from C++ directly):
* points_table searchNearbyCells()
returns points_table of all nearby points
* points_table equalCells(points_table, state)
returns table of equal points (filters points_table)
for specified state of desk
* int scoreOf(points)
returns score of the points.
This function counts possible steps on the next step
after applying points and multiplies it with
value of merged cells.
* points bestStep(points_table)
returns the best points for new step from points_table.
Uses scoreOf as scoring function.
* points_table cloneState(original_state)
returns copy of a state
--]]
math = require('math')
local state
local size
function getDeskSize()
size = math.random(2, 9)
state = {}
for i = 0, size - 1 do
state[i] = {}
end
return size
end
function getWinNumber()
return math.random(200, 1000)
end
function getTimeNumber()
return math.random(1, 10)
end
function output(model)
local p = Point()
for col = 0, size -1 do
for row = 0, size - 1 do
state[col][row] = model:getDeskNumber(p)
end
end
end
function getIndex()
local nearby_points = searchNearbyCells()
local equal_points = equalCells(nearby_points, state)
local p = bestStep(equal_points)
return p.p1.col, p.p1.row, p.p2.col, p.p2.row
end
function searchNearbyCells()
local points_table = {}
for col = 0, size - 1 do
for row = 0, size - 1 do
local ps = Points()
ps.p1.col = col
ps.p1.row = row
if col == 0 and row < size - 1 then
ps.p2.col = col
ps.p2.row = row + 1
table.insert(points_table, ps)
elseif col > 0 and row == size - 1 then
ps.p2.col = col - 1
ps.p2.row = row
table.insert(points_table, ps)
elseif col == 0 and row == size - 1 then
break
else
ps.p2.col = col - 1
ps.p2.row = row
table.insert(points_table, ps)
local ps = Points()
ps.p1.col = col
ps.p1.row = row
ps.p2.col = col
ps.p2.row = row + 1
table.insert(points_table, ps)
end
end
end
return points_table
end
function equalCells(pt, st)
local equal_cells = {}
for p = 0, #pt - 1 do
local p1c = pt[p].p1.col
local p1r = pt[p].p1.row
local p2c = pt[p].p2.col
local p2r = pt[p].p2.row
if st[p1c][p1r] == st[p2c][p2r] then
table.insert(equal_cells, pt[p])
end
end
return equal_cells
end
function bestStep(pt)
local max_score = scoreOf(pt[0])
local s
for p = 1, #pt - 1 do
if scoreOf(pt[p]) > max_score then
max_score = scoreOf(pt[p])
s = p
end
end
return pt[s]
end
function scoreOf(points)
local merge_cells = state[points.p1.col][points.p1.row] * 2
local steps_number = countSteps(points)
local result = merge_cells * steps_number
return result
end
function countSteps(pts)
local future_state = cloneState(state)
local i1c = pts.p1.col
local i1r = pts.p1.row
local i2c = pts.p2.col
local i2r = pts.p2.row
future_state[i2c][i2r] = future_state[i2c][i2r] * 2
while i1c ~= size - 1 do
future_state[i1c][i1r] = future_state[i1c + 1][i1r]
i1c = i1c + 1
end
future_state[i1c][i1r] = 2
pt = searchNearbyCells()
eq_pt = equalCells(pt, future_state)
return #eq_pt
end
function cloneState(state)
local pt = {}
for col = 0, size - 1 do
pt[col] = {}
for row = 0, size - 1 do
pt[col][row] = state[col][row]
end
end
return pt
end
|
--[[
Global variables:
* int size
* state[0-col][0-row] = value of cell
Functions called from C++:
* int getDeskSize()
* int getWinNumber()
* int getTimeNumber()
* 0-int, 0-int, 0-int, 0-int getIndex()
returns coordinates of joined cells
* output(model)
provides current state of game
model has the following methods:
* int getDeskNumber(point)
returns value of cell
Point has the following fields:
* 0-int col
* 0-int row
Points has the following fields:
* Point p1
* Point p2
type points_table:
is array of instances of Points
Utility lua-functions (not called from C++ directly):
* points_table searchNearbyCells()
returns points_table of all nearby points
* points_table equalCells(points_table, state)
returns table of equal points (filters points_table)
for specified state of desk
* int scoreOf(points)
returns score of the points.
This function counts possible steps on the next step
after applying points and multiplies it with
value of merged cells.
* points bestStep(points_table)
returns the best points for new step from points_table.
Uses scoreOf as scoring function.
* points_table cloneState(original_state)
returns copy of a state
--]]
math = require('math')
local state
local size
function getDeskSize()
size = math.random(2, 9)
state = {}
for i = 0, size - 1 do
state[i] = {}
end
return size
end
function getWinNumber()
return math.random(200, 1000)
end
function getTimeNumber()
return math.random(1, 10)
end
function output(model)
local p = Point()
for col = 0, size - 1 do
for row = 0, size - 1 do
p.col = col
p.row = row
state[col][row] = model:getDeskNumber(p)
end
end
end
function getIndex()
local nearby_points = searchNearbyCells()
local equal_points = equalCells(nearby_points, state)
local p = bestStep(equal_points)
return p.p1.col, p.p1.row, p.p2.col, p.p2.row
end
function searchNearbyCells()
local points_table = {}
for col = 0, size - 1 do
for row = 0, size - 1 do
local ps = Points()
ps.p1.col = col
ps.p1.row = row
if col == 0 and row < size - 1 then
ps.p2.col = col
ps.p2.row = row + 1
table.insert(points_table, ps)
elseif col > 0 and row == size - 1 then
ps.p2.col = col - 1
ps.p2.row = row
table.insert(points_table, ps)
elseif col == 0 and row == size - 1 then
break
else
ps.p2.col = col - 1
ps.p2.row = row
table.insert(points_table, ps)
local ps = Points()
ps.p1.col = col
ps.p1.row = row
ps.p2.col = col
ps.p2.row = row + 1
table.insert(points_table, ps)
end
end
end
return points_table
end
function equalCells(pt, st)
local equal_cells = {}
for _, p in ipairs(pt) do
local p1c = p.p1.col
local p1r = p.p1.row
local p2c = p.p2.col
local p2r = p.p2.row
if st[p1c][p1r] == st[p2c][p2r] then
table.insert(equal_cells, p)
end
end
return equal_cells
end
function bestStep(pt)
local best_points = pt[1]
local max_score = scoreOf(best_points)
for _, p in ipairs(pt) do
if scoreOf(p) > max_score then
max_score = scoreOf(p)
best_points = p
end
end
return best_points
end
function scoreOf(points)
local merge_cells = state[points.p1.col][points.p1.row] * 2
local steps_number = countSteps(points)
local result = merge_cells * steps_number
return result
end
function countSteps(pts)
local future_state = cloneState(state)
local i1c = pts.p1.col
local i1r = pts.p1.row
local i2c = pts.p2.col
local i2r = pts.p2.row
future_state[i2c][i2r] = future_state[i2c][i2r] * 2
while i1c ~= size - 1 do
future_state[i1c][i1r] = future_state[i1c + 1][i1r]
i1c = i1c + 1
end
future_state[i1c][i1r] = 2
pt = searchNearbyCells()
eq_pt = equalCells(pt, future_state)
return #eq_pt
end
function cloneState(state)
local pt = {}
for col = 0, size - 1 do
pt[col] = {}
for row = 0, size - 1 do
pt[col][row] = state[col][row]
end
end
return pt
end
|
Fix mistakes
|
Fix mistakes
|
Lua
|
mit
|
zer0main/bin_game_mvc
|
d5d47a90e2273bd120fdf33a8f1b92c598155f2b
|
tests/x.lua
|
tests/x.lua
|
di.spawn.run({"Xvfb", ":1", "-screen", "0", "1600x1200x24+32"}, true)
di.spawn.run({"Xvfb", ":2", "-screen", "0", "1600x1200x24+32"}, true)
di.env.DISPLAY=":1"
di.event.timer(0.2).on("elapsed", true, function()
-- wait a awhile for Xvfb to start
o = di.xorg.connect()
if o.errmsg then
print(o.errmsg)
di.exit(1)
return
end
print(o.xrdb)
o.xrdb = "Xft.dpi:\t192"
print(o.xrdb)
xi = o.xinput
xi.on("new-device", function(dev)
print(string.format("new device %s %s %s %d", dev.type, dev.use, dev.name, dev.id))
end)
o.key.new({"mod4"}, "d", false).on("pressed", function()
print("pressed")
end)
-- test the new-device event
di.spawn.run({"xinput", "create-master", "b"}, true)
-- test key events
di.spawn.run({"xdotool", "key", "super+d"}, true)
o.randr.on("view-change", function()
print("view-change")
end)
o.randr.on("output-change", function()
print("output-change")
end)
outs = o.randr.outputs
for _, i in pairs(outs) do
print(i.name, i.backlight, i.max_backlight)
vc = i.view.config
print(vc.x, vc.y, vc.width, vc.height, vc.rotation, vc.reflection)
i.view.config = vc
print(i.view.outputs[1].name)
end
print("Modes:")
modes = o.randr.modes
for _, i in pairs(modes) do
print(i.width, i.height, i.id)
end
di.event.timer(1).on("elapsed", true, function()
o.disconnect()
o = di.xorg.connect_to(":2")
if o.errmsg then
print(o.errmsg)
di.exit(1)
return
end
di.quit()
end)
end)
|
di.load_plugin("./plugins/xorg/di_xorg.so")
di.spawn.run({"Xvfb", ":1", "-screen", "0", "1600x1200x24+32"}, true)
di.spawn.run({"Xvfb", ":2", "-screen", "0", "1600x1200x24+32"}, true)
di.env.DISPLAY=":1"
di.event.timer(0.2).on("elapsed", true, function()
-- wait a awhile for Xvfb to start
o = di.xorg.connect()
if o.errmsg then
print(o.errmsg)
di.exit(1)
return
end
print(o.xrdb)
o.xrdb = "Xft.dpi:\t192"
print(o.xrdb)
xi = o.xinput
xi.on("new-device", function(dev)
print(string.format("new device %s %s %s %d", dev.type, dev.use, dev.name, dev.id))
end)
o.key.new({"mod4"}, "d", false).on("pressed", function()
print("pressed")
end)
-- test the new-device event
di.spawn.run({"xinput", "create-master", "b"}, true)
-- test key events
di.spawn.run({"xdotool", "key", "super+d"}, true)
o.randr.on("view-change", function()
print("view-change")
end)
o.randr.on("output-change", function()
print("output-change")
end)
outs = o.randr.outputs
for _, i in pairs(outs) do
print(i.name, i.backlight, i.max_backlight)
vc = i.view.config
print(vc.x, vc.y, vc.width, vc.height, vc.rotation, vc.reflection)
i.view.config = vc
print(i.view.outputs[1].name)
end
print("Modes:")
modes = o.randr.modes
for _, i in pairs(modes) do
print(i.width, i.height, i.id)
end
di.event.timer(1).on("elapsed", true, function()
o.disconnect()
o = di.xorg.connect_to(":2")
if o.errmsg then
print(o.errmsg)
di.exit(1)
return
end
di.quit()
end)
end)
|
Fix missing load_plugin
|
Fix missing load_plugin
|
Lua
|
mpl-2.0
|
yshui/deai,yshui/deai,yshui/deai
|
6528d5684a2886e0000322aebff682847f1f3b23
|
lib/core/src/quanta/core/entity/Entity.lua
|
lib/core/src/quanta/core/entity/Entity.lua
|
u8R""__RAW_STRING__(
local U = require "togo.utility"
local O = require "Quanta.Object"
local Match = require "Quanta.Match"
local Measurement = require "Quanta.Measurement"
local M = U.module(...)
U.class(M)
function M:__init(name)
self.is_category = false
self.name = nil
self.name_hash = O.NAME_NULL
self.description = nil
self.compositor = nil
self.sources = {}
self.sources[0] = M.Source()
self.universe = nil
self.parent = nil
self.children = {}
self:set_name(name)
end
function M:set_name(name)
U.type_assert(name, "string")
U.assert(#name > 0, "name cannot be empty")
if self.parent then
self.parent.children[self.name_hash] = nil
end
self.name = name
self.name_hash = O.hash_name(name)
if self.parent then
self.parent:add_key(self)
end
end
function M:set_compositor(compositor)
U.type_assert(compositor, Match.Tree)
self.compositor = compositor
end
function M:has_source()
return #self.sources > 0
end
function M:set_source(i, source)
U.type_assert(i, "number")
U.type_assert(source, M.Source)
self.sources[i] = source
return source
end
function M:add_source(source)
U.type_assert(source, M.Source)
table.insert(self.sources, source)
return source
end
function M:source(i)
U.type_assert(i, "number", true)
if i == nil then
return self.sources[0]
end
return self.sources[i]
end
function M:add(entity)
U.type_assert(entity, M)
U.assert(self.universe)
if entity.parent == self then
return
end
U.assert(entity.parent == nil)
entity.universe = self.universe
entity.parent = self
self:add_key(entity)
if not entity.compositor and self.compositor then
entity.compositor = self.compositor
end
return entity
end
function M:add_key(entity)
U.type_assert(entity, M)
local current = self.children[entity.name_hash]
if current then
if current == entity then
return
end
U.assert(
false,
"entity name '%s' is not unique by hash (%d => '%s')",
entity.name, entity.name_hash, current.name
)
end
self.children[entity.name_hash] = entity
end
function M:find(name)
U.type_assert_any(name, {"string", "number"})
local name_hash
if U.is_type(name, "string") then
name_hash = O.hash_name(name)
else
name_hash = name
end
return self.children[name_hash]
end
M.Category = {}
U.set_functable(M.Category, function(_, name)
local e = M(name)
e.is_category = true
e.sources = {}
return e
end)
function M.Category:set_description(description)
U.type_assert(description, "string")
self.description = description
end
function M.Category:description()
return self.description
end
M.Universe = {}
U.set_functable(M.Universe, function(_, name)
local e = M.Category(name)
e.universe = e
return e
end)
function M.is_category(entity)
return U.is_type(entity, Entity) and entity.is_category
end
function M.is_universe(entity)
return M.is_category(entity) and entity.universe == entity.universe
end
M.Source = U.class(M.Source)
function M.Source:__init()
self.description = ""
self.label = nil
self.author = nil
self.vendors = {}
self.base_model = nil
self.model = nil
self.composition = {}
end
function M.Source:set_description(description)
U.type_assert(description, "string")
self.description = description
end
function M.Source:set_label(label)
U.type_assert(label, "string")
self.label = label
end
function M.Source:set_author(author)
U.type_assert(author, M.Place)
self.author = author
end
function M.Source:set_base_model(base_model)
U.type_assert(base_model, M.Model)
self.base_model = base_model
end
function M.Source:set_model(model)
U.type_assert(model, M.Model)
self.model = model
end
function M.Source:has_vendor()
return self.vendor[0] ~= nil or #self.vendors
end
function M.Source:set_vendor(i, vendor)
U.type_assert(i, "number")
U.type_assert(vendor, M.Place)
self.vendors[i] = vendor
return vendor
end
function M.Source:add_vendor(vendor)
U.type_assert(vendor, M.Place)
table.insert(self.vendors, vendor)
return vendor
end
function M.Source:vendor(i)
U.type_assert(i, "number")
return self.vendors[i]
end
M.Place = U.class(M.Place)
function M.Place:__init()
self.name = nil
self.address = nil
end
function M.Place:set_name(name)
U.type_assert(name, "string", true)
self.name = name
end
function M.Place:set_address(address)
U.type_assert(address, "string", true)
self.address = address
end
M.Model = U.class(M.Model)
function M.Model:__init()
self.name = nil
self.id = nil
end
function M.Model:set_name(name)
U.type_assert(name, "string", true)
self.name = name
end
function M.Model:set_id(id)
U.type_assert(id, "string", true)
self.id = id
end
return M
)"__RAW_STRING__"
|
u8R""__RAW_STRING__(
local U = require "togo.utility"
local O = require "Quanta.Object"
local Match = require "Quanta.Match"
local Measurement = require "Quanta.Measurement"
local M = U.module(...)
M.Type = {
generic = 1,
category = 2,
universe = 3,
}
U.class(M)
function M:__init(name)
self.type = M.Type.generic
self.name = nil
self.name_hash = O.NAME_NULL
self.description = nil
self.compositor = nil
self.sources = {}
self.sources[0] = M.Source()
self.universe = nil
self.parent = nil
self.children = {}
self:set_name(name)
end
function M:is_category()
return U.is_type(self, M) and self.type == M.Type.category
end
function M:is_universe()
return U.is_type(self, M) and self.type == M.Type.universe
end
function M:set_name(name)
U.type_assert(name, "string")
U.assert(#name > 0, "name cannot be empty")
if self.parent then
self.parent.children[self.name_hash] = nil
end
self.name = name
self.name_hash = O.hash_name(name)
if self.parent then
self.parent:add_key(self)
end
end
function M:set_compositor(compositor)
U.type_assert(compositor, Match.Tree)
self.compositor = compositor
end
function M:has_source()
return #self.sources > 0
end
function M:set_source(i, source)
U.type_assert(i, "number")
U.type_assert(source, M.Source)
self.sources[i] = source
return source
end
function M:add_source(source)
U.type_assert(source, M.Source)
table.insert(self.sources, source)
return source
end
function M:source(i)
U.type_assert(i, "number", true)
if i == nil then
return self.sources[0]
end
return self.sources[i]
end
function M:add(entity)
U.type_assert(entity, M)
U.assert(self.universe)
if entity.parent == self then
return
end
U.assert(entity.parent == nil)
entity.universe = self.universe
entity.parent = self
self:add_key(entity)
if not entity.compositor and self.compositor then
entity.compositor = self.compositor
end
return entity
end
function M:add_key(entity)
U.type_assert(entity, M)
local current = self.children[entity.name_hash]
if current then
if current == entity then
return
end
U.assert(
false,
"entity name '%s' is not unique by hash (%d => '%s')",
entity.name, entity.name_hash, current.name
)
end
self.children[entity.name_hash] = entity
end
function M:find(name)
U.type_assert_any(name, {"string", "number"})
local name_hash
if U.is_type(name, "string") then
name_hash = O.hash_name(name)
else
name_hash = name
end
return self.children[name_hash]
end
M.Category = {}
U.set_functable(M.Category, function(_, name)
local e = M(name)
e.type = M.Type.category
e.sources = {}
return e
end)
function M.Category:set_description(description)
U.type_assert(description, "string")
self.description = description
end
function M.Category:description()
return self.description
end
M.Universe = {}
U.set_functable(M.Universe, function(_, name)
local e = M.Category(name)
e.type = M.Type.universe
e.universe = e
return e
end)
M.Source = U.class(M.Source)
function M.Source:__init()
self.description = ""
self.label = nil
self.author = nil
self.vendors = {}
self.base_model = nil
self.model = nil
self.composition = {}
end
function M.Source:set_description(description)
U.type_assert(description, "string")
self.description = description
end
function M.Source:set_label(label)
U.type_assert(label, "string")
self.label = label
end
function M.Source:set_author(author)
U.type_assert(author, M.Place)
self.author = author
end
function M.Source:set_base_model(base_model)
U.type_assert(base_model, M.Model)
self.base_model = base_model
end
function M.Source:set_model(model)
U.type_assert(model, M.Model)
self.model = model
end
function M.Source:has_vendor()
return self.vendor[0] ~= nil or #self.vendors
end
function M.Source:set_vendor(i, vendor)
U.type_assert(i, "number")
U.type_assert(vendor, M.Place)
self.vendors[i] = vendor
return vendor
end
function M.Source:add_vendor(vendor)
U.type_assert(vendor, M.Place)
table.insert(self.vendors, vendor)
return vendor
end
function M.Source:vendor(i)
U.type_assert(i, "number")
return self.vendors[i]
end
M.Place = U.class(M.Place)
function M.Place:__init()
self.name = nil
self.address = nil
end
function M.Place:set_name(name)
U.type_assert(name, "string", true)
self.name = name
end
function M.Place:set_address(address)
U.type_assert(address, "string", true)
self.address = address
end
M.Model = U.class(M.Model)
function M.Model:__init()
self.name = nil
self.id = nil
end
function M.Model:set_name(name)
U.type_assert(name, "string", true)
self.name = name
end
function M.Model:set_id(id)
U.type_assert(id, "string", true)
self.id = id
end
return M
)"__RAW_STRING__"
|
lib/core/entity/Entity.lua: simplified types; fixed type checks.
|
lib/core/entity/Entity.lua: simplified types; fixed type checks.
|
Lua
|
mit
|
komiga/quanta,komiga/quanta,komiga/quanta
|
2497eb9ce7e9ed00d0cfd7fdda52d1d0be1cacf7
|
roles/neovim/config/lua/plugins/cmp.lua
|
roles/neovim/config/lua/plugins/cmp.lua
|
-- Setup nvim-cmp.
local cmp = require('cmp')
local lspkind = require('lspkind')
local source_mapping = {
buffer = "[Buffer]",
nvim_lsp = "[LSP]",
nvim_lua = "[Lua]",
cmp_tabnine = "[TN]",
path = "[Path]",
cmp_git = "[Git]",
}
cmp.setup({
snippet = {
expand = function(args)
require('luasnip').lsp_expand(args.body) -- For `luasnip` users.
end,
},
mapping = {
['<C-d>'] = cmp.mapping(cmp.mapping.scroll_docs(-4), { 'i', 'c' }),
['<C-f>'] = cmp.mapping(cmp.mapping.scroll_docs(4), { 'i', 'c' }),
["<c-space>"] = cmp.mapping {
i = cmp.mapping.complete(),
c = function(
_ --[[fallback]]
)
if cmp.visible() then
if not cmp.confirm { select = true } then
return
end
else
cmp.complete()
end
end,
},
-- No automatic tab completion
--["<tab>"] = cmp.mapping {
--i = cmp.config.disable,
--c = function(fallback)
--fallback()
--end,
--},
-- With automatic tab completion
-- First you have to just promise to read `:help ins-completion`.
["<Tab>"] = function(fallback)
if cmp.visible() then
cmp.select_next_item()
else
fallback()
end
end,
["<S-Tab>"] = function(fallback)
if cmp.visible() then
cmp.select_prev_item()
else
fallback()
end
end,
["<c-y>"] = cmp.mapping(
cmp.mapping.confirm {
behavior = cmp.ConfirmBehavior.Insert,
select = true,
},
{ "i", "c" }
),
['<C-e>'] = cmp.mapping({
i = cmp.mapping.abort(),
c = cmp.mapping.close(),
}),
['<CR>'] = cmp.mapping.confirm({ behavior = cmp.ConfirmBehavior.Replace, select = true }),
},
sources = cmp.config.sources({
{ name = "cmp_git" },
{ name = 'nvim_lsp' },
{ name = 'luasnip' },
{ name = 'nvim_lua' },
{ name = 'path' },
{ name = 'cmp_tabnine' },
}, {
{ name = 'buffer', keyword_length = 4 },
}),
formatting = {
format = function(entry, vim_item)
vim_item.kind = lspkind.presets.default[vim_item.kind]
local menu = source_mapping[entry.source.name]
if entry.source.name == 'cmp_tabnine' then
if entry.completion_item.data ~= nil and entry.completion_item.data.detail ~= nil then
menu = entry.completion_item.data.detail .. ' ' .. menu
end
vim_item.kind = ''
end
vim_item.menu = menu
return vim_item
end
},
})
require("cmp_git").setup()
-- Use buffer source for `/` (if you enabled `native_menu`, this won't work anymore).
cmp.setup.cmdline('/', {
sources = {
{ name = 'buffer' }
}
})
-- Use cmdline & path source for ':' (if you enabled `native_menu`, this won't work anymore).
cmp.setup.cmdline(":", {
completion = {
autocomplete = false,
},
sources = cmp.config.sources({
{
name = "path",
},
}, {
{
name = "cmdline",
max_item_count = 20,
keyword_length = 4,
},
}),
})
-- Setup lspconfig.
local capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities())
-- Replace <YOUR_LSP_SERVER> with each lsp server you've enabled.
-- require('lspconfig')['<YOUR_LSP_SERVER>'].setup {
-- capabilities = capabilities
-- }
local function prequire(...)
local status, lib = pcall(require, ...)
if (status) then return lib end
return nil
end
local luasnip = prequire('luasnip')
local t = function(str)
return vim.api.nvim_replace_termcodes(str, true, true, true)
end
local check_back_space = function()
local col = vim.fn.col('.') - 1
if col == 0 or vim.fn.getline('.'):sub(col, col):match('%s') then
return true
else
return false
end
end
_G.tab_complete = function()
if cmp and cmp.visible() then
cmp.select_next_item()
elseif luasnip and luasnip.expand_or_jumpable() then
return t("<Plug>luasnip-expand-or-jump")
elseif check_back_space() then
return t "<Tab>"
else
cmp.complete()
end
return ""
end
_G.s_tab_complete = function()
if cmp and cmp.visible() then
cmp.select_prev_item()
elseif luasnip and luasnip.jumpable(-1) then
return t("<Plug>luasnip-jump-prev")
else
return t "<S-Tab>"
end
return ""
end
|
-- Setup nvim-cmp.
local cmp = require('cmp')
local lspkind = require('lspkind')
local source_mapping = {
buffer = "[Buffer]",
nvim_lsp = "[LSP]",
nvim_lua = "[Lua]",
cmp_tabnine = "[TN]",
path = "[Path]",
cmp_git = "[Git]",
}
cmp.setup({
snippet = {
expand = function(args)
require('luasnip').lsp_expand(args.body) -- For `luasnip` users.
end,
},
mapping = {
['<C-d>'] = cmp.mapping(cmp.mapping.scroll_docs(-4), { 'i', 'c' }),
['<C-f>'] = cmp.mapping(cmp.mapping.scroll_docs(4), { 'i', 'c' }),
["<c-space>"] = cmp.mapping {
i = cmp.mapping.complete(),
c = function(
_ --[[fallback]]
)
if cmp.visible() then
if not cmp.confirm { select = true } then
return
end
else
cmp.complete()
end
end,
},
-- No automatic tab completion
-- ["<Tab>"] = cmp.mapping {
-- i = cmp.config.disable,
-- c = function(fallback)
-- fallback()
-- end,
-- },
-- With automatic tab completion
-- First you have to just promise to read `:help ins-completion`.
["<Tab>"] = cmp.mapping {
i = function(fallback)
if cmp.visible() then
cmp.select_next_item()
else
fallback()
end
end,
c = function(fallback)
fallback()
end
},
["<S-Tab>"] = cmp.mapping {
i = function(fallback)
if cmp.visible() then
cmp.select_prev_item()
else
fallback()
end
end,
c = function(fallback)
fallback()
end
},
["<c-y>"] = cmp.mapping(
cmp.mapping.confirm {
behavior = cmp.ConfirmBehavior.Insert,
select = true,
},
{ "i", "c" }
),
['<C-e>'] = cmp.mapping({
i = cmp.mapping.abort(),
c = cmp.mapping.close(),
}),
['<CR>'] = cmp.mapping.confirm({ behavior = cmp.ConfirmBehavior.Replace, select = true }),
},
sources = cmp.config.sources({
{ name = "cmp_git" },
{ name = 'nvim_lsp' },
{ name = 'luasnip' },
{ name = 'nvim_lua' },
{ name = 'path' },
{ name = 'cmp_tabnine' },
}, {
{ name = 'buffer', keyword_length = 4 },
}),
formatting = {
format = function(entry, vim_item)
vim_item.kind = lspkind.presets.default[vim_item.kind]
local menu = source_mapping[entry.source.name]
if entry.source.name == 'cmp_tabnine' then
if entry.completion_item.data ~= nil and entry.completion_item.data.detail ~= nil then
menu = entry.completion_item.data.detail .. ' ' .. menu
end
vim_item.kind = ''
end
vim_item.menu = menu
return vim_item
end
},
})
require("cmp_git").setup()
-- Use buffer source for `/` (if you enabled `native_menu`, this won't work anymore).
cmp.setup.cmdline('/', {
sources = {
{ name = 'buffer' }
}
})
-- Use cmdline & path source for ':' (if you enabled `native_menu`, this won't work anymore).
cmp.setup.cmdline(":", {
completion = {
autocomplete = false,
},
sources = cmp.config.sources({
{
name = "path",
},
}, {
{
name = "cmdline",
max_item_count = 20,
keyword_length = 4,
},
}),
})
-- Setup lspconfig.
local capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities())
-- Replace <YOUR_LSP_SERVER> with each lsp server you've enabled.
-- require('lspconfig')['<YOUR_LSP_SERVER>'].setup {
-- capabilities = capabilities
-- }
local function prequire(...)
local status, lib = pcall(require, ...)
if (status) then return lib end
return nil
end
local luasnip = prequire('luasnip')
local t = function(str)
return vim.api.nvim_replace_termcodes(str, true, true, true)
end
local check_back_space = function()
local col = vim.fn.col('.') - 1
if col == 0 or vim.fn.getline('.'):sub(col, col):match('%s') then
return true
else
return false
end
end
_G.tab_complete = function()
if cmp and cmp.visible() then
cmp.select_next_item()
elseif luasnip and luasnip.expand_or_jumpable() then
return t("<Plug>luasnip-expand-or-jump")
elseif check_back_space() then
return t "<Tab>"
else
cmp.complete()
end
return ""
end
_G.s_tab_complete = function()
if cmp and cmp.visible() then
cmp.select_prev_item()
elseif luasnip and luasnip.jumpable(-1) then
return t("<Plug>luasnip-jump-prev")
else
return t "<S-Tab>"
end
return ""
end
|
Fixed autocomplete in commandline with cmp
|
Fixed autocomplete in commandline with cmp
|
Lua
|
mit
|
Irubataru/dotfiles,Irubataru/dotfiles,Irubataru/dotfiles
|
66ac24ad35e5b1e56793fede68719e276d5136ef
|
Modules/Legacy/qGUI/3DRender/ModelRender3D.lua
|
Modules/Legacy/qGUI/3DRender/ModelRender3D.lua
|
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local NevermoreEngine = require(ReplicatedStorage:WaitForChild("NevermoreEngine"))
local LoadCustomLibrary = NevermoreEngine.LoadLibrary
local ScreenSpace = LoadCustomLibrary("ScreenSpace")
-- @author Quenty
local ModelRender3D = {}
ModelRender3D.__index = ModelRender3D
function ModelRender3D.new()
local self = setmetatable({}, ModelRender3D)
self.RelativeRotation = CFrame.new()
self.Scale = 1
return self
end
function ModelRender3D:SetGui(Gui)
self.Gui = Gui
end
function ModelRender3D:SetModel(Model)
self.Model = Model
if Model then
assert(Model.PrimaryPart, "Model needs primary part")
self.PrimaryPart = Model.PrimaryPart
else
self.PrimaryPart = nil
end
end
function ModelRender3D:GetModel()
return self.Model
end
function ModelRender3D:SetRelativeRotation(CFrameRotation)
self.RelativeRotation = CFrameRotation or error("No CFrame rotation")
end
function ModelRender3D:GetModelWidth()
local ModelSize = self.Model:GetExtentsSize() * self.Scale
return math.max(ModelSize.X, ModelSize.Y, ModelSize.Z)--ModelSize.X-- math.sqrt(ModelSize.X^2+ModelSize.Z^2)
end
function ModelRender3D:UseScale(Scale)
-- @param Scale Can be a Vector3 or Number value
self.Scale = Scale -- A zoom factor, used to compensate when GetExtentsSize fails.
end
function ModelRender3D:GetPrimaryCFrame()
if self.Gui and self.Model then
local Frame = self.Gui
--local ModelSize = self.Model:GetExtentsSize() * self.Scale
local ModelSize = self.PrimaryPart.Size * self.Scale
local FrameAbsoluteSize = Frame.AbsoluteSize
local FrameCenter = Frame.AbsolutePosition + FrameAbsoluteSize/2 -- Center of the frame.
local Depth = ScreenSpace.GetDepthForWidth(FrameAbsoluteSize.X, math.max(ModelSize.X, ModelSize.Y, ModelSize.Z))--math.max(ModelSize.X, ModelSize.Z))
local Position = ScreenSpace.ScreenToWorld(FrameCenter.X, FrameCenter.Y, Depth)
local AdorneeCFrame = workspace.CurrentCamera.CoordinateFrame *
CFrame.new(Position)--[[ * -- Transform by camera coordinates
CFrame.new(0, 0, -ModelSize.Z/2) -- And take out the part size factor. --]]
return AdorneeCFrame * self.RelativeRotation
else
warn("ModelRender3D cannot update model render, GUI or model aren't there.")
end
end
return ModelRender3D
|
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local NevermoreEngine = require(ReplicatedStorage:WaitForChild("NevermoreEngine"))
local LoadCustomLibrary = NevermoreEngine.LoadLibrary
local ScreenSpace = LoadCustomLibrary("ScreenSpace")
-- @author Quenty
local ModelRender3D = {}
ModelRender3D.__index = ModelRender3D
function ModelRender3D.new()
local self = setmetatable({}, ModelRender3D)
self.RelativeRotation = CFrame.new()
self.Scale = 1
return self
end
function ModelRender3D:SetGui(Gui)
self.Gui = Gui
end
function ModelRender3D:SetModel(Model)
self.Model = Model
if Model then
assert(Model.PrimaryPart, "Model needs primary part")
self.PrimaryPart = Model.PrimaryPart
else
self.PrimaryPart = nil
end
end
function ModelRender3D:GetModel()
return self.Model
end
function ModelRender3D:SetRelativeRotation(CFrameRotation)
self.RelativeRotation = CFrameRotation or error("No CFrame rotation")
end
function ModelRender3D:GetModelWidth()
local ModelSize = self.Model:GetExtentsSize() * self.Scale
return math.max(ModelSize.X, ModelSize.Y, ModelSize.Z)--ModelSize.X-- math.sqrt(ModelSize.X^2+ModelSize.Z^2)
end
function ModelRender3D:UseScale(Scale)
-- @param Scale Can be a Vector3 or Number value
self.Scale = Scale -- A zoom factor, used to compensate when GetExtentsSize fails.
end
function ModelRender3D:GetPrimaryCFrame()
if self.Gui and self.Model then
local Frame = self.Gui
local FrameAbsoluteSize = Frame.AbsoluteSize
local FrameCenter = Frame.AbsolutePosition + FrameAbsoluteSize/2 -- Center of the frame.
local Depth = ScreenSpace.GetDepthForWidth(FrameAbsoluteSize.X, self:GetModelWidth())
local Position = ScreenSpace.ScreenToWorld(FrameCenter.X, FrameCenter.Y, Depth)
local AdorneeCFrame = workspace.CurrentCamera.CoordinateFrame
* (CFrame.new(Position, Vector3.new(0, 0, 0)) * self.RelativeRotation)
return AdorneeCFrame
else
warn("ModelRender3D cannot update model render, GUI or model aren't there.")
end
end
return ModelRender3D
|
Fix ModelRender3D to lock to camera, fixes distortion
|
Fix ModelRender3D to lock to camera, fixes distortion
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
f5235d5bc97c42803d31e3298b9dfd6868dbe638
|
hostinfo/packages.lua
|
hostinfo/packages.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 HostInfo = require('./base').HostInfo
local fmt = require('string').format
local los = require('los')
local sigar = require('sigar')
local table = require('table')
local execFileToBuffers = require('./misc').execFileToBuffers
--[[ Packages Variables ]]--
local Info = HostInfo:extend()
function Info:initialize()
HostInfo.initialize(self)
end
function Info:run(callback)
if los.type() ~= 'linux' then
self._error = 'Unsupported OS for Packages'
callback()
return
end
local function execCb(err, exitcode, stdout_data, stderr_data)
if exitcode ~= 0 then
self._error = fmt("Packages exited with a %d exitcode", exitcode)
callback()
return
end
for line in stdout_data:gmatch("[^\r\n]+") do
line = line:gsub("^%s*(.-)%s*$", "%1")
local _, _, key, value = line:find("(.*)%s(.*)")
if key ~= nil then
local obj = {}
obj[key] = value
table.insert(self._params, obj)
end
end
callback()
end
local command, args, options, vendor
vendor = sigar:new():sysinfo().vendor:lower()
if vendor == 'ubuntu' or vendor == 'debian' then
command = 'dpkg-query'
args = {'-W'}
options = {}
elseif vendor == 'rhel' or vendor == 'centos' then
command = 'rpm'
args = {"-qa", '--queryformat', '%{NAME}: %{VERSION}-%{RELEASE}\n'}
options = {}
else
self._error = 'Could not determine OS for Packages'
callback()
return
end
execFileToBuffers(command, args, options, execCb)
end
function Info:getType()
return 'PACKAGES'
end
return Info
|
--[[
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 HostInfo = require('./base').HostInfo
local fmt = require('string').format
local los = require('los')
local sigar = require('sigar')
local table = require('table')
local execFileToBuffers = require('./misc').execFileToBuffers
--[[ Packages Variables ]]--
local Info = HostInfo:extend()
function Info:initialize()
HostInfo.initialize(self)
end
function Info:run(callback)
if los.type() ~= 'linux' then
self._error = 'Unsupported OS for Packages'
callback()
return
end
local function execCb(err, exitcode, stdout_data, stderr_data)
if exitcode ~= 0 then
self._error = fmt("Packages exited with a %d exitcode", exitcode)
callback()
return
end
for line in stdout_data:gmatch("[^\r\n]+") do
line = line:gsub("^%s*(.-)%s*$", "%1")
local _, _, key, value = line:find("(.*)%s(.*)")
if key ~= nil then
table.insert(self._params, {
name = key,
version = value
})
end
end
callback()
end
local command, args, options, vendor
vendor = sigar:new():sysinfo().vendor:lower()
if vendor == 'ubuntu' or vendor == 'debian' then
command = 'dpkg-query'
args = {'-W'}
options = {}
elseif vendor == 'rhel' or vendor == 'centos' then
command = 'rpm'
args = {"-qa", '--queryformat', '%{NAME}: %{VERSION}-%{RELEASE}\n'}
options = {}
else
self._error = 'Could not determine OS for Packages'
callback()
return
end
execFileToBuffers(command, args, options, execCb)
end
function Info:getType()
return 'PACKAGES'
end
return Info
|
fix(hostinfo/packages): Make output more consistent with other checks. Closes #804
|
fix(hostinfo/packages): Make output more consistent with other checks. Closes #804
|
Lua
|
apache-2.0
|
kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent
|
43900f64b32c32b71d8bfcc2f826efaa4ef92284
|
verizon.lua
|
verizon.lua
|
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
-- Skip redirect from mysite.verizon.net and members.bellatlantic.net
if url == "http://entertainment.verizon.com/" then
return false
elseif string.match(url, "bellatlantic%.net/([^/]+)/") or
string.match(url, "verizon%.net/([^/]+)/") then
if item_type == verizon then
local directory_name_verizon = string.match(url, "verizon%.net/([^/]+)/")
directory_name_verizon = string.gsub(directory_name_verizon, '%%7E', '~')
if directory_name_verizon ~= item_value then
-- do not want someone else's homepage
-- io.stdout:write("\n Reject " .. url .. " " .. directory_name .. "\n")
-- io.stdout:flush()
return false
else
return verdict
end
elseif item_type == bellatlantic then
local directory_name_bellatlantic = string.match(url, "bellatlantic%.net/([^/]+)/")
directory_name_bellatlantic = string.gsub(directory_name_bellatlantic, '%%7E', '~')
if directory_name_bellatlantic ~= item_value then
-- do not want someone else's homepage
-- io.stdout:write("\n Reject " .. url .. " " .. directory_name .. "\n")
-- io.stdout:flush()
return false
else
return verdict
end
end
elseif string.match(url, "//////////") then
return false
else
return verdict
end
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
local status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \r")
io.stdout:flush()
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404 and status_code ~= 403) then
if string.match(url["host"], "verizon%.net") or
string.match(url["host"], "bellatlantic%.net") then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
else
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.NOTHING
else
return wget.actions.CONTINUE
end
end
elseif status_code == 0 then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
return wget.actions.ABORT
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
-- local sleep_time = 0.1 * (math.random(75, 1000) / 100.0)
local sleep_time = 0
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
-- Skip redirect from mysite.verizon.net and members.bellatlantic.net
if url == "http://entertainment.verizon.com/" then
return false
elseif string.match(url, "bellatlantic%.net/([^/]+)/") or
string.match(url, "verizon%.net/([^/]+)/") then
if item_type == "verizon" then
local directory_name_verizon = string.match(url, "verizon%.net/([^/]+)/")
directory_name_verizon = string.gsub(directory_name_verizon, '%%7E', '~')
if directory_name_verizon ~= item_value then
-- do not want someone else's homepage
-- io.stdout:write("\n Reject " .. url .. " " .. directory_name_verizon .. "\n")
-- io.stdout:flush()
return false
else
return verdict
end
elseif item_type == "bellatlantic" then
local directory_name_bellatlantic = string.match(url, "bellatlantic%.net/([^/]+)/")
directory_name_bellatlantic = string.gsub(directory_name_bellatlantic, '%%7E', '~')
if directory_name_bellatlantic ~= item_value then
-- do not want someone else's homepage
-- io.stdout:write("\n Reject " .. url .. " " .. directory_name_bellatlantic .. "\n")
-- io.stdout:flush()
return false
else
return verdict
end
else
-- shouldn't reach here!
assert(false)
end
elseif string.match(url, "//////////") then
return false
else
return verdict
end
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
local status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \r")
io.stdout:flush()
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404 and status_code ~= 403) then
if string.match(url["host"], "verizon%.net") or
string.match(url["host"], "bellatlantic%.net") then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
else
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.NOTHING
else
return wget.actions.CONTINUE
end
end
elseif status_code == 0 then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
return wget.actions.ABORT
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
-- local sleep_time = 0.1 * (math.random(75, 1000) / 100.0)
local sleep_time = 0
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
verizon.lua: Fix string compare. Assert fail on else fall-through for debugging.
|
verizon.lua: Fix string compare. Assert fail on else fall-through for debugging.
|
Lua
|
unlicense
|
ArchiveTeam/verizon-grab,ArchiveTeam/verizon-grab,ArchiveTeam/verizon-grab
|
d3ff54291d904e75cad558c8853f5c87dd1bffee
|
busted/outputHandlers/junit.lua
|
busted/outputHandlers/junit.lua
|
local xml = require 'pl.xml'
local socket = require("socket")
local string = require("string")
return function(options, busted)
local handler = require 'busted.outputHandlers.base'(busted)
local xml_doc
local suiteStartTime, suiteEndTime
handler.suiteStart = function()
suiteStartTime = socket.gettime()
xml_doc = xml.new('testsuite', {
tests = 0,
errors = 0,
failures = 0,
skip = 0,
})
return nil, true
end
local function now()
return string.format("%.2f", (socket.gettime() - suiteStartTime))
end
handler.suiteEnd = function()
xml_doc.attr.time = now()
print(xml.tostring(xml_doc, '', '\t', nil, false))
return nil, true
end
handler.testEnd = function(element, parent, status)
xml_doc.attr.tests = xml_doc.attr.tests + 1
local testcase_node = xml.new('testcase', {
classname = element.trace.short_src .. ':' .. element.trace.currentline,
name = handler.getFullName(element),
time = now()
})
xml_doc:add_direct_child(testcase_node)
if status == 'failure' then
xml_doc.attr.failures = xml_doc.attr.failures + 1
testcase_node:addtag('failure')
testcase_node:text(element.trace.traceback)
testcase_node:up()
end
return nil, true
end
handler.errorFile = function(element, parent, message, trace)
xml_doc.attr.errors = xml_doc.attr.errors + 1
xml_doc:addtag('error')
xml_doc:text(trace.traceback)
xml_doc:up()
return nil, true
end
busted.subscribe({ 'suite', 'start' }, handler.suiteStart)
busted.subscribe({ 'suite', 'end' }, handler.suiteEnd)
busted.subscribe({ 'test', 'end' }, handler.testEnd, { predicate = handler.cancelOnPending })
busted.subscribe({ 'error', 'file' }, handler.errorFile)
busted.subscribe({ 'failure', 'file' }, handler.errorFile)
return handler
end
|
local xml = require 'pl.xml'
local socket = require("socket")
local string = require("string")
return function(options, busted)
local handler = require 'busted.outputHandlers.base'(busted)
local xml_doc
local suiteStartTime, suiteEndTime
handler.suiteStart = function()
suiteStartTime = socket.gettime()
xml_doc = xml.new('testsuite', {
tests = 0,
errors = 0,
failures = 0,
skip = 0,
})
return nil, true
end
local function now()
return string.format("%.2f", (socket.gettime() - suiteStartTime))
end
handler.suiteEnd = function()
xml_doc.attr.time = now()
print(xml.tostring(xml_doc, '', '\t', nil, false))
return nil, true
end
handler.testEnd = function(element, parent, status)
xml_doc.attr.tests = xml_doc.attr.tests + 1
local testcase_node = xml.new('testcase', {
classname = element.trace.short_src .. ':' .. element.trace.currentline,
name = handler.getFullName(element),
time = now()
})
xml_doc:add_direct_child(testcase_node)
if status == 'failure' then
local formatted = handler.inProgress[tostring(element)]
xml_doc.attr.failures = xml_doc.attr.failures + 1
testcase_node:addtag('failure')
if next(formatted) then
testcase_node:text(formatted.message)
if formatted.trace and formatted.trace.traceback then
testcase_node:text(formatted.trace.traceback)
end
end
testcase_node:up()
elseif status == 'pending' then
local formatted = handler.inProgress[tostring(element)]
xml_doc.attr.skip = xml_doc.attr.skip + 1
testcase_node:addtag('pending')
if next(formatted) then
testcase_node:text(formatted.message)
if formatted.trace and formatted.trace.traceback then
testcase_node:text(formatted.trace.traceback)
end
else
testcase_node:text(element.trace.traceback)
end
testcase_node:up()
end
return nil, true
end
handler.error = function(element, parent, message, trace)
xml_doc.attr.errors = xml_doc.attr.errors + 1
xml_doc:addtag('error')
xml_doc:text(message)
if trace and trace.traceback then
xml_doc:text(trace.traceback)
end
xml_doc:up()
return nil, true
end
handler.failure = function(element, parent, message, trace)
if element.descriptor ~= 'it' then
handler.error(element, parent, message, trace)
end
return nil, true
end
busted.subscribe({ 'suite', 'start' }, handler.suiteStart)
busted.subscribe({ 'suite', 'end' }, handler.suiteEnd)
busted.subscribe({ 'test', 'end' }, handler.testEnd, { predicate = handler.cancelOnPending })
busted.subscribe({ 'error' }, handler.error)
busted.subscribe({ 'failure' }, handler.failure)
return handler
end
|
Fix junit output
|
Fix junit output
This fixes the following errors in the junit output handler:
* Skip test count
* Failure stack trace message
* Missing error tags for describe/it errors
* Missing trace info causes busted to crash
* Missing pending (skip) tags
Fixes issue #333
|
Lua
|
mit
|
xyliuke/busted,leafo/busted,Olivine-Labs/busted,istr/busted,o-lim/busted,ryanplusplus/busted,mpeterv/busted,nehz/busted,sobrinho/busted,DorianGray/busted
|
b81ad8d44207f751720a258e7b168b4912087e8c
|
IPyLua/rlcompleter.lua
|
IPyLua/rlcompleter.lua
|
--[[
IPyLua
Copyright (c) 2015 Francisco Zamora-Martinez. Simplified, less deps and making
it work.
https://github.com/pakozm/IPyLua
Released under the MIT License, see the LICENSE file.
usage: lua IPyLuaKernel.lua CONNECTION_FILENAME
--]]
-- This file is based on the work of Patrick Rapin, adapted by Reuben Thomas:
-- https://github.com/rrthomas/lua-rlcompleter/blob/master/rlcompleter.lua
local ok,lfs = pcall(require, "lfs") if not ok then lfs = nil end
local type = luatype or type
-- The list of Lua keywords
local keywords = {
'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for',
'function', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while'
}
local word_break_chars_pattern = " \t\n\"\\'><=%;%:%+%-%*%/%%%^%~%#%{%}%(%)%[%]%.%,"
local last_word_pattern = ("[%s]?([^%s]*)$"):format(word_break_chars_pattern,
word_break_chars_pattern)
local endpos_pattern = ("(.*)[%s]?"):format(word_break_chars_pattern)
-- Returns index_table field from a metatable, which is a copy of __index table
-- in APRIL-ANN
local function get_index(mt)
if type(mt.__index) == "table" then return mt.__index end
return mt.index_table -- only for APRIL-ANN
end
-- This function needs to be called to complete current input line
local function do_completion(line, text, cursor_pos, env_G, env, _G)
local line = line:sub(1,cursor_pos):match("([^\n]*)[\n]?$")
-- Extract the last word.
local word=line:match( last_word_pattern ) or ""
local startpos,endpos=1,#(line:match(endpos_pattern) or "")
-- Helper function registering possible completion words, verifying matches.
local matches_set = {}
local matches = {}
local function add(value)
value = tostring(value)
if not matches_set[value] then
if value:match("^" .. word) then
matches_set[value] = true
matches[#matches + 1] = value
end
end
end
-- This function does the same job as the default completion of readline,
-- completing paths and filenames.
local function filename_list(str)
if lfs then
local path, name = str:match("(.*)[\\/]+(.*)")
path = (path or ".") .. "/"
if str:sub(1,1) == "/" then path = "/" .. path end
name = name or str
if not lfs.attributes(path) then return end
for f in lfs.dir(path) do
if (lfs.attributes(path .. f) or {}).mode == 'directory' then
add(f .. "/")
else
add(f)
end
end
end
end
-- This function is called in a context where a keyword or a global
-- variable can be inserted. Local variables cannot be listed!
local function add_globals()
for _, k in ipairs(keywords) do add(k) end
for i,tbl in ipairs{env, env_G, _G} do
for k in pairs(tbl) do add(k) end
end
end
-- Main completion function. It evaluates the current sub-expression
-- to determine its type. Currently supports tables fields, global
-- variables and function prototype completion.
local function contextual_list(expr, sep, str)
if str then
return filename_list(str)
end
if expr and expr ~= "" then
local v = load("return " .. expr, nil, nil, env)
if v then
v = v()
local t = type(v)
if sep == '.' or sep == ':' then
if t == 'table' then
for k, v in pairs(v) do
if type(k) == 'string' and (sep ~= ':' or type(v) == "function") then
add(k)
end
end
end
if (t == 'string' or t == 'table' or t == 'userdata') and getmetatable(v) then
local aux = v
repeat
local mt = getmetatable(aux)
local idx = get_index(mt)
if idx and type(idx) == 'table' then
for k,v in pairs(idx) do
add(k)
end
end
if rawequal(aux,idx) then break end -- avoid infinite loops
aux = idx
until not aux or not getmetatable(aux)
end
elseif sep == '[' then
if t == 'table' then
for k in pairs(v) do
if type(k) == 'number' then
add(k .. "]")
end
end
if word ~= "" then add_globals() end
end
end
end
end
if #matches == 0 then add_globals() end
end
-- This complex function tries to simplify the input line, by removing
-- literal strings, full table constructors and balanced groups of
-- parentheses. Returns the sub-expression preceding the word, the
-- separator item ( '.', ':', '[', '(' ) and the current string in case
-- of an unfinished string literal.
local function simplify_expression(expr)
-- Replace annoying sequences \' and \" inside literal strings
expr = expr:gsub("\\(['\"])", function (c)
return string.format("\\%03d", string.byte(c))
end)
local curstring
-- Remove (finished and unfinished) literal strings
while true do
local idx1, _, equals = expr:find("%[(=*)%[")
local idx2, _, sign = expr:find("(['\"])")
if idx1 == nil and idx2 == nil then
break
end
local idx, startpat, endpat
if (idx1 or math.huge) < (idx2 or math.huge) then
idx, startpat, endpat = idx1, "%[" .. equals .. "%[", "%]" .. equals .. "%]"
else
idx, startpat, endpat = idx2, sign, sign
end
if expr:sub(idx):find("^" .. startpat .. ".-" .. endpat) then
expr = expr:gsub(startpat .. "(.-)" .. endpat, " STRING ")
else
expr = expr:gsub(startpat .. "(.*)", function (str)
curstring = str
return "(CURSTRING "
end)
end
end
expr = expr:gsub("%b()"," PAREN ") -- Remove groups of parentheses
expr = expr:gsub("%b{}"," TABLE ") -- Remove table constructors
-- Avoid two consecutive words without operator
expr = expr:gsub("(%w)%s+(%w)","%1|%2")
expr = expr:gsub("%s+", "") -- Remove now useless spaces
-- This main regular expression looks for table indexes and function calls.
return curstring, expr:match("([%.%w%[%]_]-)([:%.%[%(])" .. word .. "$")
end
-- Now call the processing functions and return the list of results.
local str, expr, sep = simplify_expression(line:sub(1, endpos))
contextual_list(expr, sep, str)
table.sort(matches)
-- rebuild the list of matches to prepend all required characters
if text ~= "" then
if expr then
local prefix = expr .. (sep or "")
word = prefix .. word
for i,v in ipairs(matches) do matches[i] = prefix .. v end
end
end
return {
status = "ok",
matches = matches,
matched_text = word,
-- cursor_start = 1,
-- cusor_end = cursor_pos,
metadata = {},
}
end
return {
do_completion = do_completion,
}
|
--[[
IPyLua
Copyright (c) 2015 Francisco Zamora-Martinez. Simplified, less deps and making
it work.
https://github.com/pakozm/IPyLua
Released under the MIT License, see the LICENSE file.
usage: lua IPyLuaKernel.lua CONNECTION_FILENAME
--]]
-- This file is based on the work of Patrick Rapin, adapted by Reuben Thomas:
-- https://github.com/rrthomas/lua-rlcompleter/blob/master/rlcompleter.lua
local ok,lfs = pcall(require, "lfs") if not ok then lfs = nil end
local type = luatype or type
-- The list of Lua keywords
local keywords = {
'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for',
'function', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while'
}
local word_break_chars_pattern = " \t\n\"\\'><=%;%:%+%-%*%/%%%^%~%#%{%}%(%)%[%]%.%,"
local last_word_pattern = ("[%s]?([^%s]*)$"):format(word_break_chars_pattern,
word_break_chars_pattern)
local endpos_pattern = ("(.*)[%s]?"):format(word_break_chars_pattern)
-- Returns index_table field from a metatable, which is a copy of __index table
-- in APRIL-ANN
local function get_index(mt)
if type(mt.__index) == "table" then return mt.__index end
return mt.index_table -- only for APRIL-ANN
end
-- This function needs to be called to complete current input line
local function do_completion(line, text, cursor_pos, env_G, env, _G)
local line = line:sub(1,cursor_pos):match("([^\n]*)[\n]?$")
-- Extract the last word.
local word=line:match( last_word_pattern ) or ""
local startpos,endpos=1,#(line:match(endpos_pattern) or "")
-- Helper function registering possible completion words, verifying matches.
local matches_set = {}
local matches = {}
local function add(value)
value = tostring(value)
if not matches_set[value] then
if value:match("^" .. word) then
matches_set[value] = true
matches[#matches + 1] = value
end
end
end
-- This function does the same job as the default completion of readline,
-- completing paths and filenames.
local function filename_list(str)
if lfs then
local path, name = str:match("(.*)[\\/]+(.*)")
path = (path or ".") .. "/"
if str:sub(1,1) == "/" then path = "/" .. path end
name = name or str
if not lfs.attributes(path) then return end
for f in lfs.dir(path) do
if (lfs.attributes(path .. f) or {}).mode == 'directory' then
add(f .. "/")
else
add(f)
end
end
end
end
-- This function is called in a context where a keyword or a global
-- variable can be inserted. Local variables cannot be listed!
local function add_globals()
for _, k in ipairs(keywords) do add(k) end
for i,tbl in ipairs{env, env_G, _G} do
for k in pairs(tbl) do add(k) end
end
end
-- Main completion function. It evaluates the current sub-expression
-- to determine its type. Currently supports tables fields, global
-- variables and function prototype completion.
local function contextual_list(expr, sep, str)
if str then
return filename_list(str)
end
if expr and expr ~= "" then
local v = load("return " .. expr, nil, nil, env)
if v then
v = v()
local t = type(v)
if sep == '.' or sep == ':' then
if t == 'table' then
for k, v in pairs(v) do
if type(k) == 'string' and (sep ~= ':' or type(v) == "function") then
add(k)
end
end
end
if (t == 'string' or t == 'table' or t == 'userdata') and getmetatable(v) then
local aux = v
repeat
local mt = getmetatable(aux)
local idx = get_index(mt)
if idx and type(idx) == 'table' then
for k,v in pairs(idx) do
add(k)
end
end
if rawequal(aux,idx) then break end -- avoid infinite loops
aux = idx
until not aux or not getmetatable(aux)
end
elseif sep == '[' then
if t == 'table' then
for k in pairs(v) do
if type(k) == 'number' then
add(k .. "]")
end
end
if word ~= "" then add_globals() end
end
end
end
end
if #matches == 0 then add_globals() end
end
-- This complex function tries to simplify the input line, by removing
-- literal strings, full table constructors and balanced groups of
-- parentheses. Returns the sub-expression preceding the word, the
-- separator item ( '.', ':', '[', '(' ) and the current string in case
-- of an unfinished string literal.
local function simplify_expression(expr)
-- Replace annoying sequences \' and \" inside literal strings
expr = expr:gsub("\\(['\"])", function (c)
return string.format("\\%03d", string.byte(c))
end)
local curstring
-- Remove (finished and unfinished) literal strings
while true do
local idx1, _, equals = expr:find("%[(=*)%[")
local idx2, _, sign = expr:find("(['\"])")
if idx1 == nil and idx2 == nil then
break
end
local idx, startpat, endpat
if (idx1 or math.huge) < (idx2 or math.huge) then
idx, startpat, endpat = idx1, "%[" .. equals .. "%[", "%]" .. equals .. "%]"
else
idx, startpat, endpat = idx2, sign, sign
end
if expr:sub(idx):find("^" .. startpat .. ".-" .. endpat) then
expr = expr:gsub(startpat .. "(.-)" .. endpat, " STRING ")
else
expr = expr:gsub(startpat .. "(.*)", function (str)
curstring = str
return "(CURSTRING "
end)
end
end
expr = expr:gsub("%b()"," PAREN ") -- Remove groups of parentheses
expr = expr:gsub("%b{}"," TABLE ") -- Remove table constructors
-- Avoid two consecutive words without operator
expr = expr:gsub("(%w)%s+(%w)","%1|%2")
expr = expr:gsub("%s+", "") -- Remove now useless spaces
-- This main regular expression looks for table indexes and function calls.
return curstring, expr:match("([%.%w%[%]_]-)([:%.%[%(])" .. word .. "$")
end
-- Now call the processing functions and return the list of results.
local str, expr, sep = simplify_expression(line:sub(1, endpos))
contextual_list(expr, sep, str)
table.sort(matches)
-- rebuild the list of matches to prepend all required characters
if text ~= "" then
if sep ~= "." then
expr = line:match("([^%(%)%[%]%,%:><=%+%-%*%^'\\\"])*"..word.."$")
sep = ""
end
if expr then
local prefix = expr .. (sep or "")
word = prefix .. word
for i,v in ipairs(matches) do matches[i] = prefix .. v end
end
end
return {
status = "ok",
matches = matches,
matched_text = word,
-- cursor_start = 1,
-- cusor_end = cursor_pos,
metadata = {},
}
end
return {
do_completion = do_completion,
}
|
Fixed problem with autocompletion in console
|
Fixed problem with autocompletion in console
|
Lua
|
mit
|
pakozm/IPyLua,pakozm/IPyLua
|
b90cd376c81615fec9d9c076b399c94951dc1f60
|
packages/url.lua
|
packages/url.lua
|
SILE.require("packages/verbatim")
local pdf
pcall(function() pdf = require("justenoughlibtexpdf") end)
if pdf then SILE.require("packages/pdf") end
local inputfilter = SILE.require("packages/inputfilter").exports
local urlFilter = function (node, content, breakpat)
if type(node) == "table" then return node end
local result = {}
for token in SU.gtoke(node, breakpat) do
if token.string then
result[#result+1] = token.string
else
result[#result+1] = token.separator
result[#result+1] = inputfilter.createCommand(
content.pos, content.col, content.line,
"penalty", { penalty = 100 }, nil
)
end
end
return result
end
SILE.registerCommand("href", function (options, content)
if not pdf then return SILE.process(content) end
if options.src then
SILE.call("pdf:link", { dest = options.src, external = true }, content)
else
options.src = content[1]
local breakpat = options.breakpat or "/"
content = inputfilter.transformContent(content, urlFilter, breakpat)
SILE.call("pdf:link", { dest = options.src }, content)
end
end)
SILE.registerCommand("url", function (options, content)
local breakpat = options.breakpat or "/"
local result = inputfilter.transformContent(content, urlFilter, breakpat)
SILE.call("code", {}, result)
end)
SILE.registerCommand("code", function(_, content)
SILE.settings.temporarily(function()
SILE.call("verbatim:font")
SILE.process(content)
SILE.typesetter:typeset(" ")
end)
end)
return {
documentation = [[
\begin{document}
This package enhances the typesetting of URLs in two ways. First, the
\code{\\url} command will automatically insert breakpoints into unwieldy
URLs like \url{https://github.com/simoncozens/sile/tree/master/examples/packages}
so that they can be broken up over multiple lines. It also provides the
\code{\\href[src=...]\{\}} command which inserts PDF hyperlinks,
\href[src=http://www.sile-typesetter.org/]{like this}.
\end{document}
]]
}
|
SILE.require("packages/verbatim")
local pdf
pcall(function() pdf = require("justenoughlibtexpdf") end)
if pdf then SILE.require("packages/pdf") end
local inputfilter = SILE.require("packages/inputfilter").exports
local urlFilter = function (node, content, breakpat)
if type(node) == "table" then return node end
local result = {}
for token in SU.gtoke(node, breakpat) do
if token.string then
result[#result+1] = token.string
else
result[#result+1] = token.separator
result[#result+1] = inputfilter.createCommand(
content.pos, content.col, content.line,
"penalty", { penalty = 100 }, nil
)
end
end
return result
end
SILE.registerCommand("href", function (options, content)
if not pdf then return SILE.process(content) end
if options.src then
SILE.call("pdf:link", { dest = options.src, external = true }, content)
else
options.src = content[1]
local breakpat = options.breakpat or "/"
content = inputfilter.transformContent(content, urlFilter, breakpat)
SILE.call("pdf:link", { dest = options.src }, content)
end
end)
SILE.registerCommand("url", function (options, content)
local breakpat = options.breakpat or "/"
local result = inputfilter.transformContent(content, urlFilter, breakpat)
SILE.call("code", {}, result)
end)
SILE.registerCommand("code", function(_, content)
SILE.settings.temporarily(function()
SILE.call("verbatim:font")
SILE.process(content)
end)
end)
return {
documentation = [[
\begin{document}
This package enhances the typesetting of URLs in two ways. First, the
\code{\\url} command will automatically insert breakpoints into unwieldy
URLs like \url{https://github.com/simoncozens/sile/tree/master/examples/packages}
so that they can be broken up over multiple lines. It also provides the
\code{\\href[src=...]\{\}} command which inserts PDF hyperlinks,
\href[src=http://www.sile-typesetter.org/]{like this}.
\end{document}
]]
}
|
fix(packages): Remove extra space in \code in url
|
fix(packages): Remove extra space in \code in url
Closes #1056
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
0e61eb7a7b3da3baefa31eac56b08680f92ec4b4
|
frontend/cache.lua
|
frontend/cache.lua
|
--[[
A global LRU cache
]]--
local DataStorage = require("datastorage")
local lfs = require("libs/libkoreader-lfs")
local logger = require("logger")
local md5 = require("ffi/MD5")
if require("device"):isAndroid() then
require("jit").off(true, true)
end
local function calcFreeMem()
local meminfo = io.open("/proc/meminfo", "r")
local freemem = 0
if meminfo then
for line in meminfo:lines() do
local free, buffer, cached, n
free, n = line:gsub("^MemFree:%s-(%d+) kB", "%1")
if n ~= 0 then freemem = freemem + tonumber(free)*1024 end
buffer, n = line:gsub("^Buffers:%s-(%d+) kB", "%1")
if n ~= 0 then freemem = freemem + tonumber(buffer)*1024 end
cached, n = line:gsub("^Cached:%s-(%d+) kB", "%1")
if n ~= 0 then freemem = freemem + tonumber(cached)*1024 end
end
meminfo:close()
end
return freemem
end
local function calcCacheMemSize()
local min = DGLOBAL_CACHE_SIZE_MINIMUM
local max = DGLOBAL_CACHE_SIZE_MAXIMUM
local calc = calcFreeMem()*(DGLOBAL_CACHE_FREE_PROPORTION or 0)
return math.min(max, math.max(min, calc))
end
local cache_path = DataStorage:getDataDir() .. "/cache/"
--[[
-- return a snapshot of disk cached items for subsequent check
--]]
local function getDiskCache()
local cached = {}
for key_md5 in lfs.dir(cache_path) do
local file = cache_path..key_md5
if lfs.attributes(file, "mode") == "file" then
cached[key_md5] = file
end
end
return cached
end
local Cache = {
-- cache configuration:
max_memsize = calcCacheMemSize(),
-- cache state:
current_memsize = 0,
-- associative cache
cache = {},
-- this will hold the LRU order of the cache
cache_order = {},
-- disk Cache snapshot
cached = getDiskCache(),
}
function Cache:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
-- internal: remove reference in cache_order list
function Cache:_unref(key)
for i = #self.cache_order, 1, -1 do
if self.cache_order[i] == key then
table.remove(self.cache_order, i)
end
end
end
-- internal: free cache item
function Cache:_free(key)
if not self.cache[key] then return end
self.current_memsize = self.current_memsize - self.cache[key].size
self.cache[key]:onFree()
self.cache[key] = nil
end
-- drop an item named via key from the cache
function Cache:drop(key)
self:_unref(key)
self:_free(key)
end
function Cache:insert(key, object)
-- make sure that one key only exists once: delete existing
self:drop(key)
-- guarantee that we have enough memory in cache
if (object.size > self.max_memsize) then
logger.warn("too much memory claimed for", key)
return
end
-- delete objects that least recently used
-- (they are at the end of the cache_order array)
while self.current_memsize + object.size > self.max_memsize do
local removed_key = table.remove(self.cache_order)
self:_free(removed_key)
end
-- insert new object in front of the LRU order
table.insert(self.cache_order, 1, key)
self.cache[key] = object
self.current_memsize = self.current_memsize + object.size
end
--[[
-- check for cache item for key
-- if ItemClass is given, disk cache is also checked.
--]]
function Cache:check(key, ItemClass)
if self.cache[key] then
if self.cache_order[1] ~= key then
-- put key in front of the LRU list
self:_unref(key)
table.insert(self.cache_order, 1, key)
end
return self.cache[key]
elseif ItemClass then
local cached = self.cached[md5.sum(key)]
if cached then
local item = ItemClass:new{}
local ok, msg = pcall(item.load, item, cached)
if ok then
self:insert(key, item)
return item
else
logger.warn("discard cache", msg)
end
end
end
end
function Cache:willAccept(size)
-- we only allow single objects to fill 75% of the cache
if size*4 < self.max_memsize*3 then
return true
end
end
function Cache:serialize()
-- calculate disk cache size
local cached_size = 0
local sorted_caches = {}
for _,file in pairs(self.cached) do
table.insert(sorted_caches, {file=file, time=lfs.attributes(file, "access")})
cached_size = cached_size + (lfs.attributes(file, "size") or 0)
end
table.sort(sorted_caches, function(v1,v2) return v1.time > v2.time end)
-- only serialize the most recently used cache
local cache_size = 0
for _, key in ipairs(self.cache_order) do
local cache_item = self.cache[key]
-- only dump cache item that requests serialization explicitly
if cache_item.persistent and cache_item.dump then
logger.dbg("dump cache item", key)
cache_size = cache_item:dump(cache_path..md5.sum(key)) or 0
if cache_size > 0 then break end
end
end
-- set disk cache the same limit as memory cache
while cached_size + cache_size - self.max_memsize > 0 do
-- discard the least recently used cache
local discarded = table.remove(sorted_caches)
cached_size = cached_size - lfs.attributes(discarded.file, "size")
os.remove(discarded.file)
end
-- disk cache may have changes so need to refresh disk cache snapshot
self.cached = getDiskCache()
end
-- blank the cache
function Cache:clear()
for k, _ in pairs(self.cache) do
self.cache[k]:onFree()
end
self.cache = {}
self.cache_order = {}
self.current_memsize = 0
end
return Cache
|
--[[
A global LRU cache
]]--
local DataStorage = require("datastorage")
local lfs = require("libs/libkoreader-lfs")
local logger = require("logger")
local md5 = require("ffi/MD5")
if require("device"):isAndroid() then
require("jit").off(true, true)
end
local function calcFreeMem()
local meminfo = io.open("/proc/meminfo", "r")
local freemem = 0
if meminfo then
for line in meminfo:lines() do
local free, buffer, cached, n
free, n = line:gsub("^MemFree:%s-(%d+) kB", "%1")
if n ~= 0 then freemem = freemem + tonumber(free)*1024 end
buffer, n = line:gsub("^Buffers:%s-(%d+) kB", "%1")
if n ~= 0 then freemem = freemem + tonumber(buffer)*1024 end
cached, n = line:gsub("^Cached:%s-(%d+) kB", "%1")
if n ~= 0 then freemem = freemem + tonumber(cached)*1024 end
end
meminfo:close()
end
return freemem
end
local function calcCacheMemSize()
local min = DGLOBAL_CACHE_SIZE_MINIMUM
local max = DGLOBAL_CACHE_SIZE_MAXIMUM
local calc = calcFreeMem()*(DGLOBAL_CACHE_FREE_PROPORTION or 0)
return math.min(max, math.max(min, calc))
end
local cache_path = DataStorage:getDataDir() .. "/cache/"
--[[
-- return a snapshot of disk cached items for subsequent check
--]]
local function getDiskCache()
local cached = {}
for key_md5 in lfs.dir(cache_path) do
local file = cache_path..key_md5
if lfs.attributes(file, "mode") == "file" then
cached[key_md5] = file
end
end
return cached
end
local Cache = {
-- cache configuration:
max_memsize = calcCacheMemSize(),
-- cache state:
current_memsize = 0,
-- associative cache
cache = {},
-- this will hold the LRU order of the cache
cache_order = {},
-- disk Cache snapshot
cached = getDiskCache(),
}
function Cache:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
-- internal: remove reference in cache_order list
function Cache:_unref(key)
for i = #self.cache_order, 1, -1 do
if self.cache_order[i] == key then
table.remove(self.cache_order, i)
end
end
end
-- internal: free cache item
function Cache:_free(key)
if not self.cache[key] then return end
self.current_memsize = self.current_memsize - self.cache[key].size
self.cache[key]:onFree()
self.cache[key] = nil
end
-- drop an item named via key from the cache
function Cache:drop(key)
self:_unref(key)
self:_free(key)
end
function Cache:insert(key, object)
-- make sure that one key only exists once: delete existing
self:drop(key)
-- guarantee that we have enough memory in cache
if (object.size > self.max_memsize) then
logger.warn("too much memory claimed for", key)
return
end
-- delete objects that least recently used
-- (they are at the end of the cache_order array)
while self.current_memsize + object.size > self.max_memsize do
local removed_key = table.remove(self.cache_order)
self:_free(removed_key)
end
-- insert new object in front of the LRU order
table.insert(self.cache_order, 1, key)
self.cache[key] = object
self.current_memsize = self.current_memsize + object.size
end
--[[
-- check for cache item for key
-- if ItemClass is given, disk cache is also checked.
--]]
function Cache:check(key, ItemClass)
if self.cache[key] then
if self.cache_order[1] ~= key then
-- put key in front of the LRU list
self:_unref(key)
table.insert(self.cache_order, 1, key)
end
return self.cache[key]
elseif ItemClass then
local cached = self.cached[md5.sum(key)]
if cached then
local item = ItemClass:new{}
local ok, msg = pcall(item.load, item, cached)
if ok then
self:insert(key, item)
return item
else
logger.warn("discard cache", msg)
end
end
end
end
function Cache:willAccept(size)
-- we only allow single objects to fill 75% of the cache
if size*4 < self.max_memsize*3 then
return true
end
end
function Cache:serialize()
-- calculate disk cache size
local cached_size = 0
local sorted_caches = {}
for _,file in pairs(self.cached) do
table.insert(sorted_caches, {file=file, time=lfs.attributes(file, "access")})
cached_size = cached_size + (lfs.attributes(file, "size") or 0)
end
table.sort(sorted_caches, function(v1,v2) return v1.time > v2.time end)
-- only serialize the most recently used cache
local cache_size = 0
for _, key in ipairs(self.cache_order) do
local cache_item = self.cache[key]
-- only dump cache item that requests serialization explicitly
if cache_item.persistent and cache_item.dump then
local cache_full_path = cache_path..md5.sum(key)
local cache_file_exists = lfs.attributes(cache_full_path)
if cache_file_exists then break end
logger.dbg("dump cache item", key)
cache_size = cache_item:dump(cache_full_path) or 0
if cache_size > 0 then break end
end
end
-- set disk cache the same limit as memory cache
while cached_size + cache_size - self.max_memsize > 0 do
-- discard the least recently used cache
local discarded = table.remove(sorted_caches)
cached_size = cached_size - lfs.attributes(discarded.file, "size")
os.remove(discarded.file)
end
-- disk cache may have changes so need to refresh disk cache snapshot
self.cached = getDiskCache()
end
-- blank the cache
function Cache:clear()
for k, _ in pairs(self.cache) do
self.cache[k]:onFree()
end
self.cache = {}
self.cache_order = {}
self.current_memsize = 0
end
return Cache
|
[fix] Cache: don't overwrite same CacheItem (#3847)
|
[fix] Cache: don't overwrite same CacheItem (#3847)
If the most recently used global cache item refers to the same
page, it would be overwritten. This will happen when closing a
paged (PDF/DjVu) document on the same page you opened it, as well
as when opening and closing EPUBs with crengine because it uses
its own cache.
Fixes #3846.
|
Lua
|
agpl-3.0
|
poire-z/koreader,lgeek/koreader,mihailim/koreader,Hzj-jie/koreader,NiLuJe/koreader,houqp/koreader,pazos/koreader,Frenzie/koreader,koreader/koreader,poire-z/koreader,Frenzie/koreader,NiLuJe/koreader,mwoz123/koreader,Markismus/koreader,koreader/koreader
|
324888041ba9f6a2e591fd7f8e9782ab0a655dad
|
xmake/actions/require/impl/environment.lua
|
xmake/actions/require/impl/environment.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 environment.lua
--
-- imports
import("core.project.config")
import("core.platform.environment")
import("core.package.package", {alias = "core_package"})
import("lib.detect.find_tool")
import("private.action.require.packagenv")
import("package")
-- enter environment
--
-- ensure that we can find some basic tools: git, unzip, ...
--
-- If these tools not exist, we will install it first.
--
function enter()
-- set search paths of toolchains
environment.enter("toolchains")
-- unzip is necessary
if not find_tool("unzip") then
raise("unzip not found! we need install it first")
end
-- enter the environments of git and 7z
packagenv.enter("git", "7z")
-- git not found? install it first
local packages = {}
if not find_tool("git") then
table.join2(packages, package.install_packages("git"))
end
-- missing the necessary unarchivers for *.gz, *.7z? install them first, e.g. gzip, 7z, tar ..
if not ((find_tool("gzip") and find_tool("tar")) or find_tool("7z")) then
table.join2(packages, package.install_packages("7z"))
end
-- enter the environments of installed packages
for _, instance in ipairs(packages) do
instance:envs_enter()
end
_g._PACKAGES = packages
end
-- leave environment
function leave()
-- leave the environments of installed packages
for _, instance in irpairs(_g._PACKAGES) do
instance:envs_leave()
end
_g._PACKAGES = nil
-- leave the environments of git and 7z
packagenv.leave("7z", "git")
-- restore search paths of toolchains
environment.leave("toolchains")
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 environment.lua
--
-- imports
import("core.project.config")
import("core.platform.environment")
import("core.package.package", {alias = "core_package"})
import("lib.detect.find_tool")
import("private.action.require.packagenv")
import("package")
-- enter environment
--
-- ensure that we can find some basic tools: git, unzip, ...
--
-- If these tools not exist, we will install it first.
--
function enter()
-- set search paths of toolchains
environment.enter("toolchains")
-- unzip or 7zip is necessary
if not find_tool("unzip") and not find_tool("7z") then
raise("unzip or 7zip not found! we need install it first")
end
-- enter the environments of git and 7z
packagenv.enter("git", "7z")
-- git not found? install it first
local packages = {}
if not find_tool("git") then
table.join2(packages, package.install_packages("git"))
end
-- missing the necessary unarchivers for *.gz, *.7z? install them first, e.g. gzip, 7z, tar ..
if not ((find_tool("gzip") and find_tool("tar")) or find_tool("7z")) then
table.join2(packages, package.install_packages("7z"))
end
-- enter the environments of installed packages
for _, instance in ipairs(packages) do
instance:envs_enter()
end
_g._PACKAGES = packages
end
-- leave environment
function leave()
-- leave the environments of installed packages
for _, instance in irpairs(_g._PACKAGES) do
instance:envs_leave()
end
_g._PACKAGES = nil
-- leave the environments of git and 7z
packagenv.leave("7z", "git")
-- restore search paths of toolchains
environment.leave("toolchains")
end
|
fix find unzip for requires
|
fix find unzip for requires
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
0eefbbe91d4aa69559eecdc7203e6c52565fc8a2
|
libs/web/luasrc/template.lua
|
libs/web/luasrc/template.lua
|
--[[
LuCI - Template Parser
Description:
A template parser supporting includes, translations, Lua code blocks
and more. It can be used either as a compiler or as an interpreter.
FileId: $Id$
License:
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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.
]]--
module("luci.template", package.seeall)
require("luci.config")
require("luci.util")
require("luci.fs")
require("luci.http")
luci.config.template = luci.config.template or {}
viewdir = luci.config.template.viewdir or luci.sys.libpath() .. "/view"
compiledir = luci.config.template.compiledir or luci.sys.libpath() .. "/view"
-- Enforce cache security
compiledir = compiledir .. "/" .. luci.sys.process.info("uid")
-- Compile modes:
-- none: Never compile, only use precompiled data from files
-- memory: Always compile, do not save compiled files, ignore precompiled
-- file: Compile on demand, save compiled files, update precompiled
compiler_mode = luci.config.template.compiler_mode or "memory"
-- Define the namespace for template modules
viewns = {
write = io.write,
include = function(name) Template(name):render(getfenv(2)) end,
}
-- Compiles a given template into an executable Lua module
function compile(template)
-- Search all <% %> expressions (remember: Lua table indexes begin with #1)
local function expr_add(command)
table.insert(expr, command)
return "<%" .. tostring(#expr) .. "%>"
end
-- As "expr" should be local, we have to assign it to the "expr_add" scope
local expr = {}
luci.util.extfenv(expr_add, "expr", expr)
-- Save all expressiosn to table "expr"
template = template:gsub("<%%(.-)%%>", expr_add)
local function sanitize(s)
s = luci.util.escape(s)
s = luci.util.escape(s, "'")
s = luci.util.escape(s, "\n")
return s
end
-- Escape and sanitize all the template (all non-expressions)
template = sanitize(template)
-- Template module header/footer declaration
local header = "write('"
local footer = "')"
template = header .. template .. footer
-- Replacements
local r_include = "')\ninclude('%s')\nwrite('"
local r_i18n = "'..translate('%1','%2')..'"
local r_pexec = "'..(%s or '')..'"
local r_exec = "')\n%s\nwrite('"
-- Parse the expressions
for k,v in pairs(expr) do
local p = v:sub(1, 1)
local re = nil
if p == "+" then
re = r_include:format(sanitize(string.sub(v, 2)))
elseif p == ":" then
re = sanitize(v):gsub(":(.-) (.+)", r_i18n)
elseif p == "=" then
re = r_pexec:format(v:sub(2))
else
re = r_exec:format(v)
end
template = template:gsub("<%%"..tostring(k).."%%>", re)
end
return loadstring(template)
end
-- Oldstyle render shortcut
function render(name, scope, ...)
scope = scope or getfenv(2)
local s, t = pcall(Template, name)
if not s then
error(t)
else
t:render(scope, ...)
end
end
-- Template class
Template = luci.util.class()
-- Shared template cache to store templates in to avoid unnecessary reloading
Template.cache = {}
-- Constructor - Reads and compiles the template on-demand
function Template.__init__(self, name)
if self.cache[name] then
self.template = self.cache[name]
else
self.template = nil
end
-- Create a new namespace for this template
self.viewns = {}
-- Copy over from general namespace
for k, v in pairs(viewns) do
self.viewns[k] = v
end
-- If we have a cached template, skip compiling and loading
if self.template then
return
end
-- Compile and build
local sourcefile = viewdir .. "/" .. name .. ".htm"
local compiledfile = compiledir .. "/" .. luci.http.urlencode(name) .. ".lua"
local err
if compiler_mode == "file" then
local tplmt = luci.fs.mtime(sourcefile)
local commt = luci.fs.mtime(compiledfile)
if not luci.fs.mtime(compiledir) then
luci.fs.mkdir(compiledir, true)
luci.fs.chmod(luci.fs.dirname(compiledir), "a+rxw")
end
-- Build if there is no compiled file or if compiled file is outdated
if ((commt == nil) and not (tplmt == nil))
or (not (commt == nil) and not (tplmt == nil) and commt < tplmt) then
local source
source, err = luci.fs.readfile(sourcefile)
if source then
local compiled, err = compile(source)
luci.fs.writefile(compiledfile, luci.util.dump(compiled))
self.template = compiled
end
else
self.template, err = loadfile(compiledfile)
end
elseif compiler_mode == "none" then
self.template, err = loadfile(self.compiledfile)
elseif compiler_mode == "memory" then
local source
source, err = luci.fs.readfile(sourcefile)
if source then
self.template, err = compile(source)
end
end
-- If we have no valid template throw error, otherwise cache the template
if not self.template then
error(err)
else
self.cache[name] = self.template
end
end
-- Renders a template
function Template.render(self, scope)
scope = scope or getfenv(2)
-- Save old environment
local oldfenv = getfenv(self.template)
-- Put our predefined objects in the scope of the template
luci.util.resfenv(self.template)
luci.util.updfenv(self.template, scope)
luci.util.updfenv(self.template, self.viewns)
-- Now finally render the thing
self.template()
-- Reset environment
setfenv(self.template, oldfenv)
end
|
--[[
LuCI - Template Parser
Description:
A template parser supporting includes, translations, Lua code blocks
and more. It can be used either as a compiler or as an interpreter.
FileId: $Id$
License:
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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.
]]--
module("luci.template", package.seeall)
require("luci.config")
require("luci.util")
require("luci.fs")
require("luci.http")
luci.config.template = luci.config.template or {}
viewdir = luci.config.template.viewdir or luci.sys.libpath() .. "/view"
compiledir = luci.config.template.compiledir or luci.sys.libpath() .. "/view"
-- Compile modes:
-- none: Never compile, only use precompiled data from files
-- memory: Always compile, do not save compiled files, ignore precompiled
-- file: Compile on demand, save compiled files, update precompiled
compiler_mode = luci.config.template.compiler_mode or "memory"
-- Define the namespace for template modules
viewns = {
write = io.write,
include = function(name) Template(name):render(getfenv(2)) end,
}
-- Compiles a given template into an executable Lua module
function compile(template)
-- Search all <% %> expressions (remember: Lua table indexes begin with #1)
local function expr_add(command)
table.insert(expr, command)
return "<%" .. tostring(#expr) .. "%>"
end
-- As "expr" should be local, we have to assign it to the "expr_add" scope
local expr = {}
luci.util.extfenv(expr_add, "expr", expr)
-- Save all expressiosn to table "expr"
template = template:gsub("<%%(.-)%%>", expr_add)
local function sanitize(s)
s = luci.util.escape(s)
s = luci.util.escape(s, "'")
s = luci.util.escape(s, "\n")
return s
end
-- Escape and sanitize all the template (all non-expressions)
template = sanitize(template)
-- Template module header/footer declaration
local header = "write('"
local footer = "')"
template = header .. template .. footer
-- Replacements
local r_include = "')\ninclude('%s')\nwrite('"
local r_i18n = "'..translate('%1','%2')..'"
local r_pexec = "'..(%s or '')..'"
local r_exec = "')\n%s\nwrite('"
-- Parse the expressions
for k,v in pairs(expr) do
local p = v:sub(1, 1)
local re = nil
if p == "+" then
re = r_include:format(sanitize(string.sub(v, 2)))
elseif p == ":" then
re = sanitize(v):gsub(":(.-) (.+)", r_i18n)
elseif p == "=" then
re = r_pexec:format(v:sub(2))
else
re = r_exec:format(v)
end
template = template:gsub("<%%"..tostring(k).."%%>", re)
end
return loadstring(template)
end
-- Oldstyle render shortcut
function render(name, scope, ...)
scope = scope or getfenv(2)
local s, t = pcall(Template, name)
if not s then
error(t)
else
t:render(scope, ...)
end
end
-- Template class
Template = luci.util.class()
-- Shared template cache to store templates in to avoid unnecessary reloading
Template.cache = {}
-- Constructor - Reads and compiles the template on-demand
function Template.__init__(self, name)
if self.cache[name] then
self.template = self.cache[name]
else
self.template = nil
end
-- Create a new namespace for this template
self.viewns = {}
-- Copy over from general namespace
for k, v in pairs(viewns) do
self.viewns[k] = v
end
-- If we have a cached template, skip compiling and loading
if self.template then
return
end
-- Enforce cache security
local cdir = compiledir .. "/" .. luci.sys.process.info("uid")
-- Compile and build
local sourcefile = viewdir .. "/" .. name .. ".htm"
local compiledfile = cdir .. "/" .. luci.http.urlencode(name) .. ".lua"
local err
if compiler_mode == "file" then
local tplmt = luci.fs.mtime(sourcefile)
local commt = luci.fs.mtime(compiledfile)
if not luci.fs.mtime(cdir) then
luci.fs.mkdir(cdir, true)
luci.fs.chmod(luci.fs.dirname(cdir), "a+rxw")
end
-- Build if there is no compiled file or if compiled file is outdated
if ((commt == nil) and not (tplmt == nil))
or (not (commt == nil) and not (tplmt == nil) and commt < tplmt) then
local source
source, err = luci.fs.readfile(sourcefile)
if source then
local compiled, err = compile(source)
luci.fs.writefile(compiledfile, luci.util.dump(compiled))
self.template = compiled
end
else
self.template, err = loadfile(compiledfile)
end
elseif compiler_mode == "none" then
self.template, err = loadfile(self.compiledfile)
elseif compiler_mode == "memory" then
local source
source, err = luci.fs.readfile(sourcefile)
if source then
self.template, err = compile(source)
end
end
-- If we have no valid template throw error, otherwise cache the template
if not self.template then
error(err)
else
self.cache[name] = self.template
end
end
-- Renders a template
function Template.render(self, scope)
scope = scope or getfenv(2)
-- Save old environment
local oldfenv = getfenv(self.template)
-- Put our predefined objects in the scope of the template
luci.util.resfenv(self.template)
luci.util.updfenv(self.template, scope)
luci.util.updfenv(self.template, self.viewns)
-- Now finally render the thing
self.template()
-- Reset environment
setfenv(self.template, oldfenv)
end
|
* libs/web: Fixed secure caching with setuid/setgid handling
|
* libs/web: Fixed secure caching with setuid/setgid handling
|
Lua
|
apache-2.0
|
Kyklas/luci-proto-hso,schidler/ionic-luci,palmettos/test,Hostle/luci,lcf258/openwrtcn,teslamint/luci,teslamint/luci,taiha/luci,male-puppies/luci,LuttyYang/luci,cappiewu/luci,kuoruan/lede-luci,nwf/openwrt-luci,lbthomsen/openwrt-luci,mumuqz/luci,florian-shellfire/luci,forward619/luci,david-xiao/luci,kuoruan/luci,LazyZhu/openwrt-luci-trunk-mod,florian-shellfire/luci,Hostle/openwrt-luci-multi-user,marcel-sch/luci,taiha/luci,openwrt-es/openwrt-luci,palmettos/test,Hostle/luci,male-puppies/luci,thesabbir/luci,RedSnake64/openwrt-luci-packages,cshore/luci,RuiChen1113/luci,shangjiyu/luci-with-extra,mumuqz/luci,obsy/luci,LuttyYang/luci,thess/OpenWrt-luci,cappiewu/luci,cappiewu/luci,kuoruan/luci,harveyhu2012/luci,sujeet14108/luci,981213/luci-1,sujeet14108/luci,jlopenwrtluci/luci,NeoRaider/luci,wongsyrone/luci-1,RedSnake64/openwrt-luci-packages,aa65535/luci,tobiaswaldvogel/luci,forward619/luci,daofeng2015/luci,ollie27/openwrt_luci,ReclaimYourPrivacy/cloak-luci,jchuang1977/luci-1,Wedmer/luci,mumuqz/luci,oyido/luci,maxrio/luci981213,nmav/luci,aircross/OpenWrt-Firefly-LuCI,Wedmer/luci,maxrio/luci981213,RuiChen1113/luci,sujeet14108/luci,artynet/luci,deepak78/new-luci,nmav/luci,jlopenwrtluci/luci,MinFu/luci,tobiaswaldvogel/luci,fkooman/luci,obsy/luci,kuoruan/luci,zhaoxx063/luci,florian-shellfire/luci,palmettos/cnLuCI,rogerpueyo/luci,artynet/luci,openwrt-es/openwrt-luci,aa65535/luci,jorgifumi/luci,slayerrensky/luci,lbthomsen/openwrt-luci,Hostle/luci,jlopenwrtluci/luci,zhaoxx063/luci,sujeet14108/luci,Hostle/openwrt-luci-multi-user,slayerrensky/luci,david-xiao/luci,oyido/luci,urueedi/luci,jchuang1977/luci-1,hnyman/luci,ReclaimYourPrivacy/cloak-luci,aa65535/luci,openwrt/luci,RedSnake64/openwrt-luci-packages,kuoruan/lede-luci,thess/OpenWrt-luci,slayerrensky/luci,mumuqz/luci,teslamint/luci,palmettos/cnLuCI,david-xiao/luci,zhaoxx063/luci,kuoruan/lede-luci,forward619/luci,chris5560/openwrt-luci,obsy/luci,LazyZhu/openwrt-luci-trunk-mod,palmettos/cnLuCI,rogerpueyo/luci,Hostle/openwrt-luci-multi-user,dismantl/luci-0.12,tcatm/luci,bright-things/ionic-luci,forward619/luci,lbthomsen/openwrt-luci,remakeelectric/luci,thess/OpenWrt-luci,ReclaimYourPrivacy/cloak-luci,nwf/openwrt-luci,dismantl/luci-0.12,hnyman/luci,bittorf/luci,urueedi/luci,aa65535/luci,fkooman/luci,kuoruan/luci,bright-things/ionic-luci,taiha/luci,palmettos/cnLuCI,thesabbir/luci,kuoruan/lede-luci,981213/luci-1,openwrt/luci,Kyklas/luci-proto-hso,MinFu/luci,taiha/luci,aircross/OpenWrt-Firefly-LuCI,slayerrensky/luci,rogerpueyo/luci,jlopenwrtluci/luci,lbthomsen/openwrt-luci,taiha/luci,kuoruan/luci,RuiChen1113/luci,openwrt/luci,remakeelectric/luci,artynet/luci,obsy/luci,wongsyrone/luci-1,harveyhu2012/luci,Noltari/luci,981213/luci-1,forward619/luci,joaofvieira/luci,keyidadi/luci,Kyklas/luci-proto-hso,dismantl/luci-0.12,Wedmer/luci,Hostle/luci,NeoRaider/luci,jlopenwrtluci/luci,thesabbir/luci,maxrio/luci981213,ff94315/luci-1,lcf258/openwrtcn,lcf258/openwrtcn,ollie27/openwrt_luci,aa65535/luci,palmettos/test,dismantl/luci-0.12,dismantl/luci-0.12,slayerrensky/luci,fkooman/luci,oyido/luci,obsy/luci,lcf258/openwrtcn,jorgifumi/luci,chris5560/openwrt-luci,keyidadi/luci,oneru/luci,hnyman/luci,ReclaimYourPrivacy/cloak-luci,Kyklas/luci-proto-hso,palmettos/cnLuCI,mumuqz/luci,ff94315/luci-1,hnyman/luci,NeoRaider/luci,nmav/luci,wongsyrone/luci-1,zhaoxx063/luci,cshore/luci,palmettos/test,NeoRaider/luci,wongsyrone/luci-1,palmettos/cnLuCI,deepak78/new-luci,tcatm/luci,bright-things/ionic-luci,urueedi/luci,tcatm/luci,opentechinstitute/luci,harveyhu2012/luci,maxrio/luci981213,david-xiao/luci,aircross/OpenWrt-Firefly-LuCI,bittorf/luci,openwrt-es/openwrt-luci,cshore/luci,NeoRaider/luci,cshore-firmware/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,dwmw2/luci,harveyhu2012/luci,thess/OpenWrt-luci,db260179/openwrt-bpi-r1-luci,rogerpueyo/luci,maxrio/luci981213,zhaoxx063/luci,bright-things/ionic-luci,sujeet14108/luci,Noltari/luci,Noltari/luci,lcf258/openwrtcn,Noltari/luci,Wedmer/luci,schidler/ionic-luci,daofeng2015/luci,LazyZhu/openwrt-luci-trunk-mod,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,oyido/luci,dwmw2/luci,marcel-sch/luci,rogerpueyo/luci,cshore-firmware/openwrt-luci,nmav/luci,bittorf/luci,keyidadi/luci,fkooman/luci,jlopenwrtluci/luci,nmav/luci,hnyman/luci,teslamint/luci,deepak78/new-luci,db260179/openwrt-bpi-r1-luci,MinFu/luci,marcel-sch/luci,artynet/luci,tcatm/luci,shangjiyu/luci-with-extra,nwf/openwrt-luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,zhaoxx063/luci,openwrt/luci,Sakura-Winkey/LuCI,shangjiyu/luci-with-extra,keyidadi/luci,openwrt-es/openwrt-luci,lcf258/openwrtcn,Hostle/openwrt-luci-multi-user,Kyklas/luci-proto-hso,nwf/openwrt-luci,thess/OpenWrt-luci,shangjiyu/luci-with-extra,MinFu/luci,lcf258/openwrtcn,schidler/ionic-luci,RedSnake64/openwrt-luci-packages,RedSnake64/openwrt-luci-packages,kuoruan/luci,florian-shellfire/luci,taiha/luci,cappiewu/luci,palmettos/test,dismantl/luci-0.12,LuttyYang/luci,male-puppies/luci,obsy/luci,bright-things/ionic-luci,teslamint/luci,lcf258/openwrtcn,jchuang1977/luci-1,cshore-firmware/openwrt-luci,cshore/luci,tcatm/luci,forward619/luci,jorgifumi/luci,openwrt-es/openwrt-luci,nwf/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ff94315/luci-1,oyido/luci,bright-things/ionic-luci,bittorf/luci,florian-shellfire/luci,jorgifumi/luci,palmettos/cnLuCI,wongsyrone/luci-1,schidler/ionic-luci,jorgifumi/luci,oyido/luci,remakeelectric/luci,thess/OpenWrt-luci,daofeng2015/luci,keyidadi/luci,male-puppies/luci,mumuqz/luci,Sakura-Winkey/LuCI,artynet/luci,oyido/luci,cshore/luci,Hostle/luci,MinFu/luci,bright-things/ionic-luci,NeoRaider/luci,florian-shellfire/luci,cappiewu/luci,Hostle/openwrt-luci-multi-user,jchuang1977/luci-1,keyidadi/luci,981213/luci-1,Sakura-Winkey/LuCI,wongsyrone/luci-1,fkooman/luci,jchuang1977/luci-1,remakeelectric/luci,aircross/OpenWrt-Firefly-LuCI,ReclaimYourPrivacy/cloak-luci,bittorf/luci,marcel-sch/luci,keyidadi/luci,male-puppies/luci,kuoruan/lede-luci,opentechinstitute/luci,ollie27/openwrt_luci,LazyZhu/openwrt-luci-trunk-mod,ff94315/luci-1,Sakura-Winkey/LuCI,artynet/luci,florian-shellfire/luci,sujeet14108/luci,chris5560/openwrt-luci,cshore-firmware/openwrt-luci,Kyklas/luci-proto-hso,RuiChen1113/luci,jchuang1977/luci-1,MinFu/luci,bright-things/ionic-luci,male-puppies/luci,slayerrensky/luci,ff94315/luci-1,joaofvieira/luci,palmettos/test,tobiaswaldvogel/luci,thesabbir/luci,kuoruan/luci,nmav/luci,thess/OpenWrt-luci,Noltari/luci,Hostle/openwrt-luci-multi-user,Hostle/openwrt-luci-multi-user,openwrt-es/openwrt-luci,Noltari/luci,981213/luci-1,jchuang1977/luci-1,tcatm/luci,david-xiao/luci,joaofvieira/luci,aircross/OpenWrt-Firefly-LuCI,Noltari/luci,schidler/ionic-luci,RedSnake64/openwrt-luci-packages,harveyhu2012/luci,opentechinstitute/luci,chris5560/openwrt-luci,urueedi/luci,male-puppies/luci,nmav/luci,cshore/luci,jorgifumi/luci,artynet/luci,opentechinstitute/luci,deepak78/new-luci,cshore/luci,oneru/luci,opentechinstitute/luci,daofeng2015/luci,ReclaimYourPrivacy/cloak-luci,LazyZhu/openwrt-luci-trunk-mod,schidler/ionic-luci,LuttyYang/luci,taiha/luci,jorgifumi/luci,Hostle/luci,nmav/luci,palmettos/test,deepak78/new-luci,schidler/ionic-luci,hnyman/luci,ollie27/openwrt_luci,sujeet14108/luci,palmettos/test,cshore-firmware/openwrt-luci,fkooman/luci,openwrt/luci,marcel-sch/luci,zhaoxx063/luci,cshore-firmware/openwrt-luci,lcf258/openwrtcn,RuiChen1113/luci,oneru/luci,lcf258/openwrtcn,cappiewu/luci,joaofvieira/luci,MinFu/luci,zhaoxx063/luci,kuoruan/lede-luci,slayerrensky/luci,kuoruan/luci,harveyhu2012/luci,LuttyYang/luci,jchuang1977/luci-1,oyido/luci,daofeng2015/luci,daofeng2015/luci,openwrt-es/openwrt-luci,aa65535/luci,joaofvieira/luci,hnyman/luci,ollie27/openwrt_luci,981213/luci-1,teslamint/luci,MinFu/luci,LuttyYang/luci,remakeelectric/luci,rogerpueyo/luci,maxrio/luci981213,ReclaimYourPrivacy/cloak-luci,artynet/luci,thesabbir/luci,cshore/luci,mumuqz/luci,urueedi/luci,ff94315/luci-1,thesabbir/luci,Hostle/luci,dwmw2/luci,tobiaswaldvogel/luci,nwf/openwrt-luci,obsy/luci,LazyZhu/openwrt-luci-trunk-mod,marcel-sch/luci,tobiaswaldvogel/luci,db260179/openwrt-bpi-r1-luci,Wedmer/luci,RuiChen1113/luci,tobiaswaldvogel/luci,cappiewu/luci,rogerpueyo/luci,chris5560/openwrt-luci,maxrio/luci981213,tobiaswaldvogel/luci,bittorf/luci,marcel-sch/luci,cshore-firmware/openwrt-luci,dwmw2/luci,ff94315/luci-1,openwrt/luci,kuoruan/lede-luci,NeoRaider/luci,oneru/luci,lbthomsen/openwrt-luci,shangjiyu/luci-with-extra,NeoRaider/luci,oneru/luci,opentechinstitute/luci,ollie27/openwrt_luci,LuttyYang/luci,RedSnake64/openwrt-luci-packages,aircross/OpenWrt-Firefly-LuCI,keyidadi/luci,wongsyrone/luci-1,teslamint/luci,daofeng2015/luci,schidler/ionic-luci,openwrt/luci,wongsyrone/luci-1,nwf/openwrt-luci,urueedi/luci,dwmw2/luci,oneru/luci,Sakura-Winkey/LuCI,jlopenwrtluci/luci,mumuqz/luci,remakeelectric/luci,ollie27/openwrt_luci,Sakura-Winkey/LuCI,aa65535/luci,LazyZhu/openwrt-luci-trunk-mod,tcatm/luci,dwmw2/luci,deepak78/new-luci,david-xiao/luci,RuiChen1113/luci,maxrio/luci981213,david-xiao/luci,daofeng2015/luci,slayerrensky/luci,fkooman/luci,kuoruan/lede-luci,Noltari/luci,shangjiyu/luci-with-extra,db260179/openwrt-bpi-r1-luci,shangjiyu/luci-with-extra,bittorf/luci,remakeelectric/luci,oneru/luci,joaofvieira/luci,tobiaswaldvogel/luci,RuiChen1113/luci,jlopenwrtluci/luci,chris5560/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,db260179/openwrt-bpi-r1-luci,tcatm/luci,thess/OpenWrt-luci,LuttyYang/luci,Wedmer/luci,Sakura-Winkey/LuCI,sujeet14108/luci,981213/luci-1,dwmw2/luci,obsy/luci,teslamint/luci,palmettos/cnLuCI,Sakura-Winkey/LuCI,ff94315/luci-1,dismantl/luci-0.12,marcel-sch/luci,Kyklas/luci-proto-hso,openwrt-es/openwrt-luci,cappiewu/luci,urueedi/luci,opentechinstitute/luci,chris5560/openwrt-luci,jorgifumi/luci,oneru/luci,forward619/luci,cshore-firmware/openwrt-luci,harveyhu2012/luci,joaofvieira/luci,Wedmer/luci,urueedi/luci,florian-shellfire/luci,aa65535/luci,nwf/openwrt-luci,nmav/luci,shangjiyu/luci-with-extra,Noltari/luci,lbthomsen/openwrt-luci,Wedmer/luci,opentechinstitute/luci,joaofvieira/luci,artynet/luci,forward619/luci,deepak78/new-luci,deepak78/new-luci,remakeelectric/luci,male-puppies/luci,thesabbir/luci,taiha/luci,dwmw2/luci,openwrt/luci,fkooman/luci,Hostle/luci,hnyman/luci,lbthomsen/openwrt-luci,bittorf/luci,thesabbir/luci,ollie27/openwrt_luci,rogerpueyo/luci,david-xiao/luci,Hostle/openwrt-luci-multi-user,db260179/openwrt-bpi-r1-luci
|
3b6c5e57b5488d628ef20963e87371c5b3bdeaec
|
cherry/engine/game.lua
|
cherry/engine/game.lua
|
--------------------------------------------------------------------------------
local Background = require 'cherry.components.background'
local Screen = require 'cherry.components.screen'
local Effects = require 'cherry.engine.effects'
local group = require 'cherry.libs.group'
local _ = require 'cherry.libs.underscore'
--------------------------------------------------------------------------------
local Game = {}
--------------------------------------------------------------------------------
function Game:new(extension)
local game = _.defaults(extension, {
isRunning = false,
state = {},
elements = {}
})
setmetatable(game, { __index = Game })
return game
end
--------------------------------------------------------------------------------
function Game:initialState() return {} end
function Game:resetState() self.state = self:initialState() end
function Game:getState() return self.state end
function Game:resetElements() self.elements = {} end
--------------------------------------------------------------------------------
function Game:reset()
group.empty(App.hud)
if(self.onReset) then self:onReset() end -- from extension
self:resetState()
self:resetElements()
Camera:empty()
App.score:reset()
end
function Game:run()
self.isRunning = true
if(_G.usePhysics) then
_G.log('activated physics')
_G.physics.start()
_G.physics.setGravity( App.xGravity, App.yGravity )
end
Camera:resetZoom()
Camera:center()
Camera:start()
Background:darken()
if(self.onRun) then self:onRun() end -- from extension
if(_G.CBE) then Effects:restart() end
print('Game runs!')
end
--------------------------------------------------------------------------------
function Game:start()
self:reset()
if (self.load) then
local success = self:load()
if(success) then
self:run()
else
print('could not load properly')
self:onLoadFailed()
end
else
self:run()
end
end
------------------------------------------
function Game:stop(userExit)
if(not self.isRunning) then return end
self.isRunning = false
------------------------------------------
if(self.onStop) then self:onStop(userExit) end -- from extension
------------------------------------------
if(not userExit) then
Screen:showBands()
App.score:display()
end
------------------------------------------
Background:lighten()
if(_G.CBE) then Effects:stop(true) end
Camera:stop()
end
--------------------------------------------------------------------------------
return Game
|
--------------------------------------------------------------------------------
local Background = require 'cherry.components.background'
local Screen = require 'cherry.components.screen'
local Effects = require 'cherry.engine.effects'
local group = require 'cherry.libs.group'
local _ = require 'cherry.libs.underscore'
--------------------------------------------------------------------------------
local Game = {}
--------------------------------------------------------------------------------
function Game:new(extension)
local game = _.defaults(extension, {
isRunning = false,
state = {},
elements = {}
})
setmetatable(game, { __index = Game })
return game
end
--------------------------------------------------------------------------------
function Game:initialState() return {} end
function Game:resetState() self.state = self:initialState() end
function Game:getState() return self.state end
function Game:resetElements() self.elements = {} end
--------------------------------------------------------------------------------
-- game.start --> reset, load?, run
--------------------------------------------------------------------------------
function Game:reset()
group.empty(App.hud)
if(self.onReset) then self:onReset() end -- from extension
self:resetState()
self:resetElements()
Camera:empty()
App.score:reset()
end
function Game:run()
self.isRunning = true
if(_G.usePhysics) then
_G.log('activated physics')
_G.physics.start()
_G.physics.setGravity( App.xGravity, App.yGravity )
end
Camera:resetZoom()
Camera:center()
Camera:start()
Background:darken()
if(self.onRun) then self:onRun() end -- from extension
if(_G.CBE) then Effects:restart() end
print('Game runs!')
end
--------------------------------------------------------------------------------
function Game:start()
_G.isTutorial = App.user:isNew()
self:reset()
if (self.load) then
local success = self:load()
if(success) then
self:run()
else
print('could not load properly')
self:onLoadFailed()
end
else
self:run()
end
end
------------------------------------------
function Game:stop(userExit)
if(not self.isRunning) then return end
self.isRunning = false
------------------------------------------
if(self.onStop) then self:onStop(userExit) end -- from extension
------------------------------------------
if(not userExit) then
Screen:showBands()
App.score:display()
end
------------------------------------------
Background:lighten()
if(_G.CBE) then Effects:stop(true) end
Camera:stop()
end
--------------------------------------------------------------------------------
return Game
|
fixed _G.isTutorial setting
|
fixed _G.isTutorial setting
|
Lua
|
bsd-3-clause
|
chrisdugne/cherry
|
8abb0f28f82c5d60d7722b96b7bafeb5b2f8caf2
|
core/inputs-common.lua
|
core/inputs-common.lua
|
SILE.inputs.common = {
init = function (_, tree)
local class = tree.options.class or "plain"
local constructor = SILE.require(class, "classes", true)
-- Shim legacy stdlib based classes (most shim work done by here)
if constructor._deprecated then
if constructor._base._deprecated then
SU.error("Double inheritance of legacy classes detected. I (Caleb) spent "
.."*way too much* time making the shim work for one level, I'm "
.."not going here. Convert your classes already.")
end
end
SILE.documentState.documentClass = constructor:_init(tree.options)
SILE.documentState.documentClass:start()
-- Prepend the dirname of the input file to the Lua search path
local dirname = SILE.masterFilename:match("(.-)[^%/]+$")
package.path = dirname.."?;"..dirname.."?.lua;"..package.path
end
}
local function debugAST(ast, level)
if not ast then SU.error("debugAST called with nil", true) end
local out = string.rep(" ", 1+level)
if level == 0 then SU.debug("ast", "["..SILE.currentlyProcessingFile) end
if type(ast) == "function" then SU.debug("ast", out.."(function)") end
for i=1, #ast do
local content = ast[i]
if type(content) == "string" then
SU.debug("ast", out.."["..content.."]")
elseif SILE.Commands[content.command] then
local options = pl.tablex.size(content.options) > 0 and content.options or ""
SU.debug("ast", out.."\\"..content.command..options)
if (#content>=1) then debugAST(content, level+1) end
elseif content.id == "texlike_stuff" or (not content.command and not content.id) then
debugAST(content, level+1)
else
SU.debug("ast", out.."?\\"..(content.command or content.id))
end
end
if level == 0 then SU.debug("ast", "]") end
end
SILE.process = function (input)
if not input then return end
if type(input) == "function" then return input() end
if SU.debugging("ast") then
debugAST(input, 0)
end
for i=1, #input do
local content = input[i]
if type(content) == "string" then
SILE.typesetter:typeset(content)
elseif type(content) == "function" then
content()
elseif SILE.Commands[content.command] then
SILE.call(content.command, content.options, content)
elseif content.id == "texlike_stuff" or (not content.command and not content.id) then
local pId = SILE.traceStack:pushContent(content, "texlike_stuff")
SILE.process(content)
SILE.traceStack:pop(pId)
else
local pId = SILE.traceStack:pushContent(content)
SU.error("Unknown command "..(content.command or content.id))
SILE.traceStack:pop(pId)
end
end
end
-- Just a simple one-level find. We're not reimplementing XPath here.
SILE.findInTree = function (tree, command)
for i=1, #tree do
if type(tree[i]) == "table" and tree[i].command == command then
return tree[i]
end
end
end
|
SILE.inputs.common = {
init = function (_, tree)
local class = tree.options.class or "plain"
local constructor = SILE.require(class, "classes", true)
-- Shim legacy stdlib based classes (most shim work done by here)
if constructor._deprecated then
if constructor._base._deprecated then
SU.error("Double inheritance of legacy classes detected. I (Caleb) spent "
.."*way too much* time making the shim work for one level, I'm "
.."not going here. Convert your classes already.")
end
end
SILE.documentState.documentClass = constructor:_init(tree.options)
SILE.documentState.documentClass:start()
end
}
local function debugAST(ast, level)
if not ast then SU.error("debugAST called with nil", true) end
local out = string.rep(" ", 1+level)
if level == 0 then SU.debug("ast", "["..SILE.currentlyProcessingFile) end
if type(ast) == "function" then SU.debug("ast", out.."(function)") end
for i=1, #ast do
local content = ast[i]
if type(content) == "string" then
SU.debug("ast", out.."["..content.."]")
elseif SILE.Commands[content.command] then
local options = pl.tablex.size(content.options) > 0 and content.options or ""
SU.debug("ast", out.."\\"..content.command..options)
if (#content>=1) then debugAST(content, level+1) end
elseif content.id == "texlike_stuff" or (not content.command and not content.id) then
debugAST(content, level+1)
else
SU.debug("ast", out.."?\\"..(content.command or content.id))
end
end
if level == 0 then SU.debug("ast", "]") end
end
SILE.process = function (input)
if not input then return end
if type(input) == "function" then return input() end
if SU.debugging("ast") then
debugAST(input, 0)
end
for i=1, #input do
local content = input[i]
if type(content) == "string" then
SILE.typesetter:typeset(content)
elseif type(content) == "function" then
content()
elseif SILE.Commands[content.command] then
SILE.call(content.command, content.options, content)
elseif content.id == "texlike_stuff" or (not content.command and not content.id) then
local pId = SILE.traceStack:pushContent(content, "texlike_stuff")
SILE.process(content)
SILE.traceStack:pop(pId)
else
local pId = SILE.traceStack:pushContent(content)
SU.error("Unknown command "..(content.command or content.id))
SILE.traceStack:pop(pId)
end
end
end
-- Just a simple one-level find. We're not reimplementing XPath here.
SILE.findInTree = function (tree, command)
for i=1, #tree do
if type(tree[i]) == "table" and tree[i].command == command then
return tree[i]
end
end
end
|
fix(inputs): Drop Lua path handling duplicated in core
|
fix(inputs): Drop Lua path handling duplicated in core
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
2a211bed29de028499e85d41d5288744a590e490
|
src/thread.lua
|
src/thread.lua
|
local loader = function(loader, ...)
local thread = require"_cqueues.thread"
--
-- thread.start
--
local cache = {}
local function dump(fn)
if type(fn) == "string" then
return fn
else
if not cache[fn] then
cache[fn] = string.dump(fn)
end
return cache[fn]
end
end
local include = {
"cqueues",
"cqueues.errno",
"cqueues.socket",
"cqueues.signal",
"cqueues.thread",
"cqueues.notify",
}
local start = thread.start; thread.start = function(enter, ...)
local function init(self, pipe, nloaders, ...)
local function preload(name, code)
local loader = load(code, nil, "bt", _ENV)
package.loaded[name] = loader(loader, name)
end
local function unpack(n, ...)
if n > 0 then
local name, code = select(1, ...)
preload(name, code)
return unpack(n - 1, select(3, ...))
else
return ...
end
end
nloaders = tonumber(nloaders)
local enter = unpack(nloaders, ...)
return load(enter)(pipe, select(nloaders * 2 + 2, ...))
end
local function pack(i, enter, ...)
if i == 1 then
return dump(init), #include, pack(i + 1, enter, ...)
elseif include[i - 1] then
return include[i - 1], dump(require(include[i - 1]).loader), pack(i + 1, enter, ...)
else
return dump(enter), ...
end
end
return start(pack(1, enter, ...))
end
--
-- thread:join
--
local monotime = require"cqueues".monotime
local poll = require"cqueues".poll
local EAGAIN = require"cqueues.errno".EAGAIN
local ETIMEDOUT = require"cqueues.errno".ETIMEDOUT
local join; join = thread.interpose("join", function (self, timeout)
local deadline = timeout and (monotime() + timeout)
while true do
local ok, why = join(self)
if ok then
return true, why
elseif why ~= EAGAIN then
return false, why
else
if deadline then
local curtime = monotime()
if curtime >= deadline then
return false, ETIMEDOUT
else
poll(self, deadline - curtime)
end
else
poll(self)
end
end
end
end)
thread.loader = loader
return thread
end -- loader
return loader(loader, ...)
|
local loader = function(loader, ...)
local thread = require"_cqueues.thread"
--
-- thread.start
--
local cache = {}
local function dump(fn)
if type(fn) == "string" then
return fn
else
if not cache[fn] then
cache[fn] = string.dump(fn)
end
return cache[fn]
end
end
local include = {
"cqueues",
"cqueues.errno",
"cqueues.socket",
"cqueues.signal",
"cqueues.thread",
"cqueues.notify",
}
local start = thread.start; thread.start = function(enter, ...)
local function init(self, pipe, nloaders, ...)
local function loadblob(chunk, source, ...)
if _VERSION == "Lua 5.1" then
return loadstring(chunk, source)
else
return load(chunk, source, ...)
end
end
local function preload(name, code)
local loader = loadblob(code, nil, "bt", _ENV)
package.loaded[name] = loader(loader, name)
end
local function unpack(n, ...)
if n > 0 then
local name, code = select(1, ...)
preload(name, code)
return unpack(n - 1, select(3, ...))
else
return ...
end
end
nloaders = tonumber(nloaders)
local enter = unpack(nloaders, ...)
return loadblob(enter)(pipe, select(nloaders * 2 + 2, ...))
end
local function pack(i, enter, ...)
if i == 1 then
return dump(init), #include, pack(i + 1, enter, ...)
elseif include[i - 1] then
return include[i - 1], dump(require(include[i - 1]).loader), pack(i + 1, enter, ...)
else
return dump(enter), ...
end
end
return start(pack(1, enter, ...))
end
--
-- thread:join
--
local monotime = require"cqueues".monotime
local poll = require"cqueues".poll
local EAGAIN = require"cqueues.errno".EAGAIN
local ETIMEDOUT = require"cqueues.errno".ETIMEDOUT
local join; join = thread.interpose("join", function (self, timeout)
local deadline = timeout and (monotime() + timeout)
while true do
local ok, why = join(self)
if ok then
return true, why
elseif why ~= EAGAIN then
return false, why
else
if deadline then
local curtime = monotime()
if curtime >= deadline then
return false, ETIMEDOUT
else
poll(self, deadline - curtime)
end
else
poll(self)
end
end
end
end)
thread.loader = loader
return thread
end -- loader
return loader(loader, ...)
|
fix thread function loading on Lua 5.1/LuaJIT
|
fix thread function loading on Lua 5.1/LuaJIT
|
Lua
|
mit
|
wahern/cqueues,bigcrush/cqueues,daurnimator/cqueues,wahern/cqueues,daurnimator/cqueues,bigcrush/cqueues
|
ec593dcf60b54ca401aa7bc255b95459155d9735
|
gfx.lua
|
gfx.lua
|
local ffi = require 'ffi'
local uuid = require 'uuid'
local base64 = require 'base64'
require 'pl.text'.format_operator()
require 'image'
local itorch = require 'itorch._env'
require 'itorch.bokeh'
local util = require 'itorch.util'
-- Example: require 'image';itorch.image(image.scale(image.lena(),16,16))
function itorch.image(img, opts)
assert(itorch._iopub,'itorch._iopub socket not set')
assert(itorch._msg,'itorch._msg not set')
if torch.typename(img) == 'string' then -- assume that it is path
img = image.load(img) -- TODO: revamp this to just directly load the blob, infer file prefix, and send.
end
if torch.isTensor(img) or torch.type(img) == 'table' then
opts = opts or {input=img, padding=2}
local imgDisplay = image.toDisplayTensor(opts)
if imgDisplay:dim() == 2 then
imgDisplay = imgDisplay:view(1, imgDisplay:size(1), imgDisplay:size(2))
end
local tmp = os.tmpname() .. '.png'
image.save(tmp, imgDisplay)
-------------------------------------------------------------
-- load the image back as binary blob
local f = assert(torch.DiskFile(tmp,'r',true)):binary();
f:seekEnd();
local size = f:position()-1
f:seek(1)
local buf = torch.CharStorage(size);
assert(f:readChar(buf) == size, 'wrong number of bytes read')
f:close()
os.execute('rm -f ' .. tmp)
------------------------------------------------------------
local content = {}
content.source = 'itorch'
content.data = {}
content.data['text/plain'] = 'Console does not support images'
content.data['image/png'] = base64.encode(ffi.string(torch.data(buf), size))
content.metadata = { }
content.metadata['image/png'] = {width = imgDisplay:size(2), height = imgDisplay:size(3)}
local m = util.msg('display_data', itorch._msg)
m.content = content
util.ipyEncodeAndSend(itorch._iopub, m)
else
error('unhandled type in itorch.image:' .. torch.type(img))
end
end
local audio_template = [[
<div id="${div_id}"><audio controls src="data:audio/${extension};base64,${base64audio}" /></div>
]]
-- Example: itorch.audio('hello.mp3')
function itorch.audio(fname)
assert(itorch._iopub,'itorch._iopub socket not set')
assert(itorch._msg,'itorch._msg not set')
-- get prefix
local pos = fname:reverse():find('%.')
local ext = fname:sub(#fname-pos + 2)
assert(ext == 'mp3' or ext == 'wav' or ext == 'ogg' or ext == 'aac',
'mp3, wav, ogg, aac files supported. But found extension: ' .. ext)
-- load the audio as binary blob
local f = assert(torch.DiskFile(fname,'r',true),
'File could not be opened: ' .. fname):binary();
f:seekEnd();
local size = f:position()-1
f:seek(1)
local buf = torch.CharStorage(size);
assert(f:readChar(buf) == size, 'wrong number of bytes read')
f:close()
local base64audio = base64.encode(ffi.string(torch.data(buf), size))
local div_id = uuid.new()
local content = {}
content.source = 'itorch'
content.data = {}
content.data['text/html'] =
audio_template % {
div_id = div_id,
extension = ext,
base64audio = base64audio
};
content.metadata = {}
local m = util.msg('display_data', itorch._msg)
m.content = content
util.ipyEncodeAndSend(itorch._iopub, m)
return window_id
end
local video_template = [[
<div id="${div_id}"><video controls src="data:video/${extension};base64,${base64video}" /></div>
]]
-- Example: itorch.video('hello.mp4')
function itorch.video(fname)
assert(itorch._iopub,'itorch._iopub socket not set')
assert(itorch._msg,'itorch._msg not set')
-- get prefix
local pos = fname:reverse():find('%.')
local ext = fname:sub(#fname-pos + 2)
if ext == 'ogv' then ext = 'ogg' end
assert(ext == 'mp4' or ext == 'wav' or ext == 'ogg' or ext == 'webm',
'mp4, ogg, webm files supported. But found extension: ' .. ext)
-- load the video as binary blob
local f = assert(torch.DiskFile(fname,'r',true),
'File could not be opened: ' .. fname):binary();
f:seekEnd();
local size = f:position()-1
f:seek(1)
local buf = torch.CharStorage(size);
assert(f:readChar(buf) == size, 'wrong number of bytes read')
f:close()
local base64video = base64.encode(ffi.string(torch.data(buf), size))
local div_id = uuid.new()
local content = {}
content.source = 'itorch'
content.data = {}
content.data['text/html'] =
video_template % {
div_id = div_id,
extension = ext,
base64video = base64video
};
content.metadata = {}
local m = util.msg('display_data', itorch._msg)
m.content = content
util.ipyEncodeAndSend(itorch._iopub, m)
return window_id
end
function itorch.lena()
itorch.image(image.lena())
end
local html_template =
[[
<script type="text/javascript">
$(function() {
$("#${window_id}").html('${html_content}'); // clear any previous plot in window_id
});
</script>
<div id="${div_id}"></div>
]]
local function escape_js(s)
-- single quite
s = s:gsub("'","\\'")
-- double quote
s = s:gsub('"','\\"')
-- backslash
s = s:gsub("\\","\\\\")
-- newline
s = s:gsub("\n","\\n")
-- carriage return
s = s:gsub("\r","\\r")
-- tab
s = s:gsub("\t","\\t")
-- backspace
s = s:gsub("\b","\\b")
-- form feed
s = s:gsub("\f","\\f")
return s
end
function itorch.html(html, window_id)
html = escape_js(html)
assert(itorch._iopub,'itorch._iopub socket not set')
assert(itorch._msg,'itorch._msg not set')
local div_id = uuid.new()
window_id = window_id or div_id
local content = {}
content.source = 'itorch'
content.data = {}
content.data['text/html'] =
html_template % {
html_content = html,
window_id = window_id,
div_id = div_id
};
content.metadata = {}
-- send displayData
local m = util.msg('display_data', itorch._msg)
m.content = content
util.ipyEncodeAndSend(itorch._iopub, m)
return window_id
end
local ok,err = pcall(function() require 'xlua' end)
if ok then
local progress_warning = false
local last = os.clock()
xlua.progress = function(i, n)
-- make progress bar really slow in itorch
if os.clock() - last > 15 then -- 15 seconds
print('Progress: ' .. i .. ' / ' .. n)
last = os.clock()
end
-- local m = util.msg('clear_output', itorch._msg)
-- m.content = {}
-- m.content.wait = true
-- m.content.display = true
-- util.ipyEncodeAndSend(itorch._iopub, m)
-- itorch.html(progress_template % {})
end
end
return itorch;
|
local ffi = require 'ffi'
local uuid = require 'uuid'
local base64 = require 'base64'
require 'pl.text'.format_operator()
require 'image'
local itorch = require 'itorch._env'
require 'itorch.bokeh'
local util = require 'itorch.util'
-- Example: require 'image';itorch.image(image.scale(image.lena(),16,16))
function itorch.image(img, opts)
assert(itorch._iopub,'itorch._iopub socket not set')
assert(itorch._msg,'itorch._msg not set')
if torch.typename(img) == 'string' then -- assume that it is path
img = image.load(img, 3) -- TODO: revamp this to just directly load the blob, infer file prefix, and send.
end
if torch.isTensor(img) or torch.type(img) == 'table' then
opts = opts or {padding=2}
opts.input = img
local imgDisplay = image.toDisplayTensor(opts)
if imgDisplay:dim() == 2 then
imgDisplay = imgDisplay:view(1, imgDisplay:size(1), imgDisplay:size(2))
end
local tmp = os.tmpname() .. '.png'
image.save(tmp, imgDisplay)
-------------------------------------------------------------
-- load the image back as binary blob
local f = assert(torch.DiskFile(tmp,'r',true)):binary();
f:seekEnd();
local size = f:position()-1
f:seek(1)
local buf = torch.CharStorage(size);
assert(f:readChar(buf) == size, 'wrong number of bytes read')
f:close()
os.execute('rm -f ' .. tmp)
------------------------------------------------------------
local content = {}
content.source = 'itorch'
content.data = {}
content.data['text/plain'] = 'Console does not support images'
content.data['image/png'] = base64.encode(ffi.string(torch.data(buf), size))
content.metadata = { }
content.metadata['image/png'] = {width = imgDisplay:size(3), height = imgDisplay:size(2)}
local m = util.msg('display_data', itorch._msg)
m.content = content
util.ipyEncodeAndSend(itorch._iopub, m)
else
error('unhandled type in itorch.image:' .. torch.type(img))
end
end
local audio_template = [[
<div id="${div_id}"><audio controls src="data:audio/${extension};base64,${base64audio}" /></div>
]]
-- Example: itorch.audio('hello.mp3')
function itorch.audio(fname)
assert(itorch._iopub,'itorch._iopub socket not set')
assert(itorch._msg,'itorch._msg not set')
-- get prefix
local pos = fname:reverse():find('%.')
local ext = fname:sub(#fname-pos + 2)
assert(ext == 'mp3' or ext == 'wav' or ext == 'ogg' or ext == 'aac',
'mp3, wav, ogg, aac files supported. But found extension: ' .. ext)
-- load the audio as binary blob
local f = assert(torch.DiskFile(fname,'r',true),
'File could not be opened: ' .. fname):binary();
f:seekEnd();
local size = f:position()-1
f:seek(1)
local buf = torch.CharStorage(size);
assert(f:readChar(buf) == size, 'wrong number of bytes read')
f:close()
local base64audio = base64.encode(ffi.string(torch.data(buf), size))
local div_id = uuid.new()
local content = {}
content.source = 'itorch'
content.data = {}
content.data['text/html'] =
audio_template % {
div_id = div_id,
extension = ext,
base64audio = base64audio
};
content.metadata = {}
local m = util.msg('display_data', itorch._msg)
m.content = content
util.ipyEncodeAndSend(itorch._iopub, m)
return window_id
end
local video_template = [[
<div id="${div_id}"><video controls src="data:video/${extension};base64,${base64video}" /></div>
]]
-- Example: itorch.video('hello.mp4')
function itorch.video(fname)
assert(itorch._iopub,'itorch._iopub socket not set')
assert(itorch._msg,'itorch._msg not set')
-- get prefix
local pos = fname:reverse():find('%.')
local ext = fname:sub(#fname-pos + 2)
if ext == 'ogv' then ext = 'ogg' end
assert(ext == 'mp4' or ext == 'wav' or ext == 'ogg' or ext == 'webm',
'mp4, ogg, webm files supported. But found extension: ' .. ext)
-- load the video as binary blob
local f = assert(torch.DiskFile(fname,'r',true),
'File could not be opened: ' .. fname):binary();
f:seekEnd();
local size = f:position()-1
f:seek(1)
local buf = torch.CharStorage(size);
assert(f:readChar(buf) == size, 'wrong number of bytes read')
f:close()
local base64video = base64.encode(ffi.string(torch.data(buf), size))
local div_id = uuid.new()
local content = {}
content.source = 'itorch'
content.data = {}
content.data['text/html'] =
video_template % {
div_id = div_id,
extension = ext,
base64video = base64video
};
content.metadata = {}
local m = util.msg('display_data', itorch._msg)
m.content = content
util.ipyEncodeAndSend(itorch._iopub, m)
return window_id
end
function itorch.lena()
itorch.image(image.lena())
end
local html_template =
[[
<script type="text/javascript">
$(function() {
$("#${window_id}").html('${html_content}'); // clear any previous plot in window_id
});
</script>
<div id="${div_id}"></div>
]]
local function escape_js(s)
-- single quite
s = s:gsub("'","\\'")
-- double quote
s = s:gsub('"','\\"')
-- backslash
s = s:gsub("\\","\\\\")
-- newline
s = s:gsub("\n","\\n")
-- carriage return
s = s:gsub("\r","\\r")
-- tab
s = s:gsub("\t","\\t")
-- backspace
s = s:gsub("\b","\\b")
-- form feed
s = s:gsub("\f","\\f")
return s
end
function itorch.html(html, window_id)
html = escape_js(html)
assert(itorch._iopub,'itorch._iopub socket not set')
assert(itorch._msg,'itorch._msg not set')
local div_id = uuid.new()
window_id = window_id or div_id
local content = {}
content.source = 'itorch'
content.data = {}
content.data['text/html'] =
html_template % {
html_content = html,
window_id = window_id,
div_id = div_id
};
content.metadata = {}
-- send displayData
local m = util.msg('display_data', itorch._msg)
m.content = content
util.ipyEncodeAndSend(itorch._iopub, m)
return window_id
end
local ok,err = pcall(function() require 'xlua' end)
if ok then
local progress_warning = false
local last = os.clock()
xlua.progress = function(i, n)
-- make progress bar really slow in itorch
if os.clock() - last > 15 then -- 15 seconds
print('Progress: ' .. i .. ' / ' .. n)
last = os.clock()
end
-- local m = util.msg('clear_output', itorch._msg)
-- m.content = {}
-- m.content.wait = true
-- m.content.display = true
-- util.ipyEncodeAndSend(itorch._iopub, m)
-- itorch.html(progress_template % {})
end
end
return itorch;
|
fixing image display
|
fixing image display
|
Lua
|
bsd-3-clause
|
michaf/iTorch,Laeeth/dbokeh_torch,facebook/iTorch,facebook/iTorch,Laeeth/dbokeh_torch,michaf/iTorch
|
681c78897125e5a7efbef0e40d81dcfe1caf81cb
|
frontend/ui/screen.lua
|
frontend/ui/screen.lua
|
--[[
Copyright (C) 2011 Hans-Werner Hilse <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
]]--
--[[
Codes for rotation modes:
1 for no rotation,
2 for landscape with bottom on the right side of screen, etc.
2
+--------------+
| +----------+ |
| | | |
| | Freedom! | |
| | | |
| | | |
3 | | | | 1
| | | |
| | | |
| +----------+ |
| |
| |
+--------------+
0
--]]
Screen = {
width = 0,
height = 0,
pitch = 0,
native_rotation_mode = nil,
cur_rotation_mode = 0,
bb = nil,
saved_bb = nil,
fb = einkfb.open("/dev/fb0"),
}
function Screen:init()
_, self.height = self.fb:getSize()
-- for unknown strange reason, pitch*2 is less than screen width in KPW
-- so we need to calculate width by pitch here
self.width = self.fb:getPitch()*2
self.pitch = self:getPitch()
self.bb = Blitbuffer.new(self.width, self.height, self.pitch)
self.native_rotation_mode = self.fb:getOrientation()
self.cur_rotation_mode = self.native_rotation_mode
end
function Screen:refresh(refesh_type)
if self.native_rotation_mode == self.cur_rotation_mode then
self.fb.bb:blitFrom(self.bb, 0, 0, 0, 0, self.width, self.height)
elseif self.native_rotation_mode == 0 and self.cur_rotation_mode == 1 then
self.fb.bb:blitFromRotate(self.bb, 270)
elseif self.native_rotation_mode == 1 and self.cur_rotation_mode == 0 then
self.fb.bb:blitFromRotate(self.bb, 90)
end
self.fb:refresh(refesh_type)
end
function Screen:getSize()
return Geom:new{w = self.width, h = self.height}
end
function Screen:getWidth()
return self.width
end
function Screen:getHeight()
return self.height
end
function Screen:getPitch()
return self.ptich
end
function Screen:getNativeRotationMode()
-- in EMU mode, you will always get 0 from getOrientation()
return self.fb:getOrientation()
end
function Screen:getRotationMode()
return self.cur_rotation_mode
end
function Screen:getScreenMode()
if self.width > self.height then
return "landscape"
else
return "portrait"
end
end
function Screen:setRotationMode(mode)
if mode > 3 or mode < 0 then
return
end
-- mode 0 and mode 2 has the same width and height, so do mode 1 and 3
if (self.cur_rotation_mode % 2) ~= (mode % 2) then
self.width, self.height = self.height, self.width
end
self.cur_rotation_mode = mode
self.bb:free()
self.pitch = self.width/2
self.bb = Blitbuffer.new(self.width, self.height, self.pitch)
-- update mode for input module
Input.rotation = mode
end
function Screen:setScreenMode(mode)
if mode == "portrait" then
if self.cur_rotation_mode ~= 0 then
self:setRotationMode(0)
end
elseif mode == "landscape" then
if self.cur_rotation_mode ~= 1 then
self:setRotationMode(1)
end
end
end
--[[
@brief change gesture's x and y coordinates according to screen view mode
@param ges gesture that you want to adjust
@return adjusted gesture.
--]]
function Screen:adjustGesCoordinate(ges)
-- we do nothing is screen is not rotated
if self.native_rotation_mode == self.cur_rotation_mode then
return ges
end
if self.cur_rotation_mode == 1 then
--@TODO fix wipe direction 03.02 2013 (houqp)
ges.pos.x, ges.pos.y = (self.width - ges.pos.y), (ges.pos.x)
end
return ges
end
function Screen:saveCurrentBB()
local width, height = self:getWidth(), self:getHeight()
if not self.saved_bb then
self.saved_bb = Blitbuffer.new(width, height, self:getPitch())
end
if self.saved_bb:getWidth() ~= width then
self.saved_bb:free()
self.saved_bb = Blitbuffer.new(width, height, self:getPitch())
end
self.saved_bb:blitFullFrom(self.bb)
end
function Screen:restoreFromSavedBB()
self:restoreFromBB(self.saved_bb)
end
function Screen:getCurrentScreenBB()
local bb = Blitbuffer.new(self:getWidth(), self:getHeight())
bb:blitFullFrom(self.bb)
return bb
end
function Screen:restoreFromBB(bb)
if bb then
self.bb:blitFullFrom(bb)
else
DEBUG("Got nil bb in restoreFromSavedBB!")
end
end
|
--[[
Copyright (C) 2011 Hans-Werner Hilse <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
]]--
--[[
Codes for rotation modes:
1 for no rotation,
2 for landscape with bottom on the right side of screen, etc.
2
+--------------+
| +----------+ |
| | | |
| | Freedom! | |
| | | |
| | | |
3 | | | | 1
| | | |
| | | |
| +----------+ |
| |
| |
+--------------+
0
--]]
Screen = {
width = 0,
height = 0,
pitch = 0,
native_rotation_mode = nil,
cur_rotation_mode = 0,
bb = nil,
saved_bb = nil,
fb = einkfb.open("/dev/fb0"),
}
function Screen:init()
_, self.height = self.fb:getSize()
-- for unknown strange reason, pitch*2 is less than screen width in KPW
-- so we need to calculate width by pitch here
self.pitch = self.fb:getPitch()
self.width = self.pitch * 2
self.bb = Blitbuffer.new(self.width, self.height, self.pitch)
if self.width > self.height then
-- For another unknown strange reason, self.fb:getOrientation always
-- return 0 in KPW, even though we are in landscape mode.
-- Seems like the native framework change framebuffer on the fly when
-- starting booklet. Starting KPV from ssh and KPVBooklet will get
-- different framebuffer height and width.
--
--self.native_rotation_mode = self.fb:getOrientation()
self.native_rotation_mode = 1
else
self.native_rotation_mode = 0
end
self.cur_rotation_mode = self.native_rotation_mode
end
function Screen:refresh(refesh_type)
if self.native_rotation_mode == self.cur_rotation_mode then
self.fb.bb:blitFrom(self.bb, 0, 0, 0, 0, self.width, self.height)
elseif self.native_rotation_mode == 0 and self.cur_rotation_mode == 1 then
self.fb.bb:blitFromRotate(self.bb, 270)
elseif self.native_rotation_mode == 1 and self.cur_rotation_mode == 0 then
self.fb.bb:blitFromRotate(self.bb, 90)
end
self.fb:refresh(refesh_type)
end
function Screen:getSize()
return Geom:new{w = self.width, h = self.height}
end
function Screen:getWidth()
return self.width
end
function Screen:getHeight()
return self.height
end
function Screen:getPitch()
return self.ptich
end
function Screen:getNativeRotationMode()
-- in EMU mode, you will always get 0 from getOrientation()
return self.fb:getOrientation()
end
function Screen:getRotationMode()
return self.cur_rotation_mode
end
function Screen:getScreenMode()
if self.width > self.height then
return "landscape"
else
return "portrait"
end
end
function Screen:setRotationMode(mode)
if mode > 3 or mode < 0 then
return
end
-- mode 0 and mode 2 has the same width and height, so do mode 1 and 3
if (self.cur_rotation_mode % 2) ~= (mode % 2) then
self.width, self.height = self.height, self.width
end
self.cur_rotation_mode = mode
self.bb:free()
self.pitch = self.width/2
self.bb = Blitbuffer.new(self.width, self.height, self.pitch)
-- update mode for input module
Input.rotation = mode
end
function Screen:setScreenMode(mode)
if mode == "portrait" then
if self.cur_rotation_mode ~= 0 then
self:setRotationMode(0)
end
elseif mode == "landscape" then
if self.cur_rotation_mode ~= 1 then
self:setRotationMode(1)
end
end
end
--[[
@brief change gesture's x and y coordinates according to screen view mode
@param ges gesture that you want to adjust
@return adjusted gesture.
--]]
function Screen:adjustGesCoordinate(ges)
if self.cur_rotation_mode == 1 then
--@TODO fix wipe direction 03.02 2013 (houqp)
ges.pos.x, ges.pos.y = (self.width - ges.pos.y), (ges.pos.x)
end
return ges
end
function Screen:saveCurrentBB()
local width, height = self:getWidth(), self:getHeight()
if not self.saved_bb then
self.saved_bb = Blitbuffer.new(width, height, self:getPitch())
end
if self.saved_bb:getWidth() ~= width then
self.saved_bb:free()
self.saved_bb = Blitbuffer.new(width, height, self:getPitch())
end
self.saved_bb:blitFullFrom(self.bb)
end
function Screen:restoreFromSavedBB()
self:restoreFromBB(self.saved_bb)
end
function Screen:getCurrentScreenBB()
local bb = Blitbuffer.new(self:getWidth(), self:getHeight())
bb:blitFullFrom(self.bb)
return bb
end
function Screen:restoreFromBB(bb)
if bb then
self.bb:blitFullFrom(bb)
else
DEBUG("Got nil bb in restoreFromSavedBB!")
end
end
|
fix bug for touch event coordinates handling in landscape mode
|
fix bug for touch event coordinates handling in landscape mode
This fix might only work for KPW, need to test on other devies
later.
|
Lua
|
agpl-3.0
|
apletnev/koreader-base,chihyang/koreader,NiLuJe/koreader,mwoz123/koreader,NickSavage/koreader,Frenzie/koreader-base,Markismus/koreader,Frenzie/koreader-base,houqp/koreader,Hzj-jie/koreader,Frenzie/koreader-base,houqp/koreader-base,robert00s/koreader,koreader/koreader-base,apletnev/koreader,NiLuJe/koreader-base,apletnev/koreader-base,koreader/koreader,poire-z/koreader,frankyifei/koreader-base,chrox/koreader,frankyifei/koreader-base,Hzj-jie/koreader-base,houqp/koreader-base,lgeek/koreader,Frenzie/koreader,NiLuJe/koreader,houqp/koreader-base,frankyifei/koreader,ashhher3/koreader,pazos/koreader,Hzj-jie/koreader-base,poire-z/koreader,koreader/koreader-base,noname007/koreader,apletnev/koreader-base,koreader/koreader-base,Frenzie/koreader-base,koreader/koreader-base,frankyifei/koreader-base,NiLuJe/koreader-base,NiLuJe/koreader-base,mihailim/koreader,frankyifei/koreader-base,NiLuJe/koreader-base,Hzj-jie/koreader-base,ashang/koreader,koreader/koreader,Frenzie/koreader,houqp/koreader-base,apletnev/koreader-base,Hzj-jie/koreader-base
|
c4a8f273373198540d870f9e6b283306dd880855
|
MixtureTable.lua
|
MixtureTable.lua
|
local MixtureTable, parent = torch.class('nn.MixtureTable', 'nn.Module')
function MixtureTable:__init(dim)
parent.__init(self)
self.dim = dim
self.size = torch.LongStorage()
self.batchSize = 0
self.size2 = torch.LongStorage()
self.backwardSetup = false
self.gradInput = {}
end
function MixtureTable:updateOutput(input)
local gaterInput, expertInputs = table.unpack(input)
-- buffers
self._gaterView = self._gaterView or input[1].new()
self._expert = self._expert or input[1].new()
self._expertView = self._expertView or input[1].new()
self.dimG = 2
local batchSize = gaterInput:size(1)
if gaterInput:dim() < 2 then
self.dimG = 1
self.dim = self.dim or 1
batchSize = 1
end
self.dim = self.dim or 2
if self.table or torch.type(expertInputs) == 'table' then
-- expertInputs is a Table :
self.table = true
if gaterInput:size(self.dimG) ~= #expertInputs then
error"Should be one gater output per expert"
end
local expertInput = expertInputs[1]
if self.batchSize ~= batchSize then
self.size:resize(expertInput:dim()+1):fill(1)
if self.dimG > 1 then
self.size[1] = gaterInput:size(1)
end
self.size[self.dim] = gaterInput:size(self.dimG)
self.output:resizeAs(expertInput)
self.backwardSetup = false
self.batchSize = batchSize
end
self._gaterView:view(gaterInput, self.size)
self.output:zero()
-- multiply accumulate gater outputs by their commensurate expert
for i,expertInput in ipairs(expertInputs) do
local gate = self._gaterView:select(self.dim,i):expandAs(expertInput)
self.output:addcmul(expertInput, gate)
end
else
-- expertInputs is a Tensor :
if self.batchSize ~= batchSize then
self.size:resize(expertInputs:dim()):fill(1)
if self.dimG > 1 then
self.size[1] = gaterInput:size(1)
end
self.size[self.dim] = gaterInput:size(self.dimG)
self.output:resizeAs(expertInputs:select(self.dim, 1))
self.batchSize = batchSize
self.backwardSetup = false
end
self._gaterView:view(gaterInput, self.size)
self._expert:cmul(self._gaterView:expandAs(expertInputs), expertInputs)
self.output:sum(self._expert, self.dim)
self.output:resizeAs(expertInputs:select(self.dim, 1))
end
return self.output
end
function MixtureTable:updateGradInput(input, gradOutput)
local gaterInput, expertInputs = table.unpack(input)
nn.utils.recursiveResizeAs(self.gradInput, input)
local gaterGradInput, expertGradInputs = table.unpack(self.gradInput)
-- buffers
self._sum = self._sum or input[1].new()
self._expertView2 = self._expertView2 or input[1].new()
self._expert2 = self._expert2 or input[1].new()
if self.table then
if not self.backwardSetup then
for i,expertInput in ipairs(expertInputs) do
local expertGradInput = expertGradInputs[i] or expertInput:clone()
expertGradInput:resizeAs(expertInput)
expertGradInputs[i] = expertGradInput
end
gaterGradInput:resizeAs(gaterInput)
self.backwardSetup = true
end
-- like CMulTable, but with broadcasting
for i,expertGradInput in ipairs(expertGradInputs) do
-- gater updateGradInput
self._expert:cmul(gradOutput, expertInputs[i])
if self.dimG == 1 then
self._expertView:view(self._expert, -1)
else
self._expertView:view(self._expert, gradOutput:size(1), -1)
end
self._sum:sum(self._expertView, self.dimG)
if self.dimG == 1 then
gaterGradInput[i] = self._sum:select(self.dimG,1)
else
gaterGradInput:select(self.dimG,i):copy(self._sum:select(self.dimG,1))
end
-- expert updateGradInput
local gate = self._gaterView:select(self.dim,i):expandAs(expertGradInput)
expertGradInput:cmul(gate, gradOutput)
end
else
if not self.backwardSetup then
self.size2:resize(expertInputs:dim())
self.size2:copy(expertInputs:size())
self.size2[self.dim] = 1
gaterGradInput:resizeAs(gaterInput)
self.backwardSetup = true
end
-- gater updateGradInput
self._expertView:view(gradOutput, self.size2)
local gradOutput = self._expertView:expandAs(expertInputs)
self._expert:cmul(gradOutput, expertInputs)
local expert = self._expert:transpose(self.dim, self.dimG)
if not expert:isContiguous() then
self._expert2:resizeAs(expert)
self._expert2:copy(expert)
expert = self._expert2
end
if self.dimG == 1 then
self._expertView2:view(expert, gaterInput:size(1), -1)
else
self._expertView2:view(expert, gaterInput:size(1), gaterInput:size(2), -1)
end
gaterGradInput:sum(self._expertView2, self.dimG+1)
gaterGradInput:resizeAs(gaterInput)
-- expert updateGradInput
expertGradInputs:cmul(self._gaterView:expandAs(expertInputs), gradOutput)
end
return self.gradInput
end
function MixtureTable:type(type, tensorCache)
self._gaterView = nil
self._expert = nil
self._expertView = nil
self._sum = nil
self._expert2 = nil
self._expertView2 = nil
return parent.type(self, type, tensorCache)
end
function MixtureTable:clearState()
nn.utils.clear(self, {
'_gaterView',
'_expert',
'_expertView',
'_sum',
'_expert2',
'_expertView2',
})
return parent.clearState(self)
end
|
local MixtureTable, parent = torch.class('nn.MixtureTable', 'nn.Module')
function MixtureTable:__init(dim)
parent.__init(self)
self.dim = dim
self.size = torch.LongStorage()
self.batchSize = 0
self.size2 = torch.LongStorage()
self.backwardSetup = false
self.gradInput = {}
end
function MixtureTable:updateOutput(input)
local gaterInput, expertInputs = table.unpack(input)
-- buffers
self._gaterView = self._gaterView or input[1].new()
self._expert = self._expert or input[1].new()
self._expertView = self._expertView or input[1].new()
self.dimG = 2
local batchSize = gaterInput:size(1)
if gaterInput:dim() < 2 then
self.dimG = 1
self.dim = self.dim or 1
batchSize = 1
end
self.dim = self.dim or 2
if self.table or torch.type(expertInputs) == 'table' then
-- expertInputs is a Table :
self.table = true
if gaterInput:size(self.dimG) ~= #expertInputs then
error"Should be one gater output per expert"
end
local expertInput = expertInputs[1]
self.size:resize(expertInput:dim()+1):fill(1)
if self.dimG > 1 then
self.size[1] = gaterInput:size(1)
end
self.size[self.dim] = gaterInput:size(self.dimG)
self.output:resizeAs(expertInput)
self.batchSize = batchSize
self._gaterView:view(gaterInput, self.size)
self.output:zero()
-- multiply accumulate gater outputs by their commensurate expert
for i,expertInput in ipairs(expertInputs) do
local gate = self._gaterView:select(self.dim,i):expandAs(expertInput)
self.output:addcmul(expertInput, gate)
end
else
-- expertInputs is a Tensor :
self.size:resize(expertInputs:dim()):fill(1)
if self.dimG > 1 then
self.size[1] = gaterInput:size(1)
end
self.size[self.dim] = gaterInput:size(self.dimG)
self.output:resizeAs(expertInputs:select(self.dim, 1))
self.batchSize = batchSize
self._gaterView:view(gaterInput, self.size)
self._expert:cmul(self._gaterView:expandAs(expertInputs), expertInputs)
self.output:sum(self._expert, self.dim)
self.output:resizeAs(expertInputs:select(self.dim, 1))
end
return self.output
end
function MixtureTable:updateGradInput(input, gradOutput)
local gaterInput, expertInputs = table.unpack(input)
nn.utils.recursiveResizeAs(self.gradInput, input)
local gaterGradInput, expertGradInputs = table.unpack(self.gradInput)
-- buffers
self._sum = self._sum or input[1].new()
self._expertView2 = self._expertView2 or input[1].new()
self._expert2 = self._expert2 or input[1].new()
if self.table then
for i,expertInput in ipairs(expertInputs) do
local expertGradInput = expertGradInputs[i] or expertInput:clone()
expertGradInput:resizeAs(expertInput)
expertGradInputs[i] = expertGradInput
end
gaterGradInput:resizeAs(gaterInput)
-- like CMulTable, but with broadcasting
for i,expertGradInput in ipairs(expertGradInputs) do
-- gater updateGradInput
self._expert:cmul(gradOutput, expertInputs[i])
if self.dimG == 1 then
self._expertView:view(self._expert, -1)
else
self._expertView:view(self._expert, gradOutput:size(1), -1)
end
self._sum:sum(self._expertView, self.dimG)
if self.dimG == 1 then
gaterGradInput[i] = self._sum:select(self.dimG,1)
else
gaterGradInput:select(self.dimG,i):copy(self._sum:select(self.dimG,1))
end
-- expert updateGradInput
local gate = self._gaterView:select(self.dim,i):expandAs(expertGradInput)
expertGradInput:cmul(gate, gradOutput)
end
else
self.size2:resize(expertInputs:dim())
self.size2:copy(expertInputs:size())
self.size2[self.dim] = 1
gaterGradInput:resizeAs(gaterInput)
-- gater updateGradInput
self._expertView:view(gradOutput, self.size2)
local gradOutput = self._expertView:expandAs(expertInputs)
self._expert:cmul(gradOutput, expertInputs)
local expert = self._expert:transpose(self.dim, self.dimG)
if not expert:isContiguous() then
self._expert2:resizeAs(expert)
self._expert2:copy(expert)
expert = self._expert2
end
if self.dimG == 1 then
self._expertView2:view(expert, gaterInput:size(1), -1)
else
self._expertView2:view(expert, gaterInput:size(1), gaterInput:size(2), -1)
end
gaterGradInput:sum(self._expertView2, self.dimG+1)
gaterGradInput:resizeAs(gaterInput)
-- expert updateGradInput
expertGradInputs:cmul(self._gaterView:expandAs(expertInputs), gradOutput)
end
return self.gradInput
end
function MixtureTable:type(type, tensorCache)
self._gaterView = nil
self._expert = nil
self._expertView = nil
self._sum = nil
self._expert2 = nil
self._expertView2 = nil
return parent.type(self, type, tensorCache)
end
function MixtureTable:clearState()
nn.utils.clear(self, {
'_gaterView',
'_expert',
'_expertView',
'_sum',
'_expert2',
'_expertView2',
})
return parent.clearState(self)
end
|
Bugfix for variable size inputs
|
Bugfix for variable size inputs
If batch size is same between two successive inputs of variable size, self.size was not recomputed. Removed batch size checks in order to recompute self.size every time.
|
Lua
|
bsd-3-clause
|
joeyhng/nn,apaszke/nn,nicholas-leonard/nn
|
410c381ba19247213c3a2caef64edcd5ede96ca4
|
lua.lua
|
lua.lua
|
-- So let's start with adding POSITIVE INTEGERS (integers > 0) without +
function add1(x,y) return -((-x)-y) end
function increment1(i)
for x=i,math.huge do
if x>i then
return x
end
end
end
function add2(a,b)
for i=1,b do
a = increment1(a)
end
return a
end
-- Oh so you want negative integers too?
function add3(a,b)
if a == 0 then
return b
elseif b == 0 then
return a
end
if b > 0 then
return add2(a,b)
else
return -add2(-a,-b)
end
end
-- Multiply
function mul1(a,b)
for i=1,b do
a = add1(a,a)
end
return a
end
function mul2(a,b) -- POSITIVE INT ONLY
for i=1,b do
a = add2(a,a)
end
return a
end
|
-- So let's start with adding POSITIVE INTEGERS (integers > 0) without +
function add1(x,y) return -((-x)-y) end
function increment1(i)
for x=i,math.huge do
if x>i then
return x
end
end
end
function add2(a,b)
for i=1,b do
a = increment1(a)
end
return a
end
-- Oh so you want negative integers too?
function add3(a,b)
if a == 0 then
return b
elseif b == 0 then
return a
end
if b > 0 then
return add2(a,b)
else
return -add2(-a,-b)
end
end
-- Multiply
function mul1(a,b)
if b > 0 then
for i=1,b do
a = add1(a,a)
end
else
for i=1,-b do
a = add1(a,a)
end
return -a
end
return a
end
function mul2(a,b) -- POSITIVE a ONLY
if b > 0 then
for i=1,b do
a = add2(a,a)
end
else
for i=1,-b do
a = add2(a,a)
end
return -a
end
return a
end
function mul3(a,b)
if b > 0 then
for i=1,b do
a = add3(a,a)
end
else
for i=1,-b do
a = add3(a,a)
end
return -a
end
return a
end
|
Update lua.lua
|
Update lua.lua
Add missing mul3, fix derps. UNTESTED! probably doesn't even work :/
|
Lua
|
mit
|
SoniEx2/Stuff,SoniEx2/Stuff
|
3114e91f9040e3b22615502d6551fa4b68ff27c0
|
kong/clustering/init.lua
|
kong/clustering/init.lua
|
local _M = {}
local pl_file = require("pl.file")
local pl_tablex = require("pl.tablex")
local ssl = require("ngx.ssl")
local openssl_x509 = require("resty.openssl.x509")
local ngx_null = ngx.null
local ngx_md5 = ngx.md5
local tostring = tostring
local assert = assert
local concat = table.concat
local sort = table.sort
local type = type
local MT = { __index = _M, }
local function table_to_sorted_string(t)
if t == ngx_null then
return "/null/"
end
local typ = type(t)
if typ == "table" then
local i = 1
local o = { "{" }
for k, v in pl_tablex.sort(t) do
o[i+1] = table_to_sorted_string(k)
o[i+2] = ":"
o[i+3] = table_to_sorted_string(v)
o[i+4] = ";"
i=i+4
end
if i == 1 then
i = i + 1
end
o[i] = "}"
return concat(o, nil, 1, i)
elseif typ == "string" then
return '$' .. t .. '$'
elseif typ == "number" then
return '#' .. tostring(t) .. '#'
elseif typ == "boolean" then
return '?' .. tostring(t) .. '?'
else
return '(' .. tostring(t) .. ')'
end
end
function _M.new(conf)
assert(conf, "conf can not be nil", 2)
local self = {
conf = conf,
}
setmetatable(self, MT)
-- note: pl_file.read throws error on failure so
-- no need for error checking
local cert = pl_file.read(conf.cluster_cert)
self.cert = assert(ssl.parse_pem_cert(cert))
cert = openssl_x509.new(cert, "PEM")
self.cert_digest = cert:digest("sha256")
local key = pl_file.read(conf.cluster_cert_key)
self.cert_key = assert(ssl.parse_pem_priv_key(key))
self.child = require("kong.clustering." .. conf.role).new(self)
return self
end
function _M:calculate_config_hash(config_table)
return ngx_md5(table_to_sorted_string(config_table))
end
function _M:handle_cp_websocket()
return self.child:handle_cp_websocket()
end
function _M:init_worker()
self.plugins_list = assert(kong.db.plugins:get_handlers())
sort(self.plugins_list, function(a, b)
return a.name:lower() < b.name:lower()
end)
self.plugins_list = pl_tablex.map(function(p)
return { name = p.name, version = p.handler.VERSION, }
end, self.plugins_list)
self.child:init_worker()
end
return _M
|
local _M = {}
local pl_file = require("pl.file")
local pl_tablex = require("pl.tablex")
local ssl = require("ngx.ssl")
local openssl_x509 = require("resty.openssl.x509")
local ngx_null = ngx.null
local ngx_md5 = ngx.md5
local tostring = tostring
local assert = assert
local error = error
local concat = table.concat
local sort = table.sort
local type = type
local MT = { __index = _M, }
local compare_sorted_strings
local function to_sorted_string(value)
if value == ngx_null then
return "/null/"
end
local t = type(value)
if t == "table" then
local i = 1
local o = { "{" }
for k, v in pl_tablex.sort(value, compare_sorted_strings) do
o[i+1] = to_sorted_string(k)
o[i+2] = ":"
o[i+3] = to_sorted_string(v)
o[i+4] = ";"
i=i+4
end
if i == 1 then
i = i + 1
end
o[i] = "}"
return concat(o, nil, 1, i)
elseif t == "string" then
return "$" .. value .. "$"
elseif t == "number" then
return "#" .. tostring(value) .. "#"
elseif t == "boolean" then
return "?" .. tostring(value) .. "?"
else
error("invalid type to be sorted (JSON types are supported")
end
end
compare_sorted_strings = function(a, b)
a = to_sorted_string(a)
b = to_sorted_string(b)
return a < b
end
function _M.new(conf)
assert(conf, "conf can not be nil", 2)
local self = {
conf = conf,
}
setmetatable(self, MT)
-- note: pl_file.read throws error on failure so
-- no need for error checking
local cert = pl_file.read(conf.cluster_cert)
self.cert = assert(ssl.parse_pem_cert(cert))
cert = openssl_x509.new(cert, "PEM")
self.cert_digest = cert:digest("sha256")
local key = pl_file.read(conf.cluster_cert_key)
self.cert_key = assert(ssl.parse_pem_priv_key(key))
self.child = require("kong.clustering." .. conf.role).new(self)
return self
end
function _M:calculate_config_hash(config_table)
return ngx_md5(to_sorted_string(config_table))
end
function _M:handle_cp_websocket()
return self.child:handle_cp_websocket()
end
function _M:init_worker()
self.plugins_list = assert(kong.db.plugins:get_handlers())
sort(self.plugins_list, function(a, b)
return a.name:lower() < b.name:lower()
end)
self.plugins_list = pl_tablex.map(function(p)
return { name = p.name, version = p.handler.VERSION, }
end, self.plugins_list)
self.child:init_worker()
end
return _M
|
fix(clustering) error on hashing when given invalid types
|
fix(clustering) error on hashing when given invalid types
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
c0d5867ffef08c9c19b084d79ce59401176f5676
|
src/CppParser/premake5.lua
|
src/CppParser/premake5.lua
|
clang_msvc_flags =
{
"/wd4146", "/wd4244", "/wd4800", "/wd4345",
"/wd4355", "/wd4996", "/wd4624", "/wd4291",
"/wd4251",
"/wd4141", -- 'inline' : used more than once
}
if EnableNativeProjects() then
project "CppSharp.CppParser"
kind "SharedLib"
language "C++"
SetupNativeProject()
rtti "Off"
defines { "DLL_EXPORT" }
filter "action:vs*"
buildoptions { clang_msvc_flags }
if os.getenv("APPVEYOR") then
linkoptions { "/ignore:4099" } -- LNK4099: linking object as if no debug info
end
if os.istarget("linux") then
linkgroups "On"
end
filter {}
files
{
"*.h",
"*.cpp",
"*.lua"
}
SearchLLVM()
SetupLLVMIncludes()
SetupLLVMLibs()
CopyClangIncludes()
filter {}
project "Std-symbols"
kind "SharedLib"
language "C++"
SetupNativeProject()
rtti "Off"
defines { "DLL_EXPORT" }
filter { "action:vs*" }
buildoptions { clang_msvc_flags }
filter {}
if os.istarget("windows") then
files { "Bindings/CSharp/i686-pc-win32-msvc/Std-symbols.cpp" }
elseif os.istarget("macosx") then
if is_64_bits_mono_runtime() or _OPTIONS["arch"] == "x64" then
files { "Bindings/CSharp/x86_64-apple-darwin12.4.0/Std-symbols.cpp" }
else
files { "Bindings/CSharp/i686-apple-darwin12.4.0/Std-symbols.cpp" }
end
elseif os.istarget("linux") then
local abi = ""
if UseCxx11ABI() then
abi = "-cxx11abi"
end
files { "Bindings/CSharp/x86_64-linux-gnu"..abi.."/Std-symbols.cpp" }
else
print "Unknown architecture"
end
filter {}
end
|
clang_msvc_flags =
{
"/wd4146", "/wd4244", "/wd4800", "/wd4345",
"/wd4355", "/wd4996", "/wd4624", "/wd4291",
"/wd4251",
"/wd4141", -- 'inline' : used more than once
}
if EnableNativeProjects() then
project "CppSharp.CppParser"
kind "SharedLib"
language "C++"
SetupNativeProject()
rtti "Off"
defines { "DLL_EXPORT" }
if os.istarget("linux") then
linkgroups "On"
end
filter "action:vs*"
buildoptions { clang_msvc_flags }
if os.getenv("APPVEYOR") then
linkoptions { "/ignore:4099" } -- LNK4099: linking object as if no debug info
end
filter {}
files
{
"*.h",
"*.cpp",
"*.lua"
}
SearchLLVM()
SetupLLVMIncludes()
SetupLLVMLibs()
CopyClangIncludes()
filter {}
project "Std-symbols"
kind "SharedLib"
language "C++"
SetupNativeProject()
rtti "Off"
defines { "DLL_EXPORT" }
filter { "action:vs*" }
buildoptions { clang_msvc_flags }
filter {}
if os.istarget("windows") then
files { "Bindings/CSharp/i686-pc-win32-msvc/Std-symbols.cpp" }
elseif os.istarget("macosx") then
if is_64_bits_mono_runtime() or _OPTIONS["arch"] == "x64" then
files { "Bindings/CSharp/x86_64-apple-darwin12.4.0/Std-symbols.cpp" }
else
files { "Bindings/CSharp/i686-apple-darwin12.4.0/Std-symbols.cpp" }
end
elseif os.istarget("linux") then
local abi = ""
if UseCxx11ABI() then
abi = "-cxx11abi"
end
files { "Bindings/CSharp/x86_64-linux-gnu"..abi.."/Std-symbols.cpp" }
else
print "Unknown architecture"
end
filter {}
end
|
Enable linking groups for the parser on Linux
|
Enable linking groups for the parser on Linux
The previous fix didn't work at all because premake's syntax is extremely strange at best and without any sense whatsoever it completely failed before I moved the linking groups just a few lines up.
Signed-off-by: Dimitar Dobrev <[email protected]>
|
Lua
|
mit
|
mono/CppSharp,mono/CppSharp,mono/CppSharp,mono/CppSharp,mono/CppSharp,mono/CppSharp
|
da97e2964612609aeb544798e13598ba95ba5d64
|
Modules/Binder/BinderTouchingCalculator.lua
|
Modules/Binder/BinderTouchingCalculator.lua
|
--- Extends PartTouchingCalculator with generic binder stuff
-- @classmod BinderTouchingCalculator
-- @author Quenty
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local PartTouchingCalculator = require("PartTouchingCalculator")
local BinderUtil = require("BinderUtil")
local BinderTouchingCalculator = setmetatable({}, PartTouchingCalculator)
BinderTouchingCalculator.ClassName = "BinderTouchingCalculator"
BinderTouchingCalculator.__index = BinderTouchingCalculator
function BinderTouchingCalculator.new()
local self = setmetatable(PartTouchingCalculator.new(), BinderTouchingCalculator)
return self
end
function BinderTouchingCalculator:GetTouchingClass(binder, touchingList)
local touching = {}
for _, part in pairs(touchingList) do
local class = BinderUtil.FindFirstAncestor(self._propBinder)
if not touching[class] then
touching[class] = {
Class = class;
Touching = { part };
}
else
table.insert(touching[class].Touching, part)
end
end
local list = {}
for _, data in pairs(touching) do
table.insert(list, data)
end
return list
end
return BinderTouchingCalculator
|
--- Extends PartTouchingCalculator with generic binder stuff
-- @classmod BinderTouchingCalculator
-- @author Quenty
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local PartTouchingCalculator = require("PartTouchingCalculator")
local BinderUtil = require("BinderUtil")
local BinderTouchingCalculator = setmetatable({}, PartTouchingCalculator)
BinderTouchingCalculator.ClassName = "BinderTouchingCalculator"
BinderTouchingCalculator.__index = BinderTouchingCalculator
function BinderTouchingCalculator.new()
local self = setmetatable(PartTouchingCalculator.new(), BinderTouchingCalculator)
return self
end
function BinderTouchingCalculator:GetTouchingClass(binder, touchingList)
local touching = {}
for _, part in pairs(touchingList) do
local object = BinderUtil.FindFirstAncestor(binder, part)
if object then
if not touching[object] then
touching[object] = {
Object = object;
Touching = {
part
};
}
else
table.insert(touching[object].Touching, part)
end
end
end
local list = {}
for _, data in pairs(touching) do
table.insert(list, data)
end
return list
end
return BinderTouchingCalculator
|
Fix BinderTouchingCalculator to execute properly
|
Fix BinderTouchingCalculator to execute properly
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
448e05ade927984ed8c6a7299b9c47c69282e202
|
mods/soundset/init.lua
|
mods/soundset/init.lua
|
minetest.log("action","[mod soundset] Loading...")
soundset = {}
soundset.file = minetest.get_worldpath() .. "/sounds_config.txt"
soundset.gainplayers = {}
soundset.tmp = {}
local function save_sounds_config()
local input = io.open(soundset.file, "w")
if input then
input:write(minetest.serialize(soundset.gainplayers))
input:close()
else
minetest.log("action","echec d'ouverture (mode:w) de " .. soundset.file)
end
end
local function load_sounds_config()
local file = io.open(soundset.file, "r")
if file then
soundset.gainplayers = minetest.deserialize(file:read("*all"))
file:close()
end
if soundset.gainplayers == nil or type(soundset.gainplayers) ~= "table" then
soundset.gainplayers = {}
end
end
load_sounds_config()
soundset.set_sound = function(name, param)
if param == "" then
minetest.chat_send_player(name, "/setsound <music|ambience|mobs|other> <number>")
return
end
local param_name, param_value = param:match("^(%S+)%s(%S+)$")
if param_name == nil or param_value == nil then
minetest.chat_send_player(name, "invalid param, /setsound <music|ambience|mobs|other> <number>")
return
end
if param_name ~= "music" and param_name ~= "ambience" and param_name ~= "mobs" and param_name ~= "other" then
minetest.chat_send_player(name, "invalid param " .. param_name)
return
end
local value = tonumber(param_value)
if value == nil then
minetest.chat_send_player(name, "invalid value, " ..param_value .. " must be number")
return
end
if value < 0 then
value = 0
elseif value > 100 then
value = 100
end
if soundset.gainplayers[name][param_name] == value then
minetest.chat_send_player(name, "volume " .. param_name .. " already set to " .. value)
return
end
soundset.gainplayers[name][param_name] = value
minetest.chat_send_player(name, "sound " .. param_name .. " set to " .. value)
save_sounds_config()
end
soundset.get_gain = function(name, sound_type)
if name == nil or name == "" then
return 1
end
if not soundset.gainplayers[name] then return 1 end
local gain = soundset.gainplayers[name][sound_type]
if gain == nil then
return 1
end
return gain/100
end
local inc = function(value)
value = value + 5
if value > 100 then
value = 100
end
return value
end
local dec = function(value)
value = value - 5
if value < 0 then
value = 0
end
return value
end
local formspec = "size[6,6]"..
"label[2,0;Sound Menu]"..
"label[0,1.2;MUSIC]"..
"image_button[1.6,1;1,1;soundset_dec.png;vmusic;-]"..
"label[2.7,1.2;%s]"..
"image_button[3.5,1;1,1;soundset_inc.png;vmusic;+]"..
"label[0,2.2;AMBIENCE]"..
"image_button[1.6,2;1,1;soundset_dec.png;vambience;-]"..
"label[2.7,2.2;%s]"..
"image_button[3.5,2;1,1;soundset_inc.png;vambience;+]"..
"label[0,3.2;OTHER]"..
"image_button[1.6,3;1,1;soundset_dec.png;vother;-]"..
"label[2.7,3.2;%s]"..
"image_button[3.5,3;1,1;soundset_inc.png;vother;+]"..
"button_exit[0.5,5.2;1.5,1;abort;Abort]"..
"button_exit[4,5.2;1.5,1;abort;Ok]"
local on_show_settings = function(name, music, ambience, other)
if not soundset.tmp[name] then
soundset.tmp[name] = {}
end
soundset.tmp[name]["music"] = music
soundset.tmp[name]["ambience"] = ambience
soundset.tmp[name]["other"] = other
minetest.show_formspec( name, "soundset:settings", string.format(formspec, tostring(music), tostring(ambience), tostring(other) ))
end
minetest.register_on_player_receive_fields(function(player, formname, fields)
if formname == "soundset:settings" then
local name = player:get_player_name()
if not name then return end
local fmusic = soundset.tmp[name]["music"]
local fambience = soundset.tmp[name]["ambience"]
local fother = soundset.tmp[name]["other"]
if fields["abort"] == "Ok" then
if soundset.gainplayers[name]["music"] ~= fmusic or soundset.gainplayers[name]["ambience"] ~= fambience or soundset.gainplayers[name]["other"] ~= fother then
soundset.gainplayers[name]["music"] = fmusic
soundset.gainplayers[name]["ambience"] = fambience
soundset.gainplayers[name]["other"] = fother
save_sounds_config()
end
soundset.tmp[name] = nil
return
elseif fields["abort"] == "Abort" then
soundset.tmp[name] = nil
return
elseif fields["vmusic"] == "+" then
fmusic = inc(fmusic)
elseif fields["vmusic"] == "-" then
fmusic = dec(fmusic)
elseif fields["vambience"] == "+" then
fambience = inc(fambience)
elseif fields["vambience"] == "-" then
fambience = dec(fambience)
elseif fields["vother"] == "+" then
fother = inc(fother)
elseif fields["vother"] == "-" then
fother = dec(fother)
elseif fields["quit"] == "true" then
soundset.tmp[name] = nil
return
else
return
end
on_show_settings(name, fmusic, fambience, fother)
end
end)
if (minetest.get_modpath("unified_inventory")) then
unified_inventory.register_button("menu_soundset", {
type = "image",
image = "soundset_menu_icon.png",
tooltip = "sounds menu ",
show_with = false, --Modif MFF (Crabman 30/06/2015)
action = function(player)
local name = player:get_player_name()
if not name then return end
on_show_settings(name, soundset.gainplayers[name]["music"], soundset.gainplayers[name]["ambience"], soundset.gainplayers[name]["other"])
end,
})
end
minetest.register_chatcommand("soundset", {
params = "",
description = "Display volume menu formspec",
privs = {interact=true},
func = function(name, param)
if not name then return end
on_show_settings(name, soundset.gainplayers[name]["music"], soundset.gainplayers[name]["ambience"], soundset.gainplayers[name]["other"])
end
})
minetest.register_chatcommand("soundsets", {
params = "<music|ambience|mobs|other> <number>",
description = "Set volume sound <music|ambience|mobs|other>",
privs = {interact=true},
func = soundset.set_sound,
})
minetest.register_chatcommand("soundsetg", {
params = "",
description = "Display volume sound <music|ambience|mobs|other>",
privs = {interact=true},
func = function(name, param)
local conf = ""
for k, v in pairs(soundset.gainplayers[name]) do
conf = conf .. " " .. k .. ":" .. v
end
minetest.chat_send_player(name, "sounds conf " .. conf)
minetest.log("action","Player ".. name .. " sound conf " .. conf)
end
})
minetest.register_on_joinplayer(function(player)
local name = player:get_player_name()
if soundset.gainplayers[name] == nil then
soundset.gainplayers[name] = { ["music"] = 50, ["ambience"] = 50, ["mobs"] = 50, ["other"] = 50 }
end
end)
minetest.log("action","[mod soundset] Loaded")
|
minetest.log("action","[mod soundset] Loading...")
soundset = {}
soundset.file = minetest.get_worldpath() .. "/sounds_config.txt"
soundset.gainplayers = {}
soundset.tmp = {}
local function save_sounds_config()
local input = io.open(soundset.file, "w")
if input then
input:write(minetest.serialize(soundset.gainplayers))
input:close()
else
minetest.log("action","echec d'ouverture (mode:w) de " .. soundset.file)
end
end
local function load_sounds_config()
local file = io.open(soundset.file, "r")
if file then
soundset.gainplayers = minetest.deserialize(file:read("*all"))
file:close()
end
if soundset.gainplayers == nil or type(soundset.gainplayers) ~= "table" then
soundset.gainplayers = {}
end
end
load_sounds_config()
soundset.set_sound = function(name, param)
if param == "" then
minetest.chat_send_player(name, "/setsound <music|ambience|mobs|other> <number>")
return
end
local param_name, param_value = param:match("^(%S+)%s(%S+)$")
if param_name == nil or param_value == nil then
minetest.chat_send_player(name, "invalid param, /setsound <music|ambience|mobs|other> <number>")
return
end
if param_name ~= "music" and param_name ~= "ambience" and param_name ~= "mobs" and param_name ~= "other" then
minetest.chat_send_player(name, "invalid param " .. param_name)
return
end
local value = tonumber(param_value)
if value == nil then
minetest.chat_send_player(name, "invalid value, " ..param_value .. " must be number")
return
end
if value < 0 then
value = 0
elseif value > 100 then
value = 100
end
if soundset.gainplayers[name][param_name] == value then
minetest.chat_send_player(name, "volume " .. param_name .. " already set to " .. value)
return
end
soundset.gainplayers[name][param_name] = value
minetest.chat_send_player(name, "sound " .. param_name .. " set to " .. value)
save_sounds_config()
end
soundset.get_gain = function(name, sound_type)
if name == nil or name == "" then
return 1
end
if not soundset.gainplayers[name] then return 1 end
local gain = soundset.gainplayers[name][sound_type]
if gain == nil then
return 1
end
return gain/100
end
local inc = function(value)
value = value + 5
if value > 100 then
value = 100
end
return value
end
local dec = function(value)
value = value - 5
if value < 0 then
value = 0
end
return value
end
local formspec = "size[6,6]"..
"label[2,0;Sound Menu]"..
"label[0,1.2;MUSIC]"..
"image_button[1.6,1;1,1;soundset_dec.png;vmusic;-]"..
"label[2.7,1.2;%s]"..
"image_button[3.5,1;1,1;soundset_inc.png;vmusic;+]"..
"label[0,2.2;AMBIENCE]"..
"image_button[1.6,2;1,1;soundset_dec.png;vambience;-]"..
"label[2.7,2.2;%s]"..
"image_button[3.5,2;1,1;soundset_inc.png;vambience;+]"..
"label[0,3.2;OTHER]"..
"image_button[1.6,3;1,1;soundset_dec.png;vother;-]"..
"label[2.7,3.2;%s]"..
"image_button[3.5,3;1,1;soundset_inc.png;vother;+]"..
"button_exit[0.5,5.2;1.5,1;abort;Abort]"..
"button_exit[4,5.2;1.5,1;abort;Ok]"
local on_show_settings = function(name, music, ambience, other)
if not soundset.tmp[name] then
soundset.tmp[name] = {}
end
soundset.tmp[name]["music"] = music
soundset.tmp[name]["ambience"] = ambience
soundset.tmp[name]["other"] = other
minetest.show_formspec( name, "soundset:settings", string.format(formspec, tostring(music), tostring(ambience), tostring(other) ))
end
minetest.register_on_player_receive_fields(function(player, formname, fields)
if formname == "soundset:settings" then
local name = player:get_player_name()
if not name or name == "" then return end
local fmusic = soundset.tmp[name]["music"] or 50
local fambience = soundset.tmp[name]["ambience"] or 50
local fother = soundset.tmp[name]["other"] or 50
if fields["abort"] == "Ok" then
if soundset.gainplayers[name]["music"] ~= fmusic or soundset.gainplayers[name]["ambience"] ~= fambience or soundset.gainplayers[name]["other"] ~= fother then
soundset.gainplayers[name]["music"] = fmusic
soundset.gainplayers[name]["ambience"] = fambience
soundset.gainplayers[name]["other"] = fother
save_sounds_config()
end
soundset.tmp[name] = nil
return
elseif fields["abort"] == "Abort" then
soundset.tmp[name] = nil
return
elseif fields["vmusic"] == "+" then
fmusic = inc(fmusic)
elseif fields["vmusic"] == "-" then
fmusic = dec(fmusic)
elseif fields["vambience"] == "+" then
fambience = inc(fambience)
elseif fields["vambience"] == "-" then
fambience = dec(fambience)
elseif fields["vother"] == "+" then
fother = inc(fother)
elseif fields["vother"] == "-" then
fother = dec(fother)
elseif fields["quit"] == "true" then
soundset.tmp[name] = nil
return
else
return
end
on_show_settings(name, fmusic, fambience, fother)
end
end)
if (minetest.get_modpath("unified_inventory")) then
unified_inventory.register_button("menu_soundset", {
type = "image",
image = "soundset_menu_icon.png",
tooltip = "sounds menu ",
show_with = false, --Modif MFF (Crabman 30/06/2015)
action = function(player)
local name = player:get_player_name()
if not name then return end
on_show_settings(name, soundset.gainplayers[name]["music"], soundset.gainplayers[name]["ambience"], soundset.gainplayers[name]["other"])
end,
})
end
minetest.register_chatcommand("soundset", {
params = "",
description = "Display volume menu formspec",
privs = {interact=true},
func = function(name, param)
if not name then return end
on_show_settings(name, soundset.gainplayers[name]["music"], soundset.gainplayers[name]["ambience"], soundset.gainplayers[name]["other"])
end
})
minetest.register_chatcommand("soundsets", {
params = "<music|ambience|mobs|other> <number>",
description = "Set volume sound <music|ambience|mobs|other>",
privs = {interact=true},
func = soundset.set_sound,
})
minetest.register_chatcommand("soundsetg", {
params = "",
description = "Display volume sound <music|ambience|mobs|other>",
privs = {interact=true},
func = function(name, param)
local conf = ""
for k, v in pairs(soundset.gainplayers[name]) do
conf = conf .. " " .. k .. ":" .. v
end
minetest.chat_send_player(name, "sounds conf " .. conf)
minetest.log("action","Player ".. name .. " sound conf " .. conf)
end
})
minetest.register_on_joinplayer(function(player)
local name = player:get_player_name()
if soundset.gainplayers[name] == nil then
soundset.gainplayers[name] = { ["music"] = 50, ["ambience"] = 50, ["mobs"] = 50, ["other"] = 50 }
end
end)
minetest.log("action","[mod soundset] Loaded")
|
fix crash
|
fix crash
|
Lua
|
unlicense
|
sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,crabman77/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,crabman77/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun
|
215391b37af58177b3be5ce26d51836609cb7d57
|
premake4.lua
|
premake4.lua
|
-- os.outputof is broken in premake4, hence this workaround
function llvm_config(opt)
local stream = assert(io.popen("llvm-config-3.5 " .. opt))
local output = ""
--llvm-config contains '\n'
while true do
local curr = stream:read("*l")
if curr == nil then
break
end
output = output .. curr
end
stream:close()
return output
end
function link_libponyc()
linkoptions {
llvm_config("--ldflags")
}
links { "libponyc", "libponyrt", "libponycc", "z", "curses" }
local output = llvm_config("--libs")
for lib in string.gmatch(output, "-l(%S+)") do
links { lib }
end
configuration("not macosx")
links {
"tinfo",
"dl",
}
configuration("*")
end
solution "ponyc"
configurations {
"Debug",
"Release",
"Profile"
}
buildoptions {
"-mcx16",
"-march=native",
"-pthread"
}
linkoptions {
"-pthread"
}
flags {
"ExtraWarnings",
"FatalWarnings",
"Symbols"
}
configuration "macosx"
buildoptions "-Qunused-arguments"
linkoptions "-Qunused-arguments"
configuration "Debug"
targetdir "bin/debug"
configuration "Release"
targetdir "bin/release"
configuration "Profile"
targetdir "bin/profile"
buildoptions "-pg"
linkoptions "-pg"
configuration "Release or Profile"
defines "NDEBUG"
flags "OptimizeSpeed"
linkoptions {
"-fuse-ld=gold",
}
project "libponyc"
targetname "ponyc"
kind "StaticLib"
language "C"
buildoptions {
"-Wconversion",
"-Wno-sign-conversion",
"-std=gnu11"
}
includedirs {
llvm_config("--includedir"),
"src/common/"
}
defines {
"__STDC_CONSTANT_MACROS",
"__STDC_FORMAT_MACROS",
"__STDC_LIMIT_MACROS"
}
files {
"src/common/*.h",
"src/libponyc/**.c",
"src/libponyc/**.h"
}
excludes {
"src/libponyc/platform/**.cc",
"src/libponyc/platform/vcvars.c"
}
project "libponyrt"
targetname "ponyrt"
kind "StaticLib"
language "C"
buildoptions {
"-Wconversion",
"-Wno-sign-conversion",
"-std=gnu11"
}
includedirs {
"src/common/",
"src/libponyrt/"
}
files {
"src/libponyrt/**.h",
"src/libponyrt/**.c"
}
configuration "linux or macosx"
excludes {
"src/libponyrt/asio/iocp.c",
"src/libponyrt/lang/win_except.c"
}
configuration "linux"
excludes {
"src/libponyrt/asio/kqueue.c"
}
configuration "macosx"
excludes {
"src/libponyrt/asio/epoll.c"
}
project "libponycc"
targetname "ponycc"
kind "StaticLib"
language "C++"
buildoptions "-std=gnu++11"
includedirs {
llvm_config("--includedir"),
"src/common/"
}
defines {
"__STDC_CONSTANT_MACROS",
"__STDC_FORMAT_MACROS",
"__STDC_LIMIT_MACROS",
}
files {
"src/libponyc/codegen/host.cc",
"src/libponyc/codegen/dwarf.cc"
}
project "ponyc"
kind "ConsoleApp"
language "C++"
buildoptions {
"-Wconversion",
"-Wno-sign-conversion",
"-std=gnu11"
}
includedirs { "src/common/" }
files { "src/ponyc/**.c", "src/ponyc/**.h" }
link_libponyc()
project "gtest"
language "C++"
kind "StaticLib"
includedirs { "utils/gtest/" }
files {
"utils/gtest/gtest-all.cc",
"utils/gtest/gtest_main.cc"
}
project "tests"
language "C++"
kind "ConsoleApp"
includedirs {
"utils/gtest/",
"src/libponyc/",
"src/libponyrt/",
"src/common/"
}
buildoptions "-std=gnu++11"
files { "test/unit/ponyc/**.cc", "test/unit/ponyc/**.h" }
links { "gtest" }
link_libponyc()
|
-- os.outputof is broken in premake4, hence this workaround
function llvm_config(opt)
local stream = assert(io.popen("llvm-config-3.5 " .. opt))
local output = ""
--llvm-config contains '\n'
while true do
local curr = stream:read("*l")
if curr == nil then
break
end
output = output .. curr
end
stream:close()
return output
end
function link_libponyc()
linkoptions {
llvm_config("--ldflags")
}
links { "libponyc", "libponyrt", "libponycc" }
local output = llvm_config("--libs")
for lib in string.gmatch(output, "-l(%S+)") do
links { lib }
end
links { "z", "curses" }
configuration("not macosx")
links {
"tinfo",
"dl",
}
configuration("*")
end
solution "ponyc"
configurations {
"Debug",
"Release",
"Profile"
}
buildoptions {
"-mcx16",
"-march=native",
"-pthread"
}
linkoptions {
"-pthread"
}
flags {
"ExtraWarnings",
"FatalWarnings",
"Symbols"
}
configuration "macosx"
buildoptions "-Qunused-arguments"
linkoptions "-Qunused-arguments"
configuration "Debug"
targetdir "bin/debug"
configuration "Release"
targetdir "bin/release"
configuration "Profile"
targetdir "bin/profile"
buildoptions "-pg"
linkoptions "-pg"
configuration "Release or Profile"
defines "NDEBUG"
flags "OptimizeSpeed"
linkoptions {
"-fuse-ld=gold",
}
project "libponyc"
targetname "ponyc"
kind "StaticLib"
language "C"
buildoptions {
"-Wconversion",
"-Wno-sign-conversion",
"-std=gnu11"
}
includedirs {
llvm_config("--includedir"),
"src/common/"
}
defines {
"__STDC_CONSTANT_MACROS",
"__STDC_FORMAT_MACROS",
"__STDC_LIMIT_MACROS"
}
files {
"src/common/*.h",
"src/libponyc/**.c",
"src/libponyc/**.h"
}
excludes {
"src/libponyc/platform/**.cc",
"src/libponyc/platform/vcvars.c"
}
project "libponyrt"
targetname "ponyrt"
kind "StaticLib"
language "C"
buildoptions {
"-Wconversion",
"-Wno-sign-conversion",
"-std=gnu11"
}
includedirs {
"src/common/",
"src/libponyrt/"
}
files {
"src/libponyrt/**.h",
"src/libponyrt/**.c"
}
configuration "linux or macosx"
excludes {
"src/libponyrt/asio/iocp.c",
"src/libponyrt/lang/win_except.c"
}
configuration "linux"
excludes {
"src/libponyrt/asio/kqueue.c"
}
configuration "macosx"
excludes {
"src/libponyrt/asio/epoll.c"
}
project "libponycc"
targetname "ponycc"
kind "StaticLib"
language "C++"
buildoptions "-std=gnu++11"
includedirs {
llvm_config("--includedir"),
"src/common/"
}
defines {
"__STDC_CONSTANT_MACROS",
"__STDC_FORMAT_MACROS",
"__STDC_LIMIT_MACROS",
}
files {
"src/libponyc/codegen/host.cc",
"src/libponyc/codegen/dwarf.cc"
}
project "ponyc"
kind "ConsoleApp"
language "C++"
buildoptions {
"-Wconversion",
"-Wno-sign-conversion",
"-std=gnu11"
}
includedirs { "src/common/" }
files { "src/ponyc/**.c", "src/ponyc/**.h" }
link_libponyc()
project "gtest"
language "C++"
kind "StaticLib"
includedirs { "utils/gtest/" }
files {
"utils/gtest/gtest-all.cc",
"utils/gtest/gtest_main.cc"
}
project "tests"
language "C++"
kind "ConsoleApp"
includedirs {
"utils/gtest/",
"src/libponyc/",
"src/libponyrt/",
"src/common/"
}
buildoptions "-std=gnu++11"
files { "test/unit/ponyc/**.cc", "test/unit/ponyc/**.h" }
links { "gtest" }
link_libponyc()
|
fixed link ordering problem
|
fixed link ordering problem
|
Lua
|
bsd-2-clause
|
lukecheeseman/ponyta,ponylang/ponyc,gwelr/ponyc,sgebbie/ponyc,Praetonus/ponyc,malthe/ponyc,boemmels/ponyc,jonas-l/ponyc,jupvfranco/ponyc,sgebbie/ponyc,kulibali/ponyc,jupvfranco/ponyc,Praetonus/ponyc,ryanai3/ponyc,sgebbie/ponyc,boemmels/ponyc,Praetonus/ponyc,Theodus/ponyc,CausalityLtd/ponyc,kulibali/ponyc,jonas-l/ponyc,kulibali/ponyc,kulibali/ponyc,jupvfranco/ponyc,mkfifo/ponyc,mkfifo/ponyc,darach/ponyc,pap/ponyc,jemc/ponyc,Theodus/ponyc,jemc/ponyc,lukecheeseman/ponyta,Theodus/ponyc,jemc/ponyc,ponylang/ponyc,ryanai3/ponyc,boemmels/ponyc,CausalityLtd/ponyc,boemmels/ponyc,dipinhora/ponyc,Theodus/ponyc,Praetonus/ponyc,darach/ponyc,cquinn/ponyc,ryanai3/ponyc,jupvfranco/ponyc,mkfifo/ponyc,influx6/ponyc,cquinn/ponyc,Theodus/ponyc,Perelandric/ponyc,malthe/ponyc,shlomif/ponyc,doublec/ponyc,shlomif/ponyc,Perelandric/ponyc,dipinhora/ponyc,boemmels/ponyc,cquinn/ponyc,Perelandric/ponyc,sgebbie/ponyc,mkfifo/ponyc,doublec/ponyc,doublec/ponyc,Perelandric/ponyc,malthe/ponyc,gwelr/ponyc,jupvfranco/ponyc,lukecheeseman/ponyta,dckc/ponyc,Perelandric/ponyc,jonas-l/ponyc,sgebbie/ponyc,malthe/ponyc,cquinn/ponyc,dipinhora/ponyc,pap/ponyc,CausalityLtd/ponyc,pap/ponyc,darach/ponyc,mkfifo/ponyc,influx6/ponyc,ponylang/ponyc,dckc/ponyc
|
321cc462010f45062e8bd83c96a4cd75e0deec09
|
premake5.lua
|
premake5.lua
|
solution "NebuleuseClient"
configurations { "Debug", "Release" }
project "Nebuleuse"
kind "StaticLib"
language "C++"
targetdir "lib/%{cfg.buildcfg}"
includedirs { "include",
"curl/builds/%{cfg.buildcfg}/include",
"rapidjson/include"}
files { "src/**.cpp", "include/**.h" }
libdirs { "curl/builds/%{cfg.buildcfg}/lib" }
defines "CURL_STATICLIB"
flags{ "StaticRuntime" }
filter "configurations:Debug"
defines { "DEBUG", "_ITERATOR_DEBUG_LEVEL=2" }
flags { "Symbols" }
filter "configurations:Release"
defines { "NDEBUG" }
optimize "On"
project "Tester"
kind "ConsoleApp"
language "C++"
targetdir "Tester/bin/"
includedirs { "include" }
files { "Tester/*.cpp" }
links { "Nebuleuse" }
libdirs { "lib/"}
filter "configurations:Debug"
links { "libcurl_a_debug" }
defines { "DEBUG" }
flags { "Symbols" }
filter "configurations:Release"
links { "libcurl_a" }
defines { "NDEBUG" }
optimize "On"
|
solution "NebuleuseClient"
configurations { "Debug", "Release" }
project "Nebuleuse"
kind "StaticLib"
language "C++"
targetdir "lib/%{cfg.buildcfg}"
includedirs { "include",
"curl/builds/%{cfg.buildcfg}/include",
"rapidjson/include"}
files { "src/**.cpp", "include/**.h" }
libdirs { "curl/builds/%{cfg.buildcfg}/lib" }
defines "CURL_STATICLIB"
flags{ "StaticRuntime" }
filter "configurations:Debug"
defines { "DEBUG", "_ITERATOR_DEBUG_LEVEL=2" }
flags { "Symbols" }
filter "configurations:Release"
defines { "NDEBUG" }
optimize "On"
project "Tester"
kind "ConsoleApp"
language "C++"
targetdir "Tester/bin/"
includedirs { "include" }
files { "Tester/*.cpp" }
links { "Nebuleuse" }
libdirs { "lib/%{cfg.buildcfg}"}
flags{ "StaticRuntime" }
filter "configurations:Debug"
links { "libcurl_a_debug" }
defines { "DEBUG" }
flags { "Symbols" }
filter "configurations:Release"
links { "libcurl_a" }
defines { "NDEBUG" }
optimize "On"
|
Fixed lib path for Tester project
|
Fixed lib path for Tester project
|
Lua
|
mit
|
Nebuleuse/NebuleuseClientCpp,Nebuleuse/NebuleuseClientCpp,Nebuleuse/NebuleuseClientCpp,Orygin/NebuleuseCppClient
|
0b565fb9d4b2b90106ef53b18285add4cdaa1926
|
APS/libaps2-cpp/src/test/aps2_dissectors.lua
|
APS/libaps2-cpp/src/test/aps2_dissectors.lua
|
-- wireshark APS2 protocol dissectors
-- declare our protocol
aps_proto = Proto("aps2","APS2 Control Protocol")
local a = aps_proto.fields
local aps_commands = { [0] = "RESET",
[ 0x01] = "USER I/O ACK",
[ 0x09] = "USER I/O NACK",
[ 0x02] = "EPROM I/O",
[ 0x03] = "CHIP CONFIG I/O",
[ 0x04] = "RUN CHIP CONFIG",
[ 0x05] = "FPGA CONFIG ACK",
[ 0x0D] = "FPGA CONFIG NACK",
[ 0x06] = "FPGA CONFIG CONTROL",
[ 0x07 ] = "FGPA Status"
}
a.seqnum = ProtoField.uint16("aps.seqnum", "SeqNum")
a.packedCmd = ProtoField.uint32("aps.cmd","Command" , base.HEX)
a.ack = ProtoField.uint8("aps.cmd", "Ack", base.DEC, nil, 0x80)
a.seq = ProtoField.uint8("aps.seq", "Seq", base.DEC, nil, 0x40)
a.sel = ProtoField.uint8("aps.sel", "Sel", base.DEC, nil, 0x20)
a.rw = ProtoField.uint8("aps.rw", "R/W" , base.DEC, nil, 0x10)
a.cmd = ProtoField.uint8("aps.cmd", "Cmd" , base.HEX, aps_commands, 0x0F)
a.mode_stat = ProtoField.uint8("aps.mode_state", "Mode/Stat" , base.HEX)
a.cnt = ProtoField.uint16("aps.cnt", "Cnt" , base.DEC)
a.addr = ProtoField.uint32("aps.address", "Address" , base.HEX)
a.chipcfgPacked = ProtoField.uint32("aps.chipcfgPacked", "Chip Config I/O Command" , base.HEX)
a.target = ProtoField.uint8("aps.target", "TARGET" , base.HEX)
a.spicnt = ProtoField.uint8("aps.spicnt", "SPICNT/DATA" , base.HEX)
a.instr = ProtoField.uint16("aps.instr", "INSTR" , base.HEX)
a.instrAddr = ProtoField.uint8("aps.instrAddr", "Addr" , base.HEX)
a.instrData = ProtoField.uint8("aps.instrData", "Data" , base.HEX)
-- create a function to dissect it
function aps_proto.dissector(buffer,pinfo,tree)
pinfo.cols.protocol = "APS2"
local subtree = tree:add(aps_proto,buffer())
local offset = 0
subtree:add( a.seqnum , buffer(offset,2))
offset = offset + 2
local cmdTree = subtree:add( a.packedCmd, buffer(offset,4))
cmdTree:add( a.ack, buffer(offset,1))
cmdTree:add( a.seq, buffer(offset,1))
cmdTree:add( a.sel, buffer(offset,1))
cmdTree:add( a.rw, buffer(offset,1))
cmdTree:add( a.cmd, buffer(offset,1))
cmdTree:add( a.mode_stat, buffer(offset+1,1))
cmdTree:add( a.cnt, buffer(offset+2,2))
local cmdVal = buffer(offset,1):bitfield(4,4)
pinfo.cols.info = ( aps_commands[cmdVal] or '?')
local ackVal = buffer(offset,1):bitfield(0,1)
if (ackVal == 1) then
pinfo.cols.info:append(" - ACK")
end
offset = offset + 4
subtree:add( a.addr, buffer(offset,4))
offset = offset + 4
-- parse chip config
if (cmdVal == 0x03) then
local chipcfg = subtree:add( a.chipcfgPacked, buffer(offset,4))
chipcfg:add( a.target, buffer(offset,1))
chipcfg:add( a.spicnt, buffer(offset+1,1))
local instr = chipcfg:add( a.instr, buffer(offset+2,2))
local targetVal = buffer(offset,1):uint()
if (targetVal == 0xd8 ) then
instr:add( a.instrAddr, buffer(offset+2,1))
instr:add( a.instrData, buffer(offset+3,1))
pinfo.cols.info:append(" - PLL")
end
end
-- subtree = subtree:add(buffer(2,4),"Command")
--local cmd = buffer(2,4):uint()
--local ack = tostring(bit.tohex(bit.rshift(cmd, 31),1))
--subtree:add(buffer(2,1),"ACK: " .. ack)
--local seq = tostring(bit.tohex(bit.band(bit.rshift(cmd, 30),1), 0x1))
--subtree:add(buffer(2,1),"SEQ: " .. seq)
--local sel = tostring(bit.tohex(bit.band(bit.rshift(cmd, 29),1), 0x1))
--subtree:add(buffer(2,1),"SEL: " .. sel)
--local rw = tostring(bit.tohex(bit.band(bit.rshift(cmd, 28),1), 0x1))
--subtree:add(buffer(2,1),"R/W: " .. rw)
--local cmd2 = tostring(bit.tohex(bit.band(bit.rshift(cmd, 24), 0x7)))
--subtree:add(buffer(2,1),"CMD: " .. cmd2)
--local mode_stat = tostring(bit.tohex(bit.band(bit.rshift(cmd, 16), 0xFF)))
--subtree:add(buffer(2,1),"MODE/STAT: " .. mode_stat)
--local cnt = tostring(bit.tohex(bit.band(cmd, 0xFF)))
--subtree:add(buffer(2,1),"CNT: " .. cnt)
--subtree = subtree:add(buffer(6,4),"Addr:" .. buffer(6,4))
end
eth_table = DissectorTable.get("ethertype")
-- attach to ethernet type 0xBBAE
eth_table:add(47950,aps_proto)
|
-- wireshark APS2 protocol dissectors
-- declare our protocol
aps_proto = Proto("aps2","APS2 Control Protocol")
local a = aps_proto.fields
local aps_commands = { [0] = "RESET",
[ 0x01] = "USER I/O ACK",
[ 0x09] = "USER I/O NACK",
[ 0x02] = "EPROM I/O",
[ 0x03] = "CHIP CONFIG I/O",
[ 0x04] = "RUN CHIP CONFIG",
[ 0x05] = "FPGA CONFIG ACK",
[ 0x0D] = "FPGA CONFIG NACK",
[ 0x06] = "FPGA CONFIG CONTROL",
[ 0x07 ] = "FGPA Status"
}
a.seqnum = ProtoField.uint16("aps.seqnum", "SeqNum")
a.packedCmd = ProtoField.uint32("aps.cmd","Command" , base.HEX)
a.ack = ProtoField.uint8("aps.cmd", "Ack", base.DEC, nil, 0x80)
a.seq = ProtoField.uint8("aps.seq", "Seq", base.DEC, nil, 0x40)
a.sel = ProtoField.uint8("aps.sel", "Sel", base.DEC, nil, 0x20)
a.rw = ProtoField.uint8("aps.rw", "R/W" , base.DEC, nil, 0x10)
a.cmd = ProtoField.uint8("aps.cmd", "Cmd" , base.HEX, aps_commands, 0x0F)
a.mode_stat = ProtoField.uint8("aps.mode_state", "Mode/Stat" , base.HEX)
a.cnt = ProtoField.uint16("aps.cnt", "Cnt" , base.DEC)
a.addr = ProtoField.uint32("aps.address", "Address" , base.HEX)
a.chipcfgPacked = ProtoField.uint32("aps.chipcfgPacked", "Chip Config I/O Command" , base.HEX)
a.target = ProtoField.uint8("aps.target", "TARGET" , base.HEX)
a.spicnt = ProtoField.uint8("aps.spicnt", "SPICNT/DATA" , base.HEX)
a.instr = ProtoField.uint16("aps.instr", "INSTR" , base.HEX)
a.instrAddr = ProtoField.uint32("aps.instrAddr", "Addr" , base.HEX)
a.payload = ProtoField.bytes("aps.payload", "Data")
a.hostFirmwareVersion = ProtoField.uint32("aps.hostFirmwareVersion", "Host Firmware Version", base.HEX)
-- create a function to dissect it
function aps_proto.dissector(buffer,pinfo,tree)
pinfo.cols.protocol = "APS2"
local subtree = tree:add(aps_proto,buffer())
local offset = 0
subtree:add( a.seqnum , buffer(offset,2))
offset = offset + 2
local cmdTree = subtree:add( a.packedCmd, buffer(offset,4))
cmdTree:add( a.ack, buffer(offset,1))
cmdTree:add( a.seq, buffer(offset,1))
cmdTree:add( a.sel, buffer(offset,1))
cmdTree:add( a.rw, buffer(offset,1))
cmdTree:add( a.cmd, buffer(offset,1))
cmdTree:add( a.mode_stat, buffer(offset+1,1))
cmdTree:add( a.cnt, buffer(offset+2,2))
local cmdVal = buffer(offset,1):bitfield(4,4)
pinfo.cols.info = ( aps_commands[cmdVal] or '?')
local ackVal = buffer(offset,1):bitfield(0,1)
if (ackVal == 1) then
pinfo.cols.info:append(" - ACK")
end
offset = offset + 4
subtree:add( a.addr, buffer(offset,4))
offset = offset + 4
if ((buffer:len() - 24) > 0) then
subtree:add(a.payload, buffer(offset))
end
-- parse chip config
if (cmdVal == 0x03) then
local chipcfg = subtree:add( a.chipcfgPacked, buffer(offset,4))
chipcfg:add( a.target, buffer(offset,1))
chipcfg:add( a.spicnt, buffer(offset+1,1))
local instr = chipcfg:add( a.instr, buffer(offset+2,2))
local targetVal = buffer(offset,1):uint()
if (targetVal == 0xd8 ) then
instr:add( a.instrAddr, buffer(offset+2,1))
instr:add( a.instrData, buffer(offset+3,1))
pinfo.cols.info:append(" - PLL")
end
end
-- parse status words
-- if (cmdVal == 0x07) then
-- local
-- subtree = subtree:add(buffer(2,4),"Command")
--local cmd = buffer(2,4):uint()
--local ack = tostring(bit.tohex(bit.rshift(cmd, 31),1))
--subtree:add(buffer(2,1),"ACK: " .. ack)
--local seq = tostring(bit.tohex(bit.band(bit.rshift(cmd, 30),1), 0x1))
--subtree:add(buffer(2,1),"SEQ: " .. seq)
--local sel = tostring(bit.tohex(bit.band(bit.rshift(cmd, 29),1), 0x1))
--subtree:add(buffer(2,1),"SEL: " .. sel)
--local rw = tostring(bit.tohex(bit.band(bit.rshift(cmd, 28),1), 0x1))
--subtree:add(buffer(2,1),"R/W: " .. rw)
--local cmd2 = tostring(bit.tohex(bit.band(bit.rshift(cmd, 24), 0x7)))
--subtree:add(buffer(2,1),"CMD: " .. cmd2)
--local mode_stat = tostring(bit.tohex(bit.band(bit.rshift(cmd, 16), 0xFF)))
--subtree:add(buffer(2,1),"MODE/STAT: " .. mode_stat)
--local cnt = tostring(bit.tohex(bit.band(cmd, 0xFF)))
--subtree:add(buffer(2,1),"CNT: " .. cnt)
--subtree = subtree:add(buffer(6,4),"Addr:" .. buffer(6,4))
end
eth_table = DissectorTable.get("ethertype")
-- attach to ethernet type 0xBBAE
eth_table:add(47950,aps_proto)
|
Lua dissector shows packet payload.
|
Lua dissector shows packet payload.
Also fix address type.
|
Lua
|
apache-2.0
|
BBN-Q/libaps2,BBN-Q/libaps2,BBN-Q/libaps2,BBN-Q/libaps2,BBN-Q/libaps2
|
f9319b39b1792eaf099f720567749801acc11681
|
test.lua
|
test.lua
|
local function printf(fmt, ...)
io.stdout:write(string.format(fmt, unpack(arg)))
end
package.cpath = "./?.so"
local shelve = assert(require("shelve"))
print("Opening 'db'")
local db = assert(shelve.open("test.db"))
a = "one"
b = "two"
c = "three"
db.num = 1234567890 -- a number
db.str = "a string" -- a string
db.t1 = {} -- an empty table
db.t2 = { s="S" } -- table with one element
db.t3 = { a,b,c } -- indexed table, multiple elements
db.nested = -- nested tables
{
level = a,
nest = {
level = b,
nest = {
level = c,
nest = "nothing"
}
}
}
printf("Number encoding... ")
assert(type(db.num) == "number")
assert(db.num == 1234567890)
printf("ok\nString encoding... ")
assert(db.str == "a string")
printf("ok\nTable encoding... ")
assert(type(db.t1) == "table")
assert(type(db.t2) == "table")
assert(type(db.t3) == "table")
printf("ok\nData integrity... ")
assert(db.t2.s == "S")
assert(db.t3[1] == a)
assert(db.t3[2] == b)
assert(db.t3[3] == c)
t = db.nested
assert(type(t) == "table")
assert(t.level == a)
assert(type(t.nest) == "table")
assert(t.nest.level == b)
assert(type(t.nest.nest) == "table")
assert(t.nest.nest.level == c)
assert(type(t.nest.nest.nest) == "string")
assert(t.nest.nest.nest == "nothing")
printf("ok\nLarge file storing... ")
fd, err = io.open("LICENSE", "r")
if (not fd) then
print(err)
os.exit()
end
lgpl_license = fd:read("*a")
fd:close()
db.lic = lgpl_license
assert(db.lic == lgpl_license)
printf("ok\n... all tests successfully passed ...\n")
|
local printf
if unpack ~= nil then
printf = function(fmt, ...)
io.stdout:write(string.format(fmt, unpack(arg)))
end
else
printf = function(fmt, ...)
io.stdout:write(string.format(fmt, ...))
end
end
package.cpath = "./?.so"
local shelve = assert(require("shelve"))
print("Opening 'db'")
local db = assert(shelve.open("test.db"))
a = "one"
b = "two"
c = "three"
db.num = 1234567890 -- a number
db.str = "a string" -- a string
db.t1 = {} -- an empty table
db.t2 = { s="S" } -- table with one element
db.t3 = { a,b,c } -- indexed table, multiple elements
db.nested = -- nested tables
{
level = a,
nest = {
level = b,
nest = {
level = c,
nest = "nothing"
}
}
}
printf("Number encoding... ")
assert(type(db.num) == "number")
assert(db.num == 1234567890)
printf("ok\nString encoding... ")
assert(db.str == "a string")
printf("ok\nTable encoding... ")
assert(type(db.t1) == "table")
assert(type(db.t2) == "table")
assert(type(db.t3) == "table")
printf("ok\nData integrity... ")
assert(db.t2.s == "S")
assert(db.t3[1] == a)
assert(db.t3[2] == b)
assert(db.t3[3] == c)
t = db.nested
assert(type(t) == "table")
assert(t.level == a)
assert(type(t.nest) == "table")
assert(t.nest.level == b)
assert(type(t.nest.nest) == "table")
assert(t.nest.nest.level == c)
assert(type(t.nest.nest.nest) == "string")
assert(t.nest.nest.nest == "nothing")
printf("ok\nLarge file storing... ")
fd, err = io.open("LICENSE", "r")
if (not fd) then
print(err)
os.exit()
end
lgpl_license = fd:read("*a")
fd:close()
db.lic = lgpl_license
assert(db.lic == lgpl_license)
printf("ok\n... all tests successfully passed ...\n")
|
test.lua: Use unpack() only when available
|
test.lua: Use unpack() only when available
This fixes running the test suite with Lua 5.3
|
Lua
|
lgpl-2.1
|
aperezdc/lua-shelve
|
6b2815a84f2d2e5beee25baf5ec2436002e43acf
|
after/plugin/mappings.lua
|
after/plugin/mappings.lua
|
if not vim.keymap then
vim.keymap = require('nvim').keymap
end
-- local noremap = { noremap = true }
local noremap_silent = { noremap = true, silent = true }
if not packer_plugins or (packer_plugins and not packer_plugins['vim-commentary']) then
vim.keymap.set('n', 'gc', '<cmd>set opfunc=neovim#comment<CR>g@', noremap_silent)
vim.keymap.set('v', 'gc', ':<C-U>call neovim#comment(visualmode(), v:true)<CR>', noremap_silent)
vim.keymap.set('n', 'gcc', function()
local cursor = vim.api.nvim_win_get_cursor(0)
require('utils.functions').toggle_comments(cursor[1] - 1, cursor[1])
vim.api.nvim_win_set_cursor(0, cursor)
end, noremap_silent)
end
if not packer_plugins or (packer_plugins and not packer_plugins['nvim-cmp']) then
-- TODO: Migrate to lua functions
vim.keymap.set('i', '<TAB>', [[<C-R>=neovim#tab()<CR>]], noremap_silent)
-- TODO: Migrate to lua functions
vim.keymap.set('i', '<S-TAB>', [[<C-R>=neovim#shifttab()<CR>]], noremap_silent)
-- TODO: Migrate to lua functions
vim.keymap.set('i', '<CR>', [[<C-R>=neovim#enter()<CR>]], noremap_silent)
end
|
if not vim.keymap then
vim.keymap = require('nvim').keymap
end
-- local noremap = { noremap = true }
local noremap_silent = { noremap = true, silent = true }
if
not packer_plugins
or (packer_plugins and not packer_plugins['vim-commentary'] and not packer_plugins['Comment.nvim'])
then
vim.keymap.set('n', 'gc', '<cmd>set opfunc=neovim#comment<CR>g@', noremap_silent)
vim.keymap.set('v', 'gc', ':<C-U>call neovim#comment(visualmode(), v:true)<CR>', noremap_silent)
vim.keymap.set('n', 'gcc', function()
local cursor = vim.api.nvim_win_get_cursor(0)
require('utils.functions').toggle_comments(cursor[1] - 1, cursor[1])
vim.api.nvim_win_set_cursor(0, cursor)
end, noremap_silent)
end
if not packer_plugins or (packer_plugins and not packer_plugins['nvim-cmp']) then
-- TODO: Migrate to lua functions
vim.keymap.set('i', '<TAB>', [[<C-R>=neovim#tab()<CR>]], noremap_silent)
-- TODO: Migrate to lua functions
vim.keymap.set('i', '<S-TAB>', [[<C-R>=neovim#shifttab()<CR>]], noremap_silent)
-- TODO: Migrate to lua functions
vim.keymap.set('i', '<CR>', [[<C-R>=neovim#enter()<CR>]], noremap_silent)
end
|
fix: fallback comment mapping
|
fix: fallback comment mapping
|
Lua
|
mit
|
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
|
b9fa77bc790d62cbfa02ff9234223ec8ee70d702
|
pwm/cfg_pwm_bindings.lua
|
pwm/cfg_pwm_bindings.lua
|
--
-- PWM bindings configuration file. Global bindings and bindings common
-- to screens and all types of frames only. See modules' configuration
-- files for other bindings.
--
-- Load Ion bindings
dopath("cfg_bindings")
-- Unbind anything using mod_query.
defbindings("WMPlex", {
kpress(MOD2.."F1", nil),
kpress(MOD1.."F1", "ioncore.exec_on(_, ':man pwm3')"),
kpress(MOD2.."F3", nil),
kpress(MOD1.."F3", nil),
kpress(MOD2.."F4", nil),
kpress(MOD2.."F5", nil),
kpress(MOD2.."F6", nil),
kpress(MOD2.."F9", nil),
kpress(MOD1.."G", nil),
})
defbindings("WFrame", {
kpress(MOD1.."A", nil),
})
|
--
-- PWM bindings configuration file. Global bindings and bindings common
-- to screens and all types of frames only. See modules' configuration
-- files for other bindings.
--
-- Load Ion bindings
dopath("cfg_bindings")
-- Unbind anything using mod_query and rebinding to mod_menu where
-- applicable.
defbindings("WScreen", {
kpress(ALTMETA.."F12", "mod_menu.menu(_, _sub, 'mainmenu', {big=true})"),
})
defbindings("WMPlex", {
kpress(ALTMETA.."F1", nil),
kpress(META.. "F1", "ioncore.exec_on(_, ':man pwm3')"),
kpress(ALTMETA.."F3", nil),
kpress(META.. "F3", nil),
kpress(ALTMETA.."F4", nil),
kpress(ALTMETA.."F5", nil),
kpress(ALTMETA.."F6", nil),
kpress(ALTMETA.."F9", nil),
kpress(META.."G", nil),
})
defbindings("WFrame", {
kpress(META.."A", nil),
kpress(META.."M", "mod_menu.menu(_, _sub, 'ctxmenu')"),
})
|
Updated/fixed PWM bindings configuration.
|
Updated/fixed PWM bindings configuration.
darcs-hash:20060120211608-4eba8-3f64a73e4f530149b58851acdc8308bdbd52751f.gz
|
Lua
|
lgpl-2.1
|
knixeur/notion,p5n/notion,p5n/notion,dkogan/notion,knixeur/notion,knixeur/notion,dkogan/notion,anoduck/notion,p5n/notion,anoduck/notion,neg-serg/notion,knixeur/notion,dkogan/notion.xfttest,p5n/notion,dkogan/notion.xfttest,anoduck/notion,dkogan/notion,neg-serg/notion,raboof/notion,raboof/notion,raboof/notion,raboof/notion,dkogan/notion.xfttest,dkogan/notion,anoduck/notion,knixeur/notion,neg-serg/notion,neg-serg/notion,dkogan/notion.xfttest,dkogan/notion,anoduck/notion,p5n/notion
|
ce0439b0848d939d65f6b010d967f68f2a36d8b0
|
agents/monitoring/default/check/disk.lua
|
agents/monitoring/default/check/disk.lua
|
--[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local BaseCheck = require('./base').BaseCheck
local CheckResult = require('./base').CheckResult
local DiskCheck = BaseCheck:extend()
function DiskCheck:initialize(params)
BaseCheck.initialize(self, 'agent.disk', params)
end
-- Dimension key is the mount point name, e.g. /, /home
function DiskCheck:run(callback)
-- Perform Check
local s = sigar:new()
local disks = s:disks()
local checkResult = CheckResult:new(self, {})
local name, usage
for i=1, #disks do
name = disks[i]:name()
usage = disks[i]:usage()
if usage then
for key, value in pairs(usage) do
checkResult:addMetric(key, name, nil, value)
end
end
end
-- Return Result
self._lastResult = checkResult
callback(checkResult)
end
local exports = {}
exports.DiskCheck = DiskCheck
return exports
|
--[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local BaseCheck = require('./base').BaseCheck
local CheckResult = require('./base').CheckResult
local DiskCheck = BaseCheck:extend()
function DiskCheck:initialize(params)
BaseCheck.initialize(self, 'agent.disk', params)
end
-- Dimension key is the mount point name, e.g. /, /home
function DiskCheck:run(callback)
-- Perform Check
local s = sigar:new()
local disks = s:disks()
local checkResult = CheckResult:new(self, {})
local name, usage
local metrics = {
'reads',
'writes',
'read_bytes',
'write_bytes',
'rtime',
'wtime',
'qtime',
'time',
'service_time',
'queue'
}
for i=1, #disks do
name = disks[i]:name()
usage = disks[i]:usage()
if usage then
for _, key in pairs(metrics) do
checkResult:addMetric(key, name, nil, usage[key])
end
end
end
-- Return Result
self._lastResult = checkResult
callback(checkResult)
end
local exports = {}
exports.DiskCheck = DiskCheck
return exports
|
fixes: remove snaptime metric
|
fixes: remove snaptime metric
|
Lua
|
apache-2.0
|
virgo-agent-toolkit/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base,cp16net/virgo-base,AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base,kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent
|
a6eee57b3d4015a96fc609d7f1e7570ed5143a76
|
test_scripts/Polices/build_options/013_ATF_P_TC_HMI_sends_GetURLs_one_app_registered_HTTP.lua
|
test_scripts/Polices/build_options/013_ATF_P_TC_HMI_sends_GetURLs_one_app_registered_HTTP.lua
|
---------------------------------------------------------------------------------------------
-- Requirements summary:
-- In case HMI sends GetURLs and at least one app is registered SDL must return only default url and url related to registered app
--
-- Description:
-- In case HMI sends GetURLs (<serviceType>) AND at least one mobile app is registered
-- SDL must: check "endpoint" section in PolicyDataBase, retrieve all urls related to requested <serviceType>,
-- return only default url and url related to registered mobile app
-- 1. Used preconditions
-- SDL is built with "DEXTENDED_POLICY: HTTP" flag
-- Application is registered.
-- PTU is requested.
-- 2. Performed steps
-- HMI->SDL: SDL.GetURLs(service=0x07)
--
-- Expected result:
-- PTU is requested. PTS is created.
-- SDL.GetURLs({urls[] = registered_App1, default})
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable')
local testCasesForPolicyTableSnapshot = require('user_modules/shared_testcases/testCasesForPolicyTableSnapshot')
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFileAndPolicyTable()
testCasesForPolicyTable.Delete_Policy_table_snapshot()
testCasesForPolicyTable:Precondition_updatePolicy_By_overwriting_preloaded_pt("files/jsons/Policies/Policy_Table_Update/few_endpoints_appId.json")
--TODO: Should be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed
config.defaultProtocolVersion = 2
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
require('user_modules/AppTypes')
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_PTU_GetURLs()
local endpoints = {}
--TODO(istoimenova): Should be removed when "[GENIVI] HTTP: sdl_snapshot.json is not saved to file system" is fixed.
if ( commonSteps:file_exists( '/tmp/fs/mp/images/ivsu_cache/sdl_snapshot.json') ) then
testCasesForPolicyTableSnapshot:extract_pts(
{config.application1.registerAppInterfaceParams.appID},
{self.applications[config.application1.registerAppInterfaceParams.appName]})
for i = 1, #testCasesForPolicyTableSnapshot.pts_endpoints do
if (testCasesForPolicyTableSnapshot.pts_endpoints[i].service == "0x07") then
endpoints[#endpoints + 1] = {
url = testCasesForPolicyTableSnapshot.pts_endpoints[i].value,
appID = testCasesForPolicyTableSnapshot.pts_endpoints[i].appID}
end
end
else
endpoints = {
{url = "http://policies.telematics.ford.com/api/policies1", appID = nil},
{url = "http://policies.telematics.ford.com/api/policies2", appID = nil},
{url = "http://policies.telematics.ford.com/api/policies3", appID = nil},
{url = "http://policies.telematics.ford.com/api/test_apllication", appID = self.applications[config.application1.registerAppInterfaceParams.appName]}
}
end
local RequestId = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 })
EXPECT_HMIRESPONSE(RequestId,{result = {code = 0, method = "SDL.GetURLS"} } )
:ValidIf(function(_,data)
local is_correct = {}
for i = 1, #data.result.urls do
for j = 1, #endpoints do
if ( data.result.urls[i] == endpoints[j] ) then
is_correct[i] = true
end
end
end
if(#data.result.urls ~= #endpoints ) then
self:FailTestCase("Number of urls is not as expected: "..#endpoints..". Real: "..#data.result.urls)
end
for i = 1, #is_correct do
if(is_correct[i] == false) then
self:FailTestCase("url: "..data.result.urls[i].url.." is not correct")
end
end
end)
end
--[[ Postcondition ]]
commonFunctions:newTestCasesGroup("Postconditions")
testCasesForPolicyTable:Restore_preloaded_pt()
function Test.Postcondition_Stop_SDL()
StopSDL()
end
return Test
|
---------------------------------------------------------------------------------------------
-- Requirements summary:
-- In case HMI sends GetURLs and at least one app is registered SDL must return only default url and url related to registered app
--
-- Description:
-- In case HMI sends GetURLs (<serviceType>) AND at least one mobile app is registered
-- SDL must: check "endpoint" section in PolicyDataBase, retrieve all urls related to requested <serviceType>,
-- return only default url and url related to registered mobile app
-- 1. Used preconditions
-- SDL is built with "DEXTENDED_POLICY: HTTP" flag
-- Application is registered.
-- PTU is requested.
-- 2. Performed steps
-- HMI->SDL: SDL.GetURLs(service=0x07)
--
-- Expected result:
-- PTU is requested. PTS is created.
-- SDL.GetURLs({urls[] = registered_App1, default})
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable')
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFileAndPolicyTable()
testCasesForPolicyTable.Delete_Policy_table_snapshot()
testCasesForPolicyTable:Precondition_updatePolicy_By_overwriting_preloaded_pt("files/jsons/Policies/Policy_Table_Update/few_endpoints_appId.json")
--TODO: Should be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed
config.defaultProtocolVersion = 2
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
require('user_modules/AppTypes')
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_PTU_GetURLs()
local endpoints = {
{ url = "http://policies.telematics.ford.com/api/policies1" },
{ url = "http://policies.telematics.ford.com/api/policies2" },
{ url = "http://policies.telematics.ford.com/api/policies3" },
{ url = "http://policies.telematics.ford.com/api/test_apllication" }
}
local RequestId = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 })
EXPECT_HMIRESPONSE(RequestId, { result = { code = 0, method = "SDL.GetURLS" }})
:ValidIf(function(_, data)
local is_correct = {}
for i = 1, #data.result.urls do
for j = 1, #endpoints do
if data.result.urls[i].url == endpoints[j].url then
is_correct[i] = true
end
end
end
if(#data.result.urls ~= #endpoints ) then
return false, "Number of urls is not as expected: "..#endpoints..". Real: "..#data.result.urls
end
for i = 1, #is_correct do
if(is_correct[i] == false) then
return false, "url: "..data.result.urls[i].url.." is not correct"
end
end
return true
end)
end
--[[ Postcondition ]]
commonFunctions:newTestCasesGroup("Postconditions")
testCasesForPolicyTable:Restore_preloaded_pt()
function Test.Postcondition_Stop_SDL()
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
|
0525e26809e2c6320490698c215e17188aa23d6e
|
maidroid_tool/nametag.lua
|
maidroid_tool/nametag.lua
|
------------------------------------------------------------
-- Copyright (c) 2016 tacigar. All rights reserved.
-- https://github.com/tacigar/maidroid
------------------------------------------------------------
local formspec = "size[4,1.25]"
.. default.gui_bg
.. default.gui_bg_img
.. default.gui_slots
.. "button_exit[3,0.25;1,0.875;apply_name;Apply]"
.. "field[0.5,0.5;2.75,1;name;name;]"
local maidroid_buf = {} -- for buffer of target maidroids.
minetest.register_craftitem("maidroid_tool:nametag", {
description = "maidroid tool : nametag",
inventory_image = "maidroid_tool_nametag.png",
stack_max = 1,
on_use = function(itemstack, user, pointed_thing)
if pointed_thing.type ~= "object" then
return nil
end
local obj = pointed_thing.ref
local luaentity = obj:get_luaentity()
if not obj:is_player() and luaentity then
local name = luaentity.name
if maidroid.registered_maidroids[name] then
local player_name = user:get_player_name()
minetest.show_formspec(player_name, "maidroid_tool:nametag", formspec)
maidroid_buf[player_name] = luaentity
itemstack:take_item()
return itemstack
end
end
return nil
end,
})
minetest.register_on_player_receive_fields(function(player, formname, fields)
if formname ~= "maidroid_tool:nametag" then
return
end
if fields.name then
local luaentity = maidroid_buf[player:get_player_name()]
luaentity.nametag = fields.name
luaentity.object:set_properties{
nametag = fields.name,
}
end
end)
|
------------------------------------------------------------
-- Copyright (c) 2016 tacigar. All rights reserved.
-- https://github.com/tacigar/maidroid
------------------------------------------------------------
local formspec = "size[4,1.25]"
.. default.gui_bg
.. default.gui_bg_img
.. default.gui_slots
.. "button_exit[3,0.25;1,0.875;apply_name;Apply]"
.. "field[0.5,0.5;2.75,1;name;name;%s]"
local maidroid_buf = {} -- for buffer of target maidroids.
minetest.register_craftitem("maidroid_tool:nametag", {
description = "maidroid tool : nametag",
inventory_image = "maidroid_tool_nametag.png",
stack_max = 1,
on_use = function(itemstack, user, pointed_thing)
if pointed_thing.type ~= "object" then
return nil
end
local obj = pointed_thing.ref
local luaentity = obj:get_luaentity()
if not obj:is_player() and luaentity then
local name = luaentity.name
if maidroid.is_maidroid(name) then
local player_name = user:get_player_name()
local nametag = luaentity.nametag or ""
minetest.show_formspec(player_name, "maidroid_tool:nametag", formspec:format(nametag))
maidroid_buf[player_name] = {
object = obj,
itemstack = itemstack
}
end
end
return nil
end,
})
minetest.register_on_player_receive_fields(function(player, formname, fields)
if formname ~= "maidroid_tool:nametag" then
return
end
local player_name = player:get_player_name()
if fields.name then
local luaentity = maidroid_buf[player_name].object:get_luaentity()
if luaentity then
luaentity.nametag = fields.name
luaentity.object:set_properties{
nametag = fields.name,
}
local itemstack = maidroid_buf[player_name].itemstack
itemstack:take_item()
player:set_wielded_item(itemstack)
end
end
maidroid_buf[player_name] = nil
end)
|
Fix nametag
|
Fix nametag
Set default value from existing data.
Change item decrement timing.
Use is_maidroid() method.
|
Lua
|
lgpl-2.1
|
tacigar/maidroid
|
0969aeb9c34957559ebbdcf232fb97424f650285
|
otouto/plugins/echo.lua
|
otouto/plugins/echo.lua
|
local echo = {}
echo.command = 'echo <Text>'
function echo:init(config)
echo.triggers = utilities.triggers(self.info.username, config.cmd_pat):t('echo', true).table
echo.inline_triggers = {
"^e (.+)",
"^bold (.+)"
}
echo.doc = [[*
]]..config.cmd_pat..[[echo* _<Text>_: Gibt den Text aus]]
end
function echo:inline_callback(inline_query, config, matches)
local text = matches[1]
local results = '['
-- enable custom markdown button
if text:match('%[.*%]%(.*%)') or text:match('%*.*%*') or text:match('_.*_') or text:match('`.*`') then
results = results..'{"type":"article","id":"'..math.random(100000000000000000)..'","thumb_url":"https://anditest.perseus.uberspace.de/inlineQuerys/echo/custom.jpg","title":"Eigenes Markdown","description":"'..text..'","input_message_content":{"message_text":"'..text..'","parse_mode":"Markdown"}},'
end
local results = results..'{"type":"article","id":"'..math.random(100000000000000000)..'","thumb_url":"https://anditest.perseus.uberspace.de/inlineQuerys/echo/fett.jpg","title":"Fett","description":"*'..text..'*","input_message_content":{"message_text":"*'..text..'*","parse_mode":"Markdown"}},{"type":"article","id":"'..math.random(100000000000000000)..'","thumb_url":"https://anditest.perseus.uberspace.de/inlineQuerys/echo/kursiv.jpg","title":"Kursiv","description":"_'..text..'_","input_message_content":{"message_text":"_'..text..'_","parse_mode":"Markdown"}},{"type":"article","id":"'..math.random(100000000000000000)..'","thumb_url":"https://anditest.perseus.uberspace.de/inlineQuerys/echo/fixedsys.jpg","title":"Feste Breite","description":"`'..text..'`","input_message_content":{"message_text":"`'..text..'`","parse_mode":"Markdown"}}]'
utilities.answer_inline_query(self, inline_query, results, 0)
end
function echo:action(msg)
local input = utilities.input(msg.text)
if not input then
utilities.send_message(self, msg.chat.id, echo.doc, true, msg.message_id, true)
else
local output
if msg.chat.type == 'supergroup' then
output = '*Echo:*\n"' .. utilities.md_escape(input) .. '"'
utilities.send_message(self, msg.chat.id, output, true, nil, true)
return
end
utilities.send_message(self, msg.chat.id, input, true, nil, true)
end
end
return echo
|
local echo = {}
echo.command = 'echo <Text>'
function echo:init(config)
echo.triggers = utilities.triggers(self.info.username, config.cmd_pat):t('echo', true).table
echo.inline_triggers = {
"^e (.+)",
"^bold (.+)"
}
echo.doc = [[*
]]..config.cmd_pat..[[echo* _<Text>_: Gibt den Text aus]]
end
function echo:inline_callback(inline_query, config, matches)
local text = matches[1]
local results = '['
-- enable custom markdown button
if text:match('%[.*%]%(.*%)') or text:match('%*.*%*') or text:match('_.*_') or text:match('`.*`') then
results = results..'{"type":"article","id":"'..math.random(100000000000000000)..'","thumb_url":"https://anditest.perseus.uberspace.de/inlineQuerys/echo/custom.jpg","title":"Eigenes Markdown","description":"'..text..'","input_message_content":{"message_text":"'..text..'","parse_mode":"Markdown"}},'
end
local results = results..'{"type":"article","id":"'..math.random(100000000000000000)..'","thumb_url":"https://anditest.perseus.uberspace.de/inlineQuerys/echo/fett.jpg","title":"Fett","description":"*'..text..'*","input_message_content":{"message_text":"<b>'..text..'</b>","parse_mode":"HTML"}},{"type":"article","id":"'..math.random(100000000000000000)..'","thumb_url":"https://anditest.perseus.uberspace.de/inlineQuerys/echo/kursiv.jpg","title":"Kursiv","description":"_'..text..'_","input_message_content":{"message_text":"<i>'..text..'</i>","parse_mode":"HTML"}},{"type":"article","id":"'..math.random(100000000000000000)..'","thumb_url":"https://anditest.perseus.uberspace.de/inlineQuerys/echo/fixedsys.jpg","title":"Feste Breite","description":"`'..text..'`","input_message_content":{"message_text":"<code>'..text..'</code>","parse_mode":"HTML"}}]'
utilities.answer_inline_query(self, inline_query, results, 0)
end
function echo:action(msg)
local input = utilities.input(msg.text)
if not input then
utilities.send_message(self, msg.chat.id, echo.doc, true, msg.message_id, true)
else
local output
if msg.chat.type == 'supergroup' then
output = '*Echo:*\n"' .. utilities.md_escape(input) .. '"'
utilities.send_message(self, msg.chat.id, output, true, nil, true)
return
end
utilities.send_message(self, msg.chat.id, input, true, nil, true)
end
end
return echo
|
Echo Inline: Verwende HTML, statt Markdown (teilw.), fixes #9
|
Echo Inline: Verwende HTML, statt Markdown (teilw.), fixes #9
|
Lua
|
agpl-3.0
|
Brawl345/Brawlbot-v2
|
070ef7eb69112e6aa216eee65b50639564ba963e
|
state/gamelist.lua
|
state/gamelist.lua
|
local views = {}
local view
local visible
local function hide() LOG.DEBUG("Blanking screen") visible = false end
local function show() visible = true end
local function push(node, ...)
show()
table.insert(views, new "View" (node.icon, node:path(), node, ...))
view = views[#views]
LOG.DEBUG("Push: %s", view.title)
end
local function pop()
show()
LOG.DEBUG("Pop: %s", table.remove(views).title)
view = views[#views]
end
local function peek(n)
return views[#views - (n or 0)]
end
local function prev()
show()
view:prev()
end
local function next()
show()
view:next()
end
local function contract()
show()
if #views > 1 then
LOG.DEBUG("Contract: %s -> %s", peek().title, peek(1).title)
pop()
end
end
require "mainmenu"
local in_menu = false
local function menu()
show()
if not in_menu then
LOG.DEBUG("Showing menu")
in_menu = peek()
hidden = false
push(emufun.menu)
else
LOG.DEBUG("Hiding menu")
while peek() ~= in_menu do
pop()
end
in_menu = false
end
end
-- the user has selected an entry in the list
-- the corresponding node's :run() method will return the target nodes,
-- or a number N indicating "go back N levels"
local function expand()
local next = { view:selected():run() }
LOG.DEBUG("Expand: %s -> %s", peek().title, view:selected().name)
if type(next[1]) == "number" then
for i=1,next[1] do
contract()
end
elseif #next > 0 then
push(unpack(next))
end
love.event.clear()
timer.reset("IDLE")
end
local function reload()
contract()
expand()
end
local root, library = ...
push(root)
push(unpack(library))
input.bind("up", prev)
input.bind("down", next)
input.bind("left", contract)
input.bind("right", expand)
input.bind("menu", menu)
input.bind("reload", reload)
input.bind("IDLE", hide)
input.setRepeat("up", 0.5, 0.1)
input.setRepeat("down", 0.5, 0.1)
function love.draw()
if visible then
view:draw()
end
end
|
local views = {}
local visible
local in_menu = false
local function hide() visible = false end
local function show() visible = true end
local function peek(n)
return views[#views - (n or 0)]
end
local function push(node, ...)
show()
table.insert(views, new "View" (node.icon, node:path(), node, ...))
LOG.DEBUG("Push: %s", peek().title)
end
local function pop()
show()
LOG.DEBUG("Pop: %s", table.remove(views).title)
if peek() == in_menu then
in_menu = false
end
end
local function prev()
show()
peek():prev()
end
local function next()
show()
peek():next()
end
local function contract()
show()
if #views > 1 then
LOG.DEBUG("Contract: %s -> %s", peek().title, peek(1).title)
pop()
end
end
require "mainmenu"
local function menu()
show()
if not in_menu then
LOG.DEBUG("Showing menu")
in_menu = peek()
push(emufun.menu)
else
LOG.DEBUG("Hiding menu")
while in_menu do pop() end
end
end
-- the user has selected an entry in the list
-- the corresponding node's :run() method will return the target nodes,
-- or a number N indicating "go back N levels"
local function expand()
local next = { peek():selected():run() }
LOG.DEBUG("Expand: %s -> %s", peek().title, peek():selected().name)
if type(next[1]) == "number" then
for i=1,next[1] do
contract()
end
elseif #next > 0 then
push(unpack(next))
end
love.event.clear()
timer.reset("IDLE")
end
local function reload()
contract()
expand()
end
local root, library = ...
push(root)
push(unpack(library))
input.bind("up", prev)
input.bind("down", next)
input.bind("left", contract)
input.bind("right", expand)
input.bind("menu", menu)
input.bind("reload", reload)
input.bind("IDLE", hide)
input.setRepeat("up", 0.5, 0.1)
input.setRepeat("down", 0.5, 0.1)
function love.draw()
if visible then
peek():draw()
end
end
|
Bug fix: don't crash if the user opens the menu with MENU and then closes it with BACK
|
Bug fix: don't crash if the user opens the menu with MENU and then closes it with BACK
|
Lua
|
mit
|
ToxicFrog/EmuFun
|
64d16cfdc3c59eab0bc8c67d63332cf5840f6708
|
src_trunk/resources/tag-system/c_tag_system.lua
|
src_trunk/resources/tag-system/c_tag_system.lua
|
cooldown = 0
count = 0
MAX_TAGCOUNT = 2
MAX_TAG_RADIUS = 100
function clientTagWall(weapon, ammo, ammoInClip, hitX, hitY, hitZ, hitElement)
if (weapon==41) then
local team = getPlayerTeam(getLocalPlayer())
local ftype = getElementData(team, "type")
local tag = getElementData(source, "tag")
if (ftype~=2) then
if not (hitElement) or (getElementType(hitElement)~="player") then -- Didn't attack someone
if (cooldown==0) then
if (ammoInClip>10) and (weapon==41) then
-- Check the player is near a wall
local x, y, z = getElementPosition(getLocalPlayer())
local rot = getPedRotation(getLocalPlayer())
local px = x + math.sin(math.rad(rot)) * 3
local py = y + math.cos(math.rad(rot)) * 3
local facingWall, cx, cy, cz, element = processLineOfSight(x, y, z, px, py, z, true, false, false, true, false)
if not (facingWall) then
outputChatBox("You are not near a wall.", 255, 0, 0)
count = 0
cooldown = 1
setTimer(resetCooldown, 5000, 1)
else
local colshape = createColSphere(x, y, z, MAX_TAG_RADIUS)
local tags = getElementsWithinColShape(colshape, "object")
local tagcount = 0
for key, value in ipairs(tags) do
local objtype = getElementData(value, "type")
if (tostring(objtype)=="tag") then
tagcount = tagcount + 1
end
end
if tag == 9 then tagcount = 0 end --ignore tagcount if the tag type is 9 (city maintenance)
if (tagcount<MAX_TAGCOUNT) then
count = count + 1
if (count==20) then
count = 0
cooldown = 1
setTimer(resetCooldown, 30000, 1)
local interior = getElementInterior(getLocalPlayer())
local dimension = getElementDimension(getLocalPlayer())
cx = cx - math.sin(math.rad(rot)) * 0.1
cy = cy - math.cos(math.rad(rot)) * 0.1
triggerServerEvent("createTag", getLocalPlayer(), cx, cy, cz, rot, interior, dimension)
end
else
count = 0
cooldown = 1
setTimer(resetCooldown, 30000, 1)
outputChatBox("This area has too many tags already.", source, 255, 194, 14)
end
end
end
end
end
end
end
end
addEventHandler("onClientPlayerWeaponFire", getLocalPlayer(), clientTagWall)
function resetCooldown()
cooldown = 0
end
function setTag(commandName, newTag)
if not (newTag) then
outputChatBox("SYNTAX: " .. commandName .. " [Tag # 1->8].", 255, 194, 14)
else
local newTag = tonumber(newTag)
if (newTag>0) and (newTag<9) then
setElementData(getLocalPlayer(), "tag", true, newTag)
outputChatBox("Tag changed to #" .. newTag .. ".", 0, 255, 0)
else
outputChatBox("Invalid value, please enter a value between 1 and 8.", 255, 0, 0)
end
end
end
addCommandHandler("settag", setTag)
|
cooldown = 0
count = 0
MAX_TAGCOUNT = 2
MAX_TAG_RADIUS = 100
function clientTagWall(weapon, ammo, ammoInClip, hitX, hitY, hitZ, hitElement)
if (weapon==41) then
local team = getPlayerTeam(getLocalPlayer())
local ftype = getElementData(team, "type")
local tag = getElementData(source, "tag")
if (ftype~=2) then
if not (hitElement) or (getElementType(hitElement)~="player") then -- Didn't attack someone
if (cooldown==0) then
if (ammoInClip>10) and (weapon==41) then
-- Check the player is near a wall
local oldX, oldY, oldZ = getElementPosition(getLocalPlayer())
local rot = getPedRotation(getLocalPlayer())
local matrix = getElementMatrix (getLocalPlayer())
local newX = oldX * matrix[1][1] + oldY * matrix [1][2] + oldZ * matrix [1][3] + matrix [1][4]
local newY = oldX * matrix[2][1] + oldY * matrix [2][2] + oldZ * matrix [2][3] + matrix [2][4]
local newZ = oldX * matrix[3][1] + oldY * matrix [3][2] + oldZ * matrix [3][3] + matrix [3][4]
local facingWall, cx, cy, cz, element = processLineOfSight(oldX, oldY, oldZ, newX, newY, newZ, true, false, false, true, false)
if not (facingWall) then
outputChatBox("You are not near a wall.", 255, 0, 0)
count = 0
cooldown = 1
setTimer(resetCooldown, 5000, 1)
else
local colshape = createColSphere(cx, cy, cz, MAX_TAG_RADIUS)
local tags = getElementsWithinColShape(colshape, "object")
local tagcount = 0
for key, value in ipairs(tags) do
local objtype = getElementData(value, "type")
if (tostring(objtype)=="tag") then
tagcount = tagcount + 1
end
end
if tag == 9 then tagcount = 0 end --ignore tagcount if the tag type is 9 (city maintenance)
if (tagcount<MAX_TAGCOUNT) then
count = count + 1
if (count==20) then
count = 0
cooldown = 1
setTimer(resetCooldown, 30000, 1)
local interior = getElementInterior(getLocalPlayer())
local dimension = getElementDimension(getLocalPlayer())
--cx = cx - math.sin(math.rad(rot)) * 0.1
--cy = cy - math.cos(math.rad(rot)) * 0.1
triggerServerEvent("createTag", getLocalPlayer(), cx, cy, cz, rot, interior, dimension)
end
else
count = 0
cooldown = 1
setTimer(resetCooldown, 30000, 1)
outputChatBox("This area has too many tags already.", source, 255, 194, 14)
end
end
end
end
end
end
end
end
addEventHandler("onClientPlayerWeaponFire", getLocalPlayer(), clientTagWall)
function resetCooldown()
cooldown = 0
end
function setTag(commandName, newTag)
if not (newTag) then
outputChatBox("SYNTAX: " .. commandName .. " [Tag # 1->8].", 255, 194, 14)
else
local newTag = tonumber(newTag)
if (newTag>0) and (newTag<9) then
setElementData(getLocalPlayer(), "tag", true, newTag)
outputChatBox("Tag changed to #" .. newTag .. ".", 0, 255, 0)
else
outputChatBox("Invalid value, please enter a value between 1 and 8.", 255, 0, 0)
end
end
end
addCommandHandler("settag", setTag)
|
fixed 251 & 76
|
fixed 251 & 76
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@78 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
40e7bd188951a0244ba5b0c9ea7d91a71a4f9d09
|
src/tie/src/Shared/Definition/TiePropertyDefinition.lua
|
src/tie/src/Shared/Definition/TiePropertyDefinition.lua
|
--[=[
@class TiePropertyDefinition
]=]
local require = require(script.Parent.loader).load(script)
local BaseObject = require("BaseObject")
local TiePropertyImplementation = require("TiePropertyImplementation")
local TiePropertyInterface = require("TiePropertyInterface")
local TiePropertyDefinition = setmetatable({}, BaseObject)
TiePropertyDefinition.ClassName = "TiePropertyDefinition"
TiePropertyDefinition.__index = TiePropertyDefinition
function TiePropertyDefinition.new(tieDefinition, propertyName: string, defaultValue: any)
local self = setmetatable(BaseObject.new(), TiePropertyDefinition)
self._tieDefinition = assert(tieDefinition, "No tieDefinition")
self._propertyName = assert(propertyName, "No propertyName")
self._defaultValue = defaultValue
return self
end
function TiePropertyDefinition:GetTieDefinition()
return self._tieDefinition
end
function TiePropertyDefinition:IsAttribute()
return self._isAttribute
end
function TiePropertyDefinition:GetDefaultValue()
return self._defaultValue
end
function TiePropertyDefinition:Implement(folder: Folder, initialValue)
assert(typeof(folder) == "Instance", "Bad folder")
return TiePropertyImplementation.new(self, folder, initialValue)
end
function TiePropertyDefinition:GetInterface(folder: Folder)
assert(typeof(folder) == "Instance", "Bad folder")
return TiePropertyInterface.new(folder, nil, self)
end
function TiePropertyDefinition:GetMemberName(): string
return self._propertyName
end
return TiePropertyDefinition
|
--[=[
@class TiePropertyDefinition
]=]
local require = require(script.Parent.loader).load(script)
local BaseObject = require("BaseObject")
local TiePropertyImplementation = require("TiePropertyImplementation")
local TiePropertyInterface = require("TiePropertyInterface")
local TiePropertyDefinition = setmetatable({}, BaseObject)
TiePropertyDefinition.ClassName = "TiePropertyDefinition"
TiePropertyDefinition.__index = TiePropertyDefinition
function TiePropertyDefinition.new(tieDefinition, propertyName: string, defaultValue: any)
local self = setmetatable(BaseObject.new(), TiePropertyDefinition)
self._tieDefinition = assert(tieDefinition, "No tieDefinition")
self._propertyName = assert(propertyName, "No propertyName")
self._defaultValue = defaultValue
return self
end
function TiePropertyDefinition:GetTieDefinition()
return self._tieDefinition
end
function TiePropertyDefinition:GetDefaultValue()
return self._defaultValue
end
function TiePropertyDefinition:Implement(folder: Folder, initialValue)
assert(typeof(folder) == "Instance", "Bad folder")
return TiePropertyImplementation.new(self, folder, initialValue)
end
function TiePropertyDefinition:GetInterface(folder: Folder)
assert(typeof(folder) == "Instance", "Bad folder")
return TiePropertyInterface.new(folder, nil, self)
end
function TiePropertyDefinition:GetMemberName(): string
return self._propertyName
end
return TiePropertyDefinition
|
fix: Remove unused/wrong TiePropertyDefinition:IsAttribute() API method
|
fix: Remove unused/wrong TiePropertyDefinition:IsAttribute() API method
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
9632310387598cac928f4bb69e34cdc6388ce211
|
lib/lua/utils.lua
|
lib/lua/utils.lua
|
--------------------
-- Module with utility functions
--
-- @module utils
--
-- Submodules:
--
-- * `file`: Operations on files
-- * `math`: Contains a few math functions
-- * `string`: Operations on strings
-- * `table`: Operations on tables
util = {}
-- IO Functions
util.file = {}
-- Opens the file at path with the given mode and format
-- @param path File to be opened
-- @param mode Optional mode to open file with
-- @param format Optional format to read file with
-- @return The content of the file
function util.file.read_all(path, mode, format)
assert(path ~= nil, "File path was nil")
if mode == nil then
mod = "*all"
end
local file = io.open(path)
if file == nil then
error("Unable to open " .. path .. "!", 2)
end
local data = file:read(format)
file:close()
return data
end
-- Math functions
util.math = {}
-- Converts a number in a range to a percentage
-- @param min The minimum value in the range
-- @param max The maximum value in the range
-- @param value The value in the range to convert
-- @return A percentage from 0 to 100 for the value
function util.math.range_to_percent(min, max, value)
assert(type(min) == 'number', "min: expected number")
assert(type(max) == 'number', "max: expected number")
assert(type(value) == 'number', "value: expected number")
assert(min < max, "min value was not less than max!")
value = math.min(max, value)
value = math.max(min, value)
return math.ceil( (value - min) / (max - min) * 100 )
end
-- String functions
util.string = {}
-- Counts the number of lines in a string.
-- @param text String to count lines of
-- @return The number of lines in the string.
function util.string.line_count(text)
assert(type(text) == 'string', "Non-string given to string.line_count!")
local count = 0
for result in text:gmatch("\n") do
count = count + 1
end
return count
end
-- Escapes backslashes and quotes in a string.
--
-- Replaces " with \", ' with \', and \ with \\.
-- @param text String to escape
-- @return String escaped with quotes.
function util.string.escape_quotes(text)
assert(type(text) == 'string', "string.escape: Expected a string")
text = text:gsub('\\', '\\\\')
text = text:gsub('"', '\\"')
text = text:gsub("'", "\\'")
return text
end
-- Escapes strings for HTML encoding.
--
-- Replaces <, >, &, ", and ' with their HTML &name; equivalents.
-- @param test The text to escape
-- @return HTML escaped text.
function util.string.escape_html(text)
assert(type(text) == 'string', "string.html_escape: Expected a string")
builder = ""
for i = 1, text:len() do
if char == '<' then
builder = builder + '<'
elseif char == '>' then
builder = builder + '>'
elseif char == '&' then
builder = builder + '&'
elseif char == '"' then
builder = builder + '"'
elseif char == "'" then
builder = builder + '''
else
builder = builder + text[i]
end
end
return builder
end
-- Table functions
util.table = {}
-- Gets a random element from a numerically-indexed list.
--
-- # Errors
-- Function will error if the table is nil or empty,
-- or if the indicies are not numbers.
--
-- @param tab The list to pick from
-- @return A random element from the list
function util.table.get_random(tab)
assert(type(tab) == 'table', "Non table given to table.get_random!")
local len = #tab
if len == 0 then
error("Empty table given to table.get_random!", 2)
elseif len == 1 then
return tab[1]
else
return tab[math.random(1, len)]
end
end
-- List of programs that should be spawned each start/restart.
util.program = {}
util.program.programs = {}
-- Spawns a program once. Does not update the global program spawn list.
-- @param bin The program to run. Can be an absolute path or a command to run.
-- @param args The arguments (as a string) to pass to the program.
function util.program.spawn_once(bin, args)
assert(type(bin) == 'string', 'Non string given for program')
if type(args) ~= 'string' then
args = ""
end
os.execute(bin .. " " .. args .. " &")
end
-- Registers the program to spawn at startup and every time it restarts
-- @param bin The program to run. Can be an absolute path or a command to run.
-- @param args The arguments (as a string) to pass to the program.
function util.program.spawn_at_startup(bin, args)
assert(type(bin) == 'string', 'Non string given for program')
table.insert(util.program.programs, {
bin = bin,
args = args
})
end
-- Spawns the startup programs
function util.program.spawn_startup_programs()
for index, program in ipairs(util.program.programs) do
os.execute(program.bin .. " " .. program.args .. " &")
end
end
-- Stops the startup programs. Does not remove them from the global list.
function util.program.terminate_startup_programs()
for index, program in ipairs(util.program.programs) do
-- TODO Kill in a more fine-grained matter...
-- parent joining on child process? PIDs won't work, they can be reclaimed.
os.execute("pkill " .. program.bin)
end
end
-- Stops the startup programs and then immediately starts them again.
-- Useful for the "restart" command
function util.program.restart_startup_programs()
util.program.terminate_startup_programs()
util.program.spawn_startup_programs()
end
|
--------------------
--- Module with utility functions
--
--- @module utils
--
--- Submodules:
--
--- * `file`: Operations on files
--- * `math`: Contains a few math functions
--- * `string`: Operations on strings
--- * `table`: Operations on tables
util = {}
--- IO Functions
util.file = {}
--- Opens the file at path with the given mode and format
--- @param path File to be opened
--- @param mode Optional mode to open file with
--- @param format Optional format to read file with
--- @return The content of the file
function util.file.read_all(path, mode, format)
assert(path ~= nil, "File path was nil")
if mode == nil then
mod = "*all"
end
local file = io.open(path)
if file == nil then
error("Unable to open " .. path .. "!", 2)
end
local data = file:read(format)
file:close()
return data
end
--- Math functions
util.math = {}
--- Converts a number in a range to a percentage
--- @param min The minimum value in the range
--- @param max The maximum value in the range
--- @param value The value in the range to convert
--- @return A percentage from 0 to 100 for the value
function util.math.range_to_percent(min, max, value)
assert(type(min) == 'number', "min: expected number")
assert(type(max) == 'number', "max: expected number")
assert(type(value) == 'number', "value: expected number")
assert(min < max, "min value was not less than max!")
value = math.min(max, value)
value = math.max(min, value)
return math.ceil( (value - min) / (max - min) * 100 )
end
--- String functions
util.string = {}
--- Counts the number of lines in a string.
--- @param text String to count lines of
--- @return The number of lines in the string.
function util.string.line_count(text)
assert(type(text) == 'string', "Non-string given to string.line_count!")
local count = 0
for result in text:gmatch("\n") do
count = count + 1
end
return count
end
--- Escapes backslashes and quotes in a string.
--
--- Replaces " with \", ' with \', and \ with \\.
--- @param text String to escape
--- @return String escaped with quotes.
function util.string.escape_quotes(text)
assert(type(text) == 'string', "string.escape: Expected a string")
text = text:gsub('\\', '\\\\')
text = text:gsub('"', '\\"')
text = text:gsub("'", "\\'")
return text
end
--- Escapes strings for HTML encoding.
--
--- Replaces <, >, &, ", and ' with their HTML &name; equivalents.
--- @param test The text to escape
--- @return HTML escaped text.
function util.string.escape_html(text)
assert(type(text) == 'string', "string.html_escape: Expected a string")
builder = ""
for i = 1, text:len() do
if char == '<' then
builder = builder + '<'
elseif char == '>' then
builder = builder + '>'
elseif char == '&' then
builder = builder + '&'
elseif char == '"' then
builder = builder + '"'
elseif char == "'" then
builder = builder + '''
else
builder = builder + text[i]
end
end
return builder
end
--- Table functions
util.table = {}
--- Gets a random element from a numerically-indexed list.
--
--- # Errors
--- Function will error if the table is nil or empty,
--- or if the indicies are not numbers.
--
--- @param tab The list to pick from
--- @return A random element from the list
function util.table.get_random(tab)
assert(type(tab) == 'table', "Non table given to table.get_random!")
local len = #tab
if len == 0 then
error("Empty table given to table.get_random!", 2)
elseif len == 1 then
return tab[1]
else
return tab[math.random(1, len)]
end
end
--- List of programs that should be spawned each start/restart.
util.program = {}
util.program.programs = {}
--- Returns a function that spawns a program once.
--- Does not update the global program spawn list.
--- Used primarily for key mapping.
--- @param bin The program to run. Can be an absolute path or a command to run.
--- @param args The arguments (as a string) to pass to the program.
function util.program.spawn_once(bin, args)
assert(type(bin) == 'string', 'Non string given for program')
if type(args) ~= 'string' then
args = ""
end
os.execute(bin .. " " .. args .. " &")
end
--- Registers the program to spawn at startup and every time it restarts
--- @param bin The program to run. Can be an absolute path or a command to run.
--- @param args The arguments (as a string) to pass to the program.
function util.program.spawn_at_startup(bin, args)
assert(type(bin) == 'string', 'Non string given for program')
table.insert(util.program.programs, {
bin = bin,
args = args
})
end
--- Spawns the startup programs
function util.program.spawn_startup_programs()
for index, program in ipairs(util.program.programs) do
os.execute(program.bin .. " " .. program.args .. " &")
end
end
--- Stops the startup programs. Does not remove them from the global list.
function util.program.terminate_startup_programs()
for index, program in ipairs(util.program.programs) do
-- TODO Kill in a more fine-grained matter...
-- parent joining on child process? PIDs won't work, they can be reclaimed.
os.execute("pkill " .. program.bin)
end
end
--- Stops the startup programs and then immediately starts them again.
--- Useful for the "restart" command
function util.program.restart_startup_programs()
util.program.terminate_startup_programs()
util.program.spawn_startup_programs()
end
|
Fixed comment formatting
|
Fixed comment formatting
|
Lua
|
mit
|
Immington-Industries/way-cooler,Immington-Industries/way-cooler,Immington-Industries/way-cooler,way-cooler/way-cooler,way-cooler/way-cooler,way-cooler/way-cooler
|
2b46c3a056abc576b5ff0e6846831cd7fe9aa1a8
|
rootfs/etc/nginx/lua/test/monitor_test.lua
|
rootfs/etc/nginx/lua/test/monitor_test.lua
|
_G._TEST = true
local original_ngx = ngx
local function reset_ngx()
_G.ngx = original_ngx
end
local function mock_ngx(mock)
local _ngx = mock
setmetatable(_ngx, { __index = ngx })
_G.ngx = _ngx
end
local function mock_ngx_socket_tcp()
local tcp_mock = {}
stub(tcp_mock, "connect", true)
stub(tcp_mock, "send", true)
stub(tcp_mock, "close", true)
local socket_mock = {}
stub(socket_mock, "tcp", tcp_mock)
mock_ngx({ socket = socket_mock })
return tcp_mock
end
describe("Monitor", function()
after_each(function()
reset_ngx()
package.loaded["monitor"] = nil
end)
it("batches metrics", function()
local monitor = require("monitor")
mock_ngx({ var = {} })
for i = 1,10,1 do
monitor.call()
end
assert.equal(10, #monitor.get_metrics_batch())
end)
describe("flush", function()
it("short circuits when premmature is true (when worker is shutting down)", function()
local tcp_mock = mock_ngx_socket_tcp()
local monitor = require("monitor")
mock_ngx({ var = {} })
for i = 1,10,1 do
monitor.call()
end
monitor.flush(true)
assert.stub(tcp_mock.connect).was_not_called()
end)
it("short circuits when there's no metrics batched", function()
local tcp_mock = mock_ngx_socket_tcp()
local monitor = require("monitor")
monitor.flush()
assert.stub(tcp_mock.connect).was_not_called()
end)
it("JSON encodes and sends the batched metrics", function()
local tcp_mock = mock_ngx_socket_tcp()
local monitor = require("monitor")
local ngx_var_mock = {
host = "example.com",
namespace = "default",
ingress_name = "example",
service_name = "http-svc",
location_path = "/",
request_method = "GET",
status = "200",
request_length = "256",
request_time = "0.04",
bytes_sent = "512",
upstream_addr = "10.10.0.1",
upstream_connect_time = "0.01",
upstream_response_time = "0.02",
upstream_response_length = "456",
upstream_status = "200",
}
mock_ngx({ var = ngx_var_mock })
monitor.call()
local ngx_var_mock1 = ngx_var_mock
ngx_var_mock1.status = "201"
ngx_var_mock1.request_method = "POST"
mock_ngx({ var = ngx_var_mock })
monitor.call()
monitor.flush()
local expected_payload = '[{"requestLength":256,"ingress":"example","status":"200","service":"http-svc","requestTime":0.04,"namespace":"default","host":"example.com","method":"GET","upstreamResponseTime":0.02,"upstreamResponseLength":456,"upstreamLatency":0.01,"path":"\\/","responseLength":512},{"requestLength":256,"ingress":"example","status":"201","service":"http-svc","requestTime":0.04,"namespace":"default","host":"example.com","method":"POST","upstreamResponseTime":0.02,"upstreamResponseLength":456,"upstreamLatency":0.01,"path":"\\/","responseLength":512}]'
assert.stub(tcp_mock.connect).was_called_with(tcp_mock, "unix:/tmp/prometheus-nginx.socket")
assert.stub(tcp_mock.send).was_called_with(tcp_mock, expected_payload)
assert.stub(tcp_mock.close).was_called_with(tcp_mock)
end)
end)
end)
|
_G._TEST = true
local original_ngx = ngx
local function reset_ngx()
_G.ngx = original_ngx
end
local function mock_ngx(mock)
local _ngx = mock
setmetatable(_ngx, { __index = ngx })
_G.ngx = _ngx
end
local function mock_ngx_socket_tcp()
local tcp_mock = {}
stub(tcp_mock, "connect", true)
stub(tcp_mock, "send", true)
stub(tcp_mock, "close", true)
local socket_mock = {}
stub(socket_mock, "tcp", tcp_mock)
mock_ngx({ socket = socket_mock })
return tcp_mock
end
describe("Monitor", function()
after_each(function()
reset_ngx()
package.loaded["monitor"] = nil
end)
it("batches metrics", function()
local monitor = require("monitor")
mock_ngx({ var = {} })
for i = 1,10,1 do
monitor.call()
end
assert.equal(10, #monitor.get_metrics_batch())
end)
describe("flush", function()
it("short circuits when premmature is true (when worker is shutting down)", function()
local tcp_mock = mock_ngx_socket_tcp()
local monitor = require("monitor")
mock_ngx({ var = {} })
for i = 1,10,1 do
monitor.call()
end
monitor.flush(true)
assert.stub(tcp_mock.connect).was_not_called()
end)
it("short circuits when there's no metrics batched", function()
local tcp_mock = mock_ngx_socket_tcp()
local monitor = require("monitor")
monitor.flush()
assert.stub(tcp_mock.connect).was_not_called()
end)
it("JSON encodes and sends the batched metrics", function()
local tcp_mock = mock_ngx_socket_tcp()
local monitor = require("monitor")
local ngx_var_mock = {
host = "example.com",
namespace = "default",
ingress_name = "example",
service_name = "http-svc",
location_path = "/",
request_method = "GET",
status = "200",
request_length = "256",
request_time = "0.04",
bytes_sent = "512",
upstream_addr = "10.10.0.1",
upstream_connect_time = "0.01",
upstream_response_time = "0.02",
upstream_response_length = "456",
upstream_status = "200",
}
mock_ngx({ var = ngx_var_mock })
monitor.call()
local ngx_var_mock1 = ngx_var_mock
ngx_var_mock1.status = "201"
ngx_var_mock1.request_method = "POST"
mock_ngx({ var = ngx_var_mock })
monitor.call()
monitor.flush()
local expected_payload = '[{"host":"example.com","method":"GET","requestLength":256,"status":"200","upstreamResponseLength":456,"upstreamLatency":0.01,"upstreamResponseTime":0.02,"path":"\\/","requestTime":0.04,"ingress":"example","namespace":"default","service":"http-svc","responseLength":512},{"host":"example.com","method":"POST","requestLength":256,"status":"201","upstreamResponseLength":456,"upstreamLatency":0.01,"upstreamResponseTime":0.02,"path":"\\/","requestTime":0.04,"ingress":"example","namespace":"default","service":"http-svc","responseLength":512}]'
assert.stub(tcp_mock.connect).was_called_with(tcp_mock, "unix:/tmp/prometheus-nginx.socket")
assert.stub(tcp_mock.send).was_called_with(tcp_mock, expected_payload)
assert.stub(tcp_mock.close).was_called_with(tcp_mock)
end)
end)
end)
|
fix monitor test after move to openresty
|
fix monitor test after move to openresty
|
Lua
|
apache-2.0
|
caicloud/ingress,aledbf/ingress-nginx,kubernetes/ingress-nginx,kubernetes/ingress-nginx,caicloud/ingress,canhnt/ingress,kubernetes/ingress-nginx,aledbf/ingress-nginx,canhnt/ingress,aledbf/ingress-nginx,canhnt/ingress,caicloud/ingress,aledbf/ingress-nginx,kubernetes/ingress-nginx,caicloud/ingress,kubernetes/ingress-nginx,canhnt/ingress
|
1faa50c9538291ed23adcc8b7f7d568321955584
|
middleware/burningman-demultiply/burningman_demultiply.lua
|
middleware/burningman-demultiply/burningman_demultiply.lua
|
return function(request, next_middleware)
local response = next_middleware()
local events = json.decode(response.body)
local newresponse ={}
for i=1,#events do
local e ={}
local currentEvent = events[i];
e.title = currentEvent.title
e.desc = currentEvent.description
e.id = currentEvent.id
e.host = currentEvent.hosted_by_camp
e.url =currentEvent.url
e.location = currentEvent.other_location
e.category = currentEvent.event_type.abbr
for j=1,#currentEvent.occurrence_set do
e.start_time = currentEvent.occurrence_set[j].start_time
e.end_time = currentEvent.occurrence_set[j].end_time
table.insert(newresponse,e)
end
end
response.body = json.encode(newresponse)
return next_middleware()
end
|
return function(request, next_middleware)
local response = next_middleware()
local events = json.decode(response.body)
local newresponse ={}
for i=1,#events do
local currentEvent = events[i];
for j=1,#currentEvent.occurrence_set do
table.insert(newresponse,{
title = currentEvent.title,
desc = currentEvent.description,
id = currentEvent.id,
host = currentEvent.hosted_by_camp,
url = currentEvent.url,
location = currentEvent.other_location,
category = currentEvent.event_type.abbr,
start_time = currentEvent.occurrence_set[j].start_time,
end_time = currentEvent.occurrence_set[j].end_time
})
end
end
response.body = json.encode(newresponse)
return response
end
|
fix burningman-demultiply
|
fix burningman-demultiply
|
Lua
|
mit
|
APItools/middleware
|
454f4676389738808d2231d6813e5eb70167efbe
|
test/lua/unit/html.lua
|
test/lua/unit/html.lua
|
context("HTML processing", function()
local rspamd_util = require("rspamd_util")
local logger = require("rspamd_logger")
test("Extract text from HTML", function()
local cases = {
{[[
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<!-- page content -->
Hello, world! <b>test</b>
<p>data<>
</P>
<b>stuff</p>?
</body>
</html>
]], "Hello, world! test\r\ndata\r\nstuff?"},
{[[
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>
Wikibooks
</title>
</head>
<body>
<p>
Hello, world!
</p>
</body>
</html>]], '\r\nHello, world!\r\n'},
{[[
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<style><!--
- -a -a -a -- --- -
--></head>
<body>
<!-- page content -->
Hello, world!
</body>
</html>
]], 'Hello, world!'},
}
for _,c in ipairs(cases) do
local t = rspamd_util.parse_html(c[1])
assert_not_nil(t)
assert_equal(c[2], tostring(t))
end
end)
end)
|
context("HTML processing", function()
local rspamd_util = require("rspamd_util")
local logger = require("rspamd_logger")
test("Extract text from HTML", function()
local cases = {
{[[
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<!-- page content -->
Hello, world! <b>test</b>
<p>data<>
</P>
<b>stuff</p>?
</body>
</html>
]], "Hello, world! test data\r\nstuff?"},
{[[
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>
Wikibooks
</title>
</head>
<body>
<p>
Hello, world!
</p>
</body>
</html>]], 'Hello, world!\r\n'},
{[[
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<style><!--
- -a -a -a -- --- -
--></head>
<body>
<!-- page content -->
Hello, world!
</body>
</html>
]], 'Hello, world!'},
}
for _,c in ipairs(cases) do
local t = rspamd_util.parse_html(c[1])
assert_not_nil(t)
assert_equal(c[2], tostring(t))
end
end)
end)
|
Fix HTML tests
|
Fix HTML tests
|
Lua
|
apache-2.0
|
minaevmike/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,minaevmike/rspamd,AlexeySa/rspamd,minaevmike/rspamd,andrejzverev/rspamd,minaevmike/rspamd,andrejzverev/rspamd,minaevmike/rspamd,minaevmike/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,minaevmike/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,minaevmike/rspamd,minaevmike/rspamd
|
46c3ddfc60224a5c840bfe917e5cb9c8c2b51b02
|
dotfiles/nvim/init.lua
|
dotfiles/nvim/init.lua
|
-- functions that are not behavior added to the editor
local u = require('utils')
-- shotcuts to common functions
local api = vim.api -- nvim api access
local cmd = vim.cmd -- to execute Vim commands e.g. cmd('pwd')
local fn = vim.fn -- to call Vim functions e.g. fn.bufnr()
local g = vim.g -- a table to access global variables
-- colors
cmd 'colorscheme torte'
-- plugin management
cmd 'packadd paq-nvim' -- load the package manager
local paq = require('paq-nvim').paq -- a convenient alias
paq {'savq/paq-nvim', opt = true} -- paq-nvim manages itself
paq 'tpope/vim-surround' -- handle surroundings ()[]"'{} as text objects
paq 'wellle/targets.vim' -- lots of text objects (https://mvaltas.com/targets)
paq 'davidoc/taskpaper.vim' -- support for TaskPaper format
paq 'ludovicchabant/vim-gutentags' -- support for ctags
paq 'nvim-telescope/telescope.nvim' -- File finder w/ popup window and preview support
paq 'nvim-lua/popup.nvim' -- provides popup window functionality
paq 'nvim-lua/plenary.nvim' -- collection of Lua functions used by plugins
paq 'nvim-treesitter/nvim-treesitter'-- Configuration and abstraction layer
-- general editor options
local indent = 2
u.opt('b', 'expandtab', true) -- Use spaces instead of tabs
u.opt('b', 'shiftwidth', indent) -- Size of an indent
u.opt('b', 'smartindent', true) -- Insert indents automatically
u.opt('b', 'tabstop', indent) -- Number of spaces tabs count for
u.opt('o', 'hidden', true) -- Enable modified buffers in background
u.opt('o', 'joinspaces', false) -- No double spaces with join after a dot
u.opt('o', 'scrolloff', 4 ) -- Lines of context
u.opt('o', 'shiftround', true) -- Round indent
u.opt('o', 'sidescrolloff', 8 ) -- Columns of context
u.opt('o', 'smartcase', true) -- Don't ignore case with capitals
u.opt('o', 'splitbelow', true) -- Put new windows below current
u.opt('o', 'splitright', true) -- Put new windows right of current
u.opt('o', 'termguicolors', true) -- True color support
u.opt('o', 'wildmode', 'list:longest') -- Command-line completion mode
u.opt('w', 'wrap', false)
-- end of general editor options
-- line numbers
u.opt('w', 'number', true) -- Print line number
u.opt('w', 'relativenumber', true) -- Relative line numbers
-- end line numbers
-- simple maps (no binding with function)
u.map('n', '<leader><leader>', '<c-^>') -- '\\' alternate between buffers
u.map('', '<C-z>', ':wa|:suspend<cr>') -- save files when suspending with CTRL-Z
u.map('', 'Q', '<nop>') -- disable Ex Mode
u.map('n','<esc>',':nohlsearch<cr>') -- disable search highlight on ESC
-- telescope config
u.map('n','<leader>f',':Telescope find_files<cr>') -- f find files
u.map('n','<leader>b',':Telescope buffers<cr>') -- b for buffers
u.map('n','<leader>g',':Telescope git_files<cr>') -- g for git
u.map('n','<leader>d',':Telescope treesitter<cr>') -- d for definitions
u.map('n','<leader>l',':Telescope live_grep<cr>') -- l for live_grep
u.map('n','<leader>a',':Telescope<cr>') -- a for all
-- telescope configuration
local actions = require('telescope.actions')
require('telescope').setup{
defaults = {
path_display = {
'shorten',
'absolute',
},
mappings = {
i = {
["<esc>"] = actions.close -- exit on ESC and not enter on normal mode
},
},
}
}
-- treesitter configuration
require('nvim-treesitter.configs').setup {
ensure_installed = "maintained", -- one of "all", "maintained" (parsers with maintainers)
highlight = {
enable = true,
},
incremental_selection = {
enable = true,
keymaps = {
init_selection = "gnn",
node_incremental = "grn",
scope_incremental = "grc",
node_decremental = "grm",
},
},
}
-- end treesitter configuration
-- smart_tab: triggers CTRL-P completion when the
-- character before the cursor is not empty otherwise
-- just return TAB
function smart_tab()
local cur_col = fn.col(".")
local cur_char = api.nvim_get_current_line():sub(cur_col - 2, cur_col - 1)
-- %g matches printable character in Lua
return cur_char:match('%g') and u.t'<c-p>' or u.t'<tab>'
end
-- bind <tab> to smar_tab() function
api.nvim_set_keymap('i', '<tab>', 'v:lua.smart_tab()', {expr = true, noremap = true })
-- end of smart_tab
-- shortcut to reload init.lua
cmd 'command! -nargs=0 Init :luafile ~/.config/nvim/init.lua'
cmd 'command! -nargs=0 EInit :e ~/.config/nvim/init.lua'
-- Old implementation of QuickCSE
api.nvim_exec([[
" CSE means Clear Screen and Execute, use it by
" mapping (depending of the project) to a test runner command
" map <leader>r CSE('rspec', '--color')<cr>
function! CSE(runthis, ...)
:wa
exec ':!' . a:runthis . ' ' . join(a:000, ' ')
endfunction
function! QuickCSE(cmd)
exec "map <leader>r :call CSE(\"" . a:cmd . "\")<cr>"
endfunction
]], true)
cmd 'command! -nargs=* QuickCSE call QuickCSE(<q-args>)'
-- end of QuickCSE
-- changes in colors
api.nvim_exec([[
highlight LineNr guifg=Grey
highlight TelescopeMatching guifg=Red
]], true)
-- end changes in colors
|
-- functions that are not behavior added to the editor
local u = require('utils')
-- shotcuts to common functions
local api = vim.api -- nvim api access
local cmd = vim.cmd -- to execute Vim commands e.g. cmd('pwd')
local fn = vim.fn -- to call Vim functions e.g. fn.bufnr()
local g = vim.g -- a table to access global variables
-- colors
cmd 'colorscheme torte'
-- plugin management
cmd 'packadd paq-nvim' -- load the package manager
local paq = require('paq-nvim').paq -- a convenient alias
paq {'savq/paq-nvim', opt = true} -- paq-nvim manages itself
paq 'tpope/vim-surround' -- handle surroundings ()[]"'{} as text objects
paq 'wellle/targets.vim' -- lots of text objects (https://mvaltas.com/targets)
paq 'davidoc/taskpaper.vim' -- support for TaskPaper format
paq 'ludovicchabant/vim-gutentags' -- support for ctags
paq 'nvim-telescope/telescope.nvim' -- File finder w/ popup window and preview support
paq 'nvim-lua/popup.nvim' -- provides popup window functionality
paq 'nvim-lua/plenary.nvim' -- collection of Lua functions used by plugins
paq 'nvim-treesitter/nvim-treesitter'-- Configuration and abstraction layer
-- general editor options
local indent = 2
u.opt('b', 'expandtab', true) -- Use spaces instead of tabs
u.opt('b', 'shiftwidth', indent) -- Size of an indent
u.opt('b', 'smartindent', true) -- Insert indents automatically
u.opt('b', 'tabstop', indent) -- Number of spaces tabs count for
u.opt('o', 'hidden', true) -- Enable modified buffers in background
u.opt('o', 'joinspaces', false) -- No double spaces with join after a dot
u.opt('o', 'scrolloff', 4 ) -- Lines of context
u.opt('o', 'shiftround', true) -- Round indent
u.opt('o', 'sidescrolloff', 8 ) -- Columns of context
u.opt('o', 'smartcase', true) -- Don't ignore case with capitals
u.opt('o', 'splitbelow', true) -- Put new windows below current
u.opt('o', 'splitright', true) -- Put new windows right of current
u.opt('o', 'termguicolors', true) -- True color support
u.opt('o', 'wildmode', 'list:longest') -- Command-line completion mode
u.opt('w', 'wrap', false)
-- end of general editor options
-- line numbers
u.opt('w', 'number', true) -- Print line number
u.opt('w', 'relativenumber', true) -- Relative line numbers
-- end line numbers
-- simple maps (no binding with function)
u.map('n', '<leader><leader>', '<c-^>') -- '\\' alternate between buffers
u.map('', '<C-z>', ':wa|:suspend<cr>') -- save files when suspending with CTRL-Z
u.map('', 'Q', '<nop>') -- disable Ex Mode
u.map('n','<esc>',':nohlsearch<cr>') -- disable search highlight on ESC
-- telescope config
u.map('n','<leader>f',':Telescope find_files<cr>') -- f find files
u.map('n','<leader>b',':Telescope buffers<cr>') -- b for buffers
u.map('n','<leader>g',':Telescope git_files<cr>') -- g for git
u.map('n','<leader>d',':Telescope treesitter<cr>') -- d for definitions
u.map('n','<leader>l',':Telescope live_grep<cr>') -- l for live_grep
u.map('n','<leader>a',':Telescope<cr>') -- a for all
-- telescope configuration
local actions = require('telescope.actions')
require('telescope').setup{
defaults = {
path_display = {
'shorten',
'absolute',
},
mappings = {
i = {
["<esc>"] = actions.close -- exit on ESC and not enter on normal mode
},
},
}
}
-- treesitter configuration
require('nvim-treesitter.configs').setup {
ensure_installed = "maintained", -- one of "all", "maintained" (parsers with maintainers)
highlight = {
enable = true,
},
incremental_selection = {
enable = true,
keymaps = {
init_selection = "gnn",
node_incremental = "grn",
scope_incremental = "grc",
node_decremental = "grm",
},
},
}
-- end treesitter configuration
-- smart_tab: triggers CTRL-P completion when the
-- character before the cursor is not empty otherwise
-- just return TAB
function smart_tab()
local cur_col = fn.col(".")
local cur_char = api.nvim_get_current_line():sub(cur_col - 2, cur_col - 1)
-- %g matches printable character in Lua
return cur_char:match('%g') and u.t'<c-p>' or u.t'<tab>'
end
-- bind <tab> to smar_tab() function
api.nvim_set_keymap('i', '<tab>', 'v:lua.smart_tab()', {expr = true, noremap = true })
-- end of smart_tab
-- shortcut to reload init.lua
cmd 'command! -nargs=0 Init :luafile ~/.config/nvim/init.lua'
cmd 'command! -nargs=0 EInit :e ~/.config/nvim/init.lua'
-- Old implementation of QuickCSE
api.nvim_exec([[
" CSE means Clear Screen and Execute, use it by
" mapping (depending of the project) to a test runner command
" map <leader>r CSE('rspec', '--color')<cr>
function! CSE(runthis, ...)
:wa
exec ':!' . a:runthis . ' ' . join(a:000, ' ')
endfunction
function! QuickCSE(cmd)
exec "map <leader>r :call CSE(\"" . a:cmd . "\")<cr>"
endfunction
]], true)
cmd 'command! -nargs=* QuickCSE call QuickCSE(<q-args>)'
-- end of QuickCSE
-- changes in colors
cmd[[autocmd ColorScheme * highlight LineNr guifg=Grey ctermfg=Grey]]
cmd[[autocmd ColorScheme * highlight TelescopeMatching guifg=Red ctermfg=Red]]
-- end changes in colors
|
Finally fixed the highlight bug, now it loads!
|
Finally fixed the highlight bug, now it loads!
|
Lua
|
mit
|
mavcunha/bash,mavcunha/bash
|
4a6bf9c0912d2b081138947f66cef80eaccf6a94
|
config/nvim/lua/fs.lua
|
config/nvim/lua/fs.lua
|
local M = {}
function M.exists(path)
return M.is_directory(path) or M.is_file(path)
end
function M.glob(path, pattern)
if not M.is_directory(path) then
return {}
end
return (vim.fn.globpath(path, (pattern or "*"))):split("\n")
end
function M.is_directory(path)
return vim.fn.isdirectory(path) == 1
end
function M.is_file(path)
return vim.fn.findfile(path) ~= ""
end
function M.read_file(path)
local ok, result = pcall(vim.fn.readfile, path)
if not ok then
return nil
end
return result
end
return M
|
local M = {}
function M.exists(path)
return M.is_directory(path) or M.is_file(path)
end
function M.glob(path, pattern)
if not M.is_directory(path) then
return {}
end
local result = vim.fn.globpath(path, (pattern or "*"))
if result == "" then
return {}
end
return result:split("\n")
end
function M.is_directory(path)
return vim.fn.isdirectory(path) == 1
end
function M.is_file(path)
return vim.fn.findfile(path) ~= ""
end
function M.read_file(path)
local ok, result = pcall(vim.fn.readfile, path)
if not ok then
return nil
end
return result
end
return M
|
Fix issue where glob returns empty string
|
Fix issue where glob returns empty string
|
Lua
|
mit
|
charlesbjohnson/dotfiles,charlesbjohnson/dotfiles
|
b8676103278cbeabbc28b2ef9d5e236c28e43b6e
|
mod_smacks/mod_smacks.lua
|
mod_smacks/mod_smacks.lua
|
local st = require "util.stanza";
local t_insert, t_remove = table.insert, table.remove;
local tonumber, tostring = tonumber, tostring;
local add_filter = require "util.filters".add_filter;
local xmlns_sm = "urn:xmpp:sm:2";
local sm_attr = { xmlns = xmlns_sm };
local max_unacked_stanzas = 0;
module:add_event_hook("stream-features",
function (session, features)
features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook("s2s-stream-features",
function (data)
data.features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook_stanza(xmlns_sm, "enable",
function (session, stanza)
module:log("debug", "Enabling stream management");
session.smacks = true;
session.handled_stanza_count = 0;
-- Overwrite process_stanza() and send()
local queue, queue_length = {}, 0;
session.outgoing_stanza_queue, session.outgoing_stanza_count = queue, queue_length;
local _send = session.send;
function session.send(stanza)
local attr = stanza.attr;
if attr and not attr.xmlns then -- Stanza in default stream namespace
queue_length = queue_length + 1;
session.outgoing_stanza_count = queue_length;
queue[queue_length] = st.reply(stanza);
end
local ok, err = _send(stanza);
if ok and queue_length > max_unacked_stanzas and not session.awaiting_ack then
session.awaiting_ack = true;
return _send(st.stanza("r", { xmlns = xmlns_sm }));
end
return ok, err;
end
session.handled_stanza_count = 0;
add_filter(session, "stanzas/in", function (stanza)
if not stanza.attr.xmlns then
session.handled_stanza_count = session.handled_stanza_count + 1;
session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count);
end
return stanza;
end);
if not stanza.attr.resume then -- FIXME: Resumption should be a different spec :/
_send(st.stanza("enabled", sm_attr));
return true;
end
end, 100);
module:hook_stanza(xmlns_sm, "r", function (origin, stanza)
if not origin.smacks then
module:log("debug", "Received ack request from non-smack-enabled session");
return;
end
module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count);
-- Reply with <a>
origin.send(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) }));
return true;
end);
module:hook_stanza(xmlns_sm, "a", function (origin, stanza)
if not origin.smacks then return; end
origin.awaiting_ack = nil;
-- Remove handled stanzas from outgoing_stanza_queue
local handled_stanza_count = tonumber(stanza.attr.h)+1;
for i=1,handled_stanza_count do
t_remove(origin.outgoing_stanza_queue, 1);
end
return true;
end);
--TODO: Optimise... incoming stanzas should be handled by a per-session
-- function that has a counter as an upvalue (no table indexing for increments,
-- and won't slow non-198 sessions). We can also then remove the .handled flag
-- on stanzas
function handle_unacked_stanzas(session)
local queue = session.outgoing_stanza_queue;
local error_attr = { type = "cancel" };
if #queue > 0 then
session.outgoing_stanza_queue = {};
for i=1,#queue do
local reply = queue[i];
if reply.attr.to ~= session.full_jid then
reply.attr.type = "error";
reply:tag("error", error_attr)
:tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"});
core_process_stanza(session, queue[i]);
end
end
end
end
local _destroy_session = sessionmanager.destroy_session;
function sessionmanager.destroy_session(session, err)
if session.smacks then
local queue = session.outgoing_stanza_queue;
if #queue > 0 then
module:log("warn", "Destroying session with %d unacked stanzas:", #queue);
for i=1,#queue do
module:log("warn", "::%s", tostring(queue[i]));
end
handle_unacked_stanzas(session);
end
end
return _destroy_session(session, err);
end
|
local st = require "util.stanza";
local t_insert, t_remove = table.insert, table.remove;
local math_min = math.min;
local tonumber, tostring = tonumber, tostring;
local add_filter = require "util.filters".add_filter;
local xmlns_sm = "urn:xmpp:sm:2";
local sm_attr = { xmlns = xmlns_sm };
local max_unacked_stanzas = 0;
module:add_event_hook("stream-features",
function (session, features)
features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook("s2s-stream-features",
function (data)
data.features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook_stanza(xmlns_sm, "enable",
function (session, stanza)
module:log("debug", "Enabling stream management");
session.smacks = true;
-- Overwrite process_stanza() and send()
local queue = {};
session.outgoing_stanza_queue = queue;
session.last_acknowledged_stanza = 0;
local _send = session.send;
function session.send(stanza)
local attr = stanza.attr;
if attr and not attr.xmlns then -- Stanza in default stream namespace
queue[#queue+1] = st.reply(stanza);
end
local ok, err = _send(stanza);
if ok and #queue > max_unacked_stanzas and not session.awaiting_ack then
session.awaiting_ack = true;
return _send(st.stanza("r", { xmlns = xmlns_sm }));
end
return ok, err;
end
session.handled_stanza_count = 0;
add_filter(session, "stanzas/in", function (stanza)
if not stanza.attr.xmlns then
session.handled_stanza_count = session.handled_stanza_count + 1;
session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count);
end
return stanza;
end);
if not stanza.attr.resume then -- FIXME: Resumption should be a different spec :/
_send(st.stanza("enabled", sm_attr));
return true;
end
end, 100);
module:hook_stanza(xmlns_sm, "r", function (origin, stanza)
if not origin.smacks then
module:log("debug", "Received ack request from non-smack-enabled session");
return;
end
module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count);
-- Reply with <a>
origin.send(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) }));
return true;
end);
module:hook_stanza(xmlns_sm, "a", function (origin, stanza)
if not origin.smacks then return; end
origin.awaiting_ack = nil;
-- Remove handled stanzas from outgoing_stanza_queue
local handled_stanza_count = tonumber(stanza.attr.h)-origin.last_acknowledged_stanza;
local queue = origin.outgoing_stanza_queue;
if handled_stanza_count > #queue then
module:log("warn", "The client says it handled %d new stanzas, but we only sent %d :)",
handled_stanza_count, #queue);
for i=1,#queue do
module:log("debug", "Q item %d: %s", i, tostring(queue[i]));
end
end
for i=1,math_min(handled_stanza_count,#queue) do
t_remove(origin.outgoing_stanza_queue, 1);
end
origin.last_acknowledged_stanza = origin.last_acknowledged_stanza + handled_stanza_count;
return true;
end);
--TODO: Optimise... incoming stanzas should be handled by a per-session
-- function that has a counter as an upvalue (no table indexing for increments,
-- and won't slow non-198 sessions). We can also then remove the .handled flag
-- on stanzas
function handle_unacked_stanzas(session)
local queue = session.outgoing_stanza_queue;
local error_attr = { type = "cancel" };
if #queue > 0 then
session.outgoing_stanza_queue = {};
for i=1,#queue do
local reply = queue[i];
if reply.attr.to ~= session.full_jid then
reply.attr.type = "error";
reply:tag("error", error_attr)
:tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"});
core_process_stanza(session, queue[i]);
end
end
end
end
local _destroy_session = sessionmanager.destroy_session;
function sessionmanager.destroy_session(session, err)
if session.smacks then
local queue = session.outgoing_stanza_queue;
if #queue > 0 then
module:log("warn", "Destroying session with %d unacked stanzas:", #queue);
for i=1,#queue do
module:log("warn", "::%s", tostring(queue[i]));
end
handle_unacked_stanzas(session);
end
end
return _destroy_session(session, err);
end
|
mod_smacks: Fix the logic for handling outgoing stanzas and ack requests
|
mod_smacks: Fix the logic for handling outgoing stanzas and ack requests
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
66b4e58b60f38e8339ca665640727b167a1239a1
|
mod_smacks/mod_smacks.lua
|
mod_smacks/mod_smacks.lua
|
local st = require "util.stanza";
local t_insert, t_remove = table.insert, table.remove;
local math_min = math.min;
local tonumber, tostring = tonumber, tostring;
local add_filter = require "util.filters".add_filter;
local xmlns_sm = "urn:xmpp:sm:2";
local sm_attr = { xmlns = xmlns_sm };
local max_unacked_stanzas = 0;
module:add_event_hook("stream-features",
function (session, features)
features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook("s2s-stream-features",
function (data)
data.features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook_stanza(xmlns_sm, "enable",
function (session, stanza)
module:log("debug", "Enabling stream management");
session.smacks = true;
-- Overwrite process_stanza() and send()
local queue = {};
session.outgoing_stanza_queue = queue;
session.last_acknowledged_stanza = 0;
local _send = session.sends2s or session.send;
local function new_send(stanza)
local attr = stanza.attr;
if attr and not attr.xmlns then -- Stanza in default stream namespace
queue[#queue+1] = st.clone(stanza);
end
local ok, err = _send(stanza);
if ok and #queue > max_unacked_stanzas and not session.awaiting_ack then
session.awaiting_ack = true;
return _send(st.stanza("r", { xmlns = xmlns_sm }));
end
return ok, err;
end
if session.sends2s then
session.sends2s = new_send;
else
session.send = new_send;
end
session.handled_stanza_count = 0;
add_filter(session, "stanzas/in", function (stanza)
if not stanza.attr.xmlns then
session.handled_stanza_count = session.handled_stanza_count + 1;
session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count);
end
return stanza;
end);
if not stanza.attr.resume then -- FIXME: Resumption should be a different spec :/
_send(st.stanza("enabled", sm_attr));
return true;
end
end, 100);
module:hook_stanza(xmlns_sm, "r", function (origin, stanza)
if not origin.smacks then
module:log("debug", "Received ack request from non-smack-enabled session");
return;
end
module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count);
-- Reply with <a>
(origin.sends2s or origin.send)(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) }));
return true;
end);
module:hook_stanza(xmlns_sm, "a", function (origin, stanza)
if not origin.smacks then return; end
origin.awaiting_ack = nil;
-- Remove handled stanzas from outgoing_stanza_queue
local handled_stanza_count = tonumber(stanza.attr.h)-origin.last_acknowledged_stanza;
local queue = origin.outgoing_stanza_queue;
if handled_stanza_count > #queue then
module:log("warn", "The client says it handled %d new stanzas, but we only sent %d :)",
handled_stanza_count, #queue);
for i=1,#queue do
module:log("debug", "Q item %d: %s", i, tostring(queue[i]));
end
end
for i=1,math_min(handled_stanza_count,#queue) do
t_remove(origin.outgoing_stanza_queue, 1);
end
origin.last_acknowledged_stanza = origin.last_acknowledged_stanza + handled_stanza_count;
return true;
end);
--TODO: Optimise... incoming stanzas should be handled by a per-session
-- function that has a counter as an upvalue (no table indexing for increments,
-- and won't slow non-198 sessions). We can also then remove the .handled flag
-- on stanzas
function handle_unacked_stanzas(session)
local queue = session.outgoing_stanza_queue;
local error_attr = { type = "cancel" };
if #queue > 0 then
session.outgoing_stanza_queue = {};
for i=1,#queue do
local reply = st.reply(queue[i]);
if reply.attr.to ~= session.full_jid then
reply.attr.type = "error";
reply:tag("error", error_attr)
:tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"});
core_process_stanza(session, reply);
end
end
end
end
local _destroy_session = sessionmanager.destroy_session;
function sessionmanager.destroy_session(session, err)
if session.smacks then
local queue = session.outgoing_stanza_queue;
if #queue > 0 then
module:log("warn", "Destroying session with %d unacked stanzas:", #queue);
for i=1,#queue do
module:log("warn", "::%s", tostring(queue[i]));
end
handle_unacked_stanzas(session);
end
end
return _destroy_session(session, err);
end
|
local st = require "util.stanza";
local t_insert, t_remove = table.insert, table.remove;
local math_min = math.min;
local tonumber, tostring = tonumber, tostring;
local add_filter = require "util.filters".add_filter;
local timer = require "util.timer";
local xmlns_sm = "urn:xmpp:sm:2";
local sm_attr = { xmlns = xmlns_sm };
local resume_timeout = 300;
local max_unacked_stanzas = 0;
module:add_event_hook("stream-features",
function (session, features)
features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook("s2s-stream-features",
function (data)
data.features:tag("sm", sm_attr):tag("optional"):up():up();
end);
module:hook_stanza(xmlns_sm, "enable",
function (session, stanza)
module:log("debug", "Enabling stream management");
session.smacks = true;
-- Overwrite process_stanza() and send()
local queue = {};
session.outgoing_stanza_queue = queue;
session.last_acknowledged_stanza = 0;
local _send = session.sends2s or session.send;
local function new_send(stanza)
local attr = stanza.attr;
if attr and not attr.xmlns then -- Stanza in default stream namespace
queue[#queue+1] = st.clone(stanza);
end
local ok, err = _send(stanza);
if ok and #queue > max_unacked_stanzas and not session.awaiting_ack then
session.awaiting_ack = true;
return _send(st.stanza("r", { xmlns = xmlns_sm }));
end
return ok, err;
end
if session.sends2s then
session.sends2s = new_send;
else
session.send = new_send;
end
session.handled_stanza_count = 0;
add_filter(session, "stanzas/in", function (stanza)
if not stanza.attr.xmlns then
session.handled_stanza_count = session.handled_stanza_count + 1;
session.log("debug", "Handled %d incoming stanzas", session.handled_stanza_count);
end
return stanza;
end);
if not stanza.attr.resume then -- FIXME: Resumption should be a different spec :/
_send(st.stanza("enabled", sm_attr));
return true;
end
end, 100);
module:hook_stanza(xmlns_sm, "r", function (origin, stanza)
if not origin.smacks then
module:log("debug", "Received ack request from non-smack-enabled session");
return;
end
module:log("debug", "Received ack request, acking for %d", origin.handled_stanza_count);
-- Reply with <a>
(origin.sends2s or origin.send)(st.stanza("a", { xmlns = xmlns_sm, h = tostring(origin.handled_stanza_count) }));
return true;
end);
module:hook_stanza(xmlns_sm, "a", function (origin, stanza)
if not origin.smacks then return; end
origin.awaiting_ack = nil;
-- Remove handled stanzas from outgoing_stanza_queue
local handled_stanza_count = tonumber(stanza.attr.h)-origin.last_acknowledged_stanza;
local queue = origin.outgoing_stanza_queue;
if handled_stanza_count > #queue then
module:log("warn", "The client says it handled %d new stanzas, but we only sent %d :)",
handled_stanza_count, #queue);
for i=1,#queue do
module:log("debug", "Q item %d: %s", i, tostring(queue[i]));
end
end
for i=1,math_min(handled_stanza_count,#queue) do
t_remove(origin.outgoing_stanza_queue, 1);
end
origin.last_acknowledged_stanza = origin.last_acknowledged_stanza + handled_stanza_count;
return true;
end);
--TODO: Optimise... incoming stanzas should be handled by a per-session
-- function that has a counter as an upvalue (no table indexing for increments,
-- and won't slow non-198 sessions). We can also then remove the .handled flag
-- on stanzas
function handle_unacked_stanzas(session)
local queue = session.outgoing_stanza_queue;
local error_attr = { type = "cancel" };
if #queue > 0 then
session.outgoing_stanza_queue = {};
for i=1,#queue do
local reply = st.reply(queue[i]);
if reply.attr.to ~= session.full_jid then
reply.attr.type = "error";
reply:tag("error", error_attr)
:tag("recipient-unavailable", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"});
core_process_stanza(session, reply);
end
end
end
end
local _destroy_session = sessionmanager.destroy_session;
function sessionmanager.destroy_session(session, err)
if session.smacks then
if not session.resumption_token then
local queue = session.outgoing_stanza_queue;
if #queue > 0 then
module:log("warn", "Destroying session with %d unacked stanzas:", #queue);
for i=1,#queue do
module:log("warn", "::%s", tostring(queue[i]));
end
handle_unacked_stanzas(session);
end
else
session.hibernating = true;
timer.add_task(resume_timeout, function ()
if session.hibernating then
session.resumption_token = nil;
sessionmanager.destroy_session(session); -- Re-destroy
end
end);
return; -- Postpone destruction for now
end
end
return _destroy_session(session, err);
end
|
mod_smacks: Fixes for monkey-patched sessionmanager.destroy to handle stream resumption, and to fall back to stock destroy() if the session is not smacks-enabled.
|
mod_smacks: Fixes for monkey-patched sessionmanager.destroy to handle stream resumption, and to fall back to stock destroy() if the session is not smacks-enabled.
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
d8f0c32a5ac876295f7a14ebdb45522851f119ff
|
src/cosy/loader/lua.lua
|
src/cosy/loader/lua.lua
|
if #setmetatable ({}, { __len = function () return 1 end }) ~= 1
then
error "Cosy requires Lua >= 5.2 or Luajit with 5.2 compatibility to run."
end
return function (t)
t = t or {}
local loader = {}
local modules = setmetatable ({}, { __mode = "kv" })
loader.hotswap = t.hotswap
or require "hotswap".new {}
loader.require = loader.hotswap.require
loader.load = function (name)
if modules [name] then
return modules [name]
end
local module = loader.require (name) (loader) or true
modules [name] = module
return module
end
loader.logto = t.logto
loader.scheduler = t.scheduler
if not loader.scheduler then
local ok, s = pcall (loader.require, "copas.ev")
if ok then
loader.scheduler = s
else
loader.scheduler = loader.require "copas"
loader.scheduler.autoclose = false
end
end
_G.package = loader.hotswap
_G.require = loader.require
package.loaded.copas = loader.scheduler
loader.coroutine = t.coroutine
or loader.scheduler._coroutine
or loader.require "coroutine.make" ()
_G.coroutine = loader.coroutine
loader.request = t.request
or loader.require "copas.http".request
loader.load "cosy.string"
loader.hotswap.preload ["websocket.bit" ] = function ()
return loader.require "cosy.loader.patches.bit"
end
loader.hotswap.preload ["websocket.server_copas"] = function ()
return loader.require "cosy.loader.patches.server_copas"
end
return loader
end
|
if #setmetatable ({}, { __len = function () return 1 end }) ~= 1
then
error "Cosy requires Lua >= 5.2 to run."
end
return function (t)
t = t or {}
local loader = {}
local modules = setmetatable ({}, { __mode = "kv" })
loader.hotswap = t.hotswap
or require "hotswap".new {}
loader.require = loader.hotswap.require
loader.load = function (name)
if modules [name] then
return modules [name]
end
local module = loader.require (name) (loader) or true
modules [name] = module
return module
end
loader.logto = t.logto
loader.scheduler = t.scheduler
if not loader.scheduler then
local ok, s = pcall (loader.require, "copas.ev")
if ok then
loader.scheduler = s
else
loader.scheduler = loader.require "copas"
loader.scheduler.autoclose = false
end
end
_G.package = loader.hotswap
_G.require = loader.require
package.loaded.copas = loader.scheduler
loader.coroutine = t.coroutine
or loader.scheduler._coroutine
or loader.require "coroutine.make" ()
_G.coroutine = loader.coroutine
loader.request = t.request
or loader.require "copas.http".request
loader.load "cosy.string"
loader.hotswap.preload ["websocket.bit" ] = function ()
return loader.require "cosy.loader.patches.bit"
end
loader.hotswap.preload ["websocket.server_copas"] = function ()
return loader.require "cosy.loader.patches.server_copas"
end
return loader
end
|
Fix message on required lua version.
|
Fix message on required lua version.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
fefaf17bca95ee28d7537ebc72eb0d6fdec26c1b
|
fimbul/gtk/mainwindow.lua
|
fimbul/gtk/mainwindow.lua
|
---@module fimbul.gtk.mainwindow
local mainwindow = {}
local base = _G
local table = require("table")
local lgi = require("lgi")
local Gtk = lgi.require("Gtk", "3.0")
local console_page = require("fimbul.gtk.mainwindow.console_page")
local party_page = require("fimbul.gtk.mainwindow.party_page")
function mainwindow:_emit(f)
for _, p in base.pairs(self.pages) do
local event = p["on_" .. f]
if event ~= nil and type(event) == 'function' then
event(p)
end
end
end
function mainwindow:_file_open()
dlg = Gtk.FileChooserDialog(
{ title = "Open repository...",
action = Gtk.FileChooserAction.SELECT_FOLDER,
transient_for = self.wnd,
destroy_with_parent = true,
buttons = {
{ "Open", Gtk.ResponseType.ACCEPT },
{ Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL },
},
})
res = dlg:run()
if res == Gtk.ResponseType.ACCEPT then
ok, err = pcall(self.repository.open, self.repository, dlg:get_filename())
if not ok then
self.console:error(err);
else
-- Load repository
ok, err = pcall(self.repository.load, self.repository)
if not ok then
self.console:error(err)
else
self:_emit("repository_open")
end
end
end
dlg:destroy()
end
function mainwindow:_setup()
self.wnd = Gtk.Window({
title = 'Fimbul',
on_destroy = Gtk.main_quit
})
self.wnd:set_size_request(600, 400)
self.menubar = Gtk.MenuBar(
{
id = "menubar",
Gtk.MenuItem {
label = "File",
visible = true,
submenu = Gtk.Menu {
Gtk.MenuItem {
label = "Open...",
id = "file_open",
on_activate = function () self:_file_open() end
},
Gtk.SeparatorMenuItem(),
Gtk.MenuItem {
label = "Quit",
id = "file_quit",
on_activate = Gtk.main_quit
}
},
},
})
self.notebook = Gtk.Notebook()
self.pages = {}
self.console = console_page:new(self.repository)
table.insert(self.pages, self.console)
self.party = party_page:new(self.repository)
table.insert(self.pages, self.party)
for _, page in base.pairs(self.pages) do
self.notebook:append_page(page:widget(),
Gtk.Label({label = page:name()}))
end
grid = Gtk.Grid()
grid:attach(self.menubar, 0, 0, 1, 1)
grid:attach(self.notebook, 0, 1, 1, 1)
self.wnd:add(grid)
end
function mainwindow:show()
self.wnd:show_all()
end
function mainwindow:new(repository)
local neu = {}
setmetatable(neu, self)
self.__index = self
neu.repository = repository
neu:_setup()
return neu
end
return mainwindow
|
---@module fimbul.gtk.mainwindow
local mainwindow = {}
local base = _G
local table = require("table")
local lgi = require("lgi")
local Gtk = lgi.require("Gtk", "3.0")
local console_page = require("fimbul.gtk.mainwindow.console_page")
local party_page = require("fimbul.gtk.mainwindow.party_page")
function mainwindow:_emit(f)
for _, p in base.pairs(self.pages) do
local event = p["on_" .. f]
if event ~= nil and type(event) == 'function' then
event(p)
end
end
end
function mainwindow:_file_open()
dlg = Gtk.FileChooserDialog(
{ title = "Open repository...",
action = Gtk.FileChooserAction.SELECT_FOLDER,
transient_for = self.wnd,
destroy_with_parent = true,
buttons = {
{ "Open", Gtk.ResponseType.ACCEPT },
{ Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL },
},
})
res = dlg:run()
if res == Gtk.ResponseType.ACCEPT then
local filename = dlg:get_filename()
dlg:destroy()
ok, err = pcall(self.repository.open, self.repository, filename)
if not ok then
self.console:error(err);
else
-- Load repository
ok, err = pcall(self.repository.load, self.repository)
if not ok then
self.console:error(err)
else
self:_emit("repository_open")
end
end
else
dlg:destroy()
end
end
function mainwindow:_setup()
self.wnd = Gtk.Window({
title = 'Fimbul',
on_destroy = Gtk.main_quit
})
self.wnd:set_size_request(600, 400)
self.menubar = Gtk.MenuBar(
{
id = "menubar",
Gtk.MenuItem {
label = "File",
visible = true,
submenu = Gtk.Menu {
Gtk.MenuItem {
label = "Open...",
id = "file_open",
on_activate = function () self:_file_open() end
},
Gtk.SeparatorMenuItem(),
Gtk.MenuItem {
label = "Quit",
id = "file_quit",
on_activate = Gtk.main_quit
}
},
},
})
self.notebook = Gtk.Notebook()
self.pages = {}
self.console = console_page:new(self.repository)
table.insert(self.pages, self.console)
self.party = party_page:new(self.repository)
table.insert(self.pages, self.party)
for _, page in base.pairs(self.pages) do
self.notebook:append_page(page:widget(),
Gtk.Label({label = page:name()}))
end
grid = Gtk.Grid()
grid:attach(self.menubar, 0, 0, 1, 1)
grid:attach(self.notebook, 0, 1, 1, 1)
self.wnd:add(grid)
end
function mainwindow:show()
self.wnd:show_all()
end
function mainwindow:new(repository)
local neu = {}
setmetatable(neu, self)
self.__index = self
neu.repository = repository
neu:_setup()
return neu
end
return mainwindow
|
Fix dialog not closing on error.
|
Fix dialog not closing on error.
|
Lua
|
bsd-2-clause
|
n0la/fimbul
|
d0ffb0948994cad65c503a33c91e447bb75cc7b1
|
frontend/ui/screen.lua
|
frontend/ui/screen.lua
|
--[[
Copyright (C) 2011 Hans-Werner Hilse <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
]]--
--[[
Codes for rotation modes:
1 for no rotation,
2 for landscape with bottom on the right side of screen, etc.
2
+--------------+
| +----------+ |
| | | |
| | Freedom! | |
| | | |
| | | |
3 | | | | 1
| | | |
| | | |
| +----------+ |
| |
| |
+--------------+
0
--]]
Screen = {
width = 0,
height = 0,
pitch = 0,
native_rotation_mode = nil,
cur_rotation_mode = 0,
bb = nil,
saved_bb = nil,
fb = einkfb.open("/dev/fb0"),
}
function Screen:init()
_, self.height = self.fb:getSize()
-- for unknown strange reason, pitch*2 is less than screen width in KPW
-- so we need to calculate width by pitch here
self.width = self.fb:getPitch()*2
self.pitch = self:getPitch()
self.bb = Blitbuffer.new(self.width, self.height, self.pitch)
self.native_rotation_mode = self.fb:getOrientation()
self.cur_rotation_mode = self.native_rotation_mode
end
function Screen:refresh(refesh_type)
if self.native_rotation_mode == self.cur_rotation_mode then
self.fb.bb:blitFrom(self.bb, 0, 0, 0, 0, self.width, self.height)
elseif self.native_rotation_mode == 0 and self.cur_rotation_mode == 1 then
self.fb.bb:blitFromRotate(self.bb, 270)
end
self.fb:refresh(refesh_type)
end
function Screen:getSize()
return Geom:new{w = self.width, h = self.height}
end
function Screen:getWidth()
return self.width
end
function Screen:getHeight()
return self.height
end
function Screen:getPitch()
return self.ptich
end
function Screen:getNativeRotationMode()
-- in EMU mode, you will always get 0 from getOrientation()
return self.fb:getOrientation()
end
function Screen:getRotationMode()
return self.cur_rotation_mode
end
function Screen:setRotationMode(mode)
if mode > 3 or mode < 0 then
return
end
-- mode 0 and mode 2 has the same width and height, so do mode 1 and 3
if (self.cur_rotation_mode % 2) ~= (mode % 2) then
self.width, self.height = self.height, self.width
end
self.cur_rotation_mode = mode
self.bb:free()
self.pitch = self.width/2
self.bb = Blitbuffer.new(self.width, self.height, self.pitch)
-- update mode for input module
Input.rotation = mode
end
function Screen:setViewMode(mode)
if mode == "portrait" then
if self.cur_rotation_mode ~= 0 then
self:setRotationMode(0)
end
elseif mode == "landscape" then
if self.cur_rotation_mode ~= 1 then
self:setRotationMode(1)
end
end
end
--[[
@brief change gesture's x and y coordinates according to screen view mode
@param ges gesture that you want to adjust
@return adjusted gesture.
--]]
function Screen:adjustGesCoordinate(ges)
-- we do nothing is screen is not rotated
if self.native_rotation_mode == self.cur_rotation_mode then
return ges
end
if self.native_rotation_mode == 0 and self.cur_rotation_mode == 1 then
ges.pos.x, ges.pos.y = (self.width - ges.pos.y), (ges.pos.x)
end
return ges
end
function Screen:saveCurrentBB()
local width, height = self:getWidth(), self:getHeight()
if not self.saved_bb then
self.saved_bb = Blitbuffer.new(width, height, self:getPitch())
end
if self.saved_bb:getWidth() ~= width then
self.saved_bb:free()
self.saved_bb = Blitbuffer.new(width, height, self:getPitch())
end
self.saved_bb:blitFullFrom(self.bb)
end
function Screen:restoreFromSavedBB()
self:restoreFromBB(self.saved_bb)
end
function Screen:getCurrentScreenBB()
local bb = Blitbuffer.new(self:getWidth(), self:getHeight())
bb:blitFullFrom(self.bb)
return bb
end
function Screen:restoreFromBB(bb)
if bb then
self.bb:blitFullFrom(bb)
else
DEBUG("Got nil bb in restoreFromSavedBB!")
end
end
|
--[[
Copyright (C) 2011 Hans-Werner Hilse <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
]]--
--[[
Codes for rotation modes:
1 for no rotation,
2 for landscape with bottom on the right side of screen, etc.
2
+--------------+
| +----------+ |
| | | |
| | Freedom! | |
| | | |
| | | |
3 | | | | 1
| | | |
| | | |
| +----------+ |
| |
| |
+--------------+
0
--]]
Screen = {
width = 0,
height = 0,
pitch = 0,
native_rotation_mode = nil,
cur_rotation_mode = 0,
bb = nil,
saved_bb = nil,
fb = einkfb.open("/dev/fb0"),
}
function Screen:init()
_, self.height = self.fb:getSize()
-- for unknown strange reason, pitch*2 is less than screen width in KPW
-- so we need to calculate width by pitch here
self.width = self.fb:getPitch()*2
self.pitch = self:getPitch()
self.bb = Blitbuffer.new(self.width, self.height, self.pitch)
self.native_rotation_mode = self.fb:getOrientation()
self.cur_rotation_mode = self.native_rotation_mode
end
function Screen:refresh(refesh_type)
if self.native_rotation_mode == self.cur_rotation_mode then
self.fb.bb:blitFrom(self.bb, 0, 0, 0, 0, self.width, self.height)
elseif self.native_rotation_mode == 0 and self.cur_rotation_mode == 1 then
self.fb.bb:blitFromRotate(self.bb, 270)
elseif self.native_rotation_mode == 1 and self.cur_rotation_mode == 0 then
self.fb.bb:blitFromRotate(self.bb, 90)
end
self.fb:refresh(refesh_type)
end
function Screen:getSize()
return Geom:new{w = self.width, h = self.height}
end
function Screen:getWidth()
return self.width
end
function Screen:getHeight()
return self.height
end
function Screen:getPitch()
return self.ptich
end
function Screen:getNativeRotationMode()
-- in EMU mode, you will always get 0 from getOrientation()
return self.fb:getOrientation()
end
function Screen:getRotationMode()
return self.cur_rotation_mode
end
function Screen:setRotationMode(mode)
if mode > 3 or mode < 0 then
return
end
-- mode 0 and mode 2 has the same width and height, so do mode 1 and 3
if (self.cur_rotation_mode % 2) ~= (mode % 2) then
self.width, self.height = self.height, self.width
end
self.cur_rotation_mode = mode
self.bb:free()
self.pitch = self.width/2
self.bb = Blitbuffer.new(self.width, self.height, self.pitch)
-- update mode for input module
Input.rotation = mode
end
function Screen:setViewMode(mode)
if mode == "portrait" then
if self.cur_rotation_mode ~= 0 then
self:setRotationMode(0)
end
elseif mode == "landscape" then
if self.cur_rotation_mode ~= 1 then
self:setRotationMode(1)
end
end
end
--[[
@brief change gesture's x and y coordinates according to screen view mode
@param ges gesture that you want to adjust
@return adjusted gesture.
--]]
function Screen:adjustGesCoordinate(ges)
-- we do nothing is screen is not rotated
if self.native_rotation_mode == self.cur_rotation_mode then
return ges
end
if self.cur_rotation_mode == 1 then
ges.pos.x, ges.pos.y = (self.width - ges.pos.y), (ges.pos.x)
end
return ges
end
function Screen:saveCurrentBB()
local width, height = self:getWidth(), self:getHeight()
if not self.saved_bb then
self.saved_bb = Blitbuffer.new(width, height, self:getPitch())
end
if self.saved_bb:getWidth() ~= width then
self.saved_bb:free()
self.saved_bb = Blitbuffer.new(width, height, self:getPitch())
end
self.saved_bb:blitFullFrom(self.bb)
end
function Screen:restoreFromSavedBB()
self:restoreFromBB(self.saved_bb)
end
function Screen:getCurrentScreenBB()
local bb = Blitbuffer.new(self:getWidth(), self:getHeight())
bb:blitFullFrom(self.bb)
return bb
end
function Screen:restoreFromBB(bb)
if bb then
self.bb:blitFullFrom(bb)
else
DEBUG("Got nil bb in restoreFromSavedBB!")
end
end
|
fix adjustGesCoordinate
|
fix adjustGesCoordinate
|
Lua
|
agpl-3.0
|
koreader/koreader-base,koreader/koreader,Frenzie/koreader,apletnev/koreader-base,koreader/koreader-base,Frenzie/koreader-base,Hzj-jie/koreader-base,chihyang/koreader,Hzj-jie/koreader-base,houqp/koreader,Frenzie/koreader,frankyifei/koreader-base,poire-z/koreader,Frenzie/koreader-base,chrox/koreader,Hzj-jie/koreader,mihailim/koreader,NiLuJe/koreader-base,NiLuJe/koreader-base,houqp/koreader-base,Frenzie/koreader-base,lgeek/koreader,mwoz123/koreader,NiLuJe/koreader,Markismus/koreader,frankyifei/koreader-base,koreader/koreader-base,ashang/koreader,NiLuJe/koreader,apletnev/koreader-base,houqp/koreader-base,Hzj-jie/koreader-base,NiLuJe/koreader-base,NiLuJe/koreader-base,robert00s/koreader,houqp/koreader-base,noname007/koreader,Hzj-jie/koreader-base,houqp/koreader-base,ashhher3/koreader,frankyifei/koreader,koreader/koreader-base,frankyifei/koreader-base,frankyifei/koreader-base,apletnev/koreader,Frenzie/koreader-base,apletnev/koreader-base,pazos/koreader,NickSavage/koreader,poire-z/koreader,apletnev/koreader-base,koreader/koreader
|
1c3a4ed4f9a4e7007038bd42f977e463f0057960
|
src/lua/lluv/redis.lua
|
src/lua/lluv/redis.lua
|
------------------------------------------------------------------
--
-- Author: Alexey Melnichuk <[email protected]>
--
-- Copyright (C) 2015 Alexey Melnichuk <[email protected]>
--
-- Licensed according to the included 'LICENSE' document
--
-- This file is part of lua-lluv-redis library.
--
------------------------------------------------------------------
local uv = require "lluv"
local ut = require "lluv.utils"
local RedisStream = require "lluv.redis.stream"
local RedisCommander = require "lluv.redis.commander"
local function ocall(fn, ...) if fn then return fn(...) end end
local EOF = uv.error("LIBUV", uv.EOF)
local function nil_if_empty(t)
if t and #t == 0 then return nil end
return t
end
-- Redis url shold be `[<redis>://][<password>@]host[:<port>][/<db>]`
function decode_url(url)
local scheme, pass, host, port, db
scheme, url = ut.split_first(url, '://', true)
if not url then url = scheme
elseif scheme ~= 'redis' then
error('unsupported scheme: ' .. scheme)
end
pass, url = ut.split_first(url, '@', true)
if not url then url, pass = pass end
host, url = ut.split_first(url, ':', true)
if not url then host, db = ut.split_first(host, '/', true)
else port, db = ut.split_first(url, '/', true) end
return nil_if_empty(host), nil_if_empty(port), nil_if_empty(pass), nil_if_empty(db)
end
local function call_q(q, ...)
while true do
local cb = q:pop()
if not cb then break end
cb(...)
end
end
-------------------------------------------------------------------
local Connection = ut.class() do
function Connection:__init(opt)
if type(opt) == 'string' then
opt = {server = opt}
else opt = opt or {} end
if opt.server then
self._host, self._port, self._pass, self._db = decode_url(opt.server)
self._host = self._host or '127.0.0.1'
self._port = self._port or '6379'
else
self._host = opt.host or '127.0.0.1'
self._port = opt.port or '6379'
end
self._db = opt.db
self._pass = opt.pass
self._stream = RedisStream.new(self)
self._commander = RedisCommander.new(self._stream)
self._open_q = ut.Queue.new()
self._close_q = ut.Queue.new()
self._delay_q = ut.Queue.new()
self._ready = false
self._on_message = nil
self._on_error = nil
local function on_write_error(cli, err)
if err then self._stream:halt(err) end
end
self._on_write_handler = on_write_error
self._stream
:on_command(function(s, data, cb)
if self._ready then
return self._cnn:write(data, on_write_error)
end
if self._cnn then
self._delay_q:push(data)
return true
end
error('Can not execute command on closed client', 3)
end)
:on_halt(function(s, err)
self:close(err)
if err ~= EOF then
ocall(self._on_error, self, err)
end
end)
:on_message(function(...)
ocall(self._on_message, ...)
end)
return self
end
function Connection:clone()
return Connection.new{
host = self._host;
port = self._port;
pass = self._pass;
db = self._db;
}
end
local function on_ready(self, ...)
self._ready = true
while true do
local data = self._delay_q:pop()
if not data then break end
self._cnn:write(data, self._on_write_handler)
end
while self._ready do
local cb = self._open_q:pop()
if not cb then break end
cb(self, ...)
end
end
function Connection:open(cb)
if self._ready then
uv.defer(cb, self)
return self
end
if cb then self._open_q:push(cb) end
-- Only first call
if self._cnn then return self end
local cmd -- Init command
local ok, err = uv.tcp():connect(self._host, self._port, function(cli, err)
if err then return self:close(err) end
cli:start_read(function(cli, err, data)
if err then return self._stream:halt(err) end
self._stream:append(data):execute()
end)
if not cmd then return on_ready(self) end
-- send out init command
for _, data in ipairs(cmd) do
cli:write(data, self._on_write_handler)
end
end)
if not ok then return nil, err end
self._cnn = ok
if self._db or self._pass then
local called = false
-- call until first error
local wrap = function(last)
return function(_, err, ...)
if called then return end
if err then
called = true
return self:close(err)
end
if last then on_ready(self, err, ...) end
end
end
local last = not not self._db
if self._pass then self:auth (tostring(self._pass), wrap(last)) end
if self._db then self:select(tostring(self._db ), wrap(true)) end
cmd = {}
while true do
local data = self._delay_q:pop()
if not data then break end
cmd[#cmd + 1] = data
end
end
return self
end
function Connection:close(err, cb)
if type(err) == 'function' then
cb, err = err
end
if not self._cnn then
if cb then uv.defer(cb, self) end
return
end
if cb then self._close_q:push(cb) end
if not (self._cnn:closed() or self._cnn:closing()) then
local err = err
self._cnn:close(function()
self._cnn = nil
call_q(self._open_q, self, err or EOF)
self._stream:reset(err or EOF)
call_q(self._close_q, self, err)
self._delay_q:reset()
end)
end
self._ready = false
end
function Connection:closed()
if self._cnn then
return self._cnn:closed() or self._cnn:closing()
end
return true
end
function Connection:pipeline()
return self._commander:pipeline()
end
function Connection:on_error(handler)
self._on_error = handler
return self
end
function Connection:on_message(handler)
self._on_message = handler
return self
end
function Connection:__tostring()
return string.format("Lua UV Redis (%s)", tostring(self._cnn))
end
RedisCommander.commands(function(name)
name = name:lower()
Connection[name] = function(self, ...)
return self._commander[name](self._commander, ...)
end
end)
end
-------------------------------------------------------------------
return {
Connection = Connection;
}
|
------------------------------------------------------------------
--
-- Author: Alexey Melnichuk <[email protected]>
--
-- Copyright (C) 2015 Alexey Melnichuk <[email protected]>
--
-- Licensed according to the included 'LICENSE' document
--
-- This file is part of lua-lluv-redis library.
--
------------------------------------------------------------------
local uv = require "lluv"
local ut = require "lluv.utils"
local RedisStream = require "lluv.redis.stream"
local RedisCommander = require "lluv.redis.commander"
local function ocall(fn, ...) if fn then return fn(...) end end
local EOF = uv.error("LIBUV", uv.EOF)
local function nil_if_empty(t)
if t and #t == 0 then return nil end
return t
end
-- Redis url shold be `[<redis>://][<password>@]host[:<port>][/<db>]`
function decode_url(url)
local scheme, pass, host, port, db
scheme, url = ut.split_first(url, '://', true)
if not url then url = scheme
elseif scheme ~= 'redis' then
error('unsupported scheme: ' .. scheme)
end
pass, url = ut.split_first(url, '@', true)
if not url then url, pass = pass end
host, url = ut.split_first(url, ':', true)
if not url then host, db = ut.split_first(host, '/', true)
else port, db = ut.split_first(url, '/', true) end
return nil_if_empty(host), nil_if_empty(port), nil_if_empty(pass), nil_if_empty(db)
end
local function call_q(q, ...)
while true do
local cb = q:pop()
if not cb then break end
cb(...)
end
end
-------------------------------------------------------------------
local Connection = ut.class() do
function Connection:__init(opt)
if type(opt) == 'string' then
opt = {server = opt}
else opt = opt or {} end
if opt.server then
self._host, self._port, self._pass, self._db = decode_url(opt.server)
self._host = self._host or '127.0.0.1'
self._port = self._port or '6379'
else
self._host = opt.host or '127.0.0.1'
self._port = opt.port or '6379'
self._db = opt.db
self._pass = opt.pass
end
self._stream = RedisStream.new(self)
self._commander = RedisCommander.new(self._stream)
self._open_q = ut.Queue.new()
self._close_q = ut.Queue.new()
self._delay_q = ut.Queue.new()
self._ready = false
self._on_message = nil
self._on_error = nil
local function on_write_error(cli, err)
if err then self._stream:halt(err) end
end
self._on_write_handler = on_write_error
self._stream
:on_command(function(s, data, cb)
if self._ready then
return self._cnn:write(data, on_write_error)
end
if self._cnn then
self._delay_q:push(data)
return true
end
error('Can not execute command on closed client', 3)
end)
:on_halt(function(s, err)
self:close(err)
if err ~= EOF then
ocall(self._on_error, self, err)
end
end)
:on_message(function(...)
ocall(self._on_message, ...)
end)
return self
end
function Connection:clone()
return Connection.new{
host = self._host;
port = self._port;
pass = self._pass;
db = self._db;
}
end
local function on_ready(self, ...)
self._ready = true
while true do
local data = self._delay_q:pop()
if not data then break end
self._cnn:write(data, self._on_write_handler)
end
while self._ready do
local cb = self._open_q:pop()
if not cb then break end
cb(self, ...)
end
end
function Connection:open(cb)
if self._ready then
uv.defer(cb, self)
return self
end
if cb then self._open_q:push(cb) end
-- Only first call
if self._cnn then return self end
local cmd -- Init command
local ok, err = uv.tcp():connect(self._host, self._port, function(cli, err)
if err then return self:close(err) end
cli:start_read(function(cli, err, data)
if err then return self._stream:halt(err) end
self._stream:append(data):execute()
end)
if not cmd then return on_ready(self) end
-- send out init command
for _, data in ipairs(cmd) do
cli:write(data, self._on_write_handler)
end
end)
if not ok then return nil, err end
self._cnn = ok
if self._db or self._pass then
local called = false
-- call until first error
local wrap = function(last)
return function(_, err, ...)
if called then return end
if err then
called = true
return self:close(err)
end
if last then on_ready(self, err, ...) end
end
end
local last = not not self._db
if self._pass then self:auth (tostring(self._pass), wrap(last)) end
if self._db then self:select(tostring(self._db ), wrap(true)) end
cmd = {}
while true do
local data = self._delay_q:pop()
if not data then break end
cmd[#cmd + 1] = data
end
end
return self
end
function Connection:close(err, cb)
if type(err) == 'function' then
cb, err = err
end
if not self._cnn then
if cb then uv.defer(cb, self) end
return
end
if cb then self._close_q:push(cb) end
if not (self._cnn:closed() or self._cnn:closing()) then
local err = err
self._cnn:close(function()
self._cnn = nil
call_q(self._open_q, self, err or EOF)
self._stream:reset(err or EOF)
call_q(self._close_q, self, err)
self._delay_q:reset()
end)
end
self._ready = false
end
function Connection:closed()
if self._cnn then
return self._cnn:closed() or self._cnn:closing()
end
return true
end
function Connection:pipeline()
return self._commander:pipeline()
end
function Connection:on_error(handler)
self._on_error = handler
return self
end
function Connection:on_message(handler)
self._on_message = handler
return self
end
function Connection:__tostring()
return string.format("Lua UV Redis (%s)", tostring(self._cnn))
end
RedisCommander.commands(function(name)
name = name:lower()
Connection[name] = function(self, ...)
return self._commander[name](self._commander, ...)
end
end)
end
-------------------------------------------------------------------
local cnn = Connection.new({
server = 'redis://127.0.0.1/11'
})
return {
Connection = Connection;
}
|
Fix. Get password and db number from URL.
|
Fix. Get password and db number from URL.
|
Lua
|
mit
|
moteus/lua-lluv-redis
|
bd495709b1507dcdae949acc46bf72550859791a
|
rico.lua
|
rico.lua
|
--
-- rico.lua
--
--
-- Remote Imap collector COunters. Stores some scheduling information needed for collectors.
--
--
-- Space 0: Stores last collect time, last success collect time and so on.
-- Tuple: { coll_id (NUM), last_time (NUM), last_ok (NUM), old_threshold (NUM), last_fullsync (NUM), success_collects_num (NUM) }
-- Index 0: TREE { coll_id }
--
function rico_get(coll_id)
coll_id = box.unpack('i', coll_id)
local t = box.select_limit(0, 0, 0, 1, coll_id)
if t ~=nil then return t:transform(0,1) end
end
function rico_get_lasttimes(from_coll_id, to_coll_id)
from_coll_id = box.unpack('i', from_coll_id)
to_coll_id = box.unpack('i', to_coll_id)
local result = {}
for t in box.space[0].index[0]:iterator(box.index.GE, from_coll_id) do
if box.unpack('i', t[0]) >= to_coll_id then break end
table.insert(result, { t:slice(0, 2) })
end
return result
end
function rico_reset(coll_id)
coll_id = box.unpack('i', coll_id)
box.replace(0, coll_id, box.time(), box.time(), box.time(), box.time(), 0)
end
function rico_update_success(coll_id, need_update_old_threshold, need_update_last_fullsync)
coll_id = box.unpack('i', coll_id)
need_update_old_threshold = box.unpack('i', need_update_old_threshold)
need_update_last_fullsync = box.unpack('i', need_update_last_fullsync)
local status, t
if need_update_old_threshold ~= 0 and need_update_last_fullsync ~= 0 then
status, t = pcall(box.update, 0, { coll_id }, "=p=p=p=p+p", 1, box.time(), 2, box.time(), 3, box.time(), 4, box.time(), 5, 1)
elseif need_update_old_threshold ~= 0 then
status, t = pcall(box.update, 0, { coll_id }, "=p=p=p+p", 1, box.time(), 2, box.time(), 3, box.time(), 5, 1)
elseif need_update_last_fullsync ~= 0 then
status, t = pcall(box.update, 0, { coll_id }, "=p=p=p+p", 1, box.time(), 2, box.time(), 4, box.time(), 5, 1)
else
status, t = pcall(box.update, 0, { coll_id }, "=p=p+p", 1, box.time(), 2, box.time(), 5, 1)
end
if not status or t == nil then
box.replace(0, coll_id, box.time(), box.time(), box.time(), box.time(), 1)
end
end
function rico_update_failure(coll_id, need_update_last_fullsync)
coll_id = box.unpack('i', coll_id)
need_update_last_fullsync = box.unpack('i', need_update_last_fullsync)
local status, t
if need_update_last_fullsync ~= 0 then
status, t = pcall(box.update, 0, { coll_id }, "=p=p", 1, box.time(), 4, box.time())
else
status, t = pcall(box.update, 0, { coll_id }, "=p", 1, box.time())
end
if not status or t == nil then
box.replace(0, coll_id, box.time(), box.time(), box.time(), box.time(), 0)
end
end
function rico_drop(coll_id)
coll_id = box.unpack('i', coll_id)
local t = box.delete(0, coll_id)
end
|
--
-- rico.lua
--
--
-- Remote Imap collector COunters. Stores some scheduling information needed for collectors.
--
--
-- Space 0: Stores last collect time, last success collect time and so on.
-- Tuple: { coll_id (NUM), last_time (NUM), last_ok (NUM), old_threshold (NUM), last_fullsync (NUM), success_collects_num (NUM) }
-- Index 0: TREE { coll_id }
--
function rico_get(coll_id)
coll_id = box.unpack('i', coll_id)
local t = box.select_limit(0, 0, 0, 1, coll_id)
if t ~=nil then return t:transform(0,1) end
end
function rico_get_lasttimes(from_coll_id, to_coll_id)
from_coll_id = box.unpack('i', from_coll_id)
to_coll_id = box.unpack('i', to_coll_id)
local result = {}
for t in box.space[0].index[0]:iterator(box.index.GE, from_coll_id) do
if box.unpack('i', t[0]) >= to_coll_id then break end
table.insert(result, { t:slice(0, 2) })
end
if #result > 0 then return result end
return unpack(result)
end
function rico_reset(coll_id)
coll_id = box.unpack('i', coll_id)
box.replace(0, coll_id, box.time(), box.time(), box.time(), box.time(), 0)
end
function rico_update_success(coll_id, need_update_old_threshold, need_update_last_fullsync)
coll_id = box.unpack('i', coll_id)
need_update_old_threshold = box.unpack('i', need_update_old_threshold)
need_update_last_fullsync = box.unpack('i', need_update_last_fullsync)
local status, t
if need_update_old_threshold ~= 0 and need_update_last_fullsync ~= 0 then
status, t = pcall(box.update, 0, { coll_id }, "=p=p=p=p+p", 1, box.time(), 2, box.time(), 3, box.time(), 4, box.time(), 5, 1)
elseif need_update_old_threshold ~= 0 then
status, t = pcall(box.update, 0, { coll_id }, "=p=p=p+p", 1, box.time(), 2, box.time(), 3, box.time(), 5, 1)
elseif need_update_last_fullsync ~= 0 then
status, t = pcall(box.update, 0, { coll_id }, "=p=p=p+p", 1, box.time(), 2, box.time(), 4, box.time(), 5, 1)
else
status, t = pcall(box.update, 0, { coll_id }, "=p=p+p", 1, box.time(), 2, box.time(), 5, 1)
end
if not status or t == nil then
box.replace(0, coll_id, box.time(), box.time(), box.time(), box.time(), 1)
end
end
function rico_update_failure(coll_id, need_update_last_fullsync)
coll_id = box.unpack('i', coll_id)
need_update_last_fullsync = box.unpack('i', need_update_last_fullsync)
local status, t
if need_update_last_fullsync ~= 0 then
status, t = pcall(box.update, 0, { coll_id }, "=p=p", 1, box.time(), 4, box.time())
else
status, t = pcall(box.update, 0, { coll_id }, "=p", 1, box.time())
end
if not status or t == nil then
box.replace(0, coll_id, box.time(), box.time(), box.time(), box.time(), 0)
end
end
function rico_drop(coll_id)
coll_id = box.unpack('i', coll_id)
local t = box.delete(0, coll_id)
end
|
rico.lua: fix tarantool return empty table behaivour
|
rico.lua: fix tarantool return empty table behaivour
|
Lua
|
bsd-2-clause
|
BHYCHIK/tntlua,mailru/tntlua,spectrec/tntlua,grechkin-pogrebnyakov/tntlua
|
d82319b781e06d69ff0bbfa17239adfe0e31e3d5
|
modules/more.lua
|
modules/more.lua
|
return {
PRIVMSG = {
['^%pmore$'] = function(self, source, destination, module)
local more = self.more[destination]
if more then
self:Msg('privmsg', destination, source, more)
end
end,
['^%pmore%?$'] = function(self, source, destination, module)
local more = self.more[destination]
if more then
self:Msg('privmsg', destination, source, 'There are %s more bytes.', #more)
else
self:Msg('privmsg', destination, source, 'There is no more!')
end
end,
},
}
|
return {
PRIVMSG = {
['^%pmore$'] = function(self, source, destination, module)
if(destination == self.config.nick) then
destination = source.nick
end
local more = self.more[destination]
if more then
self:Msg('privmsg', destination, source, more)
end
end,
['^%pmore%?$'] = function(self, source, destination, module)
if(destination == self.config.nick) then
destination = source.nick
end
local more = self.more[destination]
if more then
self:Msg('privmsg', destination, source, 'There are %s more bytes.', #more)
else
self:Msg('privmsg', destination, source, 'There is no more!')
end
end,
},
}
|
more: fix module to not only work on channels
|
more: fix module to not only work on channels
|
Lua
|
mit
|
torhve/ivar2,torhve/ivar2,torhve/ivar2,haste/ivar2
|
efbd272c402522e582f488c53a81c588ef4a0637
|
levent/socket_util.lua
|
levent/socket_util.lua
|
local socket = require "levent.socket"
local dns = require "levent.dns"
local util = {}
function util.create_connection(host, port, timeout)
local ret, err = dns.resolve(host)
if not ret then
return nil, err
end
local ip = ret[1]
local sock, err = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if not sock then
return nil, err --maybe: Too many open files
end
if timeout then
sock:set_timeout(timeout)
end
local ok, err = sock:connect(ip, port)
if not ok then
sock:close()
return nil, err
end
return sock
end
function util.listen(ip, port)
local sock, err= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if not sock then
return nil, err
end
local ok, err = sock:bind(ip, port)
if not ok then
return nil, err
end
local ok, err = sock:listen()
if not ok then
return nil, err
end
return sock
end
function util.read_full(sock, length)
local reply = ""
while #reply < length do
local ret, err = sock:recv(length - #reply)
if not ret then
return nil, err
end
if #ret == 0 then
return nil -- the peer may closed or shutdown write
end
reply = reply .. ret
end
return reply
end
return util
|
local socket = require "levent.socket"
local dns = require "levent.dns"
local util = {}
function util.create_connection(host, port, timeout)
local ret, err = dns.resolve(host)
if not ret then
return nil, err
end
local ip = ret[1]
local sock, err = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if not sock then
return nil, err --maybe: Too many open files
end
if timeout then
sock:set_timeout(timeout)
end
local ok, err = sock:connect(ip, port)
if not ok then
sock:close()
return nil, err
end
return sock
end
function util.listen(ip, port)
local sock, err= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if not sock then
return nil, err
end
local ok, err = sock:bind(ip, port)
if not ok then
return nil, err
end
local ok, err = sock:listen()
if not ok then
return nil, err
end
return sock
end
function util.read_full(sock, length)
local reply = ""
while #reply < length do
local ret, err = sock:recv(length - #reply)
if not ret then
return nil, err
end
if #ret == 0 then
return reply, true -- EOF
end
reply = reply .. ret
end
return reply
end
return util
|
fix util.read_full need return when EOF
|
fix util.read_full need return when EOF
|
Lua
|
mit
|
xjdrew/levent
|
54a9e666ea804ade7adec51e3fb7435d48e46771
|
src/lluv/pg/utils/bin.lua
|
src/lluv/pg/utils/bin.lua
|
local struct_unpack, struct_pack
if string.pack then -- Lua 5.3
struct_unpack, struct_pack, struct_size = string.unpack, string.pack
elseif not jit then -- Lua 5.1, 5.2
local struct = require "struct"
struct_unpack, struct_pack, struct_size = struct.unpack, struct.pack
else -- LuaJIT
local unpack = unpack or table.unpack
local bit = require "bit"
local is_bit_has_sign = bit.bor(0xFFFFFFFF, 0xFFFFFFFF) ~= 0xFFFFFFFF
local lshift
if is_bit_has_sign then
lshift = function(n, p)
return n * 2^p
end
else
lshift = function(n, p)
return bit.lshift(n, p)
end
end
local function sign1(n)
if n >= 0x80 then
n = -1 - bit.band(0xFF, bit.bnot(n) )
end
return n
end
local function sign2(n)
if n >= 0x8000 then
n = -1 - bit.band(0xFFFF, bit.bnot(n) )
end
return n
end
local function sign4(n)
if n >= 0x80000000 then
n = -1 - bit.band(0xFFFFFFFF, bit.bnot(n) )
end
return n
end
local function read_byte(str, pos)
pos = pos or 1
local a = string.sub(str, pos, pos)
if a then
return string.byte(a), pos + 1
end
return nil, pos
end
local function read_sbyte(str, pos)
local b
b, pos = read_byte(str, pos)
return sign1(b), pos
end
local function read_2_bytes(str, pos)
local a
a, pos = read_byte(str, pos)
return a, read_byte(str, pos)
end
local function read_4_bytes(str, pos)
local a, b
a, b, pos = read_byte(str, pos)
return a, b, read_byte(str, pos)
end
local function read_be_uint2(str, pos)
local a, b
a, b, pos = read_2_bytes(str, pos)
return bit.lshift(a, 8) + b, pos
end
local function read_be_int2(str, pos)
local n
n, pos = read_be_uint2(str, pos)
return sign2(n), pos
end
local function read_le_uint2(str, pos)
local a, b
a, b, pos = read_2_bytes(str, pos)
return a + bit.lshift(b,8), pos
end
local function read_le_int2(str, pos)
local n
n, pos = read_le_uint2(str, pos)
return sign2(n), pos
end
local function read_be_uint4(str, pos)
local a, b
a, pos = read_be_uint2(str, pos)
b, pos = read_be_uint2(str, pos)
return lshift(a, 16) + b, pos
end
local function read_be_int4(str, pos)
local n
n, pos = read_be_uint4(str, pos)
return sign4(n), pos
end
local function read_le_uint4(str, pos)
local a, b
a, pos = read_le_uint2(str, pos)
b, pos = read_le_uint2(str, pos)
return a + lshift(b, 16), pos
end
local function read_le_int4(str, pos)
local n
n, pos = read_le_uint4(str, pos)
return sign4(n), pos
end
local function read_zstr(str, pos)
local e = string.find(str, '\0', pos, true)
if e then
return string.sub(str, pos or 1, e-1), e + 1
end
return nil, pos
end
local function read_chars(str, n, pos)
pos = pos or 1
local s = string.sub(str, pos, pos + n - 1)
return s, pos + #s
end
local function pack_byte(n)
return string.char((bit.band(0xFF, n)))
end
local function pack_sbyte(n)
if n < 0 then
n = bit.bnot(-n) + 1
end
return pack_byte(n)
end
local function pack_le_uint2(n)
n = bit.band(0xFFFF, n)
return string.char(bit.band(n, 0x00FF), bit.rshift(n, 8))
end
local function pack_le_int2(n)
if n < 0 then
n = bit.bnot(-n) + 1
end
return pack_le_uint2(n)
end
local function pack_be_uint2(n)
n = bit.band(0xFFFF, n)
return string.char(bit.rshift(n, 8), bit.band(n, 0x00FF))
end
local function pack_be_int2(n)
if n < 0 then
n = bit.bnot(-n) + 1
end
return pack_be_uint2(n)
end
local function pack_le_uint4(n)
n = bit.band(0xFFFFFFFF, n)
return string.char(
bit.band(0xFF, bit.rshift(n, 0 )),
bit.band(0xFF, bit.rshift(n, 8 )),
bit.band(0xFF, bit.rshift(n, 16)),
bit.band(0xFF, bit.rshift(n, 24))
)
end
local function pack_be_uint4(n)
n = bit.band(0xFFFFFFFF, n)
return string.char(
bit.band(0xFF, bit.rshift(n, 24)),
bit.band(0xFF, bit.rshift(n, 16)),
bit.band(0xFF, bit.rshift(n, 8 )),
bit.band(0xFF, bit.rshift(n, 0 ))
)
end
local function pack_be_int4(n)
if n < 0 then
n = bit.bnot(-n) + 1
end
return pack_be_uint4(n)
end
local function pack_le_int4(n)
if n < 0 then
n = bit.bnot(-n) + 1
end
return pack_le_uint4(n)
end
local function pack_zstr(s)
return s .. '\0'
end
local sunpack do
local unpack_int = {
['<'] = {
I = {
['4'] = read_le_uint4;
['2'] = read_le_uint2;
};
i = {
['4'] = read_le_int4;
['2'] = read_le_int2;
};
};
['>'] = {
I = {
['4'] = read_be_uint4;
['2'] = read_be_uint2;
};
i = {
['4'] = read_be_int4;
['2'] = read_be_int2;
};
};
}
unpack_int['!'] = unpack_int['<']
local unpack_str = {
c = read_chars;
s = function(str, _, pos) return read_zstr (str, pos) end;
b = function(str, _, pos) return read_sbyte(str, pos) end;
B = function(str, _, pos) return read_byte (str, pos) end;
}
local res = {}
sunpack = function(fmt, str, pos)
local i, endian = 0, '>'
for e, p, n in string.gmatch(fmt, "([<>!]?)([iIscbB])(%d?)") do
if e ~= '' then endian = e end
if p ~= '' then
i = i + 1
local fn = unpack_str[p]
if fn then
res[i], pos = fn(str, n, pos)
elseif unpack_int[endian][p] then
fn = unpack_int[endian][p][n]
res[i], pos = fn(str, pos)
else
error('unsupported format: ' .. p)
end
end
end
i = i + 1; res[i] = pos
return unpack(res, 1, i)
end
end
local spack do
local pack_int = {
['<'] = {
I = {
['4'] = pack_le_uint4;
['2'] = pack_le_uint2;
};
i = {
['4'] = pack_le_int4;
['2'] = pack_le_int2;
};
};
['>'] = {
I = {
['4'] = pack_be_uint4;
['2'] = pack_be_uint2;
};
i = {
['4'] = pack_be_int4;
['2'] = pack_be_int2;
};
};
}
pack_int['!'] = pack_int['<']
local pack_str = {
c = function(str, n) return string.sub(str, 1, n) end;
s = pack_zstr;
b = pack_sbyte;
B = pack_byte;
}
local res = {}
spack = function(fmt, ...)
local i, endian = 0, '>'
for e, p, n in string.gmatch(fmt, "([<>!]?)([iIscbB])(%d?)") do
if e ~= '' then endian = e end
if p ~= '' then
i = i + 1
local v = select(i, ...)
local fn = pack_str[p]
if fn then
res[i], pos = fn(v, tonumber(n))
elseif pack_int[endian][p] then
fn = pack_int[endian][p][n]
res[i], pos = fn(v)
else
error('unsupported format: ' .. p)
end
end
end
return table.concat(res, '', 1, i)
end
end
struct_pack, struct_unpack = spack, sunpack
end
return {
pack = struct_pack;
unpack = struct_unpack;
}
|
local struct_unpack, struct_pack
if string.pack then -- Lua 5.3
struct_unpack = function(fmt, ...)
return string.unpack(string.gsub(fmt, 's', 'z'), ...)
end
struct_pack = function(fmt, ...)
return string.pack(string.gsub(fmt, 's', 'z'), ...)
end
elseif not jit then -- Lua 5.1, 5.2
local struct = require "struct"
struct_unpack, struct_pack, struct_size = struct.unpack, struct.pack
else -- LuaJIT
local unpack = unpack or table.unpack
local bit = require "bit"
local is_bit_has_sign = bit.bor(0xFFFFFFFF, 0xFFFFFFFF) ~= 0xFFFFFFFF
local lshift
if is_bit_has_sign then
lshift = function(n, p)
return n * 2^p
end
else
lshift = function(n, p)
return bit.lshift(n, p)
end
end
local function sign1(n)
if n >= 0x80 then
n = -1 - bit.band(0xFF, bit.bnot(n) )
end
return n
end
local function sign2(n)
if n >= 0x8000 then
n = -1 - bit.band(0xFFFF, bit.bnot(n) )
end
return n
end
local function sign4(n)
if n >= 0x80000000 then
n = -1 - bit.band(0xFFFFFFFF, bit.bnot(n) )
end
return n
end
local function read_byte(str, pos)
pos = pos or 1
local a = string.sub(str, pos, pos)
if a then
return string.byte(a), pos + 1
end
return nil, pos
end
local function read_sbyte(str, pos)
local b
b, pos = read_byte(str, pos)
return sign1(b), pos
end
local function read_2_bytes(str, pos)
local a
a, pos = read_byte(str, pos)
return a, read_byte(str, pos)
end
local function read_4_bytes(str, pos)
local a, b
a, b, pos = read_byte(str, pos)
return a, b, read_byte(str, pos)
end
local function read_be_uint2(str, pos)
local a, b
a, b, pos = read_2_bytes(str, pos)
return bit.lshift(a, 8) + b, pos
end
local function read_be_int2(str, pos)
local n
n, pos = read_be_uint2(str, pos)
return sign2(n), pos
end
local function read_le_uint2(str, pos)
local a, b
a, b, pos = read_2_bytes(str, pos)
return a + bit.lshift(b,8), pos
end
local function read_le_int2(str, pos)
local n
n, pos = read_le_uint2(str, pos)
return sign2(n), pos
end
local function read_be_uint4(str, pos)
local a, b
a, pos = read_be_uint2(str, pos)
b, pos = read_be_uint2(str, pos)
return lshift(a, 16) + b, pos
end
local function read_be_int4(str, pos)
local n
n, pos = read_be_uint4(str, pos)
return sign4(n), pos
end
local function read_le_uint4(str, pos)
local a, b
a, pos = read_le_uint2(str, pos)
b, pos = read_le_uint2(str, pos)
return a + lshift(b, 16), pos
end
local function read_le_int4(str, pos)
local n
n, pos = read_le_uint4(str, pos)
return sign4(n), pos
end
local function read_zstr(str, pos)
local e = string.find(str, '\0', pos, true)
if e then
return string.sub(str, pos or 1, e-1), e + 1
end
return nil, pos
end
local function read_chars(str, n, pos)
pos = pos or 1
local s = string.sub(str, pos, pos + n - 1)
return s, pos + #s
end
local function pack_byte(n)
return string.char((bit.band(0xFF, n)))
end
local function pack_sbyte(n)
if n < 0 then
n = bit.bnot(-n) + 1
end
return pack_byte(n)
end
local function pack_le_uint2(n)
n = bit.band(0xFFFF, n)
return string.char(bit.band(n, 0x00FF), bit.rshift(n, 8))
end
local function pack_le_int2(n)
if n < 0 then
n = bit.bnot(-n) + 1
end
return pack_le_uint2(n)
end
local function pack_be_uint2(n)
n = bit.band(0xFFFF, n)
return string.char(bit.rshift(n, 8), bit.band(n, 0x00FF))
end
local function pack_be_int2(n)
if n < 0 then
n = bit.bnot(-n) + 1
end
return pack_be_uint2(n)
end
local function pack_le_uint4(n)
n = bit.band(0xFFFFFFFF, n)
return string.char(
bit.band(0xFF, bit.rshift(n, 0 )),
bit.band(0xFF, bit.rshift(n, 8 )),
bit.band(0xFF, bit.rshift(n, 16)),
bit.band(0xFF, bit.rshift(n, 24))
)
end
local function pack_be_uint4(n)
n = bit.band(0xFFFFFFFF, n)
return string.char(
bit.band(0xFF, bit.rshift(n, 24)),
bit.band(0xFF, bit.rshift(n, 16)),
bit.band(0xFF, bit.rshift(n, 8 )),
bit.band(0xFF, bit.rshift(n, 0 ))
)
end
local function pack_be_int4(n)
if n < 0 then
n = bit.bnot(-n) + 1
end
return pack_be_uint4(n)
end
local function pack_le_int4(n)
if n < 0 then
n = bit.bnot(-n) + 1
end
return pack_le_uint4(n)
end
local function pack_zstr(s)
return s .. '\0'
end
local sunpack do
local unpack_int = {
['<'] = {
I = {
['4'] = read_le_uint4;
['2'] = read_le_uint2;
};
i = {
['4'] = read_le_int4;
['2'] = read_le_int2;
};
};
['>'] = {
I = {
['4'] = read_be_uint4;
['2'] = read_be_uint2;
};
i = {
['4'] = read_be_int4;
['2'] = read_be_int2;
};
};
}
unpack_int['!'] = unpack_int['<']
local unpack_str = {
c = read_chars;
s = function(str, _, pos) return read_zstr (str, pos) end;
b = function(str, _, pos) return read_sbyte(str, pos) end;
B = function(str, _, pos) return read_byte (str, pos) end;
}
local res = {}
sunpack = function(fmt, str, pos)
local i, endian = 0, '>'
for e, p, n in string.gmatch(fmt, "([<>!]?)([iIscbB])(%d?)") do
if e ~= '' then endian = e end
if p ~= '' then
i = i + 1
local fn = unpack_str[p]
if fn then
res[i], pos = fn(str, n, pos)
elseif unpack_int[endian][p] then
fn = unpack_int[endian][p][n]
res[i], pos = fn(str, pos)
else
error('unsupported format: ' .. p)
end
end
end
i = i + 1; res[i] = pos
return unpack(res, 1, i)
end
end
local spack do
local pack_int = {
['<'] = {
I = {
['4'] = pack_le_uint4;
['2'] = pack_le_uint2;
};
i = {
['4'] = pack_le_int4;
['2'] = pack_le_int2;
};
};
['>'] = {
I = {
['4'] = pack_be_uint4;
['2'] = pack_be_uint2;
};
i = {
['4'] = pack_be_int4;
['2'] = pack_be_int2;
};
};
}
pack_int['!'] = pack_int['<']
local pack_str = {
c = function(str, n) return string.sub(str, 1, n) end;
s = pack_zstr;
b = pack_sbyte;
B = pack_byte;
}
local res = {}
spack = function(fmt, ...)
local i, endian = 0, '>'
for e, p, n in string.gmatch(fmt, "([<>!]?)([iIscbB])(%d?)") do
if e ~= '' then endian = e end
if p ~= '' then
i = i + 1
local v = select(i, ...)
local fn = pack_str[p]
if fn then
res[i], pos = fn(v, tonumber(n))
elseif pack_int[endian][p] then
fn = pack_int[endian][p][n]
res[i], pos = fn(v)
else
error('unsupported format: ' .. p)
end
end
end
return table.concat(res, '', 1, i)
end
end
struct_pack, struct_unpack = spack, sunpack
end
return {
pack = struct_pack;
unpack = struct_unpack;
}
|
Fix. sting pattern for Lua 5.3
|
Fix. sting pattern for Lua 5.3
|
Lua
|
mit
|
moteus/lua-lluv-pg
|
23f3b66e31e2d84a8460e33412f0f1e61d13b95a
|
druid/spell/id_01_analyze_plant.lua
|
druid/spell/id_01_analyze_plant.lua
|
--ds_druidspell_01.lua / 1. Rune des Lehrlings
--Druidensystem
--Falk
require("base.common")
require("druid.base.alchemy")
require("druid.base.plants")
module("druid.spell.id_01_analyze_plant", package.seeall, package.seeall(druid.base.alchemy), package.seeall(druid.base.plants))
-- INSERT INTO spells VALUES (2^0,3,'druid.spell.id_01_analyze_plant');
function CastMagic(Caster,counter,param,ltstate)
--Caster:inform("debug #01.1")
end
function CastMagicOnCharacter(Caster,TargetCharacter,counter,param,ltstate)
--Caster:inform("debug #01.2")
end
function CastMagicOnField(Caster,Targetpos,counter,param,ltstate)
--Caster:inform("debug #01.3")
end
function CastMagicOnItem(Caster,TargetItem,counter,param)
--Caster:inform("debug #01.4")
--Analyse einer Pflanze
if (IsThatAPlant(TargetItem) == true) then
language = Caster:getPlayerLanguage()
pflanzenname = world:getItemName(TargetItem.id,language)
-- Manche Pflanzen haben Doppelfunktionen und bekommen eine neue ID
if TargetItem.data >9000 and TargetItem.data < 9017 then
dummy = TargetItem.data
for i=1,16 do
if dummyIDList[i] == dummy then
if language == 0 then
pflanzenname = dummyNameListDE[i]
else
pflanzenname = dummyNameListEN[i]
end
end
end
else
dummy =TargetItem.id
end
plusWertPos,minusWertPos = SplitPlantData(dummy)
textDE= pflanzenname.." hat Einfluss auf den Gehalt an "..wirkstoff[plusWertPos].." und "..wirkstoff[minusWertPos].." eines Trankes"
textEN= pflanzenname.." exert influence to the assay of "..wirkstoff[plusWertPos].." and "..wirkstoff[minusWertPos].." of a potion"
if Caster:getPlayerLanguage() == 0 then
Caster:inform("#b|0|0|"..textDE)
else
Caster:inform("#b|0|0|"..textEN)
end
Caster:learn(6,"vegetabilistia",3,100)
else
base.common.InformNLS(Caster,
"Das ist keine Heilpflanze","This is not a medicinal plant")
end
end
|
--ds_druidspell_01.lua / 1. Rune des Lehrlings
--Druidensystem
--Falk
require("base.common")
require("druid.base.alchemy")
require("druid.base.plants")
module("druid.spell.id_01_analyze_plant", package.seeall)
-- INSERT INTO spells VALUES (2^0,3,'druid.spell.id_01_analyze_plant');
function CastMagic(Caster,counter,param,ltstate)
--Caster:inform("debug #01.1")
end
function CastMagicOnCharacter(Caster,TargetCharacter,counter,param,ltstate)
--Caster:inform("debug #01.2")
end
function CastMagicOnField(Caster,Targetpos,counter,param,ltstate)
--Caster:inform("debug #01.3")
end
function CastMagicOnItem(Caster,TargetItem,counter,param)
--Caster:inform("debug #01.4")
--Analyse einer Pflanze
if (IsThatAPlant(TargetItem) == true) then
language = Caster:getPlayerLanguage()
pflanzenname = world:getItemName(TargetItem.id,language)
-- Manche Pflanzen haben Doppelfunktionen und bekommen eine neue ID
if TargetItem.data >9000 and TargetItem.data < 9017 then
dummy = TargetItem.data
for i=1,16 do
if dummyIDList[i] == dummy then
if language == 0 then
pflanzenname = dummyNameListDE[i]
else
pflanzenname = dummyNameListEN[i]
end
end
end
else
dummy =TargetItem.id
end
plusWertPos,minusWertPos = SplitPlantData(dummy)
textDE= pflanzenname.." hat Einfluss auf den Gehalt an "..wirkstoff[plusWertPos].." und "..wirkstoff[minusWertPos].." eines Trankes"
textEN= pflanzenname.." exert influence to the assay of "..wirkstoff[plusWertPos].." and "..wirkstoff[minusWertPos].." of a potion"
if Caster:getPlayerLanguage() == 0 then
Caster:inform("#b|0|0|"..textDE)
else
Caster:inform("#b|0|0|"..textEN)
end
Caster:learn(6,"vegetabilistia",3,100)
else
base.common.InformNLS(Caster,
"Das ist keine Heilpflanze","This is not a medicinal plant")
end
end
|
minor fixes
|
minor fixes
|
Lua
|
agpl-3.0
|
KayMD/Illarion-Content,Illarion-eV/Illarion-Content,Baylamon/Illarion-Content,LaFamiglia/Illarion-Content,vilarion/Illarion-Content
|
80b41a8a108db66109d0e86b19c03f69b2abbca7
|
test_suite/main.lua
|
test_suite/main.lua
|
# testing special comment on first line
print ("testing lua.c options")
assert(os.execute() ~= 0) -- machine has a system command
prog = os.tmpname()
otherprog = os.tmpname()
out = os.tmpname()
do
local i = 0
while arg[i] do i=i-1 end
progname = '"'..arg[i+1]..'"'
end
print(progname)
local prepfile = function (s, p)
p = p or prog
io.output(p)
io.write(s)
assert(io.close())
end
function checkout (s)
io.input(out)
local t = io.read("*a")
io.input():close()
assert(os.remove(out))
if s ~= t then print(string.format("'%s' - '%s'\n", s, t)) end
assert(s == t)
return t
end
function auxrun (...)
local s = string.format(...)
s = string.gsub(s, "lua", progname, 1)
return os.execute(s)
end
function RUN (...)
assert(auxrun(...) == 0)
end
function NoRun (...)
print("\n(the next error is expected by the test)")
assert(auxrun(...) ~= 0)
end
-- test 2 files
prepfile("print(1); a=2")
prepfile("print(a)", otherprog)
RUN("lua -l %s -l%s -lstring -l io %s > %s", prog, otherprog, otherprog, out)
checkout("1\n2\n2\n")
local a = [[
assert(table.getn(arg) == 3 and arg[1] == 'a' and
arg[2] == 'b' and arg[3] == 'c')
assert(arg[-1] == '--' and arg[-2] == "-e " and arg[-3] == %s)
assert(arg[4] == nil and arg[-4] == nil)
local a, b, c = ...
assert(... == 'a' and a == 'a' and b == 'b' and c == 'c')
]]
a = string.format(a, string.gsub(progname, '\\', '\\\\'))
prepfile(a)
RUN('lua "-e " -- %s a b c', prog)
prepfile"assert(arg==nil)"
prepfile("assert(arg)", otherprog)
RUN("lua -l%s - < %s", prog, otherprog)
prepfile""
RUN("lua - < %s > %s", prog, out)
checkout("")
-- test many arguments
prepfile[[print(({...})[30])]]
RUN("lua %s %s > %s", prog, string.rep(" a", 30), out)
checkout("a\n")
RUN([[lua "-eprint(1)" -ea=3 -e "print(a)" > %s]], out)
checkout("1\n3\n")
prepfile[[
print(
1, a
)
]]
RUN("lua - < %s > %s", prog, out)
checkout("1\tnil\n")
prepfile[[
= (6*2-6) -- ===
a
= 10
print(a)
= a]]
RUN([[lua -e"_PROMPT='' _PROMPT2=''" -i < %s > %s]], prog, out)
checkout("6\n10\n10\n\n")
prepfile("a = [[b\nc\nd\ne]]\n=a")
print(prog)
RUN([[lua -e"_PROMPT='' _PROMPT2=''" -i < %s > %s]], prog, out)
checkout("b\nc\nd\ne\n\n")
prompt = "alo"
prepfile[[ --
a = 2
]]
RUN([[lua "-e_PROMPT='%s'" -i < %s > %s]], prompt, prog, out)
checkout(string.rep(prompt, 3).."\n")
s = [=[ --
function f ( x )
local a = [[
xuxu
]]
local b = "\
xuxu\n"
if x == 11 then return 1 , 2 end --[[ test multiple returns ]]
return x + 1
--\\
end
=( f( 10 ) )
assert( a == b )
=f( 11 ) ]=]
s = string.gsub(s, ' ', '\n\n')
prepfile(s)
RUN([[lua -e"_PROMPT='' _PROMPT2=''" -i < %s > %s]], prog, out)
checkout("11\n1\t2\n\n")
prepfile[[#comment in 1st line without \n at the end]]
RUN("lua %s", prog)
prepfile("#comment with a binary file\n"..string.dump(loadstring("print(1)")))
RUN("lua %s > %s", prog, out)
checkout("1\n")
prepfile("#comment with a binary file\r\n"..string.dump(loadstring("print(1)")))
RUN("lua %s > %s", prog, out)
checkout("1\n")
-- close Lua with an open file
prepfile(string.format([[io.output(%q); io.write('alo')]], out))
RUN("lua %s", prog)
checkout('alo')
assert(os.remove(prog))
assert(os.remove(otherprog))
assert(not os.remove(out))
RUN("lua -v")
NoRun("lua -h")
NoRun("lua -e")
NoRun("lua -e a")
NoRun("lua -f")
print("OK")
|
# testing special comment on first line
print ("testing lua.c options")
assert(os.execute() ~= 0) -- machine has a system command
prog = os.tmpname()
otherprog = os.tmpname()
out = os.tmpname()
do
local i = 0
while arg[i] do i=i-1 end
progname = '"'..arg[i+1]..'"'
end
print(progname)
local prepfile = function (s, p)
p = p or prog
io.output(p)
io.write(s)
assert(io.close())
end
function checkout (s)
io.input(out)
local t = io.read("*a")
io.input():close()
assert(os.remove(out))
if s ~= t then print(string.format("'%s' - '%s'\n", s, t)) end
assert(s == t)
return t
end
function auxrun (...)
local s = string.format(...)
s = string.gsub(s, "lua", progname, 1)
return os.execute(s)
end
function RUN (...)
assert(auxrun(...) == 0)
end
function NoRun (...)
print("\n(the next error is expected by the test)")
assert(auxrun(...) ~= 0)
end
-- test 2 files
prepfile("print(1); a=2")
prepfile("print(a)", otherprog)
RUN("lua -l %s -l%s -lstring -l io %s > %s", prog, otherprog, otherprog, out)
checkout("1\n2\n2\n")
local a = [[
assert(table.getn(arg) == 3 and arg[1] == 'a' and
arg[2] == 'b' and arg[3] == 'c')
assert(arg[-1] == '--' and arg[-2] == "-e " and arg[-3] == %s)
assert(arg[4] == nil and arg[-4] == nil)
local a, b, c = ...
assert(... == 'a' and a == 'a' and b == 'b' and c == 'c')
]]
a = string.format(a, string.gsub(progname, '\\', '\\\\'))
prepfile(a)
RUN('lua "-e " -- %s a b c', prog)
prepfile"assert(arg==nil)"
prepfile("assert(arg)", otherprog)
print('Skipping test that fails due to ungetc emulation bug');
--RUN("lua -l%s - < %s", prog, otherprog)
prepfile""
print('Skipping test that fails due to ungetc emulation bug');
--RUN("lua - < %s > %s", prog, out)
--checkout("")
-- test many arguments
prepfile[[print(({...})[30])]]
RUN("lua %s %s > %s", prog, string.rep(" a", 30), out)
checkout("a\n")
RUN([[lua "-eprint(1)" -ea=3 -e "print(a)" > %s]], out)
checkout("1\n3\n")
prepfile[[
print(
1, a
)
]]
print('Skipping test that fails due to ungetc emulation bug');
--RUN("lua - < %s > %s", prog, out)
--checkout("1\tnil\n")
prepfile[[
= (6*2-6) -- ===
a
= 10
print(a)
= a]]
print('Skipping test that fails due to interactive-mode differences');
--RUN([[lua -e"_PROMPT='' _PROMPT2=''" -i < %s > %s]], prog, out)
--checkout("6\n10\n10\n\n")
prepfile("a = [[b\nc\nd\ne]]\n=a")
print(prog)
print('Skipping test that fails due to interactive-mode differences');
--RUN([[lua -e"_PROMPT='' _PROMPT2=''" -i < %s > %s]], prog, out)
--checkout("b\nc\nd\ne\n\n")
prompt = "alo"
prepfile[[ --
a = 2
]]
print('Skipping test that fails due to interactive-mode differences');
--RUN([[lua "-e_PROMPT='%s'" -i < %s > %s]], prompt, prog, out)
--checkout(string.rep(prompt, 3).."\n")
s = [=[ --
function f ( x )
local a = [[
xuxu
]]
local b = "\
xuxu\n"
if x == 11 then return 1 , 2 end --[[ test multiple returns ]]
return x + 1
--\\
end
=( f( 10 ) )
assert( a == b )
=f( 11 ) ]=]
s = string.gsub(s, ' ', '\n\n')
prepfile(s)
print('Skipping test that fails due to interactive-mode differences');
--RUN([[lua -e"_PROMPT='' _PROMPT2=''" -i < %s > %s]], prog, out)
--checkout("11\n1\t2\n\n")
print('Skipping test that fails due to ungetc emulation bug');
--prepfile[[#comment in 1st line without \n at the end]]
--RUN("lua %s", prog)
prepfile("#comment with a binary file\n"..string.dump(loadstring("print(1)")))
RUN("lua %s > %s", prog, out)
checkout("1\n")
prepfile("#comment with a binary file\r\n"..string.dump(loadstring("print(1)")))
RUN("lua %s > %s", prog, out)
checkout("1\n")
-- close Lua with an open file
print('Skipping test that fails due to io.write not working correctly');
--prepfile(string.format([[io.output(%q); io.write('alo')]], out))
--RUN("lua %s", prog)
--checkout('alo')
assert(os.remove(prog))
assert(os.remove(otherprog))
assert(not os.remove(out))
RUN("lua -v")
NoRun("lua -h")
NoRun("lua -e")
NoRun("lua -e a")
NoRun("lua -f")
print("OK")
|
Disable tests in main.lua that don't work and are unlikely to work soon
|
Disable tests in main.lua that don't work and are unlikely to work soon
Three types of errors:
* Incompatibilities between slua's interactive mode and original Lua's
* Bugs arising from slua's ungetc() emulation which will be difficult to
fix quickly
* Bugs arising from slua's incomplete io.write implementation
|
Lua
|
mit
|
Stevie-O/SharpLua,Stevie-O/SharpLua,Stevie-O/SharpLua
|
b925649a2c93cae5f26090feee49aeaf62bccf47
|
units.lua
|
units.lua
|
local lua_sources = {
"lua/src/lapi.c", "lua/src/lauxlib.c", "lua/src/lbaselib.c", "lua/src/lcode.c",
"lua/src/ldblib.c", "lua/src/ldebug.c", "lua/src/ldo.c", "lua/src/ldump.c",
"lua/src/lfunc.c", "lua/src/lgc.c", "lua/src/linit.c", "lua/src/liolib.c",
"lua/src/llex.c", "lua/src/lmathlib.c", "lua/src/lmem.c", "lua/src/loadlib.c",
"lua/src/lobject.c", "lua/src/lopcodes.c", "lua/src/loslib.c", "lua/src/lparser.c",
"lua/src/lstate.c", "lua/src/lstring.c", "lua/src/lstrlib.c", "lua/src/ltable.c",
"lua/src/ltablib.c", "lua/src/ltm.c", "lua/src/lundump.c", "lua/src/lvm.c",
"lua/src/lzio.c",
}
StaticLibrary {
Name = "base_lua_host",
Pass = "CodeGen",
Sources = lua_sources,
SubConfig = "host",
}
StaticLibrary {
Name = "base_lua",
Pass = "CodeGen",
Sources = lua_sources,
SubConfig = "target",
}
Program {
Name = "gen_lua_data",
Pass = "CodeGen",
Target = "$(GEN_LUA_DATA)",
Config = "*-*-*-standalone",
Sources = { "src/gen_lua_data.c" },
SubConfig = "host",
}
Program {
Name = "luac",
Pass = "CodeGen",
Target = "$(LUAC)",
Config = "*-*-*-standalone",
Depends = { "base_lua_host" },
Sources = {
"lua/src/luac.c",
"lua/src/print.c",
},
SubConfig = "host",
Libs = { "m", "pthread"; Config = { "linux-*-*", "freebsd-*-*" } },
}
Always "gen_lua_data"
Always "luac"
Program {
Name = "tundra",
Defines = { "TD_STANDALONE"; Config = "*-*-*-standalone" },
Depends = { "base_lua", "luac", "gen_lua_data" },
Libs = {
{ "kernel32.lib", "advapi32.lib"; Config = { "win32-*-*", "win64-*-*" } },
{ "m", "pthread"; Config = { "linux-*-*", "freebsd-*-*" } },
},
Sources = {
"src/ancestors.c",
"src/build.c",
"src/build_setup.c",
"src/bin_alloc.c",
"src/clean.c",
"src/cpp_scanner.c",
"src/debug.c",
"src/engine.c",
"src/exec_unix.c",
"src/exec_win32.c",
"src/files.c",
"src/luafs.c",
"src/md5.c",
"src/scanner.c",
"src/tundra.c",
"src/util.c",
"src/portable.c",
"src/relcache.c",
"src/luaprof.c",
"src/tty.c",
{
EmbedLuaSources {
OutputFile = "data_files.c", Dirs = { "lua/etc", "scripts" }
}
; Config = "*-*-*-standalone"
}
}
}
Default "tundra"
|
local lua_sources = {
"lua/src/lapi.c", "lua/src/lauxlib.c", "lua/src/lbaselib.c", "lua/src/lcode.c",
"lua/src/ldblib.c", "lua/src/ldebug.c", "lua/src/ldo.c", "lua/src/ldump.c",
"lua/src/lfunc.c", "lua/src/lgc.c", "lua/src/linit.c", "lua/src/liolib.c",
"lua/src/llex.c", "lua/src/lmathlib.c", "lua/src/lmem.c", "lua/src/loadlib.c",
"lua/src/lobject.c", "lua/src/lopcodes.c", "lua/src/loslib.c", "lua/src/lparser.c",
"lua/src/lstate.c", "lua/src/lstring.c", "lua/src/lstrlib.c", "lua/src/ltable.c",
"lua/src/ltablib.c", "lua/src/ltm.c", "lua/src/lundump.c", "lua/src/lvm.c",
"lua/src/lzio.c",
}
StaticLibrary {
Name = "base_lua_host",
Pass = "CodeGen",
Sources = lua_sources,
SubConfig = "host",
}
StaticLibrary {
Name = "base_lua",
Pass = "CodeGen",
Sources = lua_sources,
SubConfig = "target",
}
Program {
Name = "gen_lua_data",
Pass = "CodeGen",
Target = "$(GEN_LUA_DATA)",
Config = "*-*-*-standalone",
Sources = { "src/gen_lua_data.c" },
SubConfig = "host",
}
Program {
Name = "luac",
Pass = "CodeGen",
Target = "$(LUAC)",
Config = "*-*-*-standalone",
Depends = { "base_lua_host" },
Sources = {
"lua/src/luac.c",
"lua/src/print.c",
},
SubConfig = "host",
Libs = { "m", "pthread"; Config = { "linux-*-*", "freebsd-*-*" } },
}
Always "gen_lua_data"
Always "luac"
Program {
Name = "tundra",
Defines = { "TD_STANDALONE"; Config = "*-*-*-standalone" },
Depends = { "base_lua", "luac", "gen_lua_data" },
Libs = {
{ "kernel32.lib", "advapi32.lib"; Config = { "win32-*-*", "win64-*-*" } },
{ "m", "pthread"; Config = { "linux-*-*", "freebsd-*-*" } },
},
Sources = {
"src/ancestors.c",
"src/build.c",
"src/build_setup.c",
"src/bin_alloc.c",
"src/clean.c",
"src/cpp_scanner.c",
"src/debug.c",
"src/engine.c",
"src/files.c",
"src/luafs.c",
"src/md5.c",
"src/scanner.c",
"src/tundra.c",
"src/util.c",
"src/portable.c",
"src/relcache.c",
"src/luaprof.c",
{
"src/tty.c",
"src/exec_unix.c"
;Config = { "linux-*-*", "freebsd-*-*", "macosx-*-*" }
},
{ "src/exec_win32.c"; Config = { "win32-*-*", "win64-*-*" } },
{
EmbedLuaSources {
OutputFile = "data_files.c", Dirs = { "lua/etc", "scripts" }
}
; Config = "*-*-*-standalone"
}
}
}
Default "tundra"
|
Fixed tty.c was built on win32.
|
Fixed tty.c was built on win32.
|
Lua
|
mit
|
deplinenoise/tundra,bmharper/tundra,bmharper/tundra,bmharper/tundra,deplinenoise/tundra,bmharper/tundra,deplinenoise/tundra
|
c8353fe598ed3c912158fb7e3b21766b0edc3785
|
gin/core/router.lua
|
gin/core/router.lua
|
package.path = './app/controllers/?.lua;' .. package.path
-- dep
local json = require 'cjson'
-- gin
local Gin = require 'gin.core.gin'
local Controller = require 'gin.core.controller'
local Request = require 'gin.core.request'
local Response = require 'gin.core.response'
local Error = require 'gin.core.error'
-- app
local Routes = require 'config.routes'
local Application = require 'config.application'
-- perf
local error = error
local jencode = json.encode
local pairs = pairs
local pcall = pcall
local require = require
local setmetatable = setmetatable
local smatch = string.match
local function tappend(t, v) t[#t+1] = v end
-- init Router and set routes
local Router = {}
-- response version header
local response_version_header = 'gin/'.. Gin.version
-- accept header for application
local accept_header_matcher = "^application/vnd." .. Application.name .. ".v(%d+)(.*)+json$"
local function create_request(ngx)
local ok, request_or_error = pcall(function() return Request.new(ngx) end)
if ok == false then
-- parsing errors
local err = Error.new(request_or_error.code, request_or_error.custom_attrs)
response = Response.new({ status = err.status, body = err.body })
Router.respond(ngx, response)
return false
end
return request_or_error
end
-- main handler function, called from nginx
function Router.handler(ngx)
-- add headers
ngx.header.content_type = 'application/json'
ngx.header["X-Framework"] = response_version_header;
-- create request object
local request = create_request(ngx)
if request == false then return end
-- get routes
local ok, controller_name_or_error, action, params, request = pcall(function() return Router.match(request) end)
local response
if ok == false then
-- match returned an error (for instance a 412 for no header match)
local err = Error.new(controller_name_or_error.code, controller_name_or_error.custom_attrs)
response = Response.new({ status = err.status, body = err.body })
Router.respond(ngx, response)
elseif controller_name_or_error then
-- matching routes found
response = Router.call_controller(request, controller_name_or_error, action, params)
Router.respond(ngx, response)
else
-- no matching routes found
ngx.exit(ngx.HTTP_NOT_FOUND)
end
end
-- match request to routes
function Router.match(request)
local uri = request.uri
local method = request.method
-- match version based on headers
if request.headers['accept'] == nil then error({ code = 100 }) end
local major_version, rest_version = smatch(request.headers['accept'], accept_header_matcher)
if major_version == nil then error({ code = 101 }) end
local routes_dispatchers = Routes.dispatchers[tonumber(major_version)]
if routes_dispatchers == nil then error({ code = 102 }) end
-- loop dispatchers to find route
for i = 1, #routes_dispatchers do
local dispatcher = routes_dispatchers[i]
if dispatcher[method] then -- avoid matching if method is not defined in dispatcher
local match = { smatch(uri, dispatcher.pattern) }
if #match > 0 then
local params = {}
for j = 1, #match do
if dispatcher[method].params[j] then
params[dispatcher[method].params[j]] = match[j]
else
tappend(params, match[j])
end
end
-- set version on request
request.api_version = major_version .. rest_version
-- return
return major_version .. '/' .. dispatcher[method].controller, dispatcher[method].action, params, request
end
end
end
end
-- call the controller
function Router.call_controller(request, controller_name, action, params)
-- load matched controller and set metatable to new instance of controller
local matched_controller = require(controller_name)
local controller_instance = Controller.new(request, params)
setmetatable(matched_controller, { __index = controller_instance })
-- call action
local ok, status_or_error, body, headers = pcall(function() return matched_controller[action](matched_controller) end)
local response
if ok then
-- successful
response = Response.new({ status = status_or_error, headers = headers, body = body })
else
-- controller raised an error
local ok, err = pcall(function() return Error.new(status_or_error.code, status_or_error.custom_attrs) end)
if ok then
-- API error
response = Response.new({ status = err.status, headers = err.headers, body = err.body })
else
-- another error, throw
error(status_or_error)
end
end
return response
end
function Router.respond(ngx, response)
-- set status
ngx.status = response.status
-- set headers
for k, v in pairs(response.headers) do
ngx.header[k] = v
end
-- encode body
local json_body = jencode(response.body)
-- ensure content-length is set
ngx.header["Content-Length"] = ngx.header["Content-Length"] or ngx.header["content-length"] or json_body:len()
-- print body
ngx.print(json_body)
end
return Router
|
package.path = './app/controllers/?.lua;' .. package.path
-- dep
local json = require 'cjson'
-- gin
local Gin = require 'gin.core.gin'
local Controller = require 'gin.core.controller'
local Request = require 'gin.core.request'
local Response = require 'gin.core.response'
local Error = require 'gin.core.error'
-- app
local Routes = require 'config.routes'
local Application = require 'config.application'
-- perf
local error = error
local jencode = json.encode
local pairs = pairs
local pcall = pcall
local require = require
local setmetatable = setmetatable
local smatch = string.match
local function tappend(t, v) t[#t+1] = v end
-- init Router and set routes
local Router = {}
-- response version header
local response_version_header = 'gin/'.. Gin.version
-- accept header for application
local accept_header_matcher = "^application/vnd." .. Application.name .. ".v(%d+)(.*)+json$"
local function create_request(ngx)
local ok, request_or_error = pcall(function() return Request.new(ngx) end)
if ok == false then
-- parsing errors
local err = Error.new(request_or_error.code, request_or_error.custom_attrs)
response = Response.new({ status = err.status, body = err.body })
Router.respond(ngx, response)
return false
end
return request_or_error
end
-- main handler function, called from nginx
function Router.handler(ngx)
-- add headers
ngx.header.content_type = 'application/json'
ngx.header["X-Framework"] = response_version_header;
-- create request object
local request = create_request(ngx)
if request == false then return end
-- get routes
local ok, controller_name_or_error, action, params, request = pcall(function() return Router.match(request) end)
local response
if ok == false then
-- match returned an error (for instance a 412 for no header match)
local err = Error.new(controller_name_or_error.code, controller_name_or_error.custom_attrs)
response = Response.new({ status = err.status, body = err.body })
Router.respond(ngx, response)
elseif controller_name_or_error then
-- matching routes found
response = Router.call_controller(request, controller_name_or_error, action, params)
Router.respond(ngx, response)
else
-- no matching routes found
ngx.exit(ngx.HTTP_NOT_FOUND)
end
end
-- match request to routes
function Router.match(request)
local uri = request.uri
local method = request.method
-- match version based on headers
if request.headers['accept'] == nil then error({ code = 100 }) end
local major_version, rest_version = smatch(request.headers['accept'], accept_header_matcher)
if major_version == nil then error({ code = 101 }) end
local routes_dispatchers = Routes.dispatchers[tonumber(major_version)]
if routes_dispatchers == nil then error({ code = 102 }) end
-- loop dispatchers to find route
for i = 1, #routes_dispatchers do
local dispatcher = routes_dispatchers[i]
if dispatcher[method] then -- avoid matching if method is not defined in dispatcher
local match = { smatch(uri, dispatcher.pattern) }
if #match > 0 then
local params = {}
for j = 1, #match do
if dispatcher[method].params[j] then
params[dispatcher[method].params[j]] = match[j]
else
tappend(params, match[j])
end
end
-- set version on request
request.api_version = major_version .. rest_version
-- return
return major_version .. '/' .. dispatcher[method].controller, dispatcher[method].action, params, request
end
end
end
end
-- call the controller
function Router.call_controller(request, controller_name, action, params)
-- load matched controller and set metatable to new instance of controller
local matched_controller = require(controller_name)
setmetatable(matched_controller, Controller)
local controller_instance = Controller.new(request, params)
setmetatable(controller_instance, {__index = matched_controller})
-- call action
local ok, status_or_error, body, headers = pcall(function() return matched_controller[action](controller_instance) end)
local response
if ok then
-- successful
response = Response.new({ status = status_or_error, headers = headers, body = body })
else
-- controller raised an error
local ok, err = pcall(function() return Error.new(status_or_error.code, status_or_error.custom_attrs) end)
if ok then
-- API error
response = Response.new({ status = err.status, headers = err.headers, body = err.body })
else
-- another error, throw
error(status_or_error)
end
end
return response
end
function Router.respond(ngx, response)
-- set status
ngx.status = response.status
-- set headers
for k, v in pairs(response.headers) do
ngx.header[k] = v
end
-- encode body
local json_body = jencode(response.body)
-- ensure content-length is set
ngx.header["Content-Length"] = ngx.header["Content-Length"] or ngx.header["content-length"] or json_body:len()
-- print body
ngx.print(json_body)
end
return Router
|
Fix race condition when using code cache.
|
Fix race condition when using code cache.
Based on #16 and fix by @istr in https://github.com/ppolv/gin/commit/04b0fb6cadb0a33e1685d3a86308d95b52cf46c8
|
Lua
|
mit
|
ostinelli/gin,istr/gin
|
4733e9d95cbeb4a8840f063fe86f0b4c79dc4a3e
|
lua/encoders/opentsdb_raw.lua
|
lua/encoders/opentsdb_raw.lua
|
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
--[=[
Extracts data from message fields and generates JSON suitable for use with
OpenTSDB's TCP input.
Config:
- metric_field (string, required, default "Metric")
Field name the metric name is stored in
- value_field (string, required, default "Value")
Field name the metric value is stored in
- fields_to_tags (boolean, optional, default false)
Converts any dynamic Fields to OpenTSDB k=v tags, excluding those
defined as metric_field or value_field
- tag_prefix (string, optional, default "")
Only convert Fields to OpenTSDB k=v tags if they match the tag_prefix.
(tag_prefix is stripped from the tag name)
- ts_from_message (boolean, optional, default false)
Use the Timestamp field (otherwise "now")
- add_hostname_if_missing (boolean, optional, default false)
If no 'host' tag has been seen, append one with the value of the
Hostname field. Deprecated in favour of using the 'fieldfix' filter.
*Example Heka Configuration*
.. code-block:: ini
[OpentsdbEncoder]
type = "SandboxEncoder"
filename = "lua_encoders/opentsdb_raw.lua"
[opentsdb]
type = "TcpOutput"
message_matcher = "Type == 'opentsdb'"
address = "my.tsdb.server:4242"
encoder = "OpentsdbEncoder"
*Example Output*
.. code-block:: bash
put my.wonderful.metric 1412790960 124255 foo=bar fish=baz
--]=]
require "string"
require "os"
local metric_field = read_config("metric_field") or error("metric_field must be specified")
local value_field = read_config("value_field") or error("value_field must be specified")
local fields_to_tags = read_config("fields_to_tags")
local tag_prefix = read_config("tag_prefix")
local ts_from_message = read_config("ts_from_message")
local add_hostname = read_config("add_hostname_if_missing")
local tag_prefix_length = 0
if tag_prefix then
tag_prefix_length = #tag_prefix
end
function process_message()
local metric = read_message("Fields["..metric_field.."]")
local value = read_message("Fields["..value_field.."]")
if not metric or not value then return -1 end
local ts
if ts_from_message then
ts = read_message("Timestamp") / 1e9
else
ts = os.time()
end
add_to_payload(string.format("put %s %s %s", metric, ts, value))
local seen_hosttag = false
-- add tags from dynamic fields
if fields_to_tags then
while true do
local typ, name, value, representation, count = read_next_field()
if not typ then break end
-- don't add the metric/value fields as tags
if name ~= metric_field or name ~= value_field then
if tag_prefix_length > 0 then
-- only add fields that match the tagname_prefix
if name:sub(1, tag_prefix_length) == tag_prefix then
name = name:sub(tag_prefix_length+1)
add_to_payload(string.format(" %s=%s", name, value))
end
else
add_to_payload(string.format(" %s=%s", name, value))
end
if name == "host" then seen_hosttag = true end
end
end
end
if not seen_hosttag and add_hostname then
add_to_payload(string.format(" host=%s", read_message("Hostname")))
end
add_to_payload("\n")
inject_payload()
return 0
end
|
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
--[=[
Extracts data from message fields and generates JSON suitable for use with
OpenTSDB's TCP input.
Config:
- metric_field (string, required, default "Metric")
Field name the metric name is stored in
- value_field (string, required, default "Value")
Field name the metric value is stored in
- fields_to_tags (boolean, optional, default false)
Converts any dynamic Fields to OpenTSDB k=v tags, excluding those
defined as metric_field or value_field
- tag_prefix (string, optional, default "")
Only convert Fields to OpenTSDB k=v tags if they match the tag_prefix.
(tag_prefix is stripped from the tag name)
- ts_from_message (boolean, optional, default false)
Use the Timestamp field (otherwise "now")
- add_hostname_if_missing (boolean, optional, default false)
If no 'host' tag has been seen, append one with the value of the
Hostname field. Deprecated in favour of using the 'fieldfix' filter.
*Example Heka Configuration*
.. code-block:: ini
[OpentsdbEncoder]
type = "SandboxEncoder"
filename = "lua_encoders/opentsdb_raw.lua"
[opentsdb]
type = "TcpOutput"
message_matcher = "Type == 'opentsdb'"
address = "my.tsdb.server:4242"
encoder = "OpentsdbEncoder"
*Example Output*
.. code-block:: bash
put my.wonderful.metric 1412790960 124255 foo=bar fish=baz
--]=]
require "string"
require "os"
local metric_field = read_config("metric_field") or "Metric"
local value_field = read_config("value_field") or "Value"
local fields_to_tags = read_config("fields_to_tags")
local tag_prefix = read_config("tag_prefix")
local ts_from_message = read_config("ts_from_message")
local add_hostname = read_config("add_hostname_if_missing")
local tag_prefix_length = 0
if tag_prefix then
tag_prefix_length = #tag_prefix
end
function process_message()
local metric = read_message("Fields["..metric_field.."]")
local value = read_message("Fields["..value_field.."]")
if not metric or not value then return -1 end
local ts
if ts_from_message then
ts = read_message("Timestamp") / 1e9
else
ts = os.time()
end
add_to_payload(string.format("put %s %s %s", metric, ts, value))
local seen_hosttag = false
-- add tags from dynamic fields
if fields_to_tags then
while true do
local typ, name, value, representation, count = read_next_field()
if not typ then break end
-- don't add the metric/value fields as tags
if name ~= metric_field and name ~= value_field then
if tag_prefix_length > 0 then
-- only add fields that match the tagname_prefix
if name:sub(1, tag_prefix_length) == tag_prefix then
name = name:sub(tag_prefix_length+1)
add_to_payload(string.format(" %s=%s", name, value))
end
else
add_to_payload(string.format(" %s=%s", name, value))
end
if name == "host" then seen_hosttag = true end
end
end
end
if not seen_hosttag and add_hostname then
add_to_payload(string.format(" host=%s", read_message("Hostname")))
end
add_to_payload("\n")
inject_payload()
return 0
end
|
Fix silly logic bug
|
Fix silly logic bug
Also make field names configurable
|
Lua
|
mpl-2.0
|
timurb/heka-tsutils-plugins,hynd/heka-tsutils-plugins
|
b272d2501e6243b244c97990a5377823a3df565a
|
item/id_6_scissors.lua
|
item/id_6_scissors.lua
|
-- I_6.lua garn aus darm
-- UPDATE common SET com_script='item.id_6_scissors' WHERE com_itemid IN (6);
require("item.general.metal")
require("item.base.crafts")
module("item.id_6_scissors", package.seeall, package.seeall(item.general.metal))
function UseItem(User,SourceItem,TargetItem,Counter,Param,ltstate)
base.common.ResetInterruption( User, ltstate );
math.randomseed( os.time() );
if ( ltstate == Action.abort ) then
if (User:increaseAttrib("sex",0) == 0) then
gText = "seine";
eText = "his";
else
gText = "ihre";
eText = "her";
end
User:talkLanguage(Character.say, Player.german, "#me unterbricht "..gText.." Arbeit.");
User:talkLanguage(Character.say, Player.english,"#me interrupts "..eText.." work.");
return
end
if (SourceItem:getType()~=4) then
base.common.InformNLS(User,
"Du musst die Schere in der Hand halten.",
"You have to hold the scissors in your hands!");
return
end
if not base.common.CheckItem( User, SourceItem ) then
return
end
if not base.common.FitForWork( User ) then
return
end
if ( User:countItemAt("belt",63) < 1 ) then
Char = base.common.GetFrontCharacter( User );
if (Char ~=nil) then
GetWoolFromSheep(User,SourceItem, Char, ltstate)
elseif (ltstate ~= Action.success) then
base.common.InformNLS( User,
"Du brauchst entweder ein Schaf dem du die Wolle abnehmen kannst oder Eingeweide die du zerschneiden kannst.",
"You either need a sheep you can take the wool from or some entrails you can cut.");
end
return
end
if ( ltstate == Action.none ) then
User:startAction( 16, 0, 0, 0, 0);
User:talkLanguage( Character.say, Player.german, "#me beginnt Eingeweide zu zerschneiden.");
User:talkLanguage( Character.say, Player.english, "#me starts to cut entrails.");
return
end
if base.common.IsInterrupted( User ) then
local selectMessage = math.random(1,3);
if ( selectMessage == 1 ) then
base.common.InformNLS(User,
"Du wischst dir den Schwei von der Stirn.",
"You wipe sweat off your forehead.");
elseif ( selectMessage == 2 ) then
base.common.InformNLS(User,
"Die Schere scheint schon ziemlich stumpf zu sein. Du schleifst sie kurz nach.",
"The scissors got blunt, you sharpen them with a whetstone.");
else
base.common.InformNLS(User,
"Dir tun die Finger weh vom vielen Schneiden und du machst eine kurze Pause.",
"Your fingers hurt from cutting, you take a short break.");
end
return
end
User:eraseItem( 63, 1 );
User:createItem(50,1,333,0);
if base.common.ToolBreaks( User, SourceItem, true ) then
base.common.InformNLS(User,
"Die alte und abgenutzte Schere in deinen Hnden zerbricht.",
"The old and used scissors in your hands breaks.");
else
User:startAction( 16, 0, 0, 0, 0);
end
base.common.GetHungry( User, 100 );
end
function GetWoolFromSheep(User,SourceItem, Sheep, ltstate)
math.randomseed( os.time() );
if ( ltstate == Action.abort ) then
if (User:increaseAttrib("sex",0) == 0) then
gText = "seine";
eText = "his";
else
gText = "ihre";
eText = "her";
end
User:talkLanguage(Character.say, Player.german, "#me unterbricht "..gText.." Arbeit.");
User:talkLanguage(Character.say, Player.english,"#me interrupts "..eText.." work.");
return
end
if (SourceItem:getType()~=4) then
base.common.InformNLS(User,
"Du musst die Schere in der Hand halten.",
"You have to hold the scissors in your hands!");
return
end
if not base.common.CheckItem( User, SourceItem ) then
return
end
if not base.common.FitForWork( User ) then
return
end
if (Sheep:getRace()~=18) then
base.common.InformNLS( User,
"Du kannst nur Schafen die Wolle abnehmen.",
"You can only cut wool from sheeps.");
return
end
if (math.abs(Sheep.pos.x-User.pos.x) > 1) or (math.abs(Sheep.pos.y-User.pos.y) > 1 ) then
base.common.InformNLS( User,
"Das Schaf ist zu weit weg!",
"The sheep is too far away!");
return
end
if ( ltstate == Action.none ) then
User:startAction( 13, 0, 0, 0, 0);
User:talkLanguage( Character.say, Player.german, "#me beginnt das Schaf zu scheren");
User:talkLanguage( Character.say, Player.english, "#me starts to shear the sheep.");
Sheep.movepoints = Sheep.movepoints - 30;
return
end
if base.common.IsInterrupted( User ) then
local selectMessage = math.random(1,3);
if ( selectMessage == 1 ) then
base.common.InformNLS(User,
"Du wischst dir den Schwei von der Stirn.",
"You wipe sweat off your forehead.");
elseif ( selectMessage == 2 ) then
base.common.InformNLS(User,
"Die Schere scheint schon ziemlich stumpf zu sein. Du schleifst sie kurz nach.",
"The scissors got blunt, you sharpen them with a whetstone.");
else
base.common.InformNLS(User,
"Dir tun die Finger weh vom vielen Schneiden und du machst eine kurze Pause.",
"Your fingers hurt from cutting, you take a short break.");
end
return
end
User:createItem(170,1,333,0);
Sheep.movepoints = Sheep.movepoints - 20;
if base.common.ToolBreaks( User, SourceItem ) then
base.common.InformNLS(User,
"Die alte und abgenutzte Schere in deinen Hnden zerbricht.",
"The old and used scissors in your hands breaks.");
else
User:startAction( 13, 0, 0, 0, 0);
end
base.common.GetHungry( User, 100 );
end
|
-- I_6.lua garn aus darm
-- UPDATE common SET com_script='item.id_6_scissors' WHERE com_itemid IN (6);
require("item.general.metal")
require("item.base.crafts")
module("item.id_6_scissors", package.seeall)
function UseItem(User,SourceItem,TargetItem,Counter,Param,ltstate)
base.common.ResetInterruption( User, ltstate );
math.randomseed( os.time() );
if ( ltstate == Action.abort ) then
if (User:increaseAttrib("sex",0) == 0) then
gText = "seine";
eText = "his";
else
gText = "ihre";
eText = "her";
end
User:talkLanguage(Character.say, Player.german, "#me unterbricht "..gText.." Arbeit.");
User:talkLanguage(Character.say, Player.english,"#me interrupts "..eText.." work.");
return
end
if (SourceItem:getType()~=4) then
base.common.InformNLS(User,
"Du musst die Schere in der Hand halten.",
"You have to hold the scissors in your hands!");
return
end
if not base.common.CheckItem( User, SourceItem ) then
return
end
if not base.common.FitForWork( User ) then
return
end
if ( User:countItemAt("belt",63) < 1 ) then
Char = base.common.GetFrontCharacter( User );
if (Char ~=nil) then
GetWoolFromSheep(User,SourceItem, Char, ltstate)
elseif (ltstate ~= Action.success) then
base.common.InformNLS( User,
"Du brauchst entweder ein Schaf dem du die Wolle abnehmen kannst oder Eingeweide die du zerschneiden kannst.",
"You either need a sheep you can take the wool from or some entrails you can cut.");
end
return
end
if ( ltstate == Action.none ) then
User:startAction( 16, 0, 0, 0, 0);
User:talkLanguage( Character.say, Player.german, "#me beginnt Eingeweide zu zerschneiden.");
User:talkLanguage( Character.say, Player.english, "#me starts to cut entrails.");
return
end
if base.common.IsInterrupted( User ) then
local selectMessage = math.random(1,3);
if ( selectMessage == 1 ) then
base.common.InformNLS(User,
"Du wischst dir den Schwei von der Stirn.",
"You wipe sweat off your forehead.");
elseif ( selectMessage == 2 ) then
base.common.InformNLS(User,
"Die Schere scheint schon ziemlich stumpf zu sein. Du schleifst sie kurz nach.",
"The scissors got blunt, you sharpen them with a whetstone.");
else
base.common.InformNLS(User,
"Dir tun die Finger weh vom vielen Schneiden und du machst eine kurze Pause.",
"Your fingers hurt from cutting, you take a short break.");
end
return
end
User:eraseItem( 63, 1 );
User:createItem(50,1,333,0);
if base.common.ToolBreaks( User, SourceItem, true ) then
base.common.InformNLS(User,
"Die alte und abgenutzte Schere in deinen Hnden zerbricht.",
"The old and used scissors in your hands breaks.");
else
User:startAction( 16, 0, 0, 0, 0);
end
base.common.GetHungry( User, 100 );
end
function GetWoolFromSheep(User,SourceItem, Sheep, ltstate)
math.randomseed( os.time() );
if ( ltstate == Action.abort ) then
if (User:increaseAttrib("sex",0) == 0) then
gText = "seine";
eText = "his";
else
gText = "ihre";
eText = "her";
end
User:talkLanguage(Character.say, Player.german, "#me unterbricht "..gText.." Arbeit.");
User:talkLanguage(Character.say, Player.english,"#me interrupts "..eText.." work.");
return
end
if (SourceItem:getType()~=4) then
base.common.InformNLS(User,
"Du musst die Schere in der Hand halten.",
"You have to hold the scissors in your hands!");
return
end
if not base.common.CheckItem( User, SourceItem ) then
return
end
if not base.common.FitForWork( User ) then
return
end
if (Sheep:getRace()~=18) then
base.common.InformNLS( User,
"Du kannst nur Schafen die Wolle abnehmen.",
"You can only cut wool from sheeps.");
return
end
if (math.abs(Sheep.pos.x-User.pos.x) > 1) or (math.abs(Sheep.pos.y-User.pos.y) > 1 ) then
base.common.InformNLS( User,
"Das Schaf ist zu weit weg!",
"The sheep is too far away!");
return
end
if ( ltstate == Action.none ) then
User:startAction( 13, 0, 0, 0, 0);
User:talkLanguage( Character.say, Player.german, "#me beginnt das Schaf zu scheren");
User:talkLanguage( Character.say, Player.english, "#me starts to shear the sheep.");
Sheep.movepoints = Sheep.movepoints - 30;
return
end
if base.common.IsInterrupted( User ) then
local selectMessage = math.random(1,3);
if ( selectMessage == 1 ) then
base.common.InformNLS(User,
"Du wischst dir den Schwei von der Stirn.",
"You wipe sweat off your forehead.");
elseif ( selectMessage == 2 ) then
base.common.InformNLS(User,
"Die Schere scheint schon ziemlich stumpf zu sein. Du schleifst sie kurz nach.",
"The scissors got blunt, you sharpen them with a whetstone.");
else
base.common.InformNLS(User,
"Dir tun die Finger weh vom vielen Schneiden und du machst eine kurze Pause.",
"Your fingers hurt from cutting, you take a short break.");
end
return
end
User:createItem(170,1,333,0);
Sheep.movepoints = Sheep.movepoints - 20;
if base.common.ToolBreaks( User, SourceItem ) then
base.common.InformNLS(User,
"Die alte und abgenutzte Schere in deinen Hnden zerbricht.",
"The old and used scissors in your hands breaks.");
else
User:startAction( 13, 0, 0, 0, 0);
end
base.common.GetHungry( User, 100 );
end
function LookAtItem(User,Item)
item.general.metal.LookAtItem(User,Item)
end
|
fixed scisscors look at
|
fixed scisscors look at
|
Lua
|
agpl-3.0
|
vilarion/Illarion-Content,Illarion-eV/Illarion-Content,Baylamon/Illarion-Content,LaFamiglia/Illarion-Content,KayMD/Illarion-Content
|
78b9ad78089c2a1ded331f4e9680d95f5b04761d
|
test/test_connect.lua
|
test/test_connect.lua
|
package.path = "..\\src\\lua\\?.lua;" .. package.path
pcall(require, "luacov")
local Redis = require "lluv.redis"
local uv = require "lluv"
local TEST_PORT = 5555
local function TcpServer(host, port, cb)
if not cb then
host, port, cb = '127.0.0.1', host, port
end
return uv.tcp():bind(host, port, function(srv, err)
if err then
srv:close()
return cb(srv, err)
end
srv:listen(function(srv, err)
if err then
srv:close()
return cb(srv, err)
end
cb(srv:accept())
end)
end)
end
local C = function(t) return table.concat(t, '\r\n') .. '\r\n' end
local EOF = uv.error('LIBUV', uv.EOF)
local function test_1()
io.write("Test 1 - ")
local srv = TcpServer(TEST_PORT, function(cli, err)
assert(not err, tostring(err))
cli:close()
end)
local cli = Redis.Connection.new('127.0.0.1:5555')
local c = 1
cli:open(function(s, err)
assert(s == cli)
assert(not err, tostring(err))
assert(1 == c) c = c + 1
end)
cli:open(function(s, err)
assert(s == cli)
assert(not err, tostring(err))
assert(2 == c) c = c + 1
cli:close()
srv:close()
end)
uv.run(debug.traceback)
assert(c == 3)
io.write("OK\n")
end
local function test_2()
io.write("Test 2 - ")
local srv = TcpServer(TEST_PORT, function(cli, err)
assert(not err, tostring(err))
cli:start_read(function(_, err, data)
if err then return cli:close() end
end)
local res = C{"$2", "OK"}
cli:write(res)
end)
local cli = Redis.Connection.new('127.0.0.1:5555')
local c = 1
cli:open(function(s, err)
assert(not err, tostring(err))
assert(1 == c) c = c + 1
cli:set("A", "10", function(s, err, res)
assert(not err, tostring(err))
assert(res == 'OK')
assert(2 == c) c = c + 1
cli:close(function()
srv:close()
end)
end)
end)
uv.run(debug.traceback)
assert(c == 3)
io.write("OK\n")
end
local function test_3()
io.write("Test 3 - ")
local srv = TcpServer(TEST_PORT, function(cli, err)
assert(not err, tostring(err))
cli:start_read(function(_, err, data)
if err then return cli:close() end
end)
local res = C{"$2", "OK"}
cli:write(res)
end)
local cli = Redis.Connection.new('127.0.0.1:5555')
local c = 1
cli:open(function(s, err)
assert(not err, tostring(err))
assert(1 == c) c = c + 1
end)
cli:set("A", "10", function(s, err, res)
assert(not err, tostring(err))
assert(res == 'OK')
assert(2 == c) c = c + 1
cli:close(function()
srv:close()
end)
end)
uv.run(debug.traceback)
assert(c == 3)
io.write("OK\n")
end
local function test_4()
io.write("Test 4 - ")
local srv = TcpServer(TEST_PORT, function(cli, err)
assert(not err, tostring(err))
cli:start_read(function(_, err, data)
if err then return cli:close() end
end)
local res = C{"$2", "OK"}
cli:write(res)
end)
local cli = Redis.Connection.new('127.0.0.1:5555')
local c = 1
cli:open(function(s, err)
assert(s == cli)
assert(err == EOF, tostring(err))
assert(1 == c, c) c = c + 1
end)
cli:set("A", "10", function(s, err, res)
assert(s == cli)
assert(err == EOF, tostring(err))
assert(res == nil)
assert(2 == c, c) c = c + 1
end)
cli:close(function(s, err)
assert(3 == c, c) c = c + 1
assert(s == cli)
assert(not err, tostring(err))
srv:close()
end)
uv.run(debug.traceback)
assert(c == 4)
io.write("OK\n")
end
test_1()
test_2()
test_3()
test_4()
|
package.path = "..\\src\\lua\\?.lua;" .. package.path
pcall(require, "luacov")
local Redis = require "lluv.redis"
local uv = require "lluv"
local TEST_PORT = 5555
local function TcpServer(host, port, cb)
if not cb then
host, port, cb = '127.0.0.1', host, port
end
return uv.tcp():bind(host, port, function(srv, err)
if err then
srv:close()
return cb(srv, err)
end
srv:listen(function(srv, err)
if err then
srv:close()
return cb(srv, err)
end
cb(srv:accept())
end)
end)
end
local C = function(t) return table.concat(t, '\r\n') .. '\r\n' end
local EOF = uv.error('LIBUV', uv.EOF)
local function test_1()
io.write("Test 1 - ")
local srv = TcpServer(TEST_PORT, function(cli, err)
assert(not err, tostring(err))
cli:close()
end)
local cli = Redis.Connection.new('127.0.0.1:5555')
local c = 1
uv.timer():start(1000, function()
cli:open(function(s, err)
assert(s == cli)
assert(not err, tostring(err))
assert(1 == c) c = c + 1
end)
cli:open(function(s, err)
assert(s == cli)
assert(not err, tostring(err))
assert(2 == c) c = c + 1
cli:close()
srv:close()
end)
end)
uv.run(debug.traceback)
assert(c == 3)
io.write("OK\n")
end
local function test_2()
io.write("Test 2 - ")
local srv = TcpServer(TEST_PORT, function(cli, err)
assert(not err, tostring(err))
cli:start_read(function(_, err, data)
if err then return cli:close() end
end)
local res = C{"$2", "OK"}
cli:write(res)
end)
local cli = Redis.Connection.new('127.0.0.1:5555')
local c = 1
uv.timer():start(1000, function()
cli:open(function(s, err)
assert(not err, tostring(err))
assert(1 == c) c = c + 1
cli:set("A", "10", function(s, err, res)
assert(not err, tostring(err))
assert(res == 'OK')
assert(2 == c) c = c + 1
cli:close(function()
srv:close()
end)
end)
end)
end)
uv.run(debug.traceback)
assert(c == 3)
io.write("OK\n")
end
local function test_3()
io.write("Test 3 - ")
local srv = TcpServer(TEST_PORT, function(cli, err)
assert(not err, tostring(err))
cli:start_read(function(_, err, data)
if err then return cli:close() end
end)
local res = C{"$2", "OK"}
cli:write(res)
end)
local cli = Redis.Connection.new('127.0.0.1:5555')
local c = 1
uv.timer():start(1000, function()
cli:open(function(s, err)
assert(not err, tostring(err))
assert(1 == c) c = c + 1
end)
cli:set("A", "10", function(s, err, res)
assert(not err, tostring(err))
assert(res == 'OK')
assert(2 == c) c = c + 1
cli:close(function()
srv:close()
end)
end)
end)
uv.run(debug.traceback)
assert(c == 3)
io.write("OK\n")
end
local function test_4()
io.write("Test 4 - ")
local srv = TcpServer(TEST_PORT, function(cli, err)
assert(not err, tostring(err))
cli:start_read(function(_, err, data)
if err then return cli:close() end
end)
local res = C{"$2", "OK"}
cli:write(res)
end)
local c = 1
uv.timer():start(1000, function()
local cli = Redis.Connection.new('127.0.0.1:5555')
cli:open(function(s, err)
assert(s == cli)
assert(err == EOF, tostring(err))
assert(1 == c, c) c = c + 1
end)
cli:set("A", "10", function(s, err, res)
assert(s == cli)
assert(err == EOF, tostring(err))
assert(res == nil)
assert(2 == c, c) c = c + 1
end)
cli:close(function(s, err)
assert(3 == c, c) c = c + 1
assert(s == cli)
assert(not err, tostring(err))
srv:close()
end)
end)
uv.run(debug.traceback)
assert(c == 4)
io.write("OK\n")
end
test_1()
test_2()
test_3()
test_4()
|
Fix. Add timeout before connect in test.
|
Fix. Add timeout before connect in test.
|
Lua
|
mit
|
moteus/lua-lluv-redis
|
99d83c1738f7b6bccbb440b7fa4fd417745e83ce
|
src/vendor/gamestate.lua
|
src/vendor/gamestate.lua
|
--[[
Copyright (c) 2010-2012 Matthias Richter
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
Except as contained in this notice, the name(s) of the above copyright holders
shall not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]--
local function __NULL__() end
-- default gamestate produces error on every callback
local function __ERROR__() error("Gamestate not initialized. Use Gamestate.switch()") end
local current = setmetatable({leave = __NULL__}, {__index = __ERROR__})
local states = {}
local GS = {}
function GS.new()
return {
init = __NULL__,
enter = __NULL__,
leave = __NULL__,
update = __NULL__,
draw = __NULL__,
focus = __NULL__,
keyreleased = __NULL__,
keypressed = __NULL__,
mousepressed = __NULL__,
mousereleased = __NULL__,
joystickpressed = __NULL__,
joystickreleased = __NULL__,
quit = __NULL__,
}
end
GS.Level = nil
function GS.load(name)
if love.filesystem.exists("maps/" .. name .. ".lua") then
-- ugly hack to get around circular import
states[name] = GS.Level.new(name)
else
states[name] = require(name)
end
return states[name]
end
function GS.currentState()
return current
end
function GS.get(name)
local state = states[name]
if state then
return state
end
return GS.load(name)
end
function GS.switch(to, ...)
assert(to, "Missing argument: Gamestate to switch to")
if type(to) == "string" then
local name = to
to = GS.get(to)
assert(to, "Failed loading gamestate " .. name)
end
current:leave()
local pre = current
to:init()
to.init = __NULL__
current = to
return current:enter(pre, ...)
end
-- holds all defined love callbacks after GS.registerEvents is called
-- returns empty function on undefined callback
local registry = setmetatable({}, {__index = function() return __NULL__ end})
local all_callbacks = {
'update', 'draw', 'focus', 'keypressed', 'keyreleased',
'mousepressed', 'mousereleased', 'joystickpressed',
'joystickreleased', 'quit'
}
function GS.registerEvents(callbacks)
callbacks = callbacks or all_callbacks
for _, f in ipairs(callbacks) do
registry[f] = love[f]
love[f] = function(...) GS[f](...) end
end
end
-- forward any undefined functions
setmetatable(GS, {__index = function(_, func)
return function(...)
registry[func](...)
current[func](current, ...)
end
end})
return GS
|
--[[
Copyright (c) 2010-2012 Matthias Richter
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
Except as contained in this notice, the name(s) of the above copyright holders
shall not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]--
local function __NULL__() end
-- default gamestate produces error on every callback
local function __ERROR__() error("Gamestate not initialized. Use Gamestate.switch()") end
local current = setmetatable({leave = __NULL__}, {__index = __NULL__})
local states = {}
local GS = {}
function GS.new()
return {
init = __NULL__,
enter = __NULL__,
leave = __NULL__,
update = __NULL__,
draw = __NULL__,
focus = __NULL__,
keyreleased = __NULL__,
keypressed = __NULL__,
mousepressed = __NULL__,
mousereleased = __NULL__,
joystickpressed = __NULL__,
joystickreleased = __NULL__,
quit = __NULL__,
}
end
GS.Level = nil
function GS.load(name)
if love.filesystem.exists("maps/" .. name .. ".lua") then
-- ugly hack to get around circular import
states[name] = GS.Level.new(name)
else
states[name] = require(name)
end
return states[name]
end
function GS.currentState()
return current
end
function GS.get(name)
local state = states[name]
if state then
return state
end
return GS.load(name)
end
function GS.switch(to, ...)
assert(to, "Missing argument: Gamestate to switch to")
if type(to) == "string" then
local name = to
to = GS.get(to)
assert(to, "Failed loading gamestate " .. name)
end
current:leave()
local pre = current
to:init()
to.init = __NULL__
current = to
return current:enter(pre, ...)
end
-- holds all defined love callbacks after GS.registerEvents is called
-- returns empty function on undefined callback
local registry = setmetatable({}, {__index = function() return __NULL__ end})
local all_callbacks = {
'update', 'draw', 'focus', 'keypressed', 'keyreleased',
'mousepressed', 'mousereleased', 'joystickpressed',
'joystickreleased', 'quit'
}
function GS.registerEvents(callbacks)
callbacks = callbacks or all_callbacks
for _, f in ipairs(callbacks) do
registry[f] = love[f]
love[f] = function(...) GS[f](...) end
end
end
-- forward any undefined functions
setmetatable(GS, {__index = function(_, func)
return function(...)
registry[func](...)
current[func](current, ...)
end
end})
return GS
|
Fix #568. Allow for levels to be loaded via the command line
|
Fix #568. Allow for levels to be loaded via the command line
|
Lua
|
mit
|
hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua
|
73118c078a26812dc7a625edf3386e6d4e9fea9b
|
controller/main.lua
|
controller/main.lua
|
-- Main client program for monitoring the space probe
-- Requirents:
-- lua 5.1 or newer
require "config"
require "utils"
require "probe"
require "knob"
require "bbl-twitter"
twitter_client = client(config.oauth_consumer_key, config.oauth_consumer_secret,
config.oauth_access_key, config.oauth_access_secret)
function startup()
-- make sure we can see the probe before we start up at all
check_probe_connection()
-- Determine initial space state (doesn't send any notices during startup)
probe.leds_off()
local pos = probe.get_position()
local space_open = pos and ( pos > config.knob_deadband )
log("Starting with space " .. "open" and space_open or "closed")
if space_open then
probe.green_glow()
end
-- Kick off with our initial state
if space_open then
est_closing_time = os.time() + translate(pos, config.knob_table)*60*60
log("Estimated closing " .. os.date(nil, est_closing_time))
return space_is_open()
else
return space_is_closed()
end
end
warnings = 0
space_opened_at=os.time()
-- State
function space_is_open()
check_probe_connection()
sleep(1)
local hours_left = (est_closing_time - os.time())/60/60
probe.set_dial(round(translate(hours_left, config.dial_table)))
local hours = knob.get_movement()
if hours == 0 then
-- Space just closed
space_closing_now()
return space_is_closed()
elseif hours ~= nil then
-- Dial moved to a different non-zero number
space_closing_in(hours, true)
end
if os.time() > est_closing_time and warnings < 4 then -- est. closing is now
log("Due to close now!!!")
probe.buzz(15)
probe.slow_blue_blink(100)
warnings = 4
elseif os.time() + 1*60 > est_closing_time and warnings < 3 then -- 1 minute to est. closing
log("1 minute to estimated closing...")
probe.buzz(10)
probe.slow_blue_blink(250)
warnings = 3
elseif os.time() + 5*60 > est_closing_time and warnings < 2 then -- 5 minutes to est. closing
log("5 minutes to estimated closing...")
probe.buzz(5)
probe.slow_blue_blink(500)
warnings = 2
elseif os.time() + 30*60 > est_closing_time and warnings < 1 then -- 30 minutes to est. closing
log("30 minutes to estimated closing...")
probe.buzz(2)
probe.slow_blue_blink(1000)
warnings = 1
end
return space_is_open()
end
-- State
function space_is_closed()
check_probe_connection()
sleep(1)
local hours = knob.get_movement()
if hours ~= nil and hours > 0 then
-- Space just opened
space_closing_in(hours, false)
return space_is_open()
end
return space_is_closed()
end
function check_probe_connection()
if probe.get_offline() then
log("Probe offline. Waiting for reconnection...")
while probe.get_offline() do
sleep(1)
end
end
end
-- Space just opened, or opening hours changed
function space_closing_in(hours, was_already_open)
est_closing_time = os.time() + hours*60*60
log("Estimated closing " .. os.date(nil, est_closing_time))
if not was_already_open then
space_opened_at = os.time()
end
probe.set_dial(round(translate(hours, config.dial_table)))
local prep = was_already_open and "will remain" or "is now"
local adverb = was_already_open and "another" or ""
local est_closing_rounded = round(est_closing_time * 60*15) /60/15 -- round to 15 minute interval
local msg = string.format("The MHV space %s open for approximately %s %s (~%s)",
prep, adverb, hours_rounded(hours), os.date("%H:%M",est_closing_rounded))
update_world(msg)
probe.green_glow()
warnings = 0
return space_is_open()
end
-- Space is closing now
function space_closing_now()
probe.set_dial(0)
local duration = os.time() - space_opened_at
if duration < 180 then
duration = string.format("%d seconds", duration)
elseif duration < 60*180 then
duration = string.format("%d minutes", duration/60)
elseif duration < 60*60*24 then
duration = hours_rounded(duration/60/60)
else
duration = string.format("%.1f days", duration/60/60/24)
end
-- ironically, the duraiton is necessary to stop twitter dropping duplicate tweets!
update_world("The MHV space is now closed (was open " .. duration .. ")")
return space_is_closed()
end
function update_world(msg)
probe.fast_green_blink()
msg = string.gsub(msg, " ", " ")
log(msg)
-- email
local email = io.open("/tmp/mhv_email", "w+")
email:write("Date: " .. os.date() .. "\n")
email:write("From: " .. config.smtp_from .. "\n")
email:write("To: " .. config.smtp_to .. "\n")
email:write("Subject: " .. msg .. "\n")
email:write("\n\nThis message was sent automatically by the MHV Space Probe.\n\n")
email:close()
os.execute("cat /tmp/mhv_email | " .. config.smtp_cmd .. " &")
-- twitter
local retries = 0
while update_status(twitter_client, msg) == "" and retries < config.max_twitter_retries do
probe.get_offline() -- keep the probe awake
sleep(5)
probe.get_offline() -- keep the probe awake
retries = retries + 1
end
if retries == config.max_twitter_retries then
log("Failed to tweet... :(")
end
log("Done communicating message")
probe.leds_off()
end
-- Return number of hours, rounded to nearest 1/4 hour, as string
function hours_rounded(hours)
-- precision needed depends on how far away closing time is
if hours > 6 then
hours = round(hours)
elseif hours > 2 then
hours = round(hours * 2) / 2
else
hours = round(hours * 4) / 4
end
local fraction_name = { "", " 1/4", " 1/2", " 3/4" }
local whole = math.floor(hours)
if whole == 0 and hours > 0.125 then whole = "" end
local suffix = "s"
if hours <= 1 then suffix = "" end
return string.format("%s%s hour%s", whole, fraction_name[((hours % 1)*4)+1], suffix)
end
return startup()
|
-- Main client program for monitoring the space probe
-- Requirents:
-- lua 5.1 or newer
require "config"
require "utils"
require "probe"
require "knob"
require "bbl-twitter"
twitter_client = client(config.oauth_consumer_key, config.oauth_consumer_secret,
config.oauth_access_key, config.oauth_access_secret)
function startup()
-- make sure we can see the probe before we start up at all
check_probe_connection()
-- Determine initial space state (doesn't send any notices during startup)
probe.leds_off()
local pos = probe.get_position()
local hours = translate(pos, config.knob_table)
log("Initial position " .. pos .. " translates to " .. hours)
local space_open = translate(pos, config.knob_table) > 0.25
local starting = "open"
if not space_open then starting = "closed" end
log("Starting with space " .. starting)
if space_open then
probe.green_glow()
end
-- Kick off with our initial state
if space_open then
est_closing_time = os.time() + hours*60*60
log("Estimated closing " .. os.date(nil, est_closing_time))
return space_is_open()
else
return space_is_closed()
end
end
warnings = 0
space_opened_at=os.time()
-- State
function space_is_open()
check_probe_connection()
sleep(1)
local hours_left = (est_closing_time - os.time())/60/60
probe.set_dial(round(translate(hours_left, config.dial_table)))
local hours = knob.get_movement()
if hours == 0 then
-- Space just closed
space_closing_now()
return space_is_closed()
elseif hours ~= nil then
-- Dial moved to a different non-zero number
space_closing_in(hours, true)
end
if os.time() > est_closing_time and warnings < 4 then -- est. closing is now
log("Due to close now!!!")
probe.buzz(15)
probe.slow_blue_blink(100)
warnings = 4
elseif os.time() + 1*60 > est_closing_time and warnings < 3 then -- 1 minute to est. closing
log("1 minute to estimated closing...")
probe.buzz(10)
probe.slow_blue_blink(250)
warnings = 3
elseif os.time() + 5*60 > est_closing_time and warnings < 2 then -- 5 minutes to est. closing
log("5 minutes to estimated closing...")
probe.buzz(5)
probe.slow_blue_blink(500)
warnings = 2
elseif os.time() + 30*60 > est_closing_time and warnings < 1 then -- 30 minutes to est. closing
log("30 minutes to estimated closing...")
probe.buzz(2)
probe.slow_blue_blink(1000)
warnings = 1
end
return space_is_open()
end
-- State
function space_is_closed()
check_probe_connection()
sleep(1)
local hours = knob.get_movement()
if hours ~= nil and hours > 0 then
-- Space just opened
space_closing_in(hours, false)
return space_is_open()
end
return space_is_closed()
end
function check_probe_connection()
if probe.get_offline() then
log("Probe offline. Waiting for reconnection...")
while probe.get_offline() do
sleep(1)
end
end
end
-- Space just opened, or opening hours changed
function space_closing_in(hours, was_already_open)
est_closing_time = os.time() + hours*60*60
log("Estimated closing " .. os.date(nil, est_closing_time))
if not was_already_open then
space_opened_at = os.time()
end
probe.set_dial(round(translate(hours, config.dial_table)))
local prep = was_already_open and "will remain" or "is now"
local adverb = was_already_open and "another" or ""
local est_closing_rounded = round(est_closing_time /60/15) *60*15 -- round to 15 minute interval
local msg = string.format("The MHV space %s open for approximately %s %s (~%s)",
prep, adverb, hours_rounded(hours), os.date("%H:%M",est_closing_rounded))
update_world(msg)
probe.green_glow()
warnings = 0
return space_is_open()
end
-- Space is closing now
function space_closing_now()
probe.set_dial(0)
local duration = os.time() - space_opened_at
if duration < 180 then
duration = string.format("%d seconds", duration)
elseif duration < 60*180 then
duration = string.format("%d minutes", duration/60)
elseif duration < 60*60*24 then
duration = hours_rounded(duration/60/60)
else
duration = string.format("%.1f days", duration/60/60/24)
end
-- appending the duration open is necessary to stop twitter dropping duplicate tweets!
update_world("The MHV space is now closed (was open " .. duration .. ")")
return space_is_closed()
end
function update_world(msg)
probe.fast_green_blink()
msg = string.gsub(msg, " ", " ")
log(msg)
-- email
local email = io.open("/tmp/mhv_email", "w+")
email:write("Date: " .. os.date() .. "\n")
email:write("From: " .. config.smtp_from .. "\n")
email:write("To: " .. config.smtp_to .. "\n")
email:write("Subject: " .. msg .. "\n")
email:write("\n\nThis message was sent automatically by the MHV Space Probe.\n\n")
email:close()
os.execute("cat /tmp/mhv_email | " .. config.smtp_cmd .. " &")
-- twitter
local retries = 0
while update_status(twitter_client, msg) == "" and retries < config.max_twitter_retries do
probe.get_offline() -- keep the probe awake
sleep(5)
probe.get_offline() -- keep the probe awake
retries = retries + 1
end
if retries == config.max_twitter_retries then
log("Failed to tweet... :(")
end
log("Done communicating message")
probe.leds_off()
end
-- Return number of hours, rounded to nearest 1/4 hour, as string
function hours_rounded(hours)
-- precision needed depends on how far away closing time is
if hours > 6 then
hours = round(hours)
elseif hours > 2 then
hours = round(hours * 2) / 2
else
hours = round(hours * 4) / 4
end
local fraction_name = { "", " 1/4", " 1/2", " 3/4" }
local whole = math.floor(hours)
if whole == 0 and hours > 0.125 then whole = "" end
local suffix = "s"
if hours <= 1 then suffix = "" end
return string.format("%s%s hour%s", whole, fraction_name[((hours % 1)*4)+1], suffix)
end
return startup()
|
Timekeeping bugfixes
|
Timekeeping bugfixes
|
Lua
|
mit
|
makehackvoid/MHV-Space-Probe
|
d1c6235c5bae6f45aae6177b4774599f6df38226
|
crispy/quanty/templates/meta/rixs/fields.lua
|
crispy/quanty/templates/meta/rixs/fields.lua
|
--------------------------------------------------------------------------------
-- Define the magnetic field and exchange field terms.
--------------------------------------------------------------------------------
Sx_#m = NewOperator("Sx", NFermions, IndexUp_#m, IndexDn_#m)
Sy_#m = NewOperator("Sy", NFermions, IndexUp_#m, IndexDn_#m)
Sz_#m = NewOperator("Sz", NFermions, IndexUp_#m, IndexDn_#m)
Ssqr_#m = NewOperator("Ssqr", NFermions, IndexUp_#m, IndexDn_#m)
Splus_#m = NewOperator("Splus", NFermions, IndexUp_#m, IndexDn_#m)
Smin_#m = NewOperator("Smin", NFermions, IndexUp_#m, IndexDn_#m)
Lx_#m = NewOperator("Lx", NFermions, IndexUp_#m, IndexDn_#m)
Ly_#m = NewOperator("Ly", NFermions, IndexUp_#m, IndexDn_#m)
Lz_#m = NewOperator("Lz", NFermions, IndexUp_#m, IndexDn_#m)
Lsqr_#m = NewOperator("Lsqr", NFermions, IndexUp_#m, IndexDn_#m)
Lplus_#m = NewOperator("Lplus", NFermions, IndexUp_#m, IndexDn_#m)
Lmin_#m = NewOperator("Lmin", NFermions, IndexUp_#m, IndexDn_#m)
Jx_#m = NewOperator("Jx", NFermions, IndexUp_#m, IndexDn_#m)
Jy_#m = NewOperator("Jy", NFermions, IndexUp_#m, IndexDn_#m)
Jz_#m = NewOperator("Jz", NFermions, IndexUp_#m, IndexDn_#m)
Jsqr_#m = NewOperator("Jsqr", NFermions, IndexUp_#m, IndexDn_#m)
Jplus_#m = NewOperator("Jplus", NFermions, IndexUp_#m, IndexDn_#m)
Jmin_#m = NewOperator("Jmin", NFermions, IndexUp_#m, IndexDn_#m)
Tx_#m = NewOperator("Tx", NFermions, IndexUp_#m, IndexDn_#m)
Ty_#m = NewOperator("Ty", NFermions, IndexUp_#m, IndexDn_#m)
Tz_#m = NewOperator("Tz", NFermions, IndexUp_#m, IndexDn_#m)
Sx = Sx_#m
Sy = Sy_#m
Sz = Sz_#m
Lx = Lx_#m
Ly = Ly_#m
Lz = Lz_#m
Jx = Jx_#m
Jy = Jy_#m
Jz = Jz_#m
Tx = Tx_#m
Ty = Ty_#m
Tz = Tz_#m
Ssqr = Sx * Sx + Sy * Sy + Sz * Sz
Lsqr = Lx * Lx + Ly * Ly + Lz * Lz
Jsqr = Jx * Jx + Jy * Jy + Jz * Jz
if MagneticFieldTerm then
Bx_i = $Bx_i_value * EnergyUnits.Tesla.value
By_i = $By_i_value * EnergyUnits.Tesla.value
Bz_i = $Bz_i_value * EnergyUnits.Tesla.value
Bx_m = $Bx_m_value * EnergyUnits.Tesla.value
By_m = $By_m_value * EnergyUnits.Tesla.value
Bz_m = $Bz_m_value * EnergyUnits.Tesla.value
Bx_f = $Bx_f_value * EnergyUnits.Tesla.value
By_f = $By_f_value * EnergyUnits.Tesla.value
Bz_f = $Bz_f_value * EnergyUnits.Tesla.value
H_i = H_i + Chop(
Bx_i * (2 * Sx + Lx)
+ By_i * (2 * Sy + Ly)
+ Bz_i * (2 * Sz + Lz))
H_f = H_f + Chop(
Bx_f * (2 * Sx + Lx)
+ By_f * (2 * Sy + Ly)
+ Bz_f * (2 * Sz + Lz))
end
if ExchangeFieldTerm then
Hx_i = $Hx_i_value
Hy_i = $Hy_i_value
Hz_i = $Hz_i_value
Hx_m = $Hx_m_value
Hy_m = $Hy_m_value
Hz_m = $Hz_m_value
Hx_f = $Hx_f_value
Hy_f = $Hy_f_value
Hz_f = $Hz_f_value
H_i = H_i + Chop(
Hx_i * Sx
+ Hy_i * Sy
+ Hz_i * Sz)
H_m = H_m + Chop(
Hx_m * Sx
+ Hy_m * Sy
+ Hz_m * Sz)
H_f = H_f + Chop(
Hx_f * Sx
+ Hy_f * Sy
+ Hz_f * Sz)
end
|
--------------------------------------------------------------------------------
-- Define the magnetic field and exchange field terms.
--------------------------------------------------------------------------------
Sx_#m = NewOperator("Sx", NFermions, IndexUp_#m, IndexDn_#m)
Sy_#m = NewOperator("Sy", NFermions, IndexUp_#m, IndexDn_#m)
Sz_#m = NewOperator("Sz", NFermions, IndexUp_#m, IndexDn_#m)
Ssqr_#m = NewOperator("Ssqr", NFermions, IndexUp_#m, IndexDn_#m)
Splus_#m = NewOperator("Splus", NFermions, IndexUp_#m, IndexDn_#m)
Smin_#m = NewOperator("Smin", NFermions, IndexUp_#m, IndexDn_#m)
Lx_#m = NewOperator("Lx", NFermions, IndexUp_#m, IndexDn_#m)
Ly_#m = NewOperator("Ly", NFermions, IndexUp_#m, IndexDn_#m)
Lz_#m = NewOperator("Lz", NFermions, IndexUp_#m, IndexDn_#m)
Lsqr_#m = NewOperator("Lsqr", NFermions, IndexUp_#m, IndexDn_#m)
Lplus_#m = NewOperator("Lplus", NFermions, IndexUp_#m, IndexDn_#m)
Lmin_#m = NewOperator("Lmin", NFermions, IndexUp_#m, IndexDn_#m)
Jx_#m = NewOperator("Jx", NFermions, IndexUp_#m, IndexDn_#m)
Jy_#m = NewOperator("Jy", NFermions, IndexUp_#m, IndexDn_#m)
Jz_#m = NewOperator("Jz", NFermions, IndexUp_#m, IndexDn_#m)
Jsqr_#m = NewOperator("Jsqr", NFermions, IndexUp_#m, IndexDn_#m)
Jplus_#m = NewOperator("Jplus", NFermions, IndexUp_#m, IndexDn_#m)
Jmin_#m = NewOperator("Jmin", NFermions, IndexUp_#m, IndexDn_#m)
Tx_#m = NewOperator("Tx", NFermions, IndexUp_#m, IndexDn_#m)
Ty_#m = NewOperator("Ty", NFermions, IndexUp_#m, IndexDn_#m)
Tz_#m = NewOperator("Tz", NFermions, IndexUp_#m, IndexDn_#m)
Sx = Sx_#m
Sy = Sy_#m
Sz = Sz_#m
Lx = Lx_#m
Ly = Ly_#m
Lz = Lz_#m
Jx = Jx_#m
Jy = Jy_#m
Jz = Jz_#m
Tx = Tx_#m
Ty = Ty_#m
Tz = Tz_#m
Ssqr = Sx * Sx + Sy * Sy + Sz * Sz
Lsqr = Lx * Lx + Ly * Ly + Lz * Lz
Jsqr = Jx * Jx + Jy * Jy + Jz * Jz
if MagneticFieldTerm then
Bx_i = $Bx_i_value * EnergyUnits.Tesla.value
By_i = $By_i_value * EnergyUnits.Tesla.value
Bz_i = $Bz_i_value * EnergyUnits.Tesla.value
Bx_m = $Bx_m_value * EnergyUnits.Tesla.value
By_m = $By_m_value * EnergyUnits.Tesla.value
Bz_m = $Bz_m_value * EnergyUnits.Tesla.value
Bx_f = $Bx_f_value * EnergyUnits.Tesla.value
By_f = $By_f_value * EnergyUnits.Tesla.value
Bz_f = $Bz_f_value * EnergyUnits.Tesla.value
H_i = H_i + Chop(
Bx_i * (2 * Sx + Lx)
+ By_i * (2 * Sy + Ly)
+ Bz_i * (2 * Sz + Lz))
H_m = H_m + Chop(
Bx_m * (2 * Sx + Lx)
+ By_m * (2 * Sy + Ly)
+ Bz_m * (2 * Sz + Lz))
H_f = H_f + Chop(
Bx_f * (2 * Sx + Lx)
+ By_f * (2 * Sy + Ly)
+ Bz_f * (2 * Sz + Lz))
end
if ExchangeFieldTerm then
Hx_i = $Hx_i_value
Hy_i = $Hy_i_value
Hz_i = $Hz_i_value
Hx_m = $Hx_m_value
Hy_m = $Hy_m_value
Hz_m = $Hz_m_value
Hx_f = $Hx_f_value
Hy_f = $Hy_f_value
Hz_f = $Hz_f_value
H_i = H_i + Chop(
Hx_i * Sx
+ Hy_i * Sy
+ Hz_i * Sz)
H_m = H_m + Chop(
Hx_m * Sx
+ Hy_m * Sy
+ Hz_m * Sz)
H_f = H_f + Chop(
Hx_f * Sx
+ Hy_f * Sy
+ Hz_f * Sz)
end
|
Fix the magnetic field for RIXS
|
Fix the magnetic field for RIXS
|
Lua
|
mit
|
mretegan/crispy,mretegan/crispy
|
e2cbabbde2ca7bb1850732302f9c48986763a40d
|
torch/audio/benchmark.lua
|
torch/audio/benchmark.lua
|
require 'sys'
require 'cunn'
require 'cudnn'
require 'nnx'
require 'BatchBRNNReLU'
require 'SequenceWise'
require 'Dataset'
cudnn.fastest = true
cudnn.benchmark = false -- set this false due to the varying input shape
cudnn.verbose = false
nGPU = 4
deepSpeech = require 'cudnn_deepspeech2'
print('Running on device: ' .. cutorch.getDeviceProperties(cutorch.getDevice()).name)
steps = 1 -- nb of steps in loop to average perf
nDryRuns = 10
batchSize = 32
spectrogramSize = 161
criterion = nn.CTCCriterion():cuda()
local dataset = nn.DeepSpeechDataset(batchSize)
collectgarbage()
local model, model_name, calculateInputSizes = deepSpeech(batchSize, dataset.freqBins, nGPU)
local inputs = torch.CudaTensor() -- buffer for inputs
local sizes, input, targets = dataset:nextTorchSet()
model = model:cuda()
inputs:resize(input:size()):copy(input)
print('ModelType: ' .. model_name, 'Kernels: ' .. 'cuDNN')
-- dry-run
for i = 1, nDryRuns do
model:zeroGradParameters()
local output = model:updateOutput(inputs)
local gradInput = model:updateGradInput(inputs, output)
model:accGradParameters(inputs, output)
cutorch.synchronize()
collectgarbage()
end
local tmf, tmbi, tmbg, tRoundTrip = 0, 0, 0, 0
local ok = 1
for t = 1, steps do
local roundTripTimer = torch.Timer()
dataset = nn.DeepSpeechDataset(batchSize)
local numberOfIterations = 0
local sizes, input, targets = dataset:nextTorchSet()
while (sizes ~= nil) do
inputs:resize(input:size()):copy(input)
sys.tic()
-- Forward through model and then criterion.
local output = model:updateOutput(inputs)
loss = criterion:updateOutput(output, targets, calculateInputSizes(sizes))
tmf = tmf + sys.toc()
cutorch.synchronize()
-- Backwards (updateGradInput, accGradParameters) including the criterion.
sys.tic()
grads = criterion:updateGradInput(output, targets)
model:updateGradInput(inputs, output)
tmbi = tmbi + sys.toc()
cutorch.synchronize()
collectgarbage()
sys.tic()
ok = pcall(function() model:accGradParameters(inputs, output) end)
tmbg = tmbg + sys.toc()
cutorch.synchronize()
sizes, input, targets = dataset:nextTorchSet()
numberOfIterations = numberOfIterations + 1
xlua.progress(numberOfIterations * batchSize, dataset.size)
end
-- Divide the times to work out average time for updateOutput/updateGrad/accGrad
tmf = tmf / numberOfIterations
tmbi = tmbi / numberOfIterations
tmbg = tmbi / numberOfIterations
-- Add time taken for round trip of 1 epoch
tRoundTrip = tRoundTrip + roundTripTimer:time().real
end
tmf = tmf / steps
tmbi = tmbi / steps
tmbg = tmbi / steps
tRoundTrip = tRoundTrip / steps
print(string.format("%-30s %25s %10.2f", 'cuDNN', ':updateOutput() (ms):', tmf * 1000))
print(string.format("%-30s %25s %10.2f", 'cuDNN', ':updateGradInput() (ms):', tmbi * 1000))
if not ok then
print(string.format("%-30s %25s %s", 'cuDNN', ':accGradParameters() (ms):', 'FAILED!'))
else
print(string.format("%-30s %25s %10.2f", 'cuDNN', ':accGradParameters() (ms):', tmbg * 1000))
end
print(string.format("%-30s %25s %10.2f", 'cuDNN', ':Forward (ms):', (tmf) * 1000))
print(string.format("%-30s %25s %10.2f", 'cuDNN', ':Backward (ms):', (tmbi + tmbg) * 1000))
print(string.format("%-30s %25s %10.2f", 'cuDNN', ':TOTAL (ms):', (tmf + tmbi + tmbg) * 1000))
print(string.format("%-30s %25s %10.2f", 'cuDNN', ':Samples processed:', dataset.size))
print(string.format("%-30s %25s %10.2f", 'cuDNN', ':Samples per second:', dataset.size / tRoundTrip))
print(string.format("%-30s %25s %10.2f", 'cuDNN', ':Seconds of audio processed per second:', dataset.duration / tRoundTrip))
print(string.format("%-30s %25s %10.2f", 'cuDNN', ':EPOCH TIME (s):', tRoundTrip))
print()
print('')
|
require 'sys'
require 'cunn'
require 'cudnn'
require 'nnx'
require 'BatchBRNNReLU'
require 'SequenceWise'
require 'Dataset'
cudnn.fastest = true
cudnn.benchmark = false -- set this false due to the varying input shape
cudnn.verbose = false
nGPU = 4
deepSpeech = require 'cudnn_deepspeech2'
print('Running on device: ' .. cutorch.getDeviceProperties(cutorch.getDevice()).name)
steps = 1 -- nb of steps in loop to average perf
nDryRuns = 10
batchSize = 32
spectrogramSize = 161
criterion = nn.CTCCriterion():cuda()
local dataset = nn.DeepSpeechDataset(batchSize)
collectgarbage()
local model, model_name, calculateInputSizes = deepSpeech(batchSize, dataset.freqBins, nGPU)
local inputs = torch.CudaTensor() -- buffer for inputs
local sizes, input, targets = dataset:nextTorchSet()
model = model:cuda()
inputs:resize(input:size()):copy(input)
print('ModelType: ' .. model_name, 'Kernels: ' .. 'cuDNN')
-- dry-run
for i = 1, nDryRuns do
model:zeroGradParameters()
local output = model:updateOutput(inputs)
local gradInput = model:updateGradInput(inputs, output)
model:accGradParameters(inputs, output)
cutorch.synchronize()
collectgarbage()
end
local tmfAvg, tmbiAvg, tmbgAvg, tRoundTripAvg = 0,0,0,0
local ok = 1
for t = 1, steps do
local tmf, tmbi, tmbg, tRoundTrip = 0, 0, 0, 0
local roundTripTimer = torch.Timer()
dataset = nn.DeepSpeechDataset(batchSize)
local numberOfIterations = 0
local sizes, input, targets = dataset:nextTorchSet()
while (sizes ~= nil) do
inputs:resize(input:size()):copy(input)
sys.tic()
-- Forward through model and then criterion.
local output = model:updateOutput(inputs)
loss = criterion:updateOutput(output, targets, calculateInputSizes(sizes))
tmf = tmf + sys.toc()
cutorch.synchronize()
-- Backwards (updateGradInput, accGradParameters) including the criterion.
sys.tic()
grads = criterion:updateGradInput(output, targets)
model:updateGradInput(inputs, output)
tmbi = tmbi + sys.toc()
cutorch.synchronize()
collectgarbage()
sys.tic()
ok = pcall(function() model:accGradParameters(inputs, output) end)
tmbg = tmbg + sys.toc()
cutorch.synchronize()
sizes, input, targets = dataset:nextTorchSet()
numberOfIterations = numberOfIterations + 1
xlua.progress(numberOfIterations * batchSize, dataset.size)
end
-- Divide the times to work out average time for updateOutput/updateGrad/accGrad
tmfAvg = tmfAvg + tmf / numberOfIterations
tmbiAvg = tmbiAvg + tmbi / numberOfIterations
tmbgAvg = tmbgAvg + tmbg / numberOfIterations
-- Add time taken for round trip of 1 epoch
tRoundTripAvg = tRoundTripAvg + roundTripTimer:time().real
end
local tmf = tmfAvg / steps
local tmbi = tmbiAvg / steps
local tmbg = tmbgAvg / steps
local tRoundTrip = tRoundTripAvg / steps
print(string.format("%-30s %25s %10.2f", 'cuDNN', ':updateOutput() (ms):', tmf * 1000))
print(string.format("%-30s %25s %10.2f", 'cuDNN', ':updateGradInput() (ms):', tmbi * 1000))
if not ok then
print(string.format("%-30s %25s %s", 'cuDNN', ':accGradParameters() (ms):', 'FAILED!'))
else
print(string.format("%-30s %25s %10.2f", 'cuDNN', ':accGradParameters() (ms):', tmbg * 1000))
end
print(string.format("%-30s %25s %10.2f", 'cuDNN', ':Forward (ms):', (tmf) * 1000))
print(string.format("%-30s %25s %10.2f", 'cuDNN', ':Backward (ms):', (tmbi + tmbg) * 1000))
print(string.format("%-30s %25s %10.2f", 'cuDNN', ':TOTAL (ms):', (tmf + tmbi + tmbg) * 1000))
print(string.format("%-30s %25s %10.2f", 'cuDNN', ':Samples processed:', dataset.size))
print(string.format("%-30s %25s %10.2f", 'cuDNN', ':Samples per second:', dataset.size / tRoundTrip))
print(string.format("%-30s %25s %10.2f", 'cuDNN', ':Seconds of audio processed per second:', dataset.duration / tRoundTrip))
print(string.format("%-30s %25s %10.2f", 'cuDNN', ':EPOCH TIME (s):', tRoundTrip))
print()
print('')
|
Fix averaging, correct a couple tmbi => tmbg typos
|
Fix averaging, correct a couple tmbi => tmbg typos
With the current averaging, the more steps are done, the lower the averages become. Proposed PR fixes that.
|
Lua
|
apache-2.0
|
DeepMark/deepmark
|
3f754137f1eadded42011be782641a0f3bb72fb7
|
premake4.lua
|
premake4.lua
|
if not _ACTION then
_ACTION="vs2010"
end
isPosix = false
isVisualStudio = false
isOSX = false
if _ACTION == "vs2002" or _ACTION == "vs2003" or _ACTION == "vs2005" or _ACTION == "vs2008" or _ACTION == "vs2010" then
isVisualStudio = true
end
if _ACTION == "codeblocks" or _ACTION == "gmake"
then
isPosix = true
end
if _ACTION == "xcode3" or os.is("macosx")
then
isOSX = true
end
solution "TaskScheduler"
language "C++"
location ( "Build/" .. _ACTION )
flags {"NoManifest", "ExtraWarnings", "StaticRuntime", "NoMinimalRebuild", "FloatFast", "EnableSSE2" }
optimization_flags = { "OptimizeSpeed" }
targetdir("Bin")
if isPosix or isOSX then
defines { "_XOPEN_SOURCE=600" }
end
if isVisualStudio then
debugdir ("Bin")
end
local config_list = {
"Release",
"Debug",
"Instrumented_Release",
"Instrumented_Debug"
}
local platform_list = {
"x32",
"x64"
}
configurations(config_list)
platforms(platform_list)
-- CONFIGURATIONS
configuration "Instrumented_Release"
defines { "NDEBUG", "MT_INSTRUMENTED_BUILD", "MT_UNICODE" }
flags { "Symbols", optimization_flags }
configuration "Instrumented_Debug"
defines { "_DEBUG", "_CRTDBG_MAP_ALLOC", "MT_INSTRUMENTED_BUILD", "MT_UNICODE" }
flags { "Symbols" }
configuration "Release"
defines { "NDEBUG", "MT_UNICODE" }
flags { "Symbols", optimization_flags }
configuration "Debug"
defines { "_DEBUG", "_CRTDBG_MAP_ALLOC", "MT_UNICODE"}
flags { "Symbols" }
configuration "x32"
if isVisualStudio then
buildoptions { "/wd4127" }
else
buildoptions { "-std=c++11" }
if isPosix then
linkoptions { "-rdynamic" }
if isOSX then
buildoptions { "-Wno-invalid-offsetof -Wno-deprecated-declarations -fsanitize=address -fno-omit-frame-pointer" }
linkoptions { "-fsanitize=address" }
else
-- defines { "MT_THREAD_SANITIZER"}
buildoptions { "-Wno-invalid-offsetof -fsanitize=memory -fsanitize-memory-track-origins -fPIE -g -fno-omit-frame-pointer" }
linkoptions { "-fsanitize=memory -static-libtsan -pie" }
end
end
end
configuration "x64"
if isVisualStudio then
buildoptions { "/wd4127" }
else
buildoptions { "-std=c++11" }
if isPosix then
linkoptions { "-rdynamic" }
if isOSX then
buildoptions { "-Wno-invalid-offsetof -Wno-deprecated-declarations -fsanitize=address -fno-omit-frame-pointer" }
linkoptions { "-fsanitize=address" }
else
-- defines { "MT_THREAD_SANITIZER"}
buildoptions { "-Wno-invalid-offsetof -fsanitize=memory -fsanitize-memory-track-origins -fPIE -g -fno-omit-frame-pointer" }
linkoptions { "-fsanitize=memory -static-libtsan -pie" }
end
end
end
-- give each configuration/platform a unique output directory
for _, config in ipairs(config_list) do
for _, plat in ipairs(platform_list) do
configuration { config, plat }
objdir ( "Build/" .. _ACTION .. "/tmp/" .. config .. "-" .. plat )
end
end
os.mkdir("./Bin")
-- SUBPROJECTS
project "UnitTest++"
kind "StaticLib"
defines { "_CRT_SECURE_NO_WARNINGS" }
files {
"TestFramework/UnitTest++/**.cpp",
"TestFramework/UnitTest++/**.h",
}
if isPosix or isOSX then
excludes { "TestFramework/UnitTest++/Win32/**.*" }
else
excludes { "TestFramework/UnitTest++/Posix/**.*" }
end
project "Squish"
kind "StaticLib"
defines { "_CRT_SECURE_NO_WARNINGS" }
files {
"Squish/**.*",
}
includedirs
{
"Squish"
}
project "TaskScheduler"
kind "StaticLib"
flags {"NoPCH"}
files {
"Scheduler/**.*",
}
includedirs
{
"Squish", "Scheduler/Include", "TestFramework/UnitTest++"
}
if isPosix or isOSX then
excludes { "Src/Platform/Windows/**.*" }
else
excludes { "Src/Platform/Posix/**.*" }
end
project "Tests"
flags {"NoPCH"}
kind "ConsoleApp"
files {
"Tests/**.*",
}
includedirs
{
"Squish", "Scheduler/Include", "TestFramework/UnitTest++"
}
if isPosix or isOSX then
excludes { "Src/Platform/Windows/**.*" }
else
excludes { "Src/Platform/Posix/**.*" }
end
links {
"UnitTest++", "Squish", "TaskScheduler"
}
if isPosix or isOSX then
links { "pthread" }
end
|
if not _ACTION then
_ACTION="vs2010"
end
isPosix = false
isVisualStudio = false
isOSX = false
if _ACTION == "vs2002" or _ACTION == "vs2003" or _ACTION == "vs2005" or _ACTION == "vs2008" or _ACTION == "vs2010" then
isVisualStudio = true
end
if _ACTION == "codeblocks" or _ACTION == "gmake"
then
isPosix = true
end
if _ACTION == "xcode3" or os.is("macosx")
then
isOSX = true
end
solution "TaskScheduler"
language "C++"
location ( "Build/" .. _ACTION )
flags {"NoManifest", "ExtraWarnings", "StaticRuntime", "NoMinimalRebuild", "FloatFast", "EnableSSE2" }
optimization_flags = { "OptimizeSpeed" }
targetdir("Bin")
if isPosix or isOSX then
defines { "_XOPEN_SOURCE=600" }
end
if isVisualStudio then
debugdir ("Bin")
end
local config_list = {
"Release",
"Debug",
"Instrumented_Release",
"Instrumented_Debug"
}
local platform_list = {
"x32",
"x64"
}
configurations(config_list)
platforms(platform_list)
-- CONFIGURATIONS
configuration "Instrumented_Release"
defines { "NDEBUG", "MT_INSTRUMENTED_BUILD", "MT_UNICODE" }
flags { "Symbols", optimization_flags }
configuration "Instrumented_Debug"
defines { "_DEBUG", "_CRTDBG_MAP_ALLOC", "MT_INSTRUMENTED_BUILD", "MT_UNICODE" }
flags { "Symbols" }
configuration "Release"
defines { "NDEBUG", "MT_UNICODE" }
flags { "Symbols", optimization_flags }
configuration "Debug"
defines { "_DEBUG", "_CRTDBG_MAP_ALLOC", "MT_UNICODE"}
flags { "Symbols" }
configuration "x32"
if isVisualStudio then
buildoptions { "/wd4127" }
else
buildoptions { "-std=c++11" }
if isPosix then
linkoptions { "-rdynamic" }
if isOSX then
buildoptions { "-Wno-invalid-offsetof -Wno-deprecated-declarations -fsanitize=address -fno-omit-frame-pointer" }
linkoptions { "-fsanitize=address" }
else
-- defines { "MT_THREAD_SANITIZER"}
buildoptions { "-Wno-invalid-offsetof -fsanitize=memory -fPIE -g -fno-omit-frame-pointer" }
linkoptions { "-fsanitize=memory -static-libtsan -pie" }
end
end
end
configuration "x64"
if isVisualStudio then
buildoptions { "/wd4127" }
else
buildoptions { "-std=c++11" }
if isPosix then
linkoptions { "-rdynamic" }
if isOSX then
buildoptions { "-Wno-invalid-offsetof -Wno-deprecated-declarations -fsanitize=address -fno-omit-frame-pointer" }
linkoptions { "-fsanitize=address" }
else
-- defines { "MT_THREAD_SANITIZER"}
buildoptions { "-Wno-invalid-offsetof -fsanitize=memory -fPIE -g -fno-omit-frame-pointer" }
linkoptions { "-fsanitize=memory -static-libtsan -pie" }
end
end
end
-- give each configuration/platform a unique output directory
for _, config in ipairs(config_list) do
for _, plat in ipairs(platform_list) do
configuration { config, plat }
objdir ( "Build/" .. _ACTION .. "/tmp/" .. config .. "-" .. plat )
end
end
os.mkdir("./Bin")
-- SUBPROJECTS
project "UnitTest++"
kind "StaticLib"
defines { "_CRT_SECURE_NO_WARNINGS" }
files {
"TestFramework/UnitTest++/**.cpp",
"TestFramework/UnitTest++/**.h",
}
if isPosix or isOSX then
excludes { "TestFramework/UnitTest++/Win32/**.*" }
else
excludes { "TestFramework/UnitTest++/Posix/**.*" }
end
project "Squish"
kind "StaticLib"
defines { "_CRT_SECURE_NO_WARNINGS" }
files {
"Squish/**.*",
}
includedirs
{
"Squish"
}
project "TaskScheduler"
kind "StaticLib"
flags {"NoPCH"}
files {
"Scheduler/**.*",
}
includedirs
{
"Squish", "Scheduler/Include", "TestFramework/UnitTest++"
}
if isPosix or isOSX then
excludes { "Src/Platform/Windows/**.*" }
else
excludes { "Src/Platform/Posix/**.*" }
end
project "Tests"
flags {"NoPCH"}
kind "ConsoleApp"
files {
"Tests/**.*",
}
includedirs
{
"Squish", "Scheduler/Include", "TestFramework/UnitTest++"
}
if isPosix or isOSX then
excludes { "Src/Platform/Windows/**.*" }
else
excludes { "Src/Platform/Posix/**.*" }
end
links {
"UnitTest++", "Squish", "TaskScheduler"
}
if isPosix or isOSX then
links { "pthread" }
end
|
Fixed GCC ASAN compiler options
|
Fixed GCC ASAN compiler options
|
Lua
|
mit
|
galek/TaskScheduler,galek/TaskScheduler,SergeyMakeev/TaskScheduler,galek/TaskScheduler,SergeyMakeev/TaskScheduler
|
6f1aaf469a894728300b693a7fe843ba091e55c9
|
premake4.lua
|
premake4.lua
|
--
-- Premake 5.x build configuration script
-- Use this script to configure the project with Premake4.
--
--
-- Define the project. Put the release configuration first so it will be the
-- default when folks build using the makefile. That way they don't have to
-- worry about the /scripts argument and all that.
--
solution "Premake5"
configurations { "Release", "Debug" }
location ( _OPTIONS["to"] )
project "Premake5"
targetname "premake5"
language "C"
kind "ConsoleApp"
flags { "No64BitChecks", "ExtraWarnings", "StaticRuntime" }
includedirs { "src/host/lua/src" }
files
{
"*.txt", "**.lua",
"src/**.h", "src/**.c",
"src/host/scripts.c"
}
excludes
{
"src/host/lua/src/lauxlib.c",
"src/host/lua/src/lua.c",
"src/host/lua/src/luac.c",
"src/host/lua/src/print.c",
"src/host/lua/**.lua",
"src/host/lua/etc/*.c"
}
configuration "Debug"
targetdir "bin/debug"
defines "_DEBUG"
flags { "Symbols" }
configuration "Release"
targetdir "bin/release"
defines "NDEBUG"
flags { "OptimizeSize" }
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "vs2005"
defines {"_CRT_SECURE_NO_DEPRECATE" }
configuration "windows"
links { "ole32" }
configuration "linux or bsd or hurd"
defines { "LUA_USE_POSIX", "LUA_USE_DLOPEN" }
links { "m" }
linkoptions { "-rdynamic" }
configuration "linux or hurd"
links { "dl", "rt" }
configuration "macosx"
defines { "LUA_USE_MACOSX" }
links { "CoreServices.framework" }
configuration { "macosx", "gmake" }
-- toolset "clang" (not until a 5.0 binary is available)
buildoptions { "-mmacosx-version-min=10.4" }
linkoptions { "-mmacosx-version-min=10.4" }
configuration { "solaris" }
linkoptions { "-Wl,--export-dynamic" }
configuration "aix"
defines { "LUA_USE_POSIX", "LUA_USE_DLOPEN" }
links { "m" }
--
-- A more thorough cleanup.
--
if _ACTION == "clean" then
os.rmdir("bin")
os.rmdir("build")
end
--
-- Use the --to=path option to control where the project files get generated. I use
-- this to create project files for each supported toolset, each in their own folder,
-- in preparation for deployment.
--
newoption {
trigger = "to",
value = "path",
description = "Set the output location for the generated files"
}
--
-- This new embed action is slightly hardcoded for the 4.x executable, and is
-- really only intended to get folks bootstrapped on to 5.x
--
newaction {
trigger = "embed",
description = "Embed scripts in scripts.c; required before release builds",
execute = function ()
_MAIN_SCRIPT_DIR = os.getcwd()
_SCRIPT_DIR = path.join(_MAIN_SCRIPT_DIR, "scripts")
dofile("scripts/embed.lua")
end
}
|
--
-- Premake 5.x build configuration script
-- Use this script to configure the project with Premake4.
--
--
-- Define the project. Put the release configuration first so it will be the
-- default when folks build using the makefile. That way they don't have to
-- worry about the /scripts argument and all that.
--
solution "Premake5"
configurations { "Release", "Debug" }
location ( _OPTIONS["to"] )
project "Premake5"
targetname "premake5"
language "C"
kind "ConsoleApp"
defines { "PREMAKE_NO_BUILTIN_SCRIPTS" }
flags { "No64BitChecks", "ExtraWarnings", "StaticRuntime" }
includedirs { "contrib/lua/src" }
files
{
"*.txt", "**.lua",
"contrib/lua/src/*.c", "contrib/lua/src/*.h",
"src/host/*.c"
}
excludes
{
"contrib/lua/src/lauxlib.c",
"contrib/lua/src/lua.c",
"contrib/lua/src/luac.c",
"contrib/lua/src/print.c",
"contrib/lua/**.lua",
"contrib/lua/etc/*.c"
}
configuration "Debug"
targetdir "bin/debug"
defines "_DEBUG"
flags { "Symbols" }
configuration "Release"
targetdir "bin/release"
defines "NDEBUG"
flags { "OptimizeSize" }
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "vs2005"
defines {"_CRT_SECURE_NO_DEPRECATE" }
configuration "windows"
links { "ole32" }
configuration "linux or bsd or hurd"
defines { "LUA_USE_POSIX", "LUA_USE_DLOPEN" }
links { "m" }
linkoptions { "-rdynamic" }
configuration "linux or hurd"
links { "dl", "rt" }
configuration "macosx"
defines { "LUA_USE_MACOSX" }
links { "CoreServices.framework" }
configuration { "macosx", "gmake" }
-- toolset "clang" (not until a 5.0 binary is available)
buildoptions { "-mmacosx-version-min=10.4" }
linkoptions { "-mmacosx-version-min=10.4" }
configuration { "solaris" }
linkoptions { "-Wl,--export-dynamic" }
configuration "aix"
defines { "LUA_USE_POSIX", "LUA_USE_DLOPEN" }
links { "m" }
--
-- A more thorough cleanup.
--
if _ACTION == "clean" then
os.rmdir("bin")
os.rmdir("build")
end
--
-- Use the --to=path option to control where the project files get generated. I use
-- this to create project files for each supported toolset, each in their own folder,
-- in preparation for deployment.
--
newoption {
trigger = "to",
value = "path",
description = "Set the output location for the generated files"
}
--
-- This new embed action is slightly hardcoded for the 4.x executable, and is
-- really only intended to get folks bootstrapped on to 5.x
--
newaction {
trigger = "embed",
description = "Embed scripts in scripts.c; required before release builds",
execute = function ()
_MAIN_SCRIPT_DIR = os.getcwd()
_SCRIPT_DIR = path.join(_MAIN_SCRIPT_DIR, "scripts")
dofile("scripts/embed.lua")
end
}
|
Fix premake4.lua bootstrap build script
|
Fix premake4.lua bootstrap build script
|
Lua
|
bsd-3-clause
|
soundsrc/premake-core,resetnow/premake-core,mendsley/premake-core,noresources/premake-core,bravnsgaard/premake-core,starkos/premake-core,noresources/premake-core,mandersan/premake-core,aleksijuvani/premake-core,tvandijck/premake-core,jstewart-amd/premake-core,TurkeyMan/premake-core,premake/premake-core,noresources/premake-core,Blizzard/premake-core,Zefiros-Software/premake-core,TurkeyMan/premake-core,aleksijuvani/premake-core,jstewart-amd/premake-core,aleksijuvani/premake-core,bravnsgaard/premake-core,dcourtois/premake-core,bravnsgaard/premake-core,Zefiros-Software/premake-core,premake/premake-core,starkos/premake-core,aleksijuvani/premake-core,mendsley/premake-core,noresources/premake-core,mandersan/premake-core,jstewart-amd/premake-core,sleepingwit/premake-core,Blizzard/premake-core,dcourtois/premake-core,premake/premake-core,Zefiros-Software/premake-core,Blizzard/premake-core,sleepingwit/premake-core,Zefiros-Software/premake-core,mandersan/premake-core,noresources/premake-core,mendsley/premake-core,Blizzard/premake-core,LORgames/premake-core,tvandijck/premake-core,mandersan/premake-core,mendsley/premake-core,premake/premake-core,TurkeyMan/premake-core,premake/premake-core,TurkeyMan/premake-core,noresources/premake-core,Zefiros-Software/premake-core,tvandijck/premake-core,sleepingwit/premake-core,LORgames/premake-core,jstewart-amd/premake-core,resetnow/premake-core,dcourtois/premake-core,starkos/premake-core,LORgames/premake-core,premake/premake-core,sleepingwit/premake-core,resetnow/premake-core,tvandijck/premake-core,dcourtois/premake-core,mendsley/premake-core,tvandijck/premake-core,starkos/premake-core,resetnow/premake-core,dcourtois/premake-core,soundsrc/premake-core,starkos/premake-core,mandersan/premake-core,starkos/premake-core,soundsrc/premake-core,soundsrc/premake-core,soundsrc/premake-core,premake/premake-core,jstewart-amd/premake-core,bravnsgaard/premake-core,noresources/premake-core,bravnsgaard/premake-core,Blizzard/premake-core,LORgames/premake-core,resetnow/premake-core,LORgames/premake-core,dcourtois/premake-core,TurkeyMan/premake-core,starkos/premake-core,aleksijuvani/premake-core,Blizzard/premake-core,dcourtois/premake-core,sleepingwit/premake-core
|
45bbaab8b2467950cb1e7f7b012d0fdbf2257b75
|
jwt.lua
|
jwt.lua
|
local encode = function(payload, key)
header = { typ='JWT', alg="HS256" }
segments = {
urlsafeB64Encode(jsonEncode(header)),
urlsafeB64Encode(jsonEncode(payload))
}
signing_input = table.concat(segments, ".")
signature = sign(signing_input, key)
segments[#segments+1] = urlsafeB64Encode(signature)
return table.concat(segments, ".")
end
local sign = function(msg, key)
return crypto.hmac(key, msg, crypto.sha256).digest()
end
local jsonEncode = function(input)
result = json.stringify(input)
return result
end
local urlsafeB64Encode = function(input)
result = base64.encode(input)
result = string.gsub(result, "+", "-")
result = string.gsub(result, "/", "_")
result = string.gsub(result, "=", "")
return result
end
return { encode = encode }
|
local encode = function(payload, key)
header = { typ='JWT', alg="HS256" }
segments = {
urlsafeB64Encode(jsonEncode(header)),
urlsafeB64Encode(jsonEncode(payload))
}
signing_input = table.concat(segments, ".")
signature = sign(signing_input, key)
segments[#segments+1] = urlsafeB64Encode(signature)
return table.concat(segments, ".")
end
function sign(msg, key)
return crypto.hmac(key, msg, crypto.sha256).digest()
end
function jsonEncode(input)
result = json.stringify(input)
return result
end
function urlsafeB64Encode(input)
result = base64.encode(input)
result = string.gsub(result, "+", "-")
result = string.gsub(result, "/", "_")
result = string.gsub(result, "=", "")
return result
end
return { encode = encode }
|
Fixing reference
|
Fixing reference
|
Lua
|
bsd-3-clause
|
thejeshgn/lib,robertbrook/lib
|
e8d1c642fb12c894438e3897b7fe677d9a74c7fb
|
premake5.lua
|
premake5.lua
|
-- The _ACTION variable can be null, which will be annoying.
-- Let's make a action that won't be null
action = _ACTION or ""
-- New option to control if the chirp library should be built
-- as a shared or static library
newoption {
trigger = "shared",
description = "Generate projects for shared library (default: no)",
value = "yes/no",
allowed = {
{ "yes", "Shared library" },
{ "no", "Static library" }
}
}
-- The test solution
solution "chirp"
location ( "build/" .. action )
configurations { "debug", "release" }
warnings "Extra"
flags { "FatalWarnings" }
-- Add some flags for gmake builds
if _ACTION == "gmake" then
buildoptions { "-Wall" }
buildoptions { "-std=c++11" }
end
-- Provide a default for the "shared" option
if not _OPTIONS["shared"] then
_OPTIONS["shared"] = "no"
end
-- Since premake doesn't implement the clean command
-- on all platforms, we define our own
if action == "clean" then
os.rmdir("build")
os.rmdir("bin")
os.rmdir("lib")
end
-- Debug configuration
filter { "debug" }
targetdir ( "bin/" .. action .. "/debug" )
defines { "_DEBUG", "DEBUG" }
flags { "Symbols", "Unicode" }
libdirs { "lib/" .. action .. "/debug" }
filter {}
-- Release configuration
filter { "release" }
targetdir ( "bin/" .. action .. "/release" )
optimize ( "Full" )
defines { "NDEBUG" }
flags { "Unicode" }
libdirs { "lib/" .. action .. "/release" }
filter {}
-- Include the solution projects
include "tests"
include "chirp"
include "examples"
|
-- The _ACTION variable can be null, which will be annoying.
-- Let's make a action that won't be null
action = _ACTION or ""
-- New option to control if the chirp library should be built
-- as a shared or static library
newoption {
trigger = "shared",
description = "Generate projects for shared library (default: no)",
value = "yes/no",
allowed = {
{ "yes", "Shared library" },
{ "no", "Static library" }
}
}
-- The test solution
solution "chirp"
location ( "build/" .. action )
configurations { "debug", "release" }
warnings "Extra"
flags { "FatalWarnings" }
cppdialect "C++14"
-- Add some flags for gmake builds
if _ACTION == "gmake" then
buildoptions { "-Wall" }
end
-- Provide a default for the "shared" option
if not _OPTIONS["shared"] then
_OPTIONS["shared"] = "no"
end
-- Since premake doesn't implement the clean command
-- on all platforms, we define our own
if action == "clean" then
os.rmdir("build")
os.rmdir("bin")
os.rmdir("lib")
end
-- Debug configuration
filter { "debug" }
targetdir ( "bin/" .. action .. "/debug" )
defines { "_DEBUG", "DEBUG" }
characterset ("Unicode")
symbols "On"
libdirs { "lib/" .. action .. "/debug" }
filter {}
-- Release configuration
filter { "release" }
targetdir ( "bin/" .. action .. "/release" )
optimize ( "Full" )
defines { "NDEBUG" }
characterset ("Unicode")
libdirs { "lib/" .. action .. "/release" }
filter {}
-- Include the solution projects
include "tests"
include "chirp"
include "examples"
|
Fix premake config
|
Fix premake config
It should now produce buildable Makefile when issuing
`premake5 gmake`
|
Lua
|
apache-2.0
|
fr00b0/chirp
|
c8c1c972d47b55e5c9b0108942ada51065d1375e
|
contrib/package/ffluci-splash/src/luci-splash.lua
|
contrib/package/ffluci-splash/src/luci-splash.lua
|
#!/usr/bin/lua
package.path = "/usr/lib/lua/?.lua;/usr/lib/lua/?/init.lua;" .. package.path
package.cpath = "/usr/lib/lua/?.so;" .. package.cpath
require("ffluci.http")
require("ffluci.sys")
require("ffluci.model.uci")
-- Init state session
uci = ffluci.model.uci.StateSession()
function main(argv)
local cmd = argv[1]
local arg = argv[2]
if not cmd then
print("Usage: " .. argv[0] .. " <status|add|remove|sync> [MAC]")
os.exit(1)
elseif cmd == "status" then
if not arg then
os.exit(1)
end
if iswhitelisted(arg) then
print("whitelisted")
os.exit(0)
end
if haslease(arg) then
print("lease")
os.exit(0)
end
print("unknown")
os.exit(0)
elseif cmd == "add" then
if not arg then
os.exit(1)
end
if not haslease(arg) then
add_lease(arg)
else
print("already leased!")
os.exit(2)
end
os.exit(0)
elseif cmd == "remove" then
if not cmd[2] then
os.exit(1)
end
remove_lease(arg)
os.exit(0)
elseif cmd == "sync" then
sync()
os.exit(0)
end
end
-- Add a lease to state and invoke add_rule
function add_lease(mac)
local key = uci:add("luci_splash", "lease")
uci:set("luci_splash", key, "mac", mac)
uci:set("luci_splash", key, "start", os.time())
add_rule(mac)
end
-- Remove a lease from state and invoke remove_rule
function remove_lease(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v.mac:lower() == mac then
remove_rule(mac)
uci:del("luci_splash", k)
end
end
end
-- Add an iptables rule
function add_rule(mac)
return os.execute("iptables -t nat -I luci_splash_leases -m mac --mac-source '"..mac.."' -j RETURN")
end
-- Remove an iptables rule
function remove_rule(mac)
return os.execute("iptables -t nat -D luci_splash_leases -m mac --mac-source '"..mac.."' -j RETURN")
end
-- Check whether a MAC-Address is listed in the lease state list
function haslease(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v[".type"] == "lease" and v.mac and v.mac:lower() == mac then
return true
end
end
return false
end
-- Check whether a MAC-Address is whitelisted
function iswhitelisted(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v[".type"] == "whitelist" and v.mac and v.mac:lower() == mac then
return true
end
end
return false
end
-- Returns a list of MAC-Addresses for which a rule is existing
function listrules()
local cmd = "iptables -t nat -L luci_splash_leases | grep RETURN |"
cmd = cmd .. "egrep -io [0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+"
return ffluci.util.split(ffluci.sys.exec(cmd))
end
-- Synchronise leases, remove abandoned rules
function sync()
local written = {}
local time = os.time()
-- Current leases in state files
local leases = uci:show("luci_splash").luci_splash
-- Convert leasetime to seconds
local leasetime = tonumber(uci:get("luci_splash", "general", "leasetime")) * 3600
-- Clean state file
uci:revert("luci_splash")
-- For all leases
for k, v in pairs(uci:show("luci_splash")) do
if v[".type"] == "lease" then
if os.difftime(time, tonumber(v.start)) > leasetime then
-- Remove expired
remove_rule(v.mac)
else
-- Rewrite state
local n = uci:add("luci_splash", "lease")
uci:set("luci_splash", n, "mac", v.mac)
uci:set("luci_splash", n, "start", v.start)
written[v.mac:lower()] = 1
end
end
end
-- Delete rules without state
for i, r in ipairs(listrules()) do
if #r > 0 and not written[r:lower()] then
remove_rule(r)
end
end
end
main(arg)
|
#!/usr/bin/lua
package.path = "/usr/lib/lua/?.lua;/usr/lib/lua/?/init.lua;" .. package.path
package.cpath = "/usr/lib/lua/?.so;" .. package.cpath
require("ffluci.http")
require("ffluci.sys")
require("ffluci.model.uci")
-- Init state session
uci = ffluci.model.uci.StateSession()
function main(argv)
local cmd = argv[1]
local arg = argv[2]
if cmd == "status" then
if not arg then
os.exit(1)
end
if iswhitelisted(arg) then
print("whitelisted")
os.exit(0)
end
if haslease(arg) then
print("lease")
os.exit(0)
end
print("unknown")
os.exit(0)
elseif cmd == "add" then
if not arg then
os.exit(1)
end
if not haslease(arg) then
add_lease(arg)
else
print("already leased!")
os.exit(2)
end
os.exit(0)
elseif cmd == "remove" then
if not arg then
os.exit(1)
end
remove_lease(arg)
os.exit(0)
elseif cmd == "sync" then
sync()
os.exit(0)
else
print("Usage: " .. argv[0] .. " <status|add|remove|sync> [MAC]")
os.exit(1)
end
end
-- Add a lease to state and invoke add_rule
function add_lease(mac)
local key = uci:add("luci_splash", "lease")
uci:set("luci_splash", key, "mac", mac)
uci:set("luci_splash", key, "start", os.time())
add_rule(mac)
end
-- Remove a lease from state and invoke remove_rule
function remove_lease(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v.mac:lower() == mac then
remove_rule(mac)
uci:del("luci_splash", k)
end
end
end
-- Add an iptables rule
function add_rule(mac)
return os.execute("iptables -t nat -I luci_splash_leases -m mac --mac-source '"..mac.."' -j RETURN")
end
-- Remove an iptables rule
function remove_rule(mac)
return os.execute("iptables -t nat -D luci_splash_leases -m mac --mac-source '"..mac.."' -j RETURN")
end
-- Check whether a MAC-Address is listed in the lease state list
function haslease(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v[".type"] == "lease" and v.mac and v.mac:lower() == mac then
return true
end
end
return false
end
-- Check whether a MAC-Address is whitelisted
function iswhitelisted(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v[".type"] == "whitelist" and v.mac and v.mac:lower() == mac then
return true
end
end
return false
end
-- Returns a list of MAC-Addresses for which a rule is existing
function listrules()
local cmd = "iptables -t nat -L luci_splash_leases | grep RETURN |"
cmd = cmd .. "egrep -io [0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+"
return ffluci.util.split(ffluci.sys.exec(cmd))
end
-- Synchronise leases, remove abandoned rules
function sync()
local written = {}
local time = os.time()
-- Current leases in state files
local leases = uci:show("luci_splash").luci_splash
-- Convert leasetime to seconds
local leasetime = tonumber(uci:get("luci_splash", "general", "leasetime")) * 3600
-- Clean state file
uci:revert("luci_splash")
-- For all leases
for k, v in pairs(uci:show("luci_splash")) do
if v[".type"] == "lease" then
if os.difftime(time, tonumber(v.start)) > leasetime then
-- Remove expired
remove_rule(v.mac)
else
-- Rewrite state
local n = uci:add("luci_splash", "lease")
uci:set("luci_splash", n, "mac", v.mac)
uci:set("luci_splash", n, "start", v.start)
written[v.mac:lower()] = 1
end
end
end
-- Delete rules without state
for i, r in ipairs(listrules()) do
if #r > 0 and not written[r:lower()] then
remove_rule(r)
end
end
end
main(arg)
|
ffluci-splash: Minor fixes
|
ffluci-splash: Minor fixes
|
Lua
|
apache-2.0
|
deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci
|
7da965db8b8947a9073c7cdf7f3ffe0c080e329c
|
extension/script/backend/worker/eval/repl.lua
|
extension/script/backend/worker/eval/repl.lua
|
local source, level = ...
level = (level or 0) + 2
if _VERSION == "Lua 5.1" then
load = loadstring
function table.pack(...)
local t = {...}
t.n = select("#", ...)
return t
end
table.unpack = unpack
end
local f = assert(debug.getinfo(level,"f").func, "can't find function")
local args_name = {}
local args_value = {}
local locals = {}
do
local i = 1
while true do
local name, value = debug.getupvalue(f, i)
if name == nil then
break
end
if #name > 0 then
args_name[#args_name+1] = name
args_value[name] = value
end
i = i + 1
end
end
do
local i = 1
while true do
local name, value = debug.getlocal(level, i)
if name == nil then
break
end
if name:byte() ~= 40 then -- '('
args_name[#args_name+1] = name
args_value[name] = value
locals[#locals+1] = ("[%d]={%s},"):format(i,name)
end
i = i + 1
end
end
local full_source
if #args_name > 0 then
full_source = ([[
local $ARGS
return function(...)
$SOURCE
end,
function()
return {$LOCALS}
end
]]):gsub("%$(%w+)", {
ARGS = table.concat(args_name, ","),
SOURCE = source,
LOCALS = table.concat(locals),
})
else
full_source = ([[
return function(...)
$SOURCE
end,
function()
return {$LOCALS}
end
]]):gsub("%$(%w+)", {
SOURCE = source,
LOCALS = table.concat(locals),
})
end
local func, update = assert(load(full_source, '=(EVAL)'))()
do
local i = 1
while true do
local name = debug.getupvalue(func, i)
if name == nil then
break
end
debug.setupvalue(func, i, args_value[name])
i = i + 1
end
end
local rets
do
local vararg, v = debug.getlocal(level, -1)
if vararg then
local vargs = { v }
local i = 2
while true do
vararg, v = debug.getlocal(level, -i)
if vararg then
vargs[i] = v
else
break
end
i = i + 1
end
rets = table.pack(func(table.unpack(vargs)))
else
rets = table.pack(func())
end
end
for k,v in pairs(update()) do
debug.setlocal(level,k,v[1])
end
return table.unpack(rets)
|
local source, level = ...
level = (level or 0) + 2
if _VERSION == "Lua 5.1" then
load = loadstring
function table.pack(...)
local t = {...}
t.n = select("#", ...)
return t
end
table.unpack = unpack
end
local f = assert(debug.getinfo(level,"f").func, "can't find function")
local args_name = {}
local args_value = {}
local locals = {}
do
local i = 1
while true do
local name, value = debug.getupvalue(f, i)
if name == nil then
break
end
if #name > 0 then
args_name[#args_name+1] = name
args_value[name] = value
end
i = i + 1
end
end
do
local i = 1
while true do
local name, value = debug.getlocal(level, i)
if name == nil then
break
end
if name:byte() ~= 40 then -- '('
args_name[#args_name+1] = name
args_value[name] = value
locals[#locals+1] = ("%s={idx=%d, val=%s},"):format(name, i, name)
end
i = i + 1
end
end
local full_source
if #args_name > 0 then
full_source = ([[
local $ARGS
return function(...)
$SOURCE
end,
function()
return {$LOCALS}
end
]]):gsub("%$(%w+)", {
ARGS = table.concat(args_name, ","),
SOURCE = source,
LOCALS = table.concat(locals),
})
else
full_source = ([[
return function(...)
$SOURCE
end,
function()
return {$LOCALS}
end
]]):gsub("%$(%w+)", {
SOURCE = source,
LOCALS = table.concat(locals),
})
end
local func, update = assert(load(full_source, '=(EVAL)'))()
local found = {}
do
local i = 1
while true do
local name = debug.getupvalue(func, i)
if name == nil then
break
end
debug.setupvalue(func, i, args_value[name])
found[name] = true
i = i + 1
end
end
local rets
do
local vararg, v = debug.getlocal(level, -1)
if vararg then
local vargs = { v }
local i = 2
while true do
vararg, v = debug.getlocal(level, -i)
if vararg then
vargs[i] = v
else
break
end
i = i + 1
end
rets = table.pack(func(table.unpack(vargs)))
else
rets = table.pack(func())
end
end
for name, loc in pairs(update()) do
if found[name] then
debug.setlocal(level, loc.idx, loc.val)
end
end
return table.unpack(rets)
|
Fixes #123
|
Fixes #123
|
Lua
|
mit
|
actboy168/vscode-lua-debug,actboy168/vscode-lua-debug,actboy168/vscode-lua-debug
|
4c8ef614778fa33f22a8d67557e077524224417f
|
frontend/readhistory.lua
|
frontend/readhistory.lua
|
local DataStorage = require("datastorage")
local DocSettings = require("docsettings")
local dump = require("dump")
local joinPath = require("ffi/util").joinPath
local lfs = require("libs/libkoreader-lfs")
local realpath = require("ffi/util").realpath
local history_file = joinPath(DataStorage:getDataDir(), "history.lua")
local ReadHistory = {
hist = {},
last_read_time = 0,
}
local function buildEntry(input_time, input_file)
return {
time = input_time,
text = input_file:gsub(".*/", ""),
file = realpath(input_file) or input_file, -- keep orig file path of deleted files
dim = lfs.attributes(input_file, "mode") ~= "file", -- "dim", as expected by Menu
callback = function()
local ReaderUI = require("apps/reader/readerui")
ReaderUI:showReader(input_file)
end
}
end
local function fileFirstOrdering(l, r)
if l.file == r.file then
return l.time > r.time
else
return l.file < r.file
end
end
local function timeFirstOrdering(l, r)
if l.time == r.time then
return l.file < r.file
else
return l.time > r.time
end
end
function ReadHistory:_indexing(start)
assert(self ~= nil)
-- TODO(Hzj_jie): Use binary search to find an item when deleting it.
for i = start, #self.hist, 1 do
self.hist[i].index = i
end
end
function ReadHistory:_sort()
assert(self ~= nil)
local autoremove_deleted_items_from_history =
not G_reader_settings:nilOrFalse("autoremove_deleted_items_from_history")
if autoremove_deleted_items_from_history then
self:clearMissing()
end
table.sort(self.hist, fileFirstOrdering)
-- TODO(zijiehe): Use binary insert instead of a loop to deduplicate.
for i = #self.hist, 2, -1 do
if self.hist[i].file == self.hist[i - 1].file then
table.remove(self.hist, i)
end
end
table.sort(self.hist, timeFirstOrdering)
self:_indexing(1)
end
-- Reduces total count in hist list to a reasonable number by removing last
-- several items.
function ReadHistory:_reduce()
assert(self ~= nil)
while #self.hist > 500 do
table.remove(self.hist, #self.hist)
end
end
-- Flushes current history table into file.
function ReadHistory:_flush()
assert(self ~= nil)
local content = {}
for k, v in pairs(self.hist) do
content[k] = {
time = v.time,
file = v.file
}
end
local f = io.open(history_file, "w")
f:write("return " .. dump(content) .. "\n")
f:close()
end
--- Reads history table from file.
-- @treturn boolean true if the history_file has been updated and reloaded.
function ReadHistory:_read()
assert(self ~= nil)
local history_file_modification_time = lfs.attributes(history_file, "modification")
if history_file_modification_time == nil
or history_file_modification_time <= self.last_read_time then
return false
end
self.last_read_time = history_file_modification_time
local ok, data = pcall(dofile, history_file)
if ok and data then
for k, v in pairs(data) do
table.insert(self.hist, buildEntry(v.time, v.file))
end
end
return true
end
-- Reads history from legacy history folder
function ReadHistory:_readLegacyHistory()
assert(self ~= nil)
local history_dir = DataStorage:getHistoryDir()
for f in lfs.dir(history_dir) do
local path = joinPath(history_dir, f)
if lfs.attributes(path, "mode") == "file" then
path = DocSettings:getPathFromHistory(f)
if path ~= nil and path ~= "" then
local file = DocSettings:getNameFromHistory(f)
if file ~= nil and file ~= "" then
table.insert(
self.hist,
buildEntry(lfs.attributes(joinPath(history_dir, f), "modification"),
joinPath(path, file)))
end
end
end
end
end
function ReadHistory:_init()
assert(self ~= nil)
self:reload()
end
function ReadHistory:clearMissing()
assert(self ~= nil)
for i = #self.hist, 1, -1 do
if self.hist[i].file == nil or lfs.attributes(self.hist[i].file, "mode") ~= "file" then
table.remove(self.hist, i)
end
end
end
function ReadHistory:removeItemByPath(path)
assert(self ~= nil)
for i = #self.hist, 1, -1 do
if self.hist[i].file == path then
self:removeItem(self.hist[i])
break
end
end
end
function ReadHistory:updateItemByPath(old_path, new_path)
assert(self ~= nil)
for i = #self.hist, 1, -1 do
if self.hist[i].file == old_path then
self.hist[i].file = new_path
self:_flush()
self.hist[i].callback = function()
local ReaderUI = require("apps/reader/readerui")
ReaderUI:showReader(new_path)
end
break
end
end
end
function ReadHistory:removeItem(item)
assert(self ~= nil)
table.remove(self.hist, item.index)
os.remove(DocSettings:getHistoryPath(item.file))
self:_indexing(item.index)
self:_flush()
end
function ReadHistory:addItem(file)
assert(self ~= nil)
if file ~= nil and lfs.attributes(file, "mode") == "file" then
table.insert(self.hist, 1, buildEntry(os.time(), file))
-- TODO(zijiehe): We do not need to sort if we can use binary insert and
-- binary search.
self:_sort()
self:_reduce()
self:_flush()
end
end
function ReadHistory:setDeleted(item)
assert(self ~= nil)
if self.hist[item.index] then
self.hist[item.index].dim = true
end
end
--- Reloads history from history_file.
-- @treturn boolean true if history_file has been updated and reload happened.
function ReadHistory:reload()
assert(self ~= nil)
if self:_read() then
self:_readLegacyHistory()
self:_sort()
self:_reduce()
return true
end
return false
end
ReadHistory:_init()
return ReadHistory
|
local DataStorage = require("datastorage")
local DocSettings = require("docsettings")
local dump = require("dump")
local joinPath = require("ffi/util").joinPath
local lfs = require("libs/libkoreader-lfs")
local realpath = require("ffi/util").realpath
local history_file = joinPath(DataStorage:getDataDir(), "history.lua")
local ReadHistory = {
hist = {},
last_read_time = 0,
}
local function buildEntry(input_time, input_file)
return {
time = input_time,
text = input_file:gsub(".*/", ""),
file = realpath(input_file) or input_file, -- keep orig file path of deleted files
dim = lfs.attributes(input_file, "mode") ~= "file", -- "dim", as expected by Menu
callback = function()
local ReaderUI = require("apps/reader/readerui")
ReaderUI:showReader(input_file)
end
}
end
local function fileFirstOrdering(l, r)
if l.file == r.file then
return l.time > r.time
else
return l.file < r.file
end
end
local function timeFirstOrdering(l, r)
if l.time == r.time then
return l.file < r.file
else
return l.time > r.time
end
end
function ReadHistory:_indexing(start)
assert(self ~= nil)
-- TODO(Hzj_jie): Use binary search to find an item when deleting it.
for i = start, #self.hist, 1 do
self.hist[i].index = i
end
end
function ReadHistory:_sort()
assert(self ~= nil)
local autoremove_deleted_items_from_history =
not G_reader_settings:nilOrFalse("autoremove_deleted_items_from_history")
if autoremove_deleted_items_from_history then
self:clearMissing()
end
table.sort(self.hist, fileFirstOrdering)
-- TODO(zijiehe): Use binary insert instead of a loop to deduplicate.
for i = #self.hist, 2, -1 do
if self.hist[i].file == self.hist[i - 1].file then
table.remove(self.hist, i)
end
end
table.sort(self.hist, timeFirstOrdering)
self:_indexing(1)
end
-- Reduces total count in hist list to a reasonable number by removing last
-- several items.
function ReadHistory:_reduce()
assert(self ~= nil)
while #self.hist > 500 do
table.remove(self.hist, #self.hist)
end
end
-- Flushes current history table into file.
function ReadHistory:_flush()
assert(self ~= nil)
local content = {}
for k, v in pairs(self.hist) do
content[k] = {
time = v.time,
file = v.file
}
end
local f = io.open(history_file, "w")
f:write("return " .. dump(content) .. "\n")
f:close()
end
--- Reads history table from file.
-- @treturn boolean true if the history_file has been updated and reloaded.
function ReadHistory:_read()
assert(self ~= nil)
local history_file_modification_time = lfs.attributes(history_file, "modification")
if history_file_modification_time == nil
or history_file_modification_time <= self.last_read_time then
return false
end
self.last_read_time = history_file_modification_time
local ok, data = pcall(dofile, history_file)
if ok and data then
for k, v in pairs(data) do
table.insert(self.hist, buildEntry(v.time, v.file))
end
end
return true
end
-- Reads history from legacy history folder
function ReadHistory:_readLegacyHistory()
assert(self ~= nil)
local history_dir = DataStorage:getHistoryDir()
for f in lfs.dir(history_dir) do
local path = joinPath(history_dir, f)
if lfs.attributes(path, "mode") == "file" then
path = DocSettings:getPathFromHistory(f)
if path ~= nil and path ~= "" then
local file = DocSettings:getNameFromHistory(f)
if file ~= nil and file ~= "" then
table.insert(
self.hist,
buildEntry(lfs.attributes(joinPath(history_dir, f), "modification"),
joinPath(path, file)))
end
end
end
end
end
function ReadHistory:_init()
assert(self ~= nil)
self:reload()
end
function ReadHistory:clearMissing()
assert(self ~= nil)
for i = #self.hist, 1, -1 do
if self.hist[i].file == nil or lfs.attributes(self.hist[i].file, "mode") ~= "file" then
table.remove(self.hist, i)
end
end
end
function ReadHistory:removeItemByPath(path)
assert(self ~= nil)
for i = #self.hist, 1, -1 do
if self.hist[i].file == path then
self:removeItem(self.hist[i])
break
end
end
end
function ReadHistory:updateItemByPath(old_path, new_path)
assert(self ~= nil)
for i = #self.hist, 1, -1 do
if self.hist[i].file == old_path then
self.hist[i].file = new_path
self:_flush()
self.hist[i].callback = function()
local ReaderUI = require("apps/reader/readerui")
ReaderUI:showReader(new_path)
end
break
end
end
end
function ReadHistory:removeItem(item)
assert(self ~= nil)
table.remove(self.hist, item.index)
os.remove(DocSettings:getHistoryPath(item.file))
self:_indexing(item.index)
self:_flush()
end
function ReadHistory:addItem(file)
assert(self ~= nil)
if file ~= nil and lfs.attributes(file, "mode") == "file" then
local now = os.time()
table.insert(self.hist, 1, buildEntry(now, file))
-- TODO(zijiehe): We do not need to sort if we can use binary insert and
-- binary search.
-- util.execute("/bin/touch", "-a", file)
-- This emulates `touch -a` in LuaFileSystem's API, since it may be absent (Android)
-- or provided by busybox, which doesn't support the `-a` flag.
local mtime = lfs.attributes(file, "modification")
lfs.touch(file, now, mtime)
self:_sort()
self:_reduce()
self:_flush()
end
end
function ReadHistory:setDeleted(item)
assert(self ~= nil)
if self.hist[item.index] then
self.hist[item.index].dim = true
end
end
--- Reloads history from history_file.
-- @treturn boolean true if history_file has been updated and reload happened.
function ReadHistory:reload()
assert(self ~= nil)
if self:_read() then
self:_readLegacyHistory()
self:_sort()
self:_reduce()
return true
end
return false
end
ReadHistory:_init()
return ReadHistory
|
Fix sort-by-last-read when partition is mounted noatime (#3990)
|
Fix sort-by-last-read when partition is mounted noatime (#3990)
|
Lua
|
agpl-3.0
|
Frenzie/koreader,NiLuJe/koreader,koreader/koreader,Frenzie/koreader,koreader/koreader,mwoz123/koreader,poire-z/koreader,NiLuJe/koreader,poire-z/koreader,Markismus/koreader,pazos/koreader,Hzj-jie/koreader,houqp/koreader,mihailim/koreader,lgeek/koreader
|
efe12f3f9d92b35d49bd050ed26fb4a2799fe38d
|
nwf_modules/direct_view_access_mod/init.lua
|
nwf_modules/direct_view_access_mod/init.lua
|
--
-- desc: Supports direct access to the views via file path for front-end debugging
-- Author: Elvin
-- Date: 17-5-25
-- others: It is only enabled when the nwf.config.echoDebugInfo configuration is set to true.
--
print("direct_view_access_mod module init...");
if (nwf.config.echoDebugInfo) then
nwf.registerRequestMapper(function(requestPath)
return function(ctx)
local f = assert(io.open("www/view" .. requestPath, "r"))
local str = f:read("*all");
f:close();
return "raw", {content = str}
end;
end);
print("warning: direct_view_access_mod module is enabled.");
end
|
--
-- desc: Supports direct access to the views via file path for front-end debugging
-- Author: Elvin
-- Date: 17-5-25
-- others: It is only enabled when the nwf.config.echoDebugInfo configuration is set to true.
--
print("direct_view_access_mod module init...");
if (nwf.config.echoDebugInfo) then
nwf.registerRequestMapper(function(requestPath)
return function(ctx)
local filePath = "www/view" .. requestPath
if (ParaIO.DoesFileExist(filePath, false)) then
return;
end
local f = assert(io.open(filePath, "r"))
local str = f:read("*all");
f:close();
return "raw", {content = str}
end;
end);
print("warning: direct_view_access_mod module is enabled.");
end
|
fix bug about direct_view_access_mod
|
fix bug about direct_view_access_mod
|
Lua
|
mit
|
Links7094/nwf,Links7094/nwf,elvinzeng/nwf,elvinzeng/nwf
|
6d8f65040cc8c04c31363e3b0aaad4218e700fd3
|
modules/admin-mini/luasrc/model/cbi/mini/wifi.lua
|
modules/admin-mini/luasrc/model/cbi/mini/wifi.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("wireless", translate("wifi"), translate("a_w_devices1"))
s = m:section(TypedSection, "wifi-device", translate("devices"))
en = s:option(Flag, "disabled", translate("enable"))
en.enabled = "0"
en.disabled = "1"
mode = s:option(ListValue, "mode", translate("mode"))
mode:value("", "standard")
mode:value("11b", "802.11b")
mode:value("11g", "802.11g")
mode:value("11a", "802.11a")
mode:value("11bg", "802.11b+g")
mode.rmempty = true
s:option(Value, "channel", translate("a_w_channel"))
s = m:section(TypedSection, "wifi-iface", translate("m_n_local"))
s.anonymous = true
s:option(Value, "ssid", translate("a_w_netid")).maxlength = 32
local devs = {}
luci.model.uci.foreach("wireless", "wifi-device",
function (section)
table.insert(devs, section[".name"])
end)
if #devs > 1 then
device = s:option(DummyValue, "device", translate("device"))
else
s.defaults.device = devs[1]
end
mode = s:option(ListValue, "mode", translate("mode"))
mode:value("ap", translate("m_w_ap"))
mode:value("adhoc", translate("m_w_adhoc"))
mode:value("sta", translate("m_w_client"))
function mode.write(self, section, value)
if value == "sta" then
-- ToDo: Move this away
if not luci.model.uci.get("network", "wan") then
luci.model.uci.set("network", "wan", "proto", "none")
luci.model.uci.set("network", "wan", "ifname", " ")
end
luci.model.uci.set("network", "wan", "_ifname", luci.model.uci.get("network", "wan", "ifname") or " ")
luci.model.uci.set("network", "wan", "ifname", " ")
luci.model.uci.save("network")
luci.model.uci.unload("network")
self.map:set(section, "network", "wan")
else
if luci.model.uci.get("network", "wan", "_ifname") then
luci.model.uci.set("network", "wan", "ifname", luci.model.uci.get("network", "wan", "_ifname"))
end
self.map:set(section, "network", "lan")
end
return ListValue.write(self, section, value)
end
encr = s:option(ListValue, "encryption", translate("encryption"))
encr:value("none", "keine")
encr:value("wep", "WEP")
encr:value("psk", "WPA-PSK")
encr:value("wpa", "WPA-Radius")
encr:value("psk2", "WPA2-PSK")
encr:value("wpa2", "WPA2-Radius")
key = s:option(Value, "key", translate("key"))
key:depends("encryption", "wep")
key:depends("encryption", "psk")
key:depends("encryption", "wpa")
key:depends("encryption", "psk2")
key:depends("encryption", "wpa2")
key.rmempty = true
server = s:option(Value, "server", translate("a_w_radiussrv"))
server:depends("encryption", "wpa")
server:depends("encryption", "wpa2")
server.rmempty = true
port = s:option(Value, "port", translate("a_w_radiusport"))
port:depends("encryption", "wpa")
port:depends("encryption", "wpa2")
port.rmempty = true
iso = s:option(Flag, "isolate", translate("a_w_apisolation"), translate("a_w_apisolation1"))
iso.rmempty = true
iso:depends("mode", "ap")
hide = s:option(Flag, "hidden", translate("a_w_hideessid"))
hide.rmempty = true
hide:depends("mode", "ap")
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("wireless", translate("wifi"), translate("a_w_devices1"))
s = m:section(TypedSection, "wifi-device", translate("devices"))
en = s:option(Flag, "disabled", translate("enable"))
en.enabled = "0"
en.disabled = "1"
mode = s:option(ListValue, "mode", translate("mode"))
mode:value("", "standard")
mode:value("11b", "802.11b")
mode:value("11g", "802.11g")
mode:value("11a", "802.11a")
mode:value("11bg", "802.11b+g")
mode.rmempty = true
s:option(Value, "channel", translate("a_w_channel"))
s = m:section(TypedSection, "wifi-iface", translate("m_n_local"))
s.anonymous = true
s:option(Value, "ssid", translate("a_w_netid")).maxlength = 32
local devs = {}
luci.model.uci.foreach("wireless", "wifi-device",
function (section)
table.insert(devs, section[".name"])
end)
if #devs > 1 then
device = s:option(DummyValue, "device", translate("device"))
else
s.defaults.device = devs[1]
end
mode = s:option(ListValue, "mode", translate("mode"))
mode:value("ap", translate("m_w_ap"))
mode:value("adhoc", translate("m_w_adhoc"))
mode:value("sta", translate("m_w_client"))
function mode.write(self, section, value)
if value == "sta" then
-- ToDo: Move this away
if not luci.model.uci.get("network", "wan") then
luci.model.uci.set("network", "wan", "proto", "none")
luci.model.uci.set("network", "wan", "ifname", " ")
end
local oldif = luci.model.uci.get("network", "wan", "ifname")
if oldif and oldif ~= " " then
luci.model.uci.set("network", "wan", "_ifname", oldif)
end
luci.model.uci.set("network", "wan", "ifname", " ")
luci.model.uci.save("network")
luci.model.uci.unload("network")
self.map:set(section, "network", "wan")
else
if luci.model.uci.get("network", "wan", "_ifname") then
luci.model.uci.set("network", "wan", "ifname", luci.model.uci.get("network", "wan", "_ifname"))
end
self.map:set(section, "network", "lan")
end
return ListValue.write(self, section, value)
end
encr = s:option(ListValue, "encryption", translate("encryption"))
encr:value("none", "keine")
encr:value("wep", "WEP")
encr:value("psk", "WPA-PSK")
encr:value("wpa", "WPA-Radius")
encr:value("psk2", "WPA2-PSK")
encr:value("wpa2", "WPA2-Radius")
key = s:option(Value, "key", translate("key"))
key:depends("encryption", "wep")
key:depends("encryption", "psk")
key:depends("encryption", "wpa")
key:depends("encryption", "psk2")
key:depends("encryption", "wpa2")
key.rmempty = true
server = s:option(Value, "server", translate("a_w_radiussrv"))
server:depends("encryption", "wpa")
server:depends("encryption", "wpa2")
server.rmempty = true
port = s:option(Value, "port", translate("a_w_radiusport"))
port:depends("encryption", "wpa")
port:depends("encryption", "wpa2")
port.rmempty = true
iso = s:option(Flag, "isolate", translate("a_w_apisolation"), translate("a_w_apisolation1"))
iso.rmempty = true
iso:depends("mode", "ap")
hide = s:option(Flag, "hidden", translate("a_w_hideessid"))
hide.rmempty = true
hide:depends("mode", "ap")
return m
|
modules/admin-mini: Fixed wifi client mode again
|
modules/admin-mini: Fixed wifi client mode again
|
Lua
|
apache-2.0
|
deepak78/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci
|
2f40161c459d0530262349ce3dcd609a83b627dd
|
web.lua
|
web.lua
|
module(..., package.seeall)
local Session = require 'bamboo.session'
local Form = require 'bamboo.form'
local View = require 'bamboo.view'
local Web = Object:extend {
__tag = 'Bamboo.Web';
__name = 'Web';
init = function (self, conn, main, req, stateful)
local controller
self.conn = conn
self.req = req
self.main = main
self.stateful = stateful
if stateful then
-- state programming
controller = coroutine.create(main)
else
controller = main
end
self.controller = controller
return self
end;
path = function (self)
return self.req.headers.PATH
end;
method = function (self)
return self.req.headers.METHOD
end;
isRequestJson = function (self)
return self.req.headers.METHOD == "JSON" or
self.req.headers['content-type'] == 'application/json'
end;
isAjax = function (self)
return self.req.headers['x-requested-with'] == "XMLHttpRequest"
end;
zapSession = function (self)
-- to zap the session we just set a new random cookie instead
self:setCookie(Session.makeSessionCookie())
end;
setCookie = function (self, cookie)
self.req.headers['set-cookie'] = cookie
end;
getCookie = function (self)
return self.req.headers['cookie']
end;
session = function (self)
return self.req.session_id
end;
close = function (self)
self.conn:close(self.req)
end;
send = function (self, data)
return self.conn:reply_json(self.req, data)
end;
json = function (self, data, ctype)
if type(data) == 'table' then
for k, v in pairs(data) do
if type(v) == 'table' and #v == 0 then
--data[k] = json.util.InitArray(v)
json.util.InitArray(v)
end
end
end
self:page(json.encode(data), 200, "OK", {['content-type'] = ctype or 'application/json'})
end;
jsonError = function (self, err_code, err_desc)
self:json { success = false, err_code = err_code, err_desc = err_desc }
end;
jsonSuccess = function (self, tbl)
tbl['success'] = true
self:json(tbl)
end;
redirect = function (self, url)
self:page("", 303, "See Other", {Location=url, ['content-type'] = false})
return true
end;
error = function (self, data, code, status, headers)
self:page(data, code, status, headers or {['content-type'] = false})
self:close()
return false
end;
loginRequired = function (self, reurl)
local reurl = reurl or '/index/'
if isFalse(req.user) then web:redirect(reurl); self:close(); return false end
return true
end;
notFound = function (self, msg) return self:error(msg or 'Not Found', 404, 'Not Found') end;
unauthorized = function (self, msg) return self:error(msg or 'Unauthorized', 401, 'Unauthorized') end;
forbidden = function (self, msg) return self:error(msg or 'Forbidden', 403, 'Forbidden') end;
badRequest = function (self, msg) return self:error(msg or 'Bad Request', 400, 'Bad Request') end;
page = function (self, data, code, status, headers)
headers = headers or {}
if self.req.headers['set-cookie'] then
headers['set-cookie'] = self.req.headers['set-cookie']
end
headers['server'] = 'Bamboo on Mongrel2'
local ctype = headers['content-type']
if ctype == nil then
headers['content-type'] = 'text/html'
elseif ctype == false then
headers['content-type'] = nil
end
return self.conn:reply_http(self.req, data, code, status, headers)
end;
html = function (self, html_tmpl, tbl)
local tbl = tbl or {}
return self:page(View(html_tmpl)(tbl))
end;
ok = function (self, msg) self:page(msg or 'OK', 200, 'OK') end;
--------------------------------------------------------------------
-- State Programming
--------------------------------------------------------------------
recv = function (self)
if not self.stateful then error("This is a stateless handler, can't call recv.") end
self.req = coroutine.yield()
return self.req
end;
click = function (self)
if not self.stateful then error("This is a stateless handler, can't call click.") end
local req = self:recv()
return req.headers.PATH
end;
expect = function (self, pattern, data, code, status, headers)
if not self.stateful then error("This is a stateless handler, can't call expect.") end
self:page(data, code, status, headers)
local path = self:click()
if path:match(pattern) then
return path, nil
else
self:error("Not found", 404, "Not Found")
return nil, "Not Found"
end
end;
prompt = function (self, data, code, status, headers)
if not self.stateful then error("This is a stateless handler, can't call prompt.") end
self:page(data, code, status, headers)
return self:input()
end;
input = function (self)
if not self.stateful then error("This is a stateless handler, can't call input.") end
local req = self:recv()
return Form:parse(req), req
end;
}
return Web
|
module(..., package.seeall)
local Session = require 'bamboo.session'
local Form = require 'bamboo.form'
local View = require 'bamboo.view'
local Web = Object:extend {
__tag = 'Bamboo.Web';
__name = 'Web';
init = function (self, conn, main, req, stateful)
local controller
self.conn = conn
self.req = req
self.main = main
self.stateful = stateful
if stateful then
-- state programming
controller = coroutine.create(main)
else
controller = main
end
self.controller = controller
return self
end;
path = function (self)
return self.req.headers.PATH
end;
method = function (self)
return self.req.headers.METHOD
end;
isRequestJson = function (self)
return self.req.headers.METHOD == "JSON" or
self.req.headers['content-type'] == 'application/json'
end;
isAjax = function (self)
return self.req.headers['x-requested-with'] == "XMLHttpRequest"
end;
zapSession = function (self)
-- to zap the session we just set a new random cookie instead
self:setCookie(Session.makeSessionCookie())
end;
setCookie = function (self, cookie)
self.req.headers['set-cookie'] = cookie
end;
getCookie = function (self)
return self.req.headers['cookie']
end;
session = function (self)
return self.req.session_id
end;
close = function (self)
self.conn:close(self.req)
end;
send = function (self, data)
return self.conn:reply_json(self.req, data)
end;
json = function (self, data, ctype)
-- try:
-- temporary transform the empty table to empty array
--
if type(data) == 'table' then
for k, v in pairs(data) do
if type(v) == 'table' then
if table.isEmpty(v) then
--data[k] = json.util.InitArray(v)
json.util.InitArray(v)
else
for kk, vv in pairs(v) then
if type(vv) == 'table' and table.isEmpty(vv) then
json.util.InitArray(vv)
end
end
end
end
end
end
self:page(json.encode(data), 200, "OK", {['content-type'] = ctype or 'application/json'})
end;
jsonError = function (self, err_code, err_desc)
self:json { success = false, err_code = err_code, err_desc = err_desc }
end;
jsonSuccess = function (self, tbl)
tbl['success'] = true
self:json(tbl)
end;
redirect = function (self, url)
self:page("", 303, "See Other", {Location=url, ['content-type'] = false})
return true
end;
error = function (self, data, code, status, headers)
self:page(data, code, status, headers or {['content-type'] = false})
self:close()
return false
end;
loginRequired = function (self, reurl)
local reurl = reurl or '/index/'
if isFalse(req.user) then web:redirect(reurl); self:close(); return false end
return true
end;
notFound = function (self, msg) return self:error(msg or 'Not Found', 404, 'Not Found') end;
unauthorized = function (self, msg) return self:error(msg or 'Unauthorized', 401, 'Unauthorized') end;
forbidden = function (self, msg) return self:error(msg or 'Forbidden', 403, 'Forbidden') end;
badRequest = function (self, msg) return self:error(msg or 'Bad Request', 400, 'Bad Request') end;
page = function (self, data, code, status, headers)
headers = headers or {}
if self.req.headers['set-cookie'] then
headers['set-cookie'] = self.req.headers['set-cookie']
end
headers['server'] = 'Bamboo on Mongrel2'
local ctype = headers['content-type']
if ctype == nil then
headers['content-type'] = 'text/html'
elseif ctype == false then
headers['content-type'] = nil
end
return self.conn:reply_http(self.req, data, code, status, headers)
end;
html = function (self, html_tmpl, tbl)
local tbl = tbl or {}
return self:page(View(html_tmpl)(tbl))
end;
ok = function (self, msg) self:page(msg or 'OK', 200, 'OK') end;
--------------------------------------------------------------------
-- State Programming
--------------------------------------------------------------------
recv = function (self)
if not self.stateful then error("This is a stateless handler, can't call recv.") end
self.req = coroutine.yield()
return self.req
end;
click = function (self)
if not self.stateful then error("This is a stateless handler, can't call click.") end
local req = self:recv()
return req.headers.PATH
end;
expect = function (self, pattern, data, code, status, headers)
if not self.stateful then error("This is a stateless handler, can't call expect.") end
self:page(data, code, status, headers)
local path = self:click()
if path:match(pattern) then
return path, nil
else
self:error("Not found", 404, "Not Found")
return nil, "Not Found"
end
end;
prompt = function (self, data, code, status, headers)
if not self.stateful then error("This is a stateless handler, can't call prompt.") end
self:page(data, code, status, headers)
return self:input()
end;
input = function (self)
if not self.stateful then error("This is a stateless handler, can't call input.") end
local req = self:recv()
return Form:parse(req), req
end;
}
return Web
|
continue to fix the empty array json problem.
|
continue to fix the empty array json problem.
Now web:json support 2 rank and 3 rank empty array.
Signed-off-by: Daogang Tang <[email protected]>
|
Lua
|
bsd-3-clause
|
daogangtang/bamboo,daogangtang/bamboo
|
ed5959fe657c3938206c11aee3ea0b61037f6158
|
libs/term.lua
|
libs/term.lua
|
local prev, luv, T, stdin = ...
local _colors = {
[1] = "white";
[2] = "orange";
[4] = "magenta";
[8] = "lightBlue";
[16] = "yellow";
[32] = "lime";
[64] = "pink";
[128] = "gray";
[256] = "lightGray";
[512] = "cyan";
[1024] = "purple";
[2048] = "blue";
[4096] = "brown";
[8192] = "green";
[16384] = "red";
[32768] = "black";
}
local ansiColors = {
white = {7, false}; -- white
orange = {1, true}; -- bright red
magenta = {5, false}; -- magenta
lightBlue = {4, true}; -- bright blue
yellow = {3, true}; -- bright yellow
lime = {2, true}; -- bright green
pink = {5, false}; -- magenta
gray = {0, false}; -- black
lightGray = {0, false}; -- black
cyan = {6, false}; -- cyan
purple = {5, false}; -- magenta
blue = {4, false}; -- blue
brown = {3, false}; -- yellow
green = {2, false}; -- green
red = {1, false}; -- red
black = {0, false}; -- black
}
local hex = {
['a'] = 10;
['b'] = 11;
['c'] = 12;
['d'] = 13;
['e'] = 14;
['f'] = 15;
}
for i = 0, 7 do
hex[tostring(i)] = i
end
local cursorX, cursorY = 1, 1
local textColor, backColor = 0, 15
local log2 = math.log(2)
local function ccColorFor(c)
if type(c) ~= 'number' or c < 0 or c > 15 then
error('that\'s not a valid color: ' .. tostring(c))
end
return math.pow(2, c)
end
local function fromHexColor(h)
return hex[h] or error('not a hex color: ' .. tostring(h))
end
local termNat
termNat = {
clear = function()
prev.io.write(T.clear())
end;
clearLine = function()
termNat.setCursorPos(cursorY, 1)
prev.io.write(T.el)
termNat.setCursorPos(cursorY, cursorX)
end;
isColour = function() return true end;
isColor = function() return true end;
getSize = function()
return luv.tty_get_winsize(stdin)
-- return 52, 19
end;
getCursorPos = function() return cursorX, cursorY end;
setCursorPos = function(x, y)
if type(x) ~= 'number' or type(y) ~= 'number' then error('term.setCursorPos expects number, number, got: ' .. type(x) .. ', ' .. type(y)) end
cursorX, cursorY = x, y
prev.io.write(T.cup(cursorY - 1, cursorX - 1))
end;
setTextColour = function(...) return termNat.setTextColor(...) end;
setTextColor = function(c)
textColor = math.log(c) / log2
local color = ansiColors[_colors[c] ]
prev.io.write(T[color[2] and 'bold' or 'sgr0']())
prev.io.write(T.setaf(color[1]))
end;
getTextColour = function(...) return termNat.getTextColor(...) end;
getTextColor = function()
return ccColorFor(textColor)
end;
setBackgroundColour = function(...) return termNat.setBackgroundColor(...) end;
setBackgroundColor = function(c)
backColor = math.log(c) / log2
prev.io.write(T.setab(ansiColors[_colors[c] ][1]))
end;
getBackgroundColour = function(...) return termNat.getBackgroundColor(...) end;
getBackgroundColor = function()
return ccColorFor(backColor)
end;
write = function(text)
text = text:gsub('[\n\r]', '?')
prev.io.write(text)
termNat.setCursorPos(cursorX + #text, cursorY)
end;
blit = function(text, textColors, backColors)
text = text:gsub('[\n\r]', '?')
if #text ~= #textColors or #text ~= #backColors then error('term.blit: text, textColors and backColors have to be the same length') end
for i = 1, #text do
termNat.setTextColor(ccColorFor(fromHexColor(textColors:sub(i, i))))
termNat.setBackgroundColor(ccColorFor(fromHexColor(backColors:sub(i, i))))
prev.io.write(text:sub(i, i))
end
cursorX = cursorX + #text
end;
setCursorBlink = function() end;
scroll = function(n)
prev.io.write(T.cup(0, 0))
local txt = T[n < 0 and 'ri' or 'ind']()
prev.io.write(txt:rep(math.abs(n)))
-- if n > 0 then
-- stdscr:move(19 - n, 0)
-- stdscr:clrtobot()
-- elseif n < 0 then
-- for i = 0, n do
-- stdscr:move(i, 0)
-- stdscr:clrtoeol()
-- end
-- end
termNat.setCursorPos(cursorX, cursorY)
end
}
return termNat
|
local prev, luv, T, stdin = ...
local _colors = {
[1] = "white";
[2] = "orange";
[4] = "magenta";
[8] = "lightBlue";
[16] = "yellow";
[32] = "lime";
[64] = "pink";
[128] = "gray";
[256] = "lightGray";
[512] = "cyan";
[1024] = "purple";
[2048] = "blue";
[4096] = "brown";
[8192] = "green";
[16384] = "red";
[32768] = "black";
}
local ansiColors = {
white = {7, false}; -- white
orange = {1, true}; -- bright red
magenta = {5, false}; -- magenta
lightBlue = {4, true}; -- bright blue
yellow = {3, true}; -- bright yellow
lime = {2, true}; -- bright green
pink = {5, false}; -- magenta
gray = {0, false}; -- black
lightGray = {0, false}; -- black
cyan = {6, false}; -- cyan
purple = {5, false}; -- magenta
blue = {4, false}; -- blue
brown = {3, false}; -- yellow
green = {2, false}; -- green
red = {1, false}; -- red
black = {0, false}; -- black
}
local hex = {
['a'] = 10;
['b'] = 11;
['c'] = 12;
['d'] = 13;
['e'] = 14;
['f'] = 15;
}
for i = 0, 9 do
hex[tostring(i)] = i
end
local cursorX, cursorY = 1, 1
local textColor, backColor = 0, 15
local log2 = math.log(2)
local function ccColorFor(c)
if type(c) ~= 'number' or c < 0 or c > 15 then
error('that\'s not a valid color: ' .. tostring(c))
end
return math.pow(2, c)
end
local function fromHexColor(h)
return hex[h] or error('not a hex color: ' .. tostring(h))
end
local termNat
termNat = {
clear = function()
prev.io.write(T.clear())
end;
clearLine = function()
termNat.setCursorPos(cursorY, 1)
prev.io.write(T.el())
termNat.setCursorPos(cursorY, cursorX)
end;
isColour = function() return true end;
isColor = function() return true end;
getSize = function()
return luv.tty_get_winsize(stdin)
-- return 52, 19
end;
getCursorPos = function() return cursorX, cursorY end;
setCursorPos = function(x, y)
if type(x) ~= 'number' or type(y) ~= 'number' then error('term.setCursorPos expects number, number, got: ' .. type(x) .. ', ' .. type(y)) end
cursorX, cursorY = x, y
prev.io.write(T.cup(cursorY - 1, cursorX - 1))
end;
setTextColour = function(...) return termNat.setTextColor(...) end;
setTextColor = function(c)
textColor = math.log(c) / log2
local color = ansiColors[_colors[c] ]
prev.io.write(T[color[2] and 'bold' or 'sgr0']())
prev.io.write(T.setaf(color[1]))
end;
getTextColour = function(...) return termNat.getTextColor(...) end;
getTextColor = function()
return ccColorFor(textColor)
end;
setBackgroundColour = function(...) return termNat.setBackgroundColor(...) end;
setBackgroundColor = function(c)
backColor = math.log(c) / log2
prev.io.write(T.setab(ansiColors[_colors[c] ][1]))
end;
getBackgroundColour = function(...) return termNat.getBackgroundColor(...) end;
getBackgroundColor = function()
return ccColorFor(backColor)
end;
write = function(text)
text = tostring(text or '')
text = text:gsub('[\n\r]', '?')
prev.io.write(text)
termNat.setCursorPos(cursorX + #text, cursorY)
end;
blit = function(text, textColors, backColors)
text = text:gsub('[\n\r]', '?')
if #text ~= #textColors or #text ~= #backColors then error('term.blit: text, textColors and backColors have to be the same length') end
for i = 1, #text do
termNat.setTextColor(ccColorFor(fromHexColor(textColors:sub(i, i))))
termNat.setBackgroundColor(ccColorFor(fromHexColor(backColors:sub(i, i))))
prev.io.write(text:sub(i, i))
end
cursorX = cursorX + #text
end;
setCursorBlink = function() end;
scroll = function(n)
n = n or 1
local w, h = luv.tty_get_winsize(stdin)
prev.io.write(n < 0 and T.cup(0, 0) or T.cup(h, w))
local txt = T[n < 0 and 'ri' or 'ind']()
prev.io.write(txt:rep(math.abs(n)))
if n > 0 then
prev.io.write(T.cup(h - n, 0))
prev.io.write(T.clr_eos())
elseif n < 0 then
for i = 0, n do
prev.io.write(T.cup(i, 0))
prev.io.write(T.clr_eol())
end
end
termNat.setCursorPos(cursorX, cursorY)
end
}
return termNat
|
Fix the terminal
|
Fix the terminal
|
Lua
|
mit
|
CoderPuppy/cc-emu,CoderPuppy/cc-emu,CoderPuppy/cc-emu
|
19907774571281e758c3237983fc28c4e3a95a21
|
src/main/lua/selectionConverter.lua
|
src/main/lua/selectionConverter.lua
|
STRATEGIES = {
stabilized = 2 ^ 0,
recurring = 2 ^ 1
}
CONFIG_FILEPATH = (os.getenv("TMP") or os.getenv("TEMP")
or error("Could not find a temporary directory.")
) .. "\\HookAnyText\\hex_config"
HAT_IS_RUNNING = true
HAT_MENU_ITEM = nil
-- main hex capture function
function convertHexSelection(threadObj)
os.remove(CONFIG_FILEPATH)
math.randomseed(os.time())
local hexView = getMemoryViewForm().HexadecimalView
local history = {}
local recurringHistory = {}
local cmdTitle = "HATCMD" .. string.format("%06d", math.random(1000000) - 1)
local cmdHidden = false
local handle = io.popen(
"TITLE " .. cmdTitle .. " & "
.. "java.exe -jar \"" .. getCheatEngineDir()
.. "autorun\\HexToString.jar\" ",
"w"
)
HAT_IS_RUNNING = true
local selectionSize = 0
local previousBytes = {}
local sendText = function(cmdOrHex)
handle:write(cmdOrHex .. "\n")
handle:flush()
end
getMainForm().OnClose = function(sender)
pcall(function()
sendText(":exit")
handle:close()
end)
closeCE()
end
HAT_MENU_ITEM.OnClick = function(sender)
if HAT_IS_RUNNING then
sendText(":focus")
else
createNativeThread(convertHexSelection)
HAT_IS_RUNNING = true
end
end
while true do
sleep(REFRESH_DELAY)
if checkConfigurationUpdates() then
setConfiguration()
end
if not HAT_IS_RUNNING then
break
end
if not cmdHidden then
sendText(":hide " .. cmdTitle)
cmdHidden = true
end
if hexView.hasSelection then
selectionSize = hexView.SelectionStop-hexView.SelectionStart
local bytes = getBytes(
readBytes(hexView.SelectionStart, selectionSize + 1, true),
history,
recurringHistory
)
if bytes ~= nil
and countDifferences({previousBytes, bytes})
> table.getn(bytes) * STABILIZATION_THRESHOLD
then
local s = ""
for i = 1, table.getn(bytes) do
s = s .. string.format("%02x", bytes[i])
end
sendText(s)
previousBytes = bytes
end
end
end
end
-- determines whether it's worth converting the selection or not
-- returns nil if not
-- returns the array of bytes to use otherwise
function getBytes(selectionContent, history, recurringHistory)
if selectionContent == nil then
return nil
end
pushFirst(history, selectionContent, HISTORY_SIZE)
local bytes = selectionContent
if band(UPDATE_STRATEGY, STRATEGIES.recurring, 8) > 0 then
bytes = constructHexFromHistory(history)
pushFirst(recurringHistory, bytes, HISTORY_SIZE)
end
if band(UPDATE_STRATEGY, STRATEGIES.stabilized, 8) > 0 then
local differences = 0
if band(UPDATE_STRATEGY, STRATEGIES.recurring, 8) > 0 then
differences = countDifferences(recurringHistory)
else
differences = countDifferences(history)
end
if differences > table.getn(bytes) * STABILIZATION_THRESHOLD then
return nil
end
end
return bytes
end
-- gets the minimum size of an array in a list
function getMinSize(tables)
if tables == nil or table.getn(tables) == 0 then
return 0
end
local minSize = table.getn(tables[1]);
for i = 2, table.getn(tables) do
if table.getn(tables[i]) < minSize then
minSize = table.getn(tables[i])
end
end
return minSize
end
-- count the number of different elements between arrays
function countDifferences(tables)
local differenceCounter = 0;
for i = 1, table.getn(tables) - 1 do
for j = 1, getMinSize(tables) do
if tables[i][j] ~= tables[i + 1][j] then
differenceCounter = differenceCounter + 1
end
end
differenceCounter = differenceCounter
+ math.abs(table.getn(tables[i]) - table.getn(tables[i+1]))
end
return differenceCounter
end
-- binary and on bigEndInd bits
function band(elt1, elt2, bigEndInd)
local a = elt1 % (2 ^ (bigEndInd + 1))
local b = elt2 % (2 ^ (bigEndInd + 1))
local res = 0
for i = 0, bigEndInd do
local powerOfTwo = (2 ^ (bigEndInd - i))
if a / powerOfTwo >= 1 then
a = a - powerOfTwo
if b / powerOfTwo >= 1 then
b = b - powerOfTwo
res = res + powerOfTwo
end
end
end
return res
end
-- constructs a byte array by saving the most frequent byte at a given position
-- using the whole history
function constructHexFromHistory(history)
local res = {}
for j = 1, getMinSize(history) do
local bytesAtI = {}
for i = 1, table.getn(history) do
if bytesAtI[history[i][j]] == nil then
bytesAtI[history[i][j]] = 1
else
bytesAtI[history[i][j]] = bytesAtI[history[i][j]] + 1
end
end
local maxByte = nil
for byte, count in pairs(bytesAtI) do
if maxByte == nil or count > bytesAtI[maxByte] then
maxByte = byte;
end
end
res[j] = maxByte
end
return res
end
-- pushes an elements at the first place of an array
function pushFirst(array, elt, maxSize)
table.insert(array, 1, elt)
while table.getn(array) > maxSize do
table.remove(array, maxSize + 1)
end
end
-- sets the value of a global variable from its name
-- taken from the official documentation
function setfield(f, v)
local t = _G
for w, d in string.gfind(f, "([%w_]+)(.?)") do
if d == "." then
t[w] = t[w] or {}
t = t[w]
else
t[w] = v
end
end
end
-- sets configuration variables
function setConfiguration()
local f = nil
local nbTries = 0
while f == nil and nbTries < 30 do
nbTries = nbTries + 1
f = io.open(CONFIG_FILEPATH, "r")
sleep(200)
end
if nbTries >= 50 and f == nil then
error("Could not open temporary configuration update file.")
end
local keyValueCouples = f:read("*all")
for k, v in string.gmatch(keyValueCouples, "([%w_]+)=([%w_]+)") do
setfield(k, tonumber(v) or strtobool(v))
end
f:close()
os.remove(CONFIG_FILEPATH)
translateStrategy()
end
-- interprets "true" and "false" to true and false respectively
-- returns str if any other value
function strtobool(str)
if str == "true" then
return true
elseif str == "false" then
return false
end
return str
end
-- translates the name of an update strategy into a usable value
function translateStrategy()
if UPDATE_STRATEGY == "basic" then
HISTORY_SIZE = 1
STABILIZATION_THRESHOLD = 0
UPDATE_STRATEGY = STRATEGIES.stabilized
elseif UPDATE_STRATEGY == "stabilized" then
UPDATE_STRATEGY = STRATEGIES.stabilized
elseif UPDATE_STRATEGY == "recurring" then
UPDATE_STRATEGY = STRATEGIES.recurring
elseif UPDATE_STRATEGY == "combined" then
UPDATE_STRATEGY = STRATEGIES.stabilized + STRATEGIES.recurring
end
end
-- checks for an update in configuration
function checkConfigurationUpdates()
local f = io.open(CONFIG_FILEPATH,"r")
if f ~= nil then
f:close()
return true
else
return false
end
end
-- creates a menu item for HAT in CE's main form's "File" menu
function addHATMenuItem()
local fileMenu = getMainForm().Menu.Items[0]
HAT_MENU_ITEM = createMenuItem(fileMenu)
HAT_MENU_ITEM.Caption = "Hook Any Text"
fileMenu.insert(0, HAT_MENU_ITEM)
end
addHATMenuItem()
createNativeThread(convertHexSelection)
|
STRATEGIES = {
stabilized = 2 ^ 0,
recurring = 2 ^ 1
}
CONFIG_FILEPATH = (os.getenv("TMP") or os.getenv("TEMP")
or error("Could not find a temporary directory.")
) .. "\\HookAnyText\\hex_config"
HAT_IS_RUNNING = true
HAT_MENU_ITEM = nil
-- main hex capture function
function convertHexSelection(threadObj)
os.remove(CONFIG_FILEPATH)
math.randomseed(os.time())
local hexView = getMemoryViewForm().HexadecimalView
local history = {}
local recurringHistory = {}
local cmdTitle = "HATCMD" .. string.format("%06d", math.random(1000000) - 1)
local cmdHidden = false
local handle = io.popen(
"TITLE " .. cmdTitle .. " & "
.. "java.exe -jar \"" .. getCheatEngineDir()
.. "autorun\\HexToString.jar\" ",
"w"
)
HAT_IS_RUNNING = true
local selectionSize = 0
local previousBytes = {}
local sendText = function(cmdOrHex)
handle:write(cmdOrHex .. "\n")
handle:flush()
end
getMainForm().OnClose = function(sender)
pcall(function()
sendText(":exit")
handle:close()
end)
closeCE()
end
HAT_MENU_ITEM.OnClick = function(sender)
if HAT_IS_RUNNING then
sendText(":focus")
else
createNativeThread(convertHexSelection)
HAT_IS_RUNNING = true
end
end
while true do
sleep(REFRESH_DELAY)
if checkConfigurationUpdates() then
setConfiguration()
end
if not HAT_IS_RUNNING then
break
end
if not cmdHidden then
sendText(":hide " .. cmdTitle)
cmdHidden = true
end
if hexView.hasSelection then
selectionSize = hexView.SelectionStop-hexView.SelectionStart
local bytes = getBytes(
readBytes(hexView.SelectionStart, selectionSize + 1, true),
history,
recurringHistory
)
if bytes ~= nil
and countDifferences({previousBytes, bytes})
> getTableLength(bytes) * STABILIZATION_THRESHOLD
then
local s = ""
for i = 1, getTableLength(bytes) do
s = s .. string.format("%02x", bytes[i])
end
sendText(s)
previousBytes = bytes
end
end
end
end
-- determines whether it's worth converting the selection or not
-- returns nil if not
-- returns the array of bytes to use otherwise
function getBytes(selectionContent, history, recurringHistory)
if selectionContent == nil then
return nil
end
pushFirst(history, selectionContent, HISTORY_SIZE)
local bytes = selectionContent
if band(UPDATE_STRATEGY, STRATEGIES.recurring, 8) > 0 then
bytes = constructHexFromHistory(history)
pushFirst(recurringHistory, bytes, HISTORY_SIZE)
end
if band(UPDATE_STRATEGY, STRATEGIES.stabilized, 8) > 0 then
local differences = 0
if band(UPDATE_STRATEGY, STRATEGIES.recurring, 8) > 0 then
differences = countDifferences(recurringHistory)
else
differences = countDifferences(history)
end
if differences > getTableLength(bytes) * STABILIZATION_THRESHOLD then
return nil
end
end
return bytes
end
-- gets the minimum size of an array in a list
function getMinSize(tables)
if tables == nil or getTableLength(tables) == 0 then
return 0
end
local minSize = getTableLength(tables[1]);
for i = 2, getTableLength(tables) do
if getTableLength(tables[i]) < minSize then
minSize = getTableLength(tables[i])
end
end
return minSize
end
-- count the number of different elements between arrays
function countDifferences(tables)
local differenceCounter = 0;
for i = 1, getTableLength(tables) - 1 do
for j = 1, getMinSize(tables) do
if tables[i][j] ~= tables[i + 1][j] then
differenceCounter = differenceCounter + 1
end
end
differenceCounter = differenceCounter
+ math.abs(getTableLength(tables[i]) - getTableLength(tables[i+1]))
end
return differenceCounter
end
-- binary and on bigEndInd bits
function band(elt1, elt2, bigEndInd)
local a = elt1 % (2 ^ (bigEndInd + 1))
local b = elt2 % (2 ^ (bigEndInd + 1))
local res = 0
for i = 0, bigEndInd do
local powerOfTwo = (2 ^ (bigEndInd - i))
if a / powerOfTwo >= 1 then
a = a - powerOfTwo
if b / powerOfTwo >= 1 then
b = b - powerOfTwo
res = res + powerOfTwo
end
end
end
return res
end
-- constructs a byte array by saving the most frequent byte at a given position
-- using the whole history
function constructHexFromHistory(history)
local res = {}
for j = 1, getMinSize(history) do
local bytesAtI = {}
for i = 1, getTableLength(history) do
if bytesAtI[history[i][j]] == nil then
bytesAtI[history[i][j]] = 1
else
bytesAtI[history[i][j]] = bytesAtI[history[i][j]] + 1
end
end
local maxByte = nil
for byte, count in pairs(bytesAtI) do
if maxByte == nil or count > bytesAtI[maxByte] then
maxByte = byte;
end
end
res[j] = maxByte
end
return res
end
-- pushes an elements at the first place of an array
function pushFirst(array, elt, maxSize)
table.insert(array, 1, elt)
while getTableLength(array) > maxSize do
table.remove(array, maxSize + 1)
end
end
-- sets the value of a global variable from its name
-- taken from the official documentation
function setfield(f, v)
local t = _G
for w, d in (string.gfind or string.gmatch)(f, "([%w_]+)(.?)") do
if d == "." then
t[w] = t[w] or {}
t = t[w]
else
t[w] = v
end
end
end
-- sets configuration variables
function setConfiguration()
local f = nil
local nbTries = 0
while f == nil and nbTries < 30 do
nbTries = nbTries + 1
f = io.open(CONFIG_FILEPATH, "r")
sleep(200)
end
if nbTries >= 50 and f == nil then
error("Could not open temporary configuration update file.")
end
local keyValueCouples = f:read("*all")
for k, v in string.gmatch(keyValueCouples, "([%w_]+)=([%w_]+)") do
setfield(k, tonumber(v) or strtobool(v))
end
f:close()
os.remove(CONFIG_FILEPATH)
translateStrategy()
end
-- interprets "true" and "false" to true and false respectively
-- returns str if any other value
function strtobool(str)
if str == "true" then
return true
elseif str == "false" then
return false
end
return str
end
-- translates the name of an update strategy into a usable value
function translateStrategy()
if UPDATE_STRATEGY == "basic" then
HISTORY_SIZE = 1
STABILIZATION_THRESHOLD = 0
UPDATE_STRATEGY = STRATEGIES.stabilized
elseif UPDATE_STRATEGY == "stabilized" then
UPDATE_STRATEGY = STRATEGIES.stabilized
elseif UPDATE_STRATEGY == "recurring" then
UPDATE_STRATEGY = STRATEGIES.recurring
elseif UPDATE_STRATEGY == "combined" then
UPDATE_STRATEGY = STRATEGIES.stabilized + STRATEGIES.recurring
end
end
-- checks for an update in configuration
function checkConfigurationUpdates()
local f = io.open(CONFIG_FILEPATH,"r")
if f ~= nil then
f:close()
return true
else
return false
end
end
-- creates a menu item for HAT in CE's main form's "File" menu
function addHATMenuItem()
local fileMenu = getMainForm().Menu.Items[0]
HAT_MENU_ITEM = createMenuItem(fileMenu)
HAT_MENU_ITEM.Caption = "Hook Any Text"
fileMenu.insert(0, HAT_MENU_ITEM)
end
function getTableLength(t)
if table.getn then
return table.getn(t)
else
return #t
end
end
addHATMenuItem()
createNativeThread(convertHexSelection)
|
Address deprecation of native methods in Lua
|
Address deprecation of native methods in Lua
Fix #12
|
Lua
|
mit
|
MX-Futhark/hook-any-text
|
76188edfe583e36ea2713160e744176c9b9cdc77
|
src/rava.lua
|
src/rava.lua
|
local bcsave = require("libs/bcsave").start
local preHooks = {}
local postHooks = {}
local maincode
local mainobj
local objs = {}
local rava = {}
-- check if file exists
local function fileExists(file)
if file then
local f = io.open(file,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
end
-- run Hooks
local function callHooks(hooks, ...)
for i=1, #hooks do
hooks[i](...)
end
end
local function addHook(hooks, fn)
for i = 1, #hooks do
if hooks[i] == fn then
return false
end
end
table.insert(hooks, fn)
return true
end
-- call through pipe to generate
local function generateCodeObject(path, name)
local dir, file, ext= string.match(path, "(.-)([^/]-([^%.]+))$")
local objpath = path
local leavesym = ""
name = name or (dir:gsub("^%./",""):gsub("^/",""):gsub("/",".") .. file:gsub("%.lua$",""))
-- First file we add is always main
if mainobj == nil then
name = "main"
mainobj = true
end
-- Run preprocessors on file
callHooks(preHooks, path)
-- generate lua object
if path:match("%.lua$") then
if (not opt.flag("n")) then
-- load code to check it for errors
local fn, err = loadstring(rava.code[path])
-- die on syntax errors
if not fn then
msg.fatal(err)
end
end
-- check for leave symbols flag
if opt.flag("g") then
leavesym = "-g"
end
objpath = path..".o"
msg.info("Chunk '"..name.."' in "..objpath)
-- create CC line
local f = io.popen(string.format(
"%s -q %s --generate=%s %s %s",
RAVABIN,
leavesym,
name,
"-",
objpath),"w")
-- write code to generator
f:write(rava.code[path])
f:close()
msg.done()
end
-- add object
if name == "main" then
mainobj = objpath
else
table.insert(objs, objpath)
end
--reclame memory (probably overkill in most cases)
rava.code[path] = true
return objpath
end
-- list files in a directory
function rava.scandir(dir)
local r = {}
for file in io.popen("ls -a '"..dir.."'"):lines() do
table.insert(r, file)
end
return r
end
-- Add PreHooks to filter input
function rava.addPreHook(fn)
return addHook(preHooks, fn)
end
-- Add PostHooks to futher process output
function rava.addPostHook(fn)
return addHook(postHooks, fn)
end
-- Add files to the rava compiler
function rava.addFile(...)
local arg = {...}
for i=1, #arg do
local file = arg[i]
if rava.code[file] then
break
elseif not fileExists(file) then
msg.warning("Failed to add module: "..file)
if #file > 10 then
end
break
elseif file:match("%.lua$") then
msg.info("Loading "..file)
local f, err = io.open(file,"r")
if err then msg.fatal(err) end
rava.code[file] = f:read("*all")
f:close()
msg.done()
end
generateCodeObject(file)
end
end
-- Add a string to the rava compiler
function rava.addString(name, code)
rava.code[name] = code
generateCodeObject(name, name)
end
-- Evaluate code to run in realtime
function rava.eval(...)
local arg = {...}
local chunk = ""
for x = 1, #arg do
chunk = chunk.."\n"..arg[x]
end
local fn=loadstring(chunk)
fn()
end
-- Execute external files
function rava.exec(...)
local arg = {...}
for x = 1, #arg do
dofile(arg[x])
end
end
-- Generate binary data store
function rava.store(variable, store, ...)
-- open store
local out = io.open(store:gsub("%..+$", "")..".lua", "w+")
local files = {...}
-- make sure variable is set
variable = variable or "files"
-- start variable
out:write("local "..variable.." = {}\n")
-- loop through files
for _, path in pairs(files) do
local dir, file, ext= string.match(path, "(.-)([^/]-([^%.]+))$")
local ins = io.open(path, "r")
local data = ins:read("*all")
if not ins then
msg.fatal("Error reading " .. path)
end
ins:close()
out:write(variable..'["'..dir:gsub("^%./", ""):gsub("^/", "")..file..'"] = "')
for i = 1, #data do
out:write(string.format("\\%i", string.byte(data, i)))
end
out:write('"\n')
end
out:write('\nmodule(...)\n')
out:write('return '..variable)
out:close()
bcsave(
store:gsub("%..+$", "")..".lua",
store:gsub("%..+$", "")..".o")
end
-- Compile the rava object state to binary
function rava.compile(binary, ...)
-- make sure we have a name
if binary == true then
binary = "rava"
end
--load Lua Code
rava.addFile(...)
msg.info("Compiling Binary... ")
local f, err = io.open(binary..".a", "w+")
local files = require("libs"..".ravastore")
f:write(files["libs/rava.a"])
f:close()
-- Construct compiler call
local ccall = string.format([[
%s -O%s -Wall -Wl,-E \
-x none %s -x none %s \
%s \
-o %s -lm -ldl -flto ]],
os.getenv("CC") or "gcc",
OPLEVEL,
binary..".a",
mainobj,
os.getenv("CCARGS").." "..table.concat(objs, " "),
binary)
-- Call compiler
msg.warning(ccall)
os.execute(ccall)
-- run PostHooks
callHooks(postHooks, binary)
print("\n")
end
-- Generate an object file from lua files
function rava.generate(name, ...)
local arg = {...}
local calls = {}
if name ~= true then
table.insert(calls, "-n")
table.insert(calls, name)
end
for i = 1, #arg do
table.insert(calls, arg[i])
end
bcsave(unpack(calls))
end
-- code repository
rava.code = {}
module(...)
return rava
|
local bytecode = require("libs/bcsave").start
local preHooks = {}
local postHooks = {}
local ccargs = os.getenv("CCARGS") or ""
local mainobj
local objs = {}
local rava = {}
-- check if file exists
local function fileExists(file)
if file then
local f = io.open(file,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
end
-- run Hooks
local function callHooks(hooks, ...)
for i=1, #hooks do
hooks[i](...)
end
end
local function addHook(hooks, fn)
for i = 1, #hooks do
if hooks[i] == fn then
return false
end
end
table.insert(hooks, fn)
return true
end
-- call through pipe to generate
local function generateCodeObject(path, name)
local dir, file, ext= string.match(path, "(.-)([^/]-([^%.]+))$")
local objpath = path
local leavesym = ""
name = name or (dir:gsub("^%./",""):gsub("^/",""):gsub("/",".") .. file:gsub("%.lua$",""))
-- First file we add is always main
if mainobj == nil then
name = "main"
mainobj = true
end
-- Run preprocessors on file
callHooks(preHooks, path)
-- generate lua object
if path:match("%.lua$") then
if (not opt.flag("n")) then
-- load code to check it for errors
local fn, err = loadstring(rava.code[path])
-- die on syntax errors
if not fn then
msg.fatal(err)
end
end
-- check for leave symbols flag
if opt.flag("g") then
leavesym = "-g"
end
objpath = path..".o"
msg.info("Chunk '"..name.."' in "..objpath)
-- create CC line
local f = io.popen(string.format(
"%s -q %s --generate=%s %s %s",
RAVABIN,
leavesym,
name,
"-",
objpath),"w")
-- write code to generator
f:write(rava.code[path])
f:close()
msg.done()
end
-- add object
if name == "main" then
mainobj = objpath
else
table.insert(objs, objpath)
end
--reclame memory (probably overkill in most cases)
rava.code[path] = true
return objpath
end
-- list files in a directory
function rava.scandir(dir)
local r = {}
for file in io.popen("ls -a '"..dir.."'"):lines() do
table.insert(r, file)
end
return r
end
-- Add PreHooks to filter input
function rava.addPreHook(fn)
return addHook(preHooks, fn)
end
-- Add PostHooks to futher process output
function rava.addPostHook(fn)
return addHook(postHooks, fn)
end
-- Add files to the rava compiler
function rava.addFile(...)
local arg = {...}
for i=1, #arg do
local file = arg[i]
if rava.code[file] then
break
elseif not fileExists(file) then
msg.warning("Failed to add module: "..file)
if #file > 10 then
end
break
elseif file:match("%.lua$") then
msg.info("Loading "..file)
local f, err = io.open(file,"r")
if err then msg.fatal(err) end
rava.code[file] = f:read("*all")
f:close()
msg.done()
end
generateCodeObject(file)
end
end
-- Add a string to the rava compiler
function rava.addString(name, code)
rava.code[name] = code
generateCodeObject(name, name)
end
-- Evaluate code to run in realtime
function rava.eval(...)
local arg = {...}
local chunk = ""
for x = 1, #arg do
chunk = chunk.."\n"..arg[x]
end
local fn=loadstring(chunk)
fn()
end
-- Execute external files
function rava.exec(...)
local arg = {...}
for x = 1, #arg do
dofile(arg[x])
end
end
-- Generate binary data store
function rava.store(variable, store, ...)
-- open store
local out = io.open(store:gsub("%..+$", "")..".lua", "w+")
local files = {...}
-- make sure variable is set
variable = variable or "files"
-- start variable
out:write("local "..variable.." = {}\n")
-- loop through files
for _, path in pairs(files) do
local dir, file, ext= string.match(path, "(.-)([^/]-([^%.]+))$")
local ins = io.open(path, "r")
local data = ins:read("*all")
if not ins then
msg.fatal("Error reading " .. path)
end
ins:close()
out:write(variable..'["'..dir:gsub("^%./", ""):gsub("^/", "")..file..'"] = "')
for i = 1, #data do
out:write(string.format("\\%i", string.byte(data, i)))
end
out:write('"\n')
end
out:write('\nmodule(...)\n')
out:write('return '..variable)
out:close()
bytecode(
store:gsub("%..+$", "")..".lua",
store:gsub("%..+$", "")..".o")
end
-- Compile the rava object state to binary
function rava.compile(binary, ...)
-- make sure we have a name
if binary == true then
binary = "rava"
end
--load Lua Code
rava.addFile(...)
msg.info("Compiling Binary... ")
local f, err = io.open(binary..".a", "w+")
local files = require("libs"..".ravastore")
f:write(files["libs/rava.a"])
f:close()
-- Construct compiler call
local ccall = string.format([[
%s -O%s -Wall -Wl,-E \
-x none %s -x none %s \
%s \
-o %s -lm -ldl -flto ]],
os.getenv("CC") or "gcc",
OPLEVEL,
binary..".a",
mainobj,
ccargs.." "..table.concat(objs, " "),
binary)
-- Call compiler
msg.line(ccall)
os.execute(ccall)
-- run PostHooks
callHooks(postHooks, binary)
msg.done()
end
-- Generate an object file from lua files
function rava.generate(name, ...)
local arg = {...}
local calls = {}
if name ~= true then
table.insert(calls, "-n")
table.insert(calls, name)
end
for i = 1, #arg do
table.insert(calls, arg[i])
end
bytecode(unpack(calls))
end
-- code repository
rava.code = {}
module(...)
return rava
|
fixed compilation issue from ccargs and removed all print statements
|
fixed compilation issue from ccargs and removed all print statements
|
Lua
|
mit
|
frinknet/rava,frinknet/rava,frinknet/rava
|
79bc476fa58a94a33955b5d13f860401922ce02e
|
src/core.lua
|
src/core.lua
|
local busted = {
root_context = { type = "describe", description = "global" },
options = {},
__call = function(self)
self.output = self.options.output
--run test
local function test(description, callback)
local debug_info = debug.getinfo(callback)
local info = {
source = debug_info.source,
short_src = debug_info.short_src,
linedefined = debug_info.linedefined,
}
local stack_trace = ""
local function err_handler(err)
stack_trace = debug.traceback("", 4)
return err
end
local status, err = xpcall(callback, err_handler)
local test_status = {}
if err then
test_status = { type = "failure", description = description, info = info, trace = stack_trace, err = err }
else
test_status = { type = "success", description = description, info = info }
end
if not self.options.defer_print then
self.output.currently_executing(test_status, self.options)
end
return test_status
end
--run test case
local function run_context(context)
local match = false
if self.options.tags and #self.options.tags > 0 then
for i,t in ipairs(self.options.tags) do
if context.description:find("#"..t) then
match = true
end
end
else
match = true
end
local status = { description = context.description, type = "description", run = match }
if context.setup then
context.setup()
end
for i,v in ipairs(context) do
if context.before_each then
context.before_each()
end
if v.type == "test" then
table.insert(status, test(v.description, v.callback))
elseif v.type == "describe" then
table.insert(status, coroutine.create(function() run_context(v) end))
elseif v.type == "pending" then
local pending_test_status = { type = "pending", description = v.description, info = v.info }
v.callback(pending_test_status)
table.insert(status, pending_test_status)
end
if context.after_each then
context.after_each()
end
end
if context.teardown then
context.teardown()
end
if coroutine.running() then
coroutine.yield(status)
else
return true, status
end
end
local play_sound = function(failures)
math.randomseed(os.time())
if self.options.failure_messages and #self.options.failure_messages > 0 and self.options.success_messages and #self.options.success_messages > 0 then
if failures and failures > 0 then
io.popen("say \""..failure_messages[math.random(1, #failure_messages)]:format(failures).."\"")
else
io.popen("say \""..success_messages[math.random(1, #success_messages)].."\"")
end
end
end
local ms = os.clock()
if not self.options.defer_print then
print(self.output.header(self.root_context))
end
--fire off tests, return status list
local function get_statuses(done, list)
local ret = {}
for i,v in pairs(list) do
local vtype = type(v)
if vtype == "thread" then
local res = get_statuses(coroutine.resume(v))
for key,value in pairs(res) do
table.insert(ret, value)
end
elseif vtype == "table" then
table.insert(ret, v)
end
end
return ret
end
local statuses = get_statuses(run_context(self.root_context))
--final run time
ms = os.clock() - ms
if self.options.defer_print then
print(self.output.header(self.root_context))
end
local status_string = self.output.formatted_status(statuses, self.options, ms)
if self.options.sound then
play_sound(failures)
end
return status_string
end
}
return setmetatable(busted, busted)
|
-- return truthy if we're in a coroutine
local function in_coroutine()
local current_routine, main = coroutine.running()
-- need check to the main variable for 5.2, it's nil for 5.1
return current_routine and (main == nil or main == false)
end
local busted = {
root_context = { type = "describe", description = "global" },
options = {},
__call = function(self)
self.output = self.options.output
--run test
local function test(description, callback)
local debug_info = debug.getinfo(callback)
local info = {
source = debug_info.source,
short_src = debug_info.short_src,
linedefined = debug_info.linedefined,
}
local stack_trace = ""
local function err_handler(err)
stack_trace = debug.traceback("", 4)
return err
end
local status, err = xpcall(callback, err_handler)
local test_status = {}
if err then
test_status = { type = "failure", description = description, info = info, trace = stack_trace, err = err }
else
test_status = { type = "success", description = description, info = info }
end
if not self.options.defer_print then
self.output.currently_executing(test_status, self.options)
end
return test_status
end
--run test case
local function run_context(context)
local match = false
if self.options.tags and #self.options.tags > 0 then
for i,t in ipairs(self.options.tags) do
if context.description:find("#"..t) then
match = true
end
end
else
match = true
end
local status = { description = context.description, type = "description", run = match }
if context.setup then
context.setup()
end
for i,v in ipairs(context) do
if context.before_each then
context.before_each()
end
if v.type == "test" then
table.insert(status, test(v.description, v.callback))
elseif v.type == "describe" then
table.insert(status, coroutine.create(function() run_context(v) end))
elseif v.type == "pending" then
local pending_test_status = { type = "pending", description = v.description, info = v.info }
v.callback(pending_test_status)
table.insert(status, pending_test_status)
end
if context.after_each then
context.after_each()
end
end
if context.teardown then
context.teardown()
end
if in_coroutine() then
coroutine.yield(status)
else
return true, status
end
end
local play_sound = function(failures)
math.randomseed(os.time())
if self.options.failure_messages and #self.options.failure_messages > 0 and self.options.success_messages and #self.options.success_messages > 0 then
if failures and failures > 0 then
io.popen("say \""..failure_messages[math.random(1, #failure_messages)]:format(failures).."\"")
else
io.popen("say \""..success_messages[math.random(1, #success_messages)].."\"")
end
end
end
local ms = os.clock()
if not self.options.defer_print then
print(self.output.header(self.root_context))
end
--fire off tests, return status list
local function get_statuses(done, list)
local ret = {}
for i,v in pairs(list) do
local vtype = type(v)
if vtype == "thread" then
local res = get_statuses(coroutine.resume(v))
for key,value in pairs(res) do
table.insert(ret, value)
end
elseif vtype == "table" then
table.insert(ret, v)
end
end
return ret
end
local statuses = get_statuses(run_context(self.root_context))
--final run time
ms = os.clock() - ms
if self.options.defer_print then
print(self.output.header(self.root_context))
end
local status_string = self.output.formatted_status(statuses, self.options, ms)
if self.options.sound then
play_sound(failures)
end
return status_string
end
}
return setmetatable(busted, busted)
|
Fix coroutine detection
|
Fix coroutine detection
coroutine.running() has changed semantics between 5.1 and
5.2, and now returns a second boolean indicating whether the
running coroutine is the main one.
|
Lua
|
mit
|
istr/busted,nehz/busted,azukiapp/busted,o-lim/busted,DorianGray/busted,sobrinho/busted,mpeterv/busted,xyliuke/busted,ryanplusplus/busted,leafo/busted,Olivine-Labs/busted
|
b57c352dcbd363220828b3832098cd680f16c265
|
assets/lua/Diggler.lua
|
assets/lua/Diggler.lua
|
local rtpath = digglerNative.gameLuaRuntimePath
package.path = package.path .. ';' .. rtpath .. '/?.lua;' .. rtpath .. '/lds/?.lua'
ffi = require('ffi')
io = require('io')
debug = require('debug')
local STP = require "StackTracePlus"
debug.traceback = STP.stacktrace
diggler = {
mods = {},
modOverlays = {},
modsById = {},
publicEnv = {},
exportedFuncs = {}
}
ffi.cdef[[
struct Diggler_Game;
union PtrConvert {
void *ptr;
char str[sizeof(void*)];
};
]]
do
local cvt = ffi.new('union PtrConvert', {str = digglerNative.gameInstancePtrStr})
diggler.gameInstance = ffi.cast('struct Diggler_Game*', cvt.ptr)
end
function diggler.export(name, func)
diggler.exportedFuncs[name] = func
end
package.loaded['diggler'] = diggler
package.loaded['lds'] = require('lds')
local function setoverlay(tab, orig)
local mt = getmetatable(tab) or {}
mt.__index = function (tab, key)
if rawget(tab, key) ~= nil then
return rawget(tab, key)
else
return orig[key]
end
end
setmetatable(tab, mt)
end
diggler.MODSTATUS = {
UNAVAILABLE = 0,
DISABLED = 1,
ERRORED = 2,
LOADED = 10,
INITIALIZED = 20,
DEINITIALIZED = 90,
UNLOADED = 100
}
local match = string.match
local function trim(s)
return match(s,'^()%s*$') and '' or match(s,'^%s*(.*%S)')
end
diggler.modGlobalOverrides = {
collectgarbage = function(opt, ...)
if opt == 'count' or opt == 'collect' then
return collectgarbage(opt)
end
end
}
function diggler.loadModLua(path)
local digglerOverlay = {}
local packageOverlay = { ['path'] = path .. '/?.lua;' .. package.path }
setoverlay(packageOverlay, package)
setoverlay(digglerOverlay, diggler.publicEnv)
local env = {
package = packageOverlay,
diggler = digglerOverlay,
print = function (...)
print("<init " .. path .. ">", ...)
end,
CurrentModPath = path
}
for k, v in pairs({
require = function (module)
if module == 'diggler' then
return digglerOverlay
end
return require(module)
end,
dofile = function (name)
local f, e = loadfile(name)
if not f then error(e, 2) end
setfenv(f, env)
return f()
end,
loadfile = function (name)
if name == nil then
return
end
local f, e = loadfile(name)
if f then
setfenv(f, env)
end
return f, e
end,
loadstring = function (string, chunkname)
local f = loadstring(string, chunkname)
if f then
setfenv(f, env)
end
return f
end
}) do
env[k] = v
end
for k, v in pairs(diggler.modGlobalOverrides) do
env[k] = v
end
env['_G'] = env
setoverlay(env, _G)
local file = io.open(path .. '/mod.lua', "r")
if file == nil then
error("mod.lua not found")
end
local untrusted_code = file:read('*a')
file:close()
if untrusted_code:byte(1) == 27 then error("binary bytecode prohibited") end
local untrusted_function, message = loadstring(untrusted_code)
if not untrusted_function then error(message) end
setfenv(untrusted_function, env)
local status, ret = pcall(untrusted_function)
--- Sanity checks
if ret == nil then
error("No mod table returned")
end
local fieldChecks = {'uuid', 'id', 'name', 'version', 'versionStr'}
for _, field in ipairs(fieldChecks) do
if ret[field] == nil then
error(field .. " is nil")
end
end
do -- UUID
if type(ret.uuid) ~= 'string' then
error("uuid isn't a string")
end
if ret.uuid:len() ~= 22 then
error("uuid is of length " .. ret.uuid:len() .. ", expected 22")
end
local uuidInvalid = ret.uuid:match('[^a-zA-Z0-9+/]')
if uuidInvalid ~= nil and uuidInvalid ~= "" then
error("uuid contains invalid characters: " .. uuidInvalid)
end
end
do -- ID
if type(ret.id) ~= 'string' then
error("id isn't a string")
end
if ret.id:len() == 0 or trim(ret.id):len() == 0 then
error("id is empty")
end
if ret.id:match('%s') ~= nil then
error("id contains whitespace")
end
local punct = ret.id:match('[^%a%d]')
if punct ~= nil and punct ~= "" then
error("id contains non-letter/non-digit characters: '" .. punct .. "'")
end
end
do -- Version number
if type(ret.version) ~= 'number' then
error("version isn't a number")
end
end
do -- Version string
if type(ret.versionStr) ~= 'string' then
error("versionStr isn't a string")
end
end
--- Setup actual mod environment
env.CurrentMod = ret
diggler.modOverlays[ret.uuid] = {
['env'] = env,
['package'] = packageOverlay,
['diggler'] = digglerOverlay
}
env.print = function (...)
print(env.CurrentMod.id..":", ...)
end
for name, func in pairs(diggler.exportedFuncs) do
digglerOverlay[name] = function (...)
func(env.CurrentMod, ...)
end
end
if status then
return ret, nil
end
return status, ret
end
function diggler.loadMod(path)
local mod, err = diggler.loadModLua(path)
if mod then
if diggler.mods[mod.uuid] then
error("Mod '" .. mod.id .. "' already loaded")
end
mod.status = diggler.MODSTATUS.LOADED
diggler.mods[mod.uuid] = mod
diggler.modsById[mod.id] = mod
print("Loaded mod '" .. mod.name .. "' <" .. mod.uuid .. " " .. mod.id .. "> v" .. mod.versionStr .. " (" .. mod.version .. ")")
return mod
else
print("Error loading mod: " .. err)
end
return nil
end
function diggler.initMod(mod)
mod.init()
mod.status = diggler.MODSTATUS.INITIALIZED
end
function diggler.getMod(mod, id)
return diggler.modsById[id]
end
diggler.export("getMod", diggler.getMod)
function diggler.getModByUuid(mod, uuid)
return diggler.mods[uuid]
end
diggler.export("getMod", diggler.getMod)
--[[
function diggler.registerBlock(mod, name, block)
print("Calling registerBlock from mod " .. (mod and mod.id or "<none>"))
end
diggler.export("registerBlock", diggler.registerBlock)
]]
dofile(rtpath .. '/api/io.lua')
dofile(rtpath .. '/api/registerBlock.lua')
local m = diggler.loadMod('/media/source/Diggler/mods/TestMod')
diggler.initMod(m)
|
local rtpath = digglerNative.gameLuaRuntimePath
package.path = package.path .. ';' .. rtpath .. '/?.lua;' .. rtpath .. '/lds/?.lua'
ffi = require('ffi')
io = require('io')
debug = require('debug')
local STP = require "StackTracePlus"
debug.traceback = STP.stacktrace
diggler = {
mods = {},
modOverlays = {},
modsById = {},
publicEnv = {},
exportedFuncs = {}
}
ffi.cdef[[
struct Diggler_Game;
union PtrConvert {
void *ptr;
char str[sizeof(void*)];
};
]]
do
local cvt = ffi.new('union PtrConvert', {str = digglerNative.gameInstancePtrStr})
diggler.gameInstance = ffi.cast('struct Diggler_Game*', cvt.ptr)
end
function diggler.export(name, func)
diggler.exportedFuncs[name] = func
end
package.loaded['diggler'] = diggler
package.loaded['lds'] = require('lds')
local function setoverlay(tab, orig)
local mt = getmetatable(tab) or {}
mt.__index = function (tab, key)
if rawget(tab, key) ~= nil then
return rawget(tab, key)
else
return orig[key]
end
end
setmetatable(tab, mt)
end
diggler.MODSTATUS = {
UNAVAILABLE = 0,
DISABLED = 1,
ERRORED = 2,
LOADED = 10,
INITIALIZED = 20,
DEINITIALIZED = 90,
UNLOADED = 100
}
local match = string.match
local function trim(s)
return match(s,'^()%s*$') and '' or match(s,'^%s*(.*%S)')
end
diggler.modGlobalOverrides = {
collectgarbage = function(opt, ...)
if opt == 'count' or opt == 'collect' then
return collectgarbage(opt)
end
end
}
function diggler.loadModLua(path)
local digglerOverlay = {}
local packageOverlay = { ['path'] = path .. '/?.lua;' .. package.path }
setoverlay(packageOverlay, package)
setoverlay(digglerOverlay, diggler.publicEnv)
local env = {
package = packageOverlay,
diggler = digglerOverlay,
print = function (...)
print("<init " .. path .. ">", ...)
end,
CurrentModPath = path
}
for k, v in pairs({
require = function (module)
if module == 'diggler' then
return digglerOverlay
end
return require(module)
end,
dofile = function (name)
local f, e = loadfile(name)
if not f then error(e, 2) end
setfenv(f, env)
return f()
end,
loadfile = function (name)
if name == nil then
return
end
local f, e = loadfile(name)
if f then
setfenv(f, env)
end
return f, e
end,
loadstring = function (string, chunkname)
local f = loadstring(string, chunkname)
if f then
setfenv(f, env)
end
return f
end
}) do
env[k] = v
end
for k, v in pairs(diggler.modGlobalOverrides) do
env[k] = v
end
env['_G'] = env
setoverlay(env, _G)
local file = io.open(path .. '/mod.lua', "r")
if file == nil then
error("mod.lua not found")
end
local untrusted_code = file:read('*a')
file:close()
if untrusted_code:byte(1) == 27 then error("binary bytecode prohibited") end
local untrusted_function, message = loadstring(untrusted_code)
if not untrusted_function then error(message) end
setfenv(untrusted_function, env)
local status, ret = pcall(untrusted_function)
--- Sanity checks
if ret == nil then
error("No mod table returned")
end
local fieldChecks = {'uuid', 'id', 'name', 'version', 'versionStr'}
for _, field in ipairs(fieldChecks) do
if ret[field] == nil then
error(field .. " is nil")
end
end
do -- UUID
if type(ret.uuid) ~= 'string' then
error("uuid isn't a string")
end
if ret.uuid:len() ~= 22 then
error("uuid is of length " .. ret.uuid:len() .. ", expected 22")
end
local uuidInvalid = ret.uuid:match('[^a-zA-Z0-9+/]')
if uuidInvalid ~= nil and uuidInvalid ~= "" then
error("uuid contains invalid characters: " .. uuidInvalid)
end
end
do -- ID
if type(ret.id) ~= 'string' then
error("id isn't a string")
end
if ret.id:len() == 0 or trim(ret.id):len() == 0 then
error("id is empty")
end
if ret.id:match('%s') ~= nil then
error("id contains whitespace")
end
local punct = ret.id:match('[^%a%d]')
if punct ~= nil and punct ~= "" then
error("id contains non-letter/non-digit characters: '" .. punct .. "'")
end
end
do -- Version number
if type(ret.version) ~= 'number' then
error("version isn't a number")
end
end
do -- Version string
if type(ret.versionStr) ~= 'string' then
error("versionStr isn't a string")
end
end
--- Setup actual mod environment
env.CurrentMod = ret
diggler.modOverlays[ret.uuid] = {
['env'] = env,
['package'] = packageOverlay,
['diggler'] = digglerOverlay
}
env.print = function (...)
print(env.CurrentMod.id..":", ...)
end
for name, func in pairs(diggler.exportedFuncs) do
digglerOverlay[name] = function (...)
func(env.CurrentMod, ...)
end
end
if status then
return ret, nil
end
return status, ret
end
function diggler.loadMod(path)
local mod, err = diggler.loadModLua(path)
if mod then
if diggler.mods[mod.uuid] then
error("Mod '" .. mod.id .. "' already loaded")
end
mod.status = diggler.MODSTATUS.LOADED
diggler.mods[mod.uuid] = mod
diggler.modsById[mod.id] = mod
print("Loaded mod '" .. mod.name .. "' <" .. mod.uuid .. " " .. mod.id .. "> v" .. mod.versionStr .. " (" .. mod.version .. ")")
return mod
else
print("Error loading mod: " .. err)
end
return nil
end
function diggler.initMod(mod)
mod.init()
mod.status = diggler.MODSTATUS.INITIALIZED
end
function diggler.getMod(mod, id)
return diggler.modsById[id]
end
diggler.export("getMod", diggler.getMod)
function diggler.getModByUuid(mod, uuid)
return diggler.mods[uuid]
end
diggler.export("getMod", diggler.getMod)
--[[
function diggler.registerBlock(mod, name, block)
print("Calling registerBlock from mod " .. (mod and mod.id or "<none>"))
end
diggler.export("registerBlock", diggler.registerBlock)
]]
dofile(rtpath .. '/api/io.lua')
dofile(rtpath .. '/api/registerBlock.lua')
|
Temp fix for Lua script crashing the game
|
Temp fix for Lua script crashing the game
|
Lua
|
agpl-3.0
|
ElementW/Diggler,ElementW/Diggler
|
7ad1b2e2cc88c4ed49e3133032727d71e50b9d4e
|
states/splash.lua
|
states/splash.lua
|
local Sprite = require 'entities.sprite'
local splash = {}
function splash:init()
self.componentList = {
{
parent = self,
image = Sprite:new('assets/images/splashscreen_logo.png'),
initialAlpha = 0,
finalAlpha = 255,
fadeInTime = 2,
stillTime = 2,
fadeOutTime = 2,
init = function(self)
self.image.position = Vector(love.graphics.getWidth()/2, love.graphics.getHeight()/2)
self.image.scale = Vector(2, 2)
self.alpha = self.initialAlpha
Timer.tween(self.fadeInTime, self, {alpha=self.finalAlpha}, 'linear', function()
Timer.tween(self.stillTime, self, {}, 'linear', function()
Timer.tween(self.fadeOutTime, self, {alpha=self.initialAlpha}, 'linear', function()
self.parent:incrementActive()
end)
end)
end)
end,
draw = function(self)
self.image.color[4] = self.alpha
self.image:draw()
end,
},
}
for k, component in pairs(self.componentList) do
component:init()
end
self.active = 1
end
function splash:enter()
end
function splash:incrementActive()
self.active = self.active + 1
if self.active > #self.componentList then
State.switch(States.menu)
end
end
function splash:update(dt)
end
function splash:keyreleased(key, code)
State.switch(States.menu)
end
function splash:touchreleased(id, x, y, dx, dy, pressure)
State.switch(States.menu)
end
function splash:mousepressed(x, y, mbutton)
end
function splash:draw()
local activeComponent = self.componentList[self.active]
activeComponent:draw()
end
return splash
|
local Sprite = require 'entities.sprite'
local splash = {}
function splash:init()
self.componentList = {
{
parent = self,
image = Sprite:new('assets/images/splashscreen_logo.png'),
initialAlpha = 0,
finalAlpha = 255,
fadeInTime = 2,
stillTime = 2,
fadeOutTime = 2,
init = function(self)
self.image.position = Vector(love.graphics.getWidth()/2, love.graphics.getHeight()/2)
self.image.scale = Vector(2, 2)
self.image:moveOriginToCorner('center')
self.alpha = self.initialAlpha
Timer.tween(self.fadeInTime, self, {alpha=self.finalAlpha}, 'linear', function()
Timer.tween(self.stillTime, self, {}, 'linear', function()
Timer.tween(self.fadeOutTime, self, {alpha=self.initialAlpha}, 'linear', function()
self.parent:incrementActive()
end)
end)
end)
end,
draw = function(self)
self.image.color[4] = self.alpha
self.image:draw()
end,
},
}
for k, component in pairs(self.componentList) do
component:init()
end
self.active = 1
end
function splash:enter()
end
function splash:incrementActive()
self.active = self.active + 1
if self.active > #self.componentList then
State.switch(States.menu)
end
end
function splash:update(dt)
end
function splash:keyreleased(key, code)
State.switch(States.menu)
end
function splash:touchreleased(id, x, y, dx, dy, pressure)
State.switch(States.menu)
end
function splash:mousepressed(x, y, mbutton)
end
function splash:draw()
local activeComponent = self.componentList[self.active]
activeComponent:draw()
end
return splash
|
Fix splash image
|
Fix splash image
|
Lua
|
mit
|
Nuthen/ludum-dare-39
|
28ab3e31cb63a27d06566da53e8366041b9f3bfd
|
BIOS/init.lua
|
BIOS/init.lua
|
--The BIOS should control the system of LIKO-12 and load the peripherals--
--For now it's just a simple BIOS to get LIKO-12 working.
--Require the engine libraries--
local events = require("Engine.events")
local coreg = require("Engine.coreg")
local function splitFilePath(path) return path:match("(.-)([^\\/]-%.?([^%.\\/]*))$") end --A function to split path to path, name, extension.
local Peripherals = {} --The loaded peripherals.
local MPer = {} --Mounted and initialized peripherals.
--A function to load the peripherals.
local function indexPeripherals(path)
local files = love.filesystem.getDirectoryItems(path)
for k,filename in ipairs(files) do
if love.filesystem.isDirectory(path..filename) then
indexPeripherals(path..filename.."/")
else
local p, n, e = splitFilePath(path..filename)
if e == "lua" then
local chunk, err = love.filesystem.load(path..n)
if not chunk then Peripherals[n:sub(0,-5)] = "Err: "..tostring(err) else
Peripherals[n:sub(0,-5)] = chunk() end
end
end
end
end
indexPeripherals("/Peripherals/") --Index and Load the peripherals
--Peripheral, Err = P(PeriheralName, MountedName, ConfigTabel)
local function P(per,m,conf)
if not per then return false, "Should provide peripheral name" end
if type(per) ~= "string" then return false, "Peripheral name should be a string, provided "..type(per) end
if not Peripherals[per] then return false, "'"..per.."' Peripheral doesn't exists" end
if type(Peripherals[per]) == "string" then return false, "Compile "..Peripherals[per] end
local m = m or per
if type(m) ~= "string" then return false, "Mounting name should be a string, provided "..type(m) end
if MPer[m] then return MPer[m] end--return false, "Mounting name '"..m.."' is already taken" end
local conf = conf or {}
if type(conf) ~= "table" then return false, "Configuration table should be a table, provided "..type(conf) end
local success, peripheral = pcall(Peripherals[per],conf)
if success then
MPer[m] = peripheral
coreg:register(peripheral,m)
else
peripheral = "Init Err: "..peripheral
end
return success, peripheral
end
if not love.filesystem.exists("/bconf.lua") or true then
love.filesystem.write("/bconf.lua",love.filesystem.read("/BIOS/bconf.lua"))
end
local bconfC, bconfErr, bconfDErr = love.filesystem.load("/bconf.lua")
if not bconfC then bconfC, bconfDErr = love.filesystem.load("/BIOS/bconf.lua") end --Load the default BConfig
if not bconfC then error(bconfDErr) end
setfenv(bconfC,{P = P,error=error,assert=assert}) --BConfig sandboxing
local success, bconfRErr = pcall(bconfC)
if not success then
bconfC, err = love.filesystem.load("/BIOS/bconf.lua")
if not bconfC then error(err) end
setfenv(bconfC,{P = P,error=error,assert=assert}) --BConfig sandboxing
bconfC()
end --Load the default BConfig
coreg:register(function()
local list = {}
for per, funcs in pairs(MPer) do
list[per] = {}
for name, func in pairs(funcs) do
table.insert(list[per],name)
end
end
return true, list
end,"BIOS:listPeripherals")
local function exe(...) --Excute a LIKO12 api function (to handle errors)
local args = {...}
if args[1] then
local nargs = {}
for k,v in ipairs(args) do --Clone the args, removing the first one
nargs[k-1] = v
end
return unpack(nargs)
else
return error(args[2])
end
end
local function flushOS(os,path)
local h = MPer.HDD
local path = path or "/"
local files = love.filesystem.getDirectoryItems("/OS/"..os..path)
for k,v in pairs(files) do
if love.filesystem.isDirectory("/OS/"..os..path..v) then
flushOS(os,path..v.."/")
else
exe(h.drive("C")) --Opereating systems are installed on C drive
exe(h.write(path..v,love.filesystem.read("/OS/"..os..path..v)))
end
end
end
--No OS Screen
local function noOS()
if MPer.GPU then
flushOS("CartOS") --Should be replaced by a gui
else
flushOS("CartOS")
end
end
local function startCoroutine()
if not MPer.HDD then return error("No HDD Periphrtal") end
local h = MPer.HDD
exe(h.drive("C"))
if (not exe(h.exists("/boot.lua"))) or true then noOS() end
local chunk, err = exe(h.load("/boot.lua"))
if not chunk then error(err or "") end
coreg:sandboxCoroutine(chunk)
local co = coroutine.create(chunk)
coreg:setCoroutine(co) --For peripherals to use.
if MPer.CPU then MPer.CPU.clearEStack() end
coreg:resumeCoroutine()
end
--POST screen
if MPer.GPU then --If there is an initialized gpu
local g = MPer.GPU
g.color(8)
local chars = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","-","_","@","#","$","&","*","!","+","=","%"}
--48x16 Terminal Size
function drawAnim() g.clear()
for x=1,exe(g.termwidth()) do for y=1,exe(g.termheight()) do
math.randomseed(os.clock()*os.time()*x)
g.color(math.floor(math.random(2,16)))
g.printCursor(x,y)
math.randomseed(os.clock()*os.time()*y)
local c = chars[math.floor(math.random(1,#chars))]
if math.random(0,20) % 2 == 0 then c = c:upper() end
g.print(c,_,true)
end end
end
g.clear()
g.printCursor(_,_,0)
local timer = 0
local stage = 1
events:register("love:update",function(dt)
if stage == 7 then --Create the coroutine
g.color(8)
g.clear(1)
g.printCursor(1,1,1)
startCoroutine()
stage = 8 --So coroutine don't get duplicated
end
if stage < 4 and stage > 1 then drawAnim() end
if stage < 8 then
timer = timer + dt
if timer > 0.25 then timer = timer -0.25
stage = stage +1
if stage < 5 then --[[drawAnim()]] elseif stage == 5 then g.clear() end
end
end
end)
else --Incase the gpu doesn't exists (Then can't enter the bios nor do the boot animation
startCoroutine()
end
--[[local GPU = Peripherals.GPU({_ClearOnRender=true}) --Create a new GPU
--FPS display
events:register("love:update",function(dt) love.window.setTitle("LIKO-12 FPS: "..love.timer.getFPS()) end)
--Debug Draw--
GPU.points(1,1, 192,1, 192,128, 1,128, 8)
GPU.points(0,1, 193,1, 193,128, 0,128, 3)
GPU.points(1,0, 192,0, 192,129, 1,129, 3)
GPU.rect(2,2, 190,126, true, 12)
GPU.line(2,2,191,2,191,127,2,127,2,2,12)
GPU.line(2,2, 191,127, 9)
GPU.line(191, 2,2,127, 9)
GPU.rect(10,42,10,10,false,9)
GPU.rect(10,30,10,10,false,9)
GPU.rect(10,30,10,10,true,8)
GPU.points(10,10, 10,19, 19,19, 19,10, 8)]]
|
--The BIOS should control the system of LIKO-12 and load the peripherals--
--For now it's just a simple BIOS to get LIKO-12 working.
--Require the engine libraries--
local events = require("Engine.events")
local coreg = require("Engine.coreg")
local function splitFilePath(path) return path:match("(.-)([^\\/]-%.?([^%.\\/]*))$") end --A function to split path to path, name, extension.
local Peripherals = {} --The loaded peripherals.
local MPer = {} --Mounted and initialized peripherals.
--A function to load the peripherals.
local function indexPeripherals(path)
local files = love.filesystem.getDirectoryItems(path)
for k,filename in ipairs(files) do
if love.filesystem.isDirectory(path..filename) then
indexPeripherals(path..filename.."/")
else
local p, n, e = splitFilePath(path..filename)
if e == "lua" then
local chunk, err = love.filesystem.load(path..n)
if not chunk then Peripherals[n:sub(0,-5)] = "Err: "..tostring(err) else
Peripherals[n:sub(0,-5)] = chunk() end
end
end
end
end
indexPeripherals("/Peripherals/") --Index and Load the peripherals
--Peripheral, Err = P(PeriheralName, MountedName, ConfigTabel)
local function P(per,m,conf)
if not per then return false, "Should provide peripheral name" end
if type(per) ~= "string" then return false, "Peripheral name should be a string, provided "..type(per) end
if not Peripherals[per] then return false, "'"..per.."' Peripheral doesn't exists" end
if type(Peripherals[per]) == "string" then return false, "Compile "..Peripherals[per] end
local m = m or per
if type(m) ~= "string" then return false, "Mounting name should be a string, provided "..type(m) end
if MPer[m] then return MPer[m] end--return false, "Mounting name '"..m.."' is already taken" end
local conf = conf or {}
if type(conf) ~= "table" then return false, "Configuration table should be a table, provided "..type(conf) end
local success, peripheral = pcall(Peripherals[per],conf)
if success then
MPer[m] = peripheral
coreg:register(peripheral,m)
else
peripheral = "Init Err: "..peripheral
end
return success, peripheral
end
if not love.filesystem.exists("/bconf.lua") or true then
love.filesystem.write("/bconf.lua",love.filesystem.read("/BIOS/bconf.lua"))
end
local bconfC, bconfErr, bconfDErr = love.filesystem.load("/bconf.lua")
if not bconfC then bconfC, bconfDErr = love.filesystem.load("/BIOS/bconf.lua") end --Load the default BConfig
if not bconfC then error(bconfDErr) end
setfenv(bconfC,{P = P,error=error,assert=assert}) --BConfig sandboxing
local success, bconfRErr = pcall(bconfC)
if not success then
bconfC, err = love.filesystem.load("/BIOS/bconf.lua")
if not bconfC then error(err) end
setfenv(bconfC,{P = P,error=error,assert=assert}) --BConfig sandboxing
bconfC()
end --Load the default BConfig
coreg:register(function()
local list = {}
for per, funcs in pairs(MPer) do
list[per] = {}
for name, func in pairs(funcs) do
table.insert(list[per],name)
end
end
return true, list
end,"BIOS:listPeripherals")
local function exe(...) --Excute a LIKO12 api function (to handle errors)
local args = {...}
if args[1] then
local nargs = {}
for k,v in ipairs(args) do --Clone the args, removing the first one
nargs[k-1] = v
end
return unpack(nargs)
else
return error(args[2])
end
end
local function flushOS(os,path)
local h = MPer.HDD
local path = path or "/"
local files = love.filesystem.getDirectoryItems("/OS/"..os..path)
for k,v in pairs(files) do
if love.filesystem.isDirectory("/OS/"..os..path..v) then
exe(h.newFolder(path..v))
flushOS(os,path..v.."/")
else
exe(h.drive("C")) --Opereating systems are installed on C drive
exe(h.write(path..v,love.filesystem.read("/OS/"..os..path..v)))
end
end
end
--No OS Screen
local function noOS()
if MPer.GPU then
flushOS("CartOS") --Should be replaced by a gui
else
flushOS("CartOS")
end
end
local function startCoroutine()
if not MPer.HDD then return error("No HDD Periphrtal") end
local h = MPer.HDD
exe(h.drive("C"))
if (not exe(h.exists("/boot.lua"))) or true then noOS() end
local chunk, err = exe(h.load("/boot.lua"))
if not chunk then error(err or "") end
local coglob = coreg:sandbox(chunk)
local co = coroutine.create(chunk)
coreg:setCoroutine(co,coglob) --For peripherals to use.
if MPer.CPU then MPer.CPU.clearEStack() end
coreg:resumeCoroutine()
end
--POST screen
if MPer.GPU then --If there is an initialized gpu
local g = MPer.GPU
g.color(8)
local chars = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","-","_","@","#","$","&","*","!","+","=","%"}
--48x16 Terminal Size
function drawAnim() g.clear()
for x=1,exe(g.termwidth()) do for y=1,exe(g.termheight()) do
math.randomseed(os.clock()*os.time()*x)
g.color(math.floor(math.random(2,16)))
g.printCursor(x,y)
math.randomseed(os.clock()*os.time()*y)
local c = chars[math.floor(math.random(1,#chars))]
if math.random(0,20) % 2 == 0 then c = c:upper() end
g.print(c,_,true)
end end
end
g.clear()
g.printCursor(_,_,0)
local timer = 0
local stage = 1
events:register("love:update",function(dt)
if stage == 7 then --Create the coroutine
g.color(8)
g.clear(1)
g.printCursor(1,1,1)
startCoroutine()
stage = 8 --So coroutine don't get duplicated
end
if stage < 4 and stage > 1 then drawAnim() end
if stage < 8 then
timer = timer + dt
if timer > 0.25 then timer = timer -0.25
stage = stage +1
if stage < 5 then --[[drawAnim()]] elseif stage == 5 then g.clear() end
end
end
end)
else --Incase the gpu doesn't exists (Then can't enter the bios nor do the boot animation
startCoroutine()
end
--[[local GPU = Peripherals.GPU({_ClearOnRender=true}) --Create a new GPU
--FPS display
events:register("love:update",function(dt) love.window.setTitle("LIKO-12 FPS: "..love.timer.getFPS()) end)
--Debug Draw--
GPU.points(1,1, 192,1, 192,128, 1,128, 8)
GPU.points(0,1, 193,1, 193,128, 0,128, 3)
GPU.points(1,0, 192,0, 192,129, 1,129, 3)
GPU.rect(2,2, 190,126, true, 12)
GPU.line(2,2,191,2,191,127,2,127,2,2,12)
GPU.line(2,2, 191,127, 9)
GPU.line(191, 2,2,127, 9)
GPU.rect(10,42,10,10,false,9)
GPU.rect(10,30,10,10,false,9)
GPU.rect(10,30,10,10,true,8)
GPU.points(10,10, 10,19, 19,19, 19,10, 8)]]
|
Bugfixes
|
Bugfixes
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
84d5470a4143f497ec0242c60fbeff9d0800afaf
|
xmake/core/base/profiler.lua
|
xmake/core/base/profiler.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 profiler.lua
--
-- define module
local profiler = {}
-- load modules
local os = require("base/os")
local path = require("base/path")
local table = require("base/table")
local utils = require("base/utils")
local string = require("base/string")
-- get the function title
function profiler:_func_title(funcinfo)
-- check
assert(funcinfo)
-- the function name
local name = funcinfo.name or 'anonymous'
-- the function line
local line = string.format("%d", funcinfo.linedefined or 0)
-- the function source
local source = funcinfo.short_src or 'C_FUNC'
if os.isfile(source) then
source = path.relative(source, xmake._PROGRAM_DIR)
end
-- make title
return string.format("%-30s: %s: %s", name, source, line)
end
-- get the function report
function profiler:_func_report(funcinfo)
-- get the function title
local title = self:_func_title(funcinfo)
-- get the function report
local report = self._REPORTS_BY_TITLE[title]
if not report then
-- init report
report =
{
title = self:_func_title(funcinfo)
, callcount = 0
, totaltime = 0
}
-- save it
self._REPORTS_BY_TITLE[title] = report
table.insert(self._REPORTS, report)
end
-- ok?
return report
end
-- profiling call
function profiler:_profiling_call(funcinfo)
-- get the function report
local report = self:_func_report(funcinfo)
assert(report)
-- save the call time
report.calltime = os.clock()
-- update the call count
report.callcount = report.callcount + 1
end
-- profiling return
function profiler:_profiling_return(funcinfo)
-- get the stoptime
local stoptime = os.clock()
-- get the function report
local report = self:_func_report(funcinfo)
assert(report)
-- update the total time
if report.calltime then
report.totaltime = report.totaltime + (stoptime - report.calltime)
end
end
-- the profiling handler
function profiler._profiling_handler(hooktype)
-- the function info
local funcinfo = debug.getinfo(2, 'nS')
-- dispatch it
if hooktype == "call" then
profiler:_profiling_call(funcinfo)
elseif hooktype == "return" then
profiler:_profiling_return(funcinfo)
end
end
-- the tracing handler
function profiler._tracing_handler(hooktype)
-- the function info
local funcinfo = debug.getinfo(2, 'nS')
-- is call?
if hooktype == "call" then
-- is xmake function?
local name = funcinfo.name
local source = funcinfo.short_src or 'C_FUNC'
if name and os.isfile(source) then
-- the function line
local line = string.format("%d", funcinfo.linedefined or 0)
-- get the relative source
source = path.relative(source, xmake._PROGRAM_DIR)
-- trace it
utils.print("%-30s: %s: %s", name, source, line)
end
end
end
-- start profiling
function profiler:start(mode)
-- trace?
if mode and mode == "trace" then
debug.sethook(profiler._tracing_handler, 'cr', 0)
else
-- init reports
self._REPORTS = {}
self._REPORTS_BY_TITLE = {}
-- save the start time
self._STARTIME = os.clock()
-- start to hook
debug.sethook(profiler._profiling_handler, 'cr', 0)
end
end
-- stop profiling
function profiler:stop(mode)
-- trace?
if mode and mode == "trace" then
-- stop to hook
debug.sethook()
else
-- save the stop time
self._STOPTIME = os.clock()
-- stop to hook
debug.sethook()
-- calculate the total time
local totaltime = self._STOPTIME - self._STARTIME
-- sort reports
table.sort(self._REPORTS, function(a, b)
return a.totaltime > b.totaltime
end)
-- show reports
for _, report in ipairs(self._REPORTS) do
-- calculate percent
local percent = (report.totaltime / totaltime) * 100
if percent < 1 then
break
end
-- trace
utils.print("%6.3f, %6.2f%%, %7d, %s", report.totaltime, percent, report.callcount, report.title)
end
end
end
-- return module
return profiler
|
--!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 profiler.lua
--
-- define module
local profiler = {}
-- load modules
local os = require("base/os")
local path = require("base/path")
local table = require("base/table")
local utils = require("base/utils")
local string = require("base/string")
-- get the function title
function profiler:_func_title(funcinfo)
-- check
assert(funcinfo)
-- the function name
local name = funcinfo.name or 'anonymous'
-- the function line
local line = string.format("%d", funcinfo.linedefined or 0)
-- the function source
local source = funcinfo.short_src or 'C_FUNC'
if os.isfile(source) then
source = path.relative(source, xmake._PROGRAM_DIR)
end
-- make title
return string.format("%-30s: %s: %s", name, source, line)
end
-- get the function report
function profiler:_func_report(funcinfo)
-- get the function title
local title = self:_func_title(funcinfo)
-- get the function report
local report = self._REPORTS_BY_TITLE[title]
if not report then
-- init report
report =
{
title = self:_func_title(funcinfo)
, callcount = 0
, totaltime = 0
}
-- save it
self._REPORTS_BY_TITLE[title] = report
table.insert(self._REPORTS, report)
end
-- ok?
return report
end
-- profiling call
function profiler:_profiling_call(funcinfo)
-- get the function report
local report = self:_func_report(funcinfo)
assert(report)
-- save the call time
report.calltime = os.clock()
-- update the call count
report.callcount = report.callcount + 1
end
-- profiling return
function profiler:_profiling_return(funcinfo)
-- get the stoptime
local stoptime = os.clock()
-- get the function report
local report = self:_func_report(funcinfo)
assert(report)
-- update the total time
if report.calltime and report.calltime > 0 then
report.totaltime = report.totaltime + (stoptime - report.calltime)
report.calltime = 0
end
end
-- the profiling handler
function profiler._profiling_handler(hooktype)
-- the function info
local funcinfo = debug.getinfo(2, 'nS')
-- dispatch it
if hooktype == "call" then
profiler:_profiling_call(funcinfo)
elseif hooktype == "return" then
profiler:_profiling_return(funcinfo)
end
end
-- the tracing handler
function profiler._tracing_handler(hooktype)
-- the function info
local funcinfo = debug.getinfo(2, 'nS')
-- is call?
if hooktype == "call" then
-- is xmake function?
local name = funcinfo.name
local source = funcinfo.short_src or 'C_FUNC'
if name and os.isfile(source) then
-- the function line
local line = string.format("%d", funcinfo.linedefined or 0)
-- get the relative source
source = path.relative(source, xmake._PROGRAM_DIR)
-- trace it
utils.print("%-30s: %s: %s", name, source, line)
end
end
end
-- start profiling
function profiler:start(mode)
-- trace?
if mode and mode == "trace" then
debug.sethook(profiler._tracing_handler, 'cr', 0)
else
-- init reports
self._REPORTS = {}
self._REPORTS_BY_TITLE = {}
-- save the start time
self._STARTIME = os.clock()
-- start to hook
debug.sethook(profiler._profiling_handler, 'cr', 0)
end
end
-- stop profiling
function profiler:stop(mode)
-- trace?
if mode and mode == "trace" then
-- stop to hook
debug.sethook()
else
-- save the stop time
self._STOPTIME = os.clock()
-- stop to hook
debug.sethook()
-- calculate the total time
local totaltime = self._STOPTIME - self._STARTIME
-- sort reports
table.sort(self._REPORTS, function(a, b)
return a.totaltime > b.totaltime
end)
-- show reports
for _, report in ipairs(self._REPORTS) do
-- calculate percent
local percent = (report.totaltime / totaltime) * 100
if percent < 1 then
break
end
-- trace
utils.print("%6.3f, %6.2f%%, %7d, %s", report.totaltime, percent, report.callcount, report.title)
end
end
end
-- return module
return profiler
|
fix profiler bug
|
fix profiler bug
|
Lua
|
apache-2.0
|
waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake
|
c7df5d519892976481ba59056e8225258261394b
|
src/make.lua
|
src/make.lua
|
local file_dir
local test_dir
local function git_fresh(fname)
local f = io.open((test_dir / fname):string())
local test_file = f:read('*a')
f:close()
local map_file
f = io.open((file_dir / fname):string())
if f then
map_file = f:read('*a')
f:close()
end
if test_file ~= map_file then
f = io.open((file_dir / fname):string(), 'w')
f:write(test_file)
f:close()
print('[]: ' .. fname)
end
end
local function main()
-- arg[1]Ϊͼ, arg[2]Ϊ·
local flag_newmap
if (not arg) or (#arg < 2) then
flag_newmap = true
end
local input_map = flag_newmap and (arg[1] .. 'src\\RPLegend.w3x') or arg[1]
local root_dir = flag_newmap and arg[1] or arg[2]
--requireѰ·
package.path = package.path .. ';' .. root_dir .. 'src\\?.lua'
package.cpath = package.cpath .. ';' .. root_dir .. 'build\\?.dll'
require 'luabind'
require 'filesystem'
require 'utility'
--·
git_path = root_dir
local input_map = fs.path(input_map)
local root_dir = fs.path(root_dir)
file_dir = root_dir / 'map'
fs.create_directories(root_dir / 'test')
test_dir = root_dir / 'test'
local output_map = test_dir / input_map:filename():string()
--һݵͼ
pcall(fs.copy_file, input_map, output_map, true)
--ͼ
local inmap = mpq_open(output_map)
if inmap then
print('[ɹ]: ' .. input_map:string())
else
print('[ʧ]: ' .. input_map:string())
return
end
local fname
if not flag_newmap then
--listfile
fname = '(listfile)'
if inmap:extract(fname, test_dir / fname) then
print('[ɹ]: ' .. fname)
else
print('[ʧ]: ' .. fname)
return
end
--listfile
for line in io.lines((test_dir / fname):string()) do
--listfileоٵÿһļ
if inmap:extract(line, test_dir / line) then
print('[ɹ]: ' .. line)
git_fresh(line)
else
print('[ʧ]: ' .. line)
return
end
end
end
--dirµļ,ͼ
local files = {}
local function dir_scan(dir)
for full_path in dir:list_directory() do
if fs.is_directory(full_path) then
-- ݹ鴦
dir_scan(full_path)
else
local name = full_path:string():gsub(file_dir:string() .. '\\', '')
--ļfiles
table.insert(files, name)
end
end
end
dir_scan(file_dir)
--µlistfile
fname = '(listfile)'
local listfile_path = test_dir / fname
local listfile = io.open(listfile_path:string(), 'w')
listfile:write(table.concat(files, '\n') .. "\n")
listfile:close()
git_fresh(fname)
--ļȫȥ
table.insert(files, '(listfile)')
for _, name in ipairs(files) do
inmap:import(name, file_dir / name)
end
inmap:close()
if not flag_newmap then
pcall(fs.copy_file, output_map, input_map:parent_path() / ('new_' .. input_map:filename():string()), true)
end
print('[]: ʱ ' .. os.clock() .. ' ')
end
main()
|
local file_dir
local test_dir
local function git_fresh(fname)
local f = io.open((test_dir / fname):string(), 'rb')
local test_file = f:read('*a')
f:close()
local map_file
f = io.open((file_dir / fname):string(), 'rb')
if f then
map_file = f:read('*a')
f:close()
end
if test_file ~= map_file then
f = io.open((file_dir / fname):string(), 'wb')
f:write(test_file)
f:close()
print('[ɹ]: ' .. fname)
end
end
local function main()
-- arg[1]Ϊͼ, arg[2]Ϊ·
local flag_newmap
if (not arg) or (#arg < 2) then
flag_newmap = true
end
local input_map = flag_newmap and (arg[1] .. 'src\\RPLegend.w3x') or arg[1]
local root_dir = flag_newmap and arg[1] or arg[2]
--requireѰ·
package.path = package.path .. ';' .. root_dir .. 'src\\?.lua'
package.cpath = package.cpath .. ';' .. root_dir .. 'build\\?.dll'
require 'luabind'
require 'filesystem'
require 'utility'
for name in pairs(fs) do
print(name)
end
--·
git_path = root_dir
local input_map = fs.path(input_map)
local root_dir = fs.path(root_dir)
file_dir = root_dir / 'map'
fs.create_directories(root_dir / 'test')
test_dir = root_dir / 'test'
local output_map = test_dir / input_map:filename():string()
--һݵͼ
pcall(fs.copy_file, input_map, output_map, true)
--ͼ
local inmap = mpq_open(output_map)
if inmap then
print('[ɹ]: ' .. input_map:string())
else
print('[ʧ]: ' .. input_map:string())
return
end
local fname
if not flag_newmap then
--listfile
fname = '(listfile)'
if inmap:extract(fname, test_dir / fname) then
print('[ɹ]: ' .. fname)
else
print('[ʧ]: ' .. fname)
return
end
--listfile
for line in io.lines((test_dir / fname):string()) do
--listfileоٵÿһļ
if inmap:extract(line, test_dir / line) then
print('[ɹ]: ' .. line)
git_fresh(line)
else
print('[ʧ]: ' .. line)
return
end
end
end
--dirµļ,ͼ
local files = {}
local function dir_scan(dir)
for full_path in dir:list_directory() do
if fs.is_directory(full_path) then
-- ݹ鴦
dir_scan(full_path)
else
local name = full_path:string():gsub(file_dir:string() .. '\\', '')
--ļfiles
table.insert(files, name)
end
end
end
dir_scan(file_dir)
--µlistfile
fname = '(listfile)'
local listfile_path = test_dir / fname
local listfile = io.open(listfile_path:string(), 'w')
listfile:write(table.concat(files, '\n') .. "\n")
listfile:close()
git_fresh(fname)
--ļȫȥ
table.insert(files, '(listfile)')
for _, name in ipairs(files) do
inmap:import(name, file_dir / name)
end
inmap:close()
if not flag_newmap then
pcall(fs.copy_file, output_map, input_map:parent_path() / ('new_' .. input_map:filename():string()), true)
end
print('[]: ʱ ' .. os.clock() .. ' ')
end
main()
|
修正了会错误更改某些二进制文件的BUG
|
修正了会错误更改某些二进制文件的BUG
|
Lua
|
apache-2.0
|
syj2010syj/RPLegend
|
ca4d4953a5d57de1746230014014998dc9622a81
|
nvim/lua/plugins/cmp.lua
|
nvim/lua/plugins/cmp.lua
|
local require_safe = require("utils").require_safe
local cmp = require_safe("cmp")
local luasnip = require_safe("luasnip")
require("luasnip/loaders/from_vscode").lazy_load()
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
cmp.setup {
snippet = {
expand = function(args)
luasnip.lsp_expand(args.body) -- For `luasnip` users.
end,
},
mapping = {
["<C-b>"] = cmp.mapping(cmp.mapping.scroll_docs(-4), { "i", "c" }),
["<C-f>"] = cmp.mapping(cmp.mapping.scroll_docs(4), { "i", "c" }),
["<C-Space>"] = cmp.mapping(cmp.mapping.complete(), { "i", "c" }),
["<C-y>"] = cmp.config.disable, -- Specify `cmp.config.disable` if you want to remove the default `<C-y>` mapping.
["<C-e>"] = cmp.mapping {
i = cmp.mapping.abort(),
c = cmp.mapping.close(),
},
-- Accept currently selected item. If none selected, `select` first item.
-- Set `select` to `false` to only confirm explicitly selected items.
["<CR>"] = cmp.mapping.confirm { select = true },
["<Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_next_item()
elseif luasnip.expandable() then
luasnip.expand()
elseif luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
elseif has_words_before() then
fallback()
else
fallback()
end
end, {
"i",
"s",
}),
["<S-Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_prev_item()
elseif luasnip.jumpable(-1) then
luasnip.jump(-1)
else
fallback()
end
end, {
"i",
"s",
}),
},
formatting = {
fields = { "abbr", "menu" },
format = function(entry, vim_item)
vim_item.menu = ({
nvim_lsp = "[LSP]",
luasnip = "[Snippet]",
buffer = "[Buffer]",
path = "[Path]",
})[entry.source.name]
return vim_item
end,
},
sources = {
{ name = "nvim_lsp" },
{ name = "luasnip" },
{ name = "buffer" },
{ name = "path" },
},
confirm_opts = {
behavior = cmp.ConfirmBehavior.Replace,
select = false,
},
documentation = {
border = { "╭", "─", "╮", "│", "╯", "─", "╰", "│" },
},
views = {
entries = 'native',
},
experimental = {
ghost_text = false,
},
}
|
local require_safe = require("utils").require_safe
local cmp = require_safe("cmp")
local luasnip = require_safe("luasnip")
require("luasnip/loaders/from_vscode").lazy_load()
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
cmp.setup {
snippet = {
expand = function(args)
luasnip.lsp_expand(args.body) -- For `luasnip` users.
end,
},
mapping = {
["<C-b>"] = cmp.mapping(cmp.mapping.scroll_docs(-4), { "i", "c" }),
["<C-f>"] = cmp.mapping(cmp.mapping.scroll_docs(4), { "i", "c" }),
["<C-Space>"] = cmp.mapping(cmp.mapping.complete(), { "i", "c" }),
["<C-y>"] = cmp.config.disable, -- Specify `cmp.config.disable` if you want to remove the default `<C-y>` mapping.
["<C-e>"] = cmp.mapping {
i = cmp.mapping.abort(),
c = cmp.mapping.close(),
},
-- Accept currently selected item. If none selected, `select` first item.
-- Set `select` to `false` to only confirm explicitly selected items.
["<CR>"] = cmp.mapping.confirm { select = true },
["<Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_next_item()
elseif luasnip.expandable() then
luasnip.expand()
elseif luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
elseif has_words_before() then
fallback()
else
fallback()
end
end, {
"i",
"s",
}),
["<S-Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_prev_item()
elseif luasnip.jumpable(-1) then
luasnip.jump(-1)
else
fallback()
end
end, {
"i",
"s",
}),
},
formatting = {
fields = { "abbr", "menu" },
format = function(entry, vim_item)
vim_item.menu = ({
nvim_lsp = "[LSP]",
luasnip = "[Snippet]",
buffer = "[Buffer]",
path = "[Path]",
})[entry.source.name]
return vim_item
end,
},
sources = {
{ name = "nvim_lsp" },
{ name = "luasnip" },
{ name = "buffer" },
{ name = "path" },
},
confirm_opts = {
behavior = cmp.ConfirmBehavior.Replace,
select = false,
},
window = {
completion = {
border = { "┌", "─", "┐", "│", "┘", "─", "└", "│" },
},
documentation = {
border = { "┌", "─", "┐", "│", "┘", "─", "└", "│" },
},
},
views = {
entries = 'native',
},
experimental = {
ghost_text = false,
},
}
|
Nvim: fix cmp border config after update
|
Nvim: fix cmp border config after update
|
Lua
|
mit
|
aasare/aaku
|
31decbe144fca7578a872635207c8e450bd14188
|
gateway/src/apicast/policy/find_service/path_based_finder.lua
|
gateway/src/apicast/policy/find_service/path_based_finder.lua
|
local mapping_rules_matcher = require 'apicast.mapping_rules_matcher'
local escape = require("resty.http.uri_escape")
local _M = {}
function _M.find_service(config_store, host)
local found
local services = config_store:find_by_host(host)
local method = ngx.req.get_method()
local uri = escape.escape_uri(ngx.var.uri)
for s=1, #services do
local service = services[s]
local hosts = service.hosts or {}
for h=1, #hosts do
if hosts[h] == host then
local name = service.system_name or service.id
ngx.log(ngx.DEBUG, 'service ', name, ' matched host ', hosts[h])
local matches = mapping_rules_matcher.matches(method, uri, {}, service.rules)
-- matches() also returns the index of the first rule that matched.
-- As a future optimization, in the part of the code that calculates
-- the usage, we could use this to avoid trying to match again all the
-- rules before the one that matched.
if matches then
found = service
break
end
end
end
if found then break end
end
return found
end
return _M
|
local mapping_rules_matcher = require 'apicast.mapping_rules_matcher'
local escape = require("resty.http.uri_escape")
local pretty = require("pl.pretty")
local _M = {}
function _M.find_service(config_store, host)
local found
local services = config_store:find_by_host(host)
local method = ngx.req.get_method()
local uri = escape.escape_uri(ngx.var.uri)
local args = ngx.req.get_uri_args()
for s=1, #services do
local service = services[s]
local hosts = service.hosts or {}
for h=1, #hosts do
if hosts[h] == host then
local name = service.system_name or service.id
ngx.log(ngx.DEBUG, 'service ', name, ' matched host ', hosts[h])
local matches = mapping_rules_matcher.matches(method, uri, args, service.rules)
-- matches() also returns the index of the first rule that matched.
-- As a future optimization, in the part of the code that calculates
-- the usage, we could use this to avoid trying to match again all the
-- rules before the one that matched.
if matches then
found = service
break
end
end
end
if found then break end
end
return found
end
return _M
|
Fix: Path base routing match query args
|
Fix: Path base routing match query args
Fix THREESCALE-5149
|
Lua
|
mit
|
3scale/docker-gateway,3scale/docker-gateway
|
cd2a91b23006a09a7e432d101d9d72011931a58c
|
UCDvehicleShops/client.lua
|
UCDvehicleShops/client.lua
|
local markerInfo = {}
local sX, sY = guiGetScreenSize()
GUI = {
gridlist = {},
window = {},
button = {}
}
GUI.window = GuiWindow(1085, 205, 281, 361, "UCD | Vehicle Shop - Low End", false)
GUI.window.sizable = false
GUI.window.visible = false
GUI.window.alpha = 255
GUI.gridlist = GuiGridList(9, 28, 262, 280, false, GUI.window)
guiGridListAddColumn(GUI.gridlist, "Vehicle", 0.6)
guiGridListAddColumn(GUI.gridlist, "Price", 0.3)
GUI.button["buy"] = GuiButton(10, 318, 80, 30, "Buy", false, GUI.window)
GUI.button["colour"] = GuiButton(101, 318, 80, 30, "Colour", false, GUI.window)
GUI.button["close"] = GuiButton(191, 318, 80, 30, "Close", false, GUI.window)
function onHitShopMarker(plr, matchingDimension)
if (plr == localPlayer and not localPlayer.vehicle and matchingDimension and plr.interior == 0) then
if (localPlayer.position.z < source.position.z + 1.5 and localPlayer.position.z > source.position.z - 1.5) then
exports.UCDdx:add("vehicleshop", "Press Z: Buy Vehicle", 255, 255, 0)
bindKey("z", "down", openGUI, source)
end
end
end
function onLeaveShopMarker(plr, matchingDimension)
if (plr == localPlayer and not localPlayer.vehicle and matchingDimension and plr.interior == 0) then
exports.UCDdx:del("vehicleshop")
unbindKey("z", "down", closeGUI)
closeGUI()
end
end
for i, info in ipairs(markers) do
local m = Marker(info.x, info.y, info.z - 1, "cylinder", 2, 255, 255, 180, 170)
-- Custom blips
if (type(blips[info.t]) == "string") then
local b = exports.UCDblips:createCustomBlip(info.x, info.y, 16, 16, blips[info.t], 300)
exports.UCDblips:setCustomBlipStreamRadius(b, 50)
else
Blip.createAttachedTo(m, blips[info.t], 2, 0, 0, 0, 0, 0, 300)
end
addEventHandler("onClientMarkerHit", m, onHitShopMarker)
addEventHandler("onClientMarkerLeave", m, onLeaveShopMarker)
markerInfo[m] = {info.t, i}
end
function openGUI(_, _, m)
if (GUI.visible) then return end
if (m and isElement(m)) then
if (getDistanceBetweenPoints3D(localPlayer.position, m.position) > 1.5) then
return
end
GUI.window.text = "UCD | Vehicle Shop - "..tostring(markerInfo[m][1])
populateGridList(markerInfo[m][1])
end
GUI.window.visible = true
GUI.window:setPosition(sX - 281, sY / 2 - (361 / 2), false)
showCursor(true)
exports.UCDdx:del("vehicleshop")
unbindKey("z", "down", closeGUI)
_markerInfo = markerInfo[m]
end
function closeGUI()
if (not GUI.window.visible) then return end
GUI.gridlist:clear()
GUI.window.visible = false
showCursor(false)
exports.UCDdx:del("vehicleshop")
unbindKey("z", "down", closeGUI)
if (Camera.target ~= localPlayer) then
Camera.target = localPlayer
end
_markerInfo = nil
if (veh and isElement(veh)) then
veh:destroy()
end
veh = nil
end
addEventHandler("onClientGUIClick", GUI.button["close"], closeGUI, false)
function populateGridList(var)
GUI.gridlist:clear()
for k, v in ipairs(vehicles[var] or {}) do
local name = getVehicleNameFromModel(v)
local price = prices[name]
local row = guiGridListAddRow(GUI.gridlist)
guiGridListSetItemText(GUI.gridlist, row, 1, tostring(name), false, false)
guiGridListSetItemText(GUI.gridlist, row, 2, tostring(exports.UCDutil:tocomma(price)), false, false)
if (price ~= nil and price <= localPlayer:getMoney()) then
guiGridListSetItemColor(GUI.gridlist, row, 1, 0, 255, 0)
guiGridListSetItemColor(GUI.gridlist, row, 2, 0, 255, 0)
else
guiGridListSetItemColor(GUI.gridlist, row, 1, 255, 0, 0)
guiGridListSetItemColor(GUI.gridlist, row, 2, 255, 0, 0)
end
end
end
function onClickVehicle()
local row = guiGridListGetSelectedItem(GUI.gridlist)
if (row and row ~= -1) then
local id = getVehicleModelFromName(guiGridListGetItemText(GUI.gridlist, row, 1))
if (id and _markerInfo) then
if (veh and isElement(veh)) then
veh:destroy()
veh = nil
end
local i = _markerInfo[2]
local p = markers[i].p
veh = Vehicle(id, p)
veh.rotation = Vector3(0, 0, markers[i].r)
Camera.setMatrix(markers[i].c, p, 0, 180)
end
end
end
addEventHandler("onClientGUIClick", GUI.gridlist, onClickVehicle, false)
function onClickBuy()
local row = guiGridListGetSelectedItem(GUI.gridlist)
if (row and row ~= -1) then
local id = getVehicleModelFromName(guiGridListGetItemText(GUI.gridlist, row, 1))
if (id and veh and isElement(veh)) then
triggerServerEvent("UCDvehicleShops.purchase", localPlayer, id, {veh:getColor(true)}, _markerInfo[2])
closeGUI()
end
end
end
addEventHandler("onClientGUIClick", GUI.button["buy"], onClickBuy, false)
function onClickColour()
if (veh and isElement(veh)) then
GUI.window.visible = false
colorPicker.openSelect()
addEventHandler("onClientRender", root, updateColor)
end
end
addEventHandler("onClientGUIClick", GUI.button["colour"], onClickColour, false)
function updateColor()
if (not colorPicker.isSelectOpen) then return end
local r, g, b = colorPicker.updateTempColors()
if (veh and isElement(veh)) then
local r1, g1, b1, r2, g2, b2 = getVehicleColor(veh, true)
if (guiCheckBoxGetSelected(checkColor1)) then
r1, g1, b1 = r, g, b
end
if (guiCheckBoxGetSelected(checkColor2)) then
r2, g2, b2 = r, g, b
end
--if (guiCheckBoxGetSelected(checkColor3)) then
-- setVehicleHeadLightColor(localPlayer.vehicle, r, g, b)
--end
setVehicleColor(veh, r1, g1, b1, r2, g2, b2)
tempColors = {r1, g1, b1, r2, g2, b2}
end
end
|
local markerInfo = {}
local sX, sY = guiGetScreenSize()
GUI = {
gridlist = nil,
window = {},
button = {}
}
GUI.window = GuiWindow(1085, 205, 281, 361, "UCD | Vehicle Shop - Low End", false)
GUI.window.sizable = false
GUI.window.visible = false
GUI.window.alpha = 255
function createGridList()
if (GUI.gridlist and isElement(GUI.gridlist)) then
GUI.gridlist:destroy()
GUI.gridlist = nil
end
GUI.gridlist = GuiGridList(9, 28, 262, 280, false, GUI.window)
guiGridListAddColumn(GUI.gridlist, "Vehicle", 0.6)
guiGridListAddColumn(GUI.gridlist, "Price", 0.3)
addEventHandler("onClientGUIClick", GUI.gridlist, onClickVehicle, false)
end
addEventHandler("onClientResourceStart", resourceRoot, createGridList)
GUI.button["buy"] = GuiButton(10, 318, 80, 30, "Buy", false, GUI.window)
GUI.button["colour"] = GuiButton(101, 318, 80, 30, "Colour", false, GUI.window)
GUI.button["close"] = GuiButton(191, 318, 80, 30, "Close", false, GUI.window)
function onHitShopMarker(plr, matchingDimension)
if (plr == localPlayer and not localPlayer.vehicle and matchingDimension and plr.interior == 0) then
if (localPlayer.position.z < source.position.z + 1.5 and localPlayer.position.z > source.position.z - 1.5) then
exports.UCDdx:add("vehicleshop", "Press Z: Buy Vehicle", 255, 255, 0)
bindKey("z", "down", openGUI, source)
end
end
end
function onLeaveShopMarker(plr, matchingDimension)
if (plr == localPlayer and not localPlayer.vehicle and matchingDimension and plr.interior == 0) then
exports.UCDdx:del("vehicleshop")
unbindKey("z", "down", closeGUI)
closeGUI()
end
end
for i, info in ipairs(markers) do
local m = Marker(info.x, info.y, info.z - 1, "cylinder", 2, 255, 255, 180, 170)
-- Custom blips
if (type(blips[info.t]) == "string") then
local b = exports.UCDblips:createCustomBlip(info.x, info.y, 16, 16, blips[info.t], 300)
exports.UCDblips:setCustomBlipStreamRadius(b, 50)
else
Blip.createAttachedTo(m, blips[info.t], 2, 0, 0, 0, 0, 0, 300)
end
addEventHandler("onClientMarkerHit", m, onHitShopMarker)
addEventHandler("onClientMarkerLeave", m, onLeaveShopMarker)
markerInfo[m] = {info.t, i}
end
function openGUI(_, _, m)
if (GUI.visible) then return end
if (m and isElement(m)) then
if (getDistanceBetweenPoints3D(localPlayer.position, m.position) > 1.5) then
return
end
createGridList()
GUI.window.text = "UCD | Vehicle Shop - "..tostring(markerInfo[m][1])
populateGridList(markerInfo[m][1])
end
--GUI.gridlist = GuiGridList(9, 28, 262, 280, false, GUI.window)
GUI.window.visible = true
GUI.window:setPosition(sX - 281, sY / 2 - (361 / 2), false)
showCursor(true)
exports.UCDdx:del("vehicleshop")
unbindKey("z", "down", closeGUI)
_markerInfo = markerInfo[m]
end
function closeGUI()
if (not GUI.window.visible) then return end
createGridList()
GUI.window.visible = false
showCursor(false)
exports.UCDdx:del("vehicleshop")
unbindKey("z", "down", closeGUI)
if (Camera.target ~= localPlayer) then
Camera.target = localPlayer
end
_markerInfo = nil
if (veh and isElement(veh)) then
veh:destroy()
end
veh = nil
end
addEventHandler("onClientGUIClick", GUI.button["close"], closeGUI, false)
function populateGridList(var)
--GUI.gridlist:destroy()
--GUI.gridlist = GuiGridList(9, 28, 262, 280, false, GUI.window)
--createGridList()
for k, v in ipairs(vehicles[var] or {}) do
local name = getVehicleNameFromModel(v)
local price = prices[name]
local row = guiGridListAddRow(GUI.gridlist)
guiGridListSetItemText(GUI.gridlist, row, 1, tostring(name), false, false)
guiGridListSetItemText(GUI.gridlist, row, 2, tostring(exports.UCDutil:tocomma(price)), false, false)
if (price ~= nil and price <= localPlayer:getMoney()) then
guiGridListSetItemColor(GUI.gridlist, row, 1, 0, 255, 0)
guiGridListSetItemColor(GUI.gridlist, row, 2, 0, 255, 0)
else
guiGridListSetItemColor(GUI.gridlist, row, 1, 255, 0, 0)
guiGridListSetItemColor(GUI.gridlist, row, 2, 255, 0, 0)
end
end
end
function onClickVehicle()
local row = guiGridListGetSelectedItem(GUI.gridlist)
if (row and row ~= -1) then
local id = getVehicleModelFromName(guiGridListGetItemText(GUI.gridlist, row, 1))
if (id and _markerInfo) then
if (veh and isElement(veh)) then
veh:destroy()
veh = nil
end
local i = _markerInfo[2]
local p = markers[i].p
veh = Vehicle(id, p)
veh.rotation = Vector3(0, 0, markers[i].r)
Camera.setMatrix(markers[i].c, p, 0, 180)
end
end
end
--addEventHandler("onClientGUIClick", GUI.gridlist, onClickVehicle, false)
function onClickBuy()
local row = guiGridListGetSelectedItem(GUI.gridlist)
if (row and row ~= -1) then
local id = getVehicleModelFromName(guiGridListGetItemText(GUI.gridlist, row, 1))
if (id and veh and isElement(veh)) then
triggerServerEvent("UCDvehicleShops.purchase", localPlayer, id, {veh:getColor(true)}, _markerInfo[2])
closeGUI()
end
end
end
addEventHandler("onClientGUIClick", GUI.button["buy"], onClickBuy, false)
function onClickColour()
if (veh and isElement(veh)) then
GUI.window.visible = false
colorPicker.openSelect()
addEventHandler("onClientRender", root, updateColor)
end
end
addEventHandler("onClientGUIClick", GUI.button["colour"], onClickColour, false)
function updateColor()
if (not colorPicker.isSelectOpen) then return end
local r, g, b = colorPicker.updateTempColors()
if (veh and isElement(veh)) then
local r1, g1, b1, r2, g2, b2 = getVehicleColor(veh, true)
if (guiCheckBoxGetSelected(checkColor1)) then
r1, g1, b1 = r, g, b
end
if (guiCheckBoxGetSelected(checkColor2)) then
r2, g2, b2 = r, g, b
end
--if (guiCheckBoxGetSelected(checkColor3)) then
-- setVehicleHeadLightColor(localPlayer.vehicle, r, g, b)
--end
setVehicleColor(veh, r1, g1, b1, r2, g2, b2)
tempColors = {r1, g1, b1, r2, g2, b2}
end
end
|
UCDvehicleShops
|
UCDvehicleShops
- Fixed grid list sorting fuckung up when you sort a gridlist, then reopen the panel.
|
Lua
|
mit
|
nokizorque/ucd,nokizorque/ucd
|
ed788623be232592193783c58fcddd4c96cc1c28
|
packages/lime-system/files/usr/lib/lua/lime/wireless.lua
|
packages/lime-system/files/usr/lib/lua/lime/wireless.lua
|
#!/usr/bin/lua
module(..., package.seeall)
function generate_ssid()
local id = assert(x:get("lime", "wireless", "ssid"))
local r1, r2, r3 = node_id()
return string.format("%02x%02x%02x.%s", r1, r2, r3, id)
end
function clean()
print("Clearing wireless config...")
x:foreach("wireless", "wifi-iface", function(s)
x:delete("wireless", s[".name"])
end)
end
function init()
-- TODO
end
function configure()
local protocols = assert(x:get("lime", "network", "protos"))
local vlans = assert(x:get("lime", "network", "vlans"))
local n1, n2, n3 = network_id()
local r1, r2, r3 = node_id()
local channel2 = assert(x:get("lime", "wireless", "mesh_channel_2ghz"))
local channel5 = assert(x:get("lime", "wireless", "mesh_channel_5ghz"))
local mcast_rate_2 = assert(x:get("lime", "wireless", "mesh_mcast_rate_2ghz"))
local mcast_rate_5 = assert(x:get("lime", "wireless", "mesh_mcast_rate_5ghz"))
local wifi_num = 0
clean()
print("Defining wireless networks...")
x:foreach("wireless", "wifi-device", function(s)
local t = iw.type(s[".name"])
if not t then return end
local is_5ghz = iw[t].hwmodelist(s[".name"]).a
local ch = table.remove(is_5ghz and channel5 or channel2, 1)
local mcr = is_5ghz and mcast_rate_5 or mcast_rate_2
local id = string.format("mesh%d", wifi_num)
local net = "lm_" .. id
local ifn = string.format("mesh%d", wifi_num)
local ifn_ap = string.format("wlan%dap", wifi_num)
if not ch then
printf("-> No channel defined for %dGHz %s", is_5ghz and 5 or 2, s[".name"])
return
end
local ht = ch:match("[-+]?$")
printf("-> Using channel %s for %dGHz %s", ch, is_5ghz and 5 or 2, s[".name"])
x:set("wireless", s[".name"], "channel", (ch:gsub("[-+]$", "")))
if x:get("wireless", s[".name"], "ht_capab") then
if ht == "+" or ht == "-" then
x:set("wireless", s[".name"], "htmode", "HT40"..ht)
else
x:set("wireless", s[".name"], "htmode", "HT20")
end
end
x:set("wireless", s[".name"], "disabled", 0)
x:set("wireless", id, "wifi-iface")
x:set("wireless", id, "mode", "adhoc")
x:set("wireless", id, "device", s[".name"])
x:set("wireless", id, "network", net)
x:set("wireless", id, "ifname", ifn)
x:set("wireless", id, "mcast_rate", mcr)
x:set("wireless", id, "ssid", generate_ssid())
x:set("wireless", id, "bssid", assert(x:get("lime", "wireless", "mesh_bssid")))
x:set("wireless", ifn_ap, "wifi-iface")
x:set("wireless", ifn_ap, "mode", "ap")
x:set("wireless", ifn_ap, "device", s[".name"])
x:set("wireless", ifn_ap, "network", "lan")
x:set("wireless", ifn_ap, "ifname", ifn_ap)
x:set("wireless", ifn_ap, "ssid", assert(x:get("lime", "wireless", "ssid")))
-- base (untagged) wifi interface
x:set("network", net, "interface")
x:set("network", net, "proto", "none")
x:set("network", net, "mtu", "1528")
-- For layer2 use a vlan based off network_id, between 16 and 255, if uci doesn't specify a vlan
if not vlans[2] then vlans[2] = math.floor(16 + ((tonumber(n1) / 255) * (255 - 16))) end
-- Add vlan interfaces on top of wlans, for each proto. Eg. lm_mesh0_batadv
local n
for n = 1, #protocols do
local interface = "lm_" .. id .. "_" .. protocols[n]
local ifname = string.format("@lm_%s.%d", id, vlans[n])
local v4, v6 = generate_address(n, wifi_num)
assert(loadstring("setup_interface_" .. protocols[n] .. "(interface, ifname, v4, v6)"))
end
wifi_num = wifi_num + 1
end)
end
function apply()
-- TODO (i.e. /etc/init.d/network restart)
end
|
#!/usr/bin/lua
module(..., package.seeall)
function generate_ssid()
local r1, r2, r3 = node_id()
return string.format("%02x%02x%02x.lime", r1, r2, r3)
end
function clean()
print("Clearing wireless config...")
x:foreach("wireless", "wifi-iface", function(s)
x:delete("wireless", s[".name"])
end)
end
function init()
-- TODO
end
function configure()
local protocols = assert(x:get("lime", "network", "protos"))
local vlans = assert(x:get("lime", "network", "vlans"))
local n1, n2, n3 = network_id()
local r1, r2, r3 = node_id()
local channel2 = assert(x:get("lime", "wireless", "mesh_channel_2ghz"))
local channel5 = assert(x:get("lime", "wireless", "mesh_channel_5ghz"))
local mcast_rate_2 = assert(x:get("lime", "wireless", "mesh_mcast_rate_2ghz"))
local mcast_rate_5 = assert(x:get("lime", "wireless", "mesh_mcast_rate_5ghz"))
local wifi_num = 0
clean()
print("Defining wireless networks...")
x:foreach("wireless", "wifi-device", function(s)
local t = iw.type(s[".name"])
if not t then return end
local is_5ghz = iw[t].hwmodelist(s[".name"]).a
local ch = table.remove(is_5ghz and channel5 or channel2, 1)
local mcr = is_5ghz and mcast_rate_5 or mcast_rate_2
local id = string.format("mesh%d", wifi_num)
local net = "lm_" .. id
local ifn = string.format("mesh%d", wifi_num)
local ifn_ap = string.format("wlan%dap", wifi_num)
if not ch then
printf("-> No channel defined for %dGHz %s", is_5ghz and 5 or 2, s[".name"])
return
end
local ht = ch:match("[-+]?$")
printf("-> Using channel %s for %dGHz %s", ch, is_5ghz and 5 or 2, s[".name"])
x:set("wireless", s[".name"], "channel", (ch:gsub("[-+]$", "")))
if x:get("wireless", s[".name"], "ht_capab") then
if ht == "+" or ht == "-" then
x:set("wireless", s[".name"], "htmode", "HT40"..ht)
else
x:set("wireless", s[".name"], "htmode", "HT20")
end
end
x:set("wireless", s[".name"], "disabled", 0)
x:set("wireless", id, "wifi-iface")
x:set("wireless", id, "mode", "adhoc")
x:set("wireless", id, "device", s[".name"])
x:set("wireless", id, "network", net)
x:set("wireless", id, "ifname", ifn)
x:set("wireless", id, "mcast_rate", mcr)
x:set("wireless", id, "ssid", generate_ssid())
x:set("wireless", id, "bssid", assert(x:get("lime", "wireless", "mesh_bssid")))
x:set("wireless", ifn_ap, "wifi-iface")
x:set("wireless", ifn_ap, "mode", "ap")
x:set("wireless", ifn_ap, "device", s[".name"])
x:set("wireless", ifn_ap, "network", "lan")
x:set("wireless", ifn_ap, "ifname", ifn_ap)
x:set("wireless", ifn_ap, "ssid", assert(x:get("lime", "wireless", "ssid")))
-- base (untagged) wifi interface
x:set("network", net, "interface")
x:set("network", net, "proto", "none")
x:set("network", net, "mtu", "1528")
-- For layer2 use a vlan based off network_id, between 16 and 255, if uci doesn't specify a vlan
if not vlans[2] then vlans[2] = math.floor(16 + ((tonumber(n1) / 255) * (255 - 16))) end
-- Add vlan interfaces on top of wlans, for each proto. Eg. lm_mesh0_batadv
local n
for n = 1, #protocols do
local interface = "lm_" .. id .. "_" .. protocols[n]
local ifname = string.format("@lm_%s.%d", id, vlans[n])
local v4, v6 = generate_address(n, wifi_num)
assert(loadstring("setup_interface_" .. protocols[n] .. "(interface, ifname, v4, v6)"))
end
wifi_num = wifi_num + 1
end)
end
function apply()
-- TODO (i.e. /etc/init.d/network restart)
end
|
generate ad-hoc ssid with suffix '.lime' instead of overly long network name
|
generate ad-hoc ssid with suffix '.lime' instead of overly long network name
|
Lua
|
agpl-3.0
|
libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages
|
b5478aaeeddf44e56f7d1aecc391cd4a98061edd
|
nvim/lua/config.lua
|
nvim/lua/config.lua
|
local helper = require('helper')
vim.o.background = "dark" -- or "light" for light mode
-- vim.cmd([[colorscheme gruvbox-material]])
vim.cmd([[colorscheme gruvbox8]])
-- Copy with: "*y
vim.o.clipboard = 'unnamed'
--[[ Configure completion ]]--
-- LSP config (the mappings used in the default file don't quite work right)
helper.map(helper.MODE.NMAP, 'gd', '<cmd>lua vim.lsp.buf.definition()<CR>', { noremap = true, silent = true})
helper.map(helper.MODE.NMAP, 'gD', '<cmd>lua vim.lsp.buf.declaration()<CR>', { noremap = true, silent = true})
helper.map(helper.MODE.NMAP, 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', { noremap = true, silent = true})
helper.map(helper.MODE.NMAP, 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', { noremap = true, silent = true})
helper.map(helper.MODE.NMAP, 'K', '<cmd>lua vim.lsp.buf.hover()<CR>', { noremap = true, silent = true})
helper.map(helper.MODE.NMAP, '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', { noremap = true, silent = true})
helper.map(helper.MODE.NMAP, '<C-n>', '<cmd>lua vim.lsp.buf.goto_prev()<CR>', { noremap = true, silent = true})
helper.map(helper.MODE.NMAP, '<C-p>', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', { noremap = true, silent = true})
vim.cmd([[autocmd BufWritePre *.py lua vim.lsp.buf.formatting_sync(nil, 100)]])
vim.o.completeopt = "menuone,noselect"
require'compe'.setup {
enabled = true;
autocomplete = true;
debug = false;
min_length = 1;
preselect = 'enable';
throttle_time = 80;
source_timeout = 200;
incomplete_delay = 400;
max_abbr_width = 100;
max_kind_width = 100;
max_menu_width = 100;
documentation = false;
source = {
path = true;
buffer = true;
calc = true;
vsnip = true;
nvim_lsp = true;
nvim_lua = true;
spell = true;
tags = true;
snippets_nvim = true;
treesitter = true;
};
}
local t = function(str)
return vim.api.nvim_replace_termcodes(str, true, true, true)
end
local check_back_space = function()
local col = vim.fn.col('.') - 1
if col == 0 or vim.fn.getline('.'):sub(col, col):match('%s') then
return true
else
return false
end
end
-- Use (s-)tab to:
--- move to prev/next item in completion menuone
--- jump to prev/next snippet's placeholder
_G.tab_complete = function()
if vim.fn.pumvisible() == 1 then
return t "<C-n>"
elseif vim.fn.call("vsnip#available", {1}) == 1 then
return t "<Plug>(vsnip-expand-or-jump)"
elseif check_back_space() then
return t "<Tab>"
else
return vim.fn['compe#complete']()
end
end
_G.s_tab_complete = function()
if vim.fn.pumvisible() == 1 then
return t "<C-p>"
elseif vim.fn.call("vsnip#jumpable", {-1}) == 1 then
return t "<Plug>(vsnip-jump-prev)"
else
-- If <S-Tab> is not working in your terminal, change it to <C-h>
return t "<S-Tab>"
end
end
vim.api.nvim_set_keymap("i", "<Tab>", "v:lua.tab_complete()", {expr = true})
vim.api.nvim_set_keymap("s", "<Tab>", "v:lua.tab_complete()", {expr = true})
vim.api.nvim_set_keymap("i", "<S-Tab>", "v:lua.s_tab_complete()", {expr = true})
vim.api.nvim_set_keymap("s", "<S-Tab>", "v:lua.s_tab_complete()", {expr = true})
local lsp = require('lspconfig')
lsp.gopls.setup{}
lsp.sqls.setup{}
--lsp.pyright.setup{}
lsp.pylsp.setup{ }
lsp.bashls.setup{}
lsp.sqls.setup{
picker = 'telescope',
on_attach = function(client)
client.resolved_capabilities.execute_command = true
require'sqls'.setup{}
end
}
-- Language server
local function setup_servers()
require'lspinstall'.setup()
local servers = require'lspinstall'.installed_servers()
for _, server in pairs(servers) do
require'lspconfig'[server].setup{}
end
end
setup_servers()
-- Automatically reload after `:LspInstall <server>` so we don't have to restart neovim
require'lspinstall'.post_install_hook = function ()
setup_servers() -- reload installed servers
vim.cmd("bufdo e") -- this triggers the FileType autocmd that starts the server
end
-- Flutter configuration
require("flutter-tools").setup{} -- use defaults
require("telescope").load_extension("flutter")
require('statusline')
require('lspkind').init({
})
|
local helper = require('helper')
vim.o.background = "dark" -- or "light" for light mode
-- vim.cmd([[colorscheme gruvbox-material]])
vim.cmd([[colorscheme gruvbox8]])
-- Copy with: "*y
vim.o.clipboard = 'unnamed'
--[[ Configure completion ]]--
-- LSP config (the mappings used in the default file don't quite work right)
helper.map(helper.MODE.NMAP, 'gd', '<cmd>lua vim.lsp.buf.definition()<CR>', { noremap = true, silent = true})
helper.map(helper.MODE.NMAP, 'gD', '<cmd>lua vim.lsp.buf.declaration()<CR>', { noremap = true, silent = true})
helper.map(helper.MODE.NMAP, 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', { noremap = true, silent = true})
helper.map(helper.MODE.NMAP, 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', { noremap = true, silent = true})
helper.map(helper.MODE.NMAP, 'K', '<cmd>lua vim.lsp.buf.hover()<CR>', { noremap = true, silent = true})
helper.map(helper.MODE.NMAP, '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', { noremap = true, silent = true})
helper.map(helper.MODE.NMAP, '<C-n>', '<cmd>lua vim.lsp.buf.goto_prev()<CR>', { noremap = true, silent = true})
helper.map(helper.MODE.NMAP, '<C-p>', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', { noremap = true, silent = true})
vim.cmd([[autocmd BufWritePre *.py lua vim.lsp.buf.formatting_sync(nil, 100)]])
vim.o.completeopt = "menuone,noselect"
require'compe'.setup {
enabled = true;
autocomplete = true;
debug = false;
min_length = 1;
preselect = 'enable';
throttle_time = 80;
source_timeout = 200;
incomplete_delay = 400;
max_abbr_width = 100;
max_kind_width = 100;
max_menu_width = 100;
documentation = false;
source = {
path = true;
buffer = true;
calc = true;
vsnip = true;
nvim_lsp = true;
nvim_lua = true;
spell = true;
tags = true;
snippets_nvim = true;
treesitter = true;
};
}
local t = function(str)
return vim.api.nvim_replace_termcodes(str, true, true, true)
end
local check_back_space = function()
local col = vim.fn.col('.') - 1
if col == 0 or vim.fn.getline('.'):sub(col, col):match('%s') then
return true
else
return false
end
end
-- Use (s-)tab to:
--- move to prev/next item in completion menuone
--- jump to prev/next snippet's placeholder
_G.tab_complete = function()
if vim.fn.pumvisible() == 1 then
return t "<C-n>"
elseif vim.fn.call("vsnip#available", {1}) == 1 then
return t "<Plug>(vsnip-expand-or-jump)"
elseif check_back_space() then
return t "<Tab>"
else
return vim.fn['compe#complete']()
end
end
_G.s_tab_complete = function()
if vim.fn.pumvisible() == 1 then
return t "<C-p>"
elseif vim.fn.call("vsnip#jumpable", {-1}) == 1 then
return t "<Plug>(vsnip-jump-prev)"
else
-- If <S-Tab> is not working in your terminal, change it to <C-h>
return t "<S-Tab>"
end
end
vim.api.nvim_set_keymap("i", "<Tab>", "v:lua.tab_complete()", {expr = true})
vim.api.nvim_set_keymap("s", "<Tab>", "v:lua.tab_complete()", {expr = true})
vim.api.nvim_set_keymap("i", "<S-Tab>", "v:lua.s_tab_complete()", {expr = true})
vim.api.nvim_set_keymap("s", "<S-Tab>", "v:lua.s_tab_complete()", {expr = true})
-- Zig
require'lspconfig'.zls.setup{}
-- Go
require'lspconfig'.gopls.setup{}
-- Python
require'lspconfig'.pylsp.setup{ }
-- Bash
require'lspconfig'.bashls.setup{}
-- SQL
require'lspconfig'.sqls.setup{
picker = 'telescope',
on_attach = function(client)
client.resolved_capabilities.execute_command = true
require'sqls'.setup{}
end
}
-- Language server
local function setup_servers()
require'lspinstall'.setup()
local servers = require'lspinstall'.installed_servers()
for _, server in pairs(servers) do
require'lspconfig'[server].setup{}
end
end
setup_servers()
-- Automatically reload after `:LspInstall <server>` so we don't have to restart neovim
require'lspinstall'.post_install_hook = function ()
setup_servers() -- reload installed servers
vim.cmd("bufdo e") -- this triggers the FileType autocmd that starts the server
end
-- Flutter configuration
require("flutter-tools").setup{} -- use defaults
require("telescope").load_extension("flutter")
require('statusline')
require('lspkind').init({
})
|
Fix lsp server configuration
|
Fix lsp server configuration
|
Lua
|
bsd-2-clause
|
lateefj/side
|
0141a0d043fc8758fa8576c467dd2845df5e6e36
|
assets/dl.lua
|
assets/dl.lua
|
--[[
A LuaJIT FFI based version of dlopen() which loads dependencies
first (for implementations of dlopen() lacking that feature, like
on Android)
This is heavily inspired by the lo_dlopen() implementation from
LibreOffice (see
http://cgit.freedesktop.org/libreoffice/core/tree/sal/android/lo-bootstrap.c)
and as such:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
--]]
local ffi = require("ffi")
local Elf = require("elf")
ffi.cdef[[
void *dlopen(const char *filename, int flag);
char *dlerror(void);
const static int RTLD_LOCAL = 0;
const static int RTLD_GLOBAL = 0x00100;
]]
local dl = {
-- set this to search in certain directories
library_path = '/lib/?;/usr/lib/?;/usr/local/lib/?',
loaded_libraries = {}
}
local function sys_dlopen(library)
local p = ffi.C.dlopen(library, ffi.C.RTLD_LOCAL)
if p == nil then
local err_msg = ffi.C.dlerror()
if err_msg ~= nil then
error("error opening "..library..": "..ffi.string(err_msg))
end
end
return p
end
--[[
open_func will be used to load the library (but not its dependencies!)
if not given, the system's dlopen() will be used
if the library name is an absolute path (starting with "/"), then
the library_path will not be used
--]]
function dl.dlopen(library, load_func)
-- check if we already opened it:
if dl.loaded_libraries[library] then return loaded_libraries[library] end
load_func = load_func or sys_dlopen
for pspec in string.gmatch(
library:sub(1,1) == "/" and "" or dl.library_path,
"([^;:]+)") do
local lname, matches = string.gsub(pspec, "%?", library)
if matches == 0 then
-- if pathspec does not contain a '?', we do append
-- the library name to the pathspec
lname = lname .. '/' .. library
end
local ok, lib = pcall(Elf.open, lname)
if not ok and lname:find("%.so%.%d+$") then
lname = lname:gsub("%.so%.%d+$", "%.so")
ok, lib = pcall(Elf.open, lname)
end
if ok then
-- we found a library, now load its requirements
-- we do _not_ pass the load_func to the cascaded
-- calls, so those will always use sys_dlopen()
for _, needed in pairs(lib:dlneeds()) do
if needed == "libluajit.so" then
-- load the luajit-launcher libluajit with sys_dlopen
load_func("libluajit.so")
elseif needed ~= "libdl.so" then
-- for android >= 6.0, you can't load system library anymore
-- and since we also have our own dl implementation, it's safe
-- to skip the stock libdl.
dl.dlopen(needed)
end
end
return load_func(lname)
end
end
error("could not find library " .. library)
end
return dl
|
--[[
A LuaJIT FFI based version of dlopen() which loads dependencies
first (for implementations of dlopen() lacking that feature, like
on Android)
This is heavily inspired by the lo_dlopen() implementation from
LibreOffice (see
http://cgit.freedesktop.org/libreoffice/core/tree/sal/android/lo-bootstrap.c)
and as such:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
--]]
local ffi = require("ffi")
local Elf = require("elf")
ffi.cdef[[
void *dlopen(const char *filename, int flag);
char *dlerror(void);
const static int RTLD_LOCAL = 0;
const static int RTLD_GLOBAL = 0x00100;
]]
local dl = {
-- set this to search in certain directories
library_path = '/lib/?;/usr/lib/?;/usr/local/lib/?',
loaded_libraries = {}
}
local function sys_dlopen(library)
local p = ffi.C.dlopen(library, ffi.C.RTLD_LOCAL)
if p == nil then
local err_msg = ffi.C.dlerror()
if err_msg ~= nil then
error("error opening "..library..": "..ffi.string(err_msg))
end
end
return p
end
--[[
open_func will be used to load the library (but not its dependencies!)
if not given, the system's dlopen() will be used
if the library name is an absolute path (starting with "/"), then
the library_path will not be used
--]]
function dl.dlopen(library, load_func)
-- check if we already opened it:
if dl.loaded_libraries[library] then return loaded_libraries[library] end
load_func = load_func or sys_dlopen
for pspec in string.gmatch(
library:sub(1,1) == "/" and "" or dl.library_path,
"([^;:]+)") do
local lname, matches = string.gsub(pspec, "%?", library)
if matches == 0 then
-- if pathspec does not contain a '?', we do append
-- the library name to the pathspec
lname = lname .. '/' .. library
end
local ok, lib = pcall(Elf.open, lname)
if not ok and lname:find("%.so%.%d+$") then
lname = lname:gsub("%.so%.%d+$", "%.so")
ok, lib = pcall(Elf.open, lname)
end
if ok then
-- we found a library, now load its requirements
-- we do _not_ pass the load_func to the cascaded
-- calls, so those will always use sys_dlopen()
for _, needed in pairs(lib:dlneeds()) do
if needed == "libluajit.so" then
-- load the luajit-launcher libluajit with sys_dlopen
load_func("libluajit.so")
elseif needed ~= "libdl.so" and pspec ~= "/system/lib" then
-- For Android >= 6.0, you the list of safe system libraries is:
-- libandroid, libc, libcamera2ndk, libdl, libGLES, libjnigraphics,
-- liblog, libm, libmediandk, libOpenMAXAL, libOpenSLES, libstdc++,
-- libvulkan, and libz
-- However, we have our own dl implementation and don't need the rest.
dl.dlopen(needed)
end
end
return load_func(lname)
end
end
error("could not find library " .. library)
end
return dl
|
dl.lua: skip system libraries (fix Android 8) (#69)
|
dl.lua: skip system libraries (fix Android 8) (#69)
Fixes https://github.com/koreader/koreader/issues/3126
Thanks to @chrox for testing, see https://github.com/koreader/koreader/issues/3126#issuecomment-335556571.
|
Lua
|
mit
|
koreader/android-luajit-launcher,koreader/android-luajit-launcher,koreader/android-luajit-launcher,koreader/android-luajit-launcher
|
eff127fd58b0fec1a259786ead9ffef5f38d4c26
|
train.lua
|
train.lua
|
--
-- Copyright (c) 2016, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
-- The training loop and learning rate schedule
--
local optim = require 'optim'
local M = {}
local Trainer = torch.class('resnet.Trainer', M)
function Trainer:__init(model, criterion, opt, optimState)
self.model = model
self.criterion = criterion
self.optimState = optimState or {
learningRate = opt.LR,
learningRateDecay = 0.0,
momentum = opt.momentum,
nesterov = true,
dampening = 0.0,
weightDecay = opt.weightDecay,
}
self.opt = opt
self.params, self.gradParams = model:getParameters()
end
function Trainer:train(epoch, dataloader)
-- Trains the model for a single epoch
self.optimState.learningRate = self:learningRate(epoch)
local timer = torch.Timer()
local dataTimer = torch.Timer()
local function feval()
return self.criterion.output, self.gradParams
end
local trainSize = dataloader:size()
local top1Sum, top5Sum, lossSum = 0.0, 0.0, 0.0
local N = 0
print('=> Training epoch # ' .. epoch)
-- set the batch norm to training mode
self.model:training()
for n, sample in dataloader:run() do
local dataTime = dataTimer:time().real
-- Copy input and target to the GPU
self:copyInputs(sample)
local output = self.model:forward(self.input):float()
local loss = self.criterion:forward(self.model.output, self.target)
self.model:zeroGradParameters()
self.criterion:backward(self.model.output, self.target)
self.model:backward(self.input, self.criterion.gradInput)
optim.sgd(feval, self.params, self.optimState)
local top1, top5 = self:computeScore(output, sample.target, 1)
top1Sum = top1Sum + top1
top5Sum = top5Sum + top5
lossSum = lossSum + loss
N = N + 1
print((' | Epoch: [%d][%d/%d] Time %.3f Data %.3f Err %1.4f top1 %7.3f top5 %7.3f'):format(
epoch, n, trainSize, timer:time().real, dataTime, loss, top1, top5))
-- check that the storage didn't get changed do to an unfortunate getParameters call
assert(self.params:storage() == self.model:parameters()[1]:storage())
timer:reset()
dataTimer:reset()
end
return top1Sum / N, top5Sum / N, lossSum / N
end
function Trainer:test(epoch, dataloader)
-- Computes the top-1 and top-5 err on the validation set
local timer = torch.Timer()
local dataTimer = torch.Timer()
local size = dataloader:size()
local nCrops = self.opt.tenCrop and 10 or 1
local top1Sum, top5Sum = 0.0, 0.0
local N = 0
self.model:evaluate()
for n, sample in dataloader:run() do
local dataTime = dataTimer:time().real
-- Copy input and target to the GPU
self:copyInputs(sample)
local output = self.model:forward(self.input):float()
local loss = self.criterion:forward(self.model.output, self.target)
local top1, top5 = self:computeScore(output, sample.target, nCrops)
top1Sum = top1Sum + top1
top5Sum = top5Sum + top5
N = N + 1
print((' | Test: [%d][%d/%d] Time %.3f Data %.3f top1 %7.3f (%7.3f) top5 %7.3f (%7.3f)'):format(
epoch, n, size, timer:time().real, dataTime, top1, top1Sum / N, top5, top5Sum / N))
timer:reset()
dataTimer:reset()
end
self.model:training()
print((' * Finished epoch # %d top1: %7.3f top5: %7.3f\n'):format(
epoch, top1Sum / N, top5Sum / N))
return top1Sum / N, top5Sum / N
end
function Trainer:computeScore(output, target, nCrops)
if nCrops > 1 then
-- Sum over crops
output = output:view(output:size(1) / nCrops, nCrops, output:size(2))
--:exp()
:sum(2):squeeze(2)
end
-- Coputes the top1 and top5 error rate
local batchSize = output:size(1)
local _ , predictions = output:float():sort(2, true) -- descending
-- Find which predictions match the target
local correct = predictions:eq(
target:long():view(batchSize, 1):expandAs(output))
local top1 = 1.0 - correct:narrow(2, 1, 1):sum() / batchSize
local top5 = 1.0 - correct:narrow(2, 1, 5):sum() / batchSize
return top1 * 100, top5 * 100
end
function Trainer:copyInputs(sample)
-- Copies the input to a CUDA tensor, if using 1 GPU, or to pinned memory,
-- if using DataParallelTable. The target is always copied to a CUDA tensor
self.input = self.input or (self.opt.nGPU == 1
and torch.CudaTensor()
or cutorch.createCudaHostTensor())
self.target = self.target or torch.CudaTensor()
self.input:resize(sample.input:size()):copy(sample.input)
self.target:resize(sample.target:size()):copy(sample.target)
end
function Trainer:learningRate(epoch)
-- Training schedule
local decay = 0
if self.opt.dataset == 'imagenet' then
decay = math.floor((epoch - 1) / 30)
elseif self.opt.dataset == 'cifar10' then
decay = epoch >= 122 and 2 or epoch >= 81 and 1 or 0
end
return self.opt.LR * math.pow(0.1, decay)
end
return M.Trainer
|
--
-- Copyright (c) 2016, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
-- The training loop and learning rate schedule
--
local optim = require 'optim'
local M = {}
local Trainer = torch.class('resnet.Trainer', M)
function Trainer:__init(model, criterion, opt, optimState)
self.model = model
self.criterion = criterion
self.optimState = optimState or {
learningRate = opt.LR,
learningRateDecay = 0.0,
momentum = opt.momentum,
nesterov = true,
dampening = 0.0,
weightDecay = opt.weightDecay,
}
self.opt = opt
self.params, self.gradParams = model:getParameters()
end
function Trainer:train(epoch, dataloader)
-- Trains the model for a single epoch
self.optimState.learningRate = self:learningRate(epoch)
local timer = torch.Timer()
local dataTimer = torch.Timer()
local function feval()
return self.criterion.output, self.gradParams
end
local trainSize = dataloader:size()
local top1Sum, top5Sum, lossSum = 0.0, 0.0, 0.0
local N = 0
print('=> Training epoch # ' .. epoch)
-- set the batch norm to training mode
self.model:training()
for n, sample in dataloader:run() do
local dataTime = dataTimer:time().real
-- Copy input and target to the GPU
self:copyInputs(sample)
local output = self.model:forward(self.input):float()
local loss = self.criterion:forward(self.model.output, self.target)
self.model:zeroGradParameters()
self.criterion:backward(self.model.output, self.target)
self.model:backward(self.input, self.criterion.gradInput)
optim.sgd(feval, self.params, self.optimState)
local top1, top5 = self:computeScore(output, sample.target, 1)
top1Sum = top1Sum + top1
top5Sum = top5Sum + top5
lossSum = lossSum + loss
N = N + 1
print((' | Epoch: [%d][%d/%d] Time %.3f Data %.3f Err %1.4f top1 %7.3f top5 %7.3f'):format(
epoch, n, trainSize, timer:time().real, dataTime, loss, top1, top5))
-- check that the storage didn't get changed do to an unfortunate getParameters call
assert(self.params:storage() == self.model:parameters()[1]:storage())
timer:reset()
dataTimer:reset()
end
return top1Sum / N, top5Sum / N, lossSum / N
end
function Trainer:test(epoch, dataloader)
-- Computes the top-1 and top-5 err on the validation set
local timer = torch.Timer()
local dataTimer = torch.Timer()
local size = dataloader:size()
local nCrops = self.opt.tenCrop and 10 or 1
local top1Sum, top5Sum = 0.0, 0.0
local N = 0
self.model:evaluate()
for n, sample in dataloader:run() do
local dataTime = dataTimer:time().real
-- Copy input and target to the GPU
self:copyInputs(sample)
local output = self.model:forward(self.input):float()
local loss = self.criterion:forward(self.model.output, self.target)
local top1, top5 = self:computeScore(output, sample.target, nCrops)
top1Sum = top1Sum + top1
top5Sum = top5Sum + top5
N = N + 1
print((' | Test: [%d][%d/%d] Time %.3f Data %.3f top1 %7.3f (%7.3f) top5 %7.3f (%7.3f)'):format(
epoch, n, size, timer:time().real, dataTime, top1, top1Sum / N, top5, top5Sum / N))
timer:reset()
dataTimer:reset()
end
self.model:training()
print((' * Finished epoch # %d top1: %7.3f top5: %7.3f\n'):format(
epoch, top1Sum / N, top5Sum / N))
return top1Sum / N, top5Sum / N
end
function Trainer:computeScore(output, target, nCrops)
if nCrops > 1 then
-- Sum over crops
output = output:view(output:size(1) / nCrops, nCrops, output:size(2))
--:exp()
:sum(2):squeeze(2)
end
-- Coputes the top1 and top5 error rate
local batchSize = output:size(1)
local _ , predictions = output:float():sort(2, true) -- descending
-- Find which predictions match the target
local correct = predictions:eq(
target:long():view(batchSize, 1):expandAs(output))
-- Top-1 score
local top1 = 1.0 - (correct:narrow(2, 1, 1):sum() / batchSize)
-- Top-5 score, if there are at least 5 classes
local len = math.min(5, correct:size(2))
local top5 = 1.0 - (correct:narrow(2, 1, len):sum() / batchSize)
return top1 * 100, top5 * 100
end
function Trainer:copyInputs(sample)
-- Copies the input to a CUDA tensor, if using 1 GPU, or to pinned memory,
-- if using DataParallelTable. The target is always copied to a CUDA tensor
self.input = self.input or (self.opt.nGPU == 1
and torch.CudaTensor()
or cutorch.createCudaHostTensor())
self.target = self.target or torch.CudaTensor()
self.input:resize(sample.input:size()):copy(sample.input)
self.target:resize(sample.target:size()):copy(sample.target)
end
function Trainer:learningRate(epoch)
-- Training schedule
local decay = 0
if self.opt.dataset == 'imagenet' then
decay = math.floor((epoch - 1) / 30)
elseif self.opt.dataset == 'cifar10' then
decay = epoch >= 122 and 2 or epoch >= 81 and 1 or 0
end
return self.opt.LR * math.pow(0.1, decay)
end
return M.Trainer
|
Limit top-5 to top-N for N-way classifier
|
Limit top-5 to top-N for N-way classifier
Don't error when trying to compute top-5 for binary classifier
Fixes #14
|
Lua
|
bsd-3-clause
|
ltrottier/pelu.resnet.torch,ltrottier/pelu.resnet.torch
|
0d2d5f9f71cb5393940a5ea18472376f9ad89792
|
embark_site.lua
|
embark_site.lua
|
--[[ embark_site (by Lethosor)
Allows embarking in disabled locations (e.g. too small or on an existing site)
Note that this script is not yet complete (although it's mostly functional).
Notably, there is currently no GUI integration - you can either run it from the
console or add keybindings.
Some example keybindings:
keybinding add Alt-N@choose_start_site "embark_site nano"
keybinding add Alt-E@choose_start_site "embark_site here"
]]
usage = [[Usage:
embark_site nano enable
embark_site nano disable
embark_site anywhere enable
embark_site anywhere disable
]]
local gui = require 'gui'
local widgets = require 'gui.widgets'
local eventful = require 'plugins.eventful'
if enabled == nil then
enabled = {
anywhere = false,
nano = false,
}
end
function set_embark_size(width, height)
width, height = tonumber(width), tonumber(height)
if width == nil or height == nil then
dfhack.printerr('Embark size requires width and height')
return false
end
scr.embark_pos_max.x = math.min(15, scr.embark_pos_min.x + width - 1)
scr.embark_pos_max.y = math.min(15, scr.embark_pos_min.y + height - 1)
scr.embark_pos_min.x = math.max(0, scr.embark_pos_max.x - width + 1)
scr.embark_pos_min.y = math.max(0, scr.embark_pos_max.y - height + 1)
end
function get_embark_pos()
return {scr.embark_pos_min.x + 1, scr.embark_pos_min.y + 1, scr.embark_pos_max.x + 1, scr.embark_pos_max.y + 1}
end
embark_overlay = defclass(embark_overlay, gui.Screen)
function embark_overlay:init()
self:addviews{
widgets.Panel{
subviews = {
widgets.Label{ text="test label", frame={t=1,l=1} },
}
}
}
end
function onStateChange(...)
if dfhack.gui.getCurFocus() ~= 'choose_start_site' then return end
print('embark_site: Creating overlay')
screen = embark_overlay()
screen.show()
end
dfhack.onStateChange.embark_site = onStateChange
function main(...)
args = {...}
if #args == 2 then
feature = args[1]
state = args[2]
if enabled[feature] ~= nil then
if state == 'enable' then
enabled[feature] = true
elseif state == 'disable' then
enabled[feature] = false
else
print('Usage: embark_site ' .. feature .. ' (enable/disable)')
end
else
print('Invalid: ' .. args[1])
end
elseif #args == 0 then
for feature, state in pairs(enabled) do
print(feature .. ':' .. string.rep(' ', 10 - #feature) .. (state and 'enabled' or 'disabled'))
end
else
print(usage)
end
end
main(...)
|
--[[ embark_site (by Lethosor)
Allows embarking in disabled locations (e.g. too small or on an existing site)
Note that this script is not yet complete (although it's mostly functional).
Notably, there is currently no GUI integration - you can either run it from the
console or add keybindings.
Some example keybindings:
keybinding add Alt-N@choose_start_site "embark_site nano"
keybinding add Alt-E@choose_start_site "embark_site here"
]]
usage = [[Usage:
embark_site nano enable
embark_site nano disable
embark_site anywhere enable
embark_site anywhere disable
]]
local gui = require 'gui'
local widgets = require 'gui.widgets'
local eventful = require 'plugins.eventful'
if enabled == nil then
enabled = {
anywhere = false,
nano = false,
}
end
function tableIndex(tbl, value)
for k, v in pairs(tbl) do
if tbl[k] == value then
return k
end
end
return nil
end
function set_embark_size(width, height)
width, height = tonumber(width), tonumber(height)
if width == nil or height == nil then
dfhack.printerr('Embark size requires width and height')
return false
end
scr.embark_pos_max.x = math.min(15, scr.embark_pos_min.x + width - 1)
scr.embark_pos_max.y = math.min(15, scr.embark_pos_min.y + height - 1)
scr.embark_pos_min.x = math.max(0, scr.embark_pos_max.x - width + 1)
scr.embark_pos_min.y = math.max(0, scr.embark_pos_max.y - height + 1)
end
function get_embark_pos()
return {scr.embark_pos_min.x + 1, scr.embark_pos_min.y + 1, scr.embark_pos_max.x + 1, scr.embark_pos_max.y + 1}
end
embark_overlay = defclass(embark_overlay, gui.Screen)
function embark_overlay:init()
self:addviews{
widgets.Panel{
subviews = {
widgets.Label{ text="Embarking is disabled", frame={t=1,l=1} },
}
}
}
end
function embark_overlay:onRender()
self._native.parent:render()
self:render()
end
function embark_overlay:onInput(keys)
local interceptKeys = {"SETUP_EMBARK"}
if keys.LEAVESCREEN then
self:dismiss()
self:sendInputToParent('LEAVESCREEN')
end
for name, _ in pairs(keys) do
if tableIndex(interceptKeys, name) ~= nil then
print("Intercepting " .. name)
else
self:sendInputToParent(name)
end
end
end
function onStateChange(...)
if dfhack.gui.getCurFocus() ~= 'choose_start_site' then return end
print('embark_site: Creating overlay')
screen = embark_overlay()
screen:show()
end
dfhack.onStateChange.embark_site = onStateChange
function main(...)
args = {...}
if #args == 2 then
feature = args[1]
state = args[2]
if enabled[feature] ~= nil then
if state == 'enable' then
enabled[feature] = true
elseif state == 'disable' then
enabled[feature] = false
else
print('Usage: embark_site ' .. feature .. ' (enable/disable)')
end
else
print('Invalid: ' .. args[1])
end
elseif #args == 0 then
for feature, state in pairs(enabled) do
print(feature .. ':' .. string.rep(' ', 10 - #feature) .. (state and 'enabled' or 'disabled'))
end
elseif args[1] == 'init' then
-- pass
else
print(usage)
end
end
main(...)
|
Fix rendering and intercept input
|
Fix rendering and intercept input
|
Lua
|
unlicense
|
DFHack/lethosor-scripts,PeridexisErrant/lethosor-scripts,lethosor/dfhack-scripts
|
0a314e3ab8bbe0613a973986103b387346339ecd
|
frontend/ui/widget/scrollhtmlwidget.lua
|
frontend/ui/widget/scrollhtmlwidget.lua
|
--[[--
HTML widget with vertical scroll bar.
--]]
local Device = require("device")
local HtmlBoxWidget = require("ui/widget/htmlboxwidget")
local Geom = require("ui/geometry")
local GestureRange = require("ui/gesturerange")
local HorizontalGroup = require("ui/widget/horizontalgroup")
local HorizontalSpan = require("ui/widget/horizontalspan")
local InputContainer = require("ui/widget/container/inputcontainer")
local UIManager = require("ui/uimanager")
local VerticalScrollBar = require("ui/widget/verticalscrollbar")
local Math = require("optmath")
local Input = Device.input
local Screen = Device.screen
local ScrollHtmlWidget = InputContainer:new{
html_body = nil,
css = nil,
default_font_size = 18,
htmlbox_widget = nil,
v_scroll_bar = nil,
dialog = nil,
html_link_tapped_callback = nil,
dimen = nil,
width = 0,
height = 0,
scroll_bar_width = Screen:scaleBySize(6),
text_scroll_span = Screen:scaleBySize(12),
}
function ScrollHtmlWidget:init()
self.htmlbox_widget = HtmlBoxWidget:new{
dimen = Geom:new{
w = self.width - self.scroll_bar_width - self.text_scroll_span,
h = self.height,
},
html_link_tapped_callback = self.html_link_tapped_callback,
}
self.htmlbox_widget:setContent(self.html_body, self.css, self.default_font_size)
self.v_scroll_bar = VerticalScrollBar:new{
enable = self.htmlbox_widget.page_count > 1,
width = self.scroll_bar_width,
height = self.height,
}
self.v_scroll_bar:set((self.htmlbox_widget.page_number-1) / self.htmlbox_widget.page_count, self.htmlbox_widget.page_number / self.htmlbox_widget.page_count)
local horizontal_group = HorizontalGroup:new{}
table.insert(horizontal_group, self.htmlbox_widget)
table.insert(horizontal_group, HorizontalSpan:new{width=self.text_scroll_span})
table.insert(horizontal_group, self.v_scroll_bar)
self[1] = horizontal_group
self.dimen = Geom:new(self[1]:getSize())
if Device:isTouchDevice() then
self.ges_events = {
ScrollText = {
GestureRange:new{
ges = "swipe",
range = function() return self.dimen end,
},
},
TapScrollText = { -- allow scrolling with tap
GestureRange:new{
ges = "tap",
range = function() return self.dimen end,
},
},
}
end
if Device:hasKeys() then
self.key_events = {
ScrollDown = {{Input.group.PgFwd}, doc = "scroll down"},
ScrollUp = {{Input.group.PgBack}, doc = "scroll up"},
}
end
end
function ScrollHtmlWidget:getSinglePageHeight()
return self.htmlbox_widget:getSinglePageHeight()
end
function ScrollHtmlWidget:scrollToRatio(ratio)
ratio = math.max(0, math.min(1, ratio)) -- ensure ratio is between 0 and 1 (100%)
local page_num = 1 + Math.round((self.htmlbox_widget.page_count - 1) * ratio)
if page_num == self.htmlbox_widget.page_number then
return
end
self.htmlbox_widget.page_number = page_num
self.v_scroll_bar:set((page_num-1) / self.htmlbox_widget.page_count, page_num / self.htmlbox_widget.page_count)
self.htmlbox_widget:freeBb()
self.htmlbox_widget:_render()
UIManager:setDirty(self.dialog, function()
return "partial", self.dimen
end)
end
function ScrollHtmlWidget:scrollText(direction)
if direction == 0 then
return
end
if direction > 0 then
if self.htmlbox_widget.page_number >= self.htmlbox_widget.page_count then
return
end
self.htmlbox_widget.page_number = self.htmlbox_widget.page_number + 1
elseif direction < 0 then
if self.htmlbox_widget.page_number <= 1 then
return
end
self.htmlbox_widget.page_number = self.htmlbox_widget.page_number - 1
end
self.v_scroll_bar:set((self.htmlbox_widget.page_number-1) / self.htmlbox_widget.page_count, self.htmlbox_widget.page_number / self.htmlbox_widget.page_count)
self.htmlbox_widget:freeBb()
self.htmlbox_widget:_render()
UIManager:setDirty(self.dialog, function()
return "partial", self.dimen
end)
end
function ScrollHtmlWidget:onScrollText(arg, ges)
if ges.direction == "north" then
self:scrollText(1)
return true
elseif ges.direction == "south" then
self:scrollText(-1)
return true
end
-- if swipe west/east, let it propagate up (e.g. for quickdictlookup to
-- go to next/prev result)
end
function ScrollHtmlWidget:onTapScrollText(arg, ges)
if ges.pos.x < Screen:getWidth()/2 then
if self.htmlbox_widget.page_number > 1 then
self:scrollText(-1)
return true
end
else
if self.htmlbox_widget.page_number < self.htmlbox_widget.page_count then
self:scrollText(1)
return true
end
end
-- if we couldn't scroll (because we're already at top or bottom),
-- let it propagate up (e.g. for quickdictlookup to go to next/prev result)
end
function ScrollHtmlWidget:onScrollDown()
self:scrollText(1)
return true
end
function ScrollHtmlWidget:onScrollUp()
self:scrollText(-1)
return true
end
return ScrollHtmlWidget
|
--[[--
HTML widget with vertical scroll bar.
--]]
local Device = require("device")
local HtmlBoxWidget = require("ui/widget/htmlboxwidget")
local Geom = require("ui/geometry")
local GestureRange = require("ui/gesturerange")
local HorizontalGroup = require("ui/widget/horizontalgroup")
local HorizontalSpan = require("ui/widget/horizontalspan")
local InputContainer = require("ui/widget/container/inputcontainer")
local UIManager = require("ui/uimanager")
local VerticalScrollBar = require("ui/widget/verticalscrollbar")
local Math = require("optmath")
local Input = Device.input
local Screen = Device.screen
local ScrollHtmlWidget = InputContainer:new{
html_body = nil,
css = nil,
default_font_size = Screen:scaleBySize(24), -- same as infofont
htmlbox_widget = nil,
v_scroll_bar = nil,
dialog = nil,
html_link_tapped_callback = nil,
dimen = nil,
width = 0,
height = 0,
scroll_bar_width = Screen:scaleBySize(6),
text_scroll_span = Screen:scaleBySize(12),
}
function ScrollHtmlWidget:init()
self.htmlbox_widget = HtmlBoxWidget:new{
dimen = Geom:new{
w = self.width - self.scroll_bar_width - self.text_scroll_span,
h = self.height,
},
html_link_tapped_callback = self.html_link_tapped_callback,
}
self.htmlbox_widget:setContent(self.html_body, self.css, self.default_font_size)
self.v_scroll_bar = VerticalScrollBar:new{
enable = self.htmlbox_widget.page_count > 1,
width = self.scroll_bar_width,
height = self.height,
}
self.v_scroll_bar:set((self.htmlbox_widget.page_number-1) / self.htmlbox_widget.page_count, self.htmlbox_widget.page_number / self.htmlbox_widget.page_count)
local horizontal_group = HorizontalGroup:new{}
table.insert(horizontal_group, self.htmlbox_widget)
table.insert(horizontal_group, HorizontalSpan:new{width=self.text_scroll_span})
table.insert(horizontal_group, self.v_scroll_bar)
self[1] = horizontal_group
self.dimen = Geom:new(self[1]:getSize())
if Device:isTouchDevice() then
self.ges_events = {
ScrollText = {
GestureRange:new{
ges = "swipe",
range = function() return self.dimen end,
},
},
TapScrollText = { -- allow scrolling with tap
GestureRange:new{
ges = "tap",
range = function() return self.dimen end,
},
},
}
end
if Device:hasKeys() then
self.key_events = {
ScrollDown = {{Input.group.PgFwd}, doc = "scroll down"},
ScrollUp = {{Input.group.PgBack}, doc = "scroll up"},
}
end
end
function ScrollHtmlWidget:getSinglePageHeight()
return self.htmlbox_widget:getSinglePageHeight()
end
function ScrollHtmlWidget:scrollToRatio(ratio)
ratio = math.max(0, math.min(1, ratio)) -- ensure ratio is between 0 and 1 (100%)
local page_num = 1 + Math.round((self.htmlbox_widget.page_count - 1) * ratio)
if page_num == self.htmlbox_widget.page_number then
return
end
self.htmlbox_widget.page_number = page_num
self.v_scroll_bar:set((page_num-1) / self.htmlbox_widget.page_count, page_num / self.htmlbox_widget.page_count)
self.htmlbox_widget:freeBb()
self.htmlbox_widget:_render()
UIManager:setDirty(self.dialog, function()
return "partial", self.dimen
end)
end
function ScrollHtmlWidget:scrollText(direction)
if direction == 0 then
return
end
if direction > 0 then
if self.htmlbox_widget.page_number >= self.htmlbox_widget.page_count then
return
end
self.htmlbox_widget.page_number = self.htmlbox_widget.page_number + 1
elseif direction < 0 then
if self.htmlbox_widget.page_number <= 1 then
return
end
self.htmlbox_widget.page_number = self.htmlbox_widget.page_number - 1
end
self.v_scroll_bar:set((self.htmlbox_widget.page_number-1) / self.htmlbox_widget.page_count, self.htmlbox_widget.page_number / self.htmlbox_widget.page_count)
self.htmlbox_widget:freeBb()
self.htmlbox_widget:_render()
UIManager:setDirty(self.dialog, function()
return "partial", self.dimen
end)
end
function ScrollHtmlWidget:onScrollText(arg, ges)
if ges.direction == "north" then
self:scrollText(1)
return true
elseif ges.direction == "south" then
self:scrollText(-1)
return true
end
-- if swipe west/east, let it propagate up (e.g. for quickdictlookup to
-- go to next/prev result)
end
function ScrollHtmlWidget:onTapScrollText(arg, ges)
if ges.pos.x < Screen:getWidth()/2 then
if self.htmlbox_widget.page_number > 1 then
self:scrollText(-1)
return true
end
else
if self.htmlbox_widget.page_number < self.htmlbox_widget.page_count then
self:scrollText(1)
return true
end
end
-- if we couldn't scroll (because we're already at top or bottom),
-- let it propagate up (e.g. for quickdictlookup to go to next/prev result)
end
function ScrollHtmlWidget:onScrollDown()
self:scrollText(1)
return true
end
function ScrollHtmlWidget:onScrollUp()
self:scrollText(-1)
return true
end
return ScrollHtmlWidget
|
[fix] widget/scrollhtmlwidget: default_font_size same as infofont and Screen:scaleBySize() (#4864)
|
[fix] widget/scrollhtmlwidget: default_font_size same as infofont and Screen:scaleBySize() (#4864)
Otherwise it's:
1. Too small on virtually all devices due to a lack of scaling.
2. Unusably small by default.
It's currently scaled by the callers (dictquicklookup & footnotewidget) based on other properties, but you shouldn't have to change it from the default just to get something usable. ;-)
|
Lua
|
agpl-3.0
|
poire-z/koreader,Frenzie/koreader,mihailim/koreader,houqp/koreader,NiLuJe/koreader,Hzj-jie/koreader,koreader/koreader,Markismus/koreader,mwoz123/koreader,Frenzie/koreader,poire-z/koreader,NiLuJe/koreader,pazos/koreader,koreader/koreader
|
8b97e3bac69f19425ef4d71fb429184b88462f12
|
GPTooltip.lua
|
GPTooltip.lua
|
local mod = EPGP:NewModule("EPGP_GPTooltip", "AceHook-2.1")
local EQUIPSLOT_VALUE = {
["INVTYPE_HEAD"] = 1,
["INVTYPE_NECK"] = 0.55,
["INVTYPE_SHOULDER"] = 0.777,
["INVTYPE_CHEST"] = 1,
["INVTYPE_ROBE"] = 1,
["INVTYPE_WAIST"] = 0.777,
["INVTYPE_LEGS"] = 1,
["INVTYPE_FEET"] = 0.777,
["INVTYPE_WRIST"] = 0.55,
["INVTYPE_HAND"] = 0.777,
["INVTYPE_FINGER"] = 0.55,
["INVTYPE_TRINKET"] = 0.7,
["INVTYPE_CLOAK"] = 0.55,
["INVTYPE_WEAPON"] = 0.42,
["INVTYPE_SHIELD"] = 0.55,
["INVTYPE_2HWEAPON"] = 1,
["INVTYPE_WEAPONMAINHAND"] = 0.42,
["INVTYPE_WEAPONOFFHAND"] = 0.42,
["INVTYPE_HOLDABLE"] = 0.55,
["INVTYPE_RANGED"] = 0.42,
["INVTYPE_RANGEDRIGHT"] = 0.42
}
local ILVL_TO_IVALUE = {
[2] = function(ilvl) return (ilvl - 4) / 2 end, -- Green
[3] = function(ilvl) return (ilvl - 1.84) / 1.6 end, -- Blue
[4] = function(ilvl) return (ilvl - 1.3) / 1.3 end, -- Purple
}
function mod:AddGP2Tooltip(frame, itemLink)
local gp, ilvl, ivalue = self:GetGPValue(itemLink)
if gp and gp > 0 then
frame:AddLine(string.format("GP: %d [ItemLevel=%d ItemValue=%d]", gp, ilvl, ivalue),
NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b)
frame:Show()
end
end
function mod:GetGPValue(itemLink)
if not itemLink then return end
local name, link, rarity, level, minlevel, type, subtype, count, equipLoc = GetItemInfo(itemLink)
local islot_mod = EQUIPSLOT_VALUE[equipLoc]
if not islot_mod then return end
local ilvl2ivalue = ILVL_TO_IVALUE[rarity]
if ilvl2ivalue then
local ivalue = ilvl2ivalue(level)
return math.floor(ivalue^2 * 0.04 * islot_mod), level, ivalue
end
end
local TOOLTIPS = {
ItemRefTooltip,
GameTooltip,
ShoppingTooltip1,
ShoppingTooltip2,
--EquipCompare support
ComparisonTooltip1,
ComparisonTooltip2,
-- MultiTips support
ItemRefTooltip2,
ItemRefTooltip3,
ItemRefTooltip4,
ItemRefTooltip5,
}
function mod.OnTooltipSetItem(tooltip)
local _, itemlink = tooltip:GetItem()
mod:AddGP2Tooltip(tooltip, itemlink)
end
function mod:OnEnable()
for _, tooltip in pairs(TOOLTIPS) do
if tooltip then
if tooltip:HasScript("OnTooltipSetItem") then
local old_script = tooltip:GetScript("OnTooltipSetItem")
if old_script then
tooltip:SetScript("OnTooltipSetItem", function(tooltip)
old_script(tooltip)
mod.OnTooltipSetItem(tooltip)
end)
else
tooltip:SetScript("OnTooltipSetItem", mod.OnTooltipSetItem)
end
end
end
end
end
|
local mod = EPGP:NewModule("EPGP_GPTooltip", "AceHook-2.1")
local EQUIPSLOT_VALUE = {
["INVTYPE_HEAD"] = 1,
["INVTYPE_NECK"] = 0.55,
["INVTYPE_SHOULDER"] = 0.777,
["INVTYPE_CHEST"] = 1,
["INVTYPE_ROBE"] = 1,
["INVTYPE_WAIST"] = 0.777,
["INVTYPE_LEGS"] = 1,
["INVTYPE_FEET"] = 0.777,
["INVTYPE_WRIST"] = 0.55,
["INVTYPE_HAND"] = 0.777,
["INVTYPE_FINGER"] = 0.55,
["INVTYPE_TRINKET"] = 0.7,
["INVTYPE_CLOAK"] = 0.55,
["INVTYPE_WEAPON"] = 0.42,
["INVTYPE_SHIELD"] = 0.55,
["INVTYPE_2HWEAPON"] = 1,
["INVTYPE_WEAPONMAINHAND"] = 0.42,
["INVTYPE_WEAPONOFFHAND"] = 0.42,
["INVTYPE_HOLDABLE"] = 0.55,
["INVTYPE_RANGED"] = 0.42,
["INVTYPE_RANGEDRIGHT"] = 0.42
}
local ILVL_TO_IVALUE = {
[2] = function(ilvl) return (ilvl - 4) / 2 end, -- Green
[3] = function(ilvl) return (ilvl - 1.84) / 1.6 end, -- Blue
[4] = function(ilvl) return (ilvl - 1.3) / 1.3 end, -- Purple
}
function mod:AddGP2Tooltip(frame, itemLink)
local gp, ilvl, ivalue = self:GetGPValue(itemLink)
if gp and gp > 0 then
frame:AddLine(string.format("GP: %d [ItemLevel=%d ItemValue=%d]", gp, ilvl, ivalue),
NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b)
frame:Show()
end
end
function mod:GetGPValue(itemLink)
if not itemLink then return end
local name, link, rarity, level, minlevel, type, subtype, count, equipLoc = GetItemInfo(itemLink)
local islot_mod = EQUIPSLOT_VALUE[equipLoc]
if not islot_mod then return end
local ilvl2ivalue = ILVL_TO_IVALUE[rarity]
if ilvl2ivalue then
local ivalue = ilvl2ivalue(level)
return math.floor(ivalue^2 * 0.04 * islot_mod), level, ivalue
end
end
function mod.OnTooltipSetItem(tooltip)
local _, itemlink = tooltip:GetItem()
mod:AddGP2Tooltip(tooltip, itemlink)
end
function mod:OnEnable()
local obj = EnumerateFrames()
while obj do
if obj:IsObjectType("GameTooltip") then
if obj:HasScript("OnTooltipSetItem") then
local old_script = obj:GetScript("OnTooltipSetItem")
if old_script then
obj:SetScript("OnTooltipSetItem", function(obj)
old_script(obj)
mod.OnTooltipSetItem(obj)
end)
else
obj:SetScript("OnTooltipSetItem", mod.OnTooltipSetItem)
end
end
end
obj = EnumerateFrames(obj)
end
end
|
Fix tooltip addition to work for all tooltips: addons and blizzard ui alike.
|
Fix tooltip addition to work for all tooltips: addons and blizzard ui alike.
|
Lua
|
bsd-3-clause
|
sheldon/epgp,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,protomech/epgp-dkp-reloaded,ceason/epgp-tfatf,hayword/tfatf_epgp,sheldon/epgp
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.