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
|
---|---|---|---|---|---|---|---|---|---|
53e0001738310e056810146735c78408b76e09e5
|
orange/plugins/dynamic_upstream/handler.lua
|
orange/plugins/dynamic_upstream/handler.lua
|
local pairs = pairs
local ipairs = ipairs
local ngx_re_sub = ngx.re.sub
local ngx_re_find = ngx.re.find
local string_sub = string.sub
local orange_db = require("orange.store.orange_db")
local judge_util = require("orange.utils.judge")
local extractor_util = require("orange.utils.extractor")
local handle_util = require("orange.utils.handle")
local headers_util = require("orange.utils.headers")
local BasePlugin = require("orange.plugins.base_handler")
local ngx_set_uri_args = ngx.req.set_uri_args
local ngx_decode_args = ngx.decode_args
local function ngx_set_uri(uri,rule_handle)
ngx.var.upstream_host = rule_handle.host and rule_handle.host or ngx.var.host
ngx.var.upstream_url = rule_handle.upstream_name
ngx.var.upstream_request_uri = uri .. '?' .. ngx.encode_args(ngx.req.get_uri_args())
ngx.log(ngx.INFO,'[DynamicUpstream][upstream uri][http://',ngx.var.upstream_url,ngx.var.upstream_request_uri,']')
end
local function filter_rules(sid, plugin, ngx_var_uri)
local rules = orange_db.get_json(plugin .. ".selector." .. sid .. ".rules")
if not rules or type(rules) ~= "table" or #rules <= 0 then
return false
end
for i, rule in ipairs(rules) do
if rule.enable == true then
-- judge阶段
local pass = judge_util.judge_rule(rule, "dynamic_upstream")
-- handle阶段
if pass then
-- extract阶段
headers_util:set_headers(rule)
local variables = extractor_util.extract_variables(rule.extractor)
local handle = rule.handle
if handle and handle.uri_tmpl and handle.upstream_name then
local to_rewrite = handle_util.build_uri(rule.extractor.type, handle.uri_tmpl, variables)
if to_rewrite and to_rewrite ~= ngx_var_uri then
if handle.log == true then
ngx.log(ngx.INFO, "[DynamicUpstream] ", ngx_var_uri, " to:", to_rewrite)
end
local from, to, err = ngx_re_find(to_rewrite, "[%?]{1}", "jo")
if not err and from and from >= 1 then
--local qs = ngx_re_sub(to_rewrite, "[A-Z0-9a-z-_/]*[%?]{1}", "", "jo")
local qs = string_sub(to_rewrite, from+1)
if qs then
local args = ngx_decode_args(qs, 0)
if args then
ngx_set_uri_args(args)
end
end
end
ngx_set_uri(to_rewrite, handle)
return true
end
end
return true
end
end
end
return false
end
local DynamicUpstreamHandler = BasePlugin:extend()
DynamicUpstreamHandler.PRIORITY = 2000
function DynamicUpstreamHandler:new(store)
DynamicUpstreamHandler.super.new(self, "dynamic-upstream-plugin")
self.store = store
end
function DynamicUpstreamHandler:rewrite(conf)
DynamicUpstreamHandler.super.rewrite(self)
local enable = orange_db.get("dynamic_upstream.enable")
local meta = orange_db.get_json("dynamic_upstream.meta")
local selectors = orange_db.get_json("dynamic_upstream.selectors")
local ordered_selectors = meta and meta.selectors
if not enable or enable ~= true or not meta or not ordered_selectors or not selectors then
return
end
local ngx_var_uri = ngx.var.uri
for i, sid in ipairs(ordered_selectors) do
local selector = selectors[sid]
ngx.log(ngx.INFO, "==[DynamicUpstream][START SELECTOR:", sid, "][NAME:",selector.name,']')
if selector and selector.enable == true then
local selector_pass
if selector.type == 0 then -- 全流量选择器
selector_pass = true
else
selector_pass = judge_util.judge_selector(selector, "dynamic_upstream")-- selector judge
end
if selector_pass then
if selector.handle and selector.handle.log == true then
ngx.log(ngx.INFO, "[DynamicUpstream][PASS-SELECTOR:", sid, "] ", ngx_var_uri)
end
local stop = filter_rules(sid, "dynamic_upstream", ngx_var_uri)
if stop then -- 不再执行此插件其他逻辑
return
end
else
if selector.handle and selector.handle.log == true then
ngx.log(ngx.INFO, "[DynamicUpstream][NOT-PASS-SELECTOR:", sid, "] ", ngx_var_uri)
end
end
-- if continue or break the loop
if selector.handle and selector.handle.continue == true then
-- continue next selector
else
break
end
end
end
end
return DynamicUpstreamHandler
|
local pairs = pairs
local ipairs = ipairs
local ngx_re_sub = ngx.re.sub
local ngx_re_find = ngx.re.find
local string_sub = string.sub
local orange_db = require("orange.store.orange_db")
local judge_util = require("orange.utils.judge")
local extractor_util = require("orange.utils.extractor")
local handle_util = require("orange.utils.handle")
local headers_util = require("orange.utils.headers")
local BasePlugin = require("orange.plugins.base_handler")
local ngx_set_uri_args = ngx.req.set_uri_args
local ngx_decode_args = ngx.decode_args
local function ngx_set_uri(uri,rule_handle)
ngx.var.upstream_host = rule_handle.host and rule_handle.host or ngx.var.host
ngx.var.upstream_url = rule_handle.upstream_name
ngx.var.upstream_request_uri = uri .. '?' .. ngx.encode_args(ngx.req.get_uri_args())
ngx.log(ngx.INFO, '[DynamicUpstream][upstream request][http://', ngx.var.upstream_url, ngx.var.upstream_request_uri, ']')
end
local function filter_rules(sid, plugin, ngx_var_uri)
local rules = orange_db.get_json(plugin .. ".selector." .. sid .. ".rules")
if not rules or type(rules) ~= "table" or #rules <= 0 then
return false
end
for i, rule in ipairs(rules) do
if rule.enable == true then
ngx.log(ngx.INFO, "==[DynamicUpstream][rule name:", rule.name, "][rule id:", rule.id, ']')
-- judge阶段
local pass = judge_util.judge_rule(rule, "dynamic_upstream")
-- handle阶段
if pass then
-- extract阶段
headers_util:set_headers(rule)
local variables = extractor_util.extract_variables(rule.extractor)
local handle = rule.handle
if handle and handle.uri_tmpl and handle.upstream_name then
local to_rewrite = handle_util.build_uri(rule.extractor.type, handle.uri_tmpl, variables)
if to_rewrite then
if handle.log == true then
ngx.log(ngx.INFO, "[DynamicUpstream] ", ngx_var_uri, " to:", to_rewrite)
end
local from, to, err = ngx_re_find(to_rewrite, "[?]{1}", "jo")
if not err and from and from >= 1 then
--local qs = ngx_re_sub(to_rewrite, "[A-Z0-9a-z-_/]*[%?]{1}", "", "jo")
local qs = string_sub(to_rewrite, from + 1)
if qs then
-- save original query params
-- ngx_set_uri_args(ngx.req.get_uri_args())
-- not use above just to keep the same behavior with nginx `rewrite` instruct
local args = ngx_decode_args(qs, 0)
if args then
ngx_set_uri_args(args)
end
end
to_rewrite = string_sub(to_rewrite, 1, from - 1)
end
ngx_set_uri(to_rewrite, handle)
return true
end
end
return true
end
end
end
return false
end
local DynamicUpstreamHandler = BasePlugin:extend()
DynamicUpstreamHandler.PRIORITY = 2000
function DynamicUpstreamHandler:new(store)
DynamicUpstreamHandler.super.new(self, "dynamic-upstream-plugin")
self.store = store
end
function DynamicUpstreamHandler:rewrite(conf)
DynamicUpstreamHandler.super.rewrite(self)
local enable = orange_db.get("dynamic_upstream.enable")
local meta = orange_db.get_json("dynamic_upstream.meta")
local selectors = orange_db.get_json("dynamic_upstream.selectors")
local ordered_selectors = meta and meta.selectors
if not enable or enable ~= true or not meta or not ordered_selectors or not selectors then
return
end
local ngx_var_uri = ngx.var.uri
for i, sid in ipairs(ordered_selectors) do
local selector = selectors[sid]
ngx.log(ngx.INFO, "==[DynamicUpstream][START SELECTOR:", sid, ",NAME:",selector.name,']')
if selector and selector.enable == true then
local selector_pass
if selector.type == 0 then -- 全流量选择器
selector_pass = true
else
selector_pass = judge_util.judge_selector(selector, "dynamic_upstream")-- selector judge
end
if selector_pass then
if selector.handle and selector.handle.log == true then
ngx.log(ngx.INFO, "[DynamicUpstream][PASS-SELECTOR:", sid, "] ", ngx_var_uri)
end
local stop = filter_rules(sid, "dynamic_upstream", ngx_var_uri)
if stop then -- 不再执行此插件其他逻辑
return
end
else
if selector.handle and selector.handle.log == true then
ngx.log(ngx.INFO, "[DynamicUpstream][NOT-PASS-SELECTOR:", sid, "] ", ngx_var_uri)
end
end
-- if continue or break the loop
if selector.handle and selector.handle.continue == true then
-- continue next selector
else
break
end
end
end
end
return DynamicUpstreamHandler
|
fix & modify dynamic_upstream
|
fix & modify dynamic_upstream
1. keep the behavior with rewrite ins
2. fix copy bug: not to rewrite whtn to_rewrite equals to uri
3. test case :
添加两个规则,规则中配置处理一栏:
1. /notso/${1}/2ad%20fa/hha dd/?name=11 2223&ab=1c, ${1}
表示变量提取式,可以随意配置一个。
2. /gooda/
requrest:
http://192.168.110.137/hhhe?aafad=1
http://192.168.110.137/good?normal=1
|
Lua
|
mit
|
thisverygoodhhhh/orange,thisverygoodhhhh/orange,thisverygoodhhhh/orange
|
dd2393834d65fbcdfec44033bdbcbb2e302b14c7
|
vanilla/v/request.lua
|
vanilla/v/request.lua
|
-- Request moudle
-- @since 2015-08-17 10:54
-- @author idevz <[email protected]>
-- version $Id$
-- perf
local error = error
local pairs = pairs
local pcall = pcall
local setmetatable = setmetatable
local Reqargs = require 'vanilla.v.libs.reqargs'
local Request = {}
function Request:new()
-- local headers = ngx.req.get_headers()
-- url:http://zj.com:9210/di0000/111?aa=xx
local instance = {
uri = ngx.var.uri, -- /di0000/111
-- req_uri = ngx.var.request_uri, -- /di0000/111?aa=xx
-- req_args = ngx.var.args, -- aa=xx
-- params = params,
-- uri_args = ngx.req.get_uri_args(), -- { aa = "xx" }
-- method = ngx.req.get_method(),
-- headers = headers,
-- body_raw = ngx.req.get_body_data()
}
setmetatable(instance, {__index = self})
return instance
end
-- function Request:getControllerName()
-- return self.controller_name
-- end
-- function Request:getActionName()
-- return self.action_name
-- end
function Request:getHeaders()
if self.headers == nil then self.headers = ngx.req.get_headers() end
return self.headers
end
function Request:getHeader(key)
return self:getHeaders()[key]
end
function Request:buildParams()
local GET, POST, FILE = Reqargs:getRequestData({})
local params = {}
params['VA_GET'] = GET
params['VA_POST'] = POST
if #FILE >= 1 then params['VA_FILE']=FILE end
for k,v in pairs(GET) do params[k] = v end
for k,v in pairs(POST) do params[k] = v end
self.params = params
return self.params
end
function Request:GET()
if self.params ~= nil then return self.params.VA_GET end
return self:buildParams()['VA_GET']
end
function Request:POST()
if self.params ~= nil then return self.params.VA_POST end
return self:buildParams()['VA_POST']
end
function Request:FILE()
if self.params ~= nil then return self.params.VA_FILE end
return self:buildParams()['VA_FILE']
end
function Request:getMethod()
if self.method == nil then self.method = ngx.req.get_method() end
return self.method
end
function Request:getParams()
return self.params or self:buildParams()
end
function Request:getParam(key)
if self.params ~= nil then return self.params[key] end
return self:buildParams()[key]
end
function Request:setParam(key, value)
self.params[key] = value
end
function Request:isGet()
if self:getMethod() == 'GET' then return true else return false end
end
return Request
|
-- Request moudle
-- @since 2015-08-17 10:54
-- @author idevz <[email protected]>
-- version $Id$
-- perf
local error = error
local pairs = pairs
local pcall = pcall
local setmetatable = setmetatable
local Reqargs = require 'vanilla.v.libs.reqargs'
local Request = {}
function Request:new()
-- local headers = ngx.req.get_headers()
-- url:http://zj.com:9210/di0000/111?aa=xx
local instance = {
uri = ngx.var.uri, -- /di0000/111
-- req_uri = ngx.var.request_uri, -- /di0000/111?aa=xx
-- req_args = ngx.var.args, -- aa=xx
-- params = params,
-- uri_args = ngx.req.get_uri_args(), -- { aa = "xx" }
-- method = ngx.req.get_method(),
-- headers = headers,
-- body_raw = ngx.req.get_body_data()
}
setmetatable(instance, {__index = self})
return instance
end
-- function Request:getControllerName()
-- return self.controller_name
-- end
-- function Request:getActionName()
-- return self.action_name
-- end
function Request:getHeaders()
if self.headers == nil then self.headers = ngx.req.get_headers() end
return self.headers
end
function Request:getHeader(key)
return self:getHeaders()[key]
end
function Request:buildParams()
local GET, POST, FILE = Reqargs:getRequestData({})
local params = {}
params['VA_GET'] = GET
params['VA_POST'] = POST
if #FILE >= 1 then params['VA_FILE']=FILE end
for k,v in pairs(GET) do params[k] = v end
for k,v in pairs(POST) do params[k] = v end
self.params = params
return self.params
end
function Request:GET()
if self.params ~= nil then return self.params.VA_GET end
return self:buildParams()['VA_GET']
end
function Request:POST()
if self.params ~= nil then return self.params.VA_POST end
return self:buildParams()['VA_POST']
end
function Request:FILE()
if self.params ~= nil then return self.params.VA_FILE end
return self:buildParams()['VA_FILE']
end
function Request:getMethod()
if self.method == nil then self.method = ngx.req.get_method() end
return self.method
end
function Request:getParams()
return self.params or self:buildParams()
end
function Request:getParam(key)
if self.params ~= nil then return self.params[key] end
return self:buildParams()[key]
end
function Request:setParam(key, value)
if self.params == nil then self:buildParams() end
self.params[key] = value
end
function Request:isGet()
if self:getMethod() == 'GET' then return true else return false end
end
return Request
|
fix a request bug
|
fix a request bug
|
Lua
|
mit
|
idevz/vanilla,idevz/vanilla
|
37b2744dca46248abc48eb6aa724cb0e9b7955f7
|
src/Script.lua
|
src/Script.lua
|
local System = require 'System'
local Target = require 'Target'
local P = {}
local function write_pkg_var(w, prefix, name, value)
if not value then return end
local tp = type(value)
if tp == 'string' or tp == 'number' then
w("pkg_%s%s='%s'", prefix, name, value)
elseif tp == 'boolean' then
w("pkg_%s%s='yes'", prefix, name)
elseif tp == 'table' then
local values = table.ivalues(value)
if #values > 0 then
w("pkg_%s%s='%s'", prefix, name, table.concat(values, '\n'))
end
local keys = sort(table.keys(value))
for k in each(keys) do
write_pkg_var(w, prefix..name, '_'..k, value[k])
end
else
error(string.format('unable to write variable %s (%s)', name, tp))
end
end
local function write_common(w, pkg)
local function write_var(name, value)
return write_pkg_var(w, '', name, value)
end
local predefined_keys = {
'build',
'config',
'configs',
'contexts',
'export',
'install',
'name',
'pass_template',
'patches',
'requires',
'source',
'stages',
'template',
'use',
}
local function custom_keys(_, key)
return type(key) ~= 'number' and
not find(function (k) return k == key end, predefined_keys)
end
local names = {}
for k, v in iter(pkg, filter(custom_keys)) do
table.insert(names, k)
end
table.sort(names)
for name in each(names) do
write_var(name, pkg[name])
end
end
local function write_source(w, pkg)
local source = pkg.source
if not source then return end
local function write_var(name, value)
return write_pkg_var(w, 'source_', name, value)
end
local names = sort(table.keys(source))
if source.type and source.location then
w("pkg_source='%s %s'", source.type, source.location)
end
for name in each(names) do
write_var(name, source[name])
end
end
local function write_patches(w, pkg)
local patches = pkg.patches
if not patches then return end
local function write_var(name, value)
return write_pkg_var(w, 'patches_', name, value)
end
local names = sort(table.keys(patches))
for name in each(names) do
write_var(name, patches[name])
end
if #patches > 0 then
assert(patches.required and #patches == #patches.required)
w('jagen_pkg_apply_patches() {')
for i, item in ipairs(patches) do
local name = item[1]
local strip = item[2]
w(' pkg_run_patch %d "%s"', strip, patches.required[i])
end
w('}')
end
end
local function write_build(w, pkg)
local build = pkg.build
if not build then return end
local function write_var(name, value)
return write_pkg_var(w, 'build_', name, value)
end
local names = sort(table.keys(build))
for name in each(names) do
write_var(name, build[name])
end
end
local function write_install(w, pkg)
local install = pkg.install
if not install then return end
local function write_var(name, value)
return write_pkg_var(w, 'install_', name, value)
end
local names = sort(table.keys(install))
for name in each(names) do
write_var(name, install[name])
end
end
local function write_export(w, pkg, config)
local export = pkg.export
if not export then return end
local prefix = 'export_'
if config then
prefix = string.format('_%s__%s', config, prefix)
end
local function write_var(name, value)
return write_pkg_var(w, prefix, name, value)
end
local names = sort(table.keys(export))
for name in each(names) do
write_var(name, export[name])
end
end
local function write_use(w, pkg, config)
local use = pkg.use
if not use then return end
prefix = ''
if config then
prefix = string.format('_%s__', config)
end
local function write_var(name, value)
return write_pkg_var(w, prefix, name, value)
end
local specs, names = sort(use), {}
for spec in each(specs) do
local use = Target.from_use(spec)
append(names, use.name)
if use.alias then
write_var('alias_'..string.to_identifier(use.alias),
string.to_identifier(use.name))
end
end
write_var('use', names)
end
local function generate_script(filename, pkg, config)
local lines = {}
local function w(format, ...)
table.insert(lines, string.format(format, ...))
end
write_common(w, pkg)
write_source(w, pkg)
write_patches(w, pkg)
-- write install first to allow referencing install dir from build options
write_install(w, pkg)
write_build(w, pkg)
-- should be the last to allow referencing other variables
write_export(w, pkg, config)
write_use(w, pkg, config)
if #lines > 0 then
local file = assert(io.open(filename, 'w+'))
file:write(table.concat(lines, '\n'), '\n')
file:close()
end
end
function P:generate(pkg, dir)
local filename = System.mkpath(dir, string.format('%s.sh', pkg.name))
generate_script(filename, pkg)
for name, config in pairs(pkg.configs) do
filename = System.mkpath(dir, string.format('%s__%s.sh', pkg.name, name))
generate_script(filename, config, name)
end
end
return P
|
local System = require 'System'
local Target = require 'Target'
local P = {}
local function write_pkg_var(w, prefix, name, value)
if not value then return end
local tp = type(value)
if tp == 'string' or tp == 'number' then
w("pkg_%s%s='%s'", prefix, name, value)
elseif tp == 'boolean' then
w("pkg_%s%s='yes'", prefix, name)
elseif tp == 'table' then
local values = table.ivalues(value)
if #values > 0 then
w("pkg_%s%s='%s'", prefix, name, table.concat(values, '\n'))
end
local keys = sort(table.keys(value))
for k in each(keys) do
write_pkg_var(w, prefix..name, '_'..k, value[k])
end
else
error(string.format('unable to write variable %s (%s)', name, tp))
end
end
local function write_common(w, pkg)
local function write_var(name, value)
return write_pkg_var(w, '', name, value)
end
local predefined_keys = {
'build',
'config',
'configs',
'contexts',
'export',
'install',
'name',
'pass_template',
'patches',
'requires',
'source',
'stages',
'template',
'use',
}
local function custom_keys(_, key)
return type(key) ~= 'number' and
not find(function (k) return k == key end, predefined_keys)
end
local names = {}
for k, v in iter(pkg, filter(custom_keys)) do
table.insert(names, k)
end
table.sort(names)
for name in each(names) do
write_var(name, pkg[name])
end
end
local function write_source(w, pkg)
local source = pkg.source
if not source then return end
local function write_var(name, value)
return write_pkg_var(w, 'source_', name, value)
end
local names = sort(table.keys(source))
if source.type and source.location then
w("pkg_source='%s %s'", source.type, source.location)
end
for name in each(names) do
write_var(name, source[name])
end
end
local function write_patches(w, pkg)
local patches = pkg.patches
if not patches then return end
local function write_var(name, value)
return write_pkg_var(w, 'patches_', name, value)
end
local names = sort(table.keys(patches))
for name in each(names) do
write_var(name, patches[name])
end
if #patches > 0 then
assert(patches.required and #patches == #patches.required)
w('jagen_pkg_apply_patches() {')
for i, item in ipairs(patches) do
local name = item[1]
local strip = item[2]
w(' pkg_run_patch %d "%s"', strip, patches.required[i])
end
w('}')
end
end
local function write_build(w, pkg)
local build = pkg.build
if not build then return end
local function write_var(name, value)
return write_pkg_var(w, 'build_', name, value)
end
local names = sort(table.keys(build))
for name in each(names) do
write_var(name, build[name])
end
end
local function write_install(w, pkg)
local install = pkg.install
if not install then return end
local function write_var(name, value)
return write_pkg_var(w, 'install_', name, value)
end
local names = sort(table.keys(install))
for name in each(names) do
write_var(name, install[name])
end
end
local function write_export(w, pkg, config)
local export = pkg.export
if not export then return end
local prefix = 'export_'
if config then
prefix = string.format('_%s__%s', config, prefix)
end
local function write_var(name, value)
return write_pkg_var(w, prefix, name, value)
end
local names = sort(table.keys(export))
for name in each(names) do
write_var(name, export[name])
end
end
local function write_use(w, pkg, config)
local use = pkg.use
if not use then return end
prefix = ''
if config then
prefix = string.format('_%s__', config)
end
local function write_var(name, value)
return write_pkg_var(w, prefix, name, value)
end
local names, targets = {}, sort(map(Target.from_use, use),
function (a, b) return a.name < b.name end)
for target in each(targets) do
append(names, target.name)
if target.alias then
write_var('alias_'..string.to_identifier(target.alias),
string.to_identifier(target.name))
end
end
write_var('use', names)
end
local function generate_script(filename, pkg, config)
local lines = {}
local function w(format, ...)
table.insert(lines, string.format(format, ...))
end
write_common(w, pkg)
write_source(w, pkg)
write_patches(w, pkg)
-- write install first to allow referencing install dir from build options
write_install(w, pkg)
write_build(w, pkg)
-- should be the last to allow referencing other variables
write_export(w, pkg, config)
write_use(w, pkg, config)
if #lines > 0 then
local file = assert(io.open(filename, 'w+'))
file:write(table.concat(lines, '\n'), '\n')
file:close()
end
end
function P:generate(pkg, dir)
local filename = System.mkpath(dir, string.format('%s.sh', pkg.name))
generate_script(filename, pkg)
for name, config in pairs(pkg.configs) do
filename = System.mkpath(dir, string.format('%s__%s.sh', pkg.name, name))
generate_script(filename, config, name)
end
end
return P
|
Fix handling of use aliases when generating scripts
|
Fix handling of use aliases when generating scripts
|
Lua
|
mit
|
bazurbat/jagen
|
71cdfd067e05ab1f07b369ca26b1acf73e9a61f1
|
src/state.lua
|
src/state.lua
|
-- maintains a state of the assert engine in a linked-list fashion
-- records; formatters, parameters, spies and stubs
local state_mt = {
__call = function(self)
self:revert()
end
}
local nilvalue = {} -- unique ID to refer to nil values for parameters
-- will hold the current state
local current
-- exported module table
local state = {}
------------------------------------------------------
-- Reverts to a (specific) snapshot.
-- @param self (optional) the snapshot to revert to. If not provided, it will revert to the last snapshot.
state.revert = function(self)
if not self then
-- no snapshot given, so move 1 up
self = current
if not self.previous then
-- top of list, no previous one, nothing to do
return
end
end
if getmetatable(self) ~= state_mt then error("Value provided is not a valid snapshot", 2) end
if self.next then
self.next:revert()
end
-- revert formatters in 'last'
self.formatters = {}
-- revert parameters in 'last'
self.parameters = {}
-- revert spies/stubs in 'last'
while #self.spies > 0 do
local s = table.remove(self.spies)
s:revert()
end
setmetatable(self, nil) -- invalidate as a snapshot
current = self.previous
current.next = nil
end
------------------------------------------------------
-- Creates a new snapshot.
-- @return snapshot table
state.snapshot = function()
local s = current
local new = setmetatable ({
formatters = {},
parameters = {},
spies = {},
previous = current,
revert = state.revert,
}, state_mt)
if current then current.next = new end
current = new
return current
end
-- FORMATTERS
state.add_formatter = function(callback)
table.insert(current.formatters, 1, callback)
end
state.remove_formatter = function(callback, s)
s = s or current
for i, v in ipairs(s.formatters) do
if v == callback then
table.remove(s.formatters, i)
break
end
end
-- wasn't found, so traverse up 1 state
if s.previous then
state.remove_formatter(callback, s.previous)
end
end
state.format_argument = function(val, s, fmtargs)
s = s or current
for _, fmt in ipairs(s.formatters) do
local valfmt = fmt(val, fmtargs)
if valfmt ~= nil then return valfmt end
end
-- nothing found, check snapshot 1 up in list
if s.previous then
return state.format_argument(val, s.previous, fmtargs)
end
return nil -- end of list, couldn't format
end
-- PARAMETERS
state.set_parameter = function(name, value)
if value == nil then value = nilvalue end
current.parameters[name] = value
end
state.get_parameter = function(name, s)
s = s or current
local val = s.parameters[name]
if val == nil and s.previous then
-- not found, so check 1 up in list
return state.get_parameter(name, s.previous)
end
if val ~= nilvalue then
return val
end
return nil
end
-- SPIES / STUBS
state.add_spy = function(spy)
table.insert(current.spies, spy)
end
state.snapshot() -- create initial state
return state
|
-- maintains a state of the assert engine in a linked-list fashion
-- records; formatters, parameters, spies and stubs
local state_mt = {
__call = function(self)
self:revert()
end
}
local spies_mt = { __mode = "kv" }
local nilvalue = {} -- unique ID to refer to nil values for parameters
-- will hold the current state
local current
-- exported module table
local state = {}
------------------------------------------------------
-- Reverts to a (specific) snapshot.
-- @param self (optional) the snapshot to revert to. If not provided, it will revert to the last snapshot.
state.revert = function(self)
if not self then
-- no snapshot given, so move 1 up
self = current
if not self.previous then
-- top of list, no previous one, nothing to do
return
end
end
if getmetatable(self) ~= state_mt then error("Value provided is not a valid snapshot", 2) end
if self.next then
self.next:revert()
end
-- revert formatters in 'last'
self.formatters = {}
-- revert parameters in 'last'
self.parameters = {}
-- revert spies/stubs in 'last'
for s,_ in pairs(self.spies) do
self.spies[s] = nil
s:revert()
end
setmetatable(self, nil) -- invalidate as a snapshot
current = self.previous
current.next = nil
end
------------------------------------------------------
-- Creates a new snapshot.
-- @return snapshot table
state.snapshot = function()
local s = current
local new = setmetatable ({
formatters = {},
parameters = {},
spies = setmetatable({}, spies_mt),
previous = current,
revert = state.revert,
}, state_mt)
if current then current.next = new end
current = new
return current
end
-- FORMATTERS
state.add_formatter = function(callback)
table.insert(current.formatters, 1, callback)
end
state.remove_formatter = function(callback, s)
s = s or current
for i, v in ipairs(s.formatters) do
if v == callback then
table.remove(s.formatters, i)
break
end
end
-- wasn't found, so traverse up 1 state
if s.previous then
state.remove_formatter(callback, s.previous)
end
end
state.format_argument = function(val, s, fmtargs)
s = s or current
for _, fmt in ipairs(s.formatters) do
local valfmt = fmt(val, fmtargs)
if valfmt ~= nil then return valfmt end
end
-- nothing found, check snapshot 1 up in list
if s.previous then
return state.format_argument(val, s.previous, fmtargs)
end
return nil -- end of list, couldn't format
end
-- PARAMETERS
state.set_parameter = function(name, value)
if value == nil then value = nilvalue end
current.parameters[name] = value
end
state.get_parameter = function(name, s)
s = s or current
local val = s.parameters[name]
if val == nil and s.previous then
-- not found, so check 1 up in list
return state.get_parameter(name, s.previous)
end
if val ~= nilvalue then
return val
end
return nil
end
-- SPIES / STUBS
state.add_spy = function(spy)
current.spies[spy] = true
end
state.snapshot() -- create initial state
return state
|
Save spies to weak table
|
Save spies to weak table
This allows spies to be garbage collected without needing to revert the
current snapshot. Fixes a memory leak if a snapshot is never reverted.
|
Lua
|
mit
|
o-lim/luassert,ZyX-I/luassert
|
ed5c06edaf8172891586e9f1ad0e90b7359d9223
|
lib/resty/template.lua
|
lib/resty/template.lua
|
-- Copyright (C) 2015 Lloyd Zhou
local _M = { _VERSION = '0.1' }
local mt = {__index = _M}
function _M.new(callback, minify, tags)
tags = ("table" == type(tags) and 4 == #tags) and tags or {"{{", "}}", "{%%", "%%}"}
return setmetatable({
callback = callback or (nil == ngx and io.write or ngx.print),
minify = minify or false,
replace_templae = {
["\\"] = "\\\\",
--["\n"] = "\\n",
--["\r"] = "\\r",
["'"] = "\'",
['"'] = "\"",
[tags[1]] = "]=]_(",
[tags[2]] = ")_[=[",
[tags[3]] = "]=] ",
[tags[4]] = " _[=["
},
cache = {}
}, mt)
end
function _M.parse(self, tmpl, minify)
-- see https://github.com/dannote/lua-template
for k, v in pairs(self.replace_templae) do
tmpl = tmpl:gsub(k, v)
end
local str = "return function(_) _[=[" .. tmpl .. "]=] end"
return minify and str:gsub("%s+", " ") or str
end
function _M.compile(self, tmpl, minify)
local key = nil == ngx and tmpl or ngx.md5(tmpl)
self.cache[tmpl] = self.cache[tmpl] or loadstring(_M.parse(self, tmpl, minify))()
return self.cache[tmpl]
end
-- can render compiled function or template string
function _M.render(self, tmpl, data, callback, minify)
local compile = type(tmpl) == "function" and tmpl or _M.compile(self, tmpl, minify or self.minify)
setmetatable(data, {__index = _G})
setfenv(compile, data)
return compile(callback or self.callback)
end
setmetatable(_M, {__call = function(self, ...) return _M.render(_M.new(), ...) end})
return _M
|
-- Copyright (C) 2015 Lloyd Zhou
local _M = { _VERSION = '0.1' }
local mt = {__index = _M}
function _M.new(callback, minify, tags, cacheable)
tags = ("table" == type(tags) and 4 == #tags) and tags or {"{{", "}}", "{%%", "%%}"}
return setmetatable({
callback = callback or (nil == ngx and io.write or ngx.print),
minify = minify or false,
cacheable = cacheable or true,
replace_templae = {
["\\"] = "\\\\",
["'"] = "\'",
['"'] = "\"",
[tags[1]] = "]=]_(",
[tags[2]] = ")_[=[",
[tags[3]] = "]=] ",
[tags[4]] = " _[=["
},
cache = {}
}, mt)
end
function _M.parse(self, tmpl, minify)
-- see https://github.com/dannote/lua-template
for k, v in pairs(self.replace_templae) do
tmpl = tmpl:gsub(k, v)
end
local str = "return function(_) _[=[" .. tmpl .. "]=] end"
return minify and str:gsub("%s+", " ") or str
end
function _M.compile(self, tmpl, minify)
local key = nil == ngx and tmpl or ngx.md5(tmpl)
if self.cacheable then
self.cache[key] = self.cache[key] or loadstring(_M.parse(self, tmpl, minify))()
return self.cache[key]
end
return loadstring(_M.parse(self, tmpl, minify))()
end
-- can render compiled function or template string
function _M.render(self, tmpl, data, callback, minify)
local compile = type(tmpl) == "function" and tmpl or _M.compile(self, tmpl, minify or self.minify)
setmetatable(data, {__index = _G})
setfenv(compile, data)
return compile(callback or self.callback)
end
setmetatable(_M, {__call = function(self, ...) return _M.render(_M.new(), ...) end})
return _M
|
fixed bug for cache compiled template
|
fixed bug for cache compiled template
|
Lua
|
mit
|
lloydzhou/lua-resty-tmpl,lloydzhou/lua-resty-template
|
ddbd7088587167cf62d9d5b9579764f3d20d6b48
|
tests/file.lua
|
tests/file.lua
|
di:load_plugin("./plugins/file/di_file.so")
unpack = table.unpack or unpack
md = di.spawn:run({"mkdir", "testdir"}, true)
md:once("exit", function()
w = di.file:watch({"testdir"})
function sigh(ev)
return function(name, path)
print("event: "..ev, name, path)
end
end
events = {"create", "access", "attrib", "close-write", "close-nowrite",
"delete", "delete-self", "modify", "move-self", "open",
"moved-to", "moved-from"}
listen_handles = {}
for _, i in pairs(events) do
handle = w:on(i, sigh(i))
handle:auto_stop(1)
table.insert(listen_handles, handle)
end
fname = "./testdir/testfile"
f = di.log:file_target(fname, false)
f:write("Test")
f = nil
collectgarbage()
cmds = {
{"touch", fname},
{"cat", fname},
{"mv", fname, fname.."1"},
{"rm", fname.."1"},
{"rmdir", "./testdir"},
{"echo", "finished"}
}
function run_one(i)
return function()
print("running ", unpack(cmds[i]))
c = di.spawn:run(cmds[i], true)
if i < #cmds then
c:once("exit", run_one(i+1))
else
w:remove("testdir")
w = nil
listen_handles = nil
collectgarbage()
end
end
end
run_one(1)()
end)
md = nil
collectgarbage()
|
di:load_plugin("./plugins/file/di_file.so")
unpack = table.unpack or unpack
md = di.spawn:run({"mkdir", "testdir"}, true)
md:once("exit", function()
w = di.file:watch({"testdir"})
event_count = 0
function sigh(ev)
return function(name, path)
print("event: "..ev, name, path)
event_count = event_count + 1
if event_count == 14 then
print("all events received")
listen_handles = nil
collectgarbage()
end
end
end
events = {"create", "access", "attrib", "close-write", "close-nowrite",
"delete", "delete-self", "modify", "move-self", "open",
"moved-to", "moved-from"}
listen_handles = {}
for _, i in pairs(events) do
local handle = w:on(i, sigh(i))
handle:auto_stop(1)
table.insert(listen_handles, handle)
end
fname = "./testdir/testfile"
f = di.log:file_target(fname, false)
f:write("Test")
f = nil
collectgarbage()
cmds = {
{"touch", fname},
{"cat", fname},
{"mv", fname, fname.."1"},
{"rm", fname.."1"},
{"rmdir", "./testdir"},
{"echo", "finished"}
}
function run_one(i)
return function()
print("running ", unpack(cmds[i]))
local c = di.spawn:run(cmds[i], true)
if i < #cmds then
c:once("exit", run_one(i+1))
end
end
end
run_one(1)()
end)
md = nil
collectgarbage()
|
tests: fix file.lua hang
|
tests: fix file.lua hang
Signed-off-by: Yuxuan Shui <[email protected]>
|
Lua
|
mpl-2.0
|
yshui/deai,yshui/deai,yshui/deai
|
527e7b367446f79bc0f7c03b8f949cf37ee9cc87
|
core/lfs_ext.lua
|
core/lfs_ext.lua
|
-- Copyright 2007-2016 Mitchell mitchell.att.foicica.com. See LICENSE.
--[[ This comment is for LuaDoc.
---
-- Extends the `lfs` library to find files in directories and determine absolute
-- file paths.
module('lfs')]]
---
-- The filter table containing common binary file extensions and version control
-- directories to exclude when iterating over files and directories using
-- `dir_foreach`.
-- @see dir_foreach
-- @class table
-- @name default_filter
lfs.default_filter = {
extensions = {
'a', 'bmp', 'bz2', 'class', 'dll', 'exe', 'gif', 'gz', 'jar', 'jpeg', 'jpg',
'o', 'pdf', 'png', 'so', 'tar', 'tgz', 'tif', 'tiff', 'xz', 'zip'
},
folders = {'%.bzr$', '%.git$', '%.hg$', '%.svn$'}
}
local lfs_symlinkattributes = lfs.symlinkattributes
-- Determines whether or not the given file matches the given filter.
-- @param file The filename.
-- @param filter The filter table.
-- @return boolean `true` or `false`.
local function exclude(file, filter)
if not filter then return false end
local ext = filter.extensions
if ext and ext[file:match('[^%.]+$')] then return true end
for i = 1, #filter do
local patt = filter[i]
if patt:sub(1, 1) ~= '!' then
if file:find(patt) then return true end
else
if not file:find(patt:sub(2)) then return true end
end
end
return filter.symlink and lfs_symlinkattributes(file, 'mode') == 'link'
end
---
-- Iterates over all files and sub-directories (up to *n* levels deep) in
-- directory *dir*, calling function *f* with each file found.
-- Files passed to *f* do not match any pattern in string or table *filter*
-- (or `lfs.default_filter` when *filter* is `nil`). A filter table contains:
--
-- + Lua patterns that match filenames to exclude.
-- + Optional `folders` sub-table that contains patterns matching directories
-- to exclude.
-- + Optional `extensions` sub-table that contains raw file extensions to
-- exclude.
-- + Optional `symlink` flag that when `true`, excludes symlinked files (but
-- not symlinked directories).
-- + Optional `folders.symlink` flag that when `true`, excludes symlinked
-- directories.
--
-- Any filter patterns starting with '!' exclude files and directories that do
-- not match the pattern that follows.
-- @param dir The directory path to iterate over.
-- @param f Function to call with each full file path found. If *f* returns
-- `false` explicitly, iteration ceases.
-- @param filter Optional filter for files and directories to exclude. The
-- default value is `lfs.default_filter`.
-- @param n Optional maximum number of directory levels to descend into.
-- The default value is `nil`, which indicates no limit.
-- @param include_dirs Optional flag indicating whether or not to call *f* with
-- directory names too. Directory names are passed with a trailing '/' or '\',
-- depending on the current platform.
-- The default value is `false`.
-- @param level Utility value indicating the directory level this function is
-- at. This value is used and set internally, and should not be set otherwise.
-- @see filter
-- @name dir_foreach
function lfs.dir_foreach(dir, f, filter, n, include_dirs, level)
if not level then level = 0 end
if level == 0 then
-- Convert filter to a table from nil or string arguments.
if not filter then filter = lfs.default_filter end
if type(filter) == 'string' then filter = {filter} end
-- Create file extension filter hash table for quick lookups.
local ext = filter.extensions
if ext then for i = 1, #ext do ext[ext[i]] = true end end
end
local dir_sep, lfs_attributes = not WIN32 and '/' or '\\', lfs.attributes
for basename in lfs.dir(dir) do
if not basename:find('^%.%.?$') then -- ignore . and ..
local filename = dir..(dir ~= '/' and dir_sep or '')..basename
local mode = lfs_attributes(filename, 'mode')
if mode == 'directory' and not exclude(filename, filter.folders) then
if include_dirs and f(filename..dir_sep) == false then return end
if not n or level < n then
lfs.dir_foreach(filename, f, filter, n, include_dirs, level + 1)
end
elseif mode == 'file' and not exclude(filename, filter) then
if f(filename) == false then return end
end
end
end
end
---
-- Returns the absolute path to string *filename*.
-- *prefix* or `lfs.currentdir()` is prepended to a relative filename. The
-- returned path is not guaranteed to exist.
-- @param filename The relative or absolute path to a file.
-- @param prefix Optional prefix path prepended to a relative filename.
-- @return string absolute path
-- @name abspath
function lfs.abspath(filename, prefix)
if WIN32 then filename = filename:gsub('/', '\\') end
if not filename:find(not WIN32 and '^/' or '^%a:[/\\]') and
not (WIN32 and filename:find('^\\\\')) then
prefix = prefix or lfs.currentdir()
filename = prefix..(not WIN32 and '/' or '\\')..filename
end
filename = filename:gsub('%f[^/\\]%.[/\\]', '') -- clean up './'
while filename:find('[^/\\]+[/\\]%.%.[/\\]') do
filename = filename:gsub('[^/\\]+[/\\]%.%.[/\\]', '', 1) -- clean up '../'
end
return filename
end
|
-- Copyright 2007-2016 Mitchell mitchell.att.foicica.com. See LICENSE.
--[[ This comment is for LuaDoc.
---
-- Extends the `lfs` library to find files in directories and determine absolute
-- file paths.
module('lfs')]]
---
-- The filter table containing common binary file extensions and version control
-- directories to exclude when iterating over files and directories using
-- `dir_foreach`.
-- @see dir_foreach
-- @class table
-- @name default_filter
lfs.default_filter = {
extensions = {
'a', 'bmp', 'bz2', 'class', 'dll', 'exe', 'gif', 'gz', 'jar', 'jpeg', 'jpg',
'o', 'pdf', 'png', 'so', 'tar', 'tgz', 'tif', 'tiff', 'xz', 'zip'
},
folders = {'%.bzr$', '%.git$', '%.hg$', '%.svn$', 'node_modules'}
}
local lfs_symlinkattributes = lfs.symlinkattributes
-- Determines whether or not the given file matches the given filter.
-- @param file The filename.
-- @param filter The filter table.
-- @return boolean `true` or `false`.
local function exclude(file, filter)
if not filter then return false end
local ext = filter.extensions
if ext and ext[file:match('[^%.]+$')] then return true end
for i = 1, #filter do
local patt = filter[i]
if patt:sub(1, 1) ~= '!' then
if file:find(patt) then return true end
else
if not file:find(patt:sub(2)) then return true end
end
end
return filter.symlink and lfs_symlinkattributes(file, 'mode') == 'link'
end
---
-- Iterates over all files and sub-directories (up to *n* levels deep) in
-- directory *dir*, calling function *f* with each file found.
-- Files passed to *f* do not match any pattern in string or table *filter*
-- (or `lfs.default_filter` when *filter* is `nil`). A filter table contains:
--
-- + Lua patterns that match filenames to exclude.
-- + Optional `folders` sub-table that contains patterns matching directories
-- to exclude.
-- + Optional `extensions` sub-table that contains raw file extensions to
-- exclude.
-- + Optional `symlink` flag that when `true`, excludes symlinked files (but
-- not symlinked directories).
-- + Optional `folders.symlink` flag that when `true`, excludes symlinked
-- directories.
--
-- Any filter patterns starting with '!' exclude files and directories that do
-- not match the pattern that follows.
-- @param dir The directory path to iterate over.
-- @param f Function to call with each full file path found. If *f* returns
-- `false` explicitly, iteration ceases.
-- @param filter Optional filter for files and directories to exclude. The
-- default value is `lfs.default_filter`.
-- @param n Optional maximum number of directory levels to descend into.
-- The default value is `nil`, which indicates no limit.
-- @param include_dirs Optional flag indicating whether or not to call *f* with
-- directory names too. Directory names are passed with a trailing '/' or '\',
-- depending on the current platform.
-- The default value is `false`.
-- @param level Utility value indicating the directory level this function is
-- at. This value is used and set internally, and should not be set otherwise.
-- @see filter
-- @name dir_foreach
function lfs.dir_foreach(dir, f, filter, n, include_dirs, level)
if not level then level = 0 end
if level == 0 then
-- Convert filter to a table from nil or string arguments.
if not filter then filter = lfs.default_filter end
if type(filter) == 'string' then filter = {filter} end
-- Create file extension filter hash table for quick lookups.
local ext = filter.extensions
if ext then for i = 1, #ext do ext[ext[i]] = true end end
end
local dir_sep, lfs_attributes = not WIN32 and '/' or '\\', lfs.attributes
for basename in lfs.dir(dir) do
if not basename:find('^%.%.?$') then -- ignore . and ..
local filename = dir..(dir ~= '/' and dir_sep or '')..basename
local mode = lfs_attributes(filename, 'mode')
if mode == 'directory' and not exclude(filename, filter.folders) then
if include_dirs and f(filename..dir_sep) == false then return end
if not n or level < n then
local halt = lfs.dir_foreach(filename, f, filter, n, include_dirs,
level + 1) == false
if halt then return false end
end
elseif mode == 'file' and not exclude(filename, filter) then
if f(filename) == false then return false end
end
end
end
end
---
-- Returns the absolute path to string *filename*.
-- *prefix* or `lfs.currentdir()` is prepended to a relative filename. The
-- returned path is not guaranteed to exist.
-- @param filename The relative or absolute path to a file.
-- @param prefix Optional prefix path prepended to a relative filename.
-- @return string absolute path
-- @name abspath
function lfs.abspath(filename, prefix)
if WIN32 then filename = filename:gsub('/', '\\') end
if not filename:find(not WIN32 and '^/' or '^%a:[/\\]') and
not (WIN32 and filename:find('^\\\\')) then
prefix = prefix or lfs.currentdir()
filename = prefix..(not WIN32 and '/' or '\\')..filename
end
filename = filename:gsub('%f[^/\\]%.[/\\]', '') -- clean up './'
while filename:find('[^/\\]+[/\\]%.%.[/\\]') do
filename = filename:gsub('[^/\\]+[/\\]%.%.[/\\]', '', 1) -- clean up '../'
end
return filename
end
|
Fixed inability to effectively halt `lfs.dir_foreach()` loops; core/lfs_ext.lua
|
Fixed inability to effectively halt `lfs.dir_foreach()` loops; core/lfs_ext.lua
|
Lua
|
mit
|
rgieseke/textadept,rgieseke/textadept
|
7f521d2de11a626a9d4498a89260452e736afdea
|
src/nodish/buffer.lua
|
src/nodish/buffer.lua
|
local ffi = require'ffi'
local S = require'syscall'
ffi.cdef[[
void * memcpy(void *restrict dst, const void *restrict src, size_t n);
]]
local types = {
Double = {
ctype = 'double',
size = 8,
},
Float = {
ctype = 'float',
size = 4
},
Int32 = {
ctype = 'uint32_t',
size = 4,
}
}
local tmpBuf = ffi.new('uint8_t[8]')
local methods = {}
for typeName,typeInfo in pairs(types) do
local readName = 'read'..typeName
local ctype = typeInfo.ctype..'*'
local size = typeInfo.size
methods[readName] = function(self)
local val = ffi.cast(ctype,self.pread)[0]
self.pread = self.pread + size
return val
end
local swapRead = function(self)
local pread = self.pread
for i=0,size-1 do
tmpBuf[i] = pread[size-i-1]
end
local val = ffi.cast(ctype,tmpBuf)[0]
self.pread = self.pread + size
return val
end
if ffi.abi('be') then
methods[readName..'BE'] = methods[readName]
methods[readName..'LE'] = swapRead
else
methods[readName..'BE'] = swapRead
methods[readName..'LE'] = methods[readName]
end
end
for typeName,typeInfo in pairs(types) do
local writeName = 'write'..typeName
local size = typeInfo.size
local store = ffi.new(typeInfo.ctype..'[1]')
methods[writeName] = function(self,val)
store[0] = val
ffi.C.memcpy(self.pwrite,store,size)
self.pwrite = self.pwrite + size
end
local swapWrite = function(self)
store[0] = val
for i=0,size-1 do
tmpBuf[i] = store[size-i-1]
end
ffi.C.memcpy(self.pwrite,tmpBuf,size)
self.pwrite = self.pwrite + size
return val
end
if ffi.abi('be') then
methods[writeName..'BE'] = methods[writeName]
methods[writeName..'LE'] = swapWrite
else
methods[writeName..'BE'] = swapWrite
methods[writeName..'LE'] = methods[writeName]
end
end
local mt = {
__index = function(self,key)
if type(key) == 'number' then
return self.buf[key]
else
return methods[key]
end
end,
__newindex = function(self,key,value)
self.buf[key] = value
end
}
local Buffer = function(size)
local buf = ffi.new('uint8_t [?]',size)
local self = {}
self.pwrite = buf + 0
self.pread = buf + 0
self.buf = buf
self.dump = function()
local hex = {}
for i=0,size-1 do
hex[i+1] = string.format('%2x',buf[i])
end
print(table.concat(hex,' '))
end
setmetatable(self,mt)
return self
end
return {
Buffer = Buffer
}
|
local ffi = require'ffi'
local S = require'syscall'
ffi.cdef[[
void * memcpy(void *restrict dst, const void *restrict src, size_t n);
]]
local types = {
Double = {
ctype = 'double',
size = 8,
},
Float = {
ctype = 'float',
size = 4
},
UInt8 = {
ctype = 'uint8_t',
size = 1,
},
UInt16 = {
ctype = 'uint16_t',
size = 2,
},
UInt32 = {
ctype = 'uint32_t',
size = 4,
},
Int8 = {
ctype = 'int8_t',
size = 1,
},
Int16 = {
ctype = 'int16_t',
size = 2,
},
Int32 = {
ctype = 'int32_t',
size = 4,
},
}
local tmpBuf = ffi.new('uint8_t[8]')
local methods = {}
for typeName,typeInfo in pairs(types) do
local readName = 'read'..typeName
local ctype = typeInfo.ctype..'*'
local size = typeInfo.size
methods[readName] = function(self,offset,noAssert)
if not noAssert then
if
return ffi.cast(ctype,self.buf + offset)[0]
end
local swapRead = function(self,offset)
for i=0,size-1 do
tmpBuf[i] = self.buf[size-i-1+offset]
end
return ffi.cast(ctype,tmpBuf)[0]
end
if ffi.abi('be') then
methods[readName..'BE'] = methods[readName]
methods[readName..'LE'] = swapRead
else
methods[readName..'BE'] = swapRead
methods[readName..'LE'] = methods[readName]
end
end
for typeName,typeInfo in pairs(types) do
local writeName = 'write'..typeName
local size = typeInfo.size
local store = ffi.new(typeInfo.ctype..'[1]')
methods[writeName] = function(self,val,offset)
store[0] = val
ffi.C.memcpy(self.buf + offset,store,size)
end
local swapWrite = function(self,val,offset)
store[0] = val
for i=0,size-1 do
tmpBuf[i] = store[size-i-1]
end
ffi.C.memcpy(self.buf + offset,tmpBuf,size)
end
if ffi.abi('be') then
methods[writeName..'BE'] = methods[writeName]
methods[writeName..'LE'] = swapWrite
else
methods[writeName..'BE'] = swapWrite
methods[writeName..'LE'] = methods[writeName]
end
end
local mt = {
__index = function(self,key)
if type(key) == 'number' then
return self.buf[key]
else
return methods[key]
end
end,
__newindex = function(self,key,value)
self.buf[key] = value
end
}
local Buffer = function(size)
local buf = ffi.new('uint8_t [?]',size)
local self = {}
self.buf = buf
self.dump = function()
local hex = {}
for i=0,size-1 do
hex[i+1] = string.format('%2x',buf[i])
end
print(table.concat(hex,' '))
end
setmetatable(self,mt)
return self
end
return {
Buffer = Buffer
}
|
some fixes
|
some fixes
|
Lua
|
mit
|
lipp/nodish
|
c813877b16429a7c56bd009cfe9ab9e9b51ce26a
|
src/cmdrservice/src/Server/CmdrService.lua
|
src/cmdrservice/src/Server/CmdrService.lua
|
--[=[
Bridge to https://eryn.io/Cmdr/
Uses [PermissionService] to provide permissions.
@server
@class CmdrService
]=]
local require = require(script.Parent.loader).load(script)
local HttpService = game:GetService("HttpService")
local PermissionService = require("PermissionService")
local CmdrTemplateProviderServer = require("CmdrTemplateProviderServer")
local Promise = require("Promise")
local CmdrService = {}
local GLOBAL_REGISTRY = setmetatable({}, {__mode = "kv"})
--[=[
Initializes the CmdrService. Should be done via [ServiceBag].
@param serviceBag ServiceBag
]=]
function CmdrService:Init(serviceBag)
assert(not self._cmdr, "Already initialized")
self._serviceBag = assert(serviceBag, "No serviceBag")
self._cmdrTemplateProviderServer = self._serviceBag:GetService(CmdrTemplateProviderServer)
self._serviceId = HttpService:GenerateGUID(false)
self._cmdr = require("Cmdr")
self._permissionService = serviceBag:GetService(PermissionService)
self._definitionData = {}
self._executeData = {}
self._cmdr.Registry:RegisterHook("BeforeRun", function(context)
local providerPromise = self._permissionService:PromisePermissionProvider()
if providerPromise:IsPending() then
return "Still loading permissions"
end
local ok, provider = providerPromise:Yield()
if not ok then
return provider or "Failed to load permission provider"
end
if context.Group == "DefaultAdmin" and not provider:IsAdmin(context.Executor) then
return "You don't have permission to run this command"
end
end)
GLOBAL_REGISTRY[self._serviceId] = self
end
--[=[
Starts the service. Should be done via [ServiceBag]
]=]
function CmdrService:Start()
self._cmdr:RegisterDefaultCommands()
end
--[=[
Returns cmdr
@return Promise<Cmdr>
]=]
function CmdrService:PromiseCmdr()
assert(self._cmdr, "Not initialized")
return Promise.resolved(self._cmdr)
end
--[=[
Registers a command into cmdr.
@param commandData table
@param execute (context: table, ... T)
]=]
function CmdrService:RegisterCommand(commandData, execute)
assert(self._cmdr, "Not initialized")
assert(commandData, "No commandData")
assert(commandData.Name, "No commandData.Name")
assert(execute, "No execute")
local commandId = ("%s_%s"):format(commandData.Name, HttpService:GenerateGUID(false))
self._definitionData[commandId] = commandData
self._executeData[commandId] = execute
local commandServerScript = self._cmdrTemplateProviderServer:Clone("CmdrExecutionTemplate")
commandServerScript.Name = ("%sServer"):format(commandId)
local cmdrServiceTarget = Instance.new("ObjectValue")
cmdrServiceTarget.Name = "CmdrServiceTarget"
cmdrServiceTarget.Value = script
cmdrServiceTarget.Parent = commandServerScript
local cmdrServiceId = Instance.new("StringValue")
cmdrServiceId.Name = "CmdrServiceId"
cmdrServiceId.Value = self._serviceId
cmdrServiceId.Parent = commandServerScript
local cmdrCommandId = Instance.new("StringValue")
cmdrCommandId.Name = "CmdrCommandId"
cmdrCommandId.Value = commandId
cmdrCommandId.Parent = commandServerScript
local commandScript = self._cmdrTemplateProviderServer:Clone("CmdrCommandDefinitionTemplate")
commandScript.Name = commandId
local cmdrJsonCommandData = Instance.new("StringValue")
cmdrJsonCommandData.Value = HttpService:JSONEncode(commandData)
cmdrJsonCommandData.Name = "CmdrJsonCommandData"
cmdrJsonCommandData.Parent = commandScript
self._cmdr.Registry:RegisterCommand(commandScript, commandServerScript)
end
--[=[
Private function used by the execution template to retrieve the execution function.
@param cmdrCommandId string
@param ... any
@private
]=]
function CmdrService:__executeCommand(cmdrCommandId, ...)
assert(type(cmdrCommandId) == "string", "Bad cmdrCommandId")
assert(self._cmdr, "CmdrService is not initialized yet")
local execute = self._executeData[cmdrCommandId]
if not execute then
error(("[CmdrService] - No command definition for cmdrCommandId %q"):format(tostring(cmdrCommandId)))
end
return execute(...)
end
--[=[
Global usage but only intended for internal use
@param cmdrServiceId string
@return CmdrService
@private
]=]
function CmdrService:__getServiceFromId(cmdrServiceId)
assert(type(cmdrServiceId) == "string", "Bad cmdrServiceId")
return GLOBAL_REGISTRY[cmdrServiceId]
end
return CmdrService
|
--[=[
Bridge to https://eryn.io/Cmdr/
Uses [PermissionService] to provide permissions.
@server
@class CmdrService
]=]
local require = require(script.Parent.loader).load(script)
local HttpService = game:GetService("HttpService")
local PermissionService = require("PermissionService")
local CmdrTemplateProviderServer = require("CmdrTemplateProviderServer")
local Promise = require("Promise")
local CmdrService = {}
local GLOBAL_REGISTRY = setmetatable({}, {__mode = "kv"})
--[=[
Initializes the CmdrService. Should be done via [ServiceBag].
@param serviceBag ServiceBag
]=]
function CmdrService:Init(serviceBag)
assert(not self._cmdr, "Already initialized")
self._serviceBag = assert(serviceBag, "No serviceBag")
self._cmdrTemplateProviderServer = self._serviceBag:GetService(CmdrTemplateProviderServer)
self._serviceId = HttpService:GenerateGUID(false)
self._cmdr = require("Cmdr")
self._permissionService = serviceBag:GetService(PermissionService)
self._definitionData = {}
self._executeData = {}
self._cmdr.Registry:RegisterHook("BeforeRun", function(context)
local providerPromise = self._permissionService:PromisePermissionProvider()
if providerPromise:IsPending() then
return "Still loading permissions"
end
local ok, provider = providerPromise:Yield()
if not ok then
if type(provider) == "string" then
return provider
else
return "Failed to load permission provider"
end
end
if not provider:IsAdmin(context.Executor) then
return "You don't have permission to run this command"
else
-- allow
return nil
end
end)
GLOBAL_REGISTRY[self._serviceId] = self
end
--[=[
Starts the service. Should be done via [ServiceBag]
]=]
function CmdrService:Start()
self._cmdr:RegisterDefaultCommands()
end
--[=[
Returns cmdr
@return Promise<Cmdr>
]=]
function CmdrService:PromiseCmdr()
assert(self._cmdr, "Not initialized")
return Promise.resolved(self._cmdr)
end
--[=[
Registers a command into cmdr.
@param commandData table
@param execute (context: table, ... T)
]=]
function CmdrService:RegisterCommand(commandData, execute)
assert(self._cmdr, "Not initialized")
assert(commandData, "No commandData")
assert(commandData.Name, "No commandData.Name")
assert(execute, "No execute")
local commandId = ("%s_%s"):format(commandData.Name, HttpService:GenerateGUID(false))
self._definitionData[commandId] = commandData
self._executeData[commandId] = execute
local commandServerScript = self._cmdrTemplateProviderServer:Clone("CmdrExecutionTemplate")
commandServerScript.Name = ("%sServer"):format(commandId)
local cmdrServiceTarget = Instance.new("ObjectValue")
cmdrServiceTarget.Name = "CmdrServiceTarget"
cmdrServiceTarget.Value = script
cmdrServiceTarget.Parent = commandServerScript
local cmdrServiceId = Instance.new("StringValue")
cmdrServiceId.Name = "CmdrServiceId"
cmdrServiceId.Value = self._serviceId
cmdrServiceId.Parent = commandServerScript
local cmdrCommandId = Instance.new("StringValue")
cmdrCommandId.Name = "CmdrCommandId"
cmdrCommandId.Value = commandId
cmdrCommandId.Parent = commandServerScript
local commandScript = self._cmdrTemplateProviderServer:Clone("CmdrCommandDefinitionTemplate")
commandScript.Name = commandId
local cmdrJsonCommandData = Instance.new("StringValue")
cmdrJsonCommandData.Value = HttpService:JSONEncode(commandData)
cmdrJsonCommandData.Name = "CmdrJsonCommandData"
cmdrJsonCommandData.Parent = commandScript
self._cmdr.Registry:RegisterCommand(commandScript, commandServerScript)
end
--[=[
Private function used by the execution template to retrieve the execution function.
@param cmdrCommandId string
@param ... any
@private
]=]
function CmdrService:__executeCommand(cmdrCommandId, ...)
assert(type(cmdrCommandId) == "string", "Bad cmdrCommandId")
assert(self._cmdr, "CmdrService is not initialized yet")
local execute = self._executeData[cmdrCommandId]
if not execute then
error(("[CmdrService] - No command definition for cmdrCommandId %q"):format(tostring(cmdrCommandId)))
end
return execute(...)
end
--[=[
Global usage but only intended for internal use
@param cmdrServiceId string
@return CmdrService
@private
]=]
function CmdrService:__getServiceFromId(cmdrServiceId)
assert(type(cmdrServiceId) == "string", "Bad cmdrServiceId")
return GLOBAL_REGISTRY[cmdrServiceId]
end
return CmdrService
|
fix: Fix issue where anyone can execute admin commands
|
fix: Fix issue where anyone can execute admin commands
This is a critical security issue. You should deploy this immediately
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
c9103d3ce17be5c531a81abbfee8efb2783775be
|
packages/pirania/tests/test_redirect.lua
|
packages/pirania/tests/test_redirect.lua
|
local test_utils = require("tests.utils")
local match = require("luassert.match")
local REDIRECT_PATH = "packages/pirania/files/www/pirania-redirect/redirect"
local CONFIG_PATH = "./packages/pirania/files/etc/config/pirania"
local FAKE_ENV = {
HTTP_HOST = 'detectportal.firefox.com',
REQUEST_URI = '/success.txt'
}
local uci
describe('Pirania redirect request handler #portalredirect', function()
local snapshot
it('should redirect to url_auth when vouchers are active', function()
local url_auth = uci:get('pirania', 'base_config', 'url_auth')
handle_request(FAKE_ENV)
assert.stub(uhttpd.send).was_called_with(
'Location: http://thisnode.info' .. url_auth ..
'?prev=http%3A%2F%2Fdetectportal.firefox.com%2Fsuccess.txt' ..
'\r\n'
)
end)
it('should redirect to read_for_access portal when vouchers are non active', function()
uci:set('pirania', 'base_config', 'with_vouchers', '0')
uci:commit('pirania')
local url_portal = uci:get('pirania', 'read_for_access', 'url_portal')
handle_request(FAKE_ENV)
assert.stub(uhttpd.send).was_called_with(
'Location: http://thisnode.info' .. url_portal ..
'?prev=http%3A%2F%2Fdetectportal.firefox.com%2Fsuccess.txt' ..
'\r\n'
)
end)
before_each('', function()
snapshot = assert:snapshot()
test_dir = test_utils.setup_test_dir()
uci = test_utils.setup_test_uci()
local default_cfg = io.open(CONFIG_PATH):read("*all")
test_utils.write_uci_file(uci, 'pirania', default_cfg)
test_utils.load_lua_file_as_function(REDIRECT_PATH)()
_G.uhttpd = {
send = function(msg) end
}
stub(uhttpd, "send")
end)
after_each('', function()
snapshot:revert()
test_utils.teardown_test_dir()
test_utils.teardown_test_uci(uci)
end)
end)
|
local test_utils = require("tests.utils")
local match = require("luassert.match")
local REDIRECT_PATH = "packages/pirania/files/www/pirania-redirect/redirect"
local CONFIG_PATH = "./packages/pirania/files/etc/config/pirania"
local FAKE_ENV = {
HTTP_HOST = 'detectportal.firefox.com',
REQUEST_URI = '/success.txt'
}
local uci
describe('Pirania redirect request handler #portalredirect', function()
local snapshot
it('should redirect to url_auth when vouchers are active', function()
uci:set('pirania', 'base_config', 'with_vouchers', '1')
uci:commit('pirania')
local url_auth = uci:get('pirania', 'base_config', 'url_auth')
handle_request(FAKE_ENV)
assert.stub(uhttpd.send).was_called_with(
'Location: http://thisnode.info' .. url_auth ..
'?prev=http%3A%2F%2Fdetectportal.firefox.com%2Fsuccess.txt' ..
'\r\n'
)
end)
it('should redirect to read_for_access portal when vouchers are non active', function()
uci:set('pirania', 'base_config', 'with_vouchers', '0')
uci:commit('pirania')
local url_portal = uci:get('pirania', 'read_for_access', 'url_portal')
handle_request(FAKE_ENV)
assert.stub(uhttpd.send).was_called_with(
'Location: http://thisnode.info' .. url_portal ..
'?prev=http%3A%2F%2Fdetectportal.firefox.com%2Fsuccess.txt' ..
'\r\n'
)
end)
before_each('', function()
snapshot = assert:snapshot()
test_dir = test_utils.setup_test_dir()
uci = test_utils.setup_test_uci()
local default_cfg = io.open(CONFIG_PATH):read("*all")
test_utils.write_uci_file(uci, 'pirania', default_cfg)
test_utils.load_lua_file_as_function(REDIRECT_PATH)()
_G.uhttpd = {
send = function(msg) end
}
stub(uhttpd, "send")
end)
after_each('', function()
snapshot:revert()
test_utils.teardown_test_dir()
test_utils.teardown_test_uci(uci)
end)
end)
|
pirania: fix test after defaults changed
|
pirania: fix test after defaults changed
|
Lua
|
agpl-3.0
|
libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages
|
0006e06c6d87d83dbdc53ff4b038c0831038c779
|
BIOS/filethread.lua
|
BIOS/filethread.lua
|
--A thread to keep track of files being edited, and automatically update them in the appdata folder
--So there would be no longer need to restart LIKO-12 for some tasks.
--By default it only tracks the DiskOS folder.
require("love.system")
require("love.timer")
local reg = {}
local tpath = "/OS/DiskOS/" --Tracking Path
local dpath = "/drives/C/" --Destination Path
local channel = love.thread.getChannel("BIOSFileThread") --Stop the thread when needed.
local function checkDir(dir,r)
dir = dir or ""
r = r or reg
local path = tpath..dir
local items = love.filesystem.getDirectoryItems(path)
for k, file in ipairs(items) do if file:sub(1,1) ~= "." then
local fpath = path..file
if love.filesystem.getInfo(fpath,"file") then --It's a file
local fupdate = false --Should the file be updated ?
if not love.filesystem.getInfo(dpath..dir..file) then --Add new file
--print("New file added")
fupdate = true
else --Check old file
local info = love.filesystem.getInfo(fpath)
local modtime = info and info.modtime
if modtime then
if r[file] then --It's registered
if modtime > r[file] then --It has been edited !
fupdate = true
end
else --It's not registered !
r[file] = info.modtime --Register it.
end
else
print("Error: failed to get modification time.")
end
end
--Update the file
if fupdate then
local info = love.filesystem.getInfo(fpath)
r[file] = info and info.modtime or false
local data, rerr = love.filesystem.read(fpath)
if data then
local ok, werr = love.filesystem.write(dpath..dir..file,data)
if not ok then r[file] = nil print("Error: Failed to write,",werr) else
--print("Updated File",fpath)
end
else
print("Error: Failed to read,",rerr)
end
end
else --Nested directory
if not r[file] then r[file] = {} end
checkDir(dir..file.."/",r[file])
end
end end
end
print("Started File Thread")
while true do
local shut = channel:pop()
if shut then break end --Finish the thread.
checkDir()
love.timer.sleep(3)
end
print("Finished File Thread")
|
--Thread used to keep track of files being edited and automatically update them
--in the appdata folder so LIKO-12 does not need to be restarted for some tasks
--Only tracks the DiskOS folder by default
require("love.system")
require("love.timer")
local reg = {}
local delay_between_checks = 3 --Time in seconds between each check
local source_path = "/OS/DiskOS/"
local target_path = "/drives/C/"
local channel = love.thread.getChannel("BIOSFileThread") --Stop the thread when needed
local function checkDir(dir, r)
dir = dir or ""
r = r or reg
local path = source_path .. dir
local items = love.filesystem.getDirectoryItems(path)
-- Check every file in the tracking path
for k, file in ipairs(items) do
if file:sub(1, 1) ~= "." then
local fpath = path .. file
if love.filesystem.getInfo(fpath, "file") then
-- It's a file
local file_need_update = false --Should the file be updated?
if not love.filesystem.getInfo(target_path .. dir .. file) then
-- The files does not exist in the target path, create it
file_need_update = true
else
-- Get the last timestamp at which the file was modified
local info = love.filesystem.getInfo(fpath)
local modtime = info and info.modtime
if modtime then
--Check the previous timestamp to see if the file need to be updated
if r[file] then
--The file is already registered
if modtime > r[file] then
--The file has been edited since last time, update it
file_need_update = true
end
else
--The file is not registered yet, register it
r[file] = info.modtime
end
else
print("Error: failed to get modification time.")
end
end
--Update the file if needed
if file_need_update then
local info = love.filesystem.getInfo(fpath)
r[file] = info and info.modtime or false
local data, rerr = love.filesystem.read(fpath)
if data then
local ok, werr = love.filesystem.write(target_path .. dir .. file, data)
if not ok then
r[file] = nil
print("Error: failed to write,", werr)
end
else
print("Error: failed to read,", rerr)
end
end
else
--It's a directory, recursively check its content
if not r[file] then
r[file] = {}
end
checkDir(dir .. file .. "/", r[file])
end
end
end
end
print("Started File Thread")
while true do
local shut = channel:pop()
if shut then
--Finish the thread
break
end
checkDir()
love.timer.sleep(delay_between_checks)
end
print("Finished File Thread")
|
Improve filethread (#242)
|
Improve filethread (#242)
* Improve formatting and add some comments
* Rename some variables
* Store delay between checks in a variable
* Use 2 spaces for indentation
* Tiny spelling fix
* Fix the tab indentation problem
Former-commit-id: 7c253b7d67bbdeb7f62da2ce3d0c8118ef6463f6
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
6d031b13a74b5a8b02c2eb7a481fe8721693225a
|
src/pci.lua
|
src/pci.lua
|
-- pci.lua -- PCI device access via Linux sysfs.
-- Copyright 2012 Snabb GmbH. See the file LICENSE.
module(...,package.seeall)
local ffi = require("ffi")
local C = ffi.C
local lib = require("lib")
require("clib_h")
require("snabb_h")
--- ## Hardware device information
--- Array of all supported hardware devices.
---
--- Each entry is a "device info" table with these attributes:
--- * `pciaddress` e.g. `"0000:83:00.1"`
--- * `vendor` id hex string e.g. `"0x8086"` for Intel.
--- * `device` id hex string e.g. `"0x10fb"` for 82599 chip.
--- * `interface` name of Linux interface using this device e.g. `"eth0"`.
--- * `status` string Linux operational status, or `nil` if not known.
--- * `driver` Lua module that supports this hardware e.g. `"intel10g"`.
--- * `usable` device was suitable to use when scanned? `yes` or `no`
devices = {}
-- Return device information table i.e. value for the devices table.
function scan_devices ()
for _,device in ipairs(scandir("/sys/bus/pci/devices")) do
local info = device_info(device)
if info.driver then table.insert(devices, info) end
end
end
function scandir (dir)
local files = {}
for line in io.popen('ls -1 "'..dir..'" 2>/dev/null'):lines() do
table.insert(files, line)
end
return files
end
-- Return the
function device_info (pciaddress)
local info = {}
local p = path(pciaddress)
info.pciaddress = pciaddress
info.vendor = firstline(p.."/vendor")
info.device = firstline(p.."/device")
info.interface = firstfile(p.."/net")
info.driver = which_driver(info.vendor, info.device)
if info.interface then
info.status = firstline(p.."/net/"..info.interface.."/operstate")
end
info.usable = lib.yesno(is_usable(info))
return info
end
-- Return the path to the sysfs directory for `pcidev`.
function path(pcidev) return "/sys/bus/pci/devices/"..pcidev end
-- Return the name of the Lua module that implements support for this device.
function which_driver (vendor, device)
if vendor == '0x8086' and device == '0x10fb' then return 'intel10g' end
if vendor == '0x8086' and device == '0x10d3' then return 'intel' end
end
function firstline (filename) return lib.readfile(filename, "*l") end
-- Return the name of the first file in `dir`.
function firstfile (dir)
return lib.readcmd("ls -1 "..dir.." 2>/dev/null", "*l")
end
--- ## Device manipulation
-- Force Linux to release the device with `pciaddress`.
-- The corresponding network interface (e.g. `eth0`) will disappear.
function unbind_device_from_linux (pciaddress)
lib.writefile(path(pciaddress).."/driver/unbind", pciaddress)
end
-- Return a pointer for MMIO access to 'device' resource 'n'.
-- Device configuration registers can be accessed this way.
function map_pci_memory (device, n)
local filepath = path(device).."/resource"..n
local addr = C.map_pci_resource(filepath)
assert( addr ~= 0 )
return addr
end
-- Enable or disable PCI bus mastering.
-- (DMA only works when bus mastering is enabled.)
function set_bus_master (device, enable)
local fd = C.open_pcie_config(path(device).."/config")
local value = ffi.new("uint16_t[1]")
assert(C.pread(fd, value, 2, 0x4) == 2)
if enable then
value[0] = bit.bor(value[0], lib.bits({Master=2}))
else
value[0] = bit.band(value[0], bit.bnot(lib.bits({Master=2})))
end
assert(C.pwrite(fd, value, 2, 0x4) == 2)
end
-- Return true if `device` is available for use or false if it seems
-- to be used by the operating system.
function is_usable (info)
return info.driver and (info.interface == nil or info.status == 'down')
end
--- ## Open a device
---
--- Load a fresh copy of the device driver's Lua module for each
--- device. The module will be told at load-time the PCI address of
--- the device it is controlling. This makes the module code short
--- because it can assume that it's always talking to the same device.
---
--- This is achieved with our own require()-like function that loads a
--- fresh copy and passes the PCI address as an argument.
open_devices = {}
-- Load a new instance of the 'driver' module for 'pciaddress'.
-- On success this creates the Lua module 'driver@pciaddress'.
--
-- Example: open_device("intel10g", "0000:83:00.1") creates module
-- "intel10g@0000:83:00.1" which controls that specific device.
function open_device(pciaddress, driver)
local instance = driver.."@"..pciaddress
find_loader(driver)(instance, pciaddress)
open_devices[pciaddress] = package.loaded[instance]
return package.loaded[instance]
end
-- (This could be a Lua builtin.)
-- Return loader function for `module`.
-- Calling the loader function will run the module's code.
function find_loader (mod)
for i = 1, #package.loaders do
status, loader = pcall(package.loaders[i], mod)
if type(loader) == 'function' then return loader end
end
end
--- ## Selftest
function selftest ()
print("selftest: pci")
print_devices()
open_usable_devices()
end
--- Print a table summarizing all the available hardware devices.
function print_devices ()
local attrs = {"pciaddress", "vendor", "device", "interface", "status",
"driver", "usable"}
local fmt = "%-13s %-7s %-7s %-10s %-9s %-11s %s"
print(fmt:format(unpack(attrs)))
for _,info in ipairs(devices) do
local values = {}
for _,attr in ipairs(attrs) do
table.insert(values, info[attr] or "-")
end
print(fmt:format(unpack(values)))
end
end
function open_usable_devices ()
for _,device in ipairs(devices) do
if device.usable == 'yes' then
print("Unbinding device from linux: "..device.pciaddress)
unbind_device_from_linux(device.pciaddress)
print("Opening device "..device.pciaddress)
local driver = open_device(device.pciaddress, device.driver)
print("Testing "..device.pciaddress)
driver.selftest()
end
end
end
function module_init () scan_devices () end
module_init()
|
-- pci.lua -- PCI device access via Linux sysfs.
-- Copyright 2012 Snabb GmbH. See the file LICENSE.
module(...,package.seeall)
local ffi = require("ffi")
local C = ffi.C
local lib = require("lib")
require("clib_h")
require("snabb_h")
--- ## Hardware device information
--- Array of all supported hardware devices.
---
--- Each entry is a "device info" table with these attributes:
--- * `pciaddress` e.g. `"0000:83:00.1"`
--- * `vendor` id hex string e.g. `"0x8086"` for Intel.
--- * `device` id hex string e.g. `"0x10fb"` for 82599 chip.
--- * `interface` name of Linux interface using this device e.g. `"eth0"`.
--- * `status` string Linux operational status, or `nil` if not known.
--- * `driver` Lua module that supports this hardware e.g. `"intel10g"`.
--- * `usable` device was suitable to use when scanned? `yes` or `no`
devices = {}
-- Return device information table i.e. value for the devices table.
function scan_devices ()
for _,device in ipairs(scandir("/sys/bus/pci/devices")) do
local info = device_info(device)
if info.driver then table.insert(devices, info) end
end
end
function scandir (dir)
local files = {}
for line in io.popen('ls -1 "'..dir..'" 2>/dev/null'):lines() do
table.insert(files, line)
end
return files
end
-- Return the
function device_info (pciaddress)
local info = {}
local p = path(pciaddress)
info.pciaddress = pciaddress
info.vendor = firstline(p.."/vendor")
info.device = firstline(p.."/device")
info.interface = firstfile(p.."/net")
info.driver = which_driver(info.vendor, info.device)
if info.interface then
info.status = firstline(p.."/net/"..info.interface.."/operstate")
end
info.usable = lib.yesno(is_usable(info))
return info
end
-- Return the path to the sysfs directory for `pcidev`.
function path(pcidev) return "/sys/bus/pci/devices/"..pcidev end
-- Return the name of the Lua module that implements support for this device.
function which_driver (vendor, device)
if vendor == '0x8086' and device == '0x10fb' then return 'intel10g' end
if vendor == '0x8086' and device == '0x10d3' then return 'intel' end
end
function firstline (filename) return lib.readfile(filename, "*l") end
-- Return the name of the first file in `dir`.
function firstfile (dir)
return lib.readcmd("ls -1 "..dir.." 2>/dev/null", "*l")
end
--- ## Device manipulation
-- Force Linux to release the device with `pciaddress`.
-- The corresponding network interface (e.g. `eth0`) will disappear.
function unbind_device_from_linux (pciaddress)
lib.writefile(path(pciaddress).."/driver/unbind", pciaddress)
end
-- Return a pointer for MMIO access to 'device' resource 'n'.
-- Device configuration registers can be accessed this way.
function map_pci_memory (device, n)
local filepath = path(device).."/resource"..n
local addr = C.map_pci_resource(filepath)
assert( addr ~= 0 )
return addr
end
-- Enable or disable PCI bus mastering.
-- (DMA only works when bus mastering is enabled.)
function set_bus_master (device, enable)
local fd = C.open_pcie_config(path(device).."/config")
local value = ffi.new("uint16_t[1]")
assert(C.pread(fd, value, 2, 0x4) == 2)
if enable then
value[0] = bit.bor(value[0], lib.bits({Master=2}))
else
value[0] = bit.band(value[0], bit.bnot(lib.bits({Master=2})))
end
assert(C.pwrite(fd, value, 2, 0x4) == 2)
end
-- Return true if `device` is available for use or false if it seems
-- to be used by the operating system.
function is_usable (info)
return info.driver and (info.interface == nil or info.status == 'down')
end
--- ## Open a device
---
--- Load a fresh copy of the device driver's Lua module for each
--- device. The module will be told at load-time the PCI address of
--- the device it is controlling. This makes the module code short
--- because it can assume that it's always talking to the same device.
---
--- This is achieved with our own require()-like function that loads a
--- fresh copy and passes the PCI address as an argument.
open_devices = {}
-- Load a new instance of the 'driver' module for 'pciaddress'.
-- On success this creates the Lua module 'driver@pciaddress'.
--
-- Example: open_device("intel10g", "0000:83:00.1") creates module
-- "intel10g@0000:83:00.1" which controls that specific device.
function open_device(pciaddress, driver)
local instance = driver.."@"..pciaddress
find_loader(driver)(instance, pciaddress)
open_devices[pciaddress] = package.loaded[instance]
return package.loaded[instance]
end
-- (This could be a Lua builtin.)
-- Return loader function for `module`.
-- Calling the loader function will run the module's code.
function find_loader (mod)
for i = 1, #package.loaders do
status, loader = pcall(package.loaders[i], mod)
if type(loader) == 'function' then return loader end
end
end
--- ## Selftest
function selftest ()
print("selftest: pci")
print_devices()
open_usable_devices()
end
--- Print a table summarizing all the available hardware devices.
function print_devices ()
local attrs = {"pciaddress", "vendor", "device", "interface", "status",
"driver", "usable"}
local fmt = "%-13s %-7s %-7s %-10s %-9s %-11s %s"
print(fmt:format(unpack(attrs)))
for _,info in ipairs(devices) do
local values = {}
for _,attr in ipairs(attrs) do
table.insert(values, info[attr] or "-")
end
print(fmt:format(unpack(values)))
end
end
function open_usable_devices ()
for _,device in ipairs(devices) do
if device.usable == 'yes' then
if device.interface ~= nil then
print("Unbinding device from linux: "..device.pciaddress)
unbind_device_from_linux(device.pciaddress)
end
print("Opening device "..device.pciaddress)
local driver = open_device(device.pciaddress, device.driver)
print("Testing "..device.pciaddress)
driver.selftest()
end
end
end
function module_init () scan_devices () end
module_init()
|
pci.lua: Bug fix - don't unbind devices from Linux if they are already unbound.
|
pci.lua: Bug fix - don't unbind devices from Linux if they are already unbound.
|
Lua
|
apache-2.0
|
fhanik/snabbswitch,alexandergall/snabbswitch,mixflowtech/logsensor,kellabyte/snabbswitch,snabbco/snabb,snabbnfv-goodies/snabbswitch,andywingo/snabbswitch,aperezdc/snabbswitch,eugeneia/snabbswitch,snabbco/snabb,eugeneia/snabb,plajjan/snabbswitch,dpino/snabb,kellabyte/snabbswitch,eugeneia/snabb,justincormack/snabbswitch,SnabbCo/snabbswitch,Igalia/snabb,fhanik/snabbswitch,Igalia/snabb,aperezdc/snabbswitch,kbara/snabb,heryii/snabb,javierguerragiraldez/snabbswitch,mixflowtech/logsensor,snabbco/snabb,mixflowtech/logsensor,aperezdc/snabbswitch,Igalia/snabb,snabbnfv-goodies/snabbswitch,lukego/snabbswitch,fhanik/snabbswitch,plajjan/snabbswitch,alexandergall/snabbswitch,eugeneia/snabb,justincormack/snabbswitch,Igalia/snabbswitch,eugeneia/snabbswitch,virtualopensystems/snabbswitch,dpino/snabb,SnabbCo/snabbswitch,wingo/snabbswitch,plajjan/snabbswitch,kbara/snabb,heryii/snabb,justincormack/snabbswitch,xdel/snabbswitch,Igalia/snabbswitch,kbara/snabb,hb9cwp/snabbswitch,Igalia/snabb,andywingo/snabbswitch,alexandergall/snabbswitch,mixflowtech/logsensor,lukego/snabbswitch,snabbnfv-goodies/snabbswitch,plajjan/snabbswitch,dwdm/snabbswitch,Igalia/snabb,dpino/snabbswitch,wingo/snabbswitch,hb9cwp/snabbswitch,snabbco/snabb,snabbco/snabb,snabbco/snabb,dpino/snabbswitch,aperezdc/snabbswitch,eugeneia/snabb,dpino/snabb,virtualopensystems/snabbswitch,dpino/snabb,dpino/snabbswitch,eugeneia/snabb,heryii/snabb,dpino/snabb,pavel-odintsov/snabbswitch,lukego/snabbswitch,dpino/snabb,lukego/snabb,wingo/snabb,xdel/snabbswitch,snabbnfv-goodies/snabbswitch,javierguerragiraldez/snabbswitch,hb9cwp/snabbswitch,alexandergall/snabbswitch,kbara/snabb,mixflowtech/logsensor,kbara/snabb,Igalia/snabbswitch,wingo/snabbswitch,javierguerragiraldez/snabbswitch,Igalia/snabbswitch,lukego/snabb,wingo/snabb,lukego/snabb,heryii/snabb,dwdm/snabbswitch,eugeneia/snabb,eugeneia/snabb,xdel/snabbswitch,kellabyte/snabbswitch,heryii/snabb,Igalia/snabbswitch,alexandergall/snabbswitch,pirate/snabbswitch,wingo/snabb,wingo/snabbswitch,snabbco/snabb,pavel-odintsov/snabbswitch,alexandergall/snabbswitch,SnabbCo/snabbswitch,snabbco/snabb,andywingo/snabbswitch,lukego/snabbswitch,Igalia/snabb,wingo/snabb,dpino/snabb,justincormack/snabbswitch,eugeneia/snabbswitch,eugeneia/snabbswitch,Igalia/snabb,kbara/snabb,pirate/snabbswitch,eugeneia/snabb,pirate/snabbswitch,dwdm/snabbswitch,andywingo/snabbswitch,dpino/snabbswitch,SnabbCo/snabbswitch,lukego/snabb,virtualopensystems/snabbswitch,Igalia/snabb,hb9cwp/snabbswitch,alexandergall/snabbswitch,pavel-odintsov/snabbswitch,heryii/snabb,alexandergall/snabbswitch,wingo/snabb,wingo/snabb
|
793e9428a9ec02922e7ada4db68ae7efaed42000
|
generate/lua/format.lua
|
generate/lua/format.lua
|
local slt = require 'slt2'
local utl = require 'utl'
local format = {}
function format.html(str)
return tostring(str)
:gsub('&','&')
:gsub("'",''')
:gsub('<','<')
:gsub('>','>')
:gsub('"','"')
end
local templateCache = {}
function format.slt(file,data)
file = utl.path('resources/templates',file)
data.html = format.html
if templateCache[file] then
return slt.render(templateCache[file],data)
else
local t = slt.loadfile(file,'{{','}}')
templateCache[file] = t
return slt.render(t,data)
end
end
format.url = {}
function format.url.raw(str)
return str:gsub('[^-%.0-9A-Za-z_~]',function(c)
return ('%%%02X'):format(c:byte())
end)
end
format.url.file = format.url.raw
function format.url.type(type)
return '#type' .. format.url.raw(type)
end
function format.url.class(class)
return '/api/class/' .. format.url.raw(format.url.file(class)) .. '.html'
end
function format.url.member(class,member)
if member then
return '/api/class/' .. format.url.raw(format.url.file(class)) .. '.html#member' .. format.url.raw(member)
else
member = class
return '#member' .. format.url.raw(member)
end
end
function format.url.version(ver,frag)
if frag then
return 'v' .. ver:match('^(%d+%.%d+)')
else
return '/api/diff.html#v' .. ver:match('^(%d+%.%d+)')
end
end
function format.classtree(tree)
local o = {}
local rep = string.rep
local function r(t,d)
for i = 1,#t do
local class = t[i]
local n = #class.List > 0
o[#o+1] = rep('\t',d) .. '<li>'
if n then
o[#o+1] = '\n' .. rep('\t',d + 1)
end
o[#o+1] = format.slt('ClassIcon.html',{icon=class.Icon}) .. '<a class="api-class-name" href="' .. format.url.class(class.Class) .. '">' .. format.html(class.Class) .. '</a>'
o[#o+1] = format.slt('VersionList.html',{format=format,versions=class.Versions})
if n then
o[#o+1] = '\n' .. rep('\t',d + 1) .. '<ul>\n'
r(class.List,d + 2)
o[#o+1] = rep('\t',d + 1) .. '</ul>\n'
o[#o+1] = rep('\t',d)
end
o[#o+1] = '</li>'
o[#o+1] = '\n'
end
end
r(tree,0)
return table.concat(o,nil,1,#o-1)
end
function format.date(date)
return os.date('!%B %d, %Y',date)
end
do
local ord = {'st','nd','rd','th','th','th','th','th','th',[0] = 'th'}
function format.ordinal(n)
return n .. ord[math.abs(n)%10]
end
end
return format
|
local slt = require 'slt2'
local utl = require 'utl'
local format = {}
function format.html(str)
return tostring(str)
:gsub('&','&')
:gsub("'",''')
:gsub('<','<')
:gsub('>','>')
:gsub('"','"')
end
local templateCache = {}
function format.slt(file,data)
file = utl.path('resources/templates',file)
data.html = format.html
if templateCache[file] then
return slt.render(templateCache[file],data)
else
local t = slt.loadfile(file,'{{','}}')
templateCache[file] = t
return slt.render(t,data)
end
end
format.url = {}
function format.url.raw(str)
return str:gsub('[^-%.0-9A-Za-z_~]',function(c)
return ('%%%02X'):format(c:byte())
end)
end
format.url.file = format.url.raw
function format.url.type(type)
return '#type' .. format.url.raw(type)
end
function format.url.class(class)
return '/api/class/' .. format.url.raw(format.url.file(class)) .. '.html'
end
function format.url.member(class,member)
if member then
return format.url.class(class) .. '#member' .. format.url.raw(member)
else
member = class
return '#member' .. format.url.raw(member)
end
end
function format.url.version(ver,frag)
if frag then
return 'v' .. ver:match('^(%d+%.%d+)')
else
return '/api/diff.html#v' .. ver:match('^(%d+%.%d+)')
end
end
function format.classtree(tree)
local o = {}
local rep = string.rep
local function r(t,d)
for i = 1,#t do
local class = t[i]
local n = #class.List > 0
o[#o+1] = rep('\t',d) .. '<li>'
if n then
o[#o+1] = '\n' .. rep('\t',d + 1)
end
o[#o+1] = format.slt('ClassIcon.html',{icon=class.Icon}) .. '<a class="api-class-name" href="' .. format.url.class(class.Class) .. '">' .. format.html(class.Class) .. '</a>'
o[#o+1] = format.slt('VersionList.html',{format=format,versions=class.Versions})
if n then
o[#o+1] = '\n' .. rep('\t',d + 1) .. '<ul>\n'
r(class.List,d + 2)
o[#o+1] = rep('\t',d + 1) .. '</ul>\n'
o[#o+1] = rep('\t',d)
end
o[#o+1] = '</li>'
o[#o+1] = '\n'
end
end
r(tree,0)
return table.concat(o,nil,1,#o-1)
end
function format.date(date)
return os.date('!%B %d, %Y',date)
end
do
local ord = {'st','nd','rd','th','th','th','th','th','th',[0] = 'th'}
function format.ordinal(n)
return n .. ord[math.abs(n)%10]
end
end
return format
|
fixed redundancy
|
fixed redundancy
|
Lua
|
unlicense
|
Anaminus/roblox-api-ref,Anaminus/roblox-api-ref
|
62149acc0859a9f91d7034e03d0cf0127d0bc56f
|
mod_register_json/mod_register_json.lua
|
mod_register_json/mod_register_json.lua
|
-- Expose a simple servlet to handle user registrations from web pages
-- via JSON.
--
-- A Good chunk of the code is from mod_data_access.lua by Kim Alvefur
-- aka Zash.
local jid_prep = require "util.jid".prep;
local jid_split = require "util.jid".split;
local usermanager = require "core.usermanager";
local b64_decode = require "util.encodings".base64.decode;
local json_decode = require "util.json".decode;
local os_time = os.time;
module.host = "*" -- HTTP/BOSH Servlets need to be global.
-- Pick up configuration.
local set_realm_name = module:get_option("reg_servlet_realm") or "Restricted";
local throttle_time = module:get_option("reg_servlet_ttime") or false;
local whitelist = module:get_option("reg_servlet_wl") or {};
local blacklist = module:get_option("reg_servlet_bl") or {};
local recent_ips = {};
-- Begin
for _, ip in ipairs(whitelist) do whitelisted_ips[ip] = true; end
for _, ip in ipairs(blacklist) do blacklisted_ips[ip] = true; end
local function http_response(code, message, extra_headers)
local response = {
status = code .. " " .. message;
body = message .. "\n"; }
if extra_headers then response.headers = extra_headers; end
return response
end
local function handle_req(method, body, request)
if request.method ~= "POST" then
return http_response(405, "Bad method...", {["Allow"] = "POST"});
end
if not request.headers["authorization"] then
return http_response(401, "No... No...",
{["WWW-Authenticate"]='Basic realm="'.. set_realm_name ..'"'})
end
local user, password = b64_decode(request.headers.authorization
:match("[^ ]*$") or ""):match("([^:]*):(.*)");
user = jid_prep(user);
if not user or not password then return http_response(400, "What's this..?"); end
local user_node, user_host = jid_split(user)
if not hosts[user_host] then return http_response(401, "Negative."); end
module:log("warn", "%s is authing to submit a new user registration data", user)
if not usermanager.test_password(user_node, user_host, password) then
module:log("warn", "%s failed authentication", user)
return http_response(401, "Who the hell are you?! Guards!");
end
local req_body;
-- We check that what we have is valid JSON wise else we throw an error...
if not pcall(function() req_body = json_decode(body) end) then
module:log("debug", "JSON data submitted for user registration by %s failed to Decode.", user);
return http_response(400, "JSON Decoding failed.");
else
-- Decode JSON data and check that all bits are there else throw an error
req_body = json_decode(body);
if req_body["username"] == nil or req_body["password"] == nil or req_body["host"] == nil or req_body["ip"] == nil then
module:log("debug", "%s supplied an insufficent number of elements or wrong elements for the JSON registration", user);
return http_response(400, "Invalid syntax.");
end
-- Check if user is an admin of said host
if not usermanager.is_admin(user, req_body["host"]) then
module:log("warn", "%s tried to submit registration data for %s but he's not an admin", user, req_body["host"]);
return http_response(401, "I obey only to my masters... Have a nice day.");
else
-- Checks for both Throttling/Whitelist and Blacklist (basically copycatted from prosody's register.lua code)
if blacklist[req_body["ip"]] then module:log("warn", "Attempt of reg. submission to the JSON servlet from blacklisted address: %s", req_body["ip"]); return http_response(403, "The specified address is blacklisted, sorry sorry."); end
if throttle_time and not whitelist[req_body["ip"]] then
if not recent_ips[req_body["ip"]] then
recent_ips[req_body["ip"]] = { time = os_time(), count = 1 };
else
local ip = recent_ips[req_body["ip"]];
ip.count = ip.count + 1;
if os_time() - ip.time < throttle_time then
ip.time = os_time();
module:log("warn", "JSON Registration request from %s has been throttled.", req_body["ip"]);
return http_response(503, "Woah... How many users you want to register..? Request throttled, wait a bit and try again.");
end
ip.time = os_time();
end
end
-- We first check if the supplied username for registration is already there.
if not usermanager.user_exists(req_body["username"], req_body["host"]) then
usermanager.create_user(req_body["username"], req_body["password"], req_body["host"]);
module:log("debug", "%s registration data submission for %s is successful", user, req_body["username"]);
return http_response(200, "Done.");
else
module:log("debug", "%s registration data submission for %s failed (user already exists)", user, req_body["username"]);
return http_response(409, "User already exists.");
end
end
end
end
-- Set it up!
local function setup()
local ports = module:get_option("reg_servlet_port") or { 9280 };
local base_name = module:get_option("reg_servlet_base") or "register_account";
local ssl_cert = module:get_option("reg_servlet_sslcert") or false;
local ssl_key = module:get_option("reg_servlet_sslkey") or false;
if not ssl_cert or not ssl_key then
require "net.httpserver".new_from_config(ports, handle_req, { base = base_name });
else
if module:get_option("reg_servlet_port") == nil then ports = { 9443 }; end
require "net.httpserver".new_from_config(ports, handle_req, { ssl = { key = ssl_key, certificate = ssl_cert }, base = base_name });
end
end
if prosody.start_time then -- already started
setup();
else
prosody.events.add_handler("server-started", setup);
end
|
-- Expose a simple servlet to handle user registrations from web pages
-- via JSON.
--
-- A Good chunk of the code is from mod_data_access.lua by Kim Alvefur
-- aka Zash.
local jid_prep = require "util.jid".prep;
local jid_split = require "util.jid".split;
local usermanager = require "core.usermanager";
local b64_decode = require "util.encodings".base64.decode;
local json_decode = require "util.json".decode;
local os_time = os.time;
module.host = "*" -- HTTP/BOSH Servlets need to be global.
-- Pick up configuration.
local set_realm_name = module:get_option("reg_servlet_realm") or "Restricted";
local throttle_time = module:get_option("reg_servlet_ttime") or false;
local whitelist = module:get_option("reg_servlet_wl") or {};
local blacklist = module:get_option("reg_servlet_bl") or {};
local recent_ips = {};
-- Begin
for _, ip in ipairs(whitelist) do whitelisted_ips[ip] = true; end
for _, ip in ipairs(blacklist) do blacklisted_ips[ip] = true; end
local function http_response(code, message, extra_headers)
local response = {
status = code .. " " .. message;
body = message .. "\n"; }
if extra_headers then response.headers = extra_headers; end
return response
end
local function handle_req(method, body, request)
if request.method ~= "POST" then
return http_response(405, "Bad method...", {["Allow"] = "POST"});
end
if not request.headers["authorization"] then
return http_response(401, "No... No...",
{["WWW-Authenticate"]='Basic realm="'.. set_realm_name ..'"'})
end
local user, password = b64_decode(request.headers.authorization
:match("[^ ]*$") or ""):match("([^:]*):(.*)");
user = jid_prep(user);
if not user or not password then return http_response(400, "What's this..?"); end
local user_node, user_host = jid_split(user)
if not hosts[user_host] then return http_response(401, "Negative."); end
module:log("warn", "%s is authing to submit a new user registration data", user)
if not usermanager.test_password(user_node, user_host, password) then
module:log("warn", "%s failed authentication", user)
return http_response(401, "Who the hell are you?! Guards!");
end
local req_body;
-- We check that what we have is valid JSON wise else we throw an error...
if not pcall(function() req_body = json_decode(body) end) then
module:log("debug", "JSON data submitted for user registration by %s failed to Decode.", user);
return http_response(400, "JSON Decoding failed.");
else
-- Decode JSON data and check that all bits are there else throw an error
req_body = json_decode(body);
if req_body["username"] == nil or req_body["password"] == nil or req_body["host"] == nil or req_body["ip"] == nil then
module:log("debug", "%s supplied an insufficent number of elements or wrong elements for the JSON registration", user);
return http_response(400, "Invalid syntax.");
end
-- Check if user is an admin of said host
if not usermanager.is_admin(user, req_body["host"]) then
module:log("warn", "%s tried to submit registration data for %s but he's not an admin", user, req_body["host"]);
return http_response(401, "I obey only to my masters... Have a nice day.");
else
-- Checks for both Throttling/Whitelist and Blacklist (basically copycatted from prosody's register.lua code)
if blacklist[req_body["ip"]] then module:log("warn", "Attempt of reg. submission to the JSON servlet from blacklisted address: %s", req_body["ip"]); return http_response(403, "The specified address is blacklisted, sorry sorry."); end
if throttle_time and not whitelist[req_body["ip"]] then
if not recent_ips[req_body["ip"]] then
recent_ips[req_body["ip"]] = { time = os_time(), count = 1 };
else
local ip = recent_ips[req_body["ip"]];
ip.count = ip.count + 1;
if os_time() - ip.time < throttle_time then
ip.time = os_time();
module:log("warn", "JSON Registration request from %s has been throttled.", req_body["ip"]);
return http_response(503, "Woah... How many users you want to register..? Request throttled, wait a bit and try again.");
end
ip.time = os_time();
end
end
-- We first check if the supplied username for registration is already there.
if not usermanager.user_exists(req_body["username"], req_body["host"]) then
usermanager.create_user(req_body["username"], req_body["password"], req_body["host"]);
module:log("debug", "%s registration data submission for %s is successful", user, req_body["username"]);
return http_response(200, "Done.");
else
module:log("debug", "%s registration data submission for %s failed (user already exists)", user, req_body["username"]);
return http_response(409, "User already exists.");
end
end
end
end
-- Set it up!
local function setup()
local port = module:get_option("reg_servlet_port") or 9280;
local base_name = module:get_option("reg_servlet_base") or "register_account";
local ssl_cert = module:get_option("reg_servlet_sslcert") or false;
local ssl_key = module:get_option("reg_servlet_sslkey") or false;
if not ssl_cert or not ssl_key then
require "net.httpserver".new_from_config({ port = port }, handle_req, { base = base_name });
else
if module:get_option("reg_servlet_port") == nil then port = 9443; end
require "net.httpserver".new_from_config({ port = port; ssl = { key = ssl_key, certificate = ssl_cert }; }, handle_req, { base = base_name });
end
end
if prosody.start_time then -- already started
setup();
else
prosody.events.add_handler("server-started", setup);
end
|
mod_register_json: Fixed http listener creation syntax. (Please document that in the API, that would avoid my brain overheating, thank you.)
|
mod_register_json: Fixed http listener creation syntax. (Please document that in the API, that would avoid my brain overheating, thank you.)
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
f0058db9c5c931fce4b30b813a0b56e960296f95
|
src/structure/IndexMap.lua
|
src/structure/IndexMap.lua
|
local class = require 'lib/30log'
inspect = require 'lib/inspect'
local IndexMap = class("IndexMap",{
addressbook = {},
placeables_index = {}
})
local Location = class("Location",{
address = nil,
placeables = {},
neighbors = {}
})
function Location:init(address, neighbors)
if address == nil then error('Tried to create location with nil address') end
self.address = address
self.placeables = {}
self.neighbors = neighbors or {}
end
function IndexMap:load(registry)
local hexes = {}
local armies = {}
local cities = {}
for i, id in ipairs(registry:getIdsByPool("GameInfo")) do
local obj = registry:get(id)
if obj.description == "gsHex" then
table.insert(hexes, obj)
elseif obj.description == "gsCity" then
table.insert(cities, obj)
elseif obj.description == "gsArmy" then
table.insert(armies, obj)
end
end
for i, obj in ipairs(hexes) do
local my_cities = {}
local my_armies = {}
local hex = obj:getComponent("GameInfo")
self:addAddress(hex.address, hex.neighbors)
for j, city in ipairs(cities) do
if city.address == hex.address then
self:addPlaceable(city.uid, hex.address)
end
end
for j, army in ipairs(armies) do
if army.address == hex.address then
self:addPlaceable(army.uid, hex.address)
end
end
end
end
function IndexMap:getNeighbors(addressId)
return self.addressbook[addressId].neighbors
end
function IndexMap:addNeighborsRelation(addressA, addressB)
table.insert(self.addressbook[addressA].neighbors,addressB)
table.insert(self.addressbook[addressB].neighbors,addressA)
end
function IndexMap:addAddress(address, neighborAddresses, placeableIds)
self.addressbook[address] = Location:new(address, neighborAddresses, placeableIds)
if placeableIds ~= nil then
for i = 1, #placeableIds do
if placeableIds[i] ~= nil then self:addPlaceable(placeableIds[i],address) end
end
end
end
function IndexMap:addPlaceable(placeableId, addressId)
self.placeables_index[placeableId] = addressId
table.insert(self.addressbook[addressId].placeables, placeableId)
end
function IndexMap:removePlaceable(placeableId, addressId)
if addressId == nil then
addressId = self:findPlaceableAddress(placeableId)
end
if addressId ~= nil then
for i, v in ipairs(self.addressbook[addressId].placeables) do
if v == placeableId then
table.remove(self.addressbook[addressId].placeables, i)
break
end
end
end
self.placeables_index[placeableId] = nil
end
function IndexMap:getPlaceablesAt(addressId)
return self.addressbook[addressId].placeables
end
function IndexMap:findPlaceableAddress(placeableId)
return self.placeables_index[placeableId]
end
function IndexMap:hasPlaceable(addressId, placeableId)
return self.placeables_index[placeableId] == addressId
end
function IndexMap:movePlaceable(placeableId, srcAddressId, dstAddressId)
if self:hasPlaceable(srcAddressId, placeableId) == true then
self:removePlaceable(placeableId, srcAddressId)
self:addPlaceable(placeableId, dstAddressId)
end
end
function IndexMap:summarizeAddress(addressId)
return "Address '" .. addressId .. "' contains " .. inspect(self:getPlaceablesAt(addressId)) .. " and borders " .. inspect(self:getNeighbors(addressId))
end
return IndexMap
|
local class = require 'lib/30log'
inspect = require 'lib/inspect'
local IndexMap = class("IndexMap",{
addressbook = {},
placeables_index = {}
})
local Location = class("Location",{
address = nil,
placeables = {},
neighbors = {}
})
function Location:init(address, neighbors)
if address == nil then error('Tried to create location with nil address') end
self.address = address
self.placeables = {}
self.neighbors = neighbors or {}
end
function IndexMap:load(registry)
local hexes = {}
local armies = {}
local cities = {}
for i, id in ipairs(registry:getIdsByPool("GameInfo")) do
local obj = registry:get(id)
if obj.description == "gsHex" then
table.insert(hexes, obj)
elseif obj.description == "gsCity" then
table.insert(cities, obj)
elseif obj.description == "gsArmy" then
table.insert(armies, obj)
end
end
for i, obj in ipairs(hexes) do
local my_cities = {}
local my_armies = {}
local hex = obj:getComponent("GameInfo")
self:addAddress(hex.address, hex.neighbors)
for j, city in ipairs(cities) do
local myc = city:getComponent("GameInfo")
if myc.address == hex.address then
self:addPlaceable(city.uid, hex.address)
end
end
for j, army in ipairs(armies) do
local mya = army:getComponent("GameInfo")
if mya.address == hex.address then
self:addPlaceable(army.uid, hex.address)
end
end
end
end
function IndexMap:getNeighbors(addressId)
return self.addressbook[addressId].neighbors
end
function IndexMap:addNeighborsRelation(addressA, addressB)
table.insert(self.addressbook[addressA].neighbors,addressB)
table.insert(self.addressbook[addressB].neighbors,addressA)
end
function IndexMap:addAddress(address, neighborAddresses, placeableIds)
self.addressbook[address] = Location:new(address, neighborAddresses, placeableIds)
if placeableIds ~= nil then
for i = 1, #placeableIds do
if placeableIds[i] ~= nil then self:addPlaceable(placeableIds[i],address) end
end
end
end
function IndexMap:addPlaceable(placeableId, addressId)
self.placeables_index[placeableId] = addressId
table.insert(self.addressbook[addressId].placeables, placeableId)
end
function IndexMap:removePlaceable(placeableId, addressId)
if addressId == nil then
addressId = self:findPlaceableAddress(placeableId)
end
if addressId ~= nil then
for i, v in ipairs(self.addressbook[addressId].placeables) do
if v == placeableId then
table.remove(self.addressbook[addressId].placeables, i)
break
end
end
end
self.placeables_index[placeableId] = nil
end
function IndexMap:getPlaceablesAt(addressId)
return self.addressbook[addressId].placeables
end
function IndexMap:findPlaceableAddress(placeableId)
return self.placeables_index[placeableId]
end
function IndexMap:hasPlaceable(addressId, placeableId)
return self.placeables_index[placeableId] == addressId
end
function IndexMap:movePlaceable(placeableId, srcAddressId, dstAddressId)
if self:hasPlaceable(srcAddressId, placeableId) == true then
self:removePlaceable(placeableId, srcAddressId)
self:addPlaceable(placeableId, dstAddressId)
end
end
function IndexMap:summarizeAddress(addressId)
return "Address '" .. addressId .. "' contains " .. inspect(self:getPlaceablesAt(addressId)) .. " and borders " .. inspect(self:getNeighbors(addressId))
end
return IndexMap
|
Fix placeable placement
|
Fix placeable placement
|
Lua
|
mit
|
Sewerbird/Helios2400,Sewerbird/Helios2400,Sewerbird/Helios2400
|
0132be5a5f802ce29ec4a76884a5b742b7fbe03f
|
MMOCoreORB/bin/scripts/quest/tasks/patrol.lua
|
MMOCoreORB/bin/scripts/quest/tasks/patrol.lua
|
local Task = require("quest.tasks.task")
local ObjectManager = require("managers.object.object_manager")
local QuestManager = require("managers.quest.quest_manager")
local Logger = require("utils.logger")
Patrol = Task:new {
-- Task properties
taskName = "",
-- Patrol properties
waypointName = "",
numPoints = 0,
areaSize = 0,
originX = 0,
originY = 0,
forceSpawn = false,
onPlayerKilled = nil,
onEnteredActiveArea = nil
}
function Patrol:setupPatrolPoints(pCreature)
local playerID = SceneObject(pCreature):getObjectID()
local radius = 1024 -- Default radius
local curQuest = QuestManager.getCurrentQuestID(pCreature)
local pQuest = getQuestInfo(curQuest)
if (pQuest ~= nil) then
local questRadius = LuaQuestInfo(pQuest):getQuestParameter()
if (questRadius ~= "" and questRadius ~= nil) then
radius = tonumber(questRadius)
end
end
for i = 1, self.numPoints, 1 do
local offsetX = getRandomNumber(-75, 75)
local offsetY = getRandomNumber(-75, 75)
local offsetTheta = getRandomNumber(-2, 2)
local theta = (i * 45 + offsetTheta) * 0.0175;
local x = (self.originX + offsetX) + (radius * math.cos(theta))
local y = (self.originY + offsetY) + (radius * math.sin(theta))
local spawnPoint = getSpawnPoint(pCreature, x, y, 0, 200, self.forceSpawn)
local planetName = SceneObject(pCreature):getZoneName()
local pActiveArea = spawnActiveArea(planetName, "object/active_area.iff", spawnPoint[1], spawnPoint[2], spawnPoint[3], self.areaSize, 0)
if (pActiveArea == nil) then
return nil
end
local areaID = SceneObject(pActiveArea):getObjectID()
writeData(areaID .. self.taskName .. "ownerID", playerID)
writeData(areaID .. self.taskName .. "waypointNum", i)
writeData(playerID .. self.taskName .. "waypointNum" .. i, areaID)
createObserver(ENTEREDAREA, self.taskName, "handleEnteredAreaEvent", pActiveArea)
ObjectManager.withCreaturePlayerObject(pCreature, function(ghost)
local waypointID = ghost:addWaypoint(planetName, self.waypointName, "", spawnPoint[1], spawnPoint[3], WAYPOINTYELLOW, true, true, 0, 0)
writeData(areaID .. self.taskName .. "waypointID", waypointID)
end)
end
end
function Patrol:handleEnteredAreaEvent(pActiveArea, pCreature)
if pActiveArea == nil or not SceneObject(pCreature):isPlayerCreature() then
return 0
end
local areaID = SceneObject(pActiveArea):getObjectID()
local ownerID = readData(areaID .. self.taskName .. "ownerID")
if ownerID == SceneObject(pCreature):getObjectID() then
local wpNum = readData(areaID .. self.taskName .. "waypointNum")
self:destroyWaypoint(pCreature, wpNum)
local wpDone = readData(ownerID .. ":patrolWaypointsReached") + 1
writeData(ownerID .. ":patrolWaypointsReached", wpDone)
self:onEnteredActiveArea(pCreature, pActiveArea)
SceneObject(pActiveArea):destroyObjectFromWorld()
return 1
end
return 0
end
function Patrol:destroyWaypoint(pCreature, num)
local playerID = SceneObject(pCreature):getObjectID()
local areaID = readData(playerID .. self.taskName .. "waypointNum" .. num)
local waypointNum = readData(areaID .. self.taskName .. "waypointNum")
local waypointID = readData(areaID .. self.taskName .. "waypointID")
ObjectManager.withCreaturePlayerObject(pCreature, function(ghost)
ghost:removeWaypoint(waypointID, true)
end)
local pActiveArea = getSceneObject(areaID)
if (pActiveArea ~= nil) then
SceneObject(pActiveArea):destroyObjectFromWorld()
end
deleteData(playerID .. self.taskName .. "waypointNum" .. waypointNum)
deleteData(areaID .. self.taskName .. "waypointID")
deleteData(areaID .. self.taskName .. "waypointNum")
deleteData(areaID .. self.taskName .. "ownerID")
end
function Patrol:waypointCleanup(pCreature)
for i = 1, self.numPoints, 1 do
self:destroyWaypoint(pCreature, i)
end
end
function Patrol:failPatrol(pCreature)
self:waypointCleanup(pCreature)
local playerID = SceneObject(pCreature):getObjectID()
deleteData(playerID .. ":patrolWaypointsReached")
writeData(playerID .. ":failedPatrol", 1)
return true
end
function Patrol:taskStart(pCreature)
self:setupPatrolPoints(pCreature)
createObserver(OBJECTDESTRUCTION, self.taskName, "playerKilled", pCreature)
end
function Patrol:playerKilled(pCreature, pKiller, nothing)
if (pCreature == nil) then
return 0
end
self:callFunctionIfNotNil(self.onPlayerKilled, false, pCreature)
return 0
end
function Patrol:taskFinish(pCreature)
local playerID = SceneObject(pCreature):getObjectID()
deleteData(playerID .. ":patrolWaypointsReached")
deleteData(playerID .. ":failedPatrol")
self:waypointCleanup(pCreature)
return true
end
return Patrol
|
local Task = require("quest.tasks.task")
local ObjectManager = require("managers.object.object_manager")
local QuestManager = require("managers.quest.quest_manager")
local Logger = require("utils.logger")
Patrol = Task:new {
-- Task properties
taskName = "",
-- Patrol properties
waypointName = "",
numPoints = 0,
areaSize = 0,
originX = 0,
originY = 0,
forceSpawn = false,
onPlayerKilled = nil,
onEnteredActiveArea = nil
}
function Patrol:setupPatrolPoints(pCreature)
local playerID = SceneObject(pCreature):getObjectID()
local radius = 1024 -- Default radius
local curQuest = QuestManager.getCurrentQuestID(pCreature)
local pQuest = getQuestInfo(curQuest)
if (pQuest ~= nil) then
local questRadius = LuaQuestInfo(pQuest):getQuestParameter()
if (questRadius ~= "" and questRadius ~= nil) then
radius = tonumber(questRadius)
end
end
for i = 1, self.numPoints, 1 do
local offsetX = getRandomNumber(-75, 75)
local offsetY = getRandomNumber(-75, 75)
local offsetTheta = getRandomNumber(-2, 2)
local theta = (i * 45 + offsetTheta) * 0.0175;
local x = (self.originX + offsetX) + (radius * math.cos(theta))
local y = (self.originY + offsetY) + (radius * math.sin(theta))
local planetName = SceneObject(pCreature):getZoneName()
local spawnPoint = getSpawnPoint(planetName, x, y, 0, 200, self.forceSpawn)
local pActiveArea = spawnActiveArea(planetName, "object/active_area.iff", spawnPoint[1], spawnPoint[2], spawnPoint[3], self.areaSize, 0)
if (pActiveArea == nil) then
return nil
end
local areaID = SceneObject(pActiveArea):getObjectID()
writeData(areaID .. self.taskName .. "ownerID", playerID)
writeData(areaID .. self.taskName .. "waypointNum", i)
writeData(playerID .. self.taskName .. "waypointNum" .. i, areaID)
createObserver(ENTEREDAREA, self.taskName, "handleEnteredAreaEvent", pActiveArea)
ObjectManager.withCreaturePlayerObject(pCreature, function(ghost)
local waypointID = ghost:addWaypoint(planetName, self.waypointName, "", spawnPoint[1], spawnPoint[3], WAYPOINTYELLOW, true, true, 0, 0)
writeData(areaID .. self.taskName .. "waypointID", waypointID)
end)
end
end
function Patrol:handleEnteredAreaEvent(pActiveArea, pCreature)
if pActiveArea == nil or not SceneObject(pCreature):isPlayerCreature() then
return 0
end
local areaID = SceneObject(pActiveArea):getObjectID()
local ownerID = readData(areaID .. self.taskName .. "ownerID")
if ownerID == SceneObject(pCreature):getObjectID() then
local wpNum = readData(areaID .. self.taskName .. "waypointNum")
self:destroyWaypoint(pCreature, wpNum)
local wpDone = readData(ownerID .. ":patrolWaypointsReached") + 1
writeData(ownerID .. ":patrolWaypointsReached", wpDone)
self:onEnteredActiveArea(pCreature, pActiveArea)
SceneObject(pActiveArea):destroyObjectFromWorld()
return 1
end
return 0
end
function Patrol:destroyWaypoint(pCreature, num)
local playerID = SceneObject(pCreature):getObjectID()
local areaID = readData(playerID .. self.taskName .. "waypointNum" .. num)
local waypointNum = readData(areaID .. self.taskName .. "waypointNum")
local waypointID = readData(areaID .. self.taskName .. "waypointID")
ObjectManager.withCreaturePlayerObject(pCreature, function(ghost)
ghost:removeWaypoint(waypointID, true)
end)
local pActiveArea = getSceneObject(areaID)
if (pActiveArea ~= nil) then
SceneObject(pActiveArea):destroyObjectFromWorld()
end
deleteData(playerID .. self.taskName .. "waypointNum" .. waypointNum)
deleteData(areaID .. self.taskName .. "waypointID")
deleteData(areaID .. self.taskName .. "waypointNum")
deleteData(areaID .. self.taskName .. "ownerID")
end
function Patrol:waypointCleanup(pCreature)
for i = 1, self.numPoints, 1 do
self:destroyWaypoint(pCreature, i)
end
end
function Patrol:failPatrol(pCreature)
self:waypointCleanup(pCreature)
local playerID = SceneObject(pCreature):getObjectID()
deleteData(playerID .. ":patrolWaypointsReached")
writeData(playerID .. ":failedPatrol", 1)
return true
end
function Patrol:taskStart(pCreature)
self:setupPatrolPoints(pCreature)
createObserver(OBJECTDESTRUCTION, self.taskName, "playerKilled", pCreature)
end
function Patrol:playerKilled(pCreature, pKiller, nothing)
if (pCreature == nil) then
return 0
end
self:callFunctionIfNotNil(self.onPlayerKilled, false, pCreature)
return 0
end
function Patrol:taskFinish(pCreature)
local playerID = SceneObject(pCreature):getObjectID()
deleteData(playerID .. ":patrolWaypointsReached")
deleteData(playerID .. ":failedPatrol")
self:waypointCleanup(pCreature)
return true
end
return Patrol
|
[fixed] stability issue
|
[fixed] stability issue
Change-Id: I03b8c3945bb2d05bb4e18bf704acdced189804e5
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
|
54cedbf76ed4c03e8b8ae0c2e1540d1c8f0c44a0
|
premake.lua
|
premake.lua
|
project.name = "Premake4"
-- Project options
addoption("no-tests", "Build without automated tests")
-- Output directories
project.config["Debug"].bindir = "bin/debug"
project.config["Release"].bindir = "bin/release"
-- Packages
dopackage("src")
-- Cleanup code
function doclean(cmd, arg)
docommand(cmd, arg)
os.rmdir("bin")
os.rmdir("doc")
end
-- Release code
REPOS = "https://premake.svn.sourceforge.net/svnroot/premake"
TRUNK = "/trunk"
BRANCHES = "/branches/4.0-alpha/"
function dorelease(cmd, arg)
if (not arg) then
error "You must specify a version"
end
-------------------------------------------------------------------
-- Make sure everything is good before I start
-------------------------------------------------------------------
print("")
print("PRE-FLIGHT CHECKLIST")
print(" * is README up-to-date?")
print(" * is CHANGELOG up-to-date?")
print(" * did you test build with GCC?")
print(" * did you test build with Doxygen?")
print(" * are 'svn' (all) and '7z' (Windows) available?")
print("")
print("Press [Enter] to continue or [^C] to quit.")
io.stdin:read("*l")
-------------------------------------------------------------------
-- Set up environment
-------------------------------------------------------------------
local version = arg
os.mkdir("releases")
local folder = "premake-"..version
local trunk = REPOS..TRUNK
local branch = REPOS..BRANCHES..version
-------------------------------------------------------------------
-- Build and run all automated tests on working copy
-------------------------------------------------------------------
print("Building tests on working copy...")
os.execute("premake --target gnu >releases/release.log")
result = os.execute("make CONFIG=Release >releases/release.log")
if (result ~= 0) then
error("Test build failed; see release.log for details")
end
-------------------------------------------------------------------
-- Look for a release branch in SVN, and create one from trunk if necessary
-------------------------------------------------------------------
print("Checking for release branch...")
os.chdir("releases")
result = os.execute(string.format("svn ls %s >release.log 2>&1", branch))
if (result ~= 0) then
print("Creating release branch...")
result = os.execute(string.format('svn copy %s %s -m "Creating release branch for %s" >release.log', trunk, branch, version))
if (result ~= 0) then
error("Failed to create release branch at "..branch)
end
end
-------------------------------------------------------------------
-- Checkout a local copy of the release branch
-------------------------------------------------------------------
print("Getting source code from release branch...")
os.execute(string.format("svn co %s %s >release.log", branch, folder))
if (not os.fileexists(folder.."/README.txt")) then
error("Unable to checkout from repository at "..branch)
end
-------------------------------------------------------------------
-- Embed version numbers into the files
-------------------------------------------------------------------
-- (embed version #s)
-- (check into branch)
-------------------------------------------------------------------
-- Build the release binary for this platform
-------------------------------------------------------------------
print("Building release version...")
os.chdir(folder)
os.execute("premake --clean --no-tests --target gnu >../release.log")
os.chdir("bin/release")
if (windows) then
os.execute("make CONFIG=Release >../release.log")
result = os.execute(string.format("7z a -tzip ..\\..\\..\\premake-win32-%s.zip premake4.exe >../release.log", version))
elseif (macosx) then
os.execute('TARGET_ARCH="-arch i386 -arch ppc" make CONFIG=Release >../release.log')
result = os.execute(string.format("tar czvf ../../../premake-macosx-%s.tar.gz premake4 >../release.log", version))
else
os.execute("make CONFIG=Release >../release.log")
result = os.execute(string.format("tar czvf ../../../premake-linux-%s.tar.gz bin/release/premake4 >../release.log", version))
end
if (result ~= 0) then
error("Failed to build binary package; see release.log for details")
end
os.chdir("../../..")
-------------------------------------------------------------------
-- Build the source code package (MacOSX only)
-------------------------------------------------------------------
if (macosx) then
result = os.execute(string.format("zip -r9 premake-src-%s.zip %s/* >release.log", version, folder))
if (result ~= 0) then
error("Failed to build source code package; see release.log for details")
end
end
-------------------------------------------------------------------
-- Clean up
-------------------------------------------------------------------
print("Cleaning up...")
os.rmdir(folder)
os.remove("release.log")
-------------------------------------------------------------------
-- Next steps
-------------------------------------------------------------------
if (windows) then
print("DONE - now run release script under Linux")
elseif (linux) then
print("DONE - now run release script under Mac OS X")
else
print("DONE - really this time")
end
end
|
project.name = "Premake4"
-- Project options
addoption("no-tests", "Build without automated tests")
-- Output directories
project.config["Debug"].bindir = "bin/debug"
project.config["Release"].bindir = "bin/release"
-- Packages
dopackage("src")
-- Cleanup code
function doclean(cmd, arg)
docommand(cmd, arg)
os.rmdir("bin")
os.rmdir("doc")
end
-- Release code
REPOS = "https://premake.svn.sourceforge.net/svnroot/premake"
TRUNK = "/trunk"
BRANCHES = "/branches/4.0-alpha/"
function dorelease(cmd, arg)
if (not arg) then
error "You must specify a version"
end
-------------------------------------------------------------------
-- Make sure everything is good before I start
-------------------------------------------------------------------
print("")
print("PRE-FLIGHT CHECKLIST")
print(" * is README up-to-date?")
print(" * is CHANGELOG up-to-date?")
print(" * did you test build with GCC?")
print(" * did you test build with Doxygen?")
print(" * are 'svn' (all) and '7z' (Windows) available?")
print("")
print("Press [Enter] to continue or [^C] to quit.")
io.stdin:read("*l")
-------------------------------------------------------------------
-- Set up environment
-------------------------------------------------------------------
local version = arg
os.mkdir("releases")
local folder = "premake-"..version
local trunk = REPOS..TRUNK
local branch = REPOS..BRANCHES..version
-------------------------------------------------------------------
-- Build and run all automated tests on working copy
-------------------------------------------------------------------
print("Building tests on working copy...")
os.execute("premake --target gnu >releases/release.log")
result = os.execute("make CONFIG=Release >releases/release.log")
if (result ~= 0) then
error("Test build failed; see release.log for details")
end
-------------------------------------------------------------------
-- Look for a release branch in SVN, and create one from trunk if necessary
-------------------------------------------------------------------
print("Checking for release branch...")
os.chdir("releases")
result = os.execute(string.format("svn ls %s >release.log 2>&1", branch))
if (result ~= 0) then
print("Creating release branch...")
result = os.execute(string.format('svn copy %s %s -m "Creating release branch for %s" >release.log', trunk, branch, version))
if (result ~= 0) then
error("Failed to create release branch at "..branch)
end
end
-------------------------------------------------------------------
-- Checkout a local copy of the release branch
-------------------------------------------------------------------
print("Getting source code from release branch...")
os.execute(string.format("svn co %s %s >release.log", branch, folder))
if (not os.fileexists(folder.."/README.txt")) then
error("Unable to checkout from repository at "..branch)
end
-------------------------------------------------------------------
-- Embed version numbers into the files
-------------------------------------------------------------------
-- (embed version #s)
-- (check into branch)
-------------------------------------------------------------------
-- Build the release binary for this platform
-------------------------------------------------------------------
print("Building release version...")
os.chdir(folder)
os.execute("premake --clean --no-tests --target gnu >../release.log")
if (windows) then
os.execute("make CONFIG=Release >../release.log")
os.chdir("bin/release")
result = os.execute(string.format("7z a -tzip ..\\..\\..\\premake-win32-%s.zip premake4.exe >../release.log", version))
elseif (macosx) then
os.execute('TARGET_ARCH="-arch i386 -arch ppc" make CONFIG=Release >../release.log')
os.chdir("bin/release")
result = os.execute(string.format("tar czvf ../../../premake-macosx-%s.tar.gz premake4 >../release.log", version))
else
os.execute("make CONFIG=Release >../release.log")
os.chdir("bin/release")
result = os.execute(string.format("tar czvf ../../../premake-linux-%s.tar.gz bin/release/premake4 >../release.log", version))
end
if (result ~= 0) then
error("Failed to build binary package; see release.log for details")
end
os.chdir("../../..")
-------------------------------------------------------------------
-- Build the source code package (MacOSX only)
-------------------------------------------------------------------
if (macosx) then
result = os.execute(string.format("zip -r9 premake-src-%s.zip %s/* >release.log", version, folder))
if (result ~= 0) then
error("Failed to build source code package; see release.log for details")
end
end
-------------------------------------------------------------------
-- Clean up
-------------------------------------------------------------------
print("Cleaning up...")
os.rmdir(folder)
os.remove("release.log")
-------------------------------------------------------------------
-- Next steps
-------------------------------------------------------------------
if (windows) then
print("DONE - now run release script under Linux")
elseif (linux) then
print("DONE - now run release script under Mac OS X")
else
print("DONE - really this time")
end
end
|
Another fix to my fix
|
Another fix to my fix
--HG--
extra : convert_revision : svn%3A644ed5ae-bb15-0410-aa60-99f397bbb77a/trunk%40409
|
Lua
|
bsd-3-clause
|
Lusito/premake,annulen/premake-annulen,annulen/premake-annulen,annulen/premake-annulen,annulen/premake-dev-rgeary,Lusito/premake,warrenseine/premake,annulen/premake-dev-rgeary,annulen/premake,Lusito/premake,annulen/premake,annulen/premake,annulen/premake-annulen,Lusito/premake,annulen/premake,warrenseine/premake,warrenseine/premake,annulen/premake-dev-rgeary
|
46def6db0b9deba9c32cb14c8e4cb9bde459e453
|
Modules/Events/Maid.lua
|
Modules/Events/Maid.lua
|
--[[Maid
Manages the cleaning of events and other things.
Modified by Quenty
API:
MakeMaid() Returns a new Maid object.
Maid[key] = (function) Adds a task to perform when cleaning up.
Maid[key] = (event connection) Manages an event connection. Anything that isn"t a function is assumed to be this.
Maid[key] = (Maid) Maids can act as an event connection, allowing a Maid to have other maids to clean up.
Maid[key] = (Object) Maids can cleanup objects with a `Destroy` method
Maid[key] = nil Removes a named task. If the task is an event, it is disconnected. If it is an object, it is destroyed.
Maid:GiveTask(task) Same as above, but uses an incremented number as a key.
Maid:DoCleaning() Disconnects all managed events and performs all clean-up tasks.
Maid:IsCleaning() Returns true is in cleaning process.
Maid:Destroy() Alias for DoCleaning()
]]
--- Manages the cleaning of events and other things.
local Maid = {}
--- Returns a new Maid object
function Maid.new()
local self = {}
self.Tasks = {}
return setmetatable(self, Maid)
end
Maid.MakeMaid = Maid.new
--- Returns Maid[key] if not part of Maid metatable
-- @return Maid[key] value
function Maid:__index(Index)
if Maid[Index] then
return Maid[Index]
else
return self.Tasks[Index]
end
end
--- Add a task to clean up
-- Maid[key] = (function) Adds a task to perform
-- Maid[key] = (event connection) Manages an event connection
-- Maid[key] = (Maid) Maids can act as an event connection, allowing a Maid to have other maids to clean up.
-- Maid[key] = (Object) Maids can cleanup objects with a `Destroy` method
-- Maid[key] = nil Removes a named task. If the task is an event, it is disconnected. If it is an object, it is destroyed.
function Maid:__newindex(Index, NewTask)
if Maid[Index] ~= nil then
error(("'%s' is reserved"):format(tostring(Index)), 2)
end
local Tasks = self.Tasks
local OldTask = Tasks[Index]
Tasks[Index] = NewTask
if OldTask then
if type(OldTask) == "function" then
OldTask()
elseif typeof(OldTask) == "RBXScriptConnection" then
OldTask:disconnect()
elseif OldTask.Destroy then
OldTask:Destroy()
end
end
end
--- Same as indexing, but uses an incremented number as a key
-- @param Task An item to clean
-- @return int TaskId
function Maid:GiveTask(Task)
local TaskId = #self.Tasks+1
self[TaskId] = Task
return TaskId
end
--- Cleans up all tasks
function Maid:DoCleaning()
local Tasks = self.Tasks
-- Disconnect all events first as we know this is safe
for Index, Task in pairs(Tasks) do
Tasks[Index] = nil
if typeof(Task) == "RBXScriptConnection" then
Task:disconnect()
end
end
-- Clear out tasks table completely, even if clean up tasks add more tasks to the maid
local Index, Task = next(Tasks)
while Task ~= nil do
Tasks[Index] = nil
if type(Task) == "function" then
Task()
elseif typeof(Task) == "RBXScriptConnection" then
Task:disconnect()
elseif Task.Destroy then
Task:Destroy()
end
Index, Task = next(Tasks)
end
end
Maid.Destroy = Maid.DoCleaning -- Allow maids to nested
return Maid
|
--[[Maid
Manages the cleaning of events and other things.
Modified by Quenty
API:
MakeMaid() Returns a new Maid object.
Maid[key] = (function) Adds a task to perform when cleaning up.
Maid[key] = (event connection) Manages an event connection. Anything that isn"t a function is assumed to be this.
Maid[key] = (Maid) Maids can act as an event connection, allowing a Maid to have other maids to clean up.
Maid[key] = (Object) Maids can cleanup objects with a `Destroy` method
Maid[key] = nil Removes a named task. If the task is an event, it is disconnected. If it is an object, it is destroyed.
Maid:GiveTask(task) Same as above, but uses an incremented number as a key.
Maid:DoCleaning() Disconnects all managed events and performs all clean-up tasks.
Maid:IsCleaning() Returns true is in cleaning process.
Maid:Destroy() Alias for DoCleaning()
]]
--- Manages the cleaning of events and other things.
local Maid = {}
--- Returns a new Maid object
function Maid.new()
local self = {}
self.Tasks = {}
return setmetatable(self, Maid)
end
Maid.MakeMaid = Maid.new
--- Returns Maid[key] if not part of Maid metatable
-- @return Maid[key] value
function Maid:__index(Index)
if Maid[Index] then
return Maid[Index]
else
return self.Tasks[Index]
end
end
--- Add a task to clean up
-- Maid[key] = (function) Adds a task to perform
-- Maid[key] = (event connection) Manages an event connection
-- Maid[key] = (Maid) Maids can act as an event connection, allowing a Maid to have other maids to clean up.
-- Maid[key] = (Object) Maids can cleanup objects with a `Destroy` method
-- Maid[key] = nil Removes a named task. If the task is an event, it is disconnected. If it is an object, it is destroyed.
function Maid:__newindex(Index, NewTask)
if Maid[Index] ~= nil then
error(("'%s' is reserved"):format(tostring(Index)), 2)
end
local Tasks = self.Tasks
local OldTask = Tasks[Index]
Tasks[Index] = NewTask
if OldTask then
if type(OldTask) == "function" then
OldTask()
elseif typeof(OldTask) == "RBXScriptConnection" then
OldTask:disconnect()
elseif OldTask.Destroy then
OldTask:Destroy()
end
end
end
--- Same as indexing, but uses an incremented number as a key
-- @param Task An item to clean
-- @return int TaskId
function Maid:GiveTask(Task)
local TaskId = #self.Tasks+1
self[TaskId] = Task
return TaskId
end
--- Cleans up all tasks
function Maid:DoCleaning()
local Tasks = self.Tasks
-- Disconnect all events first as we know this is safe
for Index, Task in pairs(Tasks) do
if typeof(Task) == "RBXScriptConnection" then
Tasks[Index] = nil
Task:disconnect()
end
end
-- Clear out tasks table completely, even if clean up tasks add more tasks to the maid
local Index, Task = next(Tasks)
while Task ~= nil do
Tasks[Index] = nil
if type(Task) == "function" then
Task()
elseif typeof(Task) == "RBXScriptConnection" then
Task:disconnect()
elseif Task.Destroy then
Task:Destroy()
end
Index, Task = next(Tasks)
end
end
Maid.Destroy = Maid.DoCleaning
return Maid
|
FIx some typos with Maid,
|
FIx some typos with Maid,
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
e4d8cb8a0ed3c6dfd35cc1ce4b64c90b903247a1
|
ovi-store.lua
|
ovi-store.lua
|
dofile("urlcode.lua")
dofile("table_show.lua")
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
local downloaded = {}
local addedtolist = {}
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
local html = urlpos["link_expect_html"]
local parenturl = parent["url"]
local html = nil
if downloaded[url] == true or addedtolist[url] == true then
return false
end
if item_type == "app" and (downloaded[url] ~= true and addedtolist[url] ~= true) then
if string.match(url, "[^0-9]"..item_value.."[0-9][^0-9]") and not string.match(url, "https?://store%.ovi%.com/content/"..item_value.."[0-9]/applications%?categoryId=[0-9]+") then
return verdict
elseif html == 0 then
return verdict
else
return false
end
end
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
local html = nil
local function check(url)
if (downloaded[url] ~= true and addedtolist[url] ~= true) and not string.match(url, "https?://store%.ovi%.com/content/"..item_value.."[0-9]/applications%?categoryId=[0-9]+") then
table.insert(urls, { url=url })
addedtolist[url] = true
end
end
if item_type == "app" then
if string.match(url, "https?://store%.ovi%.com/content/[0-9]+/Download") then
html = read_file(file)
for newurl in string.gmatch(html, "(https?://[^\n]+)") do
if string.match(newurl, "https?://[a-z]%.ovi%.com/[a-z]/[a-z]/store/") or string.match(newurl, " https?://wam%.browser%.ovi%.com/[^/]+/v1_0/clients/") then
check(newurl)
end
end
end
if string.match(url, "[^0-9]"..item_value.."[0-9]") then
html = read_file(file)
for newurl in string.gmatch(html, 'src="(https?://[^"]+)"') do
if string.match(newurl, "https?://[a-z]%.[a-z]%.ovi%.com/[a-z]/[a-z]/store/") then
check(newurl)
end
end
end
if string.match(url, "[a-z]%.[a-z]%.ovi%.com/[a-z]/[a-z]/store/[0-9]+/[^%?]+%?") then
local newurl = string.match(url, "(https?://[^/]+/[a-z]/[a-z]/store/[0-9]+/[^%?]+)%?")
check(newurl)
end
end
return urls
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
local status_code = http_stat["statcode"]
last_http_statcode = status_code
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n")
io.stdout:flush()
if (status_code >= 200 and status_code <= 399) or status_code == 403 then
if string.match(url["url"], "https://") then
local newurl = string.gsub(url["url"], "https://", "http://")
downloaded[newurl] = true
else
downloaded[url["url"]] = true
end
end
if string.match(url["url"], "https?://store%.ovi%.com/content/[0-9]+/Download") and status_code == 500 then
return wget.actions.ABORT
elseif string.match(url["url"], "https?://[a-z]%.[a-z]%.ovi%.com/") and status_code == 400 then
return wget.actions.EXIT
elseif string.match(url["url"], "https?://[a-z]%.ovi%.com/") and status_code == 400 then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.EXIT
else
return wget.actions.CONTINUE
end
elseif status_code >= 500 or
(status_code >= 400 and status_code ~= 404 and status_code ~= 403) then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 1")
tries = tries + 1
if tries >= 20 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
elseif status_code == 0 then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 10 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
-- local sleep_time = 0.1 * (math.random(500, 5000) / 100.0)
local sleep_time = 0
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
dofile("urlcode.lua")
dofile("table_show.lua")
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
local downloaded = {}
local addedtolist = {}
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
local html = urlpos["link_expect_html"]
local parenturl = parent["url"]
local html = nil
if downloaded[url] == true or addedtolist[url] == true then
return false
end
if item_type == "app" and (downloaded[url] ~= true and addedtolist[url] ~= true) then
if string.match(url, "[^0-9]"..item_value.."[0-9][^0-9]")
and not string.match(url, "https?://store%.ovi%.com/content/"..item_value.."[0-9]/.*applications%?categoryId=[0-9]+")
and not string.match(url, "https?://store%.ovi%.com/content/"..item_value.."[0-9]/channel/channel/")
then
return verdict
elseif html == 0 then
return verdict
else
return false
end
end
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
local html = nil
local function check(url)
if (downloaded[url] ~= true and addedtolist[url] ~= true)
and not string.match(url, "https?://store%.ovi%.com/content/"..item_value.."[0-9]/.*applications%?categoryId=[0-9]+")
and not string.match(url, "https?://store%.ovi%.com/content/"..item_value.."[0-9]/channel/channel/") then
table.insert(urls, { url=url })
addedtolist[url] = true
end
end
if item_type == "app" then
if string.match(url, "https?://store%.ovi%.com/content/[0-9]+/Download") then
html = read_file(file)
for newurl in string.gmatch(html, "(https?://[^\n]+)") do
if string.match(newurl, "https?://[a-z]%.ovi%.com/[a-z]/[a-z]/store/") or string.match(newurl, " https?://wam%.browser%.ovi%.com/[^/]+/v1_0/clients/") then
check(newurl)
end
end
end
if string.match(url, "[^0-9]"..item_value.."[0-9]") then
html = read_file(file)
for newurl in string.gmatch(html, 'src="(https?://[^"]+)"') do
if string.match(newurl, "https?://[a-z]%.[a-z]%.ovi%.com/[a-z]/[a-z]/store/") then
check(newurl)
end
end
end
if string.match(url, "[a-z]%.[a-z]%.ovi%.com/[a-z]/[a-z]/store/[0-9]+/[^%?]+%?") then
local newurl = string.match(url, "(https?://[^/]+/[a-z]/[a-z]/store/[0-9]+/[^%?]+)%?")
check(newurl)
end
end
return urls
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
local status_code = http_stat["statcode"]
last_http_statcode = status_code
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n")
io.stdout:flush()
if (status_code >= 200 and status_code <= 399) or status_code == 403 then
if string.match(url["url"], "https://") then
local newurl = string.gsub(url["url"], "https://", "http://")
downloaded[newurl] = true
else
downloaded[url["url"]] = true
end
end
if string.match(url["url"], "https?://store%.ovi%.com/content/[0-9]+/Download") and status_code == 500 then
return wget.actions.ABORT
elseif string.match(url["url"], "https?://[a-z]%.[a-z]%.ovi%.com/") and status_code == 400 then
return wget.actions.EXIT
elseif string.match(url["url"], "https?://[a-z]%.ovi%.com/") and status_code == 400 then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.EXIT
else
return wget.actions.CONTINUE
end
elseif status_code >= 500 or
(status_code >= 400 and status_code ~= 404 and status_code ~= 403) then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 1")
tries = tries + 1
if tries >= 20 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
elseif status_code == 0 then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 10 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
-- local sleep_time = 0.1 * (math.random(500, 5000) / 100.0)
local sleep_time = 0
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
Fix ignoring related applications page
|
Fix ignoring related applications page
Fixes repeatedly fetching 404 urls
|
Lua
|
unlicense
|
ArchiveTeam/ovi-store-grab,ArchiveTeam/ovi-store-grab
|
00d58945499d82d55cd2de4c8cde4a09dc4b1560
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/ain_config/ain_ef_config_set_defaults_and_powercycle.lua
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/ain_config/ain_ef_config_set_defaults_and_powercycle.lua
|
-- This is a general AIN_EF config example that shows the basic process for
-- configuring any AIN_EF feature on a T-Series device, saving them as defaults
-- and then powercycling the device. This example configures AIN0 and AIN2 to
-- enable the Average/Min/Max extended feature.
-- For a list of all AIN_EF options, see the T-Series datasheet:
-- https://labjack.com/support/datasheets/t-series/ain/extended-features
print("Generic Config AIN_EF & set power-up defaults")
-- Note: THIS SHOULD NOT BE RUN MULTIPLE TIMES. IT WILL SLOWLY CAUSE FLASH WEAR.
-- Generic function that can be used to configure general analog input settings
-- such as Range, Resolution, and Settling. More information about these
-- settings can be found on the LabJack website under the AIN section:
-- https://labjack.com/support/datasheets/t-series/ain
function ainEFConfig(chNum, index, cfgA, cfgB, cfgC, cfgD, cfgE, cfgF, cfgG, cfgH, cfgI, cfgJ)
MB.W(9000 + chNum * 2, 1, 0) -- Disable AIN_EF
MB.W(9000 + chNum * 2, 1, index) -- Enable AIN_EF
MB.W(9300 + chNum * 2, 1, cfgA)
MB.W(9600 + chNum * 2, 1, cfgB)
MB.W(9900 + chNum * 2, 1, cfgC)
MB.W(10200 + chNum * 2, 3, cfgD)
MB.W(10500 + chNum * 2, 3, cfgE)
MB.W(10800 + chNum * 2, 3, cfgF)
MB.W(11100 + chNum * 2, 3, cfgG)
MB.W(11400 + chNum * 2, 3, cfgH)
MB.W(11700 + chNum * 2, 3, cfgI)
MB.W(12000 + chNum * 2, 3, cfgJ)
end
ainChannels = {0, 2} -- Enable AIN0 and AIN2
numSamples = 200
scanRate = 6000
-- Configure each analog input
for i=1,table.getn(ainChannels) do
ainEFConfig(ainChannels[i], 3,numSamples,0,0,scanRate,0,0,0,0,0,0)
end
-- Set as power-up default
print("Saving settings as power-up defaults")
MB.W(49002, 1, 1)
-- Re-set device
print("Rebooting Device")
MB.W(61998, 1, 0x4C4A0004)
|
--[[
Name: ain_ef_config_set_defaults_and_powercycle.lua
Desc: This is a general AIN_EF config example that shows the basic process
for configuring any AIN_EF feature on a T-Series device, saving them
as defaults, and powercycling the device. This example configures
AIN0 and AIN2 to enable the Average/Min/Max extended feature.
For a list of all AIN_EF options, see the T-Series datasheet:
https://labjack.com/support/datasheets/t-series/ain/extended-features
Note: This should not be run multiple times. It will gradually cause flash wear
--]]
-- Assign functions locally for faster processing
local modbus_write = MB.W
-------------------------------------------------------------------------------
-- Desc: Generic function that can be used to configure general analog input
-- settings such as range, resolution, and settling. More information
-- about these settings can be found on the LabJack website under the
-- AIN section:
-- https://labjack.com/support/datasheets/t-series/ain
-------------------------------------------------------------------------------
local function ain_ef_config(
channelnum,
index,
configa,
configb,
configc,
configd,
confige,
configf,
configg,
configh,
configi,
configj
)
-- Disable AIN_EF
modbus_write(9000 + channelnum * 2, 1, 0)
-- Enable AIN_EF
modbus_write(9000 + channelnum * 2, 1, index)
modbus_write(9300 + channelnum * 2, 1, configa)
modbus_write(9600 + channelnum * 2, 1, configb)
modbus_write(9900 + channelnum * 2, 1, configc)
modbus_write(10200 + channelnum * 2, 3, configd)
modbus_write(10500 + channelnum * 2, 3, confige)
modbus_write(10800 + channelnum * 2, 3, configf)
modbus_write(11100 + channelnum * 2, 3, configg)
modbus_write(11400 + channelnum * 2, 3, configh)
modbus_write(11700 + channelnum * 2, 3, configi)
modbus_write(12000 + channelnum * 2, 3, configj)
end
print("Generic Config AIN_EF & set power-up defaults")
-- Enable AIN0 and AIN2
local ainchannels = {0, 2}
-- Index 3 is the max,min, average feature
local index = 3
local numsamples = 200
-- Set the device to scan at 6000 samples per second
local scanrate = 6000
-- Configure each analog input
for i=1,table.getn(ainchannels) do
ain_ef_config(ainchannels[i], index,numsamples,0,0,scanrate,0,0,0,0,0,0)
end
-- Set as power-up default
print("Saving settings as power-up defaults")
modbus_write(49002, 1, 1)
-- Re-set device
print("Rebooting Device")
-- Write to SYSTEM_REBOOT so the system reboots after 200ms (last 4 bytes of
-- the write value tells the device how many 50ms ticks to wait before reboot)
modbus_write(61998, 1, 0x4C4A0004)
|
Fixed up formatting of the AIN EF config and powercycle script
|
Fixed up formatting of the AIN EF config and powercycle script
|
Lua
|
mit
|
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
|
e1e8029cb15ab7cf44b8618b9cc84746b52ff99d
|
scripts/genie.lua
|
scripts/genie.lua
|
solution "retrocmd"
configurations {
"Debug",
"Release",
}
platforms {
"x32",
"x64",
}
language "C++"
startproject "retrocmd"
-- BEGIN GENie configuration
premake.make.makefile_ignore = true
--premake._checkgenerate = false
premake.check_paths = true
msgcompile ("Compiling $(subst ../,,$<)...")
msgcompile_objc ("Objective-C compiling $(subst ../,,$<)...")
msgresource ("Compiling resources $(subst ../,,$<)...")
msglinking ("Linking $(notdir $@)...")
msgarchiving ("Archiving $(notdir $@)...")
msgprecompile ("Precompiling $(subst ../,,$<)...")
messageskip { "SkipCreatingMessage", "SkipBuildingMessage", "SkipCleaningMessage" }
-- END GENie configuration
MODULE_DIR = path.getabsolute("../")
SRC_DIR = path.getabsolute("../src")
BGFX_DIR = path.getabsolute("../3rdparty/bgfx")
BX_DIR = path.getabsolute("../3rdparty/bx")
local BGFX_BUILD_DIR = path.join("../", "build")
local BGFX_THIRD_PARTY_DIR = path.join(BGFX_DIR, "3rdparty")
defines {
"BX_CONFIG_ENABLE_MSVC_LEVEL4_WARNINGS=1"
}
dofile (path.join(BX_DIR, "scripts/toolchain.lua"))
if not toolchain(BGFX_BUILD_DIR, BGFX_THIRD_PARTY_DIR) then
return -- no action specified
end
function copyLib()
end
dofile (path.join(BGFX_DIR, "scripts", "bgfx.lua"))
group "common"
dofile (path.join(BGFX_DIR, "scripts", "example-common.lua"))
group "libs"
bgfxProject("", "StaticLib", {})
group "main"
-- MAIN Project
project ("retrocmd")
uuid (os.uuid("retrocmd"))
kind "WindowedApp"
targetdir(MODULE_DIR)
targetsuffix ""
removeflags {
"NoExceptions",
}
configuration {}
includedirs {
path.join(BX_DIR, "include"),
path.join(BGFX_DIR, "include"),
path.join(BGFX_DIR, "3rdparty"),
path.join(BGFX_DIR, "examples/common"),
path.join(SRC_DIR, ""),
path.join(SRC_DIR, "formats"),
}
files {
path.join(SRC_DIR, "main.cpp"),
path.join(SRC_DIR, "formats/file.cpp"),
path.join(SRC_DIR, "formats/file.h"),
path.join(SRC_DIR, "formats/format.h"),
path.join(SRC_DIR, "formats/images/image.cpp"),
path.join(SRC_DIR, "formats/images/image.h"),
path.join(SRC_DIR, "formats/images/atarist/big.h"),
path.join(SRC_DIR, "formats/images/atarist/pic.h"),
}
if _ACTION == "gmake" then
removebuildoptions_cpp {
"-std=c++11",
}
buildoptions_cpp {
"-x c++",
"-std=c++14",
}
end
links {
"bgfx",
"example-common",
}
configuration { "mingw*" }
targetextension ".exe"
links {
"gdi32",
"psapi",
}
configuration { "vs20*", "x32 or x64" }
links {
"gdi32",
"psapi",
}
configuration { "mingw-clang" }
kind "ConsoleApp"
configuration { "linux-*" }
links {
"X11",
"GL",
"pthread",
}
configuration { "osx" }
linkoptions {
"-framework Cocoa",
"-framework QuartzCore",
"-framework OpenGL",
"-weak_framework Metal",
}
configuration {}
strip()
|
solution "retrocmd"
configurations {
"Debug",
"Release",
}
platforms {
"x32",
"x64",
}
language "C++"
startproject "retrocmd"
-- BEGIN GENie configuration
premake.make.makefile_ignore = true
--premake._checkgenerate = false
premake.check_paths = true
msgcompile ("Compiling $(subst ../,,$<)...")
msgcompile_objc ("Objective-C compiling $(subst ../,,$<)...")
msgresource ("Compiling resources $(subst ../,,$<)...")
msglinking ("Linking $(notdir $@)...")
msgarchiving ("Archiving $(notdir $@)...")
msgprecompile ("Precompiling $(subst ../,,$<)...")
messageskip { "SkipCreatingMessage", "SkipBuildingMessage", "SkipCleaningMessage" }
-- END GENie configuration
MODULE_DIR = path.getabsolute("../")
SRC_DIR = path.getabsolute("../src")
BGFX_DIR = path.getabsolute("../3rdparty/bgfx")
BX_DIR = path.getabsolute("../3rdparty/bx")
local BGFX_BUILD_DIR = path.join("../", "build")
local BGFX_THIRD_PARTY_DIR = path.join(BGFX_DIR, "3rdparty")
defines {
"BX_CONFIG_ENABLE_MSVC_LEVEL4_WARNINGS=1"
}
dofile (path.join(BX_DIR, "scripts/toolchain.lua"))
if not toolchain(BGFX_BUILD_DIR, BGFX_THIRD_PARTY_DIR) then
return -- no action specified
end
function copyLib()
end
dofile (path.join(BGFX_DIR, "scripts", "bgfx.lua"))
group "common"
dofile (path.join(BGFX_DIR, "scripts", "example-common.lua"))
group "libs"
bgfxProject("", "StaticLib", {})
dofile(path.join(BX_DIR, "scripts/bx.lua"))
group "main"
-- MAIN Project
project ("retrocmd")
uuid (os.uuid("retrocmd"))
kind "WindowedApp"
targetdir(MODULE_DIR)
targetsuffix ""
removeflags {
"NoExceptions",
}
configuration {}
includedirs {
path.join(BX_DIR, "include"),
path.join(BGFX_DIR, "include"),
path.join(BGFX_DIR, "3rdparty"),
path.join(BGFX_DIR, "examples/common"),
path.join(SRC_DIR, ""),
path.join(SRC_DIR, "formats"),
}
files {
path.join(SRC_DIR, "main.cpp"),
path.join(SRC_DIR, "formats/file.cpp"),
path.join(SRC_DIR, "formats/file.h"),
path.join(SRC_DIR, "formats/format.h"),
path.join(SRC_DIR, "formats/images/image.cpp"),
path.join(SRC_DIR, "formats/images/image.h"),
path.join(SRC_DIR, "formats/images/atarist/big.h"),
path.join(SRC_DIR, "formats/images/atarist/pic.h"),
}
if _ACTION == "gmake" then
removebuildoptions_cpp {
"-std=c++11",
}
buildoptions_cpp {
"-x c++",
"-std=c++14",
}
end
links {
"bgfx",
"example-common",
"bx",
}
configuration { "mingw*" }
targetextension ".exe"
links {
"gdi32",
"psapi",
}
configuration { "vs20*", "x32 or x64" }
links {
"gdi32",
"psapi",
}
configuration { "mingw-clang" }
kind "ConsoleApp"
configuration { "linux-*" }
links {
"X11",
"GL",
"pthread",
}
configuration { "osx" }
linkoptions {
"-framework Cocoa",
"-framework QuartzCore",
"-framework OpenGL",
"-weak_framework Metal",
}
configuration {}
strip()
|
Fix compile
|
Fix compile
|
Lua
|
bsd-3-clause
|
mamedev/retrocmd
|
436501642d9cbaf5177e711b583fa79c243e1cf5
|
modules/textadept/bookmarks.lua
|
modules/textadept/bookmarks.lua
|
-- Copyright 2007-2009 Mitchell Foral 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 Foral 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
|
jozadaquebatista/textadept,jozadaquebatista/textadept
|
ad7f647f42751a64beb193e5ceac5ea52560baff
|
AceAddon-3.0/AceAddon-3.0.lua
|
AceAddon-3.0/AceAddon-3.0.lua
|
local MAJOR, MINOR = "AceAddon-3.0", 0
local AceAddon, oldminor = LibStub:NewLibrary( MAJOR, MINOR )
if not AceAddon then
return -- No Upgrade needed.
elseif not oldminor then -- This is the first version
AceAddon.frame = CreateFrame("Frame", "AceAddon30Frame") -- Our very own frame
AceAddon.addons = {} -- addons in general
AceAddon.initializequeue = {} -- addons that are new and not initialized
AceAddon.enablequeue = {} -- addons that are initialized and waiting to be enabled
AceAddon.embeds = setmetatable({}, {__index = function(tbl, key) tbl[key] = {} return tbl[key] end }) -- contains a list of libraries embedded in an addon
end
local function safecall(func,...)
if type(func) == "function" then
local success, err = pcall(func,...)
if not err:find("%.lua:%d+:") then err = (debugstack():match("\n(.-: )in.-\n") or "") .. err end
geterrorhandler()(err)
end
end
-- AceAddon:NewAddon( name, [lib, lib, lib, ...] )
-- name (string) - unique addon object name
-- [lib] (string) - optional libs to embed in the addon object
--
-- returns the addon object when succesful
function AceAddon:NewAddon( name, ... )
assert( type( name ) == "string", "Bad argument #2 to 'NewAddon' (string expected)" )
if self.addons[name] then
error( ("AceAddon '%s' already exists."):format(name), 2 )
end
local addon = { name = name}
self.addons[name] = addon
self:EmbedLibraries( addon, ... )
-- add to queue of addons to be initialized upon ADDON_LOADED
table.insert( self.initializequeue, addon )
return addon
end
-- AceAddon:GetAddon( name, [silent])
-- name (string) - unique addon object name
-- silent (boolean) - if true, addon is optional, silently return nil if its not found
--
-- throws an error if the addon object can not be found (except silent is set)
-- returns the addon object if found
function AceAddon:GetAddon( name, silent )
if not silent and not self.addons[name] then
error(("Cannot find an AceAddon with name '%s'."):format(name), 2)
end
return self.addons[name]
end
-- AceAddon:EmbedLibraries( addon, [lib, lib, lib, ...] )
-- addon (object) - addon to embed the libs in
-- [lib] (string) - optional libs to embed
function AceAddon:EmbedLibraries( addon, ... )
for i=1,select("#", ... ) do
-- TODO: load on demand?
local libname = select( i, ... )
self:EmbedLibrary(addon, libname, false, 3)
end
end
-- AceAddon:EmbedLibrary( addon, libname, silent, offset )
-- addon (object) - addon to embed the libs in
-- libname (string) - lib to embed
-- [silent] (boolean) - optional, marks an embed to fail silently if the library doesn't exist.
-- [offset] (number) - will push the error messages back to said offset defaults to 2
function AceAddon:EmbedLibrary( addon, libname, silent, offset )
local lib = LibStub:GetLibrary(libname, true)
if not silent and not lib then
error(("Cannot find a library instance of %q."):format(tostring(libname)), offset or 2)
elseif lib and type(lib.Embed) ~= "function" then
lib:Embed(addon)
table.insert( self.embeds[addon], libname )
return true
elseif lib then
error( ("Library '%s' is not Embed capable"):format(libname), offset or 2 )
end
end
-- AceAddon:IntializeAddon( addon )
-- addon (object) - addon to intialize
--
-- calls OnInitialize on the addon object if available
-- calls OnEmbedInitialize on embedded libs in the addon object if available
function AceAddon:InitializeAddon( addon )
safecall( addon.OnInitialize, addon )
for k, libname in ipairs( self.embeds[addon] ) do
local lib = LibStub:GetLibrary(libname, true)
if lib then safecall( lib.OnEmbedInitialize, lib, addon ) end
end
end
-- AceAddon:EnableAddon( addon )
-- addon (object) - addon to enable
--
-- calls OnEnable on the addon object if available
-- calls OnEmbedEnable on embedded libs in the addon object if available
function AceAddon:EnableAddon( addon )
-- TODO: enable only if needed
-- TODO: handle 'first'? Or let addons do it on their own?
safecall( addon.OnEnable, addon )
for k, libname in ipairs( self.embeds[addon] ) do
local lib = LibStub:GetLibrary(libname, true)
if lib then safecall( lib.OnEmbedEnable, lib, addon ) end
end
end
-- AceAddon:DisableAddon( addon )
-- addon (object) - addon to disable
--
-- calls OnDisable on the addon object if available
-- calls OnEmbedDisable on embedded libs in the addon object if available
function AceAddon:DisableAddon( addon )
-- TODO: disable only if enabled
safecall( addon.OnDisable, addon )
if self.embeds[addon] then
for k, libname in ipairs( self.embeds[addon] ) do
local lib = LibStub:GetLibrary(libname, true)
if lib then safecall( lib.OnEmbedDisable, lib, addon ) end
end
end
end
-- Event Handling
local function onEvent( this, event, arg1 )
if event == "ADDON_LOADED" or event == "PLAYER_LOGIN" then
for i = 1, #AceAddon.initializequeue do
local addon = AceAddon.initializequeue[i]
AceAddon:InitializeAddon( addon )
AceAddon.initializequeue[i] = nil
table.insert( AceAddon.enablequeue, addon )
end
if IsLoggedIn() then
for i = 1, #AceAddon.enablequeue do
local addon = AceAddon.enablequeue[i]
AceAddon:EnableAddon( addon )
AceAddon.enablequeue[i] = nil
end
end
end
-- TODO: do we want to disable addons on logout?
-- Mikk: unnecessary code running imo, since disable isn't == logout (we can enable and disable in-game)
-- Ammo: AceDB wants to massage the db on logout
-- Mikk: AceDB can listen for PLAYER_LOGOUT on its own, and if it massages the db on disable, it'll ahve to un-massage it on reenables
-- K: I say let it do it on PLAYER_LOGOUT, Or if it must it already will know OnEmbedDisable
-- Nev: yeah, let AceDB figure out logout on its own, and keep it seperate from disable.
-- DISCUSSION WANTED!
end
--The next few funcs are just because no one should be reaching into the internal registries
--Thoughts?
function AceAddon:IterateAddons() return pairs(self.addons) end
function AceAddon:IterateEmbedsOnAddon(addon) return pairs(self.embeds[addon]) end
AceAddon.frame:RegisterEvent("ADDON_LOADED")
AceAddon.frame:RegisterEvent("PLAYER_LOGIN")
AceAddon.frame:SetScript( "OnEvent", onEvent )
|
local MAJOR, MINOR = "AceAddon-3.0", 0
local AceAddon, oldminor = LibStub:NewLibrary( MAJOR, MINOR )
if not AceAddon then
return -- No Upgrade needed.
elseif not oldminor then -- This is the first version
AceAddon.frame = CreateFrame("Frame", "AceAddon30Frame") -- Our very own frame
AceAddon.addons = {} -- addons in general
AceAddon.initializequeue = {} -- addons that are new and not initialized
AceAddon.enablequeue = {} -- addons that are initialized and waiting to be enabled
AceAddon.embeds = setmetatable({}, {__index = function(tbl, key) tbl[key] = {} return tbl[key] end }) -- contains a list of libraries embedded in an addon
end
local function safecall(func,...)
if type(func) == "function" then
local success, err = pcall(func,...)
if not err:find("%.lua:%d+:") then err = (debugstack():match("\n(.-: )in.-\n") or "") .. err end
geterrorhandler()(err)
end
end
-- AceAddon:NewAddon( name, [lib, lib, lib, ...] )
-- name (string) - unique addon object name
-- [lib] (string) - optional libs to embed in the addon object
--
-- returns the addon object when succesful
function AceAddon:NewAddon( name, ... )
assert(type(name) == "string", "Bad argument #2 to 'NewAddon' (string expected)")
if self.addons[name] then
error(("AceAddon '%s' already exists."):format(name), 2)
end
local addon = {name = name}
self.addons[name] = addon
self:EmbedLibraries(addon, ...)
-- add to queue of addons to be initialized upon ADDON_LOADED
table.insert(self.initializequeue, addon)
return addon
end
-- AceAddon:GetAddon( name, [silent])
-- name (string) - unique addon object name
-- silent (boolean) - if true, addon is optional, silently return nil if its not found
--
-- throws an error if the addon object can not be found (except silent is set)
-- returns the addon object if found
function AceAddon:GetAddon( name, silent )
if not silent and not self.addons[name] then
error(("Cannot find an AceAddon with name '%s'."):format(name), 2)
end
return self.addons[name]
end
-- AceAddon:EmbedLibraries( addon, [lib, lib, lib, ...] )
-- addon (object) - addon to embed the libs in
-- [lib] (string) - optional libs to embed
function AceAddon:EmbedLibraries( addon, ... )
for i=1,select("#", ... ) do
-- TODO: load on demand?
local libname = select(i, ...)
self:EmbedLibrary(addon, libname, false, 3)
end
end
-- AceAddon:EmbedLibrary( addon, libname, silent, offset )
-- addon (object) - addon to embed the libs in
-- libname (string) - lib to embed
-- [silent] (boolean) - optional, marks an embed to fail silently if the library doesn't exist.
-- [offset] (number) - will push the error messages back to said offset defaults to 2
function AceAddon:EmbedLibrary( addon, libname, silent, offset )
local lib = LibStub:GetLibrary(libname, true)
if not silent and not lib then
error(("Cannot find a library instance of %q."):format(tostring(libname)), offset or 2)
elseif lib and type(lib.Embed) == "function" then
lib:Embed(addon)
table.insert(self.embeds[addon], libname)
return true
elseif lib then
error(("Library '%s' is not Embed capable"):format(libname), offset or 2)
end
end
-- AceAddon:IntializeAddon( addon )
-- addon (object) - addon to intialize
--
-- calls OnInitialize on the addon object if available
-- calls OnEmbedInitialize on embedded libs in the addon object if available
function AceAddon:InitializeAddon( addon )
safecall(addon.OnInitialize, addon)
for k, libname in ipairs(self.embeds[addon]) do
local lib = LibStub:GetLibrary(libname, true)
if lib then safecall(lib.OnEmbedInitialize, lib, addon) end
end
end
-- AceAddon:EnableAddon( addon )
-- addon (object) - addon to enable
--
-- calls OnEnable on the addon object if available
-- calls OnEmbedEnable on embedded libs in the addon object if available
function AceAddon:EnableAddon( addon )
-- TODO: enable only if needed
-- TODO: handle 'first'? Or let addons do it on their own?
safecall(addon.OnEnable, addon)
for k, libname in ipairs(self.embeds[addon]) do
local lib = LibStub:GetLibrary(libname, true)
if lib then safecall(lib.OnEmbedEnable, lib, addon) end
end
end
-- AceAddon:DisableAddon( addon )
-- addon (object) - addon to disable
--
-- calls OnDisable on the addon object if available
-- calls OnEmbedDisable on embedded libs in the addon object if available
function AceAddon:DisableAddon( addon )
-- TODO: disable only if enabled
safecall( addon.OnDisable, addon )
if self.embeds[addon] then
for k, libname in ipairs(self.embeds[addon]) do
local lib = LibStub:GetLibrary(libname, true)
if lib then safecall(lib.OnEmbedDisable, lib, addon) end
end
end
end
-- Event Handling
local function onEvent( this, event, arg1 )
if event == "ADDON_LOADED" or event == "PLAYER_LOGIN" then
for i = 1, #AceAddon.initializequeue do
local addon = AceAddon.initializequeue[i]
AceAddon:InitializeAddon(addon)
AceAddon.initializequeue[i] = nil
table.insert(AceAddon.enablequeue, addon)
end
if IsLoggedIn() then
for i = 1, #AceAddon.enablequeue do
local addon = AceAddon.enablequeue[i]
AceAddon:EnableAddon( addon )
AceAddon.enablequeue[i] = nil
end
end
end
-- TODO: do we want to disable addons on logout?
-- Mikk: unnecessary code running imo, since disable isn't == logout (we can enable and disable in-game)
-- Ammo: AceDB wants to massage the db on logout
-- Mikk: AceDB can listen for PLAYER_LOGOUT on its own, and if it massages the db on disable, it'll ahve to un-massage it on reenables
-- K: I say let it do it on PLAYER_LOGOUT, Or if it must it already will know OnEmbedDisable
-- Nev: yeah, let AceDB figure out logout on its own, and keep it seperate from disable.
-- DISCUSSION WANTED!
end
--The next few funcs are just because no one should be reaching into the internal registries
--Thoughts?
function AceAddon:IterateAddons() return pairs(self.addons) end
function AceAddon:IterateEmbedsOnAddon(addon) return pairs(self.embeds[addon]) end
AceAddon.frame:RegisterEvent("ADDON_LOADED")
AceAddon.frame:RegisterEvent("PLAYER_LOGIN")
AceAddon.frame:SetScript( "OnEvent", onEvent )
|
Ace3 - - fixed a bug in EmbedLibraries - updated svn properties
|
Ace3 -
- fixed a bug in EmbedLibraries
- updated svn properties
git-svn-id: 00c2b8bc9b083c53e126de03a83516ee6a3b87d9@6 5debad98-a965-4143-8383-f471b3509dcf
|
Lua
|
bsd-3-clause
|
sarahgerweck/Ace3
|
9d63ed2947a3938a7da2e27aca20cda606359733
|
lib/WeightedMSECriterion.lua
|
lib/WeightedMSECriterion.lua
|
local WeightedMSECriterion, parent = torch.class('w2nn.WeightedMSECriterion','nn.Criterion')
function WeightedMSECriterion:__init(w)
parent.__init(self)
self.weight = w:clone()
self.diff = torch.Tensor()
self.loss = torch.Tensor()
end
function WeightedMSECriterion:updateOutput(input, target)
self.diff:resizeAs(input):copy(input)
for i = 1, input:size(1) do
self.diff[i]:add(-1, target[i]):cmul(self.weight)
end
self.loss:resizeAs(self.diff):copy(self.diff):cmul(self.diff)
self.output = self.loss:mean()
return self.output
end
function WeightedMSECriterion:updateGradInput(input, target)
self.gradInput:resizeAs(input):copy(self.diff)
return self.gradInput
end
|
local WeightedMSECriterion, parent = torch.class('w2nn.WeightedMSECriterion','nn.Criterion')
function WeightedMSECriterion:__init(w)
parent.__init(self)
self.weight = w:clone()
self.diff = torch.Tensor()
self.loss = torch.Tensor()
end
function WeightedMSECriterion:updateOutput(input, target)
self.diff:resizeAs(input):copy(input)
for i = 1, input:size(1) do
self.diff[i]:add(-1, target[i]):cmul(self.weight)
end
self.loss:resizeAs(self.diff):copy(self.diff):cmul(self.diff)
self.output = self.loss:mean()
return self.output
end
function WeightedMSECriterion:updateGradInput(input, target)
local norm = 2.0 / input:nElement()
self.gradInput:resizeAs(input):copy(self.diff):mul(norm)
return self.gradInput
end
|
Fix gradient scale in WeightedMSECriterion
|
Fix gradient scale in WeightedMSECriterion
|
Lua
|
mit
|
higankanshi/waifu2x,vitaliylag/waifu2x,Spitfire1900/upscaler,zyhkz/waifu2x,nagadomi/waifu2x,vitaliylag/waifu2x,Spitfire1900/upscaler,higankanshi/waifu2x,nagadomi/waifu2x,higankanshi/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,vitaliylag/waifu2x,zyhkz/waifu2x,zyhkz/waifu2x,zyhkz/waifu2x
|
fa45469924a0af2d73cebd2e4499a905e1309e88
|
popups.lua
|
popups.lua
|
local mod = EPGP:NewModule("EPGP_Popups")
local L = LibStub:GetLibrary("AceLocale-3.0"):GetLocale("EPGP")
local GPTooltip = EPGP:GetModule("EPGP_GPTooltip")
StaticPopupDialogs["EPGP_CONFIRM_GP_CREDIT"] = {
text = L["Credit GP to %s"],
button1 = L["Full"],
button3 = L["Offspec"],
button2 = CANCEL,
timeout = 0,
whileDead = 1,
maxLetters = 16,
hideOnEscape = 1,
hasEditBox = 1,
hasItemFrame = 1,
OnAccept = function()
-- Todo : hook it!
end,
OnCancel = function()
self:GetParent():Hide();
ClearCursor();
end,
OnShow = function(self)
local itemFrame = getglobal(self:GetName().."ItemFrame")
local editBox = getglobal(self:GetName().."EditBox")
local button1 = getglobal(self:GetName().."Button1")
itemFrame:SetPoint("TOPLEFT", 55, -35)
editBox:SetPoint("TOPLEFT", itemFrame, "TOPRIGHT", 150, -10)
button1:SetPoint("TOPRIGHT", itemFrame, "BOTTOMLEFT", 94, -6)
editBox:SetText(GPTooltip:GetGPValue(itemFrame.link))
editBox:HighlightText()
end,
OnHide = function()
if ChatFrameEditBox:IsShown() then
ChatFrameEditBox:SetFocus();
end
end,
EditBoxOnEnterPressed = function()
-- Todo : hook it!
end,
EditBoxOnTextChanged = function(self)
local parent = self:GetParent();
if parent.editBox:GetNumber() > 0 then
parent.button1:Enable();
parent.button3:Enable();
else
parent.button1:Disable();
parent.button3:Disable();
end
end,
EditBoxOnEscapePressed = function(self)
self:GetParent():Hide();
ClearCursor();
end
}
StaticPopupDialogs["EPGP_DECAY_EPGP"] = {
text = "",
button1 = ACCEPT,
button2 = CANCEL,
timeout = 0,
hideOnEscape = 1,
whileDead = 1,
OnShow = function()
local text = getglobal(this:GetName().."Text")
text:SetFormattedText(L["Decay EP and GP by %d%%?"],
EPGP:GetDecayPercent())
end,
OnAccept = function()
EPGP:DecayEPGP()
end
}
local function Debug(fmt, ...)
DEFAULT_CHAT_FRAME:AddMessage(string.format(fmt, ...))
end
function mod:OnInitialize()
-- local itemName, itemLink, itemRarity, _, _, _, _, _, _, itemTexture = GetItemInfo(34541)
-- local r, g, b = GetItemQualityColor(itemRarity);
-- Debug("ItemName: %s ItemLink: %s ItemRarity: %d ItemTexture: %s",
-- itemName, itemLink, itemRarity, itemTexture)
-- StaticPopup_Show("EPGP_CONFIRM_GP_CREDIT", "Lane", "", {
-- texture = itemTexture,
-- name = itemName,
-- color = {r, g, b, 1},
-- link = itemLink
-- })
-- StaticPopup_Show("EPGP_DECAY_EPGP", 7)
end
|
local mod = EPGP:NewModule("EPGP_Popups")
local L = LibStub:GetLibrary("AceLocale-3.0"):GetLocale("EPGP")
local GPTooltip = EPGP:GetModule("EPGP_GPTooltip")
StaticPopupDialogs["EPGP_CONFIRM_GP_CREDIT"] = {
text = L["Credit GP to %s"],
button1 = L["Full"],
button3 = L["Offspec"],
button2 = CANCEL,
timeout = 0,
whileDead = 1,
maxLetters = 16,
hideOnEscape = 1,
hasEditBox = 1,
hasItemFrame = 1,
OnAccept = function(self)
local parent = self:GetParent()
EPGP:IncGPBy(parent.name, parent.itemFrame.link, parent.editBox:GetNumber())
end,
OnCancel = function(self)
self:Hide();
ClearCursor();
end,
OnShow = function(self)
local itemFrame = getglobal(self:GetName().."ItemFrame")
local editBox = getglobal(self:GetName().."EditBox")
local button1 = getglobal(self:GetName().."Button1")
itemFrame:SetPoint("TOPLEFT", 55, -35)
editBox:SetPoint("TOPLEFT", itemFrame, "TOPRIGHT", 150, -10)
button1:SetPoint("TOPRIGHT", itemFrame, "BOTTOMLEFT", 94, -6)
editBox:SetText(GPTooltip:GetGPValue(itemFrame.link))
editBox:HighlightText()
end,
OnHide = function()
if ChatFrameEditBox:IsShown() then
ChatFrameEditBox:SetFocus();
end
end,
EditBoxOnEnterPressed = function(self)
local parent = self:GetParent()
if EPGP:CanIncGPBy(parent.itemFrame.link, parent.editBox:GetNumber()) then
EPGP:IncGPBy(parent.name, parent.itemFrame.link, parent.editBox:GetNumber())
end
end,
EditBoxOnTextChanged = function(self)
local parent = self:GetParent()
if EPGP:CanIncGPBy(parent.itemFrame.link, parent.editBox:GetNumber()) then
parent.button1:Enable()
parent.button3:Enable()
else
parent.button1:Disable()
parent.button3:Disable()
end
end,
EditBoxOnEscapePressed = function(self)
self:GetParent():Hide()
ClearCursor()
end
}
StaticPopupDialogs["EPGP_DECAY_EPGP"] = {
text = "",
button1 = ACCEPT,
button2 = CANCEL,
timeout = 0,
hideOnEscape = 1,
whileDead = 1,
OnShow = function()
local text = getglobal(this:GetName().."Text")
text:SetFormattedText(L["Decay EP and GP by %d%%?"],
EPGP:GetDecayPercent())
end,
OnAccept = function()
EPGP:DecayEPGP()
end
}
local function Debug(fmt, ...)
DEFAULT_CHAT_FRAME:AddMessage(string.format(fmt, ...))
end
function mod:OnInitialize()
-- local playername = "Knucklehead"
-- local itemName, itemLink, itemRarity, _, _, _, _, _, _, itemTexture = GetItemInfo(34541)
-- local r, g, b = GetItemQualityColor(itemRarity);
-- Debug("ItemName: %s ItemLink: %s ItemRarity: %d ItemTexture: %s",
-- itemName, itemLink, itemRarity, itemTexture)
-- local dialog = StaticPopup_Show("EPGP_CONFIRM_GP_CREDIT", playername, "", {
-- texture = itemTexture,
-- name = itemName,
-- color = {r, g, b, 1},
-- link = itemLink
-- })
-- if dialog then
-- dialog.name = playername
-- end
end
|
Partial fix of EPGP_CONFIRM_GP_CREDIT popup and some cosmetic changes. Popup works if Enter is pressed, but the buttons still need work.
|
Partial fix of EPGP_CONFIRM_GP_CREDIT popup and some cosmetic changes.
Popup works if Enter is pressed, but the buttons still need work.
|
Lua
|
bsd-3-clause
|
hayword/tfatf_epgp,protomech/epgp-dkp-reloaded,ceason/epgp-tfatf,sheldon/epgp,hayword/tfatf_epgp,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,sheldon/epgp
|
9b49c65a301ecc3ad0bac3f377ccca29766f6b5d
|
Lua_examples/host_and_connect.lua
|
Lua_examples/host_and_connect.lua
|
-- Run this file in both SV and CL to see working output.
require("bromsock")
-- SERVER EXAMPLE
if SERVER then
if server then server:Close() end
server = BromSock()
if (not server:Listen(6789)) then
print("[BS:S] Failed to listen!")
else
print("[BS:S] Server listening...")
end
server:SetCallbackAccept(function(serversock, clientsock)
print("[BS:S] Accepted:", serversock, clientsock)
clientsock:SetCallbackReceive(function(sock, packet)
print("[BS:S] Received:", sock, packet)
print("[BS:S] R_Num:", packet:ReadInt())
packet:WriteString("Woop woop woop a string")
sock:Send(packet)
-- normaly you'd want to call Receive again to read the next packet. However, we know that the client ain't going to send more, so fuck it.
-- theres only one way to see if a client disconnected, and that's when a error occurs while sending/receiving.
-- this is why most applications have a disconnect packet in their code, so that the client informs the server that he exited cleanly. There's no other way.
-- We set a timeout, so let's be stupid and hope there's another packet incoBSing. It'll timeout and disconnect.
sock:Receive()
end)
clientsock:SetCallbackDisconnect(function(sock)
print("[BS:S] Disconnected:", sock)
end)
clientsock:SetTimeout(1000) -- timeout send/recv coBSands in 1 second. This will generate a Disconnect event if you're using callbacks
clientsock:Receive()
-- Who's next in line?
serversock:Accept()
end)
server:Accept()
end
-- CLIENT EXAMPLE
if CLIENT then
if client then client:Close() end
client = BromSock()
client:SetCallbackConnect(function(sock, ret, ip, port)
if (not ret) then
print("[BS:C] Failed to connect to: ", ret, ip, port)
return
end
print("[BS:C] Connected to server:", sock, ret, ip, port)
local packet_client = BromPacket(client)
packet_client:WriteInt(13000)
client:Send(packet_client)
-- copy from Send callback, which is currenly non functional.
print("[BS:C] Sent:", "", sock, datasent)
-- we expect a response form the server after he received this, so instead of calling Receive at the connect callback, we do it here.
client:Receive()
end)
client:SetCallbackReceive(function(sock, packet)
print("[BS:C] Received:", sock, packet, packet and packet:InSize() or -1)
print("[BS:C] R_Str:", packet:ReadString())
-- normaly you'd call Receive here again, instead of disconnect
sock:Disconnect()
end)
-- Currently disabled, won't be called.
--[[
client:SetCallbackSend(function(sock, datasent)
print("[BS:C] Sent:", "", sock, datasent)
-- we expect a response form the server after he received this, so instead of calling Receive at the connect callback, we do it here.
client:Receive()
end)
]]--
client:Connect("127.0.0.1", 6789)
end
|
-- Run this file in both SV and CL to see working output.
require("bromsock")
-- SERVER EXAMPLE
if SERVER then
if server then server:Close() end
server = BromSock()
if (not server:Listen(6789)) then
print("[BS:S] Failed to listen!")
else
print("[BS:S] Server listening...")
end
server:SetCallbackAccept(function(serversock, clientsock)
print("[BS:S] Accepted:", serversock, clientsock)
clientsock:SetCallbackReceive(function(sock, packet)
print("[BS:S] Received:", sock, packet)
print("[BS:S] R_Num:", packet:ReadInt())
packet:WriteString("Woop woop woop a string")
sock:Send(packet)
-- normaly you'd want to call Receive again to read the next packet. However, we know that the client ain't going to send more, so fuck it.
-- theres only one way to see if a client disconnected, and that's when a error occurs while sending/receiving.
-- this is why most applications have a disconnect packet in their code, so that the client informs the server that he exited cleanly. There's no other way.
-- We set a timeout, so let's be stupid and hope there's another packet incoBSing. It'll timeout and disconnect.
sock:Receive()
end)
clientsock:SetCallbackDisconnect(function(sock)
print("[BS:S] Disconnected:", sock)
end)
clientsock:SetTimeout(1000) -- timeout send/recv coBSands in 1 second. This will generate a Disconnect event if you're using callbacks
clientsock:Receive()
-- Who's next in line?
serversock:Accept()
end)
server:Accept()
end
-- CLIENT EXAMPLE
if CLIENT then
if client then client:Close() end
client = BromSock()
client:SetCallbackConnect(function(sock, ret, ip, port)
if (not ret) then
print("[BS:C] Failed to connect to: ", ret, ip, port)
return
end
print("[BS:C] Connected to server:", sock, ret, ip, port)
local packet_client = BromPacket(client)
packet_client:WriteInt(13000)
client:Send(packet_client)
-- copy from Send callback, which is currenly non functional.
print("[BS:C] Sent:", "", sock, datasent)
-- we expect a response form the server after he received this, so instead of calling Receive at the connect callback, we do it here.
client:Receive()
end)
client:SetCallbackReceive(function(sock, packet)
print("[BS:C] Received:", sock, packet, packet and packet:InSize() or -1)
print("[BS:C] R_Str:", packet:ReadString())
-- normaly you'd call Receive here again, instead of disconnect
sock:Disconnect()
end)
client:SetCallbackSend(function(sock, datasent)
print("[BS:C] Sent:", "", sock, datasent)
-- we expect a response form the server after he received this, so instead of calling Receive at the connect callback, we do it here.
client:Receive()
end)
client:Connect("127.0.0.1", 6789)
end
|
Updated example for connect, was already fixed a while ago
|
Updated example for connect, was already fixed a while ago
|
Lua
|
mit
|
Bromvlieg/gm_bromsock,Bromvlieg/gm_bromsock
|
1ed4817fb65d2ac0d2960afbd041ef5aa74c9673
|
openwrt/package/linkmeter/luasrc/linkmeterd.lua
|
openwrt/package/linkmeter/luasrc/linkmeterd.lua
|
#! /usr/bin/env lua
local io = require("io")
local os = require("os")
local rrd = require("rrd")
local nixio = require("nixio")
nixio.fs = require("nixio.fs")
local uci = require("uci")
local SERIAL_DEVICE = "/dev/ttyS1"
local RRD_FILE = "/tmp/hm.rrd"
local JSON_FILE = "/tmp/json"
local probeNames = { "Pit", "Food Probe1", "Food Probe2", "Ambient" }
function rrdCreate()
return rrd.create(
RRD_FILE,
"--step", "2",
"DS:sp:GAUGE:30:0:1000",
"DS:t0:GAUGE:30:0:1000",
"DS:t1:GAUGE:30:0:1000",
"DS:t2:GAUGE:30:0:1000",
"DS:t3:GAUGE:30:0:1000",
"DS:f:GAUGE:30:-1000:100",
"RRA:AVERAGE:0.6:5:360",
"RRA:AVERAGE:0.6:30:360",
"RRA:AVERAGE:0.6:60:360",
"RRA:AVERAGE:0.6:90:480"
)
end
-- This might look a big hokey but rather than build the string
-- and discard it every time, just replace the values to reduce
-- the load on the garbage collector
local JSON_TEMPLATE = {
'{"time":',
0,
',"temps":[{"n":"', 'Pit', '","c":', 0, ',"a":', 0, -- probe1
'},{"n":"', 'Food Probe1', '","c":', 0, ',"a":', 0, -- probe2
'},{"n":"', 'Food Probe2', '","c":', 0, ',"a":', 0, -- probe3
'},{"n":"', 'Ambient', '","c":', 0, ',"a":', 0, -- probe4
'}],"set":', 0,
',"lid":', 0,
',"fan":{"c":', 0, ',"a":', 0, '}}'
}
local JSON_FROM_CSV = {2, 28, 6, 8, 12, 14, 18, 20, 24, 26, 32, 34, 30 }
function jsonWrite(vals)
local i,v
for i,v in ipairs(vals) do
JSON_TEMPLATE[JSON_FROM_CSV[i]] = v
end
return nixio.fs.writefile(JSON_FILE, table.concat(JSON_TEMPLATE))
end
local hm = io.open(SERIAL_DEVICE, "rwb")
if hm == nil then
die("Can not open serial device")
end
nixio.umask("0022")
-- Create database
if not nixio.fs.access(RRD_FILE) then
rrdCreate()
end
-- Create json file
if not nixio.fs.access("/www/json") then
if not nixio.fs.symlink(JSON_FILE, "/www/json") then
print("Can not create JSON file link")
end
end
local hmline
while true do
hmline = hm:read("*l")
if hmline == nil then break end
if hmline:sub(1,2) ~= "OK" then
local vals = {}
for i in hmline:gmatch("[0-9.]+") do
vals[#vals+1] = i
end
if (#vals == 12) then
-- Add the time as the first item
table.insert(vals, 1, os.time())
-- vals[9] = gcinfo()
jsonWrite(vals)
local lid = tonumber(vals[13]) or 0
-- If the lid value is non-zero, it replaces the fan value
if lid ~= 0 then
vals[11] = lid
end
table.remove(vals, 13) -- lid
table.remove(vals, 12) -- fan avg
table.remove(vals, 10) -- amb avg
table.remove(vals, 8) -- food2 avg
table.remove(vals, 6) -- food1 avg
table.remove(vals, 4) -- pit avg
rrd.update(RRD_FILE, table.concat(vals, ":"))
end
end
end
hm:close()
nixio.fs.unlink("/var/run/linkmeterd/pid")
|
#! /usr/bin/env lua
local io = require("io")
local os = require("os")
local rrd = require("rrd")
local nixio = require("nixio")
nixio.fs = require("nixio.fs")
local uci = require("uci")
local SERIAL_DEVICE = "/dev/ttyS1"
local RRD_FILE = "/tmp/hm.rrd"
local JSON_FILE = "/tmp/json"
local probeNames = { "Pit", "Food Probe1", "Food Probe2", "Ambient" }
function rrdCreate()
return rrd.create(
RRD_FILE,
"--step", "2",
"DS:sp:GAUGE:30:0:1000",
"DS:t0:GAUGE:30:0:1000",
"DS:t1:GAUGE:30:0:1000",
"DS:t2:GAUGE:30:0:1000",
"DS:t3:GAUGE:30:0:1000",
"DS:f:GAUGE:30:-1000:100",
"RRA:AVERAGE:0.6:5:360",
"RRA:AVERAGE:0.6:30:360",
"RRA:AVERAGE:0.6:60:360",
"RRA:AVERAGE:0.6:90:480"
)
end
-- This might look a big hokey but rather than build the string
-- and discard it every time, just replace the values to reduce
-- the load on the garbage collector
local JSON_TEMPLATE = {
'{"time":',
0,
',"temps":[{"n":"', 'Pit', '","c":', 0, ',"a":', 0, -- probe1
'},{"n":"', 'Food Probe1', '","c":', 0, ',"a":', 0, -- probe2
'},{"n":"', 'Food Probe2', '","c":', 0, ',"a":', 0, -- probe3
'},{"n":"', 'Ambient', '","c":', 0, ',"a":', 0, -- probe4
'}],"set":', 0,
',"lid":', 0,
',"fan":{"c":', 0, ',"a":', 0, '}}'
}
local JSON_FROM_CSV = {2, 28, 6, 8, 12, 14, 18, 20, 24, 26, 32, 34, 30 }
function jsonWrite(vals)
local i,v
for i,v in ipairs(vals) do
JSON_TEMPLATE[JSON_FROM_CSV[i]] = v
end
return nixio.fs.writefile(JSON_FILE, table.concat(JSON_TEMPLATE))
end
local hm = io.open(SERIAL_DEVICE, "rwb")
if hm == nil then
die("Can not open serial device")
end
nixio.umask("0022")
-- Create database
if not nixio.fs.access(RRD_FILE) then
rrdCreate()
end
-- Create json file
if not nixio.fs.access("/www/json") then
if not nixio.fs.symlink(JSON_FILE, "/www/json") then
print("Can not create JSON file link")
end
end
local hmline
local lastUpdate = os.time()
while true do
hmline = hm:read("*l")
if hmline == nil then break end
if hmline:sub(1,2) ~= "OK" then
local vals = {}
for i in hmline:gmatch("[0-9.]+") do
vals[#vals+1] = i
end
if #vals == 12 then
-- If the time has shifted more than 24 hours since the last update
-- the clock has probably just been set from 0 (at boot) to actual
-- time. Recreate the rrd to prevent a 40 year long graph
local time = os.time()
if time - lastUpdate > (24*60*60) then
nixio.syslog("notice", "Time jumped forward by "..(time-lastUpdate)..", restarting database")
rrdCreate()
end
lastUpadte = time
-- Add the time as the first item
table.insert(vals, 1, time)
-- vals[9] = gcinfo()
jsonWrite(vals)
local lid = tonumber(vals[13]) or 0
-- If the lid value is non-zero, it replaces the fan value
if lid ~= 0 then
vals[11] = lid
end
table.remove(vals, 13) -- lid
table.remove(vals, 12) -- fan avg
table.remove(vals, 10) -- amb avg
table.remove(vals, 8) -- food2 avg
table.remove(vals, 6) -- food1 avg
table.remove(vals, 4) -- pit avg
rrd.update(RRD_FILE, table.concat(vals, ":"))
end
end
end
hm:close()
nixio.fs.unlink("/var/run/linkmeterd/pid")
|
[lm] Recreate RRD if the clock jumps forward more than 24 hours. Fixes broken RRD files created on boot
|
[lm] Recreate RRD if the clock jumps forward more than 24 hours. Fixes broken RRD files created on boot
|
Lua
|
mit
|
kdakers80/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter,dwright134/HeaterMeter,kdakers80/HeaterMeter,CapnBry/HeaterMeter,dwright134/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,kdakers80/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,kdakers80/HeaterMeter,kdakers80/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter,dwright134/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,kdakers80/HeaterMeter,shmick/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter
|
88a2559edce1b44dfa3786478508ee076df231ba
|
xmake/tools/swiftc.lua
|
xmake/tools/swiftc.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) 2015 - 2016, ruki All rights reserved.
--
-- @author ruki
-- @file swiftc.lua
--
-- imports
import("core.project.config")
-- init it
function init(shellname)
-- save the shell name
_g.shellname = shellname or "swiftc"
-- init flags map
_g.mapflags =
{
-- symbols
["-fvisibility=hidden"] = ""
-- warnings
, ["-w"] = ""
, ["-W.*"] = ""
-- optimize
, ["-O0"] = "-Onone"
, ["-Ofast"] = "-Ounchecked"
, ["-O.*"] = "-O"
-- vectorexts
, ["-m.*"] = ""
-- strip
, ["-s"] = ""
, ["-S"] = ""
-- others
, ["-ftrapv"] = ""
, ["-fsanitize=address"] = ""
}
-- init ldflags
local swift_linkdirs = config.get("__swift_linkdirs")
if swift_linkdirs then
_g.ldflags = { "-L" .. swift_linkdirs }
end
end
-- get the property
function get(name)
-- get it
return _g[name]
end
-- make the compile command
function compcmd(srcfile, objfile, flags, logfile)
-- redirect
local redirect = ""
if logfile then redirect = format(" > %s 2>&1", logfile) end
-- make it
return format("%s -c %s -o %s %s%s", _g.shellname, flags, objfile, srcfile, redirect)
end
-- make the includedir flag
function includedir(dir)
-- make it
return "-Xcc -I" .. dir
end
-- make the define flag
function define(macro)
-- make it
return "-Xcc -D" .. macro:gsub("\"", "\\\"")
end
-- make the undefine flag
function undefine(macro)
-- make it
return "-Xcc -U" .. macro
end
-- run command
function run(...)
-- run it
os.run(...)
end
-- check the given flags
function check(flags)
-- check it
os.run("%s -h", _g.shellname)
end
|
--!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) 2015 - 2016, ruki All rights reserved.
--
-- @author ruki
-- @file swiftc.lua
--
-- imports
import("core.project.config")
-- init it
function init(shellname)
-- save the shell name
_g.shellname = shellname or "swiftc"
-- init flags map
_g.mapflags =
{
-- symbols
["-fvisibility=hidden"] = ""
-- warnings
, ["-w"] = ""
, ["-W.*"] = ""
-- optimize
, ["-O0"] = "-Onone"
, ["-Ofast"] = "-Ounchecked"
, ["-O.*"] = "-O"
-- vectorexts
, ["-m.*"] = ""
-- strip
, ["-s"] = ""
, ["-S"] = ""
-- others
, ["-ftrapv"] = ""
, ["-fsanitize=address"] = ""
}
end
-- get the property
function get(name)
-- init ldflags
if not _g.ldflags then
local swift_linkdirs = config.get("__swift_linkdirs")
if swift_linkdirs then
_g.ldflags = { "-L" .. swift_linkdirs }
end
end
-- get it
return _g[name]
end
-- make the compile command
function compcmd(srcfile, objfile, flags, logfile)
-- redirect
local redirect = ""
if logfile then redirect = format(" > %s 2>&1", logfile) end
-- make it
return format("%s -c %s -o %s %s%s", _g.shellname, flags, objfile, srcfile, redirect)
end
-- make the includedir flag
function includedir(dir)
-- make it
return "-Xcc -I" .. dir
end
-- make the define flag
function define(macro)
-- make it
return "-Xcc -D" .. macro:gsub("\"", "\\\"")
end
-- make the undefine flag
function undefine(macro)
-- make it
return "-Xcc -U" .. macro
end
-- run command
function run(...)
-- run it
os.run(...)
end
-- check the given flags
function check(flags)
-- check it
os.run("%s -h", _g.shellname)
end
|
fix swift link bug
|
fix swift link bug
|
Lua
|
apache-2.0
|
tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
62d8fba76c473261bdcd2810638dd5edf87d0167
|
src/cosy/loader/lua.lua
|
src/cosy/loader/lua.lua
|
if #setmetatable ({}, { __len = function () return 1 end }) ~= 1
then
error "Cosy requires Lua >= 5.2 to run."
end
return function (t)
t = t or {}
local loader = {}
for k, v in pairs (t) do
loader [k] = v
end
loader.home = os.getenv "HOME" .. "/.cosy/" .. (loader.alias or "default")
local modules = setmetatable ({}, { __mode = "kv" })
loader.hotswap = t.hotswap
or require "hotswap".new {}
loader.require = loader.hotswap.require
loader.load = function (name)
if modules [name] then
return modules [name]
end
local module = loader.require (name) (loader) or true
modules [name] = module
return module
end
loader.logto = t.logto
loader.scheduler = t.scheduler
if not loader.scheduler then
local ok, s = pcall (loader.require, "copas.ev")
if ok then
loader.scheduler = s
else
loader.scheduler = loader.require "copas"
loader.scheduler.autoclose = false
end
end
loader.hotswap.loaded.copas = loader.scheduler
package.loaded.copas = loader.scheduler
loader.coroutine = t.coroutine
or loader.scheduler._coroutine
or loader.require "coroutine.make" ()
_G.coroutine = loader.coroutine
loader.request = t.request
or loader.require "copas.http".request
loader.load "cosy.string"
loader.hotswap.preload ["websocket.bit" ] = function ()
return loader.require "cosy.loader.patches.bit"
end
loader.hotswap.preload ["websocket.server_copas"] = function ()
return loader.require "cosy.loader.patches.server_copas"
end
local path = package.searchpath ("cosy.loader.lua", package.path)
local parts = {}
for part in path:gmatch "[^/]+" do
parts [#parts+1] = part
end
for _ = 1, 3 do
parts [#parts] = nil
end
loader.lua_modules = (path:find "^/" and "/" or "") .. table.concat (parts, "/")
for _ = 1, 3 do
parts [#parts] = nil
end
loader.prefix = (path:find "^/" and "/" or "") .. table.concat (parts, "/")
local Lfs = loader.require "lfs"
local src = loader.prefix .. "/lib/luarocks/rocks/cosy/"
for subpath in Lfs.dir (src) do
if subpath ~= "." and subpath ~= ".."
and Lfs.attributes (src .. "/" .. subpath, "mode") == "directory" then
src = src .. subpath .. "/src"
break
end
end
loader.source = src
os.execute ([[ mkdir -p {{{home}}} ]] % {
home = loader.home,
})
return loader
end
|
if #setmetatable ({}, { __len = function () return 1 end }) ~= 1
then
error "Cosy requires Lua >= 5.2 to run."
end
return function (t)
t = t or {}
local loader = {}
for k, v in pairs (t) do
loader [k] = v
end
loader.home = os.getenv "HOME" .. "/.cosy/" .. (loader.alias or "default")
local modules = setmetatable ({}, { __mode = "kv" })
loader.hotswap = t.hotswap
or require "hotswap".new {}
loader.require = loader.hotswap.require
loader.load = function (name)
if modules [name] then
return modules [name]
end
local module = loader.require (name) (loader) or true
modules [name] = module
return module
end
loader.logto = t.logto
loader.scheduler = t.scheduler
if not loader.scheduler then
local ok, s = pcall (loader.require, "copas.ev")
if ok then
loader.scheduler = s
else
loader.scheduler = loader.require "copas"
loader.scheduler.autoclose = false
end
end
loader.hotswap.loaded.copas = loader.scheduler
package.loaded.copas = loader.scheduler
loader.coroutine = t.coroutine
or loader.scheduler._coroutine
or loader.require "coroutine.make" ()
_G.coroutine = loader.coroutine
loader.request = t.request
or loader.require "copas.http".request
loader.load "cosy.string"
loader.hotswap.preload ["websocket.bit" ] = function ()
return loader.require "cosy.loader.patches.bit"
end
loader.hotswap.preload ["websocket.server_copas"] = function ()
return loader.require "cosy.loader.patches.server_copas"
end
local path = package.searchpath ("cosy.loader.lua", package.path)
local parts = {}
for part in path:gmatch "[^/]+" do
parts [#parts+1] = part
end
for _ = 1, 3 do
parts [#parts] = nil
end
loader.lua_modules = (path:find "^/" and "/" or "") .. table.concat (parts, "/")
for _ = 1, 3 do
parts [#parts] = nil
end
loader.prefix = (path:find "^/" and "/" or "") .. table.concat (parts, "/")
if path:match "^/" then
local Lfs = loader.require "lfs"
local src = loader.prefix .. "/lib/luarocks/rocks/cosy/"
for subpath in Lfs.dir (src) do
if subpath ~= "." and subpath ~= ".."
and Lfs.attributes (src .. "/" .. subpath, "mode") == "directory" then
src = src .. subpath .. "/src"
break
end
end
loader.source = src
else
loader.source = loader.lua_modules
end
os.execute ([[ mkdir -p {{{home}}} ]] % {
home = loader.home,
})
return loader
end
|
Fix loader.source for busted tests.
|
Fix loader.source for busted tests.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
e4ae3229aa7db5487d256d6af4a68d689407f9cb
|
share/lua/website/101greatgoals.lua
|
share/lua/website/101greatgoals.lua
|
-- libquvi-scripts
-- Copyright (C) 2012 quvi project
--
-- 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
--
-- Hundred and One Great Goals
local HaOgg = {} -- Utility functions specific to this script
-- Identify the script.
function ident(self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "101greatgoals%.com"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain}, {"/gvideos/.+"})
return r
end
-- Query available formats.
function query_formats(self)
self.formats = 'default'
return HaOgg.check_external_content(self)
end
-- Parse media URL.
function parse(self)
self.host_id = "101greatgoals"
return HaOgg.check_external_content(self)
end
--
-- Utility functions
--
function HaOgg.check_external_content(self)
local p = quvi.fetch(self.page_url)
local a = p:match('<div id="space4para" class="post%-type%-gvideos">(.-)</div>')
or error("no match: article")
-- Self-hosted, and they use YouTube
-- http://www.101greatgoals.com/gvideos/golazo-wanchope-abila-sarmiento-junin-v-merlo-2/
if a:match('id="jwplayer%-1%-div"') then -- get the javascript chunk for jwplayer
local U = require 'quvi/util'
local s = p:match('"file":"(.-)"') or error('no match: file location')
a = U.unescape(s):gsub("\\/", "/")
end
-- e.g. http://www.101greatgoals.com/gvideos/ea-sports-uefa-euro-2012-launch-trailer/
-- or
-- http://www.101greatgoals.com/gvideos/golazo-wanchope-abila-sarmiento-junin-v-merlo-2/
local s = a:match('http://.*youtube.com/embed/([^/"]+)')
or a:match('http://.*youtube.com/v/([^/"]+)')
or a:match('http://.*youtube.com/watch%?v=([^/"]+)')
or a:match('http://.*youtu%.be/([^/"]+)')
if s then
self.redirect_url = 'http://youtube.com/watch?v=' .. s
return self
end
-- e.g. http://www.101greatgoals.com/gvideos/leicester-1-west-ham-2/
-- or
-- http://www.101greatgoals.com/gvideos/golazo-alvaro-negredo-overhead-kick-puts-sevilla-1-0-up-at-getafe/
local s = a:match('http://.*dailymotion.com/embed/video/([^?"]+)')
or a:match('http://.*dailymotion.com/swf/video/([^?"]+)')
if s then
self.redirect_url = 'http://dailymotion.com/video/' .. s
return self
end
-- e.g. http://www.101greatgoals.com/gvideos/2-0-juventus-arturo-vidal-2-v-roma/
local s = a:match('http://.*videa.hu/flvplayer.swf%?v=([^?"]+)')
if s then
self.redirect_url = 'http://videa.hu/flvplayer.swf?v=' .. s
return self
end
-- e.g. http://www.101greatgoals.com/gvideos/golazo-hulk-porto-v-benfica/
local s = a:match('http://.*sapo.pt/([^?"/]+)')
if s then
self.redirect_url = 'http://videos.sapo.pt/' .. s
return self
end
-- FIXME rutube support missing
-- e.g. http://www.101greatgoals.com/gvideos/allesandro-diamanti-bologna-1-0-golazo-v-cagliari-2/
local s = a:match('http://video.rutube.ru/([^?"]+)')
if s then
self.redirect_url = 'http://video.rutube.ru/' .. s
return self
end
-- FIXME svt.se support missing
-- e.g. http://www.101greatgoals.com/gvideos/gais-2-norrkoping-0/
local s = a:match('http://svt%.se/embededflash/(%d+)/play%.swf')
if s then
self.redirect_url = 'http://svt.se/embededflash/' .. s .. '/play.swf'
return self
end
-- FIXME lamalla.tv support missing
-- e.g. http://www.101greatgoals.com/gvideos/golazo-bakary-espanyol-b-vs-montanesa/
-- FIXME indavideo.hu support missing
-- e.g. http://www.101greatgoals.com/gvideos/golazo-michel-bastos-lyon-v-psg-3/
-- FIXME xtsream.dk support missing
-- e.g. http://www.101greatgoals.com/gvideos/golazo-the-ball-doesnt-hit-the-floor-viktor-claesson-elfsborg-v-fc-copenhagen-1-22-mins-in/
-- FIXME mslsoccer.com support missing
-- e.g. http://www.101greatgoals.com/gvideos/thierry-henry-back-heel-assist-mehdi-ballouchy-v-montreal-impact/
error("FIXME: no support: Unable to determine the media host")
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2012 quvi project
--
-- 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
--
-- Hundred and One Great Goals
local HaOgg = {} -- Utility functions specific to this script
-- Identify the script.
function ident(self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "101greatgoals%.com"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain}, {"/gvideos/.+"})
return r
end
-- Query available formats.
function query_formats(self)
self.formats = 'default'
return HaOgg.check_external_content(self)
end
-- Parse media URL.
function parse(self)
self.host_id = "101greatgoals"
return HaOgg.check_external_content(self)
end
--
-- Utility functions
--
function HaOgg.check_external_content(self)
local p = quvi.fetch(self.page_url)
local m = '<div .- id="space4para" class="post%-type%-gvideos">'
..'.-<script (.-)</script>'
local a = p:match(m) or error("no match: article")
-- Self-hosted, and they use YouTube
-- http://www.101greatgoals.com/gvideos/golazo-wanchope-abila-sarmiento-junin-v-merlo-2/
if a:match('id="jwplayer%-1%-div"') then -- get the javascript chunk for jwplayer
local U = require 'quvi/util'
local s = p:match('"file":"(.-)"') or error('no match: file location')
a = U.unescape(s):gsub("\\/", "/")
end
-- e.g. http://www.101greatgoals.com/gvideos/ea-sports-uefa-euro-2012-launch-trailer/
-- or
-- http://www.101greatgoals.com/gvideos/golazo-wanchope-abila-sarmiento-junin-v-merlo-2/
local s = a:match('http://.*youtube.com/embed/([^/"]+)')
or a:match('http://.*youtube.com/v/([^/"]+)')
or a:match('http://.*youtube.com/watch%?v=([^/"]+)')
or a:match('http://.*youtu%.be/([^/"]+)')
if s then
self.redirect_url = 'http://youtube.com/watch?v=' .. s
return self
end
-- e.g. http://www.101greatgoals.com/gvideos/leicester-1-west-ham-2/
-- or
-- http://www.101greatgoals.com/gvideos/golazo-alvaro-negredo-overhead-kick-puts-sevilla-1-0-up-at-getafe/
local s = a:match('http://.*dailymotion.com/embed/video/([^?"]+)')
or a:match('http://.*dailymotion.com/swf/video/([^?"]+)')
if s then
self.redirect_url = 'http://dailymotion.com/video/' .. s
return self
end
-- e.g. http://www.101greatgoals.com/gvideos/2-0-juventus-arturo-vidal-2-v-roma/
local s = a:match('http://.*videa.hu/flvplayer.swf%?v=([^?"]+)')
if s then
self.redirect_url = 'http://videa.hu/flvplayer.swf?v=' .. s
return self
end
-- e.g. http://www.101greatgoals.com/gvideos/golazo-hulk-porto-v-benfica/
local s = a:match('http://.*sapo.pt/([^?"/]+)')
if s then
self.redirect_url = 'http://videos.sapo.pt/' .. s
return self
end
-- FIXME rutube support missing
-- e.g. http://www.101greatgoals.com/gvideos/allesandro-diamanti-bologna-1-0-golazo-v-cagliari-2/
local s = a:match('http://video.rutube.ru/([^?"]+)')
if s then
self.redirect_url = 'http://video.rutube.ru/' .. s
return self
end
-- FIXME svt.se support missing
-- e.g. http://www.101greatgoals.com/gvideos/gais-2-norrkoping-0/
local s = a:match('http://svt%.se/embededflash/(%d+)/play%.swf')
if s then
self.redirect_url = 'http://svt.se/embededflash/' .. s .. '/play.swf'
return self
end
-- FIXME lamalla.tv support missing
-- e.g. http://www.101greatgoals.com/gvideos/golazo-bakary-espanyol-b-vs-montanesa/
-- FIXME indavideo.hu support missing
-- e.g. http://www.101greatgoals.com/gvideos/golazo-michel-bastos-lyon-v-psg-3/
-- FIXME xtsream.dk support missing
-- e.g. http://www.101greatgoals.com/gvideos/golazo-the-ball-doesnt-hit-the-floor-viktor-claesson-elfsborg-v-fc-copenhagen-1-22-mins-in/
-- FIXME mslsoccer.com support missing
-- e.g. http://www.101greatgoals.com/gvideos/thierry-henry-back-heel-assist-mehdi-ballouchy-v-montreal-impact/
error("FIXME: no support: Unable to determine the media host")
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
FIX: 101greatgoals.lua: article pattern
|
FIX: 101greatgoals.lua: article pattern
The pattern for the article was broken for:
http://is.gd/MuYcm3
Converted the original patch to apply.
ref: http://article.gmane.org/gmane.comp.web.flash.quvi/89
|
Lua
|
lgpl-2.1
|
DangerCove/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts,DangerCove/libquvi-scripts,alech/libquvi-scripts,legatvs/libquvi-scripts
|
a6d2e80258ed88cd2483a450963d697862935663
|
lua/AtemMixer.lua
|
lua/AtemMixer.lua
|
local cqueues = require 'cqueues'
local socket = require 'cqueues.socket'
local struct = require 'struct'
--- ATEM Stuff
local AtemMixer = {
CMD_ACK = 0x8000,
CMD_RESEND = 0x2000,
CMD_HELLO = 0x1000,
CMD_ACKREQ = 0x0800,
CMD_LENGTHMASK = 0x07ff,
}
function AtemMixer:new(ip)
o = {
ip = ip,
sock = socket.connect{host=ip, port=9910, type=socket.SOCK_DGRAM},
}
o.sock:setmode("bn", "bn")
setmetatable(o, self)
self.__index = self
return o
end
function AtemMixer:send(flags, payload, ack_id)
--print("sending to", self.ip)
self.sock:write(struct.pack(">HHHHHH", bit32.bor(6*2 + #payload, flags), self.atem_uid, ack_id or 0, 0, 0, self.packet_id) .. payload)
if bit32.band(flags, AtemMixer.CMD_ACK) == 0 then
self.packet_id = self.packet_id + 1
end
end
function AtemMixer:sendCmd(cmd, data)
data = data or ""
local pkt = struct.pack(">HHc4", 8+#data, 0, cmd)..data
self:send(AtemMixer.CMD_ACKREQ, pkt)
end
function AtemMixer:doFadeToBlack()
self:sendCmd("FtbA", struct.pack(">i1i1i2", 0, 2, 0))
end
function AtemMixer:doCut()
self:sendCmd("DCut", struct.pack(">i4", 0))
end
function AtemMixer:autoDownstreamKey(id)
self:sendCmd("DDsA", struct.pack(">i1i1i2", id, 0, 0))
end
function AtemMixer:setProgram(channel)
self:sendCmd("CPgI", struct.pack(">i2i2", 0, channel))
end
function AtemMixer:setPreview(channel)
self:sendCmd("CPvI", struct.pack(">i2i2", 0, channel))
end
function AtemMixer:onPrvI(data)
local _, ndx = struct.unpack(">HH", data)
self.control:onPreviewChange(ndx)
end
function AtemMixer:onTlIn(data)
local num = data:byte(2)
for i = 1, num do
self.control:getCamera(i):setTally(bit32.band(data:byte(i+2), 1) == 1)
end
end
function AtemMixer:recv()
local pkt, err = self.sock:read("*a")
if err then return false end
if #pkt < 6 then return true end
--print(("Got %d bytes from ATEM"):format(#pkt))
local flags, uid, ack_id, _, _, packet_id = struct.unpack(">HHHHHH", pkt)
local length = bit32.band(flags, AtemMixer.CMD_LENGTHMASK)
self.atem_uid = uid
if bit32.band(flags, bit32.bor(AtemMixer.CMD_ACKREQ, AtemMixer.CMD_HELLO)) ~= 0 then
self:send(AtemMixer.CMD_ACK, "", packet_id)
end
if bit32.band(flags, AtemMixer.CMD_HELLO) ~= 0 then return true end
-- handle payload
local off = 12
while off + 8 < #pkt do
local len, _, type = struct.unpack(">HHc4", pkt, off+1)
--print((" --> %s len %d"):format(type, len))
local handler = "on"..type
if self[handler] then self[handler](self, pkt:sub(off+1+8,off+len)) end
off = off + len
end
return true
end
function AtemMixer:send_hello()
self.sock:settimeout(5)
self.atem_uid = 0x1337
self.packet_id = 0
self:send(AtemMixer.CMD_HELLO, string.char(0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00))
end
function AtemMixer:run(cq, control)
self.control = control
cq:wrap(function()
while true do
self:send_hello()
local packet_id = 1
while self:recv() do end
cqueues.sleep(5.0)
end
end)
end
return AtemMixer
|
local cqueues = require 'cqueues'
local socket = require 'cqueues.socket'
local struct = require 'struct'
--- ATEM Stuff
local AtemMixer = {
CMD_ACK = 0x8000,
CMD_RESEND = 0x2000,
CMD_HELLO = 0x1000,
CMD_ACKREQ = 0x0800,
CMD_LENGTHMASK = 0x07ff,
}
function AtemMixer:new(ip)
o = {
ip = ip,
sock = socket.connect{host=ip, port=9910, type=socket.SOCK_DGRAM},
}
o.sock:setmode("bn", "bn")
setmetatable(o, self)
self.__index = self
return o
end
function AtemMixer:send(flags, payload, ack_id)
-- print("sending to", self.ip)
if not self.connected then return end
self.sock:write(struct.pack(">HHHHHH", bit32.bor(6*2 + #payload, flags), self.atem_uid, ack_id or 0, 0, 0, self.packet_id) .. payload)
if bit32.band(flags, AtemMixer.CMD_ACK) == 0 then
self.packet_id = self.packet_id + 1
end
end
function AtemMixer:sendCmd(cmd, data)
data = data or ""
local pkt = struct.pack(">HHc4", 8+#data, 0, cmd)..data
self:send(AtemMixer.CMD_ACKREQ, pkt)
end
function AtemMixer:doFadeToBlack()
self:sendCmd("FtbA", struct.pack(">i1i1i2", 0, 2, 0))
end
function AtemMixer:doCut()
self:sendCmd("DCut", struct.pack(">i4", 0))
end
function AtemMixer:autoDownstreamKey(id)
self:sendCmd("DDsA", struct.pack(">i1i1i2", id, 0, 0))
end
function AtemMixer:setProgram(channel)
self:sendCmd("CPgI", struct.pack(">i2i2", 0, channel))
end
function AtemMixer:setPreview(channel)
self:sendCmd("CPvI", struct.pack(">i2i2", 0, channel))
end
function AtemMixer:onPrvI(data)
local _, ndx = struct.unpack(">HH", data)
self.control:onPreviewChange(ndx)
end
function AtemMixer:onTlIn(data)
local num = data:byte(2)
for i = 1, num do
self.control:getCamera(i):setTally(bit32.band(data:byte(i+2), 1) == 1)
end
end
function AtemMixer:recv()
local pkt, err = self.sock:read("*a")
if err then
-- print(("AtemMixer: disconnected %s"):format(self.ip))
self.connected = false
return false
end
if #pkt < 6 then return true end
--print(("Got %d bytes from ATEM"):format(#pkt))
local flags, uid, ack_id, _, _, packet_id = struct.unpack(">HHHHHH", pkt)
local length = bit32.band(flags, AtemMixer.CMD_LENGTHMASK)
self.atem_uid = uid
if bit32.band(flags, bit32.bor(AtemMixer.CMD_ACKREQ, AtemMixer.CMD_HELLO)) ~= 0 then
self:send(AtemMixer.CMD_ACK, "", packet_id)
end
if bit32.band(flags, AtemMixer.CMD_HELLO) ~= 0 then
self.connected = true
-- print(("AtemMixer: connected %s"):format(self.ip))
return true
end
-- handle payload
local off = 12
while off + 8 < #pkt do
local len, _, type = struct.unpack(">HHc4", pkt, off+1)
--print((" --> %s len %d"):format(type, len))
local handler = "on"..type
if self[handler] then self[handler](self, pkt:sub(off+1+8,off+len)) end
off = off + len
end
return true
end
function AtemMixer:send_hello()
self.sock:settimeout(5)
self.sock:clearerr()
self.atem_uid = 0x1337
self.packet_id = 0
self.connected = true
self:send(AtemMixer.CMD_HELLO, string.char(0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00))
self.connected = false
end
function AtemMixer:run(cq, control)
self.control = control
cq:wrap(function()
while true do
self:send_hello()
local packet_id = 1
while self:recv() do end
cqueues.sleep(5.0)
end
end)
end
return AtemMixer
|
AtemMixer: fix reconnecting on timeout
|
AtemMixer: fix reconnecting on timeout
|
Lua
|
mit
|
rstanislav/bmd-tools,fabled/bmd-tools
|
2ac580bb0effdef820c6b2b0c8595cdb3335c2b6
|
src/plugins/finalcutpro/midi/controls/timeline.lua
|
src/plugins/finalcutpro/midi/controls/timeline.lua
|
--- === plugins.finalcutpro.midi.controls.timeline ===
---
--- Final Cut Pro MIDI Timeline Controls.
local require = require
--local log = require "hs.logger".new "timeline"
local axutils = require "cp.ui.axutils"
local deferred = require "cp.deferred"
local fcp = require "cp.apple.finalcutpro"
local i18n = require "cp.i18n"
local tools = require "cp.tools"
local childWithRole = axutils.childWithRole
local rescale = tools.rescale
-- MAX_14BIT -> number
-- Constant
-- Maximum 14bit Limit (16383)
local MAX_14BIT = 0x3FFF
-- MAX_7BIT -> number
-- Constant
-- Maximum 7bit Limit (127)
local MAX_7BIT = 0x7F
-- doNextFrame() -> none
-- Function
-- Triggers keyboard shortcuts to go to the next frame.
--
-- Parameters:
-- * None
--
-- Returns:
-- * None
local function doNextFrame()
fcp:keyStroke({"shift"}, "right")
end
-- doPreviousFrame() -> none
-- Function
-- Triggers keyboard shortcuts to go to the previous frame.
--
-- Parameters:
-- * None
--
-- Returns:
-- * None
local function doPreviousFrame()
fcp:keyStroke({"shift"}, "left")
end
-- createTimelineScrub() -> function
-- Function
-- Returns the Timeline Scrub callback.
--
-- Parameters:
-- * None
--
-- Returns:
-- * None
local function createTimelineScrub()
local lastValue
return function(metadata)
local currentValue = metadata.controllerValue
if lastValue then
if currentValue == 0 and lastValue == 0 then
doPreviousFrame()
elseif currentValue == 127 and lastValue == 127 then
doNextFrame()
elseif lastValue == 127 and currentValue == 0 then
doNextFrame()
elseif lastValue == 0 and currentValue == 127 then
doPreviousFrame()
elseif currentValue > lastValue then
doNextFrame()
elseif currentValue < lastValue then
doPreviousFrame()
end
end
lastValue = currentValue
end
end
local plugin = {
id = "finalcutpro.midi.controls.timeline",
group = "finalcutpro",
dependencies = {
["core.midi.manager"] = "manager",
}
}
function plugin.init(deps)
--------------------------------------------------------------------------------
-- Scrub Timeline:
--------------------------------------------------------------------------------
local manager = deps.manager
manager.controls:new("timelineScrub", {
group = "fcpx",
text = i18n("scrubTimeline") .. " (" .. i18n("relative") .. ")",
subText = i18n("scrubTimelineDescription"),
fn = createTimelineScrub(),
})
--------------------------------------------------------------------------------
-- Trim Toggle:
--------------------------------------------------------------------------------
manager.controls:new("trimToggle", {
group = "fcpx",
text = i18n("trimToggle"),
subText = i18n("trimToggleDescription"),
fn = function(metadata)
if metadata.controllerValue == 127 then
fcp:doShortcut("SelectToolTrim"):Now()
elseif metadata.controllerValue == 0 then
fcp:doShortcut("SelectToolArrowOrRangeSelection"):Now()
end
end,
})
--------------------------------------------------------------------------------
-- Timeline Scroll:
--------------------------------------------------------------------------------
local updateTimelineScrollValue
local updateTimelineScroll = deferred.new(0.01):action(function()
fcp.timeline.contents.horizontalScrollBar:value(tonumber(updateTimelineScrollValue))
end)
manager.controls:new("horizontalTimelineScroll", {
group = "fcpx",
text = i18n("horizontalTimelineScroll"),
subText = i18n("horizontalTimelineScrollDescription"),
fn = function(metadata)
if metadata.fourteenBitCommand or metadata.pitchChange then
--------------------------------------------------------------------------------
-- 14bit:
--------------------------------------------------------------------------------
local midiValue = metadata.pitchChange or metadata.fourteenBitValue
if type(midiValue) == "number" then
updateTimelineScrollValue = rescale(midiValue, 0, MAX_14BIT, 0, 1)
end
else
--------------------------------------------------------------------------------
-- 7bit:
--------------------------------------------------------------------------------
local midiValue = metadata.controllerValue
if type(midiValue) == "number" then
updateTimelineScrollValue = rescale(midiValue, 0, MAX_7BIT, 0, 1)
end
end
updateTimelineScroll()
end,
})
end
return plugin
|
--- === plugins.finalcutpro.midi.controls.timeline ===
---
--- Final Cut Pro MIDI Timeline Controls.
local require = require
--local log = require "hs.logger".new "timeline"
local axutils = require "cp.ui.axutils"
local deferred = require "cp.deferred"
local fcp = require "cp.apple.finalcutpro"
local i18n = require "cp.i18n"
local tools = require "cp.tools"
local childWithRole = axutils.childWithRole
local rescale = tools.rescale
-- MAX_14BIT -> number
-- Constant
-- Maximum 14bit Limit (16383)
local MAX_14BIT = 0x3FFF
-- MAX_7BIT -> number
-- Constant
-- Maximum 7bit Limit (127)
local MAX_7BIT = 0x7F
-- doNextFrame() -> none
-- Function
-- Triggers keyboard shortcuts to go to the next frame.
--
-- Parameters:
-- * None
--
-- Returns:
-- * None
local function doNextFrame()
fcp:keyStroke({"shift"}, "right")
end
-- doPreviousFrame() -> none
-- Function
-- Triggers keyboard shortcuts to go to the previous frame.
--
-- Parameters:
-- * None
--
-- Returns:
-- * None
local function doPreviousFrame()
fcp:keyStroke({"shift"}, "left")
end
-- createTimelineScrub() -> function
-- Function
-- Returns the Timeline Scrub callback.
--
-- Parameters:
-- * None
--
-- Returns:
-- * None
local function createTimelineScrub()
local lastValue
return function(metadata)
local currentValue = metadata.controllerValue
if lastValue then
if currentValue == 0 and lastValue == 0 then
doPreviousFrame()
elseif currentValue == 127 and lastValue == 127 then
doNextFrame()
elseif lastValue == 127 and currentValue == 0 then
doNextFrame()
elseif lastValue == 0 and currentValue == 127 then
doPreviousFrame()
elseif currentValue > lastValue then
doNextFrame()
elseif currentValue < lastValue then
doPreviousFrame()
end
end
lastValue = currentValue
end
end
local plugin = {
id = "finalcutpro.midi.controls.timeline",
group = "finalcutpro",
dependencies = {
["core.midi.manager"] = "manager",
}
}
function plugin.init(deps)
--------------------------------------------------------------------------------
-- Scrub Timeline:
--------------------------------------------------------------------------------
local manager = deps.manager
manager.controls:new("timelineScrub", {
group = "fcpx",
text = i18n("scrubTimeline") .. " (" .. i18n("relative") .. ")",
subText = i18n("scrubTimelineDescription"),
fn = createTimelineScrub(),
})
--------------------------------------------------------------------------------
-- Trim Toggle:
--------------------------------------------------------------------------------
manager.controls:new("trimToggle", {
group = "fcpx",
text = i18n("trimToggle"),
subText = i18n("trimToggleDescription"),
fn = function(metadata)
if metadata.controllerValue == 127 then
fcp:doShortcut("SelectToolTrim"):Now()
elseif metadata.controllerValue == 0 then
fcp:doShortcut("SelectToolArrowOrRangeSelection"):Now()
end
end,
})
--------------------------------------------------------------------------------
-- Timeline Scroll:
--------------------------------------------------------------------------------
local contents = fcp.timeline.contents
local updateTimelineScrollValue
local updateTimelineScroll = deferred.new(0.01):action(function()
contents:shiftHorizontalTo(updateTimelineScrollValue)
end)
manager.controls:new("horizontalTimelineScroll", {
group = "fcpx",
text = i18n("horizontalTimelineScroll"),
subText = i18n("horizontalTimelineScrollDescription"),
fn = function(metadata)
if metadata.fourteenBitCommand or metadata.pitchChange then
--------------------------------------------------------------------------------
-- 14bit:
--------------------------------------------------------------------------------
local midiValue = metadata.pitchChange or metadata.fourteenBitValue
if type(midiValue) == "number" then
updateTimelineScrollValue = rescale(midiValue, 0, MAX_14BIT, 0, 1)
end
else
--------------------------------------------------------------------------------
-- 7bit:
--------------------------------------------------------------------------------
local midiValue = metadata.controllerValue
if type(midiValue) == "number" then
updateTimelineScrollValue = rescale(midiValue, 0, MAX_7BIT, 0, 1)
end
end
updateTimelineScroll()
end,
})
end
return plugin
|
Fixed bug in MIDI Timeline Scroll
|
Fixed bug in MIDI Timeline Scroll
- Closes #2473
|
Lua
|
mit
|
fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks
|
f9e61d217f29664b595fc60a7c05587687dd1cda
|
src/pf/codegen.lua
|
src/pf/codegen.lua
|
module(...,package.seeall)
verbose = os.getenv("PF_VERBOSE");
local function dup(db)
local ret = {}
for k, v in pairs(db) do ret[k] = v end
return ret
end
local function filter_builder(...)
local written = 'return function('
local vcount = 0
local lcount = 0
local indent = ' '
local jumps = {}
local builder = {}
local db_stack = {}
local db = {}
function builder.write(str)
written = written .. str
end
function builder.writeln(str)
builder.write(indent .. str .. '\n')
end
function builder.v(str)
if db[str] then return db[str] end
vcount = vcount + 1
local var = 'v'..vcount
db[str] = var
builder.writeln('local '..var..' = '..str)
return var
end
function builder.push()
table.insert(db_stack, db)
builder.writeln('do')
indent = indent .. ' '
db = dup(db)
end
function builder.pop()
indent = indent:sub(4)
builder.writeln('end')
db = table.remove(db_stack)
end
function builder.label()
lcount = lcount + 1
return 'L'..lcount
end
function builder.jump(label)
if label == 'ACCEPT' then return 'return true' end
if label == 'REJECT' then return 'return false' end
jumps[label] = true
return 'goto '..label
end
function builder.test(cond, kt, kf, k)
if kt == 'ACCEPT' and kf == 'REJECT' then
builder.writeln('do return '..cond..' end')
elseif kf == 'ACCEPT' and kt == 'REJECT' then
builder.writeln('do return not '..cond..' end')
elseif kt == k then
builder.writeln('if not ('..cond..') then '..builder.jump(kf)..' end')
else
builder.writeln('if '..cond..' then '..builder.jump(kt)..' end')
if kf ~= k then builder.writeln('do '..builder.jump(kf)..' end') end
end
end
function builder.writelabel(label)
if jumps[label] then builder.write('::'..label..'::\n') end
end
function builder.finish(str)
builder.write('end')
if verbose then print(written) end
return written
end
local needs_comma = false
for _, v in ipairs({...}) do
if needs_comma then builder.write(',') end
builder.write(v)
needs_comma = true
end
builder.write(')\n')
return builder
end
local function read_buffer_word_by_type(buffer, offset, size)
if size == 1 then
return buffer..'['..offset..']'
elseif size == 2 then
return ('ffi.cast("uint16_t*", '..buffer..'+'..offset..')[0]')
elseif size == 4 then
return ('ffi.cast("int32_t*", '..buffer..'+'..offset..')[0]')
else
error("bad [] size: "..size)
end
end
local function compile_value(builder, expr)
if expr == 'len' then return 'length' end
if type(expr) == 'number' then return expr end
assert(type(expr) == 'table', 'unexpected type '..type(expr))
local op = expr[1]
local lhs = compile_value(builder, expr[2])
if op == 'ntohs' then
return builder.v('bit.rshift(bit.bswap('..lhs..'), 16)')
elseif op == 'ntohl' then
return builder.v('bit.bswap('..lhs..')')
end
local rhs = compile_value(builder, expr[3])
if op == '[]' then
return builder.v(read_buffer_word_by_type('P', lhs, rhs))
elseif op == '+' then return builder.v(lhs..'+'..rhs)
elseif op == '-' then return builder.v(lhs..'-'..rhs)
elseif op == '*' then return builder.v(lhs..'*'..rhs)
elseif op == '/' then return builder.v('math.floor('..lhs..'/'..rhs..')')
elseif op == '%' then return builder.v(lhs..'%'..rhs)
elseif op == '&' then return builder.v('bit.band('..lhs..','..rhs..')')
elseif op == '^' then return builder.v('bit.bxor('..lhs..','..rhs..')')
elseif op == '|' then return builder.v('bit.bor('..lhs..','..rhs..')')
elseif op == '<<' then return builder.v('bit.lshift('..lhs..','..rhs..')')
elseif op == '>>' then return builder.v('bit.rshift('..lhs..','..rhs..')')
else error('unexpected op', op) end
end
local relop_map = {
['<']='<', ['<=']='<=', ['=']='==', ['!=']='~=', ['>=']='>=', ['>']='>'
}
local function compile_bool(builder, expr, kt, kf, k)
assert(type(expr) == 'table', 'logical expression must be a table')
local op = expr[1]
if op == 'not' then
return compile_bool(builder, expr[2], kf, kt, k)
elseif op == 'if' then
local function eta_reduce(expr)
if expr[1] == 'false' then return kf, false
elseif expr[1] == 'true' then return kt, false
elseif expr[1] == 'fail' then return 'REJECT', false
else return builder.label(), true end
end
local test_kt, fresh_kt = eta_reduce(expr[3])
local test_kf, fresh_kf = eta_reduce(expr[4])
if fresh_kt then
compile_bool(builder, expr[2], test_kt, test_kf, test_kt)
builder.writelabel(test_kt)
if fresh_kf then
builder.push()
compile_bool(builder, expr[3], kt, kf, test_kf)
builder.pop()
builder.writelabel(test_kf)
builder.push()
compile_bool(builder, expr[4], kt, kf, k)
builder.pop()
else
compile_bool(builder, expr[3], kt, kf, k)
end
elseif fresh_kf then
compile_bool(builder, expr[2], test_kt, test_kf, test_kf)
builder.writelabel(test_kf)
builder.push()
compile_bool(builder, expr[4], kt, kf, k)
builder.pop()
else
compile_bool(builder, expr[2], test_kt, test_kf, k)
end
elseif op == 'true' then
if kt ~= k then builder.writeln(builder.jump(kt)) end
elseif op == 'false' then
if kf ~= k then builder.writeln(builder.jump(kf)) end
elseif op == 'fail' then
builder.writeln('do return false end')
elseif relop_map[op] then
-- An arithmetic relop.
local op = relop_map[op]
local lhs = compile_value(builder, expr[2])
local rhs = compile_value(builder, expr[3])
local comp = lhs..' '..op..' '..rhs
builder.test(comp, kt, kf, k)
else
error('unhandled primitive'..op)
end
end
function compile_lua(parsed)
dlt = dlt or 'RAW'
local builder = filter_builder('P', 'length')
compile_bool(builder, parsed, 'ACCEPT', 'REJECT')
return builder.finish()
end
function compile(parsed, name)
if not getfenv(0).ffi then getfenv(0).ffi = require('ffi') end
return assert(loadstring(compile_lua(parsed), name))()
end
function selftest ()
print("selftest: pf.codegen")
local parse = require('pf.parse').parse
local expand = require('pf.expand').expand
local optimize = require('pf.optimize').optimize
compile(optimize(expand(parse("ip"), 'EN10MB')))
compile(optimize(expand(parse("tcp"), 'EN10MB')))
compile(optimize(expand(parse("port 80"), 'EN10MB')))
compile(optimize(expand(parse("tcp port 80"), 'EN10MB')))
print("OK")
end
|
module(...,package.seeall)
verbose = os.getenv("PF_VERBOSE");
local function dup(db)
local ret = {}
for k, v in pairs(db) do ret[k] = v end
return ret
end
local function filter_builder(...)
local written = 'return function('
local vcount = 0
local lcount = 0
local indent = ' '
local jumps = {}
local builder = {}
local db_stack = {}
local db = {}
function builder.write(str)
written = written .. str
end
function builder.writeln(str)
builder.write(indent .. str .. '\n')
end
function builder.v(str)
if db[str] then return db[str] end
vcount = vcount + 1
local var = 'v'..vcount
db[str] = var
builder.writeln('local '..var..' = '..str)
return var
end
function builder.push()
table.insert(db_stack, db)
builder.writeln('do')
indent = indent .. ' '
db = dup(db)
end
function builder.pop()
indent = indent:sub(4)
builder.writeln('end')
db = table.remove(db_stack)
end
function builder.label()
lcount = lcount + 1
return 'L'..lcount
end
function builder.jump(label)
if label == 'ACCEPT' then return 'return true' end
if label == 'REJECT' then return 'return false' end
jumps[label] = true
return 'goto '..label
end
function builder.test(cond, kt, kf, k)
if kt == 'ACCEPT' and kf == 'REJECT' then
builder.writeln('do return '..cond..' end')
elseif kf == 'ACCEPT' and kt == 'REJECT' then
builder.writeln('do return not '..cond..' end')
elseif kt == k then
builder.writeln('if not ('..cond..') then '..builder.jump(kf)..' end')
else
builder.writeln('if '..cond..' then '..builder.jump(kt)..' end')
if kf ~= k then builder.writeln('do '..builder.jump(kf)..' end') end
end
end
function builder.writelabel(label)
if jumps[label] then builder.write('::'..label..'::\n') end
end
function builder.finish(str)
builder.write('end')
if verbose then print(written) end
return written
end
local needs_comma = false
for _, v in ipairs({...}) do
if needs_comma then builder.write(',') end
builder.write(v)
needs_comma = true
end
builder.write(')\n')
return builder
end
local function read_buffer_word_by_type(buffer, offset, size)
if size == 1 then
return buffer..'['..offset..']'
elseif size == 2 then
return ('ffi.cast("uint16_t*", '..buffer..'+'..offset..')[0]')
elseif size == 4 then
return ('ffi.cast("int32_t*", '..buffer..'+'..offset..')[0]')
else
error("bad [] size: "..size)
end
end
local function compile_value(builder, expr)
if expr == 'len' then return 'length' end
if type(expr) == 'number' then return expr end
assert(type(expr) == 'table', 'unexpected type '..type(expr))
local op = expr[1]
local lhs = compile_value(builder, expr[2])
if op == 'ntohs' then
return builder.v('bit.rshift(bit.bswap('..lhs..'), 16)')
elseif op == 'ntohl' then
return builder.v('bit.bswap('..lhs..')')
end
local rhs = compile_value(builder, expr[3])
if op == '[]' then
return builder.v(read_buffer_word_by_type('P', lhs, rhs))
elseif op == '+' then return builder.v(lhs..'+'..rhs)
elseif op == '-' then return builder.v(lhs..'-'..rhs)
elseif op == '*' then return builder.v(lhs..'*'..rhs)
elseif op == '/' then return builder.v('math.floor('..lhs..'/'..rhs..')')
elseif op == '%' then return builder.v(lhs..'%'..rhs)
elseif op == '&' then return builder.v('bit.band('..lhs..','..rhs..')')
elseif op == '^' then return builder.v('bit.bxor('..lhs..','..rhs..')')
elseif op == '|' then return builder.v('bit.bor('..lhs..','..rhs..')')
elseif op == '<<' then return builder.v('bit.lshift('..lhs..','..rhs..')')
elseif op == '>>' then return builder.v('bit.rshift('..lhs..','..rhs..')')
else error('unexpected op', op) end
end
local relop_map = {
['<']='<', ['<=']='<=', ['=']='==', ['!=']='~=', ['>=']='>=', ['>']='>'
}
local function compile_bool(builder, expr, kt, kf, k)
assert(type(expr) == 'table', 'logical expression must be a table')
local op = expr[1]
if op == 'not' then
return compile_bool(builder, expr[2], kf, kt, k)
elseif op == 'if' then
local function eta_reduce(expr)
if expr[1] == 'false' then return kf, false
elseif expr[1] == 'true' then return kt, false
elseif expr[1] == 'fail' then return 'REJECT', false
else return builder.label(), true end
end
local test_kt, fresh_kt = eta_reduce(expr[3])
local test_kf, fresh_kf = eta_reduce(expr[4])
if fresh_kt then
compile_bool(builder, expr[2], test_kt, test_kf, test_kt)
builder.writelabel(test_kt)
if fresh_kf then
builder.push()
compile_bool(builder, expr[3], kt, kf, test_kf)
builder.pop()
builder.writelabel(test_kf)
builder.push()
compile_bool(builder, expr[4], kt, kf, k)
builder.pop()
else
builder.push()
compile_bool(builder, expr[3], kt, kf, k)
builder.pop()
end
elseif fresh_kf then
compile_bool(builder, expr[2], test_kt, test_kf, test_kf)
builder.writelabel(test_kf)
builder.push()
compile_bool(builder, expr[4], kt, kf, k)
builder.pop()
else
compile_bool(builder, expr[2], test_kt, test_kf, k)
end
elseif op == 'true' then
if kt ~= k then builder.writeln(builder.jump(kt)) end
elseif op == 'false' then
if kf ~= k then builder.writeln(builder.jump(kf)) end
elseif op == 'fail' then
builder.writeln('do return false end')
elseif relop_map[op] then
-- An arithmetic relop.
local op = relop_map[op]
local lhs = compile_value(builder, expr[2])
local rhs = compile_value(builder, expr[3])
local comp = lhs..' '..op..' '..rhs
builder.test(comp, kt, kf, k)
else
error('unhandled primitive'..op)
end
end
function compile_lua(parsed)
dlt = dlt or 'RAW'
local builder = filter_builder('P', 'length')
compile_bool(builder, parsed, 'ACCEPT', 'REJECT')
return builder.finish()
end
function compile(parsed, name)
if not getfenv(0).ffi then getfenv(0).ffi = require('ffi') end
return assert(loadstring(compile_lua(parsed), name))()
end
function selftest ()
print("selftest: pf.codegen")
local parse = require('pf.parse').parse
local expand = require('pf.expand').expand
local optimize = require('pf.optimize').optimize
compile(optimize(expand(parse("ip"), 'EN10MB')))
compile(optimize(expand(parse("tcp"), 'EN10MB')))
compile(optimize(expand(parse("port 80"), 'EN10MB')))
compile(optimize(expand(parse("tcp port 80"), 'EN10MB')))
print("OK")
end
|
Fix codegen scoping bug
|
Fix codegen scoping bug
* src/pf/codegen.lua (compile_bool): Wrap true continuation in a do /
end in all cases, to preserve scoping.
|
Lua
|
apache-2.0
|
mpeterv/pflua,SnabbCo/pflua
|
fde6e1971c89db8b10e9ad1233442bef9d54a765
|
packages/bidi.lua
|
packages/bidi.lua
|
SILE.registerCommand("thisframeLTR", function(options, content)
SILE.typesetter.frame.direction = "LTR"
SILE.typesetter:leaveHmode()
end);
SILE.registerCommand("thisframeRTL", function(options, content)
SILE.typesetter.frame.direction = "RTL"
SILE.typesetter:leaveHmode()
end);
local bidi = require("unicode-bidi-algorithm")
local bidiBoxupNodes = function (self)
local nl = self.state.nodes
local newNl = {}
for i=1,#nl do
if nl[i]:isUnshaped() then
local chunks = SU.splitUtf8(nl[i].text)
for j = 1,#chunks do
newNl[#newNl+1] = SILE.nodefactory.newUnshaped({text = chunks[j], options = nl[i].options })
end
else
newNl[#newNl+1] = nl[i]
end
end
nl = bidi.process(newNl, self.frame)
-- Reconstitute. This code is a bit dodgy. Currently we have a bunch of nodes
-- each with one Unicode character in them. Sending that to the shaper one-at-a-time
-- will cause, e.g. Arabic letters to all come out as isolated forms. But equally,
-- we can't send the whole lot to the shaper at once because Harfbuzz doesn't itemize
-- them for us, spaces have already been converted to glue, and so on. So we combine
-- characters with equivalent options/character sets into a single node.
newNL = {nl[1]}
local ncount = 1 -- small optimization, save indexing newNL every time
for i=2,#nl do
local this = nl[i]
local prev = newNL[ncount]
if not this:isUnshaped() or not prev:isUnshaped() then
ncount = ncount + 1
newNL[ncount] = this
-- now both are unshaped, compare them
elseif SILE.font._key(this.options) == SILE.font._key(prev.options) then -- same font
prev.text = prev.text .. this.text
else
ncount = ncount + 1
newNL[ncount] = this
end
end
self.state.nodes = newNL
return SILE.defaultTypesetter.boxUpNodes(self)
end
SILE.typesetter.boxUpNodes = bidiBoxupNodes
SILE.registerCommand("bidi-on", function(options, content)
SILE.typesetter.boxUpNodes = bidiBoxupNodes
end)
SILE.registerCommand("bidi-off", function(options, content)
SILE.typesetter.boxUpNodes = SILE.defaultTypesetter.boxUpNodes
end)
return { documentation = [[\begin{document}
Scripts like the Latin alphabet you are currently reading are normally written left to
right; however, some scripts, such as Arabic and Hebrew, are written right to left.
The \code{bidi} package provides some tools to help you correctly typeset right-to-left
text and also documents which mix right-to-left and left-to-right typesetting.
Loading the \code{bidi} package provides two commands, \command{\\thisframeLTR} and
\command{\\thisframeRTL}, which set the default text direction for the current frame.
That is, if you tell SILE that a frame is RTL, the text will start in the right margin
and proceed leftward. Additionally, loading \code{bidi} will cause SILE to check for and
correctly order left-to-right text within right-to-left paragraphs, RTL within LTR
within LTR and so on. If you are working with Hebrew, Arabic or other RTL languages,
you will want to load the \code{bidi} package.
\end{document}]] }
|
SILE.registerCommand("thisframeLTR", function(options, content)
SILE.typesetter.frame.direction = "LTR"
SILE.typesetter:leaveHmode()
end);
SILE.registerCommand("thisframeRTL", function(options, content)
SILE.typesetter.frame.direction = "RTL"
SILE.typesetter:leaveHmode()
end);
local bidi = require("unicode-bidi-algorithm")
local bidiBoxupNodes = function (self)
local nl = self.state.nodes
local newNl = {}
for i=1,#nl do
if nl[i]:isUnshaped() then
local chunks = SU.splitUtf8(nl[i].text)
for j = 1,#chunks do
newNl[#newNl+1] = SILE.nodefactory.newUnshaped({text = chunks[j], options = nl[i].options })
end
else
newNl[#newNl+1] = nl[i]
end
end
nl = bidi.process(newNl, self.frame)
-- Reconstitute. This code is a bit dodgy. Currently we have a bunch of nodes
-- each with one Unicode character in them. Sending that to the shaper one-at-a-time
-- will cause, e.g. Arabic letters to all come out as isolated forms. But equally,
-- we can't send the whole lot to the shaper at once because Harfbuzz doesn't itemize
-- them for us, spaces have already been converted to glue, and so on. So we combine
-- characters with equivalent options/character sets into a single node.
newNL = {nl[1]}
local ncount = 1 -- small optimization, save indexing newNL every time
for i=2,#nl do
local this = nl[i]
local prev = newNL[ncount]
if not this:isUnshaped() or not prev:isUnshaped() then
ncount = ncount + 1
newNL[ncount] = this
-- now both are unshaped, compare them
elseif SILE.font._key(this.options) == SILE.font._key(prev.options) then -- same font
prev.text = prev.text .. this.text
else
ncount = ncount + 1
newNL[ncount] = this
end
end
self.state.nodes = newNL
return SILE.defaultTypesetter.boxUpNodes(self)
end
SILE.typesetter.boxUpNodes = bidiBoxupNodes
SILE.registerCommand("bidi-on", function(options, content)
SILE.typesetter.boxUpNodes = bidiBoxupNodes
end)
SILE.registerCommand("bidi-off", function(options, content)
SILE.typesetter.boxUpNodes = SILE.defaultTypesetter.boxUpNodes
end)
return { documentation = [[\begin{document}
Scripts like the Latin alphabet you are currently reading are normally written left to
right; however, some scripts, such as Arabic and Hebrew, are written right to left.
The \code{bidi} package, which is loaded by default, provides SILE with the ability to
correctly typeset right-to-left text and also documents which mix right-to-left and
left-to-right typesetting. Because it is loaded by default, you can use both
LTR and RTL text within a paragraph and SILE will ensure that the output
characters appear in the correct order.
The \code{bidi} package provides two commands, \command{\\thisframeLTR} and
\command{\\thisframeRTL}, which set the default text direction for the current frame.
That is, if you tell SILE that a frame is RTL, the text will start in the right margin
and proceed leftward.
\end{document}]] }
|
Fix docs now this is default.
|
Fix docs now this is default.
|
Lua
|
mit
|
shirat74/sile,simoncozens/sile,alerque/sile,alerque/sile,WAKAMAZU/sile_fe,shirat74/sile,alerque/sile,simoncozens/sile,alerque/sile,anthrotype/sile,anthrotype/sile,neofob/sile,neofob/sile,neofob/sile,shirat74/sile,WAKAMAZU/sile_fe,WAKAMAZU/sile_fe,simoncozens/sile,WAKAMAZU/sile_fe,anthrotype/sile,neofob/sile,simoncozens/sile,anthrotype/sile,shirat74/sile
|
a2484afd3a451eea46ffd386e1a8894e5f07871a
|
pud/ui/Text.lua
|
pud/ui/Text.lua
|
local Class = require 'lib.hump.class'
local Frame = getClass 'pud.ui.Frame'
local pushRenderTarget, popRenderTarget = pushRenderTarget, popRenderTarget
local setColor = love.graphics.setColor
local setFont = love.graphics.setFont
local gprint = love.graphics.print
local math_floor = math.floor
local string_sub = string.sub
local string_gsub = string.gsub
local format = string.format
-- Text
-- A static text frame
local Text = Class{name='Text',
inherits=Frame,
function(self, ...)
Frame.construct(self, ...)
self._maxLines = 1
self._text = {}
self._justify = 'l'
self._margin = 0
end
}
-- destructor
function Text:destroy()
self:clear()
self._text = nil
self._justify = nil
self._margin = nil
Frame.destroy(self)
end
-- set the text that will be displayed
-- text can be a string or a table of strings, representing lines
-- (newline is not supported)
function Text:setText(text)
if type(text) == 'string' then text = {text} end
verify('table', text)
self:clear()
local numLines = #text
if numLines > self._maxLines then
warning('setText(lines): number of lines (%d) exceeds maximum (%d)',
numLines, self._maxLines)
for i=1,self._maxLines do
self._text[i] = text[i]
end
else
self._text = text
end
self:_drawFB()
end
-- assuming width is constant, wrap lines if they're larger than the width
-- of this frame.
function Text:_wrap(font)
local w = font:getWidth('0')
local margin = self._margin or 0
local frameWidth = self:getWidth() - (2 * margin)
local max = math_floor(frameWidth/w)
local num = #self._text
local wrapped
local wrapcount = 0
for i=1,num do
wrapcount = wrapcount + 1
wrapped = wrapped or {}
if font:getWidth(self._text[i]) > frameWidth then
local here = 0
string_gsub(self._text[i], '(%s*)()(%S+)()', function(sp, st, word, fi)
if fi-here > max then
here = st
wrapcount = wrapcount + 1
wrapped[wrapcount] = word
else
if wrapped[wrapcount] then
wrapped[wrapcount] = format('%s %s', wrapped[wrapcount], word)
else
wrapped[wrapcount] = word
end
end
end)
else
wrapped[wrapcount] = self._text[i]
end
end
return wrapped and wrapped or self._text
end
-- returns the currently set text as a table of strings, one per line
function Text:getText() return self._text end
-- clear the current text
function Text:clear()
for k in pairs(self._text) do self._text[k] = nil end
end
-- set the maximum number of lines
function Text:setMaxLines(max)
verify('number', max)
self._maxLines = max
end
-- set the margin between the frame edge and the text
function Text:setMargin(margin)
verify('number', margin)
self._margin = margin
self:_drawFB()
end
-- set the justification
function Text:setJustifyLeft() self._justify = 'l' end
function Text:setJustifyRight() self._justify = 'r' end
function Text:setJustifyCenter() self._justify = 'c' end
-- override Frame:_drawFB()
function Text:_drawFB()
self._bfb = self._bfb or self:_getFramebuffer()
pushRenderTarget(self._bfb)
self:_drawBackground()
if self._text and #self._text > 0 then
if self._curStyle then
local font = self._curStyle:getFont()
if font then
local height = font:getHeight()
local margin = self._margin or 0
local text = self:_wrap(font)
local textLines = #text
local maxLines = math_floor((self:getHeight() - (2*margin)) / height)
local numLines = textLines > maxLines and maxLines or textLines
local fontcolor = self._curStyle:getFontColor()
setFont(font)
setColor(fontcolor)
for i=1,numLines do
local line = text[i]
local h = (i-1) * height
local w = font:getWidth(line)
local y = margin + h
local x
if 'l' == self._justify then
x = margin
elseif 'c' == self._justify then
local cx = self:getWidth() / 2
x = math_floor(cx - (w/2))
elseif 'r' == self._justify then
x = self:getWidth() - (margin + w)
else
x, y = 0, 0
warning('Unjustified (justify is set to %q)',
tostring(self._justify))
end
gprint(line, x, y)
end
end
end
end
popRenderTarget()
self._ffb, self._bfb = self._bfb, self._ffb
end
-- the class
return Text
|
local Class = require 'lib.hump.class'
local Frame = getClass 'pud.ui.Frame'
local pushRenderTarget, popRenderTarget = pushRenderTarget, popRenderTarget
local setColor = love.graphics.setColor
local setFont = love.graphics.setFont
local gprint = love.graphics.print
local math_floor = math.floor
local string_sub = string.sub
local string_gmatch = string.gmatch
local format = string.format
-- Text
-- A static text frame
local Text = Class{name='Text',
inherits=Frame,
function(self, ...)
Frame.construct(self, ...)
self._maxLines = 1
self._text = {}
self._justify = 'l'
self._margin = 0
end
}
-- destructor
function Text:destroy()
self:clear()
self._text = nil
self._justify = nil
self._margin = nil
Frame.destroy(self)
end
-- set the text that will be displayed
-- text can be a string or a table of strings, representing lines
-- (newline is not supported)
function Text:setText(text)
if type(text) == 'string' then text = {text} end
verify('table', text)
self:clear()
text = self:_wrap(text)
local numLines = #text
if numLines > self._maxLines then
warning('setText(lines): number of lines (%d) exceeds maximum (%d)',
numLines, self._maxLines)
for i=1,self._maxLines do
self._text[i] = text[i]
end
else
self._text = text
end
self:_drawFB()
end
-- assuming width is constant, wrap lines if they're larger than the width
-- of this frame.
function Text:_wrap(text)
local font = self._curStyle:getFont()
if font then
local space = font:getWidth(' ')
local margin = self._margin or 0
local frameWidth = self:getWidth() - (2 * margin)
local num = #text
local wrapped
local wrapcount = 0
for i=1,num do
wrapcount = wrapcount + 1
wrapped = wrapped or {}
-- if width is too long, wrap
if font:getWidth(text[i]) > frameWidth then
local width = 0
local here = 0
-- check one word at a time
for word in string_gmatch(text[i], '%s*(%S+)') do
local wordW = font:getWidth(word)
local prevWidth = width
width = width + wordW
-- if the running width of all checked words is too long, wrap
if width > frameWidth then
-- if it's a single word, or we're on the last line, truncate
if width == wordW or wrapcount == self._maxLines then
local old = word
while #word > 0 and width > frameWidth do
word = string_sub(word, 1, -2)
wordW = font:getWidth(word)
width = prevWidth + wordW
end
warning('Word %q is too long, truncating to %q', old, word)
end
if prevWidth == 0 then
-- single word
width = -space
wrapped[wrapcount] = word
elseif wrapcount == self._maxLines then
-- last line
width = frameWidth - space
wrapped[wrapcount] = format('%s %s', wrapped[wrapcount], word)
else
-- neither single word or last line
width = wordW
wrapcount = wrapcount + 1
wrapped[wrapcount] = word
end
else
-- didn't wrap, just add the word
if wrapped[wrapcount] then
wrapped[wrapcount] = format('%s %s', wrapped[wrapcount], word)
else
wrapped[wrapcount] = word
end
end -- if width > frameWidth
width = width + space
end -- for word in string_gmatch
else
wrapped[wrapcount] = text[i]
end -- if font:getWidth
end
return wrapped and wrapped or text
end
end
-- returns the currently set text as a table of strings, one per line
function Text:getText() return self._text end
-- clear the current text
function Text:clear()
for k in pairs(self._text) do self._text[k] = nil end
end
-- set the maximum number of lines
function Text:setMaxLines(max)
verify('number', max)
self._maxLines = max
end
-- set the margin between the frame edge and the text
function Text:setMargin(margin)
verify('number', margin)
self._margin = margin
self:_drawFB()
end
-- set the justification
function Text:setJustifyLeft() self._justify = 'l' end
function Text:setJustifyRight() self._justify = 'r' end
function Text:setJustifyCenter() self._justify = 'c' end
-- override Frame:_drawFB()
function Text:_drawFB()
self._bfb = self._bfb or self:_getFramebuffer()
pushRenderTarget(self._bfb)
self:_drawBackground()
if self._text and #self._text > 0 then
if self._curStyle then
local font = self._curStyle:getFont()
if font then
local height = font:getHeight()
local margin = self._margin or 0
local text = self._text
local textLines = #text
local maxLines = math_floor((self:getHeight() - (2*margin)) / height)
local numLines = textLines > maxLines and maxLines or textLines
local fontcolor = self._curStyle:getFontColor()
setFont(font)
setColor(fontcolor)
for i=1,numLines do
local line = text[i]
local h = (i-1) * height
local w = font:getWidth(line)
local y = margin + h
local x
if 'l' == self._justify then
x = margin
elseif 'c' == self._justify then
local cx = self:getWidth() / 2
x = math_floor(cx - (w/2))
elseif 'r' == self._justify then
x = self:getWidth() - (margin + w)
else
x, y = 0, 0
warning('Unjustified (justify is set to %q)',
tostring(self._justify))
end
gprint(line, x, y)
end
end
end
end
popRenderTarget()
self._ffb, self._bfb = self._bfb, self._ffb
end
-- the class
return Text
|
fixed wrap, and call wrap on setText instead of during draw
|
fixed wrap, and call wrap on setText instead of during draw
|
Lua
|
mit
|
scottcs/wyx
|
f79a6bc543ebc146550e241713609924d3c20208
|
xmake/languages/dlang/xmake.lua
|
xmake/languages/dlang/xmake.lua
|
--!The Make-like Build Utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2017, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define language
language("dlang")
-- set source file kinds
set_sourcekinds {dc = ".d", cc = ".c", cxx = {".cc", ".cpp", ".cxx"}}
-- set source file flags
set_sourceflags {dc = "dcflags"}
-- set target kinds
set_targetkinds {binary = "dc-ld", static = "dc-ar", shared = "dc-sh"}
-- set target flags
set_targetflags {binary = "ldflags", static = "arflags", shared = "shflags"}
-- on load
on_load("load")
-- on check_main
on_check_main("check_main")
-- set name flags
set_nameflags
{
object =
{
"config.includedirs"
, "target.symbols"
, "target.warnings"
, "target.optimize:check"
, "target.vectorexts:check"
, "target.includedirs"
, "platform.includedirs"
}
, binary =
{
"config.linkdirs"
, "target.linkdirs"
, "target.strip"
, "target.symbols"
, "option.linkdirs"
, "platform.linkdirs"
, "config.links"
, "target.links"
, "option.links"
, "platform.links"
}
, shared =
{
"config.linkdirs"
, "target.linkdirs"
, "target.strip"
, "target.symbols"
, "option.linkdirs"
, "platform.linkdirs"
, "config.links"
, "target.links"
, "option.links"
, "platform.links"
}
, static =
{
"target.strip"
, "target.symbols"
}
}
-- set menu
set_menu {
config =
{
{ }
, {nil, "dc", "kv", nil, "The Dlang Compiler" }
, {nil, "dc-ld", "kv", nil, "The Dlang Linker" }
, {nil, "dc-ar", "kv", nil, "The Dlang Static Library Archiver" }
, {nil, "dc-sh", "kv", nil, "The Dlang Shared Library Linker" }
, { }
, {nil, "links", "kv", nil, "The Link Libraries" }
, {nil, "linkdirs", "kv", nil, "The Link Search Directories" }
, {nil, "includedirs","kv", nil, "The Include Search Directories" }
}
}
|
--!The Make-like Build Utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2017, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- define language
language("dlang")
-- set source file kinds
set_sourcekinds {dc = ".d"}
-- set source file flags
set_sourceflags {dc = "dcflags"}
-- set target kinds
set_targetkinds {binary = "dc-ld", static = "dc-ar", shared = "dc-sh"}
-- set target flags
set_targetflags {binary = "ldflags", static = "arflags", shared = "shflags"}
-- on load
on_load("load")
-- on check_main
on_check_main("check_main")
-- set name flags
set_nameflags
{
object =
{
"config.includedirs"
, "target.symbols"
, "target.warnings"
, "target.optimize:check"
, "target.vectorexts:check"
, "target.includedirs"
, "platform.includedirs"
}
, binary =
{
"config.linkdirs"
, "target.linkdirs"
, "target.strip"
, "target.symbols"
, "option.linkdirs"
, "platform.linkdirs"
, "config.links"
, "target.links"
, "option.links"
, "platform.links"
}
, shared =
{
"config.linkdirs"
, "target.linkdirs"
, "target.strip"
, "target.symbols"
, "option.linkdirs"
, "platform.linkdirs"
, "config.links"
, "target.links"
, "option.links"
, "platform.links"
}
, static =
{
"target.strip"
, "target.symbols"
}
}
-- set menu
set_menu {
config =
{
{ }
, {nil, "dc", "kv", nil, "The Dlang Compiler" }
, {nil, "dc-ld", "kv", nil, "The Dlang Linker" }
, {nil, "dc-ar", "kv", nil, "The Dlang Static Library Archiver" }
, {nil, "dc-sh", "kv", nil, "The Dlang Shared Library Linker" }
, { }
, {nil, "links", "kv", nil, "The Link Libraries" }
, {nil, "linkdirs", "kv", nil, "The Link Search Directories" }
, {nil, "includedirs","kv", nil, "The Include Search Directories" }
}
}
|
fix dlang config bugs
|
fix dlang config bugs
|
Lua
|
apache-2.0
|
tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake
|
2d67de80955ab5786ac8677f64c36e327f8b8eae
|
agents/monitoring/default/protocol/request.lua
|
agents/monitoring/default/protocol/request.lua
|
--[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local table = require('table')
local https = require('https')
local fs = require('fs')
local logging = require('logging')
local errors = require('../errors')
local Error = require('core').Error
local misc = require('../util/misc')
local fmt = require('string').format
local Object = require('core').Object
local exports = {}
local Request = Object:extend()
--[[
Attempts to upload or download a file over https to options.host:options.port OR
for endpoints in options.endpoints. Will try options.attempts number of times, or
for each endpoint if not specified.
options = {
host/port OR endpoints [{Endpoint1, Endpoint2, ...}]
path = "string",
method = "METHOD"
upload = nil or '/some/path'
download = nil or '/some/path'
attempts = int or #endpoints
}
]]--
local function makeRequest(...)
local req = Request:new(...)
req:set_headers()
req:request()
return req
end
function Request:initialize(options, callback)
self.callback = misc.fireOnce(callback)
if not options.method then
return self.callback(Error:new('I need a http method'))
end
if options.endpoints then
self.endpoints = misc.merge({}, options.endpoints)
else
self.endpoints = {{host=options.host, port=options.port}}
end
self.attempts = options.attempts or #self.endpoints
self.download = options.download
self.upload = options.upload
options.endpoints = nil
options.attempts = nil
options.download = nil
options.upload = nil
self.options = options
if not self:_cycle_endpoint() then
return self.callback(Error:new('call with options.port and options.host or options.endpoints'))
end
end
function Request:request()
logging.debugf('sending request to %s:%s', self.options.host, self.options.port)
local options = misc.merge({}, self.options)
local req = https.request(options, function(res)
self:_handle_response(res)
end)
req:on('error', function(err)
self:_ensure_retries(err)
end)
if not self.upload then
return req:done()
end
local data = fs.createReadStream(self.upload)
data:on('data', function(chunk)
req:write(chunk)
end)
data:on('end', function(d)
req:done(d)
end)
data:on('error', function(err)
req:done()
self._ensure_retries(err)
end)
end
function Request:_cycle_endpoint()
local position, endpoint
while self.attempts > 0 do
position = #self.endpoints % self.attempts
endpoint = self.endpoints[position+1]
self.attempts = self.attempts - 1
if endpoint and endpoint.host and endpoint.port then
self.options.host = endpoint.host
self.options.port = endpoint.port
return true
end
end
return false
end
function Request:set_headers(callback)
local method = self.options.method:upper()
local headers = {}
-- set defaults
headers['Content-Length'] = 0
headers["Content-Type"] = "application/text"
self.options.headers = misc.merge(headers, self.options.headers)
end
function Request:_write_stream(res)
logging.debugf('writing stream to disk: %s.', self.download)
local stream = fs.createWriteStream(self.download)
stream:on('end', function()
self:_ensure_retries(nil, res)
end)
stream:on('error', function(err)
self:_ensure_retries(err, res)
end)
res:on('end', function(d)
stream:finish(d)
end)
res:pipe(stream)
end
function Request:_ensure_retries(err, res)
if not err then
self.callback(err, res)
return
end
local status = res and res.status_code or "?"
local msg = fmt('%s to %s:%s failed for %s with status: %s and error: %s.', (self.options.method or "?"),
self.options.host, self.options.port, (self.download or self.upload or "?"), status, tostring(err))
logging.warn(msg)
if not self:_cycle_endpoint() then
return self.callback(err)
end
logging.debugf('retrying download %d more times.', self.attempts)
self:request()
end
function Request:_handle_response(res)
if self.download and res.status_code >= 200 and res.status_code < 300 then
return self:_write_stream(res)
end
local buf = ""
res:on('data', function(d)
buf = buf .. d
end)
res:on('end', function()
if res.status_code >= 400 then
return self:_ensure_retries(Error:new(buf), res)
end
self:_ensure_retries(nil, res)
end)
end
local exports = {makeRequest=makeRequest, Request=Request}
return exports
|
--[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local table = require('table')
local https = require('https')
local fs = require('fs')
local logging = require('logging')
local errors = require('../errors')
local Error = require('core').Error
local misc = require('../util/misc')
local fmt = require('string').format
local Object = require('core').Object
local exports = {}
local Request = Object:extend()
--[[
Attempts to upload or download a file over https to options.host:options.port OR
for endpoints in options.endpoints. Will try options.attempts number of times, or
for each endpoint if not specified.
options = {
host/port OR endpoints [{Endpoint1, Endpoint2, ...}]
path = "string",
method = "METHOD"
upload = nil or '/some/path'
download = nil or '/some/path'
attempts = int or #endpoints
}
]]--
local function makeRequest(...)
local req = Request:new(...)
req:set_headers()
req:request()
return req
end
function Request:initialize(options, callback)
self.callback = misc.fireOnce(callback)
if not options.method then
return self.callback(Error:new('I need a http method'))
end
if options.endpoints then
self.endpoints = misc.merge({}, options.endpoints)
else
self.endpoints = {{host=options.host, port=options.port}}
end
self.attempts = options.attempts or #self.endpoints
self.download = options.download
self.upload = options.upload
options.endpoints = nil
options.attempts = nil
options.download = nil
options.upload = nil
self.options = options
if not self:_cycle_endpoint() then
return self.callback(Error:new('call with options.port and options.host or options.endpoints'))
end
end
function Request:request()
logging.debugf('sending request to %s:%s', self.options.host, self.options.port)
local options = misc.merge({}, self.options)
local req = https.request(options, function(res)
self:_handle_response(res)
end)
req:on('error', function(err)
self:_ensure_retries(err)
end)
if not self.upload then
return req:done()
end
local data = fs.createReadStream(self.upload)
data:on('data', function(chunk)
req:write(chunk)
end)
data:on('end', function(d)
req:done(d)
end)
data:on('error', function(err)
req:done()
self._ensure_retries(err)
end)
end
function Request:_cycle_endpoint()
local position, endpoint
while self.attempts > 0 do
position = #self.endpoints % self.attempts
endpoint = self.endpoints[position+1]
self.attempts = self.attempts - 1
if endpoint and endpoint.host and endpoint.port then
self.options.host = endpoint.host
self.options.port = endpoint.port
return true
end
end
return false
end
function Request:set_headers(callback)
local method = self.options.method:upper()
local headers = {}
-- set defaults
headers['Content-Length'] = 0
headers["Content-Type"] = "application/text"
self.options.headers = misc.merge(headers, self.options.headers)
end
function Request:_write_stream(res)
logging.debugf('writing stream to disk: %s.', self.download)
local ok, stream = pcall(function()
return fs.createWriteStream(self.download)
end)
if not ok then
-- can't make the file because the dir doens't exist
if stream.code and stream.code == "ENOENT" then
return self.callback(stream)
end
return self:_ensure_retries(err, res)
end
stream:on('end', function()
self:_ensure_retries(nil, res)
end)
stream:on('error', function(err)
self:_ensure_retries(err, res)
end)
res:on('end', function(d)
stream:finish(d)
end)
res:pipe(stream)
end
function Request:_ensure_retries(err, res)
if not err then
self.callback(err, res)
return
end
local status = res and res.status_code or "?"
local msg = fmt('%s to %s:%s failed for %s with status: %s and error: %s.', (self.options.method or "?"),
self.options.host, self.options.port, (self.download or self.upload or "?"), status, tostring(err))
logging.warn(msg)
if not self:_cycle_endpoint() then
return self.callback(err)
end
logging.debugf('retrying download %d more times.', self.attempts)
self:request()
end
function Request:_handle_response(res)
if self.download and res.status_code >= 200 and res.status_code < 300 then
return self:_write_stream(res)
end
local buf = ""
res:on('data', function(d)
buf = buf .. d
end)
res:on('end', function()
if res.status_code >= 400 then
return self:_ensure_retries(Error:new(buf), res)
end
self:_ensure_retries(nil, res)
end)
end
local exports = {makeRequest=makeRequest, Request=Request}
return exports
|
Fix request.lua to handle trying to open a stupid file
|
Fix request.lua to handle trying to open a stupid file
|
Lua
|
apache-2.0
|
christopherjwang/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent,cp16net/virgo-base
|
7da7263d140d2a66300fbee16e3571f2b2db4e00
|
hydro/tooltip.lua
|
hydro/tooltip.lua
|
-- wrapper for imgui stuff to put a tooltip over it (and give it no title)
-- (and push/pop id strs so the no-title doesn't cause a problem)
local ffi = require 'ffi'
local ig = require 'ffi.imgui'
local table = require 'ext.table'
local function hoverTooltip(name)
if ig.igIsItemHovered(ig.ImGuiHoveredFlags_None) then
ig.igBeginTooltip()
ig.igText(name)
ig.igEndTooltip()
end
end
local function makeWrapTooltip(f)
return function(name, ...)
ig.igPushID_Str(name)
local result = f('', ...)
hoverTooltip(name)
ig.igPopID()
return result
end
end
local function tooltipLabel(label, str)
ig.igPushID_Str(label)
ig.igText(str)
hoverTooltip(label)
ig.igPopID()
end
-- naive wrappers of makeWrapTooltip
local wrap = table.map({
slider = ig.igSliderFloat,
combo = ig.igCombo,
button = ig.igButton,
float = ig.igInputFloat,
int = ig.igInputInt,
checkbox = ig.igCheckbox,
text = ig.igInputText,
}, function(f, wrapName)
return makeWrapTooltip(f), wrapName
end)
-- wrappers for table[key] access rather than ffi-allocated primitive access
local function makeTableAccess(prim, orig)
local ptr = ffi.new(prim..'[1]')
return function(title, t, k, ...)
if t[k] == nil then
error("failed to find value "..k.." in table "..tostring(t))
end
ptr[0] = t[k]
if orig(title, ptr, ...) then
t[k] = ptr[0]
return true
end
end
end
local checkboxTable = makeTableAccess('bool', wrap.checkbox)
local intTable = makeTableAccess('int', wrap.int)
local sliderTable = makeTableAccess('float', wrap.slider)
local buf = ffi.new'char[256]'
-- unlike others, this is a bit more than simple ffi primitive read/write
-- because imgui's float formatting isn't very flexible
-- also not 'tableFloat' because of the higher accuracy of double/string than float/string serializing
local function numberTable(title, t, k, ...)
local src = tostring(t[k])
local len = math.min(ffi.sizeof(buf)-1, #src)
ffi.copy(buf, src, len)
buf[len] = 0
-- TODO maybe ig.ImGuiInputTextFlags_EnterReturnsTrue
if wrap.text(title, buf, ffi.sizeof(buf), ...) then
local s = ffi.string(buf, ffi.sizeof(buf))
local v = tonumber(s)
if v then
t[k] = v
return true
end
end
end
-- here's another exception: combo boxes
-- because t[k] is Lua-based, lets make our values 1-based instead of 0-based
local int = ffi.new'int[1]'
local function comboTable(title, t, k, ...)
assert(t[k])
assert(type(t[k]) == 'number')
int[0] = t[k]-1
if wrap.combo(title, int, ...) then
t[k] = int[0]+1
return true
end
end
-- TODO dynamic sized buffer?
local function textTable(title, t, k, ...)
local src = tostring(t[k])
local len = math.min(ffi.sizeof(buf)-1, #src)
ffi.copy(buf, src, len)
buf[len] = 0
if wrap.text(title, buf, ffi.sizeof(buf), ...) then
t[k] = ffi.string(buf)
return true
end
end
-- tooltip wrappers
local tooltip = {
button = wrap.button,
checkbox = wrap.checkbox,
combo = wrap.combo,
float = wrap.float,
int = wrap.int,
slider = wrap.slider,
sliderTable = sliderTable,
checkboxTable = checkboxTable,
intTable = intTable,
numberTable = numberTable,
comboTable = comboTable,
text = wrap.text,
textTable = textTable,
label = tooltipLabel,
}
return tooltip
|
-- wrapper for imgui stuff to put a tooltip over it (and give it no title)
-- (and push/pop id strs so the no-title doesn't cause a problem)
local ffi = require 'ffi'
local ig = require 'ffi.imgui'
local table = require 'ext.table'
require 'ffi.c.string' -- strlen
local function hoverTooltip(name)
if ig.igIsItemHovered(ig.ImGuiHoveredFlags_None) then
ig.igBeginTooltip()
ig.igText(name)
ig.igEndTooltip()
end
end
local function makeWrapTooltip(f)
return function(name, ...)
ig.igPushID_Str(name)
local result = f('', ...)
hoverTooltip(name)
ig.igPopID()
return result
end
end
local function tooltipLabel(label, str)
ig.igPushID_Str(label)
ig.igText(str)
hoverTooltip(label)
ig.igPopID()
end
-- naive wrappers of makeWrapTooltip
local wrap = table.map({
slider = ig.igSliderFloat,
combo = ig.igCombo,
button = ig.igButton,
float = ig.igInputFloat,
int = ig.igInputInt,
checkbox = ig.igCheckbox,
text = ig.igInputText,
}, function(f, wrapName)
return makeWrapTooltip(f), wrapName
end)
-- wrappers for table[key] access rather than ffi-allocated primitive access
local function makeTableAccess(prim, orig)
local ptr = ffi.new(prim..'[1]')
return function(title, t, k, ...)
if t[k] == nil then
error("failed to find value "..k.." in table "..tostring(t))
end
ptr[0] = t[k]
if orig(title, ptr, ...) then
t[k] = ptr[0]
return true
end
end
end
local checkboxTable = makeTableAccess('bool', wrap.checkbox)
local intTable = makeTableAccess('int', wrap.int)
local sliderTable = makeTableAccess('float', wrap.slider)
local buf = ffi.new'char[256]'
-- unlike others, this is a bit more than simple ffi primitive read/write
-- because imgui's float formatting isn't very flexible
-- also not 'tableFloat' because of the higher accuracy of double/string than float/string serializing
local function numberTable(title, t, k, ...)
local src = tostring(t[k])
local len = math.min(ffi.sizeof(buf)-1, #src)
ffi.copy(buf, src, len)
buf[len] = 0
-- TODO maybe ig.ImGuiInputTextFlags_EnterReturnsTrue
if wrap.text(title, buf, ffi.sizeof(buf), ...) then
-- ffi.string doesn't stop at the null term when you pass a fixed size
--local s = ffi.string(buf, ffi.sizeof(buf))
local s = ffi.string(buf, math.min(ffi.sizeof(buf), tonumber(ffi.C.strlen(buf))))
local v = tonumber(s)
if v then
t[k] = v
return true
end
end
end
-- here's another exception: combo boxes
-- because t[k] is Lua-based, lets make our values 1-based instead of 0-based
local int = ffi.new'int[1]'
local function comboTable(title, t, k, ...)
assert(t[k])
assert(type(t[k]) == 'number')
int[0] = t[k]-1
if wrap.combo(title, int, ...) then
t[k] = int[0]+1
return true
end
end
-- TODO dynamic sized buffer?
local function textTable(title, t, k, ...)
local src = tostring(t[k])
local len = math.min(ffi.sizeof(buf)-1, #src)
ffi.copy(buf, src, len)
buf[len] = 0
if wrap.text(title, buf, ffi.sizeof(buf), ...) then
t[k] = ffi.string(buf)
return true
end
end
-- tooltip wrappers
local tooltip = {
button = wrap.button,
checkbox = wrap.checkbox,
combo = wrap.combo,
float = wrap.float,
int = wrap.int,
slider = wrap.slider,
sliderTable = sliderTable,
checkboxTable = checkboxTable,
intTable = intTable,
numberTable = numberTable,
comboTable = comboTable,
text = wrap.text,
textTable = textTable,
label = tooltipLabel,
}
return tooltip
|
fixed a bug
|
fixed a bug
|
Lua
|
mit
|
thenumbernine/hydro-cl-lua,thenumbernine/hydro-cl-lua,thenumbernine/hydro-cl-lua
|
1b700c00443da111bdd3eb0bad6a42a9a8f2a370
|
plugins/kobolight.koplugin/main.lua
|
plugins/kobolight.koplugin/main.lua
|
local Device = require("device")
local with_frontlight = (Device:isKindle() or Device:isKobo()) and Device:hasFrontlight()
if not (with_frontlight or Device:isSDL()) then
return { disabled = true, }
end
local ConfirmBox = require("ui/widget/confirmbox")
local ImageWidget = require("ui/widget/imagewidget")
local InfoMessage = require("ui/widget/infomessage")
local Notification = require("ui/widget/notification")
local PluginLoader = require("pluginloader")
local Screen = require("device").screen
local UIManager = require("ui/uimanager")
local WidgetContainer = require("ui/widget/container/widgetcontainer")
local T = require("ffi/util").template
local _ = require("gettext")
local tap_touch_zone_ratio = { x = 0, y = 15/16, w = 1/10, h = 1/16, }
local swipe_touch_zone_ratio = { x = 0, y = 1/8, w = 1/10, h = 7/8, }
local KoboLight = WidgetContainer:new{
name = 'kobolight',
gestureScale = nil, -- initialized in self:resetLayout()
}
function KoboLight:init()
local powerd = Device:getPowerDevice()
local scale = (powerd.fl_max - powerd.fl_min) / 2 / 10.6
self.steps = { 0.1, 0.1, 0.2, 0.4, 0.7, 1.1, 1.6, 2.2, 2.9, 3.7, 4.6, 5.6, 6.7, 7.9, 9.2, 10.6, }
for i = 1, #self.steps, 1
do
self.steps[i] = math.ceil(self.steps[i] * scale)
end
self.ui.menu:registerToMainMenu(self)
end
function KoboLight:onReaderReady()
self:setupTouchZones()
self:resetLayout()
end
function KoboLight:disabled()
return G_reader_settings:isTrue("disable_kobolight")
end
function KoboLight:setupTouchZones()
if not Device:isTouchDevice() then return end
if self:disabled() then return end
local swipe_zone = {
ratio_x = swipe_touch_zone_ratio.x, ratio_y = swipe_touch_zone_ratio.y,
ratio_w = swipe_touch_zone_ratio.w, ratio_h = swipe_touch_zone_ratio.h,
}
self.ui:registerTouchZones({
{
id = "plugin_kobolight_tap",
ges = "tap",
screen_zone = {
ratio_x = tap_touch_zone_ratio.x, ratio_y = tap_touch_zone_ratio.y,
ratio_w = tap_touch_zone_ratio.w, ratio_h = tap_touch_zone_ratio.h,
},
handler = function() return self:onTap() end,
overrides = { 'readerfooter_tap' },
},
{
id = "plugin_kobolight_swipe",
ges = "swipe",
screen_zone = swipe_zone,
handler = function(ges) return self:onSwipe(nil, ges) end,
overrides = { 'paging_swipe', 'rolling_swipe', },
},
{
-- dummy zone to disable reader panning
id = "plugin_kobolight_pan",
ges = "pan",
screen_zone = swipe_zone,
handler = function(ges) return true end,
overrides = { 'paging_pan', 'rolling_pan', },
},
{
-- dummy zone to disable reader panning
id = "plugin_kobolight_pan_release",
ges = "pan_release",
screen_zone = swipe_zone,
handler = function(ges) return true end,
overrides = { 'paging_pan_release', },
},
})
end
function KoboLight:resetLayout()
local new_screen_height = Screen:getHeight()
self.gestureScale = new_screen_height * swipe_touch_zone_ratio.h * 0.8
end
function KoboLight:onShowIntensity()
local powerd = Device:getPowerDevice()
if powerd.fl_intensity ~= nil then
UIManager:show(Notification:new{
text = T(_("Frontlight intensity is set to %1."), powerd.fl_intensity),
timeout = 1.0,
})
end
return true
end
function KoboLight:onShowOnOff()
local powerd = Device:getPowerDevice()
local new_text
if powerd.is_fl_on then
new_text = _("Frontlight is on.")
else
new_text = _("Frontlight is off.")
end
UIManager:show(Notification:new{
text = new_text,
timeout = 1.0,
})
return true
end
function KoboLight:onTap()
Device:getPowerDevice():toggleFrontlight()
self:onShowOnOff()
if self.view.footer_visible and self.view.footer.settings.frontlight then
self.view.footer:updateFooter()
end
return true
end
function KoboLight:onSwipe(_, ges)
local powerd = Device:getPowerDevice()
if powerd.fl_intensity == nil then return true end
local step = math.ceil(#self.steps * ges.distance / self.gestureScale)
local delta_int = self.steps[step] or self.steps[#self.steps]
local new_intensity
if ges.direction == "north" then
new_intensity = powerd.fl_intensity + delta_int
elseif ges.direction == "south" then
new_intensity = powerd.fl_intensity - delta_int
end
if new_intensity ~= nil then
-- when new_intensity <=0, toggle light off
if new_intensity <=0 then
if powerd.is_fl_on then
powerd:toggleFrontlight()
end
self:onShowOnOff()
else -- general case
powerd:setIntensity(new_intensity)
self:onShowIntensity()
end
if self.view.footer_visible and self.view.footer.settings.frontlight then
self.view.footer:updateFooter()
end
end
return true
end
function KoboLight:addToMainMenu(menu_items)
menu_items.frontlight_gesture_controller = {
text = _("Frontlight gesture controller"),
callback = function()
local image = ImageWidget:new{
file = PluginLoader.plugin_path .. "/kobolight.koplugin/demo.png",
height = Screen:getHeight(),
width = Screen:getWidth(),
scale_factor = 0,
}
UIManager:show(image)
UIManager:show(ConfirmBox:new{
text = T(_("Frontlight gesture controller can:\n- Turn on or off frontlight by tapping bottom left of the screen.\n- Change frontlight intensity by swiping up or down on the left of the screen.\n\nDo you want to %1 it?"),
self:disabled() and _("enable") or _("disable")),
ok_text = self:disabled() and _("Enable") or _("Disable"),
ok_callback = function()
UIManager:close(image)
UIManager:setDirty("all", "full")
UIManager:show(InfoMessage:new{
text = T(_("You have %1 the frontlight gesture controller. It will take effect on next restart."),
self:disabled() and _("enabled") or _("disabled"))
})
G_reader_settings:flipTrue("disable_kobolight")
end,
cancel_text = _("Close"),
cancel_callback = function()
UIManager:close(image)
UIManager:setDirty("all", "full")
end,
})
UIManager:setDirty("all", "full")
end,
}
end
return KoboLight
|
local Device = require("device")
local with_frontlight = (Device:isKindle() or Device:isKobo()) and Device:hasFrontlight()
if not (with_frontlight or Device:isSDL()) then
return { disabled = true, }
end
local ConfirmBox = require("ui/widget/confirmbox")
local ImageWidget = require("ui/widget/imagewidget")
local InfoMessage = require("ui/widget/infomessage")
local Notification = require("ui/widget/notification")
local PluginLoader = require("pluginloader")
local Screen = require("device").screen
local UIManager = require("ui/uimanager")
local WidgetContainer = require("ui/widget/container/widgetcontainer")
local T = require("ffi/util").template
local _ = require("gettext")
local tap_touch_zone_ratio = { x = 0, y = 15/16, w = 1/10, h = 1/16, }
local swipe_touch_zone_ratio = { x = 0, y = 1/8, w = 1/10, h = 7/8, }
local KoboLight = WidgetContainer:new{
name = 'kobolight',
gestureScale = nil, -- initialized in self:resetLayout()
}
function KoboLight:init()
local powerd = Device:getPowerDevice()
local scale = (powerd.fl_max - powerd.fl_min) / 2 / 10.6
self.steps = { 0.1, 0.1, 0.2, 0.4, 0.7, 1.1, 1.6, 2.2, 2.9, 3.7, 4.6, 5.6, 6.7, 7.9, 9.2, 10.6, }
for i = 1, #self.steps, 1
do
self.steps[i] = math.ceil(self.steps[i] * scale)
end
self.ui.menu:registerToMainMenu(self)
end
function KoboLight:onReaderReady()
self:setupTouchZones()
self:resetLayout()
end
function KoboLight:disabled()
return G_reader_settings:isTrue("disable_kobolight")
end
function KoboLight:setupTouchZones()
if not Device:isTouchDevice() then return end
if self:disabled() then return end
local swipe_zone = {
ratio_x = swipe_touch_zone_ratio.x, ratio_y = swipe_touch_zone_ratio.y,
ratio_w = swipe_touch_zone_ratio.w, ratio_h = swipe_touch_zone_ratio.h,
}
self.ui:registerTouchZones({
{
id = "plugin_kobolight_tap",
ges = "tap",
screen_zone = {
ratio_x = tap_touch_zone_ratio.x, ratio_y = tap_touch_zone_ratio.y,
ratio_w = tap_touch_zone_ratio.w, ratio_h = tap_touch_zone_ratio.h,
},
handler = function() return self:onTap() end,
overrides = { 'readerfooter_tap' },
},
{
id = "plugin_kobolight_swipe",
ges = "swipe",
screen_zone = swipe_zone,
handler = function(ges) return self:onSwipe(nil, ges) end,
overrides = { 'paging_swipe', 'rolling_swipe', },
},
{
-- dummy zone to disable reader panning
id = "plugin_kobolight_pan",
ges = "pan",
screen_zone = swipe_zone,
handler = function(ges) return true end,
overrides = { 'paging_pan', 'rolling_pan', },
},
{
-- dummy zone to disable reader panning
id = "plugin_kobolight_pan_release",
ges = "pan_release",
screen_zone = swipe_zone,
handler = function(ges) return true end,
overrides = { 'paging_pan_release', },
},
})
end
function KoboLight:resetLayout()
local new_screen_height = Screen:getHeight()
self.gestureScale = new_screen_height * swipe_touch_zone_ratio.h * 0.8
end
function KoboLight:onShowIntensity()
local powerd = Device:getPowerDevice()
if powerd.fl_intensity ~= nil then
UIManager:show(Notification:new{
text = T(_("Frontlight intensity is set to %1."), powerd.fl_intensity),
timeout = 1.0,
})
end
return true
end
function KoboLight:onShowOnOff()
local powerd = Device:getPowerDevice()
local new_text
if powerd.is_fl_on then
new_text = _("Frontlight is on.")
else
new_text = _("Frontlight is off.")
end
UIManager:show(Notification:new{
text = new_text,
timeout = 1.0,
})
return true
end
function KoboLight:onTap()
Device:getPowerDevice():toggleFrontlight()
self:onShowOnOff()
if self.view.footer_visible and self.view.footer.settings.frontlight then
self.view.footer:updateFooter()
end
return true
end
function KoboLight:onSwipe(_, ges)
local powerd = Device:getPowerDevice()
if powerd.fl_intensity == nil then return false end
local step = math.ceil(#self.steps * ges.distance / self.gestureScale)
local delta_int = self.steps[step] or self.steps[#self.steps]
local new_intensity
if ges.direction == "north" then
new_intensity = powerd.fl_intensity + delta_int
elseif ges.direction == "south" then
new_intensity = powerd.fl_intensity - delta_int
else
return false -- don't consume swipe event if it's not matched
end
-- when new_intensity <=0, toggle light off
if new_intensity <=0 then
if powerd.is_fl_on then
powerd:toggleFrontlight()
end
self:onShowOnOff()
else -- general case
powerd:setIntensity(new_intensity)
self:onShowIntensity()
end
if self.view.footer_visible and self.view.footer.settings.frontlight then
self.view.footer:updateFooter()
end
return true
end
function KoboLight:addToMainMenu(menu_items)
menu_items.frontlight_gesture_controller = {
text = _("Frontlight gesture controller"),
callback = function()
local image = ImageWidget:new{
file = PluginLoader.plugin_path .. "/kobolight.koplugin/demo.png",
height = Screen:getHeight(),
width = Screen:getWidth(),
scale_factor = 0,
}
UIManager:show(image)
UIManager:show(ConfirmBox:new{
text = T(_("Frontlight gesture controller can:\n- Turn on or off frontlight by tapping bottom left of the screen.\n- Change frontlight intensity by swiping up or down on the left of the screen.\n\nDo you want to %1 it?"),
self:disabled() and _("enable") or _("disable")),
ok_text = self:disabled() and _("Enable") or _("Disable"),
ok_callback = function()
UIManager:close(image)
UIManager:setDirty("all", "full")
UIManager:show(InfoMessage:new{
text = T(_("You have %1 the frontlight gesture controller. It will take effect on next restart."),
self:disabled() and _("enabled") or _("disabled"))
})
G_reader_settings:flipTrue("disable_kobolight")
end,
cancel_text = _("Close"),
cancel_callback = function()
UIManager:close(image)
UIManager:setDirty("all", "full")
end,
})
UIManager:setDirty("all", "full")
end,
}
end
return KoboLight
|
kobolight(fix): do not consume swipe event if not matched
|
kobolight(fix): do not consume swipe event if not matched
Otherwise it will conflict with swipe to go back feature
|
Lua
|
agpl-3.0
|
Markismus/koreader,mihailim/koreader,mwoz123/koreader,koreader/koreader,NiLuJe/koreader,Frenzie/koreader,apletnev/koreader,robert00s/koreader,lgeek/koreader,Frenzie/koreader,pazos/koreader,NiLuJe/koreader,Hzj-jie/koreader,poire-z/koreader,houqp/koreader,koreader/koreader,poire-z/koreader
|
794a2f537c2235779995192e91c482caf455b9e5
|
modules/admin-core/luasrc/controller/admin/uci.lua
|
modules/admin-core/luasrc/controller/admin/uci.lua
|
module("luci.controller.admin.uci", package.seeall)
require("luci.util")
require("luci.sys")
function index()
node("admin", "uci", "changes").target = call("action_changes")
node("admin", "uci", "revert").target = call("action_revert")
node("admin", "uci", "apply").target = call("action_apply")
end
function convert_changes(changes)
local ret = {}
for r, tbl in pairs(changes) do
for s, os in pairs(tbl) do
for o, v in pairs(os) do
local val, str
if (v == "") then
str = "-"
val = ""
else
str = ""
val = "="..v
end
str = r.."."..s
if o ~= ".type" then
str = str.."."..o
end
table.insert(ret, str..val)
end
end
end
return table.concat(ret, "\n")
end
function action_changes()
local changes = convert_changes(luci.model.uci.changes())
luci.template.render("admin_uci/changes", {changes=changes})
end
function action_apply()
local changes = luci.model.uci.changes()
local output = ""
if changes then
local com = {}
local run = {}
-- Collect files to be applied and commit changes
for r, tbl in pairs(changes) do
if r then
luci.model.uci.load(r)
luci.model.uci.commit(r)
luci.model.uci.unload(r)
if luci.config.uci_oncommit and luci.config.uci_oncommit[r] then
run[luci.config.uci_oncommit[r]] = true
end
end
end
-- Search for post-commit commands
for cmd, i in pairs(run) do
output = output .. cmd .. ":" .. luci.sys.exec(cmd) .. "\n"
end
end
luci.template.render("admin_uci/apply", {changes=convert_changes(changes), output=output})
end
function action_revert()
local changes = luci.model.uci.changes()
if changes then
local revert = {}
-- Collect files to be reverted
for r, tbl in pairs(changes) do
luci.model.uci.load(r)
luci.model.uci.revert(r)
luci.model.uci.unload(r)
end
end
luci.template.render("admin_uci/revert", {changes=convert_changes(changes)})
end
|
module("luci.controller.admin.uci", package.seeall)
function index()
node("admin", "uci", "changes").target = call("action_changes")
node("admin", "uci", "revert").target = call("action_revert")
node("admin", "uci", "apply").target = call("action_apply")
end
function convert_changes(changes)
local ret = {}
for r, tbl in pairs(changes) do
for s, os in pairs(tbl) do
for o, v in pairs(os) do
local val, str
if (v == "") then
str = "-"
val = ""
else
str = ""
val = "="..v
end
str = r.."."..s
if o ~= ".type" then
str = str.."."..o
end
table.insert(ret, str..val)
end
end
end
return table.concat(ret, "\n")
end
function action_changes()
local changes = convert_changes(luci.model.uci.changes())
luci.template.render("admin_uci/changes", {changes=changes})
end
function action_apply()
local changes = luci.model.uci.changes()
local output = ""
if changes then
local com = {}
local run = {}
-- Collect files to be applied and commit changes
for r, tbl in pairs(changes) do
if r then
luci.model.uci.load(r)
luci.model.uci.commit(r)
luci.model.uci.unload(r)
if luci.config.uci_oncommit and luci.config.uci_oncommit[r] then
run[luci.config.uci_oncommit[r]] = true
end
end
end
-- Search for post-commit commands
for cmd, i in pairs(run) do
output = output .. cmd .. ":" .. luci.sys.exec(cmd) .. "\n"
end
end
luci.template.render("admin_uci/apply", {changes=convert_changes(changes), output=output})
end
function action_revert()
local changes = luci.model.uci.changes()
if changes then
local revert = {}
-- Collect files to be reverted
for r, tbl in pairs(changes) do
luci.model.uci.load(r)
luci.model.uci.revert(r)
luci.model.uci.unload(r)
end
end
luci.template.render("admin_uci/revert", {changes=convert_changes(changes)})
end
|
* Fixed an issue that prevented the controller from working with fastindex
|
* Fixed an issue that prevented the controller from working with fastindex
|
Lua
|
apache-2.0
|
bright-things/ionic-luci,LuttyYang/luci,hnyman/luci,981213/luci-1,openwrt/luci,aircross/OpenWrt-Firefly-LuCI,zhaoxx063/luci,dwmw2/luci,david-xiao/luci,RuiChen1113/luci,fkooman/luci,Sakura-Winkey/LuCI,Noltari/luci,NeoRaider/luci,joaofvieira/luci,slayerrensky/luci,male-puppies/luci,LazyZhu/openwrt-luci-trunk-mod,kuoruan/luci,mumuqz/luci,ollie27/openwrt_luci,Hostle/luci,dismantl/luci-0.12,rogerpueyo/luci,dwmw2/luci,jorgifumi/luci,Hostle/openwrt-luci-multi-user,oneru/luci,urueedi/luci,Noltari/luci,Kyklas/luci-proto-hso,oneru/luci,nmav/luci,thesabbir/luci,rogerpueyo/luci,opentechinstitute/luci,db260179/openwrt-bpi-r1-luci,male-puppies/luci,obsy/luci,schidler/ionic-luci,ff94315/luci-1,male-puppies/luci,deepak78/new-luci,MinFu/luci,Hostle/openwrt-luci-multi-user,palmettos/cnLuCI,wongsyrone/luci-1,jchuang1977/luci-1,Hostle/openwrt-luci-multi-user,deepak78/new-luci,bittorf/luci,hnyman/luci,obsy/luci,keyidadi/luci,bright-things/ionic-luci,tcatm/luci,forward619/luci,opentechinstitute/luci,teslamint/luci,Sakura-Winkey/LuCI,jorgifumi/luci,kuoruan/luci,Hostle/openwrt-luci-multi-user,openwrt-es/openwrt-luci,oyido/luci,slayerrensky/luci,cappiewu/luci,cshore/luci,jchuang1977/luci-1,kuoruan/luci,RuiChen1113/luci,urueedi/luci,nwf/openwrt-luci,ff94315/luci-1,oyido/luci,kuoruan/lede-luci,ff94315/luci-1,schidler/ionic-luci,LuttyYang/luci,LazyZhu/openwrt-luci-trunk-mod,lcf258/openwrtcn,lcf258/openwrtcn,david-xiao/luci,Noltari/luci,ReclaimYourPrivacy/cloak-luci,MinFu/luci,nwf/openwrt-luci,db260179/openwrt-bpi-r1-luci,david-xiao/luci,cshore-firmware/openwrt-luci,remakeelectric/luci,taiha/luci,ReclaimYourPrivacy/cloak-luci,daofeng2015/luci,ff94315/luci-1,Hostle/luci,teslamint/luci,NeoRaider/luci,joaofvieira/luci,nmav/luci,jlopenwrtluci/luci,dwmw2/luci,ollie27/openwrt_luci,urueedi/luci,981213/luci-1,dismantl/luci-0.12,forward619/luci,obsy/luci,kuoruan/luci,bittorf/luci,tobiaswaldvogel/luci,slayerrensky/luci,Wedmer/luci,981213/luci-1,Noltari/luci,palmettos/test,kuoruan/luci,deepak78/new-luci,palmettos/cnLuCI,tcatm/luci,jlopenwrtluci/luci,MinFu/luci,thesabbir/luci,tcatm/luci,oneru/luci,Wedmer/luci,palmettos/cnLuCI,florian-shellfire/luci,teslamint/luci,cappiewu/luci,maxrio/luci981213,RedSnake64/openwrt-luci-packages,nwf/openwrt-luci,remakeelectric/luci,joaofvieira/luci,palmettos/cnLuCI,oneru/luci,keyidadi/luci,mumuqz/luci,rogerpueyo/luci,nmav/luci,Wedmer/luci,jchuang1977/luci-1,palmettos/cnLuCI,maxrio/luci981213,florian-shellfire/luci,nmav/luci,opentechinstitute/luci,shangjiyu/luci-with-extra,maxrio/luci981213,david-xiao/luci,ff94315/luci-1,urueedi/luci,kuoruan/lede-luci,sujeet14108/luci,openwrt/luci,tcatm/luci,artynet/luci,jchuang1977/luci-1,NeoRaider/luci,shangjiyu/luci-with-extra,aa65535/luci,aa65535/luci,dismantl/luci-0.12,Kyklas/luci-proto-hso,maxrio/luci981213,deepak78/new-luci,aa65535/luci,LuttyYang/luci,jchuang1977/luci-1,deepak78/new-luci,bright-things/ionic-luci,aircross/OpenWrt-Firefly-LuCI,981213/luci-1,taiha/luci,florian-shellfire/luci,nmav/luci,openwrt/luci,opentechinstitute/luci,Hostle/openwrt-luci-multi-user,shangjiyu/luci-with-extra,lcf258/openwrtcn,aircross/OpenWrt-Firefly-LuCI,nmav/luci,chris5560/openwrt-luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,artynet/luci,lbthomsen/openwrt-luci,RuiChen1113/luci,Sakura-Winkey/LuCI,dismantl/luci-0.12,aa65535/luci,thesabbir/luci,david-xiao/luci,chris5560/openwrt-luci,david-xiao/luci,kuoruan/lede-luci,bittorf/luci,nwf/openwrt-luci,openwrt/luci,981213/luci-1,shangjiyu/luci-with-extra,ff94315/luci-1,rogerpueyo/luci,thesabbir/luci,hnyman/luci,sujeet14108/luci,openwrt/luci,taiha/luci,db260179/openwrt-bpi-r1-luci,ReclaimYourPrivacy/cloak-luci,rogerpueyo/luci,taiha/luci,hnyman/luci,mumuqz/luci,teslamint/luci,florian-shellfire/luci,RedSnake64/openwrt-luci-packages,nwf/openwrt-luci,harveyhu2012/luci,lcf258/openwrtcn,lcf258/openwrtcn,cshore-firmware/openwrt-luci,mumuqz/luci,dismantl/luci-0.12,slayerrensky/luci,dwmw2/luci,zhaoxx063/luci,cappiewu/luci,male-puppies/luci,slayerrensky/luci,chris5560/openwrt-luci,artynet/luci,mumuqz/luci,rogerpueyo/luci,Hostle/luci,sujeet14108/luci,schidler/ionic-luci,jlopenwrtluci/luci,forward619/luci,shangjiyu/luci-with-extra,chris5560/openwrt-luci,oneru/luci,db260179/openwrt-bpi-r1-luci,remakeelectric/luci,ollie27/openwrt_luci,kuoruan/lede-luci,tobiaswaldvogel/luci,LuttyYang/luci,shangjiyu/luci-with-extra,daofeng2015/luci,cappiewu/luci,NeoRaider/luci,thesabbir/luci,tcatm/luci,obsy/luci,rogerpueyo/luci,maxrio/luci981213,bittorf/luci,joaofvieira/luci,nmav/luci,oyido/luci,openwrt/luci,slayerrensky/luci,cshore-firmware/openwrt-luci,nwf/openwrt-luci,palmettos/test,RuiChen1113/luci,RedSnake64/openwrt-luci-packages,mumuqz/luci,deepak78/new-luci,nwf/openwrt-luci,joaofvieira/luci,aircross/OpenWrt-Firefly-LuCI,lcf258/openwrtcn,tcatm/luci,NeoRaider/luci,cshore/luci,jorgifumi/luci,openwrt-es/openwrt-luci,wongsyrone/luci-1,oyido/luci,artynet/luci,taiha/luci,thess/OpenWrt-luci,fkooman/luci,lbthomsen/openwrt-luci,981213/luci-1,keyidadi/luci,openwrt-es/openwrt-luci,jchuang1977/luci-1,keyidadi/luci,keyidadi/luci,dwmw2/luci,nwf/openwrt-luci,981213/luci-1,joaofvieira/luci,LazyZhu/openwrt-luci-trunk-mod,ollie27/openwrt_luci,wongsyrone/luci-1,NeoRaider/luci,cappiewu/luci,taiha/luci,lbthomsen/openwrt-luci,jorgifumi/luci,obsy/luci,lbthomsen/openwrt-luci,artynet/luci,Kyklas/luci-proto-hso,teslamint/luci,urueedi/luci,Noltari/luci,aircross/OpenWrt-Firefly-LuCI,aa65535/luci,florian-shellfire/luci,lbthomsen/openwrt-luci,david-xiao/luci,ollie27/openwrt_luci,fkooman/luci,kuoruan/luci,palmettos/test,cshore/luci,lcf258/openwrtcn,palmettos/cnLuCI,RedSnake64/openwrt-luci-packages,marcel-sch/luci,ollie27/openwrt_luci,oyido/luci,jchuang1977/luci-1,obsy/luci,male-puppies/luci,bittorf/luci,MinFu/luci,lcf258/openwrtcn,aircross/OpenWrt-Firefly-LuCI,forward619/luci,aa65535/luci,schidler/ionic-luci,bright-things/ionic-luci,tobiaswaldvogel/luci,keyidadi/luci,daofeng2015/luci,openwrt-es/openwrt-luci,Hostle/openwrt-luci-multi-user,maxrio/luci981213,LuttyYang/luci,bright-things/ionic-luci,oneru/luci,forward619/luci,LazyZhu/openwrt-luci-trunk-mod,jlopenwrtluci/luci,lcf258/openwrtcn,LazyZhu/openwrt-luci-trunk-mod,forward619/luci,thess/OpenWrt-luci,maxrio/luci981213,keyidadi/luci,remakeelectric/luci,harveyhu2012/luci,bittorf/luci,opentechinstitute/luci,hnyman/luci,fkooman/luci,Sakura-Winkey/LuCI,chris5560/openwrt-luci,dwmw2/luci,chris5560/openwrt-luci,schidler/ionic-luci,palmettos/test,cappiewu/luci,jchuang1977/luci-1,tcatm/luci,marcel-sch/luci,kuoruan/luci,cshore-firmware/openwrt-luci,Wedmer/luci,openwrt-es/openwrt-luci,keyidadi/luci,male-puppies/luci,forward619/luci,oyido/luci,florian-shellfire/luci,artynet/luci,florian-shellfire/luci,ReclaimYourPrivacy/cloak-luci,Hostle/luci,palmettos/test,Hostle/openwrt-luci-multi-user,cshore-firmware/openwrt-luci,urueedi/luci,cappiewu/luci,nmav/luci,wongsyrone/luci-1,deepak78/new-luci,LazyZhu/openwrt-luci-trunk-mod,zhaoxx063/luci,thess/OpenWrt-luci,db260179/openwrt-bpi-r1-luci,Noltari/luci,kuoruan/lede-luci,kuoruan/lede-luci,RuiChen1113/luci,jlopenwrtluci/luci,chris5560/openwrt-luci,zhaoxx063/luci,ReclaimYourPrivacy/cloak-luci,palmettos/cnLuCI,dwmw2/luci,oyido/luci,wongsyrone/luci-1,dismantl/luci-0.12,bittorf/luci,tobiaswaldvogel/luci,daofeng2015/luci,Kyklas/luci-proto-hso,wongsyrone/luci-1,hnyman/luci,schidler/ionic-luci,artynet/luci,MinFu/luci,RedSnake64/openwrt-luci-packages,cshore-firmware/openwrt-luci,Hostle/luci,marcel-sch/luci,zhaoxx063/luci,slayerrensky/luci,cshore-firmware/openwrt-luci,artynet/luci,daofeng2015/luci,remakeelectric/luci,daofeng2015/luci,obsy/luci,sujeet14108/luci,MinFu/luci,RedSnake64/openwrt-luci-packages,hnyman/luci,Noltari/luci,jorgifumi/luci,RedSnake64/openwrt-luci-packages,cappiewu/luci,harveyhu2012/luci,male-puppies/luci,Hostle/luci,male-puppies/luci,openwrt-es/openwrt-luci,fkooman/luci,taiha/luci,cshore/luci,thess/OpenWrt-luci,bright-things/ionic-luci,florian-shellfire/luci,zhaoxx063/luci,aa65535/luci,tobiaswaldvogel/luci,cshore/luci,mumuqz/luci,jorgifumi/luci,remakeelectric/luci,marcel-sch/luci,NeoRaider/luci,ReclaimYourPrivacy/cloak-luci,remakeelectric/luci,RuiChen1113/luci,bright-things/ionic-luci,tobiaswaldvogel/luci,teslamint/luci,fkooman/luci,harveyhu2012/luci,Kyklas/luci-proto-hso,dismantl/luci-0.12,jorgifumi/luci,openwrt-es/openwrt-luci,daofeng2015/luci,cshore/luci,shangjiyu/luci-with-extra,NeoRaider/luci,MinFu/luci,marcel-sch/luci,obsy/luci,deepak78/new-luci,sujeet14108/luci,opentechinstitute/luci,tobiaswaldvogel/luci,Noltari/luci,wongsyrone/luci-1,Kyklas/luci-proto-hso,bittorf/luci,remakeelectric/luci,joaofvieira/luci,Wedmer/luci,chris5560/openwrt-luci,LuttyYang/luci,Sakura-Winkey/LuCI,lbthomsen/openwrt-luci,LuttyYang/luci,wongsyrone/luci-1,lbthomsen/openwrt-luci,shangjiyu/luci-with-extra,ff94315/luci-1,thesabbir/luci,ollie27/openwrt_luci,oyido/luci,LazyZhu/openwrt-luci-trunk-mod,LuttyYang/luci,ollie27/openwrt_luci,teslamint/luci,openwrt-es/openwrt-luci,openwrt/luci,cshore-firmware/openwrt-luci,urueedi/luci,LazyZhu/openwrt-luci-trunk-mod,daofeng2015/luci,palmettos/test,dwmw2/luci,jorgifumi/luci,cshore/luci,Hostle/luci,taiha/luci,aircross/OpenWrt-Firefly-LuCI,jlopenwrtluci/luci,Noltari/luci,kuoruan/lede-luci,thess/OpenWrt-luci,sujeet14108/luci,ReclaimYourPrivacy/cloak-luci,lbthomsen/openwrt-luci,MinFu/luci,ff94315/luci-1,bright-things/ionic-luci,palmettos/test,jlopenwrtluci/luci,zhaoxx063/luci,urueedi/luci,db260179/openwrt-bpi-r1-luci,Wedmer/luci,Hostle/openwrt-luci-multi-user,db260179/openwrt-bpi-r1-luci,Hostle/luci,david-xiao/luci,artynet/luci,RuiChen1113/luci,opentechinstitute/luci,fkooman/luci,rogerpueyo/luci,thess/OpenWrt-luci,kuoruan/luci,marcel-sch/luci,hnyman/luci,schidler/ionic-luci,joaofvieira/luci,oneru/luci,Wedmer/luci,Sakura-Winkey/LuCI,Sakura-Winkey/LuCI,thesabbir/luci,aa65535/luci,tobiaswaldvogel/luci,palmettos/cnLuCI,cshore/luci,jlopenwrtluci/luci,Sakura-Winkey/LuCI,slayerrensky/luci,forward619/luci,ReclaimYourPrivacy/cloak-luci,harveyhu2012/luci,opentechinstitute/luci,Kyklas/luci-proto-hso,zhaoxx063/luci,fkooman/luci,openwrt/luci,sujeet14108/luci,thesabbir/luci,Wedmer/luci,mumuqz/luci,thess/OpenWrt-luci,teslamint/luci,sujeet14108/luci,harveyhu2012/luci,marcel-sch/luci,thess/OpenWrt-luci,oneru/luci,maxrio/luci981213,lcf258/openwrtcn,harveyhu2012/luci,kuoruan/lede-luci,palmettos/test,tcatm/luci,schidler/ionic-luci,marcel-sch/luci,nmav/luci
|
ba4e1d91aa0eefc29e739269481c26ed5ba40172
|
lib/lua/mock_edit/drag/TextureDragIn.lua
|
lib/lua/mock_edit/drag/TextureDragIn.lua
|
module 'mock_edit'
--------------------------------------------------------------------
CLASS: TextureDragIn ( SceneViewDrag )
:MODEL{}
function TextureDragIn:__init( path, x, y )
local entity = mock.Entity()
local texturePlane = entity:attach( mock.TexturePlane() )
texturePlane:setTexture( path )
texturePlane:resetSize()
entity:setName( stripdir(stripext(path)) )
local cmd = gii.doCommand(
'scene_editor/add_entity',
{
entity = entity
}
)
self.createdEntity = entity
end
function TextureDragIn:onStart( view, x, y )
self:updateInstanceLoc( view, x, y )
end
function TextureDragIn:onMove( view, x, y )
self:updateInstanceLoc( view, x, y )
end
function TextureDragIn:onStop( view )
end
function TextureDragIn:updateInstanceLoc( view, x, y )
if not self.createdEntity then return end
x, y = view:wndToWorld( x, y )
self.createdEntity:setWorldLoc( x, y )
view:updateCanvas()
end
--------------------------------------------------------------------
CLASS: TextureDragInFactory ( SceneViewDragFactory )
:MODEL{}
function TextureDragInFactory:create( view, mimeType, data, x, y )
if mimeType ~= 'application/gii.asset-list' then return false end
local result = {}
for i, path in ipairs( data ) do
local node = mock.getAssetNode( path )
local assetType = node:getType()
if assetType == 'texture' then
return TextureDragIn( path, x, y )
end
end
return result
end
|
module 'mock_edit'
--------------------------------------------------------------------
CLASS: TextureDragIn ( SceneViewDrag )
:MODEL{}
function TextureDragIn:__init( path, x, y )
local entity = mock.Entity()
local texturePlane = entity:attach( mock.TexturePlane() )
texturePlane:setTexture( path )
texturePlane:resetSize()
entity:setName( stripdir(stripext(path)) )
local cmd = gii.doCommand(
'scene_editor/add_entity',
{
entity = entity
}
)
self.createdEntity = entity
end
function TextureDragIn:onStart( view, x, y )
self:updateInstanceLoc( view, x, y )
end
function TextureDragIn:onMove( view, x, y )
self:updateInstanceLoc( view, x, y )
end
function TextureDragIn:onStop( view )
self.createdEntity:destroyWithChildrenNow()--FIXME: use undo
-- gii.undoCommand()
view:updateCanvas()
end
function TextureDragIn:updateInstanceLoc( view, x, y )
if not self.createdEntity then return end
x, y = view:wndToWorld( x, y )
self.createdEntity:setWorldLoc( x, y )
view:updateCanvas()
end
--------------------------------------------------------------------
CLASS: TextureDragInFactory ( SceneViewDragFactory )
:MODEL{}
function TextureDragInFactory:create( view, mimeType, data, x, y )
if mimeType ~= 'application/gii.asset-list' then return false end
local result = {}
for i, path in ipairs( data ) do
local node = mock.getAssetNode( path )
local assetType = node:getType()
if assetType == 'texture' then
return TextureDragIn( path, x, y )
end
end
return result
end
|
fix texture drag stop
|
fix texture drag stop
|
Lua
|
mit
|
tommo/gii,tommo/gii,tommo/gii,tommo/gii,tommo/gii,tommo/gii
|
a1762b989ac6a650307adc0f7620bfe1609301b7
|
Mean.lua
|
Mean.lua
|
local Mean, parent = torch.class('nn.Mean', 'nn.Module')
function Mean:__init(dimension)
parent.__init(self)
dimension = dimension or 1
self.dimension = dimension
end
function Mean:updateOutput(input)
self.output:mean(input, self.dimension)
if self.output:nDimension() > 1 then
self.output = self.output:select(self.dimension, 1)
end
return self.output
end
function Mean:updateGradInput(input, gradOutput)
local size = gradOutput:size():totable()
local stride = gradOutput:stride():totable()
if input:nDimension() > 1 then
table.insert(size, self.dimension, input:size(self.dimension))
table.insert(stride, self.dimension, 0)
else
size[1] = input:size(1)
stride[1] = 0
end
self.gradInput:resizeAs(gradOutput):copy(gradOutput)
self.gradInput:mul(1/input:size(self.dimension))
self.gradInput:resize(torch.LongStorage(size), torch.LongStorage(stride))
return self.gradInput
end
|
local Mean, parent = torch.class('nn.Mean', 'nn.Module')
function Mean:__init(dimension)
parent.__init(self)
dimension = dimension or 1
self.dimension = dimension
self._gradInput = torch.Tensor()
end
function Mean:updateOutput(input)
self.output:mean(input, self.dimension)
if self.output:nDimension() > 1 then
self.output = self.output:select(self.dimension, 1)
end
return self.output
end
function Mean:updateGradInput(input, gradOutput)
self._gradInput:resizeAs(gradOutput):copy(gradOutput)
self._gradInput:mul(1/input:size(self.dimension))
if input:nDimension() > 1 then
self._gradInput = nn.utils.addSingletonDimension(self._gradInput,
self.dimension)
end
self.gradInput = self._gradInput:expandAs(input)
return self.gradInput
end
|
Fix contiguous output bug in nn.Mean
|
Fix contiguous output bug in nn.Mean
|
Lua
|
bsd-3-clause
|
nicholas-leonard/nn,rotmanmi/nn,douwekiela/nn,kmul00/nn,elbamos/nn,witgo/nn,lukasc-ch/nn,bartvm/nn,xianjiec/nn,eulerreich/nn,Moodstocks/nn,Djabbz/nn,vgire/nn,apaszke/nn,abeschneider/nn,lvdmaaten/nn,noa/nn,EnjoyHacking/nn,diz-vara/nn,PraveerSINGH/nn,PierrotLC/nn,zhangxiangxiao/nn,davidBelanger/nn,Aysegul/nn,eriche2016/nn,jonathantompson/nn,forty-2/nn,jhjin/nn,jzbontar/nn,colesbury/nn,adamlerer/nn,sbodenstein/nn,sagarwaghmare69/nn,ominux/nn,ivendrov/nn,joeyhng/nn,LinusU/nn,andreaskoepf/nn,GregSatre/nn,Jeffyrao/nn,caldweln/nn,mlosch/nn,clementfarabet/nn
|
0493d7adca89ebe73fafc6b209eb7cb9e7dee5f9
|
Ndex.lua
|
Ndex.lua
|
--[[
This module prints an entry in a list of Pokémon.
The interface allow for printing from WikiCode, and expose the class for other
modules to use it.
Example call from WikiCode:
{{#invoke: ndex | list | 396 397 398 487 487O 422E | color = alola }}
Takes a list of space separated ndexes and print the relative entries. The
color argument specify the color of the background (a name from modulo colore).
The other interface prints only the header, with the color specified:
{{#invoke: ndex | header | sinnoh }}
--]]
local n = {}
local txt = require('Wikilib-strings') -- luacheck: no unused
local tab = require('Wikilib-tables') -- luacheck: no unused
local w = require('Wikilib')
local form = require('Wikilib-forms')
local oop = require('Wikilib-oop')
local lists = require('Wikilib-lists')
local multigen = require('Wikilib-multigen')
local box = require('Box')
local ms = require('MiniSprite')
local css = require('Css')
local pokes = require('Poké-data')
local formsData = form.allFormsData()
-- Loads also useless forms because there can be entries for useless forms
form.loadUseless(true)
local alts = form.allFormsData()
--[[
This class holds data about name, ndex, types and form of a Pokémon. It also
support useless forms.
--]]
n.Entry = oop.makeClass(lists.PokeLabelledEntry)
n.Entry.strings = {
ENTRY = string.gsub([=[
<div class="inline-block width-xl-33 width-md-50 width-sm-100" style="padding: 0.2em 0.3em;">
<div class="roundy white-bg height-100 vert-middle" style="padding-right: 0.2em; padding-top: 0.1em;"><!--
--><div class="width-xl-15" style="padding: 0.3ex;">#${ndex}</div><!--
--><div class="width-xl-20" style="padding: 0.3ex;">${ms}</div><!--
--><div class="text-center width-xl-35" style="padding: 0.3ex;">[[${name}]]${form}</div><!--
--><div class="width-xl-30" style="padding: 0.3ex;">${types}</div>
</div></div>]=], "<!%-%-\n%-%->", ""),
HEADER = [=[
<div class="roundy pull-center text-center flex-row-stretch-around flex-wrap width-xl-80 width-lg-100" style="${bg}">]=],
}
n.Entry.new = function(pokedata, name)
local this = n.Entry.super.new(name, pokedata.ndex)
local baseName, abbr = form.getNameAbbr(name)
if alts[baseName] then
-- Table.copy because alts is mw.loadData, so mw.clone doesn't work
this.formsData = table.copy(alts[baseName])
this.formAbbr = abbr
end
if this.labels[1] == "" then
this.labels[1] = nil
end
return setmetatable(table.merge(this, pokedata), n.Entry)
end
-- WikiCode for an entry: card layout with all the informations on one line.
n.Entry.__tostring = function(this)
local formtag = ""
if this.labels[1] then
formtag = this.labels[1] == 'Tutte le forme'
and '<div class="small-text">Tutte le forme</div>'
or this.formsData.links[this.formAbbr]
end
local type1 = multigen.getGenValue(this.type1)
local type2 = multigen.getGenValue(this.type2)
local types = type2 == type1 and { type1 }
or { type1, type2 }
return string.interp(n.Entry.strings.ENTRY, {
ndex = this.ndex and string.tf(this.ndex) or '???',
ms = ms.staticLua(string.tf(this.ndex or 0)
.. form.toEmptyAbbr(this.formAbbr or '')),
name = this.name,
form = formtag,
types = box.listTipoLua(table.concat(types, ", "), "thin",
"width-xl-100", "margin: 0 0.2ex 0.2ex 0;"),
})
end
-- ================================== Header ==================================
n.headerLua = function(color)
return string.interp(n.Entry.strings.HEADER, {
bg = css.horizGradLua{type = color or 'pcwiki'},
})
end
n.header = function(frame)
return n.headerLua(string.trim(frame.args[1]))
end
--[[
WikiCode interface, to print a list of entries.
--]]
n.list = function(frame)
local ndexlist = frame.args[1]
local res = { n.headerLua(string.trim(frame.args.color)) }
for ndex in ndexlist:gmatch("[^ ]+") do
local baseName, _ = form.getNameAbbr(ndex)
table.insert(res, tostring(n.Entry.new(pokes[ndex]
or pokes[baseName], ndex)))
end
table.insert(res, "</div>")
return table.concat(res)
end
n.List = n.list
-- =============================== Manual entry ===============================
n.manualEntry = function(frame)
local p = w.trimAll(frame.args)
local ndex, abbr = form.getNameAbbr(p[1])
-- print(ndex, abbr)
local name = string.fu(p[2])
-- print(formsData[ndex])
local formtag = formsData[ndex] and formsData[ndex].links[abbr] or ''
local types = { p.type1, p.type2 }
local msidx
if not tonumber(ndex) then
ndex = '???'
msidx = ndex
else
msidx = ndex .. abbr
end
return string.interp(n.Entry.strings.ENTRY, {
ndex = ndex,
ms = ms.staticLua(msidx),
name = name,
form = formtag,
types = box.listTipoLua(table.concat(types, ", "), "thin",
"width-xl-100", "margin: 0 0.2ex 0.2ex 0;"),
})
end
return n
|
--[[
This module prints an entry in a list of Pokémon.
The interface allow for printing from WikiCode, and expose the class for other
modules to use it.
Example call from WikiCode:
{{#invoke: ndex | list | 396 397 398 487 487O 422E | color = alola }}
Takes a list of space separated ndexes and print the relative entries. The
color argument specify the color of the background (a name from modulo colore).
The other interface prints only the header, with the color specified:
{{#invoke: ndex | header | sinnoh }}
--]]
local n = {}
local txt = require('Wikilib-strings') -- luacheck: no unused
local tab = require('Wikilib-tables') -- luacheck: no unused
local w = require('Wikilib')
local form = require('Wikilib-forms')
local oop = require('Wikilib-oop')
local lists = require('Wikilib-lists')
local multigen = require('Wikilib-multigen')
local box = require('Box')
local ms = require('MiniSprite')
local css = require('Css')
local pokes = require('Poké-data')
local formsData = form.allFormsData()
-- Loads also useless forms because there can be entries for useless forms
form.loadUseless(true)
local alts = form.allFormsData()
--[[
This class holds data about name, ndex, types and form of a Pokémon. It also
support useless forms.
--]]
n.Entry = oop.makeClass(lists.PokeLabelledEntry)
n.Entry.strings = {
ENTRY = string.gsub([=[
<div class="width-xl-33 width-md-50 width-sm-100" style="padding: 0.2em;">
<div class="flex flex-row flex-wrap flex-items-center flex-main-stretch roundy white-bg height-100 vert-middle" style="padding-right: 0.2em; padding-top: 0.1em;"><!--
--><div class="width-xl-15" style="padding: 0.3ex;">#${ndex}</div><!--
--><div class="width-xl-15">${ms}</div><!--
--><div class="text-center width-xl-30" style="padding: 0.3ex;">[[${name}]]${form}</div><!--
--><div class="width-xl-30" style="padding: 0.3ex;">${types}</div>
</div></div>]=], "<!%-%-\n%-%->", ""),
HEADER = [=[
<div class="roundy pull-center text-center flex flex-row flex-wrap flex-items-stretch flex-main-space-evenly width-xl-100" style="${bg}; padding: 0.2em;">]=],
}
n.Entry.new = function(pokedata, name)
local this = n.Entry.super.new(name, pokedata.ndex)
local baseName, abbr = form.getNameAbbr(name)
if alts[baseName] then
-- Table.copy because alts is mw.loadData, so mw.clone doesn't work
this.formsData = table.copy(alts[baseName])
this.formAbbr = abbr
end
if this.labels[1] == "" then
this.labels[1] = nil
end
return setmetatable(table.merge(this, pokedata), n.Entry)
end
-- WikiCode for an entry: card layout with all the informations on one line.
n.Entry.__tostring = function(this)
local formtag = ""
if this.labels[1] then
formtag = this.labels[1] == 'Tutte le forme'
and '<div class="small-text">Tutte le forme</div>'
or this.formsData.links[this.formAbbr]
end
local type1 = multigen.getGenValue(this.type1)
local type2 = multigen.getGenValue(this.type2)
local types = type2 == type1 and { type1 }
or { type1, type2 }
return string.interp(n.Entry.strings.ENTRY, {
ndex = this.ndex and string.tf(this.ndex) or '???',
ms = ms.staticLua(string.tf(this.ndex or 0)
.. form.toEmptyAbbr(this.formAbbr or '')),
name = this.name,
form = formtag,
types = box.listTipoLua(table.concat(types, ", "), "thin",
"width-xl-100", "margin: 0 0.2ex 0.2ex 0;"),
})
end
-- ================================== Header ==================================
n.headerLua = function(color)
return string.interp(n.Entry.strings.HEADER, {
bg = css.horizGradLua{type = color or 'pcwiki'},
})
end
n.header = function(frame)
return n.headerLua(string.trim(frame.args[1]))
end
--[[
WikiCode interface, to print a list of entries.
--]]
n.list = function(frame)
local ndexlist = frame.args[1]
local res = { n.headerLua(string.trim(frame.args.color)) }
for ndex in ndexlist:gmatch("[^ ]+") do
local baseName, _ = form.getNameAbbr(ndex)
table.insert(res, tostring(n.Entry.new(pokes[ndex]
or pokes[baseName], ndex)))
end
table.insert(res, "</div>")
return table.concat(res)
end
n.List = n.list
-- =============================== Manual entry ===============================
n.manualEntry = function(frame)
local p = w.trimAll(frame.args)
local ndex, abbr = form.getNameAbbr(p[1])
-- print(ndex, abbr)
local name = string.fu(p[2])
-- print(formsData[ndex])
local formtag = formsData[ndex] and formsData[ndex].links[abbr] or ''
local types = { p.type1, p.type2 }
local msidx
if not tonumber(ndex) then
ndex = '???'
msidx = ndex
else
msidx = ndex .. abbr
end
return string.interp(n.Entry.strings.ENTRY, {
ndex = ndex,
ms = ms.staticLua(msidx),
name = name,
form = formtag,
types = box.listTipoLua(table.concat(types, ", "), "thin",
"width-xl-100", "margin: 0 0.2ex 0.2ex 0;"),
})
end
return n
|
Fixes and improvements to layout
|
Fixes and improvements to layout
|
Lua
|
cc0-1.0
|
pokemoncentral/wiki-lua-modules
|
8fdb3961907a79c9e8101442238739f4a86b9b3c
|
examples/cookie.lua
|
examples/cookie.lua
|
--- Turbo.lua Cookie usage example
--
-- Copyright 2013 John Abrahamsen
--
-- 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 turbo = require "turbo"
local CookieHandler = class("CookieHandler", turbo.web.RequestHandler)
function CookieHandler:get()
local counter = self:get_cookie("counter")
local new_count = counter and tonumber(counter) + 1 or 0
self:set_cookie("id", "supersecretrandomid!") -- Set cookie for one year.
self:write("Cookie counter is at: " .. new_count)
self:set_cookie("counter", new_count)
end
turbo.web.Application({{"^/$", CookieHandler}}):listen(8888)
turbo.ioloop.instance():start()
|
--- Turbo.lua Cookie usage example
--
-- Copyright 2013 John Abrahamsen
--
-- 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 turbo = require "turbo"
local CookieHandler = class("CookieHandler", turbo.web.RequestHandler)
function CookieHandler:get()
local counter = self:get_cookie("counter")
local new_count = counter and tonumber(counter) + 1 or 0
self:set_cookie("counter", new_count)
self:write("Cookie counter is at: " .. new_count)
end
turbo.web.Application({{"^/$", CookieHandler}}):listen(8888)
turbo.ioloop.instance():start()
|
Fixed cookie counter example.
|
Fixed cookie counter example.
|
Lua
|
apache-2.0
|
mniestroj/turbo,kernelsauce/turbo,YuanPeir-Chen/turbo-support-mipsel,luastoned/turbo,zcsteele/turbo,ddysher/turbo,YuanPeir-Chen/turbo-support-mipsel,zcsteele/turbo,luastoned/turbo,ddysher/turbo
|
874b1ae326c146da1743c2975bddfea4767ef701
|
mods/beds/api.lua
|
mods/beds/api.lua
|
local reverse = true
local function destruct_bed(pos, n)
local node = minetest.get_node(pos)
local other
if n == 2 then
local dir = minetest.facedir_to_dir(node.param2)
other = vector.subtract(pos, dir)
elseif n == 1 then
local dir = minetest.facedir_to_dir(node.param2)
other = vector.add(pos, dir)
end
if reverse then
reverse = not reverse
minetest.remove_node(other)
nodeupdate(other)
else
reverse = not reverse
end
end
function beds.register_bed(name, def)
minetest.register_node(name .. "_bottom", {
description = def.description,
inventory_image = def.inventory_image,
wield_image = def.wield_image,
drawtype = "nodebox",
tiles = def.tiles.bottom,
paramtype = "light",
paramtype2 = "facedir",
is_ground_content = false,
stack_max = 1,
groups = {snappy = 1, choppy = 2, oddly_breakable_by_hand = 2, flammable = 3, bed = 1},
sounds = default.node_sound_wood_defaults(),
node_box = {
type = "fixed",
fixed = def.nodebox.bottom,
},
selection_box = {
type = "fixed",
fixed = def.selectionbox,
},
on_place = function(itemstack, placer, pointed_thing)
local under = pointed_thing.under
local pos
if minetest.registered_items[minetest.get_node(under).name].buildable_to then
pos = under
else
pos = pointed_thing.above
end
if minetest.is_protected(pos, placer:get_player_name()) and
not minetest.check_player_privs(placer, "protection_bypass") then
minetest.record_protection_violation(pos, placer:get_player_name())
return itemstack
end
local dir = minetest.dir_to_facedir(placer:get_look_dir())
local botpos = vector.add(pos, minetest.facedir_to_dir(dir))
if minetest.is_protected(botpos, placer:get_player_name()) and
not minetest.check_player_privs(placer, "protection_bypass") then
minetest.record_protection_violation(botpos, placer:get_player_name())
return itemstack
end
if not minetest.registered_nodes[minetest.get_node(botpos).name].buildable_to then
return itemstack
end
minetest.set_node(pos, {name = name .. "_bottom", param2 = dir})
minetest.set_node(botpos, {name = name .. "_top", param2 = dir})
if not minetest.setting_getbool("creative_mode") then
itemstack:take_item()
end
return itemstack
end,
on_destruct = function(pos)
destruct_bed(pos, 1)
end,
on_rightclick = function(pos, node, clicker)
beds.on_rightclick(pos, clicker)
end,
on_rotate = function(pos, node, user, mode, new_param2)
local dir = minetest.facedir_to_dir(node.param2)
local p = vector.add(pos, dir)
local node2 = minetest.get_node_or_nil(p)
if not node2 or not minetest.get_item_group(node2.name, "bed") == 2 or
not node.param2 == node2.param2 then
return false
end
if minetest.is_protected(p, user:get_player_name()) then
minetest.record_protection_violation(p, user:get_player_name())
return false
end
if mode ~= screwdriver.ROTATE_FACE then
return false
end
local newp = vector.add(pos, minetest.facedir_to_dir(new_param2))
local node3 = minetest.get_node_or_nil(newp)
local def = node3 and minetest.registered_nodes[node3.name]
if not def or not def.buildable_to then
return false
end
if minetest.is_protected(newp, user:get_player_name()) then
minetest.record_protection_violation(newp, user:get_player_name())
return false
end
node.param2 = new_param2
-- do not remove_node here - it will trigger destroy_bed()
minetest.set_node(p, {name = "air"})
minetest.set_node(pos, node)
minetest.set_node(newp, {name = name .. "_top", param2 = new_param2})
return true
end,
})
minetest.register_node(name .. "_top", {
drawtype = "nodebox",
tiles = def.tiles.top,
paramtype = "light",
paramtype2 = "facedir",
is_ground_content = false,
pointable = false,
groups = {snappy = 1, choppy = 2, oddly_breakable_by_hand = 2, flammable = 3, bed = 2},
sounds = default.node_sound_wood_defaults(),
drop = name .. "_bottom",
node_box = {
type = "fixed",
fixed = def.nodebox.top,
},
on_destruct = function(pos)
destruct_bed(pos, 2)
end,
})
minetest.register_alias(name, name .. "_bottom")
minetest.register_craft({
output = name,
recipe = def.recipe
})
end
|
local reverse = true
local function destruct_bed(pos, n)
local node = minetest.get_node(pos)
local other
if n == 2 then
local dir = minetest.facedir_to_dir(node.param2)
other = vector.subtract(pos, dir)
elseif n == 1 then
local dir = minetest.facedir_to_dir(node.param2)
other = vector.add(pos, dir)
end
if reverse then
reverse = not reverse
minetest.remove_node(other)
nodeupdate(other)
else
reverse = not reverse
end
end
function beds.register_bed(name, def)
minetest.register_node(name .. "_bottom", {
description = def.description,
inventory_image = def.inventory_image,
wield_image = def.wield_image,
drawtype = "nodebox",
tiles = def.tiles.bottom,
paramtype = "light",
paramtype2 = "facedir",
is_ground_content = false,
stack_max = 1,
groups = {snappy = 1, choppy = 2, oddly_breakable_by_hand = 2, flammable = 3, bed = 1},
sounds = default.node_sound_wood_defaults(),
node_box = {
type = "fixed",
fixed = def.nodebox.bottom,
},
selection_box = {
type = "fixed",
fixed = def.selectionbox,
},
on_place = function(itemstack, placer, pointed_thing)
local under = pointed_thing.under
local pos
if minetest.registered_items[minetest.get_node(under).name].buildable_to then
pos = under
else
pos = pointed_thing.above
end
if minetest.is_protected(pos, placer:get_player_name()) and
not minetest.check_player_privs(placer, "protection_bypass") then
minetest.record_protection_violation(pos, placer:get_player_name())
return itemstack
end
local def = minetest.registered_nodes[minetest.get_node(pos).name]
if not def or not def.buildable_to then
return itemstack
end
local dir = minetest.dir_to_facedir(placer:get_look_dir())
local botpos = vector.add(pos, minetest.facedir_to_dir(dir))
if minetest.is_protected(botpos, placer:get_player_name()) and
not minetest.check_player_privs(placer, "protection_bypass") then
minetest.record_protection_violation(botpos, placer:get_player_name())
return itemstack
end
local botdef = minetest.registered_nodes[minetest.get_node(botpos).name]
if not botdef or not botdef.buildable_to then
return itemstack
end
minetest.set_node(pos, {name = name .. "_bottom", param2 = dir})
minetest.set_node(botpos, {name = name .. "_top", param2 = dir})
if not minetest.setting_getbool("creative_mode") then
itemstack:take_item()
end
return itemstack
end,
on_destruct = function(pos)
destruct_bed(pos, 1)
end,
on_rightclick = function(pos, node, clicker)
beds.on_rightclick(pos, clicker)
end,
on_rotate = function(pos, node, user, mode, new_param2)
local dir = minetest.facedir_to_dir(node.param2)
local p = vector.add(pos, dir)
local node2 = minetest.get_node_or_nil(p)
if not node2 or not minetest.get_item_group(node2.name, "bed") == 2 or
not node.param2 == node2.param2 then
return false
end
if minetest.is_protected(p, user:get_player_name()) then
minetest.record_protection_violation(p, user:get_player_name())
return false
end
if mode ~= screwdriver.ROTATE_FACE then
return false
end
local newp = vector.add(pos, minetest.facedir_to_dir(new_param2))
local node3 = minetest.get_node_or_nil(newp)
local def = node3 and minetest.registered_nodes[node3.name]
if not def or not def.buildable_to then
return false
end
if minetest.is_protected(newp, user:get_player_name()) then
minetest.record_protection_violation(newp, user:get_player_name())
return false
end
node.param2 = new_param2
-- do not remove_node here - it will trigger destroy_bed()
minetest.set_node(p, {name = "air"})
minetest.set_node(pos, node)
minetest.set_node(newp, {name = name .. "_top", param2 = new_param2})
return true
end,
})
minetest.register_node(name .. "_top", {
drawtype = "nodebox",
tiles = def.tiles.top,
paramtype = "light",
paramtype2 = "facedir",
is_ground_content = false,
pointable = false,
groups = {snappy = 1, choppy = 2, oddly_breakable_by_hand = 2, flammable = 3, bed = 2},
sounds = default.node_sound_wood_defaults(),
drop = name .. "_bottom",
node_box = {
type = "fixed",
fixed = def.nodebox.top,
},
on_destruct = function(pos)
destruct_bed(pos, 2)
end,
})
minetest.register_alias(name, name .. "_bottom")
minetest.register_craft({
output = name,
recipe = def.recipe
})
end
|
Beds: Check for buildable_to for bottom half
|
Beds: Check for buildable_to for bottom half
We properly checked top half already, just not the top half
target location.
Assure both checked positions are not unknown nodes.
Fixes #991
|
Lua
|
lgpl-2.1
|
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
|
73e58cec5b6b1f7a5c86b693430bf58cde6a8cda
|
src/c3_spec.lua
|
src/c3_spec.lua
|
require "busted.runner" ()
local assert = require "luassert"
describe ("c3 algorithm implementation", function ()
it ("can be required", function()
assert.has.no.errors (function ()
require "c3"
end)
end)
it ("can be instantiated", function ()
assert.has.no.error (function ()
local C3 = require "c3"
C3 {
superclass = function (x) return x end,
}
end)
end)
it ("detects non-callable superclass", function ()
assert.has.error (function ()
local C3 = require "c3"
C3 {
superclass = true,
}
end)
end)
it ("linearizes correctly a hierarchy", function ()
local C3 = require "c3"
local c3 = C3 {
superclass = function (x) return x end,
}
local o = {}
local a = { o, }
local b = { o, }
local c = { o, }
local d = { o, }
local e = { o, }
local k1 = { c, b, a, }
local k2 = { e, b, d, }
local k3 = { d, a, }
local z = { k3, k2, k1, }
assert.are.same (c3 (o ), { o, })
assert.are.same (c3 (a ), { o, a, })
assert.are.same (c3 (b ), { o, b, })
assert.are.same (c3 (c ), { o, c, })
assert.are.same (c3 (d ), { o, d, })
assert.are.same (c3 (e ), { o, e, })
assert.are.same (c3 (k1), { o, c, b, a, k1, })
assert.are.same (c3 (k2), { o, e, b, d, k2, })
assert.are.same (c3 (k3), { o, a, d, k3, })
assert.are.same (c3 (z ), { o, e, c, b, a, d, k3, k2, k1, z, })
end)
it ("handles cycles", function ()
local C3 = require "c3"
local c3 = C3 {
superclass = function (x) return x end,
}
local a, b = {}, {}
a [1] = b
b [1] = a
assert.are.same (c3 (a), { b, a, })
assert.are.same (c3 (b), { a, b, })
end)
it ("reports an error when linearization is not possible", function ()
local C3 = require "c3"
local c3 = C3 {
superclass = function (x) return x end,
}
local a, b = {}, {}
a [1] = b
b [1] = a
local c = { a, b, }
local ok, err = pcall (c3, c)
assert.is_falsy (ok)
assert.is_truthy (type (err) == "table")
assert.are.equal (#err.graphs, 1)
end)
it ("allows to clear the cache", function ()
assert.has.no.error (function ()
local C3 = require "c3"
local c3 = C3 {
superclass = function (x) return x end,
}
c3:clear ()
end)
end)
end)
|
require "busted.runner" ()
local assert = require "luassert"
describe ("c3 algorithm implementation", function ()
it ("can be required", function()
assert.has.no.errors (function ()
require "c3"
end)
end)
it ("can be instantiated", function ()
assert.has.no.error (function ()
local C3 = require "c3"
C3 {
superclass = function (x) return x end,
}
end)
end)
it ("detects non-callable superclass", function ()
assert.has.error (function ()
local C3 = require "c3"
C3 {
superclass = true,
}
end)
end)
it ("linearizes correctly a hierarchy", function ()
local C3 = require "c3"
local c3 = C3 {
superclass = function (x) return x end,
}
local o = {}
local a = { o, }
local b = { o, }
local c = { o, }
local d = { o, }
local e = { o, }
local k1 = { c, b, a, }
local k2 = { e, b, d, }
local k3 = { d, a, }
local z = { k3, k2, k1, }
assert.are.same (c3 (o ), { o, })
assert.are.same (c3 (a ), { o, a, })
assert.are.same (c3 (b ), { o, b, })
assert.are.same (c3 (c ), { o, c, })
assert.are.same (c3 (d ), { o, d, })
assert.are.same (c3 (e ), { o, e, })
assert.are.same (c3 (k1), { o, c, b, a, k1, })
assert.are.same (c3 (k2), { o, e, b, d, k2, })
assert.are.same (c3 (k3), { o, a, d, k3, })
assert.are.same (c3 (z ), { o, e, c, b, a, d, k3, k2, k1, z, })
end)
it ("handles cycles", function ()
local C3 = require "c3"
local c3 = C3 {
superclass = function (x) return x end,
}
local a, b = {}, {}
a [1] = b
b [1] = a
assert.are.same (c3 (a), { b, a, })
assert.are.same (c3 (b), { a, b, })
end)
it ("reports an error when linearization is not possible", function ()
local C3 = require "c3"
local c3 = C3 {
superclass = function (x) return x end,
}
local a, b = {}, {}
a [1] = b
b [1] = a
local c = { a, b, }
local ok, err = pcall (c3, c)
assert.is_falsy (ok)
assert.is_truthy (type (err) == "table")
end)
it ("allows to clear the cache", function ()
assert.has.no.error (function ()
local C3 = require "c3"
local c3 = C3 {
superclass = function (x) return x end,
}
c3:clear ()
end)
end)
end)
|
Fix test.
|
Fix test.
|
Lua
|
mit
|
saucisson/lua-c3
|
9309f35b4ace90f893a52e62bde0b6eb2e6cf83e
|
src/lib/cltable.lua
|
src/lib/cltable.lua
|
module(..., package.seeall)
local ffi = require("ffi")
local ctable = require("lib.ctable")
function build(keys, values)
return setmetatable({ keys = keys, values = values },
{__index=get, __newindex=set})
end
function new(params)
local ctable_params = {}
for k,v in _G.pairs(params) do ctable_params[k] = v end
assert(not ctable_params.value_type)
ctable_params.value_type = ffi.typeof('uint32_t')
return build(ctable.new(ctable_params), {})
end
function get(cltable, key)
local entry = cltable.keys:lookup_ptr(key)
if not entry then return nil end
return cltable.values[entry.value]
end
function set(cltable, key, value)
local entry = cltable.keys:lookup_ptr(key)
if entry then
cltable.values[entry.value] = value
if value ~= nil then
cltable.keys:remove_ptr(entry)
-- FIXME: Leaking the slot in the values array.
end
elseif value ~= nil then
table.insert(cltable.values, value)
cltable.keys:add(key, #cltable.values)
end
end
function pairs(cltable)
local ctable_next, ctable_max, ctable_entry = cltable.keys:iterate()
return function()
ctable_entry = ctable_next(ctable_max, ctable_entry)
if not ctable_entry then return end
return ctable_entry.key, cltable.values[ctable_entry.value]
end
end
function selftest()
print("selftest: cltable")
local ipv4 = require('lib.protocol.ipv4')
local params = { key_type = ffi.typeof('uint8_t[4]') }
local cltab = new(params)
for i=0,255 do
local addr = ipv4:pton('1.2.3.'..i)
cltab[addr] = 'hello, '..i
end
for i=0,255 do
local addr = ipv4:pton('1.2.3.'..i)
assert(cltab[addr] == 'hello, '..i)
end
print("selftest: ok")
end
|
module(..., package.seeall)
local ffi = require("ffi")
local ctable = require("lib.ctable")
function build(keys, values)
return setmetatable({ keys = keys, values = values },
{__index=get, __newindex=set})
end
function new(params)
local ctable_params = {}
for k,v in _G.pairs(params) do ctable_params[k] = v end
assert(not ctable_params.value_type)
ctable_params.value_type = ffi.typeof('uint32_t')
return build(ctable.new(ctable_params), {})
end
function get(cltable, key)
local entry = cltable.keys:lookup_ptr(key)
if not entry then return nil end
return cltable.values[entry.value]
end
function set(cltable, key, value)
local entry = cltable.keys:lookup_ptr(key)
if entry then
cltable.values[entry.value] = value
if value == nil then cltable.keys:remove_ptr(entry) end
elseif value ~= nil then
table.insert(cltable.values, value)
cltable.keys:add(key, #cltable.values)
end
end
function pairs(cltable)
local ctable_next, ctable_max, ctable_entry = cltable.keys:iterate()
return function()
ctable_entry = ctable_next(ctable_max, ctable_entry)
if not ctable_entry then return end
return ctable_entry.key, cltable.values[ctable_entry.value]
end
end
function selftest()
print("selftest: cltable")
local ipv4 = require('lib.protocol.ipv4')
local params = { key_type = ffi.typeof('uint8_t[4]') }
local cltab = new(params)
for i=0,255 do
local addr = ipv4:pton('1.2.3.'..i)
cltab[addr] = 'hello, '..i
end
for i=0,255 do
local addr = ipv4:pton('1.2.3.'..i)
assert(cltab[addr] == 'hello, '..i)
end
for i=0,255 do
-- Remove value that is present.
cltab[ipv4:pton('1.2.3.'..i)] = nil
-- Remove value that is not present.
cltab[ipv4:pton('2.3.4.'..i)] = nil
end
print("selftest: ok")
end
|
Fix cltable removal bug and add tests
|
Fix cltable removal bug and add tests
|
Lua
|
apache-2.0
|
alexandergall/snabbswitch,Igalia/snabb,Igalia/snabb,dpino/snabbswitch,Igalia/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,heryii/snabb,dpino/snabbswitch,SnabbCo/snabbswitch,eugeneia/snabb,Igalia/snabbswitch,snabbco/snabb,eugeneia/snabb,Igalia/snabb,dpino/snabb,eugeneia/snabbswitch,eugeneia/snabb,alexandergall/snabbswitch,heryii/snabb,Igalia/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,dpino/snabbswitch,snabbco/snabb,eugeneia/snabb,heryii/snabb,eugeneia/snabb,SnabbCo/snabbswitch,heryii/snabb,dpino/snabb,eugeneia/snabbswitch,snabbco/snabb,snabbco/snabb,alexandergall/snabbswitch,eugeneia/snabb,snabbco/snabb,snabbco/snabb,dpino/snabb,Igalia/snabbswitch,eugeneia/snabb,dpino/snabbswitch,SnabbCo/snabbswitch,SnabbCo/snabbswitch,Igalia/snabbswitch,dpino/snabb,dpino/snabb,Igalia/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,snabbco/snabb,eugeneia/snabbswitch,eugeneia/snabb,eugeneia/snabbswitch,Igalia/snabb,heryii/snabb,dpino/snabb,Igalia/snabb,heryii/snabb,Igalia/snabb,dpino/snabb,alexandergall/snabbswitch
|
2b6bf1ae8c154b88d70860cb8b326dfef44d6fc8
|
src/hs/finalcutpro/main/LibrariesFilmstrip.lua
|
src/hs/finalcutpro/main/LibrariesFilmstrip.lua
|
local axutils = require("hs.finalcutpro.axutils")
local tools = require("hs.fcpxhacks.modules.tools")
local Filmstrip = {}
function Filmstrip.matches(element)
return element and element:attributeValue("AXIdentifier") == "_NS:33"
end
function Filmstrip:new(parent)
o = {_parent = parent}
setmetatable(o, self)
self.__index = self
return o
end
function Filmstrip:parent()
return self._parent
end
function Filmstrip:app()
return self:parent():app()
end
-----------------------------------------------------------------------
-----------------------------------------------------------------------
--- TIMELINE CONTENT UI
-----------------------------------------------------------------------
-----------------------------------------------------------------------
function Filmstrip:UI()
return axutils.cache(self, "_ui", function()
local main = self:parent():mainGroupUI()
if main then
for i,child in ipairs(main) do
if child:attributeValue("AXRole") == "AXGroup" and #child == 1 then
if Filmstrip.matches(child[1]) then
return child[1]
end
end
end
end
return nil
end,
Filmstrip.matches)
end
function Filmstrip:verticalScrollBarUI()
local ui = self:UI()
return ui and ui:attributeValue("AXVerticalScrollBar")
end
function Filmstrip:isShowing()
return self:UI() ~= nil
end
function Filmstrip:contentsUI()
local ui = self:UI()
return ui and ui:contents()[1]
end
function Filmstrip:clipsUI()
local ui = self:contentsUI()
if ui then
local clips = axutils.childrenWithRole(ui, "AXGroup")
if clips then
table.sort(clips,
function(a, b)
local aFrame = a:frame()
local bFrame = b:frame()
if aFrame.y < bFrame.y then -- a is above b
return true
elseif aFrame.y == bFrame.y then
if aFrame.x < bFrame.x then -- a is left of b
return true
elseif aFrame.x == bFrame.x
and aFrame.w < bFrame.w then -- a starts with but finishes before b, so b must be multi-line
return true
end
end
return false -- b is first
end
)
return clips
end
end
return nil
end
function Filmstrip:selectedClipsUI()
local ui = self:contentsUI()
return ui and ui:selectedChildren()
end
function Filmstrip:showClip(clipUI)
local ui = self:UI()
if ui then
local vScroll = self:verticalScrollBarUI()
local vFrame = vScroll:frame()
local clipFrame = clipUI:frame()
local top = vFrame.y
local bottom = vFrame.y + vFrame.h
local clipTop = clipFrame.y
local clipBottom = clipFrame.y + clipFrame.h
if clipTop < top or clipBottom > bottom then
-- we need to scroll
local oFrame = self:contentsUI():frame()
local scrollHeight = oFrame.h - vFrame.h
local vValue = nil
if clipTop < top or clipFrame.h > vFrame.h then
vValue = (clipTop-oFrame.y)/scrollHeight
else
vValue = 1.0 - (oFrame.y + oFrame.h - clipBottom)/scrollHeight
end
vScroll:setAttributeValue("AXValue", vValue)
end
end
return self
end
function Filmstrip:showClipAt(index)
local ui = self:clipsUI()
if ui and #ui >= index then
self:showClip(ui[index])
end
return self
end
function Filmstrip:selectClip(clipUI)
if clipUI then
clipUI:parent():setAttributeValue("AXSelectedChildren", { clipUI } )
end
return self
end
function Filmstrip:selectClipAt(index)
local ui = self:clipsUI()
if ui and #ui >= index then
self:selectClip(ui[index])
end
return self
end
function Filmstrip:selectAll(clipsUI)
clipsUI = clipsUI or self:clipsUI()
if clipsUI then
for i,clip in ipairs(clipsUI) do
self:selectClip(clip)
end
end
return self
end
function Filmstrip:deselectAll()
local contents = self:contentsUI()
if contents then
contents.setAttributeValue("AXSelectedChildren", {})
end
return self
end
return Filmstrip
|
local axutils = require("hs.finalcutpro.axutils")
local tools = require("hs.fcpxhacks.modules.tools")
local Filmstrip = {}
function Filmstrip.matches(element)
return element and element:attributeValue("AXIdentifier") == "_NS:33"
end
function Filmstrip:new(parent)
o = {_parent = parent}
setmetatable(o, self)
self.__index = self
return o
end
function Filmstrip:parent()
return self._parent
end
function Filmstrip:app()
return self:parent():app()
end
-----------------------------------------------------------------------
-----------------------------------------------------------------------
--- TIMELINE CONTENT UI
-----------------------------------------------------------------------
-----------------------------------------------------------------------
function Filmstrip:UI()
return axutils.cache(self, "_ui", function()
local main = self:parent():mainGroupUI()
if main then
for i,child in ipairs(main) do
if child:attributeValue("AXRole") == "AXGroup" and #child == 1 then
if Filmstrip.matches(child[1]) then
return child[1]
end
end
end
end
return nil
end,
Filmstrip.matches)
end
function Filmstrip:verticalScrollBarUI()
local ui = self:UI()
return ui and ui:attributeValue("AXVerticalScrollBar")
end
function Filmstrip:isShowing()
return self:UI() ~= nil
end
function Filmstrip:contentsUI()
local ui = self:UI()
return ui and ui:contents()[1]
end
function Filmstrip.sortClips(a, b)
local aFrame = a:frame()
local bFrame = b:frame()
if aFrame.y < bFrame.y then -- a is above b
return true
elseif aFrame.y == bFrame.y then
if aFrame.x < bFrame.x then -- a is left of b
return true
elseif aFrame.x == bFrame.x
and aFrame.w < bFrame.w then -- a starts with but finishes before b, so b must be multi-line
return true
end
end
return false -- b is first
end
function Filmstrip:clipsUI()
local ui = self:contentsUI()
if ui then
local clips = axutils.childrenWithRole(ui, "AXGroup")
if clips then
table.sort(clips, Filmstrip.sortClips)
return clips
end
end
return nil
end
function Filmstrip:selectedClipsUI()
local ui = self:contentsUI()
if ui then
local children = ui:selectedChildren()
local clips = {}
for i,child in ipairs(children) do
clips[i] = child
end
table.sort(clips, Filmstrip.sortClips)
return clips
end
return nil
end
function Filmstrip:showClip(clipUI)
local ui = self:UI()
if ui then
local vScroll = self:verticalScrollBarUI()
local vFrame = vScroll:frame()
local clipFrame = clipUI:frame()
local top = vFrame.y
local bottom = vFrame.y + vFrame.h
local clipTop = clipFrame.y
local clipBottom = clipFrame.y + clipFrame.h
if clipTop < top or clipBottom > bottom then
-- we need to scroll
local oFrame = self:contentsUI():frame()
local scrollHeight = oFrame.h - vFrame.h
local vValue = nil
if clipTop < top or clipFrame.h > vFrame.h then
vValue = (clipTop-oFrame.y)/scrollHeight
else
vValue = 1.0 - (oFrame.y + oFrame.h - clipBottom)/scrollHeight
end
vScroll:setAttributeValue("AXValue", vValue)
end
end
return self
end
function Filmstrip:showClipAt(index)
local ui = self:clipsUI()
if ui and #ui >= index then
self:showClip(ui[index])
end
return self
end
function Filmstrip:selectClip(clipUI)
if axutils.isValid(clipUI) then
clipUI:parent():setAttributeValue("AXSelectedChildren", { clipUI } )
end
return self
end
function Filmstrip:selectClipAt(index)
local ui = self:clipsUI()
if ui and #ui >= index then
self:selectClip(ui[index])
end
return self
end
function Filmstrip:selectAll(clipsUI)
clipsUI = clipsUI or self:clipsUI()
if clipsUI then
for i,clip in ipairs(clipsUI) do
self:selectClip(clip)
end
end
return self
end
function Filmstrip:deselectAll()
local contents = self:contentsUI()
if contents then
contents.setAttributeValue("AXSelectedChildren", {})
end
return self
end
return Filmstrip
|
#145 * Fixed bug with updateTitleList when the Libraries browser was in filmstrip mode.
|
#145
* Fixed bug with updateTitleList when the Libraries browser was in filmstrip mode.
|
Lua
|
mit
|
cailyoung/CommandPost,CommandPost/CommandPost,CommandPost/CommandPost,cailyoung/CommandPost,cailyoung/CommandPost,fcpxhacks/fcpxhacks,fcpxhacks/fcpxhacks,CommandPost/CommandPost
|
f0cc87bac9ad89d32d244bf7165f144836a47753
|
src/commands/fetch.lua
|
src/commands/fetch.lua
|
local fetch = {
func = function(msg)
local f = io.popen("git pull", "r")
local s = f:read("*a")
f:close()
if (s:find("Already up to date")) then
bot.sendMessage{
chat_id = msg.chat.id,
reply_to_message_id = msg.message_id,
text = "Already up to date."
}
else
local f = io.popen("git log -1", "r")
local s = f:read("*a")
f:close()
bot.sendMessage{
chat_id = msg.chat.id,
reply_to_message_id = msg.message_id,
text = "*[latest commit]*\n```\n" .. s .. "\n```",
parse_mode = "Markdown"
}
return commands.reload.func(msg)
end
end,
desc = "fetch latest code.",
limit = {
master = true
}
}
return fetch
|
local fetch = {
func = function(msg)
local f = io.popen("cd ~/small-r/Project-Small-R/ && git pull", "r")
local s = f:read("*a")
f:close()
if (s:find("Already up to date")) then
bot.sendMessage{
chat_id = msg.chat.id,
reply_to_message_id = msg.message_id,
text = "Already up to date."
}
else
local f = io.popen("cd ~/small-r/Project-Small-R/ && git log -1", "r")
local s = f:read("*a")
f:close()
bot.sendMessage{
chat_id = msg.chat.id,
reply_to_message_id = msg.message_id,
text = "*[latest commit]*\n```\n" .. s .. "\n```",
parse_mode = "Markdown"
}
return commands.reload.func(msg)
end
end,
desc = "fetch latest code.",
limit = {
master = true
}
}
return fetch
|
fix(fetch): modified work directory
|
fix(fetch): modified work directory
|
Lua
|
apache-2.0
|
SJoshua/Project-Small-R
|
0f8b5ce99eab563afea5e798083e27ce6639fdfc
|
extension/script/backend/worker/traceback.lua
|
extension/script/backend/worker/traceback.lua
|
local rdebug = require 'remotedebug.visitor'
local hookmgr = require 'remotedebug.hookmgr'
local source = require 'backend.worker.source'
local luaver = require 'backend.worker.luaver'
local fs = require 'backend.worker.filesystem'
local info = {}
local function shortsrc(source, maxlen)
maxlen = maxlen or 60
local type = source:sub(1,1)
if type == '=' then
if #source <= maxlen then
return source:sub(2)
else
return source:sub(2, maxlen)
end
elseif type == '@' then
if #source <= maxlen then
return source:sub(2)
else
return '...' .. source:sub(#source - maxlen + 5)
end
else
local nl = source:find '\n'
maxlen = maxlen - 15
if #source < maxlen and nl == nil then
return ('[string "%s"]'):format(source)
else
local n = #source
if nl ~= nil then
n = nl - 1
end
if n > maxlen then
n = maxlen
end
return ('[string "%s..."]'):format(source:sub(1, n))
end
end
end
local function getshortsrc(src)
if src.sourceReference then
local code = source.getCode(src.sourceReference)
return shortsrc(code)
elseif src.path then
return shortsrc('@' .. source.clientPath(src.path))
elseif src.skippath then
return shortsrc('@' .. source.clientPath(src.skippath))
elseif info.source:sub(1,1) == '=' then
return shortsrc(info.source)
else
-- TODO
return '<unknown>'
end
end
local function findfield(t, f, level, name)
local loct = rdebug.tablehashv(t, 5000)
for i = 1, #loct, 2 do
local key, value = loct[i], loct[i+1]
if rdebug.type(key) == 'string' then
local skey = rdebug.value(key)
if level ~= 0 or skey ~= '_G' then
local tvalue = rdebug.type(value)
if (tvalue == 'function' or tvalue == 'c function') and rdebug.value(value) == f then
return name and (name .. '.' .. skey) or skey
end
if level < 2 and tvalue == 'table' then
return findfield(value, f, level + 1, name and (name .. '.' .. skey) or skey)
end
end
end
end
end
local function pushglobalfuncname(f)
f = rdebug.value(f)
if f ~= nil then
return findfield(rdebug._G, f, 2)
end
end
local function pushfuncname(f, info)
local funcname = pushglobalfuncname(f)
if funcname then
return ("function '%s'"):format(funcname)
elseif info.namewhat ~= '' then
return ("%s '%s'"):format(info.namewhat, info.name)
elseif info.what == 'main' then
return 'main chunk'
elseif info.what ~= 'C' then
local src = source.create(info.source)
return ('function <%s:%d>'):format(getshortsrc(src), source.line(src, info.linedefined))
else
return '?'
end
end
local function replacewhere(msg)
local f, l = msg:find ':[-%d]+: '
if not f then
if rdebug.getinfo(1, "Sl", info) then
local src = source.create(info.source)
msg = ('%s:%d: %s'):format(getshortsrc(src), source.line(src, info.currentline), msg)
end
return msg, 0
end
local srcpath = fs.source_normalize(msg:sub(1, f-1))
local line = tonumber(msg:sub(f+1, l-2))
local message = msg:sub(l + 1)
if not rdebug.getinfo(1, "Sl", info) then
return ('%s:%d: %s'):format(source.clientPath(srcpath), line, message), 1
end
local src = source.create(info.source)
return ('%s:%d: %s'):format(getshortsrc(src), source.line(src, info.currentline), message), 1
end
return function(msg)
local s = {}
local message, level = replacewhere(msg)
s[#s + 1] = 'stack traceback:'
local last = hookmgr.stacklevel()
local n1 = ((last - level) > 21) and 10 or -1
local opt = luaver.LUAVERSION >= 52 and "Slnt" or "Sln"
local depth = level
while rdebug.getinfo(depth, opt, info) do
local f = rdebug.getfunc(depth)
depth = depth + 1
n1 = n1 - 1
if n1 == 1 then
s[#s + 1] = '\n\t...'
depth = last - 10
else
local src = source.create(info.source)
s[#s + 1] = ('\n\t%s:'):format(getshortsrc(src))
if info.currentline > 0 then
s[#s + 1] = ('%d:'):format(source.line(src, info.currentline))
end
s[#s + 1] = " in "
s[#s + 1] = pushfuncname(f, info)
if info.istailcall then
s[#s + 1] = '\n\t(...tail calls...)'
end
end
end
return message, table.concat(s), level
end
|
local rdebug = require 'remotedebug.visitor'
local hookmgr = require 'remotedebug.hookmgr'
local source = require 'backend.worker.source'
local luaver = require 'backend.worker.luaver'
local fs = require 'backend.worker.filesystem'
local info = {}
local function shortsrc(source, maxlen)
maxlen = maxlen or 60
local type = source:sub(1,1)
if type == '=' then
if #source <= maxlen then
return source:sub(2)
else
return source:sub(2, maxlen)
end
elseif type == '@' then
if #source <= maxlen then
return source:sub(2)
else
return '...' .. source:sub(#source - maxlen + 5)
end
else
local nl = source:find '\n'
maxlen = maxlen - 15
if #source < maxlen and nl == nil then
return ('[string "%s"]'):format(source)
else
local n = #source
if nl ~= nil then
n = nl - 1
end
if n > maxlen then
n = maxlen
end
return ('[string "%s..."]'):format(source:sub(1, n))
end
end
end
local function getshortsrc(src)
if src.sourceReference then
local code = source.getCode(src.sourceReference)
return shortsrc(code)
elseif src.path then
return shortsrc('@' .. source.clientPath(src.path))
elseif src.skippath then
return shortsrc('@' .. source.clientPath(src.skippath))
elseif info.source:sub(1,1) == '=' then
return shortsrc(info.source)
else
-- TODO
return '<unknown>'
end
end
local function findfield(t, f, level, name)
local loct = rdebug.tablehashv(t, 5000)
for i = 1, #loct, 2 do
local key, value = loct[i], loct[i+1]
if rdebug.type(key) == 'string' then
local skey = rdebug.value(key)
if level ~= 0 or skey ~= '_G' then
local tvalue = rdebug.type(value)
if (tvalue == 'function' or tvalue == 'c function') and rdebug.value(value) == f then
return name and (name .. '.' .. skey) or skey
end
if level < 2 and tvalue == 'table' then
return findfield(value, f, level + 1, name and (name .. '.' .. skey) or skey)
end
end
end
end
end
local function pushglobalfuncname(f)
f = rdebug.value(f)
if f ~= nil then
return findfield(rdebug._G, f, 2)
end
end
local function pushfuncname(f, info)
local funcname = pushglobalfuncname(f)
if funcname then
return ("function '%s'"):format(funcname)
elseif info.namewhat ~= '' then
return ("%s '%s'"):format(info.namewhat, info.name)
elseif info.what == 'main' then
return 'main chunk'
elseif info.what ~= 'C' then
local src = source.create(info.source)
return ('function <%s:%d>'):format(getshortsrc(src), source.line(src, info.linedefined))
else
return '?'
end
end
local function replacewhere(msg)
local f, l = msg:find ':[-%d]+: '
if not f then
if rdebug.getinfo(1, "Sl", info) then
local src = source.create(info.source)
msg = ('%s:%d: %s'):format(getshortsrc(src), source.line(src, info.currentline), msg)
end
return msg, 0
end
local srcpath = fs.source_normalize(msg:sub(1, f-1))
local line = tonumber(msg:sub(f+1, l-2))
local message = msg:sub(l + 1)
local level = 0
while true do
if not rdebug.getinfo(level, "Sl", info) then
return ('%s:%d: %s'):format(source.clientPath(srcpath), line, message), 0
end
if info.what ~= 'C' then
local src = source.create(info.source)
return ('%s:%d: %s'):format(getshortsrc(src), source.line(src, info.currentline), message), level
end
level = level + 1
end
end
return function(msg)
local s = {}
local message, level = replacewhere(msg)
s[#s + 1] = 'stack traceback:'
local last = hookmgr.stacklevel()
local n1 = ((last - level) > 21) and 10 or -1
local opt = luaver.LUAVERSION >= 52 and "Slnt" or "Sln"
local depth = level
while rdebug.getinfo(depth, opt, info) do
local f = rdebug.getfunc(depth)
depth = depth + 1
n1 = n1 - 1
if n1 == 1 then
s[#s + 1] = '\n\t...'
depth = last - 10
else
local src = source.create(info.source)
s[#s + 1] = ('\n\t%s:'):format(getshortsrc(src))
if info.currentline > 0 then
s[#s + 1] = ('%d:'):format(source.line(src, info.currentline))
end
s[#s + 1] = " in "
s[#s + 1] = pushfuncname(f, info)
if info.istailcall then
s[#s + 1] = '\n\t(...tail calls...)'
end
end
end
return message, table.concat(s), level
end
|
Fixes #109
|
Fixes #109
|
Lua
|
mit
|
actboy168/vscode-lua-debug,actboy168/vscode-lua-debug,actboy168/vscode-lua-debug
|
9c64da40cd781da9bdb09b4342ced12645e5db35
|
Hydra/API/hotkey.lua
|
Hydra/API/hotkey.lua
|
hotkey.keycodes = hotkey._cachekeycodes()
--- hotkey.bind(mods, key, fn) -> hotkey
--- Shortcut for: return hotkey.new(mods, key, fn):enable()
function hotkey.bind(...)
return hotkey.new(...):enable()
end
--- hotkey.disableall()
--- Disables all hotkeys; automatically called when user config reloads.
function hotkey.disableall()
local function ishotkey(hk) return type(hk) == "userdata" end
fnutils.each(fnutils.filter(hotkey._keys, ishotkey), hotkey.disable)
end
|
hotkey.keycodes = hotkey._cachekeycodes()
--- hotkey.bind(mods, key, pressedfn, releasedfn) -> hotkey
--- Shortcut for: return hotkey.new(mods, key, pressedfn, releasedfn):enable()
function hotkey.bind(...)
return hotkey.new(...):enable()
end
--- hotkey.disableall()
--- Disables all hotkeys; automatically called when user config reloads.
function hotkey.disableall()
local function ishotkey(hk) return type(hk) == "userdata" end
fnutils.each(fnutils.filter(hotkey._keys, ishotkey), hotkey.disable)
end
|
Fixed docs for hotkey:bind(...)
|
Fixed docs for hotkey:bind(...)
|
Lua
|
mit
|
wsmith323/hammerspoon,lowne/hammerspoon,Habbie/hammerspoon,trishume/hammerspoon,hypebeast/hammerspoon,knl/hammerspoon,nkgm/hammerspoon,latenitefilms/hammerspoon,knu/hammerspoon,zzamboni/hammerspoon,Habbie/hammerspoon,kkamdooong/hammerspoon,TimVonsee/hammerspoon,Hammerspoon/hammerspoon,ocurr/hammerspoon,nkgm/hammerspoon,dopcn/hammerspoon,dopcn/hammerspoon,wsmith323/hammerspoon,knl/hammerspoon,trishume/hammerspoon,emoses/hammerspoon,wvierber/hammerspoon,bradparks/hammerspoon,asmagill/hammerspoon,Habbie/hammerspoon,zzamboni/hammerspoon,bradparks/hammerspoon,dopcn/hammerspoon,Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,nkgm/hammerspoon,Hammerspoon/hammerspoon,knu/hammerspoon,zzamboni/hammerspoon,knl/hammerspoon,wsmith323/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon,ocurr/hammerspoon,lowne/hammerspoon,chrisjbray/hammerspoon,kkamdooong/hammerspoon,bradparks/hammerspoon,cmsj/hammerspoon,joehanchoi/hammerspoon,bradparks/hammerspoon,peterhajas/hammerspoon,emoses/hammerspoon,dopcn/hammerspoon,TimVonsee/hammerspoon,knu/hammerspoon,TimVonsee/hammerspoon,hypebeast/hammerspoon,hypebeast/hammerspoon,wsmith323/hammerspoon,latenitefilms/hammerspoon,Stimim/hammerspoon,heptal/hammerspoon,tmandry/hammerspoon,kkamdooong/hammerspoon,Stimim/hammerspoon,Hammerspoon/hammerspoon,wvierber/hammerspoon,Habbie/hammerspoon,Stimim/hammerspoon,latenitefilms/hammerspoon,knu/hammerspoon,knu/hammerspoon,zzamboni/hammerspoon,chrisjbray/hammerspoon,joehanchoi/hammerspoon,bradparks/hammerspoon,knl/hammerspoon,wvierber/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon,ocurr/hammerspoon,heptal/hammerspoon,joehanchoi/hammerspoon,CommandPost/CommandPost-App,Stimim/hammerspoon,junkblocker/hammerspoon,emoses/hammerspoon,tmandry/hammerspoon,cmsj/hammerspoon,peterhajas/hammerspoon,cmsj/hammerspoon,dopcn/hammerspoon,Hammerspoon/hammerspoon,tmandry/hammerspoon,peterhajas/hammerspoon,emoses/hammerspoon,cmsj/hammerspoon,hypebeast/hammerspoon,junkblocker/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,junkblocker/hammerspoon,junkblocker/hammerspoon,CommandPost/CommandPost-App,Stimim/hammerspoon,nkgm/hammerspoon,knl/hammerspoon,chrisjbray/hammerspoon,wsmith323/hammerspoon,CommandPost/CommandPost-App,emoses/hammerspoon,Habbie/hammerspoon,heptal/hammerspoon,latenitefilms/hammerspoon,chrisjbray/hammerspoon,heptal/hammerspoon,ocurr/hammerspoon,nkgm/hammerspoon,trishume/hammerspoon,wvierber/hammerspoon,asmagill/hammerspoon,chrisjbray/hammerspoon,lowne/hammerspoon,lowne/hammerspoon,wvierber/hammerspoon,heptal/hammerspoon,asmagill/hammerspoon,ocurr/hammerspoon,zzamboni/hammerspoon,knu/hammerspoon,lowne/hammerspoon,peterhajas/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,joehanchoi/hammerspoon,chrisjbray/hammerspoon,joehanchoi/hammerspoon,hypebeast/hammerspoon,TimVonsee/hammerspoon,cmsj/hammerspoon,zzamboni/hammerspoon,junkblocker/hammerspoon,kkamdooong/hammerspoon,kkamdooong/hammerspoon,TimVonsee/hammerspoon,peterhajas/hammerspoon,CommandPost/CommandPost-App
|
983d737dac425155e5cc4f2594e3e2e7a28ff845
|
mod_ircd/mod_ircd.lua
|
mod_ircd/mod_ircd.lua
|
local irc_listener = { default_port = 6667, default_mode = "*l" };
local sessions = {};
local commands = {};
local nicks = {};
local st = require "util.stanza";
local conference_server = module:get_option("conference_server") or "conference.jabber.org";
local function irc_close_session(session)
session.conn:close();
end
function irc_listener.onincoming(conn, data)
local session = sessions[conn];
if not session then
session = { conn = conn, host = module.host, reset_stream = function () end,
close = irc_close_session, log = logger.init("irc"..(conn.id or "1")),
roster = {} };
sessions[conn] = session;
function session.data(data)
module:log("debug", "Received: %s", data);
local command, args = data:match("^%s*([^ ]+) *(.*)%s*$");
if not command then
module:log("warn", "Invalid command: %s", data);
return;
end
command = command:upper();
module:log("debug", "Received command: %s", command);
if commands[command] then
local ret = commands[command](session, args);
if ret then
session.send(ret.."\r\n");
end
end
end
function session.send(data)
module:log("debug", "sending: %s", data);
return conn:write(data.."\r\n");
end
end
if data then
session.data(data);
end
end
function irc_listener.ondisconnect(conn, error)
module:log("debug", "Client disconnected");
sessions[conn] = nil;
end
function commands.NICK(session, nick)
nick = nick:match("^[%w_]+");
if nicks[nick] then
session.send(":"..session.host.." 433 * The nickname "..nick.." is already in use");
return;
end
nicks[nick] = session;
session.nick = nick;
session.full_jid = nick.."@"..module.host.."/ircd";
session.type = "c2s";
module:log("debug", "Client bound to %s", session.full_jid);
session.send(":"..session.host.." 001 "..session.nick.." :Welcome to XMPP via the "..session.host.." gateway "..session.nick);
end
local joined_mucs = {};
function commands.JOIN(session, channel)
if not joined_mucs[channel] then
joined_mucs[channel] = { occupants = {}, sessions = {} };
end
joined_mucs[channel].sessions[session] = true;
local join_stanza = st.presence({ from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick });
core_process_stanza(session, join_stanza);
session.send(":"..session.nick.." JOIN :"..channel);
session.send(":"..session.host.." 332 "..session.nick.." "..channel.." :Connection in progress...");
session.send(":"..session.host.." 353 "..session.nick.." = "..channel.." :"..session.nick);
session.send(":"..session.host.." 366 "..session.nick.." "..channel.." :End of /NAMES list.");
end
function commands.PART(session, channel)
local channel, part_message = channel:match("^([^:]+):?(.*)$");
channel = channel:match("^([%S]*)");
core_process_stanza(session, st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }:tag("status"):text(part_message));
session.send(":"..session.nick.." PART :"..channel);
end
function commands.PRIVMSG(session, message)
local who, message = message:match("^(%S+) :(.+)$");
if joined_mucs[who] then
core_process_stanza(session, st.message{to=who:gsub("^#", "").."@"..conference_server, type="groupchat"}:tag("body"):text(message));
end
end
function commands.PING(session, server)
session.send(":"..session.host..": PONG "..server);
end
function commands.WHO(session, channel)
if joined_mucs[channel] then
for nick in pairs(joined_mucs[channel].occupants) do
--n=MattJ 91.85.191.50 irc.freenode.net MattJ H :0 Matthew Wild
session.send(":"..session.host.." 352 "..session.nick.." "..channel.." "..nick.." "..nick.." "..session.host.." "..nick.." H :0 "..nick);
end
session.send(":"..session.host.." 315 "..session.nick.." "..channel.. " :End of /WHO list");
end
end
function commands.MODE(session, channel)
session.send(":"..session.host.." 324 "..session.nick.." "..channel.." +J");
end
--- Component (handle stanzas from the server for IRC clients)
function irc_component(origin, stanza)
local from, from_bare = stanza.attr.from, jid.bare(stanza.attr.from);
local from_node = "#"..jid.split(stanza.attr.from);
if joined_mucs[from_node] and from_bare == from then
-- From room itself
local joined_muc = joined_mucs[from_node];
if stanza.name == "message" then
local subject = stanza:get_child("subject");
if subject then
local subject_text = subject:get_text();
for session in pairs(joined_muc.sessions) do
session.send(":"..session.host.." 332 "..session.nick.." "..from_node.." :"..subject_text);
end
end
end
elseif joined_mucs[from_node] then
-- From room occupant
local joined_muc = joined_mucs[from_node];
local nick = select(3, jid.split(from)):gsub(" ", "_");
if stanza.name == "presence" then
local what;
if not stanza.attr.type then
if joined_muc.occupants[nick] then
return;
end
joined_muc.occupants[nick] = true;
what = "JOIN";
else
joined_muc.occupants[nick] = nil;
what = "PART";
end
for session in pairs(joined_muc.sessions) do
if nick ~= session.nick then
session.send(":"..nick.."!"..nick.." "..what.." :"..from_node);
end
end
elseif stanza.name == "message" then
local body = stanza:get_child("body");
body = body and body:get_text() or "";
local hasdelay = stanza:get_child("delay", "urn:xmpp:delay");
if body ~= "" then
for session in pairs(joined_muc.sessions) do
if nick ~= session.nick or hasdelay then
session.send(":"..nick.." PRIVMSG "..from_node.." :"..body);
end
end
end
end
end
end
require "core.componentmanager".register_component(module.host, irc_component);
prosody.events.add_handler("server-stopping", function (shutdown)
module:log("debug", "Closing IRC connections prior to shutdown");
for channel, joined_muc in pairs(joined_mucs) do
for session in pairs(joined_muc.sessions) do
core_process_stanza(session,
st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }
:tag("status")
:text("Connection closed: Server is shutting down"..(shutdown.reason and (": "..shutdown.reason) or "")));
session:close();
end
end
end);
require "net.connlisteners".register("irc", irc_listener);
require "net.connlisteners".start("irc", { port = module:get_option("port") });
|
local irc_listener = { default_port = 6667, default_mode = "*l" };
local sessions = {};
local commands = {};
local nicks = {};
local st = require "util.stanza";
local conference_server = module:get_option("conference_server") or "conference.jabber.org";
local function irc_close_session(session)
session.conn:close();
end
function irc_listener.onincoming(conn, data)
local session = sessions[conn];
if not session then
session = { conn = conn, host = module.host, reset_stream = function () end,
close = irc_close_session, log = logger.init("irc"..(conn.id or "1")),
roster = {} };
sessions[conn] = session;
function session.data(data)
module:log("debug", "Received: %s", data);
local command, args = data:match("^%s*([^ ]+) *(.*)%s*$");
if not command then
module:log("warn", "Invalid command: %s", data);
return;
end
command = command:upper();
module:log("debug", "Received command: %s", command);
if commands[command] then
local ret = commands[command](session, args);
if ret then
session.send(ret.."\r\n");
end
end
end
function session.send(data)
module:log("debug", "sending: %s", data);
return conn:write(data.."\r\n");
end
end
if data then
session.data(data);
end
end
function irc_listener.ondisconnect(conn, error)
module:log("debug", "Client disconnected");
sessions[conn] = nil;
end
function commands.NICK(session, nick)
nick = nick:match("^[%w_]+");
if nicks[nick] then
session.send(":"..session.host.." 433 * The nickname "..nick.." is already in use");
return;
end
nicks[nick] = session;
session.nick = nick;
session.full_jid = nick.."@"..module.host.."/ircd";
session.type = "c2s";
module:log("debug", "Client bound to %s", session.full_jid);
session.send(":"..session.host.." 001 "..session.nick.." :Welcome to XMPP via the "..session.host.." gateway "..session.nick);
end
local joined_mucs = {};
function commands.JOIN(session, channel)
if not joined_mucs[channel] then
joined_mucs[channel] = { occupants = {}, sessions = {} };
end
joined_mucs[channel].sessions[session] = true;
local join_stanza = st.presence({ from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick });
core_process_stanza(session, join_stanza);
session.send(":"..session.nick.." JOIN :"..channel);
session.send(":"..session.host.." 332 "..session.nick.." "..channel.." :Connection in progress...");
session.send(":"..session.host.." 353 "..session.nick.." = "..channel.." :"..session.nick);
session.send(":"..session.host.." 366 "..session.nick.." "..channel.." :End of /NAMES list.");
end
function commands.PART(session, channel)
local channel, part_message = channel:match("^([^:]+):?(.*)$");
channel = channel:match("^([%S]*)");
core_process_stanza(session, st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }:tag("status"):text(part_message));
session.send(":"..session.nick.." PART :"..channel);
end
function commands.PRIVMSG(session, message)
local who, message = message:match("^(%S+) :(.+)$");
if joined_mucs[who] then
core_process_stanza(session, st.message{to=who:gsub("^#", "").."@"..conference_server, type="groupchat"}:tag("body"):text(message));
end
end
function commands.PING(session, server)
session.send(":"..session.host..": PONG "..server);
end
function commands.WHO(session, channel)
if joined_mucs[channel] then
for nick in pairs(joined_mucs[channel].occupants) do
--n=MattJ 91.85.191.50 irc.freenode.net MattJ H :0 Matthew Wild
session.send(":"..session.host.." 352 "..session.nick.." "..channel.." "..nick.." "..nick.." "..session.host.." "..nick.." H :0 "..nick);
end
session.send(":"..session.host.." 315 "..session.nick.." "..channel.. " :End of /WHO list");
end
end
function commands.MODE(session, channel)
session.send(":"..session.host.." 324 "..session.nick.." "..channel.." +J");
end
--- Component (handle stanzas from the server for IRC clients)
function irc_component(origin, stanza)
local from, from_bare = stanza.attr.from, jid.bare(stanza.attr.from);
local from_node = "#"..jid.split(stanza.attr.from);
if joined_mucs[from_node] and from_bare == from then
-- From room itself
local joined_muc = joined_mucs[from_node];
if stanza.name == "message" then
local subject = stanza:get_child("subject");
subject = subject and (subject:get_text() or "");
if subject then
for session in pairs(joined_muc.sessions) do
session.send(":"..session.host.." 332 "..session.nick.." "..from_node.." :"..subject);
end
end
end
elseif joined_mucs[from_node] then
-- From room occupant
local joined_muc = joined_mucs[from_node];
local nick = select(3, jid.split(from)):gsub(" ", "_");
if stanza.name == "presence" then
local what;
if not stanza.attr.type then
if joined_muc.occupants[nick] then
return;
end
joined_muc.occupants[nick] = true;
what = "JOIN";
else
joined_muc.occupants[nick] = nil;
what = "PART";
end
for session in pairs(joined_muc.sessions) do
if nick ~= session.nick then
session.send(":"..nick.."!"..nick.." "..what.." :"..from_node);
end
end
elseif stanza.name == "message" then
local body = stanza:get_child("body");
body = body and body:get_text() or "";
local hasdelay = stanza:get_child("delay", "urn:xmpp:delay");
if body ~= "" then
for session in pairs(joined_muc.sessions) do
if nick ~= session.nick or hasdelay then
session.send(":"..nick.." PRIVMSG "..from_node.." :"..body);
end
end
end
end
end
end
require "core.componentmanager".register_component(module.host, irc_component);
prosody.events.add_handler("server-stopping", function (shutdown)
module:log("debug", "Closing IRC connections prior to shutdown");
for channel, joined_muc in pairs(joined_mucs) do
for session in pairs(joined_muc.sessions) do
core_process_stanza(session,
st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }
:tag("status")
:text("Connection closed: Server is shutting down"..(shutdown.reason and (": "..shutdown.reason) or "")));
session:close();
end
end
end);
require "net.connlisteners".register("irc", irc_listener);
require "net.connlisteners".start("irc", { port = module:get_option("port") });
|
mod_ircd: Fixed handling of empty <subject/> elements.
|
mod_ircd: Fixed handling of empty <subject/> elements.
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
487bc7383c0e241f05760cfd86566bea8ee15d67
|
build/scripts/tools/ndk_server.lua
|
build/scripts/tools/ndk_server.lua
|
TOOL.Name = "SDKServer"
TOOL.Directory = "../SDK"
TOOL.Kind = "Library"
TOOL.TargetDirectory = "../SDK/lib"
TOOL.Defines = {
"NDK_BUILD",
"NDK_SERVER"
}
TOOL.Includes = {
"../SDK/include",
"../SDK/src"
}
TOOL.Files = {
"../SDK/include/NDK/**.hpp",
"../SDK/include/NDK/**.inl",
"../SDK/src/NDK/**.hpp",
"../SDK/src/NDK/**.inl",
"../SDK/src/NDK/**.cpp"
}
-- Excludes client-only files
TOOL.FilesExcluded = {
"../SDK/**/CameraComponent.*",
"../SDK/**/Console.*",
"../SDK/**/GraphicsComponent.*",
"../SDK/**/LightComponent.*",
"../SDK/**/ListenerComponent.*",
"../SDK/**/ListenerSystem.*",
"../SDK/**/RenderSystem.*",
"../SDK/**/LuaBinding_Audio.*",
"../SDK/**/LuaBinding_Graphics.*",
"../SDK/**/LuaBinding_Renderer.*"
}
TOOL.Libraries = function()
local libraries = {}
for k,v in pairs(NazaraBuild.Modules) do
if (not v.ClientOnly) then
table.insert(libraries, "Nazara" .. v.Name)
end
end
return libraries
end
|
TOOL.Name = "SDKServer"
TOOL.Directory = "../SDK"
TOOL.Kind = "Library"
TOOL.TargetDirectory = "../SDK/lib"
TOOL.Defines = {
"NDK_BUILD",
"NDK_SERVER"
}
TOOL.Includes = {
"../SDK/include",
"../SDK/src"
}
TOOL.Files = {
"../SDK/include/NDK/**.hpp",
"../SDK/include/NDK/**.inl",
"../SDK/src/NDK/**.hpp",
"../SDK/src/NDK/**.inl",
"../SDK/src/NDK/**.cpp"
}
-- Excludes client-only files
TOOL.FilesExcluded = {
"../SDK/**/CameraComponent.*",
"../SDK/**/Console.*",
"../SDK/**/GraphicsComponent.*",
"../SDK/**/LightComponent.*",
"../SDK/**/ListenerComponent.*",
"../SDK/**/ListenerSystem.*",
"../SDK/**/RenderSystem.*",
"../SDK/**/LuaBinding_Audio.*",
"../SDK/**/LuaBinding_Graphics.*",
"../SDK/**/LuaBinding_Renderer.*"
}
TOOL.Libraries = {
"NazaraCore",
"NazaraLua",
"NazaraNetwork",
"NazaraNoise",
"NazaraPhysics",
"NazaraUtility"
}
|
Build/NDKServer: Fix dependencies, allowing it to exists in server mode
|
Build/NDKServer: Fix dependencies, allowing it to exists in server mode
Former-commit-id: e917ce65aaea2567e4cb261777f458c3ea8ecdad [formerly a2f437b555af173f06b75f78bfe89ee14de7ba9f]
Former-commit-id: 83d69a7152c45f02ae5a344c7f8be574cded2318
|
Lua
|
mit
|
DigitalPulseSoftware/NazaraEngine
|
ab4a9ad98f4afc290fb5885e7b72d6127044fc18
|
examples/talking-to-children.lua
|
examples/talking-to-children.lua
|
local p = require('lib/utils').prettyPrint
local uv = require('luv')
local stdout = uv.new_pipe(false)
local stderr = uv.new_pipe( false)
local stdin = uv.new_pipe(false)
local handle, pid
local function onexit(code, signal)
p("exit", {code=code,signal=signal})
end
local function onclose()
p("close")
end
local function onread(err, chunk)
assert(not err, err)
if (chunk) then
p("data", {data=chunk})
else
p("end")
end
end
local function onshutdown()
uv.close(handle, onclose)
end
handle, pid = uv.spawn("cat", {
stdio = {stdin, stdout, stderr}
}, onexit)
p{
handle=handle,
pid=pid
}
uv.read_start(stdout, onread)
uv.read_start(stderr, onread)
uv.write(stdin, "Hello World")
uv.shutdown(stdin, onshutdown)
uv.run()
uv.walk(uv.close)
uv.run()
|
local p = require('lib/utils').prettyPrint
local uv = require('luv')
local stdout = uv.new_pipe(false)
local stderr = uv.new_pipe( false)
local stdin = uv.new_pipe(false)
local handle, pid
local function onexit(code, signal)
p("exit", {code=code,signal=signal})
end
local function onclose()
p("close")
end
local function onread(err, chunk)
assert(not err, err)
if (chunk) then
p("data", {data=chunk})
else
p("end")
end
end
local function onshutdown(err)
if err == "ECANCELED" then
return
end
uv.close(handle, onclose)
end
handle, pid = uv.spawn("cat", {
stdio = {stdin, stdout, stderr}
}, onexit)
p{
handle=handle,
pid=pid
}
uv.read_start(stdout, onread)
uv.read_start(stderr, onread)
uv.write(stdin, "Hello World")
uv.shutdown(stdin, onshutdown)
uv.run()
uv.walk(uv.close)
uv.run()
|
Quick fix for PROCESS_CLEANUP_TEST CI failures (#436)
|
Quick fix for PROCESS_CLEANUP_TEST CI failures (#436)
The problem is that the shutdown callback is being called during loop_gc, so the Lua/Libuv state is being closed/free'd and the `handle` local var has already been closed/free'd so it's no longer a valid uv_stream_t (see https://github.com/luvit/luv/pull/414).
This will fix PROCESS_CLEANUP_TEST but there is more to do to solve the general case of 'things happening during loop gc'
|
Lua
|
apache-2.0
|
zhaozg/luv,luvit/luv,luvit/luv,zhaozg/luv
|
268a79926293370ee1d5fe40081f1f16ce25b3b0
|
mod_carbons/mod_carbons.lua
|
mod_carbons/mod_carbons.lua
|
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
local jid_split = require "util.jid".split;
local xmlns_carbons = "urn:xmpp:carbons:1";
local xmlns_forward = "urn:xmpp:forward:0";
local host_sessions = hosts[module.host].sessions;
-- TODO merge message handlers into one somehow
module:hook("iq/self/"..xmlns_carbons..":enable", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
module:log("debug", "%s enabled carbons", origin.full_jid);
origin.want_carbons = true;
origin.send(st.reply(stanza));
return true
end
end);
module:hook("iq/self/"..xmlns_carbons..":disable", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
module:log("debug", "%s disabled carbons", origin.full_jid);
origin.want_carbons = nil;
origin.send(st.reply(stanza));
return true
end
end);
function c2s_message_handler(event)
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
end
local bare_jid, user_sessions;
if origin.type == "s2s" then
bare_jid = jid_bare(stanza.attr.from);
user_sessions = host_sessions[jid_split(orig_to)];
else
bare_jid = (origin.username.."@"..origin.host)
user_sessions = host_sessions[origin.username];
end
if not stanza:get_child("private", xmlns_carbons)
and not stanza:get_child("forwarded", xmlns_forward) then
user_sessions = user_sessions and user_sessions.sessions;
for resource, session in pairs(user_sessions) do
local full_jid = bare_jid .. "/" .. resource;
if session ~= origin and session.want_carbons then
local msg = st.clone(stanza);
msg.attr.xmlns = msg.attr.xmlns or "jabber:client";
local fwd = st.message{
from = bare_jid,
to = full_jid,
type = orig_type,
}
:tag("forwarded", { xmlns = xmlns_forward })
:tag("received", { xmlns = xmlns_carbons }):up()
:add_child(msg);
core_route_stanza(origin, fwd);
end
end
end
end
function s2c_message_handler(event)
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
end
local full_jid, bare_jid = orig_to, jid_bare(orig_to);
local username, hostname, resource = jid_split(full_jid);
local user_sessions = username and host_sessions[username];
if not user_sessions or hostname ~= module.host then
return
end
local no_carbon_to = {};
if resource then
no_carbon_to[resource] = true;
else
local top_resources = user_sessions.top_resources;
for i=1,top_resources do
no_carbon_to[top_resources[i]] = true;
end
end
if not stanza:get_child("private", xmlns_carbons)
and not stanza:get_child("forwarded", xmlns_forward) then
user_sessions = user_sessions and user_sessions.sessions;
for resource, session in pairs(user_sessions) do
local full_jid = bare_jid .. "/" .. resource;
if not no_carbon_to[resource] and session.want_carbons then
local msg = st.clone(stanza);
msg.attr.xmlns = msg.attr.xmlns or "jabber:client";
local fwd = st.message{
from = bare_jid,
to = full_jid,
type = orig_type,
}
:tag("forwarded", { xmlns = xmlns_forward })
:tag("received", { xmlns = xmlns_carbons }):up()
:add_child(msg);
core_route_stanza(origin, fwd);
end
end
end
end
-- Stanzas sent by local clients
module:hook("pre-message/bare", c2s_message_handler, 1);
module:hook("pre-message/full", c2s_message_handler, 1);
-- Stanszas to local clients
module:hook("message/bare", s2c_message_handler, 1); -- this will suck
module:hook("message/full", s2c_message_handler, 1);
module:add_feature(xmlns_carbons);
|
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
local jid_split = require "util.jid".split;
local xmlns_carbons = "urn:xmpp:carbons:1";
local xmlns_forward = "urn:xmpp:forward:0";
local host_sessions = hosts[module.host].sessions;
-- TODO merge message handlers into one somehow
module:hook("iq/self/"..xmlns_carbons..":enable", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
module:log("debug", "%s enabled carbons", origin.full_jid);
origin.want_carbons = true;
origin.send(st.reply(stanza));
return true
end
end);
module:hook("iq/self/"..xmlns_carbons..":disable", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
module:log("debug", "%s disabled carbons", origin.full_jid);
origin.want_carbons = nil;
origin.send(st.reply(stanza));
return true
end
end);
function c2s_message_handler(event)
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
end
local bare_jid, user_sessions;
if origin.type == "s2s" then
bare_jid = jid_bare(stanza.attr.from);
user_sessions = host_sessions[jid_split(orig_to)];
else
bare_jid = (origin.username.."@"..origin.host)
user_sessions = host_sessions[origin.username];
end
if not stanza:get_child("private", xmlns_carbons)
and not stanza:get_child("forwarded", xmlns_forward) then
user_sessions = user_sessions and user_sessions.sessions;
for resource, session in pairs(user_sessions) do
local full_jid = bare_jid .. "/" .. resource;
if session ~= origin and session.want_carbons then
local msg = st.clone(stanza);
msg.attr.xmlns = msg.attr.xmlns or "jabber:client";
local fwd = st.message{
from = bare_jid,
to = full_jid,
type = orig_type,
}
:tag("forwarded", { xmlns = xmlns_forward })
:tag("sent", { xmlns = xmlns_carbons }):up()
:add_child(msg);
core_route_stanza(origin, fwd);
end
end
end
end
function s2c_message_handler(event)
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
end
local full_jid, bare_jid = orig_to, jid_bare(orig_to);
local username, hostname, resource = jid_split(full_jid);
local user_sessions = username and host_sessions[username];
if not user_sessions or hostname ~= module.host then
return
end
local no_carbon_to = {};
if resource then
no_carbon_to[resource] = true;
else
local top_resources = user_sessions.top_resources;
for i, session in ipairs(top_resources) do
no_carbon_to[session.resource] = true;
module:log("debug", "not going to send to /%s", resource);
end
end
if not stanza:get_child("private", xmlns_carbons)
and not stanza:get_child("forwarded", xmlns_forward) then
user_sessions = user_sessions and user_sessions.sessions;
for resource, session in pairs(user_sessions) do
local full_jid = bare_jid .. "/" .. resource;
if not no_carbon_to[resource] and session.want_carbons then
local msg = st.clone(stanza);
msg.attr.xmlns = msg.attr.xmlns or "jabber:client";
local fwd = st.message{
from = bare_jid,
to = full_jid,
type = orig_type,
}
:tag("forwarded", { xmlns = xmlns_forward })
:tag("received", { xmlns = xmlns_carbons }):up()
:add_child(msg);
core_route_stanza(origin, fwd);
end
end
end
end
-- Stanzas sent by local clients
module:hook("pre-message/bare", c2s_message_handler, 1);
module:hook("pre-message/full", c2s_message_handler, 1);
-- Stanszas to local clients
module:hook("message/bare", s2c_message_handler, 1);
module:hook("message/full", s2c_message_handler, 1);
module:add_feature(xmlns_carbons);
|
mod_carbons: Fix top_resources loop and correctly stamp sent messages (thanks xnyhps)
|
mod_carbons: Fix top_resources loop and correctly stamp sent messages (thanks xnyhps)
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
1a1318622962cfad9dad192b9dcdc5297478e135
|
cardshifter-core/src/main/resources/com/cardshifter/core/start.lua
|
cardshifter-core/src/main/resources/com/cardshifter/core/start.lua
|
-- Always name this function "startGame"
function startGame(game)
local endturnAction = require "src/main/resources/com/cardshifter/core/actions/player/endturn"
game:on('actionUsed', onActionUsed)
game:on('turnStart', onTurnStart)
local numPlayers = game:getPlayers():size()
for i = 0, numPlayers - 1 do
local player = game:getPlayer(i)
print("Player: " .. player:toString())
player:addAction("End Turn", endturnAction.isAllowed, endturnAction.perform)
player.data.life = 10
player.data.mana = 0
player.data.manaMax = 0
player.data.scrap = 0
player.data.cardType = 'Player'
local field = game:createZone(player, "Battlefield")
field:setGloballyKnown(true)
player.data.battlefield = field
local deck = game:createZone(player, "Deck")
player.data.deck = deck
local hand = game:createZone(player, "Hand")
hand:setKnown(player, true)
player.data.hand = hand
for i = 1, 4 do
local card
for strength = 1, 5 do
card = createCreature(deck, strength, strength, strength, 'B0T')
if strength == 2 then
card.data.strength = card.data.strength + 1
end
end
card = createCreature(deck, 5, 4, 4, 'Bio')
card = createCreature(deck, 5, 5, 3, 'Bio')
card = createCreature(deck, 5, 3, 5, 'Bio')
card = createEnchantment(deck, 1, 0, 1)
card = createEnchantment(deck, 0, 1, 1)
card = createEnchantment(deck, 3, 0, 3)
card = createEnchantment(deck, 0, 3, 3)
card = createSpecialEnchantment(deck, 2, 2, 5)
end
deck:shuffle()
for i=1,5 do
drawCard(player)
end
end
-- Turn Start event is not called when starting game (player should not draw card), setup initial mana for first player
firstPlayer = game:getFirstPlayer()
firstPlayer.data.mana = 1
firstPlayer.data.manaMax = 1
end
function createSpecialEnchantment(deck, strength, health, cost)
local enchantspecialAction = require "src/main/resources/com/cardshifter/core/actions/card/enchantspecial"
-- A special enchantment can only target a creature that has been enchanted already
local card = deck:createCardOnBottom()
card:addTargetAction("Enchant", enchantspecialAction.isAllowed, enchantspecialAction.perform, enchantspecialAction.isTargetAllowed)
card.data.manaCost = 0
card.data.scrapCost = cost
card.data.enchStrength = strength
card.data.enchHealth = health
card.data.cardType = 'Enchantment'
return card
end
function createEnchantment(deck, strength, health, cost)
local enchantAction = require "src/main/resources/com/cardshifter/core/actions/card/enchant"
-- Can only target creatureType == 'Bio'
local card = deck:createCardOnBottom()
card:addTargetAction("Enchant", enchantAction.isAllowed, enchantAction.perform, enchantAction.isTargetAllowed)
card.data.manaCost = 0
card.data.scrapCost = cost
card.data.enchStrength = strength
card.data.enchHealth = health
card.data.cardType = 'Enchantment'
return card
end
function createCreature(deck, cost, strength, health, creatureType)
local playAction = require "src/main/resources/com/cardshifter/core/actions/card/play"
local attackAction = require "src/main/resources/com/cardshifter/core/actions/card/attack"
local scrapAction = require "src/main/resources/com/cardshifter/core/actions/card/scrap"
local card = deck:createCardOnBottom()
card:addAction("Play", playAction.isAllowed, playAction.perform)
card:addTargetAction("Attack", attackAction.isAllowed, attackAction.perform, attackAction.isTargetAllowed)
card:addAction("Scrap", scrapAction.isAllowed, scrapAction.perform)
card.data.manaCost = cost
card.data.strength = strength
card.data.health = health
card.data.enchantments = 0
card.data.creatureType = creatureType
card.data.cardType = 'Creature'
card.data.sickness = 1
card.data.attacksAvailable = 1
return card
end
function onActionUsed(card, action)
print("(This is Lua) Action Used! " .. card:toString() .. " with action " .. action:toString())
end
function onTurnStart(player, event)
print("(This is Lua) Turn Start! " .. player:toString())
if player.data.deck:isEmpty() then
print("(This is Lua) Deck is empty!")
end
local field = player.data.battlefield
local iterator = field:getCards():iterator()
while iterator:hasNext() do
local card = iterator:next()
if card.data.sickness > 0 then
card.data.sickness = card.data.sickness - 1
print("Card on field now has sickness" .. card.data.sickness)
end
card.data.attacksAvailable = 1
end
drawCard(player)
player.data.manaMax = player.data.manaMax + 1
player.data.mana = player.data.manaMax
end
function drawCard(player)
local card = player.data.deck:getTopCard()
card:moveToBottomOf(player.data.hand)
end
|
-- Always name this function "startGame"
function startGame(game)
local endturnAction = require "src/main/resources/com/cardshifter/core/actions/player/endturn"
game:on('actionUsed', onActionUsed)
game:on('turnStart', onTurnStart)
local numPlayers = game:getPlayers():size()
for i = 0, numPlayers - 1 do
local player = game:getPlayer(i)
print("Player: " .. player:toString())
player:addAction("End Turn", endturnAction.isAllowed, endturnAction.perform)
player.data.life = 10
player.data.mana = 0
player.data.manaMax = 0
player.data.scrap = 0
player.data.cardType = 'Player'
local field = game:createZone(player, "Battlefield")
field:setGloballyKnown(true)
player.data.battlefield = field
local deck = game:createZone(player, "Deck")
player.data.deck = deck
local hand = game:createZone(player, "Hand")
hand:setKnown(player, true)
player.data.hand = hand
for i = 1, 4 do
local card
for strength = 1, 5 do
card = createCreature(deck, strength, strength, strength, 'B0T')
if strength == 2 then
card.data.strength = card.data.strength + 1
end
end
card = createCreature(deck, 5, 4, 4, 'Bio')
card = createCreature(deck, 5, 5, 3, 'Bio')
card = createCreature(deck, 5, 3, 5, 'Bio')
card = createEnchantment(deck, 1, 0, 1)
card = createEnchantment(deck, 0, 1, 1)
card = createEnchantment(deck, 3, 0, 3)
card = createEnchantment(deck, 0, 3, 3)
card = createSpecialEnchantment(deck, 2, 2, 5)
end
deck:shuffle()
for i=1,5 do
drawCard(player)
end
end
-- Turn Start event is not called when starting game (player should not draw card), setup initial mana for first player
firstPlayer = game:getFirstPlayer()
firstPlayer.data.mana = 1
firstPlayer.data.manaMax = 1
end
function createSpecialEnchantment(deck, strength, health, cost)
local enchantspecialAction = require "src/main/resources/com/cardshifter/core/actions/card/enchantspecial"
-- A special enchantment can only target a creature that has been enchanted already
local card = deck:createCardOnBottom()
card:addTargetAction("Enchant", enchantspecialAction.isAllowed, enchantspecialAction.perform, enchantspecialAction.isTargetAllowed)
card.data.manaCost = 0
card.data.scrapCost = cost
card.data.enchStrength = strength
card.data.enchHealth = health
card.data.cardType = 'Enchantment'
return card
end
function createEnchantment(deck, strength, health, cost)
local enchantAction = require "src/main/resources/com/cardshifter/core/actions/card/enchant"
-- Can only target creatureType == 'Bio'
local card = deck:createCardOnBottom()
card:addTargetAction("Enchant", enchantAction.isAllowed, enchantAction.perform, enchantAction.isTargetAllowed)
card.data.manaCost = 0
card.data.scrapCost = cost
card.data.enchStrength = strength
card.data.enchHealth = health
card.data.cardType = 'Enchantment'
return card
end
function createCreature(deck, cost, strength, health, creatureType)
local playAction = require "src/main/resources/com/cardshifter/core/actions/card/play"
local attackAction = require "src/main/resources/com/cardshifter/core/actions/card/attack"
local scrapAction = require "src/main/resources/com/cardshifter/core/actions/card/scrap"
local card = deck:createCardOnBottom()
card:addAction("Play", playAction.isAllowed, playAction.perform)
card:addTargetAction("Attack", attackAction.isAllowed, attackAction.perform, attackAction.isTargetAllowed)
card:addAction("Scrap", scrapAction.isAllowed, scrapAction.perform)
card.data.manaCost = cost
card.data.strength = strength
card.data.health = health
card.data.enchantments = 0
card.data.creatureType = creatureType
card.data.cardType = 'Creature'
card.data.sickness = 1
card.data.attacksAvailable = 1
return card
end
function onActionUsed(card, action)
print("(This is Lua) Action Used! " .. card:toString() .. " with action " .. action:toString())
end
function onTurnStart(player, event)
print("(This is Lua) Turn Start! " .. player:toString())
local field = player.data.battlefield
local iterator = field:getCards():iterator()
while iterator:hasNext() do
local card = iterator:next()
if card.data.sickness > 0 then
card.data.sickness = card.data.sickness - 1
print("Card on field now has sickness" .. card.data.sickness)
end
card.data.attacksAvailable = 1
end
if not drawCard(player) then
player.data.life = player.data.life - 1
if player.data.life <= 0 then
player:getGame():gameOver()
end
print("(This is Lua) Deck is empty! One damage taken.")
end
player.data.manaMax = player.data.manaMax + 1
player.data.mana = player.data.manaMax
end
function drawCard(player)
if player.data.deck:isEmpty() then
return false
end
local card = player.data.deck:getTopCard()
card:moveToBottomOf(player.data.hand)
return true
end
|
Player now lose life on each failed draw card. Fixes #13
|
Player now lose life on each failed draw card. Fixes #13
|
Lua
|
apache-2.0
|
Cardshifter/Cardshifter,June92/Cardshifter,Cardshifter/Cardshifter,June92/Cardshifter,SirPython/Cardshifter,Cardshifter/Cardshifter,June92/Cardshifter,SirPython/Cardshifter,SirPython/Cardshifter
|
2b5ae24d57072cc0c88fbf2c2ec920e4dcc5bfde
|
plugins/pwgen.lua
|
plugins/pwgen.lua
|
local pwgen = {}
local HTTP = require('socket.http')
local JSON = require('dkjson')
local functions = require('functions')
function pwgen:init(configuration)
pwgen.command = 'pwgen <length>'
pwgen.triggers = functions.triggers(self.info.username, configuration.command_prefix):t('pwgen', true).table
pwgen.doc = configuration.command_prefix .. 'pwgen <length> - Generates a random password of the given length. Please note that this is not the recommended method of generating a password and, like all online generators, it has security risks.'
end
function pwgen:action(msg, configuration)
local input = functions.input(msg.text)
if not input then functions.send_reply(msg, pwgen.doc, true) return end
if tonumber(input) > 30 then functions.send_reply(msg, '`Please enter a lower number.`', true) return end
if tonumber(input) < 5 then functions.send_reply(msg, '`Please enter a higher number.`', true) return end
local jdat = ''
local jstr, res = HTTP.request(configuration.pwgen_api .. input)
if res ~= 200 then
functions.send_reply(msg, '`' .. configuration.errors.connection .. '`', true)
return
else
jdat = JSON.decode(jstr)
functions.send_reply(msg, '*Password:* `' .. functions.md_escape(jdat[1].password) .. '`\n*Phonetic:* `' .. functions.md_escape(jdat[1].phonetic) .. '`', true)
return
end
end
return pwgen
|
local pwgen = {}
local HTTP = require('socket.http')
local JSON = require('dkjson')
local functions = require('functions')
function pwgen:init(configuration)
pwgen.command = 'pwgen <length>'
pwgen.triggers = functions.triggers(self.info.username, configuration.command_prefix):t('pwgen', true).table
pwgen.doc = configuration.command_prefix .. 'pwgen <length> - Generates a random password of the given length.'
end
function pwgen:action(msg, configuration)
local input = functions.input(msg.text)
if not input then
functions.send_reply(msg, pwgen.doc, true)
return
else
if tonumber(input) ~= nil then
if tonumber(input) > 30 then functions.send_reply(msg, '`Please enter a lower number.`', true) return end
if tonumber(input) < 5 then functions.send_reply(msg, '`Please enter a higher number.`', true) return end
local jstr, res = HTTP.request(configuration.pwgen_api .. input)
if res ~= 200 then
functions.send_reply(msg, '`' .. configuration.errors.connection .. '`', true)
return
else
local jdat = JSON.decode(jstr)
functions.send_reply(msg, '*Password:* `' .. functions.md_escape(jstr[1].password) .. '`\n*Phonetic:* `' .. functions.md_escape(jstr[1].phonetic) .. '`', true)
return
end
else
functions.send_reply(msg, '`Please enter a numeric value.`', true)
return
end
end
end
return pwgen
|
Fixed a bug
|
Fixed a bug
Solved a bug where an error was returned if the inputted message with /pwgen wasn't numeric
|
Lua
|
mit
|
barreeeiroo/BarrePolice
|
c32edf0d4acc2d9e22acb6ae6b92b4d7672b1ff3
|
src/game/StarterPlayer/StarterCharacterScripts/TriggerListening.lua
|
src/game/StarterPlayer/StarterCharacterScripts/TriggerListening.lua
|
-- ClassName: LocalScript
--[[
Handles client-side trigger setup.
This script instantiates all of the ClientTriggers and connects to their
events to allow the user to "interact" with the game world by binding actions.
Each CharacterTrigger has an associated RemoteEvent it can fire, and the
server takes care of what happens next.
For example, if you're in the trigger right outside the Wave Station,
interacting will fire the "WaveStationUsed" RemoteEvent. The server then takes
care of the rest by teleporting you onto the Sky Wave.
--]]
local players = game:GetService("Players")
local replicatedStorage = game:GetService("ReplicatedStorage")
local remotes = require(replicatedStorage.Events.Remotes)
local Interact = require(replicatedStorage.Interaction.Interact)
local InteractionPrompt = require(replicatedStorage.UI.InteractionPrompt)
local CharacterTrigger = require(replicatedStorage.Triggers.CharacterTrigger)
local getTriggers = remotes.getFunction("GetTriggerParts")
local client = players.LocalPlayer
local playerGui = client.PlayerGui
local character = client.Character or client.CharacterAdded:wait()
local interact = Interact.new()
-- This is a little messy but right now InteractionPrompt only works off of a
-- keyboard key. Since Interact uses the keyboard as its first input type for
-- ContextActionService, we index the list of inputs and get the name for the
-- input.
--
-- Enums have a `Name` property which in this case is "E" for Enum.KeyCode.E,
-- so we pass that in to the InteractionPrompt so it displays the correct key.
local inputName = interact.Inputs[1].Name
local prompt = InteractionPrompt.new(playerGui, inputName)
local function setupTrigger(triggerPart)
local trigger = CharacterTrigger.new(triggerPart, character)
trigger:Connect()
interact:SetBoundFunction(function(inputState)
if inputState == Enum.UserInputState.End then return end
trigger:FireEvent()
end)
trigger.CharacterEntered:connect(function()
prompt:Show()
interact:Bind()
end)
trigger.CharacterLeft:connect(function()
prompt:QuickHide()
interact:Unbind()
end)
end
local function setupExistingTriggers()
local triggerParts = getTriggers:InvokeServer()
for _, triggerPart in ipairs(triggerParts) do
setupTrigger(triggerPart)
end
end
setupExistingTriggers()
|
-- ClassName: LocalScript
--[[
Handles client-side trigger setup.
This script instantiates all of the ClientTriggers and connects to their
events to allow the user to "interact" with the game world by binding actions.
Each CharacterTrigger has an associated RemoteEvent it can fire, and the
server takes care of what happens next.
For example, if you're in the trigger right outside the Wave Station,
interacting will fire the "WaveStationUsed" RemoteEvent. The server then takes
care of the rest by teleporting you onto the Sky Wave.
--]]
local players = game:GetService("Players")
local replicatedStorage = game:GetService("ReplicatedStorage")
local remotes = require(replicatedStorage.Events.Remotes)
local Interact = require(replicatedStorage.Interaction.Interact)
local InteractionPrompt = require(replicatedStorage.UI.InteractionPrompt)
local CharacterTrigger = require(replicatedStorage.Triggers.CharacterTrigger)
local getTriggers = remotes.getFunction("GetTriggerParts")
local client = players.LocalPlayer
local playerGui = client.PlayerGui
local character = client.Character or client.CharacterAdded:wait()
local interact = Interact.new()
-- This is a little messy but right now InteractionPrompt only works off of a
-- keyboard key. Since Interact uses the keyboard as its first input type for
-- ContextActionService, we index the list of inputs and get the name for the
-- input.
--
-- Enums have a `Name` property which in this case is "E" for Enum.KeyCode.E,
-- so we pass that in to the InteractionPrompt so it displays the correct key.
local inputName = interact.Inputs[1].Name
local prompt = InteractionPrompt.new(playerGui, inputName)
local function setupTrigger(triggerPart)
local trigger = CharacterTrigger.new(triggerPart, character)
trigger:Connect()
local function action(inputState)
if inputState == Enum.UserInputState.End then return end
trigger:FireEvent()
end
trigger.CharacterEntered:connect(function()
prompt:Show()
interact:SetBoundFunction(action)
interact:Bind()
end)
trigger.CharacterLeft:connect(function()
prompt:QuickHide()
interact:Unbind()
end)
end
local function setupExistingTriggers()
local triggerParts = getTriggers:InvokeServer()
for _, triggerPart in ipairs(triggerParts) do
setupTrigger(triggerPart)
end
end
setupExistingTriggers()
|
Fix last Trigger defining the bound function for all Triggers
|
Fix last Trigger defining the bound function for all Triggers
Since we only set the bound function when setting up the Trigger, this
means that the last Trigger in the call SetBoundFunction, overriding all
the other Triggers' calls to it.
This fixes that by setting the bound function each time a Character enters
one of the Triggers.
|
Lua
|
mit
|
VoxelDavid/echo-ridge
|
3be0c934ab73d19a1e1fdfaf4e40809ded2354aa
|
game/scripts/vscripts/items/item_bloodthorn.lua
|
game/scripts/vscripts/items/item_bloodthorn.lua
|
item_bloodthorn_baseclass = {}
LinkLuaModifier("modifier_item_bloodthorn_arena", "items/item_bloodthorn", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_item_bloodthorn_arena_silence", "items/item_bloodthorn", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_item_bloodthorn_arena_crit", "items/item_bloodthorn", LUA_MODIFIER_MOTION_NONE)
function item_bloodthorn_baseclass:GetIntrinsicModifierName()
return "modifier_item_bloodthorn_arena"
end
if IsServer() then
function item_bloodthorn_baseclass:OnSpellStart()
local target = self:GetCursorTarget()
if not target:TriggerSpellAbsorb(self) then
target:TriggerSpellReflect(self)
target:EmitSound("DOTA_Item.Orchid.Activate")
target:AddNewModifier(self:GetCaster(), self, "modifier_item_bloodthorn_arena_silence", {duration = self:GetSpecialValueFor("silence_duration")})
end
end
end
item_bloodthorn_2 = class(item_bloodthorn_baseclass)
modifier_item_bloodthorn_arena = class({})
function modifier_item_bloodthorn_arena:IsHidden() return true end
function modifier_item_bloodthorn_arena:GetAttributes() return MODIFIER_ATTRIBUTE_MULTIPLE end
function modifier_item_bloodthorn_arena:DeclareFunctions()
return {
MODIFIER_PROPERTY_STATS_INTELLECT_BONUS,
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE,
MODIFIER_PROPERTY_MANA_REGEN_CONSTANT,
MODIFIER_PROPERTY_PREATTACK_CRITICALSTRIKE
}
end
function modifier_item_bloodthorn_arena:GetModifierBonusStats_Intellect()
return self:GetAbility():GetSpecialValueFor("bonus_intellect")
end
function modifier_item_bloodthorn_arena:GetModifierAttackSpeedBonus_Constant()
return self:GetAbility():GetSpecialValueFor("bonus_attack_speed")
end
function modifier_item_bloodthorn_arena:GetModifierPreAttack_BonusDamage()
return self:GetAbility():GetSpecialValueFor("bonus_damage")
end
function modifier_item_bloodthorn_arena:GetModifierPercentageManaRegen()
return self:GetAbility():GetSpecialValueFor("bonus_mana_regen_pct")
end
if IsServer() then
function modifier_item_bloodthorn_arena:GetModifierPreAttack_CriticalStrike(k)
local ability = self:GetAbility()
if RollPercentage(ability:GetSpecialValueFor("crit_chance_pct")) then
return ability:GetSpecialValueFor("crit_multiplier_pct")
end
end
end
modifier_item_bloodthorn_arena_silence = class({})
function modifier_item_bloodthorn_arena_silence:IsDebuff() return true end
function modifier_item_bloodthorn_arena_silence:GetEffectName()
return "particles/items2_fx/orchid.vpcf"
end
function modifier_item_bloodthorn_arena_silence:GetEffectAttachType()
return PATTACH_OVERHEAD_FOLLOW
end
function modifier_item_bloodthorn_arena_silence:CheckState()
return {
[MODIFIER_STATE_SILENCED] = true,
[MODIFIER_STATE_EVADE_DISABLED] = true,
}
end
function modifier_item_bloodthorn_arena_silence:DeclareFunctions()
return {
MODIFIER_PROPERTY_INCOMING_DAMAGE_PERCENTAGE,
MODIFIER_PROPERTY_TOOLTIP,
MODIFIER_EVENT_ON_TAKEDAMAGE,
MODIFIER_EVENT_ON_ATTACK_START,
}
end
function modifier_item_bloodthorn_arena_silence:OnTooltip()
return self:GetAbility():GetSpecialValueFor("target_crit_multiplier_pct")
end
if IsServer() then
function modifier_item_bloodthorn_arena_silence:OnTakeDamage(keys)
local parent = self:GetParent()
if parent == keys.unit then
ParticleManager:SetParticleControl(ParticleManager:CreateParticle("particles/items2_fx/orchid_pop.vpcf", PATTACH_ABSORIGIN_FOLLOW, keys.unit), 1, Vector(keys.damage))
self.damage = (self.damage or 0) + keys.damage
end
end
function modifier_item_bloodthorn_arena_silence:OnAttackStart(keys)
local parent = self:GetParent()
if parent == keys.target then
local ability = self:GetAbility()
keys.attacker:AddNewModifier(parent, self:GetAbility(), "modifier_item_bloodthorn_arena_crit", {duration = 1.5})
end
end
function modifier_item_bloodthorn_arena_silence:OnDestroy()
local ability = self:GetAbility()
local damage = (self.damage or 0) * ability:GetSpecialValueFor("silence_damage_pct") * 0.01
ParticleManager:SetParticleControl(ParticleManager:CreateParticle("particles/items2_fx/orchid_pop.vpcf", PATTACH_ABSORIGIN_FOLLOW, keys.unit), 1, Vector(damage))
if damage > 0 then
ApplyDamage({
attacker = self:GetCaster(),
victim = self:GetParent(),
damage = damage,
damage_type = ability:GetAbilityDamageType(),
ability = ability
})
end
end
end
modifier_item_bloodthorn_arena_crit = class({})
function modifier_item_bloodthorn_arena_crit:IsHidden() return true end
function modifier_item_bloodthorn_arena_crit:IsPurgable() return false end
if IsServer() then
function modifier_item_bloodthorn_arena_crit:DeclareFunctions()
return {
MODIFIER_PROPERTY_PREATTACK_CRITICALSTRIKE,
MODIFIER_EVENT_ON_ATTACK_LANDED
}
end
function modifier_item_bloodthorn_arena_crit:GetModifierPreAttack_CriticalStrike(keys)
if keys.target == self:GetCaster() and keys.target:HasModifier("modifier_item_bloodthorn_arena_silence") then
return self:GetAbility():GetSpecialValueFor("target_crit_multiplier_pct")
else
self:Destroy()
end
end
function modifier_item_bloodthorn_arena_crit:OnAttackLanded(keys)
if self:GetParent() == keys.attacker then
keys.attacker:RemoveModifierByName("modifier_item_bloodthorn_arena_crit")
end
end
end
|
LinkLuaModifier("modifier_item_bloodthorn_arena", "items/item_bloodthorn", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_item_bloodthorn_arena_silence", "items/item_bloodthorn", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_item_bloodthorn_arena_crit", "items/item_bloodthorn", LUA_MODIFIER_MOTION_NONE)
item_bloodthorn_baseclass = {
GetIntrinsicModifierName = function() return "modifier_item_bloodthorn_arena" end,
}
if IsServer() then
function item_bloodthorn_baseclass:OnSpellStart()
local target = self:GetCursorTarget()
if not target:TriggerSpellAbsorb(self) then
target:TriggerSpellReflect(self)
target:EmitSound("DOTA_Item.Orchid.Activate")
target:AddNewModifier(self:GetCaster(), self, "modifier_item_bloodthorn_arena_silence", {duration = self:GetSpecialValueFor("silence_duration")})
end
end
end
item_bloodthorn_2 = class(item_bloodthorn_baseclass)
modifier_item_bloodthorn_arena = class({})
function modifier_item_bloodthorn_arena:IsHidden() return true end
function modifier_item_bloodthorn_arena:GetAttributes() return MODIFIER_ATTRIBUTE_MULTIPLE end
function modifier_item_bloodthorn_arena:DeclareFunctions()
return {
MODIFIER_PROPERTY_STATS_INTELLECT_BONUS,
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE,
MODIFIER_PROPERTY_MANA_REGEN_CONSTANT,
MODIFIER_PROPERTY_PREATTACK_CRITICALSTRIKE
}
end
function modifier_item_bloodthorn_arena:GetModifierBonusStats_Intellect()
return self:GetAbility():GetSpecialValueFor("bonus_intellect")
end
function modifier_item_bloodthorn_arena:GetModifierAttackSpeedBonus_Constant()
return self:GetAbility():GetSpecialValueFor("bonus_attack_speed")
end
function modifier_item_bloodthorn_arena:GetModifierPreAttack_BonusDamage()
return self:GetAbility():GetSpecialValueFor("bonus_damage")
end
function modifier_item_bloodthorn_arena:GetModifierPercentageManaRegen()
return self:GetAbility():GetSpecialValueFor("bonus_mana_regen_pct")
end
if IsServer() then
function modifier_item_bloodthorn_arena:GetModifierPreAttack_CriticalStrike(k)
local ability = self:GetAbility()
if RollPercentage(ability:GetSpecialValueFor("crit_chance_pct")) then
return ability:GetSpecialValueFor("crit_multiplier_pct")
end
end
end
modifier_item_bloodthorn_arena_silence = class({
IsDebuff = function() return true end,
GetEffectAttachType = function() return PATTACH_OVERHEAD_FOLLOW end,
GetEffectName = function() return "particles/items2_fx/orchid.vpcf" end,
})
function modifier_item_bloodthorn_arena_silence:CheckState()
return {
[MODIFIER_STATE_SILENCED] = true,
[MODIFIER_STATE_EVADE_DISABLED] = true,
}
end
function modifier_item_bloodthorn_arena_silence:DeclareFunctions()
return {
MODIFIER_PROPERTY_INCOMING_DAMAGE_PERCENTAGE,
MODIFIER_PROPERTY_TOOLTIP,
MODIFIER_EVENT_ON_TAKEDAMAGE,
MODIFIER_EVENT_ON_ATTACK_START,
}
end
function modifier_item_bloodthorn_arena_silence:OnTooltip()
return self:GetAbility():GetSpecialValueFor("target_crit_multiplier_pct")
end
if IsServer() then
function modifier_item_bloodthorn_arena_silence:OnTakeDamage(keys)
local parent = self:GetParent()
if parent == keys.unit then
ParticleManager:SetParticleControl(ParticleManager:CreateParticle("particles/items2_fx/orchid_pop.vpcf", PATTACH_ABSORIGIN_FOLLOW, keys.unit), 1, Vector(keys.damage))
self.damage = (self.damage or 0) + keys.damage
end
end
function modifier_item_bloodthorn_arena_silence:OnAttackStart(keys)
local parent = self:GetParent()
if parent == keys.target then
local ability = self:GetAbility()
keys.attacker:AddNewModifier(parent, self:GetAbility(), "modifier_item_bloodthorn_arena_crit", {duration = 1.5})
end
end
function modifier_item_bloodthorn_arena_silence:OnDestroy()
local ability = self:GetAbility()
local parent = self:GetParent()
local damage = (self.damage or 0) * ability:GetSpecialValueFor("silence_damage_pct") * 0.01
ParticleManager:SetParticleControl(ParticleManager:CreateParticle("particles/items2_fx/orchid_pop.vpcf", PATTACH_ABSORIGIN_FOLLOW, parent), 1, Vector(damage))
if damage > 0 then
ApplyDamage({
attacker = self:GetCaster(),
victim = parent,
damage = damage,
damage_type = ability:GetAbilityDamageType(),
ability = ability
})
end
end
end
modifier_item_bloodthorn_arena_crit = class({
IsHidden = function() return true end,
IsPurgable = function() return false end,
})
if IsServer() then
function modifier_item_bloodthorn_arena_crit:DeclareFunctions()
return {
MODIFIER_PROPERTY_PREATTACK_CRITICALSTRIKE,
MODIFIER_EVENT_ON_ATTACK_LANDED
}
end
function modifier_item_bloodthorn_arena_crit:GetModifierPreAttack_CriticalStrike(keys)
if keys.target == self:GetCaster() and keys.target:HasModifier("modifier_item_bloodthorn_arena_silence") then
return self:GetAbility():GetSpecialValueFor("target_crit_multiplier_pct")
else
self:Destroy()
end
end
function modifier_item_bloodthorn_arena_crit:OnAttackLanded(keys)
if self:GetParent() == keys.attacker then
keys.attacker:RemoveModifierByName("modifier_item_bloodthorn_arena_crit")
end
end
end
|
Fixed Bloodthorn 2 not dealt bonus damage
|
Fixed Bloodthorn 2 not dealt bonus damage
|
Lua
|
mit
|
ark120202/aabs
|
4ce366470467ef4052c171f02bf5e6fa6e1a5c57
|
src/plugins/lua/rbl.lua
|
src/plugins/lua/rbl.lua
|
local rbls = {}
local rspamd_logger = require "rspamd_logger"
local function ip_to_rbl(ip, rbl)
return table.concat(ip:inversed_str_octets(), ".") .. '.' .. rbl
end
local function rbl_cb (task)
local function rbl_dns_cb(resolver, to_resolve, results, err, key)
if results then
local thisrbl = nil
for k,r in pairs(rbls) do
if k == key then
thisrbl = r
break
end
end
if thisrbl ~= nil then
if thisrbl['returncodes'] == nil then
if thisrbl['symbol'] ~= nil then
task:insert_result(thisrbl['symbol'], 1)
end
else
for _,result in pairs(results) do
local ipstr = result:to_string()
local foundrc = false
for s,i in pairs(thisrbl['returncodes']) do
if type(i) == 'string' then
if string.find(ipstr, "^" .. i .. "$") then
foundrc = true
task:insert_result(s, 1)
break
end
elseif type(i) == 'table' then
for _,v in pairs(i) do
if string.find(ipstr, "^" .. v .. "$") then
foundrc = true
task:insert_result(s, 1)
break
end
end
end
end
if not foundrc then
if thisrbl['unknown'] and thisrbl['symbol'] then
task:insert_result(thisrbl['symbol'], 1)
else
rspamd_logger.err('RBL ' .. thisrbl['rbl'] ..
' returned unknown result ' .. ipstr)
end
end
end
end
end
end
task:inc_dns_req()
end
local havegot = {}
local notgot = {}
for k,rbl in pairs(rbls) do
(function()
if rbl['exclude_users'] then
if not havegot['user'] and not notgot['user'] then
havegot['user'] = task:get_user()
if havegot['user'] == nil then
notgot['user'] = true
end
end
if havegot['user'] ~= nil then
return
end
end
if rbl['helo'] then
(function()
if notgot['helo'] then
return
end
if not havegot['helo'] then
havegot['helo'] = task:get_helo()
if havegot['helo'] == nil or string.sub(havegot['helo'],1,1) == '[' then
notgot['helo'] = true
return
end
end
task:get_resolver():resolve_a(task:get_session(), task:get_mempool(),
havegot['helo'] .. '.' .. rbl['rbl'], rbl_dns_cb, k)
end)()
end
if rbl['rdns'] then
(function()
if notgot['rdns'] then
return
end
if not havegot['rdns'] then
havegot['rdns'] = task:get_hostname()
if havegot['rdns'] == nil or havegot['rdns'] == 'unknown' then
notgot['rdns'] = true
return
end
end
task:get_resolver():resolve_a(task:get_session(), task:get_mempool(),
havegot['rdns'] .. '.' .. rbl['rbl'], rbl_dns_cb, k)
end)()
end
if rbl['from'] then
(function()
if notgot['from'] then
return
end
if not havegot['from'] then
havegot['from'] = task:get_from_ip()
if not havegot['from']:is_valid() then
notgot['from'] = true
return
end
end
if (havegot['from']:get_version() == 6 and rbl['ipv6']) or
(havegot['from']:get_version() == 4 and rbl['ipv4']) then
task:get_resolver():resolve_a(task:get_session(), task:get_mempool(),
ip_to_rbl(havegot['from'], rbl['rbl']), rbl_dns_cb, k)
end
end)()
end
if rbl['received'] then
(function()
if notgot['received'] then
return
end
if not havegot['received'] then
havegot['received'] = task:get_received_headers()
if next(havegot['received']) == nil then
notgot['received'] = true
return
end
end
for _,rh in ipairs(havegot['received']) do
if rh['real_ip'] and rh['real_ip']:is_valid() then
if (rh['real_ip']:get_version() == 6 and rbl['ipv6']) or
(rh['real_ip']:get_version() == 4 and rbl['ipv4']) then
task:get_resolver():resolve_a(task:get_session(), task:get_mempool(),
ip_to_rbl(rh['real_ip'], rbl['rbl']), rbl_dns_cb, k)
end
end
end
end)()
end
end)()
end
end
-- Registration
if type(rspamd_config.get_api_version) ~= 'nil' then
if rspamd_config:get_api_version() >= 1 then
rspamd_config:register_module_option('rbl', 'rbls', 'map')
rspamd_config:register_module_option('rbl', 'default_ipv4', 'string')
rspamd_config:register_module_option('rbl', 'default_ipv6', 'string')
rspamd_config:register_module_option('rbl', 'default_received', 'string')
rspamd_config:register_module_option('rbl', 'default_from', 'string')
rspamd_config:register_module_option('rbl', 'default_rdns', 'string')
rspamd_config:register_module_option('rbl', 'default_helo', 'string')
rspamd_config:register_module_option('rbl', 'default_unknown', 'string')
rspamd_config:register_module_option('rbl', 'default_exclude_users', 'string')
end
end
-- Configuration
local opts = rspamd_config:get_all_opt('rbl')
if not opts or type(opts) ~= 'table' then
return
end
if(opts['default_ipv4'] == nil) then
opts['default_ipv4'] = true
end
if(opts['default_ipv6'] == nil) then
opts['default_ipv6'] = false
end
if(opts['default_received'] == nil) then
opts['default_received'] = true
end
if(opts['default_from'] == nil) then
opts['default_from'] = false
end
if(opts['default_unknown'] == nil) then
opts['default_unknown'] = false
end
if(opts['default_rdns'] == nil) then
opts['default_rdns'] = false
end
if(opts['default_helo'] == nil) then
opts['default_helo'] = false
end
if(opts['default_exclude_users'] == nil) then
opts['default_exclude_users'] = false
end
for key,rbl in pairs(opts['rbls']) do
local o = { "ipv4", "ipv6", "from", "received", "unknown", "rdns", "helo", "exclude_users" }
for i=1,table.maxn(o) do
if(rbl[o[i]] == nil) then
rbl[o[i]] = opts['default_' .. o[i]]
end
end
if type(rbl['returncodes']) == 'table' then
for s,_ in pairs(rbl['returncodes']) do
if type(rspamd_config.get_api_version) ~= 'nil' then
rspamd_config:register_virtual_symbol(s, 1)
end
end
end
if not rbl['symbol'] and type(rbl['returncodes']) ~= 'nil' and not rbl['unknown'] then
rbl['symbol'] = key
end
if type(rspamd_config.get_api_version) ~= 'nil' and rbl['symbol'] then
rspamd_config:register_virtual_symbol(rbl['symbol'], 1)
end
rbls[key] = rbl
end
rspamd_config:register_callback_symbol_priority('RBL', 1.0, 0, rbl_cb)
|
local rbls = {}
local rspamd_logger = require "rspamd_logger"
local rspamd_ip = require "rspamd_ip"
local function ip_to_rbl(ip, rbl)
return table.concat(ip:inversed_str_octets(), ".") .. '.' .. rbl
end
local function rbl_cb (task)
local function rbl_dns_cb(resolver, to_resolve, results, err, key)
if results then
local thisrbl = nil
for k,r in pairs(rbls) do
if k == key then
thisrbl = r
break
end
end
if thisrbl ~= nil then
if thisrbl['returncodes'] == nil then
if thisrbl['symbol'] ~= nil then
task:insert_result(thisrbl['symbol'], 1)
end
else
for _,result in pairs(results) do
local ipstr = result:to_string()
local foundrc = false
for s,i in pairs(thisrbl['returncodes']) do
if type(i) == 'string' then
if string.find(ipstr, "^" .. i .. "$") then
foundrc = true
task:insert_result(s, 1)
break
end
elseif type(i) == 'table' then
for _,v in pairs(i) do
if string.find(ipstr, "^" .. v .. "$") then
foundrc = true
task:insert_result(s, 1)
break
end
end
end
end
if not foundrc then
if thisrbl['unknown'] and thisrbl['symbol'] then
task:insert_result(thisrbl['symbol'], 1)
else
rspamd_logger.err('RBL ' .. thisrbl['rbl'] ..
' returned unknown result ' .. ipstr)
end
end
end
end
end
end
task:inc_dns_req()
end
local havegot = {}
local notgot = {}
for k,rbl in pairs(rbls) do
(function()
if rbl['exclude_users'] then
if not havegot['user'] and not notgot['user'] then
havegot['user'] = task:get_user()
if havegot['user'] == nil then
notgot['user'] = true
end
end
if havegot['user'] ~= nil then
return
end
end
if rbl['helo'] then
(function()
if notgot['helo'] then
return
end
if not havegot['helo'] then
havegot['helo'] = task:get_helo()
if not havegot['helo'] or string.sub(havegot['helo'],1,1) == '[' or rspamd_ip.from_string(havegot['helo']):is_valid() then
notgot['helo'] = true
return
end
end
task:get_resolver():resolve_a(task:get_session(), task:get_mempool(),
havegot['helo'] .. '.' .. rbl['rbl'], rbl_dns_cb, k)
end)()
end
if rbl['rdns'] then
(function()
if notgot['rdns'] then
return
end
if not havegot['rdns'] then
havegot['rdns'] = task:get_hostname()
if havegot['rdns'] == nil or havegot['rdns'] == 'unknown' then
notgot['rdns'] = true
return
end
end
task:get_resolver():resolve_a(task:get_session(), task:get_mempool(),
havegot['rdns'] .. '.' .. rbl['rbl'], rbl_dns_cb, k)
end)()
end
if rbl['from'] then
(function()
if notgot['from'] then
return
end
if not havegot['from'] then
havegot['from'] = task:get_from_ip()
if not havegot['from']:is_valid() then
notgot['from'] = true
return
end
end
if (havegot['from']:get_version() == 6 and rbl['ipv6']) or
(havegot['from']:get_version() == 4 and rbl['ipv4']) then
task:get_resolver():resolve_a(task:get_session(), task:get_mempool(),
ip_to_rbl(havegot['from'], rbl['rbl']), rbl_dns_cb, k)
end
end)()
end
if rbl['received'] then
(function()
if notgot['received'] then
return
end
if not havegot['received'] then
havegot['received'] = task:get_received_headers()
if next(havegot['received']) == nil then
notgot['received'] = true
return
end
end
for _,rh in ipairs(havegot['received']) do
if rh['real_ip'] and rh['real_ip']:is_valid() then
if (rh['real_ip']:get_version() == 6 and rbl['ipv6']) or
(rh['real_ip']:get_version() == 4 and rbl['ipv4']) then
task:get_resolver():resolve_a(task:get_session(), task:get_mempool(),
ip_to_rbl(rh['real_ip'], rbl['rbl']), rbl_dns_cb, k)
end
end
end
end)()
end
end)()
end
end
-- Registration
if type(rspamd_config.get_api_version) ~= 'nil' then
if rspamd_config:get_api_version() >= 1 then
rspamd_config:register_module_option('rbl', 'rbls', 'map')
rspamd_config:register_module_option('rbl', 'default_ipv4', 'string')
rspamd_config:register_module_option('rbl', 'default_ipv6', 'string')
rspamd_config:register_module_option('rbl', 'default_received', 'string')
rspamd_config:register_module_option('rbl', 'default_from', 'string')
rspamd_config:register_module_option('rbl', 'default_rdns', 'string')
rspamd_config:register_module_option('rbl', 'default_helo', 'string')
rspamd_config:register_module_option('rbl', 'default_unknown', 'string')
rspamd_config:register_module_option('rbl', 'default_exclude_users', 'string')
end
end
-- Configuration
local opts = rspamd_config:get_all_opt('rbl')
if not opts or type(opts) ~= 'table' then
return
end
if(opts['default_ipv4'] == nil) then
opts['default_ipv4'] = true
end
if(opts['default_ipv6'] == nil) then
opts['default_ipv6'] = false
end
if(opts['default_received'] == nil) then
opts['default_received'] = true
end
if(opts['default_from'] == nil) then
opts['default_from'] = false
end
if(opts['default_unknown'] == nil) then
opts['default_unknown'] = false
end
if(opts['default_rdns'] == nil) then
opts['default_rdns'] = false
end
if(opts['default_helo'] == nil) then
opts['default_helo'] = false
end
if(opts['default_exclude_users'] == nil) then
opts['default_exclude_users'] = false
end
for key,rbl in pairs(opts['rbls']) do
local o = { "ipv4", "ipv6", "from", "received", "unknown", "rdns", "helo", "exclude_users" }
for i=1,table.maxn(o) do
if(rbl[o[i]] == nil) then
rbl[o[i]] = opts['default_' .. o[i]]
end
end
if type(rbl['returncodes']) == 'table' then
for s,_ in pairs(rbl['returncodes']) do
if type(rspamd_config.get_api_version) ~= 'nil' then
rspamd_config:register_virtual_symbol(s, 1)
end
end
end
if not rbl['symbol'] and type(rbl['returncodes']) ~= 'nil' and not rbl['unknown'] then
rbl['symbol'] = key
end
if type(rspamd_config.get_api_version) ~= 'nil' and rbl['symbol'] then
rspamd_config:register_virtual_symbol(rbl['symbol'], 1)
end
rbls[key] = rbl
end
rspamd_config:register_callback_symbol_priority('RBL', 1.0, 0, rbl_cb)
|
Fix helo checks in rbl.lua
|
Fix helo checks in rbl.lua
|
Lua
|
apache-2.0
|
minaevmike/rspamd,awhitesong/rspamd,andrejzverev/rspamd,amohanta/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,dark-al/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,amohanta/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,minaevmike/rspamd,awhitesong/rspamd,AlexeySa/rspamd,minaevmike/rspamd,awhitesong/rspamd,minaevmike/rspamd,amohanta/rspamd,dark-al/rspamd,AlexeySa/rspamd,minaevmike/rspamd,awhitesong/rspamd,dark-al/rspamd,dark-al/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,amohanta/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,minaevmike/rspamd,dark-al/rspamd,AlexeySa/rspamd,amohanta/rspamd,andrejzverev/rspamd,minaevmike/rspamd,minaevmike/rspamd
|
01377b485f1e5cdc680ee47448d1fa4313f3a8e6
|
plugins/mod_vcard.lua
|
plugins/mod_vcard.lua
|
require "util.datamanager"
local datamanager = datamanager;
local st = require "util.stanza"
local send = require "core.sessionmanager".send_to_session
local t_concat, t_insert = table.concat, table.insert;
require "util.jid"
local jid_split = jid.split;
add_iq_handler({"c2s", "s2sin"}, "vcard-temp",
function (session, stanza)
if stanza.tags[1].name == "vCard" then
local to = stanza.attr.to;
if stanza.attr.type == "get" then
local vCard;
if to then
local node, host = jid_split(to);
if hosts[host] and hosts[host].type == "local" then
vCard = st.deserialize(datamanager.load(node, host, "vCard")); -- load vCard for user or server
end
else
vCard = st.deserialize(datamanager.load(session.username, session.host, "vCard"));-- load user's own vCard
end
if vCard then
send(session, st.reply(stanza):add_child(vCard)); -- send vCard!
else
send(session, st.error_reply(stanza, "cancel", "item-not-found"));
end
elseif stanza.attr.type == "set" then
if not to or to == session.username.."@"..session.host then
if datamanager.store(session.username, session.host, "vCard", st.preserialize(stanza.tags[1])) then
send(session, st.reply(stanza));
else
-- TODO unable to write file, file may be locked, etc, what's the correct error?
send(session, st.error_reply(stanza, "wait", "internal-server-error"));
end
else
send(session, st.error_reply(stanza, "auth", "forbidden"));
end
end
return true;
end
end);
add_event_hook("stream-features",
function (session, features)
if session.type == "c2s" then
t_insert(features, "<feature var='vcard-temp'/>");
end
end);
|
require "util.datamanager"
local datamanager = datamanager;
local st = require "util.stanza"
local t_concat, t_insert = table.concat, table.insert;
require "util.jid"
local jid_split = jid.split;
add_iq_handler({"c2s", "s2sin"}, "vcard-temp",
function (session, stanza)
if stanza.tags[1].name == "vCard" then
local to = stanza.attr.to;
if stanza.attr.type == "get" then
local vCard;
if to then
local node, host = jid_split(to);
if hosts[host] and hosts[host].type == "local" then
vCard = st.deserialize(datamanager.load(node, host, "vCard")); -- load vCard for user or server
end
else
vCard = st.deserialize(datamanager.load(session.username, session.host, "vCard"));-- load user's own vCard
end
if vCard then
session.send(st.reply(stanza):add_child(vCard)); -- send vCard!
else
session.send(st.error_reply(stanza, "cancel", "item-not-found"));
end
elseif stanza.attr.type == "set" then
if not to or to == session.username.."@"..session.host then
if datamanager.store(session.username, session.host, "vCard", st.preserialize(stanza.tags[1])) then
session.send(st.reply(stanza));
else
-- TODO unable to write file, file may be locked, etc, what's the correct error?
session.send(st.error_reply(stanza, "wait", "internal-server-error"));
end
else
session.send(st.error_reply(stanza, "auth", "forbidden"));
end
end
return true;
end
end);
add_event_hook("stream-features",
function (session, features)
if session.type == "c2s" then
t_insert(features, "<feature var='vcard-temp'/>");
end
end);
|
Fix mod_vcard to use session.send for sending stanzas
|
Fix mod_vcard to use session.send for sending stanzas
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
a60235cfa28bf382b264910230977e5e20c35692
|
tests/test_lime_config_device.lua
|
tests/test_lime_config_device.lua
|
local config = require 'lime.config'
local utils = require 'lime.utils'
local hw_detection = require 'lime.hardware_detection'
local test_utils = require 'tests.utils'
-- disable logging in config module
config.log = function() end
local uci
local librerouter_board = test_utils.get_board('librerouter-v1')
describe('LiMe Config tests', function()
it('test lime-config for a LibreRouter device', function()
config.set('system', 'lime')
config.set('system', 'domain', 'lan')
config.set('system', 'hostname', 'LiMe-%M4%M5%M6')
config.set('network', 'lime')
config.set('network', 'primary_interface', 'eth0')
config.set('network', 'main_ipv4_address', '10.%N1.0.0/16')
config.set('network', 'main_ipv6_address', '2a00:1508:0a%N1:%N200::/64')
config.set('network', 'resolvers', {'4.2.2.2'})
config.set('network', 'protocols', {'static', 'lan', 'batadv:%N1', 'babeld:17', 'ieee80211s'})
config.set('wifi', 'lime')
config.set('wifi', 'ap_ssid', 'LibreMesh.org')
config.set('wifi', 'modes', {'ap', 'apname', 'ieee80211s'})
config.set('wifi', 'channel_2ghz', '11')
config.set('wifi', 'channel_5ghz', {'157', '48'})
config.set('wifi', 'distance_2ghz', '123')
config.set('wifi', 'distance_5ghz', '1234')
config.set('wifi', 'htmode_5ghz', 'HT40')
uci:commit('lime')
-- copy openwrt first boot generated configs
for _, config_name in ipairs({'network', 'wireless'}) do
local fin = io.open('tests/devices/librerouter-v1/uci_config_' .. config_name, 'r')
local fout = io.open(uci:get_confdir() .. '/' .. config_name, 'w')
fout:write(fin:read('*a'))
fin:close()
fout:close()
uci:load(config_name)
end
local iwinfo = require 'iwinfo'
iwinfo.fake.load_from_uci(uci)
stub(utils, "getBoardAsTable", function () return librerouter_board end)
table.insert(hw_detection.search_paths, 'packages/*hwd*/files/usr/lib/lua/lime/hwd/*.lua')
config.main()
assert.is.equal('eth0.1', config.get('lm_hwd_openwrt_wan', 'linux_name'))
assert.is.equal('eth0', uci:get('network', 'lm_net_eth0_babeld_dev', 'ifname'))
assert.is.equal('17', uci:get('network', 'lm_net_eth0_babeld_dev', 'vid'))
assert.is.equal('eth0_17', uci:get('network', 'lm_net_eth0_babeld_if', 'ifname'))
assert.is_nil(uci:get('network', 'globals', 'ula_prefix'))
for _, radio in ipairs({'radio0', 'radio1', 'radio2'}) do
assert.is.equal('0', uci:get('wireless', radio, 'disabled'))
assert.is.equal('1', uci:get('wireless', radio, 'noscan'))
end
assert.is.equal('11', uci:get('wireless', 'radio0', 'channel'))
assert.is.equal('48', uci:get('wireless', 'radio1', 'channel'))
assert.is.equal('157', uci:get('wireless', 'radio2', 'channel'))
assert.is.equal('HT20', uci:get('wireless', 'radio0', 'htmode'))
assert.is.equal('HT40', uci:get('wireless', 'radio1', 'htmode'))
assert.is.equal('HT40', uci:get('wireless', 'radio2', 'htmode'))
assert.is.equal('123', uci:get('wireless', 'radio0', 'distance'))
assert.is.equal('1234', uci:get('wireless', 'radio1', 'distance'))
assert.is.equal('1234', uci:get('wireless', 'radio2', 'distance'))
end)
setup('', function()
-- fake an empty hooksDir
config.hooksDir = io.popen("mktemp -d"):read('*l')
end)
teardown('', function()
io.popen("rm -r " .. config.hooksDir)
end)
before_each('', function()
uci = test_utils.setup_test_uci()
end)
after_each('', function()
test_utils.teardown_test_uci(uci)
end)
end)
|
local config = require 'lime.config'
local network = require 'lime.network'
local utils = require 'lime.utils'
local hw_detection = require 'lime.hardware_detection'
local test_utils = require 'tests.utils'
-- disable logging in config module
config.log = function() end
local uci
local librerouter_board = test_utils.get_board('librerouter-v1')
describe('LiMe Config tests', function()
it('test lime-config for a LibreRouter device', function()
config.set('system', 'lime')
config.set('system', 'domain', 'lan')
config.set('system', 'hostname', 'LiMe-%M4%M5%M6')
config.set('network', 'lime')
config.set('network', 'primary_interface', 'eth0')
config.set('network', 'main_ipv4_address', '10.%N1.0.0/16')
config.set('network', 'main_ipv6_address', '2a00:1508:0a%N1:%N200::/64')
config.set('network', 'resolvers', {'4.2.2.2'})
config.set('network', 'protocols', {'static', 'lan', 'batadv:%N1', 'babeld:17', 'ieee80211s'})
config.set('wifi', 'lime')
config.set('wifi', 'ap_ssid', 'LibreMesh.org')
config.set('wifi', 'modes', {'ap', 'apname', 'ieee80211s'})
config.set('wifi', 'channel_2ghz', '11')
config.set('wifi', 'channel_5ghz', {'157', '48'})
config.set('wifi', 'distance_2ghz', '123')
config.set('wifi', 'distance_5ghz', '1234')
config.set('wifi', 'htmode_5ghz', 'HT40')
uci:commit('lime')
stub(network, "get_mac", utils.get_id)
stub(network, "assert_interface_exists", function () return true end)
-- copy openwrt first boot generated configs
for _, config_name in ipairs({'network', 'wireless'}) do
local fin = io.open('tests/devices/librerouter-v1/uci_config_' .. config_name, 'r')
local fout = io.open(uci:get_confdir() .. '/' .. config_name, 'w')
fout:write(fin:read('*a'))
fin:close()
fout:close()
uci:load(config_name)
end
local iwinfo = require 'iwinfo'
iwinfo.fake.load_from_uci(uci)
stub(utils, "getBoardAsTable", function () return librerouter_board end)
table.insert(hw_detection.search_paths, 'packages/*hwd*/files/usr/lib/lua/lime/hwd/*.lua')
config.main()
assert.is.equal('eth0.1', config.get('lm_hwd_openwrt_wan', 'linux_name'))
assert.is.equal('eth0', uci:get('network', 'lm_net_eth0_babeld_dev', 'ifname'))
assert.is.equal('17', uci:get('network', 'lm_net_eth0_babeld_dev', 'vid'))
assert.is.equal('eth0_17', uci:get('network', 'lm_net_eth0_babeld_if', 'ifname'))
assert.is_nil(uci:get('network', 'globals', 'ula_prefix'))
for _, radio in ipairs({'radio0', 'radio1', 'radio2'}) do
assert.is.equal('0', uci:get('wireless', radio, 'disabled'))
assert.is.equal('1', uci:get('wireless', radio, 'noscan'))
end
assert.is.equal('11', uci:get('wireless', 'radio0', 'channel'))
assert.is.equal('48', uci:get('wireless', 'radio1', 'channel'))
assert.is.equal('157', uci:get('wireless', 'radio2', 'channel'))
assert.is.equal('HT20', uci:get('wireless', 'radio0', 'htmode'))
assert.is.equal('HT40', uci:get('wireless', 'radio1', 'htmode'))
assert.is.equal('HT40', uci:get('wireless', 'radio2', 'htmode'))
assert.is.equal('123', uci:get('wireless', 'radio0', 'distance'))
assert.is.equal('1234', uci:get('wireless', 'radio1', 'distance'))
assert.is.equal('1234', uci:get('wireless', 'radio2', 'distance'))
end)
setup('', function()
-- fake an empty hooksDir
config.hooksDir = io.popen("mktemp -d"):read('*l')
end)
teardown('', function()
io.popen("rm -r " .. config.hooksDir)
end)
before_each('', function()
uci = test_utils.setup_test_uci()
end)
after_each('', function()
test_utils.teardown_test_uci(uci)
end)
end)
|
tests: fix device test assertion
|
tests: fix device test assertion
the device test was relying in the existence of eth0 in the system.
|
Lua
|
agpl-3.0
|
libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages
|
ed3f70805ac0e30bf14f6a5850e873329f5e337c
|
spec/insulate-expose_spec.lua
|
spec/insulate-expose_spec.lua
|
assert.is_nil(package.loaded.pl)
assert.is_nil(package.loaded['pl.file'])
describe('Tests insulation', function()
insulate('environment inside insulate', function()
pl = require 'pl'
_G.insuated_global = true
it('updates insuated global table _G', function()
assert.is_not_nil(insuated_global)
assert.is_not_nil(_G.insuated_global)
end)
it('updates package.loaded', function()
assert.is_not_nil(pl)
assert.is_not_nil(List)
assert.is_not_nil(package.loaded.pl)
assert.is_not_nil(package.loaded['pl.List'])
end)
end)
describe('environment after insulate', function()
it('restores insuated global table _G', function()
assert.is_nil(insuated_global)
assert.is_nil(_G.insuated_global)
end)
it('restores package.loaded', function()
assert.is_nil(pl)
assert.is_nil(List)
assert.is_nil(package.loaded.pl)
assert.is_nil(package.loaded['pl.List'])
end)
end)
end)
insulate('', function()
describe('Tests expose', function()
insulate('inside insulate block', function()
expose('tests environment inside expose block', function()
pl = require 'pl'
exposed_global = true
_G.global = true
it('creates exposed global', function()
assert.is_not_nil(exposed_global)
assert.is_nil(_G.exposed_global)
end)
it('updates global table _G', function()
assert.is_not_nil(global)
assert.is_not_nil(_G.global)
end)
it('updates package.loaded', function()
assert.is_not_nil(pl)
assert.is_not_nil(List)
assert.is_not_nil(package.loaded.pl)
assert.is_not_nil(package.loaded['pl.List'])
end)
end)
end)
describe('neutralizes insulation', function()
it('creates exposed global in outer block', function()
assert.is_not_nil(exposed_global)
assert.is_nil(_G.exposed_global)
end)
it('does not restore global table _G', function()
assert.is_not_nil(global)
assert.is_not_nil(_G.global)
end)
it('does not restore package.loaded', function()
assert.is_not_nil(pl)
assert.is_not_nil(List)
assert.is_not_nil(package.loaded.pl)
assert.is_not_nil(package.loaded['pl.List'])
end)
end)
end)
it('Tests exposed globals does not exist in outer most block', function()
assert.is_nil(pl)
assert.is_nil(exposed_global)
assert.is_nil(_G.exposed_global)
end)
it('Tests global table _G persists without insulate', function()
assert.is_not_nil(global)
assert.is_not_nil(_G.global)
end)
it('Tests package.loaded persists without insulate', function()
assert.is_not_nil(List)
assert.is_not_nil(package.loaded.pl)
assert.is_not_nil(package.loaded['pl.List'])
end)
end)
describe('Tests after insulating an expose block', function()
it('restores global table _G', function()
assert.is_nil(global)
assert.is_nil(_G.global)
end)
it('restores package.loaded', function()
assert.is_nil(pl)
assert.is_nil(List)
assert.is_nil(package.loaded.pl)
assert.is_nil(package.loaded['pl.List'])
end)
end)
describe('Tests insulate/expose', function()
local path = require 'pl.path'
local utils = require 'pl.utils'
local busted_cmd = path.is_windows and 'lua bin/busted' or 'bin/busted'
local executeBusted = function(args)
local success, exitcode, out, err = utils.executeex(busted_cmd .. ' ' .. args)
if exitcode > 255 then
exitcode = math.floor(exitcode/256), exitcode - math.floor(exitcode/256)*256
end
return not not success, exitcode, out, err
end
describe('file insulation', function()
it('works between files', function()
local success, exitcode = executeBusted('spec/insulate_file1.lua spec/insulate_file2.lua')
assert.is_true(success)
assert.is_equal(0, exitcode)
end)
it('works between files independent of order', function()
local success, exitcode = executeBusted('spec/insulate_file2.lua spec/insulate_file1.lua')
assert.is_true(success)
assert.is_equal(0, exitcode)
end)
end)
describe('expose from file context', function()
it('works between files', function()
local success, exitcode = executeBusted('spec/expose_file1.lua spec/expose_file2.lua')
assert.is_true(success)
assert.is_equal(0, exitcode)
end)
end)
end)
|
assert.is_nil(package.loaded.pl)
assert.is_nil(package.loaded['pl.file'])
describe('Tests insulation', function()
insulate('environment inside insulate', function()
pl = require 'pl'
_G.insuated_global = true
it('updates insuated global table _G', function()
assert.is_not_nil(insuated_global)
assert.is_not_nil(_G.insuated_global)
end)
it('updates package.loaded', function()
assert.is_not_nil(pl)
assert.is_not_nil(Date)
assert.is_not_nil(package.loaded.pl)
assert.is_not_nil(package.loaded['pl.Date'])
end)
end)
describe('environment after insulate', function()
it('restores insuated global table _G', function()
assert.is_nil(insuated_global)
assert.is_nil(_G.insuated_global)
end)
it('restores package.loaded', function()
assert.is_nil(pl)
assert.is_nil(Date)
assert.is_nil(package.loaded.pl)
assert.is_nil(package.loaded['pl.Date'])
end)
end)
end)
insulate('', function()
describe('Tests expose', function()
insulate('inside insulate block', function()
expose('tests environment inside expose block', function()
pl = require 'pl'
exposed_global = true
_G.global = true
it('creates exposed global', function()
assert.is_not_nil(exposed_global)
assert.is_nil(_G.exposed_global)
end)
it('updates global table _G', function()
assert.is_not_nil(global)
assert.is_not_nil(_G.global)
end)
it('updates package.loaded', function()
assert.is_not_nil(pl)
assert.is_not_nil(Date)
assert.is_not_nil(package.loaded.pl)
assert.is_not_nil(package.loaded['pl.Date'])
end)
end)
end)
describe('neutralizes insulation', function()
it('creates exposed global in outer block', function()
assert.is_not_nil(exposed_global)
assert.is_nil(_G.exposed_global)
end)
it('does not restore global table _G', function()
assert.is_not_nil(global)
assert.is_not_nil(_G.global)
end)
it('does not restore package.loaded', function()
assert.is_not_nil(pl)
assert.is_not_nil(Date)
assert.is_not_nil(package.loaded.pl)
assert.is_not_nil(package.loaded['pl.Date'])
end)
end)
end)
it('Tests exposed globals does not exist in outer most block', function()
assert.is_nil(pl)
assert.is_nil(exposed_global)
assert.is_nil(_G.exposed_global)
end)
it('Tests global table _G persists without insulate', function()
assert.is_not_nil(global)
assert.is_not_nil(_G.global)
end)
it('Tests package.loaded persists without insulate', function()
assert.is_not_nil(Date)
assert.is_not_nil(package.loaded.pl)
assert.is_not_nil(package.loaded['pl.Date'])
end)
end)
describe('Tests after insulating an expose block', function()
it('restores global table _G', function()
assert.is_nil(global)
assert.is_nil(_G.global)
end)
it('restores package.loaded', function()
assert.is_nil(pl)
assert.is_nil(Date)
assert.is_nil(package.loaded.pl)
assert.is_nil(package.loaded['pl.Date'])
end)
end)
describe('Tests insulate/expose', function()
local path = require 'pl.path'
local utils = require 'pl.utils'
local busted_cmd = path.is_windows and 'lua bin/busted' or 'bin/busted'
local executeBusted = function(args)
local success, exitcode, out, err = utils.executeex(busted_cmd .. ' ' .. args)
if exitcode > 255 then
exitcode = math.floor(exitcode/256), exitcode - math.floor(exitcode/256)*256
end
return not not success, exitcode, out, err
end
describe('file insulation', function()
it('works between files', function()
local success, exitcode = executeBusted('spec/insulate_file1.lua spec/insulate_file2.lua')
assert.is_true(success)
assert.is_equal(0, exitcode)
end)
it('works between files independent of order', function()
local success, exitcode = executeBusted('spec/insulate_file2.lua spec/insulate_file1.lua')
assert.is_true(success)
assert.is_equal(0, exitcode)
end)
end)
describe('expose from file context', function()
it('works between files', function()
local success, exitcode = executeBusted('spec/expose_file1.lua spec/expose_file2.lua')
assert.is_true(success)
assert.is_equal(0, exitcode)
end)
end)
end)
|
Fix failing tests after penlight upgrade
|
Fix failing tests after penlight upgrade
This fixes failing unit tests after upgrading `penlight`. Apparently,
the new version of `penlight` uses `pl.List` internally when traversing
a directory. Hence, we cannot use `pl.List` in any of the insulation
tests.
|
Lua
|
mit
|
Olivine-Labs/busted,o-lim/busted
|
f60b15aaa33fdf7664773713bc45d218f07b36ab
|
pud/debug/Console.lua
|
pud/debug/Console.lua
|
local Class = require 'lib.hump.class'
local Deque = getClass 'pud.kit.Deque'
local format = string.format
local gprint = love.graphics.print
local draw = love.graphics.draw
local setRenderTarget = love.graphics.setRenderTarget
local rectangle = love.graphics.rectangle
local setColor = love.graphics.setColor
local setFont = love.graphics.setFont
local colors = colors
local MARGIN = 8
local BUFFER_SIZE = 100
local FONT = Font[16]
local FONT_H = FONT:getHeight()
local DRAWLINES = math.floor(HEIGHT/FONT_H)-3
local START_Y = math.floor(HEIGHT - (MARGIN + FONT_H))
-- Console
--
local Console = Class{name='Console',
function(self)
self._buffer = Deque()
self._firstLine = 0
local size = nearestPO2(math.max(WIDTH, HEIGHT))
self._ffb = love.graphics.newFramebuffer(size, size)
self._bfb = love.graphics.newFramebuffer(size, size)
end
}
-- destructor
function Console:destroy()
self._buffer:destroy()
self._buffer = nil
self._show = nil
self._firstLine = nil
self._ffb = nil
self._bfb = nil
end
function Console:clear()
self._buffer:clear()
self._firstLine = 0
self:_drawFB()
end
function Console:pgup()
self._firstLine = self._firstLine + DRAWLINES
local max = self._buffer:size() - DRAWLINES
if self._firstLine > max then self._firstLine = max end
self:_drawFB()
end
function Console:pgdn()
self._firstLine = self._firstLine - DRAWLINES
if self._firstLine < 0 then self._firstLine = 0 end
self:_drawFB()
end
function Console:bottom()
self._firstLine = 0
self:_drawFB()
end
function Console:top()
self._firstLine = self._buffer:size() - DRAWLINES
self:_drawFB()
end
function Console:hide() self._show = false end
function Console:show() self._show = true end
function Console:print(msg, ...)
if select('#', ...) > 0 then msg = format(msg, ...) end
self._buffer:push_front(msg)
if self._buffer:size() > BUFFER_SIZE then self._buffer:pop_back() end
self:_drawFB()
end
function Console:_drawFB()
setRenderTarget(self._bfb)
setColor(colors.BLACK_A70)
rectangle('fill', 0, 0, WIDTH, HEIGHT)
local count = DRAWLINES
local skip = 1
local drawX, drawY = MARGIN, START_Y
setFont(FONT)
setColor(colors.GREY90)
for line in self._buffer:iterate() do
if skip >= self._firstLine then
gprint(line, drawX, drawY)
drawY = drawY - FONT_H
count = count - 1
if count <= 0 then break end
end
skip = skip + 1
end
setRenderTarget()
self._ffb, self._bfb = self._bfb, self._ffb
end
function Console:draw()
if self._show and self._ffb then
setColor(colors.WHITE)
draw(self._ffb, 0, 0)
end
end
-- the class
return Console
|
local Class = require 'lib.hump.class'
local Deque = getClass 'pud.kit.Deque'
local format = string.format
local gprint = love.graphics.print
local draw = love.graphics.draw
local setRenderTarget = love.graphics.setRenderTarget
local rectangle = love.graphics.rectangle
local setColor = love.graphics.setColor
local setFont = love.graphics.setFont
local colors = colors
local MARGIN = 8
local BUFFER_SIZE = 1000
local FONT = GameFont.verysmall
local FONT_H = FONT:getHeight()
local DRAWLINES = math.floor(HEIGHT/FONT_H)-2
local START_Y = math.floor(HEIGHT - (MARGIN + FONT_H*2))
print(FONT_H,DRAWLINES,START_Y)
-- Console
--
local Console = Class{name='Console',
function(self)
self._buffer = Deque()
self._firstLine = 0
local size = nearestPO2(math.max(WIDTH, HEIGHT))
self._ffb = love.graphics.newFramebuffer(size, size)
self._bfb = love.graphics.newFramebuffer(size, size)
self:_drawFB()
end
}
-- destructor
function Console:destroy()
self._buffer:destroy()
self._buffer = nil
self._show = nil
self._firstLine = nil
self._ffb = nil
self._bfb = nil
end
function Console:clear()
self._buffer:clear()
self._firstLine = 0
self:_drawFB()
end
function Console:pageup()
self._firstLine = self._firstLine + DRAWLINES
local max = 1+(self._buffer:size() - DRAWLINES)
if self._firstLine > max then self._firstLine = max end
self:_drawFB()
end
function Console:pagedown()
self._firstLine = self._firstLine - DRAWLINES
if self._firstLine < 0 then self._firstLine = 0 end
self:_drawFB()
end
function Console:bottom()
self._firstLine = 0
self:_drawFB()
end
function Console:top()
self._firstLine = 1+(self._buffer:size() - DRAWLINES)
self:_drawFB()
end
function Console:hide() self._show = false end
function Console:show() self._show = true end
function Console:toggle() self._show = not self._show end
function Console:isVisible() return self._show == true end
function Console:print(msg, ...)
if select('#', ...) > 0 then msg = format(msg, ...) end
self._buffer:push_front(msg)
if self._buffer:size() > BUFFER_SIZE then self._buffer:pop_back() end
self:_drawFB()
end
function Console:_drawFB()
setRenderTarget(self._bfb)
setColor(colors.BLACK_A70)
rectangle('fill', 0, 0, WIDTH, HEIGHT)
local count = DRAWLINES
local skip = 1
local drawX, drawY = MARGIN, START_Y
setFont(FONT)
setColor(colors.GREY90)
for line in self._buffer:iterate() do
if skip >= self._firstLine then
gprint(line, drawX, drawY)
drawY = drawY - FONT_H
count = count - 1
if count <= 0 then break end
end
skip = skip + 1
end
setRenderTarget()
self._ffb, self._bfb = self._bfb, self._ffb
end
function Console:draw()
if self._show and self._ffb then
setColor(colors.WHITE)
draw(self._ffb, 0, 0)
end
end
-- the class
return Console
|
fix bugs
|
fix bugs
|
Lua
|
mit
|
scottcs/wyx
|
539c356fb96aba1a4a2a7cc5e2e89388088dc2a9
|
libs/core/luasrc/model/wireless.lua
|
libs/core/luasrc/model/wireless.lua
|
--[[
LuCI - Wireless model
Copyright 2009 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local pairs, i18n, uci, math = pairs, luci.i18n, luci.model.uci, math
local iwi = require "iwinfo"
local utl = require "luci.util"
local uct = require "luci.model.uci.bind"
module "luci.model.network.wireless"
local ub = uct.bind("wireless")
local st, ifs
function init(self, cursor)
cursor:unload("wireless")
cursor:load("wireless")
ub:init(cursor)
st = uci.cursor_state()
ifs = { }
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
local id = "%s.network%d" %{ self.device, count }
ifs[id] = {
id = id,
sid = s['.name'],
count = count
}
local dev = st:get("wireless", s['.name'], "ifname")
or st:get("wireless", s['.name'], "device")
local wtype = dev and iwi.type(dev)
if dev and wtype then
ifs[id].winfo = iwi[wtype]
ifs[id].wdev = dev
end
end)
end
function get_device(self, dev)
return device(dev)
end
function get_network(self, id)
if ifs[id] then
return network(ifs[id].sid)
else
local n
for n, _ in pairs(ifs) do
if ifs[n].sid == id then
return network(id)
end
end
end
end
function shortname(self, iface)
if iface.dev and iface.dev.wifi then
return "%s %q" %{
i18n.translate("a_s_if_iwmode_" .. (iface.dev.wifi.mode or "ap")),
iface.dev.wifi.ssid or iface.dev.wifi.bssid or "(hidden)"
}
else
return iface:name()
end
end
function get_i18n(self, iface)
if iface.dev and iface.dev.wifi then
return "%s: %s %q" %{
i18n.translate("a_s_if_wifinet", "Wireless Network"),
i18n.translate("a_s_if_iwmode_" .. (iface.dev.wifi.mode or "ap"), iface.dev.wifi.mode or "AP"),
iface.dev.wifi.ssid or iface.dev.wifi.bssid or "(hidden)"
}
else
return "%s: %q" %{ i18n.translate("a_s_if_wifinet", "Wireless Network"), iface:name() }
end
end
function rename_network(self, old, new)
local i
for i, _ in pairs(ifs) do
if ifs[i].network == old then
ifs[i].network = new
end
end
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.network == old then
if new then
ub.uci:set("wireless", s['.name'], "network", new)
else
ub.uci:delete("wireless", s['.name'], "network")
end
end
end)
end
function del_network(self, old)
return self:rename_network(old, nil)
end
function find_interfaces(self, iflist, brlist)
local iface
for iface, _ in pairs(ifs) do
iflist[iface] = ifs[iface]
end
end
function ignore_interface(self, iface)
if ifs and ifs[iface] then
return false
else
return iwi.type(iface) and true or false
end
end
function add_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:set("wireless", ifs[iface].sid, "network", net:name())
ifs[iface].network = net:name()
return true
end
return false
end
function del_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:delete("wireless", ifs[iface].sid, "network")
--return true
end
return false
end
device = ub:section("wifi-device")
device:property("type")
device:property("channel")
device:property("disabled")
function device.name(self)
return self.sid
end
function device.get_networks(self)
local nets = { }
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.device == self:name() then
nets[#nets+1] = network(s['.name'])
end
end)
return nets
end
network = ub:section("wifi-iface")
network:property("mode")
network:property("ssid")
network:property("bssid")
network:property("network")
function network._init(self, sid)
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
return s['.name'] ~= sid
end)
self.id = "%s.network%d" %{ self.device, count }
local dev = st:get("wireless", sid, "ifname")
or st:get("wireless", sid, "device")
local wtype = dev and iwi.type(dev)
if dev and wtype then
self.winfo = iwi[wtype]
self.wdev = dev
end
end
function network.name(self)
return self.id
end
function network.ifname(self)
return self.wdev
end
function network.get_device(self)
if self.device then
return device(self.device)
end
end
function network.active_mode(self)
local m = self.winfo and self.winfo.mode(self.wdev)
if m == "Master" or m == "Auto" then
m = "ap"
elseif m == "Ad-Hoc" then
m = "adhoc"
elseif m == "Client" then
m = "sta"
elseif m then
m = m:lower()
else
m = self:mode()
end
return m or "ap"
end
function network.active_mode_i18n(self)
return i18n.translate("a_s_if_iwmode_" .. self:active_mode())
end
function network.active_ssid(self)
return self.winfo and self.winfo.ssid(self.wdev) or
self:ssid()
end
function network.active_bssid(self)
return self.winfo and self.winfo.bssid(self.wdev) or
self:bssid() or "00:00:00:00:00:00"
end
function network.signal(self)
return self.winfo and self.winfo.signal(self.wdev) or 0
end
function network.noise(self)
return self.winfo and self.winfo.noise(self.wdev) or 0
end
function network.signal_level(self)
if self:active_bssid() ~= "00:00:00:00:00:00" then
local signal = self:signal()
local noise = self:noise()
if signal > 0 and noise > 0 then
local snr = -1 * (noise - signal)
return math.floor(snr / 5)
else
return 0
end
else
return -1
end
end
function network.signal_percent(self)
local qc = self.winfo and
self.winfo.quality(self.wdev) or 0
local qm = self.winfo and
self.winfo.quality_max(self.wdev) or 0
if qc > 0 and qm > 0 then
return math.floor((100 / qm) * qc)
else
return 0
end
end
|
--[[
LuCI - Wireless model
Copyright 2009 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local pairs, i18n, uci, math = pairs, luci.i18n, luci.model.uci, math
local iwi = require "iwinfo"
local utl = require "luci.util"
local uct = require "luci.model.uci.bind"
module "luci.model.wireless"
local ub = uct.bind("wireless")
local st, ifs
function init(cursor)
cursor:unload("wireless")
cursor:load("wireless")
ub:init(cursor)
st = uci.cursor_state()
ifs = { }
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
local id = "%s.network%d" %{ s.device, count }
ifs[id] = {
id = id,
sid = s['.name'],
count = count
}
local dev = st:get("wireless", s['.name'], "ifname")
or st:get("wireless", s['.name'], "device")
local wtype = dev and iwi.type(dev)
if dev and wtype then
ifs[id].winfo = iwi[wtype]
ifs[id].wdev = dev
end
end)
end
function get_device(self, dev)
return device(dev)
end
function get_network(self, id)
if ifs[id] then
return network(ifs[id].sid)
else
local n
for n, _ in pairs(ifs) do
if ifs[n].sid == id then
return network(id)
end
end
end
end
function shortname(self, iface)
if iface.wdev and iface.winfo then
return "%s %q" %{
i18n.translate("a_s_if_iwmode_" .. iface:active_mode(), iface.winfo.mode(iface.wdev)),
iface:active_ssid() or "(hidden)"
}
else
return iface:name()
end
end
function get_i18n(self, iface)
if iface.wdev and iface.winfo then
return "%s: %s %q (%s)" %{
i18n.translate("a_s_if_wifinet", "Wireless Network"),
i18n.translate("a_s_if_iwmode_" .. iface:active_mode(), iface.winfo.mode(iface.wdev)),
iface:active_ssid() or "(hidden)", iface.wdev
}
else
return "%s: %q" %{ i18n.translate("a_s_if_wifinet", "Wireless Network"), iface:name() }
end
end
function rename_network(self, old, new)
local i
for i, _ in pairs(ifs) do
if ifs[i].network == old then
ifs[i].network = new
end
end
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.network == old then
if new then
ub.uci:set("wireless", s['.name'], "network", new)
else
ub.uci:delete("wireless", s['.name'], "network")
end
end
end)
end
function del_network(self, old)
return self:rename_network(old, nil)
end
function find_interfaces(self, iflist, brlist)
local iface
for iface, _ in pairs(ifs) do
iflist[iface] = ifs[iface]
end
end
function ignore_interface(self, iface)
if ifs and ifs[iface] then
return false
else
return iwi.type(iface) and true or false
end
end
function add_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:set("wireless", ifs[iface].sid, "network", net:name())
ifs[iface].network = net:name()
return true
end
return false
end
function del_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:delete("wireless", ifs[iface].sid, "network")
--return true
end
return false
end
device = ub:section("wifi-device")
device:property("type")
device:property("channel")
device:property("disabled")
function device.name(self)
return self.sid
end
function device.get_networks(self)
local nets = { }
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.device == self:name() then
nets[#nets+1] = network(s['.name'])
end
end)
return nets
end
network = ub:section("wifi-iface")
network:property("mode")
network:property("ssid")
network:property("bssid")
network:property("network")
function network._init(self, sid)
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
return s['.name'] ~= sid
end)
local dev = st:get("wireless", sid, "ifname")
or st:get("wireless", sid, "device")
if dev then
self.id = "%s.network%d" %{ dev, count }
local wtype = iwi.type(dev)
if dev and wtype then
self.winfo = iwi[wtype]
self.wdev = dev
end
end
end
function network.name(self)
return self.id
end
function network.ifname(self)
return self.wdev
end
function network.get_device(self)
if self.device then
return device(self.device)
end
end
function network.active_mode(self)
local m = self.winfo and self.winfo.mode(self.wdev)
if m == "Master" or m == "Auto" then
m = "ap"
elseif m == "Ad-Hoc" then
m = "adhoc"
elseif m == "Client" then
m = "sta"
elseif m then
m = m:lower()
else
m = self:mode()
end
return m or "ap"
end
function network.active_mode_i18n(self)
return i18n.translate("a_s_if_iwmode_" .. self:active_mode())
end
function network.active_ssid(self)
return self.winfo and self.winfo.ssid(self.wdev) or
self:ssid()
end
function network.active_bssid(self)
return self.winfo and self.winfo.bssid(self.wdev) or
self:bssid() or "00:00:00:00:00:00"
end
function network.signal(self)
return self.winfo and self.winfo.signal(self.wdev) or 0
end
function network.noise(self)
return self.winfo and self.winfo.noise(self.wdev) or 0
end
function network.signal_level(self)
if self:active_bssid() ~= "00:00:00:00:00:00" then
local signal = self:signal()
local noise = self:noise()
if signal > 0 and noise > 0 then
local snr = -1 * (noise - signal)
return math.floor(snr / 5)
else
return 0
end
else
return -1
end
end
function network.signal_percent(self)
local qc = self.winfo and
self.winfo.quality(self.wdev) or 0
local qm = self.winfo and
self.winfo.quality_max(self.wdev) or 0
if qc > 0 and qm > 0 then
return math.floor((100 / qm) * qc)
else
return 0
end
end
|
libs/core: fixes luci.model.wireless
|
libs/core: fixes luci.model.wireless
|
Lua
|
apache-2.0
|
8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci
|
09bc6664e537458416e82397aa37bfb07ad22afd
|
fusion/core/lexer.lua
|
fusion/core/lexer.lua
|
local re = require("re");
local defs = {}
defs['true'] = function() return true end
defs['false'] = function() return false end
defs['bool'] = function(...) return defs[(...)]() end
defs['numberify'] = tonumber
function defs:transform_binary_expression()
table.insert(self, 1, 'expression')
self.type = 'binary'
return self
end
local pattern = re.compile([[
statement_list <- {| (statement ws)* |}
statement_block <- '{' ws statement_list ws '}'
statement <- (
function_call /
assignment /
return /
{| {'break'} |}
) ws ';' ws / (
statement_block
) / (
while_loop /
numeric_for_loop /
iterative_for_loop /
function_definition /
if /
class
)
class <- {| 'new' -> 'class' space {:name: name :}
(ws 'extends' ws {:extends: variable :})? ws
'{' ws {| (class_field ws)* |} ws '}'
|}
class_field <-
function_definition /
{| '' -> 'class_field'
({:name: name :} ws '=' ws expression ws ';') /
('[' ws {:name: name :} ws ']' ws '=' ws expression ws ';')
|}
return <- {| {'return' / 'yield'} ws expression_list? |}
lambda <- {| '' -> 'lambda'
function_body
|}
function_definition <- {| '' -> 'function_definition'
{:is_async: 'async' -> true :}? ws
variable ws function_body
|}
function_body <-
'(' ws function_defined_arguments? ws ')' ws
({:is_self: '=' -> true :} / '-') '>' ws
(statement / expression_list)
function_defined_arguments <- {|
function_argument (ws ',' ws function_argument)*
|}
function_argument <- {|
{:name: name :} (ws '=' ws {:default: expression :})?
|}
while_loop <- {| '' -> 'while_loop'
'while' ws {:condition: expression :} ws statement
|}
iterative_for_loop <- {| '' -> 'iterative_for_loop'
'for' ws '(' ws name_list ws 'in' ws expression ws ')' ws statement
|}
numeric_for_loop <- {| '' -> 'numeric_for_loop'
'for' ws numeric_for_assignment ws statement
|}
numeric_for_assignment <- '('
{:incremented_variable: name :} ws '=' ws
{:start: expression :} ws
',' ws {:stop: expression :} ws
(',' ws {:step: expression :})?
')'
if <- {|
{'if'} ws {:condition: expression :} ws statement
(ws 'else' ws {:else: statement :})?
|}
function_call <- {| '' -> 'function_call' (
variable ({:has_self: ':' -> true :} variable ws
{:index_class: ws '<' ws {value} ws '>' :}? )?
ws '(' ws function_call_body? ws ')'
) |}
function_call_body <- {:generator: {|
expression (ws 'for' ws variable_list)? ws 'in' ws expression
|} :} / function_args
function_args <- expression_list?
assignment <- {| '' -> 'assignment'
{|
(variable_list ws '=' ws expression_list) /
({:is_local: 'local' -> true :} space name_list ws '=' ws
expression_list)
|}
|}
name_list <- {:variable_list: {|
local_name (ws ',' ws local_name)*
|} :} / {:variable_list: {|
{:is_destructuring: '' -> true :}
'{' ws local_name (ws ',' ws local_name)* ws '}'
|} :}
local_name <- {| '' -> 'variable' name |}
expression_list <- {:expression_list: {|
expression (ws ',' ws expression)*
|} :}
expression <- value / {| '' -> 'expression'
'(' ws operator (ws expression)+ ws ')'
|}
operator <- {:operator:
'//' /
'>>' /
'<<' /
[=!<>] '=' /
'&&' /
'||' /
'..' /
[-!#~+*/%^&|<>]
:}
value <-
lambda /
function_call /
literal /
variable /
'(' expression ')'
variable_list <- {:variable_list: {|
variable (ws ',' ws variable)*
|} :}
variable <- {| '' -> 'variable'
name ws ('.' ws name / ws '[' ws value ws ']')*
|}
name <- {[A-Za-z_][A-Za-z0-9_]*}
literal <-
table /
{| '' -> 'vararg' { '...' } |} /
number /
string /
{| '' -> 'boolean'
('true' / 'false') -> bool
|} /
{| {'nil' -> 'nil'} |}
number <- {| '' -> 'number' {:is_negative: '-' -> true :}? (
base16num /
base10num
) |}
base10num <- {:type: '' -> 'base10' :} {
((integer '.' integer) /
(integer '.') /
('.' integer) /
integer) int_exponent?
} -> numberify
integer <- [0-9]+
int_exponent <- [eE] [+-]? integer
base16num <- {:type: '' -> 'base16' :} {
'0' [Xx] [0-9A-Fa-f]+ hex_exponent?
} -> numberify
hex_exponent <- [pP] [+-]? integer
string <- {| dqstring / sqstring / blstring |}
dqstring <- '' -> 'dqstring' '"' { (('\\' .) / ([^\r\n"]))* } '"'
sqstring <- '' -> 'sqstring' "'" { [^\r\n']* } "'"
blstring <- '' -> 'blstring' '[' {:eq: '='* :} '[' blclose
blclose <- ']' =eq ']' / . blclose
table <- {| '' -> 'table' '{' ws -- TODO `for` constructor
(
table_generator /
table_field (ws ',' ws table_field)*
)?
ws '}' |}
table_generator <- {| '' -> 'generator'
table_field (ws 'for' ws variable_list)? ws 'in' ws expression
|}
table_field <-
{| '[' ws {:index: variable :} ws ']' ws '=' ws expression |} /
{| {:name: name :} ws '=' ws expression |} /
expression
ws <- %s*
space <- %s+
]], defs);
return pattern
|
local re = require("re");
local defs = {}
defs['true'] = function() return true end
defs['false'] = function() return false end
defs['bool'] = function(...) return defs[(...)]() end
defs['numberify'] = tonumber
function defs:transform_binary_expression()
table.insert(self, 1, 'expression')
self.type = 'binary'
return self
end
local pattern = re.compile([[
statement_list <- {| (statement ws)* |}
statement_block <- '{' ws statement_list ws '}'
statement <- (
function_call /
assignment /
return /
{| {'break'} |}
) ws ';' ws / (
statement_block
) / (
while_loop /
numeric_for_loop /
iterative_for_loop /
function_definition /
if /
class
)
class <- {| 'new' -> 'class' space {:name: name :}
(ws 'extends' ws {:extends: variable :})? ws
'{' ws {| (class_field ws)* |} ws '}'
|}
class_field <-
function_definition /
{| '' -> 'class_field'
(
'[' ws {:name: variable :} ws ']' ws '=' ws expression ws ';' /
{:name: name :} ws '=' ws expression ws ';'
)
|}
return <- {| {'return' / 'yield'} ws expression_list? |}
lambda <- {| '' -> 'lambda'
function_body
|}
function_definition <- {| '' -> 'function_definition'
{:is_async: 'async' -> true :}? ws
variable ws function_body
|}
function_body <-
'(' ws function_defined_arguments? ws ')' ws
({:is_self: '=' -> true :} / '-') '>' ws
(statement / expression_list)
function_defined_arguments <- {|
function_argument (ws ',' ws function_argument)*
|}
function_argument <- {|
{:name: name :} (ws '=' ws {:default: expression :})?
|}
while_loop <- {| '' -> 'while_loop'
'while' ws {:condition: expression :} ws statement
|}
iterative_for_loop <- {| '' -> 'iterative_for_loop'
'for' ws '(' ws name_list ws 'in' ws expression ws ')' ws statement
|}
numeric_for_loop <- {| '' -> 'numeric_for_loop'
'for' ws numeric_for_assignment ws statement
|}
numeric_for_assignment <- '('
{:incremented_variable: name :} ws '=' ws
{:start: expression :} ws
',' ws {:stop: expression :} ws
(',' ws {:step: expression :})?
')'
if <- {|
{'if'} ws {:condition: expression :} ws statement
(ws 'else' ws {:else: statement :})?
|}
function_call <- {| '' -> 'function_call' (
variable ({:has_self: ':' -> true :} variable ws
{:index_class: ws '<' ws {value} ws '>' :}? )?
ws '(' ws function_call_body? ws ')'
) |}
function_call_body <- {:generator: {|
expression (ws 'for' ws variable_list)? ws 'in' ws expression
|} :} / function_args
function_args <- expression_list?
assignment <- {| '' -> 'assignment'
{|
(variable_list ws '=' ws expression_list) /
({:is_local: 'local' -> true :} space name_list ws '=' ws
expression_list)
|}
|}
name_list <- {:variable_list: {|
local_name (ws ',' ws local_name)*
|} :} / {:variable_list: {|
{:is_destructuring: '' -> true :}
'{' ws local_name (ws ',' ws local_name)* ws '}'
|} :}
local_name <- {| '' -> 'variable' name |}
expression_list <- {:expression_list: {|
expression (ws ',' ws expression)*
|} :}
expression <- value / {| '' -> 'expression'
'(' ws operator (ws expression)+ ws ')'
|}
operator <- {:operator:
'//' /
'>>' /
'<<' /
[=!<>] '=' /
'&&' /
'||' /
'..' /
[-!#~+*/%^&|<>]
:}
value <-
lambda /
function_call /
literal /
variable /
'(' expression ')'
variable_list <- {:variable_list: {|
variable (ws ',' ws variable)*
|} :}
variable <- {| '' -> 'variable'
name ws ('.' ws name / ws '[' ws value ws ']')*
|}
name <- {[A-Za-z_][A-Za-z0-9_]*}
literal <-
table /
{| '' -> 'vararg' { '...' } |} /
number /
string /
{| '' -> 'boolean'
('true' / 'false') -> bool
|} /
{| {'nil' -> 'nil'} |}
number <- {| '' -> 'number' {:is_negative: '-' -> true :}? (
base16num /
base10num
) |}
base10num <- {:type: '' -> 'base10' :} {
((integer '.' integer) /
(integer '.') /
('.' integer) /
integer) int_exponent?
} -> numberify
integer <- [0-9]+
int_exponent <- [eE] [+-]? integer
base16num <- {:type: '' -> 'base16' :} {
'0' [Xx] [0-9A-Fa-f]+ hex_exponent?
} -> numberify
hex_exponent <- [pP] [+-]? integer
string <- {| dqstring / sqstring / blstring |}
dqstring <- '' -> 'dqstring' '"' { (('\\' .) / ([^\r\n"]))* } '"'
sqstring <- '' -> 'sqstring' "'" { [^\r\n']* } "'"
blstring <- '' -> 'blstring' '[' {:eq: '='* :} '[' blclose
blclose <- ']' =eq ']' / . blclose
table <- {| '' -> 'table' '{' ws -- TODO `for` constructor
(
table_generator /
table_field (ws ',' ws table_field)*
)?
ws '}' |}
table_generator <- {| '' -> 'generator'
table_field (ws 'for' ws variable_list)? ws 'in' ws expression
|}
table_field <-
{| '[' ws {:index: variable :} ws ']' ws '=' ws expression |} /
{| {:name: name :} ws '=' ws expression |} /
expression
ws <- %s*
space <- %s+
]], defs);
return pattern
|
lexer.lua: fix parsing class fields
|
lexer.lua: fix parsing class fields
|
Lua
|
mit
|
RyanSquared/FusionScript
|
a8a4c2bfcb35e72aef89ea4f6179e9d2997908ae
|
src_trunk/resources/item-system/c_books.lua
|
src_trunk/resources/item-system/c_books.lua
|
wBook, buttonClose, buttonPrev, buttonNext, page, cover, pgNumber, xml, pane = nil
pageNumber = 0
totalPages = 0
function createBook( bookName, bookTitle )
-- Window variables
local Width = 460
local Height = 520
local screenwidth, screenheight = guiGetScreenSize()
local X = (screenwidth - Width)/2
local Y = (screenheight - Height)/2
outputChatBox(tostring(wBook))
if not (wBook) then
pageNumber = 0
-- Create the window
wBook = guiCreateWindow(X, Y, Width, Height, bookTitle, false)
cover = guiCreateStaticImage ( 0.01, 0.05, 0.8, 0.95, "books/".. bookName ..".png", true, wBook ) -- display the cover image.
-- Create close, previous and Next Button
buttonPrev = guiCreateButton( 0.85, 0.25, 0.14, 0.05, "Prev", true, wBook)
addEventHandler( "onClientGUIClick", buttonPrev, prevButtonClick, false )
guiSetVisible(buttonPrev, false)
buttonClose = guiCreateButton( 0.85, 0.45, 0.14, 0.05, "Close", true, wBook)
addEventHandler( "onClientGUIClick", buttonClose, closeButtonClick, false )
buttonNext = guiCreateButton( 0.85, 0.65, 0.14, 0.05, "Next", true, wBook)
addEventHandler( "onClientGUIClick", buttonNext, nextButtonClick, false )
showCursor(true)
-- the pages
pane = guiCreateScrollPane(0.01, 0.05, 0.8, 0.9, true, wBook)
guiScrollPaneSetScrollBars(pane, false, true)
page = guiCreateLabel(0.01, 0.05, 0.8, 2.0, "", true, pane) -- create the page but leave it blank.
guiLabelSetHorizontalAlign (page, "left", true)
pgNumber = guiCreateLabel(0.95, 0.0, 0.05, 1.0, "",true, wBook) -- page number at the bottom.
guiSetVisible(pane, false)
xml = xmlLoadFile( "/books/" .. bookName .. ".xml" ) -- load the xml.
local numpagesNode = xmlFindChild(xml,"numPages", 0) -- get the children of the root node "content". Should return the "page"..pageNumber nodes in a table.
totalPages = tonumber(xmlNodeGetValue(numpagesNode))
end
end
addEvent("showBook", true)
addEventHandler("showBook", getRootElement(), createBook)
--The "prev" button's function
function prevButtonClick( )
pageNumber = pageNumber - 1
if (pageNumber == 0) then
guiSetVisible(buttonPrev, false)
guiSetVisible(pane, false)
else
guiSetVisible(buttonPrev, true)
guiSetVisible(pane, true)
end
if (pageNumber == totalPages) then
guiSetVisible(buttonNext, false)
else
guiSetVisible(buttonNext, true)
end
if (pageNumber>0) then -- if the new page is not the cover
local pageNode = xmlFindChild (xml, "page", pageNumber-1)
local contents = xmlNodeGetValue( pageNode )
guiSetText (page, contents)
guiSetText (pgNumber, pageNumber)
else -- if we are moving to the cover
guiSetVisible(buttonNext, true)
guiSetVisible(cover, true)
guiSetText (page, "")
guiSetText (pgNumber, "")
end
end
--The "next" button's function
function nextButtonClick( )
pageNumber = pageNumber + 1
if (pageNumber == 0) then
guiSetVisible(buttonPrev, false)
guiSetVisible(pane, false)
else
guiSetVisible(buttonPrev, true)
guiSetVisible(pane, true)
end
if (pageNumber == totalPages) then
guiSetVisible(buttonNext, false)
else
guiSetVisible(buttonNext, true)
end
if (pageNumber-1==0) then -- If the last page was the cover page remove the cover image.
guiSetVisible(cover, false)
end
local pageNode = xmlFindChild (xml, "page", pageNumber-1)
local contents = xmlNodeGetValue( pageNode )
guiSetText ( page, contents )
guiSetText ( pgNumber, pageNumber )
end
-- The "close" button's function
function closeButtonClick( )
pageNumber = 0
totalPages = 0
destroyElement ( page )
destroyElement ( pane )
destroyElement ( buttonClose )
destroyElement ( buttonPrev )
destroyElement ( buttonNext )
destroyElement ( cover)
destroyElement ( pgNumber )
destroyElement ( wBook )
buttonClose = nil
buttonPrev = nil
buttonNext = nil
pane = nil
page = nil
cover = nil
pgNumber = nil
wBook = nil
showCursor(false)
xmlUnloadFile(xml)
xml = nil
end
|
wBook, buttonClose, buttonPrev, buttonNext, page, cover, pgNumber, xml, pane = nil
pageNumber = 0
totalPages = 0
function createBook( bookName, bookTitle )
-- Window variables
local Width = 460
local Height = 520
local screenwidth, screenheight = guiGetScreenSize()
local X = (screenwidth - Width)/2
local Y = (screenheight - Height)/2
if not (wBook) then
pageNumber = 0
-- Create the window
wBook = guiCreateWindow(X, Y, Width, Height, bookTitle, false)
cover = guiCreateStaticImage ( 0.01, 0.05, 0.8, 0.95, "books/".. bookName ..".png", true, wBook ) -- display the cover image.
-- Create close, previous and Next Button
buttonPrev = guiCreateButton( 0.85, 0.25, 0.14, 0.05, "Prev", true, wBook)
addEventHandler( "onClientGUIClick", buttonPrev, prevButtonClick, false )
guiSetVisible(buttonPrev, false)
buttonClose = guiCreateButton( 0.85, 0.45, 0.14, 0.05, "Close", true, wBook)
addEventHandler( "onClientGUIClick", buttonClose, closeButtonClick, false )
buttonNext = guiCreateButton( 0.85, 0.65, 0.14, 0.05, "Next", true, wBook)
addEventHandler( "onClientGUIClick", buttonNext, nextButtonClick, false )
showCursor(true)
-- the pages
pane = guiCreateScrollPane(0.01, 0.05, 0.8, 0.9, true, wBook)
guiScrollPaneSetScrollBars(pane, false, true)
page = guiCreateLabel(0.01, 0.05, 0.8, 2.0, "", true, pane) -- create the page but leave it blank.
guiLabelSetHorizontalAlign (page, "left", true)
pgNumber = guiCreateLabel(0.95, 0.0, 0.05, 1.0, "",true, wBook) -- page number at the bottom.
guiSetVisible(pane, false)
xml = xmlLoadFile( "/books/" .. bookName .. ".xml" ) -- load the xml.
local numpagesNode = xmlFindChild(xml,"numPages", 0) -- get the children of the root node "content". Should return the "page"..pageNumber nodes in a table.
totalPages = tonumber(xmlNodeGetValue(numpagesNode))
end
end
addEvent("showBook", true)
addEventHandler("showBook", getRootElement(), createBook)
--The "prev" button's function
function prevButtonClick( )
pageNumber = pageNumber - 1
if (pageNumber == 0) then
guiSetVisible(buttonPrev, false)
guiSetVisible(pane, false)
else
guiSetVisible(buttonPrev, true)
guiSetVisible(pane, true)
end
if (pageNumber == totalPages) then
guiSetVisible(buttonNext, false)
else
guiSetVisible(buttonNext, true)
end
if (pageNumber>0) then -- if the new page is not the cover
local pageNode = xmlFindChild (xml, "page", pageNumber-1)
local contents = xmlNodeGetValue( pageNode )
guiSetText (page, contents)
guiSetText (pgNumber, pageNumber)
else -- if we are moving to the cover
guiSetVisible(buttonNext, true)
guiSetVisible(cover, true)
guiSetText (page, "")
guiSetText (pgNumber, "")
end
end
--The "next" button's function
function nextButtonClick( )
pageNumber = pageNumber + 1
if (pageNumber == 0) then
guiSetVisible(buttonPrev, false)
guiSetVisible(pane, false)
else
guiSetVisible(buttonPrev, true)
guiSetVisible(pane, true)
end
if (pageNumber == totalPages) then
guiSetVisible(buttonNext, false)
else
guiSetVisible(buttonNext, true)
end
if (pageNumber-1==0) then -- If the last page was the cover page remove the cover image.
guiSetVisible(cover, false)
end
local pageNode = xmlFindChild (xml, "page", pageNumber-1)
local contents = xmlNodeGetValue( pageNode )
guiSetText ( page, contents )
guiSetText ( pgNumber, pageNumber )
end
-- The "close" button's function
function closeButtonClick( )
pageNumber = 0
totalPages = 0
destroyElement ( page )
destroyElement ( pane )
destroyElement ( buttonClose )
destroyElement ( buttonPrev )
destroyElement ( buttonNext )
destroyElement ( cover)
destroyElement ( pgNumber )
destroyElement ( wBook )
buttonClose = nil
buttonPrev = nil
buttonNext = nil
pane = nil
page = nil
cover = nil
pgNumber = nil
wBook = nil
showCursor(false)
xmlUnloadFile(xml)
xml = nil
end
|
Bug fix for books
|
Bug fix for books
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@483 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
7f2c14bd494642dd81bab8583d7f9fa78998aba1
|
App/NevermoreEngine.lua
|
App/NevermoreEngine.lua
|
--- Nevermore module loader.
-- Used to simply resource loading and networking so a more unified server / client codebased can be used
-- @module Nevermore
local DEBUG_MODE = false -- Set to true to help identify what libraries have circular dependencies
local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerScriptService = game:GetService("ServerScriptService")
assert(script:IsA("ModuleScript"), "Invalid script type. For NevermoreEngine to work correctly, it should be a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage")
assert(script.Name == "NevermoreEngine", "Invalid script name. For NevermoreEngine to work correctly, it should be a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage")
assert(script.Parent == ReplicatedStorage, "Invalid parent. For NevermoreEngine to work correctly, it should be a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage")
--- Handles yielded operations by caching the retrieval process
local function _handleRetrieving(Retrieving, Function, Argument)
assert(type(Retrieving) == "table", "Error: Retrieving must be a table")
assert(type(Function) == "function", "Error: Function must be a function")
local Signal = Instance.new("BindableEvent")
local Result
Retrieving[Argument] = function()
if Result ~= nil and Result then
return Result
end
Signal.Event:Wait()
return Result
end
Result = Function(Argument)
assert(Result ~= nil, "Result cannot be nil")
Retrieving[Argument] = nil
Signal:Fire()
Signal:Destroy()
return Result
end
--- Caches single argument, single output only
local function _asyncCache(Function)
assert(type(Function) == "function", "Error: Function must be a userdata")
local Cache = {}
local Retrieving = {}
return function(Argument)
assert(Argument ~= nil, "Error: ARgument ")
if Cache[Argument] ~= nil then
return Cache[Argument]
elseif Retrieving[Argument] then
return Retrieving[Argument]()
else
Cache[Argument] = _handleRetrieving(Retrieving, Function, Argument)
return Cache[Argument]
end
end
end
--- Retrieves an instance from a parent
local function _retrieve(Parent, ClassName)
assert(type(ClassName) == "string", "Error: ClassName must be a string")
assert(typeof(Parent) == "Instance", ("Error: Parent must be an Instance, got '%s'"):format(typeof(Parent)))
return RunService:IsServer() and function(Name)
local Item = Parent:FindFirstChild(Name)
if not Item then
Item = Instance.new(ClassName)
Item.Archivable = false
Item.Name = Name
Item.Parent = Parent
end
return Item
end or function(Name)
local Resource = Parent:WaitForChild(Name, 5)
if Resource then
return Resource
end
warn(("Warning: No '%s' found, be sure to require '%s' on the server. Yielding for '%s'"):format(tostring(Name), tostring(Name), ClassName))
return Parent:WaitForChild(Name)
end
end
local function _getRepository(GetSubFolder)
if RunService:IsServer() then
local RepositoryFolder = ServerScriptService:FindFirstChild("Nevermore")
if not RepositoryFolder then
warn("Warning: No repository of Nevermore modules found (Expected in ServerScriptService with name \"Nevermore\"). Library retrieval will fail.")
RepositoryFolder = Instance.new("Folder")
RepositoryFolder.Name = "Nevermore"
end
return RepositoryFolder
else
return GetSubFolder("Modules")
end
end
local function _getLibraryCache(RepositoryFolder)
local LibraryCache = {}
for _, Child in pairs(RepositoryFolder:GetDescendants()) do
if Child:IsA("ModuleScript") then
if LibraryCache[Child.Name] then
error(("Error: Duplicate name of '%s' already exists"):format(Child.Name))
end
LibraryCache[Child.Name] = Child
end
end
return LibraryCache
end
local function _replicateRepository(ReplicationFolder, LibraryCache)
for Name, Library in pairs(LibraryCache) do
if not Name:lower():find("server") then
Library.Parent = ReplicationFolder
end
end
end
local function _debugLoading(Function)
local Count = 0
local RequestDepth = 0
return function(Module, ...)
Count = Count + 1
local LibraryID = Count
if DEBUG_MODE then
print(("\t"):rep(RequestDepth), LibraryID, "Loading: ", Module)
RequestDepth = RequestDepth + 1
end
local Result = Function(Module, ...)
if DEBUG_MODE then
RequestDepth = RequestDepth - 1
print(("\t"):rep(RequestDepth), LibraryID, "Done loading: ", Module)
end
return Result
end
end
local function _getLibraryLoader(LibraryCache)
--- Loads a library from Nevermore's library cache
-- @param Module The name of the library or a module
-- @return The library's value
return function(Module)
if typeof(Module) == "Instance" and Module:IsA("ModuleScript") then
return require(Module)
elseif type(Module) == "string" then
local ModuleScript = LibraryCache[Module] or error("Error: Library '" .. Module .. "' does not exist.", 2)
return require(ModuleScript)
else
error(("Error: Module must be a string or ModuleScript, got '%s'"):format(typeof(Module)))
end
end
end
local ResourceFolder = _retrieve(ReplicatedStorage, "Folder")("NevermoreResources")
local GetSubFolder = _retrieve(ResourceFolder, "Folder")
local RepositoryFolder = _getRepository(GetSubFolder)
local LibraryCache = _getLibraryCache(RepositoryFolder)
if RunService:IsServer() and not RunService:IsClient() then -- Don't move in SoloTestMode
_replicateRepository(GetSubFolder("Modules"), LibraryCache)
end
local Nevermore = {}
--- Load a library through Nevermore
-- @function LoadLibrary
-- @tparam string LibraryName
Nevermore.LoadLibrary = _asyncCache(_debugLoading(_getLibraryLoader(LibraryCache)))
--- Get a remote event
-- @function GetRemoteEvent
-- @tparam string RemoteEventName
-- @return RemoteEvent
Nevermore.GetRemoteEvent = _asyncCache(_retrieve(GetSubFolder("RemoteEvents"), "RemoteEvent"))
--- Get a remote function
-- @function GetRemoteFunction
-- @tparam string RemoteFunctionName
-- @return RemoteFunction
Nevermore.GetRemoteFunction = _asyncCache(_retrieve(GetSubFolder("RemoteFunctions"), "RemoteFunction"))
setmetatable(Nevermore, {
__call = Nevermore.LoadLibrary;
__index = function(self, Index)
error(("'%s is not a valid member of Nevermore"):format(tostring(Index)))
end;
})
return Nevermore
|
--- Nevermore module loader.
-- Used to simply resource loading and networking so a more unified server / client codebased can be used
-- @module Nevermore
local DEBUG_MODE = false -- Set to true to help identify what libraries have circular dependencies
local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerScriptService = game:GetService("ServerScriptService")
assert(script:IsA("ModuleScript"), "Invalid script type. For NevermoreEngine to work correctly, it should be a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage")
assert(script.Name == "NevermoreEngine", "Invalid script name. For NevermoreEngine to work correctly, it should be a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage")
assert(script.Parent == ReplicatedStorage, "Invalid parent. For NevermoreEngine to work correctly, it should be a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage")
--- Handles yielded operations by caching the retrieval process
local function _handleRetrieving(Retrieving, Function, Argument)
assert(type(Retrieving) == "table", "Error: Retrieving must be a table")
assert(type(Function) == "function", "Error: Function must be a function")
local Signal = Instance.new("BindableEvent")
local Result
Retrieving[Argument] = function()
if Result ~= nil and Result then
return Result
end
Signal.Event:Wait()
return Result
end
Result = Function(Argument)
assert(Result ~= nil, "Result cannot be nil")
Retrieving[Argument] = nil
Signal:Fire()
Signal:Destroy()
return Result
end
--- Caches single argument, single output only
local function _asyncCache(Function)
assert(type(Function) == "function", "Error: Function must be a userdata")
local Cache = {}
local Retrieving = {}
return function(Argument)
assert(Argument ~= nil, "Error: ARgument ")
if Cache[Argument] ~= nil then
return Cache[Argument]
elseif Retrieving[Argument] then
return Retrieving[Argument]()
else
Cache[Argument] = _handleRetrieving(Retrieving, Function, Argument)
return Cache[Argument]
end
end
end
--- Retrieves an instance from a parent
local function _retrieve(Parent, ClassName)
assert(type(ClassName) == "string", "Error: ClassName must be a string")
assert(typeof(Parent) == "Instance", ("Error: Parent must be an Instance, got '%s'"):format(typeof(Parent)))
return RunService:IsServer() and function(Name)
local Item = Parent:FindFirstChild(Name)
if not Item then
Item = Instance.new(ClassName)
Item.Archivable = false
Item.Name = Name
Item.Parent = Parent
end
return Item
end or function(Name)
local Resource = Parent:WaitForChild(Name, 5)
if Resource then
return Resource
end
warn(("Warning: No '%s' found, be sure to require '%s' on the server. Yielding for '%s'"):format(tostring(Name), tostring(Name), ClassName))
return Parent:WaitForChild(Name)
end
end
local function _getRepository(GetSubFolder)
if RunService:IsServer() then
local RepositoryFolder = ServerScriptService:FindFirstChild("Nevermore")
if not RepositoryFolder then
warn("Warning: No repository of Nevermore modules found (Expected in ServerScriptService with name \"Nevermore\"). Library retrieval will fail.")
RepositoryFolder = Instance.new("Folder")
RepositoryFolder.Name = "Nevermore"
end
return RepositoryFolder
else
return GetSubFolder("Modules")
end
end
local function _getLibraryCache(RepositoryFolder)
local LibraryCache = {}
for _, Child in pairs(RepositoryFolder:GetDescendants()) do
if Child:IsA("ModuleScript") and not Child:FindFirstAncestorOfClass("ModuleScript") then
if LibraryCache[Child.Name] then
error(("Error: Duplicate name of '%s' already exists"):format(Child.Name))
end
LibraryCache[Child.Name] = Child
end
end
return LibraryCache
end
local function _replicateRepository(ReplicationFolder, LibraryCache)
for Name, Library in pairs(LibraryCache) do
if not Name:lower():find("server") then
Library.Parent = ReplicationFolder
end
end
end
local function _debugLoading(Function)
local Count = 0
local RequestDepth = 0
return function(Module, ...)
Count = Count + 1
local LibraryID = Count
if DEBUG_MODE then
print(("\t"):rep(RequestDepth), LibraryID, "Loading: ", Module)
RequestDepth = RequestDepth + 1
end
local Result = Function(Module, ...)
if DEBUG_MODE then
RequestDepth = RequestDepth - 1
print(("\t"):rep(RequestDepth), LibraryID, "Done loading: ", Module)
end
return Result
end
end
local function _getLibraryLoader(LibraryCache)
--- Loads a library from Nevermore's library cache
-- @param Module The name of the library or a module
-- @return The library's value
return function(Module)
if typeof(Module) == "Instance" and Module:IsA("ModuleScript") then
return require(Module)
elseif type(Module) == "string" then
local ModuleScript = LibraryCache[Module] or error("Error: Library '" .. Module .. "' does not exist.", 2)
return require(ModuleScript)
else
error(("Error: Module must be a string or ModuleScript, got '%s'"):format(typeof(Module)))
end
end
end
local ResourceFolder = _retrieve(ReplicatedStorage, "Folder")("NevermoreResources")
local GetSubFolder = _retrieve(ResourceFolder, "Folder")
local RepositoryFolder = _getRepository(GetSubFolder)
local LibraryCache = _getLibraryCache(RepositoryFolder)
if RunService:IsServer() and not RunService:IsClient() then -- Don't move in SoloTestMode
_replicateRepository(GetSubFolder("Modules"), LibraryCache)
end
local Nevermore = {}
--- Load a library through Nevermore
-- @function LoadLibrary
-- @tparam string LibraryName
Nevermore.LoadLibrary = _asyncCache(_debugLoading(_getLibraryLoader(LibraryCache)))
--- Get a remote event
-- @function GetRemoteEvent
-- @tparam string RemoteEventName
-- @return RemoteEvent
Nevermore.GetRemoteEvent = _asyncCache(_retrieve(GetSubFolder("RemoteEvents"), "RemoteEvent"))
--- Get a remote function
-- @function GetRemoteFunction
-- @tparam string RemoteFunctionName
-- @return RemoteFunction
Nevermore.GetRemoteFunction = _asyncCache(_retrieve(GetSubFolder("RemoteFunctions"), "RemoteFunction"))
setmetatable(Nevermore, {
__call = Nevermore.LoadLibrary;
__index = function(self, Index)
error(("'%s is not a valid member of Nevermore"):format(tostring(Index)))
end;
})
return Nevermore
|
Ignore children of module scripts, fix tabbing
|
Ignore children of module scripts, fix tabbing
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
0dff850318caf3cf0911147136d8e273dce5ab0f
|
neovim/.config/nvim/ftplugin/markdown.lua
|
neovim/.config/nvim/ftplugin/markdown.lua
|
local map = require'utilities'.map
-- Enable spell checking.
vim.cmd('setlocal spell')
-- Default to 4 space indent, as that's the amount that triggers preformatted
-- text in markdown.
vim.opt.shiftwidth = 4
-- Support code fencing syntax highlighting for the listed languages.
vim.g.markdown_fenced_languages = {
'bash=sh',
'javascript',
'js=javascript',
'json=javascript',
'typescript',
'ts=typescript',
'php',
'html',
'lua',
'css'
}
-- Use a dictionary to lookup words.
if vim.fn.executable('dict') then
vim.opt.keywordprg = 'dict'
end
-- Mapping to toggle todo list status.
function ToggleTodo()
if (vim.fn.getline('.') == '[x') then
vim.cmd('normal ^f[lr ')
else
vim.cmd('normal ^f[lrx')
end
end
map {'n', '<LocalLeader>x', '<cmd>lua ToggleTodo()<CR>', silent = true}
|
local map = require'utilities'.map
-- Enable spell checking.
vim.cmd('setlocal spell')
-- Default to 4 space indent, as that's the amount that triggers preformatted
-- text in markdown.
vim.opt.shiftwidth = 4
-- Support code fencing syntax highlighting for the listed languages.
vim.g.markdown_fenced_languages = {
'bash=sh',
'javascript',
'js=javascript',
'json=javascript',
'typescript',
'ts=typescript',
'php',
'html',
'lua',
'css'
}
-- Use a dictionary to lookup words.
if vim.fn.executable('dict') then
vim.opt.keywordprg = 'dict'
end
-- Mapping to toggle todo list status.
function ToggleTodo()
vim.cmd('normal mp')
if (string.match(vim.fn.getline('.'), '[x]')) then
vim.cmd('normal ^f[lr ')
else
vim.cmd('normal ^f[lrx')
end
vim.cmd('normal `p')
end
map {'n', '<LocalLeader>x', '<cmd>lua ToggleTodo()<CR>', silent = true}
|
Fix markdown todo toggle mapping
|
Fix markdown todo toggle mapping
The mapping function didn't properly check for a string containing the
`[x]` todo syntax, instead checking for the literal, meaning the toggle
would never work to turn "off" the checkbox.
Enhance the mapping by keeping the cursor position the same after the
job is done. Use the little used (for me) and hard to reach `p` register
to store the mark.
|
Lua
|
mit
|
bronzehedwick/dotfiles,bronzehedwick/dotfiles,bronzehedwick/dotfiles,bronzehedwick/dotfiles
|
190ecf2331c0956d270fbf0de3d1e967c5ce4881
|
core/certmanager.lua
|
core/certmanager.lua
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local configmanager = require "core.configmanager";
local log = require "util.logger".init("certmanager");
local ssl = ssl;
local ssl_newcontext = ssl and ssl.newcontext;
local tostring = tostring;
local prosody = prosody;
local resolve_path = configmanager.resolve_relative_path;
local config_path = prosody.paths.config;
local luasec_has_noticket, luasec_has_verifyext, luasec_has_no_compression;
if ssl then
local luasec_major, luasec_minor = ssl._VERSION:match("^(%d+)%.(%d+)");
luasec_has_noticket = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=4;
luasec_has_verifyext = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=5;
luasec_has_no_compression = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=5;
end
module "certmanager"
-- Global SSL options if not overridden per-host
local default_ssl_config = configmanager.get("*", "ssl");
local default_capath = "/etc/ssl/certs";
local default_verify = (ssl and ssl.x509 and { "peer", "client_once", }) or "none";
local default_options = { "no_sslv2", luasec_has_noticket and "no_ticket" or nil };
local default_verifyext = { "lsec_continue", "lsec_ignore_purpose" };
if ssl and not luasec_has_verifyext and ssl.x509 then
-- COMPAT mw/luasec-hg
for i=1,#default_verifyext do -- Remove lsec_ prefix
default_verify[#default_verify+1] = default_verifyext[i]:sub(6);
end
end
if luasec_has_no_compression and configmanager.get("*", "ssl_compression") ~= true then
default_options[#default_options+1] = "no_compression";
end
if luasec_has_no_compression then -- Has no_compression? Then it has these too...
default_options[#default_options+1] = "single_dh_use";
default_options[#default_options+1] = "single_ecdh_use";
end
function create_context(host, mode, user_ssl_config)
user_ssl_config = user_ssl_config or default_ssl_config;
if not ssl then return nil, "LuaSec (required for encryption) was not found"; end
if not user_ssl_config then return nil, "No SSL/TLS configuration present for "..host; end
local ssl_config = {
mode = mode;
protocol = user_ssl_config.protocol or "sslv23";
key = resolve_path(config_path, user_ssl_config.key);
password = user_ssl_config.password or function() log("error", "Encrypted certificate for %s requires 'ssl' 'password' to be set in config", host); end;
certificate = resolve_path(config_path, user_ssl_config.certificate);
capath = resolve_path(config_path, user_ssl_config.capath or default_capath);
cafile = resolve_path(config_path, user_ssl_config.cafile);
verify = user_ssl_config.verify or default_verify;
verifyext = user_ssl_config.verifyext or default_verifyext;
options = user_ssl_config.options or default_options;
depth = user_ssl_config.depth;
curve = user_ssl_config.curve or "secp384r1";
ciphers = user_ssl_config.ciphers or "HIGH:!DSS:!aNULL@STRENGTH";
dhparam = user_ssl_config.dhparam;
};
local ctx, err = ssl_newcontext(ssl_config);
-- LuaSec ignores the cipher list from the config, so we have to take care
-- of it ourselves (W/A for #x)
if ctx and user_ssl_config.ciphers then
local success;
success, err = ssl.context.setcipher(ctx, user_ssl_config.ciphers);
if not success then ctx = nil; end
end
if not ctx then
err = err or "invalid ssl config"
local file = err:match("^error loading (.-) %(");
if file then
if file == "private key" then
file = ssl_config.key or "your private key";
elseif file == "certificate" then
file = ssl_config.certificate or "your certificate file";
end
local reason = err:match("%((.+)%)$") or "some reason";
if reason == "Permission denied" then
reason = "Check that the permissions allow Prosody to read this file.";
elseif reason == "No such file or directory" then
reason = "Check that the path is correct, and the file exists.";
elseif reason == "system lib" then
reason = "Previous error (see logs), or other system error.";
elseif reason == "(null)" or not reason then
reason = "Check that the file exists and the permissions are correct";
else
reason = "Reason: "..tostring(reason):lower();
end
log("error", "SSL/TLS: Failed to load '%s': %s (for %s)", file, reason, host);
else
log("error", "SSL/TLS: Error initialising for %s: %s", host, err);
end
end
return ctx, err;
end
function reload_ssl_config()
default_ssl_config = configmanager.get("*", "ssl");
end
prosody.events.add_handler("config-reloaded", reload_ssl_config);
return _M;
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local configmanager = require "core.configmanager";
local log = require "util.logger".init("certmanager");
local ssl = ssl;
local ssl_newcontext = ssl and ssl.newcontext;
local tostring = tostring;
local prosody = prosody;
local resolve_path = configmanager.resolve_relative_path;
local config_path = prosody.paths.config;
local luasec_has_noticket, luasec_has_verifyext, luasec_has_no_compression;
if ssl then
local luasec_major, luasec_minor = ssl._VERSION:match("^(%d+)%.(%d+)");
luasec_has_noticket = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=4;
luasec_has_verifyext = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=5;
luasec_has_no_compression = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=5;
end
module "certmanager"
-- Global SSL options if not overridden per-host
local default_ssl_config = configmanager.get("*", "ssl");
local default_capath = "/etc/ssl/certs";
local default_verify = (ssl and ssl.x509 and { "peer", "client_once", }) or "none";
local default_options = { "no_sslv2", luasec_has_noticket and "no_ticket" or nil };
local default_verifyext = { "lsec_continue", "lsec_ignore_purpose" };
if ssl and not luasec_has_verifyext and ssl.x509 then
-- COMPAT mw/luasec-hg
for i=1,#default_verifyext do -- Remove lsec_ prefix
default_verify[#default_verify+1] = default_verifyext[i]:sub(6);
end
end
if luasec_has_no_compression and configmanager.get("*", "ssl_compression") ~= true then
default_options[#default_options+1] = "no_compression";
end
if luasec_has_no_compression then -- Has no_compression? Then it has these too...
default_options[#default_options+1] = "single_dh_use";
default_options[#default_options+1] = "single_ecdh_use";
end
function create_context(host, mode, user_ssl_config)
user_ssl_config = user_ssl_config or default_ssl_config;
if not ssl then return nil, "LuaSec (required for encryption) was not found"; end
if not user_ssl_config then return nil, "No SSL/TLS configuration present for "..host; end
local ssl_config = {
mode = mode;
protocol = user_ssl_config.protocol or "sslv23";
key = resolve_path(config_path, user_ssl_config.key);
password = user_ssl_config.password or function() log("error", "Encrypted certificate for %s requires 'ssl' 'password' to be set in config", host); end;
certificate = resolve_path(config_path, user_ssl_config.certificate);
capath = resolve_path(config_path, user_ssl_config.capath or default_capath);
cafile = resolve_path(config_path, user_ssl_config.cafile);
verify = user_ssl_config.verify or default_verify;
verifyext = user_ssl_config.verifyext or default_verifyext;
options = user_ssl_config.options or default_options;
depth = user_ssl_config.depth;
curve = user_ssl_config.curve or "secp384r1";
ciphers = user_ssl_config.ciphers or "HIGH:!DSS:!aNULL@STRENGTH";
dhparam = user_ssl_config.dhparam;
};
local ctx, err = ssl_newcontext(ssl_config);
-- COMPAT: LuaSec 0.4.1 ignores the cipher list from the config, so we have to take
-- care of it ourselves...
if ctx and ssl_config.ciphers then
local success;
success, err = ssl.context.setcipher(ctx, ssl_config.ciphers);
if not success then ctx = nil; end
end
if not ctx then
err = err or "invalid ssl config"
local file = err:match("^error loading (.-) %(");
if file then
if file == "private key" then
file = ssl_config.key or "your private key";
elseif file == "certificate" then
file = ssl_config.certificate or "your certificate file";
end
local reason = err:match("%((.+)%)$") or "some reason";
if reason == "Permission denied" then
reason = "Check that the permissions allow Prosody to read this file.";
elseif reason == "No such file or directory" then
reason = "Check that the path is correct, and the file exists.";
elseif reason == "system lib" then
reason = "Previous error (see logs), or other system error.";
elseif reason == "(null)" or not reason then
reason = "Check that the file exists and the permissions are correct";
else
reason = "Reason: "..tostring(reason):lower();
end
log("error", "SSL/TLS: Failed to load '%s': %s (for %s)", file, reason, host);
else
log("error", "SSL/TLS: Error initialising for %s: %s", host, err);
end
end
return ctx, err;
end
function reload_ssl_config()
default_ssl_config = configmanager.get("*", "ssl");
end
prosody.events.add_handler("config-reloaded", reload_ssl_config);
return _M;
|
certmanager: Fix for working around a bug with LuaSec 0.4.1 that causes it to not honour the 'ciphers' option. This change will apply 0.9's default cipher string for LuaSec 0.4.1 users.
|
certmanager: Fix for working around a bug with LuaSec 0.4.1 that causes it to not honour the 'ciphers' option. This change will apply 0.9's default cipher string for LuaSec 0.4.1 users.
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
e901b16cbcdb5ad0671066e1319af066e8647006
|
tarantool/tarantool.lua
|
tarantool/tarantool.lua
|
box.cfg
{
pid_file = nil,
background = false,
log_level = 5
}
local function init()
space1 = box.schema.space.create('primary_only_index', { if_not_exists = true })
space1:create_index('primary', {type='hash', parts={1, 'unsigned'}, if_not_exists = true})
performanceSpace = box.schema.space.create('performance')
performanceSpace:create_index('primary', {type='hash', parts={1, 'unsigned'}, if_not_exists = true})
space2 = box.schema.space.create('primary_and_secondary_index')
space2:create_index('hashIndex', {type='hash', parts={1, 'unsigned'}, if_not_exists = true })
space2:create_index('treeIndex', {type='tree', parts={1, 'unsigned'}, if_not_exists = true })
box.schema.user.create('notSetPassword', { if_not_exists = true })
box.schema.user.create('emptyPassword', {password = '', if_not_exists = true})
box.schema.user.create('operator', {password = 'operator', if_not_exists = true})
box.schema.user.grant('operator','read,write,execute','universe', { if_not_exists = true })
function log_connect ()
local log = require('log')
local m = 'Connection. user=' .. box.session.user() .. ' id=' .. box.session.id()
log.info(m)
end
function log_disconnect ()
local log = require('log')
local m = 'Disconnection. user=' .. box.session.user() .. ' id=' .. box.session.id()
log.info(m)
end
function log_auth ()
local log = require('log')
local m = 'Authentication attempt'
log.info(m)
end
function log_auth_ok (user_name)
local log = require('log')
local m = 'Authenticated user ' .. user_name
log.info(m)
end
box.session.on_connect(log_connect)
box.session.on_disconnect(log_disconnect)
box.session.on_auth(log_auth)
box.session.on_auth(log_auth_ok)
end
box.once('init', init)
|
box.cfg
{
pid_file = nil,
background = false,
log_level = 5
}
local function init()
space1 = box.schema.space.create('primary_only_index', { if_not_exists = true })
space1:create_index('primary', {type='hash', parts={1, 'unsigned'}, if_not_exists = true})
performanceSpace = box.schema.space.create('performance', { if_not_exists = true })
performanceSpace:create_index('primary', {type='hash', parts={1, 'unsigned'}, if_not_exists = true})
space2 = box.schema.space.create('primary_and_secondary_index', { if_not_exists = true })
space2:create_index('hashIndex', {type='hash', parts={1, 'unsigned'}, if_not_exists = true })
space2:create_index('treeIndex', {type='tree', parts={1, 'unsigned'}, if_not_exists = true })
box.schema.user.create('notSetPassword', { if_not_exists = true })
box.schema.user.create('emptyPassword', { password = '', if_not_exists = true })
box.schema.user.create('operator', {password = 'operator', if_not_exists = true })
box.schema.user.grant('operator','read,write,execute','universe', { if_not_exists = true })
function log_connect ()
local log = require('log')
local m = 'Connection. user=' .. box.session.user() .. ' id=' .. box.session.id()
log.info(m)
end
function log_disconnect ()
local log = require('log')
local m = 'Disconnection. user=' .. box.session.user() .. ' id=' .. box.session.id()
log.info(m)
end
function log_auth ()
local log = require('log')
local m = 'Authentication attempt'
log.info(m)
end
function log_auth_ok (user_name)
local log = require('log')
local m = 'Authenticated user ' .. user_name
log.info(m)
end
box.session.on_connect(log_connect)
box.session.on_disconnect(log_disconnect)
box.session.on_auth(log_auth)
box.session.on_auth(log_auth_ok)
end
box.once('init', init)
|
Fix bug
|
Fix bug
|
Lua
|
mit
|
progaudi/progaudi.tarantool,aensidhe/tarantool-dnx,aensidhe/tarantool-csharp
|
37ae245f2b69e2483179557d9b03e063e19266a1
|
libs/web/luasrc/http.lua
|
libs/web/luasrc/http.lua
|
--[[
LuCI - HTTP-Interaction
Description:
HTTP-Header manipulator and form variable preprocessor
FileId:
$Id$
ToDo:
- Cookie handling
License:
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
module("luci.http", package.seeall)
require("ltn12")
require("luci.http.protocol")
require("luci.util")
context = luci.util.threadlocal()
Request = luci.util.class()
function Request.__init__(self, env, sourcein, sinkerr)
self.input = sourcein
self.error = sinkerr
-- File handler
self.filehandler = function() end
-- HTTP-Message table
self.message = {
env = env,
headers = {},
params = luci.http.protocol.urldecode_params(env.QUERY_STRING or ""),
}
setmetatable(self.message.params, {__index =
function(tbl, key)
setmetatable(tbl, nil)
luci.http.protocol.parse_message_body(
self.input,
self.message,
self.filehandler
)
return rawget(tbl, key)
end
})
end
function Request.formvalue(self, name, default)
if name then
return self.message.params[name] and tostring(self.message.params[name]) or default
else
return self.message.params
end
end
function Request.formvaluetable(self, prefix)
local vals = {}
prefix = prefix and prefix .. "." or "."
local void = self.message.params[nil]
for k, v in pairs(self.message.params) do
if k:find(prefix, 1, true) == 1 then
vals[k:sub(#prefix + 1)] = tostring(v)
end
end
return vals
end
function Request.getenv(self, name)
return name and self.message.env[name] or self.message.env
end
function Request.setfilehandler(self, callback)
self.filehandler = callback
end
function close()
if not context.eoh then
context.eoh = true
coroutine.yield(3)
end
if not context.closed then
context.closed = true
coroutine.yield(5)
end
end
function formvalue(...)
return context.request:formvalue(...)
end
function formvaluetable(...)
return context.request:formvaluetable(...)
end
function getvalue(...)
return context.request:getvalue(...)
end
function postvalue(...)
return context.request:postvalue(...)
end
function getenv(...)
return context.request:getenv(...)
end
function setfilehandler(...)
return context.request:setfilehandler(...)
end
function header(key, value)
if not context.status then
status()
end
if not context.headers then
context.headers = {}
end
context.headers[key:lower()] = value
coroutine.yield(2, key, value)
end
function prepare_content(mime)
header("Content-Type", mime)
end
function status(code, message)
code = code or 200
message = message or "OK"
context.status = code
coroutine.yield(1, code, message)
end
function write(content)
if not content or #content == 0 then
return
end
if not context.eoh then
if not context.status then
status()
end
if not context.headers or not context.headers["content-type"] then
header("Content-Type", "text/html; charset=utf-8")
end
context.eoh = true
coroutine.yield(3)
end
coroutine.yield(4, content)
end
function basic_auth(realm, errorpage)
header("Status", "401 Unauthorized")
header("WWW-Authenticate", string.format('Basic realm="%s"', realm or ""))
if errorpage then
errorpage()
end
close()
end
function redirect(url)
header("Status", "302 Found")
header("Location", url)
close()
end
function build_querystring(table)
local s="?"
for k, v in pairs(table) do
s = s .. urlencode(k) .. "=" .. urlencode(v) .. "&"
end
return s
end
urldecode = luci.http.protocol.urldecode
urlencode = luci.http.protocol.urlencode
|
--[[
LuCI - HTTP-Interaction
Description:
HTTP-Header manipulator and form variable preprocessor
FileId:
$Id$
ToDo:
- Cookie handling
License:
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
module("luci.http", package.seeall)
require("ltn12")
require("luci.http.protocol")
require("luci.util")
context = luci.util.threadlocal()
Request = luci.util.class()
function Request.__init__(self, env, sourcein, sinkerr)
self.input = sourcein
self.error = sinkerr
-- File handler
self.filehandler = function() end
-- HTTP-Message table
self.message = {
env = env,
headers = {},
params = luci.http.protocol.urldecode_params(env.QUERY_STRING or ""),
}
setmetatable(self.message.params, {__index =
function(tbl, key)
setmetatable(tbl, nil)
luci.http.protocol.parse_message_body(
self.input,
self.message,
self.filehandler
)
return rawget(tbl, key)
end
})
end
function Request.formvalue(self, name, default)
if name then
return self.message.params[name] and tostring(self.message.params[name]) or default
else
return self.message.params
end
end
function Request.formvaluetable(self, prefix)
local vals = {}
prefix = prefix and prefix .. "." or "."
local void = self.message.params[nil]
for k, v in pairs(self.message.params) do
if k:find(prefix, 1, true) == 1 then
vals[k:sub(#prefix + 1)] = tostring(v)
end
end
return vals
end
function Request.getenv(self, name)
if name then
return self.message.env[name]
else
return self.message.env
end
end
function Request.setfilehandler(self, callback)
self.filehandler = callback
end
function close()
if not context.eoh then
context.eoh = true
coroutine.yield(3)
end
if not context.closed then
context.closed = true
coroutine.yield(5)
end
end
function formvalue(...)
return context.request:formvalue(...)
end
function formvaluetable(...)
return context.request:formvaluetable(...)
end
function getvalue(...)
return context.request:getvalue(...)
end
function postvalue(...)
return context.request:postvalue(...)
end
function getenv(...)
return context.request:getenv(...)
end
function setfilehandler(...)
return context.request:setfilehandler(...)
end
function header(key, value)
if not context.status then
status()
end
if not context.headers then
context.headers = {}
end
context.headers[key:lower()] = value
coroutine.yield(2, key, value)
end
function prepare_content(mime)
header("Content-Type", mime)
end
function status(code, message)
code = code or 200
message = message or "OK"
context.status = code
coroutine.yield(1, code, message)
end
function write(content)
if not content or #content == 0 then
return
end
if not context.eoh then
if not context.status then
status()
end
if not context.headers or not context.headers["content-type"] then
header("Content-Type", "text/html; charset=utf-8")
end
context.eoh = true
coroutine.yield(3)
end
coroutine.yield(4, content)
end
function basic_auth(realm, errorpage)
header("Status", "401 Unauthorized")
header("WWW-Authenticate", string.format('Basic realm="%s"', realm or ""))
if errorpage then
errorpage()
end
close()
end
function redirect(url)
header("Status", "302 Found")
header("Location", url)
close()
end
function build_querystring(table)
local s="?"
for k, v in pairs(table) do
s = s .. urlencode(k) .. "=" .. urlencode(v) .. "&"
end
return s
end
urldecode = luci.http.protocol.urldecode
urlencode = luci.http.protocol.urlencode
|
libs/web: Fixed bug where the environment table gets returned in case of an undefined variable
|
libs/web: Fixed bug where the environment table gets returned in case of an undefined variable
|
Lua
|
apache-2.0
|
deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci
|
1115e0143c222a078d1159095e7500cc0a54d182
|
preprocess/lecunlcn.lua
|
preprocess/lecunlcn.lua
|
-----------------------------------------------------------------------
--[[ LeCunLCN ]]--
-- Performs Local Contrast Normalization on images
-- http://yann.lecun.com/exdb/publis/pdf/jarrett-iccv-09.pdf
-- You should probably use dp.GCN before applying LeCunLCN to
-- mitigate border effects.
-----------------------------------------------------------------------
local LeCunLCN = torch.class("dp.LeCunLCN", "dp.Preprocess")
LeCunLCN.isLeCunLCN = true
function LeCunLCN:__init(config)
config = config or {}
local args
args, self._kernel_size, self._kernel_std, self._threshold,
self._divide_by_std, self._batch_size, self._channels,
self._progress = xlua.unpack(
{config},
'LeCunLCN',
'LeCunLCN constructor',
{arg='kernel_size', type='number', default=9,
help='gaussian kernel size. Should be an odd number.'},
{arg='kernel_std', type='number', default=2,
help='standard deviation of gaussian kernel.'..
'Higher values remove lower frequency features,'..
'i.e. a value of infinity will have no effect.'},
{arg='threshold', type='number', default=1e-4,
help='threshold for denominator'},
{arg='divide_by_std', type='boolean', default=false,
help='instead of divisive normalization, divide by std'},
{arg='batch_size', type='number', default=256,
help='batch_size used for performing the preprocessing'},
{arg='channels', type='table',
help='List of channels to normalize. Defaults to {1,2,3}'},
{arg='progress', type='boolean', default=true,
help='display progress bar'}
)
assert(self._kernel_size % 2 == 1, "kernel_size should be odd (not even)")
self._sampler = dp.Sampler{batch_size = batch_size}
self._channels = self._channels or {1,2,3}
self._filter = self.gaussianFilter(self._kernel_size, self._kernel_std)
-- buffers
self._convout = torch.Tensor()
self._center = torch.Tensor()
self._square = torch.Tensor()
self._mean = torch.Tensor()
self._divisor = torch.Tensor()
self._result = torch.Tensor()
self._denom = torch.Tensor()
self._largest = torch.Tensor()
self._indice = torch.LongTensor()
end
-- static method
function LeCunLCN.gaussianFilter(kernel_size, kernel_std)
local x = torch.zeros(kernel_size, kernel_size)
local _gauss = function(x, y, sigma)
local Z = 2 * math.pi * math.pow(sigma, 2)
return 1 / Z * math.exp(-(math.pow(x,2)+math.pow(y,2))/(2 * math.pow(sigma,2)))
end
local mid = math.ceil(kernel_size / 2)
for i = 1, kernel_size do
for j = 1, kernel_size do
x[i][j] = _gauss(i-mid, j-mid, kernel_std)
end
end
return x / x:sum()
end
function LeCunLCN:apply(dv, can_fit)
if self._progress then
print"applying LeCunLCN preprocessing"
end
for stop, view in dv:ipairsSub(self._batch_size, true, true) do
-- transform and replace original tensor
view:replace("bhwc",
self:transform(
view:forward("bhwc")
), true
)
if self._progress then
-- display progress
xlua.progress(stop, dv:nSample())
end
end
-- for aesthetics :
if self._progress then
xlua.progress(dv:nSample(), dv:nSample())
end
end
-- expects x to have view 'bhwc'
function LeCunLCN:transform(x)
if torch.type(x) ~= torch.type(self._filter) then
self._filter = self._filter:type(torch.type(x))
self._convout = self._convout:type(torch.type(x))
self._center = self._center:type(torch.type(x))
self._square = self._square:type(torch.type(x))
self._mean = self._mean:type(torch.type(x))
self._divisor = self._divisor:type(torch.type(x))
self._denom = self._denom:type(torch.type(x))
self._result = self._result:type(torch.type(x))
self._indice = self._indice:type(torch.type(x))
self._largest = self._largest:type(torch.type(x))
end
self._result:resizeAs(x):copy(x)
for i,channelIdx in ipairs(self._channels) do
assert(torch.type(channelIdx) == 'number')
assert(channelIdx >= 0 and channelIdx <= x:size(4))
self._result:select(4,channelIdx):copy(self:normalize(x:select(4,channelIdx)))
end
return self._result
end
-- expects input to have view 'bhw'
function LeCunLCN:normalize(input)
local filter, convout = self._filter, self._convout
local center, square = self._center, self._square
local mean, divisor = self._mean, self._divisor
local denom, indice, largest = self._denom, self._indice, self._largest
--[[ subtractive normalization ]]--
filter = filter:view(1, filter:size(1), filter:size(2))
filter = filter:expand(input:size(1), filter:size(2), filter:size(3))
convout:conv2(input, filter, "F")
-- For each pixel, remove mean of kW x kH neighborhood
local mid = math.ceil(self._kernel_size / 2)
center:resizeAs(input):copy(input)
center:add(-1, convout[{{},{mid, -mid},{mid, -mid}}])
--[[ divisive normalization ]]--
if self._divide_by_std then
-- divide by standard deviation of each image
denom:std(center:view(center:size(1), -1), 2):add(self._threshold)
center:cdiv(denom:view(denom:size(1), 1, 1):expandAs(center))
return center
end
-- Scale down norm of kW x kH patch if norm is bigger than 1
square:pow(center, 2)
convout:conv2(square, filter, 'F')
denom:resizeAs(input)
denom:copy(convout[{{},{mid, -mid},{mid, -mid}}]) -- makes it contiguous
denom:sqrt()
-- per image mean : batchSize x 1
mean:mean(denom:view(denom:size(1),-1), 2)
largest:resize(denom:size(1), denom:size(2), denom:size(3), 2)
largest:select(4,1):copy(denom)
largest:select(4,2):copy(mean:view(mean:size(1),1,1):expandAs(denom))
divisor:max(indice, largest, 4)
divisor:apply(function(x)
return x>self._threshold and x or self._threshold
end)
center:cdiv(divisor)
return center
end
|
-----------------------------------------------------------------------
--[[ LeCunLCN ]]--
-- Performs Local Contrast Normalization on images
-- http://yann.lecun.com/exdb/publis/pdf/jarrett-iccv-09.pdf
-- You should probably use dp.GCN before applying LeCunLCN to
-- mitigate border effects.
-----------------------------------------------------------------------
local LeCunLCN = torch.class("dp.LeCunLCN", "dp.Preprocess")
LeCunLCN.isLeCunLCN = true
function LeCunLCN:__init(config)
config = config or {}
local args
args, self._kernel_size, self._kernel_std, self._threshold,
self._divide_by_std, self._batch_size, self._channels,
self._progress = xlua.unpack(
{config},
'LeCunLCN',
'LeCunLCN constructor',
{arg='kernel_size', type='number', default=9,
help='gaussian kernel size. Should be an odd number.'},
{arg='kernel_std', type='number', default=2,
help='standard deviation of gaussian kernel.'..
'Higher values remove lower frequency features,'..
'i.e. a value of infinity will have no effect.'},
{arg='threshold', type='number', default=1e-4,
help='threshold for denominator'},
{arg='divide_by_std', type='boolean', default=false,
help='instead of divisive normalization, divide by std'},
{arg='batch_size', type='number', default=256,
help='batch_size used for performing the preprocessing'},
{arg='channels', type='table',
help='List of channels to normalize. Defaults to {1,2,3}'},
{arg='progress', type='boolean', default=true,
help='display progress bar'}
)
assert(self._kernel_size % 2 == 1, "kernel_size should be odd (not even)")
self._sampler = dp.Sampler{batch_size = batch_size}
self._channels = self._channels or {1,2,3}
self._filter = self.gaussianFilter(self._kernel_size, self._kernel_std)
-- buffers
self._convout = torch.Tensor()
self._center = torch.Tensor()
self._square = torch.Tensor()
self._mean = torch.Tensor()
self._divisor = torch.Tensor()
self._result = torch.Tensor()
self._denom = torch.Tensor()
self._largest = torch.Tensor()
self._indice = torch.LongTensor()
end
-- static method
function LeCunLCN.gaussianFilter(kernel_size, kernel_std)
local x = torch.zeros(kernel_size, kernel_size)
local _gauss = function(x, y, sigma)
local Z = 2 * math.pi * math.pow(sigma, 2)
return 1 / Z * math.exp(-(math.pow(x,2)+math.pow(y,2))/(2 * math.pow(sigma,2)))
end
local mid = math.ceil(kernel_size / 2)
for i = 1, kernel_size do
for j = 1, kernel_size do
x[i][j] = _gauss(i-mid, j-mid, kernel_std)
end
end
return x / x:sum()
end
function LeCunLCN:apply(dv, can_fit)
if self._progress then
print"applying LeCunLCN preprocessing"
end
for stop, view in dv:ipairsSub(self._batch_size, true, true) do
-- transform and replace original tensor
view:replace("bhwc",
self:transform(
view:forward("bhwc")
), true
)
if self._progress then
-- display progress
xlua.progress(stop, dv:nSample())
end
end
-- for aesthetics :
if self._progress then
xlua.progress(dv:nSample(), dv:nSample())
end
end
-- expects x to have view 'bhwc'
function LeCunLCN:transform(x)
if torch.type(x) ~= torch.type(self._filter) then
self._filter = self._filter:type(torch.type(x))
self._convout = self._convout:type(torch.type(x))
self._center = self._center:type(torch.type(x))
self._square = self._square:type(torch.type(x))
self._mean = self._mean:type(torch.type(x))
self._divisor = self._divisor:type(torch.type(x))
self._denom = self._denom:type(torch.type(x))
self._result = self._result:type(torch.type(x))
self._largest = self._largest:type(torch.type(x))
end
self._result:resizeAs(x):copy(x)
for i,channelIdx in ipairs(self._channels) do
assert(torch.type(channelIdx) == 'number')
assert(channelIdx >= 0)
if channelIdx > x:size(4) then
break
end
self._result:select(4,channelIdx):copy(self:normalize(x:select(4,channelIdx)))
end
return self._result
end
-- expects input to have view 'bhw'
function LeCunLCN:normalize(input)
local filter, convout = self._filter, self._convout
local center, square = self._center, self._square
local mean, divisor = self._mean, self._divisor
local denom, indice, largest = self._denom, self._indice, self._largest
--[[ subtractive normalization ]]--
filter = filter:view(1, filter:size(1), filter:size(2))
filter = filter:expand(input:size(1), filter:size(2), filter:size(3))
convout:conv2(input, filter, "F")
-- For each pixel, remove mean of kW x kH neighborhood
local mid = math.ceil(self._kernel_size / 2)
center:resizeAs(input):copy(input)
center:add(-1, convout[{{},{mid, -mid},{mid, -mid}}])
--[[ divisive normalization ]]--
if self._divide_by_std then
-- divide by standard deviation of each image
denom:std(center:view(center:size(1), -1), 2):add(self._threshold)
center:cdiv(denom:view(denom:size(1), 1, 1):expandAs(center))
return center
end
-- Scale down norm of kW x kH patch if norm is bigger than 1
square:pow(center, 2)
convout:conv2(square, filter, 'F')
denom:resizeAs(input)
denom:copy(convout[{{},{mid, -mid},{mid, -mid}}]) -- makes it contiguous
denom:sqrt()
-- per image mean : batchSize x 1
mean:mean(denom:view(denom:size(1),-1), 2)
largest:resize(denom:size(1), denom:size(2), denom:size(3), 2)
largest:select(4,1):copy(denom)
largest:select(4,2):copy(mean:view(mean:size(1),1,1):expandAs(denom))
divisor:max(indice, largest, 4)
divisor:apply(function(x)
return x>self._threshold and x or self._threshold
end)
center:cdiv(divisor)
return center
end
|
fixed LecunLCN bug
|
fixed LecunLCN bug
|
Lua
|
bsd-3-clause
|
sagarwaghmare69/dp,nicholas-leonard/dp,jnhwkim/dp,eulerreich/dp,rickyHong/dptorchLib,kracwarlock/dp,fiskio/dp
|
9919e4ff269bbeaaa02b38c3f9f5d14a61a166a3
|
Interface/AddOns/RayUI/modules/misc/merchant.lua
|
Interface/AddOns/RayUI/modules/misc/merchant.lua
|
local R, L, P = unpack(select(2, ...)) --Inport: Engine, Locales, ProfileDB
local M = R:GetModule("Misc")
local function LoadFunc()
if not M.db.merchant then return end
local poisons = {
[6947] = 20, --速效
[3775] = 20, --减速
-- [5237] = 20, --麻痹
[2892] = 20, --致命
[10918] = 20, --致伤
}
local f = CreateFrame("Frame")
f:SetScript("OnEvent", function()
local c = 0
for b=0,4 do
for s=1,GetContainerNumSlots(b) do
local l = GetContainerItemLink(b, s)
if l then
local p = select(11, GetItemInfo(l))*select(2, GetContainerItemInfo(b, s))
if select(3, GetItemInfo(l))==0 and p>0 then
UseContainerItem(b, s)
PickupMerchantItem()
c = c+p
end
end
end
end
if c>0 then
local g, s, c = math.floor(c/10000) or 0, math.floor((c%10000)/100) or 0, c%100
DEFAULT_CHAT_FRAME:AddMessage(L["您背包内的粗糙物品已被自动卖出, 您赚取了"].." |cffffffff"..g.."|cffffd700g|r".." |cffffffff"..s.."|cffc7c7cfs|r".." |cffffffff"..c.."|cffeda55fc|r.",255,255,0)
end
if not IsShiftKeyDown() then
if CanMerchantRepair() then
local cost, possible = GetRepairAllCost()
if cost>0 then
if possible then
local c = cost%100
local s = math.floor((cost%10000)/100) or 0
local g = math.floor(cost/10000) or 0
if IsInGuild() and CanGuildBankRepair() and ((GetGuildBankWithdrawMoney() >= cost) or (GetGuildBankWithdrawMoney() == -1)) and (GetGuildBankMoney() >= cost) then
RepairAllItems(1)
DEFAULT_CHAT_FRAME:AddMessage(L["您的装备已使用工会修理, 花费了"].." |cffffffff"..g.."|cffffd700g|r".." |cffffffff"..s.."|cffc7c7cfs|r".." |cffffffff"..c.."|cffeda55fc|r.",255,255,0)
elseif GetMoney() >= cost then
RepairAllItems()
DEFAULT_CHAT_FRAME:AddMessage(L["您的装备已修理, 花费了"].." |cffffffff"..g.."|cffffd700g|r".." |cffffffff"..s.."|cffc7c7cfs|r".." |cffffffff"..c.."|cffeda55fc|r.",255,255,0)
else
DEFAULT_CHAT_FRAME:AddMessage(L["您没有足够的金钱来修理!"],255,0,0)
return
end
end
end
end
end
if M.db.poisons and R.myclass == "ROGUE" then
local numItems = GetMerchantNumItems()
for i = 1, numItems do
local merchantItemLink = GetMerchantItemLink(i)
if merchantItemLink then
local id = tonumber(merchantItemLink:match("item:(%d+)"))
if poisons[id] and GetItemCount(id) < poisons[id] then
BuyMerchantItem(i, poisons[id] - GetItemCount(id))
end
end
end
end
end)
f:RegisterEvent("MERCHANT_SHOW")
-- buy max number value with alt
local savedMerchantItemButton_OnModifiedClick = MerchantItemButton_OnModifiedClick
function MerchantItemButton_OnModifiedClick(self, ...)
if ( IsAltKeyDown() ) then
local itemLink = GetMerchantItemLink(self:GetID())
if not itemLink then return end
local maxStack = select(8, GetItemInfo(itemLink))
if ( maxStack and maxStack > 1 ) then
BuyMerchantItem(self:GetID(), GetMerchantItemMaxStack(self:GetID()))
end
end
savedMerchantItemButton_OnModifiedClick(self, ...)
end
end
M:RegisterMiscModule("Merchant", LoadFunc)
|
local R, L, P = unpack(select(2, ...)) --Inport: Engine, Locales, ProfileDB
local M = R:GetModule("Misc")
local function LoadFunc()
if not M.db.merchant then return end
local poisons = {
[6947] = 20, --速效
[3775] = 20, --减速
-- [5237] = 20, --麻痹
[2892] = 20, --致命
[10918] = 20, --致伤
}
local f = CreateFrame("Frame")
f:SetScript("OnEvent", function()
local c = 0
for b=0,4 do
for s=1,GetContainerNumSlots(b) do
local l = GetContainerItemLink(b, s)
if l and select(11, GetItemInfo(l)) then
local p = select(11, GetItemInfo(l))*select(2, GetContainerItemInfo(b, s))
if select(3, GetItemInfo(l))==0 and p>0 then
UseContainerItem(b, s)
PickupMerchantItem()
c = c+p
end
end
end
end
if c>0 then
local g, s, c = math.floor(c/10000) or 0, math.floor((c%10000)/100) or 0, c%100
DEFAULT_CHAT_FRAME:AddMessage(L["您背包内的粗糙物品已被自动卖出, 您赚取了"].." |cffffffff"..g.."|cffffd700g|r".." |cffffffff"..s.."|cffc7c7cfs|r".." |cffffffff"..c.."|cffeda55fc|r.",255,255,0)
end
if not IsShiftKeyDown() then
if CanMerchantRepair() then
local cost, possible = GetRepairAllCost()
if cost>0 then
if possible then
local c = cost%100
local s = math.floor((cost%10000)/100) or 0
local g = math.floor(cost/10000) or 0
if IsInGuild() and CanGuildBankRepair() and ((GetGuildBankWithdrawMoney() >= cost) or (GetGuildBankWithdrawMoney() == -1)) and (GetGuildBankMoney() >= cost) then
RepairAllItems(1)
DEFAULT_CHAT_FRAME:AddMessage(L["您的装备已使用工会修理, 花费了"].." |cffffffff"..g.."|cffffd700g|r".." |cffffffff"..s.."|cffc7c7cfs|r".." |cffffffff"..c.."|cffeda55fc|r.",255,255,0)
elseif GetMoney() >= cost then
RepairAllItems()
DEFAULT_CHAT_FRAME:AddMessage(L["您的装备已修理, 花费了"].." |cffffffff"..g.."|cffffd700g|r".." |cffffffff"..s.."|cffc7c7cfs|r".." |cffffffff"..c.."|cffeda55fc|r.",255,255,0)
else
DEFAULT_CHAT_FRAME:AddMessage(L["您没有足够的金钱来修理!"],255,0,0)
return
end
end
end
end
end
if M.db.poisons and R.myclass == "ROGUE" then
local numItems = GetMerchantNumItems()
for i = 1, numItems do
local merchantItemLink = GetMerchantItemLink(i)
if merchantItemLink then
local id = tonumber(merchantItemLink:match("item:(%d+)"))
if poisons[id] and GetItemCount(id) < poisons[id] then
BuyMerchantItem(i, poisons[id] - GetItemCount(id))
end
end
end
end
end)
f:RegisterEvent("MERCHANT_SHOW")
-- buy max number value with alt
local savedMerchantItemButton_OnModifiedClick = MerchantItemButton_OnModifiedClick
function MerchantItemButton_OnModifiedClick(self, ...)
if ( IsAltKeyDown() ) then
local itemLink = GetMerchantItemLink(self:GetID())
if not itemLink then return end
local maxStack = select(8, GetItemInfo(itemLink))
if ( maxStack and maxStack > 1 ) then
BuyMerchantItem(self:GetID(), GetMerchantItemMaxStack(self:GetID()))
end
end
savedMerchantItemButton_OnModifiedClick(self, ...)
end
end
M:RegisterMiscModule("Merchant", LoadFunc)
|
修复一个自动卖垃圾可能引起的bug
|
修复一个自动卖垃圾可能引起的bug
|
Lua
|
mit
|
fgprodigal/RayUI
|
d297969c7cf6e87e8c618c0310a9eaf9c83cac28
|
ssbase/gamemode/cl_init.lua
|
ssbase/gamemode/cl_init.lua
|
---------------------------
-- Bunny Hop --
-- Created by xAaron113x --
---------------------------
include("player_class/player_ssbase.lua")
include("shared.lua")
include("sh_library.lua")
include("sh_profiles.lua")
include("sh_store.lua")
include("cl_scoreboard.lua")
include("cl_store.lua")
include("cl_chatbox.lua")
include("cl_hud.lua")
include("panels/ss_slot.lua")
include("panels/ss_slider.lua")
include("panels/ss_tooltip.lua")
include("panels/ss_checkbox.lua")
include("panels/ss_notify.lua")
GM:HUDAddShouldNotDraw("CHudHealth")
GM:HUDAddShouldNotDraw("CHudSecondaryAmmo")
GM:HUDAddShouldNotDraw("CHudAmmo")
GM:HUDAddShouldNotDraw("CHudChat")
SS.ScrW = ScrW()
SS.ScrH = ScrH()
GM.GUIBlurAmt = 0
GM.GUIBlurOverlay = Material("skeyler/vgui/blur_overlay")
local PP_SCREENBLUR_MAT = Material("pp/blurscreen")
function ResolutionCheck()
local w = ScrW()
if w <= 640 then
if !LocalPlayer or !LocalPlayer():IsValid() then timer.Simple(1, ResolutionCheck) return end
LocalPlayer():ChatPrint("** We don't support this low of a resolution.")
LocalPlayer():ChatPrint("** Please increase it for a better experience.")
end
end
function GM:SetGUIBlur(bool)
self.GUIBlur = bool or false
end
function GM:DrawOverlay()
if self.GUIBlurAmt > 0 or self.GUIBlur then
if self.GUIBlur and self.GUIBlurAmt != 10 then
self.GUIBlurAmt = math.Approach(self.GUIBlurAmt, 10, 0.2)
elseif !self.GUIBlur and self.GUIBlur != 10 then
self.GUIBlurAmt = math.Approach(self.GUIBlurAmt, 0, 0.5)
end
surface.SetMaterial(PP_SCREENBLUR_MAT)
surface.SetDrawColor(255, 255, 255, 255/10*self.GUIBlurAmt)
PP_SCREENBLUR_MAT:SetFloat("$blur", 2)
PP_SCREENBLUR_MAT:Recompute()
if render then render.UpdateScreenEffectTexture() end -- Todo: Make this available to menu Lua
surface.DrawTexturedRect(0, 0, ScrW(), ScrH())
surface.SetDrawColor(92, 92, 92, 200/10*self.GUIBlurAmt)
surface.SetMaterial(self.GUIBlurOverlay)
surface.DrawTexturedRect(0, 0, ScrW(), ScrH())
end
end
local MaxAmmo = {weapon_crowbar=0,weapon_physcannon=0,weapon_physgun=0,weapon_pistol=18,gmod_tool=0,weapon_357=6,weapon_smg1=45,weapon_ar2=30,weapon_crossbow=1,weapon_frag=1,weapon_rpg=1,weapon_shotgun=6}
function GetPrimaryClipSize(wep)
if !wep or !wep:IsValid() then return false end
if MaxAmmo[wep:GetClass()] then
return MaxAmmo[wep:GetClass()]
elseif wep.Primary and wep.Primary.ClipSize then
return wep.Primary.ClipSize
end
end
local mag_left, mag_extra, mag_clip
local function HUDAmmoCalc()
local wep = LocalPlayer():GetActiveWeapon()
if(!wep or wep == "Camera" or !wep.Clip1 or wep:Clip1() == -1) then return 1, 1, "" end
mag_left = wep:Clip1()
mag_extra = LocalPlayer():GetAmmoCount(wep:GetPrimaryAmmoType())
max_clip = MaxAmmo[wep:GetClass()] or wep.Primary.ClipSize
return mag_left, max_clip, tostring(mag_left).."/"..tostring(mag_extra)
end
-----------------------------------------------------------
-- Name: gamemode:PostDrawViewModel()
-- Desc: Called after drawing the view model
-----------------------------------------------------------
function GM:PostDrawViewModel( ViewModel, Player, Weapon )
if ( !IsValid( Weapon ) ) then return false end
if ( Weapon.UseHands || !Weapon:IsScripted() ) then
local hands = LocalPlayer():GetHands()
if ( IsValid( hands ) ) then hands:DrawModel() end
end
player_manager.RunClass( Player, "PostDrawViewModel", ViewModel, Weapon )
if ( Weapon.PostDrawViewModel == nil ) then return false end
return Weapon:PostDrawViewModel( ViewModel, Weapon, Player )
end
---------------------------------------------------------
--
---------------------------------------------------------
SS.ThirdPerson = CreateClientConVar("ss_thirdperson", 0, true)
SS.ThirdPersonDistance = CreateClientConVar("ss_thirdperson_distance", 128, true)
function GM:CalcView(player, origin, angle, fov, nearZ, farZ)
if (SS.ThirdPerson:GetBool()) then
local trace = {}
trace.start = origin
trace.endpos = trace.start -angle:Forward() *SS.ThirdPersonDistance:GetInt()
trace.filter = player
trace.mask = bit.bor(MASK_SOLID, MASK_SOLID_BRUSHONLY)
trace = util.TraceLine(trace)
return self.BaseClass:CalcView(player, trace.HitPos +trace.HitNormal *2.25, angle, fov, nearZ, farZ)
end
return self.BaseClass:CalcView(player, origin, angle, fov, nearZ, farZ)
end
---------------------------------------------------------
--
---------------------------------------------------------
function GM:ShouldDrawLocalPlayer(player)
local thirdPerson = SS.ThirdPerson:GetBool()
if (thirdPerson) then
return true
end
return self.BaseClass:ShouldDrawLocalPlayer(player)
end
|
---------------------------
-- Bunny Hop --
-- Created by xAaron113x --
---------------------------
include("player_class/player_ssbase.lua")
include("shared.lua")
include("sh_library.lua")
include("sh_profiles.lua")
include("sh_store.lua")
include("cl_scoreboard.lua")
include("cl_store.lua")
include("cl_chatbox.lua")
include("cl_hud.lua")
include("panels/ss_slot.lua")
include("panels/ss_slider.lua")
include("panels/ss_tooltip.lua")
include("panels/ss_checkbox.lua")
include("panels/ss_notify.lua")
GM:HUDAddShouldNotDraw("CHudHealth")
GM:HUDAddShouldNotDraw("CHudSecondaryAmmo")
GM:HUDAddShouldNotDraw("CHudAmmo")
GM:HUDAddShouldNotDraw("CHudChat")
SS.ScrW = ScrW()
SS.ScrH = ScrH()
GM.GUIBlurAmt = 0
GM.GUIBlurOverlay = Material("skeyler/vgui/blur_overlay")
local PP_SCREENBLUR_MAT = Material("pp/blurscreen")
function ResolutionCheck()
local w = ScrW()
if w <= 640 then
if !LocalPlayer or !LocalPlayer():IsValid() then timer.Simple(1, ResolutionCheck) return end
LocalPlayer():ChatPrint("** We don't support this low of a resolution.")
LocalPlayer():ChatPrint("** Please increase it for a better experience.")
end
end
function GM:SetGUIBlur(bool)
self.GUIBlur = bool or false
self.BlurStartTime = SysTime()-0.6
end
function GM:DrawOverlay()
if self.GUIBlurAmt > 0 or self.GUIBlur then
if self.GUIBlur and self.GUIBlurAmt != 10 then
self.GUIBlurAmt = math.Approach(self.GUIBlurAmt, 10, 0.2)
elseif !self.GUIBlur and self.GUIBlur != 10 then
self.GUIBlurAmt = math.Approach(self.GUIBlurAmt, 0, 0.5)
end
surface.SetMaterial(PP_SCREENBLUR_MAT)
surface.SetDrawColor(255, 255, 255, 200/10*self.GUIBlurAmt)
for i=0.33, 1, 0.33 do
PP_SCREENBLUR_MAT:SetFloat("$blur", 5*i)
PP_SCREENBLUR_MAT:Recompute()
if render then render.UpdateScreenEffectTexture() end
surface.DrawTexturedRect(0, 0, ScrW(), ScrH())
end
surface.SetDrawColor(255, 255, 255, 127/10*self.GUIBlurAmt)
surface.SetMaterial(self.GUIBlurOverlay)
surface.DrawTexturedRect(0, 0, ScrW(), ScrH())
end
end
local MaxAmmo = {weapon_crowbar=0,weapon_physcannon=0,weapon_physgun=0,weapon_pistol=18,gmod_tool=0,weapon_357=6,weapon_smg1=45,weapon_ar2=30,weapon_crossbow=1,weapon_frag=1,weapon_rpg=1,weapon_shotgun=6}
function GetPrimaryClipSize(wep)
if !wep or !wep:IsValid() then return false end
if MaxAmmo[wep:GetClass()] then
return MaxAmmo[wep:GetClass()]
elseif wep.Primary and wep.Primary.ClipSize then
return wep.Primary.ClipSize
end
end
local mag_left, mag_extra, mag_clip
local function HUDAmmoCalc()
local wep = LocalPlayer():GetActiveWeapon()
if(!wep or wep == "Camera" or !wep.Clip1 or wep:Clip1() == -1) then return 1, 1, "" end
mag_left = wep:Clip1()
mag_extra = LocalPlayer():GetAmmoCount(wep:GetPrimaryAmmoType())
max_clip = MaxAmmo[wep:GetClass()] or wep.Primary.ClipSize
return mag_left, max_clip, tostring(mag_left).."/"..tostring(mag_extra)
end
-----------------------------------------------------------
-- Name: gamemode:PostDrawViewModel()
-- Desc: Called after drawing the view model
-----------------------------------------------------------
function GM:PostDrawViewModel( ViewModel, Player, Weapon )
if ( !IsValid( Weapon ) ) then return false end
if ( Weapon.UseHands || !Weapon:IsScripted() ) then
local hands = LocalPlayer():GetHands()
if ( IsValid( hands ) ) then hands:DrawModel() end
end
player_manager.RunClass( Player, "PostDrawViewModel", ViewModel, Weapon )
if ( Weapon.PostDrawViewModel == nil ) then return false end
return Weapon:PostDrawViewModel( ViewModel, Weapon, Player )
end
---------------------------------------------------------
--
---------------------------------------------------------
SS.ThirdPerson = CreateClientConVar("ss_thirdperson", 0, true)
SS.ThirdPersonDistance = CreateClientConVar("ss_thirdperson_distance", 128, true)
function GM:CalcView(player, origin, angle, fov, nearZ, farZ)
if (SS.ThirdPerson:GetBool()) then
local trace = {}
trace.start = origin
trace.endpos = trace.start -angle:Forward() *SS.ThirdPersonDistance:GetInt()
trace.filter = player
trace.mask = bit.bor(MASK_SOLID, MASK_SOLID_BRUSHONLY)
trace = util.TraceLine(trace)
return self.BaseClass:CalcView(player, trace.HitPos +trace.HitNormal *2.25, angle, fov, nearZ, farZ)
end
return self.BaseClass:CalcView(player, origin, angle, fov, nearZ, farZ)
end
---------------------------------------------------------
--
---------------------------------------------------------
function GM:ShouldDrawLocalPlayer(player)
local thirdPerson = SS.ThirdPerson:GetBool()
if (thirdPerson) then
return true
end
return self.BaseClass:ShouldDrawLocalPlayer(player)
end
|
Blur fix and store background update
|
Blur fix and store background update
|
Lua
|
bsd-3-clause
|
T3hArco/skeyler-gamemodes
|
12f65f155130d2e725ff8f2096189e3ed46fd105
|
mod_muc_intercom/mod_muc_intercom.lua
|
mod_muc_intercom/mod_muc_intercom.lua
|
-- Relay messages between rooms
-- By Kim Alvefur <[email protected]>
local host_session = prosody.hosts[module.host];
local st_msg = require "util.stanza".message;
local jid = require "util.jid";
function check_message(data)
local origin, stanza = data.origin, data.stanza;
local muc_rooms = host_session.muc and host_session.muc.rooms;
if not muc_rooms then return; end
local this_room = muc_rooms[stanza.attr.to];
if not this_room then return; end -- no such room
local from_room_jid = this_room._jid_nick[stanza.attr.from];
if not from_room_jid then return; end -- no such nick
local from_room, from_host, from_nick = jid.split(from_room_jid);
local body = stanza:get_child("body");
body = body and body:get_text(); -- I feel like I want to do `or ""` there :/
local target_room, message = body:match("^@([^:]+):(.*)");
if not target_room or not message then return; end
if target_room == from_room then return; end -- don't route to itself
module:log("debug", "target room is %s", target_room);
local bare_room = jid.join(target_room, from_host);
if not muc_rooms[bare_room] then return; end -- TODO send a error
module:log("info", "message from %s in %s to %s", from_nick, from_room, target_room);
local sender = jid.join(target_room, module.host, from_room .. "/" .. from_nick);
local forward_stanza = st_msg({from = sender, to = bare_room, type = "groupchat"}, message);
module:log("debug", "broadcasting message to target room");
muc_rooms[bare_room]:broadcast_message(forward_stanza);
end
module:hook("message/bare", check_message);
|
-- Relay messages between rooms
-- By Kim Alvefur <[email protected]>
local host_session = prosody.hosts[module.host];
local st_msg = require "util.stanza".message;
local jid = require "util.jid";
function check_message(data)
local origin, stanza = data.origin, data.stanza;
local muc_rooms = host_session.muc and host_session.muc.rooms;
if not muc_rooms then return; end
local this_room = muc_rooms[stanza.attr.to];
if not this_room then return; end -- no such room
local from_room_jid = this_room._jid_nick[stanza.attr.from];
if not from_room_jid then return; end -- no such nick
local from_room, from_host, from_nick = jid.split(from_room_jid);
local body = stanza:get_child("body");
if not body then return; end -- No body, like topic changes
body = body and body:get_text(); -- I feel like I want to do `or ""` there :/
local target_room, message = body:match("^@([^:]+):(.*)");
if not target_room or not message then return; end
if target_room == from_room then return; end -- don't route to itself
module:log("debug", "target room is %s", target_room);
local bare_room = jid.join(target_room, from_host);
if not muc_rooms[bare_room] then return; end -- TODO send a error
module:log("info", "message from %s in %s to %s", from_nick, from_room, target_room);
local sender = jid.join(target_room, module.host, from_room .. "/" .. from_nick);
local forward_stanza = st_msg({from = sender, to = bare_room, type = "groupchat"}, message);
module:log("debug", "broadcasting message to target room");
muc_rooms[bare_room]:broadcast_message(forward_stanza);
end
module:hook("message/bare", check_message);
|
mod_muc_intercom: Fix traceback on topic changes
|
mod_muc_intercom: Fix traceback on topic changes
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
b26fb438e149ac6c3cd19e607f1698d6144c5d07
|
genie/engine.lua
|
genie/engine.lua
|
--
-- Copyright (c) 2015 Jonathan Howard.
--
function engine_project( _name, _kind, _defines )
project ( _name )
kind (_kind)
includedirs
{
ENG_DIR .. "src/",
BGFX_DIR .. "examples/common"
}
defines
{
_defines
}
links
{
"example-common",
"bgfx",
"assimp"
}
if not _OPTIONS["with-no-luajit"] then
includedirs
{
ENG_DIR .. "ext/luajit/src",
}
configuration { "linux-* or osx" }
links
{
"luajit"
}
configuration { "osx" }
libdirs
{
ENG_DIR .. "ext/luajit/lib/osx_x64"
}
postbuildcommands {
"cp " .. ENG_DIR .. "ext/luajit/lib/osx_x64/luajit " .. ENG_DIR .. "build/osx/bin",
"cp -r " .. ENG_DIR .. "ext/luajit/src/jit " .. ENG_DIR .. "build/osx/bin",
}
configuration { "x64", "linux-*" }
libdirs
{
ENG_DIR .. "ext/luajit/lib/linux_x64"
}
postbuildcommands {
"cp " .. ENG_DIR .. "ext/luajit/lib/linux_x64/luajit " .. ENG_DIR .. "build/linux/bin",
"cp -r " .. ENG_DIR .. "ext/luajit/src/jit " .. ENG_DIR .. "build/linux/bin",
}
configuration { "vs*"}
links
{
"lua51"
}
configuration { "x32", "vs*" }
libdirs
{
ENG_DIR .. "ext/luajit/lib/win_x86"
}
configuration { "x64", "vs*" }
libdirs
{
ENG_DIR .. "ext/luajit/lib/win_x64"
}
configuration {} -- reset
end
configuration { "debug or development" }
flags {
"Symbols"
}
defines {
"_DEBUG",
}
configuration { "release" }
defines {
"NDEBUG"
}
configuration {}
files
{
ENG_DIR .. "src/**.h",
ENG_DIR .. "src/*.cpp",
path.join(BGFX_DIR, "examples/common/**.mm"),
}
strip()
configuration {}
end
|
--
-- Copyright (c) 2015 Jonathan Howard.
--
function engine_project( _name, _kind, _defines )
project ( _name )
kind (_kind)
includedirs
{
ENG_DIR .. "src/",
BGFX_DIR .. "examples/common"
}
defines
{
_defines
}
links
{
"example-common",
"bgfx",
"assimp"
}
if not _OPTIONS["with-no-luajit"] then
includedirs
{
ENG_DIR .. "ext/luajit/src",
}
configuration { "linux-* or osx" }
links
{
"luajit"
}
configuration { "osx" }
linkoptions
{
"-pagezero_size 10000",
"-image_base 100000000"
}
libdirs
{
ENG_DIR .. "ext/luajit/lib/osx_x64"
}
postbuildcommands {
"cp " .. ENG_DIR .. "ext/luajit/lib/osx_x64/luajit " .. ENG_DIR .. "build/osx/bin",
"cp -r " .. ENG_DIR .. "ext/luajit/src/jit " .. ENG_DIR .. "build/osx/bin",
}
configuration { "x64", "linux-*" }
libdirs
{
ENG_DIR .. "ext/luajit/lib/linux_x64"
}
postbuildcommands {
"cp " .. ENG_DIR .. "ext/luajit/lib/linux_x64/luajit " .. ENG_DIR .. "build/linux/bin",
"cp -r " .. ENG_DIR .. "ext/luajit/src/jit " .. ENG_DIR .. "build/linux/bin",
}
configuration { "vs*"}
links
{
"lua51"
}
configuration { "x32", "vs*" }
libdirs
{
ENG_DIR .. "ext/luajit/lib/win_x86"
}
configuration { "x64", "vs*" }
libdirs
{
ENG_DIR .. "ext/luajit/lib/win_x64"
}
configuration {} -- reset
end
configuration { "debug or development" }
flags {
"Symbols"
}
defines {
"_DEBUG",
}
configuration { "release" }
defines {
"NDEBUG"
}
configuration {}
files
{
ENG_DIR .. "src/**.h",
ENG_DIR .. "src/**.cpp",
path.join(BGFX_DIR, "examples/common/**.mm"),
}
strip()
configuration {}
end
|
fixes libluajit on OS X
|
fixes libluajit on OS X
|
Lua
|
mit
|
v3n/altertum,NathanaelThompson/altertum,NathanaelThompson/altertum,v3n/altertum,NathanaelThompson/altertum,v3n/altertum
|
b71bb5d525dd38a6d4e0991064f6c243f666bb2e
|
packages/lime-proto-bmx6/src/bmx6.lua
|
packages/lime-proto-bmx6/src/bmx6.lua
|
#!/usr/bin/lua
local network = require("lime.network")
local config = require("lime.config")
local fs = require("nixio.fs")
local libuci = require("uci")
local wireless = require("lime.wireless")
bmx6 = {}
function bmx6.setup_interface(ifname, args)
if ifname:match("^wlan%d.ap") then return end
vlanId = args[2] or 13
vlanProto = args[3] or "8021ad"
nameSuffix = args[4] or "_bmx6"
local owrtInterfaceName, linux802adIfName, owrtDeviceName = network.createVlanIface(ifname, vlanId, nameSuffix, vlanProto)
local uci = libuci:cursor()
uci:set("network", owrtDeviceName, "mtu", "1398")
-- BEGIN [Workaround issue 38]
if ifname:match("^wlan%d+") then
local macAddr = wireless.get_phy_mac("phy"..ifname:match("%d+"))
local vlanIp = { 169, 254, tonumber(macAddr[5], 16), tonumber(macAddr[6], 16) }
uci:set("network", owrtInterfaceName, "proto", "static")
uci:set("network", owrtInterfaceName, "ipaddr", table.concat(vlanIp, "."))
uci:set("network", owrtInterfaceName, "netmask", "255.255.255.255")
end
--- END [Workaround issue 38]
uci:save("network")
uci:set("bmx6", owrtInterfaceName, "dev")
uci:set("bmx6", owrtInterfaceName, "dev", linux802adIfName)
-- BEGIN [Workaround issue 40]
if ifname:match("^wlan%d+") then
uci:set("bmx6", owrtInterfaceName, "rateMax", "54000")
end
--- END [Workaround issue 40]
uci:save("bmx6")
end
function bmx6.clean()
print("Clearing bmx6 config...")
fs.writefile("/etc/config/bmx6", "")
local uci = libuci:cursor()
uci:delete("firewall", "bmxtun")
uci:save("firewall")
end
function bmx6.configure(args)
bmx6.clean()
local ipv4, ipv6 = network.primary_address()
local uci = libuci:cursor()
uci:set("bmx6", "general", "bmx6")
uci:set("bmx6", "general", "dbgMuteTimeout", "1000000")
uci:set("bmx6", "general", "tunOutTimeout", "0")
uci:set("bmx6", "main", "tunDev")
uci:set("bmx6", "main", "tunDev", "main")
uci:set("bmx6", "main", "tun4Address", ipv4:host():string().."/32")
uci:set("bmx6", "main", "tun6Address", ipv6:host():string().."/128")
-- Enable bmx6 uci config plugin
uci:set("bmx6", "config", "plugin")
uci:set("bmx6", "config", "plugin", "bmx6_config.so")
-- Enable JSON plugin to get bmx6 information in json format
uci:set("bmx6", "json", "plugin")
uci:set("bmx6", "json", "plugin", "bmx6_json.so")
-- Disable ThrowRules because they are broken in IPv6 with current Linux Kernel
uci:set("bmx6", "ipVersion", "ipVersion")
uci:set("bmx6", "ipVersion", "ipVersion", "6")
-- Search for networks in 172.16.0.0/12
uci:set("bmx6", "nodes", "tunOut")
uci:set("bmx6", "nodes", "tunOut", "nodes")
uci:set("bmx6", "nodes", "network", "172.16.0.0/12")
-- Search for networks in 10.0.0.0/8
uci:set("bmx6", "clouds", "tunOut")
uci:set("bmx6", "clouds", "tunOut", "clouds")
uci:set("bmx6", "clouds", "network", "10.0.0.0/8")
-- Search for internet in the mesh cloud
uci:set("bmx6", "inet4", "tunOut")
uci:set("bmx6", "inet4", "tunOut", "inet4")
uci:set("bmx6", "inet4", "network", "0.0.0.0/0")
uci:set("bmx6", "inet4", "maxPrefixLen", "0")
-- Search for internet IPv6 gateways in the mesh cloud
uci:set("bmx6", "inet6", "tunOut")
uci:set("bmx6", "inet6", "tunOut", "inet6")
uci:set("bmx6", "inet6", "network", "::/0")
uci:set("bmx6", "inet6", "maxPrefixLen", "0")
-- Search for other mesh cloud announcements that have public ipv6
uci:set("bmx6", "publicv6", "tunOut")
uci:set("bmx6", "publicv6", "tunOut", "publicv6")
uci:set("bmx6", "publicv6", "network", "2000::/3")
uci:set("bmx6", "publicv6", "maxPrefixLen", "64")
-- Announce local ipv4 cloud
uci:set("bmx6", "local4", "tunIn")
uci:set("bmx6", "local4", "tunIn", "local4")
uci:set("bmx6", "local4", "network", ipv4:network():string().."/"..ipv4:prefix())
-- Announce local ipv6 cloud
uci:set("bmx6", "local6", "tunIn")
uci:set("bmx6", "local6", "tunIn", "local6")
uci:set("bmx6", "local6", "network", ipv6:network():string().."/"..ipv6:prefix())
if config.get_bool("network", "bmx6_over_batman") then
for _,protoArgs in pairs(config.get("network", "protocols")) do
if(utils.split(protoArgs, network.protoParamsSeparator)[1] == "batadv") then bmx6.setup_interface("bat0", args) end
end
end
uci:save("bmx6")
uci:set("firewall", "bmxtun", "zone")
uci:set("firewall", "bmxtun", "name", "bmxtun")
uci:set("firewall", "bmxtun", "input", "ACCEPT")
uci:set("firewall", "bmxtun", "output", "ACCEPT")
uci:set("firewall", "bmxtun", "forward", "ACCEPT")
uci:set("firewall", "bmxtun", "mtu_fix", "1")
uci:set("firewall", "bmxtun", "conntrack", "1")
uci:set("firewall", "bmxtun", "device", "bmx+")
uci:set("firewall", "bmxtun", "family", "ipv4")
uci:save("firewall")
end
function bmx6.apply()
os.execute("killall bmx6 ; sleep 2 ; killall -9 bmx6")
os.execute("bmx6")
end
return bmx6
|
#!/usr/bin/lua
local network = require("lime.network")
local config = require("lime.config")
local fs = require("nixio.fs")
local libuci = require("uci")
local wireless = require("lime.wireless")
bmx6 = {}
function bmx6.setup_interface(ifname, args)
if ifname:match("^wlan%d.ap") then return end
vlanId = args[2] or 13
vlanProto = args[3] or "8021ad"
nameSuffix = args[4] or "_bmx6"
local owrtInterfaceName, linux802adIfName, owrtDeviceName = network.createVlanIface(ifname, vlanId, nameSuffix, vlanProto)
local uci = libuci:cursor()
uci:set("network", owrtDeviceName, "mtu", "1398")
-- BEGIN [Workaround issue 38]
if ifname:match("^wlan%d+") then
local macAddr = wireless.get_phy_mac("phy"..ifname:match("%d+"))
local vlanIp = { 169, 254, tonumber(macAddr[5], 16), tonumber(macAddr[6], 16) }
uci:set("network", owrtInterfaceName, "proto", "static")
uci:set("network", owrtInterfaceName, "ipaddr", table.concat(vlanIp, "."))
uci:set("network", owrtInterfaceName, "netmask", "255.255.255.255")
end
--- END [Workaround issue 38]
uci:save("network")
uci:set("bmx6", owrtInterfaceName, "dev")
uci:set("bmx6", owrtInterfaceName, "dev", linux802adIfName)
-- BEGIN [Workaround issue 40]
if ifname:match("^wlan%d+") then
uci:set("bmx6", owrtInterfaceName, "rateMax", "54000")
end
--- END [Workaround issue 40]
uci:save("bmx6")
end
function bmx6.clean()
print("Clearing bmx6 config...")
fs.writefile("/etc/config/bmx6", "")
local uci = libuci:cursor()
uci:delete("firewall", "bmxtun")
uci:save("firewall")
end
function bmx6.configure(args)
bmx6.clean()
local ipv4, ipv6 = network.primary_address()
local uci = libuci:cursor()
uci:set("bmx6", "general", "bmx6")
uci:set("bmx6", "general", "dbgMuteTimeout", "1000000")
uci:set("bmx6", "general", "tunOutTimeout", "0")
uci:set("bmx6", "main", "tunDev")
uci:set("bmx6", "main", "tunDev", "main")
uci:set("bmx6", "main", "tun4Address", ipv4:string())
uci:set("bmx6", "main", "tun6Address", ipv6:string())
-- Enable bmx6 uci config plugin
uci:set("bmx6", "config", "plugin")
uci:set("bmx6", "config", "plugin", "bmx6_config.so")
-- Enable JSON plugin to get bmx6 information in json format
uci:set("bmx6", "json", "plugin")
uci:set("bmx6", "json", "plugin", "bmx6_json.so")
-- Disable ThrowRules because they are broken in IPv6 with current Linux Kernel
uci:set("bmx6", "ipVersion", "ipVersion")
uci:set("bmx6", "ipVersion", "ipVersion", "6")
-- Search for networks in 172.16.0.0/12
uci:set("bmx6", "nodes", "tunOut")
uci:set("bmx6", "nodes", "tunOut", "nodes")
uci:set("bmx6", "nodes", "network", "172.16.0.0/12")
-- Search for networks in 10.0.0.0/8
uci:set("bmx6", "clouds", "tunOut")
uci:set("bmx6", "clouds", "tunOut", "clouds")
uci:set("bmx6", "clouds", "network", "10.0.0.0/8")
-- Search for internet in the mesh cloud
uci:set("bmx6", "inet4", "tunOut")
uci:set("bmx6", "inet4", "tunOut", "inet4")
uci:set("bmx6", "inet4", "network", "0.0.0.0/0")
uci:set("bmx6", "inet4", "maxPrefixLen", "0")
-- Search for internet IPv6 gateways in the mesh cloud
uci:set("bmx6", "inet6", "tunOut")
uci:set("bmx6", "inet6", "tunOut", "inet6")
uci:set("bmx6", "inet6", "network", "::/0")
uci:set("bmx6", "inet6", "maxPrefixLen", "0")
-- Search for other mesh cloud announcements that have public ipv6
uci:set("bmx6", "publicv6", "tunOut")
uci:set("bmx6", "publicv6", "tunOut", "publicv6")
uci:set("bmx6", "publicv6", "network", "2000::/3")
uci:set("bmx6", "publicv6", "maxPrefixLen", "64")
if config.get_bool("network", "bmx6_over_batman") then
for _,protoArgs in pairs(config.get("network", "protocols")) do
if(utils.split(protoArgs, network.protoParamsSeparator)[1] == "batadv") then bmx6.setup_interface("bat0", args) end
end
end
uci:save("bmx6")
uci:set("firewall", "bmxtun", "zone")
uci:set("firewall", "bmxtun", "name", "bmxtun")
uci:set("firewall", "bmxtun", "input", "ACCEPT")
uci:set("firewall", "bmxtun", "output", "ACCEPT")
uci:set("firewall", "bmxtun", "forward", "ACCEPT")
uci:set("firewall", "bmxtun", "mtu_fix", "1")
uci:set("firewall", "bmxtun", "conntrack", "1")
uci:set("firewall", "bmxtun", "device", "bmx+")
uci:set("firewall", "bmxtun", "family", "ipv4")
uci:save("firewall")
end
function bmx6.apply()
os.execute("killall bmx6 ; sleep 2 ; killall -9 bmx6")
os.execute("bmx6")
end
return bmx6
|
lime-proto-bmx6: simplify bmx6 config, merge local[4|6] tunIns into tun[4|6]Address
|
lime-proto-bmx6: simplify bmx6 config, merge local[4|6] tunIns into tun[4|6]Address
bmx6 automatically announces the correspondent tunIn
if tunXAddress is a network (/64) rather than a host (/128).
So it's better to not announce specific host routes,
since this creates many extra routes and tunnels
which clutter up the system.
This commit is a combined revert of both:
016612c lime-proto-bmx6: fix bmx6 main addresses
2fd4a4b lime-proto-bmx6 Add also local ipv6 announcement
|
Lua
|
agpl-3.0
|
libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,p4u/lime-packages,p4u/lime-packages
|
b20690f5501ff1adf2459e13e942f3e570b177d7
|
packages/tate.lua
|
packages/tate.lua
|
-- Japaneese language support defines units which are useful here
SILE.languageSupport.loadLanguage("ja")
SILE.tateFramePrototype = pl.class({
_base = SILE.framePrototype,
direction = "TTB-RTL",
enterHooks = {
function (self)
self.oldtypesetter = SILE.typesetter
SILE.typesetter.leadingFor = function(_, v)
v.height = SILE.length("1zw"):absolute()
local bls = SILE.settings.get("document.baselineskip")
local d = bls.height:absolute() - v.height
local len = SILE.length(d.length, bls.height.stretch, bls.height.shrink)
return SILE.nodefactory.vglue({height = len})
end
SILE.typesetter.breakIntoLines = SILE.require("packages/break-firstfit").exports.breakIntoLines
end
},
leaveHooks = {
function (self)
SILE.typesetter = self.oldtypesetter
end
}
})
SILE.newTateFrame = function (spec)
return SILE.newFrame(spec, SILE.tateFramePrototype)
end
SILE.registerCommand("tate-frame", function (options, _)
SILE.documentState.thisPageTemplate.frames[options.id] = SILE.newTateFrame(options)
end, "Declares (or re-declares) a frame on this page.")
local outputLatinInTate = function (self, typesetter, line)
-- My baseline moved
typesetter.frame:advanceWritingDirection(SILE.measurement("-0.5zw"))
typesetter.frame:advancePageDirection(SILE.measurement("0.25zw"))
local vorigin = -typesetter.frame.state.cursorY
self:oldOutputYourself(typesetter,line)
typesetter.frame.state.cursorY = -vorigin
typesetter.frame:advanceWritingDirection(self:lineContribution())
-- My baseline moved
typesetter.frame:advanceWritingDirection(SILE.measurement("0.5zw") )
typesetter.frame:advancePageDirection(-SILE.measurement("0.25zw"))
end
local outputTateChuYoko = function (self, typesetter, line)
-- My baseline moved
local em = SILE.measurement("1zw")
typesetter.frame:advanceWritingDirection(-em + em/4 - self:lineContribution()/2)
typesetter.frame:advancePageDirection(2*self.height - self.width/2)
self:oldOutputYourself(typesetter,line)
typesetter.frame:advanceWritingDirection(-self:lineContribution()*1.5+self.height*3/4)
end
-- Eventually will be automatically called by script detection, but for now
-- called manually
SILE.registerCommand("latin-in-tate", function (_, content)
local nodes
local oldT = SILE.typesetter
local prevDirection = oldT.frame.direction
if oldT.frame:writingDirection() ~= "TTB" then return SILE.process(content) end
SILE.require("packages/rotate")
SILE.settings.temporarily(function()
local latinT = SILE.defaultTypesetter {}
latinT.frame = SILE.framePrototype({}, true) -- not fully initialized, just a dummy
latinT:initState()
SILE.typesetter = latinT
SILE.settings.set("document.language", "und")
SILE.settings.set("font.direction", "LTR")
SILE.process(content)
nodes = SILE.typesetter.state.nodes
SILE.typesetter:shapeAllNodes(nodes)
SILE.typesetter.frame.direction = prevDirection
end)
SILE.typesetter = oldT
SILE.typesetter:pushGlue({
width = SILE.length("0.5zw", "0.25zw", "0.25zw"):absolute()
})
for i = 1,#nodes do
if SILE.typesetter.frame:writingDirection() ~= "TTB" then
SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes+1] = nodes[i]
elseif nodes[i].is_glue then
nodes[i].width = nodes[i].width
SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes+1] = nodes[i]
elseif nodes[i]:lineContribution():tonumber() > 0 then
SILE.call("hbox", {}, function ()
SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes+1] = nodes[i]
end)
local n = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes]
n.oldOutputYourself = n.outputYourself
n.outputYourself = outputLatinInTate
end
end
end, "Typeset rotated Western text in vertical Japanese")
SILE.registerCommand("tate-chu-yoko", function (_, content)
if SILE.typesetter.frame:writingDirection() ~= "TTB" then return SILE.process(content) end
-- SILE.typesetter:pushGlue({
-- width = SILE.length.new({length = SILE.toPoints("0.5zw"),
-- stretch = SILE.toPoints("0.25zw"),
-- shrink = SILE.toPoints("0.25zw")
-- })
-- })
SILE.settings.temporarily(function()
SILE.settings.set("document.language", "und")
SILE.settings.set("font.direction", "LTR")
SILE.call("rotate",{angle =-90}, function ()
SILE.call("hbox", {}, content)
local n = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes]
n.misfit = true
n.oldOutputYourself = n.outputYourself
n.outputYourself = outputTateChuYoko
end)
end)
-- SILE.typesetter:pushGlue({
-- width = SILE.length.new({length = SILE.toPoints("0.5zw"),
-- stretch = SILE.toPoints("0.25zw"),
-- shrink = SILE.toPoints("0.25zw")
-- })
-- })
end)
return {
documentation = [[
\begin{document}
The \code{tate} package provides support for Japanese vertical typesetting.
It allows for the definition of vertical-oriented frames, as well
as for two specific typesetting techniques required in vertical
documents: \code{latin-in-tate} typesets its content as Latin
text rotated 90 degrees, and \code{tate-chu-yoko} places (Latin)
text horizontally within a single grid-square of the vertical \em{hanmen}.
\end{document}
]]
}
|
-- Japaneese language support defines units which are useful here
SILE.languageSupport.loadLanguage("ja")
SILE.tateFramePrototype = pl.class({
_base = SILE.framePrototype,
direction = "TTB-RTL",
enterHooks = {
function (self)
self.oldtypesetter = SILE.typesetter
SILE.typesetter.leadingFor = function(_, v)
v.height = SILE.length("1zw"):absolute()
local bls = SILE.settings.get("document.baselineskip")
local d = bls.height:absolute() - v.height
local len = SILE.length(d.length, bls.height.stretch, bls.height.shrink)
return SILE.nodefactory.vglue({height = len})
end
SILE.typesetter.breakIntoLines = SILE.require("packages/break-firstfit").exports.breakIntoLines
end
},
leaveHooks = {
function (self)
SILE.typesetter = self.oldtypesetter
end
}
})
SILE.newTateFrame = function (spec)
return SILE.newFrame(spec, SILE.tateFramePrototype)
end
SILE.registerCommand("tate-frame", function (options, _)
SILE.documentState.thisPageTemplate.frames[options.id] = SILE.newTateFrame(options)
end, "Declares (or re-declares) a frame on this page.")
local outputLatinInTate = function (self, typesetter, line)
-- My baseline moved
typesetter.frame:advanceWritingDirection(SILE.measurement("-0.5zw"))
typesetter.frame:advancePageDirection(SILE.measurement("0.25zw"))
local vorigin = -typesetter.frame.state.cursorY
self:oldOutputYourself(typesetter,line)
typesetter.frame.state.cursorY = -vorigin
typesetter.frame:advanceWritingDirection(self:lineContribution())
-- My baseline moved
typesetter.frame:advanceWritingDirection(SILE.measurement("0.5zw") )
typesetter.frame:advancePageDirection(-SILE.measurement("0.25zw"))
end
local outputTateChuYoko = function (self, typesetter, line)
-- My baseline moved
local em = SILE.measurement("1zw")
typesetter.frame:advanceWritingDirection(-em + em/4 - self:lineContribution()/2)
typesetter.frame:advancePageDirection(2*self.height - self.width/2)
self:oldOutputYourself(typesetter,line)
typesetter.frame:advanceWritingDirection(-self:lineContribution()*1.5+self.height*3/4)
end
-- Eventually will be automatically called by script detection, but for now
-- called manually
SILE.registerCommand("latin-in-tate", function (_, content)
local nodes
local oldT = SILE.typesetter
local prevDirection = oldT.frame.direction
if oldT.frame:writingDirection() ~= "TTB" then return SILE.process(content) end
SILE.require("packages/rotate")
SILE.settings.temporarily(function()
local latinT = SILE.defaultTypesetter {}
latinT.frame = SILE.framePrototype({}, true) -- not fully initialized, just a dummy
latinT:initState()
SILE.typesetter = latinT
SILE.settings.set("document.language", "und")
SILE.settings.set("font.direction", "LTR")
SILE.process(content)
nodes = SILE.typesetter.state.nodes
SILE.typesetter:shapeAllNodes(nodes)
SILE.typesetter.frame.direction = prevDirection
end)
SILE.typesetter = oldT
SILE.typesetter:pushGlue({
width = SILE.length("0.5zw", "0.25zw", "0.25zw"):absolute()
})
for i = 1,#nodes do
if SILE.typesetter.frame:writingDirection() ~= "TTB" then
SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes+1] = nodes[i]
elseif nodes[i].is_glue then
nodes[i].width = nodes[i].width
SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes+1] = nodes[i]
elseif nodes[i]:lineContribution():tonumber() > 0 then
SILE.call("hbox", {}, function ()
SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes+1] = nodes[i]
end)
local n = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes]
-- Turn off all complex flags.
for j = 1,#(n.value) do
for k = 1,#(n.value[j].nodes) do
n.value[j].nodes[k].value.complex = false
end
end
n.oldOutputYourself = n.outputYourself
n.outputYourself = outputLatinInTate
end
end
end, "Typeset rotated Western text in vertical Japanese")
SILE.registerCommand("tate-chu-yoko", function (_, content)
if SILE.typesetter.frame:writingDirection() ~= "TTB" then return SILE.process(content) end
-- SILE.typesetter:pushGlue({
-- width = SILE.length.new({length = SILE.toPoints("0.5zw"),
-- stretch = SILE.toPoints("0.25zw"),
-- shrink = SILE.toPoints("0.25zw")
-- })
-- })
SILE.settings.temporarily(function()
SILE.settings.set("document.language", "und")
SILE.settings.set("font.direction", "LTR")
SILE.call("rotate",{angle =-90}, function ()
SILE.call("hbox", {}, content)
local n = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes]
n.misfit = true
n.oldOutputYourself = n.outputYourself
n.outputYourself = outputTateChuYoko
end)
end)
-- SILE.typesetter:pushGlue({
-- width = SILE.length.new({length = SILE.toPoints("0.5zw"),
-- stretch = SILE.toPoints("0.25zw"),
-- shrink = SILE.toPoints("0.25zw")
-- })
-- })
end)
return {
documentation = [[
\begin{document}
The \code{tate} package provides support for Japanese vertical typesetting.
It allows for the definition of vertical-oriented frames, as well
as for two specific typesetting techniques required in vertical
documents: \code{latin-in-tate} typesets its content as Latin
text rotated 90 degrees, and \code{tate-chu-yoko} places (Latin)
text horizontally within a single grid-square of the vertical \em{hanmen}.
\end{document}
]]
}
|
fix(packages): Turn off complex flag for items in \latin-in-tate
|
fix(packages): Turn off complex flag for items in \latin-in-tate
Arguably breaks vertical Arabic in Japanese, but to be fair it was
broken already.
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
3aa2c680a277ad222fc8d0f16d0bef449801445f
|
Modules/qGUI/Compass/ICompass.lua
|
Modules/qGUI/Compass/ICompass.lua
|
local ICompass = {}
ICompass.__index = ICompass
ICompass.ClassName = "ICompass"
ICompass.PercentSolid = 0.8
ICompass.ThetaVisible = math.pi/2
--- Provides a basis for the compass GUI. Invidiual CompassElements handle
-- the positioning.
-- @author Quenty
function ICompass.new(CompassModel, Container)
--- Makes a skyrim style "strip" compass.
-- @param CompassModel A CompassModel to use for this compass
-- @param Container A ROBLOX GUI to use as a container
local self = setmetatable({}, ICompass)
-- Composition
self.CompassModel = CompassModel or error("No CompassModel")
self.Container = Container or error("No Container")
self.Elements = {}
return self
end
function ICompass:SetPercentSolid(PercentSolid)
--- Sets the percentage of the compass that is solid (that is, visible), to the player
-- This way, we can calculate transparency
-- @param PercentSolid Number [0, 1] of the percentage solid fo the compass element.
self.PercentSolid = tonumber(PercentSolid) or error("No PercentSolid")
for Element, _ in pairs(self.Elements) do
Element:SetPercentSolid(self.PercentSolid)
end
end
function ICompass:SetThetaVisible(ThetaVisible)
-- Sets the area shown by the compass (the rest will be hidden). (In radians).
-- @param ThetaVisible Number [0, 6.28...] The theta in radians visible to the player overall.
self.ThetaVisible = tostring(ThetaVisible) or error("No or invalid ThetaVisible sent")
for Element, _ in pairs(self.Elements) do
Element:SetThetaVisible(self.ThetaVisible)
end
end
function ICompass:AddElement(Element)
-- @param Element An ICompassElement to be added to the system
assert(not self.Elements[Element], "Element already added")
self.Elements[Element] = true
Element:SetPercentSolid(self.PercentSolid)
Element:SetThetaVisible(self.ThetaVisible)
Element:GetGui().Parent = self.Container
end
function ICompass:GetPosition(PercentPosition)
--- Calculates the GUI position for the element
-- @param PercentPosition Number, the percent position to use
-- @return UDim2 The position (center) of the GUI element given its percentage. Relative to the container.
error("GetPosition is not overridden yet")
end
function ICompass:Draw()
--- Updates the compass for fun!
self.CompassModel:Step()
for Element, _ in pairs(self.Elements) do
local PercentPosition = Element:CalculatePercentPosition(self.CompassModel)
Element:SetPercentPosition(PercentPosition)
local NewPosition = self:GetPosition(PercentPosition)
Element:SetPosition(NewPosition)
Element:Draw()
end
end
return ICompass
|
local ICompass = {}
ICompass.__index = ICompass
ICompass.ClassName = "ICompass"
ICompass.PercentSolid = 0.8
ICompass.ThetaVisible = math.pi/2
--- Provides a basis for the compass GUI. Invidiual CompassElements handle
-- the positioning.
-- @author Quenty
function ICompass.new(CompassModel, Container)
--- Makes a skyrim style "strip" compass.
-- @param CompassModel A CompassModel to use for this compass
-- @param Container A ROBLOX GUI to use as a container
local self = setmetatable({}, ICompass)
-- Composition
self.CompassModel = CompassModel or error("No CompassModel")
self.Container = Container or error("No Container")
self.Elements = {}
return self
end
function ICompass:SetPercentSolid(PercentSolid)
--- Sets the percentage of the compass that is solid (that is, visible), to the player
-- This way, we can calculate transparency
-- @param PercentSolid Number [0, 1] of the percentage solid fo the compass element.
self.PercentSolid = tonumber(PercentSolid) or error("No PercentSolid")
for Element, _ in pairs(self.Elements) do
Element:SetPercentSolid(self.PercentSolid)
end
end
function ICompass:SetThetaVisible(ThetaVisible)
-- Sets the area shown by the compass (the rest will be hidden). (In radians).
-- @param ThetaVisible Number [0, 6.28...] The theta in radians visible to the player overall.
self.ThetaVisible = tonumber(ThetaVisible) or error("No or invalid ThetaVisible sent")
assert(ThetaVisible > 0, "ThetaVisible must be > 0")
for Element, _ in pairs(self.Elements) do
Element:SetThetaVisible(self.ThetaVisible)
end
end
function ICompass:AddElement(Element)
-- @param Element An ICompassElement to be added to the system
assert(not self.Elements[Element], "Element already added")
self.Elements[Element] = true
Element:SetPercentSolid(self.PercentSolid)
Element:SetThetaVisible(self.ThetaVisible)
Element:GetGui().Parent = self.Container
end
function ICompass:GetPosition(PercentPosition)
--- Calculates the GUI position for the element
-- @param PercentPosition Number, the percent position to use
-- @return UDim2 The position (center) of the GUI element given its percentage. Relative to the container.
-- @return [Rotation] Number in degrees, the rotation of the GUI to be set.
error("GetPosition is not overridden yet")
end
function ICompass:Draw()
--- Updates the compass for fun!
self.CompassModel:Step()
for Element, _ in pairs(self.Elements) do
local PercentPosition = Element:CalculatePercentPosition(self.CompassModel)
Element:SetPercentPosition(PercentPosition)
local NewPosition, NewRotation = self:GetPosition(PercentPosition)
Element:SetPosition(NewPosition)
if NewRotation then
Element:SetRotation(NewRotation)
end
Element:Draw()
end
end
return ICompass
|
tostring --> tonumber glitch fix, added rotation support
|
tostring --> tonumber glitch fix, added rotation support
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
02048eba958ab5ff2bf03497aeceea6f47f37bca
|
lua/LUA/spec/eep/EepSimulator_spec.lua
|
lua/LUA/spec/eep/EepSimulator_spec.lua
|
describe("EepFunktionen.lua", function()
insulate("EEPVer", function()
require("ak.core.eep.AkEepFunktionen")
it("EEPVer has value \"15\"", function() assert.are.equals(15, EEPVer) end)
end)
insulate("clearlog", function()
require("ak.core.eep.AkEepFunktionen")
it("clearlog() works ", function() clearlog() end)
end)
insulate("EEPSetSignal", function()
require("ak.core.eep.AkEepFunktionen")
describe("setzt Signal 2 auf Stellung 4", function()
EEPSetSignal(2, 4, 1)
it("gibt 4 zurck bei EEPGetSignal(2)", function() assert.are.equals(4, EEPGetSignal(2)) end)
end)
describe("setzt Signal 2 auf Stellung 3", function()
EEPSetSignal(2, 3, 1)
it("gibt 4 zurck bei EEPGetSignal(3)", function() assert.are.equals(3, EEPGetSignal(2)) end)
end)
end)
describe("Simulating signals on train", function()
insulate("single train in queue", function()
local EEPSimulator = require("ak.core.eep.AkEepFunktionen")
EEPSimulator.queueTrainOnSignal(54, "#train1")
it("no one waits on signal 53", function() assert.equals(0, EEPGetSignalTrainsCount(53)) end)
it("only train1 waits on signal 54", function()
assert.equals(1, EEPGetSignalTrainsCount(54))
assert.equals("#train1", EEPGetSignalTrainName(54, 1))
end)
end)
insulate("two trains in queue", function()
local EEPSimulator = require("ak.core.eep.AkEepFunktionen")
EEPSimulator.queueTrainOnSignal(54, "#train1")
EEPSimulator.queueTrainOnSignal(54, "#train2")
it("train1 and train2 wait on signal 54", function()
assert.equals(2, EEPGetSignalTrainsCount(54))
assert.equals("#train1", EEPGetSignalTrainName(54, 1))
assert.equals("#train2", EEPGetSignalTrainName(54, 2))
end)
end)
insulate("second train moves up, if first train leaves", function()
local EEPSimulator = require("ak.core.eep.AkEepFunktionen")
EEPSimulator.queueTrainOnSignal(54, "#train1")
EEPSimulator.queueTrainOnSignal(54, "#train2")
EEPSimulator.removeTrainFromSignal(54, "#train1")
it("only train2 waits on signal 54", function()
assert.equals(1, EEPGetSignalTrainsCount(54))
assert.equals("#train2", EEPGetSignalTrainName(54, 1))
end)
end)
insulate("all trains are removed correctly", function()
local EEPSimulator = require("ak.core.eep.AkEepFunktionen")
EEPSimulator.queueTrainOnSignal(54, "#train1")
EEPSimulator.queueTrainOnSignal(54, "#train2")
EEPSimulator.removeAllTrainFromSignal(54)
it("no waits on signal 54", function() assert.equals(0, EEPGetSignalTrainsCount(54)) end)
end)
end)
end)
|
describe("EepFunktionen.lua", function()
insulate("EEPVer", function()
require("ak.core.eep.AkEepFunktionen")
it("EEPVer has value \"15\"", function() assert.are.equals(15, EEPVer) end)
end)
insulate("clearlog", function()
require("ak.core.eep.AkEepFunktionen")
it("clearlog() works ", function() clearlog() end)
end)
insulate("EEPSetSignal", function()
require("ak.core.eep.AkEepFunktionen")
describe("setzt Signal 2 auf Stellung 4", function()
EEPSetSignal(2, 4, 1)
it("gibt 4 zurck bei EEPGetSignal(2)", function() assert.are.equals(4, EEPGetSignal(2)) end)
end)
describe("setzt Signal 2 auf Stellung 3", function()
EEPSetSignal(2, 3, 1)
it("gibt 4 zurck bei EEPGetSignal(3)", function() assert.are.equals(3, EEPGetSignal(2)) end)
end)
end)
describe("EEPGetSignalTrainsCount / EEPGetSignalTrainName - Simulating signals on train", function()
insulate("single train in queue", function()
local EEPSimulator = require("ak.core.eep.AkEepFunktionen")
EEPSimulator.queueTrainOnSignal(54, "#train1")
it("no one waits on signal 53", function() assert.equals(0, EEPGetSignalTrainsCount(53)) end)
it("only train1 waits on signal 54", function()
assert.equals(1, EEPGetSignalTrainsCount(54))
assert.equals("#train1", EEPGetSignalTrainName(54, 1))
end)
end)
insulate("two trains in queue", function()
local EEPSimulator = require("ak.core.eep.AkEepFunktionen")
EEPSimulator.queueTrainOnSignal(54, "#train1")
EEPSimulator.queueTrainOnSignal(54, "#train2")
it("train1 and train2 wait on signal 54", function()
assert.equals(2, EEPGetSignalTrainsCount(54))
assert.equals("#train1", EEPGetSignalTrainName(54, 1))
assert.equals("#train2", EEPGetSignalTrainName(54, 2))
end)
end)
insulate("second train moves up, if first train leaves", function()
local EEPSimulator = require("ak.core.eep.AkEepFunktionen")
EEPSimulator.queueTrainOnSignal(54, "#train1")
EEPSimulator.queueTrainOnSignal(54, "#train2")
EEPSimulator.removeTrainFromSignal(54, "#train1")
it("only train2 waits on signal 54", function()
assert.equals(1, EEPGetSignalTrainsCount(54))
assert.equals("#train2", EEPGetSignalTrainName(54, 1))
end)
end)
insulate("all trains are removed correctly", function()
local EEPSimulator = require("ak.core.eep.AkEepFunktionen")
EEPSimulator.queueTrainOnSignal(54, "#train1")
EEPSimulator.queueTrainOnSignal(54, "#train2")
EEPSimulator.removeAllTrainFromSignal(54)
it("no waits on signal 54", function() assert.equals(0, EEPGetSignalTrainsCount(54)) end)
end)
end)
end)
|
fix test description
|
fix test description
|
Lua
|
mit
|
Andreas-Kreuz/ak-lua-skripte-fuer-eep,Andreas-Kreuz/ak-lua-skripte-fuer-eep
|
3f2fc57a07bb9e658f4d53ccc60ba8177e3f1236
|
src/dns.resolvers.lua
|
src/dns.resolvers.lua
|
local loader = function(loader, ...)
local resolver = require"cqueues.dns.resolver"
local config = require"cqueues.dns.config"
local condition = require"cqueues.condition"
local monotime = require"cqueues".monotime
local random = require"cqueues.dns".random
local errno = require"cqueues.errno"
local ETIMEDOUT = errno.ETIMEDOUT
local function todeadline(timeout)
return (timeout and (monotime() + timeout)) or nil
end -- todeadline
local function totimeout(deadline)
return (deadline and math.max(0, deadline - monotime())) or nil
end -- totimeout
--
-- NOTE: Keep track of an unordered collection of objects, and in
-- particular a count of objects in the collection. If an object is
-- garbage collected automatically decrement the count and signal
-- the condition variable.
--
local alive = {}
function alive.new(condvar)
local self = setmetatable({}, { __index = alive })
self.n = 0
self.table = setmetatable({}, { __mode = "k" })
self.condvar = condvar
self.hooks = {}
self.hookmt = { __gc = function (hook)
self.n = self.n - 1
self.condvar:signal()
if self.leakcb then
pcall(self.leakcb)
end
end }
return self
end -- alive.new
local new_hook
if _G._VERSION == "Lua 5.1" then
-- Lua 5.1 does not support __gc on tables, so we need to use newproxy
new_hook = function(mt)
local u = newproxy(false)
debug.setmetatable(u, mt)
return u
end
else
new_hook = function(mt)
return setmetatable({}, mt)
end
end
function alive:add(x)
if not self.table[x] then
local hook = self.hooks[#self.hooks]
if hook then
self.hooks[#self.hooks] = nil
else
hook = new_hook(self.hookmt)
end
self.table[x] = hook
self.n = self.n + 1
end
end -- alive:add
function alive:delete(x)
if self.table[x] then
self.hooks[#self.hooks + 1] = self.table[x]
self.table[x] = nil
self.n = self.n - 1
self.condvar:signal()
end
end -- alive:delete
function alive:check()
local n = 0
for _ in pairs(self.table) do
n = n + 1
end
return assert(n == self.n, "resolver registry corrupt")
end -- alive:check
function alive:onleak(f)
local old = self.onleak
self.leakcb = f
return old
end -- alive:onleak
local pool = {}
local function tryget(self)
local res, why
local cache_len = #self.cache
if cache_len > 1 then
res = self.cache[cache_len]
self.cache[cache_len] = nil
elseif self.alive.n < self.hiwat then
res, why = resolver.new(self.resconf, self.hosts, self.hints)
if not res then
return nil, why
end
end
self.alive:add(res)
return res
end -- tryget
local function getby(self, deadline)
local res, why = tryget(self)
while not res and not why do
if deadline and deadline <= monotime() then
return nil, ETIMEDOUT
else
self.condvar:wait(totimeout(deadline))
res, why = tryget(self)
end
end
return res, why
end -- getby
function pool:get(timeout)
return getby(self, todeadline(timeout))
end -- pool:get
function pool:put(res)
self.alive:delete(res)
local cache_len = #self.cache
if cache_len < self.lowat and res:stat().queries < self.querymax then
if not self.lifo and cache_len > 0 then
local i = random(cache_len+1) + 1
self.cache[cache_len+1] = self.cache[i]
self.cache[i] = res
else
self.cache[cache_len+1] = res
end
else
res:close()
end
end -- pool:put
function pool:signal()
self.condvar:signal()
end -- pool:signal
function pool:query(name, type, class, timeout)
local deadline = todeadline(timeout or self.timeout)
local res, why = getby(self, deadline)
if not res then
return nil, why
end
return res:query(name, type, class, totimeout(deadline))
end -- pool:query
function pool:check()
return self.alive:check()
end -- pool:check
function pool:onleak(f)
return self.alive:onleak(f)
end -- pool:onleak
local resolvers = {}
resolvers.lowat = 1
resolvers.hiwat = 32
resolvers.querymax = 2048
resolvers.onleak = nil
resolvers.lifo = false
function resolvers.new(resconf, hosts, hints)
local self = {}
self.resconf = (type(resconf) == "table" and config.new(resconf)) or resconf
self.hosts = hosts
self.hints = hints
self.condvar = condition.new()
self.lowat = resolvers.lowat
self.hiwat = resolvers.hiwat
self.timeout = resolvers.timeout
self.querymax = resolvers.querymax
self.onleak = resolvers.onleak
self.lifo = resolvers.lifo
self.cache = {}
self.alive = alive.new(self.condvar)
return setmetatable(self, { __index = pool })
end -- resolvers.new
function resolvers.stub(cfg)
return resolvers.new(config.stub(cfg))
end -- resolvers.stub
function resolvers.root(cfg)
return resolvers.new(config.root(cfg))
end -- resolvers.root
function resolvers.type(o)
local mt = getmetatable(o)
if mt and mt.__index == pool then
return "dns resolver pool"
end
end -- resolvers.type
resolvers.loader = loader
return resolvers
end
return loader(loader, ...)
|
local loader = function(loader, ...)
local resolver = require"cqueues.dns.resolver"
local config = require"cqueues.dns.config"
local condition = require"cqueues.condition"
local monotime = require"cqueues".monotime
local random = require"cqueues.dns".random
local errno = require"cqueues.errno"
local ETIMEDOUT = errno.ETIMEDOUT
local function todeadline(timeout)
return (timeout and (monotime() + timeout)) or nil
end -- todeadline
local function totimeout(deadline)
return (deadline and math.max(0, deadline - monotime())) or nil
end -- totimeout
--
-- NOTE: Keep track of an unordered collection of objects, and in
-- particular a count of objects in the collection. If an object is
-- garbage collected automatically decrement the count and signal
-- the condition variable.
--
local alive = {}
function alive.new(condvar)
local self = setmetatable({}, { __index = alive })
self.n = 0
self.table = setmetatable({}, { __mode = "k" })
self.condvar = condvar
self.hooks = {}
self.hookmt = { __gc = function (hook)
self.n = self.n - 1
self.condvar:signal()
if self.leakcb then
pcall(self.leakcb)
end
end }
return self
end -- alive.new
function alive:newhook()
if not self._newhook then
if _G._VERSION == "Lua 5.1" then
-- Lua 5.1 does not support __gc on tables, so we need to use newproxy
self._newhook = function(mt)
local u = newproxy(false)
debug.setmetatable(u, mt)
return u
end
else
self._newhook = function(mt)
return setmetatable({}, mt)
end
end
end
return self._newhook(self.hookmt)
end -- alive:newhook
function alive:add(x)
if not self.table[x] then
local hook = self.hooks[#self.hooks]
if hook then
self.hooks[#self.hooks] = nil
else
hook = self:newhook()
end
self.table[x] = hook
self.n = self.n + 1
end
end -- alive:add
function alive:delete(x)
if self.table[x] then
self.hooks[#self.hooks + 1] = self.table[x]
self.table[x] = nil
self.n = self.n - 1
self.condvar:signal()
end
end -- alive:delete
function alive:check()
local n = 0
for _ in pairs(self.table) do
n = n + 1
end
return assert(n == self.n, "resolver registry corrupt")
end -- alive:check
function alive:onleak(f)
local old = self.onleak
self.leakcb = f
return old
end -- alive:onleak
local pool = {}
local function tryget(self)
local res, why
local cache_len = #self.cache
if cache_len > 1 then
res = self.cache[cache_len]
self.cache[cache_len] = nil
elseif self.alive.n < self.hiwat then
res, why = resolver.new(self.resconf, self.hosts, self.hints)
if not res then
return nil, why
end
end
self.alive:add(res)
return res
end -- tryget
local function getby(self, deadline)
local res, why = tryget(self)
while not res and not why do
if deadline and deadline <= monotime() then
return nil, ETIMEDOUT
else
self.condvar:wait(totimeout(deadline))
res, why = tryget(self)
end
end
return res, why
end -- getby
function pool:get(timeout)
return getby(self, todeadline(timeout))
end -- pool:get
function pool:put(res)
self.alive:delete(res)
local cache_len = #self.cache
if cache_len < self.lowat and res:stat().queries < self.querymax then
if not self.lifo and cache_len > 0 then
local i = random(cache_len+1) + 1
self.cache[cache_len+1] = self.cache[i]
self.cache[i] = res
else
self.cache[cache_len+1] = res
end
else
res:close()
end
end -- pool:put
function pool:signal()
self.condvar:signal()
end -- pool:signal
function pool:query(name, type, class, timeout)
local deadline = todeadline(timeout or self.timeout)
local res, why = getby(self, deadline)
if not res then
return nil, why
end
return res:query(name, type, class, totimeout(deadline))
end -- pool:query
function pool:check()
return self.alive:check()
end -- pool:check
function pool:onleak(f)
return self.alive:onleak(f)
end -- pool:onleak
local resolvers = {}
resolvers.lowat = 1
resolvers.hiwat = 32
resolvers.querymax = 2048
resolvers.onleak = nil
resolvers.lifo = false
function resolvers.new(resconf, hosts, hints)
local self = {}
self.resconf = (type(resconf) == "table" and config.new(resconf)) or resconf
self.hosts = hosts
self.hints = hints
self.condvar = condition.new()
self.lowat = resolvers.lowat
self.hiwat = resolvers.hiwat
self.timeout = resolvers.timeout
self.querymax = resolvers.querymax
self.onleak = resolvers.onleak
self.lifo = resolvers.lifo
self.cache = {}
self.alive = alive.new(self.condvar)
return setmetatable(self, { __index = pool })
end -- resolvers.new
function resolvers.stub(cfg)
return resolvers.new(config.stub(cfg))
end -- resolvers.stub
function resolvers.root(cfg)
return resolvers.new(config.root(cfg))
end -- resolvers.root
function resolvers.type(o)
local mt = getmetatable(o)
if mt and mt.__index == pool then
return "dns resolver pool"
end
end -- resolvers.type
resolvers.loader = loader
return resolvers
end
return loader(loader, ...)
|
refactor new hook creation so we can test buggy and fixed behavior from a unit test
|
refactor new hook creation so we can test buggy and fixed behavior from a unit test
|
Lua
|
mit
|
wahern/cqueues,bigcrush/cqueues,daurnimator/cqueues,daurnimator/cqueues,wahern/cqueues,bigcrush/cqueues
|
b20447b743f0fa259a05e6ecb9e3aa6e6988cd73
|
lua/entities/gmod_wire_egp_emitter.lua
|
lua/entities/gmod_wire_egp_emitter.lua
|
AddCSLuaFile()
DEFINE_BASECLASS( "gmod_wire_egp" )
ENT.PrintName = "Wire E2 Graphics Processor Emitter"
ENT.WireDebugName = "E2 Graphics Processor Emitter"
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.gmod_wire_egp_emitter = true
local DrawOffsetPos = Vector(0, 0, 71)
local DrawOffsetAng = Angle(0, 0, 90)
local DrawScale = 0.25
if SERVER then
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self:SetDrawOffsetPos(DrawOffsetPos)
self:SetDrawOffsetAng(DrawOffsetAng)
self:SetDrawScale(DrawScale)
self.Inputs = WireLib.CreateSpecialInputs(self, { "Scale", "Position", "Angle" }, {"NORMAL", "VECTOR", "ANGLE"})
end
function ENT:TriggerInput(iname, value)
if iname == "Scale" then
self:SetDrawScale( math.Clamp(value * 0.25, 0.01, 0.5) )
elseif iname == "Position" then
local x = math.Clamp(value.x, -150, 150)
local y = math.Clamp(value.y, -150, 150)
local z = math.Clamp(value.z, -150, 150)
self:SetDrawOffsetPos(Vector(x, y, z))
elseif iname == "Angle" then
self:SetDrawOffsetAng(value)
end
end
end
function ENT:SetupDataTables()
self:NetworkVar( "Float", 0, "DrawScale" )
self:NetworkVar( "Vector", 0, "DrawOffsetPos" )
self:NetworkVar( "Angle", 0, "DrawOffsetAng" )
end
if CLIENT then
function ENT:Initialize()
self.GPU = GPULib.WireGPU( self )
self.GPU.texture_filtering = TEXFILTER.ANISOTROPIC
self.GPU.GetInfo = function()
local pos = self:LocalToWorld(self:GetDrawOffsetPos())
local ang = self:LocalToWorldAngles(self:GetDrawOffsetAng())
return {RS = self:GetDrawScale(), RatioX = 1, translucent = true}, pos, ang
end
self.RenderTable = {}
self:EGP_Update( EGP.HomeScreen )
end
function ENT:DrawEntityOutline() end
local wire_egp_emitter_drawdist = CreateClientConVar("wire_egp_emitter_drawdist","0",true,false)
function ENT:Think()
local dist = Vector(1,0,1)*wire_egp_emitter_drawdist:GetInt()
self:SetRenderBounds(Vector(-64,0,0)-dist,Vector(64,0,135)+dist)
end
end
function ENT:UpdateTransmitState() return TRANSMIT_ALWAYS end
|
AddCSLuaFile()
DEFINE_BASECLASS( "gmod_wire_egp" )
ENT.PrintName = "Wire E2 Graphics Processor Emitter"
ENT.WireDebugName = "E2 Graphics Processor Emitter"
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.gmod_wire_egp_emitter = true
local DrawOffsetPos = Vector(0, 0, 71)
local DrawOffsetAng = Angle(0, 0, 90)
local DrawScale = 0.25
if SERVER then
function ENT:Initialize()
BaseClass.Initialize(self)
self:SetDrawOffsetPos(DrawOffsetPos)
self:SetDrawOffsetAng(DrawOffsetAng)
self:SetDrawScale(DrawScale)
self.Inputs = WireLib.CreateSpecialInputs(self, { "Scale", "Position", "Angle" }, {"NORMAL", "VECTOR", "ANGLE"})
end
function ENT:TriggerInput(iname, value)
if iname == "Scale" then
self:SetDrawScale( math.Clamp(value * 0.25, 0.01, 0.5) )
elseif iname == "Position" then
local x = math.Clamp(value.x, -150, 150)
local y = math.Clamp(value.y, -150, 150)
local z = math.Clamp(value.z, -150, 150)
self:SetDrawOffsetPos(Vector(x, y, z))
elseif iname == "Angle" then
self:SetDrawOffsetAng(value)
end
end
end
function ENT:SetupDataTables()
self:NetworkVar( "Float", 0, "DrawScale" )
self:NetworkVar( "Vector", 0, "DrawOffsetPos" )
self:NetworkVar( "Angle", 0, "DrawOffsetAng" )
end
if CLIENT then
function ENT:Initialize()
self.GPU = GPULib.WireGPU( self )
self.GPU.texture_filtering = TEXFILTER.ANISOTROPIC
self.GPU.GetInfo = function()
local pos = self:LocalToWorld(self:GetDrawOffsetPos())
local ang = self:LocalToWorldAngles(self:GetDrawOffsetAng())
return {RS = self:GetDrawScale(), RatioX = 1, translucent = true}, pos, ang
end
self.RenderTable = {}
self:EGP_Update( EGP.HomeScreen )
end
function ENT:DrawEntityOutline() end
local wire_egp_emitter_drawdist = CreateClientConVar("wire_egp_emitter_drawdist","0",true,false)
function ENT:Think()
local dist = Vector(1,0,1)*wire_egp_emitter_drawdist:GetInt()
self:SetRenderBounds(Vector(-64,0,0)-dist,Vector(64,0,135)+dist)
end
end
function ENT:UpdateTransmitState() return TRANSMIT_ALWAYS end
|
fixed emitters missing rendertable
|
fixed emitters missing rendertable
|
Lua
|
apache-2.0
|
dvdvideo1234/wire,garrysmodlua/wire,wiremod/wire,sammyt291/wire,NezzKryptic/Wire,Grocel/wire
|
cbbdeedaccc6a241e82114627f407d8014a0d41c
|
lua/entities/gmod_wire_nailer/init.lua
|
lua/entities/gmod_wire_nailer/init.lua
|
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')
ENT.WireDebugName = "Nailer"
function ENT:Initialize()
self.Entity:PhysicsInit( SOLID_VPHYSICS )
self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
self.Entity:SetSolid( SOLID_VPHYSICS )
self.Inputs = Wire_CreateInputs(self.Entity, { "A" })
end
function ENT:OnRemove()
Wire_Remove(self.Entity)
end
function ENT:Setup(flim)
self:TriggerInput("A", 0)
self.Flim = math.Clamp(flim, 0, 10000)
self:ShowOutput()
end
function ENT:TriggerInput(iname, value)
if (iname == "A") then
if (value ~= 0) then
local vStart = self.Entity:GetPos()
local vForward = self.Entity:GetUp()
local trace = {}
trace.start = vStart
trace.endpos = vStart + (vForward * 2048)
trace.filter = { self.Entity }
local trace = util.TraceLine( trace )
// Bail if we hit world or a player
if ( !trace.Entity:IsValid() || trace.Entity:IsPlayer() ) then return end
// If there's no physics object then we can't constraint it!
if ( !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return end
local tr = {}
tr.start = trace.HitPos
tr.endpos = trace.HitPos + (self.Entity:GetUp() * 50.0)
tr.filter = { trace.Entity, self.Entity }
local trTwo = util.TraceLine( tr )
if ( trTwo.Hit && !trTwo.Entity:IsPlayer() ) then
// Weld them!
local constraint = constraint.Weld( trace.Entity, trTwo.Entity, trace.PhysicsBone, trTwo.PhysicsBone, self.Flim )
//effect on weld (tomb332)
local effectdata = EffectData()
effectdata:SetOrigin( trTwo.HitPos )
effectdata:SetNormal( trTwo.HitNormal )
effectdata:SetMagnitude( 5 )
effectdata:SetScale( 1 )
effectdata:SetRadius( 10 )
util.Effect( "Sparks", effectdata )
end
end
end
end
function ENT:ShowOutput()
self:SetOverlayText( "Nailer\n" ..
"Force Limit: " .. self.Flim )
end
function ENT:OnRestore()
Wire_Restored(self.Entity)
end
|
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')
ENT.WireDebugName = "Nailer"
function ENT:Initialize()
self.Entity:PhysicsInit( SOLID_VPHYSICS )
self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
self.Entity:SetSolid( SOLID_VPHYSICS )
self.Inputs = Wire_CreateInputs(self.Entity, { "A" })
end
function ENT:OnRemove()
Wire_Remove(self.Entity)
end
function ENT:Setup(flim)
self:TriggerInput("A", 0)
self.Flim = math.Clamp(flim, 0, 10000)
self:ShowOutput()
end
function ENT:TriggerInput(iname, value)
if iname == "A" then
if value ~= 0 then
local vStart = self.Entity:GetPos()
local vForward = self.Entity:GetUp()
local trace = {}
trace.start = vStart
trace.endpos = vStart + (vForward * 2048)
trace.filter = { self.Entity }
local trace = util.TraceLine( trace )
-- Bail if we hit world or a player
if not trace.Entity:IsValid() or trace.Entity:IsPlayer() then return end
-- If there's no physics object then we can't constraint it!
if not util.IsValidPhysicsObject(trace.Entity, trace.PhysicsBone) then return end
local tr = {}
tr.start = trace.HitPos
tr.endpos = trace.HitPos + (self.Entity:GetUp() * 50.0)
tr.filter = { trace.Entity, self.Entity }
local trTwo = util.TraceLine( tr )
if trTwo.Hit and not trTwo.Entity:IsPlayer() then
if (trace.Entity.Owner ~= self.Owner or not self:CheckOwner(trace.Entity)) or (trTwo.Entity.Owner ~= self.Owner or not self:CheckOwner(trTwo.Entity)) then return end
-- Weld them!
local constraint = constraint.Weld( trace.Entity, trTwo.Entity, trace.PhysicsBone, trTwo.PhysicsBone, self.Flim )
-- effect on weld (tomb332)
local effectdata = EffectData()
effectdata:SetOrigin( trTwo.HitPos )
effectdata:SetNormal( trTwo.HitNormal )
effectdata:SetMagnitude( 5 )
effectdata:SetScale( 1 )
effectdata:SetRadius( 10 )
util.Effect( "Sparks", effectdata )
end
end
end
end
function ENT:ShowOutput()
self:SetOverlayText( "Nailer\n" ..
"Force Limit: " .. self.Flim )
end
function ENT:OnRestore()
Wire_Restored(self.Entity)
end
-- Free Fall's Owner Check Code
function ENT:CheckOwner(ent)
ply = self.pl
hasCPPI = (type( CPPI ) == "table")
hasEPS = type( eps ) == "table"
hasPropSecure = type( PropSecure ) == "table"
hasProtector = type( Protector ) == "table"
if not hasCPPI and not hasPropProtection and not hasSPropProtection and not hasEPS and not hasPropSecure and not hasProtector then return true end
local t = hook.GetTable()
local fn = t.CanTool.PropProtection
hasPropProtection = type( fn ) == "function"
if hasPropProtection then
-- We're going to get the function we need now. It's local so this is a bit dirty
local gi = debug.getinfo( fn )
for i=1, gi.nups do
local k, v = debug.getupvalue( fn, i )
if k == "Appartient" then
propProtectionFn = v
end
end
end
local fn = t.CanTool[ "SPropProtection.EntityRemoved" ]
hasSPropProtection = type( fn ) == "function"
if hasSPropProtection then
local gi = debug.getinfo( fn )
for i=1, gi.nups do
local k, v = debug.getupvalue( fn, i )
if k == "SPropProtection" then
SPropProtectionFn = v.PlayerCanTouch
end
end
end
local owns
if hasCPPI then
owns = ent:CPPICanPhysgun( ply )
elseif hasPropProtection then -- Chaussette's Prop Protection (preferred over PropSecure)
owns = propProtectionFn( ply, ent )
elseif hasSPropProtection then -- Simple Prop Protection by Spacetech
if ent:GetNetworkedString( "Owner" ) ~= "" then -- So it doesn't give an unowned prop
owns = SPropProtectionFn( ply, ent )
else
owns = false
end
elseif hasEPS then -- EPS
owns = eps.CanPlayerTouch( ply, ent )
elseif hasPropSecure then -- PropSecure
owns = PropSecure.IsPlayers( ply, ent )
elseif hasProtector then -- Protector
owns = Protector.Owner( ent ) == ply:UniqueID()
end
return owns
end
|
Fixed nailer exploit.
|
Fixed nailer exploit.
|
Lua
|
apache-2.0
|
garrysmodlua/wire,notcake/wire,mms92/wire,bigdogmat/wire,NezzKryptic/Wire,plinkopenguin/wiremod,rafradek/wire,Grocel/wire,thegrb93/wire,mitterdoo/wire,Python1320/wire,sammyt291/wire,dvdvideo1234/wire,immibis/wiremod,CaptainPRICE/wire,wiremod/wire
|
b968820cd25a18a748412f0005c48d15901ae744
|
Peripherals/Audio/ctunethread.lua
|
Peripherals/Audio/ctunethread.lua
|
--Chiptune Thread
local chIn = ...
require("love.audio")
require("love.sound")
require("love.timer")
local QSource = require("Peripherals.Audio.QueueableSource")
local qs = QSource:new()
local rate = 44100
local buffer_size = rate/4
local sleeptime = 0.9/(rate/buffer_size)
local wave, freq, amp
local waves = {}
--Sin
waves[0] = function(samples)
local r = 0
return function()
r = r + math.pi/(samples/2)
return math.sin(r)*amp
end
end
--Square
waves[1] = function(samples)
local c = 0
local flag = false
return function()
c = (c+1)%(samples/2)
if c == 0 then flag = not flag end
return (flag and amp or -amp)
end
end
--Sawtooth
waves[2] = function(samples)
local c = 0
local inc = 2/samples
return function()
c = (c+inc)%2 -1
return c
end
end
waves[3] = function(samples)
local c = samples/2
local v = math.random()
local flag = flag
return function()
--[[c = c -1
if c == 0 then
c = samples/2
flag = not flag
v = math.random()*2
if flag then v = -v end
end
return v*amp
]]
return math.random()*2-1
end
end
local function pullParams()
if wave then
return chIn:pop()
else
return chIn:demand()
end
end
while true do
for params in pullParams do
if type(params) == "string" and params == "stop" then
return
else
local ofreq = freq
wave, freq, amp = unpack(params)
if ofreq then
--error(ofreq.." -> "..freq)
end
--error(tostring(wave).."_"..tostring(freq).."_"..tostring(amp))
--amp = amp or 1
qs:clear()
qs = QSource:new()
chIn:clear()
end
end
--Generate audio.
if wave then
qs:step()
if qs:getFreeBufferCount() > 0 then
local sd = love.sound.newSoundData(buffer_size, rate, 16, 1)
local gen = waves[wave](rate/freq)
for i=0,buffer_size-1 do
sd:setSample(i,gen())
end
qs:queue(sd)
qs:play()
end
end
love.timer.sleep(sleeptime)
end
|
--Chiptune Thread
local chIn = ...
require("love.audio")
require("love.sound")
require("love.timer")
local QSource = require("Peripherals.Audio.QueueableSource")
local qs = QSource:new()
local rate = 44100
local buffer_size = rate/4
local sleeptime = 0.9/(rate/buffer_size)
local wave, freq, amp, gen
local waves = {}
--Sin
waves[0] = function(samples)
local r = 0
local hs = samples/2
local pi = math.pi
local dpi = pi*1
return function()
r = (r + pi/hs)%dpi
return math.sin(r)*amp
end
end
--Square
waves[1] = function(samples)
local c = 0
local hs = samples/2
return function()
c = c + 1
if c == samples then c = 0 end
if c < hs then
return amp
else
return -amp
end
end
end
--Sawtooth
waves[2] = function(samples)
local c = 0
local inc = 2/samples
return function()
c = (c+inc)%2 -1
return c*amp
end
end
--Noise
waves[3] = function(samples)
local c = samples/2
local v = math.random()
local flag = flag
return function()
return math.random()*2-1
end
end
local function pullParams()
if wave then
return chIn:pop()
else
return chIn:demand()
end
end
while true do
for params in pullParams do
if type(params) == "string" and params == "stop" then
return
else
local ofreq = freq
wave, freq, amp = unpack(params)
if wave and freq then
gen = waves[wave](math.floor(rate/freq))
end
qs:clear()
qs = QSource:new()
chIn:clear()
end
end
--Generate audio.
if wave then
qs:step()
if qs:getFreeBufferCount() > 0 then
local sd = love.sound.newSoundData(buffer_size, rate, 16, 1)
for i=0,buffer_size-1 do
sd:setSample(i,gen())
end
qs:queue(sd)
qs:play()
end
end
love.timer.sleep(sleeptime)
end
|
Got rid of the pops and fixed square wave
|
Got rid of the pops and fixed square wave
Former-commit-id: a6cd35c8077c81cd49327d9decd6dd05e0002194
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
f36259a31645fc55bab06d9c358d952233bad3de
|
busted/execute.lua
|
busted/execute.lua
|
local shuffle = require 'busted.utils'.shuffle
local urandom = require 'busted.utils'.urandom
local tablex = require 'pl.tablex'
local function sort(elements)
table.sort(elements, function(t1, t2)
if t1.name and t2.name then
return t1.name < t2.name
end
return t2.name ~= nil
end)
return elements
end
return function(busted)
local block = require 'busted.block'(busted)
local function execute(runs, options)
local root = busted.context.get()
local children = tablex.copy(busted.context.children(root))
local function suite_reset()
local oldctx = busted.context.get()
busted.context.clear()
local ctx = busted.context.get()
for k, v in pairs(oldctx) do
ctx[k] = v
end
for _, child in ipairs(children) do
for descriptor, _ in pairs(busted.executors) do
child[descriptor] = nil
end
busted.context.attach(child)
end
busted.randomseed = tonumber(options.seed) or urandom() or os.time()
end
for i = 1, runs do
local seed = (busted.randomize and busted.randomseed or nil)
if i > 1 then
suite_reset()
root = busted.context.get()
busted.safe_publish('suite', { 'suite', 'reset' }, root, i, runs)
end
if options.shuffle then
shuffle(busted.context.children(root), busted.randomseed)
elseif options.sort then
sort(busted.context.children(root))
end
if busted.safe_publish('suite', { 'suite', 'start' }, root, i, runs, seed) then
if block.setup(root) then
busted.execute()
end
block.lazyTeardown(root)
block.teardown(root)
end
busted.safe_publish('suite', { 'suite', 'end' }, root, i, runs)
if busted.skipAll then
break
end
end
end
return execute
end
|
local shuffle = require 'busted.utils'.shuffle
local urandom = require 'busted.utils'.urandom
local tablex = require 'pl.tablex'
local function sort(elements)
table.sort(elements, function(t1, t2)
if t1.name and t2.name then
return t1.name < t2.name
end
return t2.name ~= nil
end)
return elements
end
return function(busted)
local block = require 'busted.block'(busted)
local function execute(runs, options)
local root = busted.context.get()
local children = tablex.copy(busted.context.children(root))
local function suite_reset()
local oldctx = busted.context.get()
busted.context.clear()
local ctx = busted.context.get()
for k, v in pairs(oldctx) do
ctx[k] = v
end
for _, child in ipairs(children) do
for descriptor, _ in pairs(busted.executors) do
child[descriptor] = nil
end
busted.context.attach(child)
end
busted.randomseed = tonumber(options.seed) or urandom() or os.time()
end
for i = 1, runs do
if i > 1 then
suite_reset()
root = busted.context.get()
busted.safe_publish('suite', { 'suite', 'reset' }, root, i, runs)
end
if options.shuffle then
shuffle(busted.context.children(root), busted.randomseed)
elseif options.sort then
sort(busted.context.children(root))
end
local seed = (busted.randomize and busted.randomseed or nil)
if busted.safe_publish('suite', { 'suite', 'start' }, root, i, runs, seed) then
if block.setup(root) then
busted.execute()
end
block.lazyTeardown(root)
block.teardown(root)
end
busted.safe_publish('suite', { 'suite', 'end' }, root, i, runs)
if busted.skipAll then
break
end
end
end
return execute
end
|
Fix the random seed sent to suite start
|
Fix the random seed sent to suite start
The random seed being sent to suite start is incorrect when multiple
runs are requested. In such cases, the seed passed to suite start is
actually the seed for the previous run and not the current run. This
change passes to suite start the random seed being used for the current
run.
|
Lua
|
mit
|
Olivine-Labs/busted,o-lim/busted
|
e712c80c25006ee483a3547f4b07f3b678c7f153
|
vrp/modules/emotes.lua
|
vrp/modules/emotes.lua
|
-- this module define the emotes menu
local cfg = module("cfg/emotes")
local lang = vRP.lang
local emotes = cfg.emotes
-- clear current emotes
menu[lang.emotes.clear.title()] = {function(player,choice)
vRPclient.stopAnim(player,{true}) -- upper
vRPclient.stopAnim(player,{false}) -- full
end, lang.emotes.clear.description()}
local function ch_emote(player,choice)
local emote = emotes[choice]
if emote then
vRPclient.playAnim(player,{emote[1],emote[2],emote[3]})
end
end
-- add emotes menu to main menu
vRP.registerMenuBuilder("main", function(add, data)
local choices = {}
choices[lang.emotes.title()] = {function()
-- build emotes menu
local menu = {name=lang.emotes.title(),css={top="75px",header_color="rgba(0,125,255,0.75)"}}
local user_id = vRP.getUserId(player)
if user_id ~= nil then
-- add emotes to the emote menu
for k,v in pairs(emotes) do
if vRP.hasPermissions(user_id, v.permissions or {}) then
menu[k] = {ch_emote}
end
end
end
vRP.openMenu(data.player,menu)
end}
add(choices)
end)
|
-- this module define the emotes menu
local cfg = module("cfg/emotes")
local lang = vRP.lang
local emotes = cfg.emotes
local function ch_emote(player,choice)
local emote = emotes[choice]
if emote then
vRPclient.playAnim(player,{emote[1],emote[2],emote[3]})
end
end
-- add emotes menu to main menu
vRP.registerMenuBuilder("main", function(add, data)
local choices = {}
choices[lang.emotes.title()] = {function()
-- build emotes menu
local menu = {name=lang.emotes.title(),css={top="75px",header_color="rgba(0,125,255,0.75)"}}
local user_id = vRP.getUserId(player)
if user_id ~= nil then
-- add emotes to the emote menu
for k,v in pairs(emotes) do
if vRP.hasPermissions(user_id, v.permissions or {}) then
menu[k] = {ch_emote}
end
end
end
-- clear current emotes
menu[lang.emotes.clear.title()] = {function(player,choice)
vRPclient.stopAnim(player,{true}) -- upper
vRPclient.stopAnim(player,{false}) -- full
end, lang.emotes.clear.description()}
vRP.openMenu(data.player,menu)
end}
add(choices)
end)
|
Fix emote issue.
|
Fix emote issue.
|
Lua
|
mit
|
ImagicTheCat/vRP,ImagicTheCat/vRP
|
8c97711147f478710d4a9c800bbdaea506bc4b98
|
nyagos.d/aliases.lua
|
nyagos.d/aliases.lua
|
if not nyagos then
print("This is a script for nyagos not lua.exe")
os.exit()
end
nyagos.alias.lua_e=function(args)
if #args >= 1 then
local ok,err =loadstring(args[1])
if not ok then
io.stderr:write(err,"\n")
end
end
end
nyagos.alias.lua_f=function(args)
local save=_G["arg"]
local script = args[1]
local param = {}
for i=1,#args do
param[i-1] = args[i]
end
local f, err = loadfile(script)
_G["arg"] = param
if f then
f()
else
io.stderr:write(err,"\n")
end
_G["arg"] = save
end
nyagos.alias["for"]=function(args)
local batchpathu = nyagos.env.temp .. os.tmpname() .. ".cmd"
local batchpatha = nyagos.utoa(batchpathu)
local fd,fd_err = nyagos.open(batchpathu,"w")
if not fd then
nyagos.writerr(fd_err.."\n")
return
end
local cmdline = "@for "..table.concat(args.rawargs," ").."\n"
fd:write("@set prompt=$G\n")
fd:write(cmdline)
fd:close()
nyagos.rawexec(nyagos.env.comspec,"/c",batchpathu)
os.remove(batchpatha)
end
nyagos.alias.kill = function(args)
local command="taskkill.exe"
for i=1,#args do
if args[i] == "-f" then
command="taskkill.exe /F"
else
nyagos.exec(command .. " /PID " .. args[i])
end
end
end
nyagos.alias.killall = function(args)
local command="taskkill.exe"
for i=1,#args do
if args[i] == "-f" then
command="taskkill.exe /F"
else
nyagos.exec(command .. " /IM " .. args[i])
end
end
end
-- on chcp, font-width is changed.
nyagos.alias.chcp = function(args)
nyagos.resetcharwidth()
nyagos.rawexec(args[0],(table.unpack or unpack)(args))
end
-- wildcard expand for external commands
nyagos.alias.wildcard = function(args)
local newargs = {}
for i=1,#args do
local tmp = nyagos.glob(args[i])
for j=1,#tmp do
newargs[ #newargs+1] = tmp[j]
end
end
-- for i=1,#newargs do print(newargs[i]) end
nyagos.exec( newargs )
end
-- print the absolute path
function nyagos.alias.abspath(args)
local cwd = nyagos.getwd()
for i = 1,#args do
local path1 = nyagos.pathjoin(cwd,args[i])
nyagos.write(path1)
nyagos.write("\n")
end
end
-- chompf - cut last CRLF of the files and output them to STDOUT
function nyagos.alias.chompf(args)
local lf=""
if #args <= 0 then
for line in nyagos.lines() do
nyagos.write(lf)
nyagos.write(line)
lf = "\n"
end
else
for i=1,#args do
for line in nyagos.lines(args[i]) do
nyagos.write(lf)
nyagos.write(line)
lf = "\n"
end
end
end
end
|
if not nyagos then
print("This is a script for nyagos not lua.exe")
os.exit()
end
nyagos.alias.lua_e=function(args)
if #args >= 1 then
local f,err =loadstring(args[1])
if f then
f()
else
io.stderr:write(err,"\n")
end
end
end
nyagos.alias.lua_f=function(args)
local save=_G["arg"]
local script = args[1]
local param = {}
for i=1,#args do
param[i-1] = args[i]
end
local f, err = loadfile(script)
_G["arg"] = param
if f then
f()
else
io.stderr:write(err,"\n")
end
_G["arg"] = save
end
nyagos.alias["for"]=function(args)
local batchpathu = nyagos.env.temp .. os.tmpname() .. ".cmd"
local batchpatha = nyagos.utoa(batchpathu)
local fd,fd_err = nyagos.open(batchpathu,"w")
if not fd then
nyagos.writerr(fd_err.."\n")
return
end
local cmdline = "@for "..table.concat(args.rawargs," ").."\n"
fd:write("@set prompt=$G\n")
fd:write(cmdline)
fd:close()
nyagos.rawexec(nyagos.env.comspec,"/c",batchpathu)
os.remove(batchpatha)
end
nyagos.alias.kill = function(args)
local command="taskkill.exe"
for i=1,#args do
if args[i] == "-f" then
command="taskkill.exe /F"
else
nyagos.exec(command .. " /PID " .. args[i])
end
end
end
nyagos.alias.killall = function(args)
local command="taskkill.exe"
for i=1,#args do
if args[i] == "-f" then
command="taskkill.exe /F"
else
nyagos.exec(command .. " /IM " .. args[i])
end
end
end
-- on chcp, font-width is changed.
nyagos.alias.chcp = function(args)
nyagos.resetcharwidth()
nyagos.rawexec(args[0],(table.unpack or unpack)(args))
end
-- wildcard expand for external commands
nyagos.alias.wildcard = function(args)
local newargs = {}
for i=1,#args do
local tmp = nyagos.glob(args[i])
for j=1,#tmp do
newargs[ #newargs+1] = tmp[j]
end
end
-- for i=1,#newargs do print(newargs[i]) end
nyagos.exec( newargs )
end
-- print the absolute path
function nyagos.alias.abspath(args)
local cwd = nyagos.getwd()
for i = 1,#args do
local path1 = nyagos.pathjoin(cwd,args[i])
nyagos.write(path1)
nyagos.write("\n")
end
end
-- chompf - cut last CRLF of the files and output them to STDOUT
function nyagos.alias.chompf(args)
local lf=""
if #args <= 0 then
for line in nyagos.lines() do
nyagos.write(lf)
nyagos.write(line)
lf = "\n"
end
else
for i=1,#args do
for line in nyagos.lines(args[i]) do
nyagos.write(lf)
nyagos.write(line)
lf = "\n"
end
end
end
end
|
Fix lua_e broken (bug only snapshot)
|
Fix lua_e broken (bug only snapshot)
|
Lua
|
bsd-3-clause
|
zetamatta/nyagos,nocd5/nyagos,tsuyoshicho/nyagos
|
b9f2331921ef3f6eb91d600754f6d1f85475c093
|
share/lua/website/funnyordie.lua
|
share/lua/website/funnyordie.lua
|
-- libquvi-scripts
-- Copyright (C) 2011 Toni Gundogdu
-- Copyright (C) 2010 quvi project
--
-- 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
--
local FunnyOrDie = {} -- Utility functions unique to this script
-- Identify the script.
function ident(self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "funnyordie%.com"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain}, {"/videos/"})
return r
end
-- Query available formats.
function query_formats(self)
local page = quvi.fetch(self.page_url)
local formats = FunnyOrDie.iter_formats(page)
local t = {}
for _,v in pairs(formats) do
table.insert(t, FunnyOrDie.to_s(v))
end
table.sort(t)
self.formats = table.concat(t, "|")
return self
end
-- Parse media URL.
function parse(self)
self.host_id = "funnyordie"
local page = quvi.fetch(self.page_url)
self.title = page:match('"og:title" content="(.-)">')
or error ("no match: media title")
self.id = page:match('key:%s+"(.-)"')
or error ("no match: media id")
self.thumbnail_url = page:match('"og:image" content="(.-)"') or ''
local formats = FunnyOrDie.iter_formats(page)
local U = require 'quvi/util'
local format = U.choose_format(self, formats,
FunnyOrDie.choose_best,
FunnyOrDie.choose_default,
FunnyOrDie.to_s)
or error("unable to choose format")
self.url = {format.url or error('no match: media url')}
return self
end
--
-- Utility functions
--
function FunnyOrDie.iter_formats(page)
local t = {}
for u in page:gmatch("'src',%s+'(.-)'") do
local q,c = u:match('(%w+)%.(%w+)$')
table.insert(t, {url=u, quality=q, container=c})
-- print(u,c)
end
return t
end
function FunnyOrDie.choose_best(formats) -- Last is 'best'
local r = FunnyOrDie.choose_default(formats)
for _,v in pairs(formats) do
r = v
end
return r
end
function FunnyOrDie.choose_default(formats) -- First is 'default'
for _,v in pairs(formats) do
return v
end
end
function FunnyOrDie.to_s(t)
return string.format("%s_%s", t.container, t.quality)
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2011,2013 Toni Gundogdu <[email protected]>
-- Copyright (C) 2010 quvi project
--
-- 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
--
local FunnyOrDie = {} -- Utility functions unique to this script
-- Identify the script.
function ident(self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "funnyordie%.com"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain}, {"/videos/"})
return r
end
-- Query available formats.
function query_formats(self)
local page = quvi.fetch(self.page_url)
local formats = FunnyOrDie.iter_formats(page)
local t = {}
for _,v in pairs(formats) do
table.insert(t, FunnyOrDie.to_s(v))
end
table.sort(t)
self.formats = table.concat(t, "|")
return self
end
-- Parse media URL.
function parse(self)
self.host_id = "funnyordie"
local page = quvi.fetch(self.page_url)
self.title = page:match('"og:title" content="(.-)">')
or error ("no match: media title")
self.id = page:match('key:%s+"(.-)"')
or error ("no match: media ID")
self.thumbnail_url = page:match('"og:image" content="(.-)"') or ''
local formats = FunnyOrDie.iter_formats(page)
local U = require 'quvi/util'
local format = U.choose_format(self, formats,
FunnyOrDie.choose_best,
FunnyOrDie.choose_default,
FunnyOrDie.to_s)
or error("unable to choose format")
self.url = {format.url or error('no match: media stream URL')}
return self
end
--
-- Utility functions
--
function FunnyOrDie.iter_formats(page)
local t = {}
for u in page:gmatch('source src="(.-)"') do
table.insert(t,u)
end
table.remove(t,1) -- Remove the first: the URL for segmented videos
local r = {}
for _,u in pairs(t) do
local q,c = u:match('/(%w+)%.(%w+)$')
table.insert(r, {url=u, quality=q, container=c})
end
return r
end
function FunnyOrDie.choose_best(formats)
return FunnyOrDie.choose_default(formats)
end
function FunnyOrDie.choose_default(formats)
return formats[1]
end
function FunnyOrDie.to_s(t)
return string.format("%s_%s", t.container, t.quality)
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
FIX: website/funnyordie.lua: media stream URL pattern
|
FIX: website/funnyordie.lua: media stream URL pattern
* Conform to the standard media property error messages
* Fix the pattern for the media stream URLs
* Update the pattern for the "quality" and the "container"
* Both FunnyOrDie.choose_{best,default} now return the first stream
Signed-off-by: Toni Gundogdu <[email protected]>
|
Lua
|
agpl-3.0
|
alech/libquvi-scripts,legatvs/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts
|
31da259b658bd268f5163b5f471dbae31d3f94b1
|
lunaci/Cache.lua
|
lunaci/Cache.lua
|
module("lunaci.Cache", package.seeall)
local log = require "lunaci.log"
local config = require "lunaci.config"
local pl = require "pl.import_into"()
local Cache = {}
Cache.__index = Cache
setmetatable(Cache, {
__call = function(self)
local self = setmetatable({}, Cache)
self.manifest = nil
self.targets = {}
self.tasks = {}
self.reports = {}
self.latest = {}
return self
end
})
-- Load cache from files.
function Cache:load()
-- Load manifest cache
if pl.path.exists(config.cache.manifest) then
self.manifest = pl.pretty.read(pl.file.read(config.cache.manifest)) or nil
end
-- Load reports cache
if pl.path.exists(config.cache.reports) then
local out = pl.pretty.read(pl.file.read(config.cache.reports)) or {}
if out.targets then
self.targets = out.targets
end
if out.tasks then
self.tasks = out.tasks
end
if out.reports then
self.reports = out.reports
end
if out.latest then
self.latest = out.latest
end
end
end
-- Save cache to file
function Cache:persist()
-- Create cache directory if doesn't exist
if not pl.path.exists(config.cache.path) then
local ok, err = pl.dir.makepath(config.cache.path)
if not ok then
error("Could not create cache directory: " .. err)
end
end
pl.file.write(config.cache.manifest, pl.pretty.write(self.manifest, ''))
local reports = {
targets = self.targets or {},
tasks = self.tasks or {},
reports = self.reports or {},
latest = self.latest or {},
}
pl.file.write(config.cache.reports, pl.pretty.write(reports, ''))
end
function Cache:set_manifest(manifest)
self.manifest = manifest
end
-- TODO
function Cache:set_targets(targets)
-- noop at this point
end
-- TODO
function Cache:add_task(task)
-- noop at this point
end
-- Add a table of reports to cache
function Cache:add_reports(reports)
for name, report in pairs(reports) do
self:add_report(name, report)
end
end
-- Add report output to cache
function Cache:add_report(name, report)
-- Add latest package version string
local _, ver = report:get_latest()
if ver then
self.latest[name] = ver
end
local output = pl.tablex.deepcopy(report:get_output())
-- Remove full task outputs, leave only summaries
for _, out in pairs(output) do
out.package = nil
for _, target in pairs(out.targets) do
for _, task in pairs(target.tasks) do
task.output = nil
end
end
end
if not self.reports[name] then
self.reports[name] = output
else
for ver, out in pairs(output) do
self.reports[name][ver] = out
end
end
end
function Cache:get_report(name)
return self.reports[name]
end
function Cache:get_version(name, ver)
return self.reports[name] and self.reports[name][ver] or nil
end
-- Get latest versions reports
function Cache:get_latest()
local reports = {}
for name, report in pairs(self.reports) do
local latest = self.latest[name]
reports[name] = self.reports[name][latest]
end
return reports
end
return Cache
|
module("lunaci.Cache", package.seeall)
local log = require "lunaci.log"
local utils = require "lunaci.utils"
local config = require "lunaci.config"
local pl = require "pl.import_into"()
local Cache = {}
Cache.__index = Cache
setmetatable(Cache, {
__call = function(self)
local self = setmetatable({}, Cache)
self.manifest = nil
self.targets = {}
self.tasks = {}
self.reports = {}
self.latest = {}
self.specs = {}
return self
end
})
-- Load cache from files.
function Cache:load()
-- Load manifest cache
if pl.path.exists(config.cache.manifest) then
self.manifest = pl.pretty.read(pl.file.read(config.cache.manifest)) or nil
end
-- Load reports cache
if pl.path.exists(config.cache.reports) then
local out = pl.pretty.read(pl.file.read(config.cache.reports)) or {}
if out.targets then
self.targets = out.targets
end
if out.tasks then
self.tasks = out.tasks
end
if out.reports then
self.reports = out.reports
end
if out.latest then
self.latest = out.latest
end
if out.specs then
self.specs = out.specs
end
end
end
-- Save cache to file
function Cache:persist()
-- Create cache directory if doesn't exist
if not pl.path.exists(config.cache.path) then
local ok, err = pl.dir.makepath(config.cache.path)
if not ok then
error("Could not create cache directory: " .. err)
end
end
pl.file.write(config.cache.manifest, pl.pretty.write(self.manifest, ''))
local reports = {
targets = self.targets or {},
tasks = self.tasks or {},
reports = self.reports or {},
latest = self.latest or {},
specs = self.specs or {},
}
pl.file.write(config.cache.reports, pl.pretty.write(reports, ' '))
end
function Cache:set_manifest(manifest)
self.manifest = manifest
end
-- TODO
function Cache:set_targets(targets)
-- noop at this point
end
-- TODO
function Cache:add_task(task)
-- noop at this point
end
-- Add a table of reports to cache
function Cache:add_reports(reports)
for name, report in pairs(reports) do
self:add_report(name, report)
end
end
-- Add report output to cache
function Cache:add_report(name, report)
-- Add latest package version string
local latest, ver = report:get_latest()
if ver and (not self.latest[name] or utils.sortVersions(ver, self.latest[name])) then
self.latest[name] = ver
-- Add latest spec
self.specs[name] = latest.package.spec
end
local output = pl.tablex.deepcopy(report:get_output())
-- Remove full task outputs, leave only summaries
for _, out in pairs(output) do
out.package = nil
for _, target in pairs(out.targets) do
for _, task in pairs(target.tasks) do
task.output = nil
end
end
end
if not self.reports[name] then
self.reports[name] = output
else
for ver, out in pairs(output) do
self.reports[name][ver] = out
end
end
end
function Cache:get_report(name)
return self.reports[name]
end
function Cache:get_spec(name)
return self.specs[name]
end
function Cache:get_version(name, ver)
return self.reports[name] and self.reports[name][ver] or nil
end
-- Get latest versions reports
function Cache:get_latest()
local reports = {}
for name, report in pairs(self.reports) do
local latest = self.latest[name]
reports[name] = self.reports[name][latest]
end
return reports
end
return Cache
|
Cache: fix caching latest versions and add caching of latest rockspecs
|
Cache: fix caching latest versions and add caching of latest rockspecs
|
Lua
|
mit
|
smasty/LunaCI,smasty/LunaCI
|
203b5a638bcd0bd6ecded02b31d8dc9cb04c5861
|
nvim/lua/ryankoval/neotree.lua
|
nvim/lua/ryankoval/neotree.lua
|
vim.cmd([[ let g:neo_tree_remove_legacy_commands = 1 ]])
require('neo-tree').setup({
close_if_last_window = true, -- Close Neo-tree if it is the last window left in the tab
popup_border_style = 'rounded',
enable_git_status = true,
enable_diagnostics = true,
default_component_configs = {
container = {
enable_character_fade = true,
},
indent = {
indent_size = 1,
padding = 0, -- extra padding on left hand side
-- indent guides
with_markers = true,
indent_marker = '│',
last_indent_marker = '└',
highlight = 'NeoTreeIndentMarker',
-- expander config, needed for nesting files
with_expanders = nil, -- if nil and file nesting is enabled, will enable expanders
expander_collapsed = '',
expander_expanded = '',
expander_highlight = 'NeoTreeExpander',
},
icon = {
folder_closed = '',
folder_open = '',
folder_empty = 'ﰊ',
-- The next two settings are only a fallback, if you use nvim-web-devicons and configure default icons there
-- then these will never be used.
default = '*',
highlight = 'NeoTreeFileIcon',
},
modified = {
symbol = '[+]',
highlight = 'NeoTreeModified',
},
name = {
trailing_slash = false,
use_git_status_colors = true,
highlight = 'NeoTreeFileName',
},
git_status = {
symbols = {
-- Change type
added = '', -- or "✚", but this is redundant info if you use git_status_colors on the name
modified = '', -- or "", but this is redundant info if you use git_status_colors on the name
deleted = '✖', -- this can only be used in the git_status source
renamed = '', -- this can only be used in the git_status source
-- Status type
untracked = '',
ignored = '',
unstaged = '',
staged = '',
conflict = '',
},
},
},
window = {
position = 'left',
width = 40,
mapping_options = {
noremap = true,
nowait = true,
},
mappings = {
['<backspace>'] = nil,
['<space>'] = nil,
['<cr>'] = 'open',
['S'] = 'open_split',
['s'] = 'open_vsplit',
-- ["S"] = "split_with_window_picker",
-- ["s"] = "vsplit_with_window_picker",
['t'] = 'open_tabnew',
['C'] = 'close_node',
['ma'] = {
'add',
-- some commands may take optional config options, see `:h neo-tree-mappings` for details
config = {
show_path = 'absolute', -- "none", "relative", "absolute"
},
},
['md'] = 'delete',
['y'] = 'copy_to_clipboard',
['x'] = 'cut_to_clipboard',
['p'] = 'paste_from_clipboard',
['mc'] = {
'copy',
config = {
show_path = 'absolute', -- "none", "relative", "absolute"
},
},
['mm'] = {
'move',
config = {
show_path = 'absolute', -- "none", "relative", "absolute"
},
},
['R'] = 'refresh',
['?'] = 'show_help',
},
},
nesting_rules = {},
filesystem = {
filtered_items = {
visible = true, -- when true, they will just be displayed differently than normal items
hide_dotfiles = false,
hide_gitignored = true,
hide_hidden = true, -- only works on Windows for hidden files/directories
hide_by_name = {
--"node_modules"
},
hide_by_pattern = { -- uses glob style patterns
--"*.meta"
},
never_show = { -- remains hidden even if visible is toggled to true
'.DS_Store',
'node_modules',
},
},
follow_current_file = true, -- This will find and focus the file in the active buffer every
-- time the current file is changed while the tree is open.
group_empty_dirs = false, -- when true, empty folders will be grouped together
hijack_netrw_behavior = 'open_default', -- netrw disabled, opening a directory opens neo-tree
-- in whatever position is specified in window.position
-- "open_current", -- netrw disabled, opening a directory opens within the
-- window like netrw would, regardless of window.position
-- "disabled", -- netrw left alone, neo-tree does not handle opening dirs
use_libuv_file_watcher = false, -- This will use the OS level file watchers to detect changes
-- instead of relying on nvim autocmd events.
window = {
mappings = {
['<backspace>'] = '10k',
['<space>'] = '10j',
['.'] = 'set_root',
['I'] = 'toggle_hidden',
['/'] = 'fuzzy_finder',
['f'] = 'filter_on_submit',
['<c-x>'] = 'clear_filter',
['[c'] = 'prev_git_modified',
[']c'] = 'next_git_modified',
},
},
},
buffers = {
follow_current_file = true, -- This will find and focus the file in the active buffer every
-- time the current file is changed while the tree is open.
group_empty_dirs = true, -- when true, empty folders will be grouped together
show_unloaded = true,
window = {
mappings = {
['<bs>'] = 'navigate_up',
['.'] = 'set_root',
},
},
},
git_status = {
window = {
position = 'float',
mappings = {
['A'] = 'git_add_all',
['gu'] = 'git_unstage_file',
['ga'] = 'git_add_file',
['gr'] = 'git_revert_file',
['gc'] = 'git_commit',
['gp'] = 'git_push',
['gg'] = 'git_commit_and_push',
},
},
},
})
vim.api.nvim_set_keymap('n', '<leader>f', '<cmd>Neotree focus<cr>', {})
vim.api.nvim_set_keymap('n', '<leader><S-f>', '<cmd>Neotree toggle show filesystem<cr>', {})
-- close tree if only buffer open in current tab
-- see https://github.com/kyazdani42/nvim-tree.lua/issues/1005#issuecomment-1115831363
-- vim.api.nvim_create_autocmd('BufEnter', {
-- command = "if tabpagewinnr(tabpagenr(),'$') == 1 && match(bufname(),'NvimTree_') == 0 | quit | endif",
-- nested = true,
-- })
|
vim.cmd([[ let g:neo_tree_remove_legacy_commands = 1 ]])
require('neo-tree').setup({
close_if_last_window = true, -- Close Neo-tree if it is the last window left in the tab
popup_border_style = 'rounded',
enable_git_status = true,
enable_diagnostics = true,
default_component_configs = {
container = {
enable_character_fade = true,
},
indent = {
indent_size = 1,
padding = 0, -- extra padding on left hand side
-- indent guides
with_markers = true,
indent_marker = '│',
last_indent_marker = '└',
highlight = 'NeoTreeIndentMarker',
-- expander config, needed for nesting files
with_expanders = nil, -- if nil and file nesting is enabled, will enable expanders
expander_collapsed = '',
expander_expanded = '',
expander_highlight = 'NeoTreeExpander',
},
icon = {
folder_closed = '',
folder_open = '',
folder_empty = 'ﰊ',
-- The next two settings are only a fallback, if you use nvim-web-devicons and configure default icons there
-- then these will never be used.
default = '*',
highlight = 'NeoTreeFileIcon',
},
modified = {
symbol = '[+]',
highlight = 'NeoTreeModified',
},
name = {
trailing_slash = false,
use_git_status_colors = true,
highlight = 'NeoTreeFileName',
},
git_status = {
symbols = {
-- Change type
added = '', -- or "✚", but this is redundant info if you use git_status_colors on the name
modified = '', -- or "", but this is redundant info if you use git_status_colors on the name
deleted = '✖', -- this can only be used in the git_status source
renamed = '', -- this can only be used in the git_status source
-- Status type
untracked = '',
ignored = '',
unstaged = '',
staged = '',
conflict = '',
},
},
},
window = {
position = 'left',
width = 40,
mapping_options = {
noremap = true,
nowait = true,
},
mappings = {
['<backspace>'] = 'none',
['<space>'] = 'none',
['<cr>'] = 'open',
['S'] = 'open_split',
['s'] = 'open_vsplit',
-- ["S"] = "split_with_window_picker",
-- ["s"] = "vsplit_with_window_picker",
['t'] = 'open_tabnew',
['C'] = 'close_node',
['ma'] = {
'add',
-- some commands may take optional config options, see `:h neo-tree-mappings` for details
config = {
show_path = 'absolute', -- "none", "relative", "absolute"
},
},
['md'] = 'delete',
['y'] = 'copy_to_clipboard',
['x'] = 'cut_to_clipboard',
['p'] = 'paste_from_clipboard',
['m'] = 'none',
['mc'] = {
'copy',
config = {
show_path = 'absolute', -- "none", "relative", "absolute"
},
},
['mm'] = {
'move',
config = {
show_path = 'absolute', -- "none", "relative", "absolute"
},
},
['R'] = 'refresh',
['?'] = 'show_help',
},
},
nesting_rules = {},
filesystem = {
filtered_items = {
visible = true, -- when true, they will just be displayed differently than normal items
hide_dotfiles = false,
hide_gitignored = true,
hide_hidden = true, -- only works on Windows for hidden files/directories
hide_by_name = {
--"node_modules"
},
hide_by_pattern = { -- uses glob style patterns
--"*.meta"
},
never_show = { -- remains hidden even if visible is toggled to true
'.DS_Store',
'node_modules',
},
},
follow_current_file = true, -- This will find and focus the file in the active buffer every
-- time the current file is changed while the tree is open.
group_empty_dirs = false, -- when true, empty folders will be grouped together
hijack_netrw_behavior = 'open_default', -- netrw disabled, opening a directory opens neo-tree
-- in whatever position is specified in window.position
-- "open_current", -- netrw disabled, opening a directory opens within the
-- window like netrw would, regardless of window.position
-- "disabled", -- netrw left alone, neo-tree does not handle opening dirs
use_libuv_file_watcher = false, -- This will use the OS level file watchers to detect changes
-- instead of relying on nvim autocmd events.
window = {
mappings = {
['<backspace>'] = '10k',
['<space>'] = '10j',
['.'] = 'set_root',
['I'] = 'toggle_hidden',
['/'] = 'fuzzy_finder',
['f'] = 'filter_on_submit',
['<c-x>'] = 'clear_filter',
['[c'] = 'prev_git_modified',
[']c'] = 'next_git_modified',
},
},
},
buffers = {
follow_current_file = true, -- This will find and focus the file in the active buffer every
-- time the current file is changed while the tree is open.
group_empty_dirs = true, -- when true, empty folders will be grouped together
show_unloaded = true,
window = {
mappings = {
['<bs>'] = 'navigate_up',
['.'] = 'set_root',
},
},
},
git_status = {
window = {
position = 'float',
mappings = {
['A'] = 'git_add_all',
['gu'] = 'git_unstage_file',
['ga'] = 'git_add_file',
['gr'] = 'git_revert_file',
['gc'] = 'git_commit',
['gp'] = 'git_push',
['gg'] = 'git_commit_and_push',
},
},
},
})
vim.api.nvim_set_keymap('n', '<leader>f', '<cmd>Neotree focus<cr>', {})
vim.api.nvim_set_keymap('n', '<leader><S-f>', '<cmd>Neotree toggle show filesystem<cr>', {})
-- close tree if only buffer open in current tab
-- see https://github.com/kyazdani42/nvim-tree.lua/issues/1005#issuecomment-1115831363
-- vim.api.nvim_create_autocmd('BufEnter', {
-- command = "if tabpagewinnr(tabpagenr(),'$') == 1 && match(bufname(),'NvimTree_') == 0 | quit | endif",
-- nested = true,
-- })
|
fixed neotree mappings
|
fixed neotree mappings
|
Lua
|
mit
|
rkoval/dotfiles,rkoval/dotfiles,rkoval/dotfiles
|
8d0f8a504b59c1ce93fa5224a5becfcd91d03fcd
|
Peripherals/Keyboard.lua
|
Peripherals/Keyboard.lua
|
local events = require("Engine.events")
return function(config) --A function that creates a new Keyboard peripheral.
if config._SpaceWalkthrough then
events.register("love:keypressed",function(key,sc,isrepeat)
if key == "space" then
events.trigger("love:textinput"," ")
end
end)
end
if config._Android then
events.register("love:textinput",function(t)
events.trigger("love:keypressed",string.lower(t),string.lower(t))
events.trigger("love:keyreleased",string.lower(t),string.lower(t))
end)
end
if config.CPUKit then --Register Keyboard events
local cpukit = config.CPUKit
events.register("love:keypressed", function(...)
cpukit.triggerEvent("keypressed",...)
end)
events.register("love:keyreleased", function(...)
cpukit.triggerEvent("keyreleased",...)
end)
local gpukit = config.GPUKit
--The hook the textinput for feltering characters not in the font
events.register("love:textinput",function(text)
local text_escaped = text:gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%1")
if #text == 1 and ((not gpukit) or gpukit._FontChars:find(text_escaped)) then
cpukit.triggerEvent("textinput",text)
end
end)
end
--The api starts here--
local KB = {}
function KB.textinput(state)
if type(state) ~= "nil" then
love.keyboard.setTextInput(state or config._EXKB)
else
return love.keyboard.getTextInput()
end
end
function KB.keyrepeat(state)
if type(state) ~= "nil" then
love.keyboard.setKeyRepeat(state)
else
return love.keyboard.getKeyRepeat()
end
end
function KB.keytoscancode(key)
if type(key) ~= "string" then return false, "Key must be a string, provided: "..type(key) end --Error
local ok, err = pcall(love.keyboard.getScancodeFromKey, key)
if ok then
return err
else
return error(err)
end
end
function KB.scancodetokey(scancode)
if type(scancode) ~= "string" then return false, "Scancode must be a string, provided: "..type(scancode) end --Error
local ok, err = pcall(love.keyboard.getKeyFromScancode, scancode)
if ok then
return err
else
return error(err)
end
end
function KB.isKDown(...)
return love.keyboard.isDown(...)
end
return KB
end
|
local events = require("Engine.events")
return function(config) --A function that creates a new Keyboard peripheral.
local OSX = (love.system.getOS() == "OS X")
if config._SpaceWalkthrough then
events.register("love:keypressed",function(key,sc,isrepeat)
if key == "space" then
events.trigger("love:textinput"," ")
end
end)
end
if config._Android then
events.register("love:textinput",function(t)
events.trigger("love:keypressed",string.lower(t),string.lower(t))
events.trigger("love:keyreleased",string.lower(t),string.lower(t))
end)
end
if config.CPUKit then --Register Keyboard events
local cpukit = config.CPUKit
events.register("love:keypressed", function(k,...)
if OSX then
if k == "lgui" then
cpukit.triggerEvent("keypressed","lctrl",...)
elseif k == "rgui" then
cpukit.triggerEvent("keypressed","rctrl",...)
end
end
cpukit.triggerEvent("keypressed",k,...)
end)
events.register("love:keyreleased", function(k,...)
if OSX then
if k == "lgui" then
cpukit.triggerEvent("keyreleased","lctrl",...)
elseif k == "rgui" then
cpukit.triggerEvent("keyreleased","rctrl",...)
end
end
cpukit.triggerEvent("keyreleased",k,...)
end)
local gpukit = config.GPUKit
--The hook the textinput for feltering characters not in the font
events.register("love:textinput",function(text)
local text_escaped = text:gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%1")
if #text == 1 and ((not gpukit) or gpukit._FontChars:find(text_escaped)) then
cpukit.triggerEvent("textinput",text)
end
end)
end
--The api starts here--
local KB = {}
function KB.textinput(state)
if type(state) ~= "nil" then
love.keyboard.setTextInput(state or config._EXKB)
else
return love.keyboard.getTextInput()
end
end
function KB.keyrepeat(state)
if type(state) ~= "nil" then
love.keyboard.setKeyRepeat(state)
else
return love.keyboard.getKeyRepeat()
end
end
function KB.keytoscancode(key)
if type(key) ~= "string" then return false, "Key must be a string, provided: "..type(key) end --Error
local ok, err = pcall(love.keyboard.getScancodeFromKey, key)
if ok then
return err
else
return error(err)
end
end
function KB.scancodetokey(scancode)
if type(scancode) ~= "string" then return false, "Scancode must be a string, provided: "..type(scancode) end --Error
local ok, err = pcall(love.keyboard.getKeyFromScancode, scancode)
if ok then
return err
else
return error(err)
end
end
function KB.isKDown(...)
if love.keyboard.isDown(...) then
return true
end
if OSX then
for i=1, select("#", ...) do
if select(i, ...) == "lctrl" and love.keyboard.isDown("lgui") then
return true
elseif select(i, ...) == "rctrl" and love.keyboard.isDown("rgui") then
return true
end
end
end
return false
end
return KB
end
|
Keyboard Alias OSX (#212)
|
Keyboard Alias OSX (#212)
When on OSX, the Cmd key will now trigger Ctrl keypresses and keyreleases in addition to Cmd ones.
isDown will also check for rgui/lgui (Cmd keys) when rctrl/lctrl is requested (Ctrl keys) using a fast short-circuit mechanic where the first truthy value is returned before continue checking for these extra keys.
This PR partially fixes the issue #212 Mac accessibility shortcuts
Closes #211
Former-commit-id: 26f49dc961eafe85f112c0abbf91a8aa65477bcb
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
7ad5547d14fd3a2d5e5e47702b6abf416e36e6d3
|
spec/server_ev_spec.lua
|
spec/server_ev_spec.lua
|
require'busted'
package.path = package.path..'../src'
local server = require'websocket.server'
local client = require'websocket.client'
local ev = require'ev'
local port = os.getenv('LUAWS_PORT') or 8081
describe(
'The server (ev) module',
function()
local s
it(
'exposes the correct interface',
function()
assert.is_same(type(server),'table')
assert.is_same(type(server.ev),'table')
assert.is_same(type(server.ev.listen),'function')
end)
it(
'call listen with default handler',
function()
local s = server.ev.listen
{
default = function() end,
port = port
}
s:close()
end)
it(
'call listen with protocol handlers',
function()
local s = server.ev.listen
{
port = port,
protocols = {
echo = function() end
}
}
s:close()
end)
it(
'call listen without default nor protocol handlers has errors',
function()
assert.has_error(
function()
local s = server.ev.listen
{
port = port
}
s:close()
end)
end)
describe(
'communicating with clients',
function()
local s
local on_new_echo_client
before(
function()
s = server.ev.listen
{
port = port,
protocols = {
echo = function(client)
on_new_echo_client(client)
end
}
}
end)
it(
'handshake works',
async,
function(done)
local wsc = client.ev
{
url = 'ws://localhost:'..port,
protocol = 'echo'
}
on_new_echo_client = guard(
function(client)
assert.is_same(type(client),'table')
assert.is_same(type(client.on_message),'function')
assert.is_same(type(client.close),'function')
assert.is_same(type(client.send),'function')
client:close()
end)
wsc:connect(
guard(
function()
wsc:close()
done()
end))
end)
it(
'echo works',
async,
function(done)
local wsc = client.ev
{
url = 'ws://localhost:'..port,
protocol = 'echo'
}
on_new_echo_client = guard(
function(client)
client:on_message(
guard(
function(self,msg)
assert.is_equal(self,client)
msg:send('Hello')
self:close()
end))
end)
wsc:connect(
guard(
function(self)
assert.is_equal(self,wsc)
self:send('Hello')
self:on_message(
function(_,message)
assert.is_same(message,'Hello')
self:close()
done()
end)
end))
end)
after(
function()
s:close()
end)
end)
end)
return function()
ev.Loop.default:loop()
end
|
require'busted'
package.path = package.path..'../src'
local server = require'websocket.server'
local client = require'websocket.client'
local ev = require'ev'
local port = os.getenv('LUAWS_PORT') or 8081
describe(
'The server (ev) module',
function()
local s
it(
'exposes the correct interface',
function()
assert.is_same(type(server),'table')
assert.is_same(type(server.ev),'table')
assert.is_same(type(server.ev.listen),'function')
end)
it(
'call listen with default handler',
function()
local s = server.ev.listen
{
default = function() end,
port = port
}
s:close()
end)
it(
'call listen with protocol handlers',
function()
local s = server.ev.listen
{
port = port,
protocols = {
echo = function() end
}
}
s:close()
end)
it(
'call listen without default nor protocol handlers has errors',
function()
assert.has_error(
function()
local s = server.ev.listen
{
port = port
}
s:close()
end)
end)
describe(
'communicating with clients',
function()
local s
local on_new_echo_client
before(
function()
s = server.ev.listen
{
port = port,
protocols = {
echo = function(client)
on_new_echo_client(client)
end
}
}
end)
it(
'handshake works',
async,
function(done)
local wsc = client.ev
{
url = 'ws://localhost:'..port,
protocol = 'echo'
}
on_new_echo_client = guard(
function(client)
assert.is_same(type(client),'table')
assert.is_same(type(client.on_message),'function')
assert.is_same(type(client.close),'function')
assert.is_same(type(client.send),'function')
client:close()
end)
wsc:connect(
guard(
function()
wsc:close()
done()
end))
end)
it(
'echo works',
async,
function(done)
local wsc = client.ev
{
url = 'ws://localhost:'..port,
protocol = 'echo'
}
on_new_echo_client = guard(
function(client)
client:on_message(
guard(
function(self,msg)
assert.is_equal(self,client)
self:send('Hello')
end))
end)
wsc:connect(
guard(
function(self)
assert.is_equal(self,wsc)
self:send('Hello')
self:on_message(
guard(
function(_,message)
assert.is_same(message,'Hello')
self:close()
done()
end))
end))
end)
after(
function()
s:close()
end)
end)
end)
return function()
ev.Loop.default:loop()
end
|
fix connection close order
|
fix connection close order
|
Lua
|
mit
|
lipp/lua-websockets,enginix/lua-websockets,lipp/lua-websockets,OptimusLime/lua-websockets,OptimusLime/lua-websockets,OptimusLime/lua-websockets,KSDaemon/lua-websockets,KSDaemon/lua-websockets,lipp/lua-websockets,KSDaemon/lua-websockets,enginix/lua-websockets,enginix/lua-websockets
|
14dc77d00f5a68272b374896633d35b6d8df79df
|
scripts/autocomplete.lua
|
scripts/autocomplete.lua
|
require 'misc'
doubleTab = doubleTab or {}
keywords = keywords or valuesToKeys {
'and', 'break', 'do', 'else', 'elseif', 'end',
'false', 'for', 'function', 'goto', 'if', 'in',
'local', 'nil', 'not', 'or', 'repeat', 'return',
'then', 'true', 'until', 'while',
}
function autoComplete( str )
local prefixend = string.find( str:reverse(), '[() %[%]=+/,%%]' )
local prefix = ''
local possibles
if prefixend then
prefix = string.sub( str, 1, #str - prefixend + 1 )
str = string.sub( str, #str - prefixend + 2 )
end
str, possibles = complete(str)
if #possibles > 1 then
if doubleTab.str == str then
print( table.unpack( possibles ) )
else
doubleTab.str = str
end
end
return prefix..str
end
function autoCompleteClear()
doubleTab.str = nil
end
function complete( str )
local possibles = getCompletions( keywords, str )
for k,v in pairs( getCompletions( _G, str ) ) do
table.insert( possibles, v )
end
if #possibles > 0 then
str = string.sub( possibles[1], 1, getIdenticalPrefixLength( possibles, #str ) )
end
return str, possibles
end
function getCompletions( where, str )
local g = where
local ret = {}
local dotpos = string.find( str:reverse(), '[%.:]' )
local prefix = ''
local dottype = ''
if dotpos ~= nil then
dotpos = #str - dotpos
prefix = string.sub( str, 1, dotpos )
dottype = string.sub( str, dotpos + 1, dotpos + 1 )
g = getTable( where, prefix)
str = string.sub( str, dotpos + 2 )
end
if g == nil then
return {}
end
if type( g ) == 'table' then
for k,v in pairs(g) do
if string.find( k, str ) == 1 and string.sub(k,1,1) ~= '_' then
table.insert( ret, prefix .. dottype .. k )
end
end
if g.__luaclass then
for k, v in pairs( getLuaClassInfo( g ) ) do
if string.find( v, str ) == 1 then
table.insert( ret, prefix .. dottype .. v )
end
end
end
else
-- Retrieve class info if any
for k,v in pairs( getClassInfo( g ) ) do
if string.find( v, str ) == 1 then
table.insert( ret, prefix .. dottype .. v )
end
end
end
return ret
end
function getTable( where, tblname )
--print( 'Looking up:', tblname )
local lastdot = string.find( tblname:reverse(), '%.' )
if lastdot == nil then
return where[tblname]
end
local prefix = string.sub( tblname, 1, #tblname - lastdot )
local tbl = getTable( where, prefix )
local subscript = string.sub( tblname, #tblname - string.find( tblname:reverse(), '%.' ) + 2 )
--print( "Subscript:", subscript, tblname )
return tbl[subscript]
end
function getIdenticalPrefixLength( tbl, start )
if #tbl == 0 then return start end
local l = start
local str
local allSame = true
while allSame == true do
if l > #tbl[1] then return #tbl[1] end
str = string.sub( tbl[1], 1, l )
for k, v in pairs( tbl ) do
if string.find( v, str ) ~= 1 then
allSame = false
end
end
l = l + 1
end
return l - 2
end
function getClassInfo( cls )
local ret = {}
local mt = getmetatable( cls )
if mt then
for k, v in pairs( mt ) do
if string.sub( k, 1, 1 ) ~= '_' then
table.insert( ret, k )
end
end
if mt.__properties then
for k, v in pairs( mt.__properties ) do
if string.sub( k, 1, 1 ) ~= '_' then
table.insert( ret, k )
end
end
end
end
return ret
end
function getLuaClassInfo( cls )
local ret = {}
local mt = getmetatable( cls )
if mt then
if mt.__index then
for k, v in pairs( mt.__index ) do
if string.sub( k, 1, 1 ) ~= '_' then
table.insert( ret, k )
end
end
end
end
return ret
end
|
require 'misc'
doubleTab = doubleTab or {}
keywords = keywords or valuesToKeys {
'and', 'break', 'do', 'else', 'elseif', 'end',
'false', 'for', 'function', 'goto', 'if', 'in',
'local', 'nil', 'not', 'or', 'repeat', 'return',
'then', 'true', 'until', 'while',
}
function autoComplete( str )
local prefixend = string.find( str:reverse(), '[() %[%]=+/,%%]' )
local prefix = ''
local possibles
if prefixend then
prefix = string.sub( str, 1, #str - prefixend + 1 )
str = string.sub( str, #str - prefixend + 2 )
end
str, possibles = complete(str)
if #possibles > 1 then
if doubleTab.str == str then
print( table.unpack( possibles ) )
else
doubleTab.str = str
end
end
return prefix..str
end
function autoCompleteClear()
doubleTab.str = nil
end
function complete( str )
local possibles = getCompletions( keywords, str )
for k,v in pairs( getCompletions( _G, str ) ) do
table.insert( possibles, v )
end
if #possibles > 0 then
str = string.sub( possibles[1], 1, getIdenticalPrefixLength( possibles, #str ) )
end
return str, possibles
end
function getCompletions( where, str )
local g = where
local ret = {}
local dotpos = string.find( str:reverse(), '[%.:]' )
local prefix = ''
local dottype = ''
if dotpos ~= nil then
dotpos = #str - dotpos
prefix = string.sub( str, 1, dotpos )
dottype = string.sub( str, dotpos + 1, dotpos + 1 )
g = getTable( where, prefix)
str = string.sub( str, dotpos + 2 )
end
if g == nil then
return {}
end
if type( g ) == 'table' then
for k,v in pairs(g) do
if string.find( k, str ) == 1 and string.sub(k,1,1) ~= '_' then
table.insert( ret, prefix .. dottype .. k )
end
end
if g.__luaclass then
for k, v in pairs( getLuaClassInfo( g ) ) do
if string.find( v, str ) == 1 then
table.insert( ret, prefix .. dottype .. v )
end
end
end
else
-- Retrieve class info if any
for k,v in pairs( getClassInfo( g ) ) do
if string.find( v, str ) == 1 then
table.insert( ret, prefix .. dottype .. v )
end
end
end
return ret
end
function getTable( where, tblname )
--print( 'Looking up:', tblname, where )
local lastdot = string.find( tblname:reverse(), '%.' )
--print( 'Lastdot', lastdot )
if lastdot == nil then
return where[tblname]
end
local prefix = string.sub( tblname, 1, #tblname - lastdot )
local tbl = getTable( where, prefix )
local subscript = string.sub( tblname, #tblname - string.find( tblname:reverse(), '%.' ) + 2 )
--print( "Subscript:", subscript, tblname, where )
if tbl then
return tbl[subscript]
else
return nil
end
end
function getIdenticalPrefixLength( tbl, start )
if #tbl == 0 then return start end
local l = start
local str
local allSame = true
while allSame == true do
if l > #tbl[1] then return #tbl[1] end
str = string.sub( tbl[1], 1, l )
for k, v in pairs( tbl ) do
if string.find( v, str ) ~= 1 then
allSame = false
end
end
l = l + 1
end
return l - 2
end
function getClassInfo( cls )
local ret = {}
local mt = getmetatable( cls )
if mt then
for k, v in pairs( mt ) do
if string.sub( k, 1, 1 ) ~= '_' then
table.insert( ret, k )
end
end
if mt.__properties then
for k, v in pairs( mt.__properties ) do
if string.sub( k, 1, 1 ) ~= '_' then
table.insert( ret, k )
end
end
end
end
return ret
end
function getLuaClassInfo( cls )
local ret = {}
local mt = getmetatable( cls )
if mt then
if mt.__index then
for k, v in pairs( mt.__index ) do
if string.sub( k, 1, 1 ) ~= '_' then
table.insert( ret, k )
end
end
end
end
return ret
end
|
Fix auto complete for sub-tables.
|
Fix auto complete for sub-tables.
|
Lua
|
mit
|
merlinblack/oyunum,merlinblack/oyunum,merlinblack/oyunum,merlinblack/oyunum
|
e8e58814b1c511396589846ed3f7cb57a3222d48
|
src/i18n.lua
|
src/i18n.lua
|
local _M = {}
_M['translate'] = function (sentence)
local ret
local lang_code = _G.languageEnv or 'zh-cn'
local tranelem = bamboo.i18n[sentence]
if tranelem then
ret = bamboo.i18n[sentence][lang_code]
end
if ret then
return ret
else
return sentence
end
end
_M['langcode'] = function (req)
-- here, we like req is a local variable
-- get the language specified
local langenv = ''
--
local accept_language = req.headers['accept-language'] or req.headers['Accept-Language']
if not accept_language then langenv = '' end
if langenv == '' and accept_language then
-- such as zh-cn, en-us, zh-tw, zh-hk
langenv = accept_language:match('(%a%a%-%a%a)')
if langenv then
langenv = langenv:lower()
else
langenv = 'zh-cn'
end
end
-- currently, we define this language environment global variable
_G.languageEnv = langenv
return langenv
end
return _M
|
local _M = {}
_M['translate'] = function (sentence)
local ret
local lang_code = _G.languageEnv or 'zh-cn'
local tranelem = bamboo.i18n[sentence]
if tranelem then
ret = bamboo.i18n[sentence][lang_code]
end
if ret then
return ret
else
return sentence
end
end
_M['langcode'] = function (req)
-- here, we like req is a local variable
-- get the language specified
local langenv = nil
--
local accept_language = req.headers['accept-language'] or req.headers['Accept-Language']
if not accept_language then
langenv = 'zh-cn'
else
-- such as zh-cn, en-us, zh-tw, zh-hk
langenv = accept_language:match('(%a%a%-%a%a)')
if langenv then
langenv = langenv:lower()
else
langenv = 'zh-cn'
end
end
-- currently, we define this language environment global variable
_G.languageEnv = langenv
return langenv
end
return _M
|
fix a bug in i18n.
|
fix a bug in i18n.
Signed-off-by: root <[email protected]>
|
Lua
|
bsd-3-clause
|
daogangtang/bamboo,daogangtang/bamboo
|
4833316ae55dfd8ed79c39ae677b43a374a227c3
|
src/plugins/finalcutpro/menu/menuaction.lua
|
src/plugins/finalcutpro/menu/menuaction.lua
|
--- === plugins.finalcutpro.menu.menuaction ===
---
--- A `action` which will trigger an Final Cut Pro menu with a matching path, if available/enabled.
--- Registers itself with the `plugins.core.actions.actionmanager`.
local require = require
local fnutils = require("hs.fnutils")
local image = require("hs.image")
local config = require("cp.config")
local fcp = require("cp.apple.finalcutpro")
local i18n = require("cp.i18n")
local idle = require("cp.idle")
local imageFromPath = image.imageFromPath
local insert, concat = table.insert, table.concat
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local mod = {}
-- ID -> string
-- Constant
-- The menu ID.
local ID = "menu"
-- GROUP -> string
-- Constant
-- The group ID.
local GROUP = "fcpx"
-- ICON -> hs.image object
-- Constant
-- Icon
local ICON = imageFromPath(config.basePath .. "/plugins/finalcutpro/console/images/menu.png")
--- plugins.finalcutpro.menu.menuaction.id() -> none
--- Function
--- Returns the menu ID
---
--- Parameters:
--- * None
---
--- Returns:
--- * a string contains the menu ID
function mod.id()
return ID
end
--- plugins.finalcutpro.menu.menuaction.reload() -> none
--- Function
--- Reloads the choices.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function mod.reload()
local choices = {}
fcp:menu():visitMenuItems(function(path, menuItem)
local title = menuItem:title()
if path[1] ~= "Apple" then
local params = {}
params.path = fnutils.concat(fnutils.copy(path), { title })
insert(choices, {
text = title,
subText = i18n("menuChoiceSubText", {path = concat(path, " > ")}),
params = params,
image = ICON,
id = mod.actionId(params),
})
end
end)
config.set("plugins.finalcutpro.menu.menuaction.choices", choices)
mod._choices = choices
mod.reset()
end
--- plugins.finalcutpro.menu.menuaction.onChoices(choices) -> none
--- Function
--- Add choices to the chooser.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function mod.onChoices(choices)
if not fcp:isFrontmost() or not mod._choices then
return true
end
for _,choice in ipairs(mod._choices) do
choices:add(choice.text)
:subText(choice.subText)
:params(choice.params)
:image(ICON)
:id(choice.id)
end
end
--- plugins.finalcutpro.menu.menuaction.reset() -> none
--- Function
--- Resets the handler.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function mod.reset()
mod._handler:reset()
end
--- plugins.finalcutpro.menu.menuaction.actionId(params) -> string
--- Function
--- Gets the action ID from the parameters table.
---
--- Parameters:
--- * params - Parameters table.
---
--- Returns:
--- * Action ID as string.
function mod.actionId(params)
return ID .. ":" .. concat(params.path, "||")
end
--- plugins.finalcutpro.menu.menuaction.execute(action) -> boolean
--- Function
--- Executes the action with the provided parameters.
---
--- Parameters:
--- * `action` - A table of parameters, matching the following:
--- * `group` - The Command Group ID
--- * `id` - The specific Command ID within the group.
---
--- * `true` if the action was executed successfully.
function mod.onExecute(action)
if action and action.path then
fcp:launch():menu():doSelectMenu(action.path):Now()
return true
end
return false
end
--- plugins.finalcutpro.menu.menuaction.init(actionmanager) -> none
--- Function
--- Initialises the Menu Action plugin
---
--- Parameters:
--- * `actionmanager` - the Action Manager plugin
---
--- Returns:
--- * None
function mod.init(actionmanager)
mod._manager = actionmanager
mod._handler = actionmanager.addHandler(GROUP .. "_" .. ID, GROUP)
:onChoices(mod.onChoices)
:onExecute(mod.onExecute)
:onActionId(mod.actionId)
mod._choices = config.get("plugins.finalcutpro.menu.menuaction.choices", {})
local delay = config.get("plugins.finalcutpro.menu.menuaction.loadDelay", 5)
--------------------------------------------------------------------------------
-- Watch for restarts:
--------------------------------------------------------------------------------
fcp.isRunning:watch(function()
idle.queue(delay, function()
--log.df("Reloading Final Cut Menu Items")
mod.reload()
end)
end, true)
end
--------------------------------------------------------------------------------
--
-- THE PLUGIN:
--
--------------------------------------------------------------------------------
local plugin = {
id = "finalcutpro.menu.menuaction",
group = "finalcutpro",
dependencies = {
["core.action.manager"] = "actionmanager",
}
}
function plugin.init(deps)
mod.init(deps.actionmanager)
return mod
end
return plugin
|
--- === plugins.finalcutpro.menu.menuaction ===
---
--- A `action` which will trigger an Final Cut Pro menu with a matching path, if available/enabled.
--- Registers itself with the `plugins.core.actions.actionmanager`.
local require = require
local fnutils = require("hs.fnutils")
local image = require("hs.image")
local config = require("cp.config")
local fcp = require("cp.apple.finalcutpro")
local i18n = require("cp.i18n")
local idle = require("cp.idle")
local imageFromPath = image.imageFromPath
local insert, concat = table.insert, table.concat
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local mod = {}
-- ID -> string
-- Constant
-- The menu ID.
local ID = "menu"
-- GROUP -> string
-- Constant
-- The group ID.
local GROUP = "fcpx"
-- ICON -> hs.image object
-- Constant
-- Icon
local ICON = imageFromPath(config.basePath .. "/plugins/finalcutpro/console/images/menu.png")
--- plugins.finalcutpro.menu.menuaction.id() -> none
--- Function
--- Returns the menu ID
---
--- Parameters:
--- * None
---
--- Returns:
--- * a string contains the menu ID
function mod.id()
return ID
end
--- plugins.finalcutpro.menu.menuaction.reload() -> none
--- Function
--- Reloads the choices.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function mod.reload()
local choices = {}
fcp:menu():visitMenuItems(function(path, menuItem)
local title = menuItem:title()
if path[1] ~= "Apple" then
local params = {}
params.path = fnutils.concat(fnutils.copy(path), { title })
insert(choices, {
text = title,
subText = i18n("menuChoiceSubText", {path = concat(path, " > ")}),
params = params,
id = mod.actionId(params),
})
end
end)
config.set("plugins.finalcutpro.menu.menuaction.choices", choices)
mod._choices = choices
mod.reset()
end
--- plugins.finalcutpro.menu.menuaction.onChoices(choices) -> none
--- Function
--- Add choices to the chooser.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function mod.onChoices(choices)
if not fcp:isFrontmost() or not mod._choices then
return true
end
for _,choice in ipairs(mod._choices) do
choices:add(choice.text)
:subText(choice.subText)
:params(choice.params)
:image(ICON)
:id(choice.id)
end
end
--- plugins.finalcutpro.menu.menuaction.reset() -> none
--- Function
--- Resets the handler.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function mod.reset()
mod._handler:reset()
end
--- plugins.finalcutpro.menu.menuaction.actionId(params) -> string
--- Function
--- Gets the action ID from the parameters table.
---
--- Parameters:
--- * params - Parameters table.
---
--- Returns:
--- * Action ID as string.
function mod.actionId(params)
return ID .. ":" .. concat(params.path, "||")
end
--- plugins.finalcutpro.menu.menuaction.execute(action) -> boolean
--- Function
--- Executes the action with the provided parameters.
---
--- Parameters:
--- * `action` - A table of parameters, matching the following:
--- * `group` - The Command Group ID
--- * `id` - The specific Command ID within the group.
---
--- * `true` if the action was executed successfully.
function mod.onExecute(action)
if action and action.path then
fcp:launch():menu():doSelectMenu(action.path):Now()
return true
end
return false
end
--- plugins.finalcutpro.menu.menuaction.init(actionmanager) -> none
--- Function
--- Initialises the Menu Action plugin
---
--- Parameters:
--- * `actionmanager` - the Action Manager plugin
---
--- Returns:
--- * None
function mod.init(actionmanager)
mod._manager = actionmanager
mod._handler = actionmanager.addHandler(GROUP .. "_" .. ID, GROUP)
:onChoices(mod.onChoices)
:onExecute(mod.onExecute)
:onActionId(mod.actionId)
mod._choices = config.get("plugins.finalcutpro.menu.menuaction.choices", {})
local delay = config.get("plugins.finalcutpro.menu.menuaction.loadDelay", 5)
--------------------------------------------------------------------------------
-- Watch for restarts:
--------------------------------------------------------------------------------
fcp.isRunning:watch(function()
idle.queue(delay, function()
--log.df("Reloading Final Cut Menu Items")
mod.reload()
end)
end, true)
end
--------------------------------------------------------------------------------
--
-- THE PLUGIN:
--
--------------------------------------------------------------------------------
local plugin = {
id = "finalcutpro.menu.menuaction",
group = "finalcutpro",
dependencies = {
["core.action.manager"] = "actionmanager",
}
}
function plugin.init(deps)
mod.init(deps.actionmanager)
return mod
end
return plugin
|
Bug Fix
|
Bug Fix
- Removed unnecessary line of code
|
Lua
|
mit
|
fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost
|
cda2fc60d808ab1f51bb3fd560623da6cfbca18e
|
src/lpeg.lua
|
src/lpeg.lua
|
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
|
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 am = getmetatable(a)
local bm = getmetatable(b)
local f = (am and am[binop]) or (bm and bm[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 metamethod selector
|
lpeg wrapper: fix metamethod selector
|
Lua
|
mit
|
starius/lpjit,starius/lpjit
|
84962c647f8a8d487e6e574bf3278fdb28af4d43
|
.config/awesome/widgets/brightness.lua
|
.config/awesome/widgets/brightness.lua
|
local awful = require("awful")
local wibox = require("wibox")
local M = {}
function M.getBrightness()
return tonumber(awful.util.pread("xbacklight -get"))
end
function M.changeBrightness(x)
awful.util.pread("xbacklight -inc " .. tostring(x))
end
function M.update(reg)
-- reg.callback(reg.widget, M.getBrightness())
reg.widget:set_text(tostring(math.ceil(M.getBrightness())) .. "%")
end
local function creator(args)
local args = args or {}
local reg = {
widget = wibox.widget.textbox(),
-- callback = callback,
timer = timer({ timeout = args.interval or 5 })
}
reg.timer:connect_signal("timeout", function() M.update(reg) end)
reg.timer:start()
M.update(reg)
return reg
end
function M.attach(widget, reg)
widget:buttons(awful.util.table.join(
awful.button({}, 4, function()
M.changeBrightness(5)
M.update(reg)
end),
awful.button({}, 5, function()
M.changeBrightness(-5)
M.update(reg)
end)
))
end
return setmetatable(M, {__call = function(_,...) return creator(...) end})
|
local awful = require("awful")
local wibox = require("wibox")
local M = {}
function M.getBrightness(device)
-- xbacklight causes lags
-- return tonumber(awful.util.pread("xbacklight -get"))
return tonumber(awful.util.pread("cat /sys/class/backlight/" .. device .. "/brightness")) / 10
end
function M.changeBrightness(x)
awful.util.pread("xbacklight -inc " .. tostring(x))
end
function M.update(reg)
-- reg.callback(reg.widget, M.getBrightness())
reg.widget:set_text(tostring(math.ceil(M.getBrightness(reg.device))) .. "%")
end
local function creator(args)
local args = args or {}
local reg = {
widget = wibox.widget.textbox(),
device = args.device or "intel_backlight",
-- callback = callback,
timer = timer({ timeout = args.interval or 11 })
}
reg.timer:connect_signal("timeout", function() M.update(reg) end)
reg.timer:start()
M.update(reg)
return reg
end
function M.attach(widget, reg)
widget:buttons(awful.util.table.join(
awful.button({}, 4, function()
M.changeBrightness(5)
M.update(reg)
end),
awful.button({}, 5, function()
M.changeBrightness(-5)
M.update(reg)
end)
))
end
return setmetatable(M, {__call = function(_,...) return creator(...) end})
|
Fix periodic lags caused by xbacklight
|
Fix periodic lags caused by xbacklight
Seems like some update broke/changed something that causes xbacklight
to produce a short screen freeze when called.
To work around this issue the brightness value from /sys is used for
polling.
|
Lua
|
mit
|
mphe/dotfiles,mphe/dotfiles,mall0c/dotfiles,mphe/dotfiles,mphe/dotfiles,mphe/dotfiles,mphe/dotfiles,mall0c/dotfiles
|
ff32468c7f565660c122dccc119c8e29673604c8
|
Shilke2D/Utils/XmlNode.lua
|
Shilke2D/Utils/XmlNode.lua
|
--[[---
XmlNode is an helper class to work with xmls.
A XmlNode object has a name, a value, attributes, children nodes and a father.
An XmlNode without a father is a root node.
It's possible to convert product of XmlParser into an XmlNode.
It's also possible to add / remove children and attributes from a node.
--]]
XmlNode = class()
---Constructor.
function XmlNode:init(name,attributes,value,children)
self.name = name
self.value = value
self.attributes = attributes or {}
self.childNodes = children or {}
self.parent = nil
end
---Creates a XmlNode starting from the product of XmlParser.parse.
--Attaches the new xmlNode to "parent"
--@param xml a xml lua table obtained by XmlParser.parse
--@param parent
function XmlNode.fromLuaXml(xml,parent)
local node = XmlNode(xml.name, xml.attributes, xml.value)
if parent then
parent:addChild(node)
end
if xml.childNodes then
for _,child in pairs(xml.childNodes) do
childNode = XmlNode.fromLuaXml(child,node)
node:addChild(childNode)
end
end
return node
end
---Built an XmlNode starting from a string.
--Uses XmlParser.ParseXmlText to easily load the string
function XmlNode.fromString(xml)
local luaXml = XmlParser.ParseXmlText(xml)
local xmlNode = XmlNode.fromLuaXml(luaXml)
return xmlNode
end
---Adds a child to the current XmlNode
function XmlNode:addChild(child)
table.insert(self.childNodes,child)
child.parent = self
end
---Removes a child from the current XmlNode
function XmlNode:removeChild(child)
local res = table.removeObj(self.childNodes,child)
if res then
res.parent = nil
end
return res
end
---Returns the value of an attribute
--@param name attribute key
--@param default the value to return if the attribute name doesn't exist
--@return string
function XmlNode:getAttribute(name, default)
if self.attributes and self.attributes[name] then
return self.attributes[name]
end
return default
end
---Adds a new attribute
--@param name attribute name
--@param value attribute value
function XmlNode:addAttribute(name,value)
if self.attributes then
self.attributes[name] = value
end
end
---Removes an attribute
--@param name the name of the attribute to remove
--@return value of the removed attribute
function XmlNode:removeAttribute(name)
if self.attributes then
local value = self.attributes[name]
self.attributes[name] = nil
return value
end
return nil
end
--[[---
Returns an attribute already converted as number.
If attribute doesn't exist it return default value
(if provided, or nil if not)
--]]
function XmlNode:getAttributeN(name, default)
local v = self:getAttribute(name)
if v then
return tonumber(v)
else
return default
end
end
--[[---
Returns a attribute already converted as boolean.
If attribute doesn't exist it return default value
(if provided, or nil if not)
--]]
function XmlNode:getAttributeBool(name, default)
local v = self:getAttribute(name)
if v then
return v:lower() == "true"
else
return default
end
end
---Returns the attribute name of attribute number 'idx'
function XmlNode:getAttributeName(idx)
local i=1
for k,_ in pairs(self.attributes) do
if i == idx then
return k
end
i = i + 1
end
end
---Returns the number of attributes
function XmlNode:getNumAttributes()
local i=0
for _,_ in pairs(self.attributes) do
i = i + 1
end
return i
end
---Returns a children based on name
function XmlNode:getChildren(name)
if not name then
return self.childNodes
else
local tmp = {}
for _,child in pairs(self.childNodes) do
if child.name and child.name == name then
table.insert(tmp,child)
end
end
return tmp
end
end
---Returns parent node
function XmlNode:getParent()
return self.parent
end
---Dumps xmlnode content over a stringbuilder
function XmlNode:dump(stringbuilder)
stringbuilder:writeln(self.name)
if self.value then
stringbuilder:writeln(self.value)
end
for i,v in pairs(self.attributes) do
stringbuilder:writeln(i.." = "..v)
end
for _,xmlNode in pairs(self:getChildren()) do
xmlNode:dump(stringbuilder)
end
end
--[[
XmlNode.__tostring = function(o)
sb = StringBuilder()
o:dump(sb)
return sb:toString(true)
end
--]]
--[[
function XmlNode:toStr(indent,tagValue)
local indent = indent or 0
local indentStr=""
for i = 1,indent do indentStr=indentStr.." " end
local tableStr=""
if base.type(var)=="table" then
local tag = var[0] or tagValue or base.type(var)
local s = indentStr.."<"..tag
for k,v in base.pairs(var) do -- attributes
if base.type(k)=="string" then
if base.type(v)=="table" and k~="_M" then -- otherwise recursiveness imminent
tableStr = tableStr..str(v,indent+1,k)
else
s = s.." "..k.."=\""..encode(base.tostring(v)).."\""
end
end
end
if #var==0 and #tableStr==0 then
s = s.." />\n"
elseif #var==1 and base.type(var[1])~="table" and #tableStr==0 then -- single element
s = s..">"..encode(base.tostring(var[1])).."</"..tag..">\n"
else
s = s..">\n"
for k,v in base.ipairs(var) do -- elements
if base.type(v)=="string" then
s = s..indentStr.." "..encode(v).." \n"
else
s = s..str(v,indent+1)
end
end
s=s..tableStr..indentStr.."</"..tag..">\n"
end
return s
else
local tag = base.type(var)
return indentStr.."<"..tag.."> "..encode(base.tostring(var)).." </"..tag..">\n"
end
end
--]]
|
--[[---
XmlNode is an helper class to work with xmls.
A XmlNode object has a name, a value, attributes, children nodes and a father.
An XmlNode without a father is a root node.
It's possible to convert product of XmlParser into an XmlNode.
It's also possible to add / remove children and attributes from a node.
--]]
XmlNode = class()
---Constructor.
function XmlNode:init(name,attributes,value,children)
self.name = name
self.value = value
self.attributes = attributes or {}
self.childNodes = children or {}
self.parent = nil
end
---Creates a XmlNode starting from the product of XmlParser.parse.
--Attaches the new xmlNode to "parent"
--@param xml a xml lua table obtained by XmlParser.parse
--@param parent
function XmlNode.fromLuaXml(xml,parent)
local node = XmlNode(xml.name, xml.attributes, xml.value)
if parent then
parent:addChild(node)
end
if xml.childNodes then
for _,child in pairs(xml.childNodes) do
childNode = XmlNode.fromLuaXml(child,node)
end
end
return node
end
---Built an XmlNode starting from a string.
--Uses XmlParser.ParseXmlText to easily load the string
function XmlNode.fromString(xml)
local luaXml = XmlParser.ParseXmlText(xml)
local xmlNode = XmlNode.fromLuaXml(luaXml)
return xmlNode
end
---Adds a child to the current XmlNode
function XmlNode:addChild(child)
table.insert(self.childNodes,child)
child.parent = self
end
---Removes a child from the current XmlNode
function XmlNode:removeChild(child)
local res = table.removeObj(self.childNodes,child)
if res then
res.parent = nil
end
return res
end
---Returns the value of an attribute
--@param name attribute key
--@param default the value to return if the attribute name doesn't exist
--@return string
function XmlNode:getAttribute(name, default)
if self.attributes and self.attributes[name] then
return self.attributes[name]
end
return default
end
---Adds a new attribute
--@param name attribute name
--@param value attribute value
function XmlNode:addAttribute(name,value)
if self.attributes then
self.attributes[name] = value
end
end
---Removes an attribute
--@param name the name of the attribute to remove
--@return value of the removed attribute
function XmlNode:removeAttribute(name)
if self.attributes then
local value = self.attributes[name]
self.attributes[name] = nil
return value
end
return nil
end
--[[---
Returns an attribute already converted as number.
If attribute doesn't exist it return default value
(if provided, or nil if not)
--]]
function XmlNode:getAttributeN(name, default)
local v = self:getAttribute(name)
if v then
return tonumber(v)
else
return default
end
end
--[[---
Returns a attribute already converted as boolean.
If attribute doesn't exist it return default value
(if provided, or nil if not)
--]]
function XmlNode:getAttributeBool(name, default)
local v = self:getAttribute(name)
if v then
return v:lower() == "true"
else
return default
end
end
---Returns the attribute name of attribute number 'idx'
function XmlNode:getAttributeName(idx)
local i=1
for k,_ in pairs(self.attributes) do
if i == idx then
return k
end
i = i + 1
end
end
---Returns the number of attributes
function XmlNode:getNumAttributes()
local i=0
for _,_ in pairs(self.attributes) do
i = i + 1
end
return i
end
---Returns a children based on name
function XmlNode:getChildren(name)
if not name then
return self.childNodes
else
local tmp = {}
for _,child in pairs(self.childNodes) do
if child.name and child.name == name then
table.insert(tmp,child)
end
end
return tmp
end
end
---Returns parent node
function XmlNode:getParent()
return self.parent
end
---Dumps xmlnode content over a stringbuilder
function XmlNode:dump(stringbuilder)
stringbuilder:writeln(self.name)
if self.value then
stringbuilder:writeln(self.value)
end
for i,v in pairs(self.attributes) do
stringbuilder:writeln(i.." = "..v)
end
for _,xmlNode in pairs(self:getChildren()) do
xmlNode:dump(stringbuilder)
end
end
--[[
XmlNode.__tostring = function(o)
sb = StringBuilder()
o:dump(sb)
return sb:toString(true)
end
--]]
--[[
function XmlNode:toStr(indent,tagValue)
local indent = indent or 0
local indentStr=""
for i = 1,indent do indentStr=indentStr.." " end
local tableStr=""
if base.type(var)=="table" then
local tag = var[0] or tagValue or base.type(var)
local s = indentStr.."<"..tag
for k,v in base.pairs(var) do -- attributes
if base.type(k)=="string" then
if base.type(v)=="table" and k~="_M" then -- otherwise recursiveness imminent
tableStr = tableStr..str(v,indent+1,k)
else
s = s.." "..k.."=\""..encode(base.tostring(v)).."\""
end
end
end
if #var==0 and #tableStr==0 then
s = s.." />\n"
elseif #var==1 and base.type(var[1])~="table" and #tableStr==0 then -- single element
s = s..">"..encode(base.tostring(var[1])).."</"..tag..">\n"
else
s = s..">\n"
for k,v in base.ipairs(var) do -- elements
if base.type(v)=="string" then
s = s..indentStr.." "..encode(v).." \n"
else
s = s..str(v,indent+1)
end
end
s=s..tableStr..indentStr.."</"..tag..">\n"
end
return s
else
local tag = base.type(var)
return indentStr.."<"..tag.."> "..encode(base.tostring(var)).." </"..tag..">\n"
end
end
--]]
|
Fix bug in XmlNode that lead to duplicated nodes
|
Fix bug in XmlNode that lead to duplicated nodes
|
Lua
|
mit
|
Shrike78/Shilke2D
|
5b5aa493b5c9e30949585e29db4be249462ab756
|
mods/boats/init.lua
|
mods/boats/init.lua
|
--
-- Helper functions
--
local function is_water(pos)
local nn = minetest.get_node(pos).name
return minetest.get_item_group(nn, "water") ~= 0
end
local function get_sign(i)
if i == 0 then
return 0
else
return i / math.abs(i)
end
end
local function get_velocity(v, yaw, y)
local x = -math.sin(yaw) * v
local z = math.cos(yaw) * v
return {x = x, y = y, z = z}
end
local function get_v(v)
return math.sqrt(v.x ^ 2 + v.z ^ 2)
end
--
-- Boat entity
--
local boat = {
physical = true,
collisionbox = {-0.6, -0.4, -0.6, 0.6, 0.3, 0.6},
visual = "mesh",
mesh = "boat.x",
textures = {"default_wood.png"},
driver = nil,
v = 0,
last_v = 0,
removed = false
}
function boat.on_rightclick(self, clicker)
if not clicker or not clicker:is_player() then
return
end
local name = clicker:get_player_name()
if self.driver and clicker == self.driver then
self.driver = nil
clicker:set_detach()
default.player_attached[name] = false
default.player_set_animation(clicker, "stand" , 30)
elseif not self.driver then
self.driver = clicker
clicker:set_attach(self.object, "", {x = 0, y = 11, z = -3}, {x = 0, y = 0, z = 0})
default.player_attached[name] = true
minetest.after(0.2, function()
default.player_set_animation(clicker, "sit" , 30)
end)
self.object:setyaw(clicker:get_look_yaw() - math.pi / 2)
end
end
function boat.on_activate(self, staticdata, dtime_s)
self.object:set_armor_groups({immortal = 1})
if staticdata then
self.v = tonumber(staticdata)
end
self.last_v = self.v
end
function boat.get_staticdata(self)
return tostring(self.v)
end
function boat.on_punch(self, puncher, time_from_last_punch, tool_capabilities, direction)
if not puncher or not puncher:is_player() or self.removed then
return
end
puncher:set_detach()
default.player_attached[puncher:get_player_name()] = false
self.removed = true
-- delay remove to ensure player is detached
minetest.after(0.1, function()
self.object:remove()
end)
if not minetest.setting_getbool("creative_mode") then
puncher:get_inventory():add_item("main", "boats:boat")
end
end
function boat.on_step(self, dtime)
self.v = get_v(self.object:getvelocity()) * get_sign(self.v)
if self.driver then
local ctrl = self.driver:get_player_control()
local yaw = self.object:getyaw()
if ctrl.up then
self.v = self.v + 0.1
end
if ctrl.down then
self.v = self.v - 0.08
end
if ctrl.left then
if ctrl.down then
self.object:setyaw(yaw - math.pi / 120 - dtime * math.pi / 120)
else
self.object:setyaw(yaw + math.pi / 120 + dtime * math.pi / 120)
end
end
if ctrl.right then
if ctrl.down then
self.object:setyaw(yaw + math.pi / 120 + dtime * math.pi / 120)
else
self.object:setyaw(yaw - math.pi / 120 - dtime*math.pi/120)
end
end
end
local velo = self.object:getvelocity()
if self.v == 0 and velo.x == 0 and velo.z == 0 then
return
end
local s = get_sign(self.v)
self.v = self.v - 0.02 * s
if s ~= get_sign(self.v) then
self.object:setvelocity({x = 0, y = 0, z = 0})
self.v = 0
return
end
if math.abs(self.v) > 4.5 then
self.v = 4.5 * get_sign(self.v)
end
local p = self.object:getpos()
p.y = p.y - 0.5
local new_velo = {x = 0, y = 0, z = 0}
local new_acce = {x = 0, y = 0, z = 0}
if not is_water(p) then
local nodedef = minetest.registered_nodes[minetest.get_node(p).name]
if (not nodedef) or nodedef.walkable then
self.v = 0
end
new_acce = {x = 0, y = -10, z = 0}
new_velo = get_velocity(self.v, self.object:getyaw(), self.object:getvelocity().y)
else
p.y = p.y + 1
if is_water(p) then
new_acce = {x = 0, y = 3, z = 0}
local y = self.object:getvelocity().y
if y > 2 then
y = 2
end
if y < 0 then
self.object:setacceleration({x = 0, y = 10, z = 0})
end
new_velo = get_velocity(self.v, self.object:getyaw(), y)
else
new_acce = {x = 0, y = 0, z = 0}
if math.abs(self.object:getvelocity().y) < 1 then
local pos = self.object:getpos()
pos.y = math.floor(pos.y) + 0.5
self.object:setpos(pos)
new_velo = get_velocity(self.v, self.object:getyaw(), 0)
else
new_velo = get_velocity(self.v, self.object:getyaw(), self.object:getvelocity().y)
end
end
end
self.object:setvelocity(new_velo)
self.object:setacceleration(new_acce)
end
minetest.register_entity("boats:boat", boat)
minetest.register_craftitem("boats:boat", {
description = "Boat",
inventory_image = "boat_inventory.png",
wield_image = "boat_wield.png",
wield_scale = {x = 2, y = 2, z = 1},
liquids_pointable = true,
on_place = function(itemstack, placer, pointed_thing)
if pointed_thing.type ~= "node" then
return
end
if not is_water(pointed_thing.under) then
return
end
pointed_thing.under.y = pointed_thing.under.y + 0.5
minetest.add_entity(pointed_thing.under, "boats:boat")
if not minetest.setting_getbool("creative_mode") then
itemstack:take_item()
end
return itemstack
end,
})
minetest.register_craft({
output = "boats:boat",
recipe = {
{"", "", "" },
{"group:wood", "", "group:wood"},
{"group:wood", "group:wood", "group:wood"},
},
})
|
--
-- Helper functions
--
local function is_water(pos)
local nn = minetest.get_node(pos).name
return minetest.get_item_group(nn, "water") ~= 0
end
local function get_sign(i)
if i == 0 then
return 0
else
return i / math.abs(i)
end
end
local function get_velocity(v, yaw, y)
local x = -math.sin(yaw) * v
local z = math.cos(yaw) * v
return {x = x, y = y, z = z}
end
local function get_v(v)
return math.sqrt(v.x ^ 2 + v.z ^ 2)
end
--
-- Boat entity
--
local boat = {
physical = true,
collisionbox = {-0.6, -0.4, -0.6, 0.6, 0.3, 0.6},
visual = "mesh",
mesh = "boat.x",
textures = {"default_wood.png"},
driver = nil,
v = 0,
last_v = 0,
removed = false
}
function boat.on_rightclick(self, clicker)
if not clicker or not clicker:is_player() then
return
end
local name = clicker:get_player_name()
if self.driver and clicker == self.driver then
self.driver = nil
clicker:set_detach()
default.player_attached[name] = false
default.player_set_animation(clicker, "stand" , 30)
elseif not self.driver then
self.driver = clicker
clicker:set_attach(self.object, "", {x = 0, y = 11, z = -3}, {x = 0, y = 0, z = 0})
default.player_attached[name] = true
minetest.after(0.2, function()
default.player_set_animation(clicker, "sit" , 30)
end)
self.object:setyaw(clicker:get_look_yaw() - math.pi / 2)
end
end
function boat.on_activate(self, staticdata, dtime_s)
self.object:set_armor_groups({immortal = 1})
if staticdata then
self.v = tonumber(staticdata)
end
self.last_v = self.v
end
function boat.get_staticdata(self)
return tostring(self.v)
end
function boat.on_punch(self, puncher, time_from_last_punch, tool_capabilities, direction)
if not puncher or not puncher:is_player() or self.removed then
return
end
puncher:set_detach()
default.player_attached[puncher:get_player_name()] = false
self.removed = true
-- delay remove to ensure player is detached
minetest.after(0.1, function()
self.object:remove()
end)
if not minetest.setting_getbool("creative_mode") then
puncher:get_inventory():add_item("main", "boats:boat")
end
end
function boat.on_step(self, dtime)
self.v = get_v(self.object:getvelocity()) * get_sign(self.v)
if self.driver then
local ctrl = self.driver:get_player_control()
local yaw = self.object:getyaw()
if ctrl.up then
self.v = self.v + 0.1
end
if ctrl.down then
self.v = self.v - 0.08
end
if ctrl.left then
if ctrl.down then
self.object:setyaw(yaw - (1 + dtime) * 0.03)
else
self.object:setyaw(yaw + (1 + dtime) * 0.03)
end
end
if ctrl.right then
if ctrl.down then
self.object:setyaw(yaw + (1 + dtime) * 0.03)
else
self.object:setyaw(yaw - (1 + dtime) * 0.03)
end
end
end
local velo = self.object:getvelocity()
if self.v == 0 and velo.x == 0 and velo.y == 0 and velo.z == 0 then
return
end
local s = get_sign(self.v)
self.v = self.v - 0.02 * s
if s ~= get_sign(self.v) then
self.object:setvelocity({x = 0, y = 0, z = 0})
self.v = 0
return
end
if math.abs(self.v) > 4.5 then
self.v = 4.5 * get_sign(self.v)
end
local p = self.object:getpos()
p.y = p.y - 0.5
local new_velo = {x = 0, y = 0, z = 0}
local new_acce = {x = 0, y = 0, z = 0}
if not is_water(p) then
local nodedef = minetest.registered_nodes[minetest.get_node(p).name]
if (not nodedef) or nodedef.walkable then
self.v = 0
new_acce = {x = 0, y = 1, z = 0}
else
new_acce = {x = 0, y = -9.8, z = 0} -- freefall in air -9.81
end
new_velo = get_velocity(self.v, self.object:getyaw(), self.object:getvelocity().y)
else
p.y = p.y + 1
if is_water(p) then
new_acce = {x = 0, y = 3, z = 0}
local y = self.object:getvelocity().y
if y > 2 then
y = 2
end
if y < 0 then
self.object:setacceleration({x = 0, y = 10, z = 0})
end
new_velo = get_velocity(self.v, self.object:getyaw(), y)
else
new_acce = {x = 0, y = 0, z = 0}
if math.abs(self.object:getvelocity().y) <= 2 then
local pos = self.object:getpos()
pos.y = math.floor(pos.y) + 0.5
self.object:setpos(pos)
new_velo = get_velocity(self.v, self.object:getyaw(), 0)
else
new_velo = get_velocity(self.v, self.object:getyaw(), self.object:getvelocity().y)
end
end
end
self.object:setvelocity(new_velo)
self.object:setacceleration(new_acce)
end
minetest.register_entity("boats:boat", boat)
minetest.register_craftitem("boats:boat", {
description = "Boat",
inventory_image = "boat_inventory.png",
wield_image = "boat_wield.png",
wield_scale = {x = 2, y = 2, z = 1},
liquids_pointable = true,
on_place = function(itemstack, placer, pointed_thing)
if pointed_thing.type ~= "node" then
return
end
if not is_water(pointed_thing.under) then
return
end
pointed_thing.under.y = pointed_thing.under.y + 0.5
minetest.add_entity(pointed_thing.under, "boats:boat")
if not minetest.setting_getbool("creative_mode") then
itemstack:take_item()
end
return itemstack
end,
})
minetest.register_craft({
output = "boats:boat",
recipe = {
{"", "", "" },
{"group:wood", "", "group:wood"},
{"group:wood", "group:wood", "group:wood"},
},
})
|
Fix boat flying up and some tweaks
|
Fix boat flying up and some tweaks
|
Lua
|
lgpl-2.1
|
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.