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
|
---|---|---|---|---|---|---|---|---|---|
cf39991cbf1840bcd9796065b00088d61d6d7e2a
|
share/util/resolve_redirections.lua
|
share/util/resolve_redirections.lua
|
-- libquvi-scripts
-- Copyright (C) 2012-2013 Toni Gundogdu <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This program is free software: you can redistribute it and/or
-- modify it under the terms of the GNU Affero General Public
-- License as published by the Free Software Foundation, either
-- version 3 of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General
-- Public License along with this program. If not, see
-- <http://www.gnu.org/licenses/>.
--
local ResolveExceptions = {} -- Utility functions unique to this script
function resolve_redirections(qargs)
-- Let libcURL resolve the URL redirections for us.
local r = quvi.http.resolve(qargs.input_url)
if #r.resolved_url ==0 then return qargs.input_url end
-- Apply any exception rules to the destination URL.
return ResolveExceptions.YouTube(qargs, r.resolved_url)
end
--
-- Utility functions
--
function ResolveExceptions.YouTube(qargs, dst)
-- [UPDATE] 2012-11-18: g00gle servers seem not to strip the #t anymore
return dst
--[[
-- Preserve the t= parameter (if any). The g00gle servers
-- strip them from the destination URL after redirecting.
-- e.g. http://www.youtube.com/watch?v=LWxTGJ3TK1U#t=2m22s
-- -> http://www.youtube.com/watch?v=LWxTGJ3TK1U
return dst .. (qargs.input_url:match('(#t=%w+)') or '')
]]--
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2012-2013 Toni Gundogdu <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This program is free software: you can redistribute it and/or
-- modify it under the terms of the GNU Affero General Public
-- License as published by the Free Software Foundation, either
-- version 3 of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General
-- Public License along with this program. If not, see
-- <http://www.gnu.org/licenses/>.
--
local ResolveExceptions = {} -- Utility functions unique to this script
function resolve_redirections(qargs)
--[[
UPDATE (2013-10-07)
libquvi will always attempt to resolve URL redirections. This means
that quvi_media_new (for example) will always resolve first and only
then pass the input URL to the media scripts to determine the support.
Problem:
- g00gle now redirects the embedded media URLs to the API pages
- This causes libquvi to return the "no support" because the
destination URL looks nothing like a typical media page URL
Solution:
- "normalize" (quvi/youtube) the input URL before we try to resolve
URL redirections
- "normalize" will convert the embedded media URLs to media page URLs,
which can then be passed to libquvi/libcurl for URL resolving
Notes:
- quvi_supports function skips resolving altogether unless online
check is forced
- This is the reason "normalize" must still be called in "ident"
function of the media script, even if we do so here
]]--
local Y = require 'quvi/youtube'
local u = Y.normalize(qargs.input_url)
-- Have libcurl resolve the URL redirections.
local r = quvi.http.resolve(u)
if #r.resolved_url ==1 then return u end
-- Apply any exception rules to the destination URL.
return ResolveExceptions.YouTube(qargs, r.resolved_url)
end
--
-- Utility functions
--
function ResolveExceptions.YouTube(qargs, dst)
return dst -- UPDATE (2012-11-18): g00gle servers no longer strip the "#t="
--
-- Preserve the #t= (if any) after redirection.
-- e.g. http://www.youtube.com/watch?v=LWxTGJ3TK1U#t=2m22s
-- -> http://www.youtube.com/watch?v=LWxTGJ3TK1U
--
-- return table.concat({dst, (qargs.input_url:match('(#t=%w+)') or '')}, '')
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
FIX: resolve_redirections.lua: Normalize YouTube input URL
|
FIX: resolve_redirections.lua: Normalize YouTube input URL
libquvi will always attempt to resolve URL redirections. This means
that quvi_media_new (for example) will always resolve first and only
then pass the input URL to the media scripts to determine the support
Problem:
- g00gle now redirects the embedded media URLs to the API pages
- This causes libquvi to return the "no support" because the
destination URL looks nothing like a typical media page URL
Solution:
- "normalize" (quvi/youtube) the input URL before we try to resolve
URL redirections
- "normalize" will convert the embedded media URLs to media page URLs,
which can then be passed to libquvi/libcurl for URL resolving
Notes:
- quvi_supports function skips resolving altogether unless online
check is forced
- This is the reason "normalize" must still be called in "ident"
function of the media script, even if this script does so
Signed-off-by: Toni Gundogdu <[email protected]>
|
Lua
|
agpl-3.0
|
alech/libquvi-scripts,alech/libquvi-scripts,legatvs/libquvi-scripts,legatvs/libquvi-scripts
|
03c86dcd74d10f6a4bd6b4190064f35f0e69c0bc
|
lib/luvit-websocket/libs/server.lua
|
lib/luvit-websocket/libs/server.lua
|
local net = require('net')
local b64 = require('./base64.lua')
local sha1 = require('./sha1.lua')
local table = require('table')
local math = require('math')
local bit = require('bit')
local table = require('table')
local string = require('string')
require('./table.lua')(table)
require('./string.lua')(string)
function toBits(num)
-- returns a table of bits, least significant first.
local t={} -- will contain the bits
while num>0 do
rest=math.fmod(num,2)
t[#t+1]=rest
num=(num-rest)/2
end
return t
end
function decodeMessage(buf)
local bytes = {}
local byteString = ""
for i = 1, #buf do
bytes[i] = string.byte(buf:sub(i,i))
byteString = byteString .. string.byte(buf:sub(i,i)) .. " "
end
local flags = toBits(bytes[1])
if flags[4] == 1 then
return 2
end
if flags[5] == 1 and flags[6] == 0 and flags[7] == 1 and flags[8] == 0 then
flags[6] = 1
flags[7] = 0
bytes[1] = tonumber(table.concat(flags, ""), 2)
local buff = {}
for k,v in pairs(bytes) do
buff = buff .. string.char(v)
end
return 1, buff
end
if flags[1] == 0 then
print("WebSocket Error: Message Fragmentation not supported.")
return nil
end
bytes[1] = nil
local length = 0
local offset = 0
if bytes[2]-128 >= 0 and bytes[2]-128 <= 125 then
length = bytes[2] - 128
bytes[2] = nil
offset = 2
elseif bytes[2]-128 == 126 then
length = tonumber(string.format("%x%x", bytes[3], bytes[4]), 16)
bytes[2] = nil bytes[3] = nil bytes[4] = nil
offset = 2 + 2
elseif bytes[2]-128 == 127 then
length = tonumber(string.format("%x%x%x%x%x%x%x%x", bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], bytes[8], bytes[9], bytes[10]), 16)
bytes[2] = nil bytes[3] = nil bytes[4] = nil bytes[5] = nil bytes[6] = nil bytes[7] = nil bytes[8] = nil bytes[9] = nil bytes[10] = nil
offset = 2 + 8
end
for k,v in pairs(bytes) do
bytes[k-offset] = v
bytes[k] = nil
end
local mask = {bytes[1], bytes[2], bytes[3], bytes[4]}
bytes[1] = nil bytes[2] = nil bytes[3] = nil bytes[4] = nil
for k,v in pairs(bytes) do
bytes[k-5] = v
bytes[k] = nil
end
local ret = ""
for i,v in pairs(bytes) do
local b = bit.bxor(mask[(i % 4)+1], v)
ret = ret .. string.char(b)
end
return ret
end
return function(port)
local this = {}
this.listener = {connect = {}, data = {}, disconnect = {}, _buffer = "", _startup = true}
this.on = function(this, s, c)
if this.listener[s] and type(this.listener[s]) == "table" and type(c) == "function" then
table.insert(this.listener[s], c)
end
end
this.call = function(this, s, args)
if this.listener[s] and type(this.listener[s]) == "table" then
for k,v in pairs(this.listener[s]) do
if type(v) == "function" then
if type(args) == "table" then
v(table.unpack(args))
else
v(args)
end
end
end
end
end
this.clients = {}
this.server = net.createServer(function (client)
client._startup = true
client._buffer = ""
client:on("data", function(c)
client.send = function(client, msg)
local flags = "10000001"
local bytes = {tonumber(flags, 2), #msg}
if bytes[2] > 65535 then
local bits = table.reverse(toBits(bytes[2]))
local zeros = 64 - #bits
local size = ""
for i = 1, zeros do
size = size .. "0"
end
for k,v in pairs(bits) do
size = size .. v
end
bytes[3] = "" bytes[4] = "" bytes[5] = "" bytes[6] = ""
bytes[7] = "" bytes[8] = "" bytes[9] = "" bytes[10] = ""
local b = 0
for bit = 1, 64 do
bytes[3 + b] = bytes[3 + b] .. size:sub(bit,bit)
if bit - 8 * b >= 8 then
bytes[3+b] = tonumber(bytes[3+b], 2)
b = b + 1
end
end
bytes[2] = 255 - 128
elseif bytes[2] > 125 then
local bits = table.reverse(toBits(bytes[2]))
local zeros = 16 - #bits
local size = ""
for i = 1, zeros do
size = size .. "0"
end
for k,v in pairs(bits) do
size = size .. v
end
bytes[3] = "" bytes[4] = ""
local b = 0
for bit = 1, 16 do
bytes[3 + b] = bytes[3 + b] .. size:sub(bit,bit)
if bit - 8 * b >= 8 then
bytes[3+b] = tonumber(bytes[3+b], 2)
b = b + 1
end
end
bytes[2] = 254 - 128
end
for i = 1, #msg do
table.insert(bytes, string.byte(msg:sub(i,i)))
end
local str = ""
for k,v in pairs(bytes) do
str = str .. string.char(v)
end
client:write(str)
end
if client._startup then
client._buffer = client._buffer .. c
c = client._buffer
end
if this.verbose then
print("Websocket Server received " .. #c .. " bytes")
end
if c:sub(1, 3) == "GET" and string.find(c, "\r\n\r\n", 0, true) then -- Handshake
local lines = c:split('\r\n')
local title = lines[1]
lines[1] = nil
local data = {}
for k,v in pairs(lines) do
if #v > 2 then
local line = v:split(": ")
data[line[1]] = line[2]
end
end
local responseKey = data["Sec-WebSocket-Key"] .. '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
responseKey = b64.encode(sha1.binary(responseKey))
local response = "HTTP/1.1 101 Switching Protocols\r\n"
.."Connection: Upgrade\r\n"
.."Upgrade: websocket\r\n"
.."Sec-WebSocket-Accept: " .. responseKey .. "\r\n"
.."\r\n"
client:write(response)
client._startup = false
client._buffer = ""
this:call("connect", {client})
table.insert(this.clients, client)
for k,v in pairs(this.clients) do
if v == client then
client.id = k
end
end
elseif client._startup == false then
local message, v = decodeMessage(c, this.debug)
if message == 2 then
this:call("disconnect", {client})
this.clients[client.id or 0] = nil
elseif message == 1 then
client:write(v)
elseif message then
this:call("data", {client, message})
else
print("Could not parse message: " .. c)
end
end
end)
end)
this.server:listen(port)
print("WebSocket Server listening on port " .. port)
return this
end
|
local net = require('net')
local b64 = require('./base64.lua')
local sha1 = require('./sha1.lua')
local table = require('table')
local math = require('math')
local bit = require('bit')
local table = require('table')
local string = require('string')
require('./table.lua')(table)
require('./string.lua')(string)
function toBits(num)
-- returns a table of bits, least significant first.
local t={} -- will contain the bits
while num>0 do
rest=math.fmod(num,2)
t[#t+1]=rest
num=(num-rest)/2
end
return t
end
function decodeMessage(buf)
local bytes = {}
local byteString = ""
for i = 1, #buf do
bytes[i] = string.byte(buf:sub(i,i))
byteString = byteString .. string.byte(buf:sub(i,i)) .. " "
end
local flags = toBits(bytes[1])
if flags[4] == 1 then
return 2
end
if flags[5] == 1 and flags[6] == 0 and flags[7] == 1 and flags[8] == 0 then
flags[6] = 1
flags[7] = 0
bytes[1] = tonumber(table.concat(flags, ""), 2)
local buff = {}
for k,v in pairs(bytes) do
buff = buff .. string.char(v)
end
return 1, buff
end
if flags[1] == 0 then
print("WebSocket Error: Message Fragmentation not supported.")
return nil
end
bytes[1] = nil
local length = 0
local offset = 0
if bytes[2]-128 >= 0 and bytes[2]-128 <= 125 then
length = bytes[2] - 128
bytes[2] = nil
offset = 2
elseif bytes[2]-128 == 126 then
length = tonumber(string.format("%x%x", bytes[3], bytes[4]), 16)
bytes[2] = nil bytes[3] = nil bytes[4] = nil
offset = 2 + 2
elseif bytes[2]-128 == 127 then
length = tonumber(string.format("%x%x%x%x%x%x%x%x", bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], bytes[8], bytes[9], bytes[10]), 16)
bytes[2] = nil bytes[3] = nil bytes[4] = nil bytes[5] = nil bytes[6] = nil bytes[7] = nil bytes[8] = nil bytes[9] = nil bytes[10] = nil
offset = 2 + 8
end
for k,v in pairs(bytes) do
bytes[k-offset] = v
bytes[k] = nil
end
local mask = {bytes[1], bytes[2], bytes[3], bytes[4]}
bytes[1] = nil bytes[2] = nil bytes[3] = nil bytes[4] = nil
for k,v in pairs(bytes) do
bytes[k-5] = v
bytes[k] = nil
end
local ret = ""
for i,v in pairs(bytes) do
local b = bit.bxor(mask[(i % 4)+1], v)
ret = ret .. string.char(b)
end
return ret
end
return function(port)
local this = {}
this.listener = {connect = {}, data = {}, disconnect = {}, _buffer = "", _startup = true}
this.on = function(this, s, c)
if this.listener[s] and type(this.listener[s]) == "table" and type(c) == "function" then
table.insert(this.listener[s], c)
end
end
this.call = function(this, s, args)
if this.listener[s] and type(this.listener[s]) == "table" then
for k,v in pairs(this.listener[s]) do
if type(v) == "function" then
if type(args) == "table" then
v(table.unpack(args))
else
v(args)
end
end
end
end
end
this.clients = {}
this.server = net.createServer(function (client)
client._startup = true
client._buffer = ""
client:on("data", function(c)
client.send = function(client, msg)
local flags = "10000001"
local bytes = {tonumber(flags, 2), #msg}
if bytes[2] >= 65536 then
local length = bytes[2]
for i = 10, 3, -1 do
bytes[i] = band(length, 0xFF)
length = rshift(length, 8)
end
bytes[2] = 127
elseif bytes[2] >= 126 then
bytes[3] = bit.band(bit.rshift(bytes[2], 8), 0xFF)
bytes[4] = bit.band(bytes[2], 0xFF)
bytes[2] = 126
end
for i = 1, #msg do
table.insert(bytes, string.byte(msg:sub(i,i)))
end
local str = ""
for k,v in pairs(bytes) do
str = str .. string.char(v)
end
client:write(str)
end
if client._startup then
client._buffer = client._buffer .. c
c = client._buffer
end
if this.verbose then
print("Websocket Server received " .. #c .. " bytes")
end
if c:sub(1, 3) == "GET" and string.find(c, "\r\n\r\n", 0, true) then -- Handshake
local lines = c:split('\r\n')
local title = lines[1]
lines[1] = nil
local data = {}
for k,v in pairs(lines) do
if #v > 2 then
local line = v:split(": ")
data[line[1]] = line[2]
end
end
local responseKey = data["Sec-WebSocket-Key"] .. '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
responseKey = b64.encode(sha1.binary(responseKey))
local response = "HTTP/1.1 101 Switching Protocols\r\n"
.."Connection: Upgrade\r\n"
.."Upgrade: websocket\r\n"
.."Sec-WebSocket-Accept: " .. responseKey .. "\r\n"
.."\r\n"
client:write(response)
client._startup = false
client._buffer = ""
this:call("connect", {client})
table.insert(this.clients, client)
for k,v in pairs(this.clients) do
if v == client then
client.id = k
end
end
elseif client._startup == false then
local message, v = decodeMessage(c, this.debug)
if message == 2 then
this:call("disconnect", {client})
this.clients[client.id or 0] = nil
elseif message == 1 then
client:write(v)
elseif message then
this:call("data", {client, message})
else
print("Could not parse message: " .. c)
end
end
end)
end)
this.server:listen(port)
print("WebSocket Server listening on port " .. port)
return this
end
|
Fix luvit-websocket bug in send function
|
Fix luvit-websocket bug in send function
|
Lua
|
bsd-2-clause
|
elflang/elf,elflang/elf,elflang/elf
|
a36f54d7a75f83e59e4854f3dd02ca3a2a2a5a05
|
lua/starfall/libs_sh/coroutine.lua
|
lua/starfall/libs_sh/coroutine.lua
|
--- Coroutine library
--- Coroutine library
-- @shared
local coroutine_library, _ = SF.Libraries.Register( "coroutine" )
local coroutine = coroutine
local _, thread_metamethods = SF.Typedef( "thread" )
local wrap, unwrap = SF.CreateWrapper( thread_metamethods, true, false )
local coroutines = setmetatable( {}, { __mode = "v" } )
local function createCoroutine ( func )
-- Can't use coroutine.create, because of a bug that prevents halting the program when it exceeds quota
local wrappedFunc = coroutine.wrap( function ()
local args = coroutine.yield( coroutine.running() ) -- Hack to get the coroutine from a wrapped function. Necessary because coroutine.create is not available
return func( args )
end )
local thread = wrappedFunc()
coroutines[ thread ] = wrappedFunc
return wrappedFunc, thread
end
--- Creates a new coroutine.
-- @param func Function of the coroutine
-- @return coroutine
function coroutine_library.create ( func )
SF.CheckType( func, "function" )
local wrappedFunc, thread = createCoroutine( func )
local ret = { func = wrappedFunc, thread = thread }
return wrap( ret )
end
--- Creates a new coroutine.
-- @param func Function of the coroutine
-- @return A function that, when called, resumes the created coroutine. Any parameters to that function will be passed to the coroutine.
function coroutine_library.wrap ( func )
SF.CheckType( func, "function" )
local wrappedFunc, thread = createCoroutine( func )
return wrappedFunc
end
--- Resumes a suspended coroutine. Note that, in contrast to Lua's native coroutine.resume function, it will not run in protected mode and can throw an error.
-- @param thread coroutine to resume
-- @param ... optional parameters that will be passed to the coroutine
-- @return Any values the coroutine is returning to the main thread
function coroutine_library.resume ( thread, ... )
SF.CheckType( thread, thread_metamethods )
local func = unwrap( thread ).func
return func( ... )
end
--- Suspends the currently running coroutine. May not be called outside a coroutine.
-- @param ... optional parameters that will be returned to the main thread
-- @return Any values passed to the coroutine
function coroutine_library.yield ( ... )
return coroutine.yield( ... )
end
--- Returns the status of the coroutine.
-- @param thread The coroutine
-- @return Either "suspended", "running", "normal" or "dead"
function coroutine_library.status ( thread )
SF.CheckType( thread, thread_metamethods )
local thread = unwrap( thread ).thread
return coroutine.status( thread )
end
--- Returns the coroutine that is currently running.
-- @return Currently running coroutine
function coroutine_library.running ()
local thread = coroutine.running()
return wrap( { thread = thread, func = coroutines[ thread ] } )
end
--- Suspends the coroutine for a number of seconds. Note that the coroutine will not resume automatically, but any attempts to resume the coroutine while it is waiting will not resume the coroutine and act as if the coroutine suspended itself immediately.
-- @param time Time in seconds to suspend the coroutine
function coroutine_library.wait ( time )
coroutine.wait( time )
SF.CheckType( time, "number" )
end
|
--- Coroutine library
--- Coroutine library
-- @shared
local coroutine_library, _ = SF.Libraries.Register( "coroutine" )
local coroutine = coroutine
local _, thread_metamethods = SF.Typedef( "thread" )
local wrap, unwrap = SF.CreateWrapper( thread_metamethods, true, false )
local coroutines = setmetatable( {}, { __mode = "v" } )
local function createCoroutine ( func )
-- Can't use coroutine.create, because of a bug that prevents halting the program when it exceeds quota
-- Hack to get the coroutine from a wrapped function. Necessary because coroutine.create is not available
local wrappedFunc = coroutine.wrap( function() return func( coroutine.yield( coroutine.running() ) ) end )
local thread = wrappedFunc()
coroutines[ thread ] = wrappedFunc
return wrappedFunc, thread
end
--- Creates a new coroutine.
-- @param func Function of the coroutine
-- @return coroutine
function coroutine_library.create ( func )
SF.CheckType( func, "function" )
local wrappedFunc, thread = createCoroutine( func )
local ret = { func = wrappedFunc, thread = thread }
return wrap( ret )
end
--- Creates a new coroutine.
-- @param func Function of the coroutine
-- @return A function that, when called, resumes the created coroutine. Any parameters to that function will be passed to the coroutine.
function coroutine_library.wrap ( func )
SF.CheckType( func, "function" )
local wrappedFunc, thread = createCoroutine( func )
return wrappedFunc
end
--- Resumes a suspended coroutine. Note that, in contrast to Lua's native coroutine.resume function, it will not run in protected mode and can throw an error.
-- @param thread coroutine to resume
-- @param ... optional parameters that will be passed to the coroutine
-- @return Any values the coroutine is returning to the main thread
function coroutine_library.resume ( thread, ... )
SF.CheckType( thread, thread_metamethods )
local func = unwrap( thread ).func
return func( ... )
end
--- Suspends the currently running coroutine. May not be called outside a coroutine.
-- @param ... optional parameters that will be returned to the main thread
-- @return Any values passed to the coroutine
function coroutine_library.yield ( ... )
return coroutine.yield( ... )
end
--- Returns the status of the coroutine.
-- @param thread The coroutine
-- @return Either "suspended", "running", "normal" or "dead"
function coroutine_library.status ( thread )
SF.CheckType( thread, thread_metamethods )
local thread = unwrap( thread ).thread
return coroutine.status( thread )
end
--- Returns the coroutine that is currently running.
-- @return Currently running coroutine
function coroutine_library.running ()
local thread = coroutine.running()
return wrap( { thread = thread, func = coroutines[ thread ] } )
end
--- Suspends the coroutine for a number of seconds. Note that the coroutine will not resume automatically, but any attempts to resume the coroutine while it is waiting will not resume the coroutine and act as if the coroutine suspended itself immediately.
-- @param time Time in seconds to suspend the coroutine
function coroutine_library.wait ( time )
coroutine.wait( time )
SF.CheckType( time, "number" )
end
|
Fixed coroutine resumes not passing > 1 arg.
|
Fixed coroutine resumes not passing > 1 arg.
Fixes #280
|
Lua
|
bsd-3-clause
|
INPStarfall/Starfall,Jazzelhawk/Starfall,Xandaros/Starfall,INPStarfall/Starfall,Ingenious-Gaming/Starfall,Jazzelhawk/Starfall,Xandaros/Starfall,Ingenious-Gaming/Starfall
|
47f0719148aacf7fb076f6e3b16d0bdbb7b8406c
|
toshiba.lua
|
toshiba.lua
|
dofile("urlcode.lua")
dofile("table_show.lua")
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
local downloaded = {}
local addedtolist = {}
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"]
local html = urlpos["link_expect_html"]
if downloaded[url] == true or addedtolist[url] == true then
return false
end
if (downloaded[url] ~= true or addedtolist[url] ~= true) then
if string.match(urlpos["url"]["host"], "toshiba%.com") and string.match(url, "/"..item_value.."[a-z0-9][a-z0-9]") and not string.match(url, "/"..item_value.."[a-z0-9][a-z0-9][a-z0-9]") then
addedtolist[url] = true
return true
elseif html == 0 then
addedtolist[url] = true
return true
else
return false
end
end
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
local html = nil
if downloaded[url] ~= true then
downloaded[url] = true
end
local function check(url)
if (downloaded[url] ~= true and addedtolist[url] ~= true) and (string.match(url, "https?://cdgenp01.csd.toshiba.com/") or (string.match(string.match(newurl, "https?://([^/]+)"), "toshiba%.com") and string.match(url, "/"..item_value.."[a-z0-9][a-z0-9]") and not string.match(url, "/"..item_value.."[a-z0-9][a-z0-9][a-z0-9]"))) then
if string.match(url, "&") then
table.insert(urls, { url=string.gsub(url, "&", "&") })
addedtolist[url] = true
addedtolist[string.gsub(url, "&", "&")] = true
else
table.insert(urls, { url=url })
addedtolist[url] = true
end
end
end
if string.match(string.match(url, "https?://([^/]+)/"), "toshiba%.com") and string.match(url, "/"..item_value.."[a-z0-9][a-z0-9]") and not string.match(url, "/"..item_value.."[a-z0-9][a-z0-9][a-z0-9]") then
html = read_file(file)
for newurl in string.gmatch(html, '"(https?://[^"]+)"') do
check(newurl)
end
for newurl in string.gmatch(html, '("/[^"]+)"') do
if string.match(newurl, '"//') then
check(string.gsub(newurl, '"//', 'http://'))
elseif not string.match(newurl, '"//') then
check(string.match(url, "(https?://[^/]+)/")..string.match(newurl, '"(/.+)'))
end
end
for newurl in string.gmatch(html, "('/[^']+)'") do
if string.match(newurl, "'//") then
check(string.gsub(newurl, "'//", "http://"))
elseif not string.match(newurl, "'//") then
check(string.match(url, "(https?://[^/]+)/")..string.match(newurl, "'(/.+)"))
end
end
end
return urls
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
status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n")
io.stdout:flush()
if (status_code >= 200 and status_code <= 399) then
if string.match(url.url, "https://") then
local newurl = string.gsub(url.url, "https://", "http://")
downloaded[newurl] = true
else
downloaded[url.url] = true
end
end
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404 and status_code ~= 403) then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 6 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
tries = 0
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
elseif status_code == 0 then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 6 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
tries = 0
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
end
tries = 0
local sleep_time = 0
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
dofile("urlcode.lua")
dofile("table_show.lua")
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
local downloaded = {}
local addedtolist = {}
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"]
local html = urlpos["link_expect_html"]
if downloaded[url] == true or addedtolist[url] == true then
return false
end
if (downloaded[url] ~= true or addedtolist[url] ~= true) then
if string.match(urlpos["url"]["host"], "toshiba%.com") and string.match(url, "[^0-9]"..item_value.."[a-z0-9][a-z0-9]") and not string.match(url, "[^0-9]"..item_value.."[a-z0-9][a-z0-9][a-z0-9]") then
addedtolist[url] = true
return true
elseif html == 0 then
addedtolist[url] = true
return true
else
return false
end
end
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
local html = nil
if downloaded[url] ~= true then
downloaded[url] = true
end
local function check(url)
if (downloaded[url] ~= true and addedtolist[url] ~= true) and (string.match(url, "https?://cdgenp01%.csd%.toshiba%.com/") or (string.match(string.match(url, "https?://([^/]+)"), "toshiba%.com") and string.match(url, "[^0-9]"..item_value.."[a-z0-9][a-z0-9]") and not string.match(url, "[^0-9]"..item_value.."[a-z0-9][a-z0-9][a-z0-9]"))) then
if string.match(url, "&") then
table.insert(urls, { url=string.gsub(url, "&", "&") })
addedtolist[url] = true
addedtolist[string.gsub(url, "&", "&")] = true
else
table.insert(urls, { url=url })
addedtolist[url] = true
end
end
end
if string.match(string.match(url, "https?://([^/]+)/"), "toshiba%.com") and string.match(url, "[^0-9]"..item_value.."[a-z0-9][a-z0-9]") and not string.match(url, "[^0-9]"..item_value.."[a-z0-9][a-z0-9][a-z0-9]") then
html = read_file(file)
for newurl in string.gmatch(html, '"(https?://[^"]+)"') do
check(newurl)
end
for newurl in string.gmatch(html, '("/[^"]+)"') do
if string.match(newurl, '"//') then
check(string.gsub(newurl, '"//', 'http://'))
elseif not string.match(newurl, '"//') then
check(string.match(url, "(https?://[^/]+)/")..string.match(newurl, '"(/.+)'))
end
end
for newurl in string.gmatch(html, "('/[^']+)'") do
if string.match(newurl, "'//") then
check(string.gsub(newurl, "'//", "http://"))
elseif not string.match(newurl, "'//") then
check(string.match(url, "(https?://[^/]+)/")..string.match(newurl, "'(/.+)"))
end
end
end
return urls
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
status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n")
io.stdout:flush()
if (status_code >= 200 and status_code <= 399) then
if string.match(url.url, "https://") then
local newurl = string.gsub(url.url, "https://", "http://")
downloaded[newurl] = true
else
downloaded[url.url] = true
end
end
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404 and status_code ~= 403) then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 6 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
tries = 0
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
elseif status_code == 0 then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 6 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
tries = 0
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
end
tries = 0
local sleep_time = 0
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
toshiba.lua: fixes
|
toshiba.lua: fixes
|
Lua
|
unlicense
|
ArchiveTeam/toshiba-grab,ArchiveTeam/toshiba-grab
|
e8b5fdd7d625a7a2b461e8b673521fc969d4104a
|
src/auxiliary.lua
|
src/auxiliary.lua
|
-- Miscellaneous auxiliary functions.
function form_date(days)
_check_required(days, 'number')
return os.date("%d-%b-%Y", os.time() - days * 60 * 60 * 24)
end
function get_password(prompt)
_check_optional(prompt, 'string')
if (prompt ~= nil) then
io.write(prompt)
else
io.write('Enter password: ')
end
ifsys.noecho()
local p = io.read()
ifsys.echo()
return p
end
function pipe_to(command, data)
_check_required(command, 'string')
_check_required(data, 'string')
f = ifsys.popen(command, "w")
ifsys.write(f, data)
return ifsys.pclose(f)
end
function pipe_from(command)
_check_required(command, 'string')
f = ifsys.popen(command, "r")
local string = ''
while (true) do
s = ifsys.read(f)
if (s ~= nil) then
string = string .. s
else
break
end
end
return ifsys.pclose(f), string
end
function become_daemon(interval, commands, nochdir, noclose)
_check_required(interval, 'number')
_check_required(commands, 'function')
_check_optional(nochdir, 'boolean')
_check_optional(noclose, 'boolean')
ifsys.daemon(nochdir, noclose)
repeat
pcall(commands)
until (ifsys.sleep(interval) ~= 0)
end
|
-- Miscellaneous auxiliary functions.
function form_date(days)
_check_required(days, 'number')
return os.date("%d-%b-%Y", os.time() - days * 60 * 60 * 24)
end
function get_password(prompt)
_check_optional(prompt, 'string')
if (prompt ~= nil) then
io.write(prompt)
else
io.write('Enter password: ')
end
ifsys.noecho()
local p = io.read()
ifsys.echo()
return p
end
function pipe_to(command, data)
_check_required(command, 'string')
_check_required(data, 'string')
f = ifsys.popen(command, "w")
ifsys.write(f, data)
return ifsys.pclose(f)
end
function pipe_from(command)
_check_required(command, 'string')
f = ifsys.popen(command, "r")
local string = ''
while (true) do
s = ifsys.read(f)
if (s ~= nil) then
string = string .. s
else
break
end
end
return ifsys.pclose(f), string
end
function become_daemon(interval, commands, nochdir, noclose)
_check_required(interval, 'number')
_check_required(commands, 'function')
_check_optional(nochdir, 'boolean')
_check_optional(noclose, 'boolean')
if (nochdir == nil) then
nochdir = false
end
if (noclose == nil) then
noclose = false
end
ifsys.daemon(nochdir, noclose)
repeat
pcall(commands)
until (ifsys.sleep(interval) ~= 0)
end
|
Fix become_daemon() call to ifsys.daemon()
|
Fix become_daemon() call to ifsys.daemon()
Make sure that the two optional arguments of ifsys.daemon() are of type
boolean as expected.
|
Lua
|
mit
|
eliteraspberries/imapfilter,makinacorpus/imapfilter,makinacorpus/imapfilter,lefcha/imapfilter
|
d703b416b5056f28fe76623a39e7a534cf598092
|
Modules/Utility/os.lua
|
Modules/Utility/os.lua
|
-- @author Narrev
local firstRequired = os.time()
local date = function(optString, unix)
local stringPassed = false
if not (optString == nil and unix == nil) then
-- This adds compatibility for Roblox JSON and MarketPlace format, and the different ways this function accepts parameters
if type(optString) == "number" or optString:match("/Date%((%d+)") or optString:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then
-- if they didn't pass a non unix time
unix, optString = optString
elseif type(optString) == "string" and optString ~= "*t" then
assert(optString:find("%%[_cxXTrRaAbBdHIjMmpsSuwyY]"), "Invalid string passed to os.date")
unix, optString = optString:find("^!") and os.time() or unix, optString:find("^!") and optString:sub(2) or optString
stringPassed = true
end
if type(unix) == "string" then -- If it is a unix time, but in a Roblox format
if unix:match("/Date%((%d+)") then -- This is for a certain JSON compatibility. It works the same even if you don't need it
unix = unix:match("/Date%((%d+)") / 1000
elseif unix:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then -- Untested MarketPlaceService compatibility
-- This part of the script is untested
local year, month, day, hour, minute, second = unix:match("(%d+)\-(%d+)\-(%d+)T(%d+):(%d+):([%d%.]+).+")
unix = os.time{year = year, month = month, day = day, hour = hour, minute = minute, second = second}
end
end
else
optString, stringPassed = "%c", true
end
local floor, ceil = math.floor, math.ceil
local overflow = function(tab, seed) for i = 1, #tab do if seed - tab[i] <= 0 then return i, seed end seed = seed - tab[i] end end
local dayAlign = unix == 0 and 1 or 0 -- fixes calculation for unix == 0
local unix = type(unix) == "number" and unix + dayAlign or tick()
local days, month, year = ceil(unix / 86400) + 719527
local wday = (days + 6) % 7
local _4Years = 400*floor(days / 146097) + 100*floor(days % 146097 / 36524) + 4*floor(days % 146097 % 36524 / 1461)
year, days = overflow({366,365,365,365}, days - 365*_4Years - floor(.25*_4Years - .25) - floor(.0025*_4Years - .0025) + floor(.01*_4Years - .01)) -- [0-1461]
year, _4Years = year + _4Years - 1
local yDay = days
month, days = overflow({31,(year%4==0 and(year%25~=0 or year%16==0))and 29 or 28,31,30,31,30,31,31,30,31,30,31}, days)
local hours = floor(unix / 3600 % 24)
local minutes = floor(unix / 60 % 60)
local seconds = floor(unix % 60) - dayAlign
local dayNamesAbbr = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"} -- Consider using dayNames[wday + 1]:sub(1,3)
local dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
local months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
local suffixes = {"st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "st"}
if stringPassed then
local padded = function(num)
return string.format("%02d", num)
end
return (optString
:gsub("%%c", "%%x %%X")
:gsub("%%_c", "%%_x %%_X")
:gsub("%%x", "%%m/%%d/%%y")
:gsub("%%_x", "%%_m/%%_d/%%y")
:gsub("%%X", "%%H:%%M:%%S")
:gsub("%%_X", "%%_H:%%M:%%S")
:gsub("%%T", "%%I:%%M %%p")
:gsub("%%_T", "%%_I:%%M %%p")
:gsub("%%r", "%%I:%%M:%%S %%p")
:gsub("%%_r", "%%_I:%%M:%%S %%p")
:gsub("%%R", "%%H:%%M")
:gsub("%%_R", "%%_H:%%M")
:gsub("%%a", dayNamesAbbr[wday + 1])
:gsub("%%A", dayNames[wday + 1])
:gsub("%%b", months[month]:sub(1,3))
:gsub("%%B", months[month])
:gsub("%%d", padded(days))
:gsub("%%_d", days)
:gsub("%%H", padded(hours))
:gsub("%%_H", hours)
:gsub("%%I", padded(hours > 12 and hours - 12 or hours == 0 and 12 or hours))
:gsub("%%_I", hours > 12 and hours - 12 or hours == 0 and 12 or hours)
:gsub("%%j", padded(yDay))
:gsub("%%_j", yDay)
:gsub("%%M", padded(minutes))
:gsub("%%_M", minutes)
:gsub("%%m", padded(month))
:gsub("%%_m", month)
:gsub("%%n","\n")
:gsub("%%p", hours >= 12 and "pm" or "am")
:gsub("%%_p", hours >= 12 and "PM" or "AM")
:gsub("%%s", suffixes[days])
:gsub("%%S", padded(seconds))
:gsub("%%_S", seconds)
:gsub("%%t", "\t")
:gsub("%%u", wday == 0 and 7 or wday)
:gsub("%%w", wday)
:gsub("%%Y", year)
:gsub("%%y", padded(year % 100))
:gsub("%%_y", year % 100)
:gsub("%%%%", "%%")
)
end
return {year = year, month = month, day = days, yday = yDay, wday = wday, hour = hours, min = minutes, sec = seconds}
end
local clock = function() return os.time() - firstRequired end
return setmetatable({date, clock}, {__index = os})
|
-- @author Narrev
local date = function(optString, unix)
local stringPassed = false
if not (optString == nil and unix == nil) then
-- This adds compatibility for Roblox JSON and MarketPlace format, and the different ways this function accepts parameters
if type(optString) == "number" or optString:match("/Date%((%d+)") or optString:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then
-- if they didn't pass a non unix time
unix, optString = optString
elseif type(optString) == "string" and optString ~= "*t" then
assert(optString:find("%%[_cxXTrRaAbBdHIjMmpsSuwyY]"), "Invalid string passed to os.date")
unix, optString = optString:find("^!") and os.time() or unix, optString:find("^!") and optString:sub(2) or optString
stringPassed = true
end
if type(unix) == "string" then -- If it is a unix time, but in a Roblox format
if unix:match("/Date%((%d+)") then -- This is for a certain JSON compatibility. It works the same even if you don't need it
unix = unix:match("/Date%((%d+)") / 1000
elseif unix:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then -- Untested MarketPlaceService compatibility
-- This part of the script is untested
local year, month, day, hour, minute, second = unix:match("(%d+)\-(%d+)\-(%d+)T(%d+):(%d+):([%d%.]+).+")
unix = os.time{year = year, month = month, day = day, hour = hour, minute = minute, second = second}
end
end
else
optString, stringPassed = "%c", true
end
local floor, ceil = math.floor, math.ceil
local overflow = function(tab, seed) for i = 1, #tab do if seed - tab[i] <= 0 then return i, seed end seed = seed - tab[i] end end
local dayAlign = unix == 0 and 1 or 0 -- fixes calculation for unix == 0
local unix = type(unix) == "number" and unix + dayAlign or tick()
local days, month, year = ceil(unix / 86400) + 719527
local wday = (days + 6) % 7
local _4Years = 400*floor(days / 146097) + 100*floor(days % 146097 / 36524) + 4*floor(days % 146097 % 36524 / 1461) - 1
year, days = overflow({366,365,365,365}, days - 365*(_4Years + 1) - floor(.25*_4Years) - floor(.0025*_4Years) + floor(.01*_4Years)) -- [0-1461]
year, _4Years = year + _4Years
local yDay = days
month, days = overflow({31,(year%4==0 and(year%25~=0 or year%16==0))and 29 or 28,31,30,31,30,31,31,30,31,30,31}, days)
local hours = floor(unix / 3600 % 24)
local minutes = floor(unix / 60 % 60)
local seconds = floor(unix % 60) - dayAlign
local dayNamesAbbr = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"} -- Consider using dayNames[wday + 1]:sub(1,3)
local dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
local months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
local suffixes = {"st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "st"}
if stringPassed then
local padded = function(num)
return string.format("%02d", num)
end
return (optString
:gsub("%%c", "%%x %%X")
:gsub("%%_c", "%%_x %%_X")
:gsub("%%x", "%%m/%%d/%%y")
:gsub("%%_x", "%%_m/%%_d/%%y")
:gsub("%%X", "%%H:%%M:%%S")
:gsub("%%_X", "%%_H:%%M:%%S")
:gsub("%%T", "%%I:%%M %%p")
:gsub("%%_T", "%%_I:%%M %%p")
:gsub("%%r", "%%I:%%M:%%S %%p")
:gsub("%%_r", "%%_I:%%M:%%S %%p")
:gsub("%%R", "%%H:%%M")
:gsub("%%_R", "%%_H:%%M")
:gsub("%%a", dayNamesAbbr[wday + 1])
:gsub("%%A", dayNames[wday + 1])
:gsub("%%b", months[month]:sub(1,3))
:gsub("%%B", months[month])
:gsub("%%d", padded(days))
:gsub("%%_d", days)
:gsub("%%H", padded(hours))
:gsub("%%_H", hours)
:gsub("%%I", padded(hours > 12 and hours - 12 or hours == 0 and 12 or hours))
:gsub("%%_I", hours > 12 and hours - 12 or hours == 0 and 12 or hours)
:gsub("%%j", padded(yDay))
:gsub("%%_j", yDay)
:gsub("%%M", padded(minutes))
:gsub("%%_M", minutes)
:gsub("%%m", padded(month))
:gsub("%%_m", month)
:gsub("%%n","\n")
:gsub("%%p", hours >= 12 and "pm" or "am")
:gsub("%%_p", hours >= 12 and "PM" or "AM")
:gsub("%%s", suffixes[days])
:gsub("%%S", padded(seconds))
:gsub("%%_S", seconds)
:gsub("%%t", "\t")
:gsub("%%u", wday == 0 and 7 or wday)
:gsub("%%w", wday)
:gsub("%%Y", year)
:gsub("%%y", padded(year % 100))
:gsub("%%_y", year % 100)
:gsub("%%%%", "%%")
)
end
return {year = year, month = month, day = days, yday = yDay, wday = wday, hour = hours, min = minutes, sec = seconds}
end
local clock = function() return ({wait()})[2] end
return setmetatable({date = date, clock = clock}, {__index = os})
|
fix table returning
|
fix table returning
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
eddab803d5a89dca79eaec2fb7603f4050a608a1
|
Dotfiles/hydra.lua
|
Dotfiles/hydra.lua
|
-- autostart hydra
autolaunch.set(true)
-- watch for changes
pathwatcher.new(os.getenv("HOME") .. "/.hydra/", hydra.reload):start()
-- notify on start
notify.show("Hydra", "Started!", "", "")
-- window margin
local margin = 10
-- push to screen edge
function push(win, direction)
local screen = win:screen():frame_without_dock_or_menu()
local frames = {
[ "up" ] = function()
return {
x = margin + screen.x,
y = margin + screen.y,
w = screen.w - margin * 2,
h = screen.h / 2 - margin
}
end,
[ "down" ] = function()
return {
x = margin + screen.x,
y = margin * 3 / 4 + screen.h / 2 + screen.y,
w = screen.w - margin * 2,
h = screen.h / 2 - margin * (2 - 1 / 4)
}
end,
[ "left" ] = function()
return {
x = margin + screen.x,
y = margin + screen.y,
w = screen.w / 2 - margin * (2 - 1 / 4),
h = screen.h - margin * (2 - 1 / 4)
}
end,
[ "right" ] = function()
return {
x = margin / 2 + screen.w / 2 + screen.x,
y = margin + screen.y,
w = screen.w / 2 - margin * (2 - 1 / 4),
h = screen.h - margin * (2 - 1 / 4)
}
end
}
win:setframe(frames[direction]())
end
-- move by margin
function nudge(win, direction)
local screen = win:screen():frame_without_dock_or_menu()
local frame = win:frame()
local modifyframe = {
[ "up" ] = function(frame)
frame.y = math.max(screen.y + margin, frame.y - margin)
return frame
end,
[ "down" ] = function(frame)
frame.y = math.min(screen.y + screen.h - margin * 1 / 4, frame.y + margin)
return frame
end,
[ "left" ] = function(frame)
frame.x = math.max(screen.x + margin, frame.x - margin)
return frame
end,
[ "right" ] = function(frame)
frame.x = math.min(screen.x + screen.w - margin - frame.w, frame.x + margin)
return frame
end
}
win:setframe(modifyframe[direction](frame))
end
-- fit inside screen
function fitframe(screen, frame)
frame.w = math.min(frame.w, screen.w - margin * 2)
frame.h = math.min(frame.h, screen.h - margin * (2 - 1 / 4))
return frame
end
-- center inside screen
function centerframe(screen, frame)
frame.x = screen.w / 2 - frame.w / 2 + screen.x
frame.y = screen.h / 2 - frame.h / 2 + screen.y
return frame
end
-- center given window
function centerwindow(win)
local screen = win:screen():frame_without_dock_or_menu()
local frame = win:frame()
win:setframe(centerframe(screen, frame))
end
-- fullscreen window with margin
function fullscreen(win)
local screen = win:screen():frame_without_dock_or_menu()
local frame = {
x = margin + screen.x,
y = margin + screen.y,
w = screen.w - margin * 2,
h = screen.h - margin * (2 - 1 / 4)
}
win:setframe(frame)
end
-- throw to next screen, center and fit
function nextscreen(win)
local screen = win:screen():next():frame_without_dock_or_menu()
local frame = win:frame()
frame.x = screen.x
frame.y = screen.y
win:setframe(centerframe(screen, fitframe(screen, frame)))
win:focus()
end
-- set window size and center
function centerwithsize(win, w, h)
local screen = win:screen():frame_without_dock_or_menu()
local frame = win:frame()
frame.w = w
frame.h = h
win:setframe(centerframe(screen, fitframe(screen, frame)))
end
-- save and restore window positions
local positions = {}
function winposition(win, option)
local id = win:application():bundleid()
local frame = win:frame()
if option == "save" then
notify.show("Hydra", "position for " .. id .. " saved", "", "")
positions[id] = frame
end
if option == "load" and positions[id] then
notify.show("Hydra", "position for " .. id .. " restored", "", "")
win:setframe(positions[id])
end
end
-- keyboard modifier for bindings
local mod1 = { "cmd", "ctrl" }
local mod2 = { "cmd", "ctrl", "alt" }
-- window mod1ifiers
hotkey.bind(mod1, "c", function() centerwindow(window.focusedwindow()) end)
hotkey.bind(mod1, "z", function() fullscreen(window.focusedwindow()) end)
hotkey.bind(mod1, "tab", function() nextscreen(window.focusedwindow()) end)
-- push to edges and nudge
fnutils.each({ "up", "down", "left", "right" }, function(direction)
hotkey.bind(mod1, direction, function() push(window:focusedwindow(), direction) end)
hotkey.bind(mod2, direction, function() nudge(window:focusedwindow(), direction) end)
end)
-- set window sizes
fnutils.each({
{ key = 1, w = 1400, h = 940 },
{ key = 2, w = 980, h = 920 },
{ key = 3, w = 800, h = 880 },
{ key = 4, w = 800, h = 740 },
{ key = 5, w = 760, h = 620 },
{ key = 6, w = 770, h = 470 }
}, function(object)
hotkey.bind(mod1, object.key, function()
centerwithsize(window.focusedwindow(), object.w, object.h)
end)
end)
-- save and restore window positions
hotkey.bind(mod1, "s", function() winposition(window.focusedwindow(), "save") end)
hotkey.bind(mod1, "r", function() winposition(window.focusedwindow(), "load") end)
-- reload hydra settings
hotkey.bind(mod1, "h", function() hydra:reload() end)
-- launch and focus applications
fnutils.each({
{ key = "t", app = "Terminal" },
{ key = "s", app = "Safari" },
{ key = "f", app = "Finder" },
{ key = "n", app = "Notational Velocity" },
{ key = "p", app = "TaskPaper" },
{ key = "m", app = "MacVim" }
}, function(object)
hotkey.bind(mod2, object.key, function() application.launchorfocus(object.app) end)
end)
|
-- autostart hydra
autolaunch.set(true)
-- watch for changes
pathwatcher.new(os.getenv("HOME") .. "/.hydra/", hydra.reload):start()
-- notify on start
notify.show("Hydra", "Started!", "", "")
-- window margin
local margin = 10
-- push to screen edge
function push(win, direction)
local screen = win:screen():frame_without_dock_or_menu()
local frames = {
[ "up" ] = function()
return {
x = margin + screen.x,
y = margin + screen.y,
w = screen.w - margin * 2,
h = screen.h / 2 - margin
}
end,
[ "down" ] = function()
return {
x = margin + screen.x,
y = margin * 3 / 4 + screen.h / 2 + screen.y,
w = screen.w - margin * 2,
h = screen.h / 2 - margin * (2 - 1 / 4)
}
end,
[ "left" ] = function()
return {
x = margin + screen.x,
y = margin + screen.y,
w = screen.w / 2 - margin * (2 - 1 / 4),
h = screen.h - margin * (2 - 1 / 4)
}
end,
[ "right" ] = function()
return {
x = margin / 2 + screen.w / 2 + screen.x,
y = margin + screen.y,
w = screen.w / 2 - margin * (2 - 1 / 4),
h = screen.h - margin * (2 - 1 / 4)
}
end
}
win:setframe(frames[direction]())
end
-- move by margin
function nudge(win, direction)
local screen = win:screen():frame_without_dock_or_menu()
local frame = win:frame()
local modifyframe = {
[ "up" ] = function(frame)
frame.y = math.max(screen.y + margin, frame.y - margin)
return frame
end,
[ "down" ] = function(frame)
frame.y = math.min(screen.y + screen.h - margin * 1 / 4, frame.y + margin)
return frame
end,
[ "left" ] = function(frame)
frame.x = math.max(screen.x + margin, frame.x - margin)
return frame
end,
[ "right" ] = function(frame)
frame.x = math.min(screen.x + screen.w - margin - frame.w, frame.x + margin)
return frame
end
}
win:setframe(modifyframe[direction](frame))
end
-- fit inside screen
function fitframe(screen, frame)
frame.w = math.min(frame.w, screen.w - margin * 2)
frame.h = math.min(frame.h, screen.h - margin * (2 - 1 / 4))
return frame
end
-- center inside screen
function centerframe(screen, frame)
frame.x = screen.w / 2 - frame.w / 2 + screen.x
frame.y = screen.h / 2 - frame.h / 2 + screen.y
return frame
end
-- center given window
function centerwindow(win)
local screen = win:screen():frame_without_dock_or_menu()
local frame = win:frame()
win:setframe(centerframe(screen, frame))
end
-- fullscreen window with margin
function fullscreen(win)
local screen = win:screen():frame_without_dock_or_menu()
local frame = {
x = margin + screen.x,
y = margin + screen.y,
w = screen.w - margin * 2,
h = screen.h - margin * (2 - 1 / 4)
}
win:setframe(frame)
end
-- throw to next screen, center and fit
function nextscreen(win)
local screen = win:screen():next():frame_without_dock_or_menu()
local frame = win:frame()
frame.x = screen.x
frame.y = screen.y
win:setframe(centerframe(screen, fitframe(screen, frame)))
win:focus()
end
-- set window size and center
function centerwithsize(win, w, h)
local screen = win:screen():frame_without_dock_or_menu()
local frame = win:frame()
frame.w = w
frame.h = h
win:setframe(centerframe(screen, fitframe(screen, frame)))
end
-- save and restore window positions
local positions = {}
function winposition(win, option)
local id = win:application():bundleid()
local frame = win:frame()
if option == "save" then
notify.show("Hydra", "position for " .. id .. " saved", "", "")
positions[id] = frame
end
if option == "load" and positions[id] then
notify.show("Hydra", "position for " .. id .. " restored", "", "")
win:setframe(positions[id])
end
end
-- keyboard modifier for bindings
local mod1 = { "cmd", "ctrl" }
local mod2 = { "cmd", "ctrl", "alt" }
-- window modifiers
hotkey.bind(mod1, "c", function() centerwindow(window.focusedwindow()) end)
hotkey.bind(mod1, "z", function() fullscreen(window.focusedwindow()) end)
hotkey.bind(mod1, "tab", function() nextscreen(window.focusedwindow()) end)
-- push to edges and nudge
fnutils.each({ "up", "down", "left", "right" }, function(direction)
hotkey.bind(mod1, direction, function() push(window:focusedwindow(), direction) end)
hotkey.bind(mod2, direction, function() nudge(window:focusedwindow(), direction) end)
end)
-- save and restore window positions
hotkey.bind(mod1, "s", function() winposition(window.focusedwindow(), "save") end)
hotkey.bind(mod1, "r", function() winposition(window.focusedwindow(), "load") end)
-- reload hydra settings
hotkey.bind(mod1, "h", function() hydra:reload() end)
-- set window sizes
fnutils.each({
{ key = 1, w = 1400, h = 940 },
{ key = 2, w = 980, h = 920 },
{ key = 3, w = 800, h = 880 },
{ key = 4, w = 800, h = 740 },
{ key = 5, w = 760, h = 620 },
{ key = 6, w = 770, h = 470 }
}, function(object)
hotkey.bind(mod1, object.key, function()
centerwithsize(window.focusedwindow(), object.w, object.h)
end)
end)
-- launch and focus applications
fnutils.each({
{ key = "t", app = "Terminal" },
{ key = "s", app = "Safari" },
{ key = "f", app = "Finder" },
{ key = "n", app = "Notational Velocity" },
{ key = "p", app = "TaskPaper" },
{ key = "m", app = "MacVim" }
}, function(object)
hotkey.bind(mod2, object.key, function() application.launchorfocus(object.app) end)
end)
|
typo fix in hydra config
|
typo fix in hydra config
|
Lua
|
mit
|
szymonkaliski/Dotfiles,szymonkaliski/Dotfiles,szymonkaliski/Dotfiles,szymonkaliski/Dotfiles,szymonkaliski/Dotfiles
|
e7fd8e21d38d7ab848348eeda4a5729505fba368
|
framework/graphics/font.lua
|
framework/graphics/font.lua
|
--=========== Copyright © 2017, Planimeter, All rights reserved. =============--
--
-- Purpose:
--
--============================================================================--
require( "class" )
local FT = require( "freetype" )
local ffi = require( "ffi" )
local GL = require( "opengl" )
local ft = ffi.new( "FT_Library[1]" )
FT.FT_Init_FreeType( ft )
class( "framework.graphics.font" )
local font = framework.graphics.font
function font:font( filename, size )
size = size or 16
self.face = ffi.new( "FT_Face[1]" )
self.buffer, self.length = framework.filesystem.read( filename )
FT.FT_New_Memory_Face( ft[0], self.buffer, self.length, 0, self.face )
self.size = size
size = size * framework.window.getPixelScale()
FT.FT_Set_Pixel_Sizes( self.face[0], 0, size )
self.texture = ffi.new( "GLuint[1]" )
GL.glGenTextures( 1, self.texture )
GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_BASE_LEVEL, 0 )
GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAX_LEVEL, 0 )
local swizzleMask = ffi.new( "GLint[4]", { GL.GL_RED, GL.GL_RED, GL.GL_RED, GL.GL_RED } )
GL.glTexParameteriv( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_SWIZZLE_RGBA, swizzleMask )
setproxy( self )
end
function font:print( text, x, y, r, sx, sy, ox, oy, kx, ky )
local shader = framework.graphics.getShader()
local vertex = GL.glGetAttribLocation( shader, "vertex" )
local stride = 4 * ffi.sizeof( "GLfloat" )
local texcoord = GL.glGetAttribLocation( shader, "texcoord" )
local pointer = ffi.cast( "GLvoid *", 2 * ffi.sizeof( "GLfloat" ) )
GL.glBindBuffer( GL.GL_ARRAY_BUFFER, framework.graphics.defaultVBO[0] )
GL.glVertexAttribPointer( vertex, 2, GL.GL_FLOAT, 0, stride, nil )
GL.glEnableVertexAttribArray( texcoord )
GL.glVertexAttribPointer( texcoord, 2, GL.GL_FLOAT, 0, stride, pointer )
framework.graphics.updateTransformations()
GL.glBindTexture( GL.GL_TEXTURE_2D, self.texture[0] )
GL.glPixelStorei( GL.GL_UNPACK_ALIGNMENT, 1 )
local face = self.face[0]
for i = 1, #text do
local char = string.sub( text, i, i )
if ( FT.FT_Load_Char( face, string.byte( char ), 4 ) == 0 ) then
local g = face.glyph
local gx = x + g.bitmap_left
local gy = y + face.size.metrics.ascender / 64 - g.bitmap_top
local width = g.bitmap.width
local height = g.bitmap.rows
local vertices = {
-- vertex -- texcoord
gx, gy + height, 0.0, 1.0,
gx + width, gy + height, 1.0, 1.0,
gx, gy, 0.0, 0.0,
gx + width, gy + height, 1.0, 1.0,
gx + width, gy, 1.0, 0.0,
gx, gy, 0.0, 0.0
}
local pVertices = ffi.new( "GLfloat[?]", #vertices, vertices )
local size = ffi.sizeof( pVertices )
GL.glBufferData( GL.GL_ARRAY_BUFFER, size, pVertices, GL.GL_STREAM_DRAW )
GL.glTexImage2D(
GL.GL_TEXTURE_2D,
0,
GL.GL_RED,
g.bitmap.width,
g.bitmap.rows,
0,
GL.GL_RED,
GL.GL_UNSIGNED_BYTE,
g.bitmap.buffer
)
framework.graphics.drawArrays( GL.GL_TRIANGLES, 0, #vertices / 2 )
x = x + ( g.advance.x / 64 )
y = y + ( g.advance.y / 64 )
else
error( "Could not load character '" .. char .. "'", 3 )
end
end
GL.glPixelStorei( GL.GL_UNPACK_ALIGNMENT, 4 )
end
function font:__gc()
GL.glDeleteTextures( 1, self.texture )
FT.FT_Done_Face( self.face )
end
|
--=========== Copyright © 2017, Planimeter, All rights reserved. =============--
--
-- Purpose:
--
--============================================================================--
require( "class" )
local FT = require( "freetype" )
local ffi = require( "ffi" )
local GL = require( "opengl" )
local ft = ffi.new( "FT_Library[1]" )
FT.FT_Init_FreeType( ft )
class( "framework.graphics.font" )
local font = framework.graphics.font
function font:font( filename, size )
size = size or 16
self.face = ffi.new( "FT_Face[1]" )
self.buffer, self.length = framework.filesystem.read( filename )
FT.FT_New_Memory_Face( ft[0], self.buffer, self.length, 0, self.face )
self.size = size
size = size * framework.window.getPixelScale()
FT.FT_Set_Pixel_Sizes( self.face[0], 0, size )
self.texture = ffi.new( "GLuint[1]" )
GL.glGenTextures( 1, self.texture )
GL.glBindTexture( GL.GL_TEXTURE_2D, self.texture[0] )
GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_BASE_LEVEL, 0 )
GL.glTexParameteri( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAX_LEVEL, 0 )
local swizzleMask = ffi.new( "GLint[4]", { GL.GL_RED, GL.GL_RED, GL.GL_RED, GL.GL_RED } )
GL.glTexParameteriv( GL.GL_TEXTURE_2D, GL.GL_TEXTURE_SWIZZLE_RGBA, swizzleMask )
setproxy( self )
end
function font:print( text, x, y, r, sx, sy, ox, oy, kx, ky )
local shader = framework.graphics.getShader()
local vertex = GL.glGetAttribLocation( shader, "vertex" )
local stride = 4 * ffi.sizeof( "GLfloat" )
local texcoord = GL.glGetAttribLocation( shader, "texcoord" )
local pointer = ffi.cast( "GLvoid *", 2 * ffi.sizeof( "GLfloat" ) )
GL.glBindBuffer( GL.GL_ARRAY_BUFFER, framework.graphics.defaultVBO[0] )
GL.glVertexAttribPointer( vertex, 2, GL.GL_FLOAT, 0, stride, nil )
GL.glEnableVertexAttribArray( texcoord )
GL.glVertexAttribPointer( texcoord, 2, GL.GL_FLOAT, 0, stride, pointer )
framework.graphics.updateTransformations()
GL.glBindTexture( GL.GL_TEXTURE_2D, self.texture[0] )
GL.glPixelStorei( GL.GL_UNPACK_ALIGNMENT, 1 )
local face = self.face[0]
for i = 1, #text do
local char = string.sub( text, i, i )
if ( FT.FT_Load_Char( face, string.byte( char ), 4 ) == 0 ) then
local g = face.glyph
local gx = x + g.bitmap_left
local gy = y + face.size.metrics.ascender / 64 - g.bitmap_top
local width = g.bitmap.width
local height = g.bitmap.rows
local vertices = {
-- vertex -- texcoord
gx, gy + height, 0.0, 1.0,
gx + width, gy + height, 1.0, 1.0,
gx, gy, 0.0, 0.0,
gx + width, gy + height, 1.0, 1.0,
gx + width, gy, 1.0, 0.0,
gx, gy, 0.0, 0.0
}
local pVertices = ffi.new( "GLfloat[?]", #vertices, vertices )
local size = ffi.sizeof( pVertices )
GL.glBufferData( GL.GL_ARRAY_BUFFER, size, pVertices, GL.GL_STREAM_DRAW )
GL.glTexImage2D(
GL.GL_TEXTURE_2D,
0,
GL.GL_RED,
g.bitmap.width,
g.bitmap.rows,
0,
GL.GL_RED,
GL.GL_UNSIGNED_BYTE,
g.bitmap.buffer
)
framework.graphics.drawArrays( GL.GL_TRIANGLES, 0, #vertices / 2 )
x = x + ( g.advance.x / 64 )
y = y + ( g.advance.y / 64 )
else
error( "Could not load character '" .. char .. "'", 3 )
end
end
GL.glPixelStorei( GL.GL_UNPACK_ALIGNMENT, 4 )
end
function font:__gc()
GL.glDeleteTextures( 1, self.texture )
FT.FT_Done_Face( self.face )
end
|
Fix missing glBindTexture call in font()
|
Fix missing glBindTexture call in font()
|
Lua
|
mit
|
Planimeter/lgameframework,Planimeter/lgameframework,Planimeter/lgameframework
|
1a6d57345ec3a282d8679a3f7c2a31bb13b35752
|
Engine/sandbox.lua
|
Engine/sandbox.lua
|
--A function that creates new sandboxed global environment.
local basexx = require("Engine.basexx")
local bit = require("bit")
local _LuaBCHeader = string.char(0x1B).."LJ"
return function(parent)
local GLOB = {
assert=assert,
error=error,
ipairs=ipairs,
pairs=pairs,
next=next,
pcall=pcall,
select=select,
tonumber=tonumber,
tostring=tostring,
type=type,
unpack=unpack,
_VERSION=_VERSION,
xpcall=xpcall,
setmetatable=setmetatable,
getmetatable=getmetatable,
rawget = rawget,
rawset = rawset,
rawequal = rawequal,
string={
byte=string.byte,
char=string.char,
find=string.find,
format=string.format,
gmatch=string.gmatch,
gsub=string.gsub,
len=string.len,
lower=string.lower,
match=string.match,
rep=string.rep,
reverse=string.reverse,
sub=string.sub,
upper=string.upper
},
table={
insert=table.insert,
maxn=table.maxn,
remove=table.remove,
sort=table.sort,
concat=table.concat
},
math={
abs=math.abs,
acos=math.acos,
asin=math.asin,
atan=math.atan,
atan2=math.atan2,
ceil=math.ceil,
cos=math.cos,
cosh=math.cosh,
deg=math.deg,
exp=math.exp,
floor=math.floor,
fmod=math.fmod,
frexp=math.frexp,
huge=math.huge,
ldexp=math.ldexp,
log=math.log,
log10=math.log10,
max=math.max,
min=math.min,
modf=math.modf,
pi=math.pi,
pow=math.pow,
rad=math.rad,
random=love.math.random, --Replaced with love.math versions
randomseed=love.math.setRandomSeed,
sin=math.sin,
sinh=math.sinh,
sqrt=math.sqrt,
tan=math.tan,
tanh=math.tanh,
noise = love.math.noise, --LOVE releated apis
b64enc = basexx.to_base64, --Will be replaced by love.math ones in love 0.11
b64dec = basexx.from_base64,
hexenc = basexx.to_hex,
hexdec = basexx.from_hex,
compress = function(...) return love.math.compress(...):getString() end,
decompress = love.math.decompress,
isConvex = love.math.isConvex,
triangulate = love.math.triangulate,
randomNormal = love.math.randomNormal
},
coroutine={
create = coroutine.create,
resume = coroutine.resume,
yield = coroutine.yield,
status = coroutine.status
},
os={
time=os.time,
clock=os.clock,
date=os.date
},
bit={
cast=bit.cast,
bnot=bit.bnot,
band=bit.band,
bor=bit.bor,
bxor=bit.bxor,
lshift=bit.lshift,
rshift=bit.rshift,
arshift=bit.arshift,
tobit=bit.tobit,
tohex=bit.tohex,
rol=bit.rol,
ror=bit.ror,
bswap=bit.swap
}
}
GLOB.getfenv = function(f)
if type(f) ~= "function" then return error("bad argument #1 to 'getfenv' (function expected, got "..type(f)) end
local ok, env = pcall(getfenv,f)
if not ok then return error(env) end
if env.love == love then env = {} end --Protection
return env
end
GLOB.setfenv = function(f,env)
if type(f) ~= "function" then return error("bad argument #1 to 'setfenv' (function expected, got "..type(f)) end
if type(env) ~= "table" then return error("bad argument #2 to 'setfenv' (table expected, got "..type(env)) end
local oldenv = getfenv(f)
if oldenv.love == love then return end --Trying to make a crash ! evil.
local ok, err = pcall(setfenv,f,env)
if not ok then return error(err) end
end
GLOB.loadstring = function(data,chunkname)
if data:sub(1,3) == _LuaBCHeader then return error("LOADING BYTECODE IS NOT ALLOWED, YOU HACKER !") end
if chunkname and type(chunkname) ~= "string" then return error("Chunk name must be a string or a nil, provided: "..type(chunkname)) end
local chunk, err = loadstring(data,chunkname)
if not chunk then return nil, err end
setfenv(chunk,GLOB)
return chunk
end
GLOB.load = function(iter,chunkname)
if type(iter) ~= "string" then return error("Iterator must be a function, provided: "..type(iter)) end
if chunkname and type(chunkname) ~= "string" then return error("Chunk name must be a string or a nil, provided: "..type(chunkname)) end
local firstline = iter()
if firstline:sub(1,3) == _LuaBCHeader then return error("LOADING BYTECODE IS NOT ALLOWED, YOU HACKER !") end
local newiter = function()
if firstline then
local l = firstline
firstline = nil
return l
end
return iter()
end
return load(newiter,chunkname)
end
GLOB.coroutine.sethook = function(co,...)
--DEPRICATED--
--Coroutine hooks are useless because of LuaJIT
--[[if type(co) ~= "thread" then return error("bad argument #1 (thread expected, got "..type(co)..")") end
local ok, err = pcall(debug.sethook,co,...)
if not ok then return error(err) end
return err]]
end
GLOB.coroutine.running = function()
local curco = coroutine.running()
if parent and parent.co and curco == parent.co then return end
return curco
end
GLOB._G=GLOB --Mirror Mirror
return GLOB
end
|
--A function that creates new sandboxed global environment.
local basexx = require("Engine.basexx")
local bit = require("bit")
local _LuaBCHeader = string.char(0x1B).."LJ"
return function(parent)
local GLOB = {
assert=assert,
error=error,
ipairs=ipairs,
pairs=pairs,
next=next,
pcall=pcall,
select=select,
tonumber=tonumber,
tostring=tostring,
type=type,
unpack=unpack,
_VERSION=_VERSION,
xpcall=xpcall,
setmetatable=setmetatable,
getmetatable=getmetatable,
rawget = rawget,
rawset = rawset,
rawequal = rawequal,
string={
byte=string.byte,
char=string.char,
find=string.find,
format=string.format,
gmatch=string.gmatch,
gsub=string.gsub,
len=string.len,
lower=string.lower,
match=string.match,
rep=string.rep,
reverse=string.reverse,
sub=string.sub,
upper=string.upper
},
table={
insert=table.insert,
maxn=table.maxn,
remove=table.remove,
sort=table.sort,
concat=table.concat
},
math={
abs=math.abs,
acos=math.acos,
asin=math.asin,
atan=math.atan,
atan2=math.atan2,
ceil=math.ceil,
cos=math.cos,
cosh=math.cosh,
deg=math.deg,
exp=math.exp,
floor=math.floor,
fmod=math.fmod,
frexp=math.frexp,
huge=math.huge,
ldexp=math.ldexp,
log=math.log,
log10=math.log10,
max=math.max,
min=math.min,
modf=math.modf,
pi=math.pi,
pow=math.pow,
rad=math.rad,
random=love.math.random, --Replaced with love.math versions
randomseed=function(s) if s then love.math.setRandomSeed(s) else return love.math.getRandomSeed() end end,
sin=math.sin,
sinh=math.sinh,
sqrt=math.sqrt,
tan=math.tan,
tanh=math.tanh,
noise = love.math.noise, --LOVE releated apis
b64enc = basexx.to_base64, --Will be replaced by love.math ones in love 0.11
b64dec = basexx.from_base64,
hexenc = basexx.to_hex,
hexdec = basexx.from_hex,
compress = function(...) return love.math.compress(...):getString() end,
decompress = love.math.decompress,
isConvex = love.math.isConvex,
triangulate = love.math.triangulate,
randomNormal = love.math.randomNormal
},
coroutine={
create = coroutine.create,
resume = coroutine.resume,
yield = coroutine.yield,
status = coroutine.status
},
os={
time=os.time,
clock=os.clock,
date=os.date
},
bit={
cast=bit.cast,
bnot=bit.bnot,
band=bit.band,
bor=bit.bor,
bxor=bit.bxor,
lshift=bit.lshift,
rshift=bit.rshift,
arshift=bit.arshift,
tobit=bit.tobit,
tohex=bit.tohex,
rol=bit.rol,
ror=bit.ror,
bswap=bit.swap
}
}
GLOB.getfenv = function(f)
if type(f) ~= "function" then return error("bad argument #1 to 'getfenv' (function expected, got "..type(f)) end
local ok, env = pcall(getfenv,f)
if not ok then return error(env) end
if env.love == love then env = {} end --Protection
return env
end
GLOB.setfenv = function(f,env)
if type(f) ~= "function" then return error("bad argument #1 to 'setfenv' (function expected, got "..type(f)) end
if type(env) ~= "table" then return error("bad argument #2 to 'setfenv' (table expected, got "..type(env)) end
local oldenv = getfenv(f)
if oldenv.love == love then return end --Trying to make a crash ! evil.
local ok, err = pcall(setfenv,f,env)
if not ok then return error(err) end
end
GLOB.loadstring = function(data,chunkname)
if data:sub(1,3) == _LuaBCHeader then return error("LOADING BYTECODE IS NOT ALLOWED, YOU HACKER !") end
if chunkname and type(chunkname) ~= "string" then return error("Chunk name must be a string or a nil, provided: "..type(chunkname)) end
local chunk, err = loadstring(data,chunkname)
if not chunk then return nil, err end
setfenv(chunk,GLOB)
return chunk
end
GLOB.load = function(iter,chunkname)
if type(iter) ~= "string" then return error("Iterator must be a function, provided: "..type(iter)) end
if chunkname and type(chunkname) ~= "string" then return error("Chunk name must be a string or a nil, provided: "..type(chunkname)) end
local firstline = iter()
if firstline:sub(1,3) == _LuaBCHeader then return error("LOADING BYTECODE IS NOT ALLOWED, YOU HACKER !") end
local newiter = function()
if firstline then
local l = firstline
firstline = nil
return l
end
return iter()
end
return load(newiter,chunkname)
end
GLOB.coroutine.sethook = function(co,...)
--DEPRICATED--
--Coroutine hooks are useless because of LuaJIT
--[[if type(co) ~= "thread" then return error("bad argument #1 (thread expected, got "..type(co)..")") end
local ok, err = pcall(debug.sethook,co,...)
if not ok then return error(err) end
return err]]
end
GLOB.coroutine.running = function()
local curco = coroutine.running()
if parent and parent.co and curco == parent.co then return end
return curco
end
GLOB._G=GLOB --Mirror Mirror
return GLOB
end
|
Fix math.randomSeed not returning the seed when no arguments are passed.
|
Fix math.randomSeed not returning the seed when no arguments are passed.
Former-commit-id: de2353b7ef5fc731ae06a8587027f4a2f1d7a982
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
b59c14c350cc8b0dd7147d7faf07c5bb10ec22b9
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/i2c/io-expander-sx1059.lua
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/i2c/io-expander-sx1059.lua
|
--This is an example that uses the SX1509 I/O Expander on the I2C Bus on EIO4(SCL) and EIO5(SDA)
--[[
User RAM registers- change these in another program (LabVIEW, Python, C++ and more) to change the state of pins
To understand this script, it is very important to be familiar with the datasheet
This script uses only a small amount of features available on the slave devices.
Modification of the script is needed to utilize the keypad engine and PWM functionalities of the slave device.
chanAdata = 46080 (USER_RAM0_I32)
chanBdata = 46082 (USER_RAM1_I32)
chanAdir = 46084 (USER_RAM2_I32)
chanBdir = 46086 (USER_RAM3_I32)
chanAinput = 46088 (USER_RAM4_I32)
chanBinput = 46090 (USER_RAM5_I32)
chanApup = 46092 (USER_RAM6_I32)
chanBpup = 46094 (USER_RAM7_I32)
]]--
fwver = MB.R(60004, 3)
devType = MB.R(60000, 3)
if (fwver < 1.0224 and devType == 7) or (fwver < 0.2037 and devType == 4) then
print("This lua script requires a higher firmware version (T7 Requires 1.0224 or higher, T4 requires 0.2037 or higher). Program Stopping")
MB.W(6000, 1, 0)
end
SLAVE_ADDRESS = 0x3E
I2C.config(13, 12, 65516, 0, SLAVE_ADDRESS, 0)--configure the I2C Bus
addrs = I2C.search(0, 127)
addrsLen = table.getn(addrs)
found = 0
for i=1, addrsLen do--verify that the target device was found
if addrs[i] == SLAVE_ADDRESS then
print("I2C Slave Detected")
found = 1
break
end
end
if found == 0 then
print("No I2C Slave detected, program stopping")
MB.W(6000, 1, 0)
end
--Channel A is 0-7, Channel B is 8-15
chanAdir = MB.R(46084, 2)--1 = output, 0 = input
chanBdir = MB.R(46086, 2)
chanApup = MB.R(46092, 2)--0 = pullup enabled, 1 = disabled
chanBpup = MB.R(46094, 2)
--config clock and debounce
I2C.write({0x1E, 0x4F})--config clock
I2C.write({0x1F, 0x70})--RegMisc
--config channel A inputs/outputs
I2C.write({0x01, chanAdir})--input buffer disable
I2C.write({0x07, chanApup})--pull up disable
I2C.write({0x0B, chanAdir})--open drain
I2C.write({0x0F, 0xFF-chanAdir})--output
I2C.write({0x11, 0xFF})--all LED off (initially)
I2C.write({0x21, 0x00})--disable LED Driver for ALL(which diables PWM and fade)
--config channel B inputs/outputs
I2C.write({0x01-1, chanBdir})
I2C.write({0x07-1, chanBpup})
I2C.write({0x0B-1, chanBdir})
I2C.write({0x0F-1, 0xFF-chanBdir})
I2C.write({0x11-1, 0xFF})
I2C.write({0x21-1, 0x00})
LJ.IntervalConfig(0, 10)--check every 10ms
while true do
if LJ.CheckInterval(0) then
if MB.R(46080, 2) ~= data then
--Read Inputs
I2C.write({0x11})
chanAinput = I2C.read(2)
I2C.write({0x11-1})
chanBinput = I2C.read(2)
print(chanBinput[1])
MB.W(46088, 2, chanAinput)
MB.W(46090, 2, chanBinput)
--Write Outputs
chanAdata = MB.R(46080, 2)
I2C.write({0x11, chanAdata})--all LEDs written depending on User RAM Register
chanBdata = MB.R(46082, 2)
I2C.write({0x11-1, chanBdata})--all LEDs written depending on User RAM Register
end
end
end
|
--[[
Name: io-expander-sx1059.lua
Desc: This is an example that uses the SX1509 I/O Expander on the I2C Bus
on EIO4(SCL) and EIO5(SDA)
Note: User RAM registers- change these in another program (LabVIEW,
Python, C++ and more) to change the state of pins. To understand this
script, it is very important to be familiar with the datasheet. This
script uses only a small amount of features available on the slave
devices. Modification of the script is needed to utilize the keypad
engine and PWM functionalities of the slave device.
datachana = 46080 (USER_RAM0_I32)
datachanb = 46082 (USER_RAM1_I32)
dirchana = 46084 (USER_RAM2_I32)
dirchanb = 46086 (USER_RAM3_I32)
inchana = 46088 (USER_RAM4_I32)
inchanb = 46090 (USER_RAM5_I32)
pupchana = 46092 (USER_RAM6_I32)
pupchanb = 46094 (USER_RAM7_I32)
--]]
SLAVE_ADDRESS = 0x3E
-- Use EIO3 for power
MB.writeName("EIO3", 1)
-- Configure the I2C Bus
I2C.config(13, 12, 65516, 0, SLAVE_ADDRESS, 0)
local addrs = I2C.search(0, 127)
local addrslen = table.getn(addrs)
local found = 0
-- Verify that the target device was found
for i=1, addrslen do
if addrs[i] == SLAVE_ADDRESS then
print("I2C Slave Detected")
found = 1
break
end
end
if found == 0 then
print("No I2C Slave detected, program stopping")
MB.writeName("LUA_RUN", 0)
end
-- Channel A is 0-7, Channel B is 8-15
-- 1 = output, 0 = input
local dirchana = MB.readName("USER_RAM2_I32")
local dirchanb = MB.readName("USER_RAM3_I32")
-- 0 = pullup enabled, 1 = disabled
local pupchana = MB.readName("USER_RAM6_I32")
local pupchanb = MB.readName("USER_RAM7_I32")
-- Config clock
I2C.write({0x1E, 0x4F})
-- RegMisc
I2C.write({0x1F, 0x70})
-- Input buffer disable
I2C.write({0x01, dirchana})
-- Pull up disable
I2C.write({0x07, pupchana})
-- Open drain
I2C.write({0x0B, dirchana})
-- Output
I2C.write({0x0F, 0xFF-dirchana})
-- All LED off (initially)
I2C.write({0x11, 0xFF})
-- Disable LED Driver for ALL(which disables PWM and fade)
I2C.write({0x21, 0x00})
-- Config channel B inputs/outputs
I2C.write({0x01-1, dirchanb})
I2C.write({0x07-1, pupchanb})
I2C.write({0x0B-1, dirchanb})
I2C.write({0x0F-1, 0xFF-dirchanb})
I2C.write({0x11-1, 0xFF})
I2C.write({0x21-1, 0x00})
-- Configure a 10ms interval
LJ.IntervalConfig(0, 10)
while true do
-- If an interval is done
if LJ.CheckInterval(0) then
if MB.readName("USER_RAM0_I32") ~= nil then
-- Read Inputs
I2C.write({0x11})
local inchana = I2C.read(2)
I2C.write({0x11-1})
local inchanb = I2C.read(2)
print(inchanb[1])
MB.writeName("USER_RAM4_I32", inchana)
MB.writeName("USER_RAM5_I32", inchanb)
--Write Outputs
local datachana = MB.readName("USER_RAM0_I32")
-- All LEDs written depending on User RAM Register
I2C.write({0x11, datachana})
local datachanb = MB.readName("USER_RAM1_I32")
I2C.write({0x11-1, datachanb})
end
end
end
|
Fixed the formatting of the io-expander example
|
Fixed the formatting of the io-expander example
|
Lua
|
mit
|
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
|
21d9cc420396d57d59603220aba193936342ac52
|
mods/tsm_pyramids/room.lua
|
mods/tsm_pyramids/room.lua
|
pyramids.saved_chests = {}
pyramids.timer = 0
pyramids.max_time = 30*60
local room = {"a","a","a","a","a","a","a","a","a",
"a","c","a","c","a","c","a","c","a",
"a","s","a","s","a","s","a","s","a",
"a","a","a","a","a","a","a","a","a",
"a","a","a","a","a","a","a","a","a",
"a","a","a","a","a","a","a","a","a",
"a","s","a","s","a","s","a","s","a",
"a","c","a","c","a","c","a","c","a",
"a","a","a","a","a","a","a","a","a"}
local trap = {"b","b","b","b","b","b","b","b","b",
"l","b","l","b","l","b","l","b","b",
"l","b","l","b","l","b","l","b","b",
"l","b","l","l","l","b","l","l","b",
"l","l","b","l","b","l","l","b","b",
"l","b","l","l","l","l","l","l","b",
"l","b","l","b","l","b","l","b","b",
"l","b","l","b","l","b","l","b","b",
"b","b","b","b","b","b","b","b","b"}
local code = {}
code["s"] = "sandstone"
code["eye"] = "deco_stone1"
code["men"] = "deco_stone2"
code["sun"] = "deco_stone3"
code["c"] = "chest"
code["b"] = "sandstonebrick"
code["a"] = "air"
code["l"] = "lava_source"
code["t"] = "trap"
function loadchests()
local file = io.open(minetest.get_worldpath().."/pyramids_chests.txt","r")
if file then
local saved_chests = minetest.deserialize(file:read())
io.close(file)
if saved_chests and type(saved_chests) == "table" then
minetest.log("action","[tsm_pyramids] Chest loaded")
return saved_chests
else
minetest.log("error","[tsm_pyramids] Loading Chest failed")
end
end
return {}
end
function savechests()
local file = io.open(minetest.get_worldpath().."/pyramids_chests.txt","w")
if not file then return end -- should not happen
file:write(minetest.serialize(pyramids.saved_chests))
io.close(file)
minetest.log("action","[tsm_pyramids] Chests saved")
end
pyramids.saved_chests = loadchests()
minetest.register_on_shutdown(function()
savechests()
end)
minetest.register_globalstep(function(dtime)
pyramids.timer = pyramids.timer + dtime
if pyramids.timer < pyramids.max_time then return end
pyramids.timer = 0
for _,k in ipairs(pyramids.saved_chests) do
pyramids.fill_chest(k)
end
minetest.log("action","[tsm_pyramids] Chests reloaded")
end)
local function replace(str,iy)
local out = "default:"
if iy < 4 and str == "c" then str = "a" end
if iy == 0 and str == "s" then out = "tsm_pyramids:" str = "sun" end
if iy == 3 and str == "s" then out = "tsm_pyramids:" str = "men" end
if str == "a" then out = "" end
if str == "c" or str == "s" or str == "b" then out = "maptools:" end
return out..code[str]
end
local function replace2(str,iy)
local out = "default:"
if iy == 0 and str == "l" then out = "tsm_pyramids:" str = "t"
elseif iy < 3 and str == "l" then str = "a" end
if str == "a" then out = "" end
return out..code[str]
end
function pyramids.make_room(pos)
local loch = {x=pos.x+7,y=pos.y+5, z=pos.z+7}
for iy=0,4,1 do
for ix=0,8,1 do
for iz=0,8,1 do
local n_str = room[tonumber(ix*9+iz+1)]
local p2 = 0
if n_str == "c" then
if ix < 3 then p2 = 1 else p2 = 3 end
pyramids.fill_chest({x=loch.x+ix,y=loch.y-iy,z=loch.z+iz})
end
local node_name = replace(n_str,iy)
minetest.set_node({x=loch.x+ix,y=loch.y-iy,z=loch.z+iz}, {name=node_name, param2=p2})
if node_name == "maptools:chest" then
table.insert(pyramids.saved_chests,1,{x=loch.x+ix,y=loch.y-iy,z=loch.z+iz})
end
end
end
end
end
function pyramids.make_traps(pos)
local loch = {x=pos.x+7,y=pos.y, z=pos.z+7}
for iy=0,4,1 do
for ix=0,8,1 do
for iz=0,8,1 do
local n_str = trap[tonumber(ix*9+iz+1)]
local p2 = 0
minetest.set_node({x=loch.x+ix,y=loch.y-iy,z=loch.z+iz}, {name=replace2(n_str,iy), param2=p2})
end
end
end
end
|
pyramids.saved_chests = {}
pyramids.timer = 0
pyramids.max_time = 30*60
local room = {"a","a","a","a","a","a","a","a","a",
"a","c","a","c","a","c","a","c","a",
"a","s","a","s","a","s","a","s","a",
"a","a","a","a","a","a","a","a","a",
"a","a","a","a","a","a","a","a","a",
"a","a","a","a","a","a","a","a","a",
"a","s","a","s","a","s","a","s","a",
"a","c","a","c","a","c","a","c","a",
"a","a","a","a","a","a","a","a","a"}
local trap = {"b","b","b","b","b","b","b","b","b",
"l","b","l","b","l","b","l","b","b",
"l","b","l","b","l","b","l","b","b",
"l","b","l","l","l","b","l","l","b",
"l","l","b","l","b","l","l","b","b",
"l","b","l","l","l","l","l","l","b",
"l","b","l","b","l","b","l","b","b",
"l","b","l","b","l","b","l","b","b",
"b","b","b","b","b","b","b","b","b"}
local code = {}
code["s"] = "sandstone"
code["eye"] = "deco_stone1"
code["men"] = "deco_stone2"
code["sun"] = "deco_stone3"
code["c"] = "chest"
code["b"] = "sandstonebrick"
code["a"] = "air"
code["l"] = "lava_source"
code["t"] = "trap"
function loadchests()
local file = io.open(minetest.get_worldpath().."/pyramids_chests.txt","r")
if file then
local saved_chests = minetest.deserialize(file:read())
io.close(file)
if saved_chests and type(saved_chests) == "table" then
minetest.log("action","[tsm_pyramids] Chest loaded")
return saved_chests
else
minetest.log("error","[tsm_pyramids] Loading Chest failed")
end
end
return {}
end
function savechests()
local file = io.open(minetest.get_worldpath().."/pyramids_chests.txt","w")
if not file then return end -- should not happen
file:write(minetest.serialize(pyramids.saved_chests))
io.close(file)
minetest.log("action","[tsm_pyramids] Chests saved")
end
pyramids.saved_chests = loadchests()
minetest.register_on_shutdown(function()
savechests()
end)
minetest.register_globalstep(function(dtime)
pyramids.timer = pyramids.timer + dtime
if pyramids.timer < pyramids.max_time then return end
pyramids.timer = 0
-- It might happen that chests are not loaded
if pyramids.saved_chests then
for _,k in ipairs(pyramids.saved_chests) do
pyramids.fill_chest(k)
end
else
pyramids.saved_chests = loadchests() or {}
end
minetest.log("action","[tsm_pyramids] Chests reloaded")
end)
local function replace(str,iy)
local out = "default:"
if iy < 4 and str == "c" then str = "a" end
if iy == 0 and str == "s" then out = "tsm_pyramids:" str = "sun" end
if iy == 3 and str == "s" then out = "tsm_pyramids:" str = "men" end
if str == "a" then out = "" end
if str == "c" or str == "s" or str == "b" then out = "maptools:" end
return out..code[str]
end
local function replace2(str,iy)
local out = "default:"
if iy == 0 and str == "l" then out = "tsm_pyramids:" str = "t"
elseif iy < 3 and str == "l" then str = "a" end
if str == "a" then out = "" end
return out..code[str]
end
function pyramids.make_room(pos)
local loch = {x=pos.x+7,y=pos.y+5, z=pos.z+7}
for iy=0,4,1 do
for ix=0,8,1 do
for iz=0,8,1 do
local n_str = room[tonumber(ix*9+iz+1)]
local p2 = 0
if n_str == "c" then
if ix < 3 then p2 = 1 else p2 = 3 end
pyramids.fill_chest({x=loch.x+ix,y=loch.y-iy,z=loch.z+iz})
end
local node_name = replace(n_str,iy)
minetest.set_node({x=loch.x+ix,y=loch.y-iy,z=loch.z+iz}, {name=node_name, param2=p2})
if node_name == "maptools:chest" then
table.insert(pyramids.saved_chests,1,{x=loch.x+ix,y=loch.y-iy,z=loch.z+iz})
end
end
end
end
end
function pyramids.make_traps(pos)
local loch = {x=pos.x+7,y=pos.y, z=pos.z+7}
for iy=0,4,1 do
for ix=0,8,1 do
for iz=0,8,1 do
local n_str = trap[tonumber(ix*9+iz+1)]
local p2 = 0
minetest.set_node({x=loch.x+ix,y=loch.y-iy,z=loch.z+iz}, {name=replace2(n_str,iy), param2=p2})
end
end
end
end
|
Fix strange crash with tsm_pyramids - Solves #207
|
Fix strange crash with tsm_pyramids
- Solves #207
|
Lua
|
unlicense
|
MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun,sys4-fr/server-minetestforfun,paly2/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,crabman77/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server
|
af3cd6e9128919c74e2436ed222d7dfdf692e561
|
generator/types.lua
|
generator/types.lua
|
#!/usr/bin/lua
--[[
Copyright (c) 2007-2009 Mauro Iazzi
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
--]]
local base_types = (...) or {}
local number_type = function(d) return {
get = function(j)
return 'lua_tonumber(L, '..tostring(j)..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushnumber(L, '..tostring(j)..')', 1
end,
test = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lqtL_isnumber(L, '..tostring(j)..')', 1
end,
onstack = 'number,',
defect = d,
} end
local integer_type = function(d) return {
get = function(j)
return 'lua_tointeger(L, '..tostring(j)..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushinteger(L, '..tostring(j)..')', 1
end,
test = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lqtL_isinteger(L, '..tostring(j)..')', 1
end,
onstack = 'integer,',
defect = d,
} end
local bool_type = function(d) return {
get = function(j)
return 'lua_toboolean(L, '..tostring(j)..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushboolean(L, '..tostring(j)..')', 1
end,
test = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lqtL_isboolean(L, '..tostring(j)..')', 1
end,
onstack = 'boolean,',
defect = d,
} end
base_types['char const*'] = {
get = function(j)
return 'lua_tostring(L, '..tostring(j)..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushstring(L, '..tostring(j)..')', 1
end,
test = function(j)
return 'lqtL_isstring(L, '..tostring(j)..')', 1
end,
onstack = 'string,',
}
base_types['char'] = integer_type(3)
base_types['unsigned char'] = integer_type(3)
base_types['int'] = integer_type(1)
base_types['unsigned'] = integer_type(1)
base_types['unsigned int'] = integer_type(1)
base_types['short'] = integer_type(2)
base_types['short int'] = integer_type(2)
base_types['unsigned short'] = integer_type(2)
base_types['unsigned short int'] = integer_type(2)
base_types['short unsigned int'] = integer_type(2)
base_types['long'] = integer_type(0)
base_types['unsigned long'] = integer_type(0)
base_types['long int'] = integer_type(0)
base_types['unsigned long int'] = integer_type(0)
base_types['long unsigned int'] = integer_type(0)
base_types['long long'] = integer_type(0)
base_types['unsigned long long'] = integer_type(0)
base_types['long long int'] = integer_type(0)
base_types['unsigned long long int'] = integer_type(0)
base_types['float'] = number_type(1)
base_types['double'] = number_type(0)
base_types['double const&'] = number_type(1)
base_types['bool'] = bool_type()
---[[
base_types['bool*'] = {
get = function(j)
return 'lqtL_toboolref(L, '..j..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushboolean(L, *'..tostring(j)..')', 1
end,
test = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lqtL_isboolean(L, '..tostring(j)..')', 1
end,
onstack = 'boolean,',
}
base_types['int&'] = {
get = function(j)
return '*lqtL_tointref(L, '..j..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushinteger(L, '..tostring(j)..')', 1
end,
test = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lqtL_isinteger(L, '..tostring(j)..')', 1
end,
onstack = 'integer,',
}
base_types['int*'] = {
get = function(j)
return 'lqtL_tointref(L, '..j..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushinteger(L, *'..tostring(j)..')', 1
end,
test = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lqtL_isinteger(L, '..tostring(j)..')', 1
end,
onstack = 'integer,',
}
base_types['char**'] = {
get = function(j)
return 'lqtL_toarguments(L, '..tostring(j)..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lqtL_pusharguments(L, '..tostring(j)..')', 1
end,
test = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_istable(L, '..tostring(j)..')', 1
end,
onstack = 'table,',
}
--]]
base_types['std::string const&'] = {
get = function(i)
return 'std::string(lua_tostring(L, '..i..'), lua_objlen(L, '..i..'))', 1
end,
push = function(i)
return 'lua_pushlstring(L, '..i..'.c_str(), '..i..'.size())', 1
end,
test = function(i)
return 'lua_isstring(L, '..i..')', 1
end,
onstack = 'string,',
}
base_types['std::string'] = base_types['std::string const&']
return base_types
|
#!/usr/bin/lua
--[[
Copyright (c) 2007-2009 Mauro Iazzi
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
--]]
local base_types = (...) or {}
local number_type = function(d) return {
get = function(j)
return 'lua_tonumber(L, '..tostring(j)..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushnumber(L, '..tostring(j)..')', 1
end,
test = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lqtL_isnumber(L, '..tostring(j)..')', 1
end,
onstack = 'number,',
defect = d,
} end
local integer_type = function(d) return {
get = function(j)
return 'lua_tointeger(L, '..tostring(j)..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushinteger(L, '..tostring(j)..')', 1
end,
test = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lqtL_isinteger(L, '..tostring(j)..')', 1
end,
onstack = 'integer,',
defect = d,
} end
local bool_type = function(d) return {
get = function(j)
return 'lua_toboolean(L, '..tostring(j)..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushboolean(L, '..tostring(j)..')', 1
end,
test = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lqtL_isboolean(L, '..tostring(j)..')', 1
end,
onstack = 'boolean,',
defect = d,
} end
base_types['char const*'] = {
get = function(j)
return 'lua_tostring(L, '..tostring(j)..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushstring(L, '..tostring(j)..')', 1
end,
test = function(j)
return 'lqtL_isstring(L, '..tostring(j)..')', 1
end,
onstack = 'string,',
}
base_types['char'] = integer_type(3)
base_types['unsigned char'] = integer_type(3)
base_types['int'] = integer_type(1)
base_types['unsigned'] = integer_type(1)
base_types['unsigned int'] = integer_type(1)
base_types['short'] = integer_type(2)
base_types['short int'] = integer_type(2)
base_types['unsigned short'] = integer_type(2)
base_types['unsigned short int'] = integer_type(2)
base_types['short unsigned int'] = integer_type(2)
base_types['long'] = integer_type(0)
base_types['unsigned long'] = integer_type(0)
base_types['long int'] = integer_type(0)
base_types['unsigned long int'] = integer_type(0)
base_types['long unsigned int'] = integer_type(0)
base_types['long long'] = integer_type(0)
base_types['__int64'] = integer_type(0)
base_types['unsigned long long'] = integer_type(0)
base_types['long long int'] = integer_type(0)
base_types['unsigned long long int'] = integer_type(0)
base_types['float'] = number_type(1)
base_types['double'] = number_type(0)
base_types['double const&'] = number_type(1)
base_types['bool'] = bool_type()
---[[
base_types['bool*'] = {
get = function(j)
return 'lqtL_toboolref(L, '..j..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushboolean(L, *'..tostring(j)..')', 1
end,
test = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lqtL_isboolean(L, '..tostring(j)..')', 1
end,
onstack = 'boolean,',
}
base_types['int&'] = {
get = function(j)
return '*lqtL_tointref(L, '..j..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushinteger(L, '..tostring(j)..')', 1
end,
test = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lqtL_isinteger(L, '..tostring(j)..')', 1
end,
onstack = 'integer,',
}
base_types['int*'] = {
get = function(j)
return 'lqtL_tointref(L, '..j..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushinteger(L, *'..tostring(j)..')', 1
end,
test = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lqtL_isinteger(L, '..tostring(j)..')', 1
end,
onstack = 'integer,',
}
base_types['char**'] = {
get = function(j)
return 'lqtL_toarguments(L, '..tostring(j)..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lqtL_pusharguments(L, '..tostring(j)..')', 1
end,
test = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_istable(L, '..tostring(j)..')', 1
end,
onstack = 'table,',
}
--]]
base_types['std::string const&'] = {
get = function(i)
return 'std::string(lua_tostring(L, '..i..'), lua_objlen(L, '..i..'))', 1
end,
push = function(i)
return 'lua_pushlstring(L, '..i..'.c_str(), '..i..'.size())', 1
end,
test = function(i)
return 'lua_isstring(L, '..i..')', 1
end,
onstack = 'string,',
}
base_types['std::string'] = base_types['std::string const&']
return base_types
|
Fix QIoDevice::write missing (unknown type __int64), reported by Mostafa Vahedi
|
Fix QIoDevice::write missing (unknown type __int64), reported by Mostafa Vahedi
|
Lua
|
mit
|
mkottman/lqt,mkottman/lqt
|
5ad30a22562b50d8e7d81eb877c607aa2a963ded
|
core/languages.lua
|
core/languages.lua
|
SILE.languageSupport = {
languages = {},
loadLanguage = function(language)
if SILE.languageSupport.languages[language] then return end
if SILE.hyphenator.languages[language] then return end
if not(language) or language == "" then language = "en" end
ok, fail = pcall(function () SILE.require("languages/"..language.."-compiled") end)
if ok then return end
ok, fail = pcall(function () SILE.require("languages/"..language) end)
if fail then
SU.warn("Error loading language "..language..": "..fail)
end
end,
compile = function(language)
local ser = require("serpent")
-- Ensure things are loaded
SILE.languageSupport.loadLanguage(language)
SILE.hyphenate({ SILE.nodefactory.newNnode({language=language, text=""}) })
local f = io.open("languages/"..language.."-compiled.lua", "w")
f:write("_hyphenators."..language.."="..ser.line(_hyphenators[language]).."\n")
f:write("SILE.hyphenator.languages."..language.."="..ser.line(SILE.hyphenator.languages[language]).."\n")
f:close()
end
}
SILE.registerCommand("language", function (o,c)
if not c[1] then
local lang = SU.required(o, "main", "language setting")
SILE.languageSupport.loadLanguage(lang)
SILE.settings.set("document.language", lang)
else
local lang = SU.required(o, "lang", "language setting")
SILE.languageSupport.loadLanguage(lang)
SILE.settings.temporarily(function ()
SILE.settings.set("document.language", lang)
SILE.process(c)
end)
end
end)
require("languages/unicode")
-- The following languages neither have hyphenation nor specific
-- language support at present. This code is here to suppress warnings.
SILE.hyphenator.languages.ar = {patterns={}}
SILE.hyphenator.languages.urd = {patterns={}}
SILE.hyphenator.languages.snd = {patterns={}}
|
SILE.languageSupport = {
languages = {},
loadLanguage = function(language)
if SILE.languageSupport.languages[language] then return end
if SILE.hyphenator.languages[language] then return end
if not(language) or language == "" then language = "en" end
ok, fail = pcall(function () SILE.require("languages/"..language.."-compiled") end)
if ok then return end
ok, fail = pcall(function () SILE.require("languages/"..language) end)
if fail then
SU.warn("Error loading language "..language..": "..fail)
SILE.languageSupport.languages[language] = {} -- Don't try again
end
end,
compile = function(language)
local ser = require("serpent")
-- Ensure things are loaded
SILE.languageSupport.loadLanguage(language)
SILE.hyphenate({ SILE.nodefactory.newNnode({language=language, text=""}) })
local f = io.open("languages/"..language.."-compiled.lua", "w")
f:write("_hyphenators."..language.."="..ser.line(_hyphenators[language]).."\n")
f:write("SILE.hyphenator.languages."..language.."="..ser.line(SILE.hyphenator.languages[language]).."\n")
f:close()
end
}
SILE.registerCommand("language", function (o,c)
if not c[1] then
local lang = SU.required(o, "main", "language setting")
SILE.languageSupport.loadLanguage(lang)
SILE.settings.set("document.language", lang)
else
local lang = SU.required(o, "lang", "language setting")
SILE.languageSupport.loadLanguage(lang)
SILE.settings.temporarily(function ()
SILE.settings.set("document.language", lang)
SILE.process(c)
end)
end
end)
require("languages/unicode")
-- The following languages neither have hyphenation nor specific
-- language support at present. This code is here to suppress warnings.
SILE.hyphenator.languages.ar = {patterns={}}
SILE.hyphenator.languages.bo = {patterns={}}
SILE.hyphenator.languages.urd = {patterns={}}
SILE.hyphenator.languages.snd = {patterns={}}
|
Fix some warnings
|
Fix some warnings
|
Lua
|
mit
|
alerque/sile,simoncozens/sile,alerque/sile,alerque/sile,neofob/sile,simoncozens/sile,simoncozens/sile,neofob/sile,simoncozens/sile,neofob/sile,neofob/sile,alerque/sile
|
6ea77c29724776a696a6e6722bfce3fcac886cc3
|
lua/entities/gmod_wire_indicator.lua
|
lua/entities/gmod_wire_indicator.lua
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Indicator"
ENT.WireDebugName = "Indicator"
ENT.RenderGroup = RENDERGROUP_BOTH
-- Helper functions
function ENT:GetFactorFromValue( value )
return math.Clamp((value-self.a)/(self.b-self.a), 0, 1)
end
function ENT:GetColorFromValue( value )
local factor = self:GetFactorFromValue( value, self )
local r = math.Clamp((self.br-self.ar)*factor+self.ar, 0, 255)
local g = math.Clamp((self.bg-self.ag)*factor+self.ag, 0, 255)
local b = math.Clamp((self.bb-self.ab)*factor+self.ab, 0, 255)
local a = math.Clamp((self.ba-self.aa)*factor+self.aa, 0, 255)
return Color(r,g,b,a), factor
end
if CLIENT then
local color_box_size = 64
function ENT:GetWorldTipBodySize()
return 400,80
end
local white = Color(255,255,255,255)
local black = Color(0,0,0,255)
local function drawSquare( x,y,w,h )
surface.SetDrawColor( black )
surface.DrawLine( x, y, x + w, y )
surface.DrawLine( x + w, y, x + w, y + h )
surface.DrawLine( x + w, y + h, x, y + h )
surface.DrawLine( x, y + h, x, y )
end
local function drawColorSlider( x, y, w, h, self )
local len = self.b - self.a
local step = len / 50
local find_selected = nil
for i=self.a,self.b - step/2, step do
local color, factor = self:GetColorFromValue( i )
local pos_x = math.floor(x + (factor * w))
-- we're not stepping over every single possible value here,
-- so we have to check if we're close-ish to the user's selected value here
if not find_selected and i >= self.value then
find_selected = i
end
surface.SetDrawColor( color )
surface.DrawRect( pos_x, y, math.ceil(w/50), h )
end
-- if the user has set the value to this exactly, then
-- there's a possibility that the above check couldn't detect it
if self.value == self.b then find_selected = self.b end
-- draw the outline of the color slider
drawSquare( x,y,w,h )
-- draw the small box showing the current selected color
if find_selected then
find_selected = math.Clamp(find_selected,self.a+step/2,self.b-step/2)
local factor = self:GetFactorFromValue( find_selected )
local pos_x = math.floor(x + (factor * w))
drawSquare(pos_x - step / 2,y-h*0.15,math.ceil(w/50),h*1.4)
end
end
function ENT:DrawWorldTipBody( pos )
-- Get colors
local data = self:GetOverlayData()
--if not data.value then return end
-- Merge the data onto the entity itself.
-- This allows us to use the same references as serverside
for k,v in pairs( data ) do self[k] = v end
-- A
local color_text = string.format("A color: %d,%d,%d,%d\nA value: %d",self.ar,self.ag,self.ab,self.aa,self.a)
draw.DrawText( color_text, "GModWorldtip", pos.min.x + pos.edgesize, pos.min.y + pos.edgesize, white, TEXT_ALIGN_LEFT )
-- B
local color_text = string.format("B color: %d,%d,%d,%d\nB value: %d",self.br,self.bg,self.bb,self.ba,self.b)
draw.DrawText( color_text, "GModWorldtip", pos.max.x - pos.edgesize, pos.min.y + pos.edgesize, white, TEXT_ALIGN_RIGHT )
-- Percent
local factor = math.Clamp((self.value-self.a)/(self.b-self.a), 0, 1)
local color_text = string.format("%s (%d%%)",math.Round(self.value,2),factor*100)
local w,h = surface.GetTextSize(color_text)
draw.DrawText( color_text, "GModWorldtip", pos.center.x + 40, pos.min.y + pos.edgesize + h, white, TEXT_ALIGN_RIGHT )
-- Slider
drawColorSlider( pos.min.x + pos.edgesize, pos.min.y + pos.edgesize + 46, 401, 16, self )
end
return
end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
-- Preferably we would switch to storing these as colors,
-- but it's not really worth breaking all old dupes
self.a = 0
self.ar = 0
self.ag = 0
self.ab = 0
self.aa = 0
self.b = 0
self.br = 0
self.bg = 0
self.bb = 0
self.ba = 0
self.Inputs = WireLib.CreateInputs(self, { "A" })
self:SetRenderMode( RENDERMODE_TRANSALPHA )
end
function ENT:Setup(a, ar, ag, ab, aa, b, br, bg, bb, ba)
self.a = a or 0
self.ar = ar or 255
self.ag = ag or 0
self.ab = ab or 0
self.aa = aa or 255
self.b = b or 1
self.br = br or 0
self.bg = bg or 255
self.bb = bb or 0
self.ba = ba or 255
self:TriggerInput("A", self.a)
end
function ENT:TriggerInput(iname, value)
if iname == "A" then
self:ShowOutput(value)
local color = self:GetColorFromValue( value )
self:SetColor(color)
end
end
function ENT:ShowOutput(value)
self:SetOverlayData({
a = self.a,
b = self.b,
ar = self.ar,
ag = self.ag,
ab = self.ab,
aa = self.aa,
br = self.br,
bg = self.bg,
bb = self.bb,
ba = self.ba,
value = value
})
end
duplicator.RegisterEntityClass("gmod_wire_indicator", WireLib.MakeWireEnt, "Data", "a", "ar", "ag", "ab", "aa", "b", "br", "bg", "bb", "ba")
function MakeWire7Seg( pl, Pos, Ang, Model, a, ar, ag, ab, aa, b, br, bg, bb, ba)
if IsValid(pl) and not pl:CheckLimit( "wire_indicators" ) then return false end
local function MakeWireIndicator(prototype, scale)
local name, angOffset, posOffset = unpack(prototype)
posOffset = Vector(0, posOffset.x, -posOffset.y)
local Pos, Ang = LocalToWorld(posOffset * scale, Angle(), Pos, Ang), Ang + angOffset
local ent = WireLib.MakeWireEnt(pl,
{ Class = "gmod_wire_indicator",
Pos = Pos, Angle = Ang,
Model = Model, frozen = frozen, nocollide = nocollide },
a, ar, ag, ab, aa, b, br, bg, bb, ba )
if IsValid(ent) then
ent:SetNWString("WireName", name)
duplicator.StoreEntityModifier( ent, "WireName", { name = name } )
end
return ent
end
local prototypes = {
{ "G", Angle(0, 0, 0), Vector(0, 0) },
{ "A", Angle(0, 0, 0), Vector(0, 2) },
{ "B", Angle(0, 0, 90), Vector(1, 1) },
{ "C", Angle(0, 0, 90), Vector(1, -1) },
{ "D", Angle(0, 0, 0), Vector(0, -2) },
{ "E", Angle(0, 0, 90), Vector(-1, -1) },
{ "F", Angle(0, 0, 90), Vector(-1, 1) }
}
local wire_indicators = {}
wire_indicators[1] = MakeWireIndicator( prototypes[1], 0 )
-- get the scale (half the long side of the indicator) from the first one
local scale = wire_indicators[1]:OBBMaxs().y
for i = 2, 7 do
wire_indicators[i] = MakeWireIndicator( prototypes[i], scale )
if not IsValid( wire_indicators[i] ) then break end
for y = 1, i-1 do
const = constraint.Weld( wire_indicators[i], wire_indicators[y], 0, 0, 0, true, true )
end
wire_indicators[i - 1]:DeleteOnRemove( wire_indicators[i] ) --when one is removed, all are. a linked chain
end
if wire_indicators[7] then
wire_indicators[7]:DeleteOnRemove( wire_indicators[1] ) --loops chain back to first
end
return wire_indicators
end
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Indicator"
ENT.WireDebugName = "Indicator"
ENT.RenderGroup = RENDERGROUP_BOTH
-- Helper functions
function ENT:GetFactorFromValue( value )
return math.Clamp((value-self.a)/(self.b-self.a), 0, 1)
end
function ENT:GetColorFromValue( value )
local factor = self:GetFactorFromValue( value, self )
local r = math.Clamp((self.br-self.ar)*factor+self.ar, 0, 255)
local g = math.Clamp((self.bg-self.ag)*factor+self.ag, 0, 255)
local b = math.Clamp((self.bb-self.ab)*factor+self.ab, 0, 255)
local a = math.Clamp((self.ba-self.aa)*factor+self.aa, 0, 255)
return Color(r,g,b,a), factor
end
if CLIENT then
local color_box_size = 64
function ENT:GetWorldTipBodySize()
return 400,80
end
local white = Color(255,255,255,255)
local black = Color(0,0,0,255)
local function drawSquare( x,y,w,h )
surface.SetDrawColor( black )
surface.DrawLine( x, y, x + w, y )
surface.DrawLine( x + w, y, x + w, y + h )
surface.DrawLine( x + w, y + h, x, y + h )
surface.DrawLine( x, y + h, x, y )
end
local function drawColorSlider( x, y, w, h, self )
if self.a == self.b then -- no infinite loops!
draw.DrawText( "Can't draw color bar because A == B",
"GModWorldtip", x + w / 2, y + h / 2, white, TEXT_ALIGN_CENTER )
return
end
local diff = self.b - self.a
local len = math.abs(self.b) - math.abs(self.a)
local step = diff / 50
local find_selected = nil
for i=self.a,self.b - step/2, step do
local color, factor = self:GetColorFromValue( i )
local pos_x = math.floor(x + (factor * w))
-- we're not stepping over every single possible value here,
-- so we have to check if we're close-ish to the user's selected value
if not find_selected then
if diff >= 0 and i >= self.value then
find_selected = i
elseif diff < 0 and i < self.value then
find_selected = i
end
end
surface.SetDrawColor( color )
surface.DrawRect( pos_x, y, math.ceil(w/50), h )
end
-- if the user has set the value to this exactly, then
-- there's a possibility that the above check couldn't detect it
if self.value == self.b then find_selected = self.b end
-- draw the outline of the color slider
drawSquare( x,y,w,h )
-- draw the small box showing the current selected color
if find_selected then
find_selected = math.Clamp(find_selected,math.min(self.a,self.b)+step/2,math.max(self.a,self.b)-step/2)
local factor = self:GetFactorFromValue( find_selected )
local pos_x = math.floor(x + (factor * w))
drawSquare(pos_x - step / 2,y-h*0.15,math.ceil(w/50),h*1.4)
end
end
function ENT:DrawWorldTipBody( pos )
-- Get colors
local data = self:GetOverlayData()
-- Merge the data onto the entity itself.
-- This allows us to use the same references as serverside
for k,v in pairs( data ) do self[k] = v end
-- A
local color_text = string.format("A color: %d,%d,%d,%d\nA value: %d",self.ar,self.ag,self.ab,self.aa,self.a)
draw.DrawText( color_text, "GModWorldtip", pos.min.x + pos.edgesize, pos.min.y + pos.edgesize, white, TEXT_ALIGN_LEFT )
-- B
local color_text = string.format("B color: %d,%d,%d,%d\nB value: %d",self.br,self.bg,self.bb,self.ba,self.b)
draw.DrawText( color_text, "GModWorldtip", pos.max.x - pos.edgesize, pos.min.y + pos.edgesize, white, TEXT_ALIGN_RIGHT )
-- Percent
local factor = math.Clamp((self.value-self.a)/(self.b-self.a), 0, 1)
local color_text = string.format("%s (%d%%)",math.Round(self.value,2),factor*100)
local w,h = surface.GetTextSize(color_text)
draw.DrawText( color_text, "GModWorldtip", pos.center.x + 40, pos.min.y + pos.edgesize + h, white, TEXT_ALIGN_RIGHT )
-- Slider
drawColorSlider( pos.min.x + pos.edgesize, pos.min.y + pos.edgesize + 46, 401, 16, self )
end
return
end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
-- Preferably we would switch to storing these as colors,
-- but it's not really worth breaking all old dupes
self.a = 0
self.ar = 0
self.ag = 0
self.ab = 0
self.aa = 0
self.b = 0
self.br = 0
self.bg = 0
self.bb = 0
self.ba = 0
self.Inputs = WireLib.CreateInputs(self, { "A" })
self:SetRenderMode( RENDERMODE_TRANSALPHA )
end
function ENT:Setup(a, ar, ag, ab, aa, b, br, bg, bb, ba)
self.a = a or 0
self.ar = ar or 255
self.ag = ag or 0
self.ab = ab or 0
self.aa = aa or 255
self.b = b or 1
self.br = br or 0
self.bg = bg or 255
self.bb = bb or 0
self.ba = ba or 255
self:TriggerInput("A", self.a)
end
function ENT:TriggerInput(iname, value)
if iname == "A" then
self:ShowOutput(value)
local color = self:GetColorFromValue( value )
self:SetColor(color)
end
end
function ENT:ShowOutput(value)
self:SetOverlayData({
a = self.a,
b = self.b,
ar = self.ar,
ag = self.ag,
ab = self.ab,
aa = self.aa,
br = self.br,
bg = self.bg,
bb = self.bb,
ba = self.ba,
value = value
})
end
duplicator.RegisterEntityClass("gmod_wire_indicator", WireLib.MakeWireEnt, "Data", "a", "ar", "ag", "ab", "aa", "b", "br", "bg", "bb", "ba")
function MakeWire7Seg( pl, Pos, Ang, Model, a, ar, ag, ab, aa, b, br, bg, bb, ba)
if IsValid(pl) and not pl:CheckLimit( "wire_indicators" ) then return false end
local function MakeWireIndicator(prototype, scale)
local name, angOffset, posOffset = unpack(prototype)
posOffset = Vector(0, posOffset.x, -posOffset.y)
local Pos, Ang = LocalToWorld(posOffset * scale, Angle(), Pos, Ang), Ang + angOffset
local ent = WireLib.MakeWireEnt(pl,
{ Class = "gmod_wire_indicator",
Pos = Pos, Angle = Ang,
Model = Model, frozen = frozen, nocollide = nocollide },
a, ar, ag, ab, aa, b, br, bg, bb, ba )
if IsValid(ent) then
ent:SetNWString("WireName", name)
duplicator.StoreEntityModifier( ent, "WireName", { name = name } )
end
return ent
end
local prototypes = {
{ "G", Angle(0, 0, 0), Vector(0, 0) },
{ "A", Angle(0, 0, 0), Vector(0, 2) },
{ "B", Angle(0, 0, 90), Vector(1, 1) },
{ "C", Angle(0, 0, 90), Vector(1, -1) },
{ "D", Angle(0, 0, 0), Vector(0, -2) },
{ "E", Angle(0, 0, 90), Vector(-1, -1) },
{ "F", Angle(0, 0, 90), Vector(-1, 1) }
}
local wire_indicators = {}
wire_indicators[1] = MakeWireIndicator( prototypes[1], 0 )
-- get the scale (half the long side of the indicator) from the first one
local scale = wire_indicators[1]:OBBMaxs().y
for i = 2, 7 do
wire_indicators[i] = MakeWireIndicator( prototypes[i], scale )
if not IsValid( wire_indicators[i] ) then break end
for y = 1, i-1 do
const = constraint.Weld( wire_indicators[i], wire_indicators[y], 0, 0, 0, true, true )
end
wire_indicators[i - 1]:DeleteOnRemove( wire_indicators[i] ) --when one is removed, all are. a linked chain
end
if wire_indicators[7] then
wire_indicators[7]:DeleteOnRemove( wire_indicators[1] ) --loops chain back to first
end
return wire_indicators
end
|
Fixed some issues with the new indicator overlay
|
Fixed some issues with the new indicator overlay
|
Lua
|
apache-2.0
|
NezzKryptic/Wire,bigdogmat/wire,garrysmodlua/wire,Grocel/wire,sammyt291/wire,dvdvideo1234/wire,thegrb93/wire,wiremod/wire
|
0e429980d245688fd2c292c4cdfa943ffe3621ee
|
Statlist.lua
|
Statlist.lua
|
--[[
This module prints a list of all
Pokémon statistics
--]]
local s = {}
local css = require('Css')
local ms = require('MiniSprite')
local list = require('Wikilib-lists')
local oop = require('Wikilib-oop')
local tab = require('Wikilib-tables')
local txt = require('Wikilib-strings')
local c = require("Colore-data")
local pokes = require("Poké-data")
local data = require("Wikilib-data")
--[[
Class representing an entry for the
statistics list
--]]
local Entry = oop.makeClass(list.PokeSortableEntry)
Entry.new = function(stats, poke)
local this = table.merge(Entry.super.new(poke),
pokes[poke])
return setmetatable(table.merge(this, {stats = stats}),
Entry)
end
Entry.__tostring = function(this)
local sum = table.fold(this.stats, 0,
function(a, b) return a + b end)
return string.interp([=[| style="padding: 0.3ex 0.8ex;" | ${ndex}
| style="padding: 0.3ex 0.8ex;" | ${ms}
| style="padding: 0.3ex 0.8ex;" | [[${name}|<span style="color: #000;">${name}</span>]]${form}
| style="padding: 0.3ex 0.8ex; background: #${hpColor};" | '''${hp}'''
| style="padding: 0.3ex 0.8ex; background: #${atkColor};" | '''${atk}'''
| style="padding: 0.3ex 0.8ex; background: #${defColor};" | '''${def}'''
| style="padding: 0.3ex 0.8ex; background: #${spatkColor};" | '''${spatk}'''
| style="padding: 0.3ex 0.8ex; background: #${spdefColor};" | '''${spdef}'''
| style="padding: 0.3ex 0.8ex; background: #${speColor};" | '''${spe}'''
| style="padding: 0.3ex 0.8ex; background: #${pcwColor};" | '''${sum}'''
| style="padding: 0.3ex 0.8ex; background: #${pcwColor};" | '''${avg}''']=],
{
ndex = string.tf(this.ndex),
ms = ms.staticLua(string.tf(this.ndex) ..
(this.formAbbr == 'base' and ''
or this.formAbbr or '')),
name = this.name,
form = this.formsData and
this.formsData.blacklinks[this.formAbbr]
or '',
hpColor = c.ps.light,
hp = this.stats.hp,
atkColor = c.attacco.light,
atk = this.stats.atk,
defColor = c.difesa.light,
def = this.stats.def,
spatkColor = c.attacco_speciale.light,
spatk = this.stats.spatk,
spdefColor = c.difesa_speciale.light,
spdef = this.stats.spdef,
speColor = c.velocita.light,
spe = this.stats.spe,
pcwColor = c.pcwiki.medium_light,
sum = sum,
avg = string.format("%.2f", sum / 6)
})
end
Entry.toFooter = Entry.__tostring
-- List header
local header = string.interp([=[{| class="sortable roundy-corners text-center pull-center white-rows" style="border-spacing: 0; padding: 0.6ex; ${bg};"
|-
! style="padding: 0.8ex;" | [[Elenco Pokémon secondo il Pokédex Nazionale|<span style="color: #000;">#</span>]]
! style="padding: 0.8ex;" |
! style="padding: 0.8ex;" | Pokémon
! class="roundytop text-small" style="padding: 0.8ex; background: #${hp};" | [[Statistiche#PS|<span style="color: #FFF;">PS</span>]]
! class="roundytop text-small" style="padding: 0.8ex; background:#${atk};" | [[Statistiche#Attacco|<span style="color: #FFF;">Attacco</span>]]
! class="roundytop text-small" style="padding: 0.8ex; background:#${def};" | [[Statistiche#Difesa|<span style="color: #FFF;">Difesa</span>]]
! class="roundytop text-small" style="padding: 0.8ex; background:#${spatk};" | [[Statistiche#Attacco Speciale|<span style="color: #FFF;">Attacco sp.</span>]]
! class="roundytop text-small" style="padding: 0.8ex; background:#${spdef};" | [[Statistiche#Difesa Speciale|<span style="color: #FFF;">Difesa sp.</span>]]
! class="roundytop text-small" style="padding: 0.8ex; background:#${spe};">[[Statistiche#Velocità|<span style="color: #FFF;">Velocità</span>]]
! class="roundytop text-small" style="padding: 0.8ex; color: #FFF; background:#${pcw};">Totale
! class="roundytop text-small" style="padding: 0.8ex; color: #FFF; background:#${pcw};">Media]=],
{
bg = css.horizGradLua{type = 'pcwiki'},
hp = c.ps.normale,
atk = c.attacco.normale,
def = c.difesa.normale,
spatk = c.attacco_speciale.normale,
spdef = c.difesa_speciale.normale,
spe = c.velocita.normale,
pcw = c.pcwiki.dark
}
)
--[[
Wiki interface function: called with no
argument, returns the list of all Pokémon
statistics.
Example:
{{#invoke: Statlist | statlist }}
--]]
s.statlist = function(frame)
return list.makeList({
source = require('PokéStats-data'),
makeEntry = Entry,
iterator = list.pokeNames,
header = header
})
end
s.Statlist = s.statlist
print(s.statlist())
return s
|
--[[
This module prints a list of all
Pokémon base statistics
--]]
local s = {}
local css = require('Css')
local ms = require('MiniSprite')
local list = require('Wikilib-lists')
local oop = require('Wikilib-oop')
local tab = require('Wikilib-tables')
local txt = require('Wikilib-strings')
local c = require("Colore-data")
local pokes = require("Poké-data")
--[[
Class representing an entry for the base statistics
list. By subclassing PokeSortableEntry it implements
all the interfaces needed for sortForm, sortNdex
and makeList in Wikilib/lists
--]]
local Entry = oop.makeClass(list.PokeSortableEntry)
--[[
Constructor: the first argument is an entry from
PokéStats/data and the second one its key. Since
no filtering is needed, it never returns nil.
--]]
Entry.new = function(stats, poke)
local this = table.merge(Entry.super.new(poke),
pokes[poke])
--[[
Statistics are not merged at top level
to ease later total stat calculation
--]]
this.stats = stats
return setmetatable(this, Entry)
end
--[[
Wikicode for a list entry: shows Pokémon ndex,
mini sprite, name and base stats, plus total
and average.
--]]
Entry.__tostring = function(this)
local sum = table.fold(this.stats, 0,
function(a, b) return a + b end)
return string.interp([=[| style="padding: 0.3ex 0.8ex;" | ${ndex}
| style="padding: 0.3ex 0.8ex;" | ${ms}
| style="padding: 0.3ex 0.8ex;" | [[${name}|<span style="color: #000;">${name}</span>]]${form}
| style="padding: 0.3ex 0.8ex; background: #${hpColor};" | '''${hp}'''
| style="padding: 0.3ex 0.8ex; background: #${atkColor};" | '''${atk}'''
| style="padding: 0.3ex 0.8ex; background: #${defColor};" | '''${def}'''
| style="padding: 0.3ex 0.8ex; background: #${spatkColor};" | '''${spatk}'''
| style="padding: 0.3ex 0.8ex; background: #${spdefColor};" | '''${spdef}'''
| style="padding: 0.3ex 0.8ex; background: #${speColor};" | '''${spe}'''
| style="padding: 0.3ex 0.8ex; background: #${pcwColor};" | '''${sum}'''
| style="padding: 0.3ex 0.8ex; background: #${pcwColor};" | '''${avg}''']=],
{
ndex = string.tf(this.ndex),
ms = ms.staticLua(string.tf(this.ndex) ..
(this.formAbbr == 'base' and ''
or this.formAbbr or '')),
name = this.name,
form = this.formsData and
this.formsData.blacklinks[this.formAbbr]
or '',
hpColor = c.ps.light,
hp = this.stats.hp,
atkColor = c.attacco.light,
atk = this.stats.atk,
defColor = c.difesa.light,
def = this.stats.def,
spatkColor = c.attacco_speciale.light,
spatk = this.stats.spatk,
spdefColor = c.difesa_speciale.light,
spdef = this.stats.spdef,
speColor = c.velocita.light,
spe = this.stats.spe,
pcwColor = c.pcwiki.medium_light,
sum = sum,
avg = string.format("%.2f", sum / 6)
})
end
-- List header
local header = string.interp([=[{| class="sortable roundy-corners text-center pull-center white-rows" style="border-spacing: 0; padding: 0.6ex; ${bg};"
|-
! style="padding: 0.8ex;" | [[Elenco Pokémon secondo il Pokédex Nazionale|<span style="color: #000;">#</span>]]
! style="padding: 0.8ex;" |
! style="padding: 0.8ex;" | Pokémon
! class="roundytop text-small" style="padding-top: 0.8ex; padding-bottom: 0.8ex; padding-left: 0.8ex; background-color: #${hp};" | [[Statistiche#PS|<span style="color: #FFF;">PS</span>]]
! class="roundytop text-small" style="padding-top: 0.8ex; padding-bottom: 0.8ex; padding-left: 0.8ex; background-color: #${atk};" | [[Statistiche#Attacco|<span style="color: #FFF;">Attacco</span>]]
! class="roundytop text-small" style="padding-top: 0.8ex; padding-bottom: 0.8ex; padding-left: 0.8ex; background-color: #${def};" | [[Statistiche#Difesa|<span style="color: #FFF;">Difesa</span>]]
! class="roundytop text-small" style="padding-top: 0.8ex; padding-bottom: 0.8ex; padding-left: 0.8ex; background-color: #${spatk};" | [[Statistiche#Attacco Speciale|<span style="color: #FFF;">Attacco sp.</span>]]
! class="roundytop text-small" style="padding-top: 0.8ex; padding-bottom: 0.8ex; padding-left: 0.8ex; background-color: #${spdef};" | [[Statistiche#Difesa Speciale|<span style="color: #FFF;">Difesa sp.</span>]]
! class="roundytop text-small" style="padding-top: 0.8ex; padding-bottom: 0.8ex; padding-left: 0.8ex; background-color: #${spe};" | [[Statistiche#Velocità|<span style="color: #FFF;">Velocità</span>]]
! class="roundytop text-small" style="padding-top: 0.8ex; padding-bottom: 0.8ex; padding-left: 0.8ex; color: #FFF; background-color: #${pcw};" | Totale
! class="roundytop text-small" style="padding-top: 0.8ex; padding-bottom: 0.8ex; padding-left: 0.8ex; color: #FFF; background-color: #${pcw};" | Media]=],
{
bg = css.horizGradLua{type = 'pcwiki'},
hp = c.ps.normale,
atk = c.attacco.normale,
def = c.difesa.normale,
spatk = c.attacco_speciale.normale,
spdef = c.difesa_speciale.normale,
spe = c.velocita.normale,
pcw = c.pcwiki.dark
}
)
--[[
Wiki interface function: called with no
argument, returns the list of all Pokémon
statistics.
Example:
{{#invoke: Statlist | statlist }}
--]]
s.statlist = function(frame)
return list.makeList({
source = require('PokéStats-data'),
makeEntry = Entry,
iterator = list.pokeNames,
header = header,
footer = '|}'
})
end
s.Statlist = s.statlist
print(s.statlist())
return s
|
Minor graphical fixes on statslist
|
Minor graphical fixes on statslist
|
Lua
|
cc0-1.0
|
pokemoncentral/wiki-lua-modules
|
95b08955583748e56679d7e17c2b4a60c9cd0fff
|
lua/SgdMomentum.lua
|
lua/SgdMomentum.lua
|
local SgdMomentum = torch.class('nn.SgdMomentum')
function SgdMomentum:__init(module, criterion)
self.learningRate = 1e-2
self.learningRateDecay = 0.3
self.maxIteration = 100
self.convergeEps = 1e-6
self.momentum = 0.9
self.shuffleIndices = true
self.module = module
self.criterion = criterion
end
function SgdMomentum:train(dataset)
local iteration = 1
local currentLearningRate = self.learningRate
local module = self.module
local criterion = self.criterion
local shuffledIndices = torch.randperm(dataset:size(), 'torch.LongTensor')
if not self.shuffleIndices then
for t = 1,dataset:size() do
shuffledIndices[t] = t
end
end
local errPrev = math.huge
-- Initialize previous weights used to compute momentum.
criterion:forward(module:forward(dataset[shuffledIndices[1]][1]),
dataset[shuffledIndices[1]][2])
local parameters, gradients = module:parameters()
local prevParams = {}
for _, w in ipairs(parameters) do
table.insert(prevParams, w:clone())
end
print("# SgdMomentum: training")
while true do
local currentError = 0
for t = 1,dataset:size() do
local example = dataset[shuffledIndices[t]]
local input = example[1]
local target = example[2]
currentError = currentError + criterion:forward(module:forward(input), target)
module:updateGradInput(input, criterion:updateGradInput(module.output, target))
-- Add momentum term to gradients.
local parameters, gradients = module:parameters()
for i, gw in ipairs(gradients) do
local w = parameters[i]
local wPrev = prevParams[i]
-- -\delta_w = w_{t-1} - w_t
wPrev:add(-1, w)
-- Update gradient with momentum term correcting for sign and learning rate.
gw:add(-self.momentum / currentLearningRate, wPrev)
wPrev:copy(w)
end
module:accUpdateGradParameters(input, criterion.gradInput, currentLearningRate)
if self.hookExample then
self.hookExample(self, example)
end
end
if self.hookIteration then
self.hookIteration(self, iteration)
end
currentError = currentError / dataset:size()
print("# current error = "..currentError)
iteration = iteration + 1
currentLearningRate = self.learningRate/(1 + (iteration * self.learningRateDecay))
if self.maxIteration > 0 and iteration > self.maxIteration then
print("# SgdMomentum: you have reached the maximum number of iterations")
break
end
-- Check convergence (expect decrease).
local errDelta = errPrev - currentError
if errDelta < self.convergeEps then
print("# SgdMomentum: converged after "..t.." iterations")
break
end
errPrev = currentError
end
end
|
local SgdMomentum = torch.class('nn.SgdMomentum')
function SgdMomentum:__init(module, criterion)
self.learningRate = 1e-2
self.learningRateDecay = 0.3
self.maxIteration = 100
self.convergeEps = 1e-6
self.momentum = 0.9
self.shuffleIndices = true
self.module = module
self.criterion = criterion
end
function SgdMomentum:train(dataset)
local currentLearningRate = self.learningRate
local module = self.module
local criterion = self.criterion
local shuffledIndices = torch.randperm(dataset:size(), 'torch.LongTensor')
if not self.shuffleIndices then
for t = 1,dataset:size() do
shuffledIndices[t] = t
end
end
local errPrev = math.huge
-- Initialize previous weights used to compute momentum.
criterion:forward(module:forward(dataset[shuffledIndices[1]][1]),
dataset[shuffledIndices[1]][2])
local parameters, gradients = module:parameters()
local prevParams = {}
for _, w in ipairs(parameters) do
table.insert(prevParams, w:clone())
end
print("# SgdMomentum: training")
while true do
local iteration = 1
local currentError = 0
for t = 1,dataset:size() do
local example = dataset[shuffledIndices[t]]
local input = example[1]
local target = example[2]
currentError = currentError + criterion:forward(module:forward(input), target)
module:updateGradInput(input, criterion:updateGradInput(module.output, target))
-- Add momentum term to gradients.
local parameters, gradients = module:parameters()
for i, gw in ipairs(gradients) do
local w = parameters[i]
local wPrev = prevParams[i]
-- -\delta_w = w_{t-1} - w_t
wPrev:add(-1, w)
-- Update gradient with momentum term correcting for sign and learning rate.
gw:add(-self.momentum / currentLearningRate, wPrev)
wPrev:copy(w)
end
module:accUpdateGradParameters(input, criterion.gradInput, currentLearningRate)
if self.hookExample then
self.hookExample(self, example)
end
end
if self.hookIteration then
self.hookIteration(self, iteration)
end
currentError = currentError / dataset:size()
print("# current error = "..currentError)
currentLearningRate = self.learningRate / (1 + (iteration * self.learningRateDecay))
if self.maxIteration > 0 and iteration >= self.maxIteration then
print("# SgdMomentum: you have reached the maximum number of iterations")
break
end
-- Check convergence (expect decrease).
local errDelta = errPrev - currentError
if errDelta < self.convergeEps then
print("# SgdMomentum: converged after "..iteration.." iterations")
break
end
errPrev = currentError
iteration = iteration + 1
end
end
|
Fix iteration convergence bug.
|
Fix iteration convergence bug.
Trainer would crash when converged.
|
Lua
|
bsd-3-clause
|
blr246/midi-machine
|
030e57b9312703978a4f109a9e39829611510fd9
|
test_scripts/Polices/build_options/017_ATF_P_TC_PoliciesManager_Sets_Status_UPDATING_HTTP.lua
|
test_scripts/Polices/build_options/017_ATF_P_TC_PoliciesManager_Sets_Status_UPDATING_HTTP.lua
|
---------------------------------------------------------------------------------------------
-- Requirements summary:
-- [PolicyTableUpdate] PoliciesManager changes status to “UPDATING”
-- [HMI API] OnStatusUpdate
--
-- Description:
-- PoliciesManager must change the status to “UPDATING” and notify HMI with
-- OnStatusUpdate("UPDATING") right after SnapshotPT is sent out to to mobile
-- app via OnSystemRequest() RPC.
-- 1. Used preconditions
-- SDL is built with "-DEXTENDED_POLICY: HTTP" flag
-- Application is registered.
-- PTU is requested.
-- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED)
-- SDL->HMI:SDL.PolicyUpdate(file, timeout, retry[])
-- HMI -> SDL: SDL.GetURLs (<service>)
-- HMI->SDL: BasicCommunication.OnSystemRequest ('url', requestType:HTTP, appID="default")
--
-- 2. Performed steps
-- SDL->app: OnSystemRequest ('url', requestType:HTTP, fileType="JSON", appID)
-- Expected result:
-- SDL->HMI: SDL.OnStatusUpdate(UPDATING) right after SDL->app: OnSystemRequest
---------------------------------------------------------------------------------------------
--[[ 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 commonPreconditions = require('user_modules/shared_testcases/commonPreconditions')
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFileAndPolicyTable()
commonPreconditions:Connecttest_without_ExitBySDLDisconnect_WithoutOpenConnectionRegisterApp("connecttest_ConnectMobile.lua")
--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('user_modules/connecttest_ConnectMobile')
require('cardinalities')
require('user_modules/AppTypes')
local mobile_session = require('mobile_session')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:Precondition_Connect_device()
self:connectMobile()
end
function Test:Precondition_StartSession()
self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection)
self.mobileSession:StartService(7)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_PoliciesManager_changes_status_UPDATING()
local message_order = 1
local is_test_fail = false
self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams)
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", {application = { appName = config.application1.registerAppInterfaceParams.appName } })
:Do(function()
EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "HTTP"})
:Do(function()
if(message_order ~= 2) then
commonFunctions:printError("OnSystemRequest is not received as message 2 after OnAppRegistered. Received as message: "..message_order)
is_test_fail = true
else
print("OnSystemRequest received as message 2 after OnAppRegistered.")
end
message_order = message_order + 1
local CorIdSystemRequest = self.mobileSession:SendRPC("SystemRequest", { requestType = "HTTP", fileName = "PolicyTableUpdate", },"files/ptu.json")
EXPECT_RESPONSE(CorIdSystemRequest, { success = true, resultCode = "SUCCESS"})
end)
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate",
{ status = "UPDATE_NEEDED" }, {status = "UPDATING"}):Times(2)
:Do(function(_,data)
if(data.params.status == "UPDATE_NEEDED") then
if(message_order ~= 1) then
commonFunctions:printError("SDL.OnStatusUpdate(UPDATE_NEEDED) is not received as message 1 after OnAppRegistered. Received as message: "..message_order)
is_test_fail = true
else
print("SDL.OnStatusUpdate(UPDATING) received as message 1 after OnAppRegistered.")
end
message_order = message_order + 1
elseif(data.params.status == "UPDATING") then
if(message_order ~= 3) then
commonFunctions:printError("SDL.OnStatusUpdate(UPDATING) is not received as message 3 after OnAppRegistered. Received as message: "..message_order)
is_test_fail = true
else
print("SDL.OnStatusUpdate(UPDATING) received as message 3 after OnAppRegistered.")
end
message_order = message_order + 1
end
end)
if(is_test_fail == true) then
self:FailTestCase("Test is FAILED. See prints.")
end
end)
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_Stop_SDL()
StopSDL()
end
return Test
|
---------------------------------------------------------------------------------------------
-- Requirements summary:
-- [PolicyTableUpdate] PoliciesManager changes status to “UPDATING”
-- [HMI API] OnStatusUpdate
--
-- Description:
-- PoliciesManager must change the status to “UPDATING” and notify HMI with
-- OnStatusUpdate("UPDATING") right after SnapshotPT is sent out to to mobile
-- app via OnSystemRequest() RPC.
-- 1. Used preconditions
-- SDL is built with "-DEXTENDED_POLICY: HTTP" flag
-- Application is registered.
-- PTU is requested.
-- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED)
-- SDL->HMI:SDL.PolicyUpdate(file, timeout, retry[])
-- HMI -> SDL: SDL.GetURLs (<service>)
-- HMI->SDL: BasicCommunication.OnSystemRequest ('url', requestType:HTTP, appID="default")
--
-- 2. Performed steps
-- SDL->app: OnSystemRequest ('url', requestType:HTTP, fileType="JSON", appID)
-- Expected result:
-- SDL->HMI: SDL.OnStatusUpdate(UPDATING) right after SDL->app: OnSystemRequest
---------------------------------------------------------------------------------------------
--[[ 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 commonPreconditions = require('user_modules/shared_testcases/commonPreconditions')
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFileAndPolicyTable()
commonPreconditions:Connecttest_without_ExitBySDLDisconnect_WithoutOpenConnectionRegisterApp("connecttest_ConnectMobile.lua")
--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('user_modules/connecttest_ConnectMobile')
require('cardinalities')
require('user_modules/AppTypes')
local mobile_session = require('mobile_session')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:Precondition_Connect_device()
self:connectMobile()
end
function Test:Precondition_StartSession()
self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection)
self.mobileSession:StartService(7)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_PoliciesManager_changes_status_UPDATING()
local message_order = 1
local is_test_fail = false
self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams)
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", {application = { appName = config.application1.registerAppInterfaceParams.appName } })
:Do(function()
EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "HTTP"})
:Do(function()
if(message_order ~= 2) then
commonFunctions:printError("OnSystemRequest is not received as message 2 after OnAppRegistered. Received as message: "..message_order)
is_test_fail = true
else
print("OnSystemRequest received as message 2 after OnAppRegistered.")
end
message_order = message_order + 1
local CorIdSystemRequest = self.mobileSession:SendRPC("SystemRequest", { requestType = "HTTP", fileName = "PolicyTableUpdate", },"files/ptu.json")
EXPECT_RESPONSE(CorIdSystemRequest, { success = true, resultCode = "SUCCESS"})
end)
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate"):Times(Between(1,2))
:Do(function(_,data)
if(data.params.status == "UPDATE_NEEDED") then
if(message_order ~= 1) then
commonFunctions:printError("SDL.OnStatusUpdate(UPDATE_NEEDED) is not received as message 1 after OnAppRegistered. Received as message: "..message_order)
is_test_fail = true
else
print("SDL.OnStatusUpdate(UPDATING) received as message 1 after OnAppRegistered.")
end
message_order = message_order + 1
elseif(data.params.status == "UPDATING") then
if(message_order ~= 3) then
commonFunctions:printError("SDL.OnStatusUpdate(UPDATING) is not received as message 3 after OnAppRegistered. Received as message: "..message_order)
is_test_fail = true
else
print("SDL.OnStatusUpdate(UPDATING) received as message 3 after OnAppRegistered.")
end
message_order = message_order + 1
end
end)
if(is_test_fail == true) then
self:FailTestCase("Test is FAILED. See prints.")
end
end)
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_Stop_SDL()
StopSDL()
end
return Test
|
Fix wrong check in expect_notification
|
Fix wrong check in expect_notification
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
9ac78a9f145afbd1e214ecf41cb9f42e74d42f21
|
example-rcfile.lua
|
example-rcfile.lua
|
function Set(t)
local s = {}
for _,v in pairs(t) do s[v] = true end
return s
end
function set_contains(t, e)
return t[e]
end
-- The set of global shortcuts we don't want to swap cmd/alt.
global_excludes = Set{ "shift-cmd-tab",
"cmd-tab" }
-- The set of apps we want to consider swapping keys for, with some
-- notable exclusions. The exclusion means that a "cmd-w" will do the
-- normal OS Terminal behaviour. If you omit items then you would
-- have to use "alt-w" to close a terminal window.
apps = {
Terminal = { exclude = Set{ "shift-cmd-[",
"shift-cmd-]",
"cmd-c",
"cmd-v",
"cmd-w",
"cmd-1",
"cmd-2",
"cmd-3",
"cmd-t",
"cmd-n",
"cmd-`",
} },
Eclipse = { exclude = {} },
Xcode = { exclude = {} },
TextMate = { exclude = Set { "cmd-1",
"cmd-2",
"cmd-3",
"cmd-4",
"cmd-t" ,
"cmd-fn-right",
"cmd-fn-left",
} },
}
-- Return true to swap cmd/alt, otherwise false.
-- This function is passed a table comprising the following keys:
--
-- key_str_seq key sequence (e.g., "shift-cmd-e")
-- alt true if the alt key was pressed
-- fn true if the fn key was pressed
-- control true if the control key was pressed
-- shift true if the shift key was pressed
-- cmd true if the command key was pressed
-- keycode numeric virtual keycode (e.g., 48)
-- appname the frontmost application (e.g., Terminal)
--
-- The order of the modifier keys in key-str-eq is always:
-- shift control alt cmd fn, separated by a hyphen ("-").
function swap_keys(t)
-- for i,v in pairs(t) do print(i,v) end
-- print(t.appname)
if set_contains(global_excludes, t.key_str_seq) then
return false
end
if not apps[t.appname] then
return false
end
local excludes = apps[t.appname]["exclude"]
if set_contains(excludes, t.key_str_seq) then
-- print("exluding: ", t.key_str_seq)
return false
end
return true
end
|
function Set(t)
local s = {}
for _,v in pairs(t) do s[v] = true end
return s
end
function set_contains(t, e)
return t[e]
end
-- The set of global shortcuts we don't want to swap cmd/alt.
global_excludes = Set{ "shift-cmd-tab",
"cmd-tab" }
-- The set of apps we want to consider swapping keys for, with some
-- notable exclusions. The exclusion means that a "cmd-w" will do the
-- normal OS Terminal behaviour. If you omit items then you would
-- have to use "alt-w" to close a terminal window.
apps = {
Terminal = { exclude = Set{ "shift-cmd-[",
"shift-cmd-]",
"cmd-c",
"cmd-v",
"cmd-w",
"cmd-1",
"cmd-2",
"cmd-3",
"cmd-t",
"cmd-n",
"cmd-`",
} },
Eclipse = { exclude = {} },
Xcode = { exclude = {} },
TextMate = { exclude = Set { "cmd-1",
"cmd-2",
"cmd-3",
"cmd-4",
"cmd-t" ,
"cmd-fn-right",
"cmd-fn-left",
} },
["NX Player for OS X"] = { exclude = Set{} },
["Parallels Desktop"] = {},
}
-- Return true to swap cmd/alt, otherwise false.
-- This function is passed a table comprising the following keys:
--
-- key_str_seq key sequence (e.g., "shift-cmd-e")
-- alt true if the alt key was pressed
-- fn true if the fn key was pressed
-- control true if the control key was pressed
-- shift true if the shift key was pressed
-- cmd true if the command key was pressed
-- keycode numeric virtual keycode (e.g., 48)
-- appname the frontmost application (e.g., Terminal)
--
-- The order of the modifier keys in key-str-eq is always:
-- shift control alt cmd fn, separated by a hyphen ("-").
function swap_keys(t)
-- for i,v in pairs(t) do print(i,v) end
-- print(t.appname)
if set_contains(global_excludes, t.key_str_seq) then
return false
end
if not apps[t.appname] then
return false
end
local excludes = apps[t.appname]["exclude"]
if (excludes ~= nil and set_contains(excludes, t.key_str_seq)) then
-- print("exluding: ", t.key_str_seq)
return false
end
return true
end
|
Added an example of a Process with spaces in the name
|
Added an example of a Process with spaces in the name
Updated the example lua script to show how to specify a process
that has one or more spaces in its name (e.g., "NX Player for OS X").
Also fixed a bug when addressing a table that doesn't have an
"exclude" key.
|
Lua
|
mit
|
frobware/cmd-key-happy,frobware/cmd-key-happy,frobware/cmd-key-happy,frobware/cmd-key-happy,andymcd/cmd-key-happy,jaequery/cmd-key-happy,frobware/cmd-key-happy,andymcd/cmd-key-happy,andymcd/cmd-key-happy,andymcd/cmd-key-happy,jaequery/cmd-key-happy,jaequery/cmd-key-happy,andymcd/cmd-key-happy
|
17ce055658cd8bfb61a610ca04be8b343504c81e
|
applications/luci-splash/luasrc/controller/splash/splash.lua
|
applications/luci-splash/luasrc/controller/splash/splash.lua
|
module("luci.controller.splash.splash", package.seeall)
function index()
entry({"admin", "services", "splash"}, cbi("splash/splash"), "Client-Splash")
node("splash").target = call("action_dispatch")
node("splash", "activate").target = call("action_activate")
node("splash", "splash").target = template("splash_splash/splash")
end
function action_dispatch()
local mac = luci.sys.net.ip4mac(luci.http.getenv("REMOTE_ADDR")) or ""
local status = luci.util.execl("luci-splash status "..mac)[1]
if #mac > 0 and ( status == "whitelisted" or status == "lease" ) then
luci.http.redirect(luci.dispatcher.build_url())
else
luci.http.redirect(luci.dispatcher.build_url("splash", "splash"))
end
end
function action_activate()
local mac = luci.sys.net.ip4mac(luci.http.getenv("REMOTE_ADDR"))
if mac and luci.http.formvalue("accept") then
os.execute("luci-splash add "..mac.." >/dev/null 2>&1")
luci.http.redirect(luci.model.uci.cursor():get("freifunk", "community", "homepage"))
else
luci.http.redirect(luci.dispatcher.build_url())
end
end
|
module("luci.controller.splash.splash", package.seeall)
function index()
entry({"admin", "services", "splash"}, cbi("splash/splash"), "Client-Splash")
node("splash").target = call("action_dispatch")
node("splash", "activate").target = call("action_activate")
node("splash", "splash").target = template("splash_splash/splash")
end
function action_dispatch()
local mac = luci.sys.net.ip4mac(luci.http.getenv("REMOTE_ADDR")) or ""
local status = luci.util.execl("luci-splash status "..mac)[1]
if #mac > 0 and ( status == "whitelisted" or status == "lease" ) then
luci.http.redirect(luci.dispatcher.build_url())
else
luci.http.redirect(luci.dispatcher.build_url("splash", "splash"))
end
end
function action_activate()
local ip = luci.http.getenv("REMOTE_ADDR") or "127.0.0.1"
local mac = luci.sys.net.ip4mac(ip:match("^[\[::ffff:]*(%d+.%d+%.%d+%.%d+)\]*$"))
if mac and luci.http.formvalue("accept") then
os.execute("luci-splash add "..mac.." >/dev/null 2>&1")
luci.http.redirect(luci.model.uci.cursor():get("freifunk", "community", "homepage"))
else
luci.http.redirect(luci.dispatcher.build_url())
end
end
|
applications/luci-splash: properly fix mac address detection in mixed IPv4/IPv6 environments (thanks stargieg)
|
applications/luci-splash: properly fix mac address detection in mixed IPv4/IPv6 environments (thanks stargieg)
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@4734 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
|
305929ef82ceb9cd02e027b69e2c21a4b28ab935
|
test_scripts/Polices/build_options/007_ATF_P_TC_Policy_Table_Update_Trigger_After_N_Days_HTTP.lua
|
test_scripts/Polices/build_options/007_ATF_P_TC_Policy_Table_Update_Trigger_After_N_Days_HTTP.lua
|
---------------------------------------------------------------------------------------------
-- Requirement summary:
-- [PTU] Trigger: days
--
-- Description:
-- If the difference between current system time value_2 and system time value_1 when the previous
-- UpdatedPollicyTable was applied is equal or greater than to the value of "exchange_after_x_days"
-- field ("module_config" section) of policies database SDL must trigger a PolicyTableUpdate sequence
-- 1. Used preconditions:
-- SDL is built with "-DEXTENDED_POLICY: HTTP" flag
-- Application is registered.
-- The date previous PTU was received is 01.01.2016
-- the value in PT "module_config"->"'exchange_after_x_days '"is set to 150
-- 2. Performed steps:
-- SDL gets the current date 06.06.2016, it's more than 150 days after the last PTU
--
-- Expected result:
-- SDL initiates PTU: SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED)
-- PTS is created by SDL: SDL-> HMI: SDL.PolicyUpdate() //PTU sequence started
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--ToDo: Should be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed
config.defaultProtocolVersion = 2
--[[ Required Shared libraries ]]
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
local commonSteps = require ('user_modules/shared_testcases/commonSteps')
local testCasesForPolicyTableSnapshot = require ('user_modules/shared_testcases/testCasesForPolicyTableSnapshot')
local commonTestCases = require ('user_modules/shared_testcases/commonTestCases')
local commonPreconditions = require('user_modules/shared_testcases/commonPreconditions')
--[[ Local Variables ]]
local exchangeDays = testCasesForPolicyTableSnapshot:get_data_from_Preloaded_PT("module_config.exchange_after_x_days")
local currentSystemDaysAfterEpoch
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFiles()
commonSteps:DeletePolicyTable()
commonPreconditions:Connecttest_without_ExitBySDLDisconnect_WithoutOpenConnectionRegisterApp("connecttest_ConnectMobile.lua")
--[[ Local Functions ]]
local function CreatePTUFromExisted()
os.execute('cp files/ptu_general.json files/tmp_PTU.json')
end
local function DeleteTmpPTU()
os.execute('rm files/tmp_PTU.json')
end
local function getSystemDaysAfterEpoch()
return math.floor(os.time()/86400)
end
local function setPtExchangedXDaysAfterEpochInDB(daysAfterEpochFromPTS)
local pathToDB = config.pathToSDL .. "storage/policy.sqlite"
local DBQuery = 'sqlite3 ' .. pathToDB .. ' \"UPDATE module_meta SET pt_exchanged_x_days_after_epoch = ' .. daysAfterEpochFromPTS .. ' WHERE rowid = 1;\"'
os.execute(DBQuery)
os.execute(" sleep 1 ")
end
CreatePTUFromExisted()
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
require("user_modules/AppTypes")
local mobile_session = require('mobile_session')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:Precondition_Update_Policy_With_Exchange_After_X_Days_Value()
currentSystemDaysAfterEpoch = getSystemDaysAfterEpoch()
local CorIdSystemRequest = self.mobileSession:SendRPC("SystemRequest", { requestType = "HTTP", fileName = "PolicyTableUpdate", },"files/tmp_PTU.json")
EXPECT_RESPONSE(CorIdSystemRequest, { success = true, resultCode = "SUCCESS"})
EXPECT_HMICALL("BasicCommunication.SystemRequest"):Times(0)
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status="UP_TO_DATE"})
end
function Test.Precondition_StopSDL()
StopSDL()
end
function Test.Precondition_SetExchangedXDaysInDB()
setPtExchangedXDaysAfterEpochInDB(currentSystemDaysAfterEpoch - exchangeDays)
end
function Test.Precondition_StartSDL_FirstLifeCycle()
StartSDL(config.pathToSDL, config.ExitOnCrash)
end
function Test:Precondition_InitHMI_FirstLifeCycle()
self:initHMI()
end
function Test:Precondition_InitHMI_onReady_FirstLifeCycle()
self:initHMI_onReady()
end
function Test:Precondition_ConnectMobile_FirstLifeCycle()
self:connectMobile()
end
function Test:Precondition_StartSession()
self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection)
self.mobileSession:StartService(7)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_Register_App_And_Check_That_PTU_Triggered()
local CorIdRAI = self.mobileSession:SendRPC("RegisterAppInterface",
{
syncMsgVersion =
{
majorVersion = 3,
minorVersion = 0
},
appName = "Test Application",
isMediaApplication = true,
languageDesired = "EN-US",
hmiDisplayLanguageDesired = "EN-US",
appID = "0000001",
deviceInfo =
{
os = "Android",
carrier = "Megafon",
firmwareRev = "Name: Linux, Version: 3.4.0-perf",
osVersion = "4.4.2",
maxNumberRFCOMMPorts = 1
}
})
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered",
{
application =
{
appName = "Test Application",
policyAppID = "0000001",
isMediaApplication = true,
hmiDisplayLanguageDesired = "EN-US",
deviceInfo =
{
name = "127.0.0.1",
id = config.deviceMAC,
transportType = "WIFI",
isSDLAllowed = true
}
}
})
EXPECT_RESPONSE(CorIdRAI, { success = true, resultCode = "SUCCESS"})
EXPECT_HMICALL("BasicCommunication.PolicyUpdate"):Times(0)
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status="UPDATE_NEEDED"})
EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "HTTP"})
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status="UPDATING"})
end
--[[ Postcondition ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_DeleteTmpPTU()
DeleteTmpPTU()
end
function Test.Postcondition_Stop_SDL()
StopSDL()
end
return Test
|
---------------------------------------------------------------------------------------------
-- Requirement summary:
-- [PTU] Trigger: days
--
-- Description:
-- If the difference between current system time value_2 and system time value_1 when the previous
-- UpdatedPollicyTable was applied is equal or greater than to the value of "exchange_after_x_days"
-- field ("module_config" section) of policies database SDL must trigger a PolicyTableUpdate sequence
-- 1. Used preconditions:
-- SDL is built with "-DEXTENDED_POLICY: HTTP" flag
-- Application is registered.
-- The date previous PTU was received is 01.01.2016
-- the value in PT "module_config"->"'exchange_after_x_days '"is set to 150
-- 2. Performed steps:
-- SDL gets the current date 06.06.2016, it's more than 150 days after the last PTU
--
-- Expected result:
-- SDL initiates PTU: SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED)
-- PTS is created by SDL: SDL-> HMI: SDL.PolicyUpdate() //PTU sequence started
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
config.defaultProtocolVersion = 2
--[[ Required Shared libraries ]]
local commonSteps = require ('user_modules/shared_testcases/commonSteps')
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
--[[ Local Variables ]]
local exchangeDays = 30
local currentSystemDaysAfterEpoch
--[[ General Precondition before ATF start ]]
commonFunctions:SDLForceStop()
commonSteps:DeleteLogsFiles()
commonSteps:DeletePolicyTable()
--[[ Local Functions ]]
local function CreatePTUFromExisted()
os.execute('cp files/ptu_general.json files/tmp_PTU.json')
end
local function DeleteTmpPTU()
os.execute('rm files/tmp_PTU.json')
end
local function getSystemDaysAfterEpoch()
return math.floor(os.time()/86400)
end
local function setPtExchangedXDaysAfterEpochInDB(daysAfterEpochFromPTS)
local pathToDB = config.pathToSDL .. "storage/policy.sqlite"
local DBQuery = 'sqlite3 ' .. pathToDB .. ' \"UPDATE module_meta SET pt_exchanged_x_days_after_epoch = ' .. daysAfterEpochFromPTS .. ' WHERE rowid = 1;\"'
os.execute(DBQuery)
os.execute(" sleep 1 ")
end
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
require('user_modules/AppTypes')
local mobile_session = require('mobile_session')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test.Preconditions_Set_Exchange_After_X_Days_For_PTU()
CreatePTUFromExisted()
end
function Test:Precondition_Update_Policy_With_Exchange_After_X_Days_Value()
currentSystemDaysAfterEpoch = getSystemDaysAfterEpoch()
local CorIdSystemRequest = self.mobileSession:SendRPC("SystemRequest", { requestType = "HTTP", fileName = "PolicyTableUpdate" },"files/tmp_PTU.json")
EXPECT_RESPONSE(CorIdSystemRequest, { success = true, resultCode = "SUCCESS" })
EXPECT_HMICALL("BasicCommunication.SystemRequest"):Times(0)
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", { status="UP_TO_DATE" })
end
function Test.Precondition_StopSDL()
StopSDL()
end
function Test.Precondition_SetExchangedXDaysInDB()
setPtExchangedXDaysAfterEpochInDB(currentSystemDaysAfterEpoch - exchangeDays - 1)
end
function Test.Precondition_StartSDL_FirstLifeCycle()
StartSDL(config.pathToSDL, config.ExitOnCrash)
end
function Test:Precondition_InitHMI_FirstLifeCycle()
self:initHMI()
end
function Test:Precondition_InitHMI_onReady_FirstLifeCycle()
self:initHMI_onReady()
end
function Test:Precondition_ConnectMobile_FirstLifeCycle()
self:connectMobile()
end
function Test:Precondition_StartSession()
self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection)
self.mobileSession:StartService(7)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_Register_App_And_Check_That_PTU_Triggered()
local CorIdRAI = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams)
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered")
EXPECT_RESPONSE(CorIdRAI, { success = true, resultCode = "SUCCESS" })
EXPECT_HMICALL("BasicCommunication.PolicyUpdate"):Times(0)
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", { status="UPDATE_NEEDED" }, { status="UPDATING" }):Times(AtLeast(1))
EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "HTTP" })
end
--[[ Postcondition ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_DeleteTmpPTU()
DeleteTmpPTU()
end
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
|
19d82e2d4867b6cbac407f5aecaba5ea69a556d5
|
LUA/spec/eep/EepFunktionen_spec.lua
|
LUA/spec/eep/EepFunktionen_spec.lua
|
describe("EepFunktionen.lua", function()
require("ak.eep.AkEepFunktionen")
it("EEPVer steht auf \"15\"", function()
assert.are.equals("15", EEPVer)
end)
it("print() Funktion ", function()
clearlog()
end)
describe("EEPSetSignal", function()
describe("setzt Signal 2 auf Stellung 4", function()
EEPSetSignal(2, 4, 1)
it("gibt 4 zurück bei EEPGetSignal(2)", function()
assert.are.equals(4, EEPGetSignal(2))
end)
end)
describe("setzt Signal 2 auf Stellung 3", function()
EEPSetSignal(2, 3, 1)
it("gibt 4 zurück bei EEPGetSignal(3)", function()
assert.are.equals(3, EEPGetSignal(2))
end)
end)
end)
-- more tests pertaining to the top level
end)
|
describe("EepFunktionen.lua", function()
require("ak.eep.AkEepFunktionen")
it("EEPVer steht auf \"15\"", function()
assert.are.equals(15, EEPVer)
end)
it("print() Funktion ", function()
clearlog()
end)
describe("EEPSetSignal", function()
describe("setzt Signal 2 auf Stellung 4", function()
EEPSetSignal(2, 4, 1)
it("gibt 4 zurück bei EEPGetSignal(2)", function()
assert.are.equals(4, EEPGetSignal(2))
end)
end)
describe("setzt Signal 2 auf Stellung 3", function()
EEPSetSignal(2, 3, 1)
it("gibt 4 zurück bei EEPGetSignal(3)", function()
assert.are.equals(3, EEPGetSignal(2))
end)
end)
end)
-- more tests pertaining to the top level
end)
|
fix busted error - correct EEP-Version (number)
|
fix busted error - correct EEP-Version (number)
|
Lua
|
mit
|
Andreas-Kreuz/ak-lua-skripte-fuer-eep,Andreas-Kreuz/ak-lua-skripte-fuer-eep
|
5ca43e2c919987b702e2a49df361786563bfca9b
|
classes/diglot.lua
|
classes/diglot.lua
|
local plain = SILE.require("classes/plain");
local diglot = std.tree.clone(plain);
SILE.require("packages/counters");
SILE.scratch.counters.folio = { value = 1, display = "arabic" };
SILE.scratch.diglot = {}
if not(SILE.scratch.headers) then SILE.scratch.headers = {}; end
diglot:declareFrame("a", {left = "8.3%", right = "48%", top = "11.6%", bottom = "80%" });
diglot:declareFrame("b", {left = "52%", right = "100% - left(a)", top = "top(a)", bottom = "bottom(a)" });
diglot:declareFrame("folio",{left = "left(a)", right = "right(b)", top = "bottom(a)+3%",bottom = "bottom(a)+5%" });
diglot.pageTemplate.firstContentFrame = diglot.pageTemplate.frames["a"];
diglot.leftTypesetter = SILE.defaultTypesetter {};
diglot.rightTypesetter = SILE.defaultTypesetter {};
diglot.leftTypesetter.parSepPattern= -1
diglot.rightTypesetter.parSepPattern= -1
local sync = function()
if (diglot.rightTypesetter.state.cursorY > diglot.leftTypesetter.state.cursorY) then
diglot.leftTypesetter:pushVglue({ height = diglot.rightTypesetter.state.cursorY - diglot.leftTypesetter.state.cursorY })
elseif (diglot.rightTypesetter.state.cursorY < diglot.leftTypesetter.state.cursorY) then
diglot.rightTypesetter:pushVglue({ height = diglot.leftTypesetter.state.cursorY - diglot.rightTypesetter.state.cursorY })
end
diglot.rightTypesetter:leaveHmode(1);
diglot.leftTypesetter:leaveHmode();
diglot.rightTypesetter:shipOut(0,1)
diglot.leftTypesetter:shipOut(0,1)
diglot.rightTypesetter:pushBack()
diglot.leftTypesetter:pushBack()
end
diglot.newPage = function()
diglot.rightTypesetter:leaveHmode(1);
diglot.leftTypesetter:leaveHmode(1);
diglot.leftTypesetter:init(diglot.pageTemplate.frames["a"])
diglot.rightTypesetter:init(diglot.pageTemplate.frames["b"])
SILE.typesetter = diglot.leftTypesetter;
plain.newPage()
return diglot.pageTemplate.frames["a"]
end
local pfont = function(options)
if (options.family) then SILE.documentState.fontFamily = options.family end
if (options.size) then SILE.documentState.fontSize = options.size end
if (options.weight) then SILE.documentState.fontWeight = options.weight end
if (options.style) then SILE.documentState.fontStyle = options.style end
if (options.variant) then SILE.documentState.fontVariant = options.variant end
if (options.language) then SILE.documentState.language = options.language end
end
SILE.registerCommand("leftfont", function(options, content)
SILE.scratch.diglot.leftfont = options
end)
SILE.registerCommand("rightfont", function(options, content)
SILE.scratch.diglot.rightfont = options
end)
SILE.registerCommand("left", function(options, content)
SILE.typesetter = diglot.leftTypesetter;
if (not SILE.typesetter.frame) then
SILE.typesetter:init(diglot.pageTemplate.frames["a"])
end
pfont(SILE.scratch.diglot.leftfont)
end)
SILE.registerCommand("right", function(options, content)
SILE.typesetter = diglot.rightTypesetter;
if (not SILE.typesetter.frame) then
SILE.typesetter:init(diglot.pageTemplate.frames["b"])
end
pfont(SILE.scratch.diglot.rightfont)
end)
SILE.registerCommand("sync", sync)
return diglot
|
local plain = SILE.require("classes/plain");
local diglot = std.tree.clone(plain);
SILE.require("packages/counters");
SILE.scratch.counters.folio = { value = 1, display = "arabic" };
SILE.scratch.diglot = {}
if not(SILE.scratch.headers) then SILE.scratch.headers = {}; end
diglot:declareFrame("a", {left = "8.3%", right = "48%", top = "11.6%", bottom = "80%" });
diglot:declareFrame("b", {left = "52%", right = "100% - left(a)", top = "top(a)", bottom = "bottom(a)" });
diglot:declareFrame("folio",{left = "left(a)", right = "right(b)", top = "bottom(a)+3%",bottom = "bottom(a)+5%" });
diglot.pageTemplate.firstContentFrame = diglot.pageTemplate.frames["a"];
diglot.leftTypesetter = SILE.defaultTypesetter {};
diglot.rightTypesetter = SILE.defaultTypesetter {};
diglot.leftTypesetter.parSepPattern= -1
diglot.rightTypesetter.parSepPattern= -1
local sync = function()
if (diglot.rightTypesetter.state.cursorY > diglot.leftTypesetter.state.cursorY) then
diglot.leftTypesetter:pushVglue({ height = diglot.rightTypesetter.state.cursorY - diglot.leftTypesetter.state.cursorY })
elseif (diglot.rightTypesetter.state.cursorY < diglot.leftTypesetter.state.cursorY) then
diglot.rightTypesetter:pushVglue({ height = diglot.leftTypesetter.state.cursorY - diglot.rightTypesetter.state.cursorY })
end
diglot.rightTypesetter:leaveHmode(1);
diglot.leftTypesetter:leaveHmode();
diglot.rightTypesetter:shipOut(0,1)
diglot.leftTypesetter:shipOut(0,1)
diglot.rightTypesetter:pushBack()
diglot.leftTypesetter:pushBack()
end
diglot.newPage = function()
diglot.rightTypesetter:leaveHmode(1);
diglot.leftTypesetter:leaveHmode(1);
diglot.leftTypesetter:init(diglot.pageTemplate.frames["a"])
diglot.rightTypesetter:init(diglot.pageTemplate.frames["b"])
SILE.typesetter = diglot.leftTypesetter;
plain.newPage()
return diglot.pageTemplate.frames["a"]
end
SILE.registerCommand("leftfont", function(options, content)
SILE.scratch.diglot.leftfont = options
end)
SILE.registerCommand("rightfont", function(options, content)
SILE.scratch.diglot.rightfont = options
end)
SILE.registerCommand("left", function(options, content)
SILE.typesetter = diglot.leftTypesetter;
if (not SILE.typesetter.frame) then
SILE.typesetter:init(diglot.pageTemplate.frames["a"])
end
SILE.Commands["font"](SILE.scratch.diglot.leftfont, {})
end)
SILE.registerCommand("right", function(options, content)
SILE.typesetter = diglot.rightTypesetter;
if (not SILE.typesetter.frame) then
SILE.typesetter:init(diglot.pageTemplate.frames["b"])
end
SILE.Commands["font"](SILE.scratch.diglot.rightfont, {})
end)
SILE.registerCommand("sync", sync)
return diglot
|
Fix font problems with parallels. (There are bigger unfixed problems.)
|
Fix font problems with parallels. (There are bigger unfixed problems.)
|
Lua
|
mit
|
simoncozens/sile,Nathan22Miles/sile,Nathan22Miles/sile,Nathan22Miles/sile,alerque/sile,WAKAMAZU/sile_fe,anthrotype/sile,simoncozens/sile,neofob/sile,shirat74/sile,neofob/sile,simoncozens/sile,anthrotype/sile,anthrotype/sile,neofob/sile,alerque/sile,alerque/sile,Nathan22Miles/sile,WAKAMAZU/sile_fe,WAKAMAZU/sile_fe,alerque/sile,anthrotype/sile,shirat74/sile,WAKAMAZU/sile_fe,neofob/sile,shirat74/sile,Nathan22Miles/sile,shirat74/sile,simoncozens/sile
|
0b4c7a55d5d4012debc85b1dfc7c180f395b2347
|
agents/monitoring/tests/net/init.lua
|
agents/monitoring/tests/net/init.lua
|
local table = require('table')
local async = require('async')
local ConnectionStream = require('monitoring/default/client/connection_stream').ConnectionStream
local misc = require('monitoring/default/util/misc')
local helper = require('../helper')
local timer = require('timer')
local fixtures = require('../fixtures')
local constants = require('constants')
local consts = require('../../default/util/constants')
local Endpoint = require('../../default/endpoint').Endpoint
local path = require('path')
local exports = {}
local child
exports['test_reconnects'] = function(test, asserts)
local options = {
datacenter = 'test',
stateDirectory = './tests',
tls = { rejectUnauthorized = false }
}
local client = ConnectionStream:new('id', 'token', 'guid', options)
local clientEnd = 0
local reconnect = 0
client:on('client_end', function(err)
clientEnd = clientEnd + 1
end)
client:on('reconnect', function(err)
reconnect = reconnect + 1
end)
local endpoints = {}
for _, address in pairs(fixtures.TESTING_AGENT_ENDPOINTS) do
-- split ip:port
table.insert(endpoints, Endpoint:new(address))
end
async.series({
function(callback)
child = helper.start_server(callback)
end,
function(callback)
client:on('handshake_success', misc.nCallbacks(callback, 3))
local endpoints = {}
for _, address in pairs(fixtures.TESTING_AGENT_ENDPOINTS) do
-- split ip:port
table.insert(endpoints, Endpoint:new(address))
end
client:createConnections(endpoints, function() end)
end,
function(callback)
helper.stop_server(child)
client:on('reconnect', misc.nCallbacks(callback, 3))
end,
function(callback)
child = helper.start_server(function()
client:on('handshake_success', misc.nCallbacks(callback, 3))
end)
end,
}, function()
helper.stop_server(child)
asserts.ok(clientEnd > 0)
asserts.ok(reconnect > 0)
test.done()
end)
end
exports['test_upgrades'] = function(test, asserts)
local options, client, endpoints
if true then
test.skip("Skip upgrades test until it is reliable")
return nil
end
-- Override the default download path
consts.DEFAULT_DOWNLOAD_PATH = path.join('.', 'tmp')
options = {
datacenter = 'test',
stateDirectory = './tests',
tls = { rejectUnauthorized = false }
}
local endpoints = {}
for _, address in pairs(fixtures.TESTING_AGENT_ENDPOINTS) do
-- split ip:port
table.insert(endpoints, Endpoint:new(address))
end
async.series({
function(callback)
child = helper.start_server(callback)
end,
function(callback)
client = ConnectionStream:new('id', 'token', 'guid', options)
client:on('handshake_success', misc.nCallbacks(callback, 3))
client:createConnections(endpoints, function() end)
end,
function(callback)
callback = misc.nCallbacks(callback, 4)
client:on('binary_upgrade.found', callback)
client:on('bundle_upgrade.found', callback)
client:on('bundle_upgrade.error', callback)
client:on('binary_upgrade.error', callback)
client:getUpgrade():forceUpgradeCheck()
end
}, function()
helper.stop_server(child)
client:done()
test.done()
end)
end
return exports
|
local table = require('table')
local async = require('async')
local ConnectionStream = require('monitoring/default/client/connection_stream').ConnectionStream
local misc = require('monitoring/default/util/misc')
local helper = require('../helper')
local timer = require('timer')
local fixtures = require('../fixtures')
local constants = require('constants')
local consts = require('../../default/util/constants')
local Endpoint = require('../../default/endpoint').Endpoint
local path = require('path')
local os = require('os')
local exports = {}
local child
exports['test_reconnects'] = function(test, asserts)
if os.type() == "win32" then
test.skip("Skip test_reconnects until a suitable SIGUSR1 replacement is used in runner.py")
return nil
end
local options = {
datacenter = 'test',
stateDirectory = './tests',
tls = { rejectUnauthorized = false }
}
local client = ConnectionStream:new('id', 'token', 'guid', options)
local clientEnd = 0
local reconnect = 0
client:on('client_end', function(err)
clientEnd = clientEnd + 1
end)
client:on('reconnect', function(err)
reconnect = reconnect + 1
end)
local endpoints = {}
for _, address in pairs(fixtures.TESTING_AGENT_ENDPOINTS) do
-- split ip:port
table.insert(endpoints, Endpoint:new(address))
end
async.series({
function(callback)
child = helper.start_server(callback)
end,
function(callback)
client:on('handshake_success', misc.nCallbacks(callback, 3))
local endpoints = {}
for _, address in pairs(fixtures.TESTING_AGENT_ENDPOINTS) do
-- split ip:port
table.insert(endpoints, Endpoint:new(address))
end
client:createConnections(endpoints, function() end)
end,
function(callback)
helper.stop_server(child)
client:on('reconnect', misc.nCallbacks(callback, 3))
end,
function(callback)
child = helper.start_server(function()
client:on('handshake_success', misc.nCallbacks(callback, 3))
end)
end,
}, function()
helper.stop_server(child)
asserts.ok(clientEnd > 0)
asserts.ok(reconnect > 0)
test.done()
end)
end
exports['test_upgrades'] = function(test, asserts)
local options, client, endpoints
if true then
test.skip("Skip upgrades test until it is reliable")
return nil
end
-- Override the default download path
consts.DEFAULT_DOWNLOAD_PATH = path.join('.', 'tmp')
options = {
datacenter = 'test',
stateDirectory = './tests',
tls = { rejectUnauthorized = false }
}
local endpoints = {}
for _, address in pairs(fixtures.TESTING_AGENT_ENDPOINTS) do
-- split ip:port
table.insert(endpoints, Endpoint:new(address))
end
async.series({
function(callback)
child = helper.start_server(callback)
end,
function(callback)
client = ConnectionStream:new('id', 'token', 'guid', options)
client:on('handshake_success', misc.nCallbacks(callback, 3))
client:createConnections(endpoints, function() end)
end,
function(callback)
callback = misc.nCallbacks(callback, 4)
client:on('binary_upgrade.found', callback)
client:on('bundle_upgrade.found', callback)
client:on('bundle_upgrade.error', callback)
client:on('binary_upgrade.error', callback)
client:getUpgrade():forceUpgradeCheck()
end
}, function()
helper.stop_server(child)
client:done()
test.done()
end)
end
return exports
|
Change the net test, test_reconnects, to skip itself as it uses a test_server_fixture_blocking that calls a SIGUSR1. Windows can't SIGUSR1, see: http://docs.python.org/2/library/signal.html#signal.signal We'll need a Windows specific way of emulating the SIGUSR1 functionality in the Agent.
|
Change the net test, test_reconnects, to skip itself as it uses
a test_server_fixture_blocking that calls a SIGUSR1. Windows can't
SIGUSR1, see: http://docs.python.org/2/library/signal.html#signal.signal
We'll need a Windows specific way of emulating the SIGUSR1 functionality
in the Agent.
|
Lua
|
apache-2.0
|
kans/zirgo,kans/zirgo,kans/zirgo
|
ca21c0d887b15a3f0f089d9a1e4dc98b0b66ed3a
|
agents/monitoring/lua/lib/protocol/connection.lua
|
agents/monitoring/lua/lib/protocol/connection.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 os = require('os')
local timer = require('timer')
local AgentProtocol = require('./protocol')
local Emitter = require('core').Emitter
local Error = require('core').Error
local JSON = require('json')
local fmt = require('string').format
local logging = require('logging')
local msg = require ('./messages')
local table = require('table')
local utils = require('utils')
-- Response timeouts in ms
local HANDSHAKE_TIMEOUT = 30000
local STATES = {}
STATES.INITIAL = 1
STATES.HANDSHAKE = 2
STATES.RUNNING = 3
local AgentProtocolConnection = Emitter:extend()
function AgentProtocolConnection:initialize(log, myid, token, conn)
assert(conn ~= nil)
assert(myid ~= nil)
self._log = log
self._myid = myid
self._token = token
self._conn = conn
self._conn:on('data', utils.bind(AgentProtocolConnection._onData, self))
self._buf = ""
self._msgid = 0
self._endpoints = { }
self._target = 'endpoint'
self._timeoutIds = {}
self._completions = {}
self:setState(STATES.INITIAL)
end
function AgentProtocolConnection:_onData(data)
local client = self._conn, obj, status
newline = data:find("\n")
if newline then
-- TODO: use a better buffer
self._buf = self._buf .. data:sub(1, newline - 1)
self._log(logging.DEBUG, fmt('RECV: %s', self._buf))
status, obj = pcall(JSON.parse, self._buf)
self._buf = data:sub(newline + 1)
if not status then
self._log(logging.ERROR, fmt('Failed to parse incoming line: line=%s,err=%s', self._buf, obj))
return
end
self:_processMessage(obj)
else
self._buf = self._buf .. data
end
end
function AgentProtocolConnection:_processMessage(msg)
-- request
if msg.method ~= nil then
self:emit('message', msg)
else
-- response
local key = msg.source .. ':' .. msg.id
local callback = self._completions[key]
if callback then
self._completions[key] = nil
callback(null, msg)
end
end
end
function AgentProtocolConnection:_send(msg, timeout, expectedCode, callback)
msg.target = 'endpoint'
msg.source = self._myid
local data = JSON.stringify(msg) .. '\n'
local key = msg.target .. ':' .. msg.id
if not expectedCode then expectedCode = 200 end
self._log(logging.DEBUG, fmt('SEND: %s', data))
if timeout then
self:_setCommandTimeoutHandler(key, timeout, callback)
end
if callback then
self._completions[key] = function(err, msg)
local result = nil
if msg and msg.result then result = msg.result end
if self._timeoutIds[key] ~= nil then
timer.clearTimer(self._timeoutIds[key])
end
if not err and msg and result and result.code and result.code ~= expectedCode then
err = Error:new(fmt('Unexpected status code returned: code=%s, message=%s', result.code, result.message))
end
callback(err, msg)
end
end
self._conn:write(data)
self._msgid = self._msgid + 1
end
--[[
Set a timeout handler for a function.
key - Command key.
timeout - Timeout in ms.
callback - Callback which is called with (err) if timeout has been reached.
]]--
function AgentProtocolConnection:_setCommandTimeoutHandler(key, timeout, callback)
local timeoutId
timeoutId = timer.setTimeout(timeout, function()
callback(Error:new(fmt('Command timeout, haven\'t received response in %d ms', timeout)))
end)
self._timeoutIds[key] = timeoutId
end
--[[ Protocol Functions ]]--
function AgentProtocolConnection:sendHandshakeHello(agentId, token, callback)
local m = msg.HandshakeHello:new(token, agentId)
self:_send(m:serialize(self._msgid), HANDSHAKE_TIMEOUT, 200, callback)
end
function AgentProtocolConnection:sendPing(timestamp, callback)
local m = msg.Ping:new(timestamp)
self:_send(m:serialize(self._msgid), nil, 200, callback)
end
function AgentProtocolConnection:sendSystemInfo(request, callback)
local m = msg.SystemInfoResponse:new(request)
self:_send(m:serialize(self._msgid), nil, 200, callback)
end
function AgentProtocolConnection:sendManifest(callback)
local m = msg.Manifest:new()
self:_send(m:serialize(self._msgid), nil, 200, callback)
end
function AgentProtocolConnection:sendMetrics(check, checkResults, callback)
local m = msg.MetricsRequest:new(check, checkResults)
self:_send(m:serialize(self._msgid), nil, 200, callback)
end
--[[ Public Functions ]] --
function AgentProtocolConnection:setState(state)
self._state = state
end
function AgentProtocolConnection:startHandshake(callback)
self:setState(STATES.HANDSHAKE)
self:sendHandshakeHello(self._myid, self._token, function(err, msg)
if err then
self._log(logging.ERR, fmt('handshake failed (message=%s)', err.message))
callback(err, msg)
return
end
if msg.result.code and msg.result.code ~= 200 then
err = Error:new(fmt('handshake failed [message=%s,code=%s]', msg.result.message, msg.result.code))
self._log(logging.ERR, err.message)
callback(err, msg)
return
end
self:setState(STATES.RUNNING)
self._log(logging.INFO, fmt('handshake successful (ping_interval=%dms)', msg.result.ping_interval))
callback(nil, msg)
end)
end
function AgentProtocolConnection:getManifest(callback)
self:sendManifest(function(err, response)
if err then
callback(err)
else
callback(nil, response.result)
end
end)
end
--[[
Process an async message
msg - The Incoming Message
]]--
function AgentProtocolConnection:execute(msg)
if msg.method == 'system.info' then
self:sendSystemInfo(msg)
else
local err = Error:new(fmt('invalid method [method=%s]', msg.method))
self:emit('error', err)
end
end
return AgentProtocolConnection
|
--[[
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 os = require('os')
local timer = require('timer')
local AgentProtocol = require('./protocol')
local Emitter = require('core').Emitter
local Error = require('core').Error
local JSON = require('json')
local fmt = require('string').format
local logging = require('logging')
local msg = require ('./messages')
local table = require('table')
local utils = require('utils')
-- Response timeouts in ms
local HANDSHAKE_TIMEOUT = 30000
local STATES = {}
STATES.INITIAL = 1
STATES.HANDSHAKE = 2
STATES.RUNNING = 3
local AgentProtocolConnection = Emitter:extend()
function AgentProtocolConnection:initialize(log, myid, token, conn)
assert(conn ~= nil)
assert(myid ~= nil)
self._log = log
self._myid = myid
self._token = token
self._conn = conn
self._conn:on('data', utils.bind(AgentProtocolConnection._onData, self))
self._buf = ''
self._msgid = 0
self._endpoints = { }
self._target = 'endpoint'
self._timeoutIds = {}
self._completions = {}
self:setState(STATES.INITIAL)
end
function AgentProtocolConnection:_popLine()
local line = false
local index = self._buf:find('\n')
if index then
line = self._buf:sub(0, index - 1)
self._buf = self._buf:sub(index + 1)
end
return line
end
function AgentProtocolConnection:_onData(data)
local obj, status, line
self._buf = self._buf .. data
line = self:_popLine()
while line do
status, obj = pcall(JSON.parse, line)
if not status then
self._log(logging.ERROR, fmt('Failed to parse incoming line: line="%s",err=%s', line, obj))
else
self:_processMessage(obj)
end
line = self:_popLine()
end
end
function AgentProtocolConnection:_processMessage(msg)
-- request
if msg.method ~= nil then
self:emit('message', msg)
else
-- response
local key = msg.source .. ':' .. msg.id
local callback = self._completions[key]
if callback then
self._completions[key] = nil
callback(null, msg)
end
end
end
function AgentProtocolConnection:_send(msg, timeout, expectedCode, callback)
msg.target = 'endpoint'
msg.source = self._myid
local data = JSON.stringify(msg) .. '\n'
local key = msg.target .. ':' .. msg.id
if not expectedCode then expectedCode = 200 end
self._log(logging.DEBUG, fmt('SEND: %s', data))
if timeout then
self:_setCommandTimeoutHandler(key, timeout, callback)
end
if callback then
self._completions[key] = function(err, msg)
local result = nil
if msg and msg.result then result = msg.result end
if self._timeoutIds[key] ~= nil then
timer.clearTimer(self._timeoutIds[key])
end
if not err and msg and result and result.code and result.code ~= expectedCode then
err = Error:new(fmt('Unexpected status code returned: code=%s, message=%s', result.code, result.message))
end
callback(err, msg)
end
end
self._conn:write(data)
self._msgid = self._msgid + 1
end
--[[
Set a timeout handler for a function.
key - Command key.
timeout - Timeout in ms.
callback - Callback which is called with (err) if timeout has been reached.
]]--
function AgentProtocolConnection:_setCommandTimeoutHandler(key, timeout, callback)
local timeoutId
timeoutId = timer.setTimeout(timeout, function()
callback(Error:new(fmt('Command timeout, haven\'t received response in %d ms', timeout)))
end)
self._timeoutIds[key] = timeoutId
end
--[[ Protocol Functions ]]--
function AgentProtocolConnection:sendHandshakeHello(agentId, token, callback)
local m = msg.HandshakeHello:new(token, agentId)
self:_send(m:serialize(self._msgid), HANDSHAKE_TIMEOUT, 200, callback)
end
function AgentProtocolConnection:sendPing(timestamp, callback)
local m = msg.Ping:new(timestamp)
self:_send(m:serialize(self._msgid), nil, 200, callback)
end
function AgentProtocolConnection:sendSystemInfo(request, callback)
local m = msg.SystemInfoResponse:new(request)
self:_send(m:serialize(self._msgid), nil, 200, callback)
end
function AgentProtocolConnection:sendManifest(callback)
local m = msg.Manifest:new()
self:_send(m:serialize(self._msgid), nil, 200, callback)
end
function AgentProtocolConnection:sendMetrics(check, checkResults, callback)
local m = msg.MetricsRequest:new(check, checkResults)
self:_send(m:serialize(self._msgid), nil, 200, callback)
end
--[[ Public Functions ]] --
function AgentProtocolConnection:setState(state)
self._state = state
end
function AgentProtocolConnection:startHandshake(callback)
self:setState(STATES.HANDSHAKE)
self:sendHandshakeHello(self._myid, self._token, function(err, msg)
if err then
self._log(logging.ERR, fmt('handshake failed (message=%s)', err.message))
callback(err, msg)
return
end
if msg.result.code and msg.result.code ~= 200 then
err = Error:new(fmt('handshake failed [message=%s,code=%s]', msg.result.message, msg.result.code))
self._log(logging.ERR, err.message)
callback(err, msg)
return
end
self:setState(STATES.RUNNING)
self._log(logging.INFO, fmt('handshake successful (ping_interval=%dms)', msg.result.ping_interval))
callback(nil, msg)
end)
end
function AgentProtocolConnection:getManifest(callback)
self:sendManifest(function(err, response)
if err then
callback(err)
else
callback(nil, response.result)
end
end)
end
--[[
Process an async message
msg - The Incoming Message
]]--
function AgentProtocolConnection:execute(msg)
if msg.method == 'system.info' then
self:sendSystemInfo(msg)
else
local err = Error:new(fmt('invalid method [method=%s]', msg.method))
self:emit('error', err)
end
end
return AgentProtocolConnection
|
Fix line parsing - use a better approach.
|
Fix line parsing - use a better approach.
|
Lua
|
apache-2.0
|
christopherjwang/rackspace-monitoring-agent,cp16net/virgo-base,kaustavha/rackspace-monitoring-agent,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent,cp16net/virgo-base,kaustavha/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent
|
4e068f89c3d477996a97cb2bd537320a1e7c9a41
|
ffi/framebuffer_android.lua
|
ffi/framebuffer_android.lua
|
local ffi = require("ffi")
local android = require("android")
local BB = require("ffi/blitbuffer")
local C = ffi.C
--[[ configuration for devices with an electric paper display controller ]]--
-- does the device has an e-ink screen?
local has_eink_screen, eink_platform = android.isEink()
-- does the device needs to handle all screen refreshes
local has_eink_full_support = android.isEinkFull()
-- for *some* rockchip devices
local rk_full, rk_partial, rk_a2, rk_auto = 1, 2, 3, 4 -- luacheck: ignore
-- for *some* freescale devices
local update_full, update_partial = 32, 0 -- luacheck: ignore
local waveform_du, waveform_gc16, waveform_regal = 1, 2, 7 -- luacheck: ignore
local partial_du, partial_gc16, partial_regal = waveform_du, waveform_gc16, waveform_regal -- luacheck: ignore
local full_gc16, full_regal = update_full + waveform_gc16, update_full + waveform_regal -- luacheck: ignore
-- update a region of the screen
local function updatePartial(mode, delay, x, y, w, h)
if not (x and y and w and h) then
x = 0
y = 0
w = android.screen.width
h = android.screen.height
end
if x < 0 then x = 0 end
if y < 0 then y = 0 end
if (x + w) > android.screen.width then w = android.screen.width - x end
if (y + h) > android.screen.height then h = android.screen.height - y end
android.einkUpdate(mode, delay, x, y, (x + w), (y + h))
end
-- update the entire screen
local function updateFull()
-- freescale ntx platform
if has_eink_screen and (eink_platform == "freescale") then
if has_eink_full_support then
-- we handle the screen entirely. No delay is needed
updatePartial(full_gc16, 0)
else
-- we're racing against system driver. Let the system win and apply
-- a full update after it.
updatePartial(full_gc16, 500)
end
-- rockchip rk3x platform
elseif has_eink_screen and (eink_platform == "rockchip") then
android.einkUpdate(rk_full)
end
end
local framebuffer = {}
function framebuffer:init()
-- we present this buffer to the outside
self.bb = BB.new(android.screen.width, android.screen.height, BB.TYPE_BBRGB32)
self.invert_bb = BB.new(android.screen.width, android.screen.height, BB.TYPE_BBRGB32)
-- TODO: should we better use these?
-- android.lib.ANativeWindow_getWidth(window)
-- android.lib.ANativeWindow_getHeight(window)
self.bb:fill(BB.COLOR_WHITE)
self:_updateWindow()
framebuffer.parent.init(self)
end
function framebuffer:_updateWindow()
if android.app.window == nil then
android.LOGW("cannot blit: no window")
return
end
local buffer = ffi.new("ANativeWindow_Buffer[1]")
if android.lib.ANativeWindow_lock(android.app.window, buffer, nil) < 0 then
android.LOGW("Unable to lock window buffer")
return
end
local bb = nil
if buffer[0].format == C.WINDOW_FORMAT_RGBA_8888
or buffer[0].format == C.WINDOW_FORMAT_RGBX_8888
then
bb = BB.new(buffer[0].width, buffer[0].height, BB.TYPE_BBRGB32, buffer[0].bits, buffer[0].stride*4, buffer[0].stride)
elseif buffer[0].format == C.WINDOW_FORMAT_RGB_565 then
bb = BB.new(buffer[0].width, buffer[0].height, BB.TYPE_BBRGB16, buffer[0].bits, buffer[0].stride*2, buffer[0].stride)
else
android.LOGE("unsupported window format!")
end
if bb then
local ext_bb = self.full_bb or self.bb
bb:setInverse(ext_bb:getInverse())
-- adapt to possible rotation changes
bb:setRotation(ext_bb:getRotation())
self.invert_bb:setRotation(ext_bb:getRotation())
if ext_bb:getInverse() == 1 then
self.invert_bb:invertblitFrom(ext_bb)
bb:blitFrom(self.invert_bb)
else
bb:blitFrom(ext_bb)
end
end
android.lib.ANativeWindow_unlockAndPost(android.app.window);
end
function framebuffer:refreshFullImp(x, y, w, h)
self:_updateWindow()
updateFull()
end
function framebuffer:refreshPartialImp(x, y, w, h)
self:_updateWindow()
if has_eink_full_support then
updatePartial(partial_regal, 0, x, y, w, h)
end
end
function framebuffer:refreshFlashPartialImp(x, y, w, h)
self:_updateWindow()
if has_eink_full_support then
updatePartial(full_regal, 0, x, y, w, h)
end
end
function framebuffer:refreshUIImp(x, y, w, h)
self:_updateWindow()
if has_eink_full_support then
updatePartial(partial_regal, 0, x, y, w, h)
end
end
function framebuffer:refreshFlashUIImp(x, y, w, h)
self:_updateWindow()
if has_eink_full_support then
updatePartial(full_regal, 0, x, y, w, h)
end
end
function framebuffer:refreshFastImp(x, y, w, h)
self:_updateWindow()
if has_eink_full_support then
updatePartial(partial_du, 0, x, y, w, h)
end
end
return require("ffi/framebuffer"):extend(framebuffer)
|
local ffi = require("ffi")
local android = require("android")
local BB = require("ffi/blitbuffer")
local C = ffi.C
--[[ configuration for devices with an electric paper display controller ]]--
-- does the device has an e-ink screen?
local has_eink_screen, eink_platform = android.isEink()
-- does the device needs to handle all screen refreshes
local has_eink_full_support = android.isEinkFull()
-- for *some* rockchip devices
local rk_full, rk_partial, rk_a2, rk_auto = 1, 2, 3, 4 -- luacheck: ignore
-- for *some* freescale devices
local update_full, update_partial = 32, 0 -- luacheck: ignore
local waveform_du, waveform_gc16, waveform_regal = 1, 2, 7 -- luacheck: ignore
local partial_du, partial_gc16, partial_regal = waveform_du, waveform_gc16, waveform_regal -- luacheck: ignore
local full_gc16, full_regal = update_full + waveform_gc16, update_full + waveform_regal -- luacheck: ignore
local framebuffer = {}
-- update a region of the screen
function framebuffer:_updatePartial(mode, delay, x, y, w, h)
local bb = self.full_bb or self.bb
w, x = BB.checkBounds(w or bb:getWidth(), x or 0, 0, bb:getWidth(), 0xFFFF)
h, y = BB.checkBounds(h or bb:getHeight(), y or 0, 0, bb:getHeight(), 0xFFFF)
x, y, w, h = bb:getPhysicalRect(x, y, w, h)
android.einkUpdate(mode, delay, x, y, (x + w), (y + h))
end
-- update the entire screen
function framebuffer:_updateFull()
-- freescale ntx platform
if has_eink_screen and (eink_platform == "freescale") then
if has_eink_full_support then
-- we handle the screen entirely. No delay is needed
self:_updatePartial(full_gc16, 0)
else
-- we're racing against system driver. Let the system win and apply
-- a full update after it.
self:_updatePartial(full_gc16, 500)
end
-- rockchip rk3x platform
elseif has_eink_screen and (eink_platform == "rockchip") then
android.einkUpdate(rk_full)
end
end
function framebuffer:init()
-- we present this buffer to the outside
self.bb = BB.new(android.screen.width, android.screen.height, BB.TYPE_BBRGB32)
self.invert_bb = BB.new(android.screen.width, android.screen.height, BB.TYPE_BBRGB32)
-- TODO: should we better use these?
-- android.lib.ANativeWindow_getWidth(window)
-- android.lib.ANativeWindow_getHeight(window)
self.bb:fill(BB.COLOR_WHITE)
self:_updateWindow()
framebuffer.parent.init(self)
end
function framebuffer:_updateWindow()
if android.app.window == nil then
android.LOGW("cannot blit: no window")
return
end
local buffer = ffi.new("ANativeWindow_Buffer[1]")
if android.lib.ANativeWindow_lock(android.app.window, buffer, nil) < 0 then
android.LOGW("Unable to lock window buffer")
return
end
local bb = nil
if buffer[0].format == C.WINDOW_FORMAT_RGBA_8888
or buffer[0].format == C.WINDOW_FORMAT_RGBX_8888
then
bb = BB.new(buffer[0].width, buffer[0].height, BB.TYPE_BBRGB32, buffer[0].bits, buffer[0].stride*4, buffer[0].stride)
elseif buffer[0].format == C.WINDOW_FORMAT_RGB_565 then
bb = BB.new(buffer[0].width, buffer[0].height, BB.TYPE_BBRGB16, buffer[0].bits, buffer[0].stride*2, buffer[0].stride)
else
android.LOGE("unsupported window format!")
end
if bb then
local ext_bb = self.full_bb or self.bb
bb:setInverse(ext_bb:getInverse())
-- adapt to possible rotation changes
bb:setRotation(ext_bb:getRotation())
self.invert_bb:setRotation(ext_bb:getRotation())
if ext_bb:getInverse() == 1 then
self.invert_bb:invertblitFrom(ext_bb)
bb:blitFrom(self.invert_bb)
else
bb:blitFrom(ext_bb)
end
end
android.lib.ANativeWindow_unlockAndPost(android.app.window);
end
function framebuffer:refreshFullImp(x, y, w, h)
self:_updateWindow()
self:_updateFull()
end
function framebuffer:refreshPartialImp(x, y, w, h)
self:_updateWindow()
if has_eink_full_support then
self:_updatePartial(partial_regal, 0, x, y, w, h)
end
end
function framebuffer:refreshFlashPartialImp(x, y, w, h)
self:_updateWindow()
if has_eink_full_support then
self:_updatePartial(full_regal, 0, x, y, w, h)
end
end
function framebuffer:refreshUIImp(x, y, w, h)
self:_updateWindow()
if has_eink_full_support then
self:_updatePartial(partial_regal, 0, x, y, w, h)
end
end
function framebuffer:refreshFlashUIImp(x, y, w, h)
self:_updateWindow()
if has_eink_full_support then
self:_updatePartial(full_regal, 0, x, y, w, h)
end
end
function framebuffer:refreshFastImp(x, y, w, h)
self:_updateWindow()
if has_eink_full_support then
self:_updatePartial(partial_du, 0, x, y, w, h)
end
end
return require("ffi/framebuffer"):extend(framebuffer)
|
[Android] Fix partial updates in landscape orientation (#1029)
|
[Android] Fix partial updates in landscape orientation (#1029)
|
Lua
|
agpl-3.0
|
Frenzie/koreader-base,koreader/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base,NiLuJe/koreader-base,koreader/koreader-base,Frenzie/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base
|
833774664548775c9b1139aff2203afb571e8379
|
src/tools/clang.lua
|
src/tools/clang.lua
|
--
-- clang.lua
-- Clang toolset adapter for Premake
-- Copyright (c) 2013 Jason Perkins and the Premake project
--
premake.tools.clang = {}
local clang = premake.tools.clang
local gcc = premake.tools.gcc
local config = premake.config
--
-- Build a list of flags for the C preprocessor corresponding to the
-- settings in a particular project configuration.
--
-- @param cfg
-- The project configuration.
-- @return
-- An array of C preprocessor flags.
--
function clang.getcppflags(cfg)
-- Just pass through to GCC for now
local flags = gcc.getcppflags(cfg)
return flags
end
--
-- Build a list of C compiler flags corresponding to the settings in
-- a particular project configuration. These flags are exclusive
-- of the C++ compiler flags, there is no overlap.
--
-- @param cfg
-- The project configuration.
-- @return
-- An array of C compiler flags.
--
function clang.getcflags(cfg)
-- Just pass through to GCC for now
local flags = gcc.getcflags(cfg)
return flags
end
--
-- Build a list of C++ compiler flags corresponding to the settings
-- in a particular project configuration. These flags are exclusive
-- of the C compiler flags, there is no overlap.
--
-- @param cfg
-- The project configuration.
-- @return
-- An array of C++ compiler flags.
--
function clang.getcxxflags(cfg)
-- Just pass through to GCC for now
local flags = gcc.getcxxflags(cfg)
return flags
end
--
-- Returns a list of defined preprocessor symbols, decorated for
-- the compiler command line.
--
-- @param defines
-- An array of preprocessor symbols to define; as an array of
-- string values.
-- @return
-- An array of symbols with the appropriate flag decorations.
--
function clang.getdefines(defines)
-- Just pass through to GCC for now
local flags = gcc.getdefines(defines)
return flags
end
function clang.getundefines(undefines)
-- Just pass through to GCC for now
local flags = gcc.getundefines(undefines)
return flags
end
--
-- Returns a list of forced include files, decorated for the compiler
-- command line.
--
-- @param cfg
-- The project configuration.
-- @return
-- An array of force include files with the appropriate flags.
--
function clang.getforceincludes(cfg)
-- Just pass through to GCC for now
local flags = gcc.getforceincludes(cfg)
return flags
end
--
-- Returns a list of include file search directories, decorated for
-- the compiler command line.
--
-- @param cfg
-- The project configuration.
-- @param dirs
-- An array of include file search directories; as an array of
-- string values.
-- @return
-- An array of symbols with the appropriate flag decorations.
--
function clang.getincludedirs(cfg, dirs, sysdirs)
-- Just pass through to GCC for now
local flags = gcc.getincludedirs(cfg, dirs, sysdirs)
return flags
end
--
-- Build a list of linker flags corresponding to the settings in
-- a particular project configuration.
--
-- @param cfg
-- The project configuration.
-- @return
-- An array of linker flags.
--
clang.ldflags = {
architecture = {
x86 = "-m32",
x86_64 = "-m64",
},
flags = {
LinkTimeOptimization = "-flto",
},
kind = {
SharedLib = function(cfg)
local r = { iif(cfg.system == premake.MACOSX, "-dynamiclib", "-shared") }
if cfg.system == "windows" and not cfg.flags.NoImportLib then
table.insert(r, '-Wl,--out-implib="' .. cfg.linktarget.relpath .. '"')
end
return r
end,
WindowedApp = function(cfg)
if cfg.system == premake.WINDOWS then return "-mwindows" end
end,
},
system = {
wii = "$(MACHDEP)",
}
}
function clang.getldflags(cfg)
local flags = config.mapFlags(cfg, clang.ldflags)
return flags
end
--
-- Build a list of additional library directories for a particular
-- project configuration, decorated for the tool command line.
--
-- @param cfg
-- The project configuration.
-- @return
-- An array of decorated additional library directories.
--
function clang.getLibraryDirectories(cfg)
-- Just pass through to GCC for now
local flags = gcc.getLibraryDirectories(cfg)
return flags
end
--
-- Build a list of libraries to be linked for a particular project
-- configuration, decorated for the linker command line.
--
-- @param cfg
-- The project configuration.
-- @param systemOnly
-- Boolean flag indicating whether to link only system libraries,
-- or system libraries and sibling projects as well.
-- @return
-- A list of libraries to link, decorated for the linker.
--
function clang.getlinks(cfg, systemOnly)
-- Just pass through to GCC for now
return gcc.getlinksonly(cfg, systemOnly)
end
--
-- Return a list of makefile-specific configuration rules. This will
-- be going away when I get a chance to overhaul these adapters.
--
-- @param cfg
-- The project configuration.
-- @return
-- A list of additional makefile rules.
--
function clang.getmakesettings(cfg)
-- Just pass through to GCC for now
local flags = gcc.getmakesettings(cfg)
return flags
end
--
-- Retrieves the executable command name for a tool, based on the
-- provided configuration and the operating environment. I will
-- be moving these into global configuration blocks when I get
-- the chance.
--
-- @param cfg
-- The configuration to query.
-- @param tool
-- The tool to fetch, one of "cc" for the C compiler, "cxx" for
-- the C++ compiler, or "ar" for the static linker.
-- @return
-- The executable command name for a tool, or nil if the system's
-- default value should be used.
--
clang.tools = {
cc = "clang",
cxx = "clang++",
ar = "ar"
}
function clang.gettoolname(cfg, tool)
return clang.tools[tool]
end
|
--
-- clang.lua
-- Clang toolset adapter for Premake
-- Copyright (c) 2013 Jason Perkins and the Premake project
--
premake.tools.clang = {}
local clang = premake.tools.clang
local gcc = premake.tools.gcc
local config = premake.config
--
-- Build a list of flags for the C preprocessor corresponding to the
-- settings in a particular project configuration.
--
-- @param cfg
-- The project configuration.
-- @return
-- An array of C preprocessor flags.
--
function clang.getcppflags(cfg)
-- Just pass through to GCC for now
local flags = gcc.getcppflags(cfg)
return flags
end
--
-- Build a list of C compiler flags corresponding to the settings in
-- a particular project configuration. These flags are exclusive
-- of the C++ compiler flags, there is no overlap.
--
-- @param cfg
-- The project configuration.
-- @return
-- An array of C compiler flags.
--
clang.cflags = {
architecture = gcc.cflags.architecture,
flags = gcc.cflags.flags,
floatingpoint = gcc.cflags.floatingpoint,
strictaliasing = gcc.cflags.strictaliasing,
optimize = {
Off = "-O0",
On = "-O2",
Debug = "-O0",
Full = "-O3",
Size = "-Os",
Speed = "-O3",
},
pic = gcc.cflags.pic,
vectorextensions = gcc.cflags.vectorextensions,
warnings = gcc.cflags.warnings
}
function clang.getcflags(cfg)
local flags = config.mapFlags(cfg, clang.cflags)
flags = table.join(flags, clang.getwarnings(cfg))
return flags
end
function clang.getwarnings(cfg)
-- Just pass through to GCC for now
return gcc.getwarnings(cfg)
end
--
-- Build a list of C++ compiler flags corresponding to the settings
-- in a particular project configuration. These flags are exclusive
-- of the C compiler flags, there is no overlap.
--
-- @param cfg
-- The project configuration.
-- @return
-- An array of C++ compiler flags.
--
function clang.getcxxflags(cfg)
-- Just pass through to GCC for now
local flags = gcc.getcxxflags(cfg)
return flags
end
--
-- Returns a list of defined preprocessor symbols, decorated for
-- the compiler command line.
--
-- @param defines
-- An array of preprocessor symbols to define; as an array of
-- string values.
-- @return
-- An array of symbols with the appropriate flag decorations.
--
function clang.getdefines(defines)
-- Just pass through to GCC for now
local flags = gcc.getdefines(defines)
return flags
end
function clang.getundefines(undefines)
-- Just pass through to GCC for now
local flags = gcc.getundefines(undefines)
return flags
end
--
-- Returns a list of forced include files, decorated for the compiler
-- command line.
--
-- @param cfg
-- The project configuration.
-- @return
-- An array of force include files with the appropriate flags.
--
function clang.getforceincludes(cfg)
-- Just pass through to GCC for now
local flags = gcc.getforceincludes(cfg)
return flags
end
--
-- Returns a list of include file search directories, decorated for
-- the compiler command line.
--
-- @param cfg
-- The project configuration.
-- @param dirs
-- An array of include file search directories; as an array of
-- string values.
-- @return
-- An array of symbols with the appropriate flag decorations.
--
function clang.getincludedirs(cfg, dirs, sysdirs)
-- Just pass through to GCC for now
local flags = gcc.getincludedirs(cfg, dirs, sysdirs)
return flags
end
--
-- Build a list of linker flags corresponding to the settings in
-- a particular project configuration.
--
-- @param cfg
-- The project configuration.
-- @return
-- An array of linker flags.
--
clang.ldflags = {
architecture = {
x86 = "-m32",
x86_64 = "-m64",
},
flags = {
LinkTimeOptimization = "-flto",
},
kind = {
SharedLib = function(cfg)
local r = { iif(cfg.system == premake.MACOSX, "-dynamiclib", "-shared") }
if cfg.system == "windows" and not cfg.flags.NoImportLib then
table.insert(r, '-Wl,--out-implib="' .. cfg.linktarget.relpath .. '"')
end
return r
end,
WindowedApp = function(cfg)
if cfg.system == premake.WINDOWS then return "-mwindows" end
end,
},
system = {
wii = "$(MACHDEP)",
}
}
function clang.getldflags(cfg)
local flags = config.mapFlags(cfg, clang.ldflags)
return flags
end
--
-- Build a list of additional library directories for a particular
-- project configuration, decorated for the tool command line.
--
-- @param cfg
-- The project configuration.
-- @return
-- An array of decorated additional library directories.
--
function clang.getLibraryDirectories(cfg)
-- Just pass through to GCC for now
local flags = gcc.getLibraryDirectories(cfg)
return flags
end
--
-- Build a list of libraries to be linked for a particular project
-- configuration, decorated for the linker command line.
--
-- @param cfg
-- The project configuration.
-- @param systemOnly
-- Boolean flag indicating whether to link only system libraries,
-- or system libraries and sibling projects as well.
-- @return
-- A list of libraries to link, decorated for the linker.
--
function clang.getlinks(cfg, systemOnly)
-- Just pass through to GCC for now
return gcc.getlinksonly(cfg, systemOnly)
end
--
-- Return a list of makefile-specific configuration rules. This will
-- be going away when I get a chance to overhaul these adapters.
--
-- @param cfg
-- The project configuration.
-- @return
-- A list of additional makefile rules.
--
function clang.getmakesettings(cfg)
-- Just pass through to GCC for now
local flags = gcc.getmakesettings(cfg)
return flags
end
--
-- Retrieves the executable command name for a tool, based on the
-- provided configuration and the operating environment. I will
-- be moving these into global configuration blocks when I get
-- the chance.
--
-- @param cfg
-- The configuration to query.
-- @param tool
-- The tool to fetch, one of "cc" for the C compiler, "cxx" for
-- the C++ compiler, or "ar" for the static linker.
-- @return
-- The executable command name for a tool, or nil if the system's
-- default value should be used.
--
clang.tools = {
cc = "clang",
cxx = "clang++",
ar = "ar"
}
function clang.gettoolname(cfg, tool)
return clang.tools[tool]
end
|
Fix optimize 'Debug' for clang
|
Fix optimize 'Debug' for clang
The compiler flag '-Og' isn't valid for clang, so just turn
optimizations off when 'Debug' is specified.
|
Lua
|
bsd-3-clause
|
lizh06/premake-core,dcourtois/premake-core,soundsrc/premake-core,starkos/premake-core,xriss/premake-core,xriss/premake-core,dcourtois/premake-core,noresources/premake-core,premake/premake-core,bravnsgaard/premake-core,jstewart-amd/premake-core,aleksijuvani/premake-core,TurkeyMan/premake-core,lizh06/premake-core,mandersan/premake-core,premake/premake-core,premake/premake-core,dcourtois/premake-core,sleepingwit/premake-core,sleepingwit/premake-core,aleksijuvani/premake-core,aleksijuvani/premake-core,starkos/premake-core,dcourtois/premake-core,premake/premake-core,mendsley/premake-core,martin-traverse/premake-core,starkos/premake-core,martin-traverse/premake-core,LORgames/premake-core,dcourtois/premake-core,TurkeyMan/premake-core,CodeAnxiety/premake-core,CodeAnxiety/premake-core,xriss/premake-core,starkos/premake-core,dcourtois/premake-core,resetnow/premake-core,mendsley/premake-core,Zefiros-Software/premake-core,Blizzard/premake-core,premake/premake-core,noresources/premake-core,tvandijck/premake-core,jstewart-amd/premake-core,LORgames/premake-core,mandersan/premake-core,noresources/premake-core,jstewart-amd/premake-core,TurkeyMan/premake-core,jstewart-amd/premake-core,lizh06/premake-core,mendsley/premake-core,CodeAnxiety/premake-core,sleepingwit/premake-core,tvandijck/premake-core,mandersan/premake-core,LORgames/premake-core,lizh06/premake-core,noresources/premake-core,noresources/premake-core,sleepingwit/premake-core,resetnow/premake-core,xriss/premake-core,mendsley/premake-core,martin-traverse/premake-core,sleepingwit/premake-core,bravnsgaard/premake-core,tvandijck/premake-core,premake/premake-core,Blizzard/premake-core,soundsrc/premake-core,xriss/premake-core,bravnsgaard/premake-core,bravnsgaard/premake-core,resetnow/premake-core,LORgames/premake-core,TurkeyMan/premake-core,mandersan/premake-core,starkos/premake-core,mandersan/premake-core,mendsley/premake-core,CodeAnxiety/premake-core,martin-traverse/premake-core,Blizzard/premake-core,Zefiros-Software/premake-core,LORgames/premake-core,Zefiros-Software/premake-core,soundsrc/premake-core,Blizzard/premake-core,dcourtois/premake-core,starkos/premake-core,resetnow/premake-core,noresources/premake-core,Zefiros-Software/premake-core,TurkeyMan/premake-core,tvandijck/premake-core,noresources/premake-core,bravnsgaard/premake-core,CodeAnxiety/premake-core,starkos/premake-core,aleksijuvani/premake-core,premake/premake-core,jstewart-amd/premake-core,Blizzard/premake-core,Zefiros-Software/premake-core,aleksijuvani/premake-core,Blizzard/premake-core,resetnow/premake-core,soundsrc/premake-core,soundsrc/premake-core,tvandijck/premake-core
|
455943552ea93a7d4a2c8c50701ca9f82e33e835
|
mods/hbhunger/init.lua
|
mods/hbhunger/init.lua
|
if minetest.setting_getbool("enable_damage") then
hbhunger = {}
-- HUD statbar values
hbhunger.hunger = {}
hbhunger.hunger_out = {}
-- HUD item ids
local hunger_hud = {}
HUNGER_HUD_TICK = 1.0
--Some hunger settings
hbhunger.exhaustion = {} -- Exhaustion is experimental!
HUNGER_HUNGER_TICK = 800 -- time in seconds after that 1 hunger point is taken
HUNGER_EXHAUST_DIG = 3 -- exhaustion increased this value after digged node
HUNGER_EXHAUST_PLACE = 1 -- exhaustion increased this value after placed
HUNGER_EXHAUST_MOVE = 0.3 -- exhaustion increased this value if player movement detected
HUNGER_EXHAUST_LVL = 160 -- at what exhaustion player satiation gets lowerd
--load custom settings
local set = io.open(minetest.get_modpath("hbhunger").."/hbhunger.conf", "r")
if set then
dofile(minetest.get_modpath("hbhunger").."/hbhunger.conf")
set:close()
end
local function custom_hud(player)
hb.init_hudbar(player, "satiation", hbhunger.get_hunger(player))
end
dofile(minetest.get_modpath("hbhunger").."/hunger.lua")
-- register satiation hudbar
hb.register_hudbar("satiation", 0xFFFFFF, "Satiation", { icon = "hbhunger_icon.png", bar = "hbhunger_bar.png" }, 20, 30, false)
-- update hud elemtens if value has changed
local function update_hud(player)
local name = player:get_player_name()
--hunger
local h_out = tonumber(hbhunger.hunger_out[name])
local h = tonumber(hbhunger.hunger[name])
if h_out ~= h then
hbhunger.hunger_out[name] = h
hb.change_hudbar(player, "satiation", h)
end
end
hbhunger.get_hunger = function(player)
local inv = player:get_inventory()
if not inv then return nil end
local hgp = inv:get_stack("hunger", 1):get_count()
if hgp == 0 then
hgp = 21
inv:set_stack("hunger", 1, ItemStack({name=":", count=hgp}))
else
hgp = hgp
end
return hgp-1
end
hbhunger.set_hunger = function(player)
local inv = player:get_inventory()
local name = player:get_player_name()
local value = hbhunger.hunger[name]
if not inv or not value then return nil end
if value > 30 then value = 30 end
if value < 0 then value = 0 end
inv:set_stack("hunger", 1, ItemStack({name=":", count=value+1}))
return true
end
minetest.register_on_joinplayer(function(player)
local name = player:get_player_name()
local inv = player:get_inventory()
inv:set_size("hunger",1)
hbhunger.hunger[name] = hbhunger.get_hunger(player)
hbhunger.hunger_out[name] = hbhunger.hunger[name]
hbhunger.exhaustion[name] = 0
custom_hud(player)
hbhunger.set_hunger(player)
end)
minetest.register_on_respawnplayer(function(player)
-- reset hunger (and save)
local name = player:get_player_name()
hbhunger.hunger[name] = 20
hbhunger.set_hunger(player)
hbhunger.exhaustion[name] = 0
end)
<Mg> Avec Mithril armor : 7.5 seconds.
local main_timer = 0
local timer = 0
local timer2 = 0
minetest.register_globalstep(function(dtime)
main_timer = main_timer + dtime
timer = timer + dtime
timer2 = timer2 + dtime
if main_timer > HUNGER_HUD_TICK or timer > 10 or timer2 > HUNGER_HUNGER_TICK then
if main_timer > HUNGER_HUD_TICK then main_timer = 0 end
for _,player in ipairs(minetest.get_connected_players()) do
local name = player:get_player_name()
local h = tonumber(hbhunger.hunger[name])
local hp = player:get_hp()
local timerquot = 1 -- By default regen 0.5 hearth every 10sec
if pclasses.api.get_player_class(name) == "warrior" then
timerquot = 2 -- Black_Mithril armor = 0.5 hearth every 5.0sec
elseif pclasses.api.util.does_wear_full_armor(name, "mithril", false) then
timerquot = 1.33 -- Mithril armor = 0.5 hearth every 7.5sec
end
if timer > 10/timerquot then
-- heal player by 1 hp if not dead and satiation is > 15 (of 30)
if h > 15 and hp > 0 and player:get_breath() > 0 then
player:set_hp(hp+1)
-- or damage player by 1 hp if satiation is < 2 (of 30)
elseif h <= 1 then
if hp-1 >= 0 then player:set_hp(hp-1) end
end
end
-- lower satiation by 1 point after xx seconds
if timer2 > HUNGER_HUNGER_TICK then
if h > 0 then
h = h-1
hbhunger.hunger[name] = h
hbhunger.set_hunger(player)
end
end
-- update all hud elements
update_hud(player)
local controls = player:get_player_control()
-- Determine if the player is walking
if controls.up or controls.down or controls.left or controls.right then
hbhunger.handle_node_actions(nil, nil, player)
end
end
end
if timer > 10 then timer = 0 end
if timer2 > HUNGER_HUNGER_TICK then timer2 = 0 end
end)
end
|
if minetest.setting_getbool("enable_damage") then
hbhunger = {}
-- HUD statbar values
hbhunger.hunger = {}
hbhunger.hunger_out = {}
-- HUD item ids
local hunger_hud = {}
HUNGER_HUD_TICK = 1.0
--Some hunger settings
hbhunger.exhaustion = {} -- Exhaustion is experimental!
HUNGER_HUNGER_TICK = 800 -- time in seconds after that 1 hunger point is taken
HUNGER_EXHAUST_DIG = 3 -- exhaustion increased this value after digged node
HUNGER_EXHAUST_PLACE = 1 -- exhaustion increased this value after placed
HUNGER_EXHAUST_MOVE = 0.3 -- exhaustion increased this value if player movement detected
HUNGER_EXHAUST_LVL = 160 -- at what exhaustion player satiation gets lowerd
--load custom settings
local set = io.open(minetest.get_modpath("hbhunger").."/hbhunger.conf", "r")
if set then
dofile(minetest.get_modpath("hbhunger").."/hbhunger.conf")
set:close()
end
local function custom_hud(player)
hb.init_hudbar(player, "satiation", hbhunger.get_hunger(player))
end
dofile(minetest.get_modpath("hbhunger").."/hunger.lua")
-- register satiation hudbar
hb.register_hudbar("satiation", 0xFFFFFF, "Satiation", { icon = "hbhunger_icon.png", bar = "hbhunger_bar.png" }, 20, 30, false)
-- update hud elemtens if value has changed
local function update_hud(player)
local name = player:get_player_name()
--hunger
local h_out = tonumber(hbhunger.hunger_out[name])
local h = tonumber(hbhunger.hunger[name])
if h_out ~= h then
hbhunger.hunger_out[name] = h
hb.change_hudbar(player, "satiation", h)
end
end
hbhunger.get_hunger = function(player)
local inv = player:get_inventory()
if not inv then return nil end
local hgp = inv:get_stack("hunger", 1):get_count()
if hgp == 0 then
hgp = 21
inv:set_stack("hunger", 1, ItemStack({name=":", count=hgp}))
else
hgp = hgp
end
return hgp-1
end
hbhunger.set_hunger = function(player)
local inv = player:get_inventory()
local name = player:get_player_name()
local value = hbhunger.hunger[name]
if not inv or not value then return nil end
if value > 30 then value = 30 end
if value < 0 then value = 0 end
inv:set_stack("hunger", 1, ItemStack({name=":", count=value+1}))
return true
end
minetest.register_on_joinplayer(function(player)
local name = player:get_player_name()
local inv = player:get_inventory()
inv:set_size("hunger",1)
hbhunger.hunger[name] = hbhunger.get_hunger(player)
hbhunger.hunger_out[name] = hbhunger.hunger[name]
hbhunger.exhaustion[name] = 0
custom_hud(player)
hbhunger.set_hunger(player)
end)
minetest.register_on_respawnplayer(function(player)
-- reset hunger (and save)
local name = player:get_player_name()
hbhunger.hunger[name] = 20
hbhunger.set_hunger(player)
hbhunger.exhaustion[name] = 0
end)
local main_timer = 0
local timer = 0
local timer2 = 0
minetest.register_globalstep(function(dtime)
main_timer = main_timer + dtime
timer = timer + dtime
timer2 = timer2 + dtime
if main_timer > HUNGER_HUD_TICK or timer > 10 or timer2 > HUNGER_HUNGER_TICK then
if main_timer > HUNGER_HUD_TICK then main_timer = 0 end
for _,player in ipairs(minetest.get_connected_players()) do
local name = player:get_player_name()
local h = tonumber(hbhunger.hunger[name])
local hp = player:get_hp()
local timerquot = 1 -- By default regen 0.5 hearth every 10sec
if pclasses.api.get_player_class(name) == "warrior" then
timerquot = 2 -- Black_Mithril armor = 0.5 hearth every 5.0sec
elseif pclasses.api.util.does_wear_full_armor(name, "mithril", false) then
timerquot = 1.33 -- Mithril armor = 0.5 hearth every 7.5sec
end
if timer > 10/timerquot then
-- heal player by 1 hp if not dead and satiation is > 15 (of 30)
if h > 15 and hp > 0 and player:get_breath() > 0 then
player:set_hp(hp+1)
-- or damage player by 1 hp if satiation is < 2 (of 30)
elseif h <= 1 then
if hp-1 >= 0 then player:set_hp(hp-1) end
end
end
-- lower satiation by 1 point after xx seconds
if timer2 > HUNGER_HUNGER_TICK then
if h > 0 then
h = h-1
hbhunger.hunger[name] = h
hbhunger.set_hunger(player)
end
end
-- update all hud elements
update_hud(player)
local controls = player:get_player_control()
-- Determine if the player is walking
if controls.up or controls.down or controls.left or controls.right then
hbhunger.handle_node_actions(nil, nil, player)
end
end
end
if timer > 10 then timer = 0 end
if timer2 > HUNGER_HUNGER_TICK then timer2 = 0 end
end)
end
|
Fix crash
|
Fix crash
|
Lua
|
unlicense
|
Gael-de-Sailly/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,Coethium/server-minetestforfun,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,sys4-fr/server-minetestforfun,Ombridride/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Coethium/server-minetestforfun,crabman77/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server
|
96d5a0b9ee72c87ea43d6c41308dc3c703ca87fb
|
mod_register_web/mod_register_web.lua
|
mod_register_web/mod_register_web.lua
|
local captcha_options = module:get_option("captcha_options", {});
local nodeprep = require "util.encodings".stringprep.nodeprep;
local usermanager = require "core.usermanager";
local http = require "util.http";
function template(data)
-- Like util.template, but deals with plain text
return { apply = function(values) return (data:gsub("{([^}]+)}", values)); end }
end
local function get_template(name)
local fh = assert(module:load_resource("templates/"..name..".html"));
local data = assert(fh:read("*a"));
fh:close();
return template(data);
end
local function render(template, data)
return tostring(template.apply(data));
end
local register_tpl = get_template "register";
local success_tpl = get_template "success";
if next(captcha_options) ~= nil then
local recaptcha_tpl = get_template "recaptcha";
function generate_captcha(display_options)
return recaptcha_tpl.apply(setmetatable({
recaptcha_display_error = display_options and display_options.recaptcha_error
and ("&error="..display_options.recaptcha_error) or "";
}, {
__index = function (t, k)
if captcha_options[k] then return captcha_options[k]; end
module:log("error", "Missing parameter from captcha_options: %s", k);
end
}));
end
function verify_captcha(form, callback)
http.request("https://www.google.com/recaptcha/api/verify", {
body = http.formencode {
privatekey = captcha_options.recaptcha_private_key;
remoteip = request.conn:ip();
challenge = form.recaptcha_challenge_field;
response = form.recaptcha_response_field;
};
}, function (verify_result, code)
local verify_ok, verify_err = verify_result:match("^([^\n]+)\n([^\n]+)");
if verify_ok == "true" then
callback(true);
else
callback(false, verify_err)
end
end);
end
else
module:log("debug", "No Recaptcha options set, using fallback captcha")
local hmac_sha1 = require "util.hashes".hmac_sha1;
local secret = require "util.uuid".generate()
local ops = { '+', '-' };
local captcha_tpl = get_template "simplecaptcha";
function generate_captcha()
local op = ops[math.random(1, #ops)];
local x, y = math.random(1, 9)
repeat
y = math.random(1, 9);
until x ~= y;
local answer;
if op == '+' then
answer = x + y;
elseif op == '-' then
if x < y then
-- Avoid negative numbers
x, y = y, x;
end
answer = x - y;
end
local challenge = hmac_sha1(secret, answer, true);
return captcha_tpl.apply {
op = op, x = x, y = y, challenge = challenge;
};
end
function verify_captcha(form, callback)
if hmac_sha1(secret, form.captcha_reply, true) == form.captcha_challenge then
callback(true);
else
callback(false, "Captcha verification failed");
end
end
end
function generate_page(event, display_options)
local request = event.request;
return render(register_tpl, {
path = request.path; hostname = module.host;
notice = display_options and display_options.register_error or "";
captcha = generate_captcha(display_options);
})
end
function register_user(form)
local prepped_username = nodeprep(form.username);
if usermanager.user_exists(prepped_username, module.host) then
return nil, "user-exists";
end
return usermanager.create_user(prepped_username, form.password, module.host);
end
function generate_success(event, form)
return render(success_tpl, { jid = nodeprep(form.username).."@"..module.host });
end
function generate_register_response(event, form, ok, err)
local message;
if ok then
return generate_success(event, form);
else
return generate_page(event, { register_error = err });
end
end
function handle_form(event)
local request, response = event.request, event.response;
local form = http.formdecode(request.body);
verify_captcha(form, function (ok, err)
if ok then
local register_ok, register_err = register_user(form);
response:send(generate_register_response(event, form, register_ok, register_err));
else
response:send(generate_page(event, { register_error = err }));
end
end);
return true; -- Leave connection open until we respond above
end
module:provides("http", {
route = {
GET = generate_page;
POST = handle_form;
};
});
|
local captcha_options = module:get_option("captcha_options", {});
local nodeprep = require "util.encodings".stringprep.nodeprep;
local usermanager = require "core.usermanager";
local http = require "util.http";
function template(data)
-- Like util.template, but deals with plain text
return { apply = function(values) return (data:gsub("{([^}]+)}", values)); end }
end
local function get_template(name)
local fh = assert(module:load_resource("templates/"..name..".html"));
local data = assert(fh:read("*a"));
fh:close();
return template(data);
end
local function render(template, data)
return tostring(template.apply(data));
end
local register_tpl = get_template "register";
local success_tpl = get_template "success";
if next(captcha_options) ~= nil then
local recaptcha_tpl = get_template "recaptcha";
function generate_captcha(display_options)
return recaptcha_tpl.apply(setmetatable({
recaptcha_display_error = display_options and display_options.recaptcha_error
and ("&error="..display_options.recaptcha_error) or "";
}, {
__index = function (t, k)
if captcha_options[k] then return captcha_options[k]; end
module:log("error", "Missing parameter from captcha_options: %s", k);
end
}));
end
function verify_captcha(form, callback)
http.request("https://www.google.com/recaptcha/api/verify", {
body = http.formencode {
privatekey = captcha_options.recaptcha_private_key;
remoteip = request.conn:ip();
challenge = form.recaptcha_challenge_field;
response = form.recaptcha_response_field;
};
}, function (verify_result, code)
local verify_ok, verify_err = verify_result:match("^([^\n]+)\n([^\n]+)");
if verify_ok == "true" then
callback(true);
else
callback(false, verify_err)
end
end);
end
else
module:log("debug", "No Recaptcha options set, using fallback captcha")
local hmac_sha1 = require "util.hashes".hmac_sha1;
local secret = require "util.uuid".generate()
local ops = { '+', '-' };
local captcha_tpl = get_template "simplecaptcha";
function generate_captcha()
local op = ops[math.random(1, #ops)];
local x, y = math.random(1, 9)
repeat
y = math.random(1, 9);
until x ~= y;
local answer;
if op == '+' then
answer = x + y;
elseif op == '-' then
if x < y then
-- Avoid negative numbers
x, y = y, x;
end
answer = x - y;
end
local challenge = hmac_sha1(secret, answer, true);
return captcha_tpl.apply {
op = op, x = x, y = y, challenge = challenge;
};
end
function verify_captcha(form, callback)
if hmac_sha1(secret, form.captcha_reply, true) == form.captcha_challenge then
callback(true);
else
callback(false, "Captcha verification failed");
end
end
end
function generate_page(event, display_options)
local request = event.request;
return render(register_tpl, {
path = request.path; hostname = module.host;
notice = display_options and display_options.register_error or "";
captcha = generate_captcha(display_options);
})
end
function register_user(form)
local prepped_username = nodeprep(form.username);
if usermanager.user_exists(prepped_username, module.host) then
return nil, "user-exists";
end
return usermanager.create_user(prepped_username, form.password, module.host);
end
function generate_success(event, form)
return render(success_tpl, { jid = nodeprep(form.username).."@"..module.host });
end
function generate_register_response(event, form, ok, err)
local message;
if ok then
return generate_success(event, form);
else
return generate_page(event, { register_error = err });
end
end
function handle_form(event)
local request, response = event.request, event.response;
local form = http.formdecode(request.body);
verify_captcha(form, function (ok, err)
if ok then
local register_ok, register_err = register_user(form);
response:send(generate_register_response(event, form, register_ok, register_err));
else
response:send(generate_page(event, { register_error = err }));
end
end);
return true; -- Leave connection open until we respond above
end
module:provides("http", {
route = {
GET = generate_page;
POST = handle_form;
};
});
|
mod_register_web: Indentation fix
|
mod_register_web: Indentation fix
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
abd95832386c9a304da6c18ba3bde6e66e7600a7
|
user_modules/utils.lua
|
user_modules/utils.lua
|
---------------------------------------------------------------------------------------------------
-- Utils
---------------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.mobileHost = "127.0.0.1"
--[[ Required Shared libraries ]]
local json = require("modules/json")
local events = require('events')
--[[ Module ]]
local m = {}
--[[ Constants ]]
m.timeout = 2000
--[[ Functions ]]
--[[ @jsonFileToTable: convert .json file to table
--! @parameters:
--! pFileName - file name
--! @return: table
--]]
function m.jsonFileToTable(pFileName)
local f = io.open(pFileName, "r")
local content = f:read("*all")
f:close()
return json.decode(content)
end
--[[ @tableToJsonFile: convert table to .json file
--! @parameters:
--! pTbl - table
--! pFileName - file name
--! @return: none
--]]
function m.tableToJsonFile(pTbl, pFileName)
local f = io.open(pFileName, "w")
f:write(json.encode(pTbl))
f:close()
end
--[[ @readFile: read data from file
--! @parameters:
--! pPath - path to file
-- @return: content of the file
--]]
function m.readFile(pPath)
local open = io.open
local file = open(pPath, "rb")
if not file then return nil end
local content = file:read "*a"
file:close()
return content
end
--[[ @cloneTable: clone table
--! @parameters:
--! pTbl - table to clone
--! @return: cloned table
--]]
function m.cloneTable(pTbl)
if pTbl == nil then
return {}
end
local copy = {}
for k, v in pairs(pTbl) do
if type(v) == 'table' then
v = m.cloneTable(v)
end
copy[k] = v
end
return copy
end
--[[ @wait: delay test step for specific timeout
--! @parameters:
--! pTimeOut - time to wait in ms
--! @return: none
--]]
function m.wait(pTimeOut)
if not pTimeOut then pTimeOut = m.timeout end
local event = events.Event()
event.matches = function(event1, event2) return event1 == event2 end
EXPECT_EVENT(event, "Delayed event")
:Timeout(pTimeOut + 60000)
RUN_AFTER(function() RAISE_EVENT(event, event) end, pTimeOut)
end
--[[ @getDeviceName: provide device name
--! @parameters: none
--! @return: name of the device
--]]
function m.getDeviceName()
return config.mobileHost .. ":" .. config.mobilePort
end
--[[ @getDeviceMAC: provide device MAC address
--! @parameters: none
--! @return: MAC address of the device
--]]
function m.getDeviceMAC()
local cmd = "echo -n " .. m.getDeviceName() .. " | sha256sum | awk '{printf $1}'"
local handle = io.popen(cmd)
local result = handle:read("*a")
handle:close()
return result
end
--[[ @protect: make table immutable
--! @parameters:
--! pTbl - mutable table
--! @return: immutable table
--]]
function m.protect(pTbl)
local mt = {
__index = pTbl,
__newindex = function(_, k, v)
error("Attempting to change item " .. tostring(k) .. " to " .. tostring(v), 2)
end
}
return setmetatable({}, mt)
end
--[[ @cprint: print color message to console
--! @parameters:
--! pColor - color code
--! pMsg - message
--]]
function m.cprint(pColor, ...)
print("\27[" .. tostring(pColor) .. "m" .. table.concat(table.pack(...), "\t") .. "\27[0m")
end
--[[ @spairs: sorted iterator, allows to get items from table sorted by key
-- Usually used as a replacement of standard 'pairs' function
--! @parameters:
--! pTbl - table to iterate
--! @return: iterator
--]]
function m.spairs(pTbl)
local keys = {}
for k in pairs(pTbl) do
keys[#keys+1] = k
end
table.sort(keys, function(a, b) return tostring(a) < tostring(b) end)
local i = 0
return function()
i = i + 1
if keys[i] then
return keys[i], pTbl[keys[i]]
end
end
end
--[[ @tableToString: convert table to string
--! @parameters:
--! pTbl - table to convert
--! @return: string
--]]
function m.tableToString(pTbl)
local s = ""
local function tPrint(tbl, level)
if not level then level = 0 end
for k, v in m.spairs(tbl) do
local indent = string.rep(" ", level * 4)
s = s .. indent .. "[" .. k .. "]: "
if type(v) == "table" then
s = s .. "{\n"
tPrint(v, level + 1)
s = s .. indent .. "}"
elseif type(v) == "string" then
s = s .. "'" .. tostring(v) .. "'"
else
s = s .. tostring(v)
end
s = s .. "\n"
end
end
tPrint(pTbl)
return string.sub(s, 1, string.len(s) - 1)
end
--[[ @printTable: print table
--! @parameters:
--! pColor - color code
--! pTbl - table to print
--! @return: none
--]]
function m.cprintTable(pColor, pTbl)
m.cprint(pColor, string.rep("-", 50))
m.cprint(pColor, m.tableToString(pTbl))
m.cprint(pColor, string.rep("-", 50))
end
--[[ @printTable: print table
--! @parameters:
--! pTbl - table to print
--! @return: none
--]]
function m.printTable(pTbl)
m.cprintTable(39, pTbl)
end
return m
|
---------------------------------------------------------------------------------------------------
-- Utils
---------------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.mobileHost = "127.0.0.1"
--[[ Required Shared libraries ]]
local json = require("modules/json")
local events = require('events')
--[[ Module ]]
local m = {}
--[[ Constants ]]
m.timeout = 2000
--[[ Functions ]]
--[[ @jsonFileToTable: convert .json file to table
--! @parameters:
--! pFileName - file name
--! @return: table
--]]
function m.jsonFileToTable(pFileName)
local f = io.open(pFileName, "r")
local content = f:read("*all")
f:close()
return json.decode(content)
end
--[[ @tableToJsonFile: convert table to .json file
--! @parameters:
--! pTbl - table
--! pFileName - file name
--! @return: none
--]]
function m.tableToJsonFile(pTbl, pFileName)
local f = io.open(pFileName, "w")
f:write(json.encode(pTbl))
f:close()
end
--[[ @readFile: read data from file
--! @parameters:
--! pPath - path to file
-- @return: content of the file
--]]
function m.readFile(pPath)
local open = io.open
local file = open(pPath, "rb")
if not file then return nil end
local content = file:read "*a"
file:close()
return content
end
--[[ @cloneTable: clone table
--! @parameters:
--! pTbl - table to clone
--! @return: cloned table
--]]
function m.cloneTable(pTbl)
if pTbl == nil then
return {}
elseif pTbl == json.EMPTY_ARRAY then
return pTbl
end
local copy = {}
for k, v in pairs(pTbl) do
if type(v) == 'table' then
v = m.cloneTable(v)
end
copy[k] = v
end
return copy
end
--[[ @wait: delay test step for specific timeout
--! @parameters:
--! pTimeOut - time to wait in ms
--! @return: none
--]]
function m.wait(pTimeOut)
if not pTimeOut then pTimeOut = m.timeout end
local event = events.Event()
event.matches = function(event1, event2) return event1 == event2 end
EXPECT_EVENT(event, "Delayed event")
:Timeout(pTimeOut + 60000)
RUN_AFTER(function() RAISE_EVENT(event, event) end, pTimeOut)
end
--[[ @getDeviceName: provide device name
--! @parameters: none
--! @return: name of the device
--]]
function m.getDeviceName()
return config.mobileHost .. ":" .. config.mobilePort
end
--[[ @getDeviceMAC: provide device MAC address
--! @parameters: none
--! @return: MAC address of the device
--]]
function m.getDeviceMAC()
local cmd = "echo -n " .. m.getDeviceName() .. " | sha256sum | awk '{printf $1}'"
local handle = io.popen(cmd)
local result = handle:read("*a")
handle:close()
return result
end
--[[ @protect: make table immutable
--! @parameters:
--! pTbl - mutable table
--! @return: immutable table
--]]
function m.protect(pTbl)
local mt = {
__index = pTbl,
__newindex = function(_, k, v)
error("Attempting to change item " .. tostring(k) .. " to " .. tostring(v), 2)
end
}
return setmetatable({}, mt)
end
--[[ @cprint: print color message to console
--! @parameters:
--! pColor - color code
--! pMsg - message
--]]
function m.cprint(pColor, ...)
print("\27[" .. tostring(pColor) .. "m" .. table.concat(table.pack(...), "\t") .. "\27[0m")
end
--[[ @spairs: sorted iterator, allows to get items from table sorted by key
-- Usually used as a replacement of standard 'pairs' function
--! @parameters:
--! pTbl - table to iterate
--! @return: iterator
--]]
function m.spairs(pTbl)
local keys = {}
for k in pairs(pTbl) do
keys[#keys+1] = k
end
table.sort(keys, function(a, b) return tostring(a) < tostring(b) end)
local i = 0
return function()
i = i + 1
if keys[i] then
return keys[i], pTbl[keys[i]]
end
end
end
--[[ @tableToString: convert table to string
--! @parameters:
--! pTbl - table to convert
--! @return: string
--]]
function m.tableToString(pTbl)
local s = ""
local function tPrint(tbl, level)
if not level then level = 0 end
for k, v in m.spairs(tbl) do
local indent = string.rep(" ", level * 4)
s = s .. indent .. "[" .. k .. "]: "
if type(v) == "table" then
s = s .. "{\n"
tPrint(v, level + 1)
s = s .. indent .. "}"
elseif type(v) == "string" then
s = s .. "'" .. tostring(v) .. "'"
else
s = s .. tostring(v)
end
s = s .. "\n"
end
end
tPrint(pTbl)
return string.sub(s, 1, string.len(s) - 1)
end
--[[ @printTable: print table
--! @parameters:
--! pColor - color code
--! pTbl - table to print
--! @return: none
--]]
function m.cprintTable(pColor, pTbl)
m.cprint(pColor, string.rep("-", 50))
m.cprint(pColor, m.tableToString(pTbl))
m.cprint(pColor, string.rep("-", 50))
end
--[[ @printTable: print table
--! @parameters:
--! pTbl - table to print
--! @return: none
--]]
function m.printTable(pTbl)
m.cprintTable(39, pTbl)
end
return m
|
Fix issue in cloneTable function regarding empty arrays
|
Fix issue in cloneTable function regarding empty arrays
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
66cc52fa52d0231aa3191028063b6759f8b6cd0e
|
mod_lastlog/mod_lastlog.lua
|
mod_lastlog/mod_lastlog.lua
|
local datamanager = require "util.datamanager";
local time = os.time;
local log_ip = module:get_option_boolean("lastlog_ip_address", false);
local host = module.host;
module:hook("authentication-success", function(event)
local session = event.session;
if session.username then
datamanager.store(session.username, host, "lastlog", {
event = "login";
timestamp = time(),
ip = log_ip and session.ip or nil,
});
end
end);
module:hook("resource-unbind", function(event)
local session = event.session;
if session.username then
datamanager.store(session.username, host, "lastlog", {
event = "logout";
timestamp = time(),
ip = log_ip and session.ip or nil,
});
end
end);
function module.command(arg)
local user, host = require "util.jid".prepped_split(table.remove(arg, 1));
local lastlog = datamanager.load(user, host, "lastlog") or {};
print("Last login: "..(lastlog and os.date("%Y-%m-%d %H:%m:%s", datamanager.load(user, host, "lastlog").time) or "<unknown>"));
if lastlog.ip then
print("IP address: "..lastlog.ip);
end
return 0;
end
|
local datamanager = require "util.datamanager";
local time = os.time;
local log_ip = module:get_option_boolean("lastlog_ip_address", false);
local host = module.host;
module:hook("authentication-success", function(event)
local session = event.session;
if session.username then
datamanager.store(session.username, host, "lastlog", {
event = "login";
timestamp = time(),
ip = log_ip and session.ip or nil,
});
end
end);
module:hook("resource-unbind", function(event)
local session = event.session;
if session.username then
datamanager.store(session.username, host, "lastlog", {
event = "logout";
timestamp = time(),
ip = log_ip and session.ip or nil,
});
end
end);
function module.command(arg)
local user, host = require "util.jid".prepped_split(table.remove(arg, 1));
require"core.storagemanager".initialize_host(host);
local lastlog = assert(datamanager.load(user, host, "lastlog"));
if lastlog then
print(("Last %s: %s"):format(lastlog.event or "login",
lastlog.timestamp and os.date("%Y-%m-%d %H:%M:%S", lastlog.timestamp) or "<unknown>"));
if lastlog.ip then
print("IP address: "..lastlog.ip);
end
else
print("No record found");
end
return 0;
end
|
mod_lastlog: Fix command
|
mod_lastlog: Fix command
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
76fcc528fcdf4fb0b7f1683f7a2d1483105116b8
|
lib/redis_hook.lua
|
lib/redis_hook.lua
|
-- Helper Methods
function getCountry()
local country = geodb:query_by_addr(ngx.var.remote_addr, "id")
return geoip.name_by_id(country)
end
function normalizeKeys(tbl)
local normalized = {}
for k, v in pairs(tbl) do
local key = k:gsub("amp;", "")
normalized[key] = v
end
return normalized
end
function emptyGif()
ngx.exec('/_.gif')
end
function logErrorAndExit(err)
ngx.log(ngx.ERR, err)
emptyGif()
end
function initRedis()
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(3000) -- 3 sec
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then logErrorAndExit("Error connecting to redis: ".. err) end
return red
end
---------------------
ngx.header["Cache-Control"] = "no-cache"
local args = normalizeKeys(ngx.req.get_uri_args())
args["action"] = ngx.var.action
args["day"] = os.date("%d", ngx.req.start_time())
week = os.date("%W",ngx.req.start_time())
if week == "00" then week = "52" end
args["week"] = week
args["month"] = os.date("%m", ngx.req.start_time())
args["year"] = os.date("%Y",ngx.req.start_time())
args["country"] = getCountry()
local cjson = require "cjson"
local args_json = cjson.encode(args)
red = initRedis()
ok, err = red:evalsha(ngx.var.redis_counter_hash, 2, "args", "config", args_json, ngx.var.config)
if not ok then logErrorAndExit("Error evaluating redis script: ".. err) end
ok, err = red:set_keepalive(10000, 100)
if not ok then ngx.log(ngx.ERR, "Error setting redis keep alive ".. err) end
emptyGif()
|
-- Helper Methods
function getCountry()
local country = geodb:query_by_addr(ngx.var.remote_addr, "id")
return geoip.name_by_id(country)
end
function normalizeKeys(tbl)
local normalized = {}
for k, v in pairs(tbl) do
local key = k:gsub("amp;", "")
normalized[key] = v
end
return normalized
end
function emptyGif()
ngx.exec('/_.gif')
end
function logErrorAndExit(err)
ngx.log(ngx.ERR, err)
emptyGif()
end
function initRedis()
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(3000) -- 3 sec
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then logErrorAndExit("Error connecting to redis: ".. err) end
return red
end
---------------------
ngx.header["Cache-Control"] = "no-cache"
local args = normalizeKeys(ngx.req.get_uri_args())
args["action"] = ngx.var.action
args["day"] = os.date("%d", ngx.req.start_time())
args["week"] = os.date("%W",ngx.req.start_time())
args["month"] = os.date("%m", ngx.req.start_time())
args["year"] = os.date("%Y",ngx.req.start_time())
args["country"] = getCountry()
if args["week"] == "00" then
args["week"] = "52"
args["year"] = tostring( tonumber(args["year"]) - 1 )
end
local cjson = require "cjson"
local args_json = cjson.encode(args)
red = initRedis()
ok, err = red:evalsha(ngx.var.redis_counter_hash, 2, "args", "config", args_json, ngx.var.config)
if not ok then logErrorAndExit("Error evaluating redis script: ".. err) end
ok, err = red:set_keepalive(10000, 100)
if not ok then ngx.log(ngx.ERR, "Error setting redis keep alive ".. err) end
emptyGif()
|
fix year (and not just week) for the last week of the year
|
fix year (and not just week) for the last week of the year
|
Lua
|
mit
|
FTBpro/count-von-count,FTBpro/count-von-count
|
669c893b086450abb1239c22e7c03dc09c9bf972
|
src/json/decode.lua
|
src/json/decode.lua
|
--[[
Licensed according to the included 'LICENSE' document
Author: Thomas Harning Jr <[email protected]>
]]
local lpeg = require("lpeg")
local util = require("json.util")
local setmetatable, getmetatable = setmetatable, getmetatable
local assert = assert
local print = print
local tonumber = tonumber
local ipairs = ipairs
local string = string
module("json.decode")
local digit = lpeg.R("09")
local digits = digit^1
local alpha = lpeg.R("AZ","az")
local hex = lpeg.R("09","AF","af")
local hexpair = hex * hex
local identifier = lpeg.R("AZ","az","__") * lpeg.R("AZ","az", "__", "09") ^0
local space = lpeg.S(" \n\r\t\f")
local comment = (lpeg.P("//") * (1 - lpeg.P("\n"))^0 * lpeg.P("\n"))
+ (lpeg.P("/*") * (1 - lpeg.P("*/"))^0 * lpeg.P("*/"))
local ignored = (space + comment)^0
local knownReplacements = {
n = "\n",
r = "\r",
f = "\f",
t = "\t",
b = "\b",
z = "\z",
['\\'] = "\\",
['/'] = "/",
['"'] = '"'
}
local function unicodeParse(code1, code2)
code1, code2 = tonumber(code1, 16), tonumber(code2, 16)
return string.char(code1, code2)
end
-- Potential deviation, allow for newlines inside strings
local function buildStringCapture(stopParse, escapeMatch)
return lpeg.P('"') * lpeg.Cs(((1 - lpeg.S(stopParse)) + (lpeg.P("\\") / "" * escapeMatch))^0) * lpeg.P('"')
end
local doSimpleSub = lpeg.C(lpeg.S("rnfbt/\\z\"")) / knownReplacements
local doUniSub = (lpeg.P('u') * lpeg.C(hexpair) * lpeg.C(hexpair) + lpeg.P(false)) / unicodeParse
local doSub = doSimpleSub + doUniSub
-- Non-strict capture just spits back input value w/o slash
local captureString = buildStringCapture('"\\', doSub + lpeg.C(1))
local strictCaptureString = buildStringCapture('"\\\r\n\f\b\t', #lpeg.S("rnfbt/\\\"u") * doSub)
-- Deviation.. permit leading zeroes, permit inf number of negatives w/ space between
local int = lpeg.P('-')^0 * space^0 * digits
local number, strictNumber
local strictInt = (lpeg.P('-') + 0) * (lpeg.R("19") * digits + digit)
do
local frac = lpeg.P('.') * digits
local exp = lpeg.S("Ee") * (lpeg.S("-+") + 0) * digits -- Optional +- after the E
local function getNumber(intBase)
return intBase * (frac + 0) * (exp + 0)
end
number = getNumber(int)
strictNumber = getNumber(strictInt)
end
local VALUE, TABLE, ARRAY = 2,3,4
-- For null and undefined, use the util.null value to preserve null-ness
local booleanCapture =
lpeg.P("true") * lpeg.Cc(true)
+ lpeg.P("false") * lpeg.Cc(false)
local tableArrayCapture = lpeg.V(TABLE) + lpeg.V(ARRAY)
local valueCapture = ignored * (
captureString
+ lpeg.C(number) / tonumber
+ booleanCapture
+ (lpeg.P("null") + lpeg.P("undefined")) * lpeg.Cc(util.null)
+ tableArrayCapture
+ ("b64(" * captureString * ")")
) * ignored
local strictValueCapture = ignored * (
strictCaptureString
+ lpeg.C(strictNumber) / tonumber
+ booleanCapture
+ lpeg.P("null") * lpeg.Cc(util.null)
+ tableArrayCapture
) * ignored
local currentDepth
local function initDepth(s, i)
currentDepth = 0
return i
end
local function incDepth(s, i)
currentDepth = currentDepth + 1
return currentDepth < 20 and i or false
end
local function decDepth(s, i)
currentDepth = currentDepth - 1
return i
end
local tableKey =
lpeg.C(identifier)
+ captureString
+ int / tonumber
local strictTableKey = captureString
-- tableItem == pair
local function applyTableKey(tab, key, val)
if not tab then tab = {} end -- Initialize table for this set...
tab[key] = val
return tab
end
local function createTableItem(keyParser)
return (keyParser * ignored * lpeg.P(':') * ignored * lpeg.V(VALUE)) / applyTableKey
end
local tableItem = createTableItem(tableKey)
local strictTableItem = createTableItem(strictTableKey)
local tableElements = lpeg.Ca(lpeg.Cc(false) * tableItem * (ignored * lpeg.P(',') * ignored * tableItem)^0)
local strictTableElements = lpeg.Ca(lpeg.Cc(false) * strictTableItem * (ignored * lpeg.P(',') * ignored * strictTableItem)^0)
local tableCapture =
lpeg.P("{") * ignored
* (tableElements + 0) * ignored
* (lpeg.P(',') + 0) * ignored
* lpeg.P("}")
local strictTableCapture =
lpeg.P("{") * lpeg.P(incDepth) * ignored
* (strictTableElements + 0) * ignored
* lpeg.P("}") * lpeg.P(decDepth)
-- Utility function to help manage slighly sparse arrays
local function processArray(array)
array.n = #array
for i,v in ipairs(array) do
if v == util.null then
array[i] = nil
end
end
if #array == array.n then
array.n = nil
end
return array
end
-- arrayItem == element
local arrayItem = lpeg.V(VALUE)
local arrayElements = lpeg.Ct(arrayItem * (ignored * lpeg.P(',') * ignored * arrayItem)^0 + 0) / processArray
local strictArrayCapture =
lpeg.P("[") * lpeg.P(incDepth) * ignored
* (arrayElements) * ignored
* lpeg.P("]") * lpeg.P(decDepth)
local arrayCapture =
lpeg.P("[") * ignored
* (arrayElements) * ignored
* (lpeg.P(",") + 0) * ignored
* lpeg.P("]")
-- Deviation: allow for trailing comma, allow for "undefined" to be a value...
local grammar = lpeg.P({
[1] = lpeg.V(VALUE),
[VALUE] = valueCapture,
[TABLE] = tableCapture,
[ARRAY] = arrayCapture
}) * ignored * -1
local strictGrammar = lpeg.P({
[1] = lpeg.P(initDepth) * (lpeg.V(TABLE) + lpeg.V(ARRAY)), -- Initial value MUST be an object or array
[VALUE] = strictValueCapture,
[TABLE] = strictTableCapture,
[ARRAY] = strictArrayCapture
}) * ignored * -1
--NOTE: Certificate was trimmed down to make it easier to read....
function decode(data, strict)
return (assert(lpeg.match(not strict and grammar or strictGrammar, data), "Invalid JSON data"))
end
local mt = getmetatable(_M) or {}
mt.__call = function(self, ...)
return decode(...)
end
setmetatable(_M, mt)
|
--[[
Licensed according to the included 'LICENSE' document
Author: Thomas Harning Jr <[email protected]>
]]
local lpeg = require("lpeg")
local util = require("json.util")
local setmetatable, getmetatable = setmetatable, getmetatable
local assert = assert
local print = print
local tonumber = tonumber
local ipairs = ipairs
local string = string
module("json.decode")
local digit = lpeg.R("09")
local digits = digit^1
local alpha = lpeg.R("AZ","az")
local hex = lpeg.R("09","AF","af")
local hexpair = hex * hex
local identifier = lpeg.R("AZ","az","__") * lpeg.R("AZ","az", "__", "09") ^0
local space = lpeg.S(" \n\r\t\f")
local comment = (lpeg.P("//") * (1 - lpeg.P("\n"))^0 * lpeg.P("\n"))
+ (lpeg.P("/*") * (1 - lpeg.P("*/"))^0 * lpeg.P("*/"))
local ignored = (space + comment)^0
local knownReplacements = {
n = "\n",
r = "\r",
f = "\f",
t = "\t",
b = "\b",
z = "\z",
['\\'] = "\\",
['/'] = "/",
['"'] = '"'
}
local function unicodeParse(code1, code2)
code1, code2 = tonumber(code1, 16), tonumber(code2, 16)
return string.char(code1, code2)
end
-- Potential deviation, allow for newlines inside strings
local function buildStringCapture(stopParse, escapeMatch)
return lpeg.P('"') * lpeg.Cs(((1 - lpeg.S(stopParse)) + (lpeg.P("\\") / "" * escapeMatch))^0) * lpeg.P('"')
end
local doSimpleSub = lpeg.C(lpeg.S("rnfbt/\\z\"")) / knownReplacements
local doUniSub = (lpeg.P('u') * lpeg.C(hexpair) * lpeg.C(hexpair) + lpeg.P(false)) / unicodeParse
local doSub = doSimpleSub + doUniSub
-- Non-strict capture just spits back input value w/o slash
local captureString = buildStringCapture('"\\', doSub + lpeg.C(1))
local strictCaptureString = buildStringCapture('"\\\r\n\f\b\t', #lpeg.S("rnfbt/\\\"u") * doSub)
-- Deviation.. permit leading zeroes, permit inf number of negatives w/ space between
local int = lpeg.P('-')^0 * space^0 * digits
local number, strictNumber
local strictInt = (lpeg.P('-') + 0) * (lpeg.R("19") * digits + digit)
do
local frac = lpeg.P('.') * digits
local exp = lpeg.S("Ee") * (lpeg.S("-+") + 0) * digits -- Optional +- after the E
local function getNumber(intBase)
return intBase * (frac + 0) * (exp + 0)
end
number = getNumber(int)
strictNumber = getNumber(strictInt)
end
local VALUE, TABLE, ARRAY = 2,3,4
-- For null and undefined, use the util.null value to preserve null-ness
local booleanCapture =
lpeg.P("true") * lpeg.Cc(true)
+ lpeg.P("false") * lpeg.Cc(false)
local tableArrayCapture = lpeg.V(TABLE) + lpeg.V(ARRAY)
local valueCapture = ignored * (
captureString
+ lpeg.C(number) / tonumber
+ booleanCapture
+ (lpeg.P("null") + lpeg.P("undefined")) * lpeg.Cc(util.null)
+ tableArrayCapture
+ ("b64(" * captureString * ")")
) * ignored
local strictValueCapture = ignored * (
strictCaptureString
+ lpeg.C(strictNumber) / tonumber
+ booleanCapture
+ lpeg.P("null") * lpeg.Cc(util.null)
+ tableArrayCapture
) * ignored
local currentDepth
local function initDepth(s, i)
currentDepth = 0
return i
end
local function incDepth(s, i)
currentDepth = currentDepth + 1
return currentDepth < 20 and i or false
end
local function decDepth(s, i)
currentDepth = currentDepth - 1
return i
end
local tableKey =
lpeg.C(identifier)
+ captureString
+ int / tonumber
local strictTableKey = captureString
local function initTable(tab)
return {}
end
-- tableItem == pair
local function applyTableKey(tab, key, val)
if not tab then tab = {} end -- Initialize table for this set...
tab[key] = val
return tab
end
local function createTableItem(keyParser)
return (keyParser * ignored * lpeg.P(':') * ignored * lpeg.V(VALUE)) / applyTableKey
end
local tableItem = createTableItem(tableKey)
local strictTableItem = createTableItem(strictTableKey)
local tableElements = lpeg.Ca(lpeg.Cc(false) / initTable * (tableItem * (ignored * lpeg.P(',') * ignored * tableItem)^0 + 0))
local strictTableElements = lpeg.Ca(lpeg.Cc(false) / initTable * (strictTableItem * (ignored * lpeg.P(',') * ignored * strictTableItem)^0 + 0))
local tableCapture =
lpeg.P("{") * ignored
* tableElements * ignored
* (lpeg.P(',') + 0) * ignored
* lpeg.P("}")
local strictTableCapture =
lpeg.P("{") * lpeg.P(incDepth) * ignored
* strictTableElements * ignored
* lpeg.P("}") * lpeg.P(decDepth)
-- Utility function to help manage slighly sparse arrays
local function processArray(array)
array.n = #array
for i,v in ipairs(array) do
if v == util.null then
array[i] = nil
end
end
if #array == array.n then
array.n = nil
end
return array
end
-- arrayItem == element
local arrayItem = lpeg.V(VALUE)
local arrayElements = lpeg.Ct(arrayItem * (ignored * lpeg.P(',') * ignored * arrayItem)^0 + 0) / processArray
local strictArrayCapture =
lpeg.P("[") * lpeg.P(incDepth) * ignored
* (arrayElements) * ignored
* lpeg.P("]") * lpeg.P(decDepth)
local arrayCapture =
lpeg.P("[") * ignored
* (arrayElements) * ignored
* (lpeg.P(",") + 0) * ignored
* lpeg.P("]")
-- Deviation: allow for trailing comma, allow for "undefined" to be a value...
local grammar = lpeg.P({
[1] = lpeg.V(VALUE),
[VALUE] = valueCapture,
[TABLE] = tableCapture,
[ARRAY] = arrayCapture
}) * ignored * -1
local strictGrammar = lpeg.P({
[1] = lpeg.P(initDepth) * (lpeg.V(TABLE) + lpeg.V(ARRAY)), -- Initial value MUST be an object or array
[VALUE] = strictValueCapture,
[TABLE] = strictTableCapture,
[ARRAY] = strictArrayCapture
}) * ignored * -1
--NOTE: Certificate was trimmed down to make it easier to read....
function decode(data, strict)
return (assert(lpeg.match(not strict and grammar or strictGrammar, data), "Invalid JSON data"))
end
local mt = getmetatable(_M) or {}
mt.__call = function(self, ...)
return decode(...)
end
setmetatable(_M, mt)
|
decode: Fix to support empty objects
|
decode: Fix to support empty objects
|
Lua
|
mit
|
renchunxiao/luajson
|
ead331924f7d8eb29e1f1a42fb4641fe0f0792da
|
frontend/ui/widget/toggleswitch.lua
|
frontend/ui/widget/toggleswitch.lua
|
ToggleLabel = TextWidget:new{
bgcolor = 0,
fgcolor = 1,
}
function ToggleLabel:paintTo(bb, x, y)
renderUtf8Text(bb, x, y+self._height*0.75, self.face, self.text, true, self.bgcolor, self.fgcolor)
end
ToggleSwitch = InputContainer:new{
width = scaleByDPI(216),
height = scaleByDPI(30),
}
function ToggleSwitch:init()
self.n_pos = #self.toggle
self.position = nil
local label_font_face = "cfont"
local label_font_size = 16
self.toggle_frame = FrameContainer:new{background = 0, color = 7, radius = 7, bordersize = 1, padding = 2,}
self.toggle_content = HorizontalGroup:new{}
for i=1,#self.toggle do
local label = ToggleLabel:new{
align = "center",
text = self.toggle[i],
face = Font:getFace(label_font_face, label_font_size),
}
local content = CenterContainer:new{
dimen = Geom:new{w = self.width/self.n_pos, h = self.height},
label,
}
local button = FrameContainer:new{
background = 0,
color = 7,
margin = 0,
radius = 5,
bordersize = 1,
padding = 0,
content,
}
table.insert(self.toggle_content, button)
end
self.toggle_frame[1] = self.toggle_content
self[1] = self.toggle_frame
self.dimen = Geom:new(self.toggle_frame:getSize())
if Device:isTouchDevice() then
self.ges_events = {
TapSelect = {
GestureRange:new{
ges = "tap",
range = self.dimen,
},
doc = _("Toggle switch"),
},
}
end
end
function ToggleSwitch:update()
local pos = self.position
for i=1,#self.toggle_content do
if pos == i then
self.toggle_content[i].color = 7
self.toggle_content[i].background = 7
self.toggle_content[i][1][1].bgcolor = 0.5
self.toggle_content[i][1][1].fgcolor = 0.0
else
self.toggle_content[i].color = 0
self.toggle_content[i].background = 0
self.toggle_content[i][1][1].bgcolor = 0.0
self.toggle_content[i][1][1].fgcolor = 1.0
end
end
end
function ToggleSwitch:setPosition(position)
self.position = position
self:update()
end
function ToggleSwitch:togglePosition(position)
if self.n_pos == 2 and self.alternate ~= false then
self.position = (self.position+1)%self.n_pos
self.position = self.position == 0 and self.n_pos or self.position
else
self.position = position
end
self:update()
end
function ToggleSwitch:onTapSelect(arg, gev)
local position = math.ceil(
(gev.pos.x - self.dimen.x) / self.dimen.w * self.n_pos
)
--DEBUG("toggle position:", position)
self:togglePosition(position)
local option_value = nil
local option_arg = nil
if self.values then
self.values = self.values or {}
option_value = self.values[self.position]
self.config:onConfigChoice(self.name, option_value)
end
if self.event then
self.args = self.args or {}
option_arg = self.args[self.position]
self.config:onConfigEvent(self.event, option_arg)
end
if self.events then
for i=1,#self.events do
self.events[i].args = self.events[i].args or {}
option_arg = self.events[i].args[self.position]
self.config:onConfigEvent(self.events[i].event, option_arg)
end
end
UIManager.repaint_all = true
end
|
ToggleLabel = TextWidget:new{
bgcolor = 0,
fgcolor = 1,
}
function ToggleLabel:paintTo(bb, x, y)
renderUtf8Text(bb, x, y+self._height*0.75, self.face, self.text, true, self.bgcolor, self.fgcolor)
end
ToggleSwitch = InputContainer:new{
width = scaleByDPI(216),
height = scaleByDPI(30),
bgcolor = 0, -- unfoused item color
fgcolor = 7, -- focused item color
}
function ToggleSwitch:init()
self.n_pos = #self.toggle
self.position = nil
local label_font_face = "cfont"
local label_font_size = 16
self.toggle_frame = FrameContainer:new{background = 0, color = 7, radius = 7, bordersize = 1, padding = 2,}
self.toggle_content = HorizontalGroup:new{}
for i=1,#self.toggle do
local label = ToggleLabel:new{
align = "center",
text = self.toggle[i],
face = Font:getFace(label_font_face, label_font_size),
}
local content = CenterContainer:new{
dimen = Geom:new{w = self.width/self.n_pos, h = self.height},
label,
}
local button = FrameContainer:new{
background = 0,
color = 7,
margin = 0,
radius = 5,
bordersize = 1,
padding = 0,
content,
}
table.insert(self.toggle_content, button)
end
self.toggle_frame[1] = self.toggle_content
self[1] = self.toggle_frame
self.dimen = Geom:new(self.toggle_frame:getSize())
if Device:isTouchDevice() then
self.ges_events = {
TapSelect = {
GestureRange:new{
ges = "tap",
range = self.dimen,
},
doc = _("Toggle switch"),
},
}
end
end
function ToggleSwitch:update()
local pos = self.position
for i=1,#self.toggle_content do
if pos == i then
self.toggle_content[i].color = self.fgcolor
self.toggle_content[i].background = self.fgcolor
self.toggle_content[i][1][1].bgcolor = self.fgcolor/15
self.toggle_content[i][1][1].fgcolor = 0.0
else
self.toggle_content[i].color = self.bgcolor
self.toggle_content[i].background = self.bgcolor
self.toggle_content[i][1][1].bgcolor = 0.0
self.toggle_content[i][1][1].fgcolor = 1.0
end
end
end
function ToggleSwitch:setPosition(position)
self.position = position
self:update()
end
function ToggleSwitch:togglePosition(position)
if self.n_pos == 2 and self.alternate ~= false then
self.position = (self.position+1)%self.n_pos
self.position = self.position == 0 and self.n_pos or self.position
else
self.position = position
end
self:update()
end
function ToggleSwitch:onTapSelect(arg, gev)
local position = math.ceil(
(gev.pos.x - self.dimen.x) / self.dimen.w * self.n_pos
)
--DEBUG("toggle position:", position)
self:togglePosition(position)
local option_value = nil
local option_arg = nil
if self.values then
self.values = self.values or {}
option_value = self.values[self.position]
self.config:onConfigChoice(self.name, option_value)
end
if self.event then
self.args = self.args or {}
option_arg = self.args[self.position]
self.config:onConfigEvent(self.event, option_arg)
end
if self.events then
for i=1,#self.events do
self.events[i].args = self.events[i].args or {}
option_arg = self.events[i].args[self.position]
self.config:onConfigEvent(self.events[i].event, option_arg)
end
end
UIManager.repaint_all = true
end
|
fix toggle color inconsistency
|
fix toggle color inconsistency
|
Lua
|
agpl-3.0
|
chrox/koreader,robert00s/koreader,mihailim/koreader,NiLuJe/koreader,Frenzie/koreader,mwoz123/koreader,poire-z/koreader,koreader/koreader,frankyifei/koreader,Hzj-jie/koreader,Frenzie/koreader,poire-z/koreader,houqp/koreader,NickSavage/koreader,lgeek/koreader,Markismus/koreader,NiLuJe/koreader,noname007/koreader,chihyang/koreader,ashang/koreader,pazos/koreader,koreader/koreader,ashhher3/koreader,apletnev/koreader
|
8b295b583711cc4a79234849477ea31182a9d986
|
plugins/kobolight.koplugin/main.lua
|
plugins/kobolight.koplugin/main.lua
|
local Device = require("device")
if not ((Device:isKindle() or Device:isKobo()) and Device:hasFrontlight()) then
return { disabled = true, }
end
local WidgetContainer = require("ui/widget/container/widgetcontainer")
local Screen = Device.screen
local UIManager = require("ui/uimanager")
local Notification = require("ui/widget/notification")
local T = require("ffi/util").template
local _ = require("gettext")
local tap_touch_zone_ratio = { x = 0, y = 15/16, w = 1/10, h = 1/16, }
local swipe_touch_zone_ratio = { x = 0, y = 1/8, w = 1/10, h = 7/8, }
local KoboLight = WidgetContainer:new{
name = 'kobolight',
steps = { 0.1, 0.1, 0.2, 0.4, 0.7, 1.1, 1.6, 2.2, 2.9, 3.7, 4.6, 5.6, 6.7, 7.9, 9.2, 10.6, },
gestureScale = nil, -- initialized in self:resetLayout()
}
function KoboLight:init()
local powerd = Device:getPowerDevice()
local scale = (powerd.fl_max - powerd.fl_min) / 2 / 10.6
for i = 1, #self.steps, 1
do
self.steps[i] = math.ceil(self.steps[i] * scale)
end
end
function KoboLight:onReaderReady()
self:setupTouchZones()
self:resetLayout()
end
function KoboLight:setupTouchZones()
if not Device:isTouchDevice() then return end
local swipe_zone = {
ratio_x = swipe_touch_zone_ratio.x, ratio_y = swipe_touch_zone_ratio.y,
ratio_w = swipe_touch_zone_ratio.w, ratio_h = swipe_touch_zone_ratio.h,
}
self.ui:registerTouchZones({
{
id = "plugin_kobolight_tap",
ges = "tap",
screen_zone = {
ratio_x = tap_touch_zone_ratio.x, ratio_y = tap_touch_zone_ratio.y,
ratio_w = tap_touch_zone_ratio.w, ratio_h = tap_touch_zone_ratio.h,
},
handler = function() return self:onTap() end,
overrides = { 'readerfooter_tap' },
},
{
id = "plugin_kobolight_swipe",
ges = "swipe",
screen_zone = swipe_zone,
handler = function(ges) return self:onSwipe(nil, ges) end,
overrides = { 'paging_swipe', 'rolling_swipe', },
},
{
-- dummy zone to disable reader panning
id = "plugin_kobolight_pan",
ges = "pan",
screen_zone = swipe_zone,
handler = function(ges) return true end,
overrides = { 'paging_pan', 'rolling_pan', },
},
{
-- dummy zone to disable reader panning
id = "plugin_kobolight_pan_release",
ges = "pan_release",
screen_zone = swipe_zone,
handler = function(ges) return true end,
overrides = { 'paging_pan_release', },
},
})
end
function KoboLight:resetLayout()
local new_screen_height = Screen:getHeight()
self.gestureScale = new_screen_height * swipe_touch_zone_ratio.h * 0.8
end
function KoboLight:onShowIntensity()
local powerd = Device:getPowerDevice()
if powerd.fl_intensity ~= nil then
UIManager:show(Notification:new{
text = T(_("Frontlight intensity is set to %1."), powerd.fl_intensity),
timeout = 1.0,
})
end
return true
end
function KoboLight:onShowOnOff()
local powerd = Device:getPowerDevice()
local new_text
if powerd.is_fl_on then
new_text = _("Frontlight is on.")
else
new_text = _("Frontlight is off.")
end
UIManager:show(Notification:new{
text = new_text,
timeout = 1.0,
})
return true
end
function KoboLight:onTap()
Device:getPowerDevice():toggleFrontlight()
self:onShowOnOff()
if self.view.footer_visible and self.view.footer.settings.frontlight then
self.view.footer:updateFooter()
end
return true
end
function KoboLight:onSwipe(_, ges)
local powerd = Device:getPowerDevice()
if powerd.fl_intensity == nil then return true end
local step = math.ceil(#self.steps * ges.distance / self.gestureScale)
local delta_int = self.steps[step] or self.steps[#self.steps]
local new_intensity
if ges.direction == "north" then
new_intensity = powerd.fl_intensity + delta_int
elseif ges.direction == "south" then
new_intensity = powerd.fl_intensity - delta_int
end
if new_intensity ~= nil then
-- when new_intensity <=0, toggle light off
if new_intensity <=0 then
if powerd.is_fl_on then
powerd:toggleFrontlight()
end
self:onShowOnOff()
else -- general case
powerd:setIntensity(new_intensity)
self:onShowIntensity()
end
if self.view.footer_visible and self.view.footer.settings.frontlight then
self.view.footer:updateFooter()
end
end
return true
end
return KoboLight
|
local Device = require("device")
if not ((Device:isKindle() or Device:isKobo()) and Device:hasFrontlight()) then
return { disabled = true, }
end
local WidgetContainer = require("ui/widget/container/widgetcontainer")
local Screen = Device.screen
local UIManager = require("ui/uimanager")
local Notification = require("ui/widget/notification")
local T = require("ffi/util").template
local _ = require("gettext")
local tap_touch_zone_ratio = { x = 0, y = 15/16, w = 1/10, h = 1/16, }
local swipe_touch_zone_ratio = { x = 0, y = 1/8, w = 1/10, h = 7/8, }
local KoboLight = WidgetContainer:new{
name = 'kobolight',
gestureScale = nil, -- initialized in self:resetLayout()
}
function KoboLight:init()
local powerd = Device:getPowerDevice()
local scale = (powerd.fl_max - powerd.fl_min) / 2 / 10.6
self.steps = { 0.1, 0.1, 0.2, 0.4, 0.7, 1.1, 1.6, 2.2, 2.9, 3.7, 4.6, 5.6, 6.7, 7.9, 9.2, 10.6, }
for i = 1, #self.steps, 1
do
self.steps[i] = math.ceil(self.steps[i] * scale)
end
end
function KoboLight:onReaderReady()
self:setupTouchZones()
self:resetLayout()
end
function KoboLight:setupTouchZones()
if not Device:isTouchDevice() then return end
local swipe_zone = {
ratio_x = swipe_touch_zone_ratio.x, ratio_y = swipe_touch_zone_ratio.y,
ratio_w = swipe_touch_zone_ratio.w, ratio_h = swipe_touch_zone_ratio.h,
}
self.ui:registerTouchZones({
{
id = "plugin_kobolight_tap",
ges = "tap",
screen_zone = {
ratio_x = tap_touch_zone_ratio.x, ratio_y = tap_touch_zone_ratio.y,
ratio_w = tap_touch_zone_ratio.w, ratio_h = tap_touch_zone_ratio.h,
},
handler = function() return self:onTap() end,
overrides = { 'readerfooter_tap' },
},
{
id = "plugin_kobolight_swipe",
ges = "swipe",
screen_zone = swipe_zone,
handler = function(ges) return self:onSwipe(nil, ges) end,
overrides = { 'paging_swipe', 'rolling_swipe', },
},
{
-- dummy zone to disable reader panning
id = "plugin_kobolight_pan",
ges = "pan",
screen_zone = swipe_zone,
handler = function(ges) return true end,
overrides = { 'paging_pan', 'rolling_pan', },
},
{
-- dummy zone to disable reader panning
id = "plugin_kobolight_pan_release",
ges = "pan_release",
screen_zone = swipe_zone,
handler = function(ges) return true end,
overrides = { 'paging_pan_release', },
},
})
end
function KoboLight:resetLayout()
local new_screen_height = Screen:getHeight()
self.gestureScale = new_screen_height * swipe_touch_zone_ratio.h * 0.8
end
function KoboLight:onShowIntensity()
local powerd = Device:getPowerDevice()
if powerd.fl_intensity ~= nil then
UIManager:show(Notification:new{
text = T(_("Frontlight intensity is set to %1."), powerd.fl_intensity),
timeout = 1.0,
})
end
return true
end
function KoboLight:onShowOnOff()
local powerd = Device:getPowerDevice()
local new_text
if powerd.is_fl_on then
new_text = _("Frontlight is on.")
else
new_text = _("Frontlight is off.")
end
UIManager:show(Notification:new{
text = new_text,
timeout = 1.0,
})
return true
end
function KoboLight:onTap()
Device:getPowerDevice():toggleFrontlight()
self:onShowOnOff()
if self.view.footer_visible and self.view.footer.settings.frontlight then
self.view.footer:updateFooter()
end
return true
end
function KoboLight:onSwipe(_, ges)
local powerd = Device:getPowerDevice()
if powerd.fl_intensity == nil then return true end
local step = math.ceil(#self.steps * ges.distance / self.gestureScale)
local delta_int = self.steps[step] or self.steps[#self.steps]
local new_intensity
if ges.direction == "north" then
new_intensity = powerd.fl_intensity + delta_int
elseif ges.direction == "south" then
new_intensity = powerd.fl_intensity - delta_int
end
if new_intensity ~= nil then
-- when new_intensity <=0, toggle light off
if new_intensity <=0 then
if powerd.is_fl_on then
powerd:toggleFrontlight()
end
self:onShowOnOff()
else -- general case
powerd:setIntensity(new_intensity)
self:onShowIntensity()
end
if self.view.footer_visible and self.view.footer.settings.frontlight then
self.view.footer:updateFooter()
end
end
return true
end
return KoboLight
|
Fix KoboLight sensitivity
|
Fix KoboLight sensitivity
Which was increasing after each opening of a document.
Closes #2605
|
Lua
|
agpl-3.0
|
koreader/koreader,Markismus/koreader,apletnev/koreader,Frenzie/koreader,poire-z/koreader,NiLuJe/koreader,lgeek/koreader,Frenzie/koreader,poire-z/koreader,houqp/koreader,NiLuJe/koreader,koreader/koreader,mihailim/koreader,robert00s/koreader,mwoz123/koreader,Hzj-jie/koreader,pazos/koreader
|
54447400603783b2bc15d0882e4ba997796da354
|
game/scripts/vscripts/modules/bosses/boss_loot.lua
|
game/scripts/vscripts/modules/bosses/boss_loot.lua
|
function Bosses:CreateBossLoot(unit, team)
local id = team .. "_" .. Bosses.NextVoteID
Bosses.NextVoteID = Bosses.NextVoteID + 1
local dropTables = PlayerTables:copy(DROP_TABLE[unit:GetUnitName()])
local totalDamage = 0
local damageByPlayers = {}
for pid, damage in pairs(unit.DamageReceived) do
if PlayerResource:IsValidPlayerID(pid) and not IsPlayerAbandoned(pid) and team == PlayerResource:GetTeam(pid) then
damageByPlayers[pid] = (damageByPlayers[pid] or 0) + damage
end
totalDamage = totalDamage + damage
end
local damagePcts = {}
for pid, damage in pairs(damageByPlayers) do
damagePcts[pid] = damage/totalDamage*100
end
local t = {
boss = unit:GetUnitName(),
killtime = GameRules:GetGameTime(),
time = 30,
damageByPlayers = damageByPlayers,
totalDamage = totalDamage,
damagePcts = damagePcts,
rollableEntries = {},
team = team
}
local itemcount = RandomInt(math.min(5, #dropTables), math.min(6, #dropTables))
if dropTables.hero and not Options:IsEquals("MainHeroList", "NoAbilities") and not HeroSelection:IsHeroSelected(dropTables.hero) then
table.insert(t.rollableEntries, {
hero = dropTables.hero,
weight = 0,
votes = {}
})
end
while #t.rollableEntries < itemcount do
table.shuffle(dropTables)
for k,dropTable in ipairs(dropTables) do
if RollPercentage(dropTable.DropChance) then
table.insert(t.rollableEntries, {
item = dropTable.Item,
weight = dropTable.DamageWeightPct or 10,
votes = {}
})
table.remove(dropTables, k)
if #t.rollableEntries >= itemcount then
break
end
end
end
end
PlayerTables:SetTableValue("bosses_loot_drop_votes", id, t)
Timers:CreateTimer(30, function()
-- Take new data
t = PlayerTables:GetTableValue("bosses_loot_drop_votes", id)
-- Iterate over all entries
for _, entry in pairs(t.rollableEntries) do
local selectedPlayers = {}
local bestPctLeft = -math.huge
-- Iterate over all voted players and select player with biggest priority points
for pid, s in pairs(entry.votes) do
damagePcts[pid] = damagePcts[pid] or 0
local totalPointsAfterReduction = damagePcts[pid] - entry.weight
if s and totalPointsAfterReduction >= bestPctLeft and not PlayerResource:IsPlayerAbandoned(pid) then
if totalPointsAfterReduction > bestPctLeft then
selectedPlayers = {}
end
table.insert(selectedPlayers, pid)
damagePcts[pid] = totalPointsAfterReduction
bestPctLeft = totalPointsAfterReduction
end
end
if #selectedPlayers > 0 then
local selectedPlayer = selectedPlayers[RandomInt(1, #selectedPlayers)]
Bosses:GivePlayerSelectedDrop(selectedPlayer, entry)
else
local ntid = team .. "_" .. -1
local tt = PlayerTables:GetTableValue("bosses_loot_drop_votes", ntid) or {}
entry.votes = nil
entry.weight = nil
table.insert(tt, entry)
PlayerTables:SetTableValue("bosses_loot_drop_votes", ntid, tt)
end
end
PlayerTables:SetTableValue("bosses_loot_drop_votes", id, nil)
end)
end
function Bosses:VoteForItem(data)
local splittedId = data.voteid:split("_")
local PlayerID = data.PlayerID
local t = PlayerTables:GetTableValue("bosses_loot_drop_votes", data.voteid)
if t and not PlayerResource:IsPlayerAbandoned(PlayerID) and PlayerResource:GetTeam(PlayerID) == tonumber(splittedId[1]) then
if t.rollableEntries and t.rollableEntries[tonumber(data.entryid)] then
t.rollableEntries[tonumber(data.entryid)].votes[PlayerID] = not t.rollableEntries[tonumber(data.entryid)].votes[PlayerID]
else
-- -1
local entry = t[tonumber(data.entryid)]
if entry then
Bosses:GivePlayerSelectedDrop(PlayerID, entry)
table.remove(t, tonumber(data.entryid))
end
end
PlayerTables:SetTableValue("bosses_loot_drop_votes", data.voteid, t)
end
end
function Bosses:GivePlayerSelectedDrop(playerId, entry)
if entry.item then
local hero = PlayerResource:GetSelectedHeroEntity(playerId)
if hero then
PanoramaShop:PushItem(playerId, hero, entry.item, true)
end
else
local newHero = entry.hero
function ActuallyReplaceHero()
if PlayerResource:GetSelectedHeroEntity(playerId) and not HeroSelection:IsHeroSelected(newHero) then
HeroSelection:ChangeHero(playerId, newHero, true, 0)
else
Notifications:Bottom(playerId, {text="hero_selection_change_hero_selected"})
end
end
if Duel:IsDuelOngoing() then
Notifications:Bottom(playerId, {text="boss_loot_vote_hero_duel_delayed"})
Events:On("Duel/end", ActuallyReplaceHero, true)
else
ActuallyReplaceHero()
end
end
end
|
function Bosses:CreateBossLoot(unit, team)
local id = team .. "_" .. Bosses.NextVoteID
Bosses.NextVoteID = Bosses.NextVoteID + 1
local dropTables = PlayerTables:copy(DROP_TABLE[unit:GetUnitName()])
local totalDamage = 0
local damageByPlayers = {}
for pid, damage in pairs(unit.DamageReceived) do
if PlayerResource:IsValidPlayerID(pid) and not IsPlayerAbandoned(pid) and team == PlayerResource:GetTeam(pid) then
damageByPlayers[pid] = (damageByPlayers[pid] or 0) + damage
end
totalDamage = totalDamage + damage
end
local damagePcts = {}
for pid, damage in pairs(damageByPlayers) do
damagePcts[pid] = damage/totalDamage*100
end
local t = {
boss = unit:GetUnitName(),
killtime = GameRules:GetGameTime(),
time = 30,
damageByPlayers = damageByPlayers,
totalDamage = totalDamage,
damagePcts = damagePcts,
rollableEntries = {},
team = team
}
local itemcount = RandomInt(math.min(5, #dropTables), math.min(6, #dropTables))
if dropTables.hero and not Options:IsEquals("MainHeroList", "NoAbilities") and not HeroSelection:IsHeroSelected(dropTables.hero) then
table.insert(t.rollableEntries, {
hero = dropTables.hero,
weight = 0,
votes = {}
})
end
while #t.rollableEntries < itemcount do
table.shuffle(dropTables)
for k,dropTable in ipairs(dropTables) do
if RollPercentage(dropTable.DropChance) then
table.insert(t.rollableEntries, {
item = dropTable.Item,
weight = dropTable.DamageWeightPct or 10,
votes = {}
})
table.remove(dropTables, k)
if #t.rollableEntries >= itemcount then
break
end
end
end
end
PlayerTables:SetTableValue("bosses_loot_drop_votes", id, t)
Timers:CreateTimer(30, function()
-- Take new data
t = PlayerTables:GetTableValue("bosses_loot_drop_votes", id)
-- Iterate over all entries
for _, entry in pairs(t.rollableEntries) do
local selectedPlayers = {}
local bestPctLeft = -math.huge
-- Iterate over all voted players and select player with biggest priority points
for pid, s in pairs(entry.votes) do
damagePcts[pid] = damagePcts[pid] or 0
local totalPointsAfterReduction = damagePcts[pid] - entry.weight
if s and totalPointsAfterReduction >= bestPctLeft and not PlayerResource:IsPlayerAbandoned(pid) then
if totalPointsAfterReduction > bestPctLeft then
selectedPlayers = {}
end
table.insert(selectedPlayers, pid)
damagePcts[pid] = totalPointsAfterReduction
bestPctLeft = totalPointsAfterReduction
end
end
if #selectedPlayers > 0 then
local selectedPlayer = selectedPlayers[RandomInt(1, #selectedPlayers)]
Bosses:GivePlayerSelectedDrop(selectedPlayer, entry)
else
local ntid = team .. "_" .. -1
local tt = PlayerTables:GetTableValue("bosses_loot_drop_votes", ntid) or {}
entry.votes = nil
entry.weight = nil
table.insert(tt, entry)
PlayerTables:SetTableValue("bosses_loot_drop_votes", ntid, tt)
end
end
PlayerTables:SetTableValue("bosses_loot_drop_votes", id, nil)
end)
end
function Bosses:VoteForItem(data)
local splittedId = data.voteid:split("_")
local PlayerID = data.PlayerID
local t = PlayerTables:GetTableValue("bosses_loot_drop_votes", data.voteid)
if t and not PlayerResource:IsPlayerAbandoned(PlayerID) and PlayerResource:GetTeam(PlayerID) == tonumber(splittedId[1]) then
if t.rollableEntries and t.rollableEntries[tonumber(data.entryid)] then
t.rollableEntries[tonumber(data.entryid)].votes[PlayerID] = not t.rollableEntries[tonumber(data.entryid)].votes[PlayerID]
else
-- -1
local entry = t[tonumber(data.entryid)]
if entry then
Bosses:GivePlayerSelectedDrop(PlayerID, entry)
table.remove(t, tonumber(data.entryid))
end
end
PlayerTables:SetTableValue("bosses_loot_drop_votes", data.voteid, t)
end
end
function Bosses:GivePlayerSelectedDrop(playerId, entry)
if entry.item then
local hero = PlayerResource:GetSelectedHeroEntity(playerId)
if hero then
PanoramaShop:PushItem(playerId, hero, entry.item, true)
end
else
local newHero = entry.hero
function ActuallyReplaceHero()
if PlayerResource:GetSelectedHeroEntity(playerId) and not HeroSelection:IsHeroSelected(newHero) then
Timers:CreateTimer(function()
if not HeroSelection:ChangeHero(playerId, newHero, true, 0) then
return 1
end
end)
else
Notifications:Bottom(playerId, {text="hero_selection_change_hero_selected"})
end
end
if Duel:IsDuelOngoing() then
Notifications:Bottom(playerId, {text="boss_loot_vote_hero_duel_delayed"})
Events:On("Duel/end", ActuallyReplaceHero, true)
else
ActuallyReplaceHero()
end
end
end
|
fix(bosses): hero changing now will be retried until success
|
fix(bosses): hero changing now will be retried until success
|
Lua
|
mit
|
ark120202/aabs
|
fbb244ee962ddcf483dc4c6adec30de6c2616436
|
src/lua-factory/sources/grl-lastfm-cover.lua
|
src/lua-factory/sources/grl-lastfm-cover.lua
|
--[[
* Copyright (C) 2015 Bastien Nocera.
*
* Contact: Bastien Nocera <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
--]]
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-lastfm-cover",
name = "Last.fm Cover",
description = "a source for music covers",
goa_account_provider = 'lastfm',
goa_account_feature = 'music',
supported_keys = { 'thumbnail' },
supported_media = { 'audio' },
resolve_keys = {
["type"] = "audio",
required = { "artist", "album" },
},
tags = { 'music', 'net:internet', 'net:plaintext' },
}
------------------
-- Source utils --
------------------
LASTFM_SEARCH_ALBUM = 'http://ws.audioscrobbler.com/2.0/?method=album.getInfo&api_key=%s&artist=%s&album=%s'
---------------------------------
-- Handlers of Grilo functions --
---------------------------------
function grl_source_resolve()
local url, req
local artist, title
req = grl.get_media_keys()
if not req or not req.artist or not req.album
or #req.artist == 0 or #req.album == 0 then
grl.callback()
return
end
-- Prepare artist and title strings to the url
artist = grl.encode(req.artist)
album = grl.encode(req.album)
url = string.format(LASTFM_SEARCH_ALBUM, grl.goa_consumer_key(), artist, album)
grl.fetch(url, "fetch_page_cb")
end
---------------
-- Utilities --
---------------
function fetch_page_cb(result)
if not result then
grl.callback()
return
end
local media = {}
media.thumbnail = {}
for k, v in string.gmatch(result, '<image size="(.-)">(.-)</image>') do
grl.debug ('Image size ' .. k .. ' = ' .. v)
table.insert(media.thumbnail, v)
end
grl.callback(media, 0)
end
|
--[[
* Copyright (C) 2015 Bastien Nocera.
*
* Contact: Bastien Nocera <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
--]]
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-lastfm-cover",
name = "Last.fm Cover",
description = "a source for music covers",
goa_account_provider = 'lastfm',
goa_account_feature = 'music',
supported_keys = { 'thumbnail' },
supported_media = { 'audio' },
resolve_keys = {
["type"] = "audio",
required = { "artist", "album" },
},
tags = { 'music', 'net:internet', 'net:plaintext' },
}
------------------
-- Source utils --
------------------
LASTFM_SEARCH_ALBUM = 'http://ws.audioscrobbler.com/2.0/?method=album.getInfo&api_key=%s&artist=%s&album=%s'
---------------------------------
-- Handlers of Grilo functions --
---------------------------------
function grl_source_resolve(media, options, callback)
local url
local artist, title
if not media or not media.artist or not media.album
or #media.artist == 0 or #media.album == 0 then
callback()
return
end
-- Prepare artist and title strings to the url
artist = grl.encode(media.artist)
album = grl.encode(media.album)
url = string.format(LASTFM_SEARCH_ALBUM, grl.goa_consumer_key(), artist, album)
local userdata = {callback = callback, media = media}
grl.fetch(url, fetch_page_cb, userdata)
end
---------------
-- Utilities --
---------------
function fetch_page_cb(result, userdata)
if not result then
userdata.callback()
return
end
userdata.media.thumbnail = {}
for k, v in string.gmatch(result, '<image size="(.-)">(.-)</image>') do
grl.debug ('Image size ' .. k .. ' = ' .. v)
table.insert(userdata.media.thumbnail, v)
end
userdata.callback(userdata.media, 0)
end
|
lua-factory: port grl-lastfm-cover.lua to the new lua system
|
lua-factory: port grl-lastfm-cover.lua to the new lua system
https://bugzilla.gnome.org/show_bug.cgi?id=753141
Acked-by: Victor Toso <[email protected]>
|
Lua
|
lgpl-2.1
|
GNOME/grilo-plugins,jasuarez/grilo-plugins,grilofw/grilo-plugins,MikePetullo/grilo-plugins,grilofw/grilo-plugins,jasuarez/grilo-plugins,MikePetullo/grilo-plugins,MikePetullo/grilo-plugins,GNOME/grilo-plugins
|
f884bcbac382157800e0a02853960828fe6707ca
|
libs/fs.lua
|
libs/fs.lua
|
local prev, pl, dirname, dir = ...
local glob = prev.require 'posix.glob'.glob
local romPath = pl.path.normpath(pl.path.join(dirname, 'cc'))
local function findRomFile(path)
return pl.path.normpath(pl.path.join(romPath, path))
end
local function betterifyPath(path)
local oldPath
while oldPath ~= path do
oldPath = path
if path:sub(1, 1) == '/' then
path = path:sub(2)
end
if path:sub(1, 2) == './' or path == '.' then
path = path:sub(2)
end
if path:sub(1, 3) == '../' or path == '..' then
path = path:sub(3)
end
if path:sub(-2) == '/.' then
path = path:sub(1, -3)
end
end
return path
end
dir = '/' .. betterifyPath(dir)
dirname = '/' .. betterifyPath(dirname)
romPath = '/' .. betterifyPath(pl.path.abspath(romPath))
local function findPath(path)
path = pl.path.normpath(path)
path = betterifyPath(path)
if path:sub(1, 3) == 'rom' then
return findRomFile(path)
end
return pl.path.normpath(pl.path.join(dir, path))
end
local function runRom(path, ...)
local fn, err = prev.loadfile(findRomFile(path), 't', _G)
if err then
error(err)
end
if setfenv then
setfenv(fn, _G)
end
return fn(...)
end
return {
isReadOnly = function(path)
return betterifyPath(path):sub(1, 3) == 'rom'
end;
delete = function(path)
path = findPath(path)
if pl.path.exists(path) then
local ok, err = pl.file.delete(path)
if err then
error(err)
end
end
end;
move = function(src, dest)
src = findPath(src)
dest = findPath(dest)
if not pl.path.exists(src) then
error('No such file', 2)
end
if pl.path.exists(dest) then
error('File exists', 2)
end
pl.file.move(src, dest)
end;
copy = function(src, dest)
src = findPath(src)
dest = findPath(dest)
if not pl.path.exists(src) then
error('No such file', 2)
end
if pl.path.exists(dest) then
error('File exists', 2)
end
pl.file.copy(src, dest)
end;
list = function(path)
path = findPath(path)
if not pl.path.isdir(path) then
error('Not a directory', 2)
end
local files = {}
if path == dir then
files[#files + 1] = 'rom'
end
for file in pl.path.dir(path) do
if file ~= '.' and file ~= '..' then
files[#files + 1] = file
end
end
table.sort(files)
return files
end;
open = function(path, mode)
path = findPath(path)
if not pl.path.isfile(path) and (mode == 'r' or mode == 'rb') then return nil end
local file
local h = {}
if mode == 'r' then
file = prev.io.open(path, 'r')
if not file then return end
function h.readAll()
local data, err = file:read('*a')
if data then
data = data:gsub('\13', '\n')
-- prev.print('all', pl.pretty.write(data))
return data
else
if err then
error(err)
else
return ''
end
end
end
function h.readLine()
local line = file:read('*l')
if line then
line = line:gsub('[\13\n\r]*$', '')
end
-- prev.print('line', pl.pretty.write(line))
return line
end
elseif mode == 'w' or mode == 'a' then
file = prev.io.open(path, mode)
function h.write(data)
file:write(data)
end
function h.writeLine(data)
file:write(data)
file:write('\n')
end
function h.flush()
file:flush()
end
end
local open = true
function h.close()
if open then
file:close()
end
open = false
end
return h
end;
exists = function(path)
return pl.path.exists(findPath(path)) ~= false
end;
getDrive = function(path)
path = findPath(path)
if pl.path.exists(path) then
if path:find(romPath, 1, true) then
return 'rom'
else
return 'hdd'
end
end
end;
isDir = function(path)
return pl.path.isdir(findPath(path))
end;
combine = function(a, b)
local function doIt()
if a == '' then
a = '/'
end
if a:sub(1, 1) ~= '/' and a:sub(1, 2) ~= './' then
a = '/' .. a
end
if b == '.' then
return a
end
if a == '/' and b == '..' then
return '..'
end
if a:sub(-2) == '..' and b == '..' then
return a .. '/..'
end
return pl.path.normpath(pl.path.join(a, b))
end
local res = doIt()
if res:sub(1, 1) == '/' then
res = res:sub(2)
end
return res
end;
getName = function(path) return pl.path.basename(path) end;
getSize = function(path) return math.pow(2, 20) end;
find = function(pat)
pat = pl.path.normpath(pat or '')
pat = pat:gsub('%*%*', '*')
local results = {}
for _, path in ipairs(glob(findPath(pat)) or {}) do
results[#results + 1] = pl.path.relpath(path, dir)
end
for _, path in ipairs(glob(findRomFile(pat)) or {}) do
results[#results + 1] = pl.path.relpath(path, romPath)
end
return results
end;
makeDir = function(path)
path = findPath(path)
pl.path.mkdir(path)
end;
}, runRom
|
local prev, pl, dirname, dir = ...
local glob = prev.require 'posix.glob'.glob
local romPath = pl.path.normpath(pl.path.join(dirname, 'cc'))
local function findRomFile(path)
return pl.path.normpath(pl.path.join(romPath, path))
end
local function betterifyPath(path)
local oldPath
while oldPath ~= path do
oldPath = path
if path:sub(1, 1) == '/' then
path = path:sub(2)
end
if path:sub(1, 2) == './' or path == '.' then
path = path:sub(2)
end
if path:sub(1, 3) == '../' or path == '..' then
path = path:sub(3)
end
if path:sub(-2) == '/.' then
path = path:sub(1, -3)
end
end
return path
end
dir = '/' .. betterifyPath(dir)
dirname = '/' .. betterifyPath(dirname)
romPath = '/' .. betterifyPath(pl.path.abspath(romPath))
local function findPath(path)
path = pl.path.normpath(path)
path = betterifyPath(path)
if path:sub(1, 3) == 'rom' then
return findRomFile(path)
end
return pl.path.normpath(pl.path.join(dir, path))
end
local function runRom(path, ...)
local fn, err = prev.loadfile(findRomFile(path), 't', _G)
if err then
error(err)
end
if setfenv then
setfenv(fn, _G)
end
return fn(...)
end
return {
isReadOnly = function(path)
return betterifyPath(path):sub(1, 3) == 'rom'
end;
delete = function(path)
path = findPath(path)
if pl.path.exists(path) then
local ok, err = pl.file.delete(path)
if err then
error(err)
end
end
end;
move = function(src, dest)
src = findPath(src)
dest = findPath(dest)
if not pl.path.exists(src) then
error('No such file', 2)
end
if pl.path.exists(dest) then
error('File exists', 2)
end
pl.file.move(src, dest)
end;
copy = function(src, dest)
src = findPath(src)
dest = findPath(dest)
if not pl.path.exists(src) then
error('No such file', 2)
end
if pl.path.exists(dest) then
error('File exists', 2)
end
pl.file.copy(src, dest)
end;
list = function(path)
path = findPath(path)
if not pl.path.isdir(path) then
error('Not a directory', 2)
end
local files = {}
if path == dir then
files[#files + 1] = 'rom'
end
for file in pl.path.dir(path) do
if file ~= '.' and file ~= '..' then
files[#files + 1] = file
end
end
table.sort(files)
return files
end;
open = function(path, mode)
path = findPath(path)
if not pl.path.isfile(path) and (mode == 'r' or mode == 'rb') then return nil end
local file
local h = {}
if mode == 'r' then
file = prev.io.open(path, 'r')
if not file then return end
function h.readAll()
local data, err = file:read('*a')
if data then
data = data:gsub('\13', '\n')
-- prev.print('all', pl.pretty.write(data))
return data
else
if err then
error(err)
else
return ''
end
end
end
function h.readLine()
local line = file:read('*l')
if line then
line = line:gsub('[\13\n\r]*$', '')
end
-- prev.print('line', pl.pretty.write(line))
return line
end
elseif mode == 'w' or mode == 'a' then
file = prev.io.open(path, mode)
function h.write(data)
file:write(data)
end
function h.writeLine(data)
file:write(data)
file:write('\n')
end
function h.flush()
file:flush()
end
end
local open = true
function h.close()
if open then
file:close()
end
open = false
end
return h
end;
exists = function(path)
return pl.path.exists(findPath(path)) ~= false
end;
getDrive = function(path)
path = findPath(path)
if pl.path.exists(path) then
if path:find(romPath, 1, true) then
return 'rom'
else
return 'hdd'
end
end
end;
isDir = function(path)
return pl.path.isdir(findPath(path))
end;
combine = function(a, b)
local function doIt()
if a == '' then
a = '/'
end
if a:sub(1, 1) ~= '/' and a:sub(1, 2) ~= './' then
a = '/' .. a
end
if b == '.' then
return a
end
if a == '/' and b == '..' then
return '..'
end
if a:sub(-2) == '..' and b == '..' then
return a .. '/..'
end
return pl.path.normpath(pl.path.join(a, b))
end
local res = doIt()
if res:sub(1, 1) == '/' then
res = res:sub(2)
end
return res
end;
getName = function(path) return pl.path.basename(path) end;
getDir = function(path) return pl.path.dirname(path) end;
getSize = function(path) return 512 end;
getFreeSpace = function(path) return math.huge end;
find = function(pat)
pat = pl.path.normpath(pat or '')
pat = pat:gsub('%*%*', '*')
local results = {}
for _, path in ipairs(glob(findPath(pat)) or {}) do
results[#results + 1] = pl.path.relpath(path, dir)
end
for _, path in ipairs(glob(findRomFile(pat)) or {}) do
results[#results + 1] = pl.path.relpath(path, romPath)
end
return results
end;
makeDir = function(path)
path = findPath(path)
pl.path.mkdir(path)
end;
}, runRom
|
Add `fs.getDir` and `fs.getFreeSpace`, Fix `fs.getSize`
|
Add `fs.getDir` and `fs.getFreeSpace`, Fix `fs.getSize`
|
Lua
|
mit
|
CoderPuppy/cc-emu,CoderPuppy/cc-emu,CoderPuppy/cc-emu
|
f95e5426f35a1bb3f09a4e71a8126781b75d772d
|
orange/plugins/kafka/handler.lua
|
orange/plugins/kafka/handler.lua
|
local BasePlugin = require("orange.plugins.base_handler")
local cjson = require "cjson"
local producer = require "resty.kafka.producer"
local client = require "resty.kafka.client"
local KafkaHandler = BasePlugin:extend()
KafkaHandler.PRIORITY = 2000
function KafkaHandler:new(store)
KafkaHandler.super.new(self, "key_auth-plugin")
self.store = store
end
-- log_format main '$remote_addr - $remote_user [$time_local] "$request" '
-- '$status $body_bytes_sent "$http_referer" '
-- '"$http_user_agent" "$request_time" "$ssl_protocol" "$ssl_cipher" "$http_x_forwarded_for"'
-- '"$upstream_addr" "$upstream_status" "$upstream_response_length" "$upstream_response_time"';
function KafkaHandler:access()
local log_json = {}
log_json["remote_addr"] = ngx.var.remote_addr and ngx.var.remote_addr or '-'
log_json["remote_user"] = ngx.var.remote_user and ngx.var.remote_user or '-'
log_json["time_local"] = ngx.var.time_local and ngx.var.time_local or '-'
log_json['request'] = ngx.var.request and ngx.var.request or '-'
log_json["status"] = ngx.var.status and ngx.var.status or '-'
log_json["body_bytes_sent"] = ngx.var.body_bytes_sent and ngx.var.body_bytes_sent or '-'
log_json["http_referer"] = ngx.var.http_referer and ngx.var.http_referer or '-'
log_json["http_user_agent"] = ngx.var.http_user_agent and ngx.var.http_user_agent or '-'
log_json["request_time"] = ngx.var.request_time and ngx.var.request_time or '-'
log_json["uri"]=ngx.var.uri and ngx.var.uri or '-'
log_json["args"]=ngx.var.args and ngx.var.args or '-'
log_json["host"]=ngx.var.host and ngx.var.host or '-'
log_json["request_body"]=ngx.var.request_body and ngx.var.request_body or '-'
log_json['ssl_protocol'] = ngx.var.ssl_protocol and ngx.var.ssl_protocol or ' -'
log_json['ssl_cipher'] = ngx.var.ssl_cipher and ngx.var.ssl_cipher or ' -'
log_json['upstream_addr'] = ngx.var.upstream_addr and ngx.var.upstream_addr or ' -'
log_json['upstream_status'] = ngx.var.upstream_status and ngx.var.upstream_status or ' -'
log_json['upstream_response_length'] = ngx.var.upstream_response_length and ngx.var.upstream_response_length or ' -'
log_json["http_x_forwarded_for"] = ngx.var.http_x_forwarded_for and ngx.var.http_x_forwarded_for or '-'
log_json["upstream_response_time"] = ngx.var.upstream_response_time and ngx.var.upstream_response_time or '-'
local upstream_url = ngx.var.upstream_url .. ngx.var.upstream_request_uri;
log_json["upstream_url"] = "http://" .. upstream_url;
log_json["request_headers"] = ngx.req.get_headers();
log_json["response_headers"] = ngx.resp.get_headers();
-- 定义kafka broker地址,ip需要和kafka的host.name配置一致
local broker_list = context.config.plugin_config.kafka.broker_list
local kafka_topic = context.config.plugin_config.kafka.topic
local producer_config = context.config.plugin_config.kafka.producer_config
-- 定义json便于日志数据整理收集
-- 转换json为字符串
local message = cjson.encode(log_json);
-- 定义kafka异步生产者
local bp = producer:new(broker_list, producer_config)
-- 发送日志消息,send第二个参数key,用于kafka路由控制:
-- key为nill(空)时,一段时间向同一partition写入数据
-- 指定key,按照key的hash写入到对应的partition
local ok, err = bp:send(kafka_topic, nil, message)
if not ok then
ngx.log(ngx.ERR, "kafka send err:", err)
return
end
end
return KafkaHandler
|
local BasePlugin = require("orange.plugins.base_handler")
local cjson = require "cjson"
local producer = require "resty.kafka.producer"
local KafkaHandler = BasePlugin:extend()
KafkaHandler.PRIORITY = 2000
function KafkaHandler:new(store)
KafkaHandler.super.new(self, "key_auth-plugin")
self.store = store
end
local function errlog(...)
ngx.log(ngx.ERR,'[Kafka]',...)
end
local do_log = function(log_table)
-- 定义kafka broker地址,ip需要和kafka的host.name配置一致
local broker_list = context.config.plugin_config.kafka.broker_list
local kafka_topic = context.config.plugin_config.kafka.topic
local producer_config = context.config.plugin_config.kafka.producer_config
-- 定义json便于日志数据整理收集
-- 转换json为字符串
local message = cjson.encode(log_table);
-- 定义kafka异步生产者
local bp = producer:new(broker_list, producer_config)
-- 发送日志消息,send第二个参数key,用于kafka路由控制:
-- key为nill(空)时,一段时间向同一partition写入数据
-- 指定key,按照key的hash写入到对应的partition
local ok, err = bp:send(kafka_topic, nil, message)
if not ok then
ngx.log(ngx.ERR, "kafka send err:", err)
return
end
end
local function log(premature,log_table)
if premature then
errlog("timer premature")
return
end
local ok,err = pcall(do_log,log_table)
if not ok then
errlog("failed to record log by kafka",err)
local ok,err = ngx.timer.at(0,log,log_table)
if not ok then
errlog ("faild to create timer",err)
end
end
end
-- log_format main '$remote_addr - $remote_user [$time_local] "$request" '
-- '$status $body_bytes_sent "$http_referer" '
-- '"$http_user_agent" "$request_time" "$ssl_protocol" "$ssl_cipher" "$http_x_forwarded_for"'
-- '"$upstream_addr" "$upstream_status" "$upstream_response_length" "$upstream_response_time"';
function KafkaHandler:log()
local log_json = {}
log_json["remote_addr"] = ngx.var.remote_addr and ngx.var.remote_addr or '-'
log_json["remote_user"] = ngx.var.remote_user and ngx.var.remote_user or '-'
log_json["time_local"] = ngx.var.time_local and ngx.var.time_local or '-'
log_json['request'] = ngx.var.request and ngx.var.request or '-'
log_json["status"] = ngx.var.status and ngx.var.status or '-'
log_json["body_bytes_sent"] = ngx.var.body_bytes_sent and ngx.var.body_bytes_sent or '-'
log_json["http_referer"] = ngx.var.http_referer and ngx.var.http_referer or '-'
log_json["http_user_agent"] = ngx.var.http_user_agent and ngx.var.http_user_agent or '-'
log_json["request_time"] = ngx.var.request_time and ngx.var.request_time or '-'
log_json["uri"]=ngx.var.uri and ngx.var.uri or '-'
log_json["args"]=ngx.var.args and ngx.var.args or '-'
log_json["host"]=ngx.var.host and ngx.var.host or '-'
log_json["request_body"]=ngx.var.request_body and ngx.var.request_body or '-'
log_json['ssl_protocol'] = ngx.var.ssl_protocol and ngx.var.ssl_protocol or ' -'
log_json['ssl_cipher'] = ngx.var.ssl_cipher and ngx.var.ssl_cipher or ' -'
log_json['upstream_addr'] = ngx.var.upstream_addr and ngx.var.upstream_addr or ' -'
log_json['upstream_status'] = ngx.var.upstream_status and ngx.var.upstream_status or ' -'
log_json['upstream_response_length'] = ngx.var.upstream_response_length and ngx.var.upstream_response_length or ' -'
log_json["http_x_forwarded_for"] = ngx.var.http_x_forwarded_for and ngx.var.http_x_forwarded_for or '-'
log_json["upstream_response_time"] = ngx.var.upstream_response_time and ngx.var.upstream_response_time or '-'
local upstream_url = ngx.var.upstream_url .. ngx.var.upstream_request_uri;
log_json["upstream_url"] = "http://" .. upstream_url;
log_json["request_headers"] = ngx.req.get_headers();
log_json["response_headers"] = ngx.resp.get_headers();
local ok,err = ngx.timer.at(0,log,log_json)
if not ok then
errlog ("faild to create timer",err)
end
end
return KafkaHandler
|
fix phase bug: 1. Api disabled in log phrase 2.access phrase could not get fully info
|
fix phase bug: 1. Api disabled in log phrase 2.access phrase could not get fully info
|
Lua
|
mit
|
thisverygoodhhhh/orange,thisverygoodhhhh/orange,sumory/orange,sumory/orange,sumory/orange,thisverygoodhhhh/orange
|
7b16a973864e08684ad29d6753d1fd14c7bafb9c
|
src/daemon.lua
|
src/daemon.lua
|
--[[
transitd daemon main file
@file daemon.lua
@license The MIT License (MIT)
@author Alex <[email protected]>
@author William Fleurant <[email protected]>
@author Serg <[email protected]>
@copyright 2016 Alex
@copyright 2016 William Fleurant
@copyright 2016 Serg
--]]
local config = require("config")
local db = require("db")
local threadman = require("threadman")
local scanner = require("scanner")
local socket = require("socket")
local gateway = require("gateway")
local gatewayEnabled = config.gateway.enabled == "yes";
local start = true
while start do
print("[transitd]", "starting up...")
db.prepareDatabase()
db.purge()
-- configure gateway functionality
if gatewayEnabled then gateway.setup() end
threadman.setup()
-- start conneciton manager
threadman.startThreadInFunction('conman', 'run')
-- start shell script runner
if (config.gateway.enabled == "yes" and (config.gateway.onRegister ~= "" or config.gateway.onRelease ~= ""))
or (config.gateway.enabled ~= "yes" and (config.subscriber.onConnect ~= "" or config.subscriber.onDisconnect ~= "")) then
threadman.startThreadInFunction('shrunner', 'run')
end
-- start network scan if one hasn't already been started
scanner.startScan()
-- TODO: set up SIGTERM callback
-- send shutdown message
-- threadman.notify({type="exit"})
-- start http server
threadman.startThreadInFunction('httpd', 'run')
-- start monitor thread
threadman.startThreadInFunction('monitor', 'run')
-- wait until exit message is issued, send heartbeats
local retval = 0
local listener = threadman.registerListener("main",{"exit","error","info","config"})
while true do
local msg = "";
while msg ~= nil do
msg = listener:listen(true)
if msg ~= nil then
if msg["type"] == "exit" then
if msg["retval"] then retval = msg["retval"] end
break
end
if msg["type"] == "error" or msg["type"] == "info" then
print("[transitd]", msg["type"])
for k,v in pairs(msg) do
if k ~= "type" then
print("["..msg["type"].."]", k, v)
end
end
end
if msg["type"] == "config" then
set_config(msg.setting, msg.value)
end
end
end
if msg ~= nil and msg["type"] == "exit" then
start = msg["restart"]
break
end
socket.sleep(1)
threadman.notify({type = "heartbeat", ["time"] = os.time()})
end
if gatewayEnabled then gateway.teardown() end
threadman.unregisterListener(listener)
print("[transitd]", "shutting down...")
threadman.teardown()
end
print("[transitd]", "exiting.")
os.exit(retval)
|
--[[
transitd daemon main file
@file daemon.lua
@license The MIT License (MIT)
@author Alex <[email protected]>
@author William Fleurant <[email protected]>
@author Serg <[email protected]>
@copyright 2016 Alex
@copyright 2016 William Fleurant
@copyright 2016 Serg
--]]
local config = require("config")
local db = require("db")
local threadman = require("threadman")
local scanner = require("scanner")
local socket = require("socket")
local gateway = require("gateway")
local start = true
while start do
print("[transitd]", "starting up...")
db.prepareDatabase()
db.purge()
local gatewayEnabled = config.gateway.enabled == "yes";
-- configure gateway functionality
if gatewayEnabled then gateway.setup() end
threadman.setup()
-- start conneciton manager
threadman.startThreadInFunction('conman', 'run')
-- start shell script runner
if (config.gateway.enabled == "yes" and (config.gateway.onRegister ~= "" or config.gateway.onRelease ~= ""))
or (config.gateway.enabled ~= "yes" and (config.subscriber.onConnect ~= "" or config.subscriber.onDisconnect ~= "")) then
threadman.startThreadInFunction('shrunner', 'run')
end
-- start network scan if one hasn't already been started
scanner.startScan()
-- TODO: set up SIGTERM callback
-- send shutdown message
-- threadman.notify({type="exit"})
-- start http server
threadman.startThreadInFunction('httpd', 'run')
-- start monitor thread
threadman.startThreadInFunction('monitor', 'run')
-- wait until exit message is issued, send heartbeats
local retval = 0
local listener = threadman.registerListener("main",{"exit","error","info","config"})
while true do
local msg = "";
while msg ~= nil do
msg = listener:listen(true)
if msg ~= nil then
if msg["type"] == "exit" then
if msg["retval"] then retval = msg["retval"] end
break
end
if msg["type"] == "error" or msg["type"] == "info" then
print("[transitd]", msg["type"])
for k,v in pairs(msg) do
if k ~= "type" then
print("["..msg["type"].."]", k, v)
end
end
end
if msg["type"] == "config" then
set_config(msg.setting, msg.value)
end
end
end
if msg ~= nil and msg["type"] == "exit" then
start = msg["restart"]
break
end
socket.sleep(1)
threadman.notify({type = "heartbeat", ["time"] = os.time()})
end
if gatewayEnabled then gateway.teardown() end
threadman.unregisterListener(listener)
print("[transitd]", "shutting down...")
threadman.teardown()
end
print("[transitd]", "exiting.")
os.exit(retval)
|
Small fix
|
Small fix
|
Lua
|
mit
|
transitd/transitd,intermesh-networks/transitd,transitd/transitd,intermesh-networks/transitd,transitd/transitd,pdxmeshnet/mnigs,pdxmeshnet/mnigs
|
04ca12bb7fabca7004e42a8c2956c0cfd5fe72b5
|
frontend/device/remarkable/device.lua
|
frontend/device/remarkable/device.lua
|
local Generic = require("device/generic/device") -- <= look at this file!
local logger = require("logger")
local function yes() return true end
local function no() return false end
local Remarkable = Generic:new{
model = "reMarkable",
isRemarkable = yes,
hasKeys = yes,
hasOTAUpdates = yes,
canReboot = yes,
canPowerOff = yes,
isTouchDevice = yes,
hasFrontlight = no,
display_dpi = 226,
}
local EV_ABS = 3
local ABS_X = 00
local ABS_Y = 01
local ABS_MT_POSITION_X = 53
local ABS_MT_POSITION_Y = 54
-- Resolutions from libremarkable src/framebuffer/common.rs
local mt_width = 767 -- unscaled_size_check: ignore
local mt_height = 1023 -- unscaled_size_check: ignore
local mt_scale_x = 1404 / mt_width
local mt_scale_y = 1872 / mt_height
local adjustTouchEvt = function(self, ev)
if ev.type == EV_ABS then
-- Mirror X and scale up both X & Y as touch input is different res from
-- display
if ev.code == ABS_X or ev.code == ABS_MT_POSITION_X then
ev.value = (mt_width - ev.value) * mt_scale_x
end
if ev.code == ABS_Y or ev.code == ABS_MT_POSITION_Y then
ev.value = (mt_height - ev.value) * mt_scale_y
end
end
end
function Remarkable:init()
self.screen = require("ffi/framebuffer_mxcfb"):new{device = self, debug = logger.dbg}
self.powerd = require("device/remarkable/powerd"):new{device = self}
self.input = require("device/input"):new{
device = self,
event_map = require("device/remarkable/event_map"),
}
self.input.open("/dev/input/event0") -- Wacom
self.input.open("/dev/input/event1") -- Touchscreen
self.input.open("/dev/input/event2") -- Buttons
self.input:registerEventAdjustHook(adjustTouchEvt)
-- USB plug/unplug, battery charge/not charging are generated as fake events
self.input.open("fake_events")
local rotation_mode = self.screen.ORIENTATION_PORTRAIT
self.screen.native_rotation_mode = rotation_mode
self.screen.cur_rotation_mode = rotation_mode
Generic.init(self)
end
function Remarkable:supportsScreensaver() return true end
function Remarkable:setDateTime(year, month, day, hour, min, sec)
if hour == nil or min == nil then return true end
local command
if year and month and day then
command = string.format("timedatectl set-time '%d-%d-%d %d:%d:%d'", year, month, day, hour, min, sec)
else
command = string.format("timedatectl set-time '%d:%d'",hour, min)
end
return os.execute(command) == 0
end
function Remarkable:intoScreenSaver()
local Screensaver = require("ui/screensaver")
if self.screen_saver_mode == false then
Screensaver:show()
end
self.powerd:beforeSuspend()
self.screen_saver_mode = true
end
function Remarkable:outofScreenSaver()
if self.screen_saver_mode == true then
local Screensaver = require("ui/screensaver")
Screensaver:close()
end
self.powerd:afterResume()
self.screen_saver_mode = false
end
function Remarkable:suspend()
os.execute("systemctl suspend")
end
function Remarkable:resume()
end
function Remarkable:powerOff()
os.execute("systemctl poweroff")
end
function Remarkable:reboot()
os.execute("systemctl reboot")
end
return Remarkable
|
local Generic = require("device/generic/device") -- <= look at this file!
local logger = require("logger")
local function yes() return true end
local function no() return false end
local Remarkable = Generic:new{
model = "reMarkable",
isRemarkable = yes,
hasKeys = yes,
hasOTAUpdates = yes,
canReboot = yes,
canPowerOff = yes,
isTouchDevice = yes,
hasFrontlight = no,
display_dpi = 226,
}
local EV_ABS = 3
local ABS_X = 00
local ABS_Y = 01
local ABS_MT_POSITION_X = 53
local ABS_MT_POSITION_Y = 54
-- Resolutions from libremarkable src/framebuffer/common.rs
local screen_width = 1404 -- unscaled_size_check: ignore
local screen_height = 1872 -- unscaled_size_check: ignore
local wacom_width = 15725 -- unscaled_size_check: ignore
local wacom_height = 20967 -- unscaled_size_check: ignore
local wacom_scale_x = screen_width / wacom_width
local wacom_scale_y = screen_height / wacom_height
local mt_width = 767 -- unscaled_size_check: ignore
local mt_height = 1023 -- unscaled_size_check: ignore
local mt_scale_x = screen_width / mt_width
local mt_scale_y = screen_height / mt_height
local adjustTouchEvt = function(self, ev)
if ev.type == EV_ABS then
-- Mirror X and scale up both X & Y as touch input is different res from
-- display
if ev.code == ABS_MT_POSITION_X then
ev.value = (mt_width - ev.value) * mt_scale_x
end
if ev.code == ABS_MT_POSITION_Y then
ev.value = (mt_height - ev.value) * mt_scale_y
end
-- The Wacom input layer is non-multi-touch and
-- uses its own scaling factor.
-- The X and Y coordinates are swapped, and the (real) Y
-- coordinate has to be inverted.
if ev.code == ABS_X then
ev.code = ABS_Y
ev.value = (wacom_height - ev.value) * wacom_scale_y
elseif ev.code == ABS_Y then
ev.code = ABS_X
ev.value = ev.value * wacom_scale_x
end
end
end
function Remarkable:init()
self.screen = require("ffi/framebuffer_mxcfb"):new{device = self, debug = logger.dbg}
self.powerd = require("device/remarkable/powerd"):new{device = self}
self.input = require("device/input"):new{
device = self,
event_map = require("device/remarkable/event_map"),
}
self.input.open("/dev/input/event0") -- Wacom
self.input.open("/dev/input/event1") -- Touchscreen
self.input.open("/dev/input/event2") -- Buttons
self.input:registerEventAdjustHook(adjustTouchEvt)
-- USB plug/unplug, battery charge/not charging are generated as fake events
self.input.open("fake_events")
local rotation_mode = self.screen.ORIENTATION_PORTRAIT
self.screen.native_rotation_mode = rotation_mode
self.screen.cur_rotation_mode = rotation_mode
Generic.init(self)
end
function Remarkable:supportsScreensaver() return true end
function Remarkable:setDateTime(year, month, day, hour, min, sec)
if hour == nil or min == nil then return true end
local command
if year and month and day then
command = string.format("timedatectl set-time '%d-%d-%d %d:%d:%d'", year, month, day, hour, min, sec)
else
command = string.format("timedatectl set-time '%d:%d'",hour, min)
end
return os.execute(command) == 0
end
function Remarkable:intoScreenSaver()
local Screensaver = require("ui/screensaver")
if self.screen_saver_mode == false then
Screensaver:show()
end
self.powerd:beforeSuspend()
self.screen_saver_mode = true
end
function Remarkable:outofScreenSaver()
if self.screen_saver_mode == true then
local Screensaver = require("ui/screensaver")
Screensaver:close()
end
self.powerd:afterResume()
self.screen_saver_mode = false
end
function Remarkable:suspend()
os.execute("systemctl suspend")
end
function Remarkable:resume()
end
function Remarkable:powerOff()
os.execute("systemctl poweroff")
end
function Remarkable:reboot()
os.execute("systemctl reboot")
end
return Remarkable
|
Fix remarkable pen input (#6031)
|
Fix remarkable pen input (#6031)
fixes #6030
|
Lua
|
agpl-3.0
|
NiLuJe/koreader,pazos/koreader,Frenzie/koreader,NiLuJe/koreader,Hzj-jie/koreader,koreader/koreader,Frenzie/koreader,koreader/koreader,poire-z/koreader,poire-z/koreader,Markismus/koreader,mwoz123/koreader
|
9fec566036d1c3f79386129eae3a51fca4bf059b
|
triggerfield/lakeoflife_triggers.lua
|
triggerfield/lakeoflife_triggers.lua
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- INSERT INTO triggerfields VALUES (641, 266, -9,'triggerfield.lakeoflife_triggers');
-- INSERT INTO triggerfields VALUES (640, 266, -9,'triggerfield.lakeoflife_triggers');
-- INSERT INTO triggerfields VALUES (639, 245, -9,'triggerfield.lakeoflife_triggers');
-- INSERT INTO triggerfields VALUES (731, 325, -9,'triggerfield.lakeoflife_triggers');
-- INSERT INTO triggerfields VALUES (767, 305, -9,'triggerfield.lakeoflife_triggers');
-- INSERT INTO triggerfields VALUES (666, 235, -9,'triggerfield.lakeoflife_triggers');
-- INSERT INTO triggerfields VALUES (770, 293, -9,'triggerfield.lakeoflife_triggers');
-- INSERT INTO triggerfields VALUES (769, 300, -9,'triggerfield.lakeoflife_triggers');
-- INSERT INTO triggerfields VALUES (782, 293, -9,'triggerfield.lakeoflife_triggers');
-- INSERT INTO triggerfields VALUES (779, 293, -9,'triggerfield.lakeoflife_triggers');
-- INSERT INTO triggerfields VALUES (786, 294, -9,'triggerfield.lakeoflife_triggers');
--Triggerfield events in the Lake of Life dungeon
local common = require("base.common")
local M = {}
function M.MoveToField( User )
if User:getType() ~= Character.player then
return
end
if Random.uniform(1, 4) == 1 then
if User.pos == position(641, 266, -9) then -- inform
common.InformNLS(User,"Wenn Du den Eisflu umgangen hast kannst Du eine Stelle in der Eismauer ausmachen welche weggeschlagen wurde.","As you round the iceflow, you can see a section of ice wall has been chisled away.")
elseif User.pos == position(640, 266, -9) then -- inform
common.InformNLS(User,"Ein unheimliches Glhen scheint aus dem Eisboden und den Eiswnden hervorzukommen.","An eerie glow seems to come up through the ice floor and emanate out the ice walls.")
elseif User.pos == position(639, 245, -9) then -- inform
common.InformNLS(User,"Ein lautes Zerreien ist aus einiger Entfernung zu hren, gefolgt von Knacken und Krachen.","A loud cracking can be heard in the distance, followed by some crashing and splashing.")
world:makeSound(5, User.pos)
world:makeSound(9, User.pos)
elseif User.pos == position(731, 325, -9) then -- Knock out warp.
common.InformNLS(User,"Du rutscht ab und fllst ins Wasser. Du wirst weit vom Dock wieder an Land gesphlt.","You slip and fall into the water, washing ashore far from the dock.")
world:gfx(11, User.pos)
world:makeSound(9, User.pos)
User:warp(position(767, 305, -9))
world:gfx(11, User.pos)
world:makeSound(9, User.pos)
elseif User.pos == position(666, 235, -9) then -- inform
common.InformNLS(User,"In der Nhe hrst Du etwas laut etwas unter Wasser rutschen.","You hear something loud slip under the water nearby.")
world:makeSound(5, User.pos)
elseif Character.pos == position(770, 293, -9) or Character.pos == position(769, 300, -9) then -- Ice Entrapment #1
common.InformNLS(User,"Du hrst etwas laut unter deinem Fu knacken. Eine Falle lst aus und Du bist pltzlich im Eis verschttet. Bist Du klug genug um einen Weg heraus zu finden?","You hear something loud click under your foot. A trap springs and you are suddenly entombed in ice. Are you clever enough to find your way out?")
world:gfx(41, User.pos)
world:makeSound(5, User.pos)
User:warp(position(770, 295, -9))
world:gfx(41, User.pos)
world:makeSound(13, User.pos)
elseif Character.pos == position(782, 293, -9) or Character.pos == position(779, 293, -9) or Character.pos == position(786, 294, -9) then -- Ice Entrapment #2
common.InformNLS(User,"Du hrst etwas laut unter deinem Fu knacken. Eine Falle lst aus und Du bist pltzlich im Eis verschttet. Bist Du klug genug um einen Weg heraus zu finden?","You hear something loud click under your foot. A trap springs and you are suddenly entombed in ice. Are you clever enough to find your way out?")
world:gfx(41, User.pos)
world:makeSound(5, User.pos)
User:warp(position(784, 291, -9))
world:gfx(41, User.pos)
world:makeSound(13, User.pos)
end
end
end
return M
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- INSERT INTO triggerfields VALUES (641, 266, -9,'triggerfield.lakeoflife_triggers');
-- INSERT INTO triggerfields VALUES (640, 266, -9,'triggerfield.lakeoflife_triggers');
-- INSERT INTO triggerfields VALUES (639, 245, -9,'triggerfield.lakeoflife_triggers');
-- INSERT INTO triggerfields VALUES (731, 325, -9,'triggerfield.lakeoflife_triggers');
-- INSERT INTO triggerfields VALUES (767, 305, -9,'triggerfield.lakeoflife_triggers');
-- INSERT INTO triggerfields VALUES (666, 235, -9,'triggerfield.lakeoflife_triggers');
-- INSERT INTO triggerfields VALUES (770, 293, -9,'triggerfield.lakeoflife_triggers');
-- INSERT INTO triggerfields VALUES (769, 300, -9,'triggerfield.lakeoflife_triggers');
-- INSERT INTO triggerfields VALUES (782, 293, -9,'triggerfield.lakeoflife_triggers');
-- INSERT INTO triggerfields VALUES (779, 293, -9,'triggerfield.lakeoflife_triggers');
-- INSERT INTO triggerfields VALUES (786, 294, -9,'triggerfield.lakeoflife_triggers');
--Triggerfield events in the Lake of Life dungeon
local common = require("base.common")
local M = {}
function M.MoveToField( User )
if User:getType() ~= Character.player then
return
end
if Random.uniform(1, 4) == 1 then
if User.pos == position(641, 266, -9) then -- inform
common.InformNLS(User,"Wenn Du den Eisflu umgangen hast kannst Du eine Stelle in der Eismauer ausmachen welche weggeschlagen wurde.","As you round the iceflow, you can see a section of ice wall has been chisled away.")
elseif User.pos == position(640, 266, -9) then -- inform
common.InformNLS(User,"Ein unheimliches Glhen scheint aus dem Eisboden und den Eiswnden hervorzukommen.","An eerie glow seems to come up through the ice floor and emanate out the ice walls.")
elseif User.pos == position(639, 245, -9) then -- inform
common.InformNLS(User,"Ein lautes Zerreien ist aus einiger Entfernung zu hren, gefolgt von Knacken und Krachen.","A loud cracking can be heard in the distance, followed by some crashing and splashing.")
world:makeSound(5, User.pos)
world:makeSound(9, User.pos)
elseif User.pos == position(731, 325, -9) then -- Knock out warp.
common.InformNLS(User,"Du rutscht ab und fllst ins Wasser. Du wirst weit vom Dock wieder an Land gesphlt.","You slip and fall into the water, washing ashore far from the dock.")
world:gfx(11, User.pos)
world:makeSound(9, User.pos)
User:warp(position(767, 305, -9))
world:gfx(11, User.pos)
world:makeSound(9, User.pos)
elseif User.pos == position(666, 235, -9) then -- inform
common.InformNLS(User,"In der Nhe hrst Du etwas laut etwas unter Wasser rutschen.","You hear something loud slip under the water nearby.")
world:makeSound(5, User.pos)
elseif User.pos == position(770, 293, -9) or User.pos == position(769, 300, -9) then -- Ice Entrapment #1
common.InformNLS(User,"Du hrst etwas laut unter deinem Fu knacken. Eine Falle lst aus und Du bist pltzlich im Eis verschttet. Bist Du klug genug um einen Weg heraus zu finden?","You hear something loud click under your foot. A trap springs and you are suddenly entombed in ice. Are you clever enough to find your way out?")
world:gfx(41, User.pos)
world:makeSound(5, User.pos)
User:warp(position(770, 295, -9))
world:gfx(41, User.pos)
world:makeSound(13, User.pos)
elseif User.pos == position(782, 293, -9) or User.pos == position(779, 293, -9) or User.pos == position(786, 294, -9) then -- Ice Entrapment #2
common.InformNLS(User,"Du hrst etwas laut unter deinem Fu knacken. Eine Falle lst aus und Du bist pltzlich im Eis verschttet. Bist Du klug genug um einen Weg heraus zu finden?","You hear something loud click under your foot. A trap springs and you are suddenly entombed in ice. Are you clever enough to find your way out?")
world:gfx(41, User.pos)
world:makeSound(5, User.pos)
User:warp(position(784, 291, -9))
world:gfx(41, User.pos)
world:makeSound(13, User.pos)
end
end
end
return M
|
Fixes
|
Fixes
|
Lua
|
agpl-3.0
|
Baylamon/Illarion-Content,LaFamiglia/Illarion-Content,vilarion/Illarion-Content,KayMD/Illarion-Content,Illarion-eV/Illarion-Content
|
32ee1873ac89f2bd510d8982d702e127fc19d39b
|
modules/luci-mod-system/luasrc/model/cbi/admin_system/admin.lua
|
modules/luci-mod-system/luasrc/model/cbi/admin_system/admin.lua
|
-- Copyright 2008 Steven Barth <[email protected]>
-- Copyright 2011 Jo-Philipp Wich <[email protected]>
-- Licensed to the public under the Apache License 2.0.
local fs = require "nixio.fs"
m = Map("system", translate("Router Password"),
translate("Changes the administrator password for accessing the device"))
s = m:section(TypedSection, "_dummy", "")
s.addremove = false
s.anonymous = true
pw1 = s:option(Value, "pw1", translate("Password"))
pw1.password = true
pw2 = s:option(Value, "pw2", translate("Confirmation"))
pw2.password = true
function s.cfgsections()
return { "_pass" }
end
function m.parse(map)
local v1 = pw1:formvalue("_pass")
local v2 = pw2:formvalue("_pass")
if v1 and v2 and #v1 > 0 and #v2 > 0 then
if v1 == v2 then
if luci.sys.user.setpasswd(luci.dispatcher.context.authuser, v1) == 0 then
m.message = translate("Password successfully changed!")
else
m.message = translate("Unknown Error, password not changed!")
end
else
m.message = translate("Given password confirmation did not match, password not changed!")
end
end
Map.parse(map)
end
if fs.access("/etc/config/dropbear") then
m2 = Map("dropbear", translate("SSH Access"),
translate("Dropbear offers <abbr title=\"Secure Shell\">SSH</abbr> network shell access and an integrated <abbr title=\"Secure Copy\">SCP</abbr> server"))
s = m2:section(TypedSection, "dropbear", translate("Dropbear Instance"))
s.anonymous = true
s.addremove = true
ni = s:option(Value, "Interface", translate("Interface"),
translate("Listen only on the given interface or, if unspecified, on all"))
ni.template = "cbi/network_netlist"
ni.nocreate = true
ni.unspecified = true
pt = s:option(Value, "Port", translate("Port"),
translate("Specifies the listening port of this <em>Dropbear</em> instance"))
pt.datatype = "port"
pt.default = 22
pa = s:option(Flag, "PasswordAuth", translate("Password authentication"),
translate("Allow <abbr title=\"Secure Shell\">SSH</abbr> password authentication"))
pa.enabled = "on"
pa.disabled = "off"
pa.default = pa.enabled
pa.rmempty = false
ra = s:option(Flag, "RootPasswordAuth", translate("Allow root logins with password"),
translate("Allow the <em>root</em> user to login with password"))
ra.enabled = "on"
ra.disabled = "off"
ra.default = ra.enabled
gp = s:option(Flag, "GatewayPorts", translate("Gateway ports"),
translate("Allow remote hosts to connect to local SSH forwarded ports"))
gp.enabled = "on"
gp.disabled = "off"
gp.default = gp.disabled
s2 = m2:section(TypedSection, "_dummy", translate("SSH-Keys"),
translate("Here you can paste public SSH-Keys (one per line) for SSH public-key authentication."))
s2.addremove = false
s2.anonymous = true
s2.template = "cbi/tblsection"
function s2.cfgsections()
return { "_keys" }
end
keys = s2:option(TextValue, "_data", "")
keys.wrap = "off"
keys.rows = 3
function keys.cfgvalue()
return fs.readfile("/etc/dropbear/authorized_keys") or ""
end
function keys.write(self, section, value)
return fs.writefile("/etc/dropbear/authorized_keys", value:gsub("\r\n", "\n"))
end
function keys.remove(self, section, value)
return fs.writefile("/etc/dropbear/authorized_keys", "")
end
end
return m, m2
|
-- Copyright 2008 Steven Barth <[email protected]>
-- Copyright 2011 Jo-Philipp Wich <[email protected]>
-- Licensed to the public under the Apache License 2.0.
local fs = require "nixio.fs"
m = Map("system", translate("Router Password"),
translate("Changes the administrator password for accessing the device"))
m.apply_on_parse = true
s = m:section(TypedSection, "_dummy", "")
s.addremove = false
s.anonymous = true
pw1 = s:option(Value, "pw1", translate("Password"))
pw1.password = true
pw2 = s:option(Value, "pw2", translate("Confirmation"))
pw2.password = true
function s.cfgsections()
return { "_pass" }
end
function m.parse(map)
local v1 = pw1:formvalue("_pass")
local v2 = pw2:formvalue("_pass")
if v1 and v2 and #v1 > 0 and #v2 > 0 then
if v1 == v2 then
if luci.sys.user.setpasswd(luci.dispatcher.context.authuser, v1) == 0 then
m.message = translate("Password successfully changed!")
else
m.message = translate("Unknown Error, password not changed!")
end
else
m.message = translate("Given password confirmation did not match, password not changed!")
end
end
Map.parse(map)
end
if fs.access("/etc/config/dropbear") then
m2 = Map("dropbear", translate("SSH Access"),
translate("Dropbear offers <abbr title=\"Secure Shell\">SSH</abbr> network shell access and an integrated <abbr title=\"Secure Copy\">SCP</abbr> server"))
m2.apply_on_parse = true
s = m2:section(TypedSection, "dropbear", translate("Dropbear Instance"))
s.anonymous = true
s.addremove = true
ni = s:option(Value, "Interface", translate("Interface"),
translate("Listen only on the given interface or, if unspecified, on all"))
ni.template = "cbi/network_netlist"
ni.nocreate = true
ni.unspecified = true
pt = s:option(Value, "Port", translate("Port"),
translate("Specifies the listening port of this <em>Dropbear</em> instance"))
pt.datatype = "port"
pt.default = 22
pa = s:option(Flag, "PasswordAuth", translate("Password authentication"),
translate("Allow <abbr title=\"Secure Shell\">SSH</abbr> password authentication"))
pa.enabled = "on"
pa.disabled = "off"
pa.default = pa.enabled
pa.rmempty = false
ra = s:option(Flag, "RootPasswordAuth", translate("Allow root logins with password"),
translate("Allow the <em>root</em> user to login with password"))
ra.enabled = "on"
ra.disabled = "off"
ra.default = ra.enabled
gp = s:option(Flag, "GatewayPorts", translate("Gateway ports"),
translate("Allow remote hosts to connect to local SSH forwarded ports"))
gp.enabled = "on"
gp.disabled = "off"
gp.default = gp.disabled
s2 = m2:section(TypedSection, "_dummy", translate("SSH-Keys"),
translate("Here you can paste public SSH-Keys (one per line) for SSH public-key authentication."))
s2.addremove = false
s2.anonymous = true
s2.template = "cbi/tblsection"
function s2.cfgsections()
return { "_keys" }
end
keys = s2:option(TextValue, "_data", "")
keys.wrap = "off"
keys.rows = 3
function keys.cfgvalue()
return fs.readfile("/etc/dropbear/authorized_keys") or ""
end
function keys.write(self, section, value)
return fs.writefile("/etc/dropbear/authorized_keys", value:gsub("\r\n", "\n"))
end
function keys.remove(self, section, value)
return fs.writefile("/etc/dropbear/authorized_keys", "")
end
end
return m, m2
|
luci-base: fix misleading warning message when adding SSH keys
|
luci-base: fix misleading warning message when adding SSH keys
Prevent an incorrect / misleading "There are no changes to apply" message
from popping up when adding a new SSH key to the text box.
Fixes #2048.
Signed-off-by: Dirk Brenken <[email protected]>
[reword commit message]
Signed-off-by: Jo-Philipp Wich <[email protected]>
|
Lua
|
apache-2.0
|
openwrt/luci,openwrt/luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,artynet/luci,openwrt-es/openwrt-luci,hnyman/luci,tobiaswaldvogel/luci,artynet/luci,Noltari/luci,openwrt-es/openwrt-luci,nmav/luci,openwrt/luci,Noltari/luci,lbthomsen/openwrt-luci,openwrt/luci,openwrt/luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,rogerpueyo/luci,nmav/luci,rogerpueyo/luci,rogerpueyo/luci,Noltari/luci,Noltari/luci,openwrt-es/openwrt-luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,nmav/luci,hnyman/luci,artynet/luci,nmav/luci,Noltari/luci,lbthomsen/openwrt-luci,Noltari/luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,rogerpueyo/luci,rogerpueyo/luci,rogerpueyo/luci,tobiaswaldvogel/luci,openwrt/luci,nmav/luci,tobiaswaldvogel/luci,artynet/luci,artynet/luci,hnyman/luci,tobiaswaldvogel/luci,hnyman/luci,artynet/luci,nmav/luci,nmav/luci,Noltari/luci,artynet/luci,hnyman/luci,hnyman/luci,tobiaswaldvogel/luci,rogerpueyo/luci,Noltari/luci,hnyman/luci,lbthomsen/openwrt-luci,nmav/luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,artynet/luci,rogerpueyo/luci,openwrt/luci,lbthomsen/openwrt-luci,artynet/luci,hnyman/luci,openwrt/luci,openwrt-es/openwrt-luci,nmav/luci,Noltari/luci
|
c919d8f108d7a5e00b477cdbe6c7aa8514a8f4cc
|
src/cli/config.lua
|
src/cli/config.lua
|
#!/usr/bin/env lua
local cutils = require "kong.cli.utils"
local constants = require "kong.constants"
local args = require("lapp")(string.format([[
Duplicate an existing configuration for given environment.
Usage: kong config [options]
Options:
-c,--config (default %s) configuration file
-o,--output (default .) ouput
-e,--env (string) environment name
]], constants.CLI.GLOBAL_KONG_CONF))
local CONFIG_FILENAME = string.format("kong%s.yml", args.env ~= "" and "_"..args.env or "")
local config_path = cutils.get_kong_config_path(args.config)
local config_content = cutils.read_file(config_path)
local DEFAULT_ENV_VALUES = {
TEST = {
["send_anonymous_reports: true"] = "send_anonymous_reports: false",
["keyspace: kong"] = "keyspace: kong_tests",
["lua_package_path ';;'"] = "lua_package_path './src/?.lua;;'",
["error_log logs/error.log info"] = "error_log logs/error.log debug",
["listen 8000"] = "listen 8100",
["listen 8001"] = "listen 8101"
},
DEVELOPMENT = {
["send_anonymous_reports: true"] = "send_anonymous_reports: false",
["keyspace: kong"] = "keyspace: kong_development",
["lua_package_path ';;'"] = "lua_package_path './src/?.lua;;'",
["error_log logs/error.log info"] = "error_log logs/error.log debug",
["lua_code_cache on"] = "lua_code_cache off",
["daemon on"] = "daemon off"
}
}
-- Create a new default kong config for given environment
if DEFAULT_ENV_VALUES[args.env:upper()] then
-- If we know the environment we can override some of the variables
for k, v in pairs(DEFAULT_ENV_VALUES[args.env:upper()]) do
config_content = config_content:gsub(k, v)
end
end
cutils.write_to_file(cutils.path:join(args.output, CONFIG_FILENAME), config_content)
|
#!/usr/bin/env lua
local cutils = require "kong.cli.utils"
local constants = require "kong.constants"
local args = require("lapp")(string.format([[
Duplicate an existing configuration for given environment.
Usage: kong config [options]
Options:
-c,--config (default %s) configuration file
-o,--output (default .) ouput
-e,--env (string) environment name
]], constants.CLI.GLOBAL_KONG_CONF))
local CONFIG_FILENAME = string.format("kong%s.yml", args.env ~= "" and "_"..args.env or "")
local config_path = cutils.get_kong_config_path(args.config)
local config_content = cutils.read_file(config_path)
local DEFAULT_ENV_VALUES = {
TEST = {
["nginx_working_dir: /usr/local/kong/"] = "nginx_working_dir: nginx_tmp",
["send_anonymous_reports: true"] = "send_anonymous_reports: false",
["keyspace: kong"] = "keyspace: kong_tests",
["lua_package_path ';;'"] = "lua_package_path './src/?.lua;;'",
["error_log logs/error.log info"] = "error_log logs/error.log debug",
["listen 8000"] = "listen 8100",
["listen 8001"] = "listen 8101"
},
DEVELOPMENT = {
["nginx_working_dir: /usr/local/kong/"] = "nginx_working_dir: nginx_tmp",
["send_anonymous_reports: true"] = "send_anonymous_reports: false",
["keyspace: kong"] = "keyspace: kong_development",
["lua_package_path ';;'"] = "lua_package_path './src/?.lua;;'",
["error_log logs/error.log info"] = "error_log logs/error.log debug",
["lua_code_cache on"] = "lua_code_cache off",
["daemon on"] = "daemon off"
}
}
-- Create a new default kong config for given environment
if DEFAULT_ENV_VALUES[args.env:upper()] then
-- If we know the environment we can override some of the variables
for k, v in pairs(DEFAULT_ENV_VALUES[args.env:upper()]) do
config_content = config_content:gsub(k, v)
end
end
cutils.write_to_file(cutils.path:join(args.output, CONFIG_FILENAME), config_content)
|
fix: TEST and DEVELOPMENT run in ./nginx_tmp
|
fix: TEST and DEVELOPMENT run in ./nginx_tmp
|
Lua
|
apache-2.0
|
Skyscanner/kong,skynet/kong,puug/kong,bbalu/kong,ChristopherBiscardi/kong,paritoshmmmec/kong,sbuettner/kong,wakermahmud/kong,ropik/kong,AnsonSmith/kong,peterayeni/kong,vmercierfr/kong,chourobin/kong
|
cbde8473cf7b39597589a76aa3907c5ee9dd36c8
|
src/demo/xmake.lua
|
src/demo/xmake.lua
|
-- add target
target("demo")
-- add the dependent target
add_deps("tbox")
-- make as a binary
set_kind("binary")
-- add defines
add_defines("__tb_prefix__=\"demo\"")
-- set the object files directory
set_objectdir("$(buildir)/.objs")
-- add links directory
add_linkdirs("$(buildir)")
-- add includes directory
add_includedirs("$(buildir)")
add_includedirs("$(buildir)/tbox")
-- add links
add_links("tbox")
-- add packages
add_packages("zlib", "mysql", "sqlite3", "pcre", "pcre2", "openssl", "polarssl", "mbedtls", "base")
-- add the source files
add_files("*.c")
add_files("libc/*.c")
add_files("libm/integer.c")
add_files("math/random.c")
add_files("utils/*.c|option.c")
add_files("other/*.c|charset.c")
add_files("string/*.c")
add_files("memory/**.c")
add_files("platform/*.c|exception.c|context.c")
add_files("container/*.c")
add_files("algorithm/*.c")
add_files("stream/stream.c")
add_files("stream/stream/*.c")
add_files("network/**.c")
-- add the source files for the hash module
if is_option("hash") then
add_files("hash/*.c")
end
-- add the source files for the float type
if is_option("float") then
add_files("math/fixed.c")
add_files("libm/float.c")
add_files("libm/double.c")
end
-- add the source files for the coroutine module
if is_option("coroutine") then
add_files("coroutine/*.c")
add_files("platform/context.c")
end
-- add the source files for the exception module
if is_option("exception") then
add_files("platform/exception.c")
end
-- add the source files for the xml module
if is_option("xml") then
add_files("xml/*.c")
end
-- add the source files for the regex module
if is_option("regex") then
add_files("regex/*.c")
end
-- add the source files for the asio module
if is_option("deprecated") then
add_files("asio/deprecated/*.c")
add_files("stream/deprecated/async_stream.c")
add_files("stream/deprecated/transfer_pool.c")
add_files("stream/deprecated/async_transfer.c")
add_files("stream/deprecated/async_stream/*.c")
end
-- add the source files for the object module
if is_option("object") then
add_files("utils/option.c")
add_files("object/*.c")
end
-- add the source files for the charset module
if is_option("charset") then add_files("other/charset.c") end
-- add the source files for the database module
if is_option("database") then add_files("database/sql.c") end
|
-- add target
target("demo")
-- add the dependent target
add_deps("tbox")
-- make as a binary
set_kind("binary")
-- add defines
add_defines("__tb_prefix__=\"demo\"")
-- set the object files directory
set_objectdir("$(buildir)/.objs")
-- add links directory
add_linkdirs("$(buildir)")
-- add includes directory
add_includedirs("$(buildir)")
add_includedirs("$(buildir)/tbox")
-- add links
add_links("tbox")
-- add packages
add_packages("zlib", "mysql", "sqlite3", "pcre", "pcre2", "openssl", "polarssl", "mbedtls", "base")
-- add the source files
add_files("*.c")
add_files("libc/*.c")
add_files("libm/integer.c")
add_files("math/random.c")
add_files("utils/*.c|option.c")
add_files("other/*.c|charset.c")
add_files("string/*.c")
add_files("memory/**.c")
add_files("platform/*.c|exception.c|context.c")
add_files("container/*.c")
add_files("algorithm/*.c")
add_files("stream/stream.c")
add_files("stream/stream/*.c")
add_files("network/**.c")
-- add the source files for the hash module
if is_option("hash") then
add_files("hash/*.c")
end
-- add the source files for the float type
if is_option("float") then
add_files("math/fixed.c")
add_files("libm/float.c")
add_files("libm/double.c")
end
-- add the source files for the coroutine module
if is_option("coroutine") then
add_files("coroutine/*.c|spider.c")
add_files("platform/context.c")
if is_option("xml") then
add_files("coroutine/spider.c")
end
end
-- add the source files for the exception module
if is_option("exception") then
add_files("platform/exception.c")
end
-- add the source files for the xml module
if is_option("xml") then
add_files("xml/*.c")
end
-- add the source files for the regex module
if is_option("regex") then
add_files("regex/*.c")
end
-- add the source files for the asio module
if is_option("deprecated") then
add_files("asio/deprecated/*.c")
add_files("stream/deprecated/async_stream.c")
add_files("stream/deprecated/transfer_pool.c")
add_files("stream/deprecated/async_transfer.c")
add_files("stream/deprecated/async_stream/*.c")
end
-- add the source files for the object module
if is_option("object") then
add_files("utils/option.c")
add_files("object/*.c")
end
-- add the source files for the charset module
if is_option("charset") then add_files("other/charset.c") end
-- add the source files for the database module
if is_option("database") then add_files("database/sql.c") end
|
fix compile error for spider
|
fix compile error for spider
|
Lua
|
apache-2.0
|
waruqi/tbox,tboox/tbox,waruqi/tbox,tboox/tbox
|
1d3a8c551b152463ed41142354686d8f567216b2
|
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 split_host(server, def_host, def_port)
if not server then return def_host, def_port end
local host, port = string.match(server, "^(.-):(%d*)$")
if not host then return server, def_port end
if #port == 0 then port = def_port end
return host, port
end
-------------------------------------------------------------------
local Connection = ut.class() do
function Connection:__init(server)
self._host, self._port = split_host(server, "127.0.0.1", "6379")
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:connected()
return not not self._cnn
end
local function call_q(q, ...)
while true do
local cb = q:pop()
if not cb then break end
cb(...)
end
end
function Connection:open(cb)
if self._ready then
uv.defer(cb, self)
return self
end
if not self._cnn then
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)
while true do
local data = self._delay_q:pop()
if not data then break end
cli:write(data, self._on_write_handler)
end
call_q(self._open_q, self)
self._ready = true
end)
if not ok then return nil, err end
self._cnn = ok
end
if cb then self._open_q:push(cb) 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._close_q, self, err)
end)
end
err = err or EOF
call_q(self._open_q, self, err)
self._stream:reset(err or EOF)
self._delay_q:reset()
self._ready = false
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 split_host(server, def_host, def_port)
if not server then return def_host, def_port end
local host, port = string.match(server, "^(.-):(%d*)$")
if not host then return server, def_port end
if #port == 0 then port = def_port end
return host, port
end
-------------------------------------------------------------------
local Connection = ut.class() do
function Connection:__init(server)
self._host, self._port = split_host(server, "127.0.0.1", "6379")
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:connected()
return not not self._cnn
end
local function call_q(q, ...)
while true do
local cb = q:pop()
if not cb then break end
cb(...)
end
end
function Connection:open(cb)
if self._ready then
uv.defer(cb, self)
return self
end
if not self._cnn then
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)
while true do
local data = self._delay_q:pop()
if not data then break end
cli:write(data, self._on_write_handler)
end
self._ready = true
call_q(self._open_q, self)
end)
if not ok then return nil, err end
self._cnn = ok
end
if cb then self._open_q:push(cb) 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._close_q, self, err)
end)
end
err = err or EOF
call_q(self._open_q, self, err)
self._stream:reset(err or EOF)
self._delay_q:reset()
self._ready = false
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;
}
|
Fix. Set ready before open callback.
|
Fix. Set ready before open callback.
|
Lua
|
mit
|
moteus/lua-lluv-redis
|
9d45b4f99445fdb75346710955bdb7e2b29a1cc2
|
BatchNormalization.lua
|
BatchNormalization.lua
|
--Based on: http://arxiv.org/pdf/1502.03167v3
--If input dimension is larger than 1, a reshape is needed before and after usage.
--Usage example:
------------------------------------
-- model:add(nn.Reshape(3 * 32 * 32))
-- model:add(batchNormalization(3 * 32 * 32))
-- model:add(nn.Reshape(3 , 32 , 32))
------------------------------------
local Meanvec, parent = torch.class('nn.Meanvec', 'nn.Module')
function Meanvec:__init()
parent.__init(self)
end
function Meanvec:updateOutput(input)
self.output:resizeAs(input)
self.size = input:nElement()
self.std = torch.std(input) * torch.sqrt((self.size - 1.0) / self.size )
self.mean = torch.mean(input)
self.output:copy(input):add(-self.mean):div(self.std)
return self.output
end
function Meanvec:updateGradInput(input, gradOutput)
local der1 = input:clone():fill(1.0)
der1 = der1:diag()
der1:add(-1.0/self.size):div(self.std)
local der2 = input:clone()
der2:add(-self.mean)
local temp = torch.Tensor(self.size,self.size):fill(0)
temp:addr(der1,-1.0/(self.size* torch.pow(self.std,3)),der2,der2)
self.gradInput:resizeAs(gradOutput):fill(0)
self.gradInput:addmv(temp,gradOutput)
return self.gradInput
end
function batchNormalization(inputSize)
local module = nn.Sequential()
module:add(nn.Meanvec())
module:add(nn.CMul(inputSize))
module:add(nn.Add(inputSize,false))
return module
end
|
--Based on: http://arxiv.org/pdf/1502.03167v3
--Usage example:
------------------------------------
-- model:add(nn.BatchNormalization(3 * 32 * 32))
------------------------------------
require 'nn'
require 'cunn'
local BatchNormalization, parent = torch.class('nn.BatchNormalization', 'nn.Module')
function BatchNormalization:__init(inputSize)
parent.__init(self)
self.bias = torch.Tensor(inputSize)
self.weight = torch.Tensor(inputSize)
self.gradBias = torch.Tensor(inputSize)
self.gradWeight = torch.Tensor(inputSize)
self:reset(stdv)
end
function BatchNormalization:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1./math.sqrt(self.bias:nElement())
end
self.bias:uniform(-stdv,stdv)
self.weight:uniform(-stdv,stdv)
end
function BatchNormalization:updateOutput(input)
self.output = self.output or input.new()
self.output:resizeAs(input)
self.size = input:nElement()
self.std = torch.std(input) * torch.sqrt((self.size - 1.0) / self.size )
self.mean = torch.mean(input)
self.stdcube = torch.pow(self.std,3)
self.ones = torch.Tensor(self.size):fill(1.0)-- :cuda()
self.output:copy(input):add(-self.mean):div(self.std)
self.buffer = self.buffer or input.new()
self.buffer:resizeAs(self.output):copy(self.output)
self.output:cmul(self.weight)
self.output:add(self.bias)
return self.output
end
function BatchNormalization:updateGradInput(input, gradOutput)
self.buffer = self.buffer or gradOutput.new()
self.buffer:resizeAs(gradOutput):copy(gradOutput)
self.buffer:cmul(self.weight)
self.dotprod1 = torch.dot(self.ones,self.buffer)
local der1 = self.ones:clone()
der1:mul(- self.dotprod1 / self.size/self.std)
-- x_i - mu
local der2 = input:clone()
der2:add(-self.mean)
self.dotprod2 = torch.dot(der2,self.buffer)
der2:mul(self.dotprod2 / self.size / self.stdcube)
self.gradInput = self.buffer:clone()
self.gradInput:div(self.std)
self.gradInput:add(der1)
self.gradInput:add(-der2)
return self.gradInput
end
function BatchNormalization:accGradParameters(input, gradOutput, scale)
scale = scale or 1
self.gradBias:add(scale,gradOutput)
self.gradWeight:addcmul(scale,self.buffer,gradOutput)
end
|
Activation function based on: http://arxiv.org/pdf/1502.03167v3
|
Activation function based on: http://arxiv.org/pdf/1502.03167v3
Fixed the comment
|
Lua
|
mit
|
clementfarabet/lua---nnx
|
1f996001a3d4fa6cd98905b0de9158bdc2895e1c
|
Modules/Utility/os.lua
|
Modules/Utility/os.lua
|
-- @author Narrev
local function date(formatString, unix)
--- Allows you to use os.date in RobloxLua!
-- date ([format [, time]])
-- This is an optimized version. If you want to see how the numbers work, see the following:
-- https://github.com/Narrev/Unix-Epoch-Date-and-Time-Calculations/blob/master/Time%20Functions.lua
--
-- @param string formatString
-- If present, function date returns a string formatted by the tags in formatString.
-- If formatString starts with "!", date is formatted in UTC.
-- If formatString is "*t", date returns a table
-- Placing "_" in the middle of a tag (e.g. "%_d" "%_I") removes padding
-- String Reference: https://github.com/Narrev/NevermoreEngine/blob/patch-5/Modules/Utility/readme.md
-- @default "%c"
--
-- @param number unix
-- If present, unix is the time to be formatted. Otherwise, date formats the current time.
-- The amount of seconds since 1970 (negative numbers are occasionally supported)
-- @default tick()
-- @returns a string or a table containing date and time, formatted according to the given string format. If called without arguments, returns the equivalent of date("%c").
-- Localize functions
local ceil, floor, sub, find, gsub, format = math.ceil, math.floor, string.sub, string.find, string.gsub, string.format
-- Helper function
local function overflow(array, seed)
--- Subtracts the integer values in an array from a seed until the seed cannot be subtracted from any further
-- @param array array A table filled with integers to be subtracted from seed
-- @param integer seed A seed that is subtracted by the values in array until it would become negative from subtraction
-- @returns index at which the iterated value is greater than the remaining seed and what is left of the seed (before subtracting final value)
for i = 1, #array do
if seed - array[i] <= 0 then
return i, seed
end
seed = seed - array[i]
end
end
-- Find whether formatString was used
if formatString then
if type(formatString) == "number" then -- If they didn't pass a formatString, and only passed unix through
assert(type(unix) ~= "string", "Invalid parameters passed to os.date. Your parameters might be in the wrong order")
unix, formatString = formatString, "%c"
elseif type(formatString) == "string" then
assert(find(formatString, "*t") or find(formatString, "%%[_cxXTrRaAbBdHIjMmpsSuwyY]"), "Invalid string passed to os.date")
local UTC
formatString, UTC = gsub(formatString, "^!", "") -- If formatString begins in '!', use os.time()
assert(UTC == 0 or not unix, "Cannot determine time to format for os.date. Use either an \"!\" at the beginning of the string or pass a time parameter")
unix = UTC == 1 and os.time() or unix
end
else -- If they did not pass a formatting string
formatString = "%c"
end
-- Declare Variables
local unix = type(unix) == "number" and unix or tick()
-- Get hours, minutes, and seconds
local hours, minutes, seconds = floor(unix / 3600 % 24), floor(unix / 60 % 60), floor(unix % 60)
-- Get years, months, and days
local days, month, year = floor(unix / 86400) + 719528
local wday = (days + 6) % 7
local _4Years = 400*floor(days / 146097) + 100*floor(days % 146097 / 36524) + 4*floor(days % 146097 % 36524 / 1461) - 1
year, days = overflow({366,365,365,365}, days - 365*(_4Years + 1) - floor(.25*_4Years) - floor(.0025*_4Years) + floor(.01*_4Years)) -- [0-1461]
year, _4Years = year + _4Years -- _4Years is set to nil
local yDay = days
month, days = overflow({31,(year%4==0 and(year%25~=0 or year%16==0))and 29 or 28,31,30,31,30,31,31,30,31,30,31}, days)
if formatString == "*t" then -- Return a table if "*t" was used
return {year = year, month = month, day = days, yday = yDay, wday = wday, hour = hours, min = minutes, sec = seconds}
end
-- Necessary string tables
local dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
local months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
local suffixes = {"st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "st"}
-- Return formatted string
return (gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(formatString,
"%%c", "%%x %%X"),
"%%_c", "%%_x %%_X"),
"%%x", "%%m/%%d/%%y"),
"%%_x", "%%_m/%%_d/%%y"),
"%%X", "%%H:%%M:%%S"),
"%%_X", "%%_H:%%M:%%S"),
"%%T", "%%I:%%M %%p"),
"%%_T", "%%_I:%%M %%p"),
"%%r", "%%I:%%M:%%S %%p"),
"%%_r", "%%_I:%%M:%%S %%p"),
"%%R", "%%H:%%M"),
"%%_R", "%%_H:%%M"),
"%%a", sub(dayNames[wday + 1], 1, 3)),
"%%A", dayNames[wday + 1]),
"%%b", sub(months[month], 1, 3)),
"%%B", months[month]),
"%%d", format("%02d", days)),
"%%_d", days),
"%%H", format("%02d", hours)),
"%%_H", hours),
"%%I", format("%02d", hours > 12 and hours - 12 or hours == 0 and 12 or hours)),
"%%_I", hours > 12 and hours - 12 or hours == 0 and 12 or hours),
"%%j", format("%02d", yDay)),
"%%_j", yDay),
"%%M", format("%02d", minutes)),
"%%_M", minutes),
"%%m", format("%02d", month)),
"%%_m", month),
"%%n", "\n"),
"%%p", hours >= 12 and "pm" or "am"),
"%%_p", hours >= 12 and "PM" or "AM"),
"%%s", suffixes[days]),
"%%S", format("%02d", seconds)),
"%%_S", seconds),
"%%t", "\t"),
"%%u", wday == 0 and 7 or wday),
"%%w", wday),
"%%Y", year),
"%%y", format("%02d", year % 100)),
"%%_y", year % 100),
"%%%%", "%%")
)
end
local function clock()
local timeYielded, timeServerHasBeenRunning = wait()
return timeServerHasBeenRunning
end
return setmetatable({date = date, clock = clock}, {__index = os})
|
-- @author Narrev
local function date(formatString, unix)
--- Allows you to use os.date in RobloxLua!
-- date ([format [, time]])
-- This is an optimized version. If you want to see how the numbers work, see the following:
-- https://github.com/Narrev/Unix-Epoch-Date-and-Time-Calculations/blob/master/Time%20Functions.lua
--
-- @param string formatString
-- If present, function date returns a string formatted by the tags in formatString.
-- If formatString starts with "!", date is formatted in UTC.
-- If formatString is "*t", date returns a table
-- Placing "_" in the middle of a tag (e.g. "%_d" "%_I") removes padding
-- String Reference: https://github.com/Narrev/NevermoreEngine/blob/patch-5/Modules/Utility/readme.md
-- @default "%c"
--
-- @param number unix
-- If present, unix is the time to be formatted. Otherwise, date formats the current time.
-- The amount of seconds since 1970 (negative numbers are occasionally supported)
-- @default tick()
-- @returns a string or a table containing date and time, formatted according to the given string format. If called without arguments, returns the equivalent of date("%c").
-- Localize functions
local ceil, floor, sub, find, gsub, format = math.ceil, math.floor, string.sub, string.find, string.gsub, string.format
-- Helper functions
local function overflow(array, seed)
--- Subtracts the integer values in an array from a seed until the seed cannot be subtracted from any further
-- @param array array A table filled with integers to be subtracted from seed
-- @param integer seed A seed that is subtracted by the values in array until it would become negative from subtraction
-- @returns index at which the iterated value is greater than the remaining seed and what is left of the seed (before subtracting final value)
for i = 1, #array do
if seed - array[i] <= 0 then
return i, seed
end
seed = seed - array[i]
end
end
local function suffix(Number)
--- Returns st, nd (Like 1st, 2nd)
-- @param number Number The number to get the suffix of [1-31]
if Number < 21 and Number > 3 or Number > 23 and Number < 31 then return "th" end
return ({"st", "nd", "rd"})[Number % 10]
end
-- Find whether formatString was used
if formatString then
if type(formatString) == "number" then -- If they didn't pass a formatString, and only passed unix through
assert(type(unix) ~= "string", "Invalid parameters passed to os.date. Your parameters might be in the wrong order")
unix, formatString = formatString, "%c"
elseif type(formatString) == "string" then
assert(find(formatString, "*t") or find(formatString, "%%[_cxXTrRaAbBdHIjMmpsSuwyY]"), "Invalid string passed to os.date")
local UTC
formatString, UTC = gsub(formatString, "^!", "") -- If formatString begins in '!', use os.time()
assert(UTC == 0 or not unix, "Cannot determine time to format for os.date. Use either an \"!\" at the beginning of the string or pass a time parameter")
unix = UTC == 1 and os.time() or unix
end
else -- If they did not pass a formatting string
formatString = "%c"
end
-- Declare Variables
local unix = type(unix) == "number" and unix or tick()
-- Get hours, minutes, and seconds
local hours, minutes, seconds = floor(unix / 3600 % 24), floor(unix / 60 % 60), floor(unix % 60)
-- Get years, months, and days
local days, month, year = floor(unix / 86400) + 719528
local wday = (days + 6) % 7
local _4Years = 400*floor(days / 146097) + 100*floor(days % 146097 / 36524) + 4*floor(days % 146097 % 36524 / 1461) - 1
year, days = overflow({366,365,365,365}, days - 365*(_4Years + 1) - floor(.25*_4Years) - floor(.0025*_4Years) + floor(.01*_4Years)) -- [0-1461]
year, _4Years = year + _4Years -- _4Years is set to nil
local yDay = days
month, days = overflow({31,(year%4==0 and(year%25~=0 or year%16==0))and 29 or 28,31,30,31,30,31,31,30,31,30,31}, days)
if formatString == "*t" then -- Return a table if "*t" was used
return {year = year, month = month, day = days, yday = yDay, wday = wday, hour = hours, min = minutes, sec = seconds}
end
-- Necessary string tables
local dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
local months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
-- Return formatted string
return (gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(formatString,
"%%c", "%%x %%X"),
"%%_c", "%%_x %%_X"),
"%%x", "%%m/%%d/%%y"),
"%%_x", "%%_m/%%_d/%%y"),
"%%X", "%%H:%%M:%%S"),
"%%_X", "%%_H:%%M:%%S"),
"%%T", "%%I:%%M %%p"),
"%%_T", "%%_I:%%M %%p"),
"%%r", "%%I:%%M:%%S %%p"),
"%%_r", "%%_I:%%M:%%S %%p"),
"%%R", "%%H:%%M"),
"%%_R", "%%_H:%%M"),
"%%a", sub(dayNames[wday + 1], 1, 3)),
"%%A", dayNames[wday + 1]),
"%%b", sub(months[month], 1, 3)),
"%%B", months[month]),
"%%d", format("%02d", days)),
"%%_d", days),
"%%H", format("%02d", hours)),
"%%_H", hours),
"%%I", format("%02d", hours > 12 and hours - 12 or hours == 0 and 12 or hours)),
"%%_I", hours > 12 and hours - 12 or hours == 0 and 12 or hours),
"%%j", format("%02d", yDay)),
"%%_j", yDay),
"%%M", format("%02d", minutes)),
"%%_M", minutes),
"%%m", format("%02d", month)),
"%%_m", month),
"%%n", "\n"),
"%%p", hours >= 12 and "pm" or "am"),
"%%_p", hours >= 12 and "PM" or "AM"),
"%%s", suffix(days)),
"%%S", format("%02d", seconds)),
"%%_S", seconds),
"%%t", "\t"),
"%%u", wday == 0 and 7 or wday),
"%%w", wday),
"%%Y", year),
"%%y", format("%02d", year % 100)),
"%%_y", year % 100),
"%%%%", "%%")
)
end
local function clock()
local timeYielded, timeServerHasBeenRunning = wait()
return timeServerHasBeenRunning
end
return setmetatable({date = date, clock = clock}, {__index = os})
|
Added optimized suffix function
|
Added optimized suffix function
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
30d5ec4160a3204236dd4c8079b3ecc995165bdf
|
src/npge/algo/SequencesToLua.lua
|
src/npge/algo/SequencesToLua.lua
|
return function(blockset)
local wrap, yield = coroutine.wrap, coroutine.yield
return wrap(function()
yield [[do
local Sequence = require 'npge.model.Sequence'
local name2seq = {}
]]
local text = "name2seq[%q] = Sequence.fromRef(%q)\n"
for seq in blockset:iter_sequences() do
local name = seq:name()
local ref = assert(seq:toRef(),
"References don't work")
yield(text:format(name, ref))
end
yield [[
return name2seq
end]]
end)
end
|
return function(blockset)
local wrap, yield = coroutine.wrap, coroutine.yield
return wrap(function()
local preamble = [[do
local Sequence = require 'npge.model.Sequence'
local name2seq = {}
]]
yield(preamble)
local text = "name2seq[%q] = Sequence.fromRef(%q)\n"
for seq in blockset:iter_sequences() do
local name = seq:name()
local ref = assert(seq:toRef(),
"References don't work")
yield(text:format(name, ref))
end
local closing = [[
return name2seq
end]]
yield(closing)
end)
end
|
change SequencesToLua to increase coverage
|
change SequencesToLua to increase coverage
(workaround luacov's bug)
|
Lua
|
mit
|
npge/lua-npge,npge/lua-npge,starius/lua-npge,starius/lua-npge,starius/lua-npge,npge/lua-npge
|
8528fa3aa22d45ae9292690134dbf0c343dcb7b9
|
libs/core/luasrc/model/wireless.lua
|
libs/core/luasrc/model/wireless.lua
|
--[[
LuCI - Wireless model
Copyright 2009 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
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 pairs, i18n, uci, math = pairs, luci.i18n, luci.model.uci, math
local iwi = require "iwinfo"
local utl = require "luci.util"
local uct = require "luci.model.uci.bind"
module "luci.model.network.wireless"
local ub = uct.bind("wireless")
local st, ifs
function init(self, cursor)
cursor:unload("wireless")
cursor:load("wireless")
ub:init(cursor)
st = uci.cursor_state()
ifs = { }
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
local id = "%s.network%d" %{ self.device, count }
ifs[id] = {
id = id,
sid = s['.name'],
count = count
}
local dev = st:get("wireless", s['.name'], "ifname")
or st:get("wireless", s['.name'], "device")
local wtype = dev and iwi.type(dev)
if dev and wtype then
ifs[id].winfo = iwi[wtype]
ifs[id].wdev = dev
end
end)
end
function get_device(self, dev)
return device(dev)
end
function get_network(self, id)
if ifs[id] then
return network(ifs[id].sid)
else
local n
for n, _ in pairs(ifs) do
if ifs[n].sid == id then
return network(id)
end
end
end
end
function shortname(self, iface)
if iface.dev and iface.dev.wifi then
return "%s %q" %{
i18n.translate("a_s_if_iwmode_" .. (iface.dev.wifi.mode or "ap")),
iface.dev.wifi.ssid or iface.dev.wifi.bssid or "(hidden)"
}
else
return iface:name()
end
end
function get_i18n(self, iface)
if iface.dev and iface.dev.wifi then
return "%s: %s %q" %{
i18n.translate("a_s_if_wifinet", "Wireless Network"),
i18n.translate("a_s_if_iwmode_" .. (iface.dev.wifi.mode or "ap"), iface.dev.wifi.mode or "AP"),
iface.dev.wifi.ssid or iface.dev.wifi.bssid or "(hidden)"
}
else
return "%s: %q" %{ i18n.translate("a_s_if_wifinet", "Wireless Network"), iface:name() }
end
end
function rename_network(self, old, new)
local i
for i, _ in pairs(ifs) do
if ifs[i].network == old then
ifs[i].network = new
end
end
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.network == old then
if new then
ub.uci:set("wireless", s['.name'], "network", new)
else
ub.uci:delete("wireless", s['.name'], "network")
end
end
end)
end
function del_network(self, old)
return self:rename_network(old, nil)
end
function find_interfaces(self, iflist, brlist)
local iface
for iface, _ in pairs(ifs) do
iflist[iface] = ifs[iface]
end
end
function ignore_interface(self, iface)
if ifs and ifs[iface] then
return false
else
return iwi.type(iface) and true or false
end
end
function add_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:set("wireless", ifs[iface].sid, "network", net:name())
ifs[iface].network = net:name()
return true
end
return false
end
function del_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:delete("wireless", ifs[iface].sid, "network")
--return true
end
return false
end
device = ub:section("wifi-device")
device:property("type")
device:property("channel")
device:property("disabled")
function device.name(self)
return self.sid
end
function device.get_networks(self)
local nets = { }
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.device == self:name() then
nets[#nets+1] = network(s['.name'])
end
end)
return nets
end
network = ub:section("wifi-iface")
network:property("mode")
network:property("ssid")
network:property("bssid")
network:property("network")
function network._init(self, sid)
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
return s['.name'] ~= sid
end)
self.id = "%s.network%d" %{ self.device, count }
local dev = st:get("wireless", sid, "ifname")
or st:get("wireless", sid, "device")
local wtype = dev and iwi.type(dev)
if dev and wtype then
self.winfo = iwi[wtype]
self.wdev = dev
end
end
function network.name(self)
return self.id
end
function network.ifname(self)
return self.wdev
end
function network.get_device(self)
if self.device then
return device(self.device)
end
end
function network.active_mode(self)
local m = self.winfo and self.winfo.mode(self.wdev)
if m == "Master" or m == "Auto" then
m = "ap"
elseif m == "Ad-Hoc" then
m = "adhoc"
elseif m == "Client" then
m = "sta"
elseif m then
m = m:lower()
else
m = self:mode()
end
return m or "ap"
end
function network.active_mode_i18n(self)
return i18n.translate("a_s_if_iwmode_" .. self:active_mode())
end
function network.active_ssid(self)
return self.winfo and self.winfo.ssid(self.wdev) or
self:ssid()
end
function network.active_bssid(self)
return self.winfo and self.winfo.bssid(self.wdev) or
self:bssid() or "00:00:00:00:00:00"
end
function network.signal(self)
return self.winfo and self.winfo.signal(self.wdev) or 0
end
function network.noise(self)
return self.winfo and self.winfo.noise(self.wdev) or 0
end
function network.signal_level(self)
if self:active_bssid() ~= "00:00:00:00:00:00" then
local signal = self:signal()
local noise = self:noise()
if signal > 0 and noise > 0 then
local snr = -1 * (noise - signal)
return math.floor(snr / 5)
else
return 0
end
else
return -1
end
end
function network.signal_percent(self)
local qc = self.winfo and
self.winfo.quality(self.wdev) or 0
local qm = self.winfo and
self.winfo.quality_max(self.wdev) or 0
if qc > 0 and qm > 0 then
return math.floor((100 / qm) * qc)
else
return 0
end
end
|
--[[
LuCI - Wireless model
Copyright 2009 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
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 pairs, i18n, uci, math = pairs, luci.i18n, luci.model.uci, math
local iwi = require "iwinfo"
local utl = require "luci.util"
local uct = require "luci.model.uci.bind"
module "luci.model.wireless"
local ub = uct.bind("wireless")
local st, ifs
function init(cursor)
cursor:unload("wireless")
cursor:load("wireless")
ub:init(cursor)
st = uci.cursor_state()
ifs = { }
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
local id = "%s.network%d" %{ s.device, count }
ifs[id] = {
id = id,
sid = s['.name'],
count = count
}
local dev = st:get("wireless", s['.name'], "ifname")
or st:get("wireless", s['.name'], "device")
local wtype = dev and iwi.type(dev)
if dev and wtype then
ifs[id].winfo = iwi[wtype]
ifs[id].wdev = dev
end
end)
end
function get_device(self, dev)
return device(dev)
end
function get_network(self, id)
if ifs[id] then
return network(ifs[id].sid)
else
local n
for n, _ in pairs(ifs) do
if ifs[n].sid == id then
return network(id)
end
end
end
end
function shortname(self, iface)
if iface.wdev and iface.winfo then
return "%s %q" %{
i18n.translate("a_s_if_iwmode_" .. iface:active_mode(), iface.winfo.mode(iface.wdev)),
iface:active_ssid() or "(hidden)"
}
else
return iface:name()
end
end
function get_i18n(self, iface)
if iface.wdev and iface.winfo then
return "%s: %s %q (%s)" %{
i18n.translate("a_s_if_wifinet", "Wireless Network"),
i18n.translate("a_s_if_iwmode_" .. iface:active_mode(), iface.winfo.mode(iface.wdev)),
iface:active_ssid() or "(hidden)", iface.wdev
}
else
return "%s: %q" %{ i18n.translate("a_s_if_wifinet", "Wireless Network"), iface:name() }
end
end
function rename_network(self, old, new)
local i
for i, _ in pairs(ifs) do
if ifs[i].network == old then
ifs[i].network = new
end
end
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.network == old then
if new then
ub.uci:set("wireless", s['.name'], "network", new)
else
ub.uci:delete("wireless", s['.name'], "network")
end
end
end)
end
function del_network(self, old)
return self:rename_network(old, nil)
end
function find_interfaces(self, iflist, brlist)
local iface
for iface, _ in pairs(ifs) do
iflist[iface] = ifs[iface]
end
end
function ignore_interface(self, iface)
if ifs and ifs[iface] then
return false
else
return iwi.type(iface) and true or false
end
end
function add_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:set("wireless", ifs[iface].sid, "network", net:name())
ifs[iface].network = net:name()
return true
end
return false
end
function del_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:delete("wireless", ifs[iface].sid, "network")
--return true
end
return false
end
device = ub:section("wifi-device")
device:property("type")
device:property("channel")
device:property("disabled")
function device.name(self)
return self.sid
end
function device.get_networks(self)
local nets = { }
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.device == self:name() then
nets[#nets+1] = network(s['.name'])
end
end)
return nets
end
network = ub:section("wifi-iface")
network:property("mode")
network:property("ssid")
network:property("bssid")
network:property("network")
function network._init(self, sid)
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
return s['.name'] ~= sid
end)
local dev = st:get("wireless", sid, "ifname")
or st:get("wireless", sid, "device")
if dev then
self.id = "%s.network%d" %{ dev, count }
local wtype = iwi.type(dev)
if dev and wtype then
self.winfo = iwi[wtype]
self.wdev = dev
end
end
end
function network.name(self)
return self.id
end
function network.ifname(self)
return self.wdev
end
function network.get_device(self)
if self.device then
return device(self.device)
end
end
function network.active_mode(self)
local m = self.winfo and self.winfo.mode(self.wdev)
if m == "Master" or m == "Auto" then
m = "ap"
elseif m == "Ad-Hoc" then
m = "adhoc"
elseif m == "Client" then
m = "sta"
elseif m then
m = m:lower()
else
m = self:mode()
end
return m or "ap"
end
function network.active_mode_i18n(self)
return i18n.translate("a_s_if_iwmode_" .. self:active_mode())
end
function network.active_ssid(self)
return self.winfo and self.winfo.ssid(self.wdev) or
self:ssid()
end
function network.active_bssid(self)
return self.winfo and self.winfo.bssid(self.wdev) or
self:bssid() or "00:00:00:00:00:00"
end
function network.signal(self)
return self.winfo and self.winfo.signal(self.wdev) or 0
end
function network.noise(self)
return self.winfo and self.winfo.noise(self.wdev) or 0
end
function network.signal_level(self)
if self:active_bssid() ~= "00:00:00:00:00:00" then
local signal = self:signal()
local noise = self:noise()
if signal > 0 and noise > 0 then
local snr = -1 * (noise - signal)
return math.floor(snr / 5)
else
return 0
end
else
return -1
end
end
function network.signal_percent(self)
local qc = self.winfo and
self.winfo.quality(self.wdev) or 0
local qm = self.winfo and
self.winfo.quality_max(self.wdev) or 0
if qc > 0 and qm > 0 then
return math.floor((100 / qm) * qc)
else
return 0
end
end
|
libs/core: fixes luci.model.wireless
|
libs/core: fixes luci.model.wireless
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5438 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
|
247761ae57af548c52a8bb0d5dbb60fba9729a18
|
src/lib/cpuset.lua
|
src/lib/cpuset.lua
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(...,package.seeall)
local numa = require('lib.numa')
local S = require('syscall')
local CPUSet = {}
function new()
return setmetatable({by_node={}}, {__index=CPUSet})
end
do
local cpuset = false
function global_cpuset()
if not cpuset then cpuset = new() end
return cpuset
end
end
local function available_cpus (node)
local function subtract (s, t)
local ret = {}
for k,_ in pairs(s) do
if not t[k] then table.insert(ret, k) end
end
table.sort(ret)
return ret
end
-- XXX: Add sched_getaffinity cpus.
return subtract(numa.node_cpus(node), numa.isolated_cpus())
end
function CPUSet:bind_to_numa_node()
local nodes = {}
for node, _ in pairs(self.by_node) do table.insert(nodes, node) end
if #nodes == 0 then
print("No CPUs available; not binding to any NUMA node.")
elseif #nodes == 1 then
numa.bind_to_numa_node(nodes[1])
local cpus = available_cpus(nodes[1])
assert(#cpus > 0, 'Not available CPUs')
numa.bind_to_cpu(cpus, 'skip-perf-checks')
print(("Bound main process to NUMA node: %s (CPU %s)"):format(nodes[1], cpus[1]))
else
print("CPUs available from multiple NUMA nodes: "..table.concat(nodes, ","))
print("Not binding to any NUMA node.")
end
end
function CPUSet:add_from_string(cpus)
for cpu,_ in pairs(numa.parse_cpuset(cpus)) do
self:add(cpu)
end
end
function CPUSet:add(cpu)
local node = numa.cpu_get_numa_node(cpu)
assert(node ~= nil, 'Failed to get NUMA node for CPU: '..cpu)
if self.by_node[node] == nil then self.by_node[node] = {} end
assert(self.by_node[cpu] == nil, 'CPU already in set: '..cpu)
self.by_node[node][cpu] = true
end
function CPUSet:acquire_for_pci_addresses(addrs)
return self:acquire(numa.choose_numa_node_for_pci_addresses(addrs))
end
function CPUSet:acquire(on_node)
for node, cpus in pairs(self.by_node) do
if on_node == nil or on_node == node then
for cpu, avail in pairs(cpus) do
if avail then
cpus[cpu] = false
return cpu
end
end
end
end
if on_node ~= nil then
for node, cpus in pairs(self.by_node) do
for cpu, avail in pairs(cpus) do
if avail then
print("Warning: No CPU available on local NUMA node "..on_node)
print("Warning: Assigning CPU "..cpu.." from remote node "..node)
cpus[cpu] = false
return cpu
end
end
end
end
for node, cpus in pairs(self.by_node) do
print(("Warning: All assignable CPUs in use; "..
"leaving data-plane PID %d without assigned CPU."):format(S.getpid()))
return
end
print(("Warning: No assignable CPUs declared; "..
"leaving data-plane PID %d without assigned CPU."):format(S.getpid()))
end
function CPUSet:release(cpu)
local node = numa.cpu_get_numa_node(cpu)
assert(node ~= nil, 'Failed to get NUMA node for CPU: '..cpu)
for x, avail in pairs(self.by_node[node]) do
if x == cpu then
assert(self.by_node[node][cpu] == false)
self.by_node[node][cpu] = true
return
end
end
error('CPU not found on NUMA node: '..cpu..', '..node)
end
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(...,package.seeall)
local numa = require('lib.numa')
local S = require('syscall')
local CPUSet = {}
function new()
return setmetatable({by_node={}}, {__index=CPUSet})
end
do
local cpuset = false
function global_cpuset()
if not cpuset then cpuset = new() end
return cpuset
end
end
local function available_cpus (node)
local function subtract (s, t)
local ret = {}
for k,_ in pairs(s) do
if not t[k] then table.insert(ret, k) end
end
table.sort(ret)
return ret
end
-- XXX: Add sched_getaffinity cpus.
return subtract(numa.node_cpus(node), numa.isolated_cpus())
end
function CPUSet:bind_to_numa_node()
local nodes = {}
for node, _ in pairs(self.by_node) do table.insert(nodes, node) end
if #nodes == 0 then
print("No CPUs available; not binding to any NUMA node.")
elseif #nodes == 1 then
numa.bind_to_numa_node(nodes[1])
local cpus = available_cpus(nodes[1])
assert(#cpus > 0, 'Not available CPUs')
numa.bind_to_cpu(cpus, 'skip-perf-checks')
print(("Bound main process to NUMA node: %s (CPU %s)"):format(nodes[1], cpus[1]))
else
print("CPUs available from multiple NUMA nodes: "..table.concat(nodes, ","))
print("Not binding to any NUMA node.")
end
end
function CPUSet:add_from_string(cpus)
for cpu,_ in pairs(numa.parse_cpuset(cpus)) do
self:add(cpu)
end
end
function CPUSet:add(cpu)
local node = numa.cpu_get_numa_node(cpu)
assert(node ~= nil, 'Failed to get NUMA node for CPU: '..cpu)
if self.by_node[node] == nil then self.by_node[node] = {} end
assert(self.by_node[node][cpu] == nil, 'CPU already in set: '..cpu)
self.by_node[node][cpu] = true
end
function CPUSet:contains(cpu)
local node = numa.cpu_get_numa_node(cpu)
assert(node ~= nil, 'Failed to get NUMA node for CPU: '..cpu)
return self.by_node[node] and (self.by_node[node][cpu] ~= nil)
end
function CPUSet:remove (cpu)
assert(self:contains(cpu), 'CPU not in set: '..cpu)
local node = numa.cpu_get_numa_node(cpu)
if self.by_node[node][cpu] == false then
print("Warning: removing bound CPU from set: "..cpu)
end
self.by_node[node][cpu] = nil
end
function CPUSet:list ()
local list = {}
for node, cpus in pairs(self.by_node) do
for cpu in pairs(cpus) do
table.insert(list, cpu)
end
end
return list
end
function CPUSet:acquire_for_pci_addresses(addrs)
return self:acquire(numa.choose_numa_node_for_pci_addresses(addrs))
end
function CPUSet:acquire(on_node)
for node, cpus in pairs(self.by_node) do
if on_node == nil or on_node == node then
for cpu, avail in pairs(cpus) do
if avail then
cpus[cpu] = false
return cpu
end
end
end
end
if on_node ~= nil then
for node, cpus in pairs(self.by_node) do
for cpu, avail in pairs(cpus) do
if avail then
print("Warning: No CPU available on local NUMA node "..on_node)
print("Warning: Assigning CPU "..cpu.." from remote node "..node)
cpus[cpu] = false
return cpu
end
end
end
end
for node, cpus in pairs(self.by_node) do
print(("Warning: All assignable CPUs in use; "..
"leaving data-plane PID %d without assigned CPU."):format(S.getpid()))
return
end
print(("Warning: No assignable CPUs declared; "..
"leaving data-plane PID %d without assigned CPU."):format(S.getpid()))
end
function CPUSet:release(cpu)
local node = numa.cpu_get_numa_node(cpu)
assert(node ~= nil, 'Failed to get NUMA node for CPU: '..cpu)
for x, avail in pairs(self.by_node[node]) do
if x == cpu then
assert(self.by_node[node][cpu] == false)
self.by_node[node][cpu] = true
return
end
end
error('CPU not found on NUMA node: '..cpu..', '..node)
end
|
lib.cpuset: fix assertion in add, add contains/remove/list methods
|
lib.cpuset: fix assertion in add, add contains/remove/list methods
|
Lua
|
apache-2.0
|
snabbco/snabb,snabbco/snabb,snabbco/snabb,eugeneia/snabb,eugeneia/snabb,snabbco/snabb,eugeneia/snabb,snabbco/snabb,eugeneia/snabb,eugeneia/snabb,snabbco/snabb,eugeneia/snabb,eugeneia/snabb,snabbco/snabb,eugeneia/snabb,snabbco/snabb
|
46b127a9ccee3a01f95bee47e81305238ab17f3a
|
src/lua-factory/sources/grl-video-title-parsing.lua
|
src/lua-factory/sources/grl-video-title-parsing.lua
|
--[[
* Copyright (C) 2014 Grilo Project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
--]]
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-video-title-parsing",
name = "video-title-parsing",
description = "Video title parsing",
supported_keys = { "episode-title", 'show', 'publication-date', 'season', 'episode', 'title' },
supported_media = 'video',
resolve_keys = {
["type"] = "video",
required = { "title" },
},
}
blacklisted_words = {
"720p", "1080p", "x264",
"ws", "proper",
"real.repack", "repack",
"hdtv", "pdtv", "notv",
"dsr", "DVDRip", "divx", "xvid",
}
-- https://en.wikipedia.org/wiki/Video_file_format
video_suffixes = {
"webm", "mkv", "flv", "ogv", "ogg", "avi", "mov",
"wmv", "mp4", "m4v", "mpeg", "mpg"
}
parsers = {
tvshow = {
"(.-)[sS](%d+)[%s.]*[eE][pP]?(%d+)(.+)",
"(.-)(%d+)[xX.](%d+)(.+)",
},
movies = {
"(.-)(19%d%d)",
"(.-)(20%d%d)",
}
}
-- in case suffix is recognized, remove it and return true
-- or return the title and false if it fails
function remove_suffix(title)
local s = title:gsub(".*%.(.-)$", "%1")
if s then
for _, suffix in ipairs(video_suffixes) do
if s:find(suffix) then
local t = title:gsub("(.*)%..-$", "%1")
return t, true
end
end
end
return title, false
end
function clean_title(title)
return title:gsub("^[%s%W]*(.-)[%s%W]*$", "%1"):gsub("%.", " ")
end
function clean_title_from_blacklist(title)
local s = title:lower()
local last_index
local suffix_removed
-- remove movie suffix
s, suffix_removed = remove_suffix(s)
if suffix_removed == false then
grl.debug ("Suffix not find in " .. title)
end
-- ignore everything after the first blacklisted word
last_index = #s
for i, word in ipairs (blacklisted_words) do
local index = s:find(word:lower())
if index and index < last_index then
last_index = index - 1
end
end
return title:sub(1, last_index)
end
function parse_as_movie(media)
local title, date
local str = clean_title_from_blacklist (media.title)
for i, parser in ipairs(parsers.movies) do
title, date = str:match(parser)
if title and date then
media.title = clean_title(title)
media.publication_date = date
return true
end
end
return false
end
function parse_as_episode(media)
local show, season, episode, title
for i, parser in ipairs(parsers.tvshow) do
show, season, episode, title = media.title:match(parser)
if show and season and episode and tonumber(season) < 50 then
media.show = clean_title(show)
media.season = season
media.episode = episode
media.episode_title = clean_title(clean_title_from_blacklist(title))
return true
end
end
return false
end
function grl_source_resolve()
local req
local media = {}
req = grl.get_media_keys()
if not req or not req.title then
grl.callback()
return
end
media.title = req.title
-- It is easier to identify a tv show due information
-- related to episode and season number
if parse_as_episode(media) then
grl.debug(req.title .. " is an EPISODE")
grl.callback(media, 0)
return
end
if parse_as_movie(media) then
grl.debug(req.title .. " is a MOVIE")
grl.callback(media, 0)
return
end
local suffix_removed
media.title, suffix_removed = remove_suffix(media.title)
if media.title and suffix_removed then
grl.debug(req.title .. " is a MOVIE (without suffix)")
grl.callback(media, 0)
return
end
grl.debug("Fail to identify video: " .. req.title)
grl.callback()
end
|
--[[
* Copyright (C) 2014 Grilo Project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
--]]
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-video-title-parsing",
name = "video-title-parsing",
description = "Video title parsing",
supported_keys = { "episode-title", 'show', 'publication-date', 'season', 'episode', 'title' },
supported_media = 'video',
resolve_keys = {
["type"] = "video",
required = { "title" },
},
}
blacklisted_words = {
"720p", "1080p", "x264",
"ws", "proper",
"real.repack", "repack",
"hdtv", "pdtv", "notv",
"dsr", "DVDRip", "divx", "xvid",
}
-- https://en.wikipedia.org/wiki/Video_file_format
video_suffixes = {
"webm", "mkv", "flv", "ogv", "ogg", "avi", "mov",
"wmv", "mp4", "m4v", "mpeg", "mpg"
}
parsers = {
tvshow = {
"(.-)[sS](%d+)[%s.]*[eE][pP]?(%d+)(.+)",
"(.-)(%d+)[xX.](%d+)(.+)",
},
movies = {
"(.-)(19%d%d)",
"(.-)(20%d%d)",
}
}
-- in case suffix is recognized, remove it and return true
-- or return the title and false if it fails
function remove_suffix(title)
local s = title:gsub(".*%.(.-)$", "%1")
if s then
for _, suffix in ipairs(video_suffixes) do
if s:find(suffix) then
local t = title:gsub("(.*)%..-$", "%1")
return t, true
end
end
end
return title, false
end
function clean_title(title)
return title:gsub("^[%s%W]*(.-)[%s%W]*$", "%1"):gsub("%.", " ")
end
function clean_title_from_blacklist(title)
local s = title:lower()
local last_index
local suffix_removed
-- remove movie suffix
s, suffix_removed = remove_suffix(s)
if suffix_removed == false then
grl.debug ("Suffix not find in " .. title)
end
-- ignore everything after the first blacklisted word
last_index = #s
for i, word in ipairs (blacklisted_words) do
local index = s:find(word:lower())
if index and index < last_index then
last_index = index - 1
end
end
return title:sub(1, last_index)
end
function parse_as_movie(media)
local title, date
local str = clean_title_from_blacklist (media.title)
for i, parser in ipairs(parsers.movies) do
title, date = str:match(parser)
if title and date then
media.title = clean_title(title)
media.publication_date = date
return true
end
end
return false
end
function parse_as_episode(media)
local show, season, episode, title
for i, parser in ipairs(parsers.tvshow) do
show, season, episode, title = media.title:match(parser)
if show and season and episode and tonumber(season) < 50 then
media.show = clean_title(show)
media.season = season
media.episode = episode
media.episode_title = clean_title(clean_title_from_blacklist(title))
return true
end
end
return false
end
function grl_source_resolve(media, options, callback)
if not media or not media.title then
callback()
return
end
-- It is easier to identify a tv show due information
-- related to episode and season number
if parse_as_episode(media) then
grl.debug(media.title .. " is an EPISODE")
callback(media, 0)
return
end
if parse_as_movie(media) then
grl.debug(media.title .. " is a MOVIE")
callback(media, 0)
return
end
local suffix_removed
media.title, suffix_removed = remove_suffix(media.title)
if media.title and suffix_removed then
grl.debug(media.title .. " is a MOVIE (without suffix)")
callback(media, 0)
return
end
grl.debug("Fail to identify video: " .. media.title)
callback()
end
|
lua-factory: port grl-video-title-parsing.lua to the new lua system
|
lua-factory: port grl-video-title-parsing.lua to the new lua system
https://bugzilla.gnome.org/show_bug.cgi?id=753141
Acked-by: Victor Toso <[email protected]>
|
Lua
|
lgpl-2.1
|
jasuarez/grilo-plugins,MikePetullo/grilo-plugins,MikePetullo/grilo-plugins,jasuarez/grilo-plugins,GNOME/grilo-plugins,grilofw/grilo-plugins,grilofw/grilo-plugins,GNOME/grilo-plugins,MikePetullo/grilo-plugins
|
566c7b3e548011950503b3bfa7139fac3cc02fa0
|
test_scripts/Polices/build_options/ATF_transfer_SystemRequest_from_app_to_HMI.lua
|
test_scripts/Polices/build_options/ATF_transfer_SystemRequest_from_app_to_HMI.lua
|
---------------------------------------------------------------------------------------------
-- Requirement summary:
-- [PTU-Proprietary] Transfer SystemRequest from mobile app to HMI
--
-- Description:
-- 1. Used preconditions: SDL is built with "DEXTENDED_POLICY: ON" flag. Trigger for PTU occurs
-- 2. Performed steps:
-- MOB->SDL: SystemRequest(PROPRIETARY, filename)
-- SDL->HMI: BasicCommunication.SystemRequest (PROPRIETARY, filename, appID)
--
-- Expected result:
-- SDL must send BasicCommunication.SystemRequest (<path to UpdatedPT>, PROPRIETARY, params) to HMI
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
local commonSteps = require('user_modules/shared_testcases/commonSteps')
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFileAndPolicyTable()
--[[ Local Variables ]]
local BasicCommunicationSystemRequestData
local testData = {
fileName = "PTUpdate",
requestType = "PROPRIETARY",
ivsuPath = "/tmp/fs/mp/images/ivsu_cache/"
}
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('user_modules/AppTypes')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:Precondition_Activate_App_And_Consent_Device_To_Start_PTU()
local request_id = self.hmiConnection:SendRequest("SDL.ActivateApp", {appID = self.applications["Test Application"]})
EXPECT_HMIRESPONSE(request_id, { result = {isSDLAllowed = false}, method = "SDL.ActivateApp"})
:Do(function(_,_)
local RequestIdGetUserFriendlyMessage = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}})
EXPECT_HMIRESPONSE(RequestIdGetUserFriendlyMessage,{result = {code = 0, method = "SDL.GetUserFriendlyMessage"}})
:Do(function(_,_)
self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", {allowed = true, source = "GUI", device = {id = config.deviceMAC, name = "127.0.0.1"}})
EXPECT_HMICALL("BasicCommunication.ActivateApp")
:Do(function(_,data)
self.hmiConnection:SendResponse(data.id,"BasicCommunication.ActivateApp", "SUCCESS", {})
EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"})
end)
EXPECT_NOTIFICATION("OnPermissionsChange", {})
end)
end)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_Update_Policy()
local RequestIdGetURLS = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 })
EXPECT_HMIRESPONSE(RequestIdGetURLS,{result = {code = 0, method = "SDL.GetURLS", urls = {{url = "http://policies.telematics.ford.com/api/policies"}}}})
:Do(function()
self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", {requestType = "PROPRIETARY", fileName = testData.fileName})
EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY" })
:Do(function()
self.mobileSession:SendRPC("SystemRequest",
{
fileName = testData.fileName,
requestType = "PROPRIETARY"
}, "files/ptu.json")
EXPECT_HMICALL("BasicCommunication.SystemRequest")
:Do(function(_,data)
BasicCommunicationSystemRequestData = data
end)
end)
end)
end
function Test:TestStep_Check_BC_SystemRequest()
local filePath = testData.ivsuPath .. testData.fileName
if BasicCommunicationSystemRequestData.params.fileName ~= filePath or
BasicCommunicationSystemRequestData.params.requestType ~= testData.requestType then
self.FailTestCase("Data of BC.SystemRequest is incorrect")
end
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_ForceStopSDL()
StopSDL()
end
return Test
|
---------------------------------------------------------------------------------------------
-- Requirement summary:
-- [PTU-Proprietary] Transfer SystemRequest from mobile app to HMI
--
-- Description:
-- 1. Used preconditions: SDL is built with "DEXTENDED_POLICY: ON" flag. Trigger for PTU occurs
-- 2. Performed steps:
-- MOB->SDL: SystemRequest(PROPRIETARY, filename)
-- SDL->HMI: BasicCommunication.SystemRequest (PROPRIETARY, filename, appID)
--
-- Expected result:
-- SDL must send BasicCommunication.SystemRequest (<path to UpdatedPT>, PROPRIETARY, params) to HMI
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
local commonSteps = require('user_modules/shared_testcases/commonSteps')
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFileAndPolicyTable()
--[[ Local Variables ]]
local BasicCommunicationSystemRequestData
local testData = {
fileName = "PTUpdate",
requestType = "PROPRIETARY",
ivsuPath = "/tmp/fs/mp/images/ivsu_cache/"
}
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('user_modules/AppTypes')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_Update_Policy()
local RequestIdGetURLS = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 })
EXPECT_HMIRESPONSE(RequestIdGetURLS,{result = {code = 0, method = "SDL.GetURLS", urls = {{url = "http://policies.telematics.ford.com/api/policies"}}}})
:Do(function()
self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", {requestType = "PROPRIETARY", fileName = testData.fileName})
EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY" })
:Do(function()
self.mobileSession:SendRPC("SystemRequest",
{
fileName = testData.fileName,
requestType = "PROPRIETARY"
}, "files/ptu.json")
EXPECT_HMICALL("BasicCommunication.SystemRequest")
:Do(function(_,data)
BasicCommunicationSystemRequestData = data
end)
end)
end)
end
function Test:TestStep_Check_BC_SystemRequest()
local filePath = testData.ivsuPath .. testData.fileName
if BasicCommunicationSystemRequestData.params.fileName ~= filePath or
BasicCommunicationSystemRequestData.params.requestType ~= testData.requestType then
self.FailTestCase("Data of BC.SystemRequest is incorrect")
end
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_ForceStopSDL()
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
|
64949444f65385455bd4bbdc1af6a14040eecfd7
|
frontend/ui/reader/readerzooming.lua
|
frontend/ui/reader/readerzooming.lua
|
ReaderZooming = InputContainer:new{
zoom = 1.0,
-- default to nil so we can trigger ZoomModeUpdate events on start up
zoom_mode = nil,
DEFAULT_ZOOM_MODE = "page",
current_page = 1,
rotation = 0
}
function ReaderZooming:init()
if Device:hasKeyboard() then
self.key_events = {
ZoomIn = {
{ "Shift", Input.group.PgFwd },
doc = "zoom in",
event = "Zoom", args = "in"
},
ZoomOut = {
{ "Shift", Input.group.PgBack },
doc = "zoom out",
event = "Zoom", args = "out"
},
ZoomToFitPage = {
{ "A" },
doc = "zoom to fit page",
event = "SetZoomMode", args = "page"
},
ZoomToFitContent = {
{ "Shift", "A" },
doc = "zoom to fit content",
event = "SetZoomMode", args = "content"
},
ZoomToFitPageWidth = {
{ "S" },
doc = "zoom to fit page width",
event = "SetZoomMode", args = "pagewidth"
},
ZoomToFitContentWidth = {
{ "Shift", "S" },
doc = "zoom to fit content width",
event = "SetZoomMode", args = "contentwidth"
},
ZoomToFitPageHeight = {
{ "D" },
doc = "zoom to fit page height",
event = "SetZoomMode", args = "pageheight"
},
ZoomToFitContentHeight = {
{ "Shift", "D" },
doc = "zoom to fit content height",
event = "SetZoomMode", args = "contentheight"
},
}
end
self.ui.menu:registerToMainMenu(self)
end
function ReaderZooming:onReadSettings(config)
-- @TODO config file from old code base uses globalzoom_mode
-- instead of zoom_mode, we need to handle this imcompatibility
-- 04.12 2012 (houqp)
local zoom_mode = config:readSetting("zoom_mode")
if not zoom_mode then
zoom_mode = self.DEFAULT_ZOOM_MODE
end
self.ui:handleEvent(Event:new("SetZoomMode", zoom_mode))
end
function ReaderZooming:onCloseDocument()
self.ui.doc_settings:saveSetting("zoom_mode", self.zoom_mode)
end
function ReaderZooming:onSetDimensions(dimensions)
-- we were resized
self.dimen = dimensions
self:setZoom()
end
function ReaderZooming:onRotationUpdate(rotation)
self.rotation = rotation
self:setZoom()
end
function ReaderZooming:onZoom(direction)
DEBUG("zoom", direction)
if direction == "in" then
self.zoom = self.zoom * 1.333333
elseif direction == "out" then
self.zoom = self.zoom * 0.75
end
DEBUG("zoom is now at", self.zoom)
self:onSetZoomMode("free")
self.view:onZoomUpdate(self.zoom)
return true
end
function ReaderZooming:onSetZoomMode(new_mode)
self.view.zoom_mode = new_mode
if self.zoom_mode ~= new_mode then
DEBUG("setting zoom mode to", new_mode)
self.zoom_mode = new_mode
self:setZoom()
self.ui:handleEvent(Event:new("ZoomModeUpdate", new_mode))
end
end
function ReaderZooming:onPageUpdate(new_page_no)
self.current_page = new_page_no
self:setZoom()
end
function ReaderZooming:setZoom()
-- nothing to do in free zoom mode
if self.zoom_mode == "free" then
return
end
if not self.dimen then
self.dimen = self.ui.dimen
end
-- check if we're in bbox mode and work on bbox if that's the case
local page_size = {}
if self.zoom_mode == "content"
or self.zoom_mode == "contentwidth"
or self.zoom_mode == "contentheight" then
ubbox_dimen = self.ui.document:getUsedBBoxDimensions(self.current_page, 1)
--self.view:handleEvent(Event:new("BBoxUpdate", page_size))
self.view:onBBoxUpdate(ubbox_dimen)
page_size = ubbox_dimen
else
-- otherwise, operate on full page
self.view:onBBoxUpdate(nil)
page_size = self.ui.document:getNativePageDimensions(self.current_page)
end
-- calculate zoom value:
local zoom_w = self.dimen.w / page_size.w
local zoom_h = self.dimen.h / page_size.h
if self.rotation % 180 ~= 0 then
-- rotated by 90 or 270 degrees
zoom_w = self.dimen.w / page_size.h
zoom_h = self.dimen.h / page_size.w
end
if self.zoom_mode == "content" or self.zoom_mode == "page" then
if zoom_w < zoom_h then
self.zoom = zoom_w
else
self.zoom = zoom_h
end
elseif self.zoom_mode == "contentwidth" or self.zoom_mode == "pagewidth" then
self.zoom = zoom_w
elseif self.zoom_mode == "contentheight" or self.zoom_mode == "pageheight" then
self.zoom = zoom_h
end
self.ui:handleEvent(Event:new("ZoomUpdate", self.zoom))
end
function ReaderZooming:genSetZoomModeCallBack(mode)
return function()
self.ui:handleEvent(Event:new("SetZoomMode", mode))
end
end
function ReaderZooming:addToMainMenu(item_table)
if self.ui.document.info.has_pages then
table.insert(item_table, {
text = "Switch zoom mode",
sub_item_table = {
{
text = "Zoom to fit content width",
callback = self:genSetZoomModeCallBack("contentwidth")
},
{
text = "Zoom to fit content height",
callback = self:genSetZoomModeCallBack("contentheight")
},
{
text = "Zoom to fit page width",
callback = self:genSetZoomModeCallBack("pagewidth")
},
{
text = "Zoom to fit page height",
callback = self:genSetZoomModeCallBack("pageheight")
},
{
text = "Zoom to fit content",
callback = self:genSetZoomModeCallBack("content")
},
{
text = "Zoom to fit page",
callback = self:genSetZoomModeCallBack("page")
},
}
})
end
end
|
ReaderZooming = InputContainer:new{
zoom = 1.0,
-- default to nil so we can trigger ZoomModeUpdate events on start up
zoom_mode = nil,
DEFAULT_ZOOM_MODE = "page",
current_page = 1,
rotation = 0
}
function ReaderZooming:init()
if Device:hasKeyboard() then
self.key_events = {
ZoomIn = {
{ "Shift", Input.group.PgFwd },
doc = "zoom in",
event = "Zoom", args = "in"
},
ZoomOut = {
{ "Shift", Input.group.PgBack },
doc = "zoom out",
event = "Zoom", args = "out"
},
ZoomToFitPage = {
{ "A" },
doc = "zoom to fit page",
event = "SetZoomMode", args = "page"
},
ZoomToFitContent = {
{ "Shift", "A" },
doc = "zoom to fit content",
event = "SetZoomMode", args = "content"
},
ZoomToFitPageWidth = {
{ "S" },
doc = "zoom to fit page width",
event = "SetZoomMode", args = "pagewidth"
},
ZoomToFitContentWidth = {
{ "Shift", "S" },
doc = "zoom to fit content width",
event = "SetZoomMode", args = "contentwidth"
},
ZoomToFitPageHeight = {
{ "D" },
doc = "zoom to fit page height",
event = "SetZoomMode", args = "pageheight"
},
ZoomToFitContentHeight = {
{ "Shift", "D" },
doc = "zoom to fit content height",
event = "SetZoomMode", args = "contentheight"
},
}
end
self.ui.menu:registerToMainMenu(self)
end
function ReaderZooming:onReadSettings(config)
-- @TODO config file from old code base uses globalzoom_mode
-- instead of zoom_mode, we need to handle this imcompatibility
-- 04.12 2012 (houqp)
local zoom_mode = config:readSetting("zoom_mode")
if not zoom_mode then
zoom_mode = self.DEFAULT_ZOOM_MODE
end
self.ui:handleEvent(Event:new("SetZoomMode", zoom_mode))
end
function ReaderZooming:onCloseDocument()
self.ui.doc_settings:saveSetting("zoom_mode", self.zoom_mode)
end
function ReaderZooming:onSetDimensions(dimensions)
-- we were resized
self.dimen = dimensions
self:setZoom()
end
function ReaderZooming:onRotationUpdate(rotation)
self.rotation = rotation
self:setZoom()
end
function ReaderZooming:onZoom(direction)
DEBUG("zoom", direction)
if direction == "in" then
self.zoom = self.zoom * 1.333333
elseif direction == "out" then
self.zoom = self.zoom * 0.75
end
DEBUG("zoom is now at", self.zoom)
self:onSetZoomMode("free")
self.view:onZoomUpdate(self.zoom)
return true
end
function ReaderZooming:onSetZoomMode(new_mode)
self.view.zoom_mode = new_mode
if self.zoom_mode ~= new_mode then
DEBUG("setting zoom mode to", new_mode)
self.zoom_mode = new_mode
self:setZoom()
self.ui:handleEvent(Event:new("ZoomModeUpdate", new_mode))
end
end
function ReaderZooming:onPageUpdate(new_page_no)
self.current_page = new_page_no
self:setZoom()
end
function ReaderZooming:onHintPage()
if self.current_page < self.ui.document.info.number_of_pages then
self.ui.document:hintPage(
self.view.state.page + 1,
self:getZoom(self.view.state.page + 1),
self.view.state.rotation,
self.view.state.gamma,
self.view.render_mode)
end
return true
end
function ReaderZooming:getZoom(pageno)
-- check if we're in bbox mode and work on bbox if that's the case
local zoom = nil
local page_size = {}
if self.zoom_mode == "content"
or self.zoom_mode == "contentwidth"
or self.zoom_mode == "contentheight" then
local ubbox_dimen = self.ui.document:getUsedBBoxDimensions(pageno, 1)
--self.view:handleEvent(Event:new("BBoxUpdate", page_size))
self.view:onBBoxUpdate(ubbox_dimen)
page_size = ubbox_dimen
else
-- otherwise, operate on full page
self.view:onBBoxUpdate(nil)
page_size = self.ui.document:getNativePageDimensions(pageno)
end
-- calculate zoom value:
local zoom_w = self.dimen.w / page_size.w
local zoom_h = self.dimen.h / page_size.h
if self.rotation % 180 ~= 0 then
-- rotated by 90 or 270 degrees
zoom_w = self.dimen.w / page_size.h
zoom_h = self.dimen.h / page_size.w
end
if self.zoom_mode == "content" or self.zoom_mode == "page" then
if zoom_w < zoom_h then
zoom = zoom_w
else
zoom = zoom_h
end
elseif self.zoom_mode == "contentwidth" or self.zoom_mode == "pagewidth" then
zoom = zoom_w
elseif self.zoom_mode == "contentheight" or self.zoom_mode == "pageheight" then
zoom = zoom_h
end
return zoom
end
function ReaderZooming:setZoom()
-- nothing to do in free zoom mode
if self.zoom_mode == "free" then
return
end
if not self.dimen then
self.dimen = self.ui.dimen
end
self.zoom = self:getZoom(self.current_page)
self.ui:handleEvent(Event:new("ZoomUpdate", self.zoom))
end
function ReaderZooming:genSetZoomModeCallBack(mode)
return function()
self.ui:handleEvent(Event:new("SetZoomMode", mode))
end
end
function ReaderZooming:addToMainMenu(item_table)
if self.ui.document.info.has_pages then
table.insert(item_table, {
text = "Switch zoom mode",
sub_item_table = {
{
text = "Zoom to fit content width",
callback = self:genSetZoomModeCallBack("contentwidth")
},
{
text = "Zoom to fit content height",
callback = self:genSetZoomModeCallBack("contentheight")
},
{
text = "Zoom to fit page width",
callback = self:genSetZoomModeCallBack("pagewidth")
},
{
text = "Zoom to fit page height",
callback = self:genSetZoomModeCallBack("pageheight")
},
{
text = "Zoom to fit content",
callback = self:genSetZoomModeCallBack("content")
},
{
text = "Zoom to fit page",
callback = self:genSetZoomModeCallBack("page")
},
}
})
end
end
|
bugfix: calculate page zoom before hinting
|
bugfix: calculate page zoom before hinting
|
Lua
|
agpl-3.0
|
frankyifei/koreader-base,pazos/koreader,mwoz123/koreader,chihyang/koreader,mihailim/koreader,koreader/koreader,NiLuJe/koreader-base,apletnev/koreader-base,frankyifei/koreader-base,NiLuJe/koreader-base,Hzj-jie/koreader-base,noname007/koreader,houqp/koreader-base,NickSavage/koreader,Hzj-jie/koreader,chrox/koreader,Frenzie/koreader-base,NiLuJe/koreader,apletnev/koreader-base,koreader/koreader-base,frankyifei/koreader-base,koreader/koreader,poire-z/koreader,koreader/koreader-base,frankyifei/koreader,apletnev/koreader-base,Frenzie/koreader-base,poire-z/koreader,apletnev/koreader-base,Frenzie/koreader-base,houqp/koreader-base,koreader/koreader-base,Hzj-jie/koreader-base,NiLuJe/koreader,Frenzie/koreader,NiLuJe/koreader-base,NiLuJe/koreader-base,apletnev/koreader,Hzj-jie/koreader-base,ashang/koreader,Hzj-jie/koreader-base,houqp/koreader-base,lgeek/koreader,koreader/koreader-base,houqp/koreader,Frenzie/koreader-base,Frenzie/koreader,robert00s/koreader,houqp/koreader-base,Markismus/koreader,frankyifei/koreader-base,ashhher3/koreader
|
9dbec408c321b4f1f58cecf208913d3e7ac81982
|
fusion/stdlib/functional.lua
|
fusion/stdlib/functional.lua
|
--- Module for "functional" iterators and functions.
-- @module fusion.stdlib.functional
local unpack = unpack or table.unpack -- luacheck: ignore 113
--- Return an iterator over a value if possible or the value passed.
-- Possible value types can be strings and any object with __pairs or __ipairs
-- metadata.
-- @tparam table input Table to iterate over (can also be iterator function)
-- @tparam function iterator Table iterator to use (`pairs()` by default)
-- @treturn function
local function iter(input, iterator)
if type(input) == "function" then
return input
elseif type(input) == "string" then
return input:gmatch(".")
else
if not iterator then
return iter(input, pairs)
end
return iterator(input)
end
end
--- Make an iterator (or 'generator') from a function.
-- @tparam function fn
-- @treturn function Wrapped coroutine
local function mk_gen(fn)
return function(...)
local a = {...}
return coroutine.wrap(function()
return fn(unpack(a))
end)
end
end
--- Apply a function to one or more input streams, and return the values.
-- @function map
-- @tparam function fn
-- @tparam iter input
-- @treturn iter Initialized iterator
-- @usage print(x in map(((v)-> v ^ 2), 1::10)); -- squares
local function map(fn, input, ...)
local _args = {...}
for i, v in ipairs(_args) do
_args[i] = iter(v)
end
for k, v in iter(input) do
local t0 = {}
for i, _v in ipairs(_args) do -- luacheck: ignore 213
table.insert(t0, _v())
end
input[k] = fn(v, unpack(t0))
coroutine.yield(k, fn(v, unpack(t0)))
end
end
--- Return values in an input stream if an applied function returns true.
-- @function filter
-- @tparam function fn
-- @tparam iter input Iterable object
-- @treturn iter Initialized iterator
-- @usage print(x in filter(((v)-> v % 2 == 0), 1::10)); -- odds
local function filter(fn, input)
for k, v in iter(input) do -- luacheck: ignore 213
if fn(k, v) then
coroutine.yield(k, v)
end
end
end
--- Return a value from a function applied to all values of an input stream.
-- @function reduce
-- @tparam function fn
-- @tparam iter input Iterable object
-- @param init Initial value (will use first value of stream if not supplied)
-- @usage print(reduce(((x, y)-> x > y), {5, 2, 7, 9, 1})); -- math.max()
local function reduce(fn, input, init)
for k, v in iter(input) do -- luacheck: ignore 213
if init == nil then
init = v
else
init = assert(fn(init, v))
end
end
return init
end
--- Does the same thing as `reduce`, but operates on ordered sequences.
-- This function should only be used on numeric tables or indexable streams.
-- Use `foldl()` or `foldr()` for convenience instead of this function unless
-- you need control over the exact sequence.
-- @function fold
-- @tparam number start
-- @tparam number stop
-- @tparam number step
-- @tparam function fn
-- @param input Numerically indexable object
-- @param init Initial value (will use first value in input if not supplied)
-- @see reduce
local function fold(start, stop, step, fn, input, init)
for i=start, stop, step do
if not init then
init = input[i]
else
init = assert(fn(init, input[i]))
end
end
return init
end
--- Fold starting from the first value of input to the last value of input.
-- @function foldl
-- @tparam function fn
-- @param input Numerically indexable object
-- @param init Initial value (will use first value in input if not supplied)
-- @see fold, foldr, reduce
local function foldl(fn, input, init)
return fold(1, #input, 1, fn, input, init)
end
--- Fold starting from the last value of input to the first value of input.
-- @function foldr
-- @tparam function fn
-- @param input Numerically indexable object
-- @param init Initial value (will use last value in input if not supplied)
-- @see fold, foldl, reduce
local function foldr(fn, input, init)
return fold(#input, 1, -1, fn, input, init)
end
--- Return the boolean form of a value. False and nil return false, otherwise
-- true is returned.
-- @param val Value to convert to boolean value (optionally nil)
-- @treturn boolean
local function truthy(val)
return not not val
end
--- Return true if any returned value from an input stream are truthy,
-- otherwise false.
-- @function any
-- @tparam function fn
-- @tparam iter input
-- @treturn boolean
-- @usage print(any({nil, true, false})); -- true
local function any(fn, input)
if not fn or not input then
return any(truthy, fn or input)
end
for k, v in iter(input) do -- luacheck: ignore 213
if v ~= nil and fn(v) then
return true
elseif v == nil and fn(k) then
return true
end
end
return false
end
--- Return true if all returned values from an input stream are truthy.
-- @function all
-- @tparam function fn
-- @tparam iter input
-- @treturn boolean
-- @usage print(all(chain(1::50, {false}))); -- false
local function all(fn, input)
if not fn or not input then
return all(truthy, fn or input)
end
for k, v in iter(input) do -- luacheck: ignore 213
if v ~= nil and not fn(v) then
return false
elseif v == nil and not fn(k) then
return false
end
end
return true
end
--- Return a sum of all values in a stream.
-- @function sum
-- @tparam iter input
-- @tparam boolean negative optional; returns a difference instead if true
-- @treturn number
-- @usage print(sum(1::50));
local function sum(input, negative)
if negative then
return reduce(function(a, b) return a - b end, input)
else
return reduce(function(a, b) return a + b end, input)
end
end
return {
_iter = iter;
_mk_gen = mk_gen;
all = all;
any = any;
filter = mk_gen(filter);
foldl = foldl;
foldr = foldr;
map = mk_gen(map);
reduce = reduce;
sum = sum;
}
|
--- Module for "functional" iterators and functions.
-- @module fusion.stdlib.functional
local unpack = unpack or table.unpack -- luacheck: ignore 113
--- Return an iterator over a value if possible or the value passed.
-- Possible value types can be strings and any object with __pairs or __ipairs
-- metadata.
-- @tparam table input Table to iterate over (can also be iterator function)
-- @tparam function iterator Table iterator to use (`pairs()` by default)
-- @treturn function
local function iter(input, ...)
local iterator = ...
if type(input) == "function" then
return input, ...
elseif type(input) == "string" then
return input:gmatch(".")
else
if not iterator then
return iter(input, pairs)
end
return iterator(input)
end
end
--- Make an iterator (or 'generator') from a function.
-- @tparam function fn
-- @treturn function Wrapped coroutine
local function mk_gen(fn)
return function(...)
local a = {...}
return coroutine.wrap(function()
return fn(unpack(a))
end)
end
end
--- Apply a function to one or more input streams, and return the values.
-- @function map
-- @tparam function fn
-- @tparam iter input
-- @treturn iter Initialized iterator
-- @usage print(x in map(((v)-> v ^ 2), 1::10)); -- squares
local function map(fn, input)
for k, v in iter(input) do
if v then
coroutine.yield(k, fn(v))
else
coroutine.yield(fn(k))
end
end
end
--- Return values in an input stream if an applied function returns true.
-- @function filter
-- @tparam function fn
-- @tparam iter input Iterable object
-- @treturn iter Initialized iterator
-- @usage print(x in filter(((v)-> v % 2 == 0), 1::10)); -- odds
local function filter(fn, input)
for k, v in iter(input) do -- luacheck: ignore 213
if fn(k, v) then
coroutine.yield(k, v)
end
end
end
--- Return a value from a function applied to all values of an input stream.
-- @function reduce
-- @tparam function fn
-- @tparam iter input Iterable object
-- @param init Initial value (will use first value of stream if not supplied)
-- @usage print(reduce(((x, y)-> x > y), {5, 2, 7, 9, 1})); -- math.max()
local function reduce(fn, input, init)
for k, v in iter(input) do -- luacheck: ignore 213
if init == nil then
init = v
else
init = assert(fn(init, v))
end
end
return init
end
--- Does the same thing as `reduce`, but operates on ordered sequences.
-- This function should only be used on numeric tables or indexable streams.
-- Use `foldl()` or `foldr()` for convenience instead of this function unless
-- you need control over the exact sequence.
-- @function fold
-- @tparam number start
-- @tparam number stop
-- @tparam number step
-- @tparam function fn
-- @param input Numerically indexable object
-- @param init Initial value (will use first value in input if not supplied)
-- @see reduce
local function fold(start, stop, step, fn, input, init)
for i=start, stop, step do
if not init then
init = input[i]
else
init = assert(fn(init, input[i]))
end
end
return init
end
--- Fold starting from the first value of input to the last value of input.
-- @function foldl
-- @tparam function fn
-- @param input Numerically indexable object
-- @param init Initial value (will use first value in input if not supplied)
-- @see fold, foldr, reduce
local function foldl(fn, input, init)
return fold(1, #input, 1, fn, input, init)
end
--- Fold starting from the last value of input to the first value of input.
-- @function foldr
-- @tparam function fn
-- @param input Numerically indexable object
-- @param init Initial value (will use last value in input if not supplied)
-- @see fold, foldl, reduce
local function foldr(fn, input, init)
return fold(#input, 1, -1, fn, input, init)
end
--- Return the boolean form of a value. False and nil return false, otherwise
-- true is returned.
-- @param val Value to convert to boolean value (optionally nil)
-- @treturn boolean
local function truthy(val)
return not not val
end
--- Return true if any returned value from an input stream are truthy,
-- otherwise false.
-- @function any
-- @tparam function fn
-- @tparam iter input
-- @treturn boolean
-- @usage print(any({nil, true, false})); -- true
local function any(fn, input)
if not fn or not input then
return any(truthy, fn or input)
end
for k, v in iter(input) do -- luacheck: ignore 213
if v ~= nil and fn(v) then
return true
elseif v == nil and fn(k) then
return true
end
end
return false
end
--- Return true if all returned values from an input stream are truthy.
-- @function all
-- @tparam function fn
-- @tparam iter input
-- @treturn boolean
-- @usage print(all(chain(1::50, {false}))); -- false
local function all(fn, input)
if not fn or not input then
return all(truthy, fn or input)
end
for k, v in iter(input) do -- luacheck: ignore 213
if v ~= nil and not fn(v) then
return false
elseif v == nil and not fn(k) then
return false
end
end
return true
end
--- Return a sum of all values in a stream.
-- @function sum
-- @tparam iter input
-- @tparam boolean negative optional; returns a difference instead if true
-- @treturn number
-- @usage print(sum(1::50));
local function sum(input, negative)
if negative then
return reduce(function(a, b) return a - b end, input)
else
return reduce(function(a, b) return a + b end, input)
end
end
return {
_iter = iter;
_mk_gen = mk_gen;
all = all;
any = any;
filter = mk_gen(filter);
foldl = foldl;
foldr = foldr;
map = mk_gen(map);
reduce = reduce;
sum = sum;
}
|
functional: fix iter() and map()
|
functional: fix iter() and map()
|
Lua
|
mit
|
RyanSquared/FusionScript
|
5ce3fd1b678b5cece1034bb64f61a90c3e390d4c
|
framework/sound.lua
|
framework/sound.lua
|
--=========== Copyright © 2017, Planimeter, All rights reserved. =============--
--
-- Purpose:
--
--============================================================================--
local AL = require( "openal" )
local SDL = require( "SDL" )
local SDL_sound = require( "SDL_sound" )
require( "class" )
local ffi = require( "ffi" )
SDL_sound.Sound_Init()
class( "framework.sound" )
local sound = framework.sound
function sound.getFormat( channels, type )
local format = AL.AL_NONE
if ( type == SDL.AUDIO_U8 ) then
if ( channels == 1 ) then
format = AL.AL_FORMAT_MONO8
elseif ( channels == 2 ) then
format = AL.AL_FORMAT_STEREO8
end
elseif ( type == SDL.AUDIO_S16LSB or type == SDL.AUDIO_S16MSB ) then
if ( channels == 1 ) then
format = AL.AL_FORMAT_MONO16
elseif ( channels == 2 ) then
format = AL.AL_FORMAT_STEREO16
end
end
return format
end
function sound:sound( filename )
self.source = ffi.new( "ALuint[1]" )
AL.alGenSources( 1, self.source )
self.buffer = ffi.new( "ALuint[1]" )
AL.alGenBuffers( 1, self.buffer )
local sample = SDL_sound.Sound_NewSampleFromFile( filename, nil, 10240 )
self.sample = sample
local info = sample.actual
local format = sound.format( info.channels, info.format )
local size = SDL_sound.Sound_DecodeAll( sample )
local data = sample.buffer
local freq = info.rate
AL.alBufferData( self.buffer, format, data, size, freq )
setproxy( self )
end
function sound:play()
AL.alSourcePlay( self.source )
end
function sound:__gc()
SDL_sound.Sound_FreeSample( self.sample )
AL.alDeleteBuffers( 1, self.buffer )
AL.alDeleteSources( 1, self.source )
end
|
--=========== Copyright © 2017, Planimeter, All rights reserved. =============--
--
-- Purpose:
--
--============================================================================--
local AL = require( "openal" )
local SDL = require( "sdl" )
local SDL_sound = require( "sdl_sound" )
require( "class" )
local ffi = require( "ffi" )
SDL_sound.Sound_Init()
class( "framework.sound" )
local sound = framework.sound
function sound.getFormat( channels, type )
local format = AL.AL_NONE
if ( type == SDL.AUDIO_U8 ) then
if ( channels == 1 ) then
format = AL.AL_FORMAT_MONO8
elseif ( channels == 2 ) then
format = AL.AL_FORMAT_STEREO8
end
elseif ( type == SDL.AUDIO_S16LSB or type == SDL.AUDIO_S16MSB ) then
if ( channels == 1 ) then
format = AL.AL_FORMAT_MONO16
elseif ( channels == 2 ) then
format = AL.AL_FORMAT_STEREO16
end
end
return format
end
function sound:sound( filename )
self.source = ffi.new( "ALuint[1]" )
AL.alGenSources( 1, self.source )
self.buffer = ffi.new( "ALuint[1]" )
AL.alGenBuffers( 1, self.buffer )
local sample = SDL_sound.Sound_NewSampleFromFile( filename, nil, 0 )
if ( sample == nil ) then
error( "Could not load sound '" .. filename .. "'", 3 )
end
self.sample = sample
local info = sample.actual
local format = framework.sound.getFormat( info.channels, info.format )
local size = SDL_sound.Sound_DecodeAll( sample )
local data = sample.buffer
local freq = info.rate
AL.alBufferData( self.buffer[0], format, data, size, freq )
setproxy( self )
end
function sound:play()
AL.alSourcePlay( self.source[0] )
end
function sound:__gc()
SDL_sound.Sound_FreeSample( self.sample )
AL.alDeleteBuffers( 1, self.buffer )
AL.alDeleteSources( 1, self.source )
end
|
Fix OpenAL and SDL_sound integration
|
Fix OpenAL and SDL_sound integration
|
Lua
|
mit
|
Planimeter/lgameframework,Planimeter/lgameframework,Planimeter/lgameframework
|
755756a66f5500e4d4e1150fda582a09025eaef0
|
init.lua
|
init.lua
|
local framework = require('framework')
local CommandOutputDataSource = framework.CommandOutputDataSource
local PollerCollection = framework.PollerCollection
local DataSourcePoller = framework.DataSourcePoller
local Plugin = framework.Plugin
local os = require('os')
local table = require('table')
local string = require('string')
local env = require('env')
local isEmpty = framework.string.isEmpty
local clone = framework.table.clone
local params = framework.params
local HOST_IS_DOWN = -1
-- Define a map of platform to ping commands
local commands = {
linux = { path = '/bin/ping', args = {'-n', '-w 2', '-c 1'} },
win32 = { path = (env.get('SystemRoot') or 'C:/Windows') .. '/system32/ping.exe', args = {'-n', '1', '-w', '3000'} },
darwin = { path = '/sbin/ping', args = {'-n', '-t 2', '-c 1'} }
}
-- Lookup the ping command to use based on the platform we are running on
local ping_command = commands[string.lower(os.type())]
-- If we do not support this platform then emit an error and exit
if ping_command == nil then
print("_bevent:"..(Plugin.name or params.name)..":"..(Plugin.version or params.version)..":Your platform is not supported. We currently support Linux, Windows and OSX|t:error|tags:lua,plugin"..(Plugin.tags and framework.string.concat(Plugin.tags, ',') or params.tags))
process:exit(-1)
end
-- Creates a poller for each item in our plugin parameter list in param.json
local function createPollers (params, cmd)
local pollers = PollerCollection:new()
for _, item in ipairs(params.items) do
local cmd = clone(cmd)
table.insert(cmd.args, item.host)
cmd.info = item.source
cmd.callback_on_errors = true
local data_source = CommandOutputDataSource:new(cmd)
local poll_interval = tonumber(item.pollInterval or params.pollInterval) * 1000
local poller = DataSourcePoller:new(poll_interval, data_source)
pollers:add(poller)
end
return pollers
end
local function parseOutput(context, output)
assert(output ~= nil, 'parseOutput expect some data')
if isEmpty(output) then
context:emit('error', 'Unable to obtain any output.')
return HOST_IS_DOWN
end
if (string.find(output, "unknown host") or string.find(output, "could not find host.")) then
context:emit('error', 'The host ' .. context.args[#context.args] .. ' was not found.')
return HOST_IS_DOWN
end
local index
local prevIndex = 0
while true do
index = string.find(output, '\n', prevIndex+1)
if not index then break end
local line = string.sub(output, prevIndex, index-1)
local _, _, time = string.find(line, "time[=<]([0-9]*%.?[0-9]+)")
if time then
return tonumber(time)
end
prevIndex = index
end
return HOST_IS_DOWN
end
local pollers = createPollers(params, ping_command)
local plugin = Plugin:new(params, pollers)
function plugin:onParseValues(data)
local result = {}
local value = parseOutput(self, data['output'])
result['PING_RESPONSETIME'] = { value = value, source = data['info'] }
return result
end
plugin:run()
|
local framework = require('framework')
local CommandOutputDataSource = framework.CommandOutputDataSource
local PollerCollection = framework.PollerCollection
local DataSourcePoller = framework.DataSourcePoller
local Plugin = framework.Plugin
local os = require('os')
local table = require('table')
local string = require('string')
local env = require('env')
local isEmpty = framework.string.isEmpty
local clone = framework.table.clone
local params = framework.params
local HOST_IS_DOWN = -1
-- Define a map of platform to ping commands
local commands = {
linux = { path = '/bin/ping', args = {'-n', '-w 2', '-c 1'} },
win32 = { path = (env.get('SystemRoot') or 'C:/Windows') .. '/system32/ping.exe', args = {'-n', '1', '-w', '3000'} },
darwin = { path = '/sbin/ping', args = {'-n', '-t 2', '-c 1'} }
}
-- Lookup the ping command to use based on the platform we are running on
local ping_command = commands[string.lower(os.type())]
-- If we do not support this platform then emit an error and exit
if ping_command == nil then
print("_bevent:"..(Plugin.name or params.name)..":"..(Plugin.version or params.version)..":Your platform is not supported. We currently support Linux, Windows and OSX|t:error|tags:lua,plugin"..(Plugin.tags and framework.string.concat(Plugin.tags, ',') or params.tags))
process:exit(-1)
end
-- Creates a poller for each item in our plugin parameter list in param.json
local function createPollers (params, cmd)
local pollers = PollerCollection:new()
for _, item in ipairs(params.items) do
local cmd = clone(cmd)
table.insert(cmd.args, item.host)
cmd.info = item.source
cmd.callback_on_errors = true
local data_source = CommandOutputDataSource:new(cmd)
local poll_interval = tonumber(item.pollInterval or params.pollInterval) * 1000
local poller = DataSourcePoller:new(poll_interval, data_source)
pollers:add(poller)
end
return pollers
end
local function parseOutput(context, output)
assert(output ~= nil, 'parseOutput expect some data')
if isEmpty(output) then
context:emit('error', 'Unable to obtain any output.')
return HOST_IS_DOWN
end
if (string.find(output, "unknown host") or string.find(output, "could not find host.")) then
return HOST_IS_DOWN
end
local index
local prevIndex = 0
while true do
index = string.find(output, '\n', prevIndex+1)
if not index then break end
local line = string.sub(output, prevIndex, index-1)
local _, _, time = string.find(line, "time[=<]([0-9]*%.?[0-9]+)")
if time then
return tonumber(time)
end
prevIndex = index
end
return HOST_IS_DOWN
end
local pollers = createPollers(params, ping_command)
local plugin = Plugin:new(params, pollers)
function plugin:onParseValues(data)
local result = {}
local value = parseOutput(self, data['output'])
result['PING_RESPONSETIME'] = { value = value, source = data['info'] }
return result
end
plugin:run()
|
Fix when host is not found.
|
Fix when host is not found.
Signed-off-by: GabrielNicolasAvellaneda <[email protected]>
|
Lua
|
apache-2.0
|
GabrielNicolasAvellaneda/boundary-plugin-ping-check,jdgwartney/boundary-plugin-ping-check,boundary/boundary-plugin-ping-check
|
fe7c50d0826a477782e5d76404da43090f0ced42
|
examples/l2-load-latency.lua
|
examples/l2-load-latency.lua
|
-- vim:ts=4:sw=4:noexpandtab
local dpdk = require "dpdk"
local memory = require "memory"
local device = require "device"
local ts = require "timestamping"
local stats = require "stats"
local hist = require "histogram"
local PKT_SIZE = 60
function master(...)
local txPort, rxPort, rate = tonumberall(...)
if not txPort or not rxPort then
return print("usage: txPort rxPort [rate]")
end
rate = rate or 10000
-- hardware rate control fails with small packets at these rates
local numQueues = rate > 6000 and rate < 10000 and 3 or 1
local txDev = device.config(txPort, 2, 4)
local rxDev = device.config(rxPort, 2, 1) -- ignored if txDev == rxDev
local queues = {}
for i = 1, numQueues do
local queue = txDev:getTxQueue(i)
queues[#queues + 1] = queue
if rate < 10000 then -- only set rate if necessary to work with devices that don't support hw rc
queue:setRate(rate / numQueues)
end
end
dpdk.launchLua("loadSlave", queues, txDev, rxDev)
dpdk.launchLua("timerSlave", txDev:getTxQueue(0), rxDev:getRxQueue(1))
dpdk.waitForSlaves()
end
function loadSlave(queues, txDev, rxDev)
local mem = memory.createMemPool(function(buf)
buf:getEthernetPacket():fill{
ethSrc = txDev,
ethDst = ETH_DST,
ethType = 0x1234
}
end)
local bufs = mem:bufArray()
local txCtr = stats:newDevTxCounter(txDev, "plain")
local rxCtr = stats:newDevRxCounter(rxDev, "plain")
while dpdk.running() do
for i, queue in ipairs(queues) do
bufs:alloc(PKT_SIZE)
queue:send(bufs)
end
txCtr:update()
rxCtr:update()
end
txCtr:finalize()
rxCtr:finalize()
end
function timerSlave(txQueue, rxQueue)
local timestamper = ts:newTimestamper(txQueue, rxQueue)
local hist = hist:new()
dpdk.sleepMillis(1000) -- ensure that the load task is running
while dpdk.running() do
hist:update(timestamper:measureLatency())
end
hist:print()
hist:save("histogram.csv")
end
|
-- vim:ts=4:sw=4:noexpandtab
local dpdk = require "dpdk"
local memory = require "memory"
local device = require "device"
local ts = require "timestamping"
local stats = require "stats"
local hist = require "histogram"
local PKT_SIZE = 60
local ETH_DST = "11:12:13:14:15:16"
function master(...)
local txPort, rxPort, rate = tonumberall(...)
if not txPort or not rxPort then
return print("usage: txPort rxPort [rate]")
end
rate = rate or 10000
-- hardware rate control fails with small packets at these rates
local numQueues = rate > 6000 and rate < 10000 and 3 or 1
local txDev = device.config(txPort, 2, 4)
local rxDev = device.config(rxPort, 2, 1) -- ignored if txDev == rxDev
local queues = {}
for i = 1, numQueues do
local queue = txDev:getTxQueue(i)
queues[#queues + 1] = queue
if rate < 10000 then -- only set rate if necessary to work with devices that don't support hw rc
queue:setRate(rate / numQueues)
end
end
dpdk.launchLua("loadSlave", queues, txDev, rxDev)
dpdk.launchLua("timerSlave", txDev:getTxQueue(0), rxDev:getRxQueue(1))
dpdk.waitForSlaves()
end
function loadSlave(queues, txDev, rxDev)
local mem = memory.createMemPool(function(buf)
buf:getEthernetPacket():fill{
ethSrc = txDev,
ethDst = ETH_DST,
ethType = 0x1234
}
end)
local bufs = mem:bufArray()
local txCtr = stats:newDevTxCounter(txDev, "plain")
local rxCtr = stats:newDevRxCounter(rxDev, "plain")
while dpdk.running() do
for i, queue in ipairs(queues) do
bufs:alloc(PKT_SIZE)
queue:send(bufs)
end
txCtr:update()
rxCtr:update()
end
txCtr:finalize()
rxCtr:finalize()
end
function timerSlave(txQueue, rxQueue)
local timestamper = ts:newTimestamper(txQueue, rxQueue)
local hist = hist:new()
dpdk.sleepMillis(1000) -- ensure that the load task is running
while dpdk.running() do
hist:update(timestamper:measureLatency(function(buf) buf:getEthernetPacket().eth.dst:setString(ETH_DST) end))
end
hist:print()
hist:save("histogram.csv")
end
|
examples: fix dst addr in l2-load-latency
|
examples: fix dst addr in l2-load-latency
|
Lua
|
mit
|
emmericp/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,atheurer/MoonGen,slyon/MoonGen,scholzd/MoonGen,bmichalo/MoonGen,schoenb/MoonGen,gallenmu/MoonGen,wenhuizhang/MoonGen,scholzd/MoonGen,kidaa/MoonGen,duk3luk3/MoonGen,werpat/MoonGen,wenhuizhang/MoonGen,bmichalo/MoonGen,duk3luk3/MoonGen,kidaa/MoonGen,NetronomeMoongen/MoonGen,atheurer/MoonGen,gallenmu/MoonGen,bmichalo/MoonGen,slyon/MoonGen,NetronomeMoongen/MoonGen,slyon/MoonGen,gallenmu/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,NetronomeMoongen/MoonGen,dschoeffm/MoonGen,werpat/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,wenhuizhang/MoonGen,bmichalo/MoonGen,slyon/MoonGen,werpat/MoonGen,schoenb/MoonGen,gallenmu/MoonGen,atheurer/MoonGen,kidaa/MoonGen,emmericp/MoonGen,schoenb/MoonGen,duk3luk3/MoonGen,dschoeffm/MoonGen
|
d7a899d4c9c26ae418711cf9a2b4e3727d4efd26
|
kong/plugins/filelog/log.lua
|
kong/plugins/filelog/log.lua
|
-- Copyright (C) Mashape, Inc.
local ffi = require "ffi"
local bit = require "bit"
local cjson = require "cjson"
local fd_util = require "kong.plugins.filelog.fd_util"
local basic_serializer = require "kong.plugins.log_serializers.basic"
ffi.cdef[[
int open(char * filename, int flags, int mode);
int write(int fd, void * ptr, int numbytes);
]]
local O_CREAT = 0x0200
local O_APPEND = 0x0008
local O_WRONLY = 0x0001
local S_IWUSR = 0000200
local S_IRUSR = 0000400
local S_IROTH = 0000004
local function string_to_char(str)
return ffi.cast("uint8_t*", str)
end
-- Log to a file
-- @param `premature`
-- @param `conf` Configuration table, holds http endpoint details
-- @param `message` Message to be logged
local function log(premature, conf, message)
message = cjson.encode(message).."\n"
local fd = fd_util.get_fd(conf.path)
if not fd then
fd = ffi.C.open(string_to_char(conf.path), bit.bor(O_CREAT, O_APPEND, O_WRONLY), bit.bor(S_IWUSR, S_IRUSR, S_IROTH))
fd_util.set_fd(conf.path, fd)
end
ffi.C.write(fd, string_to_char(message), string.len(message))
end
local _M = {}
function _M.execute(conf)
local message = basic_serializer.serialize(ngx)
local ok, err = ngx.timer.at(0, log, conf, message)
if not ok then
ngx.log(ngx.ERR, "[filelog] failed to create timer: ", err)
end
end
return _M
|
-- Copyright (C) Mashape, Inc.
local ffi = require "ffi"
local bit = require "bit"
local cjson = require "cjson"
local fd_util = require "kong.plugins.filelog.fd_util"
local basic_serializer = require "kong.plugins.log_serializers.basic"
ffi.cdef[[
int open(char * filename, int flags, int mode);
int write(int fd, void * ptr, int numbytes);
]]
local octal = function(n) return tonumber(n, 8) end
local O_CREAT = octal('0100')
local O_APPEND = octal('02000')
local O_WRONLY = octal('0001')
local S_IWUSR = octal('00200')
local S_IRUSR = octal('00400')
local S_IXUSR = octal('00100')
local function string_to_char(str)
return ffi.cast("uint8_t*", str)
end
-- Log to a file
-- @param `premature`
-- @param `conf` Configuration table, holds http endpoint details
-- @param `message` Message to be logged
local function log(premature, conf, message)
message = cjson.encode(message).."\n"
local fd = fd_util.get_fd(conf.path)
if not fd then
fd = ffi.C.open(string_to_char(conf.path), bit.bor(O_CREAT, O_APPEND, O_WRONLY), bit.bor(S_IWUSR, S_IRUSR, S_IXUSR))
fd_util.set_fd(conf.path, fd)
end
ffi.C.write(fd, string_to_char(message), string.len(message))
end
local _M = {}
function _M.execute(conf)
local message = basic_serializer.serialize(ngx)
local ok, err = ngx.timer.at(0, log, conf, message)
if not ok then
ngx.log(ngx.ERR, "[filelog] failed to create timer: ", err)
end
end
return _M
|
Fixing file permissions, closes #461
|
Fixing file permissions, closes #461
|
Lua
|
apache-2.0
|
ChristopherBiscardi/kong,AnsonSmith/kong,peterayeni/kong,skynet/kong
|
1c8a0adbf78a755c821da515e83fce11b5543cdc
|
nyagos.d/comspec.lua
|
nyagos.d/comspec.lua
|
if not nyagos then
print("This is a script for nyagos not lua.exe")
os.exit()
end
if nyagos.goos == "windows" then
for _,name in pairs{
"assoc",
"dir",
"mklink",
"ren",
"rename",
} do
nyagos.alias[name] = "%COMSPEC% /c "..name.." $*"
end
local greppath=nyagos.which("grep")
if not greppath and not nyagos.alias.grep then
nyagos.alias.grep = "findstr.exe"
end
end
|
if not nyagos then
print("This is a script for nyagos not lua.exe")
os.exit()
end
if nyagos.goos == "windows" then
local comspec = nyagos.env.comspec
if not comspec or comspec == "" then
comspec = "CMD.EXE"
end
for _,name in pairs{
"assoc",
"dir",
"mklink",
"ren",
"rename",
} do
nyagos.alias[name] = comspec .. " /c "..name.." $*"
end
local greppath=nyagos.which("grep")
if not greppath and not nyagos.alias.grep then
nyagos.alias.grep = "findstr.exe"
end
end
|
Fix: aliases using CMD.EXE did not work when %COMSPEC% is not defined.
|
Fix: aliases using CMD.EXE did not work when %COMSPEC% is not defined.
|
Lua
|
bsd-3-clause
|
zetamatta/nyagos,nocd5/nyagos,tsuyoshicho/nyagos
|
4ef548cc9dea1424707edafead3eed64150a996f
|
script/c27971137.lua
|
script/c27971137.lua
|
--腐乱犬
function c27971137.initial_effect(c)
--atk change
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_ATTACK_ANNOUNCE)
e1:SetOperation(c27971137.atop)
c:RegisterEffect(e1)
--special summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(27971137,0))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e2:SetCode(EVENT_TO_GRAVE)
e2:SetCondition(c27971137.condition)
e2:SetTarget(c27971137.target)
e2:SetOperation(c27971137.operation)
c:RegisterEffect(e2)
end
function c27971137.atop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(500)
e1:SetReset(RESET_EVENT+0x1ff0000)
c:RegisterEffect(e1)
end
function c27971137.condition(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsReason(REASON_DESTROY) and c:IsPreviousLocation(LOCATION_ONFIELD)
end
function c27971137.filter(c,e,tp)
return c:GetLevel()==1 and c:GetDefence()==0 and c:GetAttack()==0
and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c27971137.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c27971137.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c27971137.operation(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c27971137.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
local tc=g:GetFirst()
local c=e:GetHandler()
if tc and Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1,true)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DISABLE_EFFECT)
e2:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e2,true)
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e3:SetRange(LOCATION_MZONE)
e3:SetCode(EVENT_PHASE+PHASE_END)
e3:SetOperation(c27971137.desop)
e3:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
e3:SetCountLimit(1)
tc:RegisterEffect(e3)
Duel.SpecialSummonComplete()
end
end
function c27971137.desop(e,tp,eg,ep,ev,re,r,rp)
Duel.Destroy(e:GetHandler(),REASON_EFFECT)
end
|
--腐乱犬
function c27971137.initial_effect(c)
--atk change
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_ATTACK_ANNOUNCE)
e1:SetOperation(c27971137.atop)
c:RegisterEffect(e1)
--special summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(27971137,0))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e2:SetCode(EVENT_TO_GRAVE)
e2:SetCondition(c27971137.condition)
e2:SetTarget(c27971137.target)
e2:SetOperation(c27971137.operation)
c:RegisterEffect(e2)
end
function c27971137.atop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(500)
e1:SetReset(RESET_EVENT+0x1ff0000)
c:RegisterEffect(e1)
end
function c27971137.condition(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsReason(REASON_DESTROY) and c:IsPreviousLocation(LOCATION_ONFIELD)
end
function c27971137.filter(c,e,tp)
return c:GetLevel()==1 and c:GetDefence()==0 and c:GetAttack()==0
and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c27971137.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c27971137.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c27971137.operation(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c27971137.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
local tc=g:GetFirst()
local c=e:GetHandler()
if tc and Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1,true)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DISABLE_EFFECT)
e2:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e2,true)
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e3:SetRange(LOCATION_MZONE)
e3:SetCode(EVENT_PHASE+PHASE_END)
e3:SetCountLimit(1)
e3:SetCondition(c27971137.descon)
e3:SetOperation(c27971137.desop)
if Duel.GetCurrentPhase()==PHASE_END and Duel.GetTurnPlayer()==tp then
e3:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END+RESET_SELF_TURN,2)
else
e3:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END+RESET_SELF_TURN)
end
e3:SetCountLimit(1)
tc:RegisterEffect(e3)
Duel.SpecialSummonComplete()
end
end
function c27971137.descon(e,tp)
return Duel.GetTurnPlayer()==tp
end
function c27971137.desop(e,tp,eg,ep,ev,re,r,rp)
Duel.Destroy(e:GetHandler(),REASON_EFFECT)
end
|
Update c27971137.lua
|
Update c27971137.lua
fix
|
Lua
|
mit
|
SuperAndroid17/DevProLauncher,sidschingis/DevProLauncher,Tic-Tac-Toc/DevProLauncher
|
9840697e96b35f3a65baba0aa683b4e2823bba45
|
rima.lua
|
rima.lua
|
--
-- rima.lua
--
--
-- Task manager for imap collector.
-- Task's key is a user email address.
-- Rima can manage some tasks with the same key.
-- Tasks with identical keys will be groupped and managed as one bunch of tasks.
--
-- Producers can adds tasks by rima_put() calls.
-- Consumer request a bunch of tasks (with common key) by calling rima_get().
-- When Rima gives a task to worker it locks the key until worker calls rima_done(key).
-- Rima does not return task with already locked keys.
--
--
-- Space 0: Remote IMAP Collector Task Queue
-- Tuple: { task_id (NUM64), key (STR), task_description (NUM), add_time (NUM) }
-- Index 0: TREE { task_id }
-- Index 1: TREE { key, task_id }
--
-- Space 2: Task Priority
-- Tuple: { key (STR), priority (NUM), is_locked (NUM), lock_time (NUM) }
-- Index 0: TREE { key }
-- Index 1: TREE { priority, is_locked }
--
--
-- Put task to the queue.
--
local function rima_put_impl(key, data, prio)
-- insert task data into the queue
box.auto_increment(0, key, data, box.time())
-- increase priority of the key
local pr = box.select(2, 0, key)
if pr == nil then
box.insert(2, key, prio, 0, box.time())
elseif box.unpack('i', pr[1]) < prio then
box.update(2, key, "=p", 1, prio)
end
end
function rima_put(key, data) -- deprecated
rima_put_impl(key, data, 512)
end
function rima_put_prio(key, data) -- deprecated
rima_put_impl(key, data, 1024)
end
function rima_put_with_prio(key, data, prio)
prio = box.unpack('i', prio)
rima_put_impl(key, data, prio)
end
local function get_prio_key(prio)
for v in box.space[2].index[1]:iterator(box.index.EQ, prio, 0) do
local key = v[0]
-- lock the key
box.update(2, key, "=p=p", 2, 1, 3, box.time())
return key
end
return nil
end
local function get_key_data_old(key) -- deprecated
if key == nil then return nil end
local result = {}
local tuples = { box.select_limit(0, 1, 0, 8000, key) }
for _, tuple in pairs(tuples) do
tuple = box.delete(0, tuple[0])
if tuple ~= nil then table.insert(result, tuple[2]) end
end
return result
end
local function get_key_data(key)
if key == nil then return nil end
local result = {}
local tuples = { box.select_limit(0, 1, 0, 2000, key) }
for _, tuple in pairs(tuples) do
tuple = box.delete(0, tuple[0])
if tuple ~= nil then
local add_time
if #tuple > 3 then
add_time = box.unpack('i', tuple[3])
else
add_time = box.time() -- deprecated
end
table.insert(result, { add_time, tuple[2] } )
end
end
return result
end
local function rima_get_prio_impl_old(prio) -- deprecated
local key = get_prio_key(prio)
local result = get_key_data_old(key)
return key, result
end
local function rima_get_prio_impl(prio)
local key = get_prio_key(prio)
local result = get_key_data(key)
return key, result
end
--
-- Request tasks from the queue.
--
function rima_get_with_prio(prio) -- deprecated
prio = box.unpack('i', prio)
for i = 1,10 do
local key, result = rima_get_prio_impl_old(prio)
if key ~= nil then return key, unpack(result) end
box.fiber.sleep(0.001)
end
end
function rima_get_ex(prio)
prio = box.unpack('i', prio)
for i = 1,10 do
local key, result = rima_get_prio_impl(prio)
if key ~= nil then return key, unpack(result) end
box.fiber.sleep(0.001)
end
end
--
-- Notify manager that tasks for that key was completed.
-- Rima unlocks key and next rima_get() may returns tasks with such key.
--
function rima_done(key)
local pr = box.select(2, 0, key)
if pr == nil then return end
if box.select(0, 1, key) == nil then
-- no tasks for this key in the queue
box.delete(2, key)
else
box.update(2, key, "=p=p", 2, 0, 3, box.time())
end
end
--
-- Run expiration of tuples
--
local function is_expired(args, tuple)
if tuple == nil or #tuple <= args.fieldno then
return nil
end
-- expire only locked keys
if tuple[2] == '' then return false end
print("tuple[2] = " .. box.unpack('i', tuple[2]))
local field = tuple[args.fieldno]
local current_time = box.time()
local tuple_expire_time = box.unpack('i', field) + args.expiration_time
return current_time >= tuple_expire_time
end
local function delete_expired(spaceno, args, tuple)
rima_done(tuple[0])
end
dofile('expirationd.lua')
expirationd.run_task('expire_locks', 2, is_expired, delete_expired, {fieldno = 3, expiration_time = 30*60})
|
--
-- rima.lua
--
--
-- Task manager for imap collector.
-- Task's key is a user email address.
-- Rima can manage some tasks with the same key.
-- Tasks with identical keys will be groupped and managed as one bunch of tasks.
--
-- Producers can adds tasks by rima_put() calls.
-- Consumer request a bunch of tasks (with common key) by calling rima_get().
-- When Rima gives a task to worker it locks the key until worker calls rima_done(key).
-- Rima does not return task with already locked keys.
--
--
-- Space 0: Remote IMAP Collector Task Queue
-- Tuple: { task_id (NUM64), key (STR), task_description (NUM), add_time (NUM) }
-- Index 0: TREE { task_id }
-- Index 1: TREE { key, task_id }
--
-- Space 2: Task Priority
-- Tuple: { key (STR), priority (NUM), is_locked (NUM), lock_time (NUM) }
-- Index 0: TREE { key }
-- Index 1: TREE { priority, is_locked }
--
--
-- Put task to the queue.
--
local function rima_put_impl(key, data, prio)
-- insert task data into the queue
box.auto_increment(0, key, data, box.time())
-- increase priority of the key
local pr = box.select(2, 0, key)
if pr == nil then
box.insert(2, key, prio, 0, box.time())
elseif box.unpack('i', pr[1]) < prio then
box.update(2, key, "=p", 1, prio)
end
end
function rima_put(key, data) -- deprecated
rima_put_impl(key, data, 512)
end
function rima_put_prio(key, data) -- deprecated
rima_put_impl(key, data, 1024)
end
function rima_put_with_prio(key, data, prio)
prio = box.unpack('i', prio)
rima_put_impl(key, data, prio)
end
local function get_prio_key(prio)
for v in box.space[2].index[1]:iterator(box.index.EQ, prio, 0) do
local key = v[0]
-- lock the key
box.update(2, key, "=p=p", 2, 1, 3, box.time())
return key
end
return nil
end
local function get_key_data_old(key) -- deprecated
if key == nil then return nil end
local result = {}
local tuples = { box.select_limit(0, 1, 0, 8000, key) }
for _, tuple in pairs(tuples) do
tuple = box.delete(0, tuple[0])
if tuple ~= nil then table.insert(result, tuple[2]) end
end
return result
end
local function get_key_data(key)
if key == nil then return nil end
local result = {}
local tuples = { box.select_limit(0, 1, 0, 2000, key) }
for _, tuple in pairs(tuples) do
tuple = box.delete(0, tuple[0])
if tuple ~= nil then
local add_time
if #tuple > 3 then
add_time = box.unpack('i', tuple[3])
else
add_time = box.time() -- deprecated
end
table.insert(result, { add_time, tuple[2] } )
end
end
return result
end
local function rima_get_prio_impl_old(prio) -- deprecated
local key = get_prio_key(prio)
local result = get_key_data_old(key)
return key, result
end
local function rima_get_prio_impl(prio)
local key = get_prio_key(prio)
local result = get_key_data(key)
return key, result
end
--
-- Request tasks from the queue.
--
function rima_get_with_prio(prio) -- deprecated
prio = box.unpack('i', prio)
for i = 1,10 do
local key, result = rima_get_prio_impl_old(prio)
if key ~= nil then return key, unpack(result) end
box.fiber.sleep(0.001)
end
end
function rima_get_ex(prio)
prio = box.unpack('i', prio)
for i = 1,10 do
local key, result = rima_get_prio_impl(prio)
if key ~= nil then return key, unpack(result) end
box.fiber.sleep(0.001)
end
end
--
-- Notify manager that tasks for that key was completed.
-- Rima unlocks key and next rima_get() may returns tasks with such key.
--
function rima_done(key)
local pr = box.select(2, 0, key)
if pr == nil then return end
if box.select(0, 1, key) == nil then
-- no tasks for this key in the queue
box.delete(2, key)
else
box.update(2, key, "=p=p", 2, 0, 3, box.time())
end
end
--
-- Run expiration of tuples
--
local function is_expired(args, tuple)
if tuple == nil or #tuple <= args.fieldno then
return nil
end
-- expire only locked keys
if tuple[2] == '' then return false end
if box.unpack('i', tuple[2]) == 0 then return false end
local field = tuple[args.fieldno]
local current_time = box.time()
local tuple_expire_time = box.unpack('i', field) + args.expiration_time
return current_time >= tuple_expire_time
end
local function delete_expired(spaceno, args, tuple)
rima_done(tuple[0])
end
dofile('expirationd.lua')
expirationd.run_task('expire_locks', 2, is_expired, delete_expired, {fieldno = 3, expiration_time = 30*60})
|
rima.lua: remove debug message; fix
|
rima.lua: remove debug message; fix
|
Lua
|
bsd-2-clause
|
spectrec/tntlua,grechkin-pogrebnyakov/tntlua,mailru/tntlua,BHYCHIK/tntlua,derElektrobesen/tntlua
|
1a6615b79152e36724c8083557d98c94aa3b55ad
|
lib/http.lua
|
lib/http.lua
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local TCP = require('tcp')
local net = require('net')
local Request = require('request')
local Response = require('response')
local HTTP_Parser = require('http_parser')
local Table = require('table')
local HTTP = {}
function HTTP.request(options, callback)
-- Load options into local variables. Assume defaults
local host = options.host or "127.0.0.1"
local port = options.port or 80
local method = options.method or "GET"
local path = options.path or "/"
local headers = options.headers or {}
if not headers.host then headers.host = host end
local client
client = net.create(port, host, function(err)
if err then
callback(err)
client:close()
return
end
local response = Response.new(client)
local request = {method .. " " .. path .. " HTTP/1.1\r\n"}
for field, value in pairs(headers) do
request[#request + 1] = field .. ": " .. value .. "\r\n"
end
request[#request + 1] = "\r\n"
client:write(Table.concat(request))
local headers
local current_field
local parser = HTTP_Parser.new("response", {
on_message_begin = function ()
headers = {}
end,
on_url = function (url)
end,
on_header_field = function (field)
current_field = field
end,
on_header_value = function (value)
headers[current_field:lower()] = value
end,
on_headers_complete = function (info)
response.headers = headers
response.status_code = info.status_code
response.version_minor = info.version_minor
response.version_major = info.version_major
callback(nil, response)
end,
on_body = function (chunk)
response:emit('data', chunk)
end,
on_message_complete = function ()
response:emit('end')
end
});
client:on("data", function (chunk, len)
local nparsed = parser:execute(chunk, 0, len)
-- If it wasn't all parsed then there was an error parsing
if nparsed < len then
error("Parse error in server response")
end
end)
client:on("end", function ()
parser:finish()
end)
end)
end
function HTTP.create_server(host, port, on_connection)
local server
server = net.createServer(function(client)
if err then
return server:emit("error", err)
end
-- Accept the client and build request and response objects
local request = Request.new(client)
local response = Response.new(client)
-- Convert TCP stream to HTTP stream
local current_field
local parser
local headers
parser = HTTP_Parser.new("request", {
on_message_begin = function ()
headers = {}
request.headers = headers
end,
on_url = function (url)
request.url = url
end,
on_header_field = function (field)
current_field = field
end,
on_header_value = function (value)
headers[current_field:lower()] = value
end,
on_headers_complete = function (info)
request.method = info.method
request.upgrade = info.upgrade
request.version_major = info.version_major
request.version_minor = info.version_minor
-- Give upgrade requests access to the raw client if they want it
if info.upgrade then
request.client = client
end
-- Handle 100-continue requests
if request.headers.expect and info.version_major == 1 and info.version_minor == 1 and request.headers.expect:lower() == "100-continue" then
if server.handlers and server.handlers.check_continue then
server:emit("check_continue", request, response)
else
response:write_continue()
on_connection(request, response)
end
else
on_connection(request, response)
end
-- We're done with the parser once we hit an upgrade
if request.upgrade then
parser:finish()
end
end,
on_body = function (chunk)
request:emit('data', chunk, #chunk)
end,
on_message_complete = function ()
request:emit('end')
end
})
client:on("data", function (chunk, len)
-- Ignore empty chunks
if len == 0 then return end
-- Once we're in "upgrade" mode, the protocol is no longer HTTP and we
-- shouldn't send data to the HTTP parser
if request.upgrade then
request:emit("data", chunk, len)
return
end
-- Parse the chunk of HTTP, this will syncronously emit several of the
-- above events and return how many bytes were parsed.
local nparsed = parser:execute(chunk, 0, len)
-- If it wasn't all parsed then there was an error parsing
if nparsed < len then
-- If the error was caused by non-http protocol like in websockets
-- then that's ok, just emit the rest directly to the request object
if request.upgrade then
len = len - nparsed
chunk = chunk:sub(nparsed + 1)
request:emit("data", chunk, len)
else
request:emit("error", "parse error")
end
end
end)
client:on("end", function ()
parser:finish()
end)
end)
server:listen(port, host)
return server
end
return HTTP
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local TCP = require('tcp')
local net = require('net')
local Request = require('request')
local Response = require('response')
local HTTP_Parser = require('http_parser')
local Table = require('table')
local HTTP = {}
function HTTP.request(options, callback)
-- Load options into local variables. Assume defaults
local host = options.host or "127.0.0.1"
local port = options.port or 80
local method = options.method or "GET"
local path = options.path or "/"
local headers = options.headers or {}
if not headers.host then headers.host = host end
local client
client = net.create(port, host, function(err)
if err then
callback(err)
client:close()
return
end
local response = Response.new(client)
local request = {method .. " " .. path .. " HTTP/1.1\r\n"}
for field, value in pairs(headers) do
request[#request + 1] = field .. ": " .. value .. "\r\n"
end
request[#request + 1] = "\r\n"
client:write(Table.concat(request))
local headers
local current_field
local parser = HTTP_Parser.new("response", {
on_message_begin = function ()
headers = {}
end,
on_url = function (url)
end,
on_header_field = function (field)
current_field = field
end,
on_header_value = function (value)
headers[current_field:lower()] = value
end,
on_headers_complete = function (info)
response.headers = headers
response.status_code = info.status_code
response.version_minor = info.version_minor
response.version_major = info.version_major
callback(nil, response)
end,
on_body = function (chunk)
response:emit('data', chunk)
end,
on_message_complete = function ()
response:emit('end')
end
});
client:on("data", function (chunk)
local nparsed = parser:execute(chunk, 0, #chunk)
-- If it wasn't all parsed then there was an error parsing
if nparsed < #chunk then
error("Parse error in server response")
end
end)
client:on("end", function ()
parser:finish()
end)
end)
end
function HTTP.create_server(host, port, on_connection)
local server
server = net.createServer(function(client)
if err then
return server:emit("error", err)
end
-- Accept the client and build request and response objects
local request = Request.new(client)
local response = Response.new(client)
-- Convert TCP stream to HTTP stream
local current_field
local parser
local headers
parser = HTTP_Parser.new("request", {
on_message_begin = function ()
headers = {}
request.headers = headers
end,
on_url = function (url)
request.url = url
end,
on_header_field = function (field)
current_field = field
end,
on_header_value = function (value)
headers[current_field:lower()] = value
end,
on_headers_complete = function (info)
request.method = info.method
request.upgrade = info.upgrade
request.version_major = info.version_major
request.version_minor = info.version_minor
-- Give upgrade requests access to the raw client if they want it
if info.upgrade then
request.client = client
end
-- Handle 100-continue requests
if request.headers.expect and info.version_major == 1 and info.version_minor == 1 and request.headers.expect:lower() == "100-continue" then
if server.handlers and server.handlers.check_continue then
server:emit("check_continue", request, response)
else
response:write_continue()
on_connection(request, response)
end
else
on_connection(request, response)
end
-- We're done with the parser once we hit an upgrade
if request.upgrade then
parser:finish()
end
end,
on_body = function (chunk)
request:emit('data', chunk, #chunk)
end,
on_message_complete = function ()
request:emit('end')
end
})
client:on("data", function (chunk)
-- Ignore empty chunks
if #chunk == 0 then return end
-- Once we're in "upgrade" mode, the protocol is no longer HTTP and we
-- shouldn't send data to the HTTP parser
if request.upgrade then
request:emit("data", chunk)
return
end
-- Parse the chunk of HTTP, this will syncronously emit several of the
-- above events and return how many bytes were parsed.
local nparsed = parser:execute(chunk, 0, #chunk)
-- If it wasn't all parsed then there was an error parsing
if nparsed < #chunk then
-- If the error was caused by non-http protocol like in websockets
-- then that's ok, just emit the rest directly to the request object
if request.upgrade then
chunk = chunk:sub(nparsed + 1)
request:emit("data", chunk)
else
request:emit("error", "parse error")
end
end
end)
client:on("end", function ()
parser:finish()
end)
end)
server:listen(port, host)
return server
end
return HTTP
|
fixes for http.lua
|
fixes for http.lua
|
Lua
|
apache-2.0
|
sousoux/luvit,AndrewTsao/luvit,bsn069/luvit,boundary/luvit,kaustavha/luvit,connectFree/lev,kaustavha/luvit,rjeli/luvit,sousoux/luvit,boundary/luvit,boundary/luvit,zhaozg/luvit,luvit/luvit,DBarney/luvit,sousoux/luvit,AndrewTsao/luvit,sousoux/luvit,boundary/luvit,DBarney/luvit,rjeli/luvit,boundary/luvit,rjeli/luvit,boundary/luvit,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream,sousoux/luvit,kaustavha/luvit,zhaozg/luvit,rjeli/luvit,DBarney/luvit,bsn069/luvit,connectFree/lev,GabrielNicolasAvellaneda/luvit-upstream,AndrewTsao/luvit,DBarney/luvit,luvit/luvit,GabrielNicolasAvellaneda/luvit-upstream,sousoux/luvit,bsn069/luvit
|
881f6f9e4909b0ecc8e7c1df10232938b90bc3fb
|
src/extensions/cp/console/history.lua
|
src/extensions/cp/console/history.lua
|
--- === cp.console.history ===
---
--- Console History Manager.
---
--- Based on code by @asmagill
--- https://github.com/asmagill/hammerspoon-config-take2/blob/master/utils/_actions/consoleHistory.lua
--------------------------------------------------------------------------------
--
-- EXTENSIONS:
--
--------------------------------------------------------------------------------
local require = require
--------------------------------------------------------------------------------
-- Logger:
--------------------------------------------------------------------------------
--local log = require("hs.logger").new("history")
--------------------------------------------------------------------------------
-- Hammerspoon Extensions:
--------------------------------------------------------------------------------
local console = require("hs.console")
local hash = require("hs.hash")
local timer = require("hs.timer")
--------------------------------------------------------------------------------
-- CommandPost Extensions:
--------------------------------------------------------------------------------
local config = require("cp.config")
local json = require("cp.json")
--------------------------------------------------------------------------------
--
-- CONSTANTS:
--
--------------------------------------------------------------------------------
-- FILE_NAME -> string
-- Constant
-- File name of settings file.
local FILE_NAME = "History.cpCache"
-- FOLDER_NAME -> string
-- Constant
-- Folder Name where settings file is contained.
local FOLDER_NAME = "Error Log"
-- CHECK_INTERVAL -> number
-- Constant
-- How often to check for changes.
--local CHECK_INTERVAL = 1
-- MAXIMUM -> number
-- Constant
-- Maximum history to save
local MAXIMUM = 100
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local mod = {}
-- hashFN -> function
-- Variable
-- The has function. Can use other hash function if this proves insufficient.
local hashFN = hash.MD5
-- currentHistoryCount -> number
-- Variable
-- Current History Count
local currentHistoryCount = #console.getHistory()
--- cp.console.history.cache <cp.prop: table>
--- Field
--- Console History Cache
mod.cache = json.prop(config.cachePath, FOLDER_NAME, FILE_NAME, nil)
-- uniqueHistory(raw) -> table
-- Function
-- Takes the raw history and returns only the unique history.
--
-- Parameters:
-- * raw - The raw history as a table
--
-- Returns:
-- * A table
local function uniqueHistory(raw)
local hashed, history = {}, {}
for i = #raw, 1, -1 do
local key = hashFN(raw[i])
if not hashed[key] then
table.insert(history, 1, raw[i])
hashed[key] = true
end
end
return history
end
--- cp.console.history.clearHistory() -> none
--- Function
--- Clears the Console History.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function mod.clearHistory()
return console.setHistory({})
end
--- cp.console.history.saveHistory() -> none
--- Function
--- Saves the Console History.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function mod.saveHistory()
local hist, save = console.getHistory(), {}
if #hist > MAXIMUM then
table.move(hist, #hist - MAXIMUM, #hist, 1, save)
else
save = hist
end
--------------------------------------------------------------------------------
-- Save only the unique lines:
--------------------------------------------------------------------------------
mod.cache(uniqueHistory(save))
end
--- cp.console.history.retrieveHistory() -> none
--- Function
--- Retrieve's the Console History.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function mod.retrieveHistory()
local history = mod.cache()
if (history) then
console.setHistory(history)
end
end
--- cp.console.history.pruneHistory() -> number
--- Function
--- Prune History
---
--- Parameters:
--- * None
---
--- Returns:
--- * Current History Count
function mod.pruneHistory()
console.setHistory(uniqueHistory(console.getHistory()))
currentHistoryCount = #console.getHistory()
return currentHistoryCount
end
--- cp.console.history.history(toFind) -> none
--- Function
--- Gets a history item.
---
--- Parameters:
--- * toFind - Number of the item to find.
---
--- Returns:
--- * None
function mod.history(toFind)
if type(toFind) == "number" then
local history = console.getHistory()
if toFind < 0 then toFind = #history - (toFind + 1) end
local command = history[toFind]
if command then
print(">> " .. command)
timer.doAfter(.1, function()
local newHistory = console.getHistory()
newHistory[#newHistory] = command
console.setHistory(newHistory)
end)
local fn, err = load("return " .. command)
if not fn then fn, err = load(command) end
if fn then return fn() else return err end
else
error("nil item at specified history position", 2)
end
else
toFind = toFind or ""
for i,v in ipairs(console.getHistory()) do
if v:match(toFind) then print(i, v) end
end
end
end
--- cp.console.history.init() -> self
--- Function
--- Initialise the module.
---
--- Parameters:
--- * None
---
--- Returns:
--- * Self
function mod.init()
--------------------------------------------------------------------------------
-- Setup Autosave Timer:
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- NOTE: Chris has disabled this, because he THINKS it's the source of a
-- memory leak. However, the Console history SHOULD still work
-- as it's called as part of garbage collection.
--------------------------------------------------------------------------------
--[[
mod.autosaveHistory = timer.new(CHECK_INTERVAL, function()
local historyNow = console.getHistory()
if #historyNow ~= currentHistoryCount then
currentHistoryCount = #historyNow
mod.saveHistory()
end
end):start()
--]]
--------------------------------------------------------------------------------
-- Retrieve History on Boot:
--------------------------------------------------------------------------------
mod.retrieveHistory()
return mod
end
--------------------------------------------------------------------------------
-- Setup Garbage Collection:
--------------------------------------------------------------------------------
mod = setmetatable(mod, {__gc = function(_) _.saveHistory() end})
return mod.init()
|
--- === cp.console.history ===
---
--- Console History Manager.
---
--- Based on code by @asmagill
--- https://github.com/asmagill/hammerspoon-config-take2/blob/master/utils/_actions/consoleHistory.lua
--------------------------------------------------------------------------------
--
-- EXTENSIONS:
--
--------------------------------------------------------------------------------
local require = require
--------------------------------------------------------------------------------
-- Logger:
--------------------------------------------------------------------------------
--local log = require("hs.logger").new("history")
--------------------------------------------------------------------------------
-- Hammerspoon Extensions:
--------------------------------------------------------------------------------
local console = require("hs.console")
local hash = require("hs.hash")
local timer = require("hs.timer")
--------------------------------------------------------------------------------
-- CommandPost Extensions:
--------------------------------------------------------------------------------
local config = require("cp.config")
local json = require("cp.json")
--------------------------------------------------------------------------------
--
-- CONSTANTS:
--
--------------------------------------------------------------------------------
-- FILE_NAME -> string
-- Constant
-- File name of settings file.
local FILE_NAME = "History.cpCache"
-- FOLDER_NAME -> string
-- Constant
-- Folder Name where settings file is contained.
local FOLDER_NAME = "Error Log"
-- MAXIMUM -> number
-- Constant
-- Maximum history to save
local MAXIMUM = 100
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local mod = {}
-- hashFN -> function
-- Variable
-- The has function. Can use other hash function if this proves insufficient.
local hashFN = hash.MD5
-- currentHistoryCount -> number
-- Variable
-- Current History Count
local currentHistoryCount = #console.getHistory()
--- cp.console.history.cache <cp.prop: table>
--- Field
--- Console History Cache
mod.cache = json.prop(config.cachePath, FOLDER_NAME, FILE_NAME, {})
-- uniqueHistory(raw) -> table
-- Function
-- Takes the raw history and returns only the unique history.
--
-- Parameters:
-- * raw - The raw history as a table
--
-- Returns:
-- * A table
local function uniqueHistory(raw)
local hashed, history = {}, {}
for i = #raw, 1, -1 do
local key = hashFN(raw[i])
if not hashed[key] then
table.insert(history, 1, raw[i])
hashed[key] = true
end
end
return history
end
--- cp.console.history.clearHistory() -> none
--- Function
--- Clears the Console History.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function mod.clearHistory()
return console.setHistory({})
end
--- cp.console.history.saveHistory() -> none
--- Function
--- Saves the Console History.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function mod.saveHistory()
local hist, save = console.getHistory(), {}
if #hist > MAXIMUM then
table.move(hist, #hist - MAXIMUM, #hist, 1, save)
else
save = hist
end
--------------------------------------------------------------------------------
-- Save only the unique lines:
--------------------------------------------------------------------------------
mod.cache(uniqueHistory(save))
end
--- cp.console.history.retrieveHistory() -> none
--- Function
--- Retrieve's the Console History.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function mod.retrieveHistory()
local history = mod.cache()
if (history) then
console.setHistory(history)
end
end
--- cp.console.history.pruneHistory() -> number
--- Function
--- Prune History
---
--- Parameters:
--- * None
---
--- Returns:
--- * Current History Count
function mod.pruneHistory()
console.setHistory(uniqueHistory(console.getHistory()))
currentHistoryCount = #console.getHistory()
return currentHistoryCount
end
--- cp.console.history.history(toFind) -> none
--- Function
--- Gets a history item.
---
--- Parameters:
--- * toFind - Number of the item to find.
---
--- Returns:
--- * None
function mod.history(toFind)
if type(toFind) == "number" then
local history = console.getHistory()
if toFind < 0 then toFind = #history - (toFind + 1) end
local command = history[toFind]
if command then
print(">> " .. command)
timer.doAfter(.1, function()
local newHistory = console.getHistory()
newHistory[#newHistory] = command
console.setHistory(newHistory)
end)
local fn, err = load("return " .. command)
if not fn then fn, err = load(command) end
if fn then return fn() else return err end
else
error("nil item at specified history position", 2)
end
else
toFind = toFind or ""
for i,v in ipairs(console.getHistory()) do
if v:match(toFind) then print(i, v) end
end
end
end
--- cp.console.history.init() -> self
--- Function
--- Initialise the module.
---
--- Parameters:
--- * None
---
--- Returns:
--- * Self
function mod.init()
--------------------------------------------------------------------------------
-- Retrieve History on Boot:
--------------------------------------------------------------------------------
mod.retrieveHistory()
return mod
end
--------------------------------------------------------------------------------
-- Setup Garbage Collection:
--------------------------------------------------------------------------------
mod = setmetatable(mod, {__gc = function(_) _.saveHistory() end})
return mod.init()
|
Tweaks
|
Tweaks
- Fixed an error message that would occur the first time you install
CommandPost where the Console History will try to write `nil` to the
JSON prop.
- Removed unnecesssary code from `cp.console.history`
|
Lua
|
mit
|
CommandPost/CommandPost,CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,fcpxhacks/fcpxhacks
|
4f2789ca0df4b51af264f11c2de3510c1db874d2
|
util/hashes.lua
|
util/hashes.lua
|
local softreq = function (...) return select(2, pcall(require, ...)); end
local error = error;
module "hashes"
local md5 = softreq("md5");
if md5 then
if md5.digest then
local md5_digest = md5.digest;
local sha1_digest = sha1.digest;
function _M.md5(input)
return md5_digest(input);
end
function _M.sha1(input)
return sha1_digest(input);
end
elseif md5.sumhexa then
local md5_sumhexa = md5.sumhexa;
function _M.md5(input)
return md5_sumhexa(input);
end
else
error("md5 library found, but unrecognised... no hash functions will be available", 0);
end
else
error("No md5 library found. Install md5 using luarocks, for example", 0);
end
return _M;
|
local softreq = function (...) local ok, lib = pcall(require, ...); if ok then return lib; else return nil; end end
local error = error;
module "hashes"
local md5 = softreq("md5");
if md5 then
if md5.digest then
local md5_digest = md5.digest;
local sha1_digest = sha1.digest;
function _M.md5(input)
return md5_digest(input);
end
function _M.sha1(input)
return sha1_digest(input);
end
elseif md5.sumhexa then
local md5_sumhexa = md5.sumhexa;
function _M.md5(input)
return md5_sumhexa(input);
end
else
error("md5 library found, but unrecognised... no hash functions will be available", 0);
end
else
error("No md5 library found. Install md5 using luarocks, for example", 0);
end
return _M;
|
Fix softreq, so it reports when no suitable MD5 library is found
|
Fix softreq, so it reports when no suitable MD5 library is found
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
829e7388c12114e634fed630af16488585e326c3
|
mods/sprint/esprint.lua
|
mods/sprint/esprint.lua
|
--[[
Sprint mod for Minetest by GunshipPenguin
To the extent possible under law, the author(s)
have dedicated all copyright and related and neighboring rights
to this software to the public domain worldwide. This software is
distributed without any warranty.
]]
local players = {}
local staminaHud = {}
minetest.register_on_joinplayer(function(player)
local playerName = player:get_player_name()
players[playerName] = {
sprinting = false,
timeOut = 0,
stamina = SPRINT_STAMINA,
epressed = false,
hud = player:hud_add({
hud_elem_type = "statbar",
position = {x=0.5,y=1},
size = {x=24, y=24},
text = "stamina.png",
number = 20,
alignment = {x=0,y=1},
offset = {x=-320, y=-186},
}
),
}
end)
minetest.register_on_leaveplayer(function(player)
local playerName = player:get_player_name()
players[playerName] = nil
end)
minetest.register_globalstep(function(dtime)
--Get the gametime
local gameTime = minetest.get_gametime()
--Loop through all connected players
for playerName,playerInfo in pairs(players) do
local player = minetest.get_player_by_name(playerName)
if not player then return end
local pos = player:getpos()
if player ~= nil then
-- From playerplus :
-- am I near a cactus?
pos.y = pos.y + 0.1
local near = minetest.find_node_near(pos, 1, "default:cactus")
if near then
pos = near
-- am I touching the cactus? if so it hurts
for _,player in ipairs(minetest.get_objects_inside_radius(pos, 1.0)) do
if player:get_hp() > 0 then
player:set_hp(player:get_hp()-1)
end
end
end
--Check if they are pressing the e key
players[playerName]["epressed"] = player:get_player_control()["aux1"]
--Stop sprinting if the player is pressing the LMB or RMB
if player:get_player_control()["LMB"] or player:get_player_control()["RMB"] then
setSprinting(playerName, false)
playerInfo["timeOut"] = 3
end
--If the player is sprinting, create particles behind him/her
if playerInfo["sprinting"] == true and gameTime % 0.1 == 0 then
local numParticles = math.random(1, 2)
local playerPos = player:getpos()
local playerNode = minetest.get_node({x=playerPos["x"], y=playerPos["y"]-1, z=playerPos["z"]})
if playerNode["name"] ~= "air" then
for i=1, numParticles, 1 do
minetest.add_particle({
pos = {x=playerPos["x"]+math.random(-1,1)*math.random()/2,y=playerPos["y"]+0.1,z=playerPos["z"]+math.random(-1,1)*math.random()/2},
vel = {x=0, y=5, z=0},
acc = {x=0, y=-13, z=0},
expirationtime = math.random(),
size = math.random()+0.5,
collisiondetection = true,
vertical = false,
texture = "default_dirt.png",
})
end
end
end
--Adjust player states
if players[playerName]["epressed"] == true and playerInfo["timeOut"] == 0 then --Stopped
setSprinting(playerName, true)
elseif players[playerName]["epressed"] == false then
setSprinting(playerName, false)
end
if playerInfo["timeOut"] > 0 then
playerInfo["timeOut"] = playerInfo["timeOut"] - dtime
if playerInfo["timeOut"] < 0 then
playerInfo["timeOut"] = 0
end
else
--Lower the player's stamina by dtime if he/she is sprinting and set his/her state to 0 if stamina is zero
if playerInfo["sprinting"] == true then
playerInfo["stamina"] = playerInfo["stamina"] - dtime
if playerInfo["stamina"] <= 0 then
playerInfo["stamina"] = 0
setSprinting(playerName, false)
playerInfo["timeOut"] = 1
minetest.sound_play("default_breathless",{object=player})
end
end
end
--Increase player's stamina if he/she is not sprinting and his/her stamina is less than SPRINT_STAMINA
if playerInfo["sprinting"] == false and playerInfo["stamina"] < SPRINT_STAMINA then
playerInfo["stamina"] = playerInfo["stamina"] + dtime
end
--Update the players's hud sprint stamina bar
local numBars = (playerInfo["stamina"]/SPRINT_STAMINA)*20
player:hud_change(playerInfo["hud"], "number", numBars)
end
end
end)
function setSprinting(playerName, sprinting) --Sets the state of a player (0=stopped/moving, 1=sprinting)
local player = minetest.get_player_by_name(playerName)
if players[playerName] then
players[playerName]["sprinting"] = sprinting
if sprinting == true then
player:set_physics_override({speed=SPRINT_SPEED,jump=SPRINT_JUMP})
elseif sprinting == false then
player:set_physics_override({speed=1.0,jump=1.0})
end
return true
end
return false
end
|
--[[
Sprint mod for Minetest by GunshipPenguin
To the extent possible under law, the author(s)
have dedicated all copyright and related and neighboring rights
to this software to the public domain worldwide. This software is
distributed without any warranty.
]]
local players = {}
local staminaHud = {}
minetest.register_on_joinplayer(function(player)
local playerName = player:get_player_name()
players[playerName] = {
sprinting = false,
timeOut = 0,
stamina = SPRINT_STAMINA,
epressed = false,
hud = player:hud_add({
hud_elem_type = "statbar",
position = {x=0.5,y=1},
size = {x=24, y=24},
text = "stamina.png",
number = 20,
alignment = {x=0,y=1},
offset = {x=-320, y=-186},
}
),
}
end)
minetest.register_on_leaveplayer(function(player)
local playerName = player:get_player_name()
players[playerName] = nil
end)
minetest.register_globalstep(function(dtime)
--Get the gametime
local gameTime = minetest.get_gametime()
--Loop through all connected players
for playerName,playerInfo in pairs(players) do
local player = minetest.get_player_by_name(playerName)
if player ~= nil then
local pos = player:getpos()
-- From playerplus :
-- am I near a cactus?
pos.y = pos.y + 0.1
local near = minetest.find_node_near(pos, 1, "default:cactus")
if near then
pos = near
-- am I touching the cactus? if so it hurts
for _,player in ipairs(minetest.get_objects_inside_radius(pos, 1.0)) do
if player:get_hp() > 0 then
player:set_hp(player:get_hp()-1)
end
end
end
--Check if they are pressing the e key
players[playerName]["epressed"] = player:get_player_control()["aux1"]
--Stop sprinting if the player is pressing the LMB or RMB
if player:get_player_control()["LMB"] or player:get_player_control()["RMB"] then
setSprinting(playerName, false)
playerInfo["timeOut"] = 3
end
--If the player is sprinting, create particles behind him/her
if playerInfo["sprinting"] == true and gameTime % 0.1 == 0 then
local numParticles = math.random(1, 2)
local playerPos = player:getpos()
local playerNode = minetest.get_node({x=playerPos["x"], y=playerPos["y"]-1, z=playerPos["z"]})
if playerNode["name"] ~= "air" then
for i=1, numParticles, 1 do
minetest.add_particle({
pos = {x=playerPos["x"]+math.random(-1,1)*math.random()/2,y=playerPos["y"]+0.1,z=playerPos["z"]+math.random(-1,1)*math.random()/2},
vel = {x=0, y=5, z=0},
acc = {x=0, y=-13, z=0},
expirationtime = math.random(),
size = math.random()+0.5,
collisiondetection = true,
vertical = false,
texture = "default_dirt.png",
})
end
end
end
--Adjust player states
if players[playerName]["epressed"] == true and playerInfo["timeOut"] == 0 then --Stopped
setSprinting(playerName, true)
elseif players[playerName]["epressed"] == false then
setSprinting(playerName, false)
end
if playerInfo["timeOut"] > 0 then
playerInfo["timeOut"] = playerInfo["timeOut"] - dtime
if playerInfo["timeOut"] < 0 then
playerInfo["timeOut"] = 0
end
else
--Lower the player's stamina by dtime if he/she is sprinting and set his/her state to 0 if stamina is zero
if playerInfo["sprinting"] == true then
playerInfo["stamina"] = playerInfo["stamina"] - dtime
if playerInfo["stamina"] <= 0 then
playerInfo["stamina"] = 0
setSprinting(playerName, false)
playerInfo["timeOut"] = 1
minetest.sound_play("default_breathless",{object=player})
end
end
end
--Increase player's stamina if he/she is not sprinting and his/her stamina is less than SPRINT_STAMINA
if playerInfo["sprinting"] == false and playerInfo["stamina"] < SPRINT_STAMINA then
playerInfo["stamina"] = playerInfo["stamina"] + dtime
end
--Update the players's hud sprint stamina bar
local numBars = (playerInfo["stamina"]/SPRINT_STAMINA)*20
player:hud_change(playerInfo["hud"], "number", numBars)
end
end
end)
function setSprinting(playerName, sprinting) --Sets the state of a player (0=stopped/moving, 1=sprinting)
local player = minetest.get_player_by_name(playerName)
if players[playerName] then
players[playerName]["sprinting"] = sprinting
if sprinting == true then
player:set_physics_override({speed=SPRINT_SPEED,jump=SPRINT_JUMP})
elseif sprinting == false then
player:set_physics_override({speed=1.0,jump=1.0})
end
return true
end
return false
end
|
remove useless condition (bug?)
|
remove useless condition (bug?)
|
Lua
|
unlicense
|
sys4-fr/server-minetestforfun,sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,crabman77/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Coethium/server-minetestforfun,crabman77/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server
|
888a86b8a191d5f2e490419b9b4e674eb1d14629
|
net/http/parser.lua
|
net/http/parser.lua
|
local tonumber = tonumber;
local assert = assert;
local url_parse = require "socket.url".parse;
local urldecode = require "util.http".urldecode;
local function preprocess_path(path)
path = urldecode((path:gsub("//+", "/")));
if path:sub(1,1) ~= "/" then
path = "/"..path;
end
local level = 0;
for component in path:gmatch("([^/]+)/") do
if component == ".." then
level = level - 1;
elseif component ~= "." then
level = level + 1;
end
if level < 0 then
return nil;
end
end
return path;
end
local httpstream = {};
function httpstream.new(success_cb, error_cb, parser_type, options_cb)
local client = true;
if not parser_type or parser_type == "server" then client = false; else assert(parser_type == "client", "Invalid parser type"); end
local buf = "";
local chunked, chunk_size, chunk_start;
local state = nil;
local packet;
local len;
local have_body;
local error;
return {
feed = function(self, data)
if error then return nil, "parse has failed"; end
if not data then -- EOF
if state and client and not len then -- reading client body until EOF
packet.body = buf;
success_cb(packet);
elseif buf ~= "" then -- unexpected EOF
error = true; return error_cb();
end
return;
end
buf = buf..data;
while #buf > 0 do
if state == nil then -- read request
local index = buf:find("\r\n\r\n", nil, true);
if not index then return; end -- not enough data
local method, path, httpversion, status_code, reason_phrase;
local first_line;
local headers = {};
for line in buf:sub(1,index+1):gmatch("([^\r\n]+)\r\n") do -- parse request
if first_line then
local key, val = line:match("^([^%s:]+): *(.*)$");
if not key then error = true; return error_cb("invalid-header-line"); end -- TODO handle multi-line and invalid headers
key = key:lower();
headers[key] = headers[key] and headers[key]..","..val or val;
else
first_line = line;
if client then
httpversion, status_code, reason_phrase = line:match("^HTTP/(1%.[01]) (%d%d%d) (.*)$");
status_code = tonumber(status_code);
if not status_code then error = true; return error_cb("invalid-status-line"); end
have_body = not
( (options_cb and options_cb().method == "HEAD")
or (status_code == 204 or status_code == 304 or status_code == 301)
or (status_code >= 100 and status_code < 200) );
else
method, path, httpversion = line:match("^(%w+) (%S+) HTTP/(1%.[01])$");
if not method then error = true; return error_cb("invalid-status-line"); end
end
end
end
if not first_line then error = true; return error_cb("invalid-status-line"); end
chunked = have_body and headers["transfer-encoding"] == "chunked";
len = tonumber(headers["content-length"]); -- TODO check for invalid len
if client then
-- FIXME handle '100 Continue' response (by skipping it)
if not have_body then len = 0; end
packet = {
code = status_code;
httpversion = httpversion;
headers = headers;
body = have_body and "" or nil;
-- COMPAT the properties below are deprecated
responseversion = httpversion;
responseheaders = headers;
};
else
local parsed_url;
if path:byte() == 47 then -- starts with /
local _path, _query = path:match("([^?]*).?(.*)");
if _query == "" then _query = nil; end
parsed_url = { path = _path, query = _query };
else
parsed_url = url_parse(path);
if not(parsed_url and parsed_url.path) then error = true; return error_cb("invalid-url"); end
end
path = preprocess_path(parsed_url.path);
headers.host = parsed_url.host or headers.host;
len = len or 0;
packet = {
method = method;
url = parsed_url;
path = path;
httpversion = httpversion;
headers = headers;
body = nil;
};
end
buf = buf:sub(index + 4);
state = true;
end
if state then -- read body
if client then
if chunked then
if not buf:find("\r\n", nil, true) then
return;
end -- not enough data
if not chunk_size then
chunk_size, chunk_start = buf:match("^(%x+)[^\r\n]*\r\n()");
chunk_size = chunk_size and tonumber(chunk_size, 16);
if not chunk_size then error = true; return error_cb("invalid-chunk-size"); end
end
if chunk_size == 0 and buf:find("\r\n\r\n", chunk_start-2, true) then
state, chunk_size = nil, nil;
buf = buf:gsub("^.-\r\n\r\n", ""); -- This ensure extensions and trailers are stripped
success_cb(packet);
elseif #buf - chunk_start - 2 >= chunk_size then -- we have a chunk
packet.body = packet.body..buf:sub(chunk_start, chunk_start + (chunk_size-1));
buf = buf:sub(chunk_start + chunk_size + 2);
chunk_size, chunk_start = nil, nil;
else -- Partial chunk remaining
break;
end
elseif len and #buf >= len then
if packet.code == 101 then
packet.body, buf = buf, ""
else
packet.body, buf = buf:sub(1, len), buf:sub(len + 1);
end
state = nil; success_cb(packet);
else
break;
end
elseif #buf >= len then
packet.body, buf = buf:sub(1, len), buf:sub(len + 1);
state = nil; success_cb(packet);
else
break;
end
end
end
end;
};
end
return httpstream;
|
local tonumber = tonumber;
local assert = assert;
local url_parse = require "socket.url".parse;
local urldecode = require "util.http".urldecode;
local function preprocess_path(path)
path = urldecode((path:gsub("//+", "/")));
if path:sub(1,1) ~= "/" then
path = "/"..path;
end
local level = 0;
for component in path:gmatch("([^/]+)/") do
if component == ".." then
level = level - 1;
elseif component ~= "." then
level = level + 1;
end
if level < 0 then
return nil;
end
end
return path;
end
local httpstream = {};
function httpstream.new(success_cb, error_cb, parser_type, options_cb)
local client = true;
if not parser_type or parser_type == "server" then client = false; else assert(parser_type == "client", "Invalid parser type"); end
local buf = "";
local chunked, chunk_size, chunk_start;
local state = nil;
local packet;
local len;
local have_body;
local error;
return {
feed = function(self, data)
if error then return nil, "parse has failed"; end
if not data then -- EOF
if state and client and not len then -- reading client body until EOF
packet.body = buf;
success_cb(packet);
elseif buf ~= "" then -- unexpected EOF
error = true; return error_cb();
end
return;
end
buf = buf..data;
while #buf > 0 do
if state == nil then -- read request
local index = buf:find("\r\n\r\n", nil, true);
if not index then return; end -- not enough data
local method, path, httpversion, status_code, reason_phrase;
local first_line;
local headers = {};
for line in buf:sub(1,index+1):gmatch("([^\r\n]+)\r\n") do -- parse request
if first_line then
local key, val = line:match("^([^%s:]+): *(.*)$");
if not key then error = true; return error_cb("invalid-header-line"); end -- TODO handle multi-line and invalid headers
key = key:lower();
headers[key] = headers[key] and headers[key]..","..val or val;
else
first_line = line;
if client then
httpversion, status_code, reason_phrase = line:match("^HTTP/(1%.[01]) (%d%d%d) (.*)$");
status_code = tonumber(status_code);
if not status_code then error = true; return error_cb("invalid-status-line"); end
have_body = not
( (options_cb and options_cb().method == "HEAD")
or (status_code == 204 or status_code == 304 or status_code == 301)
or (status_code >= 100 and status_code < 200) );
else
method, path, httpversion = line:match("^(%w+) (%S+) HTTP/(1%.[01])$");
if not method then error = true; return error_cb("invalid-status-line"); end
end
end
end
if not first_line then error = true; return error_cb("invalid-status-line"); end
chunked = have_body and headers["transfer-encoding"] == "chunked";
len = tonumber(headers["content-length"]); -- TODO check for invalid len
if client then
-- FIXME handle '100 Continue' response (by skipping it)
if not have_body then len = 0; end
packet = {
code = status_code;
httpversion = httpversion;
headers = headers;
body = have_body and "" or nil;
-- COMPAT the properties below are deprecated
responseversion = httpversion;
responseheaders = headers;
};
else
local parsed_url;
if path:byte() == 47 then -- starts with /
local _path, _query = path:match("([^?]*).?(.*)");
if _query == "" then _query = nil; end
parsed_url = { path = _path, query = _query };
else
parsed_url = url_parse(path);
if not(parsed_url and parsed_url.path) then error = true; return error_cb("invalid-url"); end
end
path = preprocess_path(parsed_url.path);
headers.host = parsed_url.host or headers.host;
len = len or 0;
packet = {
method = method;
url = parsed_url;
path = path;
httpversion = httpversion;
headers = headers;
body = nil;
};
end
buf = buf:sub(index + 4);
state = true;
end
if state then -- read body
if client then
if chunked then
if not buf:find("\r\n", nil, true) then
return;
end -- not enough data
if not chunk_size then
chunk_size, chunk_start = buf:match("^(%x+)[^\r\n]*\r\n()");
chunk_size = chunk_size and tonumber(chunk_size, 16);
if not chunk_size then error = true; return error_cb("invalid-chunk-size"); end
end
if chunk_size == 0 and buf:find("\r\n\r\n", chunk_start-2, true) then
state, chunk_size = nil, nil;
buf = buf:gsub("^.-\r\n\r\n", ""); -- This ensure extensions and trailers are stripped
success_cb(packet);
elseif #buf - chunk_start - 2 >= chunk_size then -- we have a chunk
packet.body = packet.body..buf:sub(chunk_start, chunk_start + (chunk_size-1));
buf = buf:sub(chunk_start + chunk_size + 2);
chunk_size, chunk_start = nil, nil;
else -- Partial chunk remaining
break;
end
elseif len and #buf >= len then
if packet.code == 101 then
packet.body, buf = buf, "";
else
packet.body, buf = buf:sub(1, len), buf:sub(len + 1);
end
state = nil; success_cb(packet);
else
break;
end
elseif #buf >= len then
packet.body, buf = buf:sub(1, len), buf:sub(len + 1);
state = nil; success_cb(packet);
else
break;
end
end
end
end;
};
end
return httpstream;
|
net.http.parser: Fix whitespace/indentation
|
net.http.parser: Fix whitespace/indentation
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
925991715f2472d66ce73f5e636d72cfa40d9db2
|
lua_modules/ds18b20/ds18b20.lua
|
lua_modules/ds18b20/ds18b20.lua
|
--------------------------------------------------------------------------------
-- DS18B20 one wire module for NODEMCU
-- by @voborsky, @devsaurus
-- encoder module is needed only for debug output; lines can be removed if no
-- debug output is needed and/or encoder module is missing
--
-- by default the module is for integer version, comment integer version and
-- uncomment float version part for float version
--------------------------------------------------------------------------------
return({
pin=3,
sens={},
temp={},
conversion = function(self)
local pin = self.pin
for i,s in ipairs(self.sens) do
if s.status == 0 then
print("starting conversion:", encoder.toHex(s.addr), s.parasite == 1 and "parasite" or " ")
ow.reset(pin)
ow.select(pin, s.addr) -- select the sensor
ow.write(pin, 0x44, 1) -- and start conversion
s.status = 1
if s.parasite == 1 then break end -- parasite sensor blocks bus during conversion
end
end
tmr.alarm(tmr.create(), 750, tmr.ALARM_SINGLE, function() self:readout() end)
end,
readTemp = function(self, cb, lpin)
if lpin then self.pin = lpin end
local pin = self.pin
self.cb = cb
self.temp={}
ow.setup(pin)
self.sens={}
ow.reset_search(pin)
-- ow.target_search(pin,0x28)
-- search the first device
local addr = ow.search(pin)
-- and loop through all devices
while addr do
-- search next device
local crc=ow.crc8(string.sub(addr,1,7))
if (crc==addr:byte(8)) and ((addr:byte(1)==0x10) or (addr:byte(1)==0x28)) then
ow.reset(pin)
ow.select(pin, addr) -- select the found sensor
ow.write(pin, 0xB4, 1) -- Read Power Supply [B4h]
local parasite = (ow.read(pin)==0 and 1 or 0)
table.insert(self.sens,{addr=addr, parasite=parasite, status=0})
print("contact: ", encoder.toHex(addr), parasite == 1 and "parasite" or " ")
end
addr = ow.search(pin)
tmr.wdclr()
end
-- place powered sensors first
table.sort(self.sens, function(a,b) return a.parasite<b.parasite end)
node.task.post(node.task.MEDIUM_PRIORITY, function() self:conversion() end)
end,
readout=function(self)
local pin = self.pin
local next = false
if not self.sens then return 0 end
for i,s in ipairs(self.sens) do
-- print(encoder.toHex(s.addr), s.status)
if s.status == 1 then
ow.reset(pin)
ow.select(pin, s.addr) -- select the sensor
ow.write(pin, 0xBE, 0) -- READ_SCRATCHPAD
data = ow.read_bytes(pin, 9)
local t=(data:byte(1)+data:byte(2)*256)
if (t > 0x7fff) then t = t - 0x10000 end
if (s.addr:byte(1) == 0x28) then
t = t * 625 -- DS18B20, 4 fractional bits
else
t = t * 5000 -- DS18S20, 1 fractional bit
end
-- integer version
local sgn = t<0 and -1 or 1
local tA = sgn*t
local tH=tA/10000
local tL=(tA%10000)/1000 + ((tA%1000)/100 >= 5 and 1 or 0)
if tH and (tH~=85) then
self.temp[s.addr]=(sgn<0 and "-" or "")..tH.."."..tL
print(encoder.toHex(s.addr),(sgn<0 and "-" or "")..tH.."."..tL)
s.status = 2
end
-- end integer version
-- -- float version
-- if t and (math.floor(t/10000)~=85) then
-- self.temp[s.addr]=t
-- print(encoder.toHex(s.addr), t)
-- s.status = 2
-- end
-- -- end float version
end
next = next or s.status == 0
end
if next then
node.task.post(node.task.MEDIUM_PRIORITY, function() self:conversion() end)
else
self.sens = nil
if self.cb then
node.task.post(node.task.MEDIUM_PRIORITY, function() self.cb(self.temp) end)
end
end
end
})
|
--------------------------------------------------------------------------------
-- DS18B20 one wire module for NODEMCU
-- by @voborsky, @devsaurus
-- encoder module is needed only for debug output; lines can be removed if no
-- debug output is needed and/or encoder module is missing
--
-- by default the module is for integer version, comment integer version and
-- uncomment float version part for float version
--------------------------------------------------------------------------------
return({
pin=3,
sens={},
temp={},
conversion = function(self)
local pin = self.pin
for i,s in ipairs(self.sens) do
if s.status == 0 then
print("starting conversion:", encoder.toHex(s.addr), s.parasite == 1 and "parasite" or " ")
ow.reset(pin)
ow.select(pin, s.addr) -- select the sensor
ow.write(pin, 0x44, 1) -- and start conversion
s.status = 1
if s.parasite == 1 then break end -- parasite sensor blocks bus during conversion
end
end
tmr.create():alarm(750, tmr.ALARM_SINGLE, function() self:readout() end)
end,
readTemp = function(self, cb, lpin)
if lpin then self.pin = lpin end
local pin = self.pin
self.cb = cb
self.temp={}
ow.setup(pin)
self.sens={}
ow.reset_search(pin)
-- ow.target_search(pin,0x28)
-- search the first device
local addr = ow.search(pin)
-- and loop through all devices
while addr do
-- search next device
local crc=ow.crc8(string.sub(addr,1,7))
if (crc==addr:byte(8)) and ((addr:byte(1)==0x10) or (addr:byte(1)==0x28)) then
ow.reset(pin)
ow.select(pin, addr) -- select the found sensor
ow.write(pin, 0xB4, 1) -- Read Power Supply [B4h]
local parasite = (ow.read(pin)==0 and 1 or 0)
table.insert(self.sens,{addr=addr, parasite=parasite, status=0})
print("contact: ", encoder.toHex(addr), parasite == 1 and "parasite" or " ")
end
addr = ow.search(pin)
tmr.wdclr()
end
-- place powered sensors first
table.sort(self.sens, function(a,b) return a.parasite<b.parasite end)
node.task.post(node.task.MEDIUM_PRIORITY, function() self:conversion() end)
end,
readout=function(self)
local pin = self.pin
local next = false
if not self.sens then return 0 end
for i,s in ipairs(self.sens) do
-- print(encoder.toHex(s.addr), s.status)
if s.status == 1 then
ow.reset(pin)
ow.select(pin, s.addr) -- select the sensor
ow.write(pin, 0xBE, 0) -- READ_SCRATCHPAD
data = ow.read_bytes(pin, 9)
local t=(data:byte(1)+data:byte(2)*256)
if (t > 0x7fff) then t = t - 0x10000 end
if (s.addr:byte(1) == 0x28) then
t = t * 625 -- DS18B20, 4 fractional bits
else
t = t * 5000 -- DS18S20, 1 fractional bit
end
if 1/2 == 0 then
-- integer version
local sgn = t<0 and -1 or 1
local tA = sgn*t
local tH=tA/10000
local tL=(tA%10000)/1000 + ((tA%1000)/100 >= 5 and 1 or 0)
if tH and (tH~=85) then
self.temp[s.addr]=(sgn<0 and "-" or "")..tH.."."..tL
print(encoder.toHex(s.addr),(sgn<0 and "-" or "")..tH.."."..tL)
s.status = 2
end
-- end integer version
else
-- float version
if t and (math.floor(t/10000)~=85) then
self.temp[s.addr]=t/10000
print(encoder.toHex(s.addr), t)
s.status = 2
end
-- end float version
end
end
next = next or s.status == 0
end
if next then
node.task.post(node.task.MEDIUM_PRIORITY, function() self:conversion() end)
else
self.sens = nil
if self.cb then
node.task.post(node.task.MEDIUM_PRIORITY, function() self.cb(self.temp) end)
end
end
end
})
|
Fix float version, auto-detect int/float, OO tmr (#1866)
|
Fix float version, auto-detect int/float, OO tmr (#1866)
|
Lua
|
mit
|
FelixPe/nodemcu-firmware,HEYAHONG/nodemcu-firmware,djphoenix/nodemcu-firmware,FrankX0/nodemcu-firmware,nwf/nodemcu-firmware,luizfeliperj/nodemcu-firmware,oyooyo/nodemcu-firmware,eku/nodemcu-firmware,vsky279/nodemcu-firmware,devsaurus/nodemcu-firmware,HEYAHONG/nodemcu-firmware,vsky279/nodemcu-firmware,marcelstoer/nodemcu-firmware,TerryE/nodemcu-firmware,luizfeliperj/nodemcu-firmware,HEYAHONG/nodemcu-firmware,fetchbot/nodemcu-firmware,fetchbot/nodemcu-firmware,marcelstoer/nodemcu-firmware,TerryE/nodemcu-firmware,nwf/nodemcu-firmware,nwf/nodemcu-firmware,nodemcu/nodemcu-firmware,nodemcu/nodemcu-firmware,fetchbot/nodemcu-firmware,vsky279/nodemcu-firmware,TerryE/nodemcu-firmware,TerryE/nodemcu-firmware,nodemcu/nodemcu-firmware,FelixPe/nodemcu-firmware,devsaurus/nodemcu-firmware,eku/nodemcu-firmware,nwf/nodemcu-firmware,FrankX0/nodemcu-firmware,FelixPe/nodemcu-firmware,FelixPe/nodemcu-firmware,fetchbot/nodemcu-firmware,FrankX0/nodemcu-firmware,devsaurus/nodemcu-firmware,FelixPe/nodemcu-firmware,devsaurus/nodemcu-firmware,oyooyo/nodemcu-firmware,FrankX0/nodemcu-firmware,vsky279/nodemcu-firmware,eku/nodemcu-firmware,nodemcu/nodemcu-firmware,luizfeliperj/nodemcu-firmware,nodemcu/nodemcu-firmware,TerryE/nodemcu-firmware,marcelstoer/nodemcu-firmware,vsky279/nodemcu-firmware,oyooyo/nodemcu-firmware,djphoenix/nodemcu-firmware,oyooyo/nodemcu-firmware,marcelstoer/nodemcu-firmware,marcelstoer/nodemcu-firmware,devsaurus/nodemcu-firmware,eku/nodemcu-firmware,djphoenix/nodemcu-firmware,djphoenix/nodemcu-firmware,luizfeliperj/nodemcu-firmware,HEYAHONG/nodemcu-firmware,nwf/nodemcu-firmware,FrankX0/nodemcu-firmware,HEYAHONG/nodemcu-firmware
|
4d27c5b7a95718db5e1892574b2ec2ab3cbbc4a7
|
OvalePassiveAura.lua
|
OvalePassiveAura.lua
|
--[[--------------------------------------------------------------------
Ovale Spell Priority
Copyright (C) 2014 Johnny C. Lam
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License in the LICENSE
file accompanying this program.
--]]-------------------------------------------------------------------
local _, Ovale = ...
local OvalePassiveAura = Ovale:NewModule("OvalePassiveAura", "AceEvent-3.0")
Ovale.OvalePassiveAura = OvalePassiveAura
--[[
This module manages passive, usually hidden, auras from various class and item effects.
--]]
--<private-static-properties>
-- Forward declarations for module dependencies.
local OvaleAura = nil
local OvaleEquipement = nil
local OvalePaperDoll = nil
local exp = math.exp
local log = math.log
local API_GetTime = GetTime
local API_UnitClass = UnitClass
local API_UnitGUID = UnitGUID
local INVSLOT_TRINKET1 = INVSLOT_TRINKET1
local INVSLOT_TRINKET2 = INVSLOT_TRINKET2
-- Player's class.
local _, self_class = API_UnitClass("player")
-- Player's GUID.
local self_guid = nil
-- Readiness (cooldown reduction) passive aura.
local READINESS_AGILITY_DPS = 146019
local READINESS_STRENGTH_DPS = 145955
local READINESS_TANK = 146025
local READINESS_TRINKET = {
[102292] = READINESS_AGILITY_DPS, -- Assurance of Consequence
[104476] = READINESS_AGILITY_DPS, -- Assurance of Consequence (Heroic)
[104725] = READINESS_AGILITY_DPS, -- Assurance of Consequence (Flexible)
[104974] = READINESS_AGILITY_DPS, -- Assurance of Consequence (Raid Finder)
[105223] = READINESS_AGILITY_DPS, -- Assurance of Consequence (Warforged)
[105472] = READINESS_AGILITY_DPS, -- Assurance of Consequence (Heroic Warforged)
[102298] = READINESS_STRENGTH_DPS, -- Evil Eye of Galakras
[104495] = READINESS_STRENGTH_DPS, -- Evil Eye of Galakras (Heroic)
[104744] = READINESS_STRENGTH_DPS, -- Evil Eye of Galakras (Flexible)
[104993] = READINESS_STRENGTH_DPS, -- Evil Eye of Galakras (Raid Finder)
[105242] = READINESS_STRENGTH_DPS, -- Evil Eye of Galakras (Warforged)
[105491] = READINESS_STRENGTH_DPS, -- Evil Eye of Galakras (Heroic Warforged)
[102306] = READINESS_TANK, -- Vial of Living Corruption
[104572] = READINESS_TANK, -- Vial of Living Corruption (Heroic)
[104821] = READINESS_TANK, -- Vial of Living Corruption (Flexible)
[105070] = READINESS_TANK, -- Vial of Living Corruption (Raid Finder)
[105319] = READINESS_TANK, -- Vial of Living Corruption (Warforged)
[105568] = READINESS_TANK, -- Vial of Living Corruption (Heroic Warforged)
}
local READINESS_ROLE = {
DEATHKNIGHT = { blood = READINESS_TANK, frost = READINESS_STRENGTH_DPS, unholy = READINESS_STRENGTH_DPS },
DRUID = { feral = READINESS_AGILITY_DPS, guardian = READINESS_TANK },
HUNTER = { beast_mastery = READINESS_AGILITY_DPS, marksmanship = READINESS_AGILITY_DPS, survival = READINESS_AGILITY_DPS },
MONK = { brewmaster = READINESS_TANK, windwalker = READINESS_AGILITY_DPS },
PALADIN = { protection = READINESS_TANK, retribution = READINESS_STRENGTH_DPS },
ROGUE = { assassination = READINESS_AGILITY_DPS, combat = READINESS_AGILITY_DPS, subtlety = READINESS_AGILITY_DPS },
SHAMAN = { enhancement = READINESS_AGILITY_DPS },
WARRIOR = { arms = READINESS_STRENGTH_DPS, fury = READINESS_STRENGTH_DPS, protection = READINESS_TANK },
}
--</private-static-properties>
--<public-static-methods>
function OvalePassiveAura:OnInitialize()
-- Resolve module dependencies.
OvaleAura = Ovale.OvaleAura
OvaleEquipement = Ovale.OvaleEquipement
OvalePaperDoll = Ovale.OvalePaperDoll
end
function OvalePassiveAura:OnEnable()
self_guid = API_UnitGUID("player")
self:RegisterMessage("Ovale_EquipmentChanged")
self:RegisterMessage("Ovale_SpecializationChanged")
end
function OvalePassiveAura:OnDisable()
self:UnregisterMessage("Ovale_EquipmentChanged")
self:UnregisterMessage("Ovale_SpecializationChanged")
end
function OvalePassiveAura:Ovale_EquipmentChanged()
self:UpdateReadiness()
end
function OvalePassiveAura:Ovale_SpecializationChanged()
self:UpdateReadiness()
end
function OvalePassiveAura:UpdateReadiness()
local specialization = OvalePaperDoll:GetSpecialization()
local spellId = READINESS_ROLE[self_class] and READINESS_ROLE[self_class][specialization]
if spellId then
-- Check a Readiness trinket is equipped and for the correct role.
local slot = INVSLOT_TRINKET1
local trinket = OvaleEquipement:GetEquippedItem(slot)
local readiness = trinket and READINESS_TRINKET[trinket]
if not readiness then
slot = INVSLOT_TRINKET2
trinket = OvaleEquipement:GetEquippedItem(slot)
readiness = trinket and READINESS_TRINKET[trinket]
end
local now = API_GetTime()
if readiness == spellId then
local name = "Readiness"
local start = now
local duration = math.huge
local ending = math.huge
local stacks = 1
-- Use a derived formula that very closely approximates the true cooldown recovery rate increase based on item level.
local ilevel = OvaleEquipement:GetEquippedItemLevel(slot)
local cdRecoveryRateIncrease = exp((ilevel - 528) * 0.009317881032 + 3.434954478)
local value = 1 / (1 + cdRecoveryRateIncrease / 100)
OvaleAura:GainedAuraOnGUID(self_guid, start, spellId, self_guid, "HELPFUL", nil, nil, stacks, nil, duration, ending, nil, name, value, nil, nil)
else
OvaleAura:LostAuraOnGUID(self_guid, now, spellId, self_guid)
end
end
end
--</public-static-methods>
|
--[[--------------------------------------------------------------------
Ovale Spell Priority
Copyright (C) 2014 Johnny C. Lam
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License in the LICENSE
file accompanying this program.
--]]-------------------------------------------------------------------
local _, Ovale = ...
local OvalePassiveAura = Ovale:NewModule("OvalePassiveAura", "AceEvent-3.0")
Ovale.OvalePassiveAura = OvalePassiveAura
--[[
This module manages passive, usually hidden, auras from various class and item effects.
--]]
--<private-static-properties>
-- Forward declarations for module dependencies.
local OvaleAura = nil
local OvaleEquipement = nil
local OvalePaperDoll = nil
local exp = math.exp
local log = math.log
local API_GetTime = GetTime
local API_UnitClass = UnitClass
local API_UnitGUID = UnitGUID
local INVSLOT_TRINKET1 = INVSLOT_TRINKET1
local INVSLOT_TRINKET2 = INVSLOT_TRINKET2
-- Player's class.
local _, self_class = API_UnitClass("player")
-- Player's GUID.
local self_guid = nil
-- Readiness (cooldown reduction) passive aura.
local READINESS_AGILITY_DPS = 146019
local READINESS_STRENGTH_DPS = 145955
local READINESS_TANK = 146025
local READINESS_TRINKET = {
[102292] = READINESS_AGILITY_DPS, -- Assurance of Consequence
[104476] = READINESS_AGILITY_DPS, -- Assurance of Consequence (Heroic)
[104725] = READINESS_AGILITY_DPS, -- Assurance of Consequence (Flexible)
[104974] = READINESS_AGILITY_DPS, -- Assurance of Consequence (Raid Finder)
[105223] = READINESS_AGILITY_DPS, -- Assurance of Consequence (Warforged)
[105472] = READINESS_AGILITY_DPS, -- Assurance of Consequence (Heroic Warforged)
[102298] = READINESS_STRENGTH_DPS, -- Evil Eye of Galakras
[104495] = READINESS_STRENGTH_DPS, -- Evil Eye of Galakras (Heroic)
[104744] = READINESS_STRENGTH_DPS, -- Evil Eye of Galakras (Flexible)
[104993] = READINESS_STRENGTH_DPS, -- Evil Eye of Galakras (Raid Finder)
[105242] = READINESS_STRENGTH_DPS, -- Evil Eye of Galakras (Warforged)
[105491] = READINESS_STRENGTH_DPS, -- Evil Eye of Galakras (Heroic Warforged)
[102306] = READINESS_TANK, -- Vial of Living Corruption
[104572] = READINESS_TANK, -- Vial of Living Corruption (Heroic)
[104821] = READINESS_TANK, -- Vial of Living Corruption (Flexible)
[105070] = READINESS_TANK, -- Vial of Living Corruption (Raid Finder)
[105319] = READINESS_TANK, -- Vial of Living Corruption (Warforged)
[105568] = READINESS_TANK, -- Vial of Living Corruption (Heroic Warforged)
}
local READINESS_ROLE = {
DEATHKNIGHT = { blood = READINESS_TANK, frost = READINESS_STRENGTH_DPS, unholy = READINESS_STRENGTH_DPS },
DRUID = { feral = READINESS_AGILITY_DPS, guardian = READINESS_TANK },
HUNTER = { beast_mastery = READINESS_AGILITY_DPS, marksmanship = READINESS_AGILITY_DPS, survival = READINESS_AGILITY_DPS },
MONK = { brewmaster = READINESS_TANK, windwalker = READINESS_AGILITY_DPS },
PALADIN = { protection = READINESS_TANK, retribution = READINESS_STRENGTH_DPS },
ROGUE = { assassination = READINESS_AGILITY_DPS, combat = READINESS_AGILITY_DPS, subtlety = READINESS_AGILITY_DPS },
SHAMAN = { enhancement = READINESS_AGILITY_DPS },
WARRIOR = { arms = READINESS_STRENGTH_DPS, fury = READINESS_STRENGTH_DPS, protection = READINESS_TANK },
}
--</private-static-properties>
--<public-static-methods>
function OvalePassiveAura:OnInitialize()
-- Resolve module dependencies.
OvaleAura = Ovale.OvaleAura
OvaleEquipement = Ovale.OvaleEquipement
OvalePaperDoll = Ovale.OvalePaperDoll
end
function OvalePassiveAura:OnEnable()
self_guid = API_UnitGUID("player")
self:RegisterMessage("Ovale_EquipmentChanged")
self:RegisterMessage("Ovale_SpecializationChanged")
end
function OvalePassiveAura:OnDisable()
self:UnregisterMessage("Ovale_EquipmentChanged")
self:UnregisterMessage("Ovale_SpecializationChanged")
end
function OvalePassiveAura:Ovale_EquipmentChanged()
self:UpdateReadiness()
end
function OvalePassiveAura:Ovale_SpecializationChanged()
self:UpdateReadiness()
end
function OvalePassiveAura:UpdateReadiness()
local specialization = OvalePaperDoll:GetSpecialization()
local spellId = READINESS_ROLE[self_class] and READINESS_ROLE[self_class][specialization]
if spellId then
-- Check a Readiness trinket is equipped and for the correct role.
local slot = INVSLOT_TRINKET1
local trinket = OvaleEquipement:GetEquippedItem(slot)
local readiness = trinket and READINESS_TRINKET[trinket]
if not readiness then
slot = INVSLOT_TRINKET2
trinket = OvaleEquipement:GetEquippedItem(slot)
readiness = trinket and READINESS_TRINKET[trinket]
end
local now = API_GetTime()
if readiness == spellId then
local name = "Readiness"
local start = now
local duration = math.huge
local ending = math.huge
local stacks = 1
-- Use a derived formula that very closely approximates the true cooldown recovery rate increase based on item level.
local ilevel = OvaleEquipement:GetEquippedItemLevel(slot)
local cdRecoveryRateIncrease = exp((ilevel - 528) * 0.009317881032 + 3.434954478)
if readiness == READINESS_TANK then
-- The cooldown recovery rate of the tank trinket is half the value of the same item-level DPS trinket.
cdRecoveryRateIncrease = cdRecoveryRateIncrease / 2
end
local value = 1 / (1 + cdRecoveryRateIncrease / 100)
OvaleAura:GainedAuraOnGUID(self_guid, start, spellId, self_guid, "HELPFUL", nil, nil, stacks, nil, duration, ending, nil, name, value, nil, nil)
else
OvaleAura:LostAuraOnGUID(self_guid, now, spellId, self_guid)
end
end
end
--</public-static-methods>
|
Fix the cooldown recovery rate for Vial of Living Corruption.
|
Fix the cooldown recovery rate for Vial of Living Corruption.
git-svn-id: b2bb544abab4b09d60f88077ac82407cb244c9c9@1488 d5049fe3-3747-40f7-a4b5-f36d6801af5f
|
Lua
|
mit
|
eXhausted/Ovale,ultijlam/ovale,eXhausted/Ovale,Xeltor/ovale,ultijlam/ovale,ultijlam/ovale,eXhausted/Ovale
|
6a471a219912c1bc7a3daccebe0d6e81e2eac684
|
Modules/Shared/Character/HumanoidTeleportUtils.lua
|
Modules/Shared/Character/HumanoidTeleportUtils.lua
|
--- Utility for teleporting humanoids
-- @module HumanoidTeleportUtils
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local Raycaster = require("Raycaster")
local HumanoidTeleportUtils = {}
local REQUIRED_SPACE = 7
local SEARCH_UP_TO = 40
-- @param[opt=nil] raycaster Optional raycaster
function HumanoidTeleportUtils.identifySafePosition(position, raycaster)
assert(typeof(position) == "Vector3")
if not raycaster then
raycaster = Raycaster.new()
raycaster.MaxCasts = 10
raycaster.Filter = function(hitData)
if not hitData.Part.CanCollide then
return false
end
end
end
for i=1, SEARCH_UP_TO, 2 do
local origin = position + Vector3.new(0, i, 0)
local direction = Vector3.new(0, REQUIRED_SPACE, 0)
local hitData = raycaster:FindPartOnRay(Ray.new(origin, direction))
if not hitData then
local secondHit = raycaster:FindPartOnRay(Ray.new(origin+direction - Vector3.new(0, 1, 0), -direction))
-- try to identify flat surface
if secondHit then
return true, secondHit.Position
end
return true, origin
end
end
return false, position + Vector3.new(0, SEARCH_UP_TO, 0)
end
function HumanoidTeleportUtils.teleportRootPart(humanoid, rootPart, position)
-- Calculate additional offset for teleportation
local offset = rootPart.Size.Y/2 + humanoid.HipHeight
rootPart.CFrame = rootPart.CFrame - rootPart.Position + position + Vector3.new(0, offset, 0)
end
return HumanoidTeleportUtils
|
--- Utility for teleporting humanoids
-- @module HumanoidTeleportUtils
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local Raycaster = require("Raycaster")
local HumanoidTeleportUtils = {}
local REQUIRED_SPACE = 7
local SEARCH_UP_TO = 40
-- @param[opt=nil] raycaster Optional raycaster
function HumanoidTeleportUtils.identifySafePosition(position, raycaster)
assert(typeof(position) == "Vector3")
if not raycaster then
raycaster = Raycaster.new()
raycaster.MaxCasts = 10
raycaster.Filter = function(hitData)
return not hitData.Part.CanCollide
end
end
for i=1, SEARCH_UP_TO, 2 do
local origin = position + Vector3.new(0, i, 0)
local direction = Vector3.new(0, REQUIRED_SPACE, 0)
local hitData = raycaster:FindPartOnRay(Ray.new(origin, direction))
if not hitData then
local secondHit = raycaster:FindPartOnRay(Ray.new(origin+direction - Vector3.new(0, 1, 0), -direction))
-- try to identify flat surface
if secondHit then
return true, secondHit.Position
end
return true, origin
end
end
return false, position + Vector3.new(0, SEARCH_UP_TO, 0)
end
function HumanoidTeleportUtils.teleportRootPart(humanoid, rootPart, position)
-- Calculate additional offset for teleportation
local offset = rootPart.Size.Y/2 + humanoid.HipHeight
rootPart.CFrame = rootPart.CFrame - rootPart.Position + position + Vector3.new(0, offset, 0)
end
return HumanoidTeleportUtils
|
Fix teleport predicate filter
|
Fix teleport predicate filter
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
1e1043b29ca48a0cc181bac3a5e60ea982f3640a
|
nyagos.d/suffix.lua
|
nyagos.d/suffix.lua
|
nyagos.suffixes={}
local function _suffix(suffix,cmdline)
local suffix=string.lower(suffix)
if string.sub(suffix,1,1)=='.' then
suffix = string.sub(suffix,2)
end
if not nyagos.suffixes[suffix] then
local orgpathext = nyagos.getenv("PATHEXT")
local newext="."..suffix
if not string.find(";"..orgpathext..";",";"..newext..";",1,true) then
nyagos.setenv("PATHEXT",orgpathext..";"..newext)
end
end
nyagos.suffixes[suffix]=cmdline
end
suffix = setmetatable({},{
__call = function(t,k,v) _suffix(k,v) return end,
__newindex = function(t,k,v) _suffix(k,v) return end,
__index = function(t,k) return nyagos.suffixes[k] end
})
local org_filter=nyagos.argsfilter
nyagos.argsfilter = function(args)
if org_filter then
local args_ = org_filter(args)
if args_ then
args = args_
end
end
local path=nyagos.which(args[0])
if not path then
return
end
local m = string.match(path,"%.(%w+)$")
if not m then
return
end
local cmdline = nyagos.suffixes[ string.lower(m) ]
if not cmdline then
return
end
local newargs={}
if type(cmdline) == 'table' then
for i=1,#cmdline do
newargs[i-1]=cmdline[i]
end
elseif type(cmdline) == 'string' then
newargs[0] = cmdline
end
newargs[#newargs+1] = path
for i=1,#args do
newargs[#newargs+1] = args[i]
end
return newargs
end
nyagos.alias.suffix = function(args)
if #args < 2 then
print "Usage: suffix SUFFIX COMMAND"
else
local cmdline={}
for i=2,#args do
cmdline[#cmdline+1]=args[i]
end
suffix(args[1],cmdline)
end
end
suffix.pl="perl"
suffix.py="ipy"
suffix.rb="ruby"
suffix.lua="lua"
suffix.awk={"awk","-f"}
suffix.js={"cscript","//nologo"}
suffix.vbs={"cscript","//nologo"}
suffix.ps1={"powershell","-file"}
|
nyagos.suffixes={}
local function _suffix(suffix,cmdline)
local suffix=string.lower(suffix)
if string.sub(suffix,1,1)=='.' then
suffix = string.sub(suffix,2)
end
if not nyagos.suffixes[suffix] then
local orgpathext = nyagos.getenv("PATHEXT")
local newext="."..suffix
if not string.find(";"..orgpathext..";",";"..newext..";",1,true) then
nyagos.setenv("PATHEXT",orgpathext..";"..newext)
end
end
nyagos.suffixes[suffix]=cmdline
end
suffix = setmetatable({},{
__call = function(t,k,v) _suffix(k,v) return end,
__newindex = function(t,k,v) _suffix(k,v) return end,
__index = function(t,k) return nyagos.suffixes[k] end
})
local org_filter=nyagos.argsfilter
nyagos.argsfilter = function(args)
if org_filter then
local args_ = org_filter(args)
if args_ then
args = args_
end
end
local path=nyagos.which(args[0])
if not path then
return
end
local m = string.match(path,"%.(%w+)$")
if not m then
return
end
local cmdline = nyagos.suffixes[ string.lower(m) ]
if not cmdline then
return
end
local newargs={}
if type(cmdline) == 'table' then
for i=1,#cmdline do
newargs[i-1]=cmdline[i]
end
elseif type(cmdline) == 'string' then
newargs[0] = cmdline
end
newargs[#newargs+1] = path
for i=1,#args do
newargs[#newargs+1] = args[i]
end
return newargs
end
nyagos.alias.suffix = function(args)
if #args < 2 then
print "Usage: suffix SUFFIX COMMAND"
else
local cmdline={}
for i=2,#args do
cmdline[#cmdline+1]=args[i]
end
suffix(args[1],cmdline)
end
end
suffix.pl="perl"
if nyagos.which("ipy") then
suffix.py="ipy"
elseif nyagos.which("py") then
suffix.py="py"
else
suffix.py="python"
end
suffix.rb="ruby"
suffix.lua="lua"
suffix.awk={"awk","-f"}
suffix.js={"cscript","//nologo"}
suffix.vbs={"cscript","//nologo"}
suffix.ps1={"powershell","-file"}
|
Update suffix.py
|
Update suffix.py
|
Lua
|
bsd-3-clause
|
hattya/nyagos,kissthink/nyagos,tyochiai/nyagos,kissthink/nyagos,hattya/nyagos,zetamatta/nyagos,nocd5/nyagos,kissthink/nyagos,hattya/nyagos,tsuyoshicho/nyagos
|
20b8f8d7202c1c398c9287f73ed00133e50f5ed3
|
pud/view/GameCam.lua
|
pud/view/GameCam.lua
|
require 'pud.util'
local Class = require 'lib.hump.class'
local Camera = require 'lib.hump.camera'
local vector = require 'lib.hump.vector'
local Rect = require 'pud.kit.Rect'
local math_max, math_min = math.max, math.min
local _zoomLevels = {1, 0.5, 0.25}
local _isVector = function(...)
local n = select('#',...)
for i=1,n do
local v = select(i,...)
assert(vector.isvector(v), 'vector expected, got %s (%s)',
tostring(v), type(v))
end
return n > 0
end
local GameCam = Class{name='GameCam',
function(self, v, zoom)
v = v or vector(0,0)
if _isVector(v) then
self._zoom = math_max(1, math_min(#_zoomLevels, zoom or 1))
self._home = v
self._cam = Camera(v, _zoomLevels[self._zoom])
end
end
}
-- destructor
function GameCam:destroy()
self:unfollowTarget()
self._cam = nil
self._home = nil
self._zoom = nil
for k,v in pairs(self._limits) do self._limits[k] = nil end
self._limits = nil
self._isAnimating = nil
end
function GameCam:_setAnimating(b)
verify('boolean', b)
self._isAnimating = b
end
function GameCam:isAnimating()
return self._isAnimating == true
end
-- zoom in smoothly
-- allows a callback to be passed in that will be called after the animation
-- is complete.
function GameCam:zoomIn(...)
if self._zoom > 1 and not self:isAnimating() then
self._zoom = self._zoom - 1
self:_setAnimating(true)
tween(0.25, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outBack',
function(self, ...)
self:_setAnimating(false)
if select('#', ...) > 0 then
local callback = select(1, ...)
callback(select(2, ...))
end
end, self, ...)
else
self:_bumpZoom(1.1)
end
end
-- zoom out smoothly
-- allows a callback to be passed in that will be called after the animation
-- is complete.
function GameCam:zoomOut(...)
if self._zoom < #_zoomLevels and not self:isAnimating() then
self._zoom = self._zoom + 1
self:_setAnimating(true)
tween(0.25, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outBack',
function(self, ...)
self:_setAnimating(false)
if select('#', ...) > 0 then
local callback = select(1, ...)
callback(select(2, ...))
end
end, self, ...)
else
self:_bumpZoom(0.9)
end
end
-- bump the zoom but don't change it
function GameCam:_bumpZoom(mult)
if not self:isAnimating() then
self:_setAnimating(true)
tween(0.1, self._cam, {zoom = _zoomLevels[self._zoom] * mult}, 'inQuad',
tween, 0.1, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outQuad',
self._setAnimating, self, false)
end
end
-- return zoom level
function GameCam:getZoom()
return self._zoom, _zoomLevels[self._zoom]
end
-- follow a target Rect
function GameCam:followTarget(rect)
assert(rect and rect.is_a and rect:is_a(Rect),
'GameCam can only follow a Rect (tried to follow %s)', tostring(rect))
self._target = rect
self._targetFuncs = {
setX = rect.setX,
setY = rect.setY,
setPosition = rect.setPosition,
setCenter = rect.setCenter,
}
local function _follow(self, theRect)
local pos = theRect:getPositionVector()
local size = theRect:getSizeVector()
if size.x == 1 and size.y == 1 then
size.x = size.x * TILEW
size.y = size.y * TILEH
end
self._cam.pos.x = (pos.x-1) * size.x + size.x/2
self._cam.pos.y = (pos.y-1) * size.y + size.y/2
self:_correctPos(self._cam.pos)
end
rect.setX = function(theRect, x)
self._targetFuncs.setX(theRect, x)
_follow(self, theRect)
end
rect.setY = function(theRect, y)
self._targetFuncs.setY(theRect, y)
_follow(self, theRect)
end
rect.setPosition = function(theRect, x, y)
self._targetFuncs.setPosition(theRect, x, y)
_follow(self, theRect)
end
rect.setCenter = function(theRect, x, y, flag)
self._targetFuncs.setCenter(theRect, x, y, flag)
_follow(self, theRect)
end
_follow(self, rect)
end
-- unfollow a target Rect
function GameCam:unfollowTarget()
if self._target then
self._target.setX = self._targetFuncs.setX
self._target.setY = self._targetFuncs.setY
self._target.setPosition = self._targetFuncs.setPosition
self._target.setCenter = self._targetFuncs.setCenter
self._targetFuncs.setX = nil
self._targetFuncs.setY = nil
self._targetFuncs.setPosition = nil
self._targetFuncs.setCenter = nil
self._targetFuncs = nil
self._target = nil
end
end
-- center on initial vector
function GameCam:home()
self:unfollowTarget()
self._cam.pos = self._home
self:_correctPos(self._cam.pos)
end
-- change home vector
function GameCam:setHome(home)
if _isVector(home) then
self._home = home
end
end
-- translate along v
-- allows a callback to be passed in that will be called after the animation
-- is complete.
function GameCam:translate(v, ...)
if _isVector(v) and not self:isAnimating() then
self:_checkLimits(v)
if v:len2() ~= 0 then
local target = self._cam.pos + v
self:_setAnimating(true)
tween(0.15, self._cam.pos, target, 'outQuint',
function(self, ...)
self:_setAnimating(false)
if select('#', ...) > 0 then
local callback = select(1, ...)
callback(select(2, ...))
end
end, self, ...)
end
end
end
function GameCam:_checkLimits(v)
local pos = self._cam.pos + v
if pos.x > self._limits.max.x then
v.x = self._limits.max.x - self._cam.pos.x
end
if pos.x < self._limits.min.x then
v.x = self._limits.min.x - self._cam.pos.x
end
if pos.y > self._limits.max.y then
v.y = self._limits.max.y - self._cam.pos.y
end
if pos.y < self._limits.min.y then
v.y = self._limits.min.y - self._cam.pos.y
end
end
-- set x and y limits for camera
function GameCam:setLimits(minV, maxV)
if _isVector(minV, maxV) then
self._limits = {min = minV, max = maxV}
end
end
-- correct the camera position if it is beyond the limits
function GameCam:_correctPos(p)
if p.x > self._limits.max.x then
p.x = self._limits.max.x
end
if p.x < self._limits.min.x then
p.x = self._limits.min.x
end
if p.y > self._limits.max.y then
p.y = self._limits.max.y
end
if p.y < self._limits.min.y then
p.y = self._limits.min.y
end
end
-- camera draw callbacks
function GameCam:predraw() self._cam:predraw() end
function GameCam:postdraw() self._cam:postdraw() end
function GameCam:draw(...) self._cam:draw(...) end
function GameCam:toWorldCoords(campos, zoom, p)
local p = vector((p.x-WIDTH/2) / zoom, (p.y-HEIGHT/2) / zoom)
return p + campos
end
-- get a rect representing the camera viewport
function GameCam:getViewport(translate, zoom)
translate = translate or vector(0,0)
zoom = self._zoom + (zoom or 0)
zoom = math_max(1, math_min(#_zoomLevels, zoom))
-- pretend to translate and zoom
local pos = self._cam.pos:clone()
pos = pos + translate
self:_correctPos(pos)
zoom = _zoomLevels[zoom]
local tl, br = vector(0,0), vector(WIDTH, HEIGHT)
local vp1 = self:toWorldCoords(pos, zoom, tl)
local vp2 = self:toWorldCoords(pos, zoom, br)
return Rect(vp1, vp2-vp1)
end
-- the class
return GameCam
|
require 'pud.util'
local Class = require 'lib.hump.class'
local Camera = require 'lib.hump.camera'
local vector = require 'lib.hump.vector'
local Rect = require 'pud.kit.Rect'
local math_max, math_min = math.max, math.min
local _zoomLevels = {1, 0.5, 0.25}
local _isVector = function(...)
local n = select('#',...)
for i=1,n do
local v = select(i,...)
assert(vector.isvector(v), 'vector expected, got %s (%s)',
tostring(v), type(v))
end
return n > 0
end
local GameCam = Class{name='GameCam',
function(self, v, zoom)
v = v or vector(0,0)
if _isVector(v) then
self._zoom = math_max(1, math_min(#_zoomLevels, zoom or 1))
self._home = v
self._cam = Camera(v, _zoomLevels[self._zoom])
end
end
}
-- destructor
function GameCam:destroy()
self:unfollowTarget()
self._cam = nil
self._home = nil
self._zoom = nil
for k,v in pairs(self._limits) do self._limits[k] = nil end
self._limits = nil
self._isAnimating = nil
end
function GameCam:_setAnimating(b)
verify('boolean', b)
self._isAnimating = b
end
function GameCam:isAnimating()
return self._isAnimating == true
end
-- zoom in smoothly
-- allows a callback to be passed in that will be called after the animation
-- is complete.
function GameCam:zoomIn(...)
if self._zoom > 1 and not self:isAnimating() then
self._zoom = self._zoom - 1
self:_setAnimating(true)
tween(0.25, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outBack',
function(self, ...)
self:_setAnimating(false)
if select('#', ...) > 0 then
local callback = select(1, ...)
callback(select(2, ...))
end
end, self, ...)
else
self:_bumpZoom(1.1)
end
end
-- zoom out smoothly
-- allows a callback to be passed in that will be called after the animation
-- is complete.
function GameCam:zoomOut(...)
if self._zoom < #_zoomLevels and not self:isAnimating() then
self._zoom = self._zoom + 1
self:_setAnimating(true)
tween(0.25, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outBack',
function(self, ...)
self:_setAnimating(false)
if select('#', ...) > 0 then
local callback = select(1, ...)
callback(select(2, ...))
end
end, self, ...)
else
self:_bumpZoom(0.9)
end
end
-- bump the zoom but don't change it
function GameCam:_bumpZoom(mult)
if not self:isAnimating() then
self:_setAnimating(true)
tween(0.1, self._cam, {zoom = _zoomLevels[self._zoom] * mult}, 'inQuad',
tween, 0.1, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outQuad',
self._setAnimating, self, false)
end
end
-- return zoom level
function GameCam:getZoom()
return self._zoom, _zoomLevels[self._zoom]
end
-- follow a target Rect
function GameCam:followTarget(rect)
assert(rect and rect.is_a and rect:is_a(Rect),
'GameCam can only follow a Rect (tried to follow %s)', tostring(rect))
if self._target then self:unfollowTarget() end
self._target = rect
self._targetFuncs = {
setX = rect.setX,
setY = rect.setY,
setPosition = rect.setPosition,
setCenter = rect.setCenter,
}
local function _follow(self, theRect)
local pos = theRect:getPositionVector()
local size = theRect:getSizeVector()
if size.x == 1 and size.y == 1 then
size.x = size.x * TILEW
size.y = size.y * TILEH
end
self._cam.pos.x = (pos.x-1) * size.x + size.x/2
self._cam.pos.y = (pos.y-1) * size.y + size.y/2
self:_correctPos(self._cam.pos)
end
rect.setX = function(theRect, x)
self._targetFuncs.setX(theRect, x)
_follow(self, theRect)
end
rect.setY = function(theRect, y)
self._targetFuncs.setY(theRect, y)
_follow(self, theRect)
end
rect.setPosition = function(theRect, x, y)
self._targetFuncs.setPosition(theRect, x, y)
_follow(self, theRect)
end
rect.setCenter = function(theRect, x, y, flag)
self._targetFuncs.setCenter(theRect, x, y, flag)
_follow(self, theRect)
end
_follow(self, rect)
end
-- unfollow a target Rect
function GameCam:unfollowTarget()
if self._target then
self._target.setX = self._targetFuncs.setX
self._target.setY = self._targetFuncs.setY
self._target.setPosition = self._targetFuncs.setPosition
self._target.setCenter = self._targetFuncs.setCenter
self._targetFuncs.setX = nil
self._targetFuncs.setY = nil
self._targetFuncs.setPosition = nil
self._targetFuncs.setCenter = nil
self._targetFuncs = nil
self._target = nil
end
end
-- center on initial vector
function GameCam:home()
self:unfollowTarget()
self._cam.pos = self._home
self:_correctPos(self._cam.pos)
end
-- change home vector
function GameCam:setHome(home)
if _isVector(home) then
self._home = home
end
end
-- translate along v
-- allows a callback to be passed in that will be called after the animation
-- is complete.
function GameCam:translate(v, ...)
if _isVector(v) and not self:isAnimating() then
self:_checkLimits(v)
if v:len2() ~= 0 then
local target = self._cam.pos + v
self:_setAnimating(true)
tween(0.15, self._cam.pos, target, 'outQuint',
function(self, ...)
self:_setAnimating(false)
if select('#', ...) > 0 then
local callback = select(1, ...)
callback(select(2, ...))
end
end, self, ...)
end
end
end
function GameCam:_checkLimits(v)
local pos = self._cam.pos + v
if pos.x > self._limits.max.x then
v.x = self._limits.max.x - self._cam.pos.x
end
if pos.x < self._limits.min.x then
v.x = self._limits.min.x - self._cam.pos.x
end
if pos.y > self._limits.max.y then
v.y = self._limits.max.y - self._cam.pos.y
end
if pos.y < self._limits.min.y then
v.y = self._limits.min.y - self._cam.pos.y
end
end
-- set x and y limits for camera
function GameCam:setLimits(minV, maxV)
if _isVector(minV, maxV) then
self._limits = {min = minV, max = maxV}
end
end
-- correct the camera position if it is beyond the limits
function GameCam:_correctPos(p)
if p.x > self._limits.max.x then
p.x = self._limits.max.x
end
if p.x < self._limits.min.x then
p.x = self._limits.min.x
end
if p.y > self._limits.max.y then
p.y = self._limits.max.y
end
if p.y < self._limits.min.y then
p.y = self._limits.min.y
end
end
-- camera draw callbacks
function GameCam:predraw() self._cam:predraw() end
function GameCam:postdraw() self._cam:postdraw() end
function GameCam:draw(...) self._cam:draw(...) end
function GameCam:toWorldCoords(campos, zoom, p)
local p = vector((p.x-WIDTH/2) / zoom, (p.y-HEIGHT/2) / zoom)
return p + campos
end
-- get a rect representing the camera viewport
function GameCam:getViewport(translate, zoom)
translate = translate or vector(0,0)
zoom = self._zoom + (zoom or 0)
zoom = math_max(1, math_min(#_zoomLevels, zoom))
-- pretend to translate and zoom
local pos = self._cam.pos:clone()
pos = pos + translate
self:_correctPos(pos)
zoom = _zoomLevels[zoom]
local tl, br = vector(0,0), vector(WIDTH, HEIGHT)
local vp1 = self:toWorldCoords(pos, zoom, tl)
local vp2 = self:toWorldCoords(pos, zoom, br)
return Rect(vp1, vp2-vp1)
end
-- the class
return GameCam
|
fix stack overflow when following an already followed target
|
fix stack overflow when following an already followed target
|
Lua
|
mit
|
scottcs/wyx
|
9ef9a4349ae65ae12c3080fd997641c56a24f111
|
ios-icons/cache.lua
|
ios-icons/cache.lua
|
local format = string.format
local cache = {}
-- add a function to get a list of keys
-- add delete function
-- what about a protocol so that we can have caches with a backend other than the file system?
-- (then what about Lua FUSE?)
function cache.new(path, keytransform)
assert(type(path) == 'string' and #path > 0, 'path must be a non-empty string')
assert(type(keytransform) == 'nil' or type(keytransform) == 'function', 'keytransform must be a function')
local c = { }
_,_,rc = os.execute('test -d ' .. path)
if rc == 1 then os.execute('mkdir -p ' .. path) end
c.keytransform = keytransform or function(k) return k end
c.key = function(k)
local kprime = c.keytransform(k)
if not kprime then return nil end
return format('%s/%s', path, kprime)
end
c.get = function(k, generate)
local data = nil
local key = c.key(k)
if not key then error('invalid key: ' .. tostring(k)) end
local fd = io.open(key, "rb")
if fd then data = fd:read("*all") ; fd:close() end
if not data and type(generate) == "function" then
data = generate(k)
c.store(k, data)
end
return data
end
c.set = function(k, v)
local key = c.key(k)
if not key then error('invalid key: ' .. tostring(k)) end
local fd = io.open(key, "wb")
fd:write(v)
fd:close()
end
setmetatable(c, {
__tostring = function() return "cache[" .. path .. "]" end,
})
return c
end
return cache
|
local format = string.format
local execute = os.execute
local open = io.open
local cache = {}
-- add a function to get a list of keys
-- what about a protocol so that we can have caches with a backend other than the file system?
-- (then what about Lua FUSE?)
function cache.new(path, keytransform)
assert(type(path) == 'string' and #path > 0, 'path must be a non-empty string')
assert(type(keytransform) == 'nil' or type(keytransform) == 'function', 'keytransform must be a function')
local c = { }
_,_,rc = execute('test -d ' .. path)
if rc == 1 then execute('mkdir -p ' .. path) end
c.keytransform = keytransform or function(k) return k end
c.key = function(k)
local kprime = c.keytransform(k)
if not kprime then return nil end
return format('%s/%s', path, kprime)
end
c.get = function(k, generate)
local data = nil
local key = c.key(k)
if not key then error('invalid key: ' .. tostring(k)) end
local fd = open(key, "rb")
if fd then data = fd:read("*all") ; fd:close() end
if not data and type(generate) == "function" then
data = generate(k)
c.set(k, data)
end
return data
end
c.set = function(k, v)
local key = c.key(k)
if not key then error('invalid key: ' .. tostring(k)) end
local fd = open(key, "wb")
fd:write(v)
fd:close()
end
c.remove = function(k)
local key = c.key(k)
_,_,rc = execute('/bin/rm -f ' .. key)
return rc
end
setmetatable(c, {
__tostring = function() return "cache[" .. path .. "]" end,
})
return c
end
return cache
|
fixed bug in get; added remove function
|
fixed bug in get; added remove function
|
Lua
|
mit
|
profburke/ios-icons,profburke/ios-icons,profburke/ios-icons
|
a26e0aba244379df13334f4a8bf22f8a3739f1a1
|
regress/regress.lua
|
regress/regress.lua
|
local require = require -- may be overloaded by regress.require
local auxlib = require"cqueues.auxlib"
local regress = {
cqueues = require"cqueues",
socket = require"cqueues.socket",
thread = require"cqueues.thread",
errno = require"cqueues.errno",
condition = require"cqueues.condition",
auxlib = auxlib,
assert = auxlib.assert,
fileresult = auxlib.fileresult,
}
local emit_progname = os.getenv"REGRESS_PROGNAME" or "regress"
local emit_verbose = tonumber(os.getenv"REGRESS_VERBOSE" or 1)
local emit_info = {}
local emit_ll = 0
local function emit(fmt, ...)
local msg = string.format(fmt, ...)
for txt, nl in msg:gmatch("([^\n]*)(\n?)") do
if emit_ll == 0 and #txt > 0 then
io.stderr:write(emit_progname, ": ")
emit_ll = #emit_progname + 2
end
io.stderr:write(txt, nl)
if nl == "\n" then
emit_ll = 0
else
emit_ll = emit_ll + #txt
end
end
end -- emit
local function emitln(fmt, ...)
if emit_ll > 0 then
emit"\n"
end
emit(fmt .. "\n", ...)
end -- emitln
local function emitinfo()
for _, txt in ipairs(emit_info) do
emitln("%s", txt)
end
end -- emitinfo
function regress.say(...)
emitln(...)
end -- say
function regress.panic(...)
emitinfo()
emitln(...)
os.exit(1)
end -- panic
function regress.info(...)
if emit_verbose > 1 then
emitln(...)
else
emit_info[#emit_info + 1] = string.format(...)
if emit_verbose > 0 then
if emit_ll > 78 then
emit"\n."
else
emit"."
end
end
end
end -- info
function regress.check(v, ...)
if v then
return v, ...
else
regress.panic(...)
end
end -- check
function regress.export(...)
for _, pat in ipairs{ ... } do
for k, v in pairs(regress) do
if string.match(k, pat) then
_G[k] = v
end
end
end
return regress
end -- export
function regress.require(modname)
local ok, module = pcall(require, modname)
regress.check(ok, "module %s required", modname)
return module
end -- regress.require
function regress.genkey(type)
local pkey = regress.require"openssl.pkey"
local x509 = regress.require"openssl.x509"
local name = regress.require"openssl.x509.name"
local altname = regress.require"openssl.x509.altname"
local key
type = string.upper(type or "RSA")
if type == "EC" then
key = regress.check(pkey.new{ type = "EC", curve = "prime192v1" })
else
key = regress.check(pkey.new{ type = type, bits = 1024 })
end
local dn = name.new()
dn:add("C", "US")
dn:add("ST", "California")
dn:add("L", "San Francisco")
dn:add("O", "Acme, Inc.")
dn:add("CN", "acme.inc")
local alt = altname.new()
alt:add("DNS", "acme.inc")
alt:add("DNS", "localhost")
local crt = x509.new()
crt:setVersion(3)
crt:setSerial(47)
crt:setSubject(dn)
crt:setIssuer(crt:getSubject())
crt:setSubjectAlt(alt)
local issued, expires = crt:getLifetime()
crt:setLifetime(issued, expires + 60)
crt:setBasicConstraints{ CA = true, pathLen = 2 }
crt:setBasicConstraintsCritical(true)
crt:setPublicKey(key)
crt:sign(key)
return key, crt
end -- regress.genkey
local function getsubtable(t, name, ...)
name = name or false -- cannot be nil
if not t[name] then
t[name] = {}
end
if select('#', ...) > 0 then
return getsubtable(t[name], ...)
else
return t[name]
end
end -- getsubtable
function regress.newsslctx(protocol, accept, keytype)
local context = regress.require"openssl.ssl.context"
local ctx = context.new(protocol, accept)
if keytype or keytype == nil then
local key, crt = regress.genkey(keytype)
ctx:setCertificate(crt)
ctx:setPrivateKey(key)
end
return ctx
end -- require.newsslctx
local ctxcache = {}
function regress.getsslctx(protocol, accept, keytype)
local keycache = getsubtable(ctxcache, protocol, accept)
if keytype == nil then
keytype = "RSA"
end
local ctx = keycache[keytype]
if not ctx then
ctx = regress.newsslctx(protocol, accept, keytype)
keycache[keytype] = ctx
end
return ctx
end -- regress.getsslctx
return regress
|
local require = require -- may be overloaded by regress.require
local auxlib = require"cqueues.auxlib"
local regress = {
cqueues = require"cqueues",
socket = require"cqueues.socket",
thread = require"cqueues.thread",
errno = require"cqueues.errno",
condition = require"cqueues.condition",
auxlib = auxlib,
assert = auxlib.assert,
fileresult = auxlib.fileresult,
}
local emit_progname = os.getenv"REGRESS_PROGNAME" or "regress"
local emit_verbose = tonumber(os.getenv"REGRESS_VERBOSE" or 1)
local emit_info = {}
local emit_ll = 0
local function emit(fmt, ...)
local msg = string.format(fmt, ...)
for txt, nl in msg:gmatch("([^\n]*)(\n?)") do
if emit_ll == 0 and #txt > 0 then
io.stderr:write(emit_progname, ": ")
emit_ll = #emit_progname + 2
end
io.stderr:write(txt, nl)
if nl == "\n" then
emit_ll = 0
else
emit_ll = emit_ll + #txt
end
end
end -- emit
local function emitln(fmt, ...)
if emit_ll > 0 then
emit"\n"
end
emit(fmt .. "\n", ...)
end -- emitln
local function emitinfo()
for _, txt in ipairs(emit_info) do
emitln("%s", txt)
end
end -- emitinfo
function regress.say(...)
emitln(...)
end -- say
function regress.panic(...)
emitinfo()
emitln(...)
os.exit(1)
end -- panic
function regress.info(...)
if emit_verbose > 1 then
emitln(...)
else
emit_info[#emit_info + 1] = string.format(...)
if emit_verbose > 0 then
if emit_ll > 78 then
emit"\n."
else
emit"."
end
end
end
end -- info
function regress.check(v, ...)
if v then
return v, ...
else
regress.panic(...)
end
end -- check
function regress.export(...)
for _, pat in ipairs{ ... } do
for k, v in pairs(regress) do
if string.match(k, pat) then
_G[k] = v
end
end
end
return regress
end -- export
function regress.require(modname)
local ok, module = pcall(require, modname)
regress.check(ok, "module %s required", modname)
return module
end -- regress.require
function regress.genkey(type)
local pkey = regress.require"openssl.pkey"
local x509 = regress.require"openssl.x509"
local name = regress.require"openssl.x509.name"
local altname = regress.require"openssl.x509.altname"
local key
type = string.upper(type or "RSA")
if type == "EC" then
key = regress.check(pkey.new{ type = "EC", curve = "prime192v1" })
else
key = regress.check(pkey.new{ type = type, bits = 1024 })
end
local dn = name.new()
dn:add("C", "US")
dn:add("ST", "California")
dn:add("L", "San Francisco")
dn:add("O", "Acme, Inc.")
dn:add("CN", "acme.inc")
local alt = altname.new()
alt:add("DNS", "acme.inc")
alt:add("DNS", "localhost")
local crt = x509.new()
crt:setVersion(3)
crt:setSerial(47)
crt:setSubject(dn)
crt:setIssuer(crt:getSubject())
crt:setSubjectAlt(alt)
local issued, expires = crt:getLifetime()
crt:setLifetime(issued, expires + 60)
crt:setBasicConstraints{ CA = true, pathLen = 2 }
crt:setBasicConstraintsCritical(true)
crt:setPublicKey(key)
crt:sign(key)
return key, crt
end -- regress.genkey
local function getsubtable(t, name, ...)
name = name or false -- cannot be nil
if not t[name] then
t[name] = {}
end
if select('#', ...) > 0 then
return getsubtable(t[name], ...)
else
return t[name]
end
end -- getsubtable
function regress.newsslctx(protocol, accept, keytype)
local context = regress.require"openssl.ssl.context"
local ctx = context.new(protocol, accept)
if keytype or keytype == nil then
local key, crt = regress.genkey(keytype)
ctx:setCertificate(crt)
ctx:setPrivateKey(key)
end
return ctx
end -- require.newsslctx
local ctxcache = {}
function regress.getsslctx(protocol, accept, keytype)
local keycache = getsubtable(ctxcache, protocol, accept)
if keytype == nil then
keytype = "RSA"
end
local ctx = keycache[keytype]
if not ctx then
ctx = regress.newsslctx(protocol, accept, keytype)
keycache[keytype] = ctx
end
return ctx
end -- regress.getsslctx
-- test 87-alpn-disappears relies on package.searchpath
function regress.searchpath(name, paths, sep, rep)
sep = (sep or "."):gsub("[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0")
rep = (rep or "/"):gsub("%%", "%%%%")
local nofile = {}
for path in paths:gmatch("([^;]+)") do
path = path:gsub("%?", (name:gsub(sep, rep):gsub("%%", "%%%%")))
local fh = io.open(path, "rb")
if fh then
fh:close()
return path
end
nofile[#nofile + 1] = string.format("no file '%s'", path)
end
return nil, table.concat(nofile, "\n")
end -- regress.searchpath
package.searchpath = package.searchpath or regress.searchpath
return regress
|
fix test 87-alpn-disappears, which relies on package.searchpath, for Lua 5.1
|
fix test 87-alpn-disappears, which relies on package.searchpath, for Lua 5.1
|
Lua
|
mit
|
wahern/cqueues,wahern/cqueues,daurnimator/cqueues,daurnimator/cqueues
|
1fc34a088a0ab5215bc3c2978875fe1c23d97c2b
|
resources/syncplay.lua
|
resources/syncplay.lua
|
--[==========================================================================[
syncplay.lua: Syncplay interface module
--[==========================================================================[
Author: Etoh
--]==========================================================================]
require "common"
require "host"
local connectorversion = "0.0.1"
local port
local msgterminator = "\n"
local msgseperator = ": "
local argseperator = ", "
local responsemarker = "-response"
local errormarker = "-error"
local noinput = "no-input"
local notimplemented = "not-implemented"
local unknowncommand = "unknown-command"
function get_args (argument, argcount)
local argarray = {}
local index
local i
local argbuffer
argbuffer = argument
for i = 1, argcount,1 do
if i == argcount then
argarray[i] = argbuffer
else
if string.find(argbuffer, argseperator) then
index = string.find(argbuffer, argseperator)
argarray[i] = string.sub(argbuffer, 0, index - 1)
argbuffer = string.sub(argbuffer, index + string.len(argseperator))
else
argarray[i] = ""
end
end
end
return argarray
end
port = tonumber(config["port"])
if (port == nil or port < 1) then port = 4123 end
vlc.msg.info("Hosting Syncplay interface on port: "..port)
h = host.host()
-- Bypass any authentication
function on_password( client )
client:switch_status( host.status.read )
end
function get_var( vartoget )
local response
local errormsg
local input = vlc.object.input()
if input then
response = vlc.var.get(input,tostring(vartoget))
else
errormsg = noinput
end
vlc.msg.info("getvar `"..tostring(vartoget).."`: '"..tostring(response).."'")
return response, errormsg
end
function set_var(vartoset, varvalue)
local errormsg
local input = vlc.object.input()
if input then
vlc.var.set(input,tostring(vartoset),tostring(varvalue))
else
errormsg = noinput
end
vlc.msg.info("setvar: '"..tostring(vartoset).."' = '"..tostring(varvalue).."'")
return errormsg
end
h:listen( "localhost:"..port)
--h:listen( "*console" )
function get_play_state()
local response
local errormsg
local input = vlc.object.input()
if input then
response = vlc.playlist.status()
else
errormsg = noinput
end
vlc.msg.info("get play state: '"..tostring(response).."'")
return response, errormsg
end
function get_filepath ()
local response
local errormsg
local item
local input = vlc.object.input()
if input then
local item = vlc.input.item()
if item then
response = vlc.strings.decode_uri(item:uri())
else
errormsg = noinput
end
else
errormsg = noinput
end
return response, errormsg
end
function display_osd ( argument )
local errormsg
local osdarray
osdarray = get_args(argument,3)
--position, duration ms, message
vlc.osd.message(osdarray[3],channel1,osdarray[1],osdarray[2])
return errormsg
end
function do_command ( command, argument)
local command = tostring(command)
local argument = tostring(argument)
local errormsg = ""
local response = ""
vlc.msg.info("Command: '"..command.."'")
vlc.msg.info("Argument: '"..argument.."'")
local input = vlc.object.input()
if command == "get-playstate" then response, errormsg = get_play_state()
elseif command == "get-time" then response, errormsg = get_var("time")
elseif command == "get-filename" then response, errormsg = get_var("title")
elseif command == "get-file-length" then response, errormsg = get_var("length")
elseif command == "get-filepath" then response, errormsg = get_filepath()
elseif command == "get-vlc-version" then response = vlc.misc.version()
elseif command == "get-version" then response = connectorversion
elseif command == "play" then errormsg = playfile()
elseif command == "pause" then errormsg = pausefile()
elseif command == "playpause" then errormsg = playpausefile()
elseif command == "seek" then errormsg = set_var("time", tonumber(argument))
elseif command == "set-rate" then errormsg = set_var("rate", tonumber(argument))
elseif command == "display-osd" then errormsg = display_osd(argument)
else errormsg = unknowncommand
end
if (tostring(errormsg) == "" or errormsg == nil) then
if (tostring(response) == "") then
response = command..responsemarker..msgterminator
else
response = command..responsemarker..msgseperator..tostring(response)..msgterminator
end
else
response = command..errormarker..msgseperator..tostring(errormsg)..msgterminator
end
vlc.msg.info("Response: '"..tostring(response).."'")
return response
end
function playfile()
local errormsg
if input then
common.hotkey("key-pause")
else
errormsg = noinput
end
return errormsg
end
function pausefile()
local errormsg
if input then
common.hotkey("key-play")
else
errormsg = noinput
end
return errormsg
end
function playpausefile()
local errormsg
if input then
vlc.playlist.pause()
else
errormsg = noinput
end
return errormsg
end
-- main loop
while not vlc.misc.should_die() do
-- accept new connections and select active clients
local write, read = h:accept_and_select()
-- handle clients in write mode
for _, client in pairs(write) do
client:send()
client.buffer = ""
client:switch_status( host.status.read )
end
-- handle clients in read mode
for _, client in pairs(read) do
local str = client:recv(1000)
local responsebuffer
if not str then break end
local safestr = string.gsub(tostring(str), "\r", "")
if client.inputbuffer == nil then
client.inputbuffer = ""
end
client.inputbuffer = client.inputbuffer .. safestr
vlc.msg.info("Str: '" .. safestr.."'")
vlc.msg.info("Input buffer: '" .. client.inputbuffer.."'")
while string.find(client.inputbuffer, msgterminator) do
local index = string.find(client.inputbuffer, msgterminator)
local request = string.sub(client.inputbuffer, 0, index - 1)
local command
local argument
client.inputbuffer = string.sub(client.inputbuffer, index + string.len(msgterminator))
if (string.find(request, msgseperator)) then
index = string.find(request, msgseperator)
command = string.sub(request, 0, index - 1)
argument = string.sub(request, index + string.len(msgseperator))
else
command = request
end
if (responsebuffer) then
responsebuffer = responsebuffer .. do_command(command,argument)
else
responsebuffer = do_command(command,argument)
end
end
client.buffer = ""
if (responsebuffer) then
client:send(responsebuffer)
end
client.buffer = ""
client:switch_status( host.status.write )
end
end
|
--[==========================================================================[
syncplay.lua: Syncplay interface module
--[==========================================================================[
Author: Etoh
--]==========================================================================]
require "common"
require "host"
local connectorversion = "0.0.1"
local port
local msgterminator = "\n"
local msgseperator = ": "
local argseperator = ", "
local responsemarker = "-response"
local errormarker = "-error"
local noinput = "no-input"
local notimplemented = "not-implemented"
local unknowncommand = "unknown-command"
function get_args (argument, argcount)
local argarray = {}
local index
local i
local argbuffer
argbuffer = argument
for i = 1, argcount,1 do
if i == argcount then
argarray[i] = argbuffer
else
if string.find(argbuffer, argseperator) then
index = string.find(argbuffer, argseperator)
argarray[i] = string.sub(argbuffer, 0, index - 1)
argbuffer = string.sub(argbuffer, index + string.len(argseperator))
else
argarray[i] = ""
end
end
end
return argarray
end
port = tonumber(config["port"])
if (port == nil or port < 1) then port = 4123 end
vlc.msg.info("Hosting Syncplay interface on port: "..port)
h = host.host()
-- Bypass any authentication
function on_password( client )
client:switch_status( host.status.read )
end
function get_var( vartoget )
local response
local errormsg
local input = vlc.object.input()
if input then
response = vlc.var.get(input,tostring(vartoget))
else
errormsg = noinput
end
vlc.msg.info("getvar `"..tostring(vartoget).."`: '"..tostring(response).."'")
return response, errormsg
end
function set_var(vartoset, varvalue)
local errormsg
local input = vlc.object.input()
if input then
vlc.var.set(input,tostring(vartoset),tostring(varvalue))
else
errormsg = noinput
end
vlc.msg.info("setvar: '"..tostring(vartoset).."' = '"..tostring(varvalue).."'")
return errormsg
end
h:listen( "localhost:"..port)
--h:listen( "*console" )
function get_play_state()
local response
local errormsg
local input = vlc.object.input()
if input then
response = vlc.playlist.status()
else
errormsg = noinput
end
vlc.msg.info("get play state: '"..tostring(response).."'")
return response, errormsg
end
function get_filepath ()
local response
local errormsg
local item
local input = vlc.object.input()
if input then
local item = vlc.input.item()
if item then
response = vlc.strings.decode_uri(item:uri())
else
errormsg = noinput
end
else
errormsg = noinput
end
return response, errormsg
end
function display_osd ( argument )
local errormsg
local osdarray
osdarray = get_args(argument,3)
--position, duration ms, message
vlc.osd.message(osdarray[3],channel1,osdarray[1],osdarray[2])
return errormsg
end
function do_command ( command, argument)
local command = tostring(command)
local argument = tostring(argument)
local errormsg = ""
local response = ""
vlc.msg.info("Command: '"..command.."'")
vlc.msg.info("Argument: '"..argument.."'")
local input = vlc.object.input()
if command == "get-playstate" then response, errormsg = get_play_state()
elseif command == "get-time" then response, errormsg = get_var("time")
elseif command == "get-filename" then response, errormsg = get_var("title")
elseif command == "get-file-length" then response, errormsg = get_var("length")
elseif command == "get-filepath" then response, errormsg = get_filepath()
elseif command == "get-vlc-version" then response = vlc.misc.version()
elseif command == "get-version" then response = connectorversion
elseif command == "play" then errormsg = playfile()
elseif command == "pause" then errormsg = pausefile()
elseif command == "playpause" then errormsg = playpausefile()
elseif command == "seek" then errormsg = set_var("time", tonumber(argument))
elseif command == "set-rate" then errormsg = set_var("rate", tonumber(argument))
elseif command == "display-osd" then errormsg = display_osd(argument)
else errormsg = unknowncommand
end
if (tostring(errormsg) == "" or errormsg == nil) then
if (tostring(response) == "") then
response = command..responsemarker..msgterminator
else
response = command..responsemarker..msgseperator..tostring(response)..msgterminator
end
else
response = command..errormarker..msgseperator..tostring(errormsg)..msgterminator
end
vlc.msg.info("Response: '"..tostring(response).."'")
return response
end
function playfile()
local errormsg
local input = vlc.object.input()
local playstate
playstate, errormsg = get_play_state()
if playstate == "paused" then
vlc.playlist.pause()
end
return errormsg
end
function pausefile()
local errormsg
local input = vlc.object.input()
local playstate
playstate, errormsg = get_play_state()
if playstate == "playing" then
vlc.playlist.pause()
end
return errormsg
end
function playpausefile()
local errormsg
local input = vlc.object.input()
if input then
vlc.playlist.pause()
else
errormsg = noinput
end
return errormsg
end
-- main loop
while not vlc.misc.should_die() do
-- accept new connections and select active clients
local write, read = h:accept_and_select()
-- handle clients in write mode
for _, client in pairs(write) do
client:send()
client.buffer = ""
client:switch_status( host.status.read )
end
-- handle clients in read mode
for _, client in pairs(read) do
local str = client:recv(1000)
local responsebuffer
if not str then break end
local safestr = string.gsub(tostring(str), "\r", "")
if client.inputbuffer == nil then
client.inputbuffer = ""
end
client.inputbuffer = client.inputbuffer .. safestr
vlc.msg.info("Str: '" .. safestr.."'")
vlc.msg.info("Input buffer: '" .. client.inputbuffer.."'")
while string.find(client.inputbuffer, msgterminator) do
local index = string.find(client.inputbuffer, msgterminator)
local request = string.sub(client.inputbuffer, 0, index - 1)
local command
local argument
client.inputbuffer = string.sub(client.inputbuffer, index + string.len(msgterminator))
if (string.find(request, msgseperator)) then
index = string.find(request, msgseperator)
command = string.sub(request, 0, index - 1)
argument = string.sub(request, index + string.len(msgseperator))
else
command = request
end
if (responsebuffer) then
responsebuffer = responsebuffer .. do_command(command,argument)
else
responsebuffer = do_command(command,argument)
end
end
client.buffer = ""
if (responsebuffer) then
client:send(responsebuffer)
end
client.buffer = ""
client:switch_status( host.status.write )
end
end
|
update resources/syncplay.lua - fixed play/pause
|
update resources/syncplay.lua - fixed play/pause
|
Lua
|
apache-2.0
|
Syncplay/syncplay,Syncplay/syncplay,NeverDecaf/syncplay,NeverDecaf/syncplay,alby128/syncplay,alby128/syncplay
|
7b75aba6fc43cf8b2552b181bd851d4f79e5ed15
|
src/program/lisper/dev-env/l2tp.lua
|
src/program/lisper/dev-env/l2tp.lua
|
#!/usr/bin/env luajit
io.stdout:setvbuf'no'
io.stderr:setvbuf'no'
--L2TP IP-over-IPv6 tunnelling program for testing.
local function assert(v, ...)
if v then return v, ... end
error(tostring((...)), 2)
end
local ffi = require'ffi'
local S = require'syscall'
local C = ffi.C
local htons = require'syscall.helpers'.htons
local function hex(s)
return (s:gsub('(.)(.?)', function(c1, c2)
return c2 and #c2 == 1 and
string.format('%02x%02x ', c1:byte(), c2:byte()) or
string.format('%02x ', c1:byte())
end))
end
local digits = {}
for i=0,9 do digits[string.char(('0'):byte()+i)] = i end
for i=0,5 do digits[string.char(('a'):byte()+i)] = 10+i end
for i=0,5 do digits[string.char(('A'):byte()+i)] = 10+i end
local function parsehex(s)
return (s:gsub('[%s%:%.]*(%x)(%x)[%s%:%.]*', function(hi, lo)
local hi = digits[hi]
local lo = digits[lo]
return string.char(lo + hi * 16)
end))
end
local function open_tap(name)
local fd = assert(S.open('/dev/net/tun', 'rdwr, nonblock'))
local ifr = S.t.ifreq{flags = 'tap, no_pi', name = name}
assert(fd:ioctl('tunsetiff', ifr))
return fd
end
local function open_raw(name)
local fd = assert(S.socket('packet', 'raw, nonblock', htons(S.c.ETH_P.all)))
local ifr = S.t.ifreq{name = name}
assert(S.ioctl(fd, 'siocgifindex', ifr))
assert(S.bind(fd, S.t.sockaddr_ll{
ifindex = ifr.ivalue,
protocol = 'all'}))
return fd
end
local function can_read(...)
return assert(S.select({readfds = {...}}, 0)).count == 1
end
local function can_write(...)
return assert(S.select({writefds = {...}}, 0)).count == 1
end
local mtu = 1500
local buf = ffi.new('uint8_t[?]', mtu)
local function read(fd)
local len = assert(S.read(fd, buf, mtu))
return ffi.string(buf, len)
end
local function write(fd, s, len)
assert(S.write(fd, s, len or #s))
end
local function close(fd)
S.close(fd)
end
local tapname, ethname, smac, dmac, sip, dip, sid, did = ...
if not (tapname and ethname and smac and dmac and sip and dip and sid and did) then
print('Usage: '..arg[0]..' TAP ETH SMAC DMAC SIP DIP SID DID')
print' TAP: the tunneled interface: will be created if not present.'
print' ETH: the tunneling interface: must have an IPv6 assigned.'
print' SMAC: the MAC address of ETH.'
print' DMAC: the MAC address of the gateway interface.'
print' SIP: the IPv6 of ETH (long form).'
print' DIP: the IPv6 of ETH at the other endpoint (long form).'
print' SID: session ID (hex)'
print' DID: peer session ID (hex)'
os.exit(1)
end
smac = parsehex(smac)
dmac = parsehex(dmac)
sip = parsehex(sip)
dip = parsehex(dip)
sid = parsehex(sid)
did = parsehex(did)
local tap = open_tap(tapname)
local raw = open_raw(ethname)
print('tap ', tapname)
print('raw ', ethname)
print('smac ', hex(smac))
print('dmac ', hex(dmac))
print('sip ', hex(sip))
print('dip ', hex(dip))
print('sid ', hex(sid))
print('did ', hex(did))
local function decap_l2tp(s)
local dmac = s:sub(1, 1+6-1)
local smac = s:sub(1+6, 1+6+6-1)
local eth_proto = s:sub(1+6+6, 1+6+6+2-1)
if eth_proto ~= '\x86\xdd' then
return nil, 'invalid eth_proto '..hex(eth_proto)
end --not ipv6
local ipv6_proto = s:sub(21, 21)
if ipv6_proto ~= '\115' then
return nil, 'invalid ipv6_proto '..hex(ipv6_proto)
end --not l2tp
local sip = s:sub(23, 23+16-1)
local dip = s:sub(23+16, 23+16+16-1)
local sid = s:sub(55, 55+4-1)
local payload = s:sub(67)
return smac, dmac, sip, dip, sid, payload
end
local function encap_l2tp(smac, dmac, sip, dip, did, payload)
local cookie = '\0\0\0\0\0\0\0\0'
local l2tp = did..cookie
local len = #payload + #l2tp
local len = string.char(bit.rshift(len, 8)) .. string.char(bit.band(len, 0xff))
local ipv6_proto = '\115' --l2tp
local maxhops = '\64'
local ipv6 = '\x60\0\0\0'..len..ipv6_proto..maxhops..sip..dip
local eth_proto = '\x86\xdd' --ipv6
local eth = dmac..smac..eth_proto
return eth..ipv6..l2tp..payload
end
while true do
if can_read(tap, raw) then
if can_read(raw) then
local s = read(raw)
local smac1, dmac1, sip1, dip1, did1, payload = decap_l2tp(s)
local accept = smac1
and smac1 == dmac
and dmac1 == smac
and dip1 == sip
and sip1 == dip
and did1 == sid
print('read ', accept and 'accepted' or
('rejected '..(smac1 and hex(dmac1) or dmac1)))
if accept then
print(' smac ', hex(smac1))
print(' dmac ', hex(dmac1))
print(' sip ', hex(sip1))
print(' dip ', hex(dip1))
print(' did ', hex(did1))
print(' # ', #payload)
end
if accept then
write(tap, payload)
end
end
if can_read(tap) then
local payload = read(tap)
local s = encap_l2tp(smac, dmac, sip, dip, did, payload)
print('write')
print(' smac ', hex(smac))
print(' dmac ', hex(dmac))
print(' sip ', hex(sip))
print(' dip ', hex(dip))
print(' did ', hex(did))
print(' # ', #payload)
write(raw, s)
end
end
end
tap:close()
raw:close()
|
#!/usr/bin/env luajit
io.stdout:setvbuf'no'
io.stderr:setvbuf'no'
--L2TP IP-over-IPv6 tunnelling program for testing.
local function assert(v, ...)
if v then return v, ... end
error(tostring((...)), 2)
end
local ffi = require'ffi'
local S = require'syscall'
local C = ffi.C
local htons = require'syscall.helpers'.htons
local function hex(s)
return (s:gsub('(.)(.?)', function(c1, c2)
return c2 and #c2 == 1 and
string.format('%02x%02x ', c1:byte(), c2:byte()) or
string.format('%02x ', c1:byte())
end))
end
local digits = {}
for i=0,9 do digits[string.char(('0'):byte()+i)] = i end
for i=0,5 do digits[string.char(('a'):byte()+i)] = 10+i end
for i=0,5 do digits[string.char(('A'):byte()+i)] = 10+i end
local function parsehex(s)
return (s:gsub('[%s%:%.]*(%x)(%x)[%s%:%.]*', function(hi, lo)
local hi = digits[hi]
local lo = digits[lo]
return string.char(lo + hi * 16)
end))
end
local function open_tap(name)
local fd = assert(S.open('/dev/net/tun', 'rdwr, nonblock'))
local ifr = S.t.ifreq{flags = 'tap, no_pi', name = name}
assert(fd:ioctl('tunsetiff', ifr))
return fd
end
local function open_raw(name)
local fd = assert(S.socket('packet', 'raw, nonblock', htons(S.c.ETH_P.all)))
local ifr = S.t.ifreq{name = name}
assert(S.ioctl(fd, 'siocgifindex', ifr))
assert(S.bind(fd, S.t.sockaddr_ll{
ifindex = ifr.ivalue,
protocol = 'all'}))
return fd
end
local function can_read(timeout, ...)
return assert(S.select({readfds = {...}}, timeout)).count > 0
end
local function can_write(timeout, ...)
return assert(S.select({writefds = {...}}, timeout)).count > 0
end
local mtu = 1500
local buf = ffi.new('uint8_t[?]', mtu)
local function read(fd)
local len = assert(S.read(fd, buf, mtu))
return ffi.string(buf, len)
end
local function write(fd, s, len)
assert(S.write(fd, s, len or #s))
end
local function close(fd)
S.close(fd)
end
local tapname, ethname, smac, dmac, sip, dip, sid, did = ...
if not (tapname and ethname and smac and dmac and sip and dip and sid and did) then
print('Usage: '..arg[0]..' TAP ETH SMAC DMAC SIP DIP SID DID')
print' TAP: the tunneled interface: will be created if not present.'
print' ETH: the tunneling interface: must have an IPv6 assigned.'
print' SMAC: the MAC address of ETH.'
print' DMAC: the MAC address of the gateway interface.'
print' SIP: the IPv6 of ETH (long form).'
print' DIP: the IPv6 of ETH at the other endpoint (long form).'
print' SID: session ID (hex)'
print' DID: peer session ID (hex)'
os.exit(1)
end
smac = parsehex(smac)
dmac = parsehex(dmac)
sip = parsehex(sip)
dip = parsehex(dip)
sid = parsehex(sid)
did = parsehex(did)
local tap = open_tap(tapname)
local raw = open_raw(ethname)
print('tap ', tapname)
print('raw ', ethname)
print('smac ', hex(smac))
print('dmac ', hex(dmac))
print('sip ', hex(sip))
print('dip ', hex(dip))
print('sid ', hex(sid))
print('did ', hex(did))
local function decap_l2tp(s)
local dmac = s:sub(1, 1+6-1)
local smac = s:sub(1+6, 1+6+6-1)
local eth_proto = s:sub(1+6+6, 1+6+6+2-1)
if eth_proto ~= '\x86\xdd' then
return nil, 'invalid eth_proto '..hex(eth_proto)
end --not ipv6
local ipv6_proto = s:sub(21, 21)
if ipv6_proto ~= '\115' then
return nil, 'invalid ipv6_proto '..hex(ipv6_proto)
end --not l2tp
local sip = s:sub(23, 23+16-1)
local dip = s:sub(23+16, 23+16+16-1)
local sid = s:sub(55, 55+4-1)
local payload = s:sub(67)
return smac, dmac, sip, dip, sid, payload
end
local function encap_l2tp(smac, dmac, sip, dip, did, payload)
local cookie = '\0\0\0\0\0\0\0\0'
local l2tp = did..cookie
local len = #payload + #l2tp
local len = string.char(bit.rshift(len, 8)) .. string.char(bit.band(len, 0xff))
local ipv6_proto = '\115' --l2tp
local maxhops = '\64'
local ipv6 = '\x60\0\0\0'..len..ipv6_proto..maxhops..sip..dip
local eth_proto = '\x86\xdd' --ipv6
local eth = dmac..smac..eth_proto
return eth..ipv6..l2tp..payload
end
while true do
if can_read(1, tap, raw) then
if can_read(0, raw) then
local s = read(raw)
local smac1, dmac1, sip1, dip1, did1, payload = decap_l2tp(s)
local accept = smac1
and smac1 == dmac
and dmac1 == smac
and dip1 == sip
and sip1 == dip
and did1 == sid
print('read ', accept and 'accepted' or
('rejected '..(smac1 and hex(dmac1) or dmac1)))
if accept then
print(' smac ', hex(smac1))
print(' dmac ', hex(dmac1))
print(' sip ', hex(sip1))
print(' dip ', hex(dip1))
print(' did ', hex(did1))
print(' # ', #payload)
end
if accept then
write(tap, payload)
end
end
if can_read(0, tap) then
local payload = read(tap)
local s = encap_l2tp(smac, dmac, sip, dip, did, payload)
print('write')
print(' smac ', hex(smac))
print(' dmac ', hex(dmac))
print(' sip ', hex(sip))
print(' dip ', hex(dip))
print(' did ', hex(did))
print(' # ', #payload)
write(raw, s)
end
end
end
tap:close()
raw:close()
|
bugfix for incredible silliness
|
bugfix for incredible silliness
|
Lua
|
apache-2.0
|
eugeneia/snabbswitch,kbara/snabb,Igalia/snabb,Igalia/snabb,Igalia/snabb,Igalia/snabbswitch,mixflowtech/logsensor,alexandergall/snabbswitch,Igalia/snabbswitch,dpino/snabb,snabbco/snabb,alexandergall/snabbswitch,mixflowtech/logsensor,mixflowtech/logsensor,Igalia/snabb,eugeneia/snabb,wingo/snabbswitch,wingo/snabb,snabbco/snabb,SnabbCo/snabbswitch,heryii/snabb,wingo/snabbswitch,eugeneia/snabb,dpino/snabbswitch,dpino/snabb,SnabbCo/snabbswitch,snabbco/snabb,heryii/snabb,wingo/snabb,snabbco/snabb,snabbco/snabb,Igalia/snabbswitch,heryii/snabb,kbara/snabb,heryii/snabb,dpino/snabb,Igalia/snabb,eugeneia/snabbswitch,kbara/snabb,SnabbCo/snabbswitch,kbara/snabb,wingo/snabb,alexandergall/snabbswitch,Igalia/snabb,eugeneia/snabb,eugeneia/snabb,dpino/snabb,Igalia/snabb,wingo/snabbswitch,Igalia/snabbswitch,dpino/snabbswitch,eugeneia/snabbswitch,eugeneia/snabb,eugeneia/snabbswitch,dpino/snabbswitch,SnabbCo/snabbswitch,alexandergall/snabbswitch,wingo/snabb,eugeneia/snabb,dpino/snabb,snabbco/snabb,Igalia/snabbswitch,kbara/snabb,mixflowtech/logsensor,mixflowtech/logsensor,dpino/snabbswitch,dpino/snabb,dpino/snabb,alexandergall/snabbswitch,snabbco/snabb,kbara/snabb,alexandergall/snabbswitch,heryii/snabb,wingo/snabbswitch,eugeneia/snabb,snabbco/snabb,alexandergall/snabbswitch,wingo/snabb,alexandergall/snabbswitch,wingo/snabb,eugeneia/snabb,Igalia/snabb,heryii/snabb
|
8c1eab280d6fd1d01b5214a8713192d0dc3b6a77
|
src/apps/ddos/ddos.lua
|
src/apps/ddos/ddos.lua
|
module(..., package.seeall)
local app = require("core.app")
local buffer = require("core.buffer")
local datagram = require("lib.protocol.datagram")
local ffi = require("ffi")
local filter = require("lib.pcap.filter")
local ipv4 = require("lib.protocol.ipv4")
local lib = require("core.lib")
local link = require("core.link")
local packet = require("core.packet")
local AF_INET = 2
local ETHERTYPE_OFFSET = 12
local ETHERTYPE_IPV6 = 0xDD86
local ETHERTYPE_IPV4 = 0x0008
DDoS = {}
-- I don't know what I'm doing
function DDoS:new (arg)
print("-- DDoS Init --")
local conf = arg and config.parse_app_arg(arg) or {}
assert(conf.block_period >= 5, "block_period must be at least 5 seconds")
local o =
{
blocklist = {},
rules = conf.rules,
block_period = conf.block_period
}
self = setmetatable(o, {__index = DDoS})
-- pre-process rules
for rule_name, rule in pairs(self.rules) do
rule.srcs = {}
-- compile the filter
local filter, errmsg = filter:new(rule.filter)
assert(filter, errmsg and ffi.string(errmsg))
rule.cfilter = filter
end
-- schedule periodic task every second
timer.activate(timer.new(
"periodic",
function () self:periodic() end,
1e9, -- every second
'repeating'
))
return self
end
function DDoS:periodic()
for src_ip, blocklist in pairs(self.blocklist) do
print("Checking block for: " .. src_ip)
if blocklist.block_until < tonumber(app.now()) then
self.blocklist[src_ip] = nil
end
end
for rule_name,rule in pairs(self.rules) do
for src_ip,src_info in pairs(rule.srcs) do
if src_info.block_until ~= nil and src_info.block_until < tonumber(app.now()) then
src_info.block_until = nil
end
end
end
end
function DDoS:push ()
local i = assert(self.input.input, "input port not found")
local o = assert(self.output.output, "output port not found")
-- TODO: should establish one rule-set per destination IP (ie the target IP we are mitigation for)
-- TODO: need to write ethernet headers on egress to match the MAC address of our "default gateway"
while not link.empty(i) and not link.full(o) do
local p = link.receive(i)
local iovec = p.iovecs[0]
-- dig out src IP from packet
-- TODO: do we really need to do ntop on this? is that an expensive operation?
-- TODO: don't use a fixed offset - it'll break badly on non-IPv4 packet :/
local src_ip = ipv4:ntop(iovec.buffer.pointer + iovec.offset + 26)
-- short cut for stuff in blocklist that is in state block
if self.blocklist[src_ip] ~= nil and self.blocklist[src_ip].action == "block" then
packet.deref(p)
else
dgram = datagram:new(p)
-- match up against our filter rules
local rule_match = self:bpf_match(p)
-- didn't match any rule, so permit it
if rule_match == nil then
link.transmit(o, p)
else
local cur_now = tonumber(app.now())
src = self:get_src(rule_match, src_ip)
src.last_time = cur_now
-- figure out rates n shit
src.pps_tokens = math.max(0,math.min(
src.pps_tokens + src.pps_rate * (cur_now - src.last_time),
src.pps_capacity
))
-- TODO: this is for pps, do the same for bps
src.pps_tokens = src.pps_tokens - 1
if src.pps_tokens <= 0 then
src.block_until = cur_now + self.block_period
self.blocklist[src_ip] = { action = "block", block_until = cur_now + self.block_period-5}
packet.deref(p)
else
link.transmit(o, p)
end
end
end
end
end
-- match against our BPF rules and return name of the match
function DDoS:bpf_match(p)
dgram = datagram:new(p)
for rule_name, rule in pairs(self.rules) do
if rule.cfilter:match(dgram:payload()) then
return rule_name
end
end
return nil
end
function DDoS:get_src(rule_match, src_ip)
-- get our data struct on that source IP
-- TODO: we need to periodically clean this data struct up so it doesn't just fill up and consume all memory
if self.rules[rule_match].srcs[src_ip] == nil then
self.rules[rule_match].srcs[src_ip] = {
last_time = nil,
pps_rate = self.rules[rule_match].pps_rate,
pps_tokens = self.rules[rule_match].pps_burst,
pps_capacity = self.rules[rule_match].pps_burst,
bucket_content = self.bucket_capacity,
bucket_capacity = self.bucket_capacity,
block_until = nil
}
end
return self.rules[rule_match].srcs[src_ip]
end
function DDoS:report()
print("-- DDoS report --")
print("Configured block period: " .. self.block_period .. " seconds")
print("Block list:")
for src_ip,blocklist in pairs(self.blocklist) do
print(" " .. src_ip .. " blocked for another " .. string.format("%0.1f", tostring(blocklist.block_until - tonumber(app.now()))) .. " seconds")
end
print("Traffic rules:")
for rule_name,rule in pairs(self.rules) do
print(" - " .. rule_name .. " [ " .. rule.filter .. " ] pps_rate: " .. rule.pps_rate)
for src_ip,src_info in pairs(rule.srcs) do
-- calculate rate of packets
if self.blocklist[src_ip] ~= nil then
-- if source is in blocklist it means we shortcut and thus don't
-- calculate pps, so we write '-'
rate = " -"
else
-- TODO: calculate real PPS rate
rate = string.format("%5.0f", src_info.pps_tokens)
end
str = string.format(" %15s last: %d tokens: %s ", src_ip, tonumber(app.now())-src_info.last_time, rate)
if src_info.block_until == nil then
str = string.format("%s %-7s", str, "allowed")
else
str = string.format("%s %-7s", str, "blocked for another " .. string.format("%0.1f", tostring(src_info.block_until - tonumber(app.now()))) .. " seconds")
end
print(str)
end
end
end
|
module(..., package.seeall)
local app = require("core.app")
local buffer = require("core.buffer")
local datagram = require("lib.protocol.datagram")
local ffi = require("ffi")
local filter = require("lib.pcap.filter")
local ipv4 = require("lib.protocol.ipv4")
local lib = require("core.lib")
local link = require("core.link")
local packet = require("core.packet")
local AF_INET = 2
local ETHERTYPE_OFFSET = 12
local ETHERTYPE_IPV6 = 0xDD86
local ETHERTYPE_IPV4 = 0x0008
DDoS = {}
-- I don't know what I'm doing
function DDoS:new (arg)
print("-- DDoS Init --")
local conf = arg and config.parse_app_arg(arg) or {}
assert(conf.block_period >= 5, "block_period must be at least 5 seconds")
local o =
{
blocklist = {},
rules = conf.rules,
block_period = conf.block_period
}
self = setmetatable(o, {__index = DDoS})
-- pre-process rules
for rule_name, rule in pairs(self.rules) do
rule.srcs = {}
-- compile the filter
local filter, errmsg = filter:new(rule.filter)
assert(filter, errmsg and ffi.string(errmsg))
rule.cfilter = filter
end
-- schedule periodic task every second
timer.activate(timer.new(
"periodic",
function () self:periodic() end,
1e9, -- every second
'repeating'
))
return self
end
function DDoS:periodic()
for src_ip, blocklist in pairs(self.blocklist) do
print("Checking block for: " .. src_ip)
if blocklist.block_until < tonumber(app.now()) then
self.blocklist[src_ip] = nil
end
end
for rule_name,rule in pairs(self.rules) do
for src_ip,src_info in pairs(rule.srcs) do
if src_info.block_until ~= nil and src_info.block_until < tonumber(app.now()) then
src_info.block_until = nil
end
end
end
end
function DDoS:push ()
local i = assert(self.input.input, "input port not found")
local o = assert(self.output.output, "output port not found")
-- TODO: should establish one rule-set per destination IP (ie the target IP we are mitigation for)
-- TODO: need to write ethernet headers on egress to match the MAC address of our "default gateway"
while not link.empty(i) and not link.full(o) do
local p = link.receive(i)
local iovec = p.iovecs[0]
-- dig out src IP from packet
-- TODO: do we really need to do ntop on this? is that an expensive operation?
-- TODO: don't use a fixed offset - it'll break badly on non-IPv4 packet :/
local src_ip = ipv4:ntop(iovec.buffer.pointer + iovec.offset + 26)
-- short cut for stuff in blocklist that is in state block
if self.blocklist[src_ip] ~= nil and self.blocklist[src_ip].action == "block" then
packet.deref(p)
else
dgram = datagram:new(p)
-- match up against our filter rules
local rule_match = self:bpf_match(p)
-- didn't match any rule, so permit it
if rule_match == nil then
link.transmit(o, p)
else
local cur_now = tonumber(app.now())
src = self:get_src(rule_match, src_ip)
-- figure out rates n shit
src.pps_tokens = math.max(0,math.min(
src.pps_tokens + src.pps_rate * (cur_now - src.last_time),
src.pps_capacity
))
src.last_time = cur_now
-- TODO: this is for pps, do the same for bps
src.pps_tokens = src.pps_tokens - 1
if src.pps_tokens <= 0 then
src.block_until = cur_now + self.block_period
self.blocklist[src_ip] = { action = "block", block_until = cur_now + self.block_period-5}
packet.deref(p)
else
link.transmit(o, p)
end
end
end
end
end
-- match against our BPF rules and return name of the match
function DDoS:bpf_match(p)
dgram = datagram:new(p)
for rule_name, rule in pairs(self.rules) do
if rule.cfilter:match(dgram:payload()) then
return rule_name
end
end
return nil
end
function DDoS:get_src(rule_match, src_ip)
-- get our data struct on that source IP
-- TODO: we need to periodically clean this data struct up so it doesn't just fill up and consume all memory
if self.rules[rule_match].srcs[src_ip] == nil then
self.rules[rule_match].srcs[src_ip] = {
last_time = tonumber(app.now()),
pps_rate = self.rules[rule_match].pps_rate,
pps_tokens = self.rules[rule_match].pps_burst,
pps_capacity = self.rules[rule_match].pps_burst,
bucket_content = self.bucket_capacity,
bucket_capacity = self.bucket_capacity,
block_until = nil
}
end
return self.rules[rule_match].srcs[src_ip]
end
function DDoS:report()
print("-- DDoS report --")
local s_i = link.stats(self.input.input)
local s_o = link.stats(self.output.output)
print("Rx: " .. s_i.rxpackets .. " packets / " .. s_i.rxbytes .. " bytes")
print("Tx: " .. s_o.txpackets .. " packets / " .. s_o.txbytes .. " bytes / " .. s_o.txdrop .. " packet drops")
print("Configured block period: " .. self.block_period .. " seconds")
print("Block list:")
for src_ip,blocklist in pairs(self.blocklist) do
print(" " .. src_ip .. " blocked for another " .. string.format("%0.1f", tostring(blocklist.block_until - tonumber(app.now()))) .. " seconds")
end
print("Traffic rules:")
for rule_name,rule in pairs(self.rules) do
print(" - " .. rule_name .. " [ " .. rule.filter .. " ] pps_rate: " .. rule.pps_rate)
for src_ip,src_info in pairs(rule.srcs) do
-- calculate rate of packets
if self.blocklist[src_ip] ~= nil then
-- if source is in blocklist it means we shortcut and thus don't
-- calculate pps, so we write '-'
rate = " -"
else
-- TODO: calculate real PPS rate
rate = string.format("%5.0f", src_info.pps_tokens)
end
str = string.format(" %15s last: %d tokens: %s ", src_ip, tonumber(app.now())-src_info.last_time, rate)
if src_info.block_until == nil then
str = string.format("%s %-7s", str, "allowed")
else
str = string.format("%s %-7s", str, "blocked for another " .. string.format("%0.1f", tostring(src_info.block_until - tonumber(app.now()))) .. " seconds")
end
print(str)
end
end
end
|
Fix bug and add stats
|
Fix bug and add stats
|
Lua
|
apache-2.0
|
plajjan/snabbswitch,plajjan/snabbswitch,plajjan/snabbswitch,plajjan/snabbswitch
|
435640f3500a1b4ba4d5487cef64f8256fd0483c
|
pud/view/GameCam.lua
|
pud/view/GameCam.lua
|
require 'pud.util'
local Class = require 'lib.hump.class'
local Camera = require 'lib.hump.camera'
local vector = require 'lib.hump.vector'
local Rect = require 'pud.kit.Rect'
local _zoomLevels = {1, 0.5, 0.25}
local _isVector = function(...)
local n = select('#',...)
for i=1,n do
local v = select(i,...)
assert(vector.isvector(v), 'vector expected, got %s (%s)',
tostring(v), type(v))
end
return n > 0
end
local GameCam = Class{name='GameCam',
function(self, v, zoom)
v = v or vector(0,0)
if _isVector(v) then
self._zoom = math.max(1, math.min(#_zoomLevels, zoom or 1))
self._home = v
self._cam = Camera(v, _zoomLevels[self._zoom])
end
end
}
-- destructor
function GameCam:destroy()
self._cam = nil
self._home = nil
self._zoom = nil
self._target = nil
self._targetFuncs.setX = nil
self._targetFuncs.setY = nil
self._targetFuncs.setCenter = nil
self._targetFuncs.setPosition = nil
self._targetFuncs = nil
for k,v in pairs(self._limits) do self._limits[k] = nil end
self._limits = nil
end
function GameCam:_setAnimating(b)
verify('boolean', b)
self._isAnimating = b
end
function GameCam:isAnimating()
return self._isAnimating == true
end
-- zoom in smoothly
function GameCam:zoomIn()
if self._zoom > 1 and not self:isAnimating() then
self._zoom = self._zoom - 1
self:_setAnimating(true)
tween(0.25, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outBack',
self._setAnimating, self, false)
else
self:_bumpZoom(1.1)
end
end
-- zoom out smoothly
function GameCam:zoomOut()
if self._zoom < #_zoomLevels and not self:isAnimating() then
self._zoom = self._zoom + 1
self:_setAnimating(true)
tween(0.25, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outBack',
self._setAnimating, self, false)
else
self:_bumpZoom(0.9)
end
end
-- bump the zoom but don't change it
function GameCam:_bumpZoom(mult)
if not self:isAnimating() then
self:_setAnimating(true)
tween(0.1, self._cam, {zoom = _zoomLevels[self._zoom] * mult}, 'inQuad',
tween, 0.1, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outQuad',
self._setAnimating, self, false)
end
end
-- return zoom level
function GameCam:getZoom()
return self._zoom, _zoomLevels[self._zoom]
end
-- follow a target Rect
function GameCam:followTarget(rect)
assert(rect and rect.is_a and rect:is_a(Rect),
'GameCam can only follow a Rect (tried to follow %s)', tostring(rect))
self._target = rect
self._targetFuncs = {
setX = rect.setX,
setY = rect.setY,
setPosition = rect.setPosition,
setCenter = rect.setCenter,
}
local function _follow(self, theRect)
self._cam.pos = theRect:getCenterVector()
self:_correctCam()
end
rect.setX = function(theRect, x)
self._targetFuncs.setX(theRect, x)
_follow(self, theRect)
end
rect.setY = function(theRect, y)
self._targetFuncs.setY(theRect, y)
_follow(self, theRect)
end
rect.setPosition = function(theRect, x, y)
self._targetFuncs.setPosition(theRect, x, y)
_follow(self, theRect)
end
rect.setCenter = function(theRect, x, y, flag)
self._targetFuncs.setCenter(theRect, x, y, flag)
_follow(self, theRect)
end
end
-- unfollow a target Rect
function GameCam:unfollowTarget()
if self._target then
self._target.setX = self._targetFuncs.setX
self._target.setY = self._targetFuncs.setY
self._target.setPosition = self._targetFuncs.setPosition
self._target.setCenter = self._targetFuncs.setCenter
self._targetFuncs.setX = nil
self._targetFuncs.setY = nil
self._targetFuncs.setPosition = nil
self._targetFuncs.setCenter = nil
self._target = nil
end
end
-- center on initial vector
function GameCam:home()
self:unfollowTarget()
self._cam.pos = self._home
self:_correctCam()
end
-- change home vector
function GameCam:setHome(home)
if _isVector(home) then
self._home = home
end
end
-- translate along v
function GameCam:translate(v)
if _isVector(v) and not self:isAnimating() then
local target = self._cam.pos + v
if self:_shouldTranslate(v) then
self:_setAnimating(true)
tween(0.15, self._cam.pos, target, 'outQuint',
self._setAnimating, self, false)
end
end
end
function GameCam:_shouldTranslate(v)
local pos = self._cam.pos + v
return not (pos.x > self._limits.max.x or pos.x < self._limits.min.x
or pos.y > self._limits.max.y or pos.y < self._limits.min.y)
end
-- set x and y limits for camera
function GameCam:setLimits(minV, maxV)
if _isVector(minV, maxV) then
self._limits = {min = minV, max = maxV}
end
end
-- correct the camera position if it is beyond the limits
function GameCam:_correctCam()
if self._cam.pos.x > self._limits.max.x then
self._cam.pos.x = self._limits.max.x
end
if self._cam.pos.x < self._limits.min.x then
self._cam.pos.x = self._limits.min.x
end
if self._cam.pos.y > self._limits.max.y then
self._cam.pos.y = self._limits.max.y
end
if self._cam.pos.y < self._limits.min.y then
self._cam.pos.y = self._limits.min.y
end
end
-- camera draw callbacks
function GameCam:predraw() self._cam:predraw() end
function GameCam:postdraw() self._cam:postdraw() end
function GameCam:draw(...) self._cam:draw(...) end
-- the class
return GameCam
|
require 'pud.util'
local Class = require 'lib.hump.class'
local Camera = require 'lib.hump.camera'
local vector = require 'lib.hump.vector'
local Rect = require 'pud.kit.Rect'
local _zoomLevels = {1, 0.5, 0.25}
local _isVector = function(...)
local n = select('#',...)
for i=1,n do
local v = select(i,...)
assert(vector.isvector(v), 'vector expected, got %s (%s)',
tostring(v), type(v))
end
return n > 0
end
local GameCam = Class{name='GameCam',
function(self, v, zoom)
v = v or vector(0,0)
if _isVector(v) then
self._zoom = math.max(1, math.min(#_zoomLevels, zoom or 1))
self._home = v
self._cam = Camera(v, _zoomLevels[self._zoom])
end
end
}
-- destructor
function GameCam:destroy()
self:unfollowTarget()
self._cam = nil
self._home = nil
self._zoom = nil
for k,v in pairs(self._limits) do self._limits[k] = nil end
self._limits = nil
end
function GameCam:_setAnimating(b)
verify('boolean', b)
self._isAnimating = b
end
function GameCam:isAnimating()
return self._isAnimating == true
end
-- zoom in smoothly
function GameCam:zoomIn()
if self._zoom > 1 and not self:isAnimating() then
self._zoom = self._zoom - 1
self:_setAnimating(true)
tween(0.25, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outBack',
self._setAnimating, self, false)
else
self:_bumpZoom(1.1)
end
end
-- zoom out smoothly
function GameCam:zoomOut()
if self._zoom < #_zoomLevels and not self:isAnimating() then
self._zoom = self._zoom + 1
self:_setAnimating(true)
tween(0.25, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outBack',
self._setAnimating, self, false)
else
self:_bumpZoom(0.9)
end
end
-- bump the zoom but don't change it
function GameCam:_bumpZoom(mult)
if not self:isAnimating() then
self:_setAnimating(true)
tween(0.1, self._cam, {zoom = _zoomLevels[self._zoom] * mult}, 'inQuad',
tween, 0.1, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outQuad',
self._setAnimating, self, false)
end
end
-- return zoom level
function GameCam:getZoom()
return self._zoom, _zoomLevels[self._zoom]
end
-- follow a target Rect
function GameCam:followTarget(rect)
assert(rect and rect.is_a and rect:is_a(Rect),
'GameCam can only follow a Rect (tried to follow %s)', tostring(rect))
self._target = rect
self._targetFuncs = {
setX = rect.setX,
setY = rect.setY,
setPosition = rect.setPosition,
setCenter = rect.setCenter,
}
local function _follow(self, theRect)
self._cam.pos = theRect:getCenterVector()
self:_correctCam()
end
rect.setX = function(theRect, x)
self._targetFuncs.setX(theRect, x)
_follow(self, theRect)
end
rect.setY = function(theRect, y)
self._targetFuncs.setY(theRect, y)
_follow(self, theRect)
end
rect.setPosition = function(theRect, x, y)
self._targetFuncs.setPosition(theRect, x, y)
_follow(self, theRect)
end
rect.setCenter = function(theRect, x, y, flag)
self._targetFuncs.setCenter(theRect, x, y, flag)
_follow(self, theRect)
end
end
-- unfollow a target Rect
function GameCam:unfollowTarget()
if self._target then
self._target.setX = self._targetFuncs.setX
self._target.setY = self._targetFuncs.setY
self._target.setPosition = self._targetFuncs.setPosition
self._target.setCenter = self._targetFuncs.setCenter
self._targetFuncs.setX = nil
self._targetFuncs.setY = nil
self._targetFuncs.setPosition = nil
self._targetFuncs.setCenter = nil
self._targetFuncs = nil
self._target = nil
end
end
-- center on initial vector
function GameCam:home()
self:unfollowTarget()
self._cam.pos = self._home
self:_correctCam()
end
-- change home vector
function GameCam:setHome(home)
if _isVector(home) then
self._home = home
end
end
-- translate along v
function GameCam:translate(v)
if _isVector(v) and not self:isAnimating() then
local target = self._cam.pos + v
if self:_shouldTranslate(v) then
self:_setAnimating(true)
tween(0.15, self._cam.pos, target, 'outQuint',
self._setAnimating, self, false)
end
end
end
function GameCam:_shouldTranslate(v)
local pos = self._cam.pos + v
return not (pos.x > self._limits.max.x or pos.x < self._limits.min.x
or pos.y > self._limits.max.y or pos.y < self._limits.min.y)
end
-- set x and y limits for camera
function GameCam:setLimits(minV, maxV)
if _isVector(minV, maxV) then
self._limits = {min = minV, max = maxV}
end
end
-- correct the camera position if it is beyond the limits
function GameCam:_correctCam()
if self._cam.pos.x > self._limits.max.x then
self._cam.pos.x = self._limits.max.x
end
if self._cam.pos.x < self._limits.min.x then
self._cam.pos.x = self._limits.min.x
end
if self._cam.pos.y > self._limits.max.y then
self._cam.pos.y = self._limits.max.y
end
if self._cam.pos.y < self._limits.min.y then
self._cam.pos.y = self._limits.min.y
end
end
-- camera draw callbacks
function GameCam:predraw() self._cam:predraw() end
function GameCam:postdraw() self._cam:postdraw() end
function GameCam:draw(...) self._cam:draw(...) end
-- the class
return GameCam
|
fix destructor
|
fix destructor
|
Lua
|
mit
|
scottcs/wyx
|
39678e68b35c83317c5dcd04513dcb0799e2a99b
|
src/ui/MainMenuView.lua
|
src/ui/MainMenuView.lua
|
local class = require 'lib/30log'
local GameObject = require 'src/GameObject'
local Transform = require 'src/component/Transform'
local Renderable = require 'src/component/Renderable'
local Interfaceable = require 'src/component/Interfaceable'
local Polygon = require 'src/datatype/Polygon'
local TouchDelegate = require 'src/datatype/TouchDelegate'
local MainMenuView = class("MainMenuView", {
root = nil,
is_attached = false,
scenegraph = nil
})
function MainMenuView:init (registry, scenegraph)
self.root = registry:add(GameObject:new("mmv_root", {
Transform:new(0,0)
}))
self.scenegraph = scenegraph
self.registry = registry
local save_button_handler = TouchDelegate:new()
save_button_handler:setHandler('onTouch', function(this, x, y)
print('Button pressed: save')
end)
local load_button_handler = TouchDelegate:new()
load_button_handler:setHandler('onTouch', function(this, x, y)
print('Button pressed: load. Loading disabled for the moment')
self:hide()
end)
local return_button_handler = TouchDelegate:new()
return_button_handler:setHandler('onTouch', function(this, x, y)
self.scenegraph:detach(self.root)
self.is_attached = false
print('Button pressed: return')
end)
local quit_button_handler = TouchDelegate:new()
quit_button_handler:setHandler('onTouch', function(this, x, y)
love.event.quit()
end)
local switch_next_handler = TouchDelegate:new()
switch_next_handler:setHandler('onTouch', function(this, x, y)
registry:publish("ui/debug_nextscene")
self:hide()
end)
local switch_prev_handler = TouchDelegate:new()
switch_prev_handler:setHandler('onTouch', function(this, x, y)
registry:publish("ui/debug_prevscene")
self:hide()
end)
local Block_Below_Delegate = TouchDelegate:new()
Block_Below_Delegate:setHandler('onTouch', function(this, x, y)
print('Blocking event')
return true
end)
local gray_out = registry:add(GameObject:new("mmv_grayout", {
Transform:new(0,0),
Renderable:new(
Polygon:new({w = 1200, h = 800}),
nil,
{0,0,0,128},
math.floor(math.random()*100000)),
Interfaceable:new(
Polygon:new({w = 1200, h = 800}),
Block_Below_Delegate)
}))
local bg_rect = registry:add(GameObject:new("mmv_bgrect", {
Transform:new(400,100),
Renderable:new(
Polygon:new({w = 400, h = 600}),
nil,
{128, 60, 128})
}))
local title_panel = registry:add(GameObject:new("mmv_title",{
Transform:new(50,20),
Renderable:new(
Polygon:new({w = 300, h = 80}),
nil,
{200,100,200},
"HELIOS 2400 DEBUG MENU")
}))
local saveload_panel = registry:add(GameObject:new("mmv_saveloadpanel",{
Transform:new(50,120),
Renderable:new(
Polygon:new({w = 300, h = 200}),
nil,
{200,100,200})
}))
local save_btn = registry:add(GameObject:new("mmv_save_btn",{
Transform:new(10, 10),
Renderable:new(
Polygon:new({w = 280, h = 30}),
nil,
{150,100,180},
"Save Game"),
Interfaceable:new(
Polygon:new({w = 280, h = 30}),
save_button_handler)
}))
local load_btn = registry:add(GameObject:new("mmv_load_btn",{
Transform:new(10, 50),
Renderable:new(
Polygon:new({w = 280, h = 30}),
nil,
{150,100,180},
"Load Game"),
Interfaceable:new(
Polygon:new({w = 280, h = 30}),
load_button_handler)
}))
local quit_btn = registry:add(GameObject:new("mmv_quit_btn",{
Transform:new(10,90),
Renderable:new(
Polygon:new({w = 280, h = 30}),
nil,
{150,100,180},
"Quit Game"),
Interfaceable:new(
Polygon:new({w = 280, h = 30}),
quit_button_handler)
}))
local return_btn = registry:add(GameObject:new("mmv_return_btn",{
Transform:new(10,150),
Renderable:new(
Polygon:new({w = 280, h = 30}),
nil,
{150,100,180},
"Return (or press Escape)"),
Interfaceable:new(
Polygon:new({w = 280, h = 30}),
return_button_handler)
}))
local view_switcher_panel = registry:add(GameObject:new("mmv_switcher_panel",{
Transform:new(50,340),
Renderable:new(
Polygon:new({w = 300, h = 50}),
nil,
{200,100,200},
nil)
}))
local switch_prev_btn = registry:add(GameObject:new("mmv_switchprev_btn",{
Transform:new(10,10),
Renderable:new(
Polygon:new({0,15 , 30,-5 , 30,0 , 135,0 , 135,30 , 30,30 , 30,35}),
nil,
{150,100,180},
"Previous View"),
Interfaceable:new(
Polygon:new({0,15 , 30,-5 , 30,0 , 135,0 , 135,30 , 30,30 , 30,35}),
switch_prev_handler)
}))
local switch_next_btn = registry:add(GameObject:new("mmv_switchnext_btn",{
Transform:new(155,10),
Renderable:new(
Polygon:new({0,0 , 105,0 , 105,-5 , 135,15 , 105,35 , 105,30 , 0,30}),
nil,
{150,100,180},
"Next View"),
Interfaceable:new(
Polygon:new({0,0 , 105,0 , 105,-5 , 135,15 , 105,35 , 105,30 , 0,30}),
switch_next_handler)
}))
self.scenegraph:attach(self.root, nil)
self.scenegraph:attachAll({gray_out, bg_rect}, self.root)
self.scenegraph:attachAll({title_panel, saveload_panel, view_switcher_panel}, bg_rect)
self.scenegraph:attachAll({save_btn, load_btn, return_btn, quit_btn}, saveload_panel)
self.scenegraph:attachAll({switch_next_btn, switch_prev_btn}, view_switcher_panel)
self.scenegraph:detach(self.root)
end
function MainMenuView:show( attachTo )
if not self.is_attached then
self.scenegraph:attach(self.root, attachTo)
self.is_attached = true
end
end
function MainMenuView:hide()
if self.is_attached then
self.scenegraph:detach(self.root)
self.is_attached = false
end
end
return MainMenuView
|
local class = require 'lib/30log'
local GameObject = require 'src/GameObject'
local Transform = require 'src/component/Transform'
local Renderable = require 'src/component/Renderable'
local Interfaceable = require 'src/component/Interfaceable'
local Polygon = require 'src/datatype/Polygon'
local TouchDelegate = require 'src/datatype/TouchDelegate'
local MainMenuView = class("MainMenuView", {
root = nil,
is_attached = false,
scenegraph = nil
})
function MainMenuView:init (registry, scenegraph)
self.root = registry:add(GameObject:new("mmv_root", {
Transform:new(0,0)
}))
self.scenegraph = scenegraph
self.registry = registry
local save_button_handler = TouchDelegate:new()
save_button_handler:setHandler('onTouch', function(this, x, y)
print('Button pressed: save')
end)
local load_button_handler = TouchDelegate:new()
load_button_handler:setHandler('onTouch', function(this, x, y)
print('Button pressed: load. Loading disabled for the moment')
self:hide()
end)
local return_button_handler = TouchDelegate:new()
return_button_handler:setHandler('onTouch', function(this, x, y)
self.scenegraph:detach(self.root)
self.is_attached = false
print('Button pressed: return')
end)
local quit_button_handler = TouchDelegate:new()
quit_button_handler:setHandler('onTouch', function(this, x, y)
love.event.quit()
end)
local switch_next_handler = TouchDelegate:new()
switch_next_handler:setHandler('onTouch', function(this, x, y)
registry:publish("ui/debug_nextscene")
self:hide()
end)
local switch_prev_handler = TouchDelegate:new()
switch_prev_handler:setHandler('onTouch', function(this, x, y)
registry:publish("ui/debug_prevscene")
self:hide()
end)
local Block_Below_Delegate = TouchDelegate:new()
Block_Below_Delegate:setHandler('onTouch', function(this, x, y)
print('Blocking event')
return true
end)
local windowW = love.graphics:getWidth()
local windowH = love.graphics:getHeight()
local gray_out = registry:add(GameObject:new("mmv_grayout", {
Transform:new(0,0),
Renderable:new(
Polygon:new({w = windowW, h = windowH}),
nil,
{0,0,0,128},
math.floor(math.random()*100000)),
Interfaceable:new(
Polygon:new({w = windowW, h = windowH}),
Block_Below_Delegate)
}))
local panelW = 400
local panelH = 600
local panelX = ( windowW - panelW ) / 2
local panelY = ( windowH - panelH ) / 2
local margin = 10
local bg_rect = registry:add(GameObject:new("mmv_bgrect", {
Transform:new(panelX,panelY),
Renderable:new(
Polygon:new({w = panelW, h = panelH}),
nil,
{128, 60, 128})
}))
local subPanelW = panelW - 2 * margin
local buttonW = subPanelW - 2 * margin
local titleH = 40
local title_panel = registry:add(GameObject:new("mmv_title",{
Transform:new(margin,margin),
Renderable:new(
Polygon:new({w = subPanelW, h = titleH}),
nil,
{200,100,200},
"HELIOS 2400 DEBUG MENU")
}))
local saveLoadY = titleH + 2 * margin
local buttonH = 30
local bigMargin = 40
local saveLoadH = buttonH * 4 + margin * 4 + bigMargin
local saveload_panel = registry:add(GameObject:new("mmv_saveloadpanel",{
Transform:new(margin,saveLoadY),
Renderable:new(
Polygon:new({w = subPanelW, h = saveLoadH}),
nil,
{200,100,200})
}))
local save_btn = registry:add(GameObject:new("mmv_save_btn",{
Transform:new(margin, margin),
Renderable:new(
Polygon:new({w = buttonW, h = buttonH}),
nil,
{150,100,180},
"Save Game"),
Interfaceable:new(
Polygon:new({w = buttonW, h = buttonH}),
save_button_handler)
}))
local load_btn = registry:add(GameObject:new("mmv_load_btn",{
Transform:new(margin, margin + buttonH + margin),
Renderable:new(
Polygon:new({w = buttonW, h = buttonH}),
nil,
{150,100,180},
"Load Game"),
Interfaceable:new(
Polygon:new({w = buttonW, h = buttonH}),
load_button_handler)
}))
local quit_btn = registry:add(GameObject:new("mmv_quit_btn",{
Transform:new(margin , margin + (buttonH + margin) * 2),
Renderable:new(
Polygon:new({w = buttonW, h = buttonH}),
nil,
{150,100,180},
"Quit Game"),
Interfaceable:new(
Polygon:new({w = buttonW, h = buttonH}),
quit_button_handler)
}))
local return_btn = registry:add(GameObject:new("mmv_return_btn",{
Transform:new(margin , margin + buttonH * 3 + margin * 2 + bigMargin),
Renderable:new(
Polygon:new({w = buttonW, h = buttonH}),
nil,
{150,100,180},
"Return (or press Escape)"),
Interfaceable:new(
Polygon:new({w = buttonW, h = buttonH}),
return_button_handler)
}))
local view_switcher_panelH = buttonH + 2 * margin
local view_switcher_panelY = saveLoadY + saveLoadH + margin
local view_switcher_panel = registry:add(GameObject:new("mmv_switcher_panel",{
Transform:new(margin,view_switcher_panelY),
Renderable:new(
Polygon:new({w = subPanelW, h = view_switcher_panelH}),
nil,
{200,100,200},
nil)
}))
local switch_prev_btn = registry:add(GameObject:new("mmv_switchprev_btn",{
Transform:new(10,10),
Renderable:new(
Polygon:new({0,15 , 30,-5 , 30,0 , 135,0 , 135,30 , 30,30 , 30,35}),
nil,
{150,100,180},
"Previous View"),
Interfaceable:new(
Polygon:new({0,15 , 30,-5 , 30,0 , 135,0 , 135,30 , 30,30 , 30,35}),
switch_prev_handler)
}))
local switch_next_btn = registry:add(GameObject:new("mmv_switchnext_btn",{
Transform:new(155,10),
Renderable:new(
Polygon:new({0,0 , 105,0 , 105,-5 , 135,15 , 105,35 , 105,30 , 0,30}),
nil,
{150,100,180},
"Next View"),
Interfaceable:new(
Polygon:new({0,0 , 105,0 , 105,-5 , 135,15 , 105,35 , 105,30 , 0,30}),
switch_next_handler)
}))
self.scenegraph:attach(self.root, nil)
self.scenegraph:attachAll({gray_out, bg_rect}, self.root)
self.scenegraph:attachAll({title_panel, saveload_panel, view_switcher_panel}, bg_rect)
self.scenegraph:attachAll({save_btn, load_btn, return_btn, quit_btn}, saveload_panel)
self.scenegraph:attachAll({switch_next_btn, switch_prev_btn}, view_switcher_panel)
self.scenegraph:detach(self.root)
end
function MainMenuView:show( attachTo )
if not self.is_attached then
self.scenegraph:attach(self.root, attachTo)
self.is_attached = true
end
end
function MainMenuView:hide()
if self.is_attached then
self.scenegraph:detach(self.root)
self.is_attached = false
end
end
return MainMenuView
|
fixed main menu scaling
|
fixed main menu scaling
|
Lua
|
mit
|
Sewerbird/Helios2400,Sewerbird/Helios2400,Sewerbird/Helios2400
|
24038a8a6a70a6d0f28099479504487b6042bdb0
|
premake4.lua
|
premake4.lua
|
------------------------------------------------------------------
-- premake 4 Pyros3D solution
------------------------------------------------------------------
solution "Pyros3D"
-- Make Directories
os.mkdir("bin");
os.mkdir("build");
os.mkdir("include");
os.mkdir("libs");
newoption {
trigger = "framework",
value = "API",
description = "Choose a particular API for window management",
allowed = {
{ "sfml", "SFML 2.1 - Default" },
{ "sdl", "SDL 2.0" }
}
}
if _OPTIONS["framework"]=="sdl" then
framework = "_SDL";
libsToLink = { "SDL2", "SDL2_image" }
excludes { "**/SFML/**" }
end
if _OPTIONS["framework"]=="sfml" or not _OPTIONS["framework"] then
framework = "_SFML";
libsToLink = { "sfml-graphics", "sfml-window", "sfml-system" }
excludes { "**/SDL/**" }
end
newoption {
trigger = "bin",
value = "output",
description = "Choose a output binary file",
allowed = {
{ "static", "Static Library - Default" },
{ "shared", "Shared Library" }
}
}
newoption {
trigger = "examples",
description = "Build Demos Examples"
}
newoption {
trigger = "log",
description = "Log Output",
allowed = {
{ "none", "No log - Default" },
{ "console", "Log to Console"},
{ "file", "Log to File"}
}
}
------------------------------------------------------------------
-- setup common settings
------------------------------------------------------------------
configurations { "Debug", "Release" }
platforms { "x32" }
location "build"
rootdir = "."
libName = "PyrosEngine"
project "PyrosEngine"
targetdir "libs"
if _OPTIONS["bin"]=="shared" then
kind "SharedLib"
else
kind "StaticLib"
end
language "C++"
files { "src/**.h", "src/**.cpp" }
includedirs { "include/" }
defines({"UNICODE", "GLEW_STATIC"})
defines({framework})
if _OPTIONS["log"]=="console" then
defines({"LOG_TO_CONSOLE"})
else
if _OPTIONS["log"]=="file" then
defines({"LOG_TO_FILE"})
else
defines({"LOG_DISABLE"})
end
end
configuration "Debug"
targetname(libName.."d")
defines({"_DEBUG"})
flags { "Symbols" }
configuration "Release"
flags { "Optimize" }
function BuildDemo(demoPath, demoName)
project (demoName)
kind "ConsoleApp"
language "C++"
files { demoPath.."/**.h", demoPath.."/**.cpp", demoPath.."/../WindowManagers/**.cpp", demoPath.."/../WindowManagers/**.h" }
includedirs { "include/", "src/" }
defines({"UNICODE", "GLEW_STATIC"})
defines({framework});
configuration "Debug"
defines({"_DEBUG"})
targetdir ("bin/debug/examples/"..demoName)
if os.get() == "linux" then
links { libName.."d", "GL", "GLU", "GLEW", libsToLink, "freeimage", "BulletCollision", "BulletDynamics", "BulletMultiThreaded", "LinearMath", "MiniCL", "freetype", "pthread", "z" }
linkoptions { "-L../libs -L/usr/local/lib -Wl,-rpath,../../../../libs" }
end
if os.get() == "windows" then
links { libName.."d", "opengl32", "glu32", "glew", libsToLink, "freeimage", "BulletCollision", "BulletDynamics", "LinearMath", "freetype", "pthread" }
libdirs { rootdir.."/libs" }
end
if os.get() == "macosx" then
links { libName.."d", "freeimage", "OpenGL.framework", "Cocoa.framework", "Carbon.framework", "GLEW.framework", "freetype.framework", "BulletCollision.framework", "BulletDynamics.framework", "BulletMultiThreaded.framework", "BulletSoftBody.framework", "LinearMath.framework", "MiniCL.framework" }
libdirs { rootdir.."/libs" }
end
flags { "Symbols" }
configuration "Release"
targetdir ("bin/release/examples/"..demoName)
if os.get() == "linux" then
links { libName, "GL", "GLU", "GLEW", libsToLink, "freeimage", "BulletCollision", "BulletDynamics", "BulletMultiThreaded", "LinearMath", "MiniCL", "freetype", "pthread", "z" }
linkoptions { "-L../libs -L/usr/local/lib -Wl,-rpath,../../../../libs" }
end
if os.get() == "windows" then
links { libName, "opengl32", "glu32", "glew", libsToLink, "freeimage", "BulletCollision", "BulletDynamics", "LinearMath", "freetype", "pthread" }
libdirs { rootdir.."/libs" }
end
if os.get() == "macosx" then
links { libName, "freeimage", "OpenGL.framework", "Cocoa.framework", "Carbon.framework", "GLEW.framework", "freetype.framework", "SFML.framework", "sfml-system.framework", "sfml-window.framework", "sfml-graphics.framework", "BulletCollision.framework", "BulletDynamics.framework", "BulletMultiThreaded.framework", "BulletSoftBody.framework", "LinearMath.framework", "MiniCL.framework" }
libdirs { rootdir.."/libs" }
end
flags { "Optimize" }
end;
if _OPTIONS["examples"] then
BuildDemo("examples/RotatingCube", "RotatingCube");
BuildDemo("examples/RotatingTexturedCube", "RotatingTexturedCube");
BuildDemo("examples/RotatingCubeWithLighting", "RotatingCubeWithLighting");
BuildDemo("examples/RotatingCubeWithLightingAndShadow", "RotatingCubeWithLightingAndShadow");
BuildDemo("examples/SimplePhysics", "SimplePhysics");
BuildDemo("examples/TextRendering", "TextRendering");
BuildDemo("examples/CustomMaterial", "CustomMaterial");
BuildDemo("examples/PickingWithPainterMethod", "PickingWithPainterMethod");
BuildDemo("examples/SkeletonAnimation", "SkeletonAnimation");
BuildDemo("examples/RacingGame", "RacingGame");
end
|
------------------------------------------------------------------
-- premake 4 Pyros3D solution
------------------------------------------------------------------
solution "Pyros3D"
-- Make Directories
os.mkdir("bin");
os.mkdir("build");
os.mkdir("include");
os.mkdir("libs");
newoption {
trigger = "framework",
value = "API",
description = "Choose a particular API for window management",
allowed = {
{ "sfml", "SFML 2.1 - Default" },
{ "sdl", "SDL 2.0" }
}
}
newoption {
trigger = "bin",
value = "output",
description = "Choose a output binary file",
allowed = {
{ "static", "Static Library - Default" },
{ "shared", "Shared Library" }
}
}
newoption {
trigger = "examples",
description = "Build Demos Examples"
}
newoption {
trigger = "log",
description = "Log Output",
allowed = {
{ "none", "No log - Default" },
{ "console", "Log to Console"},
{ "file", "Log to File"}
}
}
if _OPTIONS["framework"]=="sdl" then
framework = "_SDL";
libsToLink = { "SDL2", "SDL2_image" }
excludes { "**/SFML/**" }
end
if _OPTIONS["framework"]=="sfml" or not _OPTIONS["framework"] then
framework = "_SFML";
libsToLink = { "sfml-graphics", "sfml-window", "sfml-system" }
excludes { "**/SDL/**" }
end
------------------------------------------------------------------
-- setup common settings
------------------------------------------------------------------
configurations { "Debug", "Release" }
platforms { "x32" }
location "build"
rootdir = "."
libName = "PyrosEngine"
project "PyrosEngine"
targetdir "libs"
if _OPTIONS["bin"]=="shared" then
kind "SharedLib"
else
kind "StaticLib"
end
language "C++"
files { "src/**.h", "src/**.cpp" }
includedirs { "include/" }
defines({"UNICODE", "GLEW_STATIC"})
if _OPTIONS["log"]=="console" then
defines({"LOG_TO_CONSOLE"})
else
if _OPTIONS["log"]=="file" then
defines({"LOG_TO_FILE"})
else
defines({"LOG_DISABLE"})
end
end
configuration "Debug"
targetname(libName.."d")
defines({"_DEBUG"})
flags { "Symbols" }
configuration "Release"
flags { "Optimize" }
targetname(libName)
function BuildDemo(demoPath, demoName)
project (demoName)
kind "ConsoleApp"
language "C++"
files { demoPath.."/**.h", demoPath.."/**.cpp", demoPath.."/../WindowManagers/**.cpp", demoPath.."/../WindowManagers/**.h" }
includedirs { "include/", "src/" }
defines({"UNICODE", "GLEW_STATIC"})
defines({framework});
configuration "Debug"
defines({"_DEBUG"})
targetdir ("bin/debug/examples/"..demoName)
if os.get() == "linux" then
links { libName.."d", "GL", "GLU", "GLEW", libsToLink, "freeimage", "BulletCollision", "BulletDynamics", "BulletMultiThreaded", "LinearMath", "MiniCL", "freetype", "pthread", "z" }
linkoptions { "-L../libs -L/usr/local/lib -Wl,-rpath,../../../../libs" }
end
if os.get() == "windows" then
links { libName.."d", "opengl32", "glu32", "glew", libsToLink, "freeimage", "BulletCollision", "BulletDynamics", "LinearMath", "freetype", "pthread" }
libdirs { rootdir.."/libs" }
end
if os.get() == "macosx" then
links { libName.."d", "freeimage", "OpenGL.framework", "Cocoa.framework", "Carbon.framework", "GLEW.framework", "freetype.framework", "BulletCollision.framework", "BulletDynamics.framework", "BulletMultiThreaded.framework", "BulletSoftBody.framework", "LinearMath.framework", "MiniCL.framework" }
libdirs { rootdir.."/libs" }
end
flags { "Symbols" }
configuration "Release"
targetdir ("bin/release/examples/"..demoName)
if os.get() == "linux" then
links { libName, "GL", "GLU", "GLEW", libsToLink, "freeimage", "BulletCollision", "BulletDynamics", "BulletMultiThreaded", "LinearMath", "MiniCL", "freetype", "pthread", "z" }
linkoptions { "-L../libs -L/usr/local/lib -Wl,-rpath,../../../../libs" }
end
if os.get() == "windows" then
links { libName, "opengl32", "glu32", "glew", libsToLink, "freeimage", "BulletCollision", "BulletDynamics", "LinearMath", "freetype", "pthread" }
libdirs { rootdir.."/libs" }
end
if os.get() == "macosx" then
links { libName, "freeimage", "OpenGL.framework", "Cocoa.framework", "Carbon.framework", "GLEW.framework", "freetype.framework", "SFML.framework", "sfml-system.framework", "sfml-window.framework", "sfml-graphics.framework", "BulletCollision.framework", "BulletDynamics.framework", "BulletMultiThreaded.framework", "BulletSoftBody.framework", "LinearMath.framework", "MiniCL.framework" }
libdirs { rootdir.."/libs" }
end
flags { "Optimize" }
end;
if _OPTIONS["examples"] then
BuildDemo("examples/RotatingCube", "RotatingCube");
BuildDemo("examples/RotatingTexturedCube", "RotatingTexturedCube");
BuildDemo("examples/RotatingCubeWithLighting", "RotatingCubeWithLighting");
BuildDemo("examples/RotatingCubeWithLightingAndShadow", "RotatingCubeWithLightingAndShadow");
BuildDemo("examples/SimplePhysics", "SimplePhysics");
BuildDemo("examples/TextRendering", "TextRendering");
BuildDemo("examples/CustomMaterial", "CustomMaterial");
BuildDemo("examples/PickingWithPainterMethod", "PickingWithPainterMethod");
BuildDemo("examples/SkeletonAnimation", "SkeletonAnimation");
BuildDemo("examples/RacingGame", "RacingGame");
end
|
Fixed Premake file
|
Fixed Premake file
|
Lua
|
mit
|
Peixinho/Pyros3D,Peixinho/Pyros3D,Peixinho/Pyros3D
|
622f70f6e31180e1d9b32a90fca73eeb6a3c4199
|
mglupdate-2.x/index.lua
|
mglupdate-2.x/index.lua
|
--ihaveamac--
-- updater issues go to https://github.com/ihaveamac/another-file-manager/issues
-- licensed under the MIT license: https://github.com/ihaveamac/another-file-manager/blob/master/LICENSE.md
getstate_url = "http://ianburgwin.net/mglupdate/updatestate.php"
versionh_url = "http://ianburgwin.net/mglupdate/version.h"
boot3dsx_url = "http://ianburgwin.net/mglupdate/boot1.3dsx"
-- as in README.md, https sites don't work in ctrulib, unless there's a workaround, then nothing in "site" would be necessary
function updateState(stype, info)
Screen.refresh()
Screen.clear(TOP_SCREEN)
Screen.debugPrint(5, 5, "mashers's Grid Launcher Updater v1.23", Color.new(255, 255, 255), TOP_SCREEN)
Screen.fillEmptyRect(0,399,17,18,Color.new(140, 140, 140), TOP_SCREEN)
|
--ihaveamac--
-- updater issues go to https://github.com/ihaveamac/mashers-gl-updater/issues
-- licensed under the MIT license: https://github.com/ihaveamac/mashers-gl-updater/blob/master/LICENSE.md
getstate_url = "http://ianburgwin.net/mglupdate-2/updatestate.php"
versionh_url = "http://ianburgwin.net/mglupdate-2/version.h"
boot3dsx_url = "http://ianburgwin.net/mglupdate-2/launcher.zip"
-- as in README.md, https sites don't work in ctrulib, unless there's a workaround, then nothing in "site" would be necessary
function updateState(stype, info)
Screen.refresh()
Screen.clear(TOP_SCREEN)
Screen.debugPrint(5, 5, "Grid Launcher Updater v2.0d", Color.new(255, 255, 255), TOP_SCREEN)
Screen.fillEmptyRect(0,399,17,18,Color.new(140, 140, 140), TOP_SCREEN)
if stype == "preparing" or stype == "gettingver" then
Screen.debugPrint(5, 25, "Please wait a moment.", Color.new(255, 255, 255), TOP_SCREEN)
Screen.flip()
elseif stype == "noconnection" then
Screen.debugPrint(5, 25, "Couldn't get the latest version!", Color.new(255, 255, 255), TOP_SCREEN)
Screen.debugPrint(5, 40, "Check your connection to the Internet.", Color.new(255, 255, 255), TOP_SCREEN)
Screen.debugPrint(5, 60, "If this problem persists, there is a chance that", Color.new(255, 255, 255), TOP_SCREEN)
Screen.debugPrint(5, 75, "this updater manually needs to be replaced.", Color.new(255, 255, 255), TOP_SCREEN)
Screen.debugPrint(5, 95, "B: exit", Color.new(255, 255, 255), TOP_SCREEN)
co = Console.new(BOTTOM_SCREEN)
Console.append(co, info)
Console.show(co)
Screen.flip()
while true do
if Controls.check(Controls.read(), KEY_B) then
exit()
end
end
end
end
updateState("noconnection")
|
fix urls, add debug code for testing
|
fix urls, add debug code for testing
|
Lua
|
mit
|
ihaveamac/mashers-gl-updater,ihaveamac/mashers-gl-updater
|
89fa73eff9baf29da4070caa957dfd32702a2c7b
|
soressa/soressa.lua
|
soressa/soressa.lua
|
local led = require "led"
local time = require "time"
local mq
local DEVICE_ID = wifi.sta.getmac()
local on_wifi = wifi.sta.eventMonReg
local void = function (...) end
local function stop_events()
uart.on("data")
tmr.stop(1)
if mq then mq:close() end
end
local function wifi_err(...)
print("Wifi error!")
stop_events()
led.stop_blink(led.WIFI_OK)
led.off(led.WIFI_OK)
led.on(led.WIFI_ERROR)
tmr.alarm(2, 5000, 0, function ()
tmr.wdclr()
wifi.sta.connect()
end)
end
local function send_data(channel, data)
time = time.time()
local msg = string.format("{\"data\":\"%s\",\"ts\":\"%s\",\"id\":\"%s\"}", data, time, DEVICE_ID)
mq:publish(channel, msg, 0, 0, void)
end
local function scan_ap(t)
ssid, pwd, set, bssid = wifi.sta.getconfig()
ap = t[bssid]
if ap then send_data("/accesspoint", bssid.. "," ..ap) end
end
led.setup()
time.setup()
mq = mqtt.Client("soressa", 120, "guest", "guest")
mq:lwt("/lwt", "offline", 0, 0)
mq:on("offline", function () led.off(led.MQTT) end)
on_wifi(wifi.STA_WRONGPWD, wifi_err)
on_wifi(wifi.STA_APNOTFOUND, wifi_err)
on_wifi(wifi.STA_FAIL, wifi_err)
on_wifi(wifi.STA_IDLE, function () wifi.sta.connect() end)
on_wifi(wifi.STA_GOTIP, function ()
print("Wifi connected.")
led.off(led.WIFI_ERROR)
led.stop_blink(led.WIFI_OK)
led.on(led.WIFI_OK)
mq:connect("tcc.alexandrevicenzi.com", 1883, 0, function ()
print("MQTT connected.")
led.on(led.MQTT)
mq:subscribe("/accesspoint", 0, void)
mq:subscribe("/gpslocation", 0, void)
uart.on("data", "\n", function (data)
if (string.sub(data, 1, 1) == "$") then
send_data("/gpslocation", string.sub(data, 1, string.len(data) - 1))
else
print(data)
end
end, 0)
tmr.alarm(1, 10000, 1, function ()
tmr.wdclr()
wifi.sta.getap(1, scan_ap)
end)
end)
end)
on_wifi(wifi.STA_CONNECTING, function ()
print("Wifi connecting...")
stop_events()
led.off(led.WIFI_ERROR)
led.off(led.MQTT)
led.start_blink(led.WIFI_OK)
end)
wifi.sta.eventMonStart()
wifi.setmode(wifi.STATION)
wifi.sta.autoconnect(1)
|
local ap = require "ap"
local led = require "led"
local time = require "time"
local mq
local DEVICE_ID = wifi.sta.getmac()
local on_wifi = wifi.sta.eventMonReg
local void = function (...) end
local function stop_events()
uart.on("data")
tmr.stop(1)
if mq then mq:close() end
end
local function wifi_err(...)
print("Wifi error!")
stop_events()
led.stop_blink(led.WIFI_OK)
led.off(led.WIFI_OK)
led.on(led.WIFI_ERROR)
tmr.alarm(2, 5000, 0, function ()
tmr.wdclr()
wifi.sta.connect()
end)
end
local function send_data(channel, data)
local ts = time.time()
local msg = string.format("{\"data\":\"%s\",\"ts\":\"%s\",\"id\":\"%s\"}", data, ts, DEVICE_ID)
mq:publish(channel, msg, 0, 0, void)
print("Message sent to ".. channel)
end
local function scan_ap(t)
local ssid, pwd, set, bssid = wifi.sta.getconfig()
local c = (t[bssid])
if c then send_data("/accesspoint", bssid.. "," ..c) end
end
local function load_ap()
if file.open("wpa.conf", "r") then
local line, i, j, l, ssid, pwd, bssid
line = file.readline()
while line ~= nil do
i, j = string.find(line, ",", 1)
ssid = string.sub(line, 0, i - 1)
j, l = string.find(line, ",", i + 1)
pwd = string.sub(line, i + 1, j - 1)
bssid = string.sub(line, j + 1, string.len(line))
wifi.sta.config(ssid, pwd, 1, bssid)
end
file.close()
end
end
led.setup()
time.setup()
mq = mqtt.Client("soressa", 120, "guest", "guest")
mq:lwt("/lwt", "offline", 0, 0)
mq:on("offline", function () led.off(led.MQTT) end)
on_wifi(wifi.STA_WRONGPWD, wifi_err)
on_wifi(wifi.STA_APNOTFOUND, wifi_err)
on_wifi(wifi.STA_FAIL, wifi_err)
on_wifi(wifi.STA_IDLE, function () wifi.sta.connect() end)
on_wifi(wifi.STA_GOTIP, function ()
print("Wifi connected.")
led.off(led.WIFI_ERROR)
led.stop_blink(led.WIFI_OK)
led.on(led.WIFI_OK)
mq:connect("tcc.alexandrevicenzi.com", 1883, 0, function ()
print("MQTT connected.")
led.on(led.MQTT)
uart.on("data", "\n", function (data)
if (string.sub(data, 1, 1) == "$") then
send_data("/gpslocation", string.sub(data, 1, string.len(data) - 1))
else
print(data)
end
end, 0)
tmr.alarm(1, 10000, 1, function ()
tmr.wdclr()
wifi.sta.getap(1, scan_ap)
end)
end)
end)
on_wifi(wifi.STA_CONNECTING, function ()
print("Wifi connecting...")
stop_events()
led.off(led.WIFI_ERROR)
led.off(led.MQTT)
led.start_blink(led.WIFI_OK)
end)
wifi.sta.eventMonStart()
wifi.setmode(wifi.STATION)
wifi.sta.autoconnect(1)
load_ap()
|
Fix to compile.
|
Fix to compile.
|
Lua
|
mit
|
alexandrevicenzi/tcc,alexandrevicenzi/tcc,alexandrevicenzi/tcc,alexandrevicenzi/tcc
|
7692c244e300feb5d686f71caf025a909951afc9
|
kong/dao/error.lua
|
kong/dao/error.lua
|
-- DAOs need more specific error objects, specifying if the error is due
-- to the schema, the database connection, a constraint violation etc, so the
-- caller can take actions based on the error type.
--
-- We will test this object and might create a KongError class too
-- if successful and needed.
--
-- Ideally, those errors could switch from having a type, to having an error
-- code.
--
-- @author thibaultcha
local error_mt = {}
error_mt.__index = error_mt
-- Returned the `message` property as a string if it is already one,
-- for format it as a string if it is a table.
-- @return the formatted `message` property
function error_mt:print_message()
if type(self.message) == "string" then
return self.message
elseif type(self.message) == "table" then
local errors = {}
for k, v in pairs(self.message) do
table.insert(errors, k..": "..v)
end
return table.concat(errors, " | ")
end
end
-- Allow a DaoError to be printed
-- @return the formatted `message` property
function error_mt:__tostring()
return self:print_message()
end
-- Allow a DaoError to be concatenated
-- @return the formatted and concatenated `message` property
function error_mt.__concat(a, b)
if getmetatable(a) == error_mt then
return a:print_message() .. b
else
return a .. b:print_message()
end
end
local mt = {
-- Constructor
-- @param err A raw error, typically returned by lua-resty-cassandra (string)
-- @param type An error type from constants, will be set as a key with 'true'
-- value on the returned error for fast comparison when dealing
-- with this error.
-- @return A DaoError with the error_mt metatable
__call = function (self, err, type)
if err == nil then
return nil
end
local t = {
[type] = true,
message = err
}
return setmetatable(t, error_mt)
end
}
return setmetatable({}, mt)
|
-- DAOs need more specific error objects, specifying if the error is due
-- to the schema, the database connection, a constraint violation etc, so the
-- caller can take actions based on the error type.
--
-- We will test this object and might create a KongError class too
-- if successful and needed.
--
-- Ideally, those errors could switch from having a type, to having an error
-- code.
--
-- @author thibaultcha
local error_mt = {}
error_mt.__index = error_mt
-- Returned the `message` property as a string if it is already one,
-- for format it as a string if it is a table.
-- @return the formatted `message` property
function error_mt:print_message()
if type(self.message) == "string" then
return self.message
elseif type(self.message) == "table" then
local errors = {}
for k, v in pairs(self.message) do
table.insert(errors, k..": "..v)
end
return table.concat(errors, " | ")
end
end
-- Allow a DaoError to be printed
-- @return the formatted `message` property
function error_mt:__tostring()
return self:print_message()
end
-- Allow a DaoError to be concatenated
-- @return the formatted and concatenated `message` property
function error_mt.__concat(a, b)
if getmetatable(a) == error_mt then
return a:print_message() .. b
else
return a .. b:print_message()
end
end
local mt = {
-- Constructor
-- @param err A raw error, typically returned by lua-resty-cassandra (string)
-- @param err_type An error type from constants, will be set as a key with 'true'
-- value on the returned error for fast comparison when dealing
-- with this error.
-- @return A DaoError with the error_mt metatable
__call = function (self, err, err_type)
if err == nil then
return nil
end
local t = {
[err_type] = true,
message = tostring(err)
}
return setmetatable(t, error_mt)
end
}
return setmetatable({}, mt)
|
fix: comply to resty-cassandra's new errors
|
fix: comply to resty-cassandra's new errors
|
Lua
|
apache-2.0
|
akh00/kong,Vermeille/kong,kyroskoh/kong,kyroskoh/kong,ccyphers/kong,ind9/kong,salazar/kong,vzaramel/kong,streamdataio/kong,icyxp/kong,isdom/kong,isdom/kong,rafael/kong,jebenexer/kong,jerizm/kong,Mashape/kong,beauli/kong,ind9/kong,vzaramel/kong,ejoncas/kong,rafael/kong,streamdataio/kong,xvaara/kong,smanolache/kong,ejoncas/kong,ajayk/kong,shiprabehera/kong,Kong/kong,li-wl/kong,Kong/kong,Kong/kong
|
e6997ab93ef7c0d29ab6b89c9086870ef681afea
|
evaluation.lua
|
evaluation.lua
|
--
-- Created by IntelliJ IDEA.
-- User: bking
-- Date: 1/30/17
-- Time: 2:25 AM
-- To change this template use File | Settings | File Templates.
--
package.path = ';/homes/iws/kingb12/LanguageModelRNN/?.lua;'..package.path
require 'torch'
require 'nn'
require 'nnx'
require 'util'
require 'torch-rnn'
require 'DynamicView'
require 'Sampler'
cjson = require 'cjson'
torch.setheaptracking(true)
-- =========================================== COMMAND LINE OPTIONS ====================================================
local cmd = torch.CmdLine()
-- Options
cmd:option('-gpu', false)
-- Dataset options
cmd:option('-train_set', '/homes/iws/kingb12/data/BillionWords/25k_V_bucketed_set.th7')
cmd:option('-valid_set', '/homes/iws/kingb12/data/BillionWords/25k_V_bucketed_valid_set.th7')
cmd:option('-test_set', '/homes/iws/kingb12/data/BillionWords/25k_V_bucketed_test_set.th7')
cmd:option('-wmap_file', "/homes/iws/kingb12/data/BillionWords/25k_V_word_map.th7")
cmd:option('-wfreq_file', "/homes/iws/kingb12/data/BillionWords/25k_V_word_freq.th7")
-- Model options
cmd:option('-model', 'newcudamodel.th7')
--Output Options
cmd:option('-batch_loss_file', '')
cmd:option('-num_samples', 10)
cmd:option('-max_sample_length', 10)
cmd:option('-run', false)
local opt = cmd:parse(arg)
-- ================================================ EVALUATION =========================================================
train_set = torch.load(opt.train_set)
valid_set = torch.load(opt.valid_set)
test_set = torch.load(opt.test_set)
model = torch.load(opt.model)
criterion = nn.ClassNLLCriterion()
-- CUDA everything if GPU
if opt.gpu then
require 'cutorch'
require 'cunn'
train_set = train_set:cuda()
valid_set = valid_set:cuda()
test_set = test_set:cuda()
model = model:cuda()
criterion = criterion:cuda()
end
function loss_on_dataset(data_set, criterion)
local loss = 0.0
local batch_losses = {}
for i=1, data_set:size() do
local l, n = criterion:forward(model:forward(data_set[i][1]), data_set[i][2])
batch_losses[i] = l
loss = loss + (l / n)
end
return loss, batch_losses
end
-- We will build a report as a table which will be converted to json.
output = {}
-- calculate losses
local tr_set_loss, tr_batch_loss = loss_on_dataset(train_set, criterion)
output['train_loss'] = tr_set_loss
output['train_batch_loss'] = tr_batch_loss
local vd_set_loss, vd_batch_loss = loss_on_dataset(valid_set, criterion)
output['valid_loss'] = vd_set_loss
output['valid_batch_loss'] = vd_batch_loss
local ts_set_loss, ts_batch_loss = loss_on_dataset(test_set, criterion)
output['test_loss'] = ts_set_loss
output['test_batch_loss'] = ts_batch_loss
sampler = nn.Sampler()
function sample(output, max_samples)
if max_samples == nil then
max_samples = 1
end
local output = torch.cat(output, torch.zeros(output:size(1)))
local sampled = sampler:forward(output)
for i=1, output:size(1) do output[i][output:size(2) + 1] = sampled[i] end
if max_samples == 1 then
return output
else
return sample(output, max_samples - 1)
end
end
-- generate some samples
for i=1, opt.num_samples do
end
|
--
-- Created by IntelliJ IDEA.
-- User: bking
-- Date: 1/30/17
-- Time: 2:25 AM
-- To change this template use File | Settings | File Templates.
--
package.path = ';/homes/iws/kingb12/LanguageModelRNN/?.lua;'..package.path
require 'torch'
require 'nn'
require 'nnx'
require 'util'
require 'torch-rnn'
require 'DynamicView'
require 'Sampler'
cjson = require 'cjson'
torch.setheaptracking(true)
-- =========================================== COMMAND LINE OPTIONS ====================================================
local cmd = torch.CmdLine()
-- Options
cmd:option('-gpu', false)
-- Dataset options
cmd:option('-train_set', '/homes/iws/kingb12/data/BillionWords/25k_V_bucketed_set.th7')
cmd:option('-valid_set', '/homes/iws/kingb12/data/BillionWords/25k_V_bucketed_valid_set.th7')
cmd:option('-test_set', '/homes/iws/kingb12/data/BillionWords/25k_V_bucketed_test_set.th7')
cmd:option('-wmap_file', "/homes/iws/kingb12/data/BillionWords/25k_V_word_map.th7")
cmd:option('-wfreq_file', "/homes/iws/kingb12/data/BillionWords/25k_V_word_freq.th7")
-- Model options
cmd:option('-model', 'newcudamodel.th7')
--Output Options
cmd:option('-batch_loss_file', '')
cmd:option('-num_samples', 10)
cmd:option('-max_sample_length', 10)
cmd:option('-run', false)
local opt = cmd:parse(arg)
-- ================================================ EVALUATION =========================================================
if opt.gpu then
require 'cutorch'
require 'cunn'
end
function clean_dataset(dataset, batch_size)
new_set = {}
for i=1, #dataset do
if dataset[i][1]:size(1) == batch_size then
new_set[#new_set + 1] = dataset[i]
end
end
return new_set
end
train_set = clean_dataset(torch.load(opt.train_set), 50)
valid_set = clean_dataset(torch.load(opt.valid_set), 50)
test_set = clean_dataset(torch.load(opt.test_set), 50)
model = torch.load(opt.model)
criterion = nn.ClassNLLCriterion()
function table_cuda(dataset)
for i=1, #dataset do
dataset[i][1] = dataset[i][1]:cuda()
dataset[i][2] = dataset[i][2]:cuda()
end
return dataset
end
-- CUDA everything if GPU
if opt.gpu then
train_set = table_cuda(train_set)
valid_set = table_cuda(valid_set)
test_set = table_cuda(test_set)
model = model:cuda()
criterion = criterion:cuda()
end
function loss_on_dataset(data_set, criterion)
local loss = 0.0
local batch_losses = {}
for i=1, #data_set do
local l, n = criterion:forward(model:forward(data_set[i][1]), data_set[i][2])
if batch_losses[data_set[i][1]:size(2)] == nil then
batch_losses[data_set[i][1]:size(2)] = {l}
else
local x = batch_losses[data_set[i][1]:size(2)]
x[#x + 1] = l
end
loss = loss + (l / n)
end
return loss, batch_losses
end
-- We will build a report as a table which will be converted to json.
output = {}
-- calculate losses
print('Calculating Training Loss...')
local tr_set_loss, tr_batch_loss = loss_on_dataset(train_set, criterion)
output['train_loss'] = tr_set_loss
output['train_batch_loss'] = tr_batch_loss
print('Calculating Validation Loss...')
local vd_set_loss, vd_batch_loss = loss_on_dataset(valid_set, criterion)
output['valid_loss'] = vd_set_loss
output['valid_batch_loss'] = vd_batch_loss
print('Calculating Test Loss...')
local ts_set_loss, ts_batch_loss = loss_on_dataset(test_set, criterion)
output['test_loss'] = ts_set_loss
output['test_batch_loss'] = ts_batch_loss
sampler = nn.Sampler()
function sample(output, max_samples)
if max_samples == nil then
max_samples = 1
end
local output = torch.cat(output, torch.zeros(output:size(1)))
local sampled = sampler:forward(output)
for i=1, output:size(1) do output[i][output:size(2) + 1] = sampled[i] end
if max_samples == 1 then
return output
else
return sample(output, max_samples - 1)
end
end
-- generate some samples
|
fixed eval script for first run
|
fixed eval script for first run
|
Lua
|
mit
|
kingb12/languagemodelRNN,kingb12/languagemodelRNN,kingb12/languagemodelRNN
|
508bc42ecf785aaf17b32e485d881e58c8251051
|
layout-app.lua
|
layout-app.lua
|
SILE.scratch.layout = "app"
local class = SILE.documentState.documentClass
SILE.documentState.paperSize = SILE.paperSizeParser("80mm x 128mm")
SILE.documentState.orgPaperSize = SILE.documentState.paperSize
class:defineMaster({
id = "right",
firstContentFrame = "content",
frames = {
content = {
left = "2mm",
right = "100%pw-2mm",
top = "bottom(runningHead)+2mm",
bottom = "top(footnotes)"
},
runningHead = {
left = "left(content)",
right = "right(content)",
top = "2mm",
bottom = "14mm"
},
footnotes = {
left = "left(content)",
right = "right(content)",
height = "0",
bottom = "100%ph-2mm"
}
}
})
class:mirrorMaster("right", "left")
SILE.call("switch-master-one-page", { id = "right" })
SILE.registerCommand("output-right-running-head", function (options, content)
SILE.typesetNaturally(SILE.getFrame("runningHead"), function ()
SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue)
SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue)
SILE.settings.set("document.lskip", SILE.nodefactory.zeroGlue)
SILE.settings.set("document.rskip", SILE.nodefactory.zeroGlue)
SILE.call("book:right-running-head-font", {}, function ()
SILE.call("center", {}, function()
SILE.call("meta:title")
end)
end)
SILE.call("skip", { height = "2pt" })
SILE.call("book:right-running-head-font", {}, SILE.scratch.headers.right)
SILE.call("hfill")
SILE.call("book:page-number-font", {}, { SILE.formatCounter(SILE.scratch.counters.folio) })
SILE.call("skip", { height = "-8pt" })
SILE.call("fullrule", { raise = 0 })
end)
end)
SILE.registerCommand("output-left-running-head", function (options, content)
SILE.call("output-right-running-head")
end)
local oldImprintFont = SILE.Commands["imprint:font"]
SILE.registerCommand("imprint:font", function (options, content)
options.size = options.size or "6.5pt"
oldImprintFont(options, content)
end)
SILE.registerCommand("meta:distribution", function (options, content)
SILE.call("font", { weight = 600, style = "Bold" }, { "Yayın: " })
SILE.typesetter:typeset("Bu PDF biçimi, akıl telefon cihazlar için uygun biçimlemiştir ve Fetiye Halk Kilise’nin hazırladığı Kilise Uygulaması içinde ve Via Christus’un internet sitesinde izinle üçretsiz yayılmaktadır.")
end)
-- Mobile device PDF readers don't need blank even numbered pages ;)
SILE.registerCommand("open-double-page", function ()
SILE.typesetter:leaveHmode();
SILE.Commands["supereject"]();
SILE.typesetter:leaveHmode();
end)
-- Forgo bottom of page layouts for mobile devices
SILE.registerCommand("topfill", function (options, content)
SILE.typesetter:leaveHmode();
end)
if SILE.documentState.documentClass.options.background() == "true" then
SILE.require("packages/background")
SILE.call("background", { color = "#e1e2e6" })
local inkColor = SILE.colorparser("#19191A")
SILE.outputter:pushColor(inkColor)
end
SILE.settings.set("linebreak.emergencyStretch", SILE.length.parse("3em"))
|
SILE.scratch.layout = "app"
local class = SILE.documentState.documentClass
SILE.documentState.paperSize = SILE.paperSizeParser("80mm x 128mm")
SILE.documentState.orgPaperSize = SILE.documentState.paperSize
class:defineMaster({
id = "right",
firstContentFrame = "content",
frames = {
content = {
left = "2mm",
right = "100%pw-2mm",
top = "bottom(runningHead)+2mm",
bottom = "top(footnotes)"
},
runningHead = {
left = "left(content)",
right = "right(content)",
top = "2mm",
bottom = "14mm"
},
footnotes = {
left = "left(content)",
right = "right(content)",
height = "0",
bottom = "100%ph-2mm"
}
}
})
class:mirrorMaster("right", "left")
SILE.call("switch-master-one-page", { id = "right" })
SILE.registerCommand("output-right-running-head", function (options, content)
if not SILE.scratch.headers.right then return end
SILE.typesetNaturally(SILE.getFrame("runningHead"), function ()
SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue)
SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue)
SILE.settings.set("document.lskip", SILE.nodefactory.zeroGlue)
SILE.settings.set("document.rskip", SILE.nodefactory.zeroGlue)
SILE.call("book:right-running-head-font", {}, function ()
SILE.call("center", {}, function()
SILE.call("meta:title")
end)
end)
SILE.call("skip", { height = "2pt" })
SILE.call("book:right-running-head-font", {}, SILE.scratch.headers.right)
SILE.call("hfill")
SILE.call("book:page-number-font", {}, { SILE.formatCounter(SILE.scratch.counters.folio) })
SILE.call("skip", { height = "-8pt" })
SILE.call("fullrule", { raise = 0 })
end)
end)
SILE.registerCommand("output-left-running-head", function (options, content)
SILE.call("output-right-running-head")
end)
local oldImprintFont = SILE.Commands["imprint:font"]
SILE.registerCommand("imprint:font", function (options, content)
options.size = options.size or "6.5pt"
oldImprintFont(options, content)
end)
SILE.registerCommand("meta:distribution", function (options, content)
SILE.call("font", { weight = 600, style = "Bold" }, { "Yayın: " })
SILE.typesetter:typeset("Bu PDF biçimi, akıl telefon cihazlar için uygun biçimlemiştir ve Fetiye Halk Kilise’nin hazırladığı Kilise Uygulaması içinde ve Via Christus’un internet sitesinde izinle üçretsiz yayılmaktadır.")
end)
-- Mobile device PDF readers don't need blank even numbered pages ;)
SILE.registerCommand("open-double-page", function ()
SILE.typesetter:leaveHmode();
SILE.Commands["supereject"]();
SILE.typesetter:leaveHmode();
end)
-- Forgo bottom of page layouts for mobile devices
SILE.registerCommand("topfill", function (options, content)
SILE.typesetter:leaveHmode();
end)
local origToc = SILE.Commands["tableofcontents"]
SILE.registerCommand("tableofcontents", function (options, content)
SILE.scratch.headers.skipthispage = true
origToc(options, content)
SILE.scratch.headers.right = {}
end)
if SILE.documentState.documentClass.options.background() == "true" then
SILE.require("packages/background")
SILE.call("background", { color = "#e1e2e6" })
local inkColor = SILE.colorparser("#19191A")
SILE.outputter:pushColor(inkColor)
end
SILE.settings.set("linebreak.emergencyStretch", SILE.length.parse("3em"))
|
Fix #49 in a way that doesn't break pre-toc pages
|
Fix #49 in a way that doesn't break pre-toc pages
|
Lua
|
agpl-3.0
|
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
|
51100b4173c5546927cfd53d26e25d944fc60b4d
|
tests/lua/pipeline/test-process.lua
|
tests/lua/pipeline/test-process.lua
|
#!/usr/bin/env python
--ckwg +5
-- Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
-- KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
-- Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
function log(msg)
io.stderr:write(string.format("%s\n", msg))
end
function test_import()
if not pcall(require, "vistk.pipeline.process") then
log("Error: Failed to import the process module")
end
end
function test_create()
require("vistk.pipeline.datum")
require("vistk.pipeline.process")
vistk.pipeline.process_name()
vistk.pipeline.process_names()
vistk.pipeline.constraint()
vistk.pipeline.constraints()
vistk.pipeline.port_description()
vistk.pipeline.port()
vistk.pipeline.ports()
vistk.pipeline.port_type()
vistk.pipeline.port_flag()
vistk.pipeline.port_flags()
vistk.pipeline.port_addr()
vistk.pipeline.port_addrs()
vistk.pipeline.port_info('type', vistk.pipeline.port_flags(), 'desc')
vistk.pipeline.conf_info('default', 'desc')
vistk.pipeline.data_info(true, true, vistk.pipeline.datum.invalid)
end
function test_api_calls()
require("vistk.pipeline.datum")
require("vistk.pipeline.process")
local tmp
a = vistk.pipeline.port_addr()
tmp = a.process
tmp = a.port
a.process = ''
a.port = ''
a = vistk.pipeline.port_info('type', vistk.pipeline.port_flags(), 'desc')
tmp = a.type
tmp = a.flags
tmp = a.description
a = vistk.pipeline.conf_info('default', 'desc')
tmp = a.default
tmp = a.description
a = vistk.pipeline.data_info(true, true, vistk.pipeline.datum.invalid)
tmp = a.same_color
tmp = a.in_sync
tmp = a.max_status
tmp = vistk.pipeline.process.lua_process.constraint_no_threads
tmp = vistk.pipeline.process.lua_process.constraint_no_reentrancy
tmp = vistk.pipeline.process.lua_process.constraint_unsync_input
tmp = vistk.pipeline.process.lua_process.constraint_unsync_output
tmp = vistk.pipeline.process.lua_process.port_heartbeat
tmp = vistk.pipeline.process.lua_process.config_name
tmp = vistk.pipeline.process.lua_process.config_type
tmp = vistk.pipeline.process.lua_process.type_any
tmp = vistk.pipeline.process.lua_process.type_none
tmp = vistk.pipeline.process.lua_process.flag_output_const
tmp = vistk.pipeline.process.lua_process.flag_input_mutable
tmp = vistk.pipeline.process.lua_process.flag_required
end
function main(testname)
if testname == 'import' then
test_import()
elseif testname == 'create' then
test_create()
elseif testname == 'api_calls' then
test_api_calls()
else
log(string.format("Error: No such test '%s'", testname))
end
end
if #arg ~= 2 then
log("Error: Expected two arguments")
os.exit(1)
end
local testname = arg[1]
package.cpath = string.format("%s/?@CMAKE_SHARED_LIBRARY_SUFFIX@;%s", arg[2], package.cpath)
local status, err = pcall(main, testname)
if not status then
log(string.format("Error: Unexpected exception: %s", err))
end
|
#!/usr/bin/env python
--ckwg +5
-- Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
-- KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
-- Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
function log(msg)
io.stderr:write(string.format("%s\n", msg))
end
function test_import()
if not pcall(require, "vistk.pipeline.process") then
log("Error: Failed to import the process module")
end
end
function test_create()
require("vistk.pipeline.datum")
require("vistk.pipeline.process")
vistk.pipeline.process_name()
vistk.pipeline.process_names()
vistk.pipeline.constraint()
vistk.pipeline.constraints()
vistk.pipeline.port_description()
vistk.pipeline.port()
vistk.pipeline.ports()
vistk.pipeline.port_type()
vistk.pipeline.port_flag()
vistk.pipeline.port_flags()
vistk.pipeline.port_addr()
vistk.pipeline.port_addrs()
vistk.pipeline.port_info('type', vistk.pipeline.port_flags(), 'desc')
vistk.pipeline.conf_info('default', 'desc')
vistk.pipeline.data_info(true, true, vistk.pipeline.datum.invalid)
end
function test_api_calls()
require("vistk.pipeline.datum")
require("vistk.pipeline.process")
local tmp
a = vistk.pipeline.port_addr()
tmp = a.process
tmp = a.port
a.process = ''
a.port = ''
a = vistk.pipeline.port_info('type', vistk.pipeline.port_flags(), 'desc')
tmp = a.type
tmp = a.flags
tmp = a.description
a = vistk.pipeline.conf_info('default', 'desc')
tmp = a.default
tmp = a.description
a = vistk.pipeline.data_info(true, true, vistk.pipeline.datum.invalid)
tmp = a.same_color
tmp = a.in_sync
tmp = a.max_status
tmp = vistk.pipeline.lua_process.constraint_no_threads
tmp = vistk.pipeline.lua_process.constraint_no_reentrancy
tmp = vistk.pipeline.lua_process.constraint_unsync_input
tmp = vistk.pipeline.lua_process.constraint_unsync_output
tmp = vistk.pipeline.lua_process.port_heartbeat
tmp = vistk.pipeline.lua_process.config_name
tmp = vistk.pipeline.lua_process.config_type
tmp = vistk.pipeline.lua_process.type_any
tmp = vistk.pipeline.lua_process.type_none
tmp = vistk.pipeline.lua_process.flag_output_const
tmp = vistk.pipeline.lua_process.flag_input_mutable
tmp = vistk.pipeline.lua_process.flag_required
end
function main(testname)
if testname == 'import' then
test_import()
elseif testname == 'create' then
test_create()
elseif testname == 'api_calls' then
test_api_calls()
else
log(string.format("Error: No such test '%s'", testname))
end
end
if #arg ~= 2 then
log("Error: Expected two arguments")
os.exit(1)
end
local testname = arg[1]
package.cpath = string.format("%s/?@CMAKE_SHARED_LIBRARY_SUFFIX@;%s", arg[2], package.cpath)
local status, err = pcall(main, testname)
if not status then
log(string.format("Error: Unexpected exception: %s", err))
end
|
Fix calls in process tests for Lua
|
Fix calls in process tests for Lua
|
Lua
|
bsd-3-clause
|
mathstuf/sprokit,Kitware/sprokit,linus-sherrill/sprokit,Kitware/sprokit,mathstuf/sprokit,Kitware/sprokit,linus-sherrill/sprokit,mathstuf/sprokit,linus-sherrill/sprokit,mathstuf/sprokit,Kitware/sprokit,linus-sherrill/sprokit
|
1569e924fa750c7753a72e66b3323608d98d4ac3
|
Hydra/log.lua
|
Hydra/log.lua
|
api.log = {}
doc.api.log = {__doc = "Functionality to assist with debugging and experimentation."}
api.log.rawprint = print
function print(...)
api.log.rawprint(...)
local strs = table.pack(...)
local str = table.concat(strs, "\t") .. "\n"
api.log._gotline(str)
end
doc.api.log.lines = {"api.log.lines = {}", "List of lines logged so far; caps at api.log.maxlines. You may clear it by setting it to {} yourself."}
api.log.lines = {}
api.log._buffer = ""
doc.api.log.maxlines = {"api.log.maxlines = 500", "Maximum number of lines to be logged."}
api.log.maxlines = 500
api.log.handlers = {}
doc.api.log.addhandler = {"api.log.addhandler(fn(str)) -> index", "Registers a function to handle new log lines."}
function api.log.addhandler(fn)
table.insert(api.log.handlers, fn)
return #api.log.handlers
end
doc.api.log.removehandler = {"api.log.removehandler(index)", "Unregisters a function that handles new log lines."}
function api.log.removehandler(idx)
api.log.handlers[idx] = nil
end
local function addline(str)
table.insert(api.log.lines, str)
if # api.log.lines == api.log.maxlines + 1 then
-- we get called once per line; can't ever be maxlen + 2
table.remove(api.log.lines, 1)
end
end
api.log.addhandler(addline)
-- api.log.addhandler(function(str) api.alert("log: " .. str) end)
function api.log._gotline(str)
api.log._buffer = api.log._buffer .. str:gsub("\r", "\n")
while true do
local startindex, endindex = string.find(api.log._buffer, "\n", 1, true)
if not startindex then break end
local newstr = string.sub(api.log._buffer, 1, startindex - 1)
api.log._buffer = string.sub(api.log._buffer, endindex + 1, -1)
-- call all the registered callbacks
for _, fn in pairs(api.log.handlers) do
fn(newstr)
end
end
end
doc.api.log.show = {"api.log.show() -> textgrid", "Opens a textgrid that can browse all logs."}
function api.log.show()
local win = api.textgrid.open()
win:protect()
local pos = 1 -- i.e. line currently at top of log textgrid
local fg = "00FF00"
local bg = "222222"
win:settitle("Hydra Logs")
local function redraw()
win:clear(bg)
local size = win:getsize()
for linenum = pos, math.min(pos + size.h, # api.log.lines) do
local line = api.log.lines[linenum]
for i = 1, math.min(#line, size.w) do
local c = line:sub(i,i)
win:set(c:byte(), i, linenum - pos + 1, fg, bg)
end
end
end
win.resized = redraw
function win.keydown(t)
local size = win:getsize()
local h = size.h
-- this can't be cached on account of the textgrid's height could change
local keytable = {
j = 1,
k = -1,
n = (h-1),
p = -(h-1),
-- TODO: add emacs keys too
}
local scrollby = keytable[t.key]
if scrollby then
pos = pos + scrollby
pos = math.max(pos, 1)
pos = math.min(pos, # api.log.lines)
end
redraw()
end
local loghandler = api.log.addhandler(redraw)
function win.closed()
api.log.removehandler(loghandler)
end
redraw()
win:focus()
return win
end
|
api.log = {}
doc.api.log = {__doc = "Functionality to assist with debugging and experimentation."}
api.log.rawprint = print
function print(...)
api.log.rawprint(...)
local vals = table.pack(...)
for k = 1, vals.n do
vals[k] = tostring(vals[k])
end
local str = table.concat(vals, "\t") .. "\n"
api.log._gotline(str)
end
doc.api.log.lines = {"api.log.lines = {}", "List of lines logged so far; caps at api.log.maxlines. You may clear it by setting it to {} yourself."}
api.log.lines = {}
api.log._buffer = ""
doc.api.log.maxlines = {"api.log.maxlines = 500", "Maximum number of lines to be logged."}
api.log.maxlines = 500
api.log.handlers = {}
doc.api.log.addhandler = {"api.log.addhandler(fn(str)) -> index", "Registers a function to handle new log lines."}
function api.log.addhandler(fn)
table.insert(api.log.handlers, fn)
return #api.log.handlers
end
doc.api.log.removehandler = {"api.log.removehandler(index)", "Unregisters a function that handles new log lines."}
function api.log.removehandler(idx)
api.log.handlers[idx] = nil
end
local function addline(str)
table.insert(api.log.lines, str)
if # api.log.lines == api.log.maxlines + 1 then
-- we get called once per line; can't ever be maxlen + 2
table.remove(api.log.lines, 1)
end
end
api.log.addhandler(addline)
-- api.log.addhandler(function(str) api.alert("log: " .. str) end)
function api.log._gotline(str)
api.log._buffer = api.log._buffer .. str:gsub("\r", "\n")
while true do
local startindex, endindex = string.find(api.log._buffer, "\n", 1, true)
if not startindex then break end
local newstr = string.sub(api.log._buffer, 1, startindex - 1)
api.log._buffer = string.sub(api.log._buffer, endindex + 1, -1)
-- call all the registered callbacks
for _, fn in pairs(api.log.handlers) do
fn(newstr)
end
end
end
doc.api.log.show = {"api.log.show() -> textgrid", "Opens a textgrid that can browse all logs."}
function api.log.show()
local win = api.textgrid.open()
win:protect()
local pos = 1 -- i.e. line currently at top of log textgrid
local fg = "00FF00"
local bg = "222222"
win:settitle("Hydra Logs")
local function redraw()
win:clear(bg)
local size = win:getsize()
for linenum = pos, math.min(pos + size.h, # api.log.lines) do
local line = api.log.lines[linenum]
for i = 1, math.min(#line, size.w) do
local c = line:sub(i,i)
win:set(c:byte(), i, linenum - pos + 1, fg, bg)
end
end
end
win.resized = redraw
function win.keydown(t)
local size = win:getsize()
local h = size.h
-- this can't be cached on account of the textgrid's height could change
local keytable = {
j = 1,
k = -1,
n = (h-1),
p = -(h-1),
-- TODO: add emacs keys too
}
local scrollby = keytable[t.key]
if scrollby then
pos = pos + scrollby
pos = math.max(pos, 1)
pos = math.min(pos, # api.log.lines)
end
redraw()
end
local loghandler = api.log.addhandler(redraw)
function win.closed()
api.log.removehandler(loghandler)
end
redraw()
win:focus()
return win
end
|
Fixing new print function to accept all types.
|
Fixing new print function to accept all types.
|
Lua
|
mit
|
hypebeast/hammerspoon,knl/hammerspoon,Stimim/hammerspoon,cmsj/hammerspoon,bradparks/hammerspoon,lowne/hammerspoon,heptal/hammerspoon,latenitefilms/hammerspoon,emoses/hammerspoon,cmsj/hammerspoon,tmandry/hammerspoon,knu/hammerspoon,zzamboni/hammerspoon,Habbie/hammerspoon,hypebeast/hammerspoon,hypebeast/hammerspoon,chrisjbray/hammerspoon,wsmith323/hammerspoon,tmandry/hammerspoon,ocurr/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,knu/hammerspoon,zzamboni/hammerspoon,wsmith323/hammerspoon,knu/hammerspoon,knl/hammerspoon,Habbie/hammerspoon,heptal/hammerspoon,junkblocker/hammerspoon,dopcn/hammerspoon,tmandry/hammerspoon,lowne/hammerspoon,wvierber/hammerspoon,wvierber/hammerspoon,ocurr/hammerspoon,heptal/hammerspoon,CommandPost/CommandPost-App,dopcn/hammerspoon,latenitefilms/hammerspoon,zzamboni/hammerspoon,emoses/hammerspoon,wsmith323/hammerspoon,latenitefilms/hammerspoon,Habbie/hammerspoon,TimVonsee/hammerspoon,Habbie/hammerspoon,TimVonsee/hammerspoon,emoses/hammerspoon,latenitefilms/hammerspoon,knu/hammerspoon,asmagill/hammerspoon,asmagill/hammerspoon,joehanchoi/hammerspoon,chrisjbray/hammerspoon,knl/hammerspoon,ocurr/hammerspoon,asmagill/hammerspoon,chrisjbray/hammerspoon,peterhajas/hammerspoon,bradparks/hammerspoon,peterhajas/hammerspoon,heptal/hammerspoon,joehanchoi/hammerspoon,latenitefilms/hammerspoon,knl/hammerspoon,nkgm/hammerspoon,emoses/hammerspoon,Stimim/hammerspoon,dopcn/hammerspoon,peterhajas/hammerspoon,wvierber/hammerspoon,junkblocker/hammerspoon,trishume/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,cmsj/hammerspoon,CommandPost/CommandPost-App,peterhajas/hammerspoon,heptal/hammerspoon,Hammerspoon/hammerspoon,ocurr/hammerspoon,lowne/hammerspoon,nkgm/hammerspoon,nkgm/hammerspoon,peterhajas/hammerspoon,junkblocker/hammerspoon,wvierber/hammerspoon,Hammerspoon/hammerspoon,TimVonsee/hammerspoon,trishume/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,kkamdooong/hammerspoon,wvierber/hammerspoon,joehanchoi/hammerspoon,bradparks/hammerspoon,wsmith323/hammerspoon,knu/hammerspoon,wsmith323/hammerspoon,cmsj/hammerspoon,chrisjbray/hammerspoon,Habbie/hammerspoon,kkamdooong/hammerspoon,nkgm/hammerspoon,emoses/hammerspoon,kkamdooong/hammerspoon,Stimim/hammerspoon,Hammerspoon/hammerspoon,joehanchoi/hammerspoon,CommandPost/CommandPost-App,dopcn/hammerspoon,junkblocker/hammerspoon,TimVonsee/hammerspoon,Habbie/hammerspoon,TimVonsee/hammerspoon,cmsj/hammerspoon,bradparks/hammerspoon,Stimim/hammerspoon,asmagill/hammerspoon,lowne/hammerspoon,hypebeast/hammerspoon,Hammerspoon/hammerspoon,lowne/hammerspoon,dopcn/hammerspoon,zzamboni/hammerspoon,ocurr/hammerspoon,zzamboni/hammerspoon,hypebeast/hammerspoon,knu/hammerspoon,joehanchoi/hammerspoon,bradparks/hammerspoon,zzamboni/hammerspoon,knl/hammerspoon,asmagill/hammerspoon,junkblocker/hammerspoon,Hammerspoon/hammerspoon,kkamdooong/hammerspoon,chrisjbray/hammerspoon,nkgm/hammerspoon,Stimim/hammerspoon,kkamdooong/hammerspoon,trishume/hammerspoon,CommandPost/CommandPost-App,chrisjbray/hammerspoon
|
cd1cec921a2c6933fe03ab3669d86a3c3547ad43
|
data/pipelines/film_grain.lua
|
data/pipelines/film_grain.lua
|
local film_grain_shader = nil
function postprocess(env, transparent_phase, ldr_buffer, gbuffer0, gbuffer1, gbuffer_depth, shadowmap)
if not enabled then return ldr_buffer end
if transparent_phase ~= "post_tonemap" then return ldr_buffer end
local res = env.createRenderbuffer(1, 1, true, "rgba8")
env.beginBlock("film_grain")
if film_grain_shader == nil then
film_grain_shader = env.preloadShader("pipelines/film_grain.shd")
end
env.blending("")
env.setRenderTargets(0, res)
env.drawArray(0, 4, film_grain_shader, { u_source = ldr_buffer })
env.endBlock()
return res
end
function awake()
if _G["postprocesses"] == nil then
_G["postprocesses"] = {}
end
table.insert(_G["postprocesses"], postprocess)
end
function onDestroy()
for i, v in ipairs(_G["postprocesses"]) do
if v == postprocess then
table.remove(_G["postprocesses"], i)
break;
end
end
end
|
local film_grain_shader = nil
function postprocess(env, transparent_phase, ldr_buffer, gbuffer0, gbuffer1, gbuffer_depth, shadowmap)
if not enabled then return ldr_buffer end
if transparent_phase ~= "post_tonemap" then return ldr_buffer end
local res = env.createRenderbuffer(1, 1, true, "rgba8", "film_grain")
env.beginBlock("film_grain")
if film_grain_shader == nil then
film_grain_shader = env.preloadShader("pipelines/film_grain.shd")
end
env.setRenderTargets(0, res)
env.drawArray(0, 4, film_grain_shader,
{ ldr_buffer },
{},
{},
{ depth_test = false, blending = ""}
)
env.endBlock()
return res
end
function awake()
if _G["postprocesses"] == nil then
_G["postprocesses"] = {}
end
table.insert(_G["postprocesses"], postprocess)
end
function onDestroy()
for i, v in ipairs(_G["postprocesses"]) do
if v == postprocess then
table.remove(_G["postprocesses"], i)
break;
end
end
end
|
fixed film grain
|
fixed film grain
|
Lua
|
mit
|
nem0/LumixEngine,nem0/LumixEngine,nem0/LumixEngine
|
fdb17150ffeacd40de2ad297aa6629c1d9335f35
|
hammerspoon/.config/hammerspoon/emojipicker.lua
|
hammerspoon/.config/hammerspoon/emojipicker.lua
|
local utils = require("utils")
local settings = require("hs.settings")
local styledtext = require("hs.styledtext")
local mod = {}
local file = io.open("emojis.txt", "r")
local emojis = {}
for line in file:lines() do
table.insert(emojis, 1, line)
end
function utf8.sub(s, i, j)
i = utf8.offset(s, i)
j = utf8.offset(s, j + 1) - 1
return string.sub(s, i, j)
end
-- Emojipicker
function mod.emojipicker()
function formatChoices(choices)
choices = utils.reverse(choices)
formattedChoices =
hs.fnutils.imap(
choices,
function(result)
local text =
styledtext.new(
utils.trim(result),
{
font = {size = 16, name = "DankMonoNerdFontComplete-Regular"}
}
)
return {
["text"] = text
}
end
)
return formattedChoices
end
local copy = nil
local current = hs.application.frontmostApplication()
local choices = formatChoices(emojis)
local chooser =
hs.chooser.new(
function(choosen)
if copy then
copy:delete()
end
current:activate()
hs.eventtap.keyStrokes(choosen)
end
)
chooser:width(69)
chooser:placeholderText("Pick emoji")
chooser:choices(formatChoices(emojis))
copy =
hs.hotkey.bind(
"",
"return",
function()
local query = chooser:query()
local filteredChoices =
hs.fnutils.filter(
emojis,
function(result)
return string.match(string.lower(result), string.lower(query))
end
)
local id = chooser:selectedRow()
local item = formatChoices(filteredChoices)[id]
if item then
chooser:hide()
trimmed = utf8.sub(item.text, 1, 1)
hs.pasteboard.setContents(trimmed)
settings.set("so.meain.hs.jumpcutselect.lastselected", trimmed) -- need to make sure it does not get copied to clipboard
hs.alert.show(item.text, 1)
else
hs.alert.show("Nothing to copy", 1)
end
end
)
function updateChooser()
local query = chooser:query()
local filteredChoices =
hs.fnutils.filter(
emojis,
function(result)
return string.match(string.lower(result), string.lower(query))
end
)
chooser:choices(formatChoices(filteredChoices))
end
chooser:queryChangedCallback(updateChooser)
chooser:searchSubText(false)
chooser:show()
end
function mod.registerDefaultBindings(mods, key)
mods = mods or {"cmd", "alt", "ctrl"}
key = key or "E"
hs.hotkey.bind(mods, key, mod.emojipicker)
end
return mod
|
local utils = require("utils")
local settings = require("hs.settings")
local styledtext = require("hs.styledtext")
local mod = {}
local file = io.open("emojis.txt", "r")
local emojis = {}
for line in file:lines() do
table.insert(emojis, 1, line)
end
function utf8.sub(s, i, j)
i = utf8.offset(s, i)
j = utf8.offset(s, j + 1) - 1
return string.sub(s, i, j)
end
-- Emojipicker
function mod.emojipicker()
function formatChoices(choices)
choices = utils.reverse(choices)
formattedChoices =
hs.fnutils.imap(
choices,
function(result)
local text =
styledtext.new(
utils.trim(result),
{
font = {size = 16, name = "DankMonoNerdFontComplete-Regular"}
}
)
return {
["text"] = text,
["raw"] = result
}
end
)
return formattedChoices
end
local copy = nil
local current = hs.application.frontmostApplication()
local choices = formatChoices(emojis)
local chooser =
hs.chooser.new(
function(choosen)
if copy then
copy:delete()
end
current:activate()
hs.eventtap.keyStrokes(choosen)
end
)
chooser:width(69)
chooser:placeholderText("Pick emoji")
chooser:choices(formatChoices(emojis))
copy =
hs.hotkey.bind(
"",
"return",
function()
local query = chooser:query()
local filteredChoices =
hs.fnutils.filter(
emojis,
function(result)
return string.match(string.lower(result), string.lower(query))
end
)
local id = chooser:selectedRow()
local item = formatChoices(filteredChoices)[id]
if item then
chooser:hide()
trimmed = utf8.sub(item.raw, 1, 1)
hs.pasteboard.setContents(trimmed)
settings.set("so.meain.hs.jumpcutselect.lastselected", trimmed) -- need to make sure it does not get copied to clipboard
hs.alert.show(item.raw, 1)
else
hs.alert.show("Nothing to copy", 1)
end
end
)
function updateChooser()
local query = chooser:query()
local filteredChoices =
hs.fnutils.filter(
emojis,
function(result)
return string.match(string.lower(result), string.lower(query))
end
)
chooser:choices(formatChoices(filteredChoices))
end
chooser:queryChangedCallback(updateChooser)
chooser:searchSubText(false)
chooser:show()
end
function mod.registerDefaultBindings(mods, key)
mods = mods or {"cmd", "alt", "ctrl"}
key = key or "E"
hs.hotkey.bind(mods, key, mod.emojipicker)
end
return mod
|
[emacs] fix emoji picker
|
[emacs] fix emoji picker
Emoji picker broke now that we are using styledtext instead of simple
text field and we cannot get the value. This should fix it.
|
Lua
|
mit
|
meain/dotfiles,meain/dotfiles,meain/dotfiles,meain/dotfiles,meain/dotfiles,meain/dotfiles
|
55579cd74d64b9f3498dfb2ca2351e6278842791
|
nyagos.d/catalog/fuzzyfinder.lua
|
nyagos.d/catalog/fuzzyfinder.lua
|
if not nyagos then
print("This is a script for nyagos not lua.exe")
os.exit()
end
-- default/non-configured setting: Use fzf
local ff = {}
ff.cmd = "fzf.exe"
ff.args = {}
ff.args.dir = ""
ff.args.cmdhist = ""
ff.args.cdhist = ""
ff.args.gitlog = "--preview='git show {1}'"
share.fuzzyfinder = share.fuzzyfinder or ff
-- Compatibility settings with old settings
share.selector = share.fuzzyfinder.cmd
nyagos.alias.dump_temp_out = function()
for _,val in ipairs(share.dump_temp_out) do
nyagos.write(val,"\n")
end
end
nyagos.bindkey("C-o",function(this)
local word,pos = this:lastword()
word = string.gsub(word,'"','')
share.dump_temp_out = nyagos.glob(word.."*")
local result=nyagos.eval('dump_temp_out | ' .. share.fuzzyfinder.cmd .. " " .. share.fuzzyfinder.args.dir)
this:call("CLEAR_SCREEN")
if string.find(result," ",1,true) then
result = '"'..result..'"'
end
assert( this:replacefrom(pos,result) )
end)
nyagos.alias.__dump_history = function()
local uniq={}
for i=nyagos.gethistory()-1,1,-1 do
local line = nyagos.gethistory(i)
if line ~= "" and not uniq[line] then
nyagos.write(line,"\n")
uniq[line] = true
end
end
end
nyagos.bindkey("C_R", function(this)
local result = nyagos.eval('__dump_history | ' .. share.fuzzyfinder.cmd .. " " .. share.fuzzyfinder.args.cmdhist)
this:call("CLEAR_SCREEN")
return result
end)
nyagos.bindkey("M_H" , function(this)
local result = nyagos.eval('cd --history | ' .. share.fuzzyfinder.cmd .. " " .. share.fuzzyfinder.args.cdhist)
this:call("CLEAR_SCREEN")
if string.find(result,' ') then
result = '"'..result..'"'
end
return result
end)
nyagos.bindkey("M_G" , function(this)
local result = nyagos.eval('git log --pretty="format:%h %s" | ' .. share.fuzzyfinder.cmd .. " " .. share.fuzzyfinder.args.gitlog)
this:call("CLEAR_SCREEN")
return string.match(result,"^%S+") or ""
end)
|
if not nyagos then
print("This is a script for nyagos not lua.exe")
os.exit()
end
-- default/non-configured setting: Use fzf(exists)/peco
local ff = {}
if nyagos.which("fzf.exe") then
ff.cmd = "fzf.exe"
else
ff.cmd = "peco.exe"
end
ff.args = {}
ff.args.dir = ""
ff.args.cmdhist = ""
ff.args.cdhist = ""
if nyagos.which("fzf.exe") then
ff.args.gitlog = "--preview='git show {1}'"
else
ff.args.gitlog = ""
end
share.fuzzyfinder = share.fuzzyfinder or ff
-- Compatibility settings with old settings
share.selector = share.fuzzyfinder.cmd
nyagos.alias.dump_temp_out = function()
for _,val in ipairs(share.dump_temp_out) do
nyagos.write(val,"\n")
end
end
nyagos.bindkey("C-o",function(this)
local word,pos = this:lastword()
word = string.gsub(word,'"','')
share.dump_temp_out = nyagos.glob(word.."*")
local result=nyagos.eval('dump_temp_out | ' .. share.fuzzyfinder.cmd .. " " .. share.fuzzyfinder.args.dir)
this:call("CLEAR_SCREEN")
if string.find(result," ",1,true) then
result = '"'..result..'"'
end
assert( this:replacefrom(pos,result) )
end)
nyagos.alias.__dump_history = function()
local uniq={}
for i=nyagos.gethistory()-1,1,-1 do
local line = nyagos.gethistory(i)
if line ~= "" and not uniq[line] then
nyagos.write(line,"\n")
uniq[line] = true
end
end
end
nyagos.bindkey("C_R", function(this)
local result = nyagos.eval('__dump_history | ' .. share.fuzzyfinder.cmd .. " " .. share.fuzzyfinder.args.cmdhist)
this:call("CLEAR_SCREEN")
return result
end)
nyagos.bindkey("M_H" , function(this)
local result = nyagos.eval('cd --history | ' .. share.fuzzyfinder.cmd .. " " .. share.fuzzyfinder.args.cdhist)
this:call("CLEAR_SCREEN")
if string.find(result,' ') then
result = '"'..result..'"'
end
return result
end)
nyagos.bindkey("M_G" , function(this)
local result = nyagos.eval('git log --pretty="format:%h %s" | ' .. share.fuzzyfinder.cmd .. " " .. share.fuzzyfinder.args.gitlog)
this:call("CLEAR_SCREEN")
return string.match(result,"^%S+") or ""
end)
|
fix: fuzzyfinder.lua default command selection
|
fix: fuzzyfinder.lua default command selection
|
Lua
|
bsd-3-clause
|
tsuyoshicho/nyagos
|
b812e84e1d05b5200ead9b6a7d09a0af054e38ee
|
Assets/ToLua/Lua/System/coroutine.lua
|
Assets/ToLua/Lua/System/coroutine.lua
|
--------------------------------------------------------------------------------
-- Copyright (c) 2015 - 2016 , 蒙占志(topameng) [email protected]
-- All rights reserved.
-- Use, modification and distribution are subject to the "MIT License"
--------------------------------------------------------------------------------
local create = coroutine.create
local running = coroutine.running
local resume = coroutine.resume
local yield = coroutine.yield
local error = error
local unpack = unpack
local debug = debug
local FrameTimer = FrameTimer
local CoTimer = CoTimer
local comap = {}
local pool = {}
setmetatable(comap, {__mode = "kv"})
function coroutine.start(f, ...)
local co = create(f)
if running() == nil then
local flag, msg = resume(co, ...)
if not flag then
error(debug.traceback(co, msg))
end
else
local args = {...}
local timer = nil
local action = function()
local flag, msg = resume(co, unpack(args))
timer.func = nil
table.insert(pool, timer)
if not flag then
error(debug.traceback(co, msg))
end
end
if #pool > 0 then
timer = table.remove(pool)
timer:Reset(action, 0, 1)
else
timer = FrameTimer.New(action, 0, 1)
end
comap[co] = timer
timer:Start()
end
return co
end
function coroutine.wait(t, co, ...)
local args = {...}
co = co or running()
local timer = nil
local action = function()
local flag, msg = resume(co, unpack(args))
if not flag then
timer:Stop()
error(debug.traceback(co, msg))
return
end
end
timer = CoTimer.New(action, t, 1)
comap[co] = timer
timer:Start()
return yield()
end
function coroutine.step(t, co, ...)
local args = {...}
co = co or running()
local timer = nil
local action = function()
local flag, msg = resume(co, unpack(args))
timer.func = nil
table.insert(pool, timer)
if not flag then
error(debug.traceback(co, msg))
return
end
end
if #pool > 0 then
timer = table.remove(pool)
timer:Reset(action, t or 1, 1)
else
timer = FrameTimer.New(action, t or 1, 1)
end
comap[co] = timer
timer:Start()
return yield()
end
function coroutine.www(www, co)
co = co or running()
local timer = nil
local action = function()
if not www.isDone then
return
end
timer:Stop()
local flag, msg = resume(co)
timer.func = nil
table.insert(pool, timer)
if not flag then
error(debug.traceback(co, msg))
return
end
end
if #pool > 0 then
timer = table.remove(pool)
timer:Reset(action, 1, -1)
else
timer = FrameTimer.New(action, 1, -1)
end
comap[co] = timer
timer:Start()
return yield()
end
function coroutine.stop(co)
local timer = comap[co]
if timer ~= nil then
comap[co] = nil
timer:Stop()
end
end
|
--------------------------------------------------------------------------------
-- Copyright (c) 2015 - 2016 , 蒙占志(topameng) [email protected]
-- All rights reserved.
-- Use, modification and distribution are subject to the "MIT License"
--------------------------------------------------------------------------------
local create = coroutine.create
local running = coroutine.running
local resume = coroutine.resume
local yield = coroutine.yield
local error = error
local unpack = unpack
local debug = debug
local FrameTimer = FrameTimer
local CoTimer = CoTimer
local comap = {}
local pool = {}
setmetatable(comap, {__mode = "kv"})
function coroutine.start(f, ...)
local co = create(f)
if running() == nil then
local flag, msg = resume(co, ...)
if not flag then
error(debug.traceback(co, msg))
end
else
local args = {...}
local timer = nil
local action = function()
comap[co] = nil
local flag, msg = resume(co, unpack(args))
timer.func = nil
table.insert(pool, timer)
if not flag then
timer:Stop()
error(debug.traceback(co, msg))
end
end
if #pool > 0 then
timer = table.remove(pool)
timer:Reset(action, 0, 1)
else
timer = FrameTimer.New(action, 0, 1)
end
comap[co] = timer
timer:Start()
end
return co
end
function coroutine.wait(t, co, ...)
local args = {...}
co = co or running()
local timer = nil
local action = function()
comap[co] = nil
local flag, msg = resume(co, unpack(args))
if not flag then
timer:Stop()
error(debug.traceback(co, msg))
return
end
end
timer = CoTimer.New(action, t, 1)
comap[co] = timer
timer:Start()
return yield()
end
function coroutine.step(t, co, ...)
local args = {...}
co = co or running()
local timer = nil
local action = function()
comap[co] = nil
local flag, msg = resume(co, unpack(args))
timer.func = nil
table.insert(pool, timer)
if not flag then
timer:Stop()
error(debug.traceback(co, msg))
return
end
end
if #pool > 0 then
timer = table.remove(pool)
timer:Reset(action, t or 1, 1)
else
timer = FrameTimer.New(action, t or 1, 1)
end
comap[co] = timer
timer:Start()
return yield()
end
function coroutine.www(www, co)
co = co or running()
local timer = nil
local action = function()
if not www.isDone then
return
end
comap[co] = nil
timer:Stop()
local flag, msg = resume(co)
timer.func = nil
table.insert(pool, timer)
if not flag then
error(debug.traceback(co, msg))
return
end
end
if #pool > 0 then
timer = table.remove(pool)
timer:Reset(action, 1, -1)
else
timer = FrameTimer.New(action, 1, -1)
end
comap[co] = timer
timer:Start()
return yield()
end
function coroutine.stop(co)
local timer = comap[co]
if timer ~= nil then
comap[co] = nil
timer:Stop()
end
end
|
1.0.7.391 fixed coroutine stop other's timer
|
1.0.7.391 fixed coroutine stop other's timer
|
Lua
|
mit
|
topameng/tolua
|
cd3279ab658c0c2cf5586b385a3506673a7e6dd2
|
tests/test_util_jid.lua
|
tests/test_util_jid.lua
|
function split(split)
function test(jid, node, server, resource)
local rnode, rserver, rresource = split(jid);
assert_equal(node, rnode, "split("..jid..") failed");
assert_equal(server, rserver, "split("..jid..") failed");
assert_equal(resource, rresource, "split("..jid..") failed");
end
test("node@server", "node", "server", nil );
test("node@server/resource", "node", "server", "resource" );
test("server", nil, "server", nil );
test("server/resource", nil, "server", "resource" );
end
|
function split(split)
function test(jid, node, server, resource)
local rnode, rserver, rresource = split(jid);
assert_equal(node, rnode, "split("..tostring(jid)..") failed");
assert_equal(server, rserver, "split("..tostring(jid)..") failed");
assert_equal(resource, rresource, "split("..tostring(jid)..") failed");
end
test("node@server", "node", "server", nil );
test("node@server/resource", "node", "server", "resource" );
test("server", nil, "server", nil );
test("server/resource", nil, "server", "resource" );
test(nil, nil, nil , nil );
end
|
Fix jid.split test function
|
Fix jid.split test function
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
f7df9e4b80801579cb54ee1a4c59f8c86180e435
|
src/extensions/cp/apple/finalcutpro/inspector/info/InfoProjectInspector.lua
|
src/extensions/cp/apple/finalcutpro/inspector/info/InfoProjectInspector.lua
|
--- === cp.apple.finalcutpro.inspector.info.InfoProjectInspector ===
---
--- Info Inspector Module when a Project is selected.
local require = require
--local log = require "hs.logger".new "infoInspect"
local axutils = require "cp.ui.axutils"
local BasePanel = require "cp.apple.finalcutpro.inspector.BasePanel"
local Button = require "cp.ui.Button"
local go = require "cp.rx.go"
local IP = require "cp.apple.finalcutpro.inspector.InspectorProperty"
local strings = require "cp.apple.finalcutpro.strings"
local Do = go.Do
local WaitUntil = go.WaitUntil
local Retry = go.Retry
local If = go.If
local Throw = go.Throw
local hasProperties = IP.hasProperties
local staticText = IP.staticText
local textField = IP.textField
local childrenWithRole = axutils.childrenWithRole
local childWithRole = axutils.childWithRole
local withAttributeValue = axutils.withAttributeValue
local withRole = axutils.withRole
local InfoProjectInspector = BasePanel:subclass("InfoProjectInspector")
--- cp.apple.finalcutpro.inspector.info.InfoProjectInspector.matches(element) -> boolean
--- Function
--- Checks to see if an element matches what we think it should be.
---
--- Parameters:
--- * element - An `axuielementObject` to check.
---
--- Returns:
--- * `true` if matches otherwise `false`
function InfoProjectInspector.static.matches(element)
local root = BasePanel.matches(element) and withRole(element, "AXGroup")
local scrollArea = root and #childrenWithRole(root, "AXStaticText") >= 2 and childWithRole(root, "AXScrollArea")
return scrollArea and withAttributeValue(scrollArea, "AXDescription", strings:find("FFInspectorModuleProjectPropertiesScrollViewAXDescription")) or false
end
--- cp.apple.finalcutpro.inspector.info.InfoProjectInspector.new(parent) -> InfoProjectInspector object
--- Constructor
--- Creates a new InfoProjectInspector object
---
--- Parameters:
--- * `parent` - The parent
---
--- Returns:
--- * A InfoProjectInspector object
function InfoProjectInspector:initialize(parent)
BasePanel.initialize(self, parent, "ProjectInfo")
hasProperties(self, self.propertiesUI) {
location = staticText "FFInspectorModuleProjectPropertiesLocation",
library = staticText "FFInspectorModuleProjectPropertiesLibrary",
event = staticText "FFInspectorModuleProjectPropertiesEvent",
lastModified = staticText "FFInspectorModuleProjectPropertiesLastModified",
notes = textField "FFInspectorModuleProjectPropertiesNotes",
}
end
--- cp.apple.finalcutpro.inspector.info.InfoProjectInspector:propertiesUI() -> hs._asm.axuielement object
--- Method
--- Returns the `hs._asm.axuielement` object for the Properties UI.
---
--- Parameters:
--- * None
---
--- Returns:
--- * A `hs._asm.axuielement` object.
function InfoProjectInspector.lazy.prop:propertiesUI()
return self.UI:mutate(function(original)
return axutils.cache(self, "_properties", function()
return axutils.childWithRole(original(), "AXScrollArea")
end)
end)
end
--- cp.apple.finalcutpro.inspector.info.InfoProjectInspector:modify() -> Button
--- Method
--- Gets the Modify Project button in the Info Inspector.
---
--- Parameters:
--- * None
---
--- Returns:
--- * An `Button` object.
function InfoProjectInspector.lazy.method:modify()
return Button(self, function()
local ui = self:UI()
local button = childWithRole(ui, "AXButton")
if button and button:attributeValue("AXTitle") == strings:find("FFInspectorMediaHeaderControllerButtonEdit") then
return button
end
end)
end
--- cp.apple.finalcutpro.inspector.info.InfoProjectInspector:doShow() -> cp.rx.go.Statment
--- Method
--- A [Statement](cp.rx.go.Statement.md) that shows the panel.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `Statement`, resolving to `true` if successful and sending an error if not.
function InfoProjectInspector.lazy.method:doShow()
return Do(self:app():doSelectMenu({"Window", "Project Properties…"}))
:Then(
Retry(function()
if self.isShowing() then
return true
else
return Throw("Project Properties failed to show after a second.")
end
end):UpTo(10):DelayedBy(100)
)
:Label(self:panelType() .. ":doShow")
end
return InfoProjectInspector
|
--- === cp.apple.finalcutpro.inspector.info.InfoProjectInspector ===
---
--- Info Inspector Module when a Project is selected.
local require = require
--local log = require "hs.logger".new "infoInspect"
local axutils = require "cp.ui.axutils"
local BasePanel = require "cp.apple.finalcutpro.inspector.BasePanel"
local Button = require "cp.ui.Button"
local go = require "cp.rx.go"
local IP = require "cp.apple.finalcutpro.inspector.InspectorProperty"
local strings = require "cp.apple.finalcutpro.strings"
local Do = go.Do
local Retry = go.Retry
local Throw = go.Throw
local hasProperties = IP.hasProperties
local staticText = IP.staticText
local textField = IP.textField
local childrenWithRole = axutils.childrenWithRole
local childWithRole = axutils.childWithRole
local withAttributeValue = axutils.withAttributeValue
local withRole = axutils.withRole
local InfoProjectInspector = BasePanel:subclass("InfoProjectInspector")
--- cp.apple.finalcutpro.inspector.info.InfoProjectInspector.matches(element) -> boolean
--- Function
--- Checks to see if an element matches what we think it should be.
---
--- Parameters:
--- * element - An `axuielementObject` to check.
---
--- Returns:
--- * `true` if matches otherwise `false`
function InfoProjectInspector.static.matches(element)
local root = BasePanel.matches(element) and withRole(element, "AXGroup")
local scrollArea = root and #childrenWithRole(root, "AXStaticText") >= 2 and childWithRole(root, "AXScrollArea")
return scrollArea and withAttributeValue(scrollArea, "AXDescription", strings:find("FFInspectorModuleProjectPropertiesScrollViewAXDescription")) or false
end
--- cp.apple.finalcutpro.inspector.info.InfoProjectInspector.new(parent) -> InfoProjectInspector object
--- Constructor
--- Creates a new InfoProjectInspector object
---
--- Parameters:
--- * `parent` - The parent
---
--- Returns:
--- * A InfoProjectInspector object
function InfoProjectInspector:initialize(parent)
BasePanel.initialize(self, parent, "ProjectInfo")
hasProperties(self, self.propertiesUI) {
location = staticText "FFInspectorModuleProjectPropertiesLocation",
library = staticText "FFInspectorModuleProjectPropertiesLibrary",
event = staticText "FFInspectorModuleProjectPropertiesEvent",
lastModified = staticText "FFInspectorModuleProjectPropertiesLastModified",
notes = textField "FFInspectorModuleProjectPropertiesNotes",
}
end
--- cp.apple.finalcutpro.inspector.info.InfoProjectInspector:propertiesUI() -> hs._asm.axuielement object
--- Method
--- Returns the `hs._asm.axuielement` object for the Properties UI.
---
--- Parameters:
--- * None
---
--- Returns:
--- * A `hs._asm.axuielement` object.
function InfoProjectInspector.lazy.prop:propertiesUI()
return self.UI:mutate(function(original)
return axutils.cache(self, "_properties", function()
return axutils.childWithRole(original(), "AXScrollArea")
end)
end)
end
--- cp.apple.finalcutpro.inspector.info.InfoProjectInspector:modify() -> Button
--- Method
--- Gets the Modify Project button in the Info Inspector.
---
--- Parameters:
--- * None
---
--- Returns:
--- * An `Button` object.
function InfoProjectInspector.lazy.method:modify()
return Button(self, function()
local ui = self:UI()
local button = childWithRole(ui, "AXButton")
if button and button:attributeValue("AXTitle") == strings:find("FFInspectorMediaHeaderControllerButtonEdit") then
return button
end
end)
end
--- cp.apple.finalcutpro.inspector.info.InfoProjectInspector:doShow() -> cp.rx.go.Statment
--- Method
--- A [Statement](cp.rx.go.Statement.md) that shows the panel.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `Statement`, resolving to `true` if successful and sending an error if not.
function InfoProjectInspector.lazy.method:doShow()
return Do(self:app():doSelectMenu({"Window", "Project Properties…"}))
:Then(
Retry(function()
if self.isShowing() then
return true
else
return Throw("Project Properties failed to show after a second.")
end
end):UpTo(10):DelayedBy(100)
)
:Label(self:panelType() .. ":doShow")
end
return InfoProjectInspector
|
#1826
|
#1826
- Fixed @stickler-ci errors
|
Lua
|
mit
|
fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost
|
4c93ae675580410bfb29364d457e129ddd6e0f8d
|
xmake/packages/git/xmake.lua
|
xmake/packages/git/xmake.lua
|
package("git")
set_kind("binary")
set_homepage("https://git-scm.com/")
set_description("A free and open source distributed version control system")
set_versions("v1.0.1")
if os.host() == "windows" then
if os.arch() == "x64" then
-- add_urls("https://coding.net/u/waruqi/p/xmake-win64env/git/archive/$(version).zip", {alias = "coding"})
add_urls("https://github.com/tboox/xmake-win64env/archive/$(version).zip", {alias = "github"})
-- add_sha256s("[email protected]", "1071c5e43613ff591bad7f5ad90fe1621a070cf20c56f06d5177e095f88c9a74")
add_sha256s("[email protected]", "95170b1d144ebb30961611fd87b1e9404bbe37d2d904adb15f3e202bb3e19c21")
else
-- add_urls("https://coding.net/u/waruqi/p/xmake-win32env/git/archive/$(version).zip", {alias = "coding"})
add_urls("https://github.com/tboox/xmake-win32env/archive/$(version).zip", {alias = "github"})
-- add_sha256s("[email protected]", "de8623309f956619f70a8681201ecacfb99b7694070b63c4d53756de8855697e")
add_sha256s("[email protected]", "3c46983379329a246596a2b5f0ff971b55e3eccbbfd34272e7121e13fb346db5")
end
else
add_imports("package.manager.install")
end
on_build(function (package)
end)
on_install(function (package)
install("git")
end)
on_install("windows", function (package)
-- install winenv with git
local winenv_dir = path.translate("~/.xmake/winenv")
os.mkdir(winenv_dir)
os.cp("*", winenv_dir)
-- load winenv
import("winenv", {rootdir = winenv_dir})(winenv_dir)
end)
|
package("git")
set_kind("binary")
set_homepage("https://git-scm.com/")
set_description("A free and open source distributed version control system")
set_versions("v1.0.1")
if os.host() == "windows" then
if os.arch() == "x64" then
add_urls("https://gitee.com/tboox/xmake-winenv/raw/master/win64/$(version).zip")
add_urls("https://coding.net/u/waruqi/p/xmake-winenv/git/raw/master/win64/$(version).zip")
add_urls("https://github.com/tboox/xmake-win64env/archive/$(version).zip")
add_sha256s("v1.0.1", "95170b1d144ebb30961611fd87b1e9404bbe37d2d904adb15f3e202bb3e19c21")
else
add_urls("https://gitee.com/tboox/xmake-winenv/raw/master/win32/$(version).zip")
add_urls("https://coding.net/u/waruqi/p/xmake-winenv/git/raw/master/win32/$(version).zip")
add_urls("https://github.com/tboox/xmake-win32env/archive/$(version).zip")
add_sha256s("v1.0.1", "3c46983379329a246596a2b5f0ff971b55e3eccbbfd34272e7121e13fb346db5")
end
else
add_imports("package.manager.install")
end
on_build(function (package)
end)
on_install(function (package)
install("git")
end)
on_install("windows", function (package)
-- install winenv with git
local winenv_dir = path.translate("~/.xmake/winenv")
os.mkdir(winenv_dir)
os.cp("*", winenv_dir)
-- load winenv
import("winenv", {rootdir = winenv_dir})(winenv_dir)
end)
|
fix git mirror urls
|
fix git mirror urls
|
Lua
|
apache-2.0
|
tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake
|
4ca160c02b5755d816b60f202be4bced59dcdd76
|
xmake/core/base/process.lua
|
xmake/core/base/process.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 process.lua
--
-- define module: process
local process = process or {}
-- load modules
local utils = require("base/utils")
local string = require("base/string")
local coroutine = require("base/coroutine")
-- async run task and echo waiting info
function process.asyncrun(task, waitchars)
-- create a coroutine task
task = coroutine.create(task)
-- trace
local waitindex = 0
local waitchars = waitchars or {'\\', '|', '/', '-'}
utils.printf(waitchars[waitindex + 1])
-- start and wait this task
local ok, errors = coroutine.resume(task)
if not ok then
-- remove wait charactor
utils.printf("\b")
-- failed
return false, errors
end
-- wait and poll task
while coroutine.status(task) ~= "dead" do
-- trace
waitindex = ((waitindex + 1) % #waitchars)
utils.printf("\b" .. waitchars[waitindex + 1])
-- wait some time
os.sleep(300)
-- continue to poll this task
local ok, errors = coroutine.resume(task, 0)
if not ok then
-- remove wait charactor
utils.printf("\b")
-- failed
return false, errors
end
end
-- remove wait charactor
utils.printf("\b")
-- ok
return true
end
-- run jobs with processes
function process.runjobs(jobfunc, total, comax, timeout, timer)
-- init max coroutine count
comax = comax or total
-- init timeout
timeout = timeout or -1
-- make objects
local index = 1
local tasks = {}
local procs = {}
local indices = {}
local time = os.mclock()
repeat
-- wait processes
local tasks_finished = {}
local procs_count = #procs
local procs_infos = nil
if procs_count > 0 then
local count = -1
count, procs_infos = process.waitlist(procs, utils.ifelse(#tasks < comax and index <= total, 0, timeout))
if count < 0 then
return false, string.format("wait processes(%d) failed(%d)", #procs, count)
end
end
-- timer is triggered? call timer
if timer and os.mclock() - time > timeout then
timer(indices)
time = os.mclock()
end
-- append fake procs_infos for coroutine.yield()
procs_infos = procs_infos or {}
for taskid = #procs + 1, #tasks do
table.insert(procs_infos, {nil, taskid, 0})
end
-- wait ok
for _, procinfo in ipairs(procs_infos) do
-- the process info
local proc = procinfo[1]
local taskid = procinfo[2]
local status = procinfo[3]
-- check
assert(procs[taskid] == proc)
-- resume this task
local job_task = tasks[taskid]
local ok, job_proc_or_errors = coroutine.resume(job_task, 1, status)
if not ok then
return false, job_proc_or_errors
end
-- the other process is pending for this task?
if coroutine.status(job_task) ~= "dead" then
procs[taskid] = job_proc_or_errors
else
-- mark this task as finished?
tasks_finished[taskid] = true
end
end
-- update the pending tasks and procs
local tasks_pending = {}
local procs_pending = {}
local indices_pending = {}
for taskid, job_task in ipairs(tasks) do
if not tasks_finished[taskid] and procs[taskid] ~= nil then -- for coroutine.yield(proc) in os.execv
table.insert(tasks_pending, job_task)
table.insert(procs_pending, procs[taskid])
table.insert(indices_pending, indices[taskid])
end
end
for taskid, job_task in ipairs(tasks) do
if not tasks_finished[taskid] and procs[taskid] == nil then -- for coroutine.yield()
table.insert(tasks_pending, job_task)
table.insert(indices_pending, indices[taskid])
end
end
tasks = tasks_pending
procs = procs_pending
indices = indices_pending
-- produce tasks
tasks_pending = {}
indices_pending = {}
while (#tasks + #tasks_pending) < comax and index <= total do
-- new task
local job_task = coroutine.create(jobfunc)
-- resume it first
local ok, job_proc_or_errors = coroutine.resume(job_task, index)
if not ok then
return false, job_proc_or_errors
end
-- add pending tasks
if coroutine.status(job_task) ~= "dead" then
if job_proc_or_errors ~= nil then -- for coroutine.yield(proc) in os.execv
table.insert(tasks, job_task)
table.insert(procs, job_proc_or_errors)
table.insert(indices, index)
else
table.insert(tasks_pending, job_task)
table.insert(indices_pending, index)
end
end
-- next index
index = index + 1
end
-- append pending tasks without process
table.join2(tasks, tasks_pending)
table.join2(indices, indices_pending)
until #tasks == 0
-- ok
return true
end
-- return module: process
return process
|
--!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 process.lua
--
-- define module: process
local process = process or {}
-- load modules
local utils = require("base/utils")
local string = require("base/string")
local coroutine = require("base/coroutine")
-- async run task and echo waiting info
function process.asyncrun(task, waitchars)
-- create a coroutine task
task = coroutine.create(task)
-- trace
local waitindex = 0
local waitchars = waitchars or {'\\', '|', '/', '-'}
utils.printf(waitchars[waitindex + 1])
-- start and wait this task
local ok, errors = coroutine.resume(task)
if not ok then
-- remove wait charactor
utils.printf("\b")
-- failed
return false, errors
end
-- wait and poll task
while coroutine.status(task) ~= "dead" do
-- trace
waitindex = ((waitindex + 1) % #waitchars)
utils.printf("\b" .. waitchars[waitindex + 1])
-- wait some time
os.sleep(300)
-- continue to poll this task
local ok, errors = coroutine.resume(task, 0)
if not ok then
-- remove wait charactor
utils.printf("\b")
-- failed
return false, errors
end
end
-- remove wait charactor
utils.printf("\b")
-- ok
return true
end
-- run jobs with processes
function process.runjobs(jobfunc, total, comax, timeout, timer)
-- init max coroutine count
comax = comax or total
-- init timeout
timeout = timeout or -1
-- make objects
local index = 1
local tasks = {}
local procs = {}
local indices = {}
local time = os.mclock()
repeat
-- wait processes
local tasks_finished = {}
local procs_count = #procs
local procs_infos = nil
if procs_count > 0 then
local count = -1
count, procs_infos = process.waitlist(procs, utils.ifelse(#tasks < comax and index <= total, 0, timeout))
if count < 0 then
return false, string.format("wait processes(%d) failed(%d)", #procs, count)
end
end
-- timer is triggered? call timer
if timer and os.mclock() - time > timeout then
timer(indices)
time = os.mclock()
end
-- append fake procs_infos for coroutine.yield()
procs_infos = procs_infos or {}
for taskid = #procs + 1, #tasks do
table.insert(procs_infos, {nil, taskid, 0})
end
-- wait ok
for _, procinfo in ipairs(procs_infos) do
-- the process info
local proc = procinfo[1]
local taskid = procinfo[2]
local status = procinfo[3]
-- check
assert(procs[taskid] == proc)
-- resume this task
local job_task = tasks[taskid]
local ok, job_proc_or_errors = coroutine.resume(job_task, 1, status)
if not ok then
return false, job_proc_or_errors
end
-- the other process is pending for this task?
if coroutine.status(job_task) ~= "dead" then
procs[taskid] = job_proc_or_errors
else
-- mark this task as finished?
tasks_finished[taskid] = true
end
end
-- update the pending tasks and procs
local tasks_pending1 = {}
local procs_pending1 = {}
local indices_pending1 = {}
local tasks_pending2 = {}
local indices_pending2 = {}
for taskid, job_task in ipairs(tasks) do
if not tasks_finished[taskid] and procs[taskid] ~= nil then -- for coroutine.yield(proc) in os.execv
table.insert(tasks_pending1, job_task)
table.insert(procs_pending1, procs[taskid])
table.insert(indices_pending1, indices[taskid])
end
end
for taskid, job_task in ipairs(tasks) do
if not tasks_finished[taskid] and procs[taskid] == nil then -- for coroutine.yield()
table.insert(tasks_pending2, job_task)
table.insert(indices_pending2, indices[taskid])
end
end
-- produce tasks
while (#tasks_pending1 + #tasks_pending2) < comax and index <= total do
-- new task
local job_task = coroutine.create(jobfunc)
-- resume it first
local ok, job_proc_or_errors = coroutine.resume(job_task, index)
if not ok then
return false, job_proc_or_errors
end
-- add pending tasks
if coroutine.status(job_task) ~= "dead" then
if job_proc_or_errors ~= nil then -- for coroutine.yield(proc) in os.execv
table.insert(tasks_pending1, job_task)
table.insert(procs_pending1, job_proc_or_errors)
table.insert(indices_pending1, index)
else
table.insert(tasks_pending2, job_task)
table.insert(indices_pending2, index)
end
end
-- next index
index = index + 1
end
-- merge pending tasks
procs = procs_pending1
tasks = table.join(tasks_pending1, tasks_pending2)
indices = table.join(indices_pending1, indices_pending2)
until #tasks == 0
-- ok
return true
end
-- return module: process
return process
|
fix process.runjobs
|
fix process.runjobs
|
Lua
|
apache-2.0
|
waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake
|
cc6cf72d6039604ba33fdddf2a410db34756e633
|
src/base/detoken.lua
|
src/base/detoken.lua
|
--
-- detoken.lua
--
-- Expands tokens.
--
-- Copyright (c) 2011-2014 Jason Perkins and the Premake project
--
premake.detoken = {}
local p = premake
local detoken = p.detoken
--
-- Expand tokens in a value.
--
-- @param value
-- The value containing the tokens to be expanded.
-- @param environ
-- An execution environment for any token expansion. This is a list of
-- key-value pairs that will be inserted as global variables into the
-- token expansion runtime environment.
-- @param field
-- The definition of the field which stores the value.
-- @param basedir
-- If provided, path tokens encountered in non-path fields (where
-- field.paths is set to false) will be made relative to this location.
-- @return
-- The value with any contained tokens expanded.
--
function detoken.expand(value, environ, field, basedir)
field = field or {}
-- fetch the path variable from the action, if needed
local varMap = {}
if field.pathVars then
local action = p.action.current()
if action then
varMap = action.pathVars or {}
end
end
-- enable access to the global environment
setmetatable(environ, {__index = _G})
function expandtoken(token, environ)
-- convert the token into a function to execute
local func, err = loadstring("return " .. token)
if not func then
return nil, err
end
-- give the function access to the project objects
setfenv(func, environ)
-- run it and get the result
local result = func() or ""
-- If the result is an absolute path, and it is being inserted into
-- a NON-path value, I need to make it relative to the project that
-- will contain it. Otherwise I ended up with an absolute path in
-- the generated project, and it can no longer be moved around.
local isAbs = path.isabsolute(result)
if isAbs and not field.paths and basedir then
result = path.getrelative(basedir, result)
end
-- If this token is in my path variable mapping table, replace the
-- value with the one from the map. This needs to go here because
-- I don't want to make the result relative, but I don't want the
-- absolute path handling below.
if varMap[token] then
result = varMap[token]
if type(result) == "function" then
result = result(environ)
end
isAbs = path.isabsolute(result)
end
-- If the result is an absolute path, and it is being inserted into
-- a path value, place a special marker at the start of it. After
-- all results have been processed, I can look for these markers to
-- find the last absolute path expanded.
--
-- Example: the value "/home/user/myprj/%{cfg.objdir}" expands to:
-- "/home/user/myprj//home/user/myprj/obj/Debug".
--
-- By inserting a marker this becomes:
-- "/home/user/myprj/[\0]/home/user/myprj/obj/Debug".
--
-- I can now trim everything before the marker to get the right
-- result, which should always be the last absolute path specified:
-- "/home/user/myprj/obj/Debug"
if isAbs and field.paths then
result = "\0" .. result
end
return result
end
function expandvalue(value)
if type(value) ~= "string" then
return value
end
local count
repeat
value, count = value:gsub("%%{(.-)}", function(token)
local result, err = expandtoken(token:gsub("\\", "\\\\"), environ)
if not result then
error(err, 0)
end
return result
end)
until count == 0
-- if a path, look for a split out embedded absolute paths
if field.paths then
local i, j
repeat
i, j = value:find("\0")
if i then
value = value:sub(i + 1)
end
until not i
end
return value
end
function recurse(value)
if type(value) == "table" then
local res_table = {}
for k, v in pairs(value) do
if tonumber(k) ~= nil then
res_table[k] = recurse(v, e)
else
local nk = recurse(k, e);
res_table[nk] = recurse(v, e)
end
end
return res_table
else
return expandvalue(value)
end
end
return recurse(value)
end
|
--
-- detoken.lua
--
-- Expands tokens.
--
-- Copyright (c) 2011-2014 Jason Perkins and the Premake project
--
premake.detoken = {}
local p = premake
local detoken = p.detoken
--
-- Expand tokens in a value.
--
-- @param value
-- The value containing the tokens to be expanded.
-- @param environ
-- An execution environment for any token expansion. This is a list of
-- key-value pairs that will be inserted as global variables into the
-- token expansion runtime environment.
-- @param field
-- The definition of the field which stores the value.
-- @param basedir
-- If provided, path tokens encountered in non-path fields (where
-- field.paths is set to false) will be made relative to this location.
-- @return
-- The value with any contained tokens expanded.
--
function detoken.expand(value, environ, field, basedir)
field = field or {}
-- fetch the path variable from the action, if needed
local varMap = {}
if field.pathVars then
local action = p.action.current()
if action then
varMap = action.pathVars or {}
end
end
-- enable access to the global environment
setmetatable(environ, {__index = _G})
function expandtoken(token, e)
-- convert the token into a function to execute
local func, err = loadstring("return " .. token)
if not func then
return nil, err
end
-- give the function access to the project objects
setfenv(func, e)
-- run it and get the result
local result = func() or ""
-- If the result is an absolute path, and it is being inserted into
-- a NON-path value, I need to make it relative to the project that
-- will contain it. Otherwise I ended up with an absolute path in
-- the generated project, and it can no longer be moved around.
local isAbs = path.isabsolute(result)
if isAbs and not field.paths and basedir then
result = path.getrelative(basedir, result)
end
-- If this token is in my path variable mapping table, replace the
-- value with the one from the map. This needs to go here because
-- I don't want to make the result relative, but I don't want the
-- absolute path handling below.
if varMap[token] then
result = varMap[token]
if type(result) == "function" then
result = result(e)
end
isAbs = path.isabsolute(result)
end
-- If the result is an absolute path, and it is being inserted into
-- a path value, place a special marker at the start of it. After
-- all results have been processed, I can look for these markers to
-- find the last absolute path expanded.
--
-- Example: the value "/home/user/myprj/%{cfg.objdir}" expands to:
-- "/home/user/myprj//home/user/myprj/obj/Debug".
--
-- By inserting a marker this becomes:
-- "/home/user/myprj/[\0]/home/user/myprj/obj/Debug".
--
-- I can now trim everything before the marker to get the right
-- result, which should always be the last absolute path specified:
-- "/home/user/myprj/obj/Debug"
if isAbs and field.paths then
result = "\0" .. result
end
return result
end
function expandvalue(value, e)
if type(value) ~= "string" then
return value
end
local count
repeat
value, count = value:gsub("%%{(.-)}", function(token)
local result, err = expandtoken(token:gsub("\\", "\\\\"), e)
if not result then
error(err, 0)
end
return result
end)
until count == 0
-- if a path, look for a split out embedded absolute paths
if field.paths then
local i, j
repeat
i, j = value:find("\0")
if i then
value = value:sub(i + 1)
end
until not i
end
return value
end
function recurse(value, e)
if type(value) == "table" then
local res_table = {}
for k, v in pairs(value) do
if tonumber(k) ~= nil then
res_table[k] = recurse(v, e)
else
local nk = recurse(k, e);
res_table[nk] = recurse(v, e)
end
end
return res_table
else
return expandvalue(value, e)
end
end
return recurse(value, environ)
end
|
Fix bug in recursive calls to detoken.
|
Fix bug in recursive calls to detoken.
|
Lua
|
bsd-3-clause
|
dcourtois/premake-core,prapin/premake-core,mandersan/premake-core,mendsley/premake-core,Zefiros-Software/premake-core,Zefiros-Software/premake-core,sleepingwit/premake-core,tvandijck/premake-core,resetnow/premake-core,sleepingwit/premake-core,dcourtois/premake-core,Zefiros-Software/premake-core,jstewart-amd/premake-core,sleepingwit/premake-core,akaStiX/premake-core,soundsrc/premake-core,CodeAnxiety/premake-core,dcourtois/premake-core,mendsley/premake-core,mandersan/premake-core,premake/premake-core,LORgames/premake-core,lizh06/premake-core,starkos/premake-core,CodeAnxiety/premake-core,lizh06/premake-core,aleksijuvani/premake-core,premake/premake-core,xriss/premake-core,bravnsgaard/premake-core,jsfdez/premake-core,aleksijuvani/premake-core,mendsley/premake-core,resetnow/premake-core,Blizzard/premake-core,xriss/premake-core,starkos/premake-core,dcourtois/premake-core,resetnow/premake-core,martin-traverse/premake-core,premake/premake-core,jstewart-amd/premake-core,resetnow/premake-core,Blizzard/premake-core,noresources/premake-core,jsfdez/premake-core,Blizzard/premake-core,jsfdez/premake-core,Blizzard/premake-core,Blizzard/premake-core,noresources/premake-core,jsfdez/premake-core,soundsrc/premake-core,CodeAnxiety/premake-core,jstewart-amd/premake-core,aleksijuvani/premake-core,tritao/premake-core,LORgames/premake-core,LORgames/premake-core,noresources/premake-core,mandersan/premake-core,starkos/premake-core,bravnsgaard/premake-core,TurkeyMan/premake-core,sleepingwit/premake-core,dcourtois/premake-core,Blizzard/premake-core,saberhawk/premake-core,noresources/premake-core,prapin/premake-core,Zefiros-Software/premake-core,xriss/premake-core,bravnsgaard/premake-core,starkos/premake-core,bravnsgaard/premake-core,tritao/premake-core,mendsley/premake-core,martin-traverse/premake-core,tvandijck/premake-core,tvandijck/premake-core,noresources/premake-core,xriss/premake-core,mendsley/premake-core,LORgames/premake-core,martin-traverse/premake-core,tvandijck/premake-core,saberhawk/premake-core,CodeAnxiety/premake-core,premake/premake-core,saberhawk/premake-core,jstewart-amd/premake-core,TurkeyMan/premake-core,LORgames/premake-core,prapin/premake-core,bravnsgaard/premake-core,lizh06/premake-core,Zefiros-Software/premake-core,TurkeyMan/premake-core,saberhawk/premake-core,soundsrc/premake-core,premake/premake-core,lizh06/premake-core,sleepingwit/premake-core,soundsrc/premake-core,aleksijuvani/premake-core,CodeAnxiety/premake-core,dcourtois/premake-core,tritao/premake-core,dcourtois/premake-core,premake/premake-core,akaStiX/premake-core,noresources/premake-core,starkos/premake-core,TurkeyMan/premake-core,soundsrc/premake-core,aleksijuvani/premake-core,xriss/premake-core,jstewart-amd/premake-core,resetnow/premake-core,mandersan/premake-core,martin-traverse/premake-core,akaStiX/premake-core,premake/premake-core,prapin/premake-core,mandersan/premake-core,TurkeyMan/premake-core,starkos/premake-core,noresources/premake-core,starkos/premake-core,tvandijck/premake-core,tritao/premake-core,akaStiX/premake-core
|
ce6e262c6d840d636fcfbecb8dd6c989a6ec5f29
|
packages/lime-proto-bmx6/src/bmx6.lua
|
packages/lime-proto-bmx6/src/bmx6.lua
|
#!/usr/bin/lua
local network = require("lime.network")
local config = require("lime.config")
local fs = require("nixio.fs")
local libuci = require("uci")
local wireless = require("lime.wireless")
bmx6 = {}
function bmx6.setup_interface(ifname, args)
if ifname:match("^wlan%d.ap") then return end
vlanId = args[2] or 13
vlanProto = args[3] or "8021ad"
nameSuffix = args[4] or "_bmx6"
local owrtInterfaceName, linux802adIfName, owrtDeviceName = network.createVlanIface(ifname, vlanId, nameSuffix, vlanProto)
local uci = libuci:cursor()
uci:set("network", owrtDeviceName, "mtu", "1398")
-- BEGIN [Workaround issue 38]
if ifname:match("^wlan%d+") then
local macAddr = wireless.get_phy_mac("phy"..ifname:match("%d+"))
local vlanIp = { 169, 254, tonumber(macAddr[5], 16), tonumber(macAddr[6], 16) }
uci:set("network", owrtInterfaceName, "proto", "static")
uci:set("network", owrtInterfaceName, "ipaddr", table.concat(vlanIp, "."))
uci:set("network", owrtInterfaceName, "netmask", "255.255.255.255")
end
--- END [Workaround issue 38]
uci:save("network")
uci:set("bmx6", owrtInterfaceName, "dev")
uci:set("bmx6", owrtInterfaceName, "dev", linux802adIfName)
-- BEGIN [Workaround issue 40]
if ifname:match("^wlan%d+") then
uci:set("bmx6", owrtInterfaceName, "rateMax", "54000")
end
--- END [Workaround issue 40]
uci:save("bmx6")
end
function bmx6.clean()
print("Clearing bmx6 config...")
fs.writefile("/etc/config/bmx6", "")
local uci = libuci:cursor()
uci:delete("firewall", "bmxtun")
uci:save("firewall")
end
function bmx6.configure(args)
bmx6.clean()
local ipv4, ipv6 = network.primary_address()
local uci = libuci:cursor()
uci:set("bmx6", "general", "bmx6")
uci:set("bmx6", "general", "dbgMuteTimeout", "1000000")
uci:set("bmx6", "general", "tunOutTimeout", "0")
uci:set("bmx6", "main", "tunDev")
uci:set("bmx6", "main", "tunDev", "main")
uci:set("bmx6", "main", "tun4Address", ipv4:host():string().."/32")
uci:set("bmx6", "main", "tun6Address", ipv6:host():string().."/128")
-- Enable bmx6 uci config plugin
uci:set("bmx6", "config", "plugin")
uci:set("bmx6", "config", "plugin", "bmx6_config.so")
-- Enable JSON plugin to get bmx6 information in json format
uci:set("bmx6", "json", "plugin")
uci:set("bmx6", "json", "plugin", "bmx6_json.so")
-- Disable ThrowRules because they are broken in IPv6 with current Linux Kernel
uci:set("bmx6", "ipVersion", "ipVersion")
uci:set("bmx6", "ipVersion", "ipVersion", "6")
-- Search for networks in 172.16.0.0/12
uci:set("bmx6", "nodes", "tunOut")
uci:set("bmx6", "nodes", "tunOut", "nodes")
uci:set("bmx6", "nodes", "network", "172.16.0.0/12")
-- Search for networks in 10.0.0.0/8
uci:set("bmx6", "clouds", "tunOut")
uci:set("bmx6", "clouds", "tunOut", "clouds")
uci:set("bmx6", "clouds", "network", "10.0.0.0/8")
-- Search for internet in the mesh cloud
uci:set("bmx6", "inet4", "tunOut")
uci:set("bmx6", "inet4", "tunOut", "inet4")
uci:set("bmx6", "inet4", "network", "0.0.0.0/0")
uci:set("bmx6", "inet4", "maxPrefixLen", "0")
-- Search for internet IPv6 gateways in the mesh cloud
uci:set("bmx6", "inet6", "tunOut")
uci:set("bmx6", "inet6", "tunOut", "inet6")
uci:set("bmx6", "inet6", "network", "::/0")
uci:set("bmx6", "inet6", "maxPrefixLen", "0")
-- Search for other mesh cloud announcements that have public ipv6
uci:set("bmx6", "publicv6", "tunOut")
uci:set("bmx6", "publicv6", "tunOut", "publicv6")
uci:set("bmx6", "publicv6", "network", "2000::/3")
uci:set("bmx6", "publicv6", "maxPrefixLen", "64")
-- Announce local ipv4 cloud
uci:set("bmx6", "local4", "tunIn")
uci:set("bmx6", "local4", "tunIn", "local4")
uci:set("bmx6", "local4", "network", ipv4:network():string().."/"..ipv4:prefix())
-- Announce local ipv6 cloud
uci:set("bmx6", "local6", "tunIn")
uci:set("bmx6", "local6", "tunIn", "local6")
uci:set("bmx6", "local6", "network", ipv6:network():string().."/"..ipv6:prefix())
if config.get_bool("network", "bmx6_over_batman") then
for _,protoArgs in pairs(config.get("network", "protocols")) do
if(utils.split(protoArgs, network.protoParamsSeparator)[1] == "batadv") then bmx6.setup_interface("bat0", args) end
end
end
uci:save("bmx6")
uci:set("firewall", "bmxtun", "zone")
uci:set("firewall", "bmxtun", "name", "bmxtun")
uci:set("firewall", "bmxtun", "input", "ACCEPT")
uci:set("firewall", "bmxtun", "output", "ACCEPT")
uci:set("firewall", "bmxtun", "forward", "ACCEPT")
uci:set("firewall", "bmxtun", "mtu_fix", "1")
uci:set("firewall", "bmxtun", "device", "bmx+")
uci:set("firewall", "bmxtun", "family", "ipv4")
uci:save("firewall")
end
function bmx6.apply()
os.execute("killall bmx6 ; sleep 2 ; killall -9 bmx6")
os.execute("bmx6")
end
return bmx6
|
#!/usr/bin/lua
local network = require("lime.network")
local config = require("lime.config")
local fs = require("nixio.fs")
local libuci = require("uci")
local wireless = require("lime.wireless")
bmx6 = {}
function bmx6.setup_interface(ifname, args)
if ifname:match("^wlan%d.ap") then return end
vlanId = args[2] or 13
vlanProto = args[3] or "8021ad"
nameSuffix = args[4] or "_bmx6"
local owrtInterfaceName, linux802adIfName, owrtDeviceName = network.createVlanIface(ifname, vlanId, nameSuffix, vlanProto)
local uci = libuci:cursor()
uci:set("network", owrtDeviceName, "mtu", "1398")
-- BEGIN [Workaround issue 38]
if ifname:match("^wlan%d+") then
local macAddr = wireless.get_phy_mac("phy"..ifname:match("%d+"))
local vlanIp = { 169, 254, tonumber(macAddr[5], 16), tonumber(macAddr[6], 16) }
uci:set("network", owrtInterfaceName, "proto", "static")
uci:set("network", owrtInterfaceName, "ipaddr", table.concat(vlanIp, "."))
uci:set("network", owrtInterfaceName, "netmask", "255.255.255.255")
end
--- END [Workaround issue 38]
uci:save("network")
uci:set("bmx6", owrtInterfaceName, "dev")
uci:set("bmx6", owrtInterfaceName, "dev", linux802adIfName)
-- BEGIN [Workaround issue 40]
if ifname:match("^wlan%d+") then
uci:set("bmx6", owrtInterfaceName, "rateMax", "54000")
end
--- END [Workaround issue 40]
uci:save("bmx6")
end
function bmx6.clean()
print("Clearing bmx6 config...")
fs.writefile("/etc/config/bmx6", "")
local uci = libuci:cursor()
uci:delete("firewall", "bmxtun")
uci:save("firewall")
end
function bmx6.configure(args)
bmx6.clean()
local ipv4, ipv6 = network.primary_address()
local uci = libuci:cursor()
uci:set("bmx6", "general", "bmx6")
uci:set("bmx6", "general", "dbgMuteTimeout", "1000000")
uci:set("bmx6", "general", "tunOutTimeout", "0")
uci:set("bmx6", "main", "tunDev")
uci:set("bmx6", "main", "tunDev", "main")
uci:set("bmx6", "main", "tun4Address", ipv4:host():string().."/32")
uci:set("bmx6", "main", "tun6Address", ipv6:host():string().."/128")
-- Enable bmx6 uci config plugin
uci:set("bmx6", "config", "plugin")
uci:set("bmx6", "config", "plugin", "bmx6_config.so")
-- Enable JSON plugin to get bmx6 information in json format
uci:set("bmx6", "json", "plugin")
uci:set("bmx6", "json", "plugin", "bmx6_json.so")
-- Disable ThrowRules because they are broken in IPv6 with current Linux Kernel
uci:set("bmx6", "ipVersion", "ipVersion")
uci:set("bmx6", "ipVersion", "ipVersion", "6")
-- Search for networks in 172.16.0.0/12
uci:set("bmx6", "nodes", "tunOut")
uci:set("bmx6", "nodes", "tunOut", "nodes")
uci:set("bmx6", "nodes", "network", "172.16.0.0/12")
-- Search for networks in 10.0.0.0/8
uci:set("bmx6", "clouds", "tunOut")
uci:set("bmx6", "clouds", "tunOut", "clouds")
uci:set("bmx6", "clouds", "network", "10.0.0.0/8")
-- Search for internet in the mesh cloud
uci:set("bmx6", "inet4", "tunOut")
uci:set("bmx6", "inet4", "tunOut", "inet4")
uci:set("bmx6", "inet4", "network", "0.0.0.0/0")
uci:set("bmx6", "inet4", "maxPrefixLen", "0")
-- Search for internet IPv6 gateways in the mesh cloud
uci:set("bmx6", "inet6", "tunOut")
uci:set("bmx6", "inet6", "tunOut", "inet6")
uci:set("bmx6", "inet6", "network", "::/0")
uci:set("bmx6", "inet6", "maxPrefixLen", "0")
-- Search for other mesh cloud announcements that have public ipv6
uci:set("bmx6", "publicv6", "tunOut")
uci:set("bmx6", "publicv6", "tunOut", "publicv6")
uci:set("bmx6", "publicv6", "network", "2000::/3")
uci:set("bmx6", "publicv6", "maxPrefixLen", "64")
-- Announce local ipv4 cloud
uci:set("bmx6", "local4", "tunIn")
uci:set("bmx6", "local4", "tunIn", "local4")
uci:set("bmx6", "local4", "network", ipv4:network():string().."/"..ipv4:prefix())
-- Announce local ipv6 cloud
uci:set("bmx6", "local6", "tunIn")
uci:set("bmx6", "local6", "tunIn", "local6")
uci:set("bmx6", "local6", "network", ipv6:network():string().."/"..ipv6:prefix())
if config.get_bool("network", "bmx6_over_batman") then
for _,protoArgs in pairs(config.get("network", "protocols")) do
if(utils.split(protoArgs, network.protoParamsSeparator)[1] == "batadv") then bmx6.setup_interface("bat0", args) end
end
end
uci:save("bmx6")
uci:set("firewall", "bmxtun", "zone")
uci:set("firewall", "bmxtun", "name", "bmxtun")
uci:set("firewall", "bmxtun", "input", "ACCEPT")
uci:set("firewall", "bmxtun", "output", "ACCEPT")
uci:set("firewall", "bmxtun", "forward", "ACCEPT")
uci:set("firewall", "bmxtun", "mtu_fix", "1")
uci:set("firewall", "bmxtun", "conntrack", "1")
uci:set("firewall", "bmxtun", "device", "bmx+")
uci:set("firewall", "bmxtun", "family", "ipv4")
uci:save("firewall")
end
function bmx6.apply()
os.execute("killall bmx6 ; sleep 2 ; killall -9 bmx6")
os.execute("bmx6")
end
return bmx6
|
lime-proto-bmx6: hotfix firewall.bmxtun.conntrack=1
|
lime-proto-bmx6: hotfix firewall.bmxtun.conntrack=1
|
Lua
|
agpl-3.0
|
libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,p4u/lime-packages
|
764b95aa6e6cfdd181a6c1992bd192a10c99ea27
|
modules.lua
|
modules.lua
|
--[[ @cond ___LICENSE___
-- Copyright (c) 2017 Zefiros Software.
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
-- @endcond
--]]
-- Modules
zpm.modules = { }
zpm.modules.modules = { }
function zpm.modules.suggestModule(vendor, name)
zpm.assert(zpm.modules.modules[vendor] ~= nil, "Requiring module with vendor '%s' does not exist!", vendor)
zpm.assert(zpm.modules.modules[vendor][name] ~= nil, "Requiring module with vendor '%s' and name '%s' does not exist!", vendor, name)
end
function zpm.modules.isModuleInstalled(vendor, name)
if name ~= nil then
return os.isdir(path.join(zpm.install.getModulesDir(), path.join(vendor, name)))
end
return os.isdir(path.join(zpm.install.getModulesDir(), vendor))
end
function zpm.modules.installOrUpdateModules(modules)
for _, module in ipairs(modules) do
local pak = bootstrap.getModule(module)
local name = pak[2]
local vendor = pak[1]
zpm.assert(zpm.modules.modules[vendor] ~= nil, "Requiring module with vendor '%s' does not exist!", vendor)
zpm.assert(zpm.modules.modules[vendor][name] ~= nil, "Requiring module with vendor '%s' and name '%s' does not exist!", vendor, name)
zpm.util.askModuleConfirmation(string.format("Do you want to install or update module '%s/%s'?", vendor, name),
function()
local modPath = path.join(zpm.install.getModulesDir(), path.join(vendor, name))
local head = path.join(modPath, "head")
zpm.modules.update(head, modPath, { vendor, name })
end ,
function()
end )
end
end
function zpm.modules.installOrUpdateModule()
zpm.install.updatePremake(true)
zpm.assert(#_ARGS > 0, "No module specified to install or update!")
local module = { }
if #_ARGS > 1 then
module = { _ARGS[1], _ARGS[2] }
else
module = bootstrap.getModule(_ARGS[1])
end
local ok = zpm.modules.suggestModule(module[1], module[2])
if ok then
local modPath = path.join(zpm.install.getModulesDir(), path.join(module[1], module[2]))
local head = path.join(modPath, "head")
printf("- Installing or updating module '%s/%s'", module[1], module[2])
zpm.modules.update(head, modPath, module)
end
end
function zpm.modules.update(head, modPath, module)
zpm.git.cloneOrPull(head, zpm.modules.modules[module[1]][module[2]].repository)
local tags = zpm.git.getTags(head)
for _, tag in ipairs(tags) do
local verPath = path.join(modPath, tag.version)
if not os.isdir(verPath) then
printf("- Installing version '%s'", tag.version)
local zipFile = path.join(modPath, "archive.zip")
zpm.git.archive(head, zipFile, tag.tag)
assert(os.mkdir(verPath))
zip.extract(zipFile, verPath)
os.remove(zipFile)
zpm.assert(os.isfile(zipFile) == false, "Zipfile '%s' failed to remove!", zipFile)
end
end
end
function zpm.modules.setSearchDir()
if bootstrap ~= nil then
-- override default location
bootstrap.directories = zpm.util.concat( { path.join(zpm.cache, "modules") }, bootstrap.directories)
end
end
function zpm.modules.load()
for _, dir in ipairs(table.insertflat( { _MAIN_SCRIPT_DIR }, zpm.registry.dirs)) do
local localModFile = path.join(dir, zpm.install.registry.modules)
if os.isfile(localModFile) then
local manok, err = pcall(zpm.modules.loadFile, localModFile)
if not manok then
printf(zpm.colors.error .. "Failed to load modules '%s':\n%s", dir, err)
end
end
end
end
function zpm.modules.loadFile(file)
if not os.isfile(file) then
return nil
end
local modules = zpm.JSON:decode(zpm.util.readAll(file))
for _, module in ipairs(modules) do
local man = bootstrap.getModule(module.name)
local name = man[2]
local vendor = man[1]
zpm.assert(name ~= nil, "No 'name' supplied in module definition!")
zpm.assert(vendor ~= nil, "No 'vendor' supplied in module definition!")
zpm.assert(module.repository ~= nil, "No 'repository' supplied in module definition!")
zpm.assert(zpm.util.isAlphaNumeric(name), "'name' supplied in module definition must be alpha numeric!")
zpm.assert(name:len() <= 50, "'name' supplied in module definition exceeds maximum size of 50 characters!")
zpm.assert(name:len() >= 2, "'name' supplied in module definition must at least be 2 characters!")
zpm.assert(zpm.util.isAlphaNumeric(vendor), "'vendor' supplied in module definition must be alpha numeric!")
zpm.assert(vendor:len() <= 50, "'vendor' supplied in module definition exceeds maximum size of 50 characters!")
zpm.assert(vendor:len() >= 2, "'vendor' supplied in module definition must at least be 2 characters!")
zpm.assert(zpm.util.isGitUrl(module.repository), "'repository' supplied in module definition is not a valid https git url!")
if zpm.modules.modules[vendor] == nil then
zpm.modules.modules[vendor] = { }
end
if zpm.modules.modules[vendor][name] == nil then
zpm.modules.modules[vendor][name] = { }
zpm.modules.modules[vendor][name].includedirs = { }
zpm.modules.modules[vendor][name].repository = module.repository
end
end
end
function zpm.modules.listModules()
return os.matchdirs(path.join(zpm.install.getModulesDir(), "*/*/"))
end
function zpm.modules.updateModules()
local matches = zpm.modules.listModules()
for _, match in ipairs(matches) do
local vendor, name = match:match(".*/(.*)/(.*)")
local module = { vendor, name }
printf("Updating module '%s/%s'...", module[1], module[2])
zpm.modules.update(path.join(match, "head"), match, module)
end
end
|
--[[ @cond ___LICENSE___
-- Copyright (c) 2017 Zefiros Software.
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
-- @endcond
--]]
-- Modules
zpm.modules = { }
zpm.modules.modules = { }
function zpm.modules.suggestModule(vendor, name)
zpm.assert(zpm.modules.modules[vendor] ~= nil, "Requiring module with vendor '%s' does not exist!", vendor)
zpm.assert(zpm.modules.modules[vendor][name] ~= nil, "Requiring module with vendor '%s' and name '%s' does not exist!", vendor, name)
end
function zpm.modules.isModuleInstalled(vendor, name)
if name ~= nil then
return os.isdir(path.join(zpm.install.getModulesDir(), path.join(vendor, name)))
end
return os.isdir(path.join(zpm.install.getModulesDir(), vendor))
end
function zpm.modules.installOrUpdateModules(modules)
for _, module in ipairs(modules) do
local pak = bootstrap.getModule(module)
local name = pak[2]
local vendor = pak[1]
zpm.assert(zpm.modules.modules[vendor] ~= nil, "Requiring module with vendor '%s' does not exist!", vendor)
zpm.assert(zpm.modules.modules[vendor][name] ~= nil, "Requiring module with vendor '%s' and name '%s' does not exist!", vendor, name)
zpm.util.askModuleConfirmation(string.format("Do you want to install or update module '%s/%s'?", vendor, name),
function()
local modPath = path.join(zpm.install.getModulesDir(), path.join(vendor, name))
local head = path.join(modPath, "head")
zpm.modules.update(head, modPath, { vendor, name })
end ,
function()
end )
end
end
function zpm.modules.installOrUpdateModule()
zpm.install.updatePremake(true)
zpm.assert(#_ARGS > 0, "No module specified to install or update!")
local module = { }
if #_ARGS > 1 then
module = { _ARGS[1], _ARGS[2] }
else
module = bootstrap.getModule(_ARGS[1])
end
zpm.modules.suggestModule(module[1], module[2])
local modPath = path.join(zpm.install.getModulesDir(), path.join(module[1], module[2]))
local head = path.join(modPath, "head")
printf("- Installing or updating module '%s/%s'", module[1], module[2])
zpm.modules.update(head, modPath, module)
end
function zpm.modules.update(head, modPath, module)
zpm.git.cloneOrPull(head, zpm.modules.modules[module[1]][module[2]].repository)
local tags = zpm.git.getTags(head)
for _, tag in ipairs(tags) do
local verPath = path.join(modPath, tag.version)
if not os.isdir(verPath) then
printf("- Installing version '%s'", tag.version)
local zipFile = path.join(modPath, "archive.zip")
zpm.git.archive(head, zipFile, tag.tag)
assert(os.mkdir(verPath))
zip.extract(zipFile, verPath)
os.remove(zipFile)
zpm.assert(os.isfile(zipFile) == false, "Zipfile '%s' failed to remove!", zipFile)
end
end
end
function zpm.modules.setSearchDir()
if bootstrap ~= nil then
-- override default location
bootstrap.directories = zpm.util.concat( { path.join(zpm.cache, "modules") }, bootstrap.directories)
end
end
function zpm.modules.load()
for _, dir in ipairs(table.insertflat( { _MAIN_SCRIPT_DIR }, zpm.registry.dirs)) do
local localModFile = path.join(dir, zpm.install.registry.modules)
if os.isfile(localModFile) then
local manok, err = pcall(zpm.modules.loadFile, localModFile)
if not manok then
printf(zpm.colors.error .. "Failed to load modules '%s':\n%s", dir, err)
end
end
end
end
function zpm.modules.loadFile(file)
if not os.isfile(file) then
return nil
end
local modules = zpm.JSON:decode(zpm.util.readAll(file))
for _, module in ipairs(modules) do
local man = bootstrap.getModule(module.name)
local name = man[2]
local vendor = man[1]
zpm.assert(name ~= nil, "No 'name' supplied in module definition!")
zpm.assert(vendor ~= nil, "No 'vendor' supplied in module definition!")
zpm.assert(module.repository ~= nil, "No 'repository' supplied in module definition!")
zpm.assert(zpm.util.isAlphaNumeric(name), "'name' supplied in module definition must be alpha numeric!")
zpm.assert(name:len() <= 50, "'name' supplied in module definition exceeds maximum size of 50 characters!")
zpm.assert(name:len() >= 2, "'name' supplied in module definition must at least be 2 characters!")
zpm.assert(zpm.util.isAlphaNumeric(vendor), "'vendor' supplied in module definition must be alpha numeric!")
zpm.assert(vendor:len() <= 50, "'vendor' supplied in module definition exceeds maximum size of 50 characters!")
zpm.assert(vendor:len() >= 2, "'vendor' supplied in module definition must at least be 2 characters!")
zpm.assert(zpm.util.isGitUrl(module.repository), "'repository' supplied in module definition is not a valid https git url!")
if zpm.modules.modules[vendor] == nil then
zpm.modules.modules[vendor] = { }
end
if zpm.modules.modules[vendor][name] == nil then
zpm.modules.modules[vendor][name] = { }
zpm.modules.modules[vendor][name].includedirs = { }
zpm.modules.modules[vendor][name].repository = module.repository
end
end
end
function zpm.modules.listModules()
return os.matchdirs(path.join(zpm.install.getModulesDir(), "*/*/"))
end
function zpm.modules.updateModules()
local matches = zpm.modules.listModules()
for _, match in ipairs(matches) do
local vendor, name = match:match(".*/(.*)/(.*)")
local module = { vendor, name }
printf("Updating module '%s/%s'...", module[1], module[2])
zpm.modules.update(path.join(match, "head"), match, module)
end
end
|
Fix install module command line
|
Fix install module command line
|
Lua
|
mit
|
Zefiros-Software/ZPM
|
a604a8b410b46bb602546afd02284f930d2ee8ab
|
src/cosy/webclient/dashboard/init.lua
|
src/cosy/webclient/dashboard/init.lua
|
return function (loader)
local I18n = loader.load "cosy.i18n"
local Scheduler = loader.load "cosy.scheduler"
local Webclient = loader.load "cosy.webclient"
local i18n = I18n.load {
"cosy.webclient.dashboard",
}
i18n._locale = Webclient.window.navigator.language
local Dashboard = {
template = {},
}
Dashboard.__index = Dashboard
Dashboard.template.anonymous = Webclient.template "cosy.webclient.dashboard.anonymous"
Dashboard.template.user = Webclient.template "cosy.webclient.dashboard.user"
local function show_map ()
Dashboard.map = Webclient.js.new (
Webclient.window.google.maps.Map,
Webclient.document:getElementById "map",
Webclient.tojs {
zoom = 1,
center = {
lat = 0,
lng = 0,
},
mapTypeId = Webclient.window.google.maps.MapTypeId.SATELLITE,
streetViewControl = false,
})
local iterator = Webclient.client.server.filter {
iterator = [[
return function (coroutine, store)
for user in store / "data" * ".*" do
coroutine.yield (user)
end
end
]],
}
for user in iterator do
Webclient.js.new (Webclient.window.google.maps.Marker, Webclient.tojs {
position = {
lat = user.position and user.position.latitude or 44.7328221,
lng = user.position and user.position.longitude or 4.5917742,
},
map = Dashboard.map,
draggable = false,
animation = Webclient.window.google.maps.Animation.DROP,
icon = user.avatar and "data:image/png;base64," .. user.avatar.icon or nil,
title = user.identifier,
})
end
end
function Dashboard.anonymous ()
Dashboard.map = nil
while true do
local info = Webclient.client.server.information {}
for k, v in pairs (info) do
local key = k:match "^#(.*)$"
if key then
info ["count-" .. key] = i18n ["dashboard:count-" .. key] % { count = v }
end
end
Webclient.show {
where = "main",
template = Dashboard.template.anonymous,
data = info,
i18n = i18n,
}
if not Dashboard.map then
show_map ()
end
Scheduler.sleep (-math.huge)
end
end
function Dashboard.user ()
while true do
Webclient.show {
where = "main",
template = Dashboard.template.user,
data = {},
i18n = i18n,
}
Scheduler.sleep (-math.huge)
end
end
function Dashboard.__call ()
Webclient (function ()
local user = Webclient.client.user.authentified_as {}
if user.identifier then
Dashboard.user ()
else
Dashboard.anonymous ()
end
end)
end
return setmetatable ({}, Dashboard)
end
|
return function (loader)
local I18n = loader.load "cosy.i18n"
local Scheduler = loader.load "cosy.scheduler"
local Webclient = loader.load "cosy.webclient"
local i18n = I18n.load {
"cosy.webclient.dashboard",
}
i18n._locale = Webclient.window.navigator.language
local Dashboard = {
template = {},
}
Dashboard.__index = Dashboard
Dashboard.template.anonymous = Webclient.template "cosy.webclient.dashboard.anonymous"
Dashboard.template.user = Webclient.template "cosy.webclient.dashboard.user"
local function show_map ()
Dashboard.map = Webclient.js.new (
Webclient.window.google.maps.Map,
Webclient.document:getElementById "map",
Webclient.tojs {
zoom = 1,
center = {
lat = 0,
lng = 0,
},
mapTypeId = Webclient.window.google.maps.MapTypeId.SATELLITE,
streetViewControl = false,
})
local iterator = Webclient.client.server.filter {
iterator = [[
return function (coroutine, store)
for user in store / "data" * ".*" do
coroutine.yield (user)
end
end
]],
}
for user in iterator do
Webclient.js.new (Webclient.window.google.maps.Marker, Webclient.tojs {
position = {
lat = user.position and user.position.latitude or 44.7328221,
lng = user.position and user.position.longitude or 4.5917742,
},
map = Dashboard.map,
draggable = false,
animation = Webclient.window.google.maps.Animation.DROP,
icon = user.avatar and "data:image/png;base64," .. user.avatar.icon or nil,
title = user.identifier,
})
end
end
function Dashboard.anonymous ()
Dashboard.map = nil
while true do
local info = Webclient.client.server.information {}
local data = {}
for k, v in pairs (info) do
local key = k:match "^#(.*)$"
if key then
data ["count-" .. key] = i18n ["dashboard:count-" .. key] % { count = v }
else
data [k] = v
end
end
Webclient.show {
where = "main",
template = Dashboard.template.anonymous,
data = data,
i18n = i18n,
}
if not Dashboard.map then
show_map ()
end
Scheduler.sleep (-math.huge)
end
end
function Dashboard.user ()
while true do
Webclient.show {
where = "main",
template = Dashboard.template.user,
data = {},
i18n = i18n,
}
Scheduler.sleep (-math.huge)
end
end
function Dashboard.__call ()
Webclient (function ()
local user = Webclient.client.user.authentified_as {}
if user.identifier then
Dashboard.user ()
else
Dashboard.anonymous ()
end
end)
end
return setmetatable ({}, Dashboard)
end
|
Fix illegal mix between loop iteration and loop insertion. Fix #209
|
Fix illegal mix between loop iteration and loop insertion.
Fix #209
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
e023cee4f2bdffb7a4a9b047b63767201a4b90eb
|
src/3rdparty/Ads.lua
|
src/3rdparty/Ads.lua
|
--------------------------------------------------------------------------------
--
--
--
--------------------------------------------------------------------------------
local Mock = require("Mock")
local AdProvider = require("AdProvider")
local Ads = class()
-- workaround lua bug with math.random
math.random() math.random() math.random()
---
-- Ads - class for ad rotation from several ad SDKs
-- can receive weight config from remote server
local DEFAULT_URL = "pnc.cloudteam.pro/app/ad_test/"
---
-- Supported providers list. Used as keys in configuration table
Ads.CHARTBOOST = "chartboost"
Ads.PLAYHAVEN = "playhaven"
Ads.AD_COLONY = "adcolony"
Ads.APP_FLOOD = "appflood"
Ads.FLURRY = "flurry"
Ads.INMOBI = "inmobi"
Ads.CPIERA = "cpiera"
local ProviderFactory = {
chartboost = AdProvider.Chartboost,
playhaven = AdProvider.PlayHaven,
adcolony = AdProvider.AdColony,
flurry = AdProvider.FlurryAds,
inmobi = AdProvider.InMobi,
}
---
-- Initialize configuration
-- @param string url remote configuration server address
-- @param table providers initial ad providers configuration. All ad providers in this table will be created.
-- Keys are different for each provider (appIds, zones, placements), however
--
-- Example configuration table:
-- {
-- chartboost = { weight = 1, appId = "id", appSignature = "sign" },
-- playhaven = { weight = 1, appId = "id", appSignature = "sign", placement = "place" },
-- adcolony = { weight = 1, appId = "id", zones = {"zone1", "zone2"} },
-- flurry = { weight = 1, space = "space" }, -- flurry analytics should be initialized before calling this
-- }
function Ads:init(providers, url)
self:setProviders(providers)
self.url = url or DEFAULT_URL
self.os = MOAIAppAndroid and "android" or "ios"
end
function Ads:setProviders(providers)
self.providers = {}
for k, v in pairs(providers) do
local providerClass = ProviderFactory[k]
if not providerClass then
print("Provider for key " .. k .. " not found. Maybe it is not implemented")
else
self.providers[k] = providerClass(v)
self.providers[k].active = true
self.providers[k].adManager = self
end
end
end
function Ads:cacheInterstitial()
for providerName, provider in pairs(self.providers) do
if not provider:hasCachedInterstitial() then
provider:cacheInterstitial()
end
end
end
function Ads:hasCachedInterstitial()
for providerName, provider in pairs(self.providers) do
if provider:hasCachedInterstitial() then
return true
end
end
return false
end
---
-- Returns true if ad was cached and been showed to the user
function Ads:showInterstitial()
local queue = self:getProviderQueue()
print("Provider queue", queue)
for i, provider in ipairs(queue) do
print("----- Trying: ", provider.name)
if provider:hasCachedInterstitial() then
print("----- Has cached ad: ", provider.name)
provider:showInterstitial()
return true
end
end
-- cache all interstitials if nothing been showed
self:cacheInterstitial()
return false
end
---
-- Returns a table with providers
-- shuffled, taking into account their weights
function Ads:getProviderQueue()
local queue = {}
local providers = table.dup(self.providers)
local key, prov = self:getProvider(providers)
while prov do
queue[#queue + 1] = prov
providers[key] = nil
key, prov = self:getProvider(providers)
end
return queue
end
function Ads:getProvider(providers)
local rnd = math.random()
local total = 0
for k, provider in pairs(providers) do
if provider.active then
total = total + provider.weight
end
end
rnd = rnd * total
total = 0
for k, provider in pairs(providers) do
if provider.active then
total = total + provider.weight
if rnd <= total then
return k, provider
end
end
end
end
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- Weight management from server
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
---
-- Request new weight parameters from server and apply them to current providers
-- Some providers can be removed from pool completely
-- Async
function Ads:updateWeights()
local httpTask = HttpTask.new()
httpTask:setUrl(self.url .. "preferences?os=" .. self.os)
httpTask:setVerb(HttpTask.HTTP_GET)
httpTask:setCallback(function(task)
local confStr = task:getString()
if confStr then
local conf = MOAIJsonParser.decode(confStr)
self:onConfigReceived(conf)
end
end)
httpTask:performAsync()
end
function Ads:onConfigReceived(config)
local res, validConfig = self:validateConfig(config)
self:applyConfig(validConfig)
end
---
-- @return bool, table first return value is the result of validation, second value is valid config table.
-- valid table is built by deleting any invalid key-value pairs.
function Ads:validateConfig(config)
local result = true
local validConfig = table.dup(config)
if not config then
print("Ads: config is nil")
return false
end
for k, v in pairs(config) do
if not self.providers[k] then
print("Ads: provider not initialized - " .. k)
result = false
validConfig[k] = nil
end
if type(v) ~= "number" then
print("Ads: weight value [" .. tostring(v) .. "] is not a number for provider " .. k)
result = false
validConfig[k] = nil
end
end
return result, validConfig
end
function Ads:applyConfig(config)
for k, v in pairs(self.providers) do
if config[k] then
v.weight = config[k]
v.active = true
else
v.active = false
end
end
end
return Ads
|
--------------------------------------------------------------------------------
--
--
--
--------------------------------------------------------------------------------
local Mock = require("Mock")
local AdProvider = require("AdProvider")
local Ads = class()
local HttpTask = MOAIHttpTaskNSURL or MOAIHttpTask or Mock("HttpTask mock")
-- workaround lua bug with math.random
math.random() math.random() math.random()
---
-- Ads - class for ad rotation from several ad SDKs
-- can receive weight config from remote server
local DEFAULT_URL = "http://pnc.cloudteam.pro/app/ad_test/"
---
-- Supported providers list. Used as keys in configuration table
Ads.CHARTBOOST = "chartboost"
Ads.PLAYHAVEN = "playhaven"
Ads.AD_COLONY = "adcolony"
Ads.APP_FLOOD = "appflood"
Ads.FLURRY = "flurry"
Ads.INMOBI = "inmobi"
Ads.CPIERA = "cpiera"
local ProviderFactory = {
chartboost = AdProvider.Chartboost,
playhaven = AdProvider.PlayHaven,
adcolony = AdProvider.AdColony,
flurry = AdProvider.FlurryAds,
inmobi = AdProvider.InMobi,
}
---
-- Initialize configuration
-- @param string url remote configuration server address
-- @param table providers initial ad providers configuration. All ad providers in this table will be created.
-- Keys are different for each provider (appIds, zones, placements), however
--
-- Example configuration table:
-- {
-- chartboost = { weight = 1, appId = "id", appSignature = "sign" },
-- playhaven = { weight = 1, appId = "id", appSignature = "sign", placement = "place" },
-- adcolony = { weight = 1, appId = "id", zones = {"zone1", "zone2"} },
-- flurry = { weight = 1, space = "space" }, -- flurry analytics should be initialized before calling this
-- }
function Ads:init(providers, url)
self:setProviders(providers)
self.url = url or DEFAULT_URL
self.os = MOAIAppAndroid and "android" or "ios"
end
function Ads:setProviders(providers)
self.providers = {}
for k, v in pairs(providers) do
local providerClass = ProviderFactory[k]
if not providerClass then
print("Provider for key " .. k .. " not found. Maybe it is not implemented")
else
self.providers[k] = providerClass(v)
self.providers[k].active = true
self.providers[k].adManager = self
end
end
end
function Ads:cacheInterstitial()
for providerName, provider in pairs(self.providers) do
if not provider:hasCachedInterstitial() then
provider:cacheInterstitial()
end
end
end
function Ads:hasCachedInterstitial()
for providerName, provider in pairs(self.providers) do
if provider:hasCachedInterstitial() then
return true
end
end
return false
end
---
-- Returns true if ad was cached and been showed to the user
function Ads:showInterstitial()
local queue = self:getProviderQueue()
print("Provider queue", queue)
for i, provider in ipairs(queue) do
print("----- Trying: ", provider.name)
if provider:hasCachedInterstitial() then
print("----- Has cached ad: ", provider.name)
provider:showInterstitial()
return true
end
end
-- cache all interstitials if nothing been showed
self:cacheInterstitial()
return false
end
---
-- Returns a table with providers
-- shuffled, taking into account their weights
function Ads:getProviderQueue()
local queue = {}
local providers = table.dup(self.providers)
local key, prov = self:getProvider(providers)
while prov do
queue[#queue + 1] = prov
providers[key] = nil
key, prov = self:getProvider(providers)
end
return queue
end
function Ads:getProvider(providers)
local rnd = math.random()
local total = 0
for k, provider in pairs(providers) do
if provider.active then
total = total + provider.weight
end
end
rnd = rnd * total
total = 0
for k, provider in pairs(providers) do
if provider.active then
total = total + provider.weight
if rnd <= total then
return k, provider
end
end
end
end
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- Weight management from server
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
---
-- Request new weight parameters from server and apply them to current providers
-- Some providers can be removed from pool completely
-- Async
function Ads:updateWeights()
local httpTask = HttpTask.new()
httpTask:setUrl(self.url .. "preferences?os=" .. self.os)
httpTask:setVerb(HttpTask.HTTP_GET)
httpTask:setCallback(function(task)
local confStr = task:getString()
print(confStr)
if confStr then
local conf = MOAIJsonParser.decode(confStr)
self:onConfigReceived(conf)
end
end)
httpTask:performAsync()
end
function Ads:onConfigReceived(config)
local res, validConfig = self:validateConfig(config)
self:applyConfig(validConfig)
end
---
-- @return bool, table first return value is the result of validation, second value is valid config table.
-- valid table is built by deleting any invalid key-value pairs.
function Ads:validateConfig(config)
local result = true
local validConfig = table.dup(config)
print("validating config")
if not config then
print("Ads: config is nil")
return false
end
for k, v in pairs(config) do
if not self.providers[k] then
print("Ads: provider not initialized - " .. k)
result = false
validConfig[k] = nil
end
if type(v) ~= "number" then
print("Ads: weight value [" .. tostring(v) .. "] is not a number for provider " .. k)
result = false
validConfig[k] = nil
end
end
return result, validConfig
end
function Ads:applyConfig(config)
print("setting weights")
for k, v in pairs(self.providers) do
if config[k] then
print("new weight for ", k, config[k])
v.weight = config[k]
v.active = true
else
print("disabling ", k)
v.active = false
end
end
end
return Ads
|
remote config fixes
|
remote config fixes
|
Lua
|
mit
|
Vavius/moai-framework,Vavius/moai-framework
|
85301c7c344efaaa700e88a18986a390661eff8f
|
lib/EssentialModeApi.lua
|
lib/EssentialModeApi.lua
|
--
-- Contains MySQL method to be compatible with EssentialMode < 3.0
--
-- This functions are however deprecated, you should change them in a near future
--
Logger:Debug('EssentialModeApi is deprecated, please use the new API instead')
-- @deprecated
function MySQL.open(self, server, database, userid, password)
Logger:Debug('MySQL:open is deprecated and is not needed anymore, you can safely remove this call')
end
--- @deprecated
function MySQL.executeQuery(self, command, params)
Logger:Debug('MySQL:executeQuery is deprecated, please use MySQL.Sync.execute or MySQL.Async.execute instead')
-- Replace '@name' with @name as ' are not needed anymore
command = string.gsub(command, "'(@.+?)'", "%1")
local c = MySQL.Utils.CreateCommand(command, params)
local res = c.ExecuteNonQuery()
print("Query Executed("..res.."): " .. c.CommandText)
return {mySqlCommand = c, result = res}
end
--- @deprecated
function MySQL.getResults(self, mySqlCommand, fields, byField)
Logger:Debug('MySQL:getResults is deprecated, please use MySQL.Sync.fetchAll or MySQL.Async.fetchAll instead')
if type(fields) ~= "table" or #fields == 0 then
return nil
end
if type(mySqlCommand) == "table" and mySqlCommand['mySqlCommand'] ~= nil then
mySqlCommand = mySqlCommand['mySqlCommand']
end
local reader = mySqlCommand:ExecuteReader()
local result = {}
local c = nil
while reader:Read() do
c = #result+1
result[c] = {}
for field in pairs(fields) do
result[c][fields[field]] = self:_getFieldByName(reader, fields[field])
end
end
reader:Close()
return result
end
--- @deprecated
function MySQL.escape(self, str)
Logger:Fatal('This method is deprecated and is not safe to use, avoid it')
return str
end
--- @deprecated
function MySQL._getFieldByName(self, MysqlDataReader, name)
return MySQL.Utils.ConvertFieldValue(MysqlDataReader, MysqlDataReader.GetOrdinal(name))
end
|
--
-- Contains MySQL method to be compatible with EssentialMode < 3.0
--
-- This functions are however deprecated, you should change them in a near future
--
Logger:Debug('EssentialModeApi is deprecated, please use the new API instead')
-- @deprecated
function MySQL.open(self, server, database, userid, password)
Logger:Debug('MySQL:open is deprecated and is not needed anymore, you can safely remove this call')
end
--- @deprecated
function MySQL.executeQuery(self, command, params)
Logger:Debug('MySQL:executeQuery is deprecated, please use MySQL.Sync.execute or MySQL.Async.execute instead')
-- Replace '@name' with @name as ' are not needed anymore
command = string.gsub(command, "'(@.+?)'", "%1")
local c = MySQL.Utils.CreateCommand(command, params)
local res = c.ExecuteReader()
print("Query Executed("..res.RecordsAffected.."): " .. c.CommandText)
local value = MySQL.Utils.ConvertResultToTable(res);
c.Connection.Close()
return {mySqlCommand = c, reader = value, result = res.RecordsAffected}
end
--- @deprecated
function MySQL.getResults(self, reader, fields, byField)
Logger:Debug('MySQL:getResults is deprecated, please use MySQL.Sync.fetchAll or MySQL.Async.fetchAll instead')
if type(fields) ~= "table" or #fields == 0 then
return nil
end
if type(reader) == "table" and reader['reader'] ~= nil then
reader = reader['reader']
end
local result = {}
for c, line in ipairs(reader) do
result[c] = {}
for field in pairs(fields) do
result[c][fields[field]] = line[fields[field]]
end
end
return result
end
--- @deprecated
function MySQL.escape(self, str)
Logger:Fatal('This method is deprecated and is not safe to use, avoid it')
return str
end
--- @deprecated
function MySQL._getFieldByName(self, MysqlDataReader, name)
return MySQL.Utils.ConvertFieldValue(MysqlDataReader, MysqlDataReader.GetOrdinal(name))
end
|
Fix BC layer, do not send 2 queries, correctly shutdown / close old connections
|
Fix BC layer, do not send 2 queries, correctly shutdown / close old connections
|
Lua
|
mit
|
brouznouf/fivem-mysql-async,brouznouf/fivem-mysql-async,brouznouf/fivem-mysql-async
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.