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
|
|---|---|---|---|---|---|---|---|---|---|
92ec33e4cd95ec01ed087ff85fc0c27069270a3d
|
fblualib/ffivector/test/ffivector_test.lua
|
fblualib/ffivector/test/ffivector_test.lua
|
--
-- Copyright (c) 2014, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
require('fb.luaunit')
local ffivector = require('fb.ffivector')
local gettorch = require('torch')
function testIntFFIVector()
local v = ffivector.new_int()
v:resize(42)
assertEquals(42, #v)
assertTrue(v:capacity() >= 42)
for i = 1, 42 do
assertEquals(0, v[i])
end
assertError(function() return v[0] end)
assertError(function() return v[43] end)
for i = 1, 42 do
v[i] = i * 10
end
for i = 1, 42 do
assertEquals(i * 10, v[i])
end
end
function testStructFFIVector()
local v = ffivector.new('struct { int a; int64_t b; }')
v:resize(42)
for i = 1, 42 do
p = v[i] -- it's a reference!
p.a = i * 10
p.b = i * 100
end
for i = 1, 42 do
assertEquals(i * 10, v[i].a)
assertEquals(i * 100, tonumber(v[i].b))
end
end
function testStringFFIVector()
local v = ffivector.new_string()
v:resize(42)
for i = 1, 42 do
v[i] = 'hello ' .. tostring(i)
end
collectgarbage() -- temp strings should no longer be allocated
for i = 1, 42 do
assertEquals('hello ' .. tostring(i), v[i])
end
end
function testStringFFIVectorDestruction()
do
local v = ffivector.new_string()
end
collectgarbage()
end
function testFFIVectorDestruction()
local destructor_count = 0
do
local v = ffivector.new(
'int', 0, tonumber, nil,
function(x) destructor_count = destructor_count + 1 end)
v:resize(42)
assertEquals(0, destructor_count)
v[10] = 10
assertEquals(1, destructor_count)
v[42] = 10
assertEquals(2, destructor_count)
v[43] = 10
assertEquals(2, destructor_count)
assertEquals(43, #v)
v:resize(50)
assertEquals(2, destructor_count)
assertEquals(50, #v)
v:resize(40)
assertEquals(12, destructor_count)
assertEquals(40, #v)
end
collectgarbage()
assertEquals(52, destructor_count)
end
LuaUnit:main()
|
--
-- Copyright (c) 2014, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
require('fb.luaunit')
local ffivector = require('fb.ffivector')
function testIntFFIVector()
local v = ffivector.new_int()
v:resize(42)
assertEquals(42, #v)
assertTrue(v:capacity() >= 42)
for i = 1, 42 do
assertEquals(0, v[i])
end
assertError(function() return v[0] end)
assertError(function() return v[43] end)
for i = 1, 42 do
v[i] = i * 10
end
for i = 1, 42 do
assertEquals(i * 10, v[i])
end
end
function testStructFFIVector()
local v = ffivector.new('struct { int a; int64_t b; }')
v:resize(42)
for i = 1, 42 do
p = v[i] -- it's a reference!
p.a = i * 10
p.b = i * 100
end
for i = 1, 42 do
assertEquals(i * 10, v[i].a)
assertEquals(i * 100, tonumber(v[i].b))
end
end
function testStringFFIVector()
local v = ffivector.new_string()
v:resize(42)
for i = 1, 42 do
v[i] = 'hello ' .. tostring(i)
end
collectgarbage() -- temp strings should no longer be allocated
for i = 1, 42 do
assertEquals('hello ' .. tostring(i), v[i])
end
end
function testStringFFIVectorDestruction()
do
local v = ffivector.new_string()
end
collectgarbage()
end
function testFFIVectorDestruction()
local destructor_count = 0
do
local v = ffivector.new(
'int', 0, tonumber, nil,
function(x) destructor_count = destructor_count + 1 end)
v:resize(42)
assertEquals(0, destructor_count)
v[10] = 10
assertEquals(1, destructor_count)
v[42] = 10
assertEquals(2, destructor_count)
v[43] = 10
assertEquals(2, destructor_count)
assertEquals(43, #v)
v:resize(50)
assertEquals(2, destructor_count)
assertEquals(50, #v)
v:resize(40)
assertEquals(12, destructor_count)
assertEquals(40, #v)
end
collectgarbage()
assertEquals(52, destructor_count)
end
LuaUnit:main()
|
Fix ffivector_test.
|
Fix ffivector_test.
Summary: I broke this for no good reason at all. Sorry.
Test Plan: fbconfig fblualib/ffivector/test && fbmake runtests
Reviewed By: [email protected]
FB internal diff: D1588036
Tasks: 5096599
|
Lua
|
bsd-3-clause
|
facebook/fblualib,raphaelamorim/fblualib,soumith/fblualib,szagoruyko/fblualib,soumith/fblualib,facebook/fblualib,raphaelamorim/fblualib,szagoruyko/fblualib
|
eb85fd7974acee779212ba0e2d5b9483aef65ed2
|
onmt/Seq2Seq.lua
|
onmt/Seq2Seq.lua
|
--[[ Sequence to sequence model with attention. ]]
local Seq2Seq, parent = torch.class('Seq2Seq', 'Model')
local options = {
{
'-enc_layers', 0,
[[If > 0, number of layers of the encode. This overrides the global `-layers` option.]],
{
valid = onmt.utils.ExtendedCmdLine.isUInt(),
structural = 0
}
},
{
'-dec_layers', 0,
[[If > 0, number of layers of the decoder. This overrides the global `-layers` option.]],
{
valid = onmt.utils.ExtendedCmdLine.isUInt(),
structural = 0
}
},
{
'-word_vec_size', 0,
[[Shared word embedding size. If set, this overrides `-src_word_vec_size` and `-tgt_word_vec_size`.]],
{
valid = onmt.utils.ExtendedCmdLine.isUInt(),
structural = 0
}
},
{
'-src_word_vec_size', '500',
[[Comma-separated list of source embedding sizes: `word[,feat1[,feat2[,...] ] ]`.]],
{
structural = 0
}
},
{
'-tgt_word_vec_size', '500',
[[Comma-separated list of target embedding sizes: `word[,feat1[,feat2[,...] ] ]`.]],
{
structural = 0
}
},
{
'-pre_word_vecs_enc', '',
[[Path to pretrained word embeddings on the encoder side serialized as a Torch tensor.]],
{
valid = onmt.utils.ExtendedCmdLine.fileNullOrExists,
init_only = true
}
},
{
'-pre_word_vecs_dec', '',
[[Path to pretrained word embeddings on the decoder side serialized as a Torch tensor.]],
{
valid = onmt.utils.ExtendedCmdLine.fileNullOrExists,
init_only = true
}
},
{
'-fix_word_vecs_enc', 0,
[[Fix word embeddings on the encoder side.]],
{
enum = {0, 1},
structural = 1
}
},
{
'-fix_word_vecs_dec', 0,
[[Fix word embeddings on the decoder side.]],
{
enum = {0, 1},
structural = 1
}
},
{
'-feat_merge', 'concat',
[[Merge action for the features embeddings.]],
{
enum = {'concat', 'sum'},
structural = 0
}
},
{
'-feat_vec_exponent', 0.7,
[[When features embedding sizes are not set and using `-feat_merge concat`, their dimension
will be set to `N^feat_vec_exponent` where `N` is the number of values the feature takes.]],
{
structural = 0
}
},
{
'-feat_vec_size', 20,
[[When features embedding sizes are not set and using `-feat_merge sum`,
this is the common embedding size of the features]],
{
valid = onmt.utils.ExtendedCmdLine.isUInt(),
structural = 0
}
}
}
function Seq2Seq.declareOpts(cmd)
cmd:setCmdLineOptions(options, Seq2Seq.modelName())
onmt.Encoder.declareOpts(cmd)
onmt.Bridge.declareOpts(cmd)
onmt.Decoder.declareOpts(cmd)
onmt.Factory.declareOpts(cmd)
end
function Seq2Seq:__init(args, dicts)
parent.__init(self, args)
onmt.utils.Table.merge(self.args, onmt.utils.ExtendedCmdLine.getModuleOpts(args, options))
self.args.uneven_batches = args.uneven_batches
if not dicts.src then
-- the input is already a vector
args.dimInputSize = dicts.srcInputSize
end
local encArgs = onmt.utils.Tensor.deepClone(args)
encArgs.layers = encArgs.enc_layers > 0 and encArgs.enc_layers or encArgs.layers
self.models.encoder = onmt.Factory.buildWordEncoder(encArgs, dicts.src)
local decArgs = onmt.utils.Tensor.deepClone(args)
decArgs.layers = decArgs.dec_layers > 0 and decArgs.dec_layers or decArgs.layers
self.models.decoder = onmt.Factory.buildWordDecoder(decArgs, dicts.tgt)
self.models.bridge = onmt.Bridge(args.bridge,
self.models.encoder.args.rnnSize,
self.models.encoder.args.numEffectiveLayers,
self.models.decoder.args.rnnSize,
self.models.decoder.args.numEffectiveLayers)
self.criterion = onmt.ParallelClassNLLCriterion(onmt.Factory.getOutputSizes(dicts.tgt))
end
function Seq2Seq.load(args, models, dicts)
local self = torch.factory('Seq2Seq')()
parent.__init(self, args)
onmt.utils.Table.merge(self.args, onmt.utils.ExtendedCmdLine.getModuleOpts(args, options))
self.args.uneven_batches = args.uneven_batches
self.models.encoder = onmt.Factory.loadEncoder(models.encoder)
self.models.decoder = onmt.Factory.loadDecoder(models.decoder)
self.models.bridge = onmt.Bridge.load(models.bridge)
self.criterion = onmt.ParallelClassNLLCriterion(onmt.Factory.getOutputSizes(dicts.tgt))
return self
end
-- Returns model name.
function Seq2Seq.modelName()
return 'Sequence to Sequence with Attention'
end
-- Returns expected dataMode.
function Seq2Seq.dataType()
return 'bitext'
end
function Seq2Seq:returnIndividualLosses(enable)
if not self.models.decoder.returnIndividualLosses then
_G.logger:info('Current Seq2Seq model does not support training with sample_w_ppl option')
return false
else
self.models.decoder:returnIndividualLosses(enable)
end
return true
end
function Seq2Seq:enableProfiling()
_G.profiler.addHook(self.models.encoder, 'encoder')
_G.profiler.addHook(self.models.decoder, 'decoder')
_G.profiler.addHook(self.models.decoder.modules[2], 'generator')
_G.profiler.addHook(self.criterion, 'criterion')
end
function Seq2Seq:getOutput(batch)
return batch.targetOutput
end
function Seq2Seq:maskPadding(batch)
self.models.encoder:maskPadding()
if batch and batch.uneven then
self.models.decoder:maskPadding(self.models.encoder:contextSize(batch.sourceSize, batch.sourceLength))
else
self.models.decoder:maskPadding()
end
end
function Seq2Seq:forwardComputeLoss(batch)
if self.args.uneven_batches then
self:maskPadding(batch)
end
local encoderStates, context = self.models.encoder:forward(batch)
local decoderInitStates = self.models.bridge:forward(encoderStates)
return self.models.decoder:computeLoss(batch, decoderInitStates, context, self.criterion)
end
function Seq2Seq:trainNetwork(batch, dryRun)
if self.args.uneven_batches then
self:maskPadding(batch)
end
local encStates, context = self.models.encoder:forward(batch)
local decInitStates = self.models.bridge:forward(encStates)
local decOutputs = self.models.decoder:forward(batch, decInitStates, context)
if dryRun then
decOutputs = onmt.utils.Tensor.recursiveClone(decOutputs)
end
local decGradInputStates, gradContext, loss, indvLoss = self.models.decoder:backward(batch, decOutputs, self.criterion)
local encGradOutputStates = self.models.bridge:backward(encStates, decGradInputStates)
self.models.encoder:backward(batch, encGradOutputStates, gradContext)
return loss, indvLoss
end
return Seq2Seq
|
--[[ Sequence to sequence model with attention. ]]
local Seq2Seq, parent = torch.class('Seq2Seq', 'Model')
local options = {
{
'-enc_layers', 0,
[[If > 0, number of layers of the encode. This overrides the global `-layers` option.]],
{
valid = onmt.utils.ExtendedCmdLine.isUInt(),
structural = 0
}
},
{
'-dec_layers', 0,
[[If > 0, number of layers of the decoder. This overrides the global `-layers` option.]],
{
valid = onmt.utils.ExtendedCmdLine.isUInt(),
structural = 0
}
},
{
'-word_vec_size', 0,
[[Shared word embedding size. If set, this overrides `-src_word_vec_size` and `-tgt_word_vec_size`.]],
{
valid = onmt.utils.ExtendedCmdLine.isUInt(),
structural = 0
}
},
{
'-src_word_vec_size', '500',
[[Comma-separated list of source embedding sizes: `word[,feat1[,feat2[,...] ] ]`.]],
{
structural = 0
}
},
{
'-tgt_word_vec_size', '500',
[[Comma-separated list of target embedding sizes: `word[,feat1[,feat2[,...] ] ]`.]],
{
structural = 0
}
},
{
'-pre_word_vecs_enc', '',
[[Path to pretrained word embeddings on the encoder side serialized as a Torch tensor.]],
{
valid = onmt.utils.ExtendedCmdLine.fileNullOrExists,
init_only = true
}
},
{
'-pre_word_vecs_dec', '',
[[Path to pretrained word embeddings on the decoder side serialized as a Torch tensor.]],
{
valid = onmt.utils.ExtendedCmdLine.fileNullOrExists,
init_only = true
}
},
{
'-fix_word_vecs_enc', 0,
[[Fix word embeddings on the encoder side.]],
{
enum = {0, 1},
structural = 1
}
},
{
'-fix_word_vecs_dec', 0,
[[Fix word embeddings on the decoder side.]],
{
enum = {0, 1},
structural = 1
}
},
{
'-feat_merge', 'concat',
[[Merge action for the features embeddings.]],
{
enum = {'concat', 'sum'},
structural = 0
}
},
{
'-feat_vec_exponent', 0.7,
[[When features embedding sizes are not set and using `-feat_merge concat`, their dimension
will be set to `N^feat_vec_exponent` where `N` is the number of values the feature takes.]],
{
structural = 0
}
},
{
'-feat_vec_size', 20,
[[When features embedding sizes are not set and using `-feat_merge sum`,
this is the common embedding size of the features]],
{
valid = onmt.utils.ExtendedCmdLine.isUInt(),
structural = 0
}
}
}
function Seq2Seq.declareOpts(cmd)
cmd:setCmdLineOptions(options, Seq2Seq.modelName())
onmt.Encoder.declareOpts(cmd)
onmt.Bridge.declareOpts(cmd)
onmt.Decoder.declareOpts(cmd)
onmt.Factory.declareOpts(cmd)
end
function Seq2Seq:__init(args, dicts)
parent.__init(self, args)
onmt.utils.Table.merge(self.args, onmt.utils.ExtendedCmdLine.getModuleOpts(args, options))
self.args.uneven_batches = args.uneven_batches
if not dicts.src then
-- the input is already a vector
args.dimInputSize = dicts.srcInputSize
end
local encArgs = onmt.utils.Tensor.deepClone(args)
encArgs.layers = encArgs.enc_layers > 0 and encArgs.enc_layers or encArgs.layers
self.models.encoder = onmt.Factory.buildWordEncoder(encArgs, dicts.src)
local decArgs = onmt.utils.Tensor.deepClone(args)
decArgs.layers = decArgs.dec_layers > 0 and decArgs.dec_layers or decArgs.layers
self.models.decoder = onmt.Factory.buildWordDecoder(decArgs, dicts.tgt)
self.models.bridge = onmt.Bridge(args.bridge,
encArgs.rnn_size,
self.models.encoder.args.numEffectiveLayers,
decArgs.rnn_size,
self.models.decoder.args.numEffectiveLayers)
self.criterion = onmt.ParallelClassNLLCriterion(onmt.Factory.getOutputSizes(dicts.tgt))
end
function Seq2Seq.load(args, models, dicts)
local self = torch.factory('Seq2Seq')()
parent.__init(self, args)
onmt.utils.Table.merge(self.args, onmt.utils.ExtendedCmdLine.getModuleOpts(args, options))
self.args.uneven_batches = args.uneven_batches
self.models.encoder = onmt.Factory.loadEncoder(models.encoder)
self.models.decoder = onmt.Factory.loadDecoder(models.decoder)
self.models.bridge = onmt.Bridge.load(models.bridge)
self.criterion = onmt.ParallelClassNLLCriterion(onmt.Factory.getOutputSizes(dicts.tgt))
return self
end
-- Returns model name.
function Seq2Seq.modelName()
return 'Sequence to Sequence with Attention'
end
-- Returns expected dataMode.
function Seq2Seq.dataType()
return 'bitext'
end
function Seq2Seq:returnIndividualLosses(enable)
if not self.models.decoder.returnIndividualLosses then
_G.logger:info('Current Seq2Seq model does not support training with sample_w_ppl option')
return false
else
self.models.decoder:returnIndividualLosses(enable)
end
return true
end
function Seq2Seq:enableProfiling()
_G.profiler.addHook(self.models.encoder, 'encoder')
_G.profiler.addHook(self.models.decoder, 'decoder')
_G.profiler.addHook(self.models.decoder.modules[2], 'generator')
_G.profiler.addHook(self.criterion, 'criterion')
end
function Seq2Seq:getOutput(batch)
return batch.targetOutput
end
function Seq2Seq:maskPadding(batch)
self.models.encoder:maskPadding()
if batch and batch.uneven then
self.models.decoder:maskPadding(self.models.encoder:contextSize(batch.sourceSize, batch.sourceLength))
else
self.models.decoder:maskPadding()
end
end
function Seq2Seq:forwardComputeLoss(batch)
if self.args.uneven_batches then
self:maskPadding(batch)
end
local encoderStates, context = self.models.encoder:forward(batch)
local decoderInitStates = self.models.bridge:forward(encoderStates)
return self.models.decoder:computeLoss(batch, decoderInitStates, context, self.criterion)
end
function Seq2Seq:trainNetwork(batch, dryRun)
if self.args.uneven_batches then
self:maskPadding(batch)
end
local encStates, context = self.models.encoder:forward(batch)
local decInitStates = self.models.bridge:forward(encStates)
local decOutputs = self.models.decoder:forward(batch, decInitStates, context)
if dryRun then
decOutputs = onmt.utils.Tensor.recursiveClone(decOutputs)
end
local decGradInputStates, gradContext, loss, indvLoss = self.models.decoder:backward(batch, decOutputs, self.criterion)
local encGradOutputStates = self.models.bridge:backward(encStates, decGradInputStates)
self.models.encoder:backward(batch, encGradOutputStates, gradContext)
return loss, indvLoss
end
return Seq2Seq
|
Rely on option value to define the encoder output size
|
Rely on option value to define the encoder output size
Fixes #234.
|
Lua
|
mit
|
monsieurzhang/OpenNMT,OpenNMT/OpenNMT,jungikim/OpenNMT,monsieurzhang/OpenNMT,da03/OpenNMT,jungikim/OpenNMT,da03/OpenNMT,monsieurzhang/OpenNMT,jsenellart/OpenNMT,OpenNMT/OpenNMT,da03/OpenNMT,jungikim/OpenNMT,jsenellart/OpenNMT,jsenellart/OpenNMT,jsenellart-systran/OpenNMT,jsenellart-systran/OpenNMT,OpenNMT/OpenNMT,jsenellart-systran/OpenNMT
|
3bad170979ccbce8c9a3bb3dbfcbb9c9e0bef3de
|
Quadtastic/Frame.lua
|
Quadtastic/Frame.lua
|
local Rectangle = require("Rectangle")
local renderutils = require("Renderutils")
local Layout = require("Layout")
local Frame = {}
local transform = require("transform")
local quads = renderutils.border_quads(48, 0, 16, 16, 128, 128, 2)
Frame.start = function(state, x, y, w, h)
x = x or state.layout.next_x
y = y or state.layout.next_y
w = w or state.layout.max_w
h = h or state.layout.max_h
-- Draw border
love.graphics.setColor(255, 255, 255, 255)
renderutils.draw_border(state.style.stylesheet, quads, x, y, w, h, 2)
Layout.start(state, x+2, y+2, w - 4, h - 4)
end
Frame.finish = function(state, w, h)
Layout.finish(state)
state.layout.adv_x = w or state.layout.max_w
state.layout.adv_y = h or state.layout.max_h
end
return Frame
|
local Rectangle = require("Rectangle")
local renderutils = require("Renderutils")
local Layout = require("Layout")
local Frame = {}
local transform = require("transform")
local quads = renderutils.border_quads(48, 0, 16, 16, 128, 128, 2)
Frame.start = function(state, x, y, w, h)
x = x or state.layout.next_x
y = y or state.layout.next_y
w = w or state.layout.max_w
h = h or state.layout.max_h
-- Draw border
love.graphics.setColor(255, 255, 255, 255)
renderutils.draw_border(state.style.stylesheet, quads, x, y, w, h, 2)
Layout.start(state, x+2, y+2, w - 4, h - 4)
end
Frame.finish = function(state, w, h)
state.layout.adv_x = w or state.layout.max_w + 4
state.layout.adv_y = h or state.layout.max_h + 4
Layout.finish(state)
end
return Frame
|
Fix Frame not setting its layout advances correctly
|
Fix Frame not setting its layout advances correctly
|
Lua
|
mit
|
25A0/Quadtastic,25A0/Quadtastic
|
ab68863ee638ff0f6134fc3be3e41ad9f22c2d7f
|
lua/mediaplayer/services/resource/init.lua
|
lua/mediaplayer/services/resource/init.lua
|
AddCSLuaFile "shared.lua"
include "shared.lua"
local urllib = url
local FilenamePattern = "([^/]+)%.%S+$"
local FilenameExtPattern = "([^/]+%.%S+)$"
SERVICE.TitleIncludeExtension = true -- include extension in title
function SERVICE:GetMetadata( callback )
if not self._metadata then
local title
local pattern = self.TitleIncludeExtension and
FilenameExtPattern or FilenamePattern
local path = self.urlinfo.path
path = string.match( path, pattern ) -- get filename
title = urllib.unescape( path )
self._metadata = {
title = title or self.Name,
url = self.url
}
end
if callback then
callback(self._metadata)
end
end
|
AddCSLuaFile "shared.lua"
include "shared.lua"
local urllib = url
local FilenamePattern = "([^/]+)%.%S+$"
local FilenameExtPattern = "([^/]+%.%S+)$"
SERVICE.TitleIncludeExtension = true -- include extension in title
function SERVICE:GetMetadata( callback )
if not self._metadata then
local title
local pattern = self.TitleIncludeExtension and
FilenameExtPattern or FilenamePattern
if self.urlinfo.path then
local path = self.urlinfo.path
path = string.match( path, pattern ) -- get filename
if path then
title = urllib.unescape( path )
else
title = self.url
end
else
title = self.url
end
self._metadata = {
title = title or self.Name,
url = self.url
}
end
if callback then
callback(self._metadata)
end
end
|
Fixed error when grabbing the path string from a resource URL.
|
Fixed error when grabbing the path string from a resource URL.
|
Lua
|
mit
|
pixeltailgames/gm-mediaplayer,pixeltailgames/gm-mediaplayer
|
0f64df3ae71795b8a9371f95f39c9c006fa7bccf
|
UCDwanted/server.lua
|
UCDwanted/server.lua
|
local wantedPoints = {}
addEventHandler("onResourceStart", resourceRoot,
function ()
for _, plr in ipairs(Element.getAllByType("player")) do
if (not plr.account.guest) then
setWantedPoints(plr, exports.UCDaccounts:GAD(plr, "wp"))
end
end
end
)
addEventHandler("onResourceStop", resourceRoot,
function ()
for _, plr in ipairs(Element.getAllByType("player")) do
if (not plr.account.guest) then
exports.UCDaccounts:GAD(plr, "wp", getWantedPoints(plr))
end
end
end
)
function addWantedPoints(plr, wp)
if (plr and wp and not plr.account.guest and tonumber(wp)) then
wp = tonumber(wp)
local a = plr.account.name
if (not wantedPoints[a]) then
wantedPoints[a] = 0
end
setWantedPoints(plr, wantedPoints[a] + wp)
return true
end
end
function getWantedPoints(plr)
if (plr and not plr.account.guest) then
local a = plr.account.name
if (not wantedPoints[a]) then
wantedPoints[a] = 0
end
return wantedPoints[a]
end
end
function setWantedPoints(plr, wp)
if (plr and wp and not plr.account.guest and tonumber(wp)) then
wp = tonumber(wp)
local a = plr.account.name
if (not wantedPoints[a]) then
wantedPoints[a] = wp
return true
end
wantedPoints[a] = wp
plr:setData("w", wantedPoints[a])
triggerEvent("onPlayerWPChange", plr, wantedPoints[a])
return true
end
end
function onPlayerWPChange(wp)
-- Stars
if (wp > 0 and wp <= 10) then
source.wantedLevel = 1
elseif (wp > 10 and wp <= 20) then
source.wantedLevel = 2
elseif (wp > 20 and wp <= 30) then
source.wantedLevel = 3
elseif (wp > 30 and wp <= 40) then
source.wantedLevel = 4
elseif (wp > 40 and wp <= 50) then
source.wantedLevel = 5
elseif (wp > 50) then
--if (source.wantedLevel ~= 60) then
source.wantedLevel = 6
--end
else
source.wantedLevel = 0
end
-- Nametag
if (wp > 0) then
source.nametagText = "["..tostring(source.wantedLevel).."] "..tostring(source.name)
else
source.nametagText = source.name
end
if (wp > 0) then
if (source.team.name == "Law") then
exports.UCDjobs:setPlayerJob(source, "Criminal")
end
end
end
addEvent("onPlayerWPChange")
addEventHandler("onPlayerWPChange", root, onPlayerWPChange)
|
local wantedPoints = {}
addEventHandler("onResourceStart", resourceRoot,
function ()
for _, plr in ipairs(Element.getAllByType("player")) do
if (not plr.account.guest) then
setWantedPoints(plr, exports.UCDaccounts:GAD(plr, "wp"))
end
end
end
)
addEventHandler("onResourceStop", resourceRoot,
function ()
for _, plr in ipairs(Element.getAllByType("player")) do
if (not plr.account.guest) then
exports.UCDaccounts:SAD(plr, "wp", getWantedPoints(plr))
end
end
end
)
function addWantedPoints(plr, wp)
if (plr and wp and not plr.account.guest and tonumber(wp)) then
wp = tonumber(wp)
local a = plr.account.name
if (not wantedPoints[a]) then
wantedPoints[a] = 0
end
setWantedPoints(plr, wantedPoints[a] + wp)
exports.UCDstats:setPlayerAccountStat(plr, "lifetimeWanted", exports.UCDstats:getPlayerAccountStat(plr, "lifetimeWanted") + wp)
return true
end
end
function getWantedPoints(plr)
if (plr and not plr.account.guest) then
local a = plr.account.name
if (not wantedPoints[a]) then
wantedPoints[a] = 0
end
return wantedPoints[a]
end
end
function setWantedPoints(plr, wp)
if (plr and wp and not plr.account.guest and tonumber(wp)) then
wp = tonumber(wp)
local a = plr.account.name
if (not wantedPoints[a]) then
wantedPoints[a] = wp
return true
end
wantedPoints[a] = wp
plr:setData("w", wantedPoints[a])
triggerEvent("onPlayerWPChange", plr, wantedPoints[a])
return true
end
end
function onPlayerWPChange(wp)
-- Stars
if (wp > 0 and wp <= 10) then
source.wantedLevel = 1
elseif (wp > 10 and wp <= 20) then
source.wantedLevel = 2
elseif (wp > 20 and wp <= 30) then
source.wantedLevel = 3
elseif (wp > 30 and wp <= 40) then
source.wantedLevel = 4
elseif (wp > 40 and wp <= 50) then
source.wantedLevel = 5
elseif (wp > 50) then
--if (source.wantedLevel ~= 60) then
source.wantedLevel = 6
--end
else
source.wantedLevel = 0
end
-- Nametag
if (wp > 0) then
source.nametagText = "["..tostring(source.wantedLevel).."] "..tostring(source.name)
else
source.nametagText = source.name
end
if (wp > 0) then
if (source.team.name == "Law") then
exports.UCDjobs:setPlayerJob(source, "Criminal")
end
end
end
addEvent("onPlayerWPChange")
addEventHandler("onPlayerWPChange", root, onPlayerWPChange)
|
UCDwanted
|
UCDwanted
- Added a wanted counter stat every time wp gets added
- Fixed a simple error with saving stats
|
Lua
|
mit
|
nokizorque/ucd,nokizorque/ucd
|
1a6d1715ad377f4ebe6ce29bde5a97badd98fc66
|
premakeUtils.lua
|
premakeUtils.lua
|
function coInitParams(_params)
co_baseAbsPath = os.getcwd()
print("co_baseAbsPath: "..co_baseAbsPath)
co_externalAbsPath = co_baseAbsPath .. "/external"
co_buildPath = "build/" .. _ACTION
local coreRelativePath = "."
if _params.coreRelativePath then
coreRelativePath = _params.coreRelativePath
end
local coreAbsolutePath = path.getabsolute(coreRelativePath)
co_prebuildPath = coreAbsolutePath .. "/build/prebuild.exe"
co_versionMajor = 0
co_versionMinor = 0
co_versionBuild = 0
end
function coSetWorkspaceDefaults(_name)
print("Generating workspace ".._name.."... (in "..co_buildPath..")")
workspace(_name)
co_allConfigurations = {"debug", "dev", "release", "prebuildDebug", "prebuildRelease"}
configurations(co_allConfigurations)
location(co_buildPath)
end
function coSetPCH(_dir, _projectName, _fileName)
pchheader(_projectName .. "/".. _fileName .. '.h')
pchsource(_fileName .. '.cpp')
--[[
filter { "action:vs*" }
pchheader(_fileName .. '.h')
pchsource(_fileName .. '.cpp')
filter { "action:not vs*" }
pchheader(_dir .. '/' .. _fileName .. '.h')
filter {}
--]]
end
function coSetProjectDefaults(_name, _options)
local projectBasePath = "../.."
local buildAbsPath = projectBasePath .. "/" .. co_buildPath
local buildLocation = buildAbsPath.."/projects"
print("Generating project ".._name.."... (in "..buildLocation..")")
project(_name)
location(buildLocation)
architecture "x86_64"
warnings "Extra"
kind "StaticLib"
objdir(buildAbsPath .. "/obj")
targetdir(buildAbsPath .. "/bin/$(Configuration)")
libdirs { "$(OutDir)" }
defines { "coVERSION_MAJOR="..co_versionMajor, "coVERSION_MINOR="..co_versionMinor, "coVERSION_BUILD="..co_versionBuild }
includedirs { projectBasePath.."/build/gen", co_externalAbsPath }
includedirs(co_srcDirs)
debugdir "$(OutDir)"
defines { "coPROJECT_NAME=".._name }
if not (_options and _options.prebuildDependency) then
--removeconfigurations {"prebuild*"}
configurations { "debug", "dev", "release" }
end
filter{"configurations:debug or dev or prebuildDebug"}
defines {"coDEBUG", "coDEV"}
filter{"configurations:debug or dev or release"}
defines {"coREFLECT_ENABLED"}
filter { "configurations:dev or release or prebuildRelease" }
optimize "On"
filter {}
end
function coSetCppProjectDefaults(_name)
coSetProjectDefaults(_name)
rtti "Off"
language "C++"
exceptionhandling "Off"
vectorextensions "SSE2"
floatingpoint "Strict" -- Not slower than Fast, and helps for cross-platform/compiler determinism.
editandcontinue "Off"
symbols "On"
cppdialect "C++17"
runtime "Release" -- Even on debug builds, Unreal is setup this way anyway.
flags { "NoMinimalRebuild", "FatalWarnings", "MultiProcessorCompile" }
files { "**.cpp", "**.h", "**.inl", "**.frag", "**.vert", "**.comp", "**.tesc", "**.tese", "**.geom", "**.importShaders"}
if os.isfile("pch.h") then
coSetPCH(co_projectDir, _name, "pch")
end
filter { "gmake" }
buildoptions { "-Wno-reorder", "-Wno-deprecated" }
includedirs { gmakeIncludeDir }
filter { "action:vs*" }
files { "*.natvis"}
defines { "_HAS_EXCEPTIONS=0" }
--flags { "StaticRuntime" }
--linkoptions { "/ENTRY:mainCRTStartup" } -- TODO: Not working with DLL, should avoid that case somehow.
linkoptions {"/ignore:4221"} -- warns when .cpp are empty depending on the order of obj linking.
filter { "configurations:dev or release or prebuildRelease" }
optimize "Speed"
omitframepointer "On"
filter {"configurations:debug or dev or release"}
filter {'files:**.vert or **.frag or **.comp or **.geom'}
co_shadersFolder = "$(OutDir)/shaders/".._name
shaderOutPath = co_shadersFolder.."/%{file.name}.spv"
buildmessage 'Compiling %{file.relpath}'
buildcommands { '$(GLSLANG)/glslangValidator.exe -G -o "'..shaderOutPath ..'" %{file.relpath}' }
buildoutputs { shaderOutPath }
filter {}
--[[
if os.isfile("reflect.cpp") then
local projectBasePath = "../.."
local genAbsPath = "../../gen"
local command = co_prebuildPath .. ' "' .. path.getabsolute(co_projectDir, path.getabsolute(projectBasePath)) .. "/.." .. '" "' .. genAbsPath .. '" "' .. _name .. '" "'.. _name ..'/pch.h"'
command = command .. ' -I="$(UniversalCRT_IncludePath)"'
for _, d in pairs(co_srcDirs) do
command = command .. ' -I="'..d..'"'
end
prebuildcommands{command}
end
--]]
filter {}
end
function coSetShaderDefaults(_name)
-- Defaults
--language "C++" -- We don't have better here
---[[
--]]
end
function coSetProjectDependencies(_deps)
if not co_dependencies then
co_dependencies = {}
end
for _,v in pairs(_deps) do
table.insert(co_dependencies, v)
end
-- Add custom build commands on the .importShaders file to import shaders from other projects
filter {'files:**.importShaders'}
buildmessage 'Importing shaders...'
for _,v in pairs(_deps) do
local srcDir, foundDir = coFindDir(co_srcDirs, v)
if foundDir == nil then
error("Failed to find the project: "..v)
else
if os.isdir(foundDir.."/shaders") then
shadersDir = srcDir.."/../"..co_buildPath.."/bin/$(Configuration)/shaders/"..v
for _, f in pairs(os.matchfiles(foundDir.."/shaders/*")) do
name = path.getname(f)
local inputs = shadersDir.."/"..name..".spv"
buildinputs { inputs }
buildcommands { "{COPY} "..inputs.." $(OutDir)shaders/"..v }
buildoutputs { "$(OutDir)shaders/"..v.."/"..name..".spv" }
end
--postbuildcommands { "{COPY} "..shadersDir.."/* $(OutDir)shaders/"..v }
end
end
end
filter {}
links(_deps)
end
function coFindDir(_srcDirs, _dirName)
for _, d in pairs(_srcDirs) do
local foundDirs = os.matchdirs(d.."/".._dirName)
for _, e in pairs(foundDirs) do
return d, e
end
end
return nil
end
function coIncludeProject(_srcDirs, _projectName)
local srcDir, foundDir = coFindDir(_srcDirs, _projectName)
if foundDir == nil then
error("Failed to find the project: ".._projectName)
else
co_projectSrcDir = srcDir
co_projectDir = foundDir
include(foundDir)
end
end
function coGenerateProjectWorkspace(_params)
srcDirs = {path.getabsolute("src")}
co_workspaceDependencies = {}
for k, d in pairs(_params.dependencies) do
table.insert(srcDirs, path.getabsolute(d.."/src"))
co_workspaceDependencies[k] = path.getabsolute(d)
end
co_srcDirs = srcDirs
coSetWorkspaceDefaults(_params.name)
startproject(_params.projects[0])
for _, p in pairs(_params.projects) do
coIncludeProject(srcDirs, p)
end
if co_dependencies then
for _, d in pairs(co_dependencies) do
coIncludeProject(srcDirs, d)
end
end
end
|
function coInitParams(_params)
co_baseAbsPath = os.getcwd()
print("co_baseAbsPath: "..co_baseAbsPath)
co_externalAbsPath = co_baseAbsPath .. "/external"
co_buildPath = "build/" .. _ACTION
local coreRelativePath = "."
if _params.coreRelativePath then
coreRelativePath = _params.coreRelativePath
end
local coreAbsolutePath = path.getabsolute(coreRelativePath)
co_prebuildPath = coreAbsolutePath .. "/build/prebuild.exe"
co_versionMajor = 0
co_versionMinor = 0
co_versionBuild = 0
end
function coSetWorkspaceDefaults(_name)
print("Generating workspace ".._name.."... (in "..co_buildPath..")")
workspace(_name)
co_allConfigurations = {"debug", "dev", "release", "prebuildDebug", "prebuildRelease"}
configurations(co_allConfigurations)
location(co_buildPath)
end
function coSetPCH(_dir, _projectName, _fileName)
pchheader(_projectName .. "/".. _fileName .. '.h')
pchsource(_fileName .. '.cpp')
--[[
filter { "action:vs*" }
pchheader(_fileName .. '.h')
pchsource(_fileName .. '.cpp')
filter { "action:not vs*" }
pchheader(_dir .. '/' .. _fileName .. '.h')
filter {}
--]]
end
function coSetProjectDefaults(_name, _options)
local projectBasePath = "../.."
local buildAbsPath = projectBasePath .. "/" .. co_buildPath
local buildLocation = buildAbsPath.."/projects"
print("Generating project ".._name.."... (in "..buildLocation..")")
project(_name)
location(buildLocation)
architecture "x86_64"
warnings "Extra"
kind "StaticLib"
objdir(buildAbsPath .. "/obj")
targetdir(buildAbsPath .. "/bin/$(Configuration)")
libdirs { "$(OutDir)" }
defines { "coVERSION_MAJOR="..co_versionMajor, "coVERSION_MINOR="..co_versionMinor, "coVERSION_BUILD="..co_versionBuild }
includedirs { projectBasePath.."/build/gen", co_externalAbsPath }
includedirs(co_srcDirs)
debugdir "$(OutDir)"
defines { "coPROJECT_NAME=".._name }
if not (_options and _options.prebuildDependency) then
--removeconfigurations {"prebuild*"}
configurations { "debug", "dev", "release" }
end
filter{"configurations:debug or dev or prebuildDebug"}
defines {"coDEBUG", "coDEV"}
filter{"configurations:debug or dev or release"}
defines {"coREFLECT_ENABLED"}
filter { "configurations:dev or release or prebuildRelease" }
optimize "On"
filter {}
end
function coSetCppProjectDefaults(_name)
coSetProjectDefaults(_name)
rtti "Off"
language "C++"
exceptionhandling "Off"
vectorextensions "SSE2"
floatingpoint "Strict" -- Not slower than Fast, and helps for cross-platform/compiler determinism.
editandcontinue "Off"
symbols "On"
cppdialect "C++17"
runtime "Release" -- Even on debug builds, Unreal is setup this way anyway.
flags { "NoMinimalRebuild", "FatalWarnings", "MultiProcessorCompile" }
files { "**.cpp", "**.h", "**.inl", "**.frag", "**.vert", "**.comp", "**.tesc", "**.tese", "**.geom", "**.importShaders"}
if os.isfile("pch.h") then
coSetPCH(co_projectDir, _name, "pch")
end
filter { "gmake" }
buildoptions { "-Wno-reorder", "-Wno-deprecated" }
includedirs { gmakeIncludeDir }
filter { "action:vs*" }
files { "*.natvis"}
defines { "_HAS_EXCEPTIONS=0" }
--flags { "StaticRuntime" }
--linkoptions { "/ENTRY:mainCRTStartup" } -- TODO: Not working with DLL, should avoid that case somehow.
linkoptions {"/ignore:4221"} -- warns when .cpp are empty depending on the order of obj linking.
filter { "configurations:dev or release or prebuildRelease" }
optimize "Speed"
omitframepointer "On"
filter {"configurations:debug or dev or release"}
filter {'files:**.vert or **.frag or **.comp or **.geom'}
co_shadersFolder = "$(OutDir)/shaders/".._name
shaderOutPath = co_shadersFolder.."/%{file.name}.spv"
buildmessage 'Compiling %{file.relpath}'
buildcommands { '$(GLSLANG)/glslangValidator.exe -G -o "'..shaderOutPath ..'" %{file.relpath}' }
buildoutputs { shaderOutPath }
filter {}
--[[
if os.isfile("reflect.cpp") then
local projectBasePath = "../.."
local genAbsPath = "../../gen"
local command = co_prebuildPath .. ' "' .. path.getabsolute(co_projectDir, path.getabsolute(projectBasePath)) .. "/.." .. '" "' .. genAbsPath .. '" "' .. _name .. '" "'.. _name ..'/pch.h"'
command = command .. ' -I="$(UniversalCRT_IncludePath)"'
for _, d in pairs(co_srcDirs) do
command = command .. ' -I="'..d..'"'
end
prebuildcommands{command}
end
--]]
filter {}
end
function coSetShaderDefaults(_name)
-- Defaults
--language "C++" -- We don't have better here
---[[
--]]
end
function coSetProjectDependencies(_deps)
if not co_dependencies then
co_dependencies = {}
end
for _,v in pairs(_deps) do
table.insert(co_dependencies, v)
end
-- Add custom build commands on the .importShaders file to import shaders from other projects
filter {'files:**.importShaders'}
buildmessage 'Importing shaders...'
for _,v in pairs(_deps) do
local srcDir, foundDir = coFindDir(co_srcDirs, v)
if foundDir == nil then
error("Failed to find the project: "..v)
else
if path.normalize(path.join(srcDir, "..")) ~= path.normalize(co_baseAbsPath) then
if os.isdir(foundDir.."/shaders") then
print("Setting up shaders import from: "..foundDir.."/shaders")
shadersDir = srcDir.."/../"..co_buildPath.."/bin/$(Configuration)/shaders/"..v
for _, f in pairs(os.matchfiles(foundDir.."/shaders/*")) do
name = path.getname(f)
local inputs = shadersDir.."/"..name..".spv"
buildinputs { inputs }
buildcommands { "{COPY} "..inputs.." $(OutDir)shaders/"..v }
buildoutputs { "$(OutDir)shaders/"..v.."/"..name..".spv" }
end
--postbuildcommands { "{COPY} "..shadersDir.."/* $(OutDir)shaders/"..v }
end
end
end
end
filter {}
links(_deps)
end
function coFindDir(_srcDirs, _dirName)
for _, d in pairs(_srcDirs) do
local foundDirs = os.matchdirs(d.."/".._dirName)
for _, e in pairs(foundDirs) do
return d, e
end
end
return nil
end
function coIncludeProject(_srcDirs, _projectName)
local srcDir, foundDir = coFindDir(_srcDirs, _projectName)
if foundDir == nil then
error("Failed to find the project: ".._projectName)
else
co_projectSrcDir = srcDir
co_projectDir = foundDir
include(foundDir)
end
end
function coGenerateProjectWorkspace(_params)
srcDirs = {path.getabsolute("src")}
co_workspaceDependencies = {}
for k, d in pairs(_params.dependencies) do
table.insert(srcDirs, path.getabsolute(d.."/src"))
co_workspaceDependencies[k] = path.getabsolute(d)
end
co_srcDirs = srcDirs
coSetWorkspaceDefaults(_params.name)
startproject(_params.projects[0])
for _, p in pairs(_params.projects) do
coIncludeProject(srcDirs, p)
end
if co_dependencies then
for _, d in pairs(co_dependencies) do
coIncludeProject(srcDirs, d)
end
end
end
|
Fixed shaders import when importing from same workspace.
|
Fixed shaders import when importing from same workspace.
|
Lua
|
mit
|
smogpill/core,smogpill/core
|
999fbfe300c82a5865fee7cea98c4bfc068a4055
|
test/test_writeObject.lua
|
test/test_writeObject.lua
|
local myTester = torch.Tester()
local tests = {}
-- checks that an object can be written and unwritten
-- returns false if an error occurs
local function serializeAndDeserialize(obj)
local file = torch.MemoryFile()
file:binary()
local ok, msg = pcall (file.writeObject, file, obj)
myTester:assert(ok, 'error in writing an object' )
file:seek(1)
local ok, copy = pcall(file.readObject, file)
if not ok then print(copy) end
myTester:assert(ok, 'error in reading an object ')
return copy
end
function tests.test_can_write_a_nil_closure()
local a
local function closure()
if not a then return 1 end
return 0
end
local copyClosure = serializeAndDeserialize(closure)
myTester:assert(copyClosure() == closure(), 'the closures should give same output')
end
function tests.test_nil_upvalues_in_closure()
local a = 1
local b
local c = 2
local function closure()
if not b then return c end
return a
end
local copyClosure = serializeAndDeserialize(closure)
myTester:assert(copyClosure() == closure(), 'the closures should give same output')
end
function tests.test_global_function_in_closure()
local x = "5"
local function closure(str)
return tonumber(str .. x)
end
local copyClosure = serializeAndDeserialize(closure)
myTester:assert(copyClosure("3") == closure("3"), 'the closures should give same output')
end
function tests.test_a_recursive_closure()
local foo
foo = function (level)
if level == 1 then return 1 end
return 1+foo(level-1)
end
local copyFoo = serializeAndDeserialize(foo)
myTester:assert(copyFoo(42) == foo(42), 'the closures should give same output')
end
function tests.test_a_tensor()
local x = torch.rand(5, 10)
local xcopy = serializeAndDeserialize(x)
myTester:assert(x:norm() == xcopy:norm(), 'tensors should be the same')
end
myTester:add(tests)
myTester:run()
|
local myTester = torch.Tester()
local tests = {}
-- checks that an object can be written and unwritten
-- returns false if an error occurs
local function serializeAndDeserialize(obj)
local file = torch.MemoryFile()
file:binary()
local ok, msg = pcall (file.writeObject, file, obj)
myTester:assert(ok, 'error in writing an object' )
file:seek(1)
local ok, copy = pcall(file.readObject, file)
if not ok then print(copy) end
myTester:assert(ok, 'error in reading an object ')
return copy
end
function tests.test_can_write_a_nil_closure()
local a
local function closure()
if not a then return 1 end
return 0
end
local copyClosure = serializeAndDeserialize(closure)
myTester:assert(copyClosure() == closure(), 'the closures should give same output')
end
function tests.test_nil_upvalues_in_closure()
local a = 1
local b
local c = 2
local function closure()
if not b then return c end
return a
end
local copyClosure = serializeAndDeserialize(closure)
myTester:assert(copyClosure() == closure(), 'the closures should give same output')
end
function tests.test_global_function_in_closure()
local x = "5"
local function closure(str)
return tonumber(str .. x)
end
local copyClosure = serializeAndDeserialize(closure)
myTester:assert(copyClosure("3") == closure("3"), 'the closures should give same output')
end
function tests.test_a_recursive_closure()
local foo
foo = function (level)
if level == 1 then return 1 end
return 1+foo(level-1)
end
local copyFoo = serializeAndDeserialize(foo)
myTester:assert(copyFoo(42) == foo(42), 'the closures should give same output')
end
function tests.test_a_tensor()
local x = torch.rand(5, 10)
local xcopy = serializeAndDeserialize(x)
myTester:assert(x:norm() == xcopy:norm(), 'tensors should be the same')
end
-- Regression test for bug reported in issue 456.
function tests.test_empty_table()
local file = torch.MemoryFile()
file:writeObject({})
end
myTester:add(tests)
myTester:run()
|
Regression test for MemoryFile bug.
|
Regression test for MemoryFile bug.
|
Lua
|
bsd-3-clause
|
Moodstocks/torch7,wgapl/torch7,Moodstocks/torch7,Atcold/torch7,yozw/torch7,nicholas-leonard/torch7,adamlerer/torch7,wickedfoo/torch7,colesbury/torch7,szagoruyko/torch7,yozw/torch7,adamlerer/torch7,diz-vara/torch7,wgapl/torch7,nicholas-leonard/torch7,Atcold/torch7,colesbury/torch7,wickedfoo/torch7,diz-vara/torch7,szagoruyko/torch7
|
7b19c8c035681f990dec3bb57946360e0a47ae85
|
samples/gstvideo.lua
|
samples/gstvideo.lua
|
#! /usr/bin/env lua
--
-- Sample GStreamer application, port of public Vala GStreamer Video
-- Example (http://live.gnome.org/Vala/GStreamerSample)
--
require 'lgi'
local GLib = require 'lgi.GLib'
local Gtk = require 'lgi.Gtk'
local Gst = require 'lgi.Gst'
local GstInterfaces = require 'lgi.GstInterfaces'
Gtk.init()
Gst.init()
local pipeline = Gst.Pipeline.new('mypipeline')
local src = Gst.ElementFactory.make('videotestsrc', 'video')
local sink = Gst.ElementFactory.make('xvimagesink', 'sink')
pipeline:add(src)
pipeline:add(sink)
src:link(sink)
local function on_play()
end
local function on_stop()
pipeline.set_state(Gst.State.READY)
end
local vbox = Gtk.Box.new(Gtk.Orientation.VERTICAL, 0)
local drawing_area = Gtk.DrawingArea()
drawing_area:set_size_request(300, 150)
vbox:pack_start(drawing_area, true, true, 0)
local play_button = Gtk.Button.new_from_stock(Gtk.STOCK_MEDIA_PLAY)
play_button.on_clicked = function()
-- sink:set_window_handle(0)
pipeline:set_state(Gst.State.PLAYING)
end
local stop_button = Gtk.Button.new_from_stock(Gtk.STOCK_MEDIA_STOP)
stop_button.on_clicked = function()
pipeline:set_state(Gst.State.READY)
end
local quit_button = Gtk.Button.new_from_stock(Gtk.STOCK_QUIT)
quit_button.on_clicked = Gtk.main_quit
local button_box = Gtk.ButtonBox.new(Gtk.Orientation.HORIZONTAL)
button_box:add(play_button)
button_box:add(stop_button)
button_box:add(quit_button)
vbox:pack_start(button_box, false, true, 0)
local window = Gtk.Window {
title = 'Video Player',
child = vbox,
on_destroy = Gtk.main_quit
}
window:show_all()
Gtk.main()
|
#! /usr/bin/env lua
--
-- Sample GStreamer application, port of public Vala GStreamer Video
-- Example (http://live.gnome.org/Vala/GStreamerSample)
--
require 'lgi'
local GLib = require 'lgi.GLib'
local Gtk = require 'lgi.Gtk'
local Gst = require 'lgi.Gst'
local GstInterfaces = require 'lgi.GstInterfaces'
Gtk.init()
Gst.init()
local pipeline = Gst.Pipeline.new('mypipeline')
local src = Gst.ElementFactory.make('videotestsrc', 'video')
local sink = Gst.ElementFactory.make('xvimagesink', 'sink')
pipeline:add(src)
pipeline:add(sink)
src:link(sink)
local vbox = Gtk.Box.new(Gtk.Orientation.VERTICAL, 0)
local drawing_area = Gtk.DrawingArea()
drawing_area:set_size_request(300, 150)
vbox:pack_start(drawing_area, true, true, 0)
local play_button = Gtk.Button.new_from_stock(Gtk.STOCK_MEDIA_PLAY)
play_button.on_clicked = function()
sink:set_window_handle(0)
pipeline:set_state(Gst.State.PLAYING)
end
local stop_button = Gtk.Button.new_from_stock(Gtk.STOCK_MEDIA_STOP)
stop_button.on_clicked = function()
pipeline:set_state(Gst.State.READY)
end
local quit_button = Gtk.Button.new_from_stock(Gtk.STOCK_QUIT)
quit_button.on_clicked = Gtk.main_quit
local button_box = Gtk.ButtonBox.new(Gtk.Orientation.HORIZONTAL)
button_box:add(play_button)
button_box:add(stop_button)
button_box:add(quit_button)
vbox:pack_start(button_box, false, true, 0)
local window = Gtk.Window {
title = 'Video Player',
child = vbox,
on_destroy = Gtk.main_quit
}
window:show_all()
Gtk.main()
|
More fixes to video sample, still dysfunctional though.
|
More fixes to video sample, still dysfunctional though.
|
Lua
|
mit
|
pavouk/lgi,zevv/lgi,psychon/lgi
|
fa77dc94b184a75495329dc46044841968f3b804
|
script/c88754763.lua
|
script/c88754763.lua
|
--CX 熱血指導神アルティメットレーナー
function c88754763.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.XyzFilterFunction(c,9),4)
c:EnableReviveLimit()
--cannot be target
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetValue(1)
c:RegisterEffect(e1)
--draw
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DRAW+CATEGORY_DAMAGE)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCondition(c88754763.condition)
e1:SetCost(c88754763.cost)
e1:SetTarget(c88754763.target)
e1:SetOperation(c88754763.operation)
c:RegisterEffect(e1)
end
function c800000040.condition(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetOverlayGroup():IsExists(Card.IsType,1,nil,TYPE_XYZ)
end
function c88754763.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c88754763.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp,1) end
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c88754763.operation(e,tp,eg,ep,ev,re,r,rp,chk)
local ct=Duel.Draw(tp,1,REASON_EFFECT)
if ct==0 then return end
local dc=Duel.GetOperatedGroup():GetFirst()
Duel.ConfirmCards(1-tp,dc)
if dc:IsType(TYPE_MONSTER) then
Duel.Damage(1-tp,800,REASON_EFFECT)
end
Duel.ShuffleHand(tp)
end
|
--CX 熱血指導神アルティメットレーナー
function c88754763.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.XyzFilterFunction(c,9),4)
c:EnableReviveLimit()
--cannot be target
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetValue(1)
c:RegisterEffect(e1)
--draw
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_DRAW+CATEGORY_DAMAGE)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1)
e2:SetCondition(c88754763.condition)
e2:SetCost(c88754763.cost)
e2:SetTarget(c88754763.target)
e2:SetOperation(c88754763.operation)
c:RegisterEffect(e2)
end
function c88754763.condition(e)
return e:GetHandler():GetOverlayGroup():IsExists(Card.IsType,1,nil,TYPE_XYZ)
end
function c88754763.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c88754763.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp,1) end
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c88754763.operation(e,tp,eg,ep,ev,re,r,rp,chk)
local ct=Duel.Draw(tp,1,REASON_EFFECT)
if ct==0 then return end
local dc=Duel.GetOperatedGroup():GetFirst()
Duel.ConfirmCards(1-tp,dc)
if dc:IsType(TYPE_MONSTER) then
Duel.Damage(1-tp,800,REASON_EFFECT)
end
Duel.ShuffleHand(tp)
end
|
Update c88754763.lua
|
Update c88754763.lua
fix
|
Lua
|
mit
|
sidschingis/DevProLauncher,SuperAndroid17/DevProLauncher,Tic-Tac-Toc/DevProLauncher
|
53a2c43bed17127c8e4641ec07c39136a1aa4c5d
|
vi_tags.lua
|
vi_tags.lua
|
local M = {}
local state = {
tags = nil, -- current set of tags
tagstack = {},-- current tag stack: list of { i=num, tags={tag list} }
tagidx = 0, -- index into tagstack of current level
lasttag = nil,-- last tag list
timestamp = nil, -- tags file modification time.
}
M.state = state
-- Load a tags file
local function load_tags()
vi_mode.err("Loading tags file...")
local tagf = io.open("tags") -- TODO: configurable tags file location
local results = {}
local pat = "^([^\t]*)\t([^\t]*)\t(.*)$"
if tagf then
state.timestamp = lfs.attributes("tags", "modification")
for line in tagf:lines() do
local tname, fname, excmd = line:match(pat)
local flags
if tname then
-- Initialise to an empty list if necessary
if not results[tname] then results[tname] = {} end
-- And append.
local l = results[tname] -- now guaranteed to be a table
do
-- Try to separate the ex command from extension fields
local e,f = excmd:match('^(.-);"\t(.*)$')
if e then
excmd = e
flags = f
end
end
l[#l+1] = { sym=tname, filename=fname, excmd=excmd, flags=flags }
end
end
tagf:close()
end
state.tags = results
end
-- Return or load the tags
local function get_tags()
-- TODO: check if tags file needs reloading
if state.tags == nil or lfs.attributes("tags", "modification") ~= state.timestamp then
load_tags()
end
return state.tags
end
function M.find_tag_exact(name)
local tags = get_tags()
local result = tags[name]
if result then
local newidx = state.tagidx + 1
-- Clear the stack above where we are.
while newidx <= #state.tagstack do
state.tagstack[#state.tagstack] = nil
end
state.tagstack[newidx] = {
i=1, -- which tag within this list
tags=result, -- this level's tags
fromname=buffer.filename, -- where we came from
frompos=buffer.current_pos,-- where we came from
}
state.lasttag = result
state.tagidx = newidx
return result[1]
else
return nil
end
end
-- Return a list of tags matching Lua pat
function M.match_tag(pat)
local tags = get_tags()
local result = {}
for name,_ in pairs(tags) do
if name:match(pat) then
result[#result+1] = name
end
end
if #result > 0 then return result end
-- return nil if nothing found
end
function M.pop_tag()
if state.tagidx >= 1 then
local tos = state.tagstack[state.tagidx]
io.open_file(tos.fromname)
buffer.goto_pos(tos.frompos)
state.tagidx = state.tagidx - 1
else
vi_mode.err("Top of stack")
end
end
-- Return all the tags in the current level
function M.get_all()
if state.tagidx > 0 then
return state.tagstack[state.tagidx].tags
end
end
-- Go to a particular tag
function M.goto_tag(tag)
io.open_file(tag.filename)
local excmd = tag.excmd
local _, pat = excmd:match("^([?/])(.*)%1$")
if pat then
-- TODO: properly handle regexes and line number tags.
-- For now, assume it's a fixed string possibly with ^ and $ around it.
pat = pat:match("^^?(.-)$?$")
buffer.current_pos = 0
buffer.search_anchor()
local pos = buffer:search_next(buffer.FIND_REGEXP, pat)
if pos >= 0 then
buffer.goto_pos(pos)
else
vi_mode.err("Not found: " .. pat)
end
return
end
-- Try a numeric line number
local pat = excmd:match("^(%d+)$")
if pat then
buffer.goto_line(tonumber(pat)-1)
return
end
-- unknown tag pattern
vi_mode.err('Tag pat: '..excmd)
end
-- Return the next tag at this level, or nil.
function M.tag_next()
local taglist = state.tagstack[state.tagidx]
if taglist.i < #taglist.tags then
taglist.i = taglist.i + 1
return taglist.tags[taglist.i]
end
end
-- Return the next tag at this level, or nil.
function M.tag_prev()
local taglist = state.tagstack[state.tagidx]
if taglist.i > 1 then
taglist.i = taglist.i - 1
return taglist.tags[taglist.i]
end
end
return M
|
local M = {}
local state = {
tags = nil, -- current set of tags
tagstack = {},-- current tag stack: list of { i=num, tags={tag list} }
tagidx = 0, -- index into tagstack of current level
lasttag = nil,-- last tag list
timestamp = nil, -- tags file modification time.
}
M.state = state
-- Load a tags file
local function load_tags()
vi_mode.err("Loading tags file...")
local tagf = io.open("tags") -- TODO: configurable tags file location
local results = {}
local pat = "^([^\t]*)\t([^\t]*)\t(.*)$"
if tagf then
state.timestamp = lfs.attributes("tags", "modification")
for line in tagf:lines() do
local tname, fname, excmd = line:match(pat)
local flags
if tname then
-- Initialise to an empty list if necessary
if not results[tname] then results[tname] = {} end
-- And append.
local l = results[tname] -- now guaranteed to be a table
do
-- Try to separate the ex command from extension fields
local e,f = excmd:match('^(.-);"\t(.*)$')
if e then
excmd = e
flags = f
end
end
l[#l+1] = { sym=tname, filename=fname, excmd=excmd, flags=flags }
end
end
tagf:close()
end
state.tags = results
end
-- Return or load the tags
local function get_tags()
-- TODO: check if tags file needs reloading
if state.tags == nil or lfs.attributes("tags", "modification") ~= state.timestamp then
load_tags()
end
return state.tags
end
function M.find_tag_exact(name)
local tags = get_tags()
local result = tags[name]
if result then
local newidx = state.tagidx + 1
-- Clear the stack above where we are.
while newidx <= #state.tagstack do
state.tagstack[#state.tagstack] = nil
end
state.tagstack[newidx] = {
i=1, -- which tag within this list
tags=result, -- this level's tags
fromname=buffer.filename, -- where we came from
frompos=buffer.current_pos,-- where we came from
}
state.lasttag = result
state.tagidx = newidx
return result[1]
else
return nil
end
end
-- Return a list of tags matching Lua pat
function M.match_tag(pat)
local tags = get_tags()
local result = {}
for name,_ in pairs(tags) do
if name:match(pat) then
result[#result+1] = name
end
end
if #result > 0 then return result end
-- return nil if nothing found
end
function M.pop_tag()
if state.tagidx >= 1 then
local tos = state.tagstack[state.tagidx]
io.open_file(tos.fromname)
buffer.goto_pos(tos.frompos)
state.tagidx = state.tagidx - 1
else
vi_mode.err("Top of stack")
end
end
-- Return all the tags in the current level
function M.get_all()
if state.tagidx > 0 then
return state.tagstack[state.tagidx].tags
end
end
-- Go to a particular tag
function M.goto_tag(tag)
io.open_file(tag.filename)
local excmd = tag.excmd
local _, pat = excmd:match("^([?/])(.*)%1$")
if pat then
-- TODO: properly handle regexes and line number tags.
-- For now, assume it's a fixed string possibly with ^ and $ around it.
pat = pat:match("^^?(.-)$?$")
-- Tag file regexes are treated as in vim's nomagic; ie most special
-- characters are only magic if backquoted (except .).
-- This is an approximation for now.
pat = pat:gsub("(%\\?)([%[%]*+])", function(pre, magic)
if pre ~= "" then
return pre .. magic
else
return "\\" .. magic
end
end)
buffer.current_pos = 0
buffer.search_anchor()
local pos = buffer:search_next(buffer.FIND_REGEXP, pat)
if pos >= 0 then
buffer.goto_pos(pos)
else
vi_mode.err("Not found: " .. pat)
end
return
end
-- Try a numeric line number
local pat = excmd:match("^(%d+)$")
if pat then
buffer.goto_line(tonumber(pat)-1)
return
end
-- unknown tag pattern
vi_mode.err('Tag pat: '..excmd)
end
-- Return the next tag at this level, or nil.
function M.tag_next()
local taglist = state.tagstack[state.tagidx]
if taglist.i < #taglist.tags then
taglist.i = taglist.i + 1
return taglist.tags[taglist.i]
end
end
-- Return the next tag at this level, or nil.
function M.tag_prev()
local taglist = state.tagstack[state.tagidx]
if taglist.i > 1 then
taglist.i = taglist.i - 1
return taglist.tags[taglist.i]
end
end
return M
|
Make an attempt to convert regular expressions in tag search patterns to the right format. This fixes jumping to tags for functions with pointer arguments.
|
Make an attempt to convert regular expressions in tag search patterns to the right
format. This fixes jumping to tags for functions with pointer arguments.
|
Lua
|
mit
|
jugglerchris/textadept-vi,erig0/textadept-vi,jugglerchris/textadept-vi
|
8072eac3ed1453803a64fa8d21100e67bc1315a4
|
share/lua/website/videobash.lua
|
share/lua/website/videobash.lua
|
-- libquvi-scripts
-- Copyright (C) 2011 Thomas Preud'homme <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
-- Identify the script.
function ident (self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "videobash%.com"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain}, {"/video_show/"})
return r
end
-- Query available formats.
function query_formats(self)
self.formats = 'default'
return self
end
-- Parse media URL.
function parse (self)
self.host_id = "videobash"
local page = quvi.fetch(self.page_url)
local _,_,s = page:find("<title>(.-)%s+-")
self.title = s or error ("no match: media title")
local _,_,s = page:find("addFavorite%((%d+)")
self.id = s or error ("no match: media id")
local s = page:match('video_url="(.-);')
or error("no match: media url")
s = s:gsub("['%s+]",'')
self.url = {s}
return self
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2011 Thomas Preud'homme <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
-- Identify the script.
function ident (self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "videobash%.com"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain}, {"/video_show/"})
return r
end
-- Query available formats.
function query_formats(self)
self.formats = 'default'
return self
end
-- Parse media URL.
function parse (self)
self.host_id = "videobash"
local page = quvi.fetch(self.page_url)
local _,_,s = page:find("<title>(.-)%s+-")
self.title = s or error ("no match: media title")
local _,_,s = page:find("addFavorite%((%d+)")
self.id = s or error ("no match: media id")
local s = page:match('video_url=(.-)&')
or error("no match: media url")
local U = require 'quvi/util'
self.url = {U.unescape(s)}
return self
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
FIX: videobash.lua: media URL pattern
|
FIX: videobash.lua: media URL pattern
* Fix "error: videobash.lua:54: no match: media url"
* Unescape media URL
|
Lua
|
agpl-3.0
|
legatvs/libquvi-scripts,alech/libquvi-scripts,alech/libquvi-scripts,DangerCove/libquvi-scripts,DangerCove/libquvi-scripts,hadess/libquvi-scripts-iplayer,legatvs/libquvi-scripts,hadess/libquvi-scripts-iplayer
|
63dc89a24c054aa7c53e37c0bf6340fd07a73539
|
Abillist.lua
|
Abillist.lua
|
--[[
This module prints the list of all Pokémon, alternative forms included, having
a given ability.
--]]
local k = {}
local mw = require('mw')
local abillib = require('Wikilib-abils')
local box = require('Box')
local css = require('Css')
local links = require('Links')
local list = require('Wikilib-lists')
--local mg = require('Wikilib-multigen')
local ms = require('MiniSprite')
local oop = require('Wikilib-oop')
local tab = require('Wikilib-tables') -- luacheck: no unused
local txt = require('Wikilib-strings') -- luacheck: no unused
local pokes = require('Poké-data')
--[[
Class representing a list entry. Fulfills requirements of makeList, sortNdex
and sortForms of Wikilib/lists
--]]
local Entry = oop.makeClass(list.PokeSortableEntry)
Entry.printTypeBox = function(type, typesCount)
return box.boxTipoLua(
string.fu(type),
'text-center roundy-5',
string.interp('padding: 0 0.5ex; margin-bottom: 0.2ex; height: ${width}%;',
{width = 100 / typesCount})
)
end
--[[
Printing ability is a complex job: event have to be handled, as well as
generation changes. The first argumetn is the ability to be printed, the second
one whether it should be marked or not, to be used for events.
--]]
Entry.printAbil = function(abil, marked)
if not abil then
return marked and '' or 'Nessuna'
end
-- Marked abilities are italic
local toHTML
if marked then
toHTML = function(ability)
return string.interp([=[<div>''${abil}''</div>]=],
{
abil = links.aColor(ability, '000'),
})
end
else
toHTML = links.aColor
end
if type(abil) == 'string' then
return toHTML(abil, '000')
end
-- Adding generations superscripts
return table.concat(table.map(abillib.abilspan(abil), function(v)
return string.interp(
'<div>${abil}<sup>${gen}</sup></div>',
{
abil = v.abil == 'Nessuna' and v.abil
or toHTML(v.abil, '000'),
gen = v.first == v.last and v.first
or table.concat{v.first, '-', v.last}
})
end))
end
--[[
Constructor: the first argument is an entry from Poké/data, the second one its
key and the third is the ability the Pokémon must have. As specified by
makeList in Wikilib/lists, returns nil whenever the Pokémon can not have the
ability.
--]]
Entry.new = function(pokeAbil, name, abil)
if not table.deepSearch(pokeAbil, abil) then
return nil
end
local this = Entry.super.new(name, pokes[name].ndex)
this = table.merge(this, pokeAbil)
return setmetatable(table.merge(this, pokes[name]), Entry)
end
-- Wikicode for a list entry: Pokémon mini sprite, name, types and abilities.
Entry.__tostring = function(this)
local typesCount = this.type1 == this.type2 and 1 or 2
return string.interp([=[| ${static}
| class="hidden-xs" | ${name}${form}
| class="hidden-xs" style="padding: 1ex 0.8ex; font-size: 90%;" | ${type1}${type2}
| ${abil1}${abilEv}
| ${abil2}
| ${abild}]=],
{
static = ms.staticLua(string.tf(this.ndex or 0) ..
(this.formAbbr == 'base' and '' or this.formAbbr or '')),
name = this.name,
form = this.formsData
and this.formsData.blacklinks[this.formAbbr]
or '',
type1 = Entry.printTypeBox(this.type1, typesCount),
type2 = typesCount == 1 and ''
or Entry.printTypeBox(this.type2, typesCount),
abil1 = Entry.printAbil(this.ability1),
abilEv = Entry.printAbil(this.abilitye, true),
abil2 = Entry.printAbil(this.ability2),
abild = Entry.printAbil(this.abilityd),
})
end
-- Wikicode for list header: it takes the type name, for colors
local makeHeader = function(type)
return string.interp([=[{| class="roundy text-center pull-center white-rows" style="border-spacing: 0; padding: 0.3ex; ${bg};"
|-
! style="padding-top: 0.5ex; padding-bottom: 0.5ex;" | [[Elenco Pokémon secondo il Pokédex Nazionale|<span style="color:#000;">#</span>]]
! class="hidden-xs" | Pokémon
! class="hidden-xs" | [[Tipo|<span style="color:#000;">Tipi</span>]]
! Prima abilità
! Seconda abilità
! Abilità nascosta]=],
{
bg = css.horizGradLua{type = type}
})
end
--[[
Funzione d'interfaccia: si passano il tipo per il colore
e il titolo della pagina, da cui si ricava quello
dell'abilità.
--]]
k.abillist = function(frame)
local type = string.trim(frame.args[1]) or 'pcwiki'
local abil = string.trim(mw.text.decode(frame.args[2]))
abil = abil:match('^(.+) %(abilità%)') or 'Cacofonia'
return list.makeList({
source = require('PokéAbil-data'),
iterator = list.pokeNames,
entryArgs = abil,
makeEntry = Entry.new,
header = makeHeader(type),
footer = [[| class="text-left font-small" colspan="6" style="background: transparent; padding: 0.3ex 0.3em;" |
* Le abilità in ''corsivo'' sono ottenibili solo in determinate circostanze.
|}]]
})
end
k.Abillist = k.abillist
return k
|
--[[
This module prints the list of all Pokémon, alternative forms included, having
a given ability.
--]]
local k = {}
local mw = require('mw')
local abillib = require('Wikilib-abils')
local box = require('Box')
local css = require('Css')
local links = require('Links')
local list = require('Wikilib-lists')
local ms = require('MiniSprite')
local oop = require('Wikilib-oop')
local tab = require('Wikilib-tables') -- luacheck: no unused
local txt = require('Wikilib-strings') -- luacheck: no unused
local pokes = require('Poké-data')
--[[
Class representing a list entry. Fulfills requirements of makeList, sortNdex
and sortForms of Wikilib/lists
--]]
local Entry = oop.makeClass(list.PokeSortableEntry)
Entry.printTypeBox = function(type, typesCount)
return box.boxTipoLua(
string.fu(type),
'text-center roundy-5',
string.interp('padding: 0 0.5ex; margin-bottom: 0.2ex; height: ${width}%;',
{width = 100 / typesCount})
)
end
--[[
Printing ability is a complex job: event have to be handled, as well as
generation changes. The first argumetn is the ability to be printed, the second
one whether it should be marked or not, to be used for events.
--]]
Entry.printAbil = function(abil, marked)
if not abil then
return marked and '' or 'Nessuna'
end
-- Marked abilities are italic
local toHTML
if marked then
toHTML = function(ability)
return string.interp([=[<div>''${abil}''</div>]=],
{
abil = links.aColor(ability, '000'),
})
end
else
toHTML = links.aColor
end
if type(abil) == 'string' then
return toHTML(abil, '000')
end
-- Adding generations superscripts
return table.concat(table.map(abillib.abilspan(abil), function(v)
return string.interp(
'<div>${abil}<sup>${gen}</sup></div>',
{
abil = v.abil == 'Nessuna' and v.abil
or toHTML(v.abil, '000'),
gen = v.first == v.last and v.first
or table.concat{v.first, '-', v.last}
})
end))
end
--[[
Constructor: the first argument is an entry from Poké/data, the second one its
key and the third is the ability the Pokémon must have. As specified by
makeList in Wikilib/lists, returns nil whenever the Pokémon can not have the
ability.
--]]
Entry.new = function(pokeAbil, name, abil)
if not table.deepSearch(pokeAbil, abil) then
return nil
end
local this = Entry.super.new(name, pokes[name].ndex)
this = table.merge(this, pokeAbil)
return setmetatable(table.merge(this, pokes[name]), Entry)
end
-- Wikicode for a list entry: Pokémon mini sprite, name, types and abilities.
Entry.__tostring = function(this)
local typesCount = this.type1 == this.type2 and 1 or 2
return string.interp([=[| ${static}
| class="hidden-xs" | ${name}${form}
| class="hidden-xs" style="padding: 1ex 0.8ex; font-size: 90%;" | ${type1}${type2}
| ${abil1}${abilEv}
| ${abil2}
| ${abild}]=],
{
static = ms.staticLua(string.tf(this.ndex or 0) ..
(this.formAbbr == 'base' and '' or this.formAbbr or '')),
name = this.name,
form = this.formsData
and this.formsData.blacklinks[this.formAbbr]
or '',
type1 = Entry.printTypeBox(this.type1, typesCount),
type2 = typesCount == 1 and ''
or Entry.printTypeBox(this.type2, typesCount),
abil1 = Entry.printAbil(this.ability1),
abilEv = Entry.printAbil(this.abilitye, true),
abil2 = Entry.printAbil(this.ability2),
abild = Entry.printAbil(this.abilityd),
})
end
-- Wikicode for list header: it takes the type name, for colors
local makeHeader = function(type)
return string.interp([=[{| class="roundy text-center pull-center white-rows" style="border-spacing: 0; padding: 0.3ex; ${bg};"
|-
! style="padding-top: 0.5ex; padding-bottom: 0.5ex;" | [[Elenco Pokémon secondo il Pokédex Nazionale|<span style="color:#000;">#</span>]]
! class="hidden-xs" | Pokémon
! class="hidden-xs" | [[Tipo|<span style="color:#000;">Tipi</span>]]
! Prima abilità
! Seconda abilità
! Abilità nascosta]=],
{
bg = css.horizGradLua{type = type}
})
end
--[[
Funzione d'interfaccia: si passano il tipo per il colore
e il titolo della pagina, da cui si ricava quello
dell'abilità.
--]]
k.abillist = function(frame)
local type = string.trim(frame.args[1]) or 'pcwiki'
local abil = string.trim(mw.text.decode(frame.args[2]))
abil = abil:match('^(.+) %(abilità%)') or 'Cacofonia'
return list.makeList({
source = require('PokéAbil-data'),
iterator = list.pokeNames,
entryArgs = abil,
makeEntry = Entry.new,
header = makeHeader(type),
footer = [[| class="text-left font-small" colspan="6" style="background: transparent; padding: 0.3ex 0.3em;" |
* Le abilità in ''corsivo'' sono ottenibili solo in determinate circostanze.
|}]]
})
end
k.Abillist = k.abillist
return k
|
Just removing an import, but the last burst of commit fixed pokemoncentral/wiki-project#15
|
Just removing an import, but the last burst of commit fixed pokemoncentral/wiki-project#15
|
Lua
|
cc0-1.0
|
pokemoncentral/wiki-lua-modules
|
6428e5664ef717099417c71f2f9e6c23719f875a
|
src/lua/Parallel.lua
|
src/lua/Parallel.lua
|
local zmq = require "lzmq"
local zloop = require "lzmq.loop"
local zthreads = require "lzmq.threads"
local mp = require "cmsgpack"
local zassert = zmq.assert
local ENDPOINT = "inproc://main"
local THREAD_STARTER = [[
local ENDPOINT = ]] .. ("%q"):format(ENDPOINT) .. [[
local zmq = require "lzmq"
local zthreads = require "lzmq.threads"
local mp = require "cmsgpack"
local zassert = zmq.assert
function FOR(do_work)
local ctx = zthreads.get_parent_ctx()
local s, err = ctx:socket{zmq.DEALER, connect = ENDPOINT}
if not s then return end
s:sendx(0, 'READY')
while not s:closed() do
local tid, cmd, args = s:recvx()
if not tid then
if cmd and (cmd:no() == zmq.errors.ETERM) then break end
zassert(nil, cmd)
end
assert(tid and cmd)
if cmd == 'END' then break end
assert(cmd == 'TASK', "invalid command " .. tostring(cmd))
assert(args, "invalid args in command")
local res, err = mp.pack( do_work(mp.unpack(args)) )
s:sendx(tid, 'RESP', res)
end
ctx:destroy()
end
]]
local function pcall_ret_pack(ok, ...)
if ok then return mp.pack(ok, ...) end
return nil, ...
end
local function pcall_ret(ok, ...)
if ok then return pcall_ret_pack(...) end
return nil, ...
end
local function ppcall(...)
return pcall_ret(pcall(...))
end
local function thread_alive(self)
local ok, err = self:join(0)
if ok then return false end
if err == 'timeout' then return true end
return nil, err
end
local function parallel_for_impl(code, src, snk, N, cache_size)
N = N or 4
zthreads.set_bootstrap_prelude(THREAD_STARTER)
local src_err, snk_err
local loop = zloop.new()
function loop:add_thread(code, ...)
return zthreads.run(self:context(), code, ... )
end
local cache = {} -- заранее рассчитанные данные для заданий
local threads = {} -- рабочие потоки
local MAX_CACHE = cache_size or N
local function call_src()
if src and not src_err then
local args, err = ppcall(src)
if args then return args end
if err then
src_err = err
return nil, err
end
src = nil
end
end
local function next_src()
local args = table.remove(cache, 1)
if args then return args end
return call_src()
end
local function cache_src()
if #cache >= MAX_CACHE then return end
for i = #cache, MAX_CACHE do
local args = call_src()
if args then cache[#cache + 1] = args else break end
end
end
local skt, err = loop:create_socket{zmq.ROUTER, bind = ENDPOINT}
zassert(skt, err)
loop:add_socket(skt, function(skt)
local identity, tid, cmd, args = skt:recvx()
zassert(tid, cmd)
if cmd ~= 'READY' then
assert(cmd == 'RESP')
if not snk_err then
if snk then
local ok, err = ppcall(snk, mp.unpack(args))
if not ok and err then snk_err = err end
end
else
skt:sendx(identity, tid, 'END')
return
end
end
if #cache == 0 then cache_src() end
local args, err = next_src()
if args ~= nil then
skt:sendx(identity, tid, 'TASK', args)
return
end
skt:sendx(identity, tid, 'END')
end)
-- watchdog
loop:add_interval(1000, function()
local alive = 0
for _, thread in ipairs(threads) do
if thread_alive(thread) then alive = alive + 1 end
end
if alive == 0 then loop:interrupt() end
end)
loop:add_interval(100, function(ev) cache_src() end)
for i = 1, N do
local thread = loop:add_thread(code, i)
thread:start(true, true)
threads[#threads + 1] = thread
end
loop:start()
loop:destroy()
for _, t in ipairs(threads) do t:join() end
if src_err or snk_err then
return nil, src_err or snk_err
end
return true
end
---
-- @tparam[number] be begin index
-- @tparam[number] en end index
-- @tparam[number?] step step
-- @tparam[string] code
-- @tparam[callable?] snk sink
-- @tparam[number?] N thread count
-- @tparam[number?] C cache size
local function For(be, en, step, code, snk, N, C)
if type(step) ~= 'number' then -- no step
step, code, snk, N, C = 1, step, code, snk, N
end
if type(snk) == 'number' then -- no sink
N, C = snk, N
end
assert(type(be) == "number")
assert(type(en) == "number")
assert(type(step) == "number")
assert(type(code) == "string")
local src = function()
if be > en then return end
local n = be
be = be + step
return n
end
return parallel_for_impl(code, src, snk, N, C)
end
---
-- @tparam[string] code
-- @tparam[callable?] snk sink
-- @tparam[number?] N thread count
-- @tparam[number?] C cache size
local function ForEach(it, code, snk, N, C)
local src = it
if type(it) == 'table' then
local k, v
src = function()
k, v = next(it, k)
return k, v
end
end
if type(snk) == 'number' then -- no sink
snk, N, C = nil, snk, N
end
assert(type(src) == "function")
assert(type(code) == "string")
return parallel_for_impl(code, src, snk, N, C)
end
local function Invoke(N, ...)
local code = string.dump(function() FOR(function(_,src)
if src:sub(1,1) == '@' then dofile(src:sub(2))
else assert((loadstring or load)(src))() end
end) end)
if type(N) == 'number' then
return ForEach({...}, code, N)
end
return ForEach({N, ...}, code)
end
local Parallel = {} do
Parallel.__index = Parallel
function Parallel:new(N)
local o = setmetatable({
thread_count = N or 4;
}, self)
o.cache_size = o.thread_count * 2
return o
end
function Parallel:For(be, en, step, code, snk)
return For(be, en, step, code, snk, self.thread_count, self.cache_size)
end
function Parallel:ForEach(src, code, snk)
return ForEach(src, code, snk, self.thread_count, self.cache_size)
end
function Parallel:Invoke(...)
return ForEach(self.thread_count, ...)
end
end
return {
For = For;
ForEach = ForEach;
Invoke = Invoke;
New = function(...) return Parallel:new(...) end
}
|
local zmq = require "lzmq"
local zloop = require "lzmq.loop"
local zthreads = require "lzmq.threads"
local mp = require "cmsgpack"
local zassert = zmq.assert
local ENDPOINT = "inproc://main"
local THREAD_STARTER = [[
local ENDPOINT = ]] .. ("%q"):format(ENDPOINT) .. [[
local zmq = require "lzmq"
local zthreads = require "lzmq.threads"
local mp = require "cmsgpack"
local zassert = zmq.assert
function FOR(do_work)
local ctx = zthreads.get_parent_ctx()
local s, err = ctx:socket{zmq.DEALER, connect = ENDPOINT}
if not s then return end
s:sendx(0, 'READY')
while not s:closed() do
local tid, cmd, args = s:recvx()
if not tid then
if cmd and (cmd:no() == zmq.errors.ETERM) then break end
zassert(nil, cmd)
end
assert(tid and cmd)
if cmd == 'END' then break end
assert(cmd == 'TASK', "invalid command " .. tostring(cmd))
assert(args, "invalid args in command")
local res, err = mp.pack( do_work(mp.unpack(args)) )
s:sendx(tid, 'RESP', res)
end
ctx:destroy()
end
]]
local function pcall_ret_pack(ok, ...)
if ok then return mp.pack(ok, ...) end
return nil, ...
end
local function pcall_ret(ok, ...)
if ok then return pcall_ret_pack(...) end
return nil, ...
end
local function ppcall(...)
return pcall_ret(pcall(...))
end
local function thread_alive(self)
local ok, err = self:join(0)
if ok then return false end
if err == 'timeout' then return true end
return nil, err
end
local function parallel_for_impl(code, src, snk, N, cache_size)
N = N or 4
-- @fixme do not change global state in zthreads library
zthreads.set_bootstrap_prelude(THREAD_STARTER)
local src_err, snk_err
local cache = {} -- заранее рассчитанные данные для заданий
local threads = {} -- рабочие потоки
local MAX_CACHE = cache_size or N
local function call_src()
if src and not src_err then
local args, err = ppcall(src)
if args then return args end
if err then
src_err = err
return nil, err
end
src = nil
end
end
local function next_src()
local args = table.remove(cache, 1)
if args then return args end
return call_src()
end
local function cache_src()
if #cache >= MAX_CACHE then return end
for i = #cache, MAX_CACHE do
local args = call_src()
if args then cache[#cache + 1] = args else break end
end
end
local loop = zloop.new()
local skt, err = loop:create_socket{zmq.ROUTER, bind = ENDPOINT}
zassert(skt, err)
loop:add_socket(skt, function(skt)
local identity, tid, cmd, args = skt:recvx()
zassert(tid, cmd)
if cmd ~= 'READY' then
assert(cmd == 'RESP')
if not snk_err then
if snk then
local ok, err = ppcall(snk, mp.unpack(args))
if not ok and err then snk_err = err end
end
else
skt:sendx(identity, tid, 'END')
return
end
end
if #cache == 0 then cache_src() end
local args, err = next_src()
if args ~= nil then
skt:sendx(identity, tid, 'TASK', args)
return
end
skt:sendx(identity, tid, 'END')
end)
-- watchdog
loop:add_interval(1000, function()
local alive = 0
for _, thread in ipairs(threads) do
if thread_alive(thread) then alive = alive + 1 end
end
if alive == 0 then loop:interrupt() end
end)
loop:add_interval(100, function(ev) cache_src() end)
local err
for i = 1, N do
local thread
thread, err = zthreads.run(loop:context(), code, i)
if thread and thread:start(true, true) then
threads[#threads + 1] = thread
end
end
if #threads == 0 then return nil, err end
loop:start()
loop:destroy()
for _, t in ipairs(threads) do t:join() end
if src_err or snk_err then
return nil, src_err or snk_err
end
return true
end
---
-- @tparam[number] be begin index
-- @tparam[number] en end index
-- @tparam[number?] step step
-- @tparam[string] code
-- @tparam[callable?] snk sink
-- @tparam[number?] N thread count
-- @tparam[number?] C cache size
local function For(be, en, step, code, snk, N, C)
if type(step) ~= 'number' then -- no step
step, code, snk, N, C = 1, step, code, snk, N
end
if type(snk) == 'number' then -- no sink
N, C = snk, N
end
assert(type(be) == "number")
assert(type(en) == "number")
assert(type(step) == "number")
assert(type(code) == "string")
local src = function()
if be > en then return end
local n = be
be = be + step
return n
end
return parallel_for_impl(code, src, snk, N, C)
end
---
-- @tparam[string] code
-- @tparam[callable?] snk sink
-- @tparam[number?] N thread count
-- @tparam[number?] C cache size
local function ForEach(it, code, snk, N, C)
local src = it
if type(it) == 'table' then
local k, v
src = function()
k, v = next(it, k)
return k, v
end
end
if type(snk) == 'number' then -- no sink
snk, N, C = nil, snk, N
end
assert(type(src) == "function")
assert(type(code) == "string")
return parallel_for_impl(code, src, snk, N, C)
end
local function Invoke(N, ...)
local code = string.dump(function() FOR(function(_,src)
if src:sub(1,1) == '@' then dofile(src:sub(2))
else assert((loadstring or load)(src))() end
end) end)
if type(N) == 'number' then
return ForEach({...}, code, N)
end
return ForEach({N, ...}, code)
end
local Parallel = {} do
Parallel.__index = Parallel
function Parallel:new(N)
local o = setmetatable({
thread_count = N or 4;
}, self)
o.cache_size = o.thread_count * 2
return o
end
function Parallel:For(be, en, step, code, snk)
return For(be, en, step, code, snk, self.thread_count, self.cache_size)
end
function Parallel:ForEach(src, code, snk)
return ForEach(src, code, snk, self.thread_count, self.cache_size)
end
function Parallel:Invoke(...)
return ForEach(self.thread_count, ...)
end
end
return {
For = For;
ForEach = ForEach;
Invoke = Invoke;
New = function(...) return Parallel:new(...) end
}
|
Fix. check creation work thread.
|
Fix. check creation work thread.
|
Lua
|
mit
|
moteus/lua-Parallel,kidaa/lua-Parallel
|
099e5bd55a17f67e0510784a726abce8ce5c5e33
|
protocols/6x4/luasrc/model/cbi/admin_network/proto_6to4.lua
|
protocols/6x4/luasrc/model/cbi/admin_network/proto_6to4.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2011 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local ipaddr, adv_interface, adv_subnet
local adv_valid_lifetime, adv_preferred_lifetime, defaultroute, metric, ttl, mtu
ipaddr = section:taboption("general", Value, "ipaddr",
translate("Local IPv4 address"),
translate("Leave empty to use the current WAN address"))
ipaddr.datatype = "ip4addr"
adv_interface = section:taboption("general", Value, "adv_interface", translate("Advertise IPv6 on network"))
adv_interface.widget = "checkbox"
adv_interface.exclude = arg[1]
adv_interface.default = "lan"
adv_interface.template = "cbi/network_netlist"
adv_interface.nocreate = true
adv_interface.nobridges = true
adv_interface.novirtual = true
function adv_interface.remove(self, section)
self:write(section, " ")
end
adv_subnet = section:taboption("general", Value, "adv_subnet",
translate("Advertised network ID"),
translate("Allowed range is 1 to 65535"))
adv_subnet.placeholder = "1"
adv_subnet.datatype = "range(1,65535)"
function adv_subnet.cfgvalue(self, section)
local v = Value.cfgvalue(self, section)
return v and tonumber(v, 16)
end
function adv_subnet .write(self, section, value)
value = tonumber(value) or 1
if value > 65535 then value = 65535
elseif value < 1 then value = 1 end
Value.write(self, section, "%X" % value)
end
adv_valid_lifetime = section:taboption("advanced", Value, "adv_valid_lifetime",
translate("Use valid lifetime"),
translate("Specifies the advertised valid prefix lifetime in seconds"))
adv_valid_lifetime.placeholder = "300"
adv_valid_lifetime.datatype = "uinteger"
adv_preferred_lifetime = section:taboption("advanced", Value, "adv_preferred_lifetime",
translate("Use preferred lifetime"),
translate("Specifies the advertised preferred prefix lifetime in seconds"))
adv_preferred_lifetime.placeholder = "120"
adv_preferred_lifetime.datatype = "uinteger"
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface"))
ttl.placeholder = "64"
ttl.datatype = "range(1,255)"
mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface"))
mtu.placeholder = "1280"
mtu.datatype = "max(1500)"
|
--[[
LuCI - Lua Configuration Interface
Copyright 2011 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local ipaddr, adv_interface, adv_subnet
local adv_valid_lifetime, adv_preferred_lifetime, defaultroute, metric, ttl, mtu
ipaddr = section:taboption("general", Value, "ipaddr",
translate("Local IPv4 address"),
translate("Leave empty to use the current WAN address"))
ipaddr.datatype = "ip4addr"
adv_interface = section:taboption("general", Value, "adv_interface", translate("Advertise IPv6 on network"))
adv_interface.widget = "checkbox"
adv_interface.exclude = arg[1]
adv_interface.default = "lan"
adv_interface.template = "cbi/network_netlist"
adv_interface.nocreate = true
adv_interface.nobridges = true
adv_interface.novirtual = true
function adv_interface.write(self, section, value)
if type(value) == "table" then
Value.write(self, section, table.concat(value, " "))
else
Value.write(self, section, value)
end
end
function adv_interface.remove(self, section)
self:write(section, " ")
end
adv_subnet = section:taboption("general", Value, "adv_subnet",
translate("Advertised network ID"),
translate("Allowed range is 1 to 65535"))
adv_subnet.placeholder = "1"
adv_subnet.datatype = "range(1,65535)"
function adv_subnet.cfgvalue(self, section)
local v = Value.cfgvalue(self, section)
return v and tonumber(v, 16)
end
function adv_subnet .write(self, section, value)
value = tonumber(value) or 1
if value > 65535 then value = 65535
elseif value < 1 then value = 1 end
Value.write(self, section, "%X" % value)
end
adv_valid_lifetime = section:taboption("advanced", Value, "adv_valid_lifetime",
translate("Use valid lifetime"),
translate("Specifies the advertised valid prefix lifetime in seconds"))
adv_valid_lifetime.placeholder = "300"
adv_valid_lifetime.datatype = "uinteger"
adv_preferred_lifetime = section:taboption("advanced", Value, "adv_preferred_lifetime",
translate("Use preferred lifetime"),
translate("Specifies the advertised preferred prefix lifetime in seconds"))
adv_preferred_lifetime.placeholder = "120"
adv_preferred_lifetime.datatype = "uinteger"
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface"))
ttl.placeholder = "64"
ttl.datatype = "range(1,255)"
mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface"))
mtu.placeholder = "1280"
mtu.datatype = "max(1500)"
|
proto/6x4: cast 6to4 adv_interface to string when saving to uci, fixes 6in4.sh not picking up the adv interfaces
|
proto/6x4: cast 6to4 adv_interface to string when saving to uci, fixes 6in4.sh not picking up the adv interfaces
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@9009 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
ch3n2k/luci,Canaan-Creative/luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,8devices/carambola2-luci,eugenesan/openwrt-luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,phi-psi/luci,vhpham80/luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,gwlim/luci,phi-psi/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,vhpham80/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,phi-psi/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,phi-psi/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,yeewang/openwrt-luci,ch3n2k/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,vhpham80/luci,gwlim/luci,Canaan-Creative/luci,gwlim/luci,phi-psi/luci,8devices/carambola2-luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,8devices/carambola2-luci,8devices/carambola2-luci,phi-psi/luci,ch3n2k/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,freifunk-gluon/luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,phi-psi/luci,vhpham80/luci,gwlim/luci,8devices/carambola2-luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,Canaan-Creative/luci,gwlim/luci,8devices/carambola2-luci,freifunk-gluon/luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,Canaan-Creative/luci,gwlim/luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci
|
89fe3e305129e537088fe9ec6e6970c85265d72e
|
spec/unit/defaults_spec.lua
|
spec/unit/defaults_spec.lua
|
describe("defaults module", function()
local Defaults, DataStorage
setup(function()
require("commonrequire")
Defaults = require("apps/filemanager/filemanagersetdefaults")
DataStorage = require("datastorage")
end)
it("should load all defaults from defaults.lua", function()
Defaults:init()
assert.is_same(#Defaults.defaults_name, 77)
assert.is_same(Defaults.defaults_name[28], 'DHINTCOUNT')
end)
it("should save changes to defaults.persistent.lua", function()
local persistent_filename = DataStorage:getDataDir() .. "/defaults.persistent.lua"
os.remove(persistent_filename)
-- not in persistent but checked in defaults
Defaults.changed[11] = true
Defaults.changed[19] = true
Defaults.changed[28] = true
Defaults.changed[63] = true
Defaults.changed[77] = true
Defaults:saveSettings()
assert.is_same(#Defaults.defaults_name, 77)
assert.is_same(Defaults.defaults_name[28], 'DHINTCOUNT')
assert.is_same(Defaults.defaults_name[77], 'SEARCH_TITLE')
assert.is_same(Defaults.defaults_name[63], 'DTAP_ZONE_MENU')
assert.is_same(Defaults.defaults_name[19], 'DCREREADER_VIEW_MODE')
assert.is_same(Defaults.defaults_name[11],
'DCREREADER_CONFIG_MARGIN_SIZES_LARGE')
local fd = io.open(persistent_filename, "r")
assert.Equals(
[[-- For configuration changes that persists between updates
SEARCH_TITLE = true
DCREREADER_CONFIG_MARGIN_SIZES_LARGE = {
[1] = 20,
[2] = 20,
[3] = 20,
[4] = 20
}
DCREREADER_VIEW_MODE = "page"
DHINTCOUNT = 1
DTAP_ZONE_MENU = {
["y"] = 0,
["x"] = 0.125,
["h"] = 0.125,
["w"] = 0.75
}
]],
fd:read("*a"))
fd:close()
-- in persistent
Defaults:init()
Defaults.changed[28] = true
Defaults.defaults_value[28] = 2
Defaults.changed[63] = true
Defaults.defaults_value[63] = {
y = 10,
x = 10.125,
h = 20.25,
w = 20.75
}
Defaults:saveSettings()
fd = io.open(persistent_filename)
assert.Equals(
[[-- For configuration changes that persists between updates
SEARCH_TITLE = true
DHINTCOUNT = 2
DTAP_ZONE_MENU = {
["y"] = 10,
["x"] = 10.125,
["h"] = 20.25,
["w"] = 20.75
}
DCREREADER_CONFIG_MARGIN_SIZES_LARGE = {
[1] = 20,
[2] = 20,
[3] = 20,
[4] = 20
}
DCREREADER_VIEW_MODE = "page"
]],
fd:read("*a"))
fd:close()
os.remove(persistent_filename)
end)
it("should delete entry from defaults.persistent.lua if value is reverted back to default", function()
local persistent_filename = DataStorage:getDataDir() .. "/defaults.persistent.lua"
local fd = io.open(persistent_filename, "w")
fd:write(
[[-- For configuration changes that persists between updates
SEARCH_TITLE = true
DCREREADER_CONFIG_MARGIN_SIZES_LARGE = {
[1] = 20,
[2] = 20,
[3] = 20,
[4] = 20
}
DCREREADER_VIEW_MODE = "page"
DHINTCOUNT = 2
]])
fd:close()
-- in persistent
Defaults:init()
Defaults.changed[28] = true
Defaults.defaults_value[28] = 1
Defaults:saveSettings()
fd = io.open(persistent_filename)
assert.Equals(
[[-- For configuration changes that persists between updates
SEARCH_TITLE = true
DCREREADER_VIEW_MODE = "page"
DCREREADER_CONFIG_MARGIN_SIZES_LARGE = {
[1] = 20,
[2] = 20,
[3] = 20,
[4] = 20
}
]],
fd:read("*a"))
fd:close()
os.remove(persistent_filename)
end)
end)
|
describe("defaults module", function()
local Defaults, DataStorage
setup(function()
require("commonrequire")
Defaults = require("apps/filemanager/filemanagersetdefaults")
DataStorage = require("datastorage")
end)
it("should load all defaults from defaults.lua", function()
Defaults:init()
assert.is_same(82, #Defaults.defaults_name)
assert.is_same("DFULL_SCREEN", Defaults.defaults_name[28])
end)
it("should save changes to defaults.persistent.lua", function()
local persistent_filename = DataStorage:getDataDir() .. "/defaults.persistent.lua"
os.remove(persistent_filename)
-- not in persistent but checked in defaults
Defaults.changed[11] = true
Defaults.changed[19] = true
Defaults.changed[28] = true
Defaults.changed[63] = true
Defaults.changed[77] = true
Defaults:saveSettings()
assert.is_same(82, #Defaults.defaults_name)
assert.is_same("DFULL_SCREEN", Defaults.defaults_name[28])
assert.is_same("SEARCH_LIBRARY_PATH", Defaults.defaults_name[77])
assert.is_same("DTAP_ZONE_BACKWARD", Defaults.defaults_name[63])
assert.is_same("DCREREADER_CONFIG_WORD_GAP_LARGE", Defaults.defaults_name[19])
assert.is_same("DCREREADER_CONFIG_MARGIN_SIZES_HUGE", Defaults.defaults_name[11])
local fd = io.open(persistent_filename, "r")
assert.Equals(
[[-- For configuration changes that persists between updates
SEARCH_LIBRARY_PATH = ""
DTAP_ZONE_BACKWARD = {
["y"] = 0,
["x"] = 0,
["h"] = 1,
["w"] = 0.25
}
DCREREADER_CONFIG_WORD_GAP_LARGE = 100
DFULL_SCREEN = 1
DCREREADER_CONFIG_MARGIN_SIZES_HUGE = {
[1] = 100,
[2] = 100,
[3] = 100,
[4] = 100
}
]],
fd:read("*a"))
fd:close()
-- in persistent
Defaults:init()
Defaults.changed[28] = true
Defaults.defaults_value[28] = 2
Defaults.changed[63] = true
Defaults.defaults_value[63] = {
y = 10,
x = 10.125,
h = 20.25,
w = 20.75
}
Defaults:saveSettings()
fd = io.open(persistent_filename)
assert.Equals(
[[-- For configuration changes that persists between updates
SEARCH_LIBRARY_PATH = ""
DTAP_ZONE_BACKWARD = {
["y"] = 10,
["x"] = 10.125,
["h"] = 20.25,
["w"] = 20.75
}
DCREREADER_CONFIG_WORD_GAP_LARGE = 100
DFULL_SCREEN = 2
DCREREADER_CONFIG_MARGIN_SIZES_HUGE = {
[1] = 100,
[2] = 100,
[3] = 100,
[4] = 100
}
]],
fd:read("*a"))
fd:close()
os.remove(persistent_filename)
end)
it("should delete entry from defaults.persistent.lua if value is reverted back to default", function()
local persistent_filename = DataStorage:getDataDir() .. "/defaults.persistent.lua"
local fd = io.open(persistent_filename, "w")
fd:write(
[[-- For configuration changes that persists between updates
SEARCH_TITLE = true
DCREREADER_CONFIG_MARGIN_SIZES_LARGE = {
[1] = 20,
[2] = 20,
[3] = 20,
[4] = 20
}
DCREREADER_VIEW_MODE = "page"
DHINTCOUNT = 2
]])
fd:close()
-- in persistent
Defaults:init()
Defaults.changed[28] = true
Defaults.defaults_value[28] = 1
Defaults:saveSettings()
fd = io.open(persistent_filename)
assert.Equals(
[[-- For configuration changes that persists between updates
SEARCH_TITLE = true
DHINTCOUNT = 2
DCREREADER_CONFIG_MARGIN_SIZES_LARGE = {
[1] = 20,
[2] = 20,
[3] = 20,
[4] = 20
}
DFULL_SCREEN = 1
DCREREADER_VIEW_MODE = "page"
]],
fd:read("*a"))
fd:close()
os.remove(persistent_filename)
end)
end)
|
[spec] Fix defaults_spec
|
[spec] Fix defaults_spec
Updated for https://github.com/koreader/koreader/pull/4691
Also the assert.is_same() argument order was wrong.
The first argument is expected, the second the real-life result.
Otherwise the error message in case of failure is misleading.
|
Lua
|
agpl-3.0
|
koreader/koreader,NiLuJe/koreader,NiLuJe/koreader,koreader/koreader,Frenzie/koreader,mihailim/koreader,Markismus/koreader,poire-z/koreader,poire-z/koreader,pazos/koreader,Hzj-jie/koreader,mwoz123/koreader,houqp/koreader,Frenzie/koreader
|
526140efdd531134e4c2010a4f2415e0e7d1924c
|
lualib/sys/socketdispatch.lua
|
lualib/sys/socketdispatch.lua
|
local socket = require "sys.socket"
local core = require "sys.core"
local pairs = pairs
local assert = assert
local tremove = table.remove
local CONNECTING = 1
local CONNECTED = 2
local CLOSE = 5
local FINAL = 6
local dispatch = {}
local mt = {
__index = dispatch,
__gc = function(tbl)
tbl:close()
end
}
--the function of process response insert into d.funcqueue
function dispatch:create(config)
local d = {
sock = false,
status = CLOSE,
responseco = false,
dispatchco = false,
connectqueue = {},
waitqueue = {},
funcqueue = {}, --process response, return
result_data = {},
--come from config
addr = config.addr,
auth = config.auth,
}
setmetatable(d, mt)
return d
end
local function wakeup_all(self, ret, err)
local waitqueue = self.waitqueue
local funcqueue = self.funcqueue
local result_data = self.result_data
local co = tremove(waitqueue, 1)
tremove(funcqueue, 1)
while co do
result_data[co] = err
core.wakeup(co, ret)
co = tremove(waitqueue, 1)
tremove(funcqueue, 1)
end
end
local function doclose(self)
if (self.status == CLOSE) then
return
end
assert(self.sock >= 0)
socket.close(self.sock)
self.sock = false
self.status = CLOSE;
local co = self.responseco
if co then
self.responseco = nil
core.wakeup(co)
end
end
--this function will be run the indepedent coroutine
local function dispatch_response(self)
return function ()
local pcall = core.pcall
local waitqueue = self.waitqueue
local funcqueue = self.funcqueue
local result_data = self.result_data
while self.sock do
local co = tremove(waitqueue, 1)
local func = tremove(funcqueue, 1)
if func and co then
local ok, status, data = pcall(func, self)
if ok then
result_data[co] = data
core.wakeup(co, status)
else
result_data[co] = status
core.wakeup(co, false)
doclose(self)
break
end
else
local co = core.running()
self.responseco = co
core.wait(co)
end
end
self.dispatchco = false
wakeup_all(self, false, "disconnected")
end
end
local function waitfor_response(self, response)
local co = core.running()
local waitqueue = self.waitqueue
local funcqueue = self.funcqueue
waitqueue[#waitqueue + 1] = co
funcqueue[#funcqueue + 1] = response
if self.responseco then --the first request
local co = self.responseco
self.responseco = nil
core.wakeup(co)
end
local status = core.wait(co)
local result_data = self.result_data
local data = result_data[co]
result_data[co] = nil
return status, data
end
local function waitfor_connect(self)
local co = core.running()
local connectqueue = self.connectqueue
connectqueue[#connectqueue + 1] = co
local status = core.wait(co)
local result_data = self.result_data
local data = result_data[co]
result_data[co] = nil
return status, data
end
local function wakeup_conn(self, success, err)
local result_data = self.result_data
local connectqueue = self.connectqueue
for k, v in pairs(connectqueue) do
result_data[v] = err
core.wakeup(v, success)
connectqueue[k] = nil
end
end
local function tryconnect(self)
local status = self.status
if status == CONNECTED then
return true;
end
if status == FINAL then
return false, "already closed"
end
local res
if status == CLOSE then
local err, sock
self.status = CONNECTING;
sock = socket.connect(self.addr)
if not sock then
res = false
self.status = CLOSE
err = "socketdispatch connect fail"
else
res = true
self.status = CONNECTED;
end
if res then
--wait for responseco exit
while self.dispatchco do
core.sleep(0)
end
self.sock = sock
local auth = self.auth
self.dispatchco = core.fork(dispatch_response(self))
if auth then
local ok, msg
ok, res, msg = core.pcall(auth, self)
if not ok then
res = false
err = res
doclose(self)
elseif not res then
err = msg
doclose(self)
end
end
assert(#self.funcqueue == 0)
assert(#self.waitqueue == 0)
end
wakeup_conn(self, res, err)
return res, err
elseif status == CONNECTING then
return waitfor_connect(self)
else
core.error("[socketdispatch] incorrect call at status:" .. self.status)
end
end
function dispatch:connect()
return tryconnect(self)
end
function dispatch:close()
if self.status == FINAL then
return
end
doclose(self)
self.status = FINAL
return
end
-- the respose function will be called in the socketfifo coroutine
function dispatch:request(cmd, response)
local ok, err = tryconnect(self)
if not ok then
return ok, err
end
local ok = socket.write(self.sock, cmd)
if not ok then
doclose(self)
return nil
end
if not response then
return
end
return waitfor_response(self, response)
end
local function read_write_wrapper(func)
return function (self, p)
return func(self.sock, p)
end
end
dispatch.read = read_write_wrapper(socket.read)
dispatch.write = read_write_wrapper(socket.write)
dispatch.readline = read_write_wrapper(socket.readline)
return dispatch
|
local socket = require "sys.socket"
local core = require "sys.core"
local pairs = pairs
local assert = assert
local tremove = table.remove
local CONNECTING = 1
local CONNECTED = 2
local CLOSE = 5
local FINAL = 6
local dispatch = {}
local mt = {
__index = dispatch,
__gc = function(tbl)
if tbl.sock then
socket.close(tbl.sock)
end
end
}
--the function of process response insert into d.funcqueue
function dispatch:create(config)
local d = {
sock = nil,
status = CLOSE,
authco = nil,
responseco = false,
dispatchco = false,
connectqueue = {},
waitqueue = {},
funcqueue = {}, --process response, return
result_data = {},
--come from config
addr = config.addr,
auth = config.auth,
}
setmetatable(d, mt)
return d
end
local function wakeup_all(self, ret, err)
local waitqueue = self.waitqueue
local funcqueue = self.funcqueue
local result_data = self.result_data
local co = tremove(waitqueue, 1)
tremove(funcqueue, 1)
while co do
result_data[co] = err
core.wakeup(co, ret)
co = tremove(waitqueue, 1)
tremove(funcqueue, 1)
end
end
local function doclose(self)
if self.status == CLOSE then
return
end
assert(self.sock)
socket.close(self.sock)
self.sock = nil
self.status = CLOSE;
local co = self.responseco
if co then
self.responseco = nil
core.wakeup(co)
end
end
--this function will be run the indepedent coroutine
local function dispatch_response(self)
return function ()
local pcall = core.pcall
local waitqueue = self.waitqueue
local funcqueue = self.funcqueue
local result_data = self.result_data
while self.sock do
local co = tremove(waitqueue, 1)
local func = tremove(funcqueue, 1)
if func and co then
local ok, status, data = pcall(func, self)
if ok then
result_data[co] = data
core.wakeup(co, status)
else
result_data[co] = status
core.wakeup(co, false)
doclose(self)
break
end
else
local co = core.running()
self.responseco = co
core.wait(co)
end
end
self.dispatchco = false
wakeup_all(self, false, "disconnected")
end
end
local function waitfor_response(self, response)
local co = core.running()
local waitqueue = self.waitqueue
local funcqueue = self.funcqueue
waitqueue[#waitqueue + 1] = co
funcqueue[#funcqueue + 1] = response
if self.responseco then --the first request
local co = self.responseco
self.responseco = nil
core.wakeup(co)
end
local status = core.wait(co)
local result_data = self.result_data
local data = result_data[co]
result_data[co] = nil
return status, data
end
local function waitfor_connect(self)
local co = core.running()
local connectqueue = self.connectqueue
connectqueue[#connectqueue + 1] = co
local status = core.wait(co)
local result_data = self.result_data
local data = result_data[co]
result_data[co] = nil
return status, data
end
local function wakeup_conn(self, success, err)
local result_data = self.result_data
local connectqueue = self.connectqueue
for k, v in pairs(connectqueue) do
result_data[v] = err
core.wakeup(v, success)
connectqueue[k] = nil
end
end
local function tryconnect(self)
local status = self.status
if status == CONNECTED then
return true
end
if status == FINAL then
return false, "already closed"
end
if status == CLOSE then
local err, sock, res
self.status = CONNECTING;
sock = socket.connect(self.addr)
if sock then
self.sock = sock
--wait for responseco exit
while self.dispatchco do
core.sleep(0)
end
local auth = self.auth
self.dispatchco = core.fork(dispatch_response(self))
if auth then
local ok, msg
self.authco = core.running()
ok, res, msg = core.pcall(auth, self)
self.authco = nil
if not ok then
res = false
err = res
doclose(self)
elseif not res then
res = false
err = msg
doclose(self)
end
else
res = true
end
if res then
self.status = CONNECTED;
assert(#self.funcqueue == 0)
assert(#self.waitqueue == 0)
end
else
res = false
self.status = CLOSE
err = "socketdispatch connect fail"
end
wakeup_conn(self, res, err)
return res, err
elseif status == CONNECTING then
if self.authco == core.running() then
return true
end
return waitfor_connect(self)
else
core.error("[socketdispatch] incorrect call at status:" .. self.status)
end
end
function dispatch:connect()
return tryconnect(self)
end
function dispatch:close()
if self.status == FINAL then
return
end
doclose(self)
self.status = FINAL
return
end
-- the respose function will be called in the `dispatchco` coroutine
function dispatch:request(cmd, response)
local ok, err = tryconnect(self)
if not ok then
return ok, err
end
local ok = socket.write(self.sock, cmd)
if not ok then
doclose(self)
return nil
end
if not response then
return
end
return waitfor_response(self, response)
end
local function read_write_wrapper(func)
return function (self, p)
return func(self.sock, p)
end
end
dispatch.read = read_write_wrapper(socket.read)
dispatch.write = read_write_wrapper(socket.write)
dispatch.readline = read_write_wrapper(socket.readline)
return dispatch
|
fix socketdispatch auth race
|
fix socketdispatch auth race
|
Lua
|
mit
|
findstr/silly
|
c182b94bcab360f2e10d06de30e36223188cfe8e
|
src_trunk/resources/vehicle-system/c_vehicle_rightclick.lua
|
src_trunk/resources/vehicle-system/c_vehicle_rightclick.lua
|
wRightClick = nil
bInventory = nil
bCloseMenu = nil
ax, ay = nil
localPlayer = getLocalPlayer()
vehicle = nil
function requestInventory(button)
if button=="left" and not getElementData(localPlayer, "exclusiveGUI") then
if isVehicleLocked(vehicle) and vehicle ~= getPedOccupiedVehicle(localPlayer) then
triggerServerEvent("onVehicleRemoteAlarm", vehicle)
outputChatBox("This vehicle is locked.", 255, 0, 0)
else
triggerServerEvent( "openFreakinInventory", localPlayer, vehicle, ax, ay )
end
hideVehicleMenu()
end
end
function clickVehicle(button, state, absX, absY, wx, wy, wz, element)
if (element) and (getElementType(element)=="vehicle") and (button=="right") and (state=="down") and not (wInventory) then
local x, y, z = getElementPosition(localPlayer)
if (getDistanceBetweenPoints3D(x, y, z, wx, wy, wz)<=3) then
if (wRightClick) then
hideVehicleMenu()
end
showCursor(true)
ax = absX
ay = absY
vehicle = element
showVehicleMenu()
end
end
end
addEventHandler("onClientClick", getRootElement(), clickVehicle, true)
function showVehicleMenu()
wRightClick = guiCreateWindow(ax, ay, 150, 200, getVehicleName(vehicle), false)
lPlate = guiCreateLabel(0.05, 0.13, 0.87, 0.1, "Plate: " .. getVehiclePlateText(vehicle), true, wRightClick)
guiSetFont(lPlate, "default-bold-small")
lPlate = guiCreateLabel(0.05, 0.23, 0.87, 0.1, "Impounded: " .. (getElementData(vehicle, "Impounded") > 0 and "Yes" or "No"), true, wRightClick)
guiSetFont(lPlate, "default-bold-small")
bInventory = guiCreateButton(0.05, 0.33, 0.87, 0.1, "Inventory", true, wRightClick)
addEventHandler("onClientGUIClick", bInventory, requestInventory, false)
local y = 0.47
if getPedOccupiedVehicle(localPlayer) == vehicle or exports.global:hasItem(localPlayer, 3, getElementData(vehicle, "dbid")) or (getElementData(localPlayer, "faction") > 0 and getElementData(localPlayer, "faction") == getElementData(vehicle, "faction")) then
bLockUnlock = guiCreateButton(0.05, y, 0.87, 0.1, "Lock/Unlock", true, wRightClick)
addEventHandler("onClientGUIClick", bLockUnlock, lockUnlock, false)
y = y + 0.14
end
local vx,vy,vz = getElementVelocity(vehicle)
if vx < 0.05 and vy < 0.05 and vz < 0.05 and not getPedOccupiedVehicle(localPlayer) and not isVehicleLocked(vehicle) then -- completely stopped
if exports.global:hasItem(localPlayer, 57) then -- FUEL CAN
bFill = guiCreateButton(0.05, y, 0.87, 0.1, "Fill tank", true, wRightClick)
addEventHandler("onClientGUIClick", bFill, fillFuelTank, false)
y = y + 0.14
end
if getElementData(localPlayer, "job") == 5 then -- Mechanic
bFix = guiCreateButton(0.05, y, 0.87, 0.1, "Fix/Upgrade", true, wRightClick)
addEventHandler("onClientGUIClick", bFix, openMechanicWindow, false)
y = y + 0.14
end
end
if (getElementModel(vehicle)==497) then -- HELICOPTER
local players = getElementData(vehicle, "players")
local found = false
if (players) then
for key, value in ipairs(players) do
if (value==localPlayer) then
found = true
end
end
end
if not (found) then
bSit = guiCreateButton(0.05, y, 0.87, 0.1, "Sit", true, wRightClick)
addEventHandler("onClientGUIClick", bSit, sitInHelicopter, false)
else
bSit = guiCreateButton(0.05, y, 0.87, 0.1, "Stand up", true, wRightClick)
addEventHandler("onClientGUIClick", bSit, unsitInHelicopter, false)
end
y = y + 0.14
end
bCloseMenu = guiCreateButton(0.05, y, 0.87, 0.1, "Close Menu", true, wRightClick)
addEventHandler("onClientGUIClick", bCloseMenu, hideVehicleMenu, false)
end
function lockUnlock(button, state)
if (button=="left") then
if getPedOccupiedVehicle(localPlayer) == vehicle then
triggerServerEvent("lockUnlockInsideVehicle", localPlayer, vehicle)
else
triggerServerEvent("lockUnlockOutsideVehicle", localPlayer, vehicle)
end
hideVehicleMenu()
end
end
function fillFuelTank(button, state)
if (button=="left") then
local _,_, value = exports.global:hasItem(localPlayer, 57)
triggerServerEvent("fillFuelTankVehicle", localPlayer, vehicle, value)
hideVehicleMenu()
end
end
function openMechanicWindow(button, state)
if (button=="left") then
triggerEvent("openMechanicFixWindow", localPlayer, vehicle)
hideVehicleMenu()
end
end
function sitInHelicopter(button, state)
if (button=="left") then
triggerServerEvent("sitInHelicopter", localPlayer, vehicle)
hideVehicleMenu()
end
end
function unsitInHelicopter(button, state)
if (button=="left") then
triggerServerEvent("unsitInHelicopter", localPlayer, vehicle)
hideVehicleMenu()
end
end
function hideVehicleMenu()
if (isElement(bCloseMenu)) then
destroyElement(bCloseMenu)
end
bCloseMenu = nil
if (isElement(wRightClick)) then
destroyElement(wRightClick)
end
wRightClick = nil
ax = nil
ay = nil
vehicle = nil
showCursor(false)
triggerEvent("cursorHide", getLocalPlayer())
end
|
wRightClick = nil
bInventory = nil
bCloseMenu = nil
ax, ay = nil
localPlayer = getLocalPlayer()
vehicle = nil
function requestInventory(button)
if button=="left" and not getElementData(localPlayer, "exclusiveGUI") then
if isVehicleLocked(vehicle) and vehicle ~= getPedOccupiedVehicle(localPlayer) then
triggerServerEvent("onVehicleRemoteAlarm", vehicle)
outputChatBox("This vehicle is locked.", 255, 0, 0)
else
triggerServerEvent( "openFreakinInventory", localPlayer, vehicle, ax, ay )
end
hideVehicleMenu()
end
end
function clickVehicle(button, state, absX, absY, wx, wy, wz, element)
if (element) and (getElementType(element)=="vehicle") and (button=="right") and (state=="down") and not (wInventory) then
local x, y, z = getElementPosition(localPlayer)
if (getDistanceBetweenPoints3D(x, y, z, wx, wy, wz)<=3) then
if (wRightClick) then
hideVehicleMenu()
end
showCursor(true)
ax = absX
ay = absY
vehicle = element
showVehicleMenu()
end
end
end
addEventHandler("onClientClick", getRootElement(), clickVehicle, true)
function showVehicleMenu()
wRightClick = guiCreateWindow(ax, ay, 150, 200, getVehicleName(vehicle), false)
lPlate = guiCreateLabel(0.05, 0.13, 0.87, 0.1, "Plate: " .. getVehiclePlateText(vehicle), true, wRightClick)
guiSetFont(lPlate, "default-bold-small")
lPlate = guiCreateLabel(0.05, 0.23, 0.87, 0.1, "Impounded: " .. (type(getElementData(vehicle, "Impounded")) == "number" and getElementData(vehicle, "Impounded") > 0 and "Yes" or "No"), true, wRightClick)
guiSetFont(lPlate, "default-bold-small")
bInventory = guiCreateButton(0.05, 0.33, 0.87, 0.1, "Inventory", true, wRightClick)
addEventHandler("onClientGUIClick", bInventory, requestInventory, false)
local y = 0.47
if getPedOccupiedVehicle(localPlayer) == vehicle or exports.global:hasItem(localPlayer, 3, getElementData(vehicle, "dbid")) or (getElementData(localPlayer, "faction") > 0 and getElementData(localPlayer, "faction") == getElementData(vehicle, "faction")) then
bLockUnlock = guiCreateButton(0.05, y, 0.87, 0.1, "Lock/Unlock", true, wRightClick)
addEventHandler("onClientGUIClick", bLockUnlock, lockUnlock, false)
y = y + 0.14
end
local vx,vy,vz = getElementVelocity(vehicle)
if vx < 0.05 and vy < 0.05 and vz < 0.05 and not getPedOccupiedVehicle(localPlayer) and not isVehicleLocked(vehicle) then -- completely stopped
if exports.global:hasItem(localPlayer, 57) then -- FUEL CAN
bFill = guiCreateButton(0.05, y, 0.87, 0.1, "Fill tank", true, wRightClick)
addEventHandler("onClientGUIClick", bFill, fillFuelTank, false)
y = y + 0.14
end
if getElementData(localPlayer, "job") == 5 then -- Mechanic
bFix = guiCreateButton(0.05, y, 0.87, 0.1, "Fix/Upgrade", true, wRightClick)
addEventHandler("onClientGUIClick", bFix, openMechanicWindow, false)
y = y + 0.14
end
end
if (getElementModel(vehicle)==497) then -- HELICOPTER
local players = getElementData(vehicle, "players")
local found = false
if (players) then
for key, value in ipairs(players) do
if (value==localPlayer) then
found = true
end
end
end
if not (found) then
bSit = guiCreateButton(0.05, y, 0.87, 0.1, "Sit", true, wRightClick)
addEventHandler("onClientGUIClick", bSit, sitInHelicopter, false)
else
bSit = guiCreateButton(0.05, y, 0.87, 0.1, "Stand up", true, wRightClick)
addEventHandler("onClientGUIClick", bSit, unsitInHelicopter, false)
end
y = y + 0.14
end
bCloseMenu = guiCreateButton(0.05, y, 0.87, 0.1, "Close Menu", true, wRightClick)
addEventHandler("onClientGUIClick", bCloseMenu, hideVehicleMenu, false)
end
function lockUnlock(button, state)
if (button=="left") then
if getPedOccupiedVehicle(localPlayer) == vehicle then
triggerServerEvent("lockUnlockInsideVehicle", localPlayer, vehicle)
else
triggerServerEvent("lockUnlockOutsideVehicle", localPlayer, vehicle)
end
hideVehicleMenu()
end
end
function fillFuelTank(button, state)
if (button=="left") then
local _,_, value = exports.global:hasItem(localPlayer, 57)
triggerServerEvent("fillFuelTankVehicle", localPlayer, vehicle, value)
hideVehicleMenu()
end
end
function openMechanicWindow(button, state)
if (button=="left") then
triggerEvent("openMechanicFixWindow", localPlayer, vehicle)
hideVehicleMenu()
end
end
function sitInHelicopter(button, state)
if (button=="left") then
triggerServerEvent("sitInHelicopter", localPlayer, vehicle)
hideVehicleMenu()
end
end
function unsitInHelicopter(button, state)
if (button=="left") then
triggerServerEvent("unsitInHelicopter", localPlayer, vehicle)
hideVehicleMenu()
end
end
function hideVehicleMenu()
if (isElement(bCloseMenu)) then
destroyElement(bCloseMenu)
end
bCloseMenu = nil
if (isElement(wRightClick)) then
destroyElement(wRightClick)
end
wRightClick = nil
ax = nil
ay = nil
vehicle = nil
showCursor(false)
triggerEvent("cursorHide", getLocalPlayer())
end
|
fix for vehicle rightclick breaking with Impound again
|
fix for vehicle rightclick breaking with Impound again
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1559 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
85cba95646165e201ecb15a698b2dc6a3a12760a
|
contrib/package/ffluci-splash/src/luci-splash.lua
|
contrib/package/ffluci-splash/src/luci-splash.lua
|
#!/usr/bin/lua
package.path = "/usr/lib/lua/?.lua;/usr/lib/lua/?/init.lua;" .. package.path
package.cpath = "/usr/lib/lua/?.so;" .. package.cpath
require("ffluci.http")
require("ffluci.sys")
require("ffluci.model.uci")
-- Init state session
uci = ffluci.model.uci.StateSession()
function main(argv)
local cmd = argv[1]
local arg = argv[2]
if not cmd then
print("Usage: " .. argv[0] .. " <status|add|remove|sync> [MAC]")
os.exit(1)
elseif cmd == "status" then
if not arg then
os.exit(1)
end
if iswhitelisted(arg) then
print("whitelisted")
os.exit(0)
end
if haslease(arg) then
print("lease")
os.exit(0)
end
print("unknown")
os.exit(0)
elseif cmd == "add" then
if not arg then
os.exit(1)
end
if not haslease(arg) then
add_lease(arg)
else
print("already leased!")
os.exit(2)
end
os.exit(0)
elseif cmd == "remove" then
if not cmd[2] then
os.exit(1)
end
remove_lease(arg)
os.exit(0)
elseif cmd == "sync" then
sync()
os.exit(0)
end
end
-- Add a lease to state and invoke add_rule
function add_lease(mac)
local key = uci:add("luci_splash", "lease")
uci:set("luci_splash", key, "mac", mac)
uci:set("luci_splash", key, "start", os.time())
add_rule(mac)
end
-- Remove a lease from state and invoke remove_rule
function remove_lease(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v.mac:lower() == mac then
remove_rule(mac)
uci:del("luci_splash", k)
end
end
end
-- Add an iptables rule
function add_rule(mac)
return os.execute("iptables -t nat -I luci_splash_leases -m mac --mac-source '"..mac.."' -j RETURN")
end
-- Remove an iptables rule
function remove_rule(mac)
return os.execute("iptables -t nat -D luci_splash_leases -m mac --mac-source '"..mac.."' -j RETURN")
end
-- Check whether a MAC-Address is listed in the lease state list
function haslease(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v[".type"] == "lease" and v.mac and v.mac:lower() == mac then
return true
end
end
return false
end
-- Check whether a MAC-Address is whitelisted
function iswhitelisted(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v[".type"] == "whitelist" and v.mac and v.mac:lower() == mac then
return true
end
end
return false
end
-- Returns a list of MAC-Addresses for which a rule is existing
function listrules()
local cmd = "iptables -t nat -L luci_splash_leases | grep RETURN |"
cmd = cmd .. "egrep -io [0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+"
return ffluci.util.split(ffluci.sys.exec(cmd))
end
-- Synchronise leases, remove abandoned rules
function sync()
local written = {}
local time = os.time()
-- Current leases in state files
local leases = uci:show("luci_splash").luci_splash
-- Convert leasetime to seconds
local leasetime = tonumber(uci:get("luci_splash", "general", "leasetime")) * 3600
-- Clean state file
uci:revert("luci_splash")
-- For all leases
for k, v in pairs(uci:show("luci_splash")) do
if v[".type"] == "lease" then
if os.difftime(time, tonumber(v.start)) > leasetime then
-- Remove expired
remove_rule(v.mac)
else
-- Rewrite state
local n = uci:add("luci_splash", "lease")
uci:set("luci_splash", n, "mac", v.mac)
uci:set("luci_splash", n, "start", v.start)
written[v.mac:lower()] = 1
end
end
end
-- Delete rules without state
for i, r in ipairs(listrules()) do
if #r > 0 and not written[r:lower()] then
remove_rule(r)
end
end
end
main(arg)
|
#!/usr/bin/lua
package.path = "/usr/lib/lua/?.lua;/usr/lib/lua/?/init.lua;" .. package.path
package.cpath = "/usr/lib/lua/?.so;" .. package.cpath
require("ffluci.http")
require("ffluci.sys")
require("ffluci.model.uci")
-- Init state session
uci = ffluci.model.uci.StateSession()
function main(argv)
local cmd = argv[1]
local arg = argv[2]
if cmd == "status" then
if not arg then
os.exit(1)
end
if iswhitelisted(arg) then
print("whitelisted")
os.exit(0)
end
if haslease(arg) then
print("lease")
os.exit(0)
end
print("unknown")
os.exit(0)
elseif cmd == "add" then
if not arg then
os.exit(1)
end
if not haslease(arg) then
add_lease(arg)
else
print("already leased!")
os.exit(2)
end
os.exit(0)
elseif cmd == "remove" then
if not arg then
os.exit(1)
end
remove_lease(arg)
os.exit(0)
elseif cmd == "sync" then
sync()
os.exit(0)
else
print("Usage: " .. argv[0] .. " <status|add|remove|sync> [MAC]")
os.exit(1)
end
end
-- Add a lease to state and invoke add_rule
function add_lease(mac)
local key = uci:add("luci_splash", "lease")
uci:set("luci_splash", key, "mac", mac)
uci:set("luci_splash", key, "start", os.time())
add_rule(mac)
end
-- Remove a lease from state and invoke remove_rule
function remove_lease(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v.mac:lower() == mac then
remove_rule(mac)
uci:del("luci_splash", k)
end
end
end
-- Add an iptables rule
function add_rule(mac)
return os.execute("iptables -t nat -I luci_splash_leases -m mac --mac-source '"..mac.."' -j RETURN")
end
-- Remove an iptables rule
function remove_rule(mac)
return os.execute("iptables -t nat -D luci_splash_leases -m mac --mac-source '"..mac.."' -j RETURN")
end
-- Check whether a MAC-Address is listed in the lease state list
function haslease(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v[".type"] == "lease" and v.mac and v.mac:lower() == mac then
return true
end
end
return false
end
-- Check whether a MAC-Address is whitelisted
function iswhitelisted(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v[".type"] == "whitelist" and v.mac and v.mac:lower() == mac then
return true
end
end
return false
end
-- Returns a list of MAC-Addresses for which a rule is existing
function listrules()
local cmd = "iptables -t nat -L luci_splash_leases | grep RETURN |"
cmd = cmd .. "egrep -io [0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+"
return ffluci.util.split(ffluci.sys.exec(cmd))
end
-- Synchronise leases, remove abandoned rules
function sync()
local written = {}
local time = os.time()
-- Current leases in state files
local leases = uci:show("luci_splash").luci_splash
-- Convert leasetime to seconds
local leasetime = tonumber(uci:get("luci_splash", "general", "leasetime")) * 3600
-- Clean state file
uci:revert("luci_splash")
-- For all leases
for k, v in pairs(uci:show("luci_splash")) do
if v[".type"] == "lease" then
if os.difftime(time, tonumber(v.start)) > leasetime then
-- Remove expired
remove_rule(v.mac)
else
-- Rewrite state
local n = uci:add("luci_splash", "lease")
uci:set("luci_splash", n, "mac", v.mac)
uci:set("luci_splash", n, "start", v.start)
written[v.mac:lower()] = 1
end
end
end
-- Delete rules without state
for i, r in ipairs(listrules()) do
if #r > 0 and not written[r:lower()] then
remove_rule(r)
end
end
end
main(arg)
|
ffluci-splash: Minor fixes
|
ffluci-splash: Minor fixes
|
Lua
|
apache-2.0
|
tobiaswaldvogel/luci,ollie27/openwrt_luci,Hostle/openwrt-luci-multi-user,daofeng2015/luci,maxrio/luci981213,LazyZhu/openwrt-luci-trunk-mod,aircross/OpenWrt-Firefly-LuCI,joaofvieira/luci,openwrt/luci,tcatm/luci,lcf258/openwrtcn,harveyhu2012/luci,jorgifumi/luci,bright-things/ionic-luci,kuoruan/luci,rogerpueyo/luci,male-puppies/luci,lcf258/openwrtcn,mumuqz/luci,palmettos/test,Hostle/openwrt-luci-multi-user,openwrt-es/openwrt-luci,mumuqz/luci,artynet/luci,shangjiyu/luci-with-extra,zhaoxx063/luci,jlopenwrtluci/luci,jorgifumi/luci,opentechinstitute/luci,openwrt/luci,deepak78/new-luci,thesabbir/luci,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,taiha/luci,hnyman/luci,shangjiyu/luci-with-extra,slayerrensky/luci,bright-things/ionic-luci,teslamint/luci,oyido/luci,jchuang1977/luci-1,taiha/luci,openwrt/luci,thesabbir/luci,jlopenwrtluci/luci,kuoruan/lede-luci,NeoRaider/luci,LuttyYang/luci,marcel-sch/luci,openwrt/luci,Kyklas/luci-proto-hso,cshore/luci,slayerrensky/luci,obsy/luci,nmav/luci,Wedmer/luci,obsy/luci,MinFu/luci,forward619/luci,mumuqz/luci,kuoruan/lede-luci,NeoRaider/luci,oyido/luci,MinFu/luci,RuiChen1113/luci,palmettos/cnLuCI,tcatm/luci,RuiChen1113/luci,palmettos/cnLuCI,RuiChen1113/luci,remakeelectric/luci,Wedmer/luci,nmav/luci,tcatm/luci,openwrt-es/openwrt-luci,deepak78/new-luci,dwmw2/luci,Hostle/openwrt-luci-multi-user,Hostle/openwrt-luci-multi-user,cappiewu/luci,MinFu/luci,NeoRaider/luci,nmav/luci,fkooman/luci,thesabbir/luci,jorgifumi/luci,openwrt/luci,thess/OpenWrt-luci,openwrt-es/openwrt-luci,mumuqz/luci,harveyhu2012/luci,NeoRaider/luci,RuiChen1113/luci,oyido/luci,schidler/ionic-luci,tcatm/luci,Sakura-Winkey/LuCI,jorgifumi/luci,keyidadi/luci,zhaoxx063/luci,tobiaswaldvogel/luci,jorgifumi/luci,ff94315/luci-1,urueedi/luci,zhaoxx063/luci,maxrio/luci981213,remakeelectric/luci,thesabbir/luci,slayerrensky/luci,palmettos/cnLuCI,Noltari/luci,florian-shellfire/luci,jlopenwrtluci/luci,daofeng2015/luci,jorgifumi/luci,NeoRaider/luci,dwmw2/luci,male-puppies/luci,wongsyrone/luci-1,bittorf/luci,hnyman/luci,forward619/luci,Hostle/openwrt-luci-multi-user,harveyhu2012/luci,thess/OpenWrt-luci,deepak78/new-luci,ollie27/openwrt_luci,RedSnake64/openwrt-luci-packages,oyido/luci,ollie27/openwrt_luci,taiha/luci,RuiChen1113/luci,Kyklas/luci-proto-hso,rogerpueyo/luci,openwrt-es/openwrt-luci,opentechinstitute/luci,aa65535/luci,jchuang1977/luci-1,keyidadi/luci,sujeet14108/luci,RedSnake64/openwrt-luci-packages,cshore-firmware/openwrt-luci,remakeelectric/luci,taiha/luci,david-xiao/luci,fkooman/luci,LuttyYang/luci,artynet/luci,thesabbir/luci,sujeet14108/luci,hnyman/luci,thesabbir/luci,jlopenwrtluci/luci,shangjiyu/luci-with-extra,lcf258/openwrtcn,maxrio/luci981213,palmettos/test,oneru/luci,bittorf/luci,dismantl/luci-0.12,dwmw2/luci,nwf/openwrt-luci,wongsyrone/luci-1,opentechinstitute/luci,fkooman/luci,bittorf/luci,LazyZhu/openwrt-luci-trunk-mod,teslamint/luci,ollie27/openwrt_luci,Sakura-Winkey/LuCI,deepak78/new-luci,chris5560/openwrt-luci,oyido/luci,sujeet14108/luci,shangjiyu/luci-with-extra,florian-shellfire/luci,teslamint/luci,tobiaswaldvogel/luci,cshore-firmware/openwrt-luci,jlopenwrtluci/luci,jorgifumi/luci,aircross/OpenWrt-Firefly-LuCI,maxrio/luci981213,keyidadi/luci,kuoruan/luci,palmettos/cnLuCI,fkooman/luci,ff94315/luci-1,thesabbir/luci,bright-things/ionic-luci,kuoruan/lede-luci,artynet/luci,ff94315/luci-1,LazyZhu/openwrt-luci-trunk-mod,sujeet14108/luci,ff94315/luci-1,Sakura-Winkey/LuCI,Noltari/luci,taiha/luci,dwmw2/luci,palmettos/cnLuCI,nmav/luci,ff94315/luci-1,ReclaimYourPrivacy/cloak-luci,lbthomsen/openwrt-luci,RedSnake64/openwrt-luci-packages,Kyklas/luci-proto-hso,nwf/openwrt-luci,forward619/luci,joaofvieira/luci,bright-things/ionic-luci,db260179/openwrt-bpi-r1-luci,tobiaswaldvogel/luci,aircross/OpenWrt-Firefly-LuCI,rogerpueyo/luci,bittorf/luci,bittorf/luci,sujeet14108/luci,kuoruan/luci,artynet/luci,LuttyYang/luci,deepak78/new-luci,mumuqz/luci,david-xiao/luci,thess/OpenWrt-luci,fkooman/luci,cshore/luci,harveyhu2012/luci,hnyman/luci,daofeng2015/luci,daofeng2015/luci,cshore/luci,LuttyYang/luci,obsy/luci,chris5560/openwrt-luci,dismantl/luci-0.12,rogerpueyo/luci,urueedi/luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,obsy/luci,florian-shellfire/luci,lbthomsen/openwrt-luci,opentechinstitute/luci,lcf258/openwrtcn,LazyZhu/openwrt-luci-trunk-mod,urueedi/luci,keyidadi/luci,schidler/ionic-luci,db260179/openwrt-bpi-r1-luci,teslamint/luci,slayerrensky/luci,schidler/ionic-luci,joaofvieira/luci,marcel-sch/luci,remakeelectric/luci,wongsyrone/luci-1,kuoruan/luci,Hostle/openwrt-luci-multi-user,kuoruan/lede-luci,LuttyYang/luci,shangjiyu/luci-with-extra,jlopenwrtluci/luci,lcf258/openwrtcn,fkooman/luci,tcatm/luci,jchuang1977/luci-1,ReclaimYourPrivacy/cloak-luci,male-puppies/luci,fkooman/luci,aa65535/luci,slayerrensky/luci,maxrio/luci981213,teslamint/luci,joaofvieira/luci,oneru/luci,oneru/luci,openwrt-es/openwrt-luci,joaofvieira/luci,cshore/luci,hnyman/luci,LuttyYang/luci,nwf/openwrt-luci,schidler/ionic-luci,openwrt-es/openwrt-luci,Noltari/luci,Hostle/luci,aa65535/luci,male-puppies/luci,deepak78/new-luci,cshore/luci,urueedi/luci,RuiChen1113/luci,cshore/luci,lbthomsen/openwrt-luci,MinFu/luci,MinFu/luci,hnyman/luci,remakeelectric/luci,palmettos/cnLuCI,thess/OpenWrt-luci,oyido/luci,cappiewu/luci,david-xiao/luci,oneru/luci,Hostle/luci,lbthomsen/openwrt-luci,palmettos/cnLuCI,male-puppies/luci,teslamint/luci,db260179/openwrt-bpi-r1-luci,marcel-sch/luci,joaofvieira/luci,RuiChen1113/luci,RedSnake64/openwrt-luci-packages,chris5560/openwrt-luci,dwmw2/luci,harveyhu2012/luci,Noltari/luci,db260179/openwrt-bpi-r1-luci,cappiewu/luci,ReclaimYourPrivacy/cloak-luci,artynet/luci,Wedmer/luci,nmav/luci,taiha/luci,cappiewu/luci,daofeng2015/luci,Hostle/openwrt-luci-multi-user,dwmw2/luci,marcel-sch/luci,urueedi/luci,schidler/ionic-luci,bittorf/luci,rogerpueyo/luci,Noltari/luci,aa65535/luci,florian-shellfire/luci,nmav/luci,hnyman/luci,981213/luci-1,Hostle/luci,forward619/luci,forward619/luci,slayerrensky/luci,remakeelectric/luci,tobiaswaldvogel/luci,rogerpueyo/luci,kuoruan/lede-luci,ReclaimYourPrivacy/cloak-luci,forward619/luci,nwf/openwrt-luci,sujeet14108/luci,cappiewu/luci,aa65535/luci,ReclaimYourPrivacy/cloak-luci,wongsyrone/luci-1,Wedmer/luci,LazyZhu/openwrt-luci-trunk-mod,Hostle/luci,daofeng2015/luci,joaofvieira/luci,NeoRaider/luci,chris5560/openwrt-luci,bright-things/ionic-luci,tcatm/luci,Noltari/luci,ReclaimYourPrivacy/cloak-luci,zhaoxx063/luci,kuoruan/luci,cshore/luci,981213/luci-1,palmettos/test,openwrt-es/openwrt-luci,opentechinstitute/luci,schidler/ionic-luci,kuoruan/lede-luci,jchuang1977/luci-1,rogerpueyo/luci,LazyZhu/openwrt-luci-trunk-mod,lbthomsen/openwrt-luci,zhaoxx063/luci,fkooman/luci,marcel-sch/luci,NeoRaider/luci,MinFu/luci,palmettos/test,mumuqz/luci,tobiaswaldvogel/luci,oneru/luci,Noltari/luci,dismantl/luci-0.12,palmettos/test,daofeng2015/luci,urueedi/luci,cshore-firmware/openwrt-luci,Hostle/luci,opentechinstitute/luci,deepak78/new-luci,dismantl/luci-0.12,Hostle/luci,aa65535/luci,dwmw2/luci,teslamint/luci,Noltari/luci,palmettos/test,cappiewu/luci,cshore/luci,ff94315/luci-1,oneru/luci,hnyman/luci,lcf258/openwrtcn,jorgifumi/luci,bittorf/luci,oyido/luci,lcf258/openwrtcn,jchuang1977/luci-1,male-puppies/luci,Sakura-Winkey/LuCI,aircross/OpenWrt-Firefly-LuCI,maxrio/luci981213,LazyZhu/openwrt-luci-trunk-mod,aircross/OpenWrt-Firefly-LuCI,RuiChen1113/luci,cshore-firmware/openwrt-luci,Wedmer/luci,david-xiao/luci,Hostle/luci,chris5560/openwrt-luci,bright-things/ionic-luci,florian-shellfire/luci,sujeet14108/luci,david-xiao/luci,kuoruan/luci,thesabbir/luci,artynet/luci,thess/OpenWrt-luci,kuoruan/luci,maxrio/luci981213,opentechinstitute/luci,981213/luci-1,chris5560/openwrt-luci,florian-shellfire/luci,lcf258/openwrtcn,jchuang1977/luci-1,openwrt/luci,palmettos/test,taiha/luci,oneru/luci,MinFu/luci,artynet/luci,lbthomsen/openwrt-luci,mumuqz/luci,keyidadi/luci,deepak78/new-luci,teslamint/luci,mumuqz/luci,openwrt/luci,dismantl/luci-0.12,nwf/openwrt-luci,david-xiao/luci,tcatm/luci,obsy/luci,keyidadi/luci,RedSnake64/openwrt-luci-packages,shangjiyu/luci-with-extra,aa65535/luci,thess/OpenWrt-luci,nwf/openwrt-luci,981213/luci-1,slayerrensky/luci,bright-things/ionic-luci,obsy/luci,cshore-firmware/openwrt-luci,cappiewu/luci,nwf/openwrt-luci,nmav/luci,db260179/openwrt-bpi-r1-luci,cshore-firmware/openwrt-luci,kuoruan/lede-luci,schidler/ionic-luci,palmettos/test,shangjiyu/luci-with-extra,thess/OpenWrt-luci,male-puppies/luci,florian-shellfire/luci,jchuang1977/luci-1,zhaoxx063/luci,shangjiyu/luci-with-extra,david-xiao/luci,lcf258/openwrtcn,wongsyrone/luci-1,dismantl/luci-0.12,marcel-sch/luci,urueedi/luci,rogerpueyo/luci,oyido/luci,981213/luci-1,kuoruan/luci,nmav/luci,schidler/ionic-luci,tobiaswaldvogel/luci,lcf258/openwrtcn,Noltari/luci,zhaoxx063/luci,joaofvieira/luci,remakeelectric/luci,bittorf/luci,ReclaimYourPrivacy/cloak-luci,palmettos/cnLuCI,981213/luci-1,Wedmer/luci,bright-things/ionic-luci,slayerrensky/luci,Kyklas/luci-proto-hso,dwmw2/luci,remakeelectric/luci,Sakura-Winkey/LuCI,dismantl/luci-0.12,harveyhu2012/luci,LuttyYang/luci,artynet/luci,ollie27/openwrt_luci,artynet/luci,wongsyrone/luci-1,cshore-firmware/openwrt-luci,Kyklas/luci-proto-hso,cshore-firmware/openwrt-luci,Wedmer/luci,marcel-sch/luci,db260179/openwrt-bpi-r1-luci,opentechinstitute/luci,sujeet14108/luci,Sakura-Winkey/LuCI,aircross/OpenWrt-Firefly-LuCI,Kyklas/luci-proto-hso,Wedmer/luci,ff94315/luci-1,zhaoxx063/luci,oneru/luci,LuttyYang/luci,Hostle/openwrt-luci-multi-user,NeoRaider/luci,obsy/luci,Sakura-Winkey/LuCI,LazyZhu/openwrt-luci-trunk-mod,ollie27/openwrt_luci,MinFu/luci,tcatm/luci,thess/OpenWrt-luci,cappiewu/luci,Kyklas/luci-proto-hso,jlopenwrtluci/luci,wongsyrone/luci-1,marcel-sch/luci,aircross/OpenWrt-Firefly-LuCI,ollie27/openwrt_luci,jchuang1977/luci-1,male-puppies/luci,obsy/luci,nmav/luci,chris5560/openwrt-luci,kuoruan/lede-luci,ollie27/openwrt_luci,tobiaswaldvogel/luci,ReclaimYourPrivacy/cloak-luci,wongsyrone/luci-1,Hostle/luci,urueedi/luci,nwf/openwrt-luci,keyidadi/luci,forward619/luci,openwrt-es/openwrt-luci,jlopenwrtluci/luci,ff94315/luci-1,harveyhu2012/luci,taiha/luci,forward619/luci,RedSnake64/openwrt-luci-packages,daofeng2015/luci,openwrt/luci,aa65535/luci,db260179/openwrt-bpi-r1-luci,RedSnake64/openwrt-luci-packages,981213/luci-1,keyidadi/luci,david-xiao/luci,lbthomsen/openwrt-luci,maxrio/luci981213,florian-shellfire/luci
|
ae5216e8b4527a1e3d4962fad7b933f420793666
|
lua/weapons/remotecontroller.lua
|
lua/weapons/remotecontroller.lua
|
AddCSLuaFile()
SWEP.Author = "Divran" -- Originally by ShaRose, rewritten by Divran at 2011-04-03
SWEP.Contact = ""
SWEP.Purpose = "Remote control for Pod Controllers in wire."
SWEP.Instructions = "Left Click on Pod Controller to link up, and use to start controlling."
SWEP.Category = "Wiremod"
SWEP.PrintName = "Remote Control"
SWEP.Slot = 0
SWEP.SlotPos = 4
SWEP.DrawAmmo = false
SWEP.Weight = 1
SWEP.Spawnable = true
SWEP.AdminOnly = false
SWEP.Primary.ClipSize = -1
SWEP.Primary.DefaultClip = -1
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = "none"
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.viewModel = "models/weapons/v_pistol.mdl"
SWEP.worldModel = "models/weapons/w_pistol.mdl"
if CLIENT then return end
function SWEP:PrimaryAttack()
local trace = self:GetOwner():GetEyeTrace()
if IsValid(trace.Entity) and trace.Entity:GetClass() == "gmod_wire_pod" and gamemode.Call("PlayerUse", self:GetOwner(), trace.Entity) then
self.Linked = trace.Entity
self:GetOwner():ChatPrint("Remote Controller linked.")
end
end
function SWEP:Holster()
if (self.Linked) then
self:Off()
end
return true
end
function SWEP:OnDrop()
if (self.Linked) then
self:Off()
self.Linked = nil
end
end
function SWEP:On()
self.Active = true
self.OldMoveType = self:GetOwner():GetMoveType()
self:GetOwner():SetMoveType(MOVETYPE_NONE)
self:GetOwner():DrawViewModel(false)
if (self.Linked and self.Linked:IsValid()) then
self.Linked:PlayerEntered( self:GetOwner(), self )
end
end
function SWEP:Off()
if self.Active then
self:GetOwner():SetMoveType(self.OldMoveType or MOVETYPE_WALK)
end
self.Active = nil
self.OldMoveType = nil
self:GetOwner():DrawViewModel(true)
if (self.Linked and self.Linked:IsValid()) then
self.Linked:PlayerExited( self:GetOwner() )
end
end
function SWEP:Think()
if (!self.Linked) then return end
if (self:GetOwner():KeyPressed( IN_USE )) then
if (!self.Active) then
self:On()
else
self:Off()
end
end
end
function SWEP:Deploy()
return true
end
|
AddCSLuaFile()
SWEP.Author = "Divran" -- Originally by ShaRose, rewritten by Divran at 2011-04-03
SWEP.Contact = ""
SWEP.Purpose = "Remote control for Pod Controllers in wire."
SWEP.Instructions = "Left Click on Pod Controller to link up, and use to start controlling."
SWEP.Category = "Wiremod"
SWEP.PrintName = "Remote Control"
SWEP.Slot = 0
SWEP.SlotPos = 4
SWEP.DrawAmmo = false
SWEP.Weight = 1
SWEP.Spawnable = true
SWEP.AdminOnly = false
SWEP.Primary.ClipSize = -1
SWEP.Primary.DefaultClip = -1
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = "none"
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.viewModel = "models/weapons/v_pistol.mdl"
SWEP.worldModel = "models/weapons/w_pistol.mdl"
if CLIENT then return end
function SWEP:PrimaryAttack()
local ply = self:GetOwner()
local trace = ply:GetEyeTrace()
if IsValid(trace.Entity) and trace.Entity:GetClass() == "gmod_wire_pod" and gamemode.Call("PlayerUse", ply, trace.Entity) then
self.Linked = trace.Entity
ply:ChatPrint("Remote Controller linked.")
end
end
function SWEP:Holster()
if self.Linked then
self:Off()
end
return true
end
function SWEP:Deploy()
return true
end
function SWEP:OnDrop()
if not self.Linked then return end
self:Off()
self.Linked = nil
end
function SWEP:On()
local ply = self:GetOwner()
self.Active = true
self.OldMoveType = not ply:InVehicle() and ply:GetMoveType() or MOVETYPE_WALK
ply:SetMoveType(MOVETYPE_NONE)
ply:DrawViewModel(false)
if IsValid(self.Linked) then
self.Linked:PlayerEntered(ply, self)
end
end
function SWEP:Off()
local ply = self:GetOwner()
if self.Active then
ply:SetMoveType(self.OldMoveType or MOVETYPE_WALK)
end
self.Active = nil
self.OldMoveType = nil
ply:DrawViewModel(true)
if IsValid(self.Linked) then
self.Linked:PlayerExited(ply)
end
end
function SWEP:Think()
if not self.Linked then return end
if self:GetOwner():KeyPressed(IN_USE) then
if not self.Active then
self:On()
else
self:Off()
end
end
end
|
Updated Remote Controller (#1172)
|
Updated Remote Controller (#1172)
Fixed exploit with remote controller which allowed you to get into noclip on servers which have noclip disabled
|
Lua
|
apache-2.0
|
NezzKryptic/Wire,garrysmodlua/wire,dvdvideo1234/wire,Grocel/wire,thegrb93/wire,wiremod/wire,sammyt291/wire,bigdogmat/wire
|
05e5ba4a27bb34e60334107364c403a68cf6fba0
|
mod_carbons/mod_carbons.lua
|
mod_carbons/mod_carbons.lua
|
-- XEP-0280: Message Carbons implementation for Prosody
-- Copyright (C) 2011 Kim Alvefur
--
-- This file is MIT/X11 licensed.
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
local xmlns_carbons = "urn:xmpp:carbons:1";
local xmlns_forward = "urn:xmpp:forward:0";
local host_sessions = hosts[module.host].sessions;
local full_sessions, bare_sessions = full_sessions, bare_sessions;
local function toggle_carbons(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local state = stanza.tags[1].name;
module:log("debug", "%s %sd carbons", origin.full_jid, state);
origin.want_carbons = state == "enable";
origin.send(st.reply(stanza));
return true
end
end
module:hook("iq/self/"..xmlns_carbons..":disable", toggle_carbons);
module:hook("iq/self/"..xmlns_carbons..":enable", toggle_carbons);
local function message_handler(event, c2s)
local origin, stanza = event.origin, event.stanza;
local orig_type = stanza.attr.type;
local orig_to = stanza.attr.to;
if not (orig_type == nil
or orig_type == "normal"
or orig_type == "chat") then
return -- No carbons for messages of type error or headline
end
-- Stanza sent by a local client
local bare_jid = origin.username .. "@" .. origin.host;
local target_session = origin;
local top_priority = false;
local user_sessions = host_sessions[origin.username];
-- Stanza about to be delivered to a local client
if not c2s then
bare_jid = jid_bare(orig_to);
target_session = full_sessions[orig_to]
user_sessions = bare_sessions[bare_jid];
if not target_session and user_sessions then
-- The top resources will already receive this message per normal routing rules,
-- so we are going to skip them in order to avoid sending duplicated messages.
local top_resources = user_sessions.top_resources;
top_priority = top_resources and top_resources[1].priority
end
end
if not user_sessions then
module:log("debug", "Skip carbons for offline user");
return -- No use in sending carbons to an offline user
end
if not c2s and stanza:get_child("private", xmlns_carbons) then
stanza:maptags(function(tag)
return tag.attr.xmlns == xmlns_carbons
and tag.name == "private" and tag or nil;
end);
module:log("debug", "Message tagged private, ignoring");
return
end
-- Create the carbon copy and wrap it as per the Stanza Forwarding XEP
local copy = st.clone(stanza);
copy.attr.xmlns = "jabber:client";
local carbon = st.message{ from = bare_jid, type = orig_type, }
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons }):up()
:tag("forwarded", { xmlns = xmlns_forward })
:add_child(copy):reset();
user_sessions = user_sessions and user_sessions.sessions;
for _, session in pairs(user_sessions) do
-- Carbons are sent to resources that have enabled it
if session.want_carbons
-- but not the resource that sent the message, or the one that it's directed to
and session ~= target_session
-- and isn't among the top resources that would receive the message per standard routing rules
and (not c2s or session.priority ~= top_priority) then
carbon.attr.to = session.full_jid;
module:log("debug", "Sending carbon to %s", session.full_jid);
session.send(carbon);
end
end
end
local function c2s_message_handler(event)
return message_handler(event, true)
end
-- Stanzas sent by local clients
module:hook("pre-message/bare", c2s_message_handler, 1);
module:hook("pre-message/full", c2s_message_handler, 1);
-- Stanzas to local clients
module:hook("message/bare", message_handler, 1);
module:hook("message/full", message_handler, 1);
module:add_feature(xmlns_carbons);
|
-- XEP-0280: Message Carbons implementation for Prosody
-- Copyright (C) 2011 Kim Alvefur
--
-- This file is MIT/X11 licensed.
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
local xmlns_carbons = "urn:xmpp:carbons:1";
local xmlns_forward = "urn:xmpp:forward:0";
local host_sessions = hosts[module.host].sessions;
local full_sessions, bare_sessions = full_sessions, bare_sessions;
local function toggle_carbons(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local state = stanza.tags[1].name;
module:log("debug", "%s %sd carbons", origin.full_jid, state);
origin.want_carbons = state == "enable";
origin.send(st.reply(stanza));
return true
end
end
module:hook("iq/self/"..xmlns_carbons..":disable", toggle_carbons);
module:hook("iq/self/"..xmlns_carbons..":enable", toggle_carbons);
local function message_handler(event, c2s)
local origin, stanza = event.origin, event.stanza;
local orig_type = stanza.attr.type;
local orig_from = stanza.attr.from;
local orig_to = stanza.attr.to;
if not (orig_type == nil
or orig_type == "normal"
or orig_type == "chat") then
return -- No carbons for messages of type error or headline
end
-- Stanza sent by a local client
local bare_jid = origin.type == "c2s" and origin.username .. "@" .. origin.host or jid_bare(orig_from);
local target_session = origin;
local top_priority = false;
local user_sessions = host_sessions[origin.username];
-- Stanza about to be delivered to a local client
if not c2s then
bare_jid = jid_bare(orig_to);
target_session = full_sessions[orig_to]
user_sessions = bare_sessions[bare_jid];
if not target_session and user_sessions then
-- The top resources will already receive this message per normal routing rules,
-- so we are going to skip them in order to avoid sending duplicated messages.
local top_resources = user_sessions.top_resources;
top_priority = top_resources and top_resources[1].priority
end
end
if not user_sessions then
module:log("debug", "Skip carbons for offline user");
return -- No use in sending carbons to an offline user
end
if not c2s and stanza:get_child("private", xmlns_carbons) then
stanza:maptags(function(tag)
return tag.attr.xmlns == xmlns_carbons
and tag.name == "private" and tag or nil;
end);
module:log("debug", "Message tagged private, ignoring");
return
end
-- Create the carbon copy and wrap it as per the Stanza Forwarding XEP
local copy = st.clone(stanza);
copy.attr.xmlns = "jabber:client";
local carbon = st.message{ from = bare_jid, type = orig_type, }
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons }):up()
:tag("forwarded", { xmlns = xmlns_forward })
:add_child(copy):reset();
user_sessions = user_sessions and user_sessions.sessions;
for _, session in pairs(user_sessions) do
-- Carbons are sent to resources that have enabled it
if session.want_carbons
-- but not the resource that sent the message, or the one that it's directed to
and session ~= target_session
-- and isn't among the top resources that would receive the message per standard routing rules
and (not c2s or session.priority ~= top_priority) then
carbon.attr.to = session.full_jid;
module:log("debug", "Sending carbon to %s", session.full_jid);
session.send(carbon);
end
end
end
local function c2s_message_handler(event)
return message_handler(event, true)
end
-- Stanzas sent by local clients
module:hook("pre-message/bare", c2s_message_handler, 1);
module:hook("pre-message/full", c2s_message_handler, 1);
-- Stanzas to local clients
module:hook("message/bare", message_handler, 1);
module:hook("message/full", message_handler, 1);
module:add_feature(xmlns_carbons);
|
mod_carbons: Fix handling of messages from remote hosts
|
mod_carbons: Fix handling of messages from remote hosts
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
c971ec7dc7f5693e81535ec8f78b83ede6a33857
|
mods/screwdriver/init.lua
|
mods/screwdriver/init.lua
|
local mode_text = {
{"Change rotation, Don't change axisdir."},
{"Keep choosen face in front then rotate it."},
{"Change axis dir, Reset rotation."},
{"Bring top in front then rotate it."},
}
local opposite_faces = {
[0] = 5,
[1] = 2,
[2] = 1,
[3] = 4,
[4] = 3,
[5] = 0,
}
local function screwdriver_setmode(user,itemstack)
local player_name = user:get_player_name()
local item = itemstack:to_table()
local mode = tonumber(itemstack:get_metadata())
if not mode then
minetest.chat_send_player(player_name, "Hold shift and use to change screwdriwer modes.")
mode = 0
end
mode = mode + 1
if mode == 5 then
mode = 1
end
minetest.chat_send_player(player_name, "Screwdriver mode : "..mode.." - "..mode_text[mode][1] )
itemstack:set_name("screwdriver:screwdriver"..mode)
itemstack:set_metadata(mode)
return itemstack
end
local function get_node_face(pointed_thing)
local ax, ay, az = pointed_thing.above.x, pointed_thing.above.y, pointed_thing.above.z
local ux, uy, uz = pointed_thing.under.x, pointed_thing.under.y, pointed_thing.under.z
if ay > uy then return 0 -- Top
elseif az > uz then return 1 -- Z+ side
elseif az < uz then return 2 -- Z- side
elseif ax > ux then return 3 -- X+ side
elseif ax < ux then return 4 -- X- side
elseif ay < uy then return 5 -- Bottom
else
error("pointed_thing.above and under are the same!")
end
end
local function nextrange(x, max)
x = x + 1
if x > max then
x = 0
end
return x
end
local function screwdriver_handler(itemstack, user, pointed_thing)
if pointed_thing.type ~= "node" then
return
end
local pos = pointed_thing.under
local keys = user:get_player_control()
local player_name = user:get_player_name()
local mode = tonumber(itemstack:get_metadata())
if not mode or keys["sneak"] == true then
return screwdriver_setmode(user, itemstack)
end
if minetest.is_protected(pos, user:get_player_name()) then
minetest.record_protection_violation(pos, user:get_player_name())
return
end
local node = minetest.get_node(pos)
local node_name = node.name
local ndef = minetest.registered_nodes[node.name]
if ndef.paramtype2 == "facedir" then
if ndef.drawtype == "nodebox" and ndef.node_box.type ~= "fixed" then
return
end
if node.param2 == nil then
return
end
-- Get ready to set the param2
local n = node.param2
local axisdir = math.floor(n / 4)
local rotation = n - axisdir * 4
if mode == 1 then
n = axisdir * 4 + nextrange(rotation, 3)
elseif mode == 2 then
-- If you are pointing at the axisdir face or the
-- opposite one then you can just rotate the node.
-- Otherwise change the axisdir, avoiding the facing
-- and opposite axes.
local face = get_node_face(pointed_thing)
if axisdir == face or axisdir == opposite_faces[face] then
n = axisdir * 4 + nextrange(rotation, 3)
else
axisdir = nextrange(axisdir, 5)
-- This is repeated because switching from the face
-- can move to to the opposite and vice-versa
if axisdir == face or axisdir == opposite_faces[face] then
axisdir = nextrange(axisdir, 5)
end
if axisdir == face or axisdir == opposite_faces[face] then
axisdir = nextrange(axisdir, 5)
end
n = axisdir * 4
end
elseif mode == 3 then
n = nextrange(axisdir, 5) * 4
elseif mode == 4 then
local face = get_node_face(pointed_thing)
if axisdir == face then
n = axisdir * 4 + nextrange(rotation, 3)
else
n = face * 4
end
end
--print (dump(axisdir..", "..rotation))
node.param2 = n
minetest.swap_node(pos, node)
local item_wear = tonumber(itemstack:get_wear())
item_wear = item_wear + 327
if item_wear > 65535 then
itemstack:clear()
return itemstack
end
itemstack:set_wear(item_wear)
return itemstack
end
end
minetest.register_craft({
output = "screwdriver:screwdriver",
recipe = {
{"default:steel_ingot"},
{"group:stick"}
}
})
minetest.register_tool("screwdriver:screwdriver", {
description = "Screwdriver",
inventory_image = "screwdriver.png",
on_use = function(itemstack, user, pointed_thing)
screwdriver_handler(itemstack, user, pointed_thing)
return itemstack
end,
})
for i = 1, 4 do
minetest.register_tool("screwdriver:screwdriver"..i, {
description = "Screwdriver in Mode "..i,
inventory_image = "screwdriver.png^tool_mode"..i..".png",
wield_image = "screwdriver.png",
groups = {not_in_creative_inventory=1},
on_use = function(itemstack, user, pointed_thing)
screwdriver_handler(itemstack, user, pointed_thing)
return itemstack
end,
})
end
|
local mode_text = {
{"Change rotation, Don't change axisdir."},
{"Keep choosen face in front then rotate it."},
{"Change axis dir, Reset rotation."},
{"Bring top in front then rotate it."},
}
local opposite_faces = {
[0] = 5,
[1] = 2,
[2] = 1,
[3] = 4,
[4] = 3,
[5] = 0,
}
local function screwdriver_setmode(user,itemstack)
local player_name = user:get_player_name()
local item = itemstack:to_table()
local mode = tonumber(itemstack:get_metadata())
if not mode then
minetest.chat_send_player(player_name, "Hold shift and use to change screwdriwer modes.")
mode = 0
end
mode = mode + 1
if mode == 5 then
mode = 1
end
minetest.chat_send_player(player_name, "Screwdriver mode : "..mode.." - "..mode_text[mode][1] )
itemstack:set_name("screwdriver:screwdriver"..mode)
itemstack:set_metadata(mode)
return itemstack
end
local function get_node_face(pointed_thing)
local ax, ay, az = pointed_thing.above.x, pointed_thing.above.y, pointed_thing.above.z
local ux, uy, uz = pointed_thing.under.x, pointed_thing.under.y, pointed_thing.under.z
if ay > uy then return 0 -- Top
elseif az > uz then return 1 -- Z+ side
elseif az < uz then return 2 -- Z- side
elseif ax > ux then return 3 -- X+ side
elseif ax < ux then return 4 -- X- side
elseif ay < uy then return 5 -- Bottom
else
error("pointed_thing.above and under are the same!")
end
end
local function nextrange(x, max)
x = x + 1
if x > max then
x = 0
end
return x
end
local function screwdriver_handler(itemstack, user, pointed_thing)
if pointed_thing.type ~= "node" then
return
end
local pos = pointed_thing.under
local keys = user:get_player_control()
local player_name = user:get_player_name()
local mode = tonumber(itemstack:get_metadata())
if not mode or keys["sneak"] == true then
return screwdriver_setmode(user, itemstack)
end
if minetest.is_protected(pos, user:get_player_name()) then
minetest.record_protection_violation(pos, user:get_player_name())
return
end
local node = minetest.get_node(pos)
local ndef = minetest.registered_nodes[node.name]
if ndef and ndef.paramtype2 == "facedir" then
if ndef.drawtype == "nodebox" and ndef.node_box.type ~= "fixed" then
return
end
if node.param2 == nil then
return
end
-- Get ready to set the param2
local n = node.param2
local axisdir = math.floor(n / 4)
local rotation = n - axisdir * 4
if mode == 1 then
n = axisdir * 4 + nextrange(rotation, 3)
elseif mode == 2 then
-- If you are pointing at the axisdir face or the
-- opposite one then you can just rotate the node.
-- Otherwise change the axisdir, avoiding the facing
-- and opposite axes.
local face = get_node_face(pointed_thing)
if axisdir == face or axisdir == opposite_faces[face] then
n = axisdir * 4 + nextrange(rotation, 3)
else
axisdir = nextrange(axisdir, 5)
-- This is repeated because switching from the face
-- can move to to the opposite and vice-versa
if axisdir == face or axisdir == opposite_faces[face] then
axisdir = nextrange(axisdir, 5)
end
if axisdir == face or axisdir == opposite_faces[face] then
axisdir = nextrange(axisdir, 5)
end
n = axisdir * 4
end
elseif mode == 3 then
n = nextrange(axisdir, 5) * 4
elseif mode == 4 then
local face = get_node_face(pointed_thing)
if axisdir == face then
n = axisdir * 4 + nextrange(rotation, 3)
else
n = face * 4
end
end
--print (dump(axisdir..", "..rotation))
node.param2 = n
minetest.swap_node(pos, node)
local item_wear = tonumber(itemstack:get_wear())
item_wear = item_wear + 327
if item_wear > 65535 then
itemstack:clear()
return itemstack
end
itemstack:set_wear(item_wear)
return itemstack
end
end
minetest.register_craft({
output = "screwdriver:screwdriver",
recipe = {
{"default:steel_ingot"},
{"group:stick"}
}
})
minetest.register_tool("screwdriver:screwdriver", {
description = "Screwdriver",
inventory_image = "screwdriver.png",
on_use = function(itemstack, user, pointed_thing)
screwdriver_handler(itemstack, user, pointed_thing)
return itemstack
end,
})
for i = 1, 4 do
minetest.register_tool("screwdriver:screwdriver"..i, {
description = "Screwdriver in Mode "..i,
inventory_image = "screwdriver.png^tool_mode"..i..".png",
wield_image = "screwdriver.png",
groups = {not_in_creative_inventory=1},
on_use = function(itemstack, user, pointed_thing)
screwdriver_handler(itemstack, user, pointed_thing)
return itemstack
end,
})
end
|
Fix crash when using the screwdriver on an unknown node
|
Fix crash when using the screwdriver on an unknown node
|
Lua
|
lgpl-2.1
|
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
|
b53d4079797ca34869ed6970bf74243ec9450e9f
|
mods/mff/mff_pclasses/hunter.lua
|
mods/mff/mff_pclasses/hunter.lua
|
------------------
-- Hunter class --
------------------
--
-- See https://github.com/Ombridride/minetest-minetestforfun-server/issues/114
--
pclasses.api.register_class("hunter", {
on_assigned = function(pname, inform)
if inform then
minetest.chat_send_player(pname, "You are now a hunter")
minetest.sound_play("pclasses_full_hunter", {to_player=pname, gain=1})
end
local reinforced = pclasses.api.util.does_wear_full_armor(pname, "reinforcedleather", true)
if reinforced then
sprint.increase_maxstamina(pname, 20)
else
sprint.increase_maxstamina(pname, 10)
end
minetest.log("action", "[PClasses] Player " .. pname .. " become a hunter")
end,
on_unassigned = function(pname)
sprint.set_default_maxstamina(pname)
end,
switch_params = {
color = {r = 30, g = 170, b = 00},
tile = "default_wood.png",
holo_item = "throwing:bow_minotaur_horn_improved"
}
})
pclasses.api.reserve_item("hunter", "throwing:bow_minotaur_horn")
pclasses.api.reserve_item("hunter", "throwing:bow_minotaur_horn_improved")
pclasses.api.reserve_item("hunter", "throwing:arrow_mithril")
pclasses.api.reserve_item("hunter", "throwing:arbalest_auto")
pclasses.api.reserve_item("hunter", "spears:spear_stone")
pclasses.api.reserve_item("hunter", "spears:spear_steel")
pclasses.api.reserve_item("hunter", "spears:spear_obsidian")
pclasses.api.reserve_item("hunter", "spears:spear_diamond")
pclasses.api.reserve_item("hunter", "spears:spear_mithril")
for _, i in pairs({"helmet", "chestplate", "boots", "leggings"}) do
pclasses.api.reserve_item("hunter", "3d_armor:" .. i .. "_hardenedleather")
pclasses.api.reserve_item("hunter", "3d_armor:" .. i .. "_reinforcedleather")
end
|
------------------
-- Hunter class --
------------------
--
-- See https://github.com/Ombridride/minetest-minetestforfun-server/issues/114
--
pclasses.api.register_class("hunter", {
on_assigned = function(pname, inform)
if inform then
minetest.chat_send_player(pname, "You are now a hunter")
minetest.sound_play("pclasses_full_hunter", {to_player=pname, gain=1})
end
local reinforced = pclasses.api.util.does_wear_full_armor(pname, "reinforcedleather", true)
if reinforced then
sprint.increase_maxstamina(pname, 20)
else
sprint.increase_maxstamina(pname, 10)
end
minetest.log("action", "[PClasses] Player " .. pname .. " become a hunter")
end,
on_unassigned = function(pname)
sprint.set_default_maxstamina(pname)
end,
switch_params = {
color = {r = 30, g = 170, b = 00},
tile = "default_wood.png",
holo_item = "throwing:bow_minotaur_horn_improved"
}
})
pclasses.api.reserve_item("hunter", "throwing:bow_minotaur_horn")
pclasses.api.reserve_item("hunter", "throwing:bow_minotaur_horn_loaded")
pclasses.api.reserve_item("hunter", "throwing:bow_minotaur_horn_improved")
pclasses.api.reserve_item("hunter", "throwing:bow_minotaur_horn_improved_loaded")
pclasses.api.reserve_item("hunter", "throwing:arrow_mithril")
pclasses.api.reserve_item("hunter", "throwing:arbalest_auto")
pclasses.api.reserve_item("hunter", "throwing:arbalest_auto_loaded")
pclasses.api.reserve_item("hunter", "spears:spear_stone")
pclasses.api.reserve_item("hunter", "spears:spear_steel")
pclasses.api.reserve_item("hunter", "spears:spear_obsidian")
pclasses.api.reserve_item("hunter", "spears:spear_diamond")
pclasses.api.reserve_item("hunter", "spears:spear_mithril")
for _, i in pairs({"helmet", "chestplate", "boots", "leggings"}) do
pclasses.api.reserve_item("hunter", "3d_armor:" .. i .. "_hardenedleather")
pclasses.api.reserve_item("hunter", "3d_armor:" .. i .. "_reinforcedleather")
end
|
fix no drop hunter bow_minotaur_horn/arbalest_auto when loaded, issue https://github.com/MinetestForFun/server-minetestforfun/issues/420
|
fix no drop hunter bow_minotaur_horn/arbalest_auto when loaded, issue https://github.com/MinetestForFun/server-minetestforfun/issues/420
|
Lua
|
unlicense
|
Coethium/server-minetestforfun,sys4-fr/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun,Coethium/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/server-minetestforfun,sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,crabman77/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server
|
3761aa95483ac060dc51973727b1f059698de016
|
mods/unified_inventory/group.lua
|
mods/unified_inventory/group.lua
|
function unified_inventory.canonical_item_spec_matcher(spec)
local specname = ItemStack(spec):get_name()
if specname:sub(1, 6) == "group:" then
local group_names = specname:sub(7):split(",")
return function (itemname)
local itemdef = minetest.registered_items[itemname]
for _, group_name in ipairs(group_names) do
if (itemdef.groups[group_name] or 0) == 0 then
return false
end
end
return true
end
else
return function (itemname) return itemname == specname end
end
end
function unified_inventory.item_matches_spec(item, spec)
local itemname = ItemStack(item):get_name()
return unified_inventory.canonical_item_spec_matcher(spec)(itemname)
end
unified_inventory.registered_group_items = {
mesecon_conductor_craftable = "mesecons:wire_00000000_off",
stone = "default:cobble",
wool = "wool:white",
}
function unified_inventory.register_group_item(groupname, itemname)
unified_inventory.registered_group_items[groupname] = itemname
end
-- This is used when displaying craft recipes, where an ingredient is
-- specified by group rather than as a specific item. A single-item group
-- is represented by that item, with the single-item status signalled
-- in the "sole" field. If the group contains no items at all, the item
-- field will be nil.
--
-- Within a multiple-item group, we prefer to use an item that has the
-- same specific name as the group, and if there are more than one of
-- those items we prefer the one registered for the group by a mod.
-- Among equally-preferred items, we just pick the one with the
-- lexicographically earliest name.
--
-- The parameter to this function isn't just a single group name.
-- It may be a comma-separated list of group names. This is really a
-- "group:..." ingredient specification, minus the "group:" prefix.
local function compute_group_item(group_name_list)
local group_names = group_name_list:split(",")
local candidate_items = {}
for itemname, itemdef in pairs(minetest.registered_items) do
if (itemdef.groups.not_in_creative_inventory or 0) == 0 then
local all = true
for _, group_name in ipairs(group_names) do
if (itemdef.groups[group_name] or 0) == 0 then
all = false
end
end
if all then table.insert(candidate_items, itemname) end
end
end
local num_candidates = #candidate_items
if num_candidates == 0 then
return {sole = true}
elseif num_candidates == 1 then
return {item = candidate_items[1], sole = true}
end
local is_group = {}
local registered_rep = {}
for _, group_name in ipairs(group_names) do
is_group[group_name] = true
local rep = unified_inventory.registered_group_items[group_name]
if rep then registered_rep[rep] = true end
end
local bestitem = ""
local bestpref = 0
for _, item in ipairs(candidate_items) do
local pref
if registered_rep[item] then
pref = 4
elseif string.sub(item, 1, 8) == "default:" and is_group[string.sub(item, 9)] then
pref = 3
elseif is_group[item:gsub("^[^:]*:", "")] then
pref = 2
else
pref = 1
end
if pref > bestpref or (pref == bestpref and item < bestitem) then
bestitem = item
bestpref = pref
end
end
return {item = bestitem, sole = false}
end
local group_item_cache = {}
function unified_inventory.get_group_item(group_name)
if not group_item_cache[group_name] then
group_item_cache[group_name] = compute_group_item(group_name)
end
return group_item_cache[group_name]
end
|
function unified_inventory.canonical_item_spec_matcher(spec)
local specname = ItemStack(spec):get_name()
if specname:sub(1, 6) == "group:" then
local group_names = specname:sub(7):split(",")
return function (itemname)
local itemdef = minetest.registered_items[itemname]
for _, group_name in ipairs(group_names) do
if (itemdef.groups[group_name] or 0) == 0 then
return false
end
end
return true
end
else
return function (itemname) return itemname == specname end
end
end
function unified_inventory.item_matches_spec(item, spec)
local itemname = ItemStack(item):get_name()
return unified_inventory.canonical_item_spec_matcher(spec)(itemname)
end
unified_inventory.registered_group_items = {
mesecon_conductor_craftable = "mesecons:wire_00000000_off",
stone = "default:cobble",
wool = "wool:white",
ingot = "default:steel_ingot",
}
function unified_inventory.register_group_item(groupname, itemname)
unified_inventory.registered_group_items[groupname] = itemname
end
-- This is used when displaying craft recipes, where an ingredient is
-- specified by group rather than as a specific item. A single-item group
-- is represented by that item, with the single-item status signalled
-- in the "sole" field. If the group contains no items at all, the item
-- field will be nil.
--
-- Within a multiple-item group, we prefer to use an item that has the
-- same specific name as the group, and if there are more than one of
-- those items we prefer the one registered for the group by a mod.
-- Among equally-preferred items, we just pick the one with the
-- lexicographically earliest name.
--
-- The parameter to this function isn't just a single group name.
-- It may be a comma-separated list of group names. This is really a
-- "group:..." ingredient specification, minus the "group:" prefix.
local function compute_group_item(group_name_list)
local group_names = group_name_list:split(",")
local candidate_items = {}
for itemname, itemdef in pairs(minetest.registered_items) do
if (itemdef.groups.not_in_creative_inventory or 0) == 0 then
local all = true
for _, group_name in ipairs(group_names) do
if (itemdef.groups[group_name] or 0) == 0 then
all = false
end
end
if all then table.insert(candidate_items, itemname) end
end
end
local num_candidates = #candidate_items
if num_candidates == 0 then
return {sole = true}
elseif num_candidates == 1 then
return {item = candidate_items[1], sole = true}
end
local is_group = {}
local registered_rep = {}
for _, group_name in ipairs(group_names) do
is_group[group_name] = true
local rep = unified_inventory.registered_group_items[group_name]
if rep then registered_rep[rep] = true end
end
local bestitem = ""
local bestpref = 0
for _, item in ipairs(candidate_items) do
local pref
if registered_rep[item] then
pref = 4
elseif string.sub(item, 1, 8) == "default:" and is_group[string.sub(item, 9)] then
pref = 3
elseif is_group[item:gsub("^[^:]*:", "")] then
pref = 2
else
pref = 1
end
if pref > bestpref or (pref == bestpref and item < bestitem) then
bestitem = item
bestpref = pref
end
end
return {item = bestitem, sole = false}
end
local group_item_cache = {}
function unified_inventory.get_group_item(group_name)
if not group_item_cache[group_name] then
group_item_cache[group_name] = compute_group_item(group_name)
end
return group_item_cache[group_name]
end
|
[u_inv] Use steel ingots as group item for ingots
|
[u_inv] Use steel ingots as group item for ingots
- Fix #480
|
Lua
|
unlicense
|
sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/server-minetestforfun,Coethium/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun
|
a2937a595eafba19bd55c1f0befd9dc33cd109a2
|
lua/filters/fieldfix.lua
|
lua/filters/fieldfix.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/.
--[[
Performs some basic mutations on message Fields - add if not present, override,
remove, rename and parse. New messages will be emitted with a new Type.
The Parse function can be used to extract field data embedded in another field,
ie; in a StatsD bucket name. See Config for more information.
Config:
- msg_type (string, optional, default "fieldfix")
String to set as the new message Type (which will also have
'heka.sandbox.' automatically and unavoidably prefixed)
- payload_keep (bool, default false)
If true, maintain the original Payloads in the new messages.
- fields_if_missing (string, optional)
Space delimited string of Fields to supplement (ie; add if they're not
already present). Field name and value should be delimited with a '='.
- fields_override (string, optional)
Space delimited string of Fields to always ensure exists, overriding
existing values if necessary. Field name and value should be delimited
with a '='.
- fields_remove (string, optional)
Space delimited string of Fields to remove. Only the field name is
required.
- fields_rename (string, optional)
Space delimited string of Fields to rename. Old and new name should be
delimited with a '='.
- fields_parse (string, optional)
Space delimited string of Fields to parse for embedded fields.
- fields_parse_key_delimiter (string, optional, default '._k_')
String to demarcate keys embedded in the Field name
- fields_parse_value_delimiter (string, optional, default '._v_')
String to separate values from keys embedded in the Field name
- fields_parse_prefix (string, optional)
String to prepend to extracted Fields
*Example Heka Configuration*
.. code-block:: ini
[FieldFixFilter]
type = "SandboxFilter"
filename = "lua_filters/fieldfix.lua"
preserve_data = false
[FieldFixFilter.config]
fields_if_missing = "source=myhost target=remotehost"
fields_override = "cluster=wibble"
fields_remove = "product"
* Embedded Field parsing
You're using an existing client library/protocol/input/decoder and you'd like
to send additional data with an event.
By using the 'fields_parse' option, we can extract additional delimited KV
information from one field into their own Heka Fields for further
filtering/encoding/etc.
For example, Heka already has a hypothetical field "bucket_name". You're able
to add additional information to the string from the client:
| name:"bucket_name" type:string value:"deploys._k_dc._v_nyc._k_product._v_wibble"
With a config of 'fields_parse = "bucket_name"', this filter would generate the
following Fields:
:Fields:
| name:"bucket_name" type:string value:"deploys"
| name:"product" type:string value:"wibble"
| name:"dc" type:string value:"nyc"
This becomes useful when transforming aggregated StatsD data for use by a tool
which supports the concept of 'tags' (such as OpenTSDB), for example the
following payload:
deploys._k_product._v_dongles._k_dc._v_nyc._v_:3|ms|@7
The trailing fields_parse_value_delimiter (defaults to "._v_") plays a special
role here. When consuming the last embedded value, the field_parse function
will look either to the end of the string, or until it hits a second value
delimiter.
Anything after that second value delimiter is appended to the leading text
("deploys" in this case). This is useful when using the StatsD aggregator,
which suffixes a string to the bucket name (to denote the stat type, ".mean",
".sum", ".upper" etc.).
--]]
require "string"
require "lpeg"
local msg_type = read_config("msg_type") or "fieldfix"
local payload_keep = read_config("payload_keep")
local add_str = read_config("fields_if_missing") or ""
local override_str = read_config("fields_override") or ""
local remove_str = read_config("fields_remove") or ""
local rename_str = read_config("fields_rename") or ""
local parse_str = read_config("fields_parse") or ""
local tag_key_delimiter = read_config("fields_parse_key_delimiter") or "._k_"
local tag_value_delimiter = read_config("fields_parse_value_delimiter") or "._v_"
local tag_prefix = read_config("fields_parse_prefix") or ""
-- convert a space-delimited string into a table of kv's,
-- either splitting each token on '=', or setting the value
-- to 'true'
local function create_table(str)
local t = {}
if str:len() > 0 then
for f in str:gmatch("[%S]+") do
local k, v = f:match("([%S]+)=([%S]+)")
if k ~= nil then
t[k] = v
else
t[f] = true
end
end
end
return t
end
local function add_tag_prefix(tag)
if tag_prefix then
return tag_prefix .. tag
end
return tag
end
-- build tables
local add = create_table(add_str)
local remove = create_table(remove_str)
local override = create_table(override_str)
local rename = create_table(rename_str)
local parse = create_table(parse_str)
lpeg.locale(lpeg)
-- grammar for parsing embedded fields
local tkd = lpeg.P(tag_key_delimiter)
local tvd = lpeg.P(tag_value_delimiter)
local elem = lpeg.C((1 - (tkd + tvd))^1)
local orig_name = lpeg.Cg((1 - tkd)^1, "orig_name")
local pair = lpeg.Cg(elem / add_tag_prefix * tvd * elem) * tkd^-1
local tags = (tkd * lpeg.Cg(lpeg.Cf(lpeg.Ct("") * pair^0, rawset), "tags"))^0
local trail = (tvd * lpeg.Cg((lpeg.alnum + lpeg.S("-._/"))^0, "trail"))^0
local grammar = lpeg.Ct(orig_name * tags * trail)
function process_message ()
local message = {
Timestamp = read_message("Timestamp"),
Type = msg_type,
EnvVersion = read_message("EnvVersion"),
Fields = {}
}
if payload_keep then message.Payload = read_message("Payload") end
while true do
local typ, name, value, representation, count = read_next_field()
if not typ then break end
-- Parse any Field values
if parse[name] then
local split = grammar:match(value)
value = split.orig_name
if split.trail ~= nil then
value = value .. split.trail
end
if type(split.tags) == "table" then
message.Fields = split.tags
end
end
-- Fields to remove
if remove[name] then
-- Fields to rename
elseif rename[name] then
message.Fields[rename[name]] = value
-- Add untouched
else
message.Fields[name] = value
end
end
-- Fields to supplement
for k,v in pairs(add) do
if not message.Fields[k] then
message.Fields[k] = v
end
end
-- Fields to override
for k,v in pairs(override) do
message.Fields[k] = v
end
inject_message(message)
return 0
end
function timer_event(ns)
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/.
--[[
Performs some basic mutations on message Fields - add if not present, override,
remove, rename and parse. New messages will be emitted with a new Type.
The Parse function can be used to extract field data embedded in another field,
ie; in a StatsD bucket name. See Config for more information.
Config:
- msg_type (string, optional, default "fieldfix")
String to set as the new message Type (which will also have
'heka.sandbox.' automatically and unavoidably prefixed)
- payload_keep (bool, default false)
If true, maintain the original Payloads in the new messages.
- fields_if_missing (string, optional)
Space delimited string of Fields to supplement (ie; add if they're not
already present). Field name and value should be delimited with a '='.
- fields_override (string, optional)
Space delimited string of Fields to always ensure exists, overriding
existing values if necessary. Field name and value should be delimited
with a '='.
- fields_remove (string, optional)
Space delimited string of Fields to remove. Only the field name is
required.
- fields_rename (string, optional)
Space delimited string of Fields to rename. Old and new name should be
delimited with a '='.
*Example Heka Configuration*
.. code-block:: ini
[FieldFixFilter]
type = "SandboxFilter"
filename = "lua_filters/fieldfix.lua"
preserve_data = false
[FieldFixFilter.config]
fields_if_missing = "source=myhost target=remotehost"
fields_override = "cluster=wibble"
fields_remove = "product"
--]]
require "string"
local msg_type = read_config("msg_type") or "fieldfix"
local payload_keep = read_config("payload_keep")
local add_str = read_config("fields_if_missing") or ""
local override_str = read_config("fields_override") or ""
local remove_str = read_config("fields_remove") or ""
local rename_str = read_config("fields_rename") or ""
-- convert a space-delimited string into a table of kv's,
-- either splitting each token on '=', or setting the value
-- to 'true'
local function create_table(str)
local t = {}
if str:len() > 0 then
for f in str:gmatch("[%S]+") do
local k, v = f:match("([%S]+)=([%S]+)")
if k ~= nil then
t[k] = v
else
t[f] = true
end
end
end
return t
end
-- build tables
local add = create_table(add_str)
local remove = create_table(remove_str)
local override = create_table(override_str)
local rename = create_table(rename_str)
function process_message ()
local message = {
Timestamp = read_message("Timestamp"),
Type = msg_type,
EnvVersion = read_message("EnvVersion"),
Fields = {}
}
if payload_keep then message.Payload = read_message("Payload") end
while true do
local typ, name, value, representation, count = read_next_field()
if not typ then break end
-- Fields to remove
if remove[name] then
-- Fields to rename
elseif rename[name] then
message.Fields[rename[name]] = value
-- Add untouched
else
message.Fields[name] = value
end
end
-- Fields to supplement
for k,v in pairs(add) do
if not message.Fields[k] then
message.Fields[k] = v
end
end
-- Fields to override
for k,v in pairs(override) do
message.Fields[k] = v
end
inject_message(message)
return 0
end
function timer_event(ns)
end
|
Moved embedded field parsing into statsd_aggregator
|
Moved embedded field parsing into statsd_aggregator
Having to juggle the statsd-aggregated suffixes alongside embedded kv's was
messy.
|
Lua
|
mpl-2.0
|
hynd/heka-tsutils-plugins,timurb/heka-tsutils-plugins
|
2d0038dbc180db18e1da575fe7696cc0ff3b82fc
|
src/lpeg.lua
|
src/lpeg.lua
|
local lpjit_lpeg = {}
local lpjit = require 'lpjit'
local lpeg = require 'lpeg'
local mt = {}
local compiled = {}
mt.__index = lpjit_lpeg
local function rawWrap(pattern)
local obj = {value = pattern}
if newproxy and debug.setfenv then
-- Lua 5.1 doesn't support __len for tables
local obj2 = newproxy(true)
debug.setmetatable(obj2, mt)
debug.setfenv(obj2, obj)
assert(debug.getfenv(obj2) == obj)
return obj2
else
return setmetatable(obj, mt)
end
end
local function rawUnwrap(obj)
if type(obj) == 'table' then
return obj.value
else
return debug.getfenv(obj).value
end
end
local function wrapPattern(pattern)
if getmetatable(pattern) == mt then
-- already wrapped
return pattern
else
return rawWrap(pattern)
end
end
local function unwrapPattern(obj)
if getmetatable(obj) == mt then
return rawUnwrap(obj)
else
return obj
end
end
local function wrapGenerator(E)
return function(obj, ...)
if type(obj) == 'table' and getmetatable(obj) ~= mt then
-- P { grammar }
-- unwrap all values
local obj2 = {}
for k, v in pairs(obj) do
obj2[k] = unwrapPattern(v)
end
obj = obj2
else
obj = unwrapPattern(obj)
end
return wrapPattern(E(obj, ...))
end
end
for _, E in ipairs {'B', 'S', 'R', 'Cf', 'Cs', 'Cmt', 'Carg',
'Ct', 'P', 'Cc', 'Cp', 'Cg', 'Cb', 'V', 'C'} do
lpjit_lpeg[E] = wrapGenerator(lpeg[E])
end
for _, binop in ipairs {'__unm', '__mul', '__add', '__sub',
'__div', '__pow', '__len'} do
mt[binop] = function(a, b)
a = unwrapPattern(a)
b = unwrapPattern(b)
local f = getmetatable(a)[binop] or
getmetatable(b)[binop]
return wrapPattern(f(a, b))
end
end
function lpjit_lpeg.match(obj, ...)
if not compiled[obj] then
compiled[obj] = lpjit.compile(unwrapPattern(obj))
end
return compiled[obj]:match(...)
end
function lpjit_lpeg.setmaxstack(...)
lpeg.setmaxstack(...)
-- clear cache ot compiled patterns
compiled = {}
end
function lpjit_lpeg.locale(t)
local funcs0 = lpeg.locale()
local funcs = {}
for k, v in pairs(funcs0) do
funcs[k] = wrapPattern(v)
end
if t then
for k, v in pairs(funcs) do
t[k] = v
end
end
return funcs
end
function lpjit_lpeg.version(t)
return "lpjit with lpeg " .. lpeg.version()
end
function lpjit_lpeg.type(obj)
if getmetatable(obj) == mt then
return "pattern"
end
if lpeg.type(obj) then
return "pattern"
end
return nil
end
if lpeg.pcode then
function lpjit_lpeg.pcode(obj)
return lpeg.pcode(unwrapPattern(obj))
end
end
if lpeg.ptree then
function lpjit_lpeg.ptree(obj)
return lpeg.ptree(unwrapPattern(obj))
end
end
return lpjit_lpeg
|
local lpjit_lpeg = {}
local lpjit = require 'lpjit'
local lpeg = require 'lpeg'
local mt = {}
local compiled = {}
mt.__index = lpjit_lpeg
local function rawWrap(pattern)
local obj = {value = pattern}
if newproxy and debug.setfenv then
-- Lua 5.1 doesn't support __len for tables
local obj2 = newproxy(true)
debug.setmetatable(obj2, mt)
debug.setfenv(obj2, obj)
assert(debug.getfenv(obj2) == obj)
return obj2
else
return setmetatable(obj, mt)
end
end
local function rawUnwrap(obj)
if type(obj) == 'table' then
return obj.value
else
return debug.getfenv(obj).value
end
end
local function wrapPattern(pattern)
if getmetatable(pattern) == mt then
-- already wrapped
return pattern
else
return rawWrap(pattern)
end
end
local function unwrapPattern(obj)
if getmetatable(obj) == mt then
return rawUnwrap(obj)
else
return obj
end
end
local function wrapGenerator(E)
return function(obj, ...)
if type(obj) == 'table' and getmetatable(obj) ~= mt then
-- P { grammar }
-- unwrap all values
local obj2 = {}
for k, v in pairs(obj) do
obj2[k] = unwrapPattern(v)
end
obj = obj2
else
obj = unwrapPattern(obj)
end
return wrapPattern(E(obj, ...))
end
end
for _, E in ipairs {'B', 'S', 'R', 'Cf', 'Cs', 'Cmt', 'Carg',
'Ct', 'P', 'Cc', 'Cp', 'Cg', 'Cb', 'V', 'C'} do
lpjit_lpeg[E] = wrapGenerator(lpeg[E])
end
for _, binop in ipairs {'__unm', '__mul', '__add', '__sub',
'__div', '__pow', '__len'} do
mt[binop] = function(a, b)
a = unwrapPattern(a)
b = unwrapPattern(b)
local f = getmetatable(a)[binop] or
getmetatable(b)[binop]
return wrapPattern(f(a, b))
end
end
function lpjit_lpeg.match(obj, ...)
if not compiled[obj] then
compiled[obj] = lpjit.compile(unwrapPattern(obj))
end
return compiled[obj]:match(...)
end
function lpjit_lpeg.setmaxstack(...)
lpeg.setmaxstack(...)
-- clear cache ot compiled patterns
compiled = {}
end
function lpjit_lpeg.locale(t)
local funcs0 = lpeg.locale()
local funcs = t or {}
for k, v in pairs(funcs0) do
funcs[k] = wrapPattern(v)
end
return funcs
end
function lpjit_lpeg.version(t)
return "lpjit with lpeg " .. lpeg.version()
end
function lpjit_lpeg.type(obj)
if getmetatable(obj) == mt then
return "pattern"
end
if lpeg.type(obj) then
return "pattern"
end
return nil
end
if lpeg.pcode then
function lpjit_lpeg.pcode(obj)
return lpeg.pcode(unwrapPattern(obj))
end
end
if lpeg.ptree then
function lpjit_lpeg.ptree(obj)
return lpeg.ptree(unwrapPattern(obj))
end
end
return lpjit_lpeg
|
fix lpeg wrapper, function locale
|
fix lpeg wrapper, function locale
return argument if passed
|
Lua
|
mit
|
starius/lpjit,starius/lpjit
|
0956b327020cf8d64df16a765f7bb3ef6f2791a4
|
mb.lua
|
mb.lua
|
---------------
-- ## A datatype featuring multiple Buffers.
--
-- [Github Page](https://github.com/fhirschmann/vomote)
--
-- @author Fabian Hirschmann <[email protected]>
-- @copyright 2013
-- @license MIT/X11
local Buffer = {}
local MultiBuffer = {}
--- Creates a new buffer.
-- @param size maximum size of the append buffer
function Buffer:new(size)
local new = {}
for k, v in pairs(Buffer) do
new[k] = v
end
new._size = size or 50
new:reset()
return new
end
--- Sets the attribute identified by `name` to `value`.
-- @param name the name of the attribute
-- @param value the value
function Buffer:set(name, value)
self._buffer[name] = value
end
--- Appends a value of an attribute identified by name.
-- @param name the name of the attribute
-- @param value the value
function Buffer:append(name, value)
local tbl = self._buffer[name] or {}
if table.getn(tbl) >= self._size then
-- remove the oldest entry
table.remove(tbl, 1)
-- shift the table indices down by 1
tbl = vomote.util.table.map(function(x)
return x - 1
end, tbl)
end
table.insert(tbl, value)
self._buffer[name] = tbl
end
--- Gets the buffer.
function Buffer:get()
return self._buffer
end
--- Resets the buffer.
function Buffer:reset()
self._buffer = {}
end
--- Creates a new MultiBuffer.
function MultiBuffer:new()
local new = {}
for k, v in pairs(MultiBuffer) do
new[k] = v
end
new._buffers = {}
return new
end
--- Sets the attribute identified by `name` to `value`.
-- @param name the name of the attribute
-- @param value the value
function MultiBuffer:set(name, value)
for _, buffer in pairs(self._buffers) do
buffer:set(name, value)
end
end
--- Appends a value of an attribute identified by name.
-- @param name the name of the attribute
-- @param value the value
function MultiBuffer:append(name, value)
for _, buffer in pairs(self._buffers) do
buffer:append(name, value)
end
end
--- Adds a buffer to this MultiBuffer.
-- @param size maximum size of the buffer
-- @return id of the new buffer
function MultiBuffer:add_buffer(size)
local id = table.getn(self._buffers) + 1
self._buffers[id] = Buffer:new(size)
return id
end
--- Gets a buffer.
-- @param id the id of the buffer to get
function MultiBuffer:get_buffer(id)
return self._buffers[id]
end
return MultiBuffer
|
---------------
-- ## A datatype featuring multiple Buffers.
--
-- [Github Page](https://github.com/fhirschmann/vomote)
--
-- @author Fabian Hirschmann <[email protected]>
-- @copyright 2013
-- @license MIT/X11
local Buffer = {}
local MultiBuffer = {}
--- Creates a new buffer.
-- @param size maximum size of the append buffer
function Buffer:new(size)
local new = {}
for k, v in pairs(Buffer) do
new[k] = v
end
new._size = size or 50
new:reset()
return new
end
--- Sets the attribute identified by `name` to `value`.
-- @param name the name of the attribute
-- @param value the value
function Buffer:set(name, value)
self._buffer[name] = value
end
--- Appends a value of an attribute identified by name.
-- @param name the name of the attribute
-- @param value the value
function Buffer:append(name, value)
local tbl = self._buffer[name] or {}
if table.getn(tbl) >= self._size then
-- remove the oldest entry
table.remove(tbl, 1)
-- TODO: This should be a circular buffer
-- shift table indices down by 1
local tbl2 = {}
for k, v in pairs(tbl) do
tbl2[k - 1] = v
end
tbl = tbl2
end
table.insert(tbl, value)
self._buffer[name] = tbl
end
--- Gets the buffer.
function Buffer:get()
return self._buffer
end
--- Resets the buffer.
function Buffer:reset()
self._buffer = {}
end
--- Creates a new MultiBuffer.
function MultiBuffer:new()
local new = {}
for k, v in pairs(MultiBuffer) do
new[k] = v
end
new._buffers = {}
return new
end
--- Sets the attribute identified by `name` to `value`.
-- @param name the name of the attribute
-- @param value the value
function MultiBuffer:set(name, value)
for _, buffer in pairs(self._buffers) do
buffer:set(name, value)
end
end
--- Appends a value of an attribute identified by name.
-- @param name the name of the attribute
-- @param value the value
function MultiBuffer:append(name, value)
for _, buffer in pairs(self._buffers) do
buffer:append(name, value)
end
end
--- Adds a buffer to this MultiBuffer.
-- @param size maximum size of the buffer
-- @return id of the new buffer
function MultiBuffer:add_buffer(size)
local id = table.getn(self._buffers) + 1
self._buffers[id] = Buffer:new(size)
return id
end
--- Gets a buffer.
-- @param id the id of the buffer to get
function MultiBuffer:get_buffer(id)
return self._buffers[id]
end
return MultiBuffer
|
fixed indices shifting in buffer
|
fixed indices shifting in buffer
|
Lua
|
mit
|
fhirschmann/vocontrol
|
2fc5bc1042d46baa24fb1107a7f0a982dd6c85b0
|
src/websocket/ev_common.lua
|
src/websocket/ev_common.lua
|
local ev = require'ev'
local frame = require'websocket.frame'
local tinsert = table.insert
local tconcat = table.concat
local eps = 2^-40
local detach = function(f,loop)
if ev.Idle then
ev.Idle.new(function(loop,io)
io:stop(loop)
f()
end):start(loop)
else
ev.Timer.new(function(loop,io)
io:stop(loop)
f()
end,eps):start(loop)
end
end
local async_send = function(sock,loop)
assert(sock)
loop = loop or ev.Loop.default
local sock_send = sock.send
local buffer
local index
local callbacks = {}
local send = function(loop,write_io)
local len = #buffer
local sent,err,last = sock_send(sock,buffer,index)
if not sent and err ~= 'timeout' then
write_io:stop(loop)
if callbacks.on_err then
if write_io:is_active() then
callbacks.on_err(err)
else
detach(function()
callbacks.on_err(err)
end,loop)
end
end
elseif sent then
local copy = buffer
buffer = nil
index = nil
write_io:stop(loop)
if callbacks.on_sent then
-- detach calling callbacks.on_sent from current
-- exection if thiis call context is not
-- the send io to let send_async(_,on_sent,_) truely
-- behave async.
if write_io:is_active() then
callbacks.on_sent(copy)
else
detach(function()
callbacks.on_sent(copy)
end,loop)
end
end
else
assert(last < len)
index = last + 1
end
end
local io = ev.IO.new(send,sock:getfd(),ev.WRITE)
local stop = function()
io:stop(loop)
buffer = nil
index = nil
end
local send_async = function(data,on_sent,on_err)
if buffer then
-- a write io is still running
buffer = buffer..data
return
else
buffer = data
end
callbacks.on_sent = on_sent
callbacks.on_err = on_err
if not io:is_active() then
send(loop,io)
if index ~= nil then
io:start(loop)
end
end
end
return send_async,stop
end
local message_io = function(sock,loop,on_message,on_error)
assert(sock)
assert(loop)
assert(on_message)
assert(on_error)
local last
local frames = {}
local first_opcode
assert(sock:getfd() > -1)
local message_io
local dispatch = function(loop,io)
-- could be stopped meanwhile by on_message function
while message_io:is_active() do
local encoded,err,part = sock:receive(100000)
if err then
if err == 'timeout' and #part == 0 then
return
elseif #part == 0 then
if message_io then
message_io:stop(loop)
end
on_error(err,io,sock)
return
end
end
if last then
encoded = last..(encoded or part)
last = nil
else
encoded = encoded or part
end
repeat
local decoded,fin,opcode,rest = frame.decode(encoded)
if decoded then
if not first_opcode then
first_opcode = opcode
end
tinsert(frames,decoded)
encoded = rest
if fin == true then
on_message(tconcat(frames),first_opcode)
frames = {}
first_opcode = nil
end
end
until not decoded
if #encoded > 0 then
last = encoded
end
end
end
message_io = ev.IO.new(dispatch,sock:getfd(),ev.READ)
message_io:start(loop)
-- the might be already data waiting (which will not trigger the IO)
dispatch(loop,message_io)
return message_io
end
return {
async_send = async_send,
message_io = message_io
}
|
local ev = require'ev'
local frame = require'websocket.frame'
local tinsert = table.insert
local tconcat = table.concat
local eps = 2^-40
local detach = function(f,loop)
if ev.Idle then
ev.Idle.new(function(loop,io)
io:stop(loop)
f()
end):start(loop)
else
ev.Timer.new(function(loop,io)
io:stop(loop)
f()
end,eps):start(loop)
end
end
local async_send = function(sock,loop)
assert(sock)
loop = loop or ev.Loop.default
local sock_send = sock.send
local buffer
local index
local callbacks = {}
local send = function(loop,write_io)
local len = #buffer
local sent,err,last = sock_send(sock,buffer,index)
if not sent and err ~= 'timeout' then
write_io:stop(loop)
if callbacks.on_err then
if write_io:is_active() then
callbacks.on_err(err)
else
detach(function()
callbacks.on_err(err)
end,loop)
end
end
elseif sent then
local copy = buffer
buffer = nil
index = nil
write_io:stop(loop)
if callbacks.on_sent then
-- detach calling callbacks.on_sent from current
-- exection if thiis call context is not
-- the send io to let send_async(_,on_sent,_) truely
-- behave async.
if write_io:is_active() then
callbacks.on_sent(copy)
else
-- on_sent is only defined when responding to "on message for close op"
-- so this can happen only once per lifetime of a websocket instance.
-- callbacks.on_sent may be overwritten by a new call to send_async
-- (e.g. due to calling ws:close(...) or ws:send(...))
local on_sent = callbacks.on_sent
detach(function()
on_sent(copy)
end,loop)
end
end
else
assert(last < len)
index = last + 1
end
end
local io = ev.IO.new(send,sock:getfd(),ev.WRITE)
local stop = function()
io:stop(loop)
buffer = nil
index = nil
end
local send_async = function(data,on_sent,on_err)
if buffer then
-- a write io is still running
buffer = buffer..data
return
else
buffer = data
end
callbacks.on_sent = on_sent
callbacks.on_err = on_err
if not io:is_active() then
send(loop,io)
if index ~= nil then
io:start(loop)
end
end
end
return send_async,stop
end
local message_io = function(sock,loop,on_message,on_error)
assert(sock)
assert(loop)
assert(on_message)
assert(on_error)
local last
local frames = {}
local first_opcode
assert(sock:getfd() > -1)
local message_io
local dispatch = function(loop,io)
-- could be stopped meanwhile by on_message function
while message_io:is_active() do
local encoded,err,part = sock:receive(100000)
if err then
if err == 'timeout' and #part == 0 then
return
elseif #part == 0 then
if message_io then
message_io:stop(loop)
end
on_error(err,io,sock)
return
end
end
if last then
encoded = last..(encoded or part)
last = nil
else
encoded = encoded or part
end
repeat
local decoded,fin,opcode,rest = frame.decode(encoded)
if decoded then
if not first_opcode then
first_opcode = opcode
end
tinsert(frames,decoded)
encoded = rest
if fin == true then
on_message(tconcat(frames),first_opcode)
frames = {}
first_opcode = nil
end
end
until not decoded
if #encoded > 0 then
last = encoded
end
end
end
message_io = ev.IO.new(dispatch,sock:getfd(),ev.READ)
message_io:start(loop)
-- the might be already data waiting (which will not trigger the IO)
dispatch(loop,message_io)
return message_io
end
return {
async_send = async_send,
message_io = message_io
}
|
fix simult close
|
fix simult close
keep local of callbacks.on_sent
|
Lua
|
mit
|
OptimusLime/lua-websockets,KSDaemon/lua-websockets,lipp/lua-websockets,enginix/lua-websockets,OptimusLime/lua-websockets,enginix/lua-websockets,lipp/lua-websockets,enginix/lua-websockets,lipp/lua-websockets,KSDaemon/lua-websockets,KSDaemon/lua-websockets,OptimusLime/lua-websockets
|
e667a4c84ab379383317d36d1c6712032c0734bc
|
kong/core/plugins_iterator.lua
|
kong/core/plugins_iterator.lua
|
local responses = require "kong.tools.responses"
local singletons = require "kong.singletons"
local setmetatable = setmetatable
-- Loads a plugin config from the datastore.
-- @return plugin config table or an empty sentinel table in case of a db-miss
local function load_plugin_into_memory(api_id, consumer_id, plugin_name)
local rows, err = singletons.dao.plugins:find_all {
api_id = api_id,
consumer_id = consumer_id,
name = plugin_name
}
if err then
return nil, err
end
if #rows > 0 then
for _, row in ipairs(rows) do
if api_id == row.api_id and consumer_id == row.consumer_id then
return row
end
end
end
-- insert a cached value to not trigger too many DB queries.
return {null = true} -- works because: `.enabled == nil`
end
--- Load the configuration for a plugin entry in the DB.
-- Given an API, a Consumer and a plugin name, retrieve the plugin's
-- configuration if it exists. Results are cached in ngx.dict
-- @param[type=string] api_id ID of the API being proxied.
-- @param[type=string] consumer_id ID of the Consumer making the request (if any).
-- @param[type=stirng] plugin_name Name of the plugin being tested for.
-- @treturn table Plugin retrieved from the cache or database.
local function load_plugin_configuration(api_id, consumer_id, plugin_name)
local plugin_cache_key = singletons.dao.plugins:cache_key(plugin_name,
api_id,
consumer_id)
local plugin, err = singletons.cache:get(plugin_cache_key, nil,
load_plugin_into_memory,
api_id, consumer_id, plugin_name)
if err then
responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
if plugin ~= nil and plugin.enabled then
return plugin.config or {}
end
end
local function get_next(self)
local i = self.i
i = i + 1
local plugin = self.loaded_plugins[i]
if not plugin then
return nil
end
self.i = i
local ctx = self.ctx
-- load the plugin configuration in early phases
if self.access_or_cert_ctx then
local api = self.api
local plugin_configuration
local consumer = ctx.authenticated_consumer
if consumer then
local consumer_id = consumer.id
local schema = plugin.schema
if schema and not schema.no_consumer then
if api then
plugin_configuration = load_plugin_configuration(api.id, consumer_id, plugin.name)
end
if not plugin_configuration then
plugin_configuration = load_plugin_configuration(nil, consumer_id, plugin.name)
end
end
end
if not plugin_configuration then
-- Search API specific, or global
if api then
plugin_configuration = load_plugin_configuration(api.id, nil, plugin.name)
end
if not plugin_configuration then
plugin_configuration = load_plugin_configuration(nil, nil, plugin.name)
end
end
ctx.plugins_for_request[plugin.name] = plugin_configuration
end
-- return the plugin configuration
local plugins_for_request = ctx.plugins_for_request
if plugins_for_request[plugin.name] then
return plugin, plugins_for_request[plugin.name]
end
return get_next(self) -- Load next plugin
end
local plugin_iter_mt = { __call = get_next }
--- Plugins for request iterator.
-- Iterate over the plugin loaded for a request, stored in
-- `ngx.ctx.plugins_for_request`.
-- @param[type=boolean] access_or_cert_ctx Tells if the context
-- is access_by_lua_block. We don't use `ngx.get_phase()` simply because we can
-- avoid it.
-- @treturn function iterator
local function iter_plugins_for_req(loaded_plugins, access_or_cert_ctx)
local ctx = ngx.ctx
if not ctx.plugins_for_request then
ctx.plugins_for_request = {}
end
local plugin_iter_state = {
i = 0,
ctx = ctx,
api = ctx.api,
loaded_plugins = loaded_plugins,
access_or_cert_ctx = access_or_cert_ctx,
}
return setmetatable(plugin_iter_state, plugin_iter_mt)
end
return iter_plugins_for_req
|
local responses = require "kong.tools.responses"
local singletons = require "kong.singletons"
local setmetatable = setmetatable
-- Loads a plugin config from the datastore.
-- @return plugin config table or an empty sentinel table in case of a db-miss
local function load_plugin_into_memory(api_id, consumer_id, plugin_name)
local rows, err = singletons.dao.plugins:find_all {
api_id = api_id,
consumer_id = consumer_id,
name = plugin_name
}
if err then
error(err)
end
if #rows > 0 then
for _, row in ipairs(rows) do
if api_id == row.api_id and consumer_id == row.consumer_id then
return row
end
end
end
return nil
end
--- Load the configuration for a plugin entry in the DB.
-- Given an API, a Consumer and a plugin name, retrieve the plugin's
-- configuration if it exists. Results are cached in ngx.dict
-- @param[type=string] api_id ID of the API being proxied.
-- @param[type=string] consumer_id ID of the Consumer making the request (if any).
-- @param[type=stirng] plugin_name Name of the plugin being tested for.
-- @treturn table Plugin retrieved from the cache or database.
local function load_plugin_configuration(api_id, consumer_id, plugin_name)
local plugin_cache_key = singletons.dao.plugins:cache_key(plugin_name,
api_id,
consumer_id)
local plugin, err = singletons.cache:get(plugin_cache_key, nil,
load_plugin_into_memory,
api_id, consumer_id, plugin_name)
if err then
responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
if plugin ~= nil and plugin.enabled then
return plugin.config or {}
end
end
local function get_next(self)
local i = self.i
i = i + 1
local plugin = self.loaded_plugins[i]
if not plugin then
return nil
end
self.i = i
local ctx = self.ctx
-- load the plugin configuration in early phases
if self.access_or_cert_ctx then
local api = self.api
local plugin_configuration
local consumer = ctx.authenticated_consumer
if consumer then
local consumer_id = consumer.id
local schema = plugin.schema
if schema and not schema.no_consumer then
if api then
plugin_configuration = load_plugin_configuration(api.id, consumer_id, plugin.name)
end
if not plugin_configuration then
plugin_configuration = load_plugin_configuration(nil, consumer_id, plugin.name)
end
end
end
if not plugin_configuration then
-- Search API specific, or global
if api then
plugin_configuration = load_plugin_configuration(api.id, nil, plugin.name)
end
if not plugin_configuration then
plugin_configuration = load_plugin_configuration(nil, nil, plugin.name)
end
end
ctx.plugins_for_request[plugin.name] = plugin_configuration
end
-- return the plugin configuration
local plugins_for_request = ctx.plugins_for_request
if plugins_for_request[plugin.name] then
return plugin, plugins_for_request[plugin.name]
end
return get_next(self) -- Load next plugin
end
local plugin_iter_mt = { __call = get_next }
--- Plugins for request iterator.
-- Iterate over the plugin loaded for a request, stored in
-- `ngx.ctx.plugins_for_request`.
-- @param[type=boolean] access_or_cert_ctx Tells if the context
-- is access_by_lua_block. We don't use `ngx.get_phase()` simply because we can
-- avoid it.
-- @treturn function iterator
local function iter_plugins_for_req(loaded_plugins, access_or_cert_ctx)
local ctx = ngx.ctx
if not ctx.plugins_for_request then
ctx.plugins_for_request = {}
end
local plugin_iter_state = {
i = 0,
ctx = ctx,
api = ctx.api,
loaded_plugins = loaded_plugins,
access_or_cert_ctx = access_or_cert_ctx,
}
return setmetatable(plugin_iter_state, plugin_iter_mt)
end
return iter_plugins_for_req
|
fix(plugins-iter) properly catch errors from the cache callback
|
fix(plugins-iter) properly catch errors from the cache callback
mlcache does not catch errors coming out from a cache callback via the
traditional second return argument (yet). It only catches Lua errors
thrown by `error()`. This fixes a silent failure when such errors
happen in the plugins iterator, causing the HTTP 500 response to not be
sent.
Additionally, we take advantage of mlcache's native miss cache to remove
the need for a nil sentinel when our plugin query is a miss.
From #3078
|
Lua
|
apache-2.0
|
Kong/kong,jebenexer/kong,Kong/kong,Kong/kong,Mashape/kong
|
854d7d32434ef90a2eb2b549f4f0cc78f6e0dbe4
|
nvim/init.lua
|
nvim/init.lua
|
local cmd = vim.cmd -- to execute Vim commands e.g. cmd('pwd')
local fn = vim.fn -- to call Vim functions e.g. fn.bufnr()
local g = vim.g -- a table to access global variables
local opt = vim.opt -- to set options
require('plugins')
require('options')
require('mappings')
require('config.treesitter')
require('config.lualine')
require('config.formatter')
require('config.lspconfig')
require('config.compe')
require('config.telescope')
cmd(
[[
augroup FormatAutogroup
autocmd!
autocmd BufWritePost *.js,*.rs,*.lua FormatWrite
augroup END
]],
true
)
-- via http://stackoverflow.com/questions/2400264/is-it-possible-to-apply-vim-configurations-without-restarting/2400289#2400289 and @nelstrom
cmd([[
augroup AutoSave
autocmd!
autocmd BufWritePost init.lua source $MYVIMRC
augroup END
]])
opt.termguicolors = true
opt.background = 'dark'
cmd('color molokai')
|
local cmd = vim.cmd -- to execute Vim commands e.g. cmd('pwd')
local fn = vim.fn -- to call Vim functions e.g. fn.bufnr()
local g = vim.g -- a table to access global variables
local opt = vim.opt -- to set options
require('plugins')
require('options')
require('mappings')
require('config.treesitter')
require('config.lualine')
require('config.formatter')
require('config.lspconfig')
require('config.compe')
require('config.telescope')
cmd(
[[
augroup FormatAutogroup
autocmd!
autocmd BufWritePost *.js,*.rs,*.lua FormatWrite
augroup END
]],
true
)
opt.termguicolors = true
opt.background = 'dark'
cmd('color molokai')
|
fix: remove auto refresh attempt
|
fix: remove auto refresh attempt
I can't get it to work all the way... and with needing to compile
packages, too, it is just easier to reload manually or restart.
|
Lua
|
mit
|
drmohundro/dotfiles
|
cd42dd08d33b6eee909bd173cacceac8f18c4cfa
|
src/Modules/Game/Server.Main.lua
|
src/Modules/Game/Server.Main.lua
|
-- Name: Server.Main
-- ClassName: Script
local players = game:GetService("Players")
local replicatedStorage = game:GetService("ReplicatedStorage")
local nevermore = require(replicatedStorage:WaitForChild("NevermoreEngine"))
local getRemoteEvent = nevermore.GetRemoteEvent
local import = nevermore.LoadLibrary
local data = import("Data")
local ServerWaveRoad = import("ServerWaveRoad")
--------------------------------------------------------------------------------
-- Startup
--------------------------------------------------------------------------------
--[[
Internal: Configures properties of the game's Services.
There is no publicly available file for this game, so it's best to configure
properties progmatically so that the game is consistent between two place files.
Setting properties this way also opens up the possibility to document why a
property has been set to a certain value.
--]]
local function configureServices()
-- When testing locally, scripts do not have a chance to connect to the
-- PlayerAdded event before your player and character are loaded.
--
-- To combat this, a For loop is used to run onPlayerAdded on all existing
-- players (just one, in this case).
--
-- But this does not account for the already existing character. Another loop
-- could be used to run onCharacterAdded for the character, but loading the
-- character manually ensures that CharacterAdded will fire.
--
-- I suspect the player and character loading before scripts is a side effect
-- of how Nevermore moves everything around before enabling scripts. This used
-- to be an issue with ROBLOX itself, but has since been fixed.
--
-- This is not an issue when running a test server or when online.
players.CharacterAutoLoads = false
end
--[[
Internal: Sets all the properties for the Player and their Character.
playerEntity - An EntityPlayer to set ROBLOX properties for.
--]]
local function configurePlayer(player, character)
local humanoid = character.Humanoid
player.HealthDisplayDistance = 0
player.CameraMaxZoomDistance = 100
humanoid.NameOcclusion = "OccludeAll"
end
--------------------------------------------------------------------------------
-- Player Handling
--------------------------------------------------------------------------------
--[[
Internal: Runs tasks on a newly joined Player
An anonymous function can not be used in this case, because this function has
to run both when PlayerAdded fires and when a Player is in solo mode.
player - The Player that just joined the game.
--]]
local function onPlayerAdded(player)
local joinTime = os.time()
local saveData = data.getDataStore(tostring(player.userId), "PlayerData")
local originalPlayTime = saveData:GetAsync("PlayTime") or 0
local function updatePlayTime()
local sessionTime = os.time() - joinTime
return originalPlayTime + sessionTime
end
player.CharacterAdded:connect(function(character)
configurePlayer(player, character)
end)
players.PlayerRemoving:connect(function(leavingPlayer)
if player == leavingPlayer then
saveData:UpdateAsync("PlayTime", updatePlayTime)
end
end)
player:LoadCharacter()
end
--[[
Internal: Properly loads a Player when testing in solo mode.
When testing locally, scripts do not have a chance to connect to the
PlayerAdded event before your player and character are loaded.
I suspect the player and character loading before scripts is a side effect
of how Nevermore moves everything around before enabling scripts. This used
to be an issue with ROBLOX itself, but has since been fixed.
This is not an issue when running a test server or when online.
--]]
local function handleExistingPlayers()
local playerList = players:GetPlayers()
for _,player in pairs(playerList) do
coroutine.wrap(onPlayerAdded)(player)
end
end
--------------------------------------------------------------------------------
-- Wave World
--------------------------------------------------------------------------------
local function handleWaveWorld()
local skyWaveModel = replicatedStorage.SkyWave
local skyWaveEntered = getRemoteEvent("SkyWaveEntered")
local skyWave = ServerWaveRoad.new(skyWaveModel.TeleportPad)
skyWaveEntered.OnServerEvent:connect(function(player)
skyWave:TransIn(player)
end)
end
--------------------------------------------------------------------------------
-- Initialization
--------------------------------------------------------------------------------
local function initialize()
nevermore.SetRespawnTime(3)
configureServices()
handleExistingPlayers()
handleWaveWorld()
players.PlayerAdded:connect(onPlayerAdded)
end
initialize()
|
-- Name: Server.Main
-- ClassName: Script
local players = game:GetService("Players")
local replicatedStorage = game:GetService("ReplicatedStorage")
local nevermore = require(replicatedStorage:WaitForChild("NevermoreEngine"))
local getRemoteEvent = nevermore.GetRemoteEvent
local import = nevermore.LoadLibrary
local data = import("Data")
local ServerWaveRoad = import("ServerWaveRoad")
--------------------------------------------------------------------------------
-- Startup
--------------------------------------------------------------------------------
--[[
Internal: Configures properties of the game's Services.
There is no publicly available file for this game, so it's best to configure
properties progmatically so that the game is consistent between two place files.
Setting properties this way also opens up the possibility to document why a
property has been set to a certain value.
--]]
local function configureServices()
-- When testing locally, scripts do not have a chance to connect to the
-- PlayerAdded event before your player and character are loaded.
--
-- To combat this, a For loop is used to run onPlayerAdded on all existing
-- players (just one, in this case).
--
-- But this does not account for the already existing character. Another loop
-- could be used to run onCharacterAdded for the character, but loading the
-- character manually ensures that CharacterAdded will fire.
--
-- I suspect the player and character loading before scripts is a side effect
-- of how Nevermore moves everything around before enabling scripts. This used
-- to be an issue with ROBLOX itself, but has since been fixed.
--
-- This is not an issue when running a test server or when online.
players.CharacterAutoLoads = false
end
--[[
Sets all the properties for the Player and their Character.
This should be run inside of a CharacterAdded event that has the Character's
Player in its scope.
Example:
game.Players.PlayerAdded:connect(function(player)
player.CharacterAdded:connect(function(character)
configurePlayer(player, character)
end)
end)
player - The Player that just joined the game.
character - The Player's Character model.
--]]
local function configurePlayer(player, character)
local humanoid = character.Humanoid
player.HealthDisplayDistance = 0
player.CameraMaxZoomDistance = 100
humanoid.NameOcclusion = "OccludeAll"
end
--------------------------------------------------------------------------------
-- Player Handling
--------------------------------------------------------------------------------
--[[
Internal: Runs tasks on a newly joined Player
An anonymous function can not be used in this case, because this function has
to run both when PlayerAdded fires and when a Player is in solo mode.
player - The Player that just joined the game.
--]]
local function onPlayerAdded(player)
local joinTime = os.time()
local saveData = data.getDataStore(tostring(player.userId), "PlayerData")
local originalPlayTime = saveData:GetAsync("PlayTime") or 0
local function updatePlayTime()
local sessionTime = os.time() - joinTime
return originalPlayTime + sessionTime
end
player.CharacterAdded:connect(function(character)
configurePlayer(player, character)
end)
players.PlayerRemoving:connect(function(leavingPlayer)
if player == leavingPlayer then
saveData:UpdateAsync("PlayTime", updatePlayTime)
end
end)
player:LoadCharacter()
end
--[[
Internal: Properly loads a Player when testing in solo mode.
When testing locally, scripts do not have a chance to connect to the
PlayerAdded event before your player and character are loaded.
I suspect the player and character loading before scripts is a side effect
of how Nevermore moves everything around before enabling scripts. This used
to be an issue with ROBLOX itself, but has since been fixed.
This is not an issue when running a test server or when online.
--]]
local function handleExistingPlayers()
local playerList = players:GetPlayers()
for _,player in pairs(playerList) do
coroutine.wrap(onPlayerAdded)(player)
end
end
--------------------------------------------------------------------------------
-- Wave World
--------------------------------------------------------------------------------
local function handleWaveWorld()
local skyWaveModel = replicatedStorage.SkyWave
local skyWaveEntered = getRemoteEvent("SkyWaveEntered")
local skyWave = ServerWaveRoad.new(skyWaveModel.TeleportPad)
skyWaveEntered.OnServerEvent:connect(function(player)
skyWave:TransIn(player)
end)
end
--------------------------------------------------------------------------------
-- Initialization
--------------------------------------------------------------------------------
local function initialize()
nevermore.SetRespawnTime(3)
configureServices()
handleExistingPlayers()
handleWaveWorld()
players.PlayerAdded:connect(onPlayerAdded)
end
initialize()
|
Refactor an old comment
|
Refactor an old comment
This was something I copy/pasted from another project, and I forgot to
change the parameters. That's fixed now, and I also added a usage example.
|
Lua
|
mit
|
VoxelDavid/echo-ridge
|
9727bba51aa772e95c0c1c088454a61400bf592f
|
lib/image_loader.lua
|
lib/image_loader.lua
|
local gm = require 'graphicsmagick'
local ffi = require 'ffi'
local iproc = require 'iproc'
require 'pl'
local image_loader = {}
local clip_eps8 = (1.0 / 255.0) * 0.5 - (1.0e-7 * (1.0 / 255.0) * 0.5)
local clip_eps16 = (1.0 / 65535.0) * 0.5 - (1.0e-7 * (1.0 / 65535.0) * 0.5)
local background_color = 0.5
function image_loader.encode_png(rgb, depth)
depth = depth or 8
rgb = iproc.byte2float(rgb)
if depth < 16 then
rgb = rgb:clone():add(clip_eps8)
rgb[torch.lt(rgb, 0.0)] = 0.0
rgb[torch.gt(rgb, 1.0)] = 1.0
rgb = rgb:mul(255):long():float():div(255)
else
rgb = rgb:clone():add(clip_eps16)
rgb[torch.lt(rgb, 0.0)] = 0.0
rgb[torch.gt(rgb, 1.0)] = 1.0
rgb = rgb:mul(65535):long():float():div(65535)
end
local im
if rgb:size(1) == 4 then -- RGBA
im = gm.Image(rgb, "RGBA", "DHW")
elseif rgb:size(1) == 3 then -- RGB
im = gm.Image(rgb, "RGB", "DHW")
elseif rgb:size(1) == 1 then -- Y
im = gm.Image(rgb, "I", "DHW")
-- im:colorspace("GRAY") -- it does not work
end
return im:depth(depth):format("PNG"):toString(9)
end
function image_loader.save_png(filename, rgb, depth)
depth = depth or 8
local blob = image_loader.encode_png(rgb, depth)
local fp = io.open(filename, "wb")
if not fp then
error("IO error: " .. filename)
end
fp:write(blob)
fp:close()
return true
end
function image_loader.decode_float(blob)
local load_image = function()
local im = gm.Image()
local alpha = nil
local gamma_lcd = 0.454545
im:fromBlob(blob, #blob)
if im:colorspace() == "CMYK" then
im:colorspace("RGB")
end
local gamma = math.floor(im:gamma() * 1000000) / 1000000
if gamma ~= 0 and gamma ~= gamma_lcd then
im:gammaCorrection(gamma / gamma_lcd)
end
-- FIXME: How to detect that a image has an alpha channel?
if blob:sub(1, 4) == "\x89PNG" or blob:sub(1, 3) == "GIF" then
-- split alpha channel
im = im:toTensor('float', 'RGBA', 'DHW')
local sum_alpha = (im[4] - 1.0):sum()
if sum_alpha < 0 then
alpha = im[4]:reshape(1, im:size(2), im:size(3))
-- drop full transparent background
local mask = torch.le(alpha, 0.0)
im[1][mask] = background_color
im[2][mask] = background_color
im[3][mask] = background_color
end
local new_im = torch.FloatTensor(3, im:size(2), im:size(3))
new_im[1]:copy(im[1])
new_im[2]:copy(im[2])
new_im[3]:copy(im[3])
im = new_im
else
im = im:toTensor('float', 'RGB', 'DHW')
end
return {im, alpha, blob}
end
local state, ret = pcall(load_image)
if state then
return ret[1], ret[2], ret[3]
else
return nil, nil, nil
end
end
function image_loader.decode_byte(blob)
local im, alpha
im, alpha, blob = image_loader.decode_float(blob)
if im then
im = iproc.float2byte(im)
-- hmm, alpha does not convert here
return im, alpha, blob
else
return nil, nil, nil
end
end
function image_loader.load_float(file)
local fp = io.open(file, "rb")
if not fp then
error(file .. ": failed to load image")
end
local buff = fp:read("*a")
fp:close()
return image_loader.decode_float(buff)
end
function image_loader.load_byte(file)
local fp = io.open(file, "rb")
if not fp then
error(file .. ": failed to load image")
end
local buff = fp:read("*a")
fp:close()
return image_loader.decode_byte(buff)
end
local function test()
torch.setdefaulttensortype("torch.FloatTensor")
local a = image_loader.load_float("../images/lena.png")
local blob = image_loader.encode_png(a)
local b = image_loader.decode_float(blob)
assert((b - a):abs():sum() == 0)
a = image_loader.load_byte("../images/lena.png")
blob = image_loader.encode_png(a)
b = image_loader.decode_byte(blob)
assert((b:float() - a:float()):abs():sum() == 0)
end
--test()
return image_loader
|
local gm = require 'graphicsmagick'
local ffi = require 'ffi'
local iproc = require 'iproc'
require 'pl'
local image_loader = {}
local clip_eps8 = (1.0 / 255.0) * 0.5 - (1.0e-7 * (1.0 / 255.0) * 0.5)
local clip_eps16 = (1.0 / 65535.0) * 0.5 - (1.0e-7 * (1.0 / 65535.0) * 0.5)
local background_color = 0.5
function image_loader.encode_png(rgb, depth)
depth = depth or 8
rgb = iproc.byte2float(rgb)
if depth < 16 then
rgb = rgb:clone():add(clip_eps8)
rgb[torch.lt(rgb, 0.0)] = 0.0
rgb[torch.gt(rgb, 1.0)] = 1.0
rgb = rgb:mul(255):long():float():div(255)
else
rgb = rgb:clone():add(clip_eps16)
rgb[torch.lt(rgb, 0.0)] = 0.0
rgb[torch.gt(rgb, 1.0)] = 1.0
rgb = rgb:mul(65535):long():float():div(65535)
end
local im
if rgb:size(1) == 4 then -- RGBA
im = gm.Image(rgb, "RGBA", "DHW")
elseif rgb:size(1) == 3 then -- RGB
im = gm.Image(rgb, "RGB", "DHW")
elseif rgb:size(1) == 1 then -- Y
im = gm.Image(rgb, "I", "DHW")
-- im:colorspace("GRAY") -- it does not work
end
return im:depth(depth):format("PNG"):toString(9)
end
function image_loader.save_png(filename, rgb, depth)
depth = depth or 8
local blob = image_loader.encode_png(rgb, depth)
local fp = io.open(filename, "wb")
if not fp then
error("IO error: " .. filename)
end
fp:write(blob)
fp:close()
return true
end
function image_loader.decode_float(blob)
local load_image = function()
local im = gm.Image()
local alpha = nil
local gamma_lcd = 0.454545
im:fromBlob(blob, #blob)
if im:colorspace() == "CMYK" then
im:colorspace("RGB")
end
local gamma = math.floor(im:gamma() * 1000000) / 1000000
if gamma ~= 0 and gamma ~= gamma_lcd then
local cg = gamma / gamma_lcd
im:gammaCorrection(cg, "Red")
im:gammaCorrection(cg, "Blue")
im:gammaCorrection(cg, "Green")
end
-- FIXME: How to detect that a image has an alpha channel?
if blob:sub(1, 4) == "\x89PNG" or blob:sub(1, 3) == "GIF" then
-- split alpha channel
im = im:toTensor('float', 'RGBA', 'DHW')
local sum_alpha = (im[4] - 1.0):sum()
if sum_alpha < 0 then
alpha = im[4]:reshape(1, im:size(2), im:size(3))
-- drop full transparent background
local mask = torch.le(alpha, 0.0)
im[1][mask] = background_color
im[2][mask] = background_color
im[3][mask] = background_color
end
local new_im = torch.FloatTensor(3, im:size(2), im:size(3))
new_im[1]:copy(im[1])
new_im[2]:copy(im[2])
new_im[3]:copy(im[3])
im = new_im
else
im = im:toTensor('float', 'RGB', 'DHW')
end
return {im, alpha, blob}
end
local state, ret = pcall(load_image)
if state then
return ret[1], ret[2], ret[3]
else
return nil, nil, nil
end
end
function image_loader.decode_byte(blob)
local im, alpha
im, alpha, blob = image_loader.decode_float(blob)
if im then
im = iproc.float2byte(im)
-- hmm, alpha does not convert here
return im, alpha, blob
else
return nil, nil, nil
end
end
function image_loader.load_float(file)
local fp = io.open(file, "rb")
if not fp then
error(file .. ": failed to load image")
end
local buff = fp:read("*a")
fp:close()
return image_loader.decode_float(buff)
end
function image_loader.load_byte(file)
local fp = io.open(file, "rb")
if not fp then
error(file .. ": failed to load image")
end
local buff = fp:read("*a")
fp:close()
return image_loader.decode_byte(buff)
end
local function test()
torch.setdefaulttensortype("torch.FloatTensor")
local a = image_loader.load_float("../images/lena.png")
local blob = image_loader.encode_png(a)
local b = image_loader.decode_float(blob)
assert((b - a):abs():sum() == 0)
a = image_loader.load_byte("../images/lena.png")
blob = image_loader.encode_png(a)
b = image_loader.decode_byte(blob)
assert((b:float() - a:float()):abs():sum() == 0)
end
--test()
return image_loader
|
Fix gamma correction
|
Fix gamma correction
|
Lua
|
mit
|
zyhkz/waifu2x,Spitfire1900/upscaler,vitaliylag/waifu2x,nagadomi/waifu2x,higankanshi/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,vitaliylag/waifu2x,zyhkz/waifu2x,Spitfire1900/upscaler,zyhkz/waifu2x,higankanshi/waifu2x,higankanshi/waifu2x,vitaliylag/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x
|
336224ec981337c323c870cc6f68c35c21e3e392
|
Interface/AddOns/RayUI/modules/skins/blizzard/gossip.lua
|
Interface/AddOns/RayUI/modules/skins/blizzard/gossip.lua
|
local R, L, P = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, local
local S = R:GetModule("Skins")
local function LoadSkin()
S:SetBD(GossipFrame)
GossipFrame:DisableDrawLayer("BORDER")
GossipFrameInset:DisableDrawLayer("BORDER")
GossipFrameInsetBg:Hide()
GossipGreetingScrollFrameTop:Hide()
GossipGreetingScrollFrameBottom:Hide()
GossipGreetingScrollFrameMiddle:Hide()
for i = 1, 7 do
select(i, GossipFrame:GetRegions()):Hide()
end
select(19, GossipFrame:GetRegions()):Hide()
GossipGreetingText:SetTextColor(1, 1, 1)
S:ReskinScroll(GossipGreetingScrollFrameScrollBar)
GreetingText:SetTextColor(1, 1, 1)
GreetingText.SetTextColor = R.dummy
S:Reskin(GossipFrameGreetingGoodbyeButton)
S:ReskinClose(GossipFrameCloseButton)
hooksecurefunc("GossipFrameUpdate", function()
for i=1, NUMGOSSIPBUTTONS do
local text = _G["GossipTitleButton" .. i]:GetText()
if text then
text = string.gsub(text,"|cFF0008E8","|cFF0080FF")
_G["GossipTitleButton" .. i]:SetText(text)
end
end
end)
select(18, ItemTextFrame:GetRegions()):Hide()
InboxFrameBg:Hide()
ItemTextScrollFrameMiddle:SetAlpha(0)
ItemTextScrollFrameTop:SetAlpha(0)
ItemTextScrollFrameBottom:SetAlpha(0)
ItemTextPrevPageButton:GetRegions():Hide()
ItemTextNextPageButton:GetRegions():Hide()
ItemTextMaterialTopLeft:SetAlpha(0)
ItemTextMaterialTopRight:SetAlpha(0)
ItemTextMaterialBotLeft:SetAlpha(0)
ItemTextMaterialBotRight:SetAlpha(0)
S:ReskinPortraitFrame(ItemTextFrame, true)
S:ReskinScroll(ItemTextScrollFrameScrollBar)
S:ReskinArrow(ItemTextPrevPageButton, "left")
S:ReskinArrow(ItemTextNextPageButton, "right")
ItemTextPageText:SetTextColor(1, 1, 1)
ItemTextPageText.SetTextColor = R.dummy
NPCFriendshipStatusBar:GetRegions():Hide()
NPCFriendshipStatusBarNotch1:SetTexture(0, 0, 0)
NPCFriendshipStatusBarNotch1:Size(1, 16)
NPCFriendshipStatusBarNotch2:SetTexture(0, 0, 0)
NPCFriendshipStatusBarNotch2:Size(1, 16)
NPCFriendshipStatusBarNotch3:SetTexture(0, 0, 0)
NPCFriendshipStatusBarNotch3:Size(1, 16)
NPCFriendshipStatusBarNotch4:SetTexture(0, 0, 0)
NPCFriendshipStatusBarNotch4:Size(1, 16)
select(7, NPCFriendshipStatusBar:GetRegions()):Hide()
NPCFriendshipStatusBar.icon:SetPoint("TOPLEFT", -30, 7)
NPCFriendshipStatusBar.bd = CreateFrame("Frame", nil, NPCFriendshipStatusBar)
NPCFriendshipStatusBar.bd:SetOutside(nil, 1, 1)
NPCFriendshipStatusBar.bd:SetFrameLevel(NPCFriendshipStatusBar:GetFrameLevel() - 1)
S:CreateBD(NPCFriendshipStatusBar.bd, .25)
end
S:RegisterSkin("RayUI", LoadSkin)
|
local R, L, P = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, local
local S = R:GetModule("Skins")
local function LoadSkin()
S:SetBD(GossipFrame)
GossipFrame:DisableDrawLayer("BORDER")
GossipFrameInset:DisableDrawLayer("BORDER")
GossipFrameInsetBg:Hide()
GossipGreetingScrollFrameTop:Hide()
GossipGreetingScrollFrameBottom:Hide()
GossipGreetingScrollFrameMiddle:Hide()
for i = 1, 7 do
select(i, GossipFrame:GetRegions()):Hide()
end
select(19, GossipFrame:GetRegions()):Hide()
GossipGreetingText:SetTextColor(1, 1, 1)
S:ReskinScroll(GossipGreetingScrollFrameScrollBar)
GreetingText:SetTextColor(1, 1, 1)
GreetingText.SetTextColor = R.dummy
S:Reskin(GossipFrameGreetingGoodbyeButton)
S:ReskinClose(GossipFrameCloseButton)
hooksecurefunc("GossipFrameUpdate", function()
for i=1, NUMGOSSIPBUTTONS do
local text = _G["GossipTitleButton" .. i]:GetText()
if text then
text = string.sub(text, 11) -- remove the color prefix
_G["GossipTitleButton" .. i]:SetText(text)
end
end
end)
select(18, ItemTextFrame:GetRegions()):Hide()
InboxFrameBg:Hide()
ItemTextScrollFrameMiddle:SetAlpha(0)
ItemTextScrollFrameTop:SetAlpha(0)
ItemTextScrollFrameBottom:SetAlpha(0)
ItemTextPrevPageButton:GetRegions():Hide()
ItemTextNextPageButton:GetRegions():Hide()
ItemTextMaterialTopLeft:SetAlpha(0)
ItemTextMaterialTopRight:SetAlpha(0)
ItemTextMaterialBotLeft:SetAlpha(0)
ItemTextMaterialBotRight:SetAlpha(0)
S:ReskinPortraitFrame(ItemTextFrame, true)
S:ReskinScroll(ItemTextScrollFrameScrollBar)
S:ReskinArrow(ItemTextPrevPageButton, "left")
S:ReskinArrow(ItemTextNextPageButton, "right")
ItemTextPageText:SetTextColor(1, 1, 1)
ItemTextPageText.SetTextColor = R.dummy
NPCFriendshipStatusBar:GetRegions():Hide()
NPCFriendshipStatusBarNotch1:SetTexture(0, 0, 0)
NPCFriendshipStatusBarNotch1:Size(1, 16)
NPCFriendshipStatusBarNotch2:SetTexture(0, 0, 0)
NPCFriendshipStatusBarNotch2:Size(1, 16)
NPCFriendshipStatusBarNotch3:SetTexture(0, 0, 0)
NPCFriendshipStatusBarNotch3:Size(1, 16)
NPCFriendshipStatusBarNotch4:SetTexture(0, 0, 0)
NPCFriendshipStatusBarNotch4:Size(1, 16)
select(7, NPCFriendshipStatusBar:GetRegions()):Hide()
NPCFriendshipStatusBar.icon:SetPoint("TOPLEFT", -30, 7)
NPCFriendshipStatusBar.bd = CreateFrame("Frame", nil, NPCFriendshipStatusBar)
NPCFriendshipStatusBar.bd:SetOutside(nil, 1, 1)
NPCFriendshipStatusBar.bd:SetFrameLevel(NPCFriendshipStatusBar:GetFrameLevel() - 1)
S:CreateBD(NPCFriendshipStatusBar.bd, .25)
end
S:RegisterSkin("RayUI", LoadSkin)
|
fix gossip title text color
|
fix gossip title text color
|
Lua
|
mit
|
fgprodigal/RayUI
|
f3f859bfbab635b234c4581068ee376bccfb988b
|
lualib/websocket.lua
|
lualib/websocket.lua
|
local skynet = require "skynet"
local crypt = require "skynet.crypt"
local socket = require "skynet.socket"
local socket_write = socket.write
local socket_read = socket.read
local socket_close = socket.close
local s_format = string.format
local s_pack = string.pack
local s_unpack = string.unpack
local t_pack = table.pack
local t_unpack = table.unpack
local t_concat = table.concat
local GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
local function upgrade_response(key, protocol)
protocol = protocol or ""
if protocol ~= "" then protocol = "Sec-WebSocket-Protocol: "..protocol end
local accept = crypt.base64encode(crypt.sha1(key..GUID))
return s_format("HTTP/1.1 101 Switching Protocols\r\n"..
"Upgrade: websocket\r\n"..
"Connection: Upgrade\r\n"..
"Sec-WebSocket-Accept: %s\r\n"..
"%s\r\n\r\n", accept, protocol)
end
local function readframe(fd)
local data, err = socket_read(fd, 2)
if not data then return 'e', "Read fin, payload len error." end
local fin, len = s_unpack("BB", data)
local opcode, mask = fin & 0xf, len & 0x80 ~= 0
fin = fin & 0x80 ~= 0
len = len & 0x7f
if len == 126 then
data, err = socket_read(fd, 2)
if not data then return 'e', "Read extended payload len error." end
len = s_unpack(">H", data)
elseif len == 127 then
data, err = socket_read(fd, 8)
if not data then return 'e', "Read extended payload len error." end
len = s_unpack(">I8", data)
end
data, err = socket_read(fd, (mask and 4 or me0) + len)
if not data then return 'e', "Read payload error." end
if mask then
-- xor decrypt
mask, data = s_unpack("I4c"..len, data)
data = crypt.xor_str(data, s_pack(">I4", mask))
else
data = s_unpack("c"..len, data)
end
if opcode & 0x8 ~= 0 then
-- control frame (0x8, 0x9, 0xA)
if not fin or len >= 126 then return 'e', "Invalid control frame." end
if opcode == 0x8 then -- close frame
if len < 2 then return 'e', "Invalid close frame, miss code."
elseif len == 2 then return 'c', s_unpack(">H", data)
else return 'c', s_unpack(">Hc"..(len-2), data) end
elseif opcode == 0x9 then -- ping
return 'i', data, len
elseif opcode == 0xa then -- pong
return 'o', data, len
end
else
-- data frame (0x0, 0x1, 0x2)
return 'd', fin, opcode, data, len
end
end
local function writeframe(fd, op, fin, data, sz, mask)
local finbit = fin and 0x80 or 0x0
local maskbit = mask and 0x80 or 0x0
local payload = data
local frame, len
if type(data) == "string" then len = #data
elseif type(data) == "userdata" then len = sz end
if len < 126 then
frame = s_pack("BB", finbit | op, len | maskbit)
elseif len >= 126 and len <= 0xffff then
frame = s_pack(">BBH", finbit | op, 126 | maskbit, len)
else
frame = s_pack(">BBI8", finbit | op, 127 | maskbit, len)
end
if mask then
frame = frame..s_pack(">I4", mask)
payload = crypt.xor_str(data, s_pack(">I4", mask))
end
socket_write(self.fd, frame)
socket_write(self.fd, payload, sz)
end
local websocket = {}
function websocket.upgrade(header, checkorigin, respcb)
local key = header['sec-websocket-key']
if not key then return false, respcb("HTTP/1.1 400 Bad Request.\r\n\r\n") end
if not header['upgrade'] or header['upgrade'] ~= "websocket" or
not header['connection'] or not header['connection']:lower() ~= 'upgrade' or
not header['sec-websocket-version'] or header['sec-websocket-version'] ~= '13'
then
return false, respcb("HTTP/1.1 400 Bad Request.\r\n\r\n")
end
local origin = header["origin"] or header['sec-websocket-origin']
if origin and checkorigin and not checkorigin(origin, header['host']) then
return false, respcb("HTTP/1.1 403 Websocket agency not allowed.\r\n\r\n")
end
local protocol = header['sec-websocket-protocol']
if protocol then
for p in protocol:gmatch('(%a+),*') do
protocol = p
break
end
end
return true, respcb(upgrade_response(key, protocol))
end
function websocket.new(fd, addr, handler, mask)
local ws = setmetatable({
fd = fd,
addr = addr,
handler = handler,
mask = mask,
}, {__index = websocket})
return ws
end
function websocket:read()
local message, size = '', 0
while true do
local S, R1, R2, R3, R4 = readframe(self.fd)
if S == 'e' then self:on_error(R1) return false
elseif S == 'c' then self:on_close(R1, R2) return false
elseif S == 'i' then self:on_ping(R1, R2) return true
elseif S == 'o' then self:on_pong(R1, R2) return true
elseif S == 'd' then
local fin, op, data, sz = R1, R2, R3, R4
message = message..data
size = size + sz
if fin then break end
end
end
self:on_message(message, size)
end
function websocket:writetext(data, fin)
writeframe(self.fd, 0x1, fin or true, data, nil, self.mask)
end
function websocket:writebin(data, sz, fin)
writeframe(self.fd, 0x2, fin or true, data, sz, self.mask)
end
function websocket:ping(data, sz)
writeframe(self.fd, 0x9, true, data, sz, self.mask)
end
function websocket:pong(data, sz)
writeframe(self.fd, 0xa, true, data, sz, self.mask)
end
function websocket:close(code, reason)
local data = s_pack(">H", code)
if reason then data = data..reason end
writeframe(self.fd, 0x8, true, data)
socket_close(self.fd)
if self.handler and self.handler.on_close then
self.handler.on_close(self, code, reason)
end
end
function websocket:on_ping(data, sz)
if self.handler and self.handler.on_ping then
self.handler.on_ping(self, data, sz)
end
end
function websocket:on_pong(ws, data, sz)
if self.handler and self.handler.on_pong then
self.handler.on_pong(self, data, sz)
end
end
function websocket:on_close(code, reason)
socket_close(self.fd)
if self.handler and self.handler.on_close then
self.handler.on_close(self, code, reason)
end
end
function websocket:on_message(data, sz)
if self.handler and self.handler.on_message then
self.handler.on_message(ws, data, sz)
end
end
function websocket:on_error(err)
if self.handler and self.handler.on_error then
self.handler.on_error(ws, err)
end
end
return websocket
|
local skynet = require "skynet"
local crypt = require "skynet.crypt"
local socket = require "skynet.socket"
local socket_write = socket.write
local socket_read = socket.read
local socket_close = socket.close
local s_format = string.format
local s_pack = string.pack
local s_unpack = string.unpack
local s_match = string.match
local t_pack = table.pack
local t_unpack = table.unpack
local t_concat = table.concat
local GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
local function upgrade_response(key, protocol)
protocol = protocol or ""
if protocol ~= "" then protocol = "Sec-WebSocket-Protocol: "..protocol end
local accept = crypt.base64encode(crypt.sha1(key..GUID))
return s_format("HTTP/1.1 101 Switching Protocols\r\n"..
"Upgrade: websocket\r\n"..
"Connection: Upgrade\r\n"..
"Sec-WebSocket-Accept: %s\r\n"..
"%s\r\n\r\n", accept, protocol)
end
local function readframe(fd)
local data, err = socket_read(fd, 2)
if not data then return 'e', "Read fin, payload len error." end
local fin, len = s_unpack("BB", data)
local opcode, mask = fin & 0xf, len & 0x80 ~= 0
fin = fin & 0x80 ~= 0
len = len & 0x7f
if len == 126 then
data, err = socket_read(fd, 2)
if not data then return 'e', "Read extended payload len error." end
len = s_unpack(">H", data)
elseif len == 127 then
data, err = socket_read(fd, 8)
if not data then return 'e', "Read extended payload len error." end
len = s_unpack(">I8", data)
end
data, err = socket_read(fd, (mask and 4 or 0) + len)
if not data then return 'e', "Read payload error." end
if mask then
-- xor decrypt
mask, data = s_unpack("I4c"..len, data)
data = crypt.xor_str(data, s_pack(">I4", mask))
else
data = s_unpack("c"..len, data)
end
if opcode & 0x8 ~= 0 then
-- control frame (0x8, 0x9, 0xA)
if not fin or len >= 126 then return 'e', "Invalid control frame." end
if opcode == 0x8 then -- close frame
if len < 2 then return 'e', "Invalid close frame, miss code."
elseif len == 2 then return 'c', s_unpack(">H", data)
else return 'c', s_unpack(">Hc"..(len-2), data) end
elseif opcode == 0x9 then -- ping
return 'i', data, len
elseif opcode == 0xa then -- pong
return 'o', data, len
end
else
-- data frame (0x0, 0x1, 0x2)
return 'd', fin, opcode, data, len
end
end
local function writeframe(fd, op, fin, data, sz, mask)
local finbit = fin and 0x80 or 0x0
local maskbit = mask and 0x80 or 0x0
local payload = data
local frame, len
if type(data) == "string" then len = #data
elseif type(data) == "userdata" then len = sz end
if len < 126 then
frame = s_pack("BB", finbit | op, len | maskbit)
elseif len >= 126 and len <= 0xffff then
frame = s_pack(">BBH", finbit | op, 126 | maskbit, len)
else
frame = s_pack(">BBI8", finbit | op, 127 | maskbit, len)
end
if mask then
frame = frame..s_pack(">I4", mask)
payload = crypt.xor_str(data, s_pack(">I4", mask))
end
socket_write(self.fd, frame)
socket_write(self.fd, payload, sz)
end
local websocket = {}
function websocket.upgrade(header, checkorigin, respcb)
local key = header['sec-websocket-key']
if not key then return false, respcb("HTTP/1.1 400 Bad Request.\r\n\r\n") end
if not header['upgrade'] or header['upgrade'] ~= "websocket" or
not header['connection'] or not header['connection']:lower() ~= 'upgrade' or
not header['sec-websocket-version'] or header['sec-websocket-version'] ~= '13'
then
return false, respcb("HTTP/1.1 400 Bad Request.\r\n\r\n")
end
local origin = header["origin"] or header['sec-websocket-origin']
if origin and checkorigin and not checkorigin(origin, header['host']) then
return false, respcb("HTTP/1.1 403 Websocket agency not allowed.\r\n\r\n")
end
local protocol = header['sec-websocket-protocol']
if protocol then
protocol = s_match(protocol, '([%a]+),*')
end
return true, respcb(upgrade_response(key, protocol))
end
function websocket.new(fd, addr, handler, mask)
local ws = setmetatable({
fd = fd,
addr = addr,
handler = handler,
mask = mask,
}, {__index = websocket})
return ws
end
function websocket:read()
local message, size = '', 0
while true do
local S, R1, R2, R3, R4 = readframe(self.fd)
if S == 'e' then self:on_error(R1) return false
elseif S == 'c' then self:on_close(R1, R2) return false
elseif S == 'i' then self:on_ping(R1, R2) return true
elseif S == 'o' then self:on_pong(R1, R2) return true
elseif S == 'd' then
local fin, op, data, sz = R1, R2, R3, R4
message = message..data
size = size + sz
if fin then break end
end
end
self:on_message(message, size)
end
function websocket:writetext(data, fin)
writeframe(self.fd, 0x1, fin or true, data, nil, self.mask)
end
function websocket:writebin(data, sz, fin)
writeframe(self.fd, 0x2, fin or true, data, sz, self.mask)
end
function websocket:ping(data, sz)
writeframe(self.fd, 0x9, true, data, sz, self.mask)
end
function websocket:pong(data, sz)
writeframe(self.fd, 0xa, true, data, sz, self.mask)
end
function websocket:close(code, reason)
local data = s_pack(">H", code)
if reason then data = data..reason end
writeframe(self.fd, 0x8, true, data)
socket_close(self.fd)
if self.handler and self.handler.on_close then
self.handler.on_close(self, code, reason)
end
end
function websocket:on_ping(data, sz)
if self.handler and self.handler.on_ping then
self.handler.on_ping(self, data, sz)
end
end
function websocket:on_pong(data, sz)
if self.handler and self.handler.on_pong then
self.handler.on_pong(self, data, sz)
end
end
function websocket:on_close(code, reason)
socket_close(self.fd)
if self.handler and self.handler.on_close then
self.handler.on_close(self, code, reason)
end
end
function websocket:on_message(data, sz)
if self.handler and self.handler.on_message then
self.handler.on_message(self, data, sz)
end
end
function websocket:on_error(err)
if self.handler and self.handler.on_error then
self.handler.on_error(self, err)
end
end
return websocket
|
fix ws
|
fix ws
|
Lua
|
mit
|
korialuo/skynet,korialuo/skynet,korialuo/skynet
|
8f7b49dc636411a329339ab83a97186db59ede67
|
lua/xcb/wrappers/window.lua
|
lua/xcb/wrappers/window.lua
|
--- Wrapper for XCB window
local ffi = require("ffi")
local xcbr = require("xcb.raw")
-- TODO: Configuring
local index = {
--- Destroy the window.
destroy = function(self)
return xcbr.xcb_destroy_window(self.conn, self)
end,
destroy_checked = function(self)
return xcbr.xcb_destroy_window_checked(self.conn, self)
end,
--- Destroy the subwindows.
destroy_subwindows = function(self)
return xcbr.xcb_destroy_subwindows(self.conn, self)
end,
destroy_subwindows_checked = function(self)
return xcbr.xcb_destroy_subwindows_checked(self.conn, self)
end,
--- Reparrent the window
reparent = function(self, parent, x, y)
return xcbr.xcb_reparent_window(self.conn, self, parent, x, y)
end,
reparent_checked = function(self, parent, x, y)
return xcbr.xcb_reparent_window_checked(self.conn, self, parent, x, y)
end,
--- Show the window.
map = function(self)
return xcbr.xcb_map_window(self.conn, self)
end,
map_checked = function(self)
return xcbr.xcb_map_window_checked(self.conn, self)
end,
--- Show the subwindows.
map_subwindows = function(self)
return xcbr.xcb_map_subwindows(self.conn, self)
end,
map_subwindows_checked = function(self)
return xcbr.xcb_map_subwindows_checked(self.conn, self)
end,
--- Hide the window.
unmap = function(self)
return xcbr.xcb_unmap_window(self.conn, self)
end,
unmap_checked = function(self)
return xcbr.xcb_unmap_window_checked(self.conn, self)
end,
--- Hide the subwindows.
unmap_subwindows = function(self)
return xcbr.xcb_unmap_subwindows(self.conn, self)
end,
unmap_subwindows_checked = function(self)
return xcbr.xcb_unmap_subwindows_checked(self.conn, self)
end,
--- Get window attributes.
get_attributes = function(self)
return xcbr.xcb_get_window_attributes(self.conn, self)
end,
get_attributes_unchecked = function(self)
return xcbr.xcb_get_window_attributes_unchecked(self.conn, self)
end,
}
--- Constructor for a window object given a WID.
return function(conn, wid)
setmetatable(wid, {__index=index})
wid.conn = conn
return wid
end
|
--- Wrapper for XCB window
local ffi = require("ffi")
local xcbr = require("xcb.raw")
-- TODO: Configuring
local index = {
--- Destroy the window.
destroy = function(self)
return xcbr.xcb_destroy_window(self.conn, self.wid)
end,
destroy_checked = function(self)
return xcbr.xcb_destroy_window_checked(self.conn, self.wid)
end,
--- Destroy the subwindows.
destroy_subwindows = function(self)
return xcbr.xcb_destroy_subwindows(self.conn, self.wid)
end,
destroy_subwindows_checked = function(self)
return xcbr.xcb_destroy_subwindows_checked(self.conn, self.wid)
end,
--- Reparrent the window
reparent = function(self, parent, x, y)
return xcbr.xcb_reparent_window(self.conn, self.wid, parent, x, y)
end,
reparent_checked = function(self, parent, x, y)
return xcbr.xcb_reparent_window_checked(self.conn, self.wid, parent, x, y)
end,
--- Show the window.
map = function(self)
return xcbr.xcb_map_window(self.conn, self.wid)
end,
map_checked = function(self)
return xcbr.xcb_map_window_checked(self.conn, self.wid)
end,
--- Show the subwindows.
map_subwindows = function(self)
return xcbr.xcb_map_subwindows(self.conn, self.wid)
end,
map_subwindows_checked = function(self)
return xcbr.xcb_map_subwindows_checked(self.conn, self.wid)
end,
--- Hide the window.
unmap = function(self)
return xcbr.xcb_unmap_window(self.conn, self.wid)
end,
unmap_checked = function(self)
return xcbr.xcb_unmap_window_checked(self.conn, self.wid)
end,
--- Hide the subwindows.
unmap_subwindows = function(self)
return xcbr.xcb_unmap_subwindows(self.conn, self.wid)
end,
unmap_subwindows_checked = function(self)
return xcbr.xcb_unmap_subwindows_checked(self.conn, self.wid)
end,
--- Get window attributes.
get_attributes = function(self)
return xcbr.xcb_get_window_attributes(self.conn, self.wid)
end,
get_attributes_unchecked = function(self)
return xcbr.xcb_get_window_attributes_unchecked(self.conn, self.wid)
end,
}
local mt = {
__index=index,
__tostring = function(self)
return "<window "..io.format("0x%08x", self.wid)..">"
end,
}
--- Constructor for a window object given a WID.
return function(conn, wid)
local window = {
["wid"] = wid,
["conn"] = conn,
}
setmetatable(window, mt)
return window
end
|
hopefully fixed xcb.wrappers.window, no test case yet.
|
hopefully fixed xcb.wrappers.window, no test case yet.
|
Lua
|
mit
|
vifino/ljwm
|
c480de455bb210b641b3ce481a05f02a99dbf48e
|
regress/22-client-dtls.lua
|
regress/22-client-dtls.lua
|
#!/bin/sh
_=[[
. "${0%%/*}/regress.sh"
exec runlua "$0" "$@"
]]
require"regress".export".*"
local context = require"openssl.ssl.context"
local function exists(path)
local fh = io.open(path, "r")
if fh then
fh:close()
return true
else
return false
end
end
-- return integer version of openssl(1) command-line tool at path
local function openssl_version(path)
local fh = io.popen(string.format("%s version", path), "r")
local ln = (fh and fh:read()) or ""
if fh then
fh:close()
end
local M, m, p = ln:match("(%d+)%.(%d+)%.(%d+)")
if p then
return (tonumber(M) * 268435456) + (tonumber(m) * 268435456) + (tonumber(p) * 4096)
end
end
-- find most recent version of openssl(1) command-line tool
local function openssl_path()
local paths = check(os.getenv"PATH", "no PATH in environment")
local path = nil
local version = 0
for D in paths:gmatch("[^:]+") do
local tmp_path = D .. "/openssl"
local tmp_version = exists(tmp_path) and openssl_version(tmp_path)
if tmp_version and tmp_version > version then
info("found %s (%x)", tmp_path, tmp_version)
path = tmp_path
version = tmp_version
end
end
return version > 0 and path
end
local function openssl_run(path)
local key, crt = genkey()
local tmpname = os.tmpname()
local tmpfile = check(io.open(tmpname, "w"))
check(tmpfile:write(key:toPEM"private"))
check(tmpfile:write(tostring(crt)))
check(tmpfile:flush())
tmpfile:close()
-- The openssl will exit when stdin closes, so arrange for stdin to
-- disappear when we do. Hack necessary because we can't rely on any
-- process control bindings.
local stdin_r, stdin_w = assert(socket.pair{ cloexec = false })
check(stdin_r:pollfd() < 10 and stdin_w:pollfd() < 10, "descriptors too high (%d, %d)", stdin_r:pollfd(), stdin_w:pollfd())
local stdout_r, stdout_w = assert(socket.pair{ cloexec = false })
check(stdout_r:pollfd() < 10 and stdout_w:pollfd() < 10, "descriptors too high (%d, %d)", stdout_r:pollfd(), stdout_w:pollfd())
local exec = string.format("%s s_server -dtls1 -key %s -cert %s <&%d %d<&- >%d %d<&- 2>&1 &", path, tmpname, tmpname, stdin_r:pollfd(), stdin_w:pollfd(), stdout_w:pollfd(), stdout_r:pollfd())
os.execute(exec)
info("executed `%s`", exec)
stdin_r:close()
stdout_w:close()
stdout_r:xread("*l", 1)
os.remove(tmpname)
end
local main = cqueues.new()
assert(main:wrap(function ()
-- spin up DTLS server using openssl(1) command-line utility
openssl_run(check(openssl_path(), "no openssl command-line utility found"))
-- create client socket
local con = socket.connect{ host="localhost", port=4433, type=socket.SOCK_DGRAM };
check(fileresult(con:starttls(context.new"DTLSv1", 3)))
end):loop())
say"OK"
|
#!/bin/sh
_=[[
. "${0%%/*}/regress.sh"
exec runlua "$0" "$@"
]]
require"regress".export".*"
local context = require"openssl.ssl.context"
local function exists(path)
local fh = io.open(path, "r")
if fh then
fh:close()
return true
else
return false
end
end
-- return integer version of openssl(1) command-line tool at path
local function openssl_version(path)
local fh = io.popen(string.format("%s version", path), "r")
local ln = (fh and fh:read()) or ""
if fh then
fh:close()
end
local M, m, p = ln:match("(%d+)%.(%d+)%.(%d+)")
if p then
return (tonumber(M) * 268435456) + (tonumber(m) * 1048576) + (tonumber(p) * 4096)
end
end
-- find most recent version of openssl(1) command-line tool
local function openssl_path()
local paths = check(os.getenv"PATH", "no PATH in environment")
local path = nil
local version = 0
for D in paths:gmatch("[^:]+") do
local tmp_path = D .. "/openssl"
local tmp_version = exists(tmp_path) and openssl_version(tmp_path)
if tmp_version and tmp_version > version then
info("found %s (%x)", tmp_path, tmp_version)
path = tmp_path
version = tmp_version
end
end
return version > 0 and path
end
local function openssl_run(path)
local key, crt = genkey()
local tmpname = os.tmpname()
local tmpfile = check(io.open(tmpname, "w"))
check(tmpfile:write(key:toPEM"private"))
check(tmpfile:write(tostring(crt)))
check(tmpfile:flush())
tmpfile:close()
-- The openssl will exit when stdin closes, so arrange for stdin to
-- disappear when we do. Hack necessary because we can't rely on any
-- process control bindings.
local stdin_r, stdin_w = assert(socket.pair{ cloexec = false })
check(stdin_r:pollfd() < 10 and stdin_w:pollfd() < 10, "descriptors too high (%d, %d)", stdin_r:pollfd(), stdin_w:pollfd())
local stdout_r, stdout_w = assert(socket.pair{ cloexec = false })
check(stdout_r:pollfd() < 10 and stdout_w:pollfd() < 10, "descriptors too high (%d, %d)", stdout_r:pollfd(), stdout_w:pollfd())
local exec = string.format("exec <&%d %d<&- >%d %d<&-; %s s_server -quiet -dtls1 -key %s -cert %s &", stdin_r:pollfd(), stdin_w:pollfd(), stdout_w:pollfd(), stdout_r:pollfd(), path, tmpname, tmpname)
os.execute(exec)
info("executed `%s`", exec)
stdin_r:close()
stdout_w:close()
-- exit quickly if utility fails, otherwise give 1s to start up
stdout_r:xread("*l", 1)
os.remove(tmpname)
-- don't permit to be garbage collected
_G._stdin_w = stdin_w
end
local main = cqueues.new()
assert(main:wrap(function ()
-- spin up DTLS server using openssl(1) command-line utility
openssl_run(check(openssl_path(), "no openssl command-line utility found"))
-- create client socket
local con = socket.connect{ host="localhost", port=4433, type=socket.SOCK_DGRAM };
check(fileresult(con:starttls(context.new"DTLSv1", 3)))
end):loop())
say"OK"
|
fix openssl version detection bug in 22-client-dtls
|
fix openssl version detection bug in 22-client-dtls
|
Lua
|
mit
|
bigcrush/cqueues,daurnimator/cqueues,wahern/cqueues,wahern/cqueues,daurnimator/cqueues,bigcrush/cqueues
|
ce09dc1301c2f7b2e889fc151c9a5c8490c2a7b6
|
kong/plugins/request-transformer/schema.lua
|
kong/plugins/request-transformer/schema.lua
|
local pl_template = require "pl.template"
local tx = require "pl.tablex"
local typedefs = require "kong.db.schema.typedefs"
local validate_header_name = require("kong.tools.utils").validate_header_name
-- entries must have colons to set the key and value apart
local function check_for_value(entry)
local name, value = entry:match("^([^:]+):*(.-)$")
if not name or not value or value == "" then
return false, "key '" ..name.. "' has no value"
end
local status, res, err = pcall(pl_template.compile, value)
if not status or err then
return false, "value '" .. value ..
"' is not in supported format, error:" ..
(status and res or err)
end
return true
end
local function validate_headers(pair, validate_value)
local name, value = pair:match("^([^:]+):*(.-)$")
if validate_header_name(name) == nil then
return nil, string.format("'%s' is not a valid header", tostring(name))
end
if validate_value then
if validate_header_name(value) == nil then
return nil, string.format("'%s' is not a valid header", tostring(value))
end
end
return true
end
local function validate_colon_headers(pair)
return validate_headers(pair, true)
end
local strings_array = {
type = "array",
default = {},
elements = { type = "string" },
}
local headers_array = {
type = "array",
default = {},
elements = { type = "string", custom_validator = validate_headers },
}
local strings_array_record = {
type = "record",
fields = {
{ body = strings_array },
{ headers = headers_array },
{ querystring = strings_array },
},
}
local colon_strings_array = {
type = "array",
default = {},
elements = { type = "string", custom_validator = check_for_value }
}
local colon_header_value_array = {
type = "array",
default = {},
elements = { type = "string", match = "^[^:]+:.*$", custom_validator = validate_headers },
}
local colon_strings_array_record = {
type = "record",
fields = {
{ body = colon_strings_array },
{ headers = colon_header_value_array },
{ querystring = colon_strings_array },
},
}
local colon_headers_array = {
type = "array",
default = {},
elements = { type = "string", match = "^[^:]+:.*$", custom_validator = validate_colon_headers },
}
local colon_rename_strings_array_record = {
type = "record",
fields = {
{ body = colon_strings_array },
{ headers = colon_headers_array },
{ querystring = colon_strings_array },
},
}
local colon_strings_array_record_plus_uri = tx.deepcopy(colon_strings_array_record)
local uri = { uri = { type = "string" } }
table.insert(colon_strings_array_record_plus_uri.fields, uri)
return {
name = "request-transformer",
fields = {
{ run_on = typedefs.run_on_first },
{ config = {
type = "record",
fields = {
{ http_method = typedefs.http_method },
{ remove = strings_array_record },
{ rename = colon_rename_strings_array_record },
{ replace = colon_strings_array_record_plus_uri },
{ add = colon_strings_array_record },
{ append = colon_strings_array_record },
}
},
},
}
}
|
local pl_template = require "pl.template"
local tx = require "pl.tablex"
local typedefs = require "kong.db.schema.typedefs"
local validate_header_name = require("kong.tools.utils").validate_header_name
-- entries must have colons to set the key and value apart
local function check_for_value(entry)
local name, value = entry:match("^([^:]+):*(.-)$")
if not name or not value or value == "" then
return false, "key '" ..name.. "' has no value"
end
local status, res, err = pcall(pl_template.compile, value)
if not status or err then
return false, "value '" .. value ..
"' is not in supported format, error:" ..
(status and res or err)
end
return true
end
local function validate_headers(pair, validate_value)
local name, value = pair:match("^([^:]+):*(.-)$")
if validate_header_name(name) == nil then
return nil, string.format("'%s' is not a valid header", tostring(name))
end
if validate_value then
if validate_header_name(value) == nil then
return nil, string.format("'%s' is not a valid header", tostring(value))
end
end
return true
end
local function validate_colon_headers(pair)
return validate_headers(pair, true)
end
local strings_array = {
type = "array",
default = {},
elements = { type = "string" },
}
local headers_array = {
type = "array",
default = {},
elements = { type = "string", custom_validator = validate_headers },
}
local strings_array_record = {
type = "record",
fields = {
{ body = strings_array },
{ headers = headers_array },
{ querystring = strings_array },
},
}
local colon_strings_array = {
type = "array",
default = {},
elements = { type = "string", custom_validator = check_for_value }
}
local colon_header_value_array = {
type = "array",
default = {},
elements = { type = "string", match = "^[^:]+:.*$", custom_validator = validate_headers },
}
local colon_strings_array_record = {
type = "record",
fields = {
{ body = colon_strings_array },
{ headers = colon_header_value_array },
{ querystring = colon_strings_array },
},
}
local colon_headers_array = {
type = "array",
default = {},
elements = { type = "string", match = "^[^:]+:.*$", custom_validator = validate_colon_headers },
}
local colon_rename_strings_array_record = {
type = "record",
fields = {
{ body = colon_strings_array },
{ headers = colon_headers_array },
{ querystring = colon_strings_array },
},
}
local colon_strings_array_record_plus_uri = tx.deepcopy(colon_strings_array_record)
local uri = { uri = { type = "string" } }
table.insert(colon_strings_array_record_plus_uri.fields, uri)
return {
name = "request-transformer",
fields = {
{ config = {
type = "record",
fields = {
{ http_method = typedefs.http_method },
{ remove = strings_array_record },
{ rename = colon_rename_strings_array_record },
{ replace = colon_strings_array_record_plus_uri },
{ add = colon_strings_array_record },
{ append = colon_strings_array_record },
}
},
},
}
}
|
fix(request-transformer) remove the `run_on` field from plugin config schema (#11)
|
fix(request-transformer) remove the `run_on` field from plugin config schema (#11)
It is no longer needed as service mesh support is removed from Kong
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
ad22a3295be43156437b2ce602138f77823713e2
|
libs/core/luasrc/model/network/wireless.lua
|
libs/core/luasrc/model/network/wireless.lua
|
--[[
LuCI - Network model - Wireless extension
Copyright 2009 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local pairs, i18n, uci = pairs, luci.i18n, luci.model.uci
local iwi = require "iwinfo"
local utl = require "luci.util"
local uct = require "luci.model.uci.bind"
module "luci.model.network.wireless"
local ub = uct.bind("wireless")
local st, ifs
function init(self, cursor)
cursor:unload("wireless")
cursor:load("wireless")
ub:init(cursor)
st = uci.cursor_state()
ifs = { }
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
local device = s.device or "wlan0"
local state = st:get_all("wireless", s['.name'])
local name = device .. ".network" .. count
ifs[name] = {
idx = count,
name = name,
rawname = state and state.ifname or name,
flags = { },
ipaddrs = { },
ip6addrs = { },
type = "wifi",
network = s.network,
handler = self,
wifi = state or s,
sid = s['.name']
}
end)
end
local function _mode(m)
if m == "ap" then m = "AP"
elseif m == "sta" then m = "Client"
elseif m == "adhoc" then m = "Ad-Hoc"
elseif m == "mesh" then m = "Mesh"
elseif m == "monitor" then m = "Monitor"
end
return m or "Client"
end
function shortname(self, iface)
if iface.dev and iface.dev.wifi then
return "%s %q" %{
i18n.translate(_mode(iface.dev.wifi.mode)),
iface.dev.wifi.ssid or iface.dev.wifi.bssid
or i18n.translate("(hidden)")
}
else
return iface:name()
end
end
function get_i18n(self, iface)
if iface.dev and iface.dev.wifi then
return "%s: %s %q" %{
i18n.translate("Wireless Network"),
i18n.translate(iface.dev.wifi.mode or "Client"),
iface.dev.wifi.ssid or iface.dev.wifi.bssid
or i18n.translate("(hidden)")
}
else
return "%s: %q" %{ i18n.translate("Wireless Network"), iface:name() }
end
end
function rename_network(self, old, new)
local i
for i, _ in pairs(ifs) do
if ifs[i].network == old then
ifs[i].network = new
end
end
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.network == old then
if new then
ub.uci:set("wireless", s['.name'], "network", new)
else
ub.uci:delete("wireless", s['.name'], "network")
end
end
end)
end
function del_network(self, old)
return self:rename_network(old, nil)
end
function find_interfaces(self, iflist, brlist)
local iface
for iface, _ in pairs(ifs) do
iflist[iface] = ifs[iface]
end
end
function ignore_interface(self, iface)
if ifs and ifs[iface] then
return false
else
return iwi.type(iface) and true or false
end
end
function add_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:set("wireless", ifs[iface].sid, "network", net:name())
ifs[iface].network = net:name()
return true
end
return false
end
function del_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:delete("wireless", ifs[iface].sid, "network")
--return true
end
return false
end
return _M
|
--[[
LuCI - Network model - Wireless extension
Copyright 2009 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local pairs, i18n, uci = pairs, luci.i18n, luci.model.uci
local iwi = require "iwinfo"
local utl = require "luci.util"
local uct = require "luci.model.uci.bind"
module "luci.model.network.wireless"
local ub = uct.bind("wireless")
local st, ifs
function init(self, cursor)
cursor:unload("wireless")
cursor:load("wireless")
ub:init(cursor)
st = uci.cursor_state()
ifs = { }
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
local device = s.device or "wlan0"
local state = st:get_all("wireless", s['.name'])
local name = device .. ".network" .. count
ifs[name] = {
idx = count,
name = name,
rawname = state and state.ifname or name,
flags = { },
ipaddrs = { },
ip6addrs = { },
type = "wifi",
network = s.network,
handler = self,
wifi = state or s,
sid = s['.name']
}
end)
end
local function _mode(m)
if m == "ap" then m = "AP"
elseif m == "sta" then m = "Client"
elseif m == "adhoc" then m = "Ad-Hoc"
elseif m == "mesh" then m = "Mesh"
elseif m == "monitor" then m = "Monitor"
elseif m == "wds" then m = "WDS"
end
return m or "Client"
end
function shortname(self, iface)
if iface.dev and iface.dev.wifi then
return "%s %q" %{
i18n.translate(_mode(iface.dev.wifi.mode)),
iface.dev.wifi.ssid or iface.dev.wifi.bssid
or i18n.translate("(hidden)")
}
else
return iface:name()
end
end
function get_i18n(self, iface)
if iface.dev and iface.dev.wifi then
return "%s: %s %q" %{
i18n.translate("Wireless Network"),
i18n.translate(_mode(iface.dev.wifi.mode)),
iface.dev.wifi.ssid or iface.dev.wifi.bssid
or i18n.translate("(hidden)")
}
else
return "%s: %q" %{ i18n.translate("Wireless Network"), iface:name() }
end
end
function rename_network(self, old, new)
local i
for i, _ in pairs(ifs) do
if ifs[i].network == old then
ifs[i].network = new
end
end
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.network == old then
if new then
ub.uci:set("wireless", s['.name'], "network", new)
else
ub.uci:delete("wireless", s['.name'], "network")
end
end
end)
end
function del_network(self, old)
return self:rename_network(old, nil)
end
function find_interfaces(self, iflist, brlist)
local iface
for iface, _ in pairs(ifs) do
iflist[iface] = ifs[iface]
end
end
function ignore_interface(self, iface)
if ifs and ifs[iface] then
return false
else
return iwi.type(iface) and true or false
end
end
function add_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:set("wireless", ifs[iface].sid, "network", net:name())
ifs[iface].network = net:name()
return true
end
return false
end
function del_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:delete("wireless", ifs[iface].sid, "network")
--return true
end
return false
end
return _M
|
libs/core: i18n fixes for wds mode
|
libs/core: i18n fixes for wds mode
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5513 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
|
98b1e8199f1ba9e8e8b43e1a4b1ed26e5e0f145b
|
applications/luci-olsr/luasrc/model/cbi/olsr/olsrd.lua
|
applications/luci-olsr/luasrc/model/cbi/olsr/olsrd.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.fs")
m = Map("olsr", "OLSR")
s = m:section(NamedSection, "general", "olsr")
debug = s:option(ListValue, "DebugLevel")
for i=0, 9 do
debug:value(i)
end
ipv = s:option(ListValue, "IpVersion")
ipv:value("4", "IPv4")
ipv:value("6", "IPv6")
noint = s:option(Flag, "AllowNoInt")
noint.enabled = "yes"
noint.disabled = "no"
s:option(Value, "Pollrate")
tcr = s:option(ListValue, "TcRedundancy")
tcr:value("0", translate("olsr_general_tcredundancy_0"))
tcr:value("1", translate("olsr_general_tcredundancy_1"))
tcr:value("2", translate("olsr_general_tcredundancy_2"))
s:option(Value, "MprCoverage")
lql = s:option(ListValue, "LinkQualityLevel")
lql:value("0", translate("disable"))
lql:value("1", translate("olsr_general_linkqualitylevel_1"))
lql:value("2", translate("olsr_general_linkqualitylevel_2"))
lqfish = s:option(Flag, "LinkQualityFishEye")
s:option(Value, "LinkQualityWinSize")
s:option(Value, "LinkQualityDijkstraLimit")
hyst = s:option(Flag, "UseHysteresis")
hyst.enabled = "yes"
hyst.disabled = "no"
i = m:section(TypedSection, "Interface", translate("interfaces"))
i.anonymous = true
i.addremove = true
i.dynamic = true
network = i:option(ListValue, "Interface", translate("network"))
network:value("")
luci.model.uci.foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
if section.type and section.type == "bridge" then
network:value("br-"..section[".name"],section[".name"])
else
network:value(section[".name"])
end
end
end)
i:option(Value, "HelloInterval")
i:option(Value, "HelloValidityTime")
i:option(Value, "TcInterval")
i:option(Value, "TcValidityTime")
i:option(Value, "MidInterval")
i:option(Value, "MidValidityTime")
i:option(Value, "HnaInterval")
i:option(Value, "HnaValidityTime")
p = m:section(TypedSection, "LoadPlugin")
p.addremove = true
p.dynamic = true
lib = p:option(ListValue, "Library", translate("library"))
lib:value("")
for k, v in pairs(luci.fs.dir("/usr/lib")) do
if v:sub(1, 6) == "olsrd_" then
lib:value(v)
end
end
for i, sect in ipairs({ "Hna4", "Hna6" }) do
hna = m:section(TypedSection, sect)
hna.addremove = true
hna.anonymous = true
net = hna:option(Value, "NetAddr")
msk = hna:option(Value, "Prefix")
end
ipc = m:section(NamedSection, "IpcConnect")
conns = ipc:option(Value, "MaxConnections")
conns.isInteger = true
nets = ipc:option(Value, "Net")
nets.optional = true
hosts = ipc:option(Value, "Host")
hosts.optional = true
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.fs")
m = Map("olsr", "OLSR")
s = m:section(NamedSection, "general", "olsr")
debug = s:option(ListValue, "DebugLevel")
for i=0, 9 do
debug:value(i)
end
ipv = s:option(ListValue, "IpVersion")
ipv:value("4", "IPv4")
ipv:value("6", "IPv6")
noint = s:option(Flag, "AllowNoInt")
noint.enabled = "yes"
noint.disabled = "no"
s:option(Value, "Pollrate")
tcr = s:option(ListValue, "TcRedundancy")
tcr:value("0", translate("olsr_general_tcredundancy_0"))
tcr:value("1", translate("olsr_general_tcredundancy_1"))
tcr:value("2", translate("olsr_general_tcredundancy_2"))
s:option(Value, "MprCoverage")
lql = s:option(ListValue, "LinkQualityLevel")
lql:value("0", translate("disable"))
lql:value("1", translate("olsr_general_linkqualitylevel_1"))
lql:value("2", translate("olsr_general_linkqualitylevel_2"))
lqfish = s:option(Flag, "LinkQualityFishEye")
s:option(Value, "LinkQualityWinSize")
s:option(Value, "LinkQualityDijkstraLimit")
hyst = s:option(Flag, "UseHysteresis")
hyst.enabled = "yes"
hyst.disabled = "no"
i = m:section(TypedSection, "Interface", translate("interfaces"))
i.anonymous = true
i.addremove = true
i.dynamic = true
network = i:option(ListValue, "Interface", translate("network"))
network:value("")
luci.model.uci.foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
network:value(section[".name"])
end
end)
i:option(Value, "HelloInterval")
i:option(Value, "HelloValidityTime")
i:option(Value, "TcInterval")
i:option(Value, "TcValidityTime")
i:option(Value, "MidInterval")
i:option(Value, "MidValidityTime")
i:option(Value, "HnaInterval")
i:option(Value, "HnaValidityTime")
p = m:section(TypedSection, "LoadPlugin")
p.addremove = true
p.dynamic = true
lib = p:option(ListValue, "Library", translate("library"))
lib:value("")
for k, v in pairs(luci.fs.dir("/usr/lib")) do
if v:sub(1, 6) == "olsrd_" then
lib:value(v)
end
end
for i, sect in ipairs({ "Hna4", "Hna6" }) do
hna = m:section(TypedSection, sect)
hna.addremove = true
hna.anonymous = true
net = hna:option(Value, "NetAddr")
msk = hna:option(Value, "Prefix")
end
ipc = m:section(NamedSection, "IpcConnect")
conns = ipc:option(Value, "MaxConnections")
conns.isInteger = true
nets = ipc:option(Value, "Net")
nets.optional = true
hosts = ipc:option(Value, "Host")
hosts.optional = true
return m
|
Revert "* luci/olsr: fix names of interfaces with type bridge"
|
Revert "* luci/olsr: fix names of interfaces with type bridge"
This reverts commit 500499c2a0d7c5eeeddb621a8b96fad10523485b.
|
Lua
|
apache-2.0
|
cappiewu/luci,jorgifumi/luci,Hostle/openwrt-luci-multi-user,cappiewu/luci,nwf/openwrt-luci,Wedmer/luci,teslamint/luci,oyido/luci,openwrt-es/openwrt-luci,Sakura-Winkey/LuCI,male-puppies/luci,joaofvieira/luci,Noltari/luci,jorgifumi/luci,Hostle/openwrt-luci-multi-user,tobiaswaldvogel/luci,palmettos/cnLuCI,MinFu/luci,NeoRaider/luci,palmettos/test,wongsyrone/luci-1,deepak78/new-luci,lcf258/openwrtcn,palmettos/cnLuCI,ReclaimYourPrivacy/cloak-luci,nmav/luci,bright-things/ionic-luci,remakeelectric/luci,bittorf/luci,cappiewu/luci,openwrt/luci,oneru/luci,keyidadi/luci,urueedi/luci,aa65535/luci,Wedmer/luci,teslamint/luci,artynet/luci,cshore/luci,mumuqz/luci,thesabbir/luci,jlopenwrtluci/luci,lbthomsen/openwrt-luci,slayerrensky/luci,NeoRaider/luci,zhaoxx063/luci,nwf/openwrt-luci,nmav/luci,daofeng2015/luci,nwf/openwrt-luci,cshore/luci,teslamint/luci,nmav/luci,artynet/luci,keyidadi/luci,kuoruan/lede-luci,zhaoxx063/luci,jorgifumi/luci,oyido/luci,joaofvieira/luci,florian-shellfire/luci,opentechinstitute/luci,jlopenwrtluci/luci,dwmw2/luci,oneru/luci,kuoruan/lede-luci,RuiChen1113/luci,openwrt-es/openwrt-luci,dwmw2/luci,aircross/OpenWrt-Firefly-LuCI,palmettos/test,kuoruan/luci,thess/OpenWrt-luci,fkooman/luci,male-puppies/luci,schidler/ionic-luci,Noltari/luci,kuoruan/luci,tobiaswaldvogel/luci,db260179/openwrt-bpi-r1-luci,schidler/ionic-luci,LuttyYang/luci,maxrio/luci981213,981213/luci-1,cshore/luci,artynet/luci,hnyman/luci,oyido/luci,Sakura-Winkey/LuCI,lcf258/openwrtcn,981213/luci-1,joaofvieira/luci,kuoruan/lede-luci,openwrt-es/openwrt-luci,palmettos/cnLuCI,Kyklas/luci-proto-hso,zhaoxx063/luci,shangjiyu/luci-with-extra,lcf258/openwrtcn,aircross/OpenWrt-Firefly-LuCI,ollie27/openwrt_luci,Hostle/openwrt-luci-multi-user,keyidadi/luci,Kyklas/luci-proto-hso,kuoruan/luci,Wedmer/luci,urueedi/luci,lbthomsen/openwrt-luci,slayerrensky/luci,forward619/luci,Noltari/luci,tobiaswaldvogel/luci,forward619/luci,Noltari/luci,schidler/ionic-luci,jlopenwrtluci/luci,nwf/openwrt-luci,RuiChen1113/luci,nmav/luci,aa65535/luci,Hostle/openwrt-luci-multi-user,ReclaimYourPrivacy/cloak-luci,keyidadi/luci,oyido/luci,male-puppies/luci,maxrio/luci981213,marcel-sch/luci,cappiewu/luci,marcel-sch/luci,lbthomsen/openwrt-luci,nwf/openwrt-luci,thess/OpenWrt-luci,ollie27/openwrt_luci,thesabbir/luci,jchuang1977/luci-1,zhaoxx063/luci,ff94315/luci-1,jchuang1977/luci-1,tobiaswaldvogel/luci,palmettos/test,Wedmer/luci,artynet/luci,cshore/luci,Sakura-Winkey/LuCI,zhaoxx063/luci,RuiChen1113/luci,obsy/luci,wongsyrone/luci-1,Sakura-Winkey/LuCI,palmettos/test,remakeelectric/luci,dwmw2/luci,kuoruan/lede-luci,RedSnake64/openwrt-luci-packages,hnyman/luci,maxrio/luci981213,schidler/ionic-luci,keyidadi/luci,jchuang1977/luci-1,cshore-firmware/openwrt-luci,openwrt/luci,shangjiyu/luci-with-extra,kuoruan/luci,Sakura-Winkey/LuCI,opentechinstitute/luci,palmettos/test,harveyhu2012/luci,david-xiao/luci,daofeng2015/luci,david-xiao/luci,cshore-firmware/openwrt-luci,thess/OpenWrt-luci,kuoruan/lede-luci,artynet/luci,bright-things/ionic-luci,joaofvieira/luci,deepak78/new-luci,remakeelectric/luci,hnyman/luci,aircross/OpenWrt-Firefly-LuCI,rogerpueyo/luci,shangjiyu/luci-with-extra,david-xiao/luci,MinFu/luci,openwrt-es/openwrt-luci,Wedmer/luci,daofeng2015/luci,Wedmer/luci,aa65535/luci,obsy/luci,shangjiyu/luci-with-extra,Noltari/luci,hnyman/luci,dwmw2/luci,joaofvieira/luci,wongsyrone/luci-1,wongsyrone/luci-1,thess/OpenWrt-luci,981213/luci-1,cappiewu/luci,florian-shellfire/luci,mumuqz/luci,Hostle/luci,lbthomsen/openwrt-luci,thesabbir/luci,ff94315/luci-1,ollie27/openwrt_luci,aa65535/luci,hnyman/luci,db260179/openwrt-bpi-r1-luci,LazyZhu/openwrt-luci-trunk-mod,sujeet14108/luci,RedSnake64/openwrt-luci-packages,Hostle/luci,cshore-firmware/openwrt-luci,deepak78/new-luci,artynet/luci,urueedi/luci,maxrio/luci981213,oyido/luci,oneru/luci,aircross/OpenWrt-Firefly-LuCI,maxrio/luci981213,marcel-sch/luci,Wedmer/luci,chris5560/openwrt-luci,LuttyYang/luci,openwrt-es/openwrt-luci,ollie27/openwrt_luci,db260179/openwrt-bpi-r1-luci,taiha/luci,RedSnake64/openwrt-luci-packages,mumuqz/luci,bright-things/ionic-luci,openwrt/luci,taiha/luci,ollie27/openwrt_luci,teslamint/luci,jchuang1977/luci-1,taiha/luci,maxrio/luci981213,tobiaswaldvogel/luci,sujeet14108/luci,thess/OpenWrt-luci,jorgifumi/luci,openwrt/luci,NeoRaider/luci,Noltari/luci,RuiChen1113/luci,ReclaimYourPrivacy/cloak-luci,wongsyrone/luci-1,oneru/luci,fkooman/luci,marcel-sch/luci,Sakura-Winkey/LuCI,rogerpueyo/luci,harveyhu2012/luci,tobiaswaldvogel/luci,wongsyrone/luci-1,bittorf/luci,bright-things/ionic-luci,LazyZhu/openwrt-luci-trunk-mod,dismantl/luci-0.12,palmettos/test,MinFu/luci,thess/OpenWrt-luci,urueedi/luci,Kyklas/luci-proto-hso,tobiaswaldvogel/luci,ff94315/luci-1,bittorf/luci,forward619/luci,forward619/luci,david-xiao/luci,jorgifumi/luci,LuttyYang/luci,jlopenwrtluci/luci,Kyklas/luci-proto-hso,zhaoxx063/luci,keyidadi/luci,jorgifumi/luci,ollie27/openwrt_luci,lcf258/openwrtcn,forward619/luci,lcf258/openwrtcn,male-puppies/luci,sujeet14108/luci,wongsyrone/luci-1,schidler/ionic-luci,slayerrensky/luci,nmav/luci,chris5560/openwrt-luci,mumuqz/luci,lbthomsen/openwrt-luci,jlopenwrtluci/luci,sujeet14108/luci,openwrt/luci,shangjiyu/luci-with-extra,LuttyYang/luci,981213/luci-1,ollie27/openwrt_luci,db260179/openwrt-bpi-r1-luci,daofeng2015/luci,dismantl/luci-0.12,thesabbir/luci,florian-shellfire/luci,dismantl/luci-0.12,Kyklas/luci-proto-hso,marcel-sch/luci,cshore-firmware/openwrt-luci,oyido/luci,LazyZhu/openwrt-luci-trunk-mod,kuoruan/lede-luci,LazyZhu/openwrt-luci-trunk-mod,NeoRaider/luci,kuoruan/lede-luci,ollie27/openwrt_luci,fkooman/luci,male-puppies/luci,thesabbir/luci,cshore-firmware/openwrt-luci,981213/luci-1,deepak78/new-luci,cappiewu/luci,LazyZhu/openwrt-luci-trunk-mod,tcatm/luci,david-xiao/luci,obsy/luci,db260179/openwrt-bpi-r1-luci,chris5560/openwrt-luci,teslamint/luci,slayerrensky/luci,taiha/luci,lbthomsen/openwrt-luci,urueedi/luci,Wedmer/luci,bright-things/ionic-luci,aircross/OpenWrt-Firefly-LuCI,openwrt/luci,dismantl/luci-0.12,tobiaswaldvogel/luci,marcel-sch/luci,dismantl/luci-0.12,opentechinstitute/luci,jlopenwrtluci/luci,tcatm/luci,shangjiyu/luci-with-extra,kuoruan/luci,bittorf/luci,zhaoxx063/luci,981213/luci-1,joaofvieira/luci,tcatm/luci,palmettos/cnLuCI,wongsyrone/luci-1,mumuqz/luci,bright-things/ionic-luci,florian-shellfire/luci,thess/OpenWrt-luci,db260179/openwrt-bpi-r1-luci,teslamint/luci,urueedi/luci,rogerpueyo/luci,nmav/luci,urueedi/luci,oneru/luci,aircross/OpenWrt-Firefly-LuCI,forward619/luci,marcel-sch/luci,florian-shellfire/luci,rogerpueyo/luci,slayerrensky/luci,ReclaimYourPrivacy/cloak-luci,taiha/luci,LazyZhu/openwrt-luci-trunk-mod,rogerpueyo/luci,kuoruan/luci,jorgifumi/luci,Kyklas/luci-proto-hso,bright-things/ionic-luci,nmav/luci,lcf258/openwrtcn,cshore-firmware/openwrt-luci,artynet/luci,dwmw2/luci,chris5560/openwrt-luci,thess/OpenWrt-luci,schidler/ionic-luci,oyido/luci,cappiewu/luci,ff94315/luci-1,remakeelectric/luci,nwf/openwrt-luci,slayerrensky/luci,Hostle/openwrt-luci-multi-user,artynet/luci,tcatm/luci,obsy/luci,lcf258/openwrtcn,tcatm/luci,teslamint/luci,forward619/luci,nwf/openwrt-luci,ReclaimYourPrivacy/cloak-luci,hnyman/luci,Hostle/luci,remakeelectric/luci,981213/luci-1,NeoRaider/luci,fkooman/luci,cshore-firmware/openwrt-luci,male-puppies/luci,cshore-firmware/openwrt-luci,chris5560/openwrt-luci,RedSnake64/openwrt-luci-packages,deepak78/new-luci,schidler/ionic-luci,david-xiao/luci,forward619/luci,opentechinstitute/luci,harveyhu2012/luci,remakeelectric/luci,keyidadi/luci,nmav/luci,ff94315/luci-1,jlopenwrtluci/luci,dismantl/luci-0.12,RedSnake64/openwrt-luci-packages,ReclaimYourPrivacy/cloak-luci,opentechinstitute/luci,dwmw2/luci,lcf258/openwrtcn,kuoruan/luci,LuttyYang/luci,lbthomsen/openwrt-luci,bittorf/luci,cshore/luci,RuiChen1113/luci,marcel-sch/luci,sujeet14108/luci,RedSnake64/openwrt-luci-packages,nmav/luci,deepak78/new-luci,sujeet14108/luci,lcf258/openwrtcn,NeoRaider/luci,teslamint/luci,fkooman/luci,jchuang1977/luci-1,tcatm/luci,taiha/luci,LuttyYang/luci,mumuqz/luci,bittorf/luci,keyidadi/luci,slayerrensky/luci,david-xiao/luci,cshore/luci,Sakura-Winkey/LuCI,Sakura-Winkey/LuCI,LuttyYang/luci,sujeet14108/luci,Noltari/luci,ff94315/luci-1,daofeng2015/luci,opentechinstitute/luci,NeoRaider/luci,bittorf/luci,taiha/luci,aa65535/luci,ff94315/luci-1,bittorf/luci,maxrio/luci981213,Hostle/luci,remakeelectric/luci,Noltari/luci,slayerrensky/luci,harveyhu2012/luci,thesabbir/luci,aircross/OpenWrt-Firefly-LuCI,sujeet14108/luci,palmettos/cnLuCI,db260179/openwrt-bpi-r1-luci,fkooman/luci,obsy/luci,MinFu/luci,tcatm/luci,palmettos/cnLuCI,jorgifumi/luci,hnyman/luci,MinFu/luci,jchuang1977/luci-1,Hostle/openwrt-luci-multi-user,male-puppies/luci,david-xiao/luci,hnyman/luci,jlopenwrtluci/luci,Noltari/luci,harveyhu2012/luci,LuttyYang/luci,chris5560/openwrt-luci,maxrio/luci981213,palmettos/test,kuoruan/lede-luci,jchuang1977/luci-1,schidler/ionic-luci,shangjiyu/luci-with-extra,db260179/openwrt-bpi-r1-luci,palmettos/cnLuCI,openwrt-es/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,taiha/luci,daofeng2015/luci,florian-shellfire/luci,MinFu/luci,RedSnake64/openwrt-luci-packages,lcf258/openwrtcn,chris5560/openwrt-luci,kuoruan/luci,oyido/luci,dwmw2/luci,cappiewu/luci,Hostle/luci,Hostle/openwrt-luci-multi-user,MinFu/luci,Hostle/luci,ReclaimYourPrivacy/cloak-luci,zhaoxx063/luci,RuiChen1113/luci,mumuqz/luci,artynet/luci,obsy/luci,Hostle/openwrt-luci-multi-user,rogerpueyo/luci,lbthomsen/openwrt-luci,Hostle/luci,aa65535/luci,palmettos/test,LazyZhu/openwrt-luci-trunk-mod,nwf/openwrt-luci,obsy/luci,MinFu/luci,florian-shellfire/luci,joaofvieira/luci,shangjiyu/luci-with-extra,NeoRaider/luci,jchuang1977/luci-1,RuiChen1113/luci,rogerpueyo/luci,deepak78/new-luci,rogerpueyo/luci,cshore/luci,thesabbir/luci,obsy/luci,fkooman/luci,dwmw2/luci,chris5560/openwrt-luci,Hostle/luci,openwrt/luci,remakeelectric/luci,opentechinstitute/luci,urueedi/luci,aa65535/luci,harveyhu2012/luci,dismantl/luci-0.12,bright-things/ionic-luci,joaofvieira/luci,deepak78/new-luci,opentechinstitute/luci,ReclaimYourPrivacy/cloak-luci,openwrt-es/openwrt-luci,oneru/luci,harveyhu2012/luci,mumuqz/luci,tcatm/luci,florian-shellfire/luci,oneru/luci,openwrt/luci,palmettos/cnLuCI,oneru/luci,Kyklas/luci-proto-hso,RuiChen1113/luci,aa65535/luci,thesabbir/luci,daofeng2015/luci,ff94315/luci-1,cshore/luci,openwrt-es/openwrt-luci,fkooman/luci,male-puppies/luci,daofeng2015/luci
|
30e41a5a014e2cbd52feb3288cd1d8e99e254639
|
accounts/server/accounts.lua
|
accounts/server/accounts.lua
|
local _get = get
function get( id )
return exports.database:query_single( "SELECT * FROM `accounts` WHERE `id` = ?", id )
end
function new( username, password )
return exports.database:insert_id( "INSERT INTO `accounts` (`username`, `password`) VALUES (?, ?)", username, exports.security:hashString( password ) )
end
function login( player, username, password )
if ( getElementType( player ) ~= "player" ) then
return false
end
local account = exports.database:query_single( "SELECT * FROM `accounts` WHERE `username` = ? AND `password` = ?", username, exports.security:hashString( password ) )
if ( account ) then
exports.database:execute( "UPDATE `accounts` SET `last_login` = NOW( ) WHERE `id` = ?", account.id )
exports.security:modifyElementData( player, "database:id", account.id, false )
exports.security:modifyElementData( player, "account:username", account.username, true )
exports.security:modifyElementData( player, "account:level", account.level, true )
exports.security:modifyElementData( player, "account:duty", true, true )
exports.security:modifyElementData( player, "player:name", getPlayerName( player ), true )
triggerClientEvent( player, "accounts:onLogin", player )
triggerClientEvent( player, "admin:showHUD", player )
return true
end
return false
end
function logout( player )
characterSelection( player )
exports.database:execute( "UPDATE `accounts` SET `last_action` = NOW( ) WHERE `id` = ?", exports.common:getAccountID( player ) )
setPlayerName( player, getElementData( player, "player:name" ) )
removeElementData( player, "database:id" )
removeElementData( player, "account:username" )
removeElementData( player, "account:level" )
removeElementData( player, "account:duty" )
removeElementData( player, "player:name" )
triggerClientEvent( player, "superman:stop", player )
spawnPlayer( player, 0, 0, 0 )
setElementDimension( player, 6000 )
setCameraMatrix( player, 0, 0, 100, 100, 100, 100 )
triggerClientEvent( player, "accounts:onLogout.characters", player )
triggerClientEvent( player, "accounts:onLogout.accounts", player )
triggerClientEvent( player, "admin:hideHUD", player )
end
function register( username, password )
local query = exports.database:query_single( "SELECT NULL FROM `accounts` WHERE `username` = ?", username )
if ( not query ) then
local accountID = exports.database:insert_id( "INSERT INTO `accounts` (`username`, `password`) VALUES (?, ?)", username, exports.security:hashString( password ) )
if ( accountID ) then
return accountID
else
return -2
end
else
return -1
end
end
addEvent( "accounts:login", true )
addEventHandler( "accounts:login", root,
function( username, password )
if ( source ~= client ) then
return
end
if ( username ) and ( password ) then
local status = login( client, username, password )
if ( not status ) then
triggerClientEvent( client, "messages:create", client, "Username and/or password is incorrect. Please try again.", "login" )
else
triggerClientEvent( client, "accounts:onLogin", client )
updateCharacters( client )
end
else
triggerClientEvent( client, "messages:create", client, "Oops, something went wrong. Please try again.", "login" )
end
end
)
addEvent( "accounts:logout", true )
addEventHandler( "accounts:logout", root,
function( )
if ( source ~= client ) then
return
end
logout( client )
end
)
addEvent( "accounts:register", true )
addEventHandler( "accounts:register", root,
function( username, password )
if ( source ~= client ) then
return
end
if ( username ) and ( password ) then
local status = register( username, password )
if ( status == -1 ) then
triggerClientEvent( client, "messages:create", client, "An account with this username already exists. Please try another name.", "login" )
elseif ( status == -2 ) then
triggerClientEvent( client, "messages:create", client, "Oops, something went wrong. Please try again.", "login" )
else
triggerClientEvent( client, "accounts:onRegister", client )
end
else
triggerClientEvent( client, "messages:create", client, "Oops, something went wrong. Please try again.", "login" )
end
end
)
addEvent( "accounts:ready", true )
addEventHandler( "accounts:ready", root,
function( )
if ( source ~= client ) then
return
end
local accountID = exports.common:getAccountID( client )
if ( not accountID ) then
triggerClientEvent( client, "accounts:showLogin", client )
fadeCamera( client, true )
else
if ( not getElementData( client, "player:playing" ) ) then
exports.messages:createMessage( client, "Loading characters. Please wait.", "selection", nil, true, true )
triggerClientEvent( client, "accounts:showCharacterSelection", client )
updateCharacters( client )
exports.messages:destroyMessage( client, "selection" )
fadeCamera( client, true )
end
end
if ( not getElementData( client, "player:playing" ) ) then
triggerClientEvent( client, "accounts:showView", client )
end
if ( not getElementData( client, "player:id" ) ) then
givePlayerID( client )
end
setPlayerHudComponentVisible( client, "all", false )
setPlayerHudComponentVisible( client, "clock", true )
end
)
|
local _get = get
function get( id )
return exports.database:query_single( "SELECT * FROM `accounts` WHERE `id` = ?", id )
end
function new( username, password )
return exports.database:insert_id( "INSERT INTO `accounts` (`username`, `password`) VALUES (?, ?)", username, exports.security:hashString( password ) )
end
function login( player, username, password )
if ( getElementType( player ) ~= "player" ) then
return false
end
local account = exports.database:query_single( "SELECT * FROM `accounts` WHERE `username` = ? AND `password` = ?", username, exports.security:hashString( password ) )
if ( account ) then
exports.database:execute( "UPDATE `accounts` SET `last_login` = NOW( ), `last_ip` = ?, `last_serial` = ? WHERE `id` = ?", getPlayerIP( player ), getPlayerSerial( player ), account.id )
exports.security:modifyElementData( player, "database:id", account.id, false )
exports.security:modifyElementData( player, "account:username", account.username, true )
exports.security:modifyElementData( player, "account:level", account.level, true )
exports.security:modifyElementData( player, "account:duty", true, true )
exports.security:modifyElementData( player, "player:name", getPlayerName( player ), true )
triggerClientEvent( player, "accounts:onLogin", player )
triggerClientEvent( player, "admin:showHUD", player )
return true
end
return false
end
function logout( player )
characterSelection( player )
exports.database:execute( "UPDATE `accounts` SET `last_action` = NOW( ) WHERE `id` = ?", exports.common:getAccountID( player ) )
setPlayerName( player, getElementData( player, "player:name" ) )
removeElementData( player, "database:id" )
removeElementData( player, "account:username" )
removeElementData( player, "account:level" )
removeElementData( player, "account:duty" )
removeElementData( player, "player:name" )
triggerClientEvent( player, "superman:stop", player )
spawnPlayer( player, 0, 0, 0 )
setElementDimension( player, 6000 )
setCameraMatrix( player, 0, 0, 100, 100, 100, 100 )
triggerClientEvent( player, "accounts:onLogout.characters", player )
triggerClientEvent( player, "accounts:onLogout.accounts", player )
triggerClientEvent( player, "admin:hideHUD", player )
end
function register( username, password )
local query = exports.database:query_single( "SELECT NULL FROM `accounts` WHERE `username` = ?", username )
if ( not query ) then
local accountID = exports.database:insert_id( "INSERT INTO `accounts` (`username`, `password`) VALUES (?, ?)", username, exports.security:hashString( password ) )
if ( accountID ) then
return accountID
else
return -2
end
else
return -1
end
end
addEvent( "accounts:login", true )
addEventHandler( "accounts:login", root,
function( username, password )
if ( source ~= client ) then
return
end
if ( username ) and ( password ) then
local status = login( client, username, password )
if ( not status ) then
triggerClientEvent( client, "messages:create", client, "Username and/or password is incorrect. Please try again.", "login" )
else
triggerClientEvent( client, "accounts:onLogin", client )
updateCharacters( client )
end
else
triggerClientEvent( client, "messages:create", client, "Oops, something went wrong. Please try again.", "login" )
end
end
)
addEvent( "accounts:logout", true )
addEventHandler( "accounts:logout", root,
function( )
if ( source ~= client ) then
return
end
logout( client )
end
)
addEvent( "accounts:register", true )
addEventHandler( "accounts:register", root,
function( username, password )
if ( source ~= client ) then
return
end
if ( username ) and ( password ) then
local status = register( username, password )
if ( status == -1 ) then
triggerClientEvent( client, "messages:create", client, "An account with this username already exists. Please try another name.", "login" )
elseif ( status == -2 ) then
triggerClientEvent( client, "messages:create", client, "Oops, something went wrong. Please try again.", "login" )
else
triggerClientEvent( client, "accounts:onRegister", client )
end
else
triggerClientEvent( client, "messages:create", client, "Oops, something went wrong. Please try again.", "login" )
end
end
)
addEvent( "accounts:ready", true )
addEventHandler( "accounts:ready", root,
function( )
if ( source ~= client ) then
return
end
local accountID = exports.common:getAccountID( client )
if ( not accountID ) then
triggerClientEvent( client, "accounts:showLogin", client )
fadeCamera( client, true )
else
if ( not getElementData( client, "player:playing" ) ) then
exports.messages:createMessage( client, "Loading characters. Please wait.", "selection", nil, true, true )
triggerClientEvent( client, "accounts:showCharacterSelection", client )
updateCharacters( client )
exports.messages:destroyMessage( client, "selection" )
fadeCamera( client, true )
end
end
if ( not getElementData( client, "player:playing" ) ) then
triggerClientEvent( client, "accounts:showView", client )
end
if ( not getElementData( client, "player:id" ) ) then
givePlayerID( client )
end
setPlayerHudComponentVisible( client, "all", false )
setPlayerHudComponentVisible( client, "clock", true )
end
)
|
accounts: fixed last_ip and last_serial not being set
|
accounts: fixed last_ip and last_serial not being set
|
Lua
|
mit
|
smile-tmb/lua-mta-fairplay-roleplay
|
abd7f4f84ab68b611f5d00f639209dc97e19cfb4
|
pud/system/RenderSystem.lua
|
pud/system/RenderSystem.lua
|
local Class = require 'lib.hump.class'
local ListenerBag = getClass 'pud.kit.ListenerBag'
local table_sort = table.sort
-- RenderSystem
--
local RenderSystem = Class{name='RenderSystem',
function(self)
self._registered = {}
self._levels = {}
end
}
-- destructor
function RenderSystem:destroy()
for k,bag in pairs(self._registered) do
bag:destroy()
self._registered[k] = nil
end
self._registered = nil
self._levels = nil
end
-- draw
function RenderSystem:draw()
for i=#self._levels,1,-1 do
local level = self._levels[i]
for obj in self._registered[level]:listeners() do obj:draw() end
end
end
-- make sure the given level exists
function RenderSystem:_touchLevel(level)
if not self._registered[level] then
self._registered[level] = ListenerBag()
-- create sorted, unique array
local unique = {}
unique[level] = true
for i,l in pairs(self._levels) do
unique[l] = true
self._levels[i] = nil
end
for l in pairs(unique) do self._levels[#self._levels+1] = l end
table_sort(self._levels)
end
end
-- register an object
function RenderSystem:register(obj, level)
level = level or 1
verify('number', level)
self:_touchLevel(level)
self._registered[level]:push(obj)
end
-- unregister an object
function RenderSystem:unregister(obj)
self._registered:pop(obj)
end
-- the class
return RenderSystem
|
local Class = require 'lib.hump.class'
local ListenerBag = getClass 'pud.kit.ListenerBag'
local table_sort = table.sort
-- RenderSystem
--
local RenderSystem = Class{name='RenderSystem',
function(self)
self._registered = {}
self._levels = {}
end
}
-- destructor
function RenderSystem:destroy()
for k,bag in pairs(self._registered) do
bag:destroy()
self._registered[k] = nil
end
self._registered = nil
self._levels = nil
end
-- draw
function RenderSystem:draw()
for i=#self._levels,1,-1 do
local level = self._levels[i]
for obj in self._registered[level]:listeners() do obj:draw() end
end
end
-- make sure the given level exists
function RenderSystem:_touchLevel(level)
if not self._registered[level] then
self._registered[level] = ListenerBag()
-- create sorted, unique array
local unique = {}
unique[level] = true
for i,l in pairs(self._levels) do
unique[l] = true
self._levels[i] = nil
end
for l in pairs(unique) do self._levels[#self._levels+1] = l end
table_sort(self._levels)
end
end
-- register an object
function RenderSystem:register(obj, level)
level = level or 1
verify('number', level)
self:_touchLevel(level)
self._registered[level]:push(obj)
end
-- unregister an object
function RenderSystem:unregister(obj)
for _,l in pairs(self._levels) do
if self._registered[l] then self._registered[l]:pop(obj) end
end
end
-- the class
return RenderSystem
|
fix unregister
|
fix unregister
|
Lua
|
mit
|
scottcs/wyx
|
0a7ad3f127690816396300210f66d114bfe37358
|
base/gems.lua
|
base/gems.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/>.
]]
local M = {}
local function extractNum(text)
if text=="" then
return 0
end
return tonumber(text)
end
-- calculates the gem bonus and returns it in %
function M.getGemBonus(item)
local gemStrength = {}
gemStrength[1]=extractNum(item:getData("magicalEmerald"))
gemStrength[2]=extractNum(item:getData("magicalRuby"))
gemStrength[3]=extractNum(item:getData("magicalTopaz"))
gemStrength[4]=extractNum(item:getData("magicalAmethyst"))
gemStrength[5]=extractNum(item:getData("magicalSapphire"))
gemStrength[6]=extractNum(item:getData("magicalObsidian"))
local gemSum=0
local gemMin=1000 -- arbitrarily high number
for _, gStrength in pairs(gemStrength) do
gemSum=gemSum+gStrength
if gStrength<gemMin then gemMin=gStrength end
end
return gemSum+gemMin*6
end
return M
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
local common = require("base.common")
local M = {}
M.DIAMOND = 1
M.EMERALD = 2
M.RUBY = 3
M.OBSIDIAN = 4
M.SAPPHIRE = 5
M.AMETHYST = 6
M.TOPAZ = 7
local gemItem = {}
gemItem[M.DIAMOND] = 285
gemItem[M.EMERALD] = 45
gemItem[M.RUBY] = 46
gemItem[M.OBSIDIAN] = 283
gemItem[M.SAPPHIRE] = 284
gemItem[M.AMETHYST] = 197
gemItem[M.TOPAZ] = 198
local gemId = {}
gemId[285] = M.DIAMOND
gemId[45] = M.EMERALD
gemId[46] = M.RUBY
gemId[283] = M.OBSIDIAN
gemId[284] = M.SAPPHIRE
gemId[197] = M.AMETHYST
gemId[198] = M.TOPAZ
local gemDataKey = {}
gemDataKey[M.DIAMOND] = "magicalDiamond"
gemDataKey[M.EMERALD] = "magicalEmerald"
gemDataKey[M.RUBY] = "magicalRuby"
gemDataKey[M.OBSIDIAN] = "magicalObsidian"
gemDataKey[M.SAPPHIRE] = "magicalSapphire"
gemDataKey[M.AMETHYST] = "magicalAmethyst"
gemDataKey[M.TOPAZ] = "magicalTopaz"
local levelDataKey = "gemLevel"
local function extractNum(text)
if text=="" then
return 0
end
return tonumber(text)
end
-- calculates the gem bonus and returns it in %
function M.getGemBonus(item)
local gemStrength = {}
gemStrength[1]=extractNum(item:getData("magicalEmerald"))
gemStrength[2]=extractNum(item:getData("magicalRuby"))
gemStrength[3]=extractNum(item:getData("magicalTopaz"))
gemStrength[4]=extractNum(item:getData("magicalAmethyst"))
gemStrength[5]=extractNum(item:getData("magicalSapphire"))
gemStrength[6]=extractNum(item:getData("magicalObsidian"))
local gemSum=0
local gemMin=1000 -- arbitrarily high number
for _, gStrength in pairs(gemStrength) do
gemSum=gemSum+gStrength
if gStrength<gemMin then gemMin=gStrength end
end
return gemSum+gemMin*6
end
function M.itemIsMagicGem(item)
local gemList = { 45, 46, 197, 198, 283, 284, 285}
-- 45:emerald;46:ruby;197:amethyst;198:topaz;283:obsidian;284:sappire;285:diamant
-- if item ~= nil then
for i in pairs(gemList) do
if (item.id == gemList[i]) then
local level = tonumber(item:getData(levelDataKey))
if level and level > 0 then
return true
end
end
end
-- end
return false
end
function M.getMagicGemId(gem, level)
local level = level or 1
return gemItem[gem]
end
function M.itemHasGems(item)
return getGemBonus(item) > 0
end
function M.returnGemsToUser(user, item)
if ( itemHasGems(item) == true ) then
for i = 1, #gemDataKey do
local itemKey = gemDataKey[i]
local level = tonumber(item:getData(itemKey))
if level and level > 0 then
common.CreateItem(user, gemItem[i], 1, 999, {[levelDataKey] = level})
end
end
user:inform("Alle Edelsteine wurden aus dem Gegenstand " .. world:getItemName( item.id, 0 ) .. " entfernt und dir zurckgegeben.",
"All gems were removed from the item " .. world:getItemName( item.id, 1 ) .. " and returned to your inventory.")
end
end
return M
|
fix base.gems
|
fix base.gems
|
Lua
|
agpl-3.0
|
Baylamon/Illarion-Content,KayMD/Illarion-Content,Illarion-eV/Illarion-Content,vilarion/Illarion-Content
|
fdab546ae6710e8b870d4b7a46a4283e2f20d86c
|
misc/freeswitch/scripts/test_route.lua
|
misc/freeswitch/scripts/test_route.lua
|
-- Gemeinschaft 5 routing test module
-- (c) AMOOMA GmbH 2013
--
require 'common.array';
local arguments = {};
local value = nil;
for index=1, #argv do
if math.mod(index, 2) == 0 then
common.array.set(arguments, argv[index], value);
else
value = argv[index];
end
end
local caller = arguments.caller or {};
local channel_variables = arguments.chv or {};
function caller.to_s(variable)
return common.str.to_s(arguments[variable])
end
local log_buffer = {};
-- initialize logging
require 'common.log';
log = common.log.Log:new{ buffer = log_buffer, prefix = '' };
-- connect to database
require 'common.database';
local database = common.database.Database:new{ log = log }:connect();
if not database:connected() then
log:critical('TEST_ROUTE - database connection failed');
return;
end
-- dialplan object
require 'dialplan.dialplan'
local dialplan_object = dialplan.dialplan.Dialplan:new{ log = log, caller = caller, database = database };
dialplan_object:configuration_read();
caller.dialplan = dialplan_object;
caller.local_node_id = dialplan_object.node_id;
dialplan_object:retrieve_caller_data();
local destination = arguments.destination or dialplan_object:destination_new{ number = caller.destination_number };
local routes = {};
if destination and destination.type == 'unknown' then
local clip_no_screening = common.array.try(caller, 'account.record.clip_no_screening');
caller.caller_id_numbers = {}
if not common.str.blank(clip_no_screening) then
for index, number in ipairs(common.str.strip_to_a(clip_no_screening, ',')) do
table.insert(caller.caller_id_numbers, number);
end
end
if caller.caller_phone_numbers then
for index, number in ipairs(caller.caller_phone_numbers) do
table.insert(caller.caller_id_numbers, number);
end
end
log:info('CALLER_ID_NUMBERS - clir: ', caller.clir, ', numbers: ', table.concat(caller.caller_id_numbers, ','));
destination.callee_id_number = destination.number;
destination.callee_id_name = nil;
end
caller.destination = destination;
require 'dialplan.router';
routes = dialplan.router.Router:new{ log = log, database = database, caller = caller, variables = caller, log_details = true }:route_run(arguments.table or 'outbound');
local result = {
routes = routes,
destination = destination,
log = log_buffer
}
stream:write(common.array.to_json(result));
-- release database handle
if database then
database:release();
end
|
-- Gemeinschaft 5 routing test module
-- (c) AMOOMA GmbH 2013
--
require 'common.array';
local arguments = {};
local value = nil;
for index=1, #argv do
if math.mod(index, 2) == 0 then
common.array.set(arguments, argv[index], value);
else
value = argv[index];
end
end
local caller = arguments.caller or {};
local channel_variables = arguments.chv or {};
function caller.to_s(variable)
return common.str.to_s(arguments[variable])
end
local log_buffer = {};
-- initialize logging
require 'common.log';
log = common.log.Log:new{ buffer = log_buffer, prefix = '' };
-- connect to database
require 'common.database';
local database = common.database.Database:new{ log = log }:connect();
if not database:connected() then
log:critical('TEST_ROUTE - database connection failed');
return;
end
-- dialplan object
require 'dialplan.dialplan'
local dialplan_object = dialplan.dialplan.Dialplan:new{ log = log, caller = caller, database = database };
dialplan_object:configuration_read();
caller.dialplan = dialplan_object;
caller.local_node_id = dialplan_object.node_id;
caller.date = os.date('%y%m%d%w');
caller.time = os.date('%H%M%S');
dialplan_object:retrieve_caller_data();
local destination = arguments.destination or dialplan_object:destination_new{ number = caller.destination_number };
local routes = {};
if destination and destination.type == 'unknown' then
local clip_no_screening = common.array.try(caller, 'account.record.clip_no_screening');
caller.caller_id_numbers = {}
if not common.str.blank(clip_no_screening) then
for index, number in ipairs(common.str.strip_to_a(clip_no_screening, ',')) do
table.insert(caller.caller_id_numbers, number);
end
end
if caller.caller_phone_numbers then
for index, number in ipairs(caller.caller_phone_numbers) do
table.insert(caller.caller_id_numbers, number);
end
end
log:info('CALLER_ID_NUMBERS - clir: ', caller.clir, ', numbers: ', table.concat(caller.caller_id_numbers, ','));
destination.callee_id_number = destination.number;
destination.callee_id_name = nil;
end
caller.destination = destination;
require 'dialplan.router';
routes = dialplan.router.Router:new{ log = log, database = database, caller = caller, variables = caller, log_details = true }:route_run(arguments.table or 'outbound');
local result = {
routes = routes,
destination = destination,
log = log_buffer
}
stream:write(common.array.to_json(result));
-- release database handle
if database then
database:release();
end
|
date/time in routing test fixed
|
date/time in routing test fixed
|
Lua
|
mit
|
funkring/gs5,amooma/GS5,amooma/GS5,amooma/GS5,funkring/gs5,funkring/gs5,amooma/GS5,funkring/gs5
|
160e5662c5bd38577e98c141ea0e802a96d8dc84
|
premake5.lua
|
premake5.lua
|
-- (c) Derek Dupras 2017-2018, All Rights Reserved.
-- premake5.lua
workspace "LibSort"
configurations { "Debug", "Release" }
location "build"
project "LibSort-test"
location "build"
kind "ConsoleApp"
language "C++"
-- Catch will define a main if not provided, but we need to define DO_NOT_USE_WMAIN
defines { "DO_NOT_USE_WMAIN" }
targetdir "bin/%{cfg.buildcfg}"
includedirs { "include", "external/catch" }
files { "**.h", "**.cpp" }
configuration "Debug"
defines { "DEBUG" }
symbols "On"
configuration "Release"
defines { "NDEBUG" }
flags { "Optimize" }
|
-- (c) Derek Dupras 2017-2021, All Rights Reserved.
-- premake5.lua
workspace "LibSort"
configurations { "Debug", "Release" }
location "build"
project 'LibSort'
kind 'None'
language "C++"
files {
'include/**',
'.clang-format',
'premake5.lua'
}
vpaths {
['Headers/**'] = { 'include/**.h', 'include/**.hpp' },
['Clang/**'] = { '.clang-format' },
['Premake/**'] = { 'premake5.lua' },
['Docs'] = '**.md'
}
project "LibSort-test"
location "build"
kind "ConsoleApp"
language "C++"
-- Catch will define a main if not provided, but we need to define DO_NOT_USE_WMAIN
defines { "DO_NOT_USE_WMAIN" }
targetdir "bin/%{cfg.buildcfg}"
includedirs { "include", "external/catch" }
files { "**.h", "**.cpp" }
configuration "Debug"
defines { "DEBUG" }
symbols "On"
configuration "Release"
defines { "NDEBUG" }
optimize "On"
|
Added LibSort project in premake script
|
Added LibSort project in premake script
* Added LibSort project in premake script
* Fixed deprecation warning in premake script
|
Lua
|
mit
|
ddupras/LibSort,ddupras/LibSort
|
37fd7600c5df738e036886b9c1f48f42ebc8cd5b
|
src/extensions/cp/battery.lua
|
src/extensions/cp/battery.lua
|
--- === cp.battery ===
---
--- Provides access to various properties of the battery. Each of these properties
--- is a `cp.prop`, so it can be watched for changes. For example:
---
--- ```lua
--- local battery = require("cp.battery")
--- battery.powerSupply:watch(function(value)
--- print("Now using "..value)
--- end)
--- ```
---
--- This will `print` "Now using AC Power" or "Now using Battery Power" whenever the
--- power supply changes.
---
--- By default the watcher initialises in a "stopped" state, and must be started for
--- the `cp.prop` watchers to trigger.
--- cp.battery.amperage <cp.prop: number; read-only>
--- Constant
--- Returns the amount of current flowing through the battery, in mAh.
---
--- Notes:
--- * A number containing the amount of current flowing through the battery. The value may be:
--- ** Less than zero if the battery is being discharged (i.e. the computer is running on battery power)
--- ** Zero if the battery is being neither charged nor discharded
--- ** Greater than zero if the bettery is being charged
--- cp.battery.capacity <cp.prop: number; read-only>
--- Constant
--- Returns the current capacity of the battery in mAh.
---
--- Notes:
--- * This is the measure of how charged the battery is, vs the value of `cp.battery.maxCapacity()`.
--- cp.battery.cycles <cp.prop: number; read-only>
--- Constant
--- Returns the number of discharge cycles of the battery.
---
--- Notes:
--- * One cycle is a full discharge of the battery, followed by a full charge. This may also be an aggregate of many smaller discharge-then-charge cycles (e.g. 10 iterations of discharging the battery from 100% to 90% and then charging back to 100% each time, is considered to be one cycle).
--- cp.battery.designCapacity <cp.prop: number; read-only>
--- Constant
--- Returns the design capacity of the battery in mAh.
--- cp.battery.health <cp.prop: string; read-only>
--- Constant
--- Returns the health status of the battery; either "Good", "Fair" or "Poor",
--- as determined by the Apple Smart Battery controller.
--- cp.battery.healthCondition <cp.prop: string; read-only>
--- Constant
--- Returns the health condition status of the battery:
--- `nil` if there are no health conditions to report, or a string containing either:
--- * "Check Battery"
--- * "Permanent Battery Failure"
--- cp.battery.isCharged <cp.prop: boolean; read-only>
--- Constant
--- Checks if the battery is fully charged.
--- cp.battery.isCharging <cp.prop: boolean; read-only>
--- Constant
--- Checks if the battery is currently charging.
--- cp.battery.isFinishingCharge <cp.prop: boolean | string; read-only>
--- Constant
--- Checks if the battery is trickle charging;
--- either `true` if trickle charging, `false` if charging faster, or `"n/a" if the battery is not charging at all.
--- cp.battery.maxCapacity <cp.prop; number; read-only>
--- Constant
--- Returns the maximum capacity of the battery in mAh.
---
--- Notes:
--- * This may exceed the value of `cp.battery.designCapacity()` due to small variations in the production chemistry vs the design.
--- cp.battery.otherBatteryInfo <cp.prop: table | nil; read-only>
--- Constant
--- Returns information about non-PSU batteries (e.g. bluetooth accessories). If none are found, `nil` is returned.
--- cp.battery.percentage <cp.prop; string; read-only>
--- Constant
--- Returns the current source of power; either `"AC Power"`, `"Battery Power"` or `"Off Line"`.
--- cp.battery.psuSerial <cp.prop: number; read-only>
--- Constant
--- Returns the serial number of the attached power supply, or `0` if not present.
--- cp.battery.timeRemaining <cp.prop: number; read-only>
--- Constant
--- The amount of battery life remaining, in minuges.
---
--- Notes:
--- * The return value may be:
--- ** Greater than zero to indicate the number of minutes remaining.
--- ** `-1` if the remaining batttery life is being calculated.
--- ** `-2` if there is unlimited time remaining (i.e. the system is on AC power).
--- cp.battery.timeToFullCharge <cp.prop; number; read-only>
--- Constant
--- Returns the time remaining for the battery to be fully charged, in minutes, or `-`` if still being calculated.
--- cp.battery.voltage <cp.prop: number; read-only>
--- Constant
--- Returns the current voltage of the battery in mV.
--- cp.battery.watts <cp.prop: number; read-only>
--- Constant
--- Returns the power entering or leaving the battery, in W.
--- Discharging will be less than zero, charging greater than zero.
local require = require
local log = require "hs.logger".new "cpBattery"
local battery = require "hs.battery"
local prop = require "cp.prop"
local mod = {}
-- EXCLUDED -> table
-- Constant
-- Table of excluded items.
local EXCLUDED = {
["privateBluetoothBatteryInfo"] = true,
["getAll"] = true,
}
--- cp.battery._watcher -> hs.battery.watcher object
--- Variable
--- The battery watcher.
mod._watcher = battery.watcher.new(function()
for key,value in pairs(mod) do
if prop.is(value) then
local ok, result = xpcall(function() value:update() end, debug.traceback)
if not ok then
log.ef("Error while updating '%s'", key, result)
end
end
end
end)
--- cp.battery.start() -> none
--- Function
--- Starts the battery watcher.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function mod.start()
mod._watcher:start()
end
--- cp.battery.stop() -> none
--- Function
--- Stops the battery watcher.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function mod.stop()
mod._watcher:stop()
end
-- init() -> none
-- Function
-- Initialise the module.
--
-- Parameters:
-- * None
--
-- Returns:
-- * The module
local function init()
for key,value in pairs(battery) do
if EXCLUDED[key] ~= true and type(value) == "function" then
mod[key] = prop(value):label(string.format("cp.battery: %s", key))
end
end
return mod
end
return init()
|
--- === cp.battery ===
---
--- Provides access to various properties of the battery. Each of these properties
--- is a `cp.prop`, so it can be watched for changes. For example:
---
--- ```lua
--- local battery = require("cp.battery")
--- battery.powerSupply:watch(function(value)
--- print("Now using "..value)
--- end)
--- ```
---
--- This will `print` "Now using AC Power" or "Now using Battery Power" whenever the
--- power supply changes.
---
--- By default the watcher initialises in a "stopped" state, and must be started for
--- the `cp.prop` watchers to trigger.
--- cp.battery.amperage <cp.prop: number; read-only>
--- Constant
--- Returns the amount of current flowing through the battery, in mAh.
---
--- Notes:
--- * A number containing the amount of current flowing through the battery. The value may be:
--- ** Less than zero if the battery is being discharged (i.e. the computer is running on battery power)
--- ** Zero if the battery is being neither charged nor discharded
--- ** Greater than zero if the bettery is being charged
--- cp.battery.capacity <cp.prop: number; read-only>
--- Constant
--- Returns the current capacity of the battery in mAh.
---
--- Notes:
--- * This is the measure of how charged the battery is, vs the value of `cp.battery.maxCapacity()`.
--- cp.battery.cycles <cp.prop: number; read-only>
--- Constant
--- Returns the number of discharge cycles of the battery.
---
--- Notes:
--- * One cycle is a full discharge of the battery, followed by a full charge. This may also be an aggregate of many smaller discharge-then-charge cycles (e.g. 10 iterations of discharging the battery from 100% to 90% and then charging back to 100% each time, is considered to be one cycle).
--- cp.battery.designCapacity <cp.prop: number; read-only>
--- Constant
--- Returns the design capacity of the battery in mAh.
--- cp.battery.health <cp.prop: string; read-only>
--- Constant
--- Returns the health status of the battery; either "Good", "Fair" or "Poor",
--- as determined by the Apple Smart Battery controller.
--- cp.battery.healthCondition <cp.prop: string; read-only>
--- Constant
--- Returns the health condition status of the battery:
--- `nil` if there are no health conditions to report, or a string containing either:
--- * "Check Battery"
--- * "Permanent Battery Failure"
--- cp.battery.isCharged <cp.prop: boolean; read-only>
--- Constant
--- Checks if the battery is fully charged.
--- cp.battery.isCharging <cp.prop: boolean; read-only>
--- Constant
--- Checks if the battery is currently charging.
--- cp.battery.isFinishingCharge <cp.prop: boolean | string; read-only>
--- Constant
--- Checks if the battery is trickle charging;
--- either `true` if trickle charging, `false` if charging faster, or `"n/a" if the battery is not charging at all.
--- cp.battery.maxCapacity <cp.prop; number; read-only>
--- Constant
--- Returns the maximum capacity of the battery in mAh.
---
--- Notes:
--- * This may exceed the value of `cp.battery.designCapacity()` due to small variations in the production chemistry vs the design.
--- cp.battery.otherBatteryInfo <cp.prop: table | nil; read-only>
--- Constant
--- Returns information about non-PSU batteries (e.g. bluetooth accessories). If none are found, `nil` is returned.
--- cp.battery.percentage <cp.prop; string; read-only>
--- Constant
--- Returns the current source of power; either `"AC Power"`, `"Battery Power"` or `"Off Line"`.
--- cp.battery.psuSerial <cp.prop: number; read-only>
--- Constant
--- Returns the serial number of the attached power supply, or `0` if not present.
--- cp.battery.timeRemaining <cp.prop: number; read-only>
--- Constant
--- The amount of battery life remaining, in minuges.
---
--- Notes:
--- * The return value may be:
--- ** Greater than zero to indicate the number of minutes remaining.
--- ** `-1` if the remaining batttery life is being calculated.
--- ** `-2` if there is unlimited time remaining (i.e. the system is on AC power).
--- cp.battery.timeToFullCharge <cp.prop; number; read-only>
--- Constant
--- Returns the time remaining for the battery to be fully charged, in minutes, or `-`` if still being calculated.
--- cp.battery.voltage <cp.prop: number; read-only>
--- Constant
--- Returns the current voltage of the battery in mV.
--- cp.battery.watts <cp.prop: number; read-only>
--- Constant
--- Returns the power entering or leaving the battery, in W.
--- Discharging will be less than zero, charging greater than zero.
local require = require
local log = require "hs.logger".new "cpBattery"
local battery = require "hs.battery"
local prop = require "cp.prop"
local mod = {}
-- EXCLUDED -> table
-- Constant
-- Table of excluded items.
local EXCLUDED = {
["privateBluetoothBatteryInfo"] = true,
["getAll"] = true,
["psuSerialString"] = true,
}
--- cp.battery._watcher -> hs.battery.watcher object
--- Variable
--- The battery watcher.
mod._watcher = battery.watcher.new(function()
for key,value in pairs(mod) do
if prop.is(value) then
local ok, result = xpcall(function() value:update() end, debug.traceback)
if not ok then
log.ef("Error while updating '%s'", key, result)
end
end
end
end)
--- cp.battery.start() -> none
--- Function
--- Starts the battery watcher.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function mod.start()
mod._watcher:start()
end
--- cp.battery.stop() -> none
--- Function
--- Stops the battery watcher.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function mod.stop()
mod._watcher:stop()
end
-- init() -> none
-- Function
-- Initialise the module.
--
-- Parameters:
-- * None
--
-- Returns:
-- * The module
local function init()
for key,value in pairs(battery) do
if EXCLUDED[key] ~= true and type(value) == "function" then
mod[key] = prop(value):label(string.format("cp.battery: %s", key))
end
end
return mod
end
return init()
|
Fixes 2135 by excluding the psuSerialString value. (#2180)
|
Fixes 2135 by excluding the psuSerialString value. (#2180)
|
Lua
|
mit
|
fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks
|
0a88e815a7495e9270fec4a54c116231f5c4def5
|
share/media/publicsenat.lua
|
share/media/publicsenat.lua
|
-- libquvi-scripts
-- Copyright (C) 2013 Toni Gundogdu <[email protected]>
-- Copyright (C) 2010,2012 Raphaël Droz <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.googlecode.com/>.
--
-- This program is free software: you can redistribute it and/or
-- modify it under the terms of the GNU Affero General Public
-- License as published by the Free Software Foundation, either
-- version 3 of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General
-- Public License along with this program. If not, see
-- <http://www.gnu.org/licenses/>.
--
local PublicSenat = {} -- Utility functions unique to this script.
-- Identify the script.
function ident(qargs)
return {
can_parse_url = PublicSenat.can_parse_url(qargs),
domains = table.concat({'publicsenat.fr'}, ',')
}
end
-- Parse media URL.
function parse(self)
self.host_id = "publicsenat"
local p = quvi.fetch(self.page_url)
self.title = p:match('<title>(.-)%s+%|') or error("no match: media title")
self.id = self.page_url:match(".-idE=(%d+)$")
or self.page_url:match(".-/(%d+)$")
or error("no match: media ID")
local t = p:match('id="imgEmissionSelect" value="(.-)"') or ''
if #t >0 then
self.thumbnail_url = 'http://publicsenat.fr' .. t
end
local u = "http://videos.publicsenat.fr/vodiFrame.php?idE=" ..self.id
local c = quvi.fetch(u, {fetch_type='config'})
self.url = {c:match('id="flvEmissionSelect" value="(.-)"')
or error("no match: media stream URL")}
return self
end
--
-- Utility functions.
--
function PublicSenat.can_parse_url(qargs)
local U = require 'socket.url'
local t = U.parse(qargs.input_url)
if t and t.scheme and t.scheme:lower():match('^http$')
and t.host and t.host:lower():match('publicsenat%.fr$')
and t.path and t.path:lower():match('^/vod/.-/%d+')
then
return true
else
return false
end
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2013 Toni Gundogdu <[email protected]>
-- Copyright (C) 2010,2012 Raphaël Droz <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.googlecode.com/>.
--
-- This program is free software: you can redistribute it and/or
-- modify it under the terms of the GNU Affero General Public
-- License as published by the Free Software Foundation, either
-- version 3 of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General
-- Public License along with this program. If not, see
-- <http://www.gnu.org/licenses/>.
--
local PublicSenat = {} -- Utility functions unique to this script.
-- Identify the script.
function ident(qargs)
return {
can_parse_url = PublicSenat.can_parse_url(qargs),
domains = table.concat({'publicsenat.fr'}, ',')
}
end
-- Parse media properties.
function parse(qargs)
local p = quvi.http.fetch(qargs.input_url).data
local t = p:match('id="imgEmissionSelect" value="(.-)"') or ''
qargs.thumb_url = (#t >0) and ('http://publicsenat.fr'..t) or ''
qargs.id = qargs.input_url:match("/vod/.-/(%d+)$") or ''
qargs.title = p:match('<title>(.-)%s+%|') or ''
qargs.streams = PublicSenat.iter_streams(p)
return qargs
end
--
-- Utility functions.
--
function PublicSenat.can_parse_url(qargs)
local U = require 'socket.url'
local t = U.parse(qargs.input_url)
if t and t.scheme and t.scheme:lower():match('^http$')
and t.host and t.host:lower():match('publicsenat%.fr$')
and t.path and t.path:lower():match('^/vod/.-/%d+')
then
return true
else
return false
end
end
function PublicSenat.iter_streams(p)
local u = p:match('id="flvEmissionSelect" value="(.-)"')
or error('no match: media stream URL')
local S = require 'quvi/stream'
return {S.stream_new(u)}
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
media/publicsenat.lua: Rewrite parse function
|
media/publicsenat.lua: Rewrite parse function
Rewrite "parse" function for libquvi 0.9+ series.
* Remove any now obsolete code (e.g. self.host_id)
* Add PublicSenat.iter_streams function
* Update vim modeline
NOTE:
This port takes a shortcut to parse the media stream URL and the
thumbnail URL. They are now parsed from the input URL, rather than a
secondary URL -- put together using a static URL prefix and the media
ID. If that, really, is necessary, we can add the additional steps
later.
Signed-off-by: Toni Gundogdu <[email protected]>
|
Lua
|
agpl-3.0
|
legatvs/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts,alech/libquvi-scripts
|
d9740ac308bab90bca759ca9dc0ef11f67347e91
|
modules/admin-full/luasrc/model/cbi/admin_services/dnsmasq.lua
|
modules/admin-full/luasrc/model/cbi/admin_services/dnsmasq.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$
]]--
m = Map("dhcp", "Dnsmasq")
s = m:section(TypedSection, "dnsmasq", translate("Settings"))
s.anonymous = true
s:option(Flag, "domainneeded")
s:option(Flag, "authoritative")
s:option(Flag, "boguspriv")
s:option(Flag, "filterwin2k")
s:option(Flag, "localise_queries")
s:option(Value, "local")
s:option(Value, "domain")
s:option(Flag, "expandhosts")
s:option(Flag, "nonegcache")
s:option(Flag, "readethers")
s:option(Value, "leasefile")
s:option(Value, "resolvfile")
s:option(Flag, "nohosts").optional = true
s:option(Flag, "strictorder").optional = true
s:option(Flag, "logqueries").optional = true
s:option(Flag, "noresolv").optional = true
s:option(Value, "dnsforwardmax").optional = true
s:option(Value, "port").optional = true
s:option(Value, "ednspacket_max").optional = true
s:option(Value, "dhcpleasemax").optional = true
s:option(Value, "addnhosts").optional = true
s:option(Value, "queryport").optional = true
s:option(Flag, "enable_tftp").optional = true
s:option(Value, "tftp_root").optional = true
s:option(Value, "dhcp_boot").optional = true
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("dhcp", "Dnsmasq",
translate("Dnsmasq is a combined <abbr title=\"Dynamic Host Configuration Protocol" ..
"\">DHCP</abbr>-Server and <abbr title=\"Domain Name System\">DNS</abbr>-" ..
"Forwarder for <abbr title=\"Network Address Translation\">NAT</abbr> " ..
"firewalls"))
s = m:section(TypedSection, "dnsmasq", translate("Settings"))
s.anonymous = true
s.addremove = false
s:option(Flag, "domainneeded",
translate("Domain required"),
translate("Don't forward <abbr title=\"Domain Name System\">DNS</abbr>-Requests without " ..
"<abbr title=\"Domain Name System\">DNS</abbr>-Name"))
s:option(Flag, "authoritative",
translate("Authoritative"),
translate("This is the only <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</" ..
"abbr> in the local network"))
s:option(Flag, "boguspriv",
translate("Filter private"),
translate("Don't forward reverse lookups for local networks"))
s:option(Flag, "filterwin2k",
translate("Filter useless"),
translate("filter useless <abbr title=\"Domain Name System\">DNS</abbr>-queries of " ..
"Windows-systems"))
s:option(Flag, "localise_queries",
translate("Localise queries"),
translate("localises the hostname depending on its subnet"))
s:option(Value, "local",
translate("Local Server"))
s:option(Value, "domain",
translate("Local Domain"))
s:option(Flag, "expandhosts",
translate("Expand Hosts"),
translate("adds domain names to hostentries in the resolv file"))
s:option(Flag, "nonegcache",
translate("don't cache unknown"),
translate("prevents caching of negative <abbr title=\"Domain Name System\">DNS</abbr>-" ..
"replies"))
s:option(Flag, "readethers",
translate("Use <code>/etc/ethers</code>"),
translate("Read <code>/etc/ethers</code> to configure the <abbr title=\"Dynamic Host " ..
"Configuration Protocol\">DHCP</abbr>-Server"))
s:option(Value, "leasefile",
translate("Leasefile"),
translate("file where given <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</" ..
"abbr>-leases will be stored"))
s:option(Value, "resolvfile",
translate("Resolvfile"),
translate("local <abbr title=\"Domain Name System\">DNS</abbr> file"))
s:option(Flag, "nohosts",
translate("Ignore <code>/etc/hosts</code>")).optional = true
s:option(Flag, "strictorder",
translate("Strict order"),
translate("<abbr title=\"Domain Name System\">DNS</abbr>-Server will be queried in the " ..
"order of the resolvfile")).optional = true
s:option(Flag, "logqueries",
translate("Log queries")).optional = true
s:option(Flag, "noresolv",
translate("Ignore resolve file")).optional = true
s:option(Value, "dnsforwardmax",
translate("concurrent queries")).optional = true
s:option(Value, "port",
translate("<abbr title=\"Domain Name System\">DNS</abbr>-Port")).optional = true
s:option(Value, "ednspacket_max",
translate("<abbr title=\"maximal\">max.</abbr> <abbr title=\"Extension Mechanisms for " ..
"Domain Name System\">EDNS0</abbr> paket size")).optional = true
s:option(Value, "dhcpleasemax",
translate("<abbr title=\"maximal\">max.</abbr> <abbr title=\"Dynamic Host Configuration " ..
"Protocol\">DHCP</abbr>-Leases")).optional = true
s:option(Value, "addnhosts",
translate("additional hostfile")).optional = true
s:option(Value, "queryport",
translate("query port")).optional = true
s:option(Flag, "enable_tftp",
translate("Enable TFTP-Server")).optional = true
s:option(Value, "tftp_root",
translate("TFTP-Server Root")).optional = true
s:option(Value, "dhcp_boot",
translate("Network Boot Image")).optional = true
return m
|
modules/admin-full: fix dnsmasq page
|
modules/admin-full: fix dnsmasq page
|
Lua
|
apache-2.0
|
deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci
|
e8f45d904d419e6a182960c590eec543b098c608
|
lua/entities/gmod_wire_starfall_processor/init.lua
|
lua/entities/gmod_wire_starfall_processor/init.lua
|
AddCSLuaFile('cl_init.lua')
AddCSLuaFile('shared.lua')
include('shared.lua')
include("starfall/SFLib.lua")
assert(SF, "Starfall didn't load correctly!")
ENT.WireDebugName = "Starfall Processor"
ENT.OverlayDelay = 0
local context = SF.CreateContext()
local name = nil
function ENT:UpdateState(state)
if name then
self:SetOverlayText("Starfall Processor\n"..name.."\n"..state)
else
self:SetOverlayText("Starfall Processor\n"..state)
end
end
function ENT:Initialize()
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self.Inputs = WireLib.CreateInputs(self, {})
self.Outputs = WireLib.CreateOutputs(self, {})
self:UpdateState("Inactive (No code)")
local clr = self:GetColor()
self:SetColor(Color(255, 0, 0, clr.a))
end
function ENT:Compile(codetbl, mainfile)
if self.instance then self.instance:deinitialize() end
local ok, instance = SF.Compiler.Compile(codetbl,context,mainfile,self.owner)
if not ok then self:Error(instance) return end
self.instance = instance
instance.data.entity = self
local ok, msg = instance:initialize()
if not ok then
self:Error(msg)
return
end
instance.runOnError = function(inst,msg) self:Error(msg) end
if self.instance.ppdata.scriptnames and self.instance.mainfile and self.instance.ppdata.scriptnames[self.instance.mainfile] then
name = tostring(self.instance.ppdata.scriptnames[self.instance.mainfile])
end
if not name or string.len(name) <= 0 then
name = "generic"
end
self:UpdateState("(None)")
local clr = self:GetColor()
self:SetColor(Color(255, 255, 255, clr.a))
end
function ENT:Error(msg, traceback)
ErrorNoHalt("Processor of "..self.owner:Nick().." errored: "..msg.."\n")
if traceback then
print(traceback)
end
WireLib.ClientError(msg, self.owner)
if self.instance then
self.instance:deinitialize()
self.instance = nil
end
self:UpdateState("Inactive (Error)")
local clr = self:GetColor()
self:SetColor(Color(255, 0, 0, clr.a))
end
function ENT:Think()
self.BaseClass.Think(self)
if self.instance and not self.instance.error then
self:UpdateState(tostring(self.instance.ops).." ops, "..tostring(math.floor(self.instance.ops / self.instance.context.ops * 100)).."%")
self.instance:resetOps()
self:RunScriptHook("think")
end
self:NextThink(CurTime())
return true
end
function ENT:OnRemove()
if not self.instance then return end
self.instance:deinitialize()
self.instance = nil
end
function ENT:TriggerInput(key, value)
self:RunScriptHook("input",key, SF.Wire.InputConverters[self.Inputs[key].Type](value))
end
function ENT:ReadCell(address)
return tonumber(self:RunScriptHookForResult("readcell",address)) or 0
end
function ENT:WriteCell(address, data)
self:RunScriptHook("writecell",address,data)
end
function ENT:RunScriptHook(hook, ...)
if self.instance and not self.instance.error and self.instance.hooks[hook:lower()] then
local ok, rt = self.instance:runScriptHook(hook, ...)
if not ok then self:Error(rt) end
end
end
function ENT:RunScriptHookForResult(hook,...)
if self.instance and not self.instance.error and self.instance.hooks[hook:lower()] then
local ok, rt = self.instance:runScriptHookForResult(hook, ...)
if not ok then self:Error(rt)
else return rt end
end
end
function ENT:OnRestore()
end
function ENT:BuildDupeInfo()
local info = self.BaseClass.BuildDupeInfo(self) or {}
if self.instance then
info.starfall = SF.SerializeCode(self.instance.source, self.instance.mainfile)
end
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
self.owner = ply
if info.starfall then
local code, main = SF.DeserializeCode(info.starfall)
self:Compile(code, main)
end
end
|
AddCSLuaFile('cl_init.lua')
AddCSLuaFile('shared.lua')
include('shared.lua')
include("starfall/SFLib.lua")
assert(SF, "Starfall didn't load correctly!")
ENT.WireDebugName = "Starfall Processor"
ENT.OverlayDelay = 0
local context = SF.CreateContext()
function ENT:UpdateState(state)
if self.name then
self:SetOverlayText("Starfall Processor\n"..self.name.."\n"..state)
else
self:SetOverlayText("Starfall Processor\n"..state)
end
end
function ENT:Initialize()
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self.Inputs = WireLib.CreateInputs(self, {})
self.Outputs = WireLib.CreateOutputs(self, {})
self:UpdateState("Inactive (No code)")
local clr = self:GetColor()
self:SetColor(Color(255, 0, 0, clr.a))
end
function ENT:Compile(codetbl, mainfile)
if self.instance then self.instance:deinitialize() end
local ok, instance = SF.Compiler.Compile(codetbl,context,mainfile,self.owner)
if not ok then self:Error(instance) return end
self.instance = instance
instance.data.entity = self
local ok, msg = instance:initialize()
if not ok then
self:Error(msg)
return
end
instance.runOnError = function(inst,msg) self:Error(msg) end
self.name = nil
if self.instance.ppdata.scriptnames and self.instance.mainfile and self.instance.ppdata.scriptnames[self.instance.mainfile] then
self.name = tostring(self.instance.ppdata.scriptnames[self.instance.mainfile])
end
if not self.name or string.len(self.name) <= 0 then
self.name = "generic"
end
self:UpdateState("(None)")
local clr = self:GetColor()
self:SetColor(Color(255, 255, 255, clr.a))
end
function ENT:Error(msg, traceback)
ErrorNoHalt("Processor of "..self.owner:Nick().." errored: "..msg.."\n")
if traceback then
print(traceback)
end
WireLib.ClientError(msg, self.owner)
if self.instance then
self.instance:deinitialize()
self.instance = nil
end
self:UpdateState("Inactive (Error)")
local clr = self:GetColor()
self:SetColor(Color(255, 0, 0, clr.a))
end
function ENT:Think()
self.BaseClass.Think(self)
if self.instance and not self.instance.error then
self:UpdateState(tostring(self.instance.ops).." ops, "..tostring(math.floor(self.instance.ops / self.instance.context.ops * 100)).."%")
self.instance:resetOps()
self:RunScriptHook("think")
end
self:NextThink(CurTime())
return true
end
function ENT:OnRemove()
if not self.instance then return end
self.instance:deinitialize()
self.instance = nil
end
function ENT:TriggerInput(key, value)
self:RunScriptHook("input",key, SF.Wire.InputConverters[self.Inputs[key].Type](value))
end
function ENT:ReadCell(address)
return tonumber(self:RunScriptHookForResult("readcell",address)) or 0
end
function ENT:WriteCell(address, data)
self:RunScriptHook("writecell",address,data)
end
function ENT:RunScriptHook(hook, ...)
if self.instance and not self.instance.error and self.instance.hooks[hook:lower()] then
local ok, rt = self.instance:runScriptHook(hook, ...)
if not ok then self:Error(rt) end
end
end
function ENT:RunScriptHookForResult(hook,...)
if self.instance and not self.instance.error and self.instance.hooks[hook:lower()] then
local ok, rt = self.instance:runScriptHookForResult(hook, ...)
if not ok then self:Error(rt)
else return rt end
end
end
function ENT:OnRestore()
end
function ENT:BuildDupeInfo()
local info = self.BaseClass.BuildDupeInfo(self) or {}
if self.instance then
info.starfall = SF.SerializeCode(self.instance.source, self.instance.mainfile)
end
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
self.owner = ply
if info.starfall then
local code, main = SF.DeserializeCode(info.starfall)
self:Compile(code, main)
end
end
|
Fix names being funny
|
Fix names being funny
|
Lua
|
bsd-3-clause
|
Jazzelhawk/Starfall,INPStarfall/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall,Xandaros/Starfall,Jazzelhawk/Starfall,Ingenious-Gaming/Starfall,INPStarfall/Starfall
|
0f16c0d31d9f1084a55da26acedcc98e7d07d890
|
AceConsole-3.0/AceConsole-3.0.lua
|
AceConsole-3.0/AceConsole-3.0.lua
|
--[[ $Id$ ]]
local MAJOR,MINOR = "AceConsole-3.0", 0
local AceConsole, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
if not AceConsole then
return -- no upgrade needed
end
AceConsole.embeds = AceConsole.embeds or {} -- table containing objects AceConsole is embedded in.
AceConsole.commands = AceConsole.commands or {} -- table containing commands registered
AceConsole.weakcommands = AceConsole.weakcommands or {} -- table containing self, command => func references for weak commands that don't persist through enable/disable
-- AceConsole:Print( [chatframe,] ... )
--
-- Print to DEFAULT_CHAT_FRAME or given chatframe (anything with an .AddMessage member)
function AceConsole:Print(...)
local text = ""
if self ~= AceConsole then
text = tostring( self )..": "
end
local frame = select(1, ...)
if not ( type(frame) == "table" and frame.AddMessage ) then -- Is first argument something with an .AddMessage member?
frame=nil
end
for i=(frame and 2 or 1), select("#", ...) do
text = text .. tostring( select( i, ...) ) .." "
end
(frame or DEFAULT_CHAT_FRAME):AddMessage( text )
end
-- AceConsole:RegisterChatCommand(. command, func, persist )
--
-- command (string) - chat command to be registered. does not require / in front
-- func (string|function) - function to call, if a string is used then the member of self is used as a string.
-- persist (boolean) - if true is passed the command will not be soft disabled/enabled when aceconsole is used as a mixin
-- silent (boolean) - don't whine if command already exists, silently fail
--
-- Register a simple chat command
function AceConsole:RegisterChatCommand( command, func, persist, silent )
local name = "ACECONSOLE_"..command:upper()
if SlashCmdList[name] then
if not silent then
geterrorhandler()(tostring(self) ": Chat Command '"..command.."' already exists, will not overwrite.")
end
return
end
if type( func ) == "string" then
SlashCmdList[name] = function(input)
self[func](self, input)
end
else
SlashCmdList[name] = func
end
setglobal("SLASH_"..name.."1", "/"..command:lower())
AceConsole.commands[command] = name
-- non-persisting commands are registered for enabling disabling
if not persist then
AceConsole.weakcommands[self][command] = func
end
end
-- AceConsole:UnregisterChatCommand( command )
--
-- Unregister a chatcommand
function AceConsole:UnregisterChatCommand( command )
local cmd = AceConsole.commands[command]
if cmd then
local name = cmd.name
SlashCmdList[name] = nil
setglobal("SLASH_"..name.."1", nil)
hash_SlashCmdList["/" .. command:upper()] = nil
AceConsole.commands[command] = nil -- TODO: custom table cache?
end
end
local function nils(n, ...)
if n>1 then
return nil, nils(n-1, ...)
elseif n==1 then
return nil, ...
else
return ...
end
end
-- AceConsole:GetArgs(string, numargs, startpos)
--
-- Retreive one or more space-separated arguments from a string.
-- Treats quoted strings and itemlinks as non-spaced.
--
-- string - The raw argument string
-- numargs - How many arguments to get (default 1)
-- startpos - Where in the string to start scanning (default 1)
--
-- Returns arg1, arg2, ..., stringremainder
-- Missing arguments will be returned as nils. 'stringremainder' is returned as "" at the end.
function AceConsole:GetArgs(str, numargs, startpos)
numargs = numargs or 1
startpos = max(startpos or 1, 1)
if numargs<1 then
return strsub(str, startpos)
end
local pos=startpos
-- find start of new arg
pos = strfind(str, "[^ ]", pos)
if not pos then -- whoops, end of string
return nils(numargs, "")
end
-- quoted or space separated? find out which pattern to use
local delim_or_pipe
local ch = strsub(str, pos, pos)
if ch=='"' then
pos = pos + 1
delim_or_pipe='([|"])'
elseif ch=="'" then
pos = pos + 1
delim_or_pipe="([|'])"
else
delim_or_pipe="([| ])"
end
startpos = pos
while true do
-- find delimiter or hyperlink
local ch,_
pos,_,ch = strfind(str, delim_or_pipe, pos)
if not pos then break end
if ch=="|" then
-- some kind of escape
if strsub(str,pos,pos+1)=="|H" then
-- It's a |H....|hhyper link!|h
pos=strfind(str, "|h", pos+2) -- first |h
if not pos then break end
pos=strfind(str, "|h", pos+2) -- second |h
if not pos then break end
end
pos=pos+2 -- skip past this escape (last |h if it was a hyperlink)
else
-- found delimiter, done with this arg
return strsub(str, startpos, pos-1), AceConsole:GetArgs(str, numargs-1, pos+1)
end
end
-- search aborted, we hit end of string. return it all as one argument. (yes, even if it's an unterminated quote or hyperlink)
return strsub(str, startpos), nils(numargs-1, "")
end
--- embedding and embed handling
local mixins = {
"Print",
"RegisterChatCommand",
"UnregisterChatCommand",
"GetArgs",
}
-- AceConsole:Embed( target )
-- target (object) - target object to embed AceBucket in
--
-- Embeds AceConsole into the target object making the functions from the mixins list available on target:..
function AceConsole:Embed( target )
for k, v in pairs( mixins ) do
target[v] = self[v]
end
self.embeds[target] = true
end
function AceConsole:OnEmbedEnable( target )
if AceConsole.weakcommands[target] then
for command, func in pairs( AceConsole.weakcommands[target] ) do
target:RegisterChatCommand( command, func, false, true ) -- nonpersisting and silent registry
end
end
end
function AceConsole:OnEmbedDisable( target )
if AceConsole.weakcommands[target] then
for command, func in pairs( AceConsole.weakcommands[target] ) do
target:UnregisterChatCommand( command ) -- TODO: this could potentially unregister a command from another application in case of command conflicts. Do we care?
end
end
end
for addon in pairs(AceConsole.embeds) do
AceConsole:Embed(addon)
end
|
--[[ $Id$ ]]
local MAJOR,MINOR = "AceConsole-3.0", 0
local AceConsole, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
if not AceConsole then
return -- no upgrade needed
end
AceConsole.embeds = AceConsole.embeds or {} -- table containing objects AceConsole is embedded in.
AceConsole.commands = AceConsole.commands or {} -- table containing commands registered
AceConsole.weakcommands = AceConsole.weakcommands or {} -- table containing self, command => func references for weak commands that don't persist through enable/disable
-- AceConsole:Print( [chatframe,] ... )
--
-- Print to DEFAULT_CHAT_FRAME or given chatframe (anything with an .AddMessage member)
function AceConsole:Print(...)
local text = ""
if self ~= AceConsole then
text = tostring( self )..": "
end
local frame = select(1, ...)
if not ( type(frame) == "table" and frame.AddMessage ) then -- Is first argument something with an .AddMessage member?
frame=nil
end
for i=(frame and 2 or 1), select("#", ...) do
text = text .. tostring( select( i, ...) ) .." "
end
(frame or DEFAULT_CHAT_FRAME):AddMessage( text )
end
-- AceConsole:RegisterChatCommand(. command, func, persist )
--
-- command (string) - chat command to be registered. does not require / in front
-- func (string|function) - function to call, if a string is used then the member of self is used as a string.
-- persist (boolean) - if true is passed the command will not be soft disabled/enabled when aceconsole is used as a mixin
-- silent (boolean) - don't whine if command already exists, silently fail
--
-- Register a simple chat command
function AceConsole:RegisterChatCommand( command, func, persist, silent )
local name = "ACECONSOLE_"..command:upper()
if SlashCmdList[name] then
if not silent then
geterrorhandler()(tostring(self) ": Chat Command '"..command.."' already exists, will not overwrite.")
end
return
end
if type( func ) == "string" then
SlashCmdList[name] = function(input)
self[func](self, input)
end
else
SlashCmdList[name] = func
end
setglobal("SLASH_"..name.."1", "/"..command:lower())
AceConsole.commands[command] = name
-- non-persisting commands are registered for enabling disabling
if not persist then
AceConsole.weakcommands[self][command] = func
end
end
-- AceConsole:UnregisterChatCommand( command )
--
-- Unregister a chatcommand
function AceConsole:UnregisterChatCommand( command )
local name = AceConsole.commands[command]
if name then
SlashCmdList[name] = nil
setglobal("SLASH_"..name.."1", nil)
hash_SlashCmdList["/" .. command:upper()] = nil
AceConsole.commands[command] = nil
end
end
local function nils(n, ...)
if n>1 then
return nil, nils(n-1, ...)
elseif n==1 then
return nil, ...
else
return ...
end
end
-- AceConsole:GetArgs(string, numargs, startpos)
--
-- Retreive one or more space-separated arguments from a string.
-- Treats quoted strings and itemlinks as non-spaced.
--
-- string - The raw argument string
-- numargs - How many arguments to get (default 1)
-- startpos - Where in the string to start scanning (default 1)
--
-- Returns arg1, arg2, ..., stringremainder
-- Missing arguments will be returned as nils. 'stringremainder' is returned as "" at the end.
function AceConsole:GetArgs(str, numargs, startpos)
numargs = numargs or 1
startpos = max(startpos or 1, 1)
if numargs<1 then
return strsub(str, startpos)
end
local pos=startpos
-- find start of new arg
pos = strfind(str, "[^ ]", pos)
if not pos then -- whoops, end of string
return nils(numargs, "")
end
-- quoted or space separated? find out which pattern to use
local delim_or_pipe
local ch = strsub(str, pos, pos)
if ch=='"' then
pos = pos + 1
delim_or_pipe='([|"])'
elseif ch=="'" then
pos = pos + 1
delim_or_pipe="([|'])"
else
delim_or_pipe="([| ])"
end
startpos = pos
while true do
-- find delimiter or hyperlink
local ch,_
pos,_,ch = strfind(str, delim_or_pipe, pos)
if not pos then break end
if ch=="|" then
-- some kind of escape
if strsub(str,pos,pos+1)=="|H" then
-- It's a |H....|hhyper link!|h
pos=strfind(str, "|h", pos+2) -- first |h
if not pos then break end
pos=strfind(str, "|h", pos+2) -- second |h
if not pos then break end
end
pos=pos+2 -- skip past this escape (last |h if it was a hyperlink)
else
-- found delimiter, done with this arg
return strsub(str, startpos, pos-1), AceConsole:GetArgs(str, numargs-1, pos+1)
end
end
-- search aborted, we hit end of string. return it all as one argument. (yes, even if it's an unterminated quote or hyperlink)
return strsub(str, startpos), nils(numargs-1, "")
end
--- embedding and embed handling
local mixins = {
"Print",
"RegisterChatCommand",
"UnregisterChatCommand",
"GetArgs",
}
-- AceConsole:Embed( target )
-- target (object) - target object to embed AceBucket in
--
-- Embeds AceConsole into the target object making the functions from the mixins list available on target:..
function AceConsole:Embed( target )
for k, v in pairs( mixins ) do
target[v] = self[v]
end
self.embeds[target] = true
end
function AceConsole:OnEmbedEnable( target )
if AceConsole.weakcommands[target] then
for command, func in pairs( AceConsole.weakcommands[target] ) do
target:RegisterChatCommand( command, func, false, true ) -- nonpersisting and silent registry
end
end
end
function AceConsole:OnEmbedDisable( target )
if AceConsole.weakcommands[target] then
for command, func in pairs( AceConsole.weakcommands[target] ) do
target:UnregisterChatCommand( command ) -- TODO: this could potentially unregister a command from another application in case of command conflicts. Do we care?
end
end
end
for addon in pairs(AceConsole.embeds) do
AceConsole:Embed(addon)
end
|
Ace3: AceConsole-3.0 - bugfix UnregisterChatCommand
|
Ace3: AceConsole-3.0 - bugfix UnregisterChatCommand
git-svn-id: 00c2b8bc9b083c53e126de03a83516ee6a3b87d9@162 5debad98-a965-4143-8383-f471b3509dcf
|
Lua
|
bsd-3-clause
|
sarahgerweck/Ace3
|
1401c4ef98fcb798a1b2803e5482f7c536c2ab03
|
test_scripts/iAP2TransportSwitch/common.lua
|
test_scripts/iAP2TransportSwitch/common.lua
|
---------------------------------------------------------------------------------------------------
-- iAP2TransportSwitch common module
---------------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.defaultProtocolVersion = 2
--[[ Required Shared libraries ]]
local commonFunctions = require("user_modules/shared_testcases/commonFunctions")
local commonSteps = require("user_modules/shared_testcases/commonSteps")
local SDL = require("SDL")
local commonPreconditions = require("user_modules/shared_testcases/commonPreconditions")
local tcp = require("tcp_connection")
local file_connection = require("file_connection")
local mobile = require("mobile_connection")
local events = require("events")
local expectations = require('expectations')
local hmi_values = require('user_modules/hmi_values')
local module = require("user_modules/dummy_connecttest")
--[[ Local Variables ]]
local Expectation = expectations.Expectation
local m = {}
m.device = {
bluetooth = {
id = "127.0.0.1",
port = 23456,
out = "iap2bt.out",
type = "BLUETOOTH"
},
usb = {
id = "127.0.0.1",
port = 34567,
out = "iap2usb.out",
type = "USB_IOS"
}
}
m.appParams = config["application1"].registerAppInterfaceParams
function module:start()
local pHMIParams = hmi_values.getDefaultHMITable()
pHMIParams.BasicCommunication.UpdateDeviceList.mandatory = true
pHMIParams.BasicCommunication.UpdateDeviceList.pinned = false
self:runSDL()
commonFunctions:waitForSDLStart(self)
:Do(function()
self:initHMI(self)
:Do(function()
commonFunctions:userPrint(35, "HMI initialized")
self:initHMI_onReady(pHMIParams)
:Do(function()
commonFunctions:userPrint(35, "HMI is ready")
end)
end)
end)
end
function module:waitForAllEvents(pTimeout)
local event = events.Event()
event.matches = function(self, e) return self == e end
EXPECT_HMIEVENT(event, "Delayed event"):Timeout(pTimeout + 1000)
local function toRun()
event_dispatcher:RaiseEvent(self.hmiConnection, event)
end
RUN_AFTER(toRun, pTimeout)
end
function module:expectEvent(pEvent, pName, pDevice)
local ret = Expectation(pName, pDevice)
ret.event = pEvent
event_dispatcher:AddEvent(pDevice, pEvent, ret)
self:AddExpectation(ret)
return ret
end
function module:createIAP2Device(pDeviceId, pDevicePort, pDeviceOut)
local connection = tcp.Connection(pDeviceId, pDevicePort)
local fileConnection = file_connection.FileConnection(pDeviceOut, connection)
local device = mobile.MobileConnection(fileConnection)
event_dispatcher:AddConnection(device)
return device
end
function module:connectMobile(pDevice)
module:expectEvent(events.disconnectedEvent, "Disconnected", pDevice)
:Pin()
:Times(AnyNumber())
:Do(function()
print("Device disconnected: " .. pDevice.connection.filename)
end)
pDevice:Connect()
return module:expectEvent(events.connectedEvent, "Connected", pDevice)
end
function m.preconditions()
local ptFileName = commonFunctions:read_parameter_from_smart_device_link_ini("PreloadedPT")
local ptName = "files/jsons/sdl_preloaded_pt_all_allowed.json"
commonFunctions:SDLForceStop()
commonSteps:DeleteLogsFiles()
commonSteps:DeletePolicyTable()
commonPreconditions:BackupFile(ptFileName)
os.execute("cp -f " .. ptName .. " " .. commonPreconditions:GetPathToSDL() .. "/" .. ptFileName)
commonFunctions:SetValuesInIniFile("AppTransportChangeTimer%s-=%s-[%d]-%s-\n", "AppTransportChangeTimer", "5000")
end
function m.postconditions()
SDL:StopSDL()
local ptFileName = commonFunctions:read_parameter_from_smart_device_link_ini("PreloadedPT")
commonPreconditions:RestoreFile(ptFileName)
end
function m:start()
module.start(self)
end
function m.print(pMsg)
commonFunctions:userPrint(35, pMsg)
end
return m
|
---------------------------------------------------------------------------------------------------
-- iAP2TransportSwitch common module
---------------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.defaultProtocolVersion = 2
--[[ Required Shared libraries ]]
local commonFunctions = require("user_modules/shared_testcases/commonFunctions")
local commonSteps = require("user_modules/shared_testcases/commonSteps")
local SDL = require("SDL")
local commonPreconditions = require("user_modules/shared_testcases/commonPreconditions")
local tcp = require("tcp_connection")
local file_connection = require("file_connection")
local mobile = require("mobile_connection")
local events = require("events")
local expectations = require('expectations')
local hmi_values = require('user_modules/hmi_values')
local module = require("user_modules/dummy_connecttest")
--[[ Local Variables ]]
local Expectation = expectations.Expectation
local m = {}
m.device = {
bluetooth = {
id = "127.0.0.1",
port = 23456,
out = "iap2bt.out",
type = "BLUETOOTH"
},
usb = {
id = "127.0.0.1",
port = 34567,
out = "iap2usb.out",
type = "USB_IOS"
}
}
m.appParams = config["application1"].registerAppInterfaceParams
function module:start()
self:runSDL()
commonFunctions:waitForSDLStart(self)
:Do(function()
self:initHMI(self)
:Do(function()
commonFunctions:userPrint(35, "HMI initialized")
self:initHMI_onReady()
:Do(function()
commonFunctions:userPrint(35, "HMI is ready")
end)
end)
end)
end
function module:waitForAllEvents(pTimeout)
local event = events.Event()
event.matches = function(self, e) return self == e end
EXPECT_HMIEVENT(event, "Delayed event"):Timeout(pTimeout + 1000)
local function toRun()
event_dispatcher:RaiseEvent(self.hmiConnection, event)
end
RUN_AFTER(toRun, pTimeout)
end
function module:expectEvent(pEvent, pName, pDevice)
local ret = Expectation(pName, pDevice)
ret.event = pEvent
event_dispatcher:AddEvent(pDevice, pEvent, ret)
self:AddExpectation(ret)
return ret
end
function module:createIAP2Device(pDeviceId, pDevicePort, pDeviceOut)
local connection = tcp.Connection(pDeviceId, pDevicePort)
local fileConnection = file_connection.FileConnection(pDeviceOut, connection)
local device = mobile.MobileConnection(fileConnection)
event_dispatcher:AddConnection(device)
return device
end
function module:connectMobile(pDevice)
module:expectEvent(events.disconnectedEvent, "Disconnected", pDevice)
:Pin()
:Times(AnyNumber())
:Do(function()
print("Device disconnected: " .. pDevice.connection.filename)
end)
pDevice:Connect()
return module:expectEvent(events.connectedEvent, "Connected", pDevice)
end
function m.preconditions()
local ptFileName = commonFunctions:read_parameter_from_smart_device_link_ini("PreloadedPT")
local ptName = "files/jsons/sdl_preloaded_pt_all_allowed.json"
commonFunctions:SDLForceStop()
commonSteps:DeleteLogsFiles()
commonSteps:DeletePolicyTable()
commonPreconditions:BackupFile(ptFileName)
os.execute("cp -f " .. ptName .. " " .. commonPreconditions:GetPathToSDL() .. "/" .. ptFileName)
commonFunctions:SetValuesInIniFile("AppTransportChangeTimer%s-=%s-[%d]-%s-\n", "AppTransportChangeTimer", "5000")
end
function m.postconditions()
SDL:StopSDL()
local ptFileName = commonFunctions:read_parameter_from_smart_device_link_ini("PreloadedPT")
commonPreconditions:RestoreFile(ptFileName)
end
function m:start()
module.start(self)
end
function m.print(pMsg)
commonFunctions:userPrint(35, pMsg)
end
return m
|
iAP2 Transport Switch: Fix issue regarding enabled bluetooth device
|
iAP2 Transport Switch: Fix issue regarding enabled bluetooth device
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
7ce75e0da02edcd192af5288716ebedca92408c7
|
tundra.lua
|
tundra.lua
|
-- Copyright 2010 Andreas Fredriksson
--
-- This file is part of Tundra.
--
-- Tundra is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Tundra is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Tundra. If not, see <http://www.gnu.org/licenses/>.
-- tundra.lua - Self-hosting build file for Tundra itself
local common = {
Env = { CPPPATH = { "src", "lua/src" } },
}
Build {
Units = "units.lua",
Configs = {
Config { Name = "macosx-clang", Inherit = common, Tools = { "clang-osx" }, DefaultOnHost = "macosx" },
Config { Name = "macosx-gcc", Inherit = common, Tools = { "gcc-osx" } },
Config { Name = "win32-msvc", Inherit = common, Tools = { { "msvc-vs2008"; TargetArch = "x86"} } },
Config { Name = "win64-msvc", Inherit = common, Tools = { { "msvc-vs2008"; TargetArch = "x64"} } },
Config { Name = "linux-gcc", Inherit = common, Tools = { "gcc" } },
-- MingW32 cross compilation under OS X
Config {
Name = "macosx-mingw32",
Inherit = common,
Tools = { "gcc" },
Env = {
_GCC_BINPREFIX="/usr/local/i386-mingw32-4.3.0/bin/i386-mingw32-",
CCOPTS = "-Werror",
},
ReplaceEnv = {
PROGSUFFIX=".exe",
SHLIBSUFFIX=".dll",
},
},
},
}
|
-- Copyright 2010 Andreas Fredriksson
--
-- This file is part of Tundra.
--
-- Tundra is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Tundra is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Tundra. If not, see <http://www.gnu.org/licenses/>.
-- tundra.lua - Self-hosting build file for Tundra itself
local common = {
Env = { CPPPATH = { "src", "lua/src" } },
}
local common_win32 = {
Inherit = common,
Env = {
CCOPTS = { "/WX", "/wd4127", "/wd4100", "/wd4324" },
CPPDEFS = { "_CRT_SECURE_NO_WARNINGS" },
LIBS = { "kernel32.lib", "advapi32.lib" },
},
}
Build {
Units = "units.lua",
Configs = {
Config { Name = "macosx-clang", Inherit = common, Tools = { "clang-osx" }, DefaultOnHost = "macosx" },
Config { Name = "macosx-gcc", Inherit = common, Tools = { "gcc-osx" } },
Config { Name = "win32-msvc", Inherit = common_win32, Tools = { { "msvc-vs2008"; TargetArch = "x86"} } },
Config { Name = "win64-msvc", Inherit = common_win32, Tools = { { "msvc-vs2008"; TargetArch = "x64"} } },
Config { Name = "linux-gcc", Inherit = common, Tools = { "gcc" } },
-- MingW32 cross compilation under OS X
Config {
Name = "macosx-mingw32",
Inherit = common,
Tools = { "gcc" },
Env = {
_GCC_BINPREFIX="/usr/local/i386-mingw32-4.3.0/bin/i386-mingw32-",
CCOPTS = "-Werror",
},
ReplaceEnv = {
PROGSUFFIX=".exe",
SHLIBSUFFIX=".dll",
},
},
},
}
|
Fixed tundra self-build on win32/msvc.
|
Fixed tundra self-build on win32/msvc.
|
Lua
|
mit
|
bmharper/tundra,bmharper/tundra,bmharper/tundra,deplinenoise/tundra,deplinenoise/tundra,deplinenoise/tundra,bmharper/tundra
|
479b03a24c932312de9f0ffc89bed573150985fb
|
modules/admin-full/luasrc/model/cbi/admin_index/luci.lua
|
modules/admin-full/luasrc/model/cbi/admin_index/luci.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2010 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.config")
m = Map("luci", translate("Web <abbr title=\"User Interface\">UI</abbr>"), translate("Here you can customize the settings and the functionality of <abbr title=\"Lua Configuration Interface\">LuCI</abbr>."))
local fs = require "nixio.fs"
-- force reload of global luci config namespace to reflect the changes
function m.commit_handler(self)
package.loaded["luci.config"] = nil
require("luci.config")
end
c = m:section(NamedSection, "main", "core", translate("General"))
l = c:option(ListValue, "lang", translate("Language"))
l:value("auto")
local i18ndir = luci.i18n.i18ndir .. "base."
for k, v in luci.util.kspairs(luci.config.languages) do
local file = i18ndir .. k:gsub("_", "-")
if k:sub(1, 1) ~= "." and fs.access(file .. ".lmo") then
l:value(k, v)
end
end
t = c:option(ListValue, "mediaurlbase", translate("Design"))
for k, v in pairs(luci.config.themes) do
if k:sub(1, 1) ~= "." then
t:value(v, k)
end
end
u = m:section(NamedSection, "uci_oncommit", "event", translate("Post-commit actions"),
translate("These commands will be executed automatically when a given <abbr title=\"Unified Configuration Interface\">UCI</abbr> configuration is committed allowing changes to be applied instantly."))
u.dynamic = true
f = m:section(NamedSection, "main", "core", translate("Files to be kept when flashing a new firmware"))
f:tab("detected", translate("Detected Files"),
translate("The following files are detected by the system and will be kept automatically during sysupgrade"))
f:tab("custom", translate("Custom Files"),
translate("This is a list of shell glob patterns for matching files and directories to include during sysupgrade"))
d = f:taboption("detected", DummyValue, "_detected", translate("Detected files"))
d.rawhtml = true
d.cfgvalue = function(s)
local list = io.popen(
"( find $(sed -ne '/^[[:space:]]*$/d; /^#/d; p' /etc/sysupgrade.conf " ..
"/lib/upgrade/keep.d/* 2>/dev/null) -type f 2>/dev/null; " ..
"opkg list-changed-conffiles ) | sort -u"
)
if list then
local files = { "<ul>" }
while true do
local ln = list:read("*l")
if not ln then
break
else
files[#files+1] = "<li>"
files[#files+1] = luci.util.pcdata(ln)
files[#files+1] = "</li>"
end
end
list:close()
files[#files+1] = "</ul>"
return table.concat(files, "")
end
return "<em>" .. translate("No files found") .. "</em>"
end
c = f:taboption("custom", TextValue, "_custom", translate("Custom files"))
c.rmempty = false
c.cols = 70
c.rows = 30
c.cfgvalue = function(self, section)
return nixio.fs.readfile("/etc/sysupgrade.conf")
end
c.write = function(self, section, value)
return nixio.fs.writefile("/etc/sysupgrade.conf", value)
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2010 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.config")
m = Map("luci", translate("Web <abbr title=\"User Interface\">UI</abbr>"), translate("Here you can customize the settings and the functionality of <abbr title=\"Lua Configuration Interface\">LuCI</abbr>."))
local fs = require "nixio.fs"
-- force reload of global luci config namespace to reflect the changes
function m.commit_handler(self)
package.loaded["luci.config"] = nil
require("luci.config")
end
c = m:section(NamedSection, "main", "core", translate("General"))
l = c:option(ListValue, "lang", translate("Language"))
l:value("auto")
local i18ndir = luci.i18n.i18ndir .. "base."
for k, v in luci.util.kspairs(luci.config.languages) do
local file = i18ndir .. k:gsub("_", "-")
if k:sub(1, 1) ~= "." and fs.access(file .. ".lmo") then
l:value(k, v)
end
end
t = c:option(ListValue, "mediaurlbase", translate("Design"))
for k, v in pairs(luci.config.themes) do
if k:sub(1, 1) ~= "." then
t:value(v, k)
end
end
u = m:section(NamedSection, "uci_oncommit", "event", translate("Post-commit actions"),
translate("These commands will be executed automatically when a given <abbr title=\"Unified Configuration Interface\">UCI</abbr> configuration is committed allowing changes to be applied instantly."))
u.dynamic = true
f = m:section(NamedSection, "main", "core", translate("Files to be kept when flashing a new firmware"))
f:tab("detected", translate("Detected Files"),
translate("The following files are detected by the system and will be kept automatically during sysupgrade"))
f:tab("custom", translate("Custom Files"),
translate("This is a list of shell glob patterns for matching files and directories to include during sysupgrade"))
d = f:taboption("detected", DummyValue, "_detected", translate("Detected files"))
d.rawhtml = true
d.cfgvalue = function(s)
local list = io.popen(
"( find $(sed -ne '/^[[:space:]]*$/d; /^#/d; p' /etc/sysupgrade.conf " ..
"/lib/upgrade/keep.d/* 2>/dev/null) -type f 2>/dev/null; " ..
"opkg list-changed-conffiles ) | sort -u"
)
if list then
local files = { "<ul>" }
while true do
local ln = list:read("*l")
if not ln then
break
else
files[#files+1] = "<li>"
files[#files+1] = luci.util.pcdata(ln)
files[#files+1] = "</li>"
end
end
list:close()
files[#files+1] = "</ul>"
return table.concat(files, "")
end
return "<em>" .. translate("No files found") .. "</em>"
end
c = f:taboption("custom", TextValue, "_custom", translate("Custom files"))
c.rmempty = false
c.cols = 70
c.rows = 30
c.cfgvalue = function(self, section)
return nixio.fs.readfile("/etc/sysupgrade.conf")
end
c.write = function(self, section, value)
value = value:gsub("\r\n?", "\n")
return nixio.fs.writefile("/etc/sysupgrade.conf", value)
end
return m
|
modules/admin-full: fixup newlines when storing sysupgrade.conf
|
modules/admin-full: fixup newlines when storing sysupgrade.conf
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@6698 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
|
c3568a025aa895e92c0cc71c86c2bb210623fa69
|
src_trunk/resources/lves-system/s_lves_system.lua
|
src_trunk/resources/lves-system/s_lves_system.lua
|
-- ////////////////////////////////////
-- // MYSQL //
-- ////////////////////////////////////
sqlUsername = exports.mysql:getMySQLUsername()
sqlPassword = exports.mysql:getMySQLPassword()
sqlDB = exports.mysql:getMySQLDBName()
sqlHost = exports.mysql:getMySQLHost()
sqlPort = exports.mysql:getMySQLPort()
handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort)
function checkMySQL()
if not (mysql_ping(handler)) then
handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort)
end
end
setTimer(checkMySQL, 300000, 0)
function closeMySQL()
if (handler) then
mysql_close(handler)
end
end
addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL)
-- ////////////////////////////////////
-- // MYSQL END //
-- ////////////////////////////////////
function playerDeath()
outputChatBox("Respawn in 10 seconds.", source)
setTimer(respawnPlayer, 10000, 1, source)
end
addEventHandler("onPlayerWasted", getRootElement(), playerDeath)
function respawnPlayer(thePlayer)
if (isElement(thePlayer)) then
local cost = 0
if not exports.global:isPlayerSilverDonator(thePlayer) then
_, cost = exports.global:takeMoney(thePlayer, math.random(150, 300), true)
end
local tax = exports.global:getTaxAmount()
exports.global:giveMoney( getTeamFromName("Los Santos Emergency Services"), math.ceil((1-tax)*cost) )
exports.global:giveMoney( getTeamFromName("Government of Los Santos"), math.ceil(tax*cost) )
local update = mysql_query(handler, "UPDATE characters SET deaths = deaths + 1 WHERE charactername='" .. mysql_escape_string(handler, getPlayerName(thePlayer)) .. "'")
if (update) then
mysql_free_result(update)
end
setCameraInterior(thePlayer, 0)
local text = "You have recieved treatment from the Los Santos Emergency Services."
if cost > 0 then
text = text .. " Cost: " .. cost .. "$"
end
outputChatBox(text, thePlayer, 255, 255, 0)
-- take all drugs
local count = 0
for i = 30, 43 do
while exports.global:hasItem(thePlayer, i) do
exports.global:takeItem(thePlayer, i)
count = count + 1
end
end
if count > 0 then
outputChatBox("LSES Employee: We handed your drugs over to the LSPD Investigators.", thePlayer, 255, 194, 14)
end
local theSkin = getPedSkin(thePlayer)
local theTeam = getPlayerTeam(thePlayer)
local fat = getPedStat(thePlayer, 21)
local muscle = getPedStat(thePlayer, 23)
setPedStat(thePlayer, 21, fat)
setPedStat(thePlayer, 23, muscle)
spawnPlayer(thePlayer, 1183.291015625, -1323.033203125, 13.577140808105, 267.4580078125, theSkin, 0, 0, theTeam)
fadeCamera(thePlayer, true, 2)
end
end
function deathRemoveWeapons(weapons, removedWeapons)
setTimer(giveGunsBack, 10005, 1, source, weapons, removedWeapons)
end
addEvent("onDeathRemovePlayerWeapons", true)
addEventHandler("onDeathRemovePlayerWeapons", getRootElement(), deathRemoveWeapons)
function giveGunsBack(thePlayer, weapons, removedWeapons)
if (removedWeapons~=nil) then
if tonumber(getElementData(thePlayer, "license.gun")) == 0 and getElementData(getPlayerTeam(thePlayer),"type") ~= 2 then
outputChatBox("LSES Employee: We have taken away weapons which you did not have a license for. (" .. removedWeapons .. ").", thePlayer, 255, 194, 14)
else
outputChatBox("LSES Employee: We have taken away weapons which you are not allowed to carry. (" .. removedWeapons .. ").", thePlayer, 255, 194, 14)
end
end
for key, value in ipairs(weapons) do
local weapon = tonumber(weapons[key][1])
local ammo = tonumber(weapons[key][2])
local removed = tonumber(weapons[key][3])
if (removed==0) then
exports.global:giveWeapon(thePlayer, weapon, math.floor( ammo / 2 ), false)
else
exports.global:takeWeapon(thePlayer, weapon)
end
end
end
|
-- ////////////////////////////////////
-- // MYSQL //
-- ////////////////////////////////////
sqlUsername = exports.mysql:getMySQLUsername()
sqlPassword = exports.mysql:getMySQLPassword()
sqlDB = exports.mysql:getMySQLDBName()
sqlHost = exports.mysql:getMySQLHost()
sqlPort = exports.mysql:getMySQLPort()
handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort)
function checkMySQL()
if not (mysql_ping(handler)) then
handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort)
end
end
setTimer(checkMySQL, 300000, 0)
function closeMySQL()
if (handler) then
mysql_close(handler)
end
end
addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL)
-- ////////////////////////////////////
-- // MYSQL END //
-- ////////////////////////////////////
function playerDeath()
outputChatBox("Respawn in 10 seconds.", source)
setTimer(respawnPlayer, 10000, 1, source)
end
addEventHandler("onPlayerWasted", getRootElement(), playerDeath)
function respawnPlayer(thePlayer)
if (isElement(thePlayer)) then
local cost = math.random(150, 300)
if not exports.global:isPlayerSilverDonator(thePlayer) then
exports.global:takeMoney(thePlayer, cost, true)
end
local tax = exports.global:getTaxAmount()
exports.global:giveMoney( getTeamFromName("Los Santos Emergency Services"), math.ceil((1-tax)*cost) )
exports.global:giveMoney( getTeamFromName("Government of Los Santos"), math.ceil(tax*cost) )
local update = mysql_query(handler, "UPDATE characters SET deaths = deaths + 1 WHERE charactername='" .. mysql_escape_string(handler, getPlayerName(thePlayer)) .. "'")
if (update) then
mysql_free_result(update)
end
setCameraInterior(thePlayer, 0)
local text = "You have recieved treatment from the Los Santos Emergency Services."
if cost > 0 then
text = text .. " Cost: " .. cost .. "$"
end
outputChatBox(text, thePlayer, 255, 255, 0)
-- take all drugs
local count = 0
for i = 30, 43 do
while exports.global:hasItem(thePlayer, i) do
exports.global:takeItem(thePlayer, i)
count = count + 1
end
end
if count > 0 then
outputChatBox("LSES Employee: We handed your drugs over to the LSPD Investigators.", thePlayer, 255, 194, 14)
end
local theSkin = getPedSkin(thePlayer)
local theTeam = getPlayerTeam(thePlayer)
local fat = getPedStat(thePlayer, 21)
local muscle = getPedStat(thePlayer, 23)
setPedStat(thePlayer, 21, fat)
setPedStat(thePlayer, 23, muscle)
spawnPlayer(thePlayer, 1183.291015625, -1323.033203125, 13.577140808105, 267.4580078125, theSkin, 0, 0, theTeam)
fadeCamera(thePlayer, true, 2)
end
end
function deathRemoveWeapons(weapons, removedWeapons)
setTimer(giveGunsBack, 10005, 1, source, weapons, removedWeapons)
end
addEvent("onDeathRemovePlayerWeapons", true)
addEventHandler("onDeathRemovePlayerWeapons", getRootElement(), deathRemoveWeapons)
function giveGunsBack(thePlayer, weapons, removedWeapons)
if (removedWeapons~=nil) then
if tonumber(getElementData(thePlayer, "license.gun")) == 0 and getElementData(getPlayerTeam(thePlayer),"type") ~= 2 then
outputChatBox("LSES Employee: We have taken away weapons which you did not have a license for. (" .. removedWeapons .. ").", thePlayer, 255, 194, 14)
else
outputChatBox("LSES Employee: We have taken away weapons which you are not allowed to carry. (" .. removedWeapons .. ").", thePlayer, 255, 194, 14)
end
end
for key, value in ipairs(weapons) do
local weapon = tonumber(weapons[key][1])
local ammo = tonumber(weapons[key][2])
local removed = tonumber(weapons[key][3])
if (removed==0) then
exports.global:giveWeapon(thePlayer, weapon, math.floor( ammo / 2 ), false)
else
exports.global:takeWeapon(thePlayer, weapon)
end
end
end
|
Bug fix for dying
|
Bug fix for dying
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1862 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
ffb1c49f489ad1bbb4330e47a80b629ec10c35b0
|
slashcmd.lua
|
slashcmd.lua
|
SLASH_PFDB1, SLASH_PFDB2, SLASH_PFDB3, SLASH_PFDB4 = "/db", "/shagu", "/pfquest", "/pfdb"
SlashCmdList["PFDB"] = function(input, editbox)
local params = {}
local meta = { ["addon"] = "PFDB" }
if (input == "" or input == nil) then
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffccpf|cffffffffQuest (v" .. tostring(GetAddOnMetadata("pfQuest", "Version")) .. "):")
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff show |cffcccccc - " .. pfQuest_Loc["show database interface"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff config |cffcccccc - " .. pfQuest_Loc["show configuration interface"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff unit <unit> |cffcccccc - " .. pfQuest_Loc["search units"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff object <gameobject> |cffcccccc - " .. pfQuest_Loc["search objects"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff item <item> |cffcccccc - " .. pfQuest_Loc["search loot"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff vendor <item> |cffcccccc - " .. pfQuest_Loc["vendors for item"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff quest <questname> |cffcccccc - " .. pfQuest_Loc["show specific questgiver"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff quests |cffcccccc - " .. pfQuest_Loc["show all quests on the map"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff clean |cffcccccc - " .. pfQuest_Loc["clean map"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff locale |cffcccccc - " .. pfQuest_Loc["display the addon locales"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff meta <relation> [min, [max]] |cffcccccc - " .. pfQuest_Loc["show related objects on the map"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff scan |cffcccccc - " .. pfQuest_Loc["scan the server for items"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc ->|cffffffff " .. pfQuest_Loc["Available relations"] .. ": |cff33ffccchests|r, |cff33ffccherbs|r, |cff33ffccmines|r")
return
end
local commandlist = { }
local command
for command in string.gfind(input, "[^ ]+") do
table.insert(commandlist, command)
end
local arg1, arg2 = commandlist[1], ""
-- handle whitespace mob- and item names correctly
for i in commandlist do
if (i ~= 1) then
arg2 = arg2 .. commandlist[i]
if (commandlist[i+1] ~= nil) then
arg2 = arg2 .. " "
end
end
end
-- argument: item
if (arg1 == "item") then
local maps = pfDatabase:SearchItem(arg2, meta, "LOWER")
pfMap:ShowMapID(pfDatabase:GetBestMap(maps))
return
end
-- argument: vendor
if (arg1 == "vendor") then
local maps = pfDatabase:SearchVendor(arg2, meta, "LOWER")
pfMap:ShowMapID(pfDatabase:GetBestMap(maps))
return
end
-- argument: unit
if (arg1 == "unit") then
local maps = pfDatabase:SearchMob(arg2, meta, "LOWER")
pfMap:ShowMapID(pfDatabase:GetBestMap(maps))
return
end
-- argument: object
if (arg1 == "object") then
local maps = pfDatabase:SearchObject(arg2, meta, "LOWER")
pfMap:ShowMapID(pfDatabase:GetBestMap(maps))
return
end
-- argument: quest
if (arg1 == "quest") then
local maps = pfDatabase:SearchQuest(arg2, meta, "LOWER")
pfMap:ShowMapID(pfDatabase:GetBestMap(maps))
return
end
-- argument: quests
if (arg1 == "quests") then
local maps = pfDatabase:SearchQuests(meta)
pfMap:UpdateNodes()
return
end
-- argument: meta
if (arg1 == "meta") then
local maps = pfDatabase:SearchMetaRelation({ commandlist[2], commandlist[3], commandlist[4] }, meta)
pfMap:ShowMapID(pfDatabase:GetBestMap(maps))
return
end
-- argument: clean
if (arg1 == "clean") then
pfMap:DeleteNode("PFDB")
pfMap:UpdateNodes()
return
end
-- argument: show
if (arg1 == "show") then
if pfBrowser then pfBrowser:Show() end
return
end
-- argument: show
if (arg1 == "config") then
if pfQuestConfig then pfQuestConfig:Show() end
return
end
-- argument: locale
if (arg1 == "locale") then
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffccLocales|r:" .. pfDatabase.dbstring)
return
end
-- argument: scan
if (arg1 == "scan") then
pfDatabase:ScanServer()
return
end
-- argument: <text>
if (type(arg1)=="string") then
if pfBrowser then
pfBrowser:Show()
pfBrowser.input:SetText(string.format("%s %s",arg1,arg2))
end
return
end
end
|
SLASH_PFDB1, SLASH_PFDB2, SLASH_PFDB3, SLASH_PFDB4 = "/db", "/shagu", "/pfquest", "/pfdb"
SlashCmdList["PFDB"] = function(input, editbox)
local params = {}
local meta = { ["addon"] = "PFDB" }
if (input == "" or input == nil) then
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffccpf|cffffffffQuest (v" .. tostring(GetAddOnMetadata("pfQuest", "Version")) .. "):")
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff show |cffcccccc - " .. pfQuest_Loc["show database interface"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff config |cffcccccc - " .. pfQuest_Loc["show configuration interface"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff unit <unit> |cffcccccc - " .. pfQuest_Loc["search units"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff object <gameobject> |cffcccccc - " .. pfQuest_Loc["search objects"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff item <item> |cffcccccc - " .. pfQuest_Loc["search loot"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff vendor <item> |cffcccccc - " .. pfQuest_Loc["vendors for item"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff quest <questname> |cffcccccc - " .. pfQuest_Loc["show specific questgiver"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff quests |cffcccccc - " .. pfQuest_Loc["show all quests on the map"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff clean |cffcccccc - " .. pfQuest_Loc["clean map"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff locale |cffcccccc - " .. pfQuest_Loc["display the addon locales"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff meta <relation> [min, [max]] |cffcccccc - " .. pfQuest_Loc["show related objects on the map"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc/db|cffffffff scan |cffcccccc - " .. pfQuest_Loc["scan the server for items"])
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffcc ->|cffffffff " .. pfQuest_Loc["Available relations"] .. ": |cff33ffccchests|r, |cff33ffccherbs|r, |cff33ffccmines|r")
return
end
local commandlist = { }
local command
for command in string.gfind(input, "[^ ]+") do
table.insert(commandlist, command)
end
local arg1, arg2 = commandlist[1], ""
-- handle whitespace mob- and item names correctly
for i in commandlist do
if (i ~= 1) then
arg2 = arg2 .. commandlist[i]
if (commandlist[i+1] ~= nil) then
arg2 = arg2 .. " "
end
end
end
-- argument: item
if (arg1 == "item") then
local maps = pfDatabase:SearchItem(arg2, meta, "LOWER")
pfMap:ShowMapID(pfDatabase:GetBestMap(maps))
return
end
-- argument: vendor
if (arg1 == "vendor") then
local maps = pfDatabase:SearchVendor(arg2, meta, "LOWER")
pfMap:ShowMapID(pfDatabase:GetBestMap(maps))
return
end
-- argument: unit
if (arg1 == "unit") then
local maps = pfDatabase:SearchMob(arg2, meta, "LOWER")
pfMap:ShowMapID(pfDatabase:GetBestMap(maps))
return
end
-- argument: object
if (arg1 == "object") then
local maps = pfDatabase:SearchObject(arg2, meta, "LOWER")
pfMap:ShowMapID(pfDatabase:GetBestMap(maps))
return
end
-- argument: quest
if (arg1 == "quest") then
local maps = pfDatabase:SearchQuest(arg2, meta, "LOWER")
pfMap:ShowMapID(pfDatabase:GetBestMap(maps))
return
end
-- argument: quests
if (arg1 == "quests") then
local maps = pfDatabase:SearchQuests(meta)
pfMap:UpdateNodes()
return
end
-- argument: meta
if (arg1 == "meta") then
local maps = pfDatabase:SearchMetaRelation({ commandlist[2], commandlist[3], commandlist[4] }, meta)
pfMap:ShowMapID(pfDatabase:GetBestMap(maps))
return
end
-- argument: clean
if (arg1 == "clean") then
pfMap:DeleteNode("PFDB")
pfMap:UpdateNodes()
return
end
-- argument: show
if (arg1 == "show") then
if pfBrowser then pfBrowser:Show() end
return
end
-- argument: show
if (arg1 == "config") then
if pfQuestConfig then pfQuestConfig:Show() end
return
end
-- argument: locale
if (arg1 == "locale") then
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffccLocales|r:" .. pfDatabase.dbstring)
return
end
-- argument: scan
if (arg1 == "scan") then
pfDatabase:ScanServer()
return
end
-- argument: <text>
if (type(arg1)=="string") then
if pfBrowser then
pfBrowser:Show()
pfBrowser.input:SetText((string.gsub(string.format("%s %s",arg1,arg2),"^%s*(.-)%s*$", "%1")))
end
return
end
end
|
slashcmd: fix whitespace issue for gui search
|
slashcmd: fix whitespace issue for gui search
Thanks @Road-block
|
Lua
|
mit
|
shagu/pfQuest
|
3f5cd2ebb915f1fcdb91f648f487dd000481dd3c
|
build/premake5.lua
|
build/premake5.lua
|
function setTargetObjDir(outDir)
targetdir(outDir)
objdir(string.lower("../intermediate/%{cfg.shortname}/" .. _ACTION))
targetsuffix(string.lower("_%{cfg.shortname}_" .. _ACTION))
end
function copyfiles(dstDir, srcWildcard)
os.mkdir(dstDir)
local matches = os.matchfiles(srcWildcard)
for _, f in ipairs(matches) do
local filename = string.match(f, ".-([^\\/]-%.?[^%.\\/]*)$")
os.copyfile(f, dstDir .. "/" .. filename)
end
end
function gmake_common()
buildoptions "-march=native -Wall -Wextra"
links { "boost_system" }
if (os.findlib("boost_thread")) then
links { "boost_thread" }
elseif (os.findlib("boost_thread-mt")) then
links { "boost_thread-mt" }
end
if (os.findlib("boost_locale")) then
links { "boost_locale" }
elseif (os.findlib("boost_locale-mt")) then
links { "boost_locale-mt" }
end
if (os.findlib("PocoJSON")) then
defines { "HAS_POCO=1" }
links { "PocoFoundation", "PocoJSON" }
end
end
solution "benchmark"
configurations { "release" }
platforms { "x32", "x64" }
location ("./" .. (_ACTION or ""))
language "C++"
flags { "ExtraWarnings" }
defines { "__STDC_FORMAT_MACROS=1" }
configuration "release"
defines { "NDEBUG" }
optimize "Full"
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "gmake"
gmake_common()
project "jsonclibs"
kind "StaticLib"
includedirs {
"../thirdparty/",
"../thirdparty/include/",
"../thirdparty/ujson4c/3rdparty/",
"../thirdparty/udp-json-parser/"
}
files {
"../src/**.c",
}
setTargetObjDir("../bin")
copyfiles("../thirdparty/include/yajl", "../thirdparty/yajl/src/api/*.h")
project "nativejson"
kind "ConsoleApp"
includedirs {
"../thirdparty/",
"../thirdparty/casablanca/Release/include/",
"../thirdparty/casablanca/Release/src/pch",
"../thirdparty/fastjson/include/",
"../thirdparty/jsonbox/include/",
"../thirdparty/jsoncpp/include/",
"../thirdparty/rapidjson/include/",
"../thirdparty/udp-json-parser/",
"../thirdparty/include/",
"../thirdparty/json-voorhees/include",
"../thirdparty/json-voorhees/src",
"../thirdparty/jsoncons/src",
"../thirdparty/ArduinoJson/include",
"../thirdparty/include/jeayeson/include/dummy",
"../thirdparty/jvar/include",
}
files {
"../src/*.h",
"../src/*.cpp",
"../src/tests/*.cpp",
}
libdirs { "../bin" }
setTargetObjDir("../bin")
-- linkLib("jsonclibs")
links "jsonclibs"
configuration "gmake"
buildoptions "-std=c++14"
solution "jsonstat"
configurations { "release" }
platforms { "x32", "x64" }
location ("./" .. (_ACTION or ""))
language "C++"
flags { "ExtraWarnings" }
defines {
"USE_MEMORYSTAT=0",
"TEST_PARSE=1",
"TEST_STRINGIFY=0",
"TEST_PRETTIFY=0",
"TEST_TEST_STATISTICS=1",
"TEST_SAXROUNDTRIP=0",
"TEST_SAXSTATISTICS=0",
"TEST_SAXSTATISTICSUTF16=0",
"TEST_CONFORMANCE=0",
"TEST_INFO=0"
}
includedirs {
"../thirdparty/",
"../thirdparty/casablanca/Release/include/",
"../thirdparty/casablanca/Release/src/pch",
"../thirdparty/fastjson/include/",
"../thirdparty/jsonbox/include/",
"../thirdparty/jsoncpp/include/",
"../thirdparty/rapidjson/include/",
"../thirdparty/udp-json-parser/",
"../thirdparty/include/",
"../thirdparty/json-voorhees/include",
"../thirdparty/json-voorhees/src",
"../thirdparty/jsoncons/src",
"../thirdparty/ArduinoJson/include",
"../thirdparty/include/jeayeson/include/dummy",
"../thirdparty/jvar/include",
}
configuration "release"
defines { "NDEBUG" }
optimize "Full"
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "gmake"
gmake_common()
project "jsonclibs2"
kind "StaticLib"
includedirs {
"../thirdparty/",
"../thirdparty/include/",
"../thirdparty/ujson4c/3rdparty/",
"../thirdparty/udp-json-parser/"
}
files {
"../src/**.c",
}
setTargetObjDir("../bin/jsonstat")
copyfiles("../thirdparty/include/yajl", "../thirdparty/yajl/src/api/*.h")
local testfiles = os.matchfiles("../src/tests/*.cpp")
for _, testfile in ipairs(testfiles) do
project("jsonstat_" .. path.getbasename(testfile))
kind "ConsoleApp"
files {
"../src/jsonstat/jsonstatmain.cpp",
"../src/memorystat.cpp",
testfile
}
libdirs { "../bin/jsonstat" }
links "jsonclibs2"
setTargetObjDir("../bin/jsonstat")
configuration "gmake"
buildoptions "-std=c++14"
end
|
function setTargetObjDir(outDir)
targetdir(outDir)
objdir(string.lower("../intermediate/%{cfg.shortname}/" .. _ACTION))
targetsuffix(string.lower("_%{cfg.shortname}_" .. _ACTION))
end
function copyfiles(dstDir, srcWildcard)
os.mkdir(dstDir)
local matches = os.matchfiles(srcWildcard)
for _, f in ipairs(matches) do
local filename = string.match(f, ".-([^\\/]-%.?[^%.\\/]*)$")
os.copyfile(f, dstDir .. "/" .. filename)
end
end
function gmake_common()
buildoptions "-march=native -Wall -Wextra"
links { "boost_system" }
-- On some boost distributions, the naming contains -mt suffixes
if (os.findlib("boost_thread")) then
links { "boost_thread" }
elseif (os.findlib("boost_thread-mt")) then
links { "boost_thread-mt" }
end
if (os.findlib("boost_locale")) then
links { "boost_locale" }
elseif (os.findlib("boost_locale-mt")) then
links { "boost_locale-mt" }
end
-- For clock_gettime in jvar
if (os.findlib("rt")) then
links { "rt" }
end
if (os.findlib("PocoJSON")) then
defines { "HAS_POCO=1" }
links { "PocoFoundation", "PocoJSON" }
end
end
solution "benchmark"
configurations { "release" }
platforms { "x32", "x64" }
location ("./" .. (_ACTION or ""))
language "C++"
flags { "ExtraWarnings" }
defines { "__STDC_FORMAT_MACROS=1" }
configuration "release"
defines { "NDEBUG" }
optimize "Full"
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "gmake"
gmake_common()
project "jsonclibs"
kind "StaticLib"
includedirs {
"../thirdparty/",
"../thirdparty/include/",
"../thirdparty/ujson4c/3rdparty/",
"../thirdparty/udp-json-parser/"
}
files {
"../src/**.c",
}
setTargetObjDir("../bin")
copyfiles("../thirdparty/include/yajl", "../thirdparty/yajl/src/api/*.h")
project "nativejson"
kind "ConsoleApp"
includedirs {
"../thirdparty/",
"../thirdparty/casablanca/Release/include/",
"../thirdparty/casablanca/Release/src/pch",
"../thirdparty/fastjson/include/",
"../thirdparty/jsonbox/include/",
"../thirdparty/jsoncpp/include/",
"../thirdparty/rapidjson/include/",
"../thirdparty/udp-json-parser/",
"../thirdparty/include/",
"../thirdparty/json-voorhees/include",
"../thirdparty/json-voorhees/src",
"../thirdparty/jsoncons/src",
"../thirdparty/ArduinoJson/include",
"../thirdparty/include/jeayeson/include/dummy",
"../thirdparty/jvar/include",
}
files {
"../src/*.h",
"../src/*.cpp",
"../src/tests/*.cpp",
}
libdirs { "../bin" }
setTargetObjDir("../bin")
-- linkLib("jsonclibs")
links "jsonclibs"
configuration "gmake"
buildoptions "-std=c++14"
solution "jsonstat"
configurations { "release" }
platforms { "x32", "x64" }
location ("./" .. (_ACTION or ""))
language "C++"
flags { "ExtraWarnings" }
defines {
"USE_MEMORYSTAT=0",
"TEST_PARSE=1",
"TEST_STRINGIFY=0",
"TEST_PRETTIFY=0",
"TEST_TEST_STATISTICS=1",
"TEST_SAXROUNDTRIP=0",
"TEST_SAXSTATISTICS=0",
"TEST_SAXSTATISTICSUTF16=0",
"TEST_CONFORMANCE=0",
"TEST_INFO=0"
}
includedirs {
"../thirdparty/",
"../thirdparty/casablanca/Release/include/",
"../thirdparty/casablanca/Release/src/pch",
"../thirdparty/fastjson/include/",
"../thirdparty/jsonbox/include/",
"../thirdparty/jsoncpp/include/",
"../thirdparty/rapidjson/include/",
"../thirdparty/udp-json-parser/",
"../thirdparty/include/",
"../thirdparty/json-voorhees/include",
"../thirdparty/json-voorhees/src",
"../thirdparty/jsoncons/src",
"../thirdparty/ArduinoJson/include",
"../thirdparty/include/jeayeson/include/dummy",
"../thirdparty/jvar/include",
}
configuration "release"
defines { "NDEBUG" }
optimize "Full"
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "gmake"
gmake_common()
project "jsonclibs2"
kind "StaticLib"
includedirs {
"../thirdparty/",
"../thirdparty/include/",
"../thirdparty/ujson4c/3rdparty/",
"../thirdparty/udp-json-parser/"
}
files {
"../src/**.c",
}
setTargetObjDir("../bin/jsonstat")
copyfiles("../thirdparty/include/yajl", "../thirdparty/yajl/src/api/*.h")
local testfiles = os.matchfiles("../src/tests/*.cpp")
for _, testfile in ipairs(testfiles) do
project("jsonstat_" .. path.getbasename(testfile))
kind "ConsoleApp"
files {
"../src/jsonstat/jsonstatmain.cpp",
"../src/memorystat.cpp",
testfile
}
libdirs { "../bin/jsonstat" }
links "jsonclibs2"
setTargetObjDir("../bin/jsonstat")
configuration "gmake"
buildoptions "-std=c++14"
end
|
Try to fix clock_gettime link issue in gcc
|
Try to fix clock_gettime link issue in gcc
|
Lua
|
mit
|
miloyip/nativejson-benchmark,DavadDi/nativejson-benchmark,DavadDi/nativejson-benchmark,miloyip/nativejson-benchmark,miloyip/nativejson-benchmark,miloyip/nativejson-benchmark,DavadDi/nativejson-benchmark,miloyip/nativejson-benchmark,DavadDi/nativejson-benchmark,DavadDi/nativejson-benchmark
|
8414af5334bb89a671112bb904a6e230bd67c435
|
xmake/core/tools/tools.lua
|
xmake/core/tools/tools.lua
|
--!The Automatic Cross-platform Build Tool
--
-- XMake is free software; you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as published by
-- the Free Software Foundation; either version 2.1 of the License, or
-- (at your option) any later version.
--
-- XMake 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 XMake;
-- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a>
--
-- Copyright (C) 2009 - 2015, ruki All rights reserved.
--
-- @author ruki
-- @file tools.lua
--
-- define module: tools
local tools = tools or {}
-- load modules
local os = require("base/os")
local path = require("base/path")
local utils = require("base/utils")
local string = require("base/string")
local platform = require("base/platform")
-- match the tool name
function tools._match(name, toolname)
-- match full? ok
if name == toolname then return 100 end
-- match the name for windows? ok
if name:find("^" .. toolname .. "%.exe") then return 90 end
if name:find(toolname .. "%.exe") then return 85 end
-- match the last word? ok
if name:find(toolname .. "$") then return 80 end
-- match the partial word? ok
if name:find("%-" .. toolname) then return 60 end
-- contains it? ok
if name:find(toolname, 1, true) then return 30 end
-- not matched
return 0
end
-- find tool from the given root directory and name
function tools._find_from(root, name)
-- attempt to get it directly first
local filepath = string.format("%s/%s.lua", root, name)
if os.isfile(filepath) then
return filepath
end
-- make the lower name
name = name:lower()
-- get all tool files
local file_ok = nil
local score_maxn = 0
local files = os.match(string.format("%s/*.lua", root))
for _, file in ipairs(files) do
-- the tool name
local toolname = path.basename(file)
-- found it?
if toolname and toolname ~= "tools" then
-- match score
local score = tools._match(name, toolname:lower())
-- ok?
if score >= 100 then return file end
-- select the file with the max score
if score > score_maxn then
file_ok = file
score_maxn = score
end
end
end
-- ok?
return file_ok
end
-- probe it's absolute path if exists from the given tool name and root directory
function tools._probe(root, name)
-- check
assert(root and name)
-- make the tool path
local toolpath = string.format("%s/%s", root, name)
toolpath = path.translate(toolpath)
-- the tool exists? ok
if toolpath and os.isfile(toolpath) then
return toolpath
end
end
-- find tool from the given name and directory (optional)
function tools.find(name, root)
-- check
assert(name)
-- init filename
local filepath = nil
-- only find it from this directory if the given directory exists
if root then return tools._find_from(root, name) end
-- attempt to find it from the current platform directory first
if not filepath then filepath = tools._find_from(platform.directory() .. "/tools", name) end
-- attempt to find it from the script directory
if not filepath then filepath = tools._find_from(xmake._CORE_DIR .. "/tools", name) end
-- ok?
return filepath
end
-- load tool from the given name and directory (optional)
function tools.load(name, root)
-- check
assert(name)
-- get it directly from cache dirst
tools._TOOLS = tools._TOOLS or {}
if tools._TOOLS[name] then
return tools._TOOLS[name]
end
-- find the tool file path
local toolpath = tools.find(name, root)
-- not exists?
if not toolpath or not os.isfile(toolpath) then
return
end
-- load script
local script, errors = loadfile(toolpath)
if script then
-- load tool
local tool = script()
-- init tool
if tool and tool.init then
tool:init(name)
end
-- save tool to the cache
tools._TOOLS[name] = tool
-- ok?
return tool
else
utils.error(errors)
utils.error("load %s failed!", toolpath)
assert(false)
end
end
-- get the given tool script from the given kind
function tools.get(kind)
-- get the tool name
local toolname = platform.tool(kind)
if not toolname then
utils.error("cannot get tool name for %s", kind)
return
end
-- load it
return tools.load(toolname)
end
-- probe it's absolute path if exists from the given tool name
function tools.probe(name, dirs)
-- check
assert(name)
-- attempt to run it directly first
if os.execute(string.format("%s > %s 2>&1", name, xmake._NULDEV)) ~= 0x7f00 then
return name
end
-- attempt to get it from the given directories
if dirs then
for _, dir in ipairs(utils.wrap(dirs)) do
-- probe it
local toolpath = tools._probe(dir, name)
-- ok?
if toolpath and os.execute(string.format("%s > %s 2>&1", toolpath, xmake._NULDEV)) ~= 0x7f00 then
return toolpath
end
end
end
end
-- return module: tools
return tools
|
--!The Automatic Cross-platform Build Tool
--
-- XMake is free software; you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as published by
-- the Free Software Foundation; either version 2.1 of the License, or
-- (at your option) any later version.
--
-- XMake 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 XMake;
-- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a>
--
-- Copyright (C) 2009 - 2015, ruki All rights reserved.
--
-- @author ruki
-- @file tools.lua
--
-- define module: tools
local tools = tools or {}
-- load modules
local os = require("base/os")
local path = require("base/path")
local utils = require("base/utils")
local string = require("base/string")
local platform = require("base/platform")
-- match the tool name
function tools._match(name, toolname)
-- match full? ok
if name == toolname then return 100 end
-- match the last word? ok
if name:find(toolname .. "$") then return 80 end
-- match the partial word? ok
if name:find("%-" .. toolname) then return 60 end
-- contains it? ok
if name:find(toolname, 1, true) then return 30 end
-- not matched
return 0
end
-- find tool from the given root directory and name
function tools._find_from(root, name)
-- attempt to get it directly first
local filepath = string.format("%s/%s.lua", root, name)
if os.isfile(filepath) then
return filepath
end
-- make the lower name
name = name:lower()
-- get all tool files
local file_ok = nil
local score_maxn = 0
local files = os.match(string.format("%s/*.lua", root))
for _, file in ipairs(files) do
-- the tool name
local toolname = path.basename(file)
-- found it?
if toolname and toolname ~= "tools" then
-- match score
local score = tools._match(name, toolname:lower())
-- ok?
if score >= 100 then return file end
-- select the file with the max score
if score > score_maxn then
file_ok = file
score_maxn = score
end
end
end
-- ok?
return file_ok
end
-- probe it's absolute path if exists from the given tool name and root directory
function tools._probe(root, name)
-- check
assert(root and name)
-- make the tool path
local toolpath = string.format("%s/%s", root, name)
toolpath = path.translate(toolpath)
-- the tool exists? ok
if toolpath and os.isfile(toolpath) then
return toolpath
end
end
-- find tool from the given name and directory (optional)
function tools.find(name, root)
-- check
assert(name)
-- init filename
local filepath = nil
-- uses the basename only
name = path.basename(name)
assert(name)
-- only find it from this directory if the given directory exists
if root then return tools._find_from(root, name) end
-- attempt to find it from the current platform directory first
if not filepath then filepath = tools._find_from(platform.directory() .. "/tools", name) end
-- attempt to find it from the script directory
if not filepath then filepath = tools._find_from(xmake._CORE_DIR .. "/tools", name) end
-- ok?
return filepath
end
-- load tool from the given name and directory (optional)
function tools.load(name, root)
-- check
assert(name)
-- get it directly from cache dirst
tools._TOOLS = tools._TOOLS or {}
if tools._TOOLS[name] then
return tools._TOOLS[name]
end
-- find the tool file path
local toolpath = tools.find(name, root)
-- not exists?
if not toolpath or not os.isfile(toolpath) then
return
end
-- load script
local script, errors = loadfile(toolpath)
if script then
-- load tool
local tool = script()
-- init tool
if tool and tool.init then
tool:init(name)
end
-- save tool to the cache
tools._TOOLS[name] = tool
-- ok?
return tool
else
utils.error(errors)
utils.error("load %s failed!", toolpath)
assert(false)
end
end
-- get the given tool script from the given kind
function tools.get(kind)
-- get the tool name
local toolname = platform.tool(kind)
if not toolname then
utils.error("cannot get tool name for %s", kind)
return
end
-- load it
return tools.load(toolname)
end
-- probe it's absolute path if exists from the given tool name
function tools.probe(name, dirs)
-- check
assert(name)
-- attempt to run it directly first
if os.execute(string.format("%s > %s 2>&1", name, xmake._NULDEV)) ~= 0x7f00 then
return name
end
-- attempt to get it from the given directories
if dirs then
for _, dir in ipairs(utils.wrap(dirs)) do
-- probe it
local toolpath = tools._probe(dir, name)
-- ok?
if toolpath and os.execute(string.format("%s > %s 2>&1", toolpath, xmake._NULDEV)) ~= 0x7f00 then
return toolpath
end
end
end
end
-- return module: tools
return tools
|
fix find tool bug
|
fix find tool bug
|
Lua
|
apache-2.0
|
waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake
|
627e5086a930ef41c59dacf43b8e75361788e3a7
|
api-gateway-config/scripts/lua/metrics/factory.lua
|
api-gateway-config/scripts/lua/metrics/factory.lua
|
-- Copyright (c) 2015 Adobe Systems Incorporated. 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.
--
-- A factory to initialize the methods that can be used for capturing usage data
-- This class is provided as an example
-- User: ddascal
--
local MetricsCollector = require (ngx.var.custom_metrics_collector_path) or "metrics.MetricsCollector"
local collector = MetricsCollector:new()
local function _captureUsageData()
return collector:logCurrentRequest()
end
return {
captureUsageData = _captureUsageData
}
|
-- Copyright (c) 2015 Adobe Systems Incorporated. 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.
--
-- A factory to initialize the methods that can be used for capturing usage data
-- This class is provided as an example
-- User: ddascal
--
local MetricsCollector = require "metrics.MetricsCollector"
local collector = MetricsCollector:new()
local function _captureUsageData()
return collector:logCurrentRequest()
end
return {
captureUsageData = _captureUsageData
}
|
fix metrics factory (#51)
|
fix metrics factory (#51)
the variables from the require are not even available in init phase. Also it was written in a wrong manner.
|
Lua
|
mit
|
adobe-apiplatform/apigateway,adobe-apiplatform/apigateway,adobe-apiplatform/apigateway,adobe-apiplatform/apigateway
|
baba2755036bbe09bd46a9920c4261bd90c11f37
|
src/lpeg.lua
|
src/lpeg.lua
|
local lpjit_lpeg = {}
local lpjit = require 'lpjit'
local lpeg = require 'lpeg'
local mt = {}
local compiled = {}
mt.__index = lpjit_lpeg
local function rawWrap(pattern)
local obj = {value = pattern}
if newproxy and debug.setfenv then
-- Lua 5.1 doesn't support __len for tables
local obj2 = newproxy(true)
debug.setmetatable(obj2, mt)
debug.setfenv(obj2, obj)
assert(debug.getfenv(obj2) == obj)
return obj2
else
return setmetatable(obj, mt)
end
end
local function rawUnwrap(obj)
if type(obj) == 'table' then
return obj.value
else
return debug.getfenv(obj).value
end
end
local function wrapPattern(pattern)
if getmetatable(pattern) == mt then
-- already wrapped
return pattern
else
return rawWrap(pattern)
end
end
local function unwrapPattern(obj)
if getmetatable(obj) == mt then
return rawUnwrap(obj)
else
return obj
end
end
local function wrapGenerator(E)
return function(obj, ...)
if type(obj) == 'table' and getmetatable(obj) ~= mt then
-- P { grammar }
-- unwrap all values
local obj2 = {}
for k, v in pairs(obj) do
obj2[k] = unwrapPattern(v)
end
obj = obj2
else
obj = unwrapPattern(obj)
end
return wrapPattern(E(obj, ...))
end
end
for _, E in ipairs {'B', 'S', 'R', 'Cf', 'Cs', 'Cmt', 'Carg',
'Ct', 'P', 'Cc', 'Cp', 'Cg', 'Cb', 'V', 'C'} do
lpjit_lpeg[E] = wrapGenerator(lpeg[E])
end
for _, binop in ipairs {'__unm', '__mul', '__add', '__sub',
'__div', '__pow', '__len'} do
mt[binop] = function(a, b)
a = unwrapPattern(a)
b = unwrapPattern(b)
local f = getmetatable(a)[binop] or
getmetatable(b)[binop]
return wrapPattern(f(a, b))
end
end
function lpjit_lpeg.match(obj, ...)
if not compiled[obj] then
obj = unwrapPattern(obj)
if lpeg.type(obj) ~= 'pattern' then
obj = lpeg.P(obj)
end
compiled[obj] = lpjit.compile(obj)
end
return compiled[obj]:match(...)
end
function lpjit_lpeg.setmaxstack(...)
lpeg.setmaxstack(...)
-- clear cache ot compiled patterns
compiled = {}
end
function lpjit_lpeg.locale(t)
local funcs0 = lpeg.locale()
local funcs = t or {}
for k, v in pairs(funcs0) do
funcs[k] = wrapPattern(v)
end
return funcs
end
function lpjit_lpeg.version(t)
return "lpjit with lpeg " .. lpeg.version()
end
function lpjit_lpeg.type(obj)
if getmetatable(obj) == mt then
return "pattern"
end
if lpeg.type(obj) == 'pattern' then
return "pattern"
end
return nil
end
if lpeg.pcode then
function lpjit_lpeg.pcode(obj)
return lpeg.pcode(unwrapPattern(obj))
end
end
if lpeg.ptree then
function lpjit_lpeg.ptree(obj)
return lpeg.ptree(unwrapPattern(obj))
end
end
return lpjit_lpeg
|
local lpjit_lpeg = {}
local lpjit = require 'lpjit'
local lpeg = require 'lpeg'
local unpack = unpack or table.unpack
local mt = {}
local compiled = {}
mt.__index = lpjit_lpeg
local function rawWrap(pattern)
local obj = {value = pattern}
if newproxy and debug.setfenv then
-- Lua 5.1 doesn't support __len for tables
local obj2 = newproxy(true)
debug.setmetatable(obj2, mt)
debug.setfenv(obj2, obj)
assert(debug.getfenv(obj2) == obj)
return obj2
else
return setmetatable(obj, mt)
end
end
local function rawUnwrap(obj)
if type(obj) == 'table' then
return obj.value
else
return debug.getfenv(obj).value
end
end
local function wrapPattern(pattern)
if getmetatable(pattern) == mt then
-- already wrapped
return pattern
else
return rawWrap(pattern)
end
end
local function unwrapPattern(obj)
if getmetatable(obj) == mt then
return rawUnwrap(obj)
else
return obj
end
end
local function wrapGenerator(E)
return function(obj, ...)
if type(obj) == 'table' and getmetatable(obj) ~= mt then
-- P { grammar }
-- unwrap all values
local obj2 = {}
for k, v in pairs(obj) do
obj2[k] = unwrapPattern(v)
end
obj = obj2
else
obj = unwrapPattern(obj)
end
-- eliminate tail nils, fix lpeg.R()
local args = {obj, ...}
return wrapPattern(E(unpack(args)))
end
end
for _, E in ipairs {'B', 'S', 'R', 'Cf', 'Cs', 'Cmt', 'Carg',
'Ct', 'P', 'Cc', 'Cp', 'Cg', 'Cb', 'V', 'C'} do
lpjit_lpeg[E] = wrapGenerator(lpeg[E])
end
for _, binop in ipairs {'__unm', '__mul', '__add', '__sub',
'__div', '__pow', '__len'} do
mt[binop] = function(a, b)
a = unwrapPattern(a)
b = unwrapPattern(b)
local f = getmetatable(a)[binop] or
getmetatable(b)[binop]
return wrapPattern(f(a, b))
end
end
function lpjit_lpeg.match(obj, ...)
if not compiled[obj] then
obj = unwrapPattern(obj)
if lpeg.type(obj) ~= 'pattern' then
obj = lpeg.P(obj)
end
compiled[obj] = lpjit.compile(obj)
end
return compiled[obj]:match(...)
end
function lpjit_lpeg.setmaxstack(...)
lpeg.setmaxstack(...)
-- clear cache ot compiled patterns
compiled = {}
end
function lpjit_lpeg.locale(t)
local funcs0 = lpeg.locale()
local funcs = t or {}
for k, v in pairs(funcs0) do
funcs[k] = wrapPattern(v)
end
return funcs
end
function lpjit_lpeg.version(t)
return "lpjit with lpeg " .. lpeg.version()
end
function lpjit_lpeg.type(obj)
if getmetatable(obj) == mt then
return "pattern"
end
if lpeg.type(obj) == 'pattern' then
return "pattern"
end
return nil
end
if lpeg.pcode then
function lpjit_lpeg.pcode(obj)
return lpeg.pcode(unwrapPattern(obj))
end
end
if lpeg.ptree then
function lpjit_lpeg.ptree(obj)
return lpeg.ptree(unwrapPattern(obj))
end
end
return lpjit_lpeg
|
lpeg wrapper: fix call lpeg.R()
|
lpeg wrapper: fix call lpeg.R()
lpeg.R() works, lpeg.R(nil) fails
|
Lua
|
mit
|
starius/lpjit,starius/lpjit
|
9daf754d1a5865ccd4961a2244c89a6ac1f02627
|
net/http.lua
|
net/http.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 socket = require "socket"
local mime = require "mime"
local url = require "socket.url"
local server = require "net.server"
local connlisteners_get = require "net.connlisteners".get;
local listener = connlisteners_get("httpclient") or error("No httpclient listener!");
local t_insert, t_concat = table.insert, table.concat;
local tonumber, tostring, pairs, xpcall, select, debug_traceback, char, format =
tonumber, tostring, pairs, xpcall, select, debug.traceback, string.char, string.format;
local log = require "util.logger".init("http");
local print = function () end
module "http"
function urlencode(s) return s and (s:gsub("%W", function (c) return format("%%%02x", c:byte()); end)); end
function urldecode(s) return s and (s:gsub("%%(%x%x)", function (c) return char(tonumber(c,16)); end)); end
local function expectbody(reqt, code)
if reqt.method == "HEAD" then return nil end
if code == 204 or code == 304 or code == 301 then return nil end
if code >= 100 and code < 200 then return nil end
return 1
end
local function request_reader(request, data, startpos)
if not data then
if request.body then
log("debug", "Connection closed, but we have data, calling callback...");
request.callback(t_concat(request.body), request.code, request);
elseif request.state ~= "completed" then
-- Error.. connection was closed prematurely
request.callback("connection-closed", 0, request);
end
destroy_request(request);
request.body = nil;
request.state = "completed";
return;
end
if request.state == "body" and request.state ~= "completed" then
print("Reading body...")
if not request.body then request.body = {}; request.havebodylength, request.bodylength = 0, tonumber(request.responseheaders["content-length"]); end
if startpos then
data = data:sub(startpos, -1)
end
t_insert(request.body, data);
if request.bodylength then
request.havebodylength = request.havebodylength + #data;
if request.havebodylength >= request.bodylength then
-- We have the body
log("debug", "Have full body, calling callback");
if request.callback then
request.callback(t_concat(request.body), request.code, request);
end
request.body = nil;
request.state = "completed";
else
print("", "Have "..request.havebodylength.." bytes out of "..request.bodylength);
end
end
elseif request.state == "headers" then
print("Reading headers...")
local pos = startpos;
local headers = request.responseheaders or {};
for line in data:sub(startpos, -1):gmatch("(.-)\r\n") do
startpos = startpos + #line + 2;
local k, v = line:match("(%S+): (.+)");
if k and v then
headers[k:lower()] = v;
print("Header: "..k:lower().." = "..v);
elseif #line == 0 then
request.responseheaders = headers;
break;
else
print("Unhandled header line: "..line);
end
end
-- Reached the end of the headers
request.state = "body";
if #data > startpos then
return request_reader(request, data, startpos);
end
elseif request.state == "status" then
print("Reading status...")
local http, code, text, linelen = data:match("^HTTP/(%S+) (%d+) (.-)\r\n()", startpos);
code = tonumber(code);
if not code then
return request.callback("invalid-status-line", 0, request);
end
request.code, request.responseversion = code, http;
if request.onlystatus or not expectbody(request, code) then
if request.callback then
request.callback(nil, code, request);
end
destroy_request(request);
return;
end
request.state = "headers";
if #data > linelen then
return request_reader(request, data, linelen);
end
end
end
local function handleerr(err) log("error", "Traceback[http]: %s: %s", tostring(err), debug_traceback()); end
function request(u, ex, callback)
local req = url.parse(u);
if not (req and req.host) then
callback(nil, 0, req);
return nil, "invalid-url";
end
if not req.path then
req.path = "/";
end
local custom_headers, body;
local default_headers = { ["Host"] = req.host, ["User-Agent"] = "Prosody XMPP Server" }
if req.userinfo then
default_headers["Authorization"] = "Basic "..mime.b64(req.userinfo);
end
if ex then
custom_headers = ex.headers;
req.onlystatus = ex.onlystatus;
body = ex.body;
if body then
req.method = "POST ";
default_headers["Content-Length"] = tostring(#body);
default_headers["Content-Type"] = "application/x-www-form-urlencoded";
end
if ex.method then req.method = ex.method; end
end
req.handler, req.conn = server.wrapclient(socket.tcp(), req.host, req.port or 80, listener, "*a");
req.write = req.handler.write;
req.conn:settimeout(0);
local ok, err = req.conn:connect(req.host, req.port or 80);
if not ok and err ~= "timeout" then
callback(nil, 0, req);
return nil, err;
end
local request_line = { req.method or "GET", " ", req.path, " HTTP/1.1\r\n" };
if req.query then
t_insert(request_line, 4, "?");
t_insert(request_line, 5, req.query);
end
req.write(t_concat(request_line));
local t = { [2] = ": ", [4] = "\r\n" };
if custom_headers then
for k, v in pairs(custom_headers) do
t[1], t[3] = k, v;
req.write(t_concat(t));
default_headers[k] = nil;
end
end
for k, v in pairs(default_headers) do
t[1], t[3] = k, v;
req.write(t_concat(t));
default_headers[k] = nil;
end
req.write("\r\n");
if body then
req.write(body);
end
req.callback = function (content, code, request) log("debug", "Calling callback, status %s", code or "---"); return select(2, xpcall(function () return callback(content, code, request) end, handleerr)); end
req.reader = request_reader;
req.state = "status";
listener.register_request(req.handler, req);
return req;
end
function destroy_request(request)
if request.conn then
request.handler.close()
listener.disconnect(request.conn, "closed");
end
end
_M.urlencode = urlencode;
return _M;
|
-- 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 socket = require "socket"
local mime = require "mime"
local url = require "socket.url"
local server = require "net.server"
local connlisteners_get = require "net.connlisteners".get;
local listener = connlisteners_get("httpclient") or error("No httpclient listener!");
local t_insert, t_concat = table.insert, table.concat;
local tonumber, tostring, pairs, xpcall, select, debug_traceback, char, format =
tonumber, tostring, pairs, xpcall, select, debug.traceback, string.char, string.format;
local log = require "util.logger".init("http");
local print = function () end
module "http"
function urlencode(s) return s and (s:gsub("%W", function (c) return format("%%%02x", c:byte()); end)); end
function urldecode(s) return s and (s:gsub("%%(%x%x)", function (c) return char(tonumber(c,16)); end)); end
local function expectbody(reqt, code)
if reqt.method == "HEAD" then return nil end
if code == 204 or code == 304 or code == 301 then return nil end
if code >= 100 and code < 200 then return nil end
return 1
end
local function request_reader(request, data, startpos)
if not data then
if request.body then
log("debug", "Connection closed, but we have data, calling callback...");
request.callback(t_concat(request.body), request.code, request);
elseif request.state ~= "completed" then
-- Error.. connection was closed prematurely
request.callback("connection-closed", 0, request);
end
destroy_request(request);
request.body = nil;
request.state = "completed";
return;
end
if request.state == "body" and request.state ~= "completed" then
print("Reading body...")
if not request.body then request.body = {}; request.havebodylength, request.bodylength = 0, tonumber(request.responseheaders["content-length"]); end
if startpos then
data = data:sub(startpos, -1)
end
t_insert(request.body, data);
if request.bodylength then
request.havebodylength = request.havebodylength + #data;
if request.havebodylength >= request.bodylength then
-- We have the body
log("debug", "Have full body, calling callback");
if request.callback then
request.callback(t_concat(request.body), request.code, request);
end
request.body = nil;
request.state = "completed";
else
print("", "Have "..request.havebodylength.." bytes out of "..request.bodylength);
end
end
elseif request.state == "headers" then
print("Reading headers...")
local pos = startpos;
local headers, headers_complete = request.responseheaders;
if not headers then
headers = {};
request.responseheaders = headers;
end
for line in data:sub(startpos, -1):gmatch("(.-)\r\n") do
startpos = startpos + #line + 2;
local k, v = line:match("(%S+): (.+)");
if k and v then
headers[k:lower()] = v;
--print("Header: "..k:lower().." = "..v);
elseif #line == 0 then
headers_complete = true;
break;
else
print("Unhandled header line: "..line);
end
end
if not headers_complete then return; end
-- Reached the end of the headers
if not expectbody(request, request.code) then
request.callback(nil, request.code, request);
return;
end
request.state = "body";
if #data > startpos then
return request_reader(request, data, startpos);
end
elseif request.state == "status" then
print("Reading status...")
local http, code, text, linelen = data:match("^HTTP/(%S+) (%d+) (.-)\r\n()", startpos);
code = tonumber(code);
if not code then
return request.callback("invalid-status-line", 0, request);
end
request.code, request.responseversion = code, http;
if request.onlystatus then
if request.callback then
request.callback(nil, code, request);
end
destroy_request(request);
return;
end
request.state = "headers";
if #data > linelen then
return request_reader(request, data, linelen);
end
end
end
local function handleerr(err) log("error", "Traceback[http]: %s: %s", tostring(err), debug_traceback()); end
function request(u, ex, callback)
local req = url.parse(u);
if not (req and req.host) then
callback(nil, 0, req);
return nil, "invalid-url";
end
if not req.path then
req.path = "/";
end
local custom_headers, body;
local default_headers = { ["Host"] = req.host, ["User-Agent"] = "Prosody XMPP Server" }
if req.userinfo then
default_headers["Authorization"] = "Basic "..mime.b64(req.userinfo);
end
if ex then
custom_headers = ex.headers;
req.onlystatus = ex.onlystatus;
body = ex.body;
if body then
req.method = "POST ";
default_headers["Content-Length"] = tostring(#body);
default_headers["Content-Type"] = "application/x-www-form-urlencoded";
end
if ex.method then req.method = ex.method; end
end
req.handler, req.conn = server.wrapclient(socket.tcp(), req.host, req.port or 80, listener, "*a");
req.write = req.handler.write;
req.conn:settimeout(0);
local ok, err = req.conn:connect(req.host, req.port or 80);
if not ok and err ~= "timeout" then
callback(nil, 0, req);
return nil, err;
end
local request_line = { req.method or "GET", " ", req.path, " HTTP/1.1\r\n" };
if req.query then
t_insert(request_line, 4, "?");
t_insert(request_line, 5, req.query);
end
req.write(t_concat(request_line));
local t = { [2] = ": ", [4] = "\r\n" };
if custom_headers then
for k, v in pairs(custom_headers) do
t[1], t[3] = k, v;
req.write(t_concat(t));
default_headers[k] = nil;
end
end
for k, v in pairs(default_headers) do
t[1], t[3] = k, v;
req.write(t_concat(t));
default_headers[k] = nil;
end
req.write("\r\n");
if body then
req.write(body);
end
req.callback = function (content, code, request) log("debug", "Calling callback, status %s", code or "---"); return select(2, xpcall(function () return callback(content, code, request) end, handleerr)); end
req.reader = request_reader;
req.state = "status";
listener.register_request(req.handler, req);
return req;
end
function destroy_request(request)
if request.conn then
request.handler.close()
listener.disconnect(request.conn, "closed");
end
end
_M.urlencode = urlencode;
return _M;
|
net.http: Port commit 2f235c57d713 to net.http to fix headers in responses (thanks dersd)
|
net.http: Port commit 2f235c57d713 to net.http to fix headers in responses (thanks dersd)
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
41953a6efa288230d0bfd905f08a1256dabc5678
|
net/xmppserver_listener.lua
|
net/xmppserver_listener.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 logger = require "logger";
local log = logger.init("xmppserver_listener");
local lxp = require "lxp"
local init_xmlhandlers = require "core.xmlhandlers"
local s2s_new_incoming = require "core.s2smanager".new_incoming;
local s2s_streamopened = require "core.s2smanager".streamopened;
local s2s_streamclosed = require "core.s2smanager".streamclosed;
local s2s_destroy_session = require "core.s2smanager".destroy_session;
local s2s_attempt_connect = require "core.s2smanager".attempt_connection;
local stream_callbacks = { stream_tag = "http://etherx.jabber.org/streams|stream",
default_ns = "jabber:server",
streamopened = s2s_streamopened, streamclosed = s2s_streamclosed, handlestanza = core_process_stanza };
function stream_callbacks.error(session, error, data)
if error == "no-stream" then
session:close("invalid-namespace");
else
session.log("debug", "Server-to-server XML parse error: %s", tostring(error));
session:close("xml-not-well-formed");
end
end
local function handleerr(err) log("error", "Traceback[s2s]: %s: %s", tostring(err), debug.traceback()); end
function stream_callbacks.handlestanza(a, b)
xpcall(function () core_process_stanza(a, b) end, handleerr);
end
local connlisteners_register = require "net.connlisteners".register;
local t_insert = table.insert;
local t_concat = table.concat;
local t_concatall = function (t, sep) local tt = {}; for _, s in ipairs(t) do t_insert(tt, tostring(s)); end return t_concat(tt, sep); end
local m_random = math.random;
local format = string.format;
local sessionmanager = require "core.sessionmanager";
local sm_new_session, sm_destroy_session = sessionmanager.new_session, sessionmanager.destroy_session;
local st = require "util.stanza";
local sessions = {};
local xmppserver = { default_port = 5269, default_mode = "*a" };
-- These are session methods --
local function session_reset_stream(session)
-- Reset stream
local parser = lxp.new(init_xmlhandlers(session, stream_callbacks), "|");
session.parser = parser;
session.notopen = true;
function session.data(conn, data)
local ok, err = parser:parse(data);
if ok then return; end
session.log("warn", "Received invalid XML: %s", data);
session.log("warn", "Problem was: %s", err);
session:close("xml-not-well-formed");
end
return true;
end
local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
local default_stream_attr = { ["xmlns:stream"] = stream_callbacks.stream_tag:gsub("%|[^|]+$", ""), xmlns = stream_callbacks.default_ns, version = "1.0", id = "" };
local function session_close(session, reason)
local log = session.log or log;
if session.conn then
if session.notopen then
session.sends2s("<?xml version='1.0'?>");
session.sends2s(st.stanza("stream:stream", default_stream_attr):top_tag());
end
if reason then
if type(reason) == "string" then -- assume stream error
log("info", "Disconnecting %s[%s], <stream:error> is: %s", session.host or "(unknown host)", session.type, reason);
session.sends2s(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }));
elseif type(reason) == "table" then
if reason.condition then
local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up();
if reason.text then
stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
end
if reason.extra then
stanza:add_child(reason.extra);
end
log("info", "Disconnecting %s[%s], <stream:error> is: %s", session.host or "(unknown host)", session.type, tostring(stanza));
session.sends2s(stanza);
elseif reason.name then -- a stanza
log("info", "Disconnecting %s->%s[%s], <stream:error> is: %s", session.from_host or "(unknown host)", session.to_host or "(unknown host)", session.type, tostring(reason));
session.sends2s(reason);
end
end
end
session.sends2s("</stream:stream>");
session.conn.close();
xmppserver.disconnect(session.conn, "stream error");
end
end
-- End of session methods --
function xmppserver.listener(conn, data)
local session = sessions[conn];
if not session then
session = s2s_new_incoming(conn);
sessions[conn] = session;
-- Logging functions --
local conn_name = "s2sin"..tostring(conn):match("[a-f0-9]+$");
session.log = logger.init(conn_name);
session.log("info", "Incoming s2s connection");
session.reset_stream = session_reset_stream;
session.close = session_close;
session_reset_stream(session); -- Initialise, ready for use
session.dispatch_stanza = stream_callbacks.handlestanza;
end
if data then
session.data(conn, data);
end
end
function xmppserver.status(conn, status)
if status == "ssl-handshake-complete" then
local session = sessions[conn];
if session and session.direction == "outgoing" then
local format, to_host, from_host = string.format, session.to_host, session.from_host;
session.log("debug", "Sending stream header...");
session.sends2s(format([[<stream:stream xmlns='jabber:server' xmlns:db='jabber:server:dialback' xmlns:stream='http://etherx.jabber.org/streams' from='%s' to='%s' version='1.0'>]], from_host, to_host));
end
end
end
function xmppserver.disconnect(conn, err)
local session = sessions[conn];
if session then
if err and err ~= "closed" and session.srv_hosts then
(session.log or log)("debug", "s2s connection closed unexpectedly");
if s2s_attempt_connect(session, err) then
(session.log or log)("debug", "...so we're going to try again");
return; -- Session lives for now
end
end
(session.log or log)("info", "s2s disconnected: %s->%s (%s)", tostring(session.from_host), tostring(session.to_host), tostring(err));
s2s_destroy_session(session);
sessions[conn] = nil;
session = nil;
collectgarbage("collect");
end
end
function xmppserver.register_outgoing(conn, session)
session.direction = "outgoing";
sessions[conn] = session;
session.reset_stream = session_reset_stream;
session.close = session_close;
session_reset_stream(session); -- Initialise, ready for use
--local function handleerr(err) print("Traceback:", err, debug.traceback()); end
--session.stanza_dispatch = function (stanza) return select(2, xpcall(function () return core_process_stanza(session, stanza); end, handleerr)); end
end
connlisteners_register("xmppserver", xmppserver);
-- We need to perform some initialisation when a connection is created
-- We also need to perform that same initialisation at other points (SASL, TLS, ...)
-- ...and we need to handle data
-- ...and record all sessions associated with connections
|
-- 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 logger = require "logger";
local log = logger.init("xmppserver_listener");
local lxp = require "lxp"
local init_xmlhandlers = require "core.xmlhandlers"
local s2s_new_incoming = require "core.s2smanager".new_incoming;
local s2s_streamopened = require "core.s2smanager".streamopened;
local s2s_streamclosed = require "core.s2smanager".streamclosed;
local s2s_destroy_session = require "core.s2smanager".destroy_session;
local s2s_attempt_connect = require "core.s2smanager".attempt_connection;
local stream_callbacks = { stream_tag = "http://etherx.jabber.org/streams|stream",
default_ns = "jabber:server",
streamopened = s2s_streamopened, streamclosed = s2s_streamclosed, handlestanza = core_process_stanza };
function stream_callbacks.error(session, error, data)
if error == "no-stream" then
session:close("invalid-namespace");
else
session.log("debug", "Server-to-server XML parse error: %s", tostring(error));
session:close("xml-not-well-formed");
end
end
local function handleerr(err) log("error", "Traceback[s2s]: %s: %s", tostring(err), debug.traceback()); end
function stream_callbacks.handlestanza(a, b)
xpcall(function () core_process_stanza(a, b) end, handleerr);
end
local connlisteners_register = require "net.connlisteners".register;
local t_insert = table.insert;
local t_concat = table.concat;
local t_concatall = function (t, sep) local tt = {}; for _, s in ipairs(t) do t_insert(tt, tostring(s)); end return t_concat(tt, sep); end
local m_random = math.random;
local format = string.format;
local sessionmanager = require "core.sessionmanager";
local sm_new_session, sm_destroy_session = sessionmanager.new_session, sessionmanager.destroy_session;
local st = require "util.stanza";
local sessions = {};
local xmppserver = { default_port = 5269, default_mode = "*a" };
-- These are session methods --
local function session_reset_stream(session)
-- Reset stream
local parser = lxp.new(init_xmlhandlers(session, stream_callbacks), "|");
session.parser = parser;
session.notopen = true;
function session.data(conn, data)
local ok, err = parser:parse(data);
if ok then return; end
session:close("xml-not-well-formed");
end
return true;
end
local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
local default_stream_attr = { ["xmlns:stream"] = stream_callbacks.stream_tag:gsub("%|[^|]+$", ""), xmlns = stream_callbacks.default_ns, version = "1.0", id = "" };
local function session_close(session, reason)
local log = session.log or log;
if session.conn then
if session.notopen then
session.sends2s("<?xml version='1.0'?>");
session.sends2s(st.stanza("stream:stream", default_stream_attr):top_tag());
end
if reason then
if type(reason) == "string" then -- assume stream error
log("info", "Disconnecting %s[%s], <stream:error> is: %s", session.host or "(unknown host)", session.type, reason);
session.sends2s(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }));
elseif type(reason) == "table" then
if reason.condition then
local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up();
if reason.text then
stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
end
if reason.extra then
stanza:add_child(reason.extra);
end
log("info", "Disconnecting %s[%s], <stream:error> is: %s", session.host or "(unknown host)", session.type, tostring(stanza));
session.sends2s(stanza);
elseif reason.name then -- a stanza
log("info", "Disconnecting %s->%s[%s], <stream:error> is: %s", session.from_host or "(unknown host)", session.to_host or "(unknown host)", session.type, tostring(reason));
session.sends2s(reason);
end
end
end
session.sends2s("</stream:stream>");
if sesson.notopen or not session.conn.close() then
session.conn.close(true); -- Force FIXME: timer?
end
session.conn.close();
xmppserver.disconnect(session.conn, "stream error");
end
end
-- End of session methods --
function xmppserver.listener(conn, data)
local session = sessions[conn];
if not session then
session = s2s_new_incoming(conn);
sessions[conn] = session;
-- Logging functions --
local conn_name = "s2sin"..tostring(conn):match("[a-f0-9]+$");
session.log = logger.init(conn_name);
session.log("info", "Incoming s2s connection");
session.reset_stream = session_reset_stream;
session.close = session_close;
session_reset_stream(session); -- Initialise, ready for use
session.dispatch_stanza = stream_callbacks.handlestanza;
end
if data then
session.data(conn, data);
end
end
function xmppserver.disconnect(conn, err)
local session = sessions[conn];
if session then
if err and err ~= "closed" and session.srv_hosts then
(session.log or log)("debug", "s2s connection closed unexpectedly");
if s2s_attempt_connect(session, err) then
(session.log or log)("debug", "...so we're going to try again");
return; -- Session lives for now
end
end
(session.log or log)("info", "s2s disconnected: %s->%s (%s)", tostring(session.from_host), tostring(session.to_host), tostring(err));
s2s_destroy_session(session);
sessions[conn] = nil;
session = nil;
collectgarbage("collect");
end
end
function xmppserver.register_outgoing(conn, session)
session.direction = "outgoing";
sessions[conn] = session;
session.reset_stream = session_reset_stream;
session.close = session_close;
session_reset_stream(session); -- Initialise, ready for use
--local function handleerr(err) print("Traceback:", err, debug.traceback()); end
--session.stanza_dispatch = function (stanza) return select(2, xpcall(function () return core_process_stanza(session, stanza); end, handleerr)); end
end
connlisteners_register("xmppserver", xmppserver);
-- We need to perform some initialisation when a connection is created
-- We also need to perform that same initialisation at other points (SASL, TLS, ...)
-- ...and we need to handle data
-- ...and record all sessions associated with connections
|
xmppserver_listener: More forcefully close s2s connections (fixes fd leak)
|
xmppserver_listener: More forcefully close s2s connections (fixes fd leak)
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
527fe061696f044b6a2ca5e00debd905ce5d0d82
|
extensions/window/test_window.lua
|
extensions/window/test_window.lua
|
require("hs.timer")
function testAllWindows()
hs.openConsole()
hs.openPreferences()
local allWindows = hs.window.allWindows()
assertIsEqual("table", type(allWindows))
assertGreaterThan(1, #allWindows)
-- Enable this when hs.window objects have a proper __type metatable entry
-- assertIsUserdataOfType(allWindows[1], "hs.window")
hs.closePreferences()
hs.closeConsole()
return success()
end
function testDesktop()
local desktop = hs.window.desktop()
assertIsNotNil(desktop)
assertIsEqual("AXScrollArea", desktop:role())
return success()
end
function testOrderedWindows()
hs.openConsole() -- Make sure we have at least one window
local orderedWindows = hs.window.orderedWindows()
assertIsEqual("table", type(orderedWindows))
assertGreaterThan(1, #orderedWindows)
return success()
end
function testFocusedWindow()
hs.openConsole()
local win = hs.window.focusedWindow()
assertIsUserdataOfType("hs.window", win) -- This will fail right now, because hs.window doesn't have a __type metatable entry
return success()
end
function testSnapshots()
hs.openConsole()
local win = hs.window.focusedWindow()
local id = win:id()
assertIsNumber(id)
assertGreaterThan(0, id)
assertIsUserdataOfType("hs.image", hs.window.snapshotForID(id))
assertIsUserdataOfType("hs.image", win:snapshot())
return success()
end
function testTitle()
hs.openConsole()
local win = hs.window.focusedWindow()
local title = win:title()
assertIsString(title)
assertIsEqual("Hammerspoon Console", win:title())
assertIsString(tostring(win))
return success()
end
function testRoles()
hs.openConsole()
local win = hs.window.focusedWindow()
assertIsEqual("AXWindow", win:role())
assertIsEqual("AXStandardWindow", win:subrole())
assertTrue(win:isStandard())
return success()
end
function testTopLeft()
hs.openConsole()
local win = hs.window.focusedWindow()
local topLeftOrig = win:topLeft()
assertIsTable(topLeftOrig)
local topLeftNew = hs.geometry.point(topLeftOrig.x + 1, topLeftOrig.y + 1)
win:setTopLeft(topLeftNew)
topLeftNew = win:topLeft()
assertIsEqual(topLeftNew.x, topLeftOrig.x + 1)
assertIsEqual(topLeftNew.y, topLeftOrig.y + 1)
return success()
end
function testSize()
hs.openConsole()
local win = hs.window.focusedWindow()
local sizeOrig = win:size()
assertIsTable(sizeOrig)
local sizeNew = hs.geometry.size(sizeOrig.w + 1, sizeOrig.h + 1)
win:setSize(sizeNew)
sizeNew = win:size()
assertIsEqual(sizeNew.w, sizeOrig.w + 1)
assertIsEqual(sizeNew.h, sizeOrig.h + 1)
return success()
end
function testMinimize()
hs.openConsole()
local win = hs.window.focusedWindow()
local isMinimizedOrig = win:isMinimized()
assertIsBoolean(isMinimizedOrig)
win:minimize()
assertFalse(isMinimizedOrig == win:isMinimized())
win:unminimize()
assertTrue(isMinimizedOrig == win:isMinimized())
return success()
end
function testPID()
hs.openConsole()
local win = hs.window.focusedWindow()
assertIsEqual(win:pid(), hs.processInfo["processID"])
return success()
end
function testApplication()
hs.openConsole()
local win = hs.window.focusedWindow()
local app = win:application()
assertIsUserdataOfType("hs.application", app) -- This will fail right now, because hs.application doesn't have a __type metatable entry
return success()
end
function testTabs()
-- First test tabs on a window that doesn't have tabs
hs.openConsole()
local win = hs.window.focusedWindow()
assertIsNil(win:tabCount())
-- Now test an app with tabs
local safari = hs.application.open("Safari", 5, true)
-- Ensure we have at least two tabs
hs.urlevent.openURLWithBundle("http://www.apple.com", "com.apple.Safari")
hs.urlevent.openURLWithBundle("http://developer.apple.com", "com.apple.Safari")
local safariWin = safari:mainWindow()
local tabCount = safariWin:tabCount()
assertGreaterThan(1, tabCount)
safariWin:focusTab(tabCount - 1)
return success()
end
function testBecomeMain() -- This will fail
end
function testClose()
hs.openConsole()
local win = hs.window.focusedWindow()
assertTrue(win:close())
-- It would be nice to do something more here, to verify it's gone
return success()
end
function testFullscreen()
hs.openConsole()
local win = hs.window.focusedWindow()
assertIsUserdata(win)
local fullscreenState = win:isFullScreen()
assertIsBoolean(fullscreenState)
assertFalse(fullscreenState)
win:setFullScreen(false)
return success()
end
function testFullscreenOneSetup()
hs.openConsole()
local win = hs.window.get("Hammerspoon Console")
assertIsEqual(win:title(), "Hammerspoon Console")
assertFalse(win:isFullScreen())
win:setFullScreen(true)
--return success()
end
function testFullscreenOneResult()
local win = hs.window.get("Hammerspoon Console")
assertIsEqual(win:title(), "Hammerspoon Console")
assertTrue(win:isFullScreen())
win:setFullScreen(false)
return success()
end
function testFullscreenTwoSetup()
hs.openConsole()
local win = hs.window.get("Hammerspoon Console")
win:toggleZoom()
return success()
end
function testFullscreenTwoResult()
local win = hs.window.get("Hammerspoon Console")
assertTrue(win:isFullScreen())
win:setFullScreen(false)
return success()
end
|
require("hs.timer")
function testAllWindows()
hs.openConsole()
hs.openPreferences()
local allWindows = hs.window.allWindows()
assertIsEqual("table", type(allWindows))
assertGreaterThan(1, #allWindows)
-- Enable this when hs.window objects have a proper __type metatable entry
-- assertIsUserdataOfType(allWindows[1], "hs.window")
hs.closePreferences()
hs.closeConsole()
return success()
end
function testDesktop()
local desktop = hs.window.desktop()
assertIsNotNil(desktop)
assertIsEqual("AXScrollArea", desktop:role())
return success()
end
function testOrderedWindows()
hs.openConsole() -- Make sure we have at least one window
hs.openPreferences()
local orderedWindows = hs.window.orderedWindows()
assertIsEqual("table", type(orderedWindows))
assertGreaterThan(1, #orderedWindows)
return success()
end
function testFocusedWindow()
hs.openConsole()
local win = hs.window.focusedWindow()
assertIsUserdataOfType("hs.window", win)
return success()
end
function testSnapshots()
hs.openConsole()
local win = hs.window.focusedWindow()
local id = win:id()
assertIsNumber(id)
assertGreaterThan(0, id)
assertIsUserdataOfType("hs.image", hs.window.snapshotForID(id))
assertIsUserdataOfType("hs.image", win:snapshot())
return success()
end
function testTitle()
hs.openConsole()
local win = hs.window.focusedWindow()
local title = win:title()
assertIsString(title)
assertIsEqual("Hammerspoon Console", win:title())
assertIsString(tostring(win))
return success()
end
function testRoles()
hs.openConsole()
local win = hs.window.focusedWindow()
assertIsEqual("AXWindow", win:role())
assertIsEqual("AXStandardWindow", win:subrole())
assertTrue(win:isStandard())
return success()
end
function testTopLeft()
hs.openConsole()
local win = hs.window.focusedWindow()
local topLeftOrig = win:topLeft()
assertIsTable(topLeftOrig)
local topLeftNew = hs.geometry.point(topLeftOrig.x + 1, topLeftOrig.y + 1)
win:setTopLeft(topLeftNew)
topLeftNew = win:topLeft()
assertIsEqual(topLeftNew.x, topLeftOrig.x + 1)
assertIsEqual(topLeftNew.y, topLeftOrig.y + 1)
return success()
end
function testSize()
hs.openConsole()
local win = hs.window.focusedWindow()
win:setSize(hs.geometry.size(500, 600))
local sizeOrig = win:size()
assertIsTable(sizeOrig)
assertIsEqual(500, sizeOrig.w)
assertIsEqual(600, sizeOrig.h)
local sizeNew = hs.geometry.size(sizeOrig.w + 5, sizeOrig.h + 5)
win:setSize(sizeNew)
sizeNew = win:size()
assertIsEqual(sizeNew.w, sizeOrig.w + 5)
assertIsEqual(sizeNew.h, sizeOrig.h + 5)
return success()
end
function testMinimize()
hs.openConsole()
local win = hs.window.focusedWindow()
local isMinimizedOrig = win:isMinimized()
assertIsBoolean(isMinimizedOrig)
win:minimize()
assertFalse(isMinimizedOrig == win:isMinimized())
win:unminimize()
assertTrue(isMinimizedOrig == win:isMinimized())
return success()
end
function testPID()
hs.openConsole()
local win = hs.window.focusedWindow()
assertIsEqual(win:pid(), hs.processInfo["processID"])
return success()
end
function testApplication()
hs.openConsole()
local win = hs.window.focusedWindow()
local app = win:application()
assertIsUserdataOfType("hs.application", app) -- This will fail right now, because hs.application doesn't have a __type metatable entry
return success()
end
function testTabs()
-- First test tabs on a window that doesn't have tabs
hs.openConsole()
local win = hs.window.focusedWindow()
assertIsNil(win:tabCount())
-- Now test an app with tabs
local safari = hs.application.open("Safari", 5, true)
-- Ensure we have at least two tabs
hs.urlevent.openURLWithBundle("http://www.apple.com", "com.apple.Safari")
hs.urlevent.openURLWithBundle("http://developer.apple.com", "com.apple.Safari")
local safariWin = safari:mainWindow()
local tabCount = safariWin:tabCount()
assertGreaterThan(1, tabCount)
safariWin:focusTab(tabCount - 1)
return success()
end
function testBecomeMain() -- This will fail
end
function testClose()
hs.openConsole()
local win = hs.window.focusedWindow()
assertTrue(win:close())
-- It would be nice to do something more here, to verify it's gone
return success()
end
function testFullscreen()
hs.openConsole()
local win = hs.window.focusedWindow()
assertIsUserdata(win)
local fullscreenState = win:isFullScreen()
assertIsBoolean(fullscreenState)
assertFalse(fullscreenState)
win:setFullScreen(false)
return success()
end
function testFullscreenOneSetup()
hs.openConsole()
local win = hs.window.get("Hammerspoon Console")
assertIsEqual(win:title(), "Hammerspoon Console")
assertFalse(win:isFullScreen())
win:setFullScreen(true)
--return success()
end
function testFullscreenOneResult()
local win = hs.window.get("Hammerspoon Console")
assertIsEqual(win:title(), "Hammerspoon Console")
assertTrue(win:isFullScreen())
win:setFullScreen(false)
return success()
end
function testFullscreenTwoSetup()
hs.openConsole()
local win = hs.window.get("Hammerspoon Console")
win:toggleZoom()
return success()
end
function testFullscreenTwoResult()
local win = hs.window.get("Hammerspoon Console")
assertTrue(win:isFullScreen())
win:setFullScreen(false)
return success()
end
|
Attempt to fix a failing hs.window test
|
Attempt to fix a failing hs.window test
Test a theory that the hs.window:{size,setSize} tests are failing because the window is starting out too large
Fix hs.window size tests
|
Lua
|
mit
|
latenitefilms/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,cmsj/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,latenitefilms/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,asmagill/hammerspoon,CommandPost/CommandPost-App,CommandPost/CommandPost-App,asmagill/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,Habbie/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,Habbie/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,Habbie/hammerspoon,CommandPost/CommandPost-App,latenitefilms/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,latenitefilms/hammerspoon
|
46ba6699544c507ccdb8fe108360e65e2b9fe152
|
config/sipi.init-knora-test.lua
|
config/sipi.init-knora-test.lua
|
--
-- Copyright © 2016 Lukas Rosenthaler, Andrea Bianco, Benjamin Geer,
-- Ivan Subotic, Tobias Schweizer, André Kilchenmann, and André Fatton.
-- This file is part of Sipi.
-- Sipi 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.
-- Sipi 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.
-- Additional permission under GNU AGPL version 3 section 7:
-- If you modify this Program, or any covered work, by linking or combining
-- it with Kakadu (or a modified version of that library), containing parts
-- covered by the terms of the Kakadu Software Licence, the licensors of this
-- Program grant you additional permission to convey the resulting work.
-- 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 Sipi. If not, see <http://www.gnu.org/licenses/>.
-------------------------------------------------------------------------------
-- This function is being called from sipi before the file is served
-- Knora is called to ask for the user's permissions on the file
-- Parameters:
-- prefix: This is the prefix that is given on the IIIF url
-- identifier: the identifier for the image
-- cookie: The cookie that may be present
--
-- Returns:
-- permission:
-- 'allow' : the view is allowed with the given IIIF parameters
-- 'restrict:watermark=<path-to-watermark>' : Add a watermark
-- 'restrict:size=<iiif-size-string>' : reduce size/resolution
-- 'deny' : no access!
-- filepath: server-path where the master file is located
-------------------------------------------------------------------------------
function pre_flight(prefix,identifier,cookie)
--
-- For Knora Sipi integration testing
-- Always the same test file is served
--
filepath = config.imgroot .. '/' .. prefix .. '/' .. 'Leaves.jpg'
print("serving test image " .. filepath)
if prefix == "thumbs" then
-- always allow thumbnails
return 'allow', filepath
end
if prefix == "tmp" then
-- always deny access to tmp folder
return 'deny'
end
-- comment this in if you do not want to do a preflight request
-- print("ignoring permissions")
-- do return 'allow', filepath end
knora_cookie_header = nil
if cookie ~='' then
key = string.sub(cookie, 0, 4)
if (key ~= "sid=") then
-- cookie key is not valid
print("cookie key is invalid")
else
session_id = string.sub(cookie, 5)
knora_cookie_header = { Cookie = "KnoraAuthentication=" .. session_id }
end
end
knora_url = 'http://' .. config.knora_path .. ':' .. config.knora_port .. '/v1/files/' .. identifier
print("knora_url: " .. knora_url)
result = server.http("GET", knora_url, knora_cookie_header, 5000)
-- check HTTP request was successful
if not result.success then
print("Request to Knora failed: " .. result.errmsg)
-- deny request
return 'deny'
end
if result.status_code ~= 200 then
print("Knora returned HTTP status code " .. ret.status)
print(result.body)
return 'deny'
end
response_json = server.json_to_table(result.body)
print("status: " .. response_json.status)
print("permission code: " .. response_json.permissionCode)
if response_json.status ~= 0 then
-- something went wrong with the request, Knora returned a non zero status
return 'deny'
end
if response_json.permissionCode == 0 then
-- no view permission on file
return 'deny'
elseif response_json.permissionCode == 1 then
-- restricted view permission on file
-- either watermark or size (depends on project, should be returned with permission code by Sipi responder)
return 'restrict:size=' .. config.thumb_size, filepath
elseif response_json.permissionCode >= 2 then
-- full view permissions on file
return 'allow', filepath
else
-- invalid permission code
return 'deny'
end
end
-------------------------------------------------------------------------------
|
--
-- Copyright © 2016 Lukas Rosenthaler, Andrea Bianco, Benjamin Geer,
-- Ivan Subotic, Tobias Schweizer, André Kilchenmann, and André Fatton.
-- This file is part of Sipi.
-- Sipi 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.
-- Sipi 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.
-- Additional permission under GNU AGPL version 3 section 7:
-- If you modify this Program, or any covered work, by linking or combining
-- it with Kakadu (or a modified version of that library), containing parts
-- covered by the terms of the Kakadu Software Licence, the licensors of this
-- Program grant you additional permission to convey the resulting work.
-- 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 Sipi. If not, see <http://www.gnu.org/licenses/>.
-------------------------------------------------------------------------------
-- This function is being called from sipi before the file is served
-- Knora is called to ask for the user's permissions on the file
-- Parameters:
-- prefix: This is the prefix that is given on the IIIF url
-- identifier: the identifier for the image
-- cookie: The cookie that may be present
--
-- Returns:
-- permission:
-- 'allow' : the view is allowed with the given IIIF parameters
-- 'restrict:watermark=<path-to-watermark>' : Add a watermark
-- 'restrict:size=<iiif-size-string>' : reduce size/resolution
-- 'deny' : no access!
-- filepath: server-path where the master file is located
-------------------------------------------------------------------------------
function pre_flight(prefix,identifier,cookie)
--
-- For Knora Sipi integration testing
-- Always the same test file is served
--
filepath = config.imgroot .. '/' .. prefix .. '/' .. 'Leaves.jpg'
print("serving test image " .. filepath)
if prefix == "thumbs" then
-- always allow thumbnails
return 'allow', filepath
end
if prefix == "tmp" then
-- always deny access to tmp folder
return 'deny'
end
-- comment this in if you do not want to do a preflight request
-- print("ignoring permissions")
-- do return 'allow', filepath end
knora_cookie_header = nil
if cookie ~='' then
-- tries to extract the Knora session id from the cookie:
-- gets the digits between "sid=" and the closing ";" (only given in case of several key value pairs)
-- returns nil if it cannot find it
session_id = string.match(cookie, "sid=(%d+);?")
if session_id == nil then
-- no session_id could be extracted
print("cookie key is invalid")
else
knora_cookie_header = { Cookie = "KnoraAuthentication=" .. session_id }
end
end
knora_url = 'http://' .. config.knora_path .. ':' .. config.knora_port .. '/v1/files/' .. identifier
print("knora_url: " .. knora_url)
result = server.http("GET", knora_url, knora_cookie_header, 5000)
-- check HTTP request was successful
if not result.success then
print("Request to Knora failed: " .. result.errmsg)
-- deny request
return 'deny'
end
if result.status_code ~= 200 then
print("Knora returned HTTP status code " .. ret.status)
print(result.body)
return 'deny'
end
response_json = server.json_to_table(result.body)
print("status: " .. response_json.status)
print("permission code: " .. response_json.permissionCode)
if response_json.status ~= 0 then
-- something went wrong with the request, Knora returned a non zero status
return 'deny'
end
if response_json.permissionCode == 0 then
-- no view permission on file
return 'deny'
elseif response_json.permissionCode == 1 then
-- restricted view permission on file
-- either watermark or size (depends on project, should be returned with permission code by Sipi responder)
return 'restrict:size=' .. config.thumb_size, filepath
elseif response_json.permissionCode >= 2 then
-- full view permissions on file
return 'allow', filepath
else
-- invalid permission code
return 'deny'
end
end
-------------------------------------------------------------------------------
|
fix (cookie handling in lua): add improved cookie handling to Knora test config
|
fix (cookie handling in lua): add improved cookie handling to Knora test config
|
Lua
|
agpl-3.0
|
dhlab-basel/Sipi,dhlab-basel/Sipi,dhlab-basel/Sipi,dhlab-basel/Sipi,dhlab-basel/Sipi,dhlab-basel/Sipi
|
2776ce9f4a2517a2f2e71f975fee1f90ac3ace31
|
build/scripts/module/audio.lua
|
build/scripts/module/audio.lua
|
if (not _OPTIONS["united"]) then
project "NazaraAudio"
end
files
{
"../include/Nazara/Audio/**.hpp",
"../include/Nazara/Audio/**.inl",
"../src/Nazara/Audio/**.hpp",
"../src/Nazara/Audio/**.cpp"
}
if (os.is("windows")) then
excludes { "../src/Nazara/Audio/Posix/*.hpp", "../src/Nazara/Audio/Posix/*.cpp" }
links "sndfile-1"
else
excludes { "../src/Nazara/Audio/Win32/*.hpp", "../src/Nazara/Audio/Win32/*.cpp" }
-- Link posix ?
end
if (_OPTIONS["united"]) then
excludes "../src/Nazara/Audio/Debug/Leaks.cpp"
else
configuration "DebugStatic"
links "NazaraCore-s-d"
configuration "ReleaseStatic"
links "NazaraCore-s"
configuration "DebugDLL"
links "NazaraCore-d"
configuration "ReleaseDLL"
links "NazaraCore"
end
|
if (not _OPTIONS["united"]) then
project "NazaraAudio"
end
defines "NAZARA_AUDIO_OPENAL"
files
{
"../include/Nazara/Audio/**.hpp",
"../include/Nazara/Audio/**.inl",
"../src/Nazara/Audio/**.hpp",
"../src/Nazara/Audio/**.cpp"
}
if (os.is("windows")) then
excludes { "../src/Nazara/Audio/Posix/*.hpp", "../src/Nazara/Audio/Posix/*.cpp" }
links "sndfile-1"
else
excludes { "../src/Nazara/Audio/Win32/*.hpp", "../src/Nazara/Audio/Win32/*.cpp" }
-- Link posix ?
end
if (_OPTIONS["united"]) then
excludes "../src/Nazara/Audio/Debug/Leaks.cpp"
else
configuration "DebugStatic"
links "NazaraCore-s-d"
configuration "ReleaseStatic"
links "NazaraCore-s"
configuration "DebugDLL"
links "NazaraCore-d"
configuration "ReleaseDLL"
links "NazaraCore"
end
|
Fixed Audio module compilation
|
Fixed Audio module compilation
Former-commit-id: 6ce67eacb51d71a1bd5f3e3e05a14a615c4b12ea
|
Lua
|
mit
|
DigitalPulseSoftware/NazaraEngine
|
62ec28f0be1b951342e5770c80c4bc0bb7182622
|
protocols/ppp/luasrc/model/network/proto_ppp.lua
|
protocols/ppp/luasrc/model/network/proto_ppp.lua
|
--[[
LuCI - Network model - 3G, PPP, PPtP, PPPoE and PPPoA protocol extension
Copyright 2011 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local netmod = luci.model.network
local _, p
for _, p in ipairs({"ppp", "pptp", "pppoe", "pppoa", "3g"}) do
local proto = netmod:register_protocol(p)
function proto.get_i18n(self)
if p == "ppp" then
return luci.i18n.translate("PPP")
elseif p == "pptp" then
return luci.i18n.translate("PPtP")
elseif p == "3g" then
return luci.i18n.translate("UMTS/GPRS/EV-DO")
elseif p == "pppoe" then
return luci.i18n.translate("PPPoE")
elseif p == "pppoa" then
return luci.i18n.translate("PPPoATM")
end
end
function proto.ifname(self)
return p .. "-" .. self.sid
end
function proto.opkg_package(self)
if p == "ppp" or p == "pptp" then
return p
elseif p == "3g" then
return "comgt"
elseif p == "pppoe" then
return "ppp-mod-pppoe"
elseif p == "pppoa" then
return "ppp-mod-pppoa"
end
end
function proto.is_installed(self)
return nixio.fs.access("/lib/network/" .. p .. ".sh")
end
function proto.is_floating(self)
return (p ~= "pppoe")
end
function proto.is_virtual(self)
return true
end
function proto.get_interfaces(self)
if self:is_floating() then
return nil
else
return netmod.protocol.get_interfaces(self)
end
end
function proto.contains_interface(self, ifc)
if self:is_floating() then
return (netmod:ifnameof(ifc) == self:ifname())
else
return netmod.protocol.contains_interface(self, ifc)
end
end
netmod:register_pattern_virtual("^%s-%%w" % p)
end
|
--[[
LuCI - Network model - 3G, PPP, PPtP, PPPoE and PPPoA protocol extension
Copyright 2011 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local netmod = luci.model.network
local _, p
for _, p in ipairs({"ppp", "pptp", "pppoe", "pppoa", "3g"}) do
local proto = netmod:register_protocol(p)
function proto.get_i18n(self)
if p == "ppp" then
return luci.i18n.translate("PPP")
elseif p == "pptp" then
return luci.i18n.translate("PPtP")
elseif p == "3g" then
return luci.i18n.translate("UMTS/GPRS/EV-DO")
elseif p == "pppoe" then
return luci.i18n.translate("PPPoE")
elseif p == "pppoa" then
return luci.i18n.translate("PPPoATM")
end
end
function proto.ifname(self)
return p .. "-" .. self.sid
end
function proto.opkg_package(self)
if p == "ppp" or p == "pptp" then
return p
elseif p == "3g" then
return "comgt"
elseif p == "pppoe" then
return "ppp-mod-pppoe"
elseif p == "pppoa" then
return "ppp-mod-pppoa"
end
end
function proto.is_installed(self)
if nixio.fs.access("/lib/network/" .. p .. ".sh") then
return true
elseif p == "pppoa" then
return (nixio.fs.glob("/usr/lib/pppd/*/pppoatm.so")() ~= nil)
elseif p == "pppoe" then
return (nixio.fs.glob("/usr/lib/pppd/*/rp-pppoe.so")() ~= nil)
elseif p == "3g" then
return nixio.fs.access("/lib/netifd/proto/3g.sh")
else
return nixio.fs.access("/lib/netifd/proto/ppp.sh")
end
end
function proto.is_floating(self)
return (p ~= "pppoe")
end
function proto.is_virtual(self)
return true
end
function proto.get_interfaces(self)
if self:is_floating() then
return nil
else
return netmod.protocol.get_interfaces(self)
end
end
function proto.contains_interface(self, ifc)
if self:is_floating() then
return (netmod:ifnameof(ifc) == self:ifname())
else
return netmod.protocol.contains_interface(self, ifc)
end
end
netmod:register_pattern_virtual("^%s-%%w" % p)
end
|
protocols/ppp: fix install state detection with netifd
|
protocols/ppp: fix install state detection with netifd
|
Lua
|
apache-2.0
|
schidler/ionic-luci,thesabbir/luci,palmettos/cnLuCI,tcatm/luci,aa65535/luci,LazyZhu/openwrt-luci-trunk-mod,cshore/luci,jchuang1977/luci-1,tcatm/luci,mumuqz/luci,maxrio/luci981213,981213/luci-1,deepak78/new-luci,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,jorgifumi/luci,palmettos/cnLuCI,artynet/luci,Hostle/luci,opentechinstitute/luci,RuiChen1113/luci,artynet/luci,cshore/luci,LazyZhu/openwrt-luci-trunk-mod,lbthomsen/openwrt-luci,tcatm/luci,nmav/luci,lbthomsen/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,Noltari/luci,RuiChen1113/luci,maxrio/luci981213,remakeelectric/luci,openwrt-es/openwrt-luci,LuttyYang/luci,openwrt-es/openwrt-luci,joaofvieira/luci,dismantl/luci-0.12,schidler/ionic-luci,dwmw2/luci,schidler/ionic-luci,openwrt/luci,Hostle/luci,Wedmer/luci,bittorf/luci,jorgifumi/luci,ollie27/openwrt_luci,aa65535/luci,deepak78/new-luci,chris5560/openwrt-luci,rogerpueyo/luci,Sakura-Winkey/LuCI,opentechinstitute/luci,bright-things/ionic-luci,dismantl/luci-0.12,kuoruan/lede-luci,artynet/luci,forward619/luci,florian-shellfire/luci,981213/luci-1,zhaoxx063/luci,Sakura-Winkey/LuCI,jorgifumi/luci,981213/luci-1,ollie27/openwrt_luci,Hostle/openwrt-luci-multi-user,RuiChen1113/luci,jlopenwrtluci/luci,male-puppies/luci,chris5560/openwrt-luci,remakeelectric/luci,dismantl/luci-0.12,urueedi/luci,harveyhu2012/luci,ollie27/openwrt_luci,mumuqz/luci,oyido/luci,lcf258/openwrtcn,tcatm/luci,aircross/OpenWrt-Firefly-LuCI,jchuang1977/luci-1,cshore-firmware/openwrt-luci,taiha/luci,deepak78/new-luci,jchuang1977/luci-1,teslamint/luci,NeoRaider/luci,harveyhu2012/luci,kuoruan/luci,lcf258/openwrtcn,urueedi/luci,daofeng2015/luci,cshore/luci,Kyklas/luci-proto-hso,ff94315/luci-1,NeoRaider/luci,palmettos/test,aa65535/luci,Noltari/luci,aircross/OpenWrt-Firefly-LuCI,harveyhu2012/luci,zhaoxx063/luci,thess/OpenWrt-luci,oneru/luci,remakeelectric/luci,palmettos/test,jlopenwrtluci/luci,chris5560/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,ff94315/luci-1,Wedmer/luci,RuiChen1113/luci,forward619/luci,wongsyrone/luci-1,daofeng2015/luci,lcf258/openwrtcn,artynet/luci,fkooman/luci,Kyklas/luci-proto-hso,oyido/luci,dwmw2/luci,chris5560/openwrt-luci,sujeet14108/luci,jlopenwrtluci/luci,shangjiyu/luci-with-extra,forward619/luci,tobiaswaldvogel/luci,ollie27/openwrt_luci,RuiChen1113/luci,cappiewu/luci,ReclaimYourPrivacy/cloak-luci,lcf258/openwrtcn,Kyklas/luci-proto-hso,daofeng2015/luci,chris5560/openwrt-luci,MinFu/luci,oneru/luci,kuoruan/luci,obsy/luci,remakeelectric/luci,Sakura-Winkey/LuCI,lbthomsen/openwrt-luci,shangjiyu/luci-with-extra,hnyman/luci,jlopenwrtluci/luci,male-puppies/luci,dismantl/luci-0.12,kuoruan/luci,harveyhu2012/luci,oneru/luci,maxrio/luci981213,artynet/luci,dismantl/luci-0.12,kuoruan/lede-luci,maxrio/luci981213,palmettos/cnLuCI,fkooman/luci,fkooman/luci,aircross/OpenWrt-Firefly-LuCI,cappiewu/luci,thesabbir/luci,fkooman/luci,artynet/luci,florian-shellfire/luci,maxrio/luci981213,remakeelectric/luci,marcel-sch/luci,sujeet14108/luci,remakeelectric/luci,cappiewu/luci,palmettos/test,dwmw2/luci,tobiaswaldvogel/luci,981213/luci-1,thess/OpenWrt-luci,ReclaimYourPrivacy/cloak-luci,oyido/luci,deepak78/new-luci,LuttyYang/luci,mumuqz/luci,db260179/openwrt-bpi-r1-luci,slayerrensky/luci,cshore/luci,ollie27/openwrt_luci,Hostle/openwrt-luci-multi-user,deepak78/new-luci,MinFu/luci,cshore-firmware/openwrt-luci,cshore/luci,Noltari/luci,chris5560/openwrt-luci,mumuqz/luci,oneru/luci,harveyhu2012/luci,hnyman/luci,aa65535/luci,ReclaimYourPrivacy/cloak-luci,cshore-firmware/openwrt-luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,kuoruan/lede-luci,opentechinstitute/luci,slayerrensky/luci,sujeet14108/luci,lcf258/openwrtcn,tobiaswaldvogel/luci,david-xiao/luci,deepak78/new-luci,deepak78/new-luci,taiha/luci,oneru/luci,sujeet14108/luci,slayerrensky/luci,marcel-sch/luci,florian-shellfire/luci,ollie27/openwrt_luci,urueedi/luci,NeoRaider/luci,opentechinstitute/luci,keyidadi/luci,bright-things/ionic-luci,kuoruan/lede-luci,RedSnake64/openwrt-luci-packages,nmav/luci,bittorf/luci,palmettos/cnLuCI,teslamint/luci,urueedi/luci,taiha/luci,MinFu/luci,artynet/luci,artynet/luci,oyido/luci,teslamint/luci,daofeng2015/luci,joaofvieira/luci,kuoruan/luci,openwrt/luci,aircross/OpenWrt-Firefly-LuCI,thesabbir/luci,shangjiyu/luci-with-extra,MinFu/luci,palmettos/cnLuCI,nmav/luci,florian-shellfire/luci,forward619/luci,cshore-firmware/openwrt-luci,Sakura-Winkey/LuCI,981213/luci-1,opentechinstitute/luci,shangjiyu/luci-with-extra,kuoruan/luci,obsy/luci,lbthomsen/openwrt-luci,teslamint/luci,hnyman/luci,palmettos/cnLuCI,wongsyrone/luci-1,remakeelectric/luci,LuttyYang/luci,thess/OpenWrt-luci,nmav/luci,cappiewu/luci,male-puppies/luci,florian-shellfire/luci,nwf/openwrt-luci,db260179/openwrt-bpi-r1-luci,rogerpueyo/luci,thesabbir/luci,tobiaswaldvogel/luci,jchuang1977/luci-1,wongsyrone/luci-1,mumuqz/luci,RedSnake64/openwrt-luci-packages,maxrio/luci981213,Wedmer/luci,urueedi/luci,obsy/luci,Wedmer/luci,LuttyYang/luci,tobiaswaldvogel/luci,hnyman/luci,tobiaswaldvogel/luci,schidler/ionic-luci,florian-shellfire/luci,jlopenwrtluci/luci,palmettos/test,ff94315/luci-1,jlopenwrtluci/luci,shangjiyu/luci-with-extra,bittorf/luci,rogerpueyo/luci,obsy/luci,dwmw2/luci,Wedmer/luci,Noltari/luci,forward619/luci,lcf258/openwrtcn,fkooman/luci,LazyZhu/openwrt-luci-trunk-mod,slayerrensky/luci,MinFu/luci,daofeng2015/luci,deepak78/new-luci,db260179/openwrt-bpi-r1-luci,bright-things/ionic-luci,kuoruan/luci,joaofvieira/luci,981213/luci-1,mumuqz/luci,kuoruan/luci,tcatm/luci,LuttyYang/luci,nmav/luci,Kyklas/luci-proto-hso,florian-shellfire/luci,openwrt-es/openwrt-luci,jorgifumi/luci,lcf258/openwrtcn,nmav/luci,fkooman/luci,david-xiao/luci,marcel-sch/luci,zhaoxx063/luci,oyido/luci,bright-things/ionic-luci,slayerrensky/luci,wongsyrone/luci-1,ff94315/luci-1,ff94315/luci-1,bittorf/luci,sujeet14108/luci,cappiewu/luci,obsy/luci,teslamint/luci,Noltari/luci,harveyhu2012/luci,male-puppies/luci,thess/OpenWrt-luci,cshore/luci,oneru/luci,schidler/ionic-luci,urueedi/luci,dwmw2/luci,male-puppies/luci,Hostle/luci,harveyhu2012/luci,hnyman/luci,david-xiao/luci,taiha/luci,chris5560/openwrt-luci,Hostle/openwrt-luci-multi-user,zhaoxx063/luci,dwmw2/luci,Noltari/luci,lbthomsen/openwrt-luci,palmettos/test,Hostle/luci,lbthomsen/openwrt-luci,openwrt/luci,NeoRaider/luci,maxrio/luci981213,ReclaimYourPrivacy/cloak-luci,tcatm/luci,david-xiao/luci,nwf/openwrt-luci,slayerrensky/luci,RedSnake64/openwrt-luci-packages,remakeelectric/luci,sujeet14108/luci,thess/OpenWrt-luci,taiha/luci,RedSnake64/openwrt-luci-packages,thesabbir/luci,keyidadi/luci,opentechinstitute/luci,Hostle/luci,bright-things/ionic-luci,nwf/openwrt-luci,wongsyrone/luci-1,ReclaimYourPrivacy/cloak-luci,wongsyrone/luci-1,openwrt/luci,lcf258/openwrtcn,aircross/OpenWrt-Firefly-LuCI,db260179/openwrt-bpi-r1-luci,palmettos/cnLuCI,shangjiyu/luci-with-extra,maxrio/luci981213,Sakura-Winkey/LuCI,oneru/luci,jorgifumi/luci,MinFu/luci,db260179/openwrt-bpi-r1-luci,Noltari/luci,male-puppies/luci,tcatm/luci,rogerpueyo/luci,mumuqz/luci,dismantl/luci-0.12,zhaoxx063/luci,palmettos/test,palmettos/cnLuCI,jchuang1977/luci-1,ollie27/openwrt_luci,lcf258/openwrtcn,nwf/openwrt-luci,hnyman/luci,openwrt/luci,Kyklas/luci-proto-hso,dismantl/luci-0.12,obsy/luci,rogerpueyo/luci,Wedmer/luci,thesabbir/luci,zhaoxx063/luci,teslamint/luci,jlopenwrtluci/luci,keyidadi/luci,jlopenwrtluci/luci,LazyZhu/openwrt-luci-trunk-mod,cappiewu/luci,nmav/luci,nwf/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,Hostle/openwrt-luci-multi-user,jchuang1977/luci-1,chris5560/openwrt-luci,bittorf/luci,nmav/luci,RuiChen1113/luci,shangjiyu/luci-with-extra,oyido/luci,joaofvieira/luci,opentechinstitute/luci,ReclaimYourPrivacy/cloak-luci,sujeet14108/luci,RedSnake64/openwrt-luci-packages,Wedmer/luci,LazyZhu/openwrt-luci-trunk-mod,Hostle/luci,fkooman/luci,thess/OpenWrt-luci,nmav/luci,taiha/luci,obsy/luci,RuiChen1113/luci,aa65535/luci,ReclaimYourPrivacy/cloak-luci,forward619/luci,981213/luci-1,jorgifumi/luci,NeoRaider/luci,marcel-sch/luci,wongsyrone/luci-1,Kyklas/luci-proto-hso,cshore-firmware/openwrt-luci,schidler/ionic-luci,rogerpueyo/luci,bittorf/luci,Noltari/luci,bittorf/luci,hnyman/luci,openwrt/luci,david-xiao/luci,nwf/openwrt-luci,lbthomsen/openwrt-luci,cshore/luci,forward619/luci,schidler/ionic-luci,palmettos/test,rogerpueyo/luci,artynet/luci,thess/OpenWrt-luci,kuoruan/lede-luci,jorgifumi/luci,male-puppies/luci,NeoRaider/luci,fkooman/luci,ff94315/luci-1,Sakura-Winkey/LuCI,thess/OpenWrt-luci,opentechinstitute/luci,openwrt-es/openwrt-luci,cshore-firmware/openwrt-luci,male-puppies/luci,keyidadi/luci,palmettos/test,kuoruan/luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,aa65535/luci,forward619/luci,cshore/luci,schidler/ionic-luci,aa65535/luci,NeoRaider/luci,nwf/openwrt-luci,wongsyrone/luci-1,MinFu/luci,oneru/luci,david-xiao/luci,taiha/luci,ReclaimYourPrivacy/cloak-luci,david-xiao/luci,aircross/OpenWrt-Firefly-LuCI,keyidadi/luci,daofeng2015/luci,ff94315/luci-1,cshore-firmware/openwrt-luci,kuoruan/lede-luci,daofeng2015/luci,cappiewu/luci,bright-things/ionic-luci,obsy/luci,openwrt/luci,kuoruan/lede-luci,keyidadi/luci,joaofvieira/luci,thesabbir/luci,oyido/luci,Hostle/luci,teslamint/luci,Sakura-Winkey/LuCI,ollie27/openwrt_luci,LazyZhu/openwrt-luci-trunk-mod,slayerrensky/luci,Hostle/luci,daofeng2015/luci,LuttyYang/luci,cappiewu/luci,zhaoxx063/luci,joaofvieira/luci,hnyman/luci,LuttyYang/luci,bittorf/luci,Hostle/openwrt-luci-multi-user,openwrt-es/openwrt-luci,sujeet14108/luci,openwrt/luci,dwmw2/luci,ff94315/luci-1,david-xiao/luci,jchuang1977/luci-1,joaofvieira/luci,tcatm/luci,db260179/openwrt-bpi-r1-luci,lcf258/openwrtcn,aa65535/luci,RedSnake64/openwrt-luci-packages,jchuang1977/luci-1,openwrt-es/openwrt-luci,Noltari/luci,bright-things/ionic-luci,Kyklas/luci-proto-hso,bright-things/ionic-luci,keyidadi/luci,NeoRaider/luci,marcel-sch/luci,LuttyYang/luci,urueedi/luci,Hostle/openwrt-luci-multi-user,slayerrensky/luci,RuiChen1113/luci,mumuqz/luci,RedSnake64/openwrt-luci-packages,Hostle/openwrt-luci-multi-user,Hostle/openwrt-luci-multi-user,dwmw2/luci,marcel-sch/luci,cshore-firmware/openwrt-luci,Wedmer/luci,db260179/openwrt-bpi-r1-luci,zhaoxx063/luci,MinFu/luci,marcel-sch/luci,florian-shellfire/luci,urueedi/luci,joaofvieira/luci,jorgifumi/luci,teslamint/luci,tobiaswaldvogel/luci,keyidadi/luci,taiha/luci,marcel-sch/luci,oyido/luci,rogerpueyo/luci,shangjiyu/luci-with-extra,kuoruan/lede-luci,nwf/openwrt-luci,thesabbir/luci
|
94308493bd13ee2ff1eca06a6c05dbad987a05f7
|
deps/repl.lua
|
deps/repl.lua
|
--[[
Copyright 2014-2015 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
--[[lit-meta
name = "luvit/repl"
version = "2.0.1"
dependencies = {
"luvit/[email protected]",
"luvit/[email protected]",
}
license = "Apache 2"
homepage = "https://github.com/luvit/luvit/blob/master/deps/repl.lua"
description = "Advanced auto-completing repl for luvit lua."
tags = {"luvit", "tty", "repl"}
]]
local uv = require('uv')
local utils = require('utils')
local pathJoin = require('luvi').path.join
local Editor = require('readline').Editor
local History = require('readline').History
local _builtinLibs = { 'buffer', 'childprocess', 'codec', 'core',
'dgram', 'dns', 'fs', 'helpful', 'hooks', 'http-codec', 'http',
'https', 'json', 'los', 'net', 'pretty-print',
'querystring', 'readline', 'timer', 'url', 'utils',
'stream', 'tls', 'path'
}
return function (stdin, stdout, greeting)
local req, mod = require('require')(pathJoin(uv.cwd(), "repl"))
local oldGlobal = _G
local global = setmetatable({
require = req,
module = mod,
}, {
__index = function (_, key)
if key == "thread" then return coroutine.running() end
return oldGlobal[key]
end
})
if greeting then stdout:write(greeting .. '\n') end
local c = utils.color
local function gatherResults(success, ...)
local n = select('#', ...)
return success, { n = n, ... }
end
local function printResults(results)
for i = 1, results.n do
results[i] = utils.dump(results[i])
end
stdout:write(table.concat(results, '\t') .. '\n')
end
local buffer = ''
local function evaluateLine(line)
if line == "<3" or line == "♥" then
stdout:write("I " .. c("err") .. "♥" .. c() .. " you too!\n")
return '>'
end
local chunk = buffer .. line
local f, err = loadstring('return ' .. chunk, 'REPL') -- first we prefix return
if not f then
f, err = loadstring(chunk, 'REPL') -- try again without return
end
if f then
setfenv(f, global)
buffer = ''
local success, results = gatherResults(xpcall(f, debug.traceback))
if success then
-- successful call
if results.n > 0 then
printResults(results)
end
else
-- error
stdout:write(results[1] .. '\n')
end
else
if err:match "'<eof>'$" then
-- Lua expects some more input; stow it away for next time
buffer = chunk .. '\n'
return '>> '
else
stdout:write(err .. '\n')
buffer = ''
end
end
return '> '
end
local function completionCallback(line)
local base, sep, rest = string.match(line, "^(.*)([.:])(.*)")
if not base then
rest = line
end
local prefix = string.match(rest, "^[%a_][%a%d_]*")
if prefix and prefix ~= rest then return end
local scope
if base then
local f = loadstring("return " .. base)
setfenv(f, global)
scope = f()
else
base = ''
sep = ''
scope = global
end
local matches = {}
local prop = sep ~= ':'
while type(scope) == "table" do
for key, value in pairs(scope) do
if (prop or (type(value) == "function")) and
((not prefix) or (string.match(key, "^" .. prefix))) then
matches[key] = true
end
end
scope = getmetatable(scope)
scope = scope and scope.__index
end
local items = {}
for key in pairs(matches) do
items[#items + 1] = key
end
table.sort(items)
if #items == 1 then
return base .. sep .. items[1]
elseif #items > 1 then
return items
end
end
local function start(historyLines, onSaveHistoryLines)
local prompt = "> "
local history = History.new()
if historyLines then
history:load(historyLines)
end
local editor = Editor.new({
stdin = stdin,
stdout = stdout,
completionCallback = completionCallback,
history = history
})
local function onLine(err, line)
assert(not err, err)
coroutine.wrap(function ()
if line then
prompt = evaluateLine(line)
editor:readLine(prompt, onLine)
-- TODO: break out of >> with control+C
elseif onSaveHistoryLines then
onSaveHistoryLines(history:dump())
end
end)()
end
editor:readLine(prompt, onLine)
-- Namespace builtin libs to make the repl easier to play with
-- Requires with filenames with a - in them will be camelcased
-- e.g. pretty-print -> prettyPrint
table.foreach(_builtinLibs, function(_, lib)
local requireName = lib:gsub('-.', function (char) return char:sub(2):upper() end)
local req = string.format('%s = require("%s")', requireName, lib)
evaluateLine(req)
end)
end
return {
start = start,
evaluateLine = evaluateLine,
}
end
|
--[[
Copyright 2014-2015 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
--[[lit-meta
name = "luvit/repl"
version = "2.0.1"
dependencies = {
"luvit/[email protected]",
"luvit/[email protected]",
}
license = "Apache 2"
homepage = "https://github.com/luvit/luvit/blob/master/deps/repl.lua"
description = "Advanced auto-completing repl for luvit lua."
tags = {"luvit", "tty", "repl"}
]]
local uv = require('uv')
local utils = require('utils')
local pathJoin = require('luvi').path.join
local Editor = require('readline').Editor
local History = require('readline').History
local _builtinLibs = { 'buffer', 'childprocess', 'codec', 'core',
'dgram', 'dns', 'fs', 'helpful', 'hooks', 'http-codec', 'http',
'https', 'json', 'los', 'net', 'pretty-print',
'querystring', 'readline', 'timer', 'url', 'utils',
'stream', 'tls', 'path'
}
return function (stdin, stdout, greeting)
local req, mod = require('require')(pathJoin(uv.cwd(), "repl"))
local oldGlobal = _G
local global = setmetatable({
require = req,
module = mod,
}, {
__index = function (_, key)
if key == "thread" then return coroutine.running() end
return oldGlobal[key]
end
})
if greeting then stdout:write(greeting .. '\n') end
local c = utils.color
local function gatherResults(success, ...)
local n = select('#', ...)
return success, { n = n, ... }
end
local function printResults(results)
for i = 1, results.n do
results[i] = utils.dump(results[i])
end
stdout:write(table.concat(results, '\t') .. '\n')
end
local buffer = ''
local function evaluateLine(line)
if line == "<3" or line == "♥" then
stdout:write("I " .. c("err") .. "♥" .. c() .. " you too!\n")
return '>'
end
local chunk = buffer .. line
local f, err = loadstring('return ' .. chunk, 'REPL') -- first we prefix return
if not f then
f, err = loadstring(chunk, 'REPL') -- try again without return
end
if f then
setfenv(f, global)
buffer = ''
local success, results = gatherResults(xpcall(f, debug.traceback))
if success then
-- successful call
if results.n > 0 then
printResults(results)
end
elseif type(results[1]) == 'string' then
-- error
stdout:write(results[1] .. '\n')
else
-- error calls with non-string message objects will pass through debug.traceback without a stacktrace added
stdout:write('error with unexpected error message type (' .. type(results[1]) .. '), no stacktrace available\n')
end
else
if err:match "'<eof>'$" then
-- Lua expects some more input; stow it away for next time
buffer = chunk .. '\n'
return '>> '
else
stdout:write(err .. '\n')
buffer = ''
end
end
return '> '
end
local function completionCallback(line)
local base, sep, rest = string.match(line, "^(.*)([.:])(.*)")
if not base then
rest = line
end
local prefix = string.match(rest, "^[%a_][%a%d_]*")
if prefix and prefix ~= rest then return end
local scope
if base then
local f = loadstring("return " .. base)
setfenv(f, global)
scope = f()
else
base = ''
sep = ''
scope = global
end
local matches = {}
local prop = sep ~= ':'
while type(scope) == "table" do
for key, value in pairs(scope) do
if (prop or (type(value) == "function")) and
((not prefix) or (string.match(key, "^" .. prefix))) then
matches[key] = true
end
end
scope = getmetatable(scope)
scope = scope and scope.__index
end
local items = {}
for key in pairs(matches) do
items[#items + 1] = key
end
table.sort(items)
if #items == 1 then
return base .. sep .. items[1]
elseif #items > 1 then
return items
end
end
local function start(historyLines, onSaveHistoryLines)
local prompt = "> "
local history = History.new()
if historyLines then
history:load(historyLines)
end
local editor = Editor.new({
stdin = stdin,
stdout = stdout,
completionCallback = completionCallback,
history = history
})
local function onLine(err, line)
assert(not err, err)
coroutine.wrap(function ()
if line then
prompt = evaluateLine(line)
editor:readLine(prompt, onLine)
-- TODO: break out of >> with control+C
elseif onSaveHistoryLines then
onSaveHistoryLines(history:dump())
end
end)()
end
editor:readLine(prompt, onLine)
-- Namespace builtin libs to make the repl easier to play with
-- Requires with filenames with a - in them will be camelcased
-- e.g. pretty-print -> prettyPrint
table.foreach(_builtinLibs, function(_, lib)
local requireName = lib:gsub('-.', function (char) return char:sub(2):upper() end)
local req = string.format('%s = require("%s")', requireName, lib)
evaluateLine(req)
end)
end
return {
start = start,
evaluateLine = evaluateLine,
}
end
|
repl: Fix error() calls with a non-string message breaking the repl
|
repl: Fix error() calls with a non-string message breaking the repl
Fixes #898
`error()` calls with non-string messages will now output the following:
```
Welcome to the Luvit repl!
> error(function() end)
error with unexpected error message type (function), no stacktrace available
> error()
error with unexpected error message type (nil), no stacktrace available
```
|
Lua
|
apache-2.0
|
luvit/luvit,zhaozg/luvit,luvit/luvit,zhaozg/luvit
|
33d07f0316ffbd49ea6736c9cedf32d91fc76992
|
Resources/Scripts/Modules/ObjectLoad.lua
|
Resources/Scripts/Modules/ObjectLoad.lua
|
import('GlobalVars')
import('Actions')
function NewObject(id)
function CopyActions(obj)
obj.trigger = {}
if obj.action ~= nil then
local id
for id = 1, #obj.action do
if obj.action[id] ~= nil then
obj.trigger[obj.action[id].trigger] = obj.action[id]
end
end
end
if obj.trigger.activate ~= nil and obj.trigger.activate.count > 255 then
obj.trigger.activate.activateInterval = math.floor(obj.trigger.activate.count/2^23)
obj.trigger.activate.intervalRange = math.floor(obj.trigger.activate.count/2^15)%2^7
-- math.floor(c/2^7)%7 --No discernable use.
obj.trigger.activate.count = obj.trigger.activate.count%2^7
obj.trigger.activateInterval = obj.trigger.activate.activateInterval / TIME_FACTOR
obj.trigger.activateRange = obj.trigger.activate.intervalRange / TIME_FACTOR
obj.trigger.nextActivate = mode_manager.time() + obj.trigger.activateInterval + math.random(0,obj.trigger.activateRange)
else
obj.trigger.activateInterval = 0
end
end
local newObj = deepcopy(gameData["Objects"][id])
if newObj["sprite-id"] ~= nil then
newObj.sprite = newObj["sprite-id"]
newObj.spriteDim = graphics.sprite_dimensions("Id/" .. newObj.sprite)
end
if newObj.mass == nil then
newObj.mass = 1000.0 --We should add a way for objects to me immobile
end
--Generalize controls for the AI
newObj.control = {
accel = false;
decel = false;
left = false;
right = false;
beam = false;
pulse = false;
special = false;
warp = false;
}
newObj.physics = physics.new_object(newObj.mass)
newObj.physics.angular_velocity = 0.00
if newObj.spriteDim ~= nil then
newObj.physics.collision_radius = hypot1(newObj.spriteDim) / 32
else
newObj.physics.collision_radius = 1
end
if newObj["initial-age"] ~= nil then
newObj.created = mode_manager.time()
newObj.age = newObj["initial-age"] / TIME_FACTOR
--the documentation for Hera says that initial-age is in 20ths of a second but it appears to be 60ths
end
if newObj.animation ~= nil then
newObj.animation.start = mode_manager.time()
newObj.animation.frameTime = newObj.animation["frame-speed"] / TIME_FACTOR / 30.0 --Is the ratio here 1:1800?
end
newObj.healthMax = newObj.health + 0
newObj.dead = false
--Prepare devices
if newObj.weapon ~= nil then
local wid
for wid = 1, #newObj.weapon do
if newObj.weapon[newObj.weapon[wid].type] ~= nil then
error("More than one weapon of type '" .. newObj.weapon[wid].type .. "' defined.")
end
local weap = deepcopy(gameData["Objects"][newObj.weapon[wid].id])
weap.position = deepcopy(newObj.weapon[wid].position)
weap.position.last = 1
weap.ammo = deepcopy(weap.device.ammo)
weap.parent = newObj
weap.device.lastActivated = -weap.device["fire-time"] / TIME_FACTOR
CopyActions(weap)
newObj.weapon[newObj.weapon[wid].type] = weap
end
end
-- energy & battery
if newObj.energy ~= nil then
newObj.energyMax = newObj.energy
newObj.battery = newObj.energy * 5
newObj.batteryMax = newObj.energy
end
CopyActions(newObj)
return newObj
end
|
import('GlobalVars')
import('Actions')
function NewObject(id)
function CopyActions(obj)
obj.trigger = {}
if obj.action ~= nil then
local id
for id = 1, #obj.action do
if obj.action[id] ~= nil then
obj.trigger[obj.action[id].trigger] = obj.action[id]
end
end
end
if obj.trigger.activate ~= nil and obj.trigger.activate.count > 255 then
obj.trigger.activate.activateInterval = math.floor(obj.trigger.activate.count/2^23)
obj.trigger.activate.intervalRange = math.floor(obj.trigger.activate.count/2^15)%2^7
-- math.floor(c/2^7)%7 --No discernable use.
obj.trigger.activate.count = obj.trigger.activate.count%2^7
obj.trigger.activateInterval = obj.trigger.activate.activateInterval / TIME_FACTOR
obj.trigger.activateRange = obj.trigger.activate.intervalRange / TIME_FACTOR
obj.trigger.nextActivate = mode_manager.time() + obj.trigger.activateInterval + math.random(0,obj.trigger.activateRange)
else
obj.trigger.activateInterval = 0
end
end
local newObj = deepcopy(gameData["Objects"][id])
if newObj["sprite-id"] ~= nil then
newObj.sprite = newObj["sprite-id"]
newObj.spriteDim = graphics.sprite_dimensions("Id/" .. newObj.sprite)
end
if newObj.mass == nil then
newObj.mass = 1000.0 --We should add a way for objects to me immobile
end
--Generalize controls for the AI
newObj.control = {
accel = false;
decel = false;
left = false;
right = false;
beam = false;
pulse = false;
special = false;
warp = false;
}
newObj.physics = physics.new_object(newObj.mass)
newObj.physics.angular_velocity = 0.00
if newObj.spriteDim ~= nil then
newObj.physics.collision_radius = hypot1(newObj.spriteDim) / 32
else
newObj.physics.collision_radius = 1
end
if newObj["initial-age"] ~= nil then
newObj.created = mode_manager.time()
newObj.age = newObj["initial-age"] / TIME_FACTOR
--the documentation for Hera says that initial-age is in 20ths of a second but it appears to be 60ths
end
if newObj.animation ~= nil then
newObj.animation.start = mode_manager.time()
newObj.animation.frameTime = newObj.animation["frame-speed"] / TIME_FACTOR / 30.0 --Is the ratio here 1:1800?
end
--Prepare devices
if newObj.weapon ~= nil then
local wid
for wid = 1, #newObj.weapon do
if newObj.weapon[newObj.weapon[wid].type] ~= nil then
error("More than one weapon of type '" .. newObj.weapon[wid].type .. "' defined.")
end
local weap = deepcopy(gameData["Objects"][newObj.weapon[wid].id])
weap.position = deepcopy(newObj.weapon[wid].position)
weap.position.last = 1
weap.ammo = deepcopy(weap.device.ammo)
weap.parent = newObj
weap.device.lastActivated = -weap.device["fire-time"] / TIME_FACTOR
CopyActions(weap)
newObj.weapon[newObj.weapon[wid].type] = weap
end
end
newObj.healthMax = newObj.health
newObj.dead = false
-- energy & battery
if newObj.energy ~= nil then
newObj.energyMax = newObj.energy
newObj.battery = newObj.energy * 5
newObj.batteryMax = newObj.battery
end
CopyActions(newObj)
return newObj
end
|
Fixed battery meter on right side of screen.
|
Fixed battery meter on right side of screen.
Signed-off-by: Scott McClaugherty <[email protected]>
|
Lua
|
mit
|
prophile/xsera,prophile/xsera,adam000/xsera,adam000/xsera,prophile/xsera,prophile/xsera,adam000/xsera,prophile/xsera,adam000/xsera
|
01de24ddbec599bc3245aca8d1c1ca21382570a0
|
agents/monitoring/tests/fixtures/protocol/server.lua
|
agents/monitoring/tests/fixtures/protocol/server.lua
|
local net = require('net')
local JSON = require('json')
local fixtures = require('./')
local LineEmitter = require('line-emitter').LineEmitter
local tls = require('tls')
local timer = require('timer')
local lineEmitter = LineEmitter:new()
local port = 50041
local keyPem = [[
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd
CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre
535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB
AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0
kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb
aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9
2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC
M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg
lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM
wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm
Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR
9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd
0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei
-----END RSA PRIVATE KEY-----
]]
local certPem = [[
-----BEGIN CERTIFICATE-----
MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV
BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l
czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh
dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw
OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG
A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz
dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG
9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO
kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR
AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k
d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG
A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG
EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx
EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl
MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G
CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP
e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n
dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN
-----END CERTIFICATE-----
]]
local options = {
cert = certPem,
key = keyPem
}
local respond = function(client, payload)
-- skip responses to requests
if payload.method == nil then
return
end
local response_method = payload.method .. '.response'
local response = JSON.parse(fixtures[response_method])
local response_out = nil
response.target = payload.source
response.source = payload.target
response.id = payload.id
print("Sending response:")
p(response)
response_out = JSON.stringify(response)
response_out:gsub("\n", " ")
client:write(response_out .. '\n')
end
local send_schedule_changed = function(client)
local request = fixtures['check_schedule.changed.request']
print("Sending request:")
p(JSON.parse(request))
client:write(request .. '\n')
end
tls.createServer(options, function (client)
client:pipe(lineEmitter)
lineEmitter:on('data', function(line)
local payload = JSON.parse(line)
print("Got payload:")
p(payload)
respond(client, payload)
end)
local send_schedule_changed_timer = timer.setTimeout(2000, function()
send_schedule_changed(client)
end)
local send_schedule_changed_timer = timer.setInterval(60000, function()
send_schedule_changed(client)
end)
end):listen(port)
print("TCP echo server listening on port " .. port)
|
local net = require('net')
local JSON = require('json')
local fixtures = require('./')
local LineEmitter = require('line-emitter').LineEmitter
local tls = require('tls')
local timer = require('timer')
local lineEmitter = LineEmitter:new()
local port = 50041
local send_schedule_changed_initial = 2000
local send_schedule_changed_interval = 60000
local keyPem = [[
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd
CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre
535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB
AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0
kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb
aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9
2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC
M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg
lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM
wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm
Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR
9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd
0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei
-----END RSA PRIVATE KEY-----
]]
local certPem = [[
-----BEGIN CERTIFICATE-----
MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV
BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l
czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh
dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw
OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG
A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz
dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG
9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO
kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR
AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k
d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG
A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG
EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx
EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl
MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G
CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP
e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n
dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN
-----END CERTIFICATE-----
]]
local options = {
cert = certPem,
key = keyPem
}
local respond = function(client, payload)
-- skip responses to requests
if payload.method == nil then
return
end
local response_method = payload.method .. '.response'
local response = JSON.parse(fixtures[response_method])
local response_out = nil
response.target = payload.source
response.source = payload.target
response.id = payload.id
print("Sending response:")
p(response)
response_out = JSON.stringify(response)
response_out:gsub("\n", " ")
client:write(response_out .. '\n')
end
local send_schedule_changed = function(client)
local request = fixtures['check_schedule.changed.request']
print("Sending request:")
p(JSON.parse(request))
client:write(request .. '\n')
end
tls.createServer(options, function (client)
client:pipe(lineEmitter)
lineEmitter:on('data', function(line)
local payload = JSON.parse(line)
print("Got payload:")
p(payload)
respond(client, payload)
end)
timer.setTimeout(send_schedule_changed_initial, function()
send_schedule_changed(client)
end)
timer.setInterval(send_schedule_changed_interval, function()
send_schedule_changed(client)
end)
end):listen(port)
print("TCP echo server listening on port " .. port)
|
monitoring: fixtures: server: move constants to top
|
monitoring: fixtures: server: move constants to top
move the timer constants to the top of the file.
|
Lua
|
apache-2.0
|
kans/zirgo,kans/zirgo,kans/zirgo
|
8b8004963c4810a4f44966ad61ae8da36c633ec9
|
tests/provodnik/titles.lua
|
tests/provodnik/titles.lua
|
require "sprites"
require "theme"
require "timer"
local w, h
local font
local font_height
local text = {
{ "ПРОВОДНИК", style = 1},
{ },
{ "Сюжет и код игры:", style = 2},
{ "Петр Косых" },
{ },
{ "Иллюстрации:", style = 2 },
{ "Петр Косых" },
{ },
{ "Музыка:", style = 2 },
{ "Петр Советов" },
{ },
{ "Тестирование:", style = 2 },
{ "kerber" },
{ "Петр Советов" },
{ },
{ "Игра написана в ферале 2017" },
{ "Для тестирования движка STEAD3"},
{ },
{ "Спасибо Вам за прохождение!" },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ "КОНЕЦ", style = 1 },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
}
local offset = 0
local pos = 1
local line
local ww, hh
function game:timer()
local scr = sprite.scr()
-- scroll
scr:copy(0, 1, w, h - 1, scr, 0, 0)
if offset >= font_height then
pos = pos + 1
offset = 0
end
if offset == 0 then
if pos <= #text then
line = text[pos]
line = font:text(line[1] or ' ', line.color or 'white', line.style or 0)
ww, hh = line:size()
else
line = false
end
end
if line then
offset = offset + 1
scr:fill(0, h - offset, w, offset, 'black')
line:draw(scr, math.floor((w - ww) / 2), h - offset)
end
end
room {
nam = 'legacy_titles',
title = false,
decor = function(s)
for k, v in ipairs(text) do
if v.style == 1 then
pn(txt:center(txt:bold(v[1] or '')))
elseif v.style == 2 then
pn(txt:center(txt:em(v[1] or '')))
else
pn(txt:center(v[1] or ''))
end
end
end;
}
global 'ontitles' (false)
function end_titles()
offset = 0
ontitles = true
if not sprite.direct(true) then
instead.fading = 32
walk ('legacy_titles', false)
return
end
walk ('legacy_titles', false)
w, h = std.tonum(theme.get 'scr.w'), std.tonum(theme.get 'scr.h')
local fn = theme.get('win.fnt.name')
font = sprite.fnt(fn, 16)
font_height = font:height()
sprite.scr():fill 'black'
timer:set(30)
return true
end
|
require "sprites"
require "theme"
require "timer"
local w, h
local font
local font_height
local text = {
{ "ПРОВОДНИК", style = 1},
{ },
{ "Сюжет и код игры:", style = 2},
{ "Петр Косых" },
{ },
{ "Иллюстрации:", style = 2 },
{ "Петр Косых" },
{ },
{ "Музыка:", style = 2 },
{ "Петр Советов" },
{ },
{ "Тестирование:", style = 2 },
{ "kerber" },
{ "Петр Советов" },
{ },
{ "Игра написана в ферале 2017" },
{ "Для тестирования движка STEAD3"},
{ },
{ "Спасибо Вам за прохождение!" },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ "КОНЕЦ", style = 1 },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
}
local offset = 0
local pos = 1
local line
local ww, hh
function game:timer()
local scr = sprite.scr()
-- scroll
scr:copy(0, 1, w, h - 1, scr, 0, 0)
if offset >= font_height then
pos = pos + 1
offset = 0
end
if offset == 0 then
if pos <= #text then
line = text[pos]
line = font:text(line[1] or ' ', line.color or 'white', line.style or 0)
ww, hh = line:size()
else
line = false
end
end
if line then
offset = offset + 1
scr:fill(0, h - offset, w, offset, 'black')
line:draw(scr, math.floor((w - ww) / 2), h - offset)
end
end
room {
nam = 'legacy_titles',
title = false,
decor = function(s)
for k, v in ipairs(text) do
if v.style == 1 then
pn(txt:center(txt:bold(v[1] or '')))
elseif v.style == 2 then
pn(txt:center(txt:em(v[1] or '')))
else
pn(txt:center(v[1] or ''))
end
end
end;
}
global 'ontitles' (false)
local activated
room {
title = false;
nam = 'black';
onenter = function()
theme.set('scr.gfx.bg', '')
theme.set('scr.col.bg', 'black')
theme.set('menu.button.x', w)
timer:set(1000)
end;
timer = function(s)
if activated then
return false
end
activated = true
timer:set(30)
sprite.direct(true)
sprite.scr():fill 'black'
return false
end;
}
function end_titles()
offset = 0
ontitles = true
if true or not sprite.direct(true) then
timer:stop()
instead.fading = 32
walk ('legacy_titles', false)
return
end
sprite.direct(false)
instead.fading = 32
w, h = std.tonum(theme.get 'scr.w'), std.tonum(theme.get 'scr.h')
local fn = theme.get('win.fnt.name')
font = sprite.fnt(fn, 16)
font_height = font:height()
walk ('black', false)
end
|
titles fix
|
titles fix
|
Lua
|
mit
|
gl00my/stead3
|
e2f8c4e75517b8455fedb65b66463f1e4dea7707
|
testserver/item/chimney.lua
|
testserver/item/chimney.lua
|
-- Tree Script
-- Envi
require("base.common")
require("content.chimney")
module("item.chimney", package.seeall)
-- UPDATE common SET com_script='item.chimney' WHERE com_itemid IN (268, 269);
ChimneyListGerman =
{
"PLACEHOLDER.",
};
ChimneyListEnglish =
{
"PLACEHOLDER.",
};
function LookAtItemIdent(User,Item)
local test = "no value";
if (first==nil) then
content.chimney.InitChimey()
first=1;
end
-- fetching local references
local signTextDe = content.chimney.signTextDe;
local signTextEn = content.chimney.signTextEn;
local signCoo = content.chimney.signCoo;
local signItemId = content.chimney.signItemId;
local signPerception = content.chimney.signPerception;
found = false;
UserPer = User:increaseAttrib("perception",0);
tablePosition = Item.pos.x .. Item.pos.y .. Item.pos.z;
if signCoo ~= nil then
if (signCoo[tablePosition] ~= nil) then
for i, signpos in pairs(signCoo[tablePosition]) do
if Item.pos == signpos then
if (UserPer >= signPerception[tablePosition][i]) then
found = true;
world:itemInform(User,Item,base.common.GetNLS(User,string.gsub(signTextDe[tablePosition][i],"currentChar",User.name),string.gsub(signTextEn[tablePosition][i],"currentChar",User.name)));
test = signTextDe[tablePosition][i];
else
found = true;
world:itemInform(User,Item,base.common.GetNLS(User,"~Du erkennst, dass hier etwas ist, kannst es aber nicht entziffern, da du zu blind bist.~","~You recognise something, but you cannot read it, because you are too blind.~"));
end
end
end
end
end
--[[local outText = checkNoobiaSigns(User,Item.pos);
if outText and not found then
world:itemInform(User,Item,outText);
found = true;
end ]]
if not found then
world:itemInform(User,Item,world:getItemName(Item.id,User:getPlayerLanguage()));
end
--[[if not found then
val = ((Item.pos.x + Item.pos.y + Item.pos.z) % table.getn(ChimneyListGerman))+1;
world:itemInform( User, Item, base.common.GetNLS(User, ChimneyListGerman[val], ChimneyListEnglish[val]) );
end]]--
-- User:inform("in LookAtItem of base_wegweiser.lua");
--User:inform(test);
end
--[[
LookAtItemIdent
identity of LookAtItem
]]
LookAtItem = LookAtItemIdent;
|
-- Tree Script
-- Envi
require("base.common")
require("content.chimney")
module("item.chimney", package.seeall)
-- UPDATE common SET com_script='item.chimney' WHERE com_itemid IN (268, 269);
ChimneyListGerman =
{
"PLACEHOLDER.",
};
ChimneyListEnglish =
{
"PLACEHOLDER.",
};
function LookAtItemIdent(User,Item)
local test = "no value";
if (first==nil) then
content.chimney.InitChimey()
first=1;
end
-- fetching local references
local signTextDe = content.chimney.signTextDe;
local signTextEn = content.chimney.signTextEn;
local signCoo = content.chimney.signCoo;
local signItemId = content.chimney.signItemId;
local signPerception = content.chimney.signPerception;
found = false;
UserPer = User:increaseAttrib("perception",0);
tablePosition = Item.pos.x .. Item.pos.y .. Item.pos.z;
if signCoo ~= nil then
if (signCoo[tablePosition] ~= nil) then
for i, signpos in pairs(signCoo[tablePosition]) do
if Item.pos == signpos then
if (UserPer >= signPerception[tablePosition][i]) then
found = true;
world:itemInform(User,Item,base.common.GetNLS(User,string.gsub(signTextDe[tablePosition][i],"currentChar",User.name),string.gsub(signTextEn[tablePosition][i],"currentChar",User.name)));
test = signTextDe[tablePosition][i];
else
found = true;
world:itemInform(User,Item,base.common.GetNLS(User,"~Du erkennst, dass hier etwas ist, kannst es aber nicht entziffern, da du zu blind bist.~","~You recognise something, but you cannot read it, because you are too blind.~"));
end
end
end
end
end
--[[local outText = checkNoobiaSigns(User,Item.pos);
if outText and not found then
world:itemInform(User,Item,outText);
found = true;
end ]]
if not found then
world:itemInform(User,Item,base.lookat.GenerateLookAt(User, Item, base.lookat.NONE));
end
--[[if not found then
val = ((Item.pos.x + Item.pos.y + Item.pos.z) % table.getn(ChimneyListGerman))+1;
world:itemInform( User, Item, base.common.GetNLS(User, ChimneyListGerman[val], ChimneyListEnglish[val]) );
end]]--
-- User:inform("in LookAtItem of base_wegweiser.lua");
--User:inform(test);
end
--[[
LookAtItemIdent
identity of LookAtItem
]]
LookAtItem = LookAtItemIdent;
|
fixed 'normal' lookat, special lookat needs work or should be removed
|
fixed 'normal' lookat, special lookat needs work or should be removed
|
Lua
|
agpl-3.0
|
vilarion/Illarion-Content,LaFamiglia/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content,Illarion-eV/Illarion-Content
|
a75ff198dcf8fddda1a8adc55ef343cd75aac1ee
|
lua/cache.lua
|
lua/cache.lua
|
-- Store the cache instance in a standalone lua file to cache it.
local BACKEND_PREFIX = '/_'
local cacher = require 'cacher'
local redis = require 'redis'
local http = require 'resty.http'
local json = require 'cjson'
local json_encode = json.encode
local red = redis:new()
local function hash_key ()
local key = ngx.var.uri
local headers = ngx.req.get_headers()
local custom_field = headers['gaia-custom-field']
if custom_field then
key = key .. ',custom=' .. custom_field
end
local args = ngx.req.get_uri_args()
key = key .. ',args=' .. json_encode(args)
if headers['gaia-enable-body'] then
ngx.req.read_body()
key = key .. ',body=' .. ngx.req.get_body_data()
end
return key
end
local function get (key)
return red:eget(key)
end
local function set (key, value)
local expire_header = ngx.req.get_headers()['gaia-expires']
local expires = expire_header and tonumber(expire_header) or nil
return red:eset(key, value, expires)
end
local function load (key)
return ngx.location.capture(BACKEND_PREFIX .. ngx.var.uri, {
args = ngx.req.get_uri_args()
})
end
local function when (res)
local ok, parsed = pcall(json_decode, res.body)
return not ok or ok and parsed.code == 200
end
local cache = cacher
:new()
:hash_key(hash_key)
:getter(get)
:setter(set)
:loader(load)
:when(when)
return cache
|
-- Store the cache instance in a standalone lua file to cache it.
local BACKEND_PREFIX = '/_'
local cacher = require 'cacher'
local redis = require 'redis'
local http = require 'resty.http'
local json = require 'cjson'
local json_encode = json.encode
local json_decode = json.decode
local red = redis:new()
local function hash_key ()
local key = ngx.var.uri
local headers = ngx.req.get_headers()
local custom_field = headers['gaia-custom-field']
if custom_field then
key = key .. ',custom=' .. custom_field
end
local args = ngx.req.get_uri_args()
key = key .. ',args=' .. json_encode(args)
if headers['gaia-enable-body'] then
ngx.req.read_body()
key = key .. ',body=' .. ngx.req.get_body_data()
end
return key
end
local function get (key)
return red:eget(key)
end
local function set (key, value)
local expire_header = ngx.req.get_headers()['gaia-expires']
local expires = expire_header and tonumber(expire_header) or nil
return red:eset(key, value, expires)
end
local function load (key)
return ngx.location.capture(BACKEND_PREFIX .. ngx.var.uri, {
args = ngx.req.get_uri_args()
})
end
local function when (res)
local ok, parsed = pcall(json_decode, res.body)
return res.status == 200 and (
-- is not json
not ok
-- json with code: 200
or ok and parsed.code == 200
)
end
local cache = cacher
:new()
:hash_key(hash_key)
:getter(get)
:setter(set)
:loader(load)
:when(when)
return cache
|
lua: cache: fixes json.decode
|
lua: cache: fixes json.decode
|
Lua
|
mit
|
kaelzhang/lua-gaia,kaelzhang/lua-gaia
|
93a53d1e18d759169747f71606790c405d3fd17e
|
lua/tuple.lua
|
lua/tuple.lua
|
local ffi = require "ffi"
local pktLib = require "packet"
local eth = require "proto.ethernet"
local ip4 = require "proto.ip4"
local ip6 = require "proto.ip6"
local module = {}
ffi.cdef [[
struct ipv4_5tuple {
uint32_t ip_dst;
uint32_t ip_src;
uint16_t port_dst;
uint16_t port_src;
uint8_t proto;
} __attribute__((__packed__));
struct ipv6_5tuple {
uint8_t ip_dst[16];
uint8_t ip_src[16];
uint16_t port_dst;
uint16_t port_src;
uint8_t proto;
} __attribute__((__packed__));
]]
module.flowKeys = {
"struct ipv4_5tuple",
"struct ipv6_5tuple",
}
local ip4Tuple = {}
function ip4Tuple:__tostring()
local template = "ipv4_5tuple{ip_dst: %s, ip_src: %s, port_dst: %i, port_src: %i, proto: %s}"
local ip4AddrDst = ffi.new("union ip4_address")
local ip4AddrSrc = ffi.new("union ip4_address")
ip4AddrDst:set(self.ip_dst)
ip4AddrSrc:set(self.ip_src)
-- L4 Protocol
local proto = ""
if self.proto == ip4.PROTO_UDP then
proto = "udp"
elseif self.proto == ip4.PROTO_TCP then
proto = "tcp"
else
proto = tonumber(self.proto)
end
return template:format(ip4AddrDst:getString(), ip4AddrSrc:getString(), tonumber(self.port_dst), tonumber(self.port_src), proto)
end
local pflangTemplate = "src host %s src port %i dst host %s dst port %i %s"
function ip4Tuple:getPflang()
local ip4AddrDst = ffi.new("union ip4_address")
local ip4AddrSrc = ffi.new("union ip4_address")
ip4AddrDst:set(self.ip_dst)
ip4AddrSrc:set(self.ip_src)
local proto = ""
if self.proto == ip4.PROTO_UDP then
proto = "udp"
elseif self.proto == ip4.PROTO_TCP then
proto = "tcp"
else
proto = tostring(tonumber(self.proto))
end
return pflangTemplate:format(ip4AddrSrc:getString(), tonumber(self.port_src), ip4AddrDst:getString(), tonumber(self.port_dst), proto)
end
ip4Tuple.__index = ip4Tuple
ffi.metatype("struct ipv4_5tuple", ip4Tuple)
function module.extractIP5Tuple(buf, keyBuf)
local ethPkt = pktLib.getEthernetPacket(buf)
if ethPkt.eth:getType() == eth.TYPE_IP then
-- actual L4 type doesn't matter
keyBuf = ffi.cast("struct ipv4_5tuple&", keyBuf)
local parsedPkt = pktLib.getUdp4Packet(buf)
keyBuf.ip_dst = parsedPkt.ip4:getDst()
keyBuf.ip_src = parsedPkt.ip4:getSrc()
local TTL = parsedPkt.ip4:getTTL()
-- port is always at the same position as UDP
keyBuf.port_dst = parsedPkt.udp:getDstPort()
keyBuf.port_src = parsedPkt.udp:getSrcPort()
local proto = parsedPkt.ip4:getProtocol()
if proto == ip4.PROTO_UDP or proto == ip4.PROTO_TCP or proto == ip4.PROTO_SCTP then
keyBuf.proto = proto
return true, 1
end
elseif ethPkt.eth:getType() == eth.TYPE_IP6 then
-- FIXME: Add IPv6
end
return false
end
return module
|
local ffi = require "ffi"
local pktLib = require "packet"
local eth = require "proto.ethernet"
local ip4 = require "proto.ip4"
local ip6 = require "proto.ip6"
local module = {}
ffi.cdef [[
struct ipv4_5tuple {
uint32_t ip_dst;
uint32_t ip_src;
uint16_t port_dst;
uint16_t port_src;
uint8_t proto;
} __attribute__((__packed__));
struct ipv6_5tuple {
uint8_t ip_dst[16];
uint8_t ip_src[16];
uint16_t port_dst;
uint16_t port_src;
uint8_t proto;
} __attribute__((__packed__));
]]
module.flowKeys = {
"struct ipv4_5tuple",
"struct ipv6_5tuple",
}
local ip4Tuple = {}
local stringTemplate = "ipv4_5tuple{ip_dst: %s, ip_src: %s, port_dst: %i, port_src: %i, proto: %s}"
function ip4Tuple:__tostring()
local ip4AddrDst = ffi.new("union ip4_address")
local ip4AddrSrc = ffi.new("union ip4_address")
ip4AddrDst:set(self.ip_dst)
ip4AddrSrc:set(self.ip_src)
-- L4 Protocol
local proto
if self.proto == ip4.PROTO_UDP then
proto = "udp"
elseif self.proto == ip4.PROTO_TCP then
proto = "tcp"
else
proto = tostring(tonumber(self.proto))
end
return stringTemplate:format(ip4AddrDst:getString(), ip4AddrSrc:getString(), tonumber(self.port_dst), tonumber(self.port_src), proto)
end
-- TODO: Rearrange expressions to generate better lua code in pflua
local pflangTemplate = "src host %s src port %i dst host %s dst port %i %s"
function ip4Tuple:getPflang()
local ip4AddrDst = ffi.new("union ip4_address")
local ip4AddrSrc = ffi.new("union ip4_address")
ip4AddrDst:set(self.ip_dst)
ip4AddrSrc:set(self.ip_src)
local proto
if self.proto == ip4.PROTO_UDP then
proto = "udp"
elseif self.proto == ip4.PROTO_TCP then
proto = "tcp"
else
proto = tostring(tonumber(self.proto))
end
return pflangTemplate:format(ip4AddrSrc:getString(), tonumber(self.port_src), ip4AddrDst:getString(), tonumber(self.port_dst), proto)
end
ip4Tuple.__index = ip4Tuple
ffi.metatype("struct ipv4_5tuple", ip4Tuple)
function module.extractIP5Tuple(buf, keyBuf)
local ethPkt = pktLib.getEthernetPacket(buf)
if ethPkt.eth:getType() == eth.TYPE_IP then
-- actual L4 type doesn't matter
keyBuf = ffi.cast("struct ipv4_5tuple&", keyBuf)
local parsedPkt = pktLib.getUdp4Packet(buf)
keyBuf.ip_dst = parsedPkt.ip4:getDst()
keyBuf.ip_src = parsedPkt.ip4:getSrc()
local TTL = parsedPkt.ip4:getTTL()
-- port is always at the same position as UDP
keyBuf.port_dst = parsedPkt.udp:getDstPort()
keyBuf.port_src = parsedPkt.udp:getSrcPort()
local proto = parsedPkt.ip4:getProtocol()
if proto == ip4.PROTO_UDP or proto == ip4.PROTO_TCP or proto == ip4.PROTO_SCTP then
keyBuf.proto = proto
return true, 1
end
elseif ethPkt.eth:getType() == eth.TYPE_IP6 then
-- FIXME: Add IPv6
end
return false
end
return module
|
Fix string representation of 5-tuples
|
Fix string representation of 5-tuples
|
Lua
|
mit
|
emmericp/FlowScope
|
2241b35873fb4b3bfd799d0079d1cadd3c6bc58c
|
modules/admin-full/luasrc/model/cbi/admin_index/luci.lua
|
modules/admin-full/luasrc/model/cbi/admin_index/luci.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2010 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.config")
m = Map("luci", translate("Web <abbr title=\"User Interface\">UI</abbr>"), translate("Here you can customize the settings and the functionality of <abbr title=\"Lua Configuration Interface\">LuCI</abbr>."))
local fs = require "nixio.fs"
-- force reload of global luci config namespace to reflect the changes
function m.commit_handler(self)
package.loaded["luci.config"] = nil
require("luci.config")
end
c = m:section(NamedSection, "main", "core", translate("General"))
l = c:option(ListValue, "lang", translate("Language"))
l:value("auto")
local i18ndir = luci.i18n.i18ndir .. "base."
for k, v in luci.util.kspairs(luci.config.languages) do
local file = i18ndir .. k:gsub("_", "-")
if k:sub(1, 1) ~= "." and fs.access(file .. ".lmo") then
l:value(k, v)
end
end
t = c:option(ListValue, "mediaurlbase", translate("Design"))
for k, v in pairs(luci.config.themes) do
if k:sub(1, 1) ~= "." then
t:value(v, k)
end
end
u = m:section(NamedSection, "uci_oncommit", "event", translate("Post-commit actions"),
translate("These commands will be executed automatically when a given <abbr title=\"Unified Configuration Interface\">UCI</abbr> configuration is committed allowing changes to be applied instantly."))
u.dynamic = true
f = m:section(NamedSection, "main", "core", translate("Files to be kept when flashing a new firmware"))
f:tab("detected", translate("Detected Files"),
translate("The following files are detected by the system and will be kept automatically during sysupgrade"))
f:tab("custom", translate("Custom Files"),
translate("This is a list of shell glob patterns for matching files and directories to include during sysupgrade"))
d = f:taboption("detected", DummyValue, "_detected", translate("Detected files"))
d.rawhtml = true
d.cfgvalue = function(s)
local list = io.popen(
"( find $(sed -ne '/^[[:space:]]*$/d; /^#/d; p' /etc/sysupgrade.conf " ..
"/lib/upgrade/keep.d/* 2>/dev/null) -type f 2>/dev/null; " ..
"opkg list-changed-conffiles ) | sort -u"
)
if list then
local files = { "<ul>" }
while true do
local ln = list:read("*l")
if not ln then
break
else
files[#files+1] = "<li>"
files[#files+1] = luci.util.pcdata(ln)
files[#files+1] = "</li>"
end
end
list:close()
files[#files+1] = "</ul>"
return table.concat(files, "")
end
return "<em>" .. translate("No files found") .. "</em>"
end
c = f:taboption("custom", TextValue, "_custom", translate("Custom files"))
c.rmempty = false
c.cols = 70
c.rows = 30
c.cfgvalue = function(self, section)
return nixio.fs.readfile("/etc/sysupgrade.conf")
end
c.write = function(self, section, value)
return nixio.fs.writefile("/etc/sysupgrade.conf", value)
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2010 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.config")
m = Map("luci", translate("Web <abbr title=\"User Interface\">UI</abbr>"), translate("Here you can customize the settings and the functionality of <abbr title=\"Lua Configuration Interface\">LuCI</abbr>."))
local fs = require "nixio.fs"
-- force reload of global luci config namespace to reflect the changes
function m.commit_handler(self)
package.loaded["luci.config"] = nil
require("luci.config")
end
c = m:section(NamedSection, "main", "core", translate("General"))
l = c:option(ListValue, "lang", translate("Language"))
l:value("auto")
local i18ndir = luci.i18n.i18ndir .. "base."
for k, v in luci.util.kspairs(luci.config.languages) do
local file = i18ndir .. k:gsub("_", "-")
if k:sub(1, 1) ~= "." and fs.access(file .. ".lmo") then
l:value(k, v)
end
end
t = c:option(ListValue, "mediaurlbase", translate("Design"))
for k, v in pairs(luci.config.themes) do
if k:sub(1, 1) ~= "." then
t:value(v, k)
end
end
u = m:section(NamedSection, "uci_oncommit", "event", translate("Post-commit actions"),
translate("These commands will be executed automatically when a given <abbr title=\"Unified Configuration Interface\">UCI</abbr> configuration is committed allowing changes to be applied instantly."))
u.dynamic = true
f = m:section(NamedSection, "main", "core", translate("Files to be kept when flashing a new firmware"))
f:tab("detected", translate("Detected Files"),
translate("The following files are detected by the system and will be kept automatically during sysupgrade"))
f:tab("custom", translate("Custom Files"),
translate("This is a list of shell glob patterns for matching files and directories to include during sysupgrade"))
d = f:taboption("detected", DummyValue, "_detected", translate("Detected files"))
d.rawhtml = true
d.cfgvalue = function(s)
local list = io.popen(
"( find $(sed -ne '/^[[:space:]]*$/d; /^#/d; p' /etc/sysupgrade.conf " ..
"/lib/upgrade/keep.d/* 2>/dev/null) -type f 2>/dev/null; " ..
"opkg list-changed-conffiles ) | sort -u"
)
if list then
local files = { "<ul>" }
while true do
local ln = list:read("*l")
if not ln then
break
else
files[#files+1] = "<li>"
files[#files+1] = luci.util.pcdata(ln)
files[#files+1] = "</li>"
end
end
list:close()
files[#files+1] = "</ul>"
return table.concat(files, "")
end
return "<em>" .. translate("No files found") .. "</em>"
end
c = f:taboption("custom", TextValue, "_custom", translate("Custom files"))
c.rmempty = false
c.cols = 70
c.rows = 30
c.cfgvalue = function(self, section)
return nixio.fs.readfile("/etc/sysupgrade.conf")
end
c.write = function(self, section, value)
value = value:gsub("\r\n?", "\n")
return nixio.fs.writefile("/etc/sysupgrade.conf", value)
end
return m
|
modules/admin-full: fixup newlines when storing sysupgrade.conf
|
modules/admin-full: fixup newlines when storing sysupgrade.conf
|
Lua
|
apache-2.0
|
8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci
|
343b755579fce253677caf6232a168de89aecf42
|
init.lua
|
init.lua
|
local framework = require('framework.lua')
local Plugin = framework.Plugin
local DataSource = framework.DataSource
local Emitter = require('core').Emitter
local stringutils = framework.string
local math = require('math')
local json = require('json')
local net = require('net') -- TODO: This dependency will be moved to the framework.
local http = require('http')
local table = require('table')
local url = require('url')
require('fun')(true)
local params = framework.boundary.param
params.name = 'Boundary OpenStack plugin'
params.version = '1.0'
local HttpDataSource = DataSource:extend()
local RandomDataSource = DataSource:extend()
local KeystoneClient = Emitter:extend()
function KeystoneClient:initialize(host, port, tenantName, username, password)
self.host = host
self.port = port
self.tenantName = tenantName
self.username = username
self.password = password
end
local get = framework.table.get
local post = framework.http.post
local request = framework.http.get
local Nothing = {
_create = function () return Nothing end,
__index = _create,
isNothing = true
}
setmetatable(Nothing, Nothing)
function Nothing.isNothing(value)
return value and value.isNothing
end
function Nothing:apply(map)
if type(map) ~= 'table' then
return
end
local mt = self or Nothing
setmetatable(map, mt)
for _, v in pairs(map) do
apply(v)
end
end
function KeystoneClient:buildData(tenantName, username, password)
local data = json.stringify({auth = { tenantName = tenantName, passwordCredentials ={username = username, password = password}} })
return data
end
function KeystoneClient:getToken(callback)
local data = self:buildData(self.tenantName, self.username, self.password)
local path = '/v2.0/tokens'
local options = {
host = self.host,
port = self.port,
path = path
}
local req = post(options, data, callback, 'json')
-- Propagate errors
req:on('error', function (err) self:emit(err) end)
end
function getEndpoint(name, endpoints)
return nth(1, totable(filter(function (e) return e.name == name end, endpoints)))
end
function getAdminUrl(endpoint)
return get('adminURL', nth(1, get('endpoints', endpoint)))
end
function getToken(data)
return get('id', (get('token',(get('access', data)))))
end
local CeilometerClient = Emitter:extend()
function CeilometerClient:initialize(host, port, tenant, username, password)
self.host = host
self.port = port
self.tenant = tenant
self.username = username
self.password = password
end
function CeilometerClient:getMetric(metric, period, callback)
local client = KeystoneClient:new(self.host, self.port, self.tenant, self.username, self.password)
client:propagate('error', self)
client:getToken(function (data)
local hasError = get('error', data)
if hasError ~= nil then
-- Propagate errors
self:emit('error', data)
else
local token = getToken(data)
local endpoints = get('serviceCatalog', get('access', data))
local adminUrl = getAdminUrl(getEndpoint('ceilometer', endpoints))
local headers = {}
headers['X-Auth-Token'] = token
local path = '/v2/meters/' .. metric .. '/statistics?period=' .. period
local urlParts = url.parse(adminUrl)
local options = {
host = urlParts.hostname,
port = urlParts.port,
path = path,
headers = headers
}
local req = request(options, nil, function (res)
if callback then
callback(res)
end
end, 'json', false)
req:propagate('error', self) -- Propagate errors
end
end)
end
local mapping = {}
mapping['cpu_util'] = {avg = 'OS_CPUUTIL_AVG', sum = 'OS_CPUUTIL_SUM', min = 'OS_CPUUTIL_MIN', max = 'OS_CPUUTIL_MAX'}
mapping['cpu'] = {avg = 'OS_CPU_AVG', sum = 'OS_CPU_SUM'}
mapping['instance'] = {sum = 'OS_INSTANCE_SUM', max = 'OS_INSTANCE_MAX'}
mapping['memory'] = {sum = 'OS_MEMORY_SUM', avg = 'OS_MEMORY_AVG'}
mapping['memory.usage'] = {sum = 'OS_MEMORY_USAGE_SUM', avg = 'OS_MEMORY_USAGE_AVG'}
mapping['volume'] = {sum = 'OS_VOLUME_SUM', avg = 'OS_VOLUME_AVG'}
mapping['image'] = {sum = 'OS_IMAGE_SUM', avg = 'OS_IMAGE_AVG'}
mapping['image.size'] = {avg = 'OS_IMAGE_SIZE_AVG', sum = 'OS_IMAGE_SIZE_SUM'}
mapping['disk.read.requests.rate'] = {sum = 'OS_DISK_READ_RATE_SUM', avg = 'OS_DISK_READ_RATE_AVG'}
mapping['disk.write.requests.rate'] = {sum = 'OS_DISK_WRITE_RATE_SUM', avg = 'OS_DISK_WRITE_RATE_AVG'}
mapping['network.incoming.bytes'] = {sum = 'OS_NETWORK_IN_BYTES_SUM', avg = 'OS_NETWORK_IN_BYTES_AVG'}
mapping['network.outgoing.bytes'] = {sum = 'OS_NETWORK_OUT_BYTES_SUM', avg = 'OS_NETWORK_OUT_BYTES_AVG'}
local OpenStackDataSource = DataSource:extend()
function OpenStackDataSource:initialize(host, port, tenant, username, password)
self.host = host
self.port = port
self.tenant = tenant
self.username = username
self.password = password
end
function OpenStackDataSource:fetch(context, callback)
local ceilometer = CeilometerClient:new(self.host, self.port, self.tenant, self.username, self.password)
ceilometer:on('error', function (err) p(err.message) end)
for metric,v in pairs(mapping) do
ceilometer:getMetric(metric, 300,
function (result)
if callback then
callback(metric, result)
end
end
)
end
end
local dataSource = OpenStackDataSource:new(params.service_host, params.service_port, params.service_tenant, params.service_username, params.service_password)
local plugin = Plugin:new(params, dataSource)
function plugin:onParseValues(metric, data)
local result = {}
if data == nil then
return {}
end
local m = mapping[metric]
local data = nth(1, data)
for col, boundaryName in pairs(m) do
result[boundaryName] = tonumber(get(col, data))
end
return result
end
plugin:poll()
|
local framework = require('framework.lua')
local Plugin = framework.Plugin
local DataSource = framework.DataSource
local Emitter = require('core').Emitter
local stringutils = framework.string
local math = require('math')
local json = require('json')
local net = require('net') -- TODO: This dependency will be moved to the framework.
local http = require('http')
local table = require('table')
local url = require('url')
require('fun')(true)
local params = framework.boundary.param
--params.name = 'Boundary OpenStack plugin'
--params.version = '1.0'
local HttpDataSource = DataSource:extend()
local RandomDataSource = DataSource:extend()
local KeystoneClient = Emitter:extend()
function KeystoneClient:initialize(host, port, tenantName, username, password)
self.host = host
self.port = port
self.tenantName = tenantName
self.username = username
self.password = password
end
local get = framework.table.get
local post = framework.http.post
local request = framework.http.get
local Nothing = {
_create = function () return Nothing end,
__index = _create,
isNothing = true
}
setmetatable(Nothing, Nothing)
function Nothing.isNothing(value)
return value and value.isNothing
end
function Nothing:apply(map)
if type(map) ~= 'table' then
return
end
local mt = self or Nothing
setmetatable(map, mt)
for _, v in pairs(map) do
apply(v)
end
end
function KeystoneClient:buildData(tenantName, username, password)
local data = json.stringify({auth = { tenantName = tenantName, passwordCredentials ={username = username, password = password}} })
return data
end
function KeystoneClient:getToken(callback)
local data = self:buildData(self.tenantName, self.username, self.password)
local path = '/v2.0/tokens'
local options = {
host = self.host,
port = self.port,
path = path
}
local req = post(options, data, callback, 'json')
-- Propagate errors
req:on('error', function (err) self:emit(err) end)
end
function getEndpoint(name, endpoints)
return nth(1, totable(filter(function (e) return e.name == name end, endpoints)))
end
function getAdminUrl(endpoint)
return get('adminURL', nth(1, get('endpoints', endpoint)))
end
function getToken(data)
return get('id', (get('token',(get('access', data)))))
end
local CeilometerClient = Emitter:extend()
function CeilometerClient:initialize(host, port, tenant, username, password)
self.host = host
self.port = port
self.tenant = tenant
self.username = username
self.password = password
end
function CeilometerClient:getMetric(metric, period, callback)
local client = KeystoneClient:new(self.host, self.port, self.tenant, self.username, self.password)
client:propagate('error', self)
client:getToken(function (data)
local hasError = get('error', data)
if hasError ~= nil then
-- Propagate errors
self:emit('error', data)
else
local token = getToken(data)
local endpoints = get('serviceCatalog', get('access', data))
local adminUrl = getAdminUrl(getEndpoint('ceilometer', endpoints))
local headers = {}
headers['X-Auth-Token'] = token
local path = '/v2/meters/' .. metric .. '/statistics?period=' .. period
local urlParts = url.parse(adminUrl)
local options = {
host = urlParts.hostname,
port = urlParts.port,
path = path,
headers = headers
}
local req = request(options, nil, function (res)
if callback then
callback(res)
end
end, 'json', false)
req:propagate('error', self) -- Propagate errors
end
end)
end
local mapping = {}
mapping['cpu_util'] = {avg = 'OS_CPUUTIL_AVG', sum = 'OS_CPUUTIL_SUM', min = 'OS_CPUUTIL_MIN', max = 'OS_CPUUTIL_MAX'}
mapping['cpu'] = {avg = 'OS_CPU_AVG', sum = 'OS_CPU_SUM'}
mapping['instance'] = {sum = 'OS_INSTANCE_SUM', max = 'OS_INSTANCE_MAX'}
mapping['memory'] = {sum = 'OS_MEMORY_SUM', avg = 'OS_MEMORY_AVG'}
mapping['memory.usage'] = {sum = 'OS_MEMORY_USAGE_SUM', avg = 'OS_MEMORY_USAGE_AVG'}
mapping['volume'] = {sum = 'OS_VOLUME_SUM', avg = 'OS_VOLUME_AVG'}
mapping['image'] = {sum = 'OS_IMAGE_SUM', avg = 'OS_IMAGE_AVG'}
mapping['image.size'] = {avg = 'OS_IMAGE_SIZE_AVG', sum = 'OS_IMAGE_SIZE_SUM'}
mapping['disk.read.requests.rate'] = {sum = 'OS_DISK_READ_RATE_SUM', avg = 'OS_DISK_READ_RATE_AVG'}
mapping['disk.write.requests.rate'] = {sum = 'OS_DISK_WRITE_RATE_SUM', avg = 'OS_DISK_WRITE_RATE_AVG'}
mapping['network.incoming.bytes'] = {sum = 'OS_NETWORK_IN_BYTES_SUM', avg = 'OS_NETWORK_IN_BYTES_AVG'}
mapping['network.outgoing.bytes'] = {sum = 'OS_NETWORK_OUT_BYTES_SUM', avg = 'OS_NETWORK_OUT_BYTES_AVG'}
local OpenStackDataSource = DataSource:extend()
function OpenStackDataSource:initialize(host, port, tenant, username, password)
self.host = host
self.port = port
self.tenant = tenant
self.username = username
self.password = password
end
function OpenStackDataSource:fetch(context, callback)
local ceilometer = CeilometerClient:new(self.host, self.port, self.tenant, self.username, self.password)
ceilometer:on('error', function (err) p(err.message) end)
for metric,v in pairs(mapping) do
ceilometer:getMetric(metric, 300,
function (result)
if callback then
callback(metric, result)
end
end
)
end
end
local dataSource = OpenStackDataSource:new(params.service_host, params.service_port, params.service_tenant, params.service_username, params.service_password)
local plugin = Plugin:new(params, dataSource)
function plugin:onParseValues(metric, data)
local result = {}
if data == nil then
return {}
end
local m = mapping[metric]
local data = nth(1, data)
for col, boundaryName in pairs(m) do
result[boundaryName] = tonumber(get(col, data))
end
return result
end
plugin:poll()
|
After fixing issues, some of meterics are getting data
|
After fixing issues, some of meterics are getting data
|
Lua
|
apache-2.0
|
boundary/boundary-plugin-openstack
|
268caf3a7ec821c659254dd4577d7608b5edb09d
|
modules/textadept/bookmarks.lua
|
modules/textadept/bookmarks.lua
|
-- Copyright 2007-2009 Mitchell mitchell<att>caladbolg.net. See LICENSE.
local textadept = _G.textadept
local locale = _G.locale
---
-- Bookmarks for the textadept module.
-- There are several option variables used:
-- MARK_BOOKMARK: The integer mark used to identify a bookmarked line.
-- MARK_BOOKMARK_COLOR: The Scintilla color used for a bookmarked line.
module('_m.textadept.bookmarks', package.seeall)
-- options
local MARK_BOOKMARK = 1
local MARK_BOOKMARK_COLOR = 0xC08040
-- end options
---
-- Adds a bookmark to the current line.
function add()
local buffer = buffer
buffer:marker_set_back(MARK_BOOKMARK, MARK_BOOKMARK_COLOR)
local line = buffer:line_from_position(buffer.current_pos)
buffer:marker_add(line, MARK_BOOKMARK)
end
---
-- Clears the bookmark at the current line.
function remove()
local buffer = buffer
local line = buffer:line_from_position(buffer.current_pos)
buffer:marker_delete(line, MARK_BOOKMARK)
end
---
-- Toggles a bookmark on the current line.
function toggle()
local buffer = buffer
local line = buffer:line_from_position(buffer.current_pos)
local markers = buffer:marker_get(line) -- bit mask
if markers % 2 == 0 then add() else remove() end -- first bit is set?
end
---
-- Clears all bookmarks in the current buffer.
function clear()
local buffer = buffer
buffer:marker_delete_all(MARK_BOOKMARK)
end
---
-- Goes to the next bookmark in the current buffer.
function goto_next()
local buffer = buffer
local current_line = buffer:line_from_position(buffer.current_pos)
local line = buffer:marker_next(current_line + 1, 2^MARK_BOOKMARK)
if line >= 0 then _m.textadept.editing.goto_line(line + 1) end
end
---
-- Goes to the previous bookmark in the current buffer.
function goto_prev()
local buffer = buffer
local current_line = buffer:line_from_position(buffer.current_pos)
local line = buffer:marker_previous(current_line - 1, 2^MARK_BOOKMARK)
if line >= 0 then _m.textadept.editing.goto_line(line + 1) end
end
|
-- Copyright 2007-2009 Mitchell mitchell<att>caladbolg.net. See LICENSE.
local textadept = _G.textadept
local locale = _G.locale
---
-- Bookmarks for the textadept module.
-- There are several option variables used:
-- MARK_BOOKMARK: The integer mark used to identify a bookmarked line.
-- MARK_BOOKMARK_COLOR: The Scintilla color used for a bookmarked line.
module('_m.textadept.bookmarks', package.seeall)
-- options
local MARK_BOOKMARK = 1
local MARK_BOOKMARK_COLOR = 0xC08040
-- end options
---
-- Adds a bookmark to the current line.
function add()
local buffer = buffer
buffer:marker_set_back(MARK_BOOKMARK, MARK_BOOKMARK_COLOR)
local line = buffer:line_from_position(buffer.current_pos)
buffer:marker_add(line, MARK_BOOKMARK)
end
---
-- Clears the bookmark at the current line.
function remove()
local buffer = buffer
local line = buffer:line_from_position(buffer.current_pos)
buffer:marker_delete(line, MARK_BOOKMARK)
end
---
-- Toggles a bookmark on the current line.
function toggle()
local buffer = buffer
local line = buffer:line_from_position(buffer.current_pos)
local markers = buffer:marker_get(line) -- bit mask
local bit = 2^MARK_BOOKMARK
if markers % (bit + bit) < bit then add() else remove() end
end
---
-- Clears all bookmarks in the current buffer.
function clear()
local buffer = buffer
buffer:marker_delete_all(MARK_BOOKMARK)
end
---
-- Goes to the next bookmark in the current buffer.
function goto_next()
local buffer = buffer
local current_line = buffer:line_from_position(buffer.current_pos)
local line = buffer:marker_next(current_line + 1, 2^MARK_BOOKMARK)
if line == -1 then line = buffer:marker_next(0, 2^MARK_BOOKMARK) end
if line >= 0 then _m.textadept.editing.goto_line(line + 1) end
end
---
-- Goes to the previous bookmark in the current buffer.
function goto_prev()
local buffer = buffer
local current_line = buffer:line_from_position(buffer.current_pos)
local line = buffer:marker_previous(current_line - 1, 2^MARK_BOOKMARK)
if line == -1 then
line = buffer:marker_previous(buffer.line_count, 2^MARK_BOOKMARK)
end
if line >= 0 then _m.textadept.editing.goto_line(line + 1) end
end
|
Fixed toggle bookmark bug, wrap searches; modules/textadept/bookmarks.lua
|
Fixed toggle bookmark bug, wrap searches; modules/textadept/bookmarks.lua
|
Lua
|
mit
|
rgieseke/textadept,rgieseke/textadept
|
f2154231ba321fc6df7695f4e66335470792ef9c
|
src/lgi.lua
|
src/lgi.lua
|
--[[--
Base lgi bootstrapper.
Author: Pavel Holejsovsky
Licence: MIT
--]]--
local assert, setmetatable, getmetatable, type, pairs, pcall, string, table =
assert, setmetatable, getmetatable, type, pairs, pcall, string, table
local core = require 'lgi._core'
local bit = require 'bit'
module 'lgi'
local function getface(namespace, object, prefix, funs)
local t = {}
for _, fun in pairs(funs) do
local info = assert(core.find(namespace, object, prefix .. fun))
t[fun] = core.get(info)
core.unref(info)
end
return t
end
-- Contains gi utilities, used only locally during bootstrap.
local gi = {
IRepository = getface(
'GIRepository', 'IRepository', '', {
'require', 'find_by_name', 'get_n_infos', 'get_info',
}),
IBaseInfo = getface(
'GIRepository', nil, 'base_info_', {
'ref', 'unref', 'get_type', 'is_deprecated', 'get_name',
}),
IEnumInfo = getface(
'GIRepository', nil, 'enum_info_', {
'get_n_values', 'get_value',
}),
IValueInfo = getface(
'GIRepository', nil, 'value_info_', {
'get_value',
}),
IStructInfo = getface(
'GIRepository', nil, 'struct_info_', {
'get_n_methods', 'get_method', 'is_gtype_struct',
}),
IFunctionInfo = getface(
'GIRepository', nil, 'function_info_', {
'get_flags',
}),
IInfoType = {
FUNCTION = 1,
STRUCT = 3,
ENUM = 5,
FLAGS = 6,
OBJECT = 7,
INTERFACE = 8,
CONSTANT = 9,
},
IFunctionInfoFlags = {
IS_METHOD = 1,
IS_CONSTRUCTOR = 2,
IS_GETTER = 4,
IS_SETTER = 8,
WRAPS_VFUNC = 16,
THROWS = 32,
},
}
-- Metatable for bitfield tables, resolving arbitraru number to the
-- table containing symbolic names of contained bits.
local bitfield_mt = {}
function bitfield_mt.__index(bitfield, value)
local t = {}
for name, flag in pairs(bitfield) do
if type(flag) == 'number' and bit.band(flag, value) == flag then
table.insert(t, name)
end
end
return t
end
-- Similar metatable for enum tables.
local enum_mt = {}
function enum_mt.__index(enum, value)
for name, val in pairs(enum) do
if val == value then return name end
end
end
-- Package uses lazy namespace access, so __index method loads field
-- on-demand (but stores them back, so it is actually caching).
local package_mt = {}
function package_mt.__index(package, name)
-- Lookup baseinfo of requested symbol in the repo.
local info = gi.IRepository.find_by_name(nil, package._namespace, name)
if not info then return nil end
-- Decide according to symbol type what to do.
local value
if not gi.IBaseInfo.is_deprecated(info) then
local type = gi.IBaseInfo.get_type(info)
if type == gi.IInfoType.FUNCTION or type == gi.IInfoType.CONSTANT then
value = core.get(info)
elseif type == gi.IInfoType.STRUCT then
if not gi.IStructInfo.is_gtype_struct(info) then
value = {}
-- Create table with all constructors for the structure.
for i = 0, gi.IStructInfo.get_n_methods(info) - 1 do
local fi = gi.IStructInfo.get_method(info, i)
if bit.band(gi.IFunctionInfo.get_flags(fi),
gi.IFunctionInfoFlags.IS_CONSTRUCTOR) ~= 0 then
value[gi.IBaseInfo.get_name(fi)] = core.get(fi)
end
gi.IBaseInfo.unref(fi)
end
end
elseif type == gi.IInfoType.ENUM or type == gi.IInfoType.FLAGS then
value = {}
for i = 0, gi.IEnumInfo.get_n_values(info) - 1 do
local val = gi.IEnumInfo.get_value(info, i)
local n = string.upper(gi.IBaseInfo.get_name(val))
local v = gi.IValueInfo.get_value(val)
value[n] = v
-- Install metatable providing reverse lookup (i.e name(s)
-- by value).
if type == gi.IInfoType.ENUM then
setmetatable(value, enum_mt)
else
setmetatable(value, bitfield_mt)
end
gi.IBaseInfo.unref(val)
end
end
end
gi.IBaseInfo.unref(info)
-- Cache the result.
package[name] = value
return value
end
-- Forces loading the whole namespace (which is otherwise loaded
-- lazily). Useful when one wants to inspect the contents of the
-- whole namespace (i.e. iterate through it).
local function loadnamespace(namespace)
-- Iterate through all items in the namespace.
for i = 0, gi.IRepository.get_n_infos(nil, namespace._namespace) -1 do
local info = gi.IRepository.get_info(nil, namespace._namespace, i)
pcall(getmetatable(namespace).__index, namespace,
gi.IBaseInfo.get_name(info))
gi.IBaseInfo.unref(info)
end
end
function core.require(namespace, version)
local ns = { _namespace = namespace }
-- Load the repository.
ns._typelib = assert(gi.IRepository.require(nil, namespace, version))
-- Install 'force' closure, which forces loading this namespace.
ns._force = function()
loadnamespace(ns)
return ns
end
-- Set proper lazy metatable.
return setmetatable(ns, package_mt)
end
|
--[[--
Base lgi bootstrapper.
Author: Pavel Holejsovsky
Licence: MIT
--]]--
local assert, setmetatable, getmetatable, type, pairs, pcall, string, table =
assert, setmetatable, getmetatable, type, pairs, pcall, string, table
local core = require 'lgi._core'
local bit = require 'bit'
module 'lgi'
local function getface(namespace, object, prefix, funs)
local t = {}
for _, fun in pairs(funs) do
local info = assert(core.find(namespace, object, prefix .. fun))
t[fun] = core.get(info)
core.unref(info)
end
return t
end
-- Contains gi utilities, used only locally during bootstrap.
local gi = {
IRepository = getface(
'GIRepository', 'IRepository', '', {
'require', 'find_by_name', 'get_n_infos', 'get_info',
}),
IBaseInfo = getface(
'GIRepository', nil, 'base_info_', {
'ref', 'unref', 'get_type', 'is_deprecated', 'get_name',
}),
IEnumInfo = getface(
'GIRepository', nil, 'enum_info_', {
'get_n_values', 'get_value',
}),
IValueInfo = getface(
'GIRepository', nil, 'value_info_', {
'get_value',
}),
IStructInfo = getface(
'GIRepository', nil, 'struct_info_', {
'get_n_methods', 'get_method', 'is_gtype_struct',
}),
IInfoType = {
FUNCTION = 1,
STRUCT = 3,
ENUM = 5,
FLAGS = 6,
OBJECT = 7,
INTERFACE = 8,
CONSTANT = 9,
},
}
-- Metatable for bitfield tables, resolving arbitraru number to the
-- table containing symbolic names of contained bits.
local bitfield_mt = {}
function bitfield_mt.__index(bitfield, value)
local t = {}
for name, flag in pairs(bitfield) do
if type(flag) == 'number' and bit.band(flag, value) == flag then
table.insert(t, name)
end
end
return t
end
-- Similar metatable for enum tables.
local enum_mt = {}
function enum_mt.__index(enum, value)
for name, val in pairs(enum) do
if val == value then return name end
end
end
-- Package uses lazy namespace access, so __index method loads field
-- on-demand (but stores them back, so it is actually caching).
local package_mt = {}
function package_mt.__index(package, name)
-- Lookup baseinfo of requested symbol in the repo.
local info = gi.IRepository.find_by_name(nil, package._namespace, name)
if not info then return nil end
-- Decide according to symbol type what to do.
local value
if not gi.IBaseInfo.is_deprecated(info) then
local type = gi.IBaseInfo.get_type(info)
if type == gi.IInfoType.FUNCTION or type == gi.IInfoType.CONSTANT then
value = core.get(info)
elseif type == gi.IInfoType.STRUCT then
if not gi.IStructInfo.is_gtype_struct(info) then
value = {}
-- Create table with all methods of the structure.
for i = 0, gi.IStructInfo.get_n_methods(info) - 1 do
local fi = gi.IStructInfo.get_method(info, i)
value[gi.IBaseInfo.get_name(fi)] = core.get(fi)
gi.IBaseInfo.unref(fi)
end
end
elseif type == gi.IInfoType.ENUM or type == gi.IInfoType.FLAGS then
value = {}
for i = 0, gi.IEnumInfo.get_n_values(info) - 1 do
local val = gi.IEnumInfo.get_value(info, i)
local n = string.upper(gi.IBaseInfo.get_name(val))
local v = gi.IValueInfo.get_value(val)
value[n] = v
-- Install metatable providing reverse lookup (i.e name(s)
-- by value).
if type == gi.IInfoType.ENUM then
setmetatable(value, enum_mt)
else
setmetatable(value, bitfield_mt)
end
gi.IBaseInfo.unref(val)
end
end
end
gi.IBaseInfo.unref(info)
-- Cache the result.
package[name] = value
return value
end
-- Forces loading the whole namespace (which is otherwise loaded
-- lazily). Useful when one wants to inspect the contents of the
-- whole namespace (i.e. iterate through it).
local function loadnamespace(namespace)
-- Iterate through all items in the namespace.
for i = 0, gi.IRepository.get_n_infos(nil, namespace._namespace) -1 do
local info = gi.IRepository.get_info(nil, namespace._namespace, i)
pcall(getmetatable(namespace).__index, namespace,
gi.IBaseInfo.get_name(info))
gi.IBaseInfo.unref(info)
end
end
function core.require(namespace, version)
local ns = { _namespace = namespace }
-- Load the repository.
ns._typelib = assert(gi.IRepository.require(nil, namespace, version))
-- Install 'force' closure, which forces loading this namespace.
ns._force = function()
loadnamespace(ns)
return ns
end
-- Set proper lazy metatable.
return setmetatable(ns, package_mt)
end
|
Fix thinkos in lua-side bootstrap struct parsing.
|
Fix thinkos in lua-side bootstrap struct parsing.
|
Lua
|
mit
|
pavouk/lgi,psychon/lgi,zevv/lgi
|
d2bc29cefd0263671fc1a01d3852d2ff491be539
|
resources/stdlibrary/stdfuncs.lua
|
resources/stdlibrary/stdfuncs.lua
|
function assert(v, message) end
function collectgarbage(opt, arg) end
function dofile(filename) end
function error(message, level) end
function getfenv(f) end
function getmetatable(object) end
function ipairs (t) end
function load(func, optChunkname) end
function loadfile (filename) end
function loadstring (string, chunkname) end
function next(table, index) end
function pairs(t) end
function pcall (f, arg1, ...) end
function print (...) end
function rawequal (v1, v2) end
function rawget (table, index) end
function rawset (table, index, value) end
function select (index, ...) end
function setfenv (f, table) end
function setmetatable (table, metatable) end
function tonumber (e, base) end
function tostring (e) end
function type (v) end
function unpack (list , i , j) end
function xpcall (f, err) end
function module (name, ...) end
function require (modname) end
_VERSION = "string"
_G = {}
coroutine = {}
debug = {}
io = {}
math = {}
os = {}
package = {}
string = {}
table = {}
--file = {}
function coroutine.create() end
function coroutine.resume() end
function coroutine.running() end
function coroutine.status() end
function coroutine.wrap() end
function coroutine.yield() end
function debug.debug() end
function debug.getfenv() end
function debug.gethook() end
function debug.getinfo() end
function debug.getlocal() end
function debug.getmetatable() end
function debug.getregistry() end
function debug.getupvalue() end
function debug.setfenv() end
function debug.sethook() end
function debug.setlocal() end
function debug.setmetatable() end
function debug.setupvalue() end
function debug.traceback() end
function io.close() end
function io.flush() end
function io.input() end
function io.lines() end
function io.open() end
function io.output() end
function io.popen() end
function io.read() end
function io.tmpfile() end
function io.type() end
function io.write() end
function math.abs() end
function math.acos() end
function math.asin() end
function math.atan() end
function math.atan() end
function math.ceil() end
function math.cos() end
function math.cosh() end
function math.deg() end
function math.exp() end
function math.floor() end
function math.fmod() end
function math.frexp() end
function math.huge() end
function math.ldexp() end
function math.log() end
function math.log() end
function math.max() end
function math.min() end
function math.modf() end
math.pi = 3.1415
function math.pow() end
function math.rad() end
function math.random() end
function math.randomseed() end
function math.sin() end
function math.sinh() end
function math.sqrt() end
function math.tan() end
function math.tanh() end
function os.clock() end
function os.date() end
function os.difftime() end
function os.execute() end
function os.exit() end
function os.getenv() end
function os.remove() end
function os.rename() end
function os.setlocale() end
function os.time() end
function os.tmpname() end
-- Resolving these requires the "Enable Additional Completions" option in Settings|Lua
function file:close() end
function file:flush() end
function file:lines() end
function file:read() end
function file:seek() end
function file:setvbuf() end
function file:write() end
function package.cpath() end
function package.loaded() end
function package.loaders() end
function package.loadlib() end
function package.path() end
function package.preload() end
function package.seeall() end
function string.byte() end
function string.char() end
function string.dump() end
function string.find() end
function string.format() end
function string.gmatch() end
function string.gsub() end
function string.len() end
function string.lower() end
function string.match() end
function string.rep() end
function string.reverse() end
function string.sub() end
function string.upper() end
function table.concat() end
function table.insert() end
function table.maxn() end
function table.remove() end
function table.sort() end
|
function assert(v, message) end
function collectgarbage(opt, arg) end
function dofile(filename) end
function error(message, level) end
function getfenv(f) end
function getmetatable(object) end
function ipairs (t) end
function load(func, optChunkname) end
function loadfile (filename) end
function loadstring (string, chunkname) end
function next(table, index) end
function pairs(t) end
function pcall (f, arg1, ...) end
function print (...) end
function rawequal (v1, v2) end
function rawget (table, index) end
function rawset (table, index, value) end
function select (index, ...) end
function setfenv (f, table) end
function setmetatable (table, metatable) end
function tonumber (e, base) end
function tostring (e) end
function type (v) end
function unpack (list , i , j) end
function xpcall (f, err) end
function module (name, ...) end
function require (modname) end
_VERSION = "string"
_G = {}
coroutine = {}
debug = {}
io = {}
math = {}
os = {}
package = {}
string = {}
table = {}
--file = {}
function coroutine.create() end
function coroutine.resume() end
function coroutine.running() end
function coroutine.status() end
function coroutine.wrap() end
function coroutine.yield() end
function debug.debug() end
function debug.getfenv() end
function debug.gethook() end
function debug.getinfo() end
function debug.getlocal() end
function debug.getmetatable() end
function debug.getregistry() end
function debug.getupvalue() end
function debug.setfenv() end
function debug.sethook() end
function debug.setlocal() end
function debug.setmetatable() end
function debug.setupvalue() end
function debug.traceback() end
function io.close() end
function io.flush() end
function io.input() end
function io.lines() end
function io.open() end
function io.output() end
function io.popen() end
function io.read() end
function io.tmpfile() end
function io.type() end
function io.write() end
io.stdin = true
io.stdout= true
function math.abs() end
function math.acos() end
function math.asin() end
function math.atan() end
function math.atan() end
function math.ceil() end
function math.cos() end
function math.cosh() end
function math.deg() end
function math.exp() end
function math.floor() end
function math.fmod() end
function math.frexp() end
function math.huge() end
function math.ldexp() end
function math.log() end
function math.log() end
function math.max() end
function math.min() end
function math.modf() end
math.pi = 3.1415
function math.pow() end
function math.rad() end
function math.random() end
function math.randomseed() end
function math.sin() end
function math.sinh() end
function math.sqrt() end
function math.tan() end
function math.tanh() end
function os.clock() end
function os.date() end
function os.difftime() end
function os.execute() end
function os.exit() end
function os.getenv() end
function os.remove() end
function os.rename() end
function os.setlocale() end
function os.time() end
function os.tmpname() end
-- Resolving these requires the "Enable Additional Completions" option in Settings|Lua
function file:close() end
function file:flush() end
function file:lines() end
function file:read() end
function file:seek() end
function file:setvbuf() end
function file:write() end
function package.cpath() end
function package.loaded() end
function package.loaders() end
function package.loadlib() end
function package.path() end
function package.preload() end
function package.seeall() end
function string.byte() end
function string.char() end
function string.dump() end
function string.find() end
function string.format() end
function string.gmatch() end
function string.gsub() end
function string.len() end
function string.lower() end
function string.match() end
function string.rep() end
function string.reverse() end
function string.sub() end
function string.upper() end
function table.concat() end
function table.insert() end
function table.maxn() end
function table.remove() end
function table.sort() end
|
add io.stdin/io.stdout to stdfuncs (fix #64)
|
add io.stdin/io.stdout to stdfuncs (fix #64)
|
Lua
|
apache-2.0
|
sylvanaar/IDLua,consulo/consulo-lua,sylvanaar/IDLua,sylvanaar/IDLua,consulo/consulo-lua,consulo/consulo-lua
|
48516b1ea7b8184e7e28d6a7f485cd3db22280aa
|
testserver/item/id_505_treasuremap.lua
|
testserver/item/id_505_treasuremap.lua
|
require("base.common")
require("base.treasure")
-- UPDATE common SET com_script='item.id_505_treasuremap' WHERE com_itemid IN (505);
module("item.id_505_treasuremap", package.seeall)
function LookAtItem(User, Item)
local dir = base.treasure.getDirection( User, Item );
local distance = base.treasure.getDistance (User, Item );
local TreasureName = base.treasure.GetTreasureName( math.floor(Item.quality/100), User:getPlayerLanguage(), not dir );
if not dir then
world:itemInform( User, Item, base.common.GetNLS( User,
"Eine Karte mit einer Markierung auf einer Position irgendwo in deiner unmittelbaren Nhe. Du vermutest, dass es sich um "..TreasureName.." handelt.",
"A map that shows a position somewhere really close to your current position. You think it could be "..TreasureName.."." ) );
elseif string.find(dir,"wrong")~=nil then
world:itemInform( User, Item, base.common.GetNLS( User,
"Du scheinst dich nicht im richtigen Gebiet aufzuhalten.",
"You don't seem to be in the correct area."));
else
world:itemInform( User, Item, base.common.GetNLS( User,
"Eine Karte mit einer Markierung, die sich wahrscheinlich von dir aus gesehen "..distance.." im "..dir.." befindet. Du vermutest, dass es sich um "..TreasureName.." handelt.",
"A map that shows a mark that is probably located somewhere "..distance.." in the "..dir.." of your current position. You believe the map leads to "..TreasureName.."." ) );
end;
end;
function UseItem( User, SourceItem, TargetItem, Counter, Param, ltstate ) -- DONT EDIT THIS LINE!
end
|
require("base.common")
require("base.treasure")
-- UPDATE common SET com_script='item.id_505_treasuremap' WHERE com_itemid IN (505);
module("item.id_505_treasuremap", package.seeall)
function LookAtItem(User, Item)
local dir = base.treasure.getDirection( User, Item );
local distance = base.treasure.getDistance (User, Item );
local TreasureName = base.treasure.GetTreasureName( math.floor(Item.quality/100), User:getPlayerLanguage(), not dir );
if not dir then
base.lookat.SetSpecialDescription(Item, "Eine Karte mit einer Markierung auf einer Position irgendwo in deiner unmittelbaren Nhe. Du vermutest, dass es sich um "..TreasureName.." handelt.",
"A map that shows a position somewhere really close to your current position. You think it could be "..TreasureName.."." ) );
world:itemInform( User, Item, base.lookat.GenerateLookAt(User, Item, base.lookat.NONE) );
elseif string.find(dir,"wrong")~=nil then
base.lookat.SetSpecialDescription(Item,
"Du scheinst dich nicht im richtigen Gebiet aufzuhalten.",
"You don't seem to be in the correct area."));
world:itemInform( User, Item, base.lookat.GenerateLookAt(User, Item, base.lookat.NONE) );
else
base.lookat.SetSpecialDescription(Item,
"Eine Karte mit einer Markierung, die sich wahrscheinlich von dir aus gesehen "..distance.." im "..dir.." befindet. Du vermutest, dass es sich um "..TreasureName.." handelt.",
"A map that shows a mark that is probably located somewhere "..distance.." in the "..dir.." of your current position. You believe the map leads to "..TreasureName.."." ) );
world:itemInform( User, Item, base.lookat.GenerateLookAt(User, Item, base.lookat.NONE) );
end;
end;
function UseItem( User, SourceItem, TargetItem, Counter, Param, ltstate ) -- DONT EDIT THIS LINE!
end
|
fixed lookat
|
fixed lookat
|
Lua
|
agpl-3.0
|
LaFamiglia/Illarion-Content,vilarion/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content,Illarion-eV/Illarion-Content
|
0af0a1598ec6bbd9fff2bf00768977c5cacd9b26
|
lib/resty/iputils.lua
|
lib/resty/iputils.lua
|
local ipairs, tonumber, tostring, type = ipairs, tonumber, tostring, type
local bit = require("bit")
local tobit = bit.tobit
local lshift = bit.lshift
local band = bit.band
local bor = bit.bor
local xor = bit.bxor
local byte = string.byte
local str_find = string.find
local str_sub = string.sub
local lrucache = nil
local _M = {
_VERSION = '0.2.1',
}
local mt = { __index = _M }
-- Precompute binary subnet masks...
local bin_masks = {}
for i=1,32 do
bin_masks[tostring(i)] = lshift(tobit((2^i)-1), 32-i)
end
-- ... and their inverted counterparts
local bin_inverted_masks = {}
for i=1,32 do
local i = tostring(i)
bin_inverted_masks[i] = xor(bin_masks[i], bin_masks["32"])
end
local log_err
if ngx then
log_err = function(...)
ngx.log(ngx.ERR, ...)
end
else
log_err = function(...)
print(...)
end
end
local function enable_lrucache(size)
local size = size or 4000 -- Cache the last 4000 IPs (~1MB memory) by default
local lrucache_obj, err = require("resty.lrucache").new(size)
if not lrucache_obj then
return nil, "failed to create the cache: " .. (err or "unknown")
end
lrucache = lrucache_obj
return true
end
_M.enable_lrucache = enable_lrucache
local function split_octets(input)
local pos = 0
local prev = 0
local octs = {}
for i=1, 4 do
pos = str_find(input, ".", prev, true)
if pos then
if i == 4 then
-- Should not have a match after 4 octets
return nil, "Invalid IP"
end
octs[i] = str_sub(input, prev, pos-1)
elseif i == 4 then
-- Last octet, get everything to the end
octs[i] = str_sub(input, prev, -1)
break
else
return nil, "Invalid IP"
end
prev = pos +1
end
return octs
end
local function ip2bin(ip)
if lrucache then
local get = lrucache:get(ip)
if get then
return get[1], get[2]
end
end
if type(ip) ~= "string" then
return nil, "IP must be a string"
end
local octets = split_octets(ip)
if not octets or #octets ~= 4 then
return nil, "Invalid IP"
end
-- Return the binary representation of an IP and a table of binary octets
local bin_octets = {}
local bin_ip = 0
for i,octet in ipairs(octets) do
local bin_octet = tonumber(octet)
if not bin_octet or bin_octet > 255 then
return nil, "Invalid octet: "..tostring(octet)
end
bin_octet = tobit(bin_octet)
bin_octets[i] = bin_octet
bin_ip = bor(lshift(bin_octet, 8*(4-i) ), bin_ip)
end
if lrucache then
lrucache:set(ip, {bin_ip, bin_octets})
end
return bin_ip, bin_octets
end
_M.ip2bin = ip2bin
local function split_cidr(input)
local pos = str_find(input, "/", 0, true)
if not pos then
return {input}
end
return {str_sub(input, 1, pos-1), str_sub(input, pos+1, -1)}
end
local function parse_cidr(cidr)
local mask_split = split_cidr(cidr, '/')
local net = mask_split[1]
local mask = mask_split[2] or "32"
local mask_num = tonumber(mask)
if not mask_num or (mask_num > 32 or mask_num < 1) then
return nil, "Invalid prefix: /"..tostring(mask)
end
local bin_net, err = ip2bin(net) -- Convert IP to binary
if not bin_net then
return nil, err
end
local bin_mask = bin_masks[mask] -- Get masks
local bin_inv_mask = bin_inverted_masks[mask]
local lower = band(bin_net, bin_mask) -- Network address
local upper = bor(lower, bin_inv_mask) -- Broadcast address
return lower, upper
end
_M.parse_cidr = parse_cidr
local function parse_cidrs(cidrs)
local out = {}
local i = 1
for _,cidr in ipairs(cidrs) do
local lower, upper = parse_cidr(cidr)
if not lower then
log_err("Error parsing '", cidr, "': ", upper)
else
out[i] = {lower, upper}
i = i+1
end
end
return out
end
_M.parse_cidrs = parse_cidrs
local function ip_in_cidrs(ip, cidrs)
local bin_ip, bin_octets = ip2bin(ip)
if not bin_ip then
return nil, bin_octets
end
for _,cidr in ipairs(cidrs) do
if bin_ip >= cidr[1] and bin_ip <= cidr[2] then
return true
end
end
return false
end
_M.ip_in_cidrs = ip_in_cidrs
local function binip_in_cidrs(bin_ip_ngx, cidrs)
if 4 ~= #bin_ip_ngx then
return false, "invalid IP address"
end
local bin_ip = 0
for i=1,4 do
bin_ip = bor(lshift(bin_ip, 8), tobit(byte(bin_ip_ngx, i)))
end
for _,cidr in ipairs(cidrs) do
if bin_ip >= cidr[1] and bin_ip <= cidr[2] then
return true
end
end
return false
end
_M.binip_in_cidrs = binip_in_cidrs
return _M
|
local ipairs, tonumber, tostring, type = ipairs, tonumber, tostring, type
local bit = require("bit")
local tobit = bit.tobit
local lshift = bit.lshift
local band = bit.band
local bor = bit.bor
local xor = bit.bxor
local byte = string.byte
local str_find = string.find
local str_sub = string.sub
local lrucache = nil
local _M = {
_VERSION = '0.2.1',
}
local mt = { __index = _M }
-- Precompute binary subnet masks...
local bin_masks = {}
for i=0,32 do
bin_masks[tostring(i)] = lshift(tobit((2^i)-1), 32-i)
end
-- ... and their inverted counterparts
local bin_inverted_masks = {}
for i=0,32 do
local i = tostring(i)
bin_inverted_masks[i] = xor(bin_masks[i], bin_masks["32"])
end
local log_err
if ngx then
log_err = function(...)
ngx.log(ngx.ERR, ...)
end
else
log_err = function(...)
print(...)
end
end
local function enable_lrucache(size)
local size = size or 4000 -- Cache the last 4000 IPs (~1MB memory) by default
local lrucache_obj, err = require("resty.lrucache").new(size)
if not lrucache_obj then
return nil, "failed to create the cache: " .. (err or "unknown")
end
lrucache = lrucache_obj
return true
end
_M.enable_lrucache = enable_lrucache
local function split_octets(input)
local pos = 0
local prev = 0
local octs = {}
for i=1, 4 do
pos = str_find(input, ".", prev, true)
if pos then
if i == 4 then
-- Should not have a match after 4 octets
return nil, "Invalid IP"
end
octs[i] = str_sub(input, prev, pos-1)
elseif i == 4 then
-- Last octet, get everything to the end
octs[i] = str_sub(input, prev, -1)
break
else
return nil, "Invalid IP"
end
prev = pos +1
end
return octs
end
local function unsign(bin)
if bin < 0 then
return 4294967296 + bin
end
return bin
end
local function ip2bin(ip)
if lrucache then
local get = lrucache:get(ip)
if get then
return get[1], get[2]
end
end
if type(ip) ~= "string" then
return nil, "IP must be a string"
end
local octets = split_octets(ip)
if not octets or #octets ~= 4 then
return nil, "Invalid IP"
end
-- Return the binary representation of an IP and a table of binary octets
local bin_octets = {}
local bin_ip = 0
for i,octet in ipairs(octets) do
local bin_octet = tonumber(octet)
if not bin_octet or bin_octet > 255 then
return nil, "Invalid octet: "..tostring(octet)
end
bin_octet = tobit(bin_octet)
bin_octets[i] = bin_octet
bin_ip = bor(lshift(bin_octet, 8*(4-i) ), bin_ip)
end
bin_ip = unsign(bin_ip)
if lrucache then
lrucache:set(ip, {bin_ip, bin_octets})
end
return bin_ip, bin_octets
end
_M.ip2bin = ip2bin
local function split_cidr(input)
local pos = str_find(input, "/", 0, true)
if not pos then
return {input}
end
return {str_sub(input, 1, pos-1), str_sub(input, pos+1, -1)}
end
local function parse_cidr(cidr)
local mask_split = split_cidr(cidr, '/')
local net = mask_split[1]
local mask = mask_split[2] or "32"
local mask_num = tonumber(mask)
if not mask_num or (mask_num > 32 or mask_num < 0) then
return nil, "Invalid prefix: /"..tostring(mask)
end
local bin_net, err = ip2bin(net) -- Convert IP to binary
if not bin_net then
return nil, err
end
local bin_mask = bin_masks[mask] -- Get masks
local bin_inv_mask = bin_inverted_masks[mask]
local lower = band(bin_net, bin_mask) -- Network address
local upper = bor(lower, bin_inv_mask) -- Broadcast address
return unsign(lower), unsign(upper)
end
_M.parse_cidr = parse_cidr
local function parse_cidrs(cidrs)
local out = {}
local i = 1
for _,cidr in ipairs(cidrs) do
local lower, upper = parse_cidr(cidr)
if not lower then
log_err("Error parsing '", cidr, "': ", upper)
else
out[i] = {lower, upper}
i = i+1
end
end
return out
end
_M.parse_cidrs = parse_cidrs
local function ip_in_cidrs(ip, cidrs)
local bin_ip, bin_octets = ip2bin(ip)
if not bin_ip then
return nil, bin_octets
end
for _,cidr in ipairs(cidrs) do
if bin_ip >= cidr[1] and bin_ip <= cidr[2] then
return true
end
end
return false
end
_M.ip_in_cidrs = ip_in_cidrs
local function binip_in_cidrs(bin_ip_ngx, cidrs)
if 4 ~= #bin_ip_ngx then
return false, "invalid IP address"
end
local bin_ip = 0
for i=1,4 do
bin_ip = bor(lshift(bin_ip, 8), tobit(byte(bin_ip_ngx, i)))
end
bin_ip = unsign(bin_ip)
for _,cidr in ipairs(cidrs) do
if bin_ip >= cidr[1] and bin_ip <= cidr[2] then
return true
end
end
return false
end
_M.binip_in_cidrs = binip_in_cidrs
return _M
|
Allow /0 netmasks, fix signedness issue
|
Allow /0 netmasks, fix signedness issue
|
Lua
|
mit
|
hamishforbes/lua-resty-iputils
|
94863364a08da9c306166174782afc7d67fa340d
|
modules/admin-mini/luasrc/model/cbi/mini/network.lua
|
modules/admin-mini/luasrc/model/cbi/mini/network.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$
]]--
require("luci.tools.webadmin")
require("luci.sys")
m0 = Map("network", translate("network"))
m0.stateful = true
local netstat = luci.sys.net.deviceinfo()
m0.parse = function() end
s = m0:section(TypedSection, "interface", translate("status"))
s.template = "cbi/tblsection"
s.rowcolors = true
function s.filter(self, section)
return section ~= "loopback" and section
end
hwaddr = s:option(DummyValue, "_hwaddr")
function hwaddr.cfgvalue(self, section)
local ix = self.map:get(section, "ifname") or ""
return luci.fs.readfile("/sys/class/net/" .. ix .. "/address") or "n/a"
end
s:option(DummyValue, "ipaddr", translate("ipaddress"))
s:option(DummyValue, "netmask", translate("netmask"))
txrx = s:option(DummyValue, "_txrx")
function txrx.cfgvalue(self, section)
local ix = self.map:get(section, "ifname")
local rx = netstat and netstat[ix] and netstat[ix][1]
rx = rx and luci.tools.webadmin.byte_format(tonumber(rx)) or "-"
local tx = netstat and netstat[ix] and netstat[ix][9]
tx = tx and luci.tools.webadmin.byte_format(tonumber(tx)) or "-"
return string.format("%s / %s", tx, rx)
end
errors = s:option(DummyValue, "_err")
function errors.cfgvalue(self, section)
local ix = self.map:get(section, "ifname")
local rx = netstat and netstat[ix] and netstat[ix][3]
local tx = netstat and netstat[ix] and netstat[ix][11]
rx = rx and tostring(rx) or "-"
tx = tx and tostring(tx) or "-"
return string.format("%s / %s", tx, rx)
end
m = Map("network", "")
s = m:section(NamedSection, "lan", "interface", translate("m_n_local"))
s:option(Value, "ipaddr", translate("ipaddress"))
nm = s:option(Value, "netmask", translate("netmask"))
nm:value("255.255.255.0")
nm:value("255.255.0.0")
nm:value("255.0.0.0")
gw = s:option(Value, "gateway", translate("gateway") .. translate("cbi_optional"))
gw.rmempty = true
dns = s:option(Value, "dns", translate("dnsserver") .. translate("cbi_optional"))
dns.rmempty = true
s = m:section(NamedSection, "wan", "interface", translate("m_n_inet"))
p = s:option(ListValue, "proto", translate("protocol"))
p:value("none", "disabled")
p:value("static", translate("manual", "manual"))
p:value("dhcp", translate("automatic", "automatic"))
p:value("pppoe", "PPPoE")
p:value("pptp", "PPTP")
ip = s:option(Value, "ipaddr", translate("ipaddress"))
ip:depends("proto", "static")
nm = s:option(Value, "netmask", translate("netmask"))
nm:depends("proto", "static")
gw = s:option(Value, "gateway", translate("gateway"))
gw:depends("proto", "static")
gw.rmempty = true
dns = s:option(Value, "dns", translate("dnsserver"))
dns:depends("proto", "static")
dns.rmempty = true
usr = s:option(Value, "username", translate("username"))
usr:depends("proto", "pppoe")
usr:depends("proto", "pptp")
pwd = s:option(Value, "password", translate("password"))
pwd:depends("proto", "pppoe")
pwd:depends("proto", "pptp")
kea = s:option(Flag, "keepalive", translate("m_n_keepalive"))
kea:depends("proto", "pppoe")
kea:depends("proto", "pptp")
kea.rmempty = true
kea.enabled = "10"
cod = s:option(Value, "demand", translate("m_n_dialondemand"), "s")
cod:depends("proto", "pppoe")
cod:depends("proto", "pptp")
cod.rmempty = true
srv = s:option(Value, "server", translate("m_n_pptp_server"))
srv:depends("proto", "pptp")
srv.rmempty = true
return m0, m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
require("luci.sys")
luci.model.uci.load_state("network")
local wireless = luci.model.uci.get_all("network")
luci.model.uci.unload("network")
local netstat = luci.sys.net.deviceinfo()
local ifaces = {}
for k, v in pairs(wireless) do
if v[".type"] == "interface" and k ~= "loopback" then
table.insert(ifaces, v)
end
end
m = Map("network", translate("network"))
s = m:section(Table, ifaces, translate("status"))
s.parse = function() end
s:option(DummyValue, ".name", translate("network"))
hwaddr = s:option(DummyValue, "_hwaddr",
translate("network_interface_hwaddr"), translate("network_interface_hwaddr_desc"))
function hwaddr.cfgvalue(self, section)
local ix = self.map:get(section, "ifname") or ""
return luci.fs.readfile("/sys/class/net/" .. ix .. "/address") or "n/a"
end
s:option(DummyValue, "ipaddr", translate("ipaddress"))
s:option(DummyValue, "netmask", translate("netmask"))
txrx = s:option(DummyValue, "_txrx",
translate("network_interface_txrx"), translate("network_interface_txrx_desc"))
function txrx.cfgvalue(self, section)
local ix = self.map:get(section, "ifname")
local rx = netstat and netstat[ix] and netstat[ix][1]
rx = rx and luci.tools.webadmin.byte_format(tonumber(rx)) or "-"
local tx = netstat and netstat[ix] and netstat[ix][9]
tx = tx and luci.tools.webadmin.byte_format(tonumber(tx)) or "-"
return string.format("%s / %s", tx, rx)
end
errors = s:option(DummyValue, "_err",
translate("network_interface_err"), translate("network_interface_err_desc"))
function errors.cfgvalue(self, section)
local ix = self.map:get(section, "ifname")
local rx = netstat and netstat[ix] and netstat[ix][3]
local tx = netstat and netstat[ix] and netstat[ix][11]
rx = rx and tostring(rx) or "-"
tx = tx and tostring(tx) or "-"
return string.format("%s / %s", tx, rx)
end
s = m:section(NamedSection, "lan", "interface", translate("m_n_local"))
s:option(Value, "ipaddr", translate("ipaddress"))
nm = s:option(Value, "netmask", translate("netmask"))
nm:value("255.255.255.0")
nm:value("255.255.0.0")
nm:value("255.0.0.0")
gw = s:option(Value, "gateway", translate("gateway") .. translate("cbi_optional"))
gw.rmempty = true
dns = s:option(Value, "dns", translate("dnsserver") .. translate("cbi_optional"))
dns.rmempty = true
s = m:section(NamedSection, "wan", "interface", translate("m_n_inet"))
p = s:option(ListValue, "proto", translate("protocol"))
p:value("none", "disabled")
p:value("static", translate("manual", "manual"))
p:value("dhcp", translate("automatic", "automatic"))
p:value("pppoe", "PPPoE")
p:value("pptp", "PPTP")
ip = s:option(Value, "ipaddr", translate("ipaddress"))
ip:depends("proto", "static")
nm = s:option(Value, "netmask", translate("netmask"))
nm:depends("proto", "static")
gw = s:option(Value, "gateway", translate("gateway"))
gw:depends("proto", "static")
gw.rmempty = true
dns = s:option(Value, "dns", translate("dnsserver"))
dns:depends("proto", "static")
dns.rmempty = true
usr = s:option(Value, "username", translate("username"))
usr:depends("proto", "pppoe")
usr:depends("proto", "pptp")
pwd = s:option(Value, "password", translate("password"))
pwd:depends("proto", "pppoe")
pwd:depends("proto", "pptp")
kea = s:option(Flag, "keepalive", translate("m_n_keepalive"))
kea:depends("proto", "pppoe")
kea:depends("proto", "pptp")
kea.rmempty = true
kea.enabled = "10"
cod = s:option(Value, "demand", translate("m_n_dialondemand"), "s")
cod:depends("proto", "pppoe")
cod:depends("proto", "pptp")
cod.rmempty = true
srv = s:option(Value, "server", translate("m_n_pptp_server"))
srv:depends("proto", "pptp")
srv.rmempty = true
return m
|
Fixed duplicate tables
|
Fixed duplicate tables
|
Lua
|
apache-2.0
|
deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci
|
2ee93255d37f94ad17fdeefb65aec914c2790cb9
|
[resources]/GTWgrouplogs/logs.lua
|
[resources]/GTWgrouplogs/logs.lua
|
--[[
********************************************************************************
Project owner: RageQuit community
Project name: GTW-RPG
Developers: El Med, Mr_Moose
Source code: https://github.com/GTWCode/GTW-RPG/
Bugtracker: http://forum.404rq.com/bug-reports/
Suggestions: http://forum.404rq.com/mta-servers-development/
Version: Open source
License: BSD 2-Clause
Status: Stable release
********************************************************************************
]]--
local message = { }
local lastnick = { }
-- Database connection setup, MySQL or fallback SQLite
local mysql_host = exports.GTWcore:getMySQLHost() or nil
local mysql_database = exports.GTWcore:getMySQLDatabase() or nil
local mysql_user = exports.GTWcore:getMySQLUser() or nil
local mysql_pass = exports.GTWcore:getMySQLPass() or nil
local db = dbConnect("mysql", "dbname="..mysql_database..";host="..mysql_host, mysql_user, mysql_pass, "autoreconnect=1")
if not db then db = dbConnect("sqlite", "logs.db") end
dbExec(db, "CREATE TABLE IF NOT EXISTS groupLog (name TEXT, log TEXT, date TEXT)")
dbExec(db, "CREATE TABLE IF NOT EXISTS lastNick (account TEXT, nick TEXT)")
function getServerTime ( )
local aRealTime = getRealTime()
return
string.format ( "%04d/%02d/%02d", aRealTime.year + 1900, aRealTime.month + 1, aRealTime.monthday ),
string.format ( "%02d:%02d:%02d", aRealTime.hour, aRealTime.minute, aRealTime.second )
end
function loadGroupLogs(handler)
local data = dbPoll(handler, 0)
if (not data) then return end
for ind, dat in pairs(data) do
local group = dat.name
if (not message[group]) then message[group] = {} end
table.insert(message[group], {msg = dat.log})
end
end
dbQuery(loadGroupLogs, db, "SELECT * FROM groupLog")
function loadNicks(query)
local d = dbPoll(query, 0)
if (d) then
for ind, data in pairs(d) do
lastnick[data.account] = data.nick
end
end
end
dbQuery(loadNicks, db, "SELECT * FROM lastNick")
function logSomething(group, msg)
local date, time = getServerTime()
local date = "["..date.." - "..time.."] "
local msg = date..msg
if (not message[group]) then message[group] = {} end
table.insert(message[group], {msg = msg})
dbExec(db, "INSERT INTO groupLog (name, log, date) VALUES (?, ?, ?)", tostring(group), tostring(msg), tostring(date))
end
function viewLog(plr, group)
triggerClientEvent(plr, "GTWlogs.openLog", plr, group, message[group], "groupLog", true)
end
function getLastNick(account)
return lastnick[account] or "N/A"
end
addCommandHandler("gtwinfo", function(plr, cmd)
outputChatBox("[GTW-RPG] "..getResourceName(
getThisResource())..", by: "..getResourceInfo(
getThisResource(), "author")..", v-"..getResourceInfo(
getThisResource(), "version")..", is represented", plr)
end)
function setLastNick(player)
local account = getAccountName(getPlayerAccount(player))
if (lastnick[account]) then
dbExec(db, "UPDATE lastNick SET nick=? WHERE account=?", tostring(getPlayerName(player)), tostring(account))
else
dbExec(db, "INSERT INTO lastNick VALUES (?, ?)", tostring(account), tostring(getPlayerName(player)))
end
lastnick[account] = getPlayerName(player)
end
|
--[[
********************************************************************************
Project owner: RageQuit community
Project name: GTW-RPG
Developers: El Med, Mr_Moose
Source code: https://github.com/GTWCode/GTW-RPG/
Bugtracker: http://forum.404rq.com/bug-reports/
Suggestions: http://forum.404rq.com/mta-servers-development/
Version: Open source
License: BSD 2-Clause
Status: Stable release
********************************************************************************
]]--
local message = { }
local lastnick = { }
-- Database connection setup, MySQL or fallback SQLite
local mysql_host = exports.GTWcore:getMySQLHost() or nil
local mysql_database = exports.GTWcore:getMySQLDatabase() or nil
local mysql_user = exports.GTWcore:getMySQLUser() or nil
local mysql_pass = exports.GTWcore:getMySQLPass() or nil
local mysql_type = "mysql"
if mysql_host == nil or mysql_host == "" then
mysql_type = "sqlite"
else
mysql_type = "mysql"
end
if mysql_type == 'sqlite' then
db = dbConnect("sqlite", "logs.db")
else
db = dbConnect("mysql", "dbname="..mysql_database..";host="..mysql_host, mysql_user, mysql_pass, "autoreconnect=1")
end
dbExec(db, "CREATE TABLE IF NOT EXISTS groupLog (name TEXT, log TEXT, date TEXT)")
dbExec(db, "CREATE TABLE IF NOT EXISTS lastNick (account TEXT, nick TEXT)")
function getServerTime ( )
local aRealTime = getRealTime()
return
string.format ( "%04d/%02d/%02d", aRealTime.year + 1900, aRealTime.month + 1, aRealTime.monthday ),
string.format ( "%02d:%02d:%02d", aRealTime.hour, aRealTime.minute, aRealTime.second )
end
function loadGroupLogs(handler)
local data = dbPoll(handler, 0)
if (not data) then return end
for ind, dat in pairs(data) do
local group = dat.name
if (not message[group]) then message[group] = {} end
table.insert(message[group], {msg = dat.log})
end
end
dbQuery(loadGroupLogs, db, "SELECT * FROM groupLog")
function loadNicks(query)
local d = dbPoll(query, 0)
if (d) then
for ind, data in pairs(d) do
lastnick[data.account] = data.nick
end
end
end
dbQuery(loadNicks, db, "SELECT * FROM lastNick")
function logSomething(group, msg)
local date, time = getServerTime()
local date = "["..date.." - "..time.."] "
local msg = date..msg
if (not message[group]) then message[group] = {} end
table.insert(message[group], {msg = msg})
dbExec(db, "INSERT INTO groupLog (name, log, date) VALUES (?, ?, ?)", tostring(group), tostring(msg), tostring(date))
end
function viewLog(plr, group)
triggerClientEvent(plr, "GTWlogs.openLog", plr, group, message[group], "groupLog", true)
end
function getLastNick(account)
return lastnick[account] or "N/A"
end
addCommandHandler("gtwinfo", function(plr, cmd)
outputChatBox("[GTW-RPG] "..getResourceName(
getThisResource())..", by: "..getResourceInfo(
getThisResource(), "author")..", v-"..getResourceInfo(
getThisResource(), "version")..", is represented", plr)
end)
function setLastNick(player)
local account = getAccountName(getPlayerAccount(player))
if (lastnick[account]) then
dbExec(db, "UPDATE lastNick SET nick=? WHERE account=?", tostring(getPlayerName(player)), tostring(account))
else
dbExec(db, "INSERT INTO lastNick VALUES (?, ?)", tostring(account), tostring(getPlayerName(player)))
end
lastnick[account] = getPlayerName(player)
end
|
Fixing the DB error
|
Fixing the DB error
it fixes the MySQL error coming out by checking if the Mysql host value is nil/"" then it will decide the data type it should connect to nd then it will connect according to that.
|
Lua
|
bsd-2-clause
|
404rq/GTW-RPG,GTWCode/GTW-RPG,GTWCode/GTW-RPG,404rq/GTW-RPG,404rq/GTW-RPG,GTWCode/GTW-RPG
|
d967ecd5775f1500a97f90151120fd69c85d3428
|
src/Model.lua
|
src/Model.lua
|
require 'cudnn'
require 'src.BiLSTM'
require 'src.BGRU'
function createModel(sample_height, num_labels)
local ks = {3, 3, 3, 3, 3, 3, 2}
local ss = {1, 1, 1, 1, 1, 1, 1}
local nm = {16, 16, 32, 32, 64, 128, 128}
local nh = {256, 256, 256}
function convBlock(depth_in, depth_out, size, stride, batch_norm)
batch_norm = batch_norm or false
local block = nn.Sequential()
-- Spatial 2D convolution. Image is padded with zeroes so that the output
-- has the same size as the input / stride
block:add(nn.SpatialConvolution(depth_in, depth_out,
size, size,
stride, stride,
(size - 1) / 2, (size - 1) / 2))
-- Batch normalization
if batch_norm then
block:add(nn.SpatialBatchNormalization(depth_out))
end
-- Parametric Rectifier Linear Unit
--block:add(nn.ReLU(true))
block:add(nn.LeakyReLU(true))
return block
end
local model = nn.Sequential()
-- CNN part
model:add(convBlock(1, nm[1], ks[1], ss[1]))
model:add(nn.SpatialMaxPooling(2, 2, 2, 2))
model:add(convBlock(nm[1], nm[2], ks[2], ss[2]))
model:add(nn.SpatialMaxPooling(2, 2, 2, 2))
model:add(convBlock(nm[2], nm[3], ks[3], ss[3], true))
model:add(convBlock(nm[3], nm[4], ks[4], ss[4]))
model:add(nn.SpatialMaxPooling(2, 2, 2, 2))
-- RNN part
model:add(nn.Transpose({2,4},{1,2}))
model:add(nn.Contiguous())
model:add(nn.Reshape(-1,256,true))
model:add(nn.Dropout(0.5))
model:add(cudnn.BiLSTM(256, 256, 3, nil, 0.5))
model:add(nn.Dropout(0.5))
model:add(nn.Contiguous())
model:add(nn.Reshape(-1, 512, false))
model:add(nn.Linear(512, num_labels + 1))
return model
end
|
require 'cudnn'
require 'src.BiLSTM'
require 'src.BGRU'
function createModel(sample_height, num_labels)
local ks = {3, 3, 3, 3, 3, 3, 2}
local ss = {1, 1, 1, 1, 1, 1, 1}
local nm = {16, 16, 32, 32, 64, 128, 128}
local nh = {256}
function convBlock(depth_in, depth_out, size, stride, batch_norm)
batch_norm = batch_norm or false
local block = nn.Sequential()
-- Spatial 2D convolution. Image is padded with zeroes so that the output
-- has the same size as the input / stride
block:add(nn.SpatialConvolution(depth_in, depth_out,
size, size,
stride, stride,
(size - 1) / 2, (size - 1) / 2))
-- Batch normalization
if batch_norm then
block:add(nn.SpatialBatchNormalization(depth_out))
end
-- Parametric Rectifier Linear Unit
--block:add(nn.ReLU(true))
block:add(nn.LeakyReLU(true))
return block
end
local model = nn.Sequential()
-- CNN part
model:add(convBlock(1, nm[1], ks[1], ss[1]))
model:add(nn.SpatialMaxPooling(2, 2, 2, 2))
model:add(convBlock(nm[1], nm[2], ks[2], ss[2]))
model:add(nn.SpatialMaxPooling(2, 2, 2, 2))
model:add(convBlock(nm[2], nm[3], ks[3], ss[3], true))
model:add(convBlock(nm[3], nm[4], ks[4], ss[4]))
model:add(nn.SpatialMaxPooling(2, 2, 2, 2)) -- 32 x 8
-- RNN part
model:add(nn.Transpose({2,4},{1,2}))
model:add(nn.Contiguous())
model:add(nn.Reshape(-1,256,true))
model:add(nn.Dropout(0.5))
--model:add(cudnn.BiLSTM(nh[1], nh[1], 3, nil, 0.5))
model:add(cudnn.BGRU(256, nh[1], 3, nil, 0.5))
model:add(nn.Dropout(0.5))
model:add(nn.Contiguous())
model:add(nn.Reshape(-1, nh[1]*2, false))
model:add(nn.Linear(nh[1]*2, num_labels + 1))
return model
end
|
Fixed Model definition
|
Fixed Model definition
|
Lua
|
mit
|
jpuigcerver/Laia,jpuigcerver/Laia,jpuigcerver/Laia,jpuigcerver/Laia
|
68076827ac5c1db9bbfcc4f450ace2ec44037e37
|
kong/pdk/private/phases.lua
|
kong/pdk/private/phases.lua
|
local bit = require "bit"
local band = bit.band
local fmt = string.format
local ngx_get_phase = ngx.get_phase
local PHASES = {
--init = 0x00000001,
init_worker = 0x00000001,
certificate = 0x00000002,
--set = 0x00000004,
rewrite = 0x00000010,
access = 0x00000020,
balancer = 0x00000040,
response = 0x00000080,
--content = 0x00000100,
header_filter = 0x00000200,
body_filter = 0x00000400,
--timer = 0x00001000,
log = 0x00002000,
preread = 0x00004000,
error = 0x01000000,
admin_api = 0x10000000,
cluster_listener = 0x00000100,
}
do
local n = 0
for k, v in pairs(PHASES) do
n = n + 1
PHASES[v] = k
end
PHASES.n = n
end
local function new_phase(...)
return bit.bor(...)
end
local function get_phases_names(phases)
local names = {}
local n = 1
for _ = 1, PHASES.n do
if band(phases, n) ~= 0 and PHASES[n] then
table.insert(names, PHASES[n])
end
n = bit.lshift(n, 1)
end
return names
end
local function check_phase(accepted_phases)
if not kong or not kong.ctx then
-- no _G.kong, we are likely in tests
return
end
local current_phase = kong.ctx.core.phase
if not current_phase then
if ngx_get_phase() == "content" then
-- treat custom content blocks as the Admin API
current_phase = PHASES.admin_api
else
error("no phase in kong.ctx.core.phase")
end
end
if band(current_phase, accepted_phases) ~= 0 then
return
end
local current_phase_name = PHASES[current_phase] or "'unknown phase'"
local accepted_phases_names = get_phases_names(accepted_phases)
error(fmt("function cannot be called in %s phase (only in: %s)",
current_phase_name,
table.concat(accepted_phases_names, ", ")))
end
local function check_not_phase(rejected_phases)
if not kong or not kong.ctx then
-- no _G.kong, we are likely in tests
return
end
local current_phase = kong.ctx.core.phase
if not current_phase then
error("no phase in kong.ctx.core.phase")
end
if band(current_phase, rejected_phases) == 0 then
return
end
local current_phase_name = PHASES[current_phase] or "'unknown phase'"
local rejected_phases_names = get_phases_names(rejected_phases)
error(fmt("function cannot be called in %s phase (can be called in any " ..
"phases except: %s)",
current_phase_name,
table.concat(rejected_phases_names, ", ")))
end
-- Exact phases + convenience aliases
local public_phases = setmetatable({
request = new_phase(PHASES.rewrite,
PHASES.access,
PHASES.response,
PHASES.header_filter,
PHASES.body_filter,
PHASES.log,
PHASES.error,
PHASES.admin_api,
PHASES.cluster_listener),
}, {
__index = function(t, k)
error("unknown phase or phase alias: " .. k)
end
})
for k, v in pairs(PHASES) do
public_phases[k] = v
end
return {
new = new_phase,
check = check_phase,
check_not = check_not_phase,
phases = public_phases,
}
|
local bit = require "bit"
local band = bit.band
local fmt = string.format
local ngx_get_phase = ngx.get_phase
local PHASES = {
--init = 0x00000001,
init_worker = 0x00000001,
certificate = 0x00000002,
--set = 0x00000004,
rewrite = 0x00000010,
access = 0x00000020,
balancer = 0x00000040,
response = 0x00000080,
--content = 0x00000100,
header_filter = 0x00000200,
body_filter = 0x00000400,
--timer = 0x00001000,
log = 0x00002000,
preread = 0x00004000,
error = 0x01000000,
admin_api = 0x10000000,
cluster_listener = 0x00000100,
}
do
local t = {}
for k, v in pairs(PHASES) do
t[k] = v
end
local n = 0
for k, v in pairs(t) do
n = n + 1
PHASES[v] = k
end
PHASES.n = n
end
local function new_phase(...)
return bit.bor(...)
end
local function get_phases_names(phases)
local names = {}
local n = 1
for _ = 1, PHASES.n do
if band(phases, n) ~= 0 and PHASES[n] then
table.insert(names, PHASES[n])
end
n = bit.lshift(n, 1)
end
return names
end
local function check_phase(accepted_phases)
if not kong or not kong.ctx then
-- no _G.kong, we are likely in tests
return
end
local current_phase = kong.ctx.core.phase
if not current_phase then
if ngx_get_phase() == "content" then
-- treat custom content blocks as the Admin API
current_phase = PHASES.admin_api
else
error("no phase in kong.ctx.core.phase")
end
end
if band(current_phase, accepted_phases) ~= 0 then
return
end
local current_phase_name = PHASES[current_phase] or "'unknown phase'"
local accepted_phases_names = get_phases_names(accepted_phases)
error(fmt("function cannot be called in %s phase (only in: %s)",
current_phase_name,
table.concat(accepted_phases_names, ", ")))
end
local function check_not_phase(rejected_phases)
if not kong or not kong.ctx then
-- no _G.kong, we are likely in tests
return
end
local current_phase = kong.ctx.core.phase
if not current_phase then
error("no phase in kong.ctx.core.phase")
end
if band(current_phase, rejected_phases) == 0 then
return
end
local current_phase_name = PHASES[current_phase] or "'unknown phase'"
local rejected_phases_names = get_phases_names(rejected_phases)
error(fmt("function cannot be called in %s phase (can be called in any " ..
"phases except: %s)",
current_phase_name,
table.concat(rejected_phases_names, ", ")))
end
-- Exact phases + convenience aliases
local public_phases = setmetatable({
request = new_phase(PHASES.rewrite,
PHASES.access,
PHASES.response,
PHASES.header_filter,
PHASES.body_filter,
PHASES.log,
PHASES.error,
PHASES.admin_api,
PHASES.cluster_listener),
}, {
__index = function(t, k)
error("unknown phase or phase alias: " .. k)
end
})
for k, v in pairs(PHASES) do
public_phases[k] = v
end
return {
new = new_phase,
check = check_phase,
check_not = check_not_phase,
phases = public_phases,
}
|
fix(pdk) don't modify iterated table when building the phases
|
fix(pdk) don't modify iterated table when building the phases
### Summary
> The behavior of next is undefined if, during the traversal, you assign
> any value to a non-existent field in the table. You may however modify
> existing fields. In particular, you may clear existing fields.
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
54b38b7fe8ec0a1b1199f8a9ec212441004e9924
|
packages/lime-system/files/usr/lib/lua/lime/config.lua
|
packages/lime-system/files/usr/lib/lua/lime/config.lua
|
#!/usr/bin/lua
--! LibreMesh is modular but this doesn't mean parallel, modules are executed
--! sequencially, so we don't need to worry about transactionality and all other
--! stuff that affects parrallels database, at moment we don't need parallelism
--! as this is just some configuration stuff and is not performance critical.
local libuci = require("uci")
config = {}
config.uci = libuci:cursor()
--! Minimal /etc/config/lime santitizing
function config.sanitize()
local cf = io.open("/etc/config/lime", "r")
if (cf == nil) then
cf = io.open("/etc/config/lime", "w")
cf:write("")
end
cf:close()
for _,sectName in pairs({"system","network","wifi"}) do
config.set(sectName, "lime")
end
end
function config.get(sectionname, option, default)
local limeconf = config.uci:get("lime", sectionname, option)
if limeconf then return limeconf end
local defcnf = config.uci:get("lime-defaults", sectionname, option)
if ( defcnf ~= nil ) then
config.set(sectionname, option, defcnf)
elseif ( default ~= nil ) then
defcnf = default
local cfn = sectionname.."."..option
print("WARNING: Option "..cfn.." is not defined. Using value "..default)
else
local cfn = sectionname.."."..option
print("WARNING: Attempt to access undeclared default for: "..cfn)
print(debug.traceback())
end
return defcnf
end
--! Execute +callback+ for each config of type +configtype+ found in
--! +/etc/config/lime+.
--! beware this function doesn't look in +/etc/config/lime-default+ for default
--! values as it is designed for use with specific sections only
function config.foreach(configtype, callback)
return config.uci:foreach("lime", configtype, callback)
end
function config.get_all(sectionname)
local lime_section = config.uci:get_all("lime", sectionname)
local lime_def_section = config.uci:get_all("lime-defaults", sectionname)
if lime_section or lime_def_section then
local ret = lime_section or {}
if lime_def_section then
for key,value in pairs(lime_def_section) do
if (ret[key] == nil) then
config.set(sectionname, key, value)
ret[key] = value
end
end
end
return ret
end
return nil
end
function config.get_bool(sectionname, option, default)
local val = config.get(sectionname, option, default)
return (val and ((val == '1') or (val == 'on') or (val == 'true') or (val == 'enabled')))
end
config.batched = false
function config.init_batch()
config.batched = true
end
function config.set(...)
local aty = type(arg[3])
if (aty ~= "nil" and aty ~= "string" and aty ~= "table") then
arg[3] = tostring(arg[3])
end
config.uci:set("lime", unpack(arg))
if(not config.batched) then config.uci:save("lime") end
end
function config.delete(...)
config.uci:delete("lime", unpack(arg))
if(not config.batched) then config.uci:save("lime") end
end
function config.end_batch()
if(config.batched) then
config.uci:save("lime")
config.batched = false
end
end
function config.autogenerable(section_name)
return ( (not config.get_all(section_name)) or config.get_bool(section_name, "autogenerated") )
end
return config
|
#!/usr/bin/lua
--! LibreMesh is modular but this doesn't mean parallel, modules are executed
--! sequencially, so we don't need to worry about transactionality and all other
--! stuff that affects parrallels database, at moment we don't need parallelism
--! as this is just some configuration stuff and is not performance critical.
local libuci = require("uci")
config = {}
config.uci = libuci:cursor()
--! Minimal /etc/config/lime santitizing
function config.sanitize()
local cf = io.open("/etc/config/lime", "r")
if (cf == nil) then
cf = io.open("/etc/config/lime", "w")
cf:write("")
end
cf:close()
for _,sectName in pairs({"system","network","wifi"}) do
config.set(sectName, "lime")
end
end
function config.get(sectionname, option, default)
local limeconf = config.uci:get("lime", sectionname, option)
if limeconf then return limeconf end
local defcnf = config.uci:get("lime-defaults", sectionname, option)
if ( defcnf ~= nil ) then
config.set(sectionname, option, defcnf)
elseif ( default ~= nil ) then
defcnf = default
local cfn = sectionname.."."..option
print("WARNING: Option "..cfn.." is not defined. Using value "..tostring(defcnf))
else
local cfn = sectionname.."."..option
print("WARNING: Attempt to access undeclared default for: "..cfn)
print(debug.traceback())
end
return defcnf
end
--! Execute +callback+ for each config of type +configtype+ found in
--! +/etc/config/lime+.
--! beware this function doesn't look in +/etc/config/lime-default+ for default
--! values as it is designed for use with specific sections only
function config.foreach(configtype, callback)
return config.uci:foreach("lime", configtype, callback)
end
function config.get_all(sectionname)
local lime_section = config.uci:get_all("lime", sectionname)
local lime_def_section = config.uci:get_all("lime-defaults", sectionname)
if lime_section or lime_def_section then
local ret = lime_section or {}
if lime_def_section then
for key,value in pairs(lime_def_section) do
if (ret[key] == nil) then
config.set(sectionname, key, value)
ret[key] = value
end
end
end
return ret
end
return nil
end
function config.get_bool(sectionname, option, default)
local val = config.get(sectionname, option, default)
return (val and ((val == '1') or (val == 'on') or (val == 'true') or (val == 'enabled') or (val == 1) or (val == true)))
end
config.batched = false
function config.init_batch()
config.batched = true
end
function config.set(...)
local aty = type(arg[3])
if (aty ~= "nil" and aty ~= "string" and aty ~= "table") then
arg[3] = tostring(arg[3])
end
config.uci:set("lime", unpack(arg))
if(not config.batched) then config.uci:save("lime") end
end
function config.delete(...)
config.uci:delete("lime", unpack(arg))
if(not config.batched) then config.uci:save("lime") end
end
function config.end_batch()
if(config.batched) then
config.uci:save("lime")
config.batched = false
end
end
function config.autogenerable(section_name)
return ( (not config.get_all(section_name)) or config.get_bool(section_name, "autogenerated") )
end
return config
|
config.lua: get_bool & defcnf hotfix
|
config.lua: get_bool & defcnf hotfix
config.get_bool:
If used with real boolean values like 1 or true instead of strings like "1" and "true" the function fails.
config.get:
when the default value is a array/table the print message fails
|
Lua
|
agpl-3.0
|
libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages
|
0c410e8cc0343a7b483f55bc04f9d6e36cd1ab62
|
packages/parallel.lua
|
packages/parallel.lua
|
local typesetterPool = {}
local calculations = {}
local folioOrder = {}
local allTypesetters = function (f)
local o = SILE.typesetter
for k,v in pairs(typesetterPool) do
SILE.typesetter = v
f(k,v)
end
SILE.typesetter = o
end
local nulTypesetter = SILE.typesetter {} -- we ignore this
nulTypesetter.outputLinesToPage = function() end
local parallelPagebreak = function ()
for i = 1,#folioOrder do
local thisPageFrames = folioOrder[i]
for j = 1,#thisPageFrames do
local n = thisPageFrames[j]
local t = typesetterPool[n]
local thispage = {}
for i = 1, calculations[n].mark do
thispage[i] = table.remove(t.state.outputQueue, 1)
end
t:outputLinesToPage(thispage)
end
SILE.documentState.documentClass:endPage()
for j = 1,#thisPageFrames do
local n = thisPageFrames[j]
local t = typesetterPool[n]
t:initFrame(t.frame)
end
SILE.documentState.documentClass:newPage()
end
end
local setupParallel = function (klass, options)
nulTypesetter:init(SILE.getFrame("page"))
for k,v in pairs(options.frames) do
typesetterPool[k] = SILE.typesetter {}
typesetterPool[k].id = v
typesetterPool[k]:init(SILE.getFrame(v))
typesetterPool[k].pageBuilder = function()
-- No thank you, I will do that.
end
-- Fixed leading here is obviously a bug, but n-way leading calculations
-- get very complicated...
-- typesetterPool[k].leadingFor = function() return SILE.nodefactory.newVglue(SILE.settings.get("document.lineskip")) end
SILE.registerCommand(k, function (o,c) -- \left ...
SILE.typesetter = typesetterPool[k]
SILE.call(k..":font")
end)
SILE.registerCommand(k..":font", function (o,c) end) -- to be overridden
end
if not options.folios then
folioOrder = { {} }
for k,v in pairs(options.frames) do table.insert(folioOrder[1],k) end
else
folioOrder = options.folios -- As usual we trust the user knows what they're doing
end
local o = klass.newPage
klass.newPage = function(self)
allTypesetters(function (n,t)
calculations[n] = { mark = 0 }
end)
SILE.baseClass:newPage()
SILE.call("sync")
end
allTypesetters(function (n,t) calculations[n] = { mark = 0 } end)
o = klass.finish
klass.finish = function(self)
parallelPagebreak()
o(self)
end
end
local addBalancingGlue = function (h)
allTypesetters(function (n,t)
local g = h - calculations[n].heightOfNewMaterial
if g.length > 0 then
SU.debug("parallel", "Adding "..g.." to "..n)
t:pushVglue({ height = g })
end
calculations[n].mark = #t.state.outputQueue
end)
end
SILE.registerCommand("sync", function (o,c)
local anybreak = false
local maxheight = SILE.length.new()
allTypesetters(function (n,t)
t:leaveHmode(true)
-- Now we have each typesetter's content boxed up onto the output stream
-- but page breaking has not been run. See if page breaking would cause a
-- break
local lines = std.table.clone(t.state.outputQueue)
if SILE.pagebuilder.findBestBreak({vboxlist = lines, target = t:pageTarget() }) then
anybreak = true
end
end)
if anybreak then
parallelPagebreak()
return
end
allTypesetters(function (n,t)
calculations[n].heightOfNewMaterial = SILE.length.new()
local lastdepth = 0
for i = calculations[n].mark + 1, #t.state.outputQueue do
local thisHeight = t.state.outputQueue[i].height + t.state.outputQueue[i].depth
calculations[n].heightOfNewMaterial = calculations[n].heightOfNewMaterial + thisHeight
end
if maxheight < calculations[n].heightOfNewMaterial then maxheight = calculations[n].heightOfNewMaterial end
SU.debug("parallel", n..": pre-sync content="..calculations[n].mark..", now "..#t.state.outputQueue..", height of material: "..calculations[n].heightOfNewMaterial)
end)
addBalancingGlue(maxheight)
SILE.typesetter = nulTypesetter
end)
return {
init = setupParallel
}
|
local typesetterPool = {}
local calculations = {}
local folioOrder = {}
local allTypesetters = function (f)
local o = SILE.typesetter
for k,v in pairs(typesetterPool) do
SILE.typesetter = v
f(k,v)
end
SILE.typesetter = o
end
local nulTypesetter = SILE.typesetter {} -- we ignore this
nulTypesetter.outputLinesToPage = function() end
local parallelPagebreak = function ()
for i = 1,#folioOrder do
local thisPageFrames = folioOrder[i]
for j = 1,#thisPageFrames do
local n = thisPageFrames[j]
local t = typesetterPool[n]
local thispage = {}
SU.debug("parallel", "Dumping lines for page on typesetter "..t.id)
if #t.state.outputQueue > 0 and calculations[n].mark == 0 then
-- More than one page worth of stuff here.
-- Just ship out one page and hope for the best.
SILE.defaultTypesetter.pageBuilder(t)
else
for i = 1, calculations[n].mark do
thispage[i] = table.remove(t.state.outputQueue, 1)
SU.debug("parallel", thispage[i])
end
t:outputLinesToPage(thispage)
end
end
SILE.documentState.documentClass:endPage()
for j = 1,#thisPageFrames do
local n = thisPageFrames[j]
local t = typesetterPool[n]
t:initFrame(t.frame)
end
SILE.documentState.documentClass:newPage()
end
end
local setupParallel = function (klass, options)
nulTypesetter:init(SILE.getFrame("page"))
for k,v in pairs(options.frames) do
typesetterPool[k] = SILE.typesetter {}
typesetterPool[k].id = v
typesetterPool[k]:init(SILE.getFrame(v))
typesetterPool[k].pageBuilder = function()
-- No thank you, I will do that.
end
-- Fixed leading here is obviously a bug, but n-way leading calculations
-- get very complicated...
-- typesetterPool[k].leadingFor = function() return SILE.nodefactory.newVglue(SILE.settings.get("document.lineskip")) end
SILE.registerCommand(k, function (o,c) -- \left ...
SILE.typesetter = typesetterPool[k]
SILE.call(k..":font")
end)
SILE.registerCommand(k..":font", function (o,c) end) -- to be overridden
end
if not options.folios then
folioOrder = { {} }
for k,v in pairs(options.frames) do table.insert(folioOrder[1],k) end
else
folioOrder = options.folios -- As usual we trust the user knows what they're doing
end
local o = klass.newPage
klass.newPage = function(self)
allTypesetters(function (n,t)
calculations[n] = { mark = 0 }
end)
SILE.baseClass:newPage()
SILE.call("sync")
end
allTypesetters(function (n,t) calculations[n] = { mark = 0 } end)
o = klass.finish
klass.finish = function(self)
parallelPagebreak()
o(self)
end
end
local addBalancingGlue = function (h)
allTypesetters(function (n,t)
local g = h - calculations[n].heightOfNewMaterial
if g.length > 0 then
SU.debug("parallel", "Adding "..g.." to "..n)
t:pushVglue({ height = g })
end
calculations[n].mark = #t.state.outputQueue
end)
end
SILE.registerCommand("sync", function (o,c)
local anybreak = false
local maxheight = SILE.length.new()
SU.debug("parallel", "Trying a sync")
allTypesetters(function (n,t)
SU.debug("parallel", "Leaving hmode on "..t.id)
t:leaveHmode(true)
-- Now we have each typesetter's content boxed up onto the output stream
-- but page breaking has not been run. See if page breaking would cause a
-- break
local lines = std.table.clone(t.state.outputQueue)
if SILE.pagebuilder.findBestBreak({vboxlist = lines, target = t:pageTarget() }) then
anybreak = true
end
end)
if anybreak then
parallelPagebreak()
return
end
allTypesetters(function (n,t)
calculations[n].heightOfNewMaterial = SILE.length.new()
local lastdepth = 0
for i = calculations[n].mark + 1, #t.state.outputQueue do
local thisHeight = t.state.outputQueue[i].height + t.state.outputQueue[i].depth
calculations[n].heightOfNewMaterial = calculations[n].heightOfNewMaterial + thisHeight
end
if maxheight < calculations[n].heightOfNewMaterial then maxheight = calculations[n].heightOfNewMaterial end
SU.debug("parallel", n..": pre-sync content="..calculations[n].mark..", now "..#t.state.outputQueue..", height of material: "..calculations[n].heightOfNewMaterial)
end)
addBalancingGlue(maxheight)
SILE.typesetter = nulTypesetter
end)
return {
init = setupParallel
}
|
Mitigate bug #457.
|
Mitigate bug #457.
|
Lua
|
mit
|
simoncozens/sile,alerque/sile,alerque/sile,alerque/sile,simoncozens/sile,neofob/sile,simoncozens/sile,simoncozens/sile,neofob/sile,alerque/sile,neofob/sile,neofob/sile
|
262baf19b473f7018641807494aac15c0114929b
|
testserver/item/id_2207_wishingwell.lua
|
testserver/item/id_2207_wishingwell.lua
|
require("base.common")
-- UPDATE common SET com_script='item.id_2207_wishingwell' WHERE com_itemid IN (2207);
module("item.id_2207_wishingwell", package.seeall)
function LookAtItem(User, Item)
if ( Item.data == 666 ) then
if (User:getPlayerLanguage() == 0) then
world:itemInform(User,Item,"Wunschbrunnen");
else
world:itemInform(User,Item,"wishing well");
end
else
if (User:getPlayerLanguage() == 0) then
world:itemInform(User,Item,"Brunnen");
else
world:itemInform(User,Item,"well");
end
end
end
|
require("base.common")
-- UPDATE common SET com_script='item.id_2207_wishingwell' WHERE com_itemid IN (2207);
module("item.id_2207_wishingwell", package.seeall)
function LookAtItem(User, Item)
if ( Item:getData("modifier") == "wishing well" ) then
base.lookat.SetSpecialName(item, "Wunschbrunnen", "wishing well")
world:itemInform(User,Item,base.lookat.GenerateLookAt(User, Item, base.lookat.NONE)));
else
world:itemInform(User,Item,base.lookat.GenerateLookAt(User, Item, base.lookat.NONE)));
end
end
|
fixed itemLookAt and exchanged old data
|
fixed itemLookAt and exchanged old data
|
Lua
|
agpl-3.0
|
Baylamon/Illarion-Content,LaFamiglia/Illarion-Content,Illarion-eV/Illarion-Content,KayMD/Illarion-Content,vilarion/Illarion-Content
|
7a26372075f4b34a83668d91671366c41bd25819
|
src/rules.lua
|
src/rules.lua
|
require 'Target'
local system = require 'system'
local mkpath = system.mkpath
local P = {}
local Rule = {
init_stages = { 'unpack', 'patch' }
}
Rule.__index = Rule
local function import_paths(filename)
local o = {}
table.insert(o, mkpath(jagen.dir, 'lib', filename))
for _, overlay in ipairs(string.split(jagen.overlays, ' ')) do
table.insert(o, mkpath(jagen.dir, 'overlay', overlay, filename))
end
table.insert(o, mkpath(jagen.root, filename))
return o
end
local function loadsingle(filename)
local o, env = {}, {}
function env.package(rule)
o = rule
end
local chunk = loadfile(filename)
if chunk then
setfenv(chunk, env)
chunk()
end
return o
end
local function loadall(filename)
local o, env = {}, {
table = table,
jagen = jagen
}
function env.package(rule, template)
if template then
table.merge(rule, template)
rule.template = template
end
table.insert(o, rule)
end
local chunk = loadfile(filename)
if chunk then
setfenv(chunk, env)
chunk()
end
return o
end
local function add_package(rule, list)
rule = Rule:parse(rule)
local key = tostring(rule)
local pkg = list[key]
if not pkg then
pkg = Rule:new_package { rule.name, rule.config }
table.merge(pkg, rule)
pkg:add_default_targets(list)
pkg:add_stages(pkg, list)
list[key] = pkg
else
table.merge(pkg, rule)
end
pkg:add_stages(rule, list)
end
function Rule:__tostring()
local name = self.name
local config = self.config
if name and config then
return string.format('%s__%s', name, config)
else
return name or config or 'rule'
end
end
function Rule:parse(rule)
setmetatable(rule, self)
if type(rule[1]) == 'string' then
rule.name = rule[1]
table.remove(rule, 1)
end
if type(rule[1]) == 'string' then
rule.config = rule[1]
table.remove(rule, 1)
end
if type(rule.source) == 'string' then
rule.source = { type = 'dist', location = rule.source }
end
return rule
end
function Rule:new_package(rule)
local pkg = Rule:parse(rule)
local name = pkg.name
pkg.stages = pkg.stages or {}
for stage in each(self.init_stages) do
pkg:add_target(Target:new(name, stage))
end
for filename in each(import_paths('pkg/'..name..'.lua')) do
table.merge(pkg, Rule:parse(loadsingle(filename)))
end
return pkg
end
function Rule:required(name, config, template)
local rule = copy(assert(template))
rule.name = name
rule.config = config
rule.template = template
return rule
end
function Rule:add_stages(rule, list)
local template = rule.template or {}
local config = self.config or template.config
for _, stage in ipairs(rule) do
local tc = not stage.shared and self.config
local target = Target:from_rule(stage, self.name, tc)
for _, item in ipairs(stage.requires or {}) do
local config, name = config
if type(item) == 'string' then
name = item
else
name = item[1]
config = item[2] or config
end
target:append(Target:required(name, config))
add_package(Rule:required(name, config, template), list)
end
self:add_target(target)
end
end
function Rule:add_target(target)
local function default(this)
for _, stage in ipairs(self.init_stages) do
if stage == target.stage and stage == this.stage then
return this
end
end
end
local function eq(this)
return this.stage == target.stage and this.config == target.config or
default(this)
end
local found = find(eq, self.stages)
if found then
found:add_inputs(target)
else
table.insert(self.stages, target)
end
return self
end
function Rule:add_default_targets(list)
local source = self.source
local build = self.build
local config = self.config
if self.requires then
table.insert(self, { 'configure', requires = self.requires })
end
if build then
if build.type == 'GNU' then
if build.generate or build.autoreconf then
local autoreconf = {
{ 'autoreconf', shared = true,
requires = { { 'libtool', 'host' } }
}
}
self:add_stages(autoreconf, list)
end
end
if build.type then
local build_rules = {
{ 'configure', requires = { 'toolchain' } },
{ 'compile' },
{ 'install' }
}
self:add_stages(build_rules, list)
end
end
end
function Rule:add_ordering_dependencies()
local prev, common
for _, s in ipairs(self.stages) do
if prev then
s.inputs = s.inputs or {}
if common and s.config ~= prev.config then
append(s.inputs, common)
else
append(s.inputs, prev)
end
end
prev = s
if not s.config then
common = s
end
end
end
function Rule:each()
return each(self.stages)
end
function P.load()
local packages = {}
local Source = require 'Source'
local function add(rule)
add_package(rule, packages)
end
for filename in each(import_paths('rules.lua')) do
for rule in each(loadall(filename)) do
add(rule)
end
end
for _, pkg in pairs(packages) do
pkg.source = Source:create(pkg.source)
end
return packages
end
function P.merge(rules)
local packages = {}
for _, rule in pairs(rules) do
local name = assert(rule.name)
local pkg = packages[name]
if pkg then
for target in rule:each() do
pkg:add_target(target)
end
else
packages[name] = rule
end
end
return packages
end
return P
|
require 'Target'
local system = require 'system'
local mkpath = system.mkpath
local P = {}
local Rule = {
init_stages = { 'unpack', 'patch' }
}
Rule.__index = Rule
local function import_paths(filename)
local o = {}
table.insert(o, mkpath(jagen.dir, 'lib', filename))
for _, overlay in ipairs(string.split(jagen.overlays, ' ')) do
table.insert(o, mkpath(jagen.dir, 'overlay', overlay, filename))
end
table.insert(o, mkpath(jagen.root, filename))
return o
end
local function loadsingle(filename)
local o, env = {}, {}
function env.package(rule)
o = rule
end
local chunk = loadfile(filename)
if chunk then
setfenv(chunk, env)
chunk()
end
return o
end
local function loadall(filename)
local o, env = {}, {
table = table,
jagen = jagen
}
function env.package(rule, template)
local t
if template then
t = copy(template)
table.merge(t, Rule:parse(rule))
t.template = template
else
t = rule
end
table.insert(o, t)
end
local chunk = loadfile(filename)
if chunk then
setfenv(chunk, env)
chunk()
end
return o
end
local function add_package(rule, list)
rule = Rule:parse(rule)
local key = tostring(rule)
local pkg = list[key]
if not pkg then
pkg = Rule:new_package { rule.name, rule.config }
table.merge(pkg, rule)
pkg:add_default_targets(list)
pkg:add_stages(pkg, list)
list[key] = pkg
else
table.merge(pkg, rule)
end
pkg:add_stages(rule, list)
end
function Rule:__tostring()
local name = self.name
local config = self.config
if name and config then
return string.format('%s__%s', name, config)
else
return name or config or 'rule'
end
end
function Rule:parse(rule)
setmetatable(rule, self)
if type(rule[1]) == 'string' then
rule.name = rule[1]
table.remove(rule, 1)
end
if type(rule[1]) == 'string' then
rule.config = rule[1]
table.remove(rule, 1)
end
if type(rule.source) == 'string' then
rule.source = { type = 'dist', location = rule.source }
end
return rule
end
function Rule:new_package(rule)
local pkg = Rule:parse(rule)
local name = pkg.name
pkg.stages = pkg.stages or {}
for stage in each(self.init_stages) do
pkg:add_target(Target:new(name, stage))
end
for filename in each(import_paths('pkg/'..name..'.lua')) do
table.merge(pkg, Rule:parse(loadsingle(filename)))
end
return pkg
end
function Rule:required(name, config, template)
local rule = copy(assert(template))
rule.name = name
rule.config = config
rule.template = template
return rule
end
function Rule:add_stages(rule, list)
local template = rule.template or {}
local config = self.config or template.config
for _, stage in ipairs(rule) do
local tc = not stage.shared and self.config
local target = Target:from_rule(stage, self.name, tc)
for _, item in ipairs(stage.requires or {}) do
local config, name = config
if type(item) == 'string' then
name = item
else
name = item[1]
config = item[2] or config
end
target:append(Target:required(name, config))
add_package(Rule:required(name, config, template), list)
end
self:add_target(target)
end
end
function Rule:add_target(target)
local function default(this)
for _, stage in ipairs(self.init_stages) do
if stage == target.stage and stage == this.stage then
return this
end
end
end
local function eq(this)
return this.stage == target.stage and this.config == target.config or
default(this)
end
local found = find(eq, self.stages)
if found then
found:add_inputs(target)
else
table.insert(self.stages, target)
end
return self
end
function Rule:add_default_targets(list)
local source = self.source
local build = self.build
local config = self.config
if self.requires then
table.insert(self, { 'configure', requires = self.requires })
end
if build then
if build.type == 'GNU' then
if build.generate or build.autoreconf then
local autoreconf = {
{ 'autoreconf', shared = true,
requires = { { 'libtool', 'host' } }
}
}
self:add_stages(autoreconf, list)
end
end
if build.type then
local build_rules = {
{ 'configure', requires = { 'toolchain' } },
{ 'compile' },
{ 'install' }
}
self:add_stages(build_rules, list)
end
end
end
function Rule:add_ordering_dependencies()
local prev, common
for _, s in ipairs(self.stages) do
if prev then
s.inputs = s.inputs or {}
if common and s.config ~= prev.config then
append(s.inputs, common)
else
append(s.inputs, prev)
end
end
prev = s
if not s.config then
common = s
end
end
end
function Rule:each()
return each(self.stages)
end
function P.load()
local packages = {}
local Source = require 'Source'
local function add(rule)
add_package(rule, packages)
end
for filename in each(import_paths('rules.lua')) do
for rule in each(loadall(filename)) do
add(rule)
end
end
for _, pkg in pairs(packages) do
pkg.source = Source:create(pkg.source)
end
return packages
end
function P.merge(rules)
local packages = {}
for _, rule in pairs(rules) do
local name = assert(rule.name)
local pkg = packages[name]
if pkg then
for target in rule:each() do
pkg:add_target(target)
end
else
packages[name] = rule
end
end
return packages
end
return P
|
Fix template merge order in loadall
|
Fix template merge order in loadall
|
Lua
|
mit
|
bazurbat/jagen
|
540c98bf8e1ea43dfa00446e7edf454aa9880a42
|
init.lua
|
init.lua
|
--[[
Copyright 2014 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local uv = require('uv')
return function (main, ...)
-- Inject the global process table
_G.process = require('process').globalProcess()
-- Seed Lua's RNG
do
local math = require('math')
local os = require('os')
math.randomseed(os.time())
end
-- Load Resolver
do
local dns = require('dns')
dns.loadResolver()
end
-- EPIPE ignore
do
if jit.os ~= 'Windows' then
local sig = uv.new_signal()
uv.signal_start(sig, 'sigpipe')
uv.unref(sig)
end
end
local args = {...}
local success, err = xpcall(function ()
-- Call the main app
main(unpack(args))
-- Start the event loop
uv.run()
end, function(err)
require('hooks'):emit('process.uncaughtException',err)
return debug.traceback(err)
end)
if success then
-- Allow actions to run at process exit.
require('hooks'):emit('process.exit')
uv.run()
else
_G.process.exitCode = -1
require('pretty-print').stderr:write("Uncaught exception:\n" .. err .. "\n")
end
-- When the loop exits, close all unclosed uv handles (flushing any streams found).
uv.walk(function (handle)
if handle then
local function close()
if not handle:is_closing() then handle:close() end
end
if handle.shutdown then
handle:shutdown(close)
else
close()
end
end
end)
uv.run()
-- Send the exitCode to luvi to return from C's main.
return _G.process.exitCode
end
|
--[[
Copyright 2014 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local uv = require('uv')
return function (main, ...)
-- Inject the global process table
_G.process = require('process').globalProcess()
-- Seed Lua's RNG
do
local math = require('math')
local os = require('os')
math.randomseed(os.time())
end
-- Load Resolver
do
local dns = require('dns')
dns.loadResolver()
end
-- EPIPE ignore
do
if jit.os ~= 'Windows' then
local sig = uv.new_signal()
uv.signal_start(sig, 'sigpipe')
uv.unref(sig)
end
end
local args = {...}
local success, err = xpcall(function ()
-- Call the main app
main(unpack(args))
-- Start the event loop
uv.run()
end, function(err)
require('hooks'):emit('process.uncaughtException',err)
return debug.traceback(err)
end)
if success then
-- Allow actions to run at process exit.
require('hooks'):emit('process.exit')
uv.run()
else
_G.process.exitCode = -1
require('pretty-print').stderr:write("Uncaught exception:\n" .. err .. "\n")
end
local function isFileHandle(handle, name, fd)
return _G.process[name].handle == handle and uv.guess_handle(fd) == 'file'
end
local function isStdioFileHandle(handle)
return isFileHandle(handle, 'stdin', 0) or isFileHandle(handle, 'stdout', 1) or isFileHandle(handle, 'stderr', 2)
end
-- When the loop exits, close all unclosed uv handles (flushing any streams found).
uv.walk(function (handle)
if handle then
local function close()
if not handle:is_closing() then handle:close() end
end
-- The isStdioFileHandle check is a hacky way to avoid an abort when a stdio handle is a pipe to a file
-- TODO: Fix this in a better way, see https://github.com/luvit/luvit/issues/1094
if handle.shutdown and not isStdioFileHandle(handle) then
handle:shutdown(close)
else
close()
end
end
end)
uv.run()
-- Send the exitCode to luvi to return from C's main.
return _G.process.exitCode
end
|
Fix abort when redirecting stdout/stderr to file
|
Fix abort when redirecting stdout/stderr to file
This is a hacky band-aid fix for a bigger problem that needs a more
comprehensive solution. See https://github.com/luvit/luvit/issues/1094
Closes #1083, does not affect #1023
|
Lua
|
apache-2.0
|
luvit/luvit,zhaozg/luvit,luvit/luvit,zhaozg/luvit
|
f9ebc2cb029b878477a10de480ce6432a5a1a1f9
|
applications/luci-samba/luasrc/model/cbi/samba.lua
|
applications/luci-samba/luasrc/model/cbi/samba.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("samba")
s = m:section(TypedSection, "samba", "Samba")
s.anonymous = true
s:option(Value, "name")
s:option(Value, "description")
s:option(Value, "workgroup")
s:option(Flag, "homes")
s = m:section(TypedSection, "sambashare")
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "name", translate("name"))
s:option(Value, "path").titleref = luci.dispatcher.build_url("admin", "system", "fstab")
s:option(Value, "users").rmempty = true
ro = s:option(Flag, "read_only")
ro.enabled = "yes"
ro.disabled = "no"
go = s:option(Flag, "guest_ok")
go.enabled = "yes"
go.disabled = "no"
cm = s:option(Value, "create_mask")
cm.rmempty = true
cm.size = 4
dm = s:option(Value, "dir_mask")
dm.rmempty = true
dm.size = 4
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("samba")
s = m:section(TypedSection, "samba", "Samba")
s.anonymous = true
s:option(Value, "name")
s:option(Value, "description")
s:option(Value, "workgroup")
s:option(Flag, "homes")
s = m:section(TypedSection, "sambashare")
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "name", translate("name"))
s:option(Value, "path").titleref = luci.dispatcher.build_url("admin", "system", "fstab")
s:option(Value, "users").rmempty = true
ro = s:option(Flag, "read_only")
ro.rmempty = false
ro.enabled = "yes"
ro.disabled = "no"
go = s:option(Flag, "guest_ok")
go.rmempty = false
go.enabled = "yes"
go.disabled = "no"
cm = s:option(Value, "create_mask")
cm.rmempty = true
cm.size = 4
dm = s:option(Value, "dir_mask")
dm.rmempty = true
dm.size = 4
return m
|
Fix samba "read only" and "guest ok" settings not applied correctly.
|
Fix samba "read only" and "guest ok" settings not applied correctly.
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@3972 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
ch3n2k/luci,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,freifunk-gluon/luci,Canaan-Creative/luci,yeewang/openwrt-luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,stephank/luci,alxhh/piratenluci,8devices/carambola2-luci,Flexibity/luci,stephank/luci,saraedum/luci-packages-old,projectbismark/luci-bismark,stephank/luci,alxhh/piratenluci,zwhfly/openwrt-luci,gwlim/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,Flexibity/luci,gwlim/luci,projectbismark/luci-bismark,Flexibity/luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,8devices/carambola2-luci,saraedum/luci-packages-old,vhpham80/luci,jschmidlapp/luci,Flexibity/luci,alxhh/piratenluci,Flexibity/luci,8devices/carambola2-luci,8devices/carambola2-luci,alxhh/piratenluci,phi-psi/luci,jschmidlapp/luci,projectbismark/luci-bismark,vhpham80/luci,yeewang/openwrt-luci,jschmidlapp/luci,yeewang/openwrt-luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,alxhh/piratenluci,ch3n2k/luci,ThingMesh/openwrt-luci,alxhh/piratenluci,ThingMesh/openwrt-luci,jschmidlapp/luci,projectbismark/luci-bismark,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,phi-psi/luci,Flexibity/luci,phi-psi/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,gwlim/luci,8devices/carambola2-luci,ch3n2k/luci,Flexibity/luci,jschmidlapp/luci,saraedum/luci-packages-old,yeewang/openwrt-luci,stephank/luci,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,Canaan-Creative/luci,freifunk-gluon/luci,gwlim/luci,phi-psi/luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,Canaan-Creative/luci,phi-psi/luci,jschmidlapp/luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,freifunk-gluon/luci,gwlim/luci,vhpham80/luci,ch3n2k/luci,ch3n2k/luci,stephank/luci,eugenesan/openwrt-luci,alxhh/piratenluci,freifunk-gluon/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,Canaan-Creative/luci,ch3n2k/luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,eugenesan/openwrt-luci,phi-psi/luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,vhpham80/luci,vhpham80/luci,stephank/luci,phi-psi/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,yeewang/openwrt-luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,jschmidlapp/luci,saraedum/luci-packages-old,freifunk-gluon/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,eugenesan/openwrt-luci,vhpham80/luci,Canaan-Creative/luci,projectbismark/luci-bismark,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,freifunk-gluon/luci
|
736c1751ded2e350984db79a769c74b7fa95ad37
|
MMOCoreORB/bin/scripts/object/tangible/wearables/dress/dress_s35.lua
|
MMOCoreORB/bin/scripts/object/tangible/wearables/dress/dress_s35.lua
|
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_wearables_dress_dress_s35 = object_tangible_wearables_dress_shared_dress_s35:new {
playerRaces = { "object/creature/player/bothan_female.iff",
"object/creature/player/human_female.iff",
"object/creature/player/moncal_female.iff",
"object/creature/player/rodian_female.iff",
"object/creature/player/sullustan_female.iff",
"object/creature/player/trandoshan_female.iff",
"object/creature/player/twilek_female.iff",
"object/creature/player/zabrak_female.iff",
"object/mobile/vendor/aqualish_female.iff",
"object/mobile/vendor/bith_female.iff",
"object/mobile/vendor/bothan_female.iff",
"object/mobile/vendor/human_female.iff",
"object/mobile/vendor/moncal_female.iff",
"object/mobile/vendor/rodian_female.iff",
"object/mobile/vendor/sullustan_female.iff",
"object/mobile/vendor/trandoshan_female.iff",
"object/mobile/vendor/twilek_female.iff",
"object/mobile/vendor/zabrak_female.iff" },
numberExperimentalProperties = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
experimentalProperties = {"XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX"},
experimentalWeights = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
experimentalGroupTitles = {"null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null"},
experimentalSubGroupTitles = {"null", "null", "hitpoints", "mod_idx_one", "mod_val_one", "mod_idx_two", "mod_val_two", "mod_idx_three", "mod_val_three", "mod_idx_four", "mod_val_four", "mod_idx_five", "mod_val_five", "mod_idx_six", "mod_val_six"},
experimentalMin = {0, 0, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
experimentalMax = {0, 0, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
experimentalPrecision = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
experimentalCombineType = {0, 0, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
}
ObjectTemplates:addTemplate(object_tangible_wearables_dress_dress_s35, "object/tangible/wearables/dress/dress_s35.iff")
|
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_wearables_dress_dress_s35 = object_tangible_wearables_dress_shared_dress_s35:new {
playerRaces = { "object/creature/player/bothan_female.iff",
"object/creature/player/human_female.iff",
"object/creature/player/moncal_female.iff",
"object/creature/player/rodian_female.iff",
"object/creature/player/sullustan_female.iff",
"object/creature/player/trandoshan_female.iff",
"object/creature/player/twilek_female.iff",
"object/creature/player/zabrak_female.iff",
"object/mobile/vendor/aqualish_female.iff",
"object/mobile/vendor/bith_female.iff",
"object/mobile/vendor/bothan_female.iff",
"object/mobile/vendor/human_female.iff",
"object/mobile/vendor/moncal_female.iff",
"object/mobile/vendor/rodian_female.iff",
"object/mobile/vendor/sullustan_female.iff",
"object/mobile/vendor/trandoshan_female.iff",
"object/mobile/vendor/twilek_female.iff",
"object/mobile/vendor/zabrak_female.iff" },
numberExperimentalProperties = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
experimentalProperties = {"XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX", "XX"},
experimentalWeights = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
experimentalGroupTitles = {"null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null"},
experimentalSubGroupTitles = {"null", "null", "sockets", "hitpoints", "mod_idx_one", "mod_val_one", "mod_idx_two", "mod_val_two", "mod_idx_three", "mod_val_three", "mod_idx_four", "mod_val_four", "mod_idx_five", "mod_val_five", "mod_idx_six", "mod_val_six"},
experimentalMin = {0, 0, 0, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
experimentalMax = {0, 0, 0, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
experimentalPrecision = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
experimentalCombineType = {0, 0, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
}
ObjectTemplates:addTemplate(object_tangible_wearables_dress_dress_s35, "object/tangible/wearables/dress/dress_s35.iff")
|
[fixed] Mantis 4593: Grand Ball Gown crafted sockets
|
[fixed] Mantis 4593: Grand Ball Gown crafted sockets
Change-Id: I14495aa08c54203c2585a7d6e6ef39813c1d8066
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo
|
7331548909f8e6ca6aaaff3d0672b6d1ea631203
|
lib/wax-scripts/luaClass.lua
|
lib/wax-scripts/luaClass.lua
|
Object = {
super = nil,
init = function(self, ...)
local instance = {}
instance.super = self
instance.__index = function(self, key) return self.super[key] end
setmetatable(instance, instance)
-- add all class meta functions to instance (I don't like how this is implemented!)
for name, func in pairs(self) do
if name:find("^__") then instance[name] = func end
end
-- If an init method is specified, then call it (It was renamed to __instanceInit in luaClass)
if instance.__instanceInit then instance:__instanceInit(...) end
return instance
end,
}
function luaClass(options)
local className = options[1]
local superclass = options[2] or Object
if type(superclass) == "string" then superclass = _G[superclass] end -- allow strings for superclass
local class = superclass:init()
class.className = className
-- setup the files environment to look in the class heirarchy and then the global scope
local _M = setmetatable({}, {
__newindex = function(self, key, value)
if key == "init" then key = "__instanceInit" end -- so we match the obj-c style
class[key] = value
end,
__index = function(self, key)
return class[key] or _G[key]
end,
})
_G[className] = class
package.loaded[className] = class
setfenv(2, _M)
return class
end
|
Object = {
super = nil,
subclass = function(self, ...)
local subclass = {}
subclass.super = self
subclass.__index = function(self, key) return self.super[key] end
setmetatable(subclass, subclass)
-- add all class meta functions to instance (I don't like how this is implemented!)
for name, func in pairs(self) do
if name:find("^__") then subclass[name] = func end
end
return subclass
end,
init = function(self, ...)
local instance = {}
instance.super = self
instance.__index = function(self, key) return self.super[key] end
setmetatable(instance, instance)
-- add all class meta functions to instance (I don't like how this is implemented!)
for name, func in pairs(self) do
if name:find("^__") then instance[name] = func end
end
-- If an init method is specified, then call it (It was renamed to __instanceInit in luaClass)
if instance.__instanceInit then instance:__instanceInit(...) end
return instance
end,
}
function luaClass(options)
local className = options[1]
local superclass = options[2] or Object
if type(superclass) == "string" then superclass = _G[superclass] end -- allow strings for superclass
local class = superclass:subclass()
class.className = className
-- setup the files environment to look in the class heirarchy and then the global scope
local _M = setmetatable({}, {
__newindex = function(self, key, value)
if key == "init" then key = "__instanceInit" end -- so we match the obj-c style
class[key] = value
end,
__index = function(self, key)
return class[key] or _G[key]
end,
})
_G[className] = class
package.loaded[className] = class
setfenv(2, _M)
return class
end
|
fixed luaClass inheritence bug.
|
fixed luaClass inheritence bug.
|
Lua
|
mit
|
a20251313/wax,LiJingBiao/wax,1yvT0s/wax,hj3938/wax,qskycolor/wax,1yvT0s/wax,marinehero/wax,BITA-app/wax,dxd214/wax,dxd214/wax,BITA-app/wax,a20251313/wax,taobao-idev/wax,taobao-idev/wax,taobao-idev/wax,RoyZeng/wax,RoyZeng/wax,felipejfc/n-wax,felipejfc/n-wax,marinehero/wax,FlashHand/wax,qskycolor/wax,hj3938/wax,dxd214/wax,chiyun1/wax,chiyun1/wax,LiJingBiao/wax,RoyZeng/wax,taobao-idev/wax,1yvT0s/wax,LiJingBiao/wax,qskycolor/wax,marinehero/wax,LiJingBiao/wax,probablycorey/wax,probablycorey/wax,a20251313/wax,FlashHand/wax,chiyun1/wax,a20251313/wax,FlashHand/wax,qskycolor/wax,chiyun1/wax,BITA-app/wax,dxd214/wax,RoyZeng/wax,felipejfc/n-wax,FlashHand/wax,1yvT0s/wax,probablycorey/wax,probablycorey/wax,hj3938/wax,BITA-app/wax,hj3938/wax,felipejfc/n-wax,marinehero/wax
|
c6fa23c4e5a563a23d5754d7416edf0ae39cfdc3
|
test/inspect_namespace_test.lua
|
test/inspect_namespace_test.lua
|
--[[------------------------------------------------------
dub.Inspector test
------------------
Test introspective operations with the 'namespace' group
of classes.
--]]------------------------------------------------------
require 'lubyk'
local should = test.Suite('dub.Inspector - namespace')
local base = lk.dir()
local ins
function should.setup()
dub.warn = function() end
if not ins then
ins = dub.Inspector {
INPUT = {
base .. '/fixtures/namespace',
},
doc_dir = base .. '/tmp',
}
end
end
function should.teardown()
dub.warn = dub.warn_method
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
lk.insertSorted(res, string.match(h, '/([^/]+/[^/]+)$'))
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
table.insert(res, func:fullcname())
end
assertValueEqual({
'addTwoOut',
'Nem::addTwo',
}, res)
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
lk.insertSorted(res, const)
end
assertValueEqual({
'One',
'Three',
'Two',
}, res)
end
test.all()
|
--[[------------------------------------------------------
dub.Inspector test
------------------
Test introspective operations with the 'namespace' group
of classes.
--]]------------------------------------------------------
require 'lubyk'
local should = test.Suite('dub.Inspector - namespace')
local base = lk.dir()
local ins
function should.setup()
dub.warn = function() end
if not ins then
ins = dub.Inspector {
INPUT = {
base .. '/fixtures/namespace',
},
doc_dir = base .. '/tmp',
}
end
end
function should.teardown()
dub.warn = dub.warn_method
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
lk.insertSorted(res, string.match(h, '/([^/]+/[^/]+)$'))
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
lk.insertSorted(res, func:fullcname())
end
assertValueEqual({
'Nem::addTwo',
'Nem::customGlobal',
'addTwoOut',
'customGlobalOut',
}, res)
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
lk.insertSorted(res, const)
end
assertValueEqual({
'One',
'Three',
'Two',
}, res)
end
test.all()
|
Fixed test
|
Fixed test
|
Lua
|
mit
|
Laeeth/dub,lubyk/dub,Laeeth/dub,lubyk/dub
|
8dae132b1c788eb9011ab7a906c1123337305f73
|
openwrt/package/linkmeter/luasrc/model/cbi/linkmeter/alarms.lua
|
openwrt/package/linkmeter/luasrc/model/cbi/linkmeter/alarms.lua
|
require "luci.fs"
require "luci.sys"
require "luci.util"
require "lmclient"
local SCRIPT_PATH = "/usr/share/linkmeter/alarm-"
local function isexec_cfgvalue(self)
return luci.fs.access(SCRIPT_PATH .. self.fname, "x") and "1"
end
local function isexec_write(self, section, value)
local curmode = luci.fs.stat(SCRIPT_PATH .. self.fname).modedec
value = value == "1" and "755" or "644"
if value ~= mode then
luci.fs.chmod(SCRIPT_PATH .. self.fname, value)
end
end
local function script_cfgvalue(self)
return luci.fs.readfile(SCRIPT_PATH .. self.fname) or ""
end
local function script_write(self, section, value)
-- BRY: Note to self. If you make one big form out of the page,
-- value becomes an indexed table with a string entry for each textbox
local old = self:cfgvalue()
value = value:gsub("\r\n", "\n")
if old ~= value then
luci.fs.writefile(SCRIPT_PATH .. self.fname, value)
end
end
local scriptitems = {
{ fname = "all", title = "All Alarm Script", desc =
[[This script is run when HeaterMeter signals any alarm before any
specific script below is executed. If the 'All' script returns non-zero
the alarm-specific script will not be run.
<a href="https://github.com/CapnBry/HeaterMeter/wiki/Alarm-Script-Recipes"
target="wiki">
Example scripts</a>
can be found in the HeaterMeter wiki.
]] },
}
--local lm = LmClient()
for i = 0, 3 do
local pname = "" -- lm:query("$LMGT,pn"..i)
if pname ~= "" then pname = " (" .. pname .. ")" end
for _, j in pairs({ "Low", "High" }) do
scriptitems[#scriptitems+1] = { fname = i..j:sub(1,1),
title = "Probe " .. i .. " " .. j .. pname }
end
end
--lm:close()
local retVal = {}
for i, item in pairs(scriptitems) do
local f = SimpleForm(item.fname, item.title, item.desc)
local fld = f:field(Flag, "isexec", "Execute on alarm")
fld.fname = item.fname
fld.default = "0"
fld.rmempty = nil
fld.cfgvalue = isexec_cfgvalue
fld.write = isexec_write
fld = f:field(TextValue, "script")
fld.fname = item.fname
fld.rmempty = nil
fld.optional = true
fld.rows = 10
fld.cfgvalue = script_cfgvalue
fld.write = script_write
retVal[#retVal+1] = f
end -- for file
return unpack(retVal)
|
require "luci.fs"
require "luci.sys"
require "lmclient"
local SCRIPT_PATH = "/usr/share/linkmeter/alarm-"
local function isexec_cfgvalue(self)
return luci.fs.access(SCRIPT_PATH .. self.config, "x") and "1"
end
local function isexec_write(self, section, value)
self.value = value
local curmode = luci.fs.stat(SCRIPT_PATH .. self.config)
value = value == "1" and 755 or 644
if curmode and curmode.modedec ~= value then
luci.fs.chmod(SCRIPT_PATH .. self.config, value)
end
end
local function script_cfgvalue(self)
return luci.fs.readfile(SCRIPT_PATH .. self.config) or ""
end
local function script_write(self, section, value)
-- BRY: Note to self. If you make one big form out of the page,
-- value becomes an indexed table with a string entry for each textbox
local old = self:cfgvalue()
value = value:gsub("\r\n", "\n")
if old ~= value then
luci.fs.writefile(SCRIPT_PATH .. self.config, value)
-- If there was no file previously re-call the isexec handler
-- as it executes before this handler and there was not a file then
if old == "" then self.isexec:write(section, self.isexec.value) end
end
end
local scriptitems = {
{ fname = "all", title = "All Alarm Script", desc =
[[This script is run when HeaterMeter signals any alarm before any
specific script below is executed. If the 'All' script returns non-zero
the alarm-specific script will not be run.
<a href="https://github.com/CapnBry/HeaterMeter/wiki/Alarm-Script-Recipes"
target="wiki">
Example scripts</a>
can be found in the HeaterMeter wiki.
]] },
}
--local lm = LmClient()
for i = 0, 3 do
local pname = "" -- lm:query("$LMGT,pn"..i)
if pname ~= "" then pname = " (" .. pname .. ")" end
for _, j in pairs({ "Low", "High" }) do
scriptitems[#scriptitems+1] = { fname = i..j:sub(1,1),
title = "Probe " .. i .. " " .. j .. pname }
end
end
--lm:close()
local retVal = {}
for i, item in pairs(scriptitems) do
local f = SimpleForm(item.fname, item.title, item.desc)
local isexec = f:field(Flag, "isexec", "Execute on alarm")
isexec.default = "0"
isexec.rmempty = nil
isexec.cfgvalue = isexec_cfgvalue
isexec.write = isexec_write
local fld = f:field(TextValue, "script")
fld.isexec = isexec
fld.rmempty = nil
fld.optional = true
fld.rows = 10
fld.cfgvalue = script_cfgvalue
fld.write = script_write
retVal[#retVal+1] = f
end -- for file
return unpack(retVal)
|
[lm] Fix writing of alarm script when no script existed previously, also fix mode write always writing
|
[lm] Fix writing of alarm script when no script existed previously, also fix mode write always writing
|
Lua
|
mit
|
shmick/HeaterMeter,dwright134/HeaterMeter,dwright134/HeaterMeter,dwright134/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter,dwright134/HeaterMeter,CapnBry/HeaterMeter,kdakers80/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,kdakers80/HeaterMeter,kdakers80/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,dwright134/HeaterMeter,shmick/HeaterMeter,shmick/HeaterMeter,kdakers80/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,kdakers80/HeaterMeter,CapnBry/HeaterMeter,kdakers80/HeaterMeter
|
da0190afc460749a368cc5c5948ec51664f4129a
|
modules/admin-full/luasrc/model/cbi/admin_network/dhcp.lua
|
modules/admin-full/luasrc/model/cbi/admin_network/dhcp.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
require("luci.model.uci")
require("luci.util")
m = Map("dhcp", "DHCP")
s = m:section(TypedSection, "dhcp", "")
s.addremove = true
s.anonymous = true
iface = s:option(ListValue, "interface", translate("Interface"))
luci.tools.webadmin.cbi_add_networks(iface)
local uci = luci.model.uci.cursor()
uci:foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
iface.default = iface.default or section[".name"]
s:depends("interface", section[".name"])
end
end)
uci:foreach("network", "alias",
function (section)
iface:value(section[".name"])
s:depends("interface", section[".name"])
end)
s:option(Value, "start", translate("Start")).rmempty = true
s:option(Value, "limit", translate("Limit")).rmempty = true
s:option(Value, "leasetime").rmempty = true
local dd = s:option(Flag, "dynamicdhcp")
dd.rmempty = false
function dd.cfgvalue(self, section)
return Flag.cfgvalue(self, section) or "1"
end
s:option(Value, "name", translate("Name")).optional = true
ignore = s:option(Flag, "ignore")
ignore.optional = true
s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask")).optional = true
s:option(Flag, "force").optional = true
s:option(DynamicList, "dhcp_option").optional = true
for i, n in ipairs(s.children) do
if n ~= iface and n ~= ignore then
n:depends("ignore", "")
end
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
require("luci.model.uci")
require("luci.util")
m = Map("dhcp",
translate("Dynamic <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr>"),
translate("With <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr> network " ..
"members can automatically receive their network settings (<abbr title=" ..
"\"Internet Protocol\">IP</abbr>-address, netmask, <abbr title=\"Domain Name " ..
"System\">DNS</abbr>-server, ...)."))
s = m:section(TypedSection, "dhcp", "")
s.addremove = true
s.anonymous = true
iface = s:option(ListValue, "interface", translate("Interface"))
luci.tools.webadmin.cbi_add_networks(iface)
local uci = luci.model.uci.cursor()
uci:foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
iface.default = iface.default or section[".name"]
s:depends("interface", section[".name"])
end
end)
uci:foreach("network", "alias",
function (section)
iface:value(section[".name"])
s:depends("interface", section[".name"])
end)
s:option(Value, "start", translate("Start")).rmempty = true
s:option(Value, "limit", translate("Limit")).rmempty = true
s:option(Value, "leasetime", translate("Leasetime")).rmempty = true
local dd = s:option(Flag, "dynamicdhcp", translate("dynamic"))
dd.rmempty = false
function dd.cfgvalue(self, section)
return Flag.cfgvalue(self, section) or "1"
end
s:option(Value, "name", translate("Name")).optional = true
ignore = s:option(Flag, "ignore",
translate("Ignore interface"),
translate("disable <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr> for " ..
"this interface"))
ignore.optional = true
s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask")).optional = true
s:option(Flag, "force", translate("Force")).optional = true
s:option(DynamicList, "dhcp_option", translate("DHCP-Options")).optional = true
for i, n in ipairs(s.children) do
if n ~= iface and n ~= ignore then
n:depends("ignore", "")
end
end
return m
|
modules/admin-full: fix dhcp page
|
modules/admin-full: fix dhcp page
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5465 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
zwhfly/openwrt-luci,jschmidlapp/luci,Flexibity/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,projectbismark/luci-bismark,freifunk-gluon/luci,Canaan-Creative/luci,freifunk-gluon/luci,8devices/carambola2-luci,jschmidlapp/luci,vhpham80/luci,gwlim/luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,Flexibity/luci,gwlim/luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,vhpham80/luci,projectbismark/luci-bismark,gwlim/luci,stephank/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,zwhfly/openwrt-luci,gwlim/luci,projectbismark/luci-bismark,vhpham80/luci,stephank/luci,ch3n2k/luci,ch3n2k/luci,freifunk-gluon/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,saraedum/luci-packages-old,yeewang/openwrt-luci,phi-psi/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,projectbismark/luci-bismark,Canaan-Creative/luci,phi-psi/luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,Flexibity/luci,Canaan-Creative/luci,Flexibity/luci,phi-psi/luci,gwlim/luci,ThingMesh/openwrt-luci,vhpham80/luci,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,jschmidlapp/luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,stephank/luci,freifunk-gluon/luci,jschmidlapp/luci,freifunk-gluon/luci,freifunk-gluon/luci,saraedum/luci-packages-old,jschmidlapp/luci,jschmidlapp/luci,phi-psi/luci,Canaan-Creative/luci,8devices/carambola2-luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,stephank/luci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,ThingMesh/openwrt-luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,eugenesan/openwrt-luci,stephank/luci,Flexibity/luci,ch3n2k/luci,Flexibity/luci,zwhfly/openwrt-luci,jschmidlapp/luci,stephank/luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,8devices/carambola2-luci,8devices/carambola2-luci,eugenesan/openwrt-luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,yeewang/openwrt-luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,ch3n2k/luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,Flexibity/luci,gwlim/luci,ch3n2k/luci,phi-psi/luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,ThingMesh/openwrt-luci,gwlim/luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,8devices/carambola2-luci,yeewang/openwrt-luci,ch3n2k/luci
|
c34347784a325a338948578ee8344926c34b2459
|
applications/luci-polipo/luasrc/model/cbi/polipo.lua
|
applications/luci-polipo/luasrc/model/cbi/polipo.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Aleksandar Krsteski <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("polipo")
-- General section
s = m:section(NamedSection, "general", "polipo")
-- General settings
s:option(Flag, "enabled", translate("enable"))
s:option(Value, "proxyAddress")
s:option(Value, "proxyPort").optional = true
s:option(DynamicList, "allowedClients")
s:option(Flag, "logSyslog")
s:option(Value, "logFacility"):depends("logSyslog", "1")
v = s:option(Value, "logFile")
v:depends("logSyslog", "")
v.rmempty = true
s:option(Value, "chunkHighMark")
-- DNS and proxy settings
s:option(Value, "dnsNameServer").optional = true
s:option(Value, "parentProxy").optional = true
s:option(Value, "parentAuthCredentials").optional = true
l = s:option(ListValue, "dnsQueryIPv6")
l.optional = true
l.default = "happily"
l:value("")
l:value("true")
l:value("reluctantly")
l:value("happily")
l:value("false")
l = s:option(ListValue, "dnsUseGethostbyname")
l.optional = true
l.default = "reluctantly"
l:value("")
l:value("true")
l:value("reluctantly")
l:value("happily")
l:value("false")
-- Dsik cache section
s = m:section(NamedSection, "cache", "polipo")
-- Dsik cache settings
s:option(Value, "diskCacheRoot").rmempty = true
s:option(Flag, "cacheIsShared")
s:option(Value, "diskCacheTruncateSize").optional = true
s:option(Value, "diskCacheTruncateTime").optional = true
s:option(Value, "diskCacheUnlinkTime").optional = true
-- Poor man's multiplexing section
s = m:section(NamedSection, "pmm", "polipo")
s:option(Value, "pmmSize").rmempty = true
s:option(Value, "pmmFirstSize").optional = true
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Aleksandar Krsteski <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("polipo", translate("Polipo"),
translate("Polipo is a small and fast caching web proxy."))
-- General section
s = m:section(NamedSection, "general", "polipo", translate("Proxy"))
s:tab("general", translate("General Settings"))
s:tab("dns", translate("DNS and Query Settings"))
s:tab("proxy", translate("Parent Proxy"))
s:tab("logging", translate("Logging and RAM"))
-- General settings
s:taboption("general", Flag, "enabled", translate("enable"))
o = s:taboption("general", Value, "proxyAddress", translate("Listen address"),
translate("The interface on which Polipo will listen. To listen on all " ..
"interfaces use 0.0.0.0 or :: (IPv6)."))
o.placeholder = "0.0.0.0"
o.datatype = "ipaddr"
o = s:taboption("general", Value, "proxyPort", translate("Listen port"),
translate("Port on which Polipo will listen"))
o.optional = true
o.placeholder = "8123"
o.datatype = "port"
o = s:taboption("general", DynamicList, "allowedClients",
translate("Allowed clients"),
translate("When listen address is set to 0.0.0.0 or :: (IPv6), you must " ..
"list clients that are allowed to connect. The format is IP address " ..
"or network address (192.168.1.123, 192.168.1.0/24, " ..
"2001:660:116::/48 (IPv6))"))
o.datatype = "ipaddr"
o.placeholder = "0.0.0.0/0"
-- DNS settings
dns = s:taboption("dns", Value, "dnsNameServer", translate("DNS server address"),
translate("Set the DNS server address to use, if you want Polipo to use " ..
"different DNS server than the host system."))
dns.optional = true
dns.datatype = "ipaddr"
l = s:taboption("dns", ListValue, "dnsQueryIPv6",
translate("Query DNS for IPv6"))
l.default = "happily"
l:value("true", translate("Query only IPv6"))
l:value("happily", translate("Query IPv4 and IPv6, prefer IPv6"))
l:value("reluctantly", translate("Query IPv4 and IPv6, prefer IPv4"))
l:value("false", translate("Do not query IPv6"))
l = s:taboption("dns", ListValue, "dnsUseGethostbyname",
translate("Query DNS by hostname"))
l.default = "reluctantly"
l:value("true", translate("Always use system DNS resolver"))
l:value("happily",
translate("Query DNS directly, for unknown hosts fall back " ..
"to system resolver"))
l:value("reluctantly",
translate("Query DNS directly, fallback to system resolver"))
l:value("false", translate("Never use system DNS resolver"))
-- Proxy settings
o = s:taboption("proxy", Value, "parentProxy",
translate("Parent proxy address"),
translate("Parent proxy address (in host:port format), to which Polipo " ..
"will forward the requests."))
o.optional = true
o.datatype = "ipaddr"
o = s:taboption("proxy", Value, "parentAuthCredentials",
translate("Parent proxy authentication"),
translate("Basic HTTP authentication supported. Provide username and " ..
"password in username:password format."))
o.optional = true
o.placeholder = "username:password"
-- Logging
s:taboption("logging", Flag, "logSyslog", translate("Log to syslog"))
s:taboption("logging", Value, "logFacility",
translate("Syslog facility")):depends("logSyslog", "1")
v = s:taboption("logging", Value, "logFile",
translate("Log file location"),
translate("Use of external storage device is recommended, because the " ..
"log file is written frequently and can grow considerably."))
v:depends("logSyslog", "")
v.rmempty = true
o = s:taboption("logging", Value, "chunkHighMark",
translate("In RAM cache size (in bytes)"),
translate("How much RAM should Polipo use for its cache."))
o.datatype = "uinteger"
-- Disk cache section
s = m:section(NamedSection, "cache", "polipo", translate("On-Disk Cache"))
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
-- Disk cache settings
s:taboption("general", Value, "diskCacheRoot", translate("Disk cache location"),
translate("Location where polipo will cache files permanently. Use of " ..
"external storage devices is recommended, because the cache can " ..
"grow considerably. Leave it empty to disable on-disk " ..
"cache.")).rmempty = true
s:taboption("general", Flag, "cacheIsShared", translate("Shared cache"),
translate("Enable if cache (proxy) is shared by multiple users."))
o = s:taboption("advanced", Value, "diskCacheTruncateSize",
translate("Truncate cache files size (in bytes)"),
translate("Size to which cached files should be truncated"))
o.optional = true
o.placeholder = "1048576"
o.datatype = "uinteger"
o = s:taboption("advanced", Value, "diskCacheTruncateTime",
translate("Truncate cache files time"),
translate("Time after which cached files will be truncated"))
o.optional = true
o.placeholder = "4d12h"
o = s:taboption("advanced", Value, "diskCacheUnlinkTime",
translate("Delete cache files time"),
translate("Time after which cached files will be deleted"))
o.optional = true
o.placeholder = "32d"
-- Poor man's multiplexing section
s = m:section(NamedSection, "pmm", "polipo",
translate("Poor Man's Multiplexing"),
translate("Poor Man's Multiplexing (PMM) is a technique that simulates " ..
"multiplexing by requesting an instance in multiple segments. It " ..
"tries to lower the latency caused by the weakness of HTTP " ..
"protocol. NOTE: some sites may not work with PMM enabled."))
s:option(Value, "pmmSize", translate("PMM segments size (in bytes)"),
translate("To enable PMM, PMM segment size must be set to some " ..
"positive value.")).rmempty = true
s:option(Value, "pmmFirstSize", translate("First PMM segment size (in bytes)"),
translate("Size of the first PMM segment. If not defined, it defaults " ..
"to twice the PMM segment size.")).rmempty = true
return m
|
applications/luci-polipo: fix polipo page
|
applications/luci-polipo: fix polipo page
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@6613 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
Flexibity/luci,saraedum/luci-packages-old,projectbismark/luci-bismark,gwlim/luci,vhpham80/luci,Canaan-Creative/luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,gwlim/luci,Canaan-Creative/luci,jschmidlapp/luci,jschmidlapp/luci,ch3n2k/luci,jschmidlapp/luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,zwhfly/openwrt-luci,freifunk-gluon/luci,eugenesan/openwrt-luci,stephank/luci,projectbismark/luci-bismark,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,saraedum/luci-packages-old,saraedum/luci-packages-old,yeewang/openwrt-luci,Canaan-Creative/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,phi-psi/luci,vhpham80/luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,gwlim/luci,Flexibity/luci,8devices/carambola2-luci,gwlim/luci,freifunk-gluon/luci,projectbismark/luci-bismark,yeewang/openwrt-luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,freifunk-gluon/luci,8devices/carambola2-luci,stephank/luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,Flexibity/luci,Canaan-Creative/luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,Flexibity/luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,Flexibity/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,freifunk-gluon/luci,Canaan-Creative/luci,gwlim/luci,yeewang/openwrt-luci,ch3n2k/luci,vhpham80/luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,ch3n2k/luci,projectbismark/luci-bismark,saraedum/luci-packages-old,8devices/carambola2-luci,eugenesan/openwrt-luci,phi-psi/luci,stephank/luci,freifunk-gluon/luci,vhpham80/luci,Flexibity/luci,ch3n2k/luci,stephank/luci,jschmidlapp/luci,gwlim/luci,jschmidlapp/luci,phi-psi/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,phi-psi/luci,Flexibity/luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,stephank/luci,Canaan-Creative/luci,jschmidlapp/luci,yeewang/openwrt-luci,projectbismark/luci-bismark,vhpham80/luci,projectbismark/luci-bismark,eugenesan/openwrt-luci,ch3n2k/luci,gwlim/luci,jschmidlapp/luci,phi-psi/luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,vhpham80/luci
|
c27ff03198521d7edcc28f35747065e60a0ee259
|
applications/luci-olsr/luasrc/model/cbi/olsr/olsrd.lua
|
applications/luci-olsr/luasrc/model/cbi/olsr/olsrd.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.fs")
m = Map("olsr", "OLSR")
s = m:section(NamedSection, "general", "olsr")
debug = s:option(ListValue, "DebugLevel")
for i=0, 9 do
debug:value(i)
end
ipv = s:option(ListValue, "IpVersion")
ipv:value("4", "IPv4")
ipv:value("6", "IPv6")
noint = s:option(Flag, "AllowNoInt")
noint.enabled = "yes"
noint.disabled = "no"
s:option(Value, "Pollrate")
tcr = s:option(ListValue, "TcRedundancy")
tcr:value("0", translate("olsr_general_tcredundancy_0"))
tcr:value("1", translate("olsr_general_tcredundancy_1"))
tcr:value("2", translate("olsr_general_tcredundancy_2"))
s:option(Value, "MprCoverage")
lql = s:option(ListValue, "LinkQualityLevel")
lql:value("0", translate("disable"))
lql:value("1", translate("olsr_general_linkqualitylevel_1"))
lql:value("2", translate("olsr_general_linkqualitylevel_2"))
lqfish = s:option(Flag, "LinkQualityFishEye")
s:option(Value, "LinkQualityWinSize")
s:option(Value, "LinkQualityDijkstraLimit")
hyst = s:option(Flag, "UseHysteresis")
hyst.enabled = "yes"
hyst.disabled = "no"
i = m:section(TypedSection, "Interface", translate("interfaces"))
i.anonymous = true
i.addremove = true
i.dynamic = true
network = i:option(ListValue, "Interface", translate("network"))
network:value("")
luci.model.uci.foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
network:value(section[".name"])
end
end)
i:option(Value, "HelloInterval")
i:option(Value, "HelloValidityTime")
i:option(Value, "TcInterval")
i:option(Value, "TcValidityTime")
i:option(Value, "MidInterval")
i:option(Value, "MidValidityTime")
i:option(Value, "HnaInterval")
i:option(Value, "HnaValidityTime")
p = m:section(TypedSection, "LoadPlugin")
p.addremove = true
p.dynamic = true
lib = p:option(ListValue, "Library", translate("library"))
lib:value("")
for k, v in pairs(luci.fs.dir("/usr/lib")) do
if v:sub(1, 6) == "olsrd_" then
lib:value(v)
end
end
for i, sect in ipairs({ "Hna4", "Hna6" }) do
hna = m:section(TypedSection, sect)
hna.addremove = true
hna.anonymous = true
net = hna:option(Value, "NetAddr")
msk = hna:option(Value, "Prefix")
end
ipc = m:section(NamedSection, "IpcConnect")
conns = ipc:option(Value, "MaxConnections")
conns.isInteger = true
nets = ipc:option(Value, "Net")
nets.optional = true
hosts = ipc:option(Value, "Host")
hosts.optional = true
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.fs")
m = Map("olsr", "OLSR")
s = m:section(NamedSection, "general", "olsr")
debug = s:option(ListValue, "DebugLevel")
for i=0, 9 do
debug:value(i)
end
ipv = s:option(ListValue, "IpVersion")
ipv:value("4", "IPv4")
ipv:value("6", "IPv6")
noint = s:option(Flag, "AllowNoInt")
noint.enabled = "yes"
noint.disabled = "no"
s:option(Value, "Pollrate")
tcr = s:option(ListValue, "TcRedundancy")
tcr:value("0", translate("olsr_general_tcredundancy_0"))
tcr:value("1", translate("olsr_general_tcredundancy_1"))
tcr:value("2", translate("olsr_general_tcredundancy_2"))
s:option(Value, "MprCoverage")
lql = s:option(ListValue, "LinkQualityLevel")
lql:value("0", translate("disable"))
lql:value("1", translate("olsr_general_linkqualitylevel_1"))
lql:value("2", translate("olsr_general_linkqualitylevel_2"))
lqfish = s:option(Flag, "LinkQualityFishEye")
s:option(Value, "LinkQualityWinSize")
s:option(Value, "LinkQualityDijkstraLimit")
hyst = s:option(Flag, "UseHysteresis")
hyst.enabled = "yes"
hyst.disabled = "no"
i = m:section(TypedSection, "Interface", translate("interfaces"))
i.anonymous = true
i.addremove = true
i.dynamic = true
network = i:option(ListValue, "Interface", translate("network"))
network:value("")
luci.model.uci.foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
if section.type and section.type == "bridge" then
network:value("br-"..section[".name"],section[".name"])
else
network:value(section[".name"])
end
end
end)
i:option(Value, "HelloInterval")
i:option(Value, "HelloValidityTime")
i:option(Value, "TcInterval")
i:option(Value, "TcValidityTime")
i:option(Value, "MidInterval")
i:option(Value, "MidValidityTime")
i:option(Value, "HnaInterval")
i:option(Value, "HnaValidityTime")
p = m:section(TypedSection, "LoadPlugin")
p.addremove = true
p.dynamic = true
lib = p:option(ListValue, "Library", translate("library"))
lib:value("")
for k, v in pairs(luci.fs.dir("/usr/lib")) do
if v:sub(1, 6) == "olsrd_" then
lib:value(v)
end
end
for i, sect in ipairs({ "Hna4", "Hna6" }) do
hna = m:section(TypedSection, sect)
hna.addremove = true
hna.anonymous = true
net = hna:option(Value, "NetAddr")
msk = hna:option(Value, "Prefix")
end
ipc = m:section(NamedSection, "IpcConnect")
conns = ipc:option(Value, "MaxConnections")
conns.isInteger = true
nets = ipc:option(Value, "Net")
nets.optional = true
hosts = ipc:option(Value, "Host")
hosts.optional = true
return m
|
* luci/olsr: fix names of interfaces with type bridge
|
* luci/olsr: fix names of interfaces with type bridge
|
Lua
|
apache-2.0
|
deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci
|
8caf31b0f831b01b267f2f5c1643ceaf8e9aba22
|
apicast/src/oauth.lua
|
apicast/src/oauth.lua
|
local router = require 'router'
local apicast_oauth = require 'oauth.apicast_oauth'
local keycloak = require 'oauth.keycloak'
local _M = {
_VERSION = '0.0.2'
}
function _M.new()
local oauth
if keycloak.configured then
oauth = keycloak.new()
else
oauth = apicast_oauth.new()
end
return oauth
end
function _M.router()
-- TODO: use configuration to customize urls
local r = router:new()
local oauth = _M.new()
r:get('/authorize', function() oauth:authorize() end)
r:post('/authorize', function() oauth:authorize() end)
-- TODO: only applies to apicast oauth...
r:post('/callback', function() oauth:callback() end)
r:get('/callback', function() oauth:callback() end)
r:post('/oauth/token', function() oauth:get_token() end)
return r
end
function _M.call(method, uri, ...)
local r = _M.router()
local f, params = r:resolve(method or ngx.req.get_method(),
uri or ngx.var.uri,
unpack(... or {}))
return f, params
end
return _M
|
local env = require 'resty.env'
local router = require 'router'
local apicast_oauth = require 'oauth.apicast_oauth'
local keycloak = require 'oauth.keycloak'
local oauth
local _M = {
_VERSION = '0.0.2'
}
function _M.new()
local keycloak_configured = env.get('RHSSO_ENDPOINT')
if keycloak_configured then
oauth = keycloak
oauth.init(keycloak_configured)
else
oauth = apicast_oauth
end
return oauth.new()
end
function _M.router()
-- TODO: use configuration to customize urls
local r = router:new()
oauth = _M.new()
r:get('/authorize', function() oauth:authorize() end)
r:post('/authorize', function() oauth:authorize() end)
-- TODO: only applies to apicast oauth...
r:post('/callback', function() oauth:callback() end)
r:get('/callback', function() oauth:callback() end)
r:post('/oauth/token', function() oauth:get_token() end)
return r
end
function _M.call(method, uri, ...)
local r = _M.router()
local f, params = r:resolve(method or ngx.req.get_method(),
uri or ngx.var.uri,
unpack(... or {}))
return f, params
end
return _M
|
Fix oauth.lua
|
Fix oauth.lua
|
Lua
|
mit
|
3scale/apicast,3scale/apicast,3scale/docker-gateway,3scale/apicast,3scale/docker-gateway,3scale/apicast
|
7196fdaa2497b92bb47a5a49bd82f732b90f4bcf
|
packages/raiselower/init.lua
|
packages/raiselower/init.lua
|
local base = require("packages.base")
local package = pl.class(base)
package._name = "raiselower"
function package:registerCommands ()
self:registerCommand("raise", function (options, content)
local height = options.height or 0
height = SILE.parseComplexFrameDimension(height)
SILE.typesetter:pushHbox({
outputYourself = function (_, typesetter, _)
typesetter.frame:advancePageDirection(-height)
end
})
SILE.process(content)
SILE.typesetter:pushHbox({
outputYourself = function (_, typesetter, _)
if (type(typesetter.state.cursorY)) == "table" then
typesetter.state.cursorY = typesetter.state.cursorY.length
end
typesetter.frame:advancePageDirection(height)
end
})
end, "Raises the contents of the command by the amount specified in the <height> option")
self:registerCommand("lower", function (options, content)
SILE.call("raise", { height = "-" .. options.height }, content)
end, "Lowers the contents of the command by the amount specified in the <height> option")
end
package.documentation = [[
\begin{document}
If you don’t want your images, rules or text to be placed along the baseline, you can use the \autodoc:package{raiselower} package to move them up and down.
(The \autodoc:package{footnote} package uses this to superscript the footnote reference numbers.)
It provides two simple commands, \autodoc:command{\raise} and \autodoc:command{\lower} which both take a \autodoc:parameter{height=<dimension>} parameter.
They will respectively raise or lower their argument by the given height.
The raised or lowered content will not alter the height or depth of the line.
Here is some text raised by \raise[height=3pt]{three points}; here is some text lowered by \lower[height=4pt]{four points}.
The previous paragraph was generated by:
\begin{verbatim}
Here is some text raised by \\raise[height=3pt]\{three points\}; here is some text lowered by \\lower[height=4pt]\{four points\}.
\end{verbatim}
\end{document}
]]
return package
|
local base = require("packages.base")
local package = pl.class(base)
package._name = "raiselower"
local function raise (height, content)
SILE.typesetter:pushHbox({
outputYourself = function (_, typesetter, _)
typesetter.frame:advancePageDirection(-height)
end
})
SILE.process(content)
SILE.typesetter:pushHbox({
outputYourself = function (_, typesetter, _)
if (type(typesetter.state.cursorY)) == "table" then
typesetter.state.cursorY = typesetter.state.cursorY.length
end
typesetter.frame:advancePageDirection(height)
end
})
end
function package:registerCommands ()
self:registerCommand("raise", function (options, content)
local height = SU.cast("measurement", options.height)
raise(height:absolute(), content)
end, "Raises the contents of the command by the amount specified in the <height> option")
self:registerCommand("lower", function (options, content)
local height = SU.cast("measurement", options.height)
raise(-height:absolute(), content)
end, "Lowers the contents of the command by the amount specified in the <height> option")
end
package.documentation = [[
\begin{document}
If you don’t want your images, rules or text to be placed along the baseline, you can use the \autodoc:package{raiselower} package to move them up and down.
(The \autodoc:package{footnote} package uses this to superscript the footnote reference numbers.)
It provides two simple commands, \autodoc:command{\raise} and \autodoc:command{\lower} which both take a \autodoc:parameter{height=<dimension>} parameter.
They will respectively raise or lower their argument by the given height.
The raised or lowered content will not alter the height or depth of the line.
Here is some text raised by \raise[height=3pt]{three points}; here is some text lowered by \lower[height=4pt]{four points}.
The previous paragraph was generated by:
\begin{verbatim}
Here is some text raised by \\raise[height=3pt]\{three points\}; here is some text lowered by \\lower[height=4pt]\{four points\}.
\end{verbatim}
\end{document}
]]
return package
|
fix(packages): Parse height argument to `\raise` / `\lower` as measurement (#1506)
|
fix(packages): Parse height argument to `\raise` / `\lower` as measurement (#1506)
This is an old function that predates our SILE.length / SILE.measurement
logic and units like `%fh` that are relative to the frame or page. It
was being parsed as a frame dimension, which I assume was just a way to
get user friendly string input and perhaps some expressiveness.
I couldn't actually think of a use case for making this a full frame
string and not accepting our standardized measurement types comes with
lots of downfalls especially in programmatic usage.
I'm not marking this as breaking because in most cases I think the new
behavior will be expected and I doubt the edge cases where they differ
are seeing much use.
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
b862437068e3a2d5d618b30b2363ee4fe50fe53c
|
kong/plugins/azure-functions/schema.lua
|
kong/plugins/azure-functions/schema.lua
|
local typedefs = require "kong.db.schema.typedefs"
return {
name = "azure-functions",
fields = {
{ run_on = typedefs.run_on_first },
{ config = {
type = "record",
fields = {
-- connection basics
{ timeout = { type = "number", default = 600000}, },
{ keepalive = { type = "number", default = 60000 }, },
{ https = { type = "boolean", default = true }, },
{ https_verify = { type = "boolean", default = false }, },
-- authorization
{ apikey = { type = "string" }, },
{ clientid = { type = "string" }, },
-- target/location
{ appname = { type = "string", required = true }, },
{ hostdomain = { type = "string", required = true, default = "azurewebsites.net" }, },
{ routeprefix = { type = "string", default = "api" }, },
{ functionname = { type = "string", required = true }, },
},
}, },
},
}
|
local typedefs = require "kong.db.schema.typedefs"
return {
name = "azure-functions",
fields = {
{ config = {
type = "record",
fields = {
-- connection basics
{ timeout = { type = "number", default = 600000}, },
{ keepalive = { type = "number", default = 60000 }, },
{ https = { type = "boolean", default = true }, },
{ https_verify = { type = "boolean", default = false }, },
-- authorization
{ apikey = { type = "string" }, },
{ clientid = { type = "string" }, },
-- target/location
{ appname = { type = "string", required = true }, },
{ hostdomain = { type = "string", required = true, default = "azurewebsites.net" }, },
{ routeprefix = { type = "string", default = "api" }, },
{ functionname = { type = "string", required = true }, },
},
}, },
},
}
|
fix(azure-functions) remove `run_on` field from plugin config schema (#10)
|
fix(azure-functions) remove `run_on` field from plugin config schema (#10)
It is no longer needed as service mesh support is removed from Kong
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
4e2245ccda1edcff363088ae7dd1948eddf16c8d
|
applications/luci-minidlna/luasrc/model/cbi/minidlna.lua
|
applications/luci-minidlna/luasrc/model/cbi/minidlna.lua
|
--[[
LuCI - Lua Configuration Interface - miniDLNA support
Copyright 2012 Gabor Juhos <[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 m, s, o
m = Map("minidlna", translate("miniDLNA"),
translate("MiniDLNA is server software with the aim of being fully compliant with DLNA/UPnP-AV clients."))
m:section(SimpleSection).template = "minidlna_status"
s = m:section(TypedSection, "minidlna", "miniDLNA Settings")
s.addremove = false
s.anonymous = true
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
o = s:taboption("general", Flag, "enabled", translate("Enable:"))
o.rmempty = false
function o.cfgvalue(self, section)
return luci.sys.init.enabled("minidlna") and self.enabled or self.disabled
end
function o.write(self, section, value)
if value == "1" then
luci.sys.init.enable("minidlna")
luci.sys.call("/etc/init.d/minidlna start >/dev/null")
else
luci.sys.call("/etc/init.d/minidlna stop >/dev/null")
luci.sys.init.disable("minidlna")
end
return Flag.write(self, section, value)
end
o = s:taboption("general", Value, "port", translate("Port:"),
translate("Port for HTTP (descriptions, SOAP, media transfer) traffic."))
o.datatype = "port"
o.default = 8200
o = s:taboption("general", Value, "interface", translate("Interfaces:"),
translate("Network interfaces to serve."))
o.template = "cbi/network_ifacelist"
o.widget = "checkbox"
o.nocreate = true
function o.cfgvalue(self, section)
local rv = { }
local val = Value.cfgvalue(self, section)
if val then
local ifc
for ifc in val:gmatch("[^,%s]+") do
rv[#rv+1] = ifc
end
end
return rv
end
function o.write(self, section, value)
local rv = { }
local ifc
for ifc in luci.util.imatch(value) do
rv[#rv+1] = ifc
end
Value.write(self, section, table.concat(rv, ","))
end
o = s:taboption("general", Value, "friendly_name", translate("Friendly name:"),
translate("Set this if you want to customize the name that shows up on your clients."))
o.rmempty = true
o.placeholder = "OpenWrt DLNA Server"
o = s:taboption("advanced", Value, "db_dir", translate("Database directory:"),
translate("Set this if you would like to specify the directory where you want MiniDLNA to store its database and album art cache."))
o.rmempty = true
o.placeholder = "/var/cache/minidlna"
o = s:taboption("advanced", Value, "log_dir", translate("Log directory:"),
translate("Set this if you would like to specify the directory where you want MiniDLNA to store its log file."))
o.rmempty = true
o.placeholder = "/var/log"
s:taboption("advanced", Flag, "inotify", translate("Enable inotify:"),
translate("Set this to enable inotify monitoring to automatically discover new files."))
s:taboption("advanced", Flag, "enable_tivo", translate("Enable TIVO:"),
translate("Set this to enable support for streaming .jpg and .mp3 files to a TiVo supporting HMO."))
o.rmempty = true
o = s:taboption("advanced", Flag, "strict_dlna", translate("Strict to DLNA standard:"),
translate("Set this to strictly adhere to DLNA standards. This will allow server-side downscaling of very large JPEG images, which may hurt JPEG serving performance on (at least) Sony DLNA products."))
o.rmempty = true
o = s:taboption("advanced", Value, "presentation_url", translate("Presentation URL:"))
o.rmempty = true
o.placeholder = "http://192.168.1.1/"
o = s:taboption("advanced", Value, "notify_interval", translate("Notify interval:"),
translate("Notify interval in seconds."))
o.datatype = "uinteger"
o.placeholder = 900
o = s:taboption("advanced", Value, "serial", translate("Announced serial number:"),
translate("Serial number the miniDLNA daemon will report to clients in its XML description."))
o.placeholder = "12345678"
s:taboption("advanced", Value, "model_number", translate("Announced model number:"),
translate("Model number the miniDLNA daemon will report to clients in its XML description."))
o.placholder = "1"
o = s:taboption("advanced", Value, "minissdpsocket", translate("miniSSDP socket:"),
translate("Specify the path to the MiniSSDPd socket."))
o.rmempty = true
o.placeholder = "/var/run/minissdpd.sock"
o = s:taboption("general", ListValue, "root_container", translate("Root container:"))
o:value(".", translate("Standard container"))
o:value("B", translate("Browse directory"))
o:value("M", translate("Music"))
o:value("V", translate("Video"))
o:value("P", translate("Pictures"))
s:taboption("general", DynamicList, "media_dir", translate("Media directories:"),
translate("Set this to the directory you want scanned. If you want to restrict the directory to a specific content type, you can prepend the type ('A' for audio, 'V' for video, 'P' for images), followed by a comma, to the directory (eg. media_dir=A,/mnt/media/Music). Multiple directories can be specified."))
o = s:taboption("general", DynamicList, "album_art_names", translate("Album art names:"),
translate("This is a list of file names to check for when searching for album art."))
o.rmempty = true
o.placeholder = "Cover.jpg/cover.jpg/AlbumArtSmall.jpg/albumartsmall.jpg"
function o.cfgvalue(self, section)
local rv = { }
local val = Value.cfgvalue(self, section)
if type(val) == "table" then val = table.concat(val, "/") end
local file
for file in val:gmatch("[^/%s]+") do
rv[#rv+1] = file
end
return rv
end
function o.write(self, section, value)
local rv = { }
local file
for file in luci.util.imatch(value) do
rv[#rv+1] = file
end
Value.write(self, section, table.concat(rv, "/"))
end
return m
|
--[[
LuCI - Lua Configuration Interface - miniDLNA support
Copyright 2012 Gabor Juhos <[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 m, s, o
m = Map("minidlna", translate("miniDLNA"),
translate("MiniDLNA is server software with the aim of being fully compliant with DLNA/UPnP-AV clients."))
m:section(SimpleSection).template = "minidlna_status"
s = m:section(TypedSection, "minidlna", "miniDLNA Settings")
s.addremove = false
s.anonymous = true
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
o = s:taboption("general", Flag, "enabled", translate("Enable:"))
o.rmempty = false
function o.cfgvalue(self, section)
return luci.sys.init.enabled("minidlna") and self.enabled or self.disabled
end
function o.write(self, section, value)
if value == "1" then
luci.sys.init.enable("minidlna")
luci.sys.call("/etc/init.d/minidlna start >/dev/null")
else
luci.sys.call("/etc/init.d/minidlna stop >/dev/null")
luci.sys.init.disable("minidlna")
end
return Flag.write(self, section, value)
end
o = s:taboption("general", Value, "port", translate("Port:"),
translate("Port for HTTP (descriptions, SOAP, media transfer) traffic."))
o.datatype = "port"
o.default = 8200
o = s:taboption("general", Value, "interface", translate("Interfaces:"),
translate("Network interfaces to serve."))
o.template = "cbi/network_ifacelist"
o.widget = "checkbox"
o.nocreate = true
function o.cfgvalue(self, section)
local rv = { }
local val = Value.cfgvalue(self, section)
if val then
local ifc
for ifc in val:gmatch("[^,%s]+") do
rv[#rv+1] = ifc
end
end
return rv
end
function o.write(self, section, value)
local rv = { }
local ifc
for ifc in luci.util.imatch(value) do
rv[#rv+1] = ifc
end
Value.write(self, section, table.concat(rv, ","))
end
o = s:taboption("general", Value, "friendly_name", translate("Friendly name:"),
translate("Set this if you want to customize the name that shows up on your clients."))
o.rmempty = true
o.placeholder = "OpenWrt DLNA Server"
o = s:taboption("advanced", Value, "db_dir", translate("Database directory:"),
translate("Set this if you would like to specify the directory where you want MiniDLNA to store its database and album art cache."))
o.rmempty = true
o.placeholder = "/var/cache/minidlna"
o = s:taboption("advanced", Value, "log_dir", translate("Log directory:"),
translate("Set this if you would like to specify the directory where you want MiniDLNA to store its log file."))
o.rmempty = true
o.placeholder = "/var/log"
s:taboption("advanced", Flag, "inotify", translate("Enable inotify:"),
translate("Set this to enable inotify monitoring to automatically discover new files."))
s:taboption("advanced", Flag, "enable_tivo", translate("Enable TIVO:"),
translate("Set this to enable support for streaming .jpg and .mp3 files to a TiVo supporting HMO."))
o.rmempty = true
o = s:taboption("advanced", Flag, "strict_dlna", translate("Strict to DLNA standard:"),
translate("Set this to strictly adhere to DLNA standards. This will allow server-side downscaling of very large JPEG images, which may hurt JPEG serving performance on (at least) Sony DLNA products."))
o.rmempty = true
o = s:taboption("advanced", Value, "presentation_url", translate("Presentation URL:"))
o.rmempty = true
o.placeholder = "http://192.168.1.1/"
o = s:taboption("advanced", Value, "notify_interval", translate("Notify interval:"),
translate("Notify interval in seconds."))
o.datatype = "uinteger"
o.placeholder = 900
o = s:taboption("advanced", Value, "serial", translate("Announced serial number:"),
translate("Serial number the miniDLNA daemon will report to clients in its XML description."))
o.placeholder = "12345678"
s:taboption("advanced", Value, "model_number", translate("Announced model number:"),
translate("Model number the miniDLNA daemon will report to clients in its XML description."))
o.placholder = "1"
o = s:taboption("advanced", Value, "minissdpsocket", translate("miniSSDP socket:"),
translate("Specify the path to the MiniSSDPd socket."))
o.rmempty = true
o.placeholder = "/var/run/minissdpd.sock"
o = s:taboption("general", ListValue, "root_container", translate("Root container:"))
o:value(".", translate("Standard container"))
o:value("B", translate("Browse directory"))
o:value("M", translate("Music"))
o:value("V", translate("Video"))
o:value("P", translate("Pictures"))
s:taboption("general", DynamicList, "media_dir", translate("Media directories:"),
translate("Set this to the directory you want scanned. If you want to restrict the directory to a specific content type, you can prepend the type ('A' for audio, 'V' for video, 'P' for images), followed by a comma, to the directory (eg. media_dir=A,/mnt/media/Music). Multiple directories can be specified."))
o = s:taboption("general", DynamicList, "album_art_names", translate("Album art names:"),
translate("This is a list of file names to check for when searching for album art."))
o.rmempty = true
o.placeholder = "Cover.jpg"
function o.cfgvalue(self, section)
local rv = { }
local val = Value.cfgvalue(self, section)
if type(val) == "table" then
val = table.concat(val, "/")
elseif not val then
val = ""
end
local file
for file in val:gmatch("[^/%s]+") do
rv[#rv+1] = file
end
return rv
end
function o.write(self, section, value)
local rv = { }
local file
for file in luci.util.imatch(value) do
rv[#rv+1] = file
end
Value.write(self, section, table.concat(rv, "/"))
end
return m
|
applications/luci-minidlna: fix possible nil indexing if album art option is unset, only show one filename in placeholder
|
applications/luci-minidlna: fix possible nil indexing if album art option is unset, only show one filename in placeholder
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@8548 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
freifunk-gluon/luci,freifunk-gluon/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,8devices/carambola2-luci,jschmidlapp/luci,freifunk-gluon/luci,vhpham80/luci,vhpham80/luci,ch3n2k/luci,jschmidlapp/luci,stephank/luci,8devices/carambola2-luci,Canaan-Creative/luci,saraedum/luci-packages-old,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,dtaht/cerowrt-luci-3.3,8devices/carambola2-luci,ch3n2k/luci,Flexibity/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,jschmidlapp/luci,freifunk-gluon/luci,Flexibity/luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,stephank/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,jschmidlapp/luci,Flexibity/luci,Flexibity/luci,gwlim/luci,ch3n2k/luci,ch3n2k/luci,8devices/carambola2-luci,saraedum/luci-packages-old,jschmidlapp/luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,phi-psi/luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,jschmidlapp/luci,yeewang/openwrt-luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,vhpham80/luci,dtaht/cerowrt-luci-3.3,gwlim/luci,gwlim/luci,ThingMesh/openwrt-luci,gwlim/luci,vhpham80/luci,stephank/luci,Canaan-Creative/luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,freifunk-gluon/luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,phi-psi/luci,ThingMesh/openwrt-luci,jschmidlapp/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,8devices/carambola2-luci,8devices/carambola2-luci,stephank/luci,freifunk-gluon/luci,ch3n2k/luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,Flexibity/luci,Flexibity/luci,ThingMesh/openwrt-luci,Flexibity/luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,dtaht/cerowrt-luci-3.3,phi-psi/luci,zwhfly/openwrt-luci,gwlim/luci,Canaan-Creative/luci,phi-psi/luci,yeewang/openwrt-luci,vhpham80/luci,freifunk-gluon/luci,stephank/luci,gwlim/luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,phi-psi/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,jschmidlapp/luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,eugenesan/openwrt-luci,gwlim/luci,Canaan-Creative/luci,Canaan-Creative/luci,ch3n2k/luci,vhpham80/luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci
|
cd456ff616e0c2c18afef2753c01b957bd3a66e2
|
applications/luci-minidlna/luasrc/model/cbi/minidlna.lua
|
applications/luci-minidlna/luasrc/model/cbi/minidlna.lua
|
--[[
LuCI - Lua Configuration Interface - miniDLNA support
Copyright 2012 Gabor Juhos <[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 m, s, o
m = Map("minidlna", translate("miniDLNA"),
translate("MiniDLNA is server software with the aim of being fully compliant with DLNA/UPnP-AV clients."))
m:section(SimpleSection).template = "minidlna_status"
s = m:section(TypedSection, "minidlna", "miniDLNA Settings")
s.addremove = false
s.anonymous = true
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
o = s:taboption("general", Flag, "enabled", translate("Enable:"))
o.rmempty = false
function o.cfgvalue(self, section)
return luci.sys.init.enabled("minidlna") and self.enabled or self.disabled
end
function o.write(self, section, value)
if value == "1" then
luci.sys.init.enable("minidlna")
luci.sys.call("/etc/init.d/minidlna start >/dev/null")
else
luci.sys.call("/etc/init.d/minidlna stop >/dev/null")
luci.sys.init.disable("minidlna")
end
return Flag.write(self, section, value)
end
o = s:taboption("general", Value, "port", translate("Port:"),
translate("Port for HTTP (descriptions, SOAP, media transfer) traffic."))
o.datatype = "port"
o.default = 8200
o = s:taboption("general", Value, "interface", translate("Interfaces:"),
translate("Network interfaces to serve."))
o.template = "cbi/network_ifacelist"
o.widget = "checkbox"
o.nocreate = true
function o.cfgvalue(self, section)
local rv = { }
local val = Value.cfgvalue(self, section)
if val then
local ifc
for ifc in val:gmatch("[^,%s]+") do
rv[#rv+1] = ifc
end
end
return rv
end
function o.write(self, section, value)
local rv = { }
local ifc
for ifc in luci.util.imatch(value) do
rv[#rv+1] = ifc
end
Value.write(self, section, table.concat(rv, ","))
end
o = s:taboption("general", Value, "friendly_name", translate("Friendly name:"),
translate("Set this if you want to customize the name that shows up on your clients."))
o.rmempty = true
o.placeholder = "OpenWrt DLNA Server"
o = s:taboption("advanced", Value, "db_dir", translate("Database directory:"),
translate("Set this if you would like to specify the directory where you want MiniDLNA to store its database and album art cache."))
o.rmempty = true
o.placeholder = "/var/cache/minidlna"
o = s:taboption("advanced", Value, "log_dir", translate("Log directory:"),
translate("Set this if you would like to specify the directory where you want MiniDLNA to store its log file."))
o.rmempty = true
o.placeholder = "/var/log"
s:taboption("advanced", Flag, "inotify", translate("Enable inotify:"),
translate("Set this to enable inotify monitoring to automatically discover new files."))
s:taboption("advanced", Flag, "enable_tivo", translate("Enable TIVO:"),
translate("Set this to enable support for streaming .jpg and .mp3 files to a TiVo supporting HMO."))
o.rmempty = true
o = s:taboption("advanced", Flag, "strict_dlna", translate("Strict to DLNA standard:"),
translate("Set this to strictly adhere to DLNA standards. This will allow server-side downscaling of very large JPEG images, which may hurt JPEG serving performance on (at least) Sony DLNA products."))
o.rmempty = true
o = s:taboption("advanced", Value, "presentation_url", translate("Presentation URL:"))
o.rmempty = true
o.placeholder = "http://192.168.1.1/"
o = s:taboption("advanced", Value, "notify_interval", translate("Notify interval:"),
translate("Notify interval in seconds."))
o.datatype = "uinteger"
o.placeholder = 900
o = s:taboption("advanced", Value, "serial", translate("Announced serial number:"),
translate("Serial number the miniDLNA daemon will report to clients in its XML description."))
o.placeholder = "12345678"
s:taboption("advanced", Value, "model_number", translate("Announced model number:"),
translate("Model number the miniDLNA daemon will report to clients in its XML description."))
o.placholder = "1"
o = s:taboption("advanced", Value, "minissdpsocket", translate("miniSSDP socket:"),
translate("Specify the path to the MiniSSDPd socket."))
o.rmempty = true
o.placeholder = "/var/run/minissdpd.sock"
o = s:taboption("general", ListValue, "root_container", translate("Root container:"))
o:value(".", translate("Standard container"))
o:value("B", translate("Browse directory"))
o:value("M", translate("Music"))
o:value("V", translate("Video"))
o:value("P", translate("Pictures"))
s:taboption("general", DynamicList, "media_dir", translate("Media directories:"),
translate("Set this to the directory you want scanned. If you want to restrict the directory to a specific content type, you can prepend the type ('A' for audio, 'V' for video, 'P' for images), followed by a comma, to the directory (eg. media_dir=A,/mnt/media/Music). Multiple directories can be specified."))
o = s:taboption("general", DynamicList, "album_art_names", translate("Album art names:"),
translate("This is a list of file names to check for when searching for album art."))
o.rmempty = true
o.placeholder = "Cover.jpg/cover.jpg/AlbumArtSmall.jpg/albumartsmall.jpg"
function o.cfgvalue(self, section)
local rv = { }
local val = Value.cfgvalue(self, section)
if type(val) == "table" then val = table.concat(val, "/") end
local file
for file in val:gmatch("[^/%s]+") do
rv[#rv+1] = file
end
return rv
end
function o.write(self, section, value)
local rv = { }
local file
for file in luci.util.imatch(value) do
rv[#rv+1] = file
end
Value.write(self, section, table.concat(rv, "/"))
end
return m
|
--[[
LuCI - Lua Configuration Interface - miniDLNA support
Copyright 2012 Gabor Juhos <[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 m, s, o
m = Map("minidlna", translate("miniDLNA"),
translate("MiniDLNA is server software with the aim of being fully compliant with DLNA/UPnP-AV clients."))
m:section(SimpleSection).template = "minidlna_status"
s = m:section(TypedSection, "minidlna", "miniDLNA Settings")
s.addremove = false
s.anonymous = true
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
o = s:taboption("general", Flag, "enabled", translate("Enable:"))
o.rmempty = false
function o.cfgvalue(self, section)
return luci.sys.init.enabled("minidlna") and self.enabled or self.disabled
end
function o.write(self, section, value)
if value == "1" then
luci.sys.init.enable("minidlna")
luci.sys.call("/etc/init.d/minidlna start >/dev/null")
else
luci.sys.call("/etc/init.d/minidlna stop >/dev/null")
luci.sys.init.disable("minidlna")
end
return Flag.write(self, section, value)
end
o = s:taboption("general", Value, "port", translate("Port:"),
translate("Port for HTTP (descriptions, SOAP, media transfer) traffic."))
o.datatype = "port"
o.default = 8200
o = s:taboption("general", Value, "interface", translate("Interfaces:"),
translate("Network interfaces to serve."))
o.template = "cbi/network_ifacelist"
o.widget = "checkbox"
o.nocreate = true
function o.cfgvalue(self, section)
local rv = { }
local val = Value.cfgvalue(self, section)
if val then
local ifc
for ifc in val:gmatch("[^,%s]+") do
rv[#rv+1] = ifc
end
end
return rv
end
function o.write(self, section, value)
local rv = { }
local ifc
for ifc in luci.util.imatch(value) do
rv[#rv+1] = ifc
end
Value.write(self, section, table.concat(rv, ","))
end
o = s:taboption("general", Value, "friendly_name", translate("Friendly name:"),
translate("Set this if you want to customize the name that shows up on your clients."))
o.rmempty = true
o.placeholder = "OpenWrt DLNA Server"
o = s:taboption("advanced", Value, "db_dir", translate("Database directory:"),
translate("Set this if you would like to specify the directory where you want MiniDLNA to store its database and album art cache."))
o.rmempty = true
o.placeholder = "/var/cache/minidlna"
o = s:taboption("advanced", Value, "log_dir", translate("Log directory:"),
translate("Set this if you would like to specify the directory where you want MiniDLNA to store its log file."))
o.rmempty = true
o.placeholder = "/var/log"
s:taboption("advanced", Flag, "inotify", translate("Enable inotify:"),
translate("Set this to enable inotify monitoring to automatically discover new files."))
s:taboption("advanced", Flag, "enable_tivo", translate("Enable TIVO:"),
translate("Set this to enable support for streaming .jpg and .mp3 files to a TiVo supporting HMO."))
o.rmempty = true
o = s:taboption("advanced", Flag, "strict_dlna", translate("Strict to DLNA standard:"),
translate("Set this to strictly adhere to DLNA standards. This will allow server-side downscaling of very large JPEG images, which may hurt JPEG serving performance on (at least) Sony DLNA products."))
o.rmempty = true
o = s:taboption("advanced", Value, "presentation_url", translate("Presentation URL:"))
o.rmempty = true
o.placeholder = "http://192.168.1.1/"
o = s:taboption("advanced", Value, "notify_interval", translate("Notify interval:"),
translate("Notify interval in seconds."))
o.datatype = "uinteger"
o.placeholder = 900
o = s:taboption("advanced", Value, "serial", translate("Announced serial number:"),
translate("Serial number the miniDLNA daemon will report to clients in its XML description."))
o.placeholder = "12345678"
s:taboption("advanced", Value, "model_number", translate("Announced model number:"),
translate("Model number the miniDLNA daemon will report to clients in its XML description."))
o.placholder = "1"
o = s:taboption("advanced", Value, "minissdpsocket", translate("miniSSDP socket:"),
translate("Specify the path to the MiniSSDPd socket."))
o.rmempty = true
o.placeholder = "/var/run/minissdpd.sock"
o = s:taboption("general", ListValue, "root_container", translate("Root container:"))
o:value(".", translate("Standard container"))
o:value("B", translate("Browse directory"))
o:value("M", translate("Music"))
o:value("V", translate("Video"))
o:value("P", translate("Pictures"))
s:taboption("general", DynamicList, "media_dir", translate("Media directories:"),
translate("Set this to the directory you want scanned. If you want to restrict the directory to a specific content type, you can prepend the type ('A' for audio, 'V' for video, 'P' for images), followed by a comma, to the directory (eg. media_dir=A,/mnt/media/Music). Multiple directories can be specified."))
o = s:taboption("general", DynamicList, "album_art_names", translate("Album art names:"),
translate("This is a list of file names to check for when searching for album art."))
o.rmempty = true
o.placeholder = "Cover.jpg"
function o.cfgvalue(self, section)
local rv = { }
local val = Value.cfgvalue(self, section)
if type(val) == "table" then
val = table.concat(val, "/")
elseif not val then
val = ""
end
local file
for file in val:gmatch("[^/%s]+") do
rv[#rv+1] = file
end
return rv
end
function o.write(self, section, value)
local rv = { }
local file
for file in luci.util.imatch(value) do
rv[#rv+1] = file
end
Value.write(self, section, table.concat(rv, "/"))
end
return m
|
applications/luci-minidlna: fix possible nil indexing if album art option is unset, only show one filename in placeholder
|
applications/luci-minidlna: fix possible nil indexing if album art option is unset, only show one filename in placeholder
|
Lua
|
apache-2.0
|
NeoRaider/luci,shangjiyu/luci-with-extra,teslamint/luci,LazyZhu/openwrt-luci-trunk-mod,cshore-firmware/openwrt-luci,oneru/luci,lcf258/openwrtcn,maxrio/luci981213,urueedi/luci,chris5560/openwrt-luci,oneru/luci,thess/OpenWrt-luci,tobiaswaldvogel/luci,RedSnake64/openwrt-luci-packages,cshore-firmware/openwrt-luci,shangjiyu/luci-with-extra,teslamint/luci,kuoruan/lede-luci,ff94315/luci-1,kuoruan/lede-luci,bittorf/luci,aa65535/luci,cappiewu/luci,openwrt-es/openwrt-luci,thesabbir/luci,oyido/luci,marcel-sch/luci,thess/OpenWrt-luci,remakeelectric/luci,daofeng2015/luci,marcel-sch/luci,obsy/luci,jchuang1977/luci-1,lcf258/openwrtcn,Hostle/luci,openwrt-es/openwrt-luci,tcatm/luci,forward619/luci,shangjiyu/luci-with-extra,Hostle/luci,rogerpueyo/luci,thesabbir/luci,palmettos/test,openwrt-es/openwrt-luci,LuttyYang/luci,sujeet14108/luci,LuttyYang/luci,MinFu/luci,tcatm/luci,kuoruan/luci,dwmw2/luci,RedSnake64/openwrt-luci-packages,Kyklas/luci-proto-hso,ff94315/luci-1,nmav/luci,RedSnake64/openwrt-luci-packages,schidler/ionic-luci,deepak78/new-luci,ReclaimYourPrivacy/cloak-luci,bright-things/ionic-luci,cshore/luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,cappiewu/luci,florian-shellfire/luci,nmav/luci,obsy/luci,aircross/OpenWrt-Firefly-LuCI,wongsyrone/luci-1,hnyman/luci,mumuqz/luci,ollie27/openwrt_luci,jchuang1977/luci-1,opentechinstitute/luci,LazyZhu/openwrt-luci-trunk-mod,ollie27/openwrt_luci,aircross/OpenWrt-Firefly-LuCI,bittorf/luci,981213/luci-1,RuiChen1113/luci,Sakura-Winkey/LuCI,lcf258/openwrtcn,urueedi/luci,LuttyYang/luci,opentechinstitute/luci,aircross/OpenWrt-Firefly-LuCI,zhaoxx063/luci,ReclaimYourPrivacy/cloak-luci,david-xiao/luci,bittorf/luci,thesabbir/luci,obsy/luci,remakeelectric/luci,jorgifumi/luci,jlopenwrtluci/luci,Noltari/luci,daofeng2015/luci,Hostle/openwrt-luci-multi-user,slayerrensky/luci,maxrio/luci981213,kuoruan/luci,palmettos/test,harveyhu2012/luci,hnyman/luci,chris5560/openwrt-luci,Hostle/openwrt-luci-multi-user,hnyman/luci,zhaoxx063/luci,Wedmer/luci,taiha/luci,harveyhu2012/luci,Hostle/openwrt-luci-multi-user,LazyZhu/openwrt-luci-trunk-mod,openwrt/luci,hnyman/luci,db260179/openwrt-bpi-r1-luci,fkooman/luci,dismantl/luci-0.12,openwrt/luci,nwf/openwrt-luci,aa65535/luci,aa65535/luci,oyido/luci,kuoruan/luci,ollie27/openwrt_luci,aircross/OpenWrt-Firefly-LuCI,tcatm/luci,nwf/openwrt-luci,zhaoxx063/luci,981213/luci-1,openwrt/luci,Wedmer/luci,opentechinstitute/luci,remakeelectric/luci,taiha/luci,oneru/luci,db260179/openwrt-bpi-r1-luci,ollie27/openwrt_luci,oyido/luci,tcatm/luci,bright-things/ionic-luci,florian-shellfire/luci,dwmw2/luci,obsy/luci,taiha/luci,david-xiao/luci,jorgifumi/luci,Hostle/luci,palmettos/cnLuCI,fkooman/luci,jlopenwrtluci/luci,LuttyYang/luci,zhaoxx063/luci,oneru/luci,forward619/luci,kuoruan/luci,palmettos/cnLuCI,oyido/luci,bright-things/ionic-luci,rogerpueyo/luci,dismantl/luci-0.12,oyido/luci,rogerpueyo/luci,sujeet14108/luci,deepak78/new-luci,deepak78/new-luci,keyidadi/luci,wongsyrone/luci-1,aa65535/luci,mumuqz/luci,bittorf/luci,chris5560/openwrt-luci,openwrt/luci,chris5560/openwrt-luci,teslamint/luci,wongsyrone/luci-1,david-xiao/luci,Wedmer/luci,kuoruan/lede-luci,schidler/ionic-luci,keyidadi/luci,Hostle/luci,NeoRaider/luci,nmav/luci,schidler/ionic-luci,thesabbir/luci,wongsyrone/luci-1,rogerpueyo/luci,981213/luci-1,dwmw2/luci,openwrt-es/openwrt-luci,marcel-sch/luci,lcf258/openwrtcn,db260179/openwrt-bpi-r1-luci,cshore-firmware/openwrt-luci,Kyklas/luci-proto-hso,ff94315/luci-1,Wedmer/luci,slayerrensky/luci,cshore/luci,joaofvieira/luci,joaofvieira/luci,LazyZhu/openwrt-luci-trunk-mod,RedSnake64/openwrt-luci-packages,teslamint/luci,jlopenwrtluci/luci,remakeelectric/luci,lbthomsen/openwrt-luci,ollie27/openwrt_luci,keyidadi/luci,deepak78/new-luci,mumuqz/luci,nwf/openwrt-luci,cappiewu/luci,LazyZhu/openwrt-luci-trunk-mod,rogerpueyo/luci,NeoRaider/luci,joaofvieira/luci,palmettos/cnLuCI,cappiewu/luci,wongsyrone/luci-1,nmav/luci,slayerrensky/luci,Noltari/luci,palmettos/cnLuCI,tcatm/luci,cshore/luci,male-puppies/luci,taiha/luci,rogerpueyo/luci,NeoRaider/luci,palmettos/cnLuCI,rogerpueyo/luci,openwrt-es/openwrt-luci,oyido/luci,tcatm/luci,nmav/luci,Kyklas/luci-proto-hso,taiha/luci,fkooman/luci,schidler/ionic-luci,shangjiyu/luci-with-extra,981213/luci-1,forward619/luci,rogerpueyo/luci,Kyklas/luci-proto-hso,dwmw2/luci,LazyZhu/openwrt-luci-trunk-mod,artynet/luci,chris5560/openwrt-luci,fkooman/luci,lcf258/openwrtcn,openwrt-es/openwrt-luci,david-xiao/luci,openwrt/luci,kuoruan/luci,981213/luci-1,Noltari/luci,Sakura-Winkey/LuCI,thess/OpenWrt-luci,lbthomsen/openwrt-luci,harveyhu2012/luci,david-xiao/luci,ff94315/luci-1,maxrio/luci981213,marcel-sch/luci,Hostle/openwrt-luci-multi-user,RedSnake64/openwrt-luci-packages,florian-shellfire/luci,mumuqz/luci,daofeng2015/luci,remakeelectric/luci,aircross/OpenWrt-Firefly-LuCI,florian-shellfire/luci,jchuang1977/luci-1,maxrio/luci981213,fkooman/luci,opentechinstitute/luci,MinFu/luci,forward619/luci,forward619/luci,taiha/luci,db260179/openwrt-bpi-r1-luci,kuoruan/luci,oneru/luci,mumuqz/luci,tcatm/luci,daofeng2015/luci,remakeelectric/luci,forward619/luci,lbthomsen/openwrt-luci,palmettos/test,cshore/luci,taiha/luci,aircross/OpenWrt-Firefly-LuCI,nwf/openwrt-luci,keyidadi/luci,jlopenwrtluci/luci,marcel-sch/luci,aa65535/luci,dwmw2/luci,db260179/openwrt-bpi-r1-luci,shangjiyu/luci-with-extra,ReclaimYourPrivacy/cloak-luci,harveyhu2012/luci,cappiewu/luci,ff94315/luci-1,RuiChen1113/luci,Hostle/openwrt-luci-multi-user,florian-shellfire/luci,maxrio/luci981213,cshore-firmware/openwrt-luci,wongsyrone/luci-1,db260179/openwrt-bpi-r1-luci,thesabbir/luci,LazyZhu/openwrt-luci-trunk-mod,jchuang1977/luci-1,oneru/luci,cshore-firmware/openwrt-luci,dismantl/luci-0.12,openwrt/luci,keyidadi/luci,harveyhu2012/luci,keyidadi/luci,oyido/luci,urueedi/luci,zhaoxx063/luci,LuttyYang/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,urueedi/luci,ff94315/luci-1,david-xiao/luci,maxrio/luci981213,Sakura-Winkey/LuCI,ff94315/luci-1,daofeng2015/luci,male-puppies/luci,MinFu/luci,Hostle/luci,kuoruan/lede-luci,oneru/luci,keyidadi/luci,male-puppies/luci,sujeet14108/luci,ReclaimYourPrivacy/cloak-luci,nwf/openwrt-luci,urueedi/luci,tcatm/luci,jorgifumi/luci,NeoRaider/luci,bittorf/luci,remakeelectric/luci,cappiewu/luci,schidler/ionic-luci,lbthomsen/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,marcel-sch/luci,Hostle/luci,Sakura-Winkey/LuCI,jlopenwrtluci/luci,joaofvieira/luci,palmettos/cnLuCI,tobiaswaldvogel/luci,palmettos/test,sujeet14108/luci,artynet/luci,teslamint/luci,remakeelectric/luci,nmav/luci,fkooman/luci,RuiChen1113/luci,teslamint/luci,dwmw2/luci,hnyman/luci,male-puppies/luci,deepak78/new-luci,cshore-firmware/openwrt-luci,tobiaswaldvogel/luci,cshore/luci,lcf258/openwrtcn,mumuqz/luci,dismantl/luci-0.12,palmettos/cnLuCI,joaofvieira/luci,obsy/luci,Wedmer/luci,harveyhu2012/luci,cappiewu/luci,thesabbir/luci,florian-shellfire/luci,bright-things/ionic-luci,palmettos/test,ollie27/openwrt_luci,Noltari/luci,palmettos/test,thess/OpenWrt-luci,dismantl/luci-0.12,RedSnake64/openwrt-luci-packages,opentechinstitute/luci,shangjiyu/luci-with-extra,mumuqz/luci,Sakura-Winkey/LuCI,artynet/luci,jchuang1977/luci-1,male-puppies/luci,david-xiao/luci,NeoRaider/luci,thesabbir/luci,daofeng2015/luci,forward619/luci,Noltari/luci,male-puppies/luci,joaofvieira/luci,openwrt-es/openwrt-luci,bittorf/luci,fkooman/luci,ReclaimYourPrivacy/cloak-luci,ff94315/luci-1,cshore-firmware/openwrt-luci,sujeet14108/luci,tobiaswaldvogel/luci,artynet/luci,nmav/luci,jchuang1977/luci-1,tobiaswaldvogel/luci,male-puppies/luci,jlopenwrtluci/luci,jorgifumi/luci,nwf/openwrt-luci,mumuqz/luci,Sakura-Winkey/LuCI,Noltari/luci,maxrio/luci981213,opentechinstitute/luci,Hostle/openwrt-luci-multi-user,Hostle/luci,nmav/luci,db260179/openwrt-bpi-r1-luci,aa65535/luci,artynet/luci,bright-things/ionic-luci,MinFu/luci,schidler/ionic-luci,cshore/luci,RuiChen1113/luci,LuttyYang/luci,Kyklas/luci-proto-hso,daofeng2015/luci,jlopenwrtluci/luci,lbthomsen/openwrt-luci,kuoruan/luci,NeoRaider/luci,MinFu/luci,hnyman/luci,sujeet14108/luci,LazyZhu/openwrt-luci-trunk-mod,urueedi/luci,slayerrensky/luci,RedSnake64/openwrt-luci-packages,oyido/luci,kuoruan/lede-luci,lcf258/openwrtcn,teslamint/luci,Kyklas/luci-proto-hso,tobiaswaldvogel/luci,keyidadi/luci,deepak78/new-luci,deepak78/new-luci,chris5560/openwrt-luci,urueedi/luci,deepak78/new-luci,lcf258/openwrtcn,Hostle/openwrt-luci-multi-user,tobiaswaldvogel/luci,florian-shellfire/luci,Wedmer/luci,LuttyYang/luci,jchuang1977/luci-1,shangjiyu/luci-with-extra,shangjiyu/luci-with-extra,cshore-firmware/openwrt-luci,Sakura-Winkey/LuCI,RuiChen1113/luci,nmav/luci,bright-things/ionic-luci,bright-things/ionic-luci,thess/OpenWrt-luci,ollie27/openwrt_luci,Hostle/luci,lcf258/openwrtcn,artynet/luci,slayerrensky/luci,fkooman/luci,cshore/luci,jorgifumi/luci,wongsyrone/luci-1,RuiChen1113/luci,RuiChen1113/luci,urueedi/luci,Kyklas/luci-proto-hso,bright-things/ionic-luci,jlopenwrtluci/luci,chris5560/openwrt-luci,marcel-sch/luci,wongsyrone/luci-1,aa65535/luci,NeoRaider/luci,schidler/ionic-luci,Wedmer/luci,florian-shellfire/luci,jorgifumi/luci,daofeng2015/luci,Wedmer/luci,marcel-sch/luci,schidler/ionic-luci,opentechinstitute/luci,slayerrensky/luci,palmettos/cnLuCI,artynet/luci,chris5560/openwrt-luci,maxrio/luci981213,obsy/luci,david-xiao/luci,aa65535/luci,Noltari/luci,kuoruan/lede-luci,thesabbir/luci,dwmw2/luci,ReclaimYourPrivacy/cloak-luci,jorgifumi/luci,forward619/luci,981213/luci-1,Hostle/openwrt-luci-multi-user,slayerrensky/luci,jchuang1977/luci-1,cappiewu/luci,teslamint/luci,palmettos/test,nwf/openwrt-luci,hnyman/luci,dismantl/luci-0.12,hnyman/luci,bittorf/luci,bittorf/luci,slayerrensky/luci,thess/OpenWrt-luci,sujeet14108/luci,openwrt/luci,kuoruan/lede-luci,opentechinstitute/luci,ollie27/openwrt_luci,obsy/luci,zhaoxx063/luci,nwf/openwrt-luci,jorgifumi/luci,palmettos/test,lcf258/openwrtcn,MinFu/luci,981213/luci-1,MinFu/luci,MinFu/luci,kuoruan/lede-luci,thess/OpenWrt-luci,joaofvieira/luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,Noltari/luci,zhaoxx063/luci,lbthomsen/openwrt-luci,zhaoxx063/luci,sujeet14108/luci,dwmw2/luci,kuoruan/luci,Sakura-Winkey/LuCI,Noltari/luci,LuttyYang/luci,db260179/openwrt-bpi-r1-luci,oneru/luci,harveyhu2012/luci,dismantl/luci-0.12,male-puppies/luci,obsy/luci,artynet/luci,cshore/luci,RuiChen1113/luci,thess/OpenWrt-luci,taiha/luci,openwrt/luci,joaofvieira/luci,artynet/luci
|
af3be1c6403b20faa9a5c3b6d9466052094a8beb
|
tests/test_waiter.lua
|
tests/test_waiter.lua
|
local levent = require "levent.levent"
function t1()
local waiter = levent.waiter()
local timer = levent.get_hub().loop:timer(0.1)
local value = "hello from waiter 1"
timer:start(waiter.switch, waiter, value)
levent.sleep(0.2)
assert(waiter:get() == value)
print(value)
end
function t2()
local waiter = levent.waiter()
local timer = levent.get_hub().loop:timer(0.1)
local value = "hello from waiter 2"
timer:start(waiter.switch, waiter, value)
assert(waiter:get() == value)
print(value)
end
levent.spawn(t1)
levent.spawn(t2)
levent.wait()
|
local levent = require "levent.levent"
function t1()
local waiter = levent.waiter()
local timer = levent.get_hub().loop:timer(0.1)
local value = "hello from waiter 1"
timer:start(waiter.switch, waiter, value)
levent.sleep(0.2)
assert(waiter:get() == value)
print(value)
end
function t2()
local waiter = levent.waiter()
local timer = levent.get_hub().loop:timer(0.1)
local value = "hello from waiter 2"
timer:start(waiter.switch, waiter, value)
assert(waiter:get() == value)
print(value)
end
levent.start(function()
levent.spawn(t1)
levent.spawn(t2)
end)
|
fix test waiter case
|
fix test waiter case
|
Lua
|
mit
|
xjdrew/levent
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.