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
|
---|---|---|---|---|---|---|---|---|---|
abd4fbabfe59505b207019e927ed162c545244e3
|
Container.lua
|
Container.lua
|
-- This is code common to container modules, which are collections of
-- smaller constituent modules like Parallel, Sequential, etc.
local Container, parent = torch.class('nn.Container', 'nn.Module')
function Container:__init(...)
parent.__init(self, ...)
self.modules = {}
end
function Container:add(module)
table.insert(self.modules, module)
return self
end
function Container:get(index)
return self.modules[index]
end
function Container:size()
return #self.modules
end
-- Check if passing arguments through xpcall is supported in this Lua interpreter.
local _, XPCALL_ARGS = xpcall(function(x) return x ~= nil end, function() end, 1)
local TRACEBACK_WARNING = "WARNING: If you see a stack trace below, it doesn't point to the place where this error occured. Please use only the one above."
-- module argument can be retrieved with moduleIndex, but code is cleaner when
-- it has to be specified anyway.
function Container:rethrowErrors(module, moduleIndex, funcName, ...)
assert(module == self.modules[moduleIndex],
"mismatch between moduleIndex and self.modules in rethrowErrors")
local function handleError(err)
local err_lines = err:split('\n')
-- This will be executed only in the first container that handles the error.
if err_lines[#err_lines] ~= TRACEBACK_WARNING then
local traceback = debug.traceback()
-- Remove this handler from the stack
local _, first_line_end = traceback:find('^.-\n')
local _, second_line_end = traceback:find('^.-\n.-\n')
traceback = traceback:sub(1, first_line_end) .. traceback:sub(second_line_end+1)
err = err .. '\n' .. traceback .. '\n\n' .. TRACEBACK_WARNING
else
-- Remove file path. +1 for newline character.
local first_line_end = #err_lines[1] + 1
err = err:sub(first_line_end+1)
end
local msg = string.format('In %d module of %s:',
moduleIndex, torch.type(self))
-- Preceding newline has to be here, because Lua will prepend a file path.
err = '\n' .. msg .. '\n' .. err
return err
end
-- Lua 5.1 doesn't support passing arguments through xpcall, so they have to
-- be passed via a closure. This incurs some overhead, so it's better not to
-- make it the default.
local ok, ret, noret
if not XPCALL_ARGS then
local args = {...}
local unpack = unpack or table.unpack
ok, ret, noret = xpcall(function()
return module[funcName](module, unpack(args))
end,
handleError)
else
ok, ret, noret = xpcall(module[funcName], handleError, module, ...)
end
assert(noret == nil, "rethrowErrors supports only one return argument")
if not ok then error(ret) end
return ret
end
function Container:applyToModules(func)
for _, module in ipairs(self.modules) do
func(module)
end
end
function Container:zeroGradParameters()
self:applyToModules(function(module) module:zeroGradParameters() end)
end
function Container:updateParameters(learningRate)
self:applyToModules(function(module) module:updateParameters(learningRate) end)
end
function Container:training()
self:applyToModules(function(module) module:training() end)
parent.training(self)
end
function Container:evaluate()
self:applyToModules(function(module) module:evaluate() end)
parent.evaluate(self)
end
function Container:share(mlp, ...)
for i=1,#self.modules do
self.modules[i]:share(mlp.modules[i], ...);
end
end
function Container:reset(stdv)
self:applyToModules(function(module) module:reset(stdv) end)
end
function Container:parameters()
local function tinsert(to, from)
if type(from) == 'table' then
for i=1,#from do
tinsert(to,from[i])
end
else
table.insert(to,from)
end
end
local w = {}
local gw = {}
for i=1,#self.modules do
local mw,mgw = self.modules[i]:parameters()
if mw then
tinsert(w,mw)
tinsert(gw,mgw)
end
end
return w,gw
end
function Container:clearState()
-- don't call set because it might reset referenced tensors
local function clear(f)
if self[f] then
if torch.isTensor(self[f]) then
self[f] = self[f].new()
elseif type(self[f]) == 'table' then
self[f] = {}
else
self[f] = nil
end
end
end
clear('output')
clear('gradInput')
if self.modules then
for i,module in pairs(self.modules) do
module:clearState()
end
end
return self
end
|
-- This is code common to container modules, which are collections of
-- smaller constituent modules like Parallel, Sequential, etc.
local Container, parent = torch.class('nn.Container', 'nn.Module')
function Container:__init(...)
parent.__init(self, ...)
self.modules = {}
end
function Container:add(module)
table.insert(self.modules, module)
return self
end
function Container:get(index)
return self.modules[index]
end
function Container:size()
return #self.modules
end
-- Check if passing arguments through xpcall is supported in this Lua interpreter.
local _, XPCALL_ARGS = xpcall(function(x) return x ~= nil end, function() end, 1)
local TRACEBACK_WARNING = "WARNING: If you see a stack trace below, it doesn't point to the place where this error occured. Please use only the one above."
-- module argument can be retrieved with moduleIndex, but code is cleaner when
-- it has to be specified anyway.
function Container:rethrowErrors(module, moduleIndex, funcName, ...)
assert(module == self.modules[moduleIndex],
"mismatch between moduleIndex and self.modules in rethrowErrors")
local function handleError(err)
-- This will be executed only in the first container that handles the error.
if not err:find(TRACEBACK_WARNING) then
local traceback = debug.traceback()
-- Remove this handler from the stack
local _, first_line_end = traceback:find('^.-\n')
local _, second_line_end = traceback:find('^.-\n.-\n')
traceback = traceback:sub(1, first_line_end) .. traceback:sub(second_line_end+1)
err = err .. '\n' .. traceback .. '\n\n' .. TRACEBACK_WARNING
else
-- Remove file path
err = err:sub(err:find('\n')+1)
end
local msg = string.format('In %d module of %s:',
moduleIndex, torch.type(self))
-- Preceding newline has to be here, because Lua will prepend a file path.
err = '\n' .. msg .. '\n' .. err
return err
end
-- Lua 5.1 doesn't support passing arguments through xpcall, so they have to
-- be passed via a closure. This incurs some overhead, so it's better not to
-- make it the default.
local ok, ret, noret
if not XPCALL_ARGS then
local args = {...}
local unpack = unpack or table.unpack
ok, ret, noret = xpcall(function()
return module[funcName](module, unpack(args))
end,
handleError)
else
ok, ret, noret = xpcall(module[funcName], handleError, module, ...)
end
assert(noret == nil, "rethrowErrors supports only one return argument")
if not ok then error(ret) end
return ret
end
function Container:applyToModules(func)
for _, module in ipairs(self.modules) do
func(module)
end
end
function Container:zeroGradParameters()
self:applyToModules(function(module) module:zeroGradParameters() end)
end
function Container:updateParameters(learningRate)
self:applyToModules(function(module) module:updateParameters(learningRate) end)
end
function Container:training()
self:applyToModules(function(module) module:training() end)
parent.training(self)
end
function Container:evaluate()
self:applyToModules(function(module) module:evaluate() end)
parent.evaluate(self)
end
function Container:share(mlp, ...)
for i=1,#self.modules do
self.modules[i]:share(mlp.modules[i], ...);
end
end
function Container:reset(stdv)
self:applyToModules(function(module) module:reset(stdv) end)
end
function Container:parameters()
local function tinsert(to, from)
if type(from) == 'table' then
for i=1,#from do
tinsert(to,from[i])
end
else
table.insert(to,from)
end
end
local w = {}
local gw = {}
for i=1,#self.modules do
local mw,mgw = self.modules[i]:parameters()
if mw then
tinsert(w,mw)
tinsert(gw,mgw)
end
end
return w,gw
end
function Container:clearState()
-- don't call set because it might reset referenced tensors
local function clear(f)
if self[f] then
if torch.isTensor(self[f]) then
self[f] = self[f].new()
elseif type(self[f]) == 'table' then
self[f] = {}
else
self[f] = nil
end
end
end
clear('output')
clear('gradInput')
if self.modules then
for i,module in pairs(self.modules) do
module:clearState()
end
end
return self
end
|
Fix error handling
|
Fix error handling
When using luajit strings have no split method.
|
Lua
|
bsd-3-clause
|
eriche2016/nn,diz-vara/nn,jonathantompson/nn,apaszke/nn,sagarwaghmare69/nn,colesbury/nn,joeyhng/nn,nicholas-leonard/nn,kmul00/nn,PraveerSINGH/nn
|
83c1a2ac8875be03f20aeb6647718ec3b6a16c77
|
lua/sfoto/imagegrid.lua
|
lua/sfoto/imagegrid.lua
|
module(..., package.seeall)
require("sfoto")
local Gridder = {}
local Gridder_mt = {__metatable = {}, __index = Gridder}
function new(node, photo_url, sputnik)
return setmetatable({node=node, photo_url=photo_url, sputnik=sputnik}, Gridder_mt)
end
-----------------------------------------------------------------------------
--
-----------------------------------------------------------------------------
function Gridder:parse_flexrow(row_code)
local row = {}
local i = 0
row_code:gsub("[^\n]+",
function(item)
i = i + 1
if item~="" and item:sub(1,3) ~= "---" then
if item:sub(1,1) ~= "x" then
item = "x1 "..item
end
local size, id, title = item:match("(%w*) ([^%s]*)(.*)")
row[i] = {item=item, id=id, size=tonumber(size:sub(2)), title=title}
else
row[i] = {}
end
end)
table.insert(self.rows, row)
end
-----------------------------------------------------------------------------
-- A more flexible way to express a grid
--
-- @param row A string representing the image grid
-- @return An HTML string
-----------------------------------------------------------------------------
function Gridder:flexgrid(image_code)
-- first convert the string representing the images into a table of rows
local buffer = ""
self.rows = {}
image_code:gsub("[^~]+", function (row) self:parse_flexrow(row) end)
for i, row in ipairs(self.rows) do
for j, photo in ipairs(row) do
buffer = buffer .. (photo.id or "x").."\n"
end
end
-- first figure out the total height of the grid in pixels
local total_height = 0
for i, row in ipairs(self.rows) do
total_height = total_height + 8 + (#row==6 and 150 or 100)
end
-- a function to add "px" to ints
local function pixify(value)
return string.format("%dpx", value)
end
-- we'll be positioning each photo individually, so we are making a single
-- list of photos rather than assembling "rows"
local photos = {}
local width, dwidth, height
local y = 2
for i, row in ipairs(self.rows) do
if #row == 6 then
width, dwidth, height = 100, 6, 150
else
width, dwidth, height = 150, 10, 100
end
local x = 2
for i = 1,#row do
photo = row[i]
if photo and photo.id then
local album, image = photo.id:gmatch("(.*)/(.*)") --util.split(photo.id, "/")
photo.size = photo.size or 1
table.insert(photos, {
width = pixify(width*photo.size + dwidth*(photo.size-1)),
height = pixify(height*photo.size + 8*(photo.size-1)),
left = pixify(2 + (width + dwidth) * (i-1)),
top = pixify(y),
title = photo.title or "",
photo_url = sfoto.photo_url("photos/"..photo.id,
photo.size>1 and string.format("%dx", photo.size) or "thumb"),
link = self.sputnik:make_url("albums/"..photo.id),
link = self.sputnik:make_url("photos/"..photo.id:gsub("-", "/"))
})
end
end
y = y + height + 8
end
return cosmo.f(self.node.templates.MIXED_ALBUM){
do_photos = photos,
height = total_height
}
end
function Gridder:add_flexgrids(content)
return content:gsub("<2~*\n(.-)\n~*>", function(code) return self:flexgrid(code) end)
end
function Gridder:parse_simplerow(row_code)
local row = {}
local i = 0
row_code:gsub("[^\n]+",
function(item)
i = i + 1
if item~="" and item:sub(1,3) ~= "---" then
local id, title = item:match("([^%s]*)(.*)")
row[i] = {id=id, title=title}
else
row[i] = {}
end
end)
table.insert(self.rows, row)
end
function Gridder:simplegrid(image_code)
self.rows = {}
image_code:gsub("[^~]+", function (row) self:parse_simplerow(row) end)
for i, row in ipairs(self.rows) do
row.photos = row
for j, photo in ipairs(row) do
photo.photo_url = sfoto.photo_url("photos/"..photo.id, "thumb")
photo.link = self.sputnik:make_url("photos/"..photo.id:gsub("-", "/"))
end
end
return cosmo.f(self.node.templates.SIMPLE_IMAGE_GRID){
rows = self.rows
}
end
function Gridder:add_flexgrids(content)
return content:gsub("<2~*\n(.-)\n~*>", function(code) return self:flexgrid(code) end)
end
function Gridder:add_simplegrids(content)
return content:gsub("<~*\n(.-)\n~*>", function(code) return self:simplegrid(code) end)
end
|
module(..., package.seeall)
require("sfoto")
local Gridder = {}
local Gridder_mt = {__metatable = {}, __index = Gridder}
function new(node, photo_url, sputnik)
return setmetatable({node=node, photo_url=photo_url, sputnik=sputnik}, Gridder_mt)
end
-----------------------------------------------------------------------------
--
-----------------------------------------------------------------------------
function Gridder:parse_flexrow(row_code)
local row = {}
local i = 0
row_code:gsub("[^\n]+",
function(item)
i = i + 1
if item~="" and item:sub(1,3) ~= "---" then
if item:sub(1,1) ~= "x" then
item = "x1 "..item
end
local size, id, title = item:match("(%w*) ([^%s]*)(.*)")
row[i] = {item=item, id=id, size=tonumber(size:sub(2)), title=title}
else
row[i] = {}
end
end)
table.insert(self.rows, row)
end
-----------------------------------------------------------------------------
-- A more flexible way to express a grid
--
-- @param row A string representing the image grid
-- @return An HTML string
-----------------------------------------------------------------------------
function Gridder:flexgrid(image_code)
-- first convert the string representing the images into a table of rows
local buffer = ""
self.rows = {}
image_code:gsub("[^~]+", function (row) self:parse_flexrow(row) end)
for i, row in ipairs(self.rows) do
for j, photo in ipairs(row) do
buffer = buffer .. (photo.id or "x").."\n"
end
end
-- first figure out the total height of the grid in pixels
local total_height = 0
for i, row in ipairs(self.rows) do
total_height = total_height + 8 + (#row==6 and 150 or 100)
end
-- a function to add "px" to ints
local function pixify(value)
return string.format("%dpx", value)
end
-- we'll be positioning each photo individually, so we are making a single
-- list of photos rather than assembling "rows"
local photos = {}
local width, dwidth, height
local y = 2
for i, row in ipairs(self.rows) do
if #row == 6 then
width, dwidth, height = 100, 6, 150
else
width, dwidth, height = 150, 10, 100
end
local x = 2
for i = 1,#row do
photo = row[i]
if photo and photo.id then
local album, image = photo.id:gmatch("(.*)/(.*)") --util.split(photo.id, "/")
photo.size = photo.size or 1
local parsed = sfoto.parse_id("photos/"..photo.id)
table.insert(photos, {
width = pixify(width*photo.size + dwidth*(photo.size-1)),
height = pixify(height*photo.size + 8*(photo.size-1)),
left = pixify(2 + (width + dwidth) * (i-1)),
top = pixify(y),
title = photo.title or "",
photo_url = sfoto.photo_url(parsed,
photo.size>1 and string.format("%dx", photo.size) or "thumb"),
link = self.sputnik:make_url("photos/"..parsed.year.."/"
..parsed.month.."/"..parsed.date
.."/"..parsed.rest)
})
end
end
y = y + height + 8
end
return cosmo.f(self.node.templates.MIXED_ALBUM){
do_photos = photos,
height = total_height
}
end
function Gridder:add_flexgrids(content)
return content:gsub("<2~*\n(.-)\n~*>", function(code) return self:flexgrid(code) end)
end
function Gridder:parse_simplerow(row_code)
local row = {}
local i = 0
row_code:gsub("[^\n]+",
function(item)
i = i + 1
if item~="" and item:sub(1,3) ~= "---" then
local id, title = item:match("([^%s]*)(.*)")
row[i] = {id=id, title=title}
else
row[i] = {}
end
end)
table.insert(self.rows, row)
end
function Gridder:simplegrid(image_code)
self.rows = {}
image_code:gsub("[^~]+", function (row) self:parse_simplerow(row) end)
for i, row in ipairs(self.rows) do
row.photos = row
for j, photo in ipairs(row) do
local parsed = sfoto.parse_id("photos/"..photo.id)
photo.photo_url = sfoto.photo_url(parsed, "thumb")
photo.link = self.sputnik:make_url("photos/"..parsed.year.."/"
..parsed.month.."/"..parsed.date
.."/"..parsed.rest)
end
end
return cosmo.f(self.node.templates.SIMPLE_IMAGE_GRID){
rows = self.rows
}
end
function Gridder:add_flexgrids(content)
return content:gsub("<2~*\n(.-)\n~*>", function(code) return self:flexgrid(code) end)
end
function Gridder:add_simplegrids(content)
return content:gsub("<~*\n(.-)\n~*>", function(code) return self:simplegrid(code) end)
end
|
Another fix for sfoto grid paths.
|
Another fix for sfoto grid paths.
|
Lua
|
mit
|
yuri/sfoto
|
19d3fbb199dcca0de559177e83214ba5185a1e77
|
android-demo-cifar/appication/assets/init-only.lua
|
android-demo-cifar/appication/assets/init-only.lua
|
----------------------------------------------------------------------
-- This script is based on file from below address.
--
-- https://github.com/torch/demos/blob/master/train-on-cifar/train-on-cifar.lua
--
-- Some lines are added for using model on android demo application.
-- without require Cifar-10 data set again for recognize test.
-- We needs trained model network and values of std_u, mean_u, std_v, mean_v
-- for stand alone recognition demo application.
--
-- Karam Park
----------------------------------------------------------------------
-- This script shows how to train different models on the CIFAR
-- dataset, using multiple optimization techniques (SGD, ASGD, CG)
--
-- This script demonstrates a classical example of training
-- well-known models (convnet, MLP, logistic regression)
-- on a 10-class classification problem.
--
-- It illustrates several points:
-- 1/ description of the model
-- 2/ choice of a loss function (criterion) to minimize
-- 3/ creation of a dataset as a simple Lua table
-- 4/ description of training and test procedures
--
-- Clement Farabet
----------------------------------------------------------------------
require 'torch'
require 'nn'
require 'nnx'
require 'dok'
require 'image'
----------------------------------------------------------------------
-- set options
-- fix seed
torch.manualSeed(1)
-- set number of threads
torch.setnumthreads(2)
-- classname for cifar 10
classes = {'airplane', 'automobile', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck'}
print('load pretrained network file')
-- load pretrained network file from apk's asset folder
model=torch.load('cifar.net','r','apk')
-- retrieve parameters and gradients
parameters,gradParameters = model:getParameters()
model:add(nn.LogSoftMax())
criterion = nn.ClassNLLCriterion()
-- read mean & std values
mean_u=torch.load('mean_u','r','apk')
--print('mean_u ' .. mean_u)
mean_v=torch.load('mean_v','r','apk')
--print('mean_v ' .. mean_v)
std_u=torch.load('std_u','r','apk')
--print('std_u ' .. std_u)
std_v=torch.load('std_v','r','apk')
--print('std_v ' .. std_v)
-- Test in torch test set
function testTorchData()
--set number of test (max 10,000 samples)
tesize = 1000
-- load dataset
subset = torch.load('/sdcard/Cifar/test_batch.t7', 'ascii', 'r')
testData = {
data = subset.data:t():double(),
labels = subset.labels[1]:double(),
size = function() return tesize end
}
testData.labels = testData.labels + 1
-- resize dataset (if using small version)
testData.data = testData.data[{ {1,tesize} }]
testData.labels = testData.labels[{ {1,tesize} }]
-- reshape data
testData.data = testData.data:reshape(tesize,3,32,32)
local correct = 0
for i = 1,testData:size() do
local result = getTopOnly(testData.data[i])
if result == testData.labels[i] then
correct = correct + 1;
end
end
return correct/tesize
end
-- function for test image
function getRecogResult(sampledata)
sampledata = sampledata:reshape(3,32,32)
data = torch.DoubleTensor():set(sampledata)
normalization = nn.SpatialContrastiveNormalization(1, image.gaussian1D(7))
-- preprocess testSet
--print 'rgb -> yuv'
local rgb = data
local yuv = image.rgb2yuv(rgb)
-- print 'normalize y locally'
yuv[1] = normalization(yuv[{{1}}])
data = yuv
-- normalize u globally:
data[{ 2,{},{} }]:add(-mean_u)
data[{ 2,{},{} }]:div(-std_u)
-- normalize v globally:
data[{ 3,{},{} }]:add(-mean_v)
data[{ 3,{},{} }]:div(-std_v)
local result = model:forward(data)
return result
end
function getTopOnly(sampledata)
local result = getRecogResult(sampledata)
local max
local index = 0
for k=1,10 do
if max == nil or max < result[k] then
index = k
max = result[k]
end
end
return index
end
|
----------------------------------------------------------------------
-- This script is based on file from below address.
--
-- https://github.com/torch/demos/blob/master/train-on-cifar/train-on-cifar.lua
--
-- Some lines are added for using model on android demo application.
-- without require Cifar-10 data set again for recognize test.
-- We needs trained model network and values of std_u, mean_u, std_v, mean_v
-- for stand alone recognition demo application.
--
-- Karam Park
----------------------------------------------------------------------
-- This script shows how to train different models on the CIFAR
-- dataset, using multiple optimization techniques (SGD, ASGD, CG)
--
-- This script demonstrates a classical example of training
-- well-known models (convnet, MLP, logistic regression)
-- on a 10-class classification problem.
--
-- It illustrates several points:
-- 1/ description of the model
-- 2/ choice of a loss function (criterion) to minimize
-- 3/ creation of a dataset as a simple Lua table
-- 4/ description of training and test procedures
--
-- Clement Farabet
----------------------------------------------------------------------
require 'torch'
require 'nn'
require 'nnx'
require 'dok'
require 'image'
----------------------------------------------------------------------
-- set options
-- fix seed
torch.manualSeed(1)
-- set number of threads
torch.setnumthreads(2)
torch.setdefaulttensortype('torch.DoubleTensor')
-- classname for cifar 10
classes = {'airplane', 'automobile', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck'}
print('load pretrained network file')
-- load pretrained network file from apk's asset folder
model=torch.load('cifar.net','r','apk')
-- retrieve parameters and gradients
parameters,gradParameters = model:getParameters()
model:add(nn.LogSoftMax())
criterion = nn.ClassNLLCriterion()
-- read mean & std values
mean_u=torch.load('mean_u','r','apk')
--print('mean_u ' .. mean_u)
mean_v=torch.load('mean_v','r','apk')
--print('mean_v ' .. mean_v)
std_u=torch.load('std_u','r','apk')
--print('std_u ' .. std_u)
std_v=torch.load('std_v','r','apk')
--print('std_v ' .. std_v)
-- Test in torch test set
function testTorchData()
--set number of test (max 10,000 samples)
tesize = 1000
-- load dataset
subset = torch.load('/sdcard/Cifar/test_batch.t7', 'ascii', 'r')
testData = {
data = subset.data:t():double(),
labels = subset.labels[1]:double(),
size = function() return tesize end
}
testData.labels = testData.labels + 1
-- resize dataset (if using small version)
testData.data = testData.data[{ {1,tesize} }]
testData.labels = testData.labels[{ {1,tesize} }]
-- reshape data
testData.data = testData.data:reshape(tesize,3,32,32)
local correct = 0
for i = 1,testData:size() do
local result = getTopOnly(testData.data[i])
if result == testData.labels[i] then
correct = correct + 1;
end
end
return correct/tesize
end
-- function for test image
function getRecogResult(sampledata)
sampledata = sampledata:reshape(3,32,32)
data = torch.DoubleTensor():set(sampledata)
normalization = nn.SpatialContrastiveNormalization(1, image.gaussian1D(7))
-- preprocess testSet
--print 'rgb -> yuv'
local rgb = data
local yuv = image.rgb2yuv(rgb)
-- print 'normalize y locally'
yuv[1] = normalization(yuv[{{1}}])
data = yuv
-- normalize u globally:
data[{ 2,{},{} }]:add(-mean_u)
data[{ 2,{},{} }]:div(-std_u)
-- normalize v globally:
data[{ 3,{},{} }]:add(-mean_v)
data[{ 3,{},{} }]:div(-std_v)
local result = model:forward(data)
return result
end
function getTopOnly(sampledata)
local result = getRecogResult(sampledata)
local max
local index = 0
for k=1,10 do
if max == nil or max < result[k] then
index = k
max = result[k]
end
end
return index
end
|
fix TensorType error
|
fix TensorType error
|
Lua
|
bsd-3-clause
|
appaquet/torch-android,quanhua92/torch-android,soumith/torch-android,soumith/torch-android,quanhua92/torch-android,appaquet/torch-android,appaquet/torch-android,soumith/torch-android,soumith/torch-android,appaquet/torch-android,quanhua92/torch-android,appaquet/torch-android,quanhua92/torch-android,quanhua92/torch-android,appaquet/torch-android,quanhua92/torch-android
|
75d1f7f045cda17501190b03935778b968ab0e7d
|
pages/admin/shop/offer/new/post.lua
|
pages/admin/shop/offer/new/post.lua
|
require "bbcode"
require "util"
function post()
if not app.Shop.Enabled then
http:redirect("/")
return
end
if not session:isAdmin() then
http:redirect("/")
return
end
local data = {}
data.category = db:singleQuery("SELECT id, name FROM castro_shop_categories WHERE id = ?", http.postValues.id)
if data.category == nil then
http:redirect("/")
return
end
if http.postValues["offer-price"] == nil then
session:setFlash("validationError", "Invalid offer price range")
http:redirect("/subtopic/admin/shop/offer/new?categoryId=" .. data.category.id)
return
end
if tonumber(http.postValues["offer-price"]) ~= nil and tonumber(http.postValues["offer-price"]) <= 0 then
session:setFlash("validationError", "Invalid offer price range")
http:redirect("/subtopic/admin/shop/offer/new?categoryId=" .. data.category.id)
return
end
if http.postValues["offer-name"] == "" then
session:setFlash("validationError", "Offer name can not be empty")
http:redirect("/subtopic/admin/shop/offer/new?categoryId=" .. data.category.id)
return
end
if http.postValues["offer-description"] == "" then
session:setFlash("validationError", "Offer description can not be empty")
http:redirect("/subtopic/admin/shop/offer/new?categoryId=" .. data.category.id)
return
end
if db:singleQuery("SELECT 1 FROM castro_shop_offers WHERE name = ?", http.postValues["offer-name"]) ~= nil then
session:setFlash("validationError", "Offer name is already in use")
http:redirect("/subtopic/admin/shop/offer/new?categoryId=" .. data.category.id)
return
end
http:parseMultiPartForm()
local offerImage = http:formFile("offer-image")
local offerImagePath = ""
if offerImage ~= nil then
if not offerImage:isValidPNG() then
session:setFlash("validationError", "Offer image can only be .png")
http:redirect("/subtopic/admin/shop/offer/new?categoryId=" .. data.category.id)
return
end
offerImage:saveFileAsPNG("public/images/offer-images/" .. http.postValues["offer-name"] .. ".png", 32, 32)
offerImagePath = "public/images/offer-images/" .. http.postValues["offer-name"] .. ".png"
end
db:execute(
[[INSERT INTO castro_shop_offers
(category_id, description, price, name, created_at, updated_at, image, give_item, give_item_amount, charges, container_give_item, container_give_amount, container_give_charges)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)]],
data.category.id,
http.postValues["offer-description"],
http.postValues["offer-price"],
http.postValues["offer-name"],
os.time(),
os.time(),
offerImagePath,
ternary(http.postValues["give-item"] == nil, 0, http.postValues["give-item"]),
ternary(http.postValues["give-item-amount"] == nil, 0, http.postValues["give-item-amount"]),
ternary(http.postValues["charges"] == nil, 0, http.postValues["charges"]),
table.concat(explode(",", http.postValues["container-item[]"]), ","),
table.concat(explode(",", http.postValues["container-item-amount[]"]), ","),
table.concat(explode(",", http.postValues["container-item-charges[]"]), ",")
)
session:setFlash("success", "Shop offer created")
http:redirect("/subtopic/admin/shop/category?id=" .. data.category.id)
end
|
require "bbcode"
require "util"
function post()
if not app.Shop.Enabled then
http:redirect("/")
return
end
if not session:isAdmin() then
http:redirect("/")
return
end
local data = {}
data.category = db:singleQuery("SELECT id, name FROM castro_shop_categories WHERE id = ?", http.postValues.id)
if data.category == nil then
http:redirect("/")
return
end
if http.postValues["offer-price"] == nil then
session:setFlash("validationError", "Invalid offer price range")
http:redirect("/subtopic/admin/shop/offer/new?categoryId=" .. data.category.id)
return
end
if tonumber(http.postValues["offer-price"]) ~= nil and tonumber(http.postValues["offer-price"]) <= 0 then
session:setFlash("validationError", "Invalid offer price range")
http:redirect("/subtopic/admin/shop/offer/new?categoryId=" .. data.category.id)
return
end
if http.postValues["offer-name"] == "" then
session:setFlash("validationError", "Offer name can not be empty")
http:redirect("/subtopic/admin/shop/offer/new?categoryId=" .. data.category.id)
return
end
if http.postValues["offer-description"] == "" then
session:setFlash("validationError", "Offer description can not be empty")
http:redirect("/subtopic/admin/shop/offer/new?categoryId=" .. data.category.id)
return
end
if db:singleQuery("SELECT 1 FROM castro_shop_offers WHERE name = ?", http.postValues["offer-name"]) ~= nil then
session:setFlash("validationError", "Offer name is already in use")
http:redirect("/subtopic/admin/shop/offer/new?categoryId=" .. data.category.id)
return
end
http:parseMultiPartForm()
local offerImage = http:formFile("offer-image")
local offerImagePath = ""
if offerImage ~= nil then
local validImage = offerImage:isValidExtension("image/png") or offerImage:isValidExtension("image/jpeg") or offerImage:isValidExtension("image/gif")
if not validImage then
session:setFlash("validationError", "Offer image can only be .png, .jpeg or .gif")
http:redirect("/subtopic/admin/shop/offer/new?categoryId=" .. data.category.id)
return
end
offerImage:saveFileAsPNG("public/images/offer-images/" .. http.postValues["offer-name"] .. ".png", 32, 32)
offerImagePath = "public/images/offer-images/" .. http.postValues["offer-name"] .. ".png"
end
db:execute(
[[INSERT INTO castro_shop_offers
(category_id, description, price, name, created_at, updated_at, image, give_item, give_item_amount, charges, container_give_item, container_give_amount, container_give_charges)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)]],
data.category.id,
http.postValues["offer-description"],
http.postValues["offer-price"],
http.postValues["offer-name"],
os.time(),
os.time(),
offerImagePath,
ternary(http.postValues["give-item"] == nil, 0, http.postValues["give-item"]),
ternary(http.postValues["give-item-amount"] == nil, 0, http.postValues["give-item-amount"]),
ternary(http.postValues["charges"] == nil, 0, http.postValues["charges"]),
ternary(http.postValues["container-item[]"] == "", "", table.concat(explode(",", http.postValues["container-item[]"]), ",")),
ternary(http.postValues["container-item-amount[]"] == "", "", table.concat(explode(",", http.postValues["container-item-amount[]"]), ",")),
ternary(http.postValues["container-item-charges[]"] == "", "", table.concat(explode(",", http.postValues["container-item-charges[]"]), ","))
)
session:setFlash("success", "Shop offer created")
http:redirect("/subtopic/admin/shop/category?id=" .. data.category.id)
end
|
Fix #93
|
Fix #93
|
Lua
|
mit
|
Raggaer/castro,Raggaer/castro,Raggaer/castro
|
497566ce0371285230e38b9bca467fc8e8676185
|
plugins/mod_uptime.lua
|
plugins/mod_uptime.lua
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local st = require "util.stanza"
local jid_split = require "util.jid".split;
local t_concat = table.concat;
local start_time = prosody.start_time;
prosody.events.add_handler("server-started", function () start_time = prosody.start_time end);
module:add_feature("jabber:iq:last");
module:add_iq_handler({"c2s", "s2sin"}, "jabber:iq:last",
function (origin, stanza)
if stanza.tags[1].name == "query" then
if stanza.attr.type == "get" then
local node, host, resource = jid_split(stanza.attr.to);
if node or resource then
-- TODO
else
origin.send(st.reply(stanza):tag("query", {xmlns = "jabber:iq:last", seconds = tostring(os.difftime(os.time(), start_time))}));
return true;
end
end
end
end);
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local st = require "util.stanza"
local jid_split = require "util.jid".split;
local t_concat = table.concat;
local start_time = prosody.start_time;
prosody.events.add_handler("server-started", function() start_time = prosody.start_time end);
module:add_feature("jabber:iq:last");
module:hook("iq/host/jabber:iq:last:query", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "get" then
origin.send(st.reply(stanza):tag("query", {xmlns = "jabber:iq:last", seconds = tostring(os.difftime(os.time(), start_time))}));
return true;
end
end);
module:hook("iq/bare/jabber:iq:last:query", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "get" then
-- TODO last activity
end
end);
|
mod_uptime: Updated to use events (which also fixes a few minor issues).
|
mod_uptime: Updated to use events (which also fixes a few minor issues).
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
6bd7890e36ae3279cf57903e24747f4688fdbc7f
|
cmd/lark/lark.lua
|
cmd/lark/lark.lua
|
require 'string'
require 'table'
require 'os'
local core = require('lark.core')
local function flatten(...)
local flat = {}
for i, v in pairs(arg) do
if i == 'n' then
-- noop
elseif type(v) == 'table' then
for j, v_inner in pairs(flatten(unpack(v))) do
table.insert(flat, v_inner)
end
else
table.insert(flat, v)
end
end
return flat
end
lark = {}
lark.default_task = nil
lark.tasks = {}
lark.patterns = {}
lark.task = function (name, fn)
local pattern = nil
local t = name
if type(t) == 'table' then
pattern = t.pattern
if type(t[1]) == "string" then
name = t[1]
end
fn = t[table.getn(t)]
end
if not lark.default_task then
lark.default_task = name
end
if name then
lark.tasks[name] = fn
end
if pattern then
print('pattern task: ' .. pattern)
for _, rec in pairs(lark.patterns) do
if rec[1] == pattern then
error("pattern already defined: " .. pattern)
end
end
local rec = { pattern, fn }
table.insert(lark.patterns, rec)
end
end
local function run (name, ctx)
local fn = lark.tasks[name]
if not fn then
for _, rec in pairs(lark.patterns) do
if string.find(name, rec[1]) then
ctx.pattern = rec[1]
fn = rec[2]
break
end
end
end
if not fn then
error('no task matching ' .. name)
end
fn(ctx)
end
lark.run = function (...)
local tasks = {...}
if table.getn(tasks) == 0 then
tasks = {lark.default_task}
end
for i, name in pairs(tasks) do
local ctx = name
if type(name) == 'string' then
ctx = {name = name}
else
name = ctx.name
end
if not name then
name = lark.default_task
ctx.name = name
end
run(name, ctx)
end
end
lark.get_name = function(ctx)
if ctx then
return ctx.name
end
return nil
end
lark.get_pattern = function(ctx)
if ctx then
return ctx.pattern
end
return nil
end
-- BUG: `or` is not correct here if the parameter was given an empty string
-- value
lark.get_param = function(ctx, name, default)
if ctx and ctx.params then
return ctx.params[name] or default
end
return default
end
lark.shell_quote = function (args)
local q = function (s)
s = string.gsub(s, '\\', '\\\\')
s = string.gsub(s, '"', '\\"')
if string.find(s, '%s') then
s = '"' .. s .. '"'
end
return s
end
local str = ''
for i, x in pairs(args) do
if type(i) == 'number' then
if i > 1 then
str = str .. ' '
end
if type(x) == 'string' then
str = str .. q(x)
else if type(x) == 'table' then
str = str .. lark.shell_quote(x)
else
error(string.format('cannot quote type: %s', type(x)))
end
end
end
end
return str
end
lark.environ = core.environ
lark.log = core.log
lark.exec = function (args)
local cmd_str = lark.shell_quote(args)
args._str = lark.shell_quote(args)
local result = core.exec(args)
if args.ignore and result.error then
if lark.verbose then
local msg = string.format('%s (ignored)', result.error)
lark.log{msg, color='yellow'}
end
elseif result.error then
error(result.error)
end
end
lark.start = function(args)
args._str = lark.shell_quote(args) .. ' &'
core.start(args)
end
lark.group = function (args)
if type(args) == 'string' then
return args
end
if table.getn(args) == 1 then
args.name = args[1]
end
if table.getn(args) > 1 then
error('too many positional arguments given')
end
core.make_group(args)
return args[1]
end
lark.wait = function (...)
local args = arg
if type(args) ~= 'table' then
args = {arg}
end
local result = core.wait(unpack(flatten(args)))
if result.error then
error(result.error)
end
end
|
require 'string'
require 'table'
require 'os'
local core = require('lark.core')
local function flatten(...)
local flat = {}
for i, v in pairs(arg) do
if i == 'n' then
-- noop
elseif type(v) == 'table' then
for j, v_inner in pairs(flatten(unpack(v))) do
table.insert(flat, v_inner)
end
else
table.insert(flat, v)
end
end
return flat
end
lark = {}
lark.default_task = nil
lark.tasks = {}
lark.patterns = {}
lark.task = function (name, fn)
local pattern = nil
local t = name
if type(t) == 'table' then
pattern = t.pattern
if type(t[1]) == "string" then
name = t[1]
end
fn = t[table.getn(t)]
end
if not lark.default_task then
lark.default_task = name
end
if name then
lark.tasks[name] = fn
end
if pattern then
print('pattern task: ' .. pattern)
for _, rec in pairs(lark.patterns) do
if rec[1] == pattern then
error("pattern already defined: " .. pattern)
end
end
local rec = { pattern, fn }
table.insert(lark.patterns, rec)
end
end
local function run (name, ctx)
local fn = lark.tasks[name]
if not fn then
for _, rec in pairs(lark.patterns) do
if string.find(name, rec[1]) then
ctx.pattern = rec[1]
fn = rec[2]
break
end
end
end
if not fn then
error('no task matching ' .. name)
end
fn(ctx)
end
lark.run = function (...)
local tasks = {...}
if table.getn(tasks) == 0 then
tasks = {lark.default_task}
end
for i, name in pairs(tasks) do
local ctx = name
if type(name) == 'string' then
ctx = {name = name}
else
name = ctx.name
end
if not name then
name = lark.default_task
ctx.name = name
end
run(name, ctx)
end
end
lark.get_name = function(ctx)
if ctx then
return ctx.name
end
return nil
end
lark.get_pattern = function(ctx)
if ctx then
return ctx.pattern
end
return nil
end
lark.get_param = function(ctx, name, default)
if ctx and ctx.params then
return ctx.params[name] or default
end
return default
end
lark.shell_quote = function (args)
local q = function (s)
s = string.gsub(s, '\\', '\\\\')
s = string.gsub(s, '"', '\\"')
if string.find(s, '%s') then
s = '"' .. s .. '"'
end
return s
end
local str = ''
for i, x in pairs(args) do
if type(i) == 'number' then
if i > 1 then
str = str .. ' '
end
if type(x) == 'string' then
str = str .. q(x)
else if type(x) == 'table' then
str = str .. lark.shell_quote(x)
else
error(string.format('cannot quote type: %s', type(x)))
end
end
end
end
return str
end
lark.environ = core.environ
lark.log = core.log
lark.exec = function (args)
local cmd_str = lark.shell_quote(args)
args._str = lark.shell_quote(args)
local result = core.exec(args)
if args.ignore and result.error then
if lark.verbose then
local msg = string.format('%s (ignored)', result.error)
lark.log{msg, color='yellow'}
end
elseif result.error then
error(result.error)
end
end
lark.start = function(args)
args._str = lark.shell_quote(args) .. ' &'
core.start(args)
end
lark.group = function (args)
if type(args) == 'string' then
return args
end
if table.getn(args) == 1 then
args.name = args[1]
end
if table.getn(args) > 1 then
error('too many positional arguments given')
end
core.make_group(args)
return args[1]
end
lark.wait = function (...)
local args = arg
if type(args) ~= 'table' then
args = {arg}
end
local result = core.wait(unpack(flatten(args)))
if result.error then
error(result.error)
end
end
|
remove invalid BUG comment
|
remove invalid BUG comment
The semantics of `or` are not as were believed. An empty string is a
true value.
|
Lua
|
mit
|
bmatsuo/lark,bmatsuo/lark
|
f41657d563a34eab94a6921277a753f2bac6b4df
|
examples/ipsec-vpn.lua
|
examples/ipsec-vpn.lua
|
local dpdk = require "dpdk"
local ipsec = require "ipsec"
local memory = require "memory"
local device = require "device"
function master(txPort, rxPort)
if not txPort or not rxPort then
return print("Usage: txPort rxPort")
end
local txDev = device.config(txPort, 1)
local rxDev = device.config(rxPort, 1)
device.waitForLinks()
dpdk.launchLua("rxSlave", rxPort, rxDev:getRxQueue(0))
dpdk.launchLua("txSlave", txPort, txDev:getTxQueue(0), rxDev:getRxQueue(0))
dpdk.waitForSlaves()
print("THE END...")
end
-- txSlave sends out (ipsec crypto) packages
function txSlave(port, srcQueue, dstQueue)
local numFlows = 256
local mem = memory.createMemPool(function(buf)
buf:getUdpPacket():fill{
pktLength = 60,
ethSrc = srcQueue,
ethDst = dstQueue,
ipDst = "192.168.1.1",
udpSrc = 1234,
udpDst = 5678,
}
end)
bufs = mem:bufArray(128)
local baseIP = parseIPAddress("10.0.0.1")
local flow = 0
ipsec.enable(port)
while dpdk.running() do
bufs:alloc(60)
for _, buf in ipairs(bufs) do
local pkt = buf:getUdpPacket()
pkt.ip.src:set(baseIP + flow)
flow = incAndWrap(flow, numFlows)
end
-- UDP checksums are optional, so just IP checksums are sufficient here
-- bufs:offloadIPChecksums()
bufs:offloadUdpChecksums()
srcQueue:send(bufs)
end
ipsec.disable(port)
end
-- rxSlave logs received packages
function rxSlave(port, queue)
local dev = device.get(port)
local bufs = memory.bufArray()
local total = 0
while dpdk.running() do
local rx = queue:recv(bufs)
--for i = 1, rx do
-- local buf = bufs[i]
-- buf:dump() -- hexdump of received packet (incl. header)
--end
-- Dump only one packet per second
local buf = bufs[rx]
buf:dump() -- hexdump of received packet (incl. header)
bufs:freeAll()
local time = dpdk.getTime()
dpdk.sleepMillis(1000)
local elapsed = dpdk.getTime() - time
local pkts = dev:getRxStats(port)
total = total + pkts
printf("Received %d packets, current rate %.2f Mpps\n", total, pkts / elapsed / 10^6)
end
printf("Received %d packets", total)
end
|
local dpdk = require "dpdk"
local ipsec = require "ipsec"
local memory = require "memory"
local device = require "device"
function master(txPort, rxPort)
if not txPort or not rxPort then
return print("Usage: txPort rxPort")
end
local txDev = device.config(txPort, 1)
local rxDev = device.config(rxPort, 1)
device.waitForLinks()
dpdk.launchLua("rxSlave", rxPort, rxDev:getRxQueue(0))
dpdk.launchLua("txSlave", txPort, txDev:getTxQueue(0), rxDev:getRxQueue(0))
dpdk.waitForSlaves()
print("THE END...")
end
-- txSlave sends out (ipsec crypto) packages
function txSlave(port, srcQueue, dstQueue)
local count = 0
local mem = memory.createMemPool(function(buf)
buf:getUdpPacket():fill{
pktLength = 60,
ethSrc = srcQueue,
ethDst = dstQueue,
ipSrc = "10.0.0.1",
ipDst = "192.168.1.1",
udpSrc = 1234,
udpDst = 5678,
}
end)
bufs = mem:bufArray(128)
ipsec.enable(port)
while dpdk.running() do
bufs:alloc(60)
for _, buf in ipairs(bufs) do
local pkt = buf:getUdpPacket()
pkt.payload.uint32[0] = 0xdeadbeef
pkt.payload.uint32[1] = count
pkt.payload.uint32[2] = 0xdeadbeef
count = (count+1) % 0xffffffff
end
-- UDP checksums are optional, so just IP checksums are sufficient here
-- bufs:offloadUdpChecksums()
bufs:offloadIPChecksums()
srcQueue:send(bufs)
end
ipsec.disable(port)
end
-- rxSlave logs received packages
function rxSlave(port, queue)
local dev = device.get(port)
local bufs = memory.bufArray()
local total = 0
while dpdk.running() do
local rx = queue:recv(bufs)
--for i = 1, rx do
-- local buf = bufs[i]
-- local pkt = buf:getUdpPacket()
-- printf("C: %u", pkt.payload.uint32[1])
--end
-- Dump only one packet per second
local buf = bufs[rx]
local pkt = buf:getUdpPacket()
buf:dump() -- hexdump of received packet (incl. header)
printf("H: 0x%x", pkt.payload.uint32[0])
printf("C: 0x%x (%u)", pkt.payload.uint32[1], pkt.payload.uint32[1])
printf("T: 0x%x", pkt.payload.uint32[2])
bufs:freeAll()
local time = dpdk.getTime()
dpdk.sleepMillis(1000)
local elapsed = dpdk.getTime() - time
local pkts = dev:getRxStats(port)
total = total + pkts
printf("Received %d packets, current rate %.2f Mpps\n", total, pkts / elapsed / 10^6)
end
printf("Received %d packets", total)
end
|
ipsec: fixed IPs, counter in payload
|
ipsec: fixed IPs, counter in payload
|
Lua
|
mit
|
atheurer/MoonGen,wenhuizhang/MoonGen,emmericp/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,NetronomeMoongen/MoonGen,gallenmu/MoonGen,wenhuizhang/MoonGen,duk3luk3/MoonGen,scholzd/MoonGen,emmericp/MoonGen,NetronomeMoongen/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,NetronomeMoongen/MoonGen,atheurer/MoonGen,kidaa/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,slyon/MoonGen,dschoeffm/MoonGen,slyon/MoonGen,slyon/MoonGen,slyon/MoonGen,kidaa/MoonGen,bmichalo/MoonGen,duk3luk3/MoonGen,scholzd/MoonGen,kidaa/MoonGen,duk3luk3/MoonGen,atheurer/MoonGen,gallenmu/MoonGen,bmichalo/MoonGen,bmichalo/MoonGen,bmichalo/MoonGen,dschoeffm/MoonGen,wenhuizhang/MoonGen
|
414962d02150e868269fbbc63e7c378d8f089ff0
|
src/cli/utils/start.lua
|
src/cli/utils/start.lua
|
local IO = require "kong.tools.io"
local cutils = require "kong.cli.utils"
local constants = require "kong.constants"
local _M = {}
local function is_openresty(path_to_check)
local cmd = tostring(path_to_check).." -v 2>&1"
local handle = io.popen(cmd)
local out = handle:read()
handle:close()
local matched = out:match("^nginx version: ngx_openresty/") or out:match("^nginx version: openresty/")
if matched then
return path_to_check
end
end
local function find_nginx()
local nginx_bin = "nginx"
local nginx_search_paths = {
"/usr/local/openresty/nginx/sbin/",
"/usr/local/opt/openresty/bin/",
"/usr/local/bin/",
"/usr/sbin/",
""
}
for i = 1, #nginx_search_paths do
local prefix = nginx_search_paths[i]
local to_check = tostring(prefix)..tostring(nginx_bin)
if is_openresty(to_check) then
return to_check
end
end
end
local function prepare_nginx_working_dir(kong_config)
if kong_config.send_anonymous_reports then
kong_config.nginx = "error_log syslog:server=kong-hf.mashape.com:61828 error;\n"..kong_config.nginx
end
-- Create nginx folder if needed
local _, err = IO.path:mkdir(IO.path:join(kong_config.nginx_working_dir, "logs"))
if err then
cutils.logger:error_exit(err)
end
os.execute("touch "..IO.path:join(kong_config.nginx_working_dir, "logs", "error.log"))
os.execute("touch "..IO.path:join(kong_config.nginx_working_dir, "logs", "access.log"))
-- Extract nginx config to nginx folder
local ok, err = IO.write_to_file(IO.path:join(kong_config.nginx_working_dir, constants.CLI.NGINX_CONFIG), kong_config.nginx)
if not ok then
error(err)
end
return kong_config.nginx_working_dir
end
function _M.start(args_config)
-- Make sure nginx is there and is openresty
local nginx_path = find_nginx()
if not nginx_path then
cutils.logger:error_exit("can't find nginx")
end
-- Get configuration from default or given path
local config_path = cutils.get_kong_config_path(args_config)
local config, dao_factory = IO.load_configuration_and_dao(config_path)
-- Migrate the DB if needed and possible
local keyspace, err = dao_factory:get_migrations()
if err then
cutils.logger:error_exit(err)
elseif keyspace == nil then
cutils.logger:log("Database not initialized. Running migrations...")
local migrations = require("kong.tools.migrations")(dao_factory, cutils.get_luarocks_install_dir())
migrations:migrate(function(migration, err)
if err then
cutils.logger:error_exit(err)
elseif migration then
cutils.logger:success("Migrated up to: "..cutils.colors.yellow(migration.name))
end
end)
end
-- Prepare nginx --prefix dir
local nginx_working_dir = prepare_nginx_working_dir(config)
-- Build nginx start command
local cmd = string.format("KONG_CONF=%s %s -p %s -c %s -g 'pid %s;'",
config_path,
nginx_path,
nginx_working_dir,
constants.CLI.NGINX_CONFIG,
constants.CLI.NGINX_PID)
if os.execute(cmd) == 0 then
cutils.logger:success("Started")
else
cutils.logger:error_exit("Could not start Kong")
end
end
return _M.start
|
local IO = require "kong.tools.io"
local cutils = require "kong.cli.utils"
local constants = require "kong.constants"
local _M = {}
local KONG_SYSLOG = "kong-hf.mashape.com"
local function is_openresty(path_to_check)
local cmd = tostring(path_to_check).." -v 2>&1"
local handle = io.popen(cmd)
local out = handle:read()
handle:close()
local matched = out:match("^nginx version: ngx_openresty/") or out:match("^nginx version: openresty/")
if matched then
return path_to_check
end
end
local function find_nginx()
local nginx_bin = "nginx"
local nginx_search_paths = {
"/usr/local/openresty/nginx/sbin/",
"/usr/local/opt/openresty/bin/",
"/usr/local/bin/",
"/usr/sbin/",
""
}
for i = 1, #nginx_search_paths do
local prefix = nginx_search_paths[i]
local to_check = tostring(prefix)..tostring(nginx_bin)
if is_openresty(to_check) then
return to_check
end
end
end
local function prepare_nginx_working_dir(kong_config)
if kong_config.send_anonymous_reports then
-- If there is no internet connection, disable this feature
if os.execute("dig +time=2 +tries=2 "..KONG_SYSLOG.. "> /dev/null") == 0 then
kong_config.nginx = "error_log syslog:server="..KONG_SYSLOG..":61828 error;\n"..kong_config.nginx
else
cutils.logger:warn("The internet connection might not be available, cannot resolve "..KONG_SYSLOG)
end
end
-- Create nginx folder if needed
local _, err = IO.path:mkdir(IO.path:join(kong_config.nginx_working_dir, "logs"))
if err then
cutils.logger:error_exit(err)
end
os.execute("touch "..IO.path:join(kong_config.nginx_working_dir, "logs", "error.log"))
os.execute("touch "..IO.path:join(kong_config.nginx_working_dir, "logs", "access.log"))
-- Extract nginx config to nginx folder
local ok, err = IO.write_to_file(IO.path:join(kong_config.nginx_working_dir, constants.CLI.NGINX_CONFIG), kong_config.nginx)
if not ok then
error(err)
end
return kong_config.nginx_working_dir
end
function _M.start(args_config)
-- Make sure nginx is there and is openresty
local nginx_path = find_nginx()
if not nginx_path then
cutils.logger:error_exit("can't find nginx")
end
-- Get configuration from default or given path
local config_path = cutils.get_kong_config_path(args_config)
local config, dao_factory = IO.load_configuration_and_dao(config_path)
-- Migrate the DB if needed and possible
local keyspace, err = dao_factory:get_migrations()
if err then
cutils.logger:error_exit(err)
elseif keyspace == nil then
cutils.logger:log("Database not initialized. Running migrations...")
local migrations = require("kong.tools.migrations")(dao_factory, cutils.get_luarocks_install_dir())
migrations:migrate(function(migration, err)
if err then
cutils.logger:error_exit(err)
elseif migration then
cutils.logger:success("Migrated up to: "..cutils.colors.yellow(migration.name))
end
end)
end
-- Prepare nginx --prefix dir
local nginx_working_dir = prepare_nginx_working_dir(config)
-- Build nginx start command
local cmd = string.format("KONG_CONF=%s %s -p %s -c %s -g 'pid %s;'",
config_path,
nginx_path,
nginx_working_dir,
constants.CLI.NGINX_CONFIG,
constants.CLI.NGINX_PID)
if os.execute(cmd) == 0 then
cutils.logger:success("Started")
else
cutils.logger:error_exit("Could not start Kong")
end
end
return _M.start
|
Fixes #111
|
Fixes #111
|
Lua
|
apache-2.0
|
salazar/kong,rafael/kong,vzaramel/kong,Kong/kong,kyroskoh/kong,jebenexer/kong,Vermeille/kong,vzaramel/kong,Kong/kong,icyxp/kong,ind9/kong,akh00/kong,shiprabehera/kong,ind9/kong,ccyphers/kong,streamdataio/kong,rafael/kong,isdom/kong,ejoncas/kong,xvaara/kong,jerizm/kong,Mashape/kong,isdom/kong,kyroskoh/kong,ajayk/kong,smanolache/kong,streamdataio/kong,beauli/kong,Kong/kong,li-wl/kong,ejoncas/kong
|
d4133f277f4129adef08c82020bf82611effb803
|
vi_mode_search.lua
|
vi_mode_search.lua
|
-- Handle the vim search emulation
-- Modeled on textadept's command_entry.lua
local M = {}
M.search_hl_indic = _SCINTILLA.next_indic_number()
local function set_colours()
buffer.indic_fore[M.search_hl_indic] = 0xFF0000
buffer.indic_style[M.search_hl_indic] = _SCINTILLA.constants.INDIC_ROUNDBOX
buffer.indic_alpha[M.search_hl_indic] = 100
-- Find all occurrences to highlight.
buffer.indicator_current = M.search_hl_indic
buffer:indicator_clear_range(0, buffer.length)
end
M.state = {
in_search_mode = false,
backwards = false,
pattern = "",
}
local state = M.state
local function do_search(backwards)
if state.pattern == "" then return end
ui.statusbar_text = "Search: "..state.pattern
local saved_pos = buffer.current_pos
buffer:search_anchor()
local search_flags = _SCINTILLA.constants.FIND_REGEXP
local searcher = function(...) return buffer:search_next(...) end
-- Search from the end. We'll jump to the first one "after" the current pos.
buffer.current_pos = 0
buffer:search_anchor()
pos = searcher(search_flags, state.pattern)
set_colours()
if pos >= 0 then
local saved_flags = buffer.search_flags
buffer.search_flags = search_flags
local new_pos = nil
-- Need to use search_in_target to find the actual search extents.
buffer.target_start = 0
buffer.target_end = buffer.length
local occurences = 0
local first_pos = nil
local last_pos = nil
while buffer:search_in_target(state.pattern) >= 0 do
local match_len = buffer.target_end - buffer.target_start
last_pos = buffer.target_start
if first_pos == nil then
first_pos = buffer.target_start
end
-- Work out the current pos, ie first hit after the saved position.
if backwards then
if buffer.target_start < saved_pos then
new_pos = buffer.target_start
end
else
-- Forwards - take the first one after saved_pos
if new_pos == nil and buffer.target_start > saved_pos then
new_pos = buffer.target_start
end
end
buffer:indicator_fill_range(buffer.target_start, match_len)
if buffer.target_end == buffer.target_start then
-- Zero length match - not useful, abort here.
buffer.current_pos = saved_pos
ui.statusbar_text = "Not found"
return
end
-- Ensure we make some progress
if buffer.target_end == buffer.target_start then
buffer.target_start = buffer.target_end + 1
else
buffer.target_start = buffer.target_end
end
buffer.target_end = buffer.length
if buffer.target_start >= buffer.length then
break
end
occurences = occurences + 1
end
-- Handle wrapping search
if new_pos == nil then
if backwards then
new_pos = last_pos
else
new_pos = first_pos
end
ui.statusbar_text = "WRAPPED SEARCH"
else
ui.statusbar_text = "Found " .. tostring(occurences)
end
-- Restore global search flags
buffer.search_flags = saved_flags
buffer:ensure_visible(buffer:line_from_position(new_pos))
buffer:goto_pos(new_pos)
buffer.selection_start = new_pos
else
buffer.current_pos = saved_pos
vi_mode.err("Not found")
end
end
local function handle_search_command(command)
if state.in_search_mode then
state.pattern = command
do_search(state.backwards)
state.in_search_mode = false
return false -- make sure this isn't handled again
end
end
-- Register our key bindings for the command entry
local ui_ce = ui.command_entry
local function finish_search(text)
local exitfunc = state.exitfunc
state.exitfunc = nil
if string.len(text) == 0 then
text = state.pattern
end
exitfunc(function()
state.pattern = text
do_search(state.backwards)
end)
end
keys.vi_search_command = {
['ctrl+v'] = {
['\t'] = function()
return keys.vi_search_command['\t']()
end,
},
['\t'] = function() -- insert the string '\t' instead of tab
-- FIXME: insert at correct position ???
local text = ui.command_entry:get_text()
--ui_ce.enter_mode(nil)
ui.command_entry:set_text(text .. "\\t")
--ui_ce.enter_mode("vi_search_command")
end,
['esc'] = function()
ui_ce.enter_mode(nil) -- Exit command_entry mode
keys.mode = "vi_command"
end,
['\b'] = function()
if ui.command_entry:get_text() == "" then
return keys.vi_search_command['esc']() -- exit
end
return false -- propagate the key
end,
}
local function start_common(exitfunc)
state.in_search_mode = true
state.exitfunc = exitfunc
ui.command_entry:set_text("")
-- The command entry as of Textadept 11.0 beta has a history which is indexed
-- on the function passed in, which means that it starts with the last thing
-- entered in that mode. But when I've used the "*" or "#" commands, that
-- doesn't add to the history, and so "/<enter>" or "?<enter>" ends up searching
-- for the previous explicit search rather than what "*" or "#" searched for.
-- The current workaround is to make sure we give it a different function each
-- time, so it doesn't use the history. We need _dummy because otherwise the
-- closure has no captures and is optimised to the same function every time.
local _dummy = nil
ui.command_entry.run(function(...)
if _dummy then end
return finish_search(...)
end)
end
function M.start(exitfunc)
state.backwards = false
return start_common(exitfunc)
end
function M.start_rev(exitfunc)
state.backwards = true
return start_common(exitfunc)
end
function M.restart()
do_search(state.backwards)
end
function M.restart_rev()
do_search(not state.backwards)
end
local function search_word_common(backwards)
-- Search for the word under the cursor
-- TODO: quote properly, or better don't use regex'
-- Uses ideas from editing.lua
local pos = buffer.current_pos
local s, e = buffer:word_start_position(pos, true), buffer:word_end_position(pos)
local word = buffer:text_range(s, e)
if word == "" then return end
state.pattern = '\\b' .. word .. '\\b'
state.backwards = backwards
if backwards then
-- Avoid hitting the current word again if the cursor isn't at the
-- start.
buffer.current_pos = s
end
do_search(backwards)
end
function M.search_word()
search_word_common(false)
end
function M.search_word_rev()
search_word_common(true)
end
return M
|
-- Handle the vim search emulation
-- Modeled on textadept's command_entry.lua
local M = {}
M.search_hl_indic = _SCINTILLA.next_indic_number()
local function set_colours()
buffer.indic_fore[M.search_hl_indic] = 0xFF0000
buffer.indic_style[M.search_hl_indic] = _SCINTILLA.constants.INDIC_ROUNDBOX
buffer.indic_alpha[M.search_hl_indic] = 100
-- Find all occurrences to highlight.
buffer.indicator_current = M.search_hl_indic
buffer:indicator_clear_range(0, buffer.length)
end
M.state = {
in_search_mode = false,
backwards = false,
pattern = "",
}
local state = M.state
local function do_search(backwards)
if state.pattern == "" then return end
ui.statusbar_text = "Search: "..state.pattern
local saved_pos = buffer.current_pos
buffer:search_anchor()
local search_flags = _SCINTILLA.constants.FIND_REGEXP
local searcher = function(...) return buffer:search_next(...) end
-- Search from the end. We'll jump to the first one "after" the current pos.
buffer.current_pos = 0
buffer:search_anchor()
pos = searcher(search_flags, state.pattern)
set_colours()
if pos >= 0 then
local saved_flags = buffer.search_flags
buffer.search_flags = search_flags
local new_pos = nil
-- Need to use search_in_target to find the actual search extents.
buffer.target_start = 0
buffer.target_end = buffer.length
local occurences = 0
local first_pos = nil
local last_pos = nil
while buffer:search_in_target(state.pattern) >= 0 do
local match_len = buffer.target_end - buffer.target_start
last_pos = buffer.target_start
if first_pos == nil then
first_pos = buffer.target_start
end
-- Work out the current pos, ie first hit after the saved position.
if backwards then
if buffer.target_start < saved_pos then
new_pos = buffer.target_start
end
else
-- Forwards - take the first one after saved_pos
if new_pos == nil and buffer.target_start > saved_pos then
new_pos = buffer.target_start
end
end
buffer:indicator_fill_range(buffer.target_start, match_len)
if buffer.target_end == buffer.target_start then
-- Zero length match - not useful, abort here.
buffer.current_pos = saved_pos
ui.statusbar_text = "Not found"
return
end
-- Ensure we make some progress
if buffer.target_end == buffer.target_start then
buffer.target_start = buffer.target_end + 1
else
buffer.target_start = buffer.target_end
end
buffer.target_end = buffer.length
if buffer.target_start >= buffer.length then
break
end
occurences = occurences + 1
end
-- Handle wrapping search
if new_pos == nil then
if backwards then
new_pos = last_pos
else
new_pos = first_pos
end
ui.statusbar_text = "WRAPPED SEARCH"
else
ui.statusbar_text = "Found " .. tostring(occurences)
end
-- Restore global search flags
buffer.search_flags = saved_flags
buffer:ensure_visible(buffer:line_from_position(new_pos))
buffer:goto_pos(new_pos)
buffer.selection_start = new_pos
else
buffer.current_pos = saved_pos
vi_mode.err("Not found")
end
end
local function handle_search_command(command)
if state.in_search_mode then
state.pattern = command
do_search(state.backwards)
state.in_search_mode = false
return false -- make sure this isn't handled again
end
end
-- Register our key bindings for the command entry
local ui_ce = ui.command_entry
local function finish_search(text)
local exitfunc = state.exitfunc
state.exitfunc = nil
if string.len(text) == 0 then
text = state.pattern
end
exitfunc(function()
state.pattern = text
do_search(state.backwards)
end)
end
keys.vi_search_command = {
['ctrl+v'] = {
['\t'] = function()
return keys.vi_search_command['\t']()
end,
},
['\t'] = function() -- insert the string '\t' instead of tab
-- FIXME: insert at correct position ???
local text = ui.command_entry:get_text()
--ui_ce.enter_mode(nil)
ui.command_entry:set_text(text .. "\\t")
--ui_ce.enter_mode("vi_search_command")
end,
['esc'] = function()
ui_ce.enter_mode(nil) -- Exit command_entry mode
keys.mode = "vi_command"
end,
['\b'] = function()
if ui.command_entry:get_text() == "" then
return keys.vi_search_command['esc']() -- exit
end
return false -- propagate the key
end,
}
local function start_common(exitfunc)
state.in_search_mode = true
state.exitfunc = exitfunc
ui.command_entry.run(finish_search)
ui.command_entry:set_text("")
end
function M.start(exitfunc)
state.backwards = false
return start_common(exitfunc)
end
function M.start_rev(exitfunc)
state.backwards = true
return start_common(exitfunc)
end
function M.restart()
do_search(state.backwards)
end
function M.restart_rev()
do_search(not state.backwards)
end
local function search_word_common(backwards)
-- Search for the word under the cursor
-- TODO: quote properly, or better don't use regex'
-- Uses ideas from editing.lua
local pos = buffer.current_pos
local s, e = buffer:word_start_position(pos, true), buffer:word_end_position(pos)
local word = buffer:text_range(s, e)
if word == "" then return end
state.pattern = '\\b' .. word .. '\\b'
state.backwards = backwards
if backwards then
-- Avoid hitting the current word again if the cursor isn't at the
-- start.
buffer.current_pos = s
end
do_search(backwards)
end
function M.search_word()
search_word_common(false)
end
function M.search_word_rev()
search_word_common(true)
end
return M
|
A much simpler fix for the search default text issue.
|
A much simpler fix for the search default text issue.
|
Lua
|
mit
|
jugglerchris/textadept-vi,jugglerchris/textadept-vi
|
b3a32b74aca7178c26769052d9e2e6f179cfadea
|
Quadtastic/AppLogic.lua
|
Quadtastic/AppLogic.lua
|
local unpack = unpack or table.unpack
local quit = love.event.quit or os.exit
local AppLogic = {}
local function run(self, f, ...)
assert(type(f) == "function" or self._state.coroutine)
local co, ret
if self._state.coroutine then
co = self._state.coroutine
ret = {coroutine.resume(co, ...)}
else
co = coroutine.create(f)
ret = {coroutine.resume(co, self._state.data, ...)}
end
-- Print errors if there are any
assert(ret[1], ret[2])
-- If the coroutine yielded then we will issue a state switch based
-- on the returned values.
if coroutine.status(co) == "suspended" then
local new_state = ret[2]
-- Save the coroutine so that it can be resumed later
self._state.coroutine = co
self:push_state(new_state)
else
assert(coroutine.status(co) == "dead")
-- Remove dead coroutine
self._state.coroutine = nil
-- If values were returned, then they will be returned to the
-- next state higher up in the state stack.
-- If this is the only state, then the app will exit with the
-- returned integer as exit code.
if #ret > 1 then
if #self._state_stack > 0 then
self:pop_state(select(2, unpack(ret)))
else
quit(ret[1])
end
end
end
end
setmetatable(AppLogic, {
__call = function(_, initial_state)
local application = {}
application._state = initial_state
application._state_stack = {}
application._event_queue = {}
setmetatable(application, {
__index = function(self, key)
if rawget(AppLogic, key) then return rawget(AppLogic, key)
-- If this is a call for the current state, return that state
elseif key == self._state.name then
-- return a function that executes the command in a subroutine,
-- and captures the function's return values
return setmetatable({}, {__index = function(_, event)
local f = self._state.transitions[event]
return function(...)
run(self, f, ...)
end
end})
-- Otherwise queue that call for later if we have a queue for it
elseif self._event_queue[key] then
return setmetatable({}, {__index = function(_, event)
local f = self._state.transitions[event]
return function(...)
table.insert(self._event_queue[key], {f, ...})
end
end})
else
error(string.format("There is no state %s in the current application.", key))
end
end
})
return application
end
})
function AppLogic.push_state(self, new_state)
assert(string.sub(new_state.name, 1, 1) ~= "_",
"State name cannot start with underscore")
-- Push the current state onto the state stack
table.insert(self._state_stack, self._state)
-- Create a new event queue for the pushed state
self._event_queue[self._state.name] = {}
-- Switch states
self._state = new_state
end
function AppLogic.pop_state(self, ...)
-- Return to previous state
self._state = table.remove(self._state_stack)
-- Resume state's current coroutine with the passed event
if self._state.coroutine and
coroutine.status(self._state.coroutine) == "suspended"
then
coroutine.resume(self._state.coroutine, ...)
end
-- Catch up on events that happened for that state while we were in a
-- different state
for _,event_bundle in ipairs(self._event_queue[self._state.name]) do
local f = event_bundle[1]
f(self._state.data, unpack(event_bundle[2]))
end
end
function AppLogic.get_states(self)
local states = {}
for i,state in ipairs(self._state_stack) do
states[i] = state
end
-- Add the current state
table.insert(states, self._state)
return states
end
function AppLogic.get_current_state(self)
return self._state.name
end
return AppLogic
|
local unpack = unpack or table.unpack
local quit = love.event.quit or os.exit
local AppLogic = {}
local function run(self, f, ...)
assert(type(f) == "function" or self._state.coroutine)
local co, ret
if self._state.coroutine then
co = self._state.coroutine
ret = {coroutine.resume(co, ...)}
else
co = coroutine.create(f)
ret = {coroutine.resume(co, self._state.data, ...)}
end
-- Print errors if there are any
assert(ret[1], ret[2])
-- If the coroutine yielded then we will issue a state switch based
-- on the returned values.
if coroutine.status(co) == "suspended" then
local new_state = ret[2]
-- Save the coroutine so that it can be resumed later
self._state.coroutine = co
self:push_state(new_state)
else
assert(coroutine.status(co) == "dead")
-- Remove dead coroutine
self._state.coroutine = nil
-- If values were returned, then they will be returned to the
-- next state higher up in the state stack.
-- If this is the only state, then the app will exit with the
-- returned integer as exit code.
if #ret > 1 then
if #self._state_stack > 0 then
self:pop_state(select(2, unpack(ret)))
else
quit(ret[1])
end
end
end
end
setmetatable(AppLogic, {
__call = function(_, initial_state)
local application = {}
application._state = initial_state
application._state_stack = {}
application._event_queue = {}
setmetatable(application, {
__index = function(self, key)
if rawget(AppLogic, key) then return rawget(AppLogic, key)
-- If this is a call for the current state, return that state
elseif key == self._state.name then
-- return a function that executes the command in a subroutine,
-- and captures the function's return values
return setmetatable({}, {__index = function(_, event)
local f = self._state.transitions[event]
return function(...)
run(self, f, ...)
end
end})
-- Otherwise queue that call for later if we have a queue for it
elseif self._event_queue[key] then
return setmetatable({}, {__index = function(_, event)
return function(...)
table.insert(self._event_queue[key], {event, {...}})
end
end})
else
error(string.format("There is no state %s in the current application.", key))
end
end
})
return application
end
})
function AppLogic.push_state(self, new_state)
assert(string.sub(new_state.name, 1, 1) ~= "_",
"State name cannot start with underscore")
-- Push the current state onto the state stack
table.insert(self._state_stack, self._state)
-- Create a new event queue for the pushed state if there isn't one already
if not self._event_queue[self._state.name] then
self._event_queue[self._state.name] = {}
end
-- Switch states
self._state = new_state
end
function AppLogic.pop_state(self, ...)
-- Return to previous state
self._state = table.remove(self._state_stack)
local statename = self._state.name
-- Resume state's current coroutine with the passed event
if self._state.coroutine and
coroutine.status(self._state.coroutine) == "suspended"
then
coroutine.resume(self._state.coroutine, ...)
end
-- Catch up on events that happened for that state while we were in a
-- different state, but make sure that states haven't changed since.
if self._state.name == statename then
for _,event_bundle in ipairs(self._event_queue[statename]) do
local f = self._state.transitions[event_bundle[1]]
run(self, f, unpack(event_bundle[2]))
end
self._event_queue[statename] = nil
else
end
end
function AppLogic.get_states(self)
local states = {}
for i,state in ipairs(self._state_stack) do
states[i] = state
end
-- Add the current state
table.insert(states, self._state)
return states
end
function AppLogic.get_current_state(self)
return self._state.name
end
return AppLogic
|
Fix how function calls are queued while target state is not active
|
Fix how function calls are queued while target state is not active
|
Lua
|
mit
|
25A0/Quadtastic,25A0/Quadtastic
|
07599c84fc1a01bfe999f3ad13206c568eea89ee
|
src/controls.lua
|
src/controls.lua
|
local datastore = require 'datastore'
local controls = {}
local buttonmap = datastore.get( 'buttonmap', {
UP = 'up',
DOWN = 'down',
LEFT = 'left',
RIGHT = 'right',
SELECT = 'v',
START = 'escape',
JUMP = ' ',
ACTION = 'z',
} )
function controls.getKeymap()
local keymap = {}
for button, key in pairs(buttonmap) do
keymap[key] = button
end
return keymap
end
local keymap = controls.getKeymap()
function controls.getButtonmap()
local t = {}
for button, _ in pairs(buttonmap) do
t[button] = controls.getKey(button)
end
return t
end
function controls.getButton( key )
return keymap[key]
end
-- Only use this function for display, it returns
-- key values that love doesn't use
function controls.getKey( button )
local key = buttonmap[button]
if key == " " then
return "space"
end
return key
end
function controls.isDown( button )
local key = buttonmap[button]
if key == nil then
return false
end
return love.keyboard.isDown(key)
end
-- Returns true if key is available to be assigned to a button.
-- Returns false if key is 'f5' or already assigned to a button.
function controls.keyIsNotInUse(key)
if key == 'f5' then return false end
for usedKey, _ in pairs(keymap) do
if usedKey == key then return false end
end
return true
end
-- Reassigns key to button and returns true, or returns false if the key is unavailable.
function controls.newButton(key, button)
if controls.getButton(key) == button then return true end
if controls.keyIsNotInUse(key) then
buttonmap[button] = key
keymap = controls.getKeymap()
return true
else return false
end
end
assert(controls.newButton('z', 'ACTION'))
assert(controls.newButton('lshift', 'ACTION'))
assert(controls.newButton('v', 'ACTION') == false)
return controls
|
local datastore = require 'datastore'
local controls = {}
local buttonmap = datastore.get( 'buttonmap', {
UP = 'up',
DOWN = 'down',
LEFT = 'left',
RIGHT = 'right',
SELECT = 'v',
START = 'escape',
JUMP = ' ',
ACTION = 'z',
} )
function controls.getKeymap()
local keymap = {}
for button, key in pairs(buttonmap) do
keymap[key] = button
end
return keymap
end
local keymap = controls.getKeymap()
function controls.getButtonmap()
local t = {}
for button, _ in pairs(buttonmap) do
t[button] = controls.getKey(button)
end
return t
end
function controls.getButton( key )
return keymap[key]
end
-- Only use this function for display, it returns
-- key values that love doesn't use
function controls.getKey( button )
local key = buttonmap[button]
if key == " " then
return "space"
end
return key
end
function controls.isDown( button )
local key = buttonmap[button]
if key == nil then
return false
end
return love.keyboard.isDown(key)
end
-- Returns true if key is available to be assigned to a button.
-- Returns false if key is 'f5' or already assigned to a button.
function controls.keyIsNotInUse(key)
if key == 'f5' then return false end
for usedKey, _ in pairs(keymap) do
if usedKey == key then return false end
end
return true
end
-- Reassigns key to button and returns true, or returns false if the key is unavailable.
function controls.newButton(key, button)
if controls.getButton(key) == button then return true end
if controls.keyIsNotInUse(key) then
buttonmap[button] = key
keymap = controls.getKeymap()
return true
else return false
end
end
assert(controls.newButton('z', 'ACTION'))
assert(controls.newButton('lshift', 'ACTION'))
--temporarily commented out for multiplayer compliance testing
--assert(controls.newButton('v', 'ACTION') == false)
return controls
|
compliance fix
|
compliance fix
|
Lua
|
mit
|
hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-client-lua
|
2497f473f9d0567314e5232cd8bf9505702e90ec
|
src/lunajson/encode.lua
|
src/lunajson/encode.lua
|
local byte = string.byte
local find = string.find
local format = string.format
local gsub = string.gsub
local match = string.match
local rawequal = rawequal
local tostring = tostring
local type = type
local function encode(v, nullv)
local i = 1
local builder = {}
local visited = {}
local function f_tostring(v)
builder[i] = tostring(v)
i = i+1
end
local radixmark = match(tostring(0.5), '[^0-9]')
local delimmark = match(tostring(123456789.123456789), '[^0-9' .. radixmark .. ']')
if radixmark == '.' then
radixmark = nil
end
local f_number = f_tostring
if radixmark or delimmark then
if radixmark and find(radixmark, '%W') then
radixmark = '%' .. radixmark
end
if delimmark and find(selimmark, '%W') then
delimmark = '%' .. delimmark
end
f_number = function(n)
local s = tostring(n)
if delimmark then
s = gsub(s, delimmark, '')
end
if radixmark then
s = gsub(s, radixmark, '.')
end
builder[i] = s
i = i+1
end
end
local dodecode
local f_string_subst = {
['"'] = '\\"',
['\\'] = '\\\\',
['\b'] = '\\b',
['\f'] = '\\f',
['\n'] = '\\n',
['\r'] = '\\r',
['\t'] = '\\t',
__index = function(_, c)
return format('\\u00%02X', tostring(byte(c)))
end
}
setmetatable(f_string_subst, f_string_subst)
local function f_string(s)
-- use the cluttered pattern because lua 5.1 does not handle \0 in a pattern correctly
local pat = '[^\32-\33\35-\91\93-\255]'
builder[i] = '"'
if find(s, pat) then
s = gsub(s, pat, f_string_subst)
end
builder[i+1] = s
builder[i+2] = '"'
i = i+3
end
local function f_table(o)
if visited[o] then
error("loop detected")
end
visited[o] = true
local alen = o[0]
if type(alen) == 'number' then
builder[i] = '['
i = i+1
for j = 1, alen do
dodecode(o[j])
builder[i] = ','
i = i+1
end
if alen > 0 then
i = i-1
end
builder[i] = ']'
i = i+1
return
end
local v = o[1]
if v ~= nil then
builder[i] = '['
i = i+1
local j = 2
repeat
dodecode(v)
v = o[j]
if v == nil then
break
end
j = j+1
builder[i] = ','
i = i+1
until false
builder[i] = ']'
i = i+1
return
end
builder[i] = '{'
i = i+1
local oldi = i
for k, v in pairs(o) do
if type(k) ~= 'string' then
error("non-string key")
end
f_string(k)
builder[i] = ':'
i = i+1
dodecode(v)
builder[i] = ','
i = i+1
end
if i > oldi then
i = i-1
end
builder[i] = '}'
i = i+1
end
local dispatcher = {
boolean = f_tostring,
number = f_tostring,
string = f_string,
table = arraylen and f_table_arraylen or f_table,
__index = function()
error("invalid type value")
end
}
setmetatable(dispatcher, dispatcher)
function dodecode(v)
if rawequal(v, nullv) then
builder[i] = 'null'
i = i+1
return
end
dispatcher[type(v)](v)
end
-- exec
dodecode(v)
return table.concat(builder)
end
return {
encode = encode
}
|
local byte = string.byte
local find = string.find
local format = string.format
local gsub = string.gsub
local match = string.match
local rawequal = rawequal
local tostring = tostring
local pairs = pairs
local type = type
local function encode(v, nullv)
local i = 1
local builder = {}
local visited = {}
local function f_tostring(v)
builder[i] = tostring(v)
i = i+1
end
local f_number = function(n)
builder[i] = format("%.17g", n)
i = i+1
end
do
local radixmark = match(tostring(0.5), '[^0-9]')
local delimmark = match(tostring(123456789.123456789), '[^0-9' .. radixmark .. ']')
if radixmark == '.' then
radixmark = nil
end
if radixmark or delimmark then
if radixmark and find(radixmark, '%W') then
radixmark = '%' .. radixmark
end
if delimmark and find(selimmark, '%W') then
delimmark = '%' .. delimmark
end
f_number = function(n)
local s = format("%.17g", n)
if delimmark then
s = gsub(s, delimmark, '')
end
if radixmark then
s = gsub(s, radixmark, '.')
end
builder[i] = s
i = i+1
end
end
end
local dodecode
local f_string_subst = {
['"'] = '\\"',
['\\'] = '\\\\',
['\b'] = '\\b',
['\f'] = '\\f',
['\n'] = '\\n',
['\r'] = '\\r',
['\t'] = '\\t',
__index = function(_, c)
return format('\\u00%02X', tostring(byte(c)))
end
}
setmetatable(f_string_subst, f_string_subst)
local function f_string(s)
-- use the cluttered pattern because lua 5.1 does not handle \0 in a pattern correctly
local pat = '[^\32-\33\35-\91\93-\255]'
builder[i] = '"'
if find(s, pat) then
s = gsub(s, pat, f_string_subst)
end
builder[i+1] = s
builder[i+2] = '"'
i = i+3
end
local function f_table(o)
if visited[o] then
error("loop detected")
end
visited[o] = true
local alen = o[0]
if type(alen) == 'number' then
builder[i] = '['
i = i+1
for j = 1, alen do
dodecode(o[j])
builder[i] = ','
i = i+1
end
if alen > 0 then
i = i-1
end
builder[i] = ']'
i = i+1
return
end
local v = o[1]
if v ~= nil then
builder[i] = '['
i = i+1
local j = 2
repeat
dodecode(v)
v = o[j]
if v == nil then
break
end
j = j+1
builder[i] = ','
i = i+1
until false
builder[i] = ']'
i = i+1
return
end
builder[i] = '{'
i = i+1
local oldi = i
for k, v in pairs(o) do
if type(k) ~= 'string' then
error("non-string key")
end
f_string(k)
builder[i] = ':'
i = i+1
dodecode(v)
builder[i] = ','
i = i+1
end
if i > oldi then
i = i-1
end
builder[i] = '}'
i = i+1
end
local dispatcher = {
boolean = f_tostring,
number = f_tostring,
string = f_string,
table = arraylen and f_table_arraylen or f_table,
__index = function()
error("invalid type value")
end
}
setmetatable(dispatcher, dispatcher)
function dodecode(v)
if rawequal(v, nullv) then
builder[i] = 'null'
i = i+1
return
end
dispatcher[type(v)](v)
end
-- exec
dodecode(v)
return table.concat(builder)
end
return {
encode = encode
}
|
fix tonumber precision
|
fix tonumber precision
|
Lua
|
mit
|
bigcrush/lunajson,tst2005/lunajson,grafi-tt/lunajson,csteddy/lunajson,grafi-tt/lunajson,grafi-tt/lunajson,tst2005/lunajson,bigcrush/lunajson,csteddy/lunajson
|
248223599e402b16217674350776296861463455
|
src/plugins/finalcutpro/timeline/stabilization.lua
|
src/plugins/finalcutpro/timeline/stabilization.lua
|
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- C O M M A N D P O S T --
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--- === plugins.finalcutpro.timeline.stabilization ===
---
--- Stabilization Shortcut
--------------------------------------------------------------------------------
--
-- EXTENSIONS:
--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- CommandPost Extensions:
--------------------------------------------------------------------------------
local fcp = require("cp.apple.finalcutpro")
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local mod = {}
--- plugins.finalcutpro.timeline.stabilization.enable() -> none
--- Function
--- Enables or disables Stabilisation.
---
--- Parameters:
--- * value - `true` to enable, `false` to disable, `nil` to toggle.
---
--- Returns:
--- * None
function mod.enable(value)
--------------------------------------------------------------------------------
-- Set Stabilization:
--------------------------------------------------------------------------------
local inspector = fcp:inspector()
local inspectorShowing = inspector:isShowing()
local stabilization = inspector:video():stabilization():show()
value = value == nil and not stabilization:enabled() or value
stabilization:enabled(value)
if not inspectorShowing then
inspector:hide()
end
end
--------------------------------------------------------------------------------
--
-- THE PLUGIN:
--
--------------------------------------------------------------------------------
local plugin = {
id = "finalcutpro.timeline.stabilization",
group = "finalcutpro",
dependencies = {
["finalcutpro.commands"] = "fcpxCmds",
}
}
--------------------------------------------------------------------------------
-- INITIALISE PLUGIN:
--------------------------------------------------------------------------------
function plugin.init(deps)
--------------------------------------------------------------------------------
-- Setup Commands:
--------------------------------------------------------------------------------
if deps.fcpxCmds then
local cmds = deps.fcpxCmds
cmds:add("cpStabilizationToggle")
:groupedBy("timeline")
:whenActivated(function() mod.enable() end)
cmds:add("cpStabilizationEnable")
:groupedBy("timeline")
:whenActivated(function() mod.enable(true) end)
cmds:add("cpStabilizationDisable")
:groupedBy("timeline")
:whenActivated(function() mod.enable(false) end)
end
return mod
end
return plugin
|
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- C O M M A N D P O S T --
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--- === plugins.finalcutpro.timeline.stabilization ===
---
--- Stabilization Shortcut
--------------------------------------------------------------------------------
--
-- EXTENSIONS:
--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Logger:
--------------------------------------------------------------------------------
--local log = require("hs.logger").new("stabilization")
--------------------------------------------------------------------------------
-- CommandPost Extensions:
--------------------------------------------------------------------------------
local fcp = require("cp.apple.finalcutpro")
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local mod = {}
--- plugins.finalcutpro.timeline.stabilization.enable() -> none
--- Function
--- Enables or disables Stabilisation.
---
--- Parameters:
--- * value - `true` to enable, `false` to disable, `nil` to toggle.
---
--- Returns:
--- * None
function mod.enable(value)
--------------------------------------------------------------------------------
-- Set Stabilization:
--------------------------------------------------------------------------------
local inspector = fcp:inspector()
local inspectorShowing = inspector:isShowing()
local stabilization = inspector:video():stabilization()
stabilization:show()
if value == nil then
value = not stabilization:enabled()
end
stabilization:enabled(value)
if not inspectorShowing then
inspector:hide()
end
end
--------------------------------------------------------------------------------
--
-- THE PLUGIN:
--
--------------------------------------------------------------------------------
local plugin = {
id = "finalcutpro.timeline.stabilization",
group = "finalcutpro",
dependencies = {
["finalcutpro.commands"] = "fcpxCmds",
}
}
--------------------------------------------------------------------------------
-- INITIALISE PLUGIN:
--------------------------------------------------------------------------------
function plugin.init(deps)
--------------------------------------------------------------------------------
-- Setup Commands:
--------------------------------------------------------------------------------
if deps.fcpxCmds then
local cmds = deps.fcpxCmds
cmds:add("cpStabilizationToggle")
:groupedBy("timeline")
:whenActivated(function() mod.enable() end)
cmds:add("cpStabilizationEnable")
:groupedBy("timeline")
:whenActivated(function() mod.enable(true) end)
cmds:add("cpStabilizationDisable")
:groupedBy("timeline")
:whenActivated(function() mod.enable(false) end)
end
return mod
end
return plugin
|
#1074
|
#1074
- Fixed bug when toggling Stabilisation
- Closes #1074
|
Lua
|
mit
|
fcpxhacks/fcpxhacks,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost
|
44ca73d9f263332d4017ee25c41c7a9463e70486
|
mods/soundset/init.lua
|
mods/soundset/init.lua
|
minetest.log("action","[mod soundset] Loading...")
soundset = {}
soundset.file = minetest.get_worldpath() .. "/sounds_config.txt"
soundset.gainplayers = {}
soundset.tmp = {}
local function save_sounds_config()
local input = io.open(soundset.file, "w")
if input then
input:write(minetest.serialize(soundset.gainplayers))
input:close()
else
minetest.log("action","echec d'ouverture (mode:w) de " .. soundset.file)
end
end
local function load_sounds_config()
local file = io.open(soundset.file, "r")
if file then
soundset.gainplayers = minetest.deserialize(file:read("*all"))
file:close()
end
if soundset.gainplayers == nil or type(soundset.gainplayers) ~= "table" then
soundset.gainplayers = {}
end
end
load_sounds_config()
soundset.set_sound = function(name, param)
if param == "" then
minetest.chat_send_player(name, "/setsound <music|ambience|mobs|other> <number>")
return
end
local param_name, param_value = param:match("^(%S+)%s(%S+)$")
if param_name == nil or param_value == nil then
minetest.chat_send_player(name, "invalid param, /setsound <music|ambience|mobs|other> <number>")
return
end
if param_name ~= "music" and param_name ~= "ambience" and param_name ~= "mobs" and param_name ~= "other" then
minetest.chat_send_player(name, "invalid param " .. param_name)
return
end
local value = tonumber(param_value)
if value == nil then
minetest.chat_send_player(name, "invalid value, " ..param_value .. " must be number")
return
end
if value < 0 then
value = 0
elseif value > 100 then
value = 100
end
if soundset.gainplayers[name][param_name] == value then
minetest.chat_send_player(name, "volume " .. param_name .. " already set to " .. value)
return
end
soundset.gainplayers[name][param_name] = value
minetest.chat_send_player(name, "sound " .. param_name .. " set to " .. value)
save_sounds_config()
end
soundset.get_gain = function(name, sound_type)
if name == nil or name == "" then
return 1
end
local gain = soundset.gainplayers[name][sound_type]
if gain == nil then
return 1
end
return gain/100
end
local inc = function(value)
value = value + 5
if value > 100 then
value = 100
end
return value
end
local dec = function(value)
value = value - 5
if value < 0 then
value = 0
end
return value
end
local formspec = "size[6,6]"..
"label[2,0;Sound Menu]"..
"label[0,1.2;MUSIC]"..
"image_button[1.6,1;1,1;soundset_dec.png;vmusic;-]"..
"label[2.7,1.2;%s]"..
"image_button[3.5,1;1,1;soundset_inc.png;vmusic;+]"..
"label[0,2.2;AMBIENCE]"..
"image_button[1.6,2;1,1;soundset_dec.png;vambience;-]"..
"label[2.7,2.2;%s]"..
"image_button[3.5,2;1,1;soundset_inc.png;vambience;+]"..
"label[0,3.2;OTHER]"..
"image_button[1.6,3;1,1;soundset_dec.png;vother;-]"..
"label[2.7,3.2;%s]"..
"image_button[3.5,3;1,1;soundset_inc.png;vother;+]"..
"button_exit[0.5,5.2;1.5,1;abort;Abort]"..
"button_exit[4,5.2;1.5,1;abort;Ok]"
local on_show_settings = function(name, music, ambience, other)
if not soundset.tmp[name] then
soundset.tmp[name] = {}
end
soundset.tmp[name]["music"] = music
soundset.tmp[name]["ambience"] = ambience
soundset.tmp[name]["other"] = other
minetest.show_formspec( name, "soundset:settings", string.format(formspec, tostring(music), tostring(ambience), tostring(other) ))
end
minetest.register_on_player_receive_fields(function(player, formname, fields)
if formname == "soundset:settings" then
local name = player:get_player_name()
if not name then return end
local fmusic = soundset.tmp[name]["music"]
local fambience = soundset.tmp[name]["ambience"]
local fother = soundset.tmp[name]["other"]
if fields["abort"] == "Ok" then
if soundset.gainplayers[name]["music"] ~= fmusic or soundset.gainplayers[name]["ambience"] ~= fambience or soundset.gainplayers[name]["other"] ~= fother then
soundset.gainplayers[name]["music"] = fmusic
soundset.gainplayers[name]["ambience"] = fambience
soundset.gainplayers[name]["other"] = fother
save_sounds_config()
end
soundset.tmp[name] = nil
return
elseif fields["abort"] == "Abort" then
soundset.tmp[name] = nil
return
elseif fields["vmusic"] == "+" then
fmusic = inc(fmusic)
elseif fields["vmusic"] == "-" then
fmusic = dec(fmusic)
elseif fields["vambience"] == "+" then
fambience = inc(fambience)
elseif fields["vambience"] == "-" then
fambience = dec(fambience)
elseif fields["vother"] == "+" then
fother = inc(fother)
elseif fields["vother"] == "-" then
fother = dec(fother)
elseif fields["quit"] == "true" then
soundset.tmp[name] = nil
return
else
return
end
on_show_settings(name, fmusic, fambience, fother)
end
end)
if (minetest.get_modpath("unified_inventory")) then
unified_inventory.register_button("menu_soundset", {
type = "image",
image = "soundset_menu_icon.png",
tooltip = "sounds menu ",
show_with = false, --Modif MFF (Crabman 30/06/2015)
action = function(player)
local name = player:get_player_name()
if not name then return end
on_show_settings(name, soundset.gainplayers[name]["music"], soundset.gainplayers[name]["ambience"], soundset.gainplayers[name]["other"])
end,
})
end
minetest.register_chatcommand("soundset", {
params = "",
description = "Display volume menu formspec",
privs = {interact=true},
func = function(name, param)
if not name then return end
on_show_settings(name, soundset.gainplayers[name]["music"], soundset.gainplayers[name]["ambience"], soundset.gainplayers[name]["other"])
end
})
minetest.register_chatcommand("soundsets", {
params = "<music|ambience|mobs|other> <number>",
description = "Set volume sound <music|ambience|mobs|other>",
privs = {interact=true},
func = soundset.set_sound,
})
minetest.register_chatcommand("soundsetg", {
params = "",
description = "Display volume sound <music|ambience|mobs|other>",
privs = {interact=true},
func = function(name, param)
local conf = ""
for k, v in pairs(soundset.gainplayers[name]) do
conf = conf .. " " .. k .. ":" .. v
end
minetest.chat_send_player(name, "sounds conf " .. conf)
minetest.log("action","Player ".. name .. " sound conf " .. conf)
end
})
minetest.register_on_joinplayer(function(player)
local name = player:get_player_name()
if soundset.gainplayers[name] == nil then
soundset.gainplayers[name] = { ["music"] = 50, ["ambience"] = 50, ["mobs"] = 50, ["other"] = 50 }
end
end)
minetest.log("action","[mod soundset] Loaded")
|
minetest.log("action","[mod soundset] Loading...")
soundset = {}
soundset.file = minetest.get_worldpath() .. "/sounds_config.txt"
soundset.gainplayers = {}
soundset.tmp = {}
local function save_sounds_config()
local input = io.open(soundset.file, "w")
if input then
input:write(minetest.serialize(soundset.gainplayers))
input:close()
else
minetest.log("action","echec d'ouverture (mode:w) de " .. soundset.file)
end
end
local function load_sounds_config()
local file = io.open(soundset.file, "r")
if file then
soundset.gainplayers = minetest.deserialize(file:read("*all"))
file:close()
end
if soundset.gainplayers == nil or type(soundset.gainplayers) ~= "table" then
soundset.gainplayers = {}
end
end
load_sounds_config()
soundset.set_sound = function(name, param)
if param == "" then
minetest.chat_send_player(name, "/setsound <music|ambience|mobs|other> <number>")
return
end
local param_name, param_value = param:match("^(%S+)%s(%S+)$")
if param_name == nil or param_value == nil then
minetest.chat_send_player(name, "invalid param, /setsound <music|ambience|mobs|other> <number>")
return
end
if param_name ~= "music" and param_name ~= "ambience" and param_name ~= "mobs" and param_name ~= "other" then
minetest.chat_send_player(name, "invalid param " .. param_name)
return
end
local value = tonumber(param_value)
if value == nil then
minetest.chat_send_player(name, "invalid value, " ..param_value .. " must be number")
return
end
if value < 0 then
value = 0
elseif value > 100 then
value = 100
end
if soundset.gainplayers[name][param_name] == value then
minetest.chat_send_player(name, "volume " .. param_name .. " already set to " .. value)
return
end
soundset.gainplayers[name][param_name] = value
minetest.chat_send_player(name, "sound " .. param_name .. " set to " .. value)
save_sounds_config()
end
soundset.get_gain = function(name, sound_type)
if name == nil or name == "" then
return 1
end
if not soundset.gainplayers[name] then return gain end
local gain = soundset.gainplayers[name][sound_type]
if gain == nil then
return 1
end
return gain/100
end
local inc = function(value)
value = value + 5
if value > 100 then
value = 100
end
return value
end
local dec = function(value)
value = value - 5
if value < 0 then
value = 0
end
return value
end
local formspec = "size[6,6]"..
"label[2,0;Sound Menu]"..
"label[0,1.2;MUSIC]"..
"image_button[1.6,1;1,1;soundset_dec.png;vmusic;-]"..
"label[2.7,1.2;%s]"..
"image_button[3.5,1;1,1;soundset_inc.png;vmusic;+]"..
"label[0,2.2;AMBIENCE]"..
"image_button[1.6,2;1,1;soundset_dec.png;vambience;-]"..
"label[2.7,2.2;%s]"..
"image_button[3.5,2;1,1;soundset_inc.png;vambience;+]"..
"label[0,3.2;OTHER]"..
"image_button[1.6,3;1,1;soundset_dec.png;vother;-]"..
"label[2.7,3.2;%s]"..
"image_button[3.5,3;1,1;soundset_inc.png;vother;+]"..
"button_exit[0.5,5.2;1.5,1;abort;Abort]"..
"button_exit[4,5.2;1.5,1;abort;Ok]"
local on_show_settings = function(name, music, ambience, other)
if not soundset.tmp[name] then
soundset.tmp[name] = {}
end
soundset.tmp[name]["music"] = music
soundset.tmp[name]["ambience"] = ambience
soundset.tmp[name]["other"] = other
minetest.show_formspec( name, "soundset:settings", string.format(formspec, tostring(music), tostring(ambience), tostring(other) ))
end
minetest.register_on_player_receive_fields(function(player, formname, fields)
if formname == "soundset:settings" then
local name = player:get_player_name()
if not name then return end
local fmusic = soundset.tmp[name]["music"]
local fambience = soundset.tmp[name]["ambience"]
local fother = soundset.tmp[name]["other"]
if fields["abort"] == "Ok" then
if soundset.gainplayers[name]["music"] ~= fmusic or soundset.gainplayers[name]["ambience"] ~= fambience or soundset.gainplayers[name]["other"] ~= fother then
soundset.gainplayers[name]["music"] = fmusic
soundset.gainplayers[name]["ambience"] = fambience
soundset.gainplayers[name]["other"] = fother
save_sounds_config()
end
soundset.tmp[name] = nil
return
elseif fields["abort"] == "Abort" then
soundset.tmp[name] = nil
return
elseif fields["vmusic"] == "+" then
fmusic = inc(fmusic)
elseif fields["vmusic"] == "-" then
fmusic = dec(fmusic)
elseif fields["vambience"] == "+" then
fambience = inc(fambience)
elseif fields["vambience"] == "-" then
fambience = dec(fambience)
elseif fields["vother"] == "+" then
fother = inc(fother)
elseif fields["vother"] == "-" then
fother = dec(fother)
elseif fields["quit"] == "true" then
soundset.tmp[name] = nil
return
else
return
end
on_show_settings(name, fmusic, fambience, fother)
end
end)
if (minetest.get_modpath("unified_inventory")) then
unified_inventory.register_button("menu_soundset", {
type = "image",
image = "soundset_menu_icon.png",
tooltip = "sounds menu ",
show_with = false, --Modif MFF (Crabman 30/06/2015)
action = function(player)
local name = player:get_player_name()
if not name then return end
on_show_settings(name, soundset.gainplayers[name]["music"], soundset.gainplayers[name]["ambience"], soundset.gainplayers[name]["other"])
end,
})
end
minetest.register_chatcommand("soundset", {
params = "",
description = "Display volume menu formspec",
privs = {interact=true},
func = function(name, param)
if not name then return end
on_show_settings(name, soundset.gainplayers[name]["music"], soundset.gainplayers[name]["ambience"], soundset.gainplayers[name]["other"])
end
})
minetest.register_chatcommand("soundsets", {
params = "<music|ambience|mobs|other> <number>",
description = "Set volume sound <music|ambience|mobs|other>",
privs = {interact=true},
func = soundset.set_sound,
})
minetest.register_chatcommand("soundsetg", {
params = "",
description = "Display volume sound <music|ambience|mobs|other>",
privs = {interact=true},
func = function(name, param)
local conf = ""
for k, v in pairs(soundset.gainplayers[name]) do
conf = conf .. " " .. k .. ":" .. v
end
minetest.chat_send_player(name, "sounds conf " .. conf)
minetest.log("action","Player ".. name .. " sound conf " .. conf)
end
})
minetest.register_on_joinplayer(function(player)
local name = player:get_player_name()
if soundset.gainplayers[name] == nil then
soundset.gainplayers[name] = { ["music"] = 50, ["ambience"] = 50, ["mobs"] = 50, ["other"] = 50 }
end
end)
minetest.log("action","[mod soundset] Loaded")
|
Soundset: Fix crash when dead players rejoin a rebooted server
|
Soundset: Fix crash when dead players rejoin a rebooted server
|
Lua
|
unlicense
|
LeMagnesium/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,crabman77/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun,sys4-fr/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Coethium/server-minetestforfun,Ombridride/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/server-minetestforfun,Ombridride/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,sys4-fr/server-minetestforfun
|
fa5dc09c5f01d70641d5bd4d5fd04a34948e3a2e
|
core/ext/find.lua
|
core/ext/find.lua
|
-- Copyright 2007 Mitchell mitchell<att>caladbolg.net. See LICENSE.
local find = textadept.find
---
-- [Local table] Text escape sequences with their associated characters.
-- @class table
-- @name escapes
local escapes = {
['\\a'] = '\a', ['\\b'] = '\b', ['\\f'] = '\f', ['\\n'] = '\n',
['\\r'] = '\r', ['\\t'] = '\t', ['\\v'] = '\v', ['\\\\'] = '\\'
}
---
-- Finds and selects text in the current buffer.
-- This is used by the find dialog. It is recommended to use the buffer:find()
-- function for scripting.
-- @param text The text to find.
-- @param flags Search flags. This is a number mask of 3 flags: match case (2),
-- whole word (4), and Lua pattern (8) joined with binary AND.
-- @param next Flag indicating whether or not the search direction is forward.
-- @param nowrap Flag indicating whether or not the search won't wrap.
-- @param wrapped Utility flag indicating whether or not the search has wrapped
-- for displaying useful statusbar information. This flag is used and set
-- internally, and should not be set otherwise.
function find.find(text, flags, next, nowrap, wrapped)
local buffer = buffer
local increment, result
text = text:gsub('\\[abfnrtv\\]', escapes)
find.captures = nil
if buffer.current_pos == buffer.anchor then
increment = 0
elseif not wrapped then
increment = next and 1 or -1
end
if flags < 8 then
if next then
buffer:goto_pos(buffer.current_pos + increment)
buffer:search_anchor()
result = buffer:search_next(flags, text)
else
buffer:goto_pos(buffer.anchor - increment)
buffer:search_anchor()
result = buffer:search_prev(flags, text)
end
if result then buffer:scroll_caret() end
else -- lua pattern search
local buffer_text = buffer:get_text(buffer.length)
local results = { buffer_text:find(text, buffer.anchor + increment) }
if #results > 0 then
result = results[1]
find.captures = { unpack(results, 3) }
buffer:set_sel(results[2], result - 1)
else
result = -1
end
end
if result == -1 and not nowrap and not wrapped then -- wrap the search
local anchor, pos = buffer.anchor, buffer.current_pos
if next or flags >= 8 then
buffer:goto_pos(0)
else
buffer:goto_pos(buffer.length)
end
textadept.statusbar_text = 'Search wrapped'
result = find.find(text, flags, next, true, true)
if not result then
textadept.statusbar_text = 'No results found'
buffer:goto_pos(anchor)
end
return result
elseif result ~= -1 and not wrapped then
textadept.statusbar_text = ''
end
return result ~= -1
end
---
-- Replaces found text.
-- This function is used by the find dialog. It is not recommended to call it
-- via scripts.
-- textadept.find.find is called first, to select any found text. The selected
-- text is then replaced by the specified replacement text.
-- @param rtext The text to replace found text with. It can contain both Lua
-- capture items (%n where 1 <= n <= 9) for Lua pattern searches and %()
-- sequences for embedding Lua code for any search.
function find.replace(rtext)
if #buffer:get_sel_text() == 0 then return end
local buffer = buffer
buffer:target_from_selection()
rtext = rtext:gsub('%%%%', '\\037') -- escape '%%'
if find.captures then
for i, v in ipairs(find.captures) do
rtext = rtext:gsub('%%'..i, v)
end
end
local ret, rtext = pcall( rtext.gsub, rtext, '%%(%b())',
function(code)
local ret, val = pcall( loadstring('return '..code) )
if not ret then
os.execute('zenity --error --text "'..val:gsub('"', '\\"')..'"')
error()
end
return val
end )
if ret then
rtext = rtext:gsub('\\037', '%%') -- unescape '%'
buffer:replace_target( rtext:gsub('\\[abfnrtv\\]', escapes) )
buffer:goto_pos(buffer.target_end + 1) -- 'find' text after this replacement
else
-- Since find is called after replace returns, have it 'find' the current
-- text again, rather than the next occurance so the user can fix the error.
buffer:goto_pos(buffer.current_pos)
end
end
---
-- Replaces all found text.
-- This function is used by the find dialog. It is not recommended to call it
-- via scripts.
-- @param ftext The text to find.
-- @param rtext The text to replace found text with.
-- @param flags The number mask identical to the one in 'find'.
-- @see find.find
function find.replace_all(ftext, rtext, flags)
buffer:goto_pos(0)
local count = 0
while( find.find(ftext, flags, true, true) ) do
find.replace(rtext)
count = count + 1
end
textadept.statusbar_text = tostring(count)..' replacement(s) made'
end
|
-- Copyright 2007 Mitchell mitchell<att>caladbolg.net. See LICENSE.
local find = textadept.find
---
-- [Local table] Text escape sequences with their associated characters.
-- @class table
-- @name escapes
local escapes = {
['\\a'] = '\a', ['\\b'] = '\b', ['\\f'] = '\f', ['\\n'] = '\n',
['\\r'] = '\r', ['\\t'] = '\t', ['\\v'] = '\v', ['\\\\'] = '\\'
}
---
-- Finds and selects text in the current buffer.
-- This is used by the find dialog. It is recommended to use the buffer:find()
-- function for scripting.
-- @param text The text to find.
-- @param flags Search flags. This is a number mask of 3 flags: match case (2),
-- whole word (4), and Lua pattern (8) joined with binary AND.
-- @param next Flag indicating whether or not the search direction is forward.
-- @param nowrap Flag indicating whether or not the search won't wrap.
-- @param wrapped Utility flag indicating whether or not the search has wrapped
-- for displaying useful statusbar information. This flag is used and set
-- internally, and should not be set otherwise.
function find.find(text, flags, next, nowrap, wrapped)
local buffer = buffer
local increment, result
text = text:gsub('\\[abfnrtv\\]', escapes)
find.captures = nil
if buffer.current_pos == buffer.anchor then
increment = 0
elseif not wrapped then
increment = next and 1 or -1
end
if flags < 8 then
buffer:goto_pos( buffer[next and 'current_pos' or 'anchor'] + increment )
buffer:search_anchor()
if next then
result = buffer:search_next(flags, text)
else
result = buffer:search_prev(flags, text)
end
if result then buffer:scroll_caret() end
else -- lua pattern search (forward search only)
local buffer_text = buffer:get_text(buffer.length)
local results = { buffer_text:find(text, buffer.anchor + increment) }
if #results > 0 then
result = results[1]
find.captures = { unpack(results, 3) }
buffer:set_sel(results[2], result - 1)
else
result = -1
end
end
if result == -1 and not nowrap and not wrapped then -- wrap the search
local anchor, pos = buffer.anchor, buffer.current_pos
if next or flags >= 8 then
buffer:goto_pos(0)
else
buffer:goto_pos(buffer.length)
end
textadept.statusbar_text = 'Search wrapped'
result = find.find(text, flags, next, true, true)
if not result then
textadept.statusbar_text = 'No results found'
buffer:goto_pos(anchor)
end
return result
elseif result ~= -1 and not wrapped then
textadept.statusbar_text = ''
end
return result ~= -1
end
---
-- Replaces found text.
-- This function is used by the find dialog. It is not recommended to call it
-- via scripts.
-- textadept.find.find is called first, to select any found text. The selected
-- text is then replaced by the specified replacement text.
-- @param rtext The text to replace found text with. It can contain both Lua
-- capture items (%n where 1 <= n <= 9) for Lua pattern searches and %()
-- sequences for embedding Lua code for any search.
function find.replace(rtext)
if #buffer:get_sel_text() == 0 then return end
local buffer = buffer
buffer:target_from_selection()
rtext = rtext:gsub('%%%%', '\\037') -- escape '%%'
if find.captures then
for i, v in ipairs(find.captures) do
rtext = rtext:gsub('%%'..i, v)
end
end
local ret, rtext = pcall( rtext.gsub, rtext, '%%(%b())',
function(code)
local ret, val = pcall( loadstring('return '..code) )
if not ret then
os.execute('zenity --error --text "'..val:gsub('"', '\\"')..'"')
error()
end
return val
end )
if ret then
rtext = rtext:gsub('\\037', '%%') -- unescape '%'
buffer:replace_target( rtext:gsub('\\[abfnrtv\\]', escapes) )
buffer:goto_pos(buffer.target_end + 1) -- 'find' text after this replacement
else
-- Since find is called after replace returns, have it 'find' the current
-- text again, rather than the next occurance so the user can fix the error.
buffer:goto_pos(buffer.current_pos)
end
end
---
-- Replaces all found text.
-- This function is used by the find dialog. It is not recommended to call it
-- via scripts.
-- @param ftext The text to find.
-- @param rtext The text to replace found text with.
-- @param flags The number mask identical to the one in 'find'.
-- @see find.find
function find.replace_all(ftext, rtext, flags)
buffer:goto_pos(0)
local count = 0
while( find.find(ftext, flags, true, true) ) do
find.replace(rtext)
count = count + 1
end
textadept.statusbar_text = tostring(count)..' replacement(s) made'
end
|
Fixed 'find previous' bug; core/ext/find.lua Changeset 15 introduced an 'increment' variable that is normally +/-1 for find next and find prev respectively. However instead of adding the increment for find prev, it subtracts it, effectively adding 1 which is not right.
|
Fixed 'find previous' bug; core/ext/find.lua
Changeset 15 introduced an 'increment' variable that is normally +/-1 for find
next and find prev respectively. However instead of adding the increment for
find prev, it subtracts it, effectively adding 1 which is not right.
|
Lua
|
mit
|
rgieseke/textadept,rgieseke/textadept
|
fab27a7909658f0125a478de2993513717fad8c8
|
Peripherals/GPU/calibrate.lua
|
Peripherals/GPU/calibrate.lua
|
--This file is responsible of generating all the drawing offsets
--It will works by testing on canvases, invisibly to the user.
--[[local ofs = {} --Offsets table.
ofs.point = {0,0} --The offset of GPU.point/s.
ofs.print = {-1,-1} --The offset of GPU.print.
ofs.print_grid = {-1,-1} --The offset of GPU.print with grid mode.
ofs.line_start = {0,0} --The offset of the first coord of GPU.line/s.
ofs.line = {0,0} --The offset of GPU.line/s.
ofs.circle = {0,0,0} --The offset of GPU.circle with l as false (x,y,r).
ofs.circle_line = {0,0,0} --The offset of GPU.circle with l as true (x,y,r).
ofs.ellipse = {0,0,0,0} --The offset of GPU.circle with l as false (x,y,rx,ry).
ofs.ellipse_line = {0,0,0,0} --The offset of GPU.circle with l as true (x,y,rx,ry).
ofs.rect = {-1,-1} --The offset of GPU.rect with l as false.
ofs.rectSize = {0,0} --The offset of w,h in GPU.rect with l as false.
ofs.rect_line = {0,0} --The offset of GPU.rect with l as true.
ofs.rectSize_line = {-1,-1} --The offset of w,h in GPU.rect with l as false.
ofs.triangle = {0,0} --The offset of each vertices in GPU.triangle with l as false.
ofs.triangle_line = {0,0} --The offset of each vertices in GPU.triangle with l as true.
ofs.polygon = {0,0} --The offset of each vertices in GPU.polygon.
ofs.image = {-1,-1}
ofs.quad = {-1,-1}]]
local ofs = {}
local _Canvas
local imgdata
local function canvas(w,h)
love.graphics.setCanvas()
_Canvas = love.graphics.newCanvas(w,h)
love.graphics.setCanvas(_Canvas)
love.graphics.clear(0,0,0,255)
end
local function imagedata()
imgdata = _Canvas:newImageData()
end
love.graphics.setDefaultFilter("nearest","nearest")
love.graphics.setLineStyle("rough") --Set the line style.
love.graphics.setLineJoin("miter") --Set the line join style.
love.graphics.setPointSize(1) --Set the point size to 1px.
love.graphics.setLineWidth(1) --Set the line width to 1px.
love.graphics.setColor(255,255,255,255)
--Screen
ofs.screen = {0,0}
--Point calibration
canvas(8,8)
love.graphics.points(4,4)
imagedata() imgdata:mapPixel(function(x,y, r,g,b,a)
if r == 255 and g == 255 and b == 255 and a == 255 then
ofs.point = {4-x, 4-y}
end
return r,g,b,a
end)
--Print calibration
ofs.print = {0,0} --The offset of GPU.print.
ofs.print_grid = {0,0} --The offset of GPU.print with grid mode.
--Lines calibration
canvas(10,10)
love.graphics.line(4,4, 6,4, 6,6, 4,6, 4,4)
local xpos, ypos = 10,10
imagedata() imgdata:mapPixel(function(x,y, r,g,b,a)
if r == 255 and g == 255 and b == 255 and a == 255 then
if x < xpos then xpos = x end
if y < ypos then ypos = y end
end
return r,g,b,a
end)
ofs.line = {4-xpos,4-ypos}
ofs.line_start = {4-xpos,4-ypos}
--Circle calibration
canvas(30,30)
love.graphics.circle("fill",15,15,19)
local topy, bottomy = 30,1
local leftx, rightx = 30,1
imagedata() imgdata:mapPixel(function(x,y, r,g,b,a)
if r == 255 and g == 255 and b == 255 and a == 255 then
if y < topy then topy = y end
if y > bottomy then bottomy = y end
if x < leftx then leftx = x end
if x > rightx then rightx = x end
end
return r,g,b,a
end)
local cx = (rightx + leftx +1)/2
local cy = (topy + bottomy +1)/2
ofs.circle = {15-cx,15-cy,0}
--Circle line calibration
canvas(30,30)
love.graphics.circle("line",15,15,19)
local topy, bottomy = 30,1
local leftx, rightx = 30,1
imagedata() imgdata:mapPixel(function(x,y, r,g,b,a)
if r == 255 and g == 255 and b == 255 and a == 255 then
if y < topy then topy = y end
if y > bottomy then bottomy = y end
if x < leftx then leftx = x end
if x > rightx then rightx = x end
end
return r,g,b,a
end)
local cx = (rightx + leftx +1)/2
local cy = (topy + bottomy +1)/2
ofs.circle_line = {15-cx,15-cy,0}
--Ellipse calibration
canvas(30,30)
love.graphics.ellipse("fill",15,15,19,19)
local topy, bottomy = 30,1
local leftx, rightx = 30,1
imagedata() imgdata:mapPixel(function(x,y, r,g,b,a)
if r == 255 and g == 255 and b == 255 and a == 255 then
if y < topy then topy = y end
if y > bottomy then bottomy = y end
if x < leftx then leftx = x end
if x > rightx then rightx = x end
end
return r,g,b,a
end)
local cx = (rightx + leftx +1)/2
local cy = (topy + bottomy +1)/2
ofs.ellipse = {15-cx,15-cy,0,0}
--Ellipse line calibration
canvas(30,30)
love.graphics.ellipse("line",15,15,19,19)
local topy, bottomy = 30,1
local leftx, rightx = 30,1
imagedata() imgdata:mapPixel(function(x,y, r,g,b,a)
if r == 255 and g == 255 and b == 255 and a == 255 then
if y < topy then topy = y end
if y > bottomy then bottomy = y end
if x < leftx then leftx = x end
if x > rightx then rightx = x end
end
return r,g,b,a
end)
local cx = (rightx + leftx +1)/2
local cy = (topy + bottomy +1)/2
ofs.ellipse_line = {15-cx,15-cy,0,0}
--Rectangle calibration
canvas(10,10)
love.graphics.rectangle("fill",2,2,6,6)
local topy, bottomy = 10,1
local leftx, rightx = 10,1
imagedata() imgdata:mapPixel(function(x,y, r,g,b,a)
if r == 255 and g == 255 and b == 255 and a == 255 then
if y < topy then topy = y end
if y > bottomy then bottomy = y end
if x < leftx then leftx = x end
if x > rightx then rightx = x end
end
return r,g,b,a
end)
ofs.rect = {2-leftx,2-topy}
ofs.rectSize = {6-(rightx-leftx+1),6-(bottomy-topy+1)}
--Rectangle line calibration
canvas(10,10)
love.graphics.rectangle("line",2,2,6,6)
local topy, bottomy = 10,1
local leftx, rightx = 10,1
imagedata() imgdata:mapPixel(function(x,y, r,g,b,a)
if r == 255 and g == 255 and b == 255 and a == 255 then
if y < topy then topy = y end
if y > bottomy then bottomy = y end
if x < leftx then leftx = x end
if x > rightx then rightx = x end
end
return r,g,b,a
end)
ofs.rect_line = {2-leftx,2-topy}
ofs.rectSize_line = {6-(rightx-leftx+1),6-(bottomy-topy+1)}
--Triangle
ofs.triangle = {0,0} --The offset of each vertices in GPU.triangle with l as false.
ofs.triangle_line = {0,0} --The offset of each vertices in GPU.triangle with l as true.
--Polygone
ofs.polygon = {0,0} --The offset of each vertices in GPU.polygon.
--Image
local id = love.image.newImageData(4,4)
id:mapPixel(function() return 255,255,255,255 end)
id = love.graphics.newImage(id)
canvas(10,10)
love.graphics.draw(id,4,4)
local leftx, topy = 10,10
imagedata() imgdata:mapPixel(function(x,y, r,g,b,a)
if r == 255 and g == 255 and b == 255 and a == 255 then
if x < leftx then leftx = x end
if y < topy then topy = y end
end
return r,g,b,a
end)
ofs.image = {4-leftx,4-topy}
--Quad
ofs.quad = ofs.image
love.graphics.setCanvas()
return ofs
|
--This file is responsible of generating all the drawing offsets
--It will works by testing on canvases, invisibly to the user.
--[[local ofs = {} --Offsets table.
ofs.point = {0,0} --The offset of GPU.point/s.
ofs.print = {-1,-1} --The offset of GPU.print.
ofs.print_grid = {-1,-1} --The offset of GPU.print with grid mode.
ofs.line_start = {0,0} --The offset of the first coord of GPU.line/s.
ofs.line = {0,0} --The offset of GPU.line/s.
ofs.circle = {0,0,0} --The offset of GPU.circle with l as false (x,y,r).
ofs.circle_line = {0,0,0} --The offset of GPU.circle with l as true (x,y,r).
ofs.ellipse = {0,0,0,0} --The offset of GPU.circle with l as false (x,y,rx,ry).
ofs.ellipse_line = {0,0,0,0} --The offset of GPU.circle with l as true (x,y,rx,ry).
ofs.rect = {-1,-1} --The offset of GPU.rect with l as false.
ofs.rectSize = {0,0} --The offset of w,h in GPU.rect with l as false.
ofs.rect_line = {0,0} --The offset of GPU.rect with l as true.
ofs.rectSize_line = {-1,-1} --The offset of w,h in GPU.rect with l as false.
ofs.triangle = {0,0} --The offset of each vertices in GPU.triangle with l as false.
ofs.triangle_line = {0,0} --The offset of each vertices in GPU.triangle with l as true.
ofs.polygon = {0,0} --The offset of each vertices in GPU.polygon.
ofs.image = {-1,-1}
ofs.quad = {-1,-1}]]
--Wrapper for setColor to use 0-255 values
local function setColor(r,g,b,a)
local r,g,b,a = r,g,b,a
if type(r) == "table" then
r,g,b,a = unpack(r)
end
if r then r = r/255 end
if g then g = g/255 end
if b then b = b/255 end
if a then a = a/255 end
love.graphics.setColor(r, g, b, a)
end
local ofs = {}
local _Canvas
local imgdata
local function canvas(w,h)
love.graphics.setCanvas()
_Canvas = love.graphics.newCanvas(w,h)
love.graphics.setCanvas(_Canvas)
love.graphics.clear(0,0,0,1)
end
local function imagedata()
imgdata = _Canvas:newImageData()
end
love.graphics.setDefaultFilter("nearest","nearest")
love.graphics.setLineStyle("rough") --Set the line style.
love.graphics.setLineJoin("miter") --Set the line join style.
love.graphics.setPointSize(1) --Set the point size to 1px.
love.graphics.setLineWidth(1) --Set the line width to 1px.
love.graphics.setColor(1,1,1,1)
--Screen
ofs.screen = {0,0}
--Point calibration
canvas(8,8)
love.graphics.points(4,4)
imagedata() imgdata:mapPixel(function(x,y, r,g,b,a)
if r == 1 and g == 1 and b == 1 and a == 1 then
ofs.point = {4-x, 4-y}
end
return r,g,b,a
end)
--Print calibration
ofs.print = {0,0} --The offset of GPU.print.
ofs.print_grid = {0,0} --The offset of GPU.print with grid mode.
--Lines calibration
canvas(10,10)
love.graphics.line(4,4, 6,4, 6,6, 4,6, 4,4)
local xpos, ypos = 10,10
imagedata() imgdata:mapPixel(function(x,y, r,g,b,a)
if r == 1 and g == 1 and b == 1 and a == 1 then
if x < xpos then xpos = x end
if y < ypos then ypos = y end
end
return r,g,b,a
end)
ofs.line = {4-xpos,4-ypos}
ofs.line_start = {4-xpos,4-ypos}
--Circle calibration
canvas(30,30)
love.graphics.circle("fill",15,15,19)
local topy, bottomy = 30,1
local leftx, rightx = 30,1
imagedata() imgdata:mapPixel(function(x,y, r,g,b,a)
if r == 1 and g == 1 and b == 1 and a == 1 then
if y < topy then topy = y end
if y > bottomy then bottomy = y end
if x < leftx then leftx = x end
if x > rightx then rightx = x end
end
return r,g,b,a
end)
local cx = (rightx + leftx +1)/2
local cy = (topy + bottomy +1)/2
ofs.circle = {15-cx,15-cy,0}
--Circle line calibration
canvas(30,30)
love.graphics.circle("line",15,15,19)
local topy, bottomy = 30,1
local leftx, rightx = 30,1
imagedata() imgdata:mapPixel(function(x,y, r,g,b,a)
if r == 1 and g == 1 and b == 1 and a == 1 then
if y < topy then topy = y end
if y > bottomy then bottomy = y end
if x < leftx then leftx = x end
if x > rightx then rightx = x end
end
return r,g,b,a
end)
local cx = (rightx + leftx +1)/2
local cy = (topy + bottomy +1)/2
ofs.circle_line = {15-cx,15-cy,0}
--Ellipse calibration
canvas(30,30)
love.graphics.ellipse("fill",15,15,19,19)
local topy, bottomy = 30,1
local leftx, rightx = 30,1
imagedata() imgdata:mapPixel(function(x,y, r,g,b,a)
if r == 1 and g == 1 and b == 1 and a == 1 then
if y < topy then topy = y end
if y > bottomy then bottomy = y end
if x < leftx then leftx = x end
if x > rightx then rightx = x end
end
return r,g,b,a
end)
local cx = (rightx + leftx +1)/2
local cy = (topy + bottomy +1)/2
ofs.ellipse = {15-cx,15-cy,0,0}
--Ellipse line calibration
canvas(30,30)
love.graphics.ellipse("line",15,15,19,19)
local topy, bottomy = 30,1
local leftx, rightx = 30,1
imagedata() imgdata:mapPixel(function(x,y, r,g,b,a)
if r == 1 and g == 1 and b == 1 and a == 1 then
if y < topy then topy = y end
if y > bottomy then bottomy = y end
if x < leftx then leftx = x end
if x > rightx then rightx = x end
end
return r,g,b,a
end)
local cx = (rightx + leftx +1)/2
local cy = (topy + bottomy +1)/2
ofs.ellipse_line = {15-cx,15-cy,0,0}
--Rectangle calibration
canvas(10,10)
love.graphics.rectangle("fill",2,2,6,6)
local topy, bottomy = 10,1
local leftx, rightx = 10,1
imagedata() imgdata:mapPixel(function(x,y, r,g,b,a)
if r == 1 and g == 1 and b == 1 and a == 1 then
if y < topy then topy = y end
if y > bottomy then bottomy = y end
if x < leftx then leftx = x end
if x > rightx then rightx = x end
end
return r,g,b,a
end)
ofs.rect = {2-leftx,2-topy}
ofs.rectSize = {6-(rightx-leftx+1),6-(bottomy-topy+1)}
--Rectangle line calibration
canvas(10,10)
love.graphics.rectangle("line",2,2,6,6)
local topy, bottomy = 10,1
local leftx, rightx = 10,1
imagedata() imgdata:mapPixel(function(x,y, r,g,b,a)
if r == 1 and g == 1 and b == 1 and a == 1 then
if y < topy then topy = y end
if y > bottomy then bottomy = y end
if x < leftx then leftx = x end
if x > rightx then rightx = x end
end
return r,g,b,a
end)
ofs.rect_line = {2-leftx,2-topy}
ofs.rectSize_line = {6-(rightx-leftx+1),6-(bottomy-topy+1)}
--Triangle
ofs.triangle = {0,0} --The offset of each vertices in GPU.triangle with l as false.
ofs.triangle_line = {0,0} --The offset of each vertices in GPU.triangle with l as true.
--Polygone
ofs.polygon = {0,0} --The offset of each vertices in GPU.polygon.
--Image
local id = love.image.newImageData(4,4)
id:mapPixel(function() return 1,1,1,1 end)
id = love.graphics.newImage(id)
canvas(10,10)
love.graphics.draw(id,4,4)
local leftx, topy = 10,10
imagedata() imgdata:mapPixel(function(x,y, r,g,b,a)
if r == 1 and g == 1 and b == 1 and a == 1 then
if x < leftx then leftx = x end
if y < topy then topy = y end
end
return r,g,b,a
end)
ofs.image = {4-leftx,4-topy}
--Quad
ofs.quad = ofs.image
love.graphics.setCanvas()
return ofs
|
Color values fix calibrate.lua
|
Color values fix calibrate.lua
Former-commit-id: 659a057d9fd97905df0ed132163f2fe72edf423c
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
faf2ece79d5e8f4c79c0c57d81cc7b1136fda425
|
baraza.lua
|
baraza.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 item_type == "labelen" and (downloaded[url] ~= true or addedtolist[url] ~= true) then
if string.match(url, item_value) or 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
local function check(url, origurl)
if (downloaded[url] ~= true and addedtolist[url] ~= true) 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 item_type == "labelen" then
if string.match(url, item_value) then
html = read_file(file)
for newurl in string.gmatch(html, '"(https?://[^"]+)"') do
if string.match(newurl, item_value) then
check(newurl)
end
end
for newurl in string.gmatch(html, '"(/[^"]+"') do
if string.match(newurl, item_value) then
check("http://www.google.com"..newurl)
end
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 1")
tries = tries + 1
if tries >= 15 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 >= 10 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
-- We're okay; sleep a bit (if we have to) and continue
-- local sleep_time = 0.5 * (math.random(75, 100) / 100.0)
local sleep_time = 0
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
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 = {}
local ids = {}
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 item_type == "labelen" and (downloaded[url] ~= true or addedtolist[url] ~= true) then
if (string.match(url, item_value) or html == 0) and not (string.match(url, "accounts%.google%.com") or string.match(url, "google%.com/accounts/") or string.match(url, "loginredirect%?")) 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
local function check(url, origurl)
if (downloaded[url] ~= true and addedtolist[url] ~= true) and not (string.match(url, "accounts%.google%.com") or string.match(url, "google%.com/accounts/") or string.match(url, "loginredirect%?")) 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
if string.match(url, "/thread%?tid=[a-z0-9]+") then
if ids[string.match(url, "/thread%?tid=([a-z0-9]+)")] ~= true then
ids[string.match(url, "/thread%?tid=([a-z0-9]+)")] = true
check("http://www.google.com/baraza/en/thread?tid="..string.match(url, "/thread%?tid=([a-z0-9]+)"))
end
end
end
end
if not ids[item_value] == true then
ids[item_value] = true
end
if item_type == "labelen" then
for id in string.gmatch(url, "=([a-z0-9]+)") do
if ids[id] == true then
html = read_file(file)
for newurl in string.gmatch(html, '"(https?://[^"]+)"') do
if string.match(newurl, item_value) or string.match(newurl, id) then
check(newurl)
end
end
for newurl in string.gmatch(html, '"(/[^"]+)"') do
if string.match(newurl, item_value) or string.match(newurl, id) then
check("http://www.google.com"..newurl)
end
end
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 1")
tries = tries + 1
if tries >= 15 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 >= 10 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
-- We're okay; sleep a bit (if we have to) and continue
-- local sleep_time = 0.5 * (math.random(75, 100) / 100.0)
local sleep_time = 0
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
baraza.lua: fixes and additions
|
baraza.lua: fixes and additions
|
Lua
|
unlicense
|
ArchiveTeam/baraza-grab,ArchiveTeam/baraza-grab
|
2d6598ef14b231369d1e7c73aaa5f18504a38583
|
src/Source.lua
|
src/Source.lua
|
local system = require 'system'
local Source = {}
function Source:new(o)
local o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
local GitSource = Source:new()
local HgSource = Source:new()
local RepoSource = Source:new()
-- Source
function Source:is_scm()
return self.type == 'git' or self.type == 'hg' or self.type == 'repo'
end
function Source:basename(filename)
local name = string.match(filename, '^.*/(.+)') or filename
local exts = { '%.git', '%.tar', '%.tgz', '%.txz', '%.tbz2',
'%.zip', '%.rar', ''
}
for _, ext in ipairs(exts) do
local match = string.match(name, '^([%w_.-]+)'..ext)
if match then
return match
end
end
end
function Source:create(source)
local source = source or {}
if source.type == 'git' then
source = GitSource:new(source)
elseif source.type == 'hg' then
source = HgSource:new(source)
elseif source.type == 'repo' then
source = RepoSource:new(source)
elseif source.type == 'dist' then
source.location = '$jagen_dist_dir/'..source.location
source = Source:new(source)
else
source = Source:new(source)
end
if source.location and source.type ~= 'curl' then
local dir = source:is_scm() and '$jagen_src_dir' or '$pkg_work_dir'
local basename = source:basename(source.location)
source.path = system.mkpath(dir, source.path or basename)
end
return source
end
-- GitSource
function GitSource:new(o)
local source = Source.new(GitSource, o)
source.branch = source.branch or 'master'
return source
end
function GitSource:exec(...)
return system.exec('git', '-C', assert(self.path), ...)
end
function GitSource:popen(...)
return system.popen('git', '-C', assert(self.path), ...):read()
end
function GitSource:head()
return self:popen('rev-parse', 'HEAD')
end
function GitSource:dirty()
return self:popen('status', '--porcelain')
end
function GitSource:clean()
return self:exec('checkout', 'HEAD', '.') and self:exec('clean', '-fxd')
end
function GitSource:update()
local branch = assert(self.branch)
local cmd = { 'fetch', '--prune', '--no-tags', 'origin',
string.format('+refs/heads/%s:refs/remotes/origin/%s', branch, branch)
}
return self:exec(unpack(cmd))
end
function GitSource:_is_branch(pattern)
local branch = self:popen('branch', '-a', '--list', pattern)
local exists, active = false, false
if branch and #branch > 0 then
exists = true
active = string.sub(branch, 1, 1) == '*'
end
return exists, active
end
function GitSource:_checkout()
local branch = assert(self.branch)
local exists, active = self:_is_branch(branch)
if active then
return true
elseif exists then
return self:exec('checkout', branch)
else
local start_point = 'origin/'..branch
exists = self:_is_branch(start_point)
if exists then
local add = { 'remote', 'set-branches', 'origin', branch }
local checkout = { 'checkout', '-b', branch, start_point }
return self:exec(unpack(add)) and self:exec(unpack(checkout))
else
jagen.error("could not find branch '%s' in local repository", branch)
return false
end
end
end
function GitSource:_merge()
local branch = assert(self.branch)
local cmd = { 'merge', '--ff-only', string.format('origin/%s', branch) }
return self:exec(unpack(cmd))
end
function GitSource:switch()
return self:_checkout() and self:_merge()
end
function GitSource:clone()
return system.exec('git', 'clone', '--branch', assert(self.branch),
'--depth', 1, assert(self.location), assert(self.path))
end
-- HgSource
function HgSource:new(o)
local source = Source.new(HgSource, o)
source.branch = source.branch or 'default'
return source
end
function HgSource:exec(...)
return system.exec('hg', '-R', assert(self.path), ...)
end
function HgSource:popen(...)
return system.popen('hg', '-R', assert(self.path), ...):read()
end
function HgSource:_update()
local pull = { 'pull', '-r', assert(self.branch) }
local update = { 'update', '-r', assert(self.branch) }
return self:exec(unpack(pull)) and self:exec(unpack(update))
end
function HgSource:head()
return self:popen('id', '-i')
end
function HgSource:dirty()
return self:popen('status')
end
function HgSource:clean()
return self:exec('update', '-C', assert(self.branch)) and
self:exec('purge', '--all')
end
function HgSource:update()
end
function HgSource:switch()
end
function HgSource:clone()
return system.exec('hg', 'clone', '-r', assert(self.branch),
assert(self.location), assert(self.path))
end
-- RepoSource
function RepoSource:new(o)
local source = Source.new(RepoSource, o)
source.jobs = jagen.nproc * 2
return source
end
function RepoSource:_exec(...)
local cmd = { 'cd', '"'..assert(self.path)..'"', '&&', 'repo', ... }
return system.exec(unpack(cmd))
end
function RepoSource:_popen(...)
local cmd = { 'cd', '"'..assert(self.path)..'"', '&&', 'repo', ... }
return system.popen(unpack(cmd))
end
function RepoSource:_load_projects(...)
local o = {}
local list = self:popen('list', ...)
while true do
local line = list:read()
if not line then break end
local path, name = string.match(line, "(.+)%s:%s(.+)")
if name then
o[name] = path
end
end
return o
end
function RepoSource:_clone()
local mkdir = { 'mkdir -p "'..self.path..'"' }
local init = { 'init', '-u', assert(self.location),
'-b', assert(self.branch), '-p', 'linux', '--depth', 1
}
return system.exec(unpack(mkdir)) and self:exec(unpack(init)) and self:update()
end
function RepoSource:head()
return self:popen('status', '-j', 1, '--orphans'):read('*all')
end
function RepoSource:dirty()
return false
end
function RepoSource:clean()
local projects = self:load_projects()
local function is_empty(path)
return system.popen('cd', '"'..path..'"', '&&', 'echo', '*'):read() == '*'
end
for n, p in pairs(projects) do
local path = system.mkpath(self.path, p)
if not is_empty(path) then
if not system.exec('git', '-C', path, 'checkout', 'HEAD', '.') then
return false
end
if not system.exec('git', '-C', path, 'clean', '-fxd') then
return false
end
end
end
return true
end
function RepoSource:update()
local cmd = { 'sync', '-j', self.jobs, '--current-branch', '--no-tags',
'--optimized-fetch'
}
return self:exec(unpack(cmd))
end
function RepoSource:switch()
end
return Source
|
local system = require 'system'
local Source = {}
function Source:new(o)
local o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
local GitSource = Source:new()
local HgSource = Source:new()
local RepoSource = Source:new()
-- Source
function Source:is_scm()
return self.type == 'git' or self.type == 'hg' or self.type == 'repo'
end
function Source:basename(filename)
local name = string.match(filename, '^.*/(.+)') or filename
local exts = { '%.git', '%.tar', '%.tgz', '%.txz', '%.tbz2',
'%.zip', '%.rar', ''
}
for _, ext in ipairs(exts) do
local match = string.match(name, '^([%w_.-]+)'..ext)
if match then
return match
end
end
end
function Source:create(source)
local source = source or {}
if source.type == 'git' then
source = GitSource:new(source)
elseif source.type == 'hg' then
source = HgSource:new(source)
elseif source.type == 'repo' then
source = RepoSource:new(source)
elseif source.type == 'dist' then
source.location = '$jagen_dist_dir/'..source.location
source = Source:new(source)
else
source = Source:new(source)
end
if source.location and source.type ~= 'curl' then
local dir = source:is_scm() and '$jagen_src_dir' or '$pkg_work_dir'
local basename = source:basename(source.location)
source.path = system.mkpath(dir, source.path or basename)
end
return source
end
-- GitSource
function GitSource:new(o)
local source = Source.new(GitSource, o)
source.branch = source.branch or 'master'
return source
end
function GitSource:exec(...)
return system.exec('git', '-C', assert(self.path), ...)
end
function GitSource:popen(...)
return system.popen('git', '-C', assert(self.path), ...):read()
end
function GitSource:head()
return self:popen('rev-parse', 'HEAD')
end
function GitSource:dirty()
return self:popen('status', '--porcelain')
end
function GitSource:clean()
return self:exec('checkout', 'HEAD', '.') and self:exec('clean', '-fxd')
end
function GitSource:update()
local branch = assert(self.branch)
local cmd = { 'fetch', '--prune', '--no-tags', 'origin',
string.format('+refs/heads/%s:refs/remotes/origin/%s', branch, branch)
}
return self:exec(unpack(cmd))
end
function GitSource:_is_branch(pattern)
local branch = self:popen('branch', '-a', '--list', pattern)
local exists, active = false, false
if branch and #branch > 0 then
exists = true
active = string.sub(branch, 1, 1) == '*'
end
return exists, active
end
function GitSource:_checkout()
local branch = assert(self.branch)
local exists, active = self:_is_branch(branch)
if active then
return true
elseif exists then
return self:exec('checkout', branch)
else
local start_point = 'origin/'..branch
exists = self:_is_branch(start_point)
if exists then
local add = { 'remote', 'set-branches', 'origin', branch }
local checkout = { 'checkout', '-b', branch, start_point }
return self:exec(unpack(add)) and self:exec(unpack(checkout))
else
jagen.error("could not find branch '%s' in local repository", branch)
return false
end
end
end
function GitSource:_merge()
local branch = assert(self.branch)
local cmd = { 'merge', '--ff-only', string.format('origin/%s', branch) }
return self:exec(unpack(cmd))
end
function GitSource:switch()
return self:_checkout() and self:_merge()
end
function GitSource:clone()
return system.exec('git', 'clone', '--branch', assert(self.branch),
'--depth', 1, assert(self.location), assert(self.path))
end
-- HgSource
function HgSource:new(o)
local source = Source.new(HgSource, o)
source.branch = source.branch or 'default'
return source
end
function HgSource:exec(...)
return system.exec('hg', '-R', assert(self.path), ...)
end
function HgSource:popen(...)
return system.popen('hg', '-R', assert(self.path), ...):read()
end
function HgSource:head()
return self:popen('id', '-i')
end
function HgSource:dirty()
return self:popen('status')
end
function HgSource:clean()
return self:exec('update', '-C', assert(self.branch)) and
self:exec('purge', '--all')
end
function HgSource:update()
local cmd = { 'pull', '-r', assert(self.branch) }
return self:exec(unpack(cmd))
end
function HgSource:switch()
local cmd = { 'update', '-r', assert(self.branch) }
return self:exec(unpack(cmd))
end
function HgSource:clone()
return system.exec('hg', 'clone', '-r', assert(self.branch),
assert(self.location), assert(self.path))
end
-- RepoSource
function RepoSource:new(o)
local source = Source.new(RepoSource, o)
source.jobs = jagen.nproc * 2
return source
end
function RepoSource:_exec(...)
local cmd = { 'cd', '"'..assert(self.path)..'"', '&&', 'repo', ... }
return system.exec(unpack(cmd))
end
function RepoSource:_popen(...)
local cmd = { 'cd', '"'..assert(self.path)..'"', '&&', 'repo', ... }
return system.popen(unpack(cmd))
end
function RepoSource:_load_projects(...)
local o = {}
local list = self:popen('list', ...)
while true do
local line = list:read()
if not line then break end
local path, name = string.match(line, "(.+)%s:%s(.+)")
if name then
o[name] = path
end
end
return o
end
function RepoSource:_clone()
local mkdir = { 'mkdir -p "'..self.path..'"' }
local init = { 'init', '-u', assert(self.location),
'-b', assert(self.branch), '-p', 'linux', '--depth', 1
}
return system.exec(unpack(mkdir)) and self:exec(unpack(init)) and self:update()
end
function RepoSource:head()
return self:popen('status', '-j', 1, '--orphans'):read('*all')
end
function RepoSource:dirty()
return false
end
function RepoSource:clean()
local projects = self:load_projects()
local function is_empty(path)
return system.popen('cd', '"'..path..'"', '&&', 'echo', '*'):read() == '*'
end
for n, p in pairs(projects) do
local path = system.mkpath(self.path, p)
if not is_empty(path) then
if not system.exec('git', '-C', path, 'checkout', 'HEAD', '.') then
return false
end
if not system.exec('git', '-C', path, 'clean', '-fxd') then
return false
end
end
end
return true
end
function RepoSource:update()
local cmd = { 'sync', '-j', self.jobs, '--current-branch', '--no-tags',
'--optimized-fetch'
}
return self:exec(unpack(cmd))
end
function RepoSource:switch()
end
return Source
|
Fix HgSource update and switch
|
Fix HgSource update and switch
|
Lua
|
mit
|
bazurbat/jagen
|
bb54d580dc1f8cbe01c43de6a2fe4a89c9b2f349
|
tests/test.lua
|
tests/test.lua
|
--[[--------------------------------------------------------------------------
LGI core testsuite runner.
Copyright (c) 2010, 2011 Pavel Holejsovsky
Licensed under the MIT license:
http://www.opensource.org/licenses/mit-license.php
--]]--------------------------------------------------------------------------
-- Available groups.
local groups = {}
-- Testing infrastructure, tests are grouped in testgroup instances.
testsuite = {}
testsuite.group = {}
testsuite.group.__index = testsuite.group
-- Creates new named testgroup.
function testsuite.group.new(name)
local group = setmetatable({ name = name,
results = { total = 0, failed = 0 } },
testsuite.group)
groups[#groups + 1] = name
groups[name] = group
return group
end
-- Adds new test.
function testsuite.group:__newindex(name, func)
assert(not self[name], "test already exists in the group")
rawset(self, name, func)
rawset(self, #self + 1, name)
end
-- Runs specified test(s), either by numeric id or by regexp mask.
function testsuite.group:run(id)
local function runfunc(num)
self.results.total = self.results.total + 1
if testsuite.verbose then
io.write(('%-8s:%3d:%-35s'):format(self.name, num, self[num]))
end
local ok, msg
local func = self[self[num]]
if self.debug then func() ok = true else
ok, msg = pcall(func)
end
collectgarbage()
if not ok then
self.results.failed = self.results.failed + 1
if not testsuite.verbose then
io.write(('%-8s:%3d:%-35s'):format(self.name, num, self[num]))
end
io.write('FAIL\n ' .. tostring(msg) .. '\n')
return
end
if testsuite.verbose then
io.write('PASS\n')
end
end
id = id or ''
self.results.total = 0
self.results.failed = 0
if type(id) == 'number' then
runfunc(id)
else
for i = 1, #self do
if self[i] ~= 'debug' and self[i]:match(id) then runfunc(i) end
end
if (self.results.failed == 0) then
io.write(('%-8s: all %d tests passed.\n'):format(
self.name, self.results.total))
else
io.write(('%-8s: FAILED %d of %d tests\n'):format(
self.name, self.results.failed, self.results.total))
end
end
end
-- Fails given test with error, number indicates how many functions on
-- the stack should be skipped when reporting error location.
function testsuite.fail(msg, skip)
error(msg or 'failure', (skip or 1) + 1)
end
function testsuite.check(cond, msg, skip)
if not cond then testsuite.fail(msg, (skip or 1) + 1) end
end
-- Helper, checks that given value has requested type and value.
function testsuite.checkv(val, exp, exptype)
if exptype then
testsuite.check(type(val) == exptype,
string.format("got type `%s', expected `%s'",
type(val), exptype), 2)
end
testsuite.check(val == exp,
string.format("got value `%s', expected `%s'",
tostring(val), tostring(exp)), 2)
end
-- Check for debug mode.
if tests_debug or package.loaded.debugger then
-- Make logs verbose (do not mute DEBUG level).
testsuite.verbose = true
require('lgi').log.DEBUG = 'verbose'
for _, name in ipairs(groups) do
groups[name].debug = true
_G[name] = groups[name]
end
end
-- Load all known test source files.
local testpath = arg[0]:sub(1, arg[0]:find('[^%/\\]+$') - 1):gsub('[/\\]$', '')
for _, sourcefile in ipairs {
'gireg.lua',
'gobject.lua',
'variant.lua'
} do
dofile(testpath .. '/' .. sourcefile)
end
-- Cmdline runner.
local failed = false
if #arg == 0 then
-- Run everything.
for _, group in ipairs(groups) do
groups[group]:run()
failed = failed or groups[group].results.failed > 0
end
else
-- Run just those which pass the mask.
for _, mask in ipairs(arg) do
local group, groupmask = mask:match('^(.-):(.+)$')
if not group or not groups[group] then
io.write(("No test group for mask `%s' found.\n"):format(mask))
return 2
end
groups[group]:run(groupmask)
failed = failed or groups[group].results.failed > 0
end
end
return not failed and 0 or 1
|
--[[--------------------------------------------------------------------------
LGI core testsuite runner.
Copyright (c) 2010, 2011 Pavel Holejsovsky
Licensed under the MIT license:
http://www.opensource.org/licenses/mit-license.php
--]]--------------------------------------------------------------------------
-- Available groups.
local groups = {}
-- Testing infrastructure, tests are grouped in testgroup instances.
testsuite = {}
testsuite.group = {}
testsuite.group.__index = testsuite.group
-- Creates new named testgroup.
function testsuite.group.new(name)
local group = setmetatable({ name = name,
results = { total = 0, failed = 0 } },
testsuite.group)
groups[#groups + 1] = name
groups[name] = group
return group
end
-- Adds new test.
function testsuite.group:__newindex(name, func)
assert(not self[name], "test already exists in the group")
rawset(self, name, func)
rawset(self, #self + 1, name)
end
-- Runs specified test(s), either by numeric id or by regexp mask.
function testsuite.group:run(id)
local function runfunc(num)
self.results.total = self.results.total + 1
if testsuite.verbose then
io.write(('%-8s:%3d:%-35s'):format(self.name, num, self[num]))
end
local ok, msg
local func = self[self[num]]
if self.debug then func() ok = true else
ok, msg = pcall(func)
end
collectgarbage()
if not ok then
self.results.failed = self.results.failed + 1
if not testsuite.verbose then
io.write(('%-8s:%3d:%-35s'):format(self.name, num, self[num]))
end
io.write('FAIL\n ' .. tostring(msg) .. '\n')
return
end
if testsuite.verbose then
io.write('PASS\n')
end
end
id = id or ''
self.results.total = 0
self.results.failed = 0
if type(id) == 'number' then
runfunc(id)
else
for i = 1, #self do
if self[i] ~= 'debug' and self[i]:match(id) then runfunc(i) end
end
if (self.results.failed == 0) then
io.write(('%-8s: all %d tests passed.\n'):format(
self.name, self.results.total))
else
io.write(('%-8s: FAILED %d of %d tests\n'):format(
self.name, self.results.failed, self.results.total))
end
end
end
-- Fails given test with error, number indicates how many functions on
-- the stack should be skipped when reporting error location.
function testsuite.fail(msg, skip)
error(msg or 'failure', (skip or 1) + 1)
end
function testsuite.check(cond, msg, skip)
if not cond then testsuite.fail(msg, (skip or 1) + 1) end
end
-- Helper, checks that given value has requested type and value.
function testsuite.checkv(val, exp, exptype)
if exptype then
testsuite.check(type(val) == exptype,
string.format("got type `%s', expected `%s'",
type(val), exptype), 2)
end
testsuite.check(val == exp,
string.format("got value `%s', expected `%s'",
tostring(val), tostring(exp)), 2)
end
-- Load all known test source files.
local testpath = arg[0]:sub(1, arg[0]:find('[^%/\\]+$') - 1):gsub('[/\\]$', '')
for _, sourcefile in ipairs {
'gireg.lua',
'gobject.lua',
'variant.lua'
} do
dofile(testpath .. '/' .. sourcefile)
end
-- Check for debug mode.
if tests_debug or package.loaded.debugger then
-- Make logs verbose (do not mute DEBUG level).
testsuite.verbose = true
require('lgi').log.DEBUG = 'verbose'
for _, name in ipairs(groups) do
groups[name].debug = true
_G[name] = groups[name]
end
end
-- Cmdline runner.
local failed = false
if #arg == 0 then
-- Run everything.
for _, group in ipairs(groups) do
groups[group]:run()
failed = failed or groups[group].results.failed > 0
end
else
-- Run just those which pass the mask.
for _, mask in ipairs(arg) do
local group, groupmask = mask:match('^(.-):(.+)$')
if not group or not groups[group] then
io.write(("No test group for mask `%s' found.\n"):format(mask))
return 2
end
groups[group]:run(groupmask)
failed = failed or groups[group].results.failed > 0
end
end
return not failed and 0 or 1
|
Fix testsuite runner in debug mode - break when debugger is detected.
|
Fix testsuite runner in debug mode - break when debugger is detected.
Propagate .debug flag into groups only after the groups are actually created
and loaded.
|
Lua
|
mit
|
pavouk/lgi,zevv/lgi,psychon/lgi
|
746452873839752fcd092b9406f3f5449cf02f24
|
heka/sandbox/filters/telemetry_latency.lua
|
heka/sandbox/filters/telemetry_latency.lua
|
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
--[[
1) How many days do we need to look back for k% of active profiles to be up-to-date?
Each active profile is associated to the date in which we last received a submission
for it on our servers. Periodically, we compute for all profiles the difference
between the current date and the date of reception and finally plot a histogram
of the differences expressed in number of days.
2) How may days do we need to look back to observe k% of active profile activity?
Each active profile is associated with its last activity date. Periodically, we compute
for all active profiles the difference from the last activity date to the current date
and finally plot a histogram of the differences expressed in number of days.
3) What’s the delay in hours between the start of a session activity for an active profile
and the time we receive the submission? When we receive a new submission for an active
profile we compute the delay from the start of the submission activity to the time we
received the submission on our servers. Periodically, we plot a histogram of the latencies
expressed in hours.
Note that:
- As timeseries of histograms or heatmaps are not supported by the Heka plotting
facilities, only the median and some other percentiles are being output.
- An active profile is one who has used the browser in the last six weeks (42 days)
*Example Heka Configuration*
.. code-block:: ini
[TelemetryLatency]
type = "SandboxFilter"
filename = "lua_filters/telemetry_latency.lua"
message_matcher = "Type == 'telemetry' && Fields[docType] == 'main'"
ticker_interval = 60
preserve_data = false
--]]
require "circular_buffer"
require "table"
require "string"
require "math"
require "os"
local LOST_PROFILE_THRESHOLD = 42 -- https://people.mozilla.org/~bsmedberg/fhr-reporting/#usage
local PING_VERSION = "4"
local NSPERHOUR = 60*60*1e9
local NSPERDAY = 24*NSPERHOUR
local MEDIAN = 1
local PERCENTILE_75 = 2
local PERCENTILE_99 = 3
local seen_by_channel = {}
local seen_history_by_channel = {}
local active_by_channel = {}
local active_history_by_channel = {}
local delay_by_channel = {}
local delay_history_by_channel = {}
local rows = read_config("rows") or 1440
local sec_per_row = read_config("sec_per_row") or 60
local function log(message)
local dbg = {message}
inject_payload("txt", "debug", table.concat(dbg, "\n"))
end
local function get_channel_entry(t, channel)
local entry = t[channel]
if not entry then
entry = {}
t[channel] = entry
end
return entry
end
local function get_history(unit, metric_history_by_channel, channel)
local history = metric_history_by_channel[channel]
if not history then
history = circular_buffer.new(rows, 3, sec_per_row)
history:set_header(MEDIAN, "Median", unit, "none")
history:set_header(PERCENTILE_75, "75th percentile", unit, "none")
history:set_header(PERCENTILE_99, "99th percentile", unit, "none")
metric_history_by_channel[channel] = history
end
return history
end
local function process_client_metric(metric_by_channel, channel, client_id, value)
local metric = get_channel_entry(metric_by_channel, channel)
metric[client_id] = value
end
function process_message ()
local sample_id = read_message("Fields[sampleId]")
local version = read_message("Fields[sourceVersion]")
if version == PING_VERSION and sample_id == 0 then
local ts = read_message("Timestamp")
local channel = read_message("Fields[appUpdateChannel]") or "UNKNOWN"
local client_id = read_message("Fields[clientId]")
local activity_ts = read_message("Fields[creationTimestamp]") -- exists only in new "unified" pings
process_client_metric(seen_by_channel, channel, client_id, ts)
process_client_metric(active_by_channel, channel, client_id, activity_ts)
process_client_metric(delay_by_channel, channel, client_id, ts - activity_ts)
end
return 0
end
local function percentile(sorted_array, p)
return sorted_array[math.ceil(#sorted_array*p/100)]
end
local function timer_event_metric(descr, unit, metric_by_channel, metric_history_by_channel, ns, calc)
for channel, metric in pairs(metric_by_channel) do
local sorted_metric = {}
for k, v in pairs(metric) do
sorted_metric[#sorted_metric + 1] = calc(ns, v)
end
table.sort(sorted_metric)
local median = percentile(sorted_metric, 50)
local perc75 = percentile(sorted_metric, 75)
local perc99 = percentile(sorted_metric, 99)
local history = get_history(unit, metric_history_by_channel, channel)
if median then history:set(ns, MEDIAN, median) end
if perc75 then history:set(ns, PERCENTILE_75, perc75) end
if perc99 then history:set(ns, PERCENTILE_99, perc99) end
inject_payload("cbuf", channel .. " " .. descr, history)
end
end
local function remove_inactive_client(channel, client_id)
seen_by_channel[channel][client_id] = nil
active_by_channel[channel][client_id] = nil
delay_by_channel[channel][client_id] = nil
end
local function remove_inactive_clients(current_ts)
for channel, active in pairs(active_by_channel) do
for client_id, last_active_ts in pairs(active) do
if (current_ts - last_active_ts)/NSPERDAY > LOST_PROFILE_THRESHOLD then
remove_inactive_client(channel, client_id)
end
end
end
end
function timer_event(ns)
remove_inactive_clients(ns)
timer_event_metric("up-to-date", "days", seen_by_channel, seen_history_by_channel, ns,
function(ns, v) return math.floor((ns - v)/NSPERDAY) end)
timer_event_metric("active", "days", active_by_channel, active_history_by_channel, ns,
function(ns, v) return math.floor((ns - v)/NSPERDAY) end)
timer_event_metric("delay", "hours", delay_by_channel, delay_history_by_channel, ns,
function(ns, v) return math.floor(v/NSPERHOUR) end)
end
|
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
--[[
1) What’s the delay in hours between the date a ping was created and the time it
was received on our servers? When a new submission for an active profile is received,
the latency between the ping creation date and the reception time is computed.
Periodically, a histogram of the latencies is plot.
2) How many days do we need to look back to see at least one submission for k% of
active profiles? Each active profile is associated to the date for which a submission
was last received on our servers. Periodically, we compute for all profiles the
difference between the current date and the date of reception and finally plot
a histogram of the differences expressed in number of days.
Note that:
- As timeseries of histograms or heatmaps are not supported by the Heka plotting
facilities, only the median and some other percentiles are being output.
- An active profile is one who has used the browser in the last six weeks (42 days)
*Example Heka Configuration*
.. code-block:: ini
[TelemetryLatency]
type = "SandboxFilter"
filename = "lua_filters/telemetry_latency.lua"
message_matcher = "Type == 'telemetry' && Fields[docType] == 'main'"
ticker_interval = 60
preserve_data = false
--]]
require "circular_buffer"
require "table"
require "string"
require "math"
require "os"
local LOST_PROFILE_THRESHOLD = 42 -- https://people.mozilla.org/~bsmedberg/fhr-reporting/#usage
local PING_VERSION = "4"
local NSPERHOUR = 60*60*1e9
local NSPERDAY = 24*NSPERHOUR
local MEDIAN = 1
local PERCENTILE_75 = 2
local PERCENTILE_99 = 3
local seen_by_channel = {}
local seen_history_by_channel = {}
local creation_delay_by_channel = {}
local creation_delay_history_by_channel = {}
local rows = read_config("rows") or 1440
local sec_per_row = read_config("sec_per_row") or 60
local function log(message)
local dbg = {message}
inject_payload("txt", "debug", table.concat(dbg, "\n"))
end
local function get_channel_entry(t, channel)
local entry = t[channel]
if not entry then
entry = {}
t[channel] = entry
end
return entry
end
local function get_history(unit, metric_history_by_channel, channel)
local history = metric_history_by_channel[channel]
if not history then
history = circular_buffer.new(rows, 3, sec_per_row)
history:set_header(MEDIAN, "Median", unit, "none")
history:set_header(PERCENTILE_75, "75th percentile", unit, "none")
history:set_header(PERCENTILE_99, "99th percentile", unit, "none")
metric_history_by_channel[channel] = history
end
return history
end
local function process_client_metric(metric_by_channel, channel, client_id, value)
local metric = get_channel_entry(metric_by_channel, channel)
metric[client_id] = value
end
function process_message ()
local sample_id = read_message("Fields[sampleId]")
local version = read_message("Fields[sourceVersion]")
if version == PING_VERSION and sample_id == 0 then
local ts = read_message("Timestamp")
local channel = read_message("Fields[appUpdateChannel]") or "UNKNOWN"
local client_id = read_message("Fields[clientId]")
local creation_ts = read_message("Fields[creationTimestamp]") -- exists only in new "unified" pings
process_client_metric(seen_by_channel, channel, client_id, ts)
process_client_metric(creation_delay_by_channel, channel, client_id, ts - creation_ts)
end
return 0
end
local function percentile(sorted_array, p)
return sorted_array[math.ceil(#sorted_array*p/100)]
end
local function timer_event_metric(descr, unit, metric_by_channel, metric_history_by_channel, ns, calc)
for channel, metric in pairs(metric_by_channel) do
local sorted_metric = {}
for k, v in pairs(metric) do
sorted_metric[#sorted_metric + 1] = calc(ns, v)
end
table.sort(sorted_metric)
local median = percentile(sorted_metric, 50)
local perc75 = percentile(sorted_metric, 75)
local perc99 = percentile(sorted_metric, 99)
local history = get_history(unit, metric_history_by_channel, channel)
if median then history:set(ns, MEDIAN, median) end
if perc75 then history:set(ns, PERCENTILE_75, perc75) end
if perc99 then history:set(ns, PERCENTILE_99, perc99) end
inject_payload("cbuf", channel .. " " .. descr, history)
end
end
local function remove_inactive_client(channel, client_id)
seen_by_channel[channel][client_id] = nil
creation_delay_by_channel[channel][client_id] = nil
end
local function remove_inactive_clients(current_ts)
for channel, seen in pairs(seen_by_channel) do
for client_id, last_seen_ts in pairs(seen) do
if (current_ts - last_seen_ts)/NSPERDAY > LOST_PROFILE_THRESHOLD then
remove_inactive_client(channel, client_id)
end
end
end
end
function timer_event(ns)
remove_inactive_clients(ns)
timer_event_metric("seen", "days", seen_by_channel, seen_history_by_channel, ns,
function(ns, v) return math.floor((ns - v)/NSPERDAY) end)
timer_event_metric("creation delay", "hours", creation_delay_by_channel, creation_delay_history_by_channel, ns,
function(ns, v) return math.floor(v/NSPERHOUR) end)
end
|
Followed up on comment for Bug 1134669.
|
Followed up on comment for Bug 1134669.
|
Lua
|
mpl-2.0
|
mozilla-services/data-pipeline,whd/data-pipeline,nathwill/data-pipeline,mreid-moz/data-pipeline,sapohl/data-pipeline,whd/data-pipeline,nathwill/data-pipeline,sapohl/data-pipeline,acmiyaguchi/data-pipeline,mreid-moz/data-pipeline,acmiyaguchi/data-pipeline,nathwill/data-pipeline,mozilla-services/data-pipeline,kparlante/data-pipeline,nathwill/data-pipeline,acmiyaguchi/data-pipeline,mreid-moz/data-pipeline,whd/data-pipeline,kparlante/data-pipeline,sapohl/data-pipeline,kparlante/data-pipeline,whd/data-pipeline,mozilla-services/data-pipeline,acmiyaguchi/data-pipeline,kparlante/data-pipeline,sapohl/data-pipeline,mozilla-services/data-pipeline
|
a55ccf980ac9e68cb20499dc74f39b33834ac21b
|
mod_register_redirect/mod_register_redirect.lua
|
mod_register_redirect/mod_register_redirect.lua
|
-- (C) 2010-2011 Marco Cirillo (LW.Org)
-- (C) 2011 Kim Alvefur
--
-- Registration Redirect module for Prosody
--
-- Redirects IP addresses not in the whitelist to a web page or another method to complete the registration.
local st = require "util.stanza"
local cman = configmanager
function reg_redirect(event)
local stanza, origin = event.stanza, event.origin
local ip_wl = module:get_option("registration_whitelist") or { "127.0.0.1" }
local url = module:get_option_string("registration_url", nil)
local inst_text = module:get_option_string("registration_text", nil)
local oob = module:get_option_boolean("registration_oob", true)
local admins_g = cman.get("*", "core", "admins")
local admins_l = cman.get(module:get_host(), "core", "admins")
local no_wl = module:get_option_boolean("no_registration_whitelist", false)
local test_ip = false
if type(admins_g) ~= "table" then admins_g = nil end
if type(admins_l) ~= "table" then admins_l = nil end
-- perform checks to set default responses and sanity checks.
if not inst_text then
if url and oob then
if url:match("^%w+[:].*$") then
if url:match("^(%w+)[:].*$") == "http" or url:match("^(%w+)[:].*$") == "https" then
inst_text = "Please visit "..url.." to register an account on this server."
elseif url:match("^(%w+)[:].*$") == "mailto" then
inst_text = "Please send an e-mail at "..url:match("^%w+[:](.*)$").." to register an account on this server."
elseif url:match("^(%w+)[:].*$") == "xmpp" then
inst_text = "Please contact "..module:get_host().."'s server administrator via xmpp to register an account on this server at: "..url:match("^%w+[:](.*)$")
else
module:log("error", "This module supports only http/https, mailto or xmpp as URL formats.")
module:log("error", "If you want to use personalized instructions without an Out-Of-Band method,")
module:log("error", "specify: register_oob = false; -- in your configuration along your banner string (register_text).")
origin.send(st.error_reply(stanza, "wait", "internal-server-error")) ; return true -- bouncing request.
end
else
module:log("error", "Please check your configuration, the URL you specified is invalid")
origin.send(st.error_reply(stanza, "wait", "internal-server-error")) ; return true -- bouncing request.
end
else
if admins_l then
local ajid; for _,v in ipairs(admins_l) do ajid = v ; break end
inst_text = "Please contact "..module:get_host().."'s server administrator via xmpp to register an account on this server at: "..ajid
else
if admins_g then
local ajid; for _,v in ipairs(admins_g) do ajid = v ; break end
inst_text = "Please contact "..module:get_host().."'s server administrator via xmpp to register an account on this server at: "..ajid
else
module:log("error", "Please be sure to, _at the very least_, configure one server administrator either global or hostwise...")
module:log("error", "if you want to use this module, or read it's configuration wiki at: http://code.google.com/p/prosody-modules/wiki/mod_register_redirect")
origin.send(st.error_reply(stanza, "wait", "internal-server-error")) ; return true -- bouncing request.
end
end
end
elseif inst_text and url and oob then
if not url:match("^%w+[:].*$") then
module:log("error", "Please check your configuration, the URL specified is not valid.")
origin.send(st.error_reply(stanza, "wait", "internal-server-error")) ; return true -- bouncing request.
end
end
if not no_wl then
for i,ip in ipairs(ip_wl) do
if origin.ip == ip then test_ip = true end
break
end
end
-- Prepare replies.
local reply = st.reply(event.stanza)
if oob then
reply:query("jabber:iq:register")
:tag("instructions"):text(inst_text):up()
:tag("x", {xmlns = "jabber:x:oob"})
:tag("url"):text(url);
else
reply:query("jabber:iq:register")
:tag("instructions"):text(inst_text):up()
end
if stanza.attr.type == "get" then
origin.send(reply)
else
origin.send(st.error_reply(stanza, "cancel", "not-authorized"))
end
return true
end
module:hook("stanza/iq/jabber:iq:register:query", reg_redirect, 10)
|
-- (C) 2010-2011 Marco Cirillo (LW.Org)
-- (C) 2011 Kim Alvefur
--
-- Registration Redirect module for Prosody
--
-- Redirects IP addresses not in the whitelist to a web page or another method to complete the registration.
local st = require "util.stanza"
local cman = configmanager
function reg_redirect(event)
local stanza, origin = event.stanza, event.origin
local ip_wl = module:get_option("registration_whitelist") or { "127.0.0.1" }
local url = module:get_option_string("registration_url", nil)
local inst_text = module:get_option_string("registration_text", nil)
local oob = module:get_option_boolean("registration_oob", true)
local admins_g = cman.get("*", "core", "admins")
local admins_l = cman.get(module:get_host(), "core", "admins")
local no_wl = module:get_option_boolean("no_registration_whitelist", false)
local test_ip = false
if type(admins_g) ~= "table" then admins_g = nil end
if type(admins_l) ~= "table" then admins_l = nil end
-- perform checks to set default responses and sanity checks.
if not inst_text then
if url and oob then
if url:match("^%w+[:].*$") then
if url:match("^(%w+)[:].*$") == "http" or url:match("^(%w+)[:].*$") == "https" then
inst_text = "Please visit "..url.." to register an account on this server."
elseif url:match("^(%w+)[:].*$") == "mailto" then
inst_text = "Please send an e-mail at "..url:match("^%w+[:](.*)$").." to register an account on this server."
elseif url:match("^(%w+)[:].*$") == "xmpp" then
inst_text = "Please contact "..module:get_host().."'s server administrator via xmpp to register an account on this server at: "..url:match("^%w+[:](.*)$")
else
module:log("error", "This module supports only http/https, mailto or xmpp as URL formats.")
module:log("error", "If you want to use personalized instructions without an Out-Of-Band method,")
module:log("error", "specify: register_oob = false; -- in your configuration along your banner string (register_text).")
return origin.send(st.error_reply(stanza, "wait", "internal-server-error")) -- bouncing request.
end
else
module:log("error", "Please check your configuration, the URL you specified is invalid")
return origin.send(st.error_reply(stanza, "wait", "internal-server-error")) -- bouncing request.
end
else
if admins_l then
local ajid; for _,v in ipairs(admins_l) do ajid = v ; break end
inst_text = "Please contact "..module:get_host().."'s server administrator via xmpp to register an account on this server at: "..ajid
else
if admins_g then
local ajid; for _,v in ipairs(admins_g) do ajid = v ; break end
inst_text = "Please contact "..module:get_host().."'s server administrator via xmpp to register an account on this server at: "..ajid
else
module:log("error", "Please be sure to, _at the very least_, configure one server administrator either global or hostwise...")
module:log("error", "if you want to use this module, or read it's configuration wiki at: http://code.google.com/p/prosody-modules/wiki/mod_register_redirect")
return origin.send(st.error_reply(stanza, "wait", "internal-server-error")) -- bouncing request.
end
end
end
elseif inst_text and url and oob then
if not url:match("^%w+[:].*$") then
module:log("error", "Please check your configuration, the URL specified is not valid.")
return origin.send(st.error_reply(stanza, "wait", "internal-server-error")) -- bouncing request.
end
end
if not no_wl then
for i,ip in ipairs(ip_wl) do
if origin.ip == ip then test_ip = true end
break
end
end
-- Prepare replies.
local reply = st.reply(event.stanza)
if oob then
reply:query("jabber:iq:register")
:tag("instructions"):text(inst_text):up()
:tag("x", {xmlns = "jabber:x:oob"})
:tag("url"):text(url);
else
reply:query("jabber:iq:register")
:tag("instructions"):text(inst_text):up()
end
if stanza.attr.type == "get" then
return origin.send(reply)
else
return origin.send(st.error_reply(stanza, "cancel", "not-authorized"))
end
end
module:hook("stanza/iq/jabber:iq:register:query", reg_redirect, 10)
|
mod_register_redirect: rebacked in changeset c6f1427da79d (behaviour fixed).
|
mod_register_redirect: rebacked in changeset c6f1427da79d (behaviour fixed).
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
4f860f189797cc7767e0e6890d6b76c2afead13a
|
Shilke2D/Utils/Table.lua
|
Shilke2D/Utils/Table.lua
|
---Extends table namespace
---clears a table, setting all the values to nil
--@param t the table to clear
--@param recursive [optional] if true clear all subtables deeply. Default value is false
function table.clear(t,recursive)
for k,_ in pairs(t) do
if recursive and type(t[k]) == 'table' then
table.clear(t[k],true)
end
t[k] = nil
end
end
---make a copy of the values of a table and assign the same metatable
--@return table table to be copied
--@return a new table
function table.copy(t)
local u ={}
for k,v in pairs(t) do
u[k] = v
end
return setmetatable(u, getmetatable(t))
end
---Make a deep copy of the values of a table and assign the same metatable.
--Deep copy means that each value of type table is deepcopied itself
--@return table table to be copied
--@return a new table
function table.deepcopy(t)
if type(t) ~= 'table' then
return t
end
local mt = getmetatable(t)
local res = {}
for k,v in pairs(t) do
if type(v) == 'table' then
res[k] = table.deepcopy(v)
else
res[k] = v
end
end
setmetatable(res,mt)
return res
end
---Sets to nil a key and returns previous value
--@param table the table to modify
--@param key the key to reset
--@return previous kay value
function table.removeKey(table, key)
local element = table[key]
table[key] = nil
return element
end
---Returns position of o in table t
--@param t the table where to search
--@param o the object to be searched
--@return index of the object into the table.
--0 if the table doesn't contain the object.
function table.find(t,o)
local c = 1
for _,v in pairs(t) do
if(v == o) then
return c
end
c = c + 1
end
return 0
end
---Removes an object from a table
--@param t the table to modify
--@param o the object to be removed
--@return the removed object. nil if o doesn't belong to t
function table.removeObj(t, o)
local i = table.find(t,o)
if i then
return table.remove(t,i)
end
return nil
end
---Returns a new table that contains the same elements in inverse order.
--Threats the table as normal indexed array
--@param t the array to invert
--@return a new table
function table.invert(t)
local new = {}
for i=0, #t do
table.insert(new, t[#t - i])
end
return new
end
---Returns a new table that is a copy of a section af a given table.
--@param t the source table
--@param i1 start index of the copy section
--@param i2 end index of the copy section
--@return a new table
function table.slice(t,i1,i2)
local res = {}
local n = #t
-- default values for range
local i1 = i1 or 1
local i2 = i2 or n
if i2 < 0 then
i2 = n + i2 + 1
elseif i2 > n then
i2 = n
end
if i1 < 1 or i1 > n then
return {}
end
local k = 1
for i = i1,i2 do
res[k] = t[i]
k = k + 1
end
return res
end
---prints the content of a table using outFunc
--@param t the table to dump
--@param outFunc the function to be used for dumping. default is "print"
function table.dump(t,outFunc)
local outFunc = outFunc or print
for k,v in pairs(t) do
outFunc(k,v)
if type(v) == "table" then
table.dump(v)
end
end
end
--[[---
works on index tables (tables used like arrays). extends t1 content adding values from t2.
works in same way of python list.extend
@param t1 list to be extended (at the end t1 will be modified)
@param t2 list to extend with
@return list return a reference of t1
--]]
function table.extend(t1, t2)
for _,v in ipairs(t2) do
t1[#t1+1] = v
end
return t1
end
--[[---
Returns a random element from the provided table.
Works only with the array part of tables
@param t the table with the element to choose
@return element a random element of t
--]]
function table.random(t)
return t[math.random(#t)]
end
--[[---
"Sorted by key" table iterator
Extracted from http://www.lua.org/pil/19.3.html
@param t the table to iterate
@param comp[opt] the compare function (see table.sort).
by default uses alphabetical comparison
--]]
function sortedpairs(t, comp)
local a = {}
for n in pairs(t) do
table.insert(a, n)
end
table.sort(a, comp)
-- iterator variable
local i = 0
-- iterator function
local iter = function ()
i = i + 1
if a[i] == nil then
return nil
else
return a[i], t[a[i]]
end
end
return iter
end
|
---Extends table namespace
---clears a table, setting all the values to nil
--@param t the table to clear
--@param recursive [optional] if true clear all subtables deeply. Default value is false
function table.clear(t,recursive)
for k,_ in pairs(t) do
if recursive and type(t[k]) == 'table' then
table.clear(t[k],true)
end
t[k] = nil
end
end
---make a copy of the values of a table and assign the same metatable
--@return table table to be copied
--@return a new table
function table.copy(t)
local u ={}
for k,v in pairs(t) do
u[k] = v
end
return setmetatable(u, getmetatable(t))
end
---Make a deep copy of the values of a table and assign the same metatable.
--Deep copy means that each value of type table is deepcopied itself
--@return table table to be copied
--@return a new table
function table.deepcopy(t)
if type(t) ~= 'table' then
return t
end
local mt = getmetatable(t)
local res = {}
for k,v in pairs(t) do
if type(v) == 'table' then
res[k] = table.deepcopy(v)
else
res[k] = v
end
end
setmetatable(res,mt)
return res
end
---Sets to nil a key and returns previous value
--@param table the table to modify
--@param key the key to reset
--@return previous kay value
function table.removeKey(table, key)
local element = table[key]
table[key] = nil
return element
end
---Returns position of o in table t
--@param t the table where to search
--@param o the object to be searched
--@return index of the object into the table.
--0 if the table doesn't contain the object.
function table.find(t,o)
local c = 1
for _,v in pairs(t) do
if(v == o) then
return c
end
c = c + 1
end
return 0
end
---Removes an object from a table
--@param t the table to modify
--@param o the object to be removed
--@return the removed object. nil if o doesn't belong to t
function table.removeObj(t, o)
local i = table.find(t,o)
if i then
return table.remove(t,i)
end
return nil
end
---Returns a new table that contains the same elements in inverse order.
--Threats the table as normal indexed array
--@param t the array to invert
--@return a new table
function table.invert(t)
local new = {}
for i=0, #t do
table.insert(new, t[#t - i])
end
return new
end
---Returns a new table that is a copy of a section af a given table.
--@param t the source table
--@param i1 start index of the copy section
--@param i2 end index of the copy section
--@return a new table
function table.slice(t,i1,i2)
local res = {}
local n = #t
-- default values for range
local i1 = i1 or 1
local i2 = i2 or n
if i2 < 0 then
i2 = n + i2 + 1
elseif i2 > n then
i2 = n
end
if i1 < 1 or i1 > n then
return {}
end
local k = 1
for i = i1,i2 do
res[k] = t[i]
k = k + 1
end
return res
end
---prints the content of a table using outFunc
--@param t the table to dump
--@param outFunc the function to be used for dumping. default is "print"
function table.dump(t,outFunc)
local outFunc = outFunc or print
for k,v in pairs(t) do
outFunc(k,v)
if type(v) == "table" then
table.dump(v)
end
end
end
--[[---
works on index tables (tables used like arrays). extends t1 content adding values from t2.
works in same way of python list.extend
@param t1 list to be extended (at the end t1 will be modified)
@param t2 list to extend with
@return list return a reference of t1
--]]
function table.extend(t1, t2)
for _,v in ipairs(t2) do
t1[#t1+1] = v
end
return t1
end
--[[---
Returns a random element from the provided table.
Works only with the array part of tables
@param t the table with the element to choose
@return element a random element of t
--]]
function table.random(t)
return t[math.random(#t)]
end
--[[---
"Sorted by key" table iterator
Extracted from http://www.lua.org/pil/19.3.html
@param t the table to iterate
@param[opt=nil] comp the compare function. The function must be of the type comp(t, a, b)
with t the table on wich iterating, a and b table keys to compare. If not provided a default
alphabetical comparison on keys is done
--]]
function sortedpairs(t, comp)
local keys = {}
for k,_ in pairs(t) do
keys[#keys+1] = k
end
if comp then
table.sort(keys, function(a,b) return comp(t, a, b) end)
else
table.sort(keys)
end
-- iterator variable
local i = 0
-- iterator function
return function ()
i = i + 1
if keys[i] then
return keys[i], t[keys[i]]
end
return nil
end
end
|
fix/improvement for sortedpairs iterator
|
fix/improvement for sortedpairs iterator
the compare function is in now the form comp(t,a,b) where t is the
table and a,b the keys to be compared. That allows to make compare
functions based on table values, comparing t[a] with t[b]
|
Lua
|
mit
|
Shrike78/Shilke2D
|
d725a42e2efd2df34dc21cc1a8bb087241064268
|
src/luarocks/cache.lua
|
src/luarocks/cache.lua
|
--- Module handling the LuaRocks local cache.
-- Adds a rock or rockspec to a rocks server.
--module("luarocks.cache", package.seeall)
local cache = {}
package.loaded["luarocks.cache"] = cache
local fs = require("luarocks.fs")
local cfg = require("luarocks.cfg")
local dir = require("luarocks.dir")
local util = require("luarocks.util")
function cache.get_upload_server(server)
if not server then server = cfg.upload_server end
if not server then
return nil, "No server specified and no default configured with upload_server."
end
return server, cfg.upload_servers and cfg.upload_servers[server]
end
function cache.get_server_urls(server, upload_server)
local download_url = server
local login_url = nil
if upload_server then
if upload_server.rsync then download_url = "rsync://"..upload_server.rsync
elseif upload_server.http then download_url = "http://"..upload_server.http
elseif upload_server.ftp then download_url = "ftp://"..upload_server.ftp
end
if upload_server.ftp then login_url = "ftp://"..upload_server.ftp
elseif upload_server.sftp then login_url = "sftp://"..upload_server.sftp
end
end
return download_url, login_url
end
function cache.split_server_url(server, url, user, password)
local protocol, server_path = dir.split_url(url)
if server_path:match("@") then
local credentials
credentials, server_path = server_path:match("([^@]*)@(.*)")
if credentials:match(":") then
user, password = credentials:match("([^:]*):(.*)")
else
user = credentials
end
end
local local_cache
if cfg.local_cache then
local_cache = cfg.local_cache .. "/" .. server
end
return local_cache, protocol, server_path, user, password
end
function cache.refresh_local_cache(server, url, user, password)
local local_cache, protocol, server_path, user, password = cache.split_server_url(server, url, user, password)
local ok, err = fs.make_dir(cfg.local_cache)
if not ok then return nil, err end
local tmp_cache = false
if not local_cache then
local err
local_cache, err = fs.make_temp_dir("local_cache")
tmp_cache = true
end
local ok, err = fs.make_dir(local_cache)
if not ok then
return nil, "Failed creating local cache dir: "..err
end
fs.change_dir(local_cache)
if not ok then return nil, err end
util.printout("Refreshing cache "..local_cache.."...")
-- TODO abstract away explicit 'wget' call
local ok = false
if protocol == "rsync" then
local srv, path = server_path:match("([^/]+)(/.+)")
ok = fs.execute(cfg.variables.RSYNC.." "..cfg.variables.RSYNCFLAGS.." -e ssh "..user.."@"..srv..":"..path.."/ "..local_cache.."/")
else
local login_info = ""
if user then login_info = " --user="..user end
if password then login_info = login_info .. " --password="..password end
ok = fs.execute(cfg.variables.WGET.." --no-cache -q -m -np -nd "..protocol.."://"..server_path..login_info)
end
if not ok then
return nil, "Failed downloading cache."
end
return local_cache, protocol, server_path, user, password
end
return cache
|
--- Module handling the LuaRocks local cache.
-- Adds a rock or rockspec to a rocks server.
--module("luarocks.cache", package.seeall)
local cache = {}
package.loaded["luarocks.cache"] = cache
local fs = require("luarocks.fs")
local cfg = require("luarocks.cfg")
local dir = require("luarocks.dir")
local util = require("luarocks.util")
function cache.get_upload_server(server)
if not server then server = cfg.upload_server end
if not server then
return nil, "No server specified and no default configured with upload_server."
end
return server, cfg.upload_servers and cfg.upload_servers[server]
end
function cache.get_server_urls(server, upload_server)
local download_url = server
local login_url = nil
if upload_server then
if upload_server.rsync then download_url = "rsync://"..upload_server.rsync
elseif upload_server.http then download_url = "http://"..upload_server.http
elseif upload_server.ftp then download_url = "ftp://"..upload_server.ftp
end
if upload_server.ftp then login_url = "ftp://"..upload_server.ftp
elseif upload_server.sftp then login_url = "sftp://"..upload_server.sftp
end
end
return download_url, login_url
end
function cache.split_server_url(server, url, user, password)
local protocol, server_path = dir.split_url(url)
if server_path:match("@") then
local credentials
credentials, server_path = server_path:match("([^@]*)@(.*)")
if credentials:match(":") then
user, password = credentials:match("([^:]*):(.*)")
else
user = credentials
end
end
local local_cache = cfg.local_cache .. "/" .. server
return local_cache, protocol, server_path, user, password
end
function cache.refresh_local_cache(server, url, user, password)
local local_cache, protocol, server_path, user, password = cache.split_server_url(server, url, user, password)
local ok, err = fs.make_dir(local_cache)
if not ok then
return nil, "Failed creating local cache dir: "..err
end
fs.change_dir(local_cache)
if not ok then return nil, err end
util.printout("Refreshing cache "..local_cache.."...")
-- TODO abstract away explicit 'wget' call
local ok = false
if protocol == "rsync" then
local srv, path = server_path:match("([^/]+)(/.+)")
ok = fs.execute(cfg.variables.RSYNC.." "..cfg.variables.RSYNCFLAGS.." -e ssh "..user.."@"..srv..":"..path.."/ "..local_cache.."/")
else
local login_info = ""
if user then login_info = " --user="..user end
if password then login_info = login_info .. " --password="..password end
ok = fs.execute(cfg.variables.WGET.." --no-cache -q -m -np -nd "..protocol.."://"..server_path..login_info)
end
if not ok then
return nil, "Failed downloading cache."
end
return local_cache, protocol, server_path, user, password
end
return cache
|
Do not handle cfg.local_cache == nil in luarocks.cache
|
Do not handle cfg.local_cache == nil in luarocks.cache
cfg.local_cache is always set by defaults. Fixes #479.
|
Lua
|
mit
|
keplerproject/luarocks,starius/luarocks,ignacio/luarocks,xpol/luarocks,robooo/luarocks,xpol/luavm,xpol/luavm,keplerproject/luarocks,keplerproject/luarocks,luarocks/luarocks,robooo/luarocks,xpol/luavm,starius/luarocks,xpol/luainstaller,luarocks/luarocks,starius/luarocks,xpol/luavm,ignacio/luarocks,robooo/luarocks,luarocks/luarocks,starius/luarocks,xpol/luainstaller,xpol/luarocks,xpol/luarocks,xpol/luainstaller,tarantool/luarocks,xpol/luarocks,ignacio/luarocks,tarantool/luarocks,robooo/luarocks,xpol/luavm,xpol/luainstaller,ignacio/luarocks,tarantool/luarocks,keplerproject/luarocks
|
404610707ad4dc79c9544b110a9eca0cb3dca05a
|
input.lua
|
input.lua
|
local function event(name, ...)
if input[name] then
input[name](...)
return true
end
return false
end
function love.keypressed(name, num)
return event("key_"..name)
or event("key_any", name)
end
function love.joystickpressed(joystick, button)
local name = "joy_"..joystick.."_button_"..button
return event(name)
or event("joy_any", joystick, "button", button)
end
local axes = {}
for joy=0,love.joystick.getNumJoysticks()-1 do
eprintf("init joystick %d\n", joy)
axes[joy] = { hat = love.joystick.getHat(joy, 0); love.joystick.getAxes(0) }
end
function love.update(dt)
local old_axes
local function direction(value)
return (value == 1 and "up")
or (value == -1 and "down")
or (value == 0 and "center")
or "center"
end
local function do_axis(joy, axis, value)
if old_axes[axis] ~= value then
return event("joy_"..joy.."_axis_"..axis.."_"..direction(value))
or event("joy_any", joy, "axis", axis, direction(value))
end
end
local function do_hat(joy, value)
if value ~= old_axes.hat then
return event("joy_"..joy.."_hat_"..value)
or event("joy_any", joy, "hat", value)
end
end
for joy,joy_axes in pairs(axes) do
local new_axes = { hat = love.joystick.getHat(joy, 0); love.joystick.getAxes(joy) }
old_axes = joy_axes
for axis,value in ipairs(new_axes) do
do_axis(joy, axis, value)
end
do_hat(joy, new_axes.hat)
axes[joy] = new_axes
end
love.timer.sleep(33 - (dt*1000))
end
|
-- Input handling library. This is meant to simplify the handling of keyboard
-- and joystick events.
-- Note that it doesn't really support joystick axes except as d-pads - that is
-- to say, pushing an axis all the way will register as (say) "up" and anything
-- else is "center".
-- Dispatch an event with the given names and arguments.
-- Returns true if an event handler existed, false otherwise
local function event(name, ...)
if input[name] then
input[name](...)
return true
end
return false
end
-- love2d callback function for keyboard events. Pressing 'a' will trigger event
-- key_a() or, if that doesn't exist, key_any('a')
function love.keypressed(name, num)
return event("key_"..name)
or event("key_any", name)
end
-- same as above, but for joysticks. Joystick events are parameterized by both
-- stick and button; button 3 on stick 0 shows up as joy_0_button_3.
function love.joystickpressed(joystick, button)
local name = "joy_"..joystick.."_button_"..button
return event(name)
or event("joy_any", joystick, "button", button)
end
-- joystick axis handling. At initialization, read the state of every axis on
-- every joystick and record them. We emit events only if the state of an
-- axis changes between frames, so that someone holding a stick up doesn't
-- trigger (say) joy_0_axis_2_up every single frame.
local axes = {}
for joy=0,love.joystick.getNumJoysticks()-1 do
axes[joy] = { hat = love.joystick.getHat(joy, 0); love.joystick.getAxes(0) }
end
-- Every frame, scan joystick axes, compare them to the previous frame, and
-- emit events for any that have changed.
function love.update(dt)
local old_axes
-- translate a joystick axis value into a descriptive string
local function direction(value)
return (value == 1 and "up")
or (value == -1 and "down")
or "center"
end
-- check a single axis, and emit an event if it changed
local function do_axis(joy, axis, value)
if old_axes[axis] ~= value then
return event("joy_"..joy.."_axis_"..axis.."_"..direction(value))
or event("joy_any", joy, "axis", axis, direction(value))
end
end
-- check a hat-switch, and emit an event if it changed.
-- FIXME: this should work for multiple hats on the same stick.
local function do_hat(joy, value)
if value ~= old_axes.hat then
return event("joy_"..joy.."_hat_"..value)
or event("joy_any", joy, "hat", value)
end
end
-- iterate over all the axes on all the joysticks and check them
for joy,joy_axes in pairs(axes) do
local new_axes = { hat = love.joystick.getHat(joy, 0); love.joystick.getAxes(joy) }
old_axes = joy_axes
for axis,value in ipairs(new_axes) do
do_axis(joy, axis, value)
end
do_hat(joy, new_axes.hat)
axes[joy] = new_axes
end
-- cap framerate at 30fps
love.timer.sleep(33 - (dt*1000))
end
|
Lots of commenting for input.lua. FIXME: still needs some refactoring, multihat support
|
Lots of commenting for input.lua. FIXME: still needs some refactoring, multihat support
|
Lua
|
mit
|
ToxicFrog/EmuFun
|
efc244cbdac6f4bf230fb3bc2faa5df603680757
|
cherry/libs/group.lua
|
cherry/libs/group.lua
|
--------------------------------------------------------------------------------
local animation = require 'cherry.libs.animation'
local Group = {}
-- destroyFromDisplay --> destroy
--------------------------------------------------------------------------------
function Group.empty( group )
if(group ~= nil and group.numChildren ~= nil and group.numChildren > 0) then
for i=group.numChildren,1,-1 do
local child = group[i]
transition.cancel(child)
child:removeSelf()
group[i] = nil
end
end
end
function Group.destroy(object, easeHideEffect)
local doDestroy = function()
if(object) then
Group.empty(object)
display.remove(object)
object = nil
end
end
if(easeHideEffect) then
animation.easeHide(object, doDestroy, 125)
else
doDestroy()
end
end
--------------------------------------------------------------------------------
return Group
|
--------------------------------------------------------------------------------
local animation = require 'cherry.libs.animation'
local Group = {}
-- destroyFromDisplay --> destroy
--------------------------------------------------------------------------------
function Group.empty( group )
if(group == nil) then return end
if(#group > 0) then
for i = #group, 1, -1 do
group[i]:removeSelf()
group[i] = nil
end
end
if(group.numChildren ~= nil and group.numChildren > 0) then
for i=group.numChildren,1,-1 do
local child = group[i]
transition.cancel(child)
child:removeSelf()
group[i] = nil
end
end
end
function Group.destroy(object, easeHideEffect)
local doDestroy = function()
if(object) then
Group.empty(object)
display.remove(object)
object = nil
end
end
if(easeHideEffect) then
animation.easeHide(object, doDestroy, 125)
else
doDestroy()
end
end
--------------------------------------------------------------------------------
return Group
|
fixed group.empty
|
fixed group.empty
|
Lua
|
bsd-3-clause
|
chrisdugne/cherry
|
e66d2aab07ed6f2b394e468effa136728320f733
|
lantern/accumulators/accuracy.lua
|
lantern/accumulators/accuracy.lua
|
require "torch"
require "cutorch"
local accuracy = lantern.make_accumulator("accuracy")
function accuracy:__init(classes)
assert(
classes > 1,
"Number of classes must be greater than one. For binary " ..
"classification, use the indices one and two."
)
self.classes = classes
self.correct = 0
self.total = 0
end
-- Note: each row of outputs should contain the probabilities or log
-- probabilities of the classes.
function accuracy:update(batch, state)
local targets = batch.targets
local outputs = state.outputs
assert(targets)
assert(outputs)
if type(targets) ~= "number" then
local t = targets:type()
assert(
t == "torch.ByteTensor" or
t == "torch.LongTensor" or
t == "torch.CudaTensor"
)
end
assert(
outputs:nDimension() <= 2,
"`outputs` must either be a vector or a matrix whose rows " ..
"contain the log probabilities of the classes for each input."
)
local check_target = function(target)
assert(
target > 0,
"Found target of zero. The target must be the " ..
"_one-based_ index of the ground-truth class."
)
assert(
target <= self.classes,
"Found target greater than number of classes given " ..
"to constructor."
)
end
if outputs:nDimension() == 1 then
assert(type(targets) == "number")
check_target(targets)
local _, indices = torch.max(outputs, 1)
self.total = self.total + 1
if indices[1] == targets then
self.correct = self.correct + 1
end
else
assert(targets:nDimension() == 1)
assert(outputs:size(1) == targets:size(1))
for i = 1, targets:size(1) do
check_target(targets[i])
end
local _, indices = torch.max(outputs, 2)
self.total = self.total + outputs:size(1)
self.correct = self.correct + torch.eq(indices, targets:typeAs(indices)):sum()
end
assert(self.total > 0)
assert(self.total >= self.correct)
end
function accuracy:value()
assert(self.total > 0)
assert(self.total >= self.correct)
return {accuracy = self.correct / self.total}
end
|
require "torch"
require "cutorch"
local accuracy = lantern.make_accumulator("accuracy")
function accuracy:__init(classes)
assert(
classes > 1,
"Number of classes must be greater than one. For binary " ..
"classification, use the indices one and two."
)
self.classes = classes
self.correct = 0
self.total = 0
end
-- Note: each row of outputs should contain the probabilities or log
-- probabilities of the classes.
function accuracy:update(batch, state)
local targets = batch.targets
local outputs = state.outputs
assert(targets)
assert(outputs)
if type(targets) ~= "number" then
local t = targets:type()
assert(
t == "torch.ByteTensor" or
t == "torch.LongTensor" or
t == "torch.CudaTensor"
)
end
assert(
outputs:nDimension() <= 2,
"`outputs` must either be a vector or a matrix whose rows " ..
"contain the log probabilities of the classes for each input."
)
local check_target = function(target)
assert(
target > 0,
"Found target of zero. The target must be the " ..
"_one-based_ index of the ground-truth class."
)
assert(
target <= self.classes,
"Found target greater than number of classes given " ..
"to constructor."
)
end
if outputs:nDimension() == 1 then
check_target(targets[1])
local _, indices = torch.max(outputs, 1)
self.total = self.total + 1
if indices[1] == targets[1] then
self.correct = self.correct + 1
end
else
assert(targets:nDimension() == 1)
assert(outputs:size(1) == targets:size(1))
for i = 1, targets:size(1) do
check_target(targets[i])
end
local _, indices = torch.max(outputs, 2)
self.total = self.total + outputs:size(1)
self.correct = self.correct + torch.eq(indices, targets:typeAs(indices)):sum()
end
assert(self.total > 0)
assert(self.total >= self.correct)
end
function accuracy:value()
assert(self.total > 0)
assert(self.total >= self.correct)
return {accuracy = self.correct / self.total}
end
|
Small bugfix.
|
Small bugfix.
|
Lua
|
bsd-3-clause
|
adityaramesh/lantern
|
573013bf2ea65d21ad64c62e149cf2ccb710e76e
|
hammerspoon/layouts/lapseofthought_com.lua
|
hammerspoon/layouts/lapseofthought_com.lua
|
--------------------------------------------------------------------------------
-- LAYOUTS
-- SINTAX:
-- {
-- name = "App name" ou { "App name", "App name" }
-- title = "Window title" (optional)
-- func = function(index, win)
-- COMMANDS
-- end
-- },
--
-- It searches for application "name" and call "func" for each window object
--------------------------------------------------------------------------------
local layouts = {
{
name = "Emacs",
func = function(index, win)
win:moveToScreen(monitor_2, false, true)
end
},
{
name = "Slack",
func = function(index, win)
-- first space on 2nd monitor
-- spaces.moveWindowToSpace(win:id(), hs.screen.allScreens()[1]:spaces()[1])
if (#hs.screen.allScreens() > 1) then
win:moveToScreen(monitor_2, false, true)
hsm.windows.moveTopLeft(win)
else
hsm.windows.moveTopRight(win)
end
end
},
{
name = "Adium",
func = function(index, win)
if (#hs.screen.allScreens() > 1) then
-- second space on 1st monitor
spaces.moveWindowToSpace(win:id(), hs.screen.allScreens()[2]:spaces()[1])
end
hsm.windows.moveBottomLeft(win)
end
},
{
name = "Adium",
title = "Contacts",
func = function(index, win)
if (#hs.screen.allScreens() > 1) then
-- second space on 1st monitor
spaces.moveWindowToSpace(win:id(), hs.screen.allScreens()[1]:spaces()[2])
end
hsm.windows.moveTopLeft(win)
end
},
{
name = "Zoiper",
func = function(index, win)
hsm.windows.moveTopLeft(win,150,0)
end
},
}
return layouts
|
--------------------------------------------------------------------------------
-- LAYOUTS
-- SINTAX:
-- {
-- name = "App name" ou { "App name", "App name" }
-- title = "Window title" (optional)
-- func = function(index, win)
-- COMMANDS
-- end
-- },
--
-- It searches for application "name" and call "func" for each window object
--------------------------------------------------------------------------------
local layouts = {
{
name = "Emacs",
func = function(index, win)
win:moveToScreen(monitor_2, false, true)
end
},
{
name = "Slack",
func = function(index, win)
-- first space on 2nd monitor
-- spaces.moveWindowToSpace(win:id(), hs.screen.allScreens()[1]:spaces()[1])
if (#hs.screen.allScreens() > 1) then
win:moveToScreen(monitor_2, false, true)
hsm.windows.moveTopLeft(win)
else
hsm.windows.moveTopRight(win)
end
end
},
-- {
-- name = "Adium",
-- func = function(index, win)
-- if (#hs.screen.allScreens() > 1) then
-- -- second space on 1st monitor
-- spaces.moveWindowToSpace(win:id(), hs.screen.allScreens()[2]:spaces()[1])
-- end
-- hsm.windows.moveBottomLeft(win)
-- end
-- },
{
name = "Adium",
title = "Contacts",
func = function(index, win)
if (#hs.screen.allScreens() > 1) then
-- second space on 1st monitor
spaces.moveWindowToSpace(win:id(), hs.screen.allScreens()[1]:spaces()[2])
end
hsm.windows.moveTopLeft(win)
end
},
{
name = "Zoiper",
func = function(index, win)
hsm.windows.moveTopLeft(win,150,0)
end
},
}
return layouts
|
Fix Adium positioning
|
Fix Adium positioning
|
Lua
|
mit
|
sjthespian/dotfiles,sjthespian/dotfiles,sjthespian/dotfiles,sjthespian/dotfiles
|
392be620f55077e9a91241a6d677f1019b55958a
|
lua/mediaplayer/menu/common.lua
|
lua/mediaplayer/menu/common.lua
|
local clamp = math.Clamp
local FontTbl = {
font = "Roboto Medium",
size = 21,
weight = 400,
antialias = true
}
surface.CreateFont( "MP.MediaTitle", FontTbl )
FontTbl.font = "Roboto Medium"
FontTbl.size = 18
surface.CreateFont( "MP.MediaTime", FontTbl )
FontTbl.font = "Roboto Medium"
FontTbl.size = 18
surface.CreateFont( "MP.QueueHeader", FontTbl )
FontTbl.font = "Roboto Light"
surface.CreateFont( "MP.MediaDuration", FontTbl )
FontTbl.font = "Roboto Light"
FontTbl.size = 13
surface.CreateFont( "MP.Prefix", FontTbl )
FontTbl.font = "Roboto Bold"
FontTbl.size = 16
surface.CreateFont( "MP.AddedByName", FontTbl )
local MEDIA_TITLE = {}
function MEDIA_TITLE:Init()
self.BaseClass.Init( self )
self:SetFont( "MP.MediaTitle" )
self:SetTextColor( color_white )
end
derma.DefineControl( "MP.MediaTitle", "", MEDIA_TITLE, "DLabel" )
local MEDIA_TIME = {}
AccessorFunc( MEDIA_TIME, "StartTime", "StartTime" )
AccessorFunc( MEDIA_TIME, "Duration", "Duration" )
function MEDIA_TIME:Init()
self.TimeLbl = vgui.Create( "DLabel", self )
self.TimeLbl:SetFont( "MP.MediaTime" )
self.TimeLbl:SetText( "" )
self.TimeLbl:SetTextColor( color_white )
self.DividerLbl = vgui.Create( "DLabel", self )
self.DividerLbl:SetText( "" )
self.DividerLbl:SetFont( "MP.MediaDuration" )
-- self.DividerLbl:SetTextColor( color_white )
self.DurationLbl = vgui.Create( "DLabel", self )
self.DurationLbl:SetText( "" )
self.DurationLbl:SetFont( "MP.MediaDuration" )
-- self.DurationLbl:SetTextColor( color_white )
self.NextThink = 0
end
function MEDIA_TIME:SetStartTime( time )
self.StartTime = time
local text = time and "0:00" or ""
self.TimeLbl:SetText( text )
self:UpdateDivider()
end
function MEDIA_TIME:SetDuration( duration )
self.Duration = duration
local text = duration and string.FormatSeconds( duration ) or ""
self.DurationLbl:SetText( text )
self:UpdateDivider()
end
function MEDIA_TIME:UpdateDivider()
local text = (self.StartTime and self.Duration) and "/" or ""
self.DividerLbl:SetText( text )
end
function MEDIA_TIME:Clear()
self:SetStartTime( nil )
self:SetDuration( nil )
end
function MEDIA_TIME:Think()
local rt = RealTime()
if self.NextThink > rt then return end
local curTime = RealTime()
local mediaTime
if self.StartTime then
mediaTime = clamp( curTime - self.StartTime, 0, self.Duration )
self.TimeLbl:SetText( string.FormatSeconds( mediaTime ) )
self:InvalidateLayout()
end
self.NextThink = rt + 0.5
end
function MEDIA_TIME:PerformLayout()
self.TimeLbl:SizeToContents()
self.DividerLbl:SizeToContents()
self.DurationLbl:SizeToContents()
self.TimeLbl:CenterVertical()
self.TimeLbl:AlignLeft( 0 )
self.DividerLbl:CenterVertical()
self.DividerLbl:MoveRightOf( self.TimeLbl )
self.DurationLbl:CenterVertical()
self.DurationLbl:MoveRightOf( self.DividerLbl )
local totalwidth = self.DurationLbl:GetPos() + self.DurationLbl:GetWide()
self:SetWide( totalwidth )
end
derma.DefineControl( "MP.MediaTime", "", MEDIA_TIME, "Panel" )
local ADDED_BY = {}
ADDED_BY.Height = 21
ADDED_BY.NameOffset = 4
function ADDED_BY:Init()
self.PrefixLbl = vgui.Create( "DLabel", self )
self.PrefixLbl:SetFont( "MP.Prefix" )
self.PrefixLbl:SetText( "ADDED BY" )
self.PrefixLbl:SetTextColor( color_white )
self.PrefixLbl:SetContentAlignment( 8 )
self.NameLbl = vgui.Create( "DLabel", self )
self.NameLbl:SetFont( "MP.AddedByName" )
self.NameLbl:SetText( "Unknown" )
self.NameLbl:SetTextColor( color_white )
self.NameLbl:SetContentAlignment( 8 )
end
function ADDED_BY:SetPlayer( ply, name, steamId )
self.NameLbl:SetText( name )
self.NameLbl:SetTooltip( steamId )
end
function ADDED_BY:SetMaxWidth( width )
self.maxWidth = width
self:InvalidateLayout()
end
function ADDED_BY:PerformLayout()
self.PrefixLbl:SizeToContents()
self.NameLbl:SizeToContents()
local pw = self.PrefixLbl:GetWide()
local nw = self.NameLbl:GetWide()
local w = pw + nw + self.NameOffset
if self.maxWidth then
w = math.min( w, self.maxWidth )
-- Clips name label to the maximum width; looks kind of bad since the
-- ellipsis start too early for some reason.
-- nw = math.max( 0, w - self.NameOffset - pw )
-- self.NameLbl:SetWide( nw )
end
self:SetSize( w, self.Height )
self.PrefixLbl:AlignLeft( 0 )
self.NameLbl:MoveRightOf( self.PrefixLbl, self.NameOffset )
-- align text baselines
self.PrefixLbl:AlignBottom( 3 )
self.NameLbl:AlignBottom( 3 )
end
derma.DefineControl( "MP.AddedBy", "", ADDED_BY, "Panel" )
local SIDEBAR_BTN = {
Size = 21,
Icon = "mediaplayer/ui/skip.png",
IconW = 21,
IconH = 21
}
function SIDEBAR_BTN:Init()
self.BaseClass.Init( self )
self:SetSize( self.Size, self.Size )
self:SetStretchToFit( false )
self:SetImage( self.Icon )
end
function SIDEBAR_BTN:SetImage( strImage, strBackup )
self.m_Image:SetImage( strImage, strBackup )
self.m_Image.ActualWidth = self.IconW
self.m_Image.ActualHeight = self.IconH
end
derma.DefineControl( "MP.SidebarButton", "", SIDEBAR_BTN, "DImageButton" )
local FAVORITE_BTN = {
FavStarOutlined = "mediaplayer/ui/fav_star_outline.png",
FavStar = "mediaplayer/ui/fav_star.png",
Icon = FAVORITE_BTN.FavStarOutlined
}
function FAVORITE_BTN:Init()
self.BaseClass.Init( self )
self.Outlined = true
end
function FAVORITE_BTN:Think()
local hovered = self:IsHovered()
if self.Outlined then
if hovered then
self:SetImage( self.FavStar )
self.Outlined = false
end
else
if not hovered then
self:SetImage( self.FavStarOutlined )
self.Outlined = true
end
end
end
function FAVORITE_BTN:DoClick()
-- TODO: Favorite media
end
derma.DefineControl( "MP.FavoriteButton", "", FAVORITE_BTN, "MP.SidebarButton" )
local SKIP_BTN = {
Icon = "mediaplayer/ui/skip.png",
IconW = 16,
IconH = 16
}
function SKIP_BTN:DoClick()
-- TODO: Skip current media
end
derma.DefineControl( "MP.SkipButton", "", SKIP_BTN, "MP.SidebarButton" )
local REMOVE_BTN = {
Icon = "mediaplayer/ui/delete.png",
IconW = 17,
IconH = 20
}
function REMOVE_BTN:DoClick()
-- TODO: Remove current media
end
derma.DefineControl( "MP.RemoveButton", "", REMOVE_BTN, "MP.SidebarButton" )
|
local clamp = math.Clamp
local FontTbl = {
font = "Roboto Medium",
size = 21,
weight = 400,
antialias = true
}
surface.CreateFont( "MP.MediaTitle", FontTbl )
FontTbl.font = "Roboto Medium"
FontTbl.size = 18
surface.CreateFont( "MP.MediaTime", FontTbl )
FontTbl.font = "Roboto Medium"
FontTbl.size = 18
surface.CreateFont( "MP.QueueHeader", FontTbl )
FontTbl.font = "Roboto Light"
surface.CreateFont( "MP.MediaDuration", FontTbl )
FontTbl.font = "Roboto Light"
FontTbl.size = 13
surface.CreateFont( "MP.Prefix", FontTbl )
FontTbl.font = "Roboto Bold"
FontTbl.size = 16
surface.CreateFont( "MP.AddedByName", FontTbl )
local MEDIA_TITLE = {}
function MEDIA_TITLE:Init()
self.BaseClass.Init( self )
self:SetFont( "MP.MediaTitle" )
self:SetTextColor( color_white )
end
derma.DefineControl( "MP.MediaTitle", "", MEDIA_TITLE, "DLabel" )
local MEDIA_TIME = {}
AccessorFunc( MEDIA_TIME, "StartTime", "StartTime" )
AccessorFunc( MEDIA_TIME, "Duration", "Duration" )
function MEDIA_TIME:Init()
self.TimeLbl = vgui.Create( "DLabel", self )
self.TimeLbl:SetFont( "MP.MediaTime" )
self.TimeLbl:SetText( "" )
self.TimeLbl:SetTextColor( color_white )
self.DividerLbl = vgui.Create( "DLabel", self )
self.DividerLbl:SetText( "" )
self.DividerLbl:SetFont( "MP.MediaDuration" )
-- self.DividerLbl:SetTextColor( color_white )
self.DurationLbl = vgui.Create( "DLabel", self )
self.DurationLbl:SetText( "" )
self.DurationLbl:SetFont( "MP.MediaDuration" )
-- self.DurationLbl:SetTextColor( color_white )
self.NextThink = 0
end
function MEDIA_TIME:SetStartTime( time )
self.StartTime = time
local text = time and "0:00" or ""
self.TimeLbl:SetText( text )
self:UpdateDivider()
end
function MEDIA_TIME:SetDuration( duration )
self.Duration = duration
local text = duration and string.FormatSeconds( duration ) or ""
self.DurationLbl:SetText( text )
self:UpdateDivider()
end
function MEDIA_TIME:UpdateDivider()
local text = (self.StartTime and self.Duration) and "/" or ""
self.DividerLbl:SetText( text )
end
function MEDIA_TIME:Clear()
self:SetStartTime( nil )
self:SetDuration( nil )
end
function MEDIA_TIME:Think()
local rt = RealTime()
if self.NextThink > rt then return end
local curTime = RealTime()
local mediaTime
if self.StartTime then
mediaTime = clamp( curTime - self.StartTime, 0, self.Duration )
self.TimeLbl:SetText( string.FormatSeconds( mediaTime ) )
self:InvalidateLayout()
end
self.NextThink = rt + 0.5
end
function MEDIA_TIME:PerformLayout()
self.TimeLbl:SizeToContents()
self.DividerLbl:SizeToContents()
self.DurationLbl:SizeToContents()
self.TimeLbl:CenterVertical()
self.TimeLbl:AlignLeft( 0 )
self.DividerLbl:CenterVertical()
self.DividerLbl:MoveRightOf( self.TimeLbl )
self.DurationLbl:CenterVertical()
self.DurationLbl:MoveRightOf( self.DividerLbl )
local totalwidth = self.DurationLbl:GetPos() + self.DurationLbl:GetWide()
self:SetWide( totalwidth )
end
derma.DefineControl( "MP.MediaTime", "", MEDIA_TIME, "Panel" )
local ADDED_BY = {}
ADDED_BY.Height = 21
ADDED_BY.NameOffset = 4
function ADDED_BY:Init()
self.PrefixLbl = vgui.Create( "DLabel", self )
self.PrefixLbl:SetFont( "MP.Prefix" )
self.PrefixLbl:SetText( "ADDED BY" )
self.PrefixLbl:SetTextColor( color_white )
self.PrefixLbl:SetContentAlignment( 8 )
self.NameLbl = vgui.Create( "DLabel", self )
self.NameLbl:SetFont( "MP.AddedByName" )
self.NameLbl:SetText( "Unknown" )
self.NameLbl:SetTextColor( color_white )
self.NameLbl:SetContentAlignment( 8 )
end
function ADDED_BY:SetPlayer( ply, name, steamId )
self.NameLbl:SetText( name )
self.NameLbl:SetTooltip( steamId )
end
function ADDED_BY:SetMaxWidth( width )
self.maxWidth = width
self:InvalidateLayout()
end
function ADDED_BY:PerformLayout()
self.PrefixLbl:SizeToContents()
self.NameLbl:SizeToContents()
local pw = self.PrefixLbl:GetWide()
local nw = self.NameLbl:GetWide()
local w = pw + nw + self.NameOffset
if self.maxWidth then
w = math.min( w, self.maxWidth )
-- Clips name label to the maximum width; looks kind of bad since the
-- ellipsis start too early for some reason.
-- nw = math.max( 0, w - self.NameOffset - pw )
-- self.NameLbl:SetWide( nw )
end
self:SetSize( w, self.Height )
self.PrefixLbl:AlignLeft( 0 )
self.NameLbl:MoveRightOf( self.PrefixLbl, self.NameOffset )
-- align text baselines
self.PrefixLbl:AlignBottom( 3 )
self.NameLbl:AlignBottom( 3 )
end
derma.DefineControl( "MP.AddedBy", "", ADDED_BY, "Panel" )
local SIDEBAR_BTN = {}
function SIDEBAR_BTN:Init()
self:SetDrawBackground( false )
self:SetDrawBorder( false )
self:SetStretchToFit( false )
self:SetCursor( "hand" )
self.m_Image = vgui.Create( "DImage", self )
self:SetText( "" )
self:SetColor( Color( 255, 255, 255, 255 ) )
self:SetSize( 21, 21 )
-- self:SetImage( "mediaplayer/ui/skip.png" )
end
function SIDEBAR_BTN:SetImage( strImage, strBackup )
self.m_Image:SetImage( strImage, strBackup )
self.m_Image.ActualWidth = self.m_iIconWidth or 21
self.m_Image.ActualHeight = self.m_iIconHeight or 21
end
function SIDEBAR_BTN:SetIconSize( w, h )
self.m_iIconWidth = w
self.m_iIconHeight = h
end
derma.DefineControl( "MP.SidebarButton", "", SIDEBAR_BTN, "DImageButton" )
local FAVORITE_BTN = {
FavStarOutlined = "mediaplayer/ui/fav_star_outline.png",
FavStar = "mediaplayer/ui/fav_star.png"
}
AccessorFunc( FAVORITE_BTN, "Favorited", "Favorited" )
function FAVORITE_BTN:Init()
self.BaseClass.Init( self )
self:SetImage( self.FavStarOutlined )
self:SetFavorited( false )
self.Outlined = true
end
function FAVORITE_BTN:Think()
if not self.Favorited then
local hovered = self:IsHovered()
if self.Outlined then
if hovered then
self:SetImage( self.FavStar )
self.Outlined = false
end
else
if not hovered then
self:SetImage( self.FavStarOutlined )
self.Outlined = true
end
end
end
end
function FAVORITE_BTN:DoClick()
-- TODO: Favorite media
end
derma.DefineControl( "MP.FavoriteButton", "", FAVORITE_BTN, "MP.SidebarButton" )
local SKIP_BTN = {}
function SKIP_BTN:Init()
self.BaseClass.Init( self )
self:SetIconSize( 16, 16 )
self:SetImage( "mediaplayer/ui/skip.png" )
end
function SKIP_BTN:DoClick()
-- TODO: Skip current media
end
derma.DefineControl( "MP.SkipButton", "", SKIP_BTN, "MP.SidebarButton" )
local REMOVE_BTN = {}
function REMOVE_BTN:Init()
self.BaseClass.Init( self )
self:SetIconSize( 17, 20 )
self:SetImage( "mediaplayer/ui/delete.png" )
end
function REMOVE_BTN:DoClick()
-- TODO: Remove current media
end
derma.DefineControl( "MP.RemoveButton", "", REMOVE_BTN, "MP.SidebarButton" )
|
Fixed errors with sidebar baseclass derma control.
|
Fixed errors with sidebar baseclass derma control.
|
Lua
|
mit
|
pixeltailgames/gm-mediaplayer,pixeltailgames/gm-mediaplayer
|
00b507509a9f2b73cea35b2fc6fc38632a225257
|
Concat.lua
|
Concat.lua
|
local Concat, parent = torch.class('nn.Concat', 'nn.Module')
function Concat:__init(dimension)
parent.__init(self)
self.modules = {}
self.size = torch.LongStorage()
self.dimension = dimension
end
function Concat:add(module)
table.insert(self.modules, module)
return self
end
function Concat:get(index)
return self.modules[index]
end
function Concat:updateOutput(input)
local outs = {}
for i=1,#self.modules do
local currentOutput = self.modules[i]:updateOutput(input)
outs[i] = currentOutput
if i == 1 then
self.size:resize(currentOutput:dim()):copy(currentOutput:size())
else
self.size[self.dimension] = self.size[self.dimension] + currentOutput:size(self.dimension)
end
end
self.output:resize(self.size)
local offset = 1
for i,module in ipairs(self.modules) do
local currentOutput = outs[i]
self.output:narrow(self.dimension, offset, currentOutput:size(self.dimension)):copy(currentOutput)
offset = offset + currentOutput:size(self.dimension)
end
return self.output
end
function Concat:updateGradInput(input, gradOutput)
self.gradInput:resizeAs(input)
local offset = 1
for i,module in ipairs(self.modules) do
local currentOutput = module.output
local currentGradInput = module:updateGradInput(input, gradOutput:narrow(self.dimension, offset, currentOutput:size(self.dimension)))
if i==1 then
self.gradInput:copy(currentGradInput)
else
self.gradInput:add(currentGradInput)
end
offset = offset + currentOutput:size(self.dimension)
end
return self.gradInput
end
function Concat:accGradParameters(input, gradOutput, scale)
scale = scale or 1
local offset = 1
for i,module in ipairs(self.modules) do
local currentOutput = module.output
local currentGradInput = module:accGradParameters(input,
gradOutput:narrow(self.dimension, offset, currentOutput:size(self.dimension)),
scale)
offset = offset + currentOutput:size(self.dimension)
end
end
function Concat:accUpdateGradParameters(input, gradOutput, lr)
local offset = 1
for i,module in ipairs(self.modules) do
local currentOutput = module.output
local currentGradInput = module:accUpdateGradParameters(input,
gradOutput:narrow(self.dimension, offset, currentOutput:size(self.dimension)),
lr)
offset = offset + currentOutput:size(self.dimension)
end
end
function Concat:zeroGradParameters()
for _,module in ipairs(self.modules) do
module:zeroGradParameters()
end
end
function Concat:updateParameters(learningRate)
for _,module in ipairs(self.modules) do
module:updateParameters(learningRate)
end
end
function Concat:training()
for i=1,#self.modules do
self.modules[i]:training()
end
end
function Concat:evaluate()
for i=1,#self.modules do
self.modules[i]:evaluate()
end
end
function Concat:share(mlp,...)
for i=1,#self.modules do
self.modules[i]:share(mlp.modules[i],...);
end
end
function Concat:parameters()
local function tinsert(to, from)
if type(from) == 'table' then
for i=1,#from do
tinsert(to,from[i])
end
else
table.insert(to,from)
end
end
local w = {}
local gw = {}
for i=1,#self.modules do
local mw,mgw = self.modules[i]:parameters()
if mw then
tinsert(w,mw)
tinsert(gw,mgw)
end
end
return w,gw
end
function Concat:__tostring__()
local tab = ' '
local line = '\n'
local next = ' |`-> '
local ext = ' | '
local extlast = ' '
local last = ' ... -> '
local str = 'nn.Concat'
str = str .. ' {' .. line .. tab .. 'input'
for i=1,#self.modules do
if i == self.modules then
str = str .. line .. tab .. next .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab .. extlast)
else
str = str .. line .. tab .. next .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab .. ext)
end
end
str = str .. line .. tab .. last .. 'output'
str = str .. line .. '}'
return str
end
|
local Concat, parent = torch.class('nn.Concat', 'nn.Module')
function Concat:__init(dimension)
parent.__init(self)
self.modules = {}
self.size = torch.LongStorage()
self.dimension = dimension
end
function Concat:add(module)
table.insert(self.modules, module)
return self
end
function Concat:get(index)
return self.modules[index]
end
function Concat:updateOutput(input)
local outs = {}
for i=1,#self.modules do
local currentOutput = self.modules[i]:updateOutput(input)
outs[i] = currentOutput
if i == 1 then
self.size:resize(currentOutput:dim()):copy(currentOutput:size())
else
self.size[self.dimension] = self.size[self.dimension] + currentOutput:size(self.dimension)
end
end
self.output:resize(self.size)
local offset = 1
for i,module in ipairs(self.modules) do
local currentOutput = outs[i]
self.output:narrow(self.dimension, offset, currentOutput:size(self.dimension)):copy(currentOutput)
offset = offset + currentOutput:size(self.dimension)
end
return self.output
end
function Concat:updateGradInput(input, gradOutput)
self.gradInput:resizeAs(input)
local offset = 1
for i,module in ipairs(self.modules) do
local currentOutput = module.output
local currentGradInput = module:updateGradInput(input, gradOutput:narrow(self.dimension, offset, currentOutput:size(self.dimension)))
if currentGradInput then -- if the module does not produce a gradInput (for example first layer), then ignore it and move on.
if i==1 then
self.gradInput:copy(currentGradInput)
else
self.gradInput:add(currentGradInput)
end
end
offset = offset + currentOutput:size(self.dimension)
end
return self.gradInput
end
function Concat:accGradParameters(input, gradOutput, scale)
scale = scale or 1
local offset = 1
for i,module in ipairs(self.modules) do
local currentOutput = module.output
local currentGradInput = module:accGradParameters(input,
gradOutput:narrow(self.dimension, offset, currentOutput:size(self.dimension)),
scale)
offset = offset + currentOutput:size(self.dimension)
end
end
function Concat:accUpdateGradParameters(input, gradOutput, lr)
local offset = 1
for i,module in ipairs(self.modules) do
local currentOutput = module.output
local currentGradInput = module:accUpdateGradParameters(input,
gradOutput:narrow(self.dimension, offset, currentOutput:size(self.dimension)),
lr)
offset = offset + currentOutput:size(self.dimension)
end
end
function Concat:zeroGradParameters()
for _,module in ipairs(self.modules) do
module:zeroGradParameters()
end
end
function Concat:updateParameters(learningRate)
for _,module in ipairs(self.modules) do
module:updateParameters(learningRate)
end
end
function Concat:training()
for i=1,#self.modules do
self.modules[i]:training()
end
end
function Concat:evaluate()
for i=1,#self.modules do
self.modules[i]:evaluate()
end
end
function Concat:share(mlp,...)
for i=1,#self.modules do
self.modules[i]:share(mlp.modules[i],...);
end
end
function Concat:parameters()
local function tinsert(to, from)
if type(from) == 'table' then
for i=1,#from do
tinsert(to,from[i])
end
else
table.insert(to,from)
end
end
local w = {}
local gw = {}
for i=1,#self.modules do
local mw,mgw = self.modules[i]:parameters()
if mw then
tinsert(w,mw)
tinsert(gw,mgw)
end
end
return w,gw
end
function Concat:__tostring__()
local tab = ' '
local line = '\n'
local next = ' |`-> '
local ext = ' | '
local extlast = ' '
local last = ' ... -> '
local str = 'nn.Concat'
str = str .. ' {' .. line .. tab .. 'input'
for i=1,#self.modules do
if i == self.modules then
str = str .. line .. tab .. next .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab .. extlast)
else
str = str .. line .. tab .. next .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab .. ext)
end
end
str = str .. line .. tab .. last .. 'output'
str = str .. line .. '}'
return str
end
|
fixing concat in the case when gradInput is not emmitted
|
fixing concat in the case when gradInput is not emmitted
|
Lua
|
bsd-3-clause
|
nicholas-leonard/nn,fmassa/nn,zhangxiangxiao/nn,Djabbz/nn,lvdmaaten/nn,adamlerer/nn,elbamos/nn,ominux/nn,caldweln/nn,noa/nn,vgire/nn,GregSatre/nn,joeyhng/nn,jzbontar/nn,davidBelanger/nn,hery/nn,bartvm/nn,kmul00/nn,apaszke/nn,xianjiec/nn,forty-2/nn,hughperkins/nn,clementfarabet/nn,andreaskoepf/nn,colesbury/nn,LinusU/nn,jonathantompson/nn,aaiijmrtt/nn,boknilev/nn,szagoruyko/nn,eulerreich/nn,sbodenstein/nn,karpathy/nn,PierrotLC/nn,eriche2016/nn,jhjin/nn,Moodstocks/nn,mys007/nn,lukasc-ch/nn,Aysegul/nn,PraveerSINGH/nn,witgo/nn,zchengquan/nn,abeschneider/nn,EnjoyHacking/nn,rickyHong/nn_lib_torch,mlosch/nn,douwekiela/nn,rotmanmi/nn,ivendrov/nn,diz-vara/nn,Jeffyrao/nn,sagarwaghmare69/nn,soumith/nn
|
4eb11633bc98b4bd7faf5c39d6e97b4c0657368e
|
game/scripts/vscripts/internal/events.lua
|
game/scripts/vscripts/internal/events.lua
|
-- The overall game state has changed
function GameMode:_OnGameRulesStateChange(keys)
if GameMode._reentrantCheck then
return
end
local newState = GameRules:State_Get()
if newState == DOTA_GAMERULES_STATE_WAIT_FOR_PLAYERS_TO_LOAD then
self.bSeenWaitForPlayers = true
elseif newState == DOTA_GAMERULES_STATE_INIT then
--Timers:RemoveTimer("alljointimer")
elseif newState == DOTA_GAMERULES_STATE_CUSTOM_GAME_SETUP then
GameMode:OnAllPlayersLoaded()
elseif newState == DOTA_GAMERULES_STATE_HERO_SELECTION then
GameMode:PostLoadPrecache()
elseif newState == DOTA_GAMERULES_STATE_GAME_IN_PROGRESS then
GameMode:OnGameInProgress()
end
GameMode._reentrantCheck = true
GameMode:OnGameRulesStateChange(keys)
GameMode._reentrantCheck = false
end
-- An NPC has spawned somewhere in game. This includes heroes
function GameMode:_OnNPCSpawned(keys)
if GameMode._reentrantCheck then
return
end
local npc = EntIndexToHScript(keys.entindex)
if npc:IsRealHero() and npc.bFirstSpawned == nil and HeroSelection:GetState() >= HERO_SELECTION_PHASE_END then
npc.bFirstSpawned = true
GameMode:OnHeroInGame(npc)
end
GameMode._reentrantCheck = true
GameMode:OnNPCSpawned(keys)
GameMode._reentrantCheck = false
end
-- An entity died
function GameMode:_OnEntityKilled( keys )
if GameMode._reentrantCheck then
return
end
-- The Unit that was Killed
local killedUnit = EntIndexToHScript( keys.entindex_killed )
-- The Killing entity
local killerEntity = nil
if keys.entindex_attacker ~= nil then
killerEntity = EntIndexToHScript( keys.entindex_attacker )
end
if killedUnit:IsRealHero() then
if killerEntity then
local team = killerEntity:GetTeam()
if Teams:IsEnabled(team) then
Teams:ModifyScore(team, Teams:GetTeamKillWeight(killedUnit:GetTeam()))
if END_GAME_ON_KILLS and Teams:GetScore(team) >= KILLS_TO_END_GAME_FOR_TEAM then
self:OnKillGoalReached(team)
end
end
end
end
GameMode._reentrantCheck = true
DebugCallFunction(function()
GameMode:OnEntityKilled(keys)
end)
GameMode._reentrantCheck = false
end
-- This function is called once when the player fully connects and becomes "Ready" during Loading
function GameMode:_OnConnectFull(keys)
if GameMode._reentrantCheck then
return
end
GameMode:_CaptureGameMode()
local entIndex = keys.index+1
-- The Player entity of the joining user
local ply = EntIndexToHScript(entIndex)
local userID = keys.userid
self.vUserIds = self.vUserIds or {}
self.vUserIds[userID] = ply
PLAYER_DATA[ply:GetPlayerID()].UserID = userID
GameMode._reentrantCheck = true
GameMode:OnConnectFull( keys )
GameMode._reentrantCheck = false
end
|
-- The overall game state has changed
function GameMode:_OnGameRulesStateChange(keys)
if GameMode._reentrantCheck then
return
end
local newState = GameRules:State_Get()
if newState == DOTA_GAMERULES_STATE_WAIT_FOR_PLAYERS_TO_LOAD then
self.bSeenWaitForPlayers = true
elseif newState == DOTA_GAMERULES_STATE_INIT then
--Timers:RemoveTimer("alljointimer")
elseif newState == DOTA_GAMERULES_STATE_CUSTOM_GAME_SETUP then
GameMode:OnAllPlayersLoaded()
elseif newState == DOTA_GAMERULES_STATE_HERO_SELECTION then
GameMode:PostLoadPrecache()
elseif newState == DOTA_GAMERULES_STATE_GAME_IN_PROGRESS then
GameMode:OnGameInProgress()
end
GameMode._reentrantCheck = true
GameMode:OnGameRulesStateChange(keys)
GameMode._reentrantCheck = false
end
-- An NPC has spawned somewhere in game. This includes heroes
function GameMode:_OnNPCSpawned(keys)
if GameMode._reentrantCheck then
return
end
local npc = EntIndexToHScript(keys.entindex)
if npc:IsRealHero() and npc.bFirstSpawned == nil and HeroSelection:GetState() >= HERO_SELECTION_PHASE_END then
npc.bFirstSpawned = true
GameMode:OnHeroInGame(npc)
end
GameMode._reentrantCheck = true
GameMode:OnNPCSpawned(keys)
GameMode._reentrantCheck = false
end
-- An entity died
function GameMode:_OnEntityKilled(keys)
if GameMode._reentrantCheck then
return
end
-- The Unit that was Killed
local killedUnit = EntIndexToHScript( keys.entindex_killed )
-- The Killing entity
local killerEntity = nil
if keys.entindex_attacker ~= nil then
killerEntity = EntIndexToHScript( keys.entindex_attacker )
end
if killedUnit:IsRealHero() then
if killerEntity then
local killerTeam = killerEntity:GetTeam()
local killedTeam = killedUnit:GetTeam()
if killerTeam ~= killedTeam and Teams:IsEnabled(killerTeam) then
Teams:ModifyScore(killerTeam, Teams:GetTeamKillWeight(killedTeam))
if END_GAME_ON_KILLS and Teams:GetScore(killerTeam) >= KILLS_TO_END_GAME_FOR_TEAM then
self:OnKillGoalReached(killerTeam)
end
end
end
end
GameMode._reentrantCheck = true
DebugCallFunction(function()
GameMode:OnEntityKilled(keys)
end)
GameMode._reentrantCheck = false
end
-- This function is called once when the player fully connects and becomes "Ready" during Loading
function GameMode:_OnConnectFull(keys)
if GameMode._reentrantCheck then
return
end
GameMode:_CaptureGameMode()
local entIndex = keys.index+1
-- The Player entity of the joining user
local ply = EntIndexToHScript(entIndex)
local userID = keys.userid
self.vUserIds = self.vUserIds or {}
self.vUserIds[userID] = ply
PLAYER_DATA[ply:GetPlayerID()].UserID = userID
GameMode._reentrantCheck = true
GameMode:OnConnectFull( keys )
GameMode._reentrantCheck = false
end
|
Fixed killing players from one team gave score points
|
Fixed killing players from one team gave score points
|
Lua
|
mit
|
ark120202/aabs
|
394612dd18e431cbc3cf2960ccc24782a91fe504
|
lua/entities/gmod_wire_turret.lua
|
lua/entities/gmod_wire_turret.lua
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Turret"
ENT.WireDebugName = "Turret"
if ( CLIENT ) then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self:DrawShadow( false )
self:SetCollisionGroup( COLLISION_GROUP_WEAPON )
local phys = self:GetPhysicsObject()
if ( phys:IsValid() ) then
phys:Wake()
end
-- Allocating internal values on initialize
self.NextShot = 0
self.Firing = false
self.spreadvector = Vector()
self.effectdata = EffectData()
self.Inputs = WireLib.CreateSpecialInputs(self,
{ "Fire", "Force", "Damage", "NumBullets", "Spread", "Delay", "Sound", "Tracer" },
{ "NORMAL", "NORMAL", "NORMAL", "NORMAL", "NORMAL", "NORMAL", "STRING", "STRING" })
self.Outputs = WireLib.CreateSpecialOutputs(self, { "HitEntity" }, { "ENTITY" })
end
function ENT:FireShot()
if ( self.NextShot > CurTime() ) then return end
self.NextShot = CurTime() + self.delay
-- Make a sound if you want to.
if ( self.sound ) then
self:EmitSound( self.sound )
end
-- Get the muzzle attachment (this is pretty much always 1)
local Attachment = self:GetAttachment( 1 )
-- Get the shot angles and stuff.
local shootOrigin = Attachment.Pos + self:GetVelocity() * engine.TickInterval()
local shootAngles = self:GetAngles()
-- Shoot a bullet
local bullet = {}
bullet.Num = self.numbullets
bullet.Src = shootOrigin
bullet.Dir = shootAngles:Forward()
bullet.Spread = self.spreadvector
bullet.Tracer = self.tracernum
bullet.TracerName = self.tracer
bullet.Force = self.force
bullet.Damage = self.damage
bullet.Attacker = self:GetPlayer()
bullet.Callback = function(attacker, traceres, cdamageinfo)
WireLib.TriggerOutput(self, "HitEntity", traceres.Entity)
end
self:FireBullets( bullet )
-- Make a muzzle flash
self.effectdata:SetOrigin( shootOrigin )
self.effectdata:SetAngles( shootAngles )
self.effectdata:SetScale( 1 )
util.Effect( "MuzzleEffect", self.effectdata )
end
function ENT:OnTakeDamage( dmginfo )
self:TakePhysicsDamage( dmginfo )
end
function ENT:Think()
BaseClass.Think(self)
if ( self.Firing ) then
self:FireShot()
end
self:NextThink(CurTime())
return true
end
local ValidTracers = {
["Tracer"] = true,
["AR2Tracer"] = true,
["AirboatGunHeavyTracer"] = true,
["LaserTracer"] = true,
[""] = true
}
function ENT:SetSound(sound)
local check = string.find( sound, "[\"?]" ) -- Preventing client crashes
self.sound = check and "" or sound
end
function ENT:SetDelay(delay)
local check = game.SinglePlayer() -- clamp delay if it's not single player
local limit = check and 0.01 or 0.05
self.delay = math.Clamp( delay, limit, 1 )
end
function ENT:SetNumBullets(numbullets)
local check = game.SinglePlayer() -- clamp num bullets if it's not single player
local limit = math.floor( math.max( 1, numbullets ) )
self.numbullets = check and limit or math.Clamp( limit, 1, 10 )
end
function ENT:SetTracer(tracer)
local tracer = string.Trim(tracer)
self.tracer = ValidTracers[tracer] and tracer or ""
end
function ENT:SetSpread(spread)
self.spread = math.Clamp( spread, 0, 1 )
self.spreadvector.x = self.spread
self.spreadvector.y = self.spread
end
function ENT:SetDamage(damage)
self.damage = math.Clamp( damage, 0, 100 )
end
function ENT:SetForce(force)
self.force = math.Clamp( force, 0, 500 )
end
function ENT:SetTraceNum(tracernum)
self.tracernum = math.floor( math.max( tracernum or 1 ) )
end
function ENT:TriggerInput(iname, value)
if (iname == "Fire") then
self.Firing = value > 0
elseif (iname == "Force") then
self:SetForce( value )
elseif (iname == "Damage") then
self:SetDamage( value )
elseif (iname == "NumBullets") then
self:SetNumBullets( value )
elseif (iname == "Spread") then
self:SetSpread( value )
elseif (iname == "Delay") then
self:SetDelay( value )
elseif (iname == "Sound") then
self:SetSound( value )
elseif (iname == "Tracer") then
self:SetTracer( value )
end
end
function ENT:Setup(delay, damage, force, sound, numbullets, spread, tracer, tracernum)
self:SetForce(force)
self:SetDelay(delay)
self:SetSound(sound)
self:SetDamage(damage)
self:SetSpread(spread)
self:SetTracer(tracer)
self:SetTraceNum(tracernum)
self:SetNumBullets(numbullets)
end
duplicator.RegisterEntityClass( "gmod_wire_turret", WireLib.MakeWireEnt, "Data", "delay", "damage", "force", "sound", "numbullets", "spread", "tracer", "tracernum" )
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Turret"
ENT.WireDebugName = "Turret"
if ( CLIENT ) then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self:DrawShadow( false )
self:SetCollisionGroup( COLLISION_GROUP_WEAPON )
local phys = self:GetPhysicsObject()
if ( phys:IsValid() ) then
phys:Wake()
end
-- Allocating internal values on initialize
self.NextShot = 0
self.Firing = false
self.spreadvector = Vector()
self.effectdata = EffectData()
self.Inputs = WireLib.CreateSpecialInputs(self,
{ "Fire", "Force", "Damage", "NumBullets", "Spread", "Delay", "Sound", "Tracer" },
{ "NORMAL", "NORMAL", "NORMAL", "NORMAL", "NORMAL", "NORMAL", "STRING", "STRING" })
self.Outputs = WireLib.CreateSpecialOutputs(self, { "HitEntity" }, { "ENTITY" })
end
function ENT:FireShot()
if ( self.NextShot > CurTime() ) then return end
self.NextShot = CurTime() + self.delay
-- Make a sound if you want to.
if ( self.sound ) then
self:EmitSound( self.sound )
end
-- Get the muzzle attachment (this is pretty much always 1)
local Attachment = self:GetAttachment( 1 )
-- Get the shot angles and stuff.
local shootOrigin = Attachment.Pos + self:GetVelocity() * engine.TickInterval()
local shootAngles = self:GetAngles()
-- Shoot a bullet
local bullet = {}
bullet.Num = self.numbullets
bullet.Src = shootOrigin
bullet.Dir = shootAngles:Forward()
bullet.Spread = self.spreadvector
bullet.Tracer = self.tracernum
bullet.TracerName = self.tracer
bullet.Force = self.force
bullet.Damage = self.damage
bullet.Attacker = self:GetPlayer()
bullet.Callback = function(attacker, traceres, cdamageinfo)
WireLib.TriggerOutput(self, "HitEntity", traceres.Entity)
end
self:FireBullets( bullet )
-- Make a muzzle flash
self.effectdata:SetOrigin( shootOrigin )
self.effectdata:SetAngles( shootAngles )
self.effectdata:SetScale( 1 )
util.Effect( "MuzzleEffect", self.effectdata )
end
function ENT:OnTakeDamage( dmginfo )
self:TakePhysicsDamage( dmginfo )
end
function ENT:Think()
BaseClass.Think(self)
if ( self.Firing ) then
self:FireShot()
end
self:NextThink(CurTime())
return true
end
local ValidTracers = {
["Tracer"] = true,
["AR2Tracer"] = true,
["AirboatGunHeavyTracer"] = true,
["LaserTracer"] = true,
[""] = true
}
function ENT:SetSound( sound )
local sound = tostring( sound or "" )
sound = string.Trim( sound ) -- The string cannot have whitespace
local check = string.find( sound, "[\"?]" ) -- Preventing client crashes
sound = check and "" or sound
self.sound = ( sound ~= "" ) and sound or nil
end
function ENT:SetDelay( delay )
local check = game.SinglePlayer() -- clamp delay if it's not single player
local limit = check and 0.01 or 0.05
self.delay = math.Clamp( delay, limit, 1 )
end
function ENT:SetNumBullets( numbullets )
local check = game.SinglePlayer() -- clamp num bullets if it's not single player
local limit = math.floor( math.max( 1, numbullets ) )
self.numbullets = check and limit or math.Clamp( limit, 1, 10 )
end
function ENT:SetTracer( tracer )
local tracer = string.Trim(tracer)
self.tracer = ValidTracers[tracer] and tracer or ""
end
function ENT:SetSpread( spread )
self.spread = math.Clamp( spread, 0, 1 )
self.spreadvector.x = self.spread
self.spreadvector.y = self.spread
end
function ENT:SetDamage( damage )
self.damage = math.Clamp( damage, 0, 100 )
end
function ENT:SetForce( force )
self.force = math.Clamp( force, 0, 500 )
end
function ENT:SetTraceNum( tracernum )
self.tracernum = math.floor( math.max( tracernum or 1 ) )
end
function ENT:TriggerInput( iname, value )
if (iname == "Fire") then
self.Firing = value > 0
elseif (iname == "Force") then
self:SetForce( value )
elseif (iname == "Damage") then
self:SetDamage( value )
elseif (iname == "NumBullets") then
self:SetNumBullets( value )
elseif (iname == "Spread") then
self:SetSpread( value )
elseif (iname == "Delay") then
self:SetDelay( value )
elseif (iname == "Sound") then
self:SetSound( value )
elseif (iname == "Tracer") then
self:SetTracer( value )
end
end
function ENT:Setup(delay, damage, force, sound, numbullets, spread, tracer, tracernum)
self:SetForce(force)
self:SetDelay(delay)
self:SetSound(sound)
self:SetDamage(damage)
self:SetSpread(spread)
self:SetTracer(tracer)
self:SetTraceNum(tracernum)
self:SetNumBullets(numbullets)
end
duplicator.RegisterEntityClass( "gmod_wire_turret", WireLib.MakeWireEnt, "Data", "delay", "damage", "force", "sound", "numbullets", "spread", "tracer", "tracernum" )
|
Optimized: Internal sound is the same as `nil` when empty string is used Fixed: Force trimming on the sound path according to the manual
|
Optimized: Internal sound is the same as `nil` when empty string is used
Fixed: Force trimming on the sound path according to the manual
|
Lua
|
apache-2.0
|
wiremod/wire,dvdvideo1234/wire,Grocel/wire
|
68a444cc560e46a4aeb032f4d461968e41e616cf
|
demo/videocap.lua
|
demo/videocap.lua
|
-- a translated demo from here:
-- http://docs.opencv.org/3.0-beta/modules/videoio/doc/reading_and_writing_video.html
local cv = require 'cv'
require 'cv.highgui'
require 'cv.videoio'
require 'cv.imgproc'
local cap = cv.VideoCapture{device=0}
if not cap:isOpened() then
print("Failed to open the default camera")
os.exit(-1)
end
cv.namedWindow{"edges", cv.WINDOW_AUTOSIZE}
local _, frame = cap:read{}
local edges
while true do
edges = cv.cvtColor{frame, cv.COLOR_BGR2GRAY}
cv.GaussianBlur{
edges,
edges,
ksize = {7,7},
sigmaX = 1.5,
sigmaY = 1.5
}
cv.Canny{
edges,
edges,
threshold1 = 0,
threshold2 = 30,
apertureSize = 3
}
cv.imshow{"edges", edges}
if cv.waitKey{30} >= 0 then break end
cap:read{frame}
end
|
-- a translated demo from here:
-- http://docs.opencv.org/3.0-beta/modules/videoio/doc/reading_and_writing_video.html
local cv = require 'cv'
require 'cv.highgui'
require 'cv.videoio'
require 'cv.imgproc'
local cap = cv.VideoCapture{device=0}
if not cap:isOpened() then
print("Failed to open the default camera")
os.exit(-1)
end
cv.namedWindow{"edges", cv.WINDOW_AUTOSIZE}
local _, frame = cap:read{}
-- make a tensor of same type, but a 2-dimensional one
local edges = frame.new(frame:size()[1], frame:size()[2])
while true do
cv.cvtColor{frame, edges, cv.COLOR_BGR2GRAY}
cv.GaussianBlur{
edges,
edges,
ksize = {7,7},
sigmaX = 1.5,
sigmaY = 1.5
}
cv.Canny{
edges,
edges,
threshold1 = 0,
threshold2 = 30,
apertureSize = 3
}
cv.imshow{"edges", edges}
if cv.waitKey{30} >= 0 then break end
cap:read{frame}
end
|
Fix #52
|
Fix #52
|
Lua
|
mit
|
VisionLabs/torch-opencv
|
93df2296595fb5dfa2748da312c03ca4f6b1e449
|
src/app/scenes/RectBoyScene.lua
|
src/app/scenes/RectBoyScene.lua
|
-- Author: Hua Liang[Stupid ET] <[email protected]>
local RectBoyScene = class("RectBoyScene", function()
local scene = cc.Scene:create()
scene.name = "RectBoyScene"
return scene
end)
function RectBoyScene:ctor()
local schedulerID = 0
local visibleSize = cc.Director:getInstance():getVisibleSize()
local origin = cc.Director:getInstance():getVisibleOrigin()
local layer = cc.LayerColor:create(cc.c4b(255, 255, 255, 255))
local function bindEvent()
local function onTouchEnded(touch, event)
local location = touch:getLocation()
local x, y = layer.boy:getPosition()
layer.boy:setPositionY(y + 50)
end
local touchListener = cc.EventListenerTouchOneByOne:create()
touchListener:registerScriptHandler(function() return true end, cc.Handler.EVENT_TOUCH_BEGAN)
touchListener:registerScriptHandler(onTouchEnded, cc.Handler.EVENT_TOUCH_ENDED)
local eventDispatcher = layer:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer)
end
local function createRectBoy()
local textureBoy = cc.Director:getInstance():getTextureCache():addImage("boy.png")
local rect = cc.rect(0, 0, 40, 40)
local frame0 = cc.SpriteFrame:createWithTexture(textureBoy, rect)
rect = cc.rect(40, 0, 40, 40)
local frame1 = cc.SpriteFrame:createWithTexture(textureBoy, rect)
local spriteBoy = cc.Sprite:createWithSpriteFrame(frame0)
local size = spriteBoy:getContentSize()
local animation = cc.Animation:createWithSpriteFrames({frame0,frame1}, 0.1)
local animate = cc.Animate:create(animation);
spriteBoy:runAction(cc.RepeatForever:create(animate))
spriteBoy:setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 4 * 3)
spriteBoy.speed = 0
return spriteBoy
end
local function onEnter()
bindEvent()
local boy = createRectBoy()
layer:addChild(boy)
layer.boy = boy
local function tick(dt)
local scale = 10
local g = 9.8 * scale
local x, y = boy:getPosition()
local size = boy:getContentSize()
local lowest = origin.y + size.height / 2
local t = dt
local distance = boy.speed * t
boy.speed = boy.speed + g * t
if y < lowest then
y = lowest
boy.speed = 0
else
y = y - distance
end
boy:setPositionY(y)
end
schedulerID = cc.Director:getInstance():getScheduler():scheduleScriptFunc(tick, 0, false)
end
local function onNodeEvent(event)
if "enter" == event then
onEnter()
end
end
layer:registerScriptHandler(onNodeEvent)
self:addChild(layer)
end
return RectBoyScene
|
-- Author: Hua Liang[Stupid ET] <[email protected]>
local RectBoyScene = class("RectBoyScene", function()
local scene = cc.Scene:create()
scene.name = "RectBoyScene"
return scene
end)
function RectBoyScene:ctor()
local schedulerID = 0
local visibleSize = cc.Director:getInstance():getVisibleSize()
local origin = cc.Director:getInstance():getVisibleOrigin()
local layer = cc.LayerColor:create(cc.c4b(255, 255, 255, 255))
local function bindEvent()
local function onTouchEnded(touch, event)
local location = touch:getLocation()
local x, y = layer.boy:getPosition()
layer.boy:setPositionY(y + 50)
layer.boy.speed = 0
end
local touchListener = cc.EventListenerTouchOneByOne:create()
touchListener:registerScriptHandler(function() return true end, cc.Handler.EVENT_TOUCH_BEGAN)
touchListener:registerScriptHandler(onTouchEnded, cc.Handler.EVENT_TOUCH_ENDED)
local eventDispatcher = layer:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer)
end
local function createRectBoy()
local textureBoy = cc.Director:getInstance():getTextureCache():addImage("boy.png")
local rect = cc.rect(0, 0, 40, 40)
local frame0 = cc.SpriteFrame:createWithTexture(textureBoy, rect)
rect = cc.rect(40, 0, 40, 40)
local frame1 = cc.SpriteFrame:createWithTexture(textureBoy, rect)
local spriteBoy = cc.Sprite:createWithSpriteFrame(frame0)
local size = spriteBoy:getContentSize()
local animation = cc.Animation:createWithSpriteFrames({frame0,frame1}, 0.1)
local animate = cc.Animate:create(animation);
spriteBoy:runAction(cc.RepeatForever:create(animate))
spriteBoy:setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 4 * 3)
spriteBoy.speed = 0
return spriteBoy
end
local function onEnter()
bindEvent()
local boy = createRectBoy()
layer:addChild(boy)
layer.boy = boy
local function tick(dt)
local scale = 10
local g = 9.8 * scale
local x, y = boy:getPosition()
local size = boy:getContentSize()
local lowest = origin.y + size.height / 2
local t = dt
local distance = boy.speed * t
boy.speed = boy.speed + g * t
if y < lowest then
y = lowest
boy.speed = 0
else
y = y - distance
end
boy:setPositionY(y)
end
schedulerID = cc.Director:getInstance():getScheduler():scheduleScriptFunc(tick, 0, false)
end
local function onNodeEvent(event)
if "enter" == event then
onEnter()
end
end
layer:registerScriptHandler(onNodeEvent)
self:addChild(layer)
end
return RectBoyScene
|
fix bug of speed of boy
|
fix bug of speed of boy
|
Lua
|
apache-2.0
|
cedricporter/everlost,cedricporter/everlost,cedricporter/everlost,cedricporter/everlost,cedricporter/everlost,cedricporter/everlost
|
119a5b069b9aaba108c4eef7ff817e952eb2a2f9
|
nyagos.d/open.lua
|
nyagos.d/open.lua
|
nyagos.alias("open",function(args)
local count=0
for i=1,#args do
local list=nyagos.glob(args[i])
if list and #list >= 1 then
for i=1,#list do
assert(nyagos.shellexecute("open",list[i]))
end
else
if nyagos.access(args[i],0) then
assert(nyagos.shellexecute("open",args[i]))
else
print(args[i] .. ": can not get status")
end
end
count = count +1
end
if count <= 0 then
if nyagos.access(".\\open.cmd",0) then
nyagos.exec("open.cmd")
else
assert(nyagos.shellexecute("open","."))
end
end
end)
|
nyagos.alias("open",function(args)
local count=0
for i=1,#args do
local list=nyagos.glob(args[i])
if list and #list >= 1 then
for i=1,#list do
local fd = io.open(list[i])
if fd then
fd:close()
assert(nyagos.shellexecute("open",list[i]))
else
nyagos.writerr(list[i]..": not found.\n")
end
end
else
local fd = io.open(args[i])
if fd then
fd:close()
assert(nyagos.shellexecute("open",args[i]))
else
print(args[i] .. ": not found.\n")
end
end
count = count +1
end
if count <= 0 then
local fd = io.open("open.cmd")
if fd then
fd:close()
nyagos.exec("open.cmd")
else
assert(nyagos.shellexecute("open","."))
end
end
end)
|
Fixed open.lua did not print error when wildcard did not match anyfiles.
|
Fixed open.lua did not print error when wildcard did not match anyfiles.
|
Lua
|
bsd-3-clause
|
kissthink/nyagos,tyochiai/nyagos,kissthink/nyagos,hattya/nyagos,zetamatta/nyagos,kissthink/nyagos,nocd5/nyagos,hattya/nyagos,hattya/nyagos,tsuyoshicho/nyagos
|
d69c23c3c530ad08b21faf7525c508f6d829bff7
|
kong/plugins/acme/handler.lua
|
kong/plugins/acme/handler.lua
|
local BasePlugin = require("kong.plugins.base_plugin")
local kong_certificate = require("kong.runloop.certificate")
local client = require("kong.plugins.acme.client")
if kong.configuration.database == "off" then
error("acme can't be used in Kong dbless mode currently")
end
local acme_challenge_path = [[^/\.well-known/acme-challenge/(.+)]]
-- cache for dummy cert kong generated (it's a table)
local default_cert_key
local LetsencryptHandler = BasePlugin:extend()
LetsencryptHandler.PRIORITY = 1000
LetsencryptHandler.VERSION = "0.0.1"
function LetsencryptHandler:new()
LetsencryptHandler.super.new(self, "acme")
end
function LetsencryptHandler:init_worker()
LetsencryptHandler.super.init_worker(self, "acme")
kong.log.info("acme renew timer started")
ngx.timer.every(86400, client.renew_certificate)
end
-- access phase is to terminate the http-01 challenge request if necessary
function LetsencryptHandler:access(conf)
LetsencryptHandler.super.access(self)
local protocol = kong.client.get_protocol()
-- http-01 challenge only sends to http port
if protocol == 'http' then
local captures, err =
ngx.re.match(kong.request.get_path(), acme_challenge_path, "jo")
if err then
kong.log(kong.WARN, "error matching acme-challenge uri: ", err)
return
end
if captures then
local acme_client, err = client.new(conf)
if err then
kong.log.err("failed to create acme client:", err)
return
end
acme_client:serve_http_challenge()
end
return
end
if protocol ~= 'https' and protocol ~= 'grpcs' then
kong.log.debug("skipping because request is protocol: ", protocol)
return
end
local host = kong.request.get_host()
-- if current request is not serving challenge, do normal proxy pass
-- but check what cert did we used to serve request
local cert_and_key, err = kong_certificate.find_certificate(host)
if err then
kong.log.err("error find certificate for current request:", err)
return
end
if not default_cert_key then
-- hack: find_certificate() returns default cert and key if no sni defined
default_cert_key = kong_certificate.find_certificate()
end
-- note we compare the table address, this relies on the fact that Kong doesn't
-- copy the default cert table around
if cert_and_key ~= default_cert_key then
kong.log.debug("skipping because non-default cert is served")
return
end
-- TODO: do we match the whitelist?
ngx.timer.at(0, function()
err = client.update_certificate(conf, host, nil)
if err then
kong.log.err("failed to update certificate: ", err)
return
end
err = client.store_renew_config(conf, host)
if err then
kong.log.err("failed to store renew config: ", err)
return
end
end)
end
return LetsencryptHandler
|
local kong_certificate = require("kong.runloop.certificate")
local client = require("kong.plugins.acme.client")
if kong.configuration.database == "off" then
error("acme can't be used in Kong dbless mode currently")
end
local acme_challenge_path = [[^/\.well-known/acme-challenge/(.+)]]
-- cache for dummy cert kong generated (it's a table)
local default_cert_key
local LetsencryptHandler = {}
LetsencryptHandler.PRIORITY = 1000
LetsencryptHandler.VERSION = "0.1.0"
function LetsencryptHandler:init_worker()
kong.log.info("acme renew timer started")
ngx.timer.every(86400, client.renew_certificate)
end
-- access phase is to terminate the http-01 challenge request if necessary
function LetsencryptHandler:access(conf)
local protocol = kong.client.get_protocol()
-- http-01 challenge only sends to http port
if protocol == 'http' then
local captures, err =
ngx.re.match(kong.request.get_path(), acme_challenge_path, "jo")
if err then
kong.log(kong.WARN, "error matching acme-challenge uri: ", err)
return
end
if captures then
local acme_client, err = client.new(conf)
if err then
kong.log.err("failed to create acme client:", err)
return
end
acme_client:serve_http_challenge()
end
return
end
if protocol ~= 'https' and protocol ~= 'grpcs' then
kong.log.debug("skipping because request is protocol: ", protocol)
return
end
local host = kong.request.get_host()
-- if current request is not serving challenge, do normal proxy pass
-- but check what cert did we used to serve request
local cert_and_key, err = kong_certificate.find_certificate(host)
if err then
kong.log.err("error find certificate for current request:", err)
return
end
if not default_cert_key then
-- hack: find_certificate() returns default cert and key if no sni defined
default_cert_key = kong_certificate.find_certificate()
end
-- note we compare the table address, this relies on the fact that Kong doesn't
-- copy the default cert table around
if cert_and_key ~= default_cert_key then
kong.log.debug("skipping because non-default cert is served")
return
end
-- TODO: do we match the whitelist?
ngx.timer.at(0, function()
err = client.update_certificate(conf, host, nil)
if err then
kong.log.err("failed to update certificate: ", err)
return
end
err = client.store_renew_config(conf, host)
if err then
kong.log.err("failed to store renew config: ", err)
return
end
end)
end
return LetsencryptHandler
|
fix(acme) remove BasePlugin dependency (#3)
|
fix(acme) remove BasePlugin dependency (#3)
Inheriting from BasePlugin is no longer needed and can cause
performance drop.
See #2
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
da95579ce3b117717d419d421c8a670fd3c50ded
|
utils.lua
|
utils.lua
|
local utils = {}
-- a script to simplify trained net by incorporating every Spatial/VolumetricBatchNormalization
-- to Spatial/VolumetricConvolution and BatchNormalization to Linear
local function BNtoConv(net)
for i,v in ipairs(net.modules) do
if v.modules then
BNtoConv(v)
else
local cur = v
local pre = net:get(i-1)
if prev and
((torch.typename(cur):find'nn.SpatialBatchNormalization' and
torch.typename(pre):find'nn.SpatialConvolution') or
(torch.typename(cur):find'nn.BatchNormalization' and
torch.typename(pre):find'nn.Linear') or
(torch.typename(cur):find'nn.VolumetricBatchNormalization' and
torch.typename(pre):find'nn.VolumetricConvolution')) then
local conv = pre
local bn = v
net:remove(i)
local no = conv.nOutputPlane
local conv_w = conv.weight:view(no,-1)
cutorch.withDevice(conv_w:getDevice(), function()
if bn.running_var then
bn.running_std = bn.running_var:add(bn.eps):pow(-0.5)
end
if not conv.bias then
conv.bias = bn.running_mean:clone():zero()
conv.gradBias = conv.bias:clone()
end
conv_w:cmul(bn.running_std:view(no,-1):expandAs(conv_w))
conv.bias:add(-1,bn.running_mean):cmul(bn.running_std)
if bn.affine then
conv.bias:cmul(bn.weight):add(bn.bias)
conv_w:cmul(bn.weight:view(no,-1):expandAs(conv_w))
end
if conv.resetWeightDescriptors then
conv:resetWeightDescriptors()
assert(conv.biasDesc)
end
end)
end
end
end
end
local checklist = {
'nn.SpatialBatchNormalization',
'nn.VolumetricBatchNormalization',
'nn.BatchNormalization',
'cudnn.SpatialBatchNormalization',
'cudnn.VolumetricBatchNormalization',
'cudnn.BatchNormalization',
}
function utils.foldBatchNorm(net)
-- works in place!
BNtoConv(net)
BNtoConv(net)
for i,v in ipairs(checklist) do
assert(#net:findModules(v) == 0)
end
end
function utils.testSurgery(input, f, net, ...)
local output1 = net:forward(input):clone()
f(net,...)
local output2 = net:forward(input):clone()
local err = (output1 - output2):abs():max()
return err
end
return utils
|
local utils = {}
-- a script to simplify trained net by incorporating every Spatial/VolumetricBatchNormalization
-- to Spatial/VolumetricConvolution and BatchNormalization to Linear
local function BNtoConv(net)
for i,v in ipairs(net.modules) do
if v.modules then
BNtoConv(v)
else
local cur = v
local pre = net:get(i-1)
if prev and
((torch.typename(cur):find'nn.SpatialBatchNormalization' and
torch.typename(pre):find'nn.SpatialConvolution') or
(torch.typename(cur):find'nn.BatchNormalization' and
torch.typename(pre):find'nn.Linear') or
(torch.typename(cur):find'nn.VolumetricBatchNormalization' and
torch.typename(pre):find'nn.VolumetricConvolution')) then
local conv = pre
local bn = v
net:remove(i)
local no = conv.nOutputPlane
local conv_w = conv.weight:view(no,-1)
cutorch.withDevice(conv_w:getDevice(), function()
local invstd = bn.running_var and (bn.running_var + bn.eps):pow(-0.5) or bn.running_std
if not conv.bias then
conv.bias = bn.running_mean:clone():zero()
conv.gradBias = conv.bias:clone()
end
conv_w:cmul(invstd:view(no,-1):expandAs(conv_w))
conv.bias:add(-1,bn.running_mean):cmul(invstd)
if bn.affine then
conv.bias:cmul(bn.weight):add(bn.bias)
conv_w:cmul(bn.weight:view(no,-1):expandAs(conv_w))
end
if conv.resetWeightDescriptors then
conv:resetWeightDescriptors()
assert(conv.biasDesc)
end
end)
end
end
end
end
local checklist = {
'nn.SpatialBatchNormalization',
'nn.VolumetricBatchNormalization',
'nn.BatchNormalization',
'cudnn.SpatialBatchNormalization',
'cudnn.VolumetricBatchNormalization',
'cudnn.BatchNormalization',
}
function utils.foldBatchNorm(net)
-- works in place!
BNtoConv(net)
BNtoConv(net)
for i,v in ipairs(checklist) do
assert(#net:findModules(v) == 0)
end
end
function utils.testSurgery(input, f, net, ...)
local output1 = net:forward(input):clone()
f(net,...)
local output2 = net:forward(input):clone()
local err = (output1 - output2):abs():max()
return err
end
return utils
|
fix for foldBN
|
fix for foldBN
|
Lua
|
bsd-3-clause
|
szagoruyko/imagine-nn
|
674867629d2858f3acb7889c0dab783af39d7b2b
|
packages/cropmarks.lua
|
packages/cropmarks.lua
|
SILE.require("packages/frametricks")
SILE.registerCommand("crop:setup", function (o,c)
local papersize = SU.required(o, "papersize", "setting up crop marks")
local size = SILE.paperSizeParser(papersize)
local oldsize = SILE.documentState.paperSize
SILE.documentState.paperSize = size
local offsetx = ( SILE.documentState.paperSize[1] - oldsize[1] ) /2
local offsety = ( SILE.documentState.paperSize[2] - oldsize[2] ) /2
local page = SILE.getFrame("page")
page:constrain("right", page:right() + offsetx)
page:constrain("left", offsetx)
page:constrain("bottom", page:bottom() + offsety)
page:constrain("top", offsety)
if SILE.scratch.masters then
for k,v in pairs(SILE.scratch.masters) do
reconstrainFrameset(v.frames)
end
else
reconstrainFrameset(SILE.documentState.documentClass.pageTemplate.frames)
end
reconstrainFrameset(SILE.frames)
if SILE.typesetter.frame then SILE.typesetter.frame:init() end
end)
function reconstrainFrameset(fs)
for n,f in pairs(fs) do
if n ~= "page" then
if f:isAbsoluteConstraint("right") then
f.constraints.right = "left(page) + (" .. f.constraints.right .. ")"
end
if f:isAbsoluteConstraint("left") then
f.constraints.left = "left(page) + (" .. f.constraints.left .. ")"
end
if f:isAbsoluteConstraint("top") then
f.constraints.top = "top(page) + (" .. f.constraints.top .. ")"
end
if f:isAbsoluteConstraint("bottom") then
f.constraints.bottom = "top(page) + (" .. f.constraints.bottom .. ")"
end
f:invalidate()
end
end
end
|
local outcounter = 1
local outputMarks = function()
local page = SILE.getFrame("page")
SILE.outputter.rule(page:left() - 10, page:top(), -10, 0.5)
SILE.outputter.rule(page:left(), page:top() - 10, 0.5, -10)
SILE.outputter.rule(page:right() + 10, page:top(), 10, 0.5)
SILE.outputter.rule(page:right(), page:top() - 10, 0.5, -10)
SILE.outputter.rule(page:left() - 10, page:bottom(), -10, 0.5)
SILE.outputter.rule(page:left(), page:bottom() + 10, 0.5, 10)
SILE.outputter.rule(page:right() + 10, page:bottom(), 10, 0.5)
SILE.outputter.rule(page:right(), page:bottom() + 10, 0.5, 10)
local info = SILE.masterFilename .. " - " .. os.date("%x %X") .. " - " .. outcounter
SILE.call("hbox", {}, {info})
local hbox = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes]
SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] = nil
SILE.typesetter.frame.state.cursorX = page:left()
SILE.typesetter.frame.state.cursorY = page:top() - 30
outcounter = outcounter + 1
for i=1,#(hbox.value) do hbox.value[i]:outputYourself(SILE.typesetter, {ratio=1}) end
end
local function reconstrainFrameset(fs)
for n,f in pairs(fs) do
if n ~= "page" then
if f:isAbsoluteConstraint("right") then
f.constraints.right = "left(page) + (" .. f.constraints.right .. ")"
end
if f:isAbsoluteConstraint("left") then
f.constraints.left = "left(page) + (" .. f.constraints.left .. ")"
end
if f:isAbsoluteConstraint("top") then
f.constraints.top = "top(page) + (" .. f.constraints.top .. ")"
end
if f:isAbsoluteConstraint("bottom") then
f.constraints.bottom = "top(page) + (" .. f.constraints.bottom .. ")"
end
f:invalidate()
end
end
end
SILE.registerCommand("crop:setup", function (o,c)
local papersize = SU.required(o, "papersize", "setting up crop marks")
local size = SILE.paperSizeParser(papersize)
local oldsize = SILE.documentState.paperSize
SILE.documentState.paperSize = size
local offsetx = ( SILE.documentState.paperSize[1] - oldsize[1] ) /2
local offsety = ( SILE.documentState.paperSize[2] - oldsize[2] ) /2
local page = SILE.getFrame("page")
page:constrain("right", page:right() + offsetx)
page:constrain("left", offsetx)
page:constrain("bottom", page:bottom() + offsety)
page:constrain("top", offsety)
if SILE.scratch.masters then
for k,v in pairs(SILE.scratch.masters) do
reconstrainFrameset(v.frames)
end
else
reconstrainFrameset(SILE.documentState.documentClass.pageTemplate.frames)
end
reconstrainFrameset(SILE.frames)
if SILE.typesetter.frame then SILE.typesetter.frame:init() end
local oldEndPage = SILE.documentState.documentClass.endPage
SILE.outputter:debugFrame(page)
SILE.documentState.documentClass.endPage = function(self)
oldEndPage(self)
outputMarks()
end
end)
|
Crop marks package. Fixes #196.
|
Crop marks package. Fixes #196.
|
Lua
|
mit
|
simoncozens/sile,simoncozens/sile,neofob/sile,alerque/sile,simoncozens/sile,alerque/sile,alerque/sile,neofob/sile,simoncozens/sile,alerque/sile,neofob/sile,neofob/sile
|
6631781a7cdb4491e7069bd31f79a6ab83441bea
|
main.lua
|
main.lua
|
require "postshader"
require "light"
require "world"
require "game"
require "map"
require "tower"
require "sound"
require "TESound"
require "gui"
require "gameoverlayer"
function love.load()
G = love.graphics
W = love.window
T = love.turris
S = love.sounds
currentgamestate = 0
-- create game world
turGame = love.turris.newGame()
turMap = love.turris.newMap(13, 13, 64, 48)
turGame.init()
gameOverLayer = love.turris.newGameOverLayer()
bloomOn = true
end
function love.getgamestate()
return currentgamestate
end
function love.changegamestate(newgamestate)
currentgamestate = newgamestate
end
function love.update(dt)
if (currentgamestate == 1)then
turGame.update(dt)
elseif (currentgamestate == 4)then
gameOverEffect = gameOverEffect + dt
end
TEsound.cleanup() --Important, Clears all the channels in TEsound
end
function love.draw()
W.setTitle("FPS: " .. love.timer.getFPS())
love.postshader.setBuffer("render")
turGame.draw()
if(currentgamestate == 0) then --render main menu only
love.postshader.addEffect("blur", 2.0)
gui.drawMainMenu()
love.postshader.addEffect("scanlines")
elseif(currentgamestate==1) then --render game only
turGame.draw()
elseif(currentgamestate == 4) then -- render game + "game over" message on top
turGame.draw()
gameOverLayer.draw()
if gameOverEffect < 0.75 then
local colorAberration1 = math.sin(love.timer.getTime() * 20.0) * (0.75 - gameOverEffect) * 4.0
local colorAberration2 = math.cos(love.timer.getTime() * 20.0) * (0.75 - gameOverEffect) * 4.0
love.postshader.addEffect("blur", 1.0, 1.0)
love.postshader.addEffect("chromatic", colorAberration1, colorAberration2, colorAberration2, -colorAberration1, colorAberration1, -colorAberration2)
end
end
--currentgamestate =1 -- quick workaround, will be removed once the mouse buttons work correctly
if bloomOn then
love.postshader.addEffect("bloom")
end
love.postshader.draw()
end
function love.keypressed(key, code)
--Start Sound
if key == "1" then
love.sounds.playSound("sounds/Explosion.wav")
end
if key == "2" then
love.sounds.background("sounds/Explosion.wav")
end
if key == "b" then
bloomOn = not bloomOn
end
if key == "escape" then
buttonDetected = 1
love.turris.checkButtonPosition(320, 96)
end
end
|
require "postshader"
require "light"
require "world"
require "game"
require "map"
require "tower"
require "sound"
require "TESound"
require "gui"
require "gameoverlayer"
function love.load()
G = love.graphics
W = love.window
T = love.turris
S = love.sounds
currentgamestate = 0
-- create game world
turGame = love.turris.newGame()
turMap = love.turris.newMap(13, 13, 64, 48)
turGame.init()
gameOverLayer = love.turris.newGameOverLayer()
bloomOn = true
end
function love.getgamestate()
return currentgamestate
end
function love.changegamestate(newgamestate)
currentgamestate = newgamestate
end
function love.update(dt)
if (currentgamestate == 1)then
turGame.update(dt)
elseif (currentgamestate == 4)then
gameOverEffect = gameOverEffect + dt
end
TEsound.cleanup() --Important, Clears all the channels in TEsound
end
function love.draw()
W.setTitle("FPS: " .. love.timer.getFPS())
love.postshader.setBuffer("render")
G.setColor(0, 0, 0)
G.rectangle("fill", 0, 0, W.getWidth(), W.getHeight())
turGame.draw()
if(currentgamestate == 0) then --render main menu only
love.postshader.addEffect("blur", 2.0)
gui.drawMainMenu()
love.postshader.addEffect("scanlines")
elseif(currentgamestate==1) then --render game only
turGame.draw()
elseif(currentgamestate == 4) then -- render game + "game over" message on top
turGame.draw()
gameOverLayer.draw()
if gameOverEffect < 0.75 then
local colorAberration1 = math.sin(love.timer.getTime() * 20.0) * (0.75 - gameOverEffect) * 4.0
local colorAberration2 = math.cos(love.timer.getTime() * 20.0) * (0.75 - gameOverEffect) * 4.0
love.postshader.addEffect("blur", 1.0, 1.0)
love.postshader.addEffect("chromatic", colorAberration1, colorAberration2, colorAberration2, -colorAberration1, colorAberration1, -colorAberration2)
end
end
--currentgamestate =1 -- quick workaround, will be removed once the mouse buttons work correctly
if bloomOn then
love.postshader.addEffect("bloom")
end
love.postshader.draw()
end
function love.keypressed(key, code)
--Start Sound
if key == "1" then
love.sounds.playSound("sounds/Explosion.wav")
end
if key == "2" then
love.sounds.background("sounds/Explosion.wav")
end
if key == "b" then
bloomOn = not bloomOn
end
if key == "escape" then
buttonDetected = 1
love.turris.checkButtonPosition(320, 96)
end
end
|
fix bloom blur
|
fix bloom blur
|
Lua
|
mit
|
sam1i/Turres-Monacorum,sam1i/Turres-Monacorum
|
69141be75fbba58dab2fe77dc1b2aefcea43a59e
|
love2d/mapGenerator.lua
|
love2d/mapGenerator.lua
|
require('math')
MapGenerator = {}
MAP_PLAIN = 0
MAP_MOUNTAIN = 1
MAP_OBJ_NOTHING = 0
MAP_OBJ_WATER = 1
MAP_OBJ_TREE = 2
MAP_OBJ_START = 3
MAP_OBJ_FIREPLACE = 4
MAP_WATER_PERCENTAGE = 0.15
MAP_TREE_PERCENTAGE = 0.1
MAP_FIREPLACE_PERCENTAGE = 0.1
function MapGenerator.newMap(width, height)
local map = {}
local plain = {}
local mountain = {}
local countPlain = 0
for x = 1, width do
map[x] = {}
for y = 1, height do
if y/width < 0.5 * math.cos((x / height) * 2 * math.pi - 2*math.pi/3) -math.abs(0.5 * math.cos((x / height) * 4 * math.pi - 2*math.pi/3)) + 0.5 then
map[x][y] = {MAP_PLAIN, MAP_OBJ_NOTHING}
countPlain = countPlain + 1
plain[#plain + 1] = {x, y}
else
map[x][y] = {MAP_MOUNTAIN, MAP_OBJ_NOTHING}
mountain[#mountain + 1] = {x, y}
end
end
end
local numPlain = #plain
local numMountains = #mountain
-- create trees
local numTrees = MAP_TREE_PERCENTAGE * countPlain
for i = 1, numTrees do
local idx = math.random(#plain)
local pos = plain[idx]
table.remove(plain, idx)
map[pos[1]][pos[2]][2] = MAP_OBJ_TREE
print("Tree: ", pos[1], pos[2])
end
-- create start point
local numUnits = 1
for i = 1, numUnits do
local idx = math.random(#plain)
local pos = plain[idx]
table.remove(plain, idx)
map[pos[1]][pos[2]][2] = MAP_OBJ_START
print("Unit: ", pos[1], pos[2])
end
-- create water
local numWater = MAP_WATER_PERCENTAGE * width * height
local waterToPlace = numWater
while waterToPlace > 0 do
local pos
local maxSize = math.random(1, math.min(15, waterToPlace))
if (math.random() < numPlain/(numPlain + numMountains) and #plain > 0) or (#mountain == 0 and #plain > 0) then
local idx = math.random(#plain)
pos = plain[idx]
waterToPlace = waterToPlace - MapGenerator.generateWater(pos[1], pos[2], {plain, mountain}, map, width, height, maxSize)
else
local idx = math.random(#mountain)
pos = mountain[idx]
waterToPlace = waterToPlace - MapGenerator.generateWater(pos[1], pos[2], {plain, mountain}, map, width, height, maxSize)
end
print("Water: ", pos[1], pos[2], "@", maxSize)
end
--create fire places
local numFirePlaces = MAP_FIREPLACE_PERCENTAGE * width * height
for i = 1, numFirePlaces do
local pos
if (math.random() < numPlain/(numPlain + numMountains) and #plain > 0) or (#mountain == 0 and #plain > 0) then
local idx = math.random(#plain)
pos = plain[idx]
table.remove(plain, idx)
map[pos[1]][pos[2]][2] = MAP_OBJ_FIREPLACE
else
local idx = math.random(#mountain)
pos = mountain[idx]
table.remove(mountain, idx)
map[pos[1]][pos[2]][2] = MAP_OBJ_FIREPLACE
end
print("Fire place: ", pos[1], pos[2])
end
MapGenerator.printMap(map)
print("Trees: ", numTrees, "Water: ", numWater, "Units: ", numUnits)
return map
end
function MapGenerator.removePosFromTables(tables, x, y)
for idx, tab in pairs(tables) do
for i, v in pairs(tab) do
if x == v[1] and y == v[2] then
table.remove(tab, i)
return
end
end
end
end
function MapGenerator.canPlaceWater(map, x, y)
if map[x][y][2] == MAP_OBJ_NOTHING then
return true
else
return false
end
end
function MapGenerator.placeWater(map, x, y)
if map[x][y][2] == MAP_OBJ_NOTHING then
map[x][y][2] = MAP_OBJ_WATER
return true
else
return false
end
end
function MapGenerator.isValidPosition(x, y, width, height)
if x < 1 or x > width then
return false
end
if y < 1 or y > height then
return false
end
return true
end
function MapGenerator.checkWaterTarget(map, x, y, width, height)
if MapGenerator.isValidPosition(x, y, width, height) then
return MapGenerator.canPlaceWater(map, x, y)
end
return false
end
function MapGenerator.generateWater(x, y, tables, map, width, height, maxSize)
local placed = 0
if MapGenerator.placeWater(map, x, y) then
MapGenerator.removePosFromTables(tables, x, y)
placed = placed + 1
else
return placed
end
for i = 1, maxSize - 1 do
-- locate possible targets
local neighbours = {}
if MapGenerator.checkWaterTarget(map, x - 1, y , width, height) then neighbours[#neighbours + 1] = {x - 1, y } end
if MapGenerator.checkWaterTarget(map, x + 1, y , width, height) then neighbours[#neighbours + 1] = {x + 1, y } end
if MapGenerator.checkWaterTarget(map, x , y - 1, width, height) then neighbours[#neighbours + 1] = {x , y - 1} end
if MapGenerator.checkWaterTarget(map, x , y + 1, width, height) then neighbours[#neighbours + 1] = {x , y + 1} end
if #neighbours < 1 then
return placed
end
local idx = math.random(#neighbours)
local pos = neighbours[idx]
if MapGenerator.placeWater(map, pos[1], pos[2]) then
MapGenerator.removePosFromTables(tables, pos[1], pos[2])
placed = placed + 1
x = pos[1]
y = pos[2]
else
return placed
end
end
return placed
end
function MapGenerator.printMap(map)
for i,v in pairs(map) do
local line = ""
for j, v in pairs(v) do
line = line .. (v[1] + 2 * v[2]) .. " "
end
print(line)
end
end
function MapGenerator.getID(map, x, y)
return map[x][y][1] + 2 * map[x][y][2]
end
|
require('math')
MapGenerator = {}
MAP_UNDEFINED = 0
MAP_PLAIN = 1
MAP_MOUNTAIN = 2
MAP_OBJ_NOTHING = 0
MAP_OBJ_WATER = 1
MAP_OBJ_TREE = 2
MAP_OBJ_START = 3
MAP_OBJ_FIREPLACE = 4
MAP_WATER_PERCENTAGE = 0.15
MAP_TREE_PERCENTAGE = 0.1
MAP_FIREPLACE_PERCENTAGE = 0.1
function MapGenerator.newMap(width, height)
local map = {}
local plain = {}
local mountain = {}
local countPlain = 0
for x = 1, width do
map[x] = {}
for y = 1, height do
if y/width < 0.5 * math.cos((x / height) * 2 * math.pi - 2*math.pi/3) -math.abs(0.5 * math.cos((x / height) * 4 * math.pi - 2*math.pi/3)) + 0.5 then
map[x][y] = {MAP_PLAIN, MAP_OBJ_NOTHING}
countPlain = countPlain + 1
plain[#plain + 1] = {x, y}
else
map[x][y] = {MAP_MOUNTAIN, MAP_OBJ_NOTHING}
mountain[#mountain + 1] = {x, y}
end
end
end
local numPlain = #plain
local numMountains = #mountain
-- create trees
local numTrees = MAP_TREE_PERCENTAGE * countPlain
for i = 1, numTrees do
local idx = math.random(#plain)
local pos = plain[idx]
table.remove(plain, idx)
map[pos[1]][pos[2]][2] = MAP_OBJ_TREE
print("Tree: ", pos[1], pos[2])
end
-- create start point
local numUnits = 1
for i = 1, numUnits do
local idx = math.random(#plain)
local pos = plain[idx]
table.remove(plain, idx)
map[pos[1]][pos[2]][2] = MAP_OBJ_START
print("Unit: ", pos[1], pos[2])
end
-- create water
local numWater = MAP_WATER_PERCENTAGE * width * height
local waterToPlace = numWater
while waterToPlace > 0 do
local pos
local maxSize = math.random(1, math.min(15, waterToPlace))
if (math.random() < numPlain/(numPlain + numMountains) and #plain > 0) or (#mountain == 0 and #plain > 0) then
local idx = math.random(#plain)
pos = plain[idx]
waterToPlace = waterToPlace - MapGenerator.generateWater(pos[1], pos[2], {plain, mountain}, map, width, height, maxSize)
else
local idx = math.random(#mountain)
pos = mountain[idx]
waterToPlace = waterToPlace - MapGenerator.generateWater(pos[1], pos[2], {plain, mountain}, map, width, height, maxSize)
end
print("Water: ", pos[1], pos[2], "@", maxSize)
end
--create fire places
local numFirePlaces = MAP_FIREPLACE_PERCENTAGE * width * height
for i = 1, numFirePlaces do
local pos
if (math.random() < numPlain/(numPlain + numMountains) and #plain > 0) or (#mountain == 0 and #plain > 0) then
local idx = math.random(#plain)
pos = plain[idx]
table.remove(plain, idx)
map[pos[1]][pos[2]][2] = MAP_OBJ_FIREPLACE
else
local idx = math.random(#mountain)
pos = mountain[idx]
table.remove(mountain, idx)
map[pos[1]][pos[2]][2] = MAP_OBJ_FIREPLACE
end
print("Fire place: ", pos[1], pos[2])
end
MapGenerator.printMap(map)
print("Trees: ", numTrees, "Water: ", numWater, "Units: ", numUnits)
return map
end
function MapGenerator.removePosFromTables(tables, x, y)
for idx, tab in pairs(tables) do
for i, v in pairs(tab) do
if x == v[1] and y == v[2] then
table.remove(tab, i)
return
end
end
end
end
function MapGenerator.canPlaceWater(map, x, y)
if map[x][y][2] == MAP_OBJ_NOTHING then
return true
else
return false
end
end
function MapGenerator.placeWater(map, x, y)
if map[x][y][2] == MAP_OBJ_NOTHING then
map[x][y][2] = MAP_OBJ_WATER
return true
else
return false
end
end
function MapGenerator.isValidPosition(x, y, width, height)
if x < 1 or x > width then
return false
end
if y < 1 or y > height then
return false
end
return true
end
function MapGenerator.checkWaterTarget(map, x, y, width, height)
if MapGenerator.isValidPosition(x, y, width, height) then
return MapGenerator.canPlaceWater(map, x, y)
end
return false
end
function MapGenerator.generateWater(x, y, tables, map, width, height, maxSize)
local placed = 0
if MapGenerator.placeWater(map, x, y) then
MapGenerator.removePosFromTables(tables, x, y)
placed = placed + 1
else
return placed
end
for i = 1, maxSize - 1 do
-- locate possible targets
local neighbours = {}
if MapGenerator.checkWaterTarget(map, x - 1, y , width, height) then neighbours[#neighbours + 1] = {x - 1, y } end
if MapGenerator.checkWaterTarget(map, x + 1, y , width, height) then neighbours[#neighbours + 1] = {x + 1, y } end
if MapGenerator.checkWaterTarget(map, x , y - 1, width, height) then neighbours[#neighbours + 1] = {x , y - 1} end
if MapGenerator.checkWaterTarget(map, x , y + 1, width, height) then neighbours[#neighbours + 1] = {x , y + 1} end
if #neighbours < 1 then
return placed
end
local idx = math.random(#neighbours)
local pos = neighbours[idx]
if MapGenerator.placeWater(map, pos[1], pos[2]) then
MapGenerator.removePosFromTables(tables, pos[1], pos[2])
placed = placed + 1
x = pos[1]
y = pos[2]
else
return placed
end
end
return placed
end
function MapGenerator.printMap(map)
for i,v in pairs(map) do
local line = ""
for j, v in pairs(v) do
line = line .. (v[1] + 2 * v[2]) .. " "
end
print(line)
end
end
function MapGenerator.getID(map, x, y)
return map[x][y][1]
end
function MapGenerator.getObject(map, x, y)
return map[x][y][2]
end
|
Fixed map generator
|
Fixed map generator
|
Lua
|
mit
|
nczempin/lizard-journey
|
8ca32de9569779d4e57362ce7018499ea0779425
|
lua/sfoto/imagegrid.lua
|
lua/sfoto/imagegrid.lua
|
module(..., package.seeall)
require("sfoto")
local Gridder = {}
local Gridder_mt = {__metatable = {}, __index = Gridder}
function new(node, photo_url, sputnik)
return setmetatable({node=node, photo_url=photo_url, sputnik=sputnik}, Gridder_mt)
end
-----------------------------------------------------------------------------
--
-----------------------------------------------------------------------------
function Gridder:parse_flexrow(row_code)
local row = {}
local i = 0
row_code:gsub("[^\n]+",
function(item)
i = i + 1
if item~="" and item:sub(1,3) ~= "---" then
if item:sub(1,1) ~= "x" then
item = "x1 "..item
end
local size, id, title = item:match("(%w*) ([^%s]*)(.*)")
row[i] = {item=item, id=id, size=tonumber(size:sub(2)), title=title}
else
row[i] = {}
end
end)
table.insert(self.rows, row)
end
-----------------------------------------------------------------------------
-- A more flexible way to express a grid
--
-- @param row A string representing the image grid
-- @return An HTML string
-----------------------------------------------------------------------------
function Gridder:flexgrid(image_code)
-- first convert the string representing the images into a table of rows
local buffer = ""
self.rows = {}
image_code:gsub("[^~]+", function (row) self:parse_flexrow(row) end)
for i, row in ipairs(self.rows) do
for j, photo in ipairs(row) do
buffer = buffer .. (photo.id or "x").."\n"
end
end
-- first figure out the total height of the grid in pixels
local total_height = 0
for i, row in ipairs(self.rows) do
total_height = total_height + 8 + (#row==6 and 150 or 100)
end
-- a function to add "px" to ints
local function pixify(value)
return string.format("%dpx", value)
end
-- we'll be positioning each photo individually, so we are making a single
-- list of photos rather than assembling "rows"
local photos = {}
local width, dwidth, height
local y = 2
for i, row in ipairs(self.rows) do
if #row == 6 then
width, dwidth, height = 100, 6, 150
else
width, dwidth, height = 150, 10, 100
end
local x = 2
for i = 1,#row do
photo = row[i]
if photo and photo.id then
local album, image = photo.id:gmatch("(.*)/(.*)") --util.split(photo.id, "/")
photo.size = photo.size or 1
table.insert(photos, {
width = pixify(width*photo.size + dwidth*(photo.size-1)),
height = pixify(height*photo.size + 8*(photo.size-1)),
left = pixify(2 + (width + dwidth) * (i-1)),
top = pixify(y),
title = photo.title or "",
photo_url = sfoto.photo_url("photos/"..photo.id,
photo.size>1 and string.format("%dx", photo.size) or "thumb"),
link = self.sputnik:make_url("albums/"..photo.id),
})
end
end
y = y + height + 8
end
return cosmo.f(self.node.templates.MIXED_ALBUM){
do_photos = photos,
height = total_height
}
end
function Gridder:add_flexgrids(content)
return content:gsub("<2~*\n(.-)\n~*>", function(code) return self:flexgrid(code) end)
end
function Gridder:parse_simplerow(row_code)
local row = {}
local i = 0
row_code:gsub("[^\n]+",
function(item)
i = i + 1
if item~="" and item:sub(1,3) ~= "---" then
local id, title = item:match("([^%s]*)(.*)")
row[i] = {id=id, title=title}
else
row[i] = {}
end
end)
table.insert(self.rows, row)
end
function Gridder:simplegrid(image_code)
self.rows = {}
image_code:gsub("[^~]+", function (row) self:parse_simplerow(row) end)
for i, row in ipairs(self.rows) do
row.photos = row
for j, photo in ipairs(row) do
photo.photo_url = sfoto.photo_url(photo.id, "thumb")
photo.link = self.sputnik:make_url("albums/"..photo.id)
end
end
return cosmo.f(self.node.templates.SIMPLE_IMAGE_GRID){
rows = self.rows
}
end
function Gridder:add_flexgrids(content)
return content:gsub("<2~*\n(.-)\n~*>", function(code) return self:flexgrid(code) end)
end
function Gridder:add_simplegrids(content)
return content:gsub("<~*\n(.-)\n~*>", function(code) return self:simplegrid(code) end)
end
|
module(..., package.seeall)
require("sfoto")
local Gridder = {}
local Gridder_mt = {__metatable = {}, __index = Gridder}
function new(node, photo_url, sputnik)
return setmetatable({node=node, photo_url=photo_url, sputnik=sputnik}, Gridder_mt)
end
-----------------------------------------------------------------------------
--
-----------------------------------------------------------------------------
function Gridder:parse_flexrow(row_code)
local row = {}
local i = 0
row_code:gsub("[^\n]+",
function(item)
i = i + 1
if item~="" and item:sub(1,3) ~= "---" then
if item:sub(1,1) ~= "x" then
item = "x1 "..item
end
local size, id, title = item:match("(%w*) ([^%s]*)(.*)")
row[i] = {item=item, id=id, size=tonumber(size:sub(2)), title=title}
else
row[i] = {}
end
end)
table.insert(self.rows, row)
end
-----------------------------------------------------------------------------
-- A more flexible way to express a grid
--
-- @param row A string representing the image grid
-- @return An HTML string
-----------------------------------------------------------------------------
function Gridder:flexgrid(image_code)
-- first convert the string representing the images into a table of rows
local buffer = ""
self.rows = {}
image_code:gsub("[^~]+", function (row) self:parse_flexrow(row) end)
for i, row in ipairs(self.rows) do
for j, photo in ipairs(row) do
buffer = buffer .. (photo.id or "x").."\n"
end
end
-- first figure out the total height of the grid in pixels
local total_height = 0
for i, row in ipairs(self.rows) do
total_height = total_height + 8 + (#row==6 and 150 or 100)
end
-- a function to add "px" to ints
local function pixify(value)
return string.format("%dpx", value)
end
-- we'll be positioning each photo individually, so we are making a single
-- list of photos rather than assembling "rows"
local photos = {}
local width, dwidth, height
local y = 2
for i, row in ipairs(self.rows) do
if #row == 6 then
width, dwidth, height = 100, 6, 150
else
width, dwidth, height = 150, 10, 100
end
local x = 2
for i = 1,#row do
photo = row[i]
if photo and photo.id then
local album, image = photo.id:gmatch("(.*)/(.*)") --util.split(photo.id, "/")
photo.size = photo.size or 1
table.insert(photos, {
width = pixify(width*photo.size + dwidth*(photo.size-1)),
height = pixify(height*photo.size + 8*(photo.size-1)),
left = pixify(2 + (width + dwidth) * (i-1)),
top = pixify(y),
title = photo.title or "",
photo_url = sfoto.photo_url("photos/"..photo.id,
photo.size>1 and string.format("%dx", photo.size) or "thumb"),
link = self.sputnik:make_url("albums/"..photo.id),
link = self.sputnik:make_url("photos/"..photo.id:gsub("-", "/"))
})
end
end
y = y + height + 8
end
return cosmo.f(self.node.templates.MIXED_ALBUM){
do_photos = photos,
height = total_height
}
end
function Gridder:add_flexgrids(content)
return content:gsub("<2~*\n(.-)\n~*>", function(code) return self:flexgrid(code) end)
end
function Gridder:parse_simplerow(row_code)
local row = {}
local i = 0
row_code:gsub("[^\n]+",
function(item)
i = i + 1
if item~="" and item:sub(1,3) ~= "---" then
local id, title = item:match("([^%s]*)(.*)")
row[i] = {id=id, title=title}
else
row[i] = {}
end
end)
table.insert(self.rows, row)
end
function Gridder:simplegrid(image_code)
self.rows = {}
image_code:gsub("[^~]+", function (row) self:parse_simplerow(row) end)
for i, row in ipairs(self.rows) do
row.photos = row
for j, photo in ipairs(row) do
photo.photo_url = sfoto.photo_url("photos/"..photo.id, "thumb")
photo.link = self.sputnik:make_url("photos/"..photo.id:gsub("-", "/"))
end
end
return cosmo.f(self.node.templates.SIMPLE_IMAGE_GRID){
rows = self.rows
}
end
function Gridder:add_flexgrids(content)
return content:gsub("<2~*\n(.-)\n~*>", function(code) return self:flexgrid(code) end)
end
function Gridder:add_simplegrids(content)
return content:gsub("<~*\n(.-)\n~*>", function(code) return self:simplegrid(code) end)
end
|
Fixed path for grids.
|
Fixed path for grids.
|
Lua
|
mit
|
yuri/sfoto
|
2908b82b33237a8e256f954cc97064dc69322fc3
|
item/traps.lua
|
item/traps.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/>.
]]
--Function: Generic trap script
--Last Update: 01/04/2006
--Update by: Nitram
-- UPDATE common SET com_script='item.traps' WHERE com_itemid IN (377,378,379,380,381);
require("base.common")
module("item.traps", package.seeall)
function UseItem(User, SourceItem)
if ((User:increaseAttrib("dexterity",0) + 0.5*User:increaseAttrib("perception",0) + math.random(1,30)) >= 30) then
base.common.InformNLS( User,"Du entschrfst die Falle.","You disarm the trap." );
world:swap(SourceItem,375,333);
else
base.common.InformNLS( User,"Du lst die Falle aus!","You set off the trap!" );
world:gfx(14,SourceItem.pos);
User:increaseAttrib("hitpoints", -5000);
world:swap(SourceItem,376,333);
end
User.movepoints=User.movepoints-10;
end
function CharacterOnField( User )
local SetOff=false;
if (User:increaseAttrib("hitpoints",0)>0) then --ghosts do not set off traps
repeat
local SourceItem = world:getItemOnField( User.pos );
if (User:increaseAttrib("hitpoints",0)>0) then
if( SourceItem.id >= 377 ) and (SourceItem.id <= 381) then
base.common.InformNLS( User,"Du lst eine Falle aus!","You set off a trap!" );
world:gfx(14,User.pos);
User:increaseAttrib("hitpoints", -4999);
world:swap(SourceItem,376,333);
SetOff=true;
else
world:erase(SourceItem,1);
end
end
until ( SetOff == true )
User.movepoints=User.movepoints-10;
end
end
function LookAtItem(User,Item)
base.lookat.SetSpecialName(Item, "Falle", "trap");
if (User:distanceMetricToPosition(Item.pos)<2 and User:increaseAttrib("perception",0)>15) then
world:itemInform(User,Item,base.lookat.GenerateLookAt(User, Item, base.lookat.NONE));
end
end
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
--Function: Generic trap script
--Last Update: 01/04/2006
--Update by: Nitram
-- UPDATE common SET com_script='item.traps' WHERE com_itemid IN (377,378,379,380,381);
require("base.common")
module("item.traps", package.seeall)
|
Remove unneeded, imbalanced and buggy code
|
Remove unneeded, imbalanced and buggy code
|
Lua
|
agpl-3.0
|
vilarion/Illarion-Content,KayMD/Illarion-Content,LaFamiglia/Illarion-Content,Baylamon/Illarion-Content,Illarion-eV/Illarion-Content
|
f14a5f64cb55e45924a68923e758b4f6c152c977
|
mods/bobblocks/trap.lua
|
mods/bobblocks/trap.lua
|
-- State Changes
local update_bobtrap = function (pos, node)
local nodename=""
local param2=""
--Switch Trap State
if
-- Swap Traps
node.name == 'bobblocks:trap_spike' then nodename = 'bobblocks:trap_spike_set'
elseif node.name == 'bobblocks:trap_spike_set' then nodename = 'bobblocks:trap_spike'
elseif node.name == 'bobblocks:trap_spike_major' then nodename = 'bobblocks:trap_spike_major_set'
elseif node.name == 'bobblocks:trap_spike_major_set' then nodename = 'bobblocks:trap_spike_major'
end
minetest.add_node(pos, {name = nodename})
end
-- Punch Traps
local on_bobtrap_punched = function (pos, node, puncher)
if
-- Start Traps
node.name == 'bobblocks:trap_spike' or node.name == 'bobblocks:trap_spike_set' or
node.name == 'bobblocks:trap_spike_major' or node.name == 'bobblocks:trap_spike_major_set'
then
update_bobtrap(pos, node)
end
end
minetest.register_on_punchnode(on_bobtrap_punched)
--ABM (Spring The Traps)
minetest.register_abm(
{nodenames = {"bobblocks:trap_spike_set"},
interval = 1.0,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
local objs = minetest.get_objects_inside_radius(pos, 1)
for k, obj in pairs(objs) do
update_bobtrap(pos, node)
end
end,
})
minetest.register_abm(
{nodenames = {"bobblocks:trap_spike_major_set"},
interval = 1.0,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
local objs = minetest.get_objects_inside_radius(pos, 1)
for k, obj in pairs(objs) do
update_bobtrap(pos, node)
end
end,
})
-- Nodes
minetest.register_node("bobblocks:trap_grass", {
description = "Trap Grass",
tiles = {"default_grass.png"},
paramtype2 = "facedir",
legacy_facedir_simple = true,
groups = {snappy=2,cracky=3,oddly_breakable_by_hand=3},
is_ground_content = false,
walkable = false,
climbable = false,
})
local function spikenode(name, desc, texture, drop, groups, drawtype)
minetest.register_node("bobblocks:trap_"..name, {
description = desc,
drawtype = drawtype,
tiles = {"bobblocks_"..texture..".png"},
inventory_image = ("bobblocks_"..texture..".png"),
paramtype = "light",
walkable = false,
sunlight_propagates = true,
groups = groups,
drop = drop,
})
end
local function spike1(name, desc, texture)
spikenode(name, desc, texture, "bobblocks:trap_"..name, {cracky=3,melty=3}, "plantlike")
end
local function spike2(name, desc, texture, drop)
spikenode(name, desc, texture, drop, {cracky=3,melty=3,not_in_creative_inventory=1}, "raillike")
end
spike1("spike", "Trap Spike Minor", "minorspike")
spike2("spike_set", "Trap Spike Minor Set", "trap_set", 'bobblocks:trap_spike')
spike1("spike_major", "Trap Spike Major", "majorspike")
spike2("spike_major_set", "Trap Spike Major Set", "trap_set", 'bobblocks:trap_spike_major')
minetest.register_node("bobblocks:spike_major_reverse", {
description = "Trap Spike Major Reverse",
drawtype = "plantlike",
visual_scale = 1,
tiles = {"bobblocks_majorspike_reverse.png"},
inventory_image = ("bobblocks_majorspike_reverse.png"),
paramtype = "light",
walkable = false,
sunlight_propagates = true,
groups = {cracky=2,melty=2},
})
-- Crafting
minetest.register_craft({
output = 'bobblocks:trap_spike 3',
recipe = {
{'', 'default:obsidian_shard', ''},
{'', 'default:steel_ingot', ''},
}
})
minetest.register_craft({
output = 'bobblocks:trap_spike_major',
recipe = {
{'default:obsidian_shard', 'default:obsidian_shard', 'default:obsidian_shard'},
{'', 'default:steel_ingot', ''},
}
})
minetest.register_craft({
output = 'bobblocks:trap_grass',
recipe = {
{'', '', ''},
{'', 'default:dirt', ''},
{'', 'default:stick', ''},
}
})
minetest.register_craft({
output = 'bobblocks:spike_major_reverse',
recipe = {
{'', 'default:steel_ingot', ''},
{'default:obsidian_shard', 'default:obsidian_shard', 'default:obsidian_shard'},
}
})
-- ABM
minetest.register_abm(
{nodenames = {"bobblocks:trap_spike"},
interval = 1.0,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
local objs = minetest.get_objects_inside_radius(pos, 1)
for k, obj in pairs(objs) do
obj:set_hp(obj:get_hp()-1)
minetest.sound_play("bobblocks_trap_fall",
{pos = pos, gain = 1.0, max_hear_distance = 3,})
end
end,
})
minetest.register_abm(
{nodenames = {"bobblocks:trap_spike_major"},
interval = 1.0,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
local objs = minetest.get_objects_inside_radius(pos, 1)
for k, obj in pairs(objs) do
obj:set_hp(obj:get_hp()-100)
minetest.sound_play("bobblocks_trap_fall",
{pos = pos, gain = 1.0, max_hear_distance = 3,})
end
end,
})
minetest.register_abm(
{nodenames = {"bobblocks:spike_major_reverse"},
interval = 1.0,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
pos.y = pos.y-1.2
local objs = minetest.get_objects_inside_radius(pos, 1)
for k, obj in pairs(objs) do
obj:set_hp(obj:get_hp()-100)
minetest.sound_play("bobblocks_trap_fall",
{pos = pos, gain = 1.0, max_hear_distance = 3,})
end
end,
})
|
-- State Changes
local update_bobtrap = function (pos, node)
local nodename=""
local param2=""
--Switch Trap State
if
-- Swap Traps
node.name == 'bobblocks:trap_spike' then nodename = 'bobblocks:trap_spike_set'
elseif node.name == 'bobblocks:trap_spike_set' then nodename = 'bobblocks:trap_spike'
elseif node.name == 'bobblocks:trap_spike_major' then nodename = 'bobblocks:trap_spike_major_set'
elseif node.name == 'bobblocks:trap_spike_major_set' then nodename = 'bobblocks:trap_spike_major'
end
minetest.add_node(pos, {name = nodename})
end
-- Punch Traps
local on_bobtrap_punched = function (pos, node, puncher)
if
-- Start Traps
node.name == 'bobblocks:trap_spike' or node.name == 'bobblocks:trap_spike_set' or
node.name == 'bobblocks:trap_spike_major' or node.name == 'bobblocks:trap_spike_major_set'
then
update_bobtrap(pos, node)
end
end
minetest.register_on_punchnode(on_bobtrap_punched)
--ABM (Spring The Traps)
minetest.register_abm(
{nodenames = {"bobblocks:trap_spike_set"},
interval = 1.0,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
local objs = minetest.get_objects_inside_radius(pos, 1)
for k, obj in pairs(objs) do
update_bobtrap(pos, node)
end
end,
})
minetest.register_abm(
{nodenames = {"bobblocks:trap_spike_major_set"},
interval = 1.0,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
local objs = minetest.get_objects_inside_radius(pos, 1)
for k, obj in pairs(objs) do
update_bobtrap(pos, node)
end
end,
})
-- Nodes
minetest.register_node("bobblocks:trap_grass", {
description = "Trap Grass",
tiles = {"default_grass.png"},
paramtype2 = "facedir",
legacy_facedir_simple = true,
groups = {snappy=2,cracky=3,oddly_breakable_by_hand=3},
is_ground_content = false,
walkable = false,
climbable = false,
})
local function spikenode(name, desc, texture, drop, groups, drawtype)
minetest.register_node("bobblocks:trap_"..name, {
description = desc,
drawtype = drawtype,
tiles = {"bobblocks_"..texture..".png"},
inventory_image = ("bobblocks_"..texture..".png"),
paramtype = "light",
walkable = false,
sunlight_propagates = true,
groups = groups,
drop = drop,
})
end
local function spike1(name, desc, texture)
spikenode(name, desc, texture, "bobblocks:trap_"..name, {cracky=3,melty=3}, "plantlike")
end
local function spike2(name, desc, texture, drop)
spikenode(name, desc, texture, drop, {cracky=3,melty=3,not_in_creative_inventory=1}, "raillike")
end
spike1("spike", "Trap Spike Minor", "minorspike")
spike2("spike_set", "Trap Spike Minor Set", "trap_set", 'bobblocks:trap_spike')
spike1("spike_major", "Trap Spike Major", "majorspike")
spike2("spike_major_set", "Trap Spike Major Set", "trap_set", 'bobblocks:trap_spike_major')
minetest.register_node("bobblocks:spike_major_reverse", {
description = "Trap Spike Major Reverse",
drawtype = "plantlike",
visual_scale = 1,
tiles = {"bobblocks_majorspike_reverse.png"},
inventory_image = ("bobblocks_majorspike_reverse.png"),
paramtype = "light",
walkable = false,
sunlight_propagates = true,
groups = {cracky=2,melty=2},
})
-- Crafting
minetest.register_craft({
output = 'bobblocks:trap_spike 3',
recipe = {
{'', 'default:obsidian_shard', ''},
{'', 'default:steel_ingot', ''},
}
})
minetest.register_craft({
output = 'bobblocks:trap_spike_major',
recipe = {
{'default:obsidian_shard', 'default:obsidian_shard', 'default:obsidian_shard'},
{'', 'default:steel_ingot', ''},
}
})
minetest.register_craft({
output = 'bobblocks:trap_grass',
recipe = {
{'', '', ''},
{'', 'default:dirt', ''},
{'', 'default:stick', ''},
}
})
minetest.register_craft({
output = 'bobblocks:spike_major_reverse',
recipe = {
{'', 'default:steel_ingot', ''},
{'default:obsidian_shard', 'default:obsidian_shard', 'default:obsidian_shard'},
}
})
-- ABM
minetest.register_abm(
{nodenames = {"bobblocks:trap_spike"},
interval = 1.0,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
local objs = minetest.get_objects_inside_radius(pos, 1)
for k, obj in pairs(objs) do
if obj:get_hp() > 0 then --MFF (crabman 8/1/2016) dont re-kill dead player
obj:set_hp(obj:get_hp()-1)
end
minetest.sound_play("bobblocks_trap_fall",
{pos = pos, gain = 1.0, max_hear_distance = 3,})
end
end,
})
minetest.register_abm(
{nodenames = {"bobblocks:trap_spike_major"},
interval = 1.0,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
local objs = minetest.get_objects_inside_radius(pos, 1)
for k, obj in pairs(objs) do
if obj:get_hp() > 0 then --MFF (crabman 8/1/2016) dont re-kill dead player
obj:set_hp(obj:get_hp()-100)
end
minetest.sound_play("bobblocks_trap_fall",
{pos = pos, gain = 1.0, max_hear_distance = 3,})
end
end,
})
minetest.register_abm(
{nodenames = {"bobblocks:spike_major_reverse"},
interval = 1.0,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
pos.y = pos.y-1.2
local objs = minetest.get_objects_inside_radius(pos, 1)
for k, obj in pairs(objs) do
if obj:get_hp() > 0 then --MFF (crabman 8/1/2016) dont re-kill dead player
obj:set_hp(obj:get_hp()-100)
end
minetest.sound_play("bobblocks_trap_fall",
{pos = pos, gain = 1.0, max_hear_distance = 3,})
end
end,
})
|
trap spike don't re-kill dead player, fix multidead, issue https://github.com/MinetestForFun/server-minetestforfun/issues/375
|
trap spike don't re-kill dead player, fix multidead, issue https://github.com/MinetestForFun/server-minetestforfun/issues/375
|
Lua
|
unlicense
|
MinetestForFun/server-minetestforfun-creative,MinetestForFun/server-minetestforfun-creative,MinetestForFun/server-minetestforfun-creative
|
58fafdad73b89a5a8b2fdd1da3a1d4f91bea4d73
|
test/inspect_namespace_test.lua
|
test/inspect_namespace_test.lua
|
--[[------------------------------------------------------
dub.Inspector test
------------------
Test introspective operations with the 'namespace' group
of classes.
--]]------------------------------------------------------
local lub = require 'lub'
local lut = require 'lut'
local dub = require 'dub'
local should = lut.Test('dub.Inspector - namespace', {coverage = false})
local ins
function should.setup()
dub.warn = dub.silentWarn
if not ins then
ins = dub.Inspector {
INPUT = {
lub.path '|fixtures/namespace',
},
doc_dir = lub.path '|tmp',
}
end
end
function should.teardown()
dub.warn = dub.printWarn
end
--=============================================== TESTS
function should.findNamespace()
local Nem = ins:find('Nem')
assertEqual('dub.Namespace', Nem.type)
end
function should.listNamespaces()
local res = {}
for nm in ins.db:namespaces() do
table.insert(res, nm.name)
end
assertValueEqual({
'Nem',
}, res)
end
function should.listHeaders()
local res = {}
for h in ins.db:headers({ins:find('Nem::A')}) do
local name = string.match(h, '/([^/]+/[^/]+)$')
if name ~= 'namespace/B.h' then
-- FIXME not sure why B.h header appears when testing with luajit on linux
-- but not with regular lua.
lub.insertSorted(res, name)
end
end
assertValueEqual({
'namespace/A.h',
'namespace/constants.h',
'namespace/nem.h',
}, res)
end
function should.findByFullname()
local A = ins:find('Nem::A')
assertEqual('dub.Class', A.type)
end
function should.findNamespace()
local A = ins:find('Nem::A')
assertEqual('Nem', A:namespace().name)
end
function should.findTemplate()
local TRect = ins:find('Nem::TRect')
assertEqual('TRect', TRect.name)
assertEqual('dub.CTemplate', TRect.type)
end
function should.findTypdefByFullname()
local Rect = ins:find('Nem::Rect')
assertEqual('Rect', Rect.name)
assertEqual('Nem', Rect:namespace().name)
assertEqual('dub.Class', Rect.type)
end
function should.findNestedClassByFullname()
local C = ins:find('Nem::B::C')
assertEqual('dub.Class', C.type)
assertEqual('C', C.name)
end
function should.findNamespaceFromNestedClass()
local C = ins:find('Nem::B::C')
assertEqual('Nem', C:namespace().name)
end
function should.haveFullypeReturnValueInCtor()
local C = ins:find('Nem::B::C')
local met = C:method('C')
assertEqual('B::C *', met.return_value.create_name)
end
function should.prefixInnerClassInTypes()
local C = ins:find('Nem::B::C')
assertEqual('B::C *', C.create_name)
end
function should.properlyResolveType()
local C = ins:find('Nem::B::C')
local t = ins.db:resolveType(C, 'Nem::B::C')
assertEqual(C, t)
t = ins.db:resolveType(C, 'B::C')
assertEqual(C, t)
t = ins.db:resolveType(C, 'C')
assertEqual(C, t)
end
function should.findAttributesInParent()
local B = ins:find('Nem::B')
local res = {}
for var in B:attributes() do
table.insert(res, var.name)
end
assertValueEqual({
'nb_',
'a',
'c',
}, res)
end
function should.resolveElementsOutOfNamespace()
local e = ins:find('nmRectf')
assertEqual('dub.Class', e.type)
assertEqual('nmRectf', e:fullname())
end
function should.resolveElementsOutOfNamespace()
local e = ins:find('Nem::Rectf')
assertEqual('dub.Class', e.type)
assertEqual('Nem::Rectf', e:fullname())
end
function should.notUseSingleLibNameInNamespace()
ins.db.name = 'foo'
local e = ins:find('Nem')
assertEqual('dub.Namespace', e.type)
assertEqual('Nem', e:fullname())
ins.db.name = nil
end
function should.findMethodsInParent()
local B = ins:find('Nem::B')
local res = {}
for met in B:methods() do
table.insert(res, met.name)
end
assertValueEqual({
'~B',
B.SET_ATTR_NAME,
B.GET_ATTR_NAME,
'B',
'__tostring',
'getC',
}, res)
end
--=============================================== namespace functions
function should.listNamespaceFunctions()
local res = {}
for func in ins.db:functions() do
lub.insertSorted(res, func:fullcname())
end
assertValueEqual({
'Nem::addTwo',
'Nem::customGlobal',
'addTwoOut',
'customGlobalOut',
}, res)
end
function should.setFlagsOnNamespaceFunction()
local addTwo = ins:find('Nem::addTwo')
assertEqual('dub.Function', addTwo.type)
assertEqual(false, addTwo.member)
end
--=============================================== namespace constants
function should.findNamespaceConstants()
local n = ins:find('Nem')
local enum = ins:find('Nem::NamespaceConstant')
assertEqual('dub.Enum', enum.type)
assertTrue(n.has_constants)
end
function should.listNamespaceConstants()
local n = ins:find('Nem')
local res = {}
for const in n:constants() do
lub.insertSorted(res, const)
end
assertValueEqual({
'One',
'Three',
'Two',
}, res)
end
function should.listAllConstants()
local res = {}
for const in ins.db:constants() do
lub.insertSorted(res, const)
end
assertValueEqual({
'One',
'Three',
'Two',
}, res)
end
should:test()
|
--[[------------------------------------------------------
dub.Inspector test
------------------
Test introspective operations with the 'namespace' group
of classes.
--]]------------------------------------------------------
local lub = require 'lub'
local lut = require 'lut'
local dub = require 'dub'
local should = lut.Test('dub.Inspector - namespace', {coverage = false})
local ins
function should.setup()
dub.warn = dub.silentWarn
if not ins then
ins = dub.Inspector {
INPUT = {
lub.path '|fixtures/namespace',
},
doc_dir = lub.path '|tmp',
}
end
end
function should.teardown()
dub.warn = dub.printWarn
end
--=============================================== TESTS
function should.findNamespace()
local Nem = ins:find('Nem')
assertEqual('dub.Namespace', Nem.type)
end
function should.listNamespaces()
local res = {}
for nm in ins.db:namespaces() do
table.insert(res, nm.name)
end
assertValueEqual({
'Nem',
}, res)
end
function should.listHeaders()
local res = {}
for h in ins.db:headers({ins:find('Nem::A')}) do
local name = string.match(h, '/([^/]+/[^/]+)$')
if name ~= 'namespace/B.h' and
name ~= 'namespace/Out.h' then
-- FIXME not sure why B.h header appears when testing with luajit on linux
-- but not with regular lua.
lub.insertSorted(res, name)
end
end
assertValueEqual({
'namespace/A.h',
'namespace/constants.h',
'namespace/nem.h',
}, res)
end
function should.findByFullname()
local A = ins:find('Nem::A')
assertEqual('dub.Class', A.type)
end
function should.findNamespace()
local A = ins:find('Nem::A')
assertEqual('Nem', A:namespace().name)
end
function should.findTemplate()
local TRect = ins:find('Nem::TRect')
assertEqual('TRect', TRect.name)
assertEqual('dub.CTemplate', TRect.type)
end
function should.findTypdefByFullname()
local Rect = ins:find('Nem::Rect')
assertEqual('Rect', Rect.name)
assertEqual('Nem', Rect:namespace().name)
assertEqual('dub.Class', Rect.type)
end
function should.findNestedClassByFullname()
local C = ins:find('Nem::B::C')
assertEqual('dub.Class', C.type)
assertEqual('C', C.name)
end
function should.findNamespaceFromNestedClass()
local C = ins:find('Nem::B::C')
assertEqual('Nem', C:namespace().name)
end
function should.haveFullypeReturnValueInCtor()
local C = ins:find('Nem::B::C')
local met = C:method('C')
assertEqual('B::C *', met.return_value.create_name)
end
function should.prefixInnerClassInTypes()
local C = ins:find('Nem::B::C')
assertEqual('B::C *', C.create_name)
end
function should.properlyResolveType()
local C = ins:find('Nem::B::C')
local t = ins.db:resolveType(C, 'Nem::B::C')
assertEqual(C, t)
t = ins.db:resolveType(C, 'B::C')
assertEqual(C, t)
t = ins.db:resolveType(C, 'C')
assertEqual(C, t)
end
function should.findAttributesInParent()
local B = ins:find('Nem::B')
local res = {}
for var in B:attributes() do
table.insert(res, var.name)
end
assertValueEqual({
'nb_',
'a',
'c',
}, res)
end
function should.resolveElementsOutOfNamespace()
local e = ins:find('nmRectf')
assertEqual('dub.Class', e.type)
assertEqual('nmRectf', e:fullname())
end
function should.resolveElementsOutOfNamespace()
local e = ins:find('Nem::Rectf')
assertEqual('dub.Class', e.type)
assertEqual('Nem::Rectf', e:fullname())
end
function should.notUseSingleLibNameInNamespace()
ins.db.name = 'foo'
local e = ins:find('Nem')
assertEqual('dub.Namespace', e.type)
assertEqual('Nem', e:fullname())
ins.db.name = nil
end
function should.findMethodsInParent()
local B = ins:find('Nem::B')
local res = {}
for met in B:methods() do
table.insert(res, met.name)
end
assertValueEqual({
'~B',
B.SET_ATTR_NAME,
B.GET_ATTR_NAME,
'B',
'__tostring',
'getC',
}, res)
end
--=============================================== namespace functions
function should.listNamespaceFunctions()
local res = {}
for func in ins.db:functions() do
lub.insertSorted(res, func:fullcname())
end
assertValueEqual({
'Nem::addTwo',
'Nem::customGlobal',
'addTwoOut',
'customGlobalOut',
}, res)
end
function should.setFlagsOnNamespaceFunction()
local addTwo = ins:find('Nem::addTwo')
assertEqual('dub.Function', addTwo.type)
assertEqual(false, addTwo.member)
end
--=============================================== namespace constants
function should.findNamespaceConstants()
local n = ins:find('Nem')
local enum = ins:find('Nem::NamespaceConstant')
assertEqual('dub.Enum', enum.type)
assertTrue(n.has_constants)
end
function should.listNamespaceConstants()
local n = ins:find('Nem')
local res = {}
for const in n:constants() do
lub.insertSorted(res, const)
end
assertValueEqual({
'One',
'Three',
'Two',
}, res)
end
function should.listAllConstants()
local res = {}
for const in ins.db:constants() do
lub.insertSorted(res, const)
end
assertValueEqual({
'One',
'Three',
'Two',
}, res)
end
should:test()
|
Temporary test fix to see if we can build on travis.
|
Temporary test fix to see if we can build on travis.
|
Lua
|
mit
|
Laeeth/dub,Laeeth/dub,lubyk/dub,lubyk/dub
|
ba4fd170ee37d10103de5ea8f5d428971780f80c
|
main.lua
|
main.lua
|
io.stdout:setvbuf("no")
local reboot, events = false
--==Contribution Guide==--
--[[
I did create an events system for liko12, making my work more modular.
Below there is a modified love.run function which implements 4 things:
- Instead of calling love callbacks, it triggers the events with name "love:callback", for ex: "love:mousepressed".
- It contains a small and a nice trick which reloads all the code files (expect main.lua & conf.lua) and reboots liko12 without haveing to restart love.
- When the love.graphics is active (usable) it triggers "love:graphics" event.
- If any "love:quit" event returned true, the quit will be canceled.
About the soft restart:
* To do a soft restart trigger the "love:reboot" event.
* This works by clearing package.loaded expect bit library, then calling love.graphics.reset(), and reseting the events library, and finally restarts love.run from the top (there's an extra while loop you can see).
* In case you changed something in main.lua or conf.lua then you can do a hard restart by calling love.event.quit("restart")
* In DiskOS you can run 'reboot' command to do a soft reboot, or 'reboot hard' to do a hard one (by restarting love).
I don't think anyone would want to edit anything in this file.
==Contributers to this file==
(Add your name when contributing to this file)
- Rami Sabbagh (RamiLego4Game)
]]
love.setDeprecationOutput(false) --Disable desprecation output temporary (Until the 11.0 update is done)
local package_exceptions = {
"bit", "ffi", "ssl.core", "ssl.context", "ssl.x209", "ssl", "https", "socket.http", "ltn12", "mime", "socket.smtp", "socket", "socket.url"
}
for k,v in ipairs(package_exceptions) do package_exceptions[v] = k end
love.filesystem.load("Engine/errhand.lua")() --Apply the custom error handler.
--Internal Callbacks--
function love.load(args)
love.filesystem.load("BIOS/init.lua")() --Initialize the BIOS.
events:trigger("love:load")
end
function love.run(arg)
local function runReset()
events = require("Engine.events")
events:register("love:reboot",function(args) --Code can trigger this event to do a soft restart.
reboot = args or {}
end)
if love.math then
love.math.setRandomSeed(os.time())
end
if love.load then love.load(reboot or arg) end reboot = false
-- We don't want the first frame's dt to include time taken by love.load.
if love.timer then love.timer.step() end
local dt = 0
end
return function()
-- Process events.
if love.event then
love.event.pump()
for name, a,b,c,d,e,f in love.event.poll() do
if name == "quit" then
local r = events:trigger("love:quit")
--If any event returns true the quit will be cancelled
for k,v in pairs(r) do
if v and v[1] then r = nil break end
end
if r then return a end
else
events:trigger("love:"..name,a,b,c,d,e,f)
end
end
end
-- Update dt, as we'll be passing it to update
if love.timer then
love.timer.step()
dt = love.timer.getDelta()
end
-- Call update and draw
events:trigger("love:update",dt) -- will pass 0 if love.timer is disabled
if love.graphics and love.graphics.isActive() then
events:trigger("love:graphics")
end
if love.timer then love.timer.sleep(0.001) end
if reboot then
for k,v in pairs(package.loaded) do
if not package_exceptions[k] then package.loaded[k] = nil end
end--Reset the required packages
love.graphics.reset() --Reset the GPU
events = nil --Must undefine this.
runReset() --Reset
end
end
end
|
io.stdout:setvbuf("no")
local reboot, events = false
--==Contribution Guide==--
--[[
I did create an events system for liko12, making my work more modular.
Below there is a modified love.run function which implements 4 things:
- Instead of calling love callbacks, it triggers the events with name "love:callback", for ex: "love:mousepressed".
- It contains a small and a nice trick which reloads all the code files (expect main.lua & conf.lua) and reboots liko12 without haveing to restart love.
- When the love.graphics is active (usable) it triggers "love:graphics" event.
- If any "love:quit" event returned true, the quit will be canceled.
About the soft restart:
* To do a soft restart trigger the "love:reboot" event.
* This works by clearing package.loaded expect bit library, then calling love.graphics.reset(), and reseting the events library, and finally restarts love.run from the top (there's an extra while loop you can see).
* In case you changed something in main.lua or conf.lua then you can do a hard restart by calling love.event.quit("restart")
* In DiskOS you can run 'reboot' command to do a soft reboot, or 'reboot hard' to do a hard one (by restarting love).
I don't think anyone would want to edit anything in this file.
==Contributers to this file==
(Add your name when contributing to this file)
- Rami Sabbagh (RamiLego4Game)
]]
love.setDeprecationOutput(false) --Disable desprecation output temporary (Until the 11.0 update is done)
local package_exceptions = {
"bit", "ffi", "ssl.core", "ssl.context", "ssl.x209", "ssl", "https", "socket.http", "ltn12", "mime", "socket.smtp", "socket", "socket.url"
}
for k,v in ipairs(package_exceptions) do package_exceptions[v] = k end
love.filesystem.load("Engine/errhand.lua")() --Apply the custom error handler.
--Internal Callbacks--
function love.load(args)
love.filesystem.load("BIOS/init.lua")() --Initialize the BIOS.
events:trigger("love:load")
end
function love.run(arg)
local function runReset()
events = require("Engine.events")
events:register("love:reboot",function(args) --Code can trigger this event to do a soft restart.
reboot = args or {}
end)
if love.math then
love.math.setRandomSeed(os.time())
end
if love.load then love.load(reboot or arg) end reboot = false
-- We don't want the first frame's dt to include time taken by love.load.
if love.timer then love.timer.step() end
local dt = 0
end
runReset() --Reset for the first time
return function()
-- Process events.
if love.event then
love.event.pump()
for name, a,b,c,d,e,f in love.event.poll() do
if name == "quit" then
local r = events:trigger("love:quit")
--If any event returns true the quit will be cancelled
for k,v in pairs(r) do
if v and v[1] then r = nil break end
end
if r then return a end
else
events:trigger("love:"..name,a,b,c,d,e,f)
end
end
end
-- Update dt, as we'll be passing it to update
if love.timer then
love.timer.step()
dt = love.timer.getDelta()
end
-- Call update and draw
events:trigger("love:update",dt) -- will pass 0 if love.timer is disabled
if love.graphics and love.graphics.isActive() then
events:trigger("love:graphics")
end
if love.timer then love.timer.sleep(0.001) end
if reboot then
for k,v in pairs(package.loaded) do
if not package_exceptions[k] then package.loaded[k] = nil end
end--Reset the required packages
love.graphics.reset() --Reset the GPU
events = nil --Must undefine this.
runReset() --Reset
end
end
end
|
Fix main.lua crash
|
Fix main.lua crash
Former-commit-id: 32f39eea5376f5fdb4c1b5eca3d1ba5ddd26b59c
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
895e5a0a04147733cadee962563cf5e482ada529
|
tools/migration/migrator/prosody_files.lua
|
tools/migration/migrator/prosody_files.lua
|
local print = print;
local assert = assert;
local setmetatable = setmetatable;
local tonumber = tonumber;
local char = string.char;
local coroutine = coroutine;
local lfs = require "lfs";
local loadfile = loadfile;
local pcall = pcall;
local mtools = require "migrator.mtools";
local next = next;
local pairs = pairs;
local json = require "util.json";
local os_getenv = os.getenv;
prosody = {};
local dm = require "util.datamanager"
module "prosody_files"
local function is_dir(path) return lfs.attributes(path, "mode") == "directory"; end
local function is_file(path) return lfs.attributes(path, "mode") == "file"; end
local function clean_path(path)
return path:gsub("\\", "/"):gsub("//+", "/"):gsub("^~", os_getenv("HOME") or "~");
end
local encode, decode; do
local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
decode = function (s) return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes)); end
encode = function (s) return s and (s:gsub("%W", function (c) return format("%%%02x", c:byte()); end)); end
end
local function decode_dir(x)
if x:gsub("%%%x%x", ""):gsub("[a-zA-Z0-9]", "") == "" then
return decode(x);
end
end
local function decode_file(x)
if x:match(".%.dat$") and x:gsub("%.dat$", ""):gsub("%%%x%x", ""):gsub("[a-zA-Z0-9]", "") == "" then
return decode(x:gsub("%.dat$", ""));
end
end
local function prosody_dir(path, ondir, onfile, ...)
for x in lfs.dir(path) do
local xpath = path.."/"..x;
if decode_dir(x) and is_dir(xpath) then
ondir(xpath, x, ...);
elseif decode_file(x) and is_file(xpath) then
onfile(xpath, x, ...);
end
end
end
local function handle_root_file(path, name)
--print("root file: ", decode_file(name))
coroutine.yield { user = nil, host = nil, store = decode_file(name) };
end
local function handle_host_file(path, name, host)
--print("host file: ", decode_dir(host).."/"..decode_file(name))
coroutine.yield { user = nil, host = decode_dir(host), store = decode_file(name) };
end
local function handle_store_file(path, name, store, host)
--print("store file: ", decode_file(name).."@"..decode_dir(host).."/"..decode_dir(store))
coroutine.yield { user = decode_file(name), host = decode_dir(host), store = decode_dir(store) };
end
local function handle_host_store(path, name, host)
prosody_dir(path, function() end, handle_store_file, name, host);
end
local function handle_host_dir(path, name)
prosody_dir(path, handle_host_store, handle_host_file, name);
end
local function handle_root_dir(path)
prosody_dir(path, handle_host_dir, handle_root_file);
end
local function decode_user(item)
local userdata = {
user = item[1].user;
host = item[1].host;
stores = {};
};
for i=1,#item do -- loop over stores
local result = {};
local store = item[i];
userdata.stores[store.store] = store.data;
store.user = nil; store.host = nil; store.store = nil;
end
return userdata;
end
function reader(input)
local path = clean_path(assert(input.path, "no input.path specified"));
assert(is_dir(path), "input.path is not a directory");
local iter = coroutine.wrap(function()handle_root_dir(path);end);
-- get per-user stores, sorted
local iter = mtools.sorted {
reader = function()
local x = iter();
if x then
dm.set_data_path(path);
local err;
x.data, err = dm.load(x.user, x.host, x.store);
if x.data == nil and err then
error(("Error loading data at path %s for %s@%s (%s store)")
:format(path, x.user or "<nil>", x.host or "<nil>", x.store or "<nil>"), 0);
end
return x;
end
end;
sorter = function(a, b)
local a_host, a_user, a_store = a.host or "", a.user or "", a.store or "";
local b_host, b_user, b_store = b.host or "", b.user or "", b.store or "";
return a_host > b_host or (a_host==b_host and a_user > b_user) or (a_host==b_host and a_user==b_user and a_store > b_store);
end;
};
-- merge stores to get users
iter = mtools.merged(iter, function(a, b)
return (a.host == b.host and a.user == b.user);
end);
return function()
local x = iter();
return x and decode_user(x);
end
end
function writer(output)
local path = clean_path(assert(output.path, "no output.path specified"));
assert(is_dir(path), "output.path is not a directory");
return function(item)
if not item then return; end -- end of input
dm.set_data_path(path);
for store, data in pairs(item.stores) do
assert(dm.store(item.user, item.host, store, data));
end
end
end
return _M;
|
local print = print;
local assert = assert;
local setmetatable = setmetatable;
local tonumber = tonumber;
local char = string.char;
local coroutine = coroutine;
local lfs = require "lfs";
local loadfile = loadfile;
local pcall = pcall;
local mtools = require "migrator.mtools";
local next = next;
local pairs = pairs;
local json = require "util.json";
local os_getenv = os.getenv;
local error = error;
prosody = {};
local dm = require "util.datamanager"
module "prosody_files"
local function is_dir(path) return lfs.attributes(path, "mode") == "directory"; end
local function is_file(path) return lfs.attributes(path, "mode") == "file"; end
local function clean_path(path)
return path:gsub("\\", "/"):gsub("//+", "/"):gsub("^~", os_getenv("HOME") or "~");
end
local encode, decode; do
local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
decode = function (s) return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes)); end
encode = function (s) return s and (s:gsub("%W", function (c) return format("%%%02x", c:byte()); end)); end
end
local function decode_dir(x)
if x:gsub("%%%x%x", ""):gsub("[a-zA-Z0-9]", "") == "" then
return decode(x);
end
end
local function decode_file(x)
if x:match(".%.dat$") and x:gsub("%.dat$", ""):gsub("%%%x%x", ""):gsub("[a-zA-Z0-9]", "") == "" then
return decode(x:gsub("%.dat$", ""));
end
end
local function prosody_dir(path, ondir, onfile, ...)
for x in lfs.dir(path) do
local xpath = path.."/"..x;
if decode_dir(x) and is_dir(xpath) then
ondir(xpath, x, ...);
elseif decode_file(x) and is_file(xpath) then
onfile(xpath, x, ...);
end
end
end
local function handle_root_file(path, name)
--print("root file: ", decode_file(name))
coroutine.yield { user = nil, host = nil, store = decode_file(name) };
end
local function handle_host_file(path, name, host)
--print("host file: ", decode_dir(host).."/"..decode_file(name))
coroutine.yield { user = nil, host = decode_dir(host), store = decode_file(name) };
end
local function handle_store_file(path, name, store, host)
--print("store file: ", decode_file(name).."@"..decode_dir(host).."/"..decode_dir(store))
coroutine.yield { user = decode_file(name), host = decode_dir(host), store = decode_dir(store) };
end
local function handle_host_store(path, name, host)
prosody_dir(path, function() end, handle_store_file, name, host);
end
local function handle_host_dir(path, name)
prosody_dir(path, handle_host_store, handle_host_file, name);
end
local function handle_root_dir(path)
prosody_dir(path, handle_host_dir, handle_root_file);
end
local function decode_user(item)
local userdata = {
user = item[1].user;
host = item[1].host;
stores = {};
};
for i=1,#item do -- loop over stores
local result = {};
local store = item[i];
userdata.stores[store.store] = store.data;
store.user = nil; store.host = nil; store.store = nil;
end
return userdata;
end
function reader(input)
local path = clean_path(assert(input.path, "no input.path specified"));
assert(is_dir(path), "input.path is not a directory");
local iter = coroutine.wrap(function()handle_root_dir(path);end);
-- get per-user stores, sorted
local iter = mtools.sorted {
reader = function()
local x = iter();
while x do
dm.set_data_path(path);
local err;
x.data, err = dm.load(x.user, x.host, x.store);
if x.data == nil and err then
local p = dm.getpath(x.user, x.host, x.store);
print(("Error loading data at path %s for %s@%s (%s store): %s")
:format(p, x.user or "<nil>", x.host or "<nil>", x.store or "<nil>", err or "<nil>"));
else
return x;
end
x = iter();
end
end;
sorter = function(a, b)
local a_host, a_user, a_store = a.host or "", a.user or "", a.store or "";
local b_host, b_user, b_store = b.host or "", b.user or "", b.store or "";
return a_host > b_host or (a_host==b_host and a_user > b_user) or (a_host==b_host and a_user==b_user and a_store > b_store);
end;
};
-- merge stores to get users
iter = mtools.merged(iter, function(a, b)
return (a.host == b.host and a.user == b.user);
end);
return function()
local x = iter();
return x and decode_user(x);
end
end
function writer(output)
local path = clean_path(assert(output.path, "no output.path specified"));
assert(is_dir(path), "output.path is not a directory");
return function(item)
if not item then return; end -- end of input
dm.set_data_path(path);
for store, data in pairs(item.stores) do
assert(dm.store(item.user, item.host, store, data));
end
end
end
return _M;
|
tools/migration/migrator/prosody_files: Fix undefined global access of ?error?, print the actual error message and correct file path in the error message when we fail to load a file, skip broken files instead of failing migration.
|
tools/migration/migrator/prosody_files: Fix undefined global access of ?error?, print the actual error message and correct file path in the error message when we fail to load a file, skip broken files instead of failing migration.
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
63f81fa4aa31408063baf8b00124b5d04349e567
|
fimbul/eh/range.lua
|
fimbul/eh/range.lua
|
[email protected]
local range = {}
local rules = require('fimbul.eh.rules')
function range:new(value)
local neu = {}
setmetatable(neu, self)
self.__index = self
neu._value = value or 0
return neu
end
function range:value(v)
if v == nil then
return self._value
else
if v < 0 then
error('Negative ranges are not allowed.')
end
self._value = v
end
end
function range:ranges()
local r = {}
table.insert(r, self:value())
table.insert(r, self:maximum_lower_bound())
table.insert(r, self:far_upper_bound())
table.insert(r, self:medium_upper_bound())
table.insert(r, self:close_upper_bound())
return r
end
function range:maximum_upper_bound()
return self:value()
end
function range:maximum_lower_bound()
return self:value() * rules.combat.range.bounds[rules.combat.range.MAXIMUM]
end
function range:far_lower_bound()
return self:value() * rules.combat.range.bounds[rules.combat.range.FAR]
end
function range:far_upper_bound()
return self:maximum_lower_bound()
end
function range:medium_lower_bound()
return self:value() * rules.combat.range.bounds[rules.combat.range.MEDIUM]
end
function range:medium_upper_bound()
return self:far_lower_bound()
end
function range:close_lower_bound()
return self:value() * rules.combat.range.bounds[rules.combat.range.CLOSE]
end
function range:close_upper_bound()
return self:medium_lower_bound()
end
function range:is_maximum_range(value)
return value >= self:maximum_range()
end
function range:determine(v)
if v >= self:close_lower_bound() and v <= self:close_upper_bound() then
return rules.combat.range.CLOSE
elseif v > self:close_upper_bound() and v <= self:medium_upper_bound() then
return rules.combat.range.MEDIUM
elseif v > self:medium_upper_bound() and v <= self:far_upper_bound() then
return rules.combat.range.FAR
elseif v > self:far_upper_bound() and v <= self:maximum_upper_bound() then
return rules.combat.MAXIMUM_RANGE
elseif v > self:value() then
return rules.combat.range.OUTOF
end
return nil
end
return range
|
[email protected]
local range = {}
local rules = require('fimbul.eh.rules')
function range:new(value)
local neu = {}
setmetatable(neu, self)
self.__index = self
neu._value = value or 0
return neu
end
function range:value(v)
if v == nil then
return self._value
else
if v < 0 then
error('Negative ranges are not allowed.')
end
self._value = v
end
end
function range:ranges()
local r = {}
table.insert(r, self:value())
table.insert(r, self:maximum_lower_bound())
table.insert(r, self:far_upper_bound())
table.insert(r, self:medium_upper_bound())
table.insert(r, self:close_upper_bound())
return r
end
function range:maximum_upper_bound()
return self:value()
end
function range:maximum_lower_bound()
return self:value() * rules.combat.range.bounds[rules.combat.range.MAXIMUM]
end
function range:far_lower_bound()
return self:value() * rules.combat.range.bounds[rules.combat.range.FAR]
end
function range:far_upper_bound()
return self:maximum_lower_bound()
end
function range:medium_lower_bound()
return self:value() * rules.combat.range.bounds[rules.combat.range.MEDIUM]
end
function range:medium_upper_bound()
return self:far_lower_bound()
end
function range:close_lower_bound()
return self:value() * rules.combat.range.bounds[rules.combat.range.CLOSE]
end
function range:close_upper_bound()
return self:medium_lower_bound()
end
function range:determine(v)
if v >= self:close_lower_bound() and v <= self:close_upper_bound() then
return rules.combat.range.CLOSE
elseif v > self:close_upper_bound() and v <= self:medium_upper_bound() then
return rules.combat.range.MEDIUM
elseif v > self:medium_upper_bound() and v <= self:far_upper_bound() then
return rules.combat.range.FAR
elseif v > self:far_upper_bound() and v <= self:maximum_upper_bound() then
return rules.combat.range.MAXIMUM
elseif v > self:maximium_upper_bound() then
return rules.combat.range.OUTOF
end
return nil
end
return range
|
Fixed range class.
|
Fixed range class.
|
Lua
|
bsd-2-clause
|
n0la/fimbul
|
db82e99dee520a1751cc093c709da45f1e4fdf60
|
lua/starfall/libs_sh/hook.lua
|
lua/starfall/libs_sh/hook.lua
|
-------------------------------------------------------------------------------
-- Hook library
-------------------------------------------------------------------------------
--- Deals with hooks
-- @shared
local hook_library, _ = SF.Libraries.Register("hook")
local registered_instances = {}
--- Sets a hook function
function hook_library.add(hookname, name, func)
SF.CheckType(hookname,"string")
SF.CheckType(name,"string")
if func then SF.CheckType(func,"function") else return end
local inst = SF.instance
local hooks = inst.hooks[hookname:lower()]
if not hooks then
hooks = {}
inst.hooks[hookname:lower()] = hooks
end
hooks[name] = func
registered_instances[inst] = true
end
--- Run a hook
-- @shared
-- @param hookname The hook name
-- @param ... arguments
function hook_library.run(hookname, ...)
SF.CheckType(hookname,"string")
local instance = SF.instance
local lower = hookname:lower()
if instance.hooks[lower] then
for k,v in pairs( instance.hooks[lower] ) do
local ok, tbl, traceback = instance:runWithOps(v, ...)--instance:runFunction( v )
if not ok and instance.runOnError then
instance.runOnError( tbl[1] )
hook_library.remove( hookname, k )
elseif next(tbl) ~= nil then
return unpack( tbl )
end
end
end
end
--- Remove a hook
-- @shared
-- @param hookname The hook name
-- @param name The unique name for this hook
function hook_library.remove( hookname, name )
SF.CheckType(hookname,"string")
SF.CheckType(name,"string")
local instance = SF.instance
local lower = hookname:lower()
if instance.hooks[lower] then
instance.hooks[lower][name] = nil
if not next(instance.hooks[lower]) then
instance.hooks[lower] = nil
end
end
if not next(instance.hooks) then
registered_instances[instance] = nil
end
end
SF.Libraries.AddHook("deinitialize",function(instance)
registered_instances[instance] = nil
end)
--[[
local blocked_types = {
PhysObj = true,
NPC = true,
}
local function wrap( value )
if type(value) == "table" then
return setmetatable( {}, {__metatable = "table", __index = value, __newindex = function() end} )
elseif blocked_types[type(value)] then
return nil
else
return SF.WrapObject( value ) or value
end
end
-- Helper function for hookAdd
local function wrapArguments( ... )
local t = {...}
return wrap(t[1]), wrap(t[2]), wrap(t[3]), wrap(t[4]), wrap(t[5]), wrap(t[6])
end
]]
local wrapArguments = SF.Sanitize
--local run = SF.RunScriptHook
local function run( hookname, customfunc, ... )
for instance,_ in pairs( registered_instances ) do
if instance.hooks[hookname] then
for name, func in pairs( instance.hooks[hookname] ) do
local ok, ret = instance:runFunctionT( func, ... )
if ok and customfunc then
return customfunc( instance, ret )
end
end
end
end
end
local hooks = {}
--- Add a GMod hook so that SF gets access to it
-- @shared
-- @param hookname The hook name. In-SF hookname will be lowercased
-- @param customfunc Optional custom function
function SF.hookAdd( hookname, customfunc )
hooks[#hooks+1] = hookname
local lower = hookname:lower()
hook.Add( hookname, "SF_" .. hookname, function(...)
return run( lower, customfunc, wrapArguments( ... ) )
end)
end
--- Gets a list of all available hooks
-- @shared
function hook_library.getList()
return setmetatable({},{__metatable = "table", __index = hooks, __newindex = function() end})
end
local add = SF.hookAdd
if SERVER then
-- Server hooks
add( "GravGunOnPickedUp" )
add( "GravGunOnDropped" )
add( "OnPhysgunFreeze" )
add( "OnPhysgunReload" )
add( "PlayerDeath" )
add( "PlayerDisconnected" )
add( "PlayerInitialSpawn" )
add( "PlayerSpawn" )
add( "PlayerLeaveVehicle" )
add( "PlayerSay", function( instance, args ) if args then return args[1] end end )
add( "PlayerSpray" )
add( "PlayerUse" )
add( "PlayerSwitchFlashlight" )
else
-- Client hooks
-- todo
end
-- Shared hooks
-- Player hooks
add( "PlayerHurt" )
add( "PlayerNoClip" )
add( "KeyPress" )
add( "KeyRelease" )
add( "GravGunPunt" )
add( "PhysgunPickup" )
add( "PhysgunDrop" )
-- Entity hooks
add( "OnEntityCreated" )
add( "EntityRemoved" )
-- Other
add( "EndEntityDriving" )
add( "StartEntityDriving" )
|
-------------------------------------------------------------------------------
-- Hook library
-------------------------------------------------------------------------------
--- Deals with hooks
-- @shared
local hook_library, _ = SF.Libraries.Register("hook")
local registered_instances = {}
--- Sets a hook function
function hook_library.add(hookname, name, func)
SF.CheckType(hookname,"string")
SF.CheckType(name,"string")
if func then SF.CheckType(func,"function") else return end
local inst = SF.instance
local hooks = inst.hooks[hookname:lower()]
if not hooks then
hooks = {}
inst.hooks[hookname:lower()] = hooks
end
hooks[name] = func
registered_instances[inst] = true
end
--- Run a hook
-- @shared
-- @param hookname The hook name
-- @param ... arguments
function hook_library.run(hookname, ...)
SF.CheckType(hookname,"string")
local instance = SF.instance
local lower = hookname:lower()
if instance.hooks[lower] then
for k,v in pairs( instance.hooks[lower] ) do
local ok, tbl, traceback = instance:runWithOps(v, ...)--instance:runFunction( v )
if not ok and instance.runOnError then
instance.runOnError( tbl[1] )
hook_library.remove( hookname, k )
elseif next(tbl) ~= nil then
return unpack( tbl )
end
end
end
end
--- Remove a hook
-- @shared
-- @param hookname The hook name
-- @param name The unique name for this hook
function hook_library.remove( hookname, name )
SF.CheckType(hookname,"string")
SF.CheckType(name,"string")
local instance = SF.instance
local lower = hookname:lower()
if instance.hooks[lower] then
instance.hooks[lower][name] = nil
if not next(instance.hooks[lower]) then
instance.hooks[lower] = nil
end
end
if not next(instance.hooks) then
registered_instances[instance] = nil
end
end
SF.Libraries.AddHook("deinitialize",function(instance)
registered_instances[instance] = nil
end)
SF.Libraries.AddHook("cleanup",function(instance)
if instance.error then
registered_instances[instance] = nil
instance.hooks = {}
end
end)
--[[
local blocked_types = {
PhysObj = true,
NPC = true,
}
local function wrap( value )
if type(value) == "table" then
return setmetatable( {}, {__metatable = "table", __index = value, __newindex = function() end} )
elseif blocked_types[type(value)] then
return nil
else
return SF.WrapObject( value ) or value
end
end
-- Helper function for hookAdd
local function wrapArguments( ... )
local t = {...}
return wrap(t[1]), wrap(t[2]), wrap(t[3]), wrap(t[4]), wrap(t[5]), wrap(t[6])
end
]]
local wrapArguments = SF.Sanitize
--local run = SF.RunScriptHook
local function run( hookname, customfunc, ... )
for instance,_ in pairs( registered_instances ) do
if instance.hooks[hookname] then
for name, func in pairs( instance.hooks[hookname] ) do
local ok, ret = instance:runFunctionT( func, ... )
if ok and customfunc then
return customfunc( instance, ret )
end
end
end
end
end
local hooks = {}
--- Add a GMod hook so that SF gets access to it
-- @shared
-- @param hookname The hook name. In-SF hookname will be lowercased
-- @param customfunc Optional custom function
function SF.hookAdd( hookname, customfunc )
hooks[#hooks+1] = hookname
local lower = hookname:lower()
hook.Add( hookname, "SF_" .. hookname, function(...)
return run( lower, customfunc, wrapArguments( ... ) )
end)
end
--- Gets a list of all available hooks
-- @shared
function hook_library.getList()
return setmetatable({},{__metatable = "table", __index = hooks, __newindex = function() end})
end
local add = SF.hookAdd
if SERVER then
-- Server hooks
add( "GravGunOnPickedUp" )
add( "GravGunOnDropped" )
add( "OnPhysgunFreeze" )
add( "OnPhysgunReload" )
add( "PlayerDeath" )
add( "PlayerDisconnected" )
add( "PlayerInitialSpawn" )
add( "PlayerSpawn" )
add( "PlayerLeaveVehicle" )
add( "PlayerSay", function( instance, args ) if args then return args[1] end end )
add( "PlayerSpray" )
add( "PlayerUse" )
add( "PlayerSwitchFlashlight" )
else
-- Client hooks
-- todo
end
-- Shared hooks
-- Player hooks
add( "PlayerHurt" )
add( "PlayerNoClip" )
add( "KeyPress" )
add( "KeyRelease" )
add( "GravGunPunt" )
add( "PhysgunPickup" )
add( "PhysgunDrop" )
-- Entity hooks
add( "OnEntityCreated" )
add( "EntityRemoved" )
-- Other
add( "EndEntityDriving" )
add( "StartEntityDriving" )
|
untested fix for errored starfall chips still calling hooks
|
untested fix for errored starfall chips still calling hooks
untested fix for errored starfall chips still calling hooks
|
Lua
|
bsd-3-clause
|
INPStarfall/Starfall,Xandaros/Starfall,Ingenious-Gaming/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall,Jazzelhawk/Starfall,INPStarfall/Starfall,Jazzelhawk/Starfall
|
f7b298690de8cbe8fb6ff10e45432b192ab0a8f3
|
lib/srcnn.lua
|
lib/srcnn.lua
|
require 'w2nn'
-- ref: http://arxiv.org/abs/1502.01852
-- ref: http://arxiv.org/abs/1501.00092
local srcnn = {}
function srcnn.channels(model)
return model:get(model:size() - 1).weight:size(1)
end
function srcnn.waifu2x_cunn(ch)
local model = nn.Sequential()
model:add(nn.SpatialConvolutionMM(ch, 32, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(32, 32, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(32, 64, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(64, 64, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(64, 128, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(128, 128, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(128, ch, 3, 3, 1, 1, 0, 0))
model:add(nn.View(-1):setNumInputDims(3))
--model:cuda()
--print(model:forward(torch.Tensor(32, ch, 92, 92):uniform():cuda()):size())
return model
end
function srcnn.waifu2x_cudnn(ch)
local model = nn.Sequential()
model:add(cudnn.SpatialConvolution(ch, 32, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(32, 32, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(32, 64, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(64, 64, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(64, 128, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(128, 128, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(128, ch, 3, 3, 1, 1, 0, 0))
model:add(nn.View(-1):setNumInputDims(3))
--model:cuda()
--print(model:forward(torch.Tensor(32, ch, 92, 92):uniform():cuda()):size())
return model
end
function srcnn.create(model_name, backend, color)
local ch = 3
if color == "rgb" then
ch = 3
elseif color == "y" then
ch = 1
else
error("unsupported color: " + color)
end
if backend == "cunn" then
return srcnn.waifu2x_cunn(ch)
elseif backend == "cudnn" then
return srcnn.waifu2x_cudnn(ch)
else
error("unsupported backend: " + backend)
end
end
return srcnn
|
require 'w2nn'
-- ref: http://arxiv.org/abs/1502.01852
-- ref: http://arxiv.org/abs/1501.00092
local srcnn = {}
function nn.SpatialConvolutionMM:reset(stdv)
stdv = math.sqrt(2 / ((1.0 + 0.1 * 0.1) * self.kW * self.kH * self.nOutputPlane))
self.weight:normal(0, stdv)
self.bias:zero()
end
if cudnn then
function cudnn.SpatialConvolution:reset(stdv)
stdv = math.sqrt(2 / ((1.0 + 0.1 * 0.1) * self.kW * self.kH * self.nOutputPlane))
self.weight:normal(0, stdv)
self.bias:zero()
end
end
function srcnn.channels(model)
return model:get(model:size() - 1).weight:size(1)
end
function srcnn.waifu2x_cunn(ch)
local model = nn.Sequential()
model:add(nn.SpatialConvolutionMM(ch, 32, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(32, 32, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(32, 64, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(64, 64, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(64, 128, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(128, 128, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(128, ch, 3, 3, 1, 1, 0, 0))
model:add(nn.View(-1):setNumInputDims(3))
--model:cuda()
--print(model:forward(torch.Tensor(32, ch, 92, 92):uniform():cuda()):size())
return model
end
function srcnn.waifu2x_cudnn(ch)
local model = nn.Sequential()
model:add(cudnn.SpatialConvolution(ch, 32, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(32, 32, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(32, 64, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(64, 64, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(64, 128, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(128, 128, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(128, ch, 3, 3, 1, 1, 0, 0))
model:add(nn.View(-1):setNumInputDims(3))
--model:cuda()
--print(model:forward(torch.Tensor(32, ch, 92, 92):uniform():cuda()):size())
return model
end
function srcnn.create(model_name, backend, color)
local ch = 3
if color == "rgb" then
ch = 3
elseif color == "y" then
ch = 1
else
error("unsupported color: " + color)
end
if backend == "cunn" then
return srcnn.waifu2x_cunn(ch)
elseif backend == "cudnn" then
return srcnn.waifu2x_cudnn(ch)
else
error("unsupported backend: " + backend)
end
end
return srcnn
|
Fix the missing initialization function
|
Fix the missing initialization function
I don't know why was this function removed.
|
Lua
|
mit
|
higankanshi/waifu2x,vitaliylag/waifu2x,vitaliylag/waifu2x,Spitfire1900/upscaler,nagadomi/waifu2x,higankanshi/waifu2x,higankanshi/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,zyhkz/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,Spitfire1900/upscaler,nagadomi/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,vitaliylag/waifu2x
|
60c48e31b9582b8c14de17a8df7e3dbabda379ef
|
slt2.lua
|
slt2.lua
|
--[[
-- slt2 - Simple Lua Template 2
--
-- Project page: https://github.com/henix/slt2
--
-- @License
-- MIT License
--
-- @Copyright
-- Copyright (C) 2012-2013 henix.
--]]
local slt2 = {}
-- a tree fold on inclusion tree
-- @param init_func: must return a new value when called
local function include_fold(template, start_tag, end_tag, fold_func, init_func)
local result = init_func()
start_tag = start_tag or '#{'
end_tag = end_tag or '}#'
local start_tag_inc = start_tag..'include:'
local start1, end1 = string.find(template, start_tag_inc, 1, true)
local start2 = nil
local end2 = 0
while start1 ~= nil do
if start1 > end2 + 1 then -- for beginning part of file
result = fold_func(result, string.sub(template, end2 + 1, start1 - 1))
end
start2, end2 = string.find(template, end_tag, end1 + 1, true)
assert(start2, 'end tag "'..end_tag..'" missing')
do -- recursively include the file
local filename = assert(loadstring('return '..string.sub(template, end1 + 1, start2 - 1)))()
assert(filename)
local fin = assert(io.open(filename))
-- TODO: detect cyclic inclusion?
result = fold_func(result, include_fold(fin:read('*a'), start_tag, end_tag, fold_func, init_func), filename)
fin:close()
end
start1, end1 = string.find(template, start_tag_inc, end2 + 1, true)
end
result = fold_func(result, string.sub(template, end2 + 1))
return result
end
-- preprocess included files
-- @return string
function slt2.precompile(template, start_tag, end_tag)
return table.concat(include_fold(template, start_tag, end_tag, function(acc, v)
if type(v) == 'string' then
table.insert(acc, v)
elseif type(v) == 'table' then
table.insert(acc, table.concat(v))
else
error('Unknown type: '..type(v))
end
return acc
end, function() return {} end))
end
-- unique a list, preserve order
local function stable_uniq(t)
local existed = {}
local res = {}
for _, v in ipairs(t) do
if not existed[v] then
table.insert(res, v)
existed[v] = true
end
end
return res
end
-- @return { string }
function slt2.get_dependency(template, start_tag, end_tag)
return stable_uniq(include_fold(template, start_tag, end_tag, function(acc, v, name)
if type(v) == 'string' then
elseif type(v) == 'table' then
if name ~= nil then
table.insert(acc, name)
end
for _, subname in ipairs(v) do
table.insert(acc, subname)
end
else
error('Unknown type: '..type(v))
end
return acc
end, function() return {} end))
end
-- @return { name = string, code = string / function}
function slt2.loadstring(template, start_tag, end_tag, tmpl_name)
-- compile it to lua code
local lua_code = {}
start_tag = start_tag or '#{'
end_tag = end_tag or '}#'
local output_func = "coroutine.yield"
template = slt2.precompile(template, start_tag, end_tag)
local start1, end1 = string.find(template, start_tag, 1, true)
local start2 = nil
local end2 = 0
local cEqual = string.byte('=', 1)
while start1 ~= nil do
if start1 > end2 + 1 then
table.insert(lua_code, output_func..'('..string.format("%q", string.sub(template, end2 + 1, start1 - 1))..')')
end
start2, end2 = string.find(template, end_tag, end1 + 1, true)
assert(start2, 'end_tag "'..end_tag..'" missing')
if string.byte(template, end1 + 1) == cEqual then
table.insert(lua_code, output_func..'('..string.sub(template, end1 + 2, start2 - 1)..')')
else
table.insert(lua_code, string.sub(template, end1 + 1, start2 - 1))
end
start1, end1 = string.find(template, start_tag, end2 + 1, true)
end
table.insert(lua_code, output_func..'('..string.format("%q", string.sub(template, end2 + 1))..')')
local ret = { name = tmpl_name or '=(slt2.loadstring)' }
if setfenv == nil then -- lua 5.2
ret.code = table.concat(lua_code, '\n')
else -- lua 5.1
ret.code = assert(loadstring(table.concat(lua_code, '\n'), ret.name))
end
return ret
end
-- @return { name = string, code = string / function }
function slt2.loadfile(filename, start_tag, end_tag)
local fin = assert(io.open(filename))
local all = fin:read('*a')
fin:close()
local ret = slt2.loadstring(all, start_tag, end_tag, filename)
ret.name = filename
return ret
end
local mt52 = { __index = _ENV }
local mt51 = { __index = _G }
-- @return a coroutine function
function slt2.render_co(t, env)
local f
if setfenv == nil then -- lua 5.2
if env ~= nil then
setmetatable(env, mt52)
end
f = assert(load(t.code, t.name, 't', env or _ENV))
else -- lua 5.1
if env ~= nil then
setmetatable(env, mt51)
end
f = setfenv(t.code, env or _G)
end
return f
end
-- @return string
function slt2.render(t, env)
local result = {}
local co = coroutine.create(slt2.render_co(t, env))
while coroutine.status(co) ~= 'dead' do
local ok, chunk = coroutine.resume(co)
if not ok then
error(chunk)
end
table.insert(result, chunk)
end
return table.concat(result)
end
return slt2
|
--[[
-- slt2 - Simple Lua Template 2
--
-- Project page: https://github.com/henix/slt2
--
-- @License
-- MIT License
--
-- @Copyright
-- Copyright (C) 2012-2013 henix.
--]]
local slt2 = {}
-- a tree fold on inclusion tree
-- @param init_func: must return a new value when called
local function include_fold(template, start_tag, end_tag, fold_func, init_func)
local result = init_func()
start_tag = start_tag or '#{'
end_tag = end_tag or '}#'
local start_tag_inc = start_tag..'include:'
local start1, end1 = string.find(template, start_tag_inc, 1, true)
local start2 = nil
local end2 = 0
while start1 ~= nil do
if start1 > end2 + 1 then -- for beginning part of file
result = fold_func(result, string.sub(template, end2 + 1, start1 - 1))
end
start2, end2 = string.find(template, end_tag, end1 + 1, true)
assert(start2, 'end tag "'..end_tag..'" missing')
do -- recursively include the file
local filename = assert(loadstring('return '..string.sub(template, end1 + 1, start2 - 1)))()
assert(filename)
local fin = assert(io.open(filename))
-- TODO: detect cyclic inclusion?
result = fold_func(result, include_fold(fin:read('*a'), start_tag, end_tag, fold_func, init_func), filename)
fin:close()
end
start1, end1 = string.find(template, start_tag_inc, end2 + 1, true)
end
result = fold_func(result, string.sub(template, end2 + 1))
return result
end
-- preprocess included files
-- @return string
function slt2.precompile(template, start_tag, end_tag)
return table.concat(include_fold(template, start_tag, end_tag, function(acc, v)
if type(v) == 'string' then
table.insert(acc, v)
elseif type(v) == 'table' then
table.insert(acc, table.concat(v))
else
error('Unknown type: '..type(v))
end
return acc
end, function() return {} end))
end
-- unique a list, preserve order
local function stable_uniq(t)
local existed = {}
local res = {}
for _, v in ipairs(t) do
if not existed[v] then
table.insert(res, v)
existed[v] = true
end
end
return res
end
-- @return { string }
function slt2.get_dependency(template, start_tag, end_tag)
return stable_uniq(include_fold(template, start_tag, end_tag, function(acc, v, name)
if type(v) == 'string' then
elseif type(v) == 'table' then
if name ~= nil then
table.insert(acc, name)
end
for _, subname in ipairs(v) do
table.insert(acc, subname)
end
else
error('Unknown type: '..type(v))
end
return acc
end, function() return {} end))
end
-- @return { name = string, code = string / function}
function slt2.loadstring(template, start_tag, end_tag, tmpl_name)
-- compile it to lua code
local lua_code = {}
start_tag = start_tag or '#{'
end_tag = end_tag or '}#'
local output_func = "coroutine.yield"
template = slt2.precompile(template, start_tag, end_tag)
local start1, end1 = string.find(template, start_tag, 1, true)
local start2 = nil
local end2 = 0
local cEqual = string.byte('=', 1)
while start1 ~= nil do
if start1 > end2 + 1 then
table.insert(lua_code, output_func..'('..string.format("%q", string.sub(template, end2 + 1, start1 - 1))..')')
end
start2, end2 = string.find(template, end_tag, end1 + 1, true)
assert(start2, 'end_tag "'..end_tag..'" missing')
if string.byte(template, end1 + 1) == cEqual then
table.insert(lua_code, output_func..'('..string.sub(template, end1 + 2, start2 - 1)..')')
else
table.insert(lua_code, string.sub(template, end1 + 1, start2 - 1))
end
start1, end1 = string.find(template, start_tag, end2 + 1, true)
end
table.insert(lua_code, output_func..'('..string.format("%q", string.sub(template, end2 + 1))..')')
local ret = { name = tmpl_name or '=(slt2.loadstring)' }
if setfenv == nil then -- lua 5.2
ret.code = table.concat(lua_code, '\n')
else -- lua 5.1
ret.code = assert(loadstring(table.concat(lua_code, '\n'), ret.name))
end
return ret
end
-- @return { name = string, code = string / function }
function slt2.loadfile(filename, start_tag, end_tag)
local fin = assert(io.open(filename))
local all = fin:read('*a')
fin:close()
return slt2.loadstring(all, start_tag, end_tag, filename)
end
local mt52 = { __index = _ENV }
local mt51 = { __index = _G }
-- @return a coroutine function
function slt2.render_co(t, env)
local f
if setfenv == nil then -- lua 5.2
if env ~= nil then
setmetatable(env, mt52)
end
f = assert(load(t.code, t.name, 't', env or _ENV))
else -- lua 5.1
if env ~= nil then
setmetatable(env, mt51)
end
f = setfenv(t.code, env or _G)
end
return f
end
-- @return string
function slt2.render(t, env)
local result = {}
local co = coroutine.create(slt2.render_co(t, env))
while coroutine.status(co) ~= 'dead' do
local ok, chunk = coroutine.resume(co)
if not ok then
error(chunk)
end
table.insert(result, chunk)
end
return table.concat(result)
end
return slt2
|
Remove redundant assign to ret.name ; Fix #6
|
Remove redundant assign to ret.name ; Fix #6
|
Lua
|
mit
|
FSMaxB/liluat
|
4b9b3af14778ca88abdc07f8d30422e148ad14ba
|
spec/complete_spec.lua
|
spec/complete_spec.lua
|
local mock_loop = require 'spec.mock_loop'
describe("textDocument/completion #atm", function()
it("returns nothing with no symbols", function()
mock_loop(function(rpc)
local text = "\n"
local doc = {
uri = "file:///tmp/fake.lua"
}
rpc.notify("textDocument/didOpen", {
textDocument = {uri = doc.uri, text = text}
})
local callme
rpc.request("textDocument/completion", {
textDocument = doc,
position = {line = 0, character = 0}
}, function(out)
assert.same({
isIncomplete = false,
items = {}
}, out)
callme = true
end)
assert.truthy(callme)
end)
end)
it("returns local variables", function()
mock_loop(function(rpc)
local text = "local mySymbol\nreturn m"
local doc = {
uri = "file:///tmp/fake.lua"
}
rpc.notify("textDocument/didOpen", {
textDocument = {uri = doc.uri, text = text}
})
local callme
rpc.request("textDocument/completion", {
textDocument = doc,
position = {line = 1, character = 7}
}, function(out)
assert.same({
isIncomplete = false,
items = {{label = "mySymbol"}}
}, out)
callme = true
end)
assert.truthy(callme)
callme = nil
text = "local symbolA, symbolB\n return s"
rpc.notify("textDocument/didChange", {
textDocument = {uri = doc.uri},
contentChanges = {{text = text}}
})
rpc.request("textDocument/completion", {
textDocument = doc,
position = {line = 1, character = 7}
}, function(out)
assert.same({
isIncomplete = false,
items = {{label = "symbolA"},{label="symbolB"}}
}, out)
callme = true
end)
assert.truthy(callme)
callme = nil
text = "local symbolC \nlocal s\n local symbolD"
rpc.notify("textDocument/didChange", {
textDocument = {uri = doc.uri},
contentChanges = {{text = text}}
})
rpc.request("textDocument/completion", {
textDocument = doc,
position = {line = 1, character = 6}
}, function(out)
assert.same({
isIncomplete = false,
items = {{label = "symbolC"}}
}, out)
callme = true
end)
assert.truthy(callme)
end)
end)
end)
|
local mock_loop = require 'spec.mock_loop'
describe("textDocument/completion #atm", function()
it("returns nothing with no symbols", function()
mock_loop(function(rpc)
local text = "\n"
local doc = {
uri = "file:///tmp/fake.lua"
}
rpc.notify("textDocument/didOpen", {
textDocument = {uri = doc.uri, text = text}
})
local callme
rpc.request("textDocument/completion", {
textDocument = doc,
position = {line = 0, character = 0}
}, function(out)
assert.same({
isIncomplete = false,
items = {}
}, out)
callme = true
end)
assert.truthy(callme)
end)
end)
it("returns local variables", function()
mock_loop(function(rpc)
local text = "local mySymbol\nreturn m"
local doc = {
uri = "file:///tmp/fake.lua"
}
rpc.notify("textDocument/didOpen", {
textDocument = {uri = doc.uri, text = text}
})
local callme
rpc.request("textDocument/completion", {
textDocument = doc,
position = {line = 1, character = 7}
}, function(out)
table.sort(out.items, function(a, b)
return a < b
end)
assert.same({
isIncomplete = false,
items = {{label = "mySymbol"}}
}, out)
callme = true
end)
assert.truthy(callme)
callme = nil
text = "local symbolA, symbolB\n return s"
rpc.notify("textDocument/didChange", {
textDocument = {uri = doc.uri},
contentChanges = {{text = text}}
})
rpc.request("textDocument/completion", {
textDocument = doc,
position = {line = 1, character = 7}
}, function(out)
table.sort(out.items, function(a, b)
return a.label < b.label
end)
assert.same({
isIncomplete = false,
items = {{label = "symbolA"},{label="symbolB"}}
}, out)
callme = true
end)
assert.truthy(callme)
callme = nil
text = "local symbolC \nlocal s\n local symbolD"
rpc.notify("textDocument/didChange", {
textDocument = {uri = doc.uri},
contentChanges = {{text = text}}
})
rpc.request("textDocument/completion", {
textDocument = doc,
position = {line = 1, character = 6}
}, function(out)
table.sort(out.items, function(a, b)
return a < b
end)
assert.same({
isIncomplete = false,
items = {{label = "symbolC"}}
}, out)
callme = true
end)
assert.truthy(callme)
end)
end)
end)
|
Fix bug with unsequenced list
|
Fix bug with unsequenced list
all completion tests are sorted now for safety
|
Lua
|
mit
|
Alloyed/lua-lsp
|
19029bf6c2c2a7ee1b02ed938559dd764828b4ca
|
etc/querylib.lua
|
etc/querylib.lua
|
--
-- Some common queries for Ion
--
if QueryLib~=nil then
return
end
QueryLib={}
--
-- Helper functions
--
function QueryLib.make_simple_fn(prompt, initfn, handler, completor)
local function query_it(frame)
local initvalue;
if initfn then
initvalue=initfn()
end
query_query(frame, prompt, initvalue or "", handler, completor)
end
return query_it
end
function QueryLib.make_frame_fn(prompt, initfn, handler, completor)
local function query_it(frame)
local initvalue;
if initfn then
initvalue=initfn(frame)
end
local function handle_it(str)
handler(frame, str)
end
query_query(frame, prompt, initvalue or "", handle_it, completor)
end
return query_it
end
function QueryLib.make_rename_fn(prompt, getobj)
local function query_it(frame)
local obj=getobj(frame)
local function handle_it(str)
region_set_name(obj, str)
end
query_query(frame, prompt, region_name(obj) or "", handle_it, nil)
end
return query_it
end
function QueryLib.exec_handler(frame, cmd)
if string.sub(cmd, 1, 1)==":" then
cmd="ion-runinxterm " .. string.sub(cmd, 2)
end
exec_on_screen(region_screen_of(frame), cmd)
end
function QueryLib.make_yesno_handler(fn)
local function handle_yesno(_, yesno)
if yesno=="y" or yesno=="Y" or yesno=="yes" then
if arg then
fn(unpack(arg))
else
fn()
end
end
end
return handle_yesno
end
function QueryLib.make_yesno_fn(prompt, handler)
return QueryLib.make_frame_fn(prompt, nil,
QueryLib.make_yesno_handler(handler),
nil)
end
function QueryLib.getws(obj)
while obj~=nil do
if obj_is(obj, "WGenWS") then
return obj
end
obj=region_manager(obj)
end
end
function QueryLib.complete_ssh(str)
if string.len(str)==0 then
return query_ssh_hosts
end
local res={}
for _, v in ipairs(query_ssh_hosts) do
local s, e=string.find(v, str, 1, true)
if s==1 and e>=1 then
table.insert(res, v)
end
end
return res
end
function QueryLib.make_execwith_fn(prompt, init, prog, completor)
local function handle_execwith(frame, str)
exec_on_screen(region_screen_of(frame), prog .. " " .. str)
end
return QueryLib.make_frame_fn(prompt, init, handle_execwith, completor)
end
function QueryLib.gotoclient_handler(frame, str)
local cwin=lookup_clientwin(str)
if cwin==nil then
query_fwarn(frame, string.format("Could not find client window named"
.. ' "%s"', str))
else
region_goto(cwin)
end
end
function QueryLib.handler_lua(frame, code)
local f=loadstring(code)
if f then
local oldarg=arg
arg={frame, genframe_current(frame)}
pcall(f)
oldarg=arg
end
end
function QueryLib.get_initdir()
local wd=os.getenv("PWD")
if wd==nil then
wd="/"
elseif string.sub(wd, -1)~="/" then
wd=wd .. "/"
end
return wd
end
function QueryLib.complete_function(str)
res={}
for k, v in pairs(_G) do
if type(v)=="function" then
table.insert(res, k)
end
end
return res
end
--
-- The queries
--
QueryLib.query_gotoclient=QueryLib.make_frame_fn("Go to window:", nil,
QueryLib.gotoclient_handler,
complete_clientwin)
QueryLib.query_attachclient=QueryLib.make_frame_fn("Attach window:", nil,
query_handler_attachclient,
complete_clientwin)
QueryLib.query_workspace=QueryLib.make_frame_fn("Go to or create workspace:",
nil, query_handler_workspace,
complete_workspace)
QueryLib.query_exec=QueryLib.make_frame_fn("Run:", nil,
QueryLib.exec_handler,
complete_file_with_path)
QueryLib.query_exit=QueryLib.make_yesno_fn("Exit Ion (y/n)?",
exit_wm)
QueryLib.query_restart=QueryLib.make_yesno_fn("Restart Ion (y/n)?",
restart_wm)
QueryLib.query_renameframe=QueryLib.make_rename_fn("Frame name: ",
function(frame)
return frame
end
)
QueryLib.query_renameworkspace=QueryLib.make_rename_fn("Workspace name: ",
QueryLib.getws)
QueryLib.query_ssh=QueryLib.make_execwith_fn("SSH to:", nil, "ion-ssh",
QueryLib.complete_ssh)
QueryLib.query_man=QueryLib.make_execwith_fn("Manual page (ion):", nil,
"ion-man", nil)
QueryLib.query_editfile=QueryLib.make_execwith_fn("Edit file:",
QueryLib.get_initdir,
"ion-edit",
complete_file)
QueryLib.query_runfile=QueryLib.make_execwith_fn("View file:",
QueryLib.get_initdir,
"ion-view",
complete_file)
QueryLib.query_lua=QueryLib.make_frame_fn("Lua code to run:",
nil,
QueryLib.handler_lua,
QueryLib.complete_function);
|
--
-- Some common queries for Ion
--
if QueryLib~=nil then
return
end
QueryLib={}
--
-- Helper functions
--
function QueryLib.make_simple_fn(prompt, initfn, handler, completor)
local function query_it(frame)
local initvalue;
if initfn then
initvalue=initfn()
end
query_query(frame, prompt, initvalue or "", handler, completor)
end
return query_it
end
function QueryLib.make_frame_fn(prompt, initfn, handler, completor)
local function query_it(frame)
local initvalue;
if initfn then
initvalue=initfn(frame)
end
local function handle_it(str)
handler(frame, str)
end
query_query(frame, prompt, initvalue or "", handle_it, completor)
end
return query_it
end
function QueryLib.make_rename_fn(prompt, getobj)
local function query_it(frame)
local obj=getobj(frame)
local function handle_it(str)
region_set_name(obj, str)
end
query_query(frame, prompt, region_name(obj) or "", handle_it, nil)
end
return query_it
end
function QueryLib.exec_handler(frame, cmd)
if string.sub(cmd, 1, 1)==":" then
cmd="ion-runinxterm " .. string.sub(cmd, 2)
end
exec_on_screen(region_screen_of(frame), cmd)
end
function QueryLib.make_yesno_handler(fn)
local function handle_yesno(_, yesno)
if yesno=="y" or yesno=="Y" or yesno=="yes" then
if arg then
fn(unpack(arg))
else
fn()
end
end
end
return handle_yesno
end
function QueryLib.make_yesno_fn(prompt, handler)
return QueryLib.make_frame_fn(prompt, nil,
QueryLib.make_yesno_handler(handler),
nil)
end
function QueryLib.getws(obj)
while obj~=nil do
if obj_is(obj, "WGenWS") then
return obj
end
obj=region_manager(obj)
end
end
function QueryLib.complete_ssh(str)
if string.len(str)==0 then
return query_ssh_hosts
end
local res={}
for _, v in ipairs(query_ssh_hosts) do
local s, e=string.find(v, str, 1, true)
if s==1 and e>=1 then
table.insert(res, v)
end
end
return res
end
function QueryLib.make_execwith_fn(prompt, init, prog, completor)
local function handle_execwith(frame, str)
exec_on_screen(region_screen_of(frame), prog .. " " .. str)
end
return QueryLib.make_frame_fn(prompt, init, handle_execwith, completor)
end
function QueryLib.gotoclient_handler(frame, str)
local cwin=lookup_clientwin(str)
if cwin==nil then
query_fwarn(frame, string.format("Could not find client window named"
.. ' "%s"', str))
else
region_goto(cwin)
end
end
function QueryLib.handler_lua(frame, code)
local f=loadstring(code)
if f then
local oldarg=arg
arg={frame, genframe_current(frame)}
pcall(f)
oldarg=arg
end
end
function QueryLib.get_initdir()
local wd=os.getenv("PWD")
if wd==nil then
wd="/"
elseif string.sub(wd, -1)~="/" then
wd=wd .. "/"
end
return wd
end
function QueryLib.complete_function(str)
local res={}
local len=string.len(str)
for k, v in pairs(_G) do
if type(v)=="function" and string.sub(k, 1, len)==str then
print(k)
table.insert(res, k)
end
end
return res
end
--
-- The queries
--
QueryLib.query_gotoclient=QueryLib.make_frame_fn("Go to window:", nil,
QueryLib.gotoclient_handler,
complete_clientwin)
QueryLib.query_attachclient=QueryLib.make_frame_fn("Attach window:", nil,
query_handler_attachclient,
complete_clientwin)
QueryLib.query_workspace=QueryLib.make_frame_fn("Go to or create workspace:",
nil, query_handler_workspace,
complete_workspace)
QueryLib.query_exec=QueryLib.make_frame_fn("Run:", nil,
QueryLib.exec_handler,
complete_file_with_path)
QueryLib.query_exit=QueryLib.make_yesno_fn("Exit Ion (y/n)?",
exit_wm)
QueryLib.query_restart=QueryLib.make_yesno_fn("Restart Ion (y/n)?",
restart_wm)
QueryLib.query_renameframe=QueryLib.make_rename_fn("Frame name: ",
function(frame)
return frame
end
)
QueryLib.query_renameworkspace=QueryLib.make_rename_fn("Workspace name: ",
QueryLib.getws)
QueryLib.query_ssh=QueryLib.make_execwith_fn("SSH to:", nil, "ion-ssh",
QueryLib.complete_ssh)
QueryLib.query_man=QueryLib.make_execwith_fn("Manual page (ion):", nil,
"ion-man", nil)
QueryLib.query_editfile=QueryLib.make_execwith_fn("Edit file:",
QueryLib.get_initdir,
"ion-edit",
complete_file)
QueryLib.query_runfile=QueryLib.make_execwith_fn("View file:",
QueryLib.get_initdir,
"ion-view",
complete_file)
QueryLib.query_lua=QueryLib.make_frame_fn("Lua code to run:",
nil,
QueryLib.handler_lua,
QueryLib.complete_function);
|
trunk: changeset 414
|
trunk: changeset 414
complete_function fixed.
darcs-hash:20030411051952-e481e-b6477ae09ecffbb499140cfcef6d6834f74bfdb1.gz
|
Lua
|
lgpl-2.1
|
knixeur/notion,dkogan/notion.xfttest,raboof/notion,anoduck/notion,knixeur/notion,p5n/notion,neg-serg/notion,p5n/notion,raboof/notion,anoduck/notion,anoduck/notion,neg-serg/notion,dkogan/notion,anoduck/notion,p5n/notion,knixeur/notion,dkogan/notion.xfttest,dkogan/notion,neg-serg/notion,neg-serg/notion,anoduck/notion,dkogan/notion,dkogan/notion.xfttest,p5n/notion,p5n/notion,knixeur/notion,raboof/notion,knixeur/notion,raboof/notion,dkogan/notion.xfttest,dkogan/notion,dkogan/notion
|
bce851d5f0bc5386e0a9d3615b4d8688909a9fae
|
scope/index.lua
|
scope/index.lua
|
--package.path = package.path .. ";/usr/local/share/lua/5.1/"
local jwt = require 'resty.jwt'
local json = require 'json'
local mp = require 'MessagePack'
local module = {}
local log = ngx.log
local ERR = ngx.ERR
local format = string.format
module._VERSION = '0.0.1'
local HEADER_R = "X-Cache-Restriction"
local HEADER_P = "X-Cache-Key-Handshake"
local function authorize(restrictions, scopes)
log(ERR, "authorize from scopes ", json.encode(scopes))
local failure = false
local grant, scope, mandatory
local grants = {}
if restrictions == nil then return false end
for i, label in pairs(restrictions) do
grant = label
if label == "*" then
table.insert(grants, grant)
goto continue
end
if scopes == nil then goto continue end
log(ERR, "check scopes against ", grant, json.encode(scopes))
mandatory = false
if label:sub(1, 1) == "&" then
mandatory = true
label = label:sub(2)
end
regstr = label:gsub('*', '.*')
if regstr:len() ~= label:len() then
regstr = "^" .. regstr .. "$"
for scope, scopeObj in pairs(scopes) do
if scopeObj == true or scopeObj ~= nil and scopeObj.read == true then
if regstr:match(scope) then
table.insert(grants, grant)
goto continue
end
end
end
else
log(ERR, "scopes are ", json.encode(scopes), label)
scope = scopes[label]
if scope == true or scope ~= nil and scope.read == true then
table.insert(grants, grant)
goto continue
end
end
if mandatory then
failure = true
break
end
::continue::
end
if failure == true or #grants == 0 then
return false
end
return grants
end
local function build_key(key, restrictions, scopes)
-- TODO make sure grants are sorted
local grants = authorize(restrictions, scopes)
if grants == false then
return key
end
key = table.concat(grants, ',') .. ' ' .. key
log(ERR, "Grants Key '", key, "'")
return key
end
local function get_restrictions(key)
local pac = module.restrictions[key]
if pac == nil then
return nil
end
return mp.unpack(pac)
end
local function update_restrictions(key, data)
module.restrictions[key] = mp.pack(data)
return data
end
local function get_scopes(host, bearer)
if bearer == nil then return nil end
local publicKey = module.publicKeys[host]
if publicKey == nil then
return nil
end
local jwt_obj = jwt:load_jwt(bearer)
local verified = jwt:verify_jwt_obj(publicKey, jwt_obj)
if jwt_obj == nil or verified == false then
log(ERR, "no valid jwt", json.encode(jwt_obj))
return nil
end
if jwt_obj.payload then return jwt_obj.payload.scopes
else return nil
end
end
function module.get(key, vars)
return build_key(key, get_restrictions(key), get_scopes(vars.host, vars.cookie_bearer))
end
function module.set(key, vars, headers)
local pub = headers[HEADER_P]
if pub ~= nil then
module.publicKeys[vars.host] = ngx.unescape_uri(pub)
end
local restrictions = headers[HEADER_R];
if restrictions == nil then return end
if type(restrictions) == "string" then
restrictions = {restrictions}
end
update_restrictions(key, restrictions)
return build_key(key, restrictions, get_scopes(vars.host, vars.cookie_bearer))
end
return module;
|
--package.path = package.path .. ";/usr/local/share/lua/5.1/"
local jwt = require 'resty.jwt'
local json = require 'json'
local mp = require 'MessagePack'
local module = {}
local log = ngx.log
local ERR = ngx.ERR
local format = string.format
module._VERSION = '0.0.1'
local HEADER_R = "X-Cache-Restriction"
local HEADER_P = "X-Cache-Key-Handshake"
local function authorize(restrictions, scopes)
log(ERR, "authorize from scopes ", json.encode(scopes))
local failure = false
local grant, scope, mandatory
local grants = {}
if restrictions == nil then return false end
for i, label in pairs(restrictions) do
grant = label
if label == "*" then
table.insert(grants, grant)
goto continue
end
if scopes == nil then goto continue end
log(ERR, "check scopes against ", grant, json.encode(scopes))
mandatory = false
if label:sub(1, 1) == "&" then
mandatory = true
label = label:sub(2)
end
regstr = label:gsub('*', '.*')
if regstr:len() ~= label:len() then
regstr = "^" .. regstr .. "$"
for scope, scopeObj in pairs(scopes) do
if scopeObj == true or scopeObj ~= nil and scopeObj.read == true then
if regstr:match(scope) then
table.insert(grants, grant)
goto continue
end
end
end
else
log(ERR, "scopes are ", json.encode(scopes), label)
scope = scopes[label]
if scope == true or scope ~= nil and scope.read == true then
table.insert(grants, grant)
goto continue
end
end
if mandatory then
failure = true
break
end
::continue::
end
if failure == true or #grants == 0 then
return false
end
return grants
end
local function build_key(key, restrictions, scopes)
-- TODO make sure grants are sorted
local grants = authorize(restrictions, scopes)
if grants == false then
return key
end
key = table.concat(grants, ',') .. ' ' .. key
log(ERR, "Grants Key '", key, "'")
return key
end
local function get_restrictions(key)
local pac = module.restrictions[key]
if pac == nil then
return nil
end
return mp.unpack(pac)
end
local function update_restrictions(key, data)
module.restrictions[key] = mp.pack(data)
return data
end
local function get_scopes(publicKey, bearer)
if bearer == nil then return nil end
local jwt_obj = jwt:load_jwt(bearer)
local verified = jwt:verify_jwt_obj(publicKey, jwt_obj)
if jwt_obj == nil or verified == false then
log(ERR, "no valid jwt", json.encode(jwt_obj))
return nil
end
if jwt_obj.payload then return jwt_obj.payload.scopes
else return nil
end
end
function module.get(key, vars)
local publicKey = module.publicKeys[vars.host]
if publicKey == nil then
ngx.req.set_header(HEADER_P, "1")
return key
end
return build_key(key, get_restrictions(key), get_scopes(publicKey, vars.cookie_bearer))
end
function module.set(key, vars, headers)
local publicKey = headers[HEADER_P]
local host = vars.host
if publicKey ~= nil then
publicKey = ngx.unescape_uri(publicKey)
module.publicKeys[host] = publicKey
else
publicKey = module.publicKeys[host]
end
if publicKey == nil then
log(ERR, "missing public key for ", host)
return key
end
local restrictions = headers[HEADER_R];
if restrictions == nil then return end
if type(restrictions) == "string" then
restrictions = {restrictions}
end
update_restrictions(key, restrictions)
return build_key(key, restrictions, get_scopes(publicKey, vars.cookie_bearer))
end
return module;
|
Fix publicKey handshake
|
Fix publicKey handshake
|
Lua
|
mit
|
kapouer/upcache,kapouer/cache-protocols
|
e00f80aa4a746b89828234d03729e9f7dc051798
|
src/plugins/finalcutpro/timeline/editnewtitle.lua
|
src/plugins/finalcutpro/timeline/editnewtitle.lua
|
-- imports
local require = require
local log = require "hs.logger" .new "editnewtitle"
local fcp = require "cp.apple.finalcutpro"
local i18n = require "cp.i18n"
local tools = require "cp.tools"
local geometry = require "hs.geometry"
local go = require "cp.rx.go"
local v = require "semver"
local playErrorSound = tools.playErrorSound
local Do = go.Do
local Throw = go.Throw
-- local mod
local mod = {}
local skimmingBugVersion = v("10.5")
-- requireSkimmingDisabled() -> boolean
-- Function
-- Return `true` if skimming should be disabled for the current version of FCP to work around bug #2799.
--
-- Parameters:
-- * None
--
-- Returns:
-- * `true` if skimming should be disabled.
local function requireSkimmingDisabled()
-- TODO: Determine which versions of FCP do not give access to the skimming playhead
return fcp:version() >= skimmingBugVersion
end
local doConnectTitle = Do(fcp:doSelectMenu({"Edit", "Connect Title", 1}))
:Label("finalcutpro.editnewtitle.doConnectTitle")
local doConnectLowerThird = Do(fcp:doSelectMenu({"Edit", "Connect Title", 2}))
:Label("finalcutpro.editnewtitle.doConnectLowerThird")
local _doEditNewTitle
local _doEditNewLowerThird
--- finalcutpro.timeline.editnewtitle.doEditNewTitle() -> cp.rx.go.Statement
--- Function
--- Creates the new default title.
---
--- Parameters:
--- * None
--- Returns:
--- * The `Statement` that will create the new title.
function mod.doEditNewTitle()
if not _doEditNewTitle then
_doEditNewTitle = mod._doEditNewTitle(doConnectTitle)
end
return _doEditNewTitle
end
--- finalcutpro.timeline.editnewtitle.doEditNewLowerThirds() -> cp.rx.go.Statement
--- Function
--- Creates the new two-thirds title.
---
--- Parameters:
--- * None
--- Returns:
--- * The `Statement` that will create the new title.
function mod.doEditNewLowerThirds()
if not _doEditNewLowerThird then
_doEditNewLowerThird = mod._doEditNewTitle(doConnectLowerThird)
end
return _doEditNewLowerThird
end
function mod._doEditNewTitle(doConnectNewTitle)
local contents = fcp.timeline.contents
-- Show the timeline...
return Do(contents:doShow())
-- Focus on it...
:Then(contents:doFocus())
-- Pause the viewer...
:Then(fcp.viewer:doPause())
:Then(function()
-- Save the current skimming state...
local skimming = fcp:isSkimmingEnabled()
-- Disable skimming if required
if requireSkimmingDisabled() then
fcp:isSkimmingEnabled(false)
end
-- Next, get the current active playhead position...
local activePosition = contents:activePlayhead():position()
if not activePosition then
return Throw(i18n("doEditNewTitle_noplayhead_error"))
end
-- Deselect any selected clips...
return Do(contents:doSelectNone())
-- Create the new title clip...
:Then(doConnectNewTitle)
-- Select the top clip above the current playhead...
:Then(function()
-- Reset skimming to original state...
if requireSkimmingDisabled() then
fcp:isSkimmingEnabled(skimming)
end
-- Get the clips above the active position
local clipsUI = contents:positionClipsUI(activePosition, true)
if not clipsUI or #clipsUI == 0 then
return Throw(i18n("doEditNewTitle_noclips_error"))
end
-- Select the top clip (should be the new title)
local topClipUI = clipsUI[1]
-- calculate the center of the top clip
local frame = geometry.rect(topClipUI.AXFrame)
local topClipCenter = frame.center
-- ninja click the top clip
tools.ninjaDoubleClick(topClipCenter)
return true
end)
end)
:Catch(function(err)
playErrorSound()
log.ef("Error editing new title: %s", err)
end)
:Label("finalcutpro.timeline.editnewtitle._doEditNewTitle")
end
-- create a new plugin
local plugin = {
id = "finalcutpro.timeline.editnewtitle",
group = "finalcutpro",
dependencies = {
["finalcutpro.commands"] = "fcpxCmds",
}
}
function plugin.init(deps)
--------------------------------------------------------------------------------
-- Only load plugin if FCPX is supported
--------------------------------------------------------------------------------
if not fcp:isSupported() then return end
--------------------------------------------------------------------------------
-- Setup plugin
--------------------------------------------------------------------------------
local fcpxCmds = deps.fcpxCmds
-- Add new command for doing the edit new title
fcpxCmds:add("cpEditNewTitle")
:whenActivated(mod.doEditNewTitle())
:subtitled(i18n("cpEditNewTitle_subtitle"))
-- Add new command for doing the edit new lower thirds
fcpxCmds:add("cpEditNewLowerThirds")
:whenActivated(mod.doEditNewLowerThirds())
:subtitled(i18n("cpEditNewLowerThirds_subtitle"))
--------------------------------------------------------------------------------
-- Title Edit
--------------------------------------------------------------------------------
return mod
end
return plugin
|
--- === plugins.finalcutpro.timeline.editnewtitle ===
---
--- Allows adding and editing titles in Final Cut Pro's timeline.
local require = require
local log = require "hs.logger" .new "editnewtitle"
local fcp = require "cp.apple.finalcutpro"
local i18n = require "cp.i18n"
local tools = require "cp.tools"
local geometry = require "hs.geometry"
local go = require "cp.rx.go"
local v = require "semver"
local playErrorSound = tools.playErrorSound
local Do = go.Do
local Throw = go.Throw
local mod = {}
local skimmingBugVersion = v("10.5")
-- requireSkimmingDisabled() -> boolean
-- Function
-- Return `true` if skimming should be disabled for the current version of FCP to work around bug #2799.
--
-- Parameters:
-- * None
--
-- Returns:
-- * `true` if skimming should be disabled.
local function requireSkimmingDisabled()
-- TODO: Determine which versions of FCP do not give access to the skimming playhead
return fcp:version() >= skimmingBugVersion
end
local doConnectTitle = Do(fcp:doSelectMenu({"Edit", "Connect Title", 1}))
:Label("finalcutpro.editnewtitle.doConnectTitle")
local doConnectLowerThird = Do(fcp:doSelectMenu({"Edit", "Connect Title", 2}))
:Label("finalcutpro.editnewtitle.doConnectLowerThird")
local _doEditNewTitle
local _doEditNewLowerThird
--- plugins.finalcutpro.timeline.editnewtitle.doEditNewTitle() -> cp.rx.go.Statement
--- Function
--- Creates the new default title.
---
--- Parameters:
--- * None
--- Returns:
--- * The `Statement` that will create the new title.
function mod.doEditNewTitle()
if not _doEditNewTitle then
_doEditNewTitle = mod._doEditNewTitle(doConnectTitle)
end
return _doEditNewTitle
end
--- plugins.finalcutpro.timeline.editnewtitle.doEditNewLowerThirds() -> cp.rx.go.Statement
--- Function
--- Creates the new two-thirds title.
---
--- Parameters:
--- * None
--- Returns:
--- * The `Statement` that will create the new title.
function mod.doEditNewLowerThirds()
if not _doEditNewLowerThird then
_doEditNewLowerThird = mod._doEditNewTitle(doConnectLowerThird)
end
return _doEditNewLowerThird
end
function mod._doEditNewTitle(doConnectNewTitle)
local contents = fcp.timeline.contents
-- Show the timeline...
return Do(contents:doShow())
-- Focus on it...
:Then(contents:doFocus())
-- Pause the viewer...
:Then(fcp.viewer:doPause())
:Then(function()
-- Save the current skimming state...
local skimming = fcp:isSkimmingEnabled()
-- Disable skimming if required
if requireSkimmingDisabled() then
fcp:isSkimmingEnabled(false)
end
-- Next, get the current active playhead position...
local activePosition = contents:activePlayhead():position()
if not activePosition then
return Throw(i18n("doEditNewTitle_noplayhead_error"))
end
-- Deselect any selected clips...
return Do(contents:doSelectNone())
-- Create the new title clip...
:Then(doConnectNewTitle)
-- Select the top clip above the current playhead...
:Then(function()
-- Reset skimming to original state...
if requireSkimmingDisabled() then
fcp:isSkimmingEnabled(skimming)
end
-- Get the clips above the active position
local clipsUI = contents:positionClipsUI(activePosition, true)
if not clipsUI or #clipsUI == 0 then
return Throw(i18n("doEditNewTitle_noclips_error"))
end
-- Select the top clip (should be the new title)
local topClipUI = clipsUI[1]
-- calculate the center of the top clip
local frame = geometry.rect(topClipUI.AXFrame)
local topClipCenter = frame.center
-- ninja click the top clip
tools.ninjaDoubleClick(topClipCenter)
return true
end)
end)
:Catch(function(err)
playErrorSound()
log.ef("Error editing new title: %s", err)
end)
:Label("finalcutpro.timeline.editnewtitle._doEditNewTitle")
end
-- create a new plugin
local plugin = {
id = "finalcutpro.timeline.editnewtitle",
group = "finalcutpro",
dependencies = {
["finalcutpro.commands"] = "fcpxCmds",
}
}
function plugin.init(deps)
--------------------------------------------------------------------------------
-- Only load plugin if FCPX is supported
--------------------------------------------------------------------------------
if not fcp:isSupported() then return end
--------------------------------------------------------------------------------
-- Setup plugin
--------------------------------------------------------------------------------
local fcpxCmds = deps.fcpxCmds
-- Add new command for doing the edit new title
fcpxCmds:add("cpEditNewTitle")
:whenActivated(mod.doEditNewTitle())
:subtitled(i18n("cpEditNewTitle_subtitle"))
-- Add new command for doing the edit new lower thirds
fcpxCmds:add("cpEditNewLowerThirds")
:whenActivated(mod.doEditNewLowerThirds())
:subtitled(i18n("cpEditNewLowerThirds_subtitle"))
--------------------------------------------------------------------------------
-- Title Edit
--------------------------------------------------------------------------------
return mod
end
return plugin
|
Fixed the documentation markup
|
Fixed the documentation markup
|
Lua
|
mit
|
CommandPost/CommandPost,CommandPost/CommandPost,CommandPost/CommandPost
|
8cdf6ede2361fae948723fbada7563d44d39901d
|
packages/twoside/init.lua
|
packages/twoside/init.lua
|
local base = require("packages.base")
local package = pl.class(base)
package._name = "twoside"
local _odd = true
local mirrorMaster = function (_, existing, new)
-- Frames in one master can't "see" frames in another, so we have to get creative
-- XXX This knows altogether too much about the implementation of masters
if not SILE.scratch.masters[new] then SILE.scratch.masters[new] = {frames={}} end
if not SILE.scratch.masters[existing] then
SU.error("Can't find master "..existing)
end
for name, frame in pairs(SILE.scratch.masters[existing].frames) do
local newframe = pl.tablex.deepcopy(frame)
if frame:isAbsoluteConstraint("right") then
newframe.constraints.left = "100%pw-("..frame.constraints.right..")"
end
if frame:isAbsoluteConstraint("left") then
newframe.constraints.right = "100%pw-("..frame.constraints.left..")"
end
SILE.scratch.masters[new].frames[name] = newframe
if frame == SILE.scratch.masters[existing].firstContentFrame then
SILE.scratch.masters[new].firstContentFrame = newframe
end
end
end
function package.oddPage (_)
return _odd
end
local function switchPage (class)
_odd = not class:oddPage()
local nextmaster = _odd and class.oddPageMaster or class.evenPageMaster
class:switchMaster(nextmaster)
end
local _deprecate = [[
Directly calling master switch handling functions is no longer necessary. All
the SILE core classes and anything inheriting from them will take care of this
automatically using hooks. Custom classes that override the class:newPage()
function may need to handle this in other ways. By calling this hook directly
you are likely causing it to run twice and duplicate entries.
]]
local spread_counter = 0
local spreadHook = function ()
spread_counter = spread_counter + 1
end
function package:_init (options)
base._init(self)
if not SILE.scratch.masters then
SU.error("Cannot load twoside package before masters.")
end
self:export("oddPage", self.oddPage)
self:export("mirrorMaster", mirrorMaster)
self:export("switchPage", function (class)
SU.deprecated("class:switchPage", nil, "0.13.0", "0.15.0", _deprecate)
return class:switchPage()
end)
self.class.oddPageMaster = options.oddPageMaster
self.class.evenPageMaster = options.evenPageMaster
self.class:registerPostinit(function (class)
class:mirrorMaster(options.oddPageMaster, options.evenPageMaster)
end)
self.class:registerHook("newpage", spreadHook)
self.class:registerHook("newpage", switchPage)
end
function package:registerCommands ()
self:registerCommand("open-double-page", function()
SILE.call("open-spread", { double = false, odd = true, blank = false })
end)
self:registerCommand("open-spread-eject", function()
SILE.call("supereject")
end)
-- This is upstreamed from CaSILE. Similar to the original open-double-page,
-- but can disable headers and folios on blank pages and allows opening the
-- even side (with or without a leading blank).
self:registerCommand("open-spread", function (options)
local odd = SU.boolean(options.odd, true)
local double = SU.boolean(options.double, true)
local blank = SU.boolean(options.blank, true)
local optionsMet = function ()
return (not double or spread_counter > 1) and
(odd == self.class:oddPage())
end
spread_counter = 0
SILE.typesetter:leaveHmode()
-- Output a box, then remove it and see where we are. Without adding
-- content we can't prove on which page we would land because the page
-- breaker *might* be stuffed almost full but still sitting on the last
-- line happy to *maybe* accept more letter (but not a line). If this check
-- gets us to the desired page nuke the vertical space so we don't leak it
-- into the final content, otherwise just leave it be since we want to be
-- forced to the next page anyway.
SILE.call("hbox")
SILE.typesetter:leaveHmode()
table.remove(SILE.typesetter.state.nodes)
if spread_counter == 1 and optionsMet() then
SILE.typesetter.state.outputQueue = {}
return
end
local startedattop = #SILE.typesetter.state.outputQueue == 2 and #SILE.typesetter.state.nodes == 0
local spread_counter_at_start = spread_counter
repeat
if spread_counter > 0 then
SILE.call("hbox")
SILE.typesetter:leaveHmode()
-- Note: before you think you can simplify this, make sure all the
-- pages before chapter starts in the manual have headers if they have
-- content and not if empty. Combined with the workaround for just
-- barely full pages above it's tricky to get right.
if blank and not (spread_counter == spread_counter_at_start and not startedattop) then
SILE.scratch.headers.skipthispage = true
SILE.call("nofoliothispage")
end
end
SILE.call("open-spread-eject")
SILE.typesetter:leaveHmode()
until optionsMet()
end)
end
package.documentation = [[
\begin{document}
The \code{book} class described in chapter 4 sets up left and right mirrored page masters; the \autodoc:package{twoside} package is responsible for swapping between the two left and right frames, running headers and so on.
It's main function in mirroring master frames does not provide any user-serviceable parts.
It does supply a couple user facing commands for convenience.
The \autodoc:command{\open-double-page} ejects whatever page is currently being processed, then checks if it landed on an odd page.
If so it does nothing, but if not it ejects another page to assure content starts on an odd page.
The \autodoc:command{\open-spread} is similar but a bit more tailored to use in book layouts.
By default headers and folios will be suppressed automatically on any empty pages ejected, making them blank.
It can also accept three parameters.
The \autodoc:parameter{odd=false} parameter can be used to disable the opening page being odd, hence opening an even page spread.
The \autodoc:parameter{double=false} parameter can be used to always output at least one empty even page before the starting an odd page.
The \autodoc:parameter{blank=false} parameter can be used to not suppress headers and folios on otherwise empty pages.
Lastly the \autodoc:command{\open-spread-eject} command can be overridden to customize the output of blank pages.
By default it just runs \autodoc:command{\supereject}, but you could potentially add decorative content or other features in the otherwise dead space.
\end{document}
]]
return package
|
local base = require("packages.base")
local package = pl.class(base)
package._name = "twoside"
local _odd = true
local mirrorMaster = function (_, existing, new)
-- Frames in one master can't "see" frames in another, so we have to get creative
-- XXX This knows altogether too much about the implementation of masters
if not SILE.scratch.masters[new] then SILE.scratch.masters[new] = {frames={}} end
if not SILE.scratch.masters[existing] then
SU.error("Can't find master "..existing)
end
for name, frame in pairs(SILE.scratch.masters[existing].frames) do
local newframe = pl.tablex.deepcopy(frame)
if frame:isAbsoluteConstraint("right") then
newframe.constraints.left = "100%pw-("..frame.constraints.right..")"
end
if frame:isAbsoluteConstraint("left") then
newframe.constraints.right = "100%pw-("..frame.constraints.left..")"
end
SILE.scratch.masters[new].frames[name] = newframe
if frame == SILE.scratch.masters[existing].firstContentFrame then
SILE.scratch.masters[new].firstContentFrame = newframe
end
end
end
function package.oddPage (_)
return _odd
end
local function switchPage (class)
_odd = not class:oddPage()
local nextmaster = _odd and class.oddPageMaster or class.evenPageMaster
class:switchMaster(nextmaster)
end
local _deprecate = [[
Directly calling master switch handling functions is no longer necessary. All
the SILE core classes and anything inheriting from them will take care of this
automatically using hooks. Custom classes that override the class:newPage()
function may need to handle this in other ways. By calling this hook directly
you are likely causing it to run twice and duplicate entries.
]]
local spread_counter = 0
local spreadHook = function ()
spread_counter = spread_counter + 1
end
function package:_init (options)
base._init(self)
if not SILE.scratch.masters then
SU.error("Cannot load twoside package before masters.")
end
self:export("oddPage", self.oddPage)
self:export("mirrorMaster", mirrorMaster)
self:export("switchPage", function (class)
SU.deprecated("class:switchPage", nil, "0.13.0", "0.15.0", _deprecate)
return class:switchPage()
end)
self.class.oddPageMaster = options.oddPageMaster
self.class.evenPageMaster = options.evenPageMaster
self.class:registerPostinit(function (class)
-- TODO: Refactor this to make mirroring a separate package / option
if not SILE.scratch.masters[options.evenPageMaster] then
class:mirrorMaster(options.oddPageMaster, options.evenPageMaster)
end
end)
self.class:registerHook("newpage", spreadHook)
self.class:registerHook("newpage", switchPage)
end
function package:registerCommands ()
self:registerCommand("open-double-page", function()
SILE.call("open-spread", { double = false, odd = true, blank = false })
end)
self:registerCommand("open-spread-eject", function()
SILE.call("supereject")
end)
-- This is upstreamed from CaSILE. Similar to the original open-double-page,
-- but can disable headers and folios on blank pages and allows opening the
-- even side (with or without a leading blank).
self:registerCommand("open-spread", function (options)
local odd = SU.boolean(options.odd, true)
local double = SU.boolean(options.double, true)
local blank = SU.boolean(options.blank, true)
local optionsMet = function ()
return (not double or spread_counter > 1) and
(odd == self.class:oddPage())
end
spread_counter = 0
SILE.typesetter:leaveHmode()
-- Output a box, then remove it and see where we are. Without adding
-- content we can't prove on which page we would land because the page
-- breaker *might* be stuffed almost full but still sitting on the last
-- line happy to *maybe* accept more letter (but not a line). If this check
-- gets us to the desired page nuke the vertical space so we don't leak it
-- into the final content, otherwise just leave it be since we want to be
-- forced to the next page anyway.
SILE.call("hbox")
SILE.typesetter:leaveHmode()
table.remove(SILE.typesetter.state.nodes)
if spread_counter == 1 and optionsMet() then
SILE.typesetter.state.outputQueue = {}
return
end
local startedattop = #SILE.typesetter.state.outputQueue == 2 and #SILE.typesetter.state.nodes == 0
local spread_counter_at_start = spread_counter
repeat
if spread_counter > 0 then
SILE.call("hbox")
SILE.typesetter:leaveHmode()
-- Note: before you think you can simplify this, make sure all the
-- pages before chapter starts in the manual have headers if they have
-- content and not if empty. Combined with the workaround for just
-- barely full pages above it's tricky to get right.
if blank and not (spread_counter == spread_counter_at_start and not startedattop) then
SILE.scratch.headers.skipthispage = true
SILE.call("nofoliothispage")
end
end
SILE.call("open-spread-eject")
SILE.typesetter:leaveHmode()
until optionsMet()
end)
end
package.documentation = [[
\begin{document}
The \code{book} class described in chapter 4 sets up left and right mirrored page masters; the \autodoc:package{twoside} package is responsible for swapping between the two left and right frames, running headers and so on.
It's main function in mirroring master frames does not provide any user-serviceable parts.
It does supply a couple user facing commands for convenience.
The \autodoc:command{\open-double-page} ejects whatever page is currently being processed, then checks if it landed on an odd page.
If so it does nothing, but if not it ejects another page to assure content starts on an odd page.
The \autodoc:command{\open-spread} is similar but a bit more tailored to use in book layouts.
By default headers and folios will be suppressed automatically on any empty pages ejected, making them blank.
It can also accept three parameters.
The \autodoc:parameter{odd=false} parameter can be used to disable the opening page being odd, hence opening an even page spread.
The \autodoc:parameter{double=false} parameter can be used to always output at least one empty even page before the starting an odd page.
The \autodoc:parameter{blank=false} parameter can be used to not suppress headers and folios on otherwise empty pages.
Lastly the \autodoc:command{\open-spread-eject} command can be overridden to customize the output of blank pages.
By default it just runs \autodoc:command{\supereject}, but you could potentially add decorative content or other features in the otherwise dead space.
\end{document}
]]
return package
|
fix(packages): Avoid forcing mirrored masters in twoside package (#1562)
|
fix(packages): Avoid forcing mirrored masters in twoside package (#1562)
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
cdc4ff57e72d3f3c6c095aba3e64866e8c120d12
|
test/dom/Node-appendChild.lua
|
test/dom/Node-appendChild.lua
|
local gumbo = require "gumbo"
local input = [[
<header id=header></header>
<div id="main" class="foo bar baz etc">
<h1 id="h1">Title <!--comment --></h1>
</div>
<footer id=footer>...</footer>
]]
local document = assert(gumbo.parse(input))
local body = assert(document.body)
local main = assert(document:getElementById("main"))
local h1 = assert(document:getElementById("h1"))
local header = assert(document:getElementById("header"))
local footer = assert(document:getElementById("footer"))
assert(body.childElementCount == 3)
assert(body.children[1] == header)
assert(body.children[2] == main)
assert(body.children[3] == footer)
assert(body:appendChild(main) == main)
assert(body.childElementCount == 3)
assert(body.children[1] == header)
assert(body.children[2] == footer)
assert(body.children[3] == main)
assert(body:appendChild(header) == header)
assert(body.childElementCount == 3)
assert(body.children[1] == footer)
assert(body.children[2] == main)
assert(body.children[3] == header)
assert(body:appendChild(h1) == h1)
assert(body.childElementCount == 4)
assert(body.lastElementChild == h1)
local p = assert(document:createElement("p"))
assert(p.parentNode == nil)
assert(body:appendChild(p) == p)
assert(p.parentNode == body)
assert(body.childElementCount == 5)
assert(body.lastElementChild == p)
assert(header.childNodes.length == 0)
assert(main.parentNode == body)
assert(header:appendChild(main) == main)
assert(main.parentNode == header)
assert(body.childElementCount == 4)
assert(header.childNodes.length == 1)
assert(header.firstElementChild == main)
assert(body.children[2] == header)
-- TODO: Add test coverage for every assertion in ensurePreInsertionValidity()
assert(not pcall(body.appendChild, body, 9))
assert(not pcall(body.appendChild, body, "string"))
assert(not pcall(body.appendChild, body, true))
assert(not pcall(body.appendChild, body, false))
assert(not pcall(body.appendChild, body, nil))
assert(not pcall(body.appendChild, body, body))
assert(not pcall(body.appendChild, body, html))
assert(not pcall(body.appendChild, body, document))
|
local gumbo = require "gumbo"
local assert, pcall = assert, pcall
local _ENV = nil
local input = [[
<header id=header></header>
<div id="main" class="foo bar baz etc">
<h1 id="h1">Title <!--comment --></h1>
</div>
<footer id=footer>...</footer>
]]
local document = assert(gumbo.parse(input))
local body = assert(document.body)
local main = assert(document:getElementById("main"))
local h1 = assert(document:getElementById("h1"))
local header = assert(document:getElementById("header"))
local footer = assert(document:getElementById("footer"))
assert(body.childElementCount == 3)
assert(body.children[1] == header)
assert(body.children[2] == main)
assert(body.children[3] == footer)
assert(body:appendChild(main) == main)
assert(body.childElementCount == 3)
assert(body.children[1] == header)
assert(body.children[2] == footer)
assert(body.children[3] == main)
assert(body:appendChild(header) == header)
assert(body.childElementCount == 3)
assert(body.children[1] == footer)
assert(body.children[2] == main)
assert(body.children[3] == header)
assert(body:appendChild(h1) == h1)
assert(body.childElementCount == 4)
assert(body.lastElementChild == h1)
local p = assert(document:createElement("p"))
assert(p.parentNode == nil)
assert(body:appendChild(p) == p)
assert(p.parentNode == body)
assert(body.childElementCount == 5)
assert(body.lastElementChild == p)
assert(header.childNodes.length == 0)
assert(main.parentNode == body)
assert(header:appendChild(main) == main)
assert(main.parentNode == header)
assert(body.childElementCount == 4)
assert(header.childNodes.length == 1)
assert(header.firstElementChild == main)
assert(body.children[2] == header)
-- TODO: Add test coverage for every assertion in ensurePreInsertionValidity()
assert(not pcall(body.appendChild, body, 9))
assert(not pcall(body.appendChild, body, "string"))
assert(not pcall(body.appendChild, body, true))
assert(not pcall(body.appendChild, body, false))
assert(not pcall(body.appendChild, body, nil))
assert(not pcall(body.appendChild, body, body))
assert(not pcall(body.appendChild, body, document))
assert(not pcall(main.appendChild, main, body))
|
Fix test/dom/Node-appendChild.lua
|
Fix test/dom/Node-appendChild.lua
|
Lua
|
apache-2.0
|
craigbarnes/lua-gumbo,craigbarnes/lua-gumbo,craigbarnes/lua-gumbo
|
7f8702541a895d98aebc0b1908598c3c994b875b
|
src/rpc-interface.lua
|
src/rpc-interface.lua
|
local config = require("config")
local cjdnsTunnel = require("cjdnstools.tunnel")
local bit32 = require("bit32")
local socket = require("socket")
local db = require("db")
-- need better random numbers
math.randomseed(socket.gettime()*1000)
local interface = {
echo = function (msg) return msg end,
gatewayInfo = function()
local methods = {}
if config.cjdns.serverSupport == "yes" then
methods[#methods+1] = {name = "cjdns"}
end
return { name = config.server.name, ['methods'] = methods }
end,
requestConnection = function(name, method, options)
-- check maxclients config to make sure we are not registering more clients than needed
local activeClients = db.getActiveClients()
if #activeClients > config.server.maxConnections then
return { success = false, errorMsg = "Too many users", temporaryError = true }
end
-- TODO: fix IPv6
local userip = cgilua.servervariable("REMOTE_ADDR")
-- check to make sure the user isn't already registered
local activeClient = db.lookupActiveClientByIp(userip)
if activeClient ~= nil then
if activeClient.method ~= method then
return { success = false, errorMsg = "User is already registered with a different method", temporaryError = true }
else
local timestamp = os.time()
return { success = true, timeout = activeClient.timeout_timestamp - timestamp, ['ipv4'] = activeClient.internetIPv4, ['ipv6'] = activeClient.internetIPv6 }
end
end
if (method == "cjdns") and (config.cjdns.serverSupport == "yes") then
if options.key then
-- come up with random ipv4 based on settings in config
local a1, a2, a3, a4, s = config.cjdns.tunnelIpv4subnet:match("(%d+)%.(%d+)%.(%d+)%.(%d+)/(%d+)")
a1 = tonumber(a1)
a2 = tonumber(a2)
a3 = tonumber(a3)
a4 = tonumber(a4)
s = tonumber(s)
if 0>a1 or a1>255 or 0>a2 or a2>255 or 0>a3 or a3>255 or 0>a4 or a4>255 or 0>s or s>32 then
print("Invalid IPv4 subnet in cjdns tunnel configuration! New client registration failed.")
return { success = false, errorMsg = "Error in server configuration" }
end
local ipv4 = 0;
ipv4 = bit32.bor(ipv4,a1)
ipv4 = bit32.lshift(ipv4,8)
ipv4 = bit32.bor(ipv4,a2)
ipv4 = bit32.lshift(ipv4,8)
ipv4 = bit32.bor(ipv4,a3)
ipv4 = bit32.lshift(ipv4,8)
ipv4 = bit32.bor(ipv4,a4)
ipv4 = bit32.band(ipv4, bit32.lshift(bit32.bnot(0), 32-s))
ipv4 = bit32.bor(ipv4, math.random(0, 2^(32-s)-1))
a4 = bit32.band(0xFF,ipv4)
ipv4 = bit32.rshift(ipv4,8)
a3 = bit32.band(0xFF,ipv4)
ipv4 = bit32.rshift(ipv4,8)
a2 = bit32.band(0xFF,ipv4)
ipv4 = bit32.rshift(ipv4,8)
a1 = bit32.band(0xFF,ipv4)
-- TODO: implement ipv6 support, need ipv6 parser to parse config setting
ipv6 = nil
-- come up with session id
local sidchars = "1234567890abcdefghijklmnopqrstuvwxyz"
local sid = ""
for t=0,5 do
for i=1,32 do
local char = math.random(1,string.len(sidchars))
sid = sid .. string.sub(sidchars,char,char)
end
if db.lookupClientBySession(sid) ~= nil then
sid = ""
else
break
end
end
if sid == "" then
return { success = false, errorMsg = "Failed to come up with an unused session id", temporaryError = true }
end
local response, err = cjdnsTunnel.addKey(options.key, ipv4, ipv6)
if err then
return { success = false, errorMsg = "Error adding cjdns key at gateway: " .. err }
else
db.registerClient(sid, name, method, userip, nil, ipv4, ipv6)
return { success = true, timeout = config.server.clientTimeout, ['ipv4'] = ivp4, ['ipv6'] = ipv6 }
end
else
return { success = false, errorMsg = "Key option is required" }
end
end
return { success = false, errorMsg = "Method not supported" }
end,
renewConnection = function(sid)
return { success = false, errorMsg = "Not implemented yet" }
end,
releaseConnection = function(method, options)
if method == "cjdns" and (config.cjdns.serverSupport == "yes") then
if options.key then
local response, err = cjdnsTunnel.removeKey(options.key)
if err then
return { success = false, errorMsg = "Error adding cjdns key at gateway: " .. err }
else
return { success = true, timeout = config.server.clientTimeout }
end
else
return { success = false, errorMsg = "Key option is required" }
end
end
return { success = false, errorMsg = "Method not supported" }
end
}
return interface
|
local config = require("config")
local cjdnsTunnel = require("cjdnstools.tunnel")
local bit32 = require("bit32")
local socket = require("socket")
local db = require("db")
-- need better random numbers
math.randomseed(socket.gettime()*1000)
local interface = {
echo = function (msg) return msg end,
gatewayInfo = function()
local methods = {}
if config.cjdns.serverSupport == "yes" then
methods[#methods+1] = {name = "cjdns"}
end
return { name = config.server.name, ['methods'] = methods }
end,
requestConnection = function(name, method, options)
-- check maxclients config to make sure we are not registering more clients than needed
local activeClients = db.getActiveClients()
if #activeClients > config.server.maxConnections then
return { success = false, errorMsg = "Too many users", temporaryError = true }
end
-- TODO: fix IPv6
local userip = cgilua.servervariable("REMOTE_ADDR")
-- check to make sure the user isn't already registered
local activeClient = db.lookupActiveClientByIp(userip)
if activeClient ~= nil then
if activeClient.method ~= method then
return { success = false, errorMsg = "User is already registered with a different method", temporaryError = true }
else
local timestamp = os.time()
return { success = true, timeout = activeClient.timeout_timestamp - timestamp, ['ipv4'] = activeClient.internetIPv4, ['ipv6'] = activeClient.internetIPv6 }
end
end
if (method == "cjdns") and (config.cjdns.serverSupport == "yes") then
if options.key then
-- come up with random ipv4 based on settings in config
local a1, a2, a3, a4, s = config.cjdns.tunnelIpv4subnet:match("(%d+)%.(%d+)%.(%d+)%.(%d+)/(%d+)")
a1 = tonumber(a1)
a2 = tonumber(a2)
a3 = tonumber(a3)
a4 = tonumber(a4)
s = tonumber(s)
if 0>a1 or a1>255 or 0>a2 or a2>255 or 0>a3 or a3>255 or 0>a4 or a4>255 or 0>s or s>32 then
print("Invalid IPv4 subnet in cjdns tunnel configuration! New client registration failed.")
return { success = false, errorMsg = "Error in server configuration" }
end
local ipv4 = 0;
ipv4 = bit32.bor(ipv4,a1)
ipv4 = bit32.lshift(ipv4,8)
ipv4 = bit32.bor(ipv4,a2)
ipv4 = bit32.lshift(ipv4,8)
ipv4 = bit32.bor(ipv4,a3)
ipv4 = bit32.lshift(ipv4,8)
ipv4 = bit32.bor(ipv4,a4)
ipv4 = bit32.band(ipv4, bit32.lshift(bit32.bnot(0), 32-s))
ipv4 = bit32.bor(ipv4, math.random(0, 2^(32-s)-1))
a4 = bit32.band(0xFF,ipv4)
ipv4 = bit32.rshift(ipv4,8)
a3 = bit32.band(0xFF,ipv4)
ipv4 = bit32.rshift(ipv4,8)
a2 = bit32.band(0xFF,ipv4)
ipv4 = bit32.rshift(ipv4,8)
a1 = bit32.band(0xFF,ipv4)
local ipv4 = a1.."."..a2.."."..a3.."."..a4;
-- TODO: implement ipv6 support, need ipv6 parser to parse config setting
ipv6 = nil
-- come up with session id
local sidchars = "1234567890abcdefghijklmnopqrstuvwxyz"
local sid = ""
for t=0,5 do
for i=1,32 do
local char = math.random(1,string.len(sidchars))
sid = sid .. string.sub(sidchars,char,char)
end
if db.lookupClientBySession(sid) ~= nil then
sid = ""
else
break
end
end
if sid == "" then
return { success = false, errorMsg = "Failed to come up with an unused session id", temporaryError = true }
end
local response, err = cjdnsTunnel.addKey(options.key, ipv4, ipv6)
if err then
return { success = false, errorMsg = "Error adding cjdns key at gateway: " .. err }
else
db.registerClient(sid, name, method, userip, nil, ipv4, ipv6)
return { success = true, timeout = config.server.clientTimeout, ['ipv4'] = ivp4, ['ipv6'] = ipv6 }
end
else
return { success = false, errorMsg = "Key option is required" }
end
end
return { success = false, errorMsg = "Method not supported" }
end,
renewConnection = function(sid)
return { success = false, errorMsg = "Not implemented yet" }
end,
releaseConnection = function(method, options)
if method == "cjdns" and (config.cjdns.serverSupport == "yes") then
if options.key then
local response, err = cjdnsTunnel.removeKey(options.key)
if err then
return { success = false, errorMsg = "Error adding cjdns key at gateway: " .. err }
else
return { success = true, timeout = config.server.clientTimeout }
end
else
return { success = false, errorMsg = "Key option is required" }
end
end
return { success = false, errorMsg = "Method not supported" }
end
}
return interface
|
Bug fix
|
Bug fix
|
Lua
|
mit
|
transitd/transitd,transitd/transitd,intermesh-networks/transitd,transitd/transitd,pdxmeshnet/mnigs,pdxmeshnet/mnigs,intermesh-networks/transitd
|
188fe8b819e608fcea87275c36ed0c3f16457814
|
src/cli/utils/start.lua
|
src/cli/utils/start.lua
|
local IO = require "kong.tools.io"
local cutils = require "kong.cli.utils"
local constants = require "kong.constants"
local _M = {}
local function is_openresty(path_to_check)
local cmd = tostring(path_to_check).." -v 2>&1"
local handle = io.popen(cmd)
local out = handle:read()
handle:close()
local matched = out:match("^nginx version: ngx_openresty/") or out:match("^nginx version: openresty/")
if matched then
return path_to_check
end
end
local function find_nginx()
local nginx_bin = "nginx"
local nginx_search_paths = {
"/usr/local/openresty/nginx/sbin/",
"/usr/local/opt/openresty/bin/",
"/usr/local/bin/",
"/usr/sbin/",
""
}
for i = 1, #nginx_search_paths do
local prefix = nginx_search_paths[i]
local to_check = tostring(prefix)..tostring(nginx_bin)
if is_openresty(to_check) then
return to_check
end
end
end
local function prepare_nginx_working_dir(kong_config)
if kong_config.send_anonymous_reports then
kong_config.nginx = "error_log syslog:server=kong-hf.mashape.com:61828 error;\n"..kong_config.nginx
end
-- Create nginx folder if needed
local _, err = IO.path:mkdir(IO.path:join(kong_config.nginx_working_dir, "logs"))
if err then
cutils.logger:error_exit(err)
end
os.execute("touch "..IO.path:join(kong_config.nginx_working_dir, "logs", "error.log"))
os.execute("touch "..IO.path:join(kong_config.nginx_working_dir, "logs", "access.log"))
-- Extract nginx config to nginx folder
IO.write_to_file(IO.path:join(kong_config.nginx_working_dir, constants.CLI.NGINX_CONFIG), kong_config.nginx)
return kong_config.nginx_working_dir
end
function _M.start(args_config)
-- Make sure nginx is there and is openresty
local nginx_path = find_nginx()
if not nginx_path then
cutils.logger:error_exit("can't find nginx")
end
-- Get configuration from default or given path
local config_path = cutils.get_kong_config_path(args_config)
local config, dao_factory = IO.load_configuration_and_dao(config_path)
-- Migrate the DB if needed and possible
local keyspace, err = dao_factory:get_migrations()
if err then
cutils.logger:error_exit(err)
elseif keyspace == nil then
cutils.logger:log("Database not initialized. Running migrations...")
local migrations = require("kong.tools.migrations")(dao_factory)
migrations:migrate(function(migration, err)
if err then
cutils.logger:error_exit(err)
elseif migration then
cutils.logger:success("Migrated up to: "..cutils.colors.yellow(migration.name))
end
end)
end
-- Prepare nginx --prefix dir
local nginx_working_dir = prepare_nginx_working_dir(config)
-- Build nginx start command
local cmd = string.format("KONG_CONF=%s %s -p %s -c %s -g 'pid %s;'",
config_path,
nginx_path,
nginx_working_dir,
constants.CLI.NGINX_CONFIG,
constants.CLI.NGINX_PID)
if os.execute(cmd) == 0 then
cutils.logger:success("Started")
else
cutils.logger:error_exit("Could not start Kong")
end
end
return _M.start
|
local IO = require "kong.tools.io"
local cutils = require "kong.cli.utils"
local constants = require "kong.constants"
local _M = {}
local function is_openresty(path_to_check)
local cmd = tostring(path_to_check).." -v 2>&1"
local handle = io.popen(cmd)
local out = handle:read()
handle:close()
local matched = out:match("^nginx version: ngx_openresty/") or out:match("^nginx version: openresty/")
if matched then
return path_to_check
end
end
local function find_nginx()
local nginx_bin = "nginx"
local nginx_search_paths = {
"/usr/local/openresty/nginx/sbin/",
"/usr/local/opt/openresty/bin/",
"/usr/local/bin/",
"/usr/sbin/",
""
}
for i = 1, #nginx_search_paths do
local prefix = nginx_search_paths[i]
local to_check = tostring(prefix)..tostring(nginx_bin)
if is_openresty(to_check) then
return to_check
end
end
end
local function prepare_nginx_working_dir(kong_config)
if kong_config.send_anonymous_reports then
kong_config.nginx = "error_log syslog:server=kong-hf.mashape.com:61828 error;\n"..kong_config.nginx
end
-- Create nginx folder if needed
local _, err = IO.path:mkdir(IO.path:join(kong_config.nginx_working_dir, "logs"))
if err then
cutils.logger:error_exit(err)
end
os.execute("touch "..IO.path:join(kong_config.nginx_working_dir, "logs", "error.log"))
os.execute("touch "..IO.path:join(kong_config.nginx_working_dir, "logs", "access.log"))
-- Extract nginx config to nginx folder
IO.write_to_file(IO.path:join(kong_config.nginx_working_dir, constants.CLI.NGINX_CONFIG), kong_config.nginx)
return kong_config.nginx_working_dir
end
function _M.start(args_config)
-- Make sure nginx is there and is openresty
local nginx_path = find_nginx()
if not nginx_path then
cutils.logger:error_exit("can't find nginx")
end
-- Get configuration from default or given path
local config_path = cutils.get_kong_config_path(args_config)
local config, dao_factory = IO.load_configuration_and_dao(config_path)
-- Migrate the DB if needed and possible
local keyspace, err = dao_factory:get_migrations()
if err then
cutils.logger:error_exit(err)
elseif keyspace == nil then
cutils.logger:log("Database not initialized. Running migrations...")
local migrations = require("kong.tools.migrations")(dao_factory, cutils.get_luarocks_install_dir())
migrations:migrate(function(migration, err)
if err then
cutils.logger:error_exit(err)
elseif migration then
cutils.logger:success("Migrated up to: "..cutils.colors.yellow(migration.name))
end
end)
end
-- Prepare nginx --prefix dir
local nginx_working_dir = prepare_nginx_working_dir(config)
-- Build nginx start command
local cmd = string.format("KONG_CONF=%s %s -p %s -c %s -g 'pid %s;'",
config_path,
nginx_path,
nginx_working_dir,
constants.CLI.NGINX_CONFIG,
constants.CLI.NGINX_PID)
if os.execute(cmd) == 0 then
cutils.logger:success("Started")
else
cutils.logger:error_exit("Could not start Kong")
end
end
return _M.start
|
Fixing auto-migration
|
Fixing auto-migration
|
Lua
|
apache-2.0
|
wakermahmud/kong,AnsonSmith/kong,paritoshmmmec/kong,Skyscanner/kong,sbuettner/kong,skynet/kong,bbalu/kong,puug/kong,ropik/kong,vmercierfr/kong,chourobin/kong,ChristopherBiscardi/kong,peterayeni/kong
|
0d0e23c3a1a597a053bb8f200b5a54ac73423394
|
src/cli/utils/start.lua
|
src/cli/utils/start.lua
|
local IO = require "kong.tools.io"
local cutils = require "kong.cli.utils"
local constants = require "kong.constants"
local _M = {}
local function is_openresty(path_to_check)
local cmd = tostring(path_to_check).." -v 2>&1"
local handle = io.popen(cmd)
local out = handle:read()
handle:close()
local matched = out:match("^nginx version: ngx_openresty/") or out:match("^nginx version: openresty/")
if matched then
return path_to_check
end
end
local function find_nginx()
local nginx_bin = "nginx"
local nginx_search_paths = {
"/usr/local/openresty/nginx/sbin/",
"/usr/local/opt/openresty/bin/",
"/usr/local/bin/",
"/usr/sbin/",
""
}
for i = 1, #nginx_search_paths do
local prefix = nginx_search_paths[i]
local to_check = tostring(prefix)..tostring(nginx_bin)
if is_openresty(to_check) then
return to_check
end
end
end
local function prepare_nginx_working_dir(kong_config)
if kong_config.send_anonymous_reports then
kong_config.nginx = "error_log syslog:server=kong-hf.mashape.com:61828 error;\n"..kong_config.nginx
end
-- Create nginx folder if needed
local _, err = IO.path:mkdir(IO.path:join(kong_config.nginx_working_dir, "logs"))
if err then
cutils.logger:error_exit(err)
end
os.execute("touch "..IO.path:join(kong_config.nginx_working_dir, "logs", "error.log"))
os.execute("touch "..IO.path:join(kong_config.nginx_working_dir, "logs", "access.log"))
-- Extract nginx config to nginx folder
IO.write_to_file(IO.path:join(kong_config.nginx_working_dir, constants.CLI.NGINX_CONFIG), kong_config.nginx)
return kong_config.nginx_working_dir
end
function _M.start(args_config)
-- Make sure nginx is there and is openresty
local nginx_path = find_nginx()
if not nginx_path then
cutils.logger:error_exit("can't find nginx")
end
-- Get configuration from default or given path
local config_path = cutils.get_kong_config_path(args_config)
local config, dao_factory = IO.load_configuration_and_dao(config_path)
-- Migrate the DB if needed and possible
local keyspace, err = dao_factory:get_migrations()
if err then
cutils.logger:error_exit(err)
elseif keyspace == nil then
cutils.logger:log("Database not initialized. Running migrations...")
local migrations = require("kong.tools.migrations")(dao_factory)
migrations:migrate(function(migration, err)
if err then
cutils.logger:error_exit(err)
elseif migration then
cutils.logger:success("Migrated up to: "..cutils.colors.yellow(migration.name))
end
end)
end
-- Prepare nginx --prefix dir
local nginx_working_dir = prepare_nginx_working_dir(config)
-- Build nginx start command
local cmd = string.format("KONG_CONF=%s %s -p %s -c %s -g 'pid %s;'",
config_path,
nginx_path,
nginx_working_dir,
constants.CLI.NGINX_CONFIG,
constants.CLI.NGINX_PID)
if os.execute(cmd) == 0 then
cutils.logger:success("Started")
else
cutils.logger:error_exit("Could not start Kong")
end
end
return _M.start
|
local IO = require "kong.tools.io"
local cutils = require "kong.cli.utils"
local constants = require "kong.constants"
local _M = {}
local function is_openresty(path_to_check)
local cmd = tostring(path_to_check).." -v 2>&1"
local handle = io.popen(cmd)
local out = handle:read()
handle:close()
local matched = out:match("^nginx version: ngx_openresty/") or out:match("^nginx version: openresty/")
if matched then
return path_to_check
end
end
local function find_nginx()
local nginx_bin = "nginx"
local nginx_search_paths = {
"/usr/local/openresty/nginx/sbin/",
"/usr/local/opt/openresty/bin/",
"/usr/local/bin/",
"/usr/sbin/",
""
}
for i = 1, #nginx_search_paths do
local prefix = nginx_search_paths[i]
local to_check = tostring(prefix)..tostring(nginx_bin)
if is_openresty(to_check) then
return to_check
end
end
end
local function prepare_nginx_working_dir(kong_config)
if kong_config.send_anonymous_reports then
kong_config.nginx = "error_log syslog:server=kong-hf.mashape.com:61828 error;\n"..kong_config.nginx
end
-- Create nginx folder if needed
local _, err = IO.path:mkdir(IO.path:join(kong_config.nginx_working_dir, "logs"))
if err then
cutils.logger:error_exit(err)
end
os.execute("touch "..IO.path:join(kong_config.nginx_working_dir, "logs", "error.log"))
os.execute("touch "..IO.path:join(kong_config.nginx_working_dir, "logs", "access.log"))
-- Extract nginx config to nginx folder
IO.write_to_file(IO.path:join(kong_config.nginx_working_dir, constants.CLI.NGINX_CONFIG), kong_config.nginx)
return kong_config.nginx_working_dir
end
function _M.start(args_config)
-- Make sure nginx is there and is openresty
local nginx_path = find_nginx()
if not nginx_path then
cutils.logger:error_exit("can't find nginx")
end
-- Get configuration from default or given path
local config_path = cutils.get_kong_config_path(args_config)
local config, dao_factory = IO.load_configuration_and_dao(config_path)
-- Migrate the DB if needed and possible
local keyspace, err = dao_factory:get_migrations()
if err then
cutils.logger:error_exit(err)
elseif keyspace == nil then
cutils.logger:log("Database not initialized. Running migrations...")
local migrations = require("kong.tools.migrations")(dao_factory, cutils.get_luarocks_install_dir())
migrations:migrate(function(migration, err)
if err then
cutils.logger:error_exit(err)
elseif migration then
cutils.logger:success("Migrated up to: "..cutils.colors.yellow(migration.name))
end
end)
end
-- Prepare nginx --prefix dir
local nginx_working_dir = prepare_nginx_working_dir(config)
-- Build nginx start command
local cmd = string.format("KONG_CONF=%s %s -p %s -c %s -g 'pid %s;'",
config_path,
nginx_path,
nginx_working_dir,
constants.CLI.NGINX_CONFIG,
constants.CLI.NGINX_PID)
if os.execute(cmd) == 0 then
cutils.logger:success("Started")
else
cutils.logger:error_exit("Could not start Kong")
end
end
return _M.start
|
Fixing auto-migration
|
Fixing auto-migration
|
Lua
|
apache-2.0
|
ind9/kong,ind9/kong,Kong/kong,smanolache/kong,jebenexer/kong,ejoncas/kong,Kong/kong,shiprabehera/kong,ajayk/kong,Mashape/kong,streamdataio/kong,akh00/kong,ejoncas/kong,xvaara/kong,li-wl/kong,isdom/kong,kyroskoh/kong,vzaramel/kong,ccyphers/kong,isdom/kong,streamdataio/kong,beauli/kong,Vermeille/kong,salazar/kong,jerizm/kong,kyroskoh/kong,Kong/kong,icyxp/kong,vzaramel/kong,rafael/kong,rafael/kong
|
3e2fecb8e707389feb7069d82b031873eac424d8
|
src/lib/ptree/trace.lua
|
src/lib/ptree/trace.lua
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(...,package.seeall)
local lib = require('core.lib')
local json = require("lib.ptree.json")
local Trace = {}
local trace_config_spec = {
file = {required=true},
file_mode = {default="w"},
}
function new (conf)
local conf = lib.parse(conf, trace_config_spec)
local ret = setmetatable({}, {__index=Trace})
ret.id = 0
ret.output = io.open(conf.file, conf.file_mode)
return ret
end
local function listen_directive_for_rpc(rpc_id, args)
local ret = { path=args.path, schema=args.schema, revision=args.revision }
if rpc_id == 'get-config' then
ret.verb = 'get'
return ret
elseif rpc_id == 'set-config' then
ret.verb, ret.value = 'set', args.config
return ret
elseif rpc_id == 'add-config' then
ret.verb, ret.value = 'add', args.config
return ret
elseif rpc_id == 'remove-config' then
ret.verb = 'remove'
return ret
elseif rpc_id == 'get-state' then
ret.verb = 'get-state'
return ret
else
return nil
end
end
function Trace:record(id, args)
assert(self.output, "trace closed")
local obj = listen_directive_for_rpc(id, args)
if not obj then return end
obj.id = tostring(self.id)
self.id = self.id + 1
json.write_json_object(self.output, obj)
self.output:write('\n')
self.output:flush()
end
function Trace:close()
self.output:close()
self.output = nil
end
function selftest ()
print('selftest: lib.ptree.trace')
local S = require('syscall')
local tmp = os.tmpname()
local trace = new({file=tmp})
trace:record("foo", {bar="baz"})
trace:record("qux", {bar="baz", zog="100"})
trace:close()
local fd = S.open(tmp, 'rdonly')
local input = json.buffered_input(fd)
json.skip_whitespace(input)
local parsed = json.read_json_object(input)
assert(lib.equal(parsed, {id="0", verb="foo", bar="baz"}))
json.skip_whitespace(input)
parsed = json.read_json_object(input)
assert(lib.equal(parsed, {id="1", verb="qux", bar="baz", zog="100"}))
json.skip_whitespace(input)
assert(input:eof())
fd:close()
os.remove(tmp)
print('selftest: ok')
end
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(...,package.seeall)
local lib = require('core.lib')
local json = require("lib.ptree.json")
local Trace = {}
local trace_config_spec = {
file = {required=true},
file_mode = {default="w"},
}
function new (conf)
local conf = lib.parse(conf, trace_config_spec)
local ret = setmetatable({}, {__index=Trace})
ret.id = 0
ret.output = io.open(conf.file, conf.file_mode)
return ret
end
local function listen_directive_for_rpc(rpc_id, args)
local ret = { path=args.path, schema=args.schema, revision=args.revision }
if rpc_id == 'get-config' then
ret.verb = 'get'
return ret
elseif rpc_id == 'set-config' then
ret.verb, ret.value = 'set', args.config
return ret
elseif rpc_id == 'add-config' then
ret.verb, ret.value = 'add', args.config
return ret
elseif rpc_id == 'remove-config' then
ret.verb = 'remove'
return ret
elseif rpc_id == 'get-state' then
ret.verb = 'get-state'
return ret
else
return nil
end
end
function Trace:record(id, args)
assert(self.output, "trace closed")
local obj = listen_directive_for_rpc(id, args)
if not obj then return end
obj.id = tostring(self.id)
self.id = self.id + 1
json.write_json_object(self.output, obj)
self.output:write('\n')
self.output:flush()
end
function Trace:close()
self.output:close()
self.output = nil
end
function selftest ()
print('selftest: lib.ptree.trace')
local S = require('syscall')
local tmp = os.tmpname()
local trace = new({file=tmp})
trace:record("get-config",
{path="/", schema="foo", revision="bar"})
trace:record("set-config",
{path="/", schema="foo", revision="bar", config="baz"})
trace:record("unsupported-rpc",
{path="/", schema="foo", revision="bar", config="baz"})
trace:close()
local fd = S.open(tmp, 'rdonly')
local input = json.buffered_input(fd)
json.skip_whitespace(input)
local parsed = json.read_json_object(input)
assert(lib.equal(parsed, {id="0", verb="get", path="/",
schema="foo", revision="bar"}))
json.skip_whitespace(input)
parsed = json.read_json_object(input)
assert(lib.equal(parsed, {id="1", verb="set", path="/",
schema="foo", revision="bar", value="baz"}))
json.skip_whitespace(input)
assert(input:eof())
fd:close()
os.remove(tmp)
print('selftest: ok')
end
|
Fix ptree trace selftest
|
Fix ptree trace selftest
|
Lua
|
apache-2.0
|
alexandergall/snabbswitch,Igalia/snabbswitch,dpino/snabb,Igalia/snabb,dpino/snabb,Igalia/snabbswitch,eugeneia/snabb,Igalia/snabb,eugeneia/snabbswitch,SnabbCo/snabbswitch,alexandergall/snabbswitch,SnabbCo/snabbswitch,eugeneia/snabb,snabbco/snabb,eugeneia/snabbswitch,snabbco/snabb,dpino/snabbswitch,snabbco/snabb,Igalia/snabb,eugeneia/snabbswitch,dpino/snabbswitch,dpino/snabb,eugeneia/snabb,snabbco/snabb,alexandergall/snabbswitch,SnabbCo/snabbswitch,eugeneia/snabbswitch,Igalia/snabbswitch,Igalia/snabb,dpino/snabb,snabbco/snabb,alexandergall/snabbswitch,Igalia/snabb,Igalia/snabb,Igalia/snabb,alexandergall/snabbswitch,dpino/snabb,dpino/snabb,eugeneia/snabb,eugeneia/snabb,alexandergall/snabbswitch,Igalia/snabbswitch,SnabbCo/snabbswitch,dpino/snabbswitch,Igalia/snabbswitch,dpino/snabbswitch,alexandergall/snabbswitch,eugeneia/snabb,eugeneia/snabb,alexandergall/snabbswitch,eugeneia/snabb,snabbco/snabb,Igalia/snabb,dpino/snabb,snabbco/snabb,snabbco/snabb
|
1f5aefe482c84462118a7de6f4ffa9cb13540d0b
|
spec/02-integration/10-go_plugins/01-reports_spec.lua
|
spec/02-integration/10-go_plugins/01-reports_spec.lua
|
local helpers = require "spec.helpers"
local constants = require "kong.constants"
local cjson = require "cjson"
local pl_file = require "pl.file"
for _, strategy in helpers.each_strategy() do
local admin_client
local dns_hostsfile
local reports_server
describe("anonymous reports for go plugins #" .. strategy, function()
local reports_send_ping = function(port)
ngx.sleep(0.01) -- hand over the CPU so other threads can do work (processing the sent data)
local admin_client = helpers.admin_client()
local res = admin_client:post("/reports/send-ping" .. (port and "?port=" .. port or ""))
assert.response(res).has_status(200)
admin_client:close()
end
lazy_setup(function()
dns_hostsfile = assert(os.tmpname() .. ".hosts")
local fd = assert(io.open(dns_hostsfile, "w"))
assert(fd:write("127.0.0.1 " .. constants.REPORTS.ADDRESS))
assert(fd:close())
local bp = assert(helpers.get_db_utils(strategy, {
"services",
"routes",
"plugins",
}, { "reports-api" }))
local http_srv = assert(bp.services:insert {
name = "mock-service",
host = helpers.mock_upstream_host,
port = helpers.mock_upstream_port,
})
bp.routes:insert({ service = http_srv,
protocols = { "http" },
hosts = { "http-service.test" }})
bp.plugins:insert({
name = "reports-api",
config = {}
})
local kong_prefix = helpers.test_conf.prefix
assert(helpers.start_kong({
nginx_conf = "spec/fixtures/custom_nginx.template",
database = strategy,
dns_hostsfile = dns_hostsfile,
plugins = "bundled,reports-api,go-hello",
pluginserver_names = "test",
pluginserver_test_socket = kong_prefix .. "/go-hello.socket",
pluginserver_test_query_cmd = "./spec/fixtures/go/go-hello -dump -kong-prefix " .. kong_prefix,
pluginserver_test_start_cmd = "./spec/fixtures/go/go-hello -kong-prefix " .. kong_prefix,
anonymous_reports = true,
}))
admin_client = helpers.admin_client()
local res = admin_client:post("/plugins", {
headers = {
["Content-Type"] = "application/json"
},
body = {
name = "go-hello",
config = {
message = "Kong!"
}
}
})
assert.res_status(201, res)
end)
lazy_teardown(function()
os.remove(dns_hostsfile)
helpers.stop_kong()
end)
before_each(function()
constants.REPORTS.STATS_TLS_PORT = constants.REPORTS.STATS_TLS_PORT + math.random(1, 50)
reports_server = helpers.tcp_server(constants.REPORTS.STATS_TLS_PORT, {tls=true})
end)
it("logs number of enabled go plugins", function()
reports_send_ping(constants.REPORTS.STATS_TLS_PORT)
local _, reports_data = assert(reports_server:join())
reports_data = cjson.encode(reports_data)
assert.match("go_plugins_cnt=1", reports_data)
end)
it("logs number of requests triggering a go plugin", function()
local proxy_client = assert(helpers.proxy_client())
local res = proxy_client:get("/", {
headers = { host = "http-service.test" }
})
assert.res_status(200, res)
reports_send_ping(constants.REPORTS.STATS_TLS_PORT)
local _, reports_data = assert(reports_server:join())
reports_data = cjson.encode(reports_data)
assert.match("go_plugin_reqs=1", reports_data)
assert.match("go_plugin_reqs=1", reports_data)
proxy_client:close()
end)
it("runs fake 'response' phase", function()
local proxy_client = assert(helpers.proxy_client())
local res = proxy_client:get("/", {
headers = { host = "http-service.test" }
})
assert.res_status(200, res)
assert.equal("got from server 'mock-upstream/1.0.0'", res.headers['x-hello-from-go-at-response'])
proxy_client:close()
end)
describe("log phase has access to stuff", function()
it("puts that stuff in the log", function()
local proxy_client = assert(helpers.proxy_client())
local res = proxy_client:get("/", {
headers = {
host = "http-service.test",
["X-Loose-Data"] = "this",
}
})
assert.res_status(200, res)
proxy_client:close()
local cfg = helpers.test_conf
ngx.sleep(0.1)
local logs = pl_file.read(cfg.prefix .. "/" .. cfg.proxy_error_log)
for _, logpat in ipairs{
"access_start: %d%d+\n",
"shared_msg: Kong!\n",
"request_header: this\n",
"response_header: mock_upstream\n",
"serialized:%b{}\n",
} do
assert.match(logpat, logs)
end
end)
end)
end)
end
|
local helpers = require "spec.helpers"
local constants = require "kong.constants"
local cjson = require "cjson"
local pl_file = require "pl.file"
for _, strategy in helpers.each_strategy() do
local admin_client
local dns_hostsfile
local reports_server
describe("anonymous reports for go plugins #" .. strategy, function()
local reports_send_ping = function(port)
ngx.sleep(0.01) -- hand over the CPU so other threads can do work (processing the sent data)
local admin_client = helpers.admin_client()
local res = admin_client:post("/reports/send-ping" .. (port and "?port=" .. port or ""))
assert.response(res).has_status(200)
admin_client:close()
end
lazy_setup(function()
dns_hostsfile = assert(os.tmpname() .. ".hosts")
local fd = assert(io.open(dns_hostsfile, "w"))
assert(fd:write("127.0.0.1 " .. constants.REPORTS.ADDRESS))
assert(fd:close())
local bp = assert(helpers.get_db_utils(strategy, {
"services",
"routes",
"plugins",
}, { "reports-api" }))
local http_srv = assert(bp.services:insert {
name = "mock-service",
host = helpers.mock_upstream_host,
port = helpers.mock_upstream_port,
})
bp.routes:insert({ service = http_srv,
protocols = { "http" },
hosts = { "http-service.test" }})
bp.plugins:insert({
name = "reports-api",
config = {}
})
local kong_prefix = helpers.test_conf.prefix
assert(helpers.start_kong({
nginx_conf = "spec/fixtures/custom_nginx.template",
database = strategy,
dns_hostsfile = dns_hostsfile,
plugins = "bundled,reports-api,go-hello",
pluginserver_names = "test",
pluginserver_test_socket = kong_prefix .. "/go-hello.socket",
pluginserver_test_query_cmd = "./spec/fixtures/go/go-hello -dump -kong-prefix " .. kong_prefix,
pluginserver_test_start_cmd = "./spec/fixtures/go/go-hello -kong-prefix " .. kong_prefix,
anonymous_reports = true,
}))
admin_client = helpers.admin_client()
local res = admin_client:post("/plugins", {
headers = {
["Content-Type"] = "application/json"
},
body = {
name = "go-hello",
config = {
message = "Kong!"
}
}
})
assert.res_status(201, res)
end)
lazy_teardown(function()
os.remove(dns_hostsfile)
helpers.stop_kong()
end)
before_each(function()
reports_server = helpers.tcp_server(constants.REPORTS.STATS_TLS_PORT, {tls=true})
end)
it("logs number of enabled go plugins", function()
reports_send_ping(constants.REPORTS.STATS_TLS_PORT)
local _, reports_data = assert(reports_server:join())
reports_data = cjson.encode(reports_data)
assert.match("go_plugins_cnt=1", reports_data)
end)
it("logs number of requests triggering a go plugin", function()
local proxy_client = assert(helpers.proxy_client())
local res = proxy_client:get("/", {
headers = { host = "http-service.test" }
})
assert.res_status(200, res)
reports_send_ping(constants.REPORTS.STATS_TLS_PORT)
local _, reports_data = assert(reports_server:join())
reports_data = cjson.encode(reports_data)
assert.match("go_plugin_reqs=1", reports_data)
assert.match("go_plugin_reqs=1", reports_data)
proxy_client:close()
end)
it("runs fake 'response' phase", function()
local proxy_client = assert(helpers.proxy_client())
local res = proxy_client:get("/", {
headers = { host = "http-service.test" }
})
-- send a ping so the tcp server shutdown cleanly and not with a timeout.
reports_send_ping(constants.REPORTS.STATS_TLS_PORT)
assert.res_status(200, res)
assert.equal("got from server 'mock-upstream/1.0.0'", res.headers['x-hello-from-go-at-response'])
proxy_client:close()
end)
describe("log phase has access to stuff", function()
it("puts that stuff in the log", function()
local proxy_client = assert(helpers.proxy_client())
local res = proxy_client:get("/", {
headers = {
host = "http-service.test",
["X-Loose-Data"] = "this",
}
})
-- send a ping so the tcp server shutdown cleanly and not with a timeout.
reports_send_ping(constants.REPORTS.STATS_TLS_PORT)
assert.res_status(200, res)
proxy_client:close()
local cfg = helpers.test_conf
ngx.sleep(0.1)
local logs = pl_file.read(cfg.prefix .. "/" .. cfg.proxy_error_log)
for _, logpat in ipairs{
"access_start: %d%d+\n",
"shared_msg: Kong!\n",
"request_header: this\n",
"response_header: mock_upstream\n",
"serialized:%b{}\n",
} do
assert.match(logpat, logs)
end
end)
end)
end)
end
|
tests(reports) go_plugins: fix tcp server timeouts
|
tests(reports) go_plugins: fix tcp server timeouts
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
7d2375e0a4570dca8cb83a3e619f1691507b09d2
|
plugins/youtube.lua
|
plugins/youtube.lua
|
local youtube = {}
local mattata = require('mattata')
local HTTPS = require('ssl.https')
local URL = require('socket.url')
local JSON = require('dkjson')
function youtube:init(configuration)
youtube.arguments = 'youtube <query>'
youtube.commands = mattata.commands(self.info.username, configuration.commandPrefix):c('youtube'):c('yt').table
youtube.help = configuration.commandPrefix .. 'youtube <query> - Sends the first result from YouTube for the given search query. Alias: ' .. configuration.commandPrefix .. 'yt.'
end
function youtube:onMessageReceive(msg, configuration)
local input = mattata.input(msg.text)
if not input then
mattata.sendMessage(msg.chat.id, youtube.help, nil, true, false, msg.message_id, nil)
return
end
local url = 'https://www.googleapis.com/youtube/v3/search?key=' .. configuration.keys.google .. '&type=video&part=snippet&maxResults=1&q=' .. URL.escape(input)
local jstr, res = HTTPS.request(url)
if res ~= 200 then
mattata.sendMessage(msg.chat.id, configuration.errors.connection, nil, true, false, msg.message_id, nil)
return
end
local jdat = JSON.decode(jstr)
if jdat.pageInfo.totalResults == 0 then
mattata.sendMessage(msg.chat.id, configuration.errors.results, nil, true, false, msg.message_id, nil)
return
end
local video = 'https://www.youtube.com/watch?v=' .. jdat.items[1].id.videoId
mattata.sendMessage(msg.chat.id, video, nil, false, false, msg.message_id, nil)
end
return youtube
|
local youtube = {}
local mattata = require('mattata')
local HTTPS = require('ssl.https')
local URL = require('socket.url')
local JSON = require('dkjson')
function youtube:init(configuration)
youtube.arguments = 'youtube <query>'
youtube.commands = mattata.commands(self.info.username, configuration.commandPrefix):c('youtube'):c('yt').table
youtube.help = configuration.commandPrefix .. 'youtube <query> - Sends the first result from YouTube for the given search query. Alias: ' .. configuration.commandPrefix .. 'yt.'
end
function youtube:onMessageReceive(msg, configuration)
local input = mattata.input(msg.text)
if not input then
mattata.sendMessage(msg.chat.id, youtube.help, nil, true, false, msg.message_id, nil)
return
end
local jstr, res = HTTPS.request('https://www.googleapis.com/youtube/v3/search?key=' .. configuration.keys.google .. '&type=video&part=snippet&maxResults=1&q=' .. URL.escape(input))
if res ~= 200 then
mattata.sendMessage(msg.chat.id, configuration.errors.connection, nil, true, false, msg.message_id, nil)
return
end
local jdat = JSON.decode(jstr)
if jdat.pageInfo.totalResults == 0 then
mattata.sendMessage(msg.chat.id, configuration.errors.results, nil, true, false, msg.message_id, nil)
return
end
local output = 'https://www.youtube.com/watch?v=' .. jdat.items[1].id.videoId
mattata.sendMessage(msg.chat.id, output, nil, false, false, msg.message_id, nil)
end
return youtube
|
mattata v3.2
|
mattata v3.2
Began changes; here I fixed some issues with the indentation in youtube.lua and slightly minified the code
|
Lua
|
mit
|
barreeeiroo/BarrePolice
|
242ea88bbeefa1dfa50d00bf07760594b1b72d37
|
cherry/libs/animation.lua
|
cherry/libs/animation.lua
|
--------------------------------------------------------------------------------
local _ = require 'cherry.libs.underscore'
local isArray = require 'cherry.libs.is-array'
--------------------------------------------------------------------------------
local animation = {}
--------------------------------------------------------
function animation.rotateBackAndForth(object, angle, time)
local initialRotation = object.rotation
local back = function()
transition.to(object, {
rotation = initialRotation,
onComplete = function() animation.rotateBackAndForth(object, -angle, time) end,
time = time
})
end
transition.to(object, {
rotation = angle,
onComplete = back,
time = time
})
end
--------------------------------------------------------
function animation.scaleBackAndForth(object, options)
options = options or {}
local initialScale = object.xScale
local scaleGrow = options.scale or 1.5
local back = function()
animation.bounce(object, _.extend({
time = options.time or 500,
scaleFrom = scaleGrow,
scaleTo = initialScale,
transition = easing.outBounce,
noDelay = true,
onComplete = function ()
if(options.loop) then
animation.scaleBackAndForth(object, options)
end
end
}, options))
end
animation.bounce(object, _.extend({
time = options.time or 500,
scaleFrom = initialScale,
scaleTo = scaleGrow,
transition = easing.outSine,
onComplete = back,
noDelay = true
}, options))
end
--------------------------------------------------------
function animation.easeDisplay(object, scale)
local scaleTo = scale or object.xScale or 1
object.xScale = 0.2
object.yScale = 0.2
return transition.to( object, {
xScale = scaleTo,
yScale = scaleTo,
time = 350,
transition = easing.outCubic
})
end
function animation.bounce(objects, options)
if(not isArray(objects)) then objects = {objects} end
options = options or {}
local scaleTo = options.scaleTo or 1
local scaleFrom = options.scaleFrom or 0.1
local _bounce = function(o)
o.xScale = scaleFrom
o.yScale = scaleFrom
transition.to( o, {
xScale = scaleTo,
yScale = scaleTo,
delay = options.delay or 0,
time = options.time or 750,
transition = options.transition or easing.outBounce,
onComplete = options.onComplete
})
end
local _bounceAll = function()
for _, o in ipairs(objects) do
_bounce(o)
end
end
_bounceAll()
end
function animation.grow(object, fromScale, time, onComplete)
object.xScale = fromScale or 0.6
object.yScale = fromScale or 0.6
transition.to( object, {
xScale = 1,
yScale = 1,
time = time or 150,
onComplete = onComplete
})
end
function animation.easeHide(object, next, time)
transition.to( object, {
xScale = 0.01,
yScale = 0.01,
time = time or 450,
transition = easing.inCubic,
onComplete = function()
if(next) then
next()
end
end
})
end
function animation.fadeIn(object)
object.alpha = 0
transition.to( object, {
alpha = 1,
time = 750
})
end
--------------------------------------------------------------------------------
function animation.flash()
local flash = display.newRect(
display.contentWidth/2,
display.contentHeight/2,
display.contentWidth,
display.contentHeight
)
flash:setFillColor(1)
transition.to(flash, {
time = 300,
alpha = 0,
onComplete = function ()
display.remove(flash)
end
})
end
--------------------------------------------------------------------------------
function animation.rotate(o, options)
options = options or {}
if(o.rotateAnimation) then
transition.cancel(o.rotateAnimation)
end
local rotateTime = options.rotateTime or 3000
local speed = options.speed or 1
local clock = 1
if(options.counterClockwise) then clock = -1 end
local toRotation = o.rotation + 360 * clock * speed
o.rotateAnimation = transition.to(o, {
rotation = toRotation,
time = rotateTime,
onComplete = function()
if(not options.onlyOnce) then
animation.rotate(o, options)
end
end
})
end
--------------------------------------------------------------------------------
return animation
|
--------------------------------------------------------------------------------
local _ = require 'cherry.libs.underscore'
local isArray = require 'cherry.libs.is-array'
--------------------------------------------------------------------------------
local animation = {}
--------------------------------------------------------
function animation.rotateBackAndForth(object, angle, time)
local initialRotation = object.rotation
local back = function()
transition.to(object, {
rotation = initialRotation,
onComplete = function() animation.rotateBackAndForth(object, -angle, time) end,
time = time
})
end
transition.to(object, {
rotation = angle,
onComplete = back,
time = time
})
end
--------------------------------------------------------
function animation.scaleBackAndForth(object, options)
options = options or {}
transition.cancel(object)
object.initialScale = object.initialScale or object.xScale
local scaleGrow = options.scale or 1.5
local back = function()
animation.bounce(object, _.extend({
time = options.time or 500,
scaleFrom = scaleGrow,
scaleTo = object.initialScale,
transition = easing.outBounce,
noDelay = true,
onComplete = function ()
if(options.loop) then
animation.scaleBackAndForth(object, options)
end
end
}, options))
end
animation.bounce(object, _.extend({
time = options.time or 500,
scaleFrom = object.initialScale,
scaleTo = scaleGrow,
transition = easing.outSine,
onComplete = back,
noDelay = true
}, options))
end
--------------------------------------------------------
function animation.easeDisplay(object, scale)
local scaleTo = scale or object.xScale or 1
object.xScale = 0.2
object.yScale = 0.2
return transition.to( object, {
xScale = scaleTo,
yScale = scaleTo,
time = 350,
transition = easing.outCubic
})
end
function animation.bounce(objects, options)
if(not isArray(objects)) then objects = {objects} end
options = options or {}
local scaleTo = options.scaleTo or 1
local scaleFrom = options.scaleFrom or 0.1
local _bounce = function(o)
o.xScale = scaleFrom
o.yScale = scaleFrom
transition.to( o, {
xScale = scaleTo,
yScale = scaleTo,
delay = options.delay or 0,
time = options.time or 750,
transition = options.transition or easing.outBounce,
onComplete = options.onComplete
})
end
local _bounceAll = function()
for _, o in ipairs(objects) do
_bounce(o)
end
end
_bounceAll()
end
function animation.grow(object, fromScale, time, onComplete)
object.xScale = fromScale or 0.6
object.yScale = fromScale or 0.6
transition.to( object, {
xScale = 1,
yScale = 1,
time = time or 150,
onComplete = onComplete
})
end
function animation.easeHide(object, next, time)
transition.to( object, {
xScale = 0.01,
yScale = 0.01,
time = time or 450,
transition = easing.inCubic,
onComplete = function()
if(next) then
next()
end
end
})
end
function animation.fadeIn(object)
object.alpha = 0
transition.to( object, {
alpha = 1,
time = 750
})
end
--------------------------------------------------------------------------------
function animation.flash()
local flash = display.newRect(
display.contentWidth/2,
display.contentHeight/2,
display.contentWidth,
display.contentHeight
)
flash:setFillColor(1)
transition.to(flash, {
time = 300,
alpha = 0,
onComplete = function ()
display.remove(flash)
end
})
end
--------------------------------------------------------------------------------
function animation.rotate(o, options)
options = options or {}
if(o.rotateAnimation) then
transition.cancel(o.rotateAnimation)
end
local rotateTime = options.rotateTime or 3000
local speed = options.speed or 1
local clock = 1
if(options.counterClockwise) then clock = -1 end
local toRotation = o.rotation + 360 * clock * speed
o.rotateAnimation = transition.to(o, {
rotation = toRotation,
time = rotateTime,
onComplete = function()
if(not options.onlyOnce) then
animation.rotate(o, options)
end
end
})
end
--------------------------------------------------------------------------------
return animation
|
fixed scaleBackAndForth reset with initialScale
|
fixed scaleBackAndForth reset with initialScale
|
Lua
|
bsd-3-clause
|
chrisdugne/cherry
|
2296e3517409fa3d35dfe1a54511dd9b0ea8ce22
|
modules/game_containers/containers.lua
|
modules/game_containers/containers.lua
|
function init()
g_ui.importStyle('container')
connect(Container, { onOpen = onContainerOpen,
onClose = onContainerClose,
onAddItem = onContainerAddItem,
onUpdateItem = onContainerUpdateItem,
onRemoveItem = onContainerRemoveItem })
connect(Game, { onGameEnd = clean() })
reloadContainers()
end
function terminate()
disconnect(Container, { onOpen = onContainerOpen,
onClose = onContainerClose,
onAddItem = onContainerAddItem,
onUpdateItem = onContainerUpdateItem,
onRemoveItem = onContainerRemoveItem })
disconnect(Game, { onGameEnd = clean() })
end
function reloadContainers()
clean()
for _,container in pairs(g_game.getContainers()) do
onContainerOpen(container)
end
end
function clean()
for containerid,container in pairs(g_game.getContainers()) do
if container.window then
container.window:destroy()
container.window = nil
container.itemsPanel = nil
end
end
end
function refreshContainerItems(container)
for slot=0,container:getCapacity()-1 do
local itemWidget = container.itemsPanel:getChildById('item' .. slot)
itemWidget:setItem(container:getItem(slot))
end
end
function onContainerOpen(container, previousContainer)
local containerWindow
if previousContainer then
containerWindow = previousContainer.window
previousContainer.window = nil
previousContainer.itemsPanel = nil
else
containerWindow = g_ui.createWidget('ContainerWindow', modules.game_interface.getRightPanel())
end
containerWindow:setId('container' .. container:getId())
local containerPanel = containerWindow:getChildById('contentsPanel')
local containerItemWidget = containerWindow:getChildById('containerItemWidget')
containerWindow.onClose = function()
g_game.close(container)
containerWindow:hide()
end
-- this disables scrollbar auto hiding
local scrollbar = containerWindow:getChildById('miniwindowScrollBar')
scrollbar:mergeStyle({ ['$!on'] = { }})
local upButton = containerWindow:getChildById('upButton')
upButton.onClick = function()
g_game.openParent(container)
end
upButton:setVisible(container:hasParent())
local name = container:getName()
name = name:sub(1,1):upper() .. name:sub(2)
containerWindow:setText(name)
containerItemWidget:setItem(container:getContainerItem())
containerPanel:destroyChildren()
for slot=0,container:getCapacity()-1 do
local itemWidget = g_ui.createWidget('Item', containerPanel)
itemWidget:setId('item' .. slot)
itemWidget:setItem(container:getItem(slot))
itemWidget:setMargin(0)
itemWidget.position = container:getSlotPosition(slot)
end
container.window = containerWindow
container.itemsPanel = containerPanel
local layout = containerPanel:getLayout()
local cellSize = layout:getCellSize()
containerWindow:setContentMinimumHeight(cellSize.height)
containerWindow:setContentMaximumHeight(cellSize.height*layout:getNumLines())
if not previousContainer then
local filledLines = math.max(math.ceil(container:getItemsCount() / layout:getNumColumns()), 1)
containerWindow:setContentHeight(filledLines*cellSize.height)
end
containerWindow:setup()
end
function onContainerClose(container)
if container.window then container.window:destroy() end
end
function onContainerAddItem(container, slot, item)
if not container.window then return end
refreshContainerItems(container)
end
function onContainerUpdateItem(container, slot, item, oldItem)
if not container.window then return end
local itemWidget = container.itemsPanel:getChildById('item' .. slot)
itemWidget:setItem(item)
end
function onContainerRemoveItem(container, slot, item)
if not container.window then return end
refreshContainerItems(container)
end
|
function init()
g_ui.importStyle('container')
connect(Container, { onOpen = onContainerOpen,
onClose = onContainerClose,
onAddItem = onContainerAddItem,
onUpdateItem = onContainerUpdateItem,
onRemoveItem = onContainerRemoveItem })
connect(Game, { onGameEnd = clean() })
reloadContainers()
end
function terminate()
disconnect(Container, { onOpen = onContainerOpen,
onClose = onContainerClose,
onAddItem = onContainerAddItem,
onUpdateItem = onContainerUpdateItem,
onRemoveItem = onContainerRemoveItem })
disconnect(Game, { onGameEnd = clean() })
end
function reloadContainers()
clean()
for _,container in pairs(g_game.getContainers()) do
onContainerOpen(container)
end
end
function clean()
for containerid,container in pairs(g_game.getContainers()) do
destroy(container)
end
end
function destroy(container)
if container.window then
container.window:destroy()
container.window = nil
container.itemsPanel = nil
end
end
function refreshContainerItems(container)
for slot=0,container:getCapacity()-1 do
local itemWidget = container.itemsPanel:getChildById('item' .. slot)
itemWidget:setItem(container:getItem(slot))
end
end
function onContainerOpen(container, previousContainer)
local containerWindow
if previousContainer then
containerWindow = previousContainer.window
previousContainer.window = nil
previousContainer.itemsPanel = nil
else
containerWindow = g_ui.createWidget('ContainerWindow', modules.game_interface.getRightPanel())
end
containerWindow:setId('container' .. container:getId())
local containerPanel = containerWindow:getChildById('contentsPanel')
local containerItemWidget = containerWindow:getChildById('containerItemWidget')
containerWindow.onClose = function()
g_game.close(container)
containerWindow:hide()
end
-- this disables scrollbar auto hiding
local scrollbar = containerWindow:getChildById('miniwindowScrollBar')
scrollbar:mergeStyle({ ['$!on'] = { }})
local upButton = containerWindow:getChildById('upButton')
upButton.onClick = function()
g_game.openParent(container)
end
upButton:setVisible(container:hasParent())
local name = container:getName()
name = name:sub(1,1):upper() .. name:sub(2)
containerWindow:setText(name)
containerItemWidget:setItem(container:getContainerItem())
containerPanel:destroyChildren()
for slot=0,container:getCapacity()-1 do
local itemWidget = g_ui.createWidget('Item', containerPanel)
itemWidget:setId('item' .. slot)
itemWidget:setItem(container:getItem(slot))
itemWidget:setMargin(0)
itemWidget.position = container:getSlotPosition(slot)
end
container.window = containerWindow
container.itemsPanel = containerPanel
local layout = containerPanel:getLayout()
local cellSize = layout:getCellSize()
containerWindow:setContentMinimumHeight(cellSize.height)
containerWindow:setContentMaximumHeight(cellSize.height*layout:getNumLines())
if not previousContainer then
local filledLines = math.max(math.ceil(container:getItemsCount() / layout:getNumColumns()), 1)
containerWindow:setContentHeight(filledLines*cellSize.height)
end
containerWindow:setup()
end
function onContainerClose(container)
destroy(container)
end
function onContainerAddItem(container, slot, item)
if not container.window then return end
refreshContainerItems(container)
end
function onContainerUpdateItem(container, slot, item, oldItem)
if not container.window then return end
local itemWidget = container.itemsPanel:getChildById('item' .. slot)
itemWidget:setItem(item)
end
function onContainerRemoveItem(container, slot, item)
if not container.window then return end
refreshContainerItems(container)
end
|
Fix issue with closing containers * Wasn't clearing references properly.
|
Fix issue with closing containers
* Wasn't clearing references properly.
|
Lua
|
mit
|
EvilHero90/otclient,gpedro/otclient,Radseq/otclient,dreamsxin/otclient,gpedro/otclient,gpedro/otclient,Cavitt/otclient_mapgen,kwketh/otclient,Radseq/otclient,dreamsxin/otclient,EvilHero90/otclient,kwketh/otclient,dreamsxin/otclient,Cavitt/otclient_mapgen
|
44d0bfe0427d7e4d9a2dd437c218e7e964f88b7d
|
selist.lua
|
selist.lua
|
function box.auto_increment_uniq(spaceno, uniq, ...)
local tuple = box.select(spaceno, 1, uniq)
if tuple then
local format = 'i'
if #tuple[0] == 8 then
format = 'l'
end
return box.replace(spaceno, box.unpack(format, tuple[0]), uniq, ...)
end
return box.auto_increment(spaceno, uniq, ...)
end
local function mysplit(inputstr, sep)
if sep == nil then
sep = "%s"
end
local t={} ; i=1
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
t[i] = str
i = i + 1
end
return t
end
local function find_second_level_domain(mask)
local splited = mysplit(mask, '@')
local email_domain_part = splited[#splited]
local domain_parts = mysplit(email_domain_part, '.')
if #domain_parts == 0 then
error('In mask ' .. mask .. ' no domain found')
end
if #domain_parts == 1 then
error('In mask ' .. mask .. ' only first level domain found')
end
return domain_parts[#domain_parts - 1] .. '.' .. domain_parts[#domain_parts]
end
function selist2_add_sender(mask, name_ru, name_en, cat)
return box.auto_increment_uniq(0, mask, name_ru, name_en, box.unpack('i', cat), find_second_level_domain(mask)):transform(5,1)
end
function get_sender_list_by_offset(offset, limit)
offset = box.unpack('i', offset)
limit = box.unpack('i', limit)
return { box.select_limit(0, 0, offset, limit):transform(5,1) }
end
function get_sender_list_by_ids(...)
local ret = { }
for i, v in ipairs({...}) do
local tuple = box.select(0, 0, box.unpack('i', v)):transform(5,1)
table.insert(ret, tuple)
end
return unpack(ret)
end
function selist2_search_by_mask(mask)
return box.select(0, 1, mask):transform(5,1)
end
function selist2_search_by_domain(domain)
return box.select(0, 2, domain):transform(5,1)
end
|
function box.auto_increment_uniq(spaceno, uniq, ...)
local tuple = box.select(spaceno, 1, uniq)
if tuple then
local format = 'i'
if #tuple[0] == 8 then
format = 'l'
end
return box.replace(spaceno, box.unpack(format, tuple[0]), uniq, ...)
end
return box.auto_increment(spaceno, uniq, ...)
end
local function mysplit(inputstr, sep)
if sep == nil then
sep = "%s"
end
local t={} ; i=1
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
t[i] = str
i = i + 1
end
return t
end
local function find_second_level_domain(mask)
local splited = mysplit(mask, '@')
local email_domain_part = splited[#splited]
local domain_parts = mysplit(email_domain_part, '.')
if #domain_parts == 0 then
error('In mask ' .. mask .. ' no domain found')
end
if #domain_parts == 1 then
error('In mask ' .. mask .. ' only first level domain found')
end
return domain_parts[#domain_parts - 1] .. '.' .. domain_parts[#domain_parts]
end
function selist2_add_sender(mask, name_ru, name_en, cat)
return box.auto_increment_uniq(0, mask, name_ru, name_en, box.unpack('i', cat), find_second_level_domain(mask)):transform(5,1)
end
function get_sender_list_by_offset(offset, limit)
offset = box.unpack('i', offset)
limit = box.unpack('i', limit)
local ret = {}
local orig = {box.select_limit(0, 0, offset, limit)}
for _, tuple in ipairs(orig) do
table.insert(ret, tuple:transform(5, 1))
end
return unpack(ret)
end
function get_sender_list_by_ids(...)
local ret = { }
for i, v in ipairs({...}) do
local tuples = {box.select(0, 0, box.unpack('i', v))}
for _, tuple in ipairs(tuples) do
table.insert(ret, tuple:transform(5, 1))
end
end
return unpack(ret)
end
function selist2_search_by_mask(mask)
local ret = { }
local orig = {box.select(0, 1, mask)}
for _, tuple in ipairs(orig) do
table.insert(ret, tuple:transform(5, 1))
end
return unpack(ret)
end
function selist2_search_by_domain(domain)
local ret = { }
local orig = {box.select(0, 2, domain)}
for _, tuple in ipairs(orig) do
table.insert(ret, tuple:transform(5, 1))
end
return unpack(ret)
end
|
Selist2 fix
|
Selist2 fix
|
Lua
|
bsd-2-clause
|
mailru/tntlua,BHYCHIK/tntlua,derElektrobesen/tntlua,spectrec/tntlua,grechkin-pogrebnyakov/tntlua
|
996309128b99c6ec9105dd8545a65494023a50ec
|
modules/title/post/pgolds.lua
|
modules/title/post/pgolds.lua
|
local DBI = require 'DBI'
local util = require'util'
require'logging.console'
local log = logging.console()
-- Connection handle
local conn = false
-- Open connection to the postgresql database using DBI lib and ivar2 global config
local connect = function()
local dbh, err = DBI.Connect('PostgreSQL', ivar2.config.dbname, ivar2.config.dbuser, ivar2.config.dbpass, ivar2.config.dbhost, ivar2.config.dbport)
if not dbh then
log:error("Unable to connect to DB: %s", err)
return
end
conn = dbh
end
local openDb = function()
if not conn then
connect()
end
-- Check if connection is alive
local alive = conn:ping()
if not alive then
connect()
end
local success, err = DBI.Do(conn, 'SELECT NOW()')
if not success then
log:error("SQL Connection: %s", err)
connect()
end
return conn
end
local function url_to_pattern(str)
str = str:gsub('^https?://', 'http%%://')
return str
end
local function extract_youtube_id(str)
local patterns = {
"https?://www%.youtube%.com/watch%?.*v=([%d%a_%-]+)",
"https?://youtube%.com/watch%?.*v=([%d%a_%-]+)",
"https?://youtu.be/([%d%a_%-]+)",
"https?://youtube.com/v/([%d%a_%-]+)",
"https?://www.youtube.com/v/([%d%a_%-]+)"
}
for _,pattern in ipairs(patterns) do
local video_id = string.match(str, pattern)
if video_id ~= nil and string.len(video_id) < 20 then
return video_id
end
end
end
-- check for existing url
local checkOlds = function(dbh, source, destination, url)
-- create a select handle
local query = [[
SELECT
date_trunc('second', time),
date_trunc('second', age(now(), date_trunc('second', time))),
nick
FROM urls
WHERE
url LIKE ?
AND
channel = ?
ORDER BY time ASC
]]
-- Check for youtube ID
local vid = extract_youtube_id(url)
if vid ~= nil then
url = '%youtube.com%v='..vid..'%'
end
url = url_to_pattern(url)
local sth = assert(dbh:prepare(query))
-- execute select with a url bound to variable
sth:execute(url, destination)
-- get list of column names in the result set
--local columns = sth:columns()
local count = 0
local nick
local ago
-- iterate over the returned data
for row in sth:rows() do
count = count + 1
-- rows() with no arguments (or false) returns
-- the data as a numerically indexed table
-- passing it true returns a table indexed by
-- column names
if count == 1 then
ago = row[2]
nick = row[3]
return nick, count, ago
end
end
return nick, count, ago
end
-- save url to db
local dbLogUrl = function(dbh, source, destination, url, msg)
local nick = source.nick
log:info(string.format('Inserting URL into db. %s,%s, %s, %s', nick, destination, msg, url))
-- check status of the connection
-- local alive = dbh:ping()
-- create a handle for an insert
local insert = dbh:prepare('INSERT INTO urls(nick,channel,url,message) values(?,?,?,?)')
-- execute the handle with bind parameters
insert:execute(nick, destination, url, msg)
-- commit the transaction
dbh:commit()
--local ok = dbh:close()
end
do
return function(source, destination, queue, msg)
local dbh = openDb()
local nick, count, ago = checkOlds(dbh, source, destination, queue.url)
dbLogUrl(dbh, source, destination, queue.url, msg)
if not count then return end
if count == 0 then return end
-- Check if this module is disabled and just stop here if it is
if not ivar2:IsModuleDisabled('olds', destination) then
local prepend
-- We don't need to highlight the first linker
nick = util.nonickalertword(nick)
if(count > 1) then
prepend = string.format("Olds! %s times, first by %s %s", count, nick, ago)
else
prepend = string.format("Olds! Linked by %s %s ago", nick, ago)
end
if(queue.output) then
queue.output = string.format("%s - %s", prepend, queue.output)
else
queue.output = prepend
end
end
end
end
|
local DBI = require 'DBI'
local util = require'util'
-- Connection handle
local conn = false
-- Open connection to the postgresql database using DBI lib and ivar2 global config
local connect = function()
local dbh, err = DBI.Connect('PostgreSQL', ivar2.config.dbname, ivar2.config.dbuser, ivar2.config.dbpass, ivar2.config.dbhost, ivar2.config.dbport)
if not dbh then
ivar2:Log('error', "Unable to connect to DB: %s", err)
return
end
conn = dbh
end
local openDb = function()
if not conn then
connect()
end
-- Check if connection is alive
local alive = conn:ping()
if not alive then
connect()
end
local success, err = DBI.Do(conn, 'SELECT NOW()')
if not success then
ivar2:Log('error', "SQL Connection: %s", err)
connect()
end
return conn
end
local function url_to_pattern(str)
str = str:gsub('^https?://', 'http%%://')
return str
end
local function extract_youtube_id(str)
local patterns = {
"https?://www%.youtube%.com/watch%?.*v=([%d%a_%-]+)",
"https?://youtube%.com/watch%?.*v=([%d%a_%-]+)",
"https?://youtu.be/([%d%a_%-]+)",
"https?://youtube.com/v/([%d%a_%-]+)",
"https?://www.youtube.com/v/([%d%a_%-]+)"
}
for _,pattern in ipairs(patterns) do
local video_id = string.match(str, pattern)
if video_id ~= nil and string.len(video_id) < 20 then
return video_id
end
end
end
-- check for existing url
local checkOlds = function(dbh, source, destination, url)
-- create a select handle
local query = [[
SELECT
date_trunc('second', time),
date_trunc('second', age(now(), date_trunc('second', time))),
nick
FROM urls
WHERE
url LIKE ?
AND
channel = ?
ORDER BY time ASC
]]
-- Check for youtube ID
local vid = extract_youtube_id(url)
if vid ~= nil then
url = '%youtube.com%v='..vid..'%'
end
url = url_to_pattern(url)
local sth = assert(dbh:prepare(query))
-- execute select with a url bound to variable
sth:execute(url, destination)
-- get list of column names in the result set
--local columns = sth:columns()
local count = 0
local nick
local ago
-- iterate over the returned data
for row in sth:rows() do
count = count + 1
-- rows() with no arguments (or false) returns
-- the data as a numerically indexed table
-- passing it true returns a table indexed by
-- column names
if count == 1 then
ago = row[2]
nick = row[3]
end
end
return nick, count, ago
end
-- save url to db
local dbLogUrl = function(dbh, source, destination, url, msg)
local nick = source.nick
ivar2:Log('info', string.format('Inserting URL into db. %s,%s, %s, %s', nick, destination, msg, url))
-- check status of the connection
-- local alive = dbh:ping()
-- create a handle for an insert
local insert = dbh:prepare('INSERT INTO urls(nick,channel,url,message) values(?,?,?,?)')
-- execute the handle with bind parameters
insert:execute(nick, destination, url, msg)
-- commit the transaction
dbh:commit()
--local ok = dbh:close()
end
do
return function(source, destination, queue, msg)
local dbh = openDb()
local nick, count, ago = checkOlds(dbh, source, destination, queue.url)
dbLogUrl(dbh, source, destination, queue.url, msg)
if not count then return end
if count == 0 then return end
-- Check if this module is disabled and just stop here if it is
if not ivar2:IsModuleDisabled('olds', destination) then
local prepend
-- We don't need to highlight the first linker
nick = util.nonickalertword(nick)
if(count > 1) then
prepend = string.format("Olds! %s times, first by %s %s", count, nick, ago)
else
prepend = string.format("Olds! Linked by %s %s ago", nick, ago)
end
if(queue.output) then
queue.output = string.format("%s - %s", prepend, queue.output)
else
queue.output = prepend
end
end
end
end
|
title: pgolds: fix the count, logging, indent
|
title: pgolds: fix the count, logging, indent
Former-commit-id: 290c82ab2840deefb7368bb7faf70e658a826afa
Former-commit-id: 8b53abdc3230608a8a1ee3f71e14ecaf7047734a
|
Lua
|
mit
|
torhve/ivar2,torhve/ivar2,torhve/ivar2,haste/ivar2
|
21da9283d698934d02b248228eadf599ca2a8ac3
|
Resources/Scripts/Modules/ShipBuilding.lua
|
Resources/Scripts/Modules/ShipBuilding.lua
|
function LookupBuildId(class, race)
for id, obj in ipairs(data.objects) do
if class == obj.class and race == obj.race then
return id
end
end
end
function CalculateBuildables(object, scen)--[HACK]
for idx, class in ipairs(object.building.classes) do
object.building.ids[idx] = LookupBuildId(class,
scen.base.players[
object.ai.owner+1
].race)
end
end
function BeginBuilding(planet, class)
end
function StopBuilding(planet)
end
function GetCash(player)
return scen.players[player].cash
end
function AddCash(player, cash)
return scen.players[player].cash = scen.players[player].cash + cash
end
function GetBuildPercent(planet)
end
function UpdatePlanet(planet, dt)
end
|
function LookupBuildId(class, race)
for id, obj in ipairs(data.objects) do
if class == obj.class and race == obj.race then
return id
end
end
end
function CalculateBuildables(object, scen)--[HACK]
for idx, class in ipairs(object.building.classes) do
object.building.ids[idx] = LookupBuildId(class,
scen.base.players[
object.ai.owner+1
].race)
end
end
function BeginBuilding(planet, class)
end
function StopBuilding(planet)
end
function GetCash(player)
return scen.players[player].cash
end
function AddCash(player, cash)
scen.players[player].cash = scen.players[player].cash + cash
return scen.players[player].cash
end
function GetBuildPercent(planet)
end
function UpdatePlanet(planet, dt)
end
|
Fixed AddCash function.
|
Fixed AddCash function.
Signed-off-by: Scott McClaugherty <[email protected]>
|
Lua
|
mit
|
adam000/xsera,adam000/xsera,prophile/xsera,prophile/xsera,adam000/xsera,prophile/xsera,prophile/xsera,adam000/xsera,prophile/xsera
|
b4b67b1f75be5e4014240bb5c5103da6579666a1
|
scripts/chem_notepad.lua
|
scripts/chem_notepad.lua
|
dofile("common.inc");
function doit()
local tree = loadNotes("scripts/chem-cheap.txt");
browseMenu(tree);
end
function browseMenu(tree)
local done = false;
local tags = {};
local nextIndex = 1;
while not done do
local y = 0;
for i=1,#tags do
y = y + 30;
lsPrint(40, y, 0, 0.9, 0.9, 0xd0d0d0ff, tags[i]);
end
local nextTags = lookupData(tree, tags);
if not nextTags then
lsPrint(10, y, 0, 0.7, 0.7, 0xffd0d0ff, "No note found");
y = y + 30;
elseif type(nextTags) == "table" then
table.sort(nextTags);
for i=1,#nextTags do
local x = 40;
if i % 2 == 0 then
x = 160;
else
y = y + 30;
end
if lsButtonText(x, y, 0, 100, 0xd0ffd0ff, nextTags[i]) then
table.insert(tags, nextTags[i]);
end
end
y = y + 30;
-- if nextTags[1] ~= "" then
-- table.insert(nextTags, 1, "");
-- end
-- nextIndex = lsDropdown("NoteIndex", 40, y, 0, 250, nextIndex, nextTags);
-- if nextIndex ~= 1 then
-- table.insert(tags, nextTags[nextIndex]);
-- nextIndex = 1;
-- end
else
y = y + 30;
lsPrintWrapped(10, y, 0, lsScreenX - 20, 0.7, 0.7, 0xffffffff, nextTags);
end
if lsButtonText(10, lsScreenY - 30, 0, 100, 0xffffffff, "Restart") then
if #tags > 0 then
-- table.remove(tags);
tags = {};
nextIndex = 1;
else
-- done = true;
end
end
if lsButtonText(lsScreenX - 110, lsScreenY - 30, 0, 100, 0xffffffff,
"End Script") then
error(quit_message);
end
checkBreak();
lsSleep(tick_delay);
lsDoFrame();
end
end
function setLine(tree, line)
--local sections = csplit(line, "|");
local sections = explode("|",line);
if #sections ~= 2 then
error("Cannot parse line: " .. line);
end
--local tags = csplit(sections[1], ",");
local tags = csplit(",",sections[1]);
local data = sections[2];
setData(tree, tags, data);
end
function setData(tree, tags, data, index)
if not index then
index = 1;
end
if #tags == index then
tree[tags[index]] = data;
else
local current = tags[index];
if type(tree[current]) ~= "table" then
tree[current] = {};
end
setData(tree[current], tags, data, index + 1);
end
end
function lookupData(tree, tags, index)
if not index then
index = 1;
end
local result = {};
if tree == nil then
result = nil;
elseif type(tree) ~= "table" then
result = tree;
elseif #tags < index then
for key,value in pairs(tree) do
table.insert(result, key);
end
else
local current = tags[index];
result = lookupData(tree[current], tags, index + 1);
end
return result;
end
function dataToLine(prefix, value)
local result = "";
for i=1,#prefix do
result = result .. prefix;
if i ~= #prefix then
result = result .. ",";
end
end
result = result .. "|" .. value;
return result;
end
function lookupAllData(prefix, tree, result)
for key,value in pairs(tree) do
table.insert(prefix, key);
if type(value) == "table" then
lookupAllData(prefix, value, result);
else
table.insert(result, dataToLine(prefix, value));
end
table.remove(prefix);
end
end
function loadNotes(filename)
local result = {};
local file = io.open(filename, "a+");
io.close(file);
for line in io.lines(filename) do
setLine(result, line);
end
return result;
end
function saveNotes(filename, tree)
local file = io.open(filename, "w+");
local lines = {};
lookupAllData({}, tree, lines);
for line in lines do
file:write(line .. "\n");
end
io.close(file);
end
-- Added in an explode function (delimiter, string) to deal with broken csplit.
function explode(d,p)
local t, ll
t={}
ll=0
if(#p == 1) then
return {p}
end
while true do
l = string.find(p, d, ll, true) -- find the next d in the string
if l ~= nil then -- if "not not" found then..
table.insert(t, string.sub(p,ll,l-1)) -- Save it in our array.
ll = l + 1 -- save just after where we found it for searching next time.
else
table.insert(t, string.sub(p,ll)) -- Save what's left in our array.
break -- Break at end, as it should be, according to the lua manual.
end
end
return t
end
|
dofile("common.inc");
function doit()
local tree = loadNotes("scripts/chem-cheap.txt");
browseMenu(tree);
end
function browseMenu(tree)
local done = false;
local tags = {};
local nextIndex = 1;
while not done do
local y = 0;
for i=1,#tags do
y = y + 30;
lsPrint(40, y, 0, 0.9, 0.9, 0xd0d0d0ff, tags[i]);
end
local nextTags = lookupData(tree, tags);
if not nextTags then
lsPrint(10, y, 0, 0.7, 0.7, 0xffd0d0ff, "No note found");
y = y + 30;
elseif type(nextTags) == "table" then
table.sort(nextTags);
for i=1,#nextTags do
local x = 40;
if i % 2 == 0 then
x = 160;
else
y = y + 30;
end
if lsButtonText(x, y, 0, 100, 0xd0ffd0ff, nextTags[i]) then
table.insert(tags, nextTags[i]);
end
end
y = y + 30;
-- if nextTags[1] ~= "" then
-- table.insert(nextTags, 1, "");
-- end
-- nextIndex = lsDropdown("NoteIndex", 40, y, 0, 250, nextIndex, nextTags);
-- if nextIndex ~= 1 then
-- table.insert(tags, nextTags[nextIndex]);
-- nextIndex = 1;
-- end
else
y = y + 30;
lsPrintWrapped(10, y, 0, lsScreenX - 20, 0.7, 0.7, 0xffffffff, nextTags);
end
if lsButtonText(10, lsScreenY - 30, 0, 100, 0xffffffff, "Restart") then
if #tags > 0 then
-- table.remove(tags);
tags = {};
nextIndex = 1;
else
-- done = true;
end
end
if lsButtonText(lsScreenX - 110, lsScreenY - 30, 0, 100, 0xffffffff,
"End Script") then
error(quit_message);
end
checkBreak();
lsSleep(tick_delay);
lsDoFrame();
end
end
function setLine(tree, line)
--local sections = csplit(line, "|");
local sections = explode("|",line);
if #sections ~= 2 then
error("Cannot parse line: " .. line);
end
--local tags = csplit(sections[1], ",");
-- local tags = csplit(",",sections[1]);
local tags = explode(",",sections[1]);
local data = sections[2];
setData(tree, tags, data);
end
function setData(tree, tags, data, index)
if not index then
index = 1;
end
if #tags == index then
tree[tags[index]] = data;
else
local current = tags[index];
if type(tree[current]) ~= "table" then
tree[current] = {};
end
setData(tree[current], tags, data, index + 1);
end
end
function lookupData(tree, tags, index)
if not index then
index = 1;
end
local result = {};
if tree == nil then
result = nil;
elseif type(tree) ~= "table" then
result = tree;
elseif #tags < index then
for key,value in pairs(tree) do
table.insert(result, key);
end
else
local current = tags[index];
result = lookupData(tree[current], tags, index + 1);
end
return result;
end
function dataToLine(prefix, value)
local result = "";
for i=1,#prefix do
result = result .. prefix;
if i ~= #prefix then
result = result .. ",";
end
end
result = result .. "|" .. value;
return result;
end
function lookupAllData(prefix, tree, result)
for key,value in pairs(tree) do
table.insert(prefix, key);
if type(value) == "table" then
lookupAllData(prefix, value, result);
else
table.insert(result, dataToLine(prefix, value));
end
table.remove(prefix);
end
end
function loadNotes(filename)
local result = {};
local file = io.open(filename, "a+");
io.close(file);
for line in io.lines(filename) do
setLine(result, line);
end
return result;
end
function saveNotes(filename, tree)
local file = io.open(filename, "w+");
local lines = {};
lookupAllData({}, tree, lines);
for line in lines do
file:write(line .. "\n");
end
io.close(file);
end
-- Added in an explode function (delimiter, string) to deal with broken csplit.
function explode(d,p)
local t, ll
t={}
ll=0
if(#p == 1) then
return {p}
end
while true do
l = string.find(p, d, ll, true) -- find the next d in the string
if l ~= nil then -- if "not not" found then..
table.insert(t, string.sub(p,ll,l-1)) -- Save it in our array.
ll = l + 1 -- save just after where we found it for searching next time.
else
table.insert(t, string.sub(p,ll)) -- Save what's left in our array.
break -- Break at end, as it should be, according to the lua manual.
end
end
return t
end
|
chem_notepad.lua - Fix missing text on buttons (missing explode function)
|
chem_notepad.lua - Fix missing text on buttons (missing explode function)
|
Lua
|
mit
|
DashingStrike/Automato-ATITD,DashingStrike/Automato-ATITD
|
b753819e37332470c6e525a58e48691ca338cb7c
|
stdlib/utils/scripts/console.lua
|
stdlib/utils/scripts/console.lua
|
--- Debug console.
-- Creates a textfield allowing you to run commands directly in your mod's enviorment.
-- <p>This module requires the use of stdlib's @{Event} module for GUI interactions.
-- <p>This module was originally the ***Console*** code from a modder named ***adil***, which has been modified for use with stdlib.
-- @script console
-- @usage
-- local console = require("stdlib/utils/console")
-- remote.add_interface("my_interface", {show = console})
-- /c remote.call("my_interface", "show", game.player)
-- --In the window that appears you can run lua code directly on your mod, including globals.
require('stdlib/event/gui')
local prefix = script.mod_name
local names = {
frame = prefix..'_console',
scroll = prefix..'_console_scroll',
textbox = prefix..'_console_line',
enter = prefix..'_console_enter',
clear = prefix..'_console_clear',
close = prefix..'_console_close',
}
local function create_gui_player(player)
if player.gui.left[names.frame] then player.gui.left[names.frame].destroy() end
local c = player.gui.left.add{type='frame', name = names.frame, direction = 'horizontal'}
local scroll = c.add{type = 'scroll-pane', name = names.scroll}
scroll.style.minimal_width=600
scroll.style.maximal_width=600
scroll.style.maximal_height=150
scroll.style.minimal_height=150
local t = scroll.add{type = 'text-box', name = names.textbox}
t.style.minimal_width=600
t.style.maximal_width=600
t.style.minimal_height=150
c.add{type = 'button', name = names.enter, caption = '<', tooltip = "Run Script"}
c.add{type = 'button', name = names.clear, caption = 'C', tooltip = "Clear Input"}
c.add{type = 'button', name = names.close, caption = "X", tooltip = "Close"}
end
local function create_gui(player)
--if not sent with a player, then enable for all players?
if not (player and player.valid) then
for _, cur_player in pairs(game.players) do
create_gui_player(cur_player)
end
else
create_gui_player(player)
end
end
local function enter(event)
local p = game.players[event.player_index]
local s = event.element.parent[names.scroll][names.textbox].text
local ok, err = pcall(function() return loadstring(s)() end )
if not ok then p.print(err) end
game.write_file(prefix..'/console.log', s..'\n', true, p.index)
end
Gui.on_click('^'..names.enter..'$', enter)
local function close(event)
event.element.parent.destroy()
end
Gui.on_click('^'..names.close..'$', close)
local function clear(event)
event.element.parent[names.scroll][names.textbox].text = ""
end
Gui.on_click('^'..names.clear..'$', clear)
return create_gui
|
--- Debug console.
-- Creates a textfield allowing you to run commands directly in your mod's enviorment.
-- <p>This module requires the use of stdlib's @{Event} module for GUI interactions.
-- <p>This module was originally the ***Console*** code from a modder named ***adil***, which has been modified for use with stdlib.
-- @script console
-- @usage
-- local console = require("stdlib/utils/console")
-- remote.add_interface("my_interface", {show = console})
-- /c remote.call("my_interface", "show", game.player)
-- --In the window that appears you can run lua code directly on your mod, including globals.
require('stdlib/event/gui')
-- munge hyphens as they otherwise need escaping in lua's regexnih pattern language
local prefix = string.gsub(script.mod_name, '%-', '_')
local names = {
frame = prefix..'_console',
scroll = prefix..'_console_scroll',
textbox = prefix..'_console_line',
enter = prefix..'_console_enter',
clear = prefix..'_console_clear',
close = prefix..'_console_close',
}
local function create_gui_player(player)
if player.gui.left[names.frame] then player.gui.left[names.frame].destroy() end
local c = player.gui.left.add{type='frame', name = names.frame, direction = 'horizontal'}
local scroll = c.add{type = 'scroll-pane', name = names.scroll}
scroll.style.minimal_width=600
scroll.style.maximal_width=600
scroll.style.maximal_height=150
scroll.style.minimal_height=150
local t = scroll.add{type = 'text-box', name = names.textbox}
t.style.minimal_width=600
t.style.maximal_width=600
t.style.minimal_height=150
c.add{type = 'button', name = names.enter, caption = '<', tooltip = "Run Script"}
c.add{type = 'button', name = names.clear, caption = 'C', tooltip = "Clear Input"}
c.add{type = 'button', name = names.close, caption = "X", tooltip = "Close"}
end
local function create_gui(player)
--if not sent with a player, then enable for all players?
if not (player and player.valid) then
for _, cur_player in pairs(game.players) do
create_gui_player(cur_player)
end
else
create_gui_player(player)
end
end
local function enter(event)
local p = game.players[event.player_index]
local s = event.element.parent[names.scroll][names.textbox].text
local ok, err = pcall(function() return loadstring(s)() end )
if not ok then p.print(err) end
game.write_file(prefix..'/console.log', s..'\n', true, p.index)
end
Gui.on_click('^'..names.enter..'$', enter)
local function close(event)
event.element.parent.destroy()
end
Gui.on_click('^'..names.close..'$', close)
local function clear(event)
event.element.parent[names.scroll][names.textbox].text = ""
end
Gui.on_click('^'..names.clear..'$', clear)
return create_gui
|
Console pattern matching fix (#112)
|
Console pattern matching fix (#112)
The only thing worse than losing days to an
infuriatingly elusive bug is finding out it's
a completely uninteresting head-slapper, for
the slaying of which there will be no glory.
Signed-off-by: Gregory M. Turner <[email protected]>
|
Lua
|
isc
|
Afforess/Factorio-Stdlib
|
4a2fcca79963eb33bf06c841015567a2ffcef9ce
|
pud/view/GameCam.lua
|
pud/view/GameCam.lua
|
local Class = require 'lib.hump.class'
local Camera = require 'lib.hump.camera'
local vector = require 'lib.hump.vector'
local Rect = getClass '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,...)
verify('vector', 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)
verifyClass(Rect, 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
|
local Class = require 'lib.hump.class'
local Camera = require 'lib.hump.camera'
local vector = require 'lib.hump.vector'
local Rect = getClass 'pud.kit.Rect'
local message = require 'pud.component.message'
local property = require 'pud.component.property'
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,...)
verify('vector', 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
-- receive - receives messages from followed ComponentMediator
function GameCam:receive(msg, pos, oldpos)
if msg == message('HAS_MOVED') then
local size = self._targetSize
self._cam.pos.x = (pos.x-1) * size + size/2
self._cam.pos.y = (pos.y-1) * size + size/2
self:_correctPos(self._cam.pos)
end
end
-- follow a target
function GameCam:followTarget(t)
verifyClass('pud.component.ComponentMediator', t)
self:unfollowTarget()
t:attach(message('HAS_MOVED'), self)
self._targetSize = t:query(property('TileSize'))
self._target = t
end
-- unfollow a target Rect
function GameCam:unfollowTarget()
if self._target then
self._target:detach(message('HAS_MOVED'), self)
self._target = nil
self._targetSize = 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 GameCam follow to work with ComponentMediator
|
fix GameCam follow to work with ComponentMediator
|
Lua
|
mit
|
scottcs/wyx
|
6ee4ddbdb9dd901e1650988cd6f5409e84267b33
|
gateway/src/apicast/management.lua
|
gateway/src/apicast/management.lua
|
local _M = {}
local cjson = require('cjson')
local context = require('apicast.executor'):context()
local router = require('router')
local configuration_parser = require('apicast.configuration_parser')
local configuration_loader = require('apicast.configuration_loader')
local inspect = require('inspect')
local resolver_cache = require('resty.resolver.cache')
local env = require('resty.env')
local policy_manifests_loader = require('apicast.policy_manifests_loader')
local setmetatable = setmetatable
local live = { status = 'live', success = true }
local function json_response(body, status)
ngx.header.content_type = 'application/json; charset=utf-8'
ngx.status = status or ngx.HTTP_OK
ngx.say(cjson.encode(body))
end
function _M.ready()
local status = _M.status()
local code = status.success and ngx.HTTP_OK or 412
json_response(status, code)
end
function _M.live()
json_response(live, ngx.HTTP_OK)
end
function _M.status(config)
local configuration = config or context.configuration
-- TODO: this should be fixed for multi-tenant deployment
local has_configuration = configuration.configured
local has_services = #(configuration:all()) > 0
if not has_configuration then
return { status = 'error', error = 'not configured', success = false }
elseif not has_services then
return { status = 'warning', warning = 'no services', success = true }
else
return { status = 'ready', success = true }
end
end
function _M.config()
local config = context.configuration
local contents = cjson.encode(config.configured and { services = config:all() } or nil)
ngx.header.content_type = 'application/json; charset=utf-8'
ngx.status = ngx.HTTP_OK
ngx.say(contents)
end
function _M.update_config()
ngx.req.read_body()
ngx.log(ngx.DEBUG, 'management config update')
local data = ngx.req.get_body_data()
local file = ngx.req.get_body_file()
if not data then
data = assert(io.open(file)):read('*a')
end
local config, err = configuration_parser.decode(data)
if config then
local configured, error = configuration_loader.configure(context.configuration, config)
-- TODO: respond with proper 304 Not Modified when config is the same
if configured and #(configured.services) > 0 then
json_response({ status = 'ok', config = config, services = #(configured.services)})
else
json_response({ status = 'not_configured', config = config, services = 0, error = error }, ngx.HTTP_NOT_ACCEPTABLE)
end
else
json_response({ status = 'error', config = config or cjson.null, error = err}, ngx.HTTP_BAD_REQUEST)
end
end
function _M.delete_config()
ngx.log(ngx.DEBUG, 'management config delete')
context.configuration:reset()
-- TODO: respond with proper 304 Not Modified when config is the same
local response = cjson.encode({ status = 'ok', config = cjson.null })
ngx.header.content_type = 'application/json; charset=utf-8'
ngx.say(response)
end
local util = require 'apicast.util'
function _M.boot()
local data = util.timer('configuration.boot', configuration_loader.boot)
local config = configuration_parser.decode(data)
local response = cjson.encode({ status = 'ok', config = config or cjson.null })
ngx.log(ngx.DEBUG, 'management boot config:' .. inspect(data))
configuration_loader.configure(context.configuration, config)
ngx.say(response)
end
function _M.dns_cache()
local cache = resolver_cache.shared()
return json_response(cache:all())
end
function _M.disabled()
ngx.exit(ngx.HTTP_FORBIDDEN)
end
function _M.info()
return json_response({
timers = {
pending = ngx.timer.pending_count(),
running = ngx.timer.running_count()
},
worker = {
exiting = ngx.worker.exiting(),
count = ngx.worker.count(),
id = ngx.worker.id()
}
})
end
function _M.get_all_policy_manifests()
local manifests = policy_manifests_loader.get_all()
setmetatable(manifests, cjson.array_mt)
return json_response({ policies = manifests })
end
local routes = {}
function routes.disabled(r)
r:get('/', _M.disabled)
end
function routes.status(r)
r:get('/status/info', _M.info)
r:get('/status/ready', _M.ready)
r:get('/status/live', _M.live)
routes.policies(r)
end
function routes.debug(r)
r:get('/config', _M.config)
r:put('/config', _M.update_config)
r:post('/config', _M.update_config)
r:delete('/config', _M.delete_config)
routes.status(r)
r:get('/dns/cache', _M.dns_cache)
r:post('/boot', _M.boot)
routes.policies(r)
end
function routes.policies(r)
r:get('/policies/', _M.get_all_policy_manifests)
end
function _M.router()
local r = router.new()
local name = env.value('APICAST_MANAGEMENT_API') or 'status'
local api = routes[name]
ngx.log(ngx.DEBUG, 'management api mode: ', name)
if api then
api(r)
else
ngx.log(ngx.ERR, 'invalid management api setting: ', name)
end
return r
end
function _M.call(method, uri, ...)
local r = _M.router()
local ok, err = r:execute(method or ngx.req.get_method(),
uri or ngx.var.uri,
unpack(... or {}))
if not ok then
ngx.status = 404
end
if err then
ngx.say(err)
end
end
return _M
|
local _M = {}
local cjson = require('cjson')
local context = require('apicast.executor'):context()
local router = require('router')
local configuration_parser = require('apicast.configuration_parser')
local configuration_loader = require('apicast.configuration_loader')
local inspect = require('inspect')
local resolver_cache = require('resty.resolver.cache')
local env = require('resty.env')
local policy_manifests_loader = require('apicast.policy_manifests_loader')
local live = { status = 'live', success = true }
local function json_response(body, status)
ngx.header.content_type = 'application/json; charset=utf-8'
ngx.status = status or ngx.HTTP_OK
ngx.say(cjson.encode(body))
end
function _M.ready()
local status = _M.status()
local code = status.success and ngx.HTTP_OK or 412
json_response(status, code)
end
function _M.live()
json_response(live, ngx.HTTP_OK)
end
function _M.status(config)
local configuration = config or context.configuration
-- TODO: this should be fixed for multi-tenant deployment
local has_configuration = configuration.configured
local has_services = #(configuration:all()) > 0
if not has_configuration then
return { status = 'error', error = 'not configured', success = false }
elseif not has_services then
return { status = 'warning', warning = 'no services', success = true }
else
return { status = 'ready', success = true }
end
end
function _M.config()
local config = context.configuration
local contents = cjson.encode(config.configured and { services = config:all() } or nil)
ngx.header.content_type = 'application/json; charset=utf-8'
ngx.status = ngx.HTTP_OK
ngx.say(contents)
end
function _M.update_config()
ngx.req.read_body()
ngx.log(ngx.DEBUG, 'management config update')
local data = ngx.req.get_body_data()
local file = ngx.req.get_body_file()
if not data then
data = assert(io.open(file)):read('*a')
end
local config, err = configuration_parser.decode(data)
if config then
local configured, error = configuration_loader.configure(context.configuration, config)
-- TODO: respond with proper 304 Not Modified when config is the same
if configured and #(configured.services) > 0 then
json_response({ status = 'ok', config = config, services = #(configured.services)})
else
json_response({ status = 'not_configured', config = config, services = 0, error = error }, ngx.HTTP_NOT_ACCEPTABLE)
end
else
json_response({ status = 'error', config = config or cjson.null, error = err}, ngx.HTTP_BAD_REQUEST)
end
end
function _M.delete_config()
ngx.log(ngx.DEBUG, 'management config delete')
context.configuration:reset()
-- TODO: respond with proper 304 Not Modified when config is the same
local response = cjson.encode({ status = 'ok', config = cjson.null })
ngx.header.content_type = 'application/json; charset=utf-8'
ngx.say(response)
end
local util = require 'apicast.util'
function _M.boot()
local data = util.timer('configuration.boot', configuration_loader.boot)
local config = configuration_parser.decode(data)
local response = cjson.encode({ status = 'ok', config = config or cjson.null })
ngx.log(ngx.DEBUG, 'management boot config:' .. inspect(data))
configuration_loader.configure(context.configuration, config)
ngx.say(response)
end
function _M.dns_cache()
local cache = resolver_cache.shared()
return json_response(cache:all())
end
function _M.disabled()
ngx.exit(ngx.HTTP_FORBIDDEN)
end
function _M.info()
return json_response({
timers = {
pending = ngx.timer.pending_count(),
running = ngx.timer.running_count()
},
worker = {
exiting = ngx.worker.exiting(),
count = ngx.worker.count(),
id = ngx.worker.id()
}
})
end
function _M.get_all_policy_manifests()
local manifests = policy_manifests_loader.get_all()
return json_response({ policies = manifests })
end
local routes = {}
function routes.disabled(r)
r:get('/', _M.disabled)
end
function routes.status(r)
r:get('/status/info', _M.info)
r:get('/status/ready', _M.ready)
r:get('/status/live', _M.live)
routes.policies(r)
end
function routes.debug(r)
r:get('/config', _M.config)
r:put('/config', _M.update_config)
r:post('/config', _M.update_config)
r:delete('/config', _M.delete_config)
routes.status(r)
r:get('/dns/cache', _M.dns_cache)
r:post('/boot', _M.boot)
routes.policies(r)
end
function routes.policies(r)
r:get('/policies/', _M.get_all_policy_manifests)
end
function _M.router()
local r = router.new()
local name = env.value('APICAST_MANAGEMENT_API') or 'status'
local api = routes[name]
ngx.log(ngx.DEBUG, 'management api mode: ', name)
if api then
api(r)
else
ngx.log(ngx.ERR, 'invalid management api setting: ', name)
end
return r
end
function _M.call(method, uri, ...)
local r = _M.router()
local ok, err = r:execute(method or ngx.req.get_method(),
uri or ngx.var.uri,
unpack(... or {}))
if not ok then
ngx.status = 404
end
if err then
ngx.say(err)
end
end
return _M
|
[management] fix policies API
|
[management] fix policies API
Setting cjson.array_mt would not serialize non integer elements
resulting in always empty array response.
|
Lua
|
mit
|
3scale/apicast,3scale/docker-gateway,3scale/apicast,3scale/docker-gateway,3scale/apicast,3scale/apicast
|
eff60dacf1e85722c64dc8138b8ce5a00744ba69
|
lua/mediaplayer/players/entity/cl_init.lua
|
lua/mediaplayer/players/entity/cl_init.lua
|
include "shared.lua"
DEFINE_BASECLASS( "mp_base" )
local pcall = pcall
local print = print
local Angle = Angle
local IsValid = IsValid
local ValidPanel = ValidPanel
local Vector = Vector
local cam = cam
local Start3D = cam.Start3D
local Start3D2D = cam.Start3D2D
local End3D2D = cam.End3D2D
local draw = draw
local math = math
local string = string
local surface = surface
local FullscreenCvar = MediaPlayer.Cvars.Fullscreen
MEDIAPLAYER.Enable3DAudio = true
function MEDIAPLAYER:NetReadUpdate()
local entIndex = net.ReadUInt(16)
local ent = Entity(entIndex)
local mpEnt = self.Entity
if MediaPlayer.DEBUG then
print("MEDIAPLAYER.NetReadUpdate[entity]: ", ent, entIndex)
end
if ent ~= mpEnt then
if IsValid(ent) and ent ~= NULL then
ent:InstallMediaPlayer( self )
else
-- Wait until the entity becomes valid
self._EntIndex = entIndex
end
end
end
local RenderScale = 0.1
local InfoScale = 1/17
function MEDIAPLAYER:GetOrientation()
return self.Entity and self.Entity:GetMediaPlayerPosition() or nil
end
function MEDIAPLAYER:Draw( bDrawingDepth, bDrawingSkybox )
local ent = self.Entity
if --bDrawingSkybox or
FullscreenCvar:GetBool() or -- Don't draw if we're drawing fullscreen
not IsValid(ent) or
(ent.IsDormant and ent:IsDormant()) then
return
end
local media = self:GetMedia()
local w, h, pos, ang = self:GetOrientation()
-- Render scale
local rw, rh = w / RenderScale, h / RenderScale
if IsValid(media) then
-- Custom media draw function
if media.Draw then
Start3D2D( pos, ang, RenderScale )
media:Draw( rw, rh )
End3D2D()
end
-- TODO: else draw 'not yet implemented' screen?
-- Media info
Start3D2D( pos, ang, InfoScale )
local iw, ih = w / InfoScale, h / InfoScale
self:DrawMediaInfo( media, iw, ih )
End3D2D()
else
local browser = MediaPlayer.GetIdlescreen()
if ValidPanel(browser) then
Start3D2D( pos, ang, RenderScale )
self:DrawHTML( browser, rw, rh )
End3D2D()
end
end
end
function MEDIAPLAYER:SetMedia( media )
if media and self.Enable3DAudio then
-- Set entity on media for 3D support
media.Entity = self:GetEntity()
end
BaseClass.SetMedia( self, media )
end
|
include "shared.lua"
DEFINE_BASECLASS( "mp_base" )
local pcall = pcall
local print = print
local Angle = Angle
local IsValid = IsValid
local ValidPanel = ValidPanel
local Vector = Vector
local cam = cam
local Start3D = cam.Start3D
local Start3D2D = cam.Start3D2D
local End3D2D = cam.End3D2D
local draw = draw
local math = math
local string = string
local surface = surface
local FullscreenCvar = MediaPlayer.Cvars.Fullscreen
MEDIAPLAYER.Enable3DAudio = true
function MEDIAPLAYER:NetReadUpdate()
local entIndex = net.ReadUInt(16)
local ent = Entity(entIndex)
local mpEnt = self.Entity
if MediaPlayer.DEBUG then
print("MEDIAPLAYER.NetReadUpdate[entity]: ", ent, entIndex)
end
if ent ~= mpEnt then
if IsValid(ent) and ent ~= NULL then
ent:InstallMediaPlayer( self )
else
-- Wait until the entity becomes valid
self._EntIndex = entIndex
end
end
end
local RenderScale = 0.1
local InfoScale = 1/17
function MEDIAPLAYER:GetOrientation()
local ent = self.Entity
if ent then
return ent:GetMediaPlayerPosition()
end
return nil
end
function MEDIAPLAYER:Draw( bDrawingDepth, bDrawingSkybox )
local ent = self.Entity
if --bDrawingSkybox or
FullscreenCvar:GetBool() or -- Don't draw if we're drawing fullscreen
not IsValid(ent) or
(ent.IsDormant and ent:IsDormant()) then
return
end
local media = self:GetMedia()
local w, h, pos, ang = self:GetOrientation()
-- Render scale
local rw, rh = w / RenderScale, h / RenderScale
if IsValid(media) then
-- Custom media draw function
if media.Draw then
Start3D2D( pos, ang, RenderScale )
media:Draw( rw, rh )
End3D2D()
end
-- TODO: else draw 'not yet implemented' screen?
-- Media info
Start3D2D( pos, ang, InfoScale )
local iw, ih = w / InfoScale, h / InfoScale
self:DrawMediaInfo( media, iw, ih )
End3D2D()
else
local browser = MediaPlayer.GetIdlescreen()
if ValidPanel(browser) then
Start3D2D( pos, ang, RenderScale )
self:DrawHTML( browser, rw, rh )
End3D2D()
end
end
end
function MEDIAPLAYER:SetMedia( media )
if media and self.Enable3DAudio then
-- Set entity on media for 3D support
media.Entity = self:GetEntity()
end
BaseClass.SetMedia( self, media )
end
|
Fixed media player entities erroring when attempting to draw in 3D2D.
|
Fixed media player entities erroring when attempting to draw in 3D2D.
|
Lua
|
mit
|
pixeltailgames/gm-mediaplayer,pixeltailgames/gm-mediaplayer
|
bfeab5bc8344b16e975b4b3205141fbaa498f56f
|
libs/sys/luasrc/sys/mtdow.lua
|
libs/sys/luasrc/sys/mtdow.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local io = require "io"
local os = require "os"
local fs = require "luci.fs"
local util = require "luci.util"
local ltn12 = require "luci.ltn12"
local posix = require "posix"
local type, assert, error = type, assert, error
module "luci.sys.mtdow"
WRITE_IMAGE = 0
WRITE_COMBINED = 1
WRITE_EMULATED = 2
ERROR_INTERNAL = 1
ERROR_NOTFOUND = 2
ERROR_RESOURCE = 3
ERROR_NODETECT = 4
ERROR_NOTAVAIL = 5
ERROR_NOSTREAM = 6
ERROR_INVMAGIC = 7
Writer = util.class()
-- x86
EmulatedWriter = util.class(Writer)
EmulatedWriter.blocks = {
image = {
magic = "eb48",
device = "/dev/hda",
write = WRITE_SEPARATELY
}
}
function EmulatedWriter.write_block(self, name, imagestream, appendpattern)
if appendpattern then
os.execute("grep rootfs /proc/mtd >/dev/null || "
.. "{ echo /dev/hda2,65536,rootfs > "
.. "/sys/module/block2mtd/parameters/block2mtd }")
end
return Writer.write_block(self, name, imagestream, appendpattern)
end
-- Broadcom
CFEWriter = util.class(Writer)
CFEWriter.blocks = {
image = {
magic = {"4844", "5735"},
device = "linux",
write = WRITE_COMBINED
}
}
-- Magicbox
CommonWriter = util.class(Writer)
CommonWriter.blocks = {
image = {
device = "linux",
write = WRITE_COMBINED
}
}
-- Atheros
RedWriter = util.class(Writer)
RedWriter.blocks = {
kernel = {
device = "vmlinux.bin.l7",
write = WRITE_IMAGE
},
rootfs = {
device = "rootfs",
write = WRITE_COMBINED
}
}
-- Auto Detect
function native_writer()
local w = Writer()
-- Detect amd64 / x86
local x86 = {"x86_64", "i386", "i486", "i586", "i686"}
if util.contains(x86, posix.uname("%m")) then
return EmulatedWriter()
end
-- Detect CFE
if w:_find_mtdblock("cfe") and w:_find_mtdblock("linux") then
return CFEWriter()
end
-- Detect Redboot
if w:_find_mtdblock("RedBoot") and w:_find_mtdblock("vmlinux.bin.l7") then
return RedWriter()
end
-- Detect MagicBox
if fs.readfile("/proc/cpuinfo"):find("MagicBox") then
return CommonWriter()
end
end
Writer.MTD = "/sbin/mtd"
Writer.SAFEMTD = "/tmp/mtd"
Writer.IMAGEFIFO = "/tmp/mtdimage.fifo"
function Writer.write_block(self, name, imagestream, appendfile)
assert(self.blocks[name], ERROR_NOTFOUND)
local block = self.blocks[name]
local device = block.device
device = fs.stat(device) and device or self:_find_mtdblock(device)
assert(device, ERROR_NODETECT)
if block.magic then
imagestream = self:_check_magic(imagestream, block.magic)
end
assert(imagestream, ERROR_INVMAGIC)
if appendfile then
if block.write == WRITE_COMBINED then
return (self:_write_combined(device, imagestream, appendfile) == 0)
elseif block.write == WRITE_EMULATED then
return (self:_write_emulated(device, imagestream, appendfile) == 0)
else
error(ERROR_NOTAVAIL)
end
else
return (self:_write_memory(device, imagestream) == 0)
end
end
function Writer._check_magic(self, imagestream, magic)
magic = type(magic) == "table" and magic or {magic}
local block = imagestream()
assert(block, ERROR_NOSTREAM)
local cm = "%x%x" % {block:byte(1), block:byte(2)}
if util.contains(magic, cm) then
return ltn12.source.cat(ltn12.source.string(block), imagestream)
end
end
function Writer._find_mtdblock(self, mtdname)
local k
local prefix = "/dev/mtdblock"
prefix = prefix .. (fs.stat(prefix) and "/" or "")
for l in io.lines("/proc/mtd") do
local k = l:match('([%w-_]+):.*-"%s"' % mtdname)
if k then return prefix..k end
end
end
function Write._write_emulated(self, devicename, imagestream, appendfile)
local stat = (self:_write_memory(device, imagestream) == 0)
stat = stat and (self:_refresh_block("rootfs") == 0)
local squash = self:_find_mtdblock("rootfs_data")
if squash then
stat = stat and (self:_append("rootfs_data", imagestream, true) == 0)
else
stat = stat and (self:_append("rootfs", imagestream) == 0)
end
return stat
end
function Writer._write_memory(self, devicename, imagestream)
local devicestream = ltn12.sink.file(io.open(devicename, "w"))
local stat, err = ltn12.pump.all(imagestream, devicestream)
if stat then
return os.execute("sync")
end
end
function Writer._write_combined(self, devicename, imagestream, appendfile)
assert(fs.copy(self.MTD, self.SAFEMTD), ERROR_INTERNAL)
assert(posix.mkfifo(self.IMAGEFIFO), ERROR_RESOURCE)
local imagefifo = io.open(self.IMAGEFIFO, "w")
assert(imagefifo, ERROR_RESOURCE)
local imageproc = posix.fork()
assert(imageproc ~= -1, ERROR_RESOURCE)
if imageproc == 0 then
ltn12.pump.all(imagestream, ltn12.sink.file(imagefifo))
os.exit(0)
end
return os.execute(
"%s -j '%s' write '%s' '%s'" % {
self.SAFEMTD, appendfile, devicename, self.IMAGEFIFO
}
)
end
function Writer._refresh_block(self, devicename)
assert(fs.copy(self.MTD, self.SAFEMTD), ERROR_INTERNAL)
return os.execute("%s refresh '%s'" % {self.SAFEMTD, devicename})
end
function Writer._append(self, devicename, appendfile, erase)
assert(fs.copy(self.MTD, self.SAFEMTD), ERROR_INTERNAL)
erase = erase and ("-e '%s' " % devicename) or ''
return os.execute(
"%s %s jffs2write '%s' '%s'" % {
self.SAFEMTD, erase, appendfile, devicename
}
)
end
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local io = require "io"
local os = require "os"
local fs = require "luci.fs"
local util = require "luci.util"
local ltn12 = require "luci.ltn12"
local posix = require "posix"
local type, assert, error = type, assert, error
module "luci.sys.mtdow"
WRITE_IMAGE = 0
WRITE_COMBINED = 1
WRITE_EMULATED = 2
ERROR_INTERNAL = 1
ERROR_NOTFOUND = 2
ERROR_RESOURCE = 3
ERROR_NODETECT = 4
ERROR_NOTAVAIL = 5
ERROR_NOSTREAM = 6
ERROR_INVMAGIC = 7
Writer = util.class()
-- x86
EmulatedWriter = util.class(Writer)
EmulatedWriter.blocks = {
image = {
magic = "eb48",
device = "/dev/hda",
write = WRITE_SEPARATELY
}
}
function EmulatedWriter.write_block(self, name, imagestream, appendpattern)
if appendpattern then
os.execute("grep rootfs /proc/mtd >/dev/null || "
.. "{ echo /dev/hda2,65536,rootfs > "
.. "/sys/module/block2mtd/parameters/block2mtd }")
end
return Writer.write_block(self, name, imagestream, appendpattern)
end
-- Broadcom
CFEWriter = util.class(Writer)
CFEWriter.blocks = {
image = {
magic = {"4844", "5735"},
device = "linux",
write = WRITE_COMBINED
}
}
-- Magicbox
CommonWriter = util.class(Writer)
CommonWriter.blocks = {
image = {
device = "linux",
write = WRITE_COMBINED
}
}
-- Atheros
RedWriter = util.class(Writer)
RedWriter.blocks = {
kernel = {
device = "vmlinux.bin.l7",
write = WRITE_IMAGE
},
rootfs = {
device = "rootfs",
write = WRITE_COMBINED
}
}
-- Auto Detect
function native_writer()
local w = Writer()
-- Detect amd64 / x86
local x86 = {"x86_64", "i386", "i486", "i586", "i686"}
if util.contains(x86, posix.uname("%m")) then
return EmulatedWriter()
end
-- Detect CFE
if w:_find_mtdblock("cfe") and w:_find_mtdblock("linux") then
return CFEWriter()
end
-- Detect Redboot
if w:_find_mtdblock("RedBoot") and w:_find_mtdblock("vmlinux.bin.l7") then
return RedWriter()
end
-- Detect MagicBox
if fs.readfile("/proc/cpuinfo"):find("MagicBox") then
return CommonWriter()
end
end
Writer.MTD = "/sbin/mtd"
Writer.SAFEMTD = "/tmp/mtd"
Writer.IMAGEFIFO = "/tmp/mtdimage.fifo"
function Writer.write_block(self, name, imagestream, appendfile)
assert(self.blocks[name], ERROR_NOTFOUND)
local block = self.blocks[name]
local device = block.device
device = fs.stat(device) and device or self:_find_mtdblock(device)
assert(device, ERROR_NODETECT)
if block.magic then
imagestream = self:_check_magic(imagestream, block.magic)
end
assert(imagestream, ERROR_INVMAGIC)
if appendfile then
if block.write == WRITE_COMBINED then
return (self:_write_combined(device, imagestream, appendfile) == 0)
elseif block.write == WRITE_EMULATED then
return (self:_write_emulated(device, imagestream, appendfile) == 0)
else
error(ERROR_NOTAVAIL)
end
else
return (self:_write_memory(device, imagestream) == 0)
end
end
function Writer._check_magic(self, imagestream, magic)
magic = type(magic) == "table" and magic or {magic}
local block = imagestream()
assert(block, ERROR_NOSTREAM)
local cm = "%x%x" % {block:byte(1), block:byte(2)}
if util.contains(magic, cm) then
return ltn12.source.cat(ltn12.source.string(block), imagestream)
end
end
function Writer._find_mtdblock(self, mtdname)
local k
local prefix = "/dev/mtd"
prefix = prefix .. (fs.stat(prefix) and "/" or "")
for l in io.lines("/proc/mtd") do
local k = l:match('mtd([%%w-_]+):.*"%s"' % mtdname)
if k then return prefix..k end
end
end
function Writer._write_emulated(self, devicename, imagestream, appendfile)
local stat = (self:_write_memory(device, imagestream) == 0)
stat = stat and (self:_refresh_block("rootfs") == 0)
local squash = self:_find_mtdblock("rootfs_data")
if squash then
stat = stat and (self:_append("rootfs_data", imagestream, true) == 0)
else
stat = stat and (self:_append("rootfs", imagestream) == 0)
end
return stat
end
function Writer._write_memory(self, devicename, imagestream)
local devicestream = ltn12.sink.file(io.open(devicename, "w"))
local stat, err = ltn12.pump.all(imagestream, devicestream)
if stat then
return os.execute("sync")
end
end
function Writer._write_combined(self, devicename, imagestream, appendfile)
local imageproc = posix.fork()
assert(imageproc ~= -1, ERROR_RESOURCE)
if imageproc == 0 then
fs.unlink(self.IMAGEFIFO)
assert(posix.mkfifo(self.IMAGEFIFO), ERROR_RESOURCE)
local imagefifo = io.open(self.IMAGEFIFO, "w")
assert(imagefifo, ERROR_RESOURCE)
ltn12.pump.all(imagestream, ltn12.sink.file(imagefifo))
os.exit(0)
end
return os.execute(
"%s -j '%s' write '%s' '%s'" % {
self.MTD, appendfile, self.IMAGEFIFO, devicename
}
)
end
function Writer._refresh_block(self, devicename)
return os.execute("%s refresh '%s'" % {self.MTD, devicename})
end
function Writer._append(self, devicename, appendfile, erase)
erase = erase and ("-e '%s' " % devicename) or ''
return os.execute(
"%s %s jffs2write '%s' '%s'" % {
self.MTD, erase, appendfile, devicename
}
)
end
|
mtdow fixes level 1
|
mtdow fixes level 1
git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@3355 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,alxhh/piratenluci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,saraedum/luci-packages-old,yeewang/openwrt-luci,Flexibity/luci,gwlim/luci,freifunk-gluon/luci,Flexibity/luci,zwhfly/openwrt-luci,stephank/luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,zwhfly/openwrt-luci,8devices/carambola2-luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,vhpham80/luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,gwlim/luci,Flexibity/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,gwlim/luci,freifunk-gluon/luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,stephank/luci,gwlim/luci,alxhh/piratenluci,Flexibity/luci,alxhh/piratenluci,freifunk-gluon/luci,vhpham80/luci,phi-psi/luci,phi-psi/luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,vhpham80/luci,ch3n2k/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,jschmidlapp/luci,stephank/luci,alxhh/piratenluci,8devices/carambola2-luci,freifunk-gluon/luci,gwlim/luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,yeewang/openwrt-luci,phi-psi/luci,projectbismark/luci-bismark,ch3n2k/luci,yeewang/openwrt-luci,Canaan-Creative/luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,phi-psi/luci,jschmidlapp/luci,projectbismark/luci-bismark,yeewang/openwrt-luci,yeewang/openwrt-luci,Canaan-Creative/luci,alxhh/piratenluci,saraedum/luci-packages-old,8devices/carambola2-luci,8devices/carambola2-luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,freifunk-gluon/luci,Flexibity/luci,stephank/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,vhpham80/luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,Canaan-Creative/luci,gwlim/luci,8devices/carambola2-luci,zwhfly/openwrt-luci,alxhh/piratenluci,eugenesan/openwrt-luci,jschmidlapp/luci,zwhfly/openwrt-luci,projectbismark/luci-bismark,alxhh/piratenluci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,jschmidlapp/luci,Flexibity/luci,projectbismark/luci-bismark,vhpham80/luci,yeewang/openwrt-luci,freifunk-gluon/luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,projectbismark/luci-bismark,stephank/luci,jschmidlapp/luci,Canaan-Creative/luci,ch3n2k/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,saraedum/luci-packages-old,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,eugenesan/openwrt-luci,jschmidlapp/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,ch3n2k/luci,freifunk-gluon/luci,eugenesan/openwrt-luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,Flexibity/luci,vhpham80/luci,gwlim/luci
|
081a48ada0b00d514b3ddc118f1fa2d17b9eadda
|
core/storagemanager.lua
|
core/storagemanager.lua
|
local error, type = error, type;
local setmetatable = setmetatable;
local config = require "core.configmanager";
local datamanager = require "util.datamanager";
local modulemanager = require "core.modulemanager";
local multitable = require "util.multitable";
local hosts = hosts;
local log = require "util.logger".init("storagemanager");
local olddm = {}; -- maintain old datamanager, for backwards compatibility
for k,v in pairs(datamanager) do olddm[k] = v; end
module("storagemanager")
local default_driver_mt = { name = "internal" };
default_driver_mt.__index = default_driver_mt;
function default_driver_mt:open(store)
return setmetatable({ host = self.host, store = store }, default_driver_mt);
end
function default_driver_mt:get(user) return olddm.load(user, self.host, self.store); end
function default_driver_mt:set(user, data) return olddm.store(user, self.host, self.store, data); end
local stores_available = multitable.new();
function initialize_host(host)
host_session.events.add_handler("item-added/data-driver", function (event)
local item = event.item;
stores_available:set(host, item.name, item);
end);
host_session.events.add_handler("item-removed/data-driver", function (event)
local item = event.item;
stores_available:set(host, item.name, nil);
end);
end
local function load_driver(host, driver_name)
if not driver_name then
return;
end
local driver = stores_available:get(host, driver_name);
if not driver then
if driver_name ~= "internal" then
modulemanager.load(host, "storage_"..driver_name);
return stores_available:get(host, driver_name);
else
return setmetatable({host = host}, default_driver_mt);
end
end
end
function open(host, store, typ)
local storage = config.get(host, "core", "storage");
local driver_name;
local option_type = type(storage);
if option_type == "string" then
driver_name = storage;
elseif option_type == "table" then
driver_name = storage[store];
end
local driver = load_driver(host, driver_name);
if not driver then
driver_name = config.get(host, "core", "default_storage");
driver = load_driver(host, driver_name);
if not driver then
if storage or driver_name then
log("warn", "Falling back to default driver for %s storage on %s", store, host);
end
driver_name = "internal";
driver = load_driver(host, driver_name);
end
end
local ret, err = driver:open(store, typ);
if not ret then
if err == "unsupported-store" then
log("debug", "Storage driver %s does not support store %s (%s), falling back to internal driver",
driver_name, store, typ);
ret = setmetatable({ host = host, store = store }, default_driver_mt); -- default to default driver
err = nil;
end
end
return ret, err;
end
function datamanager.load(username, host, datastore)
return open(host, datastore):get(username);
end
function datamanager.store(username, host, datastore, data)
return open(host, datastore):set(username, data);
end
return _M;
|
local error, type = error, type;
local setmetatable = setmetatable;
local config = require "core.configmanager";
local datamanager = require "util.datamanager";
local modulemanager = require "core.modulemanager";
local multitable = require "util.multitable";
local hosts = hosts;
local log = require "util.logger".init("storagemanager");
local olddm = {}; -- maintain old datamanager, for backwards compatibility
for k,v in pairs(datamanager) do olddm[k] = v; end
module("storagemanager")
local default_driver_mt = { name = "internal" };
default_driver_mt.__index = default_driver_mt;
function default_driver_mt:open(store)
return setmetatable({ host = self.host, store = store }, default_driver_mt);
end
function default_driver_mt:get(user) return olddm.load(user, self.host, self.store); end
function default_driver_mt:set(user, data) return olddm.store(user, self.host, self.store, data); end
local stores_available = multitable.new();
function initialize_host(host)
local host_session = hosts[host];
host_session.events.add_handler("item-added/data-driver", function (event)
local item = event.item;
stores_available:set(host, item.name, item);
end);
host_session.events.add_handler("item-removed/data-driver", function (event)
local item = event.item;
stores_available:set(host, item.name, nil);
end);
end
local function load_driver(host, driver_name)
if not driver_name then
return;
end
local driver = stores_available:get(host, driver_name);
if not driver then
if driver_name ~= "internal" then
modulemanager.load(host, "storage_"..driver_name);
return stores_available:get(host, driver_name);
else
return setmetatable({host = host}, default_driver_mt);
end
end
end
function open(host, store, typ)
local storage = config.get(host, "core", "storage");
local driver_name;
local option_type = type(storage);
if option_type == "string" then
driver_name = storage;
elseif option_type == "table" then
driver_name = storage[store];
end
local driver = load_driver(host, driver_name);
if not driver then
driver_name = config.get(host, "core", "default_storage");
driver = load_driver(host, driver_name);
if not driver then
if storage or driver_name then
log("warn", "Falling back to default driver for %s storage on %s", store, host);
end
driver_name = "internal";
driver = load_driver(host, driver_name);
end
end
local ret, err = driver:open(store, typ);
if not ret then
if err == "unsupported-store" then
log("debug", "Storage driver %s does not support store %s (%s), falling back to internal driver",
driver_name, store, typ);
ret = setmetatable({ host = host, store = store }, default_driver_mt); -- default to default driver
err = nil;
end
end
return ret, err;
end
function datamanager.load(username, host, datastore)
return open(host, datastore):get(username);
end
function datamanager.store(username, host, datastore, data)
return open(host, datastore):set(username, data);
end
return _M;
|
storagemanager: Fixed a nil global access.
|
storagemanager: Fixed a nil global access.
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
91c14286788d6358340ae8fd8960d3cdb0b6717d
|
test.lua
|
test.lua
|
local json = require 'json'
print(json.parse("\"hello\""))
print(json.parse("'hello'"))
print(json.parse("1234"))
print(json.parse("true"))
print(json.parse("false"))
print(json.parse("null"))
function print_json(arg)
if type(arg) == 'table' then
io.write("{\n")
for k, v in pairs(arg) do
io.write(string.format("\t%s: ", k))
print_json(v)
io.write("\n")
end
io.write("}\n")
else
io.write(tostring(arg))
end
end
strings = {
"[ 'hello', 1234, true, null, false ]",
"{ 'hello': 1234, 'cool': true }",
"[ ['hello'], { 'wowza': 1234, 'bur': true}, [[[null]], [false] ]]"
}
for _, j in pairs(strings) do
res = json.parse(j)
print_json(res)
end
|
local json = require 'json'
print(json.parse("\"hello\""))
print(json.parse("'hello'"))
print(json.parse("1234"))
print(json.parse("true"))
print(json.parse("false"))
print(json.parse("null"))
function print_json(arg)
if type(arg) == 'table' then
io.write("{\n")
for k, v in pairs(arg) do
io.write(string.format("\t%s: ", k))
print_json(v)
io.write("\n")
end
io.write("}\n")
else
io.write(tostring(arg))
end
end
strings = {
"[ 'hello', 1234, true, null, false ]",
"{ 'hello': 1234, 'cool': true }",
"[ ['hello'], { 'wowza': 1234, 'bur': true}, [[[null]], [false] ]]"
}
for _, j in pairs(strings) do
res = json.parse(j)
print_json(res)
end
|
fixes indentations
|
fixes indentations
|
Lua
|
mit
|
FilWisher/lua-json,FilWisher/lua-json
|
883ff4ffe839bb77579c7e902a665763091397fa
|
src/wiola/wiola.lua
|
src/wiola/wiola.lua
|
--
-- Project: this project
-- User: kostik
-- Date: 16.03.14
--
local redisLib = require "resty.redis"
local redis = redisLib:new()
local ok, err = redis:connect("unix:/tmp/redis.sock")
if not ok then
ngx.say("failed to connect: ", err)
return
end
local _M = {
_VERSION = '0.1'
}
_M.__index = _M
local wamp_features = {
agent = "wiola/Lua v0.1",
roles = {
broker = {},
dealer = {}
}
}
local WAMP_MSG_SPEC = {
HELLO = 1,
WELCOME = 2,
ABORT = 3,
CHALLENGE = 4,
AUTHENTICATE = 5,
GOODBYE = 6,
HEARTBEAT = 7,
ERROR = 8,
PUBLISH = 16,
PUBLISHED = 17,
SUBSCRIBE = 32,
SUBSCRIBED = 33,
UNSUBSCRIBE = 34,
UNSUBSCRIBED = 35,
EVENT = 36,
CALL = 48,
CANCEL = 49,
RESULT = 50,
REGISTER = 64,
REGISTERED = 65,
UNREGISTER = 66,
UNREGISTERED = 67,
INVOCATION = 68,
INTERRUPT = 69,
YIELD = 70
}
local _cache = {
sessions = {},
publications = {},
subscriptions = {},
registrations = {},
ids = {},
requests = {},
realms = {}
}
-- Generate unique Id
local function getRegId()
local regId
math.randomseed( os.time() )
repeat
-- regId = math.random(9007199254740992)
regId = math.random(100000000000000)
until redis:sismember("wiolaIds",regId)
return regId
end
-- Validate uri for WAMP requirements
local function validateURI(uri)
-- var re = /^([0-9a-z_]{2,}\.)*([0-9a-z_]{2,})$/;
-- if(!re.test(uri) || uri.indexOf('wamp') === 0) {
-- return false;
-- } else {
-- return true;
-- }
end
-- Convert redis hgetall array to lua table
local function redisArr2table(ra)
local t = {}
local i = 1
while i < #ra do
t[ra[i]] = ra[i+1]
i = i + 2
end
return t
end
-- Add connection to wiola
function _M.addConnection(sid, wampProto)
local regId = getRegId()
local wProto, dataType
redis:sadd("wiolaIds",regId)
if wampProto == nil or wampProto == "" then
wampProto = 'wamp.2.json' -- Setting default protocol for encoding/decodig use
end
if wProto == 'wamp.2.msgpack' then
dataType = 'binary'
else
dataType = 'text'
end
local res, err = redis:hmset("wiolaSession" .. regId,
{ connId = sid,
sessId = regId,
isWampEstablished = 1,
-- realm = nil,
-- wamp_features = nil,
wamp_protocol = wampProto,
dataType = dataType }
)
ngx.log(ngx.DEBUG, "redis:hmset wiolaSessionKey: ", wiolaSessionKey, " Result: ", err)
return regId, dataType
end
-- Remove connection from wiola
function _M.removeConnection(regId)
local session = redisArr2table(redis:hgetall("wiolaSession" .. regId))
var_dump(session)
ngx.log(ngx.DEBUG, "Removing session: ", regId)
redis:srem("wiolaRealm" .. session.realm .. "Sessions",regId)
local rs = redis:scard("wiolaRealm" .. session.realm .. "Sessions")
if rs == 0 then
redis:del("wiolaRealm" .. session.realm .. "Sessions")
end
ngx.log(ngx.DEBUG, "Realm ", session.realm, " sessions count now is ", rs)
redis:del("wiolaSession" .. regId .. "Data")
redis:del("wiolaSession" .. regId)
redis:srem("wiolaIds",regId)
end
-- Prepare data for sending to client
local function sendData(session, data)
local dataObj
if session.wamp_protocol == 'wamp.2.msgpack' then
local mp = require 'MessagePack'
dataObj = mp.pack(data)
else --if session.wamp_protocol == 'wamp.2.json'
local cjson = require "cjson"
dataObj = cjson.encode(data)
end
ngx.log(ngx.DEBUG, "Preparing data for client: ", dataObj);
redis:rpush("wiolaSession" .. session.sessId .. "Data", dataObj)
end
-- Receive data from client
function _M.receiveData(regId, data)
local session = redisArr2table(redis:hgetall("wiolaSession" .. regId))
local dataObj
var_dump(session)
if session.wamp_protocol == 'wamp.2.msgpack' then
local mp = require 'MessagePack'
dataObj = mp.unpack(data)
else --if session.wamp_protocol == 'wamp.2.json'
local cjson = require "cjson"
dataObj = cjson.decode(data)
end
ngx.log(ngx.DEBUG, "Cli regId: ", regId, " Received data decoded. WAMP msg Id: ", dataObj[1])
-- Analyze WAMP message ID received
if dataObj[1] == WAMP_MSG_SPEC.HELLO then -- WAMP SPEC: [HELLO, Realm|uri, Details|dict]
if session.isWampEstablished == 1 then
-- Protocol error: received second hello message - aborting
-- WAMP SPEC: [GOODBYE, Details|dict, Reason|uri]
sendData(session, { WAMP_MSG_SPEC.GOODBYE, {}, "wamp.error.system_shutdown" })
else
local realm = dataObj[2]
session.isWampEstablished = 1
session.realm = realm
redis:hmset("wiolaSession" .. regId, session)
redis:hmset("wiolaSessionFeatures" .. regId, dataObj[3])
if not redis:sismember("wiolaRealms",realm) then
ngx.log(ngx.DEBUG, "No realm ", realm, " found. Creating...")
redis:sadd("wiolaIds",regId)
end
redis:sadd("wiolaRealm" .. realm .. "Sessions", regId)
-- WAMP SPEC: [WELCOME, Session|id, Details|dict]
sendData(session, { WAMP_MSG_SPEC.WELCOME, regId, wamp_features })
end
elseif dataObj[1] == WAMP_MSG_SPEC.ABORT then -- WAMP SPEC:
-- No response is expected
elseif dataObj[1] == WAMP_MSG_SPEC.GOODBYE then -- WAMP SPEC: [GOODBYE, Details|dict, Reason|uri]
if session.isWampEstablished == 1 then
sendData(session, { WAMP_MSG_SPEC.GOODBYE, {}, "wamp.error.goodbye_and_out" })
else
sendData(session, { WAMP_MSG_SPEC.GOODBYE, {}, "wamp.error.system_shutdown" })
end
elseif dataObj[1] == WAMP_MSG_SPEC.ERROR then -- WAMP SPEC:
if session.isWampEstablished == 1 then
else
end
elseif dataObj[1] == WAMP_MSG_SPEC.PUBLISH then -- WAMP SPEC:
if session.isWampEstablished == 1 then
else
sendData(session, { WAMP_MSG_SPEC.GOODBYE, {}, "wamp.error.system_shutdown" })
end
elseif dataObj[1] == WAMP_MSG_SPEC.SUBSCRIBE then -- WAMP SPEC:
if session.isWampEstablished == 1 then
else
sendData(session, { WAMP_MSG_SPEC.GOODBYE, {}, "wamp.error.system_shutdown" })
end
elseif dataObj[1] == WAMP_MSG_SPEC.UNSUBSCRIBE then -- WAMP SPEC:
if session.isWampEstablished == 1 then
else
sendData(session, { WAMP_MSG_SPEC.GOODBYE, {}, "wamp.error.system_shutdown" })
end
elseif dataObj[1] == WAMP_MSG_SPEC.CALL then -- WAMP SPEC:
if session.isWampEstablished == 1 then
else
sendData(session, { WAMP_MSG_SPEC.GOODBYE, {}, "wamp.error.system_shutdown" })
end
elseif dataObj[1] == WAMP_MSG_SPEC.REGISTER then -- WAMP SPEC:
if session.isWampEstablished == 1 then
else
sendData(session, { WAMP_MSG_SPEC.GOODBYE, {}, "wamp.error.system_shutdown" })
end
elseif dataObj[1] == WAMP_MSG_SPEC.UNREGISTER then -- WAMP SPEC:
if session.isWampEstablished == 1 then
else
sendData(session, { WAMP_MSG_SPEC.GOODBYE, {}, "wamp.error.system_shutdown" })
end
elseif dataObj[1] == WAMP_MSG_SPEC.YIELD then -- WAMP SPEC:
if session.isWampEstablished == 1 then
else
sendData(session, { WAMP_MSG_SPEC.GOODBYE, {}, "wamp.error.system_shutdown" })
end
else
end
end
-- Retrieve data, available for session
function _M.getPendingData(regId)
return redis:lpop("wiolaSession" .. regId .. "Data")
end
return _M
|
--
-- Project: this project
-- User: kostik
-- Date: 16.03.14
--
local redisLib = require "resty.redis"
local redis = redisLib:new()
local ok, err = redis:connect("unix:/tmp/redis.sock")
if not ok then
ngx.say("failed to connect: ", err)
return
end
local _M = {
_VERSION = '0.1'
}
_M.__index = _M
local wamp_features = {
agent = "wiola/Lua v0.1",
roles = {
broker = {},
dealer = {}
}
}
local WAMP_MSG_SPEC = {
HELLO = 1,
WELCOME = 2,
ABORT = 3,
CHALLENGE = 4,
AUTHENTICATE = 5,
GOODBYE = 6,
HEARTBEAT = 7,
ERROR = 8,
PUBLISH = 16,
PUBLISHED = 17,
SUBSCRIBE = 32,
SUBSCRIBED = 33,
UNSUBSCRIBE = 34,
UNSUBSCRIBED = 35,
EVENT = 36,
CALL = 48,
CANCEL = 49,
RESULT = 50,
REGISTER = 64,
REGISTERED = 65,
UNREGISTER = 66,
UNREGISTERED = 67,
INVOCATION = 68,
INTERRUPT = 69,
YIELD = 70
}
local _cache = {
sessions = {},
publications = {},
subscriptions = {},
registrations = {},
ids = {},
requests = {},
realms = {}
}
-- Generate unique Id
local function getRegId()
local regId
math.randomseed( os.time() )
repeat
-- regId = math.random(9007199254740992)
regId = math.random(100000000000000)
until redis:sismember("wiolaIds",regId)
return regId
end
-- Validate uri for WAMP requirements
local function validateURI(uri)
-- var re = /^([0-9a-z_]{2,}\.)*([0-9a-z_]{2,})$/;
-- if(!re.test(uri) || uri.indexOf('wamp') === 0) {
-- return false;
-- } else {
-- return true;
-- }
end
-- Convert redis hgetall array to lua table
local function redisArr2table(ra)
local t = {}
local i = 1
while i < #ra do
t[ra[i]] = ra[i+1]
i = i + 2
end
return t
end
-- Add connection to wiola
function _M.addConnection(sid, wampProto)
local regId = getRegId()
local wProto, dataType
redis:sadd("wiolaIds",regId)
if wampProto == nil or wampProto == "" then
wampProto = 'wamp.2.json' -- Setting default protocol for encoding/decodig use
end
if wProto == 'wamp.2.msgpack' then
dataType = 'binary'
else
dataType = 'text'
end
local res, err = redis:hmset("wiolaSession" .. regId,
{ connId = sid,
sessId = regId,
isWampEstablished = 1,
-- realm = nil,
-- wamp_features = nil,
wamp_protocol = wampProto,
dataType = dataType }
)
ngx.log(ngx.DEBUG, "redis:hmset wiolaSessionKey: ", wiolaSessionKey, " Result: ", err)
return regId, dataType
end
-- Remove connection from wiola
function _M.removeConnection(regId)
local session = redisArr2table(redis:hgetall("wiolaSession" .. regId))
var_dump(session)
ngx.log(ngx.DEBUG, "Removing session: ", regId)
redis:srem("wiolaRealm" .. session.realm .. "Sessions",regId)
local rs = redis:scard("wiolaRealm" .. session.realm .. "Sessions")
if rs == 0 then
redis:del("wiolaRealm" .. session.realm .. "Sessions")
end
ngx.log(ngx.DEBUG, "Realm ", session.realm, " sessions count now is ", rs)
redis:del("wiolaSession" .. regId .. "Data")
redis:del("wiolaSessionFeatures" .. regId)
redis:del("wiolaSession" .. regId)
redis:srem("wiolaIds",regId)
end
-- Prepare data for sending to client
local function sendData(session, data)
local dataObj
if session.wamp_protocol == 'wamp.2.msgpack' then
local mp = require 'MessagePack'
dataObj = mp.pack(data)
else --if session.wamp_protocol == 'wamp.2.json'
local cjson = require "cjson"
dataObj = cjson.encode(data)
end
ngx.log(ngx.DEBUG, "Preparing data for client: ", dataObj);
redis:rpush("wiolaSession" .. session.sessId .. "Data", dataObj)
end
-- Receive data from client
function _M.receiveData(regId, data)
local session = redisArr2table(redis:hgetall("wiolaSession" .. regId))
local cjson = require "cjson"
local dataObj
-- var_dump(session)
if session.wamp_protocol == 'wamp.2.msgpack' then
local mp = require 'MessagePack'
dataObj = mp.unpack(data)
else --if session.wamp_protocol == 'wamp.2.json'
dataObj = cjson.decode(data)
end
ngx.log(ngx.DEBUG, "Cli regId: ", regId, " Received data decoded. WAMP msg Id: ", dataObj[1])
-- Analyze WAMP message ID received
if dataObj[1] == WAMP_MSG_SPEC.HELLO then -- WAMP SPEC: [HELLO, Realm|uri, Details|dict]
if session.isWampEstablished == 1 then
-- Protocol error: received second hello message - aborting
-- WAMP SPEC: [GOODBYE, Details|dict, Reason|uri]
sendData(session, { WAMP_MSG_SPEC.GOODBYE, {}, "wamp.error.system_shutdown" })
else
local realm = dataObj[2]
session.isWampEstablished = 1
session.realm = realm
redis:hmset("wiolaSession" .. regId, session)
redis:set("wiolaSessionFeatures" .. regId, cjson.encode(dataObj[3]))
if not redis:sismember("wiolaRealms",realm) then
ngx.log(ngx.DEBUG, "No realm ", realm, " found. Creating...")
redis:sadd("wiolaIds",regId)
end
redis:sadd("wiolaRealm" .. realm .. "Sessions", regId)
-- WAMP SPEC: [WELCOME, Session|id, Details|dict]
sendData(session, { WAMP_MSG_SPEC.WELCOME, regId, wamp_features })
end
elseif dataObj[1] == WAMP_MSG_SPEC.ABORT then -- WAMP SPEC:
-- No response is expected
elseif dataObj[1] == WAMP_MSG_SPEC.GOODBYE then -- WAMP SPEC: [GOODBYE, Details|dict, Reason|uri]
if session.isWampEstablished == 1 then
sendData(session, { WAMP_MSG_SPEC.GOODBYE, {}, "wamp.error.goodbye_and_out" })
else
sendData(session, { WAMP_MSG_SPEC.GOODBYE, {}, "wamp.error.system_shutdown" })
end
elseif dataObj[1] == WAMP_MSG_SPEC.ERROR then -- WAMP SPEC:
if session.isWampEstablished == 1 then
else
end
elseif dataObj[1] == WAMP_MSG_SPEC.PUBLISH then -- WAMP SPEC:
if session.isWampEstablished == 1 then
else
sendData(session, { WAMP_MSG_SPEC.GOODBYE, {}, "wamp.error.system_shutdown" })
end
elseif dataObj[1] == WAMP_MSG_SPEC.SUBSCRIBE then -- WAMP SPEC:
if session.isWampEstablished == 1 then
else
sendData(session, { WAMP_MSG_SPEC.GOODBYE, {}, "wamp.error.system_shutdown" })
end
elseif dataObj[1] == WAMP_MSG_SPEC.UNSUBSCRIBE then -- WAMP SPEC:
if session.isWampEstablished == 1 then
else
sendData(session, { WAMP_MSG_SPEC.GOODBYE, {}, "wamp.error.system_shutdown" })
end
elseif dataObj[1] == WAMP_MSG_SPEC.CALL then -- WAMP SPEC:
if session.isWampEstablished == 1 then
else
sendData(session, { WAMP_MSG_SPEC.GOODBYE, {}, "wamp.error.system_shutdown" })
end
elseif dataObj[1] == WAMP_MSG_SPEC.REGISTER then -- WAMP SPEC:
if session.isWampEstablished == 1 then
else
sendData(session, { WAMP_MSG_SPEC.GOODBYE, {}, "wamp.error.system_shutdown" })
end
elseif dataObj[1] == WAMP_MSG_SPEC.UNREGISTER then -- WAMP SPEC:
if session.isWampEstablished == 1 then
else
sendData(session, { WAMP_MSG_SPEC.GOODBYE, {}, "wamp.error.system_shutdown" })
end
elseif dataObj[1] == WAMP_MSG_SPEC.YIELD then -- WAMP SPEC:
if session.isWampEstablished == 1 then
else
sendData(session, { WAMP_MSG_SPEC.GOODBYE, {}, "wamp.error.system_shutdown" })
end
else
end
end
-- Retrieve data, available for session
function _M.getPendingData(regId)
return redis:lpop("wiolaSession" .. regId .. "Data")
end
return _M
|
Fixed client wamp features
|
Fixed client wamp features
|
Lua
|
bsd-2-clause
|
KSDaemon/wiola,KSDaemon/wiola,KSDaemon/wiola
|
a606cd90f3bf84a3d5dec5343b2d7e590a38b39f
|
modules/rpc/luasrc/controller/rpc.lua
|
modules/rpc/luasrc/controller/rpc.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local require = require
local pairs = pairs
local print = print
local pcall = pcall
local table = table
module "luci.controller.rpc"
function index()
local function authenticator(validator, accs)
local auth = luci.http.formvalue("auth", true)
if auth then
local user = luci.sauth.read(auth)
if user and luci.util.contains(accs, user) then
return user, auth
end
end
luci.http.status(403, "Forbidden")
end
if pcall(require, "luci.model.uci") then
uci = entry({"rpc", "uci"}, call("rpc_uci"))
uci.sysauth = "root"
uci.sysauth_authenticator = authenticator
end
fs = entry({"rpc", "fs"}, call("rpc_fs"))
fs.sysauth = "root"
fs.sysauth_authenticator = authenticator
sys = entry({"rpc", "sys"}, call("rpc_sys"))
sys.sysauth = "root"
sys.sysauth_authenticator = authenticator
if pcall(require, "luci.model.ipkg") then
fs = entry({"rpc", "ipkg"}, call("rpc_ipkg"))
fs.sysauth = "root"
fs.sysauth_authenticator = authenticator
end
uci = entry({"rpc", "auth"}, call("rpc_auth"))
end
function rpc_auth()
local jsonrpc = require "luci.jsonrpc"
local sauth = require "luci.sauth"
local http = require "luci.http"
local sys = require "luci.sys"
local ltn12 = require "luci.ltn12"
http.setfilehandler()
local loginstat
local server = {}
server.login = function(user, pass)
local sid
if sys.user.checkpasswd(user, pass) then
sid = sys.uniqueid(16)
http.header("Set-Cookie", "sysauth=" .. sid.."; path=/")
sauth.write(sid, user)
end
return sid
end
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(server, http.source()), http.write)
end
function rpc_uci()
local uci = require "luci.controller.rpc.uci"
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(uci, http.source()), http.write)
end
function rpc_fs()
local util = require "luci.util"
local io = require "io"
local fs2 = util.clone(require "luci.fs")
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
function fs2.readfile(filename)
local stat, mime = pcall(require, "mime")
if not stat then
error("Base64 support not available. Please install LuaSocket.")
end
local fp = io.open(filename)
if not fp then
return nil
end
local output = {}
local sink = ltn12.sink.table(output)
local source = ltn12.source.chain(ltn12.source.file(fp), mime.encode("base64"))
return ltn12.pump.all(source, sink) and table.concat(output)
end
function fs2.writefile(filename, data)
local stat, mime = pcall(require, "mime")
if not stat then
error("Base64 support not available. Please install LuaSocket.")
end
local file = io.open(filename, "w")
local sink = file and ltn12.sink.chain(mime.decode("base64"), ltn12.sink.file(file))
return sink and ltn12.pump.all(ltn12.source.string(data), sink) or false
end
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(fs2, http.source()), http.write)
end
function rpc_sys()
local sys = require "luci.sys"
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(sys, http.source()), http.write)
end
function rpc_ipkg()
local ipkg = require "luci.model.ipkg"
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(ipkg, http.source()), http.write)
end
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local require = require
local pairs = pairs
local print = print
local pcall = pcall
local table = table
module "luci.controller.rpc"
function index()
local function authenticator(validator, accs)
local auth = luci.http.formvalue("auth", true)
if auth then
local user = luci.sauth.read(auth)
if user and luci.util.contains(accs, user) then
return user, auth
end
end
luci.http.status(403, "Forbidden")
end
uci = entry({"rpc", "uci"}, call("rpc_uci"))
uci.sysauth = "root"
uci.sysauth_authenticator = authenticator
fs = entry({"rpc", "fs"}, call("rpc_fs"))
fs.sysauth = "root"
fs.sysauth_authenticator = authenticator
sys = entry({"rpc", "sys"}, call("rpc_sys"))
sys.sysauth = "root"
sys.sysauth_authenticator = authenticator
ipkg = entry({"rpc", "ipkg"}, call("rpc_ipkg"))
ipkg.sysauth = "root"
ipkg.sysauth_authenticator = authenticator
uci = entry({"rpc", "auth"}, call("rpc_auth"))
end
function rpc_auth()
local jsonrpc = require "luci.jsonrpc"
local sauth = require "luci.sauth"
local http = require "luci.http"
local sys = require "luci.sys"
local ltn12 = require "luci.ltn12"
http.setfilehandler()
local loginstat
local server = {}
server.login = function(user, pass)
local sid
if sys.user.checkpasswd(user, pass) then
sid = sys.uniqueid(16)
http.header("Set-Cookie", "sysauth=" .. sid.."; path=/")
sauth.write(sid, user)
end
return sid
end
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(server, http.source()), http.write)
end
function rpc_uci()
if not pcall(require, "luci.model.uci") then
luci.http.status(404, "Not Found")
return nil
end
local uci = require "luci.controller.rpc.uci"
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(uci, http.source()), http.write)
end
function rpc_fs()
local util = require "luci.util"
local io = require "io"
local fs2 = util.clone(require "luci.fs")
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
function fs2.readfile(filename)
local stat, mime = pcall(require, "mime")
if not stat then
error("Base64 support not available. Please install LuaSocket.")
end
local fp = io.open(filename)
if not fp then
return nil
end
local output = {}
local sink = ltn12.sink.table(output)
local source = ltn12.source.chain(ltn12.source.file(fp), mime.encode("base64"))
return ltn12.pump.all(source, sink) and table.concat(output)
end
function fs2.writefile(filename, data)
local stat, mime = pcall(require, "mime")
if not stat then
error("Base64 support not available. Please install LuaSocket.")
end
local file = io.open(filename, "w")
local sink = file and ltn12.sink.chain(mime.decode("base64"), ltn12.sink.file(file))
return sink and ltn12.pump.all(ltn12.source.string(data), sink) or false
end
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(fs2, http.source()), http.write)
end
function rpc_sys()
local sys = require "luci.sys"
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(sys, http.source()), http.write)
end
function rpc_ipkg()
if not pcall(require, "luci.model.ipkg") then
luci.http.status(404, "Not Found")
return nil
end
local ipkg = require "luci.model.ipkg"
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(ipkg, http.source()), http.write)
end
|
Fixed RPC-API
|
Fixed RPC-API
|
Lua
|
apache-2.0
|
deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci
|
c71ecb5e9f074f17d6e3f917f6b62dc6103ed570
|
src/playerAttack.lua
|
src/playerAttack.lua
|
local sound = require 'vendor/TEsound'
local Gamestate = require 'vendor/gamestate'
local Sprite = require 'nodes/sprite'
local Timer = require 'vendor/timer'
local Server = require 'server'
local server = Server.getSingleton()
local PlayerAttack = {}
PlayerAttack.__index = PlayerAttack
PlayerAttack.playerAttack = true
---
-- Create a new Player
-- @param collider
-- @return Player
function PlayerAttack.new(collider,plyr)
local attack = {}
setmetatable(attack, PlayerAttack)
attack.width = 5
attack.height = 5
attack.radius = 10
attack.collider = collider
attack.bb = collider:addCircle(plyr.position.x+attack.width/2,(plyr.position.y+28)+attack.height/2,attack.width,attack.radius)
attack.bb.node = attack
attack.damage = 1
attack.player = plyr
attack:deactivate()
return attack
end
function PlayerAttack:update()
local player = self.player
if player.character.direction=='right' then
self.bb:moveTo(player.position.x + 24 + 20, player.position.y+28)
else
self.bb:moveTo(player.position.x + 24 - 20, player.position.y+28)
end
end
function PlayerAttack:collide(node, dt, mtv_x, mtv_y)
if not node then return end
if self.dead then return end
--implement hug button action
if node.isPlayer then return end
local tlx,tly,brx,bry = self.bb:bbox()
local attackNode = { x = tlx, y = tly,
properties = {
sheet = 'images/attack.png',
height = 20, width = 20,
}
}
if node.hurt then
local msg = string.format("%s %s %s",self.player.id,"sound","punch")
server:sendtoplayer(msg,"*")
local attackSprite = Sprite.new(attackNode, collider)
attackSprite.id = Level.generateObjectId()
Gamestate.currentState().nodes[attackSprite] = attackSprite
Timer.add(0.1,function ()
Gamestate.currentState().nodes[attackSprite] = nil
end)
node:hurt(self.damage)
self:deactivate()
end
end
function PlayerAttack:activate()
self.dead = false
self.collider:setSolid(self.bb)
end
function PlayerAttack:deactivate()
self.dead = true
self.collider:setGhost(self.bb)
end
return PlayerAttack
|
local sound = require 'vendor/TEsound'
local Gamestate = require 'vendor/gamestate'
local Sprite = require 'nodes/sprite'
local Timer = require 'vendor/timer'
local Server = require 'server'
local server = Server.getSingleton()
local PlayerAttack = {}
PlayerAttack.__index = PlayerAttack
PlayerAttack.playerAttack = true
---
-- Create a new Player
-- @param collider
-- @return Player
function PlayerAttack.new(collider,plyr)
local attack = {}
setmetatable(attack, PlayerAttack)
attack.width = 5
attack.height = 5
attack.radius = 10
attack.collider = collider
attack.bb = collider:addCircle(plyr.position.x+attack.width/2,(plyr.position.y+28)+attack.height/2,attack.width,attack.radius)
attack.bb.node = attack
attack.damage = 1
attack.player = plyr
attack:deactivate()
return attack
end
function PlayerAttack:update()
local player = self.player
if player.character.direction=='right' then
self.bb:moveTo(player.position.x + 24 + 20, player.position.y+28)
else
self.bb:moveTo(player.position.x + 24 - 20, player.position.y+28)
end
end
function PlayerAttack:collide(node, dt, mtv_x, mtv_y)
if not node then return end
if self.dead then return end
--implement hug button action
if node.isPlayer then return end
local tlx,tly,brx,bry = self.bb:bbox()
local attackNode = { x = tlx, y = tly,
properties = {
sheet = 'images/attack.png',
height = 20, width = 20,
}
}
if node.hurt then
local msg = string.format("%s %s %s",self.player.id,"sound","punch")
server:sendtoplayer(msg,"*")
local attackSprite = Sprite.new(attackNode, collider)
attackSprite.id = require("level").generateObjectId()
local level = Gamestate.get(self.player.level)
level.nodes[attackSprite] = attackSprite
Timer.add(0.1,function ()
level.nodes[attackSprite] = nil
end)
node:hurt(self.damage)
self:deactivate()
end
end
function PlayerAttack:activate()
self.dead = false
self.collider:setSolid(self.bb)
end
function PlayerAttack:deactivate()
self.dead = true
self.collider:setGhost(self.bb)
end
return PlayerAttack
|
fixed punching error
|
fixed punching error
|
Lua
|
mit
|
hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua
|
fe9cfda22af00af2a87770df144a03cde6121628
|
config/nvim/lua/gb/statusline.lua
|
config/nvim/lua/gb/statusline.lua
|
local colors = {
bg = "#202328",
fg = "#bbc2cf",
yellow = "#fabd2f",
cyan = "#008080",
darkblue = "#081633",
green = "#98be65",
orange = "#FF8800",
violet = "#a9a1e1",
magenta = "#c678dd",
blue = "#51afef",
red = "#ec5f67",
white = "#e6e6e6"
}
local vi_mode_colors = {
NORMAL = colors.green,
INSERT = colors.blue,
VISUAL = colors.magenta,
OP = colors.green,
BLOCK = colors.red,
REPLACE = colors.violet,
["V-REPLACE"] = colors.violet,
ENTER = colors.cyan,
MORE = colors.cyan,
SELECT = colors.orange,
COMMAND = colors.green,
SHELL = colors.green,
TERM = colors.green,
NONE = colors.yellow
}
local lsp = require "feline.providers.lsp"
local vi_mode_utils = require "feline.providers.vi_mode"
-- Shows the current function in the file
-- require("nvim-gps").setup()
local comps = {
vi_mode = {
left = {
provider = "▊",
hl = function()
local val = {
name = vi_mode_utils.get_mode_highlight_name(),
fg = vi_mode_utils.get_mode_color()
}
return val
end,
right_sep = " "
},
right = {
provider = "▊",
hl = function()
local val = {
name = vi_mode_utils.get_mode_highlight_name(),
fg = vi_mode_utils.get_mode_color()
}
return val
end,
left_sep = " "
}
},
line_number = {
provider = function()
return vim.api.nvim_eval("printf('%03d/%03d', line('.'), line('$'))")
end,
left_sep = {
" ",
"left_rounded_thin",
hl = {bg = colors.white, fg = colors.white}
},
right_sep = {
"right_rounded_thin",
" ",
{
hl = {fg = colors.white}
}
}
},
file = {
info = {
provider = "file_info",
hl = {
fg = colors.white,
bg = "oceanblue",
style = "bold"
},
icon = "",
file_modified_icon = "",
left_sep = {
" ",
"slant_left_2",
{hl = {bg = "oceanblue", fg = "NONE"}}
},
right_sep = {"slant_right_2", " "}
},
encoding = {
provider = "file_encoding",
left_sep = " ",
hl = {
fg = colors.violet,
style = "bold"
}
},
type = {
provider = "file_type"
}
},
line_percentage = {
provider = "line_percentage",
left_sep = " "
},
scroll_bar = {
provider = "scroll_bar",
left_sep = " ",
hl = {
fg = colors.blue,
style = "bold"
}
},
diagnos = {
err = {
provider = "diagnostic_errors",
enabled = function()
return lsp.diagnostics_exist("Error")
end,
hl = {
fg = colors.red
}
},
warn = {
provider = "diagnostic_warnings",
enabled = function()
return lsp.diagnostics_exist("Warning")
end,
hl = {
fg = colors.yellow
}
},
hint = {
provider = "diagnostic_hints",
enabled = function()
return lsp.diagnostics_exist("Hint")
end,
hl = {
fg = colors.cyan
}
},
info = {
provider = "diagnostic_info",
enabled = function()
return lsp.diagnostics_exist("Information")
end,
hl = {
fg = colors.blue
}
}
},
lsp = {
name = {
provider = "lsp_client_names",
left_sep = " ",
icon = " ",
hl = {
fg = colors.yellow,
style = "bold"
}
}
},
git = {
branch = {
provider = "git_branch",
icon = " ",
left_sep = " ",
hl = {
fg = colors.violet,
style = "bold"
},
right_sep = " "
}
}
-- nvim_gps = {
-- left_sep = " ",
-- provider = function()
-- return require("nvim-gps").get_location()
-- end,
-- enabled = function()
-- return require("nvim-gps").is_available()
-- end
-- }
}
local properties = {
force_inactive = {
filetypes = {
"NvimTree",
"dbui",
"vim-plug",
"startify",
"fugitive",
"fugitiveblame"
},
buftypes = {"terminal"},
bufnames = {}
}
}
local components = {
active = {},
inactive = {}
}
table.insert(components.active, {})
table.insert(components.active, {})
table.insert(components.inactive, {})
components.active[1] = {
comps.vi_mode.left,
comps.git.branch,
comps.file.info,
comps.lsp.name,
comps.diagnos.err,
comps.diagnos.warn,
comps.diagnos.hint,
comps.diagnos.info,
comps.nvim_gps
}
components.active[2] = {
comps.file.encoding,
comps.line_percentage,
comps.line_number,
comps.scroll_bar,
comps.vi_mode.right
}
components.inactive[1] = {comps.file.info}
-- Built in separators {{{
-- vertical_bar '┃'
-- vertical_bar_thin '│'
-- left ''
-- right ''
-- block '█'
-- left_filled ''
-- right_filled ''
-- slant_left ''
-- slant_left_thin ''
-- slant_right ''
-- slant_right_thin ''
-- slant_left_2 ''
-- slant_left_2_thin ''
-- slant_right_2 ''
-- slant_right_2_thin ''
-- left_rounded ''
-- left_rounded_thin ''
-- right_rounded ''
-- right_rounded_thin ''
-- circle '●'
-- }}}
-- modified ''
require "feline".setup {
default_bg = colors.bg,
default_fg = colors.fg,
components = components,
properties = properties,
vi_mode_colors = vi_mode_colors
}
|
local colors = {
bg = "#202328",
fg = "#bbc2cf",
yellow = "#fabd2f",
cyan = "#008080",
darkblue = "#081633",
green = "#98be65",
orange = "#FF8800",
violet = "#a9a1e1",
magenta = "#c678dd",
blue = "#51afef",
red = "#ec5f67",
white = "#e6e6e6"
}
local vi_mode_colors = {
NORMAL = colors.green,
INSERT = colors.blue,
VISUAL = colors.magenta,
OP = colors.green,
BLOCK = colors.red,
REPLACE = colors.violet,
["V-REPLACE"] = colors.violet,
ENTER = colors.cyan,
MORE = colors.cyan,
SELECT = colors.orange,
COMMAND = colors.green,
SHELL = colors.green,
TERM = colors.green,
NONE = colors.yellow
}
local lsp = require "feline.providers.lsp"
local vi_mode_utils = require "feline.providers.vi_mode"
-- Shows the current function in the file
-- require("nvim-gps").setup()
local comps = {
vi_mode = {
left = {
provider = "▊",
hl = function()
local val = {
name = vi_mode_utils.get_mode_highlight_name(),
fg = vi_mode_utils.get_mode_color()
}
return val
end,
right_sep = " "
},
right = {
provider = "▊",
hl = function()
local val = {
name = vi_mode_utils.get_mode_highlight_name(),
fg = vi_mode_utils.get_mode_color()
}
return val
end,
left_sep = " "
}
},
line_number = {
provider = function()
return vim.api.nvim_eval("printf('%03d/%03d', line('.'), line('$'))")
end,
left_sep = {
" ",
"left_rounded_thin",
hl = {bg = colors.white, fg = colors.white}
},
right_sep = {
"right_rounded_thin",
" ",
{
hl = {fg = colors.white}
}
}
},
file = {
info = {
provider = "file_info",
hl = {
fg = colors.white,
bg = "oceanblue",
style = "bold"
},
icon = "",
file_modified_icon = "",
left_sep = {
" ",
"slant_left_2",
{hl = {bg = "oceanblue", fg = "NONE"}}
},
right_sep = {"slant_right_2", " "}
},
encoding = {
provider = "file_encoding",
left_sep = " ",
hl = {
fg = colors.violet,
style = "bold"
}
},
type = {
provider = "file_type"
}
},
line_percentage = {
provider = "line_percentage",
left_sep = " "
},
scroll_bar = {
provider = "scroll_bar",
left_sep = " ",
hl = {
fg = colors.blue,
style = "bold"
}
},
diagnos = {
err = {
provider = "diagnostic_errors",
enabled = function()
return lsp.diagnostics_exist("Error")
end,
hl = {
fg = colors.red
}
},
warn = {
provider = "diagnostic_warnings",
enabled = function()
return lsp.diagnostics_exist("Warning")
end,
hl = {
fg = colors.yellow
}
},
hint = {
provider = "diagnostic_hints",
enabled = function()
return lsp.diagnostics_exist("Hint")
end,
hl = {
fg = colors.cyan
}
},
info = {
provider = "diagnostic_info",
enabled = function()
return lsp.diagnostics_exist("Information")
end,
hl = {
fg = colors.blue
}
}
},
lsp = {
name = {
provider = "lsp_client_names",
left_sep = " ",
icon = " ",
hl = {
fg = colors.yellow,
style = "bold"
}
}
},
git = {
branch = {
provider = "git_branch",
icon = " ",
left_sep = " ",
hl = {
fg = colors.violet,
style = "bold"
},
right_sep = " "
}
}
-- nvim_gps = {
-- left_sep = " ",
-- provider = function()
-- return require("nvim-gps").get_location()
-- end,
-- enabled = function()
-- return require("nvim-gps").is_available()
-- end
-- }
}
local components = {
active = {},
inactive = {}
}
table.insert(components.active, {})
table.insert(components.active, {})
table.insert(components.inactive, {})
components.active[1] = {
comps.vi_mode.left,
comps.git.branch,
comps.file.info,
comps.lsp.name,
comps.diagnos.err,
comps.diagnos.warn,
comps.diagnos.hint,
comps.diagnos.info,
comps.nvim_gps
}
components.active[2] = {
comps.file.encoding,
comps.line_percentage,
comps.line_number,
comps.scroll_bar,
comps.vi_mode.right
}
components.inactive[1] = {comps.file.info}
-- Built in separators {{{
-- vertical_bar '┃'
-- vertical_bar_thin '│'
-- left ''
-- right ''
-- block '█'
-- left_filled ''
-- right_filled ''
-- slant_left ''
-- slant_left_thin ''
-- slant_right ''
-- slant_right_thin ''
-- slant_left_2 ''
-- slant_left_2_thin ''
-- slant_right_2 ''
-- slant_right_2_thin ''
-- left_rounded ''
-- left_rounded_thin ''
-- right_rounded ''
-- right_rounded_thin ''
-- circle '●'
-- }}}
-- modified ''
require "feline".setup {
bg = colors.bg,
fg = colors.fg,
components = components,
force_inactive = {
filetypes = {
"NvimTree",
"dbui",
"vim-plug",
"startify",
"fugitive",
"fugitiveblame"
},
buftypes = {"terminal"},
bufnames = {}
},
vi_mode_colors = vi_mode_colors
}
|
Fixup feline
|
Fixup feline
|
Lua
|
mit
|
gblock0/dotfiles
|
3236bcc260ca9ce3b7c769b14a40a2e2fa5549f6
|
MMOCoreORB/bin/conf/config.lua
|
MMOCoreORB/bin/conf/config.lua
|
--Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
-- Core3 Config File
-- 0 = false, 1 = true
MakeLogin = 1
MakeZone = 1
MakePing = 1
MakeStatus = 1
MakeWeb = 1
ORB = ""
DBHost = "127.0.0.1"
DBPort = 3306
DBName = "swgemu"
DBUser = "swgemu"
DBPass = "123456"
LoginPort = 44453
LoginProcessingThreads = 1
LoginAllowedConnections = 3000
LoginRequiredVersion = "20050408-18:00"
MantisHost = "127.0.0.1"
MantisPort = 3306
MantisName = "swgemu"
MantisUser = "swgemu"
MantisPass = "123456"
MantisPrfx = "mantis_" -- The prefix for your mantis tables.
AutoReg = 1
PingPort = 44462
PingAllowedConnections = 3000
ZoneProcessingThreads = 10
ZoneAllowedConnections = 30000
ZoneGalaxyID = 2 --The actual zone server's galaxyID. Should coordinate with your login server.
ZoneOnlineCharactersPerAccount = 2 --How many characters are allowed online from a single account.
-- directory of tres with live.cfg
TrePath = "/home/kyle/workspace/cpp/SWGEmu"
TreFiles = {
"default_patch.tre",
"patch_sku1_14_00.tre",
"patch_14_00.tre",
"patch_sku1_13_00.tre",
"patch_13_00.tre",
"patch_sku1_12_00.tre",
"patch_12_00.tre",
"patch_11_03.tre",
"data_sku1_07.tre",
"patch_11_02.tre",
"data_sku1_06.tre",
"patch_11_01.tre",
"patch_11_00.tre",
"data_sku1_05.tre",
"data_sku1_04.tre",
"data_sku1_03.tre",
"data_sku1_02.tre",
"data_sku1_01.tre",
"data_sku1_00.tre",
"patch_10.tre",
"patch_09.tre",
"patch_08.tre",
"patch_07.tre",
"patch_06.tre",
"patch_05.tre",
"patch_04.tre",
"patch_03.tre",
"patch_02.tre",
"patch_01.tre",
"patch_00.tre",
"data_other_00.tre",
"data_static_mesh_01.tre",
"data_static_mesh_00.tre",
"data_texture_07.tre",
"data_texture_06.tre",
"data_texture_05.tre",
"data_texture_04.tre",
"data_texture_03.tre",
"data_texture_02.tre",
"data_texture_01.tre",
"data_texture_00.tre",
"data_skeletal_mesh_01.tre",
"data_skeletal_mesh_00.tre",
"data_animation_00.tre",
"data_sample_04.tre",
"data_sample_03.tre",
"data_sample_02.tre",
"data_sample_01.tre",
"data_sample_00.tre",
"data_music_00.tre",
"bottom.tre"
}
--Status Server Config
StatusPort = 44455
StatusAllowedConnections = 500
StatusInterval = 30 -- interval to check if zone is locked up (in seconds)
--Web Server Config
WebPort = 44460
|
--Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
-- Core3 Config File
-- 0 = false, 1 = true
MakeLogin = 1
MakeZone = 1
MakePing = 1
MakeStatus = 1
MakeWeb = 0
ORB = ""
DBHost = "127.0.0.1"
DBPort = 3306
DBName = "swgemu"
DBUser = "swgemu"
DBPass = "123456"
LoginPort = 44453
LoginProcessingThreads = 1
LoginAllowedConnections = 3000
LoginRequiredVersion = "20050408-18:00"
MantisHost = "127.0.0.1"
MantisPort = 3306
MantisName = "swgemu"
MantisUser = "swgemu"
MantisPass = "123456"
MantisPrfx = "mantis_" -- The prefix for your mantis tables.
AutoReg = 1
PingPort = 44462
PingAllowedConnections = 3000
ZoneProcessingThreads = 10
ZoneAllowedConnections = 30000
ZoneGalaxyID = 2 --The actual zone server's galaxyID. Should coordinate with your login server.
ZoneOnlineCharactersPerAccount = 2 --How many characters are allowed online from a single account.
--The following zones are enabled, and will be loaded with server start.
--To save on RAM and CPU usage, you should only enable the zones you need.
--In order to disable a zone, all you have to do is comment it out.
ZonesEnabled = {
--"09",
--"10",
--"11",
--"character_farm",
--"cinco_city_test_m5",
"corellia",
--"creature_test",
"dantooine",
"dathomir",
"dungeon1",
"endor",
--"endor_asommers",
--"floratest",
"godclient_test",
"lok",
"naboo",
--"otoh_gunga",
--"rivertest",
"rori",
--"runtimerules",
--"simple"
--"space_09",
"space_corellia",
"space_corellia_2",
"space_dantooine",
"space_dathomir",
"space_endor",
--"space_env",
--"space_halos",
--"space_heavy1",
--"space_light1",
"space_lok",
"space_naboo",
"space_naboo_2",
"space_tatooine",
"space_tatooine_2",
"space_yavin4",
--"taanab",
"talus",
"tatooine",
--"test_wearables",
"tutorial",
--"umbra",
--"watertabletest",
"yavin4"
}
-- directory of tres with live.cfg
TrePath = "/home/kyle/workspace/cpp/SWGEmu"
TreFiles = {
"default_patch.tre",
"patch_sku1_14_00.tre",
"patch_14_00.tre",
"patch_sku1_13_00.tre",
"patch_13_00.tre",
"patch_sku1_12_00.tre",
"patch_12_00.tre",
"patch_11_03.tre",
"data_sku1_07.tre",
"patch_11_02.tre",
"data_sku1_06.tre",
"patch_11_01.tre",
"patch_11_00.tre",
"data_sku1_05.tre",
"data_sku1_04.tre",
"data_sku1_03.tre",
"data_sku1_02.tre",
"data_sku1_01.tre",
"data_sku1_00.tre",
"patch_10.tre",
"patch_09.tre",
"patch_08.tre",
"patch_07.tre",
"patch_06.tre",
"patch_05.tre",
"patch_04.tre",
"patch_03.tre",
"patch_02.tre",
"patch_01.tre",
"patch_00.tre",
"data_other_00.tre",
"data_static_mesh_01.tre",
"data_static_mesh_00.tre",
"data_texture_07.tre",
"data_texture_06.tre",
"data_texture_05.tre",
"data_texture_04.tre",
"data_texture_03.tre",
"data_texture_02.tre",
"data_texture_01.tre",
"data_texture_00.tre",
"data_skeletal_mesh_01.tre",
"data_skeletal_mesh_00.tre",
"data_animation_00.tre",
"data_sample_04.tre",
"data_sample_03.tre",
"data_sample_02.tre",
"data_sample_01.tre",
"data_sample_00.tre",
"data_music_00.tre",
"bottom.tre"
}
--Status Server Config
StatusPort = 44455
StatusAllowedConnections = 500
StatusInterval = 30 -- interval to check if zone is locked up (in seconds)
--Web Server Config
WebPort = 44460
|
[Fixed] Config blunder
|
[Fixed] Config blunder
git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@3077 c3d1530f-68f5-4bd0-87dc-8ef779617e40
|
Lua
|
agpl-3.0
|
lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
|
69c42e1908f293498733eb5fa433f8742a513deb
|
tests/fibonacci.lua
|
tests/fibonacci.lua
|
--
-- FIBONACCI.LUA Copyright (c) 2007-08, Asko Kauppi <[email protected]>
--
-- Parallel calculation of Fibonacci numbers
--
-- A sample of task splitting like Intel TBB library does.
--
-- References:
-- Intel Threading Building Blocks, 'test all'
-- <http://shareit.intel.com/WikiHome/Articles/111111316>
--
-- Need to say it's 'local' so it can be an upvalue
--
local lanes = require "lanes"
lanes.configure{ nb_keepers =1, with_timers = false}
local function WR(str)
io.stderr:write( str.."\n" )
end
-- Threshold for serial calculation (optimal depends on multithreading fixed
-- cost and is system specific)
--
local KNOWN= { [0]=0, 1,1,2,3,5,8,13,21,34,55,89,144 }
--
-- uint= fib( n_uint )
--
local function fib( n )
--local lanes = require"lanes".configure()
--
local sum
local floor= assert(math.floor)
WR( "fib("..n..")" )
if n <= #KNOWN then
sum= KNOWN[n]
else
-- Splits into two; this task remains waiting for the results
--
-- note that lanes is pulled in by upvalue, so we need lanes.core to be available
-- the other solution is to require "lanes" from inside the lane body, as in:
-- local lanes = require"lanes".configure()
-- local gen_f= lanes.gen( "*", fib)
local gen_f= lanes.gen( "*", {required={"lanes.core"}}, fib)
local n1=floor(n/2) +1
local n2=floor(n/2) -1 + n%2
WR( "splitting "..n.." -> "..n1.." "..n2 )
local a= gen_f( n1 )
local b= gen_f( n2 )
-- children running...
local a2= a[1]^2
local b2= b[1]^2
sum = (n%2==1) and a2+b2 or a2-b2
end
io.stderr:write( "fib("..n..") = "..sum.."\n" )
return sum
end
--
-- Right answers from: <http://sonic.net/~douglasi/fibo.htm>
--
local right=
{
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711,
28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887,
9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437,
701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049, 12586269025, 20365011074,
32951280099, 53316291173, 86267571272, 139583862445, 225851433717, 365435296162, 591286729879,
956722026041, 1548008755920, 2504730781961, 4052739537881, 6557470319842, 10610209857723,
17167680177565, 27777890035288, 44945570212853, 72723460248141, 117669030460994, 190392490709135,
308061521170129, 498454011879264, 806515533049393, 1304969544928657, 2111485077978050,
3416454622906707, 5527939700884757, 8944394323791464, 14472334024676220, 23416728348467684,
37889062373143900, 61305790721611580, 99194853094755490, 160500643816367070, 259695496911122560,
420196140727489660, 679891637638612200, 1100087778366101900, 1779979416004714000,
2880067194370816000, 4660046610375530000, 7540113804746346000, 12200160415121877000,
19740274219868226000, 31940434634990105000, 51680708854858334000, 83621143489848440000,
135301852344706780000, 218922995834555200000
}
assert( #right==99 )
local N= 80
local res= fib(N)
print( right[N], res )
-- assert( res==right[N] ) -- can't guarantee such a large number will match exactly
|
--
-- FIBONACCI.LUA Copyright (c) 2007-08, Asko Kauppi <[email protected]>
--
-- Parallel calculation of Fibonacci numbers
--
-- A sample of task splitting like Intel TBB library does.
--
-- References:
-- Intel Threading Building Blocks, 'test all'
-- <http://shareit.intel.com/WikiHome/Articles/111111316>
--
-- Need to say it's 'local' so it can be an upvalue
--
local lanes = require "lanes"
lanes.configure{ nb_keepers =1, with_timers = false}
local function WR(str)
io.stderr:write( str.."\n" )
end
-- Threshold for serial calculation (optimal depends on multithreading fixed
-- cost and is system specific)
--
local KNOWN= { [0]=0, 1,1,2,3,5,8,13,21,34,55,89,144 }
-- dummy function so that we don't error when fib() is launched from the master state
set_debug_threadname = function ( ...)
end
--
-- uint= fib( n_uint )
--
local function fib( n )
set_debug_threadname( "fib(" .. n .. ")")
local lanes = require"lanes".configure()
--
local sum
local floor= assert(math.floor)
WR( "fib("..n..")" )
if n <= #KNOWN then
sum= KNOWN[n]
else
-- Splits into two; this task remains waiting for the results
--
local gen_f= lanes.gen( "*", fib)
local n1=floor(n/2) +1
local n2=floor(n/2) -1 + n%2
WR( "splitting "..n.." -> "..n1.." "..n2 )
local a= gen_f( n1 )
local b= gen_f( n2 )
-- children running...
local a2= a[1]^2
local b2= b[1]^2
sum = (n%2==1) and a2+b2 or a2-b2
end
io.stderr:write( "fib("..n..") = "..sum.."\n" )
return sum
end
--
-- Right answers from: <http://sonic.net/~douglasi/fibo.htm>
--
local right=
{
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711,
28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887,
9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437,
701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049, 12586269025, 20365011074,
32951280099, 53316291173, 86267571272, 139583862445, 225851433717, 365435296162, 591286729879,
956722026041, 1548008755920, 2504730781961, 4052739537881, 6557470319842, 10610209857723,
17167680177565, 27777890035288, 44945570212853, 72723460248141, 117669030460994, 190392490709135,
308061521170129, 498454011879264, 806515533049393, 1304969544928657, 2111485077978050,
3416454622906707, 5527939700884757, 8944394323791464, 14472334024676220, 23416728348467684,
37889062373143900, 61305790721611580, 99194853094755490, 160500643816367070, 259695496911122560,
420196140727489660, 679891637638612200, 1100087778366101900, 1779979416004714000,
2880067194370816000, 4660046610375530000, 7540113804746346000, 12200160415121877000,
19740274219868226000, 31940434634990105000, 51680708854858334000, 83621143489848440000,
135301852344706780000, 218922995834555200000
}
assert( #right==99 )
local N= 80
local res= fib(N)
print( right[N], res )
-- assert( res==right[N] ) -- can't guarantee such a large number will match exactly
|
Update fibonacci.lua
|
Update fibonacci.lua
Fix issue #61.
Pulling lanes as an upvalue is not a good idea after all, due to the fact that lanes.core changes its public API when lanes.core.configure() is called.
|
Lua
|
mit
|
aryajur/lanes,aryajur/lanes
|
e489433123b727d8e990f6ee78be81c6e71ea7f9
|
lua/wire/wire_paths.lua
|
lua/wire/wire_paths.lua
|
-- wire_paths.lua
--
-- This file implements syncing of wire paths, which are the visual
-- component of wires.
--
-- Conceptually, a wire path has a material, a color, and a non-zero width, as
-- well as as a non-empty polyline along the wire. (Each point in the line
-- has both a parent entity, and a local offset from that entity.)
--
if not WireLib then return end
WireLib.Paths = {}
local transmit_queues = setmetatable({}, { __index = function(t,p) t[p] = {} return t[p] end })
if CLIENT then
net.Receive("WireLib.Paths.TransmitPath", function(length)
local path = {
Path = {}
}
path.Entity = net.ReadEntity()
if not path.Entity:IsValid() then return end
path.Name = net.ReadString()
path.Width = net.ReadFloat()
if path.Width<=0 then
if path.Entity.WirePaths then
path.Entity.WirePaths[path.Name] = nil
if not next(path.Entity.WirePaths) then path.Entity.WirePaths = nil end
end
return
end
path.StartPos = net.ReadVector()
path.Material = net.ReadString()
path.Color = net.ReadColor()
local num_points = net.ReadUInt(16)
for i = 1, num_points do
path.Path[i] = { Entity = net.ReadEntity(), Pos = net.ReadVector() }
end
if path.Entity.WirePaths == nil then path.Entity.WirePaths = {} end
path.Entity.WirePaths[path.Name] = path
end)
hook.Add("NetworkEntityCreated", "WireLib.Paths.NetworkEntityCreated", function(ent)
if ent.Inputs then
net.Start("WireLib.Paths.RequestPaths")
net.WriteEntity(ent)
net.SendToServer()
end
end)
return
end
util.AddNetworkString("WireLib.Paths.RequestPaths")
util.AddNetworkString("WireLib.Paths.TransmitPath")
net.Receive("WireLib.Paths.RequestPaths", function(length, ply)
local ent = net.ReadEntity()
if ent:IsValid() and ent.Inputs then
for name, input in pairs(ent.Inputs) do
if input.Src then
WireLib.Paths.Add(path, ply)
end
end
end
end)
local function TransmitPath(input, ply)
net.Start("WireLib.Paths.TransmitPath")
local color = input.Color
net.WriteEntity(input.Entity)
net.WriteString(input.Name)
if not input.Src or input.Width<=0 then net.WriteFloat(0) return end
net.WriteFloat(input.Width)
net.WriteVector(input.StartPos)
net.WriteString(input.Material)
net.WriteColor(Color(color.r or 255, color.g or 255, color.b or 255, color.a or 255))
net.WriteUInt(#input.Path, 16)
for _, point in ipairs(input.Path) do
net.WriteEntity(point.Entity)
net.WriteVector(point.Pos)
end
net.Send(ply)
end
local function ProcessQueue()
for ply, queue in pairs(transmit_queues) do
if not ply:IsValid() then transmit_queues[ply] = nil continue end
local nextinqueue = table.remove(queue, 1)
if nextinqueue then
TransmitPath(nextinqueue, ply)
else
transmit_queues[ply] = nil
end
end
if not next(transmit_queues) then
timer.Remove("WireLib.Paths.ProcessQueue")
end
end
-- Add a path to every player's transmit queue
function WireLib.Paths.Add(input, ply)
if ply then
table.insert(transmit_queues[ply], input)
else
for _, player in pairs(player.GetAll()) do
table.insert(transmit_queues[player], input)
end
end
if not timer.Exists("WireLib.Paths.ProcessQueue") then
timer.Create("WireLib.Paths.ProcessQueue", 0, 0, ProcessQueue)
end
end
|
-- wire_paths.lua
--
-- This file implements syncing of wire paths, which are the visual
-- component of wires.
--
-- Conceptually, a wire path has a material, a color, and a non-zero width, as
-- well as as a non-empty polyline along the wire. (Each point in the line
-- has both a parent entity, and a local offset from that entity.)
--
if not WireLib then return end
WireLib.Paths = {}
local transmit_queues = setmetatable({}, { __index = function(t,p) t[p] = {} return t[p] end })
if CLIENT then
net.Receive("WireLib.Paths.TransmitPath", function(length)
local path = {
Path = {}
}
path.Entity = net.ReadEntity()
if not path.Entity:IsValid() then return end
path.Name = net.ReadString()
path.Width = net.ReadFloat()
if path.Width<=0 then
if path.Entity.WirePaths then
path.Entity.WirePaths[path.Name] = nil
if not next(path.Entity.WirePaths) then path.Entity.WirePaths = nil end
end
return
end
path.StartPos = net.ReadVector()
path.Material = net.ReadString()
path.Color = net.ReadColor()
local num_points = net.ReadUInt(16)
for i = 1, num_points do
path.Path[i] = { Entity = net.ReadEntity(), Pos = net.ReadVector() }
end
if path.Entity.WirePaths == nil then path.Entity.WirePaths = {} end
path.Entity.WirePaths[path.Name] = path
end)
return
end
util.AddNetworkString("WireLib.Paths.RequestPaths")
util.AddNetworkString("WireLib.Paths.TransmitPath")
net.Receive("WireLib.Paths.RequestPaths", function(length, ply)
local ent = net.ReadEntity()
if ent:IsValid() and ent.Inputs then
for name, input in pairs(ent.Inputs) do
if input.Src then
WireLib.Paths.Add(input, ply)
end
end
end
end)
local function TransmitPath(input, ply)
net.Start("WireLib.Paths.TransmitPath")
local color = input.Color
net.WriteEntity(input.Entity)
net.WriteString(input.Name)
if not input.Src or input.Width<=0 then net.WriteFloat(0) return end
net.WriteFloat(input.Width)
net.WriteVector(input.StartPos)
net.WriteString(input.Material)
net.WriteColor(Color(color.r or 255, color.g or 255, color.b or 255, color.a or 255))
net.WriteUInt(#input.Path, 16)
for _, point in ipairs(input.Path) do
net.WriteEntity(point.Entity)
net.WriteVector(point.Pos)
end
net.Send(ply)
end
local function ProcessQueue()
for ply, queue in pairs(transmit_queues) do
if not ply:IsValid() then transmit_queues[ply] = nil continue end
local nextinqueue = table.remove(queue, 1)
if nextinqueue then
TransmitPath(nextinqueue, ply)
else
transmit_queues[ply] = nil
end
end
if not next(transmit_queues) then
timer.Remove("WireLib.Paths.ProcessQueue")
end
end
-- Add a path to every player's transmit queue
function WireLib.Paths.Add(input, ply)
if ply then
table.insert(transmit_queues[ply], input)
else
for _, player in pairs(player.GetAll()) do
table.insert(transmit_queues[player], input)
end
end
if not timer.Exists("WireLib.Paths.ProcessQueue") then
timer.Create("WireLib.Paths.ProcessQueue", 0, 0, ProcessQueue)
end
end
|
Fix wires not appearing on player join
|
Fix wires not appearing on player join
|
Lua
|
apache-2.0
|
dvdvideo1234/wire,Grocel/wire,garrysmodlua/wire,NezzKryptic/Wire,wiremod/wire,sammyt291/wire
|
7e5c3dad26af1fd00b5bdce6361a317ac0f71124
|
mod_statsd/mod_statsd.lua
|
mod_statsd/mod_statsd.lua
|
-- Log common stats to statsd
--
-- Copyright (C) 2014 Daurnimator
--
-- This module is MIT/X11 licensed.
local socket = require "socket"
local iterators = require "util.iterators"
local jid = require "util.jid"
local options = module:get_option("statsd") or {}
-- Create UDP socket to statsd server
local sock = socket.udp()
sock:setpeername(options.hostname or "127.0.0.1", options.port or 8125)
-- Metrics are namespaced by ".", and seperated by newline
function clean(s) return (s:gsub("[%.:\n]", "_")) end
-- A 'safer' send function to expose
function send(s) return sock:send(s) end
-- prefix should end in "."
local prefix = (options.prefix or ("prosody." .. clean(module.host))) .. "."
-- Track users as they bind/unbind
-- count bare sessions every time, as we have no way to tell if it's a new bare session or not
module:hook("resource-bind", function(event)
send(prefix.."bare_sessions:"..iterators.count(bare_sessions).."|g")
send(prefix.."full_sessions:+1|g")
end, 1)
module:hook("resource-unbind", function(event)
send(prefix.."bare_sessions:"..iterators.count(bare_sessions).."|g")
send(prefix.."full_sessions:-1|g")
end, 1)
-- Track MUC occupants as they join/leave
module:hook("muc-occupant-joined", function(event)
send(prefix.."n_occupants:+1|g")
local room_node = jid.split(event.room.jid)
send(prefix..clean(room_node)..".occupants:+1|g")
end)
module:hook("muc-occupant-left", function(event)
send(prefix.."n_occupants:-1|g")
local room_node = jid.split(event.room.jid)
send(prefix..clean(room_node)..".occupants:-1|g")
end)
-- Misc other MUC
module:hook("muc-broadcast-message", function(event)
send(prefix.."broadcast-message:1|c")
local room_node = jid.split(event.room.jid)
send(prefix..clean(room_node)..".broadcast-message:1|c")
end)
module:hook("muc-invite", function(event)
send(prefix.."invite:1|c")
local room_node = jid.split(event.room.jid)
send(prefix..clean(room_node)..".invite:1|c")
local to_node, to_host, to_resource = jid.split(event.stanza.attr.to)
send(prefix..clean(to_node)..".invites:1|c")
end)
|
-- Log common stats to statsd
--
-- Copyright (C) 2014 Daurnimator
--
-- This module is MIT/X11 licensed.
local socket = require "socket"
local iterators = require "util.iterators"
local jid = require "util.jid"
local options = module:get_option("statsd") or {}
-- Create UDP socket to statsd server
local sock = socket.udp()
sock:setpeername(options.hostname or "127.0.0.1", options.port or 8125)
-- Metrics are namespaced by ".", and seperated by newline
function clean(s) return (s:gsub("[%.:\n]", "_")) end
-- A 'safer' send function to expose
function send(s) return sock:send(s) end
-- prefix should end in "."
local prefix = (options.prefix or "prosody") .. "."
if not options.no_host then
prefix = prefix .. clean(module.host) .. "."
end
-- Track users as they bind/unbind
-- count bare sessions every time, as we have no way to tell if it's a new bare session or not
module:hook("resource-bind", function(event)
send(prefix.."bare_sessions:"..iterators.count(bare_sessions).."|g")
send(prefix.."full_sessions:+1|g")
end, 1)
module:hook("resource-unbind", function(event)
send(prefix.."bare_sessions:"..iterators.count(bare_sessions).."|g")
send(prefix.."full_sessions:-1|g")
end, 1)
-- Track MUC occupants as they join/leave
module:hook("muc-occupant-joined", function(event)
send(prefix.."n_occupants:+1|g")
local room_node = jid.split(event.room.jid)
send(prefix..clean(room_node)..".occupants:+1|g")
end)
module:hook("muc-occupant-left", function(event)
send(prefix.."n_occupants:-1|g")
local room_node = jid.split(event.room.jid)
send(prefix..clean(room_node)..".occupants:-1|g")
end)
-- Misc other MUC
module:hook("muc-broadcast-message", function(event)
send(prefix.."broadcast-message:1|c")
local room_node = jid.split(event.room.jid)
send(prefix..clean(room_node)..".broadcast-message:1|c")
end)
module:hook("muc-invite", function(event)
send(prefix.."invite:1|c")
local room_node = jid.split(event.room.jid)
send(prefix..clean(room_node)..".invite:1|c")
local to_node, to_host, to_resource = jid.split(event.stanza.attr.to)
send(prefix..clean(to_node)..".invites:1|c")
end)
|
mod_statsd: Optionally include host in prefix
|
mod_statsd: Optionally include host in prefix
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
b5b1c689f508068ffbde704194b08569151e383a
|
xmake/modules/detect/sdks/find_vstudio.lua
|
xmake/modules/detect/sdks/find_vstudio.lua
|
--!A cross-platform build utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2018, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_vstudio.lua
--
-- imports
import("lib.detect.find_file")
-- init vc variables
local vcvars = {"path",
"lib",
"libpath",
"include",
"DevEnvdir",
"VSInstallDir",
"VCInstallDir",
"WindowsSdkDir",
"WindowsLibPath",
"WindowsSDKVersion",
"WindowsSdkBinPath",
"UniversalCRTSdkDir",
"UCRTVersion"}
-- load vcvarsall environment variables
function _load_vcvarsall(vcvarsall, arch)
-- make the genvcvars.bat
local genvcvars_bat = os.tmpfile() .. "_genvcvars.bat"
local genvcvars_dat = os.tmpfile() .. "_genvcvars.txt"
local file = io.open(genvcvars_bat, "w")
file:print("@echo off")
file:print("call \"%s\" %s > nul", vcvarsall, arch)
for idx, var in ipairs(vcvars) do
file:print("echo " .. var .. " = %%" .. var .. "%% %s %s", idx == 1 and ">" or ">>", genvcvars_dat)
end
file:close()
-- run genvcvars.bat
os.run(genvcvars_bat)
-- load all envirnoment variables
local variables = {}
for _, line in ipairs((io.readfile(genvcvars_dat) or ""):split("\n")) do
local p = line:find('=', 1, true)
if p then
local name = line:sub(1, p - 1):trim()
local value = line:sub(p + 1):trim()
variables[name] = value
end
end
if not variables.path then
return
end
-- remove some empty entries
for _, name in ipairs(vcvars) do
if variables[name] and #variables[name]:trim() == 0 then
variables[name] = nil
end
end
-- fix WindowsSDKVersion
local WindowsSDKVersion = variables["WindowsSDKVersion"]
if WindowsSDKVersion then
WindowsSDKVersion = WindowsSDKVersion:gsub("\\", ""):trim()
if WindowsSDKVersion ~= "" then
variables["WindowsSDKVersion"] = WindowsSDKVersion
end
end
-- fix UCRTVersion
--
-- @note vcvarsall.bat maybe detect error if install WDK and SDK at same time (multi-sdk version exists in include directory).
--
local UCRTVersion = variables["UCRTVersion"]
if UCRTVersion and UCRTVersion ~= WindowsSDKVersion and WindowsSDKVersion ~= "" then
local lib = variables["lib"]
if lib then
lib = lib:gsub(UCRTVersion, WindowsSDKVersion)
variables["lib"] = lib
end
local include = variables["include"]
if include then
include = include:gsub(UCRTVersion, WindowsSDKVersion)
variables["include"] = include
end
UCRTVersion = WindowsSDKVersion
variables["UCRTVersion"] = UCRTVersion
end
-- ok
return variables
end
-- find vstudio environment
--
-- @return { 2008 = {version = "9.0", vcvarsall = {x86 = {path = .., lib = .., include = ..}}}
-- , 2017 = {version = "15.0", vcvarsall = {x64 = {path = .., lib = ..}}}}
--
function main()
-- init vsvers
local vsvers =
{
["15.0"] = "2017"
, ["14.0"] = "2015"
, ["12.0"] = "2013"
, ["11.0"] = "2012"
, ["10.0"] = "2010"
, ["9.0"] = "2008"
, ["8.0"] = "2005"
, ["7.1"] = "2003"
, ["7.0"] = "7.0"
, ["6.0"] = "6.0"
, ["5.0"] = "5.0"
, ["4.2"] = "4.2"
}
-- init vsenvs
local vsenvs =
{
["14.0"] = "VS140COMNTOOLS"
, ["12.0"] = "VS120COMNTOOLS"
, ["11.0"] = "VS110COMNTOOLS"
, ["10.0"] = "VS100COMNTOOLS"
, ["9.0"] = "VS90COMNTOOLS"
, ["8.0"] = "VS80COMNTOOLS"
, ["7.1"] = "VS71COMNTOOLS"
, ["7.0"] = "VS70COMNTOOLS"
, ["6.0"] = "VS60COMNTOOLS"
, ["5.0"] = "VS50COMNTOOLS"
, ["4.2"] = "VS42COMNTOOLS"
}
-- find vs from environment variables
local VCInstallDir = os.getenv("VCInstallDir")
local VisualStudioVersion = os.getenv("VisualStudioVersion")
if VCInstallDir and VisualStudioVersion then
-- find vcvarsall.bat
local vcvarsall = path.join(VCInstallDir, "Auxiliary", "Build", "vcvarsall.bat")
if os.isfile(vcvarsall) then
-- load vcvarsall
local vcvarsall_x86 = _load_vcvarsall(vcvarsall, "x86")
local vcvarsall_x64 = _load_vcvarsall(vcvarsall, "x64")
-- save results
local results = {}
results[vsvers[VisualStudioVersion]] = {version = VisualStudioVersion, vcvarsall_bat = vcvarsall, vcvarsall = {x86 = vcvarsall_x86, x64 = vcvarsall_x64}}
return results
end
end
-- find vs2017 -> vs4.2
local results = {}
for _, version in ipairs({"15.0", "14.0", "12.0", "11.0", "10.0", "9.0", "8.0", "7.1", "7.0", "6.0", "5.0", "4.2"}) do
-- init pathes
local pathes =
{
format("$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7;%s)\\VC", version),
format("$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VS7;%s)\\VC", version),
format("$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7;%s)\\VC\\Auxiliary\\Build", version),
format("$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VS7;%s)\\VC\\Auxiliary\\Build", version),
format("$(env %s)\\..\\..\\VC", vsenvs[version] or "")
}
-- find vcvarsall.bat
local vcvarsall = find_file("vcvarsall.bat", pathes)
if vcvarsall then
-- load vcvarsall
local vcvarsall_x86 = _load_vcvarsall(vcvarsall, "x86")
local vcvarsall_x64 = _load_vcvarsall(vcvarsall, "x64")
-- save results
results[vsvers[version]] = {version = version, vcvarsall_bat = vcvarsall, vcvarsall = {x86 = vcvarsall_x86, x64 = vcvarsall_x64}}
end
end
-- ok?
return results
end
|
--!A cross-platform build utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2018, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_vstudio.lua
--
-- imports
import("lib.detect.find_file")
-- init vc variables
local vcvars = {"path",
"lib",
"libpath",
"include",
"DevEnvdir",
"VSInstallDir",
"VCInstallDir",
"WindowsSdkDir",
"WindowsLibPath",
"WindowsSDKVersion",
"WindowsSdkBinPath",
"UniversalCRTSdkDir",
"UCRTVersion"}
-- load vcvarsall environment variables
function _load_vcvarsall(vcvarsall, arch)
-- make the genvcvars.bat
local genvcvars_bat = os.tmpfile() .. "_genvcvars.bat"
local genvcvars_dat = os.tmpfile() .. "_genvcvars.txt"
local file = io.open(genvcvars_bat, "w")
file:print("@echo off")
file:print("call \"%s\" %s > nul", vcvarsall, arch)
for idx, var in ipairs(vcvars) do
file:print("echo " .. var .. " = %%" .. var .. "%% %s %s", idx == 1 and ">" or ">>", genvcvars_dat)
end
file:close()
-- run genvcvars.bat
os.run(genvcvars_bat)
-- load all envirnoment variables
local variables = {}
for _, line in ipairs((io.readfile(genvcvars_dat) or ""):split("\n")) do
local p = line:find('=', 1, true)
if p then
local name = line:sub(1, p - 1):trim()
local value = line:sub(p + 1):trim()
variables[name] = value
end
end
if not variables.path then
return
end
-- remove some empty entries
for _, name in ipairs(vcvars) do
if variables[name] and #variables[name]:trim() == 0 then
variables[name] = nil
end
end
-- fix WindowsSDKVersion
local WindowsSDKVersion = variables["WindowsSDKVersion"]
if WindowsSDKVersion then
WindowsSDKVersion = WindowsSDKVersion:gsub("\\", ""):trim()
if WindowsSDKVersion ~= "" then
variables["WindowsSDKVersion"] = WindowsSDKVersion
end
end
-- fix UCRTVersion
--
-- @note vcvarsall.bat maybe detect error if install WDK and SDK at same time (multi-sdk version exists in include directory).
--
local UCRTVersion = variables["UCRTVersion"]
if UCRTVersion and UCRTVersion ~= WindowsSDKVersion and WindowsSDKVersion ~= "" then
local lib = variables["lib"]
if lib then
lib = lib:gsub(UCRTVersion, WindowsSDKVersion)
variables["lib"] = lib
end
local include = variables["include"]
if include then
include = include:gsub(UCRTVersion, WindowsSDKVersion)
variables["include"] = include
end
UCRTVersion = WindowsSDKVersion
variables["UCRTVersion"] = UCRTVersion
end
-- ok
return variables
end
-- find vstudio environment
--
-- @return { 2008 = {version = "9.0", vcvarsall = {x86 = {path = .., lib = .., include = ..}}}
-- , 2017 = {version = "15.0", vcvarsall = {x64 = {path = .., lib = ..}}}}
--
function main()
-- init vsvers
local vsvers =
{
["15.0"] = "2017"
, ["14.0"] = "2015"
, ["12.0"] = "2013"
, ["11.0"] = "2012"
, ["10.0"] = "2010"
, ["9.0"] = "2008"
, ["8.0"] = "2005"
, ["7.1"] = "2003"
, ["7.0"] = "7.0"
, ["6.0"] = "6.0"
, ["5.0"] = "5.0"
, ["4.2"] = "4.2"
}
-- init vsenvs
local vsenvs =
{
["14.0"] = "VS140COMNTOOLS"
, ["12.0"] = "VS120COMNTOOLS"
, ["11.0"] = "VS110COMNTOOLS"
, ["10.0"] = "VS100COMNTOOLS"
, ["9.0"] = "VS90COMNTOOLS"
, ["8.0"] = "VS80COMNTOOLS"
, ["7.1"] = "VS71COMNTOOLS"
, ["7.0"] = "VS70COMNTOOLS"
, ["6.0"] = "VS60COMNTOOLS"
, ["5.0"] = "VS50COMNTOOLS"
, ["4.2"] = "VS42COMNTOOLS"
}
-- find vs from environment variables
local VCInstallDir = os.getenv("VCInstallDir")
local VisualStudioVersion = os.getenv("VisualStudioVersion")
if VCInstallDir and VisualStudioVersion then
-- find vcvarsall.bat
local vcvarsall = path.join(VCInstallDir, "Auxiliary", "Build", "vcvarsall.bat")
if os.isfile(vcvarsall) then
-- load vcvarsall
local vcvarsall_x86 = _load_vcvarsall(vcvarsall, "x86")
local vcvarsall_x64 = _load_vcvarsall(vcvarsall, "x64")
-- save results
local results = {}
results[vsvers[VisualStudioVersion]] = {version = VisualStudioVersion, vcvarsall_bat = vcvarsall, vcvarsall = {x86 = vcvarsall_x86, x64 = vcvarsall_x64}}
return results
end
end
-- find vs2017 -> vs4.2
local results = {}
for _, version in ipairs({"15.0", "14.0", "12.0", "11.0", "10.0", "9.0", "8.0", "7.1", "7.0", "6.0", "5.0", "4.2"}) do
-- init pathes
local pathes =
{
format("$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7;%s)\\VC", version),
format("$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7;%s)\\VC7\\bin", version),
format("$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VS7;%s)\\VC", version),
format("$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7;%s)\\VC\\Auxiliary\\Build", version),
format("$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VS7;%s)\\VC\\Auxiliary\\Build", version),
format("$(env %s)\\..\\..\\VC", vsenvs[version] or "")
}
-- find vcvarsall.bat, vcvars32.bat for vs7.1
local vcvarsall = find_file("vcvarsall.bat", pathes) or find_file("vcvars32.bat", pathes)
if vcvarsall then
-- load vcvarsall
local vcvarsall_x86 = _load_vcvarsall(vcvarsall, "x86")
local vcvarsall_x64 = _load_vcvarsall(vcvarsall, "x64")
-- save results
results[vsvers[version]] = {version = version, vcvarsall_bat = vcvarsall, vcvarsall = {x86 = vcvarsall_x86, x64 = vcvarsall_x64}}
end
end
-- ok?
return results
end
|
Fix bug for VS2003 can't be found (xmake config --vs=2003)
|
Fix bug for VS2003 can't be found
(xmake config --vs=2003)
|
Lua
|
apache-2.0
|
tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake
|
2c3d33006cbe4b9d65d4c9922c44f548e6cd43b6
|
modules/admin-mini/luasrc/model/cbi/mini/system.lua
|
modules/admin-mini/luasrc/model/cbi/mini/system.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.sys")
require("luci.sys.zoneinfo")
require("luci.tools.webadmin")
m = Map("system", translate("system"), translate("a_s_desc"))
s = m:section(TypedSection, "system", "")
s.anonymous = true
local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo()
local uptime = luci.sys.uptime()
s:option(DummyValue, "_system", translate("system")).value = system
s:option(DummyValue, "_cpu", translate("m_i_processor")).value = model
local load1, load5, load15 = luci.sys.loadavg()
s:option(DummyValue, "_la", translate("load")).value =
string.format("%.2f, %.2f, %.2f", load1, load5, load15)
s:option(DummyValue, "_memtotal", translate("m_i_memory")).value =
string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)",
tonumber(memtotal) / 1024,
100 * memcached / memtotal,
translate("mem_cached") or "",
100 * membuffers / memtotal,
translate("mem_buffered") or "",
100 * memfree / memtotal,
translate("mem_free") or "")
s:option(DummyValue, "_systime", translate("m_i_systemtime")).value =
os.date("%c")
s:option(DummyValue, "_uptime", translate("m_i_uptime")).value =
luci.tools.webadmin.date_format(tonumber(uptime))
hn = s:option(Value, "hostname", translate("hostname"))
function hn.write(self, section, value)
Value.write(self, section, value)
luci.sys.hostname(value)
end
tz = s:option(ListValue, "zonename", translate("timezone"))
tz:value("UTC")
for i, zone in ipairs(luci.sys.zoneinfo.TZ) do
tz:value(zone[1])
end
function tz.write(self, section, value)
local function lookup_zone(title)
for _, zone in ipairs(luci.sys.zoneinfo.TZ) do
if zone[1] == title then return zone[2] end
end
end
AbstractValue.write(self, section, value)
self.map.uci:set("system", section, "timezone", lookup_zone(value) or "GMT0")
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.sys")
require("luci.sys.zoneinfo")
require("luci.tools.webadmin")
m = Map("system", translate("system"), translate("a_s_desc"))
s = m:section(TypedSection, "system", "")
s.anonymous = true
local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo()
local uptime = luci.sys.uptime()
s:option(DummyValue, "_system", translate("system")).value = system
s:option(DummyValue, "_cpu", translate("m_i_processor")).value = model
local load1, load5, load15 = luci.sys.loadavg()
s:option(DummyValue, "_la", translate("load")).value =
string.format("%.2f, %.2f, %.2f", load1, load5, load15)
s:option(DummyValue, "_memtotal", translate("m_i_memory")).value =
string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)",
tonumber(memtotal) / 1024,
100 * memcached / memtotal,
tostring(translate("mem_cached", "")),
100 * membuffers / memtotal,
tostring(translate("mem_buffered", "")),
100 * memfree / memtotal,
tostring(translate("mem_free", ""))
s:option(DummyValue, "_systime", translate("m_i_systemtime")).value =
os.date("%c")
s:option(DummyValue, "_uptime", translate("m_i_uptime")).value =
luci.tools.webadmin.date_format(tonumber(uptime))
hn = s:option(Value, "hostname", translate("hostname"))
function hn.write(self, section, value)
Value.write(self, section, value)
luci.sys.hostname(value)
end
tz = s:option(ListValue, "zonename", translate("timezone"))
tz:value("UTC")
for i, zone in ipairs(luci.sys.zoneinfo.TZ) do
tz:value(zone[1])
end
function tz.write(self, section, value)
local function lookup_zone(title)
for _, zone in ipairs(luci.sys.zoneinfo.TZ) do
if zone[1] == title then return zone[2] end
end
end
AbstractValue.write(self, section, value)
self.map.uci:set("system", section, "timezone", lookup_zone(value) or "GMT0")
end
return m
|
modules/admin-mini: fix the same issue in admin-mini
|
modules/admin-mini: fix the same issue in admin-mini
|
Lua
|
apache-2.0
|
NeoRaider/luci,wongsyrone/luci-1,openwrt/luci,Hostle/openwrt-luci-multi-user,harveyhu2012/luci,thess/OpenWrt-luci,Wedmer/luci,florian-shellfire/luci,daofeng2015/luci,oyido/luci,urueedi/luci,deepak78/new-luci,chris5560/openwrt-luci,slayerrensky/luci,Sakura-Winkey/LuCI,harveyhu2012/luci,artynet/luci,aircross/OpenWrt-Firefly-LuCI,nmav/luci,zhaoxx063/luci,jorgifumi/luci,Kyklas/luci-proto-hso,jlopenwrtluci/luci,forward619/luci,aircross/OpenWrt-Firefly-LuCI,keyidadi/luci,forward619/luci,florian-shellfire/luci,cshore/luci,db260179/openwrt-bpi-r1-luci,cappiewu/luci,chris5560/openwrt-luci,thesabbir/luci,aircross/OpenWrt-Firefly-LuCI,981213/luci-1,chris5560/openwrt-luci,NeoRaider/luci,slayerrensky/luci,tcatm/luci,palmettos/test,rogerpueyo/luci,kuoruan/lede-luci,ff94315/luci-1,RuiChen1113/luci,maxrio/luci981213,thess/OpenWrt-luci,marcel-sch/luci,981213/luci-1,openwrt-es/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,tobiaswaldvogel/luci,cshore/luci,ReclaimYourPrivacy/cloak-luci,harveyhu2012/luci,sujeet14108/luci,dismantl/luci-0.12,florian-shellfire/luci,cshore-firmware/openwrt-luci,obsy/luci,wongsyrone/luci-1,Hostle/openwrt-luci-multi-user,palmettos/test,chris5560/openwrt-luci,cappiewu/luci,Wedmer/luci,981213/luci-1,palmettos/test,taiha/luci,thess/OpenWrt-luci,dismantl/luci-0.12,zhaoxx063/luci,kuoruan/lede-luci,nwf/openwrt-luci,remakeelectric/luci,urueedi/luci,RedSnake64/openwrt-luci-packages,opentechinstitute/luci,remakeelectric/luci,Wedmer/luci,tcatm/luci,keyidadi/luci,oyido/luci,tcatm/luci,RuiChen1113/luci,david-xiao/luci,Hostle/openwrt-luci-multi-user,schidler/ionic-luci,tcatm/luci,bright-things/ionic-luci,bittorf/luci,palmettos/test,cshore/luci,taiha/luci,mumuqz/luci,thess/OpenWrt-luci,thess/OpenWrt-luci,Kyklas/luci-proto-hso,joaofvieira/luci,dismantl/luci-0.12,LuttyYang/luci,LazyZhu/openwrt-luci-trunk-mod,jlopenwrtluci/luci,forward619/luci,ReclaimYourPrivacy/cloak-luci,MinFu/luci,obsy/luci,lcf258/openwrtcn,db260179/openwrt-bpi-r1-luci,cshore-firmware/openwrt-luci,oneru/luci,RuiChen1113/luci,deepak78/new-luci,male-puppies/luci,remakeelectric/luci,opentechinstitute/luci,Hostle/openwrt-luci-multi-user,Hostle/luci,florian-shellfire/luci,Hostle/luci,kuoruan/luci,ReclaimYourPrivacy/cloak-luci,remakeelectric/luci,keyidadi/luci,thesabbir/luci,LuttyYang/luci,marcel-sch/luci,rogerpueyo/luci,marcel-sch/luci,fkooman/luci,sujeet14108/luci,cappiewu/luci,kuoruan/luci,MinFu/luci,oneru/luci,Sakura-Winkey/LuCI,ollie27/openwrt_luci,remakeelectric/luci,palmettos/test,artynet/luci,ff94315/luci-1,RedSnake64/openwrt-luci-packages,fkooman/luci,RuiChen1113/luci,lcf258/openwrtcn,bittorf/luci,daofeng2015/luci,oneru/luci,male-puppies/luci,ReclaimYourPrivacy/cloak-luci,maxrio/luci981213,obsy/luci,jchuang1977/luci-1,thesabbir/luci,NeoRaider/luci,maxrio/luci981213,cshore-firmware/openwrt-luci,david-xiao/luci,NeoRaider/luci,Hostle/openwrt-luci-multi-user,harveyhu2012/luci,male-puppies/luci,david-xiao/luci,keyidadi/luci,slayerrensky/luci,openwrt-es/openwrt-luci,shangjiyu/luci-with-extra,dwmw2/luci,ff94315/luci-1,palmettos/test,rogerpueyo/luci,aa65535/luci,male-puppies/luci,zhaoxx063/luci,ReclaimYourPrivacy/cloak-luci,kuoruan/lede-luci,palmettos/cnLuCI,bright-things/ionic-luci,mumuqz/luci,tcatm/luci,sujeet14108/luci,thess/OpenWrt-luci,LuttyYang/luci,teslamint/luci,nwf/openwrt-luci,mumuqz/luci,bright-things/ionic-luci,male-puppies/luci,nwf/openwrt-luci,bright-things/ionic-luci,lbthomsen/openwrt-luci,oneru/luci,lbthomsen/openwrt-luci,lcf258/openwrtcn,florian-shellfire/luci,palmettos/test,taiha/luci,Sakura-Winkey/LuCI,lbthomsen/openwrt-luci,bright-things/ionic-luci,lbthomsen/openwrt-luci,male-puppies/luci,obsy/luci,deepak78/new-luci,RedSnake64/openwrt-luci-packages,rogerpueyo/luci,bittorf/luci,MinFu/luci,jorgifumi/luci,Wedmer/luci,ff94315/luci-1,bright-things/ionic-luci,cshore-firmware/openwrt-luci,kuoruan/luci,kuoruan/lede-luci,MinFu/luci,chris5560/openwrt-luci,thesabbir/luci,artynet/luci,Hostle/luci,deepak78/new-luci,obsy/luci,openwrt-es/openwrt-luci,palmettos/cnLuCI,opentechinstitute/luci,db260179/openwrt-bpi-r1-luci,kuoruan/lede-luci,tobiaswaldvogel/luci,db260179/openwrt-bpi-r1-luci,cappiewu/luci,RedSnake64/openwrt-luci-packages,lcf258/openwrtcn,MinFu/luci,Noltari/luci,jorgifumi/luci,openwrt/luci,dismantl/luci-0.12,jlopenwrtluci/luci,oyido/luci,joaofvieira/luci,db260179/openwrt-bpi-r1-luci,daofeng2015/luci,zhaoxx063/luci,wongsyrone/luci-1,db260179/openwrt-bpi-r1-luci,Wedmer/luci,bittorf/luci,forward619/luci,nwf/openwrt-luci,thesabbir/luci,981213/luci-1,LuttyYang/luci,artynet/luci,bittorf/luci,shangjiyu/luci-with-extra,thesabbir/luci,mumuqz/luci,NeoRaider/luci,slayerrensky/luci,sujeet14108/luci,db260179/openwrt-bpi-r1-luci,nwf/openwrt-luci,joaofvieira/luci,daofeng2015/luci,ReclaimYourPrivacy/cloak-luci,openwrt/luci,maxrio/luci981213,jchuang1977/luci-1,Sakura-Winkey/LuCI,oyido/luci,LazyZhu/openwrt-luci-trunk-mod,lcf258/openwrtcn,Noltari/luci,bittorf/luci,openwrt-es/openwrt-luci,ff94315/luci-1,Hostle/luci,nmav/luci,aa65535/luci,maxrio/luci981213,forward619/luci,wongsyrone/luci-1,wongsyrone/luci-1,jchuang1977/luci-1,maxrio/luci981213,openwrt/luci,Sakura-Winkey/LuCI,oyido/luci,deepak78/new-luci,daofeng2015/luci,marcel-sch/luci,ollie27/openwrt_luci,tobiaswaldvogel/luci,cshore-firmware/openwrt-luci,zhaoxx063/luci,RuiChen1113/luci,joaofvieira/luci,tcatm/luci,Kyklas/luci-proto-hso,keyidadi/luci,taiha/luci,ollie27/openwrt_luci,RedSnake64/openwrt-luci-packages,dwmw2/luci,wongsyrone/luci-1,dwmw2/luci,cshore-firmware/openwrt-luci,fkooman/luci,wongsyrone/luci-1,jlopenwrtluci/luci,Hostle/luci,LazyZhu/openwrt-luci-trunk-mod,forward619/luci,cappiewu/luci,lbthomsen/openwrt-luci,forward619/luci,ollie27/openwrt_luci,bright-things/ionic-luci,jlopenwrtluci/luci,hnyman/luci,lcf258/openwrtcn,florian-shellfire/luci,ReclaimYourPrivacy/cloak-luci,tobiaswaldvogel/luci,kuoruan/luci,teslamint/luci,joaofvieira/luci,florian-shellfire/luci,lbthomsen/openwrt-luci,deepak78/new-luci,jorgifumi/luci,LuttyYang/luci,lcf258/openwrtcn,jorgifumi/luci,aa65535/luci,LuttyYang/luci,thesabbir/luci,urueedi/luci,zhaoxx063/luci,sujeet14108/luci,openwrt/luci,cshore/luci,david-xiao/luci,joaofvieira/luci,aa65535/luci,openwrt/luci,artynet/luci,schidler/ionic-luci,LazyZhu/openwrt-luci-trunk-mod,deepak78/new-luci,db260179/openwrt-bpi-r1-luci,opentechinstitute/luci,RedSnake64/openwrt-luci-packages,Wedmer/luci,daofeng2015/luci,fkooman/luci,thess/OpenWrt-luci,kuoruan/luci,Sakura-Winkey/LuCI,obsy/luci,florian-shellfire/luci,oneru/luci,teslamint/luci,hnyman/luci,palmettos/cnLuCI,fkooman/luci,shangjiyu/luci-with-extra,kuoruan/luci,teslamint/luci,jchuang1977/luci-1,jlopenwrtluci/luci,oneru/luci,slayerrensky/luci,Hostle/openwrt-luci-multi-user,oyido/luci,dwmw2/luci,oyido/luci,nmav/luci,Kyklas/luci-proto-hso,rogerpueyo/luci,oneru/luci,david-xiao/luci,openwrt/luci,teslamint/luci,Noltari/luci,harveyhu2012/luci,bittorf/luci,tobiaswaldvogel/luci,aircross/OpenWrt-Firefly-LuCI,oneru/luci,urueedi/luci,Kyklas/luci-proto-hso,thesabbir/luci,shangjiyu/luci-with-extra,ff94315/luci-1,openwrt-es/openwrt-luci,aa65535/luci,marcel-sch/luci,lcf258/openwrtcn,nmav/luci,urueedi/luci,shangjiyu/luci-with-extra,NeoRaider/luci,harveyhu2012/luci,Hostle/openwrt-luci-multi-user,male-puppies/luci,artynet/luci,LazyZhu/openwrt-luci-trunk-mod,MinFu/luci,schidler/ionic-luci,teslamint/luci,urueedi/luci,cshore-firmware/openwrt-luci,maxrio/luci981213,jchuang1977/luci-1,kuoruan/lede-luci,opentechinstitute/luci,chris5560/openwrt-luci,slayerrensky/luci,ReclaimYourPrivacy/cloak-luci,kuoruan/luci,bright-things/ionic-luci,opentechinstitute/luci,rogerpueyo/luci,hnyman/luci,palmettos/cnLuCI,tcatm/luci,forward619/luci,taiha/luci,Hostle/openwrt-luci-multi-user,cshore/luci,Hostle/luci,cshore/luci,kuoruan/lede-luci,maxrio/luci981213,Noltari/luci,sujeet14108/luci,shangjiyu/luci-with-extra,RedSnake64/openwrt-luci-packages,artynet/luci,aa65535/luci,zhaoxx063/luci,nmav/luci,obsy/luci,cshore/luci,ollie27/openwrt_luci,ff94315/luci-1,LuttyYang/luci,tobiaswaldvogel/luci,chris5560/openwrt-luci,shangjiyu/luci-with-extra,aircross/OpenWrt-Firefly-LuCI,ollie27/openwrt_luci,schidler/ionic-luci,ff94315/luci-1,joaofvieira/luci,MinFu/luci,taiha/luci,teslamint/luci,mumuqz/luci,NeoRaider/luci,981213/luci-1,marcel-sch/luci,mumuqz/luci,openwrt/luci,jorgifumi/luci,marcel-sch/luci,cshore/luci,zhaoxx063/luci,remakeelectric/luci,daofeng2015/luci,mumuqz/luci,lbthomsen/openwrt-luci,Noltari/luci,opentechinstitute/luci,deepak78/new-luci,MinFu/luci,wongsyrone/luci-1,tcatm/luci,slayerrensky/luci,artynet/luci,david-xiao/luci,remakeelectric/luci,jlopenwrtluci/luci,david-xiao/luci,jlopenwrtluci/luci,palmettos/cnLuCI,schidler/ionic-luci,Noltari/luci,aa65535/luci,Hostle/luci,cappiewu/luci,ollie27/openwrt_luci,RuiChen1113/luci,Sakura-Winkey/LuCI,sujeet14108/luci,981213/luci-1,schidler/ionic-luci,LuttyYang/luci,jchuang1977/luci-1,dwmw2/luci,nmav/luci,jchuang1977/luci-1,tobiaswaldvogel/luci,obsy/luci,Hostle/luci,lcf258/openwrtcn,cappiewu/luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,Noltari/luci,dismantl/luci-0.12,LazyZhu/openwrt-luci-trunk-mod,mumuqz/luci,male-puppies/luci,NeoRaider/luci,cappiewu/luci,rogerpueyo/luci,urueedi/luci,teslamint/luci,nmav/luci,981213/luci-1,slayerrensky/luci,oyido/luci,Noltari/luci,openwrt-es/openwrt-luci,dismantl/luci-0.12,Wedmer/luci,Kyklas/luci-proto-hso,hnyman/luci,marcel-sch/luci,hnyman/luci,nmav/luci,kuoruan/lede-luci,schidler/ionic-luci,rogerpueyo/luci,joaofvieira/luci,jorgifumi/luci,openwrt-es/openwrt-luci,bittorf/luci,david-xiao/luci,dwmw2/luci,palmettos/cnLuCI,opentechinstitute/luci,lcf258/openwrtcn,keyidadi/luci,taiha/luci,cshore-firmware/openwrt-luci,palmettos/cnLuCI,LazyZhu/openwrt-luci-trunk-mod,kuoruan/luci,Kyklas/luci-proto-hso,ollie27/openwrt_luci,chris5560/openwrt-luci,fkooman/luci,schidler/ionic-luci,dismantl/luci-0.12,hnyman/luci,dwmw2/luci,aircross/OpenWrt-Firefly-LuCI,fkooman/luci,RuiChen1113/luci,palmettos/test,urueedi/luci,nmav/luci,palmettos/cnLuCI,hnyman/luci,RuiChen1113/luci,sujeet14108/luci,keyidadi/luci,nwf/openwrt-luci,daofeng2015/luci,hnyman/luci,remakeelectric/luci,taiha/luci,tobiaswaldvogel/luci,fkooman/luci,harveyhu2012/luci,Sakura-Winkey/LuCI,aircross/OpenWrt-Firefly-LuCI,nwf/openwrt-luci,dwmw2/luci,jorgifumi/luci,Wedmer/luci,shangjiyu/luci-with-extra,keyidadi/luci,nwf/openwrt-luci,artynet/luci,Noltari/luci,aa65535/luci,thess/OpenWrt-luci,jchuang1977/luci-1
|
179ec85593e24a7e8d4028c5007139de7e580b34
|
spec/core/core_send_recv.lua
|
spec/core/core_send_recv.lua
|
--local llthreads = require'llthreads'
local nml=require'nml'
local events = require'nml.events'
--local pw=require'pl.pretty'.write
require'busted'
local AF_SP = nml.symbols.AF_SP.value
local NN_PAIR = nml.symbols.NN_PAIR.value
nml = nml.core
local PAIR_ADDR = "inproc://pair"
local msg
local count
local sockets
local pair_1 = nml.socket(AF_SP, NN_PAIR)
nml.bind(pair_1, PAIR_ADDR)
local pair_2 = nml.socket(AF_SP, NN_PAIR)
nml.connect(pair_2, PAIR_ADDR)
local msg1_ud, msg1_str ,msg_type1, msg2_ud, msg2_str, msg_type2
describe("Send tests #send #recv", function()
it("can send a simple text message, without defining the buffer length.", function()
msg1 = "ABC"
assert.is_truthy(nml.send(pair_1, msg1))
end)
it("can recv a simple text message.", function()
msg2, msg_type2 = nml.recvmsg(pair_2)
assert.is_truthy(msg2)
print("msg2", msg2)
end)
-- it("receives a message as userdata", function()
-- assert.not_falsy(msg2)
-- assert.is_equal("userdata", type(msg2))
-- end)
-- it("receives a message type as the 2nd return value", function()
-- assert.is_equal("string", msg_type2)
-- end)
-- it("converts a message userdata using the nml.tostring() method.", function()
-- msg2_str = nml.tostring(msg2)
-- assert.isequal("string", type(msg2_str))
-- end)
-- it("frees the message, which is still there, even after it was converted.", function()
-- --returns true when free happens. false if no pointer. nil, msg (or error) if something bad happens.
-- assert.is_true(nml.free(msg2))
-- --freeing again returns false.
-- assert.is_false(nml.free(msg2))
-- msg2 = nil
-- collectgarbage();collectgarbage();collectgarbage()
-- --there shouldn't be any error here, even though __gc was called.
-- end)
-- it("can send and receive a string message where the length and message type are defined", function()
-- msg_type1 = "text/foo"
-- assert.is_truthy(nml.send(pair_1, msg1, 0, #msg1, msg_type1))
-- msg2, msg_type2 = nml.recv(pair_2)
-- end)
-- it("can send and recv a simple text message, without defining the buffer length.", function()
-- msg1 = "ABC"
-- nml.send(pair_1, msg1)
-- msg2 = nml.recv(pair_2)
-- assert.not_falsy(msg2)
-- assert.is_equal(msg1, msg2)
-- end)
-- -- /* Clean up. */
-- it("closes the sockets", function()
-- assert.is_truthy(nml.close(pair_2))
-- assert.is_truthy(nml.close(pair_1))
-- end)
end)
|
local nml=require'nml'
local events = require'nml.events'
require'busted'
local AF_SP = nml.symbols.AF_SP.value
local NN_PAIR = nml.symbols.NN_PAIR.value
nml = nml.core
local PAIR_ADDR = "inproc://pair"
local msg
local count
local sockets
local pair_1 = nml.socket(AF_SP, NN_PAIR)
nml.bind(pair_1, PAIR_ADDR)
local pair_2 = nml.socket(AF_SP, NN_PAIR)
nml.connect(pair_2, PAIR_ADDR)
local msg1_ud, msg1_str, msg1_type, msg2_ud
msg1_ud = nml.nml_msg()
msg1_str = "ABC"
msg1_type = "TST1"
nml.msg_fromstring(msg1_ud, msg1_str)
nml.msg_setheader(msg1_ud, msg1_type)
describe("Send tests #send #recv", function()
it("can send a simple text message.", function()
assert.is_truthy(nml.send(pair_1, msg1_ud))
end)
it("can recv a simple text message.", function()
msg2_ud = nml.recv(pair_2)
assert.is_truthy(msg2_ud)
end)
it("receives a message as userdata.", function()
assert.is_equal("userdata", type(msg2_ud))
end)
it("received a non-empty message.", function()
assert.is_true(#msg2_ud>0)
end)
it("received a message of the same type as the original.", function()
assert.is_equal(msg1_type, nml.msg_getheader(msg2_ud))
end)
it("received a message of the same size as the original.", function()
assert.are_equal(#msg1_ud, #msg2_ud)
end)
it("received the original message.", function()
assert.are_equal(msg1_str, nml.msg_tostring(msg2_ud))
end)
it("frees the message, which is still there, even after it was converted.", function()
--returns true when free happens. false if no pointer. nil, msg (or error) if something bad happens.
assert.is_true(nml.msg_free(msg2_ud))
--freeing again returns false.
assert.is_false(nml.msg_free(msg2_ud))
msg2_ud = nil
collectgarbage();collectgarbage();collectgarbage()
--there shouldn't be any error here, even though __gc was called.
end)
-- /* Clean up. */
it("closes the sockets", function()
assert.is_truthy(nml.close(pair_2))
assert.is_truthy(nml.close(pair_1))
end)
end)
|
fixed core_send_recv busted tests, passes ok
|
fixed core_send_recv busted tests, passes ok
|
Lua
|
mit
|
trms/nml,trms/nml
|
c233ac2cb42aa84cc2ee5c9aedf0d43cf5591337
|
src/Author.lua
|
src/Author.lua
|
--==================================================================================================
-- Copyright (C) 2014 - 2015 by Robert Machmer =
-- =
-- 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 Author = {};
-- ------------------------------------------------
-- Constants
-- ------------------------------------------------
local LABEL_FONT = love.graphics.newFont('res/fonts/SourceCodePro-Medium.otf', 20);
local DEFAULT_FONT = love.graphics.newFont(12);
local AVATAR_SIZE = 48;
local AUTHOR_INACTIVITY_TIMER = 2;
local LINK_INACTIVITY_TIMER = 2;
local FADE_FACTOR = 2;
local DEFAULT_AVATAR_ALPHA = 255;
local DEFAULT_LINK_ALPHA = 100;
local DAMPING_FACTOR = 0.90;
local FORCE_MAX = 2;
local FORCE_SPRING = -0.5;
local BEAM_WIDTH = 3;
local LINK_COLOR = {
A = { 0, 255, 0 },
D = { 255, 0, 0 },
M = { 254, 140, 0 },
};
-- ------------------------------------------------
-- Constructor
-- ------------------------------------------------
function Author.new(name, avatar, cx, cy)
local self = {};
local posX, posY = cx + love.math.random(5, 200) * (love.math.random(0, 1) == 0 and -1 or 1), cy + love.math.random(5, 200) * (love.math.random(0, 1) == 0 and -1 or 1);
local accX, accY = 0, 0;
local velX, velY = 0, 0;
local links = {};
local inactivity = 0;
local avatarAlpha = DEFAULT_AVATAR_ALPHA;
local linkAlpha = DEFAULT_LINK_ALPHA;
-- Avatar's width and height.
local aw, ah = avatar:getWidth(), avatar:getHeight();
-- ------------------------------------------------
-- Private Functions
-- ------------------------------------------------
local function clamp(min, val, max)
return math.max(min, math.min(val, max));
end
local function reactivate()
inactivity = 0;
avatarAlpha = DEFAULT_AVATAR_ALPHA;
linkAlpha = DEFAULT_LINK_ALPHA;
end
local function move(dt)
velX = (velX + accX * dt * 32) * DAMPING_FACTOR;
velY = (velY + accY * dt * 32) * DAMPING_FACTOR;
posX = posX + velX;
posY = posY + velY;
end
local function applyForce(fx, fy)
accX = clamp(-FORCE_MAX, accX + fx, FORCE_MAX);
accY = clamp(-FORCE_MAX, accY + fy, FORCE_MAX);
end
-- ------------------------------------------------
-- Public Functions
-- ------------------------------------------------
function self:draw(rotation)
for i = 1, #links do
love.graphics.setColor(LINK_COLOR[links[i].mod][1], LINK_COLOR[links[i].mod][2], LINK_COLOR[links[i].mod][3], linkAlpha);
love.graphics.setLineWidth(BEAM_WIDTH);
love.graphics.line(posX, posY, links[i].file:getX(), links[i].file:getY());
love.graphics.setLineWidth(1);
love.graphics.setColor(255, 255, 255, 255);
end
love.graphics.setColor(255, 255, 255, avatarAlpha);
love.graphics.setFont(LABEL_FONT);
love.graphics.print(name, posX - LABEL_FONT:getWidth(name) * 0.5, posY + 48, -rotation);
love.graphics.setFont(DEFAULT_FONT);
love.graphics.draw(avatar, posX, posY, -rotation, AVATAR_SIZE / aw, AVATAR_SIZE / ah, aw * 0.5, ah * 0.5);
love.graphics.setColor(255, 255, 255, 255);
end
function self:update(dt)
move(dt);
inactivity = inactivity + dt;
if inactivity > AUTHOR_INACTIVITY_TIMER then
avatarAlpha = avatarAlpha - avatarAlpha * dt * FADE_FACTOR;
end
if inactivity > LINK_INACTIVITY_TIMER then
linkAlpha = linkAlpha - linkAlpha * dt * FADE_FACTOR;
end
if inactivity > 0.5 then
accX, accY = 0, 0;
end
end
function self:addLink(file, modifier)
reactivate();
links[#links + 1] = { file = file, mod = modifier };
local dx, dy = posX - file:getX(), posY - file:getY();
local distance = math.sqrt(dx * dx + dy * dy);
dx = dx / distance;
dy = dy / distance;
local strength = FORCE_SPRING * distance;
applyForce(dx * strength, dy * strength);
end
function self:resetLinks()
links = {};
end
return self;
end
-- ------------------------------------------------
-- Return Module
-- ------------------------------------------------
return Author;
|
--==================================================================================================
-- Copyright (C) 2014 - 2015 by Robert Machmer =
-- =
-- 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 Author = {};
-- ------------------------------------------------
-- Constants
-- ------------------------------------------------
local LABEL_FONT = love.graphics.newFont('res/fonts/SourceCodePro-Medium.otf', 20);
local DEFAULT_FONT = love.graphics.newFont(12);
local AVATAR_SIZE = 48;
local AUTHOR_INACTIVITY_TIMER = 2;
local LINK_INACTIVITY_TIMER = 2;
local FADE_FACTOR = 2;
local DEFAULT_AVATAR_ALPHA = 255;
local DEFAULT_LINK_ALPHA = 100;
local DAMPING_FACTOR = 0.90;
local FORCE_MAX = 2;
local FORCE_SPRING = -0.5;
local BEAM_WIDTH = 3;
local LINK_COLOR = {
A = { 0, 255, 0 },
D = { 255, 0, 0 },
M = { 254, 140, 0 },
};
-- ------------------------------------------------
-- Constructor
-- ------------------------------------------------
function Author.new(name, avatar, cx, cy)
local self = {};
local posX, posY = cx + love.math.random(5, 200) * (love.math.random(0, 1) == 0 and -1 or 1), cy + love.math.random(5, 200) * (love.math.random(0, 1) == 0 and -1 or 1);
local accX, accY = 0, 0;
local velX, velY = 0, 0;
local links = {};
local inactivity = 0;
local avatarAlpha = DEFAULT_AVATAR_ALPHA;
local linkAlpha = DEFAULT_LINK_ALPHA;
-- Avatar's width and height.
local aw, ah = avatar:getWidth(), avatar:getHeight();
-- ------------------------------------------------
-- Private Functions
-- ------------------------------------------------
local function clamp(min, val, max)
return math.max(min, math.min(val, max));
end
local function reactivate()
inactivity = 0;
avatarAlpha = DEFAULT_AVATAR_ALPHA;
linkAlpha = DEFAULT_LINK_ALPHA;
end
local function move(dt)
velX = (velX + accX * dt * 32) * DAMPING_FACTOR;
velY = (velY + accY * dt * 32) * DAMPING_FACTOR;
posX = posX + velX;
posY = posY + velY;
end
local function applyForce(fx, fy)
accX = clamp(-FORCE_MAX, accX + fx, FORCE_MAX);
accY = clamp(-FORCE_MAX, accY + fy, FORCE_MAX);
end
-- ------------------------------------------------
-- Public Functions
-- ------------------------------------------------
function self:draw(rotation)
for i = 1, #links do
love.graphics.setColor(LINK_COLOR[links[i].mod][1], LINK_COLOR[links[i].mod][2], LINK_COLOR[links[i].mod][3], linkAlpha);
love.graphics.setLineWidth(BEAM_WIDTH);
love.graphics.line(posX, posY, links[i].file:getX(), links[i].file:getY());
love.graphics.setLineWidth(1);
love.graphics.setColor(255, 255, 255, 255);
end
love.graphics.setColor(255, 255, 255, avatarAlpha);
love.graphics.draw(avatar, posX, posY, -rotation, AVATAR_SIZE / aw, AVATAR_SIZE / ah, aw * 0.5, ah * 0.5);
love.graphics.setFont(LABEL_FONT);
love.graphics.print(name, posX, posY, -rotation, 1, 1, LABEL_FONT:getWidth(name) * 0.5, - AVATAR_SIZE);
love.graphics.setFont(DEFAULT_FONT);
love.graphics.setColor(255, 255, 255, 255);
end
function self:update(dt)
move(dt);
inactivity = inactivity + dt;
if inactivity > AUTHOR_INACTIVITY_TIMER then
avatarAlpha = avatarAlpha - avatarAlpha * dt * FADE_FACTOR;
end
if inactivity > LINK_INACTIVITY_TIMER then
linkAlpha = linkAlpha - linkAlpha * dt * FADE_FACTOR;
end
if inactivity > 0.5 then
accX, accY = 0, 0;
end
end
function self:addLink(file, modifier)
reactivate();
links[#links + 1] = { file = file, mod = modifier };
local dx, dy = posX - file:getX(), posY - file:getY();
local distance = math.sqrt(dx * dx + dy * dy);
dx = dx / distance;
dy = dy / distance;
local strength = FORCE_SPRING * distance;
applyForce(dx * strength, dy * strength);
end
function self:resetLinks()
links = {};
end
return self;
end
-- ------------------------------------------------
-- Return Module
-- ------------------------------------------------
return Author;
|
Fixed rotation and offset of author name labels
|
Fixed rotation and offset of author name labels
|
Lua
|
mit
|
rm-code/logivi
|
7cf6548e1d0630ae3c13b9fbd73f98e4e0e09ecd
|
Shilke2D/Display/Stage.lua
|
Shilke2D/Display/Stage.lua
|
-- Stage
Stage = class(DisplayObjContainer)
function Stage:init(viewport)
DisplayObjContainer.init(self)
self._prop:setViewport(viewport)
self._debugDeck = MOAIScriptDeck.new ()
--self._debugDeck:setRect ( -64, -64, 64, 64 )
self._debugDeck:setDrawCallback ( function()
if self._showAABounds then
self:drawAABounds(false)
end
if self._showOrientedBounds then
self:drawOrientedBounds()
end
end
)
self._debugProp = MOAIProp.new ()
self._debugProp:setDeck ( self._debugDeck )
self._rt = {self._renderTable}
end
--Stage is a Layer not a 'generic' prop like ALL the others displayObjs
function Stage:_createProp()
return MOAILayer.new()
end
function Stage:showDebugLines(showOrientedBounds,showAABounds)
self._showOrientedBounds = showOrientedBounds or false
self._showAABounds = showAABounds or true
local showDebug = self._showOrientedBounds or self._showAABounds
if showDebug and not self._rt[2] then
self._rt[2] = self._debugProp
end
if not showDebug and self._rt[2] then
self._rt[2] = nil
end
end
--with moai 1.4 clearColor funciton was moved to frameBuffer and removed from GfxDevice.
local function __setClearColor(r,g,b,a)
if MOAIGfxDevice.getFrameBuffer then
MOAIGfxDevice.getFrameBuffer():setClearColor(r,g,b,a)
else
MOAIGfxDevice.setClearColor(r,g,b,a)
end
end
function Stage:setBackground(r,g,b)
if class_type(r) == Color then
__setClearColor(r:unpack_normalized())
else
__setClearColor(r/255,g/255,b/255,1)
end
end
--the method is called by a DisplayObjContainer when the DisplayObj is
--added as child
function Stage:_setParent(parent)
error("Stage cannot be child of another DisplayObjContainer")
end
function Stage:setPivot(x,y)
error("It's not possible to set geometric properties of a Stage")
end
function Stage:setPivotX(x)
error("It's not possible to set geometric properties of a Stage")
end
function Stage:setPivotY(y)
error("It's not possible to set geometric properties of a Stage")
end
function Stage:setPosition(x,y)
error("It's not possible to set geometric properties of a Stage")
end
function Stage:setPosition_v2(v)
error("It's not possible to set geometric properties of a Stage")
end
function Stage:setPositionX(x)
error("It's not possible to set geometric properties of a Stage")
end
function Stage:setPositionY(y)
error("It's not possible to set geometric properties of a Stage")
end
function Stage:translate(x,y)
error("It's not possible to set geometric properties of a Stage")
end
-- rotation angle is expressed in radians
function Stage:setRotation(r)
error("It's not possible to set geometric properties of a Stage")
end
function Stage:setScale(x,y)
error("It's not possible to set geometric properties of a Stage")
end
function Stage:setScale_v2(v)
error("It's not possible to set geometric properties of a Stage")
end
function Stage:setScaleX(s)
error("It's not possible to set geometric properties of a Stage")
end
function Stage:setScaleY(s)
error("It's not possible to set geometric properties of a Stage")
end
|
-- Stage
Stage = class(DisplayObjContainer)
function Stage:init(viewport)
DisplayObjContainer.init(self)
self._prop:setViewport(viewport)
self._debugDeck = MOAIScriptDeck.new ()
--self._debugDeck:setRect ( -64, -64, 64, 64 )
self._debugDeck:setDrawCallback ( function()
if self._showAABounds then
self:drawAABounds(false)
end
if self._showOrientedBounds then
self:drawOrientedBounds()
end
end
)
self._debugProp = MOAIProp.new ()
self._debugProp:setDeck ( self._debugDeck )
self._rt = {self._renderTable}
end
--Stage is a Layer not a 'generic' prop like ALL the others displayObjs
function Stage:_createProp()
return MOAILayer.new()
end
function Stage:showDebugLines(showOrientedBounds,showAABounds)
self._showOrientedBounds = showOrientedBounds ~= nil and showOrientedBounds or true
self._showAABounds = showAABounds ~= nil and showAABounds or false
local showDebug = self._showOrientedBounds or self._showAABounds
if showDebug and not self._rt[2] then
self._rt[2] = self._debugProp
end
if not showDebug and self._rt[2] then
self._rt[2] = nil
end
end
--with moai 1.4 clearColor funciton was moved to frameBuffer and removed from GfxDevice.
local function __setClearColor(r,g,b,a)
if MOAIGfxDevice.getFrameBuffer then
MOAIGfxDevice.getFrameBuffer():setClearColor(r,g,b,a)
else
MOAIGfxDevice.setClearColor(r,g,b,a)
end
end
function Stage:setBackground(r,g,b)
if class_type(r) == Color then
__setClearColor(r:unpack_normalized())
else
__setClearColor(r/255,g/255,b/255,1)
end
end
--the method is called by a DisplayObjContainer when the DisplayObj is
--added as child
function Stage:_setParent(parent)
error("Stage cannot be child of another DisplayObjContainer")
end
function Stage:setPivot(x,y)
error("It's not possible to set geometric properties of a Stage")
end
function Stage:setPivotX(x)
error("It's not possible to set geometric properties of a Stage")
end
function Stage:setPivotY(y)
error("It's not possible to set geometric properties of a Stage")
end
function Stage:setPosition(x,y)
error("It's not possible to set geometric properties of a Stage")
end
function Stage:setPosition_v2(v)
error("It's not possible to set geometric properties of a Stage")
end
function Stage:setPositionX(x)
error("It's not possible to set geometric properties of a Stage")
end
function Stage:setPositionY(y)
error("It's not possible to set geometric properties of a Stage")
end
function Stage:translate(x,y)
error("It's not possible to set geometric properties of a Stage")
end
-- rotation angle is expressed in radians
function Stage:setRotation(r)
error("It's not possible to set geometric properties of a Stage")
end
function Stage:setScale(x,y)
error("It's not possible to set geometric properties of a Stage")
end
function Stage:setScale_v2(v)
error("It's not possible to set geometric properties of a Stage")
end
function Stage:setScaleX(s)
error("It's not possible to set geometric properties of a Stage")
end
function Stage:setScaleY(s)
error("It's not possible to set geometric properties of a Stage")
end
|
stage:showDebugLines - fix for defaultValues
|
stage:showDebugLines - fix for defaultValues
By default now shows only Oriented bboxes
|
Lua
|
mit
|
Shrike78/Shilke2D
|
c2ded8ec5036c806a1d7727f7d628bb85799ac76
|
src/patch/ui/hooks/joiningroom_enablemods.lua
|
src/patch/ui/hooks/joiningroom_enablemods.lua
|
if _mpPatch and _mpPatch.loaded then
Modding = _mpPatch.hookTable(Modding, {ActivateAllowedDLC = function(...)
_mpPatch.overrideModsFromPreGame()
return Modding._super.ActivateAllowedDLC(...)
end})
local function enterLobby()
UIManager:QueuePopup(Controls.StagingRoomScreen, PopupPriority.StagingScreen)
UIManager:DequeuePopup(ContextPtr)
end
local function joinFailed(message)
Events.FrontEndPopup.CallImmediate(message)
g_joinFailed = true
Matchmaking.LeaveMultiplayerGame()
UIManager:DequeuePopup(ContextPtr)
end
function OnConnectionCompete()
if not Matchmaking.IsHost() then
if _mpPatch.isModding then
local missingModList = {}
_mpPatch.debugPrint("Enabled mods for room:")
for _, mod in ipairs(_mpPatch.decodeModsList()) do
local missingText = ""
if not _mpPatch.isModInstalled(mod.ID, mod.Version) then
table.insert(missingModList, mod.Name)
missingText = " (is missing)"
end
_mpPatch.debugPrint("- "..mod.Name..missingText)
end
-- TODO: Check for DLCs/mod compatibility
if #missingModList > 0 then
local messageTable = {Locale.Lookup("TXT_KEY_MPPATCH_MOD_MISSING")}
for _, name in ipairs(missingModList) do
table.insert(messageTable, "[ICON_BULLET]"..name:gsub("%[", "("):gsub("%]", ")"))
end
joinFailed(table.concat(messageTable, "[NEWLINE]"))
return
end
_mpPatch.debugPrint("Activating mods and DLC...")
Modding.ActivateAllowedDLC()
end
enterLobby()
end
end
end
|
if _mpPatch and _mpPatch.loaded then
Modding = _mpPatch.hookTable(Modding, {ActivateAllowedDLC = function(...)
_mpPatch.overrideModsFromPreGame()
return Modding._super.ActivateAllowedDLC(...)
end})
local function enterLobby()
UIManager:QueuePopup(Controls.StagingRoomScreen, PopupPriority.StagingScreen)
UIManager:DequeuePopup(ContextPtr)
end
local function joinFailed(message)
Events.FrontEndPopup.CallImmediate(message)
g_joinFailed = true
Matchmaking.LeaveMultiplayerGame()
UIManager:DequeuePopup(ContextPtr)
end
function OnConnectionCompete()
if not Matchmaking.IsHost() then
if _mpPatch.isModding then
local missingModList = {}
_mpPatch.debugPrint("Enabled mods for room:")
for _, mod in ipairs(_mpPatch.decodeModsList()) do
local missingText = ""
if not _mpPatch.isModInstalled(mod.ID, mod.Version) then
table.insert(missingModList, mod.Name)
missingText = " (is missing)"
end
_mpPatch.debugPrint("- "..mod.Name..missingText)
end
-- TODO: Check for DLCs/mod compatibility
if #missingModList > 0 then
local messageTable = {Locale.Lookup("TXT_KEY_MPPATCH_MOD_MISSING")}
for _, name in ipairs(missingModList) do
table.insert(messageTable, "[ICON_BULLET]"..name:gsub("%[", "("):gsub("%]", ")"))
end
joinFailed(table.concat(messageTable, "[NEWLINE]"))
return
end
_mpPatch.debugPrint("Activating mods and DLC...")
Modding.ActivateAllowedDLC()
Events.SystemUpdateUI(SystemUpdateUIType.RestoreUI, "StagingRoom")
end
enterLobby()
end
end
end
|
Try to fix the unavailable leader bug.
|
Try to fix the unavailable leader bug.
|
Lua
|
mit
|
Lymia/MultiverseModManager,Lymia/MPPatch,Lymia/MPPatch,Lymia/MPPatch,Lymia/CivV_Mod2DLC,Lymia/MPPatch,Lymia/MultiverseModManager
|
eeb90dc39b0c0c548e3691424bdb1a49d8e0db2e
|
lib/pairwise_transform_utils.lua
|
lib/pairwise_transform_utils.lua
|
require 'image'
local iproc = require 'iproc'
local data_augmentation = require 'data_augmentation'
local pairwise_transform_utils = {}
function pairwise_transform_utils.random_half(src, p, filters)
if torch.uniform() < p then
local filter = filters[torch.random(1, #filters)]
return iproc.scale(src, src:size(3) * 0.5, src:size(2) * 0.5, filter)
else
return src
end
end
function pairwise_transform_utils.crop_if_large(src, max_size, mod)
local tries = 4
if src:size(2) > max_size and src:size(3) > max_size then
assert(max_size % 4 == 0)
local rect
for i = 1, tries do
local yi = torch.random(0, src:size(2) - max_size)
local xi = torch.random(0, src:size(3) - max_size)
if mod then
yi = yi - (yi % mod)
xi = xi - (xi % mod)
end
rect = iproc.crop(src, xi, yi, xi + max_size, yi + max_size)
-- ignore simple background
if rect:float():std() >= 0 then
break
end
end
return rect
else
return src
end
end
function pairwise_transform_utils.preprocess(src, crop_size, options)
local dest = src
local box_only = false
if options.data.filters then
if #options.data.filters == 1 and options.data.filters[1] == "Box" then
box_only = true
end
end
if box_only then
local mod = 2 -- assert pos % 2 == 0
dest = pairwise_transform_utils.crop_if_large(dest, math.max(crop_size * 2, options.max_size), mod)
dest = data_augmentation.flip(dest)
dest = data_augmentation.color_noise(dest, options.random_color_noise_rate)
dest = data_augmentation.overlay(dest, options.random_overlay_rate)
dest = data_augmentation.unsharp_mask(dest, options.random_unsharp_mask_rate)
else
dest = pairwise_transform_utils.random_half(dest, options.random_half_rate, options.downsampling_filters)
dest = pairwise_transform_utils.crop_if_large(dest, math.max(crop_size * 2, options.max_size))
dest = data_augmentation.flip(dest)
dest = data_augmentation.color_noise(dest, options.random_color_noise_rate)
dest = data_augmentation.overlay(dest, options.random_overlay_rate)
dest = data_augmentation.unsharp_mask(dest, options.random_unsharp_mask_rate)
dest = data_augmentation.shift_1px(dest)
end
return dest
end
function pairwise_transform_utils.active_cropping(x, y, lowres_y, size, scale, p, tries)
assert("x:size == y:size", x:size(2) * scale == y:size(2) and x:size(3) * scale == y:size(3))
assert("crop_size % scale == 0", size % scale == 0)
local r = torch.uniform()
local t = "float"
if x:type() == "torch.ByteTensor" then
t = "byte"
end
if p < r then
local xi = torch.random(1, x:size(3) - (size + 1)) * scale
local yi = torch.random(1, x:size(2) - (size + 1)) * scale
local yc = iproc.crop(y, xi, yi, xi + size, yi + size)
local xc = iproc.crop(x, xi / scale, yi / scale, xi / scale + size / scale, yi / scale + size / scale)
return xc, yc
else
local best_se = 0.0
local best_xi, best_yi
local m = torch.LongTensor(y:size(1), size, size)
local targets = {}
for i = 1, tries do
local xi = torch.random(1, x:size(3) - (size + 1)) * scale
local yi = torch.random(1, x:size(2) - (size + 1)) * scale
local xc = iproc.crop_nocopy(y, xi, yi, xi + size, yi + size)
local lc = iproc.crop_nocopy(lowres_y, xi, yi, xi + size, yi + size)
m:copy(xc:long()):csub(lc:long())
m:cmul(m)
local se = m:sum()
if se >= best_se then
best_xi = xi
best_yi = yi
best_se = se
end
end
local yc = iproc.crop(y, best_xi, best_yi, best_xi + size, best_yi + size)
local xc = iproc.crop(x, best_xi / scale, best_yi / scale, best_xi / scale + size / scale, best_yi / scale + size / scale)
return xc, yc
end
end
function pairwise_transform_utils.flip_augmentation(x, y, lowres_y, x_noise)
local xs = {}
local ns = {}
local ys = {}
local ls = {}
for j = 1, 2 do
-- TTA
local xi, yi, ri
if j == 1 then
xi = x
ni = x_noise
yi = y
ri = lowres_y
else
xi = x:transpose(2, 3):contiguous()
if x_noise then
ni = x_noise:transpose(2, 3):contiguous()
end
yi = y:transpose(2, 3):contiguous()
ri = lowres_y:transpose(2, 3):contiguous()
end
local xv = image.vflip(xi)
local nv
if x_noise then
nv = image.vflip(ni)
end
local yv = image.vflip(yi)
local rv = image.vflip(ri)
table.insert(xs, xi)
if ni then
table.insert(ns, ni)
end
table.insert(ys, yi)
table.insert(ls, ri)
table.insert(xs, xv)
if nv then
table.insert(ns, nv)
end
table.insert(ys, yv)
table.insert(ls, rv)
table.insert(xs, image.hflip(xi))
if ni then
table.insert(ns, image.hflip(ni))
end
table.insert(ys, image.hflip(yi))
table.insert(ls, image.hflip(ri))
table.insert(xs, image.hflip(xv))
if nv then
table.insert(ns, image.hflip(nv))
end
table.insert(ys, image.hflip(yv))
table.insert(ls, image.hflip(rv))
end
return xs, ys, ls, ns
end
return pairwise_transform_utils
|
require 'image'
local iproc = require 'iproc'
local data_augmentation = require 'data_augmentation'
local pairwise_transform_utils = {}
function pairwise_transform_utils.random_half(src, p, filters)
if torch.uniform() < p then
local filter = filters[torch.random(1, #filters)]
return iproc.scale(src, src:size(3) * 0.5, src:size(2) * 0.5, filter)
else
return src
end
end
function pairwise_transform_utils.crop_if_large(src, max_size, mod)
local tries = 4
if src:size(2) > max_size and src:size(3) > max_size then
assert(max_size % 4 == 0)
local rect
for i = 1, tries do
local yi = torch.random(0, src:size(2) - max_size)
local xi = torch.random(0, src:size(3) - max_size)
if mod then
yi = yi - (yi % mod)
xi = xi - (xi % mod)
end
rect = iproc.crop(src, xi, yi, xi + max_size, yi + max_size)
-- ignore simple background
if rect:float():std() >= 0 then
break
end
end
return rect
else
return src
end
end
function pairwise_transform_utils.preprocess(src, crop_size, options)
local dest = src
local box_only = false
if options.data.filters then
if #options.data.filters == 1 and options.data.filters[1] == "Box" then
box_only = true
end
end
if box_only then
local mod = 2 -- assert pos % 2 == 0
dest = pairwise_transform_utils.crop_if_large(dest, math.max(crop_size * 2, options.max_size), mod)
dest = data_augmentation.flip(dest)
dest = data_augmentation.color_noise(dest, options.random_color_noise_rate)
dest = data_augmentation.overlay(dest, options.random_overlay_rate)
dest = data_augmentation.unsharp_mask(dest, options.random_unsharp_mask_rate)
dest = iproc.crop_mod4(dest)
else
dest = pairwise_transform_utils.random_half(dest, options.random_half_rate, options.downsampling_filters)
dest = pairwise_transform_utils.crop_if_large(dest, math.max(crop_size * 2, options.max_size))
dest = data_augmentation.flip(dest)
dest = data_augmentation.color_noise(dest, options.random_color_noise_rate)
dest = data_augmentation.overlay(dest, options.random_overlay_rate)
dest = data_augmentation.unsharp_mask(dest, options.random_unsharp_mask_rate)
dest = data_augmentation.shift_1px(dest)
end
return dest
end
function pairwise_transform_utils.active_cropping(x, y, lowres_y, size, scale, p, tries)
assert("x:size == y:size", x:size(2) * scale == y:size(2) and x:size(3) * scale == y:size(3))
assert("crop_size % scale == 0", size % scale == 0)
local r = torch.uniform()
local t = "float"
if x:type() == "torch.ByteTensor" then
t = "byte"
end
if p < r then
local xi = torch.random(1, x:size(3) - (size + 1)) * scale
local yi = torch.random(1, x:size(2) - (size + 1)) * scale
local yc = iproc.crop(y, xi, yi, xi + size, yi + size)
local xc = iproc.crop(x, xi / scale, yi / scale, xi / scale + size / scale, yi / scale + size / scale)
return xc, yc
else
local best_se = 0.0
local best_xi, best_yi
local m = torch.LongTensor(y:size(1), size, size)
local targets = {}
for i = 1, tries do
local xi = torch.random(1, x:size(3) - (size + 1)) * scale
local yi = torch.random(1, x:size(2) - (size + 1)) * scale
local xc = iproc.crop_nocopy(y, xi, yi, xi + size, yi + size)
local lc = iproc.crop_nocopy(lowres_y, xi, yi, xi + size, yi + size)
m:copy(xc:long()):csub(lc:long())
m:cmul(m)
local se = m:sum()
if se >= best_se then
best_xi = xi
best_yi = yi
best_se = se
end
end
local yc = iproc.crop(y, best_xi, best_yi, best_xi + size, best_yi + size)
local xc = iproc.crop(x, best_xi / scale, best_yi / scale, best_xi / scale + size / scale, best_yi / scale + size / scale)
return xc, yc
end
end
function pairwise_transform_utils.flip_augmentation(x, y, lowres_y, x_noise)
local xs = {}
local ns = {}
local ys = {}
local ls = {}
for j = 1, 2 do
-- TTA
local xi, yi, ri
if j == 1 then
xi = x
ni = x_noise
yi = y
ri = lowres_y
else
xi = x:transpose(2, 3):contiguous()
if x_noise then
ni = x_noise:transpose(2, 3):contiguous()
end
yi = y:transpose(2, 3):contiguous()
ri = lowres_y:transpose(2, 3):contiguous()
end
local xv = image.vflip(xi)
local nv
if x_noise then
nv = image.vflip(ni)
end
local yv = image.vflip(yi)
local rv = image.vflip(ri)
table.insert(xs, xi)
if ni then
table.insert(ns, ni)
end
table.insert(ys, yi)
table.insert(ls, ri)
table.insert(xs, xv)
if nv then
table.insert(ns, nv)
end
table.insert(ys, yv)
table.insert(ls, rv)
table.insert(xs, image.hflip(xi))
if ni then
table.insert(ns, image.hflip(ni))
end
table.insert(ys, image.hflip(yi))
table.insert(ls, image.hflip(ri))
table.insert(xs, image.hflip(xv))
if nv then
table.insert(ns, image.hflip(nv))
end
table.insert(ys, image.hflip(yv))
table.insert(ls, image.hflip(rv))
end
return xs, ys, ls, ns
end
return pairwise_transform_utils
|
Fix a bug in preprocessing when filters=box only
|
Fix a bug in preprocessing when filters=box only
|
Lua
|
mit
|
Spitfire1900/upscaler,zyhkz/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,Spitfire1900/upscaler,zyhkz/waifu2x,zyhkz/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x
|
f405ea7ae81be4146034aab14b029a84d8b70995
|
src/lua/export/troff.lua
|
src/lua/export/troff.lua
|
-- © 2008 David Given.
-- WordGrinder is licensed under the MIT open source license. See the COPYING
-- file in this distribution for the full text.
local NextCharInWord = wg.nextcharinword
local ReadU8 = wg.readu8
local string_len = string.len
local string_char = string.char
local string_format = string.format
local string_gsub = string.gsub
local style_tab =
{
["H1"] = '.NH 1',
["H2"] = '.NH 2',
["H3"] = '.NH 3',
["H4"] = '.NH 4',
["P"] = '.LP',
["L"] = '.IP',
["LB"] = '.IP \\[bu]',
["Q"] = '.IP',
["V"] = '.IP',
["RAW"] = '',
["PRE"] = '.LD 1',
}
local function callback(writer, document)
local currentstyle = nil
local ul = false
local it = false
local bf = false
local embedded = false
local linestart = true
local function newline()
if not linestart then
writer("\n")
end
linestart = true
end
local function emit_text(s)
if linestart then
s = string_gsub(s, "^([.'])", '\\%1')
s = string_gsub(s, '^%s+', '')
linestart = false
end
if embedded then
s = string_gsub(s, '"', '\\"')
end
s = string_gsub(s, '\\', '\\\\')
local o = 1
local n = string_len(s)
while (o <= n) do
local c = ReadU8(s, o)
o = NextCharInWord(s, o)
if (c < 127) then
writer(string_char(c))
else
writer(string_format('\\[u%04X]', c))
end
end
end
local function changestate(newit, newul, newbf)
if newul and not ul then
newline()
writer('.UL "')
embedded = true
linestart = false
end
if newit and not newbf then
writer('\\fI')
elseif newit and newbf then
writer('\\f(BI')
elseif not newit and newbf then
writer('\\fB')
elseif not newit and not newbf and (it or bf) then
writer('\\fR')
end
if not newul and ul then
writer('"\n')
embedded = false
linestart = true
end
it = newit
ul = newul
bf = newbf
end
return ExportFileUsingCallbacks(document,
{
prologue = function()
writer('.\\" This document automatically generated by '..
'WordGrinder '..VERSION..'.\n')
writer('.\\" Use the .ms macro package!\n')
writer('.TL\n')
emit_text(Document.name)
writer('\n')
linestart = true
end,
text = emit_text,
rawtext = function(s)
writer(s)
end,
notext = function(s)
end,
italic_on = function()
changestate(true, ul, bf)
end,
italic_off = function()
changestate(false, ul, bf)
end,
underline_on = function()
changestate(it, true, bf)
end,
underline_off = function()
changestate(it, false, bf)
end,
bold_on = function()
changestate(it, ul, true)
end,
bold_off = function()
changestate(it, ul, false)
end,
list_start = function()
end,
list_end = function()
end,
paragraph_start = function(style)
if (currentstyle ~= "PRE") or (style ~= "PRE") then
if (currentstyle == "PRE") then
writer(".DE\n")
end
writer(style_tab[style] or ".LP")
writer('\n')
end
linestart = true
currentstyle = style
end,
paragraph_end = function(style)
newline()
end,
epilogue = function()
end
})
end
function Cmd.ExportTroffFile(filename)
return ExportFileWithUI(filename, "Export Troff File", ".tr",
callback)
end
|
-- © 2008 David Given.
-- WordGrinder is licensed under the MIT open source license. See the COPYING
-- file in this distribution for the full text.
local NextCharInWord = wg.nextcharinword
local ReadU8 = wg.readu8
local string_len = string.len
local string_char = string.char
local string_format = string.format
local string_gsub = string.gsub
local style_tab =
{
["H1"] = '.NH 1',
["H2"] = '.NH 2',
["H3"] = '.NH 3',
["H4"] = '.NH 4',
["P"] = '.LP',
["L"] = '.IP',
["LB"] = '.IP \\[bu]',
["Q"] = '.IP',
["V"] = '.IP',
["RAW"] = '',
["PRE"] = '.LD 1',
}
local function callback(writer, document)
local currentstyle = nil
local ul = false
local it = false
local bf = false
local embedded = false
local linestart = true
local function newline()
if not linestart then
writer("\n")
end
linestart = true
end
local function emit_text(s)
if linestart then
s = string_gsub(s, "^([.'])", '\\%1')
s = string_gsub(s, '^%s+', '')
linestart = false
end
if embedded then
s = string_gsub(s, '"', '\\"')
end
s = string_gsub(s, '\\', '\\\\')
local o = 1
local n = string_len(s)
while (o <= n) do
local c = ReadU8(s, o)
o = NextCharInWord(s, o)
if (c < 127) then
writer(string_char(c))
else
writer(string_format('\\[u%04X]', c))
end
end
end
local function changestate(newit, newul, newbf)
if newul and not ul then
newline()
writer('.UL "')
embedded = true
linestart = false
end
if newit and not newbf then
writer('\\fI')
linestart = false
elseif newit and newbf then
writer('\\f(BI')
linestart = false
elseif not newit and newbf then
writer('\\fB')
linestart = false
elseif not newit and not newbf and (it or bf) then
writer('\\fR')
linestart = false
end
if not newul and ul then
writer('"\n')
embedded = false
linestart = true
end
it = newit
ul = newul
bf = newbf
end
return ExportFileUsingCallbacks(document,
{
prologue = function()
writer('.\\" This document automatically generated by '..
'WordGrinder '..VERSION..'.\n')
writer('.\\" Use the .ms macro package!\n')
writer('.TL\n')
emit_text(Document.name)
writer('\n')
linestart = true
end,
text = emit_text,
rawtext = function(s)
writer(s)
end,
notext = function(s)
end,
italic_on = function()
changestate(true, ul, bf)
end,
italic_off = function()
changestate(false, ul, bf)
end,
underline_on = function()
changestate(it, true, bf)
end,
underline_off = function()
changestate(it, false, bf)
end,
bold_on = function()
changestate(it, ul, true)
end,
bold_off = function()
changestate(it, ul, false)
end,
list_start = function()
end,
list_end = function()
end,
paragraph_start = function(style)
if (currentstyle ~= "PRE") or (style ~= "PRE") then
if (currentstyle == "PRE") then
writer(".DE\n")
end
writer(style_tab[style] or ".LP")
writer('\n')
end
linestart = true
currentstyle = style
end,
paragraph_end = function(style)
newline()
end,
epilogue = function()
end
})
end
function Cmd.ExportTroffFile(filename)
return ExportFileWithUI(filename, "Export Troff File", ".tr",
callback)
end
|
Fix minor bug in troff output.
|
Fix minor bug in troff output.
|
Lua
|
mit
|
Munchotaur/wordgrinder,rodoviario/wordgrinder,rodoviario/wordgrinder,NRauh/wordgrinder,NRauh/wordgrinder,Munchotaur/wordgrinder
|
2f5c77f2a763cf51e91de67c2d81a1b00096782b
|
src/program/ipfix/probe/probe.lua
|
src/program/ipfix/probe/probe.lua
|
-- This module implements the `snabb flow_export` command
module(..., package.seeall)
local now = require("core.app").now
local lib = require("core.lib")
local link = require("core.link")
local arp = require("apps.ipv4.arp")
local ipfix = require("apps.ipfix.ipfix")
local ipv4 = require("lib.protocol.ipv4")
local ethernet = require("lib.protocol.ethernet")
local numa = require("lib.numa")
-- apps that can be used as an input or output for the exporter
local in_apps, out_apps = {}, {}
function in_apps.pcap (path)
return { input = "input",
output = "output" },
{ require("apps.pcap.pcap").PcapReader, path }
end
function out_apps.pcap (path)
return { input = "input",
output = "output" },
{ require("apps.pcap.pcap").PcapWriter, path }
end
function in_apps.raw (device)
return { input = "rx",
output = "tx" },
{ require("apps.socket.raw").RawSocket, device }
end
out_apps.raw = in_apps.raw
function in_apps.intel10g (device)
local conf = { pciaddr = device }
return { input = "rx",
output = "tx" },
{ require("apps.intel.intel_app").Intel82599, conf }
end
out_apps.intel10g = in_apps.intel10g
local long_opts = {
help = "h",
duration = "D",
port = "p",
transport = 1,
["host-ip"] = "a",
["input-type"] = "i",
["output-type"] = "o",
["netflow-v9"] = 0,
["ipfix"] = 0,
["active-timeout"] = 1,
["idle-timeout"] = 1,
["cpu"] = 1
}
function run (args)
local duration
local input_type, output_type = "intel10g", "intel10g"
local host_mac
local host_ip = '10.0.0.1' -- Just to have a default.
local collector_ip = '10.0.0.2' -- Likewise.
local port = 4739
local active_timeout, idle_timeout
local ipfix_version = 10
local cpu
-- TODO: better input validation
local opt = {
h = function (arg)
print(require("program.ipfix.probe.README_inc"))
main.exit(0)
end,
D = function (arg)
duration = assert(tonumber(arg), "expected number for duration")
end,
i = function (arg)
assert(in_apps[arg], "unknown input type")
input_type = arg
end,
o = function (arg)
assert(out_apps[arg], "unknown output type")
output_type = arg
end,
p = function (arg)
port = assert(tonumber(arg), "expected number for port")
end,
m = function (arg)
host_mac = arg
end,
a = function (arg)
host_ip = arg
end,
c = function (arg)
collector_ip = arg
end,
["active-timeout"] = function (arg)
active_timeout =
assert(tonumber(arg), "expected number for active timeout")
end,
["idle-timeout"] = function (arg)
idle_timeout =
assert(tonumber(arg), "expected number for idle timeout")
end,
ipfix = function (arg)
ipfix_version = 10
end,
["netflow-v9"] = function (arg)
ipfix_version = 9
end,
-- TODO: not implemented
["transport"] = function (arg) end,
["cpu"] = function (arg)
cpu = tonumber(arg)
end
}
args = lib.dogetopt(args, opt, "hD:i:o:p:m:a:c:", long_opts)
if #args ~= 2 then
print(require("program.ipfix.probe.README_inc"))
main.exit(1)
end
local in_link, in_app = in_apps[input_type](args[1])
local out_link, out_app = out_apps[output_type](args[2])
local arp_config = { self_mac = host_mac and ethernet:pton(host_mac),
self_ip = ipv4:pton(host_ip),
next_ip = ipv4:pton(collector_ip) }
local ipfix_config = { active_timeout = active_timeout,
idle_timeout = idle_timeout,
ipfix_version = ipfix_version,
exporter_ip = host_ip,
collector_ip = collector_ip,
collector_port = port }
local c = config.new()
config.app(c, "source", unpack(in_app))
config.app(c, "arp", arp.ARP, arp_config)
config.app(c, "ipfix", ipfix.IPFIX, ipfix_config)
config.app(c, "sink", unpack(out_app))
config.link(c, "source." .. in_link.output .. " -> arp.south")
config.link(c, "arp.north -> ipfix.input")
config.link(c, "ipfix.output -> arp.north")
config.link(c, "arp.south -> sink." .. out_link.input)
local done
if not duration then
done = function ()
return engine.app_table.source.done
end
end
local t1 = now()
if cpu then numa.bind_to_cpu(cpu) end
engine.configure(c)
engine.busywait = true
engine.main({ duration = duration, done = done })
local t2 = now()
local stats = link.stats(engine.app_table.ipfix.input.input)
print("IPFIX probe stats:")
local comma = lib.comma_value
print(string.format("bytes: %s packets: %s bps: %s Mpps: %s",
comma(stats.rxbytes),
comma(stats.rxpackets),
comma(math.floor((stats.rxbytes * 8) / (t2 - t1))),
comma(stats.rxpackets / ((t2 - t1) * 1000000))))
end
|
-- This module implements the `snabb flow_export` command
module(..., package.seeall)
local now = require("core.app").now
local lib = require("core.lib")
local link = require("core.link")
local basic = require("apps.basic.basic_apps")
local arp = require("apps.ipv4.arp")
local ipfix = require("apps.ipfix.ipfix")
local ipv4 = require("lib.protocol.ipv4")
local ethernet = require("lib.protocol.ethernet")
local numa = require("lib.numa")
-- apps that can be used as an input or output for the exporter
local in_apps, out_apps = {}, {}
function in_apps.pcap (path)
return { input = "input",
output = "output" },
{ require("apps.pcap.pcap").PcapReader, path }
end
function out_apps.pcap (path)
return { input = "input",
output = "output" },
{ require("apps.pcap.pcap").PcapWriter, path }
end
function in_apps.raw (device)
return { input = "rx",
output = "tx" },
{ require("apps.socket.raw").RawSocket, device }
end
out_apps.raw = in_apps.raw
function in_apps.intel10g (device)
local conf = { pciaddr = device }
return { input = "rx",
output = "tx" },
{ require("apps.intel.intel_app").Intel82599, conf }
end
out_apps.intel10g = in_apps.intel10g
local long_opts = {
help = "h",
duration = "D",
port = "p",
transport = 1,
["host-ip"] = "a",
["input-type"] = "i",
["output-type"] = "o",
["netflow-v9"] = 0,
["ipfix"] = 0,
["active-timeout"] = 1,
["idle-timeout"] = 1,
["cpu"] = 1
}
function run (args)
local duration
local input_type, output_type = "intel10g", "intel10g"
local host_mac
local host_ip = '10.0.0.1' -- Just to have a default.
local collector_ip = '10.0.0.2' -- Likewise.
local port = 4739
local active_timeout, idle_timeout
local ipfix_version = 10
local cpu
-- TODO: better input validation
local opt = {
h = function (arg)
print(require("program.ipfix.probe.README_inc"))
main.exit(0)
end,
D = function (arg)
duration = assert(tonumber(arg), "expected number for duration")
end,
i = function (arg)
assert(in_apps[arg], "unknown input type")
input_type = arg
end,
o = function (arg)
assert(out_apps[arg], "unknown output type")
output_type = arg
end,
p = function (arg)
port = assert(tonumber(arg), "expected number for port")
end,
m = function (arg)
host_mac = arg
end,
a = function (arg)
host_ip = arg
end,
c = function (arg)
collector_ip = arg
end,
["active-timeout"] = function (arg)
active_timeout =
assert(tonumber(arg), "expected number for active timeout")
end,
["idle-timeout"] = function (arg)
idle_timeout =
assert(tonumber(arg), "expected number for idle timeout")
end,
ipfix = function (arg)
ipfix_version = 10
end,
["netflow-v9"] = function (arg)
ipfix_version = 9
end,
-- TODO: not implemented
["transport"] = function (arg) end,
["cpu"] = function (arg)
cpu = tonumber(arg)
end
}
args = lib.dogetopt(args, opt, "hD:i:o:p:m:a:c:", long_opts)
if #args ~= 2 then
print(require("program.ipfix.probe.README_inc"))
main.exit(1)
end
local in_link, in_app = in_apps[input_type](args[1])
local out_link, out_app = out_apps[output_type](args[2])
local arp_config = { self_mac = host_mac and ethernet:pton(host_mac),
self_ip = ipv4:pton(host_ip),
next_ip = ipv4:pton(collector_ip) }
local ipfix_config = { active_timeout = active_timeout,
idle_timeout = idle_timeout,
ipfix_version = ipfix_version,
exporter_ip = host_ip,
collector_ip = collector_ip,
collector_port = port }
local c = config.new()
config.app(c, "in", unpack(in_app))
config.app(c, "ipfix", ipfix.IPFIX, ipfix_config)
config.app(c, "out", unpack(out_app))
-- use ARP for link-layer concerns unless the output is connected
-- to a pcap writer
if output_type ~= "pcap" then
config.app(c, "arp", arp.ARP, arp_config)
config.app(c, "sink", basic.Sink)
config.link(c, "in." .. in_link.output .. " -> ipfix.input")
config.link(c, "out." .. out_link.output .. " -> arp.south")
-- with UDP, ipfix doesn't need to handle packets from the collector
config.link(c, "arp.north -> sink.input")
config.link(c, "ipfix.output -> arp.north")
config.link(c, "arp.south -> out." .. out_link.input)
else
config.link(c, "in." .. in_link.output .. " -> ipfix.input")
config.link(c, "ipfix.output -> out." .. out_link.input)
end
local done
if not duration then
done = function ()
return engine.app_table.source.done
end
end
local t1 = now()
if cpu then numa.bind_to_cpu(cpu) end
engine.configure(c)
engine.busywait = true
engine.main({ duration = duration, done = done })
local t2 = now()
local stats = link.stats(engine.app_table.ipfix.input.input)
print("IPFIX probe stats:")
local comma = lib.comma_value
print(string.format("bytes: %s packets: %s bps: %s Mpps: %s",
comma(stats.rxbytes),
comma(stats.rxpackets),
comma(math.floor((stats.rxbytes * 8) / (t2 - t1))),
comma(stats.rxpackets / ((t2 - t1) * 1000000))))
end
|
Fix app configuration in ipfix probe
|
Fix app configuration in ipfix probe
When ARP is used (non-pcap cases), the output app should also
feedback into the arp app so that arp replies are actually
accepted.
|
Lua
|
apache-2.0
|
Igalia/snabb,snabbco/snabb,SnabbCo/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,eugeneia/snabbswitch,dpino/snabbswitch,eugeneia/snabb,Igalia/snabbswitch,eugeneia/snabbswitch,Igalia/snabb,SnabbCo/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,dpino/snabb,eugeneia/snabb,Igalia/snabbswitch,snabbco/snabb,Igalia/snabb,dpino/snabb,snabbco/snabb,dpino/snabb,Igalia/snabbswitch,Igalia/snabbswitch,alexandergall/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,eugeneia/snabb,Igalia/snabbswitch,eugeneia/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,snabbco/snabb,dpino/snabbswitch,dpino/snabb,dpino/snabbswitch,dpino/snabb,dpino/snabb,snabbco/snabb,eugeneia/snabb,snabbco/snabb,alexandergall/snabbswitch,SnabbCo/snabbswitch,eugeneia/snabbswitch,SnabbCo/snabbswitch,dpino/snabb,Igalia/snabb,eugeneia/snabb,alexandergall/snabbswitch,Igalia/snabb,eugeneia/snabb,Igalia/snabb,alexandergall/snabbswitch,eugeneia/snabb,dpino/snabbswitch,eugeneia/snabb
|
a214fda184cc74f2146dc63dc90cd271e78570ac
|
control.lua
|
control.lua
|
require "defines"
function is_array(t)
-- From: https://ericjmritz.name/2014/02/26/lua-is_array/
local i = 0
for _ in pairs(t) do
i = i + 1
if t[i] == nil then return false end
end
return true
end
remote.add_interface("timelapse",
{
active = function(bool)
if bool == nil then
game.player.print(string.format("Active = %s", global.timelapse.active))
elseif type(bool) ~= "boolean" then
game.player.print("Argument must be a boolean")
else
global.timelapse.active = bool
if bool == true then
game.player.print("Timelapse activated")
else
game.player.print("Timelapse deactivated")
end
end
end,
interval = function(seconds)
if seconds == nil then
game.player.print(string.format("Interval = %is", global.timelapse.interval / 60))
elseif type(seconds) ~= "number" then
game.player.print("Argument must be a number")
else
if seconds < 10 then
game.player.print("Argument must be >= 10")
else
global.timelapse.interval = 60 * seconds
end
end
end,
position = function(position)
if position == nil then
game.player.print(string.format("Position = {x=%.2f, y=%.2f}", global.timelapse.position.x, global.timelapse.position.y))
elseif type(position) ~= "table" then
game.player.print("Argument must be a table")
else
local x, y = 0, 0
if is_array(position) then
x, y = position[1], position[2]
else
x, y = position.x, position.y
end
if type(x) ~= "number" or type(y) ~= "number" then
game.player.print("Argument must be a table whose values are numbers")
else
global.timelapse.position = {x=x, y=y}
end
end
end,
resolution = function(resolution)
if resolution == nil then
game.player.print(string.format("Resolution = %ix%i", global.timelapse.resolution.x, global.timelapse.resolution.y))
elseif type(resolution) ~= "table" then
game.player.print("Argument must be a table")
else
local x, y = 1920, 1080
if is_array(resolution) then
x, y = resolution[1], resolution[2]
else
x, y = resolution.x, resolution.y
end
if type(x) ~= "number" or type(y) ~= "number" then
game.player.print("Argument must be a table whose values are numbers")
elseif x < 10 or y < 10 then
game.player.print("Argument must be a table whose values are >= 10")
else
global.timelapse.resolution = {x=x, y=y}
end
end
end,
zoom = function(zoom)
if zoom == nil then
game.player.print(string.format("Zoom = %.2f", global.timelapse.zoom))
elseif type(zoom) ~= "number" then
game.player.print("Argument must be a number")
else
if zoom >= 0.1 and zoom <= 3 then
global.timelapse.zoom = zoom
else
game.player.print("Argument must be a number >= 0.1 and <= 3")
end
end
end,
show_entity_info = function(bool)
if bool == nil then
game.player.print(string.format("Show Entity Info = %s", global.timelapse.show_entity_info))
elseif type(bool) ~= "boolean" then
game.player.print("Argument must be a boolean")
else
global.timelapse.show_entity_info = bool
end
end,
data = function()
local d = global.timelapse
local s = string.format("Timelapse: \z
Count = %i, Active = %s, Interval = %is, \z
Position = {x=%.2f, y=%.2f}, Resolution = %ix%i, \z
Zoom = %.2f, Show Entity Info = %s",
d.count, d.active, d.interval / 60,
d.position.x, d.position.y, d.resolution.x, d.resolution.y,
d.zoom, d.show_entity_info)
game.player.print(s)
end,
reset = function()
init_timelapse()
end,
})
function init_timelapse()
global.timelapse = {
count = 0,
active = false,
-- interval = 60 ticks per seconds * number of seconds between shots
interval = 60 * 30,
-- The spawn is at {0, 0} by default
position = {x=0, y=0},
resolution = {x=1920, y=1080},
-- zoom (default: 1, minimum scrollable to in game: 0.29)
zoom = 0.1,
show_entity_info = false,
}
end
script.on_init(function()
init_timelapse()
end)
script.on_load(function()
if global.timelapse == nil then
init_timelapse()
end
end)
script.on_configuration_changed(function(data)
init_timelapse()
end)
-- Derived from util.formattime
function ftime(ticks)
local sec = ticks / 60
local hours = math.floor(sec / 3600)
local minutes = math.floor(sec / 60 - hours * 60)
local seconds = math.floor(sec - hours * 3600 - minutes * 60)
return string.format("%02d_%02d_%02d", hours, minutes, seconds)
end
function take_shot()
global.timelapse.count = global.timelapse.count + 1
local seed = game.player.surface.map_gen_settings.seed
local outf = string.format("timelapse/%u_%010u_%s.png", seed, game.tick, ftime(game.tick))
game.player.print(string.format("x%u -> %q", global.timelapse.count, outf))
game.take_screenshot{
player = nil,
position = global.timelapse.position,
resolution = global.timelapse.resolution,
zoom = global.timelapse.zoom,
path = outf,
show_gui = false,
show_entity_info = global.timelapse.show_entity_info}
end
script.on_event(defines.events.on_tick, function(event)
if global.timelapse.active then
if game.tick % global.timelapse.interval == 0 then
take_shot()
end
end
end)
|
require "defines"
local state = 0
local current_time = 1.0
function is_array(t)
-- From: https://ericjmritz.name/2014/02/26/lua-is_array/
local i = 0
for _ in pairs(t) do
i = i + 1
if t[i] == nil then return false end
end
return true
end
remote.add_interface("timelapse",
{
active = function(bool)
if bool == nil then
game.player.print(string.format("Active = %s", global.timelapse.active))
elseif type(bool) ~= "boolean" then
game.player.print("Argument must be a boolean")
else
global.timelapse.active = bool
if bool == true then
game.player.print("Timelapse activated")
else
game.player.print("Timelapse deactivated")
end
end
end,
interval = function(seconds)
if seconds == nil then
game.player.print(string.format("Interval = %is", global.timelapse.interval / 60))
elseif type(seconds) ~= "number" then
game.player.print("Argument must be a number")
else
if seconds < 10 then
game.player.print("Argument must be >= 10")
else
global.timelapse.interval = 60 * seconds
end
end
end,
position = function(position)
if position == nil then
game.player.print(string.format("Position = {x=%.2f, y=%.2f}", global.timelapse.position.x, global.timelapse.position.y))
elseif type(position) ~= "table" then
game.player.print("Argument must be a table")
else
local x, y = 0, 0
if is_array(position) then
x, y = position[1], position[2]
else
x, y = position.x, position.y
end
if type(x) ~= "number" or type(y) ~= "number" then
game.player.print("Argument must be a table whose values are numbers")
else
global.timelapse.position = {x=x, y=y}
end
end
end,
resolution = function(resolution)
if resolution == nil then
game.player.print(string.format("Resolution = %ix%i", global.timelapse.resolution.x, global.timelapse.resolution.y))
elseif type(resolution) ~= "table" then
game.player.print("Argument must be a table")
else
local x, y = 1920, 1080
if is_array(resolution) then
x, y = resolution[1], resolution[2]
else
x, y = resolution.x, resolution.y
end
if type(x) ~= "number" or type(y) ~= "number" then
game.player.print("Argument must be a table whose values are numbers")
elseif x < 10 or y < 10 then
game.player.print("Argument must be a table whose values are >= 10")
else
global.timelapse.resolution = {x=x, y=y}
end
end
end,
zoom = function(zoom)
if zoom == nil then
game.player.print(string.format("Zoom = %.2f", global.timelapse.zoom))
elseif type(zoom) ~= "number" then
game.player.print("Argument must be a number")
else
if zoom >= 0.1 and zoom <= 3 then
global.timelapse.zoom = zoom
else
game.player.print("Argument must be a number >= 0.1 and <= 3")
end
end
end,
show_entity_info = function(bool)
if bool == nil then
game.player.print(string.format("Show Entity Info = %s", global.timelapse.show_entity_info))
elseif type(bool) ~= "boolean" then
game.player.print("Argument must be a boolean")
else
global.timelapse.show_entity_info = bool
end
end,
data = function()
local d = global.timelapse
local s = string.format("Timelapse: \z
Count = %i, Active = %s, \z
Light Mode = %s, Fixed Light = %.2f, \z
Interval = %is, \z
Position = {x=%.2f, y=%.2f}, \z
Resolution = %ix%i, \z
Zoom = %.2f, Show Entity Info = %s",
d.count, d.active,
d.light_mode, d.fixed_light,
d.interval / 60,
d.position.x, d.position.y,
d.resolution.x, d.resolution.y,
d.zoom, d.show_entity_info)
game.player.print(s)
end,
reset = function()
init_timelapse()
end,
})
function init_timelapse()
global.timelapse = {
count = 0,
active = false,
light_mode = "fixed",
fixed_light = 1.0,
-- interval = 60 ticks per seconds * number of seconds between shots
interval = 60 * 30,
-- The spawn is at {0, 0} by default
position = {x=0, y=0},
resolution = {x=1920, y=1080},
-- zoom (default: 1, minimum scrollable to in game: 0.29)
zoom = 0.1,
show_entity_info = false,
}
end
script.on_init(function()
init_timelapse()
end)
script.on_load(function()
if global.timelapse == nil then
init_timelapse()
end
end)
script.on_configuration_changed(function(data)
init_timelapse()
end)
-- Derived from util.formattime
function ftime(ticks)
local sec = ticks / 60
local hours = math.floor(sec / 3600)
local minutes = math.floor(sec / 60 - hours * 60)
local seconds = math.floor(sec - hours * 3600 - minutes * 60)
return string.format("%02d_%02d_%02d", hours, minutes, seconds)
end
function take_shot()
global.timelapse.count = global.timelapse.count + 1
local seed = game.player.surface.map_gen_settings.seed
local outf = string.format("timelapse/%u_%010u_%s.png", seed, game.tick, ftime(game.tick))
game.player.print(string.format("x%u -> %q", global.timelapse.count, outf))
game.take_screenshot{
player = nil,
position = global.timelapse.position,
resolution = global.timelapse.resolution,
zoom = global.timelapse.zoom,
path = outf,
show_gui = false,
show_entity_info = global.timelapse.show_entity_info}
end
function light()
local d = global.timelapse
if d.light_mode == "fixed" then
current_time = game.daytime
local s = string.format("Timelapse: light: %.2f -> %.2f", current_time, d.fixed_light)
game.player.print(s)
game.daytime = d.fixed_light
end
end
function unlight()
local d = global.timelapse
if d.light_mode == "fixed" then
local s = string.format("Timelapse: unlight: %.2f -> %.2f", d.fixed_light, current_time)
game.player.print(s)
game.daytime = current_time
end
end
script.on_event(defines.events.on_tick, function(event)
if global.timelapse.active then
if (game.tick + 1) % global.timelapse.interval == 0 then
light()
state = 1
elseif state == 1 then
take_shot()
state = 2
elseif state == 2 then
unlight()
state = 0
end
end
end)
|
Add basic fixed light mode functionality
|
Add basic fixed light mode functionality
|
Lua
|
mit
|
david-wm-sanders/factorio-timelapse
|
8c7c7f131c0877b1464f044dd983090d41a78059
|
src/remy/cgilua.lua
|
src/remy/cgilua.lua
|
-- Remy - CGI-Lua compatibility
-- Copyright (c) 2014 Felipe Daragon
-- License: MIT
require "base64"
-- TODO: implement all functions from mod_lua's request_rec
local request = {
-- ENCODING/DECODING FUNCTIONS
base64_decode = function(_,...) return base64.decode(...) end,
base64_encode = function(_,...) return base64.encode(...) end,
escape = function(_,...) return cgilua.urlcode.escape(...) end,
unescape = function(_,...) return cgilua.urlcode.unescape(...) end,
-- REQUEST PARSING FUNCTIONS
parseargs = function(_) return cgilua.QUERY, {} end,
parsebody = function(_) return cgilua.POST, {} end,
-- REQUEST RESPONSE FUNCTIONS
--puts = function(_,...) cgilua.put(...) end,
--write = function(_,...) cgilua.print(...) end
puts = function(_,...) remy.print(...) end,
write = function(_,...) remy.print(...) end
}
local M = {
mode = "cgilua",
request = request
}
function M.init()
local r = request
local query = cgilua.servervariable("QUERY_STRING")
local port = cgilua.servervariable("SERVER_PORT")
local server_name = cgilua.servervariable("SERVER_NAME")
local path_info = M.getpathinfo()
apache2.version = cgilua.servervariable("SERVER_SOFTWARE")
r = remy.loadrequestrec(r)
r.ap_auth_type = cgilua.servervariable("AUTH_TYPE")
if query ~= nil and query ~= '' then
r.args = query
end
r.banner = apache2.version
r.canonical_filename = cgilua.script_path
r.content_type = "text/html" -- CGILua needs a default content_type
r.context_document_root = cgilua.script_pdir
r.document_root = cgilua.script_pdir
r.filename = cgilua.script_path
r.hostname = server_name
r.method = cgilua.servervariable("REQUEST_METHOD")
r.path_info = path_info
if port ~= nil then
r.port = tonumber(port)
if r.port == 443 then
r.is_https = true
end
end
r.protocol = cgilua.servervariable("SERVER_PROTOCOL")
r.range = cgilua.servervariable("HTTP_RANGE")
r.server_name = server_name
r.started = os.time()
r.the_request = r.method..' '..M.getunparseduri()..' '..r.protocol
r.unparsed_uri = M.getunparseduri()
r.uri = path_info
r.user = cgilua.servervariable("REMOTE_USER")
r.useragent_ip = cgilua.servervariable("REMOTE_ADDR")
end
function M.getpathinfo()
local p = cgilua.servervariable("PATH_INFO")
-- Xavante compatibility fix (Etiene)
if cgilua.servervariable("SERVER_NAME") == "" then
-- By default, Xavante will have an empty server name
-- A more accurate detection method is needed here
p = cgilua.urlpath
end
if p == nil then
p = cgilua.servervariable("SCRIPT_NAME")
end
return p
end
function M.getunparseduri()
local uri = M.getpathinfo()
local query = cgilua.servervariable("QUERY_STRING")
if query ~= nil and query ~= '' then
uri = uri..'?'..query
end
return uri
end
function M.contentheader(content_type)
local r = request
r.content_type = content_type
end
-- TODO: better handle the return code
function M.finish(code)
local r = request
-- Handle page redirect
local location = r.headers_out['Location']
if location ~= nil and r.status == 302 then
if location:match('^https?://') then
cgilua.redirect(location)
else
-- CGILua needs a full URL
if r.is_https then
location = 'https://'..cgilua.servervariable("HTTP_HOST")..location
else
location = 'http://'..cgilua.servervariable("HTTP_HOST")..location
end
cgilua.redirect(location)
end
end
-- Prints the response text (if any)
if r.content_type == "text/html" then
cgilua.htmlheader()
else
local header_sep = "/"
local header_type = remy.splitstring(r.content_type,header_sep)[1]
local header_subtype = remy.splitstring(r.content_type,header_sep)[2]
cgilua.contentheader(header_type,header_subtype)
end
if remy.responsetext ~= nil then
cgilua.print(remy.responsetext)
end
end
return M
|
-- Remy - CGI-Lua compatibility
-- Copyright (c) 2014 Felipe Daragon
-- License: MIT
require "base64"
-- TODO: implement all functions from mod_lua's request_rec
local request = {
-- ENCODING/DECODING FUNCTIONS
base64_decode = function(_,...) return base64.decode(...) end,
base64_encode = function(_,...) return base64.encode(...) end,
escape = function(_,...) return cgilua.urlcode.escape(...) end,
unescape = function(_,...) return cgilua.urlcode.unescape(...) end,
-- REQUEST PARSING FUNCTIONS
parseargs = function(_) return cgilua.QUERY, {} end,
parsebody = function(_) return cgilua.POST, {} end,
-- REQUEST RESPONSE FUNCTIONS
--puts = function(_,...) cgilua.put(...) end,
--write = function(_,...) cgilua.print(...) end
puts = function(_,...) remy.print(...) end,
write = function(_,...) remy.print(...) end
}
local M = {
mode = "cgilua",
request = request
}
function M.init()
local r = request
local query = cgilua.servervariable("QUERY_STRING")
local port = cgilua.servervariable("SERVER_PORT")
local server_name = cgilua.servervariable("SERVER_NAME")
local path_info = M.getpathinfo()
apache2.version = cgilua.servervariable("SERVER_SOFTWARE")
r = remy.loadrequestrec(r)
r.ap_auth_type = cgilua.servervariable("AUTH_TYPE")
if query ~= nil and query ~= '' then
r.args = query
end
r.banner = apache2.version
r.canonical_filename = cgilua.script_path
r.content_type = "text/html" -- CGILua needs a default content_type
r.context_document_root = cgilua.script_pdir
r.document_root = cgilua.script_pdir
r.filename = cgilua.script_path
r.hostname = server_name
r.method = cgilua.servervariable("REQUEST_METHOD")
r.path_info = path_info
if port ~= nil then
r.port = tonumber(port)
if r.port == 443 then
r.is_https = true
end
end
r.protocol = cgilua.servervariable("SERVER_PROTOCOL")
r.range = cgilua.servervariable("HTTP_RANGE")
r.server_name = server_name
r.started = os.time()
r.the_request = r.method..' '..M.getunparseduri()..' '..r.protocol
r.unparsed_uri = M.getunparseduri()
r.uri = path_info
r.user = cgilua.servervariable("REMOTE_USER")
r.useragent_ip = cgilua.servervariable("REMOTE_ADDR")
end
function M.getpathinfo()
local p = cgilua.servervariable("PATH_INFO")
--Xavante compatibility fix (Etiene)
if cgilua.servervariable("SERVER_SOFTWARE"):match('^Xavante')then
p = cgilua.urlpath
end
if p == nil then
p = cgilua.servervariable("SCRIPT_NAME")
end
return p
end
function M.getunparseduri()
local uri = M.getpathinfo()
local query = cgilua.servervariable("QUERY_STRING")
if query ~= nil and query ~= '' then
uri = uri..'?'..query
end
return uri
end
function M.contentheader(content_type)
local r = request
r.content_type = content_type
end
-- TODO: better handle the return code
function M.finish(code)
local r = request
-- Handle page redirect
local location = r.headers_out['Location']
if location ~= nil and r.status == 302 then
if location:match('^https?://') then
cgilua.redirect(location)
else
-- CGILua needs a full URL
if r.is_https then
location = 'https://'..cgilua.servervariable("HTTP_HOST")..location
else
location = 'http://'..cgilua.servervariable("HTTP_HOST")..location
end
cgilua.redirect(location)
end
end
-- Prints the response text (if any)
if r.content_type == "text/html" then
cgilua.htmlheader()
else
local header_sep = "/"
local header_type = remy.splitstring(r.content_type,header_sep)[1]
local header_subtype = remy.splitstring(r.content_type,header_sep)[2]
cgilua.contentheader(header_type,header_subtype)
end
if remy.responsetext ~= nil then
cgilua.print(remy.responsetext)
end
end
return M
|
Fixing Remy's xavante recognizer
|
Fixing Remy's xavante recognizer
|
Lua
|
mit
|
jeary/sailor,felipedaragon/sailor,ignacio/sailor,ignacio/sailor,Etiene/sailor,sailorproject/sailor,felipedaragon/sailor,Etiene/sailor,mpeterv/sailor,mpeterv/sailor,hallison/sailor,noname007/sailor
|
e1b0324e93bb8abcc841c8a40afe0a4e90476dff
|
src/lib/fibers/sleep.lua
|
src/lib/fibers/sleep.lua
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
-- Timeout events.
module(..., package.seeall)
local op = require('lib.fibers.op')
local fiber = require('lib.fibers.fiber')
local now = fiber.now
local Timeout = {}
Timeout.__index = Timeout
function sleep_until_op(t)
local function try()
return t <= now()
end
local function block(suspension, wrap_fn)
suspension.sched:schedule_at_time(t, suspension:complete_task(wrap_fn))
end
return op.new_base_op(nil, try, block)
end
function sleep_until(t)
return sleep_until_op(t):perform()
end
function sleep_op(dt)
local function try() return dt <= 0 end
local function block(suspension, wrap_fn)
suspension.sched:schedule_after_sleep(dt, suspension:complete_task(wrap_fn))
end
return op.new_base_op(nil, try, block)
end
function sleep(dt)
return sleep_op(dt):perform()
end
function selftest()
print('selftest: lib.fibers.sleep')
local done = {}
local count = 1e3
for i=1,count do
local function fn()
local start, dt = now(), math.random()
sleep(dt)
assert(now() >= start + dt)
table.insert(done, i)
end
fiber.spawn(fn)
end
for t=now(),now()+1.5,0.01 do
fiber.current_scheduler:schedule_expired_timers(t)
fiber.current_scheduler:run()
end
assert(#done == count)
print('selftest: ok')
end
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
-- Timeout events.
module(..., package.seeall)
local op = require('lib.fibers.op')
local fiber = require('lib.fibers.fiber')
local now = fiber.now
local Timeout = {}
Timeout.__index = Timeout
function sleep_until_op(t)
local function try()
return t <= now()
end
local function block(suspension, wrap_fn)
suspension.sched:schedule_at_time(t, suspension:complete_task(wrap_fn))
end
return op.new_base_op(nil, try, block)
end
function sleep_until(t)
return sleep_until_op(t):perform()
end
function sleep_op(dt)
local function try() return dt <= 0 end
local function block(suspension, wrap_fn)
suspension.sched:schedule_after_sleep(dt, suspension:complete_task(wrap_fn))
end
return op.new_base_op(nil, try, block)
end
function sleep(dt)
return sleep_op(dt):perform()
end
function selftest()
print('selftest: lib.fibers.sleep')
local done = {}
local count = 1e3
for i=1,count do
local function fn()
local start, dt = now(), math.random()
sleep(dt)
assert(now() >= start + dt)
table.insert(done, i)
end
fiber.spawn(fn)
end
for t=now(),now()+1.5,0.01 do
fiber.current_scheduler:run(t)
end
assert(#done == count)
print('selftest: ok')
end
|
Fix fibers sleep self-test
|
Fix fibers sleep self-test
|
Lua
|
apache-2.0
|
alexandergall/snabbswitch,eugeneia/snabb,alexandergall/snabbswitch,Igalia/snabb,snabbco/snabb,eugeneia/snabb,Igalia/snabbswitch,snabbco/snabb,Igalia/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,snabbco/snabb,eugeneia/snabb,alexandergall/snabbswitch,Igalia/snabb,Igalia/snabb,SnabbCo/snabbswitch,Igalia/snabb,Igalia/snabbswitch,SnabbCo/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,eugeneia/snabb,SnabbCo/snabbswitch,Igalia/snabb,eugeneia/snabb,Igalia/snabb,snabbco/snabb,snabbco/snabb,alexandergall/snabbswitch,eugeneia/snabb,Igalia/snabb,snabbco/snabb,alexandergall/snabbswitch,eugeneia/snabb,Igalia/snabbswitch,Igalia/snabbswitch,eugeneia/snabb,SnabbCo/snabbswitch
|
4c59f260714576e2c23aa068b4a1beae62756fd3
|
xmake/modules/package/tools/cmake.lua
|
xmake/modules/package/tools/cmake.lua
|
--!A cross-platform build utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2018, TBOOX Open Source Group.
--
-- @author ruki
-- @file cmake.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_file")
-- install package
function install(package, configs)
os.mkdir("build/install")
local oldir = os.cd("build")
local argv = {
"-DCMAKE_INSTALL_PREFIX=\"" .. path.absolute("install") .. "\""
}
if is_plat("windows") and is_arch("x64") then
table.insert(argv, "-A x64")
end
for name, value in pairs(configs) do
value = tostring(value):trim()
if value ~= "" then
table.insert(argv, value)
end
end
os.vrunv("cmake", argv)
if is_host("windows") then
local slnfile = assert(find_file("*.sln", os.curdir()), "*.sln file not found!")
os.vrun("msbuild \"%s\" -nologo -t:Rebuild -p:Configuration=%s -p:Platform=%s", slnfile, package:debug() and "Debug" or "Release", is_arch("x64") and "x64" or "Win32")
local projfile = os.isfile("INSTALL.vcxproj") and "INSTALL.vcxproj" or "INSTALL.vcproj"
if os.isfile(projfile) then
os.vrun("msbuild \"%s\" /property:configuration=%s", projfile, package:debug() and "Debug" or "Release")
os.cp("install/lib", package:installdir())
os.cp("install/include", package:installdir())
else
os.cp("**.lib", package:installdir("lib"))
os.cp("**.dll", package:installdir("lib"))
os.cp("**.exp", package:installdir("lib"))
end
else
os.vrun("make -j4")
os.vrun("make install")
os.cp("install/lib", package:installdir())
os.cp("install/include", package:installdir())
end
os.cd(oldir)
end
|
--!A cross-platform build utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2018, TBOOX Open Source Group.
--
-- @author ruki
-- @file cmake.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_file")
-- install package
function install(package, configs)
os.mkdir("build/install")
local oldir = os.cd("build")
local argv = {
"-DCMAKE_INSTALL_PREFIX=\"" .. path.absolute("install") .. "\""
}
if is_plat("windows") and is_arch("x64") then
table.insert(argv, "-A")
table.insert(argv, "x64")
end
for name, value in pairs(configs) do
value = tostring(value):trim()
if value ~= "" then
table.insert(argv, value)
end
end
table.insert(argv, '..')
os.vrunv("cmake", argv)
if is_host("windows") then
local slnfile = assert(find_file("*.sln", os.curdir()), "*.sln file not found!")
os.vrun("msbuild \"%s\" -nologo -t:Rebuild -p:Configuration=%s -p:Platform=%s", slnfile, package:debug() and "Debug" or "Release", is_arch("x64") and "x64" or "Win32")
local projfile = os.isfile("INSTALL.vcxproj") and "INSTALL.vcxproj" or "INSTALL.vcproj"
if os.isfile(projfile) then
os.vrun("msbuild \"%s\" /property:configuration=%s", projfile, package:debug() and "Debug" or "Release")
os.cp("install/lib", package:installdir())
os.cp("install/include", package:installdir())
else
os.cp("**.lib", package:installdir("lib"))
os.cp("**.dll", package:installdir("lib"))
os.cp("**.exp", package:installdir("lib"))
end
else
os.vrun("make -j4")
os.vrun("make install")
os.cp("install/lib", package:installdir())
os.cp("install/include", package:installdir())
end
os.cd(oldir)
end
|
cmake "-A x64" fix
|
cmake "-A x64" fix
|
Lua
|
apache-2.0
|
waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake
|
3df1c68ce09653f84a1c955a1ff7e64dcd6dccc4
|
docs/lua-api/sound.lua
|
docs/lua-api/sound.lua
|
--- Play a sound to a specific player.
-- @param player player to play the sound to
-- @param sound sound to play
function playSound(player, sound) end
--- Play a note to a specific player.
-- @param player player to play the note to
-- @param instrument instrument which will playing
-- @param note note to play
function playNote(player, instrument, note) end
--- Play a song to a specific player.
-- @param player player to play the song to
-- @param song path of the .nbs song file, relative to the script directory
-- @return true if the song was started, false if not (due to missing NoteBlockAPI)
--
function playSong(player, song) end
|
--- Provides sound and music functions.
-- @module rpgplus.sound
--- Play a sound to a specific player.
-- @param player player to play the sound to
-- @param sound sound to play
function playSound(player, sound) end
--- Play a note to a specific player.
-- @param player player to play the note to
-- @param instrument instrument which will playing
-- @param note note to play
function playNote(player, instrument, note) end
--- Play a song to a specific player.
-- @param player player to play the song to
-- @param song path of the .nbs song file, relative to the script directory
-- @return true if the song was started, false if not (due to missing NoteBlockAPI plugin)
--
function playSong(player, song) end
|
Fix sound module luadoc.
|
Fix sound module luadoc.
|
Lua
|
mit
|
leMaik/RpgPlus
|
967f2e79b38bcacbf37de1ae4c0dfafb8e4a4117
|
nvim/nvim/lua/_/statusline.lua
|
nvim/nvim/lua/_/statusline.lua
|
local utils = require '_.utils'
local M = {}
---------------------------------------------------------------------------------
-- Helpers
---------------------------------------------------------------------------------
-- display lineNoIndicator (from drzel/vim-line-no-indicator)
local function line_no_indicator()
local line_no_indicator_chars = {
' ',
'▁',
'▂',
'▃',
'▄',
'▅',
'▆',
'▇',
'█'
}
local current_line = vim.fn.line('.')
local total_lines = vim.fn.line('$')
local index = current_line
if current_line == 1 then
index = 1
elseif current_line == total_lines then
index = #line_no_indicator_chars
else
local line_no_fraction = math.floor(current_line) / math.floor(total_lines)
index = math.ceil(line_no_fraction * #line_no_indicator_chars)
end
return line_no_indicator_chars[index]
end
---------------------------------------------------------------------------------
-- Main functions
---------------------------------------------------------------------------------
function M.lsp_status()
if not vim.tbl_isempty(vim.lsp.buf_get_clients()) then
local line = [[%5*%{luaeval("require'lsp-status'.status_errors()")}]]
line = line .. [[ %6*%{luaeval("require'lsp-status'.status_warnings()")}]]
line = line .. [[ %7*%{luaeval("require'lsp-status'.status_hints()")}]]
line = line .. [[ %8*%{luaeval("require'lsp-status'.status_info()")}]]
return line
end
return [[%*]]
end
function M.git_info()
if not vim.g.loaded_fugitive then return '' end
local out = vim.fn.FugitiveHead(10)
if out ~= '' then out = utils.get_icon('branch') .. ' ' .. out end
return out
end
function M.update_filepath_highlights()
if vim.bo.modified then
vim.cmd('hi! link StatusLineFilePath DiffChange')
vim.cmd('hi! link StatusLineNewFilePath DiffChange')
else
vim.cmd('hi! link StatusLineFilePath User6')
vim.cmd('hi! link StatusLineNewFilePath User4')
end
return ''
end
function M.get_filepath_parts()
local base = vim.fn.expand('%:~:.:h')
local filename = vim.fn.expand('%:~:.:t')
local prefix = (vim.fn.empty(base) == 1 or base == '.') and '' or base .. '/'
return {base, filename, prefix}
end
function M.filepath()
local parts = M.get_filepath_parts()
local prefix = parts[3]
local filename = parts[2]
local line = [[%{luaeval("require'_.statusline'.get_filepath_parts()[3]")}]]
line = line .. '%*'
line = line
.. [[%{luaeval("require'_.statusline'.update_filepath_highlights()")}]]
line = line .. '%#StatusLineFilePath#'
line = line .. [[%{luaeval("require'_.statusline'.get_filepath_parts()[2]")}]]
if vim.fn.empty(prefix) == 1 and vim.fn.empty(filename) == 1 then
line = [[%{luaeval("require'_.statusline'.update_filepath_highlights()")}]]
line = line .. '%#StatusLineNewFilePath#'
line = line .. '%f'
line = line .. '%*'
end
return line
end
function M.readonly()
local is_modifiable = vim.bo.modifiable == true
local is_readonly = vim.bo.readonly == true
if not is_modifiable and is_readonly then
return utils.get_icon('lock') .. ' RO'
end
if is_modifiable and is_readonly then return 'RO' end
if not is_modifiable and not is_readonly then return utils.get_icon('lock') end
return ''
end
local mode_table = {
no='N-Operator Pending',
v='V.',
V='V·Line',
['']='V·Block', -- this is not ^V, but it's , they're different
s='S.',
S='S·Line',
['']='S·Block',
i='I.',
ic='I·Compl',
ix='I·X-Compl',
R='R.',
Rc='Compl·Replace',
Rx='V·Replace',
Rv='X-Compl·Replace',
c='Command',
cv='Vim Ex',
ce='Ex',
r='Propmt',
rm='More',
['r?']='Confirm',
['!']='Sh',
t='T.'
}
function M.mode()
return mode_table[vim.fn.mode()]
or (vim.fn.mode() == 'n' and '' or 'NOT IN MAP')
end
function M.rhs()
return vim.fn.winwidth(0) > 80
and ('%s %02d/%02d:%02d'):format(line_no_indicator(),
vim.fn.line('.'),
vim.fn.line('$'), vim.fn.col('.'))
or line_no_indicator()
end
function M.spell()
if vim.wo.spell then return utils.get_icon('spell') end
return ''
end
function M.paste()
if vim.o.paste then return utils.get_icon('paste') end
return ''
end
function M.file_info()
local line = vim.bo.filetype
if vim.bo.fileformat ~= 'unix' then return line .. ' ' .. vim.bo.fileformat end
if vim.bo.fileencoding ~= 'utf-8' then
return line .. ' ' .. vim.bo.fileencoding
end
return line
end
function M.word_count()
if vim.bo.filetype == 'markdown' or vim.bo.filetype == 'text' then
return vim.fn.wordcount()['words'] .. ' words'
end
return ''
end
function M.filetype() return vim.bo.filetype end
---------------------------------------------------------------------------------
-- Statusline
---------------------------------------------------------------------------------
function M.active()
local line = M.lsp_status() .. ' %*'
line = line .. [[%6*%{luaeval("require'_.statusline'.git_info()")} %*]]
line = line .. '%<'
line = line .. '%4*' .. M.filepath() .. '%*'
line = line .. [[%4* %{luaeval("require'_.statusline'.word_count()")} %*]]
line = line .. [[%5* %{luaeval("require'_.statusline'.readonly()")} %w %*]]
line = line .. '%9*%=%*'
line = line .. [[ %{luaeval("require'_.statusline'.mode()")} %*]]
line = line .. [[%#ErrorMsg#%{luaeval("require'_.statusline'.paste()")}%*]]
line = line .. [[%#WarningMsg#%{luaeval("require'_.statusline'.spell()")}%*]]
line = line .. [[%4* %{luaeval("require'_.statusline'.file_info()")} %*]]
line = line .. [[%4* %{luaeval("require'_.statusline'.rhs()")} %*]]
if vim.bo.filetype == 'help' or vim.bo.filetype == 'man' then
line = [[%#StatusLineNC# %{luaeval("require'_.statusline'.filetype()")} %f]]
line = line .. [[%5* %{luaeval("require'_.statusline'.readonly()")} %w %*]]
end
vim.api.nvim_win_set_option(0, 'statusline', line)
end
function M.inactive()
local line = '%#StatusLineNC#%f%*'
vim.api.nvim_win_set_option(0, 'statusline', line)
end
function M.activate()
vim.cmd(
('hi! StatusLine gui=NONE cterm=NONE guibg=NONE ctermbg=NONE guifg=%s ctermfg=%d'):format(
utils.get_color('Identifier', 'fg', 'gui'),
utils.get_color('Identifier', 'fg', 'cterm')))
utils.augroup('MyStatusLine', function()
vim.cmd('autocmd WinEnter,BufEnter * lua require\'_.statusline\'.active()')
vim.cmd('autocmd WinLeave,BufLeave * lua require\'_.statusline\'.inactive()')
end)
end
return M
|
local utils = require '_.utils'
local M = {}
---------------------------------------------------------------------------------
-- Helpers
---------------------------------------------------------------------------------
-- display lineNoIndicator (from drzel/vim-line-no-indicator)
local function line_no_indicator()
local line_no_indicator_chars = {
' ',
'▁',
'▂',
'▃',
'▄',
'▅',
'▆',
'▇',
'█'
}
local current_line = vim.fn.line('.')
local total_lines = vim.fn.line('$')
local index = current_line
if current_line == 1 then
index = 1
elseif current_line == total_lines then
index = #line_no_indicator_chars
else
local line_no_fraction = math.floor(current_line) / math.floor(total_lines)
index = math.ceil(line_no_fraction * #line_no_indicator_chars)
end
return line_no_indicator_chars[index]
end
---------------------------------------------------------------------------------
-- Main functions
---------------------------------------------------------------------------------
function M.git_info()
if not vim.g.loaded_fugitive then return '' end
local out = vim.fn.FugitiveHead(10)
if out ~= '' then out = utils.get_icon('branch') .. ' ' .. out end
return out
end
function M.update_filepath_highlights()
if vim.bo.modified then
vim.cmd('hi! link StatusLineFilePath DiffChange')
vim.cmd('hi! link StatusLineNewFilePath DiffChange')
else
vim.cmd('hi! link StatusLineFilePath User6')
vim.cmd('hi! link StatusLineNewFilePath User4')
end
return ''
end
function M.get_filepath_parts()
local base = vim.fn.expand('%:~:.:h')
local filename = vim.fn.expand('%:~:.:t')
local prefix = (vim.fn.empty(base) == 1 or base == '.') and '' or base .. '/'
return {base, filename, prefix}
end
function M.filepath()
local parts = M.get_filepath_parts()
local prefix = parts[3]
local filename = parts[2]
local line = [[%{luaeval("require'_.statusline'.get_filepath_parts()[3]")}]]
line = line .. '%*'
line = line
.. [[%{luaeval("require'_.statusline'.update_filepath_highlights()")}]]
line = line .. '%#StatusLineFilePath#'
line = line .. [[%{luaeval("require'_.statusline'.get_filepath_parts()[2]")}]]
if vim.fn.empty(prefix) == 1 and vim.fn.empty(filename) == 1 then
line = [[%{luaeval("require'_.statusline'.update_filepath_highlights()")}]]
line = line .. '%#StatusLineNewFilePath#'
line = line .. '%f'
line = line .. '%*'
end
return line
end
function M.readonly()
local is_modifiable = vim.bo.modifiable == true
local is_readonly = vim.bo.readonly == true
if not is_modifiable and is_readonly then
return utils.get_icon('lock') .. ' RO'
end
if is_modifiable and is_readonly then return 'RO' end
if not is_modifiable and not is_readonly then return utils.get_icon('lock') end
return ''
end
local mode_table = {
no='N-Operator Pending',
v='V.',
V='V·Line',
['']='V·Block', -- this is not ^V, but it's , they're different
s='S.',
S='S·Line',
['']='S·Block',
i='I.',
ic='I·Compl',
ix='I·X-Compl',
R='R.',
Rc='Compl·Replace',
Rx='V·Replace',
Rv='X-Compl·Replace',
c='Command',
cv='Vim Ex',
ce='Ex',
r='Propmt',
rm='More',
['r?']='Confirm',
['!']='Sh',
t='T.'
}
function M.mode()
return mode_table[vim.fn.mode()]
or (vim.fn.mode() == 'n' and '' or 'NOT IN MAP')
end
function M.rhs()
return vim.fn.winwidth(0) > 80
and ('%s %02d/%02d:%02d'):format(line_no_indicator(),
vim.fn.line('.'),
vim.fn.line('$'), vim.fn.col('.'))
or line_no_indicator()
end
function M.spell()
if vim.wo.spell then return utils.get_icon('spell') end
return ''
end
function M.paste()
if vim.o.paste then return utils.get_icon('paste') end
return ''
end
function M.file_info()
local line = vim.bo.filetype
if vim.bo.fileformat ~= 'unix' then return line .. ' ' .. vim.bo.fileformat end
if vim.bo.fileencoding ~= 'utf-8' then
return line .. ' ' .. vim.bo.fileencoding
end
return line
end
function M.word_count()
if vim.bo.filetype == 'markdown' or vim.bo.filetype == 'text' then
return vim.fn.wordcount()['words'] .. ' words'
end
return ''
end
function M.filetype() return vim.bo.filetype end
---------------------------------------------------------------------------------
-- Statusline
---------------------------------------------------------------------------------
function M.active()
local line = '%*'
-- LSP Status
line = line .. [[%5*%{luaeval("require'lsp-status'.status_errors()")} %*]]
line = line .. [[%6*%{luaeval("require'lsp-status'.status_warnings()")} %*]]
line = line .. [[%7*%{luaeval("require'lsp-status'.status_hints()")} %*]]
line = line .. [[%8*%{luaeval("require'lsp-status'.status_info()")} %*]]
line = line .. [[%6*%{luaeval("require'_.statusline'.git_info()")} %*]]
line = line .. '%<'
line = line .. '%4*' .. M.filepath() .. '%*'
line = line .. [[%4* %{luaeval("require'_.statusline'.word_count()")} %*]]
line = line .. [[%5* %{luaeval("require'_.statusline'.readonly()")} %w %*]]
line = line .. '%9*%=%*'
line = line .. [[ %{luaeval("require'_.statusline'.mode()")} %*]]
line = line .. [[%#ErrorMsg#%{luaeval("require'_.statusline'.paste()")}%*]]
line = line .. [[%#WarningMsg#%{luaeval("require'_.statusline'.spell()")}%*]]
line = line .. [[%4* %{luaeval("require'_.statusline'.file_info()")} %*]]
line = line .. [[%4* %{luaeval("require'_.statusline'.rhs()")} %*]]
if vim.bo.filetype == 'help' or vim.bo.filetype == 'man' then
line = [[%#StatusLineNC# %{luaeval("require'_.statusline'.filetype()")} %f]]
line = line .. [[%5* %{luaeval("require'_.statusline'.readonly()")} %w %*]]
end
vim.api.nvim_win_set_option(0, 'statusline', line)
end
function M.inactive()
local line = '%#StatusLineNC#%f%*'
vim.api.nvim_win_set_option(0, 'statusline', line)
end
function M.activate()
vim.cmd(
('hi! StatusLine gui=NONE cterm=NONE guibg=NONE ctermbg=NONE guifg=%s ctermfg=%d'):format(
utils.get_color('Identifier', 'fg', 'gui'),
utils.get_color('Identifier', 'fg', 'cterm')))
utils.augroup('MyStatusLine', function()
vim.cmd('autocmd WinEnter,BufEnter * lua require\'_.statusline\'.active()')
vim.cmd('autocmd WinLeave,BufLeave * lua require\'_.statusline\'.inactive()')
end)
end
return M
|
fix(nvim): lsp status to be always shown
|
fix(nvim): lsp status to be always shown
|
Lua
|
mit
|
skyuplam/dotfiles,skyuplam/dotfiles
|
718ea2d25e20ca172530200561a797fe826b882c
|
scripts/lua/policies/mapping.lua
|
scripts/lua/policies/mapping.lua
|
-- Copyright (c) 2016 IBM. All rights reserved.
--
-- 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.
--- @module mapping
-- Process mapping object, turning implementation details into request transformations
-- @author Cody Walker (cmwalker), Alex Song (songs), David Green (greend)
local logger = require "lib/logger"
local utils = require "lib/utils"
local cjson = require "cjson"
local _M = {}
local body
local query
local headers
local path
--- Implementation for the mapping policy.
-- @param map The mapping object that contains details about request tranformations
function processMap(map)
getRequestParams()
for k, v in pairs(map) do
if v.action == "insert" then
insertParam(v)
elseif v.action == "remove" then
removeParam(v)
elseif v.action == "transform" then
transformParam(v)
elseif v.action == "default" then
checkDefault(v)
else
logger.err(utils.concatStrings({'Map action not recognized. Skipping... ', v.action}))
end
end
finalize()
end
--- Get request body, params, and headers from incoming requests
function getRequestParams()
ngx.req.read_body()
body = ngx.req.get_body_data()
body = (body and cjson.decode(body)) or {}
headers = ngx.req.get_headers()
path = ngx.var.uri
query = parseUrl(ngx.var.backendUrl)
local incomingQuery = ngx.req.get_uri_args()
for k, v in pairs (incomingQuery) do
query[k] = v
end
end
--- Insert parameter value to header, body, or query params into request
-- @param m Parameter value to add to request
function insertParam(m)
local v
local k = m.to.name
if m.from.value ~= nil then
v = m.from.value
elseif m.from.location == 'header' then
v = headers[m.from.name]
elseif m.from.location == 'query' then
v = query[m.from.name]
elseif m.from.location == 'body' then
v = body[m.from.name]
elseif m.from.location == 'path' then
v = ngx.ctx[m.from.name]
end
-- determine to where
if m.to.location == 'header' then
insertHeader(k, v)
elseif m.to.location == 'query' then
insertQuery(k, v)
elseif m.to.location == 'body' then
insertBody(k, v)
elseif m.to.location == 'path' then
insertPath(k,v)
end
end
--- Remove parameter value to header, body, or query params from request
-- @param m Parameter value to remove from request
function removeParam(m)
if m.from.location == "header" then
removeHeader(m.from.name)
elseif m.from.location == "query" then
removeQuery(m.from.name)
elseif m.from.location == "body" then
removeBody(m.from.name)
end
end
--- Move parameter value from one location to another in the request
-- @param m Parameter value to move within request
function transformParam(m)
if m.from.name == '*' then
transformAllParams(m.from.location, m.to.location)
else
insertParam(m)
removeParam(m)
end
end
--- Checks if the header has been set, and sets the header to a value if found to be null.
-- @param m Header name and value to be set, if header is null.
function checkDefault(m)
if m.to.location == "header" and headers[m.to.name] == nil then
insertHeader(m.to.name, m.from.value)
elseif m.to.location == "query" and query[m.to.name] == nil then
insertQuery(m.to.name, m.from.value)
elseif m.to.location == "body" and body[m.to.name] == nil then
insertBody(m.to.name, m.from.value)
end
end
--- Function to handle wildcarding in the transform process.
-- If the value in the from object is '*', this function will pull all values from the incoming request
-- and move them to the location provided in the to object
-- @param s The source object from which we pull all parameters
-- @param d The destination object that we will move all found parameters to.
function transformAllParams(s, d)
if s == 'query' then
for k, v in pairs(query) do
local t = {}
t.from = {}
t.from.name = k
t.from.location = s
t.to = {}
t.to.name = k
t.to.location = d
insertParam(t)
removeParam(t)
end
elseif s == 'header' then
for k, v in pairs(headers) do
local t = {}
t.from = {}
t.from.name = k
t.from.location = s
t.to = {}
t.to.name = k
t.to.location = d
insertParam(t)
removeParam(t)
end
elseif s == 'body' then
for k, v in pairs(body) do
local t = {}
t.from = {}
t.from.name = k
t.from.location = s
t.to = {}
t.to.name = k
t.to.location = d
insertParam(t)
removeParam(t)
end
elseif s == 'path' then
for k, v in pairs(path) do
local t = {}
t.from = {}
t.from.name = k
t.from.location = s
t.to = {}
t.to.name = k
t.to.location = d
insertParam(t)
removeParam(t)
end
end
end
function finalize()
local bodyJson = cjson.encode(body)
ngx.req.set_body_data(bodyJson)
ngx.req.set_uri_args(query)
end
function insertHeader(k, v)
ngx.req.set_header(k, v)
headers[k] = v
end
function insertQuery(k, v)
query[k] = v
end
function insertBody(k, v)
body[k] = v
end
function insertPath(k, v)
v = ngx.unescape_uri(v)
path = path:gsub(utils.concatStrings({"%{", k ,"%}"}), v)
ngx.req.set_uri(path)
end
function removeHeader(k)
ngx.req.clear_header(k)
end
function removeQuery(k)
query[k] = nil
end
function removeBody(k)
body[k] = nil
end
function parseUrl(url)
local map = {}
for k,v in url:gmatch('([^&=?]+)=([^&=?]+)') do
map[ k ] = decodeQuery(v)
end
return map
end
function decodeQuery(param)
local decoded = param:gsub('+', ' '):gsub('%%(%x%x)',
function(hex) return string.char(tonumber(hex, 16)) end)
return decoded
end
_M.processMap = processMap
return _M
|
-- Copyright (c) 2016 IBM. All rights reserved.
--
-- 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.
--- @module mapping
-- Process mapping object, turning implementation details into request transformations
-- @author Cody Walker (cmwalker), Alex Song (songs), David Green (greend)
local logger = require "lib/logger"
local utils = require "lib/utils"
local cjson = require "cjson"
local _M = {}
local body
local query
local headers
local path
--- Implementation for the mapping policy.
-- @param map The mapping object that contains details about request tranformations
function processMap(map)
getRequestParams()
for k, v in pairs(map) do
if v.action == "insert" then
insertParam(v)
elseif v.action == "remove" then
removeParam(v)
elseif v.action == "transform" then
transformParam(v)
elseif v.action == "default" then
checkDefault(v)
else
logger.err(utils.concatStrings({'Map action not recognized. Skipping... ', v.action}))
end
end
finalize()
end
--- Get request body, params, and headers from incoming requests
function getRequestParams()
ngx.req.read_body()
body = ngx.req.get_body_data()
body = (body and cjson.decode(body)) or {}
headers = ngx.req.get_headers()
path = ngx.var.uri
query = parseUrl(ngx.var.backendUrl)
local incomingQuery = ngx.req.get_uri_args()
for k, v in pairs (incomingQuery) do
query[k] = v
end
end
--- Insert parameter value to header, body, or query params into request
-- @param m Parameter value to add to request
function insertParam(m)
local v
local k = m.to.name
if m.from.value ~= nil then
v = m.from.value
elseif m.from.location == 'header' then
v = headers[m.from.name]
elseif m.from.location == 'query' then
v = query[m.from.name]
elseif m.from.location == 'body' then
v = body[m.from.name]
elseif m.from.location == 'path' then
v = ngx.ctx[m.from.name]
end
-- determine to where
if m.to.location == 'header' then
insertHeader(k, v)
elseif m.to.location == 'query' then
insertQuery(k, v)
elseif m.to.location == 'body' then
insertBody(k, v)
elseif m.to.location == 'path' then
insertPath(k,v)
end
end
--- Remove parameter value to header, body, or query params from request
-- @param m Parameter value to remove from request
function removeParam(m)
if m.from.location == "header" then
removeHeader(m.from.name)
elseif m.from.location == "query" then
removeQuery(m.from.name)
elseif m.from.location == "body" then
removeBody(m.from.name)
end
end
--- Move parameter value from one location to another in the request
-- @param m Parameter value to move within request
function transformParam(m)
if m.from.name == '*' then
transformAllParams(m.from.location, m.to.location)
else
insertParam(m)
removeParam(m)
end
end
--- Checks if the header has been set, and sets the header to a value if found to be null.
-- @param m Header name and value to be set, if header is null.
function checkDefault(m)
if m.to.location == "header" and headers[m.to.name] == nil then
insertHeader(m.to.name, m.from.value)
elseif m.to.location == "query" and query[m.to.name] == nil then
insertQuery(m.to.name, m.from.value)
elseif m.to.location == "body" and body[m.to.name] == nil then
insertBody(m.to.name, m.from.value)
end
end
--- Function to handle wildcarding in the transform process.
-- If the value in the from object is '*', this function will pull all values from the incoming request
-- and move them to the location provided in the to object
-- @param s The source object from which we pull all parameters
-- @param d The destination object that we will move all found parameters to.
function transformAllParams(s, d)
if s == 'query' then
for k, v in pairs(query) do
local t = {}
t.from = {}
t.from.name = k
t.from.location = s
t.to = {}
t.to.name = k
t.to.location = d
insertParam(t)
removeParam(t)
end
elseif s == 'header' then
for k, v in pairs(headers) do
local t = {}
t.from = {}
t.from.name = k
t.from.location = s
t.to = {}
t.to.name = k
t.to.location = d
insertParam(t)
removeParam(t)
end
elseif s == 'body' then
for k, v in pairs(body) do
local t = {}
t.from = {}
t.from.name = k
t.from.location = s
t.to = {}
t.to.name = k
t.to.location = d
insertParam(t)
removeParam(t)
end
elseif s == 'path' then
for k, v in pairs(path) do
local t = {}
t.from = {}
t.from.name = k
t.from.location = s
t.to = {}
t.to.name = k
t.to.location = d
insertParam(t)
removeParam(t)
end
end
end
function finalize()
if #body > 0 then
local bodyJson = cjson.encode(body)
ngx.req.set_body_data(bodyJson)
end
ngx.req.set_uri_args(query)
end
function insertHeader(k, v)
ngx.req.set_header(k, v)
headers[k] = v
end
function insertQuery(k, v)
query[k] = v
end
function insertBody(k, v)
body[k] = v
end
function insertPath(k, v)
v = ngx.unescape_uri(v)
path = path:gsub(utils.concatStrings({"%{", k ,"%}"}), v)
ngx.req.set_uri(path)
end
function removeHeader(k)
ngx.req.clear_header(k)
end
function removeQuery(k)
query[k] = nil
end
function removeBody(k)
body[k] = nil
end
function parseUrl(url)
local map = {}
for k,v in url:gmatch('([^&=?]+)=([^&=?]+)') do
map[ k ] = decodeQuery(v)
end
return map
end
function decodeQuery(param)
local decoded = param:gsub('+', ' '):gsub('%%(%x%x)',
function(hex) return string.char(tonumber(hex, 16)) end)
return decoded
end
_M.processMap = processMap
return _M
|
fix empty body issue in request map (#204)
|
fix empty body issue in request map (#204)
|
Lua
|
apache-2.0
|
openwhisk/apigateway,LukeFarrell/incubator-openwhisk-apigateway,LukeFarrell/incubator-openwhisk-apigateway,alexsong93/openwhisk-apigateway,LukeFarrell/incubator-openwhisk-apigateway,openwhisk/openwhisk-apigateway,openwhisk/apigateway,openwhisk/apigateway,alexsong93/openwhisk-apigateway,alexsong93/openwhisk-apigateway,openwhisk/openwhisk-apigateway,openwhisk/openwhisk-apigateway
|
e1c447a8178ca22e315243a8b673b85b85742c8e
|
xmake/modules/package/tools/cmake.lua
|
xmake/modules/package/tools/cmake.lua
|
--!A cross-platform build utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2018, TBOOX Open Source Group.
--
-- @author ruki
-- @file cmake.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_file")
-- install package
function install(package, configs)
os.mkdir("build/install")
local oldir = os.cd("build")
local argv = {}
for name, value in pairs(configs) do
value = tostring(value):trim()
if value ~= "" then
table.insert(argv, value)
end
end
if is_plat("windows") and is_arch("x64") then
os.vrunv(format("cmake -A x64 -DCMAKE_INSTALL_PREFIX=\"%s\" ..", path.absolute("install")), argv)
else
os.vrunv(format("cmake -DCMAKE_INSTALL_PREFIX=\"%s\" ..", path.absolute("install")), argv)
end
if is_host("windows") then
local slnfile = assert(find_file("*.sln", os.curdir()), "*.sln file not found!")
os.vrun("msbuild \"%s\" -nologo -t:Rebuild -p:Configuration=%s -p:Platform=%s", slnfile, package:debug() and "Debug" or "Release", is_arch("x64") and "x64" or "Win32")
local projfile = os.isfile("INSTALL.vcxproj") and "INSTALL.vcxproj" or "INSTALL.vcproj"
if os.isfile(projfile) then
os.vrun("msbuild \"%s\" /property:configuration=%s", projfile, package:debug() and "Debug" or "Release")
os.cp("install/lib", package:installdir())
os.cp("install/include", package:installdir())
else
os.cp("**.lib", package:installdir("lib"))
os.cp("**.dll", package:installdir("lib"))
os.cp("**.exp", package:installdir("lib"))
end
else
os.vrun("make -j4")
os.vrun("make install")
os.cp("install/lib", package:installdir())
os.cp("install/include", package:installdir())
end
os.cd(oldir)
end
|
--!A cross-platform build utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2018, TBOOX Open Source Group.
--
-- @author ruki
-- @file cmake.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_file")
-- install package
function install(package, configs)
os.mkdir("build/install")
local oldir = os.cd("build")
local argv = {
"-DCMAKE_INSTALL_PREFIX=\"" .. path.absolute("install") .. "\""
}
if is_plat("windows") and is_arch("x64") then
table.insert(argv, "-A x64")
end
for name, value in pairs(configs) do
value = tostring(value):trim()
if value ~= "" then
table.insert(argv, value)
end
end
os.vrunv("cmake", argv)
if is_host("windows") then
local slnfile = assert(find_file("*.sln", os.curdir()), "*.sln file not found!")
os.vrun("msbuild \"%s\" -nologo -t:Rebuild -p:Configuration=%s -p:Platform=%s", slnfile, package:debug() and "Debug" or "Release", is_arch("x64") and "x64" or "Win32")
local projfile = os.isfile("INSTALL.vcxproj") and "INSTALL.vcxproj" or "INSTALL.vcproj"
if os.isfile(projfile) then
os.vrun("msbuild \"%s\" /property:configuration=%s", projfile, package:debug() and "Debug" or "Release")
os.cp("install/lib", package:installdir())
os.cp("install/include", package:installdir())
else
os.cp("**.lib", package:installdir("lib"))
os.cp("**.dll", package:installdir("lib"))
os.cp("**.exp", package:installdir("lib"))
end
else
os.vrun("make -j4")
os.vrun("make install")
os.cp("install/lib", package:installdir())
os.cp("install/include", package:installdir())
end
os.cd(oldir)
end
|
vrunv fix
|
vrunv fix
|
Lua
|
apache-2.0
|
tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake
|
c9db66a828e1ec72128a92e1b35ae7a0a8da4de9
|
Modules/Geometry/TouchingParts/PartTouchingCalculator.lua
|
Modules/Geometry/TouchingParts/PartTouchingCalculator.lua
|
--- Determines if parts are touching or not
-- @classmod PartTouchingCalculator
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local CollectionService = game:GetService("CollectionService")
local Workspace = game:GetService("Workspace")
local BoundingBox = require("BoundingBox")
local CharacterUtil = require("CharacterUtil")
local PartTouchingCalculator = {}
PartTouchingCalculator.__index = PartTouchingCalculator
PartTouchingCalculator.ClassName = "PartTouchingCalculator"
function PartTouchingCalculator.new()
local self = setmetatable({}, PartTouchingCalculator)
return self
end
function PartTouchingCalculator:CheckIfTouchingHumanoid(humanoid, parts)
assert(humanoid)
assert(parts, "Must have parts")
local humanoidParts = {}
for _, item in pairs(humanoid.Parent:GetDescendants()) do
if item:IsA("BasePart") then
table.insert(humanoidParts, item)
end
end
if #humanoidParts == 0 then
warn("[PartTouchingCalculator.CheckIfTouchingHumanoid] - #humanoidParts == 0!")
return false
end
local dummyPart = self:GetCollidingPartFromParts(humanoidParts)
local previousProperties = {}
local toSet = {
CanCollide = true;
Anchored = false;
}
local partSet = {}
for _, part in pairs(parts) do
previousProperties[part] = {}
for name, value in pairs(toSet) do
previousProperties[part][name] = part[name]
part[name] = value
end
partSet[part] = true
end
local touching = dummyPart:GetTouchingParts()
dummyPart:Destroy()
local returnValue = false
for _, part in pairs(touching) do
if partSet[part] then
returnValue = true
break
end
end
for part, properties in pairs(previousProperties) do
for name, value in pairs(properties) do
part[name] = value
end
end
return returnValue
end
function PartTouchingCalculator:GetCollidingPartFromParts(parts, relativeTo, padding)
relativeTo = relativeTo or CFrame.new()
local size, rotation = BoundingBox.GetPartsBoundingBox(parts, relativeTo)
if padding then
size = size + Vector3.new(padding, padding, padding)
end
local dummyPart = Instance.new("Part")
dummyPart.Name = "CollisionDetection"
dummyPart.Size = size
dummyPart.CFrame = rotation
dummyPart.Anchored = false
dummyPart.CanCollide = true
dummyPart.Parent = Workspace
return dummyPart
end
function PartTouchingCalculator:GetTouchingBoundingBox(parts, relativeTo, padding)
local dummy = self:GetCollidingPartFromParts(parts, relativeTo, padding)
local touching = dummy:GetTouchingParts()
dummy:Destroy()
return touching
end
--- Expensive hull check on a list of parts (aggregating each parts touching list)
function PartTouchingCalculator:GetTouchingHull(parts, padding)
local hitParts = {}
for _, part in pairs(parts) do
for _, TouchingPart in pairs(self:GetTouching(part, padding)) do
hitParts[TouchingPart] = true
end
end
local touching = {}
for part, _ in pairs(hitParts) do
table.insert(touching, part)
end
return touching
end
--- Retrieves parts touching a base part
-- @param basePart item to identify touching. Geometry matters
-- @param padding studs of padding around the part
function PartTouchingCalculator:GetTouching(basePart, padding)
padding = padding or 2
local part
if basePart:IsA("TrussPart") then
-- Truss parts can't be resized
part = Instance.new("Part")
else
-- Clone part
part = basePart:Clone()
-- Remove all tags
for _, Tag in pairs(CollectionService:GetTags(part)) do
CollectionService:RemoveTag(part, Tag)
end
end
part:ClearAllChildren()
part.Size = basePart.Size + Vector3.new(padding, padding, padding)
part.CFrame = basePart.CFrame
part.Anchored = false
part.CanCollide = true
part.Transparency = 0.1
part.Material = Enum.Material.SmoothPlastic
part.Parent = Workspace
local touching = part:GetTouchingParts()
part:Destroy()
return touching
end
function PartTouchingCalculator:GetTouchingHumanoids(touchingList)
local touchingHumanoids = {}
for _, part in pairs(touchingList) do
local humanoid = part.Parent:FindFirstChildOfClass("Humanoid")
if humanoid then
if not touchingHumanoids[humanoid] then
local player = CharacterUtil.GetPlayerFromCharacter(humanoid)
touchingHumanoids[humanoid] = {
Humanoid = humanoid;
Character = player and player.Character; -- May be nil
Player = player; -- May be nil
Touching = { part };
}
else
table.insert(touchingHumanoids[humanoid].Touching, part)
end
end
end
local list = {}
for _, data in pairs(touchingHumanoids) do
table.insert(list, data)
end
return list
end
return PartTouchingCalculator
|
--- Determines if parts are touching or not
-- @classmod PartTouchingCalculator
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local CollectionService = game:GetService("CollectionService")
local Workspace = game:GetService("Workspace")
local BoundingBox = require("BoundingBox")
local CharacterUtil = require("CharacterUtil")
local PartTouchingCalculator = {}
PartTouchingCalculator.__index = PartTouchingCalculator
PartTouchingCalculator.ClassName = "PartTouchingCalculator"
function PartTouchingCalculator.new()
local self = setmetatable({}, PartTouchingCalculator)
return self
end
function PartTouchingCalculator:CheckIfTouchingHumanoid(humanoid, parts)
assert(humanoid)
assert(parts, "Must have parts")
local humanoidParts = {}
for _, item in pairs(humanoid.Parent:GetDescendants()) do
if item:IsA("BasePart") then
table.insert(humanoidParts, item)
end
end
if #humanoidParts == 0 then
warn("[PartTouchingCalculator.CheckIfTouchingHumanoid] - #humanoidParts == 0!")
return false
end
local dummyPart = self:GetCollidingPartFromParts(humanoidParts)
local previousProperties = {}
local toSet = {
CanCollide = true;
Anchored = false;
}
local partSet = {}
for _, part in pairs(parts) do
previousProperties[part] = {}
for name, value in pairs(toSet) do
previousProperties[part][name] = part[name]
part[name] = value
end
partSet[part] = true
end
local touching = dummyPart:GetTouchingParts()
dummyPart:Destroy()
local returnValue = false
for _, part in pairs(touching) do
if partSet[part] then
returnValue = true
break
end
end
for part, properties in pairs(previousProperties) do
for name, value in pairs(properties) do
part[name] = value
end
end
return returnValue
end
function PartTouchingCalculator:GetCollidingPartFromParts(parts, relativeTo, padding)
relativeTo = relativeTo or CFrame.new()
local size, position = BoundingBox.GetPartsBoundingBox(parts, relativeTo)
if padding then
size = size + Vector3.new(padding, padding, padding)
end
local dummyPart = Instance.new("Part")
dummyPart.Name = "CollisionDetection"
dummyPart.Size = size
dummyPart.CFrame = relativeTo + relativeTo:vectorToWorldSpace(position)
dummyPart.Anchored = false
dummyPart.CanCollide = true
dummyPart.Parent = Workspace
return dummyPart
end
function PartTouchingCalculator:GetTouchingBoundingBox(parts, relativeTo, padding)
local dummy = self:GetCollidingPartFromParts(parts, relativeTo, padding)
local touching = dummy:GetTouchingParts()
dummy:Destroy()
return touching
end
--- Expensive hull check on a list of parts (aggregating each parts touching list)
function PartTouchingCalculator:GetTouchingHull(parts, padding)
local hitParts = {}
for _, part in pairs(parts) do
for _, TouchingPart in pairs(self:GetTouching(part, padding)) do
hitParts[TouchingPart] = true
end
end
local touching = {}
for part, _ in pairs(hitParts) do
table.insert(touching, part)
end
return touching
end
--- Retrieves parts touching a base part
-- @param basePart item to identify touching. Geometry matters
-- @param padding studs of padding around the part
function PartTouchingCalculator:GetTouching(basePart, padding)
padding = padding or 2
local part
if basePart:IsA("TrussPart") then
-- Truss parts can't be resized
part = Instance.new("Part")
else
-- Clone part
part = basePart:Clone()
-- Remove all tags
for _, Tag in pairs(CollectionService:GetTags(part)) do
CollectionService:RemoveTag(part, Tag)
end
end
part:ClearAllChildren()
part.Size = basePart.Size + Vector3.new(padding, padding, padding)
part.CFrame = basePart.CFrame
part.Anchored = false
part.CanCollide = true
part.Transparency = 0.1
part.Material = Enum.Material.SmoothPlastic
part.Parent = Workspace
local touching = part:GetTouchingParts()
part:Destroy()
return touching
end
function PartTouchingCalculator:GetTouchingHumanoids(touchingList)
local touchingHumanoids = {}
for _, part in pairs(touchingList) do
local humanoid = part.Parent:FindFirstChildOfClass("Humanoid")
if humanoid then
if not touchingHumanoids[humanoid] then
local player = CharacterUtil.GetPlayerFromCharacter(humanoid)
touchingHumanoids[humanoid] = {
Humanoid = humanoid;
Character = player and player.Character; -- May be nil
Player = player; -- May be nil
Touching = { part };
}
else
table.insert(touchingHumanoids[humanoid].Touching, part)
end
end
end
local list = {}
for _, data in pairs(touchingHumanoids) do
table.insert(list, data)
end
return list
end
return PartTouchingCalculator
|
Fix BoundingBox calls
|
Fix BoundingBox calls
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.